<commit_before>#include "OpenNIPlugin.h"
#include <iostream>
#include <StreamTypes.h>
#include "../../SenseKit/sensekit_internal.h"

#ifndef MIN
#define MIN(a,b) (((a)<(b))?(a):(b))
#endif

#ifndef MAX
#define MAX(a,b) (((a)>(b))?(a):(b))
#endif

using std::cout;
using std::endl;

EXPORT_PLUGIN(sensekit::openni::OpenNIPlugin);

namespace sensekit
{
    namespace openni
    {
        OpenNIPlugin::OpenNIPlugin(PluginServiceProxy* pluginService)
            : PluginBase(pluginService)
        {
            ::openni::Status rc = ::openni::STATUS_OK;

            const char* deviceURI = ::openni::ANY_DEVICE;

            cout << "Initializing openni" << endl;
            rc = ::openni::OpenNI::initialize();
            cout << "Opening device" << endl;
            rc = m_device.open(deviceURI);

            if (rc != ::openni::STATUS_OK)
            {
                cout << "Failed to open" << endl;
                ::openni::OpenNI::shutdown();
            }

            m_deviceInfo = m_device.getDeviceInfo();

            open_sensor_streams();
        }

        OpenNIPlugin::~OpenNIPlugin()
        {
            get_pluginService().destroy_stream(m_depthHandle);
            get_pluginService().destroy_stream(m_colorHandle);
            get_pluginService().destroy_stream_set(m_streamSetHandle);
            close_sensor_streams();

            cout << "closing device" << endl;
            m_device.close();
            cout << "shutting down openni" << endl;
            ::openni::OpenNI::shutdown();
        }

        sensekit_status_t OpenNIPlugin::open_sensor_streams()
        {
            ::openni::Status rc = ::openni::STATUS_OK;

            cout << "opening depth stream" << endl;
            rc = m_depthStream.create(m_device, ::openni::SENSOR_DEPTH);
            if (rc == ::openni::STATUS_OK)
            {
                cout << "starting depth stream." << endl;
                rc = m_depthStream.start();
                if (rc != ::openni::STATUS_OK)
                {
                    cout << "failed to start depth stream" << endl;
                    m_depthStream.destroy();
                }
            }
            else
            {
                cout << "Failed to open depth stream" << endl;
            }

            if (!m_depthStream.isValid())
            {
                cout << "shutting down openni because of failure" << endl;
                ::openni::OpenNI::shutdown();
            }

            cout << "opening color stream" << endl;
            rc = m_colorStream.create(m_device, ::openni::SENSOR_COLOR);
            if (rc == ::openni::STATUS_OK)
            {
                cout << "starting color stream." << endl;
                rc = m_colorStream.start();
                if (rc != ::openni::STATUS_OK)
                {
                    cout << "failed to start color stream" << endl;
                    m_colorStream.destroy();
                }
            }
            else
            {
                cout << "Failed to open color stream" << endl;
            }

            if (!m_colorStream.isValid())
            {
                cout << "shutting down openni because of failure" << endl;
                ::openni::OpenNI::shutdown();
            }

            sensekit_frame_t* nextBuffer = nullptr;

            stream_callbacks_t pluginCallbacks = create_plugin_callbacks(this);

            get_pluginService().create_stream_set(m_streamSetHandle);

            sensekit_stream_desc_t depthDesc;
            depthDesc.type = SENSEKIT_STREAM_DEPTH;
            depthDesc.subType = DEPTH_DEFAULT_SUBTYPE;

            get_pluginService().create_stream(m_streamSetHandle,
                                              depthDesc,
                                              pluginCallbacks,
                                              &m_depthHandle);

            sensekit_stream_desc_t colorDesc;
            colorDesc.type = SENSEKIT_STREAM_COLOR;
            colorDesc.subType = COLOR_DEFAULT_SUBTYPE;

            get_pluginService().create_stream(m_streamSetHandle,
                                              colorDesc,
                                              pluginCallbacks,
                                              &m_colorHandle);

            m_depthMode = m_depthStream.getVideoMode();
            m_colorMode = m_colorStream.getVideoMode();

            m_depthBufferLength  = m_depthMode.getResolutionX() * m_depthMode.getResolutionY() * 2;
            m_colorBufferLength = m_colorMode.getResolutionX() * m_colorMode.getResolutionY() * 3;

            get_pluginService()
                .create_stream_bin(m_depthHandle,
                                   sizeof(sensekit_depthframe_wrapper_t) + m_depthBufferLength,
                                   &m_depthBinHandle,
                                   &nextBuffer);

            set_new_depth_buffer(nextBuffer);

            get_pluginService()
                .create_stream_bin(m_colorHandle,
                                   sizeof(sensekit_colorframe_wrapper_t) + m_colorBufferLength,
                                   &m_colorBinHandle,
                                   &nextBuffer);

            set_new_color_buffer(nextBuffer);

            return SENSEKIT_STATUS_SUCCESS;
        }

        void OpenNIPlugin::set_parameter(sensekit_streamconnection_t streamConnection,
                                         sensekit_parameter_id id, size_t byteLength,
                                         sensekit_parameter_data_t* data)
        {}

        void OpenNIPlugin::get_parameter_size(sensekit_streamconnection_t streamConnection,
                                              sensekit_parameter_id id,
                                              size_t& byteLength)
        {}

        void OpenNIPlugin::get_parameter_data(sensekit_streamconnection_t streamConnection,
                                              sensekit_parameter_id id,
                                              size_t byteLength,
                                              sensekit_parameter_data_t* data)
        {}

        void OpenNIPlugin::connection_added(sensekit_streamconnection_t connection)
        {
            sensekit_stream_desc_t desc;
            sensekit_stream_get_description(connection, &desc);

            switch (desc.type)
            {
            case SENSEKIT_STREAM_DEPTH:
                get_pluginService().link_connection_to_bin(connection, m_depthBinHandle);
                cout << "openniplugin: new connection added, linked to global depth" << endl;
                break;
            case SENSEKIT_STREAM_COLOR:
                get_pluginService().link_connection_to_bin(connection, m_colorBinHandle);
                cout << "openniplugin: new connection added, linked to global color" << endl;
                break;
            }
        }

        void OpenNIPlugin::connection_removed(sensekit_streamconnection_t connection)
        {
            sensekit_stream_desc_t desc;
            sensekit_stream_get_description(connection, &desc);

            switch (desc.type)
            {
            case SENSEKIT_STREAM_DEPTH:
                get_pluginService().link_connection_to_bin(connection, nullptr);
                cout << "openniplugin: connection removed, unlinking from depth" << endl;
                break;
            case SENSEKIT_STREAM_COLOR:
                get_pluginService().link_connection_to_bin(connection, nullptr);
                cout << "openniplugin: connection removed, unlinking from color" << endl;
                break;
            }
        }

        sensekit_status_t OpenNIPlugin::close_sensor_streams()
        {
            cout << "stopping depth stream" << endl;
            m_depthStream.stop();
            cout << "destroying depth stream" << endl;
            m_depthStream.destroy();

            cout << "stopping color stream" << endl;
            m_colorStream.stop();
            cout << "destroying color stream" << endl;
            m_colorStream.destroy();

            return SENSEKIT_STATUS_SUCCESS;
        }

        void OpenNIPlugin::set_new_depth_buffer(sensekit_frame_t* nextBuffer)
        {
            m_currentDepthBuffer = nextBuffer;
            m_currentDepthFrame = nullptr;
            if (m_currentDepthBuffer != nullptr)
            {
                m_currentDepthBuffer->frameIndex = m_frameIndex;
                m_currentDepthFrame = static_cast<sensekit_depthframe_wrapper_t*>(m_currentDepthBuffer->data);
                if (m_currentDepthFrame != nullptr)
                {
                    m_currentDepthFrame->frame.data = reinterpret_cast<int16_t *>(&(m_currentDepthFrame->frame_data));

                    sensekit_depthframe_metadata_t metadata;

                    metadata.width = m_depthMode.getResolutionX();
                    metadata.height = m_depthMode.getResolutionY();
                    metadata.bytesPerPixel = 2;

                    m_currentDepthFrame->frame.metadata = metadata;
                }
            }
        }

        void OpenNIPlugin::set_new_color_buffer(sensekit_frame_t* nextBuffer)
        {
            m_currentColorBuffer = nextBuffer;
            m_currentColorFrame = nullptr;
            if (m_currentColorBuffer != nullptr)
            {
                m_currentColorBuffer->frameIndex = m_frameIndex;
                m_currentColorFrame = static_cast<sensekit_colorframe_wrapper_t*>(m_currentColorBuffer->data);
                if (m_currentColorFrame != nullptr)
                {
                    m_currentColorFrame->frame.data = reinterpret_cast<uint8_t *>(&(m_currentColorFrame->frame_data));

                    sensekit_colorframe_metadata_t metadata;

                    metadata.width = m_colorMode.getResolutionX();
                    metadata.height = m_colorMode.getResolutionY();
                    metadata.bytesPerPixel = 3;

                    m_currentColorFrame->frame.metadata = metadata;
                }
            }
        }

        void OpenNIPlugin::temp_update()
        {
            read_streams();
        }

        sensekit_status_t OpenNIPlugin::read_streams()
        {
            int dummy;
            int timeout = 0;
            ::openni::VideoStream* pStreams[2] =  { &m_depthStream, &m_colorStream };
            if (::openni::OpenNI::waitForAnyStream(pStreams, 2, &dummy, timeout)
                == ::openni::STATUS_TIME_OUT)
            {
                return SENSEKIT_STATUS_TIMEOUT;
            }

            sensekit_frame_t* nextBuffer = nullptr;

            ::openni::VideoFrameRef ref;
            if (m_depthStream.readFrame(&ref) == ::openni::STATUS_OK)
            {
                const int16_t* datData = static_cast<const int16_t*>(ref.getData());

                int16_t* frameData = m_currentDepthFrame->frame.data;
                int dataSize = MIN(ref.getDataSize(), m_depthBufferLength);

                memcpy(frameData, datData, dataSize);

                ++m_frameIndex;

                ref.release();

                get_pluginService().cycle_bin_buffers(m_depthBinHandle, &nextBuffer);
                set_new_depth_buffer(nextBuffer);
            }

            if (m_colorStream.readFrame(&ref) == ::openni::STATUS_OK)
            {
                const uint8_t* datData = static_cast<const uint8_t*>(ref.getData());

                uint8_t* frameData = m_currentColorFrame->frame.data;

                int dataSize = MIN(ref.getDataSize(), m_colorBufferLength);
                memcpy(frameData, datData, dataSize);

                ++m_frameIndex;

                ref.release();

                get_pluginService().cycle_bin_buffers(m_colorBinHandle, &nextBuffer);
                set_new_color_buffer(nextBuffer);

            }

            return SENSEKIT_STATUS_SUCCESS;
        }
    }
}<commit_msg>prevent possible race condition<commit_after>#include "OpenNIPlugin.h"
#include <iostream>
#include <StreamTypes.h>
#include "../../SenseKit/sensekit_internal.h"

