<commit_before>/*************************************************************************
 *
 *  OpenOffice.org - a multi-platform office productivity suite
 *
 *  $RCSfile: EventOASISTContext.cxx,v $
 *
 *  $Revision: 1.5 $
 *
 *  last change: $Author: rt $ $Date: 2005-09-09 15:42:23 $
 *
 *  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_EVENTOASISTCONTEXT_HXX
#include "EventOASISTContext.hxx"
#endif
#ifndef _XMLOFF_EVENTMAP_HXX
#include "EventMap.hxx"
#endif
#ifndef _XMLOFF_MUTABLEATTRLIST_HXX
#include "MutableAttrList.hxx"
#endif
#ifndef _XMLOFF_XMLNMSPE_HXX
#include "xmlnmspe.hxx"
#endif
#ifndef _XMLOFF_ACTIONMAPTYPESOASIS_HXX
#include "ActionMapTypesOASIS.hxx"
#endif
#ifndef _XMLOFF_ATTRTRANSFORMERACTION_HXX
#include "AttrTransformerAction.hxx"
#endif
#ifndef _XMLOFF_TRANSFORMERACTIONS_HXX
#include "TransformerActions.hxx"
#endif
#ifndef _XMLOFF_TRANSFORMERBASE_HXX
#include "TransformerBase.hxx"
#endif

#ifndef OASIS_FILTER_OOO_1X
// Used to parse Scripting Framework URLs
#ifndef _COM_SUN_STAR_URI_XURIREFERENCEFACTORY_HPP_
#include <com/sun/star/uri/XUriReferenceFactory.hpp>
#endif
#ifndef _COM_SUN_STAR_URI_XVNDSUNSTARSCRIPTURL_HPP_
#include <com/sun/star/uri/XVndSunStarScriptUrl.hpp>
#endif
#include <comphelper/processfactory.hxx>
#endif

#include <hash_map>

using namespace ::rtl;
using namespace ::com::sun::star::uno;
using namespace ::com::sun::star::xml::sax;
using namespace ::xmloff::token;

class XMLTransformerOASISEventMap_Impl:
    public ::std::hash_map< NameKey_Impl, ::rtl::OUString,
                            NameHash_Impl, NameHash_Impl >
{
public:
    XMLTransformerOASISEventMap_Impl( XMLTransformerEventMapEntry *pInit );
    ~XMLTransformerOASISEventMap_Impl();
};

XMLTransformerOASISEventMap_Impl::XMLTransformerOASISEventMap_Impl( XMLTransformerEventMapEntry *pInit )
{
    if( pInit )
    {
        XMLTransformerOASISEventMap_Impl::key_type aKey;
        XMLTransformerOASISEventMap_Impl::data_type aData;
        while( pInit->m_pOASISName )
        {
            aKey.m_nPrefix = pInit->m_nOASISPrefix;
            aKey.m_aLocalName = OUString::createFromAscii(pInit->m_pOASISName);

            OSL_ENSURE( find( aKey ) == end(), "duplicate event map entry" );

            aData = OUString::createFromAscii(pInit->m_pOOoName);

            XMLTransformerOASISEventMap_Impl::value_type aVal( aKey, aData );

            insert( aVal );
            ++pInit;
        }
    }
}

XMLTransformerOASISEventMap_Impl::~XMLTransformerOASISEventMap_Impl()
{
}

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

TYPEINIT1( XMLEventOASISTransformerContext, XMLRenameElemTransformerContext);

XMLEventOASISTransformerContext::XMLEventOASISTransformerContext(
        XMLTransformerBase& rImp,
        const OUString& rQName ) :
    XMLRenameElemTransformerContext( rImp, rQName,
         rImp.GetNamespaceMap().GetKeyByAttrName( rQName ), XML_EVENT )
{
}

XMLEventOASISTransformerContext::~XMLEventOASISTransformerContext()
{
}

XMLTransformerOASISEventMap_Impl
    *XMLEventOASISTransformerContext::CreateEventMap()
{
    return new XMLTransformerOASISEventMap_Impl( aTransformerEventMap );
}

XMLTransformerOASISEventMap_Impl
    *XMLEventOASISTransformerContext::CreateFormEventMap()
{
    return new XMLTransformerOASISEventMap_Impl( aFormTransformerEventMap );
}

void XMLEventOASISTransformerContext::FlushEventMap(
        XMLTransformerOASISEventMap_Impl *p )
{
    delete p;
}

OUString XMLEventOASISTransformerContext::GetEventName(
        sal_uInt16 nPrefix,
        const OUString& rName,
           XMLTransformerOASISEventMap_Impl& rMap,
           XMLTransformerOASISEventMap_Impl *pMap2)
{
    XMLTransformerOASISEventMap_Impl::key_type aKey( nPrefix, rName );
    if( pMap2 )
    {
        XMLTransformerOASISEventMap_Impl::const_iterator aIter =
            pMap2->find( aKey );
        if( !(aIter == pMap2->end()) )
            return (*aIter).second;
    }

    XMLTransformerOASISEventMap_Impl::const_iterator aIter = rMap.find( aKey );
    if( aIter == rMap.end() )
        return rName;
    else
        return (*aIter).second;
}

bool ParseURLAsString(
    const OUString& rAttrValue,
    OUString* pName, OUString* pLocation )
{
    OUString SCHEME( RTL_CONSTASCII_USTRINGPARAM( "vnd.sun.star.script:" ) );

    sal_Int32 params = rAttrValue.indexOf( '?' );
    if ( rAttrValue.indexOf( SCHEME ) != 0 || params < 0 )
    {
        return FALSE;
    }

    sal_Int32 start = SCHEME.getLength();
    *pName = rAttrValue.copy( start, params - start );

    OUString aToken;
    OUString aLanguage;
    params++;
    do
    {
        aToken = rAttrValue.getToken( 0, '&', params );
        sal_Int32 dummy = 0;

        if ( aToken.match( GetXMLToken( XML_LANGUAGE ) ) )
        {
            aLanguage = aToken.getToken( 1, '=', dummy );
        }
        else if ( aToken.match( GetXMLToken( XML_LOCATION ) ) )
        {
            OUString tmp = aToken.getToken( 1, '=', dummy );
            if ( tmp.equalsIgnoreAsciiCase( GetXMLToken( XML_DOCUMENT ) ) )
            {
                *pLocation = GetXMLToken( XML_DOCUMENT );
            }
            else
            {
                *pLocation = GetXMLToken( XML_APPLICATION );
            }
        }
    } while ( params >= 0 );

    if ( aLanguage.equalsIgnoreAsciiCaseAscii( "basic" ) )
    {
        return TRUE;
    }
    return FALSE;
}

bool ParseURL(
    const OUString& rAttrValue,
    OUString* pName, OUString* pLocation )
{
#ifdef OASIS_FILTER_OOO_1X
    return ParseURLAsString( rAttrValue, pName, pLocation );
#else
    Reference< com::sun::star::lang::XMultiServiceFactory >
        xSMgr = ::comphelper::getProcessServiceFactory();

    Reference< com::sun::star::uri::XUriReferenceFactory >
        xFactory( xSMgr->createInstance( OUString::createFromAscii(
            "com.sun.star.uri.UriReferenceFactory" ) ), UNO_QUERY );

    if ( xFactory.is() )
    {
        Reference< com::sun::star::uri::XVndSunStarScriptUrl > xUrl (
            xFactory->parse( rAttrValue ), UNO_QUERY );

        if ( xUrl.is() )
        {
            OUString aLanguageKey = GetXMLToken( XML_LANGUAGE );
            if ( xUrl.is() && xUrl->hasParameter( aLanguageKey ) )
            {
                OUString aLanguage = xUrl->getParameter( aLanguageKey );

                if ( aLanguage.equalsIgnoreAsciiCaseAscii( "basic" ) )
                {
                    *pName = xUrl->getName();

                    OUString tmp =
                        xUrl->getParameter( GetXMLToken( XML_LOCATION ) );

                    OUString doc = GetXMLToken( XML_DOCUMENT );

                    if ( tmp.equalsIgnoreAsciiCase( doc ) )
                    {
                        *pLocation = doc;
                    }
                    else
                    {
                        *pLocation = GetXMLToken( XML_APPLICATION );
                    }
                    return TRUE;
                }
            }
        }
        return FALSE;
    }
    else
    {
        return ParseURLAsString( rAttrValue, pName, pLocation );
    }
#endif
}

void XMLEventOASISTransformerContext::StartElement(
    const Reference< XAttributeList >& rAttrList )
{
    OSL_TRACE("XMLEventOASISTransformerContext::StartElement");

    XMLTransformerActions *pActions =
        GetTransformer().GetUserDefinedActions( OASIS_EVENT_ACTIONS );
    OSL_ENSURE( pActions, "go no actions" );

    Reference< XAttributeList > xAttrList( rAttrList );
    XMLMutableAttributeList *pMutableAttrList = 0;
    sal_Int16 nAttrCount = xAttrList.is() ? xAttrList->getLength() : 0;
    for( sal_Int16 i=0; i < nAttrCount; i++ )
    {
        const OUString& rAttrName = xAttrList->getNameByIndex( i );
        OUString aLocalName;
        sal_uInt16 nPrefix =
            GetTransformer().GetNamespaceMap().GetKeyByAttrName( rAttrName,
                                                                 &aLocalName );
        XMLTransformerActions::key_type aKey( nPrefix, aLocalName );
        XMLTransformerActions::const_iterator aIter =
            pActions->find( aKey );
        if( !(aIter == pActions->end() ) )
        {
            if( !pMutableAttrList )
            {
                pMutableAttrList =
                        new XMLMutableAttributeList( xAttrList );
                xAttrList = pMutableAttrList;
            }
            const OUString& rAttrValue = xAttrList->getValueByIndex( i );
            switch( (*aIter).second.m_nActionType )
            {
            case XML_ATACTION_HREF:
                {
                    OUString aAttrValue( rAttrValue );
                    OUString aName, aLocation;

                    bool bNeedsTransform =
                        ParseURL( rAttrValue, &aName, &aLocation );

                    if ( bNeedsTransform )
                    {
                        pMutableAttrList->RemoveAttributeByIndex( i );

                        OUString aAttrQName(
                            GetTransformer().GetNamespaceMap().GetQNameByKey(
                                XML_NAMESPACE_SCRIPT,
                            ::xmloff::token::GetXMLToken( XML_MACRO_NAME ) ) );

                        pMutableAttrList->AddAttribute( aAttrQName, aName );

                        sal_Int16 idx = pMutableAttrList->GetIndexByName(
                            GetTransformer().GetNamespaceMap().GetQNameByKey(
                                XML_NAMESPACE_SCRIPT,
                            GetXMLToken( XML_LANGUAGE ) ) );

                        pMutableAttrList->SetValueByIndex( idx,
                            OUString::createFromAscii("StarBasic") );

                        OUString aLocQName(
                            GetTransformer().GetNamespaceMap().GetQNameByKey(
                                XML_NAMESPACE_SCRIPT,
                                GetXMLToken( XML_LOCATION ) ) );

                        pMutableAttrList->AddAttribute( aLocQName, aLocation );
                    }
                }
                break;
            case XML_ATACTION_EVENT_NAME:
                {
                    // Check if the event belongs to a form or control by
                    // cehcking the 2nd ancestor element, f.i.:
                    // <form:button><form:event-listeners><form:event-listener>
                    const XMLTransformerContext *pObjContext =
                        GetTransformer().GetAncestorContext( 1 );
                    sal_Bool bForm = pObjContext &&

                        pObjContext->HasNamespace(XML_NAMESPACE_FORM );
                    pMutableAttrList->SetValueByIndex( i,
                                   GetTransformer().GetEventName( rAttrValue,
                                                                    bForm ) );
                }
                break;
            case XML_ATACTION_REMOVE_NAMESPACE_PREFIX:
                {
                    OUString aAttrValue( rAttrValue );
                    sal_uInt16 nValPrefix =
                        static_cast<sal_uInt16>((*aIter).second.m_nParam1);
                    if( GetTransformer().RemoveNamespacePrefix(
                                aAttrValue, nValPrefix ) )
                        pMutableAttrList->SetValueByIndex( i, aAttrValue );
                }
                break;
            case XML_ATACTION_MACRO_NAME:
                {
                    OUString aName, aLocation;
                    bool bNeedsTransform =
                        ParseURL( rAttrValue, &aName, &aLocation );

                    if ( bNeedsTransform )
                    {
                        pMutableAttrList->SetValueByIndex( i, aName );

                        sal_Int16 idx = pMutableAttrList->GetIndexByName(
                            GetTransformer().GetNamespaceMap().GetQNameByKey(
                                XML_NAMESPACE_SCRIPT,
                            GetXMLToken( XML_LANGUAGE ) ) );

                        pMutableAttrList->SetValueByIndex( idx,
                            OUString::createFromAscii("StarBasic") );

                        OUString aLocQName(
                            GetTransformer().GetNamespaceMap().GetQNameByKey(
                                XML_NAMESPACE_SCRIPT,
                                GetXMLToken( XML_LOCATION ) ) );

                        pMutableAttrList->AddAttribute( aLocQName, aLocation );
                    }
                    else
                    {
                    const OUString& rApp = GetXMLToken( XML_APPLICATION );
                    const OUString& rDoc = GetXMLToken( XML_DOCUMENT );
                    OUString aLocation;
                    OUString aAttrValue;
                    if( rAttrValue.getLength() > rApp.getLength()+1 &&
                        rAttrValue.copy(0,rApp.getLength()).
                                    equalsIgnoreAsciiCase( rApp ) &&
                        ':' == rAttrValue[rApp.getLength()] )
                    {
                        aLocation = rApp;
                        aAttrValue = rAttrValue.copy( rApp.getLength()+1 );
                    }
                    else if( rAttrValue.getLength() > rDoc.getLength()+1 &&
                             rAttrValue.copy(0,rDoc.getLength()).
                                     equalsIgnoreAsciiCase( rDoc ) &&
                        ':' == rAttrValue[rDoc.getLength()] )
                    {
                        aLocation= rDoc;
                        aAttrValue = rAttrValue.copy( rDoc.getLength()+1 );
                    }
                    if( aAttrValue.getLength() )
                        pMutableAttrList->SetValueByIndex( i,
                                            aAttrValue );
                    if( aLocation.getLength() )
                    {
                        OUString aAttrQName( GetTransformer().GetNamespaceMap().
                                GetQNameByKey( XML_NAMESPACE_SCRIPT,
                            ::xmloff::token::GetXMLToken( XML_LOCATION ) ) );
                        pMutableAttrList->AddAttribute( aAttrQName, aLocation );
                        // draw bug
                        aAttrQName = GetTransformer().GetNamespaceMap().
                                GetQNameByKey( XML_NAMESPACE_SCRIPT,
                            ::xmloff::token::GetXMLToken( XML_LIBRARY ) );
                        pMutableAttrList->AddAttribute( aAttrQName, aLocation );
                    }
                    }
                }
                break;
            case XML_ATACTION_COPY:
                break;
            default:
                OSL_ENSURE( !this, "unknown action" );
                break;
            }
        }
    }

    XMLRenameElemTransformerContext::StartElement( xAttrList );
}
<commit_msg>INTEGRATION: CWS warnings01 (1.5.32); FILE MERGED 2005/11/17 16:33:57 pl 1.5.32.1: #i55991# removed warnings<commit_after>/*************************************************************************
 *
 *  OpenOffice.org - a multi-platform office productivity suite
 *
 *  $RCSfile: EventOASISTContext.cxx,v $
 *
 *  $Revision: 1.6 $
 *
 *  last change: $Author: hr $ $Date: 2006-06-19 18:52:28 $
 *
 *  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_EVENTOASISTCONTEXT_HXX
#include "EventOASISTContext.hxx"
#endif
#ifndef _XMLOFF_EVENTMAP_HXX
#include "EventMap.hxx"
#endif
#ifndef _XMLOFF_MUTABLEATTRLIST_HXX
#include "MutableAttrList.hxx"
#endif
#ifndef _XMLOFF_XMLNMSPE_HXX
#include "xmlnmspe.hxx"
#endif
#ifndef _XMLOFF_ACTIONMAPTYPESOASIS_HXX
#include "ActionMapTypesOASIS.hxx"
#endif
#ifndef _XMLOFF_ATTRTRANSFORMERACTION_HXX
#include "AttrTransformerAction.hxx"
#endif
#ifndef _XMLOFF_TRANSFORMERACTIONS_HXX
#include "TransformerActions.hxx"
#endif
#ifndef _XMLOFF_TRANSFORMERBASE_HXX
#include "TransformerBase.hxx"
#endif

#ifndef OASIS_FILTER_OOO_1X
// Used to parse Scripting Framework URLs
#ifndef _COM_SUN_STAR_URI_XURIREFERENCEFACTORY_HPP_
#include <com/sun/star/uri/XUriReferenceFactory.hpp>
#endif
#ifndef _COM_SUN_STAR_URI_XVNDSUNSTARSCRIPTURL_HPP_
#include <com/sun/star/uri/XVndSunStarScriptUrl.hpp>
#endif
#include <comphelper/processfactory.hxx>
#endif

#include <hash_map>

using namespace ::rtl;
using namespace ::com::sun::star::uno;
using namespace ::com::sun::star::xml::sax;
using namespace ::xmloff::token;

class XMLTransformerOASISEventMap_Impl:
    public ::std::hash_map< NameKey_Impl, ::rtl::OUString,
                            NameHash_Impl, NameHash_Impl >
{
public:
    XMLTransformerOASISEventMap_Impl( XMLTransformerEventMapEntry *pInit );
    ~XMLTransformerOASISEventMap_Impl();
};

XMLTransformerOASISEventMap_Impl::XMLTransformerOASISEventMap_Impl( XMLTransformerEventMapEntry *pInit )
{
    if( pInit )
    {
        XMLTransformerOASISEventMap_Impl::key_type aKey;
        XMLTransformerOASISEventMap_Impl::data_type aData;
        while( pInit->m_pOASISName )
        {
            aKey.m_nPrefix = pInit->m_nOASISPrefix;
            aKey.m_aLocalName = OUString::createFromAscii(pInit->m_pOASISName);

            OSL_ENSURE( find( aKey ) == end(), "duplicate event map entry" );

            aData = OUString::createFromAscii(pInit->m_pOOoName);

            XMLTransformerOASISEventMap_Impl::value_type aVal( aKey, aData );

            insert( aVal );
            ++pInit;
        }
    }
}

XMLTransformerOASISEventMap_Impl::~XMLTransformerOASISEventMap_Impl()
{
}

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

TYPEINIT1( XMLEventOASISTransformerContext, XMLRenameElemTransformerContext);

XMLEventOASISTransformerContext::XMLEventOASISTransformerContext(
        XMLTransformerBase& rImp,
        const OUString& rQName ) :
    XMLRenameElemTransformerContext( rImp, rQName,
         rImp.GetNamespaceMap().GetKeyByAttrName( rQName ), XML_EVENT )
{
}

XMLEventOASISTransformerContext::~XMLEventOASISTransformerContext()
{
}

XMLTransformerOASISEventMap_Impl
    *XMLEventOASISTransformerContext::CreateEventMap()
{
    return new XMLTransformerOASISEventMap_Impl( aTransformerEventMap );
}

XMLTransformerOASISEventMap_Impl
    *XMLEventOASISTransformerContext::CreateFormEventMap()
{
    return new XMLTransformerOASISEventMap_Impl( aFormTransformerEventMap );
}

void XMLEventOASISTransformerContext::FlushEventMap(
        XMLTransformerOASISEventMap_Impl *p )
{
    delete p;
}

OUString XMLEventOASISTransformerContext::GetEventName(
        sal_uInt16 nPrefix,
        const OUString& rName,
           XMLTransformerOASISEventMap_Impl& rMap,
           XMLTransformerOASISEventMap_Impl *pMap2)
{
    XMLTransformerOASISEventMap_Impl::key_type aKey( nPrefix, rName );
    if( pMap2 )
    {
        XMLTransformerOASISEventMap_Impl::const_iterator aIter =
            pMap2->find( aKey );
        if( !(aIter == pMap2->end()) )
            return (*aIter).second;
    }

    XMLTransformerOASISEventMap_Impl::const_iterator aIter = rMap.find( aKey );
    if( aIter == rMap.end() )
        return rName;
    else
        return (*aIter).second;
}

bool ParseURLAsString(
    const OUString& rAttrValue,
    OUString* pName, OUString* pLocation )
{
    OUString SCHEME( RTL_CONSTASCII_USTRINGPARAM( "vnd.sun.star.script:" ) );

    sal_Int32 params = rAttrValue.indexOf( '?' );
    if ( rAttrValue.indexOf( SCHEME ) != 0 || params < 0 )
    {
        return FALSE;
    }

    sal_Int32 start = SCHEME.getLength();
    *pName = rAttrValue.copy( start, params - start );

    OUString aToken;
    OUString aLanguage;
    params++;
    do
    {
        aToken = rAttrValue.getToken( 0, '&', params );
        sal_Int32 dummy = 0;

        if ( aToken.match( GetXMLToken( XML_LANGUAGE ) ) )
        {
            aLanguage = aToken.getToken( 1, '=', dummy );
        }
        else if ( aToken.match( GetXMLToken( XML_LOCATION ) ) )
        {
            OUString tmp = aToken.getToken( 1, '=', dummy );
            if ( tmp.equalsIgnoreAsciiCase( GetXMLToken( XML_DOCUMENT ) ) )
            {
                *pLocation = GetXMLToken( XML_DOCUMENT );
            }
            else
            {
                *pLocation = GetXMLToken( XML_APPLICATION );
            }
        }
    } while ( params >= 0 );

    if ( aLanguage.equalsIgnoreAsciiCaseAscii( "basic" ) )
    {
        return TRUE;
    }
    return FALSE;
}

bool ParseURL(
    const OUString& rAttrValue,
    OUString* pName, OUString* pLocation )
{
#ifdef OASIS_FILTER_OOO_1X
    return ParseURLAsString( rAttrValue, pName, pLocation );
#else
    Reference< com::sun::star::lang::XMultiServiceFactory >
        xSMgr = ::comphelper::getProcessServiceFactory();

    Reference< com::sun::star::uri::XUriReferenceFactory >
        xFactory( xSMgr->createInstance( OUString::createFromAscii(
            "com.sun.star.uri.UriReferenceFactory" ) ), UNO_QUERY );

    if ( xFactory.is() )
    {
        Reference< com::sun::star::uri::XVndSunStarScriptUrl > xUrl (
            xFactory->parse( rAttrValue ), UNO_QUERY );

        if ( xUrl.is() )
        {
            OUString aLanguageKey = GetXMLToken( XML_LANGUAGE );
            if ( xUrl.is() && xUrl->hasParameter( aLanguageKey ) )
            {
                OUString aLanguage = xUrl->getParameter( aLanguageKey );

                if ( aLanguage.equalsIgnoreAsciiCaseAscii( "basic" ) )
                {
                    *pName = xUrl->getName();

                    OUString tmp =
                        xUrl->getParameter( GetXMLToken( XML_LOCATION ) );

                    OUString doc = GetXMLToken( XML_DOCUMENT );

                    if ( tmp.equalsIgnoreAsciiCase( doc ) )
                    {
                        *pLocation = doc;
                    }
                    else
                    {
                        *pLocation = GetXMLToken( XML_APPLICATION );
                    }
                    return TRUE;
                }
            }
        }
        return FALSE;
    }
    else
    {
        return ParseURLAsString( rAttrValue, pName, pLocation );
    }
#endif
}

void XMLEventOASISTransformerContext::StartElement(
    const Reference< XAttributeList >& rAttrList )
{
    OSL_TRACE("XMLEventOASISTransformerContext::StartElement");

    XMLTransformerActions *pActions =
        GetTransformer().GetUserDefinedActions( OASIS_EVENT_ACTIONS );
    OSL_ENSURE( pActions, "go no actions" );

    Reference< XAttributeList > xAttrList( rAttrList );
    XMLMutableAttributeList *pMutableAttrList = 0;
    sal_Int16 nAttrCount = xAttrList.is() ? xAttrList->getLength() : 0;
    for( sal_Int16 i=0; i < nAttrCount; i++ )
    {
        const OUString& rAttrName = xAttrList->getNameByIndex( i );
        OUString aLocalName;
        sal_uInt16 nPrefix =
            GetTransformer().GetNamespaceMap().GetKeyByAttrName( rAttrName,
                                                                 &aLocalName );
        XMLTransformerActions::key_type aKey( nPrefix, aLocalName );
        XMLTransformerActions::const_iterator aIter =
            pActions->find( aKey );
        if( !(aIter == pActions->end() ) )
        {
            if( !pMutableAttrList )
            {
                pMutableAttrList =
                        new XMLMutableAttributeList( xAttrList );
                xAttrList = pMutableAttrList;
            }
            const OUString& rAttrValue = xAttrList->getValueByIndex( i );
            switch( (*aIter).second.m_nActionType )
            {
            case XML_ATACTION_HREF:
                {
                    OUString aAttrValue( rAttrValue );
                    OUString aName, aLocation;

                    bool bNeedsTransform =
                        ParseURL( rAttrValue, &aName, &aLocation );

                    if ( bNeedsTransform )
                    {
                        pMutableAttrList->RemoveAttributeByIndex( i );

                        OUString aAttrQName(
                            GetTransformer().GetNamespaceMap().GetQNameByKey(
                                XML_NAMESPACE_SCRIPT,
                            ::xmloff::token::GetXMLToken( XML_MACRO_NAME ) ) );

                        pMutableAttrList->AddAttribute( aAttrQName, aName );

                        sal_Int16 idx = pMutableAttrList->GetIndexByName(
                            GetTransformer().GetNamespaceMap().GetQNameByKey(
                                XML_NAMESPACE_SCRIPT,
                            GetXMLToken( XML_LANGUAGE ) ) );

                        pMutableAttrList->SetValueByIndex( idx,
                            OUString::createFromAscii("StarBasic") );

                        OUString aLocQName(
                            GetTransformer().GetNamespaceMap().GetQNameByKey(
                                XML_NAMESPACE_SCRIPT,
                                GetXMLToken( XML_LOCATION ) ) );

                        pMutableAttrList->AddAttribute( aLocQName, aLocation );
                    }
                }
                break;
            case XML_ATACTION_EVENT_NAME:
                {
                    // Check if the event belongs to a form or control by
                    // cehcking the 2nd ancestor element, f.i.:
                    // <form:button><form:event-listeners><form:event-listener>
                    const XMLTransformerContext *pObjContext =
                        GetTransformer().GetAncestorContext( 1 );
                    sal_Bool bForm = pObjContext &&

                        pObjContext->HasNamespace(XML_NAMESPACE_FORM );
                    pMutableAttrList->SetValueByIndex( i,
                                   GetTransformer().GetEventName( rAttrValue,
                                                                    bForm ) );
                }
                break;
            case XML_ATACTION_REMOVE_NAMESPACE_PREFIX:
                {
                    OUString aAttrValue( rAttrValue );
                    sal_uInt16 nValPrefix =
                        static_cast<sal_uInt16>((*aIter).second.m_nParam1);
                    if( GetTransformer().RemoveNamespacePrefix(
                                aAttrValue, nValPrefix ) )
                        pMutableAttrList->SetValueByIndex( i, aAttrValue );
                }
                break;
            case XML_ATACTION_MACRO_NAME:
            {
                OUString aName, aLocation;
                bool bNeedsTransform =
                ParseURL( rAttrValue, &aName, &aLocation );

                if ( bNeedsTransform )
                {
                    pMutableAttrList->SetValueByIndex( i, aName );

                    sal_Int16 idx = pMutableAttrList->GetIndexByName(
                    GetTransformer().GetNamespaceMap().GetQNameByKey(
                    XML_NAMESPACE_SCRIPT,
                    GetXMLToken( XML_LANGUAGE ) ) );

                    pMutableAttrList->SetValueByIndex( idx,
                    OUString::createFromAscii("StarBasic") );

                    OUString aLocQName(
                    GetTransformer().GetNamespaceMap().GetQNameByKey(
                    XML_NAMESPACE_SCRIPT,
                    GetXMLToken( XML_LOCATION ) ) );

                    pMutableAttrList->AddAttribute( aLocQName, aLocation );
                }
                else
                {
                    const OUString& rApp = GetXMLToken( XML_APPLICATION );
                    const OUString& rDoc = GetXMLToken( XML_DOCUMENT );
                    OUString aAttrValue;
                    if( rAttrValue.getLength() > rApp.getLength()+1 &&
                        rAttrValue.copy(0,rApp.getLength()).
                            equalsIgnoreAsciiCase( rApp ) &&
                        ':' == rAttrValue[rApp.getLength()] )
                    {
                        aLocation = rApp;
                        aAttrValue = rAttrValue.copy( rApp.getLength()+1 );
                    }
                    else if( rAttrValue.getLength() > rDoc.getLength()+1 &&
                             rAttrValue.copy(0,rDoc.getLength()).
                                equalsIgnoreAsciiCase( rDoc ) &&
                             ':' == rAttrValue[rDoc.getLength()] )
                    {
                        aLocation= rDoc;
                        aAttrValue = rAttrValue.copy( rDoc.getLength()+1 );
                    }
                    if( aAttrValue.getLength() )
                        pMutableAttrList->SetValueByIndex( i,
                    aAttrValue );
                    if( aLocation.getLength() )
                    {
                        OUString aAttrQName( GetTransformer().GetNamespaceMap().
                        GetQNameByKey( XML_NAMESPACE_SCRIPT,
                        ::xmloff::token::GetXMLToken( XML_LOCATION ) ) );
                        pMutableAttrList->AddAttribute( aAttrQName, aLocation );
                        // draw bug
                        aAttrQName = GetTransformer().GetNamespaceMap().
                        GetQNameByKey( XML_NAMESPACE_SCRIPT,
                        ::xmloff::token::GetXMLToken( XML_LIBRARY ) );
                        pMutableAttrList->AddAttribute( aAttrQName, aLocation );
                    }
                }
            }
            break;
            case XML_ATACTION_COPY:
                break;
            default:
                OSL_ENSURE( !this, "unknown action" );
                break;
            }
        }
    }

    XMLRenameElemTransformerContext::StartElement( xAttrList );
}
<|endoftext|>


<commit_before>#define TRACE_PARAMETERS 0
#define TRACE_CONSTRUCTORS_DESTRUCTORS 0
#define Y_IS_Z 1

#if BUILD_OPENAL
#include <AL/al.h>
#include <AL/alc.h>
#include <AL/alext.h>
#include <AL/efx.h>
#endif

#include "augs/math/vec2.h"
#include "augs/math/si_scaling.h"

#include "augs/audio/sound_source.h"
#include "augs/audio/sound_buffer.h"

#include "augs/audio/OpenAL_error.h"

#if TRACE_CONSTRUCTORS_DESTRUCTORS
int g_num_sources = 0;
#endif

namespace augs {
	sound_source::sound_source() {
#if BUILD_OPENAL
		alGenSources(1, &id);
		const ALenum err { alGetError() };

		if (err == AL_OUT_OF_MEMORY) {
			throw too_many_sound_sources_error();
		}
#endif

#if TRACE_CONSTRUCTORS_DESTRUCTORS
		++g_num_sources;
		LOG("alGenSources: %x (now %x sources)", id, g_num_sources);
#endif
		AL_CHECK(alSourcef(id, AL_PITCH, 1));
		AL_CHECK(alSourcef(id, AL_GAIN, 1));
		AL_CHECK(alSourcei(id, AL_LOOPING, AL_FALSE));

		initialized = true;
	}

	sound_source::~sound_source() {
		destroy();
	}

	sound_source::sound_source(sound_source&& b) :
		initialized(b.initialized),
		id(b.id),
		attached_buffer(b.attached_buffer)
	{
		b.initialized = false;
	}

	sound_source& sound_source::operator=(sound_source&& b) {
		destroy();

		initialized = b.initialized;
		id = b.id;
		attached_buffer = b.attached_buffer;

		b.initialized = false;

		return *this;
	}

	void sound_source::destroy() {
		if (initialized) {
			stop();
#if TRACE_CONSTRUCTORS_DESTRUCTORS
			--g_num_sources;
			LOG("alDeleteSources: %x (now %x sources)", id, g_num_sources);
#endif
			AL_CHECK(alDeleteSources(1, &id));
			initialized = false;
			attached_buffer = nullptr;
		}
	}

	ALuint sound_source::get_id() const {
		return id;
	}

	sound_source::operator ALuint() const {
		return get_id();
	}

	void sound_source::play() const {
		AL_CHECK(alSourcePlay(id));
	}

	void sound_source::seek_to(const float seconds) const {
		(void)seconds;
		AL_CHECK(alSourcef(id, AL_SEC_OFFSET, seconds));
	}

	float sound_source::get_time_in_seconds() const {
		float seconds = 0.f;
		AL_CHECK(alGetSourcef(id, AL_SEC_OFFSET, &seconds));
		return seconds;
	}

	void sound_source::stop() const {
		AL_CHECK(alSourceStop(id));
	}

	void sound_source::set_looping(const bool loop) const {
		(void)loop;
		AL_CHECK(alSourcei(id, AL_LOOPING, loop));
#if TRACE_PARAMETERS
		LOG_NVPS(loop);
#endif
	}

	void sound_source::set_distance_model(const distance_model model) {
#if BUILD_OPENAL
		ALint resolved;

		switch (model) {
			case distance_model::INVERSE_DISTANCE: resolved = AL_INVERSE_DISTANCE; break;
			case distance_model::INVERSE_DISTANCE_CLAMPED: resolved = AL_INVERSE_DISTANCE_CLAMPED; break;
			case distance_model::LINEAR_DISTANCE: resolved = AL_LINEAR_DISTANCE; break;
			case distance_model::LINEAR_DISTANCE_CLAMPED: resolved = AL_LINEAR_DISTANCE_CLAMPED; break;
			case distance_model::EXPONENT_DISTANCE: resolved = AL_EXPONENT_DISTANCE; break;
			case distance_model::EXPONENT_DISTANCE_CLAMPED: resolved = AL_EXPONENT_DISTANCE_CLAMPED; break;
			default: resolved = AL_NONE; break;
		}

		AL_CHECK(alSourcei(id, AL_DISTANCE_MODEL, resolved));
#else
		(void)model;
#endif
	}

	void sound_source::set_rolloff_factor(const float factor) const {
		(void)factor;
		AL_CHECK(alSourcef(id, AL_ROLLOFF_FACTOR, factor));
	}

	void sound_source::set_doppler_factor(const float factor) const {
		(void)factor;
		AL_CHECK(alSourcef(id, AL_DOPPLER_FACTOR, std::clamp(factor, 0.f, 1.f)));
	}

	void sound_source::set_spatialize(const bool f) const {
		AL_CHECK(alSourcei(id, AL_SOURCE_SPATIALIZE_SOFT, f ? AL_TRUE : AL_FALSE));
	}

	void sound_source::set_pitch(const float pitch) const {
		(void)pitch;
		AL_CHECK(alSourcef(id, AL_PITCH, pitch));
#if TRACE_PARAMETERS
		LOG_NVPS(pitch);
#endif
	}

	void sound_source::set_gain(const float gain) const {
		(void)gain;
		AL_CHECK(alSourcef(id, AL_GAIN, gain));
#if TRACE_PARAMETERS
		LOG_NVPS(gain);
#endif
	}

	void sound_source::set_air_absorption_factor(const float absorption) const {
		(void)absorption;
		AL_CHECK(alSourcef(id, AL_AIR_ABSORPTION_FACTOR, absorption));
#if TRACE_PARAMETERS
		LOG_NVPS(absorption);
#endif
	}

	void sound_source::set_velocity(const si_scaling si, vec2 v) const {
		v = si.get_meters(v);
#if Y_IS_Z
		AL_CHECK(alSource3f(id, AL_VELOCITY, v.x, 0.f, v.y));
#else
		AL_CHECK(alSource3f(id, AL_VELOCITY, v.x, v.y, 0.f));
#endif
#if TRACE_PARAMETERS
		LOG_NVPS(v);
#endif
	}

	void sound_source::set_position(const si_scaling si, vec2 pos) const {
		pos = si.get_meters(pos);

#if Y_IS_Z
		AL_CHECK(alSource3f(id, AL_POSITION, pos.x, 0.f, pos.y));
#else
		AL_CHECK(alSource3f(id, AL_POSITION, pos.x, pos.y, 0.f));
#endif
#if TRACE_PARAMETERS
		LOG_NVPS(pos);
#endif
	}

	void sound_source::set_max_distance(const si_scaling si, const float distance) const {
		const auto passed_distance = si.get_meters(distance);

		(void)passed_distance;
		AL_CHECK(alSourcef(id, AL_MAX_DISTANCE, passed_distance));
#if TRACE_PARAMETERS
		LOG_NVPS(passed_distance);
#endif
	}

	void sound_source::set_relative(const bool f) const {
		AL_CHECK(alSourcei(id, AL_SOURCE_RELATIVE, f ? 1 : 0));
		(void)f;
	}

	void sound_source::set_relative_and_zero_vel_pos() const {
		set_relative(true);
		AL_CHECK(alSource3f(id, AL_POSITION, 0.0f, 0.0f, 0.0f));
		AL_CHECK(alSource3f(id, AL_VELOCITY, 0.0f, 0.0f, 0.0f));
	}

	void sound_source::set_reference_distance(const si_scaling si, const float distance) const {
		const auto passed_distance = si.get_meters(distance);

		(void)passed_distance;
		AL_CHECK(alSourcef(id, AL_REFERENCE_DISTANCE, passed_distance));
#if TRACE_PARAMETERS
		LOG_NVPS(passed_distance);
#endif
	}

	void sound_source::set_direct_channels(const bool flag) const {
		(void)flag;
		AL_CHECK(alSourcei(id, AL_DIRECT_CHANNELS_SOFT, flag ? 1 : 0));

#if TRACE_PARAMETERS
		LOG_NVPS(flag);
#endif
	}

	float sound_source::get_gain() const {
		float gain = 0.f;
		AL_CHECK(alGetSourcef(id, AL_GAIN, &gain));
		return gain;
	}

	float sound_source::get_pitch() const {
		float pitch = 0.f;
		AL_CHECK(alGetSourcef(id, AL_PITCH, &pitch));
		return pitch;
	}

	bool sound_source::is_playing() const {
#if BUILD_OPENAL
		ALenum state = 0xdeadbeef;
		AL_CHECK(alGetSourcei(id, AL_SOURCE_STATE, &state));
		return state == AL_PLAYING;
#else
		return false;
#endif
	}

	void sound_source::bind_buffer(const single_sound_buffer& buf) {
		std::optional<float> previous_seconds;

		{
			const auto buf_addr = std::addressof(buf);

			if (attached_buffer == buf_addr) {
				return;
			}

			if (attached_buffer != nullptr) {
				previous_seconds = get_time_in_seconds();
			}

			attached_buffer = &buf;
		}

		if (previous_seconds) {
			stop();
		}

		AL_CHECK(alSourcei(id, AL_BUFFER, buf.get_id()));
#if TRACE_PARAMETERS
		LOG_NVPS(buf.get_id());
#endif

		if (previous_seconds) {
			play();
			seek_to(*previous_seconds);
		}
	}

	void sound_source::bind_buffer(
		const sound_buffer& source_buffer,
		const std::size_t variation_index
	) {
		bind_buffer(source_buffer.get_buffer(variation_index));
	}

	void sound_source::unbind_buffer() {
		attached_buffer = nullptr;
		AL_CHECK(alSourcei(id, AL_BUFFER, 0));
	}

	void sound_source::just_play(const single_sound_buffer& buffer, const float gain) {
		if (gain >= 0.f) {
			set_gain(gain);
		}

		stop();
		bind_buffer(buffer);
		set_direct_channels(true);
		play();
	}

	const single_sound_buffer* sound_source::get_bound_buffer() const {
		return attached_buffer;
	}

	void set_listener_position(const si_scaling si, vec2 pos) {
		pos = si.get_meters(pos);

#if Y_IS_Z
		AL_CHECK(alListener3f(AL_POSITION, pos.x, 0.f, pos.y));
#else
		AL_CHECK(alListener3f(AL_POSITION, pos.x, pos.y, 0.f));
#endif
#if TRACE_PARAMETERS
		LOG_NVPS(pos);
#endif
	}

	void set_listener_velocity(const si_scaling si, vec2 v) {
		v = si.get_meters(v);

#if Y_IS_Z
		AL_CHECK(alListener3f(AL_VELOCITY, v.x, 0.f, v.y));
#else
		AL_CHECK(alListener3f(AL_VELOCITY, v.x, v.y, 0.f));
#endif

#if TRACE_PARAMETERS
		LOG_NVPS(v);
#endif
	}

	void set_listener_orientation(const std::array<float, 6> data) {
		(void)data;
		AL_CHECK(alListenerfv(AL_ORIENTATION, data.data()));
	}
}
<commit_msg>Check source/listener pos/vel for finiteness<commit_after>#define TRACE_PARAMETERS 0
#define TRACE_CONSTRUCTORS_DESTRUCTORS 0
#define Y_IS_Z 1

#if BUILD_OPENAL
#include <AL/al.h>
#include <AL/alc.h>
#include <AL/alext.h>
#include <AL/efx.h>
#endif

#include "augs/math/vec2.h"
#include "augs/math/si_scaling.h"

#include "augs/audio/sound_source.h"
#include "augs/audio/sound_buffer.h"

#include "augs/audio/OpenAL_error.h"

#if TRACE_CONSTRUCTORS_DESTRUCTORS
int g_num_sources = 0;
#endif

namespace augs {
	sound_source::sound_source() {
#if BUILD_OPENAL
		alGenSources(1, &id);
		const ALenum err { alGetError() };

		if (err == AL_OUT_OF_MEMORY) {
			throw too_many_sound_sources_error();
		}
#endif

#if TRACE_CONSTRUCTORS_DESTRUCTORS
		++g_num_sources;
		LOG("alGenSources: %x (now %x sources)", id, g_num_sources);
#endif
		AL_CHECK(alSourcef(id, AL_PITCH, 1));
		AL_CHECK(alSourcef(id, AL_GAIN, 1));
		AL_CHECK(alSourcei(id, AL_LOOPING, AL_FALSE));

		initialized = true;
	}

	sound_source::~sound_source() {
		destroy();
	}

	sound_source::sound_source(sound_source&& b) :
		initialized(b.initialized),
		id(b.id),
		attached_buffer(b.attached_buffer)
	{
		b.initialized = false;
	}

	sound_source& sound_source::operator=(sound_source&& b) {
		destroy();

		initialized = b.initialized;
		id = b.id;
		attached_buffer = b.attached_buffer;

		b.initialized = false;

		return *this;
	}

	void sound_source::destroy() {
		if (initialized) {
			stop();
#if TRACE_CONSTRUCTORS_DESTRUCTORS
			--g_num_sources;
			LOG("alDeleteSources: %x (now %x sources)", id, g_num_sources);
#endif
			AL_CHECK(alDeleteSources(1, &id));
			initialized = false;
			attached_buffer = nullptr;
		}
	}

	ALuint sound_source::get_id() const {
		return id;
	}

	sound_source::operator ALuint() const {
		return get_id();
	}

	void sound_source::play() const {
		AL_CHECK(alSourcePlay(id));
	}

	void sound_source::seek_to(const float seconds) const {
		(void)seconds;
		AL_CHECK(alSourcef(id, AL_SEC_OFFSET, seconds));
	}

	float sound_source::get_time_in_seconds() const {
		float seconds = 0.f;
		AL_CHECK(alGetSourcef(id, AL_SEC_OFFSET, &seconds));
		return seconds;
	}

	void sound_source::stop() const {
		AL_CHECK(alSourceStop(id));
	}

	void sound_source::set_looping(const bool loop) const {
		(void)loop;
		AL_CHECK(alSourcei(id, AL_LOOPING, loop));
#if TRACE_PARAMETERS
		LOG_NVPS(loop);
#endif
	}

	void sound_source::set_distance_model(const distance_model model) {
#if BUILD_OPENAL
		ALint resolved;

		switch (model) {
			case distance_model::INVERSE_DISTANCE: resolved = AL_INVERSE_DISTANCE; break;
			case distance_model::INVERSE_DISTANCE_CLAMPED: resolved = AL_INVERSE_DISTANCE_CLAMPED; break;
			case distance_model::LINEAR_DISTANCE: resolved = AL_LINEAR_DISTANCE; break;
			case distance_model::LINEAR_DISTANCE_CLAMPED: resolved = AL_LINEAR_DISTANCE_CLAMPED; break;
			case distance_model::EXPONENT_DISTANCE: resolved = AL_EXPONENT_DISTANCE; break;
			case distance_model::EXPONENT_DISTANCE_CLAMPED: resolved = AL_EXPONENT_DISTANCE_CLAMPED; break;
			default: resolved = AL_NONE; break;
		}

		AL_CHECK(alSourcei(id, AL_DISTANCE_MODEL, resolved));
#else
		(void)model;
#endif
	}

	void sound_source::set_rolloff_factor(const float factor) const {
		(void)factor;
		AL_CHECK(alSourcef(id, AL_ROLLOFF_FACTOR, factor));
	}

	void sound_source::set_doppler_factor(const float factor) const {
		(void)factor;
		AL_CHECK(alSourcef(id, AL_DOPPLER_FACTOR, std::clamp(factor, 0.f, 1.f)));
	}

	void sound_source::set_spatialize(const bool f) const {
		AL_CHECK(alSourcei(id, AL_SOURCE_SPATIALIZE_SOFT, f ? AL_TRUE : AL_FALSE));
	}

	void sound_source::set_pitch(const float pitch) const {
		(void)pitch;
		AL_CHECK(alSourcef(id, AL_PITCH, pitch));
#if TRACE_PARAMETERS
		LOG_NVPS(pitch);
#endif
	}

	void sound_source::set_gain(const float gain) const {
		(void)gain;
		AL_CHECK(alSourcef(id, AL_GAIN, gain));
#if TRACE_PARAMETERS
		LOG_NVPS(gain);
#endif
	}

	void sound_source::set_air_absorption_factor(const float absorption) const {
		(void)absorption;
		AL_CHECK(alSourcef(id, AL_AIR_ABSORPTION_FACTOR, absorption));
#if TRACE_PARAMETERS
		LOG_NVPS(absorption);
#endif
	}

	void sound_source::set_velocity(const si_scaling si, vec2 v) const {
		v = si.get_meters(v);

		const bool all_finite = std::isfinite(v.x) && std::isfinite(v.y);

		if (!all_finite) {
			AL_CHECK(alSource3f(id, AL_VELOCITY, 0.f, 0.f, 0.f));
			return;
		}

#if Y_IS_Z
		AL_CHECK(alSource3f(id, AL_VELOCITY, v.x, 0.f, v.y));
#else
		AL_CHECK(alSource3f(id, AL_VELOCITY, v.x, v.y, 0.f));
#endif
#if TRACE_PARAMETERS
		LOG_NVPS(v);
#endif
	}

	void sound_source::set_position(const si_scaling si, vec2 pos) const {
		pos = si.get_meters(pos);

		const bool all_finite = std::isfinite(pos.x) && std::isfinite(pos.y);

		if (!all_finite) {
			AL_CHECK(alSource3f(id, AL_POSITION, 0.f, 0.f, 0.f));
			return;
		}

#if Y_IS_Z
		AL_CHECK(alSource3f(id, AL_POSITION, pos.x, 0.f, pos.y));
#else
		AL_CHECK(alSource3f(id, AL_POSITION, pos.x, pos.y, 0.f));
#endif
#if TRACE_PARAMETERS
		LOG_NVPS(pos);
#endif
	}

	void sound_source::set_max_distance(const si_scaling si, const float distance) const {
		const auto passed_distance = si.get_meters(distance);

		(void)passed_distance;
		AL_CHECK(alSourcef(id, AL_MAX_DISTANCE, passed_distance));
#if TRACE_PARAMETERS
		LOG_NVPS(passed_distance);
#endif
	}

	void sound_source::set_relative(const bool f) const {
		AL_CHECK(alSourcei(id, AL_SOURCE_RELATIVE, f ? 1 : 0));
		(void)f;
	}

	void sound_source::set_relative_and_zero_vel_pos() const {
		set_relative(true);
		AL_CHECK(alSource3f(id, AL_POSITION, 0.0f, 0.0f, 0.0f));
		AL_CHECK(alSource3f(id, AL_VELOCITY, 0.0f, 0.0f, 0.0f));
	}

	void sound_source::set_reference_distance(const si_scaling si, const float distance) const {
		const auto passed_distance = si.get_meters(distance);

		(void)passed_distance;
		AL_CHECK(alSourcef(id, AL_REFERENCE_DISTANCE, passed_distance));
#if TRACE_PARAMETERS
		LOG_NVPS(passed_distance);
#endif
	}

	void sound_source::set_direct_channels(const bool flag) const {
		(void)flag;
		AL_CHECK(alSourcei(id, AL_DIRECT_CHANNELS_SOFT, flag ? 1 : 0));

#if TRACE_PARAMETERS
		LOG_NVPS(flag);
#endif
	}

	float sound_source::get_gain() const {
		float gain = 0.f;
		AL_CHECK(alGetSourcef(id, AL_GAIN, &gain));
		return gain;
	}

	float sound_source::get_pitch() const {
		float pitch = 0.f;
		AL_CHECK(alGetSourcef(id, AL_PITCH, &pitch));
		return pitch;
	}

	bool sound_source::is_playing() const {
#if BUILD_OPENAL
		ALenum state = 0xdeadbeef;
		AL_CHECK(alGetSourcei(id, AL_SOURCE_STATE, &state));
		return state == AL_PLAYING;
#else
		return false;
#endif
	}

	void sound_source::bind_buffer(const single_sound_buffer& buf) {
		std::optional<float> previous_seconds;

		{
			const auto buf_addr = std::addressof(buf);

			if (attached_buffer == buf_addr) {
				return;
			}

			if (attached_buffer != nullptr) {
				previous_seconds = get_time_in_seconds();
			}

			attached_buffer = &buf;
		}

		if (previous_seconds) {
			stop();
		}

		AL_CHECK(alSourcei(id, AL_BUFFER, buf.get_id()));
#if TRACE_PARAMETERS
		LOG_NVPS(buf.get_id());
#endif

		if (previous_seconds) {
			play();
			seek_to(*previous_seconds);
		}
	}

	void sound_source::bind_buffer(
		const sound_buffer& source_buffer,
		const std::size_t variation_index
	) {
		bind_buffer(source_buffer.get_buffer(variation_index));
	}

	void sound_source::unbind_buffer() {
		attached_buffer = nullptr;
		AL_CHECK(alSourcei(id, AL_BUFFER, 0));
	}

	void sound_source::just_play(const single_sound_buffer& buffer, const float gain) {
		if (gain >= 0.f) {
			set_gain(gain);
		}

		stop();
		bind_buffer(buffer);
		set_direct_channels(true);
		play();
	}

	const single_sound_buffer* sound_source::get_bound_buffer() const {
		return attached_buffer;
	}

	void set_listener_position(const si_scaling si, vec2 pos) {
		pos = si.get_meters(pos);

		const bool all_finite = std::isfinite(pos.x) && std::isfinite(pos.y);

		if (!all_finite) {
			AL_CHECK(alListener3f(AL_POSITION, 0.f, 0.f, 0.f));
			return;
		}

#if Y_IS_Z
		AL_CHECK(alListener3f(AL_POSITION, pos.x, 0.f, pos.y));
#else
		AL_CHECK(alListener3f(AL_POSITION, pos.x, pos.y, 0.f));
#endif
#if TRACE_PARAMETERS
		LOG_NVPS(pos);
#endif
	}

	void set_listener_velocity(const si_scaling si, vec2 v) {
		v = si.get_meters(v);

		const bool all_finite = std::isfinite(v.x) && std::isfinite(v.y);

		if (!all_finite) {
			AL_CHECK(alListener3f(AL_VELOCITY, 0.f, 0.f, 0.f));
			return;
		}

#if Y_IS_Z
		AL_CHECK(alListener3f(AL_VELOCITY, v.x, 0.f, v.y));
#else
		AL_CHECK(alListener3f(AL_VELOCITY, v.x, v.y, 0.f));
#endif

#if TRACE_PARAMETERS
		LOG_NVPS(v);
#endif
	}

	void set_listener_orientation(const std::array<float, 6> data) {
		(void)data;
		AL_CHECK(alListenerfv(AL_ORIENTATION, data.data()));
	}
}
<|endoftext|>


<commit_before>/*************************************************************************
 *
 *  $RCSfile: resourcemanager.cxx,v $
 *
 *  $Revision: 1.8 $
 *
 *  last change: $Author: vg $ $Date: 2005-03-10 18:05:44 $
 *
 *  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 "resourcemanager.hxx"

#include <vcl/svapp.hxx>
#include <vcl/fixed.hxx>
#include <svtools/stdctrl.hxx>
#include <svtools/solar.hrc>

namespace XmlSec
{
    static ResMgr*          pResMgr = 0;
    static International*   pInternational = 0;

    ResMgr* GetResMgr( void )
    {
        if( !pResMgr )
        {
            ByteString  aName( "xmlsec" );
            aName += ByteString::CreateFromInt32( SOLARUPD );
//          pResMgr = ResMgr::CreateResMgr( aName.GetBuffer(), Application::GetSettings().GetUILanguage() );
//          LanguageType    aLang( LANGUAGE_ENGLISH_US );
//          pResMgr = ResMgr::CreateResMgr( aName.GetBuffer(), aLang );
// MT: Change to Locale
            pResMgr = ResMgr::CreateResMgr( aName.GetBuffer() );
        }

    return pResMgr;
    }

    International* GetInternational( void )
    {
        if( !pInternational )
        {
//          LanguageType    aLang( LANGUAGE_ENGLISH_US );
//          pInternational = new International( aLang );
            pInternational = new International( Application::GetSettings().GetInternational() );
        }
        return pInternational;
    }

    DateTime GetDateTime( const ::com::sun::star::util::DateTime& _rDT )
    {
        return DateTime(
            Date( _rDT.Day, _rDT.Month, _rDT.Year ),
            Time( _rDT.Hours, _rDT.Minutes, _rDT.Seconds, _rDT.HundredthSeconds ) );
    }

    String GetDateTimeString( const ::com::sun::star::util::DateTime& _rDT )
    {
        // --> PB 2004-10-12 #i20172# String with date and time information
        DateTime aDT( GetDateTime( _rDT ) );
        International* pInter = GetInternational();
        String sRet( pInter->GetDate( aDT ) );
        sRet += ' ';
        sRet += pInter->GetTime( aDT );
        return sRet;
    }

    String GetDateTimeString( const rtl::OUString& _rDate, const rtl::OUString& _rTime )
    {
        String sDay( _rDate, 6, 2 );
        String sMonth( _rDate, 4, 2 );
        String sYear( _rDate, 0, 4 );

        String sHour( _rTime, 0, 2 );
        String sMin( _rTime, 4, 2 );
        String sSec( _rTime, 6, 2 );

        Date aDate( (USHORT)sDay.ToInt32(), (USHORT) sMonth.ToInt32(), (USHORT)sYear.ToInt32() );
        Time aTime( sHour.ToInt32(), sMin.ToInt32(), sSec.ToInt32(), 0 );
        String aStr( GetInternational()->GetDate( aDate ) );
        aStr.AppendAscii( " " );
        aStr += GetInternational()->GetTime( aTime );
        return aStr;
    }

    String GetDateString( const ::com::sun::star::util::DateTime& _rDT )
    {
        return GetInternational()->GetDate( GetDateTime( _rDT ) );
    }

    String GetPureContent( const String& _rRawString, const char* _pCommaReplacement, bool _bPreserveId )
    {
        enum STATE { PRE_ID, ID, EQUALSIGN, PRE_CONT, CONT };
        String      s;
        STATE       e = _bPreserveId? PRE_ID : ID;

        const sal_Unicode*  p = _rRawString.GetBuffer();
        sal_Unicode         c;
        const sal_Unicode   cComma = ',';
        const sal_Unicode   cEqualSign = '=';
        const sal_Unicode   cSpace = ' ';
        String              aCommaReplacement;
        if( _pCommaReplacement )
            aCommaReplacement = String::CreateFromAscii( _pCommaReplacement );

        while( *p )
        {
            c = *p;
            switch( e )
            {
                case PRE_ID:
                    if( c != cSpace )
                    {
                        s += c;
                        e = ID;
                    }
                    break;
                case ID:
                    if( _bPreserveId )
                        s += c;

                    if( c == cEqualSign )
                        e = _bPreserveId? PRE_CONT : CONT;
                    break;
//              case EQUALSIGN:
//                  break;
                case PRE_CONT:
                    if( c != cSpace )
                    {
                        s += c;
                        e = CONT;
                    }
                    break;
                case CONT:
                    if( c == cComma )
                    {
                        s += aCommaReplacement;
                        e = _bPreserveId? PRE_ID : ID;
                    }
                    else
                        s += c;
                    break;
            }

            ++p;
        }

//      xub_StrLen  nEquPos = _rRawString.SearchAscii( "=" );
//      if( nEquPos == STRING_NOTFOUND )
//          s = _rRawString;
//      else
//      {
//          ++nEquPos;
//          s = String( _rRawString, nEquPos, STRING_MAXLEN );
//          s.EraseLeadingAndTrailingChars();
//      }

        return s;
    }

    String GetContentPart( const String& _rRawString, const String& _rPartId )
    {
        String s;

        xub_StrLen nContStart = _rRawString.Search( _rPartId );
        if( nContStart != STRING_NOTFOUND )
        {
            nContStart += _rPartId.Len();
            ++nContStart;                   // now it's start of content, directly after Id

            xub_StrLen  nContEnd = _rRawString.Search( sal_Unicode( ',' ), nContStart );

            s = String( _rRawString, nContStart, nContEnd - nContStart );
        }

        return s;
    }

    /**
     * This Method should consider some string like "C=CN-XXX , O=SUN-XXX , CN=Jack" ,
     * here the first CN represent china , and the second CN represent the common name ,
     * so I changed the method to handle this .
     * By CP , mailto : chandler.peng@sun.com
     **/
    String GetContentPart( const String& _rRawString )
    {
        // search over some parts to find a string
        //static char* aIDs[] = { "CN", "OU", "O", "E", NULL };
        static char* aIDs[] = { "CN=", "OU=", "O=", "E=", NULL };// By CP
        String sPart;
        int i = 0;
        while ( aIDs[i] )
        {
            String sPartId = String::CreateFromAscii( aIDs[i++] );
            xub_StrLen nContStart = _rRawString.Search( sPartId );
            if ( nContStart != STRING_NOTFOUND )
            {
                nContStart += sPartId.Len();
                //++nContStart;                   // now it's start of content, directly after Id // delete By CP
                xub_StrLen nContEnd = _rRawString.Search( sal_Unicode( ',' ), nContStart );
                sPart = String( _rRawString, nContStart, nContEnd - nContStart );
                break;
            }
        }

        return sPart;
    }

    String GetHexString( const ::com::sun::star::uno::Sequence< sal_Int8 >& _rSeq, const char* _pSep, UINT16 _nLineBreak )
    {
        const sal_Int8*         pSerNumSeq = _rSeq.getConstArray();
        int                     nCnt = _rSeq.getLength();
        String                  aStr;
        const char              pHexDigs[ 17 ] = "0123456789ABCDEF";
        char                    pBuffer[ 3 ] = "  ";
        UINT8                   nNum;
        UINT16                  nBreakStart = _nLineBreak? _nLineBreak : 1;
        UINT16                  nBreak = nBreakStart;
        for( int i = 0 ; i < nCnt ; ++i )
        {
            nNum = UINT8( pSerNumSeq[ i ] );

            //MM : exchange the buffer[0] and buffer[1], which make it consistent with Mozilla and Windows
            pBuffer[ 1 ] = pHexDigs[ nNum & 0x0F ];
            nNum >>= 4;
            pBuffer[ 0 ] = pHexDigs[ nNum ];
            aStr.AppendAscii( pBuffer );

            --nBreak;
            if( nBreak )
                aStr.AppendAscii( _pSep );
            else
            {
                nBreak = nBreakStart;
                aStr.AppendAscii( "\n" );
            }
        }

        return aStr;
    }

    long ShrinkToFitWidth( Control& _rCtrl, long _nOffs )
    {
        long    nWidth = _rCtrl.GetTextWidth( _rCtrl.GetText() );
        Size    aSize( _rCtrl.GetSizePixel() );
        nWidth += _nOffs;
        aSize.Width() = nWidth;
        _rCtrl.SetSizePixel( aSize );
        return nWidth;
    }

    void AlignAfterImage( const FixedImage& _rImage, Control& _rCtrl, long _nXOffset )
    {
        Point   aPos( _rImage.GetPosPixel() );
        Size    aSize( _rImage.GetSizePixel() );
        long    n = aPos.X();
        n += aSize.Width();
        n += _nXOffset;
        aPos.X() = n;
        n = aPos.Y();
        n += aSize.Height() / 2;                    // y-position is in the middle of the image
        n -= _rCtrl.GetSizePixel().Height() / 2;    // center Control
        aPos.Y() = n;
        _rCtrl.SetPosPixel( aPos );
    }

    void AlignAfterImage( const FixedImage& _rImage, FixedInfo& _rFI, long _nXOffset )
    {
        AlignAfterImage( _rImage, static_cast< Control& >( _rFI ), _nXOffset );
        ShrinkToFitWidth( _rFI );
    }

    void AlignAndFitImageAndControl( FixedImage& _rImage, FixedInfo& _rFI, long _nXOffset )
    {
        _rImage.SetSizePixel( _rImage.GetImage().GetSizePixel() );
        AlignAfterImage( _rImage, _rFI, _nXOffset );
    }
}

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

