<commit_before>// -*- Mode: c++-mode; c-basic-offset: 2; indent-tabs-mode: t; tab-width: 2; -*-
//
// Copyright (C) 2003 Grzegorz Jaskiewicz 	<gj at pointblue.com.pl>
// Copyright (C) 2002-2003 Zack Rusin 	<zack@kde.org>
//
// gaduprotocol.cpp
//
// This program is free software; you can redistribute it and/or
// modify it under the terms of the GNU General Public License
// as published by the Free Software Foundation; either version 2
// of the License, or (at your option) any later version.
//
// This program 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 General Public License for more details.
//
// You should have received a copy of the GNU General Public License
// along with this program; if not, write to the Free Software
// Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA
// 02111-1307, USA.

#include <kdebug.h>
#include <kgenericfactory.h>
#include <kconfig.h>

#include <libgadu.h>

#include "gaduaccount.h"
#include "gaducontact.h"
#include "gaduprotocol.h"

#include "gadueditaccount.h"
#include "gaduaddcontactpage.h"

#include "kopeteaccountmanager.h"
#include "kopeteaccount.h"
#include "kopetemetacontact.h"
#include "kopeteglobal.h"
#include "kopeteonlinestatusmanager.h"

typedef KGenericFactory<GaduProtocol> GaduProtocolFactory;

K_EXPORT_COMPONENT_FACTORY( kopete_gadu, KGenericFactory<GaduProtocol>( "kopete_gadu" )  )

GaduProtocol* GaduProtocol::protocolStatic_ = 0L;

GaduProtocol::GaduProtocol( QObject* parent, const char* name, const QStringList& )
:Kopete::Protocol( GaduProtocolFactory::instance(), parent, name ),
			propFirstName(Kopete::Global::Properties::self()->firstName()),
			propLastName(Kopete::Global::Properties::self()->lastName()),
			propEmail(Kopete::Global::Properties::self()->emailAddress()),
			propAwayMessage(Kopete::Global::Properties::self()->awayMessage()),
			propPhoneNr(Kopete::Global::Properties::self()->privatePhone()),
			defaultAccount_( 0 ),
			gaduStatusBlocked_( Kopete::OnlineStatus::Away, GG_STATUS_BLOCKED, this, GG_STATUS_BLOCKED,
				"gg_ignored", i18n( "Blocked" ) ),
			gaduStatusOffline_( Kopete::OnlineStatus::Offline, GG_STATUS_NOT_AVAIL, this, GG_STATUS_NOT_AVAIL,
				"gg_offline", i18n( "Offline" ) , i18n( "O&ffline" ) , Kopete::OnlineStatusManager::Offline ),
			gaduStatusOfflineDescr_( Kopete::OnlineStatus::Away, GG_STATUS_NOT_AVAIL_DESCR, this, GG_STATUS_NOT_AVAIL_DESCR,
				QStringList::split( '|', "contact_away_overlay|gg_description_overlay" ), i18n( "Offline" ), i18n( "A&way" ) , Kopete::OnlineStatusManager::Offline ),
			gaduStatusBusy_(Kopete::OnlineStatus::Away, GG_STATUS_BUSY, this, GG_STATUS_BUSY,
				"contact_away_overlay", i18n( "Busy" ) , i18n( "B&usy" ) , Kopete::OnlineStatusManager::Busy ),
			gaduStatusBusyDescr_(Kopete::OnlineStatus::Away, GG_STATUS_BUSY_DESCR, this, GG_STATUS_BUSY_DESCR,
				QStringList::split( '|', "contact_away_overlay|gg_description_overlay" ), i18n( "Busy" ) , i18n( "B&usy" ) , Kopete::OnlineStatusManager::Idle ),
			gaduStatusInvisible_( Kopete::OnlineStatus::Invisible, GG_STATUS_INVISIBLE, this, GG_STATUS_INVISIBLE,
				"contact_invisible_overlay", i18n( "Invisible" ) , i18n( "I&nvisible" ) , Kopete::OnlineStatusManager::Invisible),
			gaduStatusInvisibleDescr_(Kopete::OnlineStatus::Invisible, GG_STATUS_INVISIBLE_DESCR, this, GG_STATUS_INVISIBLE_DESCR,
				QStringList::split( '|', "contact_invisible_overlay|gg_description_overlay" ), i18n( "Invisible" ) , i18n( "I&nvisible" )),
			gaduStatusAvail_(Kopete::OnlineStatus::Online, GG_STATUS_AVAIL, this, GG_STATUS_AVAIL,
				QString::null, i18n( "Online" ) , i18n( "&Online" ) ,  Kopete::OnlineStatusManager::Online ),
			gaduStatusAvailDescr_(Kopete::OnlineStatus::Online, GG_STATUS_AVAIL_DESCR, this, GG_STATUS_AVAIL_DESCR,
				"gg_description_overlay", i18n( "Online" ) , i18n( "&Online" )),
			gaduConnecting_(Kopete::OnlineStatus::Offline, GG_STATUS_CONNECTING, this, GG_STATUS_CONNECTING,
				"gg_con", i18n( "Connecting" ) )
{
	if ( protocolStatic_ ) {
		kdDebug(14100)<<"####"<<"GaduProtocol already initialized"<<endl;
	}
	else {
		protocolStatic_ = this;
	}

	addAddressBookField( "messaging/gadu", Kopete::Plugin::MakeIndexField );

	setCapabilities( Kopete::Protocol::RichFormatting | Kopete::Protocol::RichFgColor );

}

GaduProtocol::~GaduProtocol()
{
	protocolStatic_ = 0L;
}

GaduProtocol*
GaduProtocol::protocol()
{
	return protocolStatic_;
}

AddContactPage*
GaduProtocol::createAddContactWidget( QWidget* parent, Kopete::Account* account )
{
	return new GaduAddContactPage( static_cast<GaduAccount*>( account ), parent );
}

void
GaduProtocol::settingsChanged()
{
}

Kopete::Contact *
GaduProtocol::deserializeContact( Kopete::MetaContact* metaContact,
				const QMap<QString, QString>& serializedData,
				const QMap<QString, QString>&  /* addressBookData */ )
{

	const QString aid	= serializedData[ "accountId" ];
	const QString cid	= serializedData[ "contactId" ];
	const QString dn	= serializedData[ "displayName" ];

	QDict<Kopete::Account> daccounts = Kopete::AccountManager::self()->accounts( this );

	Kopete::Account* account = daccounts[ aid ];
	if (!account) {
		account = createNewAccount(aid);
	}

	GaduAccount* gaccount = static_cast<GaduAccount *>( account );

	GaduContact* contact = new GaduContact( cid.toUInt(), dn, account, metaContact );

	contact->setParentIdentity( aid );
	gaccount->addNotify( cid.toUInt() );

	contact->setProperty( propEmail, serializedData["email"] );
	contact->setProperty( propFirstName, serializedData["FirstName"] );
	contact->setProperty( propLastName, serializedData["SecondName"] );
	contact->setProperty( propPhoneNr, serializedData["telephone"] );
	contact->setIgnored(serializedData["ignored"] == "true");
	return contact;
}

uint
GaduProtocol::statusToWithDescription( Kopete::OnlineStatus status )
{

	if ( status == gaduStatusOffline_ || status == gaduStatusOfflineDescr_ ) {
		return GG_STATUS_NOT_AVAIL_DESCR;
	}

	if ( status == gaduStatusBusyDescr_ || status == gaduStatusBusy_ ){
		return GG_STATUS_BUSY_DESCR;
	}

	if ( status == gaduStatusInvisibleDescr_ || status == gaduStatusInvisible_ ){
		return GG_STATUS_INVISIBLE_DESCR;
	}

	return GG_STATUS_AVAIL_DESCR;
}

uint
GaduProtocol::statusToWithoutDescription( Kopete::OnlineStatus status )
{
        if ( status == gaduStatusOffline_ || status == gaduStatusOfflineDescr_ ) {
		return GG_STATUS_NOT_AVAIL;
	}

	if ( status == gaduStatusBusyDescr_ || status == gaduStatusBusy_ ){
		return GG_STATUS_BUSY;
	}

	if ( status == gaduStatusInvisibleDescr_ || status == gaduStatusInvisible_ ){
		return GG_STATUS_INVISIBLE;
	}

	return GG_STATUS_AVAIL;
}

bool
GaduProtocol::statusWithDescription( uint status )
{
	switch( status ) {
		case GG_STATUS_NOT_AVAIL:
		case GG_STATUS_BUSY:
		case GG_STATUS_INVISIBLE:
		case GG_STATUS_AVAIL:
		case GG_STATUS_CONNECTING:
		case GG_STATUS_BLOCKED:
			return false;
		case GG_STATUS_INVISIBLE_DESCR:
		case GG_STATUS_NOT_AVAIL_DESCR:
		case GG_STATUS_BUSY_DESCR:
		case GG_STATUS_AVAIL_DESCR:
			return true;
	}
	return false;
}

Kopete::OnlineStatus
GaduProtocol::convertStatus( uint status ) const
{
	switch( status ) {
		case GG_STATUS_NOT_AVAIL:
			return gaduStatusOffline_;
		case GG_STATUS_NOT_AVAIL_DESCR:
			return gaduStatusOfflineDescr_;
		case GG_STATUS_BUSY:
			return gaduStatusBusy_;
		case GG_STATUS_BUSY_DESCR:
			return gaduStatusBusyDescr_;
		case GG_STATUS_INVISIBLE:
			return gaduStatusInvisible_;
		case GG_STATUS_INVISIBLE_DESCR:
			return gaduStatusInvisibleDescr_;
		case GG_STATUS_AVAIL:
			return gaduStatusAvail_;
		case GG_STATUS_AVAIL_DESCR:
			return gaduStatusAvailDescr_;
		case GG_STATUS_CONNECTING:
			return gaduConnecting_;
		case GG_STATUS_BLOCKED:
			return gaduStatusBlocked_;
		default:
			return gaduStatusOffline_;
	}
}

Kopete::Account*
GaduProtocol::createNewAccount( const QString& accountId )
{
	defaultAccount_ = new GaduAccount( this, accountId );
	return defaultAccount_ ;
}

KopeteEditAccountWidget*
GaduProtocol::createEditAccountWidget( Kopete::Account* account, QWidget* parent )
{
	return( new GaduEditAccount( this, account, parent ) );
}

#include "gaduprotocol.moc"
<commit_msg><commit_after>// -*- Mode: c++-mode; c-basic-offset: 2; indent-tabs-mode: t; tab-width: 2; -*-
//
// Copyright (C) 2003 Grzegorz Jaskiewicz 	<gj at pointblue.com.pl>
// Copyright (C) 2002-2003 Zack Rusin 	<zack@kde.org>
//
// gaduprotocol.cpp
//
// This program is free software; you can redistribute it and/or
// modify it under the terms of the GNU General Public License
// as published by the Free Software Foundation; either version 2
// of the License, or (at your option) any later version.
//
// This program 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 General Public License for more details.
//
// You should have received a copy of the GNU General Public License
// along with this program; if not, write to the Free Software
// Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA
// 02111-1307, USA.

#include <kdebug.h>
#include <kgenericfactory.h>
#include <kconfig.h>

#include <libgadu.h>

#include "gaduaccount.h"
#include "gaducontact.h"
#include "gaduprotocol.h"

#include "gadueditaccount.h"
#include "gaduaddcontactpage.h"

#include "kopeteaccountmanager.h"
#include "kopeteaccount.h"
#include "kopetemetacontact.h"
#include "kopeteglobal.h"
#include "kopeteonlinestatusmanager.h"

typedef KGenericFactory<GaduProtocol> GaduProtocolFactory;

K_EXPORT_COMPONENT_FACTORY( kopete_gadu, KGenericFactory<GaduProtocol>( "kopete_gadu" )  )

GaduProtocol* GaduProtocol::protocolStatic_ = 0L;

