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

// MARKER(update_precomp.py): autogen include statement, do not remove
#include "precompiled_connectivity.hxx"

#ifndef _CONNECTIVITY_EVOAB_LCOLUMNALIAS_HXX_
#include "LColumnAlias.hxx"
#endif
#ifndef _CONNECTIVITY_EVOAB_LDRIVER_HXX_
#include "LDriver.hxx"
#endif
#ifndef _COM_SUN_STAR_BEANS_XPROPERTYSET_HPP_
#include <com/sun/star/beans/XPropertySet.hpp>
#endif
#ifndef _COM_SUN_STAR_CONTAINER_XNAMEACCESS_HPP_
#include <com/sun/star/container/XNameAccess.hpp>
#endif
#ifndef _CONNECTIVITY_EVOAB_LCONFIGACCESS_HXX_
#include "LConfigAccess.hxx"
#endif

using namespace ::connectivity;
using namespace ::connectivity::evoab;
using namespace ::com::sun::star::uno;
using namespace ::com::sun::star::lang;
using namespace ::com::sun::star::beans;
using namespace ::com::sun::star::container;

static const ::rtl::OUString sProgrammaticNames[] =
{
    ::rtl::OUString::createFromAscii("FirstName"),
    ::rtl::OUString::createFromAscii("LastName"),
    ::rtl::OUString::createFromAscii("DisplayName"),
    ::rtl::OUString::createFromAscii("NickName"),
    ::rtl::OUString::createFromAscii("PrimaryEmail"),
    ::rtl::OUString::createFromAscii("SecondEmail"),
    ::rtl::OUString::createFromAscii("PreferMailFormat"),
    ::rtl::OUString::createFromAscii("WorkPhone"),
    ::rtl::OUString::createFromAscii("HomePhone"),
    ::rtl::OUString::createFromAscii("FaxNumber"),
    ::rtl::OUString::createFromAscii("PagerNumber"),
    ::rtl::OUString::createFromAscii("CellularNumber"),
    ::rtl::OUString::createFromAscii("HomeAddress"),
    ::rtl::OUString::createFromAscii("HomeAddress2"),
    ::rtl::OUString::createFromAscii("HomeCity"),
    ::rtl::OUString::createFromAscii("HomeState"),
    ::rtl::OUString::createFromAscii("HomeZipCode"),
    ::rtl::OUString::createFromAscii("HomeCountry"),
    ::rtl::OUString::createFromAscii("WorkAddress"),
    ::rtl::OUString::createFromAscii("WorkAddress2"),
    ::rtl::OUString::createFromAscii("WorkCity"),
    ::rtl::OUString::createFromAscii("WorkState"),
    ::rtl::OUString::createFromAscii("WorkZipCode"),
    ::rtl::OUString::createFromAscii("WorkCountry"),
    ::rtl::OUString::createFromAscii("JobTitle"),
    ::rtl::OUString::createFromAscii("Department"),
    ::rtl::OUString::createFromAscii("Company"),
    ::rtl::OUString::createFromAscii("WebPage1"),
    ::rtl::OUString::createFromAscii("WebPage2"),
    ::rtl::OUString::createFromAscii("BirthYear"),
    ::rtl::OUString::createFromAscii("BirthMonth"),
    ::rtl::OUString::createFromAscii("BirthDay"),
    ::rtl::OUString::createFromAscii("Notes")
};
//------------------------------------------------------------------------------
OColumnAlias::OColumnAlias()
{
    // Initialise m_aAlias with the default values from sProgrammaticNames.
    initialise();

    // Initialise m_aAlias map with the default values from sProgrammaticNames.
    setAliasMap();
}
//------------------------------------------------------------------
OColumnAlias::~OColumnAlias()
{
}
//------------------------------------------------------------------
void OColumnAlias::initialise()
{
    m_aAlias.reserve( END - FIRSTNAME + 1 );
    for (sal_Int32 i(FIRSTNAME); i < END; ++i)
    {
        m_aAlias.push_back(sProgrammaticNames[i]);
        m_aHeadLineNames.push_back(sProgrammaticNames[i]);
    }

    return;
}
//------------------------------------------------------------------
void OColumnAlias::setAlias(const ::com::sun::star::uno::Reference<
                                       ::com::sun::star::lang::XMultiServiceFactory >& _rxORB)
{
        OSL_TRACE("OColumnAlias::setAlias()entered");

        // open our driver settings config node

        // the config path for our own driver's settings
    Reference< XPropertySet > xEvoDriverNode = createDriverConfigNode( _rxORB, OEvoabDriver::getImplementationName_Static() );
    //Reference< XPropertySet > xMozDriverNode = createDriverConfigNode( _rxORB, mozab::OConnection::getDriverImplementationName() );
    Reference< XPropertySet > xMozDriverNode = createDriverConfigNode( _rxORB, ::rtl::OUString::createFromAscii ("com.sun.star.comp.sdbc.MozabDriver") );
    if ( xEvoDriverNode.is() && xMozDriverNode.is() )
    {
        try
        {
            //=============================================================
            Reference< XNameAccess > xEvoAliasesNode;
            Reference< XNameAccess > xMozAliasesNode;
            xEvoDriverNode->getPropertyValue( ::rtl::OUString::createFromAscii("ColumnAliases") ) >>= xEvoAliasesNode;
            xMozDriverNode->getPropertyValue( ::rtl::OUString::createFromAscii("ColumnAliases") ) >>= xMozAliasesNode;
            OSL_ENSURE( xEvoAliasesNode.is(), "OColumnAlias::setAlias: missing the evolution aliases node!" );
            OSL_ENSURE( xMozAliasesNode.is(), "OColumnAlias::setAlias: missing the mozilla aliases node!" );

            // this is a set of string nodes
            Sequence< ::rtl::OUString > aColumnProgrammaticNames;
            //OSL_TRACE("OColumnAlias::setAlias()before xAliasesNode->getElementNames()");
            if ( xEvoAliasesNode.is() )
                aColumnProgrammaticNames = xEvoAliasesNode->getElementNames();
            //OSL_TRACE("OColumnAlias::setAlias()after xAliasesNode->getElementNames()");

            //=============================================================
            // travel through all the set elements
            const ::rtl::OUString* pProgrammaticNames = aColumnProgrammaticNames.getConstArray();
            const ::rtl::OUString* pProgrammaticNamesEnd = pProgrammaticNames + aColumnProgrammaticNames.getLength();
            ::rtl::OUString sAssignedAlias;
            ::rtl::OUString sHeadLineName;

            for ( ; pProgrammaticNames < pProgrammaticNamesEnd; ++pProgrammaticNames )
            {
                //OSL_TRACE("OColumnAlias::setAlias()::*pProgrammaticNames = %s\n", ((OUtoCStr(*pProgrammaticNames)) ? (OUtoCStr(*pProgrammaticNames)):("NULL")) );
                OSL_ENSURE( m_aAliasMap.end() != m_aAliasMap.find( *pProgrammaticNames ),
                    "OColumnAlias::setAlias: found an invalid programmtic name!" );
                    // if this asserts, somebody stored a programmatic name in the configuration
                    // which is not allowed (i.e. not in the list of known programmatics).
                //OSL_TRACE("OColumnAlias::setAlias()before xAliasesNode->getByName()");

#if OSL_DEBUG_LEVEL > 0
                sal_Bool bExtractionSuccess =
#endif
                xMozAliasesNode->getByName( *pProgrammaticNames) >>= sAssignedAlias;
                OSL_ENSURE( bExtractionSuccess, "OColumnAlias::setAlias: invalid mozilla config data!" );
#if OSL_DEBUG_LEVEL > 0
                bExtractionSuccess =
#endif
                xEvoAliasesNode->getByName( *pProgrammaticNames) >>= sHeadLineName;
                OSL_ENSURE( bExtractionSuccess, "OColumnAlias::setAlias: invalid evolution config data!" );
                //OSL_TRACE("OColumnAlias::setAlias()after xAliasesNode->getByName()");

                // normalize in case the config data is corrupted
                // (what we really don't need is an empty alias ...)
                if ( 0 == sAssignedAlias.getLength() )
                      sAssignedAlias = *pProgrammaticNames;
                if ( 0 == sHeadLineName.getLength() )
                      sHeadLineName = *pProgrammaticNames;
                //OSL_TRACE("OColumnAlias::setAlias()::sAssignedAlias = %s\n", ((OUtoCStr(sAssignedAlias)) ? (OUtoCStr(sAssignedAlias)):("NULL")) );
                //OSL_TRACE("OColumnAlias::setAlias()::sHeadLineName = %s\n", ((OUtoCStr(sHeadLineName)) ? (OUtoCStr(sHeadLineName)):("NULL")) );

                //=============================================================
                // check the value
                // look up the programmatic indicated by pProgrammaticNames in the known programmatics
                const ::rtl::OUString* pProgrammatic = sProgrammaticNames + FIRSTNAME;
                const ::rtl::OUString* pProgrammaticEnd = sProgrammaticNames + END;

                OSL_ENSURE( (sal_Int32)m_aAlias.size() == pProgrammaticEnd - pProgrammatic,
                    "OColumnAlias::setAlias: aliases vector not yet initialized!" );

                // the destination where we want to remember the alias
                ::std::vector< ::rtl::OUString >::iterator aAlias = m_aAlias.begin();
                ::std::vector< ::rtl::OUString >::iterator aHeadLineName = m_aHeadLineNames.begin();

                for ( ; pProgrammatic < pProgrammaticEnd; ++pProgrammatic, ++aAlias, ++aHeadLineName )
                {
                    //OSL_TRACE("OColumnAlias::setAlias()::*pProgrammatic = %s\n", ((OUtoCStr(*pProgrammatic)) ? (OUtoCStr(*pProgrammatic)):("NULL")) );
                    if ( pProgrammaticNames->equals( *pProgrammatic ) )
                    {
                        // add alias to the vector
                        *aAlias = sAssignedAlias;
                        *aHeadLineName = sHeadLineName;
                        break;
                    }
                }
            }
        }
        catch( const Exception& )
        {
            OSL_ENSURE( sal_False, "OColumnAlias::setAlias: could not read my driver's configuration data!" );
        }
    }

    // Initialise m_aAliasMap.
    setAliasMap();

    return;
}
//------------------------------------------------------------------
const ::std::vector< ::rtl::OUString> & OColumnAlias::getAlias() const
{
    return m_aAlias;
}
//------------------------------------------------------------------
const ::std::map< ::rtl::OUString, ::rtl::OUString> & OColumnAlias::getAliasMap() const
{
    return m_aAliasMap;
}
//------------------------------------------------------------------
void OColumnAlias::setAliasMap()
{
        // Fill the map with the values of m_aAlias
        // and the sProgrammaticNames array.
    for (sal_Int32 i(FIRSTNAME); i < END; ++i) {
        m_aAliasMap[m_aAlias[i]] = m_aHeadLineNames[i];
        //OSL_TRACE("OColumnAlias::setAliasMap()::m_aAlias[i] = %s\n", ((OUtoCStr(m_aAlias[i])) ? (OUtoCStr(m_aAlias[i])):("NULL")) );
        //OSL_TRACE("OColumnAlias::setAliasMap()::m_aAliasMap[m_aAlias[i]] = %s\n", ((OUtoCStr(m_aAliasMap[m_aAlias[i]])) ? (OUtoCStr(m_aAliasMap[m_aAlias[i]])):("NULL")) );
    }

        return;
}
//------------------------------------------------------------------
<commit_msg>INTEGRATION: CWS changefileheader (1.6.216); FILE MERGED 2008/04/01 10:52:54 thb 1.6.216.2: #i85898# Stripping all external header guards 2008/03/28 15:23:29 rt 1.6.216.1: #i87441# Change license header to LPGL v3.<commit_after>/*************************************************************************
 *
 * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
 *
 * Copyright 2008 by Sun Microsystems, Inc.
 *
 * OpenOffice.org - a multi-platform office productivity suite
 *
 * $RCSfile: LColumnAlias.cxx,v $
 * $Revision: 1.7 $
 *
 * This file is part of OpenOffice.org.
 *
 * OpenOffice.org is free software: you can redistribute it and/or modify
 * it under the terms of the GNU Lesser General Public License version 3
 * only, as published by the Free Software Foundation.
 *
 * OpenOffice.org 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 version 3 for more details
 * (a copy is included in the LICENSE file that accompanied this code).
 *
 * You should have received a copy of the GNU Lesser General Public License
 * version 3 along with OpenOffice.org.  If not, see
 * <http://www.openoffice.org/license.html>
 * for a copy of the LGPLv3 License.
 *
 ************************************************************************/

