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

#ifndef COMPHELPER_COMPONENTCONTEXT_HXX
#define COMPHELPER_COMPONENTCONTEXT_HXX

#ifndef INCLUDED_COMPHELPERDLLAPI_H
#include <comphelper/comphelperdllapi.h>
#endif

/** === begin UNO includes === **/
#ifndef _COM_SUN_STAR_UNO_XCOMPONENTCONTEXT_HPP_
#include <com/sun/star/uno/XComponentContext.hpp>
#endif
#ifndef _COM_SUN_STAR_LANG_XMULTISERVICEFACTORY_HPP_
#include <com/sun/star/lang/XMultiServiceFactory.hpp>
#endif
/** === end UNO includes === **/

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

    //====================================================================
    //= ComponentContext
    //====================================================================
    /** a helper class for working with a component context
    */
    class COMPHELPER_DLLPUBLIC ComponentContext
    {
    private:
        ::com::sun::star::uno::Reference< ::com::sun::star::uno::XComponentContext >        m_xContext;
        ::com::sun::star::uno::Reference< ::com::sun::star::lang::XMultiComponentFactory >  m_xORB;

    public:
        /** constructs an instance
            @param _rxContext
                the component context to manage
            @throws ::com::sun::star::lang::NullPointerException
                if the given context, or its component factory, are <NULL/>
        */
        ComponentContext( const ::com::sun::star::uno::Reference< ::com::sun::star::uno::XComponentContext >& _rxContext );

        /** constructs an instance
            @param _rxLegacyFactory
                the legacy service factor to obtain the <type scope="com::sun::star::uno">XComponentContext</type> from
            @throws ::com::sun::star::uno::RuntimeException
                if the given factory or does not have a DefaultContext property to obtain
                a component context
            @throws ::com::sun::star::lang::NullPointerException
                if the given factory is <NULL/>, or provides a component context being <NULL/>, or provides
                a component context whose component factory is <NULL/>
        */
        ComponentContext( const ::com::sun::star::uno::Reference< ::com::sun::star::lang::XMultiServiceFactory >& _rxLegacyFactory );

        /** returns the ->XComponentContext interface
        */
        inline ::com::sun::star::uno::Reference< ::com::sun::star::uno::XComponentContext >
            getUNOContext() const { return m_xContext; }

        /** determines whether the context is not <NULL/>
        */
        inline sal_Bool is() const
        {
            return m_xContext.is();
        }

        /** creates a component using our component factory/context
            @throws ::com::sun::star::uno::Exception
            @return
                <TRUE/> if and only if the component could be successfully created
        */
        template < typename INTERFACE >
        bool createComponent( const ::rtl::OUString& _rServiceName, ::com::sun::star::uno::Reference< INTERFACE >& _out_rxComponent ) const
        {
            _out_rxComponent.clear();
            _out_rxComponent = _out_rxComponent.query(
                m_xORB->createInstanceWithContext( _rServiceName, m_xContext )
            );
            return _out_rxComponent.is();
        }

        /** creates a component using our component factory/context
            @throws ::com::sun::star::uno::Exception
            @return
                <TRUE/> if and only if the component could be successfully created
        */
        template < typename INTERFACE >
        bool createComponent( const sal_Char* _pAsciiServiceName, ::com::sun::star::uno::Reference< INTERFACE >& _out_rxComponent ) const
        {
            return createComponent( ::rtl::OUString::createFromAscii( _pAsciiServiceName ), _out_rxComponent );
        }

        /** creates a component using our component factory/context, passing creation arguments
            @throws ::com::sun::star::uno::Exception
            @return
                <TRUE/> if and only if the component could be successfully created
        */
        template < typename INTERFACE >
        bool createComponentWithArguments( const ::rtl::OUString& _rServiceName, const ::com::sun::star::uno::Sequence< ::com::sun::star::uno::Any >& _rArguments, ::com::sun::star::uno::Reference< INTERFACE >& _out_rxComponent ) const
        {
            _out_rxComponent.clear();
            _out_rxComponent = _out_rxComponent.query(
                m_xORB->createInstanceWithArgumentsAndContext( _rServiceName, _rArguments, m_xContext )
            );
            return _out_rxComponent.is();
        }

        /** creates a component using our component factory/context, passing creation arguments
            @throws ::com::sun::star::uno::Exception
            @return
                <TRUE/> if and only if the component could be successfully created
        */
        template < typename INTERFACE >
        bool createComponentWithArguments( const sal_Char* _pAsciiServiceName, const ::com::sun::star::uno::Sequence< ::com::sun::star::uno::Any >& _rArguments, ::com::sun::star::uno::Reference< INTERFACE >& _out_rxComponent ) const
        {
            return createComponentWithArguments( ::rtl::OUString::createFromAscii( _pAsciiServiceName ), _rArguments, _out_rxComponent );
        }

        /** creates a component using our component factory/context

            @throws ::com::sun::star::lang::ServiceNotRegisteredException
                if the given service is not registered
            @throws Exception
                if an exception occured during creating the component
            @return
                the newly created component. Is never <NULL/>.
        */
        ::com::sun::star::uno::Reference< ::com::sun::star::uno::XInterface > createComponent( const ::rtl::OUString& _rServiceName ) const;

        /** creates a component using our component factory/context

            @throws ::com::sun::star::lang::ServiceNotRegisteredException
                if the given service is not registered
            @throws Exception
                if an exception occured during creating the component
            @return
                the newly created component. Is never <NULL/>.
        */
        ::com::sun::star::uno::Reference< ::com::sun::star::uno::XInterface > createComponent( const sal_Char* _pAsciiServiceName ) const
        {
            return createComponent( ::rtl::OUString::createFromAscii( _pAsciiServiceName ) );
        }

        /** retrieves a singleton instance from the context

            Singletons are collected below the /singletons key in a component context,
            so accessing them means retrieving the value under /singletons/<instance_name>.
        */
        ::com::sun::star::uno::Reference< ::com::sun::star::uno::XInterface > getSingleton( const ::rtl::OUString& _rInstanceName );

        /** retrieves a singleton instance from the context

            Singletons are collected below the /singletons key in a component context,
            so accessing them means retrieving the value under /singletons/<instance_name>.
        */
        ::com::sun::star::uno::Reference< ::com::sun::star::uno::XInterface > getSingleton( const sal_Char* _pAsciiInstanceName )
        {
            return getSingleton( ::rtl::OUString::createFromAscii( _pAsciiInstanceName ) );
        }

        /** returns the ->XMultiServiceFactory interface of ->m_xORB, for passing to
            older code which does not yet support ->XMultiComponentFactory
            @throws ::com::sun::star::uno::RuntimeException
                if our our component factory does not support this interface
        */
        ::com::sun::star::uno::Reference< ::com::sun::star::lang::XMultiServiceFactory >
            getLegacyServiceFactory() const;

        /** retrieves a value from our component context
            @param _rName
                the name of the value to retrieve
            @return
                the context value with the given name
            @seealso XComponentContext::getValueByName
            @seealso getContextValueByAsciiName
        */
        ::com::sun::star::uno::Any
                getContextValueByName( const ::rtl::OUString& _rName ) const;

        /** retrieves a value from our component context, specified by 8-bit ASCII string
            @param _rName
                the name of the value to retrieve, as ASCII character string
            @return
                the context value with the given name
            @seealso XComponentContext::getValueByName
            @seealso getContextValueByName
        */
        inline ::com::sun::star::uno::Any
                getContextValueByAsciiName( const sal_Char* _pAsciiName ) const
        {
            return getContextValueByName( ::rtl::OUString::createFromAscii( _pAsciiName ) );
        }

    };

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

#endif // COMPHELPER_COMPONENTCONTEXT_HXX