#ifndef MIN
#define MIN(a,b) (((a)<(b))?(a):(b))
#endif

#ifndef MAX
#define MAX(a,b) (((a)>(b))?(a):(b))
#endif

using std::cout;
using std::endl;

EXPORT_PLUGIN(sensekit::openni::OpenNIPlugin);

namespace sensekit
{
    namespace openni
    {
        OpenNIPlugin::OpenNIPlugin(PluginServiceProxy* pluginService)
            : PluginBase(pluginService)
        {
            ::openni::Status rc = ::openni::STATUS_OK;

            const char* deviceURI = ::openni::ANY_DEVICE;

            cout << "Initializing openni" << endl;
            rc = ::openni::OpenNI::initialize();
            cout << "Opening device" << endl;
            rc = m_device.open(deviceURI);

            if (rc != ::openni::STATUS_OK)
            {
                cout << "Failed to open" << endl;
                ::openni::OpenNI::shutdown();
            }

            m_deviceInfo = m_device.getDeviceInfo();

            open_sensor_streams();
        }

        OpenNIPlugin::~OpenNIPlugin()
        {
            get_pluginService().destroy_stream(m_depthHandle);
            get_pluginService().destroy_stream(m_colorHandle);
            get_pluginService().destroy_stream_set(m_streamSetHandle);
            close_sensor_streams();

            cout << "closing device" << endl;
            m_device.close();
            cout << "shutting down openni" << endl;
            ::openni::OpenNI::shutdown();
        }

        sensekit_status_t OpenNIPlugin::open_sensor_streams()
        {
            ::openni::Status rc = ::openni::STATUS_OK;

            cout << "opening depth stream" << endl;
            rc = m_depthStream.create(m_device, ::openni::SENSOR_DEPTH);
            if (rc == ::openni::STATUS_OK)
            {
                cout << "starting depth stream." << endl;
                rc = m_depthStream.start();
                if (rc != ::openni::STATUS_OK)
                {
                    cout << "failed to start depth stream" << endl;
                    m_depthStream.destroy();
                }
            }
            else
            {
                cout << "Failed to open depth stream" << endl;
            }

            if (!m_depthStream.isValid())
            {
                cout << "shutting down openni because of failure" << endl;
                ::openni::OpenNI::shutdown();
            }

            cout << "opening color stream" << endl;
            rc = m_colorStream.create(m_device, ::openni::SENSOR_COLOR);
            if (rc == ::openni::STATUS_OK)
            {
                cout << "starting color stream." << endl;
                rc = m_colorStream.start();
                if (rc != ::openni::STATUS_OK)
                {
                    cout << "failed to start color stream" << endl;
                    m_colorStream.destroy();
                }
            }
            else
            {
                cout << "Failed to open color stream" << endl;
            }

            if (!m_colorStream.isValid())
            {
                cout << "shutting down openni because of failure" << endl;
                ::openni::OpenNI::shutdown();
            }

            sensekit_frame_t* nextBuffer = nullptr;

            stream_callbacks_t pluginCallbacks = create_plugin_callbacks(this);

            get_pluginService().create_stream_set(m_streamSetHandle);

            sensekit_stream_desc_t depthDesc;
            depthDesc.type = SENSEKIT_STREAM_DEPTH;
            depthDesc.subType = DEPTH_DEFAULT_SUBTYPE;

            get_pluginService().create_stream(m_streamSetHandle,
                                              depthDesc,
                                              pluginCallbacks,
                                              &m_depthHandle);

            sensekit_stream_desc_t colorDesc;
            colorDesc.type = SENSEKIT_STREAM_COLOR;
            colorDesc.subType = COLOR_DEFAULT_SUBTYPE;

            get_pluginService().create_stream(m_streamSetHandle,
                                              colorDesc,
                                              pluginCallbacks,
                                              &m_colorHandle);

            m_depthMode = m_depthStream.getVideoMode();
            m_colorMode = m_colorStream.getVideoMode();

            m_depthBufferLength  = m_depthMode.getResolutionX() * m_depthMode.getResolutionY() * 2;
            m_colorBufferLength = m_colorMode.getResolutionX() * m_colorMode.getResolutionY() * 3;

            get_pluginService()
                .create_stream_bin(m_depthHandle,
                                   sizeof(sensekit_depthframe_wrapper_t) + m_depthBufferLength,
                                   &m_depthBinHandle,
                                   &nextBuffer);

            set_new_depth_buffer(nextBuffer);

            get_pluginService()
                .create_stream_bin(m_colorHandle,
                                   sizeof(sensekit_colorframe_wrapper_t) + m_colorBufferLength,
                                   &m_colorBinHandle,
                                   &nextBuffer);

            set_new_color_buffer(nextBuffer);

            return SENSEKIT_STATUS_SUCCESS;
        }

        void OpenNIPlugin::set_parameter(sensekit_streamconnection_t streamConnection,
                                         sensekit_parameter_id id, size_t byteLength,
                                         sensekit_parameter_data_t* data)
        {}

        void OpenNIPlugin::get_parameter_size(sensekit_streamconnection_t streamConnection,
                                              sensekit_parameter_id id,
                                              size_t& byteLength)
        {}

        void OpenNIPlugin::get_parameter_data(sensekit_streamconnection_t streamConnection,
                                              sensekit_parameter_id id,
                                              size_t byteLength,
                                              sensekit_parameter_data_t* data)
        {}

        void OpenNIPlugin::connection_added(sensekit_streamconnection_t connection)
        {
            sensekit_stream_desc_t desc;
            sensekit_stream_get_description(connection, &desc);

            switch (desc.type)
            {
            case SENSEKIT_STREAM_DEPTH:
                get_pluginService().link_connection_to_bin(connection, m_depthBinHandle);
                cout << "openniplugin: new connection added, linked to global depth" << endl;
                break;
            case SENSEKIT_STREAM_COLOR:
                get_pluginService().link_connection_to_bin(connection, m_colorBinHandle);
                cout << "openniplugin: new connection added, linked to global color" << endl;
                break;
            }
        }

        void OpenNIPlugin::connection_removed(sensekit_streamconnection_t connection)
        {
            sensekit_stream_desc_t desc;
            sensekit_stream_get_description(connection, &desc);

            switch (desc.type)
            {
            case SENSEKIT_STREAM_DEPTH:
                get_pluginService().link_connection_to_bin(connection, nullptr);
                cout << "openniplugin: connection removed, unlinking from depth" << endl;
                break;
            case SENSEKIT_STREAM_COLOR:
                get_pluginService().link_connection_to_bin(connection, nullptr);
                cout << "openniplugin: connection removed, unlinking from color" << endl;
                break;
            }
        }

        sensekit_status_t OpenNIPlugin::close_sensor_streams()
        {
            cout << "stopping depth stream" << endl;
            m_depthStream.stop();
            cout << "destroying depth stream" << endl;
            m_depthStream.destroy();

            cout << "stopping color stream" << endl;
            m_colorStream.stop();
            cout << "destroying color stream" << endl;
            m_colorStream.destroy();

            return SENSEKIT_STATUS_SUCCESS;
        }

        void OpenNIPlugin::set_new_depth_buffer(sensekit_frame_t* nextBuffer)
        {
            m_currentDepthBuffer = nextBuffer;
            m_currentDepthFrame = nullptr;
            if (m_currentDepthBuffer != nullptr)
            {
                m_currentDepthBuffer->frameIndex = m_frameIndex;
                m_currentDepthFrame = static_cast<sensekit_depthframe_wrapper_t*>(m_currentDepthBuffer->data);
                if (m_currentDepthFrame != nullptr)
                {
                    m_currentDepthFrame->frame.data = reinterpret_cast<int16_t *>(&(m_currentDepthFrame->frame_data));

                    sensekit_depthframe_metadata_t metadata;

                    metadata.width = m_depthMode.getResolutionX();
                    metadata.height = m_depthMode.getResolutionY();
                    metadata.bytesPerPixel = 2;

                    m_currentDepthFrame->frame.metadata = metadata;
                }
            }
        }

        void OpenNIPlugin::set_new_color_buffer(sensekit_frame_t* nextBuffer)
        {
            m_currentColorBuffer = nextBuffer;
            m_currentColorFrame = nullptr;
            if (m_currentColorBuffer != nullptr)
            {
                m_currentColorBuffer->frameIndex = m_frameIndex;
                m_currentColorFrame = static_cast<sensekit_colorframe_wrapper_t*>(m_currentColorBuffer->data);
                if (m_currentColorFrame != nullptr)
                {
                    m_currentColorFrame->frame.data = reinterpret_cast<uint8_t *>(&(m_currentColorFrame->frame_data));

                    sensekit_colorframe_metadata_t metadata;

                    metadata.width = m_colorMode.getResolutionX();
                    metadata.height = m_colorMode.getResolutionY();
                    metadata.bytesPerPixel = 3;

                    m_currentColorFrame->frame.metadata = metadata;
                }
            }
        }

        void OpenNIPlugin::temp_update()
        {
            if (m_currentColorBuffer != nullptr
                && m_currentDepthBuffer != nullptr)
            {
                read_streams();
            }
            else
            {
                std::cout << "buffers not available" << std::endl;
            }
        }

        sensekit_status_t OpenNIPlugin::read_streams()
        {
            int streamIndex = -1;
            int timeout = ::openni::TIMEOUT_NONE;

            ::openni::VideoStream* pStreams[] =  { &m_depthStream, &m_colorStream };
            if (::openni::OpenNI::waitForAnyStream(pStreams, 2, &streamIndex, timeout)
                == ::openni::STATUS_TIME_OUT)
            {
                return SENSEKIT_STATUS_TIMEOUT;
            }

            if (streamIndex == -1)
                return SENSEKIT_STATUS_TIMEOUT;

            sensekit_frame_t* nextBuffer = nullptr;

            if (streamIndex == 0)
            {
                ::openni::VideoFrameRef ref;
                if (m_depthStream.readFrame(&ref) == ::openni::STATUS_OK)
                {
                    const int16_t* datData = static_cast<const int16_t*>(ref.getData());

                    int16_t* frameData = m_currentDepthFrame->frame.data;
                    int dataSize = MIN(ref.getDataSize(), m_depthBufferLength);

                    memcpy(frameData, datData, dataSize);

                    ++m_frameIndex;

                    get_pluginService().cycle_bin_buffers(m_depthBinHandle, &nextBuffer);
                    set_new_depth_buffer(nextBuffer);
                }
            }
            else if (streamIndex == 1)
            {
                ::openni::VideoFrameRef ref;
                if (m_colorStream.readFrame(&ref) == ::openni::STATUS_OK)
                {
                    const uint8_t* datData = static_cast<const uint8_t*>(ref.getData());

                    uint8_t* frameData = m_currentColorFrame->frame.data;

                    int dataSize = MIN(ref.getDataSize(), m_colorBufferLength);
                    memcpy(frameData, datData, dataSize);

                    ++m_frameIndex;

                    get_pluginService().cycle_bin_buffers(m_colorBinHandle, &nextBuffer);
                    set_new_color_buffer(nextBuffer);
                }
            }

            return SENSEKIT_STATUS_SUCCESS;
        }
    }
}<|endoftext|>


