<commit_before>/*************************************************************************
 *
 * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
 *
 * Copyright 2008 by Sun Microsystems, Inc.
 *
 * OpenOffice.org - a multi-platform office productivity suite
 *
 * $RCSfile: ManifestImport.cxx,v $
 * $Revision: 1.11 $
 *
 * This file is part of OpenOffice.org.
 *
 * OpenOffice.org is free software: you can redistribute it and/or modify
 * it under the terms of the GNU Lesser General Public License version 3
 * only, as published by the Free Software Foundation.
 *
 * OpenOffice.org is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU Lesser General Public License version 3 for more details
 * (a copy is included in the LICENSE file that accompanied this code).
 *
 * You should have received a copy of the GNU Lesser General Public License
 * version 3 along with OpenOffice.org.  If not, see
 * <http://www.openoffice.org/license.html>
 * for a copy of the LGPLv3 License.
 *
 ************************************************************************/

// MARKER(update_precomp.py): autogen include statement, do not remove
#include "precompiled_package.hxx"
#include <ManifestImport.hxx>
#include <ManifestDefines.hxx>
#ifndef _BASE64_CODEC_HXX_
#include <Base64Codec.hxx>
#endif
#include <com/sun/star/xml/sax/XAttributeList.hpp>
#include <com/sun/star/beans/PropertyValue.hpp>

using namespace com::sun::star::uno;
using namespace com::sun::star::beans;
using namespace com::sun::star;
using namespace rtl;
using namespace std;

ManifestImport::ManifestImport( vector < Sequence < PropertyValue > > & rNewManVector )
: nNumProperty (0)
, bIgnoreEncryptData    ( sal_False )
, rManVector ( rNewManVector )

, sFileEntryElement     ( RTL_CONSTASCII_USTRINGPARAM ( ELEMENT_FILE_ENTRY ) )
, sManifestElement      ( RTL_CONSTASCII_USTRINGPARAM ( ELEMENT_MANIFEST ) )
, sEncryptionDataElement( RTL_CONSTASCII_USTRINGPARAM ( ELEMENT_ENCRYPTION_DATA ) )
, sAlgorithmElement ( RTL_CONSTASCII_USTRINGPARAM ( ELEMENT_ALGORITHM ) )
, sKeyDerivationElement( RTL_CONSTASCII_USTRINGPARAM ( ELEMENT_KEY_DERIVATION ) )

, sCdataAttribute               ( RTL_CONSTASCII_USTRINGPARAM ( ATTRIBUTE_CDATA ) )
, sMediaTypeAttribute           ( RTL_CONSTASCII_USTRINGPARAM ( ATTRIBUTE_MEDIA_TYPE ) )
, sFullPathAttribute            ( RTL_CONSTASCII_USTRINGPARAM ( ATTRIBUTE_FULL_PATH ) )
, sSizeAttribute                ( RTL_CONSTASCII_USTRINGPARAM ( ATTRIBUTE_SIZE ) )
, sSaltAttribute                ( RTL_CONSTASCII_USTRINGPARAM ( ATTRIBUTE_SALT ) )
, sInitialisationVectorAttribute ( RTL_CONSTASCII_USTRINGPARAM ( ATTRIBUTE_INITIALISATION_VECTOR ) )
, sIterationCountAttribute      ( RTL_CONSTASCII_USTRINGPARAM ( ATTRIBUTE_ITERATION_COUNT ) )
, sAlgorithmNameAttribute       ( RTL_CONSTASCII_USTRINGPARAM ( ATTRIBUTE_ALGORITHM_NAME ) )
, sKeyDerivationNameAttribute   ( RTL_CONSTASCII_USTRINGPARAM ( ATTRIBUTE_KEY_DERIVATION_NAME ) )
, sChecksumAttribute            ( RTL_CONSTASCII_USTRINGPARAM ( ATTRIBUTE_CHECKSUM ) )
, sChecksumTypeAttribute        ( RTL_CONSTASCII_USTRINGPARAM ( ATTRIBUTE_CHECKSUM_TYPE ) )

, sFullPathProperty             ( RTL_CONSTASCII_USTRINGPARAM ( "FullPath" ) )
, sMediaTypeProperty            ( RTL_CONSTASCII_USTRINGPARAM ( "MediaType" ) )
, sIterationCountProperty       ( RTL_CONSTASCII_USTRINGPARAM ( "IterationCount" ) )
, sSaltProperty                 ( RTL_CONSTASCII_USTRINGPARAM ( "Salt" ) )
, sInitialisationVectorProperty ( RTL_CONSTASCII_USTRINGPARAM ( "InitialisationVector" ) )
, sSizeProperty                 ( RTL_CONSTASCII_USTRINGPARAM ( "Size" ) )
, sDigestProperty               ( RTL_CONSTASCII_USTRINGPARAM ( "Digest" ) )

, sWhiteSpace                   ( RTL_CONSTASCII_USTRINGPARAM ( " " ) )
, sBlowfish                     ( RTL_CONSTASCII_USTRINGPARAM ( "Blowfish CFB" ) )
, sPBKDF2                       ( RTL_CONSTASCII_USTRINGPARAM ( "PBKDF2" ) )
, sChecksumType                 ( RTL_CONSTASCII_USTRINGPARAM ( CHECKSUM_TYPE ) )
{
}
ManifestImport::~ManifestImport (void )
{
}
void SAL_CALL ManifestImport::startDocument(  )
        throw(xml::sax::SAXException, uno::RuntimeException)
{
}
void SAL_CALL ManifestImport::endDocument(  )
        throw(xml::sax::SAXException, uno::RuntimeException)
{
}
void SAL_CALL ManifestImport::startElement( const OUString& aName, const uno::Reference< xml::sax::XAttributeList >& xAttribs )
        throw(xml::sax::SAXException, uno::RuntimeException)
{
    if (aName == sFileEntryElement)
    {
        aStack.push( e_FileEntry );
        aSequence.realloc ( 7 ); // Can have at most 6 entries (currently, will realloc to actual number in endElement)

        // Put full-path property first for MBA
        aSequence[nNumProperty].Name = sFullPathProperty;
        aSequence[nNumProperty++].Value <<= xAttribs->getValueByName( sFullPathAttribute );
        aSequence[nNumProperty].Name = sMediaTypeProperty;
        aSequence[nNumProperty++].Value <<= xAttribs->getValueByName( sMediaTypeAttribute );

        OUString sSize = xAttribs->getValueByName ( sSizeAttribute );
        if (sSize.getLength())
        {
            sal_Int32 nSize;
            nSize = sSize.toInt32();
            aSequence[nNumProperty].Name = sSizeProperty;
            aSequence[nNumProperty++].Value <<= nSize;
        }
    }
    else if (!aStack.empty())
    {
        if (aStack.top() == e_FileEntry && aName == sEncryptionDataElement)
        {
            // If this element exists, then this stream is encrypted and we need
            // to store the initialisation vector, salt and iteration count used
            aStack.push (e_EncryptionData );
            OUString aString = xAttribs->getValueByName ( sChecksumTypeAttribute );
            if (aString == sChecksumType && !bIgnoreEncryptData)
            {
                aString = xAttribs->getValueByName ( sChecksumAttribute );
                Sequence < sal_uInt8 > aDecodeBuffer;
                Base64Codec::decodeBase64 (aDecodeBuffer, aString);
                aSequence[nNumProperty].Name = sDigestProperty;
                aSequence[nNumProperty++].Value <<= aDecodeBuffer;
            }
        }
        else if (aStack.top() == e_EncryptionData && aName == sAlgorithmElement)
        {
            aStack.push (e_Algorithm);
            OUString aString = xAttribs->getValueByName ( sAlgorithmNameAttribute );
            if (aString == sBlowfish && !bIgnoreEncryptData)
            {
                aString = xAttribs->getValueByName ( sInitialisationVectorAttribute );
                Sequence < sal_uInt8 > aDecodeBuffer;
                Base64Codec::decodeBase64 (aDecodeBuffer, aString);
                aSequence[nNumProperty].Name = sInitialisationVectorProperty;
                aSequence[nNumProperty++].Value <<= aDecodeBuffer;
            }
            else
                // If we don't recognise the algorithm, then the key derivation info
                // is useless to us
                bIgnoreEncryptData = sal_True;
        }
        else if (aStack.top() == e_EncryptionData && aName == sKeyDerivationElement)
        {
            aStack.push (e_KeyDerivation);
            OUString aString = xAttribs->getValueByName ( sKeyDerivationNameAttribute );
            if ( aString == sPBKDF2 && !bIgnoreEncryptData )
            {
                aString = xAttribs->getValueByName ( sSaltAttribute );
                Sequence < sal_uInt8 > aDecodeBuffer;
                Base64Codec::decodeBase64 (aDecodeBuffer, aString);
                aSequence[nNumProperty].Name = sSaltProperty;
                aSequence[nNumProperty++].Value <<= aDecodeBuffer;

                aString = xAttribs->getValueByName ( sIterationCountAttribute );
                aSequence[nNumProperty].Name = sIterationCountProperty;
                aSequence[nNumProperty++].Value <<= aString.toInt32();
            }
            else
                // If we don't recognise the key derivation technique, then the
                // algorithm info is useless to us
                bIgnoreEncryptData = sal_True;
        }
    }
}
void SAL_CALL ManifestImport::endElement( const OUString& /*aName*/ )
    throw(xml::sax::SAXException, uno::RuntimeException)
{
    if ( !aStack.empty() )
    {
        if (aStack.top() == e_FileEntry)
        {
            aSequence.realloc ( nNumProperty );
            bIgnoreEncryptData = sal_False;
            rManVector.push_back ( aSequence );
            nNumProperty = 0;
        }
        aStack.pop();
    }
}
void SAL_CALL ManifestImport::characters( const OUString& /*aChars*/ )
        throw(xml::sax::SAXException, uno::RuntimeException)
{
}
void SAL_CALL ManifestImport::ignorableWhitespace( const OUString& /*aWhitespaces*/ )
        throw(xml::sax::SAXException, uno::RuntimeException)
{
}
void SAL_CALL ManifestImport::processingInstruction( const OUString& /*aTarget*/, const OUString& /*aData*/ )
        throw(xml::sax::SAXException, uno::RuntimeException)
{
}
void SAL_CALL ManifestImport::setDocumentLocator( const uno::Reference< xml::sax::XLocator >& /*xLocator*/ )
        throw(xml::sax::SAXException, uno::RuntimeException)
{
}