<commit_msg>INTEGRATION: CWS sdblogging (1.3.58); FILE MERGED 2007/04/11 08:48:02 fs 1.3.58.1: getSingleton should be const<commit_after>/*************************************************************************
 *
 *  OpenOffice.org - a multi-platform office productivity suite
 *
 *  $RCSfile: componentcontext.hxx,v $
 *
 *  $Revision: 1.4 $
 *
 *  last change: $Author: hr $ $Date: 2007-06-27 14:53:10 $
 *
 *  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 COMPHELPER_COMPONENTCONTEXT_HXX
#define COMPHELPER_COMPONENTCONTEXT_HXX

#ifndef INCLUDED_COMPHELPERDLLAPI_H
#include <comphelper/comphelperdllapi.h>
#endif

/** === begin UNO includes === **/
#ifndef _COM_SUN_STAR_UNO_XCOMPONENTCONTEXT_HPP_
#include <com/sun/star/uno/XComponentContext.hpp>
#endif
#ifndef _COM_SUN_STAR_LANG_XMULTISERVICEFACTORY_HPP_
#include <com/sun/star/lang/XMultiServiceFactory.hpp>
#endif
/** === end UNO includes === **/

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

    //====================================================================
    //= ComponentContext
    //====================================================================
    /** a helper class for working with a component context
    */
    class COMPHELPER_DLLPUBLIC ComponentContext
    {
    private:
        ::com::sun::star::uno::Reference< ::com::sun::star::uno::XComponentContext >        m_xContext;
        ::com::sun::star::uno::Reference< ::com::sun::star::lang::XMultiComponentFactory >  m_xORB;

    public:
        /** constructs an instance
            @param _rxContext
                the component context to manage
            @throws ::com::sun::star::lang::NullPointerException
                if the given context, or its component factory, are <NULL/>
        */
        ComponentContext( const ::com::sun::star::uno::Reference< ::com::sun::star::uno::XComponentContext >& _rxContext );

        /** constructs an instance
            @param _rxLegacyFactory
                the legacy service factor to obtain the <type scope="com::sun::star::uno">XComponentContext</type> from
            @throws ::com::sun::star::uno::RuntimeException
                if the given factory or does not have a DefaultContext property to obtain
                a component context
            @throws ::com::sun::star::lang::NullPointerException
                if the given factory is <NULL/>, or provides a component context being <NULL/>, or provides
                a component context whose component factory is <NULL/>
        */
        ComponentContext( const ::com::sun::star::uno::Reference< ::com::sun::star::lang::XMultiServiceFactory >& _rxLegacyFactory );

        /** returns the ->XComponentContext interface
        */
        inline ::com::sun::star::uno::Reference< ::com::sun::star::uno::XComponentContext >
            getUNOContext() const { return m_xContext; }

        /** determines whether the context is not <NULL/>
        */
        inline sal_Bool is() const
        {
            return m_xContext.is();
        }

        /** creates a component using our component factory/context
            @throws ::com::sun::star::uno::Exception
            @return
                <TRUE/> if and only if the component could be successfully created
        */
        template < typename INTERFACE >
        bool createComponent( const ::rtl::OUString& _rServiceName, ::com::sun::star::uno::Reference< INTERFACE >& _out_rxComponent ) const
        {
            _out_rxComponent.clear();
            _out_rxComponent = _out_rxComponent.query(
                m_xORB->createInstanceWithContext( _rServiceName, m_xContext )
            );
            return _out_rxComponent.is();
        }

        /** creates a component using our component factory/context
            @throws ::com::sun::star::uno::Exception
            @return
                <TRUE/> if and only if the component could be successfully created
        */
        template < typename INTERFACE >
        bool createComponent( const sal_Char* _pAsciiServiceName, ::com::sun::star::uno::Reference< INTERFACE >& _out_rxComponent ) const
        {
            return createComponent( ::rtl::OUString::createFromAscii( _pAsciiServiceName ), _out_rxComponent );
        }

        /** creates a component using our component factory/context, passing creation arguments
            @throws ::com::sun::star::uno::Exception
            @return
                <TRUE/> if and only if the component could be successfully created
        */
        template < typename INTERFACE >
        bool createComponentWithArguments( const ::rtl::OUString& _rServiceName, const ::com::sun::star::uno::Sequence< ::com::sun::star::uno::Any >& _rArguments, ::com::sun::star::uno::Reference< INTERFACE >& _out_rxComponent ) const
        {
            _out_rxComponent.clear();
            _out_rxComponent = _out_rxComponent.query(
                m_xORB->createInstanceWithArgumentsAndContext( _rServiceName, _rArguments, m_xContext )
            );
            return _out_rxComponent.is();
        }

        /** creates a component using our component factory/context, passing creation arguments
            @throws ::com::sun::star::uno::Exception
            @return
                <TRUE/> if and only if the component could be successfully created
        */
        template < typename INTERFACE >
        bool createComponentWithArguments( const sal_Char* _pAsciiServiceName, const ::com::sun::star::uno::Sequence< ::com::sun::star::uno::Any >& _rArguments, ::com::sun::star::uno::Reference< INTERFACE >& _out_rxComponent ) const
        {
            return createComponentWithArguments( ::rtl::OUString::createFromAscii( _pAsciiServiceName ), _rArguments, _out_rxComponent );
        }

        /** creates a component using our component factory/context

            @throws ::com::sun::star::lang::ServiceNotRegisteredException
                if the given service is not registered
            @throws Exception
                if an exception occured during creating the component
            @return
                the newly created component. Is never <NULL/>.
        */
        ::com::sun::star::uno::Reference< ::com::sun::star::uno::XInterface > createComponent( const ::rtl::OUString& _rServiceName ) const;

        /** creates a component using our component factory/context

            @throws ::com::sun::star::lang::ServiceNotRegisteredException
                if the given service is not registered
            @throws Exception
                if an exception occured during creating the component
            @return
                the newly created component. Is never <NULL/>.
        */
        ::com::sun::star::uno::Reference< ::com::sun::star::uno::XInterface > createComponent( const sal_Char* _pAsciiServiceName ) const
        {
            return createComponent( ::rtl::OUString::createFromAscii( _pAsciiServiceName ) );
        }

        /** retrieves a singleton instance from the context

            Singletons are collected below the /singletons key in a component context,
            so accessing them means retrieving the value under /singletons/<instance_name>.
        */
        ::com::sun::star::uno::Reference< ::com::sun::star::uno::XInterface > getSingleton( const ::rtl::OUString& _rInstanceName ) const;

        /** retrieves a singleton instance from the context

            Singletons are collected below the /singletons key in a component context,
            so accessing them means retrieving the value under /singletons/<instance_name>.
        */
        ::com::sun::star::uno::Reference< ::com::sun::star::uno::XInterface > getSingleton( const sal_Char* _pAsciiInstanceName ) const
        {
            return getSingleton( ::rtl::OUString::createFromAscii( _pAsciiInstanceName ) );
        }

        /** returns the ->XMultiServiceFactory interface of ->m_xORB, for passing to
            older code which does not yet support ->XMultiComponentFactory
            @throws ::com::sun::star::uno::RuntimeException
                if our our component factory does not support this interface
        */
        ::com::sun::star::uno::Reference< ::com::sun::star::lang::XMultiServiceFactory >
            getLegacyServiceFactory() const;

        /** retrieves a value from our component context
            @param _rName
                the name of the value to retrieve
            @return
                the context value with the given name
            @seealso XComponentContext::getValueByName
            @seealso getContextValueByAsciiName
        */
        ::com::sun::star::uno::Any
                getContextValueByName( const ::rtl::OUString& _rName ) const;

        /** retrieves a value from our component context, specified by 8-bit ASCII string
            @param _rName
                the name of the value to retrieve, as ASCII character string
            @return
                the context value with the given name
            @seealso XComponentContext::getValueByName
            @seealso getContextValueByName
        */
        inline ::com::sun::star::uno::Any
                getContextValueByAsciiName( const sal_Char* _pAsciiName ) const
        {
            return getContextValueByName( ::rtl::OUString::createFromAscii( _pAsciiName ) );
        }

    };

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

#endif // COMPHELPER_COMPONENTCONTEXT_HXX

<|endoftext|>


<commit_before>#include "File.h"

#include <fstream>

#define WIN32_LEAN_AND_MEAN
#include <Windows.h>

using namespace std;

namespace File
{
    size_t FindFile(char const* path, char const* mask, std::function<void(char const*, size_t)> functor)
    {
        WIN32_FIND_DATA fileData;
        HANDLE hFiles;

        string search = path;
        search += "/";
        search += mask;

        hFiles = FindFirstFile(search.c_str(), &fileData);

        if (INVALID_HANDLE_VALUE == hFiles)
        {
            return 0;
        }

        size_t count = 0;

        do
        {
            if (fileData.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY)
            {
                // recursive option?
            }
            else
            {
                string filename = path;
                filename += "/";
                filename += fileData.cFileName;
                if (sizeof(size_t) == 4)
                {
                    if (fileData.nFileSizeHigh)
                        continue;

                    functor(filename.c_str(), fileData.nFileSizeLow);
                }
                else
                {
                    functor(filename.c_str(), (__int64)fileData.nFileSizeHigh << 32 | fileData.nFileSizeLow);
                }
                ++count;
            }
        } while (FindNextFile(hFiles, &fileData) != 0);

        return count;
    }

    //----------------------------------------------------------------------------------------
    vector<char> ReadFileData(fstream& file, size_t bytes)
    {
        bytes = bytes < UINT32_MAX ? bytes : UINT32_MAX;

        vector<char> data;
        data.resize(bytes);
        file.read(data.data(), bytes);

        if (file.gcount() < bytes)
            data.resize((unsigned int)file.gcount());
        return data;
    }

    //----------------------------------------------------------------------------------------
    vector<char> ReadFile(char const* filename)
    {
        fstream file(filename, fstream::binary | fstream::in);

        file.seekg(fstream::end);
        size_t bytes = (size_t)file.tellg();
        file.seekg(fstream::beg);

        return ReadFileData(file, bytes);
    }
    //----------------------------------------------------------------------------------------
    vector<char> ReadFile(char const* filename, size_t bytes)
    {
        return ReadFileData(fstream(filename, fstream::binary | fstream::in), bytes);
    }
}<commit_msg>Fix compiler warning<commit_after>#include "File.h"

#include <fstream>

#define WIN32_LEAN_AND_MEAN
#include <Windows.h>

using namespace std;

namespace File
{
    size_t FindFile(char const* path, char const* mask, std::function<void(char const*, size_t)> functor)
    {
        WIN32_FIND_DATA fileData;
        HANDLE hFiles;

        string search = path;
        search += "/";
        search += mask;

        hFiles = FindFirstFile(search.c_str(), &fileData);

        if (INVALID_HANDLE_VALUE == hFiles)
        {
            return 0;
        }

        size_t count = 0;

        do
        {
            if (fileData.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY)
            {
                // recursive option?
            }
            else
            {
                string filename = path;
                filename += "/";
                filename += fileData.cFileName;
                if (sizeof(size_t) == 4)
                {
                    if (fileData.nFileSizeHigh)
                        continue;

                    functor(filename.c_str(), fileData.nFileSizeLow);
                }
                else
                {
                    functor(filename.c_str(), (__int64)fileData.nFileSizeHigh << 32 | fileData.nFileSizeLow);
                }
                ++count;
            }
        } while (FindNextFile(hFiles, &fileData) != 0);

        return count;
    }

    //----------------------------------------------------------------------------------------
    vector<char> ReadFileData(fstream& file, size_t bytes)
    {
        bytes = bytes < UINT32_MAX ? bytes : UINT32_MAX;

        vector<char> data;
        data.resize(bytes);
        file.read(data.data(), bytes);

        if (file.gcount() >= 0 && (size_t)file.gcount() < bytes)
            data.resize((unsigned int)file.gcount());
        return data;
    }

    //----------------------------------------------------------------------------------------
    vector<char> ReadFile(char const* filename)
    {
        fstream file(filename, fstream::binary | fstream::in);

        file.seekg(fstream::end);
        size_t bytes = (size_t)file.tellg();
        file.seekg(fstream::beg);

        return ReadFileData(file, bytes);
    }
    //----------------------------------------------------------------------------------------
    vector<char> ReadFile(char const* filename, size_t bytes)
    {
        return ReadFileData(fstream(filename, fstream::binary | fstream::in), bytes);
    }
}<|endoftext|>


<commit_before>/*
 * Copyright (C) 2008-2010 The QXmpp developers
 *
 * Author:
 *  Jeremy Lainé
 *
 * Source:
 *  http://code.google.com/p/qxmpp
 *
 * This file is a part of QXmpp library.
 *
 * This library is free software; you can redistribute it and/or
 * modify it under the terms of the GNU Lesser General Public
 * License as published by the Free Software Foundation; either
 * version 2.1 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
 * Lesser General Public License for more details.
 *
 */

#include "QXmppClient.h"
#include "QXmppConstants.h"
#include "QXmppInvokable.h"
#include "QXmppRemoteMethod.h"
#include "QXmppRpcIq.h"
#include "QXmppRpcManager.h"

/// Constructs a QXmppRpcManager.

QXmppRpcManager::QXmppRpcManager()
{
}

/// Adds a local interface which can be queried using RPC.
///
/// \param interface

void QXmppRpcManager::addInvokableInterface( QXmppInvokable *interface )
{
    m_interfaces[ interface->metaObject()->className() ] = interface;
}

/// Invokes a remote interface using RPC.
///
/// \param iq