#include "resourcemanager.hxx"

#include <vcl/svapp.hxx>
#include <vcl/fixed.hxx>
#include <svtools/stdctrl.hxx>
#include <svtools/solar.hrc>

namespace XmlSec
{
    static ResMgr*          pResMgr = 0;
    static International*   pInternational = 0;

    ResMgr* GetResMgr( void )
    {
        if( !pResMgr )
        {
            ByteString  aName( "xmlsec" );
            aName += ByteString::CreateFromInt32( SOLARUPD );
//          pResMgr = ResMgr::CreateResMgr( aName.GetBuffer(), Application::GetSettings().GetUILanguage() );
//          LanguageType    aLang( LANGUAGE_ENGLISH_US );
//          pResMgr = ResMgr::CreateResMgr( aName.GetBuffer(), aLang );
// MT: Change to Locale
            pResMgr = ResMgr::CreateResMgr( aName.GetBuffer() );
        }

    return pResMgr;
    }

    International* GetInternational( void )
    {
        if( !pInternational )
        {
//          LanguageType    aLang( LANGUAGE_ENGLISH_US );
//          pInternational = new International( aLang );
            pInternational = new International( Application::GetSettings().GetInternational() );
        }
        return pInternational;
    }

    DateTime GetDateTime( const ::com::sun::star::util::DateTime& _rDT )
    {
        return DateTime(
            Date( _rDT.Day, _rDT.Month, _rDT.Year ),
            Time( _rDT.Hours, _rDT.Minutes, _rDT.Seconds, _rDT.HundredthSeconds ) );
    }

