<commit_before>
#include <iostream>

//GlEW, before GLFW

#define GLEW_STATIC
#include <GL/glew.h>

// GLFW
#include <GLFW/glfw3.h>
// Should make it cross platform

// Window dimensions
const GLuint WIDTH = 800, HEIGHT = 600;

void KeyCallback(GLFWwindow* window, int key, int scancode, int action, int mode)
{

	if (key == GLFW_KEY_ESCAPE && action == GLFW_PRESS)
		glfwSetWindowShouldClose(window, GL_TRUE);
}

// Shaders
const GLchar* vertexShaderSource =
	"#version 330 core\n"
	"layout (location = 0) in vec3 position;\n"
	"void main()\n"
	"{\n"
	"gl_Position = vec4(position.x, position.y, position.z, 1.0);\n"
	"}\0";

const GLchar* fragmentShaderSource =
	"#version 330 core\n"
	"out vec4 color;\n"
	"void main()\n"
	"{\n"
	"	color = vec4(1.0f, 0.5f, 0.2f, 1.0f);\n"
	"}\n";

void	InitShaders(GLuint &vertexShader, GLuint &fragmentShader)
{
	vertexShader = glCreateShader(GL_VERTEX_SHADER);
	glShaderSource(vertexShader, 1, &vertexShaderSource, NULL); // 1 string, attach source code
	glCompileShader(vertexShader);

	// Check for compile errors
	GLint vertexShaderSuccess;
	GLchar infoLog[512];
	glGetShaderiv(vertexShader, GL_COMPILE_STATUS, &vertexShaderSuccess); // Check if shader compilation successful
	if (!vertexShaderSuccess)
	{
		glGetShaderInfoLog(vertexShader, 512, NULL, infoLog);
		std::cout << "ERROR::SHADER::VERTEX::COMPILATION_FAILED\n" << infoLog << std::endl;
	}

	// Compile fragment shader
	fragmentShader = glCreateShader(GL_FRAGMENT_SHADER);
	glShaderSource(fragmentShader, 1, &fragmentShaderSource, NULL);
	glCompileShader(fragmentShader);

	// Check for compile errors
	GLint fragmentShaderSuccess;
	glGetShaderiv(fragmentShader, GL_COMPILE_STATUS, &fragmentShaderSuccess); // Check if shader compilation successful
	if (!fragmentShaderSuccess)
	{
		glGetShaderInfoLog(fragmentShader, 512, NULL, infoLog);
		std::cout << "ERROR::SHADER::FRAGMENT::COMPILATION_FAILED\n" << infoLog << std::endl;
	}
}

void InitShaderProgram(GLuint &shaderProgram, GLuint vertexShader, GLuint fragmentShader)
{
	shaderProgram = glCreateProgram();
	glAttachShader(shaderProgram, vertexShader);
	glAttachShader(shaderProgram, fragmentShader);
	glLinkProgram(shaderProgram);

	// Check for link errors
	GLint shaderProgramSuccess;
	GLchar infoLog[512];
	glGetProgramiv(shaderProgram, GL_LINK_STATUS, &shaderProgramSuccess);
	if (!shaderProgramSuccess)
	{
		glGetProgramInfoLog(shaderProgram, 512, NULL, infoLog);
		std::cout << "ERROR::SHADEPROGRAM::LINKING_FAILED\n" << infoLog << std::endl;
	}
}

void DrawPolygon(std::string type, const GLuint &shaderProgram, const GLuint &VAO, const bool &wireFramed)
{
	glUseProgram(shaderProgram);
	glBindVertexArray(VAO);

	if (wireFramed)
	{
		glPolygonMode(GL_FRONT_AND_BACK, GL_LINE);
	}
	else
	{
		glPolygonMode(GL_FRONT_AND_BACK, GL_FILL);
	}

	if (type == "triangle")
	{
		glDrawArrays(GL_TRIANGLES, 0, 3); // Arg1 0 start index of vertex array
										  // Arg2 3 vertices are to be drawn
	}
	else if (type == "rectangle")
	{
		glDrawElements(GL_TRIANGLES, 6, GL_UNSIGNED_INT, 0); // Arg2 6 indices
															 // Arg4 0 offset in EBO
	}
	else
	{
		std::cout << "Wrong type of polygon in call to DrawPolygon(). " << std::endl;
	}

	glBindVertexArray(0);
}

bool InitGlfwAndGlew(GLFWwindow* &window)
{
	std::cout << "Starting GLFW context, OpenGL 3.3" << std::endl;
	// Init GLFW and set all its required options
	glfwInit();
	glfwWindowHint(GLFW_CONTEXT_VERSION_MAJOR, 3); // Use OpenGl 3.3
	glfwWindowHint(GLFW_CONTEXT_VERSION_MINOR, 3);
	glfwWindowHint(GLFW_OPENGL_PROFILE, GLFW_OPENGL_CORE_PROFILE); // Don't use old functionality
	//glfwWindowHint(GLFW_OPENGL_FORWARD_COMPAT, GL_TRUE); // Necessary for Mac OSX

	// Init GLFWwindow object
	window = glfwCreateWindow(WIDTH, HEIGHT, "LearnOpenGL", nullptr, nullptr);
	if (window == nullptr)
	{
		std::cout << "Failed to create GLFW window" << std::endl;
		glfwTerminate();
		return false;
	}
	glfwMakeContextCurrent(window);
	glfwSetKeyCallback(window, KeyCallback);

	// Init GLEW to setup function pointers for OpenGl

	glewExperimental = GL_TRUE; // Use core profile modern OpenGL techniques
	if (glewInit() != GLEW_OK)
	{
		std::cout << "Failed to init GLEW" << std::endl;
		return false;
	}

	// Define width and height for OpenGL (viewport dimensions)
	// OpenGL uses this data to map from processed coordinates in range (-1,1) to (0,800) and (0,600)
	int width, height;
	glfwGetFramebufferSize(window, &width, &height); // Framebuffer size in pixels instead of screen coordinates
	glViewport(0, 0, width, height); // (0, 0) = Southwest corner of window

	return true;
}

/*void SetPolygonData(GLfloat (&vertices)[12], GLfloat (&indices)[6])
{
	// Triangle vertices as normalized device coordinates
	vertices[] =
	{
		0.5f, 0.5f, 0.0f,
		0.5f, -0.5f, 0.0f,
		-0.5f, -0.5f, 0.0f,
		-0.5f, 0.5f, 0.0f
	};

	indices[6] =
	{
		0, 1, 3,	// First triangle
		1, 2, 3		// Second triangle
	};
}*/

int main()
{
	GLFWwindow* window;
	bool initGlfwGlewSuccess;
	initGlfwGlewSuccess = InitGlfwAndGlew(window);
	if (!initGlfwGlewSuccess) { return -1; }

	//GLfloat vertices[12];
	//GLuint indices[6];
	//SetPolygonData(vertices, indices);

	// Triangle vertices as normalized device coordinates
	GLfloat vertices[] =
	{
		0.5f, 0.5f, 0.0f,
		0.5f, -0.5f, 0.0f,
		-0.5f, -0.5f, 0.0f,
		-0.5f, 0.5f, 0.0f
	};

	GLuint indices[6] =
	{
		0, 1, 3,	// First triangle
		1, 2, 3		// Second triangle
	};

	// Init triangle VBO to store vertices in GPU memory, rectangle EBO to index vertices
	// and VAO
	GLuint VBO, VAO, EBO;
	glGenBuffers(1, &VBO);
	glGenBuffers(1, &EBO);
	glGenVertexArrays(1, &VAO);
	glBindVertexArray(VAO);

	glBindBuffer(GL_ARRAY_BUFFER, VBO);
	glBufferData(GL_ARRAY_BUFFER, sizeof(vertices), vertices, GL_STATIC_DRAW); // Copies vertex data to GPU
																			   // GL_STATIC_DRAW since the data most likely
																			   // will not change
																			   // The VBO is stored in VAO
	glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, EBO); // Stored in VAO
	glBufferData(GL_ELEMENT_ARRAY_BUFFER, sizeof(indices), indices, GL_STATIC_DRAW);

	// Specify how vertex data is to be interpreted
	glVertexAttribPointer(0, 3, GL_FLOAT, GL_FALSE, 3 * sizeof(GLfloat), (GLvoid*)0); // Arg1 0 since position is layout 0
																					  // Arg2 3 since position data vec3
																					  // Arg4 false since already normalized values
																					  // Arg5 Space between attribute sets
																					  // Arg6 No data offset in buffer
	glEnableVertexAttribArray(0); // Vertex attribute location is 0
	glBindVertexArray(0); // Unbind vertex array to not risk misconfiguring later on

	// Compile shaders
	GLuint vertexShader, fragmentShader;
	InitShaders(vertexShader, fragmentShader);

	// Attach shaders and link shader program
	GLuint shaderProgram;
	InitShaderProgram(shaderProgram, vertexShader, fragmentShader);
	glUseProgram(shaderProgram);

	glDeleteShader(vertexShader);
	glDeleteShader(fragmentShader);

	// Game loop
	while (!glfwWindowShouldClose(window))
	{
		glfwPollEvents(); // Check if events have been activated

		// Rendering commands
		glClearColor(0.2f, 0.5f, 0.3f, 1.0f);
		glClear(GL_COLOR_BUFFER_BIT);

		bool wireFramed = true;
		DrawPolygon("rectangle", shaderProgram, VAO, wireFramed);

		glfwSwapBuffers(window);
	}

	// Deallocate resources
	glDeleteVertexArrays(1, &VAO);
	glDeleteBuffers(1, &VBO);
	glDeleteBuffers(1, &EBO);

	glfwTerminate(); // Clear allocated resources
	return 0;
}<commit_msg>Will not move out vertex data initialization from main() yet.<commit_after>
#include <iostream>

//GlEW, before GLFW

#define GLEW_STATIC
#include <GL/glew.h>

// GLFW
#include <GLFW/glfw3.h>
// Should make it cross platform

// Window dimensions
const GLuint WIDTH = 800, HEIGHT = 600;

void KeyCallback(GLFWwindow* window, int key, int scancode, int action, int mode)
{

	if (key == GLFW_KEY_ESCAPE && action == GLFW_PRESS)
		glfwSetWindowShouldClose(window, GL_TRUE);
}

// Shaders
const GLchar* vertexShaderSource =
	"#version 330 core\n"
	"layout (location = 0) in vec3 position;\n"
	"void main()\n"
	"{\n"
	"gl_Position = vec4(position.x, position.y, position.z, 1.0);\n"
	"}\0";

const GLchar* fragmentShaderSource =
	"#version 330 core\n"
	"out vec4 color;\n"
	"void main()\n"
	"{\n"
	"	color = vec4(1.0f, 0.5f, 0.2f, 1.0f);\n"
	"}\n";

void	InitShaders(GLuint &vertexShader, GLuint &fragmentShader)
{
	vertexShader = glCreateShader(GL_VERTEX_SHADER);
	glShaderSource(vertexShader, 1, &vertexShaderSource, NULL); // 1 string, attach source code
	glCompileShader(vertexShader);

	// Check for compile errors
	GLint vertexShaderSuccess;
	GLchar infoLog[512];
	glGetShaderiv(vertexShader, GL_COMPILE_STATUS, &vertexShaderSuccess); // Check if shader compilation successful
	if (!vertexShaderSuccess)
	{
		glGetShaderInfoLog(vertexShader, 512, NULL, infoLog);
		std::cout << "ERROR::SHADER::VERTEX::COMPILATION_FAILED\n" << infoLog << std::endl;
	}

	// Compile fragment shader
	fragmentShader = glCreateShader(GL_FRAGMENT_SHADER);
	glShaderSource(fragmentShader, 1, &fragmentShaderSource, NULL);
	glCompileShader(fragmentShader);

	// Check for compile errors
	GLint fragmentShaderSuccess;
	glGetShaderiv(fragmentShader, GL_COMPILE_STATUS, &fragmentShaderSuccess); // Check if shader compilation successful
	if (!fragmentShaderSuccess)
	{
		glGetShaderInfoLog(fragmentShader, 512, NULL, infoLog);
		std::cout << "ERROR::SHADER::FRAGMENT::COMPILATION_FAILED\n" << infoLog << std::endl;
	}
}

