<commit_before>#include "Globals.h"
#include "Application.h"
#include "PhysBody3D.h"
#include "ModuleCamera3D.h"

ModuleCamera3D::ModuleCamera3D( bool start_enabled) : Module(start_enabled)
{
	CalculateViewMatrix();

	X = vec3(1.0f, 0.0f, 0.0f);
	Y = vec3(0.0f, 1.0f, 0.0f);
	Z = vec3(0.0f, 0.0f, 1.0f);

	Position = vec3(0.0f, 0.0f, 5.0f);
	Reference = vec3(0.0f, 0.0f, 0.0f);
	pivotal_point = vec3(0.0f, 0.0f, 0.0f);

	name = "camera";
}

ModuleCamera3D::~ModuleCamera3D()
{}
//---------------------------------------------------------------
bool ModuleCamera3D::Init(const JSON_Object* config_data)
{
	bool ret = true;

	if (SDL_Init(SDL_INIT_VIDEO) < 0)
	{
		LOG("SDL_VIDEO could not initialize! SDL_Error: %s\n", SDL_GetError());
		ret = false;
	}
	else {
		//LoadData from Config
		JSON_Value * config_data = json_parse_file("config.json");

		assert(config_data != nullptr);

		JSON_Object * object_data = json_value_get_object(config_data);
		JSON_Object * application_data = json_object_dotget_object(object_data, "App");
		JSON_Object * camera_data = json_object_dotget_object(application_data, "camera");
		Position.x = json_object_dotget_number(camera_data, "x");
		Position.y = json_object_dotget_number(camera_data, "y");
		Position.z = json_object_dotget_number(camera_data, "z");
	}
	return ret;
}
// -----------------------------------------------------------------
bool ModuleCamera3D::Start()
{
	LOG("Setting up the camera");
	bool ret = true;
	Look(Position, Reference, true);

	return ret;
}

// -----------------------------------------------------------------
bool ModuleCamera3D::CleanUp()
{
	LOG("Cleaning camera");

	return true;
}

// -----------------------------------------------------------------
update_status ModuleCamera3D::Update(float dt)
{
	ControlCamera(dt);

	// Recalculate matrix -------------
	CalculateViewMatrix();

	return UPDATE_CONTINUE;
}

// -----------------------------------------------------------------
void ModuleCamera3D::Look(const vec3 &Position, const vec3 &Reference, bool RotateAroundReference)
{
	this->Position = Position;
	this->Reference = Reference;

	Z = normalize(Position - Reference);
	X = normalize(cross(vec3(0.0f, 1.0f, 0.0f), Z));
	Y = cross(Z, X);

	if(!RotateAroundReference)
	{
		this->Reference = this->Position;
		this->Position += Z * 0.05f;
	}

	CalculateViewMatrix();
}

// -----------------------------------------------------------------
void ModuleCamera3D::LookAt( const vec3 &Spot)
{
	Reference = Spot;

	Z = normalize(Position - Reference);
	X = normalize(cross(vec3(0.0f, 1.0f, 0.0f), Z));
	Y = cross(Z, X);

	CalculateViewMatrix();
}

// -----------------------------------------------------------------
void ModuleCamera3D::Move(const vec3 &Movement)
{
	Position += Movement;
	Reference += Movement;

	CalculateViewMatrix();
}

// -----------------------------------------------------------------
float* ModuleCamera3D::GetViewMatrix()
{
	return &ViewMatrix;
}

// -----------------------------------------------------------------
void ModuleCamera3D::CalculateViewMatrix()
{
	ViewMatrix = mat4x4(X.x, Y.x, Z.x, 0.0f, X.y, Y.y, Z.y, 0.0f, X.z, Y.z, Z.z, 0.0f, -dot(X, Position), -dot(Y, Position), -dot(Z, Position), 1.0f);
	ViewMatrixInverse = inverse(ViewMatrix);
}

void ModuleCamera3D::ControlCamera(float dt)
{
	//FP Control
	if (App->input->GetKey(SDL_SCANCODE_W) == KEY_REPEAT)
	{
		Move(Z*-camera_speed*dt);
	}

	if (App->input->GetKey(SDL_SCANCODE_S) == KEY_REPEAT)
	{
		Move(Z*camera_speed*dt);
	}

	if (App->input->GetKey(SDL_SCANCODE_A) == KEY_REPEAT)
	{
		Move(X*-camera_speed*dt);
	}

	if (App->input->GetKey(SDL_SCANCODE_D) == KEY_REPEAT)
	{
		Move(X*camera_speed*dt);
	}

	if (App->input->GetMouseButton(SDL_BUTTON_RIGHT) == KEY_REPEAT)
	{
		int x = App->input->GetMouseXMotion();
		int y = App->input->GetMouseYMotion();
		if (y != 0)
		{
			if(y > 0)
				Position += Y*camera_sensitivity * dt*y;
			else if (y < 0)
				Position += Y*camera_sensitivity * dt*y;

			Look(Position, Reference, true);
		}
		if (x != 0)
		{
			if (x > 0)
				Position -= X*camera_sensitivity * dt*x;
			else if (x < 0)
				Position -= X*camera_sensitivity * dt*x;

			Look(Position, Reference, true);
		}

	}

	if (App->input->GetMouseZ() == 1)
	{
		Position -= Z;
	}
	else if (App->input->GetMouseZ() == -1)
	{
		Position += Z;
	}

	if (App->input->GetKey(SDL_SCANCODE_R) == KEY_DOWN)
	{
		ResetCamera();
	}

}

void ModuleCamera3D::ResetCamera()
{
	X = vec3(1.0f, 0.0f, 0.0f);
	Y = vec3(0.0f, 1.0f, 0.0f);
	Z = vec3(0.0f, 0.0f, 1.0f);

	Position = vec3(5.0f, 5.0f, 5.0f);
	Reference = vec3(0.0f, 0.0f, 0.0f);

	CalculateViewMatrix();
}

bool ModuleCamera3D::SaveConfig(JSON_Object* config_data)
{
	LOG("Saving data to config--------");

	//Save window data

	json_object_dotset_number(config_data, "x", Position.x);
	json_object_dotset_number(config_data, "y", Position.y);
	json_object_dotset_number(config_data, "z", Position.z);

	return true;

}<commit_msg>Camera Pan  implemented<commit_after>#include "Globals.h"
#include "Application.h"
#include "PhysBody3D.h"
#include "ModuleCamera3D.h"

ModuleCamera3D::ModuleCamera3D( bool start_enabled) : Module(start_enabled)
{
	CalculateViewMatrix();

	X = vec3(1.0f, 0.0f, 0.0f);
	Y = vec3(0.0f, 1.0f, 0.0f);
	Z = vec3(0.0f, 0.0f, 1.0f);

	Position = vec3(0.0f, 0.0f, 5.0f);
	Reference = vec3(0.0f, 0.0f, 0.0f);
	pivotal_point = vec3(0.0f, 0.0f, 0.0f);

	name = "camera";
}

ModuleCamera3D::~ModuleCamera3D()
{}
//---------------------------------------------------------------
bool ModuleCamera3D::Init(const JSON_Object* config_data)
{
	bool ret = true;

	if (SDL_Init(SDL_INIT_VIDEO) < 0)
	{
		LOG("SDL_VIDEO could not initialize! SDL_Error: %s\n", SDL_GetError());
		ret = false;
	}
	else {
		//LoadData from Config
		JSON_Value * config_data = json_parse_file("config.json");

		assert(config_data != nullptr);

		JSON_Object * object_data = json_value_get_object(config_data);
		JSON_Object * application_data = json_object_dotget_object(object_data, "App");
		JSON_Object * camera_data = json_object_dotget_object(application_data, "camera");
		Position.x = json_object_dotget_number(camera_data, "x");
		Position.y = json_object_dotget_number(camera_data, "y");
		Position.z = json_object_dotget_number(camera_data, "z");
	}
	return ret;
}
// -----------------------------------------------------------------
bool ModuleCamera3D::Start()
{
	LOG("Setting up the camera");
	bool ret = true;
	Look(Position, Reference, true);

	return ret;
}

// -----------------------------------------------------------------
bool ModuleCamera3D::CleanUp()
{
	LOG("Cleaning camera");

	return true;
}

// -----------------------------------------------------------------
update_status ModuleCamera3D::Update(float dt)
{
	ControlCamera(dt);

	// Recalculate matrix -------------
	CalculateViewMatrix();

	return UPDATE_CONTINUE;
}

// -----------------------------------------------------------------
void ModuleCamera3D::Look(const vec3 &Position, const vec3 &Reference, bool RotateAroundReference)
{
	this->Position = Position;
	this->Reference = Reference;

	Z = normalize(Position - Reference);
	X = normalize(cross(vec3(0.0f, 1.0f, 0.0f), Z));
	Y = cross(Z, X);

	if(!RotateAroundReference)
	{
		this->Reference = this->Position;
		this->Position += Z * 0.05f;
	}

	CalculateViewMatrix();
}

// -----------------------------------------------------------------
void ModuleCamera3D::LookAt( const vec3 &Spot)
{
	Reference = Spot;

	Z = normalize(Position - Reference);
	X = normalize(cross(vec3(0.0f, 1.0f, 0.0f), Z));
	Y = cross(Z, X);

	CalculateViewMatrix();
}

// -----------------------------------------------------------------
void ModuleCamera3D::Move(const vec3 &Movement)
{
	Position += Movement;
	Reference += Movement;

	CalculateViewMatrix();
}

// -----------------------------------------------------------------
float* ModuleCamera3D::GetViewMatrix()
{
	return &ViewMatrix;
}

// -----------------------------------------------------------------
void ModuleCamera3D::CalculateViewMatrix()
{
	ViewMatrix = mat4x4(X.x, Y.x, Z.x, 0.0f, X.y, Y.y, Z.y, 0.0f, X.z, Y.z, Z.z, 0.0f, -dot(X, Position), -dot(Y, Position), -dot(Z, Position), 1.0f);
	ViewMatrixInverse = inverse(ViewMatrix);
}