    String GetDateTimeString( const ::com::sun::star::util::DateTime& _rDT )
    {
        // --> PB 2004-10-12 #i20172# String with date and time information
        DateTime aDT( GetDateTime( _rDT ) );
        International* pInter = GetInternational();
        String sRet( pInter->GetDate( aDT ) );
        sRet += ' ';
        sRet += pInter->GetTime( aDT );
        return sRet;
    }

    String GetDateTimeString( const rtl::OUString& _rDate, const rtl::OUString& _rTime )
    {
        String sDay( _rDate, 6, 2 );
        String sMonth( _rDate, 4, 2 );
        String sYear( _rDate, 0, 4 );

        String sHour( _rTime, 0, 2 );
        String sMin( _rTime, 4, 2 );
        String sSec( _rTime, 6, 2 );

        Date aDate( (USHORT)sDay.ToInt32(), (USHORT) sMonth.ToInt32(), (USHORT)sYear.ToInt32() );
        Time aTime( sHour.ToInt32(), sMin.ToInt32(), sSec.ToInt32(), 0 );
        String aStr( GetInternational()->GetDate( aDate ) );
        aStr.AppendAscii( " " );
        aStr += GetInternational()->GetTime( aTime );
        return aStr;
    }

    String GetDateString( const ::com::sun::star::util::DateTime& _rDT )
    {
        return GetInternational()->GetDate( GetDateTime( _rDT ) );
    }