void InitShaderProgram(GLuint &shaderProgram, GLuint vertexShader, GLuint fragmentShader)
{
	shaderProgram = glCreateProgram();
	glAttachShader(shaderProgram, vertexShader);
	glAttachShader(shaderProgram, fragmentShader);
	glLinkProgram(shaderProgram);

	// Check for link errors
	GLint shaderProgramSuccess;
	GLchar infoLog[512];
	glGetProgramiv(shaderProgram, GL_LINK_STATUS, &shaderProgramSuccess);
	if (!shaderProgramSuccess)
	{
		glGetProgramInfoLog(shaderProgram, 512, NULL, infoLog);
		std::cout << "ERROR::SHADEPROGRAM::LINKING_FAILED\n" << infoLog << std::endl;
	}
}

void DrawPolygon(std::string type, const GLuint &shaderProgram, const GLuint &VAO, const bool &wireFramed)
{
	glUseProgram(shaderProgram);
	glBindVertexArray(VAO);

	if (wireFramed)
	{
		glPolygonMode(GL_FRONT_AND_BACK, GL_LINE);
	}
	else
	{
		glPolygonMode(GL_FRONT_AND_BACK, GL_FILL);
	}

	if (type == "triangle")
	{
		glDrawArrays(GL_TRIANGLES, 0, 3); // Arg1 0 start index of vertex array
										  // Arg2 3 vertices are to be drawn
	}
	else if (type == "rectangle")
	{
		glDrawElements(GL_TRIANGLES, 6, GL_UNSIGNED_INT, 0); // Arg2 6 indices
															 // Arg4 0 offset in EBO
	}
	else
	{
		std::cout << "Wrong type of polygon in call to DrawPolygon(). " << std::endl;
	}

	glBindVertexArray(0);
}

bool InitGlfwAndGlew(GLFWwindow* &window)
{
	std::cout << "Starting GLFW context, OpenGL 3.3" << std::endl;
	// Init GLFW and set all its required options
	glfwInit();
	glfwWindowHint(GLFW_CONTEXT_VERSION_MAJOR, 3); // Use OpenGl 3.3
	glfwWindowHint(GLFW_CONTEXT_VERSION_MINOR, 3);
	glfwWindowHint(GLFW_OPENGL_PROFILE, GLFW_OPENGL_CORE_PROFILE); // Don't use old functionality
	//glfwWindowHint(GLFW_OPENGL_FORWARD_COMPAT, GL_TRUE); // Necessary for Mac OSX

	// Init GLFWwindow object
	window = glfwCreateWindow(WIDTH, HEIGHT, "LearnOpenGL", nullptr, nullptr);
	if (window == nullptr)
	{
		std::cout << "Failed to create GLFW window" << std::endl;
		glfwTerminate();
		return false;
	}
	glfwMakeContextCurrent(window);
	glfwSetKeyCallback(window, KeyCallback);

	// Init GLEW to setup function pointers for OpenGl

	glewExperimental = GL_TRUE; // Use core profile modern OpenGL techniques
	if (glewInit() != GLEW_OK)
	{
		std::cout << "Failed to init GLEW" << std::endl;
		return false;
	}

	// Define width and height for OpenGL (viewport dimensions)
	// OpenGL uses this data to map from processed coordinates in range (-1,1) to (0,800) and (0,600)
	int width, height;
	glfwGetFramebufferSize(window, &width, &height); // Framebuffer size in pixels instead of screen coordinates
	glViewport(0, 0, width, height); // (0, 0) = Southwest corner of window

	return true;
}

int main()
{
	GLFWwindow* window;
	bool initGlfwGlewSuccess;
	initGlfwGlewSuccess = InitGlfwAndGlew(window);
	if (!initGlfwGlewSuccess) { return -1; }

	// Triangle vertices as normalized device coordinates
	GLfloat vertices[] =
	{
		0.5f, 0.5f, 0.0f,
		0.5f, -0.5f, 0.0f,
		-0.5f, -0.5f, 0.0f,
		-0.5f, 0.5f, 0.0f
	};

	GLuint indices[6] =
	{
		0, 1, 3,	// First triangle
		1, 2, 3		// Second triangle
	};

	// Init triangle VBO to store vertices in GPU memory, rectangle EBO to index vertices
	// and VAO to collect all states
	GLuint VBO, VAO, EBO;
	glGenBuffers(1, &VBO);
	glGenBuffers(1, &EBO);
	glGenVertexArrays(1, &VAO);
	glBindVertexArray(VAO);

	glBindBuffer(GL_ARRAY_BUFFER, VBO);
	glBufferData(GL_ARRAY_BUFFER, sizeof(vertices), vertices, GL_STATIC_DRAW); // Copies vertex data to GPU
																			   // GL_STATIC_DRAW since the data most likely
																			   // will not change
																			   // The VBO is stored in VAO
	glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, EBO); // Stored in VAO
	glBufferData(GL_ELEMENT_ARRAY_BUFFER, sizeof(indices), indices, GL_STATIC_DRAW);

	// Specify how vertex data is to be interpreted
	glVertexAttribPointer(0, 3, GL_FLOAT, GL_FALSE, 3 * sizeof(GLfloat), (GLvoid*)0); // Arg1 0 since position is layout 0
																					  // Arg2 3 since position data vec3
																					  // Arg4 false since already normalized values
																					  // Arg5 Space between attribute sets
																					  // Arg6 No data offset in buffer
	glEnableVertexAttribArray(0); // Vertex attribute location is 0
	glBindVertexArray(0); // Unbind vertex array to not risk misconfiguring later on

	// Compile shaders
	GLuint vertexShader, fragmentShader;
	InitShaders(vertexShader, fragmentShader);

	// Attach shaders and link shader program
	GLuint shaderProgram;
	InitShaderProgram(shaderProgram, vertexShader, fragmentShader);
	glUseProgram(shaderProgram);
	glDeleteShader(vertexShader);
	glDeleteShader(fragmentShader);

	// Game loop
	while (!glfwWindowShouldClose(window))
	{
		glfwPollEvents(); // Check if events have been activated

		// Rendering commands
		glClearColor(0.2f, 0.5f, 0.3f, 1.0f);
		glClear(GL_COLOR_BUFFER_BIT);

		bool wireFramed = true;
		DrawPolygon("rectangle", shaderProgram, VAO, wireFramed);

		glfwSwapBuffers(window);
	}

	// Deallocate resources
	glDeleteVertexArrays(1, &VAO);
	glDeleteBuffers(1, &VBO);
	glDeleteBuffers(1, &EBO);

	glfwTerminate(); // Clear allocated resources
	return 0;
}<|endoftext|>


<commit_before>#include "stdafx.h"

DECLARE_COMPONENT_VERSION("Windows 10 Media Control","1.0","Adds the ability for foobar2000 to interact with the Windows 10 media control overlay.");
VALIDATE_COMPONENT_FILENAME("foo_mediacontrol.dll");
<commit_msg>v1.0 release.<commit_after>#include "stdafx.h"

DECLARE_COMPONENT_VERSION("Windows 10 Media Controls","1.0","Adds the ability for foobar2000 to interact with the Windows 10 media control overlay.");
VALIDATE_COMPONENT_FILENAME("foo_mediacontrol.dll");
<|endoftext|>