void ModuleCamera3D::ControlCamera(float dt)
{
	//FP Control
	if (App->input->GetKey(SDL_SCANCODE_W) == KEY_REPEAT)
	{
		Move(Z*-camera_speed*dt);
	}

	if (App->input->GetKey(SDL_SCANCODE_S) == KEY_REPEAT)
	{
		Move(Z*camera_speed*dt);
	}

	if (App->input->GetKey(SDL_SCANCODE_A) == KEY_REPEAT)
	{
		Move(X*-camera_speed*dt);
	}

	if (App->input->GetKey(SDL_SCANCODE_D) == KEY_REPEAT)
	{
		Move(X*camera_speed*dt);
	}

	if (App->input->GetMouseButton(SDL_BUTTON_RIGHT) == KEY_REPEAT)
	{
		int x = App->input->GetMouseXMotion();
		int y = App->input->GetMouseYMotion();
		if (App->input->GetKey(SDL_SCANCODE_LALT) == KEY_REPEAT)
		{
			if (y != 0)
			{
				Move(Y*camera_speed*dt*y);

			}
			if (x != 0)
			{
				Move(X*-camera_speed*dt*x);
			}
		}
		else
		{
			if (y != 0)
			{
				if (y > 0)
					Position += Y*camera_sensitivity * dt*y;
				else if (y < 0)
					Position += Y*camera_sensitivity * dt*y;

				Look(Position, Reference, true);
			}
			if (x != 0)
			{
				if (x > 0)
					Position -= X*camera_sensitivity * dt*x;
				else if (x < 0)
					Position -= X*camera_sensitivity * dt*x;

				Look(Position, Reference, true);
			}
		}

	}

	if (App->input->GetMouseZ() == 1)
	{
		Position -= Z;
	}
	else if (App->input->GetMouseZ() == -1)
	{
		Position += Z;
	}

	if (App->input->GetKey(SDL_SCANCODE_R) == KEY_DOWN)
	{
		ResetCamera();
	}

}

void ModuleCamera3D::ResetCamera()
{
	X = vec3(1.0f, 0.0f, 0.0f);
	Y = vec3(0.0f, 1.0f, 0.0f);
	Z = vec3(0.0f, 0.0f, 1.0f);

	Position = vec3(5.0f, 5.0f, 5.0f);
	Reference = vec3(0.0f, 0.0f, 0.0f);

	CalculateViewMatrix();
}

bool ModuleCamera3D::SaveConfig(JSON_Object* config_data)
{
	LOG("Saving data to config--------");

	//Save window data

	json_object_dotset_number(config_data, "x", Position.x);
	json_object_dotset_number(config_data, "y", Position.y);
	json_object_dotset_number(config_data, "z", Position.z);

	return true;

}<|endoftext|>


<commit_before>// Code based off of echo Server boost:
// http://www.boost.org/doc/libs/1_55_0/doc/html/boost_asio/example/cpp03/
//     echo/blocking_tcp_echo_server.cpp

#include <cstdlib>
#include <iostream>
#include <boost/bind.hpp>
#include <boost/format.hpp>
#include <boost/smart_ptr.hpp>
#include <boost/asio.hpp>
#include <boost/thread/thread.hpp>

#include "parser/ParserProcessor.h"

static const char *server_domain = "http://localhost";

using boost::asio::ip::tcp;

const int max_length = 1024;

typedef boost::shared_ptr<tcp::socket> socket_ptr;

std::string format_range(const std::string& format_string, const std::vector<std::string>& args)
{
    boost::format f(format_string);
    for (std::vector<std::string>::const_iterator it = args.begin(); it != args.end(); ++it) {
        f % *it;
    }
    return f.str();
}

void session(socket_ptr sock)
{
    try
    {
        for (;;)
        {
            char data[max_length];

            boost::system::error_code error;
            size_t length = sock->read_some(boost::asio::buffer(data), error);
            if (error == boost::asio::error::eof)
                break; // Connection closed cleanly by peer.
            else if (error)
                throw boost::system::system_error(error); // Some other error.
            // Make a string to return to the request with the header (%s)
            std::string response_str_format("HTTP/1.0 200 OK\nContent-Type: text/html\n\n"
                                             "%s");
            // Make a string from the received data
            std::string data_str(data);
            // Make an arguments array to pass into the response string
            std::vector<std::string> args;
            args.push_back(data_str);

            std::string response_str = format_range(response_str_format, args);

            boost::asio::write(*sock, boost::asio::buffer(response_str.c_str(),
                                                          response_str.size()));
        }
    }
    catch (std::exception& e)
    {
        std::cerr << "Exception in thread: " << e.what() << "\n";
    }
}

void server(boost::asio::io_service& io_service, unsigned short port)
{
    // Accept incoming connections
    tcp::acceptor a(io_service, tcp::endpoint(tcp::v4(), port));
    while(true)
    {
        socket_ptr sock(new tcp::socket(io_service));
        a.accept(*sock);
        boost::thread t(boost::bind(session, sock));
    }
}

int main(int argc, char* argv[])
{
    try
    {
        if (argc != 2) {
            printf("Usage: ./webserver <config file>\n");
            return 1;
        }

        // Parse the given configuration file
        NginxConfigParser config_parser;
        NginxConfig config;
        config_parser.Parse(argv[1], &config);

        // Get the port from the parsed configuration file
        ParserProcessor parser_processor = ParserProcessor(config);
        unsigned short port = parser_processor.get_port();

        // Print server address
        fprintf(stderr, "Starting server at %s:%d\n",server_domain, port);

        // Launch echo server
        boost::asio::io_service io_service;
        using namespace std;
        server(io_service, port);
    }
    catch (std::exception& e)
    {
        std::cerr << "Exception: " << e.what() << "\n";
    }

    return 0;
}

<commit_msg>Deleted the while loop so it will work on all browsers, also it stops instead of loading the entire time<commit_after>// Code based off of echo Server boost:
// http://www.boost.org/doc/libs/1_55_0/doc/html/boost_asio/example/cpp03/
//     echo/blocking_tcp_echo_server.cpp

#include <cstdlib>
#include <iostream>
#include <boost/bind.hpp>
#include <boost/format.hpp>
#include <boost/smart_ptr.hpp>
#include <boost/asio.hpp>
#include <boost/thread/thread.hpp>

#include "parser/ParserProcessor.h"

static const char *server_domain = "http://localhost";

using boost::asio::ip::tcp;

const int max_length = 1024;

typedef boost::shared_ptr<tcp::socket> socket_ptr;

std::string format_range(const std::string& format_string, const std::vector<std::string>& args)
{
    boost::format f(format_string);
    for (std::vector<std::string>::const_iterator it = args.begin(); it != args.end(); ++it) {
        f % *it;
    }
    return f.str();
}

void session(socket_ptr sock)
{
    try
    {

            char data[max_length];

            boost::system::error_code error;
            size_t length = sock->read_some(boost::asio::buffer(data), error);

            // Make a string to return to the request with the header (%s)
            std::string response_str_format("HTTP/1.0 200 OK\nContent-Type: text/html\n\n"
                                             "%s");
            // Make a string from the received data
            std::string data_str(data);
            // Make an arguments array to pass into the response string
            std::vector<std::string> args;
            args.push_back(data_str);

            std::string response_str = format_range(response_str_format, args);

            boost::asio::write(*sock, boost::asio::buffer(response_str.c_str(),
                                                          response_str.size()));
    }
    catch (std::exception& e)
    {
        std::cerr << "Exception in thread: " << e.what() << "\n";
    }
}

void server(boost::asio::io_service& io_service, unsigned short port)
{
    // Accept incoming connections
    tcp::acceptor a(io_service, tcp::endpoint(tcp::v4(), port));
    while(true)
    {
        socket_ptr sock(new tcp::socket(io_service));
        a.accept(*sock);
        boost::thread t(boost::bind(session, sock));
    }
}

int main(int argc, char* argv[])
{
    try
    {
        if (argc != 2) {
            printf("Usage: ./webserver <config file>\n");
            return 1;
        }

        // Parse the given configuration file
        NginxConfigParser config_parser;
        NginxConfig config;
        config_parser.Parse(argv[1], &config);

        // Get the port from the parsed configuration file
        ParserProcessor parser_processor = ParserProcessor(config);
        unsigned short port = parser_processor.get_port();

        // Print server address
        fprintf(stderr, "Starting server at %s:%d\n",server_domain, port);

        // Launch echo server
        boost::asio::io_service io_service;
        using namespace std;
        server(io_service, port);
    }
    catch (std::exception& e)
    {
        std::cerr << "Exception: " << e.what() << "\n";
    }

    return 0;
}

<|endoftext|>


<commit_before>/*
 * Copyright (c) 2011-2013, "Kira"
 * All rights reserved.
 *
 * Redistribution and use in source and binary forms, with or without
 * modification, are permitted provided that the following conditions are met:
 *
 * 1. Redistributions of source code must retain the above copyright notice, this
 *   list of conditions and the following disclaimer.
 * 2. Redistributions in binary form must reproduce the above copyright notice,
 *   this list of conditions and the following disclaimer in the documentation
 *   and/or other materials provided with the distribution.
 *
 * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
 * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
 * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
 * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR
 * ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
 * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
 * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
 * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
 * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
 * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
 */

// This code is HEAVILY based off of the Chromium websocket server source.
// You may view the license for Chromium in 3rdparty/LICENSE.chromium

#include "precompiled_headers.hpp"

#include "websocket.hpp"
#include "sha1.hpp"
#include "base64.hpp"
#include <stdlib.h>
#include <stdio.h>
#include <exception>
#include "startup_config.hpp"
#include "logging.hpp"

#include <map>
#include <vector>

#include <arpa/inet.h>
#include <netinet/in.h>

// NOTE NOTE NOTE NOTE
// These functions have side effects!
// The receive function for these classes DOES modify the input buffer!
// The send function DOES NOT modify the input buffer.
// This is an implementation detail. The input buffering is known to be simple.
// The output buffering is far more complex, involving splitting and other things,
// and thus is beyond the scope of these functions. Input buffering is simple to implement here,
// and saves passing around a size variable to then advance the input buffer only if needed.
// NOTE NOTE NOTE NOTE
namespace Websocket {