void QXmppRpcManager::invokeInterfaceMethod( const QXmppRpcInvokeIq &iq )
{
    QXmppStanza::Error error;

    const QStringList methodBits = iq.method().split('.');
    if (methodBits.size() != 2)
        return;
    const QString interface = methodBits.first();
    const QString method = methodBits.last();
    QXmppInvokable *iface = m_interfaces.value(interface);
    if (iface)
    {
        if ( iface->isAuthorized( iq.from() ) )
        {

            if ( iface->interfaces().contains(method) )
            {
                QVariant result = iface->dispatch(method.toLatin1(),
                                                  iq.arguments() );
                QXmppRpcResponseIq resultIq;
                resultIq.setId(iq.id());
                resultIq.setTo(iq.from());
                resultIq.setValues(QVariantList() << result);
                client()->sendPacket( resultIq );
                return;
            }
            else
            {
                error.setType(QXmppStanza::Error::Cancel);
                error.setCondition(QXmppStanza::Error::ItemNotFound);
            }
        }
        else
        {
            error.setType(QXmppStanza::Error::Auth);
            error.setCondition(QXmppStanza::Error::Forbidden);
        }
    }
    else
    {
        error.setType(QXmppStanza::Error::Cancel);
        error.setCondition(QXmppStanza::Error::ItemNotFound);
    }
    QXmppRpcErrorIq errorIq;
    errorIq.setId(iq.id());
    errorIq.setTo(iq.from());
    errorIq.setQuery(iq);
    errorIq.setError(error);
    client()->sendPacket(errorIq);
}

/// Call a remote method using RPC with the specified arguments.

QXmppRemoteMethodResult QXmppRpcManager::callRemoteMethod( const QString &jid,
                                          const QString &interface,
                                          const QVariant &arg1,
                                          const QVariant &arg2,
                                          const QVariant &arg3,
                                          const QVariant &arg4,
                                          const QVariant &arg5,
                                          const QVariant &arg6,
                                          const QVariant &arg7,
                                          const QVariant &arg8,
                                          const QVariant &arg9,
                                          const QVariant &arg10 )
{
    QVariantList args;
    if( arg1.isValid() ) args << arg1;
    if( arg2.isValid() ) args << arg2;
    if( arg3.isValid() ) args << arg3;
    if( arg4.isValid() ) args << arg4;
    if( arg5.isValid() ) args << arg5;
    if( arg6.isValid() ) args << arg6;
    if( arg7.isValid() ) args << arg7;
    if( arg8.isValid() ) args << arg8;
    if( arg9.isValid() ) args << arg9;
    if( arg10.isValid() ) args << arg10;

    QXmppRemoteMethod method( jid, interface, args, client() );
    connect(this, SIGNAL(rpcCallResponse(QXmppRpcResponseIq)),
            &method, SLOT(gotResult(QXmppRpcResponseIq)));
    connect(this, SIGNAL(rpcCallError(QXmppRpcErrorIq)),
            &method, SLOT(gotError(QXmppRpcErrorIq)));

    return method.call();
}

QStringList QXmppRpcManager::discoveryFeatures() const
{
    // XEP-0009: Jabber-RPC
    return QStringList() << ns_rpc;
}

QList<QXmppDiscoveryIq::Identity> QXmppRpcManager::discoveryIdentities() const
{
    QXmppDiscoveryIq::Identity identity;
    identity.setCategory("automation");
    identity.setType("rpc");
    return QList<QXmppDiscoveryIq::Identity>() << identity;
}

bool QXmppRpcManager::handleStanza(const QDomElement &element)
{
    // XEP-0009: Jabber-RPC
    if (QXmppRpcInvokeIq::isRpcInvokeIq(element))
    {
        QXmppRpcInvokeIq rpcIqPacket;
        rpcIqPacket.parse(element);
        invokeInterfaceMethod(rpcIqPacket);
        return true;
    }
    else if(QXmppRpcResponseIq::isRpcResponseIq(element))
    {
        QXmppRpcResponseIq rpcResponseIq;
        rpcResponseIq.parse(element);
        emit rpcCallResponse(rpcResponseIq);
        return true;
    }
    else if(QXmppRpcErrorIq::isRpcErrorIq(element))
    {
        QXmppRpcErrorIq rpcErrorIq;
        rpcErrorIq.parse(element);
        emit rpcCallError(rpcErrorIq);
        return true;
    }
    return false;
}

<commit_msg>add a warning about QXmppRpcManager::callRemoteMethod() in code documentation<commit_after>/*
 * Copyright (C) 2008-2010 The QXmpp developers
 *
 * Author:
 *  Jeremy Lainé
 *
 * Source:
 *  http://code.google.com/p/qxmpp
 *
 * This file is a part of QXmpp library.
 *
 * This library is free software; you can redistribute it and/or
 * modify it under the terms of the GNU Lesser General Public
 * License as published by the Free Software Foundation; either
 * version 2.1 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
 * Lesser General Public License for more details.
 *
 */

#include "QXmppClient.h"
#include "QXmppConstants.h"
#include "QXmppInvokable.h"
#include "QXmppRemoteMethod.h"
#include "QXmppRpcIq.h"
#include "QXmppRpcManager.h"

/// Constructs a QXmppRpcManager.

QXmppRpcManager::QXmppRpcManager()
{
}

/// Adds a local interface which can be queried using RPC.
///
/// \param interface

void QXmppRpcManager::addInvokableInterface( QXmppInvokable *interface )
{
    m_interfaces[ interface->metaObject()->className() ] = interface;
}

/// Invokes a remote interface using RPC.
///
/// \param iq

void QXmppRpcManager::invokeInterfaceMethod( const QXmppRpcInvokeIq &iq )
{
    QXmppStanza::Error error;

    const QStringList methodBits = iq.method().split('.');
    if (methodBits.size() != 2)
        return;
    const QString interface = methodBits.first();
    const QString method = methodBits.last();
    QXmppInvokable *iface = m_interfaces.value(interface);
    if (iface)
    {
        if ( iface->isAuthorized( iq.from() ) )
        {

            if ( iface->interfaces().contains(method) )
            {
                QVariant result = iface->dispatch(method.toLatin1(),
                                                  iq.arguments() );
                QXmppRpcResponseIq resultIq;
                resultIq.setId(iq.id());
                resultIq.setTo(iq.from());
                resultIq.setValues(QVariantList() << result);
                client()->sendPacket( resultIq );
                return;
            }
            else
            {
                error.setType(QXmppStanza::Error::Cancel);
                error.setCondition(QXmppStanza::Error::ItemNotFound);
            }
        }
        else
        {
            error.setType(QXmppStanza::Error::Auth);
            error.setCondition(QXmppStanza::Error::Forbidden);
        }
    }
    else
    {
        error.setType(QXmppStanza::Error::Cancel);
        error.setCondition(QXmppStanza::Error::ItemNotFound);
    }
    QXmppRpcErrorIq errorIq;
    errorIq.setId(iq.id());
    errorIq.setTo(iq.from());
    errorIq.setQuery(iq);
    errorIq.setError(error);
    client()->sendPacket(errorIq);
}

/// Calls a remote method using RPC with the specified arguments.
///
/// \note This method blocks until the response is received, and it may
/// cause XMPP stanzas to be lost!

QXmppRemoteMethodResult QXmppRpcManager::callRemoteMethod( const QString &jid,
                                          const QString &interface,
                                          const QVariant &arg1,
                                          const QVariant &arg2,
                                          const QVariant &arg3,
                                          const QVariant &arg4,
                                          const QVariant &arg5,
                                          const QVariant &arg6,
                                          const QVariant &arg7,
                                          const QVariant &arg8,
                                          const QVariant &arg9,
                                          const QVariant &arg10 )
{
    QVariantList args;
    if( arg1.isValid() ) args << arg1;
    if( arg2.isValid() ) args << arg2;
    if( arg3.isValid() ) args << arg3;
    if( arg4.isValid() ) args << arg4;
    if( arg5.isValid() ) args << arg5;
    if( arg6.isValid() ) args << arg6;
    if( arg7.isValid() ) args << arg7;
    if( arg8.isValid() ) args << arg8;
    if( arg9.isValid() ) args << arg9;
    if( arg10.isValid() ) args << arg10;

    QXmppRemoteMethod method( jid, interface, args, client() );
    connect(this, SIGNAL(rpcCallResponse(QXmppRpcResponseIq)),
            &method, SLOT(gotResult(QXmppRpcResponseIq)));
    connect(this, SIGNAL(rpcCallError(QXmppRpcErrorIq)),
            &method, SLOT(gotError(QXmppRpcErrorIq)));

    return method.call();
}

QStringList QXmppRpcManager::discoveryFeatures() const
{
    // XEP-0009: Jabber-RPC
    return QStringList() << ns_rpc;
}

QList<QXmppDiscoveryIq::Identity> QXmppRpcManager::discoveryIdentities() const
{
    QXmppDiscoveryIq::Identity identity;
    identity.setCategory("automation");
    identity.setType("rpc");
    return QList<QXmppDiscoveryIq::Identity>() << identity;
}

bool QXmppRpcManager::handleStanza(const QDomElement &element)
{
    // XEP-0009: Jabber-RPC
    if (QXmppRpcInvokeIq::isRpcInvokeIq(element))
    {
        QXmppRpcInvokeIq rpcIqPacket;
        rpcIqPacket.parse(element);
        invokeInterfaceMethod(rpcIqPacket);
        return true;
    }
    else if(QXmppRpcResponseIq::isRpcResponseIq(element))
    {
        QXmppRpcResponseIq rpcResponseIq;
        rpcResponseIq.parse(element);
        emit rpcCallResponse(rpcResponseIq);
        return true;
    }
    else if(QXmppRpcErrorIq::isRpcErrorIq(element))
    {
        QXmppRpcErrorIq rpcErrorIq;
        rpcErrorIq.parse(element);
        emit rpcCallError(rpcErrorIq);
        return true;
    }
    return false;
}

<|endoftext|>


<commit_before><commit_msg>drop unneeded include<commit_after><|endoftext|>


<commit_before>//  Copyright 2010 Gregory Szorc
//
//  Licensed under the Apache License, Version 2.0 (the "License");
//  you may not use this file except in compliance with the License.
//  You may obtain a copy of the License at
//
//      http://www.apache.org/licenses/LICENSE-2.0
//
//  Unless required by applicable law or agreed to in writing, software
//  distributed under the License is distributed on an "AS IS" BASIS,
//  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
//  See the License for the specific language governing permissions and
//  limitations under the License.

#ifndef PBLOG_SERVER_BROKER_HPP_
#define PBLOG_SERVER_BROKER_HPP_

#include <pblog/pblog.h>
#include <pblog/server.hpp>
#include <pblog/store.hpp>

#include <vector>
#include <zmq.hpp>

