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

/**************************************************************************
                                TODO
 **************************************************************************

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

#include <stdio.h>
#ifndef _OSL_FILE_HXX_
#include <osl/file.hxx>
#endif
#ifndef _VOS_DIAGNOSE_HXX_
#include <vos/diagnose.hxx>
#endif
#ifndef _UCBHELPER_CONTENTIDENTIFIER_HXX
#include <ucbhelper/contentidentifier.hxx>
#endif
#ifndef _DATABASES_HXX_
#include <provider/databases.hxx>
#endif
#ifndef _PROVIDER_HXX
#include <provider/provider.hxx>
#endif
#ifndef _CONTENT_HXX
#include <provider/content.hxx>
#endif
#ifndef _DATABASES_HXX_
#include <provider/databases.hxx>
#endif
#ifndef _COM_SUN_STAR_FRAME_XCONFIGMANAGER_HPP_
#include <com/sun/star/frame/XConfigManager.hpp>
#endif
#ifndef _COM_SUN_STAR_BEANS_PROPERTYATTRIBBUTE_HPP_
#include <com/sun/star/beans/PropertyAttribute.hpp>
#endif
#ifndef _COM_SUN_STAR_BEANS_PROPERTYVALUE_HPP_
#include <com/sun/star/beans/PropertyValue.hpp>
#endif
#ifndef _COM_SUN_STAR_BEANS_PROPERTYSTATE_HPP_
#include <com/sun/star/beans/PropertyState.hpp>
#endif
#ifndef _COM_SUN_STAR_CONTAINER_XCONTAINER_HPP_
#include <com/sun/star/container/XContainer.hpp>
#endif
#ifndef _COM_SUN_STAR_CONTAINER_XNAMEACCESS_HPP_
#include <com/sun/star/container/XNameAccess.hpp>
#endif
#ifndef _COM_SUN_STAR_CONTAINER_XNAMEREPLACE_HPP_
#include <com/sun/star/container/XNameReplace.hpp>
#endif

using namespace com::sun::star::frame;
using namespace com::sun::star::beans;
using namespace com::sun::star::container;
using namespace com::sun::star::lang;
using namespace com::sun::star::ucb;
using namespace com::sun::star::uno;
using namespace rtl;

using namespace chelp;

//=========================================================================
//=========================================================================
//
// ContentProvider Implementation.
//
//=========================================================================
//=========================================================================

ContentProvider::ContentProvider( const Reference< XMultiServiceFactory >& rSMgr )
    : ::ucb::ContentProviderImplHelper( rSMgr ),
        isInitialized( false ),
        m_aScheme( OUString::createFromAscii( MYUCP_URL_SCHEME ) ),
        m_pDatabases( 0 )
{
}

//=========================================================================
// virtual
ContentProvider::~ContentProvider()
{
    delete m_pDatabases;
}

//=========================================================================
//
// XInterface methods.
//
//=========================================================================

XINTERFACE_IMPL_6( ContentProvider,
                   XTypeProvider,
                   XServiceInfo,
                   XContentProvider,
                   XComponent,
                   XEventListener, /* base of XContainerListener */
                   XContainerListener);

//=========================================================================
//
// XTypeProvider methods.
//
//=========================================================================

XTYPEPROVIDER_IMPL_5( ContentProvider,
                         XTypeProvider,
                         XServiceInfo,
                         XContentProvider,
                      XComponent,
                      XContainerListener);

//=========================================================================
//
// XServiceInfo methods.
//
//=========================================================================

rtl::OUString SAL_CALL ContentProvider::getImplementationName()
    throw( com::sun::star::uno::RuntimeException )
{
    return getImplementationName_Static();
}

rtl::OUString ContentProvider::getImplementationName_Static()
{
    return OUString::createFromAscii("CHelpContentProvider" );
}

sal_Bool SAL_CALL
ContentProvider::supportsService(const rtl::OUString& ServiceName )
    throw( com::sun::star::uno::RuntimeException )
{
    com::sun::star::uno::Sequence< rtl::OUString > aSNL =
        getSupportedServiceNames();
    const rtl::OUString* pArray = aSNL.getArray();
    for( sal_Int32 i = 0; i < aSNL.getLength(); i++ )
    {
        if( pArray[ i ] == ServiceName )
            return sal_True;
    }

    return sal_False;
}

com::sun::star::uno::Sequence< rtl::OUString > SAL_CALL
ContentProvider::getSupportedServiceNames()
    throw( com::sun::star::uno::RuntimeException )
{
    return getSupportedServiceNames_Static();
}

static com::sun::star::uno::Reference<
com::sun::star::uno::XInterface > SAL_CALL
ContentProvider_CreateInstance(
    const com::sun::star::uno::Reference<
    com::sun::star::lang::XMultiServiceFactory> & rSMgr )
    throw( com::sun::star::uno::Exception )
{
    com::sun::star::lang::XServiceInfo* pX =
        (com::sun::star::lang::XServiceInfo*)new ContentProvider( rSMgr );
    return com::sun::star::uno::Reference<
        com::sun::star::uno::XInterface >::query( pX );
}

com::sun::star::uno::Sequence< rtl::OUString >
ContentProvider::getSupportedServiceNames_Static()
{
    com::sun::star::uno::Sequence< rtl::OUString > aSNS( 2 );
    aSNS.getArray()[ 0 ] =
        OUString::createFromAscii(
            MYUCP_CONTENT_PROVIDER_SERVICE_NAME1 );
    aSNS.getArray()[ 1 ] =
        OUString::createFromAscii(
            MYUCP_CONTENT_PROVIDER_SERVICE_NAME2 );

    return aSNS;
}

//=========================================================================
//
// Service factory implementation.
//
//=========================================================================

ONE_INSTANCE_SERVICE_FACTORY_IMPL( ContentProvider );

//=========================================================================
//
// XContentProvider methods.
//
//=========================================================================

// virtual
Reference< XContent > SAL_CALL ContentProvider::queryContent( const Reference< XContentIdentifier >& xCanonicId )
    throw( IllegalIdentifierException, RuntimeException )
{
    if ( ! xCanonicId->getContentProviderScheme().equalsIgnoreAsciiCase( m_aScheme ) )
    {   // Wrong URL-scheme
        throw IllegalIdentifierException();
    }

    {
        osl::MutexGuard aGuard( m_aMutex );
        if( ! isInitialized )
            init();
    }

    if( ! m_pDatabases )
        throw RuntimeException();

    rtl::OUString aOUString( m_pDatabases->getInstallPathAsURL() );
    rtl::OString aOString( aOUString.getStr(),
                           aOUString.getLength(),
                           RTL_TEXTENCODING_UTF8 );

    // Check, if a content with given id already exists...
    Reference< XContent > xContent
        = queryExistingContent( xCanonicId ).getBodyPtr();
    if ( xContent.is() )
        return xContent;

    xContent = new Content( m_xSMgr,this,xCanonicId,m_pDatabases );

    // Further checks

    if ( !xContent->getIdentifier().is() )
        throw IllegalIdentifierException();

    return xContent;
}

void SAL_CALL
ContentProvider::dispose()
    throw ( com::sun::star::uno::RuntimeException)
{
    if(m_xContainer.is())
    {
        m_xContainer->removeContainerListener(this);
        m_xContainer = Reference<XContainer>(0);
    }
}

#include <provider/debughelper.hxx>

void SAL_CALL
ContentProvider::elementReplaced(const ContainerEvent& Event)
    throw (::com::sun::star::uno::RuntimeException)
{
    if(!m_pDatabases)
        return;

    rtl::OUString accessor;
    Event.Accessor >>= accessor;
    if(accessor.compareToAscii("HelpStyleSheet"))
        return;

    rtl::OUString replacedElement,element;
    Event.ReplacedElement >>= replacedElement;
    Event.Element >>= element;

    if(replacedElement == element)
        return;

    m_pDatabases->changeCSS(element);
}

void ContentProvider::init()
{
    osl::MutexGuard aGuard( m_aMutex );

    isInitialized = true;
    Reference< XMultiServiceFactory >  sProvider( getConfiguration() );
    Reference< XHierarchicalNameAccess > xHierAccess( getHierAccess( sProvider,
                                                                     "org.openoffice.Office.Common" ) );

    rtl::OUString instPath( getKey( xHierAccess,"Path/Current/Help" ) );
    if( ! instPath.getLength() )
        // try to determine path from default
        instPath = rtl::OUString::createFromAscii( "$(instpath)/help" );
    // replace anything like $(instpath);
    subst( instPath );

    rtl::OUString stylesheet(getKey(xHierAccess,"Help/HelpStyleSheet"));
    try {
        // now adding as configuration change listener for the stylesheet
        Reference<XNameAccess> xAccess(xHierAccess,UNO_QUERY);
        if(xAccess.is()) {
            Any aAny =
                xAccess->getByName(rtl::OUString::createFromAscii("Help"));
            aAny >>= m_xContainer;
            if(m_xContainer.is())
                m_xContainer->addContainerListener(this);
        }
    } catch(const com::sun::star::uno::Exception&) {
    }

    /**
     *  now determing
     *  productname,
     *  productversion,
     *  vendorname,
     *  vendorversion,
     *  vendorshort
     */

    xHierAccess = getHierAccess( sProvider,
                                 "org.openoffice.Setup" );
    rtl::OUString productname( getKey(  xHierAccess,"Product/ooName" ) );

    rtl::OUString setupversion( getKey(  xHierAccess,"Product/ooSetupVersion" ) );
    rtl::OUString setupextension( getKey(  xHierAccess,"Product/ooSetupExtension") );
    rtl::OUString productversion( setupversion +
                                  rtl::OUString::createFromAscii( " " ) +
                                  setupextension );

    xHierAccess = getHierAccess( sProvider,
                                 "org.openoffice.Webtop.Common" );
    rtl::OUString vendorname( getKey(  xHierAccess,"Product/ooName" ) );

    setupversion = rtl::OUString( getKey(  xHierAccess,"Product/ooSetupVersion" ) );
    setupextension = rtl::OUString ( getKey(  xHierAccess,"Product/ooSetupExtension") );
    rtl::OUString vendorversion( setupversion +
                                 rtl::OUString::createFromAscii( " " ) +
                                 setupextension );
    rtl::OUString vendorshort = vendorname;

    bool found = false;
    xHierAccess = getHierAccess( sProvider,
                                 "org.openoffice.Office.Common" );
    rtl::OUString imageZip(getKey(xHierAccess,"Path/Current/UserConfig"));
    subst(imageZip);
    if(imageZip.getLength()) {
        // test existence
        if(1+imageZip.lastIndexOf('/') == imageZip.getLength())
            imageZip += rtl::OUString::createFromAscii("images.zip");
        else
            imageZip += rtl::OUString::createFromAscii("/images.zip");
        osl::DirectoryItem aDirItem;
        if(osl::DirectoryItem::get(imageZip,aDirItem) == osl::FileBase::E_None)
            found = true;
    }

    if(!found) {
        imageZip = getKey(xHierAccess,"Path/Current/Config");
        subst(imageZip);
        if(1+imageZip.lastIndexOf('/') == imageZip.getLength())
            imageZip += rtl::OUString::createFromAscii("images.zip");
        else
            imageZip += rtl::OUString::createFromAscii("/images.zip");
    }

    m_pDatabases = new Databases( instPath,
                                  imageZip,
                                  productname,
                                  productversion,
                                  vendorname,
                                  vendorversion,
                                  vendorshort,
                                  stylesheet,
                                  m_xSMgr );

}