    /*
     * Due to some "issues" with the TLS proxy server mangling headers, we
     * have to lowercase headers to normalize the capitalization.
     */
    ProtocolVersion Acceptor::accept(std::string& input, std::string& output,
            std::string& ip) {
        ProtocolVersion ret = PROTOCOL_INCOMPLETE;
        try {
            DLOG(INFO) << "Attempting to parse a websocket header.";
            if (input.find("\r\n\r\n") == std::string::npos)
                return ret;

            std::map<std::string, std::string> headers;
            std::string line;
            std::string remainder = input;
            std::string::size_type end = remainder.find("\r\n");
            while (end != std::string::npos) {
                line = remainder.substr(0, end);
                remainder = remainder.substr(end + 2);

                std::string::size_type pos = line.find(": ");
                if (pos != std::string::npos) {
                    std::string key = line.substr(0, pos);
                    for (size_t i = 0; i < key.length(); ++i) {
                        key[i] = tolower(key[i]);
                    }
                    headers[key] = line.substr(pos + 2);
                }

                end = remainder.find("\r\n");
            }

            std::string outbuffer;

            // Copy the forwarded for ip into our output if it exists.
            // Caller checks for proper remote address before trusting this.
            if (headers.count("x-forwarded-for") != 0) {
                ip = headers["x-forwarded-for"];
            }
            if (headers.count("sec-websocket-version") != 0 && headers.count("sec-websocket-key") != 0) {
                DLOG(INFO) << "Found a Hybi websocket header.";
                if (Hybi::accept(headers["sec-websocket-key"], headers["sec-websocket-origin"], outbuffer) != WS_RESULT_OK) {
                    ret = PROTOCOL_BAD;
                } else {
                    ret = PROTOCOL_HYBI;
                }
            } else {
                ret = PROTOCOL_BAD;
            }
            output = outbuffer;
        } catch (std::exception e) {
            LOG(WARNING) << "Exception occurred in websocket accept. e.what: " << e.what();
            ret = PROTOCOL_BAD;
        } catch (...) {
            LOG(WARNING) << "Unexpected exception occured in websocket accept.";
            ret = PROTOCOL_BAD;
        }
        return ret;
    }

    static const unsigned int wsHeaderSize = 2;
    static const unsigned int wsMaskingKeySize = 4;
    static const unsigned int wsOpcodeMask = 0x0F;
    static const unsigned int wsMaskedMask = 0x80;
    static const unsigned int wsLengthMask = 0x7F;
    static const unsigned int wsSingleByteLength = 125;
    static const unsigned int wsTwoByteLength = 126;
    static const unsigned int wsEightByteLength = 127;
    static const unsigned int wsOpcodeText = 0x01;
    static const unsigned int wsOpcodeClose = 0x08;
    static const unsigned int wsMaximumClientFrameSize = 0x80000; //512kB should be sufficient for any client->server message.
    static const char* const wsMagicalGUID = "258EAFA5-E914-47DA-95CA-C5AB0DC85B11";

    WebSocketResult Hybi::accept(string& key, string& origin, string& output) {
        if (key.empty())
            return WS_RESULT_ERROR;

        //		if(origin.find("f-list.net") == string::npos)
        //		{
        //			return WS_RESULT_ERROR;
        //		}

        char buf[4096];
        bzero(&buf[0], sizeof (buf));
        int len = snprintf(&buf[0], sizeof (buf), "%s%s", key.c_str(), wsMagicalGUID);
        string keystr(&buf[0], len);
        bzero(&buf[0], sizeof (buf));
        string encodedkey;
        string hashkey = thirdparty::SHA1HashString(keystr);
        thirdparty::Base64Encode(hashkey, encodedkey);
        len = snprintf(&buf[0], sizeof (buf),
                "HTTP/1.1 101 Switching Protocols\r\n"
                "Upgrade: websocket\r\n"
                "Connection: Upgrade\r\n"
                "Sec-WebSocket-Accept: %s\r\n\r\n", encodedkey.c_str());
        string tmp(&buf[0], len);
        output.swap(tmp);
        return WS_RESULT_OK;
    }

    WebSocketResult Hybi::receive(std::string& input, std::string& output) {
        unsigned long rlen = input.length();
        if (rlen < wsHeaderSize)
            return WS_RESULT_INCOMPLETE;

        const char* msg = input.c_str();
        unsigned char b1 = *msg++;
        unsigned char b2 = *msg++;

        unsigned int opcode = b1 & wsOpcodeMask;
        bool masked = b2 & wsMaskedMask;
        unsigned int lengthhint = b2 & wsLengthMask;

        // Standard defines that all client to server communication must be masked.
        if (!masked)
            return WS_RESULT_ERROR;

        switch (opcode) {
                // Text
            case wsOpcodeText:
                break;
                // Close
            case wsOpcodeClose:
                return WS_RESULT_CLOSE;
            default:
                return WS_RESULT_ERROR;
        }

        uint64_t payload_length = 0;
        int lengthsize = 0;
        if (lengthhint > wsSingleByteLength) {
            lengthsize = 2;
            if (lengthhint == wsEightByteLength)
                lengthsize = 8;

            if (rlen < wsHeaderSize + lengthsize)
                return WS_RESULT_INCOMPLETE;

            for (int i = 0; i < lengthsize; ++i) {
                payload_length <<= 8;
                payload_length |= static_cast<unsigned char> (*msg++);
            }
        } else {
            payload_length = lengthhint;
        }

        if (payload_length > wsMaximumClientFrameSize)
            return WS_RESULT_ERROR;

        uint64_t totallen = (masked ? wsMaskingKeySize : 0) + payload_length;
        if (rlen < (wsHeaderSize + lengthsize + totallen))
            return WS_RESULT_INCOMPLETE;

        if (masked) {
            output.resize(payload_length);
            const char* mask = msg;
            msg += wsMaskingKeySize;
            for (unsigned int i = 0; i < payload_length; ++i) {
                output[i] = msg[i] ^ mask[i % wsMaskingKeySize];
            }
        } else {
            string tmp(msg, payload_length);
            output.swap(tmp);
        }

        input = input.substr(wsHeaderSize + lengthsize + totallen);

        return WS_RESULT_OK;
    }

