<commit_before>/*-
 *   Copyright (C) 2008-2009 by Maxim Ignatenko
 *   gelraen.ua@gmail.com
 *
 *   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.                                                     *
 *                                                                         *
 *   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.  *
 *
 *  $Id$
 */
#include "config.h"
#include "defs.h"
#include <fstream>
#include <string>
#include <sstream>

using namespace std;

Config::Config()
	: IRCConfig(), DCConfig()
{
	m_loglevel=log::error + log::warning + log::notice;
	m_bSyslog=0;
}

Config::Config(const IRCConfig& c1,const DCConfig& c2, const Config& conf)
	: IRCConfig(c1), DCConfig(c2)
{
	m_sLogFile=conf.m_sLogFile;
	m_pidfile=conf.m_pidfile;
	m_loglevel=conf.m_loglevel;
	m_bSyslog=m_bSyslog;
}

Config::~Config()
{
}

struct confvar
{
	string name;
	char type; // 's','i'
	int Config::* np;
	string Config::* sp;
};

const confvar varlist[]={
 {"irc_server",		's',	NULL,	&Config::m_irc_server},
 {"irc_port",		'i',	&Config::m_irc_port,	NULL},
 {"irc_nick",		's',	NULL,	&Config::m_irc_nick},
 {"irc_username",	's',	NULL,	&Config::m_irc_username},
 {"irc_password",	's',	NULL,	&Config::m_irc_password},
 {"irc_realname",	's',	NULL,	&Config::m_irc_realname},
 {"irc_channel",	's',	NULL,	&Config::m_irc_channel},
 {"dc_server",		's',	NULL,	&Config::m_dc_server},
 {"dc_port",		'i',	&Config::m_dc_port,	NULL},
 {"dc_nick",		's',	NULL,	&Config::m_dc_nick},
 {"dc_pass",		's',	NULL,	&Config::m_dc_pass},
 {"dc_description",	's',	NULL,	&Config::m_dc_description},
 {"dc_speed",		's',	NULL,	&Config::m_dc_speed},
 {"dc_speed_val",	'i',	&Config::m_dc_speed_val,	NULL},
 {"dc_email",		's',	NULL,	&Config::m_dc_email},
 {"dc_share_size",	's',	NULL,	&Config::m_dc_share_size},
 {"logfile",		's',	NULL,	&Config::m_sLogFile},
 {"pidfile",		's',	NULL,	&Config::m_pidfile},
 {"loglevel",		'i',	&Config::m_loglevel,	NULL},
 {"use_syslog",		'i',	&Config::m_bSyslog,	NULL},
 {"",				'\0',	NULL,	NULL} // terminator
};

/*!
    \fn Config::ReadFromFile(const string& sConfFile)
 */
bool Config::ReadFromFile(const string& sConfFile)
{
	string str;
	ifstream conf(sConfFile.c_str());

	if (conf.bad()) return false;

	while (!conf.eof())
	{
		getline(conf,str);

		string::size_type pos=0;
		str=trim(str);
		if ((pos=str.find(';'))!=string::npos)
		{
			str.erase(pos); // erase all after ';'
		}
		if (str == ""||(pos=str.find("="))==string::npos)
			continue;
		vars[trim(str.substr(0, pos))] =
				trim(trim(trim(str.substr(pos + 1)), '\''), '\"');
	};

	int i;
	istringstream s;
	for(i=0;varlist[i].type!='\0';i++)
	{
		if (vars.find(varlist[i].name)==vars.end()) continue;
		switch (varlist[i].type)
		{
			case 's':
				(this->*(varlist[i].sp))=vars[varlist[i].name];
				break;
			case 'i':
				s.str(vars[varlist[i].name]);
				s >> (this->*(varlist[i].np));
				break;
		}
	}

	return true;
}

/*!
    \fn Config::getLogFile()
 */
const string& Config::getLogFile()
{
	return m_sLogFile;
}
<commit_msg>Bugfixing<commit_after>/*-
 *   Copyright (C) 2008-2009 by Maxim Ignatenko
 *   gelraen.ua@gmail.com
 *
 *   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.                                                     *
 *                                                                         *
 *   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.  *
 *
 *  $Id$
 */
#include "config.h"
#include "defs.h"
#include <fstream>
#include <string>
#include <sstream>
#include <cstdlib>

using namespace std;

Config::Config()
	: IRCConfig(), DCConfig()
{
	m_loglevel=log::error + log::warning + log::notice;
	m_bSyslog=0;
}

Config::Config(const IRCConfig& c1,const DCConfig& c2, const Config& conf)
	: IRCConfig(c1), DCConfig(c2)
{
	m_sLogFile=conf.m_sLogFile;
	m_pidfile=conf.m_pidfile;
	m_loglevel=conf.m_loglevel;
	m_bSyslog=m_bSyslog;
}

Config::~Config()
{
}

struct confvar
{
	string name;
	char type; // 's','i'
	int Config::* np;
	string Config::* sp;
};

const confvar varlist[]={
 {"irc_server",		's',	NULL,	&Config::m_irc_server},
 {"irc_port",		'i',	&Config::m_irc_port,	NULL},
 {"irc_nick",		's',	NULL,	&Config::m_irc_nick},
 {"irc_username",	's',	NULL,	&Config::m_irc_username},
 {"irc_password",	's',	NULL,	&Config::m_irc_password},
 {"irc_realname",	's',	NULL,	&Config::m_irc_realname},
 {"irc_channel",	's',	NULL,	&Config::m_irc_channel},
 {"dc_server",		's',	NULL,	&Config::m_dc_server},
 {"dc_port",		'i',	&Config::m_dc_port,	NULL},
 {"dc_nick",		's',	NULL,	&Config::m_dc_nick},
 {"dc_pass",		's',	NULL,	&Config::m_dc_pass},
 {"dc_description",	's',	NULL,	&Config::m_dc_description},
 {"dc_speed",		's',	NULL,	&Config::m_dc_speed},
 {"dc_speed_val",	'i',	&Config::m_dc_speed_val,	NULL},
 {"dc_email",		's',	NULL,	&Config::m_dc_email},
 {"dc_share_size",	's',	NULL,	&Config::m_dc_share_size},
 {"logfile",		's',	NULL,	&Config::m_sLogFile},
 {"pidfile",		's',	NULL,	&Config::m_pidfile},
 {"loglevel",		'i',	&Config::m_loglevel,	NULL},
 {"use_syslog",		'i',	&Config::m_bSyslog,	NULL},
 {"",				'\0',	NULL,	NULL} // terminator
};

/*!
    \fn Config::ReadFromFile(const string& sConfFile)
 */
bool Config::ReadFromFile(const string& sConfFile)
{
	string str;
	ifstream conf(sConfFile.c_str());

	if (conf.bad()) return false;

	while (!conf.eof())
	{
		getline(conf,str);

		string::size_type pos=0;
		str=trim(str);
		if ((pos=str.find(';'))!=string::npos)
		{
			str.erase(pos); // erase all after ';'
		}
		if (str == ""||(pos=str.find("="))==string::npos)
			continue;
		vars[trim(str.substr(0, pos))] =
				trim(trim(trim(str.substr(pos + 1)), '\''), '\"');
	};

	int i;
	for(i=0;varlist[i].type!='\0';i++)
	{
		if (vars.find(varlist[i].name)==vars.end()) continue;
		switch (varlist[i].type)
		{
			case 's':
				(this->*(varlist[i].sp))=vars[varlist[i].name];
				break;
			case 'i':
				this->*(varlist[i].np)=(int)strtol(vars[varlist[i].name].c_str(),
													(char **)NULL, 10);
				break;
		}
	}

	return true;
}

/*!
    \fn Config::getLogFile()
 */
const string& Config::getLogFile()
{
	return m_sLogFile;
}
<|endoftext|>


<commit_before>#ifndef AX_INPUT_OUTPUT_H
#define AX_INPUT_OUTPUT_H
#include <iostream>
#include "Expression.hpp"

namespace ax
{

template<class V,
         typename std::enable_if<
                 is_VectorExpression<typename V::value_trait>::value
             >::type*& = enabler>
std::ostream& operator<<(std::ostream& os, const V& vec)
{
    for(auto i(0); i<V::size; ++i)
        os << vec[i] << " ";
    return os;
}

template<class V,
         typename std::enable_if<
                 is_DynamicVectorExpression<typename V::value_trait>::value
             >::type*& = enabler>
std::ostream& operator<<(std::ostream& os, const V& vec)
{
    for(auto i(0); i<vec.size(); ++i)
        os << vec[i] << " ";
    return os;
}

template<class M,
         typename std::enable_if<
                 is_MatrixExpression<typename M::value_trait>::value
             >::type*& = enabler>
std::ostream& operator<<(std::ostream& os, const M& mat)
{
    for(std::size_t i(0); i<M::row; ++i)
    {
        for(std::size_t j(0); j<M::col; ++j)
            os << mat(i,j) << " ";
        std::cout << std::endl;
    }
    return os;
}

template<class M,
         typename std::enable_if<
                 is_DynamicMatrixExpression<typename M::value_trait>::value
             >::type*& = enabler>
std::ostream& operator<<(std::ostream& os, const M& mat)
{
    for(std::size_t i(0); i<mat.size_row(); ++i)
    {
        for(std::size_t j(0); j<mat.size_col(); ++j)
            os << mat(i,j) << " ";
        std::cout << std::endl;
    }
    return os;
}

}
#endif /*AX_INPUT_OUTPUT_H*/
<commit_msg>add VectorAVX output<commit_after>#ifndef AX_INPUT_OUTPUT_H
#define AX_INPUT_OUTPUT_H
#include <iostream>
#include <array>
#include "Expression.hpp"

namespace ax
{

template<class V,
         typename std::enable_if<
                 is_VectorExpression<typename V::value_trait>::value
             >::type*& = enabler>
std::ostream& operator<<(std::ostream& os, const V& vec)
{
    for(auto i(0); i<V::size; ++i)
        os << vec[i] << " ";
    return os;
}

template<class V,
         typename std::enable_if<
                 is_DynamicVectorExpression<typename V::value_trait>::value
             >::type*& = enabler>
std::ostream& operator<<(std::ostream& os, const V& vec)
{
    for(auto i(0); i<vec.size(); ++i)
        os << vec[i] << " ";
    return os;
}

template<class V,
         typename std::enable_if<
                 is_AVXVectorExpression<typename V::value_trait>::value
             >::type*& = enabler>
std::ostream& operator<<(std::ostream& os, const V& vec)
{
    std::array<double, V::size> val = vec.get();
    for(auto i(0); i<V::size; ++i)
        os << val[i] << " ";
    return os;
}

template<class M,
         typename std::enable_if<
                 is_MatrixExpression<typename M::value_trait>::value
             >::type*& = enabler>
std::ostream& operator<<(std::ostream& os, const M& mat)
{
    for(std::size_t i(0); i<M::row; ++i)
    {
        for(std::size_t j(0); j<M::col; ++j)
            os << mat(i,j) << " ";
        std::cout << std::endl;
    }
    return os;
}

template<class M,
         typename std::enable_if<
                 is_DynamicMatrixExpression<typename M::value_trait>::value
             >::type*& = enabler>
std::ostream& operator<<(std::ostream& os, const M& mat)
{
    for(std::size_t i(0); i<mat.size_row(); ++i)
    {
        for(std::size_t j(0); j<mat.size_col(); ++j)
            os << mat(i,j) << " ";
        std::cout << std::endl;
    }
    return os;
}

}
#endif /*AX_INPUT_OUTPUT_H*/
<|endoftext|>


<commit_before>/*************************************************************************
 *
 * 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: olestorage.cxx,v $
 * $Revision: 1.3 $
 *
 * 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.
 *
 ************************************************************************/