<commit_before>/*************************************************************************
 *
 *  $RCSfile: scrollbar.cxx,v $
 *
 *  $Revision: 1.2 $
 *
 *  last change: $Author: kz $ $Date: 2003-12-11 12:30:16 $
 *
 *  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 FORMS_SOURCE_COMPONENT_SCROLLBAR_HXX
#include "scrollbar.hxx"
#endif

#ifndef _COMPHELPER_STREAMSECTION_HXX_
#include <comphelper/streamsection.hxx>
#endif

#ifndef INCLUDED_RTL_MATH_HXX
#include <rtl/math.hxx>
#endif

//--------------------------------------------------------------------------
extern "C" void SAL_CALL createRegistryInfo_OScrollBarModel()
{
    static ::frm::OMultiInstanceAutoRegistration< ::frm::OScrollBarModel >   aRegisterModel;
}

//........................................................................
namespace frm
{
//........................................................................

    using namespace ::com::sun::star::uno;
    using namespace ::com::sun::star::beans;
    using namespace ::com::sun::star::form;
    using namespace ::com::sun::star::awt;
    using namespace ::com::sun::star::lang;
    using namespace ::com::sun::star::util;
    using namespace ::com::sun::star::io;
    using namespace ::drafts::com::sun::star::form;

    //====================================================================
    //= helper
    //====================================================================
    //--------------------------------------------------------------------
    Any translateExternalDoubleToControlIntValue(
        const Reference< XValueBinding >& _rxBinding, const Reference< XPropertySet >& _rxProperties,
        const ::rtl::OUString& _rMinValueName, const ::rtl::OUString& _rMaxValueName )
    {
        OSL_PRECOND( _rxBinding.is(), "translateExternalDoubleToControlIntValue: no external binding!" );
        OSL_ENSURE( _rxProperties.is(), "translateExternalDoubleToControlIntValue: no aggregate!?" );

        sal_Int32 nControlValue( 0 );
        if ( _rxBinding.is() )
        {
            Any aExternalValue = _rxBinding->getValue( ::getCppuType( static_cast< double* >( NULL ) ) );
            double nExternalValue = 0;
            if ( aExternalValue >>= nExternalValue )
            {
                if ( ::rtl::math::isInf( nExternalValue ) )
                {

                    // set the minimum or maximum of the scroll values
                    ::rtl::OUString sLimitPropertyName = ::rtl::math::isSignBitSet( nExternalValue )
                        ? _rMinValueName : _rMaxValueName;
                    if ( _rxProperties.is() )
                        _rxProperties->getPropertyValue( sLimitPropertyName ) >>= nControlValue;
                }
                else
                {
                    nControlValue = (sal_Int32)::rtl::math::round( nExternalValue );
                }
            }
            else
            {
                if ( _rxProperties.is() )
                    _rxProperties->getPropertyValue( ::rtl::OUString( RTL_CONSTASCII_USTRINGPARAM( "ScrollValueMin" ) ) ) >>= nControlValue;
            }
        }

        return makeAny( nControlValue );
    }

    //--------------------------------------------------------------------
    Any translateControlIntToExternalDoubleValue( const Any& _rControlIntValue )
    {
        Any aExternalDoubleValue;
        sal_Int32 nScrollValue = 0;
        if ( _rControlIntValue >>= nScrollValue )
            aExternalDoubleValue <<= (double)nScrollValue;
        else
        {
            OSL_ENSURE( sal_False, "translateControlIntToExternalDoubleValue: no integer scroll value!" );
            // aExternalDoubleValue is void here, which is okay for this purpose ...
        }

        return aExternalDoubleValue;
    }

    //====================================================================
    //= OScrollBarModel
    //====================================================================
    //--------------------------------------------------------------------
    DBG_NAME( OScrollBarModel )
    //--------------------------------------------------------------------
    OScrollBarModel::OScrollBarModel( const Reference<XMultiServiceFactory>& _rxFactory )
        :OBoundControlModel( _rxFactory, VCL_CONTROLMODEL_SCROLLBAR, VCL_CONTROL_SCROLLBAR, sal_True, sal_True )
        ,m_nDefaultScrollValue( 0 )
    {
        DBG_CTOR( OScrollBarModel, NULL );

        m_nClassId = FormComponentType::SCROLLBAR;
        initValueProperty( PROPERTY_SCROLL_VALUE, PROPERTY_ID_SCROLL_VALUE );
    }

    //--------------------------------------------------------------------
    OScrollBarModel::OScrollBarModel( const OScrollBarModel* _pOriginal, const Reference< XMultiServiceFactory >& _rxFactory )
        :OBoundControlModel( _pOriginal, _rxFactory )
    {
        DBG_CTOR( OScrollBarModel, NULL );
        m_nDefaultScrollValue = _pOriginal->m_nDefaultScrollValue;
    }

    //--------------------------------------------------------------------
    OScrollBarModel::~OScrollBarModel( )
    {
        DBG_DTOR( OScrollBarModel, NULL );
    }

    //--------------------------------------------------------------------
    IMPLEMENT_SERVICE_REGISTRATION_1( OScrollBarModel, OControlModel, FRM_SUN_COMPONENT_SCROLLBAR )
        // note that we're passing OControlModel as "base class". This is because
        // OBoundControlModel, our real base class, claims to support the DataAwareControlModel
        // service, which isn't really true for us. We only derive from this class
        // to benefit from the functionality for binding to spreadsheet cells

    //------------------------------------------------------------------------------
    IMPLEMENT_DEFAULT_CLONING( OScrollBarModel )

    //------------------------------------------------------------------------------
    void SAL_CALL OScrollBarModel::disposing()
    {
        OBoundControlModel::disposing();
    }

    //--------------------------------------------------------------------
    Reference< XPropertySetInfo > SAL_CALL OScrollBarModel::getPropertySetInfo() throw(RuntimeException)
    {
        return Reference< XPropertySetInfo >( createPropertySetInfo( getInfoHelper() ) );
    }

    //--------------------------------------------------------------------
    cppu::IPropertyArrayHelper& OScrollBarModel::getInfoHelper()
    {
        return *const_cast< OScrollBarModel* >( this )->getArrayHelper();
    }

    //--------------------------------------------------------------------
    void OScrollBarModel::fillProperties( Sequence< Property >& _rProps, Sequence< Property >& _rAggregateProps ) const
    {
        FRM_BEGIN_PROP_HELPER( 6 )
            DECL_PROP2( CLASSID,              sal_Int16,       READONLY, TRANSIENT );
            DECL_PROP1( DEFAULT_SCROLL_VALUE, sal_Int32,       BOUND );
            DECL_PROP1( NAME,                 ::rtl::OUString, BOUND );
            DECL_PROP1( TABINDEX,             sal_Int16,       BOUND );
            DECL_PROP1( TAG,                  ::rtl::OUString, BOUND );
            DECL_PROP2( CONTROLSOURCEPROPERTY,::rtl::OUString, READONLY, TRANSIENT );
        FRM_END_PROP_HELPER();
    }

    //------------------------------------------------------------------------------
    void OScrollBarModel::getFastPropertyValue( Any& _rValue, sal_Int32 _nHandle ) const
    {
        switch ( _nHandle )
        {
            case PROPERTY_ID_DEFAULT_SCROLL_VALUE:
                _rValue <<= m_nDefaultScrollValue;
                break;

            default:
                OBoundControlModel::getFastPropertyValue( _rValue, _nHandle );
        }
    }

    //------------------------------------------------------------------------------
    void OScrollBarModel::setFastPropertyValue_NoBroadcast( sal_Int32 _nHandle, const Any& _rValue ) throw ( Exception )
    {
        switch ( _nHandle )
        {
            case PROPERTY_ID_DEFAULT_SCROLL_VALUE:
                OSL_VERIFY( _rValue >>= m_nDefaultScrollValue );
                resetNoBroadcast();
                break;

            default:
                OBoundControlModel::setFastPropertyValue_NoBroadcast( _nHandle, _rValue );
        }
    }

    //------------------------------------------------------------------------------
    sal_Bool OScrollBarModel::convertFastPropertyValue(
                Any& _rConvertedValue, Any& _rOldValue, sal_Int32 _nHandle, const Any& _rValue )
                throw ( IllegalArgumentException )
    {
        sal_Bool bModified( sal_False );
        switch ( _nHandle )
        {
            case PROPERTY_ID_DEFAULT_SCROLL_VALUE:
                bModified = tryPropertyValue( _rConvertedValue, _rOldValue, _rValue, m_nDefaultScrollValue );
                break;

            default:
                bModified = OBoundControlModel::convertFastPropertyValue( _rConvertedValue, _rOldValue, _nHandle, _rValue );
                break;
        }
        return bModified;
    }

    //--------------------------------------------------------------------
    Any OScrollBarModel::getPropertyDefaultByHandle( sal_Int32 _nHandle ) const
    {
        Any aReturn;

        switch ( _nHandle )
        {
        case PROPERTY_ID_DEFAULT_SCROLL_VALUE:
            aReturn <<= (sal_Int32)0;
            break;

        default:
            aReturn = OBoundControlModel::getPropertyDefaultByHandle( _nHandle );
            break;
        }

        return aReturn;
    }

    //------------------------------------------------------------------------------
    Any OScrollBarModel::translateDbColumnToControlValue( )
    {
        OSL_ENSURE( sal_False, "OScrollBarModel::commitControlValueToDbColumn: never to be called (we're not bound)!" );
        return Any();
    }

    //------------------------------------------------------------------------------
    sal_Bool OScrollBarModel::commitControlValueToDbColumn( bool _bPostReset )
    {
        OSL_ENSURE( sal_False, "OScrollBarModel::commitControlValueToDbColumn: never to be called (we're not bound)!" );
        return sal_True;
    }

    //------------------------------------------------------------------------------
    Any OScrollBarModel::getDefaultForReset() const
    {
        return makeAny( (sal_Int32)m_nDefaultScrollValue );
    }

    //--------------------------------------------------------------------
    ::rtl::OUString SAL_CALL OScrollBarModel::getServiceName() throw( RuntimeException )
    {
        return FRM_SUN_COMPONENT_SCROLLBAR;
    }

    //--------------------------------------------------------------------
    void SAL_CALL OScrollBarModel::write( const Reference< XObjectOutputStream >& _rxOutStream )
        throw( IOException, RuntimeException )
    {
        OBoundControlModel::write( _rxOutStream );
        ::osl::MutexGuard aGuard( m_aMutex );

        OStreamSection aSection( Reference< XDataOutputStream >( _rxOutStream, UNO_QUERY ) );

        // version
        _rxOutStream->writeShort( 0x0001 );

        // properties
        _rxOutStream << m_nDefaultScrollValue;
        writeHelpTextCompatibly( _rxOutStream );
    }

    //--------------------------------------------------------------------
    void SAL_CALL OScrollBarModel::read( const Reference< XObjectInputStream>& _rxInStream ) throw( IOException, RuntimeException )
    {
        OBoundControlModel::read( _rxInStream );
        ::osl::MutexGuard aGuard( m_aMutex );

        // version
        {
            OStreamSection aSection( Reference< XDataInputStream >( _rxInStream, UNO_QUERY ) );

            sal_uInt16 nVersion = _rxInStream->readShort();
            if ( nVersion == 0x0001 )
            {
                _rxInStream >> m_nDefaultScrollValue;
                readHelpTextCompatibly( _rxInStream );
            }
            else
                defaultCommonProperties();

            // here, everything in the stream section which is left will be skipped
        }
    }

    //--------------------------------------------------------------------
    Any OScrollBarModel::translateExternalValueToControlValue( )
    {
        return translateExternalDoubleToControlIntValue( m_xExternalBinding, m_xAggregateSet,
            ::rtl::OUString( RTL_CONSTASCII_USTRINGPARAM( "ScrollValueMin" ) ),
            ::rtl::OUString( RTL_CONSTASCII_USTRINGPARAM( "ScrollValueMax" ) ) );
    }

    //--------------------------------------------------------------------
    Any OScrollBarModel::translateControlValueToExternalValue( )
    {
        // by definition, the base class simply obtains the property value
        return translateControlIntToExternalDoubleValue( OBoundControlModel::translateControlValueToExternalValue() );
    }

    //--------------------------------------------------------------------
    sal_Bool OScrollBarModel::approveValueBinding( const Reference< XValueBinding >& _rxBinding )
    {
        OSL_PRECOND( _rxBinding.is(), "OScrollBarModel::approveValueBinding: invalid binding!" );

        // only strings are accepted for simplicity
        return  _rxBinding.is()
            &&  _rxBinding->supportsType( ::getCppuType( static_cast< double* >( NULL ) ) );
    }

//........................................................................
}   // namespace frm
//........................................................................
<commit_msg>INTEGRATION: CWS frmvalidation (1.2.26); FILE MERGED 2004/03/11 16:46:20 fs 1.2.26.1: mass checkin - #i25106# core for validating form controls via external XValidator instances - moved the services/interfaces related to binding form controls to external   value suppliers into css.form.binding (out of drafts.css.form/component)<commit_after>/*************************************************************************
 *
 *  $RCSfile: scrollbar.cxx,v $
 *
 *  $Revision: 1.3 $
 *
 *  last change: $Author: rt $ $Date: 2004-04-02 10:56:46 $
 *
 *  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 FORMS_SOURCE_COMPONENT_SCROLLBAR_HXX
#include "scrollbar.hxx"
#endif

#ifndef _COMPHELPER_STREAMSECTION_HXX_
#include <comphelper/streamsection.hxx>
#endif
#ifndef _COMPHELPER_BASIC_IO_HXX_
#include <comphelper/basicio.hxx>
#endif

#ifndef INCLUDED_RTL_MATH_HXX
#include <rtl/math.hxx>
#endif

//--------------------------------------------------------------------------
extern "C" void SAL_CALL createRegistryInfo_OScrollBarModel()
{
    static ::frm::OMultiInstanceAutoRegistration< ::frm::OScrollBarModel >   aRegisterModel;
}

//........................................................................
namespace frm
{
//........................................................................

    using namespace ::com::sun::star::uno;
    using namespace ::com::sun::star::beans;
    using namespace ::com::sun::star::form;
    using namespace ::com::sun::star::awt;
    using namespace ::com::sun::star::lang;
    using namespace ::com::sun::star::util;
    using namespace ::com::sun::star::io;
    using namespace ::com::sun::star::form::binding;

    //====================================================================
    //= helper
    //====================================================================
    //--------------------------------------------------------------------
    Any translateExternalDoubleToControlIntValue(
        const Reference< XValueBinding >& _rxBinding, const Reference< XPropertySet >& _rxProperties,
        const ::rtl::OUString& _rMinValueName, const ::rtl::OUString& _rMaxValueName )
    {
        OSL_PRECOND( _rxBinding.is(), "translateExternalDoubleToControlIntValue: no external binding!" );
        OSL_ENSURE( _rxProperties.is(), "translateExternalDoubleToControlIntValue: no aggregate!?" );

        sal_Int32 nControlValue( 0 );
        if ( _rxBinding.is() )
        {
            Any aExternalValue = _rxBinding->getValue( ::getCppuType( static_cast< double* >( NULL ) ) );
            double nExternalValue = 0;
            if ( aExternalValue >>= nExternalValue )
            {
                if ( ::rtl::math::isInf( nExternalValue ) )
                {

                    // set the minimum or maximum of the scroll values
                    ::rtl::OUString sLimitPropertyName = ::rtl::math::isSignBitSet( nExternalValue )
                        ? _rMinValueName : _rMaxValueName;
                    if ( _rxProperties.is() )
                        _rxProperties->getPropertyValue( sLimitPropertyName ) >>= nControlValue;
                }
                else
                {
                    nControlValue = (sal_Int32)::rtl::math::round( nExternalValue );
                }
            }
            else
            {
                if ( _rxProperties.is() )
                    _rxProperties->getPropertyValue( ::rtl::OUString( RTL_CONSTASCII_USTRINGPARAM( "ScrollValueMin" ) ) ) >>= nControlValue;
            }
        }

        return makeAny( nControlValue );
    }

    //--------------------------------------------------------------------
    Any translateControlIntToExternalDoubleValue( const Any& _rControlIntValue )
    {
        Any aExternalDoubleValue;
        sal_Int32 nScrollValue = 0;
        if ( _rControlIntValue >>= nScrollValue )
            aExternalDoubleValue <<= (double)nScrollValue;
        else
        {
            OSL_ENSURE( sal_False, "translateControlIntToExternalDoubleValue: no integer scroll value!" );
            // aExternalDoubleValue is void here, which is okay for this purpose ...
        }

        return aExternalDoubleValue;
    }

    //====================================================================
    //= OScrollBarModel
    //====================================================================
    //--------------------------------------------------------------------
    DBG_NAME( OScrollBarModel )
    //--------------------------------------------------------------------
    OScrollBarModel::OScrollBarModel( const Reference<XMultiServiceFactory>& _rxFactory )
        :OBoundControlModel( _rxFactory, VCL_CONTROLMODEL_SCROLLBAR, VCL_CONTROL_SCROLLBAR, sal_True, sal_True, sal_False )
        ,m_nDefaultScrollValue( 0 )
    {
        DBG_CTOR( OScrollBarModel, NULL );

        m_nClassId = FormComponentType::SCROLLBAR;
        initValueProperty( PROPERTY_SCROLL_VALUE, PROPERTY_ID_SCROLL_VALUE );
    }

    //--------------------------------------------------------------------
    OScrollBarModel::OScrollBarModel( const OScrollBarModel* _pOriginal, const Reference< XMultiServiceFactory >& _rxFactory )
        :OBoundControlModel( _pOriginal, _rxFactory )
    {
        DBG_CTOR( OScrollBarModel, NULL );
        m_nDefaultScrollValue = _pOriginal->m_nDefaultScrollValue;
    }

    //--------------------------------------------------------------------
    OScrollBarModel::~OScrollBarModel( )
    {
        DBG_DTOR( OScrollBarModel, NULL );
    }

    //--------------------------------------------------------------------
    IMPLEMENT_SERVICE_REGISTRATION_1( OScrollBarModel, OControlModel, FRM_SUN_COMPONENT_SCROLLBAR )
        // note that we're passing OControlModel as "base class". This is because
        // OBoundControlModel, our real base class, claims to support the DataAwareControlModel
        // service, which isn't really true for us. We only derive from this class
        // to benefit from the functionality for binding to spreadsheet cells

    //------------------------------------------------------------------------------
    IMPLEMENT_DEFAULT_CLONING( OScrollBarModel )

    //------------------------------------------------------------------------------
    void SAL_CALL OScrollBarModel::disposing()
    {
        OBoundControlModel::disposing();
    }

    //--------------------------------------------------------------------
    Reference< XPropertySetInfo > SAL_CALL OScrollBarModel::getPropertySetInfo() throw(RuntimeException)
    {
        return Reference< XPropertySetInfo >( createPropertySetInfo( getInfoHelper() ) );
    }

    //--------------------------------------------------------------------
    cppu::IPropertyArrayHelper& OScrollBarModel::getInfoHelper()
    {
        return *const_cast< OScrollBarModel* >( this )->getArrayHelper();
    }

    //--------------------------------------------------------------------
    void OScrollBarModel::fillProperties( Sequence< Property >& _rProps, Sequence< Property >& _rAggregateProps ) const
    {
        BEGIN_DESCRIBE_PROPERTIES( 3, OControlModel )
            DECL_PROP1( DEFAULT_SCROLL_VALUE, sal_Int32,       BOUND );
            DECL_PROP1( TABINDEX,             sal_Int16,       BOUND );
            DECL_PROP2( CONTROLSOURCEPROPERTY,::rtl::OUString, READONLY, TRANSIENT );
        END_DESCRIBE_PROPERTIES();
    }

    //------------------------------------------------------------------------------
    void OScrollBarModel::getFastPropertyValue( Any& _rValue, sal_Int32 _nHandle ) const
    {
        switch ( _nHandle )
        {
            case PROPERTY_ID_DEFAULT_SCROLL_VALUE:
                _rValue <<= m_nDefaultScrollValue;
                break;

            default:
                OBoundControlModel::getFastPropertyValue( _rValue, _nHandle );
        }
    }

    //------------------------------------------------------------------------------
    void OScrollBarModel::setFastPropertyValue_NoBroadcast( sal_Int32 _nHandle, const Any& _rValue ) throw ( Exception )
    {
        switch ( _nHandle )
        {
            case PROPERTY_ID_DEFAULT_SCROLL_VALUE:
                OSL_VERIFY( _rValue >>= m_nDefaultScrollValue );
                resetNoBroadcast();
                break;

            default:
                OBoundControlModel::setFastPropertyValue_NoBroadcast( _nHandle, _rValue );
        }
    }

    //------------------------------------------------------------------------------
    sal_Bool OScrollBarModel::convertFastPropertyValue(
                Any& _rConvertedValue, Any& _rOldValue, sal_Int32 _nHandle, const Any& _rValue )
                throw ( IllegalArgumentException )
    {
        sal_Bool bModified( sal_False );
        switch ( _nHandle )
        {
            case PROPERTY_ID_DEFAULT_SCROLL_VALUE:
                bModified = tryPropertyValue( _rConvertedValue, _rOldValue, _rValue, m_nDefaultScrollValue );
                break;

            default:
                bModified = OBoundControlModel::convertFastPropertyValue( _rConvertedValue, _rOldValue, _nHandle, _rValue );
                break;
        }
        return bModified;
    }

    //--------------------------------------------------------------------
    Any OScrollBarModel::getPropertyDefaultByHandle( sal_Int32 _nHandle ) const
    {
        Any aReturn;

        switch ( _nHandle )
        {
        case PROPERTY_ID_DEFAULT_SCROLL_VALUE:
            aReturn <<= (sal_Int32)0;
            break;

        default:
            aReturn = OBoundControlModel::getPropertyDefaultByHandle( _nHandle );
            break;
        }

        return aReturn;
    }

    //------------------------------------------------------------------------------
    Any OScrollBarModel::translateDbColumnToControlValue( )
    {
        OSL_ENSURE( sal_False, "OScrollBarModel::commitControlValueToDbColumn: never to be called (we're not bound)!" );
        return Any();
    }

    //------------------------------------------------------------------------------
    sal_Bool OScrollBarModel::commitControlValueToDbColumn( bool _bPostReset )
    {
        OSL_ENSURE( sal_False, "OScrollBarModel::commitControlValueToDbColumn: never to be called (we're not bound)!" );
        return sal_True;
    }

    //------------------------------------------------------------------------------
    Any OScrollBarModel::getDefaultForReset() const
    {
        return makeAny( (sal_Int32)m_nDefaultScrollValue );
    }

    //--------------------------------------------------------------------
    ::rtl::OUString SAL_CALL OScrollBarModel::getServiceName() throw( RuntimeException )
    {
        return FRM_SUN_COMPONENT_SCROLLBAR;
    }

    //--------------------------------------------------------------------
    void SAL_CALL OScrollBarModel::write( const Reference< XObjectOutputStream >& _rxOutStream )
        throw( IOException, RuntimeException )
    {
        OBoundControlModel::write( _rxOutStream );
        ::osl::MutexGuard aGuard( m_aMutex );

        OStreamSection aSection( Reference< XDataOutputStream >( _rxOutStream, UNO_QUERY ) );

        // version
        _rxOutStream->writeShort( 0x0001 );

        // properties
        _rxOutStream << m_nDefaultScrollValue;
        writeHelpTextCompatibly( _rxOutStream );
    }

    //--------------------------------------------------------------------
    void SAL_CALL OScrollBarModel::read( const Reference< XObjectInputStream>& _rxInStream ) throw( IOException, RuntimeException )
    {
        OBoundControlModel::read( _rxInStream );
        ::osl::MutexGuard aGuard( m_aMutex );

        // version
        {
            OStreamSection aSection( Reference< XDataInputStream >( _rxInStream, UNO_QUERY ) );

            sal_uInt16 nVersion = _rxInStream->readShort();
            if ( nVersion == 0x0001 )
            {
                _rxInStream >> m_nDefaultScrollValue;
                readHelpTextCompatibly( _rxInStream );
            }
            else
                defaultCommonProperties();

            // here, everything in the stream section which is left will be skipped
        }
    }

    //--------------------------------------------------------------------
    Any OScrollBarModel::translateExternalValueToControlValue( )
    {
        return translateExternalDoubleToControlIntValue( m_xExternalBinding, m_xAggregateSet,
            ::rtl::OUString( RTL_CONSTASCII_USTRINGPARAM( "ScrollValueMin" ) ),
            ::rtl::OUString( RTL_CONSTASCII_USTRINGPARAM( "ScrollValueMax" ) ) );
    }

    //--------------------------------------------------------------------
    Any OScrollBarModel::translateControlValueToExternalValue( )
    {
        // by definition, the base class simply obtains the property value
        return translateControlIntToExternalDoubleValue( OBoundControlModel::translateControlValueToExternalValue() );
    }

    //--------------------------------------------------------------------
    sal_Bool OScrollBarModel::approveValueBinding( const Reference< XValueBinding >& _rxBinding )
    {
        OSL_PRECOND( _rxBinding.is(), "OScrollBarModel::approveValueBinding: invalid binding!" );

        // only strings are accepted for simplicity
        return  _rxBinding.is()
            &&  _rxBinding->supportsType( ::getCppuType( static_cast< double* >( NULL ) ) );
    }

//........................................................................
}   // namespace frm
//........................................................................
<|endoftext|>


<commit_before>//
// compiler_support.hpp
//
// (c) 2013 helloworld922
//
//  Distributed under the Boost Software License, Version 1.0. (See
//  accompanying file LICENSE_1_0.txt or copy at
//  http://www.boost.org/LICENSE_1_0.txt)

#ifndef BOOST_SIGNALS3_COMPILER_SUPPORT_HPP
#define BOOST_SIGNALS3_COMPILER_SUPPORT_HPP

#include <boost/move/move.hpp>

// testing defines
//#define BOOST_NO_CXX11_ATOMIC
//#define BOOST_NO_CXX11_HDR_FUNCTIONAL
//#define BOOST_NO_CXX11_HDR_TUPLE

#include <memory>
#include <atomic>
#include <mutex>
#include <functional>
#include <numeric>
#include <forward_list>
#include <tuple>
#include <memory>

namespace boost
{
    namespace signals3
    {
        namespace detail
        {
            // shared_ptr and atomic shared_ptr
            using ::std::shared_ptr;
            using ::std::weak_ptr;
            using ::std::static_pointer_cast;
            using ::std::atomic_compare_exchange_strong;

            /**
             * FIXME! Compilers don't yet support atomic_load/store from C++11, so this needs
             * deleting when they do! DIRTY DIRTY UNSAFE HACK!
             */
            template<class T> std::shared_ptr<T> atomic_load(std::shared_ptr<T> const * p)
            {
                //boost::detail::spinlock_pool<2>::scoped_lock lock( p );
                return *p;
            }

            template<class T> void atomic_store(std::shared_ptr<T> * p, std::shared_ptr<T> r)
            {
                //boost::detail::spinlock_pool<2>::scoped_lock lock( p );
                p->swap(r);
            }

            using ::std::make_shared;

            // atomic int
            using ::std::atomic;

            // thread mutex and unique locking
            using ::std::mutex;
            using ::std::lock_guard;

            // tuple
            using ::std::tuple;
            using ::std::get;
            using ::std::function;

            // forward list
            using ::std::forward_list;
        }
    }
}