<commit_before>/*************************************************************************
 *
 *  OpenOffice.org - a multi-platform office productivity suite
 *
 *  $RCSfile: ContainerMediator.hxx,v $
 *
 *  $Revision: 1.4 $
 *
 *  last change: $Author: rt $ $Date: 2005-09-08 13:32:43 $
 *
 *  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 DBA_CONTAINERMEDIATOR_HXX
#define DBA_CONTAINERMEDIATOR_HXX

#ifndef _CPPUHELPER_IMPLBASE1_HXX_
#include <cppuhelper/implbase1.hxx>
#endif
#ifndef _COM_SUN_STAR_CONTAINER_XCONTAINERLISTENER_HPP_
#include <com/sun/star/container/XContainerListener.hpp>
#endif
#ifndef _COM_SUN_STAR_CONTAINER_XCONTAINER_HPP_
#include <com/sun/star/container/XContainer.hpp>
#endif
#ifndef _COM_SUN_STAR_CONTAINER_XNAMECONTAINER_HPP_
#include <com/sun/star/container/XNameContainer.hpp>
#endif
#ifndef _COM_SUN_STAR_BEANS_XPROPERTYSET_HPP_
#include <com/sun/star/beans/XPropertySet.hpp>
#endif
#ifndef _COMPHELPER_STLTYPES_HXX_
#include <comphelper/stl_types.hxx>
#endif
#ifndef _COMPHELPER_BROADCASTHELPER_HXX_
#include <comphelper/broadcasthelper.hxx>
#endif
#ifndef DBA_PROPERTYSETFORWARD_HXX
#include "PropertyForward.hxx"
#endif

//........................................................................
namespace dbaccess
{
//........................................................................

    class OContainerMediator :   public ::comphelper::OBaseMutex
                                ,public ::cppu::WeakImplHelper1< ::com::sun::star::container::XContainerListener >
    {
        typedef ::std::pair<OPropertyForward*,::com::sun::star::uno::Reference< ::com::sun::star::uno::XInterface> > TPropertyForward;
        DECLARE_STL_USTRINGACCESS_MAP(TPropertyForward,PropertyForwardList);
        PropertyForwardList                                                             m_aForwardList;
        ::com::sun::star::uno::Reference< ::com::sun::star::container::XNameAccess >    m_xSettings;
        ::com::sun::star::uno::Reference< ::com::sun::star::container::XContainer >     m_xContainer;
        sal_Bool                                                                        m_bTables;
    protected:
        virtual ~OContainerMediator();
    public:
        OContainerMediator(const ::com::sun::star::uno::Reference< ::com::sun::star::container::XContainer >& _xContainer
                        ,const ::com::sun::star::uno::Reference< ::com::sun::star::container::XNameAccess >& _xSettings
                        ,sal_Bool _bTables = sal_True);

        virtual void SAL_CALL elementInserted( const ::com::sun::star::container::ContainerEvent& _rEvent ) throw(::com::sun::star::uno::RuntimeException);
        virtual void SAL_CALL elementRemoved( const ::com::sun::star::container::ContainerEvent& _rEvent ) throw(::com::sun::star::uno::RuntimeException);
        virtual void SAL_CALL elementReplaced( const ::com::sun::star::container::ContainerEvent& _rEvent ) throw(::com::sun::star::uno::RuntimeException);
        virtual void SAL_CALL disposing( const ::com::sun::star::lang::EventObject& Source ) throw(::com::sun::star::uno::RuntimeException);

        void notifyElementCreated(const ::rtl::OUString& _sElementName
                                ,const ::com::sun::star::uno::Reference< ::com::sun::star::beans::XPropertySet>& _xElement);
    };
//........................................................................
}   // namespace dbaccess
//........................................................................

#endif // DBA_CONTAINERMEDIATOR_HXX
<commit_msg>INTEGRATION: CWS dba205b (1.4.166); FILE MERGED 2006/08/06 20:18:36 fs 1.4.166.1: #i67020# when initializing a column object with its settings counterpart, then allow a fallback if the settings do not yet exist, but the object refers to a table column we could use instead<commit_after>/*************************************************************************
 *
 *  OpenOffice.org - a multi-platform office productivity suite
 *
 *  $RCSfile: ContainerMediator.hxx,v $
 *
 *  $Revision: 1.5 $
 *
 *  last change: $Author: ihi $ $Date: 2006-10-18 13:28:07 $
 *
 *  The Contents of this file are made available subject to
 *  the terms of GNU Lesser General Public License Version 2.1.
 *
 *
 *    GNU Lesser General Public License Version 2.1
 *    =============================================
 *    Copyright 2005 by Sun Microsystems, Inc.
 *    901 San Antonio Road, Palo Alto, CA 94303, USA
 *
 *    This library is free software; you can redistribute it and/or
 *    modify it under the terms of the GNU Lesser General Public
 *    License version 2.1, as published by the Free Software Foundation.
 *
 *    This library is distributed in the hope that it will be useful,
 *    but WITHOUT ANY WARRANTY; without even the implied warranty of
 *    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 *    Lesser General Public License for more details.
 *
 *    You should have received a copy of the GNU Lesser General Public
 *    License along with this library; if not, write to the Free Software
 *    Foundation, Inc., 59 Temple Place, Suite 330, Boston,
 *    MA  02111-1307  USA
 *
 ************************************************************************/
#ifndef DBA_CONTAINERMEDIATOR_HXX
#define DBA_CONTAINERMEDIATOR_HXX

#ifndef _COM_SUN_STAR_CONTAINER_XCONTAINERLISTENER_HPP_
#include <com/sun/star/container/XContainerListener.hpp>
#endif
#ifndef _COM_SUN_STAR_CONTAINER_XCONTAINER_HPP_
#include <com/sun/star/container/XContainer.hpp>
#endif
#ifndef _COM_SUN_STAR_CONTAINER_XNAMECONTAINER_HPP_
#include <com/sun/star/container/XNameContainer.hpp>
#endif
#ifndef _COM_SUN_STAR_BEANS_XPROPERTYSET_HPP_
#include <com/sun/star/beans/XPropertySet.hpp>
#endif
#ifndef _COM_SUN_STAR_SDBC_XCONNECTION_HPP_
#include <com/sun/star/sdbc/XConnection.hpp>
#endif

#ifndef _COMPHELPER_BROADCASTHELPER_HXX_
#include <comphelper/broadcasthelper.hxx>
#endif
#ifndef _COMPHELPER_BROADCASTHELPER_HXX_
#include <comphelper/broadcasthelper.hxx>
#endif
#ifndef _CPPUHELPER_IMPLBASE1_HXX_
#include <cppuhelper/implbase1.hxx>
#endif
#ifndef _RTL_REF_HXX_
#include <rtl/ref.hxx>
#endif

#include <map>

//........................................................................
namespace dbaccess
{
//........................................................................

    class OPropertyForward;

    class OContainerMediator :   public ::comphelper::OBaseMutex
                                ,public ::cppu::WeakImplHelper1< ::com::sun::star::container::XContainerListener >
    {
    public:
        enum ContainerType
        {
            eColumns,
            eTables
        };

    private:
        typedef ::rtl::Reference< OPropertyForward >                TPropertyForward;
        typedef ::std::map< ::rtl::OUString, TPropertyForward >     PropertyForwardList;
        PropertyForwardList                                                             m_aForwardList;
        ::com::sun::star::uno::Reference< ::com::sun::star::container::XNameAccess >    m_xSettings;
        ::com::sun::star::uno::Reference< ::com::sun::star::container::XContainer >     m_xContainer;
        ::com::sun::star::uno::WeakReference< ::com::sun::star::sdbc::XConnection >     m_aConnection;
        ContainerType                                                                   m_eType;

    protected:
        virtual ~OContainerMediator();

    public:
        OContainerMediator(
            const ::com::sun::star::uno::Reference< ::com::sun::star::container::XContainer >& _xContainer,
            const ::com::sun::star::uno::Reference< ::com::sun::star::container::XNameAccess >& _xSettings,
            const ::com::sun::star::uno::Reference< ::com::sun::star::sdbc::XConnection >& _rxConnection,
            ContainerType _eType
       );

        virtual void SAL_CALL elementInserted( const ::com::sun::star::container::ContainerEvent& _rEvent ) throw(::com::sun::star::uno::RuntimeException);
        virtual void SAL_CALL elementRemoved( const ::com::sun::star::container::ContainerEvent& _rEvent ) throw(::com::sun::star::uno::RuntimeException);
        virtual void SAL_CALL elementReplaced( const ::com::sun::star::container::ContainerEvent& _rEvent ) throw(::com::sun::star::uno::RuntimeException);
        virtual void SAL_CALL disposing( const ::com::sun::star::lang::EventObject& Source ) throw(::com::sun::star::uno::RuntimeException);

        void notifyElementCreated(const ::rtl::OUString& _sElementName
                                ,const ::com::sun::star::uno::Reference< ::com::sun::star::beans::XPropertySet>& _xElement);

    private:
        /** cleans up the instance, by deregistering as listener at the containers,
            and resetting them to <NULL/>
        */
        void    impl_cleanup_nothrow();

        /** retrieves the settings object to initialize a container element

            Normally, this object will simply retrieve the object with the given name from our settings
            container. Hiowever, for columns, there's a fallback in case this settings object does
            not yet exist: Then, we check if the given destination object refers to a table column, via its
            TableName and RealName property. If so, this table column is used as initialization object.

            @param _rName
                the name of the destination object in its container
            @param _rxDestination
                the destination object to initialize
        */
        ::com::sun::star::uno::Reference< ::com::sun::star::beans::XPropertySet >
                impl_getSettingsForInitialization_nothrow(
                    const ::rtl::OUString& _rName,
                    const ::com::sun::star::uno::Reference< ::com::sun::star::beans::XPropertySet >& _rxDestination
                ) const;
    };
//........................................................................
}   // namespace dbaccess
//........................................................................

#endif // DBA_CONTAINERMEDIATOR_HXX
<|endoftext|>


<commit_before>/**
 *  pretty_print_msg.cpp
 *
 *  @author Nathan Campos
 */

#include <string>
#include <cstdlib>

#include "pretty_print_msg.h"
#include "message.h"
#include "channels.h"
#include "color.h"
#include "irc_reply_codes.h"
using namespace std;

Pretty_Print_Message::Pretty_Print_Message(const char *_buffer) {
    buffer = _buffer;
    echo = true;
}

string Pretty_Print_Message::color_string(string nickname, bool include_msg) {
    // Generate a color for the nick based on its letters.
    string chars = " abcdefghijklmnopqrstuvwxyz1234567890_-";
    int color = 0;
    char color_chr[2];

    for (size_t i = 0; i < nickname.size(); i++) {
        // Get the characted position in our dictionary.
        size_t pos = chars.find(nickname.at(i));

        // If we couldn't find it just default it to 10.
        if (pos == string::npos) {
            pos = 10;
        }

        color += pos;
    }

    // Build the string.
    color = (color % 7) + 1;
    sprintf(color_chr, "%d", color);

    if (!include_msg) {
        return "\033[1m\033[3" + string(color_chr) + "m";
    } else {
        return "\033[1m\033[3" + string(color_chr) + "m" + nickname + RESET;
    }
}

