<commit_before>//=====================================================================//
/*!	@file
	@brief	キーボード入力を扱うクラス
	@author	平松邦仁 (hira@rvf-rc45.net)
*/
//=====================================================================//
#include "utils/keyboard.hpp"
#include "core/glcore.hpp"
#include <boost/foreach.hpp>

namespace sys {

	struct key_t {
		gl::device::key::type	key_type;
		char	normal_code;
		char	shift_code;
	};

	static const key_t us_key_type_tbls_[] = {
		{ gl::device::key::ESCAPE,        0x1b, 0x1b },
		{ gl::device::key::GRAVE_ACCENT,  '`', '~' },
		{ gl::device::key::_1,            '1', '!' },
		{ gl::device::key::_2,            '2', '@' },
		{ gl::device::key::_3,            '3', '#' },
		{ gl::device::key::_4,            '4', '$' },
		{ gl::device::key::_5,            '5', '%' },
		{ gl::device::key::_6,            '6', '^' },
		{ gl::device::key::_7,            '7', '&' },
		{ gl::device::key::_8,            '8', '*' },
		{ gl::device::key::_9,            '9', '(' },
		{ gl::device::key::_0,            '0', ')' },
		{ gl::device::key::MINUS,         '-', '_' },
		{ gl::device::key::EQUAL,         '=', '+' },
		{ gl::device::key::BACKSPACE,     0x08, 0x08 },
		{ gl::device::key::DELETE,        0x3f, 0x3f },
		{ gl::device::key::TAB,           0x09, 0x09 },
		{ gl::device::key::Q,             'Q', 'q' },
		{ gl::device::key::W,             'W', 'w' },
		{ gl::device::key::E,             'E', 'e' },
		{ gl::device::key::R,             'R', 'r' },
		{ gl::device::key::T,             'T', 't' },
		{ gl::device::key::Y,             'Y', 'y' },
		{ gl::device::key::U,             'U', 'u' },
		{ gl::device::key::I,             'I', 'i' },
		{ gl::device::key::O,             'O', 'o' },
		{ gl::device::key::P,             'P', 'p' },
		{ gl::device::key::LEFT_BRACKET,  '[', '{' },
		{ gl::device::key::RIGHT_BRACKET, ']', '}' },
		{ gl::device::key::BACKSLASH,     '\\', '|' },

		{ gl::device::key::A,             'A', 'a' },
		{ gl::device::key::S,             'S', 's' },
		{ gl::device::key::D,             'D', 'd' },
		{ gl::device::key::F,             'F', 'f' },
		{ gl::device::key::G,             'G', 'g' },
		{ gl::device::key::H,             'H', 'h' },
		{ gl::device::key::J,             'J', 'j' },
		{ gl::device::key::K,             'K', 'k' },
		{ gl::device::key::L,             'L', 'l' },
		{ gl::device::key::SEMICOLON,     ';', ':' },
		{ gl::device::key::APOSTROPHE,    '\'', '"' },
		{ gl::device::key::ENTER,         0x0d, 0x0d },

		{ gl::device::key::Z,             'Z', 'z' },
		{ gl::device::key::X,             'X', 'x' },
		{ gl::device::key::C,             'C', 'c' },
		{ gl::device::key::V,             'V', 'v' },
		{ gl::device::key::B,             'B', 'b' },
		{ gl::device::key::N,             'N', 'n' },
		{ gl::device::key::M,             'M', 'm' },
		{ gl::device::key::COMMA,         ',', '<' },
		{ gl::device::key::PERIOD,        '.', '>' },
		{ gl::device::key::SLASH,         '/', '?' },
		{ gl::device::key::SPACE,         ' ', ' ' },

		{ gl::device::key::RIGHT,         'Q'-0x40, 'Q'-0x40 },
		{ gl::device::key::LEFT,          'R'-0x40, 'R'-0x40 },
		{ gl::device::key::DOWN,          'S'-0x40, 'S'-0x40 },
		{ gl::device::key::UP,            'T'-0x40, 'T'-0x40 },
	};

	static const key_t jp_key_type_tbls_[] = {
		{ gl::device::key::ESCAPE,        0x1b, 0x1b },
//		{ gl::device::key::WORLD_1,       'a', 'a' },
		{ gl::device::key::_1,            '1', '!' },
		{ gl::device::key::_2,            '2', '"' },
		{ gl::device::key::_3,            '3', '#' },
		{ gl::device::key::_4,            '4', '$' },
		{ gl::device::key::_5,            '5', '%' },
		{ gl::device::key::_6,            '6', '&' },
		{ gl::device::key::_7,            '7', '\'' },
		{ gl::device::key::_8,            '8', '(' },
		{ gl::device::key::_9,            '9', ')' },
		{ gl::device::key::_0,            '0', '0' },
		{ gl::device::key::MINUS,         '-', '=' },
		{ gl::device::key::EQUAL,         ';', '+' },
		{ gl::device::key::BACKSPACE,     0x08, 0x08 },
		{ gl::device::key::DELETE,        0x3f, 0x3f },

		{ gl::device::key::TAB,           0x09, 0x09 },
		{ gl::device::key::Q,             'Q', 'q' },
		{ gl::device::key::W,             'W', 'w' },
		{ gl::device::key::E,             'E', 'e' },
		{ gl::device::key::R,             'R', 'r' },
		{ gl::device::key::T,             'T', 't' },
		{ gl::device::key::Y,             'Y', 'y' },
		{ gl::device::key::U,             'U', 'u' },
		{ gl::device::key::I,             'I', 'i' },
		{ gl::device::key::O,             'O', 'o' },
		{ gl::device::key::P,             'P', 'p' },
		{ gl::device::key::GRAVE_ACCENT,  '@', '`' },
		{ gl::device::key::LEFT_BRACKET,  '[', '{' },
		{ gl::device::key::RIGHT_BRACKET, ']', '}' },
		{ gl::device::key::BACKSLASH,     '\\', '|' },

		{ gl::device::key::A,             'A', 'a' },
		{ gl::device::key::S,             'S', 's' },
		{ gl::device::key::D,             'D', 'd' },
		{ gl::device::key::F,             'F', 'f' },
		{ gl::device::key::G,             'G', 'g' },
		{ gl::device::key::H,             'H', 'h' },
		{ gl::device::key::J,             'J', 'j' },
		{ gl::device::key::K,             'K', 'k' },
		{ gl::device::key::L,             'L', 'l' },
		{ gl::device::key::SEMICOLON,     ':', '*' },
		{ gl::device::key::APOSTROPHE,    '^', '~' },
		{ gl::device::key::ENTER,         0x0d, 0x0d },

		{ gl::device::key::Z,             'Z', 'z' },
		{ gl::device::key::X,             'X', 'x' },
		{ gl::device::key::C,             'C', 'c' },
		{ gl::device::key::V,             'V', 'v' },
		{ gl::device::key::B,             'B', 'b' },
		{ gl::device::key::N,             'N', 'n' },
		{ gl::device::key::M,             'M', 'm' },
		{ gl::device::key::COMMA,         ',', '<' },
		{ gl::device::key::PERIOD,        '.', '>' },
		{ gl::device::key::SLASH,         '/', '?' },
		{ gl::device::key::WORLD_2,       '\\', '_' },
		{ gl::device::key::SPACE,         ' ', ' ' },

		{ gl::device::key::RIGHT,         'Q'-0x40, 'Q'-0x40 },
		{ gl::device::key::LEFT,          'R'-0x40, 'R'-0x40 },
		{ gl::device::key::DOWN,          'S'-0x40, 'S'-0x40 },
		{ gl::device::key::UP,            'T'-0x40, 'T'-0x40 },
	};

#if 0
				INSERT    = 260,
				PAGE_UP   = 266,
				PAGE_DOWN = 267,
				HOME      = 268,
				END       = 269,

				CAPS_LOCK    = 280,
				SCROLL_LOCK  = 281,
				NUM_LOCK     = 282,
				PRINT_SCREEN = 283,
				PAUSE        = 284,

				LEFT_SHIFT    = 340,
				LEFT_CONTROL,
				LEFT_ALT,
				LEFT_SUPER,
				RIGHT_SHIFT,
				RIGHT_CONTROL,
				RIGHT_ALT,
				RIGHT_SUPER,
				SHIFT,
				CONTROL,
				ALT,
				SUPER,
				MENU,
#endif

	//-----------------------------------------------------------------//
	/*!
		@brief	サービス
	*/
	//-----------------------------------------------------------------//
	void keyboard::service()
	{
		using namespace gl;

		core& core = core::get_instance();
		const device& dev = core.get_device();

		input_.clear();
		bool caps = dev.get_level(device::key::STATE_CAPS_LOCK);
		const key_t* tbl;
		int n;
		if(core.keyboard_japan()) {
			tbl = jp_key_type_tbls_;
			n = sizeof(jp_key_type_tbls_) / sizeof(key_t);
		} else {
			tbl = us_key_type_tbls_;
			n = sizeof(us_key_type_tbls_) / sizeof(key_t);
		}
		bool repeat = false;
		for(int i = 0; i < n; ++i) {
			const key_t& t = tbl[i];
			if(dev.get_positive(t.key_type)) {
				char nc = t.normal_code;
				if(dev.get_level(device::key::CONTROL)) {
					if(nc >= 0x40) last_char_ = nc - 0x40;
					else last_char_ = nc;
				} else {
					bool f = dev.get_level(device::key::SHIFT);
					if(nc >= 'A' && nc <= 'Z') {
						if(caps) f = !f;
						if(f) last_char_ = nc;
						else last_char_ = t.shift_code;
					} else {
						if(!f) last_char_ = nc;
						else last_char_ = t.shift_code;
					}
				}
				input_ += last_char_;
				last_key_idx_ = i;
			}
			if(dev.get_level(t.key_type)) {
				if(repeat_enable_) {
					if(last_key_idx_ == i) {
						++repeat_delay_cnt_;
						repeat = true;
					}
				}
			}
		}
		if(repeat) {
			if(repeat_delay_cnt_ >= repeat_delay_) {
				++repeat_cycle_cnt_;
				if(repeat_cycle_cnt_ >= repeat_cycle_) {
					repeat_cycle_cnt_ = 0;
					if(last_char_) {
						input_ += last_char_;
					}
				}
			}
		} else {
			repeat_delay_cnt_ = 0;
			repeat_cycle_cnt_ = 0;
			last_char_ = 0;
		}
	}

}
<commit_msg>Update device bits<commit_after>//=====================================================================//
/*!	@file
	@brief	キーボード入力を扱うクラス
	@author	平松邦仁 (hira@rvf-rc45.net)
*/
//=====================================================================//
#include "utils/keyboard.hpp"
#include "core/glcore.hpp"
#include <boost/foreach.hpp>

namespace sys {

	struct key_t {
		gl::device::key	key_type;
		char	normal_code;
		char	shift_code;
	};