// MARKER(update_precomp.py): autogen include statement, do not remove
#include "precompiled_connectivity.hxx"
#include "LColumnAlias.hxx"
#include "LDriver.hxx"
#include <com/sun/star/beans/XPropertySet.hpp>
#include <com/sun/star/container/XNameAccess.hpp>
#include "LConfigAccess.hxx"

using namespace ::connectivity;
using namespace ::connectivity::evoab;
using namespace ::com::sun::star::uno;
using namespace ::com::sun::star::lang;
using namespace ::com::sun::star::beans;
using namespace ::com::sun::star::container;

static const ::rtl::OUString sProgrammaticNames[] =
{
    ::rtl::OUString::createFromAscii("FirstName"),
    ::rtl::OUString::createFromAscii("LastName"),
    ::rtl::OUString::createFromAscii("DisplayName"),
    ::rtl::OUString::createFromAscii("NickName"),
    ::rtl::OUString::createFromAscii("PrimaryEmail"),
    ::rtl::OUString::createFromAscii("SecondEmail"),
    ::rtl::OUString::createFromAscii("PreferMailFormat"),
    ::rtl::OUString::createFromAscii("WorkPhone"),
    ::rtl::OUString::createFromAscii("HomePhone"),
    ::rtl::OUString::createFromAscii("FaxNumber"),
    ::rtl::OUString::createFromAscii("PagerNumber"),
    ::rtl::OUString::createFromAscii("CellularNumber"),
    ::rtl::OUString::createFromAscii("HomeAddress"),
    ::rtl::OUString::createFromAscii("HomeAddress2"),
    ::rtl::OUString::createFromAscii("HomeCity"),
    ::rtl::OUString::createFromAscii("HomeState"),
    ::rtl::OUString::createFromAscii("HomeZipCode"),
    ::rtl::OUString::createFromAscii("HomeCountry"),
    ::rtl::OUString::createFromAscii("WorkAddress"),
    ::rtl::OUString::createFromAscii("WorkAddress2"),
    ::rtl::OUString::createFromAscii("WorkCity"),
    ::rtl::OUString::createFromAscii("WorkState"),
    ::rtl::OUString::createFromAscii("WorkZipCode"),
    ::rtl::OUString::createFromAscii("WorkCountry"),
    ::rtl::OUString::createFromAscii("JobTitle"),
    ::rtl::OUString::createFromAscii("Department"),
    ::rtl::OUString::createFromAscii("Company"),
    ::rtl::OUString::createFromAscii("WebPage1"),
    ::rtl::OUString::createFromAscii("WebPage2"),
    ::rtl::OUString::createFromAscii("BirthYear"),
    ::rtl::OUString::createFromAscii("BirthMonth"),
    ::rtl::OUString::createFromAscii("BirthDay"),
    ::rtl::OUString::createFromAscii("Notes")
};
//------------------------------------------------------------------------------
OColumnAlias::OColumnAlias()
{
    // Initialise m_aAlias with the default values from sProgrammaticNames.
    initialise();

    // Initialise m_aAlias map with the default values from sProgrammaticNames.
    setAliasMap();
}
//------------------------------------------------------------------
OColumnAlias::~OColumnAlias()
{
}
//------------------------------------------------------------------
void OColumnAlias::initialise()
{
    m_aAlias.reserve( END - FIRSTNAME + 1 );
    for (sal_Int32 i(FIRSTNAME); i < END; ++i)
    {
        m_aAlias.push_back(sProgrammaticNames[i]);
        m_aHeadLineNames.push_back(sProgrammaticNames[i]);
    }

    return;
}
//------------------------------------------------------------------
void OColumnAlias::setAlias(const ::com::sun::star::uno::Reference<
                                       ::com::sun::star::lang::XMultiServiceFactory >& _rxORB)
{
        OSL_TRACE("OColumnAlias::setAlias()entered");

        // open our driver settings config node

        // the config path for our own driver's settings
    Reference< XPropertySet > xEvoDriverNode = createDriverConfigNode( _rxORB, OEvoabDriver::getImplementationName_Static() );
    //Reference< XPropertySet > xMozDriverNode = createDriverConfigNode( _rxORB, mozab::OConnection::getDriverImplementationName() );
    Reference< XPropertySet > xMozDriverNode = createDriverConfigNode( _rxORB, ::rtl::OUString::createFromAscii ("com.sun.star.comp.sdbc.MozabDriver") );
    if ( xEvoDriverNode.is() && xMozDriverNode.is() )
    {
        try
        {
            //=============================================================
            Reference< XNameAccess > xEvoAliasesNode;
            Reference< XNameAccess > xMozAliasesNode;
            xEvoDriverNode->getPropertyValue( ::rtl::OUString::createFromAscii("ColumnAliases") ) >>= xEvoAliasesNode;
            xMozDriverNode->getPropertyValue( ::rtl::OUString::createFromAscii("ColumnAliases") ) >>= xMozAliasesNode;
            OSL_ENSURE( xEvoAliasesNode.is(), "OColumnAlias::setAlias: missing the evolution aliases node!" );
            OSL_ENSURE( xMozAliasesNode.is(), "OColumnAlias::setAlias: missing the mozilla aliases node!" );

            // this is a set of string nodes
            Sequence< ::rtl::OUString > aColumnProgrammaticNames;
            //OSL_TRACE("OColumnAlias::setAlias()before xAliasesNode->getElementNames()");
            if ( xEvoAliasesNode.is() )
                aColumnProgrammaticNames = xEvoAliasesNode->getElementNames();
            //OSL_TRACE("OColumnAlias::setAlias()after xAliasesNode->getElementNames()");

            //=============================================================
            // travel through all the set elements
            const ::rtl::OUString* pProgrammaticNames = aColumnProgrammaticNames.getConstArray();
            const ::rtl::OUString* pProgrammaticNamesEnd = pProgrammaticNames + aColumnProgrammaticNames.getLength();
            ::rtl::OUString sAssignedAlias;
            ::rtl::OUString sHeadLineName;

            for ( ; pProgrammaticNames < pProgrammaticNamesEnd; ++pProgrammaticNames )
            {
                //OSL_TRACE("OColumnAlias::setAlias()::*pProgrammaticNames = %s\n", ((OUtoCStr(*pProgrammaticNames)) ? (OUtoCStr(*pProgrammaticNames)):("NULL")) );
                OSL_ENSURE( m_aAliasMap.end() != m_aAliasMap.find( *pProgrammaticNames ),
                    "OColumnAlias::setAlias: found an invalid programmtic name!" );
                    // if this asserts, somebody stored a programmatic name in the configuration
                    // which is not allowed (i.e. not in the list of known programmatics).
                //OSL_TRACE("OColumnAlias::setAlias()before xAliasesNode->getByName()");

#if OSL_DEBUG_LEVEL > 0
                sal_Bool bExtractionSuccess =
#endif
                xMozAliasesNode->getByName( *pProgrammaticNames) >>= sAssignedAlias;
                OSL_ENSURE( bExtractionSuccess, "OColumnAlias::setAlias: invalid mozilla config data!" );
#if OSL_DEBUG_LEVEL > 0
                bExtractionSuccess =
#endif
                xEvoAliasesNode->getByName( *pProgrammaticNames) >>= sHeadLineName;
                OSL_ENSURE( bExtractionSuccess, "OColumnAlias::setAlias: invalid evolution config data!" );
                //OSL_TRACE("OColumnAlias::setAlias()after xAliasesNode->getByName()");

                // normalize in case the config data is corrupted
                // (what we really don't need is an empty alias ...)
                if ( 0 == sAssignedAlias.getLength() )
                      sAssignedAlias = *pProgrammaticNames;
                if ( 0 == sHeadLineName.getLength() )
                      sHeadLineName = *pProgrammaticNames;
                //OSL_TRACE("OColumnAlias::setAlias()::sAssignedAlias = %s\n", ((OUtoCStr(sAssignedAlias)) ? (OUtoCStr(sAssignedAlias)):("NULL")) );
                //OSL_TRACE("OColumnAlias::setAlias()::sHeadLineName = %s\n", ((OUtoCStr(sHeadLineName)) ? (OUtoCStr(sHeadLineName)):("NULL")) );

                //=============================================================
                // check the value
                // look up the programmatic indicated by pProgrammaticNames in the known programmatics
                const ::rtl::OUString* pProgrammatic = sProgrammaticNames + FIRSTNAME;
                const ::rtl::OUString* pProgrammaticEnd = sProgrammaticNames + END;

                OSL_ENSURE( (sal_Int32)m_aAlias.size() == pProgrammaticEnd - pProgrammatic,
                    "OColumnAlias::setAlias: aliases vector not yet initialized!" );

                // the destination where we want to remember the alias
                ::std::vector< ::rtl::OUString >::iterator aAlias = m_aAlias.begin();
                ::std::vector< ::rtl::OUString >::iterator aHeadLineName = m_aHeadLineNames.begin();

                for ( ; pProgrammatic < pProgrammaticEnd; ++pProgrammatic, ++aAlias, ++aHeadLineName )
                {
                    //OSL_TRACE("OColumnAlias::setAlias()::*pProgrammatic = %s\n", ((OUtoCStr(*pProgrammatic)) ? (OUtoCStr(*pProgrammatic)):("NULL")) );
                    if ( pProgrammaticNames->equals( *pProgrammatic ) )
                    {
                        // add alias to the vector
                        *aAlias = sAssignedAlias;
                        *aHeadLineName = sHeadLineName;
                        break;
                    }
                }
            }
        }
        catch( const Exception& )
        {
            OSL_ENSURE( sal_False, "OColumnAlias::setAlias: could not read my driver's configuration data!" );
        }
    }

    // Initialise m_aAliasMap.
    setAliasMap();

    return;
}
//------------------------------------------------------------------
const ::std::vector< ::rtl::OUString> & OColumnAlias::getAlias() const
{
    return m_aAlias;
}
//------------------------------------------------------------------
const ::std::map< ::rtl::OUString, ::rtl::OUString> & OColumnAlias::getAliasMap() const
{
    return m_aAliasMap;
}
//------------------------------------------------------------------
void OColumnAlias::setAliasMap()
{
        // Fill the map with the values of m_aAlias
        // and the sProgrammaticNames array.
    for (sal_Int32 i(FIRSTNAME); i < END; ++i) {
        m_aAliasMap[m_aAlias[i]] = m_aHeadLineNames[i];
        //OSL_TRACE("OColumnAlias::setAliasMap()::m_aAlias[i] = %s\n", ((OUtoCStr(m_aAlias[i])) ? (OUtoCStr(m_aAlias[i])):("NULL")) );
        //OSL_TRACE("OColumnAlias::setAliasMap()::m_aAliasMap[m_aAlias[i]] = %s\n", ((OUtoCStr(m_aAliasMap[m_aAlias[i]])) ? (OUtoCStr(m_aAliasMap[m_aAlias[i]])):("NULL")) );
    }

        return;
}
//------------------------------------------------------------------
<|endoftext|>


<commit_before>/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */
/*************************************************************************
 *
 * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
 *
 * Copyright 2000, 2010 Oracle and/or its affiliates.
 *
 * OpenOffice.org - a multi-platform office productivity suite
 *
 * This file is part of OpenOffice.org.
 *
 * OpenOffice.org is free software: you can redistribute it and/or modify
 * it under the terms of the GNU Lesser General Public License version 3
 * only, as published by the Free Software Foundation.
 *
 * OpenOffice.org 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 version 3 for more details
 * (a copy is included in the LICENSE file that accompanied this code).
 *
 * You should have received a copy of the GNU Lesser General Public License
 * version 3 along with OpenOffice.org.  If not, see
 * <http://www.openoffice.org/license.html>
 * for a copy of the LGPLv3 License.
 *
 ************************************************************************/