string Pretty_Print_Message::generate(Message &message, Channels &channels) {
    // Parse and return a better and more human-readable message.
    string str_buffer(buffer);
    vector<string> arguments = message.get_command_args();

    if (message.get_command() == "PRIVMSG") {
        if (arguments.at(0).at(0) == '#') {
            // Channel message.
            if (arguments.at(0) != "#" + channels.list.at(channels.current)) {
                echo = false;
            }

            // A normal message.
            string nickname = message.get_nickname();
            str_buffer = color_string(nickname, false) + "<" + nickname + "> " + string(RESET) + arguments.at(1) + "\r\n";

            if (arguments.at(1).size() > 6) {
                if (arguments.at(1).substr(0, 7) == "\001ACTION") {
                    // This is a ACTION message.
                    str_buffer = string(BOLDMAGENTA) + "\u2022 " + message.get_nickname() + " " + arguments.at(1).substr(8) + string(RESET) + "\r\n";
                }
            }
        }
    } else if (message.get_command() == "JOIN") {
        // Someone joined the channel.
        // TODO: Check if this isn't adding more than one time when another user joins the channel.
        // If it is move this to the repl loop and create an eval return for it.
        if (!arguments.empty()) {
            channels.add(arguments.at(0).substr(1, arguments.at(0).find(":") - 1));
        }

        str_buffer = string(BOLDGREEN) + "> " + string(RESET) + message.get_nickname() + " joined " + arguments.at(0) + "\r\n";
    } else if (message.get_command() == "PART") {
        // Someone left the channel.
        str_buffer = string(BOLDRED) + "< " + string(RESET) + message.get_nickname() + " left\r\n";
    } else if (message.get_command() == "KICK") {
        // Someone got kicked.
        str_buffer = string(BOLDRED) + "<< " + message.get_nickname() + " got kicked from " + arguments.at(0) + " (" + arguments.at(2) + ")" + string(RESET) + "\r\n";
    } else if (message.get_command() == "MODE") {
        // Changing modes.
        str_buffer = string(BOLDBLUE) + "* " + string(RESET) + message.get_nickname() + " set mode ";

        for (unsigned int i = 0; i < arguments.size(); i++) {
            str_buffer += arguments.at(i) + " ";
        }

        str_buffer += "\r\n";
    } else if (message.get_command() == "QUIT") {
        // Quitting.
        str_buffer = string(BOLDRED) + "<< " + string(RESET) + message.get_nickname() + " quit (" + arguments.at(0) + ")\r\n";
    } else if (message.get_command() == "ERROR") {
        // Oh noes! Error!
        str_buffer = string(BOLDRED) + "Error: " + arguments.at(0) + string(RESET) + "\r\n";
    } else if (message.get_command() == "NICK") {
        // Someone is chaning the nick.
        str_buffer = string(BOLDBLUE) + "* " + color_string(message.get_nickname(), true) + " is now known as " + color_string(arguments.at(0), true) + "\r\n";
    } else {
        // Might be a server message, so let's check for the reply code.
        int reply_code = message.get_reply_code();

        switch (reply_code) {
            case RPL_TOPIC:
                // Got a topic.
                str_buffer = string(BOLDWHITE) + "Topic: " + "\"" + arguments.at(2) + "\"" + string(RESET) + "\r\n";
                break;
            case RPL_TOPICWHOTIME:
                // Got who set the topic.
                str_buffer = "Topic set by " +  arguments.at(2).substr(0,  arguments.at(2).find('!')) + "\r\n";
                break;
            case RPL_NAMREPLY:
                // Got a list of the people online.
                //[01:48:50] :irc.arcti.ca 353 leafirc = #leafirc :leafirc nathanpc @vivid_
                //[01:48:50] :irc.arcti.ca 366 leafirc #leafirc :End of /NAMES list.
                break;
            case RPL_ENDOFNAMES:
                // (Ignored) Got the end of the online names list
                str_buffer = "";
                break;
            default:
                // Got some other kind of message that we haven't covered.
                str_buffer = "";

                for (size_t i = 1; i < arguments.size(); i++) {
                    str_buffer += arguments.at(i) + " ";
                }

                str_buffer += "\r\n";
                break;
        }
    }

    if (arguments.at(0).at(0) == '#') {
        channels.cache(arguments.at(0).substr(1), str_buffer);
    }

    return str_buffer;
}

bool Pretty_Print_Message::echo_message() {
    return echo;
}<commit_msg>Include <cstdio> was added to fix compiler error<commit_after>/**
 *  pretty_print_msg.cpp
 *
 *  @author Nathan Campos
 */

#include <string>
#include <cstdio>
#include <cstdlib>

#include "pretty_print_msg.h"
#include "message.h"
#include "channels.h"
#include "color.h"
#include "irc_reply_codes.h"
using namespace std;

Pretty_Print_Message::Pretty_Print_Message(const char *_buffer) {
    buffer = _buffer;
    echo = true;
}

string Pretty_Print_Message::color_string(string nickname, bool include_msg) {
    // Generate a color for the nick based on its letters.
    string chars = " abcdefghijklmnopqrstuvwxyz1234567890_-";
    int color = 0;
    char color_chr[2];

    for (size_t i = 0; i < nickname.size(); i++) {
        // Get the characted position in our dictionary.
        size_t pos = chars.find(nickname.at(i));

        // If we couldn't find it just default it to 10.
        if (pos == string::npos) {
            pos = 10;
        }

        color += pos;
    }

    // Build the string.
    color = (color % 7) + 1;
    sprintf(color_chr, "%d", color);

    if (!include_msg) {
        return "\033[1m\033[3" + string(color_chr) + "m";
    } else {
        return "\033[1m\033[3" + string(color_chr) + "m" + nickname + RESET;
    }
}

string Pretty_Print_Message::generate(Message &message, Channels &channels) {
    // Parse and return a better and more human-readable message.
    string str_buffer(buffer);
    vector<string> arguments = message.get_command_args();

    if (message.get_command() == "PRIVMSG") {
        if (arguments.at(0).at(0) == '#') {
            // Channel message.
            if (arguments.at(0) != "#" + channels.list.at(channels.current)) {
                echo = false;
            }

            // A normal message.
            string nickname = message.get_nickname();
            str_buffer = color_string(nickname, false) + "<" + nickname + "> " + string(RESET) + arguments.at(1) + "\r\n";

            if (arguments.at(1).size() > 6) {
                if (arguments.at(1).substr(0, 7) == "\001ACTION") {
                    // This is a ACTION message.
                    str_buffer = string(BOLDMAGENTA) + "\u2022 " + message.get_nickname() + " " + arguments.at(1).substr(8) + string(RESET) + "\r\n";
                }
            }
        }
    } else if (message.get_command() == "JOIN") {
        // Someone joined the channel.
        // TODO: Check if this isn't adding more than one time when another user joins the channel.
        // If it is move this to the repl loop and create an eval return for it.
        if (!arguments.empty()) {
            channels.add(arguments.at(0).substr(1, arguments.at(0).find(":") - 1));
        }

        str_buffer = string(BOLDGREEN) + "> " + string(RESET) + message.get_nickname() + " joined " + arguments.at(0) + "\r\n";
    } else if (message.get_command() == "PART") {
        // Someone left the channel.
        str_buffer = string(BOLDRED) + "< " + string(RESET) + message.get_nickname() + " left\r\n";
    } else if (message.get_command() == "KICK") {
        // Someone got kicked.
        str_buffer = string(BOLDRED) + "<< " + message.get_nickname() + " got kicked from " + arguments.at(0) + " (" + arguments.at(2) + ")" + string(RESET) + "\r\n";
    } else if (message.get_command() == "MODE") {
        // Changing modes.
        str_buffer = string(BOLDBLUE) + "* " + string(RESET) + message.get_nickname() + " set mode ";

        for (unsigned int i = 0; i < arguments.size(); i++) {
            str_buffer += arguments.at(i) + " ";
        }

        str_buffer += "\r\n";
    } else if (message.get_command() == "QUIT") {
        // Quitting.
        str_buffer = string(BOLDRED) + "<< " + string(RESET) + message.get_nickname() + " quit (" + arguments.at(0) + ")\r\n";
    } else if (message.get_command() == "ERROR") {
        // Oh noes! Error!
        str_buffer = string(BOLDRED) + "Error: " + arguments.at(0) + string(RESET) + "\r\n";
    } else if (message.get_command() == "NICK") {
        // Someone is chaning the nick.
        str_buffer = string(BOLDBLUE) + "* " + color_string(message.get_nickname(), true) + " is now known as " + color_string(arguments.at(0), true) + "\r\n";
    } else {
        // Might be a server message, so let's check for the reply code.
        int reply_code = message.get_reply_code();

        switch (reply_code) {
            case RPL_TOPIC:
                // Got a topic.
                str_buffer = string(BOLDWHITE) + "Topic: " + "\"" + arguments.at(2) + "\"" + string(RESET) + "\r\n";
                break;
            case RPL_TOPICWHOTIME:
                // Got who set the topic.
                str_buffer = "Topic set by " +  arguments.at(2).substr(0,  arguments.at(2).find('!')) + "\r\n";
                break;
            case RPL_NAMREPLY:
                // Got a list of the people online.
                //[01:48:50] :irc.arcti.ca 353 leafirc = #leafirc :leafirc nathanpc @vivid_
                //[01:48:50] :irc.arcti.ca 366 leafirc #leafirc :End of /NAMES list.
                break;
            case RPL_ENDOFNAMES:
                // (Ignored) Got the end of the online names list
                str_buffer = "";
                break;
            default:
                // Got some other kind of message that we haven't covered.
                str_buffer = "";

                for (size_t i = 1; i < arguments.size(); i++) {
                    str_buffer += arguments.at(i) + " ";
                }

                str_buffer += "\r\n";
                break;
        }
    }

    if (arguments.at(0).at(0) == '#') {
        channels.cache(arguments.at(0).substr(1), str_buffer);
    }

    return str_buffer;
}

bool Pretty_Print_Message::echo_message() {
    return echo;
}
<|endoftext|>


<commit_before>#include "progress.hpp"
#include "errors.hpp"
#include "utils2.hpp"

progress_bar_t::progress_bar_t(std::string activity, int redraw_interval_ms = 100)
    : repeating_timer_t(redraw_interval_ms, boost::bind(&progress_bar_t::refresh, this)),
      activity(activity), redraw_interval_ms(redraw_interval_ms), start_time(get_ticks()),
      total_refreshes(0)
{ }

void progress_bar_t::refresh() {
    total_refreshes++;
    reset_bar();
    draw();
    reset_bar();
}

void progress_bar_t::reset_bar() {
    printf("\r");
    fflush(stdout);
}