	static const key_t us_key_type_tbls_[] = {
		{ gl::device::key::ESCAPE,        0x1b, 0x1b },
		{ gl::device::key::GRAVE_ACCENT,  '`', '~' },
		{ gl::device::key::_1,            '1', '!' },
		{ gl::device::key::_2,            '2', '@' },
		{ gl::device::key::_3,            '3', '#' },
		{ gl::device::key::_4,            '4', '$' },
		{ gl::device::key::_5,            '5', '%' },
		{ gl::device::key::_6,            '6', '^' },
		{ gl::device::key::_7,            '7', '&' },
		{ gl::device::key::_8,            '8', '*' },
		{ gl::device::key::_9,            '9', '(' },
		{ gl::device::key::_0,            '0', ')' },
		{ gl::device::key::MINUS,         '-', '_' },
		{ gl::device::key::EQUAL,         '=', '+' },
		{ gl::device::key::BACKSPACE,     0x08, 0x08 },
		{ gl::device::key::DELETE,        0x3f, 0x3f },
		{ gl::device::key::TAB,           0x09, 0x09 },
		{ gl::device::key::Q,             'Q', 'q' },
		{ gl::device::key::W,             'W', 'w' },
		{ gl::device::key::E,             'E', 'e' },
		{ gl::device::key::R,             'R', 'r' },
		{ gl::device::key::T,             'T', 't' },
		{ gl::device::key::Y,             'Y', 'y' },
		{ gl::device::key::U,             'U', 'u' },
		{ gl::device::key::I,             'I', 'i' },
		{ gl::device::key::O,             'O', 'o' },
		{ gl::device::key::P,             'P', 'p' },
		{ gl::device::key::LEFT_BRACKET,  '[', '{' },
		{ gl::device::key::RIGHT_BRACKET, ']', '}' },
		{ gl::device::key::BACKSLASH,     '\\', '|' },

		{ gl::device::key::A,             'A', 'a' },
		{ gl::device::key::S,             'S', 's' },
		{ gl::device::key::D,             'D', 'd' },
		{ gl::device::key::F,             'F', 'f' },
		{ gl::device::key::G,             'G', 'g' },
		{ gl::device::key::H,             'H', 'h' },
		{ gl::device::key::J,             'J', 'j' },
		{ gl::device::key::K,             'K', 'k' },
		{ gl::device::key::L,             'L', 'l' },
		{ gl::device::key::SEMICOLON,     ';', ':' },
		{ gl::device::key::APOSTROPHE,    '\'', '"' },
		{ gl::device::key::ENTER,         0x0d, 0x0d },

		{ gl::device::key::Z,             'Z', 'z' },
		{ gl::device::key::X,             'X', 'x' },
		{ gl::device::key::C,             'C', 'c' },
		{ gl::device::key::V,             'V', 'v' },
		{ gl::device::key::B,             'B', 'b' },
		{ gl::device::key::N,             'N', 'n' },
		{ gl::device::key::M,             'M', 'm' },
		{ gl::device::key::COMMA,         ',', '<' },
		{ gl::device::key::PERIOD,        '.', '>' },
		{ gl::device::key::SLASH,         '/', '?' },
		{ gl::device::key::SPACE,         ' ', ' ' },

		{ gl::device::key::RIGHT,         'Q'-0x40, 'Q'-0x40 },
		{ gl::device::key::LEFT,          'R'-0x40, 'R'-0x40 },
		{ gl::device::key::DOWN,          'S'-0x40, 'S'-0x40 },
		{ gl::device::key::UP,            'T'-0x40, 'T'-0x40 },
	};

	static const key_t jp_key_type_tbls_[] = {
		{ gl::device::key::ESCAPE,        0x1b, 0x1b },
//		{ gl::device::key::WORLD_1,       'a', 'a' },
		{ gl::device::key::_1,            '1', '!' },
		{ gl::device::key::_2,            '2', '"' },
		{ gl::device::key::_3,            '3', '#' },
		{ gl::device::key::_4,            '4', '$' },
		{ gl::device::key::_5,            '5', '%' },
		{ gl::device::key::_6,            '6', '&' },
		{ gl::device::key::_7,            '7', '\'' },
		{ gl::device::key::_8,            '8', '(' },
		{ gl::device::key::_9,            '9', ')' },
		{ gl::device::key::_0,            '0', '0' },
		{ gl::device::key::MINUS,         '-', '=' },
		{ gl::device::key::EQUAL,         ';', '+' },
		{ gl::device::key::BACKSPACE,     0x08, 0x08 },
		{ gl::device::key::DELETE,        0x3f, 0x3f },

		{ gl::device::key::TAB,           0x09, 0x09 },
		{ gl::device::key::Q,             'Q', 'q' },
		{ gl::device::key::W,             'W', 'w' },
		{ gl::device::key::E,             'E', 'e' },
		{ gl::device::key::R,             'R', 'r' },
		{ gl::device::key::T,             'T', 't' },
		{ gl::device::key::Y,             'Y', 'y' },
		{ gl::device::key::U,             'U', 'u' },
		{ gl::device::key::I,             'I', 'i' },
		{ gl::device::key::O,             'O', 'o' },
		{ gl::device::key::P,             'P', 'p' },
		{ gl::device::key::GRAVE_ACCENT,  '@', '`' },
		{ gl::device::key::LEFT_BRACKET,  '[', '{' },
		{ gl::device::key::RIGHT_BRACKET, ']', '}' },
		{ gl::device::key::BACKSLASH,     '\\', '|' },

		{ gl::device::key::A,             'A', 'a' },
		{ gl::device::key::S,             'S', 's' },
		{ gl::device::key::D,             'D', 'd' },
		{ gl::device::key::F,             'F', 'f' },
		{ gl::device::key::G,             'G', 'g' },
		{ gl::device::key::H,             'H', 'h' },
		{ gl::device::key::J,             'J', 'j' },
		{ gl::device::key::K,             'K', 'k' },
		{ gl::device::key::L,             'L', 'l' },
		{ gl::device::key::SEMICOLON,     ':', '*' },
		{ gl::device::key::APOSTROPHE,    '^', '~' },
		{ gl::device::key::ENTER,         0x0d, 0x0d },

		{ gl::device::key::Z,             'Z', 'z' },
		{ gl::device::key::X,             'X', 'x' },
		{ gl::device::key::C,             'C', 'c' },
		{ gl::device::key::V,             'V', 'v' },
		{ gl::device::key::B,             'B', 'b' },
		{ gl::device::key::N,             'N', 'n' },
		{ gl::device::key::M,             'M', 'm' },
		{ gl::device::key::COMMA,         ',', '<' },
		{ gl::device::key::PERIOD,        '.', '>' },
		{ gl::device::key::SLASH,         '/', '?' },
		{ gl::device::key::WORLD_2,       '\\', '_' },
		{ gl::device::key::SPACE,         ' ', ' ' },

		{ gl::device::key::RIGHT,         'Q'-0x40, 'Q'-0x40 },
		{ gl::device::key::LEFT,          'R'-0x40, 'R'-0x40 },
		{ gl::device::key::DOWN,          'S'-0x40, 'S'-0x40 },
		{ gl::device::key::UP,            'T'-0x40, 'T'-0x40 },
	};

#if 0
				INSERT    = 260,
				PAGE_UP   = 266,
				PAGE_DOWN = 267,
				HOME      = 268,
				END       = 269,

				CAPS_LOCK    = 280,
				SCROLL_LOCK  = 281,
				NUM_LOCK     = 282,
				PRINT_SCREEN = 283,
				PAUSE        = 284,

				LEFT_SHIFT    = 340,
				LEFT_CONTROL,
				LEFT_ALT,
				LEFT_SUPER,
				RIGHT_SHIFT,
				RIGHT_CONTROL,
				RIGHT_ALT,
				RIGHT_SUPER,
				SHIFT,
				CONTROL,
				ALT,
				SUPER,
				MENU,
#endif

	//-----------------------------------------------------------------//
	/*!
		@brief	サービス
	*/
	//-----------------------------------------------------------------//
	void keyboard::service()
	{
		using namespace gl;

		core& core = core::get_instance();
		const device& dev = core.get_device();

		input_.clear();
		bool caps = dev.get_level(device::key::STATE_CAPS_LOCK);
		const key_t* tbl;
		int n;
		if(core.keyboard_japan()) {
			tbl = jp_key_type_tbls_;
			n = sizeof(jp_key_type_tbls_) / sizeof(key_t);
		} else {
			tbl = us_key_type_tbls_;
			n = sizeof(us_key_type_tbls_) / sizeof(key_t);
		}
		bool repeat = false;
		for(int i = 0; i < n; ++i) {
			const key_t& t = tbl[i];
			if(dev.get_positive(t.key_type)) {
				char nc = t.normal_code;
				if(dev.get_level(device::key::CONTROL)) {
					if(nc >= 0x40) last_char_ = nc - 0x40;
					else last_char_ = nc;
				} else {
					bool f = dev.get_level(device::key::SHIFT);
					if(nc >= 'A' && nc <= 'Z') {
						if(caps) f = !f;
						if(f) last_char_ = nc;
						else last_char_ = t.shift_code;
					} else {
						if(!f) last_char_ = nc;
						else last_char_ = t.shift_code;
					}
				}
				input_ += last_char_;
				last_key_idx_ = i;
			}
			if(dev.get_level(t.key_type)) {
				if(repeat_enable_) {
					if(last_key_idx_ == i) {
						++repeat_delay_cnt_;
						repeat = true;
					}
				}
			}
		}
		if(repeat) {
			if(repeat_delay_cnt_ >= repeat_delay_) {
				++repeat_cycle_cnt_;
				if(repeat_cycle_cnt_ >= repeat_cycle_) {
					repeat_cycle_cnt_ = 0;
					if(last_char_) {
						input_ += last_char_;
					}
				}
			}
		} else {
			repeat_delay_cnt_ = 0;
			repeat_cycle_cnt_ = 0;
			last_char_ = 0;
		}
	}

}
<|endoftext|>


<commit_before>/* GNE - Game Networking Engine, a portable multithreaded networking library.
 * Copyright (C) 2001 Jason Winnebeck (gillius@mail.rit.edu)
 * Project website: http://www.rit.edu/~jpw9607/
 *
 * This library is free software; you can redistribute it and/or
 * modify it under the terms of the GNU Lesser General Public
 * License as published by the Free Software Foundation; either
 * version 2.1 of the License, or (at your option) any later version.
 *
 * This library is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 * Lesser General Public License for more details.
 *
 * You should have received a copy of the GNU Lesser General Public
 * License along with this library; if not, write to the Free Software
 * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
 */

/**
 * exhello
 * Everyone knows the "Hello World" program.  Perhaps it's been coded
 * too many times.  However, the GNE coders just plain don't care ;).
 * This is an example to show the minimum code needed to connect and send
 * data, in this case, "Hello Server (or Client)!" to the other end of the
 * connection.  This program uses asyncronous event-driven methods.
 * Well... perhaps not the minimum.  Lots of errors can happen over network
 * connections that we have to handle for this program to properly execute
 * when conditions aren't perfectly ideal, like when we can't reach the
 * server.
 */

#include "../../include/gnelib.h"
#include <iostream>
#include <string>