Reference< XMultiServiceFactory > ContentProvider::getConfiguration() const
{
    Reference< XMultiServiceFactory > sProvider;
    if( m_xSMgr.is() )
    {
        Any aAny;
        aAny <<= rtl::OUString::createFromAscii( "plugin" );
        PropertyValue aProp( rtl::OUString::createFromAscii( "servertype" ),
                             -1,
                             aAny,
                             PropertyState_DIRECT_VALUE );

        Sequence< Any > seq(1);
        seq[0] <<= aProp;

        try
        {
            rtl::OUString sProviderService =
                rtl::OUString::createFromAscii(
                    "com.sun.star.configuration.ConfigurationProvider" );
            sProvider =
                Reference< XMultiServiceFactory >(
                    m_xSMgr->createInstanceWithArguments(
                        sProviderService,seq ),
                    UNO_QUERY );
        }
        catch( const com::sun::star::uno::Exception& )
        {
            OSL_ENSURE( sProvider.is(),"cant instantiate configuration" );
        }
    }

    return sProvider;
}

Reference< XHierarchicalNameAccess >
ContentProvider::getHierAccess( const Reference< XMultiServiceFactory >& sProvider,
                                const char* file ) const
{
    Reference< XHierarchicalNameAccess > xHierAccess;

    if( sProvider.is() )
    {
        Sequence< Any > seq(1);
        rtl::OUString sReaderService =
            rtl::OUString::createFromAscii( "com.sun.star.configuration.ConfigurationAccess" );

        seq[0] <<= rtl::OUString::createFromAscii( file );

        try
        {
            xHierAccess =
                Reference< XHierarchicalNameAccess >
                ( sProvider->createInstanceWithArguments( sReaderService,seq ),
                  UNO_QUERY );
        }
        catch( const com::sun::star::uno::Exception& )
        {
        }
    }

    return xHierAccess;
}

rtl::OUString
ContentProvider::getKey(const Reference<
                        XHierarchicalNameAccess >& xHierAccess,
                        const char* key) const
{
    rtl::OUString instPath;
    if( xHierAccess.is() )
    {
        Any aAny;
        try
        {
            aAny =
                xHierAccess->getByHierarchicalName(
                    rtl::OUString::createFromAscii(key));
        }
        catch( const com::sun::star::container::NoSuchElementException& )
        {
        }
        aAny >>= instPath;
    }
    return instPath;
}

void ContentProvider::subst( rtl::OUString& instpath ) const
{
    Reference< XConfigManager >  xCfgMgr;
    if( m_xSMgr.is() )
    {
        try
        {
            xCfgMgr =
                Reference< XConfigManager >(
                    m_xSMgr->createInstance( rtl::OUString::createFromAscii( "com.sun.star.config.SpecialConfigManager" ) ),
                    UNO_QUERY );
        }
        catch( const com::sun::star::uno::Exception&)
        {
            OSL_ENSURE( xCfgMgr.is()," cant instantiate the special config manager " );
        }
    }

    OSL_ENSURE( xCfgMgr.is(), "specialconfigmanager not found\n" );

    if( xCfgMgr.is() )
        instpath = xCfgMgr->substituteVariables( instpath );
}
<commit_msg>INTEGRATION: CWS c06 (1.17.48); FILE MERGED 2005/08/24 14:59:54 abi 1.17.48.1: #i53539# no basic help, if org.openoffice.Office.Common/Help/ShowBasic is set to false<commit_after>/*************************************************************************
 *
 *  OpenOffice.org - a multi-platform office productivity suite
 *
 *  $RCSfile: provider.cxx,v $
 *
 *  $Revision: 1.19 $
 *
 *  last change: $Author: rt $ $Date: 2005-11-11 12:17: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
 *
 ************************************************************************/

/**************************************************************************
                                TODO
 **************************************************************************

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

#include <stdio.h>
#ifndef _OSL_FILE_HXX_
#include <osl/file.hxx>
#endif
#ifndef _VOS_DIAGNOSE_HXX_
#include <vos/diagnose.hxx>
#endif
#ifndef _UCBHELPER_CONTENTIDENTIFIER_HXX
#include <ucbhelper/contentidentifier.hxx>
#endif
#ifndef _DATABASES_HXX_
#include <provider/databases.hxx>
#endif
#ifndef _PROVIDER_HXX
#include <provider/provider.hxx>
#endif
#ifndef _CONTENT_HXX
#include <provider/content.hxx>
#endif
#ifndef _DATABASES_HXX_
#include <provider/databases.hxx>
#endif
#ifndef _COM_SUN_STAR_FRAME_XCONFIGMANAGER_HPP_
#include <com/sun/star/frame/XConfigManager.hpp>
#endif
#ifndef _COM_SUN_STAR_BEANS_PROPERTYATTRIBBUTE_HPP_
#include <com/sun/star/beans/PropertyAttribute.hpp>
#endif
#ifndef _COM_SUN_STAR_BEANS_PROPERTYVALUE_HPP_
#include <com/sun/star/beans/PropertyValue.hpp>
#endif
#ifndef _COM_SUN_STAR_BEANS_PROPERTYSTATE_HPP_
#include <com/sun/star/beans/PropertyState.hpp>
#endif
#ifndef _COM_SUN_STAR_CONTAINER_XCONTAINER_HPP_
#include <com/sun/star/container/XContainer.hpp>
#endif
#ifndef _COM_SUN_STAR_CONTAINER_XNAMEACCESS_HPP_
#include <com/sun/star/container/XNameAccess.hpp>
#endif
#ifndef _COM_SUN_STAR_CONTAINER_XNAMEREPLACE_HPP_
#include <com/sun/star/container/XNameReplace.hpp>
#endif

using namespace com::sun::star::frame;
using namespace com::sun::star::beans;
using namespace com::sun::star::container;
using namespace com::sun::star::lang;
using namespace com::sun::star::ucb;
using namespace com::sun::star::uno;
using namespace rtl;

using namespace chelp;

//=========================================================================
//=========================================================================
//
// ContentProvider Implementation.
//
//=========================================================================
//=========================================================================

ContentProvider::ContentProvider( const Reference< XMultiServiceFactory >& rSMgr )
    : ::ucb::ContentProviderImplHelper( rSMgr ),
        isInitialized( false ),
        m_aScheme( OUString::createFromAscii( MYUCP_URL_SCHEME ) ),
        m_pDatabases( 0 )
{
}

//=========================================================================
// virtual
ContentProvider::~ContentProvider()
{
    delete m_pDatabases;
}

//=========================================================================
//
// XInterface methods.
//
//=========================================================================

XINTERFACE_IMPL_6( ContentProvider,
                   XTypeProvider,
                   XServiceInfo,
                   XContentProvider,
                   XComponent,
                   XEventListener, /* base of XContainerListener */
                   XContainerListener);

//=========================================================================
//
// XTypeProvider methods.
//
//=========================================================================

XTYPEPROVIDER_IMPL_5( ContentProvider,
                         XTypeProvider,
                         XServiceInfo,
                         XContentProvider,
                      XComponent,
                      XContainerListener);

//=========================================================================
//
// XServiceInfo methods.
//
//=========================================================================

rtl::OUString SAL_CALL ContentProvider::getImplementationName()
    throw( com::sun::star::uno::RuntimeException )
{
    return getImplementationName_Static();
}

rtl::OUString ContentProvider::getImplementationName_Static()
{
    return OUString::createFromAscii("CHelpContentProvider" );
}

sal_Bool SAL_CALL
ContentProvider::supportsService(const rtl::OUString& ServiceName )
    throw( com::sun::star::uno::RuntimeException )
{
    com::sun::star::uno::Sequence< rtl::OUString > aSNL =
        getSupportedServiceNames();
    const rtl::OUString* pArray = aSNL.getArray();
    for( sal_Int32 i = 0; i < aSNL.getLength(); i++ )
    {
        if( pArray[ i ] == ServiceName )
            return sal_True;
    }

    return sal_False;
}

com::sun::star::uno::Sequence< rtl::OUString > SAL_CALL
ContentProvider::getSupportedServiceNames()
    throw( com::sun::star::uno::RuntimeException )
{
    return getSupportedServiceNames_Static();
}

static com::sun::star::uno::Reference<
com::sun::star::uno::XInterface > SAL_CALL
ContentProvider_CreateInstance(
    const com::sun::star::uno::Reference<
    com::sun::star::lang::XMultiServiceFactory> & rSMgr )
    throw( com::sun::star::uno::Exception )
{
    com::sun::star::lang::XServiceInfo* pX =
        (com::sun::star::lang::XServiceInfo*)new ContentProvider( rSMgr );
    return com::sun::star::uno::Reference<
        com::sun::star::uno::XInterface >::query( pX );
}

com::sun::star::uno::Sequence< rtl::OUString >
ContentProvider::getSupportedServiceNames_Static()
{
    com::sun::star::uno::Sequence< rtl::OUString > aSNS( 2 );
    aSNS.getArray()[ 0 ] =
        OUString::createFromAscii(
            MYUCP_CONTENT_PROVIDER_SERVICE_NAME1 );
    aSNS.getArray()[ 1 ] =
        OUString::createFromAscii(
            MYUCP_CONTENT_PROVIDER_SERVICE_NAME2 );

    return aSNS;
}

//=========================================================================
//
// Service factory implementation.
//
//=========================================================================

ONE_INSTANCE_SERVICE_FACTORY_IMPL( ContentProvider );

//=========================================================================
//
// XContentProvider methods.
//
//=========================================================================

// virtual
Reference< XContent > SAL_CALL ContentProvider::queryContent( const Reference< XContentIdentifier >& xCanonicId )
    throw( IllegalIdentifierException, RuntimeException )
{
    if ( ! xCanonicId->getContentProviderScheme().equalsIgnoreAsciiCase( m_aScheme ) )
    {   // Wrong URL-scheme
        throw IllegalIdentifierException();
    }

    {
        osl::MutexGuard aGuard( m_aMutex );
        if( ! isInitialized )
            init();
    }

    if( ! m_pDatabases )
        throw RuntimeException();

    rtl::OUString aOUString( m_pDatabases->getInstallPathAsURL() );
    rtl::OString aOString( aOUString.getStr(),
                           aOUString.getLength(),
                           RTL_TEXTENCODING_UTF8 );

    // Check, if a content with given id already exists...
    Reference< XContent > xContent
        = queryExistingContent( xCanonicId ).getBodyPtr();
    if ( xContent.is() )
        return xContent;

    xContent = new Content( m_xSMgr,this,xCanonicId,m_pDatabases );

    // Further checks

    if ( !xContent->getIdentifier().is() )
        throw IllegalIdentifierException();

    return xContent;
}

void SAL_CALL
ContentProvider::dispose()
    throw ( com::sun::star::uno::RuntimeException)
{
    if(m_xContainer.is())
    {
        m_xContainer->removeContainerListener(this);
        m_xContainer = Reference<XContainer>(0);
    }
}

#include <provider/debughelper.hxx>

void SAL_CALL
ContentProvider::elementReplaced(const ContainerEvent& Event)
    throw (::com::sun::star::uno::RuntimeException)
{
    if(!m_pDatabases)
        return;

    rtl::OUString accessor;
    Event.Accessor >>= accessor;
    if(accessor.compareToAscii("HelpStyleSheet"))
        return;

    rtl::OUString replacedElement,element;
    Event.ReplacedElement >>= replacedElement;
    Event.Element >>= element;

    if(replacedElement == element)
        return;

    m_pDatabases->changeCSS(element);
}