#endif // BOOST_SIGNALS3_COMPILER_SUPPORT_HPP
<commit_msg>Restore locking in the signals stuff<commit_after>//
// compiler_support.hpp
//
// (c) 2013 helloworld922
//
//  Distributed under the Boost Software License, Version 1.0. (See
//  accompanying file LICENSE_1_0.txt or copy at
//  http://www.boost.org/LICENSE_1_0.txt)

#ifndef BOOST_SIGNALS3_COMPILER_SUPPORT_HPP
#define BOOST_SIGNALS3_COMPILER_SUPPORT_HPP

#include <boost/move/move.hpp>
#include <boost/smart_ptr/detail/spinlock_pool.hpp>

// testing defines
//#define BOOST_NO_CXX11_ATOMIC
//#define BOOST_NO_CXX11_HDR_FUNCTIONAL
//#define BOOST_NO_CXX11_HDR_TUPLE

#include <memory>
#include <atomic>
#include <mutex>
#include <functional>
#include <numeric>
#include <forward_list>
#include <tuple>
#include <memory>

namespace boost
{
    namespace signals3
    {
        namespace detail
        {
            // shared_ptr and atomic shared_ptr
            using ::std::shared_ptr;
            using ::std::weak_ptr;
            using ::std::static_pointer_cast;
            using ::std::atomic_compare_exchange_strong;

            /**
             * FIXME! Compilers don't yet support atomic_load/store from C++11, so this needs
             * deleting when they do! DIRTY DIRTY UNSAFE HACK!
             */
            template<class T> std::shared_ptr<T> atomic_load(std::shared_ptr<T> const * p)
            {
                boost::detail::spinlock_pool<2>::scoped_lock lock( p );
                return *p;
            }

            template<class T> void atomic_store(std::shared_ptr<T> * p, std::shared_ptr<T> r)
            {
                boost::detail::spinlock_pool<2>::scoped_lock lock( p );
                p->swap(r);
            }