namespace pblog {
namespace server {

using ::pblog::Store;
using ::std::string;
using ::std::vector;
using ::zmq::context_t;
using ::zmq::socket_t;

typedef struct broker_config {
    broker_config();
    string store_path;
    vector<string> listen_endpoints;
} broker_config;

// the broker is a ZMQ device that provides the core message routing component
// of pblogd. it binds to a number of sockets and coordinates all the workers
// in the system
class PBLOG_EXPORT Broker {
    public:
        Broker(const string config_file_path);
        Broker(Store *store);
        Broker(Store *store, context_t *ctx);

        ~Broker();

        void run();

    protected:
        context_t * zctx;
        socket_t * workers_sock;
        socket_t * clients_external_sock;
        vector<socket_t *> listen_sockets;
        vector<socket_t *> listen_proxy_sockets;
        vector<void *> worker_threads;
        Store * store;
        bool active;
        request_processor_start_data *worker_start_data;
        broker_config config;

        static bool ParseConfig(const string path, broker_config &config, string &error);

        void init();
        void create_worker_threads();
        void setup_internal_sockets();
        void setup_listener_sockets();

};

}} // namespaces

#endif<commit_msg>stub code for store watcher<commit_after>//  Copyright 2010 Gregory Szorc
//
//  Licensed under the Apache License, Version 2.0 (the "License");
//  you may not use this file except in compliance with the License.
//  You may obtain a copy of the License at
//
//      http://www.apache.org/licenses/LICENSE-2.0
//
//  Unless required by applicable law or agreed to in writing, software
//  distributed under the License is distributed on an "AS IS" BASIS,
//  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
//  See the License for the specific language governing permissions and
//  limitations under the License.

#ifndef PBLOG_SERVER_BROKER_HPP_
#define PBLOG_SERVER_BROKER_HPP_

#include <pblog/pblog.h>
#include <pblog/server.hpp>
#include <pblog/store.hpp>
#include <pblog/store_watcher.hpp>

#include <vector>
#include <zmq.hpp>

namespace pblog {
namespace server {

using ::pblog::Store;
using ::std::string;
using ::std::vector;
using ::zmq::context_t;
using ::zmq::socket_t;

typedef struct broker_config {
    broker_config();
    string store_path;
    vector<string> listen_endpoints;
} broker_config;

typedef struct store_watcher_start_data {
    context_t *zctx;
    Store *store;
    char *endpoint;
} store_watcher_start_data;

// the broker is a ZMQ device that provides the core message routing component
// of pblogd. it binds to a number of sockets and coordinates all the workers
// in the system
class PBLOG_EXPORT Broker {
    public:
        Broker(const string config_file_path);
        Broker(Store *store);
        Broker(Store *store, context_t *ctx);

        ~Broker();

        void run();

    protected:
        context_t * zctx;
        socket_t * workers_sock;
        socket_t * clients_external_sock;
        vector<socket_t *> listen_sockets;
        vector<socket_t *> listen_proxy_sockets;
        vector<void *> worker_threads;
        Store * store;
        bool active;
        request_processor_start_data * worker_start_data;
        broker_config config;
        void * store_watcher_thread;
        store_watcher_start_data * store_watcher_start;

        static bool ParseConfig(const string path, broker_config &config, string &error);
        static void * __stdcall StoreWatcherStart(void *data);

        void init();
        void create_worker_threads();
        void create_store_watcher();
        void setup_internal_sockets();
        void setup_listener_sockets();

};

}} // namespaces

#endif<|endoftext|>


<commit_before>//debugging level 0 = nothing
//debugging level 1 = critical errors
//debugging level 2 = errors
//debugging level 3 = status information
//debugging level 4 = extremely verbose status information
#define DEBUG 3

#include <iostream>
#include <cstdlib>
#include <cstdio>
#include <cmath>
#include <unistd.h>
#include <sys/types.h>
#include <sys/wait.h>
#include <sys/epoll.h>
#include <getopt.h>

enum {HANDLER_PROGRESSIVE, HANDLER_FLASH, HANDLER_APPLE, HANDLER_MICRO};

#define DEFAULT_PORT 80
#include "../util/server_setup.cpp"
#include "../util/http_parser.cpp"

int mainHandler(int CONN_fd){
  int handler = HANDLER_PROGRESSIVE;
  bool ready4data = false;//set to true when streaming starts
  bool inited = false;
  bool progressive_has_sent_header = false;
  int ss;
  std::string streamname;
  FLV_Pack * tag = 0;
  HTTPReader HTTP_R, HTTP_S;//HTTP Receiver en HTTP Sender.

  int retval;
  int poller = epoll_create(1);
  int sspoller = epoll_create(1);
  struct epoll_event ev;
  ev.events = EPOLLIN;
  ev.data.fd = CONN_fd;
  epoll_ctl(poller, EPOLL_CTL_ADD, CONN_fd, &ev);
  struct epoll_event events[1];

  std::string Movie = "";
  std::string Quality = "";
  int Segment = -1;
  int Fragment = -1;
  int temp;

  while (!socketError && !All_Hell_Broke_Loose){
    //only parse input if available or not yet init'ed
    retval = epoll_wait(poller, events, 1, 1);
    if ((retval > 0) || !ready4data){
      if (HTTP_R.ReadSocket(CONN_fd)){
        if( (HTTP_R.url.find("Seg") != std::string::npos) &&
            (HTTP_R.url.find("Frag") != std::string::npos) ) {
          handler = HANDLER_FLASH;
        }
        if(handler == HANDLER_FLASH) {
          Movie = HTTP_R.url.substr(1);
          Movie = Movie.substr(0,Movie.find("/"));
          Quality = HTTP_R.url.substr( HTTP_R.url.find("/",1)+1 );
          Quality = Quality.substr(0, Quality.find("Seg"));
          temp = HTTP_R.url.find("Seg") + 3;
          Segment = atoi( HTTP_R.url.substr(temp,HTTP_R.url.find("-",temp)-temp).c_str());
          temp = HTTP_R.url.find("Frag") + 4;
          Fragment = atoi( HTTP_R.url.substr(temp).c_str() );

          printf( "URL: %s\n", HTTP_R.url.c_str());
          printf( "Movie Identifier: %s\n", Movie.c_str() );
          printf( "Quality Modifier: %s\n", Quality.c_str() );
          printf( "Segment: %d\n", Segment );
          printf( "Fragment: %d\n", Fragment );
          streamname = "/tmp/shared_socket_";
          streamname += Movie.c_str();

          ready4data = true;
        }//FLASH handler
        //ERIK: we hebben nu een hele HTTP request geparsed - verwerken mag hier, door aanroepen naar
        //ERIK: bijvoorbeeld HTTP_R.GetHeader("headernaam") (voor headers) of HTTP_R.GetVar("varnaam") (voor GET/POST vars)
        //ERIK: of HTTP_R.method of HTTP_R.url of HTTP_R.protocol....
        //ERIK: zie ook ../util/http_parser.cpp - de class definitie bovenaan zou genoeg moeten zijn voor je

        //ERIK: Ik heb een handler variabele gemaakt die moet setten naar bijv HANDLER_FLASH in jouw geval.
        //ERIK: Als de handler niet is geset, is hij by default PROGRESSIVE, en daarvoor heb ik de verwerking al gecode.
        //ERIK: Je eigen handler instellen voorkomt dus dat mijn code hem handled alsof hij progressive is.
        if (handler == HANDLER_PROGRESSIVE){
          //in het geval progressive nemen we aan dat de URL de streamname is, met .flv erachter
          streamname = HTTP_R.url.substr(0, HTTP_R.url.size()-4);//strip de .flv
          for (std::string::iterator i=streamname.end()-1; i>=streamname.begin(); --i){
            if (!isalpha(*i) && !isdigit(*i)){streamname.erase(i);}else{*i=tolower(*i);}//strip nonalphanumeric
          }
          streamname = "/tmp/shared_socket_" + streamname;//dit is dan onze shared_socket
          //normaal zouden we ook een position uitlezen uit de URL, maar bij LIVE streams is dat zinloos
          ready4data = true;
        }//PROGRESSIVE handler
        HTTP_R.Clean(); //maak schoon na verwerken voor eventuele volgende requests...
      }
    }
    if (ready4data){
      if (!inited){
        //we are ready, connect the socket!
        ss = DDV_OpenUnix(streamname);
        if (ss <= 0){
          #if DEBUG >= 1
          fprintf(stderr, "Could not connect to server!\n");
          #endif
          socketError = 1;
          break;
        }
        ev.events = EPOLLIN;
        ev.data.fd = ss;
        epoll_ctl(sspoller, EPOLL_CTL_ADD, ss, &ev);
        #if DEBUG >= 3
        fprintf(stderr, "Everything connected, starting to send video data...\n");
        #endif
        inited = true;
      }

      retval = epoll_wait(sspoller, events, 1, 1);
      switch (DDV_ready(ss)){
        case 0:
          socketError = true;
          #if DEBUG >= 1
          fprintf(stderr, "Source socket is disconnected.\n");
          #endif
          break;
        case -1: break;//not ready yet
        default:
          if (FLV_GetPacket(tag, ss)){//able to read a full packet?
            //ERIK: "tag" bevat nu een FLV tag (video, audio, of metadata), de header hebben we al weggelezen, np.
            //ERIK: Dit is het punt waarop je eventueel data mag/kan gaan sturen en/of parsen. Leef je uit.
            //ERIK: je kan een HTTP_S gebruiken om je HTTP request op te bouwen (via SetBody, SetHeader, etc)
            //ERIK: en dan met de .BuildResponse("200", "OK"); call een std::string met de hele response maken, klaar voor versturen
            //ERIK: Note: hergebruik echter NIET de HTTP_R die ik al heb gemaakt hierboven, want er kunnen meerdere requests binnenkomen!
            if (handler == HANDLER_PROGRESSIVE){
              if (!progressive_has_sent_header){
                HTTP_S.Clean();//troep opruimen die misschien aanwezig is...
                HTTP_S.SetHeader("Content-Type", "video/x-flv");//FLV files hebben altijd dit content-type.
                std::string tmpresp = HTTP_S.BuildResponse("200", "OK");//geen SetBody = unknown length! Dat willen we hier.
                DDV_write(tmpresp.c_str(), tmpresp.size(), CONN_fd);//schrijf de HTTP response header
                DDV_write(FLVHeader, 13, CONN_fd);//schrijf de FLV header, altijd 13 chars lang
                progressive_has_sent_header = true;
              }
              DDV_write(tag->data, tag->len, CONN_fd);//schrijf deze FLV tag onbewerkt weg
            }//PROGRESSIVE handler
          }
          break;
      }
    }
  }
  close(CONN_fd);
  if (inited) close(ss);
  #if DEBUG >= 1
  if (All_Hell_Broke_Loose){fprintf(stderr, "All Hell Broke Loose\n");}
  fprintf(stderr, "User %i disconnected.\n", CONN_fd);
  if (inited){
    fprintf(stderr, "Status was: inited\n");
  }else{
    if (ready4data){
      fprintf(stderr, "Status was: ready4data\n");
    }else{
      fprintf(stderr, "Status was: connected\n");
    }
  }
  #endif
  return 0;
}