void ContentProvider::init()
{
    osl::MutexGuard aGuard( m_aMutex );

    isInitialized = true;
    Reference< XMultiServiceFactory >  sProvider( getConfiguration() );
    Reference< XHierarchicalNameAccess > xHierAccess( getHierAccess( sProvider,
                                                                     "org.openoffice.Office.Common" ) );

    rtl::OUString instPath( getKey( xHierAccess,"Path/Current/Help" ) );
    if( ! instPath.getLength() )
        // try to determine path from default
        instPath = rtl::OUString::createFromAscii( "$(instpath)/help" );
    // replace anything like $(instpath);
    subst( instPath );

    rtl::OUString stylesheet(getKey(xHierAccess,"Help/HelpStyleSheet"));
    try {
        // now adding as configuration change listener for the stylesheet
        Reference<XNameAccess> xAccess(xHierAccess,UNO_QUERY);
        if(xAccess.is()) {
            Any aAny =
                xAccess->getByName(rtl::OUString::createFromAscii("Help"));
            aAny >>= m_xContainer;
            if(m_xContainer.is())
                m_xContainer->addContainerListener(this);
        }
    } catch(const com::sun::star::uno::Exception&) {
    }

    /**
     *  now determing
     *  productname,
     *  productversion,
     *  vendorname,
     *  vendorversion,
     *  vendorshort
     */

    xHierAccess = getHierAccess( sProvider,
                                 "org.openoffice.Setup" );
    rtl::OUString productname( getKey(  xHierAccess,"Product/ooName" ) );

    rtl::OUString setupversion( getKey(  xHierAccess,"Product/ooSetupVersion" ) );
    rtl::OUString setupextension( getKey(  xHierAccess,"Product/ooSetupExtension") );
    rtl::OUString productversion( setupversion +
                                  rtl::OUString::createFromAscii( " " ) +
                                  setupextension );

    xHierAccess = getHierAccess( sProvider,
                                 "org.openoffice.Webtop.Common" );
    rtl::OUString vendorname( getKey(  xHierAccess,"Product/ooName" ) );

    setupversion = rtl::OUString( getKey(  xHierAccess,"Product/ooSetupVersion" ) );
    setupextension = rtl::OUString ( getKey(  xHierAccess,"Product/ooSetupExtension") );
    rtl::OUString vendorversion( setupversion +
                                 rtl::OUString::createFromAscii( " " ) +
                                 setupextension );
    rtl::OUString vendorshort = vendorname;

    bool found = false;
    xHierAccess = getHierAccess( sProvider,
                                 "org.openoffice.Office.Common" );
    rtl::OUString imageZip(getKey(xHierAccess,"Path/Current/UserConfig"));
    subst(imageZip);
    if(imageZip.getLength()) {
        // test existence
        if(1+imageZip.lastIndexOf('/') == imageZip.getLength())
            imageZip += rtl::OUString::createFromAscii("images.zip");
        else
            imageZip += rtl::OUString::createFromAscii("/images.zip");
        osl::DirectoryItem aDirItem;
        if(osl::DirectoryItem::get(imageZip,aDirItem) == osl::FileBase::E_None)
            found = true;
    }

    if(!found) {
        imageZip = getKey(xHierAccess,"Path/Current/Config");
        subst(imageZip);
        if(1+imageZip.lastIndexOf('/') == imageZip.getLength())
            imageZip += rtl::OUString::createFromAscii("images.zip");
        else
            imageZip += rtl::OUString::createFromAscii("/images.zip");
    }

    sal_Bool showBasic = getBooleanKey(xHierAccess,"Help/ShowBasic");
    m_pDatabases = new Databases( showBasic,
                                  instPath,
                                  imageZip,
                                  productname,
                                  productversion,
                                  vendorname,
                                  vendorversion,
                                  vendorshort,
                                  stylesheet,
                                  m_xSMgr );

}

Reference< XMultiServiceFactory > ContentProvider::getConfiguration() const
{
    Reference< XMultiServiceFactory > sProvider;
    if( m_xSMgr.is() )
    {
        Any aAny;
        aAny <<= rtl::OUString::createFromAscii( "plugin" );
        PropertyValue aProp( rtl::OUString::createFromAscii( "servertype" ),
                             -1,
                             aAny,
                             PropertyState_DIRECT_VALUE );

        Sequence< Any > seq(1);
        seq[0] <<= aProp;

        try
        {
            rtl::OUString sProviderService =
                rtl::OUString::createFromAscii(
                    "com.sun.star.configuration.ConfigurationProvider" );
            sProvider =
                Reference< XMultiServiceFactory >(
                    m_xSMgr->createInstanceWithArguments(
                        sProviderService,seq ),
                    UNO_QUERY );
        }
        catch( const com::sun::star::uno::Exception& )
        {
          OSL_ENSURE( sProvider.is(),"cant instantiate configuration" );
        }
    }

    return sProvider;
}

Reference< XHierarchicalNameAccess >
ContentProvider::getHierAccess( const Reference< XMultiServiceFactory >& sProvider,
                                const char* file ) const
{
    Reference< XHierarchicalNameAccess > xHierAccess;

    if( sProvider.is() )
    {
        Sequence< Any > seq(1);
        rtl::OUString sReaderService =
            rtl::OUString::createFromAscii( "com.sun.star.configuration.ConfigurationAccess" );

        seq[0] <<= rtl::OUString::createFromAscii( file );

        try
        {
            xHierAccess =
                Reference< XHierarchicalNameAccess >
                ( sProvider->createInstanceWithArguments( sReaderService,seq ),
                  UNO_QUERY );
        }
        catch( const com::sun::star::uno::Exception& )
        {
        }
    }

    return xHierAccess;
}

rtl::OUString
ContentProvider::getKey(const Reference<
                        XHierarchicalNameAccess >& xHierAccess,
                        const char* key) const
{
    rtl::OUString instPath;
    if( xHierAccess.is() )
    {
        Any aAny;
        try
        {
            aAny =
                xHierAccess->getByHierarchicalName(
                    rtl::OUString::createFromAscii(key));
        }
        catch( const com::sun::star::container::NoSuchElementException& )
        {
        }
        aAny >>= instPath;
    }
    return instPath;
}

sal_Bool
ContentProvider::getBooleanKey(const Reference<
                        XHierarchicalNameAccess >& xHierAccess,
                        const char* key) const
{
  sal_Bool ret = sal_False;
  if( xHierAccess.is() )
    {
      Any aAny;
      try
        {
          aAny =
            xHierAccess->getByHierarchicalName(
                                               rtl::OUString::createFromAscii(key));
        }
      catch( const com::sun::star::container::NoSuchElementException& )
        {
        }
      aAny >>= ret;
    }
  return ret;
}

void ContentProvider::subst( rtl::OUString& instpath ) const
{
    Reference< XConfigManager >  xCfgMgr;
    if( m_xSMgr.is() )
    {
        try
        {
            xCfgMgr =
                Reference< XConfigManager >(
                    m_xSMgr->createInstance( rtl::OUString::createFromAscii( "com.sun.star.config.SpecialConfigManager" ) ),
                    UNO_QUERY );
        }
        catch( const com::sun::star::uno::Exception&)
        {
            OSL_ENSURE( xCfgMgr.is()," cant instantiate the special config manager " );
        }
    }

    OSL_ENSURE( xCfgMgr.is(), "specialconfigmanager not found\n" );

    if( xCfgMgr.is() )
        instpath = xCfgMgr->substituteVariables( instpath );
}
<|endoftext|>