            using ::std::make_shared;

            // atomic int
            using ::std::atomic;

            // thread mutex and unique locking
            using ::std::mutex;
            using ::std::lock_guard;

            // tuple
            using ::std::tuple;
            using ::std::get;
            using ::std::function;

            // forward list
            using ::std::forward_list;
        }
    }
}

#endif // BOOST_SIGNALS3_COMPILER_SUPPORT_HPP
<|endoftext|>


<commit_before>/**
 * func_memory.cpp - the module implementing the concept of
 * programer-visible memory space accesing via memory address.
 * @author Roman Zavodskikh <roman.zavodskikh@phystech.edu>
 * Copyright 2015 uArchSim iLab project
 */

// Generic C

// Generic C++
#include <algorithm>
#include <iostream>
#include <string>
#include <sstream>

// uArchSim modules
#include <func_memory.h>
#include <elf_parser.h>

const int POISON = -1;

uint64 FuncMemory::get_num_of_set_priv( uint64 addr) const
{
    return addr >> ( addr_size_priv - set_num_size_priv);
}

uint64 FuncMemory::get_num_of_page_priv( uint64 addr) const
{
    return ( addr >> offset_size_priv) & ( ( 1 << page_num_size_priv) - 1);
}

uint64 FuncMemory::get_offset_priv( uint64 addr) const
{
    return addr & ( ( 1 << offset_size_priv) - 1);
}

void FuncMemory::increase_offset_priv ( uint64& offset,
            uint64& num_of_page,
            uint64& num_of_set, unsigned inc_by) const
{
    offset+=inc_by;
    if ( offset >= max_offset_priv)
    {
        offset-=max_offset_priv;
        ++num_of_page;
        if ( num_of_page >= num_of_pages_priv)
        {
            num_of_page-=num_of_pages_priv;
            ++num_of_set;
            if( num_of_set >= num_of_sets_priv)
            {
                cerr << "The END of the memory REACHED!!!" << endl;
                terminate();
            }
        }
    }
}

void FuncMemory::decrease_offset_priv ( uint64& offset,
        uint64& num_of_page,
        uint64& num_of_set, unsigned dec_by) const
{
    offset-=dec_by;
    if ( offset + dec_by < dec_by)
    {
        offset+=max_offset_priv;
        --num_of_page;
        if ( num_of_page + 1 < 1)
        {
            num_of_page+=num_of_pages_priv;
            --num_of_set;
            if( num_of_set + 1 < 1)
            {
                cerr << "The BEGINNING of the memory REACHED!!!" << endl;
                terminate();
            }
        }
    }
}
FuncMemory::FuncMemory( const char* executable_file_name,
                        uint64 addr_size,
                        uint64 page_bits,
                        uint64 offset_bits)
    :addr_size_priv( addr_size),
     page_num_size_priv( page_bits),
     offset_size_priv( offset_bits),
     exe_file_name_priv( executable_file_name)
{
    vector<ElfSection> sections_array;
    ElfSection::getAllElfSections( exe_file_name_priv.c_str(), sections_array);

    set_num_size_priv = addr_size_priv - page_num_size_priv -
        offset_size_priv;

    num_of_sets_priv = (uint64)1 << set_num_size_priv;
    num_of_pages_priv = (uint64)1 << page_num_size_priv;
    max_offset_priv = (uint64)1 << offset_size_priv;

    clog << "The max values: " << "offset==" << max_offset_priv
         << ", page==" << num_of_pages_priv
         << ", set==" << num_of_sets_priv << endl;

    sets_array_priv = new uint8**[ num_of_sets_priv];
    clog << "Initalized array of " << num_of_sets_priv << " sets." << endl;
    #if 0
    memset( sets_array_priv, 0,
        num_of_sets_priv * sizeof( *( sets_array_priv)));
    #endif
    fill( sets_array_priv, sets_array_priv + num_of_sets_priv,
        (unsigned char**)'\0');

    for ( unsigned i = 0; i < sections_array.size( ); ++i)
    {
        uint64 cur_addr = sections_array[ i].start_addr;
        if ( string( sections_array[ i].name) ==
             string( ".text") )
        {
            start_pc_adress_priv = cur_addr;
            clog << "start_pc_adress finded and written: "
                 << start_pc_adress_priv << endl;
        }

        for ( size_t offset = 0; offset < sections_array[ i].size; offset++)
        {
            write( sections_array[ i].content[ offset], cur_addr, 1);
            cur_addr++;
        }
    }
}

FuncMemory::~FuncMemory()
{
    for( unsigned i = 0; i < num_of_sets_priv; ++i)
    {
        if( sets_array_priv[ i] != NULL)
        {
            for (unsigned j = 0; j < num_of_pages_priv; ++j) {
                if( sets_array_priv[ i][ j] != NULL)
                {
                    delete [] sets_array_priv[ i][ j];
                }
            }
            delete [] sets_array_priv[ i];
        }
    }
    delete [] sets_array_priv;

    addr_size_priv=page_num_size_priv=offset_size_priv=POISON;
    num_of_sets_priv=num_of_pages_priv=max_offset_priv=POISON;
}

uint64 FuncMemory::startPC() const
{
    // put your code here
    return start_pc_adress_priv;
}

uint64 FuncMemory::read( uint64 addr, unsigned short num_of_bytes) const
{
    // put your code here
    clog << "FUNCTION FuncMemory::read" << endl;
    clog << "addr==" << addr << ", num_of_bytes==" << num_of_bytes << endl;

    if( num_of_bytes > 8)
    {
        cerr << "Cannot read more than eight ("
             << num_of_bytes << ") bytes" << endl;
        terminate();
    }
    else if( num_of_bytes == 0)
    {
        cerr << "Trying to read 0 bytes" << endl;
        terminate();
    }
    clog << "Passed num_of_bytes > 8 checking" << endl;

    uint64 num_of_set = get_num_of_set_priv( addr);
    uint64 num_of_page = get_num_of_page_priv( addr);
    uint64 offset = get_offset_priv( addr);

    clog << "Counted num_of_set (" << num_of_set
         << ") num_of_page (" << num_of_page
         << ") and offset (" << offset << ")" << endl;

    if ( sets_array_priv[ num_of_set] == NULL)
    {
        cerr << "Tryed to read from unitialized memory (set)" << endl;
        terminate();
    }

    if ( sets_array_priv[ num_of_set][ num_of_page] == NULL)
    {
        cerr << "Tryed to read from unitialized memory (page)" << endl;
        terminate();
    }

    uint64 rtr_val = 0;
    increase_offset_priv( offset, num_of_page, num_of_set, num_of_bytes);
    for ( unsigned i = 0; i < num_of_bytes; ++i)
    {
        rtr_val <<= 8;
        if( sets_array_priv[ num_of_set] != NULL &&
            sets_array_priv[ num_of_set][ num_of_page] != NULL)
        {
            rtr_val += sets_array_priv[ num_of_set][ num_of_page][ offset];
        }
        decrease_offset_priv( offset, num_of_page, num_of_set, 1);
    }
    clog << "END_OF_FUNCTION FuncMemory::read. rtr_val == " << rtr_val << endl;
    return rtr_val;
}

void FuncMemory::write( uint64 value, uint64 addr, unsigned short num_of_bytes)
{
    // put your code here
    clog << "FUNCTION FuncMemory::write" << endl;
    clog << "value==" << value << ", addr==" << addr
         << ", num_of_bytes==" << num_of_bytes << endl;
    if( num_of_bytes > 8)
    {
        cerr << "Cannot write more than eight ("
             << num_of_bytes << ") bytes" << endl;
        terminate();
    }
    else if( num_of_bytes == 0)
    {
        cerr << "Trying to write 0 bytes" << endl;
        terminate();
    }
    clog << "Passed checking num_of_bytes > 8" << endl;

    uint64 num_of_set = get_num_of_set_priv( addr);
    uint64 num_of_page = get_num_of_page_priv( addr);
    uint64 offset = get_offset_priv( addr);

    clog << "Counted num_of_set (" << num_of_set
         << ") num_of_page (" << num_of_page;
    clog << ") and offset (" << offset << ")" << endl;

    increase_offset_priv( offset, num_of_page, num_of_set, num_of_bytes);
    for ( unsigned i = 0; i < num_of_bytes; ++i)
    {
        if ( sets_array_priv[ num_of_set] == NULL)
        {
            clog << "Initializing set number " << num_of_set << " with "
                 << num_of_pages_priv << " pages." << endl;
            sets_array_priv[ num_of_set] = new uint8*[ num_of_pages_priv];
            #if 0
            memset( sets_array_priv[ num_of_set], 0,
                num_of_pages_priv * sizeof( *( sets_array_priv[ num_of_set])));
            #endif
            fill( sets_array_priv[ num_of_set],
                sets_array_priv[ num_of_set] + num_of_pages_priv,
                (unsigned char*)'\0');
        }

        if ( sets_array_priv[ num_of_set][ num_of_page] == NULL)
        {
            clog << "Initializing page number " << num_of_page << " in "
                 << num_of_set << " set with "
                 << max_offset_priv << " bytes." << endl;
            sets_array_priv[ num_of_set][ num_of_page] =
                new uint8[ max_offset_priv];
            #if 0
            memset( sets_array_priv[ num_of_set][ num_of_page], 0,
                max_offset_priv *
                    sizeof( *( sets_array_priv[ num_of_set][ num_of_page])));
            #endif
        }

        uint64 val_to_write = ( value & ( 0xFF << ( num_of_bytes-i-1)*8))
            >> ( ( num_of_bytes-i-1)*8);
        clog << "value==" << value<< ";val_to_write==" << val_to_write;
        clog << "----num_of_set==" << num_of_set
             << ", num_of_page==" << num_of_page
             << ", offset==" << offset << endl;
        sets_array_priv[ num_of_set][ num_of_page][ offset] = val_to_write;
        decrease_offset_priv( offset, num_of_page, num_of_set, 1);
    }
    clog << "END_OF_FUNCTION FucnMemory::write" << endl;
}

string FuncMemory::dump( string indent) const
{
    // put your code here
    ostringstream oss;

    oss << indent << "Dump of FuncMemory" << endl
        << indent << "Content" << endl;

    oss << hex;
    bool skip_was_printed = false;
    for( unsigned set_num = 0; set_num < num_of_sets_priv; ++set_num)
    {
        if ( sets_array_priv[ set_num] != NULL)
        {
            for( unsigned page_num = 0;
                page_num < num_of_pages_priv; ++page_num)
            {
                if ( sets_array_priv[ set_num][ page_num] != NULL)
                {
                    for ( unsigned offset = 0; offset < max_offset_priv;
                        offset+=sizeof( uint32))
                    {
                        uint64 addr = offset;
                        addr += set_num << page_num_size_priv+offset_size_priv;
                        addr += page_num << offset_size_priv;

                        uint32 val = read( addr, sizeof( uint32));
                        if ( val ==0)
                        {
                            if ( !skip_was_printed)
                            {
                                oss << indent << " ..... " << endl;
                                skip_was_printed = true;
                            }
                        }
                        else
                        {
                            ostringstream addr_str;
                            addr_str << hex;
                            addr_str.width( 8);
                            addr_str.fill( '0');
                            addr_str << addr;

                            ostringstream val_str;
                            val_str << hex;
                            val_str.width( 8);
                            val_str.fill( '0');
                            val_str << val;

                            oss << indent << "Addr 0x"
                                << addr_str.str()
                                << " : "
                                << val_str.str() << endl;

                            skip_was_printed = false;
                        }
                    }
                }
            }
        }
    }
    return oss.str();
}
<commit_msg>Fixed bug when read/write was one byte forward that expected<commit_after>/**
 * func_memory.cpp - the module implementing the concept of
 * programer-visible memory space accesing via memory address.
 * @author Roman Zavodskikh <roman.zavodskikh@phystech.edu>
 * Copyright 2015 uArchSim iLab project
 */

// Generic C

// Generic C++
#include <algorithm>
#include <iostream>
#include <string>
#include <sstream>

// uArchSim modules
#include <func_memory.h>
#include <elf_parser.h>