    String GetPureContent( const String& _rRawString, const char* _pCommaReplacement, bool _bPreserveId )
    {
        enum STATE { PRE_ID, ID, EQUALSIGN, PRE_CONT, CONT };
        String      s;
        STATE       e = _bPreserveId? PRE_ID : ID;

        const sal_Unicode*  p = _rRawString.GetBuffer();
        sal_Unicode         c;
        const sal_Unicode   cComma = ',';
        const sal_Unicode   cEqualSign = '=';
        const sal_Unicode   cSpace = ' ';
        String              aCommaReplacement;
        if( _pCommaReplacement )
            aCommaReplacement = String::CreateFromAscii( _pCommaReplacement );

        while( *p )
        {
            c = *p;
            switch( e )
            {
                case PRE_ID:
                    if( c != cSpace )
                    {
                        s += c;
                        e = ID;
                    }
                    break;
                case ID:
                    if( _bPreserveId )
                        s += c;

                    if( c == cEqualSign )
                        e = _bPreserveId? PRE_CONT : CONT;
                    break;
//              case EQUALSIGN:
//                  break;
                case PRE_CONT:
                    if( c != cSpace )
                    {
                        s += c;
                        e = CONT;
                    }
                    break;
                case CONT:
                    if( c == cComma )
                    {
                        s += aCommaReplacement;
                        e = _bPreserveId? PRE_ID : ID;
                    }
                    else
                        s += c;
                    break;
            }

            ++p;
        }

//      xub_StrLen  nEquPos = _rRawString.SearchAscii( "=" );
//      if( nEquPos == STRING_NOTFOUND )
//          s = _rRawString;
//      else
//      {
//          ++nEquPos;
//          s = String( _rRawString, nEquPos, STRING_MAXLEN );
//          s.EraseLeadingAndTrailingChars();
//      }

        return s;
    }