using namespace std;
using namespace GNE;
using namespace GNE::Console;
using namespace GNE::PacketParser;

#include "shared.h"

class OurClient : public ConnectionListener {
public:
	OurClient() : conn(NULL) {
		mprintf("Client listener created.\n");
	}

	~OurClient() {
		mprintf("Client listener destroyed.\n");
	}

	void onDisconnect() {
		mprintf("Client just disconnected.\n");
    //This is an iffy practice.  If we do this, we have to be careful to
    //always note that each new connection we use this listener with gets
    //its own new copy which we don't destroy later.
		delete this;
	}

  void onConnect(SyncConnection& conn2) {
		conn = conn2.getConnection();
    mprintf("Connection to server successful.\n");
  }

	void onReceive() {
		Packet* message = conn->stream().getNextPacket();
		if (message->getType() == MIN_USER_ID) {
			HelloPacket* helloMessage = (HelloPacket*)message;
			mprintf("got message: \"");
			mprintf(helloMessage->getMessage().c_str());
			mprintf("\"\n");
		} else
			mprintf("got bad packet.\n");
		delete message;
	}

	void onFailure(const Error& error) {
		mprintf("Socket failure: %s\n", error.toString().c_str());
	}

	void onError(const Error& error) {
		mprintf("Socket error: %s\n", error.toString().c_str());
		conn->disconnect();
	}

  void onConnectFailure(const Error& error) {
    mprintf("Connection to server failed.\n");
		mprintf("GNE reported error: %s\n", error.toString().c_str());
  }
private:
	Connection* conn;
};

class OurServer : public ConnectionListener {
public:
  OurServer() : conn(NULL), received(false) {
		mprintf("Server instance created\n");
	}

  virtual ~OurServer() {
		mprintf("ServerConnection instance killed\n");
	}

	void onDisconnect() {
		mprintf("ServerConnection just disconnected.\n");
		if (!received)
			mprintf("No message received.\n");
		delete this;
	}

  void onNewConn(SyncConnection& conn2) {
		conn = conn2.getConnection();
    mprintf("Connection received from %s; waiting for message...\n", conn->getRemoteAddress(true).toString().c_str());
  }

	void onReceive() {
		Packet* message = conn->stream().getNextPacket();
		if (message->getType() == MIN_USER_ID) {
			HelloPacket* helloMessage = (HelloPacket*)message;
			mprintf("got message: \"");
			mprintf(helloMessage->getMessage().c_str());
			mprintf("\"\n");
			received = true;

			//Send Response
			mprintf("  Sending Response...\n");
			HelloPacket response("Hello, client!  I'm the event-driven server!");
			conn->stream().writePacket(response, true);
		} else
			mprintf("got bad packet.\n");
		delete message;
	}

	void onFailure(const Error& error) {
		mprintf("Socket failure: %s\n", error.toString().c_str());
	}

	void onError(const Error& error) {
		mprintf("Socket error: %s\n", error.toString().c_str());
		conn->disconnect();
	}

private:
	Connection* conn;
	bool received;
};

void OurListener::getNewConnectionParams(int& inRate, int& outRate, ConnectionListener*& listener) {
		inRate = 3200;
    outRate = 3200;
    listener = new OurServer();
}

int main(int argc, char* argv[]) {
  doMain("Event-Driven");
  return 0;
}

void doClient(int outRate, int inRate, int port) {
#ifdef _DEBUG
	initDebug(DLEVEL1 | DLEVEL2 | DLEVEL3 | DLEVEL4 | DLEVEL5, "client.log");
#endif
  string host;
  gout << "Enter hostname or IP address: ";
  gin >> host;

	Address address(host);
	address.setPort(port);
	if (!address)
		errorExit("Invalid address.");
  gout << "Connecting to: " << address << endl;

	ClientConnection client(outRate, inRate, new OurClient());
  if (client.open(address, 0)) //localPort = 0, for any local port.
    errorExit("Cannot open client socket.");

  client.connect();
  client.join();     //join on the connection thread
  //if we did not call join, we would have called client.detach(false)
  //instead for true async connections.

	//Check if our connection was successful.
	if (client.isConnected()) {

		//Send our information
		HelloPacket message("Hello, server!  I'm the event-driven client!");
		client.stream().writePacket(message, true);
		client.stream().waitToSendAll();

	}
}

<commit_msg>Added a couple of comments to clairify.<commit_after>/* GNE - Game Networking Engine, a portable multithreaded networking library.
 * Copyright (C) 2001 Jason Winnebeck (gillius@mail.rit.edu)
 * Project website: http://www.rit.edu/~jpw9607/
 *
 * This library is free software; you can redistribute it and/or
 * modify it under the terms of the GNU Lesser General Public
 * License as published by the Free Software Foundation; either
 * version 2.1 of the License, or (at your option) any later version.
 *
 * This library is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 * Lesser General Public License for more details.
 *
 * You should have received a copy of the GNU Lesser General Public
 * License along with this library; if not, write to the Free Software
 * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
 */

/**
 * exhello
 * Everyone knows the "Hello World" program.  Perhaps it's been coded
 * too many times.  However, the GNE coders just plain don't care ;).
 * This is an example to show the minimum code needed to connect and send
 * data, in this case, "Hello Server (or Client)!" to the other end of the
 * connection.  This program uses asyncronous event-driven methods.
 * Well... perhaps not the minimum.  Lots of errors can happen over network
 * connections that we have to handle for this program to properly execute
 * when conditions aren't perfectly ideal, like when we can't reach the
 * server.
 */

#include "../../include/gnelib.h"
#include <iostream>
#include <string>

using namespace std;
using namespace GNE;
using namespace GNE::Console;
using namespace GNE::PacketParser;

#include "shared.h"

class OurClient : public ConnectionListener {
public:
	OurClient() : conn(NULL) {
		mprintf("Client listener created.\n");
	}

	~OurClient() {
		mprintf("Client listener destroyed.\n");
	}

	void onDisconnect() {
		mprintf("Client just disconnected.\n");
    //This is an iffy practice.  If we do this, we have to be careful to
    //always note that each new connection we use this listener with gets
    //its own new copy which we don't destroy later.
		delete this;
	}

  void onConnect(SyncConnection& conn2) {
		conn = conn2.getConnection();
    mprintf("Connection to server successful.\n");
  }

	void onReceive() {
		Packet* message = conn->stream().getNextPacket();
		if (message->getType() == MIN_USER_ID) {
			HelloPacket* helloMessage = (HelloPacket*)message;
			mprintf("got message: \"");
			mprintf(helloMessage->getMessage().c_str());
			mprintf("\"\n");
		} else
			mprintf("got bad packet.\n");
		delete message;
	}

	void onFailure(const Error& error) {
		mprintf("Socket failure: %s\n", error.toString().c_str());
    //No need to disconnect, this has already happened on a failure.
	}

	void onError(const Error& error) {
		mprintf("Socket error: %s\n", error.toString().c_str());
		conn->disconnect();//For simplicity we treat even normal errors as fatal.
	}

  void onConnectFailure(const Error& error) {
    mprintf("Connection to server failed.\n");
		mprintf("GNE reported error: %s\n", error.toString().c_str());
  }
private:
	Connection* conn;
};

class OurServer : public ConnectionListener {
public:
  OurServer() : conn(NULL), received(false) {
		mprintf("Server instance created\n");
	}

  virtual ~OurServer() {
		mprintf("ServerConnection instance killed\n");
	}

	void onDisconnect() {
		mprintf("ServerConnection just disconnected.\n");
		if (!received)
			mprintf("No message received.\n");
		delete this;
	}

  void onNewConn(SyncConnection& conn2) {
		conn = conn2.getConnection();
    mprintf("Connection received from %s; waiting for message...\n", conn->getRemoteAddress(true).toString().c_str());
  }

	void onReceive() {
		Packet* message = conn->stream().getNextPacket();
		if (message->getType() == MIN_USER_ID) {
			HelloPacket* helloMessage = (HelloPacket*)message;
			mprintf("got message: \"");
			mprintf(helloMessage->getMessage().c_str());
			mprintf("\"\n");
			received = true;

			//Send Response
			mprintf("  Sending Response...\n");
			HelloPacket response("Hello, client!  I'm the event-driven server!");
			conn->stream().writePacket(response, true);
		} else
			mprintf("got bad packet.\n");
		delete message;
	}

	void onFailure(const Error& error) {
		mprintf("Socket failure: %s\n", error.toString().c_str());
	}

	void onError(const Error& error) {
		mprintf("Socket error: %s\n", error.toString().c_str());
		conn->disconnect();
	}

private:
	Connection* conn;
	bool received;
};

void OurListener::getNewConnectionParams(int& inRate, int& outRate, ConnectionListener*& listener) {
		inRate = 3200;
    outRate = 3200;
    listener = new OurServer();
}

int main(int argc, char* argv[]) {
  doMain("Event-Driven");
  return 0;
}

void doClient(int outRate, int inRate, int port) {
#ifdef _DEBUG
	initDebug(DLEVEL1 | DLEVEL2 | DLEVEL3 | DLEVEL4 | DLEVEL5, "client.log");
#endif
  string host;
  gout << "Enter hostname or IP address: ";
  gin >> host;

	Address address(host);
	address.setPort(port);
	if (!address)
		errorExit("Invalid address.");
  gout << "Connecting to: " << address << endl;

	ClientConnection client(outRate, inRate, new OurClient());
  if (client.open(address, 0)) //localPort = 0, for any local port.
    errorExit("Cannot open client socket.");

  client.connect();
  client.join();     //join on the connection thread
  //if we did not call join, we would have called client.detach(false)
  //instead for true async connections.

	//Check if our connection was successful.
	if (client.isConnected()) {

		//Send our information
		HelloPacket message("Hello, server!  I'm the event-driven client!");
		client.stream().writePacket(message, true);
		client.stream().waitToSendAll();

	}
}

<|endoftext|>


<commit_before>/* IBM_PROLOG_BEGIN_TAG                                                   */
/* This is an automatically generated prolog.                             */
/*                                                                        */
/* $Source: src/import/chips/p9/procedures/hwp/pm/p9_pm_init.H $          */
/*                                                                        */
/* OpenPOWER HostBoot Project                                             */
/*                                                                        */
/* Contributors Listed Below - COPYRIGHT 2016,2019                        */
/* [+] International Business Machines Corp.                              */
/*                                                                        */
/*                                                                        */
/* 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.                         */
/*                                                                        */
/* IBM_PROLOG_END_TAG                                                     */
///
/// @file p9_pm_init.H
/// @brief Wrapper that initializes or resets the OCC complex.
///
// *HWP HWP Owner        : Greg Still <stillgs@us.ibm.com>
// *HWP HWP Backup Owner :
// *HWP FW Owner         : Sangeetha T S <sangeet2@in.ibm.com>
// *HWP Team             : PM
// *HWP Level            : 2
// *HWP Consumed by      : HS

#ifndef _P9_PM_INIT_H
#define _P9_PM_INIT_H