uint64 FuncMemory::get_num_of_set_priv( uint64 addr) const
{
    return addr >> ( addr_size_priv - set_num_size_priv);
}

uint64 FuncMemory::get_num_of_page_priv( uint64 addr) const
{
    return ( addr >> offset_size_priv) & ( ( 1 << page_num_size_priv) - 1);
}

uint64 FuncMemory::get_offset_priv( uint64 addr) const
{
    return addr & ( ( 1 << offset_size_priv) - 1);
}

void FuncMemory::increase_offset_priv ( uint64& offset,
            uint64& num_of_page,
            uint64& num_of_set, unsigned inc_by) const
{
    offset+=inc_by;
    if ( offset >= max_offset_priv)
    {
        offset-=max_offset_priv;
        ++num_of_page;
        if ( num_of_page >= num_of_pages_priv)
        {
            num_of_page-=num_of_pages_priv;
            ++num_of_set;
            if( num_of_set >= num_of_sets_priv)
            {
                cerr << "The END of the memory REACHED!!!" << endl;
                terminate();
            }
        }
    }
}

void FuncMemory::decrease_offset_priv ( uint64& offset,
        uint64& num_of_page,
        uint64& num_of_set, unsigned dec_by) const
{
    offset-=dec_by;
    if ( offset + dec_by < dec_by)
    {
        offset+=max_offset_priv;
        --num_of_page;
        if ( num_of_page + 1 < 1)
        {
            num_of_page+=num_of_pages_priv;
            --num_of_set;
            if( num_of_set + 1 < 1)
            {
                cerr << "The BEGINNING of the memory REACHED!!!" << endl;
                terminate();
            }
        }
    }
}
FuncMemory::FuncMemory( const char* executable_file_name,
                        uint64 addr_size,
                        uint64 page_bits,
                        uint64 offset_bits)
    :addr_size_priv( addr_size),
     page_num_size_priv( page_bits),
     offset_size_priv( offset_bits),
     exe_file_name_priv( executable_file_name)
{
    vector<ElfSection> sections_array;
    ElfSection::getAllElfSections( exe_file_name_priv.c_str(), sections_array);

    set_num_size_priv = addr_size_priv - page_num_size_priv -
        offset_size_priv;

    num_of_sets_priv = (uint64)1 << set_num_size_priv;
    num_of_pages_priv = (uint64)1 << page_num_size_priv;
    max_offset_priv = (uint64)1 << offset_size_priv;

    clog << "The max values: " << "offset==" << max_offset_priv
         << ", page==" << num_of_pages_priv
         << ", set==" << num_of_sets_priv << endl;

    sets_array_priv = new uint8**[ num_of_sets_priv];
    clog << "Initalized array of " << num_of_sets_priv << " sets." << endl;
    #if 0
    memset( sets_array_priv, 0,
        num_of_sets_priv * sizeof( *( sets_array_priv)));
    #endif
    fill( sets_array_priv, sets_array_priv + num_of_sets_priv,
        (unsigned char**)'\0');

    for ( unsigned i = 0; i < sections_array.size( ); ++i)
    {
        uint64 cur_addr = sections_array[ i].start_addr;
        if ( string( sections_array[ i].name) ==
             string( ".text") )
        {
            start_pc_adress_priv = cur_addr;
            clog << "start_pc_adress finded and written: "
                 << start_pc_adress_priv << endl;
        }

        for ( size_t offset = 0; offset < sections_array[ i].size; offset++)
        {
            write( sections_array[ i].content[ offset], cur_addr, 1);
            cur_addr++;
        }
    }
}

FuncMemory::~FuncMemory()
{
    for( unsigned i = 0; i < num_of_sets_priv; ++i)
    {
        if( sets_array_priv[ i] != NULL)
        {
            for (unsigned j = 0; j < num_of_pages_priv; ++j) {
                if( sets_array_priv[ i][ j] != NULL)
                {
                    delete [] sets_array_priv[ i][ j];
                }
            }
            delete [] sets_array_priv[ i];
        }
    }
    delete [] sets_array_priv;

    addr_size_priv=page_num_size_priv=offset_size_priv=NO_VAL64;
    num_of_sets_priv=num_of_pages_priv=max_offset_priv=NO_VAL64;
}

uint64 FuncMemory::startPC() const
{
    // put your code here
    return start_pc_adress_priv;
}

uint64 FuncMemory::read( uint64 addr, unsigned short num_of_bytes) const
{
    // put your code here
    clog << "FUNCTION FuncMemory::read" << endl;
    clog << "addr==" << addr << ", num_of_bytes==" << num_of_bytes << endl;

    if( num_of_bytes > 8)
    {
        cerr << "Cannot read more than eight ("
             << num_of_bytes << ") bytes" << endl;
        terminate();
    }
    else if( num_of_bytes == 0)
    {
        cerr << "Trying to read 0 bytes" << endl;
        terminate();
    }
    clog << "Passed num_of_bytes > 8 checking" << endl;

    uint64 num_of_set = get_num_of_set_priv( addr);
    uint64 num_of_page = get_num_of_page_priv( addr);
    uint64 offset = get_offset_priv( addr);

    clog << "Counted num_of_set (" << num_of_set
         << ") num_of_page (" << num_of_page
         << ") and offset (" << offset << ")" << endl;

    if ( sets_array_priv[ num_of_set] == NULL)
    {
        cerr << "Tryed to read from unitialized memory (set)" << endl;
        terminate();
    }

    if ( sets_array_priv[ num_of_set][ num_of_page] == NULL)
    {
        cerr << "Tryed to read from unitialized memory (page)" << endl;
        terminate();
    }

    uint64 rtr_val = 0;
    increase_offset_priv( offset, num_of_page, num_of_set, num_of_bytes - 1);
    for ( unsigned i = 0; i < num_of_bytes; ++i)
    {
        rtr_val <<= 8;
        if( sets_array_priv[ num_of_set] != NULL &&
            sets_array_priv[ num_of_set][ num_of_page] != NULL)
        {
            rtr_val += sets_array_priv[ num_of_set][ num_of_page][ offset];
        }
        if ( i != num_of_bytes - 1)
        /*We don't need to decrease last time because we need to decrease
          (num_of_bytes - 1) times, not num_of_bytes!!!*/
        {
            decrease_offset_priv( offset, num_of_page, num_of_set, 1);
        }
    }
    clog << "END_OF_FUNCTION FuncMemory::read. rtr_val == " << rtr_val << endl;
    return rtr_val;
}

void FuncMemory::write( uint64 value, uint64 addr, unsigned short num_of_bytes)
{
    // put your code here
    clog << "FUNCTION FuncMemory::write" << endl;
    clog << "value==" << value << ", addr==" << addr
         << ", num_of_bytes==" << num_of_bytes << endl;
    if( num_of_bytes > 8)
    {
        cerr << "Cannot write more than eight ("
             << num_of_bytes << ") bytes" << endl;
        terminate();
    }
    else if( num_of_bytes == 0)
    {
        cerr << "Trying to write 0 bytes" << endl;
        terminate();
    }
    clog << "Passed checking num_of_bytes > 8" << endl;

    uint64 num_of_set = get_num_of_set_priv( addr);
    uint64 num_of_page = get_num_of_page_priv( addr);
    uint64 offset = get_offset_priv( addr);

    clog << "Counted num_of_set (" << num_of_set
         << ") num_of_page (" << num_of_page;
    clog << ") and offset (" << offset << ")" << endl;

    increase_offset_priv( offset, num_of_page, num_of_set, num_of_bytes - 1);
    for ( unsigned i = 0; i < num_of_bytes; ++i)
    {
        if ( sets_array_priv[ num_of_set] == NULL)
        {
            clog << "Initializing set number " << num_of_set << " with "
                 << num_of_pages_priv << " pages." << endl;
            sets_array_priv[ num_of_set] = new uint8*[ num_of_pages_priv];
            #if 0
            memset( sets_array_priv[ num_of_set], 0,
                num_of_pages_priv * sizeof( *( sets_array_priv[ num_of_set])));
            #endif
            fill( sets_array_priv[ num_of_set],
                sets_array_priv[ num_of_set] + num_of_pages_priv,
                (unsigned char*)'\0');
        }

        if ( sets_array_priv[ num_of_set][ num_of_page] == NULL)
        {
            clog << "Initializing page number " << num_of_page << " in "
                 << num_of_set << " set with "
                 << max_offset_priv << " bytes." << endl;
            sets_array_priv[ num_of_set][ num_of_page] =
                new uint8[ max_offset_priv];
            #if 0
            memset( sets_array_priv[ num_of_set][ num_of_page], 0,
                max_offset_priv *
                    sizeof( *( sets_array_priv[ num_of_set][ num_of_page])));
            #endif
        }

        uint64 val_to_write = ( value & ( 0xFF << ( num_of_bytes-i-1)*8))
            >> ( ( num_of_bytes-i-1)*8);
        clog << "value==" << value<< ";val_to_write==" << val_to_write;
        clog << "----num_of_set==" << num_of_set
             << ", num_of_page==" << num_of_page
             << ", offset==" << offset << endl;
        sets_array_priv[ num_of_set][ num_of_page][ offset] = val_to_write;
        if ( i != num_of_bytes - 1)
        /*We don't need to decrease last time because we need to decrease
          (num_of_bytes - 1) times, not num_of_bytes!!!*/
        {
            decrease_offset_priv( offset, num_of_page, num_of_set, 1);
        }
    }
    clog << "END_OF_FUNCTION FucnMemory::write" << endl;
}

string FuncMemory::dump( string indent) const
{
    // put your code here
    ostringstream oss;

    oss << indent << "Dump of FuncMemory" << endl
        << indent << "Content" << endl;

    oss << hex;
    bool skip_was_printed = false;
    for( unsigned set_num = 0; set_num < num_of_sets_priv; ++set_num)
    {
        if ( sets_array_priv[ set_num] != NULL)
        {
            for( unsigned page_num = 0;
                page_num < num_of_pages_priv; ++page_num)
            {
                if ( sets_array_priv[ set_num][ page_num] != NULL)
                {
                    for ( unsigned offset = 0; offset < max_offset_priv;
                        offset+=sizeof( uint32))
                    {
                        uint64 addr = offset;
                        addr += set_num << page_num_size_priv+offset_size_priv;
                        addr += page_num << offset_size_priv;

                        uint32 val = read( addr, sizeof( uint32));
                        if ( val ==0)
                        {
                            if ( !skip_was_printed)
                            {
                                oss << indent << " ..... " << endl;
                                skip_was_printed = true;
                            }
                        }
                        else
                        {
                            ostringstream addr_str;
                            addr_str << hex;
                            addr_str.width( 8);
                            addr_str.fill( '0');
                            addr_str << addr;

                            ostringstream val_str;
                            val_str << hex;
                            val_str.width( 8);
                            val_str.fill( '0');
                            val_str << val;

                            oss << indent << "Addr 0x"
                                << addr_str.str()
                                << " : "
                                << val_str.str() << endl;

                            skip_was_printed = false;
                        }
                    }
                }
            }
        }
    }
    return oss.str();
}
<|endoftext|>


<commit_before><commit_msg>comments<commit_after><|endoftext|>


<commit_before>/*
 * TI Voxel Lib component.
 *
 * Copyright (c) 2014 Texas Instruments Inc.
 */

#include "TintinCDKCamera.h"
#include "VoxelXUProgrammer.h"
#include "VoxelUSBProgrammer.h"
#include <Logger.h>
#include <UVCStreamer.h>
#include <USBBulkStreamer.h>

#include <Parameter.h>
#define _USE_MATH_DEFINES
#include <math.h>
namespace Voxel
{

namespace TI
{

TintinCDKCamera::TintinCDKCamera(Voxel::DevicePtr device): ToFTintinCamera("TintinCDKCamera", device)
{
  _init();
}

class TintinCDKMixVoltageParameter: public UnsignedIntegerParameter
{
protected:
  virtual uint _fromRawValue(uint32_t value) const
  {
    if(value > 0x80U)
      return (value - 0x80U)*50 + 500;
    else
      return 500;
  }