    String GetContentPart( const String& _rRawString, const String& _rPartId )
    {
        String s;

        xub_StrLen nContStart = _rRawString.Search( _rPartId );
        if( nContStart != STRING_NOTFOUND )
        {
            nContStart += _rPartId.Len();
            ++nContStart;                   // now it's start of content, directly after Id

            xub_StrLen  nContEnd = _rRawString.Search( sal_Unicode( ',' ), nContStart );

            s = String( _rRawString, nContStart, nContEnd - nContStart );
        }

        return s;
    }

    /**
     * This Method should consider some string like "C=CN-XXX , O=SUN-XXX , CN=Jack" ,
     * here the first CN represent china , and the second CN represent the common name ,
     * so I changed the method to handle this .
     * By CP , mailto : chandler.peng@sun.com
     **/
    String GetContentPart( const String& _rRawString )
    {
        // search over some parts to find a string
        //static char* aIDs[] = { "CN", "OU", "O", "E", NULL };
        static char* aIDs[] = { "CN=", "OU=", "O=", "E=", NULL };// By CP
        String sPart;
        int i = 0;
        while ( aIDs[i] )
        {
            String sPartId = String::CreateFromAscii( aIDs[i++] );
            xub_StrLen nContStart = _rRawString.Search( sPartId );
            if ( nContStart != STRING_NOTFOUND )
            {
                nContStart += sPartId.Len();
                //++nContStart;                   // now it's start of content, directly after Id // delete By CP
                xub_StrLen nContEnd = _rRawString.Search( sal_Unicode( ',' ), nContStart );
                sPart = String( _rRawString, nContStart, nContEnd - nContStart );
                break;
            }
        }

        return sPart;
    }