#include "oox/helper/olestorage.hxx"
#include <com/sun/star/lang/XMultiServiceFactory.hpp>
#include <com/sun/star/beans/PropertyValue.hpp>
#include <com/sun/star/container/XNameContainer.hpp>
#include <com/sun/star/io/XInputStream.hpp>
#include <com/sun/star/io/XOutputStream.hpp>
#include "oox/helper/helper.hxx"

using ::rtl::OUString;
using ::com::sun::star::uno::Any;
using ::com::sun::star::uno::Reference;
using ::com::sun::star::uno::Sequence;
using ::com::sun::star::uno::Exception;
using ::com::sun::star::uno::UNO_QUERY;
using ::com::sun::star::uno::UNO_QUERY_THROW;
using ::com::sun::star::container::XNameAccess;
using ::com::sun::star::lang::XMultiServiceFactory;
using ::com::sun::star::beans::PropertyValue;
using ::com::sun::star::embed::XStorage;
using ::com::sun::star::io::XInputStream;
using ::com::sun::star::io::XOutputStream;

namespace oox {

// ============================================================================

OleStorage::OleStorage(
        const Reference< XMultiServiceFactory >& rxFactory,
        const Reference< XInputStream >& rxInStream,
        bool bBaseStreamAccess ) :
    StorageBase( rxInStream, bBaseStreamAccess )
{
    OSL_ENSURE( rxFactory.is(), "OleStorage::OleStorage - missing service factory" );
    // create base storage object
    Sequence< Any > aArgs( 2 );
    aArgs[ 0 ] <<= rxInStream;
    aArgs[ 1 ] <<= true;        // true = do not create a copy of the input stream
    mxStorage.set( rxFactory->createInstanceWithArguments(
        CREATE_OUSTRING( "com.sun.star.embed.OLESimpleStorage" ), aArgs ), UNO_QUERY );
    mxElements.set( mxStorage, UNO_QUERY );
}

OleStorage::OleStorage(
        const Reference< XMultiServiceFactory >& rxFactory,
        const Reference< XOutputStream >& rxOutStream,
        bool bBaseStreamAccess ) :
    StorageBase( rxOutStream, bBaseStreamAccess )
{
    OSL_ENSURE( rxFactory.is(), "OleStorage::OleStorage - missing service factory" );
    (void)rxFactory;    // prevent compiler warning
    OSL_ENSURE( false, "OleStorage::OleStorage - not implemented" );
    mxElements.set( mxStorage, UNO_QUERY );
}

OleStorage::OleStorage( const OleStorage& rParentStorage, const Reference< XNameAccess >& rxElementsAccess, const OUString& rElementName ) :
    StorageBase( rParentStorage, rElementName ),
    mxStorage( rParentStorage.mxStorage ),
    mxElements( rxElementsAccess )
{
    OSL_ENSURE( mxElements.is(), "OleStorage::OleStorage - missing elements access" );
}

OleStorage::~OleStorage()
{
}

// StorageBase interface ------------------------------------------------------

bool OleStorage::implIsStorage() const
{
    if( mxStorage.is() && mxElements.is() ) try
    {
        /*  If this is not a storage, hasElements() throws an exception. But we
            do not return the result of hasElements(), because an empty storage
            is a valid storage too. */
        mxElements->hasElements();
        return true;
    }
    catch( Exception& )
    {
    }
    return false;
}

Reference< XStorage > OleStorage::implGetXStorage() const
{
    OSL_ENSURE( false, "OleStorage::getXStorage - not implemented" );
    return Reference< XStorage >();
}

void OleStorage::implGetElementNames( ::std::vector< OUString >& orElementNames ) const
{
    Sequence< OUString > aNames;
    if( mxStorage.is() ) try
    {
        aNames = mxElements->getElementNames();
        if( aNames.getLength() > 0 )
            orElementNames.insert( orElementNames.end(), aNames.getConstArray(), aNames.getConstArray() + aNames.getLength() );
    }
    catch( Exception& )
    {
    }
}

StorageRef OleStorage::implOpenSubStorage( const OUString& rElementName, bool bCreate )
{
    OSL_ENSURE( !bCreate, "OleStorage::implOpenSubStorage - creating substorages not implemented" );
    (void)bCreate;  // prevent compiler warning
    StorageRef xSubStorage;
    if( mxElements.is() ) try
    {
        Reference< XNameAccess > xSubElements( mxElements->getByName( rElementName ), UNO_QUERY_THROW );
        xSubStorage.reset( new OleStorage( *this, xSubElements, rElementName ) );
    }
    catch( Exception& )
    {
    }
    return xSubStorage;
}

Reference< XInputStream > OleStorage::implOpenInputStream( const OUString& rElementName )
{
    Reference< XInputStream > xInStream;
    if( mxElements.is() ) try
    {
        xInStream.set( mxElements->getByName( rElementName ), UNO_QUERY );
    }
    catch( Exception& )
    {
    }
    return xInStream;
}

Reference< XOutputStream > OleStorage::implOpenOutputStream( const OUString& rElementName )
{
    Reference< XOutputStream > xOutStream;
    if( mxElements.is() && (rElementName.getLength() > 0) ) try
    {
        (void)rElementName;     // prevent compiler warning
        OSL_ENSURE( false, "OleStorage::implOpenOutputStream - not implemented" );
    }
    catch( Exception& )
    {
    }
    return xOutStream;
}

// ============================================================================

} // namespace oox

<commit_msg>INTEGRATION: CWS xmlfilter05 (1.2.18); FILE MERGED 2008/05/02 11:24:39 hbrinkm 1.2.18.2: RESYNC: (1.2-1.3); FILE MERGED 2008/04/17 09:45:46 dr 1.2.18.1: #i86546# #i86549# #i86560# support all file types and templates<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: olestorage.cxx,v $
 * $Revision: 1.4 $
 *
 * 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.
 *
 ************************************************************************/

#include "oox/helper/olestorage.hxx"
#include <com/sun/star/lang/XMultiServiceFactory.hpp>
#include <com/sun/star/beans/PropertyValue.hpp>
#include <com/sun/star/container/XNameContainer.hpp>
#include <com/sun/star/io/XInputStream.hpp>
#include <com/sun/star/io/XOutputStream.hpp>
#include "oox/helper/helper.hxx"

using ::rtl::OUString;
using ::com::sun::star::uno::Any;
using ::com::sun::star::uno::Reference;
using ::com::sun::star::uno::Sequence;
using ::com::sun::star::uno::Exception;
using ::com::sun::star::uno::UNO_QUERY;
using ::com::sun::star::uno::UNO_QUERY_THROW;
using ::com::sun::star::container::XNameAccess;
using ::com::sun::star::lang::XMultiServiceFactory;
using ::com::sun::star::beans::PropertyValue;
using ::com::sun::star::embed::XStorage;
using ::com::sun::star::io::XInputStream;
using ::com::sun::star::io::XOutputStream;

namespace oox {

// ============================================================================

OleStorage::OleStorage(
        const Reference< XMultiServiceFactory >& rxFactory,
        const Reference< XInputStream >& rxInStream,
        bool bBaseStreamAccess ) :
    StorageBase( rxInStream, bBaseStreamAccess )
{
    OSL_ENSURE( rxFactory.is(), "OleStorage::OleStorage - missing service factory" );
    // create base storage object
    Sequence< Any > aArgs( 2 );
    aArgs[ 0 ] <<= rxInStream;
    aArgs[ 1 ] <<= true;        // true = do not create a copy of the input stream
    mxStorage.set( rxFactory->createInstanceWithArguments(
        CREATE_OUSTRING( "com.sun.star.embed.OLESimpleStorage" ), aArgs ), UNO_QUERY );
    mxElements.set( mxStorage, UNO_QUERY );
}

OleStorage::OleStorage(
        const Reference< XMultiServiceFactory >& rxFactory,
        const Reference< XOutputStream >& rxOutStream,
        bool bBaseStreamAccess ) :
    StorageBase( rxOutStream, bBaseStreamAccess )
{
    OSL_ENSURE( rxFactory.is(), "OleStorage::OleStorage - missing service factory" );
    (void)rxFactory;    // prevent compiler warning
    OSL_ENSURE( false, "OleStorage::OleStorage - not implemented" );
    mxElements.set( mxStorage, UNO_QUERY );
}

OleStorage::OleStorage( const OleStorage& rParentStorage, const Reference< XNameAccess >& rxElementsAccess, const OUString& rElementName ) :
    StorageBase( rParentStorage, rElementName ),
    mxStorage( rParentStorage.mxStorage ),
    mxElements( rxElementsAccess )
{
    OSL_ENSURE( mxElements.is(), "OleStorage::OleStorage - missing elements access" );
}

OleStorage::~OleStorage()
{
}

// StorageBase interface ------------------------------------------------------

bool OleStorage::implIsStorage() const
{
    if( mxStorage.is() && mxElements.is() ) try
    {
        /*  If this is not a storage, hasElements() throws an exception. But we
            do not return the result of hasElements(), because an empty storage
            is a valid storage too. */
        mxElements->hasElements();
        return true;
    }
    catch( Exception& )
    {
    }
    return false;
}

Reference< XStorage > OleStorage::implGetXStorage() const
{
    OSL_ENSURE( false, "OleStorage::getXStorage - not implemented" );
    return Reference< XStorage >();
}

void OleStorage::implGetElementNames( ::std::vector< OUString >& orElementNames ) const
{
    Sequence< OUString > aNames;
    if( mxElements.is() ) try
    {
        aNames = mxElements->getElementNames();
        if( aNames.getLength() > 0 )
            orElementNames.insert( orElementNames.end(), aNames.getConstArray(), aNames.getConstArray() + aNames.getLength() );
    }
    catch( Exception& )
    {
    }
}

StorageRef OleStorage::implOpenSubStorage( const OUString& rElementName, bool bCreate )
{
    OSL_ENSURE( !bCreate, "OleStorage::implOpenSubStorage - creating substorages not implemented" );
    (void)bCreate;  // prevent compiler warning
    StorageRef xSubStorage;
    if( mxElements.is() ) try
    {
        Reference< XNameAccess > xSubElements( mxElements->getByName( rElementName ), UNO_QUERY_THROW );
        xSubStorage.reset( new OleStorage( *this, xSubElements, rElementName ) );
    }
    catch( Exception& )
    {
    }
    return xSubStorage;
}

Reference< XInputStream > OleStorage::implOpenInputStream( const OUString& rElementName )
{
    Reference< XInputStream > xInStream;
    if( mxElements.is() ) try
    {
        xInStream.set( mxElements->getByName( rElementName ), UNO_QUERY );
    }
    catch( Exception& )
    {
    }
    return xInStream;
}

Reference< XOutputStream > OleStorage::implOpenOutputStream( const OUString& rElementName )
{
    Reference< XOutputStream > xOutStream;
    if( mxElements.is() && (rElementName.getLength() > 0) ) try
    {
        (void)rElementName;     // prevent compiler warning
        OSL_ENSURE( false, "OleStorage::implOpenOutputStream - not implemented" );
    }
    catch( Exception& )
    {
    }
    return xOutStream;
}

// ============================================================================

} // namespace oox

<|endoftext|>


<commit_before>/*===================================================================

The Medical Imaging Interaction Toolkit (MITK)

Copyright (c) German Cancer Research Center,
Division of Medical and Biological Informatics.
All rights reserved.

This software is distributed WITHOUT ANY WARRANTY; without
even the implied warranty of MERCHANTABILITY or FITNESS FOR
A PARTICULAR PURPOSE.

See LICENSE.txt or http://www.mitk.org for details.

===================================================================*/

#include "QmitkMorphologicalOperationsWidget.h"
#include <mitkProgressBar.h>
#include <mitkSliceNavigationController.h>
#include <QCheckBox>

static const char* const HelpText = "Select a segmentation above";