/* progress should be in [0.0,1.0] */
void progress_bar_t::draw_bar(float progress,  int eta) {
    int percent_done = int(progress * 100);
    printf("%s: ", activity.c_str());
    printf("[");
    for (int i = 1; i < 49; i++) {
        if (i % 5 == 0) printf("%d", 2 * i);
        else if (i == percent_done / 2) printf(">");
        else if (i < percent_done / 2) printf("=");
        else printf(" ");
    }
    printf("] ");

    if (eta == -1 && progress > 0) {
        //Do automatic linear interpolation for eta
        eta = ((1.0f / progress) - 1) * ticks_to_secs(get_ticks() - start_time);
    }

    if (eta == -1) printf("ETA: -");
    else printf("ETA: %01d:%02d:%02d", (eta / 3600), (eta / 60) % 60, eta % 60);

    printf("                 "); //make sure we don't leave an characters behind
    fflush(stdout);
}

counter_progress_bar_t::counter_progress_bar_t(std::string activity, int expected_count, int redraw_interval_ms)
    : progress_bar_t(activity, redraw_interval_ms), count(0), expected_count(expected_count)
{ }

void counter_progress_bar_t::draw() {
    progress_bar_t::draw_bar(float(count) / float(expected_count), -1);
}

void counter_progress_bar_t::operator++(int) {
    count++;
}

file_progress_bar_t::file_progress_bar_t(std::string activity, FILE *file, int redraw_interval_ms)
    : progress_bar_t(activity, redraw_interval_ms), file(file)
{
    struct stat file_stats;
    fstat(fileno(file), &file_stats);
    file_size = file_stats.st_size;
}

void file_progress_bar_t::draw() {
    progress_bar_t::draw_bar(float(ftell(file)) / float(file_size), -1);
}
<commit_msg>Include <sys/stat.h> in progress/progress.cc.<commit_after>#include "progress.hpp"
#include "errors.hpp"
#include "utils2.hpp"
#include <sys/stat.h>

progress_bar_t::progress_bar_t(std::string activity, int redraw_interval_ms = 100)
    : repeating_timer_t(redraw_interval_ms, boost::bind(&progress_bar_t::refresh, this)),
      activity(activity), redraw_interval_ms(redraw_interval_ms), start_time(get_ticks()),
      total_refreshes(0)
{ }

void progress_bar_t::refresh() {
    total_refreshes++;
    reset_bar();
    draw();
    reset_bar();
}

void progress_bar_t::reset_bar() {
    printf("\r");
    fflush(stdout);
}

/* progress should be in [0.0,1.0] */
void progress_bar_t::draw_bar(float progress,  int eta) {
    int percent_done = int(progress * 100);
    printf("%s: ", activity.c_str());
    printf("[");
    for (int i = 1; i < 49; i++) {
        if (i % 5 == 0) printf("%d", 2 * i);
        else if (i == percent_done / 2) printf(">");
        else if (i < percent_done / 2) printf("=");
        else printf(" ");
    }
    printf("] ");

    if (eta == -1 && progress > 0) {
        //Do automatic linear interpolation for eta
        eta = ((1.0f / progress) - 1) * ticks_to_secs(get_ticks() - start_time);
    }

    if (eta == -1) printf("ETA: -");
    else printf("ETA: %01d:%02d:%02d", (eta / 3600), (eta / 60) % 60, eta % 60);

    printf("                 "); //make sure we don't leave an characters behind
    fflush(stdout);
}

counter_progress_bar_t::counter_progress_bar_t(std::string activity, int expected_count, int redraw_interval_ms)
    : progress_bar_t(activity, redraw_interval_ms), count(0), expected_count(expected_count)
{ }

void counter_progress_bar_t::draw() {
    progress_bar_t::draw_bar(float(count) / float(expected_count), -1);
}

void counter_progress_bar_t::operator++(int) {
    count++;
}

file_progress_bar_t::file_progress_bar_t(std::string activity, FILE *file, int redraw_interval_ms)
    : progress_bar_t(activity, redraw_interval_ms), file(file)
{
    struct stat file_stats;
    fstat(fileno(file), &file_stats);
    file_size = file_stats.st_size;
}

void file_progress_bar_t::draw() {
    progress_bar_t::draw_bar(float(ftell(file)) / float(file_size), -1);
}
<|endoftext|>


<commit_before>/*
 * Copyright 2015 Aldebaran
 *
 * 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.
 *
*/

/**
* LOCAL includes
*/
#include "sonar.hpp"

namespace alros
{
namespace publisher
{

SonarPublisher::SonarPublisher( const std::vector<std::string>& topics )
  : is_initialized_(false),
  topics_(topics)
{
}

void SonarPublisher::publish( const std::vector<sensor_msgs::Range>& sonar_msgs )
{
  if ( pubs_.size() != sonar_msgs.size() )
  {
    std::cerr << "Incorrect number of sonar range messages in sonar publisher. " << sonar_msgs.size() << "/" << pubs_.size() << std::endl;
    return;
  }

  for( size_t i=0; i<sonar_msgs.size(); ++i)
  {
    pubs_[i].publish( sonar_msgs[i] );
  }
}

void SonarPublisher::reset( ros::NodeHandle& nh )
{
  for( size_t i=0; i<topics_.size(); ++i)
  {
    pubs_.push_back( nh.advertise<sensor_msgs::Range>(topics_[i], 1) );
  }

  is_initialized_ = true;
}

} // publisher
} //alros
<commit_msg>Reset the list of publishers when resetting sonar publisher node<commit_after>/*
 * Copyright 2015 Aldebaran
 *
 * 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.
 *
*/

/**
* LOCAL includes
*/
#include "sonar.hpp"

namespace alros
{
namespace publisher
{

SonarPublisher::SonarPublisher( const std::vector<std::string>& topics )
  : is_initialized_(false),
  topics_(topics)
{
}

void SonarPublisher::publish( const std::vector<sensor_msgs::Range>& sonar_msgs )
{
  if ( pubs_.size() != sonar_msgs.size() )
  {
    std::cerr << "Incorrect number of sonar range messages in sonar publisher. " << sonar_msgs.size() << "/" << pubs_.size() << std::endl;
    return;
  }

  for( size_t i=0; i<sonar_msgs.size(); ++i)
  {
    pubs_[i].publish( sonar_msgs[i] );
  }
}

void SonarPublisher::reset( ros::NodeHandle& nh )
{
  pubs_ = std::vector<ros::Publisher>();
  for( size_t i=0; i<topics_.size(); ++i)
  {
    pubs_.push_back( nh.advertise<sensor_msgs::Range>(topics_[i], 1) );
  }

  is_initialized_ = true;
}

} // publisher
} //alros
<|endoftext|>


<commit_before>// @(#)root/bonjour:$Id$
// Author: Fons Rademakers   29/05/2009

/*************************************************************************
 * Copyright (C) 1995-2009, Rene Brun and Fons Rademakers.               *
 * All rights reserved.                                                  *
 *                                                                       *
 * For the licensing terms see $ROOTSYS/LICENSE.                         *
 * For the list of contributors see $ROOTSYS/README/CREDITS.             *
 *************************************************************************/

//////////////////////////////////////////////////////////////////////////
//                                                                      //
// TBonjourResolver                                                     //
//                                                                      //
// This class consists of one main member function,                     //
// ResolveBonjourRecord(), that resolves the service to an actual       //
// IP address and port number. The rest of the class wraps the various  //
// bits of Bonjour service resolver. The static callback function       //
// is marked with the DNSSD_API macro to make sure that the callback    //
// has the correct calling convention on Windows.                       //
//                                                                      //
//////////////////////////////////////////////////////////////////////////

#include "TBonjourResolver.h"
#include "TBonjourRecord.h"
#include "TSysEvtHandler.h"
#include "TSystem.h"
#include "TError.h"

#include <arpa/inet.h>

ClassImp(TBonjourResolver)

//______________________________________________________________________________
TBonjourResolver::TBonjourResolver() : fDNSRef(0), fBonjourSocketHandler(0)
{
   // Default ctor.
}

//______________________________________________________________________________
TBonjourResolver::~TBonjourResolver()
{
   // Cleanup.

   delete fBonjourSocketHandler;

   if (fDNSRef) {
      DNSServiceRefDeallocate(fDNSRef);
      fDNSRef = 0;
   }
}

//______________________________________________________________________________
Int_t TBonjourResolver::ResolveBonjourRecord(const TBonjourRecord &record)
{
   // Resolve Bonjour service to IP address and port.
   // Returns -1 in case of error, 0 otherwise.

   if (fDNSRef) {
      Warning("ResolveBonjourRecord", "resolve already in process");
      return 0;
   }

   DNSServiceErrorType err = DNSServiceResolve(&fDNSRef, 0, 0,
                                               record.GetServiceName(),
                                               record.GetRegisteredType(),
                                               record.GetReplyDomain(),
                                               BonjourResolveReply, this);
   if (err != kDNSServiceErr_NoError) {
      Error("ResolveBonjourRecord", "error in DNSServiceResolve (%d)", err);
      return -1;
   }

   Int_t sockfd = DNSServiceRefSockFD(fDNSRef);
   if (sockfd == -1) {
      Error("ResolveBonjourRecord", "invalide sockfd");
      return -1;
   }

   fBonjourSocketHandler = new TFileHandler(sockfd, TFileHandler::kRead);
   fBonjourSocketHandler->Connect("Notified()", "TBonjourResolver", this, "BonjourSocketReadyRead()");
   fBonjourSocketHandler->Add();

   return 0;
}

//______________________________________________________________________________
void TBonjourResolver::RecordResolved(const TInetAddress *hostInfo, Int_t port)
{
   // Emit RecordResolved signal.

   Long_t args[2];
   args[0] = (Long_t) hostInfo;
   args[1] = port;

   Emit("RecordResolved(TInetAddress*,Int_t)", args);
}

//______________________________________________________________________________
void TBonjourResolver::BonjourSocketReadyRead()
{
   // The Bonjour socket is ready for reading. Tell Bonjour to process the
   // information on the socket, this will invoke the BonjourResolveReply
   // callback. This is a private slot, used in ResolveBonjourRecord.

   DNSServiceErrorType err = DNSServiceProcessResult(fDNSRef);
   if (err != kDNSServiceErr_NoError)
      Error("BonjourSocketReadyRead", "error in DNSServiceProcessResult");
}

//______________________________________________________________________________
void TBonjourResolver::BonjourResolveReply(DNSServiceRef,
                                           DNSServiceFlags, UInt_t,
                                           DNSServiceErrorType errorCode, const char *,
                                           const char *hostTarget, UShort_t port, UShort_t,
                                           const unsigned char *, void *context)
{
   // Static Bonjour resolver callback function.

   TBonjourResolver *resolver = static_cast<TBonjourResolver *>(context);
   if (errorCode != kDNSServiceErr_NoError) {
      ::Error("TBonjourResolver::BonjourResolveReply", "error in BonjourResolveReply");
      //resolver->Error(errorCode);
   } else {
      resolver->fPort = ntohs(port);
      resolver->fHostAddress = gSystem->GetHostByName(hostTarget);
      resolver->RecordResolved(&resolver->fHostAddress, resolver->fPort);
   }
}
<commit_msg>fix an incomatibility on MacOS X 10.4.<commit_after>// @(#)root/bonjour:$Id$
// Author: Fons Rademakers   29/05/2009