<commit_before>/*************************************************************************
 *
 *  OpenOffice.org - a multi-platform office productivity suite
 *
 *  $RCSfile: XMLChartStyleContext.cxx,v $
 *
 *  $Revision: 1.11 $
 *
 *  last change: $Author: hr $ $Date: 2007-06-27 14:51:11 $
 *
 *  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_xmloff.hxx"
#include "XMLChartStyleContext.hxx"

#ifndef _XMLOFF_XMLTOKEN_HXX
#include <xmloff/xmltoken.hxx>
#endif
#ifndef _XMLOFF_XMLNMSPE_HXX
#include "xmlnmspe.hxx"
#endif
#ifndef _XMLOFF_XMLNUMFI_HXX
#include <xmloff/xmlnumfi.hxx>
#endif
#ifndef _XMLOFF_FAMILIES_HXX_
#include <xmloff/families.hxx>
#endif

#include "XMLChartPropertyContext.hxx"

using namespace com::sun::star;
using ::xmloff::token::IsXMLToken;
using ::xmloff::token::XML_DATA_STYLE_NAME;
using ::xmloff::token::XML_TEXT_PROPERTIES;
using ::xmloff::token::XML_PARAGRAPH_PROPERTIES;
using ::xmloff::token::XML_GRAPHIC_PROPERTIES;
using ::xmloff::token::XML_CHART_PROPERTIES;

TYPEINIT1( XMLChartStyleContext, XMLPropStyleContext );

// protected

void XMLChartStyleContext::SetAttribute(
    sal_uInt16 nPrefixKey,
    const ::rtl::OUString& rLocalName,
    const ::rtl::OUString& rValue )
{
    if( IsXMLToken( rLocalName, XML_DATA_STYLE_NAME ) )
    {
        msDataStyleName =rValue;
    }
    else
    {
        XMLShapeStyleContext::SetAttribute( nPrefixKey, rLocalName, rValue );
    }
}

//public

// CTOR
XMLChartStyleContext::XMLChartStyleContext(
    SvXMLImport& rImport, sal_uInt16 nPrfx,
    const ::rtl::OUString& rLName,
    const uno::Reference< xml::sax::XAttributeList > & xAttrList,
    SvXMLStylesContext& rStyles, sal_uInt16 nFamily ) :

        XMLShapeStyleContext( rImport, nPrfx, rLName, xAttrList, rStyles, nFamily ),
        mrStyles( rStyles )
{}

// DTOR
XMLChartStyleContext::~XMLChartStyleContext()
{}

void XMLChartStyleContext::FillPropertySet(
    const uno::Reference< beans::XPropertySet > & rPropSet )
{
    try
    {
        XMLShapeStyleContext::FillPropertySet( rPropSet );
    }
    catch( beans::UnknownPropertyException&  )
    {
        DBG_ASSERT( false, "unknown property exception -> shape style not completly imported for chart style" );
    }
    if( msDataStyleName.getLength())
    {
        SvXMLNumFormatContext* pStyle = (SvXMLNumFormatContext *)mrStyles.FindStyleChildContext(
            XML_STYLE_FAMILY_DATA_STYLE, msDataStyleName, sal_True );
        if( pStyle )
        {
            uno::Any aNumberFormat;
            sal_Int32 nNumberFormat = pStyle->GetKey();
            aNumberFormat <<= nNumberFormat;
            rPropSet->setPropertyValue( rtl::OUString( RTL_CONSTASCII_USTRINGPARAM( "NumberFormat" )),
                                        aNumberFormat );
        }
    }
}

SvXMLImportContext *XMLChartStyleContext::CreateChildContext(
    sal_uInt16 nPrefix,
    const ::rtl::OUString& rLocalName,
    const uno::Reference< xml::sax::XAttributeList > & xAttrList )
{
    SvXMLImportContext* pContext = NULL;

    if( XML_NAMESPACE_STYLE == nPrefix )
    {
        sal_uInt32 nFamily = 0;
        if( IsXMLToken( rLocalName, XML_TEXT_PROPERTIES ) )
            nFamily = XML_TYPE_PROP_TEXT;
        else if( IsXMLToken( rLocalName, XML_PARAGRAPH_PROPERTIES ) )
            nFamily = XML_TYPE_PROP_PARAGRAPH;
        else if( IsXMLToken( rLocalName, XML_GRAPHIC_PROPERTIES ) )
            nFamily = XML_TYPE_PROP_GRAPHIC;
        else if( IsXMLToken( rLocalName, XML_CHART_PROPERTIES ) )
            nFamily = XML_TYPE_PROP_CHART;
        if( nFamily )
        {
            UniReference < SvXMLImportPropertyMapper > xImpPrMap =
                GetStyles()->GetImportPropertyMapper( GetFamily() );
            if( xImpPrMap.is() )
                pContext = new XMLChartPropertyContext(
                    GetImport(), nPrefix, rLocalName, xAttrList, nFamily,
                    GetProperties(), xImpPrMap );
        }
    }

    if( !pContext )
        pContext = XMLShapeStyleContext::CreateChildContext( nPrefix, rLocalName,
                                                             xAttrList );

    return pContext;
}
<commit_msg>INTEGRATION: CWS chart14 (1.11.48); FILE MERGED 2007/08/10 21:58:04 iha 1.11.48.1: #i37792# number format for data labels<commit_after>/*************************************************************************
 *
 *  OpenOffice.org - a multi-platform office productivity suite
 *
 *  $RCSfile: XMLChartStyleContext.cxx,v $
 *
 *  $Revision: 1.12 $
 *
 *  last change: $Author: vg $ $Date: 2007-10-22 16:33:51 $
 *
 *  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_xmloff.hxx"
#include "XMLChartStyleContext.hxx"

#ifndef _XMLOFF_XMLTOKEN_HXX
#include <xmloff/xmltoken.hxx>
#endif
#ifndef _XMLOFF_XMLNMSPE_HXX
#include "xmlnmspe.hxx"
#endif
#ifndef _XMLOFF_XMLNUMFI_HXX
#include <xmloff/xmlnumfi.hxx>
#endif
#ifndef _XMLOFF_FAMILIES_HXX_
#include <xmloff/families.hxx>
#endif

#include "XMLChartPropertyContext.hxx"

using namespace com::sun::star;
using ::xmloff::token::IsXMLToken;
using ::xmloff::token::XML_DATA_STYLE_NAME;
using ::xmloff::token::XML_PERCENTAGE_DATA_STYLE_NAME;
using ::xmloff::token::XML_TEXT_PROPERTIES;
using ::xmloff::token::XML_PARAGRAPH_PROPERTIES;
using ::xmloff::token::XML_GRAPHIC_PROPERTIES;
using ::xmloff::token::XML_CHART_PROPERTIES;

TYPEINIT1( XMLChartStyleContext, XMLPropStyleContext );

// protected

void XMLChartStyleContext::SetAttribute(
    sal_uInt16 nPrefixKey,
    const ::rtl::OUString& rLocalName,
    const ::rtl::OUString& rValue )
{
    if( IsXMLToken( rLocalName, XML_DATA_STYLE_NAME ) )
    {
        msDataStyleName =rValue;
    }
    if( IsXMLToken( rLocalName, XML_PERCENTAGE_DATA_STYLE_NAME ) )
    {
        msPercentageDataStyleName =rValue;
    }
    else
    {
        XMLShapeStyleContext::SetAttribute( nPrefixKey, rLocalName, rValue );
    }
}

//public

// CTOR
XMLChartStyleContext::XMLChartStyleContext(
    SvXMLImport& rImport, sal_uInt16 nPrfx,
    const ::rtl::OUString& rLName,
    const uno::Reference< xml::sax::XAttributeList > & xAttrList,
    SvXMLStylesContext& rStyles, sal_uInt16 nFamily ) :

        XMLShapeStyleContext( rImport, nPrfx, rLName, xAttrList, rStyles, nFamily ),
        mrStyles( rStyles )
{}

// DTOR
XMLChartStyleContext::~XMLChartStyleContext()
{}

namespace
{

    void lcl_NumberFormatStyleToProperty( const ::rtl::OUString& rStyleName, const ::rtl::OUString& rPropertyName,
                                      const SvXMLStylesContext& rStylesContext,
                                      const uno::Reference< beans::XPropertySet >& rPropSet )
{
    if( rStyleName.getLength())
    {
        SvXMLNumFormatContext* pStyle = (SvXMLNumFormatContext *)rStylesContext.FindStyleChildContext(
            XML_STYLE_FAMILY_DATA_STYLE, rStyleName, sal_True );
        if( pStyle )
        {
            uno::Any aNumberFormat;
            sal_Int32 nNumberFormat = pStyle->GetKey();
            aNumberFormat <<= nNumberFormat;
            rPropSet->setPropertyValue( rPropertyName, aNumberFormat );
        }
    }
}

}// anonymous namespace

void XMLChartStyleContext::FillPropertySet(
    const uno::Reference< beans::XPropertySet > & rPropSet )
{
    try
    {
        XMLShapeStyleContext::FillPropertySet( rPropSet );
    }
    catch( beans::UnknownPropertyException&  )
    {
        DBG_ASSERT( false, "unknown property exception -> shape style not completly imported for chart style" );
    }

    lcl_NumberFormatStyleToProperty( msDataStyleName, rtl::OUString( RTL_CONSTASCII_USTRINGPARAM( "NumberFormat" )), mrStyles, rPropSet );
    lcl_NumberFormatStyleToProperty( msPercentageDataStyleName, rtl::OUString( RTL_CONSTASCII_USTRINGPARAM( "PercentageNumberFormat" )), mrStyles, rPropSet );
}

SvXMLImportContext *XMLChartStyleContext::CreateChildContext(
    sal_uInt16 nPrefix,
    const ::rtl::OUString& rLocalName,
    const uno::Reference< xml::sax::XAttributeList > & xAttrList )
{
    SvXMLImportContext* pContext = NULL;

    if( XML_NAMESPACE_STYLE == nPrefix )
    {
        sal_uInt32 nFamily = 0;
        if( IsXMLToken( rLocalName, XML_TEXT_PROPERTIES ) )
            nFamily = XML_TYPE_PROP_TEXT;
        else if( IsXMLToken( rLocalName, XML_PARAGRAPH_PROPERTIES ) )
            nFamily = XML_TYPE_PROP_PARAGRAPH;
        else if( IsXMLToken( rLocalName, XML_GRAPHIC_PROPERTIES ) )
            nFamily = XML_TYPE_PROP_GRAPHIC;
        else if( IsXMLToken( rLocalName, XML_CHART_PROPERTIES ) )
            nFamily = XML_TYPE_PROP_CHART;
        if( nFamily )
        {
            UniReference < SvXMLImportPropertyMapper > xImpPrMap =
                GetStyles()->GetImportPropertyMapper( GetFamily() );
            if( xImpPrMap.is() )
                pContext = new XMLChartPropertyContext(
                    GetImport(), nPrefix, rLocalName, xAttrList, nFamily,
                    GetProperties(), xImpPrMap );
        }
    }

    if( !pContext )
        pContext = XMLShapeStyleContext::CreateChildContext( nPrefix, rLocalName,
                                                             xAttrList );

    return pContext;
}
<|endoftext|>


<commit_before>#pragma once
/*
* Covariant Script Version Info
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
* Copyright (C) 2018 Michael Lee(李登淳)
* Email: mikecovlee@163.com
* Github: https://github.com/mikecovlee
*
* Version Format:
*   1 . 0 . 0 [Version Code](Preview/Unstable/Stable) Build 1
*   |   |   |                           |
*   |   | Minor                       Status
*   | Major
* Master
*
*/
#define COVSCRIPT_VERSION_NUM 3,0,0,6
#define COVSCRIPT_VERSION_STR "3.0.0 Pantholops hodgsonii(Stable) Build 6"
#define COVSCRIPT_STD_VERSION 190101
#define COVSCRIPT_ABI_VERSION 190101
#if defined(_WIN32) || defined(WIN32)
#define COVSCRIPT_PLATFORM_WIN32
#endif
<commit_msg>Update CovScript Version<commit_after>#pragma once
/*
* Covariant Script Version Info
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
* Copyright (C) 2018 Michael Lee(李登淳)
* Email: mikecovlee@163.com
* Github: https://github.com/mikecovlee
*
* Version Format:
*   1 . 0 . 0 [Version Code](Preview/Unstable/Stable) Build 1
*   |   |   |                           |
*   |   | Minor                       Status
*   | Major
* Master
*
*/
#define COVSCRIPT_VERSION_NUM 3,0,1,1
#define COVSCRIPT_VERSION_STR "3.0.1 Acipenser sinensis(Unstable) Build 1"
#define COVSCRIPT_STD_VERSION 190101
#define COVSCRIPT_ABI_VERSION 190101
#if defined(_WIN32) || defined(WIN32)
#define COVSCRIPT_PLATFORM_WIN32
#endif
<|endoftext|>


<commit_before>#include <ros/ros.h>
#include <dynamic_reconfigure/server.h>
#include <geometry_msgs/Pose.h>
#include <geometry_msgs/PoseArray.h>
#include <geometry_msgs/PoseStamped.h>

#include <kinect_tomato_searcher/CalibrationConfig.h>

#include <algorithm>
#include <memory>
#include <vector>

struct Calibrator
{
  double offset_x_;
  double offset_y_;
  double offset_z_;

  geometry_msgs::Pose calibrate(geometry_msgs::Pose) const;
  void callback(kinect_tomato_searcher::CalibrationConfig& config, uint32_t level);
};

class NearSelector
{
public:
  geometry_msgs::Pose select(const geometry_msgs::PoseArray& pose_array);
private:
  geometry_msgs::Pose last_pose_;
};

void callback(const geometry_msgs::PoseArray&);
double calcDiff(const geometry_msgs::Pose&, const geometry_msgs::Pose&);

ros::Publisher pub;
std::unique_ptr<Calibrator> calibrator;

int main(int argc, char** argv)
{
  ros::init(argc, argv, "kinect_tomato_selector_node");
  ros::NodeHandle tomato_nh {"tomato"};
  auto sub = tomato_nh.subscribe("array", 1, &callback);
  pub = tomato_nh.advertise<geometry_msgs::PoseStamped>("raw", 1);
  ros::NodeHandle offset_nh {"~offset"};
  double offset_x, offset_y, offset_z;
  offset_nh.getParam("x", offset_x);
  offset_nh.getParam("y", offset_y);
  offset_nh.getParam("z", offset_z);
  calibrator = std::unique_ptr<Calibrator> {new Calibrator {offset_x, offset_y, offset_z}};
  ros::spin();
  return 0;
}

inline geometry_msgs::Pose Calibrator::calibrate(geometry_msgs::Pose pose) const
{
  pose.position.x += offset_x_;
  pose.position.y += offset_y_;
  pose.position.z += offset_z_;
  return pose;
}

void Calibrator::callback(kinect_tomato_searcher::CalibrationConfig& config, uint32_t level)
{
  offset_x_ = config.offset_x;
  offset_y_ = config.offset_y;
  offset_z_ = config.offset_z;
}

inline geometry_msgs::Pose NearSelector::select(const geometry_msgs::PoseArray& pose_array)
{
  std::vector<double> diffs(pose_array.poses.size());
  auto diff_it = diffs.begin();
  for (auto pose : pose_array.poses) {
    *diff_it = calcDiff(pose, last_pose_);
    ++diff_it;
  }
  auto min_diff_it = std::min_element(diffs.cbegin(), diffs.cend());
  return pose_array.poses[min_diff_it - diffs.cbegin()];
}

/**
 * This function calculate lie distance.
 *
 * @return diff linear difference. NOT real difference.
 */
inline double calcDiff(const geometry_msgs::Pose& target, const geometry_msgs::Pose& origin) {
  double diff_x {target.position.x - origin.position.x};
  double diff_y {target.position.y - origin.position.y};
  double diff_z {target.position.z - origin.position.z};
  return diff_x + diff_y + diff_z;
}

void callback(const geometry_msgs::PoseArray& pose_array)
{
  static NearSelector selector {};
  geometry_msgs::PoseStamped pub_msg;
  pub_msg.header = pose_array.header;
  pub_msg.pose = calibrator->calibrate(selector.select(pose_array));
  pub.publish(pub_msg);
}
<commit_msg>Impliment dynamic_reconfigure<commit_after>#include <ros/ros.h>
#include <dynamic_reconfigure/server.h>
#include <geometry_msgs/Pose.h>
#include <geometry_msgs/PoseArray.h>
#include <geometry_msgs/PoseStamped.h>

#include <kinect_tomato_searcher/CalibrationConfig.h>

#include <algorithm>
#include <memory>
#include <vector>

struct Calibrator
{
  Calibrator(double offset_x, double offset_y, double offset_z);
  double offset_x_;
  double offset_y_;
  double offset_z_;

  geometry_msgs::Pose calibrate(geometry_msgs::Pose) const;
private:
  dynamic_reconfigure::Server<kinect_tomato_searcher::CalibrationConfig> server;
  dynamic_reconfigure::Server<kinect_tomato_searcher::CalibrationConfig>::CallbackType f;
  void callback(kinect_tomato_searcher::CalibrationConfig& config, uint32_t level);
};

class NearSelector
{
public:
  geometry_msgs::Pose select(const geometry_msgs::PoseArray& pose_array);
private:
  geometry_msgs::Pose last_pose_;
};

void callback(const geometry_msgs::PoseArray&);
double calcDiff(const geometry_msgs::Pose&, const geometry_msgs::Pose&);