  virtual uint32_t _toRawValue(uint value) const
  {
    if(value > 500)
      return (value - 500)/50 + 0x80U;
    else
      return 0x80U;
  }

public:
  TintinCDKMixVoltageParameter(RegisterProgrammer &programmer):
  UnsignedIntegerParameter(programmer, MIX_VOLTAGE, "mV", 0x2D05, 8, 7, 0, 1200, 2000, 1500, "Mixing voltage",
                           "Mixing voltage?", Parameter::IO_READ_WRITE, {})
  {}

  virtual ~TintinCDKMixVoltageParameter() {}
};

class TintinCDKPVDDParameter: public UnsignedIntegerParameter
{
protected:
  virtual uint _fromRawValue(uint32_t value) const
  {
    if(value > 0x80U)
      return (value - 0x80U)*50 + 500;
    else
      return 500;
  }

  virtual uint32_t _toRawValue(uint value) const
  {
    if(value > 500)
      return (value - 500)/50 + 0x80U;
    else
      return 0x80U;
  }

public:
  TintinCDKPVDDParameter(RegisterProgrammer &programmer):
  UnsignedIntegerParameter(programmer, PVDD, "mV", 0x2D0E, 8, 7, 0, 2000, 3600, 3300, "Pixel VDD",
                           "Reset voltage level of pixel.", Parameter::IO_READ_WRITE, {})
  {}

  virtual ~TintinCDKPVDDParameter() {}
};

class TintinCDKIlluminationPowerParameter: public UnsignedIntegerParameter
{
protected:
  // Relations derived by Subhash
  virtual uint _fromRawValue(uint32_t value) const
  {
    float R = value*100.0/255; //Digipot resistance in kOhms for given register setting
    float Rlim = R*113.0/(R+113)+51.1; //Effective current limiting resistor in kOhms for the given digipot resistance
    float I = 118079.0e-3/Rlim; //Current limit implemented by the linear current limiting IC for the given limiting resistance. This has a small variation as compared to the datasheet. That assumption has been made for the purpose of simplification.
    return (I-0.2)*1100; //Subtracting the threshold current and multiplying by the power gain of the laser diode.
  }

  virtual uint32_t _toRawValue(uint value) const
  {
    float v = value/1000.0;
    return uint32_t(((130000/(v + 0.22))-51.1e3)*28815e3/((164.1e3 - 130000/(v + 0.22))*100e3));
  }

public:
  TintinCDKIlluminationPowerParameter(RegisterProgrammer &programmer):
  UnsignedIntegerParameter(programmer, ILLUM_POWER, "mW", 0x5401, 8, 7, 0, 1050, 2200, 1129, "Illumination Power",
                           "These power numbers are approximate (+- 20%) and the actual power numbers are subject to component tolerances.", Parameter::IO_READ_WRITE, {})
  {}

  virtual ~TintinCDKIlluminationPowerParameter() {}
};

class TintinCDKIlluminationPowerPercentParameter: public UnsignedIntegerParameter
{
protected:
  TintinCDKCamera &_depthCamera;

public:
  TintinCDKIlluminationPowerPercentParameter(TintinCDKCamera &depthCamera, RegisterProgrammer &programmer):
  UnsignedIntegerParameter(programmer, ILLUM_POWER_PERCENTAGE, "%", 0, 0, 0, 0, 48, 100, 51, "Illumination Power",
                           "These power numbers are approximate (+- 20%) and the actual power numbers are subject to component tolerances.", Parameter::IO_READ_WRITE, {}),
                           _depthCamera(depthCamera)
  {}

  virtual bool get(uint &value, bool refresh = false)
  {
    uint v;
    TintinCDKIlluminationPowerParameter *p = dynamic_cast<TintinCDKIlluminationPowerParameter *>(_depthCamera.getParam(ILLUM_POWER).get());
    if(!p || !p->get(v))
      return false;

    value = v*100/p->upperLimit();
    return true;
  }

  virtual bool set(const uint &value)
  {
    TintinCDKIlluminationPowerParameter *p = dynamic_cast<TintinCDKIlluminationPowerParameter *>(_depthCamera.getParam(ILLUM_POWER).get());
    if(!p)
      return false;

    uint v = value*p->upperLimit()/100;

    if(!p->set(v))
      return false;

    return true;
  }

  virtual ~TintinCDKIlluminationPowerPercentParameter() {}
};

bool TintinCDKCamera::_init()
{
  USBDevice &d = (USBDevice &)*_device;

  DevicePtr controlDevice = _device;

  if (d.productID() == TINTIN_CDK_PRODUCT_UVC) {
    _programmer = Ptr<RegisterProgrammer>(new VoxelXUProgrammer(
      { {0x2D, 1}, {0x52, 1}, {0x54, 1}, {0x4B, 2}, {0x4E, 2}, {0x58, 3}, {0x5C, 3} },
      controlDevice));
    _streamer = Ptr<Streamer>(new UVCStreamer(controlDevice));
  } else {
    USBIOPtr usbIO(new USBIO(controlDevice));

    _programmer = Ptr<RegisterProgrammer>(new VoxelUSBProgrammer(
      { {0x2D, 1}, {0x52, 1}, {0x54, 1}, {0x4B, 2}, {0x4E, 2}, {0x58, 3}, {0x5C, 3} },
      {
        {0x58, {0x08, 0x09, 0}},
        {0x5C, {0x08, 0x09, 0}},
        {0x4B, {0x0A, 0x0B, 0}},
        {0x4E, {0x0A, 0x0B, 0}},
        {0x2D, {0x04, 0x03, 8}},
        {0x52, {0x04, 0x03, 8}},
        {0x54, {0x04, 0x03, 8}}
      }, usbIO, controlDevice));
    _streamer = Ptr<Streamer>(new USBBulkStreamer(usbIO, controlDevice, 0x82));
  }

  if(!_programmer->isInitialized() || !_streamer->isInitialized())
    return false;

  if(!_addParameters({
    ParameterPtr(new TintinCDKMixVoltageParameter(*_programmer)),
    //ParameterPtr(new TintinCDKPVDDParameter(*_programmer)),
    ParameterPtr(new TintinCDKIlluminationPowerParameter(*_programmer)),
    ParameterPtr(new TintinCDKIlluminationPowerPercentParameter(*this, *_programmer)),
    }))
  {
    return false;
  }
  /*
  // Settings for mix voltage and PVDD
  if(!_programmer->writeRegister(0x2D06, 0xFF) ||
    !_programmer->writeRegister(0x2D04, 0x40) ||
    !_programmer->writeRegister(0x2D05, 0x94) ||
    !_programmer->writeRegister(0x2D0D, 0x40) ||
    !_programmer->writeRegister(0x2D0E, 0xB8) ||
    !_programmer->writeRegister(0x2D0F, 0xFF)
  )
    return false;
	*/

  if(!ToFTintinCamera::_init())
    return false;

  return true;
}

bool TintinCDKCamera::_initStartParams()
{
  USBDevice &d = (USBDevice &)*_device;

  if(!ToFTintinCamera::_initStartParams())
    return false;

  if (!set(TILLUM_SLAVE_ADDR, 0x72U))
    return false;

  if ((d.productID() == TINTIN_CDK_PRODUCT_BULK) && !set(BLK_HEADER_EN, false))
    return false;

  return true;
}

bool TintinCDKCamera::_getFieldOfView(float &fovHalfAngle) const
{
  fovHalfAngle = (87/2.0f)*(M_PI/180.0f);
  return true;
}

bool TintinCDKCamera::_setStreamerFrameSize(const FrameSize &s)
{
  UVCStreamer *uvcStreamer = dynamic_cast<UVCStreamer *>(&*_streamer);
  USBBulkStreamer *bulkStreamer = dynamic_cast<USBBulkStreamer *>(&*_streamer);
  USBDevice &d = (USBDevice &)*_device;

  VideoMode m;
  m.frameSize = s;

  int bytesPerPixel;

  if(!_get(PIXEL_DATA_SIZE, bytesPerPixel))
  {
    logger(LOG_ERROR) << "TintinCDKCamera: Could not get current bytes per pixel" << std::endl;
    return false;
  }

  if(!_getFrameRate(m.frameRate))
  {
    logger(LOG_ERROR) << "TintinCDKCamera: Could not get current frame rate" << std::endl;
    return false;
  }

  if ((d.productID() == TINTIN_CDK_PRODUCT_UVC))
  {
    if(bytesPerPixel == 4)
      m.frameSize.width *= 2;
    if (!uvcStreamer)
    {
      logger(LOG_ERROR) << "TintinCDKCamera: Streamer is not of type UVC" << std::endl;
      return false;
    }

    if(!uvcStreamer->setVideoMode(m))
    {
      logger(LOG_ERROR) << "TintinCDKCamera: Could not set video mode for UVC" << std::endl;
      return false;
    }
  }
  else if ((d.productID() == TINTIN_CDK_PRODUCT_BULK))
  {
    if (!bulkStreamer)
    {
      logger(LOG_ERROR) << "TintinCDKCamera: Streamer is not of type Bulk" << std::endl;
      return false;
    }

    if (!bulkStreamer->setBufferSize(s.width * s.height * bytesPerPixel))
    {
      logger(LOG_ERROR) << "TintinCDKCamera: Could not set buffer size for bulk transfer" << std::endl;
      return false;
    }
  }

  return true;
}

bool TintinCDKCamera::_getSupportedVideoModes(Vector<SupportedVideoMode> &supportedVideoModes) const
{
  USBDevice &d = (USBDevice &)*_device;

  if (d.productID() == TINTIN_CDK_PRODUCT_UVC) {
    supportedVideoModes = Vector<SupportedVideoMode> {
      SupportedVideoMode(320,240,25,1,4),
      SupportedVideoMode(160,240,50,1,4),
      SupportedVideoMode(160,120,100,1,4),
      SupportedVideoMode(80,120,200,1,4),
      SupportedVideoMode(80,60,400,1,4),
      SupportedVideoMode(320,240,50,1,2),
      SupportedVideoMode(320,120,100,1,2),
      SupportedVideoMode(160,120,200,1,2),
      SupportedVideoMode(160,60,400,1,2),
      SupportedVideoMode(80,60,400,1,2),
    };
  } else {
    supportedVideoModes = Vector<SupportedVideoMode> {
      SupportedVideoMode(320,240,50,1,4),
      SupportedVideoMode(160,240,100,1,4),
      SupportedVideoMode(160,120,100,1,4),
      SupportedVideoMode(80,120,200,1,4),
      SupportedVideoMode(80,60,400,1,4),
      SupportedVideoMode(320,240,50,1,2),
      SupportedVideoMode(320,120,100,1,2),
      SupportedVideoMode(160,120,200,1,2),
      SupportedVideoMode(160,60,400,1,2),
      SupportedVideoMode(80,60,400,1,2),
    };
  }

  return true;
}

bool TintinCDKCamera::_getMaximumVideoMode(VideoMode &videoMode) const
{
  int bytesPerPixel;
  USBDevice &d = (USBDevice &)*_device;
  if(!_get(PIXEL_DATA_SIZE, bytesPerPixel))
  {
    logger(LOG_ERROR) << "TintinCDKCamera: Could not get current bytes per pixel" << std::endl;
    return false;
  }

  videoMode.frameSize.width = 320;
  videoMode.frameSize.height = 240;
  videoMode.frameRate.denominator = 1;
  if (d.productID() == TINTIN_CDK_PRODUCT_UVC) {
    videoMode.frameRate.numerator = (bytesPerPixel == 4)?25:50;
  } else {
    videoMode.frameRate.numerator = 30;
  }

  return true;
}

}
}<commit_msg>TintinCDKCamera: initialize TPL0102 and INA226<commit_after>/*
 * TI Voxel Lib component.
 *
 * Copyright (c) 2014 Texas Instruments Inc.
 */

#include "TintinCDKCamera.h"
#include "VoxelXUProgrammer.h"
#include "VoxelUSBProgrammer.h"
#include <Logger.h>
#include <UVCStreamer.h>
#include <USBBulkStreamer.h>

#include <Parameter.h>
#define _USE_MATH_DEFINES
#include <math.h>
namespace Voxel
{

namespace TI
{

TintinCDKCamera::TintinCDKCamera(Voxel::DevicePtr device): ToFTintinCamera("TintinCDKCamera", device)
{
  _init();
}

class TintinCDKMixVoltageParameter: public UnsignedIntegerParameter
{
protected:
  virtual uint _fromRawValue(uint32_t value) const
  {
    if(value > 0x80U)
      return (value - 0x80U)*50 + 500;
    else
      return 500;
  }