/*************************************************************************
 * Copyright (C) 1995-2009, Rene Brun and Fons Rademakers.               *
 * All rights reserved.                                                  *
 *                                                                       *
 * For the licensing terms see $ROOTSYS/LICENSE.                         *
 * For the list of contributors see $ROOTSYS/README/CREDITS.             *
 *************************************************************************/

//////////////////////////////////////////////////////////////////////////
//                                                                      //
// TBonjourResolver                                                     //
//                                                                      //
// This class consists of one main member function,                     //
// ResolveBonjourRecord(), that resolves the service to an actual       //
// IP address and port number. The rest of the class wraps the various  //
// bits of Bonjour service resolver. The static callback function       //
// is marked with the DNSSD_API macro to make sure that the callback    //
// has the correct calling convention on Windows.                       //
//                                                                      //
//////////////////////////////////////////////////////////////////////////

#include "TBonjourResolver.h"
#include "TBonjourRecord.h"
#include "TSysEvtHandler.h"
#include "TSystem.h"
#include "TError.h"

#include <arpa/inet.h>

ClassImp(TBonjourResolver)

//______________________________________________________________________________
TBonjourResolver::TBonjourResolver() : fDNSRef(0), fBonjourSocketHandler(0)
{
   // Default ctor.
}

//______________________________________________________________________________
TBonjourResolver::~TBonjourResolver()
{
   // Cleanup.

   delete fBonjourSocketHandler;

   if (fDNSRef) {
      DNSServiceRefDeallocate(fDNSRef);
      fDNSRef = 0;
   }
}

//______________________________________________________________________________
Int_t TBonjourResolver::ResolveBonjourRecord(const TBonjourRecord &record)
{
   // Resolve Bonjour service to IP address and port.
   // Returns -1 in case of error, 0 otherwise.

   if (fDNSRef) {
      Warning("ResolveBonjourRecord", "resolve already in process");
      return 0;
   }

   DNSServiceErrorType err = DNSServiceResolve(&fDNSRef, 0, 0,
                                               record.GetServiceName(),
                                               record.GetRegisteredType(),
                                               record.GetReplyDomain(),
                                               (DNSServiceResolveReply)BonjourResolveReply,
                                               this);
   if (err != kDNSServiceErr_NoError) {
      Error("ResolveBonjourRecord", "error in DNSServiceResolve (%d)", err);
      return -1;
   }

   Int_t sockfd = DNSServiceRefSockFD(fDNSRef);
   if (sockfd == -1) {
      Error("ResolveBonjourRecord", "invalide sockfd");
      return -1;
   }

   fBonjourSocketHandler = new TFileHandler(sockfd, TFileHandler::kRead);
   fBonjourSocketHandler->Connect("Notified()", "TBonjourResolver", this, "BonjourSocketReadyRead()");
   fBonjourSocketHandler->Add();

   return 0;
}

//______________________________________________________________________________
void TBonjourResolver::RecordResolved(const TInetAddress *hostInfo, Int_t port)
{
   // Emit RecordResolved signal.

   Long_t args[2];
   args[0] = (Long_t) hostInfo;
   args[1] = port;

   Emit("RecordResolved(TInetAddress*,Int_t)", args);
}

//______________________________________________________________________________
void TBonjourResolver::BonjourSocketReadyRead()
{
   // The Bonjour socket is ready for reading. Tell Bonjour to process the
   // information on the socket, this will invoke the BonjourResolveReply
   // callback. This is a private slot, used in ResolveBonjourRecord.

   DNSServiceErrorType err = DNSServiceProcessResult(fDNSRef);
   if (err != kDNSServiceErr_NoError)
      Error("BonjourSocketReadyRead", "error in DNSServiceProcessResult");
}

//______________________________________________________________________________
void TBonjourResolver::BonjourResolveReply(DNSServiceRef,
                                           DNSServiceFlags, UInt_t,
                                           DNSServiceErrorType errorCode, const char *,
                                           const char *hostTarget, UShort_t port, UShort_t,
                                           const unsigned char *, void *context)
{
   // Static Bonjour resolver callback function.

   TBonjourResolver *resolver = static_cast<TBonjourResolver *>(context);
   if (errorCode != kDNSServiceErr_NoError) {
      ::Error("TBonjourResolver::BonjourResolveReply", "error in BonjourResolveReply");
      //resolver->Error(errorCode);
   } else {
      resolver->fPort = ntohs(port);
      resolver->fHostAddress = gSystem->GetHostByName(hostTarget);
      resolver->RecordResolved(&resolver->fHostAddress, resolver->fPort);
   }
}
<|endoftext|>


<commit_before>// @(#)root/net:$Id$
// Author: Philippe Canal October 2011.

/*************************************************************************
 * Copyright (C) 1995-2011, Rene Brun, Fons Rademakers and al.           *
 * All rights reserved.                                                  *
 *                                                                       *
 * For the licensing terms see $ROOTSYS/LICENSE.                         *
 * For the list of contributors see $ROOTSYS/README/CREDITS.             *
 *************************************************************************/

//////////////////////////////////////////////////////////////////////////
//                                                                      //
// TParallelMergingFile                                                 //
//                                                                      //
// Specialization of TMemFile to connect to a parallel file merger.     //
// Upon a call to UploadAndReset, the content already written to the    //
// file is upload to the server and the object implementing the function//
// ResetAfterMerge (like TTree) are reset.                              //
// The parallel file merger will then collate the information coming    //
// from this client and any other client in to the file described by    //
// the filename of this object.                                         //
//                                                                      //
//////////////////////////////////////////////////////////////////////////

#include "TParallelMergingFile.h"
#include "TSocket.h"
#include "TArrayC.h"

////////////////////////////////////////////////////////////////////////////////
/// Constructor.
/// We do no yet open any connection to the server.  This will be done at the
/// time the first upload will be requested.

TParallelMergingFile::TParallelMergingFile(const char *filename, Option_t *option /* = "" */,
                                           const char *ftitle /* = "" */, Int_t compress /* = 1 */) :
   TMemFile(filename,option,ftitle,compress),fSocket(0),fServerIdx(-1),fServerVersion(0),fClassSent(0),fMessage(kMESS_OBJECT)
{
   TString serverurl = strstr(fUrl.GetOptions(),"pmerge=");
   if (serverurl.Length()) {
      serverurl.ReplaceAll("pmerge=","pmerge://");
      fServerLocation = TUrl(serverurl);
   }
}

////////////////////////////////////////////////////////////////////////////////
/// Destructor.

TParallelMergingFile::~TParallelMergingFile()
{
   // We need to call Close, right here so that it is executed _before_
   // the data member of TParallelMergingFile are destructed.
   Close();
   delete fClassSent;
}

////////////////////////////////////////////////////////////////////////////////

void TParallelMergingFile::Close(Option_t *option)
{
   TMemFile::Close(option);
   if (fSocket) {
      if (0==fSocket->Send("Finished")) {          // tell server we are finished
         Warning("Close","Failed to send the finishing message to the server %s:%d",fServerLocation.GetHost(),fServerLocation.GetPort());
      }
      fSocket->Close();
      delete fSocket;
   }
   fSocket = 0;
}

////////////////////////////////////////////////////////////////////////////////
/// Upload the current file data to the merging server.
/// Reset the file and return true in case of success.

Bool_t TParallelMergingFile::UploadAndReset()
{
   // Open connection to server
   if (fSocket == 0) {
      const char *host = fServerLocation.GetHost();
      Int_t port = fServerLocation.GetPort();
      if (host == 0 || host[0] == '\0') {
         host = "localhost";
      }
      if (port <= 0) {
         port = 1095;
      }
      fSocket = new TSocket(host,port);
      if (!fSocket->IsValid()) {
         Error("UploadAndReset","Could not contact the server %s:%d\n",host,port);
         delete fSocket;
         fSocket = 0;
         return kFALSE;
      }
      // Wait till we get the start message
      // server tells us who we are
      Int_t kind;
      Int_t n = fSocket->Recv(fServerIdx, kind);

      if (n < 0 && kind != 0 /* kStartConnection */)
      {
         Error("UploadAndReset","Unexpected server message: kind=%d idx=%d\n",kind,fServerIdx);
         delete fSocket;
         fSocket = 0;
         return kTRUE;
      }
      n = fSocket->Recv(fServerVersion, kind);
      if (n < 0 && kind != 1 /* kProtocol */)
      {
         Fatal("UploadAndReset","Unexpected server message: kind=%d status=%d\n",kind,fServerVersion);
      } else {
         Info("UploadAndReset","Connected to fastMergeServer version %d with index %d\n",fServerVersion,fServerIdx);
      }
      TMessage::EnableSchemaEvolutionForAll(kTRUE);
   }

   fMessage.Reset(kMESS_ANY); // re-use TMessage object
   fMessage.WriteInt(fServerIdx);
   fMessage.WriteTString(GetName());
   fMessage.WriteLong64(GetEND());
   CopyTo(fMessage);

   if (int error = fSocket->Send(fMessage) <= 0) {
      Error("UploadAndReset","Upload to the merging server failed with %d\n",error);
      delete fSocket;
      fSocket = 0;
      return kFALSE;
   }

   // Record the StreamerInfo we sent over.
   Int_t isize = fClassIndex->GetSize();
   if (!fClassSent) {
      fClassSent = new TArrayC(isize);
   } else {
      if (isize > fClassSent->GetSize()) {
         fClassSent->Set(isize);
      }
   }
   for(Int_t c = 0; c < isize; ++c) {
      if (fClassIndex->fArray[c]) {
         fClassSent->fArray[c] = 1;
      }
   }
   ResetAfterMerge(0);

   return kTRUE;
}

////////////////////////////////////////////////////////////////////////////////
/// Write memory objects to this file and upload them to the parallel merge server.
/// Then reset all the resetable object (those with a ResetAfterMerge routine,
/// like TTree).
///
/// Loop on all objects in memory (including subdirectories).
/// A new key is created in the KEYS linked list for each object.
/// The list of keys is then saved on the file (via WriteKeys)
/// as a single data record.
/// For values of opt see TObject::Write().
/// The directory header info is rewritten on the directory header record.
/// The linked list of FREE segments is written.
/// The file header is written (bytes 1->fBEGIN).

Int_t TParallelMergingFile::Write(const char *, Int_t opt, Int_t bufsiz)
{
   Int_t nbytes = TMemFile::Write(0,opt,bufsiz);
   if (nbytes) {
      UploadAndReset();
   }
   return nbytes;
}

////////////////////////////////////////////////////////////////////////////////
/// One can not save a const TDirectory object.