<commit_msg>adjustments to HTTP connector<commit_after>//debugging level 0 = nothing
//debugging level 1 = critical errors
//debugging level 2 = errors
//debugging level 3 = status information
//debugging level 4 = extremely verbose status information
#define DEBUG 3

#include <iostream>
#include <cstdlib>
#include <cstdio>
#include <cmath>
#include <unistd.h>
#include <sys/types.h>
#include <sys/wait.h>
#include <sys/epoll.h>
#include <getopt.h>

enum {HANDLER_PROGRESSIVE, HANDLER_FLASH, HANDLER_APPLE, HANDLER_MICRO};

#define DEFAULT_PORT 80
#include "../util/server_setup.cpp"
#include "../util/http_parser.cpp"

int mainHandler(int CONN_fd){
  int handler = HANDLER_PROGRESSIVE;
  bool ready4data = false;//set to true when streaming starts
  bool inited = false;
  bool progressive_has_sent_header = false;
  int ss;
  std::string streamname;
  FLV_Pack * tag = 0;
  HTTPReader HTTP_R, HTTP_S;//HTTP Receiver en HTTP Sender.

  int retval;
  int poller = epoll_create(1);
  int sspoller = epoll_create(1);
  struct epoll_event ev;
  ev.events = EPOLLIN;
  ev.data.fd = CONN_fd;
  epoll_ctl(poller, EPOLL_CTL_ADD, CONN_fd, &ev);
  struct epoll_event events[1];

  std::string Movie = "";
  std::string Quality = "";
  int Segment = -1;
  int Fragment = -1;
  int temp;

  while (!socketError && !All_Hell_Broke_Loose){
    //only parse input if available or not yet init'ed
    retval = epoll_wait(poller, events, 1, 1);
    if ((retval > 0) || !ready4data){
      if (HTTP_R.ReadSocket(CONN_fd)){
        if( (HTTP_R.url.find("Seg") != std::string::npos) &&
            (HTTP_R.url.find("Frag") != std::string::npos) ) {
          handler = HANDLER_FLASH;
        }
        printf( "Handler: %d\n", handler );
        if(handler == HANDLER_FLASH) {
          Movie = HTTP_R.url.substr(1);
          Movie = Movie.substr(0,Movie.find("/"));
          Quality = HTTP_R.url.substr( HTTP_R.url.find("/",1)+1 );
          Quality = Quality.substr(0, Quality.find("Seg"));
          temp = HTTP_R.url.find("Seg") + 3;
          Segment = atoi( HTTP_R.url.substr(temp,HTTP_R.url.find("-",temp)-temp).c_str());
          temp = HTTP_R.url.find("Frag") + 4;
          Fragment = atoi( HTTP_R.url.substr(temp).c_str() );

          printf( "URL: %s\n", HTTP_R.url.c_str());
          printf( "Movie Identifier: %s\n", Movie.c_str() );
          printf( "Quality Modifier: %s\n", Quality.c_str() );
          printf( "Segment: %d\n", Segment );
          printf( "Fragment: %d\n", Fragment );
          streamname = "/tmp/shared_socket_";
          streamname += Movie.c_str();

          ready4data = true;
        }//FLASH handler
        //ERIK: we hebben nu een hele HTTP request geparsed - verwerken mag hier, door aanroepen naar
        //ERIK: bijvoorbeeld HTTP_R.GetHeader("headernaam") (voor headers) of HTTP_R.GetVar("varnaam") (voor GET/POST vars)
        //ERIK: of HTTP_R.method of HTTP_R.url of HTTP_R.protocol....
        //ERIK: zie ook ../util/http_parser.cpp - de class definitie bovenaan zou genoeg moeten zijn voor je

        //ERIK: Ik heb een handler variabele gemaakt die moet setten naar bijv HANDLER_FLASH in jouw geval.
        //ERIK: Als de handler niet is geset, is hij by default PROGRESSIVE, en daarvoor heb ik de verwerking al gecode.
        //ERIK: Je eigen handler instellen voorkomt dus dat mijn code hem handled alsof hij progressive is.
        if (handler == HANDLER_PROGRESSIVE){
          //in het geval progressive nemen we aan dat de URL de streamname is, met .flv erachter
          streamname = HTTP_R.url.substr(0, HTTP_R.url.size()-4);//strip de .flv
          for (std::string::iterator i=streamname.end()-1; i>=streamname.begin(); --i){
            if (!isalpha(*i) && !isdigit(*i)){streamname.erase(i);}else{*i=tolower(*i);}//strip nonalphanumeric
          }
          streamname = "/tmp/shared_socket_" + streamname;//dit is dan onze shared_socket
          //normaal zouden we ook een position uitlezen uit de URL, maar bij LIVE streams is dat zinloos
  printf( "Streamname: %s\n", streamname.c_str() );
          ready4data = true;
        }//PROGRESSIVE handler
        HTTP_R.Clean(); //maak schoon na verwerken voor eventuele volgende requests...
      }
    }
    if (ready4data){
      if (!inited){
        //we are ready, connect the socket!
        ss = DDV_OpenUnix(streamname);
        if (ss <= 0){
          #if DEBUG >= 1
          fprintf(stderr, "Could not connect to server!\n");
          #endif
          socketError = 1;
          break;
        }
        ev.events = EPOLLIN;
        ev.data.fd = ss;
        epoll_ctl(sspoller, EPOLL_CTL_ADD, ss, &ev);
        #if DEBUG >= 3
        fprintf(stderr, "Everything connected, starting to send video data...\n");
        #endif
        inited = true;
      }

      retval = epoll_wait(sspoller, events, 1, 1);
      switch (DDV_ready(ss)){
        case 0:
          socketError = true;
          #if DEBUG >= 1
          fprintf(stderr, "Source socket is disconnected.\n");
          #endif
          break;
        case -1: break;//not ready yet
        default:
          if (FLV_GetPacket(tag, ss)){//able to read a full packet?
            //ERIK: "tag" bevat nu een FLV tag (video, audio, of metadata), de header hebben we al weggelezen, np.
            //ERIK: Dit is het punt waarop je eventueel data mag/kan gaan sturen en/of parsen. Leef je uit.
            //ERIK: je kan een HTTP_S gebruiken om je HTTP request op te bouwen (via SetBody, SetHeader, etc)
            //ERIK: en dan met de .BuildResponse("200", "OK"); call een std::string met de hele response maken, klaar voor versturen
            //ERIK: Note: hergebruik echter NIET de HTTP_R die ik al heb gemaakt hierboven, want er kunnen meerdere requests binnenkomen!
            if (handler == HANDLER_PROGRESSIVE){
              if (!progressive_has_sent_header){
                HTTP_S.Clean();//troep opruimen die misschien aanwezig is...
                HTTP_S.SetHeader("Content-Type", "video/x-flv");//FLV files hebben altijd dit content-type.
                std::string tmpresp = HTTP_S.BuildResponse("200", "OK");//geen SetBody = unknown length! Dat willen we hier.
                DDV_write(tmpresp.c_str(), tmpresp.size(), CONN_fd);//schrijf de HTTP response header
                DDV_write(FLVHeader, 13, CONN_fd);//schrijf de FLV header, altijd 13 chars lang
                progressive_has_sent_header = true;
              }
              DDV_write(tag->data, tag->len, CONN_fd);//schrijf deze FLV tag onbewerkt weg
            }//PROGRESSIVE handler
          }
          break;
      }
    }
  }
  close(CONN_fd);
  if (inited) close(ss);
  #if DEBUG >= 1
  if (All_Hell_Broke_Loose){fprintf(stderr, "All Hell Broke Loose\n");}
  fprintf(stderr, "User %i disconnected.\n", CONN_fd);
  if (inited){
    fprintf(stderr, "Status was: inited\n");
  }else{
    if (ready4data){
      fprintf(stderr, "Status was: ready4data\n");
    }else{
      fprintf(stderr, "Status was: connected\n");
    }
  }
  #endif
  return 0;
}

<|endoftext|>


<commit_before>// Copyright (c) 2009-2010 Satoshi Nakamoto
// Copyright (c) 2009-2014 The Bitcoin developers
// Distributed under the MIT software license, see the accompanying
// file COPYING or http://www.opensource.org/licenses/mit-license.php.

#include "core/block.h"
#include "core/transaction.h"
#include "main.h"
#include "rpcserver.h"
#include "streams.h"
#include "sync.h"
#include "utilstrencodings.h"
#include "version.h"

#include <boost/algorithm/string.hpp>

using namespace std;
using namespace json_spirit;

enum RetFormat {
    RF_BINARY,
    RF_HEX,
    RF_JSON,
};

static const struct {
    enum RetFormat rf;
    const char *name;
} rf_names[] = {
    { RF_BINARY, "binary" },            // default, if match not found
    { RF_HEX, "hex" },
    { RF_JSON, "json" },
};

class RestErr {
public:
    enum HTTPStatusCode status;
    string message;
};

extern void TxToJSON(const CTransaction& tx, const uint256 hashBlock, Object& entry);
extern Object blockToJSON(const CBlock& block, const CBlockIndex* blockindex);

static RestErr RESTERR(enum HTTPStatusCode status, string message)
{
    RestErr re;
    re.status = status;
    re.message = message;
    return re;
}

static enum RetFormat ParseDataFormat(const string& format)
{
    for (unsigned int i = 0; i < ARRAYLEN(rf_names); i++)
        if (format == rf_names[i].name)
            return rf_names[i].rf;

    return rf_names[0].rf;
}

static bool ParseHashStr(const string& strReq, uint256& v)
{
    if (!IsHex(strReq) || (strReq.size() != 64))
        return false;

    v.SetHex(strReq);
    return true;
}