GaduProtocol::GaduProtocol( QObject* parent, const char* name, const QStringList& )
:Kopete::Protocol( GaduProtocolFactory::instance(), parent, name ),
			propFirstName(Kopete::Global::Properties::self()->firstName()),
			propLastName(Kopete::Global::Properties::self()->lastName()),
			propEmail(Kopete::Global::Properties::self()->emailAddress()),
			propAwayMessage(Kopete::Global::Properties::self()->awayMessage()),
			propPhoneNr(Kopete::Global::Properties::self()->privatePhone()),
			defaultAccount_( 0 ),
			gaduStatusBlocked_( Kopete::OnlineStatus::Away, GG_STATUS_BLOCKED, this, GG_STATUS_BLOCKED,
				"gg_ignored", i18n( "Blocked" ) ),
			gaduStatusOffline_( Kopete::OnlineStatus::Offline, GG_STATUS_NOT_AVAIL, this, GG_STATUS_NOT_AVAIL,
				"gg_offline", i18n( "Offline" ) , i18n( "O&ffline" ) , Kopete::OnlineStatusManager::Offline ),
			gaduStatusOfflineDescr_( Kopete::OnlineStatus::Offline, GG_STATUS_NOT_AVAIL_DESCR, this, GG_STATUS_NOT_AVAIL_DESCR,
				QStringList::split( '|', "contact_away_overlay|gg_description_overlay" ), i18n( "Offline" ), i18n( "A&way" ) , Kopete::OnlineStatusManager::Offline ),
			gaduStatusBusy_(Kopete::OnlineStatus::Away, GG_STATUS_BUSY, this, GG_STATUS_BUSY,
				"contact_away_overlay", i18n( "Busy" ) , i18n( "B&usy" ) , Kopete::OnlineStatusManager::Busy ),
			gaduStatusBusyDescr_(Kopete::OnlineStatus::Away, GG_STATUS_BUSY_DESCR, this, GG_STATUS_BUSY_DESCR,
				QStringList::split( '|', "contact_away_overlay|gg_description_overlay" ), i18n( "Busy" ) , i18n( "B&usy" ) , Kopete::OnlineStatusManager::Idle ),
			gaduStatusInvisible_( Kopete::OnlineStatus::Invisible, GG_STATUS_INVISIBLE, this, GG_STATUS_INVISIBLE,
				"contact_invisible_overlay", i18n( "Invisible" ) , i18n( "I&nvisible" ) , Kopete::OnlineStatusManager::Invisible),
			gaduStatusInvisibleDescr_(Kopete::OnlineStatus::Invisible, GG_STATUS_INVISIBLE_DESCR, this, GG_STATUS_INVISIBLE_DESCR,
				QStringList::split( '|', "contact_invisible_overlay|gg_description_overlay" ), i18n( "Invisible" ) , i18n( "I&nvisible" )),
			gaduStatusAvail_(Kopete::OnlineStatus::Online, GG_STATUS_AVAIL, this, GG_STATUS_AVAIL,
				QString::null, i18n( "Online" ) , i18n( "&Online" ) ,  Kopete::OnlineStatusManager::Online ),
			gaduStatusAvailDescr_(Kopete::OnlineStatus::Online, GG_STATUS_AVAIL_DESCR, this, GG_STATUS_AVAIL_DESCR,
				"gg_description_overlay", i18n( "Online" ) , i18n( "&Online" )),
			gaduConnecting_(Kopete::OnlineStatus::Offline, GG_STATUS_CONNECTING, this, GG_STATUS_CONNECTING,
				"gg_con", i18n( "Connecting" ) )
{
	if ( protocolStatic_ ) {
		kdDebug(14100)<<"####"<<"GaduProtocol already initialized"<<endl;
	}
	else {
		protocolStatic_ = this;
	}

	addAddressBookField( "messaging/gadu", Kopete::Plugin::MakeIndexField );

	setCapabilities( Kopete::Protocol::RichFormatting | Kopete::Protocol::RichFgColor );

}

GaduProtocol::~GaduProtocol()
{
	protocolStatic_ = 0L;
}

GaduProtocol*
GaduProtocol::protocol()
{
	return protocolStatic_;
}

AddContactPage*
GaduProtocol::createAddContactWidget( QWidget* parent, Kopete::Account* account )
{
	return new GaduAddContactPage( static_cast<GaduAccount*>( account ), parent );
}

void
GaduProtocol::settingsChanged()
{
}

Kopete::Contact *
GaduProtocol::deserializeContact( Kopete::MetaContact* metaContact,
				const QMap<QString, QString>& serializedData,
				const QMap<QString, QString>&  /* addressBookData */ )
{

	const QString aid	= serializedData[ "accountId" ];
	const QString cid	= serializedData[ "contactId" ];
	const QString dn	= serializedData[ "displayName" ];

	QDict<Kopete::Account> daccounts = Kopete::AccountManager::self()->accounts( this );

	Kopete::Account* account = daccounts[ aid ];
	if (!account) {
		account = createNewAccount(aid);
	}

	GaduAccount* gaccount = static_cast<GaduAccount *>( account );

	GaduContact* contact = new GaduContact( cid.toUInt(), dn, account, metaContact );

	contact->setParentIdentity( aid );
	gaccount->addNotify( cid.toUInt() );

	contact->setProperty( propEmail, serializedData["email"] );
	contact->setProperty( propFirstName, serializedData["FirstName"] );
	contact->setProperty( propLastName, serializedData["SecondName"] );
	contact->setProperty( propPhoneNr, serializedData["telephone"] );
	contact->setIgnored(serializedData["ignored"] == "true");
	return contact;
}

uint
GaduProtocol::statusToWithDescription( Kopete::OnlineStatus status )
{

	if ( status == gaduStatusOffline_ || status == gaduStatusOfflineDescr_ ) {
		return GG_STATUS_NOT_AVAIL_DESCR;
	}

	if ( status == gaduStatusBusyDescr_ || status == gaduStatusBusy_ ){
		return GG_STATUS_BUSY_DESCR;
	}

	if ( status == gaduStatusInvisibleDescr_ || status == gaduStatusInvisible_ ){
		return GG_STATUS_INVISIBLE_DESCR;
	}

	return GG_STATUS_AVAIL_DESCR;
}

uint
GaduProtocol::statusToWithoutDescription( Kopete::OnlineStatus status )
{
        if ( status == gaduStatusOffline_ || status == gaduStatusOfflineDescr_ ) {
		return GG_STATUS_NOT_AVAIL;
	}

	if ( status == gaduStatusBusyDescr_ || status == gaduStatusBusy_ ){
		return GG_STATUS_BUSY;
	}

	if ( status == gaduStatusInvisibleDescr_ || status == gaduStatusInvisible_ ){
		return GG_STATUS_INVISIBLE;
	}

	return GG_STATUS_AVAIL;
}

bool
GaduProtocol::statusWithDescription( uint status )
{
	switch( status ) {
		case GG_STATUS_NOT_AVAIL:
		case GG_STATUS_BUSY:
		case GG_STATUS_INVISIBLE:
		case GG_STATUS_AVAIL:
		case GG_STATUS_CONNECTING:
		case GG_STATUS_BLOCKED:
			return false;
		case GG_STATUS_INVISIBLE_DESCR:
		case GG_STATUS_NOT_AVAIL_DESCR:
		case GG_STATUS_BUSY_DESCR:
		case GG_STATUS_AVAIL_DESCR:
			return true;
	}
	return false;
}

Kopete::OnlineStatus
GaduProtocol::convertStatus( uint status ) const
{
	switch( status ) {
		case GG_STATUS_NOT_AVAIL:
			return gaduStatusOffline_;
		case GG_STATUS_NOT_AVAIL_DESCR:
			return gaduStatusOfflineDescr_;
		case GG_STATUS_BUSY:
			return gaduStatusBusy_;
		case GG_STATUS_BUSY_DESCR:
			return gaduStatusBusyDescr_;
		case GG_STATUS_INVISIBLE:
			return gaduStatusInvisible_;
		case GG_STATUS_INVISIBLE_DESCR:
			return gaduStatusInvisibleDescr_;
		case GG_STATUS_AVAIL:
			return gaduStatusAvail_;
		case GG_STATUS_AVAIL_DESCR:
			return gaduStatusAvailDescr_;
		case GG_STATUS_CONNECTING:
			return gaduConnecting_;
		case GG_STATUS_BLOCKED:
			return gaduStatusBlocked_;
		default:
			return gaduStatusOffline_;
	}
}

Kopete::Account*
GaduProtocol::createNewAccount( const QString& accountId )
{
	defaultAccount_ = new GaduAccount( this, accountId );
	return defaultAccount_ ;
}

KopeteEditAccountWidget*
GaduProtocol::createEditAccountWidget( Kopete::Account* account, QWidget* parent )
{
	return( new GaduEditAccount( this, account, parent ) );
}

#include "gaduprotocol.moc"
<|endoftext|>


<commit_before>/* IBM_PROLOG_BEGIN_TAG                                                   */
/* This is an automatically generated prolog.                             */
/*                                                                        */
/* $Source: hwpf/fapi2/include/ffdc.H $                                   */
/*                                                                        */
/* IBM CONFIDENTIAL                                                       */
/*                                                                        */
/* EKB Project                                                            */
/*                                                                        */
/* COPYRIGHT 2011,2016                                                    */
/* [+] International Business Machines Corp.                              */
/*                                                                        */
/*                                                                        */
/* The source code for this program is not published or otherwise         */
/* divested of its trade secrets, irrespective of what has been           */
/* deposited with the U.S. Copyright Office.                              */
/*                                                                        */
/* IBM_PROLOG_END_TAG                                                     */
/**
 *  @file ffdc.H
 *  @brief Defines the FirstFailureData class
 */

#ifndef FAPI2_FFDC_H_
#define FAPI2_FFDC_H_

#include <memory>
#include <hwp_return_codes.H>
#include <return_code_defs.H>
#include <plat_trace.H>
#include <error_info.H>
#include <target.H>

using fapi2::TARGET_TYPE_ALL;

namespace fapi2
{
///
/// @brief Check the type of a variable
///
/// This function can be called to check that a variable type is as expected
/// @note This mechanism will allow for cast ctor's which other static type
/// checking might not.
///
template<typename T>
inline
void checkType(const T&) {}

class ReturnCode;

///
/// @class FirstFailureData
///
/// This class provides storage and methods for creating and manipulating
/// FFDC.
/// It is not needed on all platforms - platforms which need this class have
/// specified this by forcing their fapi2::ReturnCode to be a subclass of
/// this class.
///
template< class R = fapi2::ReturnCode >
class FirstFailureData
{
    public:

        ///
        /// @brief Default constructor.
        /// @note We don't create our error info by default. It will be created
        /// when its needed in the setHwpError() method. Note that dereferencing
        /// the error info without first calling setHwpError() will create a
        //  problem.
        ///
        FirstFailureData(void):
            iv_info( nullptr ), iv_platDataPtr(nullptr)
        {}

        ///
        /// @brief Copy Constructor
        ///
        /// @param[in] i_right Reference to FirstFailureData to copy
        /// @note Generates default copy constructor - no deep pointer
        /// copies necessary.
        ///
        FirstFailureData(const FirstFailureData& i_right) = default;

        ///
        /// @brief Destructor
        ///
        ~FirstFailureData(void) = default;

        ///
        /// @brief Assignment Operator.
        ///
        /// @param[in] i_right Reference to FirstFailureData to assign from.
        /// @return Reference to 'this' FirstFailureData
        ///
        FirstFailureData& operator=(const FirstFailureData& i_right) = default;

        ///
        /// @brief Sets a HWP error. Sets the rcValue to the supplied value (from
        ///      the HwpFirstFailureData enumeration) and deletes any
        /// associated data.
        ///
        /// HWP code must call the FAPI_SET_HWP_ERROR macro rather than this
        /// function
        /// directly to generate an error so that any error information is
        /// automatically added to the FirstFailureData
        ///
        /// @param[in] i_rcValue Error value to set
        ///
        inline void _setHwpError(const fapi2::HwpReturnCode i_rcValue)
        {
            FAPI_ERR("_setHwpError: Creating HWP error 0x%x", i_rcValue);
            static_cast<R*>(this)->operator=(i_rcValue);

            // Forget about any associated data (this is a new error)
            iv_info.reset(new ErrorInfo());
        }

        ///
        /// @return void *. Pointer to error info data. If NULL then no data
        ///
        void* getData(void) const;

        ///
        /// @brief Get a pointer to any error info and release ownership from
        ///      FirstFailureData. The caller is responsible for deletion.
        ///
        /// This is called by PLAT. The expected use-case is to retrieve a
        /// platform error log.
        ///
        /// @return void*. Pointer to any Error data. If NULL then no data
        ///
        inline void* releaseData(void)
        {
            void* l_pData = iv_info;
            iv_info = NULL;
            return l_pData;
        }

        ///
        /// @brief Add ErrorInfo
        ///
        /// This is called by the FAPI_SET_HWP_ERROR and macro to add ErrorInfo
        /// to the FirstFailureData when a HWP generates an error. The function
        /// is designed to add all the ErrorInfo at once rather than the
        /// FAPI_SET_HWP_ERROR macro making multiple function calls to add each
        /// piece of ErrorInfo individually in order to minimize code size
        ///
        /// @param[in] i_pObjects Pointer to array of const pointers to const
        ///     objects that are referred to by ErrorInfoEntry objects
        /// @param[in] i_pEntries Pointer to array of ErrorInfoEntry objects
        ///     defining the ErrorInfo that needs to be added
        /// @param[in] i_count    Number of ErrorInfoEntry entries
        ///
        void addErrorInfo(const void* const* i_pObjects,
                          const ErrorInfoEntry* i_pEntries,
                          const uint8_t i_count);