#ifndef _CONNECTIVITY_MAB_COLUMNALIAS_HXX_
#define _CONNECTIVITY_MAB_COLUMNALIAS_HXX_

#include <unotools/confignode.hxx>

#include <osl/mutex.hxx>
#include <vector>
#include <boost/unordered_map.hpp>

namespace connectivity
{
    namespace mozab
    {
        class OColumnAlias
        {
        public:
            struct AliasEntry
            {
                ::rtl::OString  programmaticAsciiName;
                sal_Int32       columnPosition;

                AliasEntry()
                    :programmaticAsciiName()
                    ,columnPosition( 0 )
                {
                }
                AliasEntry( const sal_Char* _programmaticAsciiName, sal_Int32 _columnPosition )
                    :programmaticAsciiName( _programmaticAsciiName )
                    ,columnPosition( _columnPosition )
                {
                }
            };
            typedef ::boost::unordered_map< ::rtl::OUString, AliasEntry, ::rtl::OUStringHash > AliasMap;

        private:
            AliasMap    m_aAliasMap;

        public:
            OColumnAlias( const ::com::sun::star::uno::Reference< ::com::sun::star::lang::XMultiServiceFactory > & );

            inline bool hasAlias( const ::rtl::OUString& _rAlias ) const
            {
                return m_aAliasMap.find( _rAlias ) != m_aAliasMap.end();
            }
            ::rtl::OString getProgrammaticNameOrFallbackToUTF8Alias( const ::rtl::OUString& _rAlias ) const;

            inline AliasMap::const_iterator begin() const { return m_aAliasMap.begin(); }
            inline AliasMap::const_iterator end() const { return m_aAliasMap.end(); }

            bool isColumnSearchable( const ::rtl::OUString _alias ) const;

        private:
            void initialize( const ::com::sun::star::uno::Reference< ::com::sun::star::lang::XMultiServiceFactory >& _rxORB );
        };
    }
}
#endif // _CONNECTIVITY_MAB_COLUMNALIAS_HXX_

/* vim:set shiftwidth=4 softtabstop=4 expandtab: */
<commit_msg>WaE: signed/unsigned<commit_after>/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */
/*************************************************************************
 *
 * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
 *
 * Copyright 2000, 2010 Oracle and/or its affiliates.
 *
 * OpenOffice.org - a multi-platform office productivity suite
 *
 * This file is part of OpenOffice.org.
 *
 * OpenOffice.org is free software: you can redistribute it and/or modify
 * it under the terms of the GNU Lesser General Public License version 3
 * only, as published by the Free Software Foundation.
 *
 * OpenOffice.org 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 version 3 for more details
 * (a copy is included in the LICENSE file that accompanied this code).
 *
 * You should have received a copy of the GNU Lesser General Public License
 * version 3 along with OpenOffice.org.  If not, see
 * <http://www.openoffice.org/license.html>
 * for a copy of the LGPLv3 License.
 *
 ************************************************************************/

#ifndef _CONNECTIVITY_MAB_COLUMNALIAS_HXX_
#define _CONNECTIVITY_MAB_COLUMNALIAS_HXX_

#include <unotools/confignode.hxx>

#include <osl/mutex.hxx>
#include <vector>
#include <boost/unordered_map.hpp>

namespace connectivity
{
    namespace mozab
    {
        class OColumnAlias
        {
        public:
            struct AliasEntry
            {
                ::rtl::OString  programmaticAsciiName;
                size_t columnPosition;

                AliasEntry()
                    :programmaticAsciiName()
                    ,columnPosition( 0 )
                {
                }
                AliasEntry( const sal_Char* _programmaticAsciiName, size_t _columnPosition )
                    :programmaticAsciiName( _programmaticAsciiName )
                    ,columnPosition( _columnPosition )
                {
                }
            };
            typedef ::boost::unordered_map< ::rtl::OUString, AliasEntry, ::rtl::OUStringHash > AliasMap;

        private:
            AliasMap    m_aAliasMap;

        public:
            OColumnAlias( const ::com::sun::star::uno::Reference< ::com::sun::star::lang::XMultiServiceFactory > & );

            inline bool hasAlias( const ::rtl::OUString& _rAlias ) const
            {
                return m_aAliasMap.find( _rAlias ) != m_aAliasMap.end();
            }
            ::rtl::OString getProgrammaticNameOrFallbackToUTF8Alias( const ::rtl::OUString& _rAlias ) const;

            inline AliasMap::const_iterator begin() const { return m_aAliasMap.begin(); }
            inline AliasMap::const_iterator end() const { return m_aAliasMap.end(); }

            bool isColumnSearchable( const ::rtl::OUString _alias ) const;

        private:
            void initialize( const ::com::sun::star::uno::Reference< ::com::sun::star::lang::XMultiServiceFactory >& _rxORB );
        };
    }
}
#endif // _CONNECTIVITY_MAB_COLUMNALIAS_HXX_

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


<commit_before>// Copyright 2014 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 "content/browser/devtools/protocol/input_handler.h"

#include "base/strings/stringprintf.h"
#include "content/browser/renderer_host/render_view_host_impl.h"
#include "third_party/WebKit/public/web/WebInputEvent.h"

namespace content {
namespace devtools {
namespace input {

typedef DevToolsProtocolClient::Response Response;

InputHandler::InputHandler()
  : host_(NULL) {
}

InputHandler::~InputHandler() {
}

void InputHandler::SetRenderViewHost(RenderViewHostImpl* host) {
  host_ = host;
}

void InputHandler::SetClient(scoped_ptr<DevToolsProtocolClient> client) {
}

Response InputHandler::DispatchKeyEvent(
    const std::string& type,
    const int* modifiers,
    const double* timestamp,
    const std::string* text,
    const std::string* unmodified_text,
    const std::string* key_identifier,
    const std::string* code,
    const int* windows_virtual_key_code,
    const int* native_virtual_key_code,
    const bool* auto_repeat,
    const bool* is_keypad,
    const bool* is_system_key) {
  return Response::FallThrough();
}

Response InputHandler::DispatchMouseEvent(
    const std::string& type,
    int x,
    int y,
    const int* modifiers,
    const double* timestamp,
    const std::string* button,
    const int* click_count) {
  return Response::FallThrough();
}

Response InputHandler::EmulateTouchFromMouseEvent(const std::string& type,
                                                  int x,
                                                  int y,
                                                  double timestamp,
                                                  const std::string& button,
                                                  double* delta_x,
                                                  double* delta_y,
                                                  int* modifiers,
                                                  int* click_count) {
  blink::WebMouseWheelEvent wheel_event;
  blink::WebMouseEvent mouse_event;
  blink::WebMouseEvent* event = &mouse_event;

  if (type == emulate_touch_from_mouse_event::kTypeMousePressed) {
    event->type = blink::WebInputEvent::MouseDown;
  } else if (type == emulate_touch_from_mouse_event::kTypeMouseReleased) {
    event->type = blink::WebInputEvent::MouseUp;
  } else if (type == emulate_touch_from_mouse_event::kTypeMouseMoved) {
    event->type = blink::WebInputEvent::MouseMove;
  } else if (type == emulate_touch_from_mouse_event::kTypeMouseWheel) {
    if (!delta_x || !delta_y) {
      return Response::InvalidParams(
          "'deltaX' and 'deltaY' are expected for mouseWheel event");
    }
    wheel_event.deltaX = static_cast<float>(*delta_x);
    wheel_event.deltaY = static_cast<float>(*delta_y);
    event = &wheel_event;
    event->type = blink::WebInputEvent::MouseWheel;
  } else {
    return Response::InvalidParams(
        base::StringPrintf("Unexpected event type '%s'", type.c_str()));
  }

  if (modifiers) {
    if (*modifiers & 1)
      event->modifiers |= blink::WebInputEvent::AltKey;
    if (*modifiers & 2)
      event->modifiers |= blink::WebInputEvent::ControlKey;
    if (*modifiers & 4)
      event->modifiers |= blink::WebInputEvent::MetaKey;
    if (*modifiers & 8)
      event->modifiers |= blink::WebInputEvent::ShiftKey;
  }

  event->timeStampSeconds = timestamp;
  event->x = x;
  event->y = y;
  event->windowX = x;
  event->windowY = y;
  event->globalX = x;
  event->globalY = y;

  if (click_count)
    event->clickCount = *click_count;

  if (button == emulate_touch_from_mouse_event::kButtonNone) {
    event->button = blink::WebMouseEvent::ButtonNone;
  } else if (button == emulate_touch_from_mouse_event::kButtonLeft) {
    event->button = blink::WebMouseEvent::ButtonLeft;
    event->modifiers |= blink::WebInputEvent::LeftButtonDown;
  } else if (button == emulate_touch_from_mouse_event::kButtonMiddle) {
    event->button = blink::WebMouseEvent::ButtonMiddle;
    event->modifiers |= blink::WebInputEvent::MiddleButtonDown;
  } else if (button == emulate_touch_from_mouse_event::kButtonRight) {
    event->button = blink::WebMouseEvent::ButtonRight;
    event->modifiers |= blink::WebInputEvent::RightButtonDown;
  } else {
    return Response::InvalidParams(
        base::StringPrintf("Unexpected mouse button '%s'", button.c_str()));
  }

  if (!host_)
    return Response::ServerError("Could not connect to view");

  if (event->type == blink::WebInputEvent::MouseWheel)
    host_->ForwardWheelEvent(wheel_event);
  else
    host_->ForwardMouseEvent(mouse_event);
  return Response::OK();
}

Response InputHandler::SynthesizePinchGesture(
    DevToolsCommandId command_id,
    int x,
    int y,
    double scale_factor,
    const int* relative_speed,
    const std::string* gesture_source_type) {
  return Response::InternalError("Not yet implemented");
}

Response InputHandler::SynthesizeScrollGesture(
    DevToolsCommandId command_id,
    int x,
    int y,
    const int* x_distance,
    const int* y_distance,
    const int* x_overscroll,
    const int* y_overscroll,
    const bool* prevent_fling,
    const int* speed,
    const std::string* gesture_source_type) {
  return Response::InternalError("Not yet implemented");
}

Response InputHandler::SynthesizeTapGesture(
    DevToolsCommandId command_id,
    int x,
    int y,
    const int* duration,
    const int* tap_count,
    const std::string* gesture_source_type) {
  return Response::InternalError("Not yet implemented");
}

}  // namespace input
}  // namespace devtools
}  // namespace content
<commit_msg>[DevTools] Input domain implementation in browser.<commit_after>// Copyright 2014 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 "content/browser/devtools/protocol/input_handler.h"

#include "base/strings/stringprintf.h"
#include "base/strings/utf_string_conversions.h"
#include "content/browser/renderer_host/render_view_host_impl.h"
#include "third_party/WebKit/public/web/WebInputEvent.h"
#include "ui/events/keycodes/dom4/keycode_converter.h"