static bool rest_block(AcceptedConnection *conn,
                       string& strReq,
                       map<string, string>& mapHeaders,
                       bool fRun)
{
    vector<string> params;
    boost::split(params, strReq, boost::is_any_of("/"));

    enum RetFormat rf = ParseDataFormat(params.size() > 1 ? params[1] : string(""));

    string hashStr = params[0];
    uint256 hash;
    if (!ParseHashStr(hashStr, hash))
        throw RESTERR(HTTP_BAD_REQUEST, "Invalid hash: " + hashStr);

    CBlock block;
    CBlockIndex* pblockindex = NULL;
    {
        LOCK(cs_main);
        if (mapBlockIndex.count(hash) == 0)
            throw RESTERR(HTTP_NOT_FOUND, hashStr + " not found");

        pblockindex = mapBlockIndex[hash];
        if (!ReadBlockFromDisk(block, pblockindex))
            throw RESTERR(HTTP_NOT_FOUND, hashStr + " not found");
    }

    CDataStream ssBlock(SER_NETWORK, PROTOCOL_VERSION);
    ssBlock << block;

    switch (rf) {
    case RF_BINARY: {
        string binaryBlock = ssBlock.str();
        conn->stream() << HTTPReplyHeader(HTTP_OK, fRun, binaryBlock.size(), "application/octet-stream") << binaryBlock << std::flush;
        return true;
    }

    case RF_HEX: {
        string strHex = HexStr(ssBlock.begin(), ssBlock.end()) + "\n";;
        conn->stream() << HTTPReply(HTTP_OK, strHex, fRun, false, "text/plain") << std::flush;
        return true;
    }

    case RF_JSON: {
        Object objBlock = blockToJSON(block, pblockindex);
        string strJSON = write_string(Value(objBlock), false) + "\n";
        conn->stream() << HTTPReply(HTTP_OK, strJSON, fRun) << std::flush;
        return true;
     }
    }

    // not reached
    return true;     // continue to process further HTTP reqs on this cxn
}

static bool rest_tx(AcceptedConnection *conn,
                    string& strReq,
                    map<string, string>& mapHeaders,
                    bool fRun)
{
    vector<string> params;
    boost::split(params, strReq, boost::is_any_of("/"));

    enum RetFormat rf = ParseDataFormat(params.size() > 1 ? params[1] : string(""));

    string hashStr = params[0];
    uint256 hash;
    if (!ParseHashStr(hashStr, hash))
        throw RESTERR(HTTP_BAD_REQUEST, "Invalid hash: " + hashStr);

    CTransaction tx;
    uint256 hashBlock = 0;
    if (!GetTransaction(hash, tx, hashBlock, true))
        throw RESTERR(HTTP_NOT_FOUND, hashStr + " not found");

    CDataStream ssTx(SER_NETWORK, PROTOCOL_VERSION);
    ssTx << tx;

    switch (rf) {
    case RF_BINARY: {
        string binaryTx = ssTx.str();
        conn->stream() << HTTPReplyHeader(HTTP_OK, fRun, binaryTx.size(), "application/octet-stream") << binaryTx << std::flush;
        return true;
    }

    case RF_HEX: {
        string strHex = HexStr(ssTx.begin(), ssTx.end()) + "\n";;
        conn->stream() << HTTPReply(HTTP_OK, strHex, fRun, false, "text/plain") << std::flush;
        return true;
    }

    case RF_JSON: {
        Object objTx;
        TxToJSON(tx, hashBlock, objTx);
        string strJSON = write_string(Value(objTx), false) + "\n";
        conn->stream() << HTTPReply(HTTP_OK, strJSON, fRun) << std::flush;
        return true;
    }
    }

    // not reached
    return true;     // continue to process further HTTP reqs on this cxn
}

static const struct {
    const char *prefix;
    bool (*handler)(AcceptedConnection *conn,
                    string& strURI,
                    map<string, string>& mapHeaders,
                    bool fRun);
} uri_prefixes[] = {
    { "/rest/tx/", rest_tx },
    { "/rest/block/", rest_block },
};

bool HTTPReq_REST(AcceptedConnection *conn,
                  string& strURI,
                  map<string, string>& mapHeaders,
                  bool fRun)
{
    try {
        std::string statusmessage;
        if(RPCIsInWarmup(&statusmessage))
            throw RESTERR(HTTP_SERVICE_UNAVAILABLE, "Service temporarily unavailable: "+statusmessage);

        for (unsigned int i = 0; i < ARRAYLEN(uri_prefixes); i++) {
            unsigned int plen = strlen(uri_prefixes[i].prefix);
            if (strURI.substr(0, plen) == uri_prefixes[i].prefix) {
                string strReq = strURI.substr(plen);
                return uri_prefixes[i].handler(conn, strReq, mapHeaders, fRun);
            }
        }
    }
    catch (RestErr& re) {
        conn->stream() << HTTPReply(re.status, re.message + "\r\n", false, false, "text/plain") << std::flush;
        return false;
    }

    conn->stream() << HTTPError(HTTP_NOT_FOUND, false) << std::flush;
    return false;
}
<commit_msg>[REST] make selection of output-format mandatory, support dot url syntax<commit_after>// Copyright (c) 2009-2010 Satoshi Nakamoto
// Copyright (c) 2009-2014 The Bitcoin developers
// Distributed under the MIT software license, see the accompanying
// file COPYING or http://www.opensource.org/licenses/mit-license.php.

#include "core/block.h"
#include "core/transaction.h"
#include "main.h"
#include "rpcserver.h"
#include "streams.h"
#include "sync.h"
#include "utilstrencodings.h"
#include "version.h"

#include <boost/algorithm/string.hpp>

using namespace std;
using namespace json_spirit;

enum RetFormat {
    RF_UNDEF,
    RF_BINARY,
    RF_HEX,
    RF_JSON,
};

static const struct {
    enum RetFormat rf;
    const char* name;
} rf_names[] = {
      {RF_UNDEF, ""},
      {RF_BINARY, "bin"},
      {RF_HEX, "hex"},
      {RF_JSON, "json"},
};

class RestErr
{
public:
    enum HTTPStatusCode status;
    string message;
};

extern void TxToJSON(const CTransaction& tx, const uint256 hashBlock, Object& entry);
extern Object blockToJSON(const CBlock& block, const CBlockIndex* blockindex);

static RestErr RESTERR(enum HTTPStatusCode status, string message)
{
    RestErr re;
    re.status = status;
    re.message = message;
    return re;
}

static enum RetFormat ParseDataFormat(vector<string>& params, const string strReq)
{
    boost::split(params, strReq, boost::is_any_of("."));
    if (params.size() > 1) {
        for (unsigned int i = 0; i < ARRAYLEN(rf_names); i++)
            if (params[1] == rf_names[i].name)
                return rf_names[i].rf;
    }

    return rf_names[0].rf;
}

static string AvailableDataFormatsString()
{
    string formats = "";
    for (unsigned int i = 0; i < ARRAYLEN(rf_names); i++)
        if (strlen(rf_names[i].name) > 0) {
            formats.append(".");
            formats.append(rf_names[i].name);
            formats.append(", ");
        }

    if (formats.length() > 0)
        return formats.substr(0, formats.length() - 2);

    return formats;
}

static bool ParseHashStr(const string& strReq, uint256& v)
{
    if (!IsHex(strReq) || (strReq.size() != 64))
        return false;

    v.SetHex(strReq);
    return true;
}

static bool rest_block(AcceptedConnection* conn,
                       string& strReq,
                       map<string, string>& mapHeaders,
                       bool fRun)
{
    vector<string> params;
    enum RetFormat rf = ParseDataFormat(params, strReq);

    string hashStr = params[0];
    uint256 hash;
    if (!ParseHashStr(hashStr, hash))
        throw RESTERR(HTTP_BAD_REQUEST, "Invalid hash: " + hashStr);

    CBlock block;
    CBlockIndex* pblockindex = NULL;
    {
        LOCK(cs_main);
        if (mapBlockIndex.count(hash) == 0)
            throw RESTERR(HTTP_NOT_FOUND, hashStr + " not found");

        pblockindex = mapBlockIndex[hash];
        if (!ReadBlockFromDisk(block, pblockindex))
            throw RESTERR(HTTP_NOT_FOUND, hashStr + " not found");
    }

    CDataStream ssBlock(SER_NETWORK, PROTOCOL_VERSION);
    ssBlock << block;

    switch (rf) {
    case RF_BINARY: {
        string binaryBlock = ssBlock.str();
        conn->stream() << HTTPReplyHeader(HTTP_OK, fRun, binaryBlock.size(), "application/octet-stream") << binaryBlock << std::flush;
        return true;
    }

    case RF_HEX: {
        string strHex = HexStr(ssBlock.begin(), ssBlock.end()) + "\n";
        conn->stream() << HTTPReply(HTTP_OK, strHex, fRun, false, "text/plain") << std::flush;
        return true;
    }

    case RF_JSON: {
        Object objBlock = blockToJSON(block, pblockindex);
        string strJSON = write_string(Value(objBlock), false) + "\n";
        conn->stream() << HTTPReply(HTTP_OK, strJSON, fRun) << std::flush;
        return true;
    }

    default: {
        throw RESTERR(HTTP_NOT_FOUND, "output format not found (available: " + AvailableDataFormatsString() + ")");
    }
    }

    // not reached
    return true; // continue to process further HTTP reqs on this cxn
}

static bool rest_tx(AcceptedConnection* conn,
                    string& strReq,
                    map<string, string>& mapHeaders,
                    bool fRun)
{
    vector<string> params;
    enum RetFormat rf = ParseDataFormat(params, strReq);

    string hashStr = params[0];
    uint256 hash;
    if (!ParseHashStr(hashStr, hash))
        throw RESTERR(HTTP_BAD_REQUEST, "Invalid hash: " + hashStr);

    CTransaction tx;
    uint256 hashBlock = 0;
    if (!GetTransaction(hash, tx, hashBlock, true))
        throw RESTERR(HTTP_NOT_FOUND, hashStr + " not found");

    CDataStream ssTx(SER_NETWORK, PROTOCOL_VERSION);
    ssTx << tx;

    switch (rf) {
    case RF_BINARY: {
        string binaryTx = ssTx.str();
        conn->stream() << HTTPReplyHeader(HTTP_OK, fRun, binaryTx.size(), "application/octet-stream") << binaryTx << std::flush;
        return true;
    }

    case RF_HEX: {
        string strHex = HexStr(ssTx.begin(), ssTx.end()) + "\n";
        conn->stream() << HTTPReply(HTTP_OK, strHex, fRun, false, "text/plain") << std::flush;
        return true;
    }

    case RF_JSON: {
        Object objTx;
        TxToJSON(tx, hashBlock, objTx);
        string strJSON = write_string(Value(objTx), false) + "\n";
        conn->stream() << HTTPReply(HTTP_OK, strJSON, fRun) << std::flush;
        return true;
    }

    default: {
        throw RESTERR(HTTP_NOT_FOUND, "output format not found (available: " + AvailableDataFormatsString() + ")");
    }
    }

    // not reached
    return true; // continue to process further HTTP reqs on this cxn
}