// -----------------------------------------------------------------------------
// Includes
// -----------------------------------------------------------------------------
#include <fapi2.H>
#include <p9_pm.H>
#include <p9_pm_utils.H>
#include <p9_pm_corequad_init.H>
#include <p9_pm_ocb_init.H>
#include <p9_pm_pss_init.H>
#include <p9_pm_pba_init.H>
#include <p9_pm_firinit.H>
#include <p9_pm_stop_gpe_init.H>
#include <p9_pm_occ_control.H>
#include <p9_pm_reset.H>

// Function pointer defintion
typedef fapi2::ReturnCode (*p9_pm_init_FP_t) (
    const fapi2::Target<fapi2::TARGET_TYPE_PROC_CHIP>&,
    const p9pm::PM_FLOW_MODE);

extern "C"
{
//------------------------------------------------------------------------------
///
/// @brief Wrapper that initializes or resets the OCC complex.
///
/// @param[in] i_target Chip target
/// @param[in] i_mode   Mode of operation (PM_INIT/ PM_RESET)
///
/// @return FAPI2_RC_SUCCESS on success, else error code.
///
    fapi2::ReturnCode p9_pm_init(
        const fapi2::Target<fapi2::TARGET_TYPE_PROC_CHIP>& i_target,
        const p9pm::PM_FLOW_MODE i_mode);
}

#endif // _P9_PM_INIT_H
<commit_msg>Enable PGPE reset & init in the PM reset-init flow<commit_after>/* IBM_PROLOG_BEGIN_TAG                                                   */
/* This is an automatically generated prolog.                             */
/*                                                                        */
/* $Source: src/import/chips/p9/procedures/hwp/pm/p9_pm_init.H $          */
/*                                                                        */
/* OpenPOWER HostBoot Project                                             */
/*                                                                        */
/* Contributors Listed Below - COPYRIGHT 2016,2019                        */
/* [+] International Business Machines Corp.                              */
/*                                                                        */
/*                                                                        */
/* 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.                         */
/*                                                                        */
/* IBM_PROLOG_END_TAG                                                     */
///
/// @file p9_pm_init.H
/// @brief Wrapper that initializes or resets the OCC complex.
///
// *HWP HWP Owner        : Greg Still <stillgs@us.ibm.com>
// *HWP HWP Backup Owner :
// *HWP FW Owner         : Sangeetha T S <sangeet2@in.ibm.com>
// *HWP Team             : PM
// *HWP Level            : 2
// *HWP Consumed by      : HS

#ifndef _P9_PM_INIT_H
#define _P9_PM_INIT_H

// -----------------------------------------------------------------------------
// Includes
// -----------------------------------------------------------------------------
#include <fapi2.H>
#include <p9_pm.H>
#include <p9_pm_utils.H>
#include <p9_pm_corequad_init.H>
#include <p9_pm_ocb_init.H>
#include <p9_pm_pss_init.H>
#include <p9_pm_pba_init.H>
#include <p9_pm_firinit.H>
#include <p9_pm_stop_gpe_init.H>
#include <p9_pm_pstate_gpe_init.H>
#include <p9_pm_occ_control.H>
#include <p9_pm_reset.H>

// Function pointer defintion
typedef fapi2::ReturnCode (*p9_pm_init_FP_t) (
    const fapi2::Target<fapi2::TARGET_TYPE_PROC_CHIP>&,
    const p9pm::PM_FLOW_MODE);

extern "C"
{
//------------------------------------------------------------------------------
///
/// @brief Wrapper that initializes or resets the OCC complex.
///
/// @param[in] i_target Chip target
/// @param[in] i_mode   Mode of operation (PM_INIT/ PM_RESET)
///
/// @return FAPI2_RC_SUCCESS on success, else error code.
///
    fapi2::ReturnCode p9_pm_init(
        const fapi2::Target<fapi2::TARGET_TYPE_PROC_CHIP>& i_target,
        const p9pm::PM_FLOW_MODE i_mode);
}

#endif // _P9_PM_INIT_H
<|endoftext|>


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

Licensed to the OpenCOR team under one or more contributor license agreements.
See the NOTICE.txt file distributed with this work for additional information
regarding copyright ownership. The OpenCOR team licenses this file to you 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.

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

//==============================================================================
// Collapsible widget
//==============================================================================

#include "collapsiblewidget.h"
#include "guiutils.h"

//==============================================================================

#include <Qt>

//==============================================================================

#include <QLayout>
#include <QSettings>
#include <QToolButton>
#include <QVariant>

//==============================================================================

namespace OpenCOR {
namespace Core {

//==============================================================================

CollapsibleHeaderTitleWidget::CollapsibleHeaderTitleWidget(QWidget *pParent) :
    QLabel(pParent)
{
}

//==============================================================================

void CollapsibleHeaderTitleWidget::mouseDoubleClickEvent(QMouseEvent *pEvent)
{
    // Default handling of the event

    QLabel::mouseDoubleClickEvent(pEvent);

    // Let people know that the widget has been double clicked

    emit doubleClicked();
}

//==============================================================================

CollapsibleHeaderWidget::CollapsibleHeaderWidget(const QColor &pSeparatorColor,
                                                 QWidget *pParent) :
    QWidget(pParent),
    mCollapsed(false),
    mLastHeader(false)
{
    // Create our main (vertical) layout

    QVBoxLayout *layout = new QVBoxLayout(this);

    layout->setMargin(0);
    layout->setSpacing(0);

    setLayout(layout);

    // Create a sub-widget with a horizontal layout

    QWidget *subWidget = new QWidget(this);

    QHBoxLayout *subLayout = new QHBoxLayout(subWidget);

    subLayout->setMargin(0);
    subLayout->setSpacing(0);

    subWidget->setLayout(subLayout);

    // Create and customise our button and title

    mButton = new QToolButton(subWidget);
    mTitle  = new CollapsibleHeaderTitleWidget(subWidget);

    int iconSize = 0.4*mTitle->height();

    mButton->setIcon(QIcon(":/oxygen/actions/arrow-down.png"));
    mButton->setIconSize(QSize(iconSize, iconSize));
    mButton->setStyleSheet("QToolButton {"
                           "    border: 0px;"
                           "}"
                           ""
                           "QToolButton::pressed {"
                           "    margin: 0px;"
                           "}");

    mTitle->setAlignment(Qt::AlignCenter);

    // Add our button and title to our sub-layout

    subLayout->addWidget(mButton);
    subLayout->addWidget(mTitle);

    // Add a top separator, our sub-widget and a bottom separator to our main
    // layout
    // Note: we keep track of our top and bottom separators since we may need
    //       to hide them in some cases/circumstances...

    mTopSeparator    = Core::newLineWidget(pSeparatorColor, this);
    mBottomSeparator = Core::newLineWidget(pSeparatorColor, this);

    layout->addWidget(mTopSeparator);
    layout->addWidget(subWidget);
    layout->addWidget(mBottomSeparator);

    // Connections to toggle our collapsed state

    connect(mButton, SIGNAL(clicked()),
            this, SLOT(toggleCollapsedState()));
    connect(mTitle, SIGNAL(doubleClicked()),
            this, SLOT(toggleCollapsedState()));
}

//==============================================================================

void CollapsibleHeaderWidget::setFirstHeader(const bool &pFirstHeader)
{
    // Show/hide our top separator depending on whether we are the first header

    mTopSeparator->setVisible(!pFirstHeader);
}

//==============================================================================

void CollapsibleHeaderWidget::setLastHeader(const bool &pLastHeader)
{
    // Keep track of our last header status and update our bottom separator
    // visible status, if needed

    if (pLastHeader != mLastHeader) {
        mLastHeader = pLastHeader;

        updateBottomSeparatorVisibleStatus();
    }
}

//==============================================================================

bool CollapsibleHeaderWidget::isCollapsed() const
{
    // Return wheter we are collapsed

    return mCollapsed;
}

//==============================================================================

void CollapsibleHeaderWidget::setCollapsed(const bool &pCollapsed)
{
    // Collapse or uncollapse ourselves, if needed

    if (pCollapsed != mCollapsed)
        toggleCollapsedState();
}

//==============================================================================

QString CollapsibleHeaderWidget::title() const
{
    // Return our title

    return mTitle->text();
}

//==============================================================================

void CollapsibleHeaderWidget::setTitle(const QString &pTitle)
{
    // Set our title

    mTitle->setText(pTitle);
}

//==============================================================================

void CollapsibleHeaderWidget::updateBottomSeparatorVisibleStatus()
{
    // Show/hide our bottom separator depending on whether we are collapsed or
    // whether we are the last header

    mBottomSeparator->setVisible(!mCollapsed || mLastHeader);
}

//==============================================================================

void CollapsibleHeaderWidget::toggleCollapsedState()
{
    // Toggle our collapsed state

    mCollapsed = !mCollapsed;

    // Update our button's icon to reflect our new collapsed state

    if (mCollapsed)
        mButton->setIcon(QIcon(":/oxygen/actions/arrow-right.png"));
    else
        mButton->setIcon(QIcon(":/oxygen/actions/arrow-down.png"));

    // Update our bottom separator visible status

    updateBottomSeparatorVisibleStatus();

    // Let people know about our new new collapsed state

    emit widgetVisible(!mCollapsed);
}

//==============================================================================

void CollapsibleWidget::constructor(const QColor &pSeparatorColor)
{
    // Some initialisations

    mSeparatorColor = pSeparatorColor;

    mHeaders = QList<CollapsibleHeaderWidget *>();

    // Create a vertical layout which will contain our headers and widgets

    mLayout = new QVBoxLayout(this);

    mLayout->setMargin(0);
    mLayout->setSpacing(0);

    setLayout(mLayout);

    // Add a stretch to our layout so that its contents will take as little
    // space as possible

    mLayout->addStretch(1);
}

//==============================================================================

CollapsibleWidget::CollapsibleWidget(const QColor &pSeparatorColor,
                                     QWidget *pParent) :
    Widget(QSize(), pParent)
{
    // Construct our object

    constructor(pSeparatorColor);
}

//==============================================================================

CollapsibleWidget::CollapsibleWidget(QWidget *pParent) :
    Widget(QSize(), pParent)
{
    // Construct our object

    constructor();
}

//==============================================================================

static const auto SettingsCollapsed = QStringLiteral("Collapsed%1");

//==============================================================================

void CollapsibleWidget::loadSettings(QSettings *pSettings)
{
    // Retrieve our collapsable state

    for (int i = 0, iMax = mHeaders.count(); i < iMax; ++i)
        setCollapsed(i, pSettings->value(SettingsCollapsed.arg(i), false).toBool());
}

//==============================================================================

void CollapsibleWidget::saveSettings(QSettings *pSettings) const
{
    // Keep track of our collapsable state

    for (int i = 0, iMax = mHeaders.count(); i < iMax; ++i)
        pSettings->setValue(SettingsCollapsed.arg(i), isCollapsed(i));
}

//==============================================================================

bool CollapsibleWidget::isCollapsed(const int &pIndex) const
{
    // Return wheter our requested header is collapsed

    return mHeaders.value(pIndex)?mHeaders[pIndex]->isCollapsed():false;
}

//==============================================================================

void CollapsibleWidget::setCollapsed(const int &pIndex, const bool &pCollapsed)
{
    // Collapse or uncollapse our requested header

    if (mHeaders.value(pIndex))
        mHeaders[pIndex]->setCollapsed(pCollapsed);
}

//==============================================================================

QString CollapsibleWidget::headerTitle(const int &pIndex) const
{
    // Return the title of our requested header

    return mHeaders.value(pIndex)?mHeaders[pIndex]->title():QString();
}

//==============================================================================

void CollapsibleWidget::setHeaderTitle(const int &pIndex, const QString &pTitle)
{
    // Set the title of our requested header

    if (mHeaders.value(pIndex))
        mHeaders[pIndex]->setTitle(pTitle);
}

//==============================================================================

void CollapsibleWidget::addWidget(QWidget *pWidget)
{
    // Make sure that there is a widget to add

    if (!pWidget)
        return;

    // We want to add a new widget, so we first need to add a new header to our
    // layout

    int beforeIndex = 2*mHeaders.count();

    CollapsibleHeaderWidget *header = new CollapsibleHeaderWidget(mSeparatorColor, this);

    // Let our header know whether it is the first header

    header->setFirstHeader(!beforeIndex);

    // Let our header know that, if anything, it is our new last header, meaning
    // that our previous header is not the last one anymore

    if (!mHeaders.isEmpty())
        mHeaders.last()->setLastHeader(false);

    header->setLastHeader(true);

    // Now, we can actually add the header to our layout, as well as keep track
    // of it

    mLayout->insertWidget(beforeIndex, header);

    mHeaders.append(header);

    // Add the new widget itself

    mLayout->insertWidget(++beforeIndex, pWidget);

    // Create a connection to show/hide our widget depending on the collapsed
    // state of our header

    connect(header, SIGNAL(widgetVisible(const bool &)),
            pWidget, SLOT(setVisible(bool)));
}

//==============================================================================

}   // namespace Core
}   // namespace OpenCOR