QmitkMorphologicalOperationsWidget::QmitkMorphologicalOperationsWidget(mitk::SliceNavigationController* timeNavigationController, QWidget* parent)
  : QmitkSegmentationUtilityWidget(timeNavigationController, parent)
{
  m_Controls.setupUi(this);

  m_Controls.dataSelectionWidget->AddDataStorageComboBox(QmitkDataSelectionWidget::SegmentationPredicate);
  m_Controls.dataSelectionWidget->SetHelpText(HelpText);

  connect(m_Controls.btnClosing, SIGNAL(clicked()), this, SLOT(OnClosingButtonClicked()));
  connect(m_Controls.btnOpening, SIGNAL(clicked()), this, SLOT(OnOpeningButtonClicked()));
  connect(m_Controls.btnDilatation, SIGNAL(clicked()), this, SLOT(OnDilatationButtonClicked()));
  connect(m_Controls.btnErosion, SIGNAL(clicked()), this, SLOT(OnErosionButtonClicked()));
  connect(m_Controls.btnFillHoles, SIGNAL(clicked()), this, SLOT(OnFillHolesButtonClicked()));
  connect(m_Controls.radioButtonMorphoCross, SIGNAL(clicked()), this, SLOT(OnRadioButtonsClicked()));
  connect(m_Controls.radioButtonMorphoBall, SIGNAL(clicked()), this, SLOT(OnRadioButtonsClicked()));
  connect(m_Controls.dataSelectionWidget, SIGNAL(SelectionChanged(unsigned int, const mitk::DataNode*)), this, SLOT(OnSelectionChanged(unsigned int, const mitk::DataNode*)));

  if (m_Controls.dataSelectionWidget->GetSelection(0).IsNotNull())
    this->OnSelectionChanged(0, m_Controls.dataSelectionWidget->GetSelection(0));
}

QmitkMorphologicalOperationsWidget::~QmitkMorphologicalOperationsWidget()
{
}

void QmitkMorphologicalOperationsWidget::OnSelectionChanged(unsigned int index, const mitk::DataNode* selection)
{
  QmitkDataSelectionWidget* dataSelectionWidget = m_Controls.dataSelectionWidget;
  mitk::DataNode::Pointer node = dataSelectionWidget->GetSelection(0);

  if (node.IsNotNull())
  {
    m_Controls.dataSelectionWidget->SetHelpText("");
    this->EnableButtons(true);
  }
  else
  {
    m_Controls.dataSelectionWidget->SetHelpText(HelpText);
    this->EnableButtons(false);
  }
}

void QmitkMorphologicalOperationsWidget::EnableButtons(bool enable)
{
  m_Controls.btnClosing->setEnabled(enable);
  m_Controls.btnDilatation->setEnabled(enable);
  m_Controls.btnErosion->setEnabled(enable);
  m_Controls.btnFillHoles->setEnabled(enable);
  m_Controls.btnOpening->setEnabled(enable);
}

void QmitkMorphologicalOperationsWidget::OnRadioButtonsClicked()
{
  bool enable = m_Controls.radioButtonMorphoBall->isChecked();

  m_Controls.sliderMorphFactor->setEnabled(enable);
  m_Controls.spinBoxMorphFactor->setEnabled(enable);
}

void QmitkMorphologicalOperationsWidget::OnClosingButtonClicked()
{
  QApplication::setOverrideCursor(QCursor(Qt::BusyCursor));
  mitk::RenderingManager::GetInstance()->RequestUpdateAll();

  QmitkDataSelectionWidget* dataSelectionWidget = m_Controls.dataSelectionWidget;
  mitk::DataNode::Pointer node = dataSelectionWidget->GetSelection(0);
  mitk::Image::Pointer image = static_cast<mitk::Image*>(node->GetData());
  bool ball = m_Controls.radioButtonMorphoBall->isChecked();

  mitk::MorphologicalOperations::StructuralElementType structuralElement = ball
    ? mitk::MorphologicalOperations::Ball
    : mitk::MorphologicalOperations::Cross;

  try
  {
    mitk::MorphologicalOperations::Closing(image, m_Controls.spinBoxMorphFactor->value(), structuralElement);
  }
  catch (const itk::ExceptionObject& exception)
  {
    MITK_WARN << "Exception caught: " << exception.GetDescription();

    QApplication::restoreOverrideCursor();
    return;
  }

  node->SetData(image);

  mitk::RenderingManager::GetInstance()->RequestUpdateAll();
  QApplication::restoreOverrideCursor();
}

void QmitkMorphologicalOperationsWidget::OnOpeningButtonClicked()
{
  QApplication::setOverrideCursor(QCursor(Qt::BusyCursor));
  mitk::RenderingManager::GetInstance()->RequestUpdateAll();

  QmitkDataSelectionWidget* dataSelectionWidget = m_Controls.dataSelectionWidget;
  mitk::DataNode::Pointer node = dataSelectionWidget->GetSelection(0);
  mitk::Image::Pointer image = static_cast<mitk::Image*>(node->GetData());
  bool ball = m_Controls.radioButtonMorphoBall->isChecked();

  mitk::MorphologicalOperations::StructuralElementType structuralElement = ball
    ? mitk::MorphologicalOperations::Ball
    : mitk::MorphologicalOperations::Cross;

  try
  {
     mitk::MorphologicalOperations::Opening(image, m_Controls.spinBoxMorphFactor->value(), structuralElement);
  }
  catch (const itk::ExceptionObject& exception)
  {
     MITK_WARN << "Exception caught: " << exception.GetDescription();

     QApplication::restoreOverrideCursor();
     return;
  }

  node->SetData(image);

  mitk::RenderingManager::GetInstance()->RequestUpdateAll();
  QApplication::restoreOverrideCursor();
}

void QmitkMorphologicalOperationsWidget::OnDilatationButtonClicked()
{
  QApplication::setOverrideCursor(QCursor(Qt::BusyCursor));
  mitk::RenderingManager::GetInstance()->RequestUpdateAll();

  QmitkDataSelectionWidget* dataSelectionWidget = m_Controls.dataSelectionWidget;
  mitk::DataNode::Pointer node = dataSelectionWidget->GetSelection(0);
  mitk::Image::Pointer image = static_cast<mitk::Image*>(node->GetData());
  bool ball = m_Controls.radioButtonMorphoBall->isChecked();

  mitk::MorphologicalOperations::StructuralElementType structuralElement = ball
    ? mitk::MorphologicalOperations::Ball
    : mitk::MorphologicalOperations::Cross;

  try
  {
    mitk::MorphologicalOperations::Dilate(image, m_Controls.spinBoxMorphFactor->value(), structuralElement);
  }
  catch (const itk::ExceptionObject& exception)
  {
    MITK_WARN << "Exception caught: " << exception.GetDescription();

    QApplication::restoreOverrideCursor();
    return;
  }

  node->SetData(image);

  mitk::RenderingManager::GetInstance()->RequestUpdateAll();
  QApplication::restoreOverrideCursor();
}

void QmitkMorphologicalOperationsWidget::OnErosionButtonClicked()
{
  QApplication::setOverrideCursor(QCursor(Qt::BusyCursor));
  mitk::RenderingManager::GetInstance()->RequestUpdateAll();

  QmitkDataSelectionWidget* dataSelectionWidget = m_Controls.dataSelectionWidget;
  mitk::DataNode::Pointer node = dataSelectionWidget->GetSelection(0);
  mitk::Image::Pointer image = static_cast<mitk::Image*>(node->GetData());
  bool ball = m_Controls.radioButtonMorphoBall->isChecked();

  mitk::MorphologicalOperations::StructuralElementType structuralElement = ball
    ? mitk::MorphologicalOperations::Ball
    : mitk::MorphologicalOperations::Cross;

  try
  {
    mitk::MorphologicalOperations::Erode(image, m_Controls.spinBoxMorphFactor->value(), structuralElement);
  }
  catch (const itk::ExceptionObject& exception)
  {
    MITK_WARN << "Exception caught: " << exception.GetDescription();

    QApplication::restoreOverrideCursor();
    return;
 }

  node->SetData(image);

  mitk::RenderingManager::GetInstance()->RequestUpdateAll();
  QApplication::restoreOverrideCursor();
}

void QmitkMorphologicalOperationsWidget::OnFillHolesButtonClicked()
{
  QApplication::setOverrideCursor(QCursor(Qt::BusyCursor));
  mitk::RenderingManager::GetInstance()->RequestUpdateAll();

  QmitkDataSelectionWidget* dataSelectionWidget = m_Controls.dataSelectionWidget;
  mitk::DataNode::Pointer node = dataSelectionWidget->GetSelection(0);
  mitk::Image::Pointer image = static_cast<mitk::Image*>(node->GetData());

  try
  {
    mitk::MorphologicalOperations::FillHoles(image);
  }
  catch (const itk::ExceptionObject& exception)
  {
    MITK_WARN << "Exception caught: " << exception.GetDescription();

    QApplication::restoreOverrideCursor();
    return;
  }

  node->SetData(image);

  mitk::RenderingManager::GetInstance()->RequestUpdateAll();
  QApplication::restoreOverrideCursor();
}

mitk::MorphologicalOperations::StructuralElementType QmitkMorphologicalOperationsWidget::CreateStructerElement_UI()
{
  bool ball = m_Controls.radioButtonMorphoBall->isChecked();
  int accum_flag = 0;
  if(ball){
   if(m_Controls.m_AxialCheckbox->isChecked()) accum_flag |= mitk::MorphologicalOperations::Ball_Axial;
   if(m_Controls.m_SagitalCheckbox->isChecked()) accum_flag |= mitk::MorphologicalOperations::Ball_Sagital;
   if(m_Controls.m_CornalCheckbox->isChecked()) accum_flag |= mitk::MorphologicalOperations::Ball_Coronal;
  }else{
    if(m_Controls.m_AxialCheckbox->isChecked()) accum_flag |= mitk::MorphologicalOperations::Cross_Axial;
    if(m_Controls.m_SagitalCheckbox->isChecked()) accum_flag |= mitk::MorphologicalOperations::Cross_Sagital;
    if(m_Controls.m_CornalCheckbox->isChecked()) accum_flag |= mitk::MorphologicalOperations::Cross_Coronal;
  }
  return (mitk::MorphologicalOperations::StructuralElementType)accum_flag;
}
<commit_msg>use the new added method<commit_after>/*===================================================================

The Medical Imaging Interaction Toolkit (MITK)

Copyright (c) German Cancer Research Center,
Division of Medical and Biological Informatics.
All rights reserved.

This software is distributed WITHOUT ANY WARRANTY; without
even the implied warranty of MERCHANTABILITY or FITNESS FOR
A PARTICULAR PURPOSE.

See LICENSE.txt or http://www.mitk.org for details.

===================================================================*/

#include "QmitkMorphologicalOperationsWidget.h"
#include <mitkProgressBar.h>
#include <mitkSliceNavigationController.h>
#include <QCheckBox>

static const char* const HelpText = "Select a segmentation above";

QmitkMorphologicalOperationsWidget::QmitkMorphologicalOperationsWidget(mitk::SliceNavigationController* timeNavigationController, QWidget* parent)
  : QmitkSegmentationUtilityWidget(timeNavigationController, parent)
{
  m_Controls.setupUi(this);

  m_Controls.dataSelectionWidget->AddDataStorageComboBox(QmitkDataSelectionWidget::SegmentationPredicate);
  m_Controls.dataSelectionWidget->SetHelpText(HelpText);

  connect(m_Controls.btnClosing, SIGNAL(clicked()), this, SLOT(OnClosingButtonClicked()));
  connect(m_Controls.btnOpening, SIGNAL(clicked()), this, SLOT(OnOpeningButtonClicked()));
  connect(m_Controls.btnDilatation, SIGNAL(clicked()), this, SLOT(OnDilatationButtonClicked()));
  connect(m_Controls.btnErosion, SIGNAL(clicked()), this, SLOT(OnErosionButtonClicked()));
  connect(m_Controls.btnFillHoles, SIGNAL(clicked()), this, SLOT(OnFillHolesButtonClicked()));
  connect(m_Controls.radioButtonMorphoCross, SIGNAL(clicked()), this, SLOT(OnRadioButtonsClicked()));
  connect(m_Controls.radioButtonMorphoBall, SIGNAL(clicked()), this, SLOT(OnRadioButtonsClicked()));
  connect(m_Controls.dataSelectionWidget, SIGNAL(SelectionChanged(unsigned int, const mitk::DataNode*)), this, SLOT(OnSelectionChanged(unsigned int, const mitk::DataNode*)));

  if (m_Controls.dataSelectionWidget->GetSelection(0).IsNotNull())
    this->OnSelectionChanged(0, m_Controls.dataSelectionWidget->GetSelection(0));
}