namespace content {
namespace devtools {
namespace input {

typedef DevToolsProtocolClient::Response Response;

namespace {

void SetEventModifiers(blink::WebInputEvent* event, const int* modifiers) {
  if (!modifiers)
    return;
  if (*modifiers & 1)
    event->modifiers |= blink::WebInputEvent::AltKey;
  if (*modifiers & 2)
    event->modifiers |= blink::WebInputEvent::ControlKey;
  if (*modifiers & 4)
    event->modifiers |= blink::WebInputEvent::MetaKey;
  if (*modifiers & 8)
    event->modifiers |= blink::WebInputEvent::ShiftKey;
}

void SetEventTimestamp(blink::WebInputEvent* event, const double* timestamp) {
  event->timeStampSeconds =
      timestamp ? *timestamp : base::Time::Now().ToDoubleT();
}

bool SetKeyboardEventText(blink::WebUChar* to, const std::string* from) {
  if (!from)
    return true;

  base::string16 text16 = base::UTF8ToUTF16(*from);
  if (text16.size() > blink::WebKeyboardEvent::textLengthCap)
    return false;

  for (size_t i = 0; i < text16.size(); ++i)
    to[i] = text16[i];
  return true;
}

bool SetMouseEventButton(blink::WebMouseEvent* event,
                         const std::string* button) {
  if (!button)
    return true;

  if (*button == dispatch_mouse_event::kButtonNone) {
    event->button = blink::WebMouseEvent::ButtonNone;
  } else if (*button == dispatch_mouse_event::kButtonLeft) {
    event->button = blink::WebMouseEvent::ButtonLeft;
    event->modifiers |= blink::WebInputEvent::LeftButtonDown;
  } else if (*button == dispatch_mouse_event::kButtonMiddle) {
    event->button = blink::WebMouseEvent::ButtonMiddle;
    event->modifiers |= blink::WebInputEvent::MiddleButtonDown;
  } else if (*button == dispatch_mouse_event::kButtonRight) {
    event->button = blink::WebMouseEvent::ButtonRight;
    event->modifiers |= blink::WebInputEvent::RightButtonDown;
  } else {
    return false;
  }
  return true;
}

bool SetMouseEventType(blink::WebMouseEvent* event, const std::string& type) {
  if (type == dispatch_mouse_event::kTypeMousePressed) {
    event->type = blink::WebInputEvent::MouseDown;
  } else if (type == dispatch_mouse_event::kTypeMouseReleased) {
    event->type = blink::WebInputEvent::MouseUp;
  } else if (type == dispatch_mouse_event::kTypeMouseMoved) {
    event->type = blink::WebInputEvent::MouseMove;
  } else {
    return false;
  }
  return true;
}

}  // namespace

InputHandler::InputHandler()
  : host_(NULL) {
}

InputHandler::~InputHandler() {
}

void InputHandler::SetRenderViewHost(RenderViewHostImpl* host) {
  host_ = host;
}

void InputHandler::SetClient(scoped_ptr<DevToolsProtocolClient> client) {
}

Response InputHandler::DispatchKeyEvent(
    const std::string& type,
    const int* modifiers,
    const double* timestamp,
    const std::string* text,
    const std::string* unmodified_text,
    const std::string* key_identifier,
    const std::string* code,
    const int* windows_virtual_key_code,
    const int* native_virtual_key_code,
    const bool* auto_repeat,
    const bool* is_keypad,
    const bool* is_system_key) {
  NativeWebKeyboardEvent event;

  if (type == dispatch_key_event::kTypeKeyDown) {
    event.type = blink::WebInputEvent::KeyDown;
  } else if (type == dispatch_key_event::kTypeKeyUp) {
    event.type = blink::WebInputEvent::KeyUp;
  } else if (type == dispatch_key_event::kTypeChar) {
    event.type = blink::WebInputEvent::Char;
  } else if (type == dispatch_key_event::kTypeRawKeyDown) {
    event.type = blink::WebInputEvent::RawKeyDown;
  } else {
    return Response::InvalidParams(
        base::StringPrintf("Unexpected event type '%s'", type.c_str()));
  }

  SetEventModifiers(&event, modifiers);
  SetEventTimestamp(&event, timestamp);
  if (!SetKeyboardEventText(event.text, text))
    return Response::InvalidParams("Invalid 'text' parameter");
  if (!SetKeyboardEventText(event.unmodifiedText, unmodified_text))
    return Response::InvalidParams("Invalid 'unmodifiedText' parameter");

  if (key_identifier) {
    if (key_identifier->size() >
        blink::WebKeyboardEvent::keyIdentifierLengthCap) {
      return Response::InvalidParams("Invalid 'keyIdentifier' parameter");
    }
    for (size_t i = 0; i < key_identifier->size(); ++i)
      event.keyIdentifier[i] = (*key_identifier)[i];
  }

  if (code) {
    event.domCode = static_cast<int>(
        ui::KeycodeConverter::CodeStringToDomCode(code->c_str()));
  }

  if (windows_virtual_key_code)
    event.windowsKeyCode = *windows_virtual_key_code;
  if (native_virtual_key_code)
    event.nativeKeyCode = *native_virtual_key_code;
  if (auto_repeat && *auto_repeat)
    event.modifiers |= blink::WebInputEvent::IsAutoRepeat;
  if (is_keypad && *is_keypad)
    event.modifiers |= blink::WebInputEvent::IsKeyPad;
  if (is_system_key)
    event.isSystemKey = *is_system_key;

  if (!host_)
    return Response::ServerError("Could not connect to view");

  if (!host_->is_focused())
    host_->Focus();
  host_->ForwardKeyboardEvent(event);
  return Response::OK();
}

Response InputHandler::DispatchMouseEvent(
    const std::string& type,
    int x,
    int y,
    const int* modifiers,
    const double* timestamp,
    const std::string* button,
    const int* click_count) {
  blink::WebMouseEvent event;

  if (!SetMouseEventType(&event, type)) {
    return Response::InvalidParams(
        base::StringPrintf("Unexpected event type '%s'", type.c_str()));
  }
  SetEventModifiers(&event, modifiers);
  SetEventTimestamp(&event, timestamp);
  if (!SetMouseEventButton(&event, button))
    return Response::InvalidParams("Invalid mouse button");

  event.x = x;
  event.y = y;
  event.windowX = x;
  event.windowY = y;
  event.globalX = x;
  event.globalY = y;
  event.clickCount = click_count ? *click_count : 0;

  if (!host_)
    return Response::ServerError("Could not connect to view");

  if (!host_->is_focused())
    host_->Focus();
  host_->ForwardMouseEvent(event);
  return Response::OK();
}

Response InputHandler::EmulateTouchFromMouseEvent(const std::string& type,
                                                  int x,
                                                  int y,
                                                  double timestamp,
                                                  const std::string& button,
                                                  double* delta_x,
                                                  double* delta_y,
                                                  int* modifiers,
                                                  int* click_count) {
  blink::WebMouseWheelEvent wheel_event;
  blink::WebMouseEvent mouse_event;
  blink::WebMouseEvent* event = &mouse_event;

  if (type == emulate_touch_from_mouse_event::kTypeMouseWheel) {
    if (!delta_x || !delta_y) {
      return Response::InvalidParams(
          "'deltaX' and 'deltaY' are expected for mouseWheel event");
    }
    wheel_event.deltaX = static_cast<float>(*delta_x);
    wheel_event.deltaY = static_cast<float>(*delta_y);
    event = &wheel_event;
    event->type = blink::WebInputEvent::MouseWheel;
  } else if (!SetMouseEventType(event, type)) {
    return Response::InvalidParams(
        base::StringPrintf("Unexpected event type '%s'", type.c_str()));
  }

  SetEventModifiers(event, modifiers);
  SetEventTimestamp(event, &timestamp);
  if (!SetMouseEventButton(event, &button))
    return Response::InvalidParams("Invalid mouse button");

  event->x = x;
  event->y = y;
  event->windowX = x;
  event->windowY = y;
  event->globalX = x;
  event->globalY = y;
  event->clickCount = click_count ? *click_count : 0;

  if (!host_)
    return Response::ServerError("Could not connect to view");

  if (event->type == blink::WebInputEvent::MouseWheel)
    host_->ForwardWheelEvent(wheel_event);
  else
    host_->ForwardMouseEvent(mouse_event);
  return Response::OK();
}

Response InputHandler::SynthesizePinchGesture(
    DevToolsCommandId command_id,
    int x,
    int y,
    double scale_factor,
    const int* relative_speed,
    const std::string* gesture_source_type) {
  return Response::InternalError("Not yet implemented");
}

Response InputHandler::SynthesizeScrollGesture(
    DevToolsCommandId command_id,
    int x,
    int y,
    const int* x_distance,
    const int* y_distance,
    const int* x_overscroll,
    const int* y_overscroll,
    const bool* prevent_fling,
    const int* speed,
    const std::string* gesture_source_type) {
  return Response::InternalError("Not yet implemented");
}

Response InputHandler::SynthesizeTapGesture(
    DevToolsCommandId command_id,
    int x,
    int y,
    const int* duration,
    const int* tap_count,
    const std::string* gesture_source_type) {
  return Response::InternalError("Not yet implemented");
}

}  // namespace input
}  // namespace devtools
}  // namespace content
<|endoftext|>


<commit_before>#include "manager.h"
using namespace AhoViewer::Plugin;

#include "config.h"
#include "siteactivatable.h"
#include "windowabstract.h"

#include <algorithm>
#include <glibmm.h>
#include <iostream>

Manager::Manager() : m_Engine{ peas_engine_get_default() }
{
    peas_engine_enable_loader(m_Engine, "python3");
    peas_engine_enable_loader(m_Engine, "lua5.1");

    auto user_plugin_dir{ Glib::build_filename(Glib::get_user_data_dir(), PACKAGE, "plugins") };
    peas_engine_prepend_search_path(m_Engine, user_plugin_dir.c_str(), nullptr);
#ifdef _WIN32
    // Check for plugins inside the plugins dir packaged with the exe
    gchar* g{ g_win32_get_package_installation_directory_of_module(NULL) };
    if (g)
    {
        std::string plugin_path{ Glib::build_filename(g, "plugins") };
        peas_engine_prepend_search_path(m_Engine, plugin.c_str(), nullptr);

        // typelib file should be in the same folder as the exe
        g_irepository_prepend_search_path(g);

        g_free(g);
    }
#else  // !_WIN32
    auto gir_dir{ Glib::build_filename(AHOVIEWER_PREFIX, "lib", "girepository-1.0") };
    g_irepository_prepend_search_path(gir_dir.c_str());
#endif // !_WIN32

    m_WindowExtensionSet =
        peas_extension_set_new(m_Engine, AHOVIEWER_WINDOW_TYPE_ABSTRACT, nullptr);
    m_SiteExtensionSet = peas_extension_set_new(m_Engine, AHOVIEWER_SITE_TYPE_ACTIVATABLE, nullptr);

    peas_engine_rescan_plugins(m_Engine);

    const GList* ps{ peas_engine_get_plugin_list(m_Engine) };

    for (; ps != nullptr; ps = ps->next)
    {
        auto p{ static_cast<PeasPluginInfo*>(ps->data) };

        if (peas_engine_load_plugin(m_Engine, p))
        {
            bool found{ false };

            // Plugins could potentially implement multiple activatable interfaces
            if (peas_engine_provides_extension(m_Engine, p, AHOVIEWER_SITE_TYPE_ACTIVATABLE))
            {
                auto aa{ AHOVIEWER_SITE_ACTIVATABLE(
                    peas_extension_set_get_extension(m_SiteExtensionSet, p)) };
                auto plugin{ std::make_shared<SitePlugin>(p, aa) };
                m_SitePlugins.push_back(plugin);
                found = true;
            }

            if (peas_engine_provides_extension(m_Engine, p, AHOVIEWER_WINDOW_TYPE_ABSTRACT))
            {
                auto aa{ AHOVIEWER_WINDOW_ABSTRACT(
                    peas_extension_set_get_extension(m_WindowExtensionSet, p)) };
                m_WindowPlugins.push_back(std::make_unique<WindowPlugin>(p, aa));
                found = true;
            }

            if (!found)
            {
                std::cerr << "Plugin '" << peas_plugin_info_get_name(p)
                          << "' does not implement a known extension" << std::endl;
            }
        }
        else
        {
            std::cerr << "Failed to load plugin " << peas_plugin_info_get_name(p) << std::endl;
        }
    }

    // Sort window plugins alphabetically by their names so they show up in a consistent order in
    // the menu
    std::sort(m_WindowPlugins.begin(), m_WindowPlugins.end(), [](const auto& a, const auto& b) {
        return a->get_name() < b->get_name();
    });
}

Manager::~Manager()
{
    g_object_unref(m_SiteExtensionSet);
    g_object_unref(m_WindowExtensionSet);
    g_object_unref(m_Engine);
}
<commit_msg>plugin/manager: Clear plugin vectors explicitly in destructor<commit_after>#include "manager.h"
using namespace AhoViewer::Plugin;

#include "config.h"
#include "siteactivatable.h"
#include "windowabstract.h"