//==============================================================================
// End of file
//==============================================================================
<commit_msg>Some minor cleaning up [ci skip].<commit_after>/*******************************************************************************

Licensed to the OpenCOR team under one or more contributor license agreements.
See the NOTICE.txt file distributed with this work for additional information
regarding copyright ownership. The OpenCOR team licenses this file to you 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.

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

//==============================================================================
// Collapsible widget
//==============================================================================

#include "collapsiblewidget.h"
#include "guiutils.h"

//==============================================================================

#include <Qt>

//==============================================================================

#include <QLayout>
#include <QSettings>
#include <QToolButton>
#include <QVariant>

//==============================================================================

namespace OpenCOR {
namespace Core {

//==============================================================================

CollapsibleHeaderTitleWidget::CollapsibleHeaderTitleWidget(QWidget *pParent) :
    QLabel(pParent)
{
}

//==============================================================================

void CollapsibleHeaderTitleWidget::mouseDoubleClickEvent(QMouseEvent *pEvent)
{
    // Default handling of the event

    QLabel::mouseDoubleClickEvent(pEvent);

    // Let people know that the widget has been double clicked

    emit doubleClicked();
}

//==============================================================================

CollapsibleHeaderWidget::CollapsibleHeaderWidget(const QColor &pSeparatorColor,
                                                 QWidget *pParent) :
    QWidget(pParent),
    mCollapsed(false),
    mLastHeader(false)
{
    // Create our main (vertical) layout

    QVBoxLayout *layout = new QVBoxLayout(this);

    layout->setMargin(0);
    layout->setSpacing(0);

    setLayout(layout);

    // Create a sub-widget with a horizontal layout

    QWidget *subWidget = new QWidget(this);

    QHBoxLayout *subLayout = new QHBoxLayout(subWidget);

    subLayout->setMargin(0);
    subLayout->setSpacing(0);

    subWidget->setLayout(subLayout);

    // Create and customise our button and title

    mButton = new QToolButton(subWidget);
    mTitle  = new CollapsibleHeaderTitleWidget(subWidget);

    int iconSize = 0.4*mTitle->height();

    mButton->setIcon(QIcon(":/oxygen/actions/arrow-down.png"));
    mButton->setIconSize(QSize(iconSize, iconSize));
    mButton->setStyleSheet("QToolButton {"
                           "    border: 0px;"
                           "}"
                           ""
                           "QToolButton:pressed {"
                           "    margin: 0px;"
                           "}");

    mTitle->setAlignment(Qt::AlignCenter);

    // Add our button and title to our sub-layout

    subLayout->addWidget(mButton);
    subLayout->addWidget(mTitle);

    // Add a top separator, our sub-widget and a bottom separator to our main
    // layout
    // Note: we keep track of our top and bottom separators since we may need
    //       to hide them in some cases/circumstances...

    mTopSeparator    = Core::newLineWidget(pSeparatorColor, this);
    mBottomSeparator = Core::newLineWidget(pSeparatorColor, this);

    layout->addWidget(mTopSeparator);
    layout->addWidget(subWidget);
    layout->addWidget(mBottomSeparator);

    // Connections to toggle our collapsed state

    connect(mButton, SIGNAL(clicked()),
            this, SLOT(toggleCollapsedState()));
    connect(mTitle, SIGNAL(doubleClicked()),
            this, SLOT(toggleCollapsedState()));
}

//==============================================================================

void CollapsibleHeaderWidget::setFirstHeader(const bool &pFirstHeader)
{
    // Show/hide our top separator depending on whether we are the first header

    mTopSeparator->setVisible(!pFirstHeader);
}

//==============================================================================

void CollapsibleHeaderWidget::setLastHeader(const bool &pLastHeader)
{
    // Keep track of our last header status and update our bottom separator
    // visible status, if needed

    if (pLastHeader != mLastHeader) {
        mLastHeader = pLastHeader;

        updateBottomSeparatorVisibleStatus();
    }
}

//==============================================================================

bool CollapsibleHeaderWidget::isCollapsed() const
{
    // Return wheter we are collapsed

    return mCollapsed;
}

//==============================================================================

void CollapsibleHeaderWidget::setCollapsed(const bool &pCollapsed)
{
    // Collapse or uncollapse ourselves, if needed

    if (pCollapsed != mCollapsed)
        toggleCollapsedState();
}

//==============================================================================

QString CollapsibleHeaderWidget::title() const
{
    // Return our title

    return mTitle->text();
}

//==============================================================================

void CollapsibleHeaderWidget::setTitle(const QString &pTitle)
{
    // Set our title

    mTitle->setText(pTitle);
}

//==============================================================================

void CollapsibleHeaderWidget::updateBottomSeparatorVisibleStatus()
{
    // Show/hide our bottom separator depending on whether we are collapsed or
    // whether we are the last header

    mBottomSeparator->setVisible(!mCollapsed || mLastHeader);
}

//==============================================================================

void CollapsibleHeaderWidget::toggleCollapsedState()
{
    // Toggle our collapsed state

    mCollapsed = !mCollapsed;

    // Update our button's icon to reflect our new collapsed state

    if (mCollapsed)
        mButton->setIcon(QIcon(":/oxygen/actions/arrow-right.png"));
    else
        mButton->setIcon(QIcon(":/oxygen/actions/arrow-down.png"));

    // Update our bottom separator visible status

    updateBottomSeparatorVisibleStatus();

    // Let people know about our new new collapsed state

    emit widgetVisible(!mCollapsed);
}

//==============================================================================

void CollapsibleWidget::constructor(const QColor &pSeparatorColor)
{
    // Some initialisations

    mSeparatorColor = pSeparatorColor;

    mHeaders = QList<CollapsibleHeaderWidget *>();

    // Create a vertical layout which will contain our headers and widgets

    mLayout = new QVBoxLayout(this);

    mLayout->setMargin(0);
    mLayout->setSpacing(0);

    setLayout(mLayout);

    // Add a stretch to our layout so that its contents will take as little
    // space as possible

    mLayout->addStretch(1);
}

//==============================================================================

CollapsibleWidget::CollapsibleWidget(const QColor &pSeparatorColor,
                                     QWidget *pParent) :
    Widget(QSize(), pParent)
{
    // Construct our object

    constructor(pSeparatorColor);
}

//==============================================================================

CollapsibleWidget::CollapsibleWidget(QWidget *pParent) :
    Widget(QSize(), pParent)
{
    // Construct our object

    constructor();
}

//==============================================================================

static const auto SettingsCollapsed = QStringLiteral("Collapsed%1");

//==============================================================================

void CollapsibleWidget::loadSettings(QSettings *pSettings)
{
    // Retrieve our collapsable state

    for (int i = 0, iMax = mHeaders.count(); i < iMax; ++i)
        setCollapsed(i, pSettings->value(SettingsCollapsed.arg(i), false).toBool());
}

//==============================================================================

void CollapsibleWidget::saveSettings(QSettings *pSettings) const
{
    // Keep track of our collapsable state

    for (int i = 0, iMax = mHeaders.count(); i < iMax; ++i)
        pSettings->setValue(SettingsCollapsed.arg(i), isCollapsed(i));
}

//==============================================================================

bool CollapsibleWidget::isCollapsed(const int &pIndex) const
{
    // Return wheter our requested header is collapsed

    return mHeaders.value(pIndex)?mHeaders[pIndex]->isCollapsed():false;
}

//==============================================================================

void CollapsibleWidget::setCollapsed(const int &pIndex, const bool &pCollapsed)
{
    // Collapse or uncollapse our requested header

    if (mHeaders.value(pIndex))
        mHeaders[pIndex]->setCollapsed(pCollapsed);
}

//==============================================================================

QString CollapsibleWidget::headerTitle(const int &pIndex) const
{
    // Return the title of our requested header

    return mHeaders.value(pIndex)?mHeaders[pIndex]->title():QString();
}

//==============================================================================

void CollapsibleWidget::setHeaderTitle(const int &pIndex, const QString &pTitle)
{
    // Set the title of our requested header

    if (mHeaders.value(pIndex))
        mHeaders[pIndex]->setTitle(pTitle);
}

//==============================================================================

void CollapsibleWidget::addWidget(QWidget *pWidget)
{
    // Make sure that there is a widget to add

    if (!pWidget)
        return;

    // We want to add a new widget, so we first need to add a new header to our
    // layout

    int beforeIndex = 2*mHeaders.count();

    CollapsibleHeaderWidget *header = new CollapsibleHeaderWidget(mSeparatorColor, this);

    // Let our header know whether it is the first header

    header->setFirstHeader(!beforeIndex);

    // Let our header know that, if anything, it is our new last header, meaning
    // that our previous header is not the last one anymore

    if (!mHeaders.isEmpty())
        mHeaders.last()->setLastHeader(false);

    header->setLastHeader(true);

    // Now, we can actually add the header to our layout, as well as keep track
    // of it

    mLayout->insertWidget(beforeIndex, header);

    mHeaders.append(header);

    // Add the new widget itself

    mLayout->insertWidget(++beforeIndex, pWidget);

    // Create a connection to show/hide our widget depending on the collapsed
    // state of our header

    connect(header, SIGNAL(widgetVisible(const bool &)),
            pWidget, SLOT(setVisible(bool)));
}

//==============================================================================

}   // namespace Core
}   // namespace OpenCOR

//==============================================================================
// End of file
//==============================================================================
<|endoftext|>


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

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

#ifndef _SV_SALBTYPE_HXX
#include <vcl/salbtype.hxx>
#endif
#ifndef _SV_BITMAP_HXX
#include <vcl/bitmap.hxx>
#endif
#ifndef _TL_POLY_HXX
#include <tools/poly.hxx>
#endif
#ifndef _SV_REGION_HXX
#include <vcl/region.hxx>
#endif
#ifndef _SV_BMPACC_HXX
#include <vcl/bmpacc.hxx>
#endif
#ifndef _SV_BMPFAST_HXX
#include <vcl/bmpfast.hxx>
#endif

// ---------------------
// - BitmapWriteAccess -
// ---------------------

void BitmapWriteAccess::SetLineColor()
{
    delete mpLineColor;
    mpLineColor = NULL;
}

// ------------------------------------------------------------------

void BitmapWriteAccess::SetLineColor( const Color& rColor )
{
    delete mpLineColor;

    if( rColor.GetTransparency() == 255 )
        mpLineColor = NULL;
    else
        mpLineColor = ( HasPalette() ? new BitmapColor(  (BYTE) GetBestPaletteIndex( rColor ) ) : new BitmapColor( rColor ) );
}

// ------------------------------------------------------------------

Color BitmapWriteAccess::GetLineColor() const
{
    Color aRet;

    if( mpLineColor )
        aRet = (const Color&) *mpLineColor;
    else
        aRet.SetTransparency( 255 );

    return aRet;
}

// ------------------------------------------------------------------

void BitmapWriteAccess::SetFillColor()
{
    delete mpFillColor;
    mpFillColor = NULL;
}

// ------------------------------------------------------------------

void BitmapWriteAccess::SetFillColor( const Color& rColor )
{
    delete mpFillColor;

    if( rColor.GetTransparency() == 255 )
        mpFillColor = NULL;
    else
        mpFillColor = ( HasPalette() ? new BitmapColor(  (BYTE) GetBestPaletteIndex( rColor ) ) : new BitmapColor( rColor ) );
}

// ------------------------------------------------------------------

Color BitmapWriteAccess::GetFillColor() const
{
    Color aRet;

    if( mpFillColor )
        aRet = (const Color&) *mpFillColor;
    else
        aRet.SetTransparency( 255 );

    return aRet;
}

// ------------------------------------------------------------------

void BitmapWriteAccess::Erase( const Color& rColor )
{
    // convert the color format from RGB to palette index if needed
    // TODO: provide and use Erase( BitmapColor& method)
    BitmapColor aColor = rColor;
    if( HasPalette() )
        aColor = BitmapColor( (BYTE)GetBestPaletteIndex( rColor) );
    // try fast bitmap method first
    if( ImplFastEraseBitmap( *mpBuffer, aColor ) )
        return;

    // use the canonical method to clear the bitmap
    BitmapColor*    pOldFillColor = mpFillColor ? new BitmapColor( *mpFillColor ) : NULL;
    const Point     aPoint;
    const Rectangle aRect( aPoint, maBitmap.GetSizePixel() );

    SetFillColor( rColor );
    FillRect( aRect );
    delete mpFillColor;
    mpFillColor = pOldFillColor;
}

// ------------------------------------------------------------------

void BitmapWriteAccess::DrawLine( const Point& rStart, const Point& rEnd )
{
    if( mpLineColor )
    {
        const BitmapColor&  rLineColor = *mpLineColor;
        long                nX, nY;

        if ( rStart.X() == rEnd.X() )
        {
            // vertikale Line
            const long nEndY = rEnd.Y();

            nX = rStart.X();
            nY = rStart.Y();

            if ( nEndY > nY )
            {
                for (; nY <= nEndY; nY++ )
                    SetPixel( nY, nX, rLineColor );
            }
            else
            {
                for (; nY >= nEndY; nY-- )
                    SetPixel( nY, nX, rLineColor );
            }
        }
        else if ( rStart.Y() == rEnd.Y() )
        {
            // horizontale Line
            const long nEndX = rEnd.X();

            nX = rStart.X();
            nY = rStart.Y();

            if ( nEndX > nX )
            {
                for (; nX <= nEndX; nX++ )
                    SetPixel( nY, nX, rLineColor );
            }
            else
            {
                for (; nX >= nEndX; nX-- )
                    SetPixel( nY, nX, rLineColor );
            }
        }
        else
        {
            const long  nDX = labs( rEnd.X() - rStart.X() );
            const long  nDY = labs( rEnd.Y() - rStart.Y() );
            long        nX1;
            long        nY1;
            long        nX2;
            long        nY2;

            if ( nDX >= nDY )
            {
                if ( rStart.X() < rEnd.X() )
                {
                    nX1 = rStart.X();
                    nY1 = rStart.Y();
                    nX2 = rEnd.X();
                    nY2 = rEnd.Y();
                }
                else
                {
                    nX1 = rEnd.X();
                    nY1 = rEnd.Y();
                    nX2 = rStart.X();
                    nY2 = rStart.Y();
                }

                const long  nDYX = ( nDY - nDX ) << 1;
                const long  nDY2 = nDY << 1;
                long        nD = nDY2 - nDX;
                BOOL        bPos = nY1 < nY2;

                for ( nX = nX1, nY = nY1; nX <= nX2; nX++ )
                {
                    SetPixel( nY, nX, rLineColor );

                    if ( nD < 0 )
                        nD += nDY2;
                    else
                    {
                        nD += nDYX;

                        if ( bPos )
                            nY++;
                        else
                            nY--;
                    }
                }
            }
            else
            {
                if ( rStart.Y() < rEnd.Y() )
                {
                    nX1 = rStart.X();
                    nY1 = rStart.Y();
                    nX2 = rEnd.X();
                    nY2 = rEnd.Y();
                }
                else
                {
                    nX1 = rEnd.X();
                    nY1 = rEnd.Y();
                    nX2 = rStart.X();
                    nY2 = rStart.Y();
                }

                const long  nDYX = ( nDX - nDY ) << 1;
                const long  nDY2 = nDX << 1;
                long        nD = nDY2 - nDY;
                BOOL        bPos = nX1 < nX2;

                for ( nX = nX1, nY = nY1; nY <= nY2; nY++ )
                {
                    SetPixel( nY, nX, rLineColor );

                    if ( nD < 0 )
                        nD += nDY2;
                    else
                    {
                        nD += nDYX;

                        if ( bPos )
                            nX++;
                        else
                            nX--;
                    }
                }
            }
        }
    }
}

// ------------------------------------------------------------------

void BitmapWriteAccess::FillRect( const Rectangle& rRect )
{
    if( mpFillColor )
    {
        const BitmapColor&  rFillColor = *mpFillColor;
        Point               aPoint;
        Rectangle           aRect( aPoint, maBitmap.GetSizePixel() );

        aRect.Intersection( rRect );

        if( !aRect.IsEmpty() )
        {
            const long  nStartX = rRect.Left();
            const long  nStartY = rRect.Top();
            const long  nEndX = rRect.Right();
            const long  nEndY = rRect.Bottom();

            for( long nY = nStartY; nY <= nEndY; nY++ )
                for( long nX = nStartX; nX <= nEndX; nX++ )
                    SetPixel( nY, nX, rFillColor );
        }
    }
}

// ------------------------------------------------------------------

void BitmapWriteAccess::DrawRect( const Rectangle& rRect )
{
    if( mpFillColor )
        FillRect( rRect );

    if( mpLineColor && ( !mpFillColor || ( *mpFillColor != *mpLineColor ) ) )
    {
        DrawLine( rRect.TopLeft(), rRect.TopRight() );
        DrawLine( rRect.TopRight(), rRect.BottomRight() );
        DrawLine( rRect.BottomRight(), rRect.BottomLeft() );
        DrawLine( rRect.BottomLeft(), rRect.TopLeft() );
    }
}

// ------------------------------------------------------------------

void BitmapWriteAccess::FillPolygon( const Polygon& rPoly )
{
    const USHORT nSize = rPoly.GetSize();

    if( nSize && mpFillColor )
    {
        const BitmapColor&  rFillColor = *mpFillColor;
        Region              aRegion( rPoly );
        Rectangle           aRect;

        aRegion.Intersect( Rectangle( Point(), Size( Width(), Height() ) ) );

        if( !aRegion.IsEmpty() )
        {
            RegionHandle aRegHandle( aRegion.BeginEnumRects() );

            while( aRegion.GetNextEnumRect( aRegHandle, aRect ) )
                for( long nY = aRect.Top(), nEndY = aRect.Bottom(); nY <= nEndY; nY++ )
                    for( long nX = aRect.Left(), nEndX = aRect.Right(); nX <= nEndX; nX++ )
                        SetPixel( nY, nX, rFillColor );

            aRegion.EndEnumRects( aRegHandle );
        }
    }
}

// ------------------------------------------------------------------

void BitmapWriteAccess::DrawPolygon( const Polygon& rPoly )
{
    if( mpFillColor )
        FillPolygon( rPoly );

    if( mpLineColor && ( !mpFillColor || ( *mpFillColor != *mpLineColor ) ) )
    {
        const USHORT nSize = rPoly.GetSize();

        for( USHORT i = 0, nSize1 = nSize - 1; i < nSize1; i++ )
            DrawLine( rPoly[ i ], rPoly[ i + 1 ] );

        if( rPoly[ nSize - 1 ] != rPoly[ 0 ] )
            DrawLine( rPoly[ nSize - 1 ], rPoly[ 0 ] );
    }
}

// ------------------------------------------------------------------

void BitmapWriteAccess::FillPolyPolygon( const PolyPolygon& rPolyPoly )
{
    const USHORT nCount = rPolyPoly.Count();

    if( nCount && mpFillColor )
    {
        const BitmapColor&  rFillColor = *mpFillColor;
        Region              aRegion( rPolyPoly );
        Rectangle           aRect;

        aRegion.Intersect( Rectangle( Point(), Size( Width(), Height() ) ) );

        if( !aRegion.IsEmpty() )
        {
            RegionHandle aRegHandle( aRegion.BeginEnumRects() );

            while( aRegion.GetNextEnumRect( aRegHandle, aRect ) )
                for( long nY = aRect.Top(), nEndY = aRect.Bottom(); nY <= nEndY; nY++ )
                    for( long nX = aRect.Left(), nEndX = aRect.Right(); nX <= nEndX; nX++ )
                        SetPixel( nY, nX, rFillColor );

            aRegion.EndEnumRects( aRegHandle );
        }
    }
}

// ------------------------------------------------------------------

void BitmapWriteAccess::DrawPolyPolygon( const PolyPolygon& rPolyPoly )
{
    if( mpFillColor )
        FillPolyPolygon( rPolyPoly );

    if( mpLineColor && ( !mpFillColor || ( *mpFillColor != *mpLineColor ) ) )
    {
        for( USHORT n = 0, nCount = rPolyPoly.Count(); n < nCount; )
        {
            const Polygon&  rPoly = rPolyPoly[ n++ ];
            const USHORT    nSize = rPoly.GetSize();

            if( nSize )
            {
                for( USHORT i = 0, nSize1 = nSize - 1; i < nSize1; i++ )
                    DrawLine( rPoly[ i ], rPoly[ i + 1 ] );

                if( rPoly[ nSize - 1 ] != rPoly[ 0 ] )
                    DrawLine( rPoly[ nSize - 1 ], rPoly[ 0 ] );
            }
        }
    }
}
<commit_msg>INTEGRATION: CWS changefileheader (1.10.224); FILE MERGED 2008/04/01 16:05:30 thb 1.10.224.3: #i85898# Stripping all external header guards 2008/04/01 13:01:37 thb 1.10.224.2: #i85898# Stripping all external header guards 2008/03/28 15:44:44 rt 1.10.224.1: #i87441# Change license header to LPGL v3.<commit_after>/*************************************************************************
 *
 * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
 *
 * Copyright 2008 by Sun Microsystems, Inc.
 *
 * OpenOffice.org - a multi-platform office productivity suite
 *
 * $RCSfile: bmpacc3.cxx,v $
 * $Revision: 1.11 $
 *
 * This file is part of OpenOffice.org.
 *
 * OpenOffice.org is free software: you can redistribute it and/or modify
 * it under the terms of the GNU Lesser General Public License version 3
 * only, as published by the Free Software Foundation.
 *
 * OpenOffice.org is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU Lesser General Public License version 3 for more details
 * (a copy is included in the LICENSE file that accompanied this code).
 *
 * You should have received a copy of the GNU Lesser General Public License
 * version 3 along with OpenOffice.org.  If not, see
 * <http://www.openoffice.org/license.html>
 * for a copy of the LGPLv3 License.
 *
 ************************************************************************/