QmitkMorphologicalOperationsWidget::~QmitkMorphologicalOperationsWidget()
{
}

void QmitkMorphologicalOperationsWidget::OnSelectionChanged(unsigned int index, const mitk::DataNode* selection)
{
  QmitkDataSelectionWidget* dataSelectionWidget = m_Controls.dataSelectionWidget;
  mitk::DataNode::Pointer node = dataSelectionWidget->GetSelection(0);

  if (node.IsNotNull())
  {
    m_Controls.dataSelectionWidget->SetHelpText("");
    this->EnableButtons(true);
  }
  else
  {
    m_Controls.dataSelectionWidget->SetHelpText(HelpText);
    this->EnableButtons(false);
  }
}

void QmitkMorphologicalOperationsWidget::EnableButtons(bool enable)
{
  m_Controls.btnClosing->setEnabled(enable);
  m_Controls.btnDilatation->setEnabled(enable);
  m_Controls.btnErosion->setEnabled(enable);
  m_Controls.btnFillHoles->setEnabled(enable);
  m_Controls.btnOpening->setEnabled(enable);
}

void QmitkMorphologicalOperationsWidget::OnRadioButtonsClicked()
{
  bool enable = m_Controls.radioButtonMorphoBall->isChecked();

  m_Controls.sliderMorphFactor->setEnabled(enable);
  m_Controls.spinBoxMorphFactor->setEnabled(enable);
}

void QmitkMorphologicalOperationsWidget::OnClosingButtonClicked()
{
  QApplication::setOverrideCursor(QCursor(Qt::BusyCursor));
  mitk::RenderingManager::GetInstance()->RequestUpdateAll();

  QmitkDataSelectionWidget* dataSelectionWidget = m_Controls.dataSelectionWidget;
  mitk::DataNode::Pointer node = dataSelectionWidget->GetSelection(0);
  mitk::Image::Pointer image = static_cast<mitk::Image*>(node->GetData());
  mitk::MorphologicalOperations::StructuralElementType structuralElement = CreateStructerElement_UI();
  try
  {
    mitk::MorphologicalOperations::Closing(image, m_Controls.spinBoxMorphFactor->value(), structuralElement);
  }
  catch (const itk::ExceptionObject& exception)
  {
    MITK_WARN << "Exception caught: " << exception.GetDescription();

    QApplication::restoreOverrideCursor();
    return;
  }

  node->SetData(image);

  mitk::RenderingManager::GetInstance()->RequestUpdateAll();
  QApplication::restoreOverrideCursor();
}

void QmitkMorphologicalOperationsWidget::OnOpeningButtonClicked()
{
  QApplication::setOverrideCursor(QCursor(Qt::BusyCursor));
  mitk::RenderingManager::GetInstance()->RequestUpdateAll();

  QmitkDataSelectionWidget* dataSelectionWidget = m_Controls.dataSelectionWidget;
  mitk::DataNode::Pointer node = dataSelectionWidget->GetSelection(0);
  mitk::Image::Pointer image = static_cast<mitk::Image*>(node->GetData());

  mitk::MorphologicalOperations::StructuralElementType structuralElement = CreateStructerElement_UI();

  try
  {
     mitk::MorphologicalOperations::Opening(image, m_Controls.spinBoxMorphFactor->value(), structuralElement);
  }
  catch (const itk::ExceptionObject& exception)
  {
     MITK_WARN << "Exception caught: " << exception.GetDescription();

     QApplication::restoreOverrideCursor();
     return;
  }

  node->SetData(image);

  mitk::RenderingManager::GetInstance()->RequestUpdateAll();
  QApplication::restoreOverrideCursor();
}

void QmitkMorphologicalOperationsWidget::OnDilatationButtonClicked()
{
  QApplication::setOverrideCursor(QCursor(Qt::BusyCursor));
  mitk::RenderingManager::GetInstance()->RequestUpdateAll();

  QmitkDataSelectionWidget* dataSelectionWidget = m_Controls.dataSelectionWidget;
  mitk::DataNode::Pointer node = dataSelectionWidget->GetSelection(0);
  mitk::Image::Pointer image = static_cast<mitk::Image*>(node->GetData());
  mitk::MorphologicalOperations::StructuralElementType structuralElement = this->CreateStructerElement_UI();

  try
  {
    mitk::MorphologicalOperations::Dilate(image, m_Controls.spinBoxMorphFactor->value(), structuralElement);
  }
  catch (const itk::ExceptionObject& exception)
  {
    MITK_WARN << "Exception caught: " << exception.GetDescription();

    QApplication::restoreOverrideCursor();
    return;
  }

  node->SetData(image);

  mitk::RenderingManager::GetInstance()->RequestUpdateAll();
  QApplication::restoreOverrideCursor();
}

void QmitkMorphologicalOperationsWidget::OnErosionButtonClicked()
{
  QApplication::setOverrideCursor(QCursor(Qt::BusyCursor));
  mitk::RenderingManager::GetInstance()->RequestUpdateAll();

  QmitkDataSelectionWidget* dataSelectionWidget = m_Controls.dataSelectionWidget;
  mitk::DataNode::Pointer node = dataSelectionWidget->GetSelection(0);
  mitk::Image::Pointer image = static_cast<mitk::Image*>(node->GetData());
mitk::MorphologicalOperations::StructuralElementType structuralElement = CreateStructerElement_UI();

  try
  {
    mitk::MorphologicalOperations::Erode(image, m_Controls.spinBoxMorphFactor->value(), structuralElement);
  }
  catch (const itk::ExceptionObject& exception)
  {
    MITK_WARN << "Exception caught: " << exception.GetDescription();

    QApplication::restoreOverrideCursor();
    return;
 }

  node->SetData(image);

  mitk::RenderingManager::GetInstance()->RequestUpdateAll();
  QApplication::restoreOverrideCursor();
}

void QmitkMorphologicalOperationsWidget::OnFillHolesButtonClicked()
{
  QApplication::setOverrideCursor(QCursor(Qt::BusyCursor));
  mitk::RenderingManager::GetInstance()->RequestUpdateAll();

  QmitkDataSelectionWidget* dataSelectionWidget = m_Controls.dataSelectionWidget;
  mitk::DataNode::Pointer node = dataSelectionWidget->GetSelection(0);
  mitk::Image::Pointer image = static_cast<mitk::Image*>(node->GetData());

  try
  {
    mitk::MorphologicalOperations::FillHoles(image);
  }
  catch (const itk::ExceptionObject& exception)
  {
    MITK_WARN << "Exception caught: " << exception.GetDescription();

    QApplication::restoreOverrideCursor();
    return;
  }

  node->SetData(image);

  mitk::RenderingManager::GetInstance()->RequestUpdateAll();
  QApplication::restoreOverrideCursor();
}

mitk::MorphologicalOperations::StructuralElementType QmitkMorphologicalOperationsWidget::CreateStructerElement_UI()
{
  bool ball = m_Controls.radioButtonMorphoBall->isChecked();
  int accum_flag = 0;
  if(ball){
   if(m_Controls.m_AxialCheckbox->isChecked()) accum_flag |= mitk::MorphologicalOperations::Ball_Axial;
   if(m_Controls.m_SagitalCheckbox->isChecked()) accum_flag |= mitk::MorphologicalOperations::Ball_Sagital;
   if(m_Controls.m_CornalCheckbox->isChecked()) accum_flag |= mitk::MorphologicalOperations::Ball_Coronal;
  }else{
    if(m_Controls.m_AxialCheckbox->isChecked()) accum_flag |= mitk::MorphologicalOperations::Cross_Axial;
    if(m_Controls.m_SagitalCheckbox->isChecked()) accum_flag |= mitk::MorphologicalOperations::Cross_Sagital;
    if(m_Controls.m_CornalCheckbox->isChecked()) accum_flag |= mitk::MorphologicalOperations::Cross_Coronal;
  }
  return (mitk::MorphologicalOperations::StructuralElementType)accum_flag;
}
<|endoftext|>


<commit_before>//=============================================================================================================
/**
 * @file     annotationview.cpp
 * @author   Lorenz Esch <lesch@mgh.harvard.edu>;
 *           Gabriel Motta <gbmotta@mgh.harvard.edu>
 * @since    0.1.0
 * @date     March, 2020
 *
 * @section  LICENSE
 *
 * Copyright (C) 2020, Christoph Dinh, Lorenz Esch, Gabriel Motta. 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 MNE-CPP authors 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.
 *
 *
 * @brief    Definition of the AnnotationView Class.
 *
 */

//=============================================================================================================
// INCLUDES
//=============================================================================================================

#include "annotationview.h"
#include "ui_annotationview.h"

//=============================================================================================================
// QT INCLUDES
//=============================================================================================================

#include <QDebug>
#include <QMap>
#include <QToolBar>
#include <QColorDialog>
#include <QFileDialog>
#include <QKeyEvent>

//=============================================================================================================
// Eigen INCLUDES
//=============================================================================================================

//=============================================================================================================
// DEFINE MEMBER METHODS
//=============================================================================================================

AnnotationView::AnnotationView()
: ui(new Ui::EventWindowDockWidget)
, m_iCheckState(0)
, m_iLastSampClicked(0)
, m_pAnnModel(Q_NULLPTR)
, m_pColordialog(new QColorDialog(this))
{
    ui->setupUi(this);

    ui->m_comboBox_filterTypes->addItem("All");
    ui->m_comboBox_filterTypes->addItem("0");
    ui->m_comboBox_filterTypes->setCurrentText("All");

    onDataChanged();
}

//=============================================================================================================

void AnnotationView::initMSVCSettings()
{
    //Model
    ui->m_tableView_eventTableView->setModel(m_pAnnModel.data());
    connect(m_pAnnModel.data(),&ANSHAREDLIB::AnnotationModel::dataChanged,
            this, &AnnotationView::onDataChanged, Qt::UniqueConnection);

    //Delegate
    m_pAnnDelegate = QSharedPointer<AnnotationDelegate>(new AnnotationDelegate(this));
    ui->m_tableView_eventTableView->setItemDelegate(m_pAnnDelegate.data());

    connect(m_pAnnDelegate.data(), &AnnotationDelegate::sampleValueChanged,
            this, &AnnotationView::realTimeDataSample, Qt::UniqueConnection);

    connect(m_pAnnDelegate.data(), &AnnotationDelegate::timeValueChanged,
            this, &AnnotationView::realTimeDataTime, Qt::UniqueConnection);

    ui->m_tableView_eventTableView->resizeColumnsToContents();
    ui->m_tableView_eventTableView->adjustSize();
    ui->m_tableView_eventTableView->setSelectionMode(QAbstractItemView::ExtendedSelection);
}

//=============================================================================================================

void AnnotationView::initGUIFunctionality()
{

    //'Activate annotations' checkbox
    connect(ui->m_checkBox_activateEvents, &QCheckBox::stateChanged,
            this, &AnnotationView::onActiveEventsChecked, Qt::UniqueConnection);

    //'Show selected annotation' checkbox
    connect(ui->m_checkBox_showSelectedEventsOnly,&QCheckBox::stateChanged,
            this, &AnnotationView::onSelectedEventsChecked, Qt::UniqueConnection);
    connect(ui->m_tableView_eventTableView->selectionModel(), &QItemSelectionModel::selectionChanged,
            this, &AnnotationView::onCurrentSelectedChanged, Qt::UniqueConnection);

    //Annotation types combo box

    //ui->m_comboBox_filterTypes->addItems(m_pAnnModel->getEventTypeList());

    connect(ui->m_comboBox_filterTypes, &QComboBox::currentTextChanged,
            m_pAnnModel.data(), &ANSHAREDLIB::AnnotationModel::setEventFilterType, Qt::UniqueConnection);
    connect(m_pAnnModel.data(), &ANSHAREDLIB::AnnotationModel::updateEventTypes,
            this, &AnnotationView::updateComboBox, Qt::UniqueConnection);

    //'Remove annotations' button
    QToolBar *toolBar = new QToolBar(this);
    toolBar->setOrientation(Qt::Vertical);
    toolBar->setMovable(false);
    QAction* removeEvent = new QAction("Remove", this);
    removeEvent->setStatusTip(tr("Remove an annotation from the list"));
    toolBar->addAction(removeEvent);
    connect(removeEvent, &QAction::triggered,
            this, &AnnotationView::removeAnnotationfromModel, Qt::UniqueConnection);
    ui->m_gridLayout_Main->addWidget(toolBar,1,1,1,1);

    //Add type button
    connect(ui->m_pushButton_addEventType, &QPushButton::clicked,
            this, &AnnotationView::addNewAnnotationType, Qt::UniqueConnection);

    connect(ui->m_pushButtonSave, &QPushButton::clicked,
            this, &AnnotationView::onSaveButton, Qt::UniqueConnection);

    //connect(ui->m_tableView_eventTableView.)
}

//=============================================================================================================

void AnnotationView::onActiveEventsChecked(int iCheckBoxState)
{
    //qDebug() << "onActiveEventsChecked" << iCheckBoxState;
    m_iCheckState = iCheckBoxState;
    emit activeEventsChecked(m_iCheckState);
}

//=============================================================================================================

void AnnotationView::updateComboBox(const QString &currentAnnotationType)
{
    ui->m_comboBox_filterTypes->clear();
    ui->m_comboBox_filterTypes->addItem("All");
    ui->m_comboBox_filterTypes->addItems(m_pAnnModel->getEventTypeList());
//    if(m_pAnnModel->getEventTypeList().contains(currentAnnotationType))
//        ui->m_comboBox_filterTypes->setCurrentText(currentAnnotationType);

    m_pAnnModel->setLastType(currentAnnotationType.toInt());
    emit triggerRedraw();
}

//=============================================================================================================

void AnnotationView::addAnnotationToModel(const int iSample)
{
    //qDebug() << "AnnotationView::addAnnotationToModel -- Here";
    m_iLastSampClicked = iSample;
    m_pAnnModel->setSamplePos(m_iLastSampClicked);
    m_pAnnModel->insertRow(0, QModelIndex());
    emit triggerRedraw();
}

//=============================================================================================================

void AnnotationView::setModel(QSharedPointer<ANSHAREDLIB::AnnotationModel> pAnnModel)
{
    m_pAnnModel = pAnnModel;

    initMSVCSettings();
    initGUIFunctionality();
    onDataChanged();
}

//=============================================================================================================

void AnnotationView::onDataChanged()
{
    //qDebug() << "AnnotationView::onDataChanged";
    ui->m_tableView_eventTableView->viewport()->update();
    ui->m_tableView_eventTableView->viewport()->repaint();
    emit triggerRedraw();
}

//=============================================================================================================

void AnnotationView::passFiffParams(int iFirst,int iLast,float fFreq)
{
    m_pAnnModel->setFirstLastSample(iFirst, iLast);
    m_pAnnModel->setSampleFreq(fFreq);
}

//=============================================================================================================

void AnnotationView::removeAnnotationfromModel()
{
    QModelIndexList indexList = ui->m_tableView_eventTableView->selectionModel()->selectedIndexes();
    for(int i = 0; i<indexList.size(); i++)
        m_pAnnModel->removeRow(indexList.at(i).row() /*- i*/);
    emit triggerRedraw();
}

//=============================================================================================================

void AnnotationView::addNewAnnotationType()
{
    m_pAnnModel->addNewAnnotationType(QString().number(ui->m_spinBox_addEventType->value()), m_pColordialog->getColor(Qt::black, this));
    //m_pAnnModel->setEventFilterType(QString().number(ui->m_spinBox_addEventType->value()));
    emit triggerRedraw();
}

//=============================================================================================================

void AnnotationView::onSelectedEventsChecked(int iCheckBoxState)
{
    m_iCheckSelectedState = iCheckBoxState;
    m_pAnnModel->setShowSelected(m_iCheckSelectedState);
    //qDebug() << ui->m_tableView_eventTableView->selectionModel()->currentIndex().row();
    //ui->m_tableView_eventTableView->selectionModel()->sle
    //m_pAnnModel
    emit triggerRedraw();
}

//=============================================================================================================

void AnnotationView::disconnectFromModel()
{
    disconnect(m_pAnnModel.data(),&ANSHAREDLIB::AnnotationModel::dataChanged,
            this, &AnnotationView::onDataChanged);
    disconnect(ui->m_checkBox_activateEvents, &QCheckBox::stateChanged,
            this, &AnnotationView::onActiveEventsChecked);
    disconnect(ui->m_checkBox_showSelectedEventsOnly,&QCheckBox::stateChanged,
            this, &AnnotationView::onSelectedEventsChecked);
    disconnect(ui->m_comboBox_filterTypes, &QComboBox::currentTextChanged,
            m_pAnnModel.data(), &ANSHAREDLIB::AnnotationModel::setEventFilterType);
    disconnect(m_pAnnModel.data(), &ANSHAREDLIB::AnnotationModel::updateEventTypes,
            this, &AnnotationView::updateComboBox);
    disconnect(ui->m_pushButton_addEventType, &QPushButton::clicked,
            this, &AnnotationView::addNewAnnotationType);

}

//=============================================================================================================

void AnnotationView::onCurrentSelectedChanged()
{
    m_pAnnModel->clearSelected();
    //qDebug() << "AnnotationView::onCurrentSelectedChanged";
    //qDebug() << ui->m_tableView_eventTableView->selectionModel()->currentIndex().row();
    m_pAnnModel->setSelectedAnn(ui->m_tableView_eventTableView->selectionModel()->currentIndex().row());
//    m_pAnnModel->setSelectedAnn(ui->m_tableView_eventTableView
//    qDebug() << ui->m_tableView_eventTableView->selectionModel()->selectedIndexes();

    for (int i = 0;  i < ui->m_tableView_eventTableView->selectionModel()->selectedRows().size(); i++) {
//        qDebug() << ui->m_tableView_eventTableView->selectionModel()->selectedRows().at(i).row();
        m_pAnnModel->appendSelected(ui->m_tableView_eventTableView->selectionModel()->selectedRows().at(i).row());
    }
}

//=============================================================================================================

void AnnotationView::onSaveButton()
{
#ifdef WASMBUILD
    m_pAnnModel->saveToFile("");
#else
    QString fileName = QFileDialog::getSaveFileName(Q_NULLPTR,
                                                    tr("Save Annotations"), "",
                                                    tr("Event file (*.eve);;All Files (*)"));

    if (fileName.isEmpty()) {
        return;
    }
    qInfo() << "AnnotationView::onSaveButton";

    m_pAnnModel->saveToFile(fileName);
#endif
}

//=============================================================================================================

void AnnotationView::keyPressEvent(QKeyEvent* event)
{
    if(event->key() == Qt::Key_Delete) {
        //qDebug() << "[AnnotationView::keyPressEvent] -- Qt::Key_Delete";
        this->removeAnnotationfromModel();
    }
}

//=============================================================================================================

void AnnotationView::realTimeDataSample(int iValue)
{
    m_pAnnModel->setSelectedAnn(ui->m_tableView_eventTableView->selectionModel()->currentIndex().row());
    //qDebug() << "AnnotationView::realTimeData --" << iValue;
    m_pAnnModel->updateFilteredSample(iValue);
    this->onDataChanged();
}

//=============================================================================================================

void AnnotationView::realTimeDataTime(double dValue)
{
    m_pAnnModel->setSelectedAnn(ui->m_tableView_eventTableView->selectionModel()->currentIndex().row());
    //qDebug() << "AnnotationView::realTimeDataTime" << dValue;
    dValue *= m_pAnnModel->getFreq();
    //qDebug() << "AnnotationView::realTimeDataTime" << dValue;
    int t_iSample = static_cast<int>(dValue);
    m_pAnnModel->updateFilteredSample(t_iSample);
    this->onDataChanged();
}
<commit_msg>ENH: fix deleting annotations when multiple selected<commit_after>//=============================================================================================================
/**
 * @file     annotationview.cpp
 * @author   Lorenz Esch <lesch@mgh.harvard.edu>;
 *           Gabriel Motta <gbmotta@mgh.harvard.edu>
 * @since    0.1.0
 * @date     March, 2020
 *
 * @section  LICENSE
 *
 * Copyright (C) 2020, Christoph Dinh, Lorenz Esch, Gabriel Motta. 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 MNE-CPP authors 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.
 *
 *
 * @brief    Definition of the AnnotationView Class.
 *
 */

//=============================================================================================================
// INCLUDES
//=============================================================================================================

#include "annotationview.h"
#include "ui_annotationview.h"

//=============================================================================================================
// QT INCLUDES
//=============================================================================================================

#include <QDebug>
#include <QMap>
#include <QToolBar>
#include <QColorDialog>
#include <QFileDialog>
#include <QKeyEvent>

//=============================================================================================================
// Eigen INCLUDES
//=============================================================================================================

//=============================================================================================================
// DEFINE MEMBER METHODS
//=============================================================================================================

AnnotationView::AnnotationView()
: ui(new Ui::EventWindowDockWidget)
, m_iCheckState(0)
, m_iLastSampClicked(0)
, m_pAnnModel(Q_NULLPTR)
, m_pColordialog(new QColorDialog(this))
{
    ui->setupUi(this);

    ui->m_comboBox_filterTypes->addItem("All");
    ui->m_comboBox_filterTypes->addItem("0");
    ui->m_comboBox_filterTypes->setCurrentText("All");

    onDataChanged();
}

//=============================================================================================================

void AnnotationView::initMSVCSettings()
{
    //Model
    ui->m_tableView_eventTableView->setModel(m_pAnnModel.data());
    connect(m_pAnnModel.data(),&ANSHAREDLIB::AnnotationModel::dataChanged,
            this, &AnnotationView::onDataChanged, Qt::UniqueConnection);

    //Delegate
    m_pAnnDelegate = QSharedPointer<AnnotationDelegate>(new AnnotationDelegate(this));
    ui->m_tableView_eventTableView->setItemDelegate(m_pAnnDelegate.data());

    connect(m_pAnnDelegate.data(), &AnnotationDelegate::sampleValueChanged,
            this, &AnnotationView::realTimeDataSample, Qt::UniqueConnection);

    connect(m_pAnnDelegate.data(), &AnnotationDelegate::timeValueChanged,
            this, &AnnotationView::realTimeDataTime, Qt::UniqueConnection);

    ui->m_tableView_eventTableView->resizeColumnsToContents();
    ui->m_tableView_eventTableView->adjustSize();
    ui->m_tableView_eventTableView->setSelectionMode(QAbstractItemView::ExtendedSelection);
}

//=============================================================================================================

void AnnotationView::initGUIFunctionality()
{

    //'Activate annotations' checkbox
    connect(ui->m_checkBox_activateEvents, &QCheckBox::stateChanged,
            this, &AnnotationView::onActiveEventsChecked, Qt::UniqueConnection);

    //'Show selected annotation' checkbox
    connect(ui->m_checkBox_showSelectedEventsOnly,&QCheckBox::stateChanged,
            this, &AnnotationView::onSelectedEventsChecked, Qt::UniqueConnection);
    connect(ui->m_tableView_eventTableView->selectionModel(), &QItemSelectionModel::selectionChanged,
            this, &AnnotationView::onCurrentSelectedChanged, Qt::UniqueConnection);

    //Annotation types combo box

    //ui->m_comboBox_filterTypes->addItems(m_pAnnModel->getEventTypeList());

    connect(ui->m_comboBox_filterTypes, &QComboBox::currentTextChanged,
            m_pAnnModel.data(), &ANSHAREDLIB::AnnotationModel::setEventFilterType, Qt::UniqueConnection);
    connect(m_pAnnModel.data(), &ANSHAREDLIB::AnnotationModel::updateEventTypes,
            this, &AnnotationView::updateComboBox, Qt::UniqueConnection);

    //'Remove annotations' button
    QToolBar *toolBar = new QToolBar(this);
    toolBar->setOrientation(Qt::Vertical);
    toolBar->setMovable(false);
    QAction* removeEvent = new QAction("Remove", this);
    removeEvent->setStatusTip(tr("Remove an annotation from the list"));
    toolBar->addAction(removeEvent);
    connect(removeEvent, &QAction::triggered,
            this, &AnnotationView::removeAnnotationfromModel, Qt::UniqueConnection);
    ui->m_gridLayout_Main->addWidget(toolBar,1,1,1,1);

    //Add type button
    connect(ui->m_pushButton_addEventType, &QPushButton::clicked,
            this, &AnnotationView::addNewAnnotationType, Qt::UniqueConnection);

    connect(ui->m_pushButtonSave, &QPushButton::clicked,
            this, &AnnotationView::onSaveButton, Qt::UniqueConnection);

    //connect(ui->m_tableView_eventTableView.)
}

//=============================================================================================================

void AnnotationView::onActiveEventsChecked(int iCheckBoxState)
{
    //qDebug() << "onActiveEventsChecked" << iCheckBoxState;
    m_iCheckState = iCheckBoxState;
    emit activeEventsChecked(m_iCheckState);
}

//=============================================================================================================

void AnnotationView::updateComboBox(const QString &currentAnnotationType)
{
    ui->m_comboBox_filterTypes->clear();
    ui->m_comboBox_filterTypes->addItem("All");
    ui->m_comboBox_filterTypes->addItems(m_pAnnModel->getEventTypeList());
//    if(m_pAnnModel->getEventTypeList().contains(currentAnnotationType))
//        ui->m_comboBox_filterTypes->setCurrentText(currentAnnotationType);

    m_pAnnModel->setLastType(currentAnnotationType.toInt());
    emit triggerRedraw();
}

//=============================================================================================================

void AnnotationView::addAnnotationToModel(const int iSample)
{
    //qDebug() << "AnnotationView::addAnnotationToModel -- Here";
    m_iLastSampClicked = iSample;
    m_pAnnModel->setSamplePos(m_iLastSampClicked);
    m_pAnnModel->insertRow(0, QModelIndex());
    emit triggerRedraw();
}

//=============================================================================================================

void AnnotationView::setModel(QSharedPointer<ANSHAREDLIB::AnnotationModel> pAnnModel)
{
    m_pAnnModel = pAnnModel;

    initMSVCSettings();
    initGUIFunctionality();
    onDataChanged();
}

//=============================================================================================================

void AnnotationView::onDataChanged()
{
    //qDebug() << "AnnotationView::onDataChanged";
    ui->m_tableView_eventTableView->viewport()->update();
    ui->m_tableView_eventTableView->viewport()->repaint();
    emit triggerRedraw();
}

//=============================================================================================================

void AnnotationView::passFiffParams(int iFirst,int iLast,float fFreq)
{
    m_pAnnModel->setFirstLastSample(iFirst, iLast);
    m_pAnnModel->setSampleFreq(fFreq);
}

//=============================================================================================================

void AnnotationView::removeAnnotationfromModel()
{
    ui->m_tableView_eventTableView->setSelectionMode(QAbstractItemView::SingleSelection);
    //QModelIndexList indexList = ui->m_tableView_eventTableView->selectionModel()->selectedIndexes();
    QModelIndexList indexList = ui->m_tableView_eventTableView->selectionModel()->selectedRows();
    qDebug() << indexList;
    int iLastDeleted();
    for(int i = 0; i<indexList.size(); i++) {
        //qDebug() << "Index List" << indexList.at(i).row();
        //qDebug() << "With Modifier" << indexList.at(i).row() - i;
        m_pAnnModel->removeRow(indexList.at(i).row() - i);
    }
    emit triggerRedraw();
    ui->m_tableView_eventTableView->setSelectionMode(QAbstractItemView::ExtendedSelection);

}

//=============================================================================================================

void AnnotationView::addNewAnnotationType()
{
    m_pAnnModel->addNewAnnotationType(QString().number(ui->m_spinBox_addEventType->value()), m_pColordialog->getColor(Qt::black, this));
    //m_pAnnModel->setEventFilterType(QString().number(ui->m_spinBox_addEventType->value()));
    emit triggerRedraw();
}

//=============================================================================================================

void AnnotationView::onSelectedEventsChecked(int iCheckBoxState)
{
    m_iCheckSelectedState = iCheckBoxState;
    m_pAnnModel->setShowSelected(m_iCheckSelectedState);
    //qDebug() << ui->m_tableView_eventTableView->selectionModel()->currentIndex().row();
    //ui->m_tableView_eventTableView->selectionModel()->sle
    //m_pAnnModel
    emit triggerRedraw();
}

//=============================================================================================================

void AnnotationView::disconnectFromModel()
{
    disconnect(m_pAnnModel.data(),&ANSHAREDLIB::AnnotationModel::dataChanged,
            this, &AnnotationView::onDataChanged);
    disconnect(ui->m_checkBox_activateEvents, &QCheckBox::stateChanged,
            this, &AnnotationView::onActiveEventsChecked);
    disconnect(ui->m_checkBox_showSelectedEventsOnly,&QCheckBox::stateChanged,
            this, &AnnotationView::onSelectedEventsChecked);
    disconnect(ui->m_comboBox_filterTypes, &QComboBox::currentTextChanged,
            m_pAnnModel.data(), &ANSHAREDLIB::AnnotationModel::setEventFilterType);
    disconnect(m_pAnnModel.data(), &ANSHAREDLIB::AnnotationModel::updateEventTypes,
            this, &AnnotationView::updateComboBox);
    disconnect(ui->m_pushButton_addEventType, &QPushButton::clicked,
            this, &AnnotationView::addNewAnnotationType);

}

//=============================================================================================================

void AnnotationView::onCurrentSelectedChanged()
{
    m_pAnnModel->clearSelected();
    //qDebug() << "AnnotationView::onCurrentSelectedChanged";
    //qDebug() << ui->m_tableView_eventTableView->selectionModel()->currentIndex().row();
    m_pAnnModel->setSelectedAnn(ui->m_tableView_eventTableView->selectionModel()->currentIndex().row());
//    m_pAnnModel->setSelectedAnn(ui->m_tableView_eventTableView
//    qDebug() << ui->m_tableView_eventTableView->selectionModel()->selectedIndexes();

    for (int i = 0;  i < ui->m_tableView_eventTableView->selectionModel()->selectedRows().size(); i++) {
//        qDebug() << ui->m_tableView_eventTableView->selectionModel()->selectedRows().at(i).row();
        m_pAnnModel->appendSelected(ui->m_tableView_eventTableView->selectionModel()->selectedRows().at(i).row());
    }
}

//=============================================================================================================

void AnnotationView::onSaveButton()
{
#ifdef WASMBUILD
    m_pAnnModel->saveToFile("");
#else
    QString fileName = QFileDialog::getSaveFileName(Q_NULLPTR,
                                                    tr("Save Annotations"), "",
                                                    tr("Event file (*.eve);;All Files (*)"));

    if (fileName.isEmpty()) {
        return;
    }
    qInfo() << "AnnotationView::onSaveButton";

    m_pAnnModel->saveToFile(fileName);
#endif
}

//=============================================================================================================

void AnnotationView::keyPressEvent(QKeyEvent* event)
{
    if(event->key() == Qt::Key_Delete) {
        //qDebug() << "[AnnotationView::keyPressEvent] -- Qt::Key_Delete";
        this->removeAnnotationfromModel();
    }
}

//=============================================================================================================

void AnnotationView::realTimeDataSample(int iValue)
{
    m_pAnnModel->setSelectedAnn(ui->m_tableView_eventTableView->selectionModel()->currentIndex().row());
    //qDebug() << "AnnotationView::realTimeData --" << iValue;
    m_pAnnModel->updateFilteredSample(iValue);
    this->onDataChanged();
}

//=============================================================================================================

void AnnotationView::realTimeDataTime(double dValue)
{
    m_pAnnModel->setSelectedAnn(ui->m_tableView_eventTableView->selectionModel()->currentIndex().row());
    //qDebug() << "AnnotationView::realTimeDataTime" << dValue;
    dValue *= m_pAnnModel->getFreq();
    //qDebug() << "AnnotationView::realTimeDataTime" << dValue;
    int t_iSample = static_cast<int>(dValue);
    m_pAnnModel->updateFilteredSample(t_iSample);
    this->onDataChanged();
}
<|endoftext|>


<commit_before>/*
 * Copyright (c) 2012-2016 Daniele Bartolini and individual contributors.
 * License: https://github.com/taylor001/crown/blob/master/LICENSE
 */

#include "device.h"
#include "array.h"
#include "config.h"
#include "input_manager.h"
#include "log.h"
#include "lua_environment.h"
#include "material_manager.h"
#include "memory.h"
#include "os.h"
#include "resource_loader.h"
#include "resource_manager.h"
#include "resource_package.h"
#include "types.h"
#include "world.h"
#include "filesystem.h"
#include "path.h"
#include "disk_filesystem.h"
#include "physics.h"
#include "audio.h"
#include "profiler.h"
#include "console_server.h"
#include "input_device.h"
#include "sjson.h"
#include "map.h"
#include "vector3.h"

#if CROWN_PLATFORM_ANDROID
	#include "apk_filesystem.h"
#endif // CROWN_PLATFORM_ANDROID

#define MAX_SUBSYSTEMS_HEAP 8 * 1024 * 1024

namespace crown
{

Device::Device(const DeviceOptions& opts)
	: _allocator(default_allocator(), MAX_SUBSYSTEMS_HEAP)
	, _width(0)
	, _height(0)
	, _mouse_curr_x(0)
	, _mouse_curr_y(0)
	, _mouse_last_x(0)
	, _mouse_last_y(0)
	, _is_init(false)
	, _is_running(false)
	, _is_paused(false)
	, _frame_count(0)
	, _last_time(0)
	, _current_time(0)
	, _last_delta_time(0.0f)
	, _time_since_start(0.0)
	, _device_options(opts)
	, _bundle_filesystem(NULL)
	, _boot_package_id(uint64_t(0))
	, _boot_script_id(uint64_t(0))
	, _boot_package(NULL)
	, _lua_environment(NULL)
	, _resource_loader(NULL)
	, _resource_manager(NULL)
	, _input_manager(NULL)
	, _shader_manager(NULL)
	, _material_manager(NULL)
	, _unit_manager(NULL)
	, _worlds(default_allocator())
	, _bgfx_allocator(default_allocator())
{
}

void Device::init()
{
	// Initialize
	CE_LOGI("Initializing Crown Engine %s...", version());

	profiler_globals::init();

#if CROWN_PLATFORM_ANDROID
	_bundle_filesystem = CE_NEW(_allocator, ApkFilesystem)(const_cast<AAssetManager*>(_device_options.asset_manager()));
#else
	_bundle_filesystem = CE_NEW(_allocator, DiskFilesystem)(_device_options.bundle_dir());
#endif // CROWN_PLATFORM_ANDROID

	_resource_loader = CE_NEW(_allocator, ResourceLoader)(*_bundle_filesystem);
	_resource_manager = CE_NEW(_allocator, ResourceManager)(*_resource_loader);

	read_config();

	bgfx::init(bgfx::RendererType::Count
		, BGFX_PCI_ID_NONE
		, 0
		, &_bgfx_callback
		, &_bgfx_allocator
		);

	_shader_manager = CE_NEW(_allocator, ShaderManager)(default_allocator());
	_material_manager = CE_NEW(_allocator, MaterialManager)(default_allocator(), *_resource_manager);
	_input_manager = CE_NEW(_allocator, InputManager)(default_allocator());
	_unit_manager = CE_NEW(_allocator, UnitManager)(default_allocator());

	audio_globals::init();
	physics_globals::init();

	_boot_package = create_resource_package(_boot_package_id);
	_boot_package->load();
	_boot_package->flush();

	_lua_environment = CE_NEW(_allocator, LuaEnvironment)();
	_lua_environment->load_libs();
	_lua_environment->execute((LuaResource*)_resource_manager->get(SCRIPT_TYPE, _boot_script_id));
	_lua_environment->call_global("init", 0);

	_is_init = true;
	_is_running = true;
	_last_time = os::clocktime();

	CE_LOGD("Engine initialized");
}

void Device::shutdown()
{
	CE_ASSERT(_is_init, "Engine is not initialized");

	_is_running = false;
	_is_init = false;

	_lua_environment->call_global("shutdown", 0);
	CE_DELETE(_allocator, _lua_environment);

	_boot_package->unload();
	destroy_resource_package(*_boot_package);

	physics_globals::shutdown();
	audio_globals::shutdown();

	CE_DELETE(_allocator, _unit_manager);
	CE_DELETE(_allocator, _input_manager);
	CE_DELETE(_allocator, _material_manager);
	CE_DELETE(_allocator, _shader_manager);
	CE_DELETE(_allocator, _resource_manager);
	CE_DELETE(_allocator, _resource_loader);
	CE_DELETE(_allocator, _bundle_filesystem);

	bgfx::shutdown();

	profiler_globals::shutdown();

	_allocator.clear();
}

void Device::quit()
{
	_is_running = false;
}

void Device::pause()
{
	_is_paused = true;
	CE_LOGI("Engine paused.");
}

void Device::unpause()
{
	_is_paused = false;
	CE_LOGI("Engine unpaused.");
}

void Device::resolution(uint16_t& width, uint16_t& height)
{
	width = _width;
	height = _height;
}

bool Device::is_running() const
{
	return _is_running;
}

uint64_t Device::frame_count() const
{
	return _frame_count;
}

float Device::last_delta_time() const
{
	return _last_delta_time;
}

double Device::time_since_start() const
{
	return _time_since_start;
}

void Device::update()
{
	while (!process_events() && _is_running)
	{
		_current_time = os::clocktime();
		const int64_t time = _current_time - _last_time;
		_last_time = _current_time;
		const double freq = (double) os::clockfrequency();
		_last_delta_time = time * (1.0 / freq);
		_time_since_start += _last_delta_time;

		profiler_globals::clear();
		console_server_globals::update();

		RECORD_FLOAT("device.dt", _last_delta_time);
		RECORD_FLOAT("device.fps", 1.0f/_last_delta_time);

		if (!_is_paused)
		{
			_resource_manager->complete_requests();
			_lua_environment->call_global("update", 1, ARGUMENT_FLOAT, last_delta_time());
			_lua_environment->call_global("render", 1, ARGUMENT_FLOAT, last_delta_time());
		}

		_input_manager->update();

		const bgfx::Stats* stats = bgfx::getStats();
		RECORD_FLOAT("bgfx.gpu_time", double(stats->gpuTimeEnd - stats->gpuTimeBegin)*1000.0/stats->gpuTimerFreq);
		RECORD_FLOAT("bgfx.cpu_time", double(stats->cpuTimeEnd - stats->cpuTimeBegin)*1000.0/stats->cpuTimerFreq);

		bgfx::frame();
		profiler_globals::flush();

		_lua_environment->clear_temporaries();

		_frame_count++;
	}
}

void Device::render_world(World& world, CameraInstance camera)
{
	world.render(camera);
}

World* Device::create_world()
{
	World* w = CE_NEW(default_allocator(), World)(default_allocator()
		, *_resource_manager
		, *_lua_environment
		, *_material_manager
		, *_unit_manager
		);
	array::push_back(_worlds, w);
	return w;
}

void Device::destroy_world(World& w)
{
	for (uint32_t i = 0, n = array::size(_worlds); i < n; ++i)
	{
		if (&w == _worlds[i])
		{
			CE_DELETE(default_allocator(), &w);
			_worlds[i] = _worlds[n - 1];
			array::pop_back(_worlds);
			return;
		}
	}

	CE_ASSERT(false, "Bad world");
}

ResourcePackage* Device::create_resource_package(StringId64 id)
{
	return CE_NEW(default_allocator(), ResourcePackage)(id, *_resource_manager);
}

void Device::destroy_resource_package(ResourcePackage& rp)
{
	CE_DELETE(default_allocator(), &rp);
}

void Device::reload(StringId64 type, StringId64 name)
{
	const void* old_resource = _resource_manager->get(type, name);
	_resource_manager->reload(type, name);
	const void* new_resource = _resource_manager->get(type, name);

	if (type == SCRIPT_TYPE)
	{
		_lua_environment->execute((const LuaResource*)new_resource);
	}
}

ResourceManager* Device::resource_manager()
{
	return _resource_manager;
}

LuaEnvironment* Device::lua_environment()
{
	return _lua_environment;
}

InputManager* Device::input_manager()
{
	return _input_manager;
}

ShaderManager* Device::shader_manager()
{
	return _shader_manager;
}

MaterialManager* Device::material_manager()
{
	return _material_manager;
}

UnitManager* Device::unit_manager()
{
	return _unit_manager;
}

bool Device::process_events()
{
	OsEvent event;
	bool exit = false;
	InputManager* im = _input_manager;

	const int16_t dt_x = _mouse_curr_x - _mouse_last_x;
	const int16_t dt_y = _mouse_curr_y - _mouse_last_y;
	im->mouse()->set_axis(MouseAxis::CURSOR_DELTA, vector3(dt_x, dt_y, 0.0f));
	_mouse_last_x = _mouse_curr_x;
	_mouse_last_y = _mouse_curr_y;

	while(next_event(event))
	{
		if (event.type == OsEvent::NONE) continue;

		switch (event.type)
		{
			case OsEvent::TOUCH:
			{
				const OsTouchEvent& ev = event.touch;
				switch (ev.type)
				{
					case OsTouchEvent::POINTER:
						im->touch()->set_button_state(ev.pointer_id, ev.pressed);
						break;
					case OsTouchEvent::MOVE:
						im->touch()->set_axis(ev.pointer_id, vector3(ev.x, ev.y, 0.0f));
						break;
					default:
						CE_FATAL("Unknown touch event type");
						break;
				}
				break;
			}
			case OsEvent::MOUSE:
			{
				const OsMouseEvent& ev = event.mouse;
				switch (ev.type)
				{
					case OsMouseEvent::BUTTON:
						im->mouse()->set_button_state(ev.button, ev.pressed);
						break;
					case OsMouseEvent::MOVE:
						_mouse_curr_x = ev.x;
						_mouse_curr_y = ev.y;
						im->mouse()->set_axis(MouseAxis::CURSOR, vector3(ev.x, ev.y, 0.0f));
						break;
					case OsMouseEvent::WHEEL:
						im->mouse()->set_axis(MouseAxis::WHEEL, vector3(0.0f, ev.wheel, 0.0f));
						break;
					default:
						CE_FATAL("Unknown mouse event type");
						break;
				}
				break;
			}
			case OsEvent::KEYBOARD:
			{
				const OsKeyboardEvent& ev = event.keyboard;
				im->keyboard()->set_button_state(ev.button, ev.pressed);
				break;
			}
			case OsEvent::JOYPAD:
			{
				const OsJoypadEvent& ev = event.joypad;
				switch (ev.type)
				{
					case OsJoypadEvent::CONNECTED:
						im->joypad(ev.index)->set_connected(ev.connected);
						break;
					case OsJoypadEvent::BUTTON:
						im->joypad(ev.index)->set_button_state(ev.button, ev.pressed);
						break;
					case OsJoypadEvent::AXIS:
						im->joypad(ev.index)->set_axis(ev.button, vector3(ev.x, ev.y, ev.z));
						break;
					default:
						CE_FATAL("Unknown joypad event");
						break;
				}
				break;
			}
			case OsEvent::METRICS:
			{
				const OsMetricsEvent& ev = event.metrics;
				_width = ev.width;
				_height = ev.height;
				bgfx::reset(ev.width, ev.height, BGFX_RESET_VSYNC);
				break;
			}
			case OsEvent::EXIT:
			{
				exit = true;
				break;
			}
			case OsEvent::PAUSE:
			{
				pause();
				break;
			}
			case OsEvent::RESUME:
			{
				unpause();
				break;
			}
			default:
			{
				CE_FATAL("Unknown Os Event");
				break;
			}
		}
	}

	return exit;
}

void Device::read_config()
{
	TempAllocator4096 ta;
	DynamicString project_path(ta);

	if (_device_options.project() != NULL)
	{
		project_path += _device_options.project();
		project_path += '/';
	}

	project_path += CROWN_BOOT_CONFIG;

	const StringId64 config_name(project_path.c_str());

	_resource_manager->load(CONFIG_TYPE, config_name);
	_resource_manager->flush();
	const char* cfile = (const char*)_resource_manager->get(CONFIG_TYPE, config_name);

	JsonObject config(ta);
	sjson::parse(cfile, config);

	_boot_script_id  = sjson::parse_resource_id(config["boot_script"]);
	_boot_package_id = sjson::parse_resource_id(config["boot_package"]);

	_resource_manager->unload(CONFIG_TYPE, config_name);
}

char _buffer[sizeof(Device)];
Device* _device = NULL;

void init(const DeviceOptions& opts)
{
	CE_ASSERT(_device == NULL, "Crown already initialized");
	_device = new (_buffer) Device(opts);
	_device->init();
}

void update()
{
	_device->update();
}

void shutdown()
{
	_device->shutdown();
	_device->~Device();
	_device = NULL;
}

Device* device()
{
	return crown::_device;
}

} // namespace crown
<commit_msg>Cleanup<commit_after>/*
 * Copyright (c) 2012-2016 Daniele Bartolini and individual contributors.
 * License: https://github.com/taylor001/crown/blob/master/LICENSE
 */

#include "device.h"
#include "array.h"
#include "config.h"
#include "input_manager.h"
#include "log.h"
#include "lua_environment.h"
#include "material_manager.h"
#include "memory.h"
#include "os.h"
#include "resource_loader.h"
#include "resource_manager.h"
#include "resource_package.h"
#include "types.h"
#include "world.h"
#include "filesystem.h"
#include "path.h"
#include "disk_filesystem.h"
#include "physics.h"
#include "audio.h"
#include "profiler.h"
#include "console_server.h"
#include "input_device.h"
#include "sjson.h"
#include "map.h"
#include "vector3.h"

#if CROWN_PLATFORM_ANDROID
	#include "apk_filesystem.h"
#endif // CROWN_PLATFORM_ANDROID

#define MAX_SUBSYSTEMS_HEAP 8 * 1024 * 1024

namespace crown
{

Device::Device(const DeviceOptions& opts)
	: _allocator(default_allocator(), MAX_SUBSYSTEMS_HEAP)
	, _width(0)
	, _height(0)
	, _mouse_curr_x(0)
	, _mouse_curr_y(0)
	, _mouse_last_x(0)
	, _mouse_last_y(0)
	, _is_init(false)
	, _is_running(false)
	, _is_paused(false)
	, _frame_count(0)
	, _last_time(0)
	, _current_time(0)
	, _last_delta_time(0.0f)
	, _time_since_start(0.0)
	, _device_options(opts)
	, _bundle_filesystem(NULL)
	, _boot_package_id(uint64_t(0))
	, _boot_script_id(uint64_t(0))
	, _boot_package(NULL)
	, _lua_environment(NULL)
	, _resource_loader(NULL)
	, _resource_manager(NULL)
	, _input_manager(NULL)
	, _shader_manager(NULL)
	, _material_manager(NULL)
	, _unit_manager(NULL)
	, _worlds(default_allocator())
	, _bgfx_allocator(default_allocator())
{
}

void Device::init()
{
	// Initialize
	CE_LOGI("Initializing Crown Engine %s...", version());

	profiler_globals::init();

#if CROWN_PLATFORM_ANDROID
	_bundle_filesystem = CE_NEW(_allocator, ApkFilesystem)(const_cast<AAssetManager*>(_device_options.asset_manager()));
#else
	_bundle_filesystem = CE_NEW(_allocator, DiskFilesystem)(_device_options.bundle_dir());
#endif // CROWN_PLATFORM_ANDROID

	_resource_loader  = CE_NEW(_allocator, ResourceLoader)(*_bundle_filesystem);
	_resource_manager = CE_NEW(_allocator, ResourceManager)(*_resource_loader);

	read_config();

	bgfx::init(bgfx::RendererType::Count
		, BGFX_PCI_ID_NONE
		, 0
		, &_bgfx_callback
		, &_bgfx_allocator
		);

	_shader_manager   = CE_NEW(_allocator, ShaderManager)(default_allocator());
	_material_manager = CE_NEW(_allocator, MaterialManager)(default_allocator(), *_resource_manager);
	_input_manager    = CE_NEW(_allocator, InputManager)(default_allocator());
	_unit_manager     = CE_NEW(_allocator, UnitManager)(default_allocator());
	_lua_environment  = CE_NEW(_allocator, LuaEnvironment)();

	audio_globals::init();
	physics_globals::init();

	_boot_package = create_resource_package(_boot_package_id);
	_boot_package->load();
	_boot_package->flush();

	_lua_environment->load_libs();
	_lua_environment->execute((LuaResource*)_resource_manager->get(SCRIPT_TYPE, _boot_script_id));
	_lua_environment->call_global("init", 0);

	_is_init = true;
	_is_running = true;
	_last_time = os::clocktime();

	CE_LOGD("Engine initialized");
}

void Device::shutdown()
{
	CE_ASSERT(_is_init, "Engine is not initialized");

	_is_running = false;
	_is_init = false;

	_lua_environment->call_global("shutdown", 0);

	_boot_package->unload();
	destroy_resource_package(*_boot_package);

	physics_globals::shutdown();
	audio_globals::shutdown();

	CE_DELETE(_allocator, _lua_environment);
	CE_DELETE(_allocator, _unit_manager);
	CE_DELETE(_allocator, _input_manager);
	CE_DELETE(_allocator, _material_manager);
	CE_DELETE(_allocator, _shader_manager);
	CE_DELETE(_allocator, _resource_manager);
	CE_DELETE(_allocator, _resource_loader);
	CE_DELETE(_allocator, _bundle_filesystem);

	bgfx::shutdown();

	profiler_globals::shutdown();

	_allocator.clear();
}

void Device::quit()
{
	_is_running = false;
}

void Device::pause()
{
	_is_paused = true;
	CE_LOGI("Engine paused.");
}

void Device::unpause()
{
	_is_paused = false;
	CE_LOGI("Engine unpaused.");
}

void Device::resolution(uint16_t& width, uint16_t& height)
{
	width = _width;
	height = _height;
}

bool Device::is_running() const
{
	return _is_running;
}

uint64_t Device::frame_count() const
{
	return _frame_count;
}

float Device::last_delta_time() const
{
	return _last_delta_time;
}

double Device::time_since_start() const
{
	return _time_since_start;
}

void Device::update()
{
	while (!process_events() && _is_running)
	{
		_current_time = os::clocktime();
		const int64_t time = _current_time - _last_time;
		_last_time = _current_time;
		const double freq = (double) os::clockfrequency();
		_last_delta_time = time * (1.0 / freq);
		_time_since_start += _last_delta_time;

		profiler_globals::clear();
		console_server_globals::update();

		RECORD_FLOAT("device.dt", _last_delta_time);
		RECORD_FLOAT("device.fps", 1.0f/_last_delta_time);

		if (!_is_paused)
		{
			_resource_manager->complete_requests();
			_lua_environment->call_global("update", 1, ARGUMENT_FLOAT, last_delta_time());
			_lua_environment->call_global("render", 1, ARGUMENT_FLOAT, last_delta_time());
		}

		_input_manager->update();

		const bgfx::Stats* stats = bgfx::getStats();
		RECORD_FLOAT("bgfx.gpu_time", double(stats->gpuTimeEnd - stats->gpuTimeBegin)*1000.0/stats->gpuTimerFreq);
		RECORD_FLOAT("bgfx.cpu_time", double(stats->cpuTimeEnd - stats->cpuTimeBegin)*1000.0/stats->cpuTimerFreq);

		bgfx::frame();
		profiler_globals::flush();

		_lua_environment->clear_temporaries();

		_frame_count++;
	}
}

void Device::render_world(World& world, CameraInstance camera)
{
	world.render(camera);
}

World* Device::create_world()
{
	World* w = CE_NEW(default_allocator(), World)(default_allocator()
		, *_resource_manager
		, *_lua_environment
		, *_material_manager
		, *_unit_manager
		);
	array::push_back(_worlds, w);
	return w;
}

void Device::destroy_world(World& w)
{
	for (uint32_t i = 0, n = array::size(_worlds); i < n; ++i)
	{
		if (&w == _worlds[i])
		{
			CE_DELETE(default_allocator(), &w);
			_worlds[i] = _worlds[n - 1];
			array::pop_back(_worlds);
			return;
		}
	}

	CE_ASSERT(false, "Bad world");
}

ResourcePackage* Device::create_resource_package(StringId64 id)
{
	return CE_NEW(default_allocator(), ResourcePackage)(id, *_resource_manager);
}

void Device::destroy_resource_package(ResourcePackage& rp)
{
	CE_DELETE(default_allocator(), &rp);
}

void Device::reload(StringId64 type, StringId64 name)
{
	const void* old_resource = _resource_manager->get(type, name);
	_resource_manager->reload(type, name);
	const void* new_resource = _resource_manager->get(type, name);

	if (type == SCRIPT_TYPE)
	{
		_lua_environment->execute((const LuaResource*)new_resource);
	}
}

ResourceManager* Device::resource_manager()
{
	return _resource_manager;
}

LuaEnvironment* Device::lua_environment()
{
	return _lua_environment;
}

InputManager* Device::input_manager()
{
	return _input_manager;
}

ShaderManager* Device::shader_manager()
{
	return _shader_manager;
}

MaterialManager* Device::material_manager()
{
	return _material_manager;
}

UnitManager* Device::unit_manager()
{
	return _unit_manager;
}

bool Device::process_events()
{
	OsEvent event;
	bool exit = false;
	InputManager* im = _input_manager;

	const int16_t dt_x = _mouse_curr_x - _mouse_last_x;
	const int16_t dt_y = _mouse_curr_y - _mouse_last_y;
	im->mouse()->set_axis(MouseAxis::CURSOR_DELTA, vector3(dt_x, dt_y, 0.0f));
	_mouse_last_x = _mouse_curr_x;
	_mouse_last_y = _mouse_curr_y;

	while(next_event(event))
	{
		if (event.type == OsEvent::NONE) continue;

		switch (event.type)
		{
			case OsEvent::TOUCH:
			{
				const OsTouchEvent& ev = event.touch;
				switch (ev.type)
				{
					case OsTouchEvent::POINTER:
						im->touch()->set_button_state(ev.pointer_id, ev.pressed);
						break;
					case OsTouchEvent::MOVE:
						im->touch()->set_axis(ev.pointer_id, vector3(ev.x, ev.y, 0.0f));
						break;
					default:
						CE_FATAL("Unknown touch event type");
						break;
				}
				break;
			}
			case OsEvent::MOUSE:
			{
				const OsMouseEvent& ev = event.mouse;
				switch (ev.type)
				{
					case OsMouseEvent::BUTTON:
						im->mouse()->set_button_state(ev.button, ev.pressed);
						break;
					case OsMouseEvent::MOVE:
						_mouse_curr_x = ev.x;
						_mouse_curr_y = ev.y;
						im->mouse()->set_axis(MouseAxis::CURSOR, vector3(ev.x, ev.y, 0.0f));
						break;
					case OsMouseEvent::WHEEL:
						im->mouse()->set_axis(MouseAxis::WHEEL, vector3(0.0f, ev.wheel, 0.0f));
						break;
					default:
						CE_FATAL("Unknown mouse event type");
						break;
				}
				break;
			}
			case OsEvent::KEYBOARD:
			{
				const OsKeyboardEvent& ev = event.keyboard;
				im->keyboard()->set_button_state(ev.button, ev.pressed);
				break;
			}
			case OsEvent::JOYPAD:
			{
				const OsJoypadEvent& ev = event.joypad;
				switch (ev.type)
				{
					case OsJoypadEvent::CONNECTED:
						im->joypad(ev.index)->set_connected(ev.connected);
						break;
					case OsJoypadEvent::BUTTON:
						im->joypad(ev.index)->set_button_state(ev.button, ev.pressed);
						break;
					case OsJoypadEvent::AXIS:
						im->joypad(ev.index)->set_axis(ev.button, vector3(ev.x, ev.y, ev.z));
						break;
					default:
						CE_FATAL("Unknown joypad event");
						break;
				}
				break;
			}
			case OsEvent::METRICS:
			{
				const OsMetricsEvent& ev = event.metrics;
				_width = ev.width;
				_height = ev.height;
				bgfx::reset(ev.width, ev.height, BGFX_RESET_VSYNC);
				break;
			}
			case OsEvent::EXIT:
			{
				exit = true;
				break;
			}
			case OsEvent::PAUSE:
			{
				pause();
				break;
			}
			case OsEvent::RESUME:
			{
				unpause();
				break;
			}
			default:
			{
				CE_FATAL("Unknown Os Event");
				break;
			}
		}
	}

	return exit;
}

void Device::read_config()
{
	TempAllocator4096 ta;
	DynamicString project_path(ta);

	if (_device_options.project() != NULL)
	{
		project_path += _device_options.project();
		project_path += '/';
	}

	project_path += CROWN_BOOT_CONFIG;

	const StringId64 config_name(project_path.c_str());

	_resource_manager->load(CONFIG_TYPE, config_name);
	_resource_manager->flush();
	const char* cfile = (const char*)_resource_manager->get(CONFIG_TYPE, config_name);

	JsonObject config(ta);
	sjson::parse(cfile, config);

	_boot_script_id  = sjson::parse_resource_id(config["boot_script"]);
	_boot_package_id = sjson::parse_resource_id(config["boot_package"]);

	_resource_manager->unload(CONFIG_TYPE, config_name);
}

char _buffer[sizeof(Device)];
Device* _device = NULL;

void init(const DeviceOptions& opts)
{
	CE_ASSERT(_device == NULL, "Crown already initialized");
	_device = new (_buffer) Device(opts);
	_device->init();
}

void update()
{
	_device->update();
}

void shutdown()
{
	_device->shutdown();
	_device->~Device();
	_device = NULL;
}

Device* device()
{
	return crown::_device;
}

} // namespace crown
<|endoftext|>