    String GetHexString( const ::com::sun::star::uno::Sequence< sal_Int8 >& _rSeq, const char* _pSep, UINT16 _nLineBreak )
    {
        const sal_Int8*         pSerNumSeq = _rSeq.getConstArray();
        int                     nCnt = _rSeq.getLength();
        String                  aStr;
        const char              pHexDigs[ 17 ] = "0123456789ABCDEF";
        char                    pBuffer[ 3 ] = "  ";
        UINT8                   nNum;
        UINT16                  nBreakStart = _nLineBreak? _nLineBreak : 1;
        UINT16                  nBreak = nBreakStart;
        for( int i = 0 ; i < nCnt ; ++i )
        {
            nNum = UINT8( pSerNumSeq[ i ] );

            //MM : exchange the buffer[0] and buffer[1], which make it consistent with Mozilla and Windows
            pBuffer[ 1 ] = pHexDigs[ nNum & 0x0F ];
            nNum >>= 4;
            pBuffer[ 0 ] = pHexDigs[ nNum ];
            aStr.AppendAscii( pBuffer );

            --nBreak;
            if( nBreak )
                aStr.AppendAscii( _pSep );
            else
            {
                nBreak = nBreakStart;
                aStr.AppendAscii( "\n" );
            }
        }

        return aStr;
    }