// MARKER(update_precomp.py): autogen include statement, do not remove
#include "precompiled_vcl.hxx"
#include <vcl/salbtype.hxx>
#include <vcl/bitmap.hxx>
#include <tools/poly.hxx>
#include <vcl/region.hxx>
#include <vcl/bmpacc.hxx>
#include <vcl/bmpfast.hxx>

// ---------------------
// - BitmapWriteAccess -
// ---------------------

void BitmapWriteAccess::SetLineColor()
{
    delete mpLineColor;
    mpLineColor = NULL;
}

// ------------------------------------------------------------------

void BitmapWriteAccess::SetLineColor( const Color& rColor )
{
    delete mpLineColor;

    if( rColor.GetTransparency() == 255 )
        mpLineColor = NULL;
    else
        mpLineColor = ( HasPalette() ? new BitmapColor(  (BYTE) GetBestPaletteIndex( rColor ) ) : new BitmapColor( rColor ) );
}

// ------------------------------------------------------------------

Color BitmapWriteAccess::GetLineColor() const
{
    Color aRet;

    if( mpLineColor )
        aRet = (const Color&) *mpLineColor;
    else
        aRet.SetTransparency( 255 );

    return aRet;
}

// ------------------------------------------------------------------

void BitmapWriteAccess::SetFillColor()
{
    delete mpFillColor;
    mpFillColor = NULL;
}