  virtual uint32_t _toRawValue(uint value) const
  {
    if(value > 500)
      return (value - 500)/50 + 0x80U;
    else
      return 0x80U;
  }

public:
  TintinCDKMixVoltageParameter(RegisterProgrammer &programmer):
  UnsignedIntegerParameter(programmer, MIX_VOLTAGE, "mV", 0x2D05, 8, 7, 0, 1200, 2000, 1500, "Mixing voltage",
                           "Mixing voltage?", Parameter::IO_READ_WRITE, {})
  {}

  virtual ~TintinCDKMixVoltageParameter() {}
};

class TintinCDKPVDDParameter: public UnsignedIntegerParameter
{
protected:
  virtual uint _fromRawValue(uint32_t value) const
  {
    if(value > 0x80U)
      return (value - 0x80U)*50 + 500;
    else
      return 500;
  }

  virtual uint32_t _toRawValue(uint value) const
  {
    if(value > 500)
      return (value - 500)/50 + 0x80U;
    else
      return 0x80U;
  }

public:
  TintinCDKPVDDParameter(RegisterProgrammer &programmer):
  UnsignedIntegerParameter(programmer, PVDD, "mV", 0x2D0E, 8, 7, 0, 2000, 3600, 3300, "Pixel VDD",
                           "Reset voltage level of pixel.", Parameter::IO_READ_WRITE, {})
  {}

  virtual ~TintinCDKPVDDParameter() {}
};

class TintinCDKIlluminationPowerParameter: public UnsignedIntegerParameter
{
protected:
  // Relations derived by Subhash
  virtual uint _fromRawValue(uint32_t value) const
  {
    float R = value*100.0/255; //Digipot resistance in kOhms for given register setting
    float Rlim = R*113.0/(R+113)+51.1; //Effective current limiting resistor in kOhms for the given digipot resistance
    float I = 118079.0e-3/Rlim; //Current limit implemented by the linear current limiting IC for the given limiting resistance. This has a small variation as compared to the datasheet. That assumption has been made for the purpose of simplification.
    return (I-0.2)*1100; //Subtracting the threshold current and multiplying by the power gain of the laser diode.
  }

  virtual uint32_t _toRawValue(uint value) const
  {
    float v = value/1000.0;
    return uint32_t(((130000/(v + 0.22))-51.1e3)*28815e3/((164.1e3 - 130000/(v + 0.22))*100e3));
  }

public:
  TintinCDKIlluminationPowerParameter(RegisterProgrammer &programmer):
  UnsignedIntegerParameter(programmer, ILLUM_POWER, "mW", 0x5401, 8, 7, 0, 1050, 2200, 1129, "Illumination Power",
                           "These power numbers are approximate (+- 20%) and the actual power numbers are subject to component tolerances.", Parameter::IO_READ_WRITE, {})
  {}

  virtual ~TintinCDKIlluminationPowerParameter() {}
};

class TintinCDKIlluminationPowerPercentParameter: public UnsignedIntegerParameter
{
protected:
  TintinCDKCamera &_depthCamera;

public:
  TintinCDKIlluminationPowerPercentParameter(TintinCDKCamera &depthCamera, RegisterProgrammer &programmer):
  UnsignedIntegerParameter(programmer, ILLUM_POWER_PERCENTAGE, "%", 0, 0, 0, 0, 48, 100, 51, "Illumination Power",
                           "These power numbers are approximate (+- 20%) and the actual power numbers are subject to component tolerances.", Parameter::IO_READ_WRITE, {}),
                           _depthCamera(depthCamera)
  {}

  virtual bool get(uint &value, bool refresh = false)
  {
    uint v;
    TintinCDKIlluminationPowerParameter *p = dynamic_cast<TintinCDKIlluminationPowerParameter *>(_depthCamera.getParam(ILLUM_POWER).get());
    if(!p || !p->get(v))
      return false;

    value = v*100/p->upperLimit();
    return true;
  }

  virtual bool set(const uint &value)
  {
    TintinCDKIlluminationPowerParameter *p = dynamic_cast<TintinCDKIlluminationPowerParameter *>(_depthCamera.getParam(ILLUM_POWER).get());
    if(!p)
      return false;

    uint v = value*p->upperLimit()/100;

    if(!p->set(v))
      return false;

    return true;
  }

  virtual ~TintinCDKIlluminationPowerPercentParameter() {}
};

bool TintinCDKCamera::_init()
{
  USBDevice &d = (USBDevice &)*_device;

  DevicePtr controlDevice = _device;

  if (d.productID() == TINTIN_CDK_PRODUCT_UVC) {
    _programmer = Ptr<RegisterProgrammer>(new VoxelXUProgrammer(
      { {0x2D, 1}, {0x52, 1}, {0x54, 1}, {0x4B, 2}, {0x4E, 2}, {0x58, 3}, {0x5C, 3} },
      controlDevice));
    _streamer = Ptr<Streamer>(new UVCStreamer(controlDevice));
  } else {
    USBIOPtr usbIO(new USBIO(controlDevice));

    _programmer = Ptr<RegisterProgrammer>(new VoxelUSBProgrammer(
      { {0x2D, 1}, {0x52, 1}, {0x54, 1}, {0x4B, 2}, {0x4E, 2}, {0x58, 3}, {0x5C, 3} },
      {
        {0x58, {0x08, 0x09, 0}},
        {0x5C, {0x08, 0x09, 0}},
        {0x4B, {0x0A, 0x0B, 0}},
        {0x4E, {0x0A, 0x0B, 0}},
        {0x2D, {0x04, 0x03, 8}},
        {0x52, {0x04, 0x03, 8}},
        {0x54, {0x04, 0x03, 8}}
      }, usbIO, controlDevice));
    _streamer = Ptr<Streamer>(new USBBulkStreamer(usbIO, controlDevice, 0x82));
  }

  if(!_programmer->isInitialized() || !_streamer->isInitialized())
    return false;

  /* TPL0102 - remove non-volatile access */

  if (!_programmer->writeRegister(0x5410, 0xC0))
    return false;

  if(!_addParameters({
    ParameterPtr(new TintinCDKMixVoltageParameter(*_programmer)),
    //ParameterPtr(new TintinCDKPVDDParameter(*_programmer)),
    ParameterPtr(new TintinCDKIlluminationPowerParameter(*_programmer)),
    ParameterPtr(new TintinCDKIlluminationPowerPercentParameter(*this, *_programmer)),
    }))
  {
    return false;
  }
  /* INA226 initializations: note byteswapped for now */
  if (!_programmer->writeRegister(0x4B00, 0x274F) ||
    !_programmer->writeRegister(0x4E00, 0x274F) ||
    !_programmer->writeRegister(0x4B05, 0x4807) ||
    !_programmer->writeRegister(0x4E05, 0x4F1B)
  )
    return false;
  /*
  // Settings for mix voltage and PVDD
  if(!_programmer->writeRegister(0x2D06, 0xFF) ||
    !_programmer->writeRegister(0x2D04, 0x40) ||
    !_programmer->writeRegister(0x2D05, 0x94) ||
    !_programmer->writeRegister(0x2D0D, 0x40) ||
    !_programmer->writeRegister(0x2D0E, 0xB8) ||
    !_programmer->writeRegister(0x2D0F, 0xFF)
  )
    return false;
	*/

  if(!ToFTintinCamera::_init())
    return false;

  return true;
}

bool TintinCDKCamera::_initStartParams()
{
  USBDevice &d = (USBDevice &)*_device;

  if(!ToFTintinCamera::_initStartParams())
    return false;

  if (!set(TILLUM_SLAVE_ADDR, 0x72U))
    return false;

  if ((d.productID() == TINTIN_CDK_PRODUCT_BULK) && !set(BLK_HEADER_EN, false))
    return false;

  return true;
}

bool TintinCDKCamera::_getFieldOfView(float &fovHalfAngle) const
{
  fovHalfAngle = (87/2.0f)*(M_PI/180.0f);
  return true;
}

bool TintinCDKCamera::_setStreamerFrameSize(const FrameSize &s)
{
  UVCStreamer *uvcStreamer = dynamic_cast<UVCStreamer *>(&*_streamer);
  USBBulkStreamer *bulkStreamer = dynamic_cast<USBBulkStreamer *>(&*_streamer);
  USBDevice &d = (USBDevice &)*_device;

  VideoMode m;
  m.frameSize = s;

  int bytesPerPixel;

  if(!_get(PIXEL_DATA_SIZE, bytesPerPixel))
  {
    logger(LOG_ERROR) << "TintinCDKCamera: Could not get current bytes per pixel" << std::endl;
    return false;
  }

  if(!_getFrameRate(m.frameRate))
  {
    logger(LOG_ERROR) << "TintinCDKCamera: Could not get current frame rate" << std::endl;
    return false;
  }

  if ((d.productID() == TINTIN_CDK_PRODUCT_UVC))
  {
    if(bytesPerPixel == 4)
      m.frameSize.width *= 2;
    if (!uvcStreamer)
    {
      logger(LOG_ERROR) << "TintinCDKCamera: Streamer is not of type UVC" << std::endl;
      return false;
    }

    if(!uvcStreamer->setVideoMode(m))
    {
      logger(LOG_ERROR) << "TintinCDKCamera: Could not set video mode for UVC" << std::endl;
      return false;
    }
  }
  else if ((d.productID() == TINTIN_CDK_PRODUCT_BULK))
  {
    if (!bulkStreamer)
    {
      logger(LOG_ERROR) << "TintinCDKCamera: Streamer is not of type Bulk" << std::endl;
      return false;
    }

    if (!bulkStreamer->setBufferSize(s.width * s.height * bytesPerPixel))
    {
      logger(LOG_ERROR) << "TintinCDKCamera: Could not set buffer size for bulk transfer" << std::endl;
      return false;
    }
  }

  return true;
}

bool TintinCDKCamera::_getSupportedVideoModes(Vector<SupportedVideoMode> &supportedVideoModes) const
{
  USBDevice &d = (USBDevice &)*_device;

  if (d.productID() == TINTIN_CDK_PRODUCT_UVC) {
    supportedVideoModes = Vector<SupportedVideoMode> {
      SupportedVideoMode(320,240,25,1,4),
      SupportedVideoMode(160,240,50,1,4),
      SupportedVideoMode(160,120,100,1,4),
      SupportedVideoMode(80,120,200,1,4),
      SupportedVideoMode(80,60,400,1,4),
      SupportedVideoMode(320,240,50,1,2),
      SupportedVideoMode(320,120,100,1,2),
      SupportedVideoMode(160,120,200,1,2),
      SupportedVideoMode(160,60,400,1,2),
      SupportedVideoMode(80,60,400,1,2),
    };
  } else {
    supportedVideoModes = Vector<SupportedVideoMode> {
      SupportedVideoMode(320,240,50,1,4),
      SupportedVideoMode(160,240,100,1,4),
      SupportedVideoMode(160,120,100,1,4),
      SupportedVideoMode(80,120,200,1,4),
      SupportedVideoMode(80,60,400,1,4),
      SupportedVideoMode(320,240,50,1,2),
      SupportedVideoMode(320,120,100,1,2),
      SupportedVideoMode(160,120,200,1,2),
      SupportedVideoMode(160,60,400,1,2),
      SupportedVideoMode(80,60,400,1,2),
    };
  }

  return true;
}

bool TintinCDKCamera::_getMaximumVideoMode(VideoMode &videoMode) const
{
  int bytesPerPixel;
  USBDevice &d = (USBDevice &)*_device;
  if(!_get(PIXEL_DATA_SIZE, bytesPerPixel))
  {
    logger(LOG_ERROR) << "TintinCDKCamera: Could not get current bytes per pixel" << std::endl;
    return false;
  }

  videoMode.frameSize.width = 320;
  videoMode.frameSize.height = 240;
  videoMode.frameRate.denominator = 1;
  if (d.productID() == TINTIN_CDK_PRODUCT_UVC) {
    videoMode.frameRate.numerator = (bytesPerPixel == 4)?25:50;
  } else {
    videoMode.frameRate.numerator = 30;
  }

  return true;
}

}
}<|endoftext|>