    long ShrinkToFitWidth( Control& _rCtrl, long _nOffs )
    {
        long    nWidth = _rCtrl.GetTextWidth( _rCtrl.GetText() );
        Size    aSize( _rCtrl.GetSizePixel() );
        nWidth += _nOffs;
        aSize.Width() = nWidth;
        _rCtrl.SetSizePixel( aSize );
        return nWidth;
    }

    void AlignAfterImage( const FixedImage& _rImage, Control& _rCtrl, long _nXOffset )
    {
        Point   aPos( _rImage.GetPosPixel() );
        Size    aSize( _rImage.GetSizePixel() );
        long    n = aPos.X();
        n += aSize.Width();
        n += _nXOffset;
        aPos.X() = n;
        n = aPos.Y();
        n += aSize.Height() / 2;                    // y-position is in the middle of the image
        n -= _rCtrl.GetSizePixel().Height() / 2;    // center Control
        aPos.Y() = n;
        _rCtrl.SetPosPixel( aPos );
    }

    void AlignAfterImage( const FixedImage& _rImage, FixedInfo& _rFI, long _nXOffset )
    {
        AlignAfterImage( _rImage, static_cast< Control& >( _rFI ), _nXOffset );
        ShrinkToFitWidth( _rFI );
    }

    void AlignAndFitImageAndControl( FixedImage& _rImage, FixedInfo& _rFI, long _nXOffset )
    {
        _rImage.SetSizePixel( _rImage.GetImage().GetSizePixel() );
        AlignAfterImage( _rImage, _rFI, _nXOffset );
    }
}