// ------------------------------------------------------------------

void BitmapWriteAccess::SetFillColor( const Color& rColor )
{
    delete mpFillColor;

    if( rColor.GetTransparency() == 255 )
        mpFillColor = NULL;
    else
        mpFillColor = ( HasPalette() ? new BitmapColor(  (BYTE) GetBestPaletteIndex( rColor ) ) : new BitmapColor( rColor ) );
}

// ------------------------------------------------------------------

Color BitmapWriteAccess::GetFillColor() const
{
    Color aRet;

    if( mpFillColor )
        aRet = (const Color&) *mpFillColor;
    else
        aRet.SetTransparency( 255 );

    return aRet;
}

// ------------------------------------------------------------------

void BitmapWriteAccess::Erase( const Color& rColor )
{
    // convert the color format from RGB to palette index if needed
    // TODO: provide and use Erase( BitmapColor& method)
    BitmapColor aColor = rColor;
    if( HasPalette() )
        aColor = BitmapColor( (BYTE)GetBestPaletteIndex( rColor) );
    // try fast bitmap method first
    if( ImplFastEraseBitmap( *mpBuffer, aColor ) )
        return;

    // use the canonical method to clear the bitmap
    BitmapColor*    pOldFillColor = mpFillColor ? new BitmapColor( *mpFillColor ) : NULL;
    const Point     aPoint;
    const Rectangle aRect( aPoint, maBitmap.GetSizePixel() );

    SetFillColor( rColor );
    FillRect( aRect );
    delete mpFillColor;
    mpFillColor = pOldFillColor;
}

// ------------------------------------------------------------------

void BitmapWriteAccess::DrawLine( const Point& rStart, const Point& rEnd )
{
    if( mpLineColor )
    {
        const BitmapColor&  rLineColor = *mpLineColor;
        long                nX, nY;

        if ( rStart.X() == rEnd.X() )
        {
            // vertikale Line
            const long nEndY = rEnd.Y();

            nX = rStart.X();
            nY = rStart.Y();

            if ( nEndY > nY )
            {
                for (; nY <= nEndY; nY++ )
                    SetPixel( nY, nX, rLineColor );
            }
            else
            {
                for (; nY >= nEndY; nY-- )
                    SetPixel( nY, nX, rLineColor );
            }
        }
        else if ( rStart.Y() == rEnd.Y() )
        {
            // horizontale Line
            const long nEndX = rEnd.X();

            nX = rStart.X();
            nY = rStart.Y();

            if ( nEndX > nX )
            {
                for (; nX <= nEndX; nX++ )
                    SetPixel( nY, nX, rLineColor );
            }
            else
            {
                for (; nX >= nEndX; nX-- )
                    SetPixel( nY, nX, rLineColor );
            }
        }
        else
        {
            const long  nDX = labs( rEnd.X() - rStart.X() );
            const long  nDY = labs( rEnd.Y() - rStart.Y() );
            long        nX1;
            long        nY1;
            long        nX2;
            long        nY2;

            if ( nDX >= nDY )
            {
                if ( rStart.X() < rEnd.X() )
                {
                    nX1 = rStart.X();
                    nY1 = rStart.Y();
                    nX2 = rEnd.X();
                    nY2 = rEnd.Y();
                }
                else
                {
                    nX1 = rEnd.X();
                    nY1 = rEnd.Y();
                    nX2 = rStart.X();
                    nY2 = rStart.Y();
                }

                const long  nDYX = ( nDY - nDX ) << 1;
                const long  nDY2 = nDY << 1;
                long        nD = nDY2 - nDX;
                BOOL        bPos = nY1 < nY2;

                for ( nX = nX1, nY = nY1; nX <= nX2; nX++ )
                {
                    SetPixel( nY, nX, rLineColor );

                    if ( nD < 0 )
                        nD += nDY2;
                    else
                    {
                        nD += nDYX;

                        if ( bPos )
                            nY++;
                        else
                            nY--;
                    }
                }
            }
            else
            {
                if ( rStart.Y() < rEnd.Y() )
                {
                    nX1 = rStart.X();
                    nY1 = rStart.Y();
                    nX2 = rEnd.X();
                    nY2 = rEnd.Y();
                }
                else
                {
                    nX1 = rEnd.X();
                    nY1 = rEnd.Y();
                    nX2 = rStart.X();
                    nY2 = rStart.Y();
                }

                const long  nDYX = ( nDX - nDY ) << 1;
                const long  nDY2 = nDX << 1;
                long        nD = nDY2 - nDY;
                BOOL        bPos = nX1 < nX2;

                for ( nX = nX1, nY = nY1; nY <= nY2; nY++ )
                {
                    SetPixel( nY, nX, rLineColor );

                    if ( nD < 0 )
                        nD += nDY2;
                    else
                    {
                        nD += nDYX;

                        if ( bPos )
                            nX++;
                        else
                            nX--;
                    }
                }
            }
        }
    }
}

// ------------------------------------------------------------------

void BitmapWriteAccess::FillRect( const Rectangle& rRect )
{
    if( mpFillColor )
    {
        const BitmapColor&  rFillColor = *mpFillColor;
        Point               aPoint;
        Rectangle           aRect( aPoint, maBitmap.GetSizePixel() );

        aRect.Intersection( rRect );

        if( !aRect.IsEmpty() )
        {
            const long  nStartX = rRect.Left();
            const long  nStartY = rRect.Top();
            const long  nEndX = rRect.Right();
            const long  nEndY = rRect.Bottom();

            for( long nY = nStartY; nY <= nEndY; nY++ )
                for( long nX = nStartX; nX <= nEndX; nX++ )
                    SetPixel( nY, nX, rFillColor );
        }
    }
}

// ------------------------------------------------------------------

void BitmapWriteAccess::DrawRect( const Rectangle& rRect )
{
    if( mpFillColor )
        FillRect( rRect );

    if( mpLineColor && ( !mpFillColor || ( *mpFillColor != *mpLineColor ) ) )
    {
        DrawLine( rRect.TopLeft(), rRect.TopRight() );
        DrawLine( rRect.TopRight(), rRect.BottomRight() );
        DrawLine( rRect.BottomRight(), rRect.BottomLeft() );
        DrawLine( rRect.BottomLeft(), rRect.TopLeft() );
    }
}

// ------------------------------------------------------------------

void BitmapWriteAccess::FillPolygon( const Polygon& rPoly )
{
    const USHORT nSize = rPoly.GetSize();

    if( nSize && mpFillColor )
    {
        const BitmapColor&  rFillColor = *mpFillColor;
        Region              aRegion( rPoly );
        Rectangle           aRect;

        aRegion.Intersect( Rectangle( Point(), Size( Width(), Height() ) ) );

        if( !aRegion.IsEmpty() )
        {
            RegionHandle aRegHandle( aRegion.BeginEnumRects() );

            while( aRegion.GetNextEnumRect( aRegHandle, aRect ) )
                for( long nY = aRect.Top(), nEndY = aRect.Bottom(); nY <= nEndY; nY++ )
                    for( long nX = aRect.Left(), nEndX = aRect.Right(); nX <= nEndX; nX++ )
                        SetPixel( nY, nX, rFillColor );

            aRegion.EndEnumRects( aRegHandle );
        }
    }
}

// ------------------------------------------------------------------

void BitmapWriteAccess::DrawPolygon( const Polygon& rPoly )
{
    if( mpFillColor )
        FillPolygon( rPoly );

    if( mpLineColor && ( !mpFillColor || ( *mpFillColor != *mpLineColor ) ) )
    {
        const USHORT nSize = rPoly.GetSize();

        for( USHORT i = 0, nSize1 = nSize - 1; i < nSize1; i++ )
            DrawLine( rPoly[ i ], rPoly[ i + 1 ] );

        if( rPoly[ nSize - 1 ] != rPoly[ 0 ] )
            DrawLine( rPoly[ nSize - 1 ], rPoly[ 0 ] );
    }
}