    void Hybi::send(string& input, string& output) {
        std::vector<char> frame;
        unsigned int length = input.length();

        frame.push_back(0x80 | wsOpcodeText);

        if (length <= wsSingleByteLength) {
            frame.push_back(static_cast<char> (length));
        } else if (length <= 0xFFFF) {
            frame.push_back(wsTwoByteLength);
            frame.push_back((length & 0xFF00) >> 8);
            frame.push_back(length & 0xFF);
        } else {
            uint64_t qlength = length;
            frame.push_back(wsEightByteLength);
            for (size_t i = 0; i<sizeof (qlength); ++i) {
                frame.push_back(qlength & 0xFF);
                qlength >>= 8;
            }
        }
        frame.insert(frame.end(), input.c_str(), input.c_str() + length);
        string tmp(frame.begin(), frame.end());
        output.swap(tmp);
    }
}
<commit_msg>[ISSUE #31] Fix encoding of websocket frames larger than 65535 bytes.<commit_after>/*
 * Copyright (c) 2011-2013, "Kira"
 * All rights reserved.
 *
 * Redistribution and use in source and binary forms, with or without
 * modification, are permitted provided that the following conditions are met:
 *
 * 1. Redistributions of source code must retain the above copyright notice, this
 *   list of conditions and the following disclaimer.
 * 2. Redistributions in binary form must reproduce the above copyright notice,
 *   this list of conditions and the following disclaimer in the documentation
 *   and/or other materials provided with the distribution.
 *
 * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
 * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
 * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
 * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR
 * ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
 * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
 * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
 * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
 * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
 * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
 */

// This code is HEAVILY based off of the Chromium websocket server source.
// You may view the license for Chromium in 3rdparty/LICENSE.chromium

#include "precompiled_headers.hpp"

#include "websocket.hpp"
#include "sha1.hpp"
#include "base64.hpp"
#include <stdlib.h>
#include <stdio.h>
#include <exception>
#include "startup_config.hpp"
#include "logging.hpp"

#include <map>
#include <vector>

#include <arpa/inet.h>
#include <netinet/in.h>

// NOTE NOTE NOTE NOTE
// These functions have side effects!
// The receive function for these classes DOES modify the input buffer!
// The send function DOES NOT modify the input buffer.
// This is an implementation detail. The input buffering is known to be simple.
// The output buffering is far more complex, involving splitting and other things,
// and thus is beyond the scope of these functions. Input buffering is simple to implement here,
// and saves passing around a size variable to then advance the input buffer only if needed.
// NOTE NOTE NOTE NOTE
namespace Websocket {

    /*
     * Due to some "issues" with the TLS proxy server mangling headers, we
     * have to lowercase headers to normalize the capitalization.
     */
    ProtocolVersion Acceptor::accept(std::string& input, std::string& output,
            std::string& ip) {
        ProtocolVersion ret = PROTOCOL_INCOMPLETE;
        try {
            DLOG(INFO) << "Attempting to parse a websocket header.";
            if (input.find("\r\n\r\n") == std::string::npos)
                return ret;

            std::map<std::string, std::string> headers;
            std::string line;
            std::string remainder = input;
            std::string::size_type end = remainder.find("\r\n");
            while (end != std::string::npos) {
                line = remainder.substr(0, end);
                remainder = remainder.substr(end + 2);

                std::string::size_type pos = line.find(": ");
                if (pos != std::string::npos) {
                    std::string key = line.substr(0, pos);
                    for (size_t i = 0; i < key.length(); ++i) {
                        key[i] = tolower(key[i]);
                    }
                    headers[key] = line.substr(pos + 2);
                }

                end = remainder.find("\r\n");
            }

            std::string outbuffer;

            // Copy the forwarded for ip into our output if it exists.
            // Caller checks for proper remote address before trusting this.
            if (headers.count("x-forwarded-for") != 0) {
                ip = headers["x-forwarded-for"];
            }
            if (headers.count("sec-websocket-version") != 0 && headers.count("sec-websocket-key") != 0) {
                DLOG(INFO) << "Found a Hybi websocket header.";
                if (Hybi::accept(headers["sec-websocket-key"], headers["sec-websocket-origin"], outbuffer) != WS_RESULT_OK) {
                    ret = PROTOCOL_BAD;
                } else {
                    ret = PROTOCOL_HYBI;
                }
            } else {
                ret = PROTOCOL_BAD;
            }
            output = outbuffer;
        } catch (std::exception e) {
            LOG(WARNING) << "Exception occurred in websocket accept. e.what: " << e.what();
            ret = PROTOCOL_BAD;
        } catch (...) {
            LOG(WARNING) << "Unexpected exception occured in websocket accept.";
            ret = PROTOCOL_BAD;
        }
        return ret;
    }

    static const unsigned int wsHeaderSize = 2;
    static const unsigned int wsMaskingKeySize = 4;
    static const unsigned int wsOpcodeMask = 0x0F;
    static const unsigned int wsMaskedMask = 0x80;
    static const unsigned int wsLengthMask = 0x7F;
    static const unsigned int wsSingleByteLength = 125;
    static const unsigned int wsTwoByteLength = 126;
    static const unsigned int wsEightByteLength = 127;
    static const unsigned int wsOpcodeText = 0x01;
    static const unsigned int wsOpcodeClose = 0x08;
    static const unsigned int wsMaximumClientFrameSize = 0x80000; //512kB should be sufficient for any client->server message.
    static const char* const wsMagicalGUID = "258EAFA5-E914-47DA-95CA-C5AB0DC85B11";

    WebSocketResult Hybi::accept(string& key, string& origin, string& output) {
        if (key.empty())
            return WS_RESULT_ERROR;

        //		if(origin.find("f-list.net") == string::npos)
        //		{
        //			return WS_RESULT_ERROR;
        //		}

        char buf[4096];
        bzero(&buf[0], sizeof (buf));
        int len = snprintf(&buf[0], sizeof (buf), "%s%s", key.c_str(), wsMagicalGUID);
        string keystr(&buf[0], len);
        bzero(&buf[0], sizeof (buf));
        string encodedkey;
        string hashkey = thirdparty::SHA1HashString(keystr);
        thirdparty::Base64Encode(hashkey, encodedkey);
        len = snprintf(&buf[0], sizeof (buf),
                "HTTP/1.1 101 Switching Protocols\r\n"
                "Upgrade: websocket\r\n"
                "Connection: Upgrade\r\n"
                "Sec-WebSocket-Accept: %s\r\n\r\n", encodedkey.c_str());
        string tmp(&buf[0], len);
        output.swap(tmp);
        return WS_RESULT_OK;
    }

    WebSocketResult Hybi::receive(std::string& input, std::string& output) {
        unsigned long rlen = input.length();
        if (rlen < wsHeaderSize)
            return WS_RESULT_INCOMPLETE;

        const char* msg = input.c_str();
        unsigned char b1 = *msg++;
        unsigned char b2 = *msg++;

        unsigned int opcode = b1 & wsOpcodeMask;
        bool masked = b2 & wsMaskedMask;
        unsigned int lengthhint = b2 & wsLengthMask;

        // Standard defines that all client to server communication must be masked.
        if (!masked)
            return WS_RESULT_ERROR;

        switch (opcode) {
                // Text
            case wsOpcodeText:
                break;
                // Close
            case wsOpcodeClose:
                return WS_RESULT_CLOSE;
            default:
                return WS_RESULT_ERROR;
        }

        uint64_t payload_length = 0;
        int lengthsize = 0;
        if (lengthhint > wsSingleByteLength) {
            lengthsize = 2;
            if (lengthhint == wsEightByteLength)
                lengthsize = 8;

            if (rlen < wsHeaderSize + lengthsize)
                return WS_RESULT_INCOMPLETE;

            for (int i = 0; i < lengthsize; ++i) {
                payload_length <<= 8;
                payload_length |= static_cast<unsigned char> (*msg++);
            }
        } else {
            payload_length = lengthhint;
        }

        if (payload_length > wsMaximumClientFrameSize)
            return WS_RESULT_ERROR;

        uint64_t totallen = (masked ? wsMaskingKeySize : 0) + payload_length;
        if (rlen < (wsHeaderSize + lengthsize + totallen))
            return WS_RESULT_INCOMPLETE;

        if (masked) {
            output.resize(payload_length);
            const char* mask = msg;
            msg += wsMaskingKeySize;
            for (unsigned int i = 0; i < payload_length; ++i) {
                output[i] = msg[i] ^ mask[i % wsMaskingKeySize];
            }
        } else {
            string tmp(msg, payload_length);
            output.swap(tmp);
        }

        input = input.substr(wsHeaderSize + lengthsize + totallen);

        return WS_RESULT_OK;
    }

    void Hybi::send(string& input, string& output) {
        std::vector<unsigned char> frame;
        unsigned int length = input.length();

        frame.push_back(0x80 | wsOpcodeText);

        if (length <= wsSingleByteLength) {
            frame.push_back(static_cast<unsigned char> (length));
        } else if (length <= 0xFFFF) {
            frame.push_back(wsTwoByteLength);
            frame.push_back((length & 0xFF00) >> 8);
            frame.push_back(length & 0xFF);
        } else {
            uint64_t qlength = length;
            frame.push_back(wsEightByteLength);
            for (size_t i = 0; i < 8; ++i) {
                unsigned char length_piece = (qlength >> 8*(7-i)) & 0xFF;
                frame.push_back(length_piece);
            }
        }
        frame.insert(frame.end(), input.data(), input.data() + length);
        string tmp(frame.begin(), frame.end());
        output.swap(tmp);
    }
}
<|endoftext|>


<commit_before>// Generated by esidl 0.3.0.
// This file is expected to be modified for the Web IDL interface
// implementation.  Permission to use, copy, modify and distribute
// this file in any software license is hereby granted.

#include "HTMLOptGroupElementImp.h"

namespace org
{
namespace w3c
{
namespace dom
{
namespace bootstrap
{

bool HTMLOptGroupElementImp::getDisabled()
{
    // TODO: implement me!
    return 0;
}

void HTMLOptGroupElementImp::setDisabled(bool disabled)
{
    // TODO: implement me!
}

std::u16string HTMLOptGroupElementImp::getLabel()
{
    // TODO: implement me!
    return u"";
}

void HTMLOptGroupElementImp::setLabel(const std::u16string& label)
{
    // TODO: implement me!
}

}
}
}
}
<commit_msg>(HTMLOptGroupElementImp) : Process disabled and label attributes<commit_after>/*
 * Copyright 2013 Esrille Inc.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

#include "HTMLOptGroupElementImp.h"

namespace org
{
namespace w3c
{
namespace dom
{
namespace bootstrap
{

bool HTMLOptGroupElementImp::getDisabled()
{
    return getAttributeAsBoolean(u"disabled");
}

void HTMLOptGroupElementImp::setDisabled(bool disabled)
{
    setAttributeAsBoolean(u"disabled", disabled);
}

std::u16string HTMLOptGroupElementImp::getLabel()
{
    return getAttribute(u"label");
}

void HTMLOptGroupElementImp::setLabel(const std::u16string& label)
{
    setAttribute(u"label", label);
}

}
}
}
}
<|endoftext|>


<commit_before>/*
 *  yosys -- Yosys Open SYnthesis Suite
 *
 *  Copyright (C) 2012  Clifford Wolf <clifford@clifford.at>
 *
 *  Permission to use, copy, modify, and/or distribute this software for any
 *  purpose with or without fee is hereby granted, provided that the above
 *  copyright notice and this permission notice appear in all copies.
 *
 *  THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
 *  WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
 *  MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
 *  ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
 *  WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
 *  ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
 *  OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
 *
 */

#include "kernel/yosys.h"

USING_YOSYS_NAMESPACE
PRIVATE_NAMESPACE_BEGIN

int autoname_worker(Module *module)
{
	dict<Cell*, pair<int, IdString>> proposed_cell_names;
	dict<Wire*, pair<int, IdString>> proposed_wire_names;
	dict<Wire*, int> wire_score;
	int best_score = -1;

	for (auto cell : module->selected_cells())
	for (auto &conn : cell->connections())
	for (auto bit : conn.second)
		if (bit.wire != nullptr)
			wire_score[bit.wire]++;

	for (auto cell : module->selected_cells()) {
		if (cell->name[0] == '$') {
			for (auto &conn : cell->connections()) {
				string suffix = stringf("_%s_%s", log_id(cell->type), log_id(conn.first));
				for (auto bit : conn.second)
					if (bit.wire != nullptr && bit.wire->name[0] != '$') {
						IdString new_name(bit.wire->name.str() + suffix);
						int score = wire_score.at(bit.wire);
						if (cell->output(conn.first)) score = 0;
						score = 10000*score + new_name.size();
						if (!proposed_cell_names.count(cell) || score < proposed_cell_names.at(cell).first) {
							if (best_score < 0 || score < best_score)
								best_score = score;
							proposed_cell_names[cell] = make_pair(score, new_name);
						}
					}
			}
		} else {
			for (auto &conn : cell->connections()) {
				string suffix = stringf("_%s", log_id(conn.first));
				for (auto bit : conn.second)
					if (bit.wire != nullptr && bit.wire->name[0] == '$' && !bit.wire->port_id) {
						IdString new_name(cell->name.str() + suffix);
						int score = wire_score.at(bit.wire);
						if (cell->output(conn.first)) score = 0;
						score = 10000*score + new_name.size();
						if (!proposed_wire_names.count(bit.wire) || score < proposed_wire_names.at(bit.wire).first) {
							if (best_score < 0 || score < best_score)
								best_score = score;
							proposed_wire_names[bit.wire] = make_pair(score, new_name);
						}
					}
			}
		}
	}

	for (auto &it : proposed_cell_names) {
		if (best_score*2 < it.second.first)
			continue;
		IdString n = module->uniquify(it.second.second);
		log_debug("Rename cell %s in %s to %s.\n", log_id(it.first), log_id(module), log_id(n));
		module->rename(it.first, n);
	}

	for (auto &it : proposed_wire_names) {
		if (best_score*2 < it.second.first)
			continue;
		IdString n = module->uniquify(it.second.second);
		log_debug("Rename wire %s in %s to %s.\n", log_id(it.first), log_id(module), log_id(n));
		module->rename(it.first, n);
	}

	return proposed_cell_names.size() + proposed_wire_names.size();
}

struct AutonamePass : public Pass {
	AutonamePass() : Pass("autoname", "automatically assign names to objects") { }
	void help() override
	{
		//   |---v---|---v---|---v---|---v---|---v---|---v---|---v---|---v---|---v---|---v---|
		log("\n");
		log("    autoname [selection]\n");
		log("\n");
		log("Assign auto-generated public names to objects with private names (the ones\n");
		log("with $-prefix).\n");
		log("\n");
	}
	void execute(std::vector<std::string> args, RTLIL::Design *design) override
	{
		size_t argidx;
		for (argidx = 1; argidx < args.size(); argidx++)
		{
			// if (args[argidx] == "-foo") {
			// 	foo = true;
			// 	continue;
			// }
			break;
		}

		log_header(design, "Executing AUTONAME pass.\n");

		for (auto module : design->selected_modules())
		{
			int count = 0, iter = 0;
			while (1) {
				iter++;
				int n = autoname_worker(module);
				if (!n) break;
				count += n;
			}
			if (count > 0)
				log("Renamed %d objects in module %s (%d iterations).\n", count, log_id(module), iter);
		}
	}
} AutonamePass;

PRIVATE_NAMESPACE_END
<commit_msg>autoname: simple perf optimizations<commit_after>/*
 *  yosys -- Yosys Open SYnthesis Suite
 *
 *  Copyright (C) 2012  Clifford Wolf <clifford@clifford.at>
 *
 *  Permission to use, copy, modify, and/or distribute this software for any
 *  purpose with or without fee is hereby granted, provided that the above
 *  copyright notice and this permission notice appear in all copies.
 *
 *  THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
 *  WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
 *  MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
 *  ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
 *  WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
 *  ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
 *  OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
 *
 */

#include "kernel/yosys.h"

USING_YOSYS_NAMESPACE
PRIVATE_NAMESPACE_BEGIN

int autoname_worker(Module *module, const dict<Wire*, int>& wire_score)
{
	dict<Cell*, pair<int, IdString>> proposed_cell_names;
	dict<Wire*, pair<int, IdString>> proposed_wire_names;
	int best_score = -1;

	for (auto cell : module->selected_cells()) {
		if (cell->name[0] == '$') {
			for (auto &conn : cell->connections()) {
				string suffix;
				for (auto bit : conn.second)
					if (bit.wire != nullptr && bit.wire->name[0] != '$') {
						if (suffix.empty())
							suffix = stringf("_%s_%s", log_id(cell->type), log_id(conn.first));
						IdString new_name(bit.wire->name.str() + suffix);
						int score = wire_score.at(bit.wire);
						if (cell->output(conn.first)) score = 0;
						score = 10000*score + new_name.size();
						if (!proposed_cell_names.count(cell) || score < proposed_cell_names.at(cell).first) {
							if (best_score < 0 || score < best_score)
								best_score = score;
							proposed_cell_names[cell] = make_pair(score, new_name);
						}
					}
			}
		} else {
			for (auto &conn : cell->connections()) {
				string suffix;
				for (auto bit : conn.second)
					if (bit.wire != nullptr && bit.wire->name[0] == '$' && !bit.wire->port_id) {
						if (suffix.empty())
							suffix = stringf("_%s", log_id(conn.first));
						IdString new_name(cell->name.str() + suffix);
						int score = wire_score.at(bit.wire);
						if (cell->output(conn.first)) score = 0;
						score = 10000*score + new_name.size();
						if (!proposed_wire_names.count(bit.wire) || score < proposed_wire_names.at(bit.wire).first) {
							if (best_score < 0 || score < best_score)
								best_score = score;
							proposed_wire_names[bit.wire] = make_pair(score, new_name);
						}
					}
			}
		}
	}

	for (auto &it : proposed_cell_names) {
		if (best_score*2 < it.second.first)
			continue;
		IdString n = module->uniquify(it.second.second);
		log_debug("Rename cell %s in %s to %s.\n", log_id(it.first), log_id(module), log_id(n));
		module->rename(it.first, n);
	}

	for (auto &it : proposed_wire_names) {
		if (best_score*2 < it.second.first)
			continue;
		IdString n = module->uniquify(it.second.second);
		log_debug("Rename wire %s in %s to %s.\n", log_id(it.first), log_id(module), log_id(n));
		module->rename(it.first, n);
	}

	return proposed_cell_names.size() + proposed_wire_names.size();
}

struct AutonamePass : public Pass {
	AutonamePass() : Pass("autoname", "automatically assign names to objects") { }
	void help() override
	{
		//   |---v---|---v---|---v---|---v---|---v---|---v---|---v---|---v---|---v---|---v---|
		log("\n");
		log("    autoname [selection]\n");
		log("\n");
		log("Assign auto-generated public names to objects with private names (the ones\n");
		log("with $-prefix).\n");
		log("\n");
	}
	void execute(std::vector<std::string> args, RTLIL::Design *design) override
	{
		size_t argidx;
		for (argidx = 1; argidx < args.size(); argidx++)
		{
			// if (args[argidx] == "-foo") {
			// 	foo = true;
			// 	continue;
			// }
			break;
		}

		log_header(design, "Executing AUTONAME pass.\n");

		for (auto module : design->selected_modules())
		{
			dict<Wire*, int> wire_score;
			for (auto cell : module->selected_cells())
			for (auto &conn : cell->connections())
			for (auto bit : conn.second)
				if (bit.wire != nullptr)
					wire_score[bit.wire]++;

			int count = 0, iter = 0;
			while (1) {
				iter++;
				int n = autoname_worker(module, wire_score);
				if (!n) break;
				count += n;
			}
			if (count > 0)
				log("Renamed %d objects in module %s (%d iterations).\n", count, log_id(module), iter);
		}
	}
} AutonamePass;

PRIVATE_NAMESPACE_END
<|endoftext|>


<commit_before>/* json_feeder.cc
   Wolfgang Sourdeau, February 2013
   Copyright (c) 2013 Datacratic.  All rights reserved.

   A utility that feeds a stream of JSON samples to an HTTP server.
 */

#include <string>

#include <boost/program_options/cmdline.hpp>
#include <boost/program_options/options_description.hpp>
#include <boost/program_options/positional_options.hpp>
#include <boost/program_options/parsers.hpp>
#include <boost/program_options/variables_map.hpp>

#include <curlpp/Easy.hpp>
#include <curlpp/Info.hpp>
#include <curlpp/Infos.hpp>
#include <curlpp/Options.hpp>

#include "jml/utils/filter_streams.h"

using namespace std;
using namespace boost::program_options;
using namespace curlpp;

struct JsonFeeder {
    JsonFeeder(string uri, string filename,
               bool printRequests, bool printResponses,
               int maxSamples = 1000)
        : serverUri(uri), filename(filename), jsonStream(filename),
          printRequests(printRequests), printResponses(printResponses),
          maxSamples(maxSamples)
        {}

    void perform()
    {
        int sampleNum;

        for (sampleNum = 0; jsonStream && sampleNum < maxSamples;
             sampleNum++) {
            string current;
            getline(jsonStream, current);

            if (current == "") {
                jsonStream = ML::filter_istream(filename);
                getline(jsonStream, current);
            }

            Easy client;

            /* perform request */
            client.setOpt(options::Url(serverUri));

            client.setOpt(options::Post(true));
            client.setOpt(options::PostFields(current));

            list<string> headers;
            headers.push_back("Content-Type: application/json");
            headers.push_back("Expect:"); /* avoid dual-phase post */
            client.setOpt(options::HttpHeader(headers));

            /* separate response headers from body and store response body in "body" */
            stringstream body;
            client.setOpt(options::TcpNoDelay(true));
            client.setOpt(options::Header(false));
            client.setOpt(options::WriteStream(&body));
            client.perform();

            if (sampleNum > 0 && (printRequests || printResponses)) {
                cerr << "----------------------------" << endl
                     << "sample: " << sampleNum << endl;
            }

            if (printRequests) {
                cerr << "rq body: " << current << endl;
            }

            if (printResponses) {
                int code = infos::ResponseCode::get(client);
                cerr << "resp. code: " << code << endl
                     << "resp. body: " << body.str() << endl;
            }
        }

        cerr << "posted " << sampleNum << " samples" << endl;
    }

    string serverUri;
    string filename;
    ML::filter_istream jsonStream;
    bool printRequests;
    bool printResponses;
    int maxSamples;
};

int main(int argc, char *argv[])
{
    string serverUri;
    string filename;
    bool printRequests(false), printResponses(false);

    {
        using namespace boost::program_options;

        options_description configuration_options("Configuration options");

        configuration_options.add_options()
            ("server-uri,s", value(&serverUri),
             "URI of server to feed")
            ("filename,f", value(&filename),
             "filename")
            ("printrequests", value(&printRequests)->zero_tokens(),
             "print requests on console")
            ("printresponses", value(&printResponses)->zero_tokens(),
             "print responses on console");

        options_description all_opt;
        all_opt.add(configuration_options);
        all_opt.add_options()
            ("help,h", "print this message");

        variables_map vm;
        store(command_line_parser(argc, argv)
              .options(all_opt)
              .run(),
              vm);
        notify(vm);

        if (vm.count("help")) {
            cerr << all_opt << endl;
            exit(1);
        }

        if (serverUri.empty()) {
            cerr << "'server-uri' parameter is required" << endl;
            exit(1);
        }

        if (filename.empty()) {
            cerr << "'filename' parameter is required" << endl;
            exit(1);
        }
    }

    JsonFeeder feeder(serverUri, filename, printRequests, printResponses);
    feeder.perform();

    return 0;
}
<commit_msg>added the ability to specify a minimal delay between requests and a number of requests to perform<commit_after>/* json_feeder.cc
   Wolfgang Sourdeau, February 2013
   Copyright (c) 2013 Datacratic.  All rights reserved.

   A utility that feeds a stream of JSON samples to an HTTP server.
 */

#include <string>

#include <boost/program_options/cmdline.hpp>
#include <boost/program_options/options_description.hpp>
#include <boost/program_options/positional_options.hpp>
#include <boost/program_options/parsers.hpp>
#include <boost/program_options/variables_map.hpp>

#include <curlpp/Easy.hpp>
#include <curlpp/Info.hpp>
#include <curlpp/Infos.hpp>
#include <curlpp/Options.hpp>

#include "jml/arch/exception.h"
#include "jml/arch/timers.h"
#include "jml/utils/filter_streams.h"

using namespace std;
using namespace boost::program_options;
using namespace curlpp;

int deltaDelayMs(const struct timeval & oldTime,
                 const struct timeval & newTime)
{
    int64_t deltaMuSecs;

    if (oldTime.tv_usec > newTime.tv_usec) {
        deltaMuSecs = ((1000000 + newTime.tv_usec - oldTime.tv_usec)
                       + (newTime.tv_sec - oldTime.tv_sec - 1) * 1000000);
    }
    else {
        deltaMuSecs = ((newTime.tv_usec - oldTime.tv_usec)
                       + (newTime.tv_sec - oldTime.tv_sec) * 1000000);
    }

    if (deltaMuSecs < 0)
        throw ML::Exception("the future must not occur before the past");

    return deltaMuSecs / 1000;
}

struct JsonFeeder {
    JsonFeeder(string uri, string filename,
               int nSamples, int delayMs,
               bool printRequests, bool printResponses)
        : serverUri(uri), filename(filename), jsonStream(filename),
          nSamples(nSamples), delayMs(delayMs),
          printRequests(printRequests), printResponses(printResponses)
        {}

    void perform()
    {
        int sampleNum;
        struct timeval lastRequest;

        for (sampleNum = 0; jsonStream && sampleNum < nSamples;
             sampleNum++) {
            string current;
            struct timeval thisRequest, thisResponse;
            getline(jsonStream, current);

            if (current == "") {
                /* start over from the beginning of the file */
                jsonStream = ML::filter_istream(filename);
                getline(jsonStream, current);
            }

            if (delayMs > 0) {
                ::gettimeofday(&thisRequest, NULL);
                if (sampleNum > 0) {
                    int deltaRqMs = deltaDelayMs(lastRequest, thisRequest);
                    // printf("deltaRqMs: %d\n", deltaRqMs);
                    if (deltaRqMs < delayMs) {
                        float sleepTime = (float) (delayMs - deltaRqMs) / 1000;
                        // cerr << "sleeping for " << sleepTime << " secs\n";
                        ML::sleep(sleepTime);
                        ::gettimeofday(&thisRequest, NULL);
                    }
                }
                lastRequest = thisRequest;
            }

            Easy client;

            /* perform request */
            client.setOpt(options::Url(serverUri));

            client.setOpt(options::Post(true));
            client.setOpt(options::PostFields(current));

            list<string> headers;
            headers.push_back("Content-Type: application/json");
            headers.push_back("Expect:"); /* avoid dual-phase post */
            client.setOpt(options::HttpHeader(headers));

            /* separate response headers from body and store response body in "body" */
            stringstream body;
            client.setOpt(options::TcpNoDelay(true));
            client.setOpt(options::Header(false));
            client.setOpt(options::WriteStream(&body));
            client.perform();

            if (delayMs > 0) {
                ::gettimeofday(&thisResponse, NULL);
                int deltaRqMs = deltaDelayMs(thisRequest, thisResponse);
                cerr << "request took " << deltaRqMs << " millisecs\n";
            }

            if (sampleNum > 0 && (printRequests || printResponses)) {
                cerr << "----------------------------" << endl
                     << "sample: " << sampleNum << endl;
            }

            if (printRequests) {
                cerr << "rq body: " << current << endl;
            }

            if (printResponses) {
                int code = infos::ResponseCode::get(client);
                cerr << "resp. code: " << code << endl
                     << "resp. body: " << body.str() << endl;
            }
        }

        cerr << "posted " << sampleNum << " samples" << endl;
    }

    string serverUri;
    string filename;
    ML::filter_istream jsonStream;
    int nSamples;
    int delayMs;
    bool printRequests;
    bool printResponses;
};

int main(int argc, char *argv[])
{
    string serverUri;
    string filename;
    int delay(0);
    int nSamples(1000);
    bool printRequests(false), printResponses(false);

    {
        using namespace boost::program_options;

        options_description configuration_options("Configuration options");

        configuration_options.add_options()
            ("server-uri,s", value(&serverUri),
             "URI of server to feed")
            ("filename,f", value(&filename),
             "filename")
            ("n-samples,n", value(&nSamples),
             "number of requests to perform")
            ("rq-delay,d", value(&delay),
             "minimal delay (in ms, between requests)")
            ("printrequests", value(&printRequests)->zero_tokens(),
             "print requests on console")
            ("printresponses", value(&printResponses)->zero_tokens(),
             "print responses on console");

        options_description all_opt;
        all_opt.add(configuration_options);
        all_opt.add_options()
            ("help,h", "print this message");

        variables_map vm;
        store(command_line_parser(argc, argv)
              .options(all_opt)
              .run(),
              vm);
        notify(vm);

        if (vm.count("help")) {
            cerr << all_opt << endl;
            exit(1);
        }

        if (serverUri.empty()) {
            cerr << "'server-uri' parameter is required" << endl;
            exit(1);
        }

        if (filename.empty()) {
            cerr << "'filename' parameter is required" << endl;
            exit(1);
        }
    }

    JsonFeeder feeder(serverUri, filename, nSamples, delay,
                      printRequests, printResponses);
    feeder.perform();

    return 0;
}
<|endoftext|>


<commit_before>#ifdef STAN_OPENCL
#include <stan/math/prim.hpp>
#include <stan/math/opencl/copy.hpp>
#include <stan/math/opencl/matrix_cl_view.hpp>
#include <stan/math/opencl/matrix_cl.hpp>
#include <stan/math/opencl/triangular_transpose.hpp>
#include <gtest/gtest.h>
#include <algorithm>

TEST(MathMatrixCL, triangular_transpose_m_exception_pass) {
  stan::math::matrix_cl<double> m1(1, 1);
  stan::math::matrix_cl<double> m0;
  stan::math::matrix_cl<double> m2(5, 3);
  stan::math::matrix_cl<double> m3(3, 4);

  EXPECT_NO_THROW(
      m0.triangular_transpose<stan::math::TriangularMapCL::LowerToUpper>());
  EXPECT_NO_THROW(
      m0.triangular_transpose<stan::math::TriangularMapCL::UpperToLower>());
  EXPECT_NO_THROW(
      m1.triangular_transpose<stan::math::TriangularMapCL::LowerToUpper>());
  EXPECT_NO_THROW(
      m1.triangular_transpose<stan::math::TriangularMapCL::UpperToLower>());
  EXPECT_THROW(
      m2.triangular_transpose<stan::math::TriangularMapCL::LowerToUpper>(),
      std::invalid_argument);
  EXPECT_THROW(
      m2.triangular_transpose<stan::math::TriangularMapCL::UpperToLower>(),
      std::invalid_argument);
  EXPECT_THROW(
      m3.triangular_transpose<stan::math::TriangularMapCL::LowerToUpper>(),
      std::invalid_argument);
  EXPECT_THROW(
      m3.triangular_transpose<stan::math::TriangularMapCL::UpperToLower>(),
      std::invalid_argument);
}

TEST(MathMatrixCL, triangular_transpose_m_pass) {
  stan::math::matrix_d m0(2, 2);
  stan::math::matrix_d m0_dst(2, 2);
  m0 << 1, 2, 3, 4;

  stan::math::matrix_cl<double> m00(m0);
  stan::math::matrix_cl<double> m11(m0);

  EXPECT_NO_THROW(
      m00.triangular_transpose<stan::math::TriangularMapCL::LowerToUpper>());
  EXPECT_NO_THROW(m0_dst = stan::math::from_matrix_cl(m00));
  EXPECT_EQ(1, m0_dst(0, 0));
  EXPECT_EQ(3, m0_dst(0, 1));
  EXPECT_EQ(3, m0_dst(1, 0));
  EXPECT_EQ(4, m0_dst(1, 1));

  EXPECT_NO_THROW(
      m11.triangular_transpose<stan::math::TriangularMapCL::UpperToLower>());
  EXPECT_NO_THROW(m0_dst = stan::math::from_matrix_cl(m11));
  EXPECT_EQ(1, m0_dst(0, 0));
  EXPECT_EQ(2, m0_dst(0, 1));
  EXPECT_EQ(2, m0_dst(1, 0));
  EXPECT_EQ(4, m0_dst(1, 1));
}

#endif
<commit_msg>fix triangular_transpose_test<commit_after>#ifdef STAN_OPENCL
#include <stan/math/prim.hpp>
#include <stan/math/opencl/copy.hpp>
#include <stan/math/opencl/matrix_cl_view.hpp>
#include <stan/math/opencl/matrix_cl.hpp>
#include <stan/math/opencl/triangular_transpose.hpp>
#include <gtest/gtest.h>
#include <algorithm>

TEST(MathMatrixCL, triangular_transpose_m_exception_pass) {
  stan::math::matrix_cl<double> m1(1, 1);
  stan::math::matrix_cl<double> m0;
  stan::math::matrix_cl<double> m2(5, 3);
  stan::math::matrix_cl<double> m3(3, 4);

  EXPECT_NO_THROW(
      m0.triangular_transpose<stan::math::TriangularMapCL::LowerToUpper>());
  EXPECT_NO_THROW(
      m0.triangular_transpose<stan::math::TriangularMapCL::UpperToLower>());
  EXPECT_NO_THROW(
      m1.triangular_transpose<stan::math::TriangularMapCL::LowerToUpper>());
  EXPECT_NO_THROW(
      m1.triangular_transpose<stan::math::TriangularMapCL::UpperToLower>());
  EXPECT_THROW(
      m2.triangular_transpose<stan::math::TriangularMapCL::LowerToUpper>(),
      std::invalid_argument);
  EXPECT_THROW(
      m2.triangular_transpose<stan::math::TriangularMapCL::UpperToLower>(),
      std::invalid_argument);
  EXPECT_THROW(
      m3.triangular_transpose<stan::math::TriangularMapCL::LowerToUpper>(),
      std::invalid_argument);
  EXPECT_THROW(
      m3.triangular_transpose<stan::math::TriangularMapCL::UpperToLower>(),
      std::invalid_argument);
}

TEST(MathMatrixCL, triangular_transpose_m_pass) {
  stan::math::matrix_d m0(2, 2);
  m0 << 1, 2, 3, 4;
  stan::math::matrix_d m1(2, 2);
  m1 << 1, 2, 3, 4;
  stan::math::matrix_d m0_dst(2, 2);

  stan::math::matrix_cl<double> m00(m0);
  stan::math::matrix_cl<double> m11(m1);

  EXPECT_NO_THROW(
      m00.triangular_transpose<stan::math::TriangularMapCL::LowerToUpper>());
  EXPECT_NO_THROW(m0_dst = stan::math::from_matrix_cl(m00));
  EXPECT_EQ(1, m0_dst(0, 0));
  EXPECT_EQ(3, m0_dst(0, 1));
  EXPECT_EQ(3, m0_dst(1, 0));
  EXPECT_EQ(4, m0_dst(1, 1));

  EXPECT_NO_THROW(
      m11.triangular_transpose<stan::math::TriangularMapCL::UpperToLower>());
  EXPECT_NO_THROW(m0_dst = stan::math::from_matrix_cl(m11));
  EXPECT_EQ(1, m0_dst(0, 0));
  EXPECT_EQ(2, m0_dst(0, 1));
  EXPECT_EQ(2, m0_dst(1, 0));
  EXPECT_EQ(4, m0_dst(1, 1));
}

#endif
<|endoftext|>


<commit_before><commit_msg>typo: ddjust -> adjust<commit_after><|endoftext|>


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

#ifndef SD_FU_TEXT_HXX
#define SD_FU_TEXT_HXX

#ifndef _EDITDATA_HXX
#include <svx/editdata.hxx>
#endif
#ifndef SD_FU_CONSTRUCT_HXX
#include "fuconstr.hxx"
#endif

struct StyleRequestData;
class SdrTextObj;
class OutlinerParaObject;

namespace sd {

/*************************************************************************
|*
|* Basisklasse fuer Textfunktionen
|*
\************************************************************************/

class FuText
    : public FuConstruct
{
public:
    TYPEINFO();

    static FunctionReference Create( ViewShell* pViewSh, ::sd::Window* pWin, ::sd::View* pView, SdDrawDocument* pDoc, SfxRequest& rReq );
    virtual void DoExecute( SfxRequest& rReq );

    virtual BOOL KeyInput(const KeyEvent& rKEvt);
    virtual BOOL MouseMove(const MouseEvent& rMEvt);
    virtual BOOL MouseButtonUp(const MouseEvent& rMEvt);
    virtual BOOL MouseButtonDown(const MouseEvent& rMEvt);
    virtual BOOL Command(const CommandEvent& rCEvt);
    virtual BOOL RequestHelp(const HelpEvent& rHEvt);
    virtual void ReceiveRequest(SfxRequest& rReq);
    virtual void DoubleClick(const MouseEvent& rMEvt);

    virtual void Activate();           // Function aktivieren
    virtual void Deactivate();         // Function deaktivieren

    void    SetInEditMode(const MouseEvent& rMEvt, BOOL bQuickDrag);
    BOOL    DeleteDefaultText();
    BOOL    RestoreDefaultText();
    void    ObjectChanged();
    SdrTextObj* GetTextObj() { return pTextObj; }
    void    SetSpellOptions( ULONG& rCntrl );

    DECL_LINK(SpellError, void* );

    // #97016#
    virtual SdrObject* CreateDefaultObject(const sal_uInt16 nID, const Rectangle& rRectangle);

    /** is called when the currenct function should be aborted.

        This is used when a function gets a KEY_ESCAPE but can also
        be called directly.

        @returns true if a active function was aborted
    */
    virtual bool cancel();

    /** Call this method to tell a text function that the specified
        object is not in the edit mode anymore, respectively will not
        be in a short time.  If this method is not called and the edit
        mode of the object is canceled from the outside, i.e. not by
        the text function itself, the text function the pointer to the
        text object is not valid anymore and must not be accessed.

A better solution would be to make the text function a
        listener at the text object when the former starts the editing
        mode of the later.  This, however, would require changes
        beyond the scope of a bug fix, which brought up the
        problem (#111862#).

        @param pTextObject
            The text object which is not being edited anymore.  When
            this object is not the one used by this text function the
            call is silentyl ignored.
    */
    void TextEditingHasEnded (const SdrTextObj* pTextObject);

protected:
    FuText (ViewShell* pViewSh,
        ::sd::Window* pWin,
        ::sd::View* pView,
        SdDrawDocument* pDoc,
        SfxRequest& rReq);

    virtual void disposing();

    SdrTextObj*         pTextObj;
    Link                aOldLink;
    BOOL                bFirstObjCreated;

    SfxRequest&         rRequest;

private:
    // #97016#
    void ImpSetAttributesForNewTextObject(SdrTextObj* pTxtObj);
    void ImpSetAttributesFitToSize(SdrTextObj* pTxtObj);
    void ImpSetAttributesFitToSizeVertical(SdrTextObj* pTxtObj);
    void ImpSetAttributesFitCommon(SdrTextObj* pTxtObj);
};

} // end of namespace sd

#endif
<commit_msg>INTEGRATION: CWS impresstables2 (1.7.312); FILE MERGED 2007/05/03 09:23:28 cl 1.7.312.2: new table toolbar 2007/04/18 15:16:33 cl 1.7.312.1: #i72702# reworked SdrBeginTextEdit to be virtual at last!<commit_after>/*************************************************************************
 *
 *  OpenOffice.org - a multi-platform office productivity suite
 *
 *  $RCSfile: futext.hxx,v $
 *
 *  $Revision: 1.8 $
 *
 *  last change: $Author: rt $ $Date: 2008-03-12 11:44:16 $
 *
 *  The Contents of this file are made available subject to
 *  the terms of GNU Lesser General Public License Version 2.1.
 *
 *
 *    GNU Lesser General Public License Version 2.1
 *    =============================================
 *    Copyright 2005 by Sun Microsystems, Inc.
 *    901 San Antonio Road, Palo Alto, CA 94303, USA
 *
 *    This library is free software; you can redistribute it and/or
 *    modify it under the terms of the GNU Lesser General Public
 *    License version 2.1, as published by the Free Software Foundation.
 *
 *    This library is distributed in the hope that it will be useful,
 *    but WITHOUT ANY WARRANTY; without even the implied warranty of
 *    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 *    Lesser General Public License for more details.
 *
 *    You should have received a copy of the GNU Lesser General Public
 *    License along with this library; if not, write to the Free Software
 *    Foundation, Inc., 59 Temple Place, Suite 330, Boston,
 *    MA  02111-1307  USA
 *
 ************************************************************************/

#ifndef SD_FU_TEXT_HXX
#define SD_FU_TEXT_HXX

#ifndef _EDITDATA_HXX
#include <svx/editdata.hxx>
#endif
#ifndef SD_FU_CONSTRUCT_HXX
#include "fuconstr.hxx"
#endif
#include <svx/svdotext.hxx>

struct StyleRequestData;
class SdrTextObj;
class OutlinerParaObject;

namespace sd {

/*************************************************************************
|*
|* Basisklasse fuer Textfunktionen
|*
\************************************************************************/

class FuText
    : public FuConstruct
{
public:
    TYPEINFO();

    static FunctionReference Create( ViewShell* pViewSh, ::sd::Window* pWin, ::sd::View* pView, SdDrawDocument* pDoc, SfxRequest& rReq );
    virtual void DoExecute( SfxRequest& rReq );

    virtual BOOL KeyInput(const KeyEvent& rKEvt);
    virtual BOOL MouseMove(const MouseEvent& rMEvt);
    virtual BOOL MouseButtonUp(const MouseEvent& rMEvt);
    virtual BOOL MouseButtonDown(const MouseEvent& rMEvt);
    virtual BOOL Command(const CommandEvent& rCEvt);
    virtual BOOL RequestHelp(const HelpEvent& rHEvt);
    virtual void ReceiveRequest(SfxRequest& rReq);
    virtual void DoubleClick(const MouseEvent& rMEvt);

    virtual void Activate();           // Function aktivieren
    virtual void Deactivate();         // Function deaktivieren

    void    SetInEditMode(const MouseEvent& rMEvt, BOOL bQuickDrag);
    BOOL    DeleteDefaultText();
    SdrTextObj* GetTextObj() { return static_cast< SdrTextObj* >( mxTextObj.get() ); }

    DECL_LINK(SpellError, void* );

    // #97016#
    virtual SdrObject* CreateDefaultObject(const sal_uInt16 nID, const Rectangle& rRectangle);

    /** is called when the currenct function should be aborted.

        This is used when a function gets a KEY_ESCAPE but can also
        be called directly.

        @returns true if a active function was aborted
    */
    virtual bool cancel();

protected:
    FuText (ViewShell* pViewSh,
        ::sd::Window* pWin,
        ::sd::View* pView,
        SdDrawDocument* pDoc,
        SfxRequest& rReq);

    virtual void disposing();

    SdrObjectWeakRef    mxTextObj;
    Link                aOldLink;
    BOOL                bFirstObjCreated;

    SfxRequest&         rRequest;

private:
    // #97016#
    void ImpSetAttributesForNewTextObject(SdrTextObj* pTxtObj);
    void ImpSetAttributesFitToSize(SdrTextObj* pTxtObj);
    void ImpSetAttributesFitToSizeVertical(SdrTextObj* pTxtObj);
    void ImpSetAttributesFitCommon(SdrTextObj* pTxtObj);
};

} // end of namespace sd

#endif
<|endoftext|>


<commit_before>/*
  C++ interface test
*/
#include "libmemcached/memcached.hh"

#include <assert.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <sys/time.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <unistd.h>
#include <time.h>
#include "server.h"

#include "test.h"

#include <string>

using namespace std;

extern "C" {
   test_return basic_test(memcached_st *memc);
   test_return increment_test(memcached_st *memc);
   test_return basic_master_key_test(memcached_st *memc);
   test_return mget_result_function(memcached_st *memc);
   test_return mget_test(memcached_st *memc);
   void *world_create(void);
   void world_destroy(void *p);
}

test_return basic_test(memcached_st *memc)
{
  Memcached foo(memc);
  const string value_set("This is some data");
  string value;
  size_t value_length;

  foo.set("mine", value_set, 0, 0);
  value= foo.get("mine", &value_length);

  assert((memcmp(value.c_str(), value_set.c_str(), value_length) == 0));

  return TEST_SUCCESS;
}

test_return increment_test(memcached_st *memc)
{
  Memcached mcach(memc);
  bool rc;
  const string key("inctest");
  const string inc_value("1");
  string ret_value;
  uint64_t int_inc_value;
  uint64_t int_ret_value;
  size_t value_length;

  mcach.set(key, inc_value, 0, 0);
  ret_value= mcach.get(key, &value_length);
  printf("\nretvalue %s\n",ret_value.c_str());
  int_inc_value= uint64_t(atol(inc_value.c_str()));
  int_ret_value= uint64_t(atol(ret_value.c_str()));
  assert(int_ret_value == int_inc_value);

  rc= mcach.increment(key, 1, &int_ret_value);
  assert(rc == true);
  assert(int_ret_value == 2);

  rc= mcach.increment(key, 1, &int_ret_value);
  assert(rc == true);
  assert(int_ret_value == 3);

  rc= mcach.increment(key, 5, &int_ret_value);
  assert(rc == true);
  assert(int_ret_value == 8);

  return TEST_SUCCESS;
}

test_return basic_master_key_test(memcached_st *memc)
{
  Memcached foo(memc);
  const string value_set("Data for server A");
  const string master_key_a("server-a");
  const string master_key_b("server-b");
  const string key("xyz");
  string value;
  size_t value_length;

  foo.set_by_key(master_key_a, key, value_set, 0, 0);
  value= foo.get_by_key(master_key_a, key, &value_length);

  assert((memcmp(value.c_str(), value_set.c_str(), value_length) == 0));

  value= foo.get_by_key(master_key_b, key, &value_length);
  assert((memcmp(value.c_str(), value_set.c_str(), value_length) == 0));

  return TEST_SUCCESS;
}

/* Count the results */
static memcached_return callback_counter(memcached_st *ptr __attribute__((unused)),
                                     memcached_result_st *result __attribute__((unused)),
                                     void *context)
{
  unsigned int *counter= static_cast<unsigned int *>(context);

  *counter= *counter + 1;

  return MEMCACHED_SUCCESS;
}

test_return mget_result_function(memcached_st *memc)
{
  Memcached mc(memc);
  bool rc;
  string key1("fudge");
  string key2("son");
  string key3("food");
  vector<string> keys;
  keys.reserve(3);
  keys.push_back(key1);
  keys.push_back(key2);
  keys.push_back(key3);
  unsigned int counter;
  memcached_execute_function callbacks[1];

  /* We need to empty the server before we continue the test */
  rc= mc.flush(0);
  rc= mc.set_all(keys, keys, 50, 9);
  assert(rc == true);

  rc= mc.mget(keys);
  assert(rc == true);

  callbacks[0]= &callback_counter;
  counter= 0;
  rc= mc.fetch_execute(callbacks, static_cast<void *>(&counter), 1);

  assert(counter == 3);

  return TEST_SUCCESS;
}

test_return mget_test(memcached_st *memc)
{
  Memcached mc(memc);
  bool rc;
  memcached_return mc_rc;
  vector<string> keys;
  keys.reserve(3);
  keys.push_back("fudge");
  keys.push_back("son");
  keys.push_back("food");
  uint32_t flags;

  string return_key;
  size_t return_key_length;
  string return_value;
  size_t return_value_length;

  /* We need to empty the server before we continue the test */
  rc= mc.flush(0);
  assert(rc == true);

  rc= mc.mget(keys);
  assert(rc == true);

  while (mc.fetch(return_key, return_value, &return_key_length,
                  &return_value_length, &flags, &mc_rc))
  {
    assert(return_value.length() != 0);
  }
  assert(return_value_length == 0);
  assert(mc_rc == MEMCACHED_END);

  rc= mc.set_all(keys, keys, 50, 9);
  assert(rc == true);

  rc= mc.mget(keys);
  assert(rc == true);

  while ((mc.fetch(return_key, return_value, &return_key_length,
                   &return_value_length, &flags, &mc_rc)))
  {
    assert(return_value.length() != 0);
    assert(mc_rc == MEMCACHED_SUCCESS);
    assert(return_key_length == return_value_length);
    assert(!memcmp(return_value.c_str(), return_key.c_str(), return_value_length));
  }

  return TEST_SUCCESS;
}

test_st tests[] ={
  { "basic", 0, basic_test },
  { "basic_master_key", 0, basic_master_key_test },
  { "increment_test", 0, increment_test },
  { "mget", 1, mget_test },
  { "mget_result_function", 1, mget_result_function },
  {0, 0, 0}
};

collection_st collection[] ={
  {"block", 0, 0, tests},
  {0, 0, 0, 0}
};

#define SERVERS_TO_CREATE 1

extern "C" void *world_create(void)
{
  server_startup_st *construct;

  construct= (server_startup_st *)malloc(sizeof(server_startup_st));
  memset(construct, 0, sizeof(server_startup_st));

  construct->count= SERVERS_TO_CREATE;
  server_startup(construct);

  return construct;
}

void world_destroy(void *p)
{
  server_startup_st *construct= static_cast<server_startup_st *>(p);
  memcached_server_st *servers=
    static_cast<memcached_server_st *>(construct->servers);
  memcached_server_list_free(servers);

  server_shutdown(construct);
  free(construct);
}

void get_world(world_st *world)
{
  world->collections= collection;
  world->create= world_create;
  world->destroy= world_destroy;
}
<commit_msg>Some more updates to the C++ test file to remove solaris warnings.<commit_after>/*
  C++ interface test
*/
#include "libmemcached/memcached.hh"

#include <assert.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <sys/time.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <unistd.h>
#include <time.h>
#include "server.h"

#include "test.h"

#include <string>

using namespace std;

extern "C" {
   test_return basic_test(memcached_st *memc);
   test_return increment_test(memcached_st *memc);
   test_return basic_master_key_test(memcached_st *memc);
   test_return mget_result_function(memcached_st *memc);
   test_return mget_test(memcached_st *memc);
   memcached_return callback_counter(memcached_st *ptr __attribute__((unused)),
                                     memcached_result_st *result __attribute__((unused)),
                                     void *context);
   void *world_create(void);
   void world_destroy(void *p);
}

test_return basic_test(memcached_st *memc)
{
  Memcached foo(memc);
  const string value_set("This is some data");
  string value;
  size_t value_length;

  foo.set("mine", value_set, 0, 0);
  value= foo.get("mine", &value_length);

  assert((memcmp(value.c_str(), value_set.c_str(), value_length) == 0));

  return TEST_SUCCESS;
}

test_return increment_test(memcached_st *memc)
{
  Memcached mcach(memc);
  bool rc;
  const string key("inctest");
  const string inc_value("1");
  string ret_value;
  uint64_t int_inc_value;
  uint64_t int_ret_value;
  size_t value_length;

  mcach.set(key, inc_value, 0, 0);
  ret_value= mcach.get(key, &value_length);
  printf("\nretvalue %s\n",ret_value.c_str());
  int_inc_value= uint64_t(atol(inc_value.c_str()));
  int_ret_value= uint64_t(atol(ret_value.c_str()));
  assert(int_ret_value == int_inc_value);

  rc= mcach.increment(key, 1, &int_ret_value);
  assert(rc == true);
  assert(int_ret_value == 2);

  rc= mcach.increment(key, 1, &int_ret_value);
  assert(rc == true);
  assert(int_ret_value == 3);

  rc= mcach.increment(key, 5, &int_ret_value);
  assert(rc == true);
  assert(int_ret_value == 8);

  return TEST_SUCCESS;
}

test_return basic_master_key_test(memcached_st *memc)
{
  Memcached foo(memc);
  const string value_set("Data for server A");
  const string master_key_a("server-a");
  const string master_key_b("server-b");
  const string key("xyz");
  string value;
  size_t value_length;

  foo.set_by_key(master_key_a, key, value_set, 0, 0);
  value= foo.get_by_key(master_key_a, key, &value_length);

  assert((memcmp(value.c_str(), value_set.c_str(), value_length) == 0));

  value= foo.get_by_key(master_key_b, key, &value_length);
  assert((memcmp(value.c_str(), value_set.c_str(), value_length) == 0));

  return TEST_SUCCESS;
}

/* Count the results */
memcached_return callback_counter(memcached_st *ptr __attribute__((unused)),
                                  memcached_result_st *result __attribute__((unused)),
                                  void *context)
{
  unsigned int *counter= static_cast<unsigned int *>(context);

  *counter= *counter + 1;

  return MEMCACHED_SUCCESS;
}

test_return mget_result_function(memcached_st *memc)
{
  Memcached mc(memc);
  bool rc;
  string key1("fudge");
  string key2("son");
  string key3("food");
  vector<string> keys;
  keys.reserve(3);
  keys.push_back(key1);
  keys.push_back(key2);
  keys.push_back(key3);
  unsigned int counter;
  memcached_execute_function callbacks[1];

  /* We need to empty the server before we continue the test */
  rc= mc.flush(0);
  rc= mc.set_all(keys, keys, 50, 9);
  assert(rc == true);

  rc= mc.mget(keys);
  assert(rc == true);

  callbacks[0]= &callback_counter;
  counter= 0;
  rc= mc.fetch_execute(callbacks, static_cast<void *>(&counter), 1);

  assert(counter == 3);

  return TEST_SUCCESS;
}

test_return mget_test(memcached_st *memc)
{
  Memcached mc(memc);
  bool rc;
  memcached_return mc_rc;
  vector<string> keys;
  keys.reserve(3);
  keys.push_back("fudge");
  keys.push_back("son");
  keys.push_back("food");
  uint32_t flags;

  string return_key;
  size_t return_key_length;
  string return_value;
  size_t return_value_length;

  /* We need to empty the server before we continue the test */
  rc= mc.flush(0);
  assert(rc == true);

  rc= mc.mget(keys);
  assert(rc == true);

  while (mc.fetch(return_key, return_value, &return_key_length,
                  &return_value_length, &flags, &mc_rc))
  {
    assert(return_value.length() != 0);
  }
  assert(return_value_length == 0);
  assert(mc_rc == MEMCACHED_END);

  rc= mc.set_all(keys, keys, 50, 9);
  assert(rc == true);

  rc= mc.mget(keys);
  assert(rc == true);

  while ((mc.fetch(return_key, return_value, &return_key_length,
                   &return_value_length, &flags, &mc_rc)))
  {
    assert(return_value.length() != 0);
    assert(mc_rc == MEMCACHED_SUCCESS);
    assert(return_key_length == return_value_length);
    assert(!memcmp(return_value.c_str(), return_key.c_str(), return_value_length));
  }

  return TEST_SUCCESS;
}

test_st tests[] ={
  { "basic", 0, basic_test },
  { "basic_master_key", 0, basic_master_key_test },
  { "increment_test", 0, increment_test },
  { "mget", 1, mget_test },
  { "mget_result_function", 1, mget_result_function },
  {0, 0, 0}
};

collection_st collection[] ={
  {"block", 0, 0, tests},
  {0, 0, 0, 0}
};

#define SERVERS_TO_CREATE 1

extern "C" void *world_create(void)
{
  server_startup_st *construct;

  construct= (server_startup_st *)malloc(sizeof(server_startup_st));
  memset(construct, 0, sizeof(server_startup_st));

  construct->count= SERVERS_TO_CREATE;
  server_startup(construct);

  return construct;
}

void world_destroy(void *p)
{
  server_startup_st *construct= static_cast<server_startup_st *>(p);
  memcached_server_st *servers=
    static_cast<memcached_server_st *>(construct->servers);
  memcached_server_list_free(servers);

  server_shutdown(construct);
  free(construct);
}

void get_world(world_st *world)
{
  world->collections= collection;
  world->create= world_create;
  world->destroy= world_destroy;
}
<|endoftext|>