<|endoftext|>


<commit_before>#include "menu.h"
#include <QDebug>
#include <QString>
#include <QPainter>
#include <QPaintEvent>
#include <QBrush>
#include <QColor>
#include <QWidget>

#include "guiview.h"
#include "simview.h"
#include "autview.h"

/**
 * Menu for insantiating views
 */

Menu::Menu()
{
    setMouseTracking(true);
    buttonRectSize = QSize(150,50);
    setWindowTitle("Sub Menu");
    this->setFixedSize(800,600);

    //Welcome
    welcomeMessage = new QLabel();

        //Sizing
    welcomeMessage->setFixedSize(400,300);

        //Font
    welcomeFont = QFont("Calibri",15);
    welcomeFont.setItalic(true);
    welcomeFont.setBold(true);

        //Set Text
    welcomeMessage->setFont(welcomeFont);
    welcomeMessage->setText("Welcome to the menu\nPlease select your view");

    //Making the Buttons
    guiButton = new QPushButton(this);
    simButton = new QPushButton(this);
    autButton = new QPushButton(this);

    connect(guiButton, SIGNAL(clicked()), this, SLOT(makeView()));

         //Sizing
    guiButton->setFixedSize(buttonRectSize);
    simButton->setFixedSize(buttonRectSize);
    autButton->setFixedSize(buttonRectSize);

        //Text Sizing and Font
    menuItemFont = QFont("Times New Roman",12);
    menuItemFont.setItalic(true);

    guiButton->setFont(menuItemFont);
    simButton->setFont(menuItemFont);
    autButton->setFont(menuItemFont);

        //color
    guiButton->setStyleSheet("QPushButton{ background-color : yellow; color:blue}");
    simButton->setStyleSheet("QPushButton{ background-color : yellow; color:blue}");
    autButton->setStyleSheet("QPushButton{ background-color : yellow; color:blue}");

        //Change Color when mouse hovers over a menu item
    guiButton->setStyleSheet("QPushButton:hover{ background-color : lightGrey; color:black}");
    simButton->setStyleSheet("QPushButton:hover{ background-color : lightGrey; color:black}");
    autButton->setStyleSheet("QPushButton:hover{ background-color : lightGrey; color:black}");

    //Consider using setBackGroundImage to achieve a nicer effect

        //Text
    guiButton->setText("Gui Mode");
    simButton->setText("Simulation Mode");
    autButton->setText("Autonomous Mode");

    //Layout
    mainLayout = new QGridLayout();

    mainLayout->setSpacing(10);
    mainLayout->addWidget(welcomeMessage,1,3);
    mainLayout->addWidget(guiButton,2,4);
    mainLayout->addWidget(simButton,3,4);
    mainLayout->addWidget(autButton,4,4);
    this->setLayout(mainLayout);

    //Leave only the button text visible

    guiButton->setFlat(true);
    simButton->setFlat(true);
    autButton->setFlat(true);

}

void Menu::paintEvent(QPaintEvent *event)
{
 QBrush background(QColor(32,32,32,0));//Grey brush to paint background with
 QPainter painter;

 painter.begin(this);
 painter.fillRect(event->rect(), background);

 painter.end();
}

void Menu::makeGuiView()
{
    GuiView *guiView = new GuiView;

}
/*Not made yet
 *
 *
void Menu::makeSimView()
{
    SimView *simView = new SimView;
    delete this;
}

void Menu::makeAutView()
{
    AutView *autView = new autView;
    delete this;
}

*/
<commit_msg>Update menu.cpp<commit_after>#include "menu.h"
#include <QDebug>
#include <QString>
#include <QPainter>
#include <QPaintEvent>
#include <QBrush>
#include <QColor>
#include <QWidget>
#include <QVBoxLayout>
#include <QHBoxLayout>

#include "showcaseview.h"

Menu::Menu()
{
    initializeMenu();

}

void Menu::initializeMenu()
{
    // setMouseTracking(true);
     buttonRectSize = QSize(150,50);
     setWindowTitle("Sub Menu");
     this->setFixedSize(800,600);

     //Welcome
     welcomeMessage = new QLabel();

         //Sizingprivate:
     welcomeMessage->setFixedSize(400,300);

         //Font
     welcomeFont = QFont("Calibri",15);
     welcomeFont.setItalic(true);
     welcomeFont.setBold(true);

         //Set Text
     welcomeMessage->setFont(welcomeFont);
     welcomeMessage->setText("Welcome to the menu\nPlease select your view");

     //Making the Buttons
     guiButton = new QPushButton();
     simButton = new QPushButton();
     autButton = new QPushButton();

          //Connecting
     connect(guiButton, SIGNAL(clicked()), this, SLOT(makeView()));

          //Sizing
     guiButton->setFixedSize(buttonRectSize);
     simButton->setFixedSize(buttonRectSize);
     autButton->setFixedSize(buttonRectSize);

         //Text Sizing and Font
     menuItemFont = QFont("Times New Roman",12);
     menuItemFont.setItalic(true);

     guiButton->setFont(menuItemFont);
     simButton->setFont(menuItemFont);
     autButton->setFont(menuItemFont);

        //Change Color when mouse hovers over a menu setMouseTrack item
     guiButton->setStyleSheet("QPushButton:hover{ background-color : lightGrey; color:black}");
     simButton->setStyleSheet("QPushButton:hover{ background-color : lightGrey; color:black}");
     autButton->setStyleSheet("QPushButton:hover{ background-color : lightGrey; color:black}");

         //Text
     guiButton->setText("Gui Mode");
     simButton->setText("Simulation Mode");
     autButton->setText("Autonomous Mode");

     //Layout

         //Sizing
     mainLayout = new QGridLayout();

     mainLayout->setSpacing(10);

     for (int i = 0; i<10; i++)
    {
         mainLayout->setRowStretch(i,1); //Setting max size relative to minimum for the first 10 rows
    }

     for (int i = 0; i<10; i++)
    {
     mainLayout->setRowMinimumHeight(i,100); //Setting 10 rows of equal "size" 100
     }

     for (int i = 0; i<10; i++)
    {
         mainLayout->setColumnStretch(i,1); //Setting max size relative to minimum for the first 10 Columns
    }

     for (int i = 0; i<10; i++)
    {
     mainLayout->setColumnMinimumWidth(i,100); //Setting 10 Columns of equal "size" 100
     }

         //Positioning      *note that the widgets span multiple rows and columns
     mainLayout->addWidget(welcomeMessage,0,5);
     mainLayout->addWidget(guiButton,3,6);
     mainLayout->addWidget(simButton,4,6);
     mainLayout->addWidget(autButton,5,6);
     this->setLayout(mainLayout);

     //Leave only the button text visible

     guiButton->setFlat(true);
     simButton->setFlat(true);
     autButton->setFlat(true);

}

void Menu::paintEvent(QPaintEvent *event)
{

     QImage background(":/img/MDA.jpg");
     background = background.scaled(800,700);

    QPainter painter;

     painter.begin(this);
    painter.fillRect(event->rect(), background);

    painter.end();
}

void Menu::makeView()
{
    ShowCaseView *view = new ShowCaseView;
    view->show();

    Controller *controller = new Controller();
    controller->initialize();

    view->initialize_VC_Connection(controller);//Connect the controller to the view

    this->close();
}
<|endoftext|>


<commit_before>#include "Drivetrain.h"
#include "../RobotMap.h"
#include "WPILib.h"

Drivetrain::Drivetrain() : Subsystem("ExampleSubsystem")
{
  leftBackMotor = new CANTalon(3), rightBackMotor = new CANTalon(4),
    leftFrontMotor = new CANTalon(1), rightFrontMotor = new CANTalon(2);

  drive = new RobotDrive;
}

void Drivetrain::InitDefaultCommand()
{
	SetDefaultCommand(new GetYPosition);
	// Set the default command for a subsystem here.
	//SetDefaultCommand(new MySpecialCommand());
}

void Drivetrain::tankDrive(Joystick *leftJoystick, Joystick *rightJoystick)
{
	drive->TankDrive(leftJoystick, rightJoystick);
}

void Drivetrain::tankDrive(float leftSpeed, float rightSpeed)
{
	drive->TankDrive(leftSpeed, rightSpeed);
}

void Drivetrain::rightBackMotor(float speed)
{
	rightBackMotor->Set(speed);
}

void Drivetrain::leftBackMotor(float speed)
{
	leftBackMotor->Set(speed);
}

void Drivetrain::rightFrontMotor(float speed)
{
  rightFrontMotor->Set(speed);
}

void Drivetrain::leftFrontMotor(float speed)
{
  leftFrontMotor->Set(speed);
}

// Put methods for controlling this subsystem
// here. Call these from Commands.
<commit_msg>Set default command of the Drivetrain Subsystem to TankDrive.<commit_after>#include "Drivetrain.h"
#include "../RobotMap.h"
#include "WPILib.h"

Drivetrain::Drivetrain() : Subsystem("ExampleSubsystem")
{
  leftBackMotor = new CANTalon(3), rightBackMotor = new CANTalon(4),
    leftFrontMotor = new CANTalon(1), rightFrontMotor = new CANTalon(2);

  drive = new RobotDrive;
}

void Drivetrain::InitDefaultCommand()
{
	SetDefaultCommand(new TankDrive);
	// Set the default command for a subsystem here.
	//SetDefaultCommand(new MySpecialCommand());
}

void Drivetrain::tankDrive(Joystick *leftJoystick, Joystick *rightJoystick)
{
	drive->TankDrive(leftJoystick, rightJoystick);
}

void Drivetrain::tankDrive(float leftSpeed, float rightSpeed)
{
	drive->TankDrive(leftSpeed, rightSpeed);
}

void Drivetrain::rightBackMotor(float speed)
{
	rightBackMotor->Set(speed);
}

void Drivetrain::leftBackMotor(float speed)
{
	leftBackMotor->Set(speed);
}

void Drivetrain::rightFrontMotor(float speed)
{
  rightFrontMotor->Set(speed);
}

void Drivetrain::leftFrontMotor(float speed)
{
  leftFrontMotor->Set(speed);
}

// Put methods for controlling this subsystem
// here. Call these from Commands.
<|endoftext|>