#include <algorithm>
#include <glibmm.h>
#include <iostream>

Manager::Manager() : m_Engine{ peas_engine_get_default() }
{
    peas_engine_enable_loader(m_Engine, "python3");
    peas_engine_enable_loader(m_Engine, "lua5.1");

    auto user_plugin_dir{ Glib::build_filename(Glib::get_user_data_dir(), PACKAGE, "plugins") };
    peas_engine_prepend_search_path(m_Engine, user_plugin_dir.c_str(), nullptr);
#ifdef _WIN32
    // Check for plugins inside the plugins dir packaged with the exe
    gchar* g{ g_win32_get_package_installation_directory_of_module(NULL) };
    if (g)
    {
        std::string plugin_path{ Glib::build_filename(g, "plugins") };
        peas_engine_prepend_search_path(m_Engine, plugin.c_str(), nullptr);

        // typelib file should be in the same folder as the exe
        g_irepository_prepend_search_path(g);

        g_free(g);
    }
#else  // !_WIN32
    auto gir_dir{ Glib::build_filename(AHOVIEWER_PREFIX, "lib", "girepository-1.0") };
    g_irepository_prepend_search_path(gir_dir.c_str());
#endif // !_WIN32

    m_WindowExtensionSet =
        peas_extension_set_new(m_Engine, AHOVIEWER_WINDOW_TYPE_ABSTRACT, nullptr);
    m_SiteExtensionSet = peas_extension_set_new(m_Engine, AHOVIEWER_SITE_TYPE_ACTIVATABLE, nullptr);

    peas_engine_rescan_plugins(m_Engine);

    const GList* ps{ peas_engine_get_plugin_list(m_Engine) };

    for (; ps != nullptr; ps = ps->next)
    {
        auto p{ static_cast<PeasPluginInfo*>(ps->data) };

        if (peas_engine_load_plugin(m_Engine, p))
        {
            bool found{ false };

            // Plugins could potentially implement multiple activatable interfaces
            if (peas_engine_provides_extension(m_Engine, p, AHOVIEWER_SITE_TYPE_ACTIVATABLE))
            {
                auto aa{ AHOVIEWER_SITE_ACTIVATABLE(
                    peas_extension_set_get_extension(m_SiteExtensionSet, p)) };
                auto plugin{ std::make_shared<SitePlugin>(p, aa) };
                m_SitePlugins.push_back(plugin);
                found = true;
            }

            if (peas_engine_provides_extension(m_Engine, p, AHOVIEWER_WINDOW_TYPE_ABSTRACT))
            {
                auto aa{ AHOVIEWER_WINDOW_ABSTRACT(
                    peas_extension_set_get_extension(m_WindowExtensionSet, p)) };
                m_WindowPlugins.push_back(std::make_unique<WindowPlugin>(p, aa));
                found = true;
            }

            if (!found)
            {
                std::cerr << "Plugin '" << peas_plugin_info_get_name(p)
                          << "' does not implement a known extension" << std::endl;
            }
        }
        else
        {
            std::cerr << "Failed to load plugin " << peas_plugin_info_get_name(p) << std::endl;
        }
    }

    // Sort window plugins alphabetically by their names so they show up in a consistent order in
    // the menu
    std::sort(m_WindowPlugins.begin(), m_WindowPlugins.end(), [](const auto& a, const auto& b) {
        return a->get_name() < b->get_name();
    });
}

Manager::~Manager()
{
    m_WindowPlugins.clear();
    m_SitePlugins.clear();

    g_object_unref(m_SiteExtensionSet);
    g_object_unref(m_WindowExtensionSet);
    g_object_unref(m_Engine);
}
<|endoftext|>


<commit_before>/*
 * Software License Agreement (BSD License)
 *
 *  Copyright (c) 2011, Willow Garage, Inc.
 *  All rights reserved.
 *
 *  Redistribution and use in source and binary forms, with or without
 *  modification, are permitted provided that the following conditions
 *  are met:
 *
 *   * Redistributions of source code must retain the above copyright
 *     notice, this list of conditions and the following disclaimer.
 *   * Redistributions in binary form must reproduce the above
 *     copyright notice, this list of conditions and the following
 *     disclaimer in the documentation and/or other materials provided
 *     with the distribution.
 *   * Neither the name of Willow Garage, Inc. nor the names of its
 *     contributors may be used to endorse or promote products derived
 *     from this software without specific prior written permission.
 *
 *  THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
 *  "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
 *  LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
 *  FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
 *  COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
 *  INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
 *  BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
 *  LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
 *  CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
 *  LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN
 *  ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
 *  POSSIBILITY OF SUCH DAMAGE.
 *
 * Author: Nico Blodow (blodow@cs.tum.edu)
 *         Radu Bogdan Rusu (rusu@willowgarage.com)
 *         Suat Gedikli (gedikli@willowgarage.com)
 *         Ethan Rublee (rublee@willowgarage.com)
 */

#include <pcl/point_cloud.h>
#include <pcl/point_types.h>
#include <pcl/common/time.h> //fps calculations
#include <pcl/io/openni_grabber.h>
#include <pcl/visualization/boost.h>
#include <pcl/visualization/cloud_viewer.h>
#include <pcl/visualization/image_viewer.h>
#include <pcl/io/openni_camera/openni_driver.h>
#include <pcl/console/parse.h>
#include <pcl/visualization/mouse_event.h>
#include <vtkImageViewer.h>
#include <vtkImageImport.h>
#include <vector>
#include <string>

using namespace std;

#define SHOW_FPS 1
#if SHOW_FPS
#define FPS_CALC(_WHAT_) \
do \
{ \
    static unsigned count = 0;\
    static double last = pcl::getTime ();\
    double now = pcl::getTime (); \
    ++count; \
    if (now - last >= 1.0) \
    { \
      std::cout << "Average framerate("<< _WHAT_ << "): " << double(count)/double(now - last) << " Hz" <<  std::endl; \
      count = 0; \
      last = now; \
    } \
}while(false)
#else
#define FPS_CALC(_WHAT_) \
do \
{ \
}while(false)
#endif

//////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
class SimpleOpenNIViewer
{
  public:
    SimpleOpenNIViewer (pcl::OpenNIGrabber& grabber)
      : grabber_ (grabber),
        image_viewer_ ("PCL/OpenNI RGB image viewer"),
        depth_image_viewer_ ("PCL/OpenNI depth image viewer"),
        image_cld_init_ (false), depth_image_cld_init_ (false)
    {
    }

    void
    image_callback (const boost::shared_ptr<openni_wrapper::Image> &image,
                    const boost::shared_ptr<openni_wrapper::DepthImage> &depth_image, float)
    {
      FPS_CALC ("image callback");
      boost::mutex::scoped_lock lock (image_mutex_);
      image_ = image;
      depth_image_ = depth_image;
    }

    void
    keyboard_callback (const pcl::visualization::KeyboardEvent& event, void* cookie)
    {
      string* message = static_cast<string*> (cookie);
      cout << (*message) << " :: ";
      if (event.getKeyCode ())
        cout << "the key \'" << event.getKeyCode () << "\' (" << event.getKeyCode () << ") was";
      else
        cout << "the special key \'" << event.getKeySym () << "\' was";
      if (event.keyDown ())
        cout << " pressed" << endl;
      else
        cout << " released" << endl;
    }

    void
    mouse_callback (const pcl::visualization::MouseEvent& mouse_event, void* cookie)
    {
      string* message = static_cast<string*> (cookie);
      if (mouse_event.getType () == pcl::visualization::MouseEvent::MouseButtonPress && mouse_event.getButton () == pcl::visualization::MouseEvent::LeftButton)
      {
        cout << (*message) << " :: " << mouse_event.getX () << " , " << mouse_event.getY () << endl;
      }
    }

    void
    run ()
    {
      string mouseMsg2D ("Mouse coordinates in image viewer");
      string keyMsg2D ("Key event for image viewer");

      image_viewer_.registerMouseCallback (&SimpleOpenNIViewer::mouse_callback, *this, static_cast<void*> (&mouseMsg2D));
      image_viewer_.registerKeyboardCallback(&SimpleOpenNIViewer::keyboard_callback, *this, static_cast<void*> (&keyMsg2D));
      depth_image_viewer_.registerMouseCallback (&SimpleOpenNIViewer::mouse_callback, *this, static_cast<void*> (&mouseMsg2D));
      depth_image_viewer_.registerKeyboardCallback(&SimpleOpenNIViewer::keyboard_callback, *this, static_cast<void*> (&keyMsg2D));

      boost::function<void (const boost::shared_ptr<openni_wrapper::Image>&, const boost::shared_ptr<openni_wrapper::DepthImage>&, float) > image_cb = boost::bind (&SimpleOpenNIViewer::image_callback, this, _1, _2, _3);
      boost::signals2::connection image_connection = grabber_.registerCallback (image_cb);

      grabber_.start ();

      unsigned char* rgb_data = 0;
      unsigned rgb_data_size = 0;

      //boost::shared_ptr<openni_wrapper::Image> image;
      //boost::shared_ptr<openni_wrapper::DepthImage> depth_image;
      while (!image_viewer_.wasStopped () && !depth_image_viewer_.wasStopped ())
      {
        if (image_)
        {
          boost::mutex::scoped_lock lock (image_mutex_);
          if (!image_cld_init_)
          {
            image_viewer_.setPosition (0, 0);
            image_cld_init_ = !image_cld_init_;
          }

          if (image_->getEncoding() == openni_wrapper::Image::RGB)
            // Use add instead of show to save a render call
            image_viewer_.addRGBImage (image_->getMetaData ().Data (), image_->getWidth (), image_->getHeight ());
            //image_viewer_.showRGBImage (image_->getMetaData ().Data (), image_->getWidth (), image_->getHeight ());
          else
          {
            if (rgb_data_size < image_->getWidth () * image_->getHeight ())
            {
              if (rgb_data)
                delete [] rgb_data;
              rgb_data_size = image_->getWidth () * image_->getHeight ();
              rgb_data = new unsigned char [rgb_data_size * 3];
            }
            image_->fillRGB (image_->getWidth (), image_->getHeight (), rgb_data);
            // Use add instead of show to save a render call
            image_viewer_.addRGBImage (rgb_data, image_->getWidth (), image_->getHeight ());
            //image_viewer_.showRGBImage (rgb_data, image_->getWidth (), image_->getHeight ());
          }
          image_viewer_.spinOnce ();
        }
        if (depth_image_)
        {
          boost::mutex::scoped_lock lock (image_mutex_);
          if (!depth_image_cld_init_)
          {
            depth_image_viewer_.setPosition (depth_image_->getWidth (), 0);
            depth_image_cld_init_ = !depth_image_cld_init_;
          }

          // Use add instead of show to save a render call
          depth_image_viewer_.addShortImage (reinterpret_cast<const unsigned short*> (depth_image_->getDepthMetaData ().Data ()),
                                             depth_image_->getWidth (), depth_image_->getHeight (),
                                             std::numeric_limits<unsigned short>::min (),
                                             // Scale so that the colors look brigher on screen
                                             std::numeric_limits<unsigned short>::max () / 10,
                                             true);
          //depth_image_viewer_.showShortImage (reinterpret_cast<const unsigned short*> (depth_image_->getDepthMetaData ().Data ()),
          //                                    depth_image_->getWidth (), depth_image_->getHeight (),
          //                                    std::numeric_limits<unsigned short>::min (),
          //                                    // Scale so that the colors look brigher on screen
          //                                    std::numeric_limits<unsigned short>::max () / 10,
          //                                    true);
          depth_image_viewer_.spinOnce ();
        }
        boost::this_thread::sleep (boost::posix_time::microseconds (100));
      }

      grabber_.stop ();

      image_connection.disconnect ();

      if (rgb_data)
        delete[] rgb_data;
    }

    pcl::OpenNIGrabber& grabber_;
    boost::mutex image_mutex_;
    boost::shared_ptr<openni_wrapper::Image> image_;
    boost::shared_ptr<openni_wrapper::DepthImage> depth_image_;
    pcl::visualization::ImageViewer image_viewer_;
    pcl::visualization::ImageViewer depth_image_viewer_;
    bool image_cld_init_, depth_image_cld_init_;
};