// ------------------------------------------------------------------

void BitmapWriteAccess::FillPolyPolygon( const PolyPolygon& rPolyPoly )
{
    const USHORT nCount = rPolyPoly.Count();

    if( nCount && mpFillColor )
    {
        const BitmapColor&  rFillColor = *mpFillColor;
        Region              aRegion( rPolyPoly );
        Rectangle           aRect;

        aRegion.Intersect( Rectangle( Point(), Size( Width(), Height() ) ) );

        if( !aRegion.IsEmpty() )
        {
            RegionHandle aRegHandle( aRegion.BeginEnumRects() );

            while( aRegion.GetNextEnumRect( aRegHandle, aRect ) )
                for( long nY = aRect.Top(), nEndY = aRect.Bottom(); nY <= nEndY; nY++ )
                    for( long nX = aRect.Left(), nEndX = aRect.Right(); nX <= nEndX; nX++ )
                        SetPixel( nY, nX, rFillColor );

            aRegion.EndEnumRects( aRegHandle );
        }
    }
}

// ------------------------------------------------------------------

void BitmapWriteAccess::DrawPolyPolygon( const PolyPolygon& rPolyPoly )
{
    if( mpFillColor )
        FillPolyPolygon( rPolyPoly );

    if( mpLineColor && ( !mpFillColor || ( *mpFillColor != *mpLineColor ) ) )
    {
        for( USHORT n = 0, nCount = rPolyPoly.Count(); n < nCount; )
        {
            const Polygon&  rPoly = rPolyPoly[ n++ ];
            const USHORT    nSize = rPoly.GetSize();

            if( nSize )
            {
                for( USHORT i = 0, nSize1 = nSize - 1; i < nSize1; i++ )
                    DrawLine( rPoly[ i ], rPoly[ i + 1 ] );

                if( rPoly[ nSize - 1 ] != rPoly[ 0 ] )
                    DrawLine( rPoly[ nSize - 1 ], rPoly[ 0 ] );
            }
        }
    }
}
<|endoftext|>


<commit_before>// Copyright 2010 Google Inc. All Rights Reserved.
// Author: jacobsa@google.com (Aaron Jacobs)
//
// 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.

// A driver for Google JS Test. Executes each JS file it's given, in order,
// then runs any tests that were registered in the process.
//
// Input files should be topologically sorted. That is, if you have
// foo_test.js, which tests foo.js, which depends on bar.js and baz.js, the
// input should look like this:
//
//     --js_files=\
//         bar.js,\
//         baz.js,\
//         foo.js,\
//         foo_test.js
//
// (The relative order of bar.js and baz.js does not matter in this example.

#include <string>
#include <vector>

#include <gflags/gflags.h>

#include "base/integral_types.h"
#include "base/logging.h"
#include "file/file_utils.h"
#include "gjstest/internal/compiler/compiler.pb.h"
#include "gjstest/internal/driver/cpp/driver.h"
#include "strings/strutil.h"

DEFINE_string(js_files, "",
              "The list of JS files to execute, comma separated.");

DEFINE_string(xml_output_file, "", "An XML file to write results to.");
DEFINE_string(filter, "", "Regular expression for test names to run.");

namespace gjstest {

static bool Run() {
  // Find the file containing the scripts to be run, and load its contents.
  const string scripts_path =
      FindSingleFileWithSuffix(
          google::StringFromEnv("TEST_SRCDIR", ""),
          "-gjstest-scripts.binarypb");

  NamedScripts scripts;
  CHECK(scripts.ParseFromString(ReadFileOrDie(scripts_path)))
      << "Couldn't parse NamedScripts proto.";

  // Run the tests.
  string output;
  string xml;
  const bool success = RunTests(scripts, FLAGS_filter, &output, &xml);

  // Log the output.
  LOG(ERROR) << output;

  // Write out the XML file to the appropriate place.
  const string xml_path = google::StringFromEnv("XML_OUTPUT_FILE", "");
  WriteStringToFileOrDie(xml, xml_path);

  return success;
}

}  // namespace gjstest

int main(int argc, char** argv) {
  google::InitGoogleLogging(argv[0]);
  google::ParseCommandLineFlags(&argc, &argv, true);

  // Turn off timestamp and file number junk in the output of LOG().
  FLAGS_log_prefix = false;

  return gjstest::Run() ? 0 : 1;
}
<commit_msg>Finished refactoring.<commit_after>// Copyright 2010 Google Inc. All Rights Reserved.
// Author: jacobsa@google.com (Aaron Jacobs)
//
// 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.

// A driver for Google JS Test. Executes each JS file it's given, in order,
// then runs any tests that were registered in the process.
//
// Input files should be topologically sorted. That is, if you have
// foo_test.js, which tests foo.js, which depends on bar.js and baz.js, the
// input should look like this:
//
//     --js_files=\
//         bar.js,\
//         baz.js,\
//         foo.js,\
//         foo_test.js
//
// (The relative order of bar.js and baz.js does not matter in this example.

#include <string>
#include <vector>

#include <gflags/gflags.h>

#include "base/integral_types.h"
#include "base/logging.h"
#include "file/file_utils.h"
#include "gjstest/internal/compiler/compiler.pb.h"
#include "gjstest/internal/driver/cpp/driver.h"
#include "strings/strutil.h"

DEFINE_string(js_files, "",
              "The list of JS files to execute, comma separated.");

DEFINE_string(xml_output_file, "", "An XML file to write results to.");
DEFINE_string(filter, "", "Regular expression for test names to run.");

namespace gjstest {

// Attempt to read in all of the specified user scripts.
static bool GetScripts(
    NamedScripts* scripts,
    string* error) {
  vector<string> paths;
  SplitStringUsing(FLAGS_js_files, ",", &paths);

  for (uint32 i = 0; i < paths.size(); ++i) {
    const string& path = paths[i];

    NamedScript* script = scripts->add_script();
    script->set_name(Basename(path));
    script->set_source(ReadFileOrDie(path));
  }

  return true;
}

static bool Run() {
  // Attempt to load the appropriate scripts.
  NamedScripts scripts;
  string error;
  if (!GetScripts(&scripts, &error)) {
    LOG(ERROR) << "Failed to load scripts: " << error;
    return false;
  }

  // Run any tests registered.
  string output;
  string xml;
  const bool success = RunTests(scripts, FLAGS_filter, &output, &xml);

  // Log the output.
  //
  // TODO(jacobsa): Use a different severity?
  LOG(ERROR) << output;

  // Write out the XML file to the appropriate place.
  if (!FLAGS_xml_output_file.empty()) {
    WriteStringToFileOrDie(xml, FLAGS_xml_output_file);
  }

  return success;
}

}  // namespace gjstest

int main(int argc, char** argv) {
  google::InitGoogleLogging(argv[0]);
  google::ParseCommandLineFlags(&argc, &argv, true);

  // Turn off timestamp and file number junk in the output of LOG().
  FLAGS_log_prefix = false;

  return gjstest::Run() ? 0 : 1;
}
<|endoftext|>


<commit_before>// Copyright (c) 2013-2018 mogemimi. Distributed under the MIT license.

#pragma once

#include "Pomdog/Basic/Export.hpp"
#include "Pomdog/Signals/Signal.hpp"
#include <cstdint>
#include <string>

namespace Pomdog {

class Rectangle;
enum class MouseCursor : std::uint8_t;

class POMDOG_EXPORT GameWindow {
public:
    GameWindow() = default;
    GameWindow(const GameWindow&) = delete;
    GameWindow & operator=(const GameWindow&) = delete;

    virtual ~GameWindow() = default;

    virtual bool GetAllowUserResizing() const = 0;

    virtual void SetAllowUserResizing(bool allowResizing) = 0;

    virtual std::string GetTitle() const = 0;

    virtual void SetTitle(const std::string& title) = 0;

    virtual Rectangle GetClientBounds() const = 0;

    virtual void SetClientBounds(const Rectangle& clientBounds) = 0;

    ///@brief Return true if the mouse cursor is visible, false otherwise.
    virtual bool IsMouseCursorVisible() const = 0;

    virtual void SetMouseCursorVisible(bool visible) = 0;

    virtual void SetMouseCursor(MouseCursor cursor) = 0;

    Signal<void(int width, int height)> ClientSizeChanged;
};

} // namespace Pomdog
<commit_msg>Add documentation for GameWindow<commit_after>// Copyright (c) 2013-2018 mogemimi. Distributed under the MIT license.

#pragma once

#include "Pomdog/Basic/Export.hpp"
#include "Pomdog/Signals/Signal.hpp"
#include <cstdint>
#include <string>

namespace Pomdog {

class Rectangle;
enum class MouseCursor : std::uint8_t;

/// Base interface for application window that contains the game.
///
/// Instances of this class are unique.
///
/// @todo Implement window resizing in X11 backend.
/// @todo Implement cursor visibility in X11 backend.
/// @todo Implement cursor setting in X11 backend.
/// @todo ClientSizeChanged should fire in Cocoa and Win32 backends.
class POMDOG_EXPORT GameWindow {
public:
    GameWindow() = default;
    GameWindow(const GameWindow&) = delete;
    GameWindow & operator=(const GameWindow&) = delete;

    virtual ~GameWindow() = default;

    /// @return If window can be resized by user.
    /// @warning Not implemented in X11 !
    virtual bool GetAllowUserResizing() const = 0;

    /// Set if window can be resized by user.
    /// @param allowResizing New value of the resizing flag.
    /// @warning Not implemented in X11 !
    virtual void SetAllowUserResizing(bool allowResizing) = 0;

    /// @return Title of the window.
    virtual std::string GetTitle() const = 0;

    /// Set title of the window.
    /// @param title New title of the window.
    virtual void SetTitle(const std::string& title) = 0;

    /// @return Rectangle that describes windows position and size.
    virtual Rectangle GetClientBounds() const = 0;

    /// Moves the window to the @p clientBounds x and y, and sets windows
    /// width and height according to the method parameter.
    /// @param clientBounds Rectangle that will adjust the window.
    virtual void SetClientBounds(const Rectangle& clientBounds) = 0;

    /// @return True if the mouse cursor is visible, false otherwise.
    /// @warning Not implemented in X11 !
    virtual bool IsMouseCursorVisible() const = 0;

    /// Set visibility of the cursor in the window
    /// @param visible New value of the cursor visibility flag.
    /// @warning Not implemented in X11 !
    virtual void SetMouseCursorVisible(bool visible) = 0;

    /// Set mouse cursor system provided asset.
    /// @param cursor New mouse cursor asset.
    /// @warning Not implemented in X11 !
    virtual void SetMouseCursor(MouseCursor cursor) = 0;

    /// Signal that fires when windows size is changed.
    /// @warning Do not fire in Cocoa and Win32 !
    Signal<void(int width, int height)> ClientSizeChanged;
};

} // namespace Pomdog
<|endoftext|>