static const struct {
    const char* prefix;
    bool (*handler)(AcceptedConnection* conn,
                    string& strURI,
                    map<string, string>& mapHeaders,
                    bool fRun);
} uri_prefixes[] = {
      {"/rest/tx/", rest_tx},
      {"/rest/block/", rest_block},
};

bool HTTPReq_REST(AcceptedConnection* conn,
                  string& strURI,
                  map<string, string>& mapHeaders,
                  bool fRun)
{
    try {
        std::string statusmessage;
        if (RPCIsInWarmup(&statusmessage))
            throw RESTERR(HTTP_SERVICE_UNAVAILABLE, "Service temporarily unavailable: " + statusmessage);

        for (unsigned int i = 0; i < ARRAYLEN(uri_prefixes); i++) {
            unsigned int plen = strlen(uri_prefixes[i].prefix);
            if (strURI.substr(0, plen) == uri_prefixes[i].prefix) {
                string strReq = strURI.substr(plen);
                return uri_prefixes[i].handler(conn, strReq, mapHeaders, fRun);
            }
        }
    } catch (RestErr& re) {
        conn->stream() << HTTPReply(re.status, re.message + "\r\n", false, false, "text/plain") << std::flush;
        return false;
    }

    conn->stream() << HTTPError(HTTP_NOT_FOUND, false) << std::flush;
    return false;
}
<|endoftext|>


<commit_before>// Sh: A GPU metaprogramming language.
//
// Copyright (c) 2003 University of Waterloo Computer Graphics Laboratory
// Project administrator: Michael D. McCool
// Authors: Zheng Qin, Stefanus Du Toit, Kevin Moule, Tiberiu S. Popa,
//          Michael D. McCool
//
// This software is provided 'as-is', without any express or implied
// warranty. In no event will the authors be held liable for any damages
// arising from the use of this software.
//
// Permission is granted to anyone to use this software for any purpose,
// including commercial applications, and to alter it and redistribute it
// freely, subject to the following restrictions:
//
// 1. The origin of this software must not be misrepresented; you must
// not claim that you wrote the original software. If you use this
// software in a product, an acknowledgment in the product documentation
// would be appreciated but is not required.
//
// 2. Altered source versions must be plainly marked as such, and must
// not be misrepresented as being the original software.
//
// 3. This notice may not be removed or altered from any source
// distribution.
//////////////////////////////////////////////////////////////////////////////
#include <sh/sh.hpp>
#include <sh/shutil.hpp>
#include <iostream>
#include "Shader.hpp"
#include "Globals.hpp"

using namespace SH;
using namespace ShUtil;

#include "util.hpp"

class LuciteShader : public Shader {
public:
  ShProgram vsh, fsh;

  LuciteShader();
  ~LuciteShader();

  bool init();

  ShProgram vertex() { return vsh;}
  ShProgram fragment() { return fsh;}
};

LuciteShader::LuciteShader()
  : Shader("Refraction: Lucite")
{
}

LuciteShader::~LuciteShader()
{
}

bool LuciteShader::init()
{
  std::cerr << "Initializing " << name() << std::endl;

  std::string imageNames[6] = {"left", "right", "top", "bottom", "back", "front"};
  ShImage test_image;
  test_image.loadPng(std::string(SHMEDIA_DIR "/envmaps/aniroom/") + imageNames[0] + ".png");

  ShTextureCube<ShColor4f> cubemap(test_image.width(), test_image.height());
  {
    for (int i = 0; i < 6; i++) {
      ShImage image;
      image.loadPng(std::string(SHMEDIA_DIR "/envmaps/aniroom/") + imageNames[i] + ".png");
      cubemap.memory(image.memory(), static_cast<ShCubeDirection>(i));
    }
  }

  ShAttrib3f theta = ShAttrib3f(1.32f,1.3f,1.28f);
  theta.name("relative indices of refraction");
  theta.range(0.0f,2.0f);

  vsh = SH_BEGIN_PROGRAM("gpu:vertex") {
    ShInputPosition4f ipos;
    ShInputNormal3f inorm;

    ShOutputPosition4f opos;    // Position in NDC
    ShOutputNormal3f onorm;     // view-space normal
    ShOutputVector3f reflv;     // reflection vector
    ShOutputVector3f refrv[3];  // refraction vectors (per RGB channel)
    ShOutputAttrib3f fres;      // fresnel terms (per RGB channel)

    opos = Globals::mvp | ipos; // Compute NDC position
    onorm = Globals::mv | inorm; // Compute view-space normal
    onorm = normalize(onorm);
    ShPoint3f posv = (Globals::mv | ipos)(0,1,2); // Compute view-space position
    ShPoint3f viewv = -normalize(posv); // Compute view vector

    reflv = reflect(viewv,onorm); // Compute reflection vector

    // actually do reflection lookup in model space
    reflv = Globals::mv_inverse | reflv;

    for (int i=0; i<3; i++) {
    	refrv[i] = refract(viewv,onorm,theta[i]); // Compute refraction vectors

        // actually do refraction lookup in model space
        refrv[i] = Globals::mv_inverse | refrv[i];

        fres[i] = fresnel(viewv,onorm,theta[i]); // Compute fresnel term
    }
  } SH_END;

  fsh = SH_BEGIN_PROGRAM("gpu:fragment") {
    ShInputPosition4f posh;
    ShInputNormal3f n;  // normal
    ShInputVector3f reflv;     // reflection vector
    ShInputVector3f refrv[3];     // refraction vectors (per RGB channel)
    ShInputAttrib3f fres;         // fresnel terms (per RGB channel)

    ShOutputColor3f result;

    result = fres*cubemap(reflv)(0,1,2);
    for (int i=0; i<3; i++) {
        result[i] += (1.0f-fres[i])*cubemap(refrv[i])(i);
    }
  } SH_END;

  return true;
}

LuciteShader the_lucite_shader;
<commit_msg>added more name and variable documentation (so can use this shader as an example in shrike when showing output code).   uncovered a few bugs... get a crash if a program is named before it is initialized, title and desc are not documented in doxygen.<commit_after>// Sh: A GPU metaprogramming language.
//
// Copyright (c) 2003 University of Waterloo Computer Graphics Laboratory
// Project administrator: Michael D. McCool
// Authors: Zheng Qin, Stefanus Du Toit, Kevin Moule, Tiberiu S. Popa,
//          Michael D. McCool
//
// This software is provided 'as-is', without any express or implied
// warranty. In no event will the authors be held liable for any damages
// arising from the use of this software.
//
// Permission is granted to anyone to use this software for any purpose,
// including commercial applications, and to alter it and redistribute it
// freely, subject to the following restrictions:
//
// 1. The origin of this software must not be misrepresented; you must
// not claim that you wrote the original software. If you use this
// software in a product, an acknowledgment in the product documentation
// would be appreciated but is not required.
//
// 2. Altered source versions must be plainly marked as such, and must
// not be misrepresented as being the original software.
//
// 3. This notice may not be removed or altered from any source
// distribution.
//////////////////////////////////////////////////////////////////////////////
#include <sh/sh.hpp>
#include <sh/shutil.hpp>
#include <iostream>
#include "Shader.hpp"
#include "Globals.hpp"

using namespace SH;
using namespace ShUtil;

#include "util.hpp"

class LuciteShader : public Shader {
public:
  ShProgram vsh, fsh;

  LuciteShader();
  ~LuciteShader();

  bool init();

  ShProgram vertex() { return vsh;}
  ShProgram fragment() { return fsh;}
};

LuciteShader::LuciteShader()
  : Shader("Refraction: Lucite")
{
}

LuciteShader::~LuciteShader()
{
}

bool LuciteShader::init()
{
  std::cerr << "Initializing " << name() << std::endl;

  std::string imageNames[6] = {"left", "right", "top", "bottom", "back", "front"};
  ShImage test_image;
  test_image.loadPng(std::string(SHMEDIA_DIR "/envmaps/aniroom/") + imageNames[0] + ".png");

  ShTextureCube<ShColor4f> SH_DECL(cubemap) =
	  ShTextureCube<ShColor4f>(test_image.width(), test_image.height());
  {
    for (int i = 0; i < 6; i++) {
      ShImage image;
      image.loadPng(std::string(SHMEDIA_DIR "/envmaps/aniroom/") + imageNames[i] + ".png");
      cubemap.memory(image.memory(), static_cast<ShCubeDirection>(i));
    }
  }

  ShAttrib3f SH_DECL(eta) = ShAttrib3f(1.32f,1.3f,1.28f);
  eta.title("relative indices of refraction");
  eta.description("relative indices of refraction for each color component to model dispersion");
  eta.range(0.0f,2.0f);

  vsh = SH_BEGIN_PROGRAM("gpu:vertex") {
    ShInputPosition4f SH_DECL(ipos);
    ShInputNormal3f SH_DECL(inorm);

    ShOutputPosition4f SH_DECL(opos);    // Position in NDC
    ShOutputNormal3f SH_DECL(onorm);     // view-space normal
    ShOutputVector3f SH_DECL(reflv);     // reflection vector
    ShOutputVector3f refrv[3];  // refraction vectors (per RGB channel)
    refrv[0].name("refrv[0]");  // should be nicer way to name these
    refrv[1].name("refrv[1]");
    refrv[2].name("refrv[2]");
    ShOutputAttrib3f SH_DECL(fres);      // fresnel terms (per RGB channel)

    opos = Globals::mvp | ipos; // Compute NDC position
    onorm = Globals::mv | inorm; // Compute view-space normal
    onorm = normalize(onorm);
    ShPoint3f SH_DECL(posv) = (Globals::mv | ipos)(0,1,2); // Compute view-space position
    ShPoint3f SH_DECL(viewv) = -normalize(posv); // Compute view vector

    reflv = reflect(viewv,onorm); // Compute reflection vector

    // actually do reflection lookup in model space
    reflv = Globals::mv_inverse | reflv;

    for (int i=0; i<3; i++) {
    	refrv[i] = refract(viewv,onorm,eta[i]); // Compute refraction vectors

        // actually do refraction lookup in model space
        refrv[i] = Globals::mv_inverse | refrv[i];

        fres[i] = fresnel(viewv,onorm,eta[i]); // Compute fresnel term
    }
  } SH_END;
  vsh.name("LuciteShader::vsh");

  fsh = SH_BEGIN_PROGRAM("gpu:fragment") {
    ShInputPosition4f SH_DECL(posh);
    ShInputNormal3f SH_DECL(n);  // normal
    ShInputVector3f SH_DECL(reflv);     // reflection vector
    ShInputVector3f refrv[3];     // refraction vectors (per RGB channel)
    refrv[0].name("refrv[0]");  // should be nicer way to name these
    refrv[1].name("refrv[1]");
    refrv[2].name("refrv[2]");
    ShInputAttrib3f SH_DECL(fres);         // fresnel terms (per RGB channel)

    ShOutputColor3f SH_DECL(result);

    result = fres*cubemap(reflv)(0,1,2);
    for (int i=0; i<3; i++) {
        result[i] += (1.0f-fres[i])*cubemap(refrv[i])(i);
    }
  } SH_END;
  fsh.name("LuciteShader::fsh");

  return true;
}