Int_t TParallelMergingFile::Write(const char *n, Int_t opt, Int_t bufsize) const
{
   Error("Write const","A const TFile object should not be saved. We try to proceed anyway.");
   return const_cast<TParallelMergingFile*>(this)->Write(n, opt, bufsize);
}

////////////////////////////////////////////////////////////////////////////////
/// Write the list of TStreamerInfo as a single object in this file
/// The class Streamer description for all classes written to this file
/// is saved. See class TStreamerInfo.

void TParallelMergingFile::WriteStreamerInfo()
{
   if (!fWritable) return;
   if (!fClassIndex) return;
   //no need to update the index if no new classes added to the file
   if (fClassIndex->fArray[0] == 0) return;

   // clear fClassIndex for anything we already sent.
   if (fClassSent) {
      Int_t isize = fClassIndex->GetSize();
      Int_t ssize = fClassSent->GetSize();
      for(Int_t c = 0; c < isize && c < ssize; ++c) {
         if (fClassSent->fArray[c]) {
            fClassIndex->fArray[c] = 0;
         }
      }
   }

   TMemFile::WriteStreamerInfo();
}
<commit_msg>Fix condition which was incorrect due to operator precedence<commit_after>// @(#)root/net:$Id$
// Author: Philippe Canal October 2011.

/*************************************************************************
 * Copyright (C) 1995-2011, Rene Brun, Fons Rademakers and al.           *
 * All rights reserved.                                                  *
 *                                                                       *
 * For the licensing terms see $ROOTSYS/LICENSE.                         *
 * For the list of contributors see $ROOTSYS/README/CREDITS.             *
 *************************************************************************/

//////////////////////////////////////////////////////////////////////////
//                                                                      //
// TParallelMergingFile                                                 //
//                                                                      //
// Specialization of TMemFile to connect to a parallel file merger.     //
// Upon a call to UploadAndReset, the content already written to the    //
// file is upload to the server and the object implementing the function//
// ResetAfterMerge (like TTree) are reset.                              //
// The parallel file merger will then collate the information coming    //
// from this client and any other client in to the file described by    //
// the filename of this object.                                         //
//                                                                      //
//////////////////////////////////////////////////////////////////////////

#include "TParallelMergingFile.h"
#include "TSocket.h"
#include "TArrayC.h"

////////////////////////////////////////////////////////////////////////////////
/// Constructor.
/// We do no yet open any connection to the server.  This will be done at the
/// time the first upload will be requested.

TParallelMergingFile::TParallelMergingFile(const char *filename, Option_t *option /* = "" */,
                                           const char *ftitle /* = "" */, Int_t compress /* = 1 */) :
   TMemFile(filename,option,ftitle,compress),fSocket(0),fServerIdx(-1),fServerVersion(0),fClassSent(0),fMessage(kMESS_OBJECT)
{
   TString serverurl = strstr(fUrl.GetOptions(),"pmerge=");
   if (serverurl.Length()) {
      serverurl.ReplaceAll("pmerge=","pmerge://");
      fServerLocation = TUrl(serverurl);
   }
}

////////////////////////////////////////////////////////////////////////////////
/// Destructor.

TParallelMergingFile::~TParallelMergingFile()
{
   // We need to call Close, right here so that it is executed _before_
   // the data member of TParallelMergingFile are destructed.
   Close();
   delete fClassSent;
}

////////////////////////////////////////////////////////////////////////////////

void TParallelMergingFile::Close(Option_t *option)
{
   TMemFile::Close(option);
   if (fSocket) {
      if (0==fSocket->Send("Finished")) {          // tell server we are finished
         Warning("Close","Failed to send the finishing message to the server %s:%d",fServerLocation.GetHost(),fServerLocation.GetPort());
      }
      fSocket->Close();
      delete fSocket;
   }
   fSocket = 0;
}

////////////////////////////////////////////////////////////////////////////////
/// Upload the current file data to the merging server.
/// Reset the file and return true in case of success.

Bool_t TParallelMergingFile::UploadAndReset()
{
   // Open connection to server
   if (fSocket == 0) {
      const char *host = fServerLocation.GetHost();
      Int_t port = fServerLocation.GetPort();
      if (host == 0 || host[0] == '\0') {
         host = "localhost";
      }
      if (port <= 0) {
         port = 1095;
      }
      fSocket = new TSocket(host,port);
      if (!fSocket->IsValid()) {
         Error("UploadAndReset","Could not contact the server %s:%d\n",host,port);
         delete fSocket;
         fSocket = 0;
         return kFALSE;
      }
      // Wait till we get the start message
      // server tells us who we are
      Int_t kind;
      Int_t n = fSocket->Recv(fServerIdx, kind);

      if (n < 0 && kind != 0 /* kStartConnection */)
      {
         Error("UploadAndReset","Unexpected server message: kind=%d idx=%d\n",kind,fServerIdx);
         delete fSocket;
         fSocket = 0;
         return kTRUE;
      }
      n = fSocket->Recv(fServerVersion, kind);
      if (n < 0 && kind != 1 /* kProtocol */)
      {
         Fatal("UploadAndReset","Unexpected server message: kind=%d status=%d\n",kind,fServerVersion);
      } else {
         Info("UploadAndReset","Connected to fastMergeServer version %d with index %d\n",fServerVersion,fServerIdx);
      }
      TMessage::EnableSchemaEvolutionForAll(kTRUE);
   }

   fMessage.Reset(kMESS_ANY); // re-use TMessage object
   fMessage.WriteInt(fServerIdx);
   fMessage.WriteTString(GetName());
   fMessage.WriteLong64(GetEND());
   CopyTo(fMessage);

   // FIXME: CXX17: Use init-statement in if to declare `error` variable
   int error;
   if ((error = fSocket->Send(fMessage)) <= 0) {
      Error("UploadAndReset","Upload to the merging server failed with %d\n",error);
      delete fSocket;
      fSocket = 0;
      return kFALSE;
   }

   // Record the StreamerInfo we sent over.
   Int_t isize = fClassIndex->GetSize();
   if (!fClassSent) {
      fClassSent = new TArrayC(isize);
   } else {
      if (isize > fClassSent->GetSize()) {
         fClassSent->Set(isize);
      }
   }
   for(Int_t c = 0; c < isize; ++c) {
      if (fClassIndex->fArray[c]) {
         fClassSent->fArray[c] = 1;
      }
   }
   ResetAfterMerge(0);

   return kTRUE;
}

////////////////////////////////////////////////////////////////////////////////
/// Write memory objects to this file and upload them to the parallel merge server.
/// Then reset all the resetable object (those with a ResetAfterMerge routine,
/// like TTree).
///
/// Loop on all objects in memory (including subdirectories).
/// A new key is created in the KEYS linked list for each object.
/// The list of keys is then saved on the file (via WriteKeys)
/// as a single data record.
/// For values of opt see TObject::Write().
/// The directory header info is rewritten on the directory header record.
/// The linked list of FREE segments is written.
/// The file header is written (bytes 1->fBEGIN).

Int_t TParallelMergingFile::Write(const char *, Int_t opt, Int_t bufsiz)
{
   Int_t nbytes = TMemFile::Write(0,opt,bufsiz);
   if (nbytes) {
      UploadAndReset();
   }
   return nbytes;
}

////////////////////////////////////////////////////////////////////////////////
/// One can not save a const TDirectory object.

Int_t TParallelMergingFile::Write(const char *n, Int_t opt, Int_t bufsize) const
{
   Error("Write const","A const TFile object should not be saved. We try to proceed anyway.");
   return const_cast<TParallelMergingFile*>(this)->Write(n, opt, bufsize);
}

////////////////////////////////////////////////////////////////////////////////
/// Write the list of TStreamerInfo as a single object in this file
/// The class Streamer description for all classes written to this file
/// is saved. See class TStreamerInfo.

void TParallelMergingFile::WriteStreamerInfo()
{
   if (!fWritable) return;
   if (!fClassIndex) return;
   //no need to update the index if no new classes added to the file
   if (fClassIndex->fArray[0] == 0) return;

   // clear fClassIndex for anything we already sent.
   if (fClassSent) {
      Int_t isize = fClassIndex->GetSize();
      Int_t ssize = fClassSent->GetSize();
      for(Int_t c = 0; c < isize && c < ssize; ++c) {
         if (fClassSent->fArray[c]) {
            fClassIndex->fArray[c] = 0;
         }
      }
   }

   TMemFile::WriteStreamerInfo();
}
<|endoftext|>


<commit_before>/*************************************************************************
 *
 *  $RCSfile: dp_resource.cxx,v $
 *
 *  $Revision: 1.5 $
 *
 *  last change: $Author: obo $ $Date: 2004-08-12 12:25:28 $
 *
 *  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: 2002 by Sun Microsystems, Inc.
 *
 *  All Rights Reserved.
 *
 *  Contributor(s): _______________________________________
 *
 *
 ************************************************************************/

#include "dp_misc.h"
#include "dp_resource.h"
#include "osl/module.hxx"
#include "unotools/configmgr.hxx"
#include "tools/resmgr.hxx"
#include "tools/isolang.hxx"

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

namespace dp_misc {

static ::vos::OMutex s_mutex;
::vos::IMutex * g_pResMgrMmutex = &s_mutex;

static lang::Locale s_locale;

//==============================================================================
static ResMgr * getResMgr()
{
    static ResMgr * s_pResMgr = 0;
    if (s_pResMgr == 0)
    {
        OUString slang;
        if (! (::utl::ConfigManager::GetDirectConfigProperty(
                   ::utl::ConfigManager::LOCALE ) >>= slang))
            throw RuntimeException( OUSTR("Cannot determine language!"),
                                    Reference<XInterface>() );

        s_locale = toLocale(slang);

        OUString path;
        ::osl::Module::getUrlFromAddress( (void *) getResMgr, path );
        path = path.copy( 0, path.lastIndexOf( '/' ) + 1 ) + OUSTR("resource");
        String resourcePath( path );

        s_pResMgr = ResMgr::CreateResMgr(
            "deployment" LIBRARY_SOLARUPD(), s_locale, NULL, &resourcePath );
        OSL_ASSERT( s_pResMgr != 0 );
    }
    return s_pResMgr;
}

//==============================================================================
ResId getResId( USHORT id )
{
    ::vos::OGuard guard( g_pResMgrMmutex );
    return ResId( id, getResMgr() );
}

//==============================================================================
String getResourceString( USHORT id )
{
    ::vos::OGuard guard( g_pResMgrMmutex );
    String ret( ResId( id, getResMgr() ) );
    if (ret.SearchAscii( "%PRODUCTNAME" ) != STRING_NOTFOUND) {
        static String s_brandName;
        if (s_brandName.Len() == 0) {
            OUString brandName(
                extract_throw<OUString>(
                    ::utl::ConfigManager::GetDirectConfigProperty(
                        ::utl::ConfigManager::PRODUCTNAME ) ) );
            s_brandName = brandName;
        }
        ret.SearchAndReplaceAllAscii( "%PRODUCTNAME", s_brandName );
    }
    return ret;
}

//==============================================================================
lang::Locale const & getOfficeLocale()
{
    if (g_pResMgrMmutex == 0) {
        ::vos::OGuard guard( g_pResMgrMmutex );
        getResMgr(); // init locale
    }
    return s_locale;
}

}