<commit_msg>INTEGRATION: CWS jl93 (1.10.58); FILE MERGED 2008/05/06 10:46:23 jl 1.10.58.3: #i86651# wrong order of initialization of members in constructor 2008/05/05 13:28:24 jl 1.10.58.2: RESYNC: (1.10-1.11); FILE MERGED 2008/04/08 15:43:27 mav 1.10.58.1: #i86651# add Version property<commit_after>/*************************************************************************
 *
 * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
 *
 * Copyright 2008 by Sun Microsystems, Inc.
 *
 * OpenOffice.org - a multi-platform office productivity suite
 *
 * $RCSfile: ManifestImport.cxx,v $
 * $Revision: 1.12 $
 *
 * This file is part of OpenOffice.org.
 *
 * OpenOffice.org is free software: you can redistribute it and/or modify
 * it under the terms of the GNU Lesser General Public License version 3
 * only, as published by the Free Software Foundation.
 *
 * OpenOffice.org is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU Lesser General Public License version 3 for more details
 * (a copy is included in the LICENSE file that accompanied this code).
 *
 * You should have received a copy of the GNU Lesser General Public License
 * version 3 along with OpenOffice.org.  If not, see
 * <http://www.openoffice.org/license.html>
 * for a copy of the LGPLv3 License.
 *
 ************************************************************************/

// MARKER(update_precomp.py): autogen include statement, do not remove
#include "precompiled_package.hxx"
#include <ManifestImport.hxx>
#include <ManifestDefines.hxx>
#ifndef _BASE64_CODEC_HXX_
#include <Base64Codec.hxx>
#endif
#include <com/sun/star/xml/sax/XAttributeList.hpp>
#include <com/sun/star/beans/PropertyValue.hpp>

using namespace com::sun::star::uno;
using namespace com::sun::star::beans;
using namespace com::sun::star;
using namespace rtl;
using namespace std;

ManifestImport::ManifestImport( vector < Sequence < PropertyValue > > & rNewManVector )
: nNumProperty (0)
, bIgnoreEncryptData    ( sal_False )
, rManVector ( rNewManVector )

, sFileEntryElement     ( RTL_CONSTASCII_USTRINGPARAM ( ELEMENT_FILE_ENTRY ) )
, sManifestElement      ( RTL_CONSTASCII_USTRINGPARAM ( ELEMENT_MANIFEST ) )
, sEncryptionDataElement( RTL_CONSTASCII_USTRINGPARAM ( ELEMENT_ENCRYPTION_DATA ) )
, sAlgorithmElement ( RTL_CONSTASCII_USTRINGPARAM ( ELEMENT_ALGORITHM ) )
, sKeyDerivationElement( RTL_CONSTASCII_USTRINGPARAM ( ELEMENT_KEY_DERIVATION ) )

, sCdataAttribute               ( RTL_CONSTASCII_USTRINGPARAM ( ATTRIBUTE_CDATA ) )
, sMediaTypeAttribute           ( RTL_CONSTASCII_USTRINGPARAM ( ATTRIBUTE_MEDIA_TYPE ) )
, sVersionAttribute             ( RTL_CONSTASCII_USTRINGPARAM ( ATTRIBUTE_VERSION ) )
, sFullPathAttribute            ( RTL_CONSTASCII_USTRINGPARAM ( ATTRIBUTE_FULL_PATH ) )
, sSizeAttribute                ( RTL_CONSTASCII_USTRINGPARAM ( ATTRIBUTE_SIZE ) )
, sSaltAttribute                ( RTL_CONSTASCII_USTRINGPARAM ( ATTRIBUTE_SALT ) )
, sInitialisationVectorAttribute ( RTL_CONSTASCII_USTRINGPARAM ( ATTRIBUTE_INITIALISATION_VECTOR ) )
, sIterationCountAttribute      ( RTL_CONSTASCII_USTRINGPARAM ( ATTRIBUTE_ITERATION_COUNT ) )
, sAlgorithmNameAttribute       ( RTL_CONSTASCII_USTRINGPARAM ( ATTRIBUTE_ALGORITHM_NAME ) )
, sKeyDerivationNameAttribute   ( RTL_CONSTASCII_USTRINGPARAM ( ATTRIBUTE_KEY_DERIVATION_NAME ) )
, sChecksumAttribute            ( RTL_CONSTASCII_USTRINGPARAM ( ATTRIBUTE_CHECKSUM ) )
, sChecksumTypeAttribute        ( RTL_CONSTASCII_USTRINGPARAM ( ATTRIBUTE_CHECKSUM_TYPE ) )

, sFullPathProperty             ( RTL_CONSTASCII_USTRINGPARAM ( "FullPath" ) )
, sMediaTypeProperty            ( RTL_CONSTASCII_USTRINGPARAM ( "MediaType" ) )
, sVersionProperty              ( RTL_CONSTASCII_USTRINGPARAM ( "Version" ) )
, sIterationCountProperty       ( RTL_CONSTASCII_USTRINGPARAM ( "IterationCount" ) )
, sSaltProperty                 ( RTL_CONSTASCII_USTRINGPARAM ( "Salt" ) )
, sInitialisationVectorProperty ( RTL_CONSTASCII_USTRINGPARAM ( "InitialisationVector" ) )
, sSizeProperty                 ( RTL_CONSTASCII_USTRINGPARAM ( "Size" ) )
, sDigestProperty               ( RTL_CONSTASCII_USTRINGPARAM ( "Digest" ) )

, sWhiteSpace                   ( RTL_CONSTASCII_USTRINGPARAM ( " " ) )
, sBlowfish                     ( RTL_CONSTASCII_USTRINGPARAM ( "Blowfish CFB" ) )
, sPBKDF2                       ( RTL_CONSTASCII_USTRINGPARAM ( "PBKDF2" ) )
, sChecksumType                 ( RTL_CONSTASCII_USTRINGPARAM ( CHECKSUM_TYPE ) )
{
}
ManifestImport::~ManifestImport (void )
{
}
void SAL_CALL ManifestImport::startDocument(  )
        throw(xml::sax::SAXException, uno::RuntimeException)
{
}
void SAL_CALL ManifestImport::endDocument(  )
        throw(xml::sax::SAXException, uno::RuntimeException)
{
}
void SAL_CALL ManifestImport::startElement( const OUString& aName, const uno::Reference< xml::sax::XAttributeList >& xAttribs )
        throw(xml::sax::SAXException, uno::RuntimeException)
{
    if (aName == sFileEntryElement)
    {
        aStack.push( e_FileEntry );
        aSequence.realloc ( PKG_SIZE_ENCR_MNFST );

        // Put full-path property first for MBA
        aSequence[nNumProperty].Name = sFullPathProperty;
        aSequence[nNumProperty++].Value <<= xAttribs->getValueByName( sFullPathAttribute );
        aSequence[nNumProperty].Name = sMediaTypeProperty;
        aSequence[nNumProperty++].Value <<= xAttribs->getValueByName( sMediaTypeAttribute );

        OUString sVersion = xAttribs->getValueByName ( sVersionAttribute );
        if ( sVersion.getLength() )
        {
            aSequence[nNumProperty].Name = sVersionProperty;
            aSequence[nNumProperty++].Value <<= sVersion;
        }

        OUString sSize = xAttribs->getValueByName ( sSizeAttribute );
        if (sSize.getLength())
        {
            sal_Int32 nSize;
            nSize = sSize.toInt32();
            aSequence[nNumProperty].Name = sSizeProperty;
            aSequence[nNumProperty++].Value <<= nSize;
        }
    }
    else if (!aStack.empty())
    {
        if (aStack.top() == e_FileEntry && aName == sEncryptionDataElement)
        {
            // If this element exists, then this stream is encrypted and we need
            // to store the initialisation vector, salt and iteration count used
            aStack.push (e_EncryptionData );
            OUString aString = xAttribs->getValueByName ( sChecksumTypeAttribute );
            if (aString == sChecksumType && !bIgnoreEncryptData)
            {
                aString = xAttribs->getValueByName ( sChecksumAttribute );
                Sequence < sal_uInt8 > aDecodeBuffer;
                Base64Codec::decodeBase64 (aDecodeBuffer, aString);
                aSequence[nNumProperty].Name = sDigestProperty;
                aSequence[nNumProperty++].Value <<= aDecodeBuffer;
            }
        }
        else if (aStack.top() == e_EncryptionData && aName == sAlgorithmElement)
        {
            aStack.push (e_Algorithm);
            OUString aString = xAttribs->getValueByName ( sAlgorithmNameAttribute );
            if (aString == sBlowfish && !bIgnoreEncryptData)
            {
                aString = xAttribs->getValueByName ( sInitialisationVectorAttribute );
                Sequence < sal_uInt8 > aDecodeBuffer;
                Base64Codec::decodeBase64 (aDecodeBuffer, aString);
                aSequence[nNumProperty].Name = sInitialisationVectorProperty;
                aSequence[nNumProperty++].Value <<= aDecodeBuffer;
            }
            else
                // If we don't recognise the algorithm, then the key derivation info
                // is useless to us
                bIgnoreEncryptData = sal_True;
        }
        else if (aStack.top() == e_EncryptionData && aName == sKeyDerivationElement)
        {
            aStack.push (e_KeyDerivation);
            OUString aString = xAttribs->getValueByName ( sKeyDerivationNameAttribute );
            if ( aString == sPBKDF2 && !bIgnoreEncryptData )
            {
                aString = xAttribs->getValueByName ( sSaltAttribute );
                Sequence < sal_uInt8 > aDecodeBuffer;
                Base64Codec::decodeBase64 (aDecodeBuffer, aString);
                aSequence[nNumProperty].Name = sSaltProperty;
                aSequence[nNumProperty++].Value <<= aDecodeBuffer;

                aString = xAttribs->getValueByName ( sIterationCountAttribute );
                aSequence[nNumProperty].Name = sIterationCountProperty;
                aSequence[nNumProperty++].Value <<= aString.toInt32();
            }
            else
                // If we don't recognise the key derivation technique, then the
                // algorithm info is useless to us
                bIgnoreEncryptData = sal_True;
        }
    }
}
void SAL_CALL ManifestImport::endElement( const OUString& /*aName*/ )
    throw(xml::sax::SAXException, uno::RuntimeException)
{
    if ( !aStack.empty() )
    {
        if (aStack.top() == e_FileEntry)
        {
            aSequence.realloc ( nNumProperty );
            bIgnoreEncryptData = sal_False;
            rManVector.push_back ( aSequence );
            nNumProperty = 0;
        }
        aStack.pop();
    }
}
void SAL_CALL ManifestImport::characters( const OUString& /*aChars*/ )
        throw(xml::sax::SAXException, uno::RuntimeException)
{
}
void SAL_CALL ManifestImport::ignorableWhitespace( const OUString& /*aWhitespaces*/ )
        throw(xml::sax::SAXException, uno::RuntimeException)
{
}
void SAL_CALL ManifestImport::processingInstruction( const OUString& /*aTarget*/, const OUString& /*aData*/ )
        throw(xml::sax::SAXException, uno::RuntimeException)
{
}
void SAL_CALL ManifestImport::setDocumentLocator( const uno::Reference< xml::sax::XLocator >& /*xLocator*/ )
        throw(xml::sax::SAXException, uno::RuntimeException)
{
}

<|endoftext|>


<commit_before>/***************************************************************************
                          connectionstatusplugin.cpp
                             -------------------
    begin                : 26th Oct 2002
    copyright            : (C) 2002-2003 Chris Howells
    email                : howells@kde.org
 ***************************************************************************/

/***************************************************************************
 *                                                                         *
 *   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; version 2 of the License.		       *
 *                                                                         *
 ***************************************************************************/

#include <kdebug.h>
#include <kgenericfactory.h>
#include <qtimer.h>
#include <kprocess.h>

#include "connectionstatusplugin.h"
#include "kopeteaccountmanager.h"

K_EXPORT_COMPONENT_FACTORY(kopete_connectionstatus, KGenericFactory<ConnectionStatusPlugin>);

ConnectionStatusPlugin::ConnectionStatusPlugin(QObject *parent, const char *name, const QStringList& /* args */ ) : KopetePlugin(parent, name)
{
	kdDebug(14301) << "ConnectionStatusPlugin::ConnectionStatusPlugin()" << endl;

	qtTimer = new QTimer();
	connect(qtTimer, SIGNAL(timeout()), this,
		 SLOT(slotCheckStatus()) );
	qtTimer->start(60000);

	kpIfconfig = new KProcess;
	connect(kpIfconfig, SIGNAL(receivedStdout(KProcess *, char *, int)),
		this, SLOT(slotProcessStdout(KProcess *, char *, int)));

	m_boolPluginConnected = false;
}

ConnectionStatusPlugin::~ConnectionStatusPlugin()
{
	kdDebug(14301) << "ConnectionStatusPlugin::~ConnectionStatusPlugin()" << endl;
	delete qtTimer;
	delete kpIfconfig;
}

void ConnectionStatusPlugin::slotCheckStatus()
{
	/* Use KProcess to run netstat -r. We'll then parse the output of
	* netstat -r in slotProcessStdout() to see if it mentions the
	* default gateway. If so, we're connected, if not, we're offline */

	kdDebug(14301) << "ConnectionStatusPlugin::checkStatus()" << endl;
	*kpIfconfig << "netstat" << "-r";
	kpIfconfig->start(KProcess::DontCare, KProcess::Stdout);
}

void ConnectionStatusPlugin::slotProcessStdout(KProcess *, char *buffer, int buflen)
{
	// Look for a default gateway
	kdDebug(14301) << "ConnectionStatusPlugin::slotProcessStdout()" << endl;
	QString qsBuffer = QString::fromLatin1(buffer, buflen);
	//kdDebug(14301) << qsBuffer << endl;
	setConnectedStatus(qsBuffer.contains("default"));
}

void ConnectionStatusPlugin::setConnectedStatus(bool connected)
{
	/* We have to handle a few cases here. First is the machine is connected, and the plugin thinks
	* we're connected. Then we don't do anything. Next, we can have machine connected, but plugin thinks
	* we're disconnected. Also, machine disconnected, plugin disconnected -- we
	* don't do anything. Finally, we can have the machine disconnected, and the plugin thinks we're
	* connected. This mechanism is required so that we don't keep calling the connect/disconnect functions
	* constantly.
	*/

	kdDebug(14301) << "ConnectionStatusPlugin::setConnectedStatus()" << endl;

	if (connected && !m_boolPluginConnected) // the machine is connected and plugin thinks we're disconnected
	{
		kdDebug(14301) << "Setting m_boolPluginConnected to true" << endl;
		m_boolPluginConnected = true;
		kdDebug(14301) << "ConnectionStatusPlugin::setConnectedStatus() -- we're connected" << endl;
		KopeteAccountManager::manager()->connectAll();
	}
	else
	if (!connected && m_boolPluginConnected) // the machine isn't connected and plugin thinks we're connected
	{
		kdDebug(14301) << "Setting m_boolPluginConnected to false" << endl;
		m_boolPluginConnected = false;
		kdDebug(14301) << "ConnectionStatusPlugin::setConnectedStatus() -- we're offline" << endl;
		KopeteAccountManager::manager()->disconnectAll();
	}
}

#include "connectionstatusplugin.moc"

// vim: set noet ts=4 sts=4 sw=4:

<commit_msg>Correct a problem which seems to have been caused by changes to KProcess. Don't accumulate '-r' options eventually meaning that netstat -r -r -r -r -r etc is called.<commit_after>/***************************************************************************
                          connectionstatusplugin.cpp
                             -------------------
    begin                : 26th Oct 2002
    copyright            : (C) 2002-2003 Chris Howells
    email                : howells@kde.org
 ***************************************************************************/

/***************************************************************************
 *                                                                         *
 *   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; version 2 of the License.		       *
 *                                                                         *
 ***************************************************************************/

#include <kdebug.h>
#include <kgenericfactory.h>
#include <qtimer.h>
#include <kprocess.h>

#include "connectionstatusplugin.h"
#include "kopeteaccountmanager.h"

K_EXPORT_COMPONENT_FACTORY(kopete_connectionstatus, KGenericFactory<ConnectionStatusPlugin>);

ConnectionStatusPlugin::ConnectionStatusPlugin(QObject *parent, const char *name, const QStringList& /* args */ ) : KopetePlugin(parent, name)
{
	kdDebug(14301) << "ConnectionStatusPlugin::ConnectionStatusPlugin()" << endl;

	qtTimer = new QTimer();
	connect(qtTimer, SIGNAL(timeout()), this,
		 SLOT(slotCheckStatus()) );
	qtTimer->start(60000);

	kpIfconfig = new KProcess;
        *kpIfconfig << "netstat" << "-r";
	connect(kpIfconfig, SIGNAL(receivedStdout(KProcess *, char *, int)),
		this, SLOT(slotProcessStdout(KProcess *, char *, int)));

	m_boolPluginConnected = false;
}

ConnectionStatusPlugin::~ConnectionStatusPlugin()
{
	kdDebug(14301) << "ConnectionStatusPlugin::~ConnectionStatusPlugin()" << endl;
	delete qtTimer;
	delete kpIfconfig;
}

void ConnectionStatusPlugin::slotCheckStatus()
{
	/* Use KProcess to run netstat -r. We'll then parse the output of
	* netstat -r in slotProcessStdout() to see if it mentions the
	* default gateway. If so, we're connected, if not, we're offline */

	kdDebug(14301) << "ConnectionStatusPlugin::checkStatus()" << endl;
	kpIfconfig->start(KProcess::DontCare, KProcess::Stdout);
}

void ConnectionStatusPlugin::slotProcessStdout(KProcess *, char *buffer, int buflen)
{
	// Look for a default gateway
	kdDebug(14301) << "ConnectionStatusPlugin::slotProcessStdout()" << endl;
	QString qsBuffer = QString::fromLatin1(buffer, buflen);
	//kdDebug(14301) << qsBuffer << endl;
	setConnectedStatus(qsBuffer.contains("default"));
}

void ConnectionStatusPlugin::setConnectedStatus(bool connected)
{
	/* We have to handle a few cases here. First is the machine is connected, and the plugin thinks
	* we're connected. Then we don't do anything. Next, we can have machine connected, but plugin thinks
	* we're disconnected. Also, machine disconnected, plugin disconnected -- we
	* don't do anything. Finally, we can have the machine disconnected, and the plugin thinks we're
	* connected. This mechanism is required so that we don't keep calling the connect/disconnect functions
	* constantly.
	*/

	kdDebug(14301) << "ConnectionStatusPlugin::setConnectedStatus()" << endl;

	if (connected && !m_boolPluginConnected) // the machine is connected and plugin thinks we're disconnected
	{
		kdDebug(14301) << "Setting m_boolPluginConnected to true" << endl;
		m_boolPluginConnected = true;
		kdDebug(14301) << "ConnectionStatusPlugin::setConnectedStatus() -- we're connected" << endl;
		KopeteAccountManager::manager()->connectAll();
	}
	else
	if (!connected && m_boolPluginConnected) // the machine isn't connected and plugin thinks we're connected
	{
		kdDebug(14301) << "Setting m_boolPluginConnected to false" << endl;
		m_boolPluginConnected = false;
		kdDebug(14301) << "ConnectionStatusPlugin::setConnectedStatus() -- we're offline" << endl;
		KopeteAccountManager::manager()->disconnectAll();
	}
}

#include "connectionstatusplugin.moc"

// vim: set noet ts=4 sts=4 sw=4:

<|endoftext|>


<commit_before>/**************************************************************************
**
** This file is part of Qt Creator
**
** Copyright (c) 2011 Nokia Corporation and/or its subsidiary(-ies).
**
** Contact: Nokia Corporation (qt-info@nokia.com)
**
** No Commercial Usage
**
** This file contains pre-release code and may not be distributed.
** You may use this file in accordance with the terms and conditions
** contained in the Technology Preview License Agreement accompanying
** this package.
**
** GNU Lesser General Public License Usage
**
** Alternatively, this file may be used under the terms of the GNU Lesser
** General Public License version 2.1 as published by the Free Software
** Foundation and appearing in the file LICENSE.LGPL included in the
** packaging of this file.  Please review the following information to
** ensure the GNU Lesser General Public License version 2.1 requirements
** will be met: http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
**
** In addition, as a special exception, Nokia gives you certain additional
** rights.  These rights are described in the Nokia Qt LGPL Exception
** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.
**
** If you have questions regarding the use of this file, please contact
** Nokia at qt-info@nokia.com.
**
**************************************************************************/

#include "formeditorgraphicsview.h"

#include <QWheelEvent>
#include <QApplication>
#include <QtDebug>

#include <qmlanchors.h>

namespace QmlDesigner {

FormEditorGraphicsView::FormEditorGraphicsView(QWidget *parent) :
    QGraphicsView(parent)
{
    setTransformationAnchor(QGraphicsView::AnchorUnderMouse);
    setResizeAnchor(QGraphicsView::AnchorViewCenter);
    setCacheMode(QGraphicsView::CacheNone);
//    setCacheMode(QGraphicsView::CacheBackground);
    setViewportUpdateMode(QGraphicsView::BoundingRectViewportUpdate);
    setOptimizationFlags(QGraphicsView::DontSavePainterState);
//    setViewportUpdateMode(QGraphicsView::NoViewportUpdate);
    setRenderHint(QPainter::Antialiasing, false);

    setFrameShape(QFrame::NoFrame);

    setAutoFillBackground(true);
    setBackgroundRole(QPalette::Window);

    const int checkerbordSize= 20;
    QPixmap tilePixmap(checkerbordSize * 2, checkerbordSize * 2);
    tilePixmap.fill(Qt::white);
    QPainter tilePainter(&tilePixmap);
    QColor color(220, 220, 220);
    tilePainter.fillRect(0, 0, checkerbordSize, checkerbordSize, color);
    tilePainter.fillRect(checkerbordSize, checkerbordSize, checkerbordSize, checkerbordSize, color);
    tilePainter.end();

    setBackgroundBrush(tilePixmap);

    viewport()->setMouseTracking(true);
}

void FormEditorGraphicsView::wheelEvent(QWheelEvent *event)
{
    if (event->modifiers().testFlag(Qt::ControlModifier)) {
        event->ignore();
    } else {
        QGraphicsView::wheelEvent(event);
    }

}

void FormEditorGraphicsView::mouseMoveEvent(QMouseEvent *event)
{
    if (rect().contains(event->pos())) {
        QGraphicsView::mouseMoveEvent(event);
    } else {
        QPoint position = event->pos();
        QPoint topLeft = rect().topLeft();
        QPoint bottomRight = rect().bottomRight();
        position.rx() = qMax(topLeft.x(), qMin(position.x(), bottomRight.x()));
        position.ry() = qMax(topLeft.y(), qMin(position.y(), bottomRight.y()));
        QMouseEvent *mouseEvent = QMouseEvent::createExtendedMouseEvent(event->type(), position, mapToGlobal(position), event->button(), event->buttons(), event->modifiers());

        QGraphicsView::mouseMoveEvent(mouseEvent);
        delete mouseEvent;
    }

    // Keeps the feedback bubble within screen boundraries
    int tx = qMin(width() - 114,  qMax(16, event->pos().x() + 50));
    int ty = qMin(height() - 45, qMax(10, event->pos().y() - 70));
    m_feedbackOriginPoint = QPoint(tx, ty);
}

void FormEditorGraphicsView::keyPressEvent(QKeyEvent *event)
{
    m_feedbackOriginPoint = QPoint();
    QGraphicsView::keyPressEvent(event);
}

void FormEditorGraphicsView::setRootItemRect(const QRectF &rect)
{
    m_rootItemRect = rect;
    qDebug() << __FUNCTION__ << m_rootItemRect;
}

QRectF FormEditorGraphicsView::rootItemRect() const
{
    return m_rootItemRect;
}

void FormEditorGraphicsView::mouseReleaseEvent(QMouseEvent *event)
{
    if (rect().contains(event->pos())) {
        QGraphicsView::mouseReleaseEvent(event);
    } else {
        QPoint position = event->pos();
        QPoint topLeft = rect().topLeft();
        QPoint bottomRight = rect().bottomRight();
        position.rx() = qMax(topLeft.x(), qMin(position.x(), bottomRight.x()));
        position.ry() = qMax(topLeft.y(), qMin(position.y(), bottomRight.y()));
        QMouseEvent *mouseEvent = QMouseEvent::createExtendedMouseEvent(event->type(), position, mapToGlobal(position), event->button(), event->buttons(), event->modifiers());

        QGraphicsView::mouseReleaseEvent(mouseEvent);
        delete mouseEvent;
    }

    m_feedbackOriginPoint = QPoint();
}

void FormEditorGraphicsView::leaveEvent(QEvent *event)
{
     m_feedbackOriginPoint = QPoint();
     QGraphicsView::leaveEvent(event);
 }

static QPixmap createBubblePixmap()
{
    QPixmap pixmap(124, 48);
    pixmap.fill(Qt::transparent);
    QPainter pmPainter(&pixmap);
    pmPainter.setRenderHint(QPainter::Antialiasing);
    pmPainter.setOpacity(0.85);
    pmPainter.translate(0.5, 0.5);
    pmPainter.setPen(Qt::NoPen);
    pmPainter.setBrush(QColor(0, 0, 0, 40));
    pmPainter.drawRoundedRect(QRect(0, 0, 124, 48), 8, 8);
    QLinearGradient gradient(QPoint(0, 0), QPoint(0, 44));
    gradient.setColorAt(0.0, QColor(70, 70, 70));
    gradient.setColorAt(1.0, QColor(10, 10, 10));
    pmPainter.setBrush(gradient);
    pmPainter.setPen(QColor(60, 60, 60));
    pmPainter.drawRoundedRect(QRect(2, 1, 120, 45), 5, 5);
    pmPainter.setBrush(Qt::NoBrush);
    pmPainter.setPen(QColor(255, 255, 255, 140));
    pmPainter.drawRoundedRect(QRect(3, 2, 118, 43), 5, 5);
    pmPainter.end();
    return pixmap;
}

void FormEditorGraphicsView::drawForeground(QPainter *painter, const QRectF &/*rect*/ )
{
    if (!m_feedbackNode.isValid())
        return;

    if (m_feedbackOriginPoint.isNull())
        return;

    painter->save();
    painter->resetTransform();
    painter->translate(m_feedbackOriginPoint);

    QColor defaultColor(Qt::white);
    QColor changeColor("#9999ff");

    QFont font;
    font.setFamily("Helvetica");
    font.setPixelSize(12);
    painter->setFont(font);

    if (m_bubblePixmap.isNull())
        m_bubblePixmap = createBubblePixmap();
    painter->drawPixmap(-13, -7, m_bubblePixmap);

    if (m_beginXHasExpression) {
        if(m_feedbackNode.hasBindingProperty("x"))
            painter->setPen(defaultColor);
        else
            painter->setPen(Qt::red);
    } else {
        if (m_beginX != m_feedbackNode.instanceValue("x"))
            painter->setPen(changeColor);
        else
            painter->setPen(defaultColor);
    }

    painter->drawText(QPoint(8.0, 13.0), QString("x:"));
    painter->drawText(QPoint(22.0, 13.0), m_feedbackNode.instanceValue("x").toString());

    if (m_beginYHasExpression) {
        if(m_feedbackNode.hasBindingProperty("y"))
            painter->setPen(defaultColor);
        else
            painter->setPen(Qt::red);
    } else {
        if (m_beginY != m_feedbackNode.instanceValue("y"))
            painter->setPen(changeColor);
        else
            painter->setPen(defaultColor);
    }

    painter->drawText(QPoint(60.0, 13.0), QString("y:"));
    painter->drawText(QPoint(72.0, 13.0), m_feedbackNode.instanceValue("y").toString());

    if (m_beginWidthHasExpression) {
        if(m_feedbackNode.hasBindingProperty("width"))
            painter->setPen(defaultColor);
        else
            painter->setPen(Qt::red);
    } else {
        if (m_beginWidth != m_feedbackNode.instanceValue("width"))
            painter->setPen(changeColor);
        else
            painter->setPen(defaultColor);
    }

    painter->drawText(QPoint(8.0, 29.0), QString("w:"));
    painter->drawText(QPoint(22.0, 29.0), m_feedbackNode.instanceValue("width").toString());

    if (m_beginHeightHasExpression) {
        if(m_feedbackNode.hasBindingProperty("height"))
            painter->setPen(defaultColor);
        else
            painter->setPen(Qt::red);
    } else {
        if (m_beginHeight != m_feedbackNode.instanceValue("height"))
            painter->setPen(changeColor);
        else
            painter->setPen(defaultColor);
    }

    painter->drawText(QPoint(60.0, 29.0), QString("h:"));
    painter->drawText(QPoint(72.0, 29.0), m_feedbackNode.instanceValue("height").toString());

    if (m_parentNode != m_feedbackNode.instanceParent()) {
        painter->setPen(changeColor);
        painter->drawText(QPoint(2.0, 39.0), QString("Parent changed"));

    }

    painter->restore();
}

void FormEditorGraphicsView::setFeedbackNode(const QmlItemNode &node)
{
    if (node == m_feedbackNode)
        return;

    m_feedbackNode = node;

    if (m_feedbackNode.isValid()) {
        m_beginX = m_feedbackNode.instanceValue("x");
        m_beginY = m_feedbackNode.instanceValue("y");
        m_beginWidth = m_feedbackNode.instanceValue("width");
        m_beginHeight = m_feedbackNode.instanceValue("height");
        m_parentNode = m_feedbackNode.instanceParent();
        m_beginLeftMargin = m_feedbackNode.instanceValue("anchors.leftMargin");
        m_beginRightMargin = m_feedbackNode.instanceValue("anchors.rightMargin");
        m_beginTopMargin = m_feedbackNode.instanceValue("anchors.topMargin");
        m_beginBottomMargin = m_feedbackNode.instanceValue("anchors.bottomMargin");
        m_beginXHasExpression = m_feedbackNode.hasBindingProperty("x");
        m_beginYHasExpression = m_feedbackNode.hasBindingProperty("y");
        m_beginWidthHasExpression = m_feedbackNode.hasBindingProperty("width");
        m_beginHeightHasExpression = m_feedbackNode.hasBindingProperty("height");
    } else {
        m_beginX = QVariant();
        m_beginY = QVariant();
        m_beginWidth = QVariant();
        m_beginHeight = QVariant();
        m_parentNode = QmlObjectNode();
        m_beginLeftMargin = QVariant();
        m_beginRightMargin = QVariant();
        m_beginTopMargin = QVariant();
        m_beginBottomMargin = QVariant();
        m_beginXHasExpression = false;
        m_beginYHasExpression = false;
        m_beginWidthHasExpression = false;
        m_beginHeightHasExpression = false;
    }
}

void FormEditorGraphicsView::drawBackground(QPainter *painter, const QRectF &rect)
{
    painter->save();
    painter->setBrushOrigin(0, 0);
    painter->fillRect(rect.intersected(rootItemRect()), backgroundBrush());
    // paint rect around editable area
    painter->setPen(Qt::black);
    painter->drawRect( rootItemRect());
    painter->restore();
}

} // namespace QmlDesigner
<commit_msg>QmlDesigner: Fix the formeditor background<commit_after>/**************************************************************************
**
** This file is part of Qt Creator
**
** Copyright (c) 2011 Nokia Corporation and/or its subsidiary(-ies).
**
** Contact: Nokia Corporation (qt-info@nokia.com)
**
** No Commercial Usage
**
** This file contains pre-release code and may not be distributed.
** You may use this file in accordance with the terms and conditions
** contained in the Technology Preview License Agreement accompanying
** this package.
**
** GNU Lesser General Public License Usage
**
** Alternatively, this file may be used under the terms of the GNU Lesser
** General Public License version 2.1 as published by the Free Software
** Foundation and appearing in the file LICENSE.LGPL included in the
** packaging of this file.  Please review the following information to
** ensure the GNU Lesser General Public License version 2.1 requirements
** will be met: http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
**
** In addition, as a special exception, Nokia gives you certain additional
** rights.  These rights are described in the Nokia Qt LGPL Exception
** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.
**
** If you have questions regarding the use of this file, please contact
** Nokia at qt-info@nokia.com.
**
**************************************************************************/

#include "formeditorgraphicsview.h"

#include <QWheelEvent>
#include <QApplication>
#include <QtDebug>

#include <qmlanchors.h>

namespace QmlDesigner {

FormEditorGraphicsView::FormEditorGraphicsView(QWidget *parent) :
    QGraphicsView(parent)
{
    setTransformationAnchor(QGraphicsView::AnchorUnderMouse);
    setResizeAnchor(QGraphicsView::AnchorViewCenter);
    setCacheMode(QGraphicsView::CacheNone);
//    setCacheMode(QGraphicsView::CacheBackground);
    setViewportUpdateMode(QGraphicsView::BoundingRectViewportUpdate);
    setOptimizationFlags(QGraphicsView::DontSavePainterState);
//    setViewportUpdateMode(QGraphicsView::NoViewportUpdate);
    setRenderHint(QPainter::Antialiasing, false);

    setFrameShape(QFrame::NoFrame);

    setAutoFillBackground(true);
    setBackgroundRole(QPalette::Window);

    const int checkerbordSize= 20;
    QPixmap tilePixmap(checkerbordSize * 2, checkerbordSize * 2);
    tilePixmap.fill(Qt::white);
    QPainter tilePainter(&tilePixmap);
    QColor color(220, 220, 220);
    tilePainter.fillRect(0, 0, checkerbordSize, checkerbordSize, color);
    tilePainter.fillRect(checkerbordSize, checkerbordSize, checkerbordSize, checkerbordSize, color);
    tilePainter.end();

    setBackgroundBrush(tilePixmap);

    viewport()->setMouseTracking(true);
}

void FormEditorGraphicsView::wheelEvent(QWheelEvent *event)
{
    if (event->modifiers().testFlag(Qt::ControlModifier)) {
        event->ignore();
    } else {
        QGraphicsView::wheelEvent(event);
    }

}

void FormEditorGraphicsView::mouseMoveEvent(QMouseEvent *event)
{
    if (rect().contains(event->pos())) {
        QGraphicsView::mouseMoveEvent(event);
    } else {
        QPoint position = event->pos();
        QPoint topLeft = rect().topLeft();
        QPoint bottomRight = rect().bottomRight();
        position.rx() = qMax(topLeft.x(), qMin(position.x(), bottomRight.x()));
        position.ry() = qMax(topLeft.y(), qMin(position.y(), bottomRight.y()));
        QMouseEvent *mouseEvent = QMouseEvent::createExtendedMouseEvent(event->type(), position, mapToGlobal(position), event->button(), event->buttons(), event->modifiers());

        QGraphicsView::mouseMoveEvent(mouseEvent);
        delete mouseEvent;
    }

    // Keeps the feedback bubble within screen boundraries
    int tx = qMin(width() - 114,  qMax(16, event->pos().x() + 50));
    int ty = qMin(height() - 45, qMax(10, event->pos().y() - 70));
    m_feedbackOriginPoint = QPoint(tx, ty);
}

void FormEditorGraphicsView::keyPressEvent(QKeyEvent *event)
{
    m_feedbackOriginPoint = QPoint();
    QGraphicsView::keyPressEvent(event);
}

void FormEditorGraphicsView::setRootItemRect(const QRectF &rect)
{
    m_rootItemRect = rect;
    update();
}

QRectF FormEditorGraphicsView::rootItemRect() const
{
    return m_rootItemRect;
}

void FormEditorGraphicsView::mouseReleaseEvent(QMouseEvent *event)
{
    if (rect().contains(event->pos())) {
        QGraphicsView::mouseReleaseEvent(event);
    } else {
        QPoint position = event->pos();
        QPoint topLeft = rect().topLeft();
        QPoint bottomRight = rect().bottomRight();
        position.rx() = qMax(topLeft.x(), qMin(position.x(), bottomRight.x()));
        position.ry() = qMax(topLeft.y(), qMin(position.y(), bottomRight.y()));
        QMouseEvent *mouseEvent = QMouseEvent::createExtendedMouseEvent(event->type(), position, mapToGlobal(position), event->button(), event->buttons(), event->modifiers());

        QGraphicsView::mouseReleaseEvent(mouseEvent);
        delete mouseEvent;
    }

    m_feedbackOriginPoint = QPoint();
}

void FormEditorGraphicsView::leaveEvent(QEvent *event)
{
     m_feedbackOriginPoint = QPoint();
     QGraphicsView::leaveEvent(event);
 }

static QPixmap createBubblePixmap()
{
    QPixmap pixmap(124, 48);
    pixmap.fill(Qt::transparent);
    QPainter pmPainter(&pixmap);
    pmPainter.setRenderHint(QPainter::Antialiasing);
    pmPainter.setOpacity(0.85);
    pmPainter.translate(0.5, 0.5);
    pmPainter.setPen(Qt::NoPen);
    pmPainter.setBrush(QColor(0, 0, 0, 40));
    pmPainter.drawRoundedRect(QRect(0, 0, 124, 48), 8, 8);
    QLinearGradient gradient(QPoint(0, 0), QPoint(0, 44));
    gradient.setColorAt(0.0, QColor(70, 70, 70));
    gradient.setColorAt(1.0, QColor(10, 10, 10));
    pmPainter.setBrush(gradient);
    pmPainter.setPen(QColor(60, 60, 60));
    pmPainter.drawRoundedRect(QRect(2, 1, 120, 45), 5, 5);
    pmPainter.setBrush(Qt::NoBrush);
    pmPainter.setPen(QColor(255, 255, 255, 140));
    pmPainter.drawRoundedRect(QRect(3, 2, 118, 43), 5, 5);
    pmPainter.end();
    return pixmap;
}

void FormEditorGraphicsView::drawForeground(QPainter *painter, const QRectF &/*rect*/ )
{
    if (!m_feedbackNode.isValid())
        return;

    if (m_feedbackOriginPoint.isNull())
        return;

    painter->save();
    painter->resetTransform();
    painter->translate(m_feedbackOriginPoint);

    QColor defaultColor(Qt::white);
    QColor changeColor("#9999ff");

    QFont font;
    font.setFamily("Helvetica");
    font.setPixelSize(12);
    painter->setFont(font);

    if (m_bubblePixmap.isNull())
        m_bubblePixmap = createBubblePixmap();
    painter->drawPixmap(-13, -7, m_bubblePixmap);

    if (m_beginXHasExpression) {
        if(m_feedbackNode.hasBindingProperty("x"))
            painter->setPen(defaultColor);
        else
            painter->setPen(Qt::red);
    } else {
        if (m_beginX != m_feedbackNode.instanceValue("x"))
            painter->setPen(changeColor);
        else
            painter->setPen(defaultColor);
    }

    painter->drawText(QPoint(8.0, 13.0), QString("x:"));
    painter->drawText(QPoint(22.0, 13.0), m_feedbackNode.instanceValue("x").toString());

    if (m_beginYHasExpression) {
        if(m_feedbackNode.hasBindingProperty("y"))
            painter->setPen(defaultColor);
        else
            painter->setPen(Qt::red);
    } else {
        if (m_beginY != m_feedbackNode.instanceValue("y"))
            painter->setPen(changeColor);
        else
            painter->setPen(defaultColor);
    }

    painter->drawText(QPoint(60.0, 13.0), QString("y:"));
    painter->drawText(QPoint(72.0, 13.0), m_feedbackNode.instanceValue("y").toString());

    if (m_beginWidthHasExpression) {
        if(m_feedbackNode.hasBindingProperty("width"))
            painter->setPen(defaultColor);
        else
            painter->setPen(Qt::red);
    } else {
        if (m_beginWidth != m_feedbackNode.instanceValue("width"))
            painter->setPen(changeColor);
        else
            painter->setPen(defaultColor);
    }

    painter->drawText(QPoint(8.0, 29.0), QString("w:"));
    painter->drawText(QPoint(22.0, 29.0), m_feedbackNode.instanceValue("width").toString());

    if (m_beginHeightHasExpression) {
        if(m_feedbackNode.hasBindingProperty("height"))
            painter->setPen(defaultColor);
        else
            painter->setPen(Qt::red);
    } else {
        if (m_beginHeight != m_feedbackNode.instanceValue("height"))
            painter->setPen(changeColor);
        else
            painter->setPen(defaultColor);
    }

    painter->drawText(QPoint(60.0, 29.0), QString("h:"));
    painter->drawText(QPoint(72.0, 29.0), m_feedbackNode.instanceValue("height").toString());

    if (m_parentNode != m_feedbackNode.instanceParent()) {
        painter->setPen(changeColor);
        painter->drawText(QPoint(2.0, 39.0), QString("Parent changed"));

    }

    painter->restore();
}

void FormEditorGraphicsView::setFeedbackNode(const QmlItemNode &node)
{
    if (node == m_feedbackNode)
        return;

    m_feedbackNode = node;

    if (m_feedbackNode.isValid()) {
        m_beginX = m_feedbackNode.instanceValue("x");
        m_beginY = m_feedbackNode.instanceValue("y");
        m_beginWidth = m_feedbackNode.instanceValue("width");
        m_beginHeight = m_feedbackNode.instanceValue("height");
        m_parentNode = m_feedbackNode.instanceParent();
        m_beginLeftMargin = m_feedbackNode.instanceValue("anchors.leftMargin");
        m_beginRightMargin = m_feedbackNode.instanceValue("anchors.rightMargin");
        m_beginTopMargin = m_feedbackNode.instanceValue("anchors.topMargin");
        m_beginBottomMargin = m_feedbackNode.instanceValue("anchors.bottomMargin");
        m_beginXHasExpression = m_feedbackNode.hasBindingProperty("x");
        m_beginYHasExpression = m_feedbackNode.hasBindingProperty("y");
        m_beginWidthHasExpression = m_feedbackNode.hasBindingProperty("width");
        m_beginHeightHasExpression = m_feedbackNode.hasBindingProperty("height");
    } else {
        m_beginX = QVariant();
        m_beginY = QVariant();
        m_beginWidth = QVariant();
        m_beginHeight = QVariant();
        m_parentNode = QmlObjectNode();
        m_beginLeftMargin = QVariant();
        m_beginRightMargin = QVariant();
        m_beginTopMargin = QVariant();
        m_beginBottomMargin = QVariant();
        m_beginXHasExpression = false;
        m_beginYHasExpression = false;
        m_beginWidthHasExpression = false;
        m_beginHeightHasExpression = false;
    }
}

void FormEditorGraphicsView::drawBackground(QPainter *painter, const QRectF &rect)
{
    painter->save();
    painter->setBrushOrigin(0, 0);
    painter->fillRect(rect.intersected(rootItemRect()), backgroundBrush());
    // paint rect around editable area
    painter->setPen(Qt::black);
    painter->drawRect( rootItemRect());
    painter->restore();
}

} // namespace QmlDesigner
<|endoftext|>


<commit_before>#include "pch.h"
#include "utils.h"
#include "ui/dial_button.h"
#include "ui/expanded_tab.h"
#include "utf8.h"

#if defined (WIN32)
#include <Rpc.h>
#elif defined (__ANDROID__) || defined (__EMSCRIPTEN__)
#include <uuidlib/uuid.h>
#else
#include <uuid/uuid.h>
#endif

std::string Utils::generateUUID( )
{
    std::string s;

#ifdef WIN32
    UUID uuid;
    UuidCreate ( &uuid );

    unsigned char * str;
    UuidToStringA ( &uuid, &str );

    s = ( const char* ) str;

    RpcStringFreeA ( &str );
#else
    uuid_t uuid;
    uuid_generate_random ( uuid );
    char str[37];
    uuid_unparse ( uuid, str );

    s = str;
#endif

    return s;
}

const wchar_t * Utils::UTF8ToWCS(const char * str)
{
    static std::wstring res;
    res.clear();
    utf8::unchecked::utf8to16(str, str + strlen(str), std::back_inserter(res));
    return res.c_str();
}

const char * Utils::WCSToUTF8(const wchar_t * str)
{
    static std::string res;
    res.clear();
    utf8::unchecked::utf16to8(str, str + wcslen(str), std::back_inserter(res));
    return res.c_str();
}

const wchar_t * Utils::ANSIToWCS(const char * str)
{
    static wchar_t result[2048];

    wchar_t * o = result;
    while( *str )
        *o++ = *str++;
    *o = 0;

    return result;
}

const char * Utils::format(const char * fmt, ...)
{
    static char results[16][2048];
    static int resInd = 0;

    char * result = results[resInd];
    resInd = (resInd + 1) & 15;

    va_list args;
    va_start(args, fmt);

#ifdef WIN32
    _vsnprintf(result, 2048, fmt, args);
#else
    vsnprintf(result, 2048, fmt, args);
#endif

    va_end(args);

    return result;
}

const char * Utils::urlEncode(const char * src)
{
    static std::string res[16];
    static int resInd = 0;

    std::string& result = res[resInd];
    resInd = (resInd + 1) & 15;

    result.clear();

    static char hexmap[16] = { '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'A', 'B', 'C', 'D', 'E', 'F' };

    int max = strlen(src);
    for (int i = 0; i < max; i++, src++)
    {
        if (('0' <= *src && *src <= '9') ||
            ('A' <= *src && *src <= 'Z') ||
            ('a' <= *src && *src <= 'z') ||
            (*src == '~' || *src == '-' || *src == '_' || *src == '.')
            )
        {
            result.push_back(*src);
        }
        else
        {
            result.push_back('%');
            result.push_back(hexmap[(unsigned char)(*src) >> 4]);
            result.push_back(hexmap[*src & 0x0F]);
        }
    }

    return result.c_str();
}

const wchar_t * Utils::clipTextToBounds(const wchar_t * text, float width, const gameplay::Font * font, float fontSize, float characterSpacing)
{
    static std::wstring result;

    if (width <= 0.0f)
        return L"";

    float textw = 0, texth = 0;
    font->measureText(text, fontSize, gameplay::Font::LEFT_TO_RIGHT, &textw, &texth, characterSpacing);

    if (textw < width)
        return text;

    result = text;

    result.erase(result.end() - 1, result.end());
    result.push_back('.');
    result.push_back('.');
    result.push_back('.');
    do
    {
        result.erase(result.end() - 4, result.end());
        result.push_back('.');
        result.push_back('.');
        result.push_back('.');
        font->measureText(result.c_str(), fontSize, gameplay::Font::LEFT_TO_RIGHT, &textw, &texth, characterSpacing);
    } while (result.size() > 3 && textw >= width);

    return result.c_str();
}

const wchar_t * Utils::clipTextToBounds(const wchar_t * text, float width, float height, const gameplay::Font * font, float fontSize,
    float characterSpacing, float lineSpacing)
{
    static std::wstring result;

    if (width <= 0.0f || height <= fontSize)
        return L"";

    gameplay::Rectangle clip(width, height);
    gameplay::Rectangle out;

    font->measureText(text, clip, fontSize, gameplay::Font::LEFT_TO_RIGHT, &out, gameplay::Font::ALIGN_TOP_LEFT, true, true, characterSpacing, lineSpacing);

    if (out.width < width && out.height < height)
        return text;

    result = text;

    result.erase(result.end() - 1, result.end());
    result.push_back('.');
    result.push_back('.');
    result.push_back('.');
    do
    {
        result.erase(result.end() - 4, result.end());
        result.push_back('.');
        result.push_back('.');
        result.push_back('.');
        font->measureText(result.c_str(), clip, fontSize, gameplay::Font::LEFT_TO_RIGHT, &out, gameplay::Font::ALIGN_TOP_LEFT, true, true, characterSpacing, lineSpacing);
    } while (result.size() > 3 && (out.width >= width || out.height >= height));

    return result.c_str();
}

void Utils::serializeString(gameplay::Stream * stream, const std::string& str)
{
    int32_t size = static_cast<int32_t>(str.size());
    stream->write(&size, sizeof(size), 1);
    stream->write(str.c_str(), sizeof(char), size);
}

void Utils::deserializeString(gameplay::Stream * stream, std::string * str)
{
    int32_t size = 0;
    if (stream->read(&size, sizeof(size), 1) != 1)
        return;

    if (size < 0 || size > 65535)
        return; // something wrong with data

    char * buf = reinterpret_cast<char *>(alloca(sizeof(char)* (size + 1)));
    if (buf)
    {
        stream->read(buf, sizeof(char), size);
        buf[size] = '\0';
        if (str)
        {
            str->clear();
            *str = buf;
        }
    }
}

void Utils::scaleUIControl(gameplay::Control * control, float kx, float ky)
{
    if (!control)
        return;

    // the actual scaling
    if (!control->isXPercentage())
        control->setX(control->getX() * kx);
    if (!control->isYPercentage())
        control->setY(control->getY() * ky);
    if (!control->isWidthPercentage() && (control->getAutoSize() & gameplay::Control::AUTO_SIZE_WIDTH) == 0)
        control->setWidth(control->getWidth() * kx);
    if (!control->isHeightPercentage() && (control->getAutoSize() & gameplay::Control::AUTO_SIZE_HEIGHT) == 0)
        control->setHeight(control->getHeight() * ky);

    const gameplay::Theme::Border& border = control->getBorder();
    const gameplay::Theme::Margin& margin = control->getMargin();
    const gameplay::Theme::Padding& padding = control->getPadding();
    control->setBorder(border.top * ky, border.bottom * ky, border.left * kx, border.right * kx);
    control->setMargin(margin.top * ky, margin.bottom * ky, margin.left * kx, margin.right * kx);
    control->setPadding(padding.top * ky, padding.bottom * ky, padding.left * kx, padding.right * kx);

    control->setFontSize(ky * control->getFontSize());
    control->setCharacterSpacing(ky * control->getCharacterSpacing());
    control->setLineSpacing(ky * control->getLineSpacing());

    if (strcmp(control->getTypeName(), "Slider") == 0)
        static_cast<gameplay::Slider *>(control)->setScaleFactor(ky);

    if (strcmp(control->getTypeName(), "ImageControl") == 0)
    {
        gameplay::ImageControl * image = static_cast< gameplay::ImageControl * >(control);
        const gameplay::Rectangle& dstRegion = image->getRegionDst();
        image->setRegionDst(dstRegion.x * kx, dstRegion.y * ky, dstRegion.width * kx, dstRegion.height * ky);
    }

    if (strcmp(control->getTypeName(), "DialButton") == 0)
    {
        DialButton * button = static_cast<DialButton *>(control);
        button->setHeightCollapsed(ky * button->getHeightCollapsed());
        button->setHeightExpanded(ky * button->getHeightExpanded());
    }

    if (strcmp(control->getTypeName(), "ExpandedTab") == 0)
    {
        ExpandedTab * tab = static_cast<ExpandedTab * >(control);
        tab->setWidthMinimized(kx * tab->getWidthMinimized());
        tab->setWidthMaximized(kx * tab->getWidthMaximized());
    }

    if (strcmp(control->getTypeName(), "RadioButton") == 0)
    {
        gameplay::RadioButton * button = static_cast<gameplay::RadioButton *>(control);
        button->setIconScale(button->getIconScale() * ky);
    }

    if (strcmp(control->getTypeName(), "CheckBox") == 0)
    {
        gameplay::CheckBox * button = static_cast<gameplay::CheckBox *>(control);
        button->setIconScale(button->getIconScale() * ky);
    }

    if (control->isContainer())
    {
        gameplay::Container * container = static_cast<gameplay::Container *>(control);
        container->setScrollScale(container->getScrollScale() * ky);

        const std::vector< gameplay::Control * >& children = container->getControls();
        for (unsigned j = 0; j < children.size(); j++)
            scaleUIControl(children[j], kx, ky);
    }
}

void Utils::measureChildrenBounds(gameplay::Container * container, float * width, float * height)
{
    // Calculate total width and height.
    float totalWidth = 0.0f, totalHeight = 0.0f;
    const std::vector<gameplay::Control*>& controls = container->getControls();
    for (size_t i = 0, count = controls.size(); i < count; ++i)
    {
        gameplay::Control* control = controls[i];

        if (!control->isVisible())
            continue;

        const gameplay::Rectangle& bounds = control->getBounds();
        const gameplay::Theme::Margin& margin = control->getMargin();

        float newWidth = bounds.x + bounds.width + margin.right;
        if (newWidth > totalWidth)
            totalWidth = newWidth;

        float newHeight = bounds.y + bounds.height + margin.bottom;
        if (newHeight > totalHeight)
            totalHeight = newHeight;
    }

    if (width)
        *width = totalWidth;
    if (height)
        *height = totalHeight;
}<commit_msg>make sure fonts always use integer sizes<commit_after>#include "pch.h"
#include "utils.h"
#include "ui/dial_button.h"
#include "ui/expanded_tab.h"
#include "utf8.h"

#if defined (WIN32)
#include <Rpc.h>
#elif defined (__ANDROID__) || defined (__EMSCRIPTEN__)
#include <uuidlib/uuid.h>
#else
#include <uuid/uuid.h>
#endif

std::string Utils::generateUUID( )
{
    std::string s;

#ifdef WIN32
    UUID uuid;
    UuidCreate ( &uuid );

    unsigned char * str;
    UuidToStringA ( &uuid, &str );

    s = ( const char* ) str;

    RpcStringFreeA ( &str );
#else
    uuid_t uuid;
    uuid_generate_random ( uuid );
    char str[37];
    uuid_unparse ( uuid, str );

    s = str;
#endif

    return s;
}

const wchar_t * Utils::UTF8ToWCS(const char * str)
{
    static std::wstring res;
    res.clear();
    utf8::unchecked::utf8to16(str, str + strlen(str), std::back_inserter(res));
    return res.c_str();
}

const char * Utils::WCSToUTF8(const wchar_t * str)
{
    static std::string res;
    res.clear();
    utf8::unchecked::utf16to8(str, str + wcslen(str), std::back_inserter(res));
    return res.c_str();
}

const wchar_t * Utils::ANSIToWCS(const char * str)
{
    static wchar_t result[2048];

    wchar_t * o = result;
    while( *str )
        *o++ = *str++;
    *o = 0;

    return result;
}

const char * Utils::format(const char * fmt, ...)
{
    static char results[16][2048];
    static int resInd = 0;

    char * result = results[resInd];
    resInd = (resInd + 1) & 15;

    va_list args;
    va_start(args, fmt);

#ifdef WIN32
    _vsnprintf(result, 2048, fmt, args);
#else
    vsnprintf(result, 2048, fmt, args);
#endif

    va_end(args);

    return result;
}

const char * Utils::urlEncode(const char * src)
{
    static std::string res[16];
    static int resInd = 0;

    std::string& result = res[resInd];
    resInd = (resInd + 1) & 15;

    result.clear();

    static char hexmap[16] = { '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'A', 'B', 'C', 'D', 'E', 'F' };

    int max = strlen(src);
    for (int i = 0; i < max; i++, src++)
    {
        if (('0' <= *src && *src <= '9') ||
            ('A' <= *src && *src <= 'Z') ||
            ('a' <= *src && *src <= 'z') ||
            (*src == '~' || *src == '-' || *src == '_' || *src == '.')
            )
        {
            result.push_back(*src);
        }
        else
        {
            result.push_back('%');
            result.push_back(hexmap[(unsigned char)(*src) >> 4]);
            result.push_back(hexmap[*src & 0x0F]);
        }
    }

    return result.c_str();
}

const wchar_t * Utils::clipTextToBounds(const wchar_t * text, float width, const gameplay::Font * font, float fontSize, float characterSpacing)
{
    static std::wstring result;

    if (width <= 0.0f)
        return L"";

    float textw = 0, texth = 0;
    font->measureText(text, fontSize, gameplay::Font::LEFT_TO_RIGHT, &textw, &texth, characterSpacing);

    if (textw < width)
        return text;

    result = text;

    result.erase(result.end() - 1, result.end());
    result.push_back('.');
    result.push_back('.');
    result.push_back('.');
    do
    {
        result.erase(result.end() - 4, result.end());
        result.push_back('.');
        result.push_back('.');
        result.push_back('.');
        font->measureText(result.c_str(), fontSize, gameplay::Font::LEFT_TO_RIGHT, &textw, &texth, characterSpacing);
    } while (result.size() > 3 && textw >= width);

    return result.c_str();
}

const wchar_t * Utils::clipTextToBounds(const wchar_t * text, float width, float height, const gameplay::Font * font, float fontSize,
    float characterSpacing, float lineSpacing)
{
    static std::wstring result;

    if (width <= 0.0f || height <= fontSize)
        return L"";

    gameplay::Rectangle clip(width, height);
    gameplay::Rectangle out;

    font->measureText(text, clip, fontSize, gameplay::Font::LEFT_TO_RIGHT, &out, gameplay::Font::ALIGN_TOP_LEFT, true, true, characterSpacing, lineSpacing);

    if (out.width < width && out.height < height)
        return text;

    result = text;

    result.erase(result.end() - 1, result.end());
    result.push_back('.');
    result.push_back('.');
    result.push_back('.');
    do
    {
        result.erase(result.end() - 4, result.end());
        result.push_back('.');
        result.push_back('.');
        result.push_back('.');
        font->measureText(result.c_str(), clip, fontSize, gameplay::Font::LEFT_TO_RIGHT, &out, gameplay::Font::ALIGN_TOP_LEFT, true, true, characterSpacing, lineSpacing);
    } while (result.size() > 3 && (out.width >= width || out.height >= height));

    return result.c_str();
}

void Utils::serializeString(gameplay::Stream * stream, const std::string& str)
{
    int32_t size = static_cast<int32_t>(str.size());
    stream->write(&size, sizeof(size), 1);
    stream->write(str.c_str(), sizeof(char), size);
}

void Utils::deserializeString(gameplay::Stream * stream, std::string * str)
{
    int32_t size = 0;
    if (stream->read(&size, sizeof(size), 1) != 1)
        return;

    if (size < 0 || size > 65535)
        return; // something wrong with data

    char * buf = reinterpret_cast<char *>(alloca(sizeof(char)* (size + 1)));
    if (buf)
    {
        stream->read(buf, sizeof(char), size);
        buf[size] = '\0';
        if (str)
        {
            str->clear();
            *str = buf;
        }
    }
}

void Utils::scaleUIControl(gameplay::Control * control, float kx, float ky)
{
    if (!control)
        return;

    // the actual scaling
    if (!control->isXPercentage())
        control->setX(control->getX() * kx);
    if (!control->isYPercentage())
        control->setY(control->getY() * ky);
    if (!control->isWidthPercentage() && (control->getAutoSize() & gameplay::Control::AUTO_SIZE_WIDTH) == 0)
        control->setWidth(control->getWidth() * kx);
    if (!control->isHeightPercentage() && (control->getAutoSize() & gameplay::Control::AUTO_SIZE_HEIGHT) == 0)
        control->setHeight(control->getHeight() * ky);

    const gameplay::Theme::Border& border = control->getBorder();
    const gameplay::Theme::Margin& margin = control->getMargin();
    const gameplay::Theme::Padding& padding = control->getPadding();
    control->setBorder(border.top * ky, border.bottom * ky, border.left * kx, border.right * kx);
    control->setMargin(margin.top * ky, margin.bottom * ky, margin.left * kx, margin.right * kx);
    control->setPadding(padding.top * ky, padding.bottom * ky, padding.left * kx, padding.right * kx);

    control->setFontSize(roundf(ky * control->getFontSize()));
    control->setCharacterSpacing(roundf(ky * control->getCharacterSpacing()));
    control->setLineSpacing(roundf(ky * control->getLineSpacing()));

    if (strcmp(control->getTypeName(), "Slider") == 0)
        static_cast<gameplay::Slider *>(control)->setScaleFactor(ky);

    if (strcmp(control->getTypeName(), "ImageControl") == 0)
    {
        gameplay::ImageControl * image = static_cast< gameplay::ImageControl * >(control);
        const gameplay::Rectangle& dstRegion = image->getRegionDst();
        image->setRegionDst(dstRegion.x * kx, dstRegion.y * ky, dstRegion.width * kx, dstRegion.height * ky);
    }

    if (strcmp(control->getTypeName(), "DialButton") == 0)
    {
        DialButton * button = static_cast<DialButton *>(control);
        button->setHeightCollapsed(ky * button->getHeightCollapsed());
        button->setHeightExpanded(ky * button->getHeightExpanded());
    }

    if (strcmp(control->getTypeName(), "ExpandedTab") == 0)
    {
        ExpandedTab * tab = static_cast<ExpandedTab * >(control);
        tab->setWidthMinimized(kx * tab->getWidthMinimized());
        tab->setWidthMaximized(kx * tab->getWidthMaximized());
    }

    if (strcmp(control->getTypeName(), "RadioButton") == 0)
    {
        gameplay::RadioButton * button = static_cast<gameplay::RadioButton *>(control);
        button->setIconScale(button->getIconScale() * ky);
    }

    if (strcmp(control->getTypeName(), "CheckBox") == 0)
    {
        gameplay::CheckBox * button = static_cast<gameplay::CheckBox *>(control);
        button->setIconScale(button->getIconScale() * ky);
    }

    if (control->isContainer())
    {
        gameplay::Container * container = static_cast<gameplay::Container *>(control);
        container->setScrollScale(container->getScrollScale() * ky);

        const std::vector< gameplay::Control * >& children = container->getControls();
        for (unsigned j = 0; j < children.size(); j++)
            scaleUIControl(children[j], kx, ky);
    }
}

void Utils::measureChildrenBounds(gameplay::Container * container, float * width, float * height)
{
    // Calculate total width and height.
    float totalWidth = 0.0f, totalHeight = 0.0f;
    const std::vector<gameplay::Control*>& controls = container->getControls();
    for (size_t i = 0, count = controls.size(); i < count; ++i)
    {
        gameplay::Control* control = controls[i];

        if (!control->isVisible())
            continue;

        const gameplay::Rectangle& bounds = control->getBounds();
        const gameplay::Theme::Margin& margin = control->getMargin();

        float newWidth = bounds.x + bounds.width + margin.right;
        if (newWidth > totalWidth)
            totalWidth = newWidth;

        float newHeight = bounds.y + bounds.height + margin.bottom;
        if (newHeight > totalHeight)
            totalHeight = newHeight;
    }

    if (width)
        *width = totalWidth;
    if (height)
        *height = totalHeight;
}<|endoftext|>


<commit_before>/* Copyright (c) 2016 PaddlePaddle Authors. All Rights Reserve.

Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at

    http://www.apache.org/licenses/LICENSE-2.0

Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License. */

#include "SwitchOrderLayer.h"
#include "paddle/utils/Stat.h"

namespace paddle {

REGISTER_LAYER(switch_order, SwitchOrderLayer);

bool SwitchOrderLayer::init(const LayerMap& layerMap,
                            const ParameterMap& parameterMap) {
  /* Initialize the basic parent class */
  Layer::init(layerMap, parameterMap);
  auto& img_conf = config_.inputs(0).image_conf();
  size_t inH =
      img_conf.has_img_size_y() ? img_conf.img_size_y() : img_conf.img_size();
  size_t inW = img_conf.img_size();
  size_t inC = img_conf.channels();
  inDims_ = TensorShape({0, inC, inH, inW});
  outDims_ = TensorShape(4);

  auto& reshape_conf = config_.reshape_conf();
  for (size_t i = 0; i < reshape_conf.heightaxis_size(); i++) {
    heightAxis_.push_back(reshape_conf.heightaxis(i));
  }
  for (size_t i = 0; i < reshape_conf.widthaxis_size(); i++) {
    widthAxis_.push_back(reshape_conf.widthaxis(i));
  }
  createFunction(nchw2nhwc_, "NCHW2NHWC", FuncConfig());
  createFunction(nhwc2nchw_, "NHWC2NCHW", FuncConfig());
  return true;
}

void SwitchOrderLayer::setOutDims() {
  outDims_.setDim(0, inDims_[0]);
  outDims_.setDim(1, inDims_[2]);
  outDims_.setDim(2, inDims_[3]);
  outDims_.setDim(3, inDims_[1]);
  reshapeHeight_ = 1;
  for (size_t i = 0; i < heightAxis_.size(); i++) {
    reshapeHeight_ *= outDims_[heightAxis_[i]];
  }
  output_.setFrameHeight(reshapeHeight_);
  reshapeWidth_ = 1;
  for (size_t i = 0; i < widthAxis_.size(); i++) {
    reshapeWidth_ *= outDims_[widthAxis_[i]];
  }
  output_.setFrameWidth(reshapeWidth_);
}

void SwitchOrderLayer::setInDims() {
  MatrixPtr input = inputLayers_[0]->getOutputValue();
  size_t batchSize = input->getHeight();
  inDims_.setDim(0, batchSize);

  int h = inputLayers_[0]->getOutput().getFrameHeight();
  if (h != 0) inDims_.setDim(2, h);
  int w = inputLayers_[0]->getOutput().getFrameWidth();
  if (w != 0) inDims_.setDim(3, w);
  int totalCount = input->getElementCnt();
  int channels = totalCount / (inDims_[0] * inDims_[2] * inDims_[3]);
  if (channels != 0) inDims_.setDim(1, channels);
}

void SwitchOrderLayer::forward(PassType passType) {
  Layer::forward(passType);
  setInDims();
  setOutDims();
  resetOutput(outDims_[0], outDims_[1] * outDims_[2] * outDims_[3]);
  if (heightAxis_.size() > 0) {
    getOutputValue()->reshape(reshapeHeight_, reshapeWidth_);
  }

  // switch NCHW to NHWC
  BufferArgs inputs;
  BufferArgs outputs;
  inputs.addArg(*getInputValue(0), inDims_);
  outputs.addArg(*getOutputValue(), outDims_);
  nchw2nhwc_[0]->calc(inputs, outputs);
  forwardActivation();
}

void SwitchOrderLayer::backward(const UpdateCallback& callback) {
  (void)callback;
  backwardActivation();

  // switch NHWC to NCHW
  BufferArgs inputs;
  BufferArgs outputs;
  inputs.addArg(*getOutputGrad(), outDims_);
  outputs.addArg(*getInputGrad(0), inDims_, ADD_TO);
  nhwc2nchw_[0]->calc(inputs, outputs);
}
}  // namespace paddle
<commit_msg>Fix SwitchOrderLayer grad bugs by reshape output.grad<commit_after>/* Copyright (c) 2016 PaddlePaddle Authors. All Rights Reserve.

Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at

    http://www.apache.org/licenses/LICENSE-2.0

Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License. */

#include "SwitchOrderLayer.h"
#include "paddle/utils/Stat.h"

namespace paddle {

REGISTER_LAYER(switch_order, SwitchOrderLayer);

bool SwitchOrderLayer::init(const LayerMap& layerMap,
                            const ParameterMap& parameterMap) {
  /* Initialize the basic parent class */
  Layer::init(layerMap, parameterMap);
  auto& img_conf = config_.inputs(0).image_conf();
  size_t inH =
      img_conf.has_img_size_y() ? img_conf.img_size_y() : img_conf.img_size();
  size_t inW = img_conf.img_size();
  size_t inC = img_conf.channels();
  inDims_ = TensorShape({0, inC, inH, inW});
  outDims_ = TensorShape(4);

  auto& reshape_conf = config_.reshape_conf();
  for (size_t i = 0; i < reshape_conf.heightaxis_size(); i++) {
    heightAxis_.push_back(reshape_conf.heightaxis(i));
  }
  for (size_t i = 0; i < reshape_conf.widthaxis_size(); i++) {
    widthAxis_.push_back(reshape_conf.widthaxis(i));
  }
  createFunction(nchw2nhwc_, "NCHW2NHWC", FuncConfig());
  createFunction(nhwc2nchw_, "NHWC2NCHW", FuncConfig());
  return true;
}

void SwitchOrderLayer::setOutDims() {
  outDims_.setDim(0, inDims_[0]);
  outDims_.setDim(1, inDims_[2]);
  outDims_.setDim(2, inDims_[3]);
  outDims_.setDim(3, inDims_[1]);
  reshapeHeight_ = 1;
  for (size_t i = 0; i < heightAxis_.size(); i++) {
    reshapeHeight_ *= outDims_[heightAxis_[i]];
  }
  output_.setFrameHeight(reshapeHeight_);
  reshapeWidth_ = 1;
  for (size_t i = 0; i < widthAxis_.size(); i++) {
    reshapeWidth_ *= outDims_[widthAxis_[i]];
  }
  output_.setFrameWidth(reshapeWidth_);
}

void SwitchOrderLayer::setInDims() {
  MatrixPtr input = inputLayers_[0]->getOutputValue();
  size_t batchSize = input->getHeight();
  inDims_.setDim(0, batchSize);

  int h = inputLayers_[0]->getOutput().getFrameHeight();
  if (h != 0) inDims_.setDim(2, h);
  int w = inputLayers_[0]->getOutput().getFrameWidth();
  if (w != 0) inDims_.setDim(3, w);
  int totalCount = input->getElementCnt();
  int channels = totalCount / (inDims_[0] * inDims_[2] * inDims_[3]);
  if (channels != 0) inDims_.setDim(1, channels);
}

void SwitchOrderLayer::forward(PassType passType) {
  Layer::forward(passType);
  setInDims();
  setOutDims();
  resetOutput(outDims_[0], outDims_[1] * outDims_[2] * outDims_[3]);
  if (heightAxis_.size() > 0) {
    getOutputValue()->reshape(reshapeHeight_, reshapeWidth_);
    getOutputGrad()->reshape(reshapeHeight_, reshapeWidth_);
  }

  // switch NCHW to NHWC
  BufferArgs inputs;
  BufferArgs outputs;
  inputs.addArg(*getInputValue(0), inDims_);
  outputs.addArg(*getOutputValue(), outDims_);
  nchw2nhwc_[0]->calc(inputs, outputs);
  forwardActivation();
}

void SwitchOrderLayer::backward(const UpdateCallback& callback) {
  (void)callback;
  backwardActivation();

  // switch NHWC to NCHW
  BufferArgs inputs;
  BufferArgs outputs;
  inputs.addArg(*getOutputGrad(), outDims_);
  outputs.addArg(*getInputGrad(0), inDims_, ADD_TO);
  nhwc2nchw_[0]->calc(inputs, outputs);
}
}  // namespace paddle
<|endoftext|>