LuciteShader the_lucite_shader;
<|endoftext|>


<commit_before>#include "stdafx.h"
#include "CtrlrPanelViewport.h"
#include "CtrlrPanel/CtrlrPanel.h"
#include "CtrlrPanelEditor.h"
#include "CtrlrManager/CtrlrManager.h"

/**
 */

CtrlrPanelViewport::CtrlrPanelViewport (CtrlrPanelEditor &_owner)
	: owner(_owner), isSpaceDown(false)
{
	currentZoom = 1.0;

	canvasList.add (new CtrlrPanelCanvas (owner));

	magnifier = new CtrlrMagnifierComponent (canvasList[0]);
	addAndMakeVisible (viewport = new CtrlrViewportImpl(this));
	viewport->setViewedComponent (magnifier);

    setSize (512, 512);
}

CtrlrPanelViewport::~CtrlrPanelViewport()
{
	canvasList.clear (false);
	deleteAndZero (viewport);
}

void CtrlrPanelViewport::paint (Graphics& g)
{
	g.fillAll (Colours::transparentBlack);
}

void CtrlrPanelViewport::resized()
{
	viewport->setBounds	(0, 0, getWidth(), getHeight());
}

bool CtrlrPanelViewport::keyStateChanged (const bool isKeyDown)
{
	if (KeyPress::isKeyCurrentlyDown(KeyPress::spaceKey))
	{
		dragKeyHeldDown (true);
	}
	else
	{
		dragKeyHeldDown (false);
	}
    return false;
}

void CtrlrPanelViewport::setZoom (const double zoom, int anchorX, int anchorY)
{
	if (zoom < 0.5)
		return;

	currentZoom = zoom;

	Point<int> anchor (getCurrentCanvas()->getLocalPoint (viewport, Point<int> (anchorX, anchorY)));

	resized();
	anchor = viewport->getLocalPoint (getCurrentCanvas(), anchor);

	viewport->setViewPosition (jlimit (0, jmax (0, viewport->getViewedComponent()->getWidth() - viewport->getViewWidth()),
                                       viewport->getViewPositionX() + anchor.getX() - anchorX),
                               jlimit (0, jmax (0, viewport->getViewedComponent()->getHeight() - viewport->getViewHeight()),
                                       viewport->getViewPositionY() + anchor.getY() - anchorY));
	magnifier->setScaleFactor (currentZoom);
}

const double CtrlrPanelViewport::getZoom ()
{
	return (currentZoom);
}

void CtrlrPanelViewport::dragKeyHeldDown (const bool isKeyDown)
{
	if (isSpaceDown != isKeyDown)
	{
		isSpaceDown = isKeyDown;

		if (isSpaceDown)
		{
			CtrlrDraggerOverlayComp* const dc = new CtrlrDraggerOverlayComp(viewport);
			addAndMakeVisible (dc);
			dc->setBounds (0, 0, getWidth(), getHeight());
		}
		else
		{
			for (int i = getNumChildComponents(); --i >= 0;)
			{
				if (dynamic_cast <CtrlrDraggerOverlayComp*> (getChildComponent (i)) != 0)
				{
					delete getChildComponent (i);
				}
			}
		}
	}
}

CtrlrViewportImpl::CtrlrViewportImpl(CtrlrPanelViewport *_panelViewport) : panelViewport(_panelViewport)
{
}

CtrlrViewportImpl::~CtrlrViewportImpl()
{
}

void CtrlrViewportImpl::mouseWheelMove (const MouseEvent& e, const MouseWheelDetails& wheel)
{
    if (e.mods.isCtrlDown() || e.mods.isAltDown())
	{
	    const double factor = (wheel.deltaY > 0) ? 2.0 : 0.5;

		panelViewport->setZoom (panelViewport->getZoom() * factor, e.x, e.y);
    }
    else
    {
		CtrlrViewport::mouseWheelMove (e, wheel);
	}
}

bool CtrlrViewportImpl::keyPressed (const KeyPress &key, Component *originatingComponent)
{
	return (false);
}

bool CtrlrViewportImpl::keyStateChanged (bool isKeyDown, Component *originatingComponent)
{
	return (false);
}

void CtrlrPanelViewport::setCurrentEditedCanvas(const int canvasIndex)
{
}

void CtrlrPanelViewport::addCanvas(const String &canvasName)
{
	CtrlrPanelCanvas *c = new CtrlrPanelCanvas (owner);
	c->setProperty (Ids::uiPanelCanvasLayerName, canvasName);
	c->setProperty (Ids::uiPanelCanvasLayerIndex, canvasList.size());

	canvasList.add (c);
}

void CtrlrPanelViewport::removeCanvas(const int canvasIndex)
{
}

const int CtrlrPanelViewport::getNumCanvases()
{
	return (canvasList.size());
}

void CtrlrPanelViewport::moveCanvasUp(const int canvasIndex)
{
}

void CtrlrPanelViewport::moveCanvasDown(const int canvasIndex)
{
}

CtrlrPanelCanvas *CtrlrPanelViewport::getCurrentCanvas()
{
	return (canvasList[0]);
}

void CtrlrPanelViewport::lookAndFeelChanged()
{
	resized();
}
<commit_msg>zoomin and zoomout corrected.<commit_after>#include "stdafx.h"
#include "CtrlrPanelViewport.h"
#include "CtrlrPanel/CtrlrPanel.h"
#include "CtrlrPanelEditor.h"
#include "CtrlrManager/CtrlrManager.h"

/**
 */

CtrlrPanelViewport::CtrlrPanelViewport (CtrlrPanelEditor &_owner)
	: owner(_owner), isSpaceDown(false)
{
	currentZoom = 1.0;

	canvasList.add (new CtrlrPanelCanvas (owner));

	magnifier = new CtrlrMagnifierComponent (canvasList[0]);
	addAndMakeVisible (viewport = new CtrlrViewportImpl(this));
	viewport->setViewedComponent (magnifier);

    setSize (512, 512);
}

CtrlrPanelViewport::~CtrlrPanelViewport()
{
	canvasList.clear (false);
	deleteAndZero (viewport);
}

void CtrlrPanelViewport::paint (Graphics& g)
{
	g.fillAll (Colours::transparentBlack);
}

void CtrlrPanelViewport::resized()
{
	viewport->setBounds	(0, 0, getWidth(), getHeight());
}

bool CtrlrPanelViewport::keyStateChanged (const bool isKeyDown)
{
	if (KeyPress::isKeyCurrentlyDown(KeyPress::spaceKey))
	{
		dragKeyHeldDown (true);
	}
	else
	{
		dragKeyHeldDown (false);
	}
    return false;
}

void CtrlrPanelViewport::setZoom (const double zoom, int anchorX, int anchorY)
{
	if (zoom < 0.5)
		return;

	currentZoom = zoom;

	Point<int> anchor (getCurrentCanvas()->getLocalPoint (viewport, Point<int> (anchorX, anchorY)));

	resized();
	anchor = viewport->getLocalPoint (getCurrentCanvas(), anchor);

	viewport->setViewPosition (jlimit (0, jmax (0, viewport->getViewedComponent()->getWidth() - viewport->getViewWidth()),
                                       viewport->getViewPositionX() + anchor.getX() - anchorX),
                               jlimit (0, jmax (0, viewport->getViewedComponent()->getHeight() - viewport->getViewHeight()),
                                       viewport->getViewPositionY() + anchor.getY() - anchorY));
	magnifier->setScaleFactor (currentZoom);
}

const double CtrlrPanelViewport::getZoom ()
{
	return (currentZoom);
}

void CtrlrPanelViewport::dragKeyHeldDown (const bool isKeyDown)
{
	if (isSpaceDown != isKeyDown)
	{
		isSpaceDown = isKeyDown;

		if (isSpaceDown)
		{
			CtrlrDraggerOverlayComp* const dc = new CtrlrDraggerOverlayComp(viewport);
			addAndMakeVisible (dc);
			dc->setBounds (0, 0, getWidth(), getHeight());
		}
		else
		{
			for (int i = getNumChildComponents(); --i >= 0;)
			{
				if (dynamic_cast <CtrlrDraggerOverlayComp*> (getChildComponent (i)) != 0)
				{
					delete getChildComponent (i);
				}
			}
		}
	}
}

CtrlrViewportImpl::CtrlrViewportImpl(CtrlrPanelViewport *_panelViewport) : panelViewport(_panelViewport)
{
}

CtrlrViewportImpl::~CtrlrViewportImpl()
{
}

void CtrlrViewportImpl::mouseWheelMove (const MouseEvent& e, const MouseWheelDetails& wheel)
{
    if (e.mods.isCtrlDown() || e.mods.isAltDown())
	{
		const double factor = (wheel.deltaY > 0) ? 1.10 : 0.90;
		panelViewport->setZoom (panelViewport->getZoom() * factor, e.x, e.y);
    }
    else
    {
		CtrlrViewport::mouseWheelMove (e, wheel);
	}
}

bool CtrlrViewportImpl::keyPressed (const KeyPress &key, Component *originatingComponent)
{
	return (false);
}

bool CtrlrViewportImpl::keyStateChanged (bool isKeyDown, Component *originatingComponent)
{
	return (false);
}

void CtrlrPanelViewport::setCurrentEditedCanvas(const int canvasIndex)
{
}

void CtrlrPanelViewport::addCanvas(const String &canvasName)
{
	CtrlrPanelCanvas *c = new CtrlrPanelCanvas (owner);
	c->setProperty (Ids::uiPanelCanvasLayerName, canvasName);
	c->setProperty (Ids::uiPanelCanvasLayerIndex, canvasList.size());

	canvasList.add (c);
}

void CtrlrPanelViewport::removeCanvas(const int canvasIndex)
{
}

const int CtrlrPanelViewport::getNumCanvases()
{
	return (canvasList.size());
}

void CtrlrPanelViewport::moveCanvasUp(const int canvasIndex)
{
}

void CtrlrPanelViewport::moveCanvasDown(const int canvasIndex)
{
}

CtrlrPanelCanvas *CtrlrPanelViewport::getCurrentCanvas()
{
	return (canvasList[0]);
}

void CtrlrPanelViewport::lookAndFeelChanged()
{
	resized();
}
<|endoftext|>