ros::Publisher pub;
std::unique_ptr<Calibrator> calibrator;

int main(int argc, char** argv)
{
  ros::init(argc, argv, "kinect_tomato_selector_node");
  ros::NodeHandle tomato_nh {"tomato"};
  auto sub = tomato_nh.subscribe("array", 1, &callback);
  pub = tomato_nh.advertise<geometry_msgs::PoseStamped>("raw", 1);
  ros::NodeHandle offset_nh {"~offset"};
  double offset_x, offset_y, offset_z;
  offset_nh.getParam("x", offset_x);
  offset_nh.getParam("y", offset_y);
  offset_nh.getParam("z", offset_z);
  calibrator = std::unique_ptr<Calibrator> {new Calibrator {offset_x, offset_y, offset_z}};
  ros::spin();
  return 0;
}

Calibrator::Calibrator(double offset_x, double offset_y, double offset_z)
  : offset_x_ {offset_x},
    offset_y_ {offset_y},
    offset_z_ {offset_z},
    server {},
    f(std::bind(&Calibrator::callback, this, std::placeholders::_1, std::placeholders::_2))
{
   server.setCallback(f);
}

inline geometry_msgs::Pose Calibrator::calibrate(geometry_msgs::Pose pose) const
{
  pose.position.x += offset_x_;
  pose.position.y += offset_y_;
  pose.position.z += offset_z_;
  return pose;
}

void Calibrator::callback(kinect_tomato_searcher::CalibrationConfig& config, uint32_t level)
{
  offset_x_ = config.offset_x;
  offset_y_ = config.offset_y;
  offset_z_ = config.offset_z;
}

inline geometry_msgs::Pose NearSelector::select(const geometry_msgs::PoseArray& pose_array)
{
  std::vector<double> diffs(pose_array.poses.size());
  auto diff_it = diffs.begin();
  for (auto pose : pose_array.poses) {
    *diff_it = calcDiff(pose, last_pose_);
    ++diff_it;
  }
  auto min_diff_it = std::min_element(diffs.cbegin(), diffs.cend());
  return pose_array.poses[min_diff_it - diffs.cbegin()];
}

/**
 * This function calculate lie distance.
 *
 * @return diff linear difference. NOT real difference.
 */
inline double calcDiff(const geometry_msgs::Pose& target, const geometry_msgs::Pose& origin) {
  double diff_x {target.position.x - origin.position.x};
  double diff_y {target.position.y - origin.position.y};
  double diff_z {target.position.z - origin.position.z};
  return diff_x + diff_y + diff_z;
}

void callback(const geometry_msgs::PoseArray& pose_array)
{
  static NearSelector selector {};
  geometry_msgs::PoseStamped pub_msg;
  pub_msg.header = pose_array.header;
  pub_msg.pose = calibrator->calibrate(selector.select(pose_array));
  pub.publish(pub_msg);
}
<|endoftext|>


<commit_before>/*************************************************************************
 *
 *  $RCSfile: NamedBoolPropertyHdl.cxx,v $
 *
 *  $Revision: 1.2 $
 *
 *  last change: $Author: sab $ $Date: 2001-03-16 14:37:07 $
 *
 *  The Contents of this file are made available subject to the terms of
 *  either of the following licenses
 *
 *         - GNU Lesser General Public License Version 2.1
 *         - Sun Industry Standards Source License Version 1.1
 *
 *  Sun Microsystems Inc., October, 2000
 *
 *  GNU Lesser General Public License Version 2.1
 *  =============================================
 *  Copyright 2000 by Sun Microsystems, Inc.
 *  901 San Antonio Road, Palo Alto, CA 94303, USA
 *
 *  This library is free software; you can redistribute it and/or
 *  modify it under the terms of the GNU Lesser General Public
 *  License version 2.1, as published by the Free Software Foundation.
 *
 *  This library is distributed in the hope that it will be useful,
 *  but WITHOUT ANY WARRANTY; without even the implied warranty of
 *  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 *  Lesser General Public License for more details.
 *
 *  You should have received a copy of the GNU Lesser General Public
 *  License along with this library; if not, write to the Free Software
 *  Foundation, Inc., 59 Temple Place, Suite 330, Boston,
 *  MA  02111-1307  USA
 *
 *
 *  Sun Industry Standards Source License Version 1.1
 *  =================================================
 *  The contents of this file are subject to the Sun Industry Standards
 *  Source License Version 1.1 (the "License"); You may not use this file
 *  except in compliance with the License. You may obtain a copy of the
 *  License at http://www.openoffice.org/license.html.
 *
 *  Software provided under this License is provided on an "AS IS" basis,
 *  WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING,
 *  WITHOUT LIMITATION, WARRANTIES THAT THE SOFTWARE IS FREE OF DEFECTS,
 *  MERCHANTABLE, FIT FOR A PARTICULAR PURPOSE, OR NON-INFRINGING.
 *  See the License for the specific provisions governing your rights and
 *  obligations concerning the Software.
 *
 *  The Initial Developer of the Original Code is: Sun Microsystems, Inc.
 *
 *  Copyright: 2000 by Sun Microsystems, Inc.
 *
 *  All Rights Reserved.
 *
 *  Contributor(s): _______________________________________
 *
 *
 ************************************************************************/

#ifndef _XMLOFF_NAMEDBOOLPROPERTYHANDLER_HXX
#include <NamedBoolPropertyHdl.hxx>
#endif

#ifndef _XMLOFF_XMLUCONV_HXX
#include "xmluconv.hxx"
#endif

#ifndef _COMPHELPER_EXTRACT_HXX_
#include <comphelper/extract.hxx>
#endif

#ifndef _RTL_USTRING_
#include <rtl/ustring>
#endif

#ifndef _RTL_USTRBUF_HXX_
#include <rtl/ustrbuf.hxx>
#endif

#ifndef _COM_SUN_STAR_UNO_ANY_HXX_
#include <com/sun/star/uno/Any.hxx>
#endif

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

///////////////////////////////////////////////////////////////////////////////
//
// class XMLNamedBoolPropertyHdl
//

XMLNamedBoolPropertyHdl::~XMLNamedBoolPropertyHdl()
{
    // Nothing to do
}

sal_Bool XMLNamedBoolPropertyHdl::importXML( const OUString& rStrImpValue, Any& rValue, const SvXMLUnitConverter& rUnitConverter ) const
{
    if( rStrImpValue == maTrueStr )
    {
        rValue = ::cppu::bool2any( sal_True );
        return sal_True;
    }

    if( rStrImpValue == maFalseStr )
    {
        rValue = ::cppu::bool2any( sal_False );
        return sal_True;
    }

    return sal_False;
}

sal_Bool XMLNamedBoolPropertyHdl::exportXML( OUString& rStrExpValue, const Any& rValue, const SvXMLUnitConverter& rUnitConverter ) const
{
    if( ::cppu::any2bool( rValue ) )
    {
        rStrExpValue = maTrueStr;
    }
    else
    {
        rStrExpValue = maFalseStr;
    }

    return sal_True;
}

<commit_msg>INTEGRATION: CWS ooo19126 (1.2.642); FILE MERGED 2005/09/05 14:39:12 rt 1.2.642.1: #i54170# Change license header: remove SISSL<commit_after>/*************************************************************************
 *
 *  OpenOffice.org - a multi-platform office productivity suite
 *
 *  $RCSfile: NamedBoolPropertyHdl.cxx,v $
 *
 *  $Revision: 1.3 $
 *
 *  last change: $Author: rt $ $Date: 2005-09-09 14:25:04 $
 *
 *  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 _XMLOFF_NAMEDBOOLPROPERTYHANDLER_HXX
#include <NamedBoolPropertyHdl.hxx>
#endif

#ifndef _XMLOFF_XMLUCONV_HXX
#include "xmluconv.hxx"
#endif

#ifndef _COMPHELPER_EXTRACT_HXX_
#include <comphelper/extract.hxx>
#endif

#ifndef _RTL_USTRING_
#include <rtl/ustring>
#endif

#ifndef _RTL_USTRBUF_HXX_
#include <rtl/ustrbuf.hxx>
#endif

#ifndef _COM_SUN_STAR_UNO_ANY_HXX_
#include <com/sun/star/uno/Any.hxx>
#endif

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

///////////////////////////////////////////////////////////////////////////////
//
// class XMLNamedBoolPropertyHdl
//

XMLNamedBoolPropertyHdl::~XMLNamedBoolPropertyHdl()
{
    // Nothing to do
}

sal_Bool XMLNamedBoolPropertyHdl::importXML( const OUString& rStrImpValue, Any& rValue, const SvXMLUnitConverter& rUnitConverter ) const
{
    if( rStrImpValue == maTrueStr )
    {
        rValue = ::cppu::bool2any( sal_True );
        return sal_True;
    }

    if( rStrImpValue == maFalseStr )
    {
        rValue = ::cppu::bool2any( sal_False );
        return sal_True;
    }

    return sal_False;
}

sal_Bool XMLNamedBoolPropertyHdl::exportXML( OUString& rStrExpValue, const Any& rValue, const SvXMLUnitConverter& rUnitConverter ) const
{
    if( ::cppu::any2bool( rValue ) )
    {
        rStrExpValue = maTrueStr;
    }
    else
    {
        rStrExpValue = maFalseStr;
    }

    return sal_True;
}

<|endoftext|>


<commit_before><commit_msg>adding glBindBuffer in opengl.hpp<commit_after>#ifndef ATEMA_OPENGL_HEADER
#define ATEMA_OPENGL_HEADER

#include <glad/glad.h>

// glBindBuffer
#undef glBindBuffer
GLAPI PFNGLBINDBUFFERPROC at_glBindBuffer;
#define glBindBuffer at_glBindBuffer

#endif<|endoftext|>


<commit_before>/*

Copyright (c) 2005, Arvid Norberg
All rights reserved.

Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions
are met:

    * Redistributions of source code must retain the above copyright
      notice, this list of conditions and the following disclaimer.
    * Redistributions in binary form must reproduce the above copyright
      notice, this list of conditions and the following disclaimer in
      the documentation and/or other materials provided with the distribution.
    * Neither the name of the author nor the names of its
      contributors may be used to endorse or promote products derived
      from this software without specific prior written permission.

THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE
LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
POSSIBILITY OF SUCH DAMAGE.

*/

#ifndef TORRENT_CONFIG_HPP_INCLUDED
#define TORRENT_CONFIG_HPP_INCLUDED

#include <boost/config.hpp>
#include <boost/version.hpp>

#if defined(__GNUC__) && __GNUC__ >= 4

#define TORRENT_DEPRECATED __attribute__ ((deprecated))

# if defined(TORRENT_BUILDING_SHARED) || defined(TORRENT_LINKING_SHARED)
#  define TORRENT_EXPORT __attribute__ ((visibility("default")))
# else
#  define TORRENT_EXPORT
# endif

#elif defined(__GNUC__)

# define TORRENT_EXPORT

#elif defined(BOOST_MSVC)

# if defined(TORRENT_BUILDING_SHARED)
#  define TORRENT_EXPORT __declspec(dllexport)
# elif defined(TORRENT_LINKING_SHARED)
#  define TORRENT_EXPORT __declspec(dllimport)
# else
#  define TORRENT_EXPORT
# endif

#else
# define TORRENT_EXPORT
#endif

#ifndef TORRENT_DEPRECATED
#define TORRENT_DEPRECATED
#endif

// set up defines for target environments
#if (defined __APPLE__ && __MACH__) || defined __FreeBSD__ || defined __NetBSD__ \
	|| defined __OpenBSD__ || defined __bsdi__ || defined __DragonFly__ \
	|| defined __FreeBSD_kernel__
#define TORRENT_BSD
#elif defined __linux__
#define TORRENT_LINUX
#elif defined WIN32
#define TORRENT_WINDOWS
#elif defined sun || defined __sun
#define TORRENT_SOLARIS
#else
#warning unkown OS, assuming BSD
#define TORRENT_BSD
#endif

#define TORRENT_USE_IPV6 1
#define TORRENT_USE_MLOCK 1
#define TORRENT_USE_READV 1
#define TORRENT_USE_WRITEV 1
#define TORRENT_USE_IOSTREAM 1

// should wpath or path be used?
#if defined UNICODE && !defined BOOST_FILESYSTEM_NARROW_ONLY \
	&& BOOST_VERSION >= 103400 && !defined __APPLE__
#define TORRENT_USE_WPATH 1
#else
#define TORRENT_USE_WPATH 0
#endif

#ifdef TORRENT_WINDOWS
// this is the maximum number of characters in a
// path element / filename on windows
#define NAME_MAX 255
#endif

#if (defined(TORRENT_LOGGING) || defined(TORRENT_VERBOSE_LOGGING)) && !defined (TORRENT_UPNP_LOGGING)
#define TORRENT_UPNP_LOGGING
#endif

#if !TORRENT_USE_WPATH && defined TORRENT_LINUX
// libiconv presnce, not implemented yet
#define TORRENT_USE_LOCALE_FILENAMES 1
#else
#define TORRENT_USE_LOCALE_FILENAMES 0
#endif

#endif // TORRENT_CONFIG_HPP_INCLUDED

<commit_msg>defines for snprintf and strtoll for windows<commit_after>/*

Copyright (c) 2005, Arvid Norberg
All rights reserved.

Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions
are met:

    * Redistributions of source code must retain the above copyright
      notice, this list of conditions and the following disclaimer.
    * Redistributions in binary form must reproduce the above copyright
      notice, this list of conditions and the following disclaimer in
      the documentation and/or other materials provided with the distribution.
    * Neither the name of the author nor the names of its
      contributors may be used to endorse or promote products derived
      from this software without specific prior written permission.

THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE
LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
POSSIBILITY OF SUCH DAMAGE.

*/

#ifndef TORRENT_CONFIG_HPP_INCLUDED
#define TORRENT_CONFIG_HPP_INCLUDED

#include <boost/config.hpp>
#include <boost/version.hpp>

#if defined(__GNUC__) && __GNUC__ >= 4

#define TORRENT_DEPRECATED __attribute__ ((deprecated))

# if defined(TORRENT_BUILDING_SHARED) || defined(TORRENT_LINKING_SHARED)
#  define TORRENT_EXPORT __attribute__ ((visibility("default")))
# else
#  define TORRENT_EXPORT
# endif

#elif defined(__GNUC__)

# define TORRENT_EXPORT

#elif defined(BOOST_MSVC)

# if defined(TORRENT_BUILDING_SHARED)
#  define TORRENT_EXPORT __declspec(dllexport)
# elif defined(TORRENT_LINKING_SHARED)
#  define TORRENT_EXPORT __declspec(dllimport)
# else
#  define TORRENT_EXPORT
# endif

#else
# define TORRENT_EXPORT
#endif

#ifndef TORRENT_DEPRECATED
#define TORRENT_DEPRECATED
#endif

// set up defines for target environments
#if (defined __APPLE__ && __MACH__) || defined __FreeBSD__ || defined __NetBSD__ \
	|| defined __OpenBSD__ || defined __bsdi__ || defined __DragonFly__ \
	|| defined __FreeBSD_kernel__
#define TORRENT_BSD
#elif defined __linux__
#define TORRENT_LINUX
#elif defined WIN32
#define TORRENT_WINDOWS
#elif defined sun || defined __sun
#define TORRENT_SOLARIS
#else
#warning unkown OS, assuming BSD
#define TORRENT_BSD
#endif

#define TORRENT_USE_IPV6 1
#define TORRENT_USE_MLOCK 1
#define TORRENT_USE_READV 1
#define TORRENT_USE_WRITEV 1
#define TORRENT_USE_IOSTREAM 1

// should wpath or path be used?
#if defined UNICODE && !defined BOOST_FILESYSTEM_NARROW_ONLY \
	&& BOOST_VERSION >= 103400 && !defined __APPLE__
#define TORRENT_USE_WPATH 1
#else
#define TORRENT_USE_WPATH 0
#endif

#ifdef TORRENT_WINDOWS
// this is the maximum number of characters in a
// path element / filename on windows
#define NAME_MAX 255
#define snprintf _snprintf_s
#define strtoll _strtoi64
#endif

#if (defined(TORRENT_LOGGING) || defined(TORRENT_VERBOSE_LOGGING)) && !defined (TORRENT_UPNP_LOGGING)
#define TORRENT_UPNP_LOGGING
#endif

#if !TORRENT_USE_WPATH && defined TORRENT_LINUX
// libiconv presnce, not implemented yet
#define TORRENT_USE_LOCALE_FILENAMES 1
#else
#define TORRENT_USE_LOCALE_FILENAMES 0
#endif

#endif // TORRENT_CONFIG_HPP_INCLUDED

<|endoftext|>


<commit_before>/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */
/*
 * This file is part of the LibreOffice project.
 *
 * This Source Code Form is subject to the terms of the Mozilla Public
 * License, v. 2.0. If a copy of the MPL was not distributed with this
 * file, You can obtain one at http://mozilla.org/MPL/2.0/.
 *
 * This file incorporates work covered by the following license notice:
 *
 *   Licensed to the Apache Software Foundation (ASF) under one or more
 *   contributor license agreements. See the NOTICE file distributed
 *   with this work for additional information regarding copyright
 *   ownership. The ASF licenses this file to you under the Apache
 *   License, Version 2.0 (the "License"); you may not use this file
 *   except in compliance with the License. You may obtain a copy of
 *   the License at http://www.apache.org/licenses/LICENSE-2.0 .
 */
#ifndef INCLUDED_COMPHELPER_STL_TYPES_HXX
#define INCLUDED_COMPHELPER_STL_TYPES_HXX

#include <sal/config.h>

#include <stack>

#include <math.h>
#include <functional>

#include <rtl/ustring.hxx>
#include <rtl/ustrbuf.hxx>
#include <com/sun/star/uno/Reference.hxx>
#include <com/sun/star/beans/PropertyValue.hpp>
#include <com/sun/star/beans/NamedValue.hpp>

//... namespace comphelper ................................................
namespace comphelper
{
//.........................................................................

//========================================================================
// comparison functors

struct UStringMixLess : public ::std::binary_function< OUString, OUString, bool>
{
    bool m_bCaseSensitive;
public:
    UStringMixLess(bool bCaseSensitive = true):m_bCaseSensitive(bCaseSensitive){}
    bool operator() (const OUString& x, const OUString& y) const
    {
        if (m_bCaseSensitive)
            return rtl_ustr_compare(x.getStr(), y.getStr()) < 0 ? true : false;
        else
            return rtl_ustr_compareIgnoreAsciiCase(x.getStr(), y.getStr()) < 0 ? true : false;
    }

    bool isCaseSensitive() const {return m_bCaseSensitive;}
};
//------------------------------------------------------------------------
struct UStringEqual
{
    sal_Bool operator() (const OUString& lhs, const OUString& rhs) const { return lhs.equals( rhs );}
};

//------------------------------------------------------------------------
struct UStringIEqual
{
    sal_Bool operator() (const OUString& lhs, const OUString& rhs) const { return lhs.equalsIgnoreAsciiCase( rhs );}
};

//------------------------------------------------------------------------
class UStringMixEqual
{
    sal_Bool m_bCaseSensitive;

public:
    UStringMixEqual(sal_Bool bCaseSensitive = sal_True):m_bCaseSensitive(bCaseSensitive){}
    sal_Bool operator() (const OUString& lhs, const OUString& rhs) const
    {
        return m_bCaseSensitive ? lhs.equals( rhs ) : lhs.equalsIgnoreAsciiCase( rhs );
    }
    sal_Bool isCaseSensitive() const {return m_bCaseSensitive;}
};
//------------------------------------------------------------------------
class TStringMixEqualFunctor : public ::std::binary_function< OUString,OUString,bool>
{
    sal_Bool m_bCaseSensitive;

public:
    TStringMixEqualFunctor(sal_Bool bCaseSensitive = sal_True)
        :m_bCaseSensitive(bCaseSensitive)
    {}
    bool operator() (const OUString& lhs, const OUString& rhs) const
    {
        return !!(m_bCaseSensitive ? lhs.equals( rhs ) : lhs.equalsIgnoreAsciiCase( rhs ));
    }
    sal_Bool isCaseSensitive() const {return m_bCaseSensitive;}
};
//------------------------------------------------------------------------
class TPropertyValueEqualFunctor : public ::std::binary_function< ::com::sun::star::beans::PropertyValue,OUString,bool>
{
public:
    TPropertyValueEqualFunctor()
    {}
    bool operator() (const ::com::sun::star::beans::PropertyValue& lhs, const OUString& rhs) const
    {
        return !!(lhs.Name == rhs);
    }
};
//------------------------------------------------------------------------
class TNamedValueEqualFunctor : public ::std::binary_function< ::com::sun::star::beans::NamedValue,OUString,bool>
{
public:
    TNamedValueEqualFunctor()
    {}
    bool operator() (const ::com::sun::star::beans::NamedValue& lhs, const OUString& rhs) const
    {
        return !!(lhs.Name == rhs);
    }
};
//------------------------------------------------------------------------
class UStringMixHash
{
    sal_Bool m_bCaseSensitive;

public:
    UStringMixHash(sal_Bool bCaseSensitive = sal_True):m_bCaseSensitive(bCaseSensitive){}
    size_t operator() (const OUString& rStr) const
    {
        return m_bCaseSensitive ? rStr.hashCode() : rStr.toAsciiUpperCase().hashCode();
    }
    sal_Bool isCaseSensitive() const {return m_bCaseSensitive;}
};

//=====================================================================
//= OInterfaceCompare
//=====================================================================
/** is stl-compliant structure for comparing Reference< <iface> > instances
*/
template < class IAFCE >
struct OInterfaceCompare
    :public ::std::binary_function  <   ::com::sun::star::uno::Reference< IAFCE >
                                    ,   ::com::sun::star::uno::Reference< IAFCE >
                                    ,   bool
                                    >
{
    bool operator() (const ::com::sun::star::uno::Reference< IAFCE >& lhs, const ::com::sun::star::uno::Reference< IAFCE >& rhs) const
    {
        return lhs.get() < rhs.get();
            // this does not make any sense if you see the semantics of the pointer returned by get:
            // It's a pointer to a point in memory where an interface implementation lies.
            // But for our purpose (provide a reliable less-operator which can be used with the STL), this is
            // sufficient ....
    }
};

template <class _Tp, class _Arg>
class mem_fun1_t : public ::std::binary_function<_Tp*,_Arg,void>
{
    typedef void (_Tp::*_fun_type)(_Arg);
public:
    explicit mem_fun1_t(_fun_type __pf) : _M_f(__pf) {}
    void operator()(_Tp* __p, _Arg __x) const { (__p->*_M_f)(__x); }
private:
    _fun_type _M_f;
};

template <class _Tp, class _Arg>
inline mem_fun1_t<_Tp,_Arg> mem_fun(void (_Tp::*__f)(_Arg))
{
    return mem_fun1_t<_Tp,_Arg>(__f);
}

//.........................................................................
/** output iterator that appends OUStrings into an OUStringBuffer.
 */
class OUStringBufferAppender :
    public ::std::iterator< ::std::output_iterator_tag, void, void, void, void>
{
public:
    typedef OUStringBufferAppender Self;
    typedef ::std::output_iterator_tag iterator_category;
    typedef void value_type;
    typedef void reference;
    typedef void pointer;
    typedef size_t difference_type;

    OUStringBufferAppender(OUStringBuffer & i_rBuffer)
        : m_rBuffer(i_rBuffer) { }
    Self & operator=(OUString const & i_rStr)
    {
        m_rBuffer.append( i_rStr );
        return *this;
    }
    Self & operator*() { return *this; } // so operator= works
    Self & operator++() { return *this; }
    Self & operator++(int) { return *this; }

private:
    OUStringBuffer & m_rBuffer;
};

//.........................................................................
/** algorithm similar to std::copy, but inserts a separator between elements.
 */
template< typename ForwardIter, typename OutputIter, typename T >
OutputIter intersperse(
    ForwardIter start, ForwardIter end, OutputIter out, T const & separator)
{
    if (start != end) {
        *out = *start;
        ++start;
        ++out;
    }

    while (start != end) {
        *out = separator;
        ++out;
        *out = *start;
        ++start;
        ++out;
    }

    return out;
}

//.........................................................................
}
//... namespace comphelper ................................................

#endif // INCLUDED_COMPHELPER_STL_TYPES_HXX

/* vim:set shiftwidth=4 softtabstop=4 expandtab: */
<commit_msg>Remove unused comphelper::UStringMixHash<commit_after>/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */
/*
 * This file is part of the LibreOffice project.
 *
 * This Source Code Form is subject to the terms of the Mozilla Public
 * License, v. 2.0. If a copy of the MPL was not distributed with this
 * file, You can obtain one at http://mozilla.org/MPL/2.0/.
 *
 * This file incorporates work covered by the following license notice:
 *
 *   Licensed to the Apache Software Foundation (ASF) under one or more
 *   contributor license agreements. See the NOTICE file distributed
 *   with this work for additional information regarding copyright
 *   ownership. The ASF licenses this file to you under the Apache
 *   License, Version 2.0 (the "License"); you may not use this file
 *   except in compliance with the License. You may obtain a copy of
 *   the License at http://www.apache.org/licenses/LICENSE-2.0 .
 */
#ifndef INCLUDED_COMPHELPER_STL_TYPES_HXX
#define INCLUDED_COMPHELPER_STL_TYPES_HXX

#include <sal/config.h>

#include <stack>

#include <math.h>
#include <functional>

#include <rtl/ustring.hxx>
#include <rtl/ustrbuf.hxx>
#include <com/sun/star/uno/Reference.hxx>
#include <com/sun/star/beans/PropertyValue.hpp>
#include <com/sun/star/beans/NamedValue.hpp>

//... namespace comphelper ................................................
namespace comphelper
{
//.........................................................................

//========================================================================
// comparison functors

struct UStringMixLess : public ::std::binary_function< OUString, OUString, bool>
{
    bool m_bCaseSensitive;
public:
    UStringMixLess(bool bCaseSensitive = true):m_bCaseSensitive(bCaseSensitive){}
    bool operator() (const OUString& x, const OUString& y) const
    {
        if (m_bCaseSensitive)
            return rtl_ustr_compare(x.getStr(), y.getStr()) < 0 ? true : false;
        else
            return rtl_ustr_compareIgnoreAsciiCase(x.getStr(), y.getStr()) < 0 ? true : false;
    }

    bool isCaseSensitive() const {return m_bCaseSensitive;}
};
//------------------------------------------------------------------------
struct UStringEqual
{
    sal_Bool operator() (const OUString& lhs, const OUString& rhs) const { return lhs.equals( rhs );}
};

//------------------------------------------------------------------------
struct UStringIEqual
{
    sal_Bool operator() (const OUString& lhs, const OUString& rhs) const { return lhs.equalsIgnoreAsciiCase( rhs );}
};

//------------------------------------------------------------------------
class UStringMixEqual
{
    sal_Bool m_bCaseSensitive;

public:
    UStringMixEqual(sal_Bool bCaseSensitive = sal_True):m_bCaseSensitive(bCaseSensitive){}
    sal_Bool operator() (const OUString& lhs, const OUString& rhs) const
    {
        return m_bCaseSensitive ? lhs.equals( rhs ) : lhs.equalsIgnoreAsciiCase( rhs );
    }
    sal_Bool isCaseSensitive() const {return m_bCaseSensitive;}
};
//------------------------------------------------------------------------
class TStringMixEqualFunctor : public ::std::binary_function< OUString,OUString,bool>
{
    sal_Bool m_bCaseSensitive;

public:
    TStringMixEqualFunctor(sal_Bool bCaseSensitive = sal_True)
        :m_bCaseSensitive(bCaseSensitive)
    {}
    bool operator() (const OUString& lhs, const OUString& rhs) const
    {
        return !!(m_bCaseSensitive ? lhs.equals( rhs ) : lhs.equalsIgnoreAsciiCase( rhs ));
    }
    sal_Bool isCaseSensitive() const {return m_bCaseSensitive;}
};
//------------------------------------------------------------------------
class TPropertyValueEqualFunctor : public ::std::binary_function< ::com::sun::star::beans::PropertyValue,OUString,bool>
{
public:
    TPropertyValueEqualFunctor()
    {}
    bool operator() (const ::com::sun::star::beans::PropertyValue& lhs, const OUString& rhs) const
    {
        return !!(lhs.Name == rhs);
    }
};
//------------------------------------------------------------------------
class TNamedValueEqualFunctor : public ::std::binary_function< ::com::sun::star::beans::NamedValue,OUString,bool>
{
public:
    TNamedValueEqualFunctor()
    {}
    bool operator() (const ::com::sun::star::beans::NamedValue& lhs, const OUString& rhs) const
    {
        return !!(lhs.Name == rhs);
    }
};

//=====================================================================
//= OInterfaceCompare
//=====================================================================
/** is stl-compliant structure for comparing Reference< <iface> > instances
*/
template < class IAFCE >
struct OInterfaceCompare
    :public ::std::binary_function  <   ::com::sun::star::uno::Reference< IAFCE >
                                    ,   ::com::sun::star::uno::Reference< IAFCE >
                                    ,   bool
                                    >
{
    bool operator() (const ::com::sun::star::uno::Reference< IAFCE >& lhs, const ::com::sun::star::uno::Reference< IAFCE >& rhs) const
    {
        return lhs.get() < rhs.get();
            // this does not make any sense if you see the semantics of the pointer returned by get:
            // It's a pointer to a point in memory where an interface implementation lies.
            // But for our purpose (provide a reliable less-operator which can be used with the STL), this is
            // sufficient ....
    }
};

template <class _Tp, class _Arg>
class mem_fun1_t : public ::std::binary_function<_Tp*,_Arg,void>
{
    typedef void (_Tp::*_fun_type)(_Arg);
public:
    explicit mem_fun1_t(_fun_type __pf) : _M_f(__pf) {}
    void operator()(_Tp* __p, _Arg __x) const { (__p->*_M_f)(__x); }
private:
    _fun_type _M_f;
};

template <class _Tp, class _Arg>
inline mem_fun1_t<_Tp,_Arg> mem_fun(void (_Tp::*__f)(_Arg))
{
    return mem_fun1_t<_Tp,_Arg>(__f);
}

//.........................................................................
/** output iterator that appends OUStrings into an OUStringBuffer.
 */
class OUStringBufferAppender :
    public ::std::iterator< ::std::output_iterator_tag, void, void, void, void>
{
public:
    typedef OUStringBufferAppender Self;
    typedef ::std::output_iterator_tag iterator_category;
    typedef void value_type;
    typedef void reference;
    typedef void pointer;
    typedef size_t difference_type;

    OUStringBufferAppender(OUStringBuffer & i_rBuffer)
        : m_rBuffer(i_rBuffer) { }
    Self & operator=(OUString const & i_rStr)
    {
        m_rBuffer.append( i_rStr );
        return *this;
    }
    Self & operator*() { return *this; } // so operator= works
    Self & operator++() { return *this; }
    Self & operator++(int) { return *this; }

private:
    OUStringBuffer & m_rBuffer;
};

//.........................................................................
/** algorithm similar to std::copy, but inserts a separator between elements.
 */
template< typename ForwardIter, typename OutputIter, typename T >
OutputIter intersperse(
    ForwardIter start, ForwardIter end, OutputIter out, T const & separator)
{
    if (start != end) {
        *out = *start;
        ++start;
        ++out;
    }

    while (start != end) {
        *out = separator;
        ++out;
        *out = *start;
        ++start;
        ++out;
    }

    return out;
}

//.........................................................................
}
//... namespace comphelper ................................................

#endif // INCLUDED_COMPHELPER_STL_TYPES_HXX

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


<commit_before>// File:      QtxDockWindow.cxx
// Author:    Sergey TELKOV

#include "QtxDockWindow.h"

#include <qlayout.h>
#include <qpixmap.h>
#include <qdockarea.h>
#include <qmainwindow.h>
#include <qapplication.h>

/*!
    Class: QtxDockWindow::Watcher [Internal]
    Descr: Internal object with event filter.
*/

class QtxDockWindow::Watcher : public QObject
{
public:
  Watcher( QtxDockWindow* );

  void           shown( QtxDockWindow* );
  void           hided( QtxDockWindow* );

  virtual bool   eventFilter( QObject*, QEvent* );

protected:
  virtual void   customEvent( QCustomEvent* );

private:
  void           installFilters();

  void           showContainer();
  void           hideContainer();

  void           updateIcon();
  void           updateCaption();
  void           updateVisibility();

private:
  QtxDockWindow* myCont;
  bool           myState;
  bool           myEmpty;
  bool           myVisible;
};

QtxDockWindow::Watcher::Watcher( QtxDockWindow* cont )
: QObject( cont ), myCont( cont ),
myState( true ),
myEmpty( true )
{
  if ( myCont->mainWindow() )
    myState = myCont->mainWindow()->appropriate( myCont );

  myCont->installEventFilter( this );
  myVisible = myCont->isVisibleTo( myCont->parentWidget() );

  installFilters();
}

bool QtxDockWindow::Watcher::eventFilter( QObject* o, QEvent* e )
{
  if ( o == myCont &&
       ( e->type() == QEvent::Show || e->type() == QEvent::ShowToParent ||
         e->type() == QEvent::Hide || e->type() == QEvent::HideToParent ||
         e->type() == QEvent::ChildInserted ) )
    QApplication::postEvent( this, new QCustomEvent( QEvent::User ) );

  if ( o != myCont && e->type() == QEvent::IconChange )
    updateIcon();

  if ( o != myCont && e->type() == QEvent::CaptionChange )
    updateCaption();

  if ( o != myCont &&
       ( e->type() == QEvent::Show || e->type() == QEvent::ShowToParent ||
         e->type() == QEvent::Hide || e->type() == QEvent::HideToParent ||
         e->type() == QEvent::ChildRemoved ) )
    updateVisibility();

  return false;
}

void QtxDockWindow::Watcher::shown( QtxDockWindow* dw )
{
  if ( dw != myCont )
    return;

  myVisible = true;
}

void QtxDockWindow::Watcher::hided( QtxDockWindow* dw )
{
  if ( dw != myCont )
    return;

  myVisible = false;
}

void QtxDockWindow::Watcher::showContainer()
{
  if ( !myCont )
    return;

  QtxDockWindow* cont = myCont;
  myCont = 0;
  cont->show();
  myCont = cont;
}

void QtxDockWindow::Watcher::hideContainer()
{
  if ( !myCont )
    return;

  QtxDockWindow* cont = myCont;
  myCont = 0;
  cont->hide();
  myCont = cont;
}

void QtxDockWindow::Watcher::customEvent( QCustomEvent* e )
{
  installFilters();

  updateIcon();
  updateCaption();
  updateVisibility();
}

void QtxDockWindow::Watcher::installFilters()
{
  if ( !myCont )
    return;

  QBoxLayout* bl = myCont->boxLayout();
  if ( !bl )
    return;

  for ( QLayoutIterator it = bl->iterator(); it.current(); ++it )
  {
    if ( it.current()->widget() )
      it.current()->widget()->installEventFilter( this );
  }
}

void QtxDockWindow::Watcher::updateVisibility()
{
  if ( !myCont )
    return;

  QBoxLayout* bl = myCont->boxLayout();
  if ( !bl )
    return;

  bool vis = false;
  for ( QLayoutIterator it = bl->iterator(); it.current() && !vis; ++it )
    vis = it.current()->widget() && it.current()->widget()->isVisibleTo( myCont );

  QMainWindow* mw = myCont->mainWindow();
  if ( mw && myEmpty == vis )
  {
    myEmpty = !vis;
    if ( !myEmpty )
      mw->setAppropriate( myCont, myState );
    else
    {
      myState = mw->appropriate( myCont );
      mw->setAppropriate( myCont, false );
    }
  }

  vis = !myEmpty && myVisible;
  if ( vis != myCont->isVisibleTo( myCont->parentWidget() ) )
    vis ? showContainer() : hideContainer();
}

void QtxDockWindow::Watcher::updateIcon()
{
  if ( !myCont || !myCont->widget() )
    return;

  const QPixmap* ico = myCont->widget()->icon();
  myCont->setIcon( ico ? *ico : QPixmap() );
}

void QtxDockWindow::Watcher::updateCaption()
{
  if ( myCont && myCont->widget() && !myCont->widget()->caption().isNull() )
    myCont->setCaption( myCont->widget()->caption() );
}

/*!
    Class: QtxDockWindow [Public]
    Descr:
*/

QtxDockWindow::QtxDockWindow( Place p, QWidget* parent, const char* name, WFlags f )
: QDockWindow( p, parent, name, f ),
myWatcher( 0 ),
myStretch( false )
{
}

QtxDockWindow::QtxDockWindow( const bool watch, QWidget* parent, const char* name, WFlags f )
: QDockWindow( InDock, parent, name, f ),
myWatcher( 0 ),
myStretch( false )
{
  if ( watch )
    myWatcher = new Watcher( this );
}

QtxDockWindow::QtxDockWindow( QWidget* parent, const char* name, WFlags f )
: QDockWindow( InDock, parent, name, f ),
myWatcher( 0 ),
myStretch( false )
{
}

QtxDockWindow::~QtxDockWindow()
{
}

void QtxDockWindow::setWidget( QWidget* wid )
{
  if ( wid )
    wid->reparent( this, QPoint( 0, 0 ), wid->isVisibleTo( wid->parentWidget() ) );

  QDockWindow::setWidget( wid );
}

bool QtxDockWindow::isStretchable() const
{
  return myStretch;
}

void QtxDockWindow::setStretchable( const bool on )
{
  if ( myStretch == on )
    return;

  myStretch = on;

  boxLayout()->setStretchFactor( widget(), myStretch ? 1 : 0 );

  if ( myStretch != isHorizontalStretchable() ||
       myStretch != isVerticalStretchable() )
  {
	  if ( orientation() == Horizontal )
	    setHorizontalStretchable( myStretch );
	  else
	    setVerticalStretchable( myStretch );
  }
}

QSize QtxDockWindow::sizeHint() const
{
  QSize sz = QDockWindow::sizeHint();

  if ( place() == InDock && isStretchable() && area() )
  {
    if ( orientation() == Horizontal )
      sz.setWidth( area()->width() );
    else
      sz.setHeight( area()->height() );
  }

  return sz;
}

QSize QtxDockWindow::minimumSizeHint() const
{
  QSize sz = QDockWindow::minimumSizeHint();

  if ( orientation() == Horizontal )
	  sz = QSize( 0, QDockWindow::minimumSizeHint().height() );
  else
    sz = QSize( QDockWindow::minimumSizeHint().width(), 0 );

  if ( place() == InDock && isStretchable() && area() )
  {
    if ( orientation() == Horizontal )
      sz.setWidth( area()->width() );
    else
      sz.setHeight( area()->height() );
  }

  return sz;
}

QMainWindow* QtxDockWindow::mainWindow() const
{
  QMainWindow* mw = 0;

  QWidget* wid = parentWidget();
  while ( !mw && wid )
  {
    if ( wid->inherits( "QMainWindow" ) )
      mw = (QMainWindow*)wid;
    wid = wid->parentWidget();
  }

  return mw;
}

void QtxDockWindow::show()
{
  if ( myWatcher )
    myWatcher->shown( this );

  QDockWindow::show();
}

void QtxDockWindow::hide()
{
  if ( myWatcher )
    myWatcher->hided( this );

  QDockWindow::hide();
}
<commit_msg>Don't allow to show the empty dock window.<commit_after>// File:      QtxDockWindow.cxx
// Author:    Sergey TELKOV

#include "QtxDockWindow.h"

#include <qlayout.h>
#include <qpixmap.h>
#include <qdockarea.h>
#include <qmainwindow.h>
#include <qapplication.h>

/*!
    Class: QtxDockWindow::Watcher [Internal]
    Descr: Internal object with event filter.
*/

class QtxDockWindow::Watcher : public QObject
{
public:
  Watcher( QtxDockWindow* );

  void           shown( QtxDockWindow* );
  void           hided( QtxDockWindow* );

  virtual bool   eventFilter( QObject*, QEvent* );

protected:
  virtual void   customEvent( QCustomEvent* );

private:
  void           installFilters();

  void           showContainer();
  void           hideContainer();

  void           updateIcon();
  void           updateCaption();
  void           updateVisibility();

private:
  QtxDockWindow* myCont;
  bool           myState;
  bool           myEmpty;
  bool           myVisible;
};

QtxDockWindow::Watcher::Watcher( QtxDockWindow* cont )
: QObject( cont ), myCont( cont ),
myState( true ),
myEmpty( true )
{
  if ( myCont->mainWindow() )
    myState = myCont->mainWindow()->appropriate( myCont );

  myCont->installEventFilter( this );
  myVisible = myCont->isVisibleTo( myCont->parentWidget() );

  installFilters();
}

bool QtxDockWindow::Watcher::eventFilter( QObject* o, QEvent* e )
{
  if ( o == myCont &&
       ( e->type() == QEvent::Show || e->type() == QEvent::ShowToParent ||
         e->type() == QEvent::Hide || e->type() == QEvent::HideToParent ||
         e->type() == QEvent::ChildInserted ) )
    QApplication::postEvent( this, new QCustomEvent( QEvent::User ) );

  if ( o != myCont && e->type() == QEvent::IconChange )
    updateIcon();

  if ( o != myCont && e->type() == QEvent::CaptionChange )
    updateCaption();

  if ( ( o != myCont && ( e->type() == QEvent::Hide || e->type() == QEvent::HideToParent ) ) ||
       ( o == myCont && ( e->type() == QEvent::ChildRemoved ) ) ||
       ( e->type() == QEvent::Show || e->type() == QEvent::ShowToParent ) )
    updateVisibility();

  return false;
}

void QtxDockWindow::Watcher::shown( QtxDockWindow* dw )
{
  if ( dw != myCont )
    return;

  myVisible = true;
}

void QtxDockWindow::Watcher::hided( QtxDockWindow* dw )
{
  if ( dw != myCont )
    return;

  myVisible = false;
}

void QtxDockWindow::Watcher::showContainer()
{
  if ( !myCont )
    return;

  QtxDockWindow* cont = myCont;
  myCont = 0;
  cont->show();
  myCont = cont;
}

void QtxDockWindow::Watcher::hideContainer()
{
  if ( !myCont )
    return;

  QtxDockWindow* cont = myCont;
  myCont = 0;
  cont->hide();
  myCont = cont;
}

void QtxDockWindow::Watcher::customEvent( QCustomEvent* e )
{
  installFilters();

  updateIcon();
  updateCaption();
  updateVisibility();
}

void QtxDockWindow::Watcher::installFilters()
{
  if ( !myCont )
    return;

  QBoxLayout* bl = myCont->boxLayout();
  if ( !bl )
    return;

  for ( QLayoutIterator it = bl->iterator(); it.current(); ++it )
  {
    if ( it.current()->widget() )
      it.current()->widget()->installEventFilter( this );
  }
}

void QtxDockWindow::Watcher::updateVisibility()
{
  if ( !myCont )
    return;

  QBoxLayout* bl = myCont->boxLayout();
  if ( !bl )
    return;

  bool vis = false;
  for ( QLayoutIterator it = bl->iterator(); it.current() && !vis; ++it )
    vis = it.current()->widget() && it.current()->widget()->isVisibleTo( myCont );

  QMainWindow* mw = myCont->mainWindow();
  if ( mw && myEmpty == vis )
  {
    myEmpty = !vis;
    if ( !myEmpty )
      mw->setAppropriate( myCont, myState );
    else
    {
      myState = mw->appropriate( myCont );
      mw->setAppropriate( myCont, false );
    }
  }

  vis = !myEmpty && myVisible;
  if ( vis != myCont->isVisibleTo( myCont->parentWidget() ) )
    vis ? showContainer() : hideContainer();
}

void QtxDockWindow::Watcher::updateIcon()
{
  if ( !myCont || !myCont->widget() )
    return;

  const QPixmap* ico = myCont->widget()->icon();
  myCont->setIcon( ico ? *ico : QPixmap() );
}

void QtxDockWindow::Watcher::updateCaption()
{
  if ( myCont && myCont->widget() && !myCont->widget()->caption().isNull() )
    myCont->setCaption( myCont->widget()->caption() );
}

/*!
    Class: QtxDockWindow [Public]
    Descr:
*/

QtxDockWindow::QtxDockWindow( Place p, QWidget* parent, const char* name, WFlags f )
: QDockWindow( p, parent, name, f ),
myWatcher( 0 ),
myStretch( false )
{
}

QtxDockWindow::QtxDockWindow( const bool watch, QWidget* parent, const char* name, WFlags f )
: QDockWindow( InDock, parent, name, f ),
myWatcher( 0 ),
myStretch( false )
{
  if ( watch )
    myWatcher = new Watcher( this );
}

QtxDockWindow::QtxDockWindow( QWidget* parent, const char* name, WFlags f )
: QDockWindow( InDock, parent, name, f ),
myWatcher( 0 ),
myStretch( false )
{
}

QtxDockWindow::~QtxDockWindow()
{
}

void QtxDockWindow::setWidget( QWidget* wid )
{
  if ( wid )
    wid->reparent( this, QPoint( 0, 0 ), wid->isVisibleTo( wid->parentWidget() ) );

  QDockWindow::setWidget( wid );
}

bool QtxDockWindow::isStretchable() const
{
  return myStretch;
}

void QtxDockWindow::setStretchable( const bool on )
{
  if ( myStretch == on )
    return;

  myStretch = on;

  boxLayout()->setStretchFactor( widget(), myStretch ? 1 : 0 );

  if ( myStretch != isHorizontalStretchable() ||
       myStretch != isVerticalStretchable() )
  {
	  if ( orientation() == Horizontal )
	    setHorizontalStretchable( myStretch );
	  else
	    setVerticalStretchable( myStretch );
  }
}

QSize QtxDockWindow::sizeHint() const
{
  QSize sz = QDockWindow::sizeHint();

  if ( place() == InDock && isStretchable() && area() )
  {
    if ( orientation() == Horizontal )
      sz.setWidth( area()->width() );
    else
      sz.setHeight( area()->height() );
  }

  return sz;
}

QSize QtxDockWindow::minimumSizeHint() const
{
  QSize sz = QDockWindow::minimumSizeHint();

  if ( orientation() == Horizontal )
	  sz = QSize( 0, QDockWindow::minimumSizeHint().height() );
  else
    sz = QSize( QDockWindow::minimumSizeHint().width(), 0 );

  if ( place() == InDock && isStretchable() && area() )
  {
    if ( orientation() == Horizontal )
      sz.setWidth( area()->width() );
    else
      sz.setHeight( area()->height() );
  }

  return sz;
}

QMainWindow* QtxDockWindow::mainWindow() const
{
  QMainWindow* mw = 0;

  QWidget* wid = parentWidget();
  while ( !mw && wid )
  {
    if ( wid->inherits( "QMainWindow" ) )
      mw = (QMainWindow*)wid;
    wid = wid->parentWidget();
  }

  return mw;
}

void QtxDockWindow::show()
{
  if ( myWatcher )
    myWatcher->shown( this );

  QDockWindow::show();
}

void QtxDockWindow::hide()
{
  if ( myWatcher )
    myWatcher->hided( this );

  QDockWindow::hide();
}
<|endoftext|>