        ///
        /// @brief Get a pointer to any ErrorInfo
        ///
        /// This is called by PLAT to find information about an error
        ///
        /// @return ErrorInfo *. Pointer to any ErrorInfo. If NULL then no info
        ///
        inline const fapi2::ErrorInfo* getErrorInfo(void) const
        {
            return iv_info.get();
        }

        ///
        /// @brief Forgets about any associated data (PlatData and ErrorInfo)
        ///
        /// If this is the only FirstFailureData pointing to the data then the
        /// data is deleted
        ///
        inline void forgetData(void)
        {
            iv_info = nullptr;
        }

        ///
        /// @brief Returns the platform data pointer value to the caller.
        ///
        inline void* getPlatDataPtr()
        {
            return iv_platDataPtr;
        };

        ///
        /// @brief Sets objects platform data pointer to the passed in value.
        ///
        ///
        inline void  setPlatDataPtr( void* i_ptr )
        {
            static_cast<R*>(this)->operator=(FAPI2_RC_PLAT_ERR_SEE_DATA);
            iv_platDataPtr = i_ptr;
        };

    private:

        // Pointer to the error info
        std::shared_ptr<ErrorInfo> iv_info;

        // free format data, to be used by the platform
        void*    iv_platDataPtr;
};

}
#endif // FAPI2_FFDC_H_
<commit_msg>Add new addErrorInfo method to enable collectFfdc and collectRegFfdc<commit_after>/* IBM_PROLOG_BEGIN_TAG                                                   */
/* This is an automatically generated prolog.                             */
/*                                                                        */
/* $Source: hwpf/fapi2/include/ffdc.H $                                   */
/*                                                                        */
/* IBM CONFIDENTIAL                                                       */
/*                                                                        */
/* EKB Project                                                            */
/*                                                                        */
/* COPYRIGHT 2011,2016                                                    */
/* [+] International Business Machines Corp.                              */
/*                                                                        */
/*                                                                        */
/* The source code for this program is not published or otherwise         */
/* divested of its trade secrets, irrespective of what has been           */
/* deposited with the U.S. Copyright Office.                              */
/*                                                                        */
/* IBM_PROLOG_END_TAG                                                     */
/**
 *  @file ffdc.H
 *  @brief Defines the FirstFailureData class
 */

#ifndef FAPI2_FFDC_H_
#define FAPI2_FFDC_H_

#include <memory>
#include <hwp_return_codes.H>
#include <return_code_defs.H>
#include <plat_trace.H>
#include <error_info.H>
#include <target.H>

using fapi2::TARGET_TYPE_ALL;

namespace fapi2
{
///
/// @brief Check the type of a variable
///
/// This function can be called to check that a variable type is as expected
/// @note This mechanism will allow for cast ctor's which other static type
/// checking might not.
///
template<typename T>
inline
void checkType(const T&) {}

class ReturnCode;

///
/// @class FirstFailureData
///
/// This class provides storage and methods for creating and manipulating
/// FFDC.
/// It is not needed on all platforms - platforms which need this class have
/// specified this by forcing their fapi2::ReturnCode to be a subclass of
/// this class.
///
template< class R = fapi2::ReturnCode >
class FirstFailureData
{
    public:

        ///
        /// @brief Default constructor.
        /// @note We don't create our error info by default. It will be created
        /// when its needed in the setHwpError() method. Note that dereferencing
        /// the error info without first calling setHwpError() will create a
        //  problem.
        ///
        FirstFailureData(void):
            iv_info( nullptr ), iv_platDataPtr(nullptr)
        {}

        ///
        /// @brief Copy Constructor
        ///
        /// @param[in] i_right Reference to FirstFailureData to copy
        /// @note Generates default copy constructor - no deep pointer
        /// copies necessary.
        ///
        FirstFailureData(const FirstFailureData& i_right) = default;

        ///
        /// @brief Destructor
        ///
        ~FirstFailureData(void) = default;

        ///
        /// @brief Assignment Operator.
        ///
        /// @param[in] i_right Reference to FirstFailureData to assign from.
        /// @return Reference to 'this' FirstFailureData
        ///
        FirstFailureData& operator=(const FirstFailureData& i_right) = default;

        ///
        /// @brief Sets a HWP error. Sets the rcValue to the supplied value (from
        ///      the HwpFirstFailureData enumeration) and deletes any
        /// associated data.
        ///
        /// HWP code must call the FAPI_SET_HWP_ERROR macro rather than this
        /// function
        /// directly to generate an error so that any error information is
        /// automatically added to the FirstFailureData
        ///
        /// @param[in] i_rcValue Error value to set
        ///
        inline void _setHwpError(const fapi2::HwpReturnCode i_rcValue)
        {
            FAPI_ERR("_setHwpError: Creating HWP error 0x%x", i_rcValue);
            static_cast<R*>(this)->operator=(i_rcValue);

            // Forget about any associated data (this is a new error)
            iv_info.reset(new ErrorInfo());
        }

        ///
        /// @return void *. Pointer to error info data. If NULL then no data
        ///
        void* getData(void) const;

        ///
        /// @brief Get a pointer to any error info and release ownership from
        ///      FirstFailureData. The caller is responsible for deletion.
        ///
        /// This is called by PLAT. The expected use-case is to retrieve a
        /// platform error log.
        ///
        /// @return void*. Pointer to any Error data. If NULL then no data
        ///
        inline void* releaseData(void)
        {
            void* l_pData = iv_info;
            iv_info = NULL;
            return l_pData;
        }

        ///
        /// @brief Add ErrorInfo
        ///
        /// This is called by the FAPI_SET_HWP_ERROR and macro to add ErrorInfo
        /// to the FirstFailureData when a HWP generates an error. The function
        /// is designed to add all the ErrorInfo at once rather than the
        /// FAPI_SET_HWP_ERROR macro making multiple function calls to add each
        /// piece of ErrorInfo individually in order to minimize code size
        ///
        /// @param[in] i_pObjects Pointer to array of const pointers to const
        ///     objects that are referred to by ErrorInfoEntry objects
        /// @param[in] i_pEntries Pointer to array of ErrorInfoEntry objects
        ///     defining the ErrorInfo that needs to be added
        /// @param[in] i_count    Number of ErrorInfoEntry entries
        ///
        void addErrorInfo(const void* const* i_pObjects,
                          const ErrorInfoEntry* i_pEntries,
                          const uint8_t i_count);

        ///
        /// @brief Add ErrorInfo
        ///
        /// This is called by the collectFfdc and collectRegFfdc functions
        /// following the call to actually collect the ffdc data, the ffdc
        /// collection functions return a vector of shared pointers to the
        /// ErrorInfoFfdc objects
        ///
        /// @param[in] i_errorInfo - vector of shared pointers to
        ///                          errorInfoFfdc objects
        ///
        inline void addErrorInfo(std::vector<std::shared_ptr<ErrorInfoFfdc>>& i_errorInfo)
        {
            for( auto p : i_errorInfo )
            {
                iv_info->iv_ffdcs.push_back(p);
            }
        };

        ///

        ///
        /// @brief Get a pointer to any ErrorInfo
        ///
        /// This is called by PLAT to find information about an error
        ///
        /// @return ErrorInfo *. Pointer to any ErrorInfo. If NULL then no info
        ///
        inline const fapi2::ErrorInfo* getErrorInfo(void) const
        {
            return iv_info.get();
        }

        ///
        /// @brief Forgets about any associated data (PlatData and ErrorInfo)
        ///
        /// If this is the only FirstFailureData pointing to the data then the
        /// data is deleted
        ///
        inline void forgetData(void)
        {
            iv_info = nullptr;
        }

        ///
        /// @brief Returns the platform data pointer value to the caller.
        ///
        inline void* getPlatDataPtr()
        {
            return iv_platDataPtr;
        };

        ///
        /// @brief Sets objects platform data pointer to the passed in value.
        ///
        ///
        inline void  setPlatDataPtr( void* i_ptr )
        {
            static_cast<R*>(this)->operator=(FAPI2_RC_PLAT_ERR_SEE_DATA);
            iv_platDataPtr = i_ptr;
        };

    private:

        // Pointer to the error info
        std::shared_ptr<ErrorInfo> iv_info;

        // free format data, to be used by the platform
        void*    iv_platDataPtr;
};

}
#endif // FAPI2_FFDC_H_
<|endoftext|>


<commit_before>// test/testcrypto.cc
// Test /libdissent/crypto.{hpp cc}
//
// Author: Fei Huang <felix.fei.huang _AT_ gmail *DOT* com>

/* ====================================================================
 * Dissent: Accountable Group Anonymity
 * Copyright (c) 2010 Yale University.
 *
 * This library is free software; you can redistribute it and/or
 * modify it under the terms of the GNU Lesser General Public
 * License as published by the Free Software Foundation; either
 * version 2.1 of the License, or (at your option) any later version.
 *
 * This library is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 * Lesser General Public License for more details.
 *
 * You should have received a copy of the GNU Lesser General Public
 * License along with this library; if not, write to
 *
 *   Free Software Foundation, Inc.,
 *   51 Franklin Street, Fifth Floor,
 *   Boston, MA  02110-1301  USA
 */

#include <QtTest/QtTest>

#include "../libdissent/crypto.hpp"

namespace Dissent {

class TestCrypto: public QObject {
  Q_OBJECT

 private slots:
  void TestSingletonImplementation();
};

void TestCrypto::TestSingletonImplementation() {
  Crypto *first = Crypto::GetInstance();
  Crypto *second = Crypto::GetInstance();
  QCOMPARE(first == second, true);
}

}

QTEST_MAIN(Dissent::TestCrypto)
#include "testcrypto.moc"

<commit_msg>testcrypto completed except for testing encrytion and decryption<commit_after>// test/testcrypto.cc
// Test /libdissent/crypto.{hpp cc}
//
// Author: Fei Huang <felix.fei.huang@gmail.com>

/* ====================================================================
 * Dissent: Accountable Group Anonymity
 * Copyright (c) 2010 Yale University.
 *
 * This library is free software; you can redistribute it and/or
 * modify it under the terms of the GNU Lesser General Public
 * License as published by the Free Software Foundation; either
 * version 2.1 of the License, or (at your option) any later version.
 *
 * This library is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 * Lesser General Public License for more details.
 *
 * You should have received a copy of the GNU Lesser General Public
 * License along with this library; if not, write to
 *
 *   Free Software Foundation, Inc.,
 *   51 Franklin Street, Fifth Floor,
 *   Boston, MA  02110-1301  USA
 */

#include <QtTest/QtTest>
#include <QSharedPointer>
#include <iostream>

#include "../libdissent/crypto.hpp"

namespace Dissent {

class TestCrypto: public QObject {
  Q_OBJECT

 private slots:
  void initTestCase();
  void cleanupTestCase();
  void TestSingletonImplementation();
  void TestKeyPairGenerationAndChecking();
  void TestKeySerialization();
  void TestEncryptAndDecrypt();
 // void TestEncryptAndDecrypt_data();
  void TestSignAndVerify();
  void TestHash();
 private:
  Crypto *crypto_;
  int key_length_;
  QScopedPointer<PrivateKey> private_key_;
  QScopedPointer<PublicKey> public_key_;
};

void TestCrypto::initTestCase() {
  crypto_ = Crypto::GetInstance();
  key_length_ = 2048;
}

void TestCrypto::cleanupTestCase() {

}

void TestCrypto::TestSingletonImplementation() {
  Crypto *another = Crypto::GetInstance();
  QCOMPARE(crypto_ == another, true);
}

void TestCrypto::TestKeyPairGenerationAndChecking() {
  private_key_.reset(crypto_->GenerateKey(key_length_));
  public_key_.reset(new PublicKey(private_key_->toPublicKey().toRSA()));
  QCOMPARE(crypto_->CheckKeyPair(*private_key_, *public_key_), true);
}

void TestCrypto::TestKeySerialization() {
  QByteArray public_key_buf;
  QByteArray private_key_buf;
  QCOMPARE(crypto_->SerializePublicKey(*public_key_, &public_key_buf), true);
  QEXPECT_FAIL("", "return false in the implementation.", Continue);
  QCOMPARE(crypto_->SerializePrivateKey(*private_key_, &private_key_buf), true);

  QScopedPointer<PublicKey> public_key_from_buf(
                              crypto_->DeserializePublicKey(public_key_buf));
  QScopedPointer<PrivateKey> private_key_from_buf(
                              crypto_->DeserializePrivateKey(private_key_buf));
  QCOMPARE(public_key_ == public_key_from_buf, true);
  QCOMPARE(private_key_ == private_key_from_buf, true);
}

void TestCrypto::TestEncryptAndDecrypt() {
 // QFETCH(PublicKey *, key);
 // QFETCH(QByteArray, msg);
 // QFETCH(QSharedPointer<QByteArray>, ctext);
 // QFETCH(QSharedPointer<QByteArray>, randomness);

 // QCOMPARE(crypto_->Encrypt(key, msg, ctext.data(), randomness.data()), true);
 //QByteArray msg("GGG");
 //QByteArray ctext;
 //QCOMPARE(crypto_->Encrypt(public_key_.data(), msg,
 //         &ctext, NULL), true);
}
/*
void TestCrypto::TestEncryptAndDecrypt_data() {
  QTest::addColumn<PublicKey *>("key");
  QTest::addColumn<QByteArray>("msg");
  QTest::addColumn<QSharedPointer<QByteArray> >("ctext");
  QTest::addColumn<QSharedPointer<QByteArray> >("randomness");

  QByteArray msg("Hello, world!");

  QTest::newRow("no randomness") << public_key_.data() << msg
                                 << QSharedPointer<QByteArray>(new QByteArray())
                                 << QSharedPointer<QByteArray>(NULL);
  QTest::newRow("want to know") << public_key_.data() << msg
                                << QSharedPointer<QByteArray>(new QByteArray())
                                << QSharedPointer<QByteArray>(new QByteArray());
  //QByteArray *arr = new QByteArray()
  //QTest::newRow("known randomness") << public_key_ << msg << new QByteArray()
}
*/

void TestCrypto::TestSignAndVerify() {
  QByteArray msg("Hello, world!");
  QByteArray signature;

  QCOMPARE(crypto_->Sign(private_key_.data(), msg, &signature), true);
  QCOMPARE(crypto_->Verify(public_key_.data(), msg, signature), true);
}

void TestCrypto::TestHash() {
  QList<QByteArray> msgs;
  QByteArray hash;

  msgs.append(QByteArray("Hello"));
  msgs.append(QByteArray(", "));
  msgs.append(QByteArray("world!"));
  QCOMPARE(crypto_->Hash(msgs, &hash), true);
}

}