void
usage (char ** argv)
{
  cout << "usage: " << argv[0] << " [((<device_id> | <path-to-oni-file>) [-imagemode <mode>] | -l [<device_id>]| -h | --help)]" << endl;
  cout << argv[0] << " -h | --help : shows this help" << endl;
  cout << argv[0] << " -l : list all available devices" << endl;
  cout << argv[0] << " -l <device-id> : list all available modes for specified device" << endl;

  cout << "                 device_id may be #1, #2, ... for the first, second etc device in the list"
#ifndef _WIN32
       << " or" << endl
       << "                 bus@address for the device connected to a specific usb-bus / address combination or" << endl
       << "                 <serial-number>"
#endif
       << endl;
  cout << endl;
  cout << "examples:" << endl;
  cout << argv[0] << " \"#1\"" << endl;
  cout << "    uses the first device." << endl;
  cout << argv[0] << " \"./temp/test.oni\"" << endl;
  cout << "    uses the oni-player device to play back oni file given by path." << endl;
  cout << argv[0] << " -l" << endl;
  cout << "    lists all available devices." << endl;
  cout << argv[0] << " -l \"#2\"" << endl;
  cout << "    lists all available modes for the second device" << endl;
#ifndef _WIN32
  cout << argv[0] << " A00361800903049A" << endl;
  cout << "    uses the device with the serial number \'A00361800903049A\'." << endl;
  cout << argv[0] << " 1@16" << endl;
  cout << "    uses the device on address 16 at USB bus 1." << endl;
#endif
}

int
main (int argc, char ** argv)
{
  std::string device_id ("");
  pcl::OpenNIGrabber::Mode image_mode = pcl::OpenNIGrabber::OpenNI_Default_Mode;

  if (argc >= 2)
  {
    device_id = argv[1];
    if (device_id == "--help" || device_id == "-h")
    {
      usage (argv);
      return (0);
    }
    else if (device_id == "-l")
    {
      if (argc >= 3)
      {
        pcl::OpenNIGrabber grabber (argv[2]);
        boost::shared_ptr<openni_wrapper::OpenNIDevice> device = grabber.getDevice ();
        std::vector<std::pair<int, XnMapOutputMode> > modes;

        if (device->hasImageStream ())
        {
          cout << endl << "Supported image modes for device: " << device->getVendorName () << " , " << device->getProductName () << endl;
          modes = grabber.getAvailableImageModes ();
          for (std::vector<std::pair<int, XnMapOutputMode> >::const_iterator it = modes.begin (); it != modes.end (); ++it)
          {
            cout << it->first << " = " << it->second.nXRes << " x " << it->second.nYRes << " @ " << it->second.nFPS << endl;
          }
        }
      }
      else
      {
        openni_wrapper::OpenNIDriver& driver = openni_wrapper::OpenNIDriver::getInstance ();
        if (driver.getNumberDevices () > 0)
        {
          for (unsigned deviceIdx = 0; deviceIdx < driver.getNumberDevices (); ++deviceIdx)
          {
            cout << "Device: " << deviceIdx + 1 << ", vendor: " << driver.getVendorName (deviceIdx) << ", product: " << driver.getProductName (deviceIdx)
              << ", connected: " << driver.getBus (deviceIdx) << " @ " << driver.getAddress (deviceIdx) << ", serial number: \'" << driver.getSerialNumber (deviceIdx) << "\'" << endl;
          }

        }
        else
          cout << "No devices connected." << endl;

        cout <<"Virtual Devices available: ONI player" << endl;
      }
      return (0);
    }
  }
  else
  {
    openni_wrapper::OpenNIDriver& driver = openni_wrapper::OpenNIDriver::getInstance ();
    if (driver.getNumberDevices() > 0)
      cout << "Device Id not set, using first device." << endl;
  }

  unsigned mode;
  if (pcl::console::parse (argc, argv, "-imagemode", mode) != -1)
    image_mode = static_cast<pcl::OpenNIGrabber::Mode> (mode);

  pcl::OpenNIGrabber grabber (device_id, pcl::OpenNIGrabber::OpenNI_Default_Mode, image_mode);
  SimpleOpenNIViewer v (grabber);
  v.run ();

  return (0);
}
<commit_msg>improved version<commit_after>/*
 * Software License Agreement (BSD License)
 *
 *  Point Cloud Library (PCL) - www.pointclouds.org
 *  Copyright (c) 2011, Willow Garage, Inc.
 *  Copyright (c) 2012-, Open Perception, Inc.
 *
 *  All rights reserved.
 *
 *  Redistribution and use in source and binary forms, with or without
 *  modification, are permitted provided that the following conditions
 *  are met:
 *
 *   * Redistributions of source code must retain the above copyright
 *     notice, this list of conditions and the following disclaimer.
 *   * Redistributions in binary form must reproduce the above
 *     copyright notice, this list of conditions and the following
 *     disclaimer in the documentation and/or other materials provided
 *     with the distribution.
 *   * Neither the name of Willow Garage, Inc. nor the names of its
 *     contributors may be used to endorse or promote products derived
 *     from this software without specific prior written permission.
 *
 *  THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
 *  "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
 *  LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
 *  FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
 *  COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
 *  INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
 *  BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
 *  LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
 *  CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
 *  LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN
 *  ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
 *  POSSIBILITY OF SUCH DAMAGE.
 *
 */

#include <pcl/point_cloud.h>
#include <pcl/point_types.h>
#include <pcl/common/time.h> //fps calculations
#include <pcl/io/openni_grabber.h>
#include <pcl/visualization/boost.h>
#include <pcl/visualization/common/float_image_utils.h>
#include <pcl/visualization/cloud_viewer.h>
#include <pcl/visualization/image_viewer.h>
#include <pcl/io/openni_camera/openni_driver.h>
#include <pcl/console/parse.h>
#include <pcl/visualization/mouse_event.h>

using namespace std;

#define SHOW_FPS 1
#if SHOW_FPS
#define FPS_CALC(_WHAT_) \
do \
{ \
    static unsigned count = 0;\
    static double last = pcl::getTime ();\
    double now = pcl::getTime (); \
    ++count; \
    if (now - last >= 1.0) \
    { \
      std::cout << "Average framerate("<< _WHAT_ << "): " << double(count)/double(now - last) << " Hz" <<  std::endl; \
      count = 0; \
      last = now; \
    } \
}while(false)
#else
#define FPS_CALC(_WHAT_) \
do \
{ \
}while(false)
#endif

//////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
class SimpleOpenNIViewer
{
  public:
    SimpleOpenNIViewer (pcl::OpenNIGrabber& grabber)
      : grabber_ (grabber),
        image_viewer_ ("PCL/OpenNI RGB image viewer"),
        depth_image_viewer_ ("PCL/OpenNI depth image viewer"),
        image_cld_init_ (false), depth_image_cld_init_ (false),
        rgb_data_ (0), depth_data_ (0), rgb_data_size_ (0)
    {
    }

    void
    image_callback (const boost::shared_ptr<openni_wrapper::Image> &image,
                    const boost::shared_ptr<openni_wrapper::DepthImage> &depth_image, float)
    {
      FPS_CALC ("image callback");
      boost::mutex::scoped_lock lock (image_mutex_);

      // Copy data
      image_ = image;
      if (image->getEncoding() != openni_wrapper::Image::RGB)
      {
        if (rgb_data_size_ < image->getWidth () * image->getHeight ())
        {
          if (rgb_data_)
            delete [] rgb_data_;
          rgb_data_size_ = image->getWidth () * image->getHeight ();
          rgb_data_ = new unsigned char [rgb_data_size_ * 3];
        }
        image_->fillRGB (image_->getWidth (), image_->getHeight (), rgb_data_);
      }

      // Copy data
      depth_image_ = depth_image;
      if (depth_data_)
        delete[] depth_data_;
      depth_data_ = pcl::visualization::FloatImageUtils::getVisualImage (
          reinterpret_cast<const unsigned short*> (depth_image->getDepthMetaData ().Data ()),
            depth_image->getWidth (), depth_image->getHeight (),
            std::numeric_limits<unsigned short>::min (),
            // Scale so that the colors look brigher on screen
            std::numeric_limits<unsigned short>::max () / 10,
            true);
    }

    void
    keyboard_callback (const pcl::visualization::KeyboardEvent& event, void* cookie)
    {
      string* message = static_cast<string*> (cookie);
      cout << (*message) << " :: ";
      if (event.getKeyCode ())
        cout << "the key \'" << event.getKeyCode () << "\' (" << event.getKeyCode () << ") was";
      else
        cout << "the special key \'" << event.getKeySym () << "\' was";
      if (event.keyDown ())
        cout << " pressed" << endl;
      else
        cout << " released" << endl;
    }

    void
    mouse_callback (const pcl::visualization::MouseEvent& mouse_event, void* cookie)
    {
      string* message = static_cast<string*> (cookie);
      if (mouse_event.getType () == pcl::visualization::MouseEvent::MouseButtonPress && mouse_event.getButton () == pcl::visualization::MouseEvent::LeftButton)
      {
        cout << (*message) << " :: " << mouse_event.getX () << " , " << mouse_event.getY () << endl;
      }
    }

    void
    run ()
    {
      string mouseMsg2D ("Mouse coordinates in image viewer");
      string keyMsg2D ("Key event for image viewer");

      image_viewer_.registerMouseCallback (&SimpleOpenNIViewer::mouse_callback, *this, static_cast<void*> (&mouseMsg2D));
      image_viewer_.registerKeyboardCallback(&SimpleOpenNIViewer::keyboard_callback, *this, static_cast<void*> (&keyMsg2D));
      depth_image_viewer_.registerMouseCallback (&SimpleOpenNIViewer::mouse_callback, *this, static_cast<void*> (&mouseMsg2D));
      depth_image_viewer_.registerKeyboardCallback(&SimpleOpenNIViewer::keyboard_callback, *this, static_cast<void*> (&keyMsg2D));

      boost::function<void (const boost::shared_ptr<openni_wrapper::Image>&, const boost::shared_ptr<openni_wrapper::DepthImage>&, float) > image_cb = boost::bind (&SimpleOpenNIViewer::image_callback, this, _1, _2, _3);
      boost::signals2::connection image_connection = grabber_.registerCallback (image_cb);

      grabber_.start ();

      boost::shared_ptr<openni_wrapper::Image> image;
      boost::shared_ptr<openni_wrapper::DepthImage> depth_image;
      while (!image_viewer_.wasStopped () && !depth_image_viewer_.wasStopped ())
      {
        if (!image_cld_init_)
        {
          image_viewer_.setPosition (0, 0);
          image_cld_init_ = !image_cld_init_;
        }

        if (image_mutex_.try_lock ())
        {
          // Swap data
          if (image_)
            image_.swap (image);

          if (depth_image_)
            depth_image_.swap (depth_image);

          // Unlock
          image_mutex_.unlock ();

          // Add to renderer
          if (image)
          {
            if (image->getEncoding() == openni_wrapper::Image::RGB)
              image_viewer_.addRGBImage (image->getMetaData ().Data (), image->getWidth (), image->getHeight ());
            else
              image_viewer_.addRGBImage (rgb_data_, image->getWidth (), image->getHeight ());
          }

          if (depth_image)
          {
            depth_image_viewer_.addRGBImage (depth_data_, depth_image->getWidth (), depth_image->getHeight ());
            if (!depth_image_cld_init_)
            {
              depth_image_viewer_.setPosition (depth_image->getWidth (), 0);
              depth_image_cld_init_ = !depth_image_cld_init_;
            }
          }
        }
        image_viewer_.spinOnce ();
        depth_image_viewer_.spinOnce ();

        boost::this_thread::sleep (boost::posix_time::microseconds (100));
      }

      grabber_.stop ();

      image_connection.disconnect ();

      if (rgb_data_)
        delete[] rgb_data_;
      if (depth_data_)
        delete[] depth_data_;
    }

    pcl::OpenNIGrabber& grabber_;
    boost::mutex image_mutex_;
    boost::shared_ptr<openni_wrapper::Image> image_;
    boost::shared_ptr<openni_wrapper::DepthImage> depth_image_;
    pcl::visualization::ImageViewer image_viewer_;
    pcl::visualization::ImageViewer depth_image_viewer_;
    bool image_cld_init_, depth_image_cld_init_;
    unsigned char* rgb_data_, *depth_data_;
    unsigned rgb_data_size_;
};

void
usage (char ** argv)
{
  cout << "usage: " << argv[0] << " [((<device_id> | <path-to-oni-file>) [-imagemode <mode>] | -l [<device_id>]| -h | --help)]" << endl;
  cout << argv[0] << " -h | --help : shows this help" << endl;
  cout << argv[0] << " -l : list all available devices" << endl;
  cout << argv[0] << " -l <device-id> : list all available modes for specified device" << endl;

  cout << "                 device_id may be #1, #2, ... for the first, second etc device in the list"
#ifndef _WIN32
       << " or" << endl
       << "                 bus@address for the device connected to a specific usb-bus / address combination or" << endl
       << "                 <serial-number>"
#endif
       << endl;
  cout << endl;
  cout << "examples:" << endl;
  cout << argv[0] << " \"#1\"" << endl;
  cout << "    uses the first device." << endl;
  cout << argv[0] << " \"./temp/test.oni\"" << endl;
  cout << "    uses the oni-player device to play back oni file given by path." << endl;
  cout << argv[0] << " -l" << endl;
  cout << "    lists all available devices." << endl;
  cout << argv[0] << " -l \"#2\"" << endl;
  cout << "    lists all available modes for the second device" << endl;
#ifndef _WIN32
  cout << argv[0] << " A00361800903049A" << endl;
  cout << "    uses the device with the serial number \'A00361800903049A\'." << endl;
  cout << argv[0] << " 1@16" << endl;
  cout << "    uses the device on address 16 at USB bus 1." << endl;
#endif
}

int
main (int argc, char ** argv)
{
  std::string device_id ("");
  pcl::OpenNIGrabber::Mode image_mode = pcl::OpenNIGrabber::OpenNI_Default_Mode;

  if (argc >= 2)
  {
    device_id = argv[1];
    if (device_id == "--help" || device_id == "-h")
    {
      usage (argv);
      return (0);
    }
    else if (device_id == "-l")
    {
      if (argc >= 3)
      {
        pcl::OpenNIGrabber grabber (argv[2]);
        boost::shared_ptr<openni_wrapper::OpenNIDevice> device = grabber.getDevice ();
        std::vector<std::pair<int, XnMapOutputMode> > modes;

        if (device->hasImageStream ())
        {
          cout << endl << "Supported image modes for device: " << device->getVendorName () << " , " << device->getProductName () << endl;
          modes = grabber.getAvailableImageModes ();
          for (std::vector<std::pair<int, XnMapOutputMode> >::const_iterator it = modes.begin (); it != modes.end (); ++it)
          {
            cout << it->first << " = " << it->second.nXRes << " x " << it->second.nYRes << " @ " << it->second.nFPS << endl;
          }
        }
      }
      else
      {
        openni_wrapper::OpenNIDriver& driver = openni_wrapper::OpenNIDriver::getInstance ();
        if (driver.getNumberDevices () > 0)
        {
          for (unsigned deviceIdx = 0; deviceIdx < driver.getNumberDevices (); ++deviceIdx)
          {
            cout << "Device: " << deviceIdx + 1 << ", vendor: " << driver.getVendorName (deviceIdx) << ", product: " << driver.getProductName (deviceIdx)
              << ", connected: " << driver.getBus (deviceIdx) << " @ " << driver.getAddress (deviceIdx) << ", serial number: \'" << driver.getSerialNumber (deviceIdx) << "\'" << endl;
          }

        }
        else
          cout << "No devices connected." << endl;

        cout <<"Virtual Devices available: ONI player" << endl;
      }
      return (0);
    }
  }
  else
  {
    openni_wrapper::OpenNIDriver& driver = openni_wrapper::OpenNIDriver::getInstance ();
    if (driver.getNumberDevices() > 0)
      cout << "Device Id not set, using first device." << endl;
  }

  unsigned mode;
  if (pcl::console::parse (argc, argv, "-imagemode", mode) != -1)
    image_mode = static_cast<pcl::OpenNIGrabber::Mode> (mode);

  pcl::OpenNIGrabber grabber (device_id, pcl::OpenNIGrabber::OpenNI_Default_Mode, image_mode);
  SimpleOpenNIViewer v (grabber);
  v.run ();

  return (0);
}
<|endoftext|>


<commit_before>#include "BasicBlock.h"
#include "MipsCodeGen.h"
#include "MemStream.h"
#include "offsetof_def.h"

using namespace Framework;

CBasicBlock::CBasicBlock(CMIPS& context, uint32 begin, uint32 end) :
m_begin(begin),
m_end(end),
m_context(context),
m_text(NULL)
{
    assert(m_end >= m_begin);
}

CBasicBlock::~CBasicBlock()
{
    if(m_text != NULL)
    {
        delete [] m_text;
    }
}

void CBasicBlock::Compile()
{
    CMemStream stream;
    {
        CMipsCodeGen codeGen;

        for(unsigned int i = 0; i < 4; i++)
        {
            codeGen.SetVariableAsConstant(
                offsetof(CMIPS, m_State.nGPR[CMIPS::R0].nV[i]),
                0
                );
        }
        codeGen.SetStream(&stream);
        codeGen.Begin(NULL);
        for(uint32 address = m_begin; address <= m_end; address += 4)
        {
            m_context.m_pArch->CompileInstruction(
                address,
                reinterpret_cast<CCacheBlock*>(&codeGen),
                &m_context,
                true);
            //Sanity check
            assert(codeGen.IsStackEmpty());
        }
        codeGen.DumpVariables(0);
        codeGen.m_Assembler.Ret();
        codeGen.End();
    }

    //Save text
    m_text = new uint8[stream.GetSize()];
    memcpy(m_text, stream.GetBuffer(), stream.GetSize());
}

unsigned int CBasicBlock::Execute()
{
    volatile void* function = m_text;
    volatile CMIPS* context = &m_context;

    __asm
    {
#ifdef MACOSX
		pusha
#endif

        mov     eax, function
		mov		ebp, context
        call    eax

#ifdef MACOSX
		popa
#endif
    }

//	asm("pushl %%ebx\n\t"
//		"movl %%edi, %%eax\n\t"
//		"movl %%ecx, %%ebp\n\t"
//		"pushl %%eax\n\t"
//		"call (%%esp)\n\t"
//		"popl %%eax\n\t"
//		"popl %%ebx\n\t"
//		:
//		: "D" (function), "c" (context)
//		: "%ebp", "%esi");

    if((m_context.m_State.nGPR[CMIPS::RA].nV0 & 3) != 0)
    {
        assert(0);
    }

    if(m_context.m_State.nDelayedJumpAddr != MIPS_INVALID_PC)
    {
        m_context.m_State.nPC = m_context.m_State.nDelayedJumpAddr;
        m_context.m_State.nDelayedJumpAddr = MIPS_INVALID_PC;
    }
    else
    {
        m_context.m_State.nPC = m_end + 4;
    }

    return ((m_end - m_begin) / 4) + 1;
}

uint32 CBasicBlock::GetBeginAddress() const
{
    return m_begin;
}

uint32 CBasicBlock::GetEndAddress() const
{
    return m_end;
}

bool CBasicBlock::IsCompiled() const
{
    return m_text != NULL;
}
<commit_msg>Another attempt to fix inline assembly portability.<commit_after>#include "BasicBlock.h"
#include "MipsCodeGen.h"
#include "MemStream.h"
#include "offsetof_def.h"

using namespace Framework;

CBasicBlock::CBasicBlock(CMIPS& context, uint32 begin, uint32 end) :
m_begin(begin),
m_end(end),
m_context(context),
m_text(NULL)
{
    assert(m_end >= m_begin);
}

CBasicBlock::~CBasicBlock()
{
    if(m_text != NULL)
    {
        delete [] m_text;
    }
}

void CBasicBlock::Compile()
{
    CMemStream stream;
    {
        CMipsCodeGen codeGen;

        for(unsigned int i = 0; i < 4; i++)
        {
            codeGen.SetVariableAsConstant(
                offsetof(CMIPS, m_State.nGPR[CMIPS::R0].nV[i]),
                0
                );
        }
        codeGen.SetStream(&stream);
        codeGen.Begin(NULL);
        for(uint32 address = m_begin; address <= m_end; address += 4)
        {
            m_context.m_pArch->CompileInstruction(
                address,
                reinterpret_cast<CCacheBlock*>(&codeGen),
                &m_context,
                true);
            //Sanity check
            assert(codeGen.IsStackEmpty());
        }
        codeGen.DumpVariables(0);
        codeGen.m_Assembler.Ret();
        codeGen.End();
    }

    //Save text
    m_text = new uint8[stream.GetSize()];
    memcpy(m_text, stream.GetBuffer(), stream.GetSize());
}

unsigned int CBasicBlock::Execute()
{
    volatile void* function = m_text;
    volatile CMIPS* context = &m_context;

    //Should change pre-proc definitions used here (MACOSX to GCC?)
    __asm
    {
#if defined(MACOSX)
		pusha
#elif defined(_MSVC)
        pushad
#endif

        mov     eax, function
		mov		ebp, context
        call    eax

#if defined(MACOSX)
		popa
#elif defined(_MSVC)
        popad
#endif
    }

//	asm("pushl %%ebx\n\t"
//		"movl %%edi, %%eax\n\t"
//		"movl %%ecx, %%ebp\n\t"
//		"pushl %%eax\n\t"
//		"call (%%esp)\n\t"
//		"popl %%eax\n\t"
//		"popl %%ebx\n\t"
//		:
//		: "D" (function), "c" (context)
//		: "%ebp", "%esi");

    if((m_context.m_State.nGPR[CMIPS::RA].nV0 & 3) != 0)
    {
        assert(0);
    }

    if(m_context.m_State.nDelayedJumpAddr != MIPS_INVALID_PC)
    {
        m_context.m_State.nPC = m_context.m_State.nDelayedJumpAddr;
        m_context.m_State.nDelayedJumpAddr = MIPS_INVALID_PC;
    }
    else
    {
        m_context.m_State.nPC = m_end + 4;
    }

    return ((m_end - m_begin) / 4) + 1;
}

uint32 CBasicBlock::GetBeginAddress() const
{
    return m_begin;
}

uint32 CBasicBlock::GetEndAddress() const
{
    return m_end;
}

bool CBasicBlock::IsCompiled() const
{
    return m_text != NULL;
}
<|endoftext|>


<commit_before><commit_msg>Make multiplication usable with more types<commit_after><|endoftext|>


<commit_before>#ifndef LINKEDLIST_HPP
#define LINKEDLIST_HPP

#include <iostream>

template <class Type>
class LinkedList {
public:
	LinkedList( );

	LinkedList(const LinkedList& rhs);

	~LinkedList( );

	void appendToHead(Type* data);

	void append(Type* data);

	void appendAtIndex(Type* data, int index);

	Type* dataAtHead( ) const;

	Type* dataAtTail( ) const;

	Type* dataAtIndex(int index) const;

	void insert(Type* data);

	int getSize( ) const;

	bool remove(Type data);

	LinkedList& operator=(const LinkedList& rhs);

	friend std::ostream& operator<<(std::ostream& output, const LinkedList<Type>& currentList) {
		if (currentList.size == 0) {
			output << "The list is empty.\n";
		}
		Node* current = currentList.head;
		while (current != nullptr) {
			output << *current->data << "\n";
			current = current->next;
		}
		return output;
	}

private:
	struct Node {
		Type* data;
		Node* next;

		Node(Type* data);
		Node(Type* data, Node* next);
	};

	Node* head;
	Node* tail;
	int size;
};

template <class Type>
LinkedList<Type>::Node::Node(Type* data) : data(data), next(nullptr) { }

template <class Type>
LinkedList<Type>::Node::Node(Type* data, Node* next) : data(data), next(next) { }

template <class Type>
LinkedList<Type>::LinkedList( ) : head(nullptr), tail(nullptr), size(0) { }

template <class Type>
LinkedList<Type>::LinkedList(const LinkedList& rhs) : head(nullptr), tail(nullptr), size(0) {
	if (rhs.head != nullptr) {
		head = new Node (rhs.head->data);
		++size;
		Node* current = head;
		Node* rhsCurrent = rhs.head->next;
		while (rhsCurrent != nullptr) {
			current->next = new Node (*rhsCurrent->data);
			++size;
			current = current->next;
			rhsCurrent = rhsCurrent->next;
		}
		tail = current;
	}
}

template <class Type>
LinkedList<Type>::~LinkedList( ) {
	while (head != nullptr) {
		Node* tempNext = head->next;
		delete head;
		head = tempNext;
	}
	head = nullptr;
	tail = nullptr;
}

template <class Type>
void LinkedList<Type>::appendToHead(Type* data) {
	head = new Node(data, head);
	if (size == 0) {
		tail = head;
	}
	size++;
}

template <class Type>
void LinkedList<Type>::append(Type* data) {
	if (size != 0) {
		tail->next = new Node(data);
		tail = tail->next;
		++size;
	} else {
		appendToHead (data);
	}
}

template <class Type>
void LinkedList<Type>::appendAtIndex(Type* data, int index) {
	if (index < 0 || index > size) {
		return;
	}
	if (index == 0) {
		appendAtHead (data);
		return;
	}
	if (index == size - 1) {
		append (data);
		return;
	}
	Node* current = head;
	for (int i = 0; i < index; ++i) {
		current = current->next;
	}
	current->next = new Node(data, current->next);
	++size;
}

template <class Type>
Type* LinkedList<Type>::dataAtHead( ) const {
	if(head != nullptr) {
		return head->data;
	}
	return nullptr;
}

template <class Type>
Type* LinkedList<Type>::dataAtTail( ) const {
	if (tail != nullptr) {
		return tail->data;
	}
	return nullptr;
}

template <class Type>
Type* LinkedList<Type>::dataAtIndex(int index) const {
	if (index >= 0 || index < size) {
		if (index == 0) { return head->data; }
		if (index == size - 1) { return tail->data; }

		Node* current = head;
		for (int i = 0; i < index; ++i) {
			current = current->next;
		}
		return current->data;
	} else {
		return nullptr;
	}
}

template <class Type>
void LinkedList<Type>::insert(Type* data) {
	if (head == nullptr) {
		head = new Node(data);
		tail = head;
	} else if (*data <= *head->data) {
		head = new Node(data, head);
	} else {
		Node* previous = head;
		Node* current = head->next;
		while (current != nullptr && *data > *current->data) {
			previous = current;
			current = current->next;
		}
		previous->next = new Node(data, current);
		if (previous == tail) {
			tail = previous->next;
		}
	}
	++size;
}

template <class Type>
int LinkedList<Type>::getSize( ) const {
	return size;
}

template <class Type>
bool LinkedList<Type>::remove(Type data) {
	if (head == nullptr) {
		return false;
	}
	Node* previous = nullptr;
	Node* current = head;
	while (current != nullptr && data != *current->data) {
		previous = current;
		current = current->next;
	}
	if (current == nullptr) { return false; }	// If current is null, the parameter pass was not found.
	if (current == head) { head = head->next; } // Update the head if node found is at the head.
	if (current == tail) { tail = previous; }	// Update the tail if the node found is at the tail.
	if (previous != nullptr) {
		previous->next = current->next;			// Update the previous nodes next.
	}
	delete current;								// Delete the node found.
	--size;
	return true;
}

template <class Type>
LinkedList<Type>& LinkedList<Type>::operator=(const LinkedList& rhs) {
	if (this != &rhs) {
		while (head != nullptr) {
			Node* temp = head->next;
			delete head;
			head = temp;
		}

		head = nullptr;
		tail = nullptr;
		size = 0;
		if (rhs.head != nullptr) {
			head = new Node (rhs.head->data);
			++size;
			Node* current = head;
			Node* rhsCurrent = rhs.head->next;
			while (rhsCurrent != nullptr) {
				current->next = new Node (*rhsCurrent->data);
				++size;
				current = current->next;
				rhsCurrent = rhsCurrent->next;
			}
			tail = current;
		}
	}
	return *this;
}
#endif //LINKEDLIST_HPP<commit_msg>Standardizes the type used by Linkedlist as intended originally<commit_after>#ifndef LINKEDLIST_HPP
#define LINKEDLIST_HPP

#include <iostream>

template <class Type>
class LinkedList {
public:
	LinkedList( );

	LinkedList(const LinkedList& rhs);

	~LinkedList( );

	void appendToHead(Type data);

	void append(Type data);

	void appendAtIndex(Type data, int index);

	Type dataAtHead( ) const;

	Type dataAtTail( ) const;

	Type dataAtIndex(int index) const;

	void insert(Type data);

	int getSize( ) const;

	bool remove(Type data);

	LinkedList& operator=(const LinkedList& rhs);

	friend std::ostream& operator<<(std::ostream& output, const LinkedList<Type>& currentList) {
		if (currentList.size == 0) {
			output << "The list is empty.\n";
		}
		Node* current = currentList.head;
		while (current != nullptr) {
			output << *current->data << "\n";
			current = current->next;
		}
		return output;
	}

private:
	struct Node {
		Type data;
		Node* next;

		Node(Type data);
		Node(Type data, Node* next);
	};

	Node* head;
	Node* tail;
	int size;
};

template <class Type>
LinkedList<Type>::Node::Node(Type data) : data(data), next(nullptr) { }

template <class Type>
LinkedList<Type>::Node::Node(Type data, Node* next) : data(data), next(next) { }

template <class Type>
LinkedList<Type>::LinkedList( ) : head(nullptr), tail(nullptr), size(0) { }

template <class Type>
LinkedList<Type>::LinkedList(const LinkedList& rhs) : head(nullptr), tail(nullptr), size(0) {
	if (rhs.head != nullptr) {
		head = new Node (rhs.head->data);
		++size;
		Node* current = head;
		Node* rhsCurrent = rhs.head->next;
		while (rhsCurrent != nullptr) {
			current->next = new Node (*rhsCurrent->data);
			++size;
			current = current->next;
			rhsCurrent = rhsCurrent->next;
		}
		tail = current;
	}
}

template <class Type>
LinkedList<Type>::~LinkedList( ) {
	while (head != nullptr) {
		Node* tempNext = head->next;
		delete head;
		head = tempNext;
	}
	head = nullptr;
	tail = nullptr;
}

template <class Type>
void LinkedList<Type>::appendToHead(Type data) {
	head = new Node(data, head);
	if (size == 0) {
		tail = head;
	}
	size++;
}

template <class Type>
void LinkedList<Type>::append(Type data) {
	if (size != 0) {
		tail->next = new Node(data);
		tail = tail->next;
		++size;
	} else {
		appendToHead (data);
	}
}

template <class Type>
void LinkedList<Type>::appendAtIndex(Type data, int index) {
	if (index < 0 || index > size) {
		return;
	}
	if (index == 0) {
		appendAtHead (data);
		return;
	}
	if (index == size - 1) {
		append (data);
		return;
	}
	Node* current = head;
	for (int i = 0; i < index; ++i) {
		current = current->next;
	}
	current->next = new Node(data, current->next);
	++size;
}

template <class Type>
Type LinkedList<Type>::dataAtHead( ) const {
	if(head != nullptr) {
		return head->data;
	}
	return nullptr;
}

template <class Type>
Type LinkedList<Type>::dataAtTail( ) const {
	if (tail != nullptr) {
		return tail->data;
	}
	return nullptr;
}

template <class Type>
Type LinkedList<Type>::dataAtIndex(int index) const {
	if (index >= 0 || index < size) {
		if (index == 0) { return head->data; }
		if (index == size - 1) { return tail->data; }

		Node* current = head;
		for (int i = 0; i < index; ++i) {
			current = current->next;
		}
		return current->data;
	} else {
		return nullptr;
	}
}

template <class Type>
void LinkedList<Type>::insert(Type data) {
	if (head == nullptr) {
		head = new Node(data);
		tail = head;
	} else if (*data <= *head->data) {
		head = new Node(data, head);
	} else {
		Node* previous = head;
		Node* current = head->next;
		while (current != nullptr && *data > *current->data) {
			previous = current;
			current = current->next;
		}
		previous->next = new Node(data, current);
		if (previous == tail) {
			tail = previous->next;
		}
	}
	++size;
}

template <class Type>
int LinkedList<Type>::getSize( ) const {
	return size;
}

template <class Type>
bool LinkedList<Type>::remove(Type data) {
	if (head == nullptr) {
		return false;
	}
	Node* previous = nullptr;
	Node* current = head;
	while (current != nullptr && data != *current->data) {
		previous = current;
		current = current->next;
	}
	if (current == nullptr) { return false; }	// If current is null, the parameter pass was not found.
	if (current == head) { head = head->next; } // Update the head if node found is at the head.
	if (current == tail) { tail = previous; }	// Update the tail if the node found is at the tail.
	if (previous != nullptr) {
		previous->next = current->next;			// Update the previous nodes next.
	}
	delete current;								// Delete the node found.
	--size;
	return true;
}

template <class Type>
LinkedList<Type>& LinkedList<Type>::operator=(const LinkedList& rhs) {
	if (this != &rhs) {
		while (head != nullptr) {
			Node* temp = head->next;
			delete head;
			head = temp;
		}

		head = nullptr;
		tail = nullptr;
		size = 0;
		if (rhs.head != nullptr) {
			head = new Node (rhs.head->data);
			++size;
			Node* current = head;
			Node* rhsCurrent = rhs.head->next;
			while (rhsCurrent != nullptr) {
				current->next = new Node (*rhsCurrent->data);
				++size;
				current = current->next;
				rhsCurrent = rhsCurrent->next;
			}
			tail = current;
		}
	}
	return *this;
}
#endif //LINKEDLIST_HPP<|endoftext|>


<commit_before>// Copyright Sergey Anisimov 2016-2017
// MIT License
//
// Gluino
// https://github.com/anisimovsergey/gluino

#ifndef SERIALIZATION_LIST_SERIALIZER_HPP
#define SERIALIZATION_LIST_SERIALIZER_HPP

#include "Core/List.hpp"
#include "Serializer.hpp"

namespace Serialization {

template<typename T>
class ListSerializer : public Serializer<T> {
  protected:
    // From Serializer
    virtual Core::Status
      serializeImpl(ISerializationContext& context, const T& list) const override {

      auto result = context.setEntity("elements", list);
      if (!result.isOk())
        return result;

      return Core::Status::OK;
    }

    virtual std::tuple<Core::Status, std::unique_ptr<T>>
    deserializeImpl(const IDeserializationContext& context) const override {
       return std::make_tuple(Core::Status::NotImplemented, nullptr);
    }
};

}

#endif /* end of include guard: SERIALIZATION_LIST_SERIALIZER_HPP */
<commit_msg>A warning fix<commit_after>// Copyright Sergey Anisimov 2016-2017
// MIT License
//
// Gluino
// https://github.com/anisimovsergey/gluino

#ifndef SERIALIZATION_LIST_SERIALIZER_HPP
#define SERIALIZATION_LIST_SERIALIZER_HPP

#include "Core/List.hpp"
#include "Serializer.hpp"

namespace Serialization {

template<typename T>
class ListSerializer : public Serializer<T> {
  protected:
    // From Serializer
    virtual Core::Status
      serializeImpl(ISerializationContext& context, const T& list) const override {

      auto result = context.setEntity("elements", list);
      if (!result.isOk())
        return result;

      return Core::Status::OK;
    }

    virtual std::tuple<Core::Status, std::unique_ptr<T>>
    deserializeImpl(const IDeserializationContext&) const override {
       return std::make_tuple(Core::Status::NotImplemented, nullptr);
    }
};

}

#endif /* end of include guard: SERIALIZATION_LIST_SERIALIZER_HPP */
<|endoftext|>