<commit_msg>INTEGRATION: CWS jl13 (1.5.12); FILE MERGED 2004/11/02 15:34:58 dbo 1.5.12.7: #i36265# 2004/10/28 13:33:16 dbo 1.5.12.6: #i36265# 2004/10/28 13:28:30 dbo 1.5.12.5: #i36265# resource manager madness Issue number: Submitted by: Reviewed by: 2004/10/09 00:22:40 dbo 1.5.12.4: #i35194# 2004/10/09 00:12:52 dbo 1.5.12.3: #i35194# handling invalid manifest entries, resource mgr shutdown crash Issue number: Submitted by: Reviewed by: 2004/10/01 10:23:02 dbo 1.5.12.2: #i34555# added All Files to file picker list, misc cleanup 2004/09/14 15:31:44 dbo 1.5.12.1: #i34149##i33982# modified makeURL(), misc fixes<commit_after>/*************************************************************************
 *
 *  $RCSfile: dp_resource.cxx,v $
 *
 *  $Revision: 1.6 $
 *
 *  last change: $Author: hr $ $Date: 2004-11-09 14:09:38 $
 *
 *  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: 2002 by Sun Microsystems, Inc.
 *
 *  All Rights Reserved.
 *
 *  Contributor(s): _______________________________________
 *
 *
 ************************************************************************/

#include "dp_misc.h"
#include "dp_resource.h"
#include "osl/module.hxx"
#include "cppuhelper/implbase1.hxx"
#include "unotools/configmgr.hxx"
#include "tools/isolang.hxx"

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

namespace dp_misc {
namespace {

struct OfficeLocale : public ::rtl::StaticData<lang::Locale, OfficeLocale> {
    lang::Locale operator () () {
        OUString slang;
        if (! (::utl::ConfigManager::GetDirectConfigProperty(
                   ::utl::ConfigManager::LOCALE ) >>= slang))
            throw RuntimeException( OUSTR("Cannot determine language!"), 0 );
        return toLocale(slang);
    }
};

void dummy() {}
struct DeploymentResMgr : public ::rtl::StaticData< ResMgr *,
                                                    DeploymentResMgr > {
    ResMgr * operator () () {
        OUString path;
        ::osl::Module::getUrlFromAddress( (void *) dummy, path );
        String resourcePath(
            path.copy( 0, path.lastIndexOf( '/' ) + 1 ) + OUSTR("resource") );
        const ::vos::OGuard guard( g_pResMgrMutex );
        return ResMgr::CreateResMgr( "deployment" LIBRARY_SOLARUPD(),
                                     OfficeLocale::get(), NULL, &resourcePath );
    }
};

::vos::OMutex s_mutex;

} // anon namespace

::vos::IMutex * g_pResMgrMutex = &s_mutex;

//==============================================================================
ResId getResId( USHORT id )
{
    const ::vos::OGuard guard( g_pResMgrMutex );
    return ResId( id, DeploymentResMgr::get() );
}

//==============================================================================
String getResourceString( USHORT id )
{
    const ::vos::OGuard guard( g_pResMgrMutex );
    String ret( ResId( id, DeploymentResMgr::get() ) );
    if (ret.SearchAscii( "%PRODUCTNAME" ) != STRING_NOTFOUND) {
        static String s_brandName;
        if (s_brandName.Len() == 0) {
            OUString brandName(
                extract_throw<OUString>(
                    ::utl::ConfigManager::GetDirectConfigProperty(
                        ::utl::ConfigManager::PRODUCTNAME ) ) );
            s_brandName = brandName;
        }
        ret.SearchAndReplaceAllAscii( "%PRODUCTNAME", s_brandName );
    }
    return ret;
}

//==============================================================================
lang::Locale const & getOfficeLocale()
{
    return OfficeLocale::get();
}

}

<|endoftext|>


<commit_before><commit_msg>Move assertions before use<commit_after><|endoftext|>


<commit_before>// Copyright (c) 2011 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

#include "webkit/glue/resource_type.h"

#include "base/logging.h"

using WebKit::WebURLRequest;

// static
ResourceType::Type ResourceType::FromTargetType(
    WebURLRequest::TargetType type) {
  switch (type) {
    case WebURLRequest::TargetIsMainFrame:
      return ResourceType::MAIN_FRAME;
    case WebURLRequest::TargetIsSubframe:
      return ResourceType::SUB_FRAME;
    case WebURLRequest::TargetIsSubresource:
      return ResourceType::SUB_RESOURCE;
    case WebURLRequest::TargetIsStyleSheet:
      return ResourceType::STYLESHEET;
    case WebURLRequest::TargetIsScript:
      return ResourceType::SCRIPT;
    case WebURLRequest::TargetIsFontResource:
      return ResourceType::FONT_RESOURCE;
    case WebURLRequest::TargetIsImage:
      return ResourceType::IMAGE;
    case WebURLRequest::TargetIsObject:
      return ResourceType::OBJECT;
    case WebURLRequest::TargetIsMedia:
      return ResourceType::MEDIA;
    case WebURLRequest::TargetIsWorker:
      return ResourceType::WORKER;
    case WebURLRequest::TargetIsSharedWorker:
      return ResourceType::SHARED_WORKER;
    case WebURLRequest::TargetIsPrefetch:
      return ResourceType::PREFETCH;
    case WebURLRequest::TargetIsPrerender:
      return ResourceType::PRERENDER;
    case WebURLRequest::TargetIsFavicon:
      return ResourceType::FAVICON;
    // TODO(jochen): remove the #ifdef as soon as WebKit side has landed.
#if defined(WEBKIT_HAS_TARGET_IS_XHR)
    case WebURLRequest::TargetIsXHR:
      return ResourceType::XHR;
#endif
    default:
      NOTREACHED();
      return ResourceType::SUB_RESOURCE;
  }
}
<commit_msg>Add support for ResourceRequest::TargetIsXHR (part II)<commit_after>// Copyright (c) 2011 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

#include "webkit/glue/resource_type.h"

#include "base/logging.h"

using WebKit::WebURLRequest;

// static
ResourceType::Type ResourceType::FromTargetType(
    WebURLRequest::TargetType type) {
  switch (type) {
    case WebURLRequest::TargetIsMainFrame:
      return ResourceType::MAIN_FRAME;
    case WebURLRequest::TargetIsSubframe:
      return ResourceType::SUB_FRAME;
    case WebURLRequest::TargetIsSubresource:
      return ResourceType::SUB_RESOURCE;
    case WebURLRequest::TargetIsStyleSheet:
      return ResourceType::STYLESHEET;
    case WebURLRequest::TargetIsScript:
      return ResourceType::SCRIPT;
    case WebURLRequest::TargetIsFontResource:
      return ResourceType::FONT_RESOURCE;
    case WebURLRequest::TargetIsImage:
      return ResourceType::IMAGE;
    case WebURLRequest::TargetIsObject:
      return ResourceType::OBJECT;
    case WebURLRequest::TargetIsMedia:
      return ResourceType::MEDIA;
    case WebURLRequest::TargetIsWorker:
      return ResourceType::WORKER;
    case WebURLRequest::TargetIsSharedWorker:
      return ResourceType::SHARED_WORKER;
    case WebURLRequest::TargetIsPrefetch:
      return ResourceType::PREFETCH;
    case WebURLRequest::TargetIsPrerender:
      return ResourceType::PRERENDER;
    case WebURLRequest::TargetIsFavicon:
      return ResourceType::FAVICON;
    case WebURLRequest::TargetIsXHR:
      return ResourceType::XHR;
    default:
      NOTREACHED();
      return ResourceType::SUB_RESOURCE;
  }
}
<|endoftext|>


<commit_before>/*
  Copyright (c) 2012 Stuart Walsh

  Permission is hereby granted, free of charge, to any person
  obtaining a copy of this software and associated documentation
  files (the "Software"), to deal in the Software without
  restriction, including without limitation the rights to use,
  copy, modify, merge, publish, distribute, sublicense, and/or sell
  copies of the Software, and to permit persons to whom the
  Software is furnished to do so, subject to the following
  conditions:

  The above copyright notice and this permission notice shall be
  included in all copies or substantial portions of the Software.

  THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
  EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES
  OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
  NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT
  HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
  WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
  FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
  OTHER DEALINGS IN THE SOFTWARE.
*/

#include "python/ptupleitem.h"
#include "python/pythonutil.h"
#include "stdinc.h"

PTupleItem::PTupleItem() : PObject(0, 0, 0)
{
}

PTupleItem::PTupleItem(int i, PyObject *obj) : PObject(0, 0, 0), index(i), tuple(obj)
{
  object = PyTuple_GetItem(tuple, index);
  Py_XINCREF(object);
  Logging::trace << "tupleitem: " << object << " [+++] (" << object->ob_refcnt << ")" << Logging::endl;
}

PTupleItem::~PTupleItem()
{
  if(object != NULL)
    Logging::trace << "tupleitem: " << object << " [---] (" << object->ob_refcnt - 1 << ")" << Logging::endl;
}

void PTupleItem::operator =(PObject foo)
{
  PyTuple_SetItem(tuple, index, foo);
  Py_XDECREF(object);
  object = PyTuple_GetItem(tuple, index);
  Py_XINCREF(object);
}
<commit_msg>guard against tuple getitem returning null<commit_after>/*
  Copyright (c) 2012 Stuart Walsh

  Permission is hereby granted, free of charge, to any person
  obtaining a copy of this software and associated documentation
  files (the "Software"), to deal in the Software without
  restriction, including without limitation the rights to use,
  copy, modify, merge, publish, distribute, sublicense, and/or sell
  copies of the Software, and to permit persons to whom the
  Software is furnished to do so, subject to the following
  conditions:

  The above copyright notice and this permission notice shall be
  included in all copies or substantial portions of the Software.

  THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
  EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES
  OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
  NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT
  HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
  WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
  FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
  OTHER DEALINGS IN THE SOFTWARE.
*/

#include "python/ptupleitem.h"
#include "python/pythonutil.h"
#include "stdinc.h"

PTupleItem::PTupleItem() : PObject(0, 0, 0)
{
}

PTupleItem::PTupleItem(int i, PyObject *obj) : PObject(0, 0, 0), index(i), tuple(obj)
{
  object = PyTuple_GetItem(tuple, index);
  Py_XINCREF(object);
  if(object != NULL)
    Logging::trace << "tupleitem: " << object << " [+++] (" << object->ob_refcnt << ")" << Logging::endl;
}

PTupleItem::~PTupleItem()
{
  if(object != NULL)
    Logging::trace << "tupleitem: " << object << " [---] (" << object->ob_refcnt - 1 << ")" << Logging::endl;
}

void PTupleItem::operator =(PObject foo)
{
  PyTuple_SetItem(tuple, index, foo);
  Py_XDECREF(object);
  object = PyTuple_GetItem(tuple, index);
  Py_XINCREF(object);
}
<|endoftext|>