Q_DECLARE_METATYPE(Dissent::PublicKey *)
Q_DECLARE_METATYPE(QSharedPointer<QByteArray>)

QTEST_MAIN(Dissent::TestCrypto)
#include "testcrypto.moc"

<|endoftext|>


<commit_before>/*  This file is part of the KDE project
    Copyright (C) 2004,2006 Matthias Kretz <kretz@kde.org>

    This program is free software; you can redistribute it and/or modify
    it under the terms of the GNU General Public License version 2
    as published by the Free Software Foundation.

    This program 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 General Public License for more details.

    You should have received a copy of the GNU General Public License
    along with this program; if not, write to the Free Software
    Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA
    02110-1301, USA.

*/

#include "backendselection.h"

#include <kuserprofile.h> // KServiceTypeProfile
#include <dcopclient.h>
#include <ktrader.h>
#include <ksimpleconfig.h>
#include <QStringList>
#include <QListWidgetItem>
#include <kapplication.h>
#include <kicon.h>
#include <QList>

BackendSelection::BackendSelection( QWidget* parent )
	: QWidget( parent )
{
	setupUi( this );

	connect( m_select, SIGNAL( itemSelectionChanged() ),
			SLOT( selectionChanged() ) );
	//connect( m_website, SIGNAL( leftClickedURL( const QString & ) ),
			//kapp, SLOT( invokeBrowser( const QString & ) ) );
	connect( m_up, SIGNAL( clicked() ), SLOT( up() ) );
	connect( m_down, SIGNAL( clicked() ), SLOT( down() ) );
}

void BackendSelection::load()
{
	m_services.clear();
	m_select->clear();
	KServiceTypeProfile::clear();

	KTrader::OfferList offers = KTrader::self()->query( "PhononBackend",
			"Type == 'Service' and [X-KDE-PhononBackendInfo-InterfaceVersion] == 1" );
	// the offers are already sorted for preference
	KTrader::OfferListIterator it = offers.begin();
	KTrader::OfferListIterator end = offers.end();
	for( ; it != end; ++it )
	{
		KService::Ptr service = *it;
		m_select->addItem( service->name() );
		m_services[ service->name() ] = service;
	}
	m_select->setItemSelected( m_select->item( 0 ), true );
}

void BackendSelection::save()
{
	// save to profilerc
	KSimpleConfig config( "profilerc" );
	QStringList grouplist = config.groupList();
	QStringList::Iterator it = grouplist.begin();
	QStringList::Iterator end = grouplist.end();
	for( ; it != end; ++it )
	{
		config.setGroup( *it );
		if( config.readEntry( "ServiceType" ) == "PhononBackend" )
			config.deleteGroup( *it );
	}
	unsigned int count = m_select->count();
	for( unsigned int i = 0; i < count; ++i )
	{
		QListWidgetItem* item = m_select->item( i );
		KService::Ptr service = m_services[ item->text() ];
		config.setGroup( "PhononBackend" + QString( " - %1" ).arg( i ) );
		config.writeEntry( "AllowAsDefault", true );
		config.writeEntry( "Application", service->storageId() );
		config.writeEntry( "GenericServiceType", "PhononBackend" );
		config.writeEntry( "Preference", count - i );
		config.writeEntry( "ServiceType", "PhononBackend" );
	}
	config.sync();
	KService::rebuildKSycoca( this );

	kapp->dcopClient()->emitDCOPSignal( "phononBackendChanged()", QByteArray() );
}

void BackendSelection::defaults()
{
	// XXX: hack, I don't know how to get the initalPreference without
	// reading it all manually
	KSimpleConfig config( "profilerc" );
	QStringList grouplist = config.groupList();
	QStringList::Iterator it = grouplist.begin();
	QStringList::Iterator end = grouplist.end();
	QStringList apps;
	QList<int> pref;
	for( ; it != end; ++it )
	{
		config.setGroup( *it );
		if( config.readEntry( "ServiceType" ) == "PhononBackend" )
		{
			apps.append( config.readEntry( "Application" ) );
			pref.append( config.readEntry( "Preference", int( 0 ) ) );
			config.deleteGroup( *it );
		}
	}
	config.sync();
	load();
	for( int i = 0; i < apps.count(); ++i )
	{
		config.setGroup( "PhononBackend" + QString( " - %1" ).arg( i ) );
		config.writeEntry( "AllowAsDefault", true );
		config.writeEntry( "Application", apps[ i ] );
		config.writeEntry( "GenericServiceType", "PhononBackend" );
		config.writeEntry( "Preference", pref[ i ] );
		config.writeEntry( "ServiceType", "PhononBackend" );
	}
	config.sync();
}

void BackendSelection::selectionChanged()
{
	KService::Ptr service;
	for( int i = 0; i < m_select->count(); ++i )
	{
		QListWidgetItem* item = m_select->item( i );
		if( m_select->isItemSelected( item ) )
		{
			service = m_services[ item->text() ];
			break;
		}
	}
	m_icon->setPixmap( KIcon( service->icon() ).pixmap( 32 ) );
	m_name->setText( service->name() );
	m_comment->setText( service->comment() );
	m_website->setText( service->property( "X-KDE-PhononBackendInfo-Website" ).toString() );
	//m_website->setURL( m_website->text() );
	m_version->setText( service->property( "X-KDE-PhononBackendInfo-Version" ).toString() );
}

void BackendSelection::up()
{
	QList<QListWidgetItem*> selectedList = m_select->selectedItems();
	foreach( QListWidgetItem* selected, selectedList )
	{
		int row = m_select->row( selected );
		if( row > 0 )
		{
			QListWidgetItem* taken = m_select->takeItem( row - 1 );
			m_select->insertItem( row, taken );
			emit changed();
		}
	}
}

void BackendSelection::down()
{
	QList<QListWidgetItem*> selectedList = m_select->selectedItems();
	foreach( QListWidgetItem* selected, selectedList )
	{
		int row = m_select->row( selected );
		if( row + 1 < m_select->count() )
		{
			QListWidgetItem* taken = m_select->takeItem( row + 1 );
			m_select->insertItem( row, taken );
			emit changed();
		}
	}
}

#include "backendselection.moc"

// vim: sw=4 ts=4 noet
<commit_msg>The header file for KServiceTypeProfile has changed from kuserprofile.h to kservicetypeprofile.h<commit_after>/*  This file is part of the KDE project
    Copyright (C) 2004,2006 Matthias Kretz <kretz@kde.org>

    This program is free software; you can redistribute it and/or modify
    it under the terms of the GNU General Public License version 2
    as published by the Free Software Foundation.

    This program 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 General Public License for more details.

    You should have received a copy of the GNU General Public License
    along with this program; if not, write to the Free Software
    Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA
    02110-1301, USA.

*/

#include "backendselection.h"

#include <kservicetypeprofile.h>
#include <dcopclient.h>
#include <ktrader.h>
#include <ksimpleconfig.h>
#include <QStringList>
#include <QListWidgetItem>
#include <kapplication.h>
#include <kicon.h>
#include <QList>

BackendSelection::BackendSelection( QWidget* parent )
	: QWidget( parent )
{
	setupUi( this );

	connect( m_select, SIGNAL( itemSelectionChanged() ),
			SLOT( selectionChanged() ) );
	//connect( m_website, SIGNAL( leftClickedURL( const QString & ) ),
			//kapp, SLOT( invokeBrowser( const QString & ) ) );
	connect( m_up, SIGNAL( clicked() ), SLOT( up() ) );
	connect( m_down, SIGNAL( clicked() ), SLOT( down() ) );
}

void BackendSelection::load()
{
	m_services.clear();
	m_select->clear();
	KServiceTypeProfile::clear();

	KTrader::OfferList offers = KTrader::self()->query( "PhononBackend",
			"Type == 'Service' and [X-KDE-PhononBackendInfo-InterfaceVersion] == 1" );
	// the offers are already sorted for preference
	KTrader::OfferListIterator it = offers.begin();
	KTrader::OfferListIterator end = offers.end();
	for( ; it != end; ++it )
	{
		KService::Ptr service = *it;
		m_select->addItem( service->name() );
		m_services[ service->name() ] = service;
	}
	m_select->setItemSelected( m_select->item( 0 ), true );
}

void BackendSelection::save()
{
	// save to profilerc
	KSimpleConfig config( "profilerc" );
	QStringList grouplist = config.groupList();
	QStringList::Iterator it = grouplist.begin();
	QStringList::Iterator end = grouplist.end();
	for( ; it != end; ++it )
	{
		config.setGroup( *it );
		if( config.readEntry( "ServiceType" ) == "PhononBackend" )
			config.deleteGroup( *it );
	}
	unsigned int count = m_select->count();
	for( unsigned int i = 0; i < count; ++i )
	{
		QListWidgetItem* item = m_select->item( i );
		KService::Ptr service = m_services[ item->text() ];
		config.setGroup( "PhononBackend" + QString( " - %1" ).arg( i ) );
		config.writeEntry( "AllowAsDefault", true );
		config.writeEntry( "Application", service->storageId() );
		config.writeEntry( "GenericServiceType", "PhononBackend" );
		config.writeEntry( "Preference", count - i );
		config.writeEntry( "ServiceType", "PhononBackend" );
	}
	config.sync();
	KService::rebuildKSycoca( this );

	kapp->dcopClient()->emitDCOPSignal( "phononBackendChanged()", QByteArray() );
}

void BackendSelection::defaults()
{
	// XXX: hack, I don't know how to get the initalPreference without
	// reading it all manually
	KSimpleConfig config( "profilerc" );
	QStringList grouplist = config.groupList();
	QStringList::Iterator it = grouplist.begin();
	QStringList::Iterator end = grouplist.end();
	QStringList apps;
	QList<int> pref;
	for( ; it != end; ++it )
	{
		config.setGroup( *it );
		if( config.readEntry( "ServiceType" ) == "PhononBackend" )
		{
			apps.append( config.readEntry( "Application" ) );
			pref.append( config.readEntry( "Preference", int( 0 ) ) );
			config.deleteGroup( *it );
		}
	}
	config.sync();
	load();
	for( int i = 0; i < apps.count(); ++i )
	{
		config.setGroup( "PhononBackend" + QString( " - %1" ).arg( i ) );
		config.writeEntry( "AllowAsDefault", true );
		config.writeEntry( "Application", apps[ i ] );
		config.writeEntry( "GenericServiceType", "PhononBackend" );
		config.writeEntry( "Preference", pref[ i ] );
		config.writeEntry( "ServiceType", "PhononBackend" );
	}
	config.sync();
}

void BackendSelection::selectionChanged()
{
	KService::Ptr service;
	for( int i = 0; i < m_select->count(); ++i )
	{
		QListWidgetItem* item = m_select->item( i );
		if( m_select->isItemSelected( item ) )
		{
			service = m_services[ item->text() ];
			break;
		}
	}
	m_icon->setPixmap( KIcon( service->icon() ).pixmap( 32 ) );
	m_name->setText( service->name() );
	m_comment->setText( service->comment() );
	m_website->setText( service->property( "X-KDE-PhononBackendInfo-Website" ).toString() );
	//m_website->setURL( m_website->text() );
	m_version->setText( service->property( "X-KDE-PhononBackendInfo-Version" ).toString() );
}

void BackendSelection::up()
{
	QList<QListWidgetItem*> selectedList = m_select->selectedItems();
	foreach( QListWidgetItem* selected, selectedList )
	{
		int row = m_select->row( selected );
		if( row > 0 )
		{
			QListWidgetItem* taken = m_select->takeItem( row - 1 );
			m_select->insertItem( row, taken );
			emit changed();
		}
	}
}

void BackendSelection::down()
{
	QList<QListWidgetItem*> selectedList = m_select->selectedItems();
	foreach( QListWidgetItem* selected, selectedList )
	{
		int row = m_select->row( selected );
		if( row + 1 < m_select->count() )
		{
			QListWidgetItem* taken = m_select->takeItem( row + 1 );
			m_select->insertItem( row, taken );
			emit changed();
		}
	}
}

#include "backendselection.moc"

// vim: sw=4 ts=4 noet
<|endoftext|>


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

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

#ifdef SD_DLLIMPLEMENTATION
#undef SD_DLLIMPLEMENTATION
#endif

#include <svx/svxids.hrc>
#include <svx/dlgutil.hxx>
#ifndef _SFXITEMPOOL_HXX //autogen
#include <svtools/itempool.hxx>
#endif
#ifndef _AEITEM_HXX //autogen
#include <svtools/aeitem.hxx>
#endif

#include "dlgsnap.hrc"
#include "sdattr.hxx"
#ifndef SD_VIEW_HXX
#include "View.hxx"
#endif
#include "sdresid.hxx"
#include "drawdoc.hxx"
#include "dlgsnap.hxx"

/*************************************************************************
|*
|* Dialog zum Einstellen des Rasters (wohl kaum ESO!)
|*
\************************************************************************/

SdSnapLineDlg::SdSnapLineDlg(
    ::Window* pWindow,
    const SfxItemSet& rInAttrs,
    ::sd::View* pView)
    : ModalDialog (pWindow, SdResId(DLG_SNAPLINE)),
      aFlPos      (this, SdResId(FL_POSITION)),
      aFtX        (this, SdResId(FT_X)),
      aMtrFldX    (this, SdResId(MTR_FLD_X)),
      aFtY        (this, SdResId(FT_Y)),
      aMtrFldY    (this, SdResId(MTR_FLD_Y)),
      aFlDir      (this, SdResId(FL_DIRECTION)),
      aRbPoint    (this, SdResId(RB_POINT)),
      aRbVert     (this, SdResId(RB_VERTICAL)),
      aRbHorz     (this, SdResId(RB_HORIZONTAL)),
      aBtnOK      (this, SdResId(BTN_OK)),
      aBtnCancel  (this, SdResId(BTN_CANCEL)),
      aBtnHelp    (this, SdResId(BTN_HELP)),
      aBtnDelete  (this, SdResId(BTN_DELETE)),
      eUIUnit(pView->GetDoc()->GetUIUnit()),
      aUIScale(pView->GetDoc()->GetUIScale())
{
    aRbPoint.SetModeRadioImage( Image( SdResId( BMP_POINT_H ) ), BMP_COLOR_HIGHCONTRAST );
    aRbVert.SetModeRadioImage( Image( SdResId( BMP_VERTICAL_H ) ), BMP_COLOR_HIGHCONTRAST );
    aRbHorz.SetModeRadioImage( Image( SdResId( BMP_HORIZONTAL_H ) ), BMP_COLOR_HIGHCONTRAST );

    FreeResource();

    aRbHorz.SetClickHdl(LINK(this, SdSnapLineDlg, ClickHdl));
    aRbVert.SetClickHdl(LINK(this, SdSnapLineDlg, ClickHdl));
    aRbPoint.SetClickHdl(LINK(this, SdSnapLineDlg, ClickHdl));

    aBtnDelete.SetClickHdl(LINK(this, SdSnapLineDlg, ClickHdl));

    SetFieldUnit( aMtrFldX, eUIUnit, TRUE );
    SetFieldUnit( aMtrFldY, eUIUnit, TRUE );

    // WorkArea holen
    Rectangle aWorkArea = pView->GetWorkArea();

    // PoolUnit ermitteln
    SfxItemPool* pPool = rInAttrs.GetPool();
    DBG_ASSERT( pPool, "Wo ist der Pool?" );
    SfxMapUnit ePoolUnit = pPool->GetMetric( SID_ATTR_FILL_HATCH );

    // Hier werden die Max- und MinWerte in Ahaengigkeit von der
    // WorkArea, PoolUnit und der FieldUnit:
    SetMetricValue( aMtrFldX, aWorkArea.Left(), ePoolUnit );
    long nValue = aMtrFldX.GetValue();
    nValue = Fraction( nValue ) / aUIScale;
    aMtrFldX.SetMin( nValue );
    aMtrFldX.SetFirst( nValue );

    SetMetricValue( aMtrFldX, aWorkArea.Right()+1, ePoolUnit );
    nValue = aMtrFldX.GetValue();
    nValue = Fraction( nValue ) / aUIScale;
    aMtrFldX.SetMax( nValue );
    aMtrFldX.SetLast( nValue );

    SetMetricValue( aMtrFldY, aWorkArea.Top(), ePoolUnit );
    nValue = aMtrFldY.GetValue();
    nValue = Fraction( nValue ) / aUIScale;
    aMtrFldY.SetMin( nValue );
    aMtrFldY.SetFirst( nValue );

    SetMetricValue( aMtrFldY, aWorkArea.Bottom()+1, ePoolUnit );
    nValue = aMtrFldY.GetValue();
    nValue = Fraction( nValue ) / aUIScale;
    aMtrFldY.SetMax( nValue );
    aMtrFldY.SetLast( nValue );

    // Setzen der Werte
    nXValue = ((const SfxUInt32Item&) rInAttrs.Get(ATTR_SNAPLINE_X)).GetValue();
    nYValue = ((const SfxUInt32Item&) rInAttrs.Get(ATTR_SNAPLINE_Y)).GetValue();
    nXValue = Fraction(nXValue) / aUIScale;
    nYValue = Fraction(nYValue) / aUIScale;
    SetMetricValue( aMtrFldX, nXValue, SFX_MAPUNIT_100TH_MM);
    SetMetricValue( aMtrFldY, nYValue, SFX_MAPUNIT_100TH_MM);

    aRbPoint.Check();
}

/*************************************************************************
|*
|* Fuellt uebergebenes Item-Set mit Dialogbox-Attributen
|*
\************************************************************************/

IMPL_LINK( SdSnapLineDlg, ClickHdl, Button *, pBtn )
{
    if ( pBtn == &aRbPoint )        SetInputFields(TRUE, TRUE);
    else if ( pBtn == &aRbHorz )    SetInputFields(FALSE, TRUE);
    else if ( pBtn == &aRbVert )    SetInputFields(TRUE, FALSE);
    else if ( pBtn == &aBtnDelete ) EndDialog(RET_SNAP_DELETE);

    return 0;
}

/*************************************************************************
|*
|* Fuellt uebergebenes Item-Set mit Dialogbox-Attributen
|*
\************************************************************************/

void SdSnapLineDlg::GetAttr(SfxItemSet& rOutAttrs)
{
    SnapKind eKind;

    if ( aRbHorz.IsChecked() )      eKind = SK_HORIZONTAL;
    else if ( aRbVert.IsChecked() ) eKind = SK_VERTICAL;
    else                            eKind = SK_POINT;

    nXValue = Fraction( GetCoreValue( aMtrFldX, SFX_MAPUNIT_100TH_MM) ) * aUIScale;
    nYValue = Fraction( GetCoreValue( aMtrFldY, SFX_MAPUNIT_100TH_MM) ) * aUIScale;

    rOutAttrs.Put(SfxAllEnumItem(ATTR_SNAPLINE_KIND, (USHORT)eKind));
    rOutAttrs.Put(SfxUInt32Item(ATTR_SNAPLINE_X, nXValue));
    rOutAttrs.Put(SfxUInt32Item(ATTR_SNAPLINE_Y, nYValue));
}

/*************************************************************************
|*
|* Gruppe mit Radiobutton verstecken
|*
\************************************************************************/

void SdSnapLineDlg::HideRadioGroup()
{
    aFlDir.Hide();
    aRbHorz.Hide();
    aRbVert.Hide();
    aRbPoint.Hide();
}

/*************************************************************************
|*
|* X- bzw. Y-Inputfeld disablen
|*
\************************************************************************/

void SdSnapLineDlg::SetInputFields(BOOL bEnableX, BOOL bEnableY)
{
    if ( bEnableX )
    {
        if ( !aMtrFldX.IsEnabled() )
            aMtrFldX.SetValue(nXValue);
        aMtrFldX.Enable();
        aFtX.Enable();
    }
    else if ( aMtrFldX.IsEnabled() )
    {
        nXValue = aMtrFldX.GetValue();
        aMtrFldX.SetText(String());
        aMtrFldX.Disable();
        aFtX.Disable();
    }
    if ( bEnableY )
    {
        if ( !aMtrFldY.IsEnabled() )
            aMtrFldY.SetValue(nYValue);
        aMtrFldY.Enable();
        aFtY.Enable();
    }
    else if ( aMtrFldY.IsEnabled() )
    {
        nYValue = aMtrFldY.GetValue();
        aMtrFldY.SetText(String());
        aMtrFldY.Disable();
        aFtY.Disable();
    }
}

<commit_msg>INTEGRATION: CWS mfdouble (1.9.4); FILE MERGED 2006/12/22 13:39:50 pl 1.9.4.1: #i71046# increase precision of MetricField and friends<commit_after>/*************************************************************************
 *
 *  OpenOffice.org - a multi-platform office productivity suite
 *
 *  $RCSfile: dlgsnap.cxx,v $
 *
 *  $Revision: 1.10 $
 *
 *  last change: $Author: obo $ $Date: 2007-01-23 11:13:53 $
 *
 *  The Contents of this file are made available subject to
 *  the terms of GNU Lesser General Public License Version 2.1.
 *
 *
 *    GNU Lesser General Public License Version 2.1
 *    =============================================
 *    Copyright 2005 by Sun Microsystems, Inc.
 *    901 San Antonio Road, Palo Alto, CA 94303, USA
 *
 *    This library is free software; you can redistribute it and/or
 *    modify it under the terms of the GNU Lesser General Public
 *    License version 2.1, as published by the Free Software Foundation.
 *
 *    This library is distributed in the hope that it will be useful,
 *    but WITHOUT ANY WARRANTY; without even the implied warranty of
 *    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 *    Lesser General Public License for more details.
 *
 *    You should have received a copy of the GNU Lesser General Public
 *    License along with this library; if not, write to the Free Software
 *    Foundation, Inc., 59 Temple Place, Suite 330, Boston,
 *    MA  02111-1307  USA
 *
 ************************************************************************/

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

#ifdef SD_DLLIMPLEMENTATION
#undef SD_DLLIMPLEMENTATION
#endif

#include <svx/svxids.hrc>
#include <svx/dlgutil.hxx>
#ifndef _SFXITEMPOOL_HXX //autogen
#include <svtools/itempool.hxx>
#endif
#ifndef _AEITEM_HXX //autogen
#include <svtools/aeitem.hxx>
#endif

#include "dlgsnap.hrc"
#include "sdattr.hxx"
#ifndef SD_VIEW_HXX
#include "View.hxx"
#endif
#include "sdresid.hxx"
#include "drawdoc.hxx"
#include "dlgsnap.hxx"

/*************************************************************************
|*
|* Dialog zum Einstellen des Rasters (wohl kaum ESO!)
|*
\************************************************************************/

SdSnapLineDlg::SdSnapLineDlg(
    ::Window* pWindow,
    const SfxItemSet& rInAttrs,
    ::sd::View* pView)
    : ModalDialog (pWindow, SdResId(DLG_SNAPLINE)),
      aFlPos      (this, SdResId(FL_POSITION)),
      aFtX        (this, SdResId(FT_X)),
      aMtrFldX    (this, SdResId(MTR_FLD_X)),
      aFtY        (this, SdResId(FT_Y)),
      aMtrFldY    (this, SdResId(MTR_FLD_Y)),
      aFlDir      (this, SdResId(FL_DIRECTION)),
      aRbPoint    (this, SdResId(RB_POINT)),
      aRbVert     (this, SdResId(RB_VERTICAL)),
      aRbHorz     (this, SdResId(RB_HORIZONTAL)),
      aBtnOK      (this, SdResId(BTN_OK)),
      aBtnCancel  (this, SdResId(BTN_CANCEL)),
      aBtnHelp    (this, SdResId(BTN_HELP)),
      aBtnDelete  (this, SdResId(BTN_DELETE)),
      eUIUnit(pView->GetDoc()->GetUIUnit()),
      aUIScale(pView->GetDoc()->GetUIScale())
{
    aRbPoint.SetModeRadioImage( Image( SdResId( BMP_POINT_H ) ), BMP_COLOR_HIGHCONTRAST );
    aRbVert.SetModeRadioImage( Image( SdResId( BMP_VERTICAL_H ) ), BMP_COLOR_HIGHCONTRAST );
    aRbHorz.SetModeRadioImage( Image( SdResId( BMP_HORIZONTAL_H ) ), BMP_COLOR_HIGHCONTRAST );

    FreeResource();

    aRbHorz.SetClickHdl(LINK(this, SdSnapLineDlg, ClickHdl));
    aRbVert.SetClickHdl(LINK(this, SdSnapLineDlg, ClickHdl));
    aRbPoint.SetClickHdl(LINK(this, SdSnapLineDlg, ClickHdl));

    aBtnDelete.SetClickHdl(LINK(this, SdSnapLineDlg, ClickHdl));

    SetFieldUnit( aMtrFldX, eUIUnit, TRUE );
    SetFieldUnit( aMtrFldY, eUIUnit, TRUE );

    // WorkArea holen
    Rectangle aWorkArea = pView->GetWorkArea();

    // PoolUnit ermitteln
    SfxItemPool* pPool = rInAttrs.GetPool();
    DBG_ASSERT( pPool, "Wo ist der Pool?" );
    SfxMapUnit ePoolUnit = pPool->GetMetric( SID_ATTR_FILL_HATCH );

    // Hier werden die Max- und MinWerte in Ahaengigkeit von der
    // WorkArea, PoolUnit und der FieldUnit:
    SetMetricValue( aMtrFldX, aWorkArea.Left(), ePoolUnit );
    long nValue = static_cast<long>(aMtrFldX.GetValue());
    nValue = Fraction( nValue ) / aUIScale;
    aMtrFldX.SetMin( nValue );
    aMtrFldX.SetFirst( nValue );

    SetMetricValue( aMtrFldX, aWorkArea.Right()+1, ePoolUnit );
    nValue = static_cast<long>(aMtrFldX.GetValue());
    nValue = Fraction( nValue ) / aUIScale;
    aMtrFldX.SetMax( nValue );
    aMtrFldX.SetLast( nValue );

    SetMetricValue( aMtrFldY, aWorkArea.Top(), ePoolUnit );
    nValue = static_cast<long>(aMtrFldY.GetValue());
    nValue = Fraction( nValue ) / aUIScale;
    aMtrFldY.SetMin( nValue );
    aMtrFldY.SetFirst( nValue );

    SetMetricValue( aMtrFldY, aWorkArea.Bottom()+1, ePoolUnit );
    nValue = static_cast<long>(aMtrFldY.GetValue());
    nValue = Fraction( nValue ) / aUIScale;
    aMtrFldY.SetMax( nValue );
    aMtrFldY.SetLast( nValue );

    // Setzen der Werte
    nXValue = ((const SfxUInt32Item&) rInAttrs.Get(ATTR_SNAPLINE_X)).GetValue();
    nYValue = ((const SfxUInt32Item&) rInAttrs.Get(ATTR_SNAPLINE_Y)).GetValue();
    nXValue = Fraction(nXValue) / aUIScale;
    nYValue = Fraction(nYValue) / aUIScale;
    SetMetricValue( aMtrFldX, nXValue, SFX_MAPUNIT_100TH_MM);
    SetMetricValue( aMtrFldY, nYValue, SFX_MAPUNIT_100TH_MM);

    aRbPoint.Check();
}

/*************************************************************************
|*
|* Fuellt uebergebenes Item-Set mit Dialogbox-Attributen
|*
\************************************************************************/

IMPL_LINK( SdSnapLineDlg, ClickHdl, Button *, pBtn )
{
    if ( pBtn == &aRbPoint )        SetInputFields(TRUE, TRUE);
    else if ( pBtn == &aRbHorz )    SetInputFields(FALSE, TRUE);
    else if ( pBtn == &aRbVert )    SetInputFields(TRUE, FALSE);
    else if ( pBtn == &aBtnDelete ) EndDialog(RET_SNAP_DELETE);

    return 0;
}

/*************************************************************************
|*
|* Fuellt uebergebenes Item-Set mit Dialogbox-Attributen
|*
\************************************************************************/

void SdSnapLineDlg::GetAttr(SfxItemSet& rOutAttrs)
{
    SnapKind eKind;

    if ( aRbHorz.IsChecked() )      eKind = SK_HORIZONTAL;
    else if ( aRbVert.IsChecked() ) eKind = SK_VERTICAL;
    else                            eKind = SK_POINT;

    nXValue = Fraction( GetCoreValue( aMtrFldX, SFX_MAPUNIT_100TH_MM) ) * aUIScale;
    nYValue = Fraction( GetCoreValue( aMtrFldY, SFX_MAPUNIT_100TH_MM) ) * aUIScale;

    rOutAttrs.Put(SfxAllEnumItem(ATTR_SNAPLINE_KIND, (USHORT)eKind));
    rOutAttrs.Put(SfxUInt32Item(ATTR_SNAPLINE_X, nXValue));
    rOutAttrs.Put(SfxUInt32Item(ATTR_SNAPLINE_Y, nYValue));
}

/*************************************************************************
|*
|* Gruppe mit Radiobutton verstecken
|*
\************************************************************************/

void SdSnapLineDlg::HideRadioGroup()
{
    aFlDir.Hide();
    aRbHorz.Hide();
    aRbVert.Hide();
    aRbPoint.Hide();
}

/*************************************************************************
|*
|* X- bzw. Y-Inputfeld disablen
|*
\************************************************************************/

void SdSnapLineDlg::SetInputFields(BOOL bEnableX, BOOL bEnableY)
{
    if ( bEnableX )
    {
        if ( !aMtrFldX.IsEnabled() )
            aMtrFldX.SetValue(nXValue);
        aMtrFldX.Enable();
        aFtX.Enable();
    }
    else if ( aMtrFldX.IsEnabled() )
    {
        nXValue = static_cast<long>(aMtrFldX.GetValue());
        aMtrFldX.SetText(String());
        aMtrFldX.Disable();
        aFtX.Disable();
    }
    if ( bEnableY )
    {
        if ( !aMtrFldY.IsEnabled() )
            aMtrFldY.SetValue(nYValue);
        aMtrFldY.Enable();
        aFtY.Enable();
    }
    else if ( aMtrFldY.IsEnabled() )
    {
        nYValue = static_cast<long>(aMtrFldY.GetValue());
        aMtrFldY.SetText(String());
        aMtrFldY.Disable();
        aFtY.Disable();
    }
}

<|endoftext|>


<commit_before>/*************************************************************************
 *
 *  $RCSfile: fuvect.cxx,v $
 *
 *  $Revision: 1.5 $
 *
 *  last change: $Author: rt $ $Date: 2004-07-12 15:09:24 $
 *
 *  The Contents of this file are made available subject to the terms of
 *  either of the following licenses
 *
 *         - GNU Lesser General Public License Version 2.1
 *         - Sun Industry Standards Source License Version 1.1
 *
 *  Sun Microsystems Inc., October, 2000
 *
 *  GNU Lesser General Public License Version 2.1
 *  =============================================
 *  Copyright 2000 by Sun Microsystems, Inc.
 *  901 San Antonio Road, Palo Alto, CA 94303, USA
 *
 *  This library is free software; you can redistribute it and/or
 *  modify it under the terms of the GNU Lesser General Public
 *  License version 2.1, as published by the Free Software Foundation.
 *
 *  This library is distributed in the hope that it will be useful,
 *  but WITHOUT ANY WARRANTY; without even the implied warranty of
 *  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 *  Lesser General Public License for more details.
 *
 *  You should have received a copy of the GNU Lesser General Public
 *  License along with this library; if not, write to the Free Software
 *  Foundation, Inc., 59 Temple Place, Suite 330, Boston,
 *  MA  02111-1307  USA
 *
 *
 *  Sun Industry Standards Source License Version 1.1
 *  =================================================
 *  The contents of this file are subject to the Sun Industry Standards
 *  Source License Version 1.1 (the "License"); You may not use this file
 *  except in compliance with the License. You may obtain a copy of the
 *  License at http://www.openoffice.org/license.html.
 *
 *  Software provided under this License is provided on an "AS IS" basis,
 *  WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING,
 *  WITHOUT LIMITATION, WARRANTIES THAT THE SOFTWARE IS FREE OF DEFECTS,
 *  MERCHANTABLE, FIT FOR A PARTICULAR PURPOSE, OR NON-INFRINGING.
 *  See the License for the specific provisions governing your rights and
 *  obligations concerning the Software.
 *
 *  The Initial Developer of the Original Code is: Sun Microsystems, Inc.
 *
 *  Copyright: 2000 by Sun Microsystems, Inc.
 *
 *  All Rights Reserved.
 *
 *  Contributor(s): _______________________________________
 *
 *
 ************************************************************************/

#include "fuvect.hxx"

#ifndef _TL_POLY_HXX
#include <tools/poly.hxx>
#endif
#ifndef _SVDOPATH_HXX //autogen
#include <svx/svdograf.hxx>
#endif
#ifndef _SV_MSGBOX_HXX //autogen
#include <vcl/msgbox.hxx>
#endif
#ifndef _SVX_SVDOGRAF_HXX //autogen
#include <svx/svdograf.hxx>
#endif
#ifndef _SVX_SVDEDTV_HXX //autogen
#include <svx/svdedtv.hxx>
#endif

#pragma hdrstop

#ifndef SD_VIEW_HXX
#include "View.hxx"
#endif
#ifndef SD_VIEW_SHELL_HXX
#include "ViewShell.hxx"
#endif
#ifndef SD_WINDOW_HXX
#include "Window.hxx"
#endif
#include "strings.hrc"
#include "sdresid.hxx"
//CHINA001 #include "vectdlg.hxx"
#include "sdabstdlg.hxx" //CHINA001
#include "vectdlg.hrc" //CHINA001
namespace sd {

TYPEINIT1( FuVectorize, FuPoor );

/*************************************************************************
|*
|* Konstruktor
|*
\************************************************************************/

FuVectorize::FuVectorize (
    ViewShell* pViewSh,
    ::sd::Window* pWin,
    ::sd::View* pView,
    SdDrawDocument* pDoc,
    SfxRequest& rReq)
    : FuPoor (pViewSh, pWin, pView, pDoc, rReq)
{
    const SdrMarkList& rMarkList = pView->GetMarkedObjectList();

    if( rMarkList.GetMarkCount() == 1 )
    {
        SdrObject* pObj = rMarkList.GetMark( 0 )->GetObj();

        if( pObj && pObj->ISA( SdrGrafObj ) )
        {
            //CHINA001 SdVectorizeDlg aDlg(pWin, ( (SdrGrafObj*) pObj )->GetGraphic().GetBitmap(), pDocSh );
            SdAbstractDialogFactory* pFact = SdAbstractDialogFactory::Create();//CHINA001
            DBG_ASSERT(pFact, "SdAbstractDialogFactory fail!");//CHINA001
            AbstractSdVectorizeDlg* pDlg = pFact->CreateSdVectorizeDlg(ResId( DLG_VECTORIZE ), pWin, ( (SdrGrafObj*) pObj )->GetGraphic().GetBitmap(), pDocSh );
            DBG_ASSERT(pDlg, "Dialogdiet fail!");//CHINA001
            if( pDlg->Execute() == RET_OK ) //CHINA001 if( aDlg.Execute() == RET_OK )
            {
                const GDIMetaFile&  rMtf = pDlg->GetGDIMetaFile(); //CHINA001 const GDIMetaFile&    rMtf = aDlg.GetGDIMetaFile();
                SdrPageView*        pPageView = pView->GetPageViewPvNum( 0 );

                if( pPageView && rMtf.GetActionCount() )
                {
                    SdrGrafObj* pVectObj = (SdrGrafObj*) pObj->Clone();
                    String      aStr( pView->GetDescriptionOfMarkedObjects() );

                    aStr.Append( sal_Unicode(' ') );
                    aStr.Append( String( SdResId( STR_UNDO_VECTORIZE ) ) );
                    pView->BegUndo( aStr );
                    pVectObj->SetGraphic( rMtf );
                    pView->ReplaceObject( pObj, *pPageView, pVectObj );
                    pView->EndUndo();
                }
            }
            delete pDlg; //add by CHINA001
        }
    }
}

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

#include "fuvect.hxx"

#ifndef _TL_POLY_HXX
#include <tools/poly.hxx>
#endif
#ifndef _SVDOPATH_HXX //autogen
#include <svx/svdograf.hxx>
#endif
#ifndef _SV_MSGBOX_HXX //autogen
#include <vcl/msgbox.hxx>
#endif
#ifndef _SVX_SVDOGRAF_HXX //autogen
#include <svx/svdograf.hxx>
#endif
#ifndef _SVX_SVDEDTV_HXX //autogen
#include <svx/svdedtv.hxx>
#endif

#pragma hdrstop

#ifndef SD_VIEW_HXX
#include "View.hxx"
#endif
#ifndef SD_VIEW_SHELL_HXX
#include "ViewShell.hxx"
#endif
#ifndef SD_WINDOW_HXX
#include "Window.hxx"
#endif
#include "strings.hrc"
#include "sdresid.hxx"
//CHINA001 #include "vectdlg.hxx"
#include "sdabstdlg.hxx" //CHINA001
#include "vectdlg.hrc" //CHINA001
namespace sd {

TYPEINIT1( FuVectorize, FuPoor );

/*************************************************************************
|*
|* Konstruktor
|*
\************************************************************************/

FuVectorize::FuVectorize (
    ViewShell* pViewSh,
    ::sd::Window* pWin,
    ::sd::View* pView,
    SdDrawDocument* pDoc,
    SfxRequest& rReq)
    : FuPoor (pViewSh, pWin, pView, pDoc, rReq)
{
    const SdrMarkList& rMarkList = pView->GetMarkedObjectList();

    if( rMarkList.GetMarkCount() == 1 )
    {
        SdrObject* pObj = rMarkList.GetMark( 0 )->GetObj();

        if( pObj && pObj->ISA( SdrGrafObj ) )
        {
            //CHINA001 SdVectorizeDlg aDlg(pWin, ( (SdrGrafObj*) pObj )->GetGraphic().GetBitmap(), pDocSh );
            SdAbstractDialogFactory* pFact = SdAbstractDialogFactory::Create();//CHINA001
            DBG_ASSERT(pFact, "SdAbstractDialogFactory fail!");//CHINA001
            AbstractSdVectorizeDlg* pDlg = pFact->CreateSdVectorizeDlg(ResId( DLG_VECTORIZE ), pWin, ( (SdrGrafObj*) pObj )->GetGraphic().GetBitmap(), pDocSh );
            DBG_ASSERT(pDlg, "Dialogdiet fail!");//CHINA001
            if( pDlg->Execute() == RET_OK ) //CHINA001 if( aDlg.Execute() == RET_OK )
            {
                const GDIMetaFile&  rMtf = pDlg->GetGDIMetaFile(); //CHINA001 const GDIMetaFile&    rMtf = aDlg.GetGDIMetaFile();
                SdrPageView*        pPageView = pView->GetPageViewPvNum( 0 );

                if( pPageView && rMtf.GetActionCount() )
                {
                    SdrGrafObj* pVectObj = (SdrGrafObj*) pObj->Clone();
                    String      aStr( pView->GetDescriptionOfMarkedObjects() );

                    aStr.Append( sal_Unicode(' ') );
                    aStr.Append( String( SdResId( STR_UNDO_VECTORIZE ) ) );
                    pView->BegUndo( aStr );
                    pVectObj->SetGraphic( rMtf );
                    pView->ReplaceObject( pObj, *pPageView, pVectObj );
                    pView->EndUndo();
                }
            }
            delete pDlg; //add by CHINA001
        }
    }
}

} // end of namespace sd
<|endoftext|>


<commit_before>/*************************************************************************
 *
 *  $RCSfile: dlgsnap.hxx,v $
 *
 *  $Revision: 1.2 $
 *
 *  last change: $Author: af $ $Date: 2001-05-16 15:54:01 $
 *
 *  The Contents of this file are made available subject to the terms of
 *  either of the following licenses
 *
 *         - GNU Lesser General Public License Version 2.1
 *         - Sun Industry Standards Source License Version 1.1
 *
 *  Sun Microsystems Inc., October, 2000
 *
 *  GNU Lesser General Public License Version 2.1
 *  =============================================
 *  Copyright 2000 by Sun Microsystems, Inc.
 *  901 San Antonio Road, Palo Alto, CA 94303, USA
 *
 *  This library is free software; you can redistribute it and/or
 *  modify it under the terms of the GNU Lesser General Public
 *  License version 2.1, as published by the Free Software Foundation.
 *
 *  This library is distributed in the hope that it will be useful,
 *  but WITHOUT ANY WARRANTY; without even the implied warranty of
 *  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 *  Lesser General Public License for more details.
 *
 *  You should have received a copy of the GNU Lesser General Public
 *  License along with this library; if not, write to the Free Software
 *  Foundation, Inc., 59 Temple Place, Suite 330, Boston,
 *  MA  02111-1307  USA
 *
 *
 *  Sun Industry Standards Source License Version 1.1
 *  =================================================
 *  The contents of this file are subject to the Sun Industry Standards
 *  Source License Version 1.1 (the "License"); You may not use this file
 *  except in compliance with the License. You may obtain a copy of the
 *  License at http://www.openoffice.org/license.html.
 *
 *  Software provided under this License is provided on an "AS IS" basis,
 *  WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING,
 *  WITHOUT LIMITATION, WARRANTIES THAT THE SOFTWARE IS FREE OF DEFECTS,
 *  MERCHANTABLE, FIT FOR A PARTICULAR PURPOSE, OR NON-INFRINGING.
 *  See the License for the specific provisions governing your rights and
 *  obligations concerning the Software.
 *
 *  The Initial Developer of the Original Code is: Sun Microsystems, Inc.
 *
 *  Copyright: 2000 by Sun Microsystems, Inc.
 *
 *  All Rights Reserved.
 *
 *  Contributor(s): _______________________________________
 *
 *
 ************************************************************************/

#ifndef _SD_DLGSNAP_HXX
#define _SD_DLGSNAP_HXX

#ifndef _IMAGEBTN_HXX //autogen
#include <vcl/imagebtn.hxx>
#endif
#ifndef _FIXED_HXX //autogen
#include <vcl/fixed.hxx>
#endif
#ifndef _FIELD_HXX //autogen
#include <vcl/field.hxx>
#endif
#ifndef _GROUP_HXX //autogen
#include <vcl/group.hxx>
#endif
#ifndef _BUTTON_HXX //autogen
#include <vcl/button.hxx>
#endif
#ifndef _FRACT_HXX //autogen
#include <tools/fract.hxx>
#endif
#ifndef _DIALOG_HXX //autogen
#include <vcl/dialog.hxx>
#endif
/************************************************************************/

class SfxItemSet;
class SdView;

#define RET_SNAP_DELETE 111

enum SnapKind { SK_HORIZONTAL, SK_VERTICAL, SK_POINT };

/*************************************************************************
|*
|* Dialog zum Einstellen von Fanglinien und -punkten
|*
\************************************************************************/

class SdSnapLineDlg : public ModalDialog
{
private:
    FixedLine           aFlPos;
    FixedText           aFtX;
    MetricField         aMtrFldX;
    FixedText           aFtY;
    MetricField         aMtrFldY;
    FixedLine           aFlDir;
    ImageRadioButton    aRbPoint;
    ImageRadioButton    aRbVert;
    ImageRadioButton    aRbHorz;
    OKButton            aBtnOK;
    CancelButton        aBtnCancel;
    HelpButton          aBtnHelp;
    PushButton          aBtnDelete;
    long                nXValue;
    long                nYValue;
    FieldUnit           eUIUnit;
    Fraction            aUIScale;

    DECL_LINK( ClickHdl, Button * );

public:
    SdSnapLineDlg(Window* pWindow, const SfxItemSet& rInAttrs, SdView* pView);

    void GetAttr(SfxItemSet& rOutAttrs);

    void HideRadioGroup();
    void HideDeleteBtn() { aBtnDelete.Hide(); }
    void SetInputFields(BOOL bEnableX, BOOL bEnableY);
};

#endif      // _SD_DLGSNAP_HXX
<commit_msg>INTEGRATION: CWS impress1 (1.2.248); FILE MERGED 2003/09/16 13:40:38 af 1.2.248.1: #111996# Introduction of namespace sd. Use of sub-shells.<commit_after>/*************************************************************************
 *
 *  $RCSfile: dlgsnap.hxx,v $
 *
 *  $Revision: 1.3 $
 *
 *  last change: $Author: obo $ $Date: 2004-01-20 11:49:42 $
 *
 *  The Contents of this file are made available subject to the terms of
 *  either of the following licenses
 *
 *         - GNU Lesser General Public License Version 2.1
 *         - Sun Industry Standards Source License Version 1.1
 *
 *  Sun Microsystems Inc., October, 2000
 *
 *  GNU Lesser General Public License Version 2.1
 *  =============================================
 *  Copyright 2000 by Sun Microsystems, Inc.
 *  901 San Antonio Road, Palo Alto, CA 94303, USA
 *
 *  This library is free software; you can redistribute it and/or
 *  modify it under the terms of the GNU Lesser General Public
 *  License version 2.1, as published by the Free Software Foundation.
 *
 *  This library is distributed in the hope that it will be useful,
 *  but WITHOUT ANY WARRANTY; without even the implied warranty of
 *  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 *  Lesser General Public License for more details.
 *
 *  You should have received a copy of the GNU Lesser General Public
 *  License along with this library; if not, write to the Free Software
 *  Foundation, Inc., 59 Temple Place, Suite 330, Boston,
 *  MA  02111-1307  USA
 *
 *
 *  Sun Industry Standards Source License Version 1.1
 *  =================================================
 *  The contents of this file are subject to the Sun Industry Standards
 *  Source License Version 1.1 (the "License"); You may not use this file
 *  except in compliance with the License. You may obtain a copy of the
 *  License at http://www.openoffice.org/license.html.
 *
 *  Software provided under this License is provided on an "AS IS" basis,
 *  WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING,
 *  WITHOUT LIMITATION, WARRANTIES THAT THE SOFTWARE IS FREE OF DEFECTS,
 *  MERCHANTABLE, FIT FOR A PARTICULAR PURPOSE, OR NON-INFRINGING.
 *  See the License for the specific provisions governing your rights and
 *  obligations concerning the Software.
 *
 *  The Initial Developer of the Original Code is: Sun Microsystems, Inc.
 *
 *  Copyright: 2000 by Sun Microsystems, Inc.
 *
 *  All Rights Reserved.
 *
 *  Contributor(s): _______________________________________
 *
 *
 ************************************************************************/

#ifndef _SD_DLGSNAP_HXX
#define _SD_DLGSNAP_HXX

#ifndef _IMAGEBTN_HXX //autogen
#include <vcl/imagebtn.hxx>
#endif
#ifndef _FIXED_HXX //autogen
#include <vcl/fixed.hxx>
#endif
#ifndef _FIELD_HXX //autogen
#include <vcl/field.hxx>
#endif
#ifndef _GROUP_HXX //autogen
#include <vcl/group.hxx>
#endif
#ifndef _BUTTON_HXX //autogen
#include <vcl/button.hxx>
#endif
#ifndef _FRACT_HXX //autogen
#include <tools/fract.hxx>
#endif
#ifndef _DIALOG_HXX //autogen
#include <vcl/dialog.hxx>
#endif
/************************************************************************/

class SfxItemSet;
class ::sd::View;

#define RET_SNAP_DELETE 111

enum SnapKind { SK_HORIZONTAL, SK_VERTICAL, SK_POINT };

/*************************************************************************
|*
|* Dialog zum Einstellen von Fanglinien und -punkten
|*
\************************************************************************/

class SdSnapLineDlg : public ModalDialog
{
private:
    FixedLine           aFlPos;
    FixedText           aFtX;
    MetricField         aMtrFldX;
    FixedText           aFtY;
    MetricField         aMtrFldY;
    FixedLine           aFlDir;
    ImageRadioButton    aRbPoint;
    ImageRadioButton    aRbVert;
    ImageRadioButton    aRbHorz;
    OKButton            aBtnOK;
    CancelButton        aBtnCancel;
    HelpButton          aBtnHelp;
    PushButton          aBtnDelete;
    long                nXValue;
    long                nYValue;
    FieldUnit           eUIUnit;
    Fraction            aUIScale;

    DECL_LINK( ClickHdl, Button * );

public:
    SdSnapLineDlg(Window* pWindow, const SfxItemSet& rInAttrs, ::sd::View* pView);

    void GetAttr(SfxItemSet& rOutAttrs);

    void HideRadioGroup();
    void HideDeleteBtn() { aBtnDelete.Hide(); }
    void SetInputFields(BOOL bEnableX, BOOL bEnableY);
};

#endif      // _SD_DLGSNAP_HXX
<|endoftext|>


<commit_before>
#define DOCTEST_CONFIG_IMPLEMENT
#include "doctest.h"
#include "iguana/json_reader.hpp"
#include "test_headers.h"
#include <iguana/json.hpp>
#include <iguana/json_util.hpp>
#include <iostream>

TEST_CASE("test parse item num_t") {
  {
    std::string str{"1.4806532964699196e-22"};
    double p{};
    iguana::parse_item(p, str.begin(), str.end());
    CHECK(p == 1.4806532964699196e-22);
  }
  {
    std::string str{ "" };
    double p{};
    CHECK_THROWS(iguana::parse_item(p, str.begin(), str.end()));
  }
  {
    std::string str{"1.0"};
    int p{};
    iguana::parse_item(p, str.begin(), str.end());
    CHECK(p == 1);
  }
  {
    std::string str{"3e6"};
    int p{};
    iguana::parse_item(p, str.begin(), str.end());
    //throw here because parsed p = 3 and said not correct.
    //CHECK(p == 3e6);
  }
  {
    std::string str;
    str.append(300, '1');
    int p{};
    CHECK_THROWS(iguana::parse_item(p, str.begin(), str.end()));
  }
}

TEST_CASE("test parse item array_t") {
  {
    std::string str{"[1, -222]"};
    std::array<int, 2> test;
    iguana::parse_item(test, str.begin(), str.end());
    CHECK(test[0] == 1);
    CHECK(test[1] == -222);
  }
  {
    std::string str{"[1, -222,"};
    std::array<int, 2> test;
    CHECK_NOTHROW(iguana::parse_item(test, str.begin(), str.end()));
  }
  {
    std::string str{"[   "};
    std::array<int, 2> test;
    CHECK_THROWS(iguana::parse_item(test, str.begin(), str.end()));
  }
  {
    std::string str{"[ ]  "};
    std::array<int, 2> test;
    CHECK_NOTHROW(iguana::parse_item(test, str.begin(), str.end()));
  }
  {
    std::string str{"[ 1.2345]  "};
    std::array<int, 2> test;
    CHECK_THROWS(iguana::parse_item(test, str.begin(), str.end()));
  }
}

TEST_CASE("test parse item str_t") {
  {
    std::string str{"\"aaaaaaaaaa1\""};
    std::string test{};
    iguana::parse_item(test, str.begin(), str.end());
    CHECK(test == str.substr(1, test.size()));
  }
  {
    // this case throw at json_util@line 132
    std::string str{"\"aaa1\""};
    std::string test{};
    //iguana::parse_item(test, str.begin(), str.end());
    //CHECK(test == str.substr(1, test.size()));
  }
}

TEST_CASE("test parse item seq container") {
    {
        std::string str{ "[0,1,2,3]" };
        std::vector<double> test{};
        iguana::parse_item(test, str.begin(), str.end());
        CHECK(test.size() == 4);
        CHECK(test[0] == 0);
        CHECK(test[1] == 1);
        CHECK(test[2] == 2);
        CHECK(test[3] == 3);
    }
    {
        std::string str{ "[0,1,2,3,]" };
        std::vector<double> test{};
        CHECK_THROWS(iguana::parse_item(test, str.begin(), str.end()));
    }
    {
        std::string str{ "[0,1,2,3," };
        std::vector<double> test{};
        CHECK_THROWS(iguana::parse_item(test, str.begin(), str.end()));
    }
}

TEST_CASE("test parse item map container")
{
    {
        std::string str{ "{\"key1\":\"value1\", \"key2\":\"value2\"}" };
        std::map<std::string, std::string> test{};
        iguana::parse_item(test, str.begin(), str.end());
        CHECK(test.size() == 2);
        CHECK(test.at("key1") == "value1");
        CHECK(test.at("key2") == "value2");
    }
}

TEST_CASE("test parse item char")
{
    {
        std::string str{ "\"c\"" };
        char test{};
        iguana::parse_item(test, str.begin(), str.end());
        CHECK(test == 'c');
    }
    {
        std::string str{ "\"" };
        char test{};
        CHECK_THROWS(iguana::parse_item(test, str.begin(), str.end()));
    }
    {
        std::string str{ "" };
        char test{};
        CHECK_THROWS(iguana::parse_item(test, str.begin(), str.end()));
    }
}

// doctest comments
// 'function' : must be 'attribute' - see issue #182
DOCTEST_MSVC_SUPPRESS_WARNING_WITH_PUSH(4007) int main(int argc, char **argv) {
    return doctest::Context(argc, argv).run();
}
DOCTEST_MSVC_SUPPRESS_WARNING_POP<commit_msg>more ut for json reader<commit_after>
#define DOCTEST_CONFIG_IMPLEMENT
#include "doctest.h"
#include "iguana/json_reader.hpp"
#include "test_headers.h"
#include <iguana/json.hpp>
#include <iguana/json_util.hpp>
#include <iostream>

TEST_CASE("test parse item num_t") {
  {
    std::string str{"1.4806532964699196e-22"};
    double p{};
    iguana::parse_item(p, str.begin(), str.end());
    CHECK(p == 1.4806532964699196e-22);
  }
  {
    std::string str{""};
    double p{};
    CHECK_THROWS(iguana::parse_item(p, str.begin(), str.end()));
  }
  {
    std::string str{"1.0"};
    int p{};
    iguana::parse_item(p, str.begin(), str.end());
    CHECK(p == 1);
  }
  {
    std::string str{"3e6"};
    int p{};
    iguana::parse_item(p, str.begin(), str.end());
    //throw here because parsed p = 3 and said not correct.
    //CHECK(p == 3e6);
  }
  {
    std::string str;
    str.append(300, '1');
    int p{};
    CHECK_THROWS(iguana::parse_item(p, str.begin(), str.end()));
  }
  {
    std::list<char> arr{ '0','.','9'};
    double test = 0;
    iguana::parse_item(test, arr.begin(), arr.end());
    CHECK(test == 0.9);
  }
  {
    std::list<char> arr{ '0','.','9' };
    for (int i = 0; i < 999; i++)
    {
        arr.push_back('1');
    }

    double test = 0;
    CHECK_THROWS(iguana::parse_item(test, arr.begin(), arr.end()));
  }
}

TEST_CASE("test parse item array_t") {
  {
    std::string str{"[1, -222]"};
    std::array<int, 2> test;
    iguana::parse_item(test, str.begin(), str.end());
    CHECK(test[0] == 1);
    CHECK(test[1] == -222);
  }
  {
    std::string str{"[1, -222,"};
    std::array<int, 2> test;
    CHECK_NOTHROW(iguana::parse_item(test, str.begin(), str.end()));
  }
  {
    std::string str{"[   "};
    std::array<int, 2> test;
    CHECK_THROWS(iguana::parse_item(test, str.begin(), str.end()));
  }
  {
    std::string str{"[ ]  "};
    std::array<int, 2> test;
    CHECK_NOTHROW(iguana::parse_item(test, str.begin(), str.end()));
  }
  {
    std::string str{"[ 1.2345]  "};
    std::array<int, 2> test;
    CHECK_THROWS(iguana::parse_item(test, str.begin(), str.end()));
  }
}

TEST_CASE("test parse item str_t") {
  {
    std::string str{"\"aaaaaaaaaa1\""};
    std::string test{};
    iguana::parse_item(test, str.begin(), str.end());
    CHECK(test == str.substr(1, test.size()));
  }
  {
    // this case throw at json_util@line 132
    std::string str{"\"aaa1\""};
    std::string test{};
    //iguana::parse_item(test, str.begin(), str.end());
    //CHECK(test == str.substr(1, test.size()));
  }
  {
    std::list<char> str;
    str.push_back('\\');
    str.push_back('a');
    str.push_back('\"');
    str.push_back('a');
    str.push_back('a');
    str.push_back('1');
    std::string test{};
    test.resize(2);
    iguana::parse_item(test, str.begin(), str.end(),true);
    //CHECK(test.empty());
  }
  {
    std::list<char> str;
    str.push_back('\"');
    str.push_back('a');
    str.push_back('a');
    str.push_back('a');
    str.push_back('1');
    std::string test{};
    test.resize(3);
    iguana::parse_item(test, str.begin(), str.end());
  }
  {
    std::list<char> str;
    str.push_back('\"');
    str.push_back('\\');
    str.push_back('a');
    str.push_back('\"');
    std::string test{};
    test.resize(1);
    iguana::parse_item(test, str.begin(), str.end());
    CHECK(test == "a");
  }
  {
    std::list<char> str;
    str.push_back('\"');
    str.push_back('a');
    str.push_back('\\');
    str.push_back('\"');
    std::string test{};
    iguana::parse_item(test, str.begin(), str.end());
    //CHECK(test == "a");
  }
  {
    std::string str{"\"\\aaaa1\""};
    std::string test{};
    iguana::parse_item(test, str.begin(), str.end());
    CHECK(test == str.substr(2,test.size()));
  }
  {
    std::string str{"\"aaaa1\""};
    std::string test{};
    iguana::parse_item(test, str.begin(), str.end());
    CHECK(test == str.substr(1, test.size()));
  }
}

TEST_CASE("test parse item seq container") {
  {
    std::string str{"[0,1,2,3]"};
    std::vector<double> test{};
    iguana::parse_item(test, str.begin(), str.end());
    CHECK(test.size() == 4);
    CHECK(test[0] == 0);
    CHECK(test[1] == 1);
    CHECK(test[2] == 2);
    CHECK(test[3] == 3);
  }
  {
    std::string str{"[0,1,2,3,]"};
    std::vector<double> test{};
    CHECK_THROWS(iguana::parse_item(test, str.begin(), str.end()));
  }
  {
    std::string str{"[0,1,2,3,"};
    std::vector<double> test{};
    CHECK_THROWS(iguana::parse_item(test, str.begin(), str.end()));
  }
  {
    std::string str{"[0,1,2"};
    std::array<int, 3> test{};
    CHECK_THROWS(iguana::parse_item(test, str.begin(), str.end()));
  }
}

TEST_CASE("test parse item map container")
{
  {
    std::string str{"{\"key1\":\"value1\", \"key2\":\"value2\"}"};
    std::map<std::string, std::string> test{};
    iguana::parse_item(test, str.begin(), str.end());
    CHECK(test.size() == 2);
    CHECK(test.at("key1") == "value1");
    CHECK(test.at("key2") == "value2");
  }
}

TEST_CASE("test parse item char")
{
  {
    std::string str{"\"c\""};
    char test{};
    iguana::parse_item(test, str.begin(), str.end());
    CHECK(test == 'c');
  }
  {
    std::string str{"\""};
    char test{};
    CHECK_THROWS(iguana::parse_item(test, str.begin(), str.end()));
  }
  {
    std::string str{""};
    char test{};
    CHECK_THROWS(iguana::parse_item(test, str.begin(), str.end()));
  }
  {
    std::string str{"\"\\a\""};
    char test{};
    iguana::parse_item(test, str.begin(), str.end());
    CHECK(test == 'a');
  }
}

TEST_CASE("test parse item tuple")
{
  {
    std::string str{"[1],\"a\",1.5]"};

    std::tuple<int, std::string,double> tp;

    iguana::parse_item(tp, str.begin(), str.end());
    CHECK(std::get<0>(tp) == 1);
  }
  {
    std::string str{"[1,\"a\",1.5,[1,1.5]]"};

    std::tuple<int, std::string, double,std::tuple<int,double>> tp;

    iguana::parse_item(tp, str.begin(), str.end());
    CHECK(std::get<0>(tp) == 1);
  }
}

TEST_CASE("test parse item bool")
{
  {
    std::string str{"true"};
    bool test = false;
    iguana::parse_item(test, str.begin(), str.end());
    CHECK(test == true);
  }
  {
    std::string str{"false"};
    bool test = true;
    iguana::parse_item(test, str.begin(), str.end());
    CHECK(test == false);
  }
  {
    std::string str{"True"};
    bool test = false;

    CHECK_THROWS(iguana::parse_item(test, str.begin(), str.end()));
  }
  {
    std::string str{"False"};
    bool test = true;

    CHECK_THROWS(iguana::parse_item(test, str.begin(), str.end()));
  }
  {
    std::string str{"\"false\""};
    bool test = false;

    CHECK_THROWS(iguana::parse_item(test, str.begin(), str.end()));
  }
  {
    std::string str{""};
    bool test = false;
    CHECK_THROWS(iguana::parse_item(test, str.begin(), str.end()));
  }
}

TEST_CASE("test parse item optional")
{
  {
    std::string str{"null"};
    std::optional<int> test{};
    iguana::parse_item(test, str.begin(), str.end());
    CHECK(!test.has_value());
  }
  {
    std::string str{""};
    std::optional<int> test{};
    CHECK_THROWS(iguana::parse_item(test, str.begin(), str.end()));
  }
  {
    std::string str{"1"};
    std::optional<int> test{};
    iguana::parse_item(test, str.begin(), str.end());
    CHECK(*test == 1);
  }
}

// doctest comments
// 'function' : must be 'attribute' - see issue #182
DOCTEST_MSVC_SUPPRESS_WARNING_WITH_PUSH(4007) int main(int argc, char** argv) {
    return doctest::Context(argc, argv).run();
}
DOCTEST_MSVC_SUPPRESS_WARNING_POP<|endoftext|>