<commit_before>/*************************************************************************
 *
 *  $RCSfile: xml_helper.hxx,v $
 *
 *  $Revision: 1.9 $
 *
 *  last change: $Author: hr $ $Date: 2004-11-09 12:33:23 $
 *
 *  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 _XMLSCRIPT_XML_HELPER_HXX_
#define _XMLSCRIPT_XML_HELPER_HXX_

#include <vector>

#ifndef _RTL_BYTESEQ_HXX_
#include <rtl/byteseq.hxx>
#endif

#ifndef _CPPUHELPER_IMPLBASE1_HXX_
#include <cppuhelper/implbase1.hxx>
#endif

#ifndef _COM_SUN_STAR_XML_SAX_XDOCUMENTHANDLER_HPP_
#include <com/sun/star/xml/sax/XDocumentHandler.hpp>
#endif
#ifndef _COM_SUN_STAR_IO_XINPUTSTREAM_HPP_
#include <com/sun/star/io/XInputStream.hpp>
#endif
#ifndef _COM_SUN_STAR_IO_XOUTPUTSTREAM_HPP_
#include <com/sun/star/io/XOutputStream.hpp>
#endif

namespace xmlscript
{

/*##################################################################################################

    EXPORTING

##################################################################################################*/

//==================================================================================================
class XMLElement
    : public ::cppu::WeakImplHelper1< ::com::sun::star::xml::sax::XAttributeList >
{
public:
    inline XMLElement( ::rtl::OUString const & name )
        SAL_THROW( () )
        : _name( name )
        {}

    /** Adds a sub element of element.

        @param xElem element reference
    */
    void SAL_CALL addSubElement(
        ::com::sun::star::uno::Reference< ::com::sun::star::xml::sax::XAttributeList > const & xElem )
        SAL_THROW( () );

    /** Gets sub element of given index.  The index follows order in which sub elements were added.

        @param nIndex index of sub element
    */
    ::com::sun::star::uno::Reference< ::com::sun::star::xml::sax::XAttributeList > SAL_CALL getSubElement( sal_Int32 nIndex )
        SAL_THROW( () );

    /** Adds an attribute to elements.

        @param rAttrName qname of attribute
        @param rValue value string of element
    */
    void SAL_CALL addAttribute( ::rtl::OUString const & rAttrName, ::rtl::OUString const & rValue )
        SAL_THROW( () );

    /** Gets the tag name (qname) of element.

        @return
                qname of element
    */
    inline ::rtl::OUString SAL_CALL getName() SAL_THROW( () )
        { return _name; }

    /** Dumps out element (and all sub elements).

        @param xOut document handler to be written to
    */
    void SAL_CALL dump(
        ::com::sun::star::uno::Reference< ::com::sun::star::xml::sax::XDocumentHandler > const & xOut );
    /** Dumps out sub elements (and all further sub elements).

        @param xOut document handler to be written to
    */
    void SAL_CALL dumpSubElements(
        ::com::sun::star::uno::Reference< ::com::sun::star::xml::sax::XDocumentHandler > const & xOut );

    // XAttributeList
    virtual sal_Int16 SAL_CALL getLength()
        throw (::com::sun::star::uno::RuntimeException);
    virtual ::rtl::OUString SAL_CALL getNameByIndex( sal_Int16 nPos )
        throw (::com::sun::star::uno::RuntimeException);
    virtual ::rtl::OUString SAL_CALL getTypeByIndex( sal_Int16 nPos )
        throw (::com::sun::star::uno::RuntimeException);
    virtual ::rtl::OUString SAL_CALL getTypeByName( ::rtl::OUString const & rName )
        throw (::com::sun::star::uno::RuntimeException);
    virtual ::rtl::OUString SAL_CALL getValueByIndex( sal_Int16 nPos )
        throw (::com::sun::star::uno::RuntimeException);
    virtual ::rtl::OUString SAL_CALL getValueByName( ::rtl::OUString const & rName )
        throw (::com::sun::star::uno::RuntimeException);

protected:
    ::rtl::OUString _name;

    ::std::vector< ::rtl::OUString > _attrNames;
    ::std::vector< ::rtl::OUString > _attrValues;

    ::std::vector< ::com::sun::star::uno::Reference<
                   ::com::sun::star::xml::sax::XAttributeList > > _subElems;
};

/*##################################################################################################

    STREAMING

##################################################################################################*/

//==================================================================================================
::com::sun::star::uno::Reference< ::com::sun::star::io::XInputStream >
SAL_CALL createInputStream(
    ::rtl::ByteSequence const & rInData )
    SAL_THROW( () );

//==================================================================================================
::com::sun::star::uno::Reference< ::com::sun::star::io::XOutputStream >
SAL_CALL createOutputStream(
    ::rtl::ByteSequence * pOutData )
    SAL_THROW( () );

};

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

#include <vector>

#ifndef _RTL_BYTESEQ_HXX_
#include <rtl/byteseq.hxx>
#endif

#ifndef _CPPUHELPER_IMPLBASE1_HXX_
#include <cppuhelper/implbase1.hxx>
#endif

#ifndef _COM_SUN_STAR_XML_SAX_XDOCUMENTHANDLER_HPP_
#include <com/sun/star/xml/sax/XDocumentHandler.hpp>
#endif
#ifndef _COM_SUN_STAR_IO_XINPUTSTREAM_HPP_
#include <com/sun/star/io/XInputStream.hpp>
#endif
#ifndef _COM_SUN_STAR_IO_XOUTPUTSTREAM_HPP_
#include <com/sun/star/io/XOutputStream.hpp>
#endif

namespace xmlscript
{

/*##################################################################################################

    EXPORTING

##################################################################################################*/

//==================================================================================================
class XMLElement
    : public ::cppu::WeakImplHelper1< ::com::sun::star::xml::sax::XAttributeList >
{
public:
    inline XMLElement( ::rtl::OUString const & name )
        SAL_THROW( () )
        : _name( name )
        {}

    /** Adds a sub element of element.

        @param xElem element reference
    */
    void SAL_CALL addSubElement(
        ::com::sun::star::uno::Reference< ::com::sun::star::xml::sax::XAttributeList > const & xElem )
        SAL_THROW( () );

    /** Gets sub element of given index.  The index follows order in which sub elements were added.

        @param nIndex index of sub element
    */
    ::com::sun::star::uno::Reference< ::com::sun::star::xml::sax::XAttributeList > SAL_CALL getSubElement( sal_Int32 nIndex )
        SAL_THROW( () );

    /** Adds an attribute to elements.

        @param rAttrName qname of attribute
        @param rValue value string of element
    */
    void SAL_CALL addAttribute( ::rtl::OUString const & rAttrName, ::rtl::OUString const & rValue )
        SAL_THROW( () );

    /** Gets the tag name (qname) of element.

        @return
                qname of element
    */
    inline ::rtl::OUString SAL_CALL getName() SAL_THROW( () )
        { return _name; }

    /** Dumps out element (and all sub elements).

        @param xOut document handler to be written to
    */
    void SAL_CALL dump(
        ::com::sun::star::uno::Reference< ::com::sun::star::xml::sax::XDocumentHandler > const & xOut );
    /** Dumps out sub elements (and all further sub elements).

        @param xOut document handler to be written to
    */
    void SAL_CALL dumpSubElements(
        ::com::sun::star::uno::Reference< ::com::sun::star::xml::sax::XDocumentHandler > const & xOut );

    // XAttributeList
    virtual sal_Int16 SAL_CALL getLength()
        throw (::com::sun::star::uno::RuntimeException);
    virtual ::rtl::OUString SAL_CALL getNameByIndex( sal_Int16 nPos )
        throw (::com::sun::star::uno::RuntimeException);
    virtual ::rtl::OUString SAL_CALL getTypeByIndex( sal_Int16 nPos )
        throw (::com::sun::star::uno::RuntimeException);
    virtual ::rtl::OUString SAL_CALL getTypeByName( ::rtl::OUString const & rName )
        throw (::com::sun::star::uno::RuntimeException);
    virtual ::rtl::OUString SAL_CALL getValueByIndex( sal_Int16 nPos )
        throw (::com::sun::star::uno::RuntimeException);
    virtual ::rtl::OUString SAL_CALL getValueByName( ::rtl::OUString const & rName )
        throw (::com::sun::star::uno::RuntimeException);

protected:
    ::rtl::OUString _name;

    ::std::vector< ::rtl::OUString > _attrNames;
    ::std::vector< ::rtl::OUString > _attrValues;

    ::std::vector< ::com::sun::star::uno::Reference<
                   ::com::sun::star::xml::sax::XAttributeList > > _subElems;
};

/*##################################################################################################

    STREAMING

##################################################################################################*/

//==================================================================================================
::com::sun::star::uno::Reference< ::com::sun::star::io::XInputStream >
SAL_CALL createInputStream(
    ::rtl::ByteSequence const & rInData )
    SAL_THROW( () );

//==================================================================================================
::com::sun::star::uno::Reference< ::com::sun::star::io::XOutputStream >
SAL_CALL createOutputStream(
    ::rtl::ByteSequence * pOutData )
    SAL_THROW( () );

};

#endif
<|endoftext|>


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

 This file is part of the GLC-lib library.
 Copyright (C) 2005-2008 Laurent Ribon (laumaya@users.sourceforge.net)
 http://glc-lib.sourceforge.net

 GLC-lib 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 3 of the License, or
 (at your option) any later version.

 GLC-lib 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 GLC-lib; if not, write to the Free Software
 Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301  USA

*****************************************************************************/

//! \file glc_light.cpp implementation of the GLC_Light class.

#include <QGLContext>
#include <QtDebug>

#include "glc_light.h"
#include "../glc_openglexception.h"

GLint GLC_Light::m_MaxLight= 8;
QHash<const QGLContext*, QSet<GLenum> > GLC_Light::m_ContextToFreeLightSet;

//////////////////////////////////////////////////////////////////////
// Constructor Destructor
//////////////////////////////////////////////////////////////////////
GLC_Light::GLC_Light(const QGLContext* pContext, const QColor& color)
:GLC_Object("Light")
, m_LightID(-1)
, m_LightType(LightPosition)
, m_AmbientColor(Qt::black)
, m_DiffuseColor(color)
, m_SpecularColor(Qt::white)
, m_Position()
, m_SpotDirection(0.0, 0.0, -1.0)
, m_SpotExponent(0.0f)
, m_SpotCutoffAngle(180.0f)
, m_ConstantAttenuation(1.0f)
, m_LinearAttenuation(0.0f)
, m_QuadraticAttenuation(0.0f)
, m_TwoSided(false)
, m_pContext(const_cast<QGLContext*>(pContext))
, m_IsValid(false)
{
	addNewLight();
}

GLC_Light::GLC_Light(LightType lightType, const QGLContext* pContext, const QColor& color)
:GLC_Object("Light")
, m_LightID(-1)
, m_LightType(lightType)
, m_AmbientColor(Qt::black)
, m_DiffuseColor(color)
, m_SpecularColor(Qt::white)
, m_Position()
, m_SpotDirection(0.0, 0.0, -1.0)
, m_SpotExponent(0.0f)
, m_SpotCutoffAngle(180.0f)
, m_ConstantAttenuation(1.0f)
, m_LinearAttenuation(0.0f)
, m_QuadraticAttenuation(0.0f)
, m_TwoSided(false)
, m_pContext(const_cast<QGLContext*>(pContext))
, m_IsValid(false)
{
	addNewLight();
}

GLC_Light::GLC_Light(const GLC_Light& light)
:GLC_Object(light)
, m_LightID(-1)
, m_LightType(light.m_LightType)
, m_AmbientColor(light.m_AmbientColor)
, m_DiffuseColor(light.m_DiffuseColor)
, m_SpecularColor(light.m_SpecularColor)
, m_Position(light.m_Position)
, m_SpotDirection(light.m_SpotDirection)
, m_SpotExponent(light.m_SpotExponent)
, m_SpotCutoffAngle(light.m_SpotCutoffAngle)
, m_ConstantAttenuation(light.m_ConstantAttenuation)
, m_LinearAttenuation(light.m_LinearAttenuation)
, m_QuadraticAttenuation(light.m_QuadraticAttenuation)
, m_TwoSided(light.m_TwoSided)
, m_pContext(light.m_pContext)
, m_IsValid(false)
{
	addNewLight();
}

GLC_Light::~GLC_Light(void)
{
	removeThisLight();
}

/////////////////////////////////////////////////////////////////////
// Get Functions
//////////////////////////////////////////////////////////////////////

int GLC_Light::maxLightCount()
{
	return m_MaxLight;
}

int GLC_Light::builtAbleLightCount(QGLContext* pContext)
{
	if (m_ContextToFreeLightSet.contains(pContext))
	{
		return m_ContextToFreeLightSet.value(pContext).size();
	}
	else return m_MaxLight;
}

/////////////////////////////////////////////////////////////////////
// Set Functions
//////////////////////////////////////////////////////////////////////
void GLC_Light::initForThisContext()
{
	for (int i= 0; i < m_MaxLight; ++i)
	{
		m_ContextToFreeLightSet[m_pContext].insert(GL_LIGHT0 + i);
	}
}

void GLC_Light::setPosition(const GLC_Point3d &pos)
{
	m_Position= pos;
}

void GLC_Light::setPosition(GLfloat x, GLfloat y, GLfloat z)
{
	m_Position.setVect(static_cast<double>(x), static_cast<double>(y), static_cast<double>(z));
}

void GLC_Light::setAmbientColor(const QColor& color)
{
	m_AmbientColor= color;
	m_IsValid= false;
}

void GLC_Light::setDiffuseColor(const QColor& color)
{
	m_DiffuseColor= color;
	m_IsValid= false;
}

void GLC_Light::setSpecularColor(const QColor& color)
{
	m_SpecularColor= color;
	m_IsValid= false;
}

void GLC_Light::setTwoSided(const bool mode)
{
	m_TwoSided= mode;
	m_IsValid= false;
}

void GLC_Light::setConstantAttenuation(GLfloat constantAttenuation)
{
	m_ConstantAttenuation= constantAttenuation;
	m_IsValid= false;
}

void GLC_Light::setLinearAttenuation(GLfloat linearAttenuation)
{
	m_LinearAttenuation= linearAttenuation;
	m_IsValid= false;
}

void GLC_Light::setQuadraticAttenuation(GLfloat quadraticAttenuation)
{
	m_QuadraticAttenuation= quadraticAttenuation;
	m_IsValid= false;
}

void GLC_Light::setSpotDirection(const GLC_Vector3d& direction)
{
	m_SpotDirection= direction;
	m_IsValid= false;
}

void GLC_Light::setSpotCutoffAngle(GLfloat cutoffAngle)
{
	m_SpotCutoffAngle= cutoffAngle;
	m_IsValid= false;
}

void GLC_Light::setSpotEponent(GLfloat exponent)
{
	m_SpotExponent= exponent;
	m_IsValid= false;
}

//////////////////////////////////////////////////////////////////////
// OpenGL Functions
//////////////////////////////////////////////////////////////////////

void GLC_Light::disable()
{
	if (NULL != m_pContext)
	{
		glDisable(m_LightID);
	}
}

void GLC_Light::glExecute()
{
	if (NULL == m_pContext)
	{
		m_pContext= const_cast<QGLContext*>(QGLContext::currentContext());
		Q_ASSERT(NULL != m_pContext);
		addNewLight();
	}

	if (!glIsEnabled(GL_LIGHTING))
	{
		glEnable(GL_LIGHTING);
	}
	if (!glIsEnabled(m_LightID))
	{
		glEnable(m_LightID);
	}
	if (m_pContext != QGLContext::currentContext())
	{
		Q_ASSERT(QGLContext::areSharing(m_pContext, QGLContext::currentContext()));
		m_IsValid= false;
	}
	Q_ASSERT(m_pContext->isValid());

	GLfloat setArray[4];

	// Position
	setArray[0]= static_cast<GLfloat>(m_Position.x());
	setArray[1]= static_cast<GLfloat>(m_Position.y());
	setArray[2]= static_cast<GLfloat>(m_Position.z());

	if (LightDirection == m_LightType)
	{
		setArray[3]= 0.0f;
		glLightfv(m_LightID, GL_POSITION, setArray);	// Direction of the Light
	}
	else
	{
		setArray[3]= 1.0f;
		glLightfv(m_LightID, GL_POSITION, setArray);	// Position of the Light
	}

	if (!m_IsValid)
	{
		// Set the lighting model
		if (m_TwoSided)
		{
			glLightModeli(GL_LIGHT_MODEL_TWO_SIDE, 1);
		}
		else
		{
			glLightModeli(GL_LIGHT_MODEL_TWO_SIDE, 0);
		}

		// Color
		setArray[0]= static_cast<GLfloat>(m_AmbientColor.redF());
		setArray[1]= static_cast<GLfloat>(m_AmbientColor.greenF());
		setArray[2]= static_cast<GLfloat>(m_AmbientColor.blueF());
		setArray[3]= static_cast<GLfloat>(m_AmbientColor.alphaF());
		glLightfv(m_LightID, GL_AMBIENT, setArray);		// Setup The Ambient Light

		setArray[0]= static_cast<GLfloat>(m_DiffuseColor.redF());
		setArray[1]= static_cast<GLfloat>(m_DiffuseColor.greenF());
		setArray[2]= static_cast<GLfloat>(m_DiffuseColor.blueF());
		setArray[3]= static_cast<GLfloat>(m_DiffuseColor.alphaF());
		glLightfv(m_LightID, GL_DIFFUSE, setArray);		// Setup The Diffuse Light

		setArray[0]= static_cast<GLfloat>(m_SpecularColor.redF());
		setArray[1]= static_cast<GLfloat>(m_SpecularColor.greenF());
		setArray[2]= static_cast<GLfloat>(m_SpecularColor.blueF());
		setArray[3]= static_cast<GLfloat>(m_SpecularColor.alphaF());
		glLightfv(m_LightID, GL_SPECULAR, setArray);	// Setup The specular Light

		if (LightDirection != m_LightType)
			glLightf(m_LightID, GL_CONSTANT_ATTENUATION, m_ConstantAttenuation);
			glLightf(m_LightID, GL_LINEAR_ATTENUATION, m_LinearAttenuation);
			glLightf(m_LightID, GL_QUADRATIC_ATTENUATION, m_QuadraticAttenuation);

		// Spot light parameters
		if (LightSpot == m_LightType)
		{
			// Spot Direction
			setArray[0]= static_cast<GLfloat>(m_SpotDirection.x());
			setArray[1]= static_cast<GLfloat>(m_SpotDirection.y());
			setArray[2]= static_cast<GLfloat>(m_SpotDirection.z());
			glLightfv(m_LightID, GL_SPOT_DIRECTION, setArray);
			glLightf(m_LightID, GL_SPOT_EXPONENT, m_SpotExponent);
			glLightf(m_LightID, GL_SPOT_CUTOFF, m_SpotCutoffAngle);
		}

		m_IsValid= true;
	}

	// OpenGL error handler
	GLenum error= glGetError();
	if (error != GL_NO_ERROR)
	{
		qDebug() << "GLC_Light::glExecute Exception, id= " << m_LightID;
		GLC_OpenGlException OpenGlException("GLC_Light::glExecute ", error);
		throw(OpenGlException);
	}

}

//////////////////////////////////////////////////////////////////////
// Private services Functions
//////////////////////////////////////////////////////////////////////

//////////////////////////////////////////////////////////////////////
// Private services fonction
//////////////////////////////////////////////////////////////////////
void GLC_Light::addNewLight()
{
	if (NULL != m_pContext)
	{
		if (!m_ContextToFreeLightSet.contains(m_pContext))
		{
			m_ContextToFreeLightSet.insert(m_pContext, QSet<GLenum>());
			initForThisContext();
		}

		// Some OpenGL driver support only Light0 ???
		if (m_ContextToFreeLightSet.value(m_pContext).size() == m_MaxLight)
		{
			m_LightID= GL_LIGHT0;
		}
		else
		{
			m_LightID= *(m_ContextToFreeLightSet[m_pContext].constBegin());
		}

		m_ContextToFreeLightSet[m_pContext].remove(m_LightID);
	}
}

void GLC_Light::removeThisLight()
{
	if (NULL != m_pContext)
	{
		Q_ASSERT(m_ContextToFreeLightSet.contains(m_pContext));
		Q_ASSERT(!m_ContextToFreeLightSet[m_pContext].contains(m_LightID));
		m_ContextToFreeLightSet[m_pContext].insert(m_LightID);
		if (m_ContextToFreeLightSet[m_pContext].size() == m_MaxLight)
		{
			m_ContextToFreeLightSet.remove(m_pContext);
		}
	}
}
<commit_msg>Don't use glGet* methods... Time consuming !!!!<commit_after>/****************************************************************************

 This file is part of the GLC-lib library.
 Copyright (C) 2005-2008 Laurent Ribon (laumaya@users.sourceforge.net)
 http://glc-lib.sourceforge.net

 GLC-lib 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 3 of the License, or
 (at your option) any later version.

 GLC-lib 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 GLC-lib; if not, write to the Free Software
 Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301  USA

*****************************************************************************/

//! \file glc_light.cpp implementation of the GLC_Light class.

#include <QGLContext>
#include <QtDebug>

#include "glc_light.h"
#include "../glc_openglexception.h"

GLint GLC_Light::m_MaxLight= 8;
QHash<const QGLContext*, QSet<GLenum> > GLC_Light::m_ContextToFreeLightSet;

//////////////////////////////////////////////////////////////////////
// Constructor Destructor
//////////////////////////////////////////////////////////////////////
GLC_Light::GLC_Light(const QGLContext* pContext, const QColor& color)
:GLC_Object("Light")
, m_LightID(-1)
, m_LightType(LightPosition)
, m_AmbientColor(Qt::black)
, m_DiffuseColor(color)
, m_SpecularColor(Qt::white)
, m_Position()
, m_SpotDirection(0.0, 0.0, -1.0)
, m_SpotExponent(0.0f)
, m_SpotCutoffAngle(180.0f)
, m_ConstantAttenuation(1.0f)
, m_LinearAttenuation(0.0f)
, m_QuadraticAttenuation(0.0f)
, m_TwoSided(false)
, m_pContext(const_cast<QGLContext*>(pContext))
, m_IsValid(false)
{
	addNewLight();
}

GLC_Light::GLC_Light(LightType lightType, const QGLContext* pContext, const QColor& color)
:GLC_Object("Light")
, m_LightID(-1)
, m_LightType(lightType)
, m_AmbientColor(Qt::black)
, m_DiffuseColor(color)
, m_SpecularColor(Qt::white)
, m_Position()
, m_SpotDirection(0.0, 0.0, -1.0)
, m_SpotExponent(0.0f)
, m_SpotCutoffAngle(180.0f)
, m_ConstantAttenuation(1.0f)
, m_LinearAttenuation(0.0f)
, m_QuadraticAttenuation(0.0f)
, m_TwoSided(false)
, m_pContext(const_cast<QGLContext*>(pContext))
, m_IsValid(false)
{
	addNewLight();
}

GLC_Light::GLC_Light(const GLC_Light& light)
:GLC_Object(light)
, m_LightID(-1)
, m_LightType(light.m_LightType)
, m_AmbientColor(light.m_AmbientColor)
, m_DiffuseColor(light.m_DiffuseColor)
, m_SpecularColor(light.m_SpecularColor)
, m_Position(light.m_Position)
, m_SpotDirection(light.m_SpotDirection)
, m_SpotExponent(light.m_SpotExponent)
, m_SpotCutoffAngle(light.m_SpotCutoffAngle)
, m_ConstantAttenuation(light.m_ConstantAttenuation)
, m_LinearAttenuation(light.m_LinearAttenuation)
, m_QuadraticAttenuation(light.m_QuadraticAttenuation)
, m_TwoSided(light.m_TwoSided)
, m_pContext(light.m_pContext)
, m_IsValid(false)
{
	addNewLight();
}

GLC_Light::~GLC_Light(void)
{
	removeThisLight();
}

/////////////////////////////////////////////////////////////////////
// Get Functions
//////////////////////////////////////////////////////////////////////

int GLC_Light::maxLightCount()
{
	return m_MaxLight;
}

int GLC_Light::builtAbleLightCount(QGLContext* pContext)
{
	if (m_ContextToFreeLightSet.contains(pContext))
	{
		return m_ContextToFreeLightSet.value(pContext).size();
	}
	else return m_MaxLight;
}

/////////////////////////////////////////////////////////////////////
// Set Functions
//////////////////////////////////////////////////////////////////////
void GLC_Light::initForThisContext()
{
	for (int i= 0; i < m_MaxLight; ++i)
	{
		m_ContextToFreeLightSet[m_pContext].insert(GL_LIGHT0 + i);
	}
}

void GLC_Light::setPosition(const GLC_Point3d &pos)
{
	m_Position= pos;
}

void GLC_Light::setPosition(GLfloat x, GLfloat y, GLfloat z)
{
	m_Position.setVect(static_cast<double>(x), static_cast<double>(y), static_cast<double>(z));
}

void GLC_Light::setAmbientColor(const QColor& color)
{
	m_AmbientColor= color;
	m_IsValid= false;
}

void GLC_Light::setDiffuseColor(const QColor& color)
{
	m_DiffuseColor= color;
	m_IsValid= false;
}

void GLC_Light::setSpecularColor(const QColor& color)
{
	m_SpecularColor= color;
	m_IsValid= false;
}

void GLC_Light::setTwoSided(const bool mode)
{
	m_TwoSided= mode;
	m_IsValid= false;
}

void GLC_Light::setConstantAttenuation(GLfloat constantAttenuation)
{
	m_ConstantAttenuation= constantAttenuation;
	m_IsValid= false;
}

void GLC_Light::setLinearAttenuation(GLfloat linearAttenuation)
{
	m_LinearAttenuation= linearAttenuation;
	m_IsValid= false;
}

void GLC_Light::setQuadraticAttenuation(GLfloat quadraticAttenuation)
{
	m_QuadraticAttenuation= quadraticAttenuation;
	m_IsValid= false;
}

void GLC_Light::setSpotDirection(const GLC_Vector3d& direction)
{
	m_SpotDirection= direction;
	m_IsValid= false;
}

void GLC_Light::setSpotCutoffAngle(GLfloat cutoffAngle)
{
	m_SpotCutoffAngle= cutoffAngle;
	m_IsValid= false;
}

void GLC_Light::setSpotEponent(GLfloat exponent)
{
	m_SpotExponent= exponent;
	m_IsValid= false;
}

//////////////////////////////////////////////////////////////////////
// OpenGL Functions
//////////////////////////////////////////////////////////////////////

void GLC_Light::disable()
{
	if (NULL != m_pContext)
	{
		glDisable(m_LightID);
	}
}

void GLC_Light::glExecute()
{
	if (NULL == m_pContext)
	{
		m_pContext= const_cast<QGLContext*>(QGLContext::currentContext());
		Q_ASSERT(NULL != m_pContext);
		addNewLight();
	}

	glEnable(GL_LIGHTING);
	glEnable(m_LightID);

	if (m_pContext != QGLContext::currentContext())
	{
		Q_ASSERT(QGLContext::areSharing(m_pContext, QGLContext::currentContext()));
		m_IsValid= false;
	}
	Q_ASSERT(m_pContext->isValid());

	GLfloat setArray[4];

	// Position
	setArray[0]= static_cast<GLfloat>(m_Position.x());
	setArray[1]= static_cast<GLfloat>(m_Position.y());
	setArray[2]= static_cast<GLfloat>(m_Position.z());

	if (LightDirection == m_LightType)
	{
		setArray[3]= 0.0f;
		glLightfv(m_LightID, GL_POSITION, setArray);	// Direction of the Light
	}
	else
	{
		setArray[3]= 1.0f;
		glLightfv(m_LightID, GL_POSITION, setArray);	// Position of the Light
	}

	if (!m_IsValid)
	{
		// Set the lighting model
		if (m_TwoSided)
		{
			glLightModeli(GL_LIGHT_MODEL_TWO_SIDE, 1);
		}
		else
		{
			glLightModeli(GL_LIGHT_MODEL_TWO_SIDE, 0);
		}

		// Color
		setArray[0]= static_cast<GLfloat>(m_AmbientColor.redF());
		setArray[1]= static_cast<GLfloat>(m_AmbientColor.greenF());
		setArray[2]= static_cast<GLfloat>(m_AmbientColor.blueF());
		setArray[3]= static_cast<GLfloat>(m_AmbientColor.alphaF());
		glLightfv(m_LightID, GL_AMBIENT, setArray);		// Setup The Ambient Light

		setArray[0]= static_cast<GLfloat>(m_DiffuseColor.redF());
		setArray[1]= static_cast<GLfloat>(m_DiffuseColor.greenF());
		setArray[2]= static_cast<GLfloat>(m_DiffuseColor.blueF());
		setArray[3]= static_cast<GLfloat>(m_DiffuseColor.alphaF());
		glLightfv(m_LightID, GL_DIFFUSE, setArray);		// Setup The Diffuse Light

		setArray[0]= static_cast<GLfloat>(m_SpecularColor.redF());
		setArray[1]= static_cast<GLfloat>(m_SpecularColor.greenF());
		setArray[2]= static_cast<GLfloat>(m_SpecularColor.blueF());
		setArray[3]= static_cast<GLfloat>(m_SpecularColor.alphaF());
		glLightfv(m_LightID, GL_SPECULAR, setArray);	// Setup The specular Light

		if (LightDirection != m_LightType)
			glLightf(m_LightID, GL_CONSTANT_ATTENUATION, m_ConstantAttenuation);
			glLightf(m_LightID, GL_LINEAR_ATTENUATION, m_LinearAttenuation);
			glLightf(m_LightID, GL_QUADRATIC_ATTENUATION, m_QuadraticAttenuation);

		// Spot light parameters
		if (LightSpot == m_LightType)
		{
			// Spot Direction
			setArray[0]= static_cast<GLfloat>(m_SpotDirection.x());
			setArray[1]= static_cast<GLfloat>(m_SpotDirection.y());
			setArray[2]= static_cast<GLfloat>(m_SpotDirection.z());
			glLightfv(m_LightID, GL_SPOT_DIRECTION, setArray);
			glLightf(m_LightID, GL_SPOT_EXPONENT, m_SpotExponent);
			glLightf(m_LightID, GL_SPOT_CUTOFF, m_SpotCutoffAngle);
		}

		m_IsValid= true;
	}

	// OpenGL error handler
	GLenum error= glGetError();
	if (error != GL_NO_ERROR)
	{
		qDebug() << "GLC_Light::glExecute Exception, id= " << m_LightID;
		GLC_OpenGlException OpenGlException("GLC_Light::glExecute ", error);
		throw(OpenGlException);
	}

}

//////////////////////////////////////////////////////////////////////
// Private services Functions
//////////////////////////////////////////////////////////////////////

//////////////////////////////////////////////////////////////////////
// Private services fonction
//////////////////////////////////////////////////////////////////////
void GLC_Light::addNewLight()
{
	if (NULL != m_pContext)
	{
		if (!m_ContextToFreeLightSet.contains(m_pContext))
		{
			m_ContextToFreeLightSet.insert(m_pContext, QSet<GLenum>());
			initForThisContext();
		}

		// Some OpenGL driver support only Light0 ???
		if (m_ContextToFreeLightSet.value(m_pContext).size() == m_MaxLight)
		{
			m_LightID= GL_LIGHT0;
		}
		else
		{
			m_LightID= *(m_ContextToFreeLightSet[m_pContext].constBegin());
		}

		m_ContextToFreeLightSet[m_pContext].remove(m_LightID);
	}
}

void GLC_Light::removeThisLight()
{
	if (NULL != m_pContext)
	{
		Q_ASSERT(m_ContextToFreeLightSet.contains(m_pContext));
		Q_ASSERT(!m_ContextToFreeLightSet[m_pContext].contains(m_LightID));
		m_ContextToFreeLightSet[m_pContext].insert(m_LightID);
		if (m_ContextToFreeLightSet[m_pContext].size() == m_MaxLight)
		{
			m_ContextToFreeLightSet.remove(m_pContext);
		}
	}
}
<|endoftext|>


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

#include "config.h"
#include "platform/fonts/FontCache.h"

#include "SkFontMgr.h"
#include "SkTypeface_win.h"
#include "platform/RuntimeEnabledFeatures.h"
#include "platform/fonts/FontDescription.h"
#include "platform/fonts/FontFaceCreationParams.h"
#include "platform/fonts/SimpleFontData.h"
#include "platform/fonts/harfbuzz/FontPlatformDataHarfbuzz.h"
#include "platform/fonts/win/FontFallbackWin.h"

namespace blink {

HashMap<String, RefPtr<SkTypeface> >* FontCache::s_sideloadedFonts = 0;

// static
void FontCache::addSideloadedFontForTesting(SkTypeface* typeface)
{
    if (!s_sideloadedFonts)
        s_sideloadedFonts = new HashMap<String, RefPtr<SkTypeface> >;
    SkString name;
    typeface->getFamilyName(&name);
    s_sideloadedFonts->set(name.c_str(), typeface);
}

FontCache::FontCache()
    : m_purgePreventCount(0)
{
    SkFontMgr* fontManager;

    if (s_useDirectWrite) {
        fontManager = SkFontMgr_New_DirectWrite(s_directWriteFactory);
        s_useSubpixelPositioning = RuntimeEnabledFeatures::subpixelFontScalingEnabled();
    } else {
        fontManager = SkFontMgr_New_GDI();
        // Subpixel text positioning is not supported by the GDI backend.
        s_useSubpixelPositioning = false;
    }

    ASSERT(fontManager);
    m_fontManager = adoptPtr(fontManager);
}

// Given the desired base font, this will create a SimpleFontData for a specific
// font that can be used to render the given range of characters.
PassRefPtr<SimpleFontData> FontCache::fallbackFontForCharacter(const FontDescription& fontDescription, UChar32 character, const SimpleFontData*)
{
    // First try the specified font with standard style & weight.
    if (fontDescription.style() == FontStyleItalic
        || fontDescription.weight() >= FontWeightBold) {
        RefPtr<SimpleFontData> fontData = fallbackOnStandardFontStyle(
            fontDescription, character);
        if (fontData)
            return fontData;
    }

    // FIXME: Consider passing fontDescription.dominantScript()
    // to GetFallbackFamily here.
    UScriptCode script;
    const wchar_t* family = getFallbackFamily(character,
        fontDescription.genericFamily(),
        &script,
        m_fontManager.get());
    FontPlatformData* data = 0;
    if (family) {
        FontFaceCreationParams createByFamily(AtomicString(family, wcslen(family)));
        data = getFontPlatformData(fontDescription, createByFamily);
    }

    // Last resort font list : PanUnicode. CJK fonts have a pretty
    // large repertoire. Eventually, we need to scan all the fonts
    // on the system to have a Firefox-like coverage.
    // Make sure that all of them are lowercased.
    const static wchar_t* const cjkFonts[] = {
        L"arial unicode ms",
        L"ms pgothic",
        L"simsun",
        L"gulim",
        L"pmingliu",
        L"wenquanyi zen hei", // Partial CJK Ext. A coverage but more widely known to Chinese users.
        L"ar pl shanheisun uni",
        L"ar pl zenkai uni",
        L"han nom a", // Complete CJK Ext. A coverage.
        L"code2000" // Complete CJK Ext. A coverage.
        // CJK Ext. B fonts are not listed here because it's of no use
        // with our current non-BMP character handling because we use
        // Uniscribe for it and that code path does not go through here.
    };

    const static wchar_t* const commonFonts[] = {
        L"tahoma",
        L"arial unicode ms",
        L"lucida sans unicode",
        L"microsoft sans serif",
        L"palatino linotype",
        // Six fonts below (and code2000 at the end) are not from MS, but
        // once installed, cover a very wide range of characters.
        L"dejavu serif",
        L"dejavu sasns",
        L"freeserif",
        L"freesans",
        L"gentium",
        L"gentiumalt",
        L"ms pgothic",
        L"simsun",
        L"gulim",
        L"pmingliu",
        L"code2000"
    };

    const wchar_t* const* panUniFonts = 0;
    int numFonts = 0;
    if (script == USCRIPT_HAN) {
        panUniFonts = cjkFonts;
        numFonts = WTF_ARRAY_LENGTH(cjkFonts);
    } else {
        panUniFonts = commonFonts;
        numFonts = WTF_ARRAY_LENGTH(commonFonts);
    }
    // Font returned from getFallbackFamily may not cover |character|
    // because it's based on script to font mapping. This problem is
    // critical enough for non-Latin scripts (especially Han) to
    // warrant an additional (real coverage) check with fontCotainsCharacter.
    int i;
    for (i = 0; (!data || !data->fontContainsCharacter(character)) && i < numFonts; ++i) {
        family = panUniFonts[i];
        FontFaceCreationParams createByFamily(AtomicString(family, wcslen(family)));
        data = getFontPlatformData(fontDescription, createByFamily);
    }

    // When i-th font (0-base) in |panUniFonts| contains a character and
    // we get out of the loop, |i| will be |i + 1|. That is, if only the
    // last font in the array covers the character, |i| will be numFonts.
    // So, we have to use '<=" rather than '<' to see if we found a font
    // covering the character.
    if (i <= numFonts)
        return fontDataFromFontPlatformData(data, DoNotRetain);

    return nullptr;
}

static inline bool equalIgnoringCase(const AtomicString& a, const SkString& b)
{
    return equalIgnoringCase(a, AtomicString::fromUTF8(b.c_str()));
}

static bool typefacesMatchesFamily(const SkTypeface* tf, const AtomicString& family)
{
    SkTypeface::LocalizedStrings* actualFamilies = tf->createFamilyNameIterator();
    bool matchesRequestedFamily = false;
    SkTypeface::LocalizedString actualFamily;

    while (actualFamilies->next(&actualFamily)) {
        if (equalIgnoringCase(family, actualFamily.fString)) {
            matchesRequestedFamily = true;
            break;
        }
    }
    actualFamilies->unref();

    // getFamilyName may return a name not returned by the createFamilyNameIterator.
    // Specifically in cases where Windows substitutes the font based on the
    // HKLM\SOFTWARE\Microsoft\Windows NT\CurrentVersion\FontSubstitutes registry entries.
    if (!matchesRequestedFamily) {
        SkString familyName;
        tf->getFamilyName(&familyName);
        if (equalIgnoringCase(family, familyName))
            matchesRequestedFamily = true;
    }

    return matchesRequestedFamily;
}

static bool typefacesHasVariantSuffix(const AtomicString& family,
    AtomicString& adjustedName, FontWeight& variantWeight)
{
    struct FamilyVariantSuffix {
        const wchar_t* suffix;
        size_t length;
        FontWeight weight;
    };
    // Mapping from suffix to weight from the DirectWrite documentation.
    // http://msdn.microsoft.com/en-us/library/windows/desktop/dd368082(v=vs.85).aspx
    const static FamilyVariantSuffix variantForSuffix[] = {
        { L" thin", 5,  FontWeight100 },
        { L" extralight", 11,  FontWeight200 },
        { L" ultralight", 11,  FontWeight200 },
        { L" light", 6,  FontWeight300 },
        { L" medium", 7,  FontWeight500 },
        { L" demibold", 9,  FontWeight600 },
        { L" semibold", 9,  FontWeight600 },
        { L" extrabold", 10,  FontWeight800 },
        { L" ultrabold", 10,  FontWeight800 },
        { L" black", 6,  FontWeight900 },
        { L" heavy", 6,  FontWeight900 }
    };
    size_t numVariants = WTF_ARRAY_LENGTH(variantForSuffix);
    bool caseSensitive = false;
    for (size_t i = 0; i < numVariants; i++) {
        const FamilyVariantSuffix& entry = variantForSuffix[i];
        if (family.endsWith(entry.suffix, caseSensitive)) {
            String familyName = family.string();
            familyName.truncate(family.length() - entry.length);
            adjustedName = AtomicString(familyName);
            variantWeight = entry.weight;
            return true;
        }
    }

    return false;
}

FontPlatformData* FontCache::createFontPlatformData(const FontDescription& fontDescription, const FontFaceCreationParams& creationParams, float fontSize)
{
    ASSERT(creationParams.creationType() == CreateFontByFamily);

    CString name;
    RefPtr<SkTypeface> tf = createTypeface(fontDescription, creationParams, name);
    // Windows will always give us a valid pointer here, even if the face name
    // is non-existent. We have to double-check and see if the family name was
    // really used.
    if (!tf || !typefacesMatchesFamily(tf.get(), creationParams.family())) {
        AtomicString adjustedName;
        FontWeight variantWeight;
        if (typefacesHasVariantSuffix(creationParams.family(), adjustedName,
            variantWeight)) {
            FontFaceCreationParams adjustedParams(adjustedName);
            FontDescription adjustedFontDescription = fontDescription;
            adjustedFontDescription.setWeight(variantWeight);
            tf = createTypeface(adjustedFontDescription, adjustedParams, name);
            if (!tf || !typefacesMatchesFamily(tf.get(), adjustedName))
                return 0;
        } else {
            return 0;
        }
    }

    FontPlatformData* result = new FontPlatformData(tf,
        name.data(),
        fontSize,
        fontDescription.weight() >= FontWeight600 && !tf->isBold() || fontDescription.isSyntheticBold(),
        fontDescription.style() == FontStyleItalic && !tf->isItalic() || fontDescription.isSyntheticItalic(),
        fontDescription.orientation(),
        s_useSubpixelPositioning);

    struct FamilyMinSize {
        const wchar_t* family;
        unsigned minSize;
    };
    const static FamilyMinSize minAntiAliasSizeForFont[] = {
        { L"simsun", 11 },
        { L"dotum", 12 },
        { L"gulim", 12 },
        { L"pmingliu", 11 }
    };
    size_t numFonts = WTF_ARRAY_LENGTH(minAntiAliasSizeForFont);
    for (size_t i = 0; i < numFonts; i++) {
        FamilyMinSize entry = minAntiAliasSizeForFont[i];
        if (typefacesMatchesFamily(tf.get(), entry.family)) {
            result->setMinSizeForAntiAlias(entry.minSize);
            break;
        }
    }

    // List of fonts that look bad with subpixel text rendering at smaller font
    // sizes. This includes all fonts in the Microsoft Core fonts for the Web
    // collection.
    const static wchar_t* noSubpixelForSmallSizeFont[] = {
        L"andale mono",
        L"arial",
        L"comic sans",
        L"courier new",
        L"georgia",
        L"impact",
        L"lucida console",
        L"tahoma",
        L"times new roman",
        L"trebuchet ms",
        L"verdana",
        L"webdings"
    };
    const static float minSizeForSubpixelForFont = 16.0f;
    numFonts = WTF_ARRAY_LENGTH(noSubpixelForSmallSizeFont);
    for (size_t i = 0; i < numFonts; i++) {
        const wchar_t* family = noSubpixelForSmallSizeFont[i];
        if (typefacesMatchesFamily(tf.get(), family)) {
            result->setMinSizeForSubpixel(minSizeForSubpixelForFont);
            break;
        }
    }

    return result;
}

} // namespace blink
<commit_msg>Gardening: Fix tests failing on Win7(dbg) caused by hitting an assert in FontCache::addSideloadedFontForTesting<commit_after>/*
 * Copyright (C) 2006, 2007 Apple Computer, Inc.
 * Copyright (c) 2006, 2007, 2008, 2009, 2012 Google Inc. All rights reserved.
 *
 * Redistribution and use in source and binary forms, with or without
 * modification, are permitted provided that the following conditions are
 * met:
 *
 *     * Redistributions of source code must retain the above copyright
 * notice, this list of conditions and the following disclaimer.
 *     * Redistributions in binary form must reproduce the above
 * copyright notice, this list of conditions and the following disclaimer
 * in the documentation and/or other materials provided with the
 * distribution.
 *     * Neither the name of Google Inc. nor the names of its
 * contributors may be used to endorse or promote products derived from
 * this software without specific prior written permission.
 *
 * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
 * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
 * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
 * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
 * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
 * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
 * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
 * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
 * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
 * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
 * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
 */

#include "config.h"
#include "platform/fonts/FontCache.h"

#include "SkFontMgr.h"
#include "SkTypeface_win.h"
#include "platform/RuntimeEnabledFeatures.h"
#include "platform/fonts/FontDescription.h"
#include "platform/fonts/FontFaceCreationParams.h"
#include "platform/fonts/SimpleFontData.h"
#include "platform/fonts/harfbuzz/FontPlatformDataHarfbuzz.h"
#include "platform/fonts/win/FontFallbackWin.h"

namespace blink {

HashMap<String, RefPtr<SkTypeface> >* FontCache::s_sideloadedFonts = 0;

// static
void FontCache::addSideloadedFontForTesting(SkTypeface* typeface)
{
    if (!typeface)
        return;
    if (!s_sideloadedFonts)
        s_sideloadedFonts = new HashMap<String, RefPtr<SkTypeface> >;
    SkString name;
    typeface->getFamilyName(&name);
    s_sideloadedFonts->set(name.c_str(), typeface);
}

FontCache::FontCache()
    : m_purgePreventCount(0)
{
    SkFontMgr* fontManager;

    if (s_useDirectWrite) {
        fontManager = SkFontMgr_New_DirectWrite(s_directWriteFactory);
        s_useSubpixelPositioning = RuntimeEnabledFeatures::subpixelFontScalingEnabled();
    } else {
        fontManager = SkFontMgr_New_GDI();
        // Subpixel text positioning is not supported by the GDI backend.
        s_useSubpixelPositioning = false;
    }

    ASSERT(fontManager);
    m_fontManager = adoptPtr(fontManager);
}

// Given the desired base font, this will create a SimpleFontData for a specific
// font that can be used to render the given range of characters.
PassRefPtr<SimpleFontData> FontCache::fallbackFontForCharacter(const FontDescription& fontDescription, UChar32 character, const SimpleFontData*)
{
    // First try the specified font with standard style & weight.
    if (fontDescription.style() == FontStyleItalic
        || fontDescription.weight() >= FontWeightBold) {
        RefPtr<SimpleFontData> fontData = fallbackOnStandardFontStyle(
            fontDescription, character);
        if (fontData)
            return fontData;
    }

    // FIXME: Consider passing fontDescription.dominantScript()
    // to GetFallbackFamily here.
    UScriptCode script;
    const wchar_t* family = getFallbackFamily(character,
        fontDescription.genericFamily(),
        &script,
        m_fontManager.get());
    FontPlatformData* data = 0;
    if (family) {
        FontFaceCreationParams createByFamily(AtomicString(family, wcslen(family)));
        data = getFontPlatformData(fontDescription, createByFamily);
    }

    // Last resort font list : PanUnicode. CJK fonts have a pretty
    // large repertoire. Eventually, we need to scan all the fonts
    // on the system to have a Firefox-like coverage.
    // Make sure that all of them are lowercased.
    const static wchar_t* const cjkFonts[] = {
        L"arial unicode ms",
        L"ms pgothic",
        L"simsun",
        L"gulim",
        L"pmingliu",
        L"wenquanyi zen hei", // Partial CJK Ext. A coverage but more widely known to Chinese users.
        L"ar pl shanheisun uni",
        L"ar pl zenkai uni",
        L"han nom a", // Complete CJK Ext. A coverage.
        L"code2000" // Complete CJK Ext. A coverage.
        // CJK Ext. B fonts are not listed here because it's of no use
        // with our current non-BMP character handling because we use
        // Uniscribe for it and that code path does not go through here.
    };

    const static wchar_t* const commonFonts[] = {
        L"tahoma",
        L"arial unicode ms",
        L"lucida sans unicode",
        L"microsoft sans serif",
        L"palatino linotype",
        // Six fonts below (and code2000 at the end) are not from MS, but
        // once installed, cover a very wide range of characters.
        L"dejavu serif",
        L"dejavu sasns",
        L"freeserif",
        L"freesans",
        L"gentium",
        L"gentiumalt",
        L"ms pgothic",
        L"simsun",
        L"gulim",
        L"pmingliu",
        L"code2000"
    };

    const wchar_t* const* panUniFonts = 0;
    int numFonts = 0;
    if (script == USCRIPT_HAN) {
        panUniFonts = cjkFonts;
        numFonts = WTF_ARRAY_LENGTH(cjkFonts);
    } else {
        panUniFonts = commonFonts;
        numFonts = WTF_ARRAY_LENGTH(commonFonts);
    }
    // Font returned from getFallbackFamily may not cover |character|
    // because it's based on script to font mapping. This problem is
    // critical enough for non-Latin scripts (especially Han) to
    // warrant an additional (real coverage) check with fontCotainsCharacter.
    int i;
    for (i = 0; (!data || !data->fontContainsCharacter(character)) && i < numFonts; ++i) {
        family = panUniFonts[i];
        FontFaceCreationParams createByFamily(AtomicString(family, wcslen(family)));
        data = getFontPlatformData(fontDescription, createByFamily);
    }

    // When i-th font (0-base) in |panUniFonts| contains a character and
    // we get out of the loop, |i| will be |i + 1|. That is, if only the
    // last font in the array covers the character, |i| will be numFonts.
    // So, we have to use '<=" rather than '<' to see if we found a font
    // covering the character.
    if (i <= numFonts)
        return fontDataFromFontPlatformData(data, DoNotRetain);

    return nullptr;
}

static inline bool equalIgnoringCase(const AtomicString& a, const SkString& b)
{
    return equalIgnoringCase(a, AtomicString::fromUTF8(b.c_str()));
}

static bool typefacesMatchesFamily(const SkTypeface* tf, const AtomicString& family)
{
    SkTypeface::LocalizedStrings* actualFamilies = tf->createFamilyNameIterator();
    bool matchesRequestedFamily = false;
    SkTypeface::LocalizedString actualFamily;

    while (actualFamilies->next(&actualFamily)) {
        if (equalIgnoringCase(family, actualFamily.fString)) {
            matchesRequestedFamily = true;
            break;
        }
    }
    actualFamilies->unref();

    // getFamilyName may return a name not returned by the createFamilyNameIterator.
    // Specifically in cases where Windows substitutes the font based on the
    // HKLM\SOFTWARE\Microsoft\Windows NT\CurrentVersion\FontSubstitutes registry entries.
    if (!matchesRequestedFamily) {
        SkString familyName;
        tf->getFamilyName(&familyName);
        if (equalIgnoringCase(family, familyName))
            matchesRequestedFamily = true;
    }

    return matchesRequestedFamily;
}

static bool typefacesHasVariantSuffix(const AtomicString& family,
    AtomicString& adjustedName, FontWeight& variantWeight)
{
    struct FamilyVariantSuffix {
        const wchar_t* suffix;
        size_t length;
        FontWeight weight;
    };
    // Mapping from suffix to weight from the DirectWrite documentation.
    // http://msdn.microsoft.com/en-us/library/windows/desktop/dd368082(v=vs.85).aspx
    const static FamilyVariantSuffix variantForSuffix[] = {
        { L" thin", 5,  FontWeight100 },
        { L" extralight", 11,  FontWeight200 },
        { L" ultralight", 11,  FontWeight200 },
        { L" light", 6,  FontWeight300 },
        { L" medium", 7,  FontWeight500 },
        { L" demibold", 9,  FontWeight600 },
        { L" semibold", 9,  FontWeight600 },
        { L" extrabold", 10,  FontWeight800 },
        { L" ultrabold", 10,  FontWeight800 },
        { L" black", 6,  FontWeight900 },
        { L" heavy", 6,  FontWeight900 }
    };
    size_t numVariants = WTF_ARRAY_LENGTH(variantForSuffix);
    bool caseSensitive = false;
    for (size_t i = 0; i < numVariants; i++) {
        const FamilyVariantSuffix& entry = variantForSuffix[i];
        if (family.endsWith(entry.suffix, caseSensitive)) {
            String familyName = family.string();
            familyName.truncate(family.length() - entry.length);
            adjustedName = AtomicString(familyName);
            variantWeight = entry.weight;
            return true;
        }
    }

    return false;
}

FontPlatformData* FontCache::createFontPlatformData(const FontDescription& fontDescription, const FontFaceCreationParams& creationParams, float fontSize)
{
    ASSERT(creationParams.creationType() == CreateFontByFamily);

    CString name;
    RefPtr<SkTypeface> tf = createTypeface(fontDescription, creationParams, name);
    // Windows will always give us a valid pointer here, even if the face name
    // is non-existent. We have to double-check and see if the family name was
    // really used.
    if (!tf || !typefacesMatchesFamily(tf.get(), creationParams.family())) {
        AtomicString adjustedName;
        FontWeight variantWeight;
        if (typefacesHasVariantSuffix(creationParams.family(), adjustedName,
            variantWeight)) {
            FontFaceCreationParams adjustedParams(adjustedName);
            FontDescription adjustedFontDescription = fontDescription;
            adjustedFontDescription.setWeight(variantWeight);
            tf = createTypeface(adjustedFontDescription, adjustedParams, name);
            if (!tf || !typefacesMatchesFamily(tf.get(), adjustedName))
                return 0;
        } else {
            return 0;
        }
    }

    FontPlatformData* result = new FontPlatformData(tf,
        name.data(),
        fontSize,
        fontDescription.weight() >= FontWeight600 && !tf->isBold() || fontDescription.isSyntheticBold(),
        fontDescription.style() == FontStyleItalic && !tf->isItalic() || fontDescription.isSyntheticItalic(),
        fontDescription.orientation(),
        s_useSubpixelPositioning);

    struct FamilyMinSize {
        const wchar_t* family;
        unsigned minSize;
    };
    const static FamilyMinSize minAntiAliasSizeForFont[] = {
        { L"simsun", 11 },
        { L"dotum", 12 },
        { L"gulim", 12 },
        { L"pmingliu", 11 }
    };
    size_t numFonts = WTF_ARRAY_LENGTH(minAntiAliasSizeForFont);
    for (size_t i = 0; i < numFonts; i++) {
        FamilyMinSize entry = minAntiAliasSizeForFont[i];
        if (typefacesMatchesFamily(tf.get(), entry.family)) {
            result->setMinSizeForAntiAlias(entry.minSize);
            break;
        }
    }

    // List of fonts that look bad with subpixel text rendering at smaller font
    // sizes. This includes all fonts in the Microsoft Core fonts for the Web
    // collection.
    const static wchar_t* noSubpixelForSmallSizeFont[] = {
        L"andale mono",
        L"arial",
        L"comic sans",
        L"courier new",
        L"georgia",
        L"impact",
        L"lucida console",
        L"tahoma",
        L"times new roman",
        L"trebuchet ms",
        L"verdana",
        L"webdings"
    };
    const static float minSizeForSubpixelForFont = 16.0f;
    numFonts = WTF_ARRAY_LENGTH(noSubpixelForSmallSizeFont);
    for (size_t i = 0; i < numFonts; i++) {
        const wchar_t* family = noSubpixelForSmallSizeFont[i];
        if (typefacesMatchesFamily(tf.get(), family)) {
            result->setMinSizeForSubpixel(minSizeForSubpixelForFont);
            break;
        }
    }

    return result;
}

} // namespace blink
<|endoftext|>


<commit_before>//  Copyright 2016 Peter Georg
//
//  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 "operations.hpp"
extern "C" {
#include <infiniband/verbs.h>
}
#include <stdexcept>
#include "verbs.hpp"

void pMR::Verbs::postSendRequest(
    Endpoint &endpoint, ScatterGatherElement &scatterGatherElement)
{
    return postSendRequest(endpoint.getQueuePair(), scatterGatherElement);
}

void pMR::Verbs::postSendRequest(
    QueuePair &queuePair, ScatterGatherElement &scatterGatherElement)
{
    ibv_send_wr workRequest = {};

    workRequest.wr_id = {cSendWRID};
    workRequest.sg_list = scatterGatherElement.get();
    workRequest.num_sge = {scatterGatherElement.getNumEntries()};
    workRequest.opcode = IBV_WR_SEND;

    if(scatterGatherElement.getLength() <= cMaxInlineDataSize)
    {
        workRequest.send_flags = IBV_SEND_INLINE;
    }

    ibv_send_wr *badRequest;

    if(ibv_post_send(queuePair.get(), &workRequest, &badRequest))
    {
        throw std::runtime_error("pMR: Unable to post Send Work Request.");
    }
}

void pMR::Verbs::postRecvRequest(
    Endpoint &endpoint, ScatterGatherElement &scatterGatherElement)
{
    return postRecvRequest(endpoint.getQueuePair(), scatterGatherElement);
}

void pMR::Verbs::postRecvRequest(
    QueuePair &queuePair, ScatterGatherElement &scatterGatherElement)
{
    ibv_recv_wr workRequest = {};

    workRequest.wr_id = {cRecvWRID};
    workRequest.sg_list = scatterGatherElement.get();
    workRequest.num_sge = {scatterGatherElement.getNumEntries()};

    ibv_recv_wr *badRequest;

    if(ibv_post_recv(queuePair.get(), &workRequest, &badRequest))
    {
        throw std::runtime_error("pMR: Unable to post Receive Work Request.");
    }
}

void pMR::Verbs::postWriteRequest(Endpoint &endpoint,
    ScatterGatherElement &scatterGatherElement, MemoryAddress &target)
{
    return postWriteRequest(
        endpoint.getQueuePair(), scatterGatherElement, target);
}

void pMR::Verbs::postWriteRequest(QueuePair &queuePair,
    ScatterGatherElement &scatterGatherElement, MemoryAddress &target)
{
    ibv_send_wr workRequest = {};

    workRequest.wr_id = {cWriteWRID};
    workRequest.sg_list = scatterGatherElement.get();
    workRequest.num_sge = {scatterGatherElement.getNumEntries()};
    workRequest.opcode = IBV_WR_RDMA_WRITE_WITH_IMM;
    workRequest.wr.rdma.remote_addr = {target.getAddress()};
    workRequest.wr.rdma.rkey = {target.getRKey()};

    if(scatterGatherElement.getLength() <= cMaxInlineDataSize)
    {
        workRequest.send_flags = IBV_SEND_INLINE;
    }

    ibv_send_wr *badRequest;

    if(ibv_post_send(queuePair.get(), &workRequest, &badRequest))
    {
        throw std::runtime_error("pMR: Unable to post RDMA Work Request.");
    }
}
<commit_msg>Improve error messages<commit_after>//  Copyright 2016 Peter Georg
//
//  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 "operations.hpp"
#include <cstring>
#include <stdexcept>
extern "C" {
#include <infiniband/verbs.h>
}
#include "../../misc/string.hpp"
#include "verbs.hpp"

void pMR::Verbs::postSendRequest(
    Endpoint &endpoint, ScatterGatherElement &scatterGatherElement)
{
    return postSendRequest(endpoint.getQueuePair(), scatterGatherElement);
}

void pMR::Verbs::postSendRequest(
    QueuePair &queuePair, ScatterGatherElement &scatterGatherElement)
{
    ibv_send_wr workRequest = {};

    workRequest.wr_id = {cSendWRID};
    workRequest.sg_list = scatterGatherElement.get();
    workRequest.num_sge = {scatterGatherElement.getNumEntries()};
    workRequest.opcode = IBV_WR_SEND;

    if(scatterGatherElement.getLength() <= cMaxInlineDataSize)
    {
        workRequest.send_flags = IBV_SEND_INLINE;
    }

    ibv_send_wr *badRequest;

    auto err = ibv_post_send(queuePair.get(), &workRequest, &badRequest);
    if(err)
    {
        throw std::runtime_error(toString(
            "pMR: Unable to post Send Work Request:", std::strerror(err)));
    }
}

void pMR::Verbs::postRecvRequest(
    Endpoint &endpoint, ScatterGatherElement &scatterGatherElement)
{
    return postRecvRequest(endpoint.getQueuePair(), scatterGatherElement);
}

void pMR::Verbs::postRecvRequest(
    QueuePair &queuePair, ScatterGatherElement &scatterGatherElement)
{
    ibv_recv_wr workRequest = {};

    workRequest.wr_id = {cRecvWRID};
    workRequest.sg_list = scatterGatherElement.get();
    workRequest.num_sge = {scatterGatherElement.getNumEntries()};

    ibv_recv_wr *badRequest;

    auto err = ibv_post_recv(queuePair.get(), &workRequest, &badRequest);
    if(err)
    {
        throw std::runtime_error(toString(
            "pMR: Unable to post Receive Work Request:", std::strerror(err)));
    }
}

void pMR::Verbs::postWriteRequest(Endpoint &endpoint,
    ScatterGatherElement &scatterGatherElement, MemoryAddress &target)
{
    return postWriteRequest(
        endpoint.getQueuePair(), scatterGatherElement, target);
}

void pMR::Verbs::postWriteRequest(QueuePair &queuePair,
    ScatterGatherElement &scatterGatherElement, MemoryAddress &target)
{
    ibv_send_wr workRequest = {};

    workRequest.wr_id = {cWriteWRID};
    workRequest.sg_list = scatterGatherElement.get();
    workRequest.num_sge = {scatterGatherElement.getNumEntries()};
    workRequest.opcode = IBV_WR_RDMA_WRITE_WITH_IMM;
    workRequest.wr.rdma.remote_addr = {target.getAddress()};
    workRequest.wr.rdma.rkey = {target.getRKey()};

    if(scatterGatherElement.getLength() <= cMaxInlineDataSize)
    {
        workRequest.send_flags = IBV_SEND_INLINE;
    }

    ibv_send_wr *badRequest;

    auto err = ibv_post_send(queuePair.get(), &workRequest, &badRequest);
    if(err)
    {
        throw std::runtime_error(toString(
            "pMR: Unable to post RDMA Work Request:", std::strerror(err)));
    }
}
<|endoftext|>


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

#include "config.h"
#include "platform/graphics/paint/DisplayItem.h"

namespace blink {

#ifndef NDEBUG

static WTF::String paintPhaseAsDebugString(int paintPhase)
{
    // Must be kept in sync with PaintPhase.
    switch (paintPhase) {
    case 0: return "PaintPhaseBlockBackground";
    case 1: return "PaintPhaseChildBlockBackground";
    case 2: return "PaintPhaseChildBlockBackgrounds";
    case 3: return "PaintPhaseFloat";
    case 4: return "PaintPhaseForeground";
    case 5: return "PaintPhaseOutline";
    case 6: return "PaintPhaseChildOutlines";
    case 7: return "PaintPhaseSelfOutline";
    case 8: return "PaintPhaseSelection";
    case 9: return "PaintPhaseCollapsedTableBorders";
    case 10: return "PaintPhaseTextClip";
    case 11: return "PaintPhaseMask";
    case DisplayItem::PaintPhaseMax: return "PaintPhaseClippingMask";
    default:
        ASSERT_NOT_REACHED();
        return "Unknown";
    }
}

#define PAINT_PHASE_BASED_DEBUG_STRINGS(Category) \
    if (type >= DisplayItem::Category##PaintPhaseFirst && type <= DisplayItem::Category##PaintPhaseLast) \
        return #Category + paintPhaseAsDebugString(type - DisplayItem::Category##PaintPhaseFirst);

static WTF::String drawingTypeAsDebugString(DisplayItem::Type type)
{
    PAINT_PHASE_BASED_DEBUG_STRINGS(Drawing);

    switch (type) {
    case DisplayItem::BoxDecorationBackground: return "DrawingBoxDecorationBackground";
    case DisplayItem::Caret: return "DrawingCaret";
    case DisplayItem::ColumnRules: return "DrawingColumnRules";
    case DisplayItem::DebugRedFill: return "DrawingDebugRedFill";
    case DisplayItem::DragImage: return "DrawingDragImage";
    case DisplayItem::SVGImage: return "DrawingSVGImage";
    case DisplayItem::LinkHighlight: return "DrawingLinkHighlight";
    case DisplayItem::PageOverlay: return "PageOverlay";
    case DisplayItem::PageWidgetDelegateBackgroundFallback: return "DrawingPageWidgetDelegateBackgroundFallback";
    case DisplayItem::PopupContainerBorder: return "DrawingPopupContainerBorder";
    case DisplayItem::PopupListBoxBackground: return "DrawingPopupListBoxBackground";
    case DisplayItem::PopupListBoxRow: return "DrawingPopupListBoxRow";
    case DisplayItem::Resizer: return "DrawingResizer";
    case DisplayItem::SVGClip: return "DrawingSVGClip";
    case DisplayItem::SVGFilter: return "DrawingSVGFilter";
    case DisplayItem::SVGMask: return "DrawingSVGMask";
    case DisplayItem::ScrollbarBackButtonEnd: return "ScrollbarBackButtonEnd";
    case DisplayItem::ScrollbarBackButtonStart: return "ScrollbarBackButtonStart";
    case DisplayItem::ScrollbarBackground: return "ScrollbarBackground";
    case DisplayItem::ScrollbarBackTrack: return "ScrollbarBackTrack";
    case DisplayItem::ScrollbarCorner: return "DrawingScrollbarCorner";
    case DisplayItem::ScrollbarForwardButtonEnd: return "ScrollbarForwardButtonEnd";
    case DisplayItem::ScrollbarForwardButtonStart: return "ScrollbarForwardButtonStart";
    case DisplayItem::ScrollbarForwardTrack: return "ScrollbarForwardTrack";
    case DisplayItem::ScrollbarHorizontal: return "ScrollbarHorizontal";
    case DisplayItem::ScrollbarThumb: return "ScrollbarThumb";
    case DisplayItem::ScrollbarTickmarks: return "ScrollbarTickmarks";
    case DisplayItem::ScrollbarTrackBackground: return "ScrollbarTrackBackground";
    case DisplayItem::ScrollbarVertical: return "ScrollbarVertical";
    case DisplayItem::SelectionGap: return "DrawingSelectionGap";
    case DisplayItem::SelectionTint: return "DrawingSelectionTint";
    case DisplayItem::TableCellBackgroundFromSelfPaintingRow: return "TableCellBackgroundFromSelfPaintingRow";
    case DisplayItem::VideoBitmap: return "DrawingVideoBitmap";
    case DisplayItem::WebPlugin: return "DrawingWebPlugin";
    default:
        ASSERT_NOT_REACHED();
        return "Unknown";
    }
}

static WTF::String clipTypeAsDebugString(DisplayItem::Type type)
{
    PAINT_PHASE_BASED_DEBUG_STRINGS(ClipBox);
    PAINT_PHASE_BASED_DEBUG_STRINGS(ClipColumnBounds);
    PAINT_PHASE_BASED_DEBUG_STRINGS(ClipLayerFragment);

    switch (type) {
    case DisplayItem::ClipFileUploadControlRect: return "ClipFileUploadControlRect";
    case DisplayItem::ClipFrameToVisibleContentRect: return "ClipFrameToVisibleContentRect";
    case DisplayItem::ClipFrameScrollbars: return "ClipFrameScrollbars";
    case DisplayItem::ClipLayerBackground: return "ClipLayerBackground";
    case DisplayItem::ClipLayerColumnBounds: return "ClipLayerColumnBounds";
    case DisplayItem::ClipLayerFilter: return "ClipLayerFilter";
    case DisplayItem::ClipLayerForeground: return "ClipLayerForeground";
    case DisplayItem::ClipLayerParent: return "ClipLayerParent";
    case DisplayItem::ClipLayerOverflowControls: return "ClipLayerOverflowControls";
    case DisplayItem::ClipNodeImage: return "ClipNodeImage";
    case DisplayItem::ClipPopupListBoxFrame: return "ClipPopupListBoxFrame";
    case DisplayItem::ClipSelectionImage: return "ClipSelectionImage";
    case DisplayItem::PageWidgetDelegateClip: return "PageWidgetDelegateClip";
    case DisplayItem::TransparencyClip: return "TransparencyClip";
    default:
        ASSERT_NOT_REACHED();
        return "Unknown";
    }
}

static String transform3DTypeAsDebugString(DisplayItem::Type type)
{
    switch (type) {
    case DisplayItem::Transform3DElementTransform: return "Transform3DElementTransform";
    default:
        ASSERT_NOT_REACHED();
        return "Unknown";
    }
}

WTF::String DisplayItem::typeAsDebugString(Type type)
{
    if (isDrawingType(type))
        return drawingTypeAsDebugString(type);
    if (isCachedType(type))
        return "Cached" + drawingTypeAsDebugString(cachedTypeToDrawingType(type));
    if (isClipType(type))
        return clipTypeAsDebugString(type);
    if (isEndClipType(type))
        return "End" + clipTypeAsDebugString(endClipTypeToClipType(type));

    PAINT_PHASE_BASED_DEBUG_STRINGS(FloatClip);
    if (isEndFloatClipType(type))
        return "End" + typeAsDebugString(endFloatClipTypeToFloatClipType(type));

    PAINT_PHASE_BASED_DEBUG_STRINGS(Scroll);
    if (isEndScrollType(type))
        return "End" + typeAsDebugString(endScrollTypeToScrollType(type));

    if (isTransform3DType(type))
        return transform3DTypeAsDebugString(type);
    if (isEndTransform3DType(type))
        return "End" + transform3DTypeAsDebugString(endTransform3DTypeToTransform3DType(type));

    PAINT_PHASE_BASED_DEBUG_STRINGS(SubtreeCached);
    PAINT_PHASE_BASED_DEBUG_STRINGS(BeginSubtree);
    PAINT_PHASE_BASED_DEBUG_STRINGS(EndSubtree);

    switch (type) {
    case BeginFilter: return "BeginFilter";
    case EndFilter: return "EndFilter";
    case BeginCompositing: return "BeginCompositing";
    case EndCompositing: return "EndCompositing";
    case BeginTransform: return "BeginTransform";
    case EndTransform: return "EndTransform";
    case BeginClipPath: return "BeginClipPath";
    case EndClipPath: return "EndClipPath";
    default:
        ASSERT_NOT_REACHED();
        return "Unknown";
    }
}

WTF::String DisplayItem::asDebugString() const
{
    WTF::StringBuilder stringBuilder;
    stringBuilder.append('{');
    dumpPropertiesAsDebugString(stringBuilder);
    stringBuilder.append('}');
    return stringBuilder.toString();
}

void DisplayItem::dumpPropertiesAsDebugString(WTF::StringBuilder& stringBuilder) const
{
    stringBuilder.append(String::format("client: \"%p", client()));
    if (!clientDebugString().isEmpty()) {
        stringBuilder.append(' ');
        stringBuilder.append(clientDebugString());
    }
    stringBuilder.append("\", type: \"");
    stringBuilder.append(typeAsDebugString(type()));
    stringBuilder.append('"');
    if (m_id.scopeContainer)
        stringBuilder.append(String::format(", scope: \"%p,%d\"", m_id.scopeContainer, m_id.scopeId));
}

#endif

} // namespace blink
<commit_msg>DEBUG_STRING helper macro for DisplayItem::typeAsDebugString()<commit_after>// Copyright 2014 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

#include "config.h"
#include "platform/graphics/paint/DisplayItem.h"

namespace blink {

#ifndef NDEBUG

static WTF::String paintPhaseAsDebugString(int paintPhase)
{
    // Must be kept in sync with PaintPhase.
    switch (paintPhase) {
    case 0: return "PaintPhaseBlockBackground";
    case 1: return "PaintPhaseChildBlockBackground";
    case 2: return "PaintPhaseChildBlockBackgrounds";
    case 3: return "PaintPhaseFloat";
    case 4: return "PaintPhaseForeground";
    case 5: return "PaintPhaseOutline";
    case 6: return "PaintPhaseChildOutlines";
    case 7: return "PaintPhaseSelfOutline";
    case 8: return "PaintPhaseSelection";
    case 9: return "PaintPhaseCollapsedTableBorders";
    case 10: return "PaintPhaseTextClip";
    case 11: return "PaintPhaseMask";
    case DisplayItem::PaintPhaseMax: return "PaintPhaseClippingMask";
    default:
        ASSERT_NOT_REACHED();
        return "Unknown";
    }
}

#define PAINT_PHASE_BASED_DEBUG_STRINGS(Category) \
    if (type >= DisplayItem::Category##PaintPhaseFirst && type <= DisplayItem::Category##PaintPhaseLast) \
        return #Category + paintPhaseAsDebugString(type - DisplayItem::Category##PaintPhaseFirst);

#define DEBUG_STRING_CASE(DisplayItemName) \
    case DisplayItem::DisplayItemName: return #DisplayItemName

#define DEFAULT_CASE default: ASSERT_NOT_REACHED(); return "Unknown"

static WTF::String specialDrawingTypeAsDebugString(DisplayItem::Type type)
{
    switch (type) {
        DEBUG_STRING_CASE(BoxDecorationBackground);
        DEBUG_STRING_CASE(Caret);
        DEBUG_STRING_CASE(ColumnRules);
        DEBUG_STRING_CASE(DebugRedFill);
        DEBUG_STRING_CASE(DragImage);
        DEBUG_STRING_CASE(SVGImage);
        DEBUG_STRING_CASE(LinkHighlight);
        DEBUG_STRING_CASE(PageOverlay);
        DEBUG_STRING_CASE(PageWidgetDelegateBackgroundFallback);
        DEBUG_STRING_CASE(PopupContainerBorder);
        DEBUG_STRING_CASE(PopupListBoxBackground);
        DEBUG_STRING_CASE(PopupListBoxRow);
        DEBUG_STRING_CASE(Resizer);
        DEBUG_STRING_CASE(SVGClip);
        DEBUG_STRING_CASE(SVGFilter);
        DEBUG_STRING_CASE(SVGMask);
        DEBUG_STRING_CASE(ScrollbarBackButtonEnd);
        DEBUG_STRING_CASE(ScrollbarBackButtonStart);
        DEBUG_STRING_CASE(ScrollbarBackground);
        DEBUG_STRING_CASE(ScrollbarBackTrack);
        DEBUG_STRING_CASE(ScrollbarCorner);
        DEBUG_STRING_CASE(ScrollbarForwardButtonEnd);
        DEBUG_STRING_CASE(ScrollbarForwardButtonStart);
        DEBUG_STRING_CASE(ScrollbarForwardTrack);
        DEBUG_STRING_CASE(ScrollbarHorizontal);
        DEBUG_STRING_CASE(ScrollbarThumb);
        DEBUG_STRING_CASE(ScrollbarTickmarks);
        DEBUG_STRING_CASE(ScrollbarTrackBackground);
        DEBUG_STRING_CASE(ScrollbarVertical);
        DEBUG_STRING_CASE(SelectionGap);
        DEBUG_STRING_CASE(SelectionTint);
        DEBUG_STRING_CASE(TableCellBackgroundFromSelfPaintingRow);
        DEBUG_STRING_CASE(VideoBitmap);
        DEBUG_STRING_CASE(WebPlugin);
        DEFAULT_CASE;
    }
}

static WTF::String drawingTypeAsDebugString(DisplayItem::Type type)
{
    PAINT_PHASE_BASED_DEBUG_STRINGS(Drawing);
    return "Drawing" + specialDrawingTypeAsDebugString(type);
}

static WTF::String clipTypeAsDebugString(DisplayItem::Type type)
{
    PAINT_PHASE_BASED_DEBUG_STRINGS(ClipBox);
    PAINT_PHASE_BASED_DEBUG_STRINGS(ClipColumnBounds);
    PAINT_PHASE_BASED_DEBUG_STRINGS(ClipLayerFragment);

    switch (type) {
        DEBUG_STRING_CASE(ClipFileUploadControlRect);
        DEBUG_STRING_CASE(ClipFrameToVisibleContentRect);
        DEBUG_STRING_CASE(ClipFrameScrollbars);
        DEBUG_STRING_CASE(ClipLayerBackground);
        DEBUG_STRING_CASE(ClipLayerColumnBounds);
        DEBUG_STRING_CASE(ClipLayerFilter);
        DEBUG_STRING_CASE(ClipLayerForeground);
        DEBUG_STRING_CASE(ClipLayerParent);
        DEBUG_STRING_CASE(ClipLayerOverflowControls);
        DEBUG_STRING_CASE(ClipNodeImage);
        DEBUG_STRING_CASE(ClipPopupListBoxFrame);
        DEBUG_STRING_CASE(ClipSelectionImage);
        DEBUG_STRING_CASE(PageWidgetDelegateClip);
        DEBUG_STRING_CASE(TransparencyClip);
        DEFAULT_CASE;
    }
}

static String transform3DTypeAsDebugString(DisplayItem::Type type)
{
    switch (type) {
        DEBUG_STRING_CASE(Transform3DElementTransform);
        DEFAULT_CASE;
    }
}

WTF::String DisplayItem::typeAsDebugString(Type type)
{
    if (isDrawingType(type))
        return drawingTypeAsDebugString(type);
    if (isCachedType(type))
        return "Cached" + drawingTypeAsDebugString(cachedTypeToDrawingType(type));
    if (isClipType(type))
        return clipTypeAsDebugString(type);
    if (isEndClipType(type))
        return "End" + clipTypeAsDebugString(endClipTypeToClipType(type));

    PAINT_PHASE_BASED_DEBUG_STRINGS(FloatClip);
    if (isEndFloatClipType(type))
        return "End" + typeAsDebugString(endFloatClipTypeToFloatClipType(type));

    PAINT_PHASE_BASED_DEBUG_STRINGS(Scroll);
    if (isEndScrollType(type))
        return "End" + typeAsDebugString(endScrollTypeToScrollType(type));

    if (isTransform3DType(type))
        return transform3DTypeAsDebugString(type);
    if (isEndTransform3DType(type))
        return "End" + transform3DTypeAsDebugString(endTransform3DTypeToTransform3DType(type));

    PAINT_PHASE_BASED_DEBUG_STRINGS(SubtreeCached);
    PAINT_PHASE_BASED_DEBUG_STRINGS(BeginSubtree);
    PAINT_PHASE_BASED_DEBUG_STRINGS(EndSubtree);

    switch (type) {
        DEBUG_STRING_CASE(BeginFilter);
        DEBUG_STRING_CASE(EndFilter);
        DEBUG_STRING_CASE(BeginCompositing);
        DEBUG_STRING_CASE(EndCompositing);
        DEBUG_STRING_CASE(BeginTransform);
        DEBUG_STRING_CASE(EndTransform);
        DEBUG_STRING_CASE(BeginClipPath);
        DEBUG_STRING_CASE(EndClipPath);
        DEFAULT_CASE;
    }
}

WTF::String DisplayItem::asDebugString() const
{
    WTF::StringBuilder stringBuilder;
    stringBuilder.append('{');
    dumpPropertiesAsDebugString(stringBuilder);
    stringBuilder.append('}');
    return stringBuilder.toString();
}

void DisplayItem::dumpPropertiesAsDebugString(WTF::StringBuilder& stringBuilder) const
{
    stringBuilder.append(String::format("client: \"%p", client()));
    if (!clientDebugString().isEmpty()) {
        stringBuilder.append(' ');
        stringBuilder.append(clientDebugString());
    }
    stringBuilder.append("\", type: \"");
    stringBuilder.append(typeAsDebugString(type()));
    stringBuilder.append('"');
    if (m_id.scopeContainer)
        stringBuilder.append(String::format(", scope: \"%p,%d\"", m_id.scopeContainer, m_id.scopeId));
}

#endif

} // namespace blink
<|endoftext|>


<commit_before>/**
 * This file is part of TelepathyQt4
 *
 * @copyright Copyright (C) 2011 Collabora Ltd. <http://www.collabora.co.uk/>
 * @copyright Copyright (C) 2011 Nokia Corporation
 * @license LGPL 2.1
 *
 * 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 the Free Software
 * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA  02110-1301  USA
 */

#include "TelepathyQt4/fake-handler-manager-internal.h"

#include "TelepathyQt4/_gen/fake-handler-manager-internal.moc.hpp"

#include <TelepathyQt4/Channel>

namespace Tp
{

FakeHandler::FakeHandler(const QDBusConnection &bus)
    : QObject(),
      mBus(bus)
{
}

FakeHandler::~FakeHandler()
{
}

ObjectPathList FakeHandler::handledChannels() const
{
    ObjectPathList ret;
    foreach (const Channel *channel, mChannels) {
        ret << QDBusObjectPath(channel->objectPath());
    }
    return ret;
}

void FakeHandler::registerChannel(const ChannelPtr &channel)
{
    if (mChannels.contains(channel.data())) {
        return;
    }

    mChannels.insert(channel.data());
    connect(channel.data(),
            SIGNAL(invalidated(Tp::DBusProxy*,QString,QString)),
            SLOT(onChannelInvalidated(Tp::DBusProxy*)));
    connect(channel.data(),
            SIGNAL(destroyed(QObject*)),
            SLOT(onChannelDestroyed(QObject*)));
}

void FakeHandler::onChannelInvalidated(DBusProxy *channel)
{
    disconnect(channel, SIGNAL(destroyed(QObject*)), this, SLOT(onChannelDestroyed(QObject*)));
    onChannelDestroyed(channel);
}

void FakeHandler::onChannelDestroyed(QObject *channel)
{
    Q_ASSERT(mChannels.contains((Channel*) channel));

    mChannels.remove((Channel*) channel);
    if (mChannels.isEmpty()) {
        // emit invalidated here instead of relying on QObject::destroyed as FakeHandlerManager
        // may reuse this fake handler if FakeHandlerManager::registerChannel is called before the
        // slot from QObject::destroyed is invoked (deleteLater()).
        emit invalidated(this);
        deleteLater();
    }
}

FakeHandlerManager *FakeHandlerManager::mInstance = 0;

FakeHandlerManager *FakeHandlerManager::instance()
{
    if (!mInstance) {
        mInstance = new FakeHandlerManager();
    }
    return mInstance;
}

FakeHandlerManager::FakeHandlerManager()
    : QObject()
{
}

FakeHandlerManager::~FakeHandlerManager()
{
    mInstance = 0;
}

ObjectPathList FakeHandlerManager::handledChannels(const QDBusConnection &bus) const
{
    QPair<QString, QString> busUniqueId(bus.name(), bus.baseService());
    if (mFakeHandlers.contains(busUniqueId)) {
        FakeHandler *fakeHandler = mFakeHandlers.value(busUniqueId);
        return fakeHandler->handledChannels();
    }
    return ObjectPathList();
}

void FakeHandlerManager::registerClientRegistrar(const ClientRegistrarPtr &cr)
{
    QDBusConnection bus(cr->dbusConnection());
    QPair<QString, QString> busUniqueId(bus.name(), bus.baseService());
    // keep one registrar around per bus so at least the handlers registered by it will be
    // around until all channels on that bus gets invalidated/destroyed
    if (!mClientRegistrars.contains(busUniqueId)) {
        mClientRegistrars.insert(busUniqueId, cr);
    }
}

void FakeHandlerManager::registerChannels(const QList<ChannelPtr> &channels)
{
    foreach (const ChannelPtr &channel, channels) {
        QDBusConnection bus(channel->dbusConnection());
        QPair<QString, QString> busUniqueId(bus.name(), bus.baseService());
        FakeHandler *fakeHandler = mFakeHandlers.value(busUniqueId);
        if (!fakeHandler) {
            fakeHandler = new FakeHandler(bus);
            mFakeHandlers.insert(busUniqueId, fakeHandler);
            connect(fakeHandler,
                    SIGNAL(invalidated(Tp::FakeHandler*)),
                    SLOT(onFakeHandlerInvalidated(Tp::FakeHandler*)));
        }
        fakeHandler->registerChannel(channel);
    }
}

void FakeHandlerManager::onFakeHandlerInvalidated(FakeHandler *fakeHandler)
{
    QDBusConnection bus(fakeHandler->dbusConnection());
    QPair<QString, QString> busUniqueId(bus.name(), bus.baseService());
    mFakeHandlers.remove(busUniqueId);

    // all channels for the bus represented by busUniqueId were already destroyed/invalidated,
    // we can now free the CR (thus the handlers registered by it) registered for that bus
    mClientRegistrars.remove(busUniqueId);

    if (mFakeHandlers.isEmpty()) {
        // set mInstance to 0 here as we don't want instance() to return a already
        // deleted instance
        mInstance = 0;
        deleteLater();
    }
}

}
<commit_msg>FakeHandlerManager: Do not use C-style casts.<commit_after>/**
 * This file is part of TelepathyQt4
 *
 * @copyright Copyright (C) 2011 Collabora Ltd. <http://www.collabora.co.uk/>
 * @copyright Copyright (C) 2011 Nokia Corporation
 * @license LGPL 2.1
 *
 * 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 the Free Software
 * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA  02110-1301  USA
 */

#include "TelepathyQt4/fake-handler-manager-internal.h"

#include "TelepathyQt4/_gen/fake-handler-manager-internal.moc.hpp"

#include <TelepathyQt4/Channel>

namespace Tp
{

FakeHandler::FakeHandler(const QDBusConnection &bus)
    : QObject(),
      mBus(bus)
{
}

FakeHandler::~FakeHandler()
{
}

ObjectPathList FakeHandler::handledChannels() const
{
    ObjectPathList ret;
    foreach (const Channel *channel, mChannels) {
        ret << QDBusObjectPath(channel->objectPath());
    }
    return ret;
}

void FakeHandler::registerChannel(const ChannelPtr &channel)
{
    if (mChannels.contains(channel.data())) {
        return;
    }

    mChannels.insert(channel.data());
    connect(channel.data(),
            SIGNAL(invalidated(Tp::DBusProxy*,QString,QString)),
            SLOT(onChannelInvalidated(Tp::DBusProxy*)));
    connect(channel.data(),
            SIGNAL(destroyed(QObject*)),
            SLOT(onChannelDestroyed(QObject*)));
}

void FakeHandler::onChannelInvalidated(DBusProxy *channel)
{
    disconnect(channel, SIGNAL(destroyed(QObject*)), this, SLOT(onChannelDestroyed(QObject*)));
    onChannelDestroyed(channel);
}

void FakeHandler::onChannelDestroyed(QObject *obj)
{
    Channel *channel = reinterpret_cast<Channel*>(obj);

    Q_ASSERT(mChannels.contains(channel));

    mChannels.remove(channel);

    if (mChannels.isEmpty()) {
        // emit invalidated here instead of relying on QObject::destroyed as FakeHandlerManager
        // may reuse this fake handler if FakeHandlerManager::registerChannel is called before the
        // slot from QObject::destroyed is invoked (deleteLater()).
        emit invalidated(this);
        deleteLater();
    }
}

FakeHandlerManager *FakeHandlerManager::mInstance = 0;

FakeHandlerManager *FakeHandlerManager::instance()
{
    if (!mInstance) {
        mInstance = new FakeHandlerManager();
    }
    return mInstance;
}

FakeHandlerManager::FakeHandlerManager()
    : QObject()
{
}

FakeHandlerManager::~FakeHandlerManager()
{
    mInstance = 0;
}

ObjectPathList FakeHandlerManager::handledChannels(const QDBusConnection &bus) const
{
    QPair<QString, QString> busUniqueId(bus.name(), bus.baseService());
    if (mFakeHandlers.contains(busUniqueId)) {
        FakeHandler *fakeHandler = mFakeHandlers.value(busUniqueId);
        return fakeHandler->handledChannels();
    }
    return ObjectPathList();
}

void FakeHandlerManager::registerClientRegistrar(const ClientRegistrarPtr &cr)
{
    QDBusConnection bus(cr->dbusConnection());
    QPair<QString, QString> busUniqueId(bus.name(), bus.baseService());
    // keep one registrar around per bus so at least the handlers registered by it will be
    // around until all channels on that bus gets invalidated/destroyed
    if (!mClientRegistrars.contains(busUniqueId)) {
        mClientRegistrars.insert(busUniqueId, cr);
    }
}

void FakeHandlerManager::registerChannels(const QList<ChannelPtr> &channels)
{
    foreach (const ChannelPtr &channel, channels) {
        QDBusConnection bus(channel->dbusConnection());
        QPair<QString, QString> busUniqueId(bus.name(), bus.baseService());
        FakeHandler *fakeHandler = mFakeHandlers.value(busUniqueId);
        if (!fakeHandler) {
            fakeHandler = new FakeHandler(bus);
            mFakeHandlers.insert(busUniqueId, fakeHandler);
            connect(fakeHandler,
                    SIGNAL(invalidated(Tp::FakeHandler*)),
                    SLOT(onFakeHandlerInvalidated(Tp::FakeHandler*)));
        }
        fakeHandler->registerChannel(channel);
    }
}

void FakeHandlerManager::onFakeHandlerInvalidated(FakeHandler *fakeHandler)
{
    QDBusConnection bus(fakeHandler->dbusConnection());
    QPair<QString, QString> busUniqueId(bus.name(), bus.baseService());
    mFakeHandlers.remove(busUniqueId);

    // all channels for the bus represented by busUniqueId were already destroyed/invalidated,
    // we can now free the CR (thus the handlers registered by it) registered for that bus
    mClientRegistrars.remove(busUniqueId);

    if (mFakeHandlers.isEmpty()) {
        // set mInstance to 0 here as we don't want instance() to return a already
        // deleted instance
        mInstance = 0;
        deleteLater();
    }
}

}
<|endoftext|>


<commit_before>#include "render/hat_action_renderer.h"
#include "platform/auto_id.h"
#include "core/i_inventory_component.h"
#include "core/player_controller_component.h"
namespace render{

    glm::vec4 const ColorRepo::mDefaultColor = glm::vec4(1,1,1,1);

    ColorRepo::ColorRepo()
        : Repository<glm::vec4>( mDefaultColor )
    {
        int32_t i=0;
        mElements.insert(i,new glm::vec4(0.8,0.0,0.0,1));++i;
        mElements.insert(i,new glm::vec4(0.0,0.7,0.0,1));++i;
        mElements.insert(i,new glm::vec4(0.0,0.0,0.8,1));++i;
        mElements.insert(i,new glm::vec4(0.9,0.9,0.0,1));++i;
        mElements.insert(i,new glm::vec4(0.8,0.0,0.8,1));++i;
        mElements.insert(i,new glm::vec4(0.0,0.8,0.8,1));++i;
        mElements.insert(i,new glm::vec4(0.8,0.8,0.8,1));++i;
        mElements.insert(i,new glm::vec4(1.0,0.6,0.0,1));++i;
        mElements.insert(i,new glm::vec4(0.5,0.8,0.5,1));++i;
        mElements.insert(i,new glm::vec4(0.6,0.0,1.0,1));++i;
        mElements.insert(i,new glm::vec4(0.2,0.4,0.8,1));++i;
    }

    HatActionRenderer::HatActionRenderer(int32_t Id)
        : ActionRenderer(Id)
    {
        mHatId=AutoId("hat");
    }

    void HatActionRenderer::Init(const Actor& actor)
    {
        Opt<Weapon> weapon=actor.Get<IInventoryComponent>()->GetSelectedWeapon();
        if (!weapon.IsValid())
        {
            return;
        }
        SpriteCollection const& Sprites=mRenderableRepo(actor.GetId());
        Sprite const& Spr=Sprites(mHatId);
        if( Spr.IsValid() )
        {
            mSecsToEnd=Spr.GetSecsToEnd();
        }
    }

    void HatActionRenderer::FillRenderableSprites(const Actor& actor, RenderableSprites_t& renderableSprites)
    {
        SpriteCollection const& Sprites=mRenderableRepo(actor.GetId());
        Sprite const& Spr=Sprites(mHatId);
        if( Spr.IsValid() )
        {
            SpritePhase const& Phase = Spr( (int32_t)GetState() );
            Opt<PlayerControllerComponent> playerCC=actor.Get<PlayerControllerComponent>();
            renderableSprites.push_back( RenderableSprite( &actor, mHatId, &Spr, &Phase, ColorRepo::Get()(playerCC->mControllerId) ) );
        }
    }

} // namespace render<commit_msg>F: some color tweak<commit_after>#include "render/hat_action_renderer.h"
#include "platform/auto_id.h"
#include "core/i_inventory_component.h"
#include "core/player_controller_component.h"
namespace render{

    glm::vec4 const ColorRepo::mDefaultColor = glm::vec4(1,1,1,1);

    ColorRepo::ColorRepo()
        : Repository<glm::vec4>( mDefaultColor )
    {
        int32_t i=0;
        mElements.insert(i,new glm::vec4(0.8,0.0,0.0,1));++i;
        mElements.insert(i,new glm::vec4(0.0,0.8,0.8,1));++i;
        mElements.insert(i,new glm::vec4(0.9,0.9,0.0,1));++i;
        mElements.insert(i,new glm::vec4(0.0,0.7,0.0,1));++i;
        mElements.insert(i,new glm::vec4(0.8,0.0,0.8,1));++i;
        mElements.insert(i,new glm::vec4(0.3,0.3,0.3,1));++i;
        mElements.insert(i,new glm::vec4(0.95,0.95,0.95,1));++i;
        mElements.insert(i,new glm::vec4(1.0,0.6,0.0,1));++i;
        mElements.insert(i,new glm::vec4(0.5,0.8,0.5,1));++i;
        mElements.insert(i,new glm::vec4(0.6,0.0,1.0,1));++i;
        mElements.insert(i,new glm::vec4(0.2,0.4,0.8,1));++i;
    }

    HatActionRenderer::HatActionRenderer(int32_t Id)
        : ActionRenderer(Id)
    {
        mHatId=AutoId("hat");
    }

    void HatActionRenderer::Init(const Actor& actor)
    {
        Opt<Weapon> weapon=actor.Get<IInventoryComponent>()->GetSelectedWeapon();
        if (!weapon.IsValid())
        {
            return;
        }
        SpriteCollection const& Sprites=mRenderableRepo(actor.GetId());
        Sprite const& Spr=Sprites(mHatId);
        if( Spr.IsValid() )
        {
            mSecsToEnd=Spr.GetSecsToEnd();
        }
    }

    void HatActionRenderer::FillRenderableSprites(const Actor& actor, RenderableSprites_t& renderableSprites)
    {
        SpriteCollection const& Sprites=mRenderableRepo(actor.GetId());
        Sprite const& Spr=Sprites(mHatId);
        if( Spr.IsValid() )
        {
            SpritePhase const& Phase = Spr( (int32_t)GetState() );
            Opt<PlayerControllerComponent> playerCC=actor.Get<PlayerControllerComponent>();
            renderableSprites.push_back( RenderableSprite( &actor, mHatId, &Spr, &Phase, ColorRepo::Get()(playerCC->mControllerId) ) );
        }
    }

} // namespace render<|endoftext|>