<commit_before>/*************************************************************************
 *
 *  $RCSfile: ScriptNameResolverImpl.cxx,v $
 *
 *  $Revision: 1.8 $
 *
 *  last change: $Author: dfoster $ $Date: 2002-10-24 13:57:02 $
 *
 *  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): _______________________________________
 *
 *
 ************************************************************************/

#include <vector>

#include <cppuhelper/implementationentry.hxx>
#include <com/sun/star/beans/XPropertySet.hpp>

#include <util/util.hxx>
#include <util/scriptingconstants.hxx>

#include "ScriptNameResolverImpl.hxx"
#include "ScriptRuntimeManager.hxx"

using namespace ::rtl;
using namespace ::com::sun::star;
using namespace ::com::sun::star::uno;
using namespace ::drafts::com::sun::star::script::framework;

namespace scripting_runtimemgr
{

const sal_Char* const LANGUAGE_TO_RESOLVE_ON = "Java"; // should be configurable
OUString nrs_implName = OUString::createFromAscii(
    "drafts.com.sun.star.script.framework.DefaultScriptNameResolver" );
OUString nrs_serviceName = OUString::createFromAscii(
    "drafts.com.sun.star.script.framework.DefaultScriptNameResolver" );
Sequence< OUString > nrs_serviceNames = Sequence< OUString >( &nrs_serviceName, 1 );

extern ::rtl_StandardModuleCount s_moduleCount;

// define storages to search
static ::std::vector< sal_Int32 >* m_pSearchIDs = NULL;

//*************************************************************************
ScriptNameResolverImpl::ScriptNameResolverImpl(
    const Reference< XComponentContext > & xContext ) :
    m_xContext( xContext ), m_StorageFactory( xContext )
{
    OSL_TRACE( "< ScriptNameResolverImpl ctor called >\n" );
    if( !m_pSearchIDs )
    {
        osl::Guard< osl::Mutex > aGuard( m_mutex );
        if( !m_pSearchIDs )
        {
            scripting_constants::ScriptingConstantsPool& scriptingConstantsPool =
                scripting_constants::ScriptingConstantsPool::instance();
            m_pSearchIDs = new ::std::vector< sal_Int32 >();
            m_pSearchIDs->push_back( scriptingConstantsPool.DOC_STORAGE_ID_NOT_SET );
            m_pSearchIDs->push_back( scriptingConstantsPool.USER_STORAGE_ID );
            m_pSearchIDs->push_back( scriptingConstantsPool.SHARED_STORAGE_ID );
        }
    }

    s_moduleCount.modCnt.acquire( &s_moduleCount.modCnt );
}

//*************************************************************************
ScriptNameResolverImpl::~ScriptNameResolverImpl()
{
    OSL_TRACE( "< ScriptNameResolverImpl dtor called >\n" );
    s_moduleCount.modCnt.release( &s_moduleCount.modCnt );
}

//*************************************************************************
Reference< XInterface > ScriptNameResolverImpl::resolve(
const ::rtl::OUString & scriptURI, Any& invocationCtx )
throw ( lang::IllegalArgumentException, script::CannotConvertException, RuntimeException )
{

    Reference< XInterface > resolvedName;
    Reference< beans::XPropertySet > xPropSetScriptingContext;
    OSL_TRACE( "ScriptNameResolverImpl::resolve: in resolve - start" );

    if ( sal_False == ( invocationCtx >>= xPropSetScriptingContext ) )
    {
        throw RuntimeException( OUSTR(
            "ScriptNameResolverImpl::resolve : unable to get XScriptingContext from param" ),
            Reference< XInterface > () );
    }

    Any any;
    OUString docUri;
    sal_Int32 docSid;
    try
    {
        scripting_constants::ScriptingConstantsPool& scriptingConstantsPool =
            scripting_constants::ScriptingConstantsPool::instance();
        any = xPropSetScriptingContext->getPropertyValue(
            scriptingConstantsPool.DOC_URI );
        OSL_TRACE( "ScriptNameResolverImpl::resolve: in resolve - got anyUri" );
        if ( sal_False == ( any >>= docUri ) )
        {
            throw RuntimeException( OUSTR(
            "ScriptNameResolverImpl::resolve : unable to get doc Uri from xPropSetScriptingContext" ),
                Reference< XInterface > () );
        }
        any = xPropSetScriptingContext->getPropertyValue(
            scriptingConstantsPool.DOC_STORAGE_ID );
        if ( sal_False == ( any >>= docSid ) )
        {
            throw RuntimeException( OUSTR(
                "ScriptNameResolverImpl::resolve : unable to get doc storage id from xPropSetScriptingContext" ),
                Reference< XInterface > () );
        }
    }
    catch ( Exception & e )
    {
        OUString temp = OUSTR(
            "ScriptNameResolverImpl::resolve : problem with getPropertyValue" );
        throw RuntimeException( temp.concat( e.Message ),
                                Reference< XInterface > () );
    }
#ifdef _DEBUG
    catch ( ... )
    {
        throw RuntimeException( OUSTR(
            "ScriptNameResolverImpl::resolve Unknown Exception caught - RuntimeException rethrown" ),
            Reference< XInterface > () );
    }
#endif

#ifdef _DEBUG
    ::rtl::OString docUriO(
        ::rtl::OUStringToOString( docUri , RTL_TEXTENCODING_ASCII_US ) );
    fprintf( stderr,
        "ScriptNameResolverImpl::resolve: *** >>> DOC URI: %s, doc sid is %d\n",
        docUriO.pData->buffer, docSid );
#endif

    OSL_TRACE( "ScriptNameResolverImpl::resolve Starting..." );
    ::std::vector< sal_Int32 >& m_vSearchIDs = *m_pSearchIDs;
    m_vSearchIDs[ 0 ] = docSid;
    ::std::vector< sal_Int32 >::const_iterator iter;
    ::std::vector< sal_Int32 >::const_iterator iterEnd = m_vSearchIDs.end();

    for ( iter = m_vSearchIDs.begin() ; iter != iterEnd; ++iter )
    {
        try
        {
            OSL_TRACE( "** about to resolve from storage using id %d from vector of size %d",
                *iter, m_vSearchIDs.size() );
            if ( ( resolvedName = resolveURIFromStorageID( *iter, scriptURI ) ).is() )
            {
                OSL_TRACE( "found match in uri from storage %d", *iter );
                break;
            }

        }

        catch ( Exception & e )
        {
            OSL_TRACE( "Exception thrown by storage %d, failed to match uri: %s",
                *iter,
                ::rtl::OUStringToOString( e.Message,
                    RTL_TEXTENCODING_ASCII_US ).pData->buffer );
        }
#ifdef _DEBUG
        catch ( ... )
        {
            OSL_TRACE( "unknown exception thrown by storage %d, failed to match uri",
                *iter );
        }
#endif

    }

    return resolvedName;
}

//*************************************************************************
OUString SAL_CALL
ScriptNameResolverImpl::getImplementationName( )
throw( RuntimeException )
{
    return nrs_implName;
}

//*************************************************************************
sal_Bool SAL_CALL
ScriptNameResolverImpl::supportsService( const OUString& serviceName )
throw( RuntimeException )
{
    OUString const * pNames = nrs_serviceNames.getConstArray();
    for ( sal_Int32 nPos = nrs_serviceNames.getLength(); nPos--; )
    {
        if ( serviceName.equals( pNames[ nPos ] ) )
        {
            return sal_True;
        }
    }
    return sal_False;
}

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

Reference< XInterface >
ScriptNameResolverImpl::resolveURIFromStorageID
( sal_Int32 sid, const ::rtl::OUString& scriptURI )
SAL_THROW ( ( lang::IllegalArgumentException, RuntimeException ) )
{
    Reference< XInterface > resolvedName;
    scripting_constants::ScriptingConstantsPool& scriptingConstantsPool =
        scripting_constants::ScriptingConstantsPool::instance();
    if ( sid == scriptingConstantsPool.DOC_STORAGE_ID_NOT_SET )
    {
        OSL_TRACE( "@@@@ **** ScriptNameResolverImpl::resolve DOC_STORAGE_ID_NOT_SET" );
        return resolvedName;
    }
    try
    {
        Reference< storage::XScriptInfoAccess > storage =
            m_StorageFactory.getStorageInstance( sid );
        validateXRef( storage,
        "ScriptNameResolverImpl::resolveURIFromStorageID: cannot get XScriptInfoAccess" );
        Sequence< Reference< storage::XScriptInfo > > results =
            storage->getImplementations( scriptURI );

        const sal_Int32 length = results.getLength();

        if ( !length )
        {
            return resolvedName;
        }

        OSL_TRACE( "ScriptNameResolverImpl::resolve Got some results..." );
        for ( sal_Int32 index = 0;index < length;index++ )
        {
            Reference< storage::XScriptInfo > uri = results[ index ];
#ifdef _DEBUG

            ::rtl::OString locationO( ::rtl::OUStringToOString( uri->getScriptLocation(),
                RTL_TEXTENCODING_ASCII_US ) );
            ::rtl::OString languageO( ::rtl::OUStringToOString( uri->getLanguage(),
                RTL_TEXTENCODING_ASCII_US ) );
            ::rtl::OString functionName( ::rtl::OUStringToOString( uri->getFunctionName(),
                RTL_TEXTENCODING_ASCII_US ) );
            ::rtl::OString logicalName( ::rtl::OUStringToOString( uri->getLogicalName(),
                RTL_TEXTENCODING_ASCII_US ) );
            fprintf( stderr, "[%d] URI, {location = %s}, {language = %s}, {funtionName = %s}, {logicalName = %s}\n",
                     index, locationO.pData->buffer, languageO.pData->buffer,
                     functionName.pData->buffer, logicalName.pData->buffer );
#endif

            // just choose first one that has language=LANGUAGE_TO_RESOLVE_ON
            ::rtl::OUString language( uri->getLanguage() );

            if ( ( language.compareToAscii( LANGUAGE_TO_RESOLVE_ON ) == 0 ) )
            {
                OSL_TRACE( "Found desired language\n" );
                resolvedName = uri;
                break;
            }
        }
    }
    catch ( lang::IllegalArgumentException & iae )
    {
        OUString temp = OUSTR(
            "ScriptRuntimeManager::resolveURIFromStorageID IllegalArgumentException: " );
        throw lang::IllegalArgumentException( temp.concat( iae.Message ),
                                              Reference< XInterface > (),
                                              iae.ArgumentPosition );
    }
    catch ( RuntimeException & re )
    {
        OUString temp = OUSTR(
            "ScriptRuntimeManager::resolveURIFromStorageID RuntimeException: " );
        throw RuntimeException( temp.concat( re.Message ),
                                Reference< XInterface > () );
    }
    catch ( Exception & e )
    {
        OUString temp = OUSTR(
            "ScriptNameResolverImpl::resolveURIFromStorageID : Exception caught - RuntimeException rethrown" );
        throw RuntimeException( temp.concat( e.Message ),
                                Reference< XInterface > () );
    }
#ifdef _DEBUG
    catch ( ... )
    {
        throw RuntimeException( OUSTR(
            "ScriptNameResolverImpl::resolveURIFromStorageID Unknown exception caught - RuntimeException rethrown" ),
            Reference< XInterface > () );
    }
#endif
    return resolvedName;
}
//*************************************************************************
Sequence<OUString> SAL_CALL
ScriptNameResolverImpl::getSupportedServiceNames( )
throw( RuntimeException )
{
    return nrs_serviceNames;
}

//*************************************************************************
Reference< XInterface > SAL_CALL scriptnri_create(
    Reference< XComponentContext > const & xComponentContext )
SAL_THROW( ( Exception ) )
{
    return ( cppu::OWeakObject * ) new ScriptNameResolverImpl( xComponentContext );
}

//*************************************************************************
Sequence< OUString > scriptnri_getSupportedServiceNames() SAL_THROW( () )
{
    return nrs_serviceNames;
}

//*************************************************************************
OUString scriptnri_getImplementationName() SAL_THROW( () )
{
    return nrs_implName;
}
} // namespace scripting_runtimemgr
<commit_msg>resolved storage ID set on resolved context<commit_after>/*************************************************************************
 *
 *  $RCSfile: ScriptNameResolverImpl.cxx,v $
 *
 *  $Revision: 1.9 $
 *
 *  last change: $Author: lkovacs $ $Date: 2002-10-30 14:25:26 $
 *
 *  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): _______________________________________
 *
 *
 ************************************************************************/

#include <vector>

#include <cppuhelper/implementationentry.hxx>
#include <com/sun/star/beans/XPropertySet.hpp>

#include <util/util.hxx>
#include <util/scriptingconstants.hxx>

#include "ScriptNameResolverImpl.hxx"
#include "ScriptRuntimeManager.hxx"

using namespace ::rtl;
using namespace ::com::sun::star;
using namespace ::com::sun::star::uno;
using namespace ::drafts::com::sun::star::script::framework;

namespace scripting_runtimemgr
{

const sal_Char* const LANGUAGE_TO_RESOLVE_ON = "Java"; // should be configurable
OUString nrs_implName = OUString::createFromAscii(
    "drafts.com.sun.star.script.framework.DefaultScriptNameResolver" );
OUString nrs_serviceName = OUString::createFromAscii(
    "drafts.com.sun.star.script.framework.DefaultScriptNameResolver" );
Sequence< OUString > nrs_serviceNames = Sequence< OUString >( &nrs_serviceName, 1 );

extern ::rtl_StandardModuleCount s_moduleCount;

// define storages to search
static ::std::vector< sal_Int32 >* m_pSearchIDs = NULL;

//*************************************************************************
ScriptNameResolverImpl::ScriptNameResolverImpl(
    const Reference< XComponentContext > & xContext ) :
    m_xContext( xContext ), m_StorageFactory( xContext )
{
    OSL_TRACE( "< ScriptNameResolverImpl ctor called >\n" );
    if( !m_pSearchIDs )
    {
        osl::Guard< osl::Mutex > aGuard( m_mutex );
        if( !m_pSearchIDs )
        {
            scripting_constants::ScriptingConstantsPool& scriptingConstantsPool =
                scripting_constants::ScriptingConstantsPool::instance();
            m_pSearchIDs = new ::std::vector< sal_Int32 >();
            m_pSearchIDs->push_back( scriptingConstantsPool.DOC_STORAGE_ID_NOT_SET );
            m_pSearchIDs->push_back( scriptingConstantsPool.USER_STORAGE_ID );
            m_pSearchIDs->push_back( scriptingConstantsPool.SHARED_STORAGE_ID );
        }
    }

    s_moduleCount.modCnt.acquire( &s_moduleCount.modCnt );
}

//*************************************************************************
ScriptNameResolverImpl::~ScriptNameResolverImpl()
{
    OSL_TRACE( "< ScriptNameResolverImpl dtor called >\n" );
    s_moduleCount.modCnt.release( &s_moduleCount.modCnt );
}

//*************************************************************************
Reference< XInterface > ScriptNameResolverImpl::resolve(
const ::rtl::OUString & scriptURI, Any& invocationCtx )
throw ( lang::IllegalArgumentException, script::CannotConvertException, RuntimeException )
{

    Reference< XInterface > resolvedName;
    Reference< beans::XPropertySet > xPropSetScriptingContext;
    scripting_constants::ScriptingConstantsPool& scriptingConstantsPool =
            scripting_constants::ScriptingConstantsPool::instance();

    OSL_TRACE( "ScriptNameResolverImpl::resolve: in resolve - start" );

    if ( sal_False == ( invocationCtx >>= xPropSetScriptingContext ) )
    {
        throw RuntimeException( OUSTR(
            "ScriptNameResolverImpl::resolve : unable to get XScriptingContext from param" ),
            Reference< XInterface > () );
    }

    Any any;
    OUString docUri;
    sal_Int32 docSid;
    try
    {
        any = xPropSetScriptingContext->getPropertyValue(
            scriptingConstantsPool.DOC_URI );
        OSL_TRACE( "ScriptNameResolverImpl::resolve: in resolve - got anyUri" );
        if ( sal_False == ( any >>= docUri ) )
        {
            throw RuntimeException( OUSTR(
            "ScriptNameResolverImpl::resolve : unable to get doc Uri from xPropSetScriptingContext" ),
                Reference< XInterface > () );
        }
        any = xPropSetScriptingContext->getPropertyValue(
            scriptingConstantsPool.DOC_STORAGE_ID );
        if ( sal_False == ( any >>= docSid ) )
        {
            throw RuntimeException( OUSTR(
                "ScriptNameResolverImpl::resolve : unable to get doc storage id from xPropSetScriptingContext" ),
                Reference< XInterface > () );
        }
    }
    catch ( Exception & e )
    {
        OUString temp = OUSTR(
            "ScriptNameResolverImpl::resolve : problem with getPropertyValue" );
        throw RuntimeException( temp.concat( e.Message ),
                                Reference< XInterface > () );
    }
#ifdef _DEBUG
    catch ( ... )
    {
        throw RuntimeException( OUSTR(
            "ScriptNameResolverImpl::resolve Unknown Exception caught - RuntimeException rethrown" ),
            Reference< XInterface > () );
    }
#endif

#ifdef _DEBUG
    ::rtl::OString docUriO(
        ::rtl::OUStringToOString( docUri , RTL_TEXTENCODING_ASCII_US ) );
    fprintf( stderr,
        "ScriptNameResolverImpl::resolve: *** >>> DOC URI: %s, doc sid is %d\n",
        docUriO.pData->buffer, docSid );
#endif

    OSL_TRACE( "ScriptNameResolverImpl::resolve Starting..." );
    ::std::vector< sal_Int32 >& m_vSearchIDs = *m_pSearchIDs;
    m_vSearchIDs[ 0 ] = docSid;
    ::std::vector< sal_Int32 >::const_iterator iter;
    ::std::vector< sal_Int32 >::const_iterator iterEnd = m_vSearchIDs.end();

    for ( iter = m_vSearchIDs.begin() ; iter != iterEnd; ++iter )
    {
        try
        {
            OSL_TRACE( "** about to resolve from storage using id %d from vector of size %d",
                *iter, m_vSearchIDs.size() );
            if ( ( resolvedName = resolveURIFromStorageID( *iter, scriptURI ) ).is() )
            {
                OSL_TRACE( "found match in uri from storage %d", *iter );
            xPropSetScriptingContext->setPropertyValue(
                scriptingConstantsPool.RESOLVED_STORAGE_ID, makeAny(*iter) );
                break;
            }

        }
    catch ( beans::UnknownPropertyException & e )
        {
            OUString temp = OUSTR(
                "ScriptNameResolverImpl::resolve : UnknownPropertyException" );
            throw RuntimeException( temp.concat( e.Message ),
                                Reference< XInterface > () );
        }
    catch ( beans::PropertyVetoException  & e )
        {
            OUString temp = OUSTR(
                "ScriptNameResolverImpl::resolve : PropertyVetoException " );
            throw RuntimeException( temp.concat( e.Message ),
                                Reference< XInterface > () );
        }
    catch ( lang::IllegalArgumentException  & e )
        {
            OUString temp = OUSTR(
                "ScriptNameResolverImpl::resolve : IllegalArgumentException " );
            throw RuntimeException( temp.concat( e.Message ),
                                Reference< XInterface > () );
        }
    catch ( lang::WrappedTargetException & e )
        {
        OUString temp = OUSTR(
                "ScriptNameResolverImpl::resolve : WrappedTargetException " );
            throw RuntimeException( temp.concat( e.Message ),
                                Reference< XInterface > () );
        }
        catch ( Exception & e )
        {
            OSL_TRACE( "Exception thrown by storage %d, failed to match uri: %s",
                *iter,
                ::rtl::OUStringToOString( e.Message,
                    RTL_TEXTENCODING_ASCII_US ).pData->buffer );
        OUString temp = OUSTR(
                "ScriptNameResolverImpl::resolve : unknown exception" );
            throw RuntimeException( temp.concat( e.Message ),
                                Reference< XInterface > () );
        }
#ifdef _DEBUG
        catch ( ... )
        {
            OSL_TRACE( "unknown exception thrown by storage %d, failed to match uri",
                *iter );
        OUString temp = OUSTR(
                "ScriptNameResolverImpl::resolve Unknown exception caught - RuntimeException rethrown" );
            throw RuntimeException( temp,
                                Reference< XInterface > () );
        }
#endif

    }

    return resolvedName;
}

//*************************************************************************
OUString SAL_CALL
ScriptNameResolverImpl::getImplementationName( )
throw( RuntimeException )
{
    return nrs_implName;
}

//*************************************************************************
sal_Bool SAL_CALL
ScriptNameResolverImpl::supportsService( const OUString& serviceName )
throw( RuntimeException )
{
    OUString const * pNames = nrs_serviceNames.getConstArray();
    for ( sal_Int32 nPos = nrs_serviceNames.getLength(); nPos--; )
    {
        if ( serviceName.equals( pNames[ nPos ] ) )
        {
            return sal_True;
        }
    }
    return sal_False;
}

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

Reference< XInterface >
ScriptNameResolverImpl::resolveURIFromStorageID
( sal_Int32 sid, const ::rtl::OUString& scriptURI )
SAL_THROW ( ( lang::IllegalArgumentException, RuntimeException ) )
{
    Reference< XInterface > resolvedName;
    scripting_constants::ScriptingConstantsPool& scriptingConstantsPool =
        scripting_constants::ScriptingConstantsPool::instance();
    if ( sid == scriptingConstantsPool.DOC_STORAGE_ID_NOT_SET )
    {
        OSL_TRACE( "@@@@ **** ScriptNameResolverImpl::resolve DOC_STORAGE_ID_NOT_SET" );
        return resolvedName;
    }
    try
    {
        Reference< storage::XScriptInfoAccess > storage =
            m_StorageFactory.getStorageInstance( sid );
        validateXRef( storage,
        "ScriptNameResolverImpl::resolveURIFromStorageID: cannot get XScriptInfoAccess" );
        Sequence< Reference< storage::XScriptInfo > > results =
            storage->getImplementations( scriptURI );

        const sal_Int32 length = results.getLength();

        if ( !length )
        {
            return resolvedName;
        }

        OSL_TRACE( "ScriptNameResolverImpl::resolve Got some results..." );
        for ( sal_Int32 index = 0;index < length;index++ )
        {
            Reference< storage::XScriptInfo > uri = results[ index ];
#ifdef _DEBUG

            ::rtl::OString locationO( ::rtl::OUStringToOString( uri->getScriptLocation(),
                RTL_TEXTENCODING_ASCII_US ) );
            ::rtl::OString languageO( ::rtl::OUStringToOString( uri->getLanguage(),
                RTL_TEXTENCODING_ASCII_US ) );
            ::rtl::OString functionName( ::rtl::OUStringToOString( uri->getFunctionName(),
                RTL_TEXTENCODING_ASCII_US ) );
            ::rtl::OString logicalName( ::rtl::OUStringToOString( uri->getLogicalName(),
                RTL_TEXTENCODING_ASCII_US ) );
            fprintf( stderr, "[%d] URI, {location = %s}, {language = %s}, {funtionName = %s}, {logicalName = %s}\n",
                     index, locationO.pData->buffer, languageO.pData->buffer,
                     functionName.pData->buffer, logicalName.pData->buffer );
#endif

            // just choose first one that has language=LANGUAGE_TO_RESOLVE_ON
            ::rtl::OUString language( uri->getLanguage() );

            if ( ( language.compareToAscii( LANGUAGE_TO_RESOLVE_ON ) == 0 ) )
            {
                OSL_TRACE( "Found desired language\n" );
                resolvedName = uri;
                break;
            }
        }
    }
    catch ( lang::IllegalArgumentException & iae )
    {
        OUString temp = OUSTR(
            "ScriptRuntimeManager::resolveURIFromStorageID IllegalArgumentException: " );
        throw lang::IllegalArgumentException( temp.concat( iae.Message ),
                                              Reference< XInterface > (),
                                              iae.ArgumentPosition );
    }
    catch ( RuntimeException & re )
    {
        OUString temp = OUSTR(
            "ScriptRuntimeManager::resolveURIFromStorageID RuntimeException: " );
        throw RuntimeException( temp.concat( re.Message ),
                                Reference< XInterface > () );
    }
    catch ( Exception & e )
    {
        OUString temp = OUSTR(
            "ScriptNameResolverImpl::resolveURIFromStorageID : Exception caught - RuntimeException rethrown" );
        throw RuntimeException( temp.concat( e.Message ),
                                Reference< XInterface > () );
    }
#ifdef _DEBUG
    catch ( ... )
    {
        throw RuntimeException( OUSTR(
            "ScriptNameResolverImpl::resolveURIFromStorageID Unknown exception caught - RuntimeException rethrown" ),
            Reference< XInterface > () );
    }
#endif
    return resolvedName;
}
//*************************************************************************
Sequence<OUString> SAL_CALL
ScriptNameResolverImpl::getSupportedServiceNames( )
throw( RuntimeException )
{
    return nrs_serviceNames;
}

//*************************************************************************
Reference< XInterface > SAL_CALL scriptnri_create(
    Reference< XComponentContext > const & xComponentContext )
SAL_THROW( ( Exception ) )
{
    return ( cppu::OWeakObject * ) new ScriptNameResolverImpl( xComponentContext );
}

//*************************************************************************
Sequence< OUString > scriptnri_getSupportedServiceNames() SAL_THROW( () )
{
    return nrs_serviceNames;
}

//*************************************************************************
OUString scriptnri_getImplementationName() SAL_THROW( () )
{
    return nrs_implName;
}
} // namespace scripting_runtimemgr
<|endoftext|>


<commit_before><commit_msg>Fixed userlevel check on parameter observation.<commit_after><|endoftext|>


<commit_before>/*
 * Copyright 2016 neurodata (http://neurodata.io/)
 * Written by Disa Mhembere (disa@jhu.edu)
 *
 * This file is part of knor
 *
 * 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 CURRENT_KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

#include <cassert>

#include "io.hpp"
#include "util.hpp"
#include "clusters.hpp"

namespace knor { namespace base {
void clusters::clear() {
    std::fill(means.begin(), means.end(), 0);
    std::fill(num_members_v.begin(), num_members_v.end(), 0);
    std::fill(complete_v.begin(), complete_v.end(), false);
}

/** \param idx the cluster index.
*/
void clusters::set_mean(const kmsvector& mean, const int idx) {
    if (idx == -1) { // Set all means
        means = mean;
    } else {
        std::copy(mean.begin(), mean.end(),
                this->means.begin()+(idx*ncol));
    }
}

void clusters::set_mean(const double* mean, const int idx) {
    if (idx == -1) { // Set all means
        if (means.size() != (ncol*nclust))
            means.resize(ncol*nclust);
        std::copy(&(mean[0]), &(mean[ncol*nclust]), this->means.begin());
    } else {
        std::copy(&(mean[0]), &(mean[ncol]), this->means.begin()+(idx*ncol));
    }
}

void clusters::finalize(const unsigned idx) {
    if (is_complete(idx)) {
        return;
    }

    if (num_members_v[idx] > 1) { // Less than 2 is the same result
        for (unsigned i = 0; i < ncol; i++) {
            means[(idx*ncol)+i] /= double(num_members_v[idx]);
        }
    }
    complete_v[idx] = true;
}

void clusters::unfinalize(const unsigned idx) {
    if (!is_complete(idx)) {
        return;
    }
    complete_v[idx] = false;

    for (unsigned col = 0; col < ncol; col++) {
        this->means[(ncol*idx) + col] *= (double)num_members_v[idx];
    }
}

void clusters::finalize_all() {
    for (unsigned c = 0;  c < get_nclust(); c++)
        finalize(c);
}

void clusters::unfinalize_all() {
    for (unsigned c = 0;  c < get_nclust(); c++)
        unfinalize(c);
}

void clusters::set_num_members_v(const size_t* arg) {
    std::copy(&(arg[0]), &(arg[nclust]), num_members_v.begin());
}

clusters& clusters::operator=(clusters& other) {
    this->means = other.get_means();
    this->num_members_v = other.get_num_members_v();
    this->ncol = other.get_ncol();
    this->nclust = other.get_nclust();
    return *this;
}

bool clusters::operator==(clusters& other) {
    return (get_ncol() == other.get_ncol() &&
            get_nclust() == other.get_nclust() &&
            v_eq(get_num_members_v(), other.get_num_members_v()) &&
            v_eq(get_means(), other.get_means())
           );
}

clusters& clusters::operator+=(clusters& rhs) {
    for (unsigned i = 0; i < size(); i++)
        this->means[i] += rhs[i];

    for (unsigned idx = 0; idx < nclust; idx++)
        num_members_peq(rhs.get_num_members(idx), idx);
    return *this;
}

void clusters::peq(ptr rhs) {
    assert(rhs->size() == size());
    for (unsigned i = 0; i < size(); i++)
        this->means[i] += rhs->get(i);

    for (unsigned idx = 0; idx < nclust; idx++)
        num_members_peq(rhs->get_num_members(idx), idx);
}

void clusters::means_peq(const double* other) {
    for (unsigned i = 0; i < size(); i++)
        this->means[i] += other[i];
}

void clusters::num_members_v_peq(const size_t* other) {
    for (unsigned i = 0; i < num_members_v.size(); i++)
        this->num_members_v[i] += other[i];
}

// Begin Helpers //
const void clusters::print_means() const {
    for (unsigned cl_idx = 0; cl_idx < get_nclust(); cl_idx++) {
#ifndef BIND
        std::cout << "#memb = " << get_num_members(cl_idx) << " ";
#endif
        print_arr<double>(&(means[cl_idx*ncol]), ncol);
    }
#ifndef BIND
    std::cout << "\n";
#endif
}

clusters::clusters(const unsigned nclust, const unsigned ncol) {
    this->nclust = nclust;
    this->ncol = ncol;

    means.resize(ncol*nclust);
    num_members_v.resize(nclust);
    complete_v.assign(nclust, false);
}

clusters::clusters(const unsigned nclust, const unsigned ncol,
        const double* means) {
    this->nclust = nclust;
    this->ncol = ncol;

    set_mean(means);
    num_members_v.resize(nclust);
    complete_v.assign(nclust, true);
}

clusters::clusters(const unsigned nclust, const unsigned ncol,
        const kmsvector& means) : clusters(nclust, ncol, &means[0]) {
}

const void clusters::print_membership_count() const {
    std::string p = "[ ";
    for (unsigned cl_idx = 0; cl_idx < get_nclust(); cl_idx++) {
        p += std::to_string(get_num_members(cl_idx)) + " ";
    }
    p += "]\n";
#ifndef BIND
    std::cout << p;
#endif
}

void clusters::scale_centroid(const double factor,
        const unsigned idx, const double* member) {
    assert(idx < nclust);
    for (unsigned col = 0; col < ncol; col++) {
        means[(ncol*idx)+col] = ((1-factor)*means[(idx*ncol)+col])
            + (factor*(member[col]));
    }
}

// Pruning clusters //
void prune_clusters::reset_s_val_v() {
    std::fill(s_val_v.begin(), s_val_v.end(),
            std::numeric_limits<double>::max());
}

const void prune_clusters::print_prev_means_v() const {
    for (unsigned cl_idx = 0; cl_idx < get_nclust(); cl_idx++) {
        print_arr<double>(&(prev_means[cl_idx*ncol]), ncol);
    }
#ifndef BIND
    std::cout << "\n";
#endif
}
} } // End namespace knor, base
<commit_msg>clusters debugging<commit_after>/*
 * Copyright 2016 neurodata (http://neurodata.io/)
 * Written by Disa Mhembere (disa@jhu.edu)
 *
 * This file is part of knor
 *
 * 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 CURRENT_KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

#include <cassert>

#include "io.hpp"
#include "util.hpp"
#include "clusters.hpp"

namespace knor { namespace base {
void clusters::clear() {
    std::fill(means.begin(), means.end(), 0);
    std::fill(num_members_v.begin(), num_members_v.end(), 0);
    std::fill(complete_v.begin(), complete_v.end(), false);
}

/** \param idx the cluster index.
*/
void clusters::set_mean(const kmsvector& mean, const int idx) {
    if (idx == -1) { // Set all means
        means = mean;
    } else {
        std::copy(mean.begin(), mean.end(),
                this->means.begin()+(idx*ncol));
    }
}

void clusters::set_mean(const double* mean, const int idx) {
    if (idx == -1) { // Set all means
        if (means.size() != (ncol*nclust))
            means.resize(ncol*nclust);
        std::copy(&(mean[0]), &(mean[ncol*nclust]), this->means.begin());
    } else {
        std::copy(&(mean[0]), &(mean[ncol]), this->means.begin()+(idx*ncol));
    }
}

void clusters::finalize(const unsigned idx) {
    if (is_complete(idx)) {
        return;
    }

    if (num_members_v[idx] > 1) { // Less than 2 is the same result
        for (unsigned i = 0; i < ncol; i++) {
            means[(idx*ncol)+i] /= double(num_members_v[idx]);
        }
    }
    complete_v[idx] = true;
}

void clusters::unfinalize(const unsigned idx) {
    if (!is_complete(idx)) {
        return;
    }
    complete_v[idx] = false;

    for (unsigned col = 0; col < ncol; col++) {
        this->means[(ncol*idx) + col] *= (double)num_members_v[idx];
    }
}

void clusters::finalize_all() {
    for (unsigned c = 0;  c < get_nclust(); c++)
        finalize(c);
}

void clusters::unfinalize_all() {
    for (unsigned c = 0;  c < get_nclust(); c++)
        unfinalize(c);
}

void clusters::set_num_members_v(const size_t* arg) {
    std::copy(&(arg[0]), &(arg[nclust]), num_members_v.begin());
}

clusters& clusters::operator=(clusters& other) {
    this->means = other.get_means();
    this->num_members_v = other.get_num_members_v();
    this->ncol = other.get_ncol();
    this->nclust = other.get_nclust();
    return *this;
}

bool clusters::operator==(clusters& other) {
    return (get_ncol() == other.get_ncol() &&
            get_nclust() == other.get_nclust() &&
            v_eq(get_num_members_v(), other.get_num_members_v()) &&
            v_eq(get_means(), other.get_means())
           );
}

clusters& clusters::operator+=(clusters& rhs) {
    for (unsigned i = 0; i < size(); i++)
        this->means[i] += rhs[i];

    for (unsigned idx = 0; idx < nclust; idx++)
        num_members_peq(rhs.get_num_members(idx), idx);
    return *this;
}

void clusters::peq(ptr rhs) {
    assert(rhs->size() == size());
    for (unsigned i = 0; i < size(); i++)
        this->means[i] += rhs->get(i);

    for (unsigned idx = 0; idx < nclust; idx++)
        num_members_peq(rhs->get_num_members(idx), idx);
}

void clusters::means_peq(const double* other) {
    for (unsigned i = 0; i < size(); i++)
        this->means[i] += other[i];
}

void clusters::num_members_v_peq(const size_t* other) {
    for (unsigned i = 0; i < num_members_v.size(); i++)
        this->num_members_v[i] += other[i];
}

// Begin Helpers //
const void clusters::print_means() const {
    for (unsigned cl_idx = 0; cl_idx < get_nclust(); cl_idx++) {
#ifndef BIND
        std::cout << "#memb = " << get_num_members(cl_idx) << " ";
#endif
        print_arr<double>(&(means[cl_idx*ncol]), ncol);
    }
}

const void h_clusters::print_means() const {
    clusters::print_means();
#ifndef BIND
    printf("Mean 0 ID: %u\n", zeroid);
    printf("Mean 1 ID: %u\n", oneid);
#endif
}

clusters::clusters(const unsigned nclust, const unsigned ncol) {
    this->nclust = nclust;
    this->ncol = ncol;

    means.resize(ncol*nclust);
    num_members_v.resize(nclust);
    complete_v.assign(nclust, false);
}

clusters::clusters(const unsigned nclust, const unsigned ncol,
        const double* means) {
    this->nclust = nclust;
    this->ncol = ncol;

    set_mean(means);
    num_members_v.resize(nclust);
    complete_v.assign(nclust, true);
}

clusters::clusters(const unsigned nclust, const unsigned ncol,
        const kmsvector& means) : clusters(nclust, ncol, &means[0]) {
}

const void clusters::print_membership_count() const {
    std::string p = "[ ";
    for (unsigned cl_idx = 0; cl_idx < get_nclust(); cl_idx++) {
        p += std::to_string(get_num_members(cl_idx)) + " ";
    }
    p += "]\n";
#ifndef BIND
    std::cout << p;
#endif
}

void clusters::scale_centroid(const double factor,
        const unsigned idx, const double* member) {
    assert(idx < nclust);
    for (unsigned col = 0; col < ncol; col++) {
        means[(ncol*idx)+col] = ((1-factor)*means[(idx*ncol)+col])
            + (factor*(member[col]));
    }
}

// Pruning clusters //
void prune_clusters::reset_s_val_v() {
    std::fill(s_val_v.begin(), s_val_v.end(),
            std::numeric_limits<double>::max());
}

const void prune_clusters::print_prev_means_v() const {
    for (unsigned cl_idx = 0; cl_idx < get_nclust(); cl_idx++) {
        print_arr<double>(&(prev_means[cl_idx*ncol]), ncol);
    }
#ifndef BIND
    std::cout << "\n";
#endif
}
} } // End namespace knor, base
<|endoftext|>


<commit_before>// -*- mode: C++; c-file-style: "gnu" -*-
// kaddrbook.cpp
// Author: Stefan Taferner <taferner@kde.org>
// This code is under GPL

#include <config.h>

#include "kaddrbook.h"

#ifdef KDEPIM_NEW_DISTRLISTS
#include "distributionlist.h"
#else
#include <kabc/distributionlist.h>
#endif

#include <kapplication.h>
#include <kdebug.h>
#include <klocale.h>
#include <kmessagebox.h>
#include <kdeversion.h>
#include <kabc/resource.h>
#include <kabc/stdaddressbook.h>
#include <kabc/vcardconverter.h>
#include <kresources/selectdialog.h>
#include <dcopref.h>
#include <dcopclient.h>

#include <qeventloop.h>
#include <qregexp.h>

#include <unistd.h>

//-----------------------------------------------------------------------------
void KAddrBookExternal::openEmail( const QString &addr, QWidget *parent ) {
  QString email;
  QString name;

  KABC::Addressee::parseEmailAddress( addr, name, email );

  KABC::AddressBook *ab = KABC::StdAddressBook::self( true );

  // force a reload of the address book file so that changes that were made
  // by other programs are loaded
  ab->asyncLoad();

  // if we have to reload the address book then we should also wait until
  // it's completely reloaded
#if KDE_IS_VERSION(3,4,89)
  // This ugly hack will be removed in 4.0
  while ( !ab->loadingHasFinished() ) {
    QApplication::eventLoop()->processEvents( QEventLoop::ExcludeUserInput );

    // use sleep here to reduce cpu usage
    usleep( 100 );
  }
#endif

  KABC::Addressee::List addressees = ab->findByEmail( email );

  if ( addressees.count() > 0 ) {
    if ( kapp->dcopClient()->isApplicationRegistered( "kaddressbook" ) ){
      //make sure kaddressbook is loaded, otherwise showContactEditor
      //won't work as desired, see bug #87233
      DCOPRef call ( "kaddressbook", "kaddressbook" );
      call.send( "newInstance()" );
    }  else {
      kapp->startServiceByDesktopName( "kaddressbook" );
    }

    DCOPRef call( "kaddressbook", "KAddressBookIface" );
    call.send( "showContactEditor(QString)", addressees.first().uid() );
  } else {
    //TODO: Enable the better message at the next string unfreeze
#if 0
    QString text = i18n("<qt>The email address %1 cannot be "
                        "found in your addressbook.</qt>").arg( email );
#else
    QString text = email + " " + i18n( "is not in address book" );
#endif
    KMessageBox::information( parent, text, QString::null, "notInAddressBook" );
  }
}

//-----------------------------------------------------------------------------
void KAddrBookExternal::addEmail( const QString& addr, QWidget *parent) {
  QString email;
  QString name;

  KABC::Addressee::parseEmailAddress( addr, name, email );

  KABC::AddressBook *ab = KABC::StdAddressBook::self( true );

  // force a reload of the address book file so that changes that were made
  // by other programs are loaded
  ab->asyncLoad();

  // if we have to reload the address book then we should also wait until
  // it's completely reloaded
#if KDE_IS_VERSION(3,4,89)
  // This ugly hack will be removed in 4.0
  while ( !ab->loadingHasFinished() ) {
    QApplication::eventLoop()->processEvents( QEventLoop::ExcludeUserInput );

    // use sleep here to reduce cpu usage
    usleep( 100 );
  }
#endif

  KABC::Addressee::List addressees = ab->findByEmail( email );

  if ( addressees.isEmpty() ) {
    KABC::Addressee a;
    a.setNameFromString( name );
    a.insertEmail( email, true );

    {
      KConfig config( "kaddressbookrc" );
      config.setGroup( "General" );
      int type = config.readNumEntry( "FormattedNameType", 1 );

      QString name;
      switch ( type ) {
        case 1:
          name = a.givenName() + " " + a.familyName();
          break;
        case 2:
          name = a.assembledName();
          break;
        case 3:
          name = a.familyName() + ", " + a.givenName();
          break;
        case 4:
          name = a.familyName() + " " + a.givenName();
          break;
        case 5:
          name = a.organization();
          break;
        default:
          name = "";
          break;
      }
      name.simplifyWhiteSpace();

      a.setFormattedName( name );
    }

    if ( !KAddrBookExternal::addAddressee( a ) ) {
      KMessageBox::error( parent, i18n("Cannot save to addressbook.") );
    } else {
      QString text = i18n("<qt>The email address %1 was added to your "
                          "addressbook; you can add more information to this "
                          "entry by opening the addressbook.</qt>").arg( addr );
      KMessageBox::information( parent, text, QString::null, "addedtokabc" );
    }
  } else {
    QString text = i18n("<qt>The email address %1 is already in your "
                        "addressbook.</qt>").arg( addr );
    KMessageBox::information( parent, text, QString::null,
                              "alreadyInAddressBook" );
  }
}

void KAddrBookExternal::openAddressBook(QWidget *) {
  kapp->startServiceByDesktopName( "kaddressbook" );
}

void KAddrBookExternal::addNewAddressee( QWidget* )
{
  kapp->startServiceByDesktopName("kaddressbook");
  DCOPRef call("kaddressbook", "KAddressBookIface");
  call.send("newContact()");
}

bool KAddrBookExternal::addVCard( const KABC::Addressee& addressee, QWidget *parent )
{
  KABC::AddressBook *ab = KABC::StdAddressBook::self( true );
  bool inserted = false;

  KABC::Addressee::List addressees =
      ab->findByEmail( addressee.preferredEmail() );

  if ( addressees.isEmpty() ) {
    if ( !KAddrBookExternal::addAddressee( addressee ) ) {
      KMessageBox::error( parent, i18n("Cannot save to addressbook.") );
      inserted = false;
    } else {
      QString text = i18n("The VCard was added to your addressbook; "
                          "you can add more information to this "
                          "entry by opening the addressbook.");
      KMessageBox::information( parent, text, QString::null, "addedtokabc" );
      inserted = true;
    }
  } else {
    QString text = i18n("The VCard's primary email address is already in "
                        "your addressbook; however, you may save the VCard "
                        "into a file and import it into the addressbook "
                        "manually.");
    KMessageBox::information( parent, text );
    inserted = true;
  }

  return inserted;
}

bool KAddrBookExternal::addAddressee( const KABC::Addressee& addr )
{
  KABC::AddressBook *addressBook = KABC::StdAddressBook::self( true );

#if KDE_IS_VERSION(3,4,89)
  // This ugly hack will be removed in 4.0
  while ( !addressBook->loadingHasFinished() ) {
    QApplication::eventLoop()->processEvents( QEventLoop::ExcludeUserInput );

    // use sleep here to reduce cpu usage
    usleep( 100 );
  }
#endif

  // Select a resource
  QPtrList<KABC::Resource> kabcResources = addressBook->resources();

  QPtrList<KRES::Resource> kresResources;
  QPtrListIterator<KABC::Resource> resIt( kabcResources );
  KABC::Resource *kabcResource;
  while ( ( kabcResource = resIt.current() ) != 0 ) {
    ++resIt;
    if ( !kabcResource->readOnly() ) {
      KRES::Resource *res = static_cast<KRES::Resource*>( kabcResource );
      if ( res )
        kresResources.append( res );
    }
  }

  kabcResource = static_cast<KABC::Resource*>( KRES::SelectDialog::getResource( kresResources, 0 ) );

  KABC::Ticket *ticket = addressBook->requestSaveTicket( kabcResource );
  bool saved = false;
  if ( ticket ) {
    KABC::Addressee addressee( addr );
    addressee.setResource( kabcResource );
    addressBook->insertAddressee( addressee );
    saved = addressBook->save( ticket );
    if ( !saved )
      addressBook->releaseSaveTicket( ticket );
  }

  addressBook->emitAddressBookChanged();

  return saved;
}

QString KAddrBookExternal::expandDistributionList( const QString& listName )
{
  if ( listName.isEmpty() )
    return QString::null;

  const QString lowerListName = listName.lower();
  KABC::AddressBook *addressBook = KABC::StdAddressBook::self( true );
#ifdef KDEPIM_NEW_DISTRLISTS
  KPIM::DistributionList distrList = KPIM::DistributionList::findByName( addressBook, lowerListName, false );
  if ( !distrList.isEmpty() ) {
    return distrList.emails( addressBook ).join( ", " );
  }
#else
  KABC::DistributionListManager manager( addressBook );
  manager.load();
  const QStringList listNames = manager.listNames();

  for ( QStringList::ConstIterator it = listNames.begin();
        it != listNames.end(); ++it) {
    if ( (*it).lower() == lowerListName ) {
      const QStringList addressList = manager.list( *it )->emails();
      return addressList.join( ", " );
    }
  }
#endif
  return QString::null;
}
<commit_msg>fix use proper error handler to show kabc errors patch provided by Felix Berger. Thanks!<commit_after>// -*- mode: C++; c-file-style: "gnu" -*-
// kaddrbook.cpp
// Author: Stefan Taferner <taferner@kde.org>
// This code is under GPL

#include <config.h>

#include "kaddrbook.h"

#ifdef KDEPIM_NEW_DISTRLISTS
#include "distributionlist.h"
#else
#include <kabc/distributionlist.h>
#endif

#include <kapplication.h>
#include <kdebug.h>
#include <klocale.h>
#include <kmessagebox.h>
#include <kdeversion.h>
#include <kabc/resource.h>
#include <kabc/stdaddressbook.h>
#include <kabc/vcardconverter.h>
#include <kabc/errorhandler.h>
#include <kresources/selectdialog.h>
#include <dcopref.h>
#include <dcopclient.h>

#include <qeventloop.h>
#include <qregexp.h>

#include <unistd.h>

//-----------------------------------------------------------------------------
void KAddrBookExternal::openEmail( const QString &addr, QWidget *parent ) {
  QString email;
  QString name;

  KABC::Addressee::parseEmailAddress( addr, name, email );

  KABC::AddressBook *ab = KABC::StdAddressBook::self( true );

  // force a reload of the address book file so that changes that were made
  // by other programs are loaded
  ab->asyncLoad();

  // if we have to reload the address book then we should also wait until
  // it's completely reloaded
#if KDE_IS_VERSION(3,4,89)
  // This ugly hack will be removed in 4.0
  while ( !ab->loadingHasFinished() ) {
    QApplication::eventLoop()->processEvents( QEventLoop::ExcludeUserInput );

    // use sleep here to reduce cpu usage
    usleep( 100 );
  }
#endif

  KABC::Addressee::List addressees = ab->findByEmail( email );

  if ( addressees.count() > 0 ) {
    if ( kapp->dcopClient()->isApplicationRegistered( "kaddressbook" ) ){
      //make sure kaddressbook is loaded, otherwise showContactEditor
      //won't work as desired, see bug #87233
      DCOPRef call ( "kaddressbook", "kaddressbook" );
      call.send( "newInstance()" );
    }  else {
      kapp->startServiceByDesktopName( "kaddressbook" );
    }

    DCOPRef call( "kaddressbook", "KAddressBookIface" );
    call.send( "showContactEditor(QString)", addressees.first().uid() );
  } else {
    //TODO: Enable the better message at the next string unfreeze
#if 0
    QString text = i18n("<qt>The email address %1 cannot be "
                        "found in your addressbook.</qt>").arg( email );
#else
    QString text = email + " " + i18n( "is not in address book" );
#endif
    KMessageBox::information( parent, text, QString::null, "notInAddressBook" );
  }
}

//-----------------------------------------------------------------------------
void KAddrBookExternal::addEmail( const QString& addr, QWidget *parent) {
  QString email;
  QString name;

  KABC::Addressee::parseEmailAddress( addr, name, email );

  KABC::AddressBook *ab = KABC::StdAddressBook::self( true );

  ab->setErrorHandler( new KABC::GuiErrorHandler( parent ) );

  // force a reload of the address book file so that changes that were made
  // by other programs are loaded
  ab->asyncLoad();

  // if we have to reload the address book then we should also wait until
  // it's completely reloaded
#if KDE_IS_VERSION(3,4,89)
  // This ugly hack will be removed in 4.0
  while ( !ab->loadingHasFinished() ) {
    QApplication::eventLoop()->processEvents( QEventLoop::ExcludeUserInput );

    // use sleep here to reduce cpu usage
    usleep( 100 );
  }
#endif

  KABC::Addressee::List addressees = ab->findByEmail( email );

  if ( addressees.isEmpty() ) {
    KABC::Addressee a;
    a.setNameFromString( name );
    a.insertEmail( email, true );

    {
      KConfig config( "kaddressbookrc" );
      config.setGroup( "General" );
      int type = config.readNumEntry( "FormattedNameType", 1 );

      QString name;
      switch ( type ) {
        case 1:
          name = a.givenName() + " " + a.familyName();
          break;
        case 2:
          name = a.assembledName();
          break;
        case 3:
          name = a.familyName() + ", " + a.givenName();
          break;
        case 4:
          name = a.familyName() + " " + a.givenName();
          break;
        case 5:
          name = a.organization();
          break;
        default:
          name = "";
          break;
      }
      name.simplifyWhiteSpace();

      a.setFormattedName( name );
    }

    if ( KAddrBookExternal::addAddressee( a ) ) {
      QString text = i18n("<qt>The email address %1 was added to your "
                          "addressbook; you can add more information to this "
                          "entry by opening the addressbook.</qt>").arg( addr );
      KMessageBox::information( parent, text, QString::null, "addedtokabc" );
    }
  } else {
    QString text = i18n("<qt>The email address %1 is already in your "
                        "addressbook.</qt>").arg( addr );
    KMessageBox::information( parent, text, QString::null,
                              "alreadyInAddressBook" );
  }
  ab->setErrorHandler( 0 );
}

void KAddrBookExternal::openAddressBook(QWidget *) {
  kapp->startServiceByDesktopName( "kaddressbook" );
}

void KAddrBookExternal::addNewAddressee( QWidget* )
{
  kapp->startServiceByDesktopName("kaddressbook");
  DCOPRef call("kaddressbook", "KAddressBookIface");
  call.send("newContact()");
}

bool KAddrBookExternal::addVCard( const KABC::Addressee& addressee, QWidget *parent )
{
  KABC::AddressBook *ab = KABC::StdAddressBook::self( true );
  bool inserted = false;

  ab->setErrorHandler( new KABC::GuiErrorHandler( parent ) );

  KABC::Addressee::List addressees =
      ab->findByEmail( addressee.preferredEmail() );

  if ( addressees.isEmpty() ) {
    if ( KAddrBookExternal::addAddressee( addressee ) ) {
      QString text = i18n("The VCard was added to your addressbook; "
                          "you can add more information to this "
                          "entry by opening the addressbook.");
      KMessageBox::information( parent, text, QString::null, "addedtokabc" );
      inserted = true;
    }
  } else {
    QString text = i18n("The VCard's primary email address is already in "
                        "your addressbook; however, you may save the VCard "
                        "into a file and import it into the addressbook "
                        "manually.");
    KMessageBox::information( parent, text );
    inserted = true;
  }

  ab->setErrorHandler( 0 );
  return inserted;
}

bool KAddrBookExternal::addAddressee( const KABC::Addressee& addr )
{
  KABC::AddressBook *addressBook = KABC::StdAddressBook::self( true );

#if KDE_IS_VERSION(3,4,89)
  // This ugly hack will be removed in 4.0
  while ( !addressBook->loadingHasFinished() ) {
    QApplication::eventLoop()->processEvents( QEventLoop::ExcludeUserInput );

    // use sleep here to reduce cpu usage
    usleep( 100 );
  }
#endif

  // Select a resource
  QPtrList<KABC::Resource> kabcResources = addressBook->resources();

  QPtrList<KRES::Resource> kresResources;
  QPtrListIterator<KABC::Resource> resIt( kabcResources );
  KABC::Resource *kabcResource;
  while ( ( kabcResource = resIt.current() ) != 0 ) {
    ++resIt;
    if ( !kabcResource->readOnly() ) {
      KRES::Resource *res = static_cast<KRES::Resource*>( kabcResource );
      if ( res )
        kresResources.append( res );
    }
  }

  kabcResource = static_cast<KABC::Resource*>( KRES::SelectDialog::getResource( kresResources, 0 ) );

  KABC::Ticket *ticket = addressBook->requestSaveTicket( kabcResource );
  bool saved = false;
  if ( ticket ) {
    KABC::Addressee addressee( addr );
    addressee.setResource( kabcResource );
    addressBook->insertAddressee( addressee );
    saved = addressBook->save( ticket );
    if ( !saved )
      addressBook->releaseSaveTicket( ticket );
  }

  addressBook->emitAddressBookChanged();

  return saved;
}

QString KAddrBookExternal::expandDistributionList( const QString& listName )
{
  if ( listName.isEmpty() )
    return QString::null;

  const QString lowerListName = listName.lower();
  KABC::AddressBook *addressBook = KABC::StdAddressBook::self( true );
#ifdef KDEPIM_NEW_DISTRLISTS
  KPIM::DistributionList distrList = KPIM::DistributionList::findByName( addressBook, lowerListName, false );
  if ( !distrList.isEmpty() ) {
    return distrList.emails( addressBook ).join( ", " );
  }
#else
  KABC::DistributionListManager manager( addressBook );
  manager.load();
  const QStringList listNames = manager.listNames();

  for ( QStringList::ConstIterator it = listNames.begin();
        it != listNames.end(); ++it) {
    if ( (*it).lower() == lowerListName ) {
      const QStringList addressList = manager.list( *it )->emails();
      return addressList.join( ", " );
    }
  }
#endif
  return QString::null;
}
<|endoftext|>


<commit_before>/*
 * Copyright (C) 2010, Gostai S.A.S.
 *
 * This software is provided "as is" without warranty of any kind,
 * either expressed or implied, including but not limited to the
 * implied warranties of fitness for a particular purpose.
 *
 * See the LICENSE file for more information.
 */

#include <libport/asio.hh>

#include <urbi/uobject.hh>

using namespace urbi;

/** Subsumption object.
 *
 * Takes one output, and provides multiple inputs that conditionaly bounce to
 * said output.
 */
class subsumption: public UObject
{
public:
  subsumption(const std::string& n);
  /// Set target for all write operations, create 'val' source at level 0.
  int init(UVar& target);
  /** Creates slot \b varName that writes at \b level, and sets this level for
   * \b delay seconds.
   */
  void createTimedOverride(const std::string& varName, int level, ufloat delay);
  /// Create a new slot \b varName that writes at level \b level.
  void createOverride(const std::string& varName, int level);
  /// All write operations below this level will be ignored.
  UVar level;
private:
  class SUVar: public UVar
  {
  public:
    SUVar(const std::string& obj, const std::string& var, int level,
         ufloat delay = 0);
    friend class subsumption;
  private:
    int level_;
    ufloat timer_;
  };
  int onLevelChange(UVar& v);
  int onWrite(UVar& v);
  void resetLevel(int oldLevel, int writeCount);
  UVar* target_;
  int writeCount_;
};

subsumption::subsumption(const std::string& n)
  : UObject(n)
  , target_(0)
  , writeCount_(0)
{
  UBindFunction(subsumption, init);
}

int
subsumption::init(UVar& target)
{
  std::string targetName = target.get_name();
  UBindVar(subsumption, level);
  UBindFunction(subsumption, createOverride);
  UBindFunction(subsumption, createTimedOverride);
  UNotifyChange(level, &subsumption::onLevelChange);
  level = 0;
  target_ = new UVar(targetName);
  createOverride("val", 0);
  return 0;
}

void
subsumption::createOverride(const std::string& name, int level)
{
  UNotifyChange(*new SUVar(__name, name, level), &subsumption::onWrite);
}

void
subsumption::createTimedOverride(const std::string& name, int level,
                                 ufloat timer)
{
  UNotifyChange(*new SUVar(__name, name, level, timer), &subsumption::onWrite);
}

int
subsumption::onLevelChange(UVar&)
{
  writeCount_++;
  return 0;
}

int
subsumption::onWrite(UVar& v)
{
  SUVar& sv = static_cast<SUVar&>(v);
  if ((int)level <= sv.level_)
  {
    *target_ = sv.val();
    if (sv.timer_)
    {
      int oldLevel = level;
      level = sv.level_;
      // Keep this line after the previous one.
      libport::asyncCall(boost::bind(&subsumption::resetLevel, this,
                                     oldLevel, writeCount_),
                         useconds_t(sv.timer_ * 1000000.0));
    }
  }
  return 0;
}

subsumption::SUVar::SUVar(const std::string& obj, const std::string& var,
                          int level, ufloat delay)
  : UVar(obj, var)
  , level_(level)
  , timer_(delay)
{
}

void
subsumption::resetLevel(int newLevel, int wc)
{
  ctx_->lock();
  // Only reset if level was not written on since first trigger.
  if (writeCount_ == wc)
    level = newLevel;
  ctx_->unlock();
}

UStart(subsumption);
<commit_msg>Subsumption: Support variable read.<commit_after>/*
 * Copyright (C) 2010, Gostai S.A.S.
 *
 * This software is provided "as is" without warranty of any kind,
 * either expressed or implied, including but not limited to the
 * implied warranties of fitness for a particular purpose.
 *
 * See the LICENSE file for more information.
 */

#include <libport/asio.hh>

#include <urbi/uobject.hh>

using namespace urbi;

/** Subsumption object.
 *
 * Takes one output, and provides multiple inputs that conditionaly bounce to
 * said output.
 */
class subsumption: public UObject
{
public:
  subsumption(const std::string& n);
  /// Set target for all write operations, create 'val' source at level 0.
  int init(UVar& target);
  /** Creates slot \b varName that writes at \b level, and sets this level for
   * \b delay seconds.
   */
  void createTimedOverride(const std::string& varName, int level, ufloat delay);
  /// Create a new slot \b varName that writes at level \b level.
  void createOverride(const std::string& varName, int level);
  /// All write operations below this level will be ignored.
  UVar level;
private:
  class SUVar: public UVar
  {
  public:
    SUVar(const std::string& obj, const std::string& var, int level,
         ufloat delay = 0);
    friend class subsumption;
  private:
    int level_;
    ufloat timer_;
  };
  int onLevelChange(UVar& v);
  int onWrite(UVar& v);
  int onRead(UVar& v);
  void resetLevel(int oldLevel, int writeCount);
  UVar* target_;
  int writeCount_;
};

subsumption::subsumption(const std::string& n)
  : UObject(n)
  , target_(0)
  , writeCount_(0)
{
  UBindFunction(subsumption, init);
}

int
subsumption::init(UVar& target)
{
  std::string targetName = target.get_name();
  UBindVar(subsumption, level);
  UBindFunction(subsumption, createOverride);
  UBindFunction(subsumption, createTimedOverride);
  UNotifyChange(level, &subsumption::onLevelChange);
  level = 0;
  target_ = new UVar(targetName);
  createOverride("val", 0);
  return 0;
}

void
subsumption::createOverride(const std::string& name, int level)
{
  createTimedOverride(name, level, 0);
}

void
subsumption::createTimedOverride(const std::string& name, int level,
                                 ufloat timer)
{
  SUVar* v = new SUVar(__name, name, level, timer);
  v->setOwned();
  UNotifyChange(*v, &subsumption::onWrite);
  UNotifyAccess(*v, &subsumption::onRead);
}

int
subsumption::onLevelChange(UVar&)
{
  writeCount_++;
  return 0;
}

int
subsumption::onRead(UVar& v)
{
  v = target_->val();
  return 0;
}

int
subsumption::onWrite(UVar& v)
{
  SUVar& sv = static_cast<SUVar&>(v);
  if ((int)level <= sv.level_)
  {
    *target_ = sv.val();
    if (sv.timer_)
    {
      int oldLevel = level;
      level = sv.level_;
      // Keep this line after the previous one.
      libport::asyncCall(boost::bind(&subsumption::resetLevel, this,
                                     oldLevel, writeCount_),
                         useconds_t(sv.timer_ * 1000000.0));
    }
  }
  return 0;
}

subsumption::SUVar::SUVar(const std::string& obj, const std::string& var,
                          int level, ufloat delay)
  : UVar(obj, var)
  , level_(level)
  , timer_(delay)
{
}

void
subsumption::resetLevel(int newLevel, int wc)
{
  ctx_->lock();
  // Only reset if level was not written on since first trigger.
  if (writeCount_ == wc)
    level = newLevel;
  ctx_->unlock();
}

UStart(subsumption);
<|endoftext|>


<commit_before>/*
  Crystal Space Event Queue
  Copyright (C) 1998-2004 by Jorrit Tyberghein
  Written by Andrew Zabolotny <bit@eltech.ru>, Eric Sunshine, Jonathan Tarbox,
    Frank Richter

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

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

  You should have received a copy of the GNU Library General Public
  License along with this library; if not, write to the Free
  Software Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
*/

#include "cssysdef.h"
#include "csutil/array.h"
#include "csutil/csevent.h"
#include "csutil/cseventq.h"
#include "csutil/memfile.h"
#include "csutil/util.h"
#include "csutil/sysfunc.h"

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

SCF_IMPLEMENT_IBASE (csEvent)
  SCF_IMPLEMENTS_INTERFACE (iEvent)
  SCF_IMPLEMENTS_INTERFACE (csEvent)
SCF_IMPLEMENT_IBASE_END

CS_IMPLEMENT_STATIC_VAR(GetEventStrSet, csStringSet, ())

char const* csEvent::GetTypeName (csEventAttributeType t)
{
  switch (t)
  {
    case csEventAttrInt:	    return "int";
    case csEventAttrUInt:	    return "uint";
    case csEventAttrFloat:	    return "double";
    case csEventAttrDatabuffer:	    return "databuffer";
    case csEventAttrEvent:	    return "event";
    case csEventAttriBase:	    return "iBase";
    default:
      break;
  }
  return "unknown";
}

csStringID csEvent::GetKeyID (const char* key)
{
  return GetEventStrSet()->Request (key);
}

const char* csEvent::GetKeyName (csStringID id)
{
  return GetEventStrSet()->Request (id);
}

csEvent::csEvent ()
{
  SCF_CONSTRUCT_IBASE (0);

  count = 0;
}

csEvent::csEvent (csTicks iTime, int eType, int mx, int my,
		  int mButton, int mModifiers) : attributes (53)
{
  SCF_CONSTRUCT_IBASE (0);
  Time = iTime;
  Type = eType;
  Category = SubCategory = Flags = 0;
  Mouse.x = mx;
  Mouse.y = my;
  Mouse.Button = mButton;
  Mouse.Modifiers = mModifiers;

  count = 0;
}

csEvent::csEvent (csTicks iTime, int eType, int jn, int jx, int jy,
		  int jButton, int jModifiers) : attributes (53)
{
  SCF_CONSTRUCT_IBASE (0);
  Time = iTime;
  Type = eType;
  Category = SubCategory = Flags = 0;
  Joystick.number = jn;
  Joystick.x = jx;
  Joystick.y = jy;
  Joystick.Button = jButton;
  Joystick.Modifiers = jModifiers;

  count = 0;
}

csEvent::csEvent (csTicks iTime, int eType, int cCode, intptr_t cInfo) :
  attributes (53)
{
  SCF_CONSTRUCT_IBASE (0);
  Time = iTime;
  Type = eType;
  Category = SubCategory = Flags = 0;
  Command.Code = cCode;
  Command.Info = cInfo;
  if (eType == csevBroadcast)
    Flags = CSEF_BROADCAST;

  count = 0;
}

csEvent::csEvent (csEvent const& e) : iEvent(), attributes (53)
{
  SCF_CONSTRUCT_IBASE (0);
  count = 0;

  Type = e.Type;
  Category = e.Category;
  SubCategory = e.SubCategory;
  Flags = e.Flags;
  Time = e.Time;
  attributes = e.attributes;

  if ((Type & CSMASK_Mouse) != 0)
  {
    Mouse.x = e.Mouse.x;
    Mouse.y = e.Mouse.y;
    Mouse.Button = e.Mouse.Button;
    Mouse.Modifiers = e.Mouse.Modifiers;
  }
  else if ((Type & CSMASK_Joystick) != 0)
  {
    Joystick.number = e.Joystick.number;
    Joystick.x = e.Joystick.x;
    Joystick.y = e.Joystick.y;
    Joystick.Button = e.Joystick.Button;
    Joystick.Modifiers = e.Joystick.Modifiers;
  }
  else
  {
    Command.Code = e.Command.Code;
    Command.Info = e.Command.Info;
  }
}

csEvent::~csEvent ()
{
  RemoveAll();
  SCF_DESTRUCT_IBASE ();
}

bool csEvent::Add (const char *name, float v)
{
  if (attributes.In (GetKeyID (name))) return false;
  attribute* object = new attribute (csEventAttrFloat);
  object->doubleVal = v;
  attributes.Put (GetKeyID (name), object);
  count++;
  return true;
}

bool csEvent::Add (const char *name, double v)
{
  if (attributes.In (GetKeyID (name))) return false;
  attribute* object = new attribute (csEventAttrFloat);
  object->doubleVal = v;
  attributes.Put (GetKeyID (name), object);
  count++;
  return true;
}

bool csEvent::Add (const char *name, bool v)
{
  if (attributes.In (GetKeyID (name))) return false;
  attribute* object = new attribute (csEventAttrInt);
  object->intVal = v ? 1 : 0;
  attributes.Put (GetKeyID (name), object);
  count++;
  return true;
}

bool csEvent::Add (const char *name, const char *v)
{
  if (attributes.In (GetKeyID (name))) return false;
  attribute* object = new attribute (csEventAttrDatabuffer);
  object->dataSize = strlen(v);
  object->bufferVal = csStrNew(v);
  attributes.Put (GetKeyID (name), object);
  count++;
  return true;
}

bool csEvent::Add (const char *name, const void *v, size_t size)
{
  if (attributes.In (GetKeyID (name))) return false;
  attribute* object = new attribute (csEventAttrDatabuffer);
  object->bufferVal = new char[size + 1];
  memcpy (object->bufferVal, v, size);
  object->bufferVal[size] = 0;
  object->dataSize = size;
  attributes.Put (GetKeyID (name), object);
  count++;
  return true;
}

bool csEvent::CheckForLoops (iEvent* current, iEvent* e)
{
  csRef<iEventAttributeIterator> iter (current->GetAttributeIterator());

  while (iter->HasNext())
  {
    const char* attr = iter->Next();

    if (current->GetAttributeType (attr) == csEventAttrEvent)
    {
      csRef<iEvent> ev;
      if (current->Retrieve (attr, ev) != csEventErrNone) continue;
      if (ev == e)
	return false;
      return CheckForLoops(ev, e);
    }
  }
  return true;
}

bool csEvent::Add (const char *name, iEvent *v)
{
  if (attributes.In (GetKeyID (name))) return false;
  if (this == v)
    return false;
  if (v && CheckForLoops(v, this))
  {
    attribute* object = new attribute (csEventAttrEvent);
    (object->ibaseVal = (iBase*)v)->IncRef();
    attributes.Put (GetKeyID (name), object);
    count++;
    return true;
  }
  return false;
}

bool csEvent::Add (const char *name, iBase* v)
{
  if (attributes.In (GetKeyID (name))) return false;
  if (v)
  {
    attribute* object = new attribute (csEventAttriBase);
    (object->ibaseVal = v)->IncRef();
    attributes.Put (GetKeyID (name), object);
    count++;
    return true;
  }
  return false;
}

csEventError csEvent::Retrieve (const char *name, float &v) const
{
  attribute* object = attributes.Get (GetKeyID (name), 0);
  if (!object) return csEventErrNotFound;
  if (object->type == csEventAttrFloat)
  {
    v = object->doubleVal;
    return csEventErrNone;
  }
  else
  {
    return InternalReportMismatch (object);
  }
}

csEventError csEvent::Retrieve (const char *name, double &v) const
{
  attribute* object = attributes.Get (GetKeyID (name), 0);
  if (!object) return csEventErrNotFound;
  if (object->type == csEventAttrFloat)
  {
    v = object->doubleVal;
    return csEventErrNone;
  }
  else
  {
    return InternalReportMismatch (object);
  }
}

csEventError csEvent::Retrieve (const char *name, const char *&v) const
{
  attribute* object = attributes.Get (GetKeyID (name), 0);
  if (!object) return csEventErrNotFound;
  if (object->type == csEventAttrDatabuffer)
  {
    v = object->bufferVal;
    return csEventErrNone;
  }
  else
  {
    return InternalReportMismatch (object);
  }
}

csEventError csEvent::Retrieve (const char *name, void const *&v,
  size_t &size) const
{
  attribute* object = attributes.Get (GetKeyID (name), 0);
  if (!object) return csEventErrNotFound;
  if (object->type == csEventAttrDatabuffer)
  {
    v = object->bufferVal;
    size = object->dataSize;
    return csEventErrNone;
  }
  else
  {
    return InternalReportMismatch (object);
  }
}

csEventError csEvent::Retrieve (const char *name, bool &v) const
{
  attribute* object = attributes.Get (GetKeyID (name), 0);
  if (!object) return csEventErrNotFound;
  if (object->type == csEventAttrInt)
  {
    v = object->intVal != 0;
    return csEventErrNone;
  }
  else
  {
    return InternalReportMismatch (object);
  }
}

csEventError csEvent::Retrieve (const char *name, csRef<iEvent> &v) const
{
  attribute* object = attributes.Get (GetKeyID (name), 0);
  if (!object) return csEventErrNotFound;
  if (object->type == csEventAttrEvent)
  {
    v = (iEvent*)object->ibaseVal;
    return csEventErrNone;
  }
  else
  {
    return InternalReportMismatch (object);
  }
}

csEventError csEvent::Retrieve (const char *name, csRef<iBase> &v) const
{
  attribute* object = attributes.Get (GetKeyID (name), 0);
  if (!object) return csEventErrNotFound;
  if (object->type == csEventAttriBase)
  {
    v = object->ibaseVal;
    return csEventErrNone;
  }
  else
  {
    return InternalReportMismatch (object);
  }
}

bool csEvent::AttributeExists (const char* name)
{
  return attributes.In (GetKeyID (name));
}

csEventAttributeType csEvent::GetAttributeType (const char* name)
{
  attribute* object = attributes.Get (GetKeyID (name), 0);
  if (object)
  {
    return object->type;
  }
  return csEventAttrUnknown;
}

bool csEvent::Remove(const char *name)
{
  csStringID id = GetKeyID (name);
  if (!attributes.In (id)) return false;
  attribute* object = attributes.Get (id, 0);
  bool result = attributes.Delete (id, object);
  delete object;
  return result;
}

bool csEvent::RemoveAll()
{
  csHash<attribute*, csStringID>::GlobalIterator iter (
    attributes.GetIterator ());

  while (iter.HasNext())
  {
    csStringID name;
    attribute* object = iter.Next (name);
    delete object;
  }

  attributes.DeleteAll();
  count = 0;
  return true;
}

csRef<iEventAttributeIterator> csEvent::GetAttributeIterator()
{
  csHash<csEvent::attribute*, csStringID>::GlobalIterator attrIter (
    attributes.GetIterator());
  return csPtr<iEventAttributeIterator> (new csEventAttributeIterator (
    attrIter));
}

static void IndentLevel(int level)
{
  for (int i = 0; i < level; i++)
    csPrintf("\t");
}

bool csEvent::Print (int level)
{
  csHash<attribute*, csStringID>::GlobalIterator iter (
    attributes.GetIterator ());

  while (iter.HasNext())
  {
    csStringID name;
    attribute* object = iter.Next (name);

    IndentLevel(level); csPrintf ("------\n");
    IndentLevel(level); csPrintf ("Name: %s\n", GetKeyName (name));
    IndentLevel(level); csPrintf (" Datatype: %s\n",
	  GetTypeName(object->type));
    if (object->type == csEventAttrEvent)
    {
      IndentLevel(level); csPrintf(" Sub-Event Contents:\n");
      csRef<csEvent> csev = SCF_QUERY_INTERFACE (object->ibaseVal, csEvent);
      if (csev)
	csev->Print(level+1);
      else
      {
	IndentLevel(level+1); csPrintf(" (Not an event!):\n");
      }

    }
    if (object->type == csEventAttrInt)
    {

      IndentLevel(level);
      csPrintf (" Value: %lld\n", // Avoid Mingw/gcc borked PRId64.
	object->intVal);
    }
    else if (object->type == csEventAttrUInt)
    {
      IndentLevel(level);
      csPrintf (" Value: %llu\n", // Avoid Mingw/gcc borked PRIu64.
	(ulonglong) object->intVal);
    }
    else if (object->type == csEventAttrFloat)
    {
      IndentLevel(level);
      csPrintf (" Value: %f\n", object->doubleVal);
    }
    else if (object->type == csEventAttrDatabuffer)
    {
      IndentLevel(level); csPrintf(" Value: 0x%p\n", object->bufferVal);
      IndentLevel(level); csPrintf(" Length: %zu\n", object->dataSize);
    }
  }

  return true;
}

csRef<iEvent> csEvent::CreateEvent()
{
  return csPtr<iEvent>(new csEvent());
}

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

SCF_IMPLEMENT_IBASE (csEventAttributeIterator)
  SCF_IMPLEMENTS_INTERFACE (iEventAttributeIterator)
SCF_IMPLEMENT_IBASE_END

const char* csEventAttributeIterator::Next()
{
  csStringID key;
  iterator.Next (key);
  return csEvent::GetKeyName (key);
}

//*****************************************************************************
// csPoolEvent
//*****************************************************************************
csPoolEvent::csPoolEvent(csEventQueue *q)
{
    pool = q;
    next = 0;
}

void csPoolEvent::DecRef()
{
  if (scfRefCount == 1)
  {
    if (!pool.IsValid())
      return;

    next = pool->EventPool;
    pool->EventPool = this;
    RemoveAll();
    Type = 0;
    Category = 0;
    Flags = 0;
    Time = 0;
    SubCategory = 0;
    Command.Code = 0;
    Command.Info = 0;
  }
  else
  {
    scfRefCount--;
  }
}

csRef<iEvent> csPoolEvent::CreateEvent()
{
  if (pool.IsValid())
    return pool->CreateEvent(0);
  return superclass::CreateEvent();
}
<commit_msg>More ugly 64-bit printf() format directive hackiness.<commit_after>/*
  Crystal Space Event Queue
  Copyright (C) 1998-2004 by Jorrit Tyberghein
  Written by Andrew Zabolotny <bit@eltech.ru>, Eric Sunshine, Jonathan Tarbox,
    Frank Richter

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

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

  You should have received a copy of the GNU Library General Public
  License along with this library; if not, write to the Free
  Software Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
*/

#include "cssysdef.h"
#include "csutil/array.h"
#include "csutil/csevent.h"
#include "csutil/cseventq.h"
#include "csutil/memfile.h"
#include "csutil/util.h"
#include "csutil/sysfunc.h"

// Ugly work-around for Mingw/gcc borked PRId64.
#ifndef __CS_PRI64_PREFIX
#if CS_PROCESSOR_SIZE == 64
#define __CS_PRI64_PREFIX "l"
#else
#define __CS_PRI64_PREFIX "ll"
#endif
#endif

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

SCF_IMPLEMENT_IBASE (csEvent)
  SCF_IMPLEMENTS_INTERFACE (iEvent)
  SCF_IMPLEMENTS_INTERFACE (csEvent)
SCF_IMPLEMENT_IBASE_END

CS_IMPLEMENT_STATIC_VAR(GetEventStrSet, csStringSet, ())

char const* csEvent::GetTypeName (csEventAttributeType t)
{
  switch (t)
  {
    case csEventAttrInt:	    return "int";
    case csEventAttrUInt:	    return "uint";
    case csEventAttrFloat:	    return "double";
    case csEventAttrDatabuffer:	    return "databuffer";
    case csEventAttrEvent:	    return "event";
    case csEventAttriBase:	    return "iBase";
    default:
      break;
  }
  return "unknown";
}

csStringID csEvent::GetKeyID (const char* key)
{
  return GetEventStrSet()->Request (key);
}

const char* csEvent::GetKeyName (csStringID id)
{
  return GetEventStrSet()->Request (id);
}

csEvent::csEvent ()
{
  SCF_CONSTRUCT_IBASE (0);

  count = 0;
}

csEvent::csEvent (csTicks iTime, int eType, int mx, int my,
		  int mButton, int mModifiers) : attributes (53)
{
  SCF_CONSTRUCT_IBASE (0);
  Time = iTime;
  Type = eType;
  Category = SubCategory = Flags = 0;
  Mouse.x = mx;
  Mouse.y = my;
  Mouse.Button = mButton;
  Mouse.Modifiers = mModifiers;

  count = 0;
}

csEvent::csEvent (csTicks iTime, int eType, int jn, int jx, int jy,
		  int jButton, int jModifiers) : attributes (53)
{
  SCF_CONSTRUCT_IBASE (0);
  Time = iTime;
  Type = eType;
  Category = SubCategory = Flags = 0;
  Joystick.number = jn;
  Joystick.x = jx;
  Joystick.y = jy;
  Joystick.Button = jButton;
  Joystick.Modifiers = jModifiers;

  count = 0;
}

csEvent::csEvent (csTicks iTime, int eType, int cCode, intptr_t cInfo) :
  attributes (53)
{
  SCF_CONSTRUCT_IBASE (0);
  Time = iTime;
  Type = eType;
  Category = SubCategory = Flags = 0;
  Command.Code = cCode;
  Command.Info = cInfo;
  if (eType == csevBroadcast)
    Flags = CSEF_BROADCAST;

  count = 0;
}

csEvent::csEvent (csEvent const& e) : iEvent(), attributes (53)
{
  SCF_CONSTRUCT_IBASE (0);
  count = 0;

  Type = e.Type;
  Category = e.Category;
  SubCategory = e.SubCategory;
  Flags = e.Flags;
  Time = e.Time;
  attributes = e.attributes;

  if ((Type & CSMASK_Mouse) != 0)
  {
    Mouse.x = e.Mouse.x;
    Mouse.y = e.Mouse.y;
    Mouse.Button = e.Mouse.Button;
    Mouse.Modifiers = e.Mouse.Modifiers;
  }
  else if ((Type & CSMASK_Joystick) != 0)
  {
    Joystick.number = e.Joystick.number;
    Joystick.x = e.Joystick.x;
    Joystick.y = e.Joystick.y;
    Joystick.Button = e.Joystick.Button;
    Joystick.Modifiers = e.Joystick.Modifiers;
  }
  else
  {
    Command.Code = e.Command.Code;
    Command.Info = e.Command.Info;
  }
}

csEvent::~csEvent ()
{
  RemoveAll();
  SCF_DESTRUCT_IBASE ();
}

bool csEvent::Add (const char *name, float v)
{
  if (attributes.In (GetKeyID (name))) return false;
  attribute* object = new attribute (csEventAttrFloat);
  object->doubleVal = v;
  attributes.Put (GetKeyID (name), object);
  count++;
  return true;
}

bool csEvent::Add (const char *name, double v)
{
  if (attributes.In (GetKeyID (name))) return false;
  attribute* object = new attribute (csEventAttrFloat);
  object->doubleVal = v;
  attributes.Put (GetKeyID (name), object);
  count++;
  return true;
}

bool csEvent::Add (const char *name, bool v)
{
  if (attributes.In (GetKeyID (name))) return false;
  attribute* object = new attribute (csEventAttrInt);
  object->intVal = v ? 1 : 0;
  attributes.Put (GetKeyID (name), object);
  count++;
  return true;
}

bool csEvent::Add (const char *name, const char *v)
{
  if (attributes.In (GetKeyID (name))) return false;
  attribute* object = new attribute (csEventAttrDatabuffer);
  object->dataSize = strlen(v);
  object->bufferVal = csStrNew(v);
  attributes.Put (GetKeyID (name), object);
  count++;
  return true;
}

bool csEvent::Add (const char *name, const void *v, size_t size)
{
  if (attributes.In (GetKeyID (name))) return false;
  attribute* object = new attribute (csEventAttrDatabuffer);
  object->bufferVal = new char[size + 1];
  memcpy (object->bufferVal, v, size);
  object->bufferVal[size] = 0;
  object->dataSize = size;
  attributes.Put (GetKeyID (name), object);
  count++;
  return true;
}

bool csEvent::CheckForLoops (iEvent* current, iEvent* e)
{
  csRef<iEventAttributeIterator> iter (current->GetAttributeIterator());

  while (iter->HasNext())
  {
    const char* attr = iter->Next();

    if (current->GetAttributeType (attr) == csEventAttrEvent)
    {
      csRef<iEvent> ev;
      if (current->Retrieve (attr, ev) != csEventErrNone) continue;
      if (ev == e)
	return false;
      return CheckForLoops(ev, e);
    }
  }
  return true;
}

bool csEvent::Add (const char *name, iEvent *v)
{
  if (attributes.In (GetKeyID (name))) return false;
  if (this == v)
    return false;
  if (v && CheckForLoops(v, this))
  {
    attribute* object = new attribute (csEventAttrEvent);
    (object->ibaseVal = (iBase*)v)->IncRef();
    attributes.Put (GetKeyID (name), object);
    count++;
    return true;
  }
  return false;
}

bool csEvent::Add (const char *name, iBase* v)
{
  if (attributes.In (GetKeyID (name))) return false;
  if (v)
  {
    attribute* object = new attribute (csEventAttriBase);
    (object->ibaseVal = v)->IncRef();
    attributes.Put (GetKeyID (name), object);
    count++;
    return true;
  }
  return false;
}

csEventError csEvent::Retrieve (const char *name, float &v) const
{
  attribute* object = attributes.Get (GetKeyID (name), 0);
  if (!object) return csEventErrNotFound;
  if (object->type == csEventAttrFloat)
  {
    v = object->doubleVal;
    return csEventErrNone;
  }
  else
  {
    return InternalReportMismatch (object);
  }
}

csEventError csEvent::Retrieve (const char *name, double &v) const
{
  attribute* object = attributes.Get (GetKeyID (name), 0);
  if (!object) return csEventErrNotFound;
  if (object->type == csEventAttrFloat)
  {
    v = object->doubleVal;
    return csEventErrNone;
  }
  else
  {
    return InternalReportMismatch (object);
  }
}

csEventError csEvent::Retrieve (const char *name, const char *&v) const
{
  attribute* object = attributes.Get (GetKeyID (name), 0);
  if (!object) return csEventErrNotFound;
  if (object->type == csEventAttrDatabuffer)
  {
    v = object->bufferVal;
    return csEventErrNone;
  }
  else
  {
    return InternalReportMismatch (object);
  }
}

csEventError csEvent::Retrieve (const char *name, void const *&v,
  size_t &size) const
{
  attribute* object = attributes.Get (GetKeyID (name), 0);
  if (!object) return csEventErrNotFound;
  if (object->type == csEventAttrDatabuffer)
  {
    v = object->bufferVal;
    size = object->dataSize;
    return csEventErrNone;
  }
  else
  {
    return InternalReportMismatch (object);
  }
}

csEventError csEvent::Retrieve (const char *name, bool &v) const
{
  attribute* object = attributes.Get (GetKeyID (name), 0);
  if (!object) return csEventErrNotFound;
  if (object->type == csEventAttrInt)
  {
    v = object->intVal != 0;
    return csEventErrNone;
  }
  else
  {
    return InternalReportMismatch (object);
  }
}

csEventError csEvent::Retrieve (const char *name, csRef<iEvent> &v) const
{
  attribute* object = attributes.Get (GetKeyID (name), 0);
  if (!object) return csEventErrNotFound;
  if (object->type == csEventAttrEvent)
  {
    v = (iEvent*)object->ibaseVal;
    return csEventErrNone;
  }
  else
  {
    return InternalReportMismatch (object);
  }
}

csEventError csEvent::Retrieve (const char *name, csRef<iBase> &v) const
{
  attribute* object = attributes.Get (GetKeyID (name), 0);
  if (!object) return csEventErrNotFound;
  if (object->type == csEventAttriBase)
  {
    v = object->ibaseVal;
    return csEventErrNone;
  }
  else
  {
    return InternalReportMismatch (object);
  }
}

bool csEvent::AttributeExists (const char* name)
{
  return attributes.In (GetKeyID (name));
}

csEventAttributeType csEvent::GetAttributeType (const char* name)
{
  attribute* object = attributes.Get (GetKeyID (name), 0);
  if (object)
  {
    return object->type;
  }
  return csEventAttrUnknown;
}

bool csEvent::Remove(const char *name)
{
  csStringID id = GetKeyID (name);
  if (!attributes.In (id)) return false;
  attribute* object = attributes.Get (id, 0);
  bool result = attributes.Delete (id, object);
  delete object;
  return result;
}

bool csEvent::RemoveAll()
{
  csHash<attribute*, csStringID>::GlobalIterator iter (
    attributes.GetIterator ());

  while (iter.HasNext())
  {
    csStringID name;
    attribute* object = iter.Next (name);
    delete object;
  }

  attributes.DeleteAll();
  count = 0;
  return true;
}

csRef<iEventAttributeIterator> csEvent::GetAttributeIterator()
{
  csHash<csEvent::attribute*, csStringID>::GlobalIterator attrIter (
    attributes.GetIterator());
  return csPtr<iEventAttributeIterator> (new csEventAttributeIterator (
    attrIter));
}

static void IndentLevel(int level)
{
  for (int i = 0; i < level; i++)
    csPrintf("\t");
}

bool csEvent::Print (int level)
{
  csHash<attribute*, csStringID>::GlobalIterator iter (
    attributes.GetIterator ());

  while (iter.HasNext())
  {
    csStringID name;
    attribute* object = iter.Next (name);

    IndentLevel(level); csPrintf ("------\n");
    IndentLevel(level); csPrintf ("Name: %s\n", GetKeyName (name));
    IndentLevel(level); csPrintf (" Datatype: %s\n",
	  GetTypeName(object->type));
    if (object->type == csEventAttrEvent)
    {
      IndentLevel(level); csPrintf(" Sub-Event Contents:\n");
      csRef<csEvent> csev = SCF_QUERY_INTERFACE (object->ibaseVal, csEvent);
      if (csev)
	csev->Print(level+1);
      else
      {
	IndentLevel(level+1); csPrintf(" (Not an event!):\n");
      }

    }
    if (object->type == csEventAttrInt)
    {

      IndentLevel(level);
      csPrintf(" Value: %" __CS_PRI64_PREFIX "d\n", object->intVal);
    }
    else if (object->type == csEventAttrUInt)
    {
      IndentLevel(level);
      csPrintf(" Value: %" __CS_PRI64_PREFIX "u\n", object->intVal);
    }
    else if (object->type == csEventAttrFloat)
    {
      IndentLevel(level);
      csPrintf (" Value: %f\n", object->doubleVal);
    }
    else if (object->type == csEventAttrDatabuffer)
    {
      IndentLevel(level); csPrintf(" Value: 0x%p\n", object->bufferVal);
      IndentLevel(level); csPrintf(" Length: %zu\n", object->dataSize);
    }
  }

  return true;
}

csRef<iEvent> csEvent::CreateEvent()
{
  return csPtr<iEvent>(new csEvent());
}

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

SCF_IMPLEMENT_IBASE (csEventAttributeIterator)
  SCF_IMPLEMENTS_INTERFACE (iEventAttributeIterator)
SCF_IMPLEMENT_IBASE_END

const char* csEventAttributeIterator::Next()
{
  csStringID key;
  iterator.Next (key);
  return csEvent::GetKeyName (key);
}

//*****************************************************************************
// csPoolEvent
//*****************************************************************************
csPoolEvent::csPoolEvent(csEventQueue *q)
{
    pool = q;
    next = 0;
}

void csPoolEvent::DecRef()
{
  if (scfRefCount == 1)
  {
    if (!pool.IsValid())
      return;

    next = pool->EventPool;
    pool->EventPool = this;
    RemoveAll();
    Type = 0;
    Category = 0;
    Flags = 0;
    Time = 0;
    SubCategory = 0;
    Command.Code = 0;
    Command.Info = 0;
  }
  else
  {
    scfRefCount--;
  }
}

csRef<iEvent> csPoolEvent::CreateEvent()
{
  if (pool.IsValid())
    return pool->CreateEvent(0);
  return superclass::CreateEvent();
}
<|endoftext|>


<commit_before><commit_msg>fix 'dark image' bug in imwri<commit_after><|endoftext|>