text stringlengths 54 60.6k |
|---|
<commit_before>//
// async_client.cpp
// ~~~~~~~~~~~~~~~~
//
// Copyright (c) 2003-2010 Christopher M. Kohlhoff (chris at kohlhoff dot com)
//
// Distributed under the Boost Software License, Version 1.0. (See accompanying
// file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt)
//
#include <iostream>
#include <istream>
#include <ostream>
#include <string>
#include <boost/asio.hpp>
#include <boost/bind.hpp>
#include <boost/asio/ssl.hpp>
#include <fstream>
#include <boost/archive/iterators/base64_from_binary.hpp>
#include <boost/archive/iterators/binary_from_base64.hpp>
#include <boost/archive/iterators/transform_width.hpp>
#include <boost/archive/iterators/insert_linebreaks.hpp>
using namespace boost::archive::iterators;
using boost::asio::ip::tcp;
class client
{
public:
client(boost::asio::io_service& io_service,
const std::string& server, const std::string& path, const std::string& binaryImgStr)
: resolver_(io_service),
ctx(io_service, boost::asio::ssl::context::method::tlsv12_client),
socket_(io_service, ctx)
{
SSL_set_tlsext_host_name(socket_.native_handle(),server.c_str());
ctx.set_default_verify_paths();
/*ctx.set_options(boost::asio::ssl::context::default_workarounds
| boost::asio::ssl::context::no_sslv2
| boost::asio::ssl::context::no_sslv3
| boost::asio::ssl::context::no_tlsv1
| boost::asio::ssl::context::no_tlsv1_1);*/
//socket_.set_verify_mode(boost::asio::ssl::verify_none);
//ctx.load_verify_file("ca.pem");
std::string b64ImgStr = base64_encode(reinterpret_cast<const unsigned char*>(binaryImgStr.c_str()), binaryImgStr.length());
// Form the request. We specify the "Connection: close" header so that the
// server will close the socket after transmitting the response. This will
// allow us to treat all data up until the EOF as the content.
std::ostream request_stream(&request_);
request_stream << "POST " << path << " HTTP/1.1\r\n";
request_stream << "Host: " << server << "\r\n";
request_stream << "content-type: application/json;charset=UTF-8\r\n";
std::string bodyStartStr = "{\"httpMethod\":\"POST\",\"pathWithQueryString\":\"/mxnet-test-dev-hello\",\"body\":\"{\\\"b64Img\\\": \\\"";
std::string bodyEndStr = "\\\"}\",\"headers\":{},\"stageVariables\":{},\"withAuthorization\":false}\r\n";
request_stream << "content-length: " << std::to_string(bodyStartStr.length() + b64ImgStr.length() + bodyEndStr.length()) << "\r\n";
request_stream << "Connection: close\r\n\r\n";
request_stream << bodyStartStr << b64ImgStr << bodyEndStr;
//request_stream << "Accept: */*\r\n";
// Start an asynchronous resolve to translate the server and service names
// into a list of endpoints.
tcp::resolver::query query(server, "https");
resolver_.async_resolve(query,
boost::bind(&client::handle_resolve, this,
boost::asio::placeholders::error,
boost::asio::placeholders::iterator));
}
private:
// http://renenyffenegger.ch/notes/development/Base64/Encoding-and-decoding-base-64-with-cpp
const std::string base64_chars =
"ABCDEFGHIJKLMNOPQRSTUVWXYZ"
"abcdefghijklmnopqrstuvwxyz"
"0123456789+/";
std::string base64_encode(unsigned char const* bytes_to_encode, unsigned int in_len) {
std::string ret;
int i = 0;
int j = 0;
unsigned char char_array_3[3];
unsigned char char_array_4[4];
while (in_len--) {
char_array_3[i++] = *(bytes_to_encode++);
if (i == 3) {
char_array_4[0] = (char_array_3[0] & 0xfc) >> 2;
char_array_4[1] = ((char_array_3[0] & 0x03) << 4) + ((char_array_3[1] & 0xf0) >> 4);
char_array_4[2] = ((char_array_3[1] & 0x0f) << 2) + ((char_array_3[2] & 0xc0) >> 6);
char_array_4[3] = char_array_3[2] & 0x3f;
for(i = 0; (i <4) ; i++)
ret += base64_chars[char_array_4[i]];
i = 0;
}
}
if (i)
{
for(j = i; j < 3; j++)
char_array_3[j] = '\0';
char_array_4[0] = ( char_array_3[0] & 0xfc) >> 2;
char_array_4[1] = ((char_array_3[0] & 0x03) << 4) + ((char_array_3[1] & 0xf0) >> 4);
char_array_4[2] = ((char_array_3[1] & 0x0f) << 2) + ((char_array_3[2] & 0xc0) >> 6);
for (j = 0; (j < i + 1); j++)
ret += base64_chars[char_array_4[j]];
while((i++ < 3))
ret += '=';
}
return ret;
}
//typedef transform_width< binary_from_base64<remove_whitespace<std::string::const_iterator> >, 8, 6 > it_binary_t;
/*
std::string b64Encode(const std::string& binaryStr)
{
typedef insert_linebreaks<base64_from_binary<transform_width<std::string::const_iterator,6,8> >, 72 > it_base64_t;
unsigned int writePaddChars = (3-binaryStr.length()%3)%3;
std::string base64(it_base64_t(binaryStr.begin()),it_base64_t(binaryStr.end()));
base64.append(writePaddChars,'=');
return base64;
}
*/
void handle_resolve(const boost::system::error_code& err,
tcp::resolver::iterator endpoint_iterator)
{
if (!err)
{
// std::cout << "Resolve OK" << "\n";
socket_.set_verify_mode(boost::asio::ssl::verify_peer);
socket_.set_verify_callback(
boost::bind(&client::verify_certificate, this, _1, _2));
boost::asio::async_connect(socket_.lowest_layer(), endpoint_iterator,
boost::bind(&client::handle_connect, this,
boost::asio::placeholders::error));
}
else
{
std::cout << "Error resolve: " << err.message() << "\n";
}
}
bool verify_certificate(bool preverified,
boost::asio::ssl::verify_context& ctx)
{
// The verify callback can be used to check whether the certificate that is
// being presented is valid for the peer. For example, RFC 2818 describes
// the steps involved in doing this for HTTPS. Consult the OpenSSL
// documentation for more details. Note that the callback is called once
// for each certificate in the certificate chain, starting from the root
// certificate authority.
// In this example we will simply print the certificate's subject name.
char subject_name[256];
X509* cert = X509_STORE_CTX_get_current_cert(ctx.native_handle());
X509_NAME_oneline(X509_get_subject_name(cert), subject_name, 256);
// std::cout << "Verifying " << subject_name << "\n";
return preverified;
}
void handle_connect(const boost::system::error_code& err)
{
if (!err)
{
// std::cout << "Connect OK " << "\n";
// socket_.lowest_layer().set_option(tcp::no_delay(true));
socket_.async_handshake(boost::asio::ssl::stream_base::client,
boost::bind(&client::handle_handshake, this,
boost::asio::placeholders::error));
}
else
{
std::cout << "Connect failed: " << err.message() << "\n";
}
}
void handle_handshake(const boost::system::error_code& error)
{
if (!error)
{
// std::cout << "Handshake OK " << "\n";
// std::cout << "Request: " << "\n";
const char* header=boost::asio::buffer_cast<const char*>(request_.data());
// std::cout << header << "\n";
// The handshake was successful. Send the request.
boost::asio::async_write(socket_, request_,
boost::bind(&client::handle_write_request, this,
boost::asio::placeholders::error));
}
else
{
std::cout << "Handshake failed: " << error.message() << "\n";
}
}
void handle_write_request(const boost::system::error_code& err)
{
if (!err)
{
// Read the response status line. The response_ streambuf will
// automatically grow to accommodate the entire line. The growth may be
// limited by passing a maximum size to the streambuf constructor.
boost::asio::async_read_until(socket_, response_, "\r\n",
boost::bind(&client::handle_read_status_line, this,
boost::asio::placeholders::error));
}
else
{
std::cout << "Error write req: " << err.message() << "\n";
}
}
void handle_read_status_line(const boost::system::error_code& err)
{
if (!err)
{
// Check that response is OK.
std::istream response_stream(&response_);
std::string http_version;
response_stream >> http_version;
unsigned int status_code;
response_stream >> status_code;
std::string status_message;
std::getline(response_stream, status_message);
if (!response_stream || http_version.substr(0, 5) != "HTTP/")
{
std::cout << "Invalid response\n";
return;
}
if (status_code != 200)
{
std::cout << "Response returned with status code ";
std::cout << status_code << "\n";
return;
}
std::cout << "Status code: " << status_code << "\n";
// Read the response headers, which are terminated by a blank line.
boost::asio::async_read_until(socket_, response_, "\r\n\r\n",
boost::bind(&client::handle_read_headers, this,
boost::asio::placeholders::error));
}
else
{
std::cout << "Error: " << err.message() << "\n";
}
}
void handle_read_headers(const boost::system::error_code& err)
{
if (!err)
{
// Process the response headers.
std::istream response_stream(&response_);
std::string header;
while (std::getline(response_stream, header) && header != "\r") {
// std::cout << header << "\n";
}
// std::cout << "\n";
// Write whatever content we already have to output.
if (response_.size() > 0)
std::cout << &response_;
// Start reading remaining data until EOF.
boost::asio::async_read(socket_, response_,
boost::asio::transfer_at_least(1),
boost::bind(&client::handle_read_content, this,
boost::asio::placeholders::error));
}
else
{
std::cout << "Error: " << err << "\n";
}
}
void handle_read_content(const boost::system::error_code& err)
{
if (!err)
{
// std::cout << "reading the content..." << std::endl;
// Write all of the data that has been read so far.
std::cout << &response_;
// Continue reading remaining data until EOF.
boost::asio::async_read(socket_, response_,
boost::asio::transfer_at_least(1),
boost::bind(&client::handle_read_content, this,
boost::asio::placeholders::error));
}
else if (err != boost::asio::error::eof)
{
std::cout << "Error: " << err << "\n";
}
}
tcp::resolver resolver_;
// https://stackoverflow.com/questions/40036854/creating-a-https-request-using-boost-asio-and-openssl
// http://www.boost.org/doc/libs/1_65_1/doc/html/boost_asio/overview/ssl.html
boost::asio::ssl::context ctx;
boost::asio::ssl::stream<tcp::socket> socket_;
boost::asio::streambuf request_;
boost::asio::streambuf response_;
};
int main(int argc, char* argv[])
{
try
{
if (argc != 4)
{
std::cout << "Usage: async_client <server> <path> <fileContainingPostBody>\n";
std::cout << "Example:\n";
std::cout << " async_client www.boost.org /LICENSE_1_0.txt\n";
return 1;
}
boost::asio::io_service io_service;
std::ifstream b64File(argv[3]);
std::stringstream b64ImgStream;
b64ImgStream << b64File.rdbuf();
std::string binaryImgStr = b64ImgStream.str();
//client c(io_service, "www.deelay.me", "/1000/hmpg.net");
client c(io_service, argv[1], argv[2], binaryImgStr);
io_service.run();
// std::cout << "should print first\n";
}
catch (std::exception& e)
{
std::cout << "Exception: " << e.what() << "\n";
}
return 0;
}
<commit_msg>update, save response to a stringstream<commit_after>//
// async_client.cpp
// ~~~~~~~~~~~~~~~~
//
// Copyright (c) 2003-2010 Christopher M. Kohlhoff (chris at kohlhoff dot com)
//
// Distributed under the Boost Software License, Version 1.0. (See accompanying
// file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt)
//
#include <iostream>
#include <istream>
#include <ostream>
#include <string>
#include <boost/asio.hpp>
#include <boost/bind.hpp>
#include <boost/asio/ssl.hpp>
#include <fstream>
#include <boost/archive/iterators/base64_from_binary.hpp>
#include <boost/archive/iterators/binary_from_base64.hpp>
#include <boost/archive/iterators/transform_width.hpp>
#include <boost/archive/iterators/insert_linebreaks.hpp>
using namespace boost::archive::iterators;
using boost::asio::ip::tcp;
class client
{
public:
std::stringstream resultss;
bool finished = false;
client(boost::asio::io_service& io_service,
const std::string& server, const std::string& path, const std::string& binaryImgStr)
: resolver_(io_service),
ctx(io_service, boost::asio::ssl::context::method::tlsv12_client),
socket_(io_service, ctx)
{
SSL_set_tlsext_host_name(socket_.native_handle(),server.c_str());
ctx.set_default_verify_paths();
/*ctx.set_options(boost::asio::ssl::context::default_workarounds
| boost::asio::ssl::context::no_sslv2
| boost::asio::ssl::context::no_sslv3
| boost::asio::ssl::context::no_tlsv1
| boost::asio::ssl::context::no_tlsv1_1);*/
//socket_.set_verify_mode(boost::asio::ssl::verify_none);
//ctx.load_verify_file("ca.pem");
std::string b64ImgStr = base64_encode(reinterpret_cast<const unsigned char*>(binaryImgStr.c_str()), binaryImgStr.length());
// Form the request. We specify the "Connection: close" header so that the
// server will close the socket after transmitting the response. This will
// allow us to treat all data up until the EOF as the content.
std::ostream request_stream(&request_);
request_stream << "POST " << path << " HTTP/1.1\r\n";
request_stream << "Host: " << server << "\r\n";
request_stream << "content-type: application/json;charset=UTF-8\r\n";
std::string bodyStartStr = "{\"httpMethod\":\"POST\",\"pathWithQueryString\":\"/mxnet-test-dev-hello\",\"body\":\"{\\\"b64Img\\\": \\\"";
std::string bodyEndStr = "\\\"}\",\"headers\":{},\"stageVariables\":{},\"withAuthorization\":false}\r\n";
request_stream << "content-length: " << std::to_string(bodyStartStr.length() + b64ImgStr.length() + bodyEndStr.length()) << "\r\n";
request_stream << "Connection: close\r\n\r\n";
request_stream << bodyStartStr << b64ImgStr << bodyEndStr;
//request_stream << "Accept: */*\r\n";
// Start an asynchronous resolve to translate the server and service names
// into a list of endpoints.
tcp::resolver::query query(server, "https");
resolver_.async_resolve(query,
boost::bind(&client::handle_resolve, this,
boost::asio::placeholders::error,
boost::asio::placeholders::iterator));
}
private:
// http://renenyffenegger.ch/notes/development/Base64/Encoding-and-decoding-base-64-with-cpp
const std::string base64_chars =
"ABCDEFGHIJKLMNOPQRSTUVWXYZ"
"abcdefghijklmnopqrstuvwxyz"
"0123456789+/";
std::string base64_encode(unsigned char const* bytes_to_encode, unsigned int in_len) {
std::string ret;
int i = 0;
int j = 0;
unsigned char char_array_3[3];
unsigned char char_array_4[4];
while (in_len--) {
char_array_3[i++] = *(bytes_to_encode++);
if (i == 3) {
char_array_4[0] = (char_array_3[0] & 0xfc) >> 2;
char_array_4[1] = ((char_array_3[0] & 0x03) << 4) + ((char_array_3[1] & 0xf0) >> 4);
char_array_4[2] = ((char_array_3[1] & 0x0f) << 2) + ((char_array_3[2] & 0xc0) >> 6);
char_array_4[3] = char_array_3[2] & 0x3f;
for(i = 0; (i <4) ; i++)
ret += base64_chars[char_array_4[i]];
i = 0;
}
}
if (i)
{
for(j = i; j < 3; j++)
char_array_3[j] = '\0';
char_array_4[0] = ( char_array_3[0] & 0xfc) >> 2;
char_array_4[1] = ((char_array_3[0] & 0x03) << 4) + ((char_array_3[1] & 0xf0) >> 4);
char_array_4[2] = ((char_array_3[1] & 0x0f) << 2) + ((char_array_3[2] & 0xc0) >> 6);
for (j = 0; (j < i + 1); j++)
ret += base64_chars[char_array_4[j]];
while((i++ < 3))
ret += '=';
}
return ret;
}
//typedef transform_width< binary_from_base64<remove_whitespace<std::string::const_iterator> >, 8, 6 > it_binary_t;
/*
std::string b64Encode(const std::string& binaryStr)
{
typedef insert_linebreaks<base64_from_binary<transform_width<std::string::const_iterator,6,8> >, 72 > it_base64_t;
unsigned int writePaddChars = (3-binaryStr.length()%3)%3;
std::string base64(it_base64_t(binaryStr.begin()),it_base64_t(binaryStr.end()));
base64.append(writePaddChars,'=');
return base64;
}
*/
void handle_resolve(const boost::system::error_code& err,
tcp::resolver::iterator endpoint_iterator)
{
if (!err)
{
// std::cout << "Resolve OK" << "\n";
socket_.set_verify_mode(boost::asio::ssl::verify_peer);
socket_.set_verify_callback(
boost::bind(&client::verify_certificate, this, _1, _2));
boost::asio::async_connect(socket_.lowest_layer(), endpoint_iterator,
boost::bind(&client::handle_connect, this,
boost::asio::placeholders::error));
}
else
{
std::cout << "Error resolve: " << err.message() << "\n";
}
}
bool verify_certificate(bool preverified,
boost::asio::ssl::verify_context& ctx)
{
// The verify callback can be used to check whether the certificate that is
// being presented is valid for the peer. For example, RFC 2818 describes
// the steps involved in doing this for HTTPS. Consult the OpenSSL
// documentation for more details. Note that the callback is called once
// for each certificate in the certificate chain, starting from the root
// certificate authority.
// In this example we will simply print the certificate's subject name.
char subject_name[256];
X509* cert = X509_STORE_CTX_get_current_cert(ctx.native_handle());
X509_NAME_oneline(X509_get_subject_name(cert), subject_name, 256);
// std::cout << "Verifying " << subject_name << "\n";
return preverified;
}
void handle_connect(const boost::system::error_code& err)
{
if (!err)
{
// std::cout << "Connect OK " << "\n";
// socket_.lowest_layer().set_option(tcp::no_delay(true));
socket_.async_handshake(boost::asio::ssl::stream_base::client,
boost::bind(&client::handle_handshake, this,
boost::asio::placeholders::error));
}
else
{
std::cout << "Connect failed: " << err.message() << "\n";
}
}
void handle_handshake(const boost::system::error_code& error)
{
if (!error)
{
// std::cout << "Handshake OK " << "\n";
// std::cout << "Request: " << "\n";
const char* header=boost::asio::buffer_cast<const char*>(request_.data());
// std::cout << header << "\n";
// The handshake was successful. Send the request.
boost::asio::async_write(socket_, request_,
boost::bind(&client::handle_write_request, this,
boost::asio::placeholders::error));
}
else
{
std::cout << "Handshake failed: " << error.message() << "\n";
}
}
void handle_write_request(const boost::system::error_code& err)
{
if (!err)
{
// Read the response status line. The response_ streambuf will
// automatically grow to accommodate the entire line. The growth may be
// limited by passing a maximum size to the streambuf constructor.
boost::asio::async_read_until(socket_, response_, "\r\n",
boost::bind(&client::handle_read_status_line, this,
boost::asio::placeholders::error));
}
else
{
std::cout << "Error write req: " << err.message() << "\n";
}
}
void handle_read_status_line(const boost::system::error_code& err)
{
if (!err)
{
// Check that response is OK.
std::istream response_stream(&response_);
std::string http_version;
response_stream >> http_version;
unsigned int status_code;
response_stream >> status_code;
std::string status_message;
std::getline(response_stream, status_message);
if (!response_stream || http_version.substr(0, 5) != "HTTP/")
{
std::cout << "Invalid response\n";
return;
}
if (status_code != 200)
{
std::cout << "Response returned with status code ";
std::cout << status_code << "\n";
return;
}
// std::cout << "Status code: " << status_code << "\n";
// Read the response headers, which are terminated by a blank line.
boost::asio::async_read_until(socket_, response_, "\r\n\r\n",
boost::bind(&client::handle_read_headers, this,
boost::asio::placeholders::error));
}
else
{
std::cout << "Error: " << err.message() << "\n";
}
}
void handle_read_headers(const boost::system::error_code& err)
{
if (!err)
{
// Process the response headers.
std::istream response_stream(&response_);
std::string header;
while (std::getline(response_stream, header) && header != "\r") {
// std::cout << header << "\n";
}
// std::cout << "\n";
// Write whatever content we already have to output.
if (response_.size() > 0)
resultss << &response_;
// Start reading remaining data until EOF.
boost::asio::async_read(socket_, response_,
boost::asio::transfer_at_least(1),
boost::bind(&client::handle_read_content, this,
boost::asio::placeholders::error));
}
else
{
std::cout << "Error: " << err << "\n";
}
}
void handle_read_content(const boost::system::error_code& err)
{
if (!err)
{
// std::cout << "reading the content..." << std::endl;
// Write all of the data that has been read so far.
// std::cout << &response_;
resultss << &response_;
// Continue reading remaining data until EOF.
boost::asio::async_read(socket_, response_,
boost::asio::transfer_at_least(1),
boost::bind(&client::handle_read_content, this,
boost::asio::placeholders::error));
}
else if (err != boost::asio::error::eof)
{
std::cout << "Error: " << err << "\n";
} else {
// std::cout << std::endl;
resultss << std::endl;
finished = true;
}
}
tcp::resolver resolver_;
// https://stackoverflow.com/questions/40036854/creating-a-https-request-using-boost-asio-and-openssl
// http://www.boost.org/doc/libs/1_65_1/doc/html/boost_asio/overview/ssl.html
boost::asio::ssl::context ctx;
boost::asio::ssl::stream<tcp::socket> socket_;
boost::asio::streambuf request_;
boost::asio::streambuf response_;
};
int main(int argc, char* argv[])
{
try
{
if (argc != 4)
{
std::cout << "Usage: async_client <server> <path> <fileContainingPostBody>\n";
std::cout << "Example:\n";
std::cout << " async_client www.boost.org /LICENSE_1_0.txt\n";
return 1;
}
boost::asio::io_service io_service;
std::ifstream b64File(argv[3]);
std::stringstream b64ImgStream;
b64ImgStream << b64File.rdbuf();
std::string binaryImgStr = b64ImgStream.str();
//client c(io_service, "www.deelay.me", "/1000/hmpg.net");
client c(io_service, argv[1], argv[2], binaryImgStr);
io_service.run();
// std::cout << "should print first\n";
while (!c.finished) {}
std::cout << "The response is: \n";
std::cout << c.resultss.str();
}
catch (std::exception& e)
{
std::cout << "Exception: " << e.what() << "\n";
}
return 0;
}
<|endoftext|> |
<commit_before>#include "GUI.hpp"
#include "Level.hpp"
#include "FROG/Component/AudioSource.hpp"
#include "FROG/Collision/BoxCollider.hpp"
#include "FROG/Control.hpp"
#include "FROG/Control/ControlComponent.hpp"
#include "FROG/Debug.hpp"
#include "FROG/Translator.hpp"
#include "FROG/App.hpp"
#include "FROG/AppInfo.hpp"
#include "FROG/Random.hpp"
#include "FROG/Rendering/Sprite.hpp"
#include "FROG/Rendering/TextSprite.hpp"
#include "FROG/Physics/PhysicBody.hpp"
#include "MovePlayer.hpp"
#include "JoystickMover.hpp"
#include "FROG/Rendering/RenderingComponent.hpp"
#include <SFML/Graphics.hpp>
#include <iostream> // TODO remove
using namespace frog;
#define PLAYER_SPEED 512
const unsigned short TERRAIN_LAYER = 0;
const unsigned short TARGET_LAYER = 1;
const unsigned short PLAYER_LAYER = 2;
const unsigned short ENEMY_LAYER = 3;
const unsigned short GUI_LAYER = 4;
Level::Level(AppInfo& appinfo)
: Scene(appinfo),
m_appinfo(appinfo),
m_player(new Player),
m_terrain(new GameObject),
m_gui(new GameObject)
{
m_collisionManager = new LSAP();
m_fontManager.loadFromFile("assets/fonts/Hyperspace_Bold.ttf", GUI_FONT);
}
Level::~Level()
{
delete m_collisionManager;
m_ennemies.clear();
m_targets.clear();
}
void Level::enter()
{
setControls(m_player, m_appinfo );
m_terrain->addComponent( new Sprite(defaultTextureManager.get("TERRAIN_TEXTURE") ), "RENDERING" );
m_terrain->transform->setPosition(0, 0);
m_terrain->transform->layer = TERRAIN_LAYER;
addObject(m_terrain);
m_player->addComponent( new Sprite(defaultTextureManager.get("FROG_TEXTURE") ), "RENDERING" );
m_player->transform->setPosition( 400, 400 );
m_player->transform->layer = PLAYER_LAYER;
m_player->transform->setOrigin( 32, 32 );
std::cerr << "before adding audio" << std::endl;
m_player->addComponent( new AudioSource(), "AUDIO");
std::cerr << "after adding audio" << std::endl;
m_player->addComponent( new BoxCollider(sf::Vector2u(64, 64) ),
"COLLIDER");
m_player->getComponent<BoxCollider>("COLLIDER")->setScript(
[this](Collision c)
{
std::cout << "player collided " << std::endl;
this->m_player->getComponent<AudioSource>("AUDIO")->playSound(this->defaultSoundManager.get("BITE_1") );
auto bb1 = c.first->getComponent<Collider>("COLLIDER")->getBoundingBox();
std::cout << bb1.left << "," << bb1.top << " - " << bb1.width << "x" << bb1.height << std::endl;
auto bb2 = c.second->getComponent<Collider>("COLLIDER")->getBoundingBox();
std::cout << bb2.left << "," << bb2.top << " - " << bb2.width << "x" << bb2.height << std::endl;
}
);
addObject(m_player);
m_collisionManager->addObject(m_player);
std::shared_ptr<GUI> pgui(new GUI(800, 64,
m_fontManager.get(GUI_FONT),
3) );
m_gui->addComponent( pgui, "GUI" );
m_gui->transform->layer = GUI_LAYER;
m_gui->addComponent( new RenderingComponent(pgui.get() ), "RENDERING" );
addObject(m_gui);
}
void Level::postupdate()
{
m_collisionManager->update();
updateEnemies();
updateTargets();
sf::Time t = m_clock.getElapsedTime();
if( t.asSeconds() > 0.2f && m_targets.size() < 4 ){
spawnTarget();
}
if(t.asSeconds() > 0.4f ){
spawnEnemy();
m_clock.restart();
}
}
void Level::setControls(std::shared_ptr<GameObject> go, const AppInfo& appinfo)
{
std::shared_ptr<Command> moveleft(new MovePlayer(go.get(), -PLAYER_SPEED, 0, appinfo) );
std::shared_ptr<Command> moveright(new MovePlayer(go.get(), PLAYER_SPEED, 0, appinfo) );
std::shared_ptr<Command> moveup(new MovePlayer(go.get(), 0, -PLAYER_SPEED, appinfo) );
std::shared_ptr<Command> movedown(new MovePlayer(go.get(), 0, PLAYER_SPEED, appinfo) );
std::shared_ptr<Input> qkey(new KeyboardButton(sf::Keyboard::Q) );
std::shared_ptr<Input> dkey(new KeyboardButton(sf::Keyboard::D) );
std::shared_ptr<Input> zkey(new KeyboardButton(sf::Keyboard::Z) );
std::shared_ptr<Input> skey(new KeyboardButton(sf::Keyboard::S) );
std::shared_ptr<ControlComponent> ctrl(new ControlComponent(appinfo.eventList));
ctrl->bind(qkey, moveleft );
ctrl->bind(dkey, moveright );
ctrl->bind(zkey, moveup );
ctrl->bind(skey, movedown );
go->addComponent(ctrl, "CONTROL");
go->addComponent( new JoystickMover(PLAYER_SPEED/60.0f,
(sf::Joystick::Axis)XBOX::LSTICK_X,
(sf::Joystick::Axis)XBOX::LSTICK_Y,
25),
"JOYSTICK");
}
void Level::spawnEnemy()
{
std::shared_ptr<GameObject> e(new GameObject() );
std::shared_ptr<sf::RectangleShape> r(new sf::RectangleShape(sf::Vector2f(25,25) ) );
r->setFillColor(sf::Color::Red);
r->setOutlineThickness(2);
r->setOutlineColor(sf::Color::Black);
e->addComponent(new RenderingComponent( r ), "RENDERING" );
// m_boundingBox = new sf::RectangleShape(sf::Vector2f(25, 25) );
// m_boundingBox->setFillColor(sf::Color::Red);
e->addComponent(new PhysicBody(), "PHYSICS");
e->transform->layer = ENEMY_LAYER;
e->transform->setPosition(Random::get(100, 700), 50);
e->transform->setOrigin(12, 12);
auto phi = e->getComponent<PhysicBody>("PHYSICS");
phi->addVelocity(sf::Vector2f(Random::get(-2,2), Random::get(4, 5.5) ) );
phi->addRotation( Random::get(-20, 20) );
auto x_center = r->getLocalBounds().left + (r->getLocalBounds().width/2.0);
auto y_center = r->getLocalBounds().top + (r->getLocalBounds().height/2.0);
e->transform->setOrigin( sf::Vector2f(x_center, y_center) );
e->addComponent(new BoxCollider(sf::Vector2u(25,25) ), "COLLIDER");
m_ennemies.push_back(e);
addObject(e);
}
void Level::spawnTarget()
{
std::shared_ptr<GameObject> e(new GameObject() );
// m_boundingBox = new sf::RectangleShape(sf::Vector2f(25, 25) );
// m_boundingBox->setFillColor(sf::Color::Green);
e->addComponent(new Sprite(defaultTextureManager.get("BONUS_TEXTURE") ), "RENDERING" );
e->transform->setPosition(Random::get(100, 700), Random::get(50, 550) );
e->transform->layer = TARGET_LAYER;
// e->transform->setScale(0.5f, 0.5f);
// auto bounds = e->getComponent<Sprite>("RENDERING")->getLocalBounds();
// e->transform->setOrigin(bounds.left + bounds.width/2.0,
// bounds.top + bounds.height/2.0f);
e->transform->setOrigin(32, 32);
e->addComponent(new PhysicBody(), "PHYSICS");
auto phi = e->getComponent<PhysicBody>("PHYSICS");
phi->addVelocity(sf::Vector2f(Random::get(-10, 10) / 10.f,
Random::get(-10, 10) / 10.f ) );
phi->addGrowth( sf::Vector2f(-0.005f, -0.005f) );
phi->addRotation( Random::get(-20, 20) );
e->addComponent(new BoxCollider(sf::Vector2u(64,64) ), "COLLIDER");
m_targets.push_back(e);
m_collisionManager->addObject(e);
addObject(e);
}
void Level::updateEnemies()
{
for(auto it = m_ennemies.begin(); it != m_ennemies.end(); ++it)
{
// PhysicEngine::update( it->get() );
if((*it)->transform->getPosition().x > 800
|| (*it)->transform->getPosition().y > 600)
{
removeObject(*it);
it->reset();
*it = nullptr;
}
}
m_ennemies.remove(nullptr);
}
void Level::updateTargets()
{
for(auto it = m_targets.begin(); it != m_targets.end(); ++it)
{
// PhysicEngine::update( it->get() );
// m_collisionManager->updateObject( it->get() );
auto tr = (*it)->transform;
if ( tr->getPosition().x > 800
|| tr->getPosition().y > 600
|| tr->getPosition().x < -32
|| tr->getPosition().y < -32){
removeObject(*it);
it->reset();
*it = nullptr;
}
}
m_targets.remove(nullptr);
}
<commit_msg>dodger uses control factories<commit_after>#include "GUI.hpp"
#include "Level.hpp"
#include "FROG/Component/AudioSource.hpp"
#include "FROG/Collision/BoxCollider.hpp"
#include "FROG/Control.hpp"
#include "FROG/Control/ControlComponent.hpp"
#include "FROG/Debug.hpp"
#include "FROG/Translator.hpp"
#include "FROG/App.hpp"
#include "FROG/AppInfo.hpp"
#include "FROG/Random.hpp"
#include "FROG/Rendering/Sprite.hpp"
#include "FROG/Rendering/TextSprite.hpp"
#include "FROG/Physics/PhysicBody.hpp"
#include "MovePlayer.hpp"
#include "JoystickMover.hpp"
#include "FROG/Rendering/RenderingComponent.hpp"
#include <SFML/Graphics.hpp>
#include <iostream> // TODO remove
using namespace frog;
#define PLAYER_SPEED 512
const unsigned short TERRAIN_LAYER = 0;
const unsigned short TARGET_LAYER = 1;
const unsigned short PLAYER_LAYER = 2;
const unsigned short ENEMY_LAYER = 3;
const unsigned short GUI_LAYER = 4;
Level::Level(AppInfo& appinfo)
: Scene(appinfo),
m_appinfo(appinfo),
m_player(new Player),
m_terrain(new GameObject),
m_gui(new GameObject)
{
m_collisionManager = new LSAP();
m_fontManager.loadFromFile("assets/fonts/Hyperspace_Bold.ttf", GUI_FONT);
}
Level::~Level()
{
delete m_collisionManager;
m_ennemies.clear();
m_targets.clear();
}
void Level::enter()
{
setControls(m_player, m_appinfo );
m_terrain->addComponent( new Sprite(defaultTextureManager.get("TERRAIN_TEXTURE") ), "RENDERING" );
m_terrain->transform->setPosition(0, 0);
m_terrain->transform->layer = TERRAIN_LAYER;
addObject(m_terrain);
m_player->addComponent( new Sprite(defaultTextureManager.get("FROG_TEXTURE") ), "RENDERING" );
m_player->transform->setPosition( 400, 400 );
m_player->transform->layer = PLAYER_LAYER;
m_player->transform->setOrigin( 32, 32 );
std::cerr << "before adding audio" << std::endl;
m_player->addComponent( new AudioSource(), "AUDIO");
std::cerr << "after adding audio" << std::endl;
m_player->addComponent( new BoxCollider(sf::Vector2u(64, 64) ),
"COLLIDER");
m_player->getComponent<BoxCollider>("COLLIDER")->setScript(
[this](Collision c)
{
std::cout << "player collided " << std::endl;
this->m_player->getComponent<AudioSource>("AUDIO")->playSound(this->defaultSoundManager.get("BITE_1") );
}
);
addObject(m_player);
m_collisionManager->addObject(m_player);
std::shared_ptr<GUI> pgui(new GUI(800, 64,
m_fontManager.get(GUI_FONT),
3) );
m_gui->addComponent( pgui, "GUI" );
m_gui->transform->layer = GUI_LAYER;
m_gui->addComponent( new RenderingComponent(pgui.get() ), "RENDERING" );
addObject(m_gui);
}
void Level::postupdate()
{
m_collisionManager->update();
updateEnemies();
updateTargets();
sf::Time t = m_clock.getElapsedTime();
if( t.asSeconds() > 0.2f && m_targets.size() < 4 ){
spawnTarget();
}
if(t.asSeconds() > 0.4f ){
spawnEnemy();
m_clock.restart();
}
}
void Level::setControls(std::shared_ptr<GameObject> go, const AppInfo& appinfo)
{
std::shared_ptr<Command> moveleft(new MovePlayer(go.get(), -PLAYER_SPEED, 0, appinfo) );
std::shared_ptr<Command> moveright(new MovePlayer(go.get(), PLAYER_SPEED, 0, appinfo) );
std::shared_ptr<Command> moveup(new MovePlayer(go.get(), 0, -PLAYER_SPEED, appinfo) );
std::shared_ptr<Command> movedown(new MovePlayer(go.get(), 0, PLAYER_SPEED, appinfo) );
auto qkey = KeyboardButton::create(sf::Keyboard::Q);
auto dkey = KeyboardButton::create(sf::Keyboard::D);
auto zkey = KeyboardButton::create(sf::Keyboard::Z);
auto skey = KeyboardButton::create(sf::Keyboard::S);
std::shared_ptr<ControlComponent> ctrl(new ControlComponent(appinfo.eventList));
ctrl->bind(qkey, moveleft );
ctrl->bind(dkey, moveright );
ctrl->bind(zkey, moveup );
ctrl->bind(skey, movedown );
go->addComponent(ctrl, "CONTROL");
go->addComponent( new JoystickMover(PLAYER_SPEED/60.0f,
(sf::Joystick::Axis)XBOX::LSTICK_X,
(sf::Joystick::Axis)XBOX::LSTICK_Y,
25),
"JOYSTICK");
}
void Level::spawnEnemy()
{
std::shared_ptr<GameObject> e(new GameObject() );
std::shared_ptr<sf::RectangleShape> r(new sf::RectangleShape(sf::Vector2f(25,25) ) );
r->setFillColor(sf::Color::Red);
r->setOutlineThickness(2);
r->setOutlineColor(sf::Color::Black);
e->addComponent(new RenderingComponent( r ), "RENDERING" );
// m_boundingBox = new sf::RectangleShape(sf::Vector2f(25, 25) );
// m_boundingBox->setFillColor(sf::Color::Red);
e->addComponent(new PhysicBody(), "PHYSICS");
e->transform->layer = ENEMY_LAYER;
e->transform->setPosition(Random::get(100, 700), 50);
e->transform->setOrigin(12, 12);
auto phi = e->getComponent<PhysicBody>("PHYSICS");
phi->addVelocity(sf::Vector2f(Random::get(-2,2), Random::get(4, 5.5) ) );
phi->addRotation( Random::get(-20, 20) );
auto x_center = r->getLocalBounds().left + (r->getLocalBounds().width/2.0);
auto y_center = r->getLocalBounds().top + (r->getLocalBounds().height/2.0);
e->transform->setOrigin( sf::Vector2f(x_center, y_center) );
e->addComponent(new BoxCollider(sf::Vector2u(25,25) ), "COLLIDER");
m_ennemies.push_back(e);
addObject(e);
}
void Level::spawnTarget()
{
std::shared_ptr<GameObject> e(new GameObject() );
// m_boundingBox = new sf::RectangleShape(sf::Vector2f(25, 25) );
// m_boundingBox->setFillColor(sf::Color::Green);
e->addComponent(new Sprite(defaultTextureManager.get("BONUS_TEXTURE") ), "RENDERING" );
e->transform->setPosition(Random::get(100, 700), Random::get(50, 550) );
e->transform->layer = TARGET_LAYER;
// e->transform->setScale(0.5f, 0.5f);
// auto bounds = e->getComponent<Sprite>("RENDERING")->getLocalBounds();
// e->transform->setOrigin(bounds.left + bounds.width/2.0,
// bounds.top + bounds.height/2.0f);
e->transform->setOrigin(32, 32);
e->addComponent(new PhysicBody(), "PHYSICS");
auto phi = e->getComponent<PhysicBody>("PHYSICS");
phi->addVelocity(sf::Vector2f(Random::get(-10, 10) / 10.f,
Random::get(-10, 10) / 10.f ) );
phi->addGrowth( sf::Vector2f(-0.005f, -0.005f) );
phi->addRotation( Random::get(-20, 20) );
e->addComponent(new BoxCollider(sf::Vector2u(64,64) ), "COLLIDER");
m_targets.push_back(e);
m_collisionManager->addObject(e);
addObject(e);
}
void Level::updateEnemies()
{
for(auto it = m_ennemies.begin(); it != m_ennemies.end(); ++it)
{
// PhysicEngine::update( it->get() );
if((*it)->transform->getPosition().x > 800
|| (*it)->transform->getPosition().y > 600)
{
removeObject(*it);
it->reset();
*it = nullptr;
}
}
m_ennemies.remove(nullptr);
}
void Level::updateTargets()
{
for(auto it = m_targets.begin(); it != m_targets.end(); ++it)
{
// PhysicEngine::update( it->get() );
// m_collisionManager->updateObject( it->get() );
auto tr = (*it)->transform;
if ( tr->getPosition().x > 800
|| tr->getPosition().y > 600
|| tr->getPosition().x < -32
|| tr->getPosition().y < -32){
removeObject(*it);
it->reset();
*it = nullptr;
}
}
m_targets.remove(nullptr);
}
<|endoftext|> |
<commit_before>#include <iostream>
#include <set>
#include "TFile.h"
#include "TTree.h"
#include "TObject.h"
#include "TTreeFormula.h"
#include "FlatSkimmer.h"
ClassImp(FlatSkimmer)
//--------------------------------------------------------------------
FlatSkimmer::FlatSkimmer() :
fGoodLumiFilter(NULL),
fInDirectory("."),
fOutDirectory("."),
fCut("1"),
fTreeName("events"),
fRunExpr("runNum"),
fLumiExpr("lumiNum"),
fEventExpr("eventNum"),
fReportFreq(100000)
{
fCopyObjects.resize(0);
}
//--------------------------------------------------------------------
void
FlatSkimmer::Slim(TString fileName)
{
TFile *inFile = TFile::Open(fInDirectory + "/" + fileName);
TTree *inTree = (TTree*) inFile->Get(fTreeName);
TTreeFormula *cutter = new TTreeFormula("cutter",fCut,inTree);
Int_t runNum = 0;
Int_t lumiNum = 0;
ULong64_t eventNum = 0;
inTree->SetBranchAddress(fRunExpr,&runNum);
inTree->SetBranchAddress(fLumiExpr,&lumiNum);
inTree->SetBranchAddress(fEventExpr,&eventNum);
TFile *outFile = new TFile(fOutDirectory + "/" + fileName,"RECREATE");
TTree *outTree = inTree->CloneTree(0);
std::set<TString> eventsRecorded;
TString testString = "";
Int_t badlumis = 0;
Int_t cutevents = 0;
Int_t duplicates = 0;
for (Int_t iEntry = 0; iEntry != inTree->GetEntriesFast(); ++iEntry) {
if (iEntry % fReportFreq == 0)
std::cout << float(iEntry)/inTree->GetEntriesFast() << std::endl;
inTree->GetEntry(iEntry);
if (eventsRecorded.find(testString) == eventsRecorded.end()) {
if (fGoodLumiFilter->IsGood(runNum,lumiNum)) {
if (cutter->EvalInstance()) {
testString = TString::Format("%i_%i_%i",runNum,lumiNum,eventNum);
outTree->Fill();
eventsRecorded.insert(testString);
}
else
cutevents++;
}
else
badlumis++;
}
else
duplicates++;
}
outFile->WriteTObject(outTree,fTreeName,"Overwrite");
for (UInt_t iObj = 0; iObj != fCopyObjects.size(); ++iObj) {
if (inFile->Get(fCopyObjects[iObj]))
outFile->WriteTObject(inFile->Get(fCopyObjects[iObj])->Clone());
else
std::cout << "Could not find " << fCopyObjects[iObj] << " in " << fileName << std::endl;
}
outFile->Close();
inFile->Close();
std::cout << fileName << " events removed for" << std::endl;
std::cout << " Duplicates: " << duplicates << std::endl;
std::cout << " Bad Runs: " << badlumis << std::endl;
std::cout << " Event Cut: " << cutevents << std::endl;
}
<commit_msg>Fixed more long things.<commit_after>#include <iostream>
#include <set>
#include "TFile.h"
#include "TTree.h"
#include "TObject.h"
#include "TTreeFormula.h"
#include "FlatSkimmer.h"
ClassImp(FlatSkimmer)
//--------------------------------------------------------------------
FlatSkimmer::FlatSkimmer() :
fGoodLumiFilter(NULL),
fInDirectory("."),
fOutDirectory("."),
fCut("1"),
fTreeName("events"),
fRunExpr("runNum"),
fLumiExpr("lumiNum"),
fEventExpr("eventNum"),
fReportFreq(100000)
{
fCopyObjects.resize(0);
}
//--------------------------------------------------------------------
void
FlatSkimmer::Slim(TString fileName)
{
TFile *inFile = TFile::Open(fInDirectory + "/" + fileName);
TTree *inTree = (TTree*) inFile->Get(fTreeName);
TTreeFormula *cutter = new TTreeFormula("cutter",fCut,inTree);
Int_t runNum = 0;
Int_t lumiNum = 0;
ULong64_t eventNum = 0;
inTree->SetBranchAddress(fRunExpr,&runNum);
inTree->SetBranchAddress(fLumiExpr,&lumiNum);
inTree->SetBranchAddress(fEventExpr,&eventNum);
TFile *outFile = new TFile(fOutDirectory + "/" + fileName,"RECREATE");
TTree *outTree = inTree->CloneTree(0);
std::set<TString> eventsRecorded;
TString testString = "";
Int_t badlumis = 0;
Int_t cutevents = 0;
Int_t duplicates = 0;
for (Int_t iEntry = 0; iEntry != inTree->GetEntriesFast(); ++iEntry) {
if (iEntry % fReportFreq == 0)
std::cout << float(iEntry)/inTree->GetEntriesFast() << std::endl;
inTree->GetEntry(iEntry);
if (eventsRecorded.find(testString) == eventsRecorded.end()) {
if (fGoodLumiFilter->IsGood(runNum,lumiNum)) {
if (cutter->EvalInstance()) {
testString = TString::Format("%i_%i_%llu",runNum,lumiNum,eventNum);
outTree->Fill();
eventsRecorded.insert(testString);
}
else
cutevents++;
}
else
badlumis++;
}
else
duplicates++;
}
outFile->WriteTObject(outTree,fTreeName,"Overwrite");
for (UInt_t iObj = 0; iObj != fCopyObjects.size(); ++iObj) {
if (inFile->Get(fCopyObjects[iObj]))
outFile->WriteTObject(inFile->Get(fCopyObjects[iObj])->Clone());
else
std::cout << "Could not find " << fCopyObjects[iObj] << " in " << fileName << std::endl;
}
outFile->Close();
inFile->Close();
std::cout << fileName << " events removed for" << std::endl;
std::cout << " Duplicates: " << duplicates << std::endl;
std::cout << " Bad Runs: " << badlumis << std::endl;
std::cout << " Event Cut: " << cutevents << std::endl;
}
<|endoftext|> |
<commit_before>#include "AudioMonitorServer.hpp"
/*Constructor of AudioMonitorServer, create the server socket and initialize the data
* structure*/
AudioMonitorServer::AudioMonitorServer(int prt,int dbg):
debug(1),port(prt){
/* socket factory*/
if((servSockfd = socket(AF_INET,SOCK_STREAM,IPPROTO_TCP)) == -1)
{
perror("socket");
exit(EXIT_FAILURE);
}
/* init local addr structure and other params */
my_addr.sin_family = AF_INET;
my_addr.sin_port = htons(port);
my_addr.sin_addr.s_addr = htonl(INADDR_ANY);
addrlen = sizeof(struct sockaddr_in);
/* bind addr structure with socket */
if(bind(servSockfd,(struct sockaddr*)&my_addr,addrlen) == -1)
{
perror("bind");
close(servSockfd);
exit(EXIT_FAILURE);
}
/*Set servSockfd to be non-blocking*/
fcntl(servSockfd,F_SETFL,O_NONBLOCK);
/* set the socket in passive mode (only used for accept())
* and set the list size for pending connection*/
listen(servSockfd,SOMAXCONN);
max_select=servSockfd;
list_client=new std::vector<EASEAClientData>;
}
/**
* /brief Destructor of AudioMonitorServer
**/
AudioMonitorServer::~AudioMonitorServer(){
/*close every opened socket*/
unsigned int i;
for(i=0;i<list_client->size();i++){
close(list_client->at(i).getSocket());
}
}
void AudioMonitorServer::signalHandler(){
/*Signal handler in case of ^C, to close the sockets*/
//terminaison.sa_handler=sigIntEvent;
sigfillset(&terminaison.sa_mask);
terminaison.sa_flags=0;
sigaction(SIGINT,&terminaison,NULL);
}
void AudioMonitorServer::sigIntEvent(int sig){
unsigned int i;
close(servSockfd);
for(i=0;i<list_client->size();i++){
//send(list_client[i].getSocket(),"000/END",8,0);
close(list_client->at(i).getSocket());
}
exit(0);
}
void AudioMonitorServer::buildSocketList(){
unsigned int i;
FD_ZERO(&rdclient);
FD_SET(servSockfd,&rdclient);
for(i=0;i<list_client->size();i++){
FD_SET(list_client->at(i).getSocket(),&rdclient);
}
}
void AudioMonitorServer::newClient(){
int tmp_sockfd;
EASEAClientData* new_client;
tmp_sockfd = accept(servSockfd,(struct sockaddr*)&my_addr,&addrlen);
/*selected need to know the highest numerical socket value*/
if(tmp_sockfd>max_select){
max_select=tmp_sockfd;
}
if (debug) {
std::cout<<"nouveaux client"<<std::endl;
}
/*Adding the newly connected client to the list of client*/
new_client = new EASEAClientData(tmp_sockfd);
new_client->setIP(inet_ntoa(my_addr.sin_addr));
new_client->setPort(ntohs(my_addr.sin_port));
list_client->push_back(*new_client);
}
void AudioMonitorServer::recvSomething(){
if(FD_ISSET(servSockfd,&rdclient))
newClient();
else
recvFromClient();
}
/*FAIRE DES STRUCTS POUR L'ENVOI/RECEPTION*/
/* Case new data from known client*/
/* Check whose fd changed and received from them*/
void AudioMonitorServer::recvFromClient(){
char buf[1024];
MonitorParameter* params;
unsigned char typeOfParam;
unsigned int i;
EASEAClientData* changedClient;
memset(buf,'\0',1024); //reset buffer
for(i=0;i<list_client->size();i++){
if(list_client->at(i).getSocket()!=0){
if(FD_ISSET(list_client->at(i).getSocket(),&rdclient)){
changedClient=&list_client->at(i);
recv(changedClient->getSocket(),buf,1024,0);
typeOfParam=buf[0];
switch (typeOfParam) {
case SIMPLEDATA:
params=new ClientMonitorParameter(NULL);
params->deserialize(buf);
break;
default:
params=NULL;
}
if (!changedClient->toIgnore()) {
changedClient->verifyReception(params);
changedClient->verifySending(params);
changedClient->addData(params);
if (debug){
std::cout<<"I have received something from "<<
changedClient->getIP()<<":"<<changedClient->getPort()
<<std::endl;
float* last=changedClient->getLast();
std::cout<<last[0]<<" "<<last[1]<<" "<<last[2]<<" "<<last[3]<<std::endl;
delete[] last;
}
compo->notify(changedClient);
}
else{
list_client->at(i).setIgnoreFlag(false);
}
}
}
}
}
/**
* /brief Start the server, which will never stop listening
**/
void AudioMonitorServer::start(){
debug=1;
while(1){
buildSocketList();
if((select(max_select+1,&rdclient,NULL,NULL,NULL))>=1){
recvSomething();
}
}
}
/**
* /brief Add a Compositor
**/
void AudioMonitorServer::setCompositor(Compositor* compo){
this->compo=compo;
}
<commit_msg>Fix segfault when a client close its connection<commit_after>#include "AudioMonitorServer.hpp"
/*Constructor of AudioMonitorServer, create the server socket and initialize the data
* structure*/
AudioMonitorServer::AudioMonitorServer(int prt,int dbg):
debug(1),port(prt){
/* socket factory*/
if((servSockfd = socket(AF_INET,SOCK_STREAM,IPPROTO_TCP)) == -1)
{
perror("socket");
exit(EXIT_FAILURE);
}
/* init local addr structure and other params */
my_addr.sin_family = AF_INET;
my_addr.sin_port = htons(port);
my_addr.sin_addr.s_addr = htonl(INADDR_ANY);
addrlen = sizeof(struct sockaddr_in);
/* bind addr structure with socket */
if(bind(servSockfd,(struct sockaddr*)&my_addr,addrlen) == -1)
{
perror("bind");
close(servSockfd);
exit(EXIT_FAILURE);
}
/*Set servSockfd to be non-blocking*/
fcntl(servSockfd,F_SETFL,O_NONBLOCK);
/* set the socket in passive mode (only used for accept())
* and set the list size for pending connection*/
listen(servSockfd,SOMAXCONN);
max_select=servSockfd;
list_client=new std::vector<EASEAClientData>;
}
/**
* /brief Destructor of AudioMonitorServer
**/
AudioMonitorServer::~AudioMonitorServer(){
/*close every opened socket*/
unsigned int i;
for(i=0;i<list_client->size();i++){
close(list_client->at(i).getSocket());
}
}
void AudioMonitorServer::signalHandler(){
/*Signal handler in case of ^C, to close the sockets*/
//terminaison.sa_handler=sigIntEvent;
sigfillset(&terminaison.sa_mask);
terminaison.sa_flags=0;
sigaction(SIGINT,&terminaison,NULL);
}
void AudioMonitorServer::sigIntEvent(int sig){
unsigned int i;
close(servSockfd);
for(i=0;i<list_client->size();i++){
//send(list_client[i].getSocket(),"000/END",8,0);
close(list_client->at(i).getSocket());
}
exit(0);
}
void AudioMonitorServer::buildSocketList(){
unsigned int i;
FD_ZERO(&rdclient);
FD_SET(servSockfd,&rdclient);
for(i=0;i<list_client->size();i++){
FD_SET(list_client->at(i).getSocket(),&rdclient);
}
}
void AudioMonitorServer::newClient(){
int tmp_sockfd;
EASEAClientData* new_client;
tmp_sockfd = accept(servSockfd,(struct sockaddr*)&my_addr,&addrlen);
/*selected need to know the highest numerical socket value*/
if(tmp_sockfd>max_select){
max_select=tmp_sockfd;
}
if (debug) {
std::cout<<"nouveaux client"<<std::endl;
}
/*Adding the newly connected client to the list of client*/
new_client = new EASEAClientData(tmp_sockfd);
new_client->setIP(inet_ntoa(my_addr.sin_addr));
new_client->setPort(ntohs(my_addr.sin_port));
list_client->push_back(*new_client);
}
void AudioMonitorServer::recvSomething(){
if(FD_ISSET(servSockfd,&rdclient))
newClient();
else
recvFromClient();
}
/*FAIRE DES STRUCTS POUR L'ENVOI/RECEPTION*/
/* Case new data from known client*/
/* Check whose fd changed and received from them*/
void AudioMonitorServer::recvFromClient(){
char buf[1024];
MonitorParameter* params;
unsigned char typeOfParam;
unsigned int i;
EASEAClientData* changedClient;
memset(buf,'\0',1024); //reset buffer
for(i=0;i<list_client->size();i++){
if(list_client->at(i).getSocket()!=0){
if(FD_ISSET(list_client->at(i).getSocket(),&rdclient)){
changedClient=&list_client->at(i);
if(recv(changedClient->getSocket(),buf,1024,0)!=0){
typeOfParam=buf[0];
switch (typeOfParam) {
case SIMPLEDATA:
params=new ClientMonitorParameter(NULL);
params->deserialize(buf);
break;
default:
params=NULL;
}
if (!changedClient->toIgnore()) {
changedClient->verifyReception(params);
changedClient->verifySending(params);
changedClient->addData(params);
if (debug){
std::cout<<"I have received something from "<<
changedClient->getIP()<<":"<<changedClient->getPort()
<<std::endl;
float* last=changedClient->getLast();
std::cout<<last[0]<<" "<<last[1]<<" "<<last[2]<<" "<<last[3]<<std::endl;
delete[] last;
}
compo->notify(changedClient);
}
else{
list_client->at(i).setIgnoreFlag(false);
}
}
}
}
}
}
/**
* /brief Start the server, which will never stop listening
**/
void AudioMonitorServer::start(){
debug=1;
while(1){
buildSocketList();
if((select(max_select+1,&rdclient,NULL,NULL,NULL))>=1){
recvSomething();
}
}
}
/**
* /brief Add a Compositor
**/
void AudioMonitorServer::setCompositor(Compositor* compo){
this->compo=compo;
}
<|endoftext|> |
<commit_before>/* -*- mode: C++; c-file-style: "gnu" -*-
aboutdata.cpp
This file is part of KMail, the KDE mail client.
Copyright (c) 2003 Marc Mutz <mutz@kde.org>
KMail is free software; you can redistribute it and/or modify it
under the terms of the GNU General Public License, version 2, as
published by the Free Software Foundation.
KMail 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
General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program; if not, write to the Free Software
Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
In addition, as a special exception, the copyright holders give
permission to link the code of this program with any edition of
the Qt library by Trolltech AS, Norway (or with modified versions
of Qt that use the same license as Qt), and distribute linked
combinations including the two. You must obey the GNU General
Public License in all respects for all of the code used other than
Qt. If you modify this file, you may extend this exception to
your version of the file, but you are not obligated to do so. If
you do not wish to do so, delete this exception statement from
your version.
*/
#include "aboutdata.h"
#include "kmversion.h"
#include <klocale.h>
namespace KMail {
struct about_data {
const char * name;
const char * desc;
const char * email;
const char * web;
};
// This file should not be changed by anybody other than the maintainer
// or the co-maintainer.
static const about_data authors[] = {
{ "Ingo Kl\303\266cker", I18N_NOOP("Maintainer"),
"kloecker@kde.org", 0 },
{ "Don Sanders", I18N_NOOP("Adopter and co-maintainer"),
"sanders@kde.org", 0 },
{ "Stefan Taferner", I18N_NOOP("Original author"),
"taferner@kde.org", 0 },
{ "Michael H\303\244ckel", I18N_NOOP("Former maintainer"),
"haeckel@kde.org", 0 },
{ "Till Adam", I18N_NOOP("Core developer"),
"adam@kde.org", 0 },
{ "Carsten Burghardt", I18N_NOOP("Core developer"),
"burghardt@kde.org", 0 },
{ "Marc Mutz", I18N_NOOP("Core developer"),
"mutz@kde.org", 0 },
{ "Daniel Naber", I18N_NOOP("Documentation"),
"daniel.naber@t-online.de", 0 },
{ "Zack Rusin", I18N_NOOP("Core developer"),
"zack@kde.org", 0 },
{ "Toyohiro Asukai", 0,
"toyohiro@ksmplus.com", 0 },
{ "Waldo Bastian", 0,
"bastian@kde.org", 0 },
{ "Ryan Breen", I18N_NOOP("system tray notification"),
"ryan@ryanbreen.com", 0 },
{ "Steven Brown", 0,
"swbrown@ucsd.edu", 0 },
{ "Matthias Kalle Dalheimer", 0,
"kalle@kde.org", 0 },
{ "Matt Douhan", 0,
"matt@fruitsalad.org", 0 },
{ "Cristi Dumitrescu", 0,
"cristid@chip.ro", 0 },
{ "David Faure", 0,
"faure@kde.org", 0 },
{ "Philippe Fremy", 0,
"pfremy@chez.com", 0 },
{ "Kurt Granroth", 0,
"granroth@kde.org", 0 },
{ "Andreas Gungl", I18N_NOOP("PGP 6 support and further enhancements of the encryption support"),
"a.gungl@gmx.de", 0 },
{ "Steffen Hansen", 0,
"hansen@kde.org", 0 },
{ "Igor Janssen", 0,
"rm@linux.ru.net", 0 },
{ "Matt Johnston", 0,
"matt@caifex.org", 0 },
{ "Christer Kaivo-oja", 0,
"whizkid@telia.com", 0 },
{ "Lars Knoll", I18N_NOOP("Original encryption support\n"
"PGP 2 and PGP 5 support"),
"knoll@kde.org", 0 },
{ "J. Nick Koston", I18N_NOOP("GnuPG support"),
"bdraco@darkorb.net", 0 },
{ "Stephan Kulow", 0,
"coolo@kde.org", 0 },
{ "Guillaume Laurent", 0,
"glaurent@telegraph-road.org", 0 },
{ "Sam Magnuson", 0,
"sam@trolltech.com", 0 },
{ "Laurent Montel", 0,
"lmontel@mandrakesoft.com", 0 },
{ "Matt Newell", 0,
"newellm@proaxis.com", 0 },
{ "Denis Perchine", 0,
"dyp@perchine.com", 0 },
{ "Samuel Penn", 0,
"sam@bifrost.demon.co.uk", 0 },
{ "Carsten Pfeiffer", 0,
"pfeiffer@kde.org", 0 },
{ "Sven Radej", 0,
"radej@kde.org", 0 },
{ "Mark Roberts", 0,
"mark@taurine.demon.co.uk", 0 },
{ "Wolfgang Rohdewald", 0,
"wrohdewald@dplanet.ch", 0 },
{ "Espen Sand", 0,
"espen@kde.org", 0 },
{ "Aaron J. Seigo", 0,
"aseigo@olympusproject.org", 0 },
{ "George Staikos", 0,
"staikos@kde.org", 0 },
{ "Jason Stephenson", 0,
"panda@mis.net", 0 },
{ "Jacek Stolarczyk", 0,
"jacek@mer.chemia.polsl.gliwice.pl", 0 },
{ "Roberto S. Teixeira", 0,
"maragato@kde.org", 0 },
{ "Bo Thorsen", 0,
"bo@sonofthor.dk", 0 },
{ "Ronen Tzur", 0,
"rtzur@shani.net", 0 },
{ "Mario Weilguni", 0,
"mweilguni@sime.com", 0 },
{ "Wynn Wilkes", 0,
"wynnw@calderasystems.com", 0 },
{ "Robert D. Williams", 0,
"rwilliams@kde.org", 0 },
{ "Markus W\303\274bben", 0,
"markus.wuebben@kde.org", 0 },
{ "Karl-Heinz Zimmer", 0,
"khz@kde.org", 0 }
};
static const about_data credits[] = {
{ "Sam Abed", 0, 0, 0 }, // KConfigXT porting, smileys->emoticons replacement
{ "Joern Ahrens", 0, 0, 0 }, // implement wish 77182 (Add some separators to "Mark Message as" popup menu)
{ "Tom Albers", 0, 0, 0 }, // small fixes, bugzilla maintenance
{ "Albert Cervera Areny", 0, 0, 0 }, // implemented wish 88309 (optional compression of attachments)
{ "Patrick Audley", 0, 0, 0 }, // add optional graphical spam status to fancy headers
{ "Benjamin Azan", 0, 0, 0 }, // implemented todo status handling
{ "Albert Astals Cid", 0, 0, 0 }, // fix for bug:95441 (folder tree context menu doesn't show shortcuts assigned to the actions)
{ "Cornelius Schumacher", 0, "schumacher@kde.org", 0 }, // implemented the new recipients editor and picker
{ "Frederick Emmott", I18N_NOOP("Anti-virus support"),
"fred87@users.sf.net", 0 },
{ "Sandro Giessl", 0, 0, 0 }, // frame width fixes for widget styles
{ "Severin Greimel", 0, 0, 0 }, // several patches
{ "Shaheed Haque", 0, 0, 0 }, // fix for bug:69744 (Resource folders: "Journals" should be "Journal")
{ "Ingo Heeskens", 0, 0, 0 }, // implemented wish 34857 (per folder option for loading external references)
{ "Kurt Hindenburg", 0, 0, 0 }, // implemented wish 89003 (delete whole thread)
{ "Heiko Hund", I18N_NOOP("POP filters"),
"heiko@ist.eigentlich.net", 0 },
{ "Torsten Kasch", 0, 0, 0 }, // crash fix for Solaris (cf. bug:68801)
{ "Jason 'vanRijn' Kasper", 0, 0, 0 }, // implemented wish 79938 (configurable font for new/unread/important messages)
{ "Martijn Klingens", 0, 0, 0 }, // fix keyboard navigation in the Status combo of the quick search
{ "Christoph Kl\303\274nter", 0, 0, 0 }, // fix for bug:88216 (drag&drop from KAddressBook to the To: field)
{ "Martin Koller", 0, 0, 0 }, // optional columns in the message list
{ "Tobias K\303\266nig", 0, 0, 0 }, // edit recent addresses, store email<->OpenPGP key association in address book
{ "Volker Krause", 0, 0, 0 }, // implemented KWallet support, fixed multiple bugs
{ "Francois Kritzinger", 0, 0, 0 }, // fix bug in configuration dialog
{ "Danny Kukawka", 0, 0, 0 }, // DCOP enhancements for better message importing
{ "Roger Larsson", 0, 0, 0 }, // add name of checked account to status bar message
{ "Jeffrey McGee", 0, 0, 0 }, // fix for bug:64251
{ "Dirk M\303\274ller", 0, 0, 0 }, // KUrl() fixes and qt_cast optimizations
{ "OpenUsability", I18N_NOOP("Usability tests and improvements"), 0, "http://www.openusability.org" },
{ "Mario Teijeiro Otero", 0, 0, 0 }, // various vendor annotations fixes
{ "Simon Perreault", 0, 0, 0 }, // make the composer remember its "Use Fixed Font" setting (bug 49481)
{ "Bernhard Reiter", I18N_NOOP("\xC3\x84gypten and Kroupware project management"),
"bernhard@intevation.de", 0 },
{ "Edwin Schepers", 0, "yez@home.nl", 0 }, // composition of HTML messages
{ "Jakob Schr\303\266ter", 0, 0, 0 }, // implemented wish 28319 (X-Face support)
{ "Jan Simonson", I18N_NOOP("beta testing of PGP 6 support"),
"jan@simonson.pp.se", 0 },
{ "Paul Sprakes", 0, 0, 0 }, // fix for bug:63619 (filter button in toolbar doesn't work), context menu clean up
{ "Will Stephenson", 0, 0, 0 }, // added IM status indicator
{ "Hasso Tepper", 0, 0, 0 }, // improve layout of recipients editor
{ "Patrick S. Vogt", I18N_NOOP("timestamp for 'Transmission completed' status messages"),
"patrick.vogt@unibas.ch", 0 },
{ "Jan-Oliver Wagner", I18N_NOOP("\xC3\x84gypten and Kroupware project management"),
"jan@intevation.de", 0 },
{ "Wolfgang Westphal", I18N_NOOP("multiple encryption keys per address"),
"wolfgang.westphal@gmx.de", 0 },
{ "Thorsten Zachmann", I18N_NOOP("POP filters"),
"t.zachmann@zagge.de", 0 },
{ "Thomas Zander", 0, 0, 0 }
};
AboutData::AboutData()
: KAboutData( "kmail", 0, ki18n("KMail"),KMAIL_VERSION,
ki18n("KDE Email Client"), License_GPL,
ki18n("(c) 1997-2008, The KMail developers"), KLocalizedString(),
"http://kontact.kde.org/kmail/" )
{
using KMail::authors;
using KMail::credits;
for ( unsigned int i = 0 ; i < sizeof authors / sizeof *authors ; ++i )
addAuthor( ki18n(authors[i].name), ki18n(authors[i].desc), authors[i].email, authors[i].web );
for ( unsigned int i = 0 ; i < sizeof credits / sizeof *credits ; ++i )
addCredit( ki18n(credits[i].name), ki18n(credits[i].desc), credits[i].email, credits[i].web );
}
AboutData::~AboutData() {
}
} // namespace KMail
<commit_msg>Thomas McGuire took over maintainership of KMail.<commit_after>/* -*- mode: C++; c-file-style: "gnu" -*-
aboutdata.cpp
This file is part of KMail, the KDE mail client.
Copyright (c) 2003 Marc Mutz <mutz@kde.org>
KMail is free software; you can redistribute it and/or modify it
under the terms of the GNU General Public License, version 2, as
published by the Free Software Foundation.
KMail 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
General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program; if not, write to the Free Software
Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
In addition, as a special exception, the copyright holders give
permission to link the code of this program with any edition of
the Qt library by Trolltech AS, Norway (or with modified versions
of Qt that use the same license as Qt), and distribute linked
combinations including the two. You must obey the GNU General
Public License in all respects for all of the code used other than
Qt. If you modify this file, you may extend this exception to
your version of the file, but you are not obligated to do so. If
you do not wish to do so, delete this exception statement from
your version.
*/
#include "aboutdata.h"
#include "kmversion.h"
#include <klocale.h>
namespace KMail {
struct about_data {
const char * name;
const char * desc;
const char * email;
const char * web;
};
// This file should not be changed by anybody other than the maintainer
// or the co-maintainer.
static const about_data authors[] = {
{ "Thomas McGuire", I18N_NOOP("Maintainer"),
"thomas.mcguire@gmx.net", 0 },
{ "Don Sanders", I18N_NOOP("Adopter and co-maintainer"),
"sanders@kde.org", 0 },
{ "Stefan Taferner", I18N_NOOP("Original author"),
"taferner@kde.org", 0 },
{ "Michael H\303\244ckel", I18N_NOOP("Former maintainer"),
"haeckel@kde.org", 0 },
{ "Ingo Kl\303\266cker", I18N_NOOP("Former maintainer"),
"kloecker@kde.org", 0 },
{ "Till Adam", I18N_NOOP("Core developer"),
"adam@kde.org", 0 },
{ "Carsten Burghardt", I18N_NOOP("Core developer"),
"burghardt@kde.org", 0 },
{ "Marc Mutz", I18N_NOOP("Core developer"),
"mutz@kde.org", 0 },
{ "Daniel Naber", I18N_NOOP("Documentation"),
"daniel.naber@t-online.de", 0 },
{ "Zack Rusin", I18N_NOOP("Core developer"),
"zack@kde.org", 0 },
{ "Toyohiro Asukai", 0,
"toyohiro@ksmplus.com", 0 },
{ "Waldo Bastian", 0,
"bastian@kde.org", 0 },
{ "Ryan Breen", I18N_NOOP("system tray notification"),
"ryan@ryanbreen.com", 0 },
{ "Steven Brown", 0,
"swbrown@ucsd.edu", 0 },
{ "Matthias Kalle Dalheimer", 0,
"kalle@kde.org", 0 },
{ "Matt Douhan", 0,
"matt@fruitsalad.org", 0 },
{ "Cristi Dumitrescu", 0,
"cristid@chip.ro", 0 },
{ "David Faure", 0,
"faure@kde.org", 0 },
{ "Philippe Fremy", 0,
"pfremy@chez.com", 0 },
{ "Kurt Granroth", 0,
"granroth@kde.org", 0 },
{ "Andreas Gungl", I18N_NOOP("PGP 6 support and further enhancements of the encryption support"),
"a.gungl@gmx.de", 0 },
{ "Steffen Hansen", 0,
"hansen@kde.org", 0 },
{ "Igor Janssen", 0,
"rm@linux.ru.net", 0 },
{ "Matt Johnston", 0,
"matt@caifex.org", 0 },
{ "Christer Kaivo-oja", 0,
"whizkid@telia.com", 0 },
{ "Lars Knoll", I18N_NOOP("Original encryption support\n"
"PGP 2 and PGP 5 support"),
"knoll@kde.org", 0 },
{ "J. Nick Koston", I18N_NOOP("GnuPG support"),
"bdraco@darkorb.net", 0 },
{ "Stephan Kulow", 0,
"coolo@kde.org", 0 },
{ "Guillaume Laurent", 0,
"glaurent@telegraph-road.org", 0 },
{ "Sam Magnuson", 0,
"sam@trolltech.com", 0 },
{ "Laurent Montel", 0,
"lmontel@mandrakesoft.com", 0 },
{ "Matt Newell", 0,
"newellm@proaxis.com", 0 },
{ "Denis Perchine", 0,
"dyp@perchine.com", 0 },
{ "Samuel Penn", 0,
"sam@bifrost.demon.co.uk", 0 },
{ "Carsten Pfeiffer", 0,
"pfeiffer@kde.org", 0 },
{ "Sven Radej", 0,
"radej@kde.org", 0 },
{ "Mark Roberts", 0,
"mark@taurine.demon.co.uk", 0 },
{ "Wolfgang Rohdewald", 0,
"wrohdewald@dplanet.ch", 0 },
{ "Espen Sand", 0,
"espen@kde.org", 0 },
{ "Aaron J. Seigo", 0,
"aseigo@olympusproject.org", 0 },
{ "George Staikos", 0,
"staikos@kde.org", 0 },
{ "Jason Stephenson", 0,
"panda@mis.net", 0 },
{ "Jacek Stolarczyk", 0,
"jacek@mer.chemia.polsl.gliwice.pl", 0 },
{ "Roberto S. Teixeira", 0,
"maragato@kde.org", 0 },
{ "Bo Thorsen", 0,
"bo@sonofthor.dk", 0 },
{ "Ronen Tzur", 0,
"rtzur@shani.net", 0 },
{ "Mario Weilguni", 0,
"mweilguni@sime.com", 0 },
{ "Wynn Wilkes", 0,
"wynnw@calderasystems.com", 0 },
{ "Robert D. Williams", 0,
"rwilliams@kde.org", 0 },
{ "Markus W\303\274bben", 0,
"markus.wuebben@kde.org", 0 },
{ "Karl-Heinz Zimmer", 0,
"khz@kde.org", 0 }
};
static const about_data credits[] = {
{ "Sam Abed", 0, 0, 0 }, // KConfigXT porting, smileys->emoticons replacement
{ "Joern Ahrens", 0, 0, 0 }, // implement wish 77182 (Add some separators to "Mark Message as" popup menu)
{ "Tom Albers", 0, 0, 0 }, // small fixes, bugzilla maintenance
{ "Albert Cervera Areny", 0, 0, 0 }, // implemented wish 88309 (optional compression of attachments)
{ "Patrick Audley", 0, 0, 0 }, // add optional graphical spam status to fancy headers
{ "Benjamin Azan", 0, 0, 0 }, // implemented todo status handling
{ "Albert Astals Cid", 0, 0, 0 }, // fix for bug:95441 (folder tree context menu doesn't show shortcuts assigned to the actions)
{ "Cornelius Schumacher", 0, "schumacher@kde.org", 0 }, // implemented the new recipients editor and picker
{ "Frederick Emmott", I18N_NOOP("Anti-virus support"),
"fred87@users.sf.net", 0 },
{ "Sandro Giessl", 0, 0, 0 }, // frame width fixes for widget styles
{ "Severin Greimel", 0, 0, 0 }, // several patches
{ "Shaheed Haque", 0, 0, 0 }, // fix for bug:69744 (Resource folders: "Journals" should be "Journal")
{ "Ingo Heeskens", 0, 0, 0 }, // implemented wish 34857 (per folder option for loading external references)
{ "Kurt Hindenburg", 0, 0, 0 }, // implemented wish 89003 (delete whole thread)
{ "Heiko Hund", I18N_NOOP("POP filters"),
"heiko@ist.eigentlich.net", 0 },
{ "Torsten Kasch", 0, 0, 0 }, // crash fix for Solaris (cf. bug:68801)
{ "Jason 'vanRijn' Kasper", 0, 0, 0 }, // implemented wish 79938 (configurable font for new/unread/important messages)
{ "Martijn Klingens", 0, 0, 0 }, // fix keyboard navigation in the Status combo of the quick search
{ "Christoph Kl\303\274nter", 0, 0, 0 }, // fix for bug:88216 (drag&drop from KAddressBook to the To: field)
{ "Martin Koller", 0, 0, 0 }, // optional columns in the message list
{ "Tobias K\303\266nig", 0, 0, 0 }, // edit recent addresses, store email<->OpenPGP key association in address book
{ "Volker Krause", 0, 0, 0 }, // implemented KWallet support, fixed multiple bugs
{ "Francois Kritzinger", 0, 0, 0 }, // fix bug in configuration dialog
{ "Danny Kukawka", 0, 0, 0 }, // DCOP enhancements for better message importing
{ "Roger Larsson", 0, 0, 0 }, // add name of checked account to status bar message
{ "Jeffrey McGee", 0, 0, 0 }, // fix for bug:64251
{ "Dirk M\303\274ller", 0, 0, 0 }, // KUrl() fixes and qt_cast optimizations
{ "OpenUsability", I18N_NOOP("Usability tests and improvements"), 0, "http://www.openusability.org" },
{ "Mario Teijeiro Otero", 0, 0, 0 }, // various vendor annotations fixes
{ "Simon Perreault", 0, 0, 0 }, // make the composer remember its "Use Fixed Font" setting (bug 49481)
{ "Bernhard Reiter", I18N_NOOP("\xC3\x84gypten and Kroupware project management"),
"bernhard@intevation.de", 0 },
{ "Edwin Schepers", 0, "yez@home.nl", 0 }, // composition of HTML messages
{ "Jakob Schr\303\266ter", 0, 0, 0 }, // implemented wish 28319 (X-Face support)
{ "Jan Simonson", I18N_NOOP("beta testing of PGP 6 support"),
"jan@simonson.pp.se", 0 },
{ "Paul Sprakes", 0, 0, 0 }, // fix for bug:63619 (filter button in toolbar doesn't work), context menu clean up
{ "Will Stephenson", 0, 0, 0 }, // added IM status indicator
{ "Hasso Tepper", 0, 0, 0 }, // improve layout of recipients editor
{ "Patrick S. Vogt", I18N_NOOP("timestamp for 'Transmission completed' status messages"),
"patrick.vogt@unibas.ch", 0 },
{ "Jan-Oliver Wagner", I18N_NOOP("\xC3\x84gypten and Kroupware project management"),
"jan@intevation.de", 0 },
{ "Wolfgang Westphal", I18N_NOOP("multiple encryption keys per address"),
"wolfgang.westphal@gmx.de", 0 },
{ "Thorsten Zachmann", I18N_NOOP("POP filters"),
"t.zachmann@zagge.de", 0 },
{ "Thomas Zander", 0, 0, 0 }
};
AboutData::AboutData()
: KAboutData( "kmail", 0, ki18n("KMail"),KMAIL_VERSION,
ki18n("KDE Email Client"), License_GPL,
ki18n("(c) 1997-2008, The KMail developers"), KLocalizedString(),
"http://kontact.kde.org/kmail/" )
{
using KMail::authors;
using KMail::credits;
for ( unsigned int i = 0 ; i < sizeof authors / sizeof *authors ; ++i )
addAuthor( ki18n(authors[i].name), ki18n(authors[i].desc), authors[i].email, authors[i].web );
for ( unsigned int i = 0 ; i < sizeof credits / sizeof *credits ; ++i )
addCredit( ki18n(credits[i].name), ki18n(credits[i].desc), credits[i].email, credits[i].web );
}
AboutData::~AboutData() {
}
} // namespace KMail
<|endoftext|> |
<commit_before>// KMail Account
#include <stdlib.h>
#include <unistd.h>
#include <qdir.h>
#include <qstrlist.h>
#include <qtextstream.h>
#include <qfile.h>
#include <assert.h>
#include <kconfig.h>
#include <kapp.h>
#include <qregexp.h>
#include <klocale.h>
#include <kprocess.h>
#include <kmessagebox.h>
#include <kdebug.h>
#include "kmacctmgr.h"
#include "kmacctfolder.h"
#include "kmaccount.h"
#include "kmglobal.h"
#include "kmfoldermgr.h"
#include "kmfiltermgr.h"
#include "kmsender.h"
#include "kmmessage.h"
#include "kmbroadcaststatus.h"
//----------------------
#include "kmaccount.moc"
//-----------------------------------------------------------------------------
KMAccount::KMAccount(KMAcctMgr* aOwner, const char* aName)
{
initMetaObject();
assert(aOwner != NULL);
mOwner = aOwner;
mName = aName;
mFolder = NULL;
mTimer = NULL;
mInterval = 0;
mExclude = false;
mCheckingMail = FALSE;
connect(&mReceiptTimer,SIGNAL(timeout()),SLOT(sendReceipts()));
}
//-----------------------------------------------------------------------------
KMAccount::~KMAccount()
{
if (!kernel->shuttingDown() && mFolder) mFolder->removeAccount(this);
if (mTimer) deinstallTimer();
}
//-----------------------------------------------------------------------------
void KMAccount::setName(const QString& aName)
{
mName = aName;
}
//-----------------------------------------------------------------------------
void KMAccount::clearPasswd()
{
}
//-----------------------------------------------------------------------------
void KMAccount::setFolder(KMFolder* aFolder)
{
if(!aFolder)
{
kdDebug() << "KMAccount::setFolder() : aFolder == NULL" << endl;
mFolder = NULL;
return;
}
mFolder = (KMAcctFolder*)aFolder;
}
//-----------------------------------------------------------------------------
void KMAccount::readConfig(KConfig& config)
{
KMAcctFolder* folder;
QString folderName;
mFolder = NULL;
mName = config.readEntry("Name", i18n("Unnamed"));
folderName = config.readEntry("Folder", "");
setCheckInterval(config.readNumEntry("check-interval", 0));
setCheckExclude(config.readBoolEntry("check-exclude", false));
setPrecommand(config.readEntry("precommand"));
if (!folderName.isEmpty())
{
folder = (KMAcctFolder*)kernel->folderMgr()->find(folderName);
if (folder)
{
mFolder = folder;
mFolder->addAccount(this);
}
else kdDebug() << "Cannot find folder `" << (const char*)folderName << "' for account `" << (const char*)mName << "'." << endl;
}
}
//-----------------------------------------------------------------------------
void KMAccount::writeConfig(KConfig& config)
{
config.writeEntry("Type", type());
config.writeEntry("Name", mName);
config.writeEntry("Folder", mFolder ? mFolder->name() : QString::null);
config.writeEntry("check-interval", mInterval);
config.writeEntry("check-exclude", mExclude);
config.writeEntry("precommand", mPrecommand);
}
//-----------------------------------------------------------------------------
void KMAccount::sendReceipt(KMMessage* aMsg, const QString aReceiptTo)
{
KMMessage* newMsg = new KMMessage;
QString str, receiptTo;
KConfig* cfg = kapp->config();
bool sendReceipts;
cfg->setGroup("General");
sendReceipts = cfg->readBoolEntry("send-receipts", false);
if (!sendReceipts) return;
receiptTo = aReceiptTo;
receiptTo.replace(QRegExp("\\n"),"");
newMsg->initHeader();
newMsg->setTo(receiptTo);
newMsg->setSubject(i18n("Receipt: ") + aMsg->subject());
str = "Your message was successfully delivered.";
str += "\n\n---------- Message header follows ----------\n";
str += aMsg->headerAsString();
str += "--------------------------------------------\n";
// Conversion to latin1 is correct here as Mail headers should contain
// ascii only
newMsg->setBody(str.latin1());
newMsg->setAutomaticFields();
mReceipts.append(newMsg);
mReceiptTimer.start(0,true);
}
//-----------------------------------------------------------------------------
bool KMAccount::processNewMsg(KMMessage* aMsg)
{
QString receiptTo;
int rc, processResult;
assert(aMsg != NULL);
receiptTo = aMsg->headerField("Return-Receipt-To");
if (!receiptTo.isEmpty()) sendReceipt(aMsg, receiptTo);
// Set status of new messages that are marked as old to read, otherwise
// the user won't see which messages newly arrived.
if (aMsg->status()==KMMsgStatusOld)
aMsg->setStatus(KMMsgStatusUnread); // -sanders
// aMsg->setStatus(KMMsgStatusRead);
else aMsg->setStatus(KMMsgStatusNew);
// 0==processed ok, 1==processing failed, 2==critical error, abort!
processResult = kernel->filterMgr()->process(aMsg);
if (processResult == 2) {
perror("Critical error: Unable to collect mail (out of space?)");
KMessageBox::information(0,(i18n("Critical error: "
"Unable to collect mail (out of space?)")));
return false;
}
else if (processResult == 1)
{
kernel->filterMgr()->tempOpenFolder(mFolder);
rc = mFolder->addMsg(aMsg);
if (rc) {
perror("failed to add message");
KMessageBox::information(0, i18n("Failed to add message:\n") +
QString(strerror(rc)));
return false;
}
else return true;
}
// What now - are we owner or not?
return true; //Everything's fine - message has been added by filter }
}
//-----------------------------------------------------------------------------
void KMAccount::setCheckInterval(int aInterval)
{
if (aInterval <= 0)
{
mInterval = 0;
deinstallTimer();
}
else
{
mInterval = aInterval;
installTimer();
}
}
//-----------------------------------------------------------------------------
void KMAccount::setCheckExclude(bool aExclude)
{
mExclude = aExclude;
}
//-----------------------------------------------------------------------------
void KMAccount::installTimer()
{
if (mInterval <= 0) return;
if(!mTimer)
{
mTimer = new QTimer();
connect(mTimer,SIGNAL(timeout()),SLOT(mailCheck()));
}
else
{
mTimer->stop();
}
mTimer->start(mInterval*60000);
}
//-----------------------------------------------------------------------------
void KMAccount::deinstallTimer()
{
if(mTimer) {
mTimer->stop();
disconnect(mTimer);
delete mTimer;
mTimer = NULL;
}
}
bool KMAccount::runPrecommand(const QString &precommand)
{
KProcess precommandProcess;
// Run the pre command if there is one
if (precommand.length() == 0)
return true;
KMBroadcastStatus::instance()->setStatusMsg(
i18n( QString("Executing precommand ") + precommand ));
QStringList args;
// Tokenize on space
int left = 0;
QString parseString = precommand;
left = parseString.find(' ', 0, false);
while ((left <= (int)parseString.length()) && (left != -1))
{
args << parseString.left(left);
parseString = parseString.right(parseString.length() - (left+1));
left = parseString.find(' ', 0, false);
}
args << parseString;
for (unsigned int i = 0; i < args.count(); i++)
{
//kdDebug() << "KMAccount::runPrecommand: arg " << i << " = " << args[i] << endl;
precommandProcess << args[i];
}
kapp->processEvents();
kdDebug() << "Running precommand " << precommand << endl;
if (!precommandProcess.start(KProcess::Block))
return false;
return true;
}
//-----------------------------------------------------------------------------
void KMAccount::mailCheck()
{
if (mCheckingMail) return;
mCheckingMail = TRUE;
kernel->acctMgr()->singleCheckMail(this,false);
mCheckingMail = FALSE;
}
//-----------------------------------------------------------------------------
void KMAccount::sendReceipts()
{
// re-entrant
QValueList<KMMessage*> receipts;
QValueList<KMMessage*>::Iterator it;
for(it = mReceipts.begin(); it != mReceipts.end(); ++it)
receipts.append(*it);
mReceipts.clear();
for(it = receipts.begin(); it != receipts.end(); ++it)
kernel->msgSender()->send(*it); //might process events
}
<commit_msg>Don't allow deleting the account name. Leads to some trouble otherwise.<commit_after>// KMail Account
#include <stdlib.h>
#include <unistd.h>
#include <qdir.h>
#include <qstrlist.h>
#include <qtextstream.h>
#include <qfile.h>
#include <assert.h>
#include <kconfig.h>
#include <kapp.h>
#include <qregexp.h>
#include <klocale.h>
#include <kprocess.h>
#include <kmessagebox.h>
#include <kdebug.h>
#include "kmacctmgr.h"
#include "kmacctfolder.h"
#include "kmaccount.h"
#include "kmglobal.h"
#include "kmfoldermgr.h"
#include "kmfiltermgr.h"
#include "kmsender.h"
#include "kmmessage.h"
#include "kmbroadcaststatus.h"
//----------------------
#include "kmaccount.moc"
//-----------------------------------------------------------------------------
KMAccount::KMAccount(KMAcctMgr* aOwner, const char* aName)
{
initMetaObject();
assert(aOwner != NULL);
mOwner = aOwner;
mName = aName;
mFolder = NULL;
mTimer = NULL;
mInterval = 0;
mExclude = false;
mCheckingMail = FALSE;
connect(&mReceiptTimer,SIGNAL(timeout()),SLOT(sendReceipts()));
}
//-----------------------------------------------------------------------------
KMAccount::~KMAccount()
{
if (!kernel->shuttingDown() && mFolder) mFolder->removeAccount(this);
if (mTimer) deinstallTimer();
}
//-----------------------------------------------------------------------------
void KMAccount::setName(const QString& aName)
{
mName = (aName.isEmpty()) ? i18n("Unnamed") : aName;
}
//-----------------------------------------------------------------------------
void KMAccount::clearPasswd()
{
}
//-----------------------------------------------------------------------------
void KMAccount::setFolder(KMFolder* aFolder)
{
if(!aFolder)
{
kdDebug() << "KMAccount::setFolder() : aFolder == NULL" << endl;
mFolder = NULL;
return;
}
mFolder = (KMAcctFolder*)aFolder;
}
//-----------------------------------------------------------------------------
void KMAccount::readConfig(KConfig& config)
{
KMAcctFolder* folder;
QString folderName;
mFolder = NULL;
mName = config.readEntry("Name", i18n("Unnamed"));
folderName = config.readEntry("Folder", "");
setCheckInterval(config.readNumEntry("check-interval", 0));
setCheckExclude(config.readBoolEntry("check-exclude", false));
setPrecommand(config.readEntry("precommand"));
if (!folderName.isEmpty())
{
folder = (KMAcctFolder*)kernel->folderMgr()->find(folderName);
if (folder)
{
mFolder = folder;
mFolder->addAccount(this);
}
else kdDebug() << "Cannot find folder `" << (const char*)folderName << "' for account `" << (const char*)mName << "'." << endl;
}
}
//-----------------------------------------------------------------------------
void KMAccount::writeConfig(KConfig& config)
{
config.writeEntry("Type", type());
config.writeEntry("Name", mName);
config.writeEntry("Folder", mFolder ? mFolder->name() : QString::null);
config.writeEntry("check-interval", mInterval);
config.writeEntry("check-exclude", mExclude);
config.writeEntry("precommand", mPrecommand);
}
//-----------------------------------------------------------------------------
void KMAccount::sendReceipt(KMMessage* aMsg, const QString aReceiptTo)
{
KMMessage* newMsg = new KMMessage;
QString str, receiptTo;
KConfig* cfg = kapp->config();
bool sendReceipts;
cfg->setGroup("General");
sendReceipts = cfg->readBoolEntry("send-receipts", false);
if (!sendReceipts) return;
receiptTo = aReceiptTo;
receiptTo.replace(QRegExp("\\n"),"");
newMsg->initHeader();
newMsg->setTo(receiptTo);
newMsg->setSubject(i18n("Receipt: ") + aMsg->subject());
str = "Your message was successfully delivered.";
str += "\n\n---------- Message header follows ----------\n";
str += aMsg->headerAsString();
str += "--------------------------------------------\n";
// Conversion to latin1 is correct here as Mail headers should contain
// ascii only
newMsg->setBody(str.latin1());
newMsg->setAutomaticFields();
mReceipts.append(newMsg);
mReceiptTimer.start(0,true);
}
//-----------------------------------------------------------------------------
bool KMAccount::processNewMsg(KMMessage* aMsg)
{
QString receiptTo;
int rc, processResult;
assert(aMsg != NULL);
receiptTo = aMsg->headerField("Return-Receipt-To");
if (!receiptTo.isEmpty()) sendReceipt(aMsg, receiptTo);
// Set status of new messages that are marked as old to read, otherwise
// the user won't see which messages newly arrived.
if (aMsg->status()==KMMsgStatusOld)
aMsg->setStatus(KMMsgStatusUnread); // -sanders
// aMsg->setStatus(KMMsgStatusRead);
else aMsg->setStatus(KMMsgStatusNew);
// 0==processed ok, 1==processing failed, 2==critical error, abort!
processResult = kernel->filterMgr()->process(aMsg);
if (processResult == 2) {
perror("Critical error: Unable to collect mail (out of space?)");
KMessageBox::information(0,(i18n("Critical error: "
"Unable to collect mail (out of space?)")));
return false;
}
else if (processResult == 1)
{
kernel->filterMgr()->tempOpenFolder(mFolder);
rc = mFolder->addMsg(aMsg);
if (rc) {
perror("failed to add message");
KMessageBox::information(0, i18n("Failed to add message:\n") +
QString(strerror(rc)));
return false;
}
else return true;
}
// What now - are we owner or not?
return true; //Everything's fine - message has been added by filter }
}
//-----------------------------------------------------------------------------
void KMAccount::setCheckInterval(int aInterval)
{
if (aInterval <= 0)
{
mInterval = 0;
deinstallTimer();
}
else
{
mInterval = aInterval;
installTimer();
}
}
//-----------------------------------------------------------------------------
void KMAccount::setCheckExclude(bool aExclude)
{
mExclude = aExclude;
}
//-----------------------------------------------------------------------------
void KMAccount::installTimer()
{
if (mInterval <= 0) return;
if(!mTimer)
{
mTimer = new QTimer();
connect(mTimer,SIGNAL(timeout()),SLOT(mailCheck()));
}
else
{
mTimer->stop();
}
mTimer->start(mInterval*60000);
}
//-----------------------------------------------------------------------------
void KMAccount::deinstallTimer()
{
if(mTimer) {
mTimer->stop();
disconnect(mTimer);
delete mTimer;
mTimer = NULL;
}
}
bool KMAccount::runPrecommand(const QString &precommand)
{
KProcess precommandProcess;
// Run the pre command if there is one
if (precommand.length() == 0)
return true;
KMBroadcastStatus::instance()->setStatusMsg(
i18n( QString("Executing precommand ") + precommand ));
QStringList args;
// Tokenize on space
int left = 0;
QString parseString = precommand;
left = parseString.find(' ', 0, false);
while ((left <= (int)parseString.length()) && (left != -1))
{
args << parseString.left(left);
parseString = parseString.right(parseString.length() - (left+1));
left = parseString.find(' ', 0, false);
}
args << parseString;
for (unsigned int i = 0; i < args.count(); i++)
{
//kdDebug() << "KMAccount::runPrecommand: arg " << i << " = " << args[i] << endl;
precommandProcess << args[i];
}
kapp->processEvents();
kdDebug() << "Running precommand " << precommand << endl;
if (!precommandProcess.start(KProcess::Block))
return false;
return true;
}
//-----------------------------------------------------------------------------
void KMAccount::mailCheck()
{
if (mCheckingMail) return;
mCheckingMail = TRUE;
kernel->acctMgr()->singleCheckMail(this,false);
mCheckingMail = FALSE;
}
//-----------------------------------------------------------------------------
void KMAccount::sendReceipts()
{
// re-entrant
QValueList<KMMessage*> receipts;
QValueList<KMMessage*>::Iterator it;
for(it = mReceipts.begin(); it != mReceipts.end(); ++it)
receipts.append(*it);
mReceipts.clear();
for(it = receipts.begin(); it != receipts.end(); ++it)
kernel->msgSender()->send(*it); //might process events
}
<|endoftext|> |
<commit_before>// Copyright (c) 2011 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "base/bind.h"
#include "base/command_line.h"
#include "base/file_path.h"
#include "base/string_number_conversions.h"
#include "base/utf_string_conversions.h"
#include "chrome/browser/ui/browser.h"
#include "chrome/test/base/in_process_browser_test.h"
#include "chrome/test/base/ui_test_utils.h"
#include "content/browser/renderer_host/render_view_host.h"
#include "content/browser/speech/speech_input_dispatcher_host.h"
#include "content/browser/speech/speech_input_manager.h"
#include "content/browser/tab_contents/tab_contents.h"
#include "content/public/browser/notification_types.h"
#include "content/public/common/content_switches.h"
#include "content/public/common/speech_input_result.h"
#include "third_party/WebKit/Source/WebKit/chromium/public/WebInputEvent.h"
using content::NavigationController;
using content::WebContents;
namespace speech_input {
class FakeSpeechInputManager;
}
namespace speech_input {
const char* kTestResult = "Pictures of the moon";
class FakeSpeechInputManager : public SpeechInputManager {
public:
FakeSpeechInputManager()
: caller_id_(0),
delegate_(NULL),
did_cancel_all_(false),
send_fake_response_(true) {
}
std::string grammar() {
return grammar_;
}
bool did_cancel_all() {
return did_cancel_all_;
}
void set_send_fake_response(bool send) {
send_fake_response_ = send;
}
// SpeechInputManager methods.
virtual void StartRecognition(Delegate* delegate, int caller_id,
int render_process_id, int render_view_id, const gfx::Rect& element_rect,
const std::string& language, const std::string& grammar,
const std::string& origin_url,
net::URLRequestContextGetter* context_getter,
SpeechInputPreferences* speech_input_prefs,
AudioManager* audio_manager) OVERRIDE {
VLOG(1) << "StartRecognition invoked.";
EXPECT_EQ(0, caller_id_);
EXPECT_EQ(NULL, delegate_);
caller_id_ = caller_id;
delegate_ = delegate;
grammar_ = grammar;
if (send_fake_response_) {
// Give the fake result in a short while.
MessageLoop::current()->PostTask(FROM_HERE, base::Bind(
&FakeSpeechInputManager::SetFakeRecognitionResult,
// This class does not need to be refcounted (typically done by
// PostTask) since it will outlive the test and gets released only
// when the test shuts down. Disabling refcounting here saves a bit
// of unnecessary code and the factory method can return a plain
// pointer below as required by the real code.
base::Unretained(this)));
}
}
virtual void CancelRecognition(int caller_id) OVERRIDE {
VLOG(1) << "CancelRecognition invoked.";
EXPECT_EQ(caller_id_, caller_id);
caller_id_ = 0;
delegate_ = NULL;
}
virtual void StopRecording(int caller_id) OVERRIDE {
VLOG(1) << "StopRecording invoked.";
EXPECT_EQ(caller_id_, caller_id);
// Nothing to do here since we aren't really recording.
}
virtual void CancelAllRequestsWithDelegate(Delegate* delegate) OVERRIDE {
VLOG(1) << "CancelAllRequestsWithDelegate invoked.";
// delegate_ is set to NULL if a fake result was received (see below), so
// check that delegate_ matches the incoming parameter only when there is
// no fake result sent.
EXPECT_TRUE(send_fake_response_ || delegate_ == delegate);
did_cancel_all_ = true;
}
protected:
virtual void GetRequestInfo(AudioManager* audio_manager,
bool* can_report_metrics,
std::string* request_info) OVERRIDE {}
virtual void ShowRecognitionRequested(int caller_id, int render_process_id,
int render_view_id, const gfx::Rect& element_rect) OVERRIDE {}
virtual void ShowWarmUp(int caller_id) OVERRIDE {}
virtual void ShowRecognizing(int caller_id) OVERRIDE {}
virtual void ShowRecording(int caller_id) OVERRIDE {}
virtual void ShowInputVolume(int caller_id, float volume,
float noise_volume) OVERRIDE {}
virtual void ShowMicError(int caller_id,
SpeechInputManager::MicError error) OVERRIDE {}
virtual void ShowRecognizerError(int caller_id,
content::SpeechInputError error) OVERRIDE {}
virtual void DoClose(int caller_id) OVERRIDE {}
private:
void SetFakeRecognitionResult() {
if (caller_id_) { // Do a check in case we were cancelled..
VLOG(1) << "Setting fake recognition result.";
delegate_->DidCompleteRecording(caller_id_);
content::SpeechInputResult results;
results.hypotheses.push_back(content::SpeechInputHypothesis(
ASCIIToUTF16(kTestResult), 1.0));
delegate_->SetRecognitionResult(caller_id_, results);
delegate_->DidCompleteRecognition(caller_id_);
caller_id_ = 0;
delegate_ = NULL;
VLOG(1) << "Finished setting fake recognition result.";
}
}
int caller_id_;
Delegate* delegate_;
std::string grammar_;
bool did_cancel_all_;
bool send_fake_response_;
};
class SpeechInputBrowserTest : public InProcessBrowserTest {
public:
// InProcessBrowserTest methods
virtual void SetUpCommandLine(CommandLine* command_line) {
EXPECT_TRUE(!command_line->HasSwitch(switches::kDisableSpeechInput));
}
GURL testUrl(const FilePath::CharType* filename) {
const FilePath kTestDir(FILE_PATH_LITERAL("speech"));
return ui_test_utils::GetTestUrl(kTestDir, FilePath(filename));
}
protected:
void LoadAndStartSpeechInputTest(const FilePath::CharType* filename) {
// The test page calculates the speech button's coordinate in the page on
// load & sets that coordinate in the URL fragment. We send mouse down & up
// events at that coordinate to trigger speech recognition.
GURL test_url = testUrl(filename);
ui_test_utils::NavigateToURL(browser(), test_url);
WebKit::WebMouseEvent mouse_event;
mouse_event.type = WebKit::WebInputEvent::MouseDown;
mouse_event.button = WebKit::WebMouseEvent::ButtonLeft;
mouse_event.x = 0;
mouse_event.y = 0;
mouse_event.clickCount = 1;
WebContents* web_contents = browser()->GetSelectedWebContents();
ui_test_utils::WindowedNotificationObserver observer(
content::NOTIFICATION_LOAD_STOP,
content::Source<NavigationController>(&web_contents->GetController()));
web_contents->GetRenderViewHost()->ForwardMouseEvent(mouse_event);
mouse_event.type = WebKit::WebInputEvent::MouseUp;
web_contents->GetRenderViewHost()->ForwardMouseEvent(mouse_event);
observer.Wait();
}
void RunSpeechInputTest(const FilePath::CharType* filename) {
// The fake speech input manager would receive the speech input
// request and return the test string as recognition result. The test page
// then sets the URL fragment as 'pass' if it received the expected string.
LoadAndStartSpeechInputTest(filename);
EXPECT_EQ("pass", browser()->GetSelectedWebContents()->GetURL().ref());
}
// InProcessBrowserTest methods.
virtual void SetUpInProcessBrowserTestFixture() {
fake_speech_input_manager_.set_send_fake_response(true);
speech_input_manager_ = &fake_speech_input_manager_;
// Inject the fake manager factory so that the test result is returned to
// the web page.
SpeechInputDispatcherHost::set_manager(speech_input_manager_);
}
virtual void TearDownInProcessBrowserTestFixture() {
speech_input_manager_ = NULL;
}
FakeSpeechInputManager fake_speech_input_manager_;
// This is used by the static |fakeManager|, and it is a pointer rather than a
// direct instance per the style guide.
static SpeechInputManager* speech_input_manager_;
};
SpeechInputManager* SpeechInputBrowserTest::speech_input_manager_ = NULL;
// Marked as DISABLED due to http://crbug.com/51337
//
// TODO(satish): Once this flakiness has been fixed, add a second test here to
// check for sending many clicks in succession to the speech button and verify
// that it doesn't cause any crash but works as expected. This should act as the
// test for http://crbug.com/59173
//
// TODO(satish): Similar to above, once this flakiness has been fixed add
// another test here to check that when speech recognition is in progress and
// a renderer crashes, we get a call to
// SpeechInputManager::CancelAllRequestsWithDelegate.
//
// Marked as DISABLED due to http://crbug.com/71227
#if defined(GOOGLE_CHROME_BUILD)
#define MAYBE_TestBasicRecognition DISABLED_TestBasicRecognition
#else
#define MAYBE_TestBasicRecognition TestBasicRecognition
#endif
IN_PROC_BROWSER_TEST_F(SpeechInputBrowserTest, MAYBE_TestBasicRecognition) {
RunSpeechInputTest(FILE_PATH_LITERAL("basic_recognition.html"));
EXPECT_TRUE(fake_speech_input_manager_.grammar().empty());
}
// Marked as FLAKY due to http://crbug.com/51337
// Marked as DISALBED due to http://crbug.com/71227
#if defined(GOOGLE_CHROME_BUILD)
#define MAYBE_GrammarAttribute DISABLED_GrammarAttribute
#else
#define MAYBE_GrammarAttribute GrammarAttribute
#endif
IN_PROC_BROWSER_TEST_F(SpeechInputBrowserTest, MAYBE_GrammarAttribute) {
RunSpeechInputTest(FILE_PATH_LITERAL("grammar_attribute.html"));
EXPECT_EQ("http://example.com/grammar.xml",
fake_speech_input_manager_.grammar());
}
// Marked as DISABLED due to http://crbug.com/71227
IN_PROC_BROWSER_TEST_F(SpeechInputBrowserTest, DISABLED_TestCancelAll) {
// The test checks that the cancel-all callback gets issued when a session
// is pending, so don't send a fake response.
fake_speech_input_manager_.set_send_fake_response(false);
LoadAndStartSpeechInputTest(FILE_PATH_LITERAL("basic_recognition.html"));
// Make the renderer crash. This should trigger SpeechInputDispatcherHost to
// cancel all pending sessions.
GURL test_url("about:crash");
ui_test_utils::NavigateToURL(browser(), test_url);
EXPECT_TRUE(fake_speech_input_manager_.did_cancel_all());
}
} // namespace speech_input
<commit_msg>Fixed a bug causing hang of speech input tests (especially TestCancelAll). Re-enabling tests.<commit_after>// Copyright (c) 2012 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "base/bind.h"
#include "base/command_line.h"
#include "base/file_path.h"
#include "base/string_number_conversions.h"
#include "base/utf_string_conversions.h"
#include "chrome/browser/ui/browser.h"
#include "chrome/test/base/in_process_browser_test.h"
#include "chrome/test/base/ui_test_utils.h"
#include "content/browser/renderer_host/render_view_host.h"
#include "content/browser/speech/speech_input_dispatcher_host.h"
#include "content/browser/speech/speech_input_manager.h"
#include "content/browser/tab_contents/tab_contents.h"
#include "content/public/browser/notification_types.h"
#include "content/public/common/content_switches.h"
#include "content/public/common/speech_input_result.h"
#include "third_party/WebKit/Source/WebKit/chromium/public/WebInputEvent.h"
using content::NavigationController;
using content::WebContents;
namespace speech_input {
class FakeSpeechInputManager;
}
namespace speech_input {
const char* kTestResult = "Pictures of the moon";
class FakeSpeechInputManager : public SpeechInputManager {
public:
FakeSpeechInputManager()
: caller_id_(0),
delegate_(NULL),
did_cancel_all_(false),
should_send_fake_response_(true) {
}
std::string grammar() {
return grammar_;
}
bool did_cancel_all() {
return did_cancel_all_;
}
void set_should_send_fake_response(bool send) {
should_send_fake_response_ = send;
}
bool should_send_fake_response() {
return should_send_fake_response_;
}
// SpeechInputManager methods.
virtual void StartRecognition(Delegate* delegate, int caller_id,
int render_process_id, int render_view_id, const gfx::Rect& element_rect,
const std::string& language, const std::string& grammar,
const std::string& origin_url,
net::URLRequestContextGetter* context_getter,
SpeechInputPreferences* speech_input_prefs,
AudioManager* audio_manager) OVERRIDE {
VLOG(1) << "StartRecognition invoked.";
EXPECT_EQ(0, caller_id_);
EXPECT_EQ(NULL, delegate_);
caller_id_ = caller_id;
delegate_ = delegate;
grammar_ = grammar;
if (should_send_fake_response_) {
// Give the fake result in a short while.
MessageLoop::current()->PostTask(FROM_HERE, base::Bind(
&FakeSpeechInputManager::SetFakeRecognitionResult,
// This class does not need to be refcounted (typically done by
// PostTask) since it will outlive the test and gets released only
// when the test shuts down. Disabling refcounting here saves a bit
// of unnecessary code and the factory method can return a plain
// pointer below as required by the real code.
base::Unretained(this)));
}
}
virtual void CancelRecognition(int caller_id) OVERRIDE {
VLOG(1) << "CancelRecognition invoked.";
EXPECT_EQ(caller_id_, caller_id);
caller_id_ = 0;
delegate_ = NULL;
}
virtual void StopRecording(int caller_id) OVERRIDE {
VLOG(1) << "StopRecording invoked.";
EXPECT_EQ(caller_id_, caller_id);
// Nothing to do here since we aren't really recording.
}
virtual void CancelAllRequestsWithDelegate(Delegate* delegate) OVERRIDE {
VLOG(1) << "CancelAllRequestsWithDelegate invoked.";
// delegate_ is set to NULL if a fake result was received (see below), so
// check that delegate_ matches the incoming parameter only when there is
// no fake result sent.
EXPECT_TRUE(should_send_fake_response_ || delegate_ == delegate);
did_cancel_all_ = true;
}
protected:
virtual void GetRequestInfo(AudioManager* audio_manager,
bool* can_report_metrics,
std::string* request_info) OVERRIDE {}
virtual void ShowRecognitionRequested(int caller_id, int render_process_id,
int render_view_id, const gfx::Rect& element_rect) OVERRIDE {}
virtual void ShowWarmUp(int caller_id) OVERRIDE {}
virtual void ShowRecognizing(int caller_id) OVERRIDE {}
virtual void ShowRecording(int caller_id) OVERRIDE {}
virtual void ShowInputVolume(int caller_id, float volume,
float noise_volume) OVERRIDE {}
virtual void ShowMicError(int caller_id,
SpeechInputManager::MicError error) OVERRIDE {}
virtual void ShowRecognizerError(int caller_id,
content::SpeechInputError error) OVERRIDE {}
virtual void DoClose(int caller_id) OVERRIDE {}
private:
void SetFakeRecognitionResult() {
if (caller_id_) { // Do a check in case we were cancelled..
VLOG(1) << "Setting fake recognition result.";
delegate_->DidCompleteRecording(caller_id_);
content::SpeechInputResult results;
results.hypotheses.push_back(content::SpeechInputHypothesis(
ASCIIToUTF16(kTestResult), 1.0));
delegate_->SetRecognitionResult(caller_id_, results);
delegate_->DidCompleteRecognition(caller_id_);
caller_id_ = 0;
delegate_ = NULL;
VLOG(1) << "Finished setting fake recognition result.";
}
}
int caller_id_;
Delegate* delegate_;
std::string grammar_;
bool did_cancel_all_;
bool should_send_fake_response_;
};
class SpeechInputBrowserTest : public InProcessBrowserTest {
public:
// InProcessBrowserTest methods
virtual void SetUpCommandLine(CommandLine* command_line) {
EXPECT_TRUE(!command_line->HasSwitch(switches::kDisableSpeechInput));
}
GURL testUrl(const FilePath::CharType* filename) {
const FilePath kTestDir(FILE_PATH_LITERAL("speech"));
return ui_test_utils::GetTestUrl(kTestDir, FilePath(filename));
}
protected:
void LoadAndStartSpeechInputTest(const FilePath::CharType* filename) {
// The test page calculates the speech button's coordinate in the page on
// load & sets that coordinate in the URL fragment. We send mouse down & up
// events at that coordinate to trigger speech recognition.
GURL test_url = testUrl(filename);
ui_test_utils::NavigateToURL(browser(), test_url);
WebKit::WebMouseEvent mouse_event;
mouse_event.type = WebKit::WebInputEvent::MouseDown;
mouse_event.button = WebKit::WebMouseEvent::ButtonLeft;
mouse_event.x = 0;
mouse_event.y = 0;
mouse_event.clickCount = 1;
WebContents* web_contents = browser()->GetSelectedWebContents();
ui_test_utils::WindowedNotificationObserver observer(
content::NOTIFICATION_LOAD_STOP,
content::Source<NavigationController>(&web_contents->GetController()));
web_contents->GetRenderViewHost()->ForwardMouseEvent(mouse_event);
mouse_event.type = WebKit::WebInputEvent::MouseUp;
web_contents->GetRenderViewHost()->ForwardMouseEvent(mouse_event);
// We should wait for a navigation event, raised by the test page JS code
// upon the onwebkitspeechchange event, in all cases except when the
// speech response is inhibited.
if (fake_speech_input_manager_.should_send_fake_response())
observer.Wait();
}
void RunSpeechInputTest(const FilePath::CharType* filename) {
// The fake speech input manager would receive the speech input
// request and return the test string as recognition result. The test page
// then sets the URL fragment as 'pass' if it received the expected string.
LoadAndStartSpeechInputTest(filename);
EXPECT_EQ("pass", browser()->GetSelectedWebContents()->GetURL().ref());
}
// InProcessBrowserTest methods.
virtual void SetUpInProcessBrowserTestFixture() {
fake_speech_input_manager_.set_should_send_fake_response(true);
speech_input_manager_ = &fake_speech_input_manager_;
// Inject the fake manager factory so that the test result is returned to
// the web page.
SpeechInputDispatcherHost::set_manager(speech_input_manager_);
}
virtual void TearDownInProcessBrowserTestFixture() {
speech_input_manager_ = NULL;
}
FakeSpeechInputManager fake_speech_input_manager_;
// This is used by the static |fakeManager|, and it is a pointer rather than a
// direct instance per the style guide.
static SpeechInputManager* speech_input_manager_;
};
SpeechInputManager* SpeechInputBrowserTest::speech_input_manager_ = NULL;
// TODO(satish): Once this flakiness has been fixed, add a second test here to
// check for sending many clicks in succession to the speech button and verify
// that it doesn't cause any crash but works as expected. This should act as the
// test for http://crbug.com/59173
//
// TODO(satish): Similar to above, once this flakiness has been fixed add
// another test here to check that when speech recognition is in progress and
// a renderer crashes, we get a call to
// SpeechInputManager::CancelAllRequestsWithDelegate.
IN_PROC_BROWSER_TEST_F(SpeechInputBrowserTest, TestBasicRecognition) {
RunSpeechInputTest(FILE_PATH_LITERAL("basic_recognition.html"));
EXPECT_TRUE(fake_speech_input_manager_.grammar().empty());
}
IN_PROC_BROWSER_TEST_F(SpeechInputBrowserTest, GrammarAttribute) {
RunSpeechInputTest(FILE_PATH_LITERAL("grammar_attribute.html"));
EXPECT_EQ("http://example.com/grammar.xml",
fake_speech_input_manager_.grammar());
}
IN_PROC_BROWSER_TEST_F(SpeechInputBrowserTest, TestCancelAll) {
// The test checks that the cancel-all callback gets issued when a session
// is pending, so don't send a fake response.
// We are not expecting a navigation event being raised from the JS of the
// test page JavaScript in this case.
fake_speech_input_manager_.set_should_send_fake_response(false);
LoadAndStartSpeechInputTest(FILE_PATH_LITERAL("basic_recognition.html"));
// Make the renderer crash. This should trigger SpeechInputDispatcherHost to
// cancel all pending sessions.
GURL test_url("about:crash");
ui_test_utils::NavigateToURL(browser(), test_url);
EXPECT_TRUE(fake_speech_input_manager_.did_cancel_all());
}
} // namespace speech_input
<|endoftext|> |
<commit_before>#include <iostream>
#include <string>
#include "gaol/gaol.h"
#include "gaol_wrap.hh"
#include <cstring>
#include <cassert>
#include <cfenv>
#define TO_INTERVAL(x) (*(reinterpret_cast<interval*>(x)))
#define TO_INTERVAL_C(x) (*(reinterpret_cast<const interval*>(x)))
#define TO_STACK(x) (*(reinterpret_cast<gaol_int*>(x)))
// The following assertions ensure that the punned type gaol_int is correct.
static_assert(sizeof(interval) == sizeof(gaol_int),
"Size of punned type gaol_int does not match size of interval.");
static_assert(alignof(interval) == alignof(gaol_int),
"Alignment of punned type gaol_int does not match alignment of interval.");
void make_interval_dd(double inf, double sup, gaol_int* out) {
TO_INTERVAL(out) = interval(inf, sup);
}
// These Gaol functions my throw. Exceptions must be caught here since Rust
// has no mechanism for handling these.
void make_interval_ss(const char* inf, const char* sup, gaol_int* out, char* success) {
try {
TO_INTERVAL(out) = interval(inf, sup);
*success = 1;
}
catch(...) {
*success = 0;
}
}
void make_interval_s(const char* in, gaol_int* out, char* success) {
try {
TO_INTERVAL(out) = interval(in);
*success = 1;
}
catch(...) {
*success = 0;
}
}
void make_interval_i(const gaol_int* in, gaol_int* out) {
TO_INTERVAL(out) = interval(TO_INTERVAL_C(in));
}
gaol_int make_interval_e() {
interval result;
return TO_STACK(&result);
}
// void del_int(gaol_int);
void add(const gaol_int* a, const gaol_int* b, gaol_int* out) {
TO_INTERVAL(out) = TO_INTERVAL_C(a) + TO_INTERVAL_C(b);
}
void iadd(gaol_int* a, const gaol_int* b) {
TO_INTERVAL(a) += TO_INTERVAL_C(b);
}
void sub(const gaol_int* a, const gaol_int* b, gaol_int* out) {
TO_INTERVAL(out) = TO_INTERVAL_C(a) - TO_INTERVAL_C(b);
}
void isub(gaol_int* a, const gaol_int* b) {
TO_INTERVAL(a) -= TO_INTERVAL_C(b);
}
void mul(const gaol_int* a, const gaol_int* b, gaol_int* out) {
TO_INTERVAL(out) = TO_INTERVAL_C(a) * TO_INTERVAL_C(b);
}
void imul(gaol_int* a, const gaol_int* b) {
TO_INTERVAL(a) *= TO_INTERVAL_C(b);
}
void div_g(const gaol_int* a, const gaol_int* b, gaol_int* out) {
TO_INTERVAL(out) = TO_INTERVAL_C(a) / TO_INTERVAL_C(b);
}
void idiv_g(gaol_int* a, const gaol_int* b) {
TO_INTERVAL(a) /= TO_INTERVAL_C(b);
}
void neg_g(const gaol_int* in, gaol_int* out) {
TO_INTERVAL(out) = -TO_INTERVAL_C(in);
}
void ineg_g(gaol_int* x) {
TO_INTERVAL(x) = -TO_INTERVAL(x);
}
void sin_g(const gaol_int* in, gaol_int* out) {
TO_INTERVAL(out) = sin(TO_INTERVAL_C(in));
}
void asin_g(const gaol_int* in, gaol_int* out) {
TO_INTERVAL(out) = asin(TO_INTERVAL_C(in));
}
void isin_g(gaol_int* x) {
TO_INTERVAL(x) = sin(TO_INTERVAL(x));
}
void iasin_g(gaol_int* x) {
TO_INTERVAL(x) = asin(TO_INTERVAL(x));
}
void sqrt_g(const gaol_int* in, gaol_int* out) {
TO_INTERVAL(out) = sqrt(TO_INTERVAL_C(in));
}
void isqrt_g(gaol_int* x) {
TO_INTERVAL(x) = sqrt(TO_INTERVAL(x));
}
void cos_g(const gaol_int* in, gaol_int* out) {
TO_INTERVAL(out) = cos(TO_INTERVAL_C(in));
}
void icos_g(gaol_int* x) {
TO_INTERVAL(x) = cos(TO_INTERVAL(x));
}
void acos_g(const gaol_int* in, gaol_int* out) {
TO_INTERVAL(out) = acos(TO_INTERVAL_C(in));
}
void iacos_g(gaol_int* x) {
TO_INTERVAL(x) = acos(TO_INTERVAL(x));
}
void tan_g(const gaol_int* in, gaol_int* out) {
TO_INTERVAL(out) = atan(TO_INTERVAL_C(in));
}
void itan_g(gaol_int* x) {
TO_INTERVAL(x) = tan(TO_INTERVAL(x));
}
void atan_g(const gaol_int* in, gaol_int* out) {
TO_INTERVAL(out) = atan(TO_INTERVAL_C(in));
}
void iatan_g(gaol_int* x) {
TO_INTERVAL(x) = atan(TO_INTERVAL(x));
}
void exp_g(const gaol_int* in, gaol_int* out) {
TO_INTERVAL(out) = exp(TO_INTERVAL_C(in));
}
void iexp_g(gaol_int* x) {
TO_INTERVAL(x) = exp(TO_INTERVAL(x));
}
void log_g(const gaol_int* in, gaol_int* out) {
TO_INTERVAL(out) = log(TO_INTERVAL_C(in));
}
void ilog_g(gaol_int* x) {
TO_INTERVAL(x) = log(TO_INTERVAL(x));
}
void abs_g(const gaol_int* in, gaol_int* out) {
TO_INTERVAL(out) = abs(TO_INTERVAL_C(in));
}
void iabs_g(gaol_int* x) {
TO_INTERVAL(x) = abs(TO_INTERVAL(x));
}
void pow_ig(const gaol_int* a, int b, gaol_int* out) {
TO_INTERVAL(out) = pow(TO_INTERVAL_C(a), b);
}
void ipow_ig(gaol_int* a, int b) {
TO_INTERVAL(a) = pow(TO_INTERVAL(a), b);
}
void pow_vg(const gaol_int* a, const gaol_int* b, gaol_int* out) {
TO_INTERVAL(out) = pow(TO_INTERVAL_C(a), TO_INTERVAL_C(b));
}
void ipow_vg(gaol_int* a, const gaol_int* b) {
TO_INTERVAL(a) = pow(TO_INTERVAL(a), TO_INTERVAL_C(b));
}
void print(gaol_int* x) {
std::cout << TO_INTERVAL(x) << std::endl;
}
const char* to_str(const gaol_int* x) {
// interval::precision(100);
std::string t(TO_INTERVAL_C(x));
char* result = reinterpret_cast<char*>(malloc((t.size() + 1) * sizeof(char)));
strcpy(result, t.c_str());
return result;
}
double upper_g(const gaol_int* x) {
return TO_INTERVAL_C(x).right();
}
double lower_g(const gaol_int* x) {
return TO_INTERVAL_C(x).left();
}
double width_g(const gaol_int* x) {
return TO_INTERVAL_C(x).width();
}
gaol_int midpoint_g(const gaol_int* x) {
interval result = TO_INTERVAL_C(x).midpoint();
return TO_STACK(&result);
}
void split_g(const gaol_int* in, gaol_int* out_1, gaol_int* out_2) {
TO_INTERVAL_C(in).split(TO_INTERVAL(out_1), TO_INTERVAL(out_2));
}
<commit_msg>Made tan atan by mistake<commit_after>#include <iostream>
#include <string>
#include "gaol/gaol.h"
#include "gaol_wrap.hh"
#include <cstring>
#include <cassert>
#include <cfenv>
#define TO_INTERVAL(x) (*(reinterpret_cast<interval*>(x)))
#define TO_INTERVAL_C(x) (*(reinterpret_cast<const interval*>(x)))
#define TO_STACK(x) (*(reinterpret_cast<gaol_int*>(x)))
// The following assertions ensure that the punned type gaol_int is correct.
static_assert(sizeof(interval) == sizeof(gaol_int),
"Size of punned type gaol_int does not match size of interval.");
static_assert(alignof(interval) == alignof(gaol_int),
"Alignment of punned type gaol_int does not match alignment of interval.");
void make_interval_dd(double inf, double sup, gaol_int* out) {
TO_INTERVAL(out) = interval(inf, sup);
}
// These Gaol functions my throw. Exceptions must be caught here since Rust
// has no mechanism for handling these.
void make_interval_ss(const char* inf, const char* sup, gaol_int* out, char* success) {
try {
TO_INTERVAL(out) = interval(inf, sup);
*success = 1;
}
catch(...) {
*success = 0;
}
}
void make_interval_s(const char* in, gaol_int* out, char* success) {
try {
TO_INTERVAL(out) = interval(in);
*success = 1;
}
catch(...) {
*success = 0;
}
}
void make_interval_i(const gaol_int* in, gaol_int* out) {
TO_INTERVAL(out) = interval(TO_INTERVAL_C(in));
}
gaol_int make_interval_e() {
interval result;
return TO_STACK(&result);
}
// void del_int(gaol_int);
void add(const gaol_int* a, const gaol_int* b, gaol_int* out) {
TO_INTERVAL(out) = TO_INTERVAL_C(a) + TO_INTERVAL_C(b);
}
void iadd(gaol_int* a, const gaol_int* b) {
TO_INTERVAL(a) += TO_INTERVAL_C(b);
}
void sub(const gaol_int* a, const gaol_int* b, gaol_int* out) {
TO_INTERVAL(out) = TO_INTERVAL_C(a) - TO_INTERVAL_C(b);
}
void isub(gaol_int* a, const gaol_int* b) {
TO_INTERVAL(a) -= TO_INTERVAL_C(b);
}
void mul(const gaol_int* a, const gaol_int* b, gaol_int* out) {
TO_INTERVAL(out) = TO_INTERVAL_C(a) * TO_INTERVAL_C(b);
}
void imul(gaol_int* a, const gaol_int* b) {
TO_INTERVAL(a) *= TO_INTERVAL_C(b);
}
void div_g(const gaol_int* a, const gaol_int* b, gaol_int* out) {
TO_INTERVAL(out) = TO_INTERVAL_C(a) / TO_INTERVAL_C(b);
}
void idiv_g(gaol_int* a, const gaol_int* b) {
TO_INTERVAL(a) /= TO_INTERVAL_C(b);
}
void neg_g(const gaol_int* in, gaol_int* out) {
TO_INTERVAL(out) = -TO_INTERVAL_C(in);
}
void ineg_g(gaol_int* x) {
TO_INTERVAL(x) = -TO_INTERVAL(x);
}
void sin_g(const gaol_int* in, gaol_int* out) {
TO_INTERVAL(out) = sin(TO_INTERVAL_C(in));
}
void asin_g(const gaol_int* in, gaol_int* out) {
TO_INTERVAL(out) = asin(TO_INTERVAL_C(in));
}
void isin_g(gaol_int* x) {
TO_INTERVAL(x) = sin(TO_INTERVAL(x));
}
void iasin_g(gaol_int* x) {
TO_INTERVAL(x) = asin(TO_INTERVAL(x));
}
void sqrt_g(const gaol_int* in, gaol_int* out) {
TO_INTERVAL(out) = sqrt(TO_INTERVAL_C(in));
}
void isqrt_g(gaol_int* x) {
TO_INTERVAL(x) = sqrt(TO_INTERVAL(x));
}
void cos_g(const gaol_int* in, gaol_int* out) {
TO_INTERVAL(out) = cos(TO_INTERVAL_C(in));
}
void icos_g(gaol_int* x) {
TO_INTERVAL(x) = cos(TO_INTERVAL(x));
}
void acos_g(const gaol_int* in, gaol_int* out) {
TO_INTERVAL(out) = acos(TO_INTERVAL_C(in));
}
void iacos_g(gaol_int* x) {
TO_INTERVAL(x) = acos(TO_INTERVAL(x));
}
void tan_g(const gaol_int* in, gaol_int* out) {
TO_INTERVAL(out) = tan(TO_INTERVAL_C(in));
}
void itan_g(gaol_int* x) {
TO_INTERVAL(x) = tan(TO_INTERVAL(x));
}
void atan_g(const gaol_int* in, gaol_int* out) {
TO_INTERVAL(out) = atan(TO_INTERVAL_C(in));
}
void iatan_g(gaol_int* x) {
TO_INTERVAL(x) = atan(TO_INTERVAL(x));
}
void exp_g(const gaol_int* in, gaol_int* out) {
TO_INTERVAL(out) = exp(TO_INTERVAL_C(in));
}
void iexp_g(gaol_int* x) {
TO_INTERVAL(x) = exp(TO_INTERVAL(x));
}
void log_g(const gaol_int* in, gaol_int* out) {
TO_INTERVAL(out) = log(TO_INTERVAL_C(in));
}
void ilog_g(gaol_int* x) {
TO_INTERVAL(x) = log(TO_INTERVAL(x));
}
void abs_g(const gaol_int* in, gaol_int* out) {
TO_INTERVAL(out) = abs(TO_INTERVAL_C(in));
}
void iabs_g(gaol_int* x) {
TO_INTERVAL(x) = abs(TO_INTERVAL(x));
}
void pow_ig(const gaol_int* a, int b, gaol_int* out) {
TO_INTERVAL(out) = pow(TO_INTERVAL_C(a), b);
}
void ipow_ig(gaol_int* a, int b) {
TO_INTERVAL(a) = pow(TO_INTERVAL(a), b);
}
void pow_vg(const gaol_int* a, const gaol_int* b, gaol_int* out) {
TO_INTERVAL(out) = pow(TO_INTERVAL_C(a), TO_INTERVAL_C(b));
}
void ipow_vg(gaol_int* a, const gaol_int* b) {
TO_INTERVAL(a) = pow(TO_INTERVAL(a), TO_INTERVAL_C(b));
}
void print(gaol_int* x) {
std::cout << TO_INTERVAL(x) << std::endl;
}
const char* to_str(const gaol_int* x) {
// interval::precision(100);
std::string t(TO_INTERVAL_C(x));
char* result = reinterpret_cast<char*>(malloc((t.size() + 1) * sizeof(char)));
strcpy(result, t.c_str());
return result;
}
double upper_g(const gaol_int* x) {
return TO_INTERVAL_C(x).right();
}
double lower_g(const gaol_int* x) {
return TO_INTERVAL_C(x).left();
}
double width_g(const gaol_int* x) {
return TO_INTERVAL_C(x).width();
}
gaol_int midpoint_g(const gaol_int* x) {
interval result = TO_INTERVAL_C(x).midpoint();
return TO_STACK(&result);
}
void split_g(const gaol_int* in, gaol_int* out_1, gaol_int* out_2) {
TO_INTERVAL_C(in).split(TO_INTERVAL(out_1), TO_INTERVAL(out_2));
}
<|endoftext|> |
<commit_before>/*
This file is part of KMail, the KDE mail client.
Copyright (c) 2000 Don Sanders <sanders@kde.org>
KMail is free software; you can redistribute it and/or modify it
under the terms of the GNU General Public License, version 2, as
published by the Free Software Foundation.
KMail 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
General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program; if not, write to the Free Software
Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
*/
#include "kmstartup.h"
#include <kdepim-compat.h> // for KDE_signal, remove in KDEPIM 4.2
#include "kmkernel.h" //control center
#include "kcursorsaver.h"
#include <klocale.h>
#include <kcomponentdata.h>
#include <kconfig.h>
#include <kstandarddirs.h>
#include <kmessagebox.h>
#include <kcrash.h>
#include <kglobal.h>
#include <kaboutdata.h>
#include <kiconloader.h>
#include <kconfiggroup.h>
#include <kde_file.h>
#include <QHostInfo>
#include <errno.h>
#include <sys/types.h>
#include <sys/param.h>
#include <signal.h>
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <qfile.h>
#undef Status // stupid X headers
extern "C" {
// Crash recovery signal handler
void kmsignalHandler(int sigId)
{
kmsetSignalHandler(SIG_DFL);
fprintf(stderr, "*** KMail got signal %d (Exiting)\n", sigId);
// try to cleanup all windows
if (kmkernel) kmkernel->dumpDeadLetters();
::exit(-1); //
}
// Crash recovery signal handler
void kmcrashHandler(int sigId)
{
kmsetSignalHandler(SIG_DFL);
fprintf(stderr, "*** KMail got signal %d (Crashing)\n", sigId);
// try to cleanup all windows
if (kmkernel) kmkernel->dumpDeadLetters();
// Return to DrKonqi.
}
//-----------------------------------------------------------------------------
void kmsetSignalHandler(void (*handler)(int))
{
KDE_signal(SIGKILL, handler);
KDE_signal(SIGTERM, handler);
KDE_signal(SIGHUP, handler);
KCrash::setEmergencySaveFunction(kmcrashHandler);
}
}
//-----------------------------------------------------------------------------
namespace KMail {
void checkConfigUpdates() {
static const char * const updates[] = {
"9",
"3.1-update-identities",
"3.1-use-identity-uoids",
"3.1-new-mail-notification",
"3.2-update-loop-on-goto-unread-settings",
"3.1.4-dont-use-UOID-0-for-any-identity", //krazy:exclude=spelling
"3.2-misc",
"3.2-moves",
"3.3-use-ID-for-accounts",
"3.3-update-filter-rules",
"3.3-move-identities-to-own-file",
"3.3-aegypten-kpgprc-to-kmailrc",
"3.3-aegypten-kpgprc-to-libkleopatrarc",
"3.3-aegypten-emailidentities-split-sign-encr-keys",
"3.3-misc",
"3.3b1-misc",
"3.4-misc",
"3.4a",
"3.4b",
"3.4.1",
"3.5.4",
"3.5.7-imap-flag-migration",
"4.0-misc",
"4.2"
};
static const int numUpdates = sizeof updates / sizeof *updates;
// Warning: do not remove entries in the above array, or the update-level check below will break
KConfig * config = KMKernel::config();
KConfigGroup startup( config, "Startup" );
const int configUpdateLevel = startup.readEntry( "update-level", 0 );
if ( configUpdateLevel == numUpdates ) // Optimize for the common case that everything is OK
return;
for ( int i = configUpdateLevel ; i < numUpdates ; ++i ) {
config->checkUpdate( updates[i], "kmail.upd" );
}
startup.writeEntry( "update-level", numUpdates );
}
void lockOrDie() {
// Check and create a lock file to prevent concurrent access to kmail files
QString appName = KGlobal::mainComponent().componentName();
if ( appName.isEmpty() )
appName = "kmail";
QString programName;
const KAboutData *about = KGlobal::mainComponent().aboutData();
if ( about )
programName = about->programName();
if ( programName.isEmpty() )
programName = i18n("KMail");
QString lockLocation = KStandardDirs::locateLocal("data", "kmail/lock");
KConfig config(lockLocation, KConfig::SimpleConfig);
KConfigGroup group(&config, "");
int oldPid = group.readEntry("pid", -1 );
kDebug() <<"oldPid=" << oldPid;
const QString oldHostName = group.readEntry("hostname");
const QString oldAppName = group.readEntry( "appName", appName );
const QString oldProgramName = group.readEntry( "programName", programName );
const QString hostName = QHostInfo::localHostName();
bool first_instance = false;
if ( oldPid == -1 ) {
first_instance = true;
} else if ( hostName == oldHostName && oldPid != getpid() ) {
// check if the lock file is stale
#ifdef Q_OS_LINUX //krazy:exclude=cpp
if ( ::access("/proc", X_OK ) == 0 ) {
// On linux with /proc we can even check that
// it's really kmail and not something else
char path_buffer[MAXPATHLEN + 1];
path_buffer[MAXPATHLEN] = 0;
const QString procPath = QString( "/proc/%1/exe" ).arg( oldPid );
const int length =
readlink( procPath.toLatin1(), path_buffer, MAXPATHLEN );
if ( length == -1 ) { // no such pid
first_instance = true;
} else {
path_buffer[length] = '\0';
const QString path = QFile::decodeName( path_buffer );
kDebug() << path;
const int pos = path.lastIndexOf( '/' );
const QString fileName = path.mid( pos + 1 );
kDebug() <<"Found process" << oldPid
<< "running. It's:" << fileName;
first_instance = fileName != "kmail" && fileName != "kontact";
}
} else
#endif
{
// Otherwise we just check if the other pid is currently running.
// Not 100% correct but better safe than sorry.
if ( kill(oldPid, 0) == -1 )
first_instance = ( errno == ESRCH );
}
}
if ( !first_instance ) {
QString msg;
if ( oldHostName == hostName ) {
// this can only happen if the user is running this application on
// different displays on the same machine. All other cases will be
// taken care of by KUniqueApplication()
if ( oldAppName == appName )
msg = i18n("%1 already seems to be running on another display on "
"this machine. Running %2 more than once "
"can cause the loss of mail. You should not start %1 "
"unless you are sure that it is not already running.",
programName, programName );
// QString::arg( st ) only replaces the first occurrence of %1
// with st while QString::arg( s1, s2 ) replacess all occurrences
// of %1 with s1 and all occurrences of %2 with s2. So don't
// even think about changing the above to .arg( programName ).
else
msg = i18n("%1 seems to be running on another display on this "
"machine. Running %1 and %2 at the same "
"time can cause the loss of mail. You should not start %2 "
"unless you are sure that %1 is not running.",
oldProgramName, programName );
}
else {
if ( oldAppName == appName )
msg = i18n("%1 already seems to be running on %2. Running %1 more "
"than once can cause the loss of mail. You should not "
"start %1 on this computer unless you are sure that it is "
"not already running on %2.",
programName, oldHostName );
else
msg = i18n("%1 seems to be running on %3. Running %1 and %2 at the "
"same time can cause the loss of mail. You should not "
"start %2 on this computer unless you are sure that %1 is "
"not running on %3.",
oldProgramName, programName, oldHostName );
}
KCursorSaver idle( KBusyPtr::idle() );
if ( KMessageBox::No ==
KMessageBox::warningYesNo( 0, msg, QString(),
KGuiItem(i18nc("Start kmail even when another instance is running.", "Start %1", programName )),
KGuiItem(i18nc("Do not start another kmail instance.","Exit")) ) ) {
exit(1);
}
}
group.writeEntry("pid", getpid());
group.writeEntry("hostname", hostName);
group.writeEntry( "appName", appName );
group.writeEntry( "programName", programName );
group.sync();
}
void insertLibraryCataloguesAndIcons() {
static const char * const catalogs[] = {
"libkdepim",
"libksieve",
"libkleopatra",
"libkmime"
};
KLocale * l = KGlobal::locale();
KIconLoader * il = KIconLoader::global();
for ( unsigned int i = 0 ; i < sizeof catalogs / sizeof *catalogs ; ++i ) {
l->insertCatalog( catalogs[i] );
il->addAppDir( catalogs[i] );
}
}
void cleanup()
{
const QString lockLocation = KStandardDirs::locateLocal("data", "kmail/lock");
KConfig config(lockLocation, KConfig::SimpleConfig);
KConfigGroup group(&config, "");
group.writeEntry("pid", -1);
group.sync();
}
}
<commit_msg>cast getpid() to a qlonglong so we don't rely on a system include to give us a type that QVariant can't handle.<commit_after>/*
This file is part of KMail, the KDE mail client.
Copyright (c) 2000 Don Sanders <sanders@kde.org>
KMail is free software; you can redistribute it and/or modify it
under the terms of the GNU General Public License, version 2, as
published by the Free Software Foundation.
KMail 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
General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program; if not, write to the Free Software
Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
*/
#include "kmstartup.h"
#include <kdepim-compat.h> // for KDE_signal, remove in KDEPIM 4.2
#include "kmkernel.h" //control center
#include "kcursorsaver.h"
#include <klocale.h>
#include <kcomponentdata.h>
#include <kconfig.h>
#include <kstandarddirs.h>
#include <kmessagebox.h>
#include <kcrash.h>
#include <kglobal.h>
#include <kaboutdata.h>
#include <kiconloader.h>
#include <kconfiggroup.h>
#include <kde_file.h>
#include <QHostInfo>
#include <errno.h>
#include <sys/types.h>
#include <sys/param.h>
#include <signal.h>
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <qfile.h>
#undef Status // stupid X headers
extern "C" {
// Crash recovery signal handler
void kmsignalHandler(int sigId)
{
kmsetSignalHandler(SIG_DFL);
fprintf(stderr, "*** KMail got signal %d (Exiting)\n", sigId);
// try to cleanup all windows
if (kmkernel) kmkernel->dumpDeadLetters();
::exit(-1); //
}
// Crash recovery signal handler
void kmcrashHandler(int sigId)
{
kmsetSignalHandler(SIG_DFL);
fprintf(stderr, "*** KMail got signal %d (Crashing)\n", sigId);
// try to cleanup all windows
if (kmkernel) kmkernel->dumpDeadLetters();
// Return to DrKonqi.
}
//-----------------------------------------------------------------------------
void kmsetSignalHandler(void (*handler)(int))
{
KDE_signal(SIGKILL, handler);
KDE_signal(SIGTERM, handler);
KDE_signal(SIGHUP, handler);
KCrash::setEmergencySaveFunction(kmcrashHandler);
}
}
//-----------------------------------------------------------------------------
namespace KMail {
void checkConfigUpdates() {
static const char * const updates[] = {
"9",
"3.1-update-identities",
"3.1-use-identity-uoids",
"3.1-new-mail-notification",
"3.2-update-loop-on-goto-unread-settings",
"3.1.4-dont-use-UOID-0-for-any-identity", //krazy:exclude=spelling
"3.2-misc",
"3.2-moves",
"3.3-use-ID-for-accounts",
"3.3-update-filter-rules",
"3.3-move-identities-to-own-file",
"3.3-aegypten-kpgprc-to-kmailrc",
"3.3-aegypten-kpgprc-to-libkleopatrarc",
"3.3-aegypten-emailidentities-split-sign-encr-keys",
"3.3-misc",
"3.3b1-misc",
"3.4-misc",
"3.4a",
"3.4b",
"3.4.1",
"3.5.4",
"3.5.7-imap-flag-migration",
"4.0-misc",
"4.2"
};
static const int numUpdates = sizeof updates / sizeof *updates;
// Warning: do not remove entries in the above array, or the update-level check below will break
KConfig * config = KMKernel::config();
KConfigGroup startup( config, "Startup" );
const int configUpdateLevel = startup.readEntry( "update-level", 0 );
if ( configUpdateLevel == numUpdates ) // Optimize for the common case that everything is OK
return;
for ( int i = configUpdateLevel ; i < numUpdates ; ++i ) {
config->checkUpdate( updates[i], "kmail.upd" );
}
startup.writeEntry( "update-level", numUpdates );
}
void lockOrDie() {
// Check and create a lock file to prevent concurrent access to kmail files
QString appName = KGlobal::mainComponent().componentName();
if ( appName.isEmpty() )
appName = "kmail";
QString programName;
const KAboutData *about = KGlobal::mainComponent().aboutData();
if ( about )
programName = about->programName();
if ( programName.isEmpty() )
programName = i18n("KMail");
QString lockLocation = KStandardDirs::locateLocal("data", "kmail/lock");
KConfig config(lockLocation, KConfig::SimpleConfig);
KConfigGroup group(&config, "");
int oldPid = group.readEntry("pid", -1 );
kDebug() <<"oldPid=" << oldPid;
const QString oldHostName = group.readEntry("hostname");
const QString oldAppName = group.readEntry( "appName", appName );
const QString oldProgramName = group.readEntry( "programName", programName );
const QString hostName = QHostInfo::localHostName();
bool first_instance = false;
if ( oldPid == -1 ) {
first_instance = true;
} else if ( hostName == oldHostName && oldPid != getpid() ) {
// check if the lock file is stale
#ifdef Q_OS_LINUX //krazy:exclude=cpp
if ( ::access("/proc", X_OK ) == 0 ) {
// On linux with /proc we can even check that
// it's really kmail and not something else
char path_buffer[MAXPATHLEN + 1];
path_buffer[MAXPATHLEN] = 0;
const QString procPath = QString( "/proc/%1/exe" ).arg( oldPid );
const int length =
readlink( procPath.toLatin1(), path_buffer, MAXPATHLEN );
if ( length == -1 ) { // no such pid
first_instance = true;
} else {
path_buffer[length] = '\0';
const QString path = QFile::decodeName( path_buffer );
kDebug() << path;
const int pos = path.lastIndexOf( '/' );
const QString fileName = path.mid( pos + 1 );
kDebug() <<"Found process" << oldPid
<< "running. It's:" << fileName;
first_instance = fileName != "kmail" && fileName != "kontact";
}
} else
#endif
{
// Otherwise we just check if the other pid is currently running.
// Not 100% correct but better safe than sorry.
if ( kill(oldPid, 0) == -1 )
first_instance = ( errno == ESRCH );
}
}
if ( !first_instance ) {
QString msg;
if ( oldHostName == hostName ) {
// this can only happen if the user is running this application on
// different displays on the same machine. All other cases will be
// taken care of by KUniqueApplication()
if ( oldAppName == appName )
msg = i18n("%1 already seems to be running on another display on "
"this machine. Running %2 more than once "
"can cause the loss of mail. You should not start %1 "
"unless you are sure that it is not already running.",
programName, programName );
// QString::arg( st ) only replaces the first occurrence of %1
// with st while QString::arg( s1, s2 ) replacess all occurrences
// of %1 with s1 and all occurrences of %2 with s2. So don't
// even think about changing the above to .arg( programName ).
else
msg = i18n("%1 seems to be running on another display on this "
"machine. Running %1 and %2 at the same "
"time can cause the loss of mail. You should not start %2 "
"unless you are sure that %1 is not running.",
oldProgramName, programName );
}
else {
if ( oldAppName == appName )
msg = i18n("%1 already seems to be running on %2. Running %1 more "
"than once can cause the loss of mail. You should not "
"start %1 on this computer unless you are sure that it is "
"not already running on %2.",
programName, oldHostName );
else
msg = i18n("%1 seems to be running on %3. Running %1 and %2 at the "
"same time can cause the loss of mail. You should not "
"start %2 on this computer unless you are sure that %1 is "
"not running on %3.",
oldProgramName, programName, oldHostName );
}
KCursorSaver idle( KBusyPtr::idle() );
if ( KMessageBox::No ==
KMessageBox::warningYesNo( 0, msg, QString(),
KGuiItem(i18nc("Start kmail even when another instance is running.", "Start %1", programName )),
KGuiItem(i18nc("Do not start another kmail instance.","Exit")) ) ) {
exit(1);
}
}
qlonglong pid = static_cast<qlonglong>( getpid() );
group.writeEntry( "pid", pid );
group.writeEntry( "hostname", hostName );
group.writeEntry( "appName", appName );
group.writeEntry( "programName", programName );
group.sync();
}
void insertLibraryCataloguesAndIcons() {
static const char * const catalogs[] = {
"libkdepim",
"libksieve",
"libkleopatra",
"libkmime"
};
KLocale * l = KGlobal::locale();
KIconLoader * il = KIconLoader::global();
for ( unsigned int i = 0 ; i < sizeof catalogs / sizeof *catalogs ; ++i ) {
l->insertCatalog( catalogs[i] );
il->addAppDir( catalogs[i] );
}
}
void cleanup()
{
const QString lockLocation = KStandardDirs::locateLocal("data", "kmail/lock");
KConfig config(lockLocation, KConfig::SimpleConfig);
KConfigGroup group(&config, "");
group.writeEntry("pid", -1);
group.sync();
}
}
<|endoftext|> |
<commit_before>#include <iostream>
#include "WiFi_Controller.h"
using namespace flyhero;
extern "C" void app_main(void)
{
WiFi_Controller& wifi = WiFi_Controller::Instance();
LEDs::Init();
wifi.Init();
uint8_t buffer[200];
uint8_t read;
while (true) {
if (wifi.Receive(buffer, 200, read)) {
buffer[read] = '\0';
std::cout << buffer << std::endl;
}
vTaskDelay(500 / portTICK_RATE_MS);
}
}
<commit_msg>(WiFi): fix NVS flash not being initialized<commit_after>#include <iostream>
#include <nvs_flash.h>
#include "WiFi_Controller.h"
using namespace flyhero;
extern "C" void app_main(void)
{
// Initialize NVS
esp_err_t nvs_status = nvs_flash_init();
if (nvs_status == ESP_ERR_NVS_NO_FREE_PAGES) {
ESP_ERROR_CHECK(nvs_flash_erase());
nvs_status = nvs_flash_init();
}
ESP_ERROR_CHECK(nvs_status);
WiFi_Controller& wifi = WiFi_Controller::Instance();
LEDs::Init();
wifi.Init();
uint8_t buffer[200];
uint8_t read;
while (true) {
if (wifi.Receive(buffer, 200, read)) {
buffer[read] = '\0';
std::cout << buffer << std::endl;
}
vTaskDelay(500 / portTICK_RATE_MS);
}
}
<|endoftext|> |
<commit_before>#include "settingslist.h"
std::vector<std::wstring> getSettingsList(void)
{
std::vector<std::wstring> ret;
ret.push_back(L"update_freq_incr");
ret.push_back(L"update_freq_full");
ret.push_back(L"update_freq_image_full");
ret.push_back(L"update_freq_image_incr");
ret.push_back(L"max_file_incr");
ret.push_back(L"min_file_incr");
ret.push_back(L"max_file_full");
ret.push_back(L"min_file_full");
ret.push_back(L"min_image_incr");
ret.push_back(L"max_image_incr");
ret.push_back(L"min_image_full");
ret.push_back(L"max_image_full");
ret.push_back(L"startup_backup_delay");
ret.push_back(L"backup_window_incr_file");
ret.push_back(L"backup_window_full_file");
ret.push_back(L"backup_window_incr_image");
ret.push_back(L"backup_window_full_image");
ret.push_back(L"exclude_files");
ret.push_back(L"include_files");
ret.push_back(L"computername");
ret.push_back(L"default_dirs");
ret.push_back(L"allow_config_paths");
ret.push_back(L"allow_starting_full_file_backups");
ret.push_back(L"allow_starting_incr_file_backups");
ret.push_back(L"allow_starting_full_image_backups");
ret.push_back(L"allow_starting_incr_image_backups");
ret.push_back(L"allow_pause");
ret.push_back(L"allow_log_view");
ret.push_back(L"allow_overwrite");
ret.push_back(L"allow_tray_exit");
ret.push_back(L"image_letters");
ret.push_back(L"internet_server");
ret.push_back(L"internet_server_port");
ret.push_back(L"internet_authkey");
ret.push_back(L"internet_speed");
ret.push_back(L"local_speed");
ret.push_back(L"internet_client_enabled");
ret.push_back(L"internet_image_backups");
ret.push_back(L"internet_full_file_backups");
ret.push_back(L"internet_encrypt");
ret.push_back(L"internet_compress");
ret.push_back(L"internet_mode_enabled");
ret.push_back(L"silent_update");
ret.push_back(L"client_quota");
ret.push_back(L"local_full_file_transfer_mode");
ret.push_back(L"internet_full_file_transfer_mode");
ret.push_back(L"local_incr_file_transfer_mode");
ret.push_back(L"internet_incr_file_transfer_mode");
ret.push_back(L"local_image_transfer_mode");
ret.push_back(L"internet_image_transfer_mode");
ret.push_back(L"file_hash_collect_amount");
ret.push_back(L"file_hash_collect_timeout");
ret.push_back(L"file_hash_collect_cachesize");
ret.push_back(L"end_to_end_file_backup_verification");
ret.push_back(L"internet_calculate_filehashes_on_client");
ret.push_back(L"image_file_format");
ret.push_back(L"internet_connect_always");
ret.push_back(L"verify_using_client_hashes");
ret.push_back(L"internet_readd_file_entries");
return ret;
}
std::vector<std::wstring> getOnlyServerClientSettingsList(void)
{
std::vector<std::wstring> ret;
ret.push_back(L"silent_update");
ret.push_back(L"client_quota");
ret.push_back(L"local_full_file_transfer_mode");
ret.push_back(L"internet_full_file_transfer_mode");
ret.push_back(L"local_incr_file_transfer_mode");
ret.push_back(L"internet_incr_file_transfer_mode");
ret.push_back(L"local_image_transfer_mode");
ret.push_back(L"internet_image_transfer_mode");
ret.push_back(L"file_hash_collect_amount");
ret.push_back(L"file_hash_collect_timeout");
ret.push_back(L"file_hash_collect_cachesize");
ret.push_back(L"end_to_end_file_backup_verification");
ret.push_back(L"internet_calculate_filehashes_on_client");
ret.push_back(L"image_file_format");
ret.push_back(L"verify_using_client_hashes");
ret.push_back(L"internet_readd_file_entries");
return ret;
}
std::vector<std::wstring> getGlobalizedSettingsList(void)
{
std::vector<std::wstring> ret;
ret.push_back(L"internet_server");
ret.push_back(L"internet_server_port");
return ret;
}
std::vector<std::wstring> getLocalizedSettingsList(void)
{
std::vector<std::wstring> ret;
ret.push_back(L"internet_authkey");
return ret;
}
std::vector<std::wstring> getGlobalSettingsList(void)
{
std::vector<std::wstring> ret;
ret.push_back(L"backupfolder");
ret.push_back(L"no_images");
ret.push_back(L"no_file_backups");
ret.push_back(L"autoshutdown");
ret.push_back(L"download_client");
ret.push_back(L"autoupdate_clients");
ret.push_back(L"max_sim_backups");
ret.push_back(L"max_active_clients");
ret.push_back(L"cleanup_window");
ret.push_back(L"backup_database");
ret.push_back(L"internet_server");
ret.push_back(L"internet_server_port");
ret.push_back(L"global_local_speed");
ret.push_back(L"global_internet_speed");
ret.push_back(L"use_tmpfiles");
ret.push_back(L"use_tmpfiles_images");
ret.push_back(L"tmpdir");
ret.push_back(L"update_stats_cachesize");
ret.push_back(L"global_soft_fs_quota");
ret.push_back(L"filescache_type");
ret.push_back(L"filescache_size");
ret.push_back(L"trust_client_hashes");
ret.push_back(L"show_server_updates");
return ret;
}<commit_msg>Fix disabling of symlink incremental backups from web interface<commit_after>#include "settingslist.h"
std::vector<std::wstring> getSettingsList(void)
{
std::vector<std::wstring> ret;
ret.push_back(L"update_freq_incr");
ret.push_back(L"update_freq_full");
ret.push_back(L"update_freq_image_full");
ret.push_back(L"update_freq_image_incr");
ret.push_back(L"max_file_incr");
ret.push_back(L"min_file_incr");
ret.push_back(L"max_file_full");
ret.push_back(L"min_file_full");
ret.push_back(L"min_image_incr");
ret.push_back(L"max_image_incr");
ret.push_back(L"min_image_full");
ret.push_back(L"max_image_full");
ret.push_back(L"startup_backup_delay");
ret.push_back(L"backup_window_incr_file");
ret.push_back(L"backup_window_full_file");
ret.push_back(L"backup_window_incr_image");
ret.push_back(L"backup_window_full_image");
ret.push_back(L"exclude_files");
ret.push_back(L"include_files");
ret.push_back(L"computername");
ret.push_back(L"default_dirs");
ret.push_back(L"allow_config_paths");
ret.push_back(L"allow_starting_full_file_backups");
ret.push_back(L"allow_starting_incr_file_backups");
ret.push_back(L"allow_starting_full_image_backups");
ret.push_back(L"allow_starting_incr_image_backups");
ret.push_back(L"allow_pause");
ret.push_back(L"allow_log_view");
ret.push_back(L"allow_overwrite");
ret.push_back(L"allow_tray_exit");
ret.push_back(L"image_letters");
ret.push_back(L"internet_server");
ret.push_back(L"internet_server_port");
ret.push_back(L"internet_authkey");
ret.push_back(L"internet_speed");
ret.push_back(L"local_speed");
ret.push_back(L"internet_client_enabled");
ret.push_back(L"internet_image_backups");
ret.push_back(L"internet_full_file_backups");
ret.push_back(L"internet_encrypt");
ret.push_back(L"internet_compress");
ret.push_back(L"internet_mode_enabled");
ret.push_back(L"silent_update");
ret.push_back(L"client_quota");
ret.push_back(L"local_full_file_transfer_mode");
ret.push_back(L"internet_full_file_transfer_mode");
ret.push_back(L"local_incr_file_transfer_mode");
ret.push_back(L"internet_incr_file_transfer_mode");
ret.push_back(L"local_image_transfer_mode");
ret.push_back(L"internet_image_transfer_mode");
ret.push_back(L"file_hash_collect_amount");
ret.push_back(L"file_hash_collect_timeout");
ret.push_back(L"file_hash_collect_cachesize");
ret.push_back(L"end_to_end_file_backup_verification");
ret.push_back(L"internet_calculate_filehashes_on_client");
ret.push_back(L"image_file_format");
ret.push_back(L"internet_connect_always");
ret.push_back(L"verify_using_client_hashes");
ret.push_back(L"internet_readd_file_entries");
return ret;
}
std::vector<std::wstring> getOnlyServerClientSettingsList(void)
{
std::vector<std::wstring> ret;
ret.push_back(L"silent_update");
ret.push_back(L"client_quota");
ret.push_back(L"local_full_file_transfer_mode");
ret.push_back(L"internet_full_file_transfer_mode");
ret.push_back(L"local_incr_file_transfer_mode");
ret.push_back(L"internet_incr_file_transfer_mode");
ret.push_back(L"local_image_transfer_mode");
ret.push_back(L"internet_image_transfer_mode");
ret.push_back(L"file_hash_collect_amount");
ret.push_back(L"file_hash_collect_timeout");
ret.push_back(L"file_hash_collect_cachesize");
ret.push_back(L"end_to_end_file_backup_verification");
ret.push_back(L"internet_calculate_filehashes_on_client");
ret.push_back(L"image_file_format");
ret.push_back(L"verify_using_client_hashes");
ret.push_back(L"internet_readd_file_entries");
return ret;
}
std::vector<std::wstring> getGlobalizedSettingsList(void)
{
std::vector<std::wstring> ret;
ret.push_back(L"internet_server");
ret.push_back(L"internet_server_port");
return ret;
}
std::vector<std::wstring> getLocalizedSettingsList(void)
{
std::vector<std::wstring> ret;
ret.push_back(L"internet_authkey");
return ret;
}
std::vector<std::wstring> getGlobalSettingsList(void)
{
std::vector<std::wstring> ret;
ret.push_back(L"backupfolder");
ret.push_back(L"no_images");
ret.push_back(L"no_file_backups");
ret.push_back(L"autoshutdown");
ret.push_back(L"download_client");
ret.push_back(L"autoupdate_clients");
ret.push_back(L"max_sim_backups");
ret.push_back(L"max_active_clients");
ret.push_back(L"cleanup_window");
ret.push_back(L"backup_database");
ret.push_back(L"internet_server");
ret.push_back(L"internet_server_port");
ret.push_back(L"global_local_speed");
ret.push_back(L"global_internet_speed");
ret.push_back(L"use_tmpfiles");
ret.push_back(L"use_tmpfiles_images");
ret.push_back(L"tmpdir");
ret.push_back(L"update_stats_cachesize");
ret.push_back(L"global_soft_fs_quota");
ret.push_back(L"filescache_type");
ret.push_back(L"filescache_size");
ret.push_back(L"trust_client_hashes");
ret.push_back(L"show_server_updates");
ret.push_back(L"use_incremental_symlinks");
return ret;
}<|endoftext|> |
<commit_before>
#include <vector>
#include <string>
using namespace std;
namespace L10ns {
enum class ActionKind {
None,
Init,
Update,
Log,
Set,
};
enum class FlagKind {
None,
Help,
Version,
Language,
Key,
Value,
};
struct Argument {
string * name;
string * description;
Argument(string * pname, string * pdescription) {
name = pname;
description = pdescription;
}
};
struct Flag : Argument {
string * alias;
bool hasValue;
FlagKind kind;
string value;
Flag(FlagKind pkind, const char pname[], const char palias[], const char pdescription[], bool phasValue)
: kind(pkind), Argument(new string(pname), new string(pdescription)), alias(new string(palias)) {
hasValue = phasValue;
value = "";
}
};
struct Action : Argument {
vector<Flag> * flags;
ActionKind kind;
Action(ActionKind pkind, const char pname[], const char pdescription[], vector<Flag> * pflags)
: kind(pkind), Argument(new string(pname), new string(pdescription)) {
if (pflags != NULL) {
flags = pflags;
}
}
};
static Flag helpFlag = Flag(FlagKind::Help, "--help", "-h", "Print help description.", /*hasValue*/ false);
static Flag languageFlag = Flag(FlagKind::Language, "--language", "-l", "Specify language.", false);
static vector<Flag> defaultFlags = {
helpFlag,
Flag(FlagKind::Version, "--version", "-v", "Print current version.", /*hasValue*/ false),
};
static vector<Flag> helpFlags = {
helpFlag,
};
static vector<Flag> setFlags = {
Flag(FlagKind::Key, "--key", "-k", "Specify localization key.", /*hasValue*/ true),
Flag(FlagKind::Value, "--value", "-v", "Specify localization value.", /*hasValue*/ true),
languageFlag,
helpFlag,
};
static vector<Flag> logFlags = {
languageFlag,
helpFlag,
};
static vector<Action> actions = {
Action(ActionKind::Init, "init", "Initialize project.", &helpFlags),
Action(ActionKind::Update, "update", "Update localization keys.", &helpFlags),
Action(ActionKind::Log, "log", "Show latest added localizations.", &logFlags),
Action(ActionKind::Set, "set", "Set localization.", &setFlags),
};
struct Command {
bool isRequestingHelp;
bool isRequestingVersion;
ActionKind action;
vector<Flag> * flags;
Command()
: isRequestingHelp(false)
, isRequestingVersion(false)
, action(ActionKind::None)
, flags(&defaultFlags) {
}
};
void setCommandFlag(Command *command, const Flag *flag, char *value = NULL) {
switch (flag->kind) {
case FlagKind::Help:
command->isRequestingHelp = true;
return;
case FlagKind::Version:
command->isRequestingVersion = true;
return;
default:
return;
}
}
Command* parseCommandArguments(int argc, char* argv[]) {
Command * command = new Command();
bool hasAction = false; // Flag to optimize has action parsing.
const Flag * flagWhichAwaitsValue = NULL; // The option flag that is pending for a value.
for (int argIndex = 1; argIndex < argc; argIndex++) {
auto arg = argv[argIndex];
if (!hasAction) {
for (auto const& a : actions) {
if (strcmp(a.name->c_str(), arg) == 0) {
command->action = a.kind;
hasAction = true;
command->flags = a.flags;
break;
}
}
}
if (flagWhichAwaitsValue == NULL) {
for (auto const& flag : *command->flags) {
if (strcmp(flag.name->c_str(), arg) == 0 || (flag.alias->length() != 0 && strcmp(flag.name->c_str(), arg) == 0)) {
if (flag.hasValue) {
flagWhichAwaitsValue = &flag;
}
setCommandFlag(command, &flag);
break;
}
}
}
else {
setCommandFlag(command, flagWhichAwaitsValue, arg);
flagWhichAwaitsValue = NULL;
continue;
}
}
return command;
}
} // L10ns
<commit_msg>Improve comments<commit_after>
#include <vector>
#include <string>
using namespace std;
namespace L10ns {
enum class ActionKind {
None,
Init,
Update,
Log,
Set,
};
enum class FlagKind {
None,
Help,
Version,
Language,
Key,
Value,
};
struct Argument {
string * name;
string * description;
Argument(string * pname, string * pdescription) {
name = pname;
description = pdescription;
}
};
struct Flag : Argument {
string * alias;
bool hasValue;
FlagKind kind;
string value;
Flag(FlagKind pkind, const char pname[], const char palias[], const char pdescription[], bool phasValue)
: kind(pkind), Argument(new string(pname), new string(pdescription)), alias(new string(palias)) {
hasValue = phasValue;
value = "";
}
};
struct Action : Argument {
vector<Flag> * flags;
ActionKind kind;
Action(ActionKind pkind, const char pname[], const char pdescription[], vector<Flag> * pflags)
: kind(pkind), Argument(new string(pname), new string(pdescription)) {
if (pflags != NULL) {
flags = pflags;
}
}
};
static Flag helpFlag = Flag(FlagKind::Help, "--help", "-h", "Print help description.", /*hasValue*/ false);
static Flag languageFlag = Flag(FlagKind::Language, "--language", "-l", "Specify language.", false);
static vector<Flag> defaultFlags = {
helpFlag,
Flag(FlagKind::Version, "--version", "-v", "Print current version.", /*hasValue*/ false),
};
static vector<Flag> helpFlags = {
helpFlag,
};
static vector<Flag> setFlags = {
Flag(FlagKind::Key, "--key", "-k", "Specify localization key.", /*hasValue*/ true),
Flag(FlagKind::Value, "--value", "-v", "Specify localization value.", /*hasValue*/ true),
languageFlag,
helpFlag,
};
static vector<Flag> logFlags = {
languageFlag,
helpFlag,
};
static vector<Action> actions = {
Action(ActionKind::Init, "init", "Initialize project.", &helpFlags),
Action(ActionKind::Update, "update", "Update localization keys.", &helpFlags),
Action(ActionKind::Log, "log", "Show latest added localizations.", &logFlags),
Action(ActionKind::Set, "set", "Set localization.", &setFlags),
};
struct Command {
bool isRequestingHelp;
bool isRequestingVersion;
ActionKind action;
vector<Flag> * flags;
Command()
: isRequestingHelp(false)
, isRequestingVersion(false)
, action(ActionKind::None)
, flags(&defaultFlags) {
}
};
void setCommandFlag(Command *command, const Flag *flag, char *value = NULL) {
switch (flag->kind) {
case FlagKind::Help:
command->isRequestingHelp = true;
return;
case FlagKind::Version:
command->isRequestingVersion = true;
return;
default:
return;
}
}
Command* parseCommandArguments(int argc, char* argv[]) {
Command * command = new Command();
// Flag to optimize has action parsing.
bool hasAction = false;
// The option flag that is pending for a value.
const Flag * flagWhichAwaitsValue = NULL;
for (int argIndex = 1; argIndex < argc; argIndex++) {
auto arg = argv[argIndex];
if (!hasAction) {
for (auto const& a : actions) {
if (strcmp(a.name->c_str(), arg) == 0) {
command->action = a.kind;
hasAction = true;
command->flags = a.flags;
break;
}
}
}
if (flagWhichAwaitsValue == NULL) {
for (auto const& flag : *command->flags) {
if (strcmp(flag.name->c_str(), arg) == 0 || (flag.alias->length() != 0 && strcmp(flag.name->c_str(), arg) == 0)) {
if (flag.hasValue) {
flagWhichAwaitsValue = &flag;
}
setCommandFlag(command, &flag);
break;
}
}
}
else {
setCommandFlag(command, flagWhichAwaitsValue, arg);
flagWhichAwaitsValue = NULL;
continue;
}
}
return command;
}
} // L10ns
<|endoftext|> |
<commit_before>// Copyright (c) 2017 ASMlover. All rights reserved.
//
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions
// are met:
//
// * Redistributions of source code must retain the above copyright
// notice, this list ofconditions and the following disclaimer.
//
// * Redistributions in binary form must reproduce the above copyright
// notice, this list of conditions and the following disclaimer in
// the documentation and/or other materialsprovided with the
// distribution.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
// FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
// COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
// INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
// BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
// LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
// CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
// LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN
// ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
// POSSIBILITY OF SUCH DAMAGE.
#include <algorithm>
#include <functional>
#include <iostream>
#include <Chaos/Types.h>
#include <Chaos/Concurrent/Thread.h>
#include "object.h"
#include "parallel_gc.h"
namespace gc {
class Sweeper : private Chaos::UnCopyable {
int id_{};
bool running_{true};
bool sweeping_{};
mutable Chaos::Mutex mutex_;
Chaos::Condition cond_;
Chaos::Thread thread_;
std::vector<BaseObject*> roots_;
std::list<BaseObject*> objects_;
std::vector<BaseObject*> worklist_;
void mark(void) {
while (!worklist_.empty()) {
auto* obj = worklist_.back();
worklist_.pop_back();
if (obj->is_pair()) {
auto append_fn = [this](BaseObject* o) {
if (o != nullptr && !o->is_marked()) {
o->set_marked(); worklist_.push_back(o);
}
};
append_fn(Chaos::down_cast<Pair*>(obj)->first());
append_fn(Chaos::down_cast<Pair*>(obj)->second());
}
}
}
void mark_from_roots(void) {
for (auto* obj : roots_) {
obj->set_marked();
worklist_.push_back(obj);
mark();
}
}
void sweep(void) {
for (auto it = objects_.begin(); it != objects_.end();) {
if (!(*it)->is_marked()) {
delete *it;
objects_.erase(it++);
}
else {
(*it)->unset_marked();
++it;
}
}
}
void sweeper_closure(void) {
while (sweeping_) {
while (running_ && !sweeping_)
cond_.wait();
if (!running_)
break;
mark_from_roots();
sweep();
if (sweeping_) {
sweeping_ = false;
gc::ParallelGC::get_instance().notify_collected(id_, objects_.size());
}
}
}
public:
Sweeper(int id)
: id_(id)
, mutex_()
, cond_(mutex_)
, thread_([this]{ sweeper_closure(); }) {
thread_.start();
}
~Sweeper(void) { stop(); thread_.join(); }
void stop(void) { running_ = false; cond_.notify_one(); }
void collect(void) { sweeping_ = true; cond_.notify_one(); }
void put_in(BaseObject* obj) {
roots_.push_back(obj);
objects_.push_back(obj);
}
BaseObject* fetch_out(void) {
auto* obj = roots_.back();
roots_.pop_back();
return obj;
}
};
ParallelGC::ParallelGC(void)
: sweeper_mutex_()
, sweeper_cond_(sweeper_mutex_) {
startup_sweepers();
}
ParallelGC::~ParallelGC(void) {
clearup_sweepers();
}
void ParallelGC::startup_sweepers(void) {
for (auto i = 0u; i < kMaxSweepers; ++i)
sweepers_.emplace_back(new Sweeper(i));
}
void ParallelGC::clearup_sweepers(void) {
for (auto& s : sweepers_)
s->stop();
}
int ParallelGC::put_in_order(void) {
int r = order_;
order_ = (order_ + 1) % kMaxSweepers;
return r;
}
int ParallelGC::fetch_out_order(void) {
order_ = (order_ - 1 + kMaxSweepers) % kMaxSweepers;
return order_;
}
ParallelGC& ParallelGC::get_instance(void) {
static ParallelGC ins;
return ins;
}
void ParallelGC::notify_collected(int /*id*/, std::size_t remain_count) {
{
Chaos::ScopedLock<Chaos::Mutex> g(mutex_);
++sweeper_counter_;
object_counter_ += remain_count;
}
sweeper_cond_.notify_one();
}
void ParallelGC::collect(void) {
auto old_count = object_counter_;
sweeper_counter_ = 0;
object_counter_ = 0;
for (auto& s : sweepers_)
s->collect();
while (sweeper_counter_ < kMaxSweepers)
sweeper_cond_.wait();
std::cout
<< "[" << old_count - object_counter_ << "] objects collected, "
<< "[" << object_counter_ << "] objects remaining." << std::endl;
}
BaseObject* ParallelGC::put_in(int value) {
if (object_counter_ >= kMaxObjects)
collect();
auto* obj = new Int();
obj->set_value(value);
++object_counter_;
sweepers_[put_in_order()]->put_in(obj);
return obj;
}
BaseObject* ParallelGC::put_in(BaseObject* first, BaseObject* second) {
if (object_counter_ >= kMaxObjects)
collect();
auto* obj = new Pair();
if (first != nullptr)
obj->set_first(first);
if (second != nullptr)
obj->set_second(second);
++object_counter_;
sweepers_[put_in_order()]->put_in(obj);
return obj;
}
BaseObject* ParallelGC::fetch_out(void) {
return sweepers_[fetch_out_order()]->fetch_out();
}
}
<commit_msg>:bug: fix(ParallelGC): fixed sweeper bug for parallel gc<commit_after>// Copyright (c) 2017 ASMlover. All rights reserved.
//
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions
// are met:
//
// * Redistributions of source code must retain the above copyright
// notice, this list ofconditions and the following disclaimer.
//
// * Redistributions in binary form must reproduce the above copyright
// notice, this list of conditions and the following disclaimer in
// the documentation and/or other materialsprovided with the
// distribution.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
// FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
// COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
// INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
// BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
// LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
// CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
// LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN
// ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
// POSSIBILITY OF SUCH DAMAGE.
#include <algorithm>
#include <functional>
#include <iostream>
#include <Chaos/Types.h>
#include <Chaos/Concurrent/Thread.h>
#include "object.h"
#include "parallel_gc.h"
namespace gc {
class Sweeper : private Chaos::UnCopyable {
int id_{};
bool running_{true};
bool sweeping_{};
mutable Chaos::Mutex mutex_;
Chaos::Condition cond_;
Chaos::Thread thread_;
std::vector<BaseObject*> roots_;
std::list<BaseObject*> objects_;
std::vector<BaseObject*> worklist_;
void mark(void) {
while (!worklist_.empty()) {
auto* obj = worklist_.back();
worklist_.pop_back();
if (obj->is_pair()) {
auto append_fn = [this](BaseObject* o) {
if (o != nullptr && !o->is_marked()) {
o->set_marked(); worklist_.push_back(o);
}
};
append_fn(Chaos::down_cast<Pair*>(obj)->first());
append_fn(Chaos::down_cast<Pair*>(obj)->second());
}
}
}
void mark_from_roots(void) {
for (auto* obj : roots_) {
obj->set_marked();
worklist_.push_back(obj);
mark();
}
}
void sweep(void) {
for (auto it = objects_.begin(); it != objects_.end();) {
if (!(*it)->is_marked()) {
delete *it;
objects_.erase(it++);
}
else {
(*it)->unset_marked();
++it;
}
}
}
void sweeper_closure(void) {
while (running_) {
while (running_ && !sweeping_)
cond_.wait();
if (!running_)
break;
mark_from_roots();
sweep();
if (sweeping_) {
sweeping_ = false;
gc::ParallelGC::get_instance().notify_collected(id_, objects_.size());
}
}
}
public:
Sweeper(int id)
: id_(id)
, mutex_()
, cond_(mutex_)
, thread_([this]{ sweeper_closure(); }) {
thread_.start();
}
~Sweeper(void) { stop(); thread_.join(); }
void stop(void) { running_ = false; cond_.notify_one(); }
void collect(void) { sweeping_ = true; cond_.notify_one(); }
void put_in(BaseObject* obj) {
roots_.push_back(obj);
objects_.push_back(obj);
}
BaseObject* fetch_out(void) {
auto* obj = roots_.back();
roots_.pop_back();
return obj;
}
};
ParallelGC::ParallelGC(void)
: sweeper_mutex_()
, sweeper_cond_(sweeper_mutex_) {
startup_sweepers();
}
ParallelGC::~ParallelGC(void) {
clearup_sweepers();
}
void ParallelGC::startup_sweepers(void) {
for (auto i = 0u; i < kMaxSweepers; ++i)
sweepers_.emplace_back(new Sweeper(i));
}
void ParallelGC::clearup_sweepers(void) {
for (auto& s : sweepers_)
s->stop();
}
int ParallelGC::put_in_order(void) {
int r = order_;
order_ = (order_ + 1) % kMaxSweepers;
return r;
}
int ParallelGC::fetch_out_order(void) {
order_ = (order_ - 1 + kMaxSweepers) % kMaxSweepers;
return order_;
}
ParallelGC& ParallelGC::get_instance(void) {
static ParallelGC ins;
return ins;
}
void ParallelGC::notify_collected(int /*id*/, std::size_t remain_count) {
{
Chaos::ScopedLock<Chaos::Mutex> g(mutex_);
++sweeper_counter_;
object_counter_ += remain_count;
}
sweeper_cond_.notify_one();
}
void ParallelGC::collect(void) {
auto old_count = object_counter_;
sweeper_counter_ = 0;
object_counter_ = 0;
for (auto& s : sweepers_)
s->collect();
while (sweeper_counter_ < kMaxSweepers)
sweeper_cond_.wait();
std::cout
<< "[" << old_count - object_counter_ << "] objects collected, "
<< "[" << object_counter_ << "] objects remaining." << std::endl;
}
BaseObject* ParallelGC::put_in(int value) {
if (object_counter_ >= kMaxObjects)
collect();
auto* obj = new Int();
obj->set_value(value);
++object_counter_;
sweepers_[put_in_order()]->put_in(obj);
return obj;
}
BaseObject* ParallelGC::put_in(BaseObject* first, BaseObject* second) {
if (object_counter_ >= kMaxObjects)
collect();
auto* obj = new Pair();
if (first != nullptr)
obj->set_first(first);
if (second != nullptr)
obj->set_second(second);
++object_counter_;
sweepers_[put_in_order()]->put_in(obj);
return obj;
}
BaseObject* ParallelGC::fetch_out(void) {
return sweepers_[fetch_out_order()]->fetch_out();
}
}
<|endoftext|> |
<commit_before>#include "Texture.h"
#include "DebugLog.h"
#include "volume.hpp"
#include <chrono>
#include <iostream>
#include <windows.h>
#include <direct.h>
#include <Commdlg.h>
using namespace std;
const int SCREEN_WIDTH = 1280;
const int SCREEN_HEIGHT = 1024;
char fileName[MAX_PATH];
Texture* texture;
void raycast()
{
Shader computeShader("Shaders\\raycast.glsl");
glUseProgram(computeShader.program);
glBindImageTexture(0, texture->textureId, 0, GL_FALSE, 0, GL_WRITE_ONLY, GL_RGBA32F);
Volume volume(fileName);
const uint64_t volumeSize = sizeof(float) * volume.info.volume();
header info = volume.info;
GLuint buffer;
glGenBuffers(1, &buffer);
glBindBuffer(GL_SHADER_STORAGE_BUFFER, buffer);
glBufferData(GL_SHADER_STORAGE_BUFFER, volumeSize * 4, volume.data, GL_DYNAMIC_COPY);
glBindBufferBase(GL_SHADER_STORAGE_BUFFER, 1, buffer);
glUniform1f(glGetUniformLocation(computeShader.program, "eyePosition"), -500.0f);
glUniform1f(glGetUniformLocation(computeShader.program, "monitorPosition"), 0.0f);
glUniform2i(glGetUniformLocation(computeShader.program, "screen"), SCREEN_WIDTH, SCREEN_HEIGHT);
glUniform3i(glGetUniformLocation(computeShader.program, "size"), static_cast<GLint>(info.x), static_cast<GLint>(info.y), static_cast<GLint>(info.z));
glUniform3f(glGetUniformLocation(computeShader.program, "d"), info.d.x, info.d.y, info.d.z);
glUniform3f(glGetUniformLocation(computeShader.program, "min"), info.min.x, info.min.y, info.min.z);
glUniform3f(glGetUniformLocation(computeShader.program, "max"), info.max.x, info.max.y, info.max.z);
auto start = chrono::steady_clock::now();
glDispatchCompute(SCREEN_WIDTH, SCREEN_HEIGHT, 1);
glMemoryBarrier(GL_SHADER_IMAGE_ACCESS_BARRIER_BIT);
auto end = chrono::steady_clock::now();
const auto total = chrono::duration <double, milli>(end - start).count();
cout << "time: " << total << endl;
glDeleteBuffers(1, &buffer);
}
void display()
{
glClear(GL_COLOR_BUFFER_BIT);
glClearColor(.7f, .0f, 1.f, 1.f);
texture->draw();
glFlush();
}
void init(int argc, char* argv[])
{
glutInit(&argc, argv);
glutInitContextVersion(3, 3);
glutInitContextProfile(GLUT_CORE_PROFILE);
glutInitDisplayMode(GLUT_RGBA);
glutInitWindowSize(SCREEN_WIDTH, SCREEN_HEIGHT);
glutCreateWindow("Volume Ray Casting");
glutDisplayFunc(display);
if (glewInit())
{
cerr << "Unable to initialize GLEW" << endl;
exit(EXIT_FAILURE);
}
#ifdef _DEBUG
glEnable(GL_DEBUG_OUTPUT);
glDebugMessageCallback(debugCallback, NULL);
glDebugMessageControl(GL_DONT_CARE, GL_DONT_CARE, GL_DONT_CARE, 0, NULL, GL_TRUE);
std::cout << "OpenGL Debug enabled" << std::endl;
#endif
}
void menu(int id)
{
if (id == 0)
{
//TODO:
}
glutPostRedisplay();
}
void createMenu()
{
int menuId = glutCreateMenu(menu);
glutAddMenuEntry("Open file", 0);
glutAttachMenu(GLUT_RIGHT_BUTTON);
}
int main(int argc, char* argv[])
{
init(argc, argv);
createMenu();
OPENFILENAME ofn;
ZeroMemory(&ofn, sizeof(ofn));
ofn.lStructSize = sizeof(ofn);
ofn.hwndOwner = NULL;
ofn.lpstrFile = fileName;
ofn.lpstrFile[0] = '\0';
ofn.nMaxFile = sizeof(fileName);
ofn.lpstrFilter = "All\0*.*\0Text\0*.TXT\0";
ofn.nFilterIndex = 1;
ofn.lpstrFileTitle = NULL;
ofn.nMaxFileTitle = 0;
ofn.lpstrInitialDir = NULL;
ofn.Flags = OFN_PATHMUSTEXIST | OFN_FILEMUSTEXIST;
char CWD[MAX_PATH];
_getcwd(CWD, MAX_PATH);
GetOpenFileName(&ofn);
_chdir(CWD);
Shader shader("Shaders\\vertex.glsl", "Shaders\\fragment.glsl");
texture = new Texture(SCREEN_WIDTH, SCREEN_HEIGHT, shader.program);
raycast();
glutMainLoop();
delete texture;
return 0;
}<commit_msg>Choose file at any time<commit_after>#include "Texture.h"
#include "DebugLog.h"
#include "volume.hpp"
#include <chrono>
#include <iostream>
#include <windows.h>
#include <direct.h>
#include <Commdlg.h>
using namespace std;
const int SCREEN_WIDTH = 1280;
const int SCREEN_HEIGHT = 1024;
char fileName[MAX_PATH];
Texture* texture;
void raycast()
{
Shader computeShader("Shaders\\raycast.glsl");
glUseProgram(computeShader.program);
glBindImageTexture(0, texture->textureId, 0, GL_FALSE, 0, GL_WRITE_ONLY, GL_RGBA32F);
Volume volume(fileName);
const uint64_t volumeSize = sizeof(float) * volume.info.volume();
header info = volume.info;
GLuint buffer;
glGenBuffers(1, &buffer);
glBindBuffer(GL_SHADER_STORAGE_BUFFER, buffer);
glBufferData(GL_SHADER_STORAGE_BUFFER, volumeSize * 4, volume.data, GL_DYNAMIC_COPY);
glBindBufferBase(GL_SHADER_STORAGE_BUFFER, 1, buffer);
glUniform1f(glGetUniformLocation(computeShader.program, "eyePosition"), -500.0f);
glUniform1f(glGetUniformLocation(computeShader.program, "monitorPosition"), 0.0f);
glUniform2i(glGetUniformLocation(computeShader.program, "screen"), SCREEN_WIDTH, SCREEN_HEIGHT);
glUniform3i(glGetUniformLocation(computeShader.program, "size"), static_cast<GLint>(info.x), static_cast<GLint>(info.y), static_cast<GLint>(info.z));
glUniform3f(glGetUniformLocation(computeShader.program, "d"), info.d.x, info.d.y, info.d.z);
glUniform3f(glGetUniformLocation(computeShader.program, "min"), info.min.x, info.min.y, info.min.z);
glUniform3f(glGetUniformLocation(computeShader.program, "max"), info.max.x, info.max.y, info.max.z);
auto start = chrono::steady_clock::now();
glDispatchCompute(SCREEN_WIDTH, SCREEN_HEIGHT, 1);
glMemoryBarrier(GL_SHADER_IMAGE_ACCESS_BARRIER_BIT);
auto end = chrono::steady_clock::now();
const auto total = chrono::duration <double, milli>(end - start).count();
cout << "time: " << total << endl;
glDeleteBuffers(1, &buffer);
}
void chooseAndDrawImage()
{
OPENFILENAME ofn;
ZeroMemory(&ofn, sizeof(ofn));
ofn.lStructSize = sizeof(ofn);
ofn.hwndOwner = NULL;
ofn.lpstrFile = fileName;
ofn.lpstrFile[0] = '\0';
ofn.nMaxFile = sizeof(fileName);
ofn.lpstrFilter = "All\0*.*\0Text\0*.TXT\0";
ofn.nFilterIndex = 1;
ofn.lpstrFileTitle = NULL;
ofn.nMaxFileTitle = 0;
ofn.lpstrInitialDir = NULL;
ofn.Flags = OFN_PATHMUSTEXIST | OFN_FILEMUSTEXIST;
char CWD[MAX_PATH];
_getcwd(CWD, MAX_PATH);
GetOpenFileName(&ofn);
_chdir(CWD);
raycast();
}
void display()
{
glClear(GL_COLOR_BUFFER_BIT);
glClearColor(.7f, .0f, 1.f, 1.f);
texture->draw();
glFlush();
}
void init(int argc, char* argv[])
{
glutInit(&argc, argv);
glutInitContextVersion(3, 3);
glutInitContextProfile(GLUT_CORE_PROFILE);
glutInitDisplayMode(GLUT_RGBA);
glutInitWindowSize(SCREEN_WIDTH, SCREEN_HEIGHT);
glutCreateWindow("Volume Ray Casting");
glutDisplayFunc(display);
if (glewInit())
{
cerr << "Unable to initialize GLEW" << endl;
exit(EXIT_FAILURE);
}
#ifdef _DEBUG
glEnable(GL_DEBUG_OUTPUT);
glDebugMessageCallback(debugCallback, NULL);
glDebugMessageControl(GL_DONT_CARE, GL_DONT_CARE, GL_DONT_CARE, 0, NULL, GL_TRUE);
std::cout << "OpenGL Debug enabled" << std::endl;
#endif
}
void menu(int id)
{
if (id == 0)
{
chooseAndDrawImage();
}
glutPostRedisplay();
}
void createMenu()
{
int menuId = glutCreateMenu(menu);
glutAddMenuEntry("Open file", 0);
glutAttachMenu(GLUT_RIGHT_BUTTON);
}
int main(int argc, char* argv[])
{
init(argc, argv);
createMenu();
Shader shader("Shaders\\vertex.glsl", "Shaders\\fragment.glsl");
texture = new Texture(SCREEN_WIDTH, SCREEN_HEIGHT, shader.program);
chooseAndDrawImage();
glutMainLoop();
delete texture;
return 0;
}<|endoftext|> |
<commit_before>/*
This file is part of KMail, the KDE mail client.
Copyright (c) 2000 Don Sanders <sanders@kde.org>
KMail is free software; you can redistribute it and/or modify it
under the terms of the GNU General Public License, version 2, as
published by the Free Software Foundation.
KMail 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
General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program; if not, write to the Free Software
Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
*/
#include "kmstartup.h"
#include "kmkernel.h" //control center
#include "kcursorsaver.h"
#include <klocale.h>
#include <kcomponentdata.h>
#include <kconfig.h>
#include <kstandarddirs.h>
#include <kmessagebox.h>
#include <kcrash.h>
#include <kglobal.h>
#include <kaboutdata.h>
#include <kiconloader.h>
#include <kconfiggroup.h>
#include <kde_file.h>
#include <QHostInfo>
#include <errno.h>
#include <sys/types.h>
#include <sys/param.h>
#include <signal.h>
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <qfile.h>
#undef Status // stupid X headers
extern "C" {
// Crash recovery signal handler
void kmsignalHandler(int sigId)
{
kmsetSignalHandler(SIG_DFL);
fprintf(stderr, "*** KMail got signal %d (Exiting)\n", sigId);
// try to cleanup all windows
if (kmkernel) kmkernel->dumpDeadLetters();
::exit(-1); //
}
// Crash recovery signal handler
void kmcrashHandler(int sigId)
{
kmsetSignalHandler(SIG_DFL);
fprintf(stderr, "*** KMail got signal %d (Crashing)\n", sigId);
// try to cleanup all windows
if (kmkernel) kmkernel->dumpDeadLetters();
// Return to DrKonqi.
}
//-----------------------------------------------------------------------------
void kmsetSignalHandler(void (*handler)(int))
{
KDE_signal(SIGTERM, handler);
KDE_signal(SIGHUP, handler);
KCrash::setEmergencySaveFunction(kmcrashHandler);
}
}
//-----------------------------------------------------------------------------
namespace KMail {
void checkConfigUpdates() {
static const char * const updates[] = {
"9",
"3.1-update-identities",
"3.1-use-identity-uoids",
"3.1-new-mail-notification",
"3.2-update-loop-on-goto-unread-settings",
"3.1.4-dont-use-UOID-0-for-any-identity", //krazy:exclude=spelling
"3.2-misc",
"3.2-moves",
"3.3-use-ID-for-accounts",
"3.3-update-filter-rules",
"3.3-move-identities-to-own-file",
"3.3-aegypten-kpgprc-to-kmailrc",
"3.3-aegypten-kpgprc-to-libkleopatrarc",
"3.3-aegypten-emailidentities-split-sign-encr-keys",
"3.3-misc",
"3.3b1-misc",
"3.4-misc",
"3.4a",
"3.4b",
"3.4.1",
"3.5.4",
"3.5.7-imap-flag-migration",
"4.0-misc",
"4.2"
};
static const int numUpdates = sizeof updates / sizeof *updates;
// Warning: do not remove entries in the above array, or the update-level check below will break
KSharedConfig::Ptr config = KMKernel::config();
KConfigGroup startup( config, "Startup" );
const int configUpdateLevel = startup.readEntry( "update-level", 0 );
if ( configUpdateLevel == numUpdates ) // Optimize for the common case that everything is OK
return;
for ( int i = configUpdateLevel ; i < numUpdates ; ++i ) {
config->checkUpdate( updates[i], "kmail.upd" );
}
startup.writeEntry( "update-level", numUpdates );
}
void lockOrDie() {
// Check and create a lock file to prevent concurrent access to kmail files
QString appName = KGlobal::mainComponent().componentName();
if ( appName.isEmpty() )
appName = "kmail";
QString programName;
const KAboutData *about = KGlobal::mainComponent().aboutData();
if ( about )
programName = about->programName();
if ( programName.isEmpty() )
programName = i18n("KMail");
QString lockLocation = KStandardDirs::locateLocal("data", "kmail/lock");
KConfig config(lockLocation, KConfig::SimpleConfig);
KConfigGroup group(&config, "");
int oldPid = group.readEntry("pid", -1 );
kDebug() << "oldPid=" << oldPid;
const QString oldHostName = group.readEntry("hostname");
const QString oldAppName = group.readEntry( "appName", appName );
const QString oldProgramName = group.readEntry( "programName", programName );
const QString hostName = QHostInfo::localHostName();
bool first_instance = false;
if ( oldPid == -1 ) {
first_instance = true;
} else if ( hostName == oldHostName && oldPid != getpid() ) {
// check if the lock file is stale
#ifdef Q_OS_LINUX //krazy:exclude=cpp
if ( ::access("/proc", X_OK ) == 0 ) {
// On linux with /proc we can even check that
// it's really kmail and not something else
char path_buffer[MAXPATHLEN + 1];
path_buffer[MAXPATHLEN] = 0;
const QString procPath = QString( "/proc/%1/exe" ).arg( oldPid );
const int length =
readlink( procPath.toLatin1(), path_buffer, MAXPATHLEN );
if ( length == -1 ) { // no such pid
first_instance = true;
} else {
path_buffer[length] = '\0';
const QString path = QFile::decodeName( path_buffer );
kDebug() << path;
const int pos = path.lastIndexOf( '/' );
const QString fileName = path.mid( pos + 1 );
kDebug() << "Found process" << oldPid
<< "running. It's:" << fileName;
first_instance = fileName != "kmail" && fileName != "kontact";
}
} else
#endif
{
// Otherwise we just check if the other pid is currently running.
// Not 100% correct but better safe than sorry.
if ( kill(oldPid, 0) == -1 )
first_instance = ( errno == ESRCH );
}
}
if ( !first_instance ) {
QString msg;
if ( oldHostName == hostName ) {
// this can only happen if the user is running this application on
// different displays on the same machine. All other cases will be
// taken care of by KUniqueApplication()
if ( oldAppName == appName )
msg = i18n("%1 already seems to be running on another display on "
"this machine. Running %2 more than once "
"can cause the loss of mail. You should not start %1 "
"unless you are sure that it is not already running.",
programName, programName );
// QString::arg( st ) only replaces the first occurrence of %1
// with st while QString::arg( s1, s2 ) replacess all occurrences
// of %1 with s1 and all occurrences of %2 with s2. So don't
// even think about changing the above to .arg( programName ).
else
msg = i18n("%1 seems to be running on another display on this "
"machine. Running %1 and %2 at the same "
"time can cause the loss of mail. You should not start %2 "
"unless you are sure that %1 is not running.",
oldProgramName, programName );
}
else {
if ( oldAppName == appName )
msg = i18n("%1 already seems to be running on %2. Running %1 more "
"than once can cause the loss of mail. You should not "
"start %1 on this computer unless you are sure that it is "
"not already running on %2.",
programName, oldHostName );
else
msg = i18n("%1 seems to be running on %3. Running %1 and %2 at the "
"same time can cause the loss of mail. You should not "
"start %2 on this computer unless you are sure that %1 is "
"not running on %3.",
oldProgramName, programName, oldHostName );
}
KCursorSaver idle( KBusyPtr::idle() );
if ( KMessageBox::No ==
KMessageBox::warningYesNo( 0, msg, QString(),
KGuiItem(i18nc("Start kmail even when another instance is running.", "Start %1", programName )),
KGuiItem(i18nc("Do not start another kmail instance.","Exit")) ) ) {
exit(1);
}
}
qlonglong pid = static_cast<qlonglong>( getpid() );
group.writeEntry( "pid", pid );
group.writeEntry( "hostname", hostName );
group.writeEntry( "appName", appName );
group.writeEntry( "programName", programName );
group.sync();
}
void insertLibraryCataloguesAndIcons() {
static const char * const catalogs[] = {
"libkdepim",
"libksieve",
"libkleopatra",
"libkmime",
"libmessagelist"
};
KLocale * l = KGlobal::locale();
KIconLoader * il = KIconLoader::global();
for ( unsigned int i = 0 ; i < sizeof catalogs / sizeof *catalogs ; ++i ) {
l->insertCatalog( catalogs[i] );
il->addAppDir( catalogs[i] );
}
}
void cleanup()
{
const QString lockLocation = KStandardDirs::locateLocal("data", "kmail/lock");
KConfig config(lockLocation, KConfig::SimpleConfig);
KConfigGroup group(&config, "");
group.writeEntry("pid", -1);
group.sync();
}
}
<commit_msg>We use libmessagecore too => load catalog<commit_after>/*
This file is part of KMail, the KDE mail client.
Copyright (c) 2000 Don Sanders <sanders@kde.org>
KMail is free software; you can redistribute it and/or modify it
under the terms of the GNU General Public License, version 2, as
published by the Free Software Foundation.
KMail 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
General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program; if not, write to the Free Software
Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
*/
#include "kmstartup.h"
#include "kmkernel.h" //control center
#include "kcursorsaver.h"
#include <klocale.h>
#include <kcomponentdata.h>
#include <kconfig.h>
#include <kstandarddirs.h>
#include <kmessagebox.h>
#include <kcrash.h>
#include <kglobal.h>
#include <kaboutdata.h>
#include <kiconloader.h>
#include <kconfiggroup.h>
#include <kde_file.h>
#include <QHostInfo>
#include <errno.h>
#include <sys/types.h>
#include <sys/param.h>
#include <signal.h>
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <qfile.h>
#undef Status // stupid X headers
extern "C" {
// Crash recovery signal handler
void kmsignalHandler(int sigId)
{
kmsetSignalHandler(SIG_DFL);
fprintf(stderr, "*** KMail got signal %d (Exiting)\n", sigId);
// try to cleanup all windows
if (kmkernel) kmkernel->dumpDeadLetters();
::exit(-1); //
}
// Crash recovery signal handler
void kmcrashHandler(int sigId)
{
kmsetSignalHandler(SIG_DFL);
fprintf(stderr, "*** KMail got signal %d (Crashing)\n", sigId);
// try to cleanup all windows
if (kmkernel) kmkernel->dumpDeadLetters();
// Return to DrKonqi.
}
//-----------------------------------------------------------------------------
void kmsetSignalHandler(void (*handler)(int))
{
KDE_signal(SIGTERM, handler);
KDE_signal(SIGHUP, handler);
KCrash::setEmergencySaveFunction(kmcrashHandler);
}
}
//-----------------------------------------------------------------------------
namespace KMail {
void checkConfigUpdates() {
static const char * const updates[] = {
"9",
"3.1-update-identities",
"3.1-use-identity-uoids",
"3.1-new-mail-notification",
"3.2-update-loop-on-goto-unread-settings",
"3.1.4-dont-use-UOID-0-for-any-identity", //krazy:exclude=spelling
"3.2-misc",
"3.2-moves",
"3.3-use-ID-for-accounts",
"3.3-update-filter-rules",
"3.3-move-identities-to-own-file",
"3.3-aegypten-kpgprc-to-kmailrc",
"3.3-aegypten-kpgprc-to-libkleopatrarc",
"3.3-aegypten-emailidentities-split-sign-encr-keys",
"3.3-misc",
"3.3b1-misc",
"3.4-misc",
"3.4a",
"3.4b",
"3.4.1",
"3.5.4",
"3.5.7-imap-flag-migration",
"4.0-misc",
"4.2"
};
static const int numUpdates = sizeof updates / sizeof *updates;
// Warning: do not remove entries in the above array, or the update-level check below will break
KSharedConfig::Ptr config = KMKernel::config();
KConfigGroup startup( config, "Startup" );
const int configUpdateLevel = startup.readEntry( "update-level", 0 );
if ( configUpdateLevel == numUpdates ) // Optimize for the common case that everything is OK
return;
for ( int i = configUpdateLevel ; i < numUpdates ; ++i ) {
config->checkUpdate( updates[i], "kmail.upd" );
}
startup.writeEntry( "update-level", numUpdates );
}
void lockOrDie() {
// Check and create a lock file to prevent concurrent access to kmail files
QString appName = KGlobal::mainComponent().componentName();
if ( appName.isEmpty() )
appName = "kmail";
QString programName;
const KAboutData *about = KGlobal::mainComponent().aboutData();
if ( about )
programName = about->programName();
if ( programName.isEmpty() )
programName = i18n("KMail");
QString lockLocation = KStandardDirs::locateLocal("data", "kmail/lock");
KConfig config(lockLocation, KConfig::SimpleConfig);
KConfigGroup group(&config, "");
int oldPid = group.readEntry("pid", -1 );
kDebug() << "oldPid=" << oldPid;
const QString oldHostName = group.readEntry("hostname");
const QString oldAppName = group.readEntry( "appName", appName );
const QString oldProgramName = group.readEntry( "programName", programName );
const QString hostName = QHostInfo::localHostName();
bool first_instance = false;
if ( oldPid == -1 ) {
first_instance = true;
} else if ( hostName == oldHostName && oldPid != getpid() ) {
// check if the lock file is stale
#ifdef Q_OS_LINUX //krazy:exclude=cpp
if ( ::access("/proc", X_OK ) == 0 ) {
// On linux with /proc we can even check that
// it's really kmail and not something else
char path_buffer[MAXPATHLEN + 1];
path_buffer[MAXPATHLEN] = 0;
const QString procPath = QString( "/proc/%1/exe" ).arg( oldPid );
const int length =
readlink( procPath.toLatin1(), path_buffer, MAXPATHLEN );
if ( length == -1 ) { // no such pid
first_instance = true;
} else {
path_buffer[length] = '\0';
const QString path = QFile::decodeName( path_buffer );
kDebug() << path;
const int pos = path.lastIndexOf( '/' );
const QString fileName = path.mid( pos + 1 );
kDebug() << "Found process" << oldPid
<< "running. It's:" << fileName;
first_instance = fileName != "kmail" && fileName != "kontact";
}
} else
#endif
{
// Otherwise we just check if the other pid is currently running.
// Not 100% correct but better safe than sorry.
if ( kill(oldPid, 0) == -1 )
first_instance = ( errno == ESRCH );
}
}
if ( !first_instance ) {
QString msg;
if ( oldHostName == hostName ) {
// this can only happen if the user is running this application on
// different displays on the same machine. All other cases will be
// taken care of by KUniqueApplication()
if ( oldAppName == appName )
msg = i18n("%1 already seems to be running on another display on "
"this machine. Running %2 more than once "
"can cause the loss of mail. You should not start %1 "
"unless you are sure that it is not already running.",
programName, programName );
// QString::arg( st ) only replaces the first occurrence of %1
// with st while QString::arg( s1, s2 ) replacess all occurrences
// of %1 with s1 and all occurrences of %2 with s2. So don't
// even think about changing the above to .arg( programName ).
else
msg = i18n("%1 seems to be running on another display on this "
"machine. Running %1 and %2 at the same "
"time can cause the loss of mail. You should not start %2 "
"unless you are sure that %1 is not running.",
oldProgramName, programName );
}
else {
if ( oldAppName == appName )
msg = i18n("%1 already seems to be running on %2. Running %1 more "
"than once can cause the loss of mail. You should not "
"start %1 on this computer unless you are sure that it is "
"not already running on %2.",
programName, oldHostName );
else
msg = i18n("%1 seems to be running on %3. Running %1 and %2 at the "
"same time can cause the loss of mail. You should not "
"start %2 on this computer unless you are sure that %1 is "
"not running on %3.",
oldProgramName, programName, oldHostName );
}
KCursorSaver idle( KBusyPtr::idle() );
if ( KMessageBox::No ==
KMessageBox::warningYesNo( 0, msg, QString(),
KGuiItem(i18nc("Start kmail even when another instance is running.", "Start %1", programName )),
KGuiItem(i18nc("Do not start another kmail instance.","Exit")) ) ) {
exit(1);
}
}
qlonglong pid = static_cast<qlonglong>( getpid() );
group.writeEntry( "pid", pid );
group.writeEntry( "hostname", hostName );
group.writeEntry( "appName", appName );
group.writeEntry( "programName", programName );
group.sync();
}
void insertLibraryCataloguesAndIcons() {
static const char * const catalogs[] = {
"libkdepim",
"libksieve",
"libkleopatra",
"libkmime",
"libmessagelist",
"libmessagecore"
};
KLocale * l = KGlobal::locale();
KIconLoader * il = KIconLoader::global();
for ( unsigned int i = 0 ; i < sizeof catalogs / sizeof *catalogs ; ++i ) {
l->insertCatalog( catalogs[i] );
il->addAppDir( catalogs[i] );
}
}
void cleanup()
{
const QString lockLocation = KStandardDirs::locateLocal("data", "kmail/lock");
KConfig config(lockLocation, KConfig::SimpleConfig);
KConfigGroup group(&config, "");
group.writeEntry("pid", -1);
group.sync();
}
}
<|endoftext|> |
<commit_before>/* Copyright (c) 2017, CNRS-LAAS
All rights reserved.
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are met:
* Redistributions of source code must retain the above copyright notice, this
list of conditions and the following disclaimer.
* Redistributions in binary form must reproduce the above copyright notice,
this list of conditions and the following disclaimer in the documentation
and/or other materials provided with the distribution.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE
FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */
#include <iostream>
#include "../ext/dubins.h"
#include "../core/trajectory.hpp"
#include "../core/raster.hpp"
#include "../core/uav.hpp"
#include "../vns/vns_interface.hpp"
#include "../vns/factory.hpp"
#include "../vns/neighborhoods/dubins_optimization.hpp"
#include "../core/fire_data.hpp"
#include <boost/test/included/unit_test.hpp>
namespace SAOP::Test {
using namespace boost::unit_test;
UAV uav(10., 32. * M_PI / 180, 0.1);
void test_single_point_to_observe() {
// all points ignited at time 0, except ont at time 100
DRaster ignitions(100, 100, 0, 0, 25);
ignitions.set(10, 10, 100);
DRaster elevation(100, 100, 0, 0, 25);
auto fd = make_shared<FireData>(ignitions, elevation);
// only interested in the point ignited at time 100
vector<TrajectoryConfig> confs{TrajectoryConfig(uav, 100)};
Plan p(confs, fd, TimeWindow{90, 110});
auto vns = vns::build_default();
auto res = vns->search(p, 0, 1);
BOOST_CHECK(res.final_plan);
Plan solution = res.final();
cout << "SUCCESS" << endl;
}
void test_many_points_to_observe() {
// circular firedata spread
DRaster ignitions(100, 100, 0, 0, 1);
for (size_t x = 0; x < 100; x++) {
for (size_t y = 0; y < 100; y++) {
ignitions.set(x, y, sqrt(pow((double) x - 50, 2) + pow((double) y - 50, 2)));
}
}
DRaster elevation(100, 100, 0, 0, 1);
auto fd = make_shared<FireData>(ignitions, elevation);
vector<TrajectoryConfig> confs{TrajectoryConfig(uav, 10)};
Plan p(confs, fd, TimeWindow{0, 110});
auto vns = vns::build_default();
auto res = vns->search(p, 0, 1);
BOOST_CHECK(res.final_plan);
Plan solution = res.final();
cout << "SUCCESS" << endl;
}
void test_many_points_to_observe_with_start_end_positions() {
Waypoint3d start(5, 5, 0, 0);
Waypoint3d end(11, 11, 0, 0);
// circular firedata spread
DRaster ignitions(100, 100, 0, 0, 1);
for (size_t x = 0; x < 100; x++) {
for (size_t y = 0; y < 100; y++) {
ignitions.set(x, y, sqrt(pow((double) x - 50, 2) + pow((double) y - 50, 2)));
}
}
DRaster elevation(100, 100, 0, 0, 1);
auto fd = make_shared<FireData>(ignitions, elevation);
vector<TrajectoryConfig> confs{TrajectoryConfig(
uav,
start,
end,
10)};
Plan p(confs, fd, TimeWindow{0, 110});
auto vns = vns::build_default();
auto res = vns->search(p, 0, 1);
BOOST_CHECK(res.final_plan);
Plan solution = res.final();
auto& traj = solution.core[0];
// ASSERT(traj[0] == start);
// ASSERT(traj[traj.size()-1] == end);
BOOST_CHECK(traj.first_modifiable_id() == 1);
BOOST_CHECK(traj.last_modifiable_id() == traj.size() - 2);
cout << "SUCCESS" << endl;
}
void test_segment_rotation() {
for (size_t i = 0; i < 100; i++) {
Waypoint wp(drand(-100000, 10000), drand(-100000, 100000), drand(-10 * M_PI, 10 * M_PI));
Segment seg(wp, drand(0, 1000));
Segment seg_rotated = uav.rotate_on_visibility_center(seg, drand(-10 * M_PI, 10 * M_PI));
Segment seg_back = uav.rotate_on_visibility_center(seg_rotated, wp.dir);
BOOST_CHECK(seg == seg_back);
}
}
void test_projection_on_firefront() {
// uniform propagation along the y axis
{
DRaster ignitions(100, 100, 0, 0, 1);
for (size_t x = 0; x < 100; x++) {
for (size_t y = 0; y < 100; y++) {
ignitions.set(x, y, y);
}
}
DRaster elevation(100, 100, 0, 0, 1);
FireData fd(ignitions, elevation);
auto res = fd.project_on_fire_front(Cell{1, 1}, 50.5);
BOOST_CHECK(res && res->y == 50);
auto res_back = fd.project_on_fire_front(Cell{79, 1}, 50.5);
BOOST_CHECK(res_back && res_back->y == 50);
}
// uniform propagation along the x axis
{
DRaster ignitions(10, 10, 0, 0, 1);
for (size_t x = 0; x < 10; x++) {
for (size_t y = 0; y < 10; y++) {
ignitions.set(x, y, x);
}
}
DRaster elevation(10, 10, 0, 0, 1);
FireData fd(ignitions, elevation);
auto res = fd.project_on_fire_front(Cell{1, 1}, 5.5);
BOOST_CHECK(res && res->x == 5);
auto res_back = fd.project_on_fire_front(Cell{7, 1}, 5.5);
BOOST_CHECK(res_back && res_back->x == 5);
}
// circular propagation center on (50,50)
{
auto dist = [](size_t x, size_t y) { return sqrt(pow((double) x - 50., 2.) + pow((double) y - 50., 2.)); };
DRaster ignitions(100, 100, 0, 0, 1);
for (size_t x = 0; x < 100; x++) {
for (size_t y = 0; y < 100; y++) {
ignitions.set(x, y, dist(x, y));
}
}
DRaster elevation(100, 100, 0, 0, 1);
FireData fd(ignitions, elevation);
for (size_t i = 0; i < 100; i++) {
const size_t x = rand(0, 100);
const size_t y = rand(0, 100);
auto res = fd.project_on_fire_front(Cell{x, y}, 25);
BOOST_CHECK(res && abs(dist(res->x, res->y) - 25) < 1.5);
}
}
}
void test_trajectory_as_waypoints() {
Trajectory traj((TrajectoryConfig(uav)));
traj.sampled(2);
}
void test_trajectory_slice() {
TimeWindow tw1 = TimeWindow(10, 300);
TrajectoryConfig config1 = TrajectoryConfig(uav, tw1.start, tw1.end);
Trajectory traj = Trajectory(config1);
traj.append_segment(Segment3d(Waypoint3d(0, 0, 0, 0)));
traj.append_segment(Segment3d(Waypoint3d(100, 100, 0, 0), 50));
traj.append_segment(Segment3d(Waypoint3d(300, 200, 0, 0), 50));
traj.append_segment(Segment3d(Waypoint3d(500, 500, 0, 0)));
Trajectory sliced1 = traj.slice(TimeWindow(tw1.start + 1, tw1.end - 1));
Trajectory sliced2 = traj.slice(TimeWindow(tw1.start + 1, 85));
BOOST_CHECK(sliced1.size() == traj.size() - 1);
BOOST_CHECK(sliced2.size() == traj.size() - 2);
BOOST_CHECK_CLOSE(traj.start_time(1), sliced1.start_time(0), 0.1);
BOOST_CHECK_CLOSE(traj.start_time(1), sliced2.start_time(0), 0.1);
BOOST_CHECK_CLOSE(traj.start_time(3), sliced1.start_time(2), 0.1);
BOOST_CHECK_CLOSE(traj.start_time(2), sliced2.start_time(1), 0.1);
}
void test_time_window_order() {
double s = 10;
double e = 25;
TimeWindow tw1 = TimeWindow(s, e);
TimeWindow tw2 = TimeWindow(e, s);
BOOST_CHECK(tw1.start == s);
BOOST_CHECK(tw1.end == e);
BOOST_CHECK(tw1.start == tw2.start);
BOOST_CHECK(tw1.end == tw1.end);
}
void test_time_window() {
double s = 10;
double e = 25;
TimeWindow tw1 = TimeWindow(s, e);
TimeWindow tw2 = TimeWindow(e, s);
TimeWindow tw3 = TimeWindow(s - 1, e);
TimeWindow tw4 = TimeWindow(s, e + 1);
BOOST_CHECK(tw1 == tw2);
BOOST_CHECK(tw1 != tw3);
BOOST_CHECK(tw3.contains(tw1));
BOOST_CHECK(tw3.contains(tw1.center()));
BOOST_CHECK(tw3.intersects(tw4));
BOOST_CHECK(tw3.union_with(tw1) == tw3);
BOOST_CHECK(tw4.intersection_with(tw3) == tw1);
auto empty_intersect = TimeWindow(s - 1, s).intersection_with(TimeWindow(e, e + 1));
BOOST_CHECK(empty_intersect.is_empty());
}
test_suite* position_manipulation_test_suite() {
test_suite* ts2 = BOOST_TEST_SUITE("position_manipulation_tests");
srand(time(0));
ts2->add(BOOST_TEST_CASE(&test_trajectory_slice));
ts2->add(BOOST_TEST_CASE(&test_time_window_order));
ts2->add(BOOST_TEST_CASE(&test_time_window));
ts2->add(BOOST_TEST_CASE(&test_trajectory_as_waypoints));
ts2->add(BOOST_TEST_CASE(&test_segment_rotation));
ts2->add(BOOST_TEST_CASE(&test_single_point_to_observe));
ts2->add(BOOST_TEST_CASE(&test_many_points_to_observe));
ts2->add(BOOST_TEST_CASE(&test_many_points_to_observe_with_start_end_positions));
ts2->add(BOOST_TEST_CASE(&test_projection_on_firefront));
return ts2;
}
}<commit_msg>Fix wrong namespace in tests<commit_after>/* Copyright (c) 2017, CNRS-LAAS
All rights reserved.
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are met:
* Redistributions of source code must retain the above copyright notice, this
list of conditions and the following disclaimer.
* Redistributions in binary form must reproduce the above copyright notice,
this list of conditions and the following disclaimer in the documentation
and/or other materials provided with the distribution.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE
FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */
#include <iostream>
#include "../ext/dubins.h"
#include "../core/trajectory.hpp"
#include "../core/raster.hpp"
#include "../core/uav.hpp"
#include "../vns/vns_interface.hpp"
#include "../vns/factory.hpp"
#include "../vns/neighborhoods/dubins_optimization.hpp"
#include "../core/fire_data.hpp"
#include <boost/test/included/unit_test.hpp>
namespace SAOP::Test {
using namespace boost::unit_test;
UAV uav(10., 32. * M_PI / 180, 0.1);
void test_single_point_to_observe() {
// all points ignited at time 0, except ont at time 100
DRaster ignitions(100, 100, 0, 0, 25);
ignitions.set(10, 10, 100);
DRaster elevation(100, 100, 0, 0, 25);
auto fd = make_shared<FireData>(ignitions, elevation);
// only interested in the point ignited at time 100
vector<TrajectoryConfig> confs{TrajectoryConfig(uav, 100)};
Plan p(confs, fd, TimeWindow{90, 110});
auto vns = SAOP::build_default();
auto res = vns->search(p, 0, 1);
BOOST_CHECK(res.final_plan);
Plan solution = res.final();
cout << "SUCCESS" << endl;
}
void test_many_points_to_observe() {
// circular firedata spread
DRaster ignitions(100, 100, 0, 0, 1);
for (size_t x = 0; x < 100; x++) {
for (size_t y = 0; y < 100; y++) {
ignitions.set(x, y, sqrt(pow((double) x - 50, 2) + pow((double) y - 50, 2)));
}
}
DRaster elevation(100, 100, 0, 0, 1);
auto fd = make_shared<FireData>(ignitions, elevation);
vector<TrajectoryConfig> confs{TrajectoryConfig(uav, 10)};
Plan p(confs, fd, TimeWindow{0, 110});
auto vns = SAOP::build_default();
auto res = vns->search(p, 0, 1);
BOOST_CHECK(res.final_plan);
Plan solution = res.final();
cout << "SUCCESS" << endl;
}
void test_many_points_to_observe_with_start_end_positions() {
Waypoint3d start(5, 5, 0, 0);
Waypoint3d end(11, 11, 0, 0);
// circular firedata spread
DRaster ignitions(100, 100, 0, 0, 1);
for (size_t x = 0; x < 100; x++) {
for (size_t y = 0; y < 100; y++) {
ignitions.set(x, y, sqrt(pow((double) x - 50, 2) + pow((double) y - 50, 2)));
}
}
DRaster elevation(100, 100, 0, 0, 1);
auto fd = make_shared<FireData>(ignitions, elevation);
vector<TrajectoryConfig> confs{TrajectoryConfig(
uav,
start,
end,
10)};
Plan p(confs, fd, TimeWindow{0, 110});
auto vns = SAOP::build_default();
auto res = vns->search(p, 0, 1);
BOOST_CHECK(res.final_plan);
Plan solution = res.final();
auto& traj = solution.core[0];
// ASSERT(traj[0] == start);
// ASSERT(traj[traj.size()-1] == end);
BOOST_CHECK(traj.first_modifiable_id() == 1);
BOOST_CHECK(traj.last_modifiable_id() == traj.size() - 2);
cout << "SUCCESS" << endl;
}
void test_segment_rotation() {
for (size_t i = 0; i < 100; i++) {
Waypoint wp(drand(-100000, 10000), drand(-100000, 100000), drand(-10 * M_PI, 10 * M_PI));
Segment seg(wp, drand(0, 1000));
Segment seg_rotated = uav.rotate_on_visibility_center(seg, drand(-10 * M_PI, 10 * M_PI));
Segment seg_back = uav.rotate_on_visibility_center(seg_rotated, wp.dir);
BOOST_CHECK(seg == seg_back);
}
}
void test_projection_on_firefront() {
// uniform propagation along the y axis
{
DRaster ignitions(100, 100, 0, 0, 1);
for (size_t x = 0; x < 100; x++) {
for (size_t y = 0; y < 100; y++) {
ignitions.set(x, y, y);
}
}
DRaster elevation(100, 100, 0, 0, 1);
FireData fd(ignitions, elevation);
auto res = fd.project_on_fire_front(Cell{1, 1}, 50.5);
BOOST_CHECK(res && res->y == 50);
auto res_back = fd.project_on_fire_front(Cell{79, 1}, 50.5);
BOOST_CHECK(res_back && res_back->y == 50);
}
// uniform propagation along the x axis
{
DRaster ignitions(10, 10, 0, 0, 1);
for (size_t x = 0; x < 10; x++) {
for (size_t y = 0; y < 10; y++) {
ignitions.set(x, y, x);
}
}
DRaster elevation(10, 10, 0, 0, 1);
FireData fd(ignitions, elevation);
auto res = fd.project_on_fire_front(Cell{1, 1}, 5.5);
BOOST_CHECK(res && res->x == 5);
auto res_back = fd.project_on_fire_front(Cell{7, 1}, 5.5);
BOOST_CHECK(res_back && res_back->x == 5);
}
// circular propagation center on (50,50)
{
auto dist = [](size_t x, size_t y) { return sqrt(pow((double) x - 50., 2.) + pow((double) y - 50., 2.)); };
DRaster ignitions(100, 100, 0, 0, 1);
for (size_t x = 0; x < 100; x++) {
for (size_t y = 0; y < 100; y++) {
ignitions.set(x, y, dist(x, y));
}
}
DRaster elevation(100, 100, 0, 0, 1);
FireData fd(ignitions, elevation);
for (size_t i = 0; i < 100; i++) {
const size_t x = rand(0, 100);
const size_t y = rand(0, 100);
auto res = fd.project_on_fire_front(Cell{x, y}, 25);
BOOST_CHECK(res && abs(dist(res->x, res->y) - 25) < 1.5);
}
}
}
void test_trajectory_as_waypoints() {
Trajectory traj((TrajectoryConfig(uav)));
traj.sampled(2);
}
void test_trajectory_slice() {
TimeWindow tw1 = TimeWindow(10, 300);
TrajectoryConfig config1 = TrajectoryConfig(uav, tw1.start, tw1.end);
Trajectory traj = Trajectory(config1);
traj.append_segment(Segment3d(Waypoint3d(0, 0, 0, 0)));
traj.append_segment(Segment3d(Waypoint3d(100, 100, 0, 0), 50));
traj.append_segment(Segment3d(Waypoint3d(300, 200, 0, 0), 50));
traj.append_segment(Segment3d(Waypoint3d(500, 500, 0, 0)));
Trajectory sliced1 = traj.slice(TimeWindow(tw1.start + 1, tw1.end - 1));
Trajectory sliced2 = traj.slice(TimeWindow(tw1.start + 1, 85));
BOOST_CHECK(sliced1.size() == traj.size() - 1);
BOOST_CHECK(sliced2.size() == traj.size() - 2);
BOOST_CHECK_CLOSE(traj.start_time(1), sliced1.start_time(0), 0.1);
BOOST_CHECK_CLOSE(traj.start_time(1), sliced2.start_time(0), 0.1);
BOOST_CHECK_CLOSE(traj.start_time(3), sliced1.start_time(2), 0.1);
BOOST_CHECK_CLOSE(traj.start_time(2), sliced2.start_time(1), 0.1);
}
void test_time_window_order() {
double s = 10;
double e = 25;
TimeWindow tw1 = TimeWindow(s, e);
TimeWindow tw2 = TimeWindow(e, s);
BOOST_CHECK(tw1.start == s);
BOOST_CHECK(tw1.end == e);
BOOST_CHECK(tw1.start == tw2.start);
BOOST_CHECK(tw1.end == tw1.end);
}
void test_time_window() {
double s = 10;
double e = 25;
TimeWindow tw1 = TimeWindow(s, e);
TimeWindow tw2 = TimeWindow(e, s);
TimeWindow tw3 = TimeWindow(s - 1, e);
TimeWindow tw4 = TimeWindow(s, e + 1);
BOOST_CHECK(tw1 == tw2);
BOOST_CHECK(tw1 != tw3);
BOOST_CHECK(tw3.contains(tw1));
BOOST_CHECK(tw3.contains(tw1.center()));
BOOST_CHECK(tw3.intersects(tw4));
BOOST_CHECK(tw3.union_with(tw1) == tw3);
BOOST_CHECK(tw4.intersection_with(tw3) == tw1);
auto empty_intersect = TimeWindow(s - 1, s).intersection_with(TimeWindow(e, e + 1));
BOOST_CHECK(empty_intersect.is_empty());
}
test_suite* position_manipulation_test_suite() {
test_suite* ts2 = BOOST_TEST_SUITE("position_manipulation_tests");
srand(time(0));
ts2->add(BOOST_TEST_CASE(&test_trajectory_slice));
ts2->add(BOOST_TEST_CASE(&test_time_window_order));
ts2->add(BOOST_TEST_CASE(&test_time_window));
ts2->add(BOOST_TEST_CASE(&test_trajectory_as_waypoints));
ts2->add(BOOST_TEST_CASE(&test_segment_rotation));
ts2->add(BOOST_TEST_CASE(&test_single_point_to_observe));
ts2->add(BOOST_TEST_CASE(&test_many_points_to_observe));
ts2->add(BOOST_TEST_CASE(&test_many_points_to_observe_with_start_end_positions));
ts2->add(BOOST_TEST_CASE(&test_projection_on_firefront));
return ts2;
}
}<|endoftext|> |
<commit_before>/*
* Copyright (C) 2013 Google Inc. All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are
* met:
*
* * Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* * Neither the name of Google Inc. nor the names of its
* contributors may be used to endorse or promote products derived from
* this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
* "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
* LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
* A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
* OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
* SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
* LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
* DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
* THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
* OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
#include "config.h"
#include "core/events/EventPath.h"
#include "EventNames.h"
#include "RuntimeEnabledFeatures.h"
#include "SVGNames.h"
#include "core/dom/FullscreenElementStack.h"
#include "core/dom/Touch.h"
#include "core/dom/TouchList.h"
#include "core/dom/shadow/InsertionPoint.h"
#include "core/dom/shadow/ShadowRoot.h"
#include "core/events/FocusEvent.h"
#include "core/events/MouseEvent.h"
#include "core/events/TouchEvent.h"
#include "core/events/TouchEventContext.h"
#include "core/svg/SVGElementInstance.h"
#include "core/svg/SVGUseElement.h"
namespace WebCore {
EventTarget* EventPath::eventTargetRespectingTargetRules(Node* referenceNode)
{
ASSERT(referenceNode);
if (referenceNode->isPseudoElement())
return referenceNode->parentNode();
if (!referenceNode->isSVGElement() || !referenceNode->isInShadowTree())
return referenceNode;
// Spec: The event handling for the non-exposed tree works as if the referenced element had been textually included
// as a deeply cloned child of the 'use' element, except that events are dispatched to the SVGElementInstance objects.
Node& rootNode = referenceNode->treeScope().rootNode();
Element* shadowHostElement = rootNode.isShadowRoot() ? toShadowRoot(rootNode).host() : 0;
// At this time, SVG nodes are not supported in non-<use> shadow trees.
if (!isSVGUseElement(shadowHostElement))
return referenceNode;
SVGUseElement& useElement = toSVGUseElement(*shadowHostElement);
if (SVGElementInstance* instance = useElement.instanceForShadowTreeElement(referenceNode))
return instance;
return referenceNode;
}
static inline bool inTheSameScope(ShadowRoot* shadowRoot, EventTarget* target)
{
return target->toNode() && target->toNode()->treeScope().rootNode() == shadowRoot;
}
static inline EventDispatchBehavior determineDispatchBehavior(Event* event, ShadowRoot* shadowRoot, EventTarget* target)
{
// WebKit never allowed selectstart event to cross the the shadow DOM boundary.
// Changing this breaks existing sites.
// See https://bugs.webkit.org/show_bug.cgi?id=52195 for details.
const AtomicString eventType = event->type();
if (inTheSameScope(shadowRoot, target)
&& (eventType == EventTypeNames::abort
|| eventType == EventTypeNames::change
|| eventType == EventTypeNames::error
|| eventType == EventTypeNames::load
|| eventType == EventTypeNames::reset
|| eventType == EventTypeNames::resize
|| eventType == EventTypeNames::scroll
|| eventType == EventTypeNames::select
|| eventType == EventTypeNames::selectstart))
return StayInsideShadowDOM;
return RetargetEvent;
}
EventPath::EventPath(Event* event)
: m_node(0)
, m_event(event)
{
}
EventPath::EventPath(Node* node)
: m_node(node)
, m_event(nullptr)
{
resetWith(node);
}
void EventPath::resetWith(Node* node)
{
ASSERT(node);
m_node = node;
m_nodeEventContexts.clear();
m_treeScopeEventContexts.clear();
calculatePath();
calculateAdjustedTargets();
if (!node->isSVGElement())
calculateTreeScopePrePostOrderNumbers();
}
void EventPath::addNodeEventContext(Node* node)
{
m_nodeEventContexts.append(NodeEventContext(node, eventTargetRespectingTargetRules(node)));
}
void EventPath::calculatePath()
{
ASSERT(m_node);
ASSERT(m_nodeEventContexts.isEmpty());
m_node->document().updateDistributionForNodeIfNeeded(const_cast<Node*>(m_node));
Node* current = m_node;
addNodeEventContext(current);
if (!m_node->inDocument())
return;
while (current) {
if (current->isShadowRoot() && m_event && determineDispatchBehavior(m_event, toShadowRoot(current), m_node) == StayInsideShadowDOM)
break;
Vector<InsertionPoint*, 8> insertionPoints;
collectDestinationInsertionPoints(*current, insertionPoints);
if (!insertionPoints.isEmpty()) {
for (size_t i = 0; i < insertionPoints.size(); ++i) {
InsertionPoint* insertionPoint = insertionPoints[i];
if (insertionPoint->isShadowInsertionPoint()) {
ShadowRoot* containingShadowRoot = insertionPoint->containingShadowRoot();
ASSERT(containingShadowRoot);
if (!containingShadowRoot->isOldest())
addNodeEventContext(containingShadowRoot->olderShadowRoot());
}
addNodeEventContext(insertionPoint);
}
current = insertionPoints.last();
continue;
}
if (current->isShadowRoot()) {
current = current->shadowHost();
addNodeEventContext(current);
} else {
current = current->parentNode();
if (current)
addNodeEventContext(current);
}
}
}
void EventPath::calculateTreeScopePrePostOrderNumbers()
{
// Precondition:
// - TreeScopes in m_treeScopeEventContexts must be *connected* in the same tree of trees.
// - The root tree must be included.
HashMap<const TreeScope*, TreeScopeEventContext*> treeScopeEventContextMap;
for (size_t i = 0; i < m_treeScopeEventContexts.size(); ++i)
treeScopeEventContextMap.add(&m_treeScopeEventContexts[i]->treeScope(), m_treeScopeEventContexts[i].get());
TreeScopeEventContext* rootTree = 0;
for (size_t i = 0; i < m_treeScopeEventContexts.size(); ++i) {
TreeScopeEventContext* treeScopeEventContext = m_treeScopeEventContexts[i].get();
// Use olderShadowRootOrParentTreeScope here for parent-child relationships.
// See the definition of trees of trees in the Shado DOM spec: http://w3c.github.io/webcomponents/spec/shadow/
TreeScope* parent = treeScopeEventContext->treeScope().olderShadowRootOrParentTreeScope();
if (!parent) {
ASSERT(!rootTree);
rootTree = treeScopeEventContext;
continue;
}
ASSERT(treeScopeEventContextMap.find(parent) != treeScopeEventContextMap.end());
treeScopeEventContextMap.find(parent)->value->addChild(*treeScopeEventContext);
}
ASSERT(rootTree);
rootTree->calculatePrePostOrderNumber(0);
}
TreeScopeEventContext* EventPath::ensureTreeScopeEventContext(Node* currentTarget, TreeScope* treeScope, TreeScopeEventContextMap& treeScopeEventContextMap)
{
if (!treeScope)
return 0;
TreeScopeEventContext* treeScopeEventContext;
bool isNewEntry;
{
TreeScopeEventContextMap::AddResult addResult = treeScopeEventContextMap.add(treeScope, TreeScopeEventContext::create(*treeScope));
treeScopeEventContext = addResult.storedValue->value.get();
isNewEntry = addResult.isNewEntry;
}
if (isNewEntry) {
TreeScopeEventContext* parentTreeScopeEventContext = ensureTreeScopeEventContext(0, treeScope->olderShadowRootOrParentTreeScope(), treeScopeEventContextMap);
if (parentTreeScopeEventContext && parentTreeScopeEventContext->target()) {
treeScopeEventContext->setTarget(parentTreeScopeEventContext->target());
} else if (currentTarget) {
treeScopeEventContext->setTarget(eventTargetRespectingTargetRules(currentTarget));
}
} else if (!treeScopeEventContext->target() && currentTarget) {
treeScopeEventContext->setTarget(eventTargetRespectingTargetRules(currentTarget));
}
return treeScopeEventContext;
}
void EventPath::calculateAdjustedTargets()
{
const TreeScope* lastTreeScope = 0;
bool isSVGElement = at(0).node()->isSVGElement();
TreeScopeEventContextMap treeScopeEventContextMap;
TreeScopeEventContext* lastTreeScopeEventContext = 0;
for (size_t i = 0; i < size(); ++i) {
Node* currentNode = at(i).node();
TreeScope& currentTreeScope = currentNode->treeScope();
if (lastTreeScope != ¤tTreeScope) {
if (!isSVGElement) {
lastTreeScopeEventContext = ensureTreeScopeEventContext(currentNode, ¤tTreeScope, treeScopeEventContextMap);
} else {
TreeScopeEventContextMap::AddResult addResult = treeScopeEventContextMap.add(¤tTreeScope, TreeScopeEventContext::create(currentTreeScope));
lastTreeScopeEventContext = addResult.storedValue->value.get();
if (addResult.isNewEntry) {
// Don't adjust an event target for SVG.
lastTreeScopeEventContext->setTarget(eventTargetRespectingTargetRules(at(0).node()));
}
}
}
ASSERT(lastTreeScopeEventContext);
at(i).setTreeScopeEventContext(lastTreeScopeEventContext);
lastTreeScope = ¤tTreeScope;
}
m_treeScopeEventContexts.appendRange(treeScopeEventContextMap.values().begin(), treeScopeEventContextMap.values().end());
}
void EventPath::buildRelatedNodeMap(const Node* relatedNode, RelatedTargetMap& relatedTargetMap)
{
EventPath relatedTargetEventPath(const_cast<Node*>(relatedNode));
for (size_t i = 0; i < relatedTargetEventPath.m_treeScopeEventContexts.size(); ++i) {
TreeScopeEventContext* treeScopeEventContext = relatedTargetEventPath.m_treeScopeEventContexts[i].get();
relatedTargetMap.add(&treeScopeEventContext->treeScope(), treeScopeEventContext->target());
}
}
EventTarget* EventPath::findRelatedNode(TreeScope* scope, RelatedTargetMap& relatedTargetMap)
{
Vector<TreeScope*, 32> parentTreeScopes;
EventTarget* relatedNode = 0;
while (scope) {
parentTreeScopes.append(scope);
RelatedTargetMap::const_iterator iter = relatedTargetMap.find(scope);
if (iter != relatedTargetMap.end() && iter->value) {
relatedNode = iter->value;
break;
}
scope = scope->olderShadowRootOrParentTreeScope();
}
ASSERT(relatedNode);
for (Vector<TreeScope*, 32>::iterator iter = parentTreeScopes.begin(); iter < parentTreeScopes.end(); ++iter)
relatedTargetMap.add(*iter, relatedNode);
return relatedNode;
}
void EventPath::adjustForRelatedTarget(Node* target, EventTarget* relatedTarget)
{
if (!target)
return;
if (!relatedTarget)
return;
Node* relatedNode = relatedTarget->toNode();
if (!relatedNode)
return;
if (target->document() != relatedNode->document())
return;
if (!target->inDocument() || !relatedNode->inDocument())
return;
RelatedTargetMap relatedNodeMap;
buildRelatedNodeMap(relatedNode, relatedNodeMap);
for (size_t i = 0; i < m_treeScopeEventContexts.size(); ++i) {
TreeScopeEventContext* treeScopeEventContext = m_treeScopeEventContexts[i].get();
EventTarget* adjustedRelatedTarget = findRelatedNode(&treeScopeEventContext->treeScope(), relatedNodeMap);
ASSERT(adjustedRelatedTarget);
treeScopeEventContext->setRelatedTarget(adjustedRelatedTarget);
}
shrinkIfNeeded(target, relatedTarget);
}
void EventPath::shrinkIfNeeded(const Node* target, const EventTarget* relatedTarget)
{
// Synthetic mouse events can have a relatedTarget which is identical to the target.
bool targetIsIdenticalToToRelatedTarget = (target == relatedTarget);
for (size_t i = 0; i < size(); ++i) {
if (targetIsIdenticalToToRelatedTarget) {
if (target->treeScope().rootNode() == at(i).node()) {
shrink(i + 1);
break;
}
} else if (at(i).target() == at(i).relatedTarget()) {
// Event dispatching should be stopped here.
shrink(i);
break;
}
}
}
void EventPath::adjustForTouchEvent(Node* node, TouchEvent& touchEvent)
{
WillBeHeapVector<RawPtrWillBeMember<TouchList> > adjustedTouches;
WillBeHeapVector<RawPtrWillBeMember<TouchList> > adjustedTargetTouches;
WillBeHeapVector<RawPtrWillBeMember<TouchList> > adjustedChangedTouches;
Vector<TreeScope*> treeScopes;
for (size_t i = 0; i < m_treeScopeEventContexts.size(); ++i) {
TouchEventContext* touchEventContext = m_treeScopeEventContexts[i]->ensureTouchEventContext();
adjustedTouches.append(&touchEventContext->touches());
adjustedTargetTouches.append(&touchEventContext->targetTouches());
adjustedChangedTouches.append(&touchEventContext->changedTouches());
treeScopes.append(&m_treeScopeEventContexts[i]->treeScope());
}
adjustTouchList(node, touchEvent.touches(), adjustedTouches, treeScopes);
adjustTouchList(node, touchEvent.targetTouches(), adjustedTargetTouches, treeScopes);
adjustTouchList(node, touchEvent.changedTouches(), adjustedChangedTouches, treeScopes);
#ifndef NDEBUG
for (size_t i = 0; i < m_treeScopeEventContexts.size(); ++i) {
TreeScope& treeScope = m_treeScopeEventContexts[i]->treeScope();
TouchEventContext* touchEventContext = m_treeScopeEventContexts[i]->touchEventContext();
checkReachability(treeScope, touchEventContext->touches());
checkReachability(treeScope, touchEventContext->targetTouches());
checkReachability(treeScope, touchEventContext->changedTouches());
}
#endif
}
void EventPath::adjustTouchList(const Node* node, const TouchList* touchList, WillBeHeapVector<RawPtrWillBeMember<TouchList> > adjustedTouchList, const Vector<TreeScope*>& treeScopes)
{
if (!touchList)
return;
for (size_t i = 0; i < touchList->length(); ++i) {
const Touch& touch = *touchList->item(i);
RelatedTargetMap relatedNodeMap;
buildRelatedNodeMap(touch.target()->toNode(), relatedNodeMap);
for (size_t j = 0; j < treeScopes.size(); ++j) {
adjustedTouchList[j]->append(touch.cloneWithNewTarget(findRelatedNode(treeScopes[j], relatedNodeMap)));
}
}
}
#ifndef NDEBUG
void EventPath::checkReachability(TreeScope& treeScope, TouchList& touchList)
{
for (size_t i = 0; i < touchList.length(); ++i)
ASSERT(touchList.item(i)->target()->toNode()->treeScope().isInclusiveOlderSiblingShadowRootOrAncestorTreeScopeOf(treeScope));
}
#endif
void EventPath::trace(Visitor* visitor)
{
visitor->trace(m_event);
}
} // namespace
<commit_msg>Avoid unnecessary allocation in EventPath::ensureTreeScopeEventContext.<commit_after>/*
* Copyright (C) 2013 Google Inc. All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are
* met:
*
* * Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* * Neither the name of Google Inc. nor the names of its
* contributors may be used to endorse or promote products derived from
* this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
* "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
* LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
* A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
* OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
* SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
* LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
* DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
* THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
* OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
#include "config.h"
#include "core/events/EventPath.h"
#include "EventNames.h"
#include "RuntimeEnabledFeatures.h"
#include "SVGNames.h"
#include "core/dom/FullscreenElementStack.h"
#include "core/dom/Touch.h"
#include "core/dom/TouchList.h"
#include "core/dom/shadow/InsertionPoint.h"
#include "core/dom/shadow/ShadowRoot.h"
#include "core/events/FocusEvent.h"
#include "core/events/MouseEvent.h"
#include "core/events/TouchEvent.h"
#include "core/events/TouchEventContext.h"
#include "core/svg/SVGElementInstance.h"
#include "core/svg/SVGUseElement.h"
namespace WebCore {
EventTarget* EventPath::eventTargetRespectingTargetRules(Node* referenceNode)
{
ASSERT(referenceNode);
if (referenceNode->isPseudoElement())
return referenceNode->parentNode();
if (!referenceNode->isSVGElement() || !referenceNode->isInShadowTree())
return referenceNode;
// Spec: The event handling for the non-exposed tree works as if the referenced element had been textually included
// as a deeply cloned child of the 'use' element, except that events are dispatched to the SVGElementInstance objects.
Node& rootNode = referenceNode->treeScope().rootNode();
Element* shadowHostElement = rootNode.isShadowRoot() ? toShadowRoot(rootNode).host() : 0;
// At this time, SVG nodes are not supported in non-<use> shadow trees.
if (!isSVGUseElement(shadowHostElement))
return referenceNode;
SVGUseElement& useElement = toSVGUseElement(*shadowHostElement);
if (SVGElementInstance* instance = useElement.instanceForShadowTreeElement(referenceNode))
return instance;
return referenceNode;
}
static inline bool inTheSameScope(ShadowRoot* shadowRoot, EventTarget* target)
{
return target->toNode() && target->toNode()->treeScope().rootNode() == shadowRoot;
}
static inline EventDispatchBehavior determineDispatchBehavior(Event* event, ShadowRoot* shadowRoot, EventTarget* target)
{
// WebKit never allowed selectstart event to cross the the shadow DOM boundary.
// Changing this breaks existing sites.
// See https://bugs.webkit.org/show_bug.cgi?id=52195 for details.
const AtomicString eventType = event->type();
if (inTheSameScope(shadowRoot, target)
&& (eventType == EventTypeNames::abort
|| eventType == EventTypeNames::change
|| eventType == EventTypeNames::error
|| eventType == EventTypeNames::load
|| eventType == EventTypeNames::reset
|| eventType == EventTypeNames::resize
|| eventType == EventTypeNames::scroll
|| eventType == EventTypeNames::select
|| eventType == EventTypeNames::selectstart))
return StayInsideShadowDOM;
return RetargetEvent;
}
EventPath::EventPath(Event* event)
: m_node(0)
, m_event(event)
{
}
EventPath::EventPath(Node* node)
: m_node(node)
, m_event(nullptr)
{
resetWith(node);
}
void EventPath::resetWith(Node* node)
{
ASSERT(node);
m_node = node;
m_nodeEventContexts.clear();
m_treeScopeEventContexts.clear();
calculatePath();
calculateAdjustedTargets();
if (!node->isSVGElement())
calculateTreeScopePrePostOrderNumbers();
}
void EventPath::addNodeEventContext(Node* node)
{
m_nodeEventContexts.append(NodeEventContext(node, eventTargetRespectingTargetRules(node)));
}
void EventPath::calculatePath()
{
ASSERT(m_node);
ASSERT(m_nodeEventContexts.isEmpty());
m_node->document().updateDistributionForNodeIfNeeded(const_cast<Node*>(m_node));
Node* current = m_node;
addNodeEventContext(current);
if (!m_node->inDocument())
return;
while (current) {
if (current->isShadowRoot() && m_event && determineDispatchBehavior(m_event, toShadowRoot(current), m_node) == StayInsideShadowDOM)
break;
Vector<InsertionPoint*, 8> insertionPoints;
collectDestinationInsertionPoints(*current, insertionPoints);
if (!insertionPoints.isEmpty()) {
for (size_t i = 0; i < insertionPoints.size(); ++i) {
InsertionPoint* insertionPoint = insertionPoints[i];
if (insertionPoint->isShadowInsertionPoint()) {
ShadowRoot* containingShadowRoot = insertionPoint->containingShadowRoot();
ASSERT(containingShadowRoot);
if (!containingShadowRoot->isOldest())
addNodeEventContext(containingShadowRoot->olderShadowRoot());
}
addNodeEventContext(insertionPoint);
}
current = insertionPoints.last();
continue;
}
if (current->isShadowRoot()) {
current = current->shadowHost();
addNodeEventContext(current);
} else {
current = current->parentNode();
if (current)
addNodeEventContext(current);
}
}
}
void EventPath::calculateTreeScopePrePostOrderNumbers()
{
// Precondition:
// - TreeScopes in m_treeScopeEventContexts must be *connected* in the same tree of trees.
// - The root tree must be included.
HashMap<const TreeScope*, TreeScopeEventContext*> treeScopeEventContextMap;
for (size_t i = 0; i < m_treeScopeEventContexts.size(); ++i)
treeScopeEventContextMap.add(&m_treeScopeEventContexts[i]->treeScope(), m_treeScopeEventContexts[i].get());
TreeScopeEventContext* rootTree = 0;
for (size_t i = 0; i < m_treeScopeEventContexts.size(); ++i) {
TreeScopeEventContext* treeScopeEventContext = m_treeScopeEventContexts[i].get();
// Use olderShadowRootOrParentTreeScope here for parent-child relationships.
// See the definition of trees of trees in the Shado DOM spec: http://w3c.github.io/webcomponents/spec/shadow/
TreeScope* parent = treeScopeEventContext->treeScope().olderShadowRootOrParentTreeScope();
if (!parent) {
ASSERT(!rootTree);
rootTree = treeScopeEventContext;
continue;
}
ASSERT(treeScopeEventContextMap.find(parent) != treeScopeEventContextMap.end());
treeScopeEventContextMap.find(parent)->value->addChild(*treeScopeEventContext);
}
ASSERT(rootTree);
rootTree->calculatePrePostOrderNumber(0);
}
TreeScopeEventContext* EventPath::ensureTreeScopeEventContext(Node* currentTarget, TreeScope* treeScope, TreeScopeEventContextMap& treeScopeEventContextMap)
{
if (!treeScope)
return 0;
TreeScopeEventContext* treeScopeEventContext;
bool isNewEntry;
{
TreeScopeEventContextMap::AddResult addResult = treeScopeEventContextMap.add(treeScope, nullptr);
if ((isNewEntry = addResult.isNewEntry))
addResult.storedValue->value = TreeScopeEventContext::create(*treeScope);
treeScopeEventContext = addResult.storedValue->value.get();
}
if (isNewEntry) {
TreeScopeEventContext* parentTreeScopeEventContext = ensureTreeScopeEventContext(0, treeScope->olderShadowRootOrParentTreeScope(), treeScopeEventContextMap);
if (parentTreeScopeEventContext && parentTreeScopeEventContext->target()) {
treeScopeEventContext->setTarget(parentTreeScopeEventContext->target());
} else if (currentTarget) {
treeScopeEventContext->setTarget(eventTargetRespectingTargetRules(currentTarget));
}
} else if (!treeScopeEventContext->target() && currentTarget) {
treeScopeEventContext->setTarget(eventTargetRespectingTargetRules(currentTarget));
}
return treeScopeEventContext;
}
void EventPath::calculateAdjustedTargets()
{
const TreeScope* lastTreeScope = 0;
bool isSVGElement = at(0).node()->isSVGElement();
TreeScopeEventContextMap treeScopeEventContextMap;
TreeScopeEventContext* lastTreeScopeEventContext = 0;
for (size_t i = 0; i < size(); ++i) {
Node* currentNode = at(i).node();
TreeScope& currentTreeScope = currentNode->treeScope();
if (lastTreeScope != ¤tTreeScope) {
if (!isSVGElement) {
lastTreeScopeEventContext = ensureTreeScopeEventContext(currentNode, ¤tTreeScope, treeScopeEventContextMap);
} else {
TreeScopeEventContextMap::AddResult addResult = treeScopeEventContextMap.add(¤tTreeScope, TreeScopeEventContext::create(currentTreeScope));
lastTreeScopeEventContext = addResult.storedValue->value.get();
if (addResult.isNewEntry) {
// Don't adjust an event target for SVG.
lastTreeScopeEventContext->setTarget(eventTargetRespectingTargetRules(at(0).node()));
}
}
}
ASSERT(lastTreeScopeEventContext);
at(i).setTreeScopeEventContext(lastTreeScopeEventContext);
lastTreeScope = ¤tTreeScope;
}
m_treeScopeEventContexts.appendRange(treeScopeEventContextMap.values().begin(), treeScopeEventContextMap.values().end());
}
void EventPath::buildRelatedNodeMap(const Node* relatedNode, RelatedTargetMap& relatedTargetMap)
{
EventPath relatedTargetEventPath(const_cast<Node*>(relatedNode));
for (size_t i = 0; i < relatedTargetEventPath.m_treeScopeEventContexts.size(); ++i) {
TreeScopeEventContext* treeScopeEventContext = relatedTargetEventPath.m_treeScopeEventContexts[i].get();
relatedTargetMap.add(&treeScopeEventContext->treeScope(), treeScopeEventContext->target());
}
}
EventTarget* EventPath::findRelatedNode(TreeScope* scope, RelatedTargetMap& relatedTargetMap)
{
Vector<TreeScope*, 32> parentTreeScopes;
EventTarget* relatedNode = 0;
while (scope) {
parentTreeScopes.append(scope);
RelatedTargetMap::const_iterator iter = relatedTargetMap.find(scope);
if (iter != relatedTargetMap.end() && iter->value) {
relatedNode = iter->value;
break;
}
scope = scope->olderShadowRootOrParentTreeScope();
}
ASSERT(relatedNode);
for (Vector<TreeScope*, 32>::iterator iter = parentTreeScopes.begin(); iter < parentTreeScopes.end(); ++iter)
relatedTargetMap.add(*iter, relatedNode);
return relatedNode;
}
void EventPath::adjustForRelatedTarget(Node* target, EventTarget* relatedTarget)
{
if (!target)
return;
if (!relatedTarget)
return;
Node* relatedNode = relatedTarget->toNode();
if (!relatedNode)
return;
if (target->document() != relatedNode->document())
return;
if (!target->inDocument() || !relatedNode->inDocument())
return;
RelatedTargetMap relatedNodeMap;
buildRelatedNodeMap(relatedNode, relatedNodeMap);
for (size_t i = 0; i < m_treeScopeEventContexts.size(); ++i) {
TreeScopeEventContext* treeScopeEventContext = m_treeScopeEventContexts[i].get();
EventTarget* adjustedRelatedTarget = findRelatedNode(&treeScopeEventContext->treeScope(), relatedNodeMap);
ASSERT(adjustedRelatedTarget);
treeScopeEventContext->setRelatedTarget(adjustedRelatedTarget);
}
shrinkIfNeeded(target, relatedTarget);
}
void EventPath::shrinkIfNeeded(const Node* target, const EventTarget* relatedTarget)
{
// Synthetic mouse events can have a relatedTarget which is identical to the target.
bool targetIsIdenticalToToRelatedTarget = (target == relatedTarget);
for (size_t i = 0; i < size(); ++i) {
if (targetIsIdenticalToToRelatedTarget) {
if (target->treeScope().rootNode() == at(i).node()) {
shrink(i + 1);
break;
}
} else if (at(i).target() == at(i).relatedTarget()) {
// Event dispatching should be stopped here.
shrink(i);
break;
}
}
}
void EventPath::adjustForTouchEvent(Node* node, TouchEvent& touchEvent)
{
WillBeHeapVector<RawPtrWillBeMember<TouchList> > adjustedTouches;
WillBeHeapVector<RawPtrWillBeMember<TouchList> > adjustedTargetTouches;
WillBeHeapVector<RawPtrWillBeMember<TouchList> > adjustedChangedTouches;
Vector<TreeScope*> treeScopes;
for (size_t i = 0; i < m_treeScopeEventContexts.size(); ++i) {
TouchEventContext* touchEventContext = m_treeScopeEventContexts[i]->ensureTouchEventContext();
adjustedTouches.append(&touchEventContext->touches());
adjustedTargetTouches.append(&touchEventContext->targetTouches());
adjustedChangedTouches.append(&touchEventContext->changedTouches());
treeScopes.append(&m_treeScopeEventContexts[i]->treeScope());
}
adjustTouchList(node, touchEvent.touches(), adjustedTouches, treeScopes);
adjustTouchList(node, touchEvent.targetTouches(), adjustedTargetTouches, treeScopes);
adjustTouchList(node, touchEvent.changedTouches(), adjustedChangedTouches, treeScopes);
#ifndef NDEBUG
for (size_t i = 0; i < m_treeScopeEventContexts.size(); ++i) {
TreeScope& treeScope = m_treeScopeEventContexts[i]->treeScope();
TouchEventContext* touchEventContext = m_treeScopeEventContexts[i]->touchEventContext();
checkReachability(treeScope, touchEventContext->touches());
checkReachability(treeScope, touchEventContext->targetTouches());
checkReachability(treeScope, touchEventContext->changedTouches());
}
#endif
}
void EventPath::adjustTouchList(const Node* node, const TouchList* touchList, WillBeHeapVector<RawPtrWillBeMember<TouchList> > adjustedTouchList, const Vector<TreeScope*>& treeScopes)
{
if (!touchList)
return;
for (size_t i = 0; i < touchList->length(); ++i) {
const Touch& touch = *touchList->item(i);
RelatedTargetMap relatedNodeMap;
buildRelatedNodeMap(touch.target()->toNode(), relatedNodeMap);
for (size_t j = 0; j < treeScopes.size(); ++j) {
adjustedTouchList[j]->append(touch.cloneWithNewTarget(findRelatedNode(treeScopes[j], relatedNodeMap)));
}
}
}
#ifndef NDEBUG
void EventPath::checkReachability(TreeScope& treeScope, TouchList& touchList)
{
for (size_t i = 0; i < touchList.length(); ++i)
ASSERT(touchList.item(i)->target()->toNode()->treeScope().isInclusiveOlderSiblingShadowRootOrAncestorTreeScopeOf(treeScope));
}
#endif
void EventPath::trace(Visitor* visitor)
{
visitor->trace(m_event);
}
} // namespace
<|endoftext|> |
<commit_before>/*************************************************************************
> File Name: TaskSerializer.cpp
> Project Name: Hearthstonepp
> Author: Young-Joong Kim
> Purpose: Serializer for TaskMeta and MetaData
> Created Time: 2018/05/20
> Copyright (c) 2018, Young-Joong Kim
*************************************************************************/
#include <Cards/Character.h>
#include <Cards/Weapon.h>
#include <Tasks/MetaData.h>
#include <Tasks/TaskSerializer.h>
#include <algorithm>
namespace Hearthstonepp::Serializer
{
flatbuffers::Offset<FlatData::Entity> CreateEntity(
flatbuffers::FlatBufferBuilder& builder, const Entity* entity)
{
if (entity == nullptr)
{
return FlatData::CreateEntity(builder);
}
return FlatData::CreateEntity(builder,
CreateCard(builder, entity->card, entity), 0);
}
flatbuffers::Offset<FlatData::Card> CreateCard(
flatbuffers::FlatBufferBuilder& builder, const Card* card, const Entity* entity)
{
std::vector<int> mechanics;
mechanics.reserve(card->mechanics.size());
for (const auto& mechanic : card->mechanics)
{
mechanics.emplace_back(static_cast<int>(mechanic));
}
size_t attack = card->attack ? *card->attack : 0;
size_t health = card->health ? *card->health : 0;
size_t durability = card->durability ? *card->durability : 0;
if (entity != nullptr)
{
if (auto character = dynamic_cast<const Character*>(entity); character != nullptr)
{
attack = character->attack;
health = character->health;
}
if (auto weapon = dynamic_cast<const Weapon*>(entity); weapon != nullptr)
{
durability = weapon->durability;
}
}
return FlatData::CreateCard(
builder, builder.CreateString(card->id), static_cast<int>(card->rarity),
static_cast<int>(card->faction), static_cast<int>(card->cardSet),
static_cast<int>(card->cardClass), static_cast<int>(card->cardType),
static_cast<int>(card->race), builder.CreateString(card->name),
builder.CreateString(card->text), card->isCollectible,
static_cast<int>(card->cost), static_cast<uint32_t>(attack),
static_cast<uint32_t>(health), static_cast<uint32_t>(durability),
builder.CreateVector(mechanics), 0, 0, card->GetMaxAllowedInDeck());
}
TaskMeta CreateEntityVector(const TaskMetaTrait& trait,
const std::vector<Entity*>& vector)
{
flatbuffers::FlatBufferBuilder builder(1024);
std::vector<flatbuffers::Offset<FlatData::Entity>> flatten;
for (const auto entity : vector)
{
flatten.emplace_back(CreateEntity(builder, entity));
}
auto entities =
FlatData::CreateEntityVector(builder, builder.CreateVector(flatten));
builder.Finish(entities);
return TaskMeta(trait, builder.GetSize(), builder.GetBufferPointer());
}
TaskMeta CreateTaskMetaVector(const std::vector<TaskMeta>& vector,
MetaData status, BYTE userID)
{
flatbuffers::FlatBufferBuilder builder(1024);
std::vector<flatbuffers::Offset<FlatData::TaskMeta>> flatten;
// Convert TaskMeta to FlatData::TaskMeta
for (const auto& task : vector)
{
auto trait = FlatData::TaskMetaTrait(static_cast<int>(task.id),
static_cast<status_t>(task.status),
task.userID);
const auto& unique = task.GetConstBuffer();
auto buffer = builder.CreateVector(unique.get(), task.GetBufferSize());
auto temporal = FlatData::CreateTaskMeta(builder, &trait, buffer);
flatten.emplace_back(std::move(temporal));
}
// Convert std::vector to FlatData::TaskMetaVector
auto integrated =
FlatData::CreateTaskMetaVector(builder, builder.CreateVector(flatten));
builder.Finish(integrated);
return TaskMeta(TaskMetaTrait(TaskID::TASK_VECTOR, status, userID),
builder.GetSize(), builder.GetBufferPointer());
}
TaskMeta CreateRequire(TaskID request, BYTE userID)
{
flatbuffers::FlatBufferBuilder builder(32);
auto flat =
FlatData::CreateRequireTaskMeta(builder, static_cast<int>(request));
builder.Finish(flat);
return TaskMeta(TaskMetaTrait(TaskID::REQUIRE, MetaData::INVALID, userID),
builder.GetSize(), builder.GetBufferPointer());
}
TaskMeta CreateResponseMulligan(const BYTE* index, size_t size)
{
flatbuffers::FlatBufferBuilder builder(32);
auto vector = builder.CreateVector(index, size);
auto flat = FlatData::CreateResponseMulligan(builder, vector);
builder.Finish(flat);
return TaskMeta(TaskMetaTrait(TaskID::MULLIGAN), builder.GetSize(),
builder.GetBufferPointer());
}
TaskMeta CreateResponsePlayCard(size_t cardIndex)
{
flatbuffers::FlatBufferBuilder builder(32);
auto flat =
FlatData::CreateResponsePlayCard(builder, static_cast<BYTE>(cardIndex));
builder.Finish(flat);
return TaskMeta(TaskMetaTrait(TaskID::SELECT_CARD, MetaData::SELECT_CARD),
builder.GetSize(), builder.GetBufferPointer());
}
TaskMeta CreateResponsePlayMinion(size_t position)
{
flatbuffers::FlatBufferBuilder builder(32);
auto flat = FlatData::CreateResponsePlayMinion(builder,
static_cast<BYTE>(position));
builder.Finish(flat);
return TaskMeta(
TaskMetaTrait(TaskID::SELECT_POSITION, MetaData::SELECT_POSITION),
builder.GetSize(), builder.GetBufferPointer());
}
TaskMeta CreateResponsePlaySpell(TargetType targetType, size_t targetPosition)
{
flatbuffers::FlatBufferBuilder builder(32);
auto flat = FlatData::CreateResponsePlaySpell(
builder, static_cast<BYTE>(targetType),
static_cast<BYTE>(targetPosition));
builder.Finish(flat);
return TaskMeta(
TaskMetaTrait(TaskID::SELECT_TARGET, MetaData::SELECT_TARGET),
builder.GetSize(), builder.GetBufferPointer());
}
TaskMeta CreateResponseTarget(size_t src, size_t dst)
{
flatbuffers::FlatBufferBuilder builder(32);
auto flat = FlatData::CreateResponseTarget(builder, static_cast<BYTE>(src),
static_cast<BYTE>(dst));
builder.Finish(flat);
return TaskMeta(
TaskMetaTrait(TaskID::SELECT_TARGET, MetaData::SELECT_TARGET),
builder.GetSize(), builder.GetBufferPointer());
}
TaskMeta CreatePlayerSetting(const std::string& player1,
const std::string& player2)
{
flatbuffers::FlatBufferBuilder builder(256);
auto setting = FlatData::CreatePlayerSetting(
builder, builder.CreateString(player1), builder.CreateString(player2));
builder.Finish(setting);
return TaskMeta(
TaskMetaTrait(TaskID::PLAYER_SETTING, MetaData::PLAYER_SETTING_REQUEST),
builder.GetSize(), builder.GetBufferPointer());
}
TaskMeta CreateGameStatus(TaskID taskID, MetaData status, const Player& player1,
const Player& player2)
{
using EntityOffset = flatbuffers::Offset<FlatData::Entity>;
using VectorOffset = flatbuffers::Offset<flatbuffers::Vector<EntityOffset>>;
flatbuffers::FlatBufferBuilder builder(256);
auto makeOffset = [&builder](auto&& vec) -> VectorOffset {
std::vector<EntityOffset> dest(vec.size());
std::transform(vec.begin(), vec.end(), dest.begin(),
[&builder](Entity* entity) {
return CreateEntity(builder, entity);
});
return builder.CreateVector(dest);
};
// Tie multi card vector
auto target = {player1.field, player2.field};
std::vector<VectorOffset> result(target.size());
// Convert Card vector to FlatData::Card vector
std::transform(target.begin(), target.end(), result.begin(), makeOffset);
auto gameStatus = FlatData::CreateGameStatus(
builder, player1.id, player2.id, player1.existMana, player2.existMana,
CreateEntity(builder, player1.hero),
CreateEntity(builder, player2.hero), result[0],
makeOffset(player1.hand), result[1],
static_cast<BYTE>(player2.hand.size()),
static_cast<BYTE>(player1.cards.size()),
static_cast<BYTE>(player2.cards.size()), result[2], result[3]);
builder.Finish(gameStatus);
return TaskMeta(TaskMetaTrait(taskID, status, player1.id),
builder.GetSize(), builder.GetBufferPointer());
}
} // namespace Hearthstonepp::Serializer
<commit_msg>Update TaskSerializer - Remove Attacked vector serializer<commit_after>/*************************************************************************
> File Name: TaskSerializer.cpp
> Project Name: Hearthstonepp
> Author: Young-Joong Kim
> Purpose: Serializer for TaskMeta and MetaData
> Created Time: 2018/05/20
> Copyright (c) 2018, Young-Joong Kim
*************************************************************************/
#include <Cards/Character.h>
#include <Cards/Weapon.h>
#include <Tasks/MetaData.h>
#include <Tasks/TaskSerializer.h>
#include <algorithm>
namespace Hearthstonepp::Serializer
{
flatbuffers::Offset<FlatData::Entity> CreateEntity(
flatbuffers::FlatBufferBuilder& builder, const Entity* entity)
{
if (entity == nullptr)
{
return FlatData::CreateEntity(builder);
}
return FlatData::CreateEntity(builder,
CreateCard(builder, entity->card, entity), 0);
}
flatbuffers::Offset<FlatData::Card> CreateCard(
flatbuffers::FlatBufferBuilder& builder, const Card* card,
const Entity* entity)
{
std::vector<int> mechanics;
mechanics.reserve(card->mechanics.size());
for (const auto& mechanic : card->mechanics)
{
mechanics.emplace_back(static_cast<int>(mechanic));
}
size_t attack = card->attack ? *card->attack : 0;
size_t health = card->health ? *card->health : 0;
size_t durability = card->durability ? *card->durability : 0;
if (entity != nullptr)
{
if (auto character = dynamic_cast<const Character*>(entity);
character != nullptr)
{
attack = character->attack;
health = character->health;
}
if (auto weapon = dynamic_cast<const Weapon*>(entity);
weapon != nullptr)
{
durability = weapon->durability;
}
}
return FlatData::CreateCard(
builder, builder.CreateString(card->id), static_cast<int>(card->rarity),
static_cast<int>(card->faction), static_cast<int>(card->cardSet),
static_cast<int>(card->cardClass), static_cast<int>(card->cardType),
static_cast<int>(card->race), builder.CreateString(card->name),
builder.CreateString(card->text), card->isCollectible,
static_cast<int>(card->cost), static_cast<uint32_t>(attack),
static_cast<uint32_t>(health), static_cast<uint32_t>(durability),
builder.CreateVector(mechanics), 0, 0, card->GetMaxAllowedInDeck());
}
TaskMeta CreateEntityVector(const TaskMetaTrait& trait,
const std::vector<Entity*>& vector)
{
flatbuffers::FlatBufferBuilder builder(1024);
std::vector<flatbuffers::Offset<FlatData::Entity>> flatten;
for (const auto entity : vector)
{
flatten.emplace_back(CreateEntity(builder, entity));
}
auto entities =
FlatData::CreateEntityVector(builder, builder.CreateVector(flatten));
builder.Finish(entities);
return TaskMeta(trait, builder.GetSize(), builder.GetBufferPointer());
}
TaskMeta CreateTaskMetaVector(const std::vector<TaskMeta>& vector,
MetaData status, BYTE userID)
{
flatbuffers::FlatBufferBuilder builder(1024);
std::vector<flatbuffers::Offset<FlatData::TaskMeta>> flatten;
// Convert TaskMeta to FlatData::TaskMeta
for (const auto& task : vector)
{
auto trait = FlatData::TaskMetaTrait(static_cast<int>(task.id),
static_cast<status_t>(task.status),
task.userID);
const auto& unique = task.GetConstBuffer();
auto buffer = builder.CreateVector(unique.get(), task.GetBufferSize());
auto temporal = FlatData::CreateTaskMeta(builder, &trait, buffer);
flatten.emplace_back(std::move(temporal));
}
// Convert std::vector to FlatData::TaskMetaVector
auto integrated =
FlatData::CreateTaskMetaVector(builder, builder.CreateVector(flatten));
builder.Finish(integrated);
return TaskMeta(TaskMetaTrait(TaskID::TASK_VECTOR, status, userID),
builder.GetSize(), builder.GetBufferPointer());
}
TaskMeta CreateRequire(TaskID request, BYTE userID)
{
flatbuffers::FlatBufferBuilder builder(32);
auto flat =
FlatData::CreateRequireTaskMeta(builder, static_cast<int>(request));
builder.Finish(flat);
return TaskMeta(TaskMetaTrait(TaskID::REQUIRE, MetaData::INVALID, userID),
builder.GetSize(), builder.GetBufferPointer());
}
TaskMeta CreateResponseMulligan(const BYTE* index, size_t size)
{
flatbuffers::FlatBufferBuilder builder(32);
auto vector = builder.CreateVector(index, size);
auto flat = FlatData::CreateResponseMulligan(builder, vector);
builder.Finish(flat);
return TaskMeta(TaskMetaTrait(TaskID::MULLIGAN), builder.GetSize(),
builder.GetBufferPointer());
}
TaskMeta CreateResponsePlayCard(size_t cardIndex)
{
flatbuffers::FlatBufferBuilder builder(32);
auto flat =
FlatData::CreateResponsePlayCard(builder, static_cast<BYTE>(cardIndex));
builder.Finish(flat);
return TaskMeta(TaskMetaTrait(TaskID::SELECT_CARD, MetaData::SELECT_CARD),
builder.GetSize(), builder.GetBufferPointer());
}
TaskMeta CreateResponsePlayMinion(size_t position)
{
flatbuffers::FlatBufferBuilder builder(32);
auto flat = FlatData::CreateResponsePlayMinion(builder,
static_cast<BYTE>(position));
builder.Finish(flat);
return TaskMeta(
TaskMetaTrait(TaskID::SELECT_POSITION, MetaData::SELECT_POSITION),
builder.GetSize(), builder.GetBufferPointer());
}
TaskMeta CreateResponsePlaySpell(TargetType targetType, size_t targetPosition)
{
flatbuffers::FlatBufferBuilder builder(32);
auto flat = FlatData::CreateResponsePlaySpell(
builder, static_cast<BYTE>(targetType),
static_cast<BYTE>(targetPosition));
builder.Finish(flat);
return TaskMeta(
TaskMetaTrait(TaskID::SELECT_TARGET, MetaData::SELECT_TARGET),
builder.GetSize(), builder.GetBufferPointer());
}
TaskMeta CreateResponseTarget(size_t src, size_t dst)
{
flatbuffers::FlatBufferBuilder builder(32);
auto flat = FlatData::CreateResponseTarget(builder, static_cast<BYTE>(src),
static_cast<BYTE>(dst));
builder.Finish(flat);
return TaskMeta(
TaskMetaTrait(TaskID::SELECT_TARGET, MetaData::SELECT_TARGET),
builder.GetSize(), builder.GetBufferPointer());
}
TaskMeta CreatePlayerSetting(const std::string& player1,
const std::string& player2)
{
flatbuffers::FlatBufferBuilder builder(256);
auto setting = FlatData::CreatePlayerSetting(
builder, builder.CreateString(player1), builder.CreateString(player2));
builder.Finish(setting);
return TaskMeta(
TaskMetaTrait(TaskID::PLAYER_SETTING, MetaData::PLAYER_SETTING_REQUEST),
builder.GetSize(), builder.GetBufferPointer());
}
TaskMeta CreateGameStatus(TaskID taskID, MetaData status, const Player& player1,
const Player& player2)
{
using EntityOffset = flatbuffers::Offset<FlatData::Entity>;
using VectorOffset = flatbuffers::Offset<flatbuffers::Vector<EntityOffset>>;
flatbuffers::FlatBufferBuilder builder(256);
auto makeOffset = [&builder](auto&& vec) -> VectorOffset {
std::vector<EntityOffset> dest(vec.size());
std::transform(vec.begin(), vec.end(), dest.begin(),
[&builder](Entity* entity) {
return CreateEntity(builder, entity);
});
return builder.CreateVector(dest);
};
// Tie multi card vector
auto target = {player1.field, player2.field};
std::vector<VectorOffset> result(target.size());
// Convert Card vector to FlatData::Card vector
std::transform(target.begin(), target.end(), result.begin(), makeOffset);
auto gameStatus = FlatData::CreateGameStatus(
builder, player1.id, player2.id, player1.existMana, player2.existMana,
CreateEntity(builder, player1.hero),
CreateEntity(builder, player2.hero), result[0],
makeOffset(player1.hand), result[1],
static_cast<BYTE>(player2.hand.size()),
static_cast<BYTE>(player1.cards.size()),
static_cast<BYTE>(player2.cards.size()));
builder.Finish(gameStatus);
return TaskMeta(TaskMetaTrait(taskID, status, player1.id),
builder.GetSize(), builder.GetBufferPointer());
}
} // namespace Hearthstonepp::Serializer
<|endoftext|> |
<commit_before><commit_msg>Added unit tests for node methods<commit_after>#define CATCH_CONFIG_MAIN
#include "catch.hpp"
#include "Graph.hpp"
SCENARIO ( "Graph nodes work correctly" ) {
GIVEN ( "A graph node with initial values" ) {
GraphNode gnode(1, 10);
WHEN ( "I get the values" ) {
THEN ( "Values should be the same as the initial state" ) {
REQUIRE( gnode.getId() == 1 );
REQUIRE( gnode.getValue() == 10);
REQUIRE( gnode.getVisit() == false );
REQUIRE( gnode.getHasParentId() == false );
REQUIRE( gnode.getParentId() == 0 );
}
}
WHEN ( "I set new values" ) {
gnode.setId(2);
gnode.setValue(20);
gnode.setVisit(true);
gnode.setHasParentId(true);
gnode.setParentId(2);
THEN ( "Values should be the same as the new values I set" ) {
REQUIRE( gnode.getId() == 2 );
REQUIRE( gnode.getValue() == 20 );
REQUIRE( gnode.getVisit() == true );
REQUIRE( gnode.getHasParentId() == true );
REQUIRE( gnode.getParentId() == 2 );
}
}
}
}
<|endoftext|> |
<commit_before>
#include <orne_rviz_plugins/state_trigger_panel.h>
#include <QHBoxLayout>
namespace orne_navigation
{
StateTriggerPanel::StateTriggerPanel(QWidget *parent) :
rviz::Panel(parent)
{
QHBoxLayout *layout = new QHBoxLayout;
start_nav_button_ = new QPushButton("StartWaypointsNav");
layout->addWidget(start_nav_button_);
setLayout(layout);
connect(start_nav_button_, SIGNAL(clicked()), this, SLOT(pushStartWaypointsNav()));
}
void StateTriggerPanel::pushStartWaypointsNav() {
ROS_ERROR("DEBUG: panel!!!");
}
void StateTriggerPanel::load(const rviz::Config &config) {
rviz::Panel::load(config);
}
void StateTriggerPanel::save(rviz::Config config) const {
rviz::Panel::save(config);
}
} //namespace orne_navigation
#include <pluginlib/class_list_macros.h>
PLUGINLIB_EXPORT_CLASS(orne_navigation::StateTriggerPanel, rviz::Panel)
<commit_msg>the namespace switched<commit_after>
#include <orne_rviz_plugins/state_trigger_panel.h>
#include <QHBoxLayout>
namespace orne_rviz_plugins
{
StateTriggerPanel::StateTriggerPanel(QWidget *parent) :
rviz::Panel(parent)
{
QHBoxLayout *layout = new QHBoxLayout;
start_nav_button_ = new QPushButton("StartWaypointsNav");
layout->addWidget(start_nav_button_);
setLayout(layout);
connect(start_nav_button_, SIGNAL(clicked()), this, SLOT(pushStartWaypointsNav()));
}
void StateTriggerPanel::pushStartWaypointsNav() {
ROS_ERROR("DEBUG: panel!!!");
}
void StateTriggerPanel::load(const rviz::Config &config) {
rviz::Panel::load(config);
}
void StateTriggerPanel::save(rviz::Config config) const {
rviz::Panel::save(config);
}
} //namespace orne_navigation
#include <pluginlib/class_list_macros.h>
PLUGINLIB_EXPORT_CLASS(orne_rviz_plugins::StateTriggerPanel, rviz::Panel)
<|endoftext|> |
<commit_before>#include <string>
#include <fstream>
#include <streambuf>
#include <sstream>
#include <map>
#include <boost/lexical_cast.hpp>
#include <libudev.h>
#include <blkid/blkid.h>
#include "osquery/core.h"
#include "osquery/database.h"
#include "osquery/filesystem.h"
namespace osquery {
namespace tables {
static void fillRow(struct udev_device *dev, Row &r) {
struct udev_device *parent, *scsi_dev;
blkid_probe pr;
const char *name, *tmp;
if ((name = udev_device_get_devnode(dev)))
r["name"] = std::string(name);
if ((parent =
udev_device_get_parent_with_subsystem_devtype(dev, "block", NULL)))
r["parent"] = std::string(udev_device_get_devnode(parent));
if ((tmp = udev_device_get_sysattr_value(dev, "size")))
r["size"] = std::string(tmp);
if ((scsi_dev =
udev_device_get_parent_with_subsystem_devtype(dev, "scsi", NULL))) {
if ((tmp = udev_device_get_sysattr_value(scsi_dev, "model")))
r["model"] = std::string(tmp);
if ((tmp = udev_device_get_sysattr_value(scsi_dev, "vendor")))
r["vendor"] = std::string(tmp);
}
if (name && ((pr = blkid_new_probe_from_filename(name)))) {
blkid_probe_enable_superblocks(pr, 1);
blkid_probe_set_superblocks_flags(
pr, BLKID_SUBLKS_LABEL | BLKID_SUBLKS_UUID | BLKID_SUBLKS_TYPE);
if (!blkid_do_safeprobe(pr)) {
if (!blkid_probe_lookup_value(pr, "TYPE", &tmp, NULL))
r["type"] = std::string(tmp);
if (!blkid_probe_lookup_value(pr, "UUID", &tmp, NULL))
r["uuid"] = std::string(tmp);
if (!blkid_probe_lookup_value(pr, "LABEL", &tmp, NULL))
r["label"] = std::string(tmp);
}
blkid_free_probe(pr);
}
}
QueryData genBlockDevs() {
QueryData results;
struct udev *udev;
struct udev_enumerate *enumerate;
struct udev_list_entry *devices, *dev_list_entry;
struct udev_device *dev, *parent;
if ((udev = udev_new())) {
enumerate = udev_enumerate_new(udev);
udev_enumerate_add_match_subsystem(enumerate, "block");
udev_enumerate_scan_devices(enumerate);
devices = udev_enumerate_get_list_entry(enumerate);
udev_list_entry_foreach(dev_list_entry, devices) {
const char *path;
Row r;
path = udev_list_entry_get_name(dev_list_entry);
dev = udev_device_new_from_syspath(udev, path);
fillRow(dev, r);
results.push_back(r);
udev_device_unref(dev);
}
}
udev_enumerate_unref(enumerate);
udev_unref(udev);
return results;
}
}
}
<commit_msg>Add braces<commit_after>#include <string>
#include <fstream>
#include <streambuf>
#include <sstream>
#include <map>
#include <boost/lexical_cast.hpp>
#include <libudev.h>
#include <blkid/blkid.h>
#include "osquery/core.h"
#include "osquery/database.h"
#include "osquery/filesystem.h"
namespace osquery {
namespace tables {
static void fillRow(struct udev_device *dev, Row &r) {
struct udev_device *parent, *scsi_dev;
blkid_probe pr;
const char *name, *tmp;
if ((name = udev_device_get_devnode(dev))) {
r["name"] = std::string(name);
}
if ((parent =
udev_device_get_parent_with_subsystem_devtype(dev, "block", NULL))) {
r["parent"] = std::string(udev_device_get_devnode(parent));
}
if ((tmp = udev_device_get_sysattr_value(dev, "size"))) {
r["size"] = std::string(tmp);
}
if ((scsi_dev =
udev_device_get_parent_with_subsystem_devtype(dev, "scsi", NULL))) {
if ((tmp = udev_device_get_sysattr_value(scsi_dev, "model"))) {
r["model"] = std::string(tmp);
}
if ((tmp = udev_device_get_sysattr_value(scsi_dev, "vendor"))) {
r["vendor"] = std::string(tmp);
}
}
if (name && ((pr = blkid_new_probe_from_filename(name)))) {
blkid_probe_enable_superblocks(pr, 1);
blkid_probe_set_superblocks_flags(
pr, BLKID_SUBLKS_LABEL | BLKID_SUBLKS_UUID | BLKID_SUBLKS_TYPE);
if (!blkid_do_safeprobe(pr)) {
if (!blkid_probe_lookup_value(pr, "TYPE", &tmp, NULL)) {
r["type"] = std::string(tmp);
}
if (!blkid_probe_lookup_value(pr, "UUID", &tmp, NULL)) {
r["uuid"] = std::string(tmp);
}
if (!blkid_probe_lookup_value(pr, "LABEL", &tmp, NULL)) {
r["label"] = std::string(tmp);
}
}
blkid_free_probe(pr);
}
}
QueryData genBlockDevs() {
QueryData results;
struct udev *udev;
struct udev_enumerate *enumerate;
struct udev_list_entry *devices, *dev_list_entry;
struct udev_device *dev, *parent;
if ((udev = udev_new())) {
enumerate = udev_enumerate_new(udev);
udev_enumerate_add_match_subsystem(enumerate, "block");
udev_enumerate_scan_devices(enumerate);
devices = udev_enumerate_get_list_entry(enumerate);
udev_list_entry_foreach(dev_list_entry, devices) {
const char *path;
Row r;
path = udev_list_entry_get_name(dev_list_entry);
dev = udev_device_new_from_syspath(udev, path);
fillRow(dev, r);
results.push_back(r);
udev_device_unref(dev);
}
}
udev_enumerate_unref(enumerate);
udev_unref(udev);
return results;
}
}
}
<|endoftext|> |
<commit_before>#ifndef K3_RUNTIME_CONTEXT_H
#define K3_RUNTIME_CONTEXT_H
#include <map>
#include <string>
#include "Dispatch.hpp"
namespace K3 {
class Engine;
class __k3_context {
public:
__k3_context(Engine& e): __engine(e) {}
virtual void __dispatch(std::shared_ptr<Dispatcher>) {}
virtual std::map<std::string, std::string> __prettify() { return std::map<std::string, std::string> {}; }
virtual void __patch(std::string) {}
protected:
Engine& __engine;
};
}
#endif
<commit_msg>Make program context methods pure virtual.<commit_after>#ifndef K3_RUNTIME_CONTEXT_H
#define K3_RUNTIME_CONTEXT_H
#include <map>
#include <string>
#include "Dispatch.hpp"
namespace K3 {
class Engine;
class __k3_context {
public:
__k3_context(Engine& e): __engine(e) {}
virtual void __dispatch(std::shared_ptr<Dispatcher>) = 0;
virtual std::map<std::string, std::string> __prettify() = 0;
virtual void __patch(std::string) = 0;
protected:
Engine& __engine;
};
}
#endif
<|endoftext|> |
<commit_before>/*
* Copyright (C) 2013 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#include "mem_map.h"
#include <memory>
#include "gtest/gtest.h"
namespace art {
class MemMapTest : public testing::Test {
public:
static byte* BaseBegin(MemMap* mem_map) {
return reinterpret_cast<byte*>(mem_map->base_begin_);
}
static size_t BaseSize(MemMap* mem_map) {
return mem_map->base_size_;
}
static void RemapAtEndTest(bool low_4gb) {
std::string error_msg;
// Cast the page size to size_t.
const size_t page_size = static_cast<size_t>(kPageSize);
// Map a two-page memory region.
MemMap* m0 = MemMap::MapAnonymous("MemMapTest_RemapAtEndTest_map0",
nullptr,
2 * page_size,
PROT_READ | PROT_WRITE,
low_4gb,
&error_msg);
// Check its state and write to it.
byte* base0 = m0->Begin();
ASSERT_TRUE(base0 != nullptr) << error_msg;
size_t size0 = m0->Size();
EXPECT_EQ(m0->Size(), 2 * page_size);
EXPECT_EQ(BaseBegin(m0), base0);
EXPECT_EQ(BaseSize(m0), size0);
memset(base0, 42, 2 * page_size);
// Remap the latter half into a second MemMap.
MemMap* m1 = m0->RemapAtEnd(base0 + page_size,
"MemMapTest_RemapAtEndTest_map1",
PROT_READ | PROT_WRITE,
&error_msg);
// Check the states of the two maps.
EXPECT_EQ(m0->Begin(), base0) << error_msg;
EXPECT_EQ(m0->Size(), page_size);
EXPECT_EQ(BaseBegin(m0), base0);
EXPECT_EQ(BaseSize(m0), page_size);
byte* base1 = m1->Begin();
size_t size1 = m1->Size();
EXPECT_EQ(base1, base0 + page_size);
EXPECT_EQ(size1, page_size);
EXPECT_EQ(BaseBegin(m1), base1);
EXPECT_EQ(BaseSize(m1), size1);
// Write to the second region.
memset(base1, 43, page_size);
// Check the contents of the two regions.
for (size_t i = 0; i < page_size; ++i) {
EXPECT_EQ(base0[i], 42);
}
for (size_t i = 0; i < page_size; ++i) {
EXPECT_EQ(base1[i], 43);
}
// Unmap the first region.
delete m0;
// Make sure the second region is still accessible after the first
// region is unmapped.
for (size_t i = 0; i < page_size; ++i) {
EXPECT_EQ(base1[i], 43);
}
delete m1;
}
#if defined(__LP64__) && !defined(__x86_64__)
static uintptr_t GetLinearScanPos() {
return MemMap::next_mem_pos_;
}
#endif
};
#if defined(__LP64__) && !defined(__x86_64__)
#ifdef __BIONIC__
extern uintptr_t CreateStartPos(uint64_t input);
#endif
TEST_F(MemMapTest, Start) {
uintptr_t start = GetLinearScanPos();
EXPECT_LE(64 * KB, start);
EXPECT_LT(start, static_cast<uintptr_t>(ART_BASE_ADDRESS));
#ifdef __BIONIC__
// Test a couple of values. Make sure they are different.
uintptr_t last = 0;
for (size_t i = 0; i < 100; ++i) {
uintptr_t random_start = CreateStartPos(i * kPageSize);
EXPECT_NE(last, random_start);
last = random_start;
}
// Even on max, should be below ART_BASE_ADDRESS.
EXPECT_LT(CreateStartPos(~0), static_cast<uintptr_t>(ART_BASE_ADDRESS));
#endif
// End of test.
}
#endif
TEST_F(MemMapTest, MapAnonymousEmpty) {
std::string error_msg;
std::unique_ptr<MemMap> map(MemMap::MapAnonymous("MapAnonymousEmpty",
nullptr,
0,
PROT_READ,
false,
&error_msg));
ASSERT_TRUE(map.get() != nullptr) << error_msg;
ASSERT_TRUE(error_msg.empty());
map.reset(MemMap::MapAnonymous("MapAnonymousEmpty",
nullptr,
kPageSize,
PROT_READ | PROT_WRITE,
false,
&error_msg));
ASSERT_TRUE(map.get() != nullptr) << error_msg;
ASSERT_TRUE(error_msg.empty());
}
#ifdef __LP64__
TEST_F(MemMapTest, MapAnonymousEmpty32bit) {
std::string error_msg;
std::unique_ptr<MemMap> map(MemMap::MapAnonymous("MapAnonymousEmpty",
nullptr,
kPageSize,
PROT_READ | PROT_WRITE,
true,
&error_msg));
ASSERT_TRUE(map.get() != nullptr) << error_msg;
ASSERT_TRUE(error_msg.empty());
ASSERT_LT(reinterpret_cast<uintptr_t>(BaseBegin(map.get())), 1ULL << 32);
}
#endif
TEST_F(MemMapTest, MapAnonymousExactAddr) {
std::string error_msg;
// Map at an address that should work, which should succeed.
std::unique_ptr<MemMap> map0(MemMap::MapAnonymous("MapAnonymous0",
reinterpret_cast<byte*>(ART_BASE_ADDRESS),
kPageSize,
PROT_READ | PROT_WRITE,
false,
&error_msg));
ASSERT_TRUE(map0.get() != nullptr) << error_msg;
ASSERT_TRUE(error_msg.empty());
ASSERT_TRUE(map0->BaseBegin() == reinterpret_cast<void*>(ART_BASE_ADDRESS));
// Map at an unspecified address, which should succeed.
std::unique_ptr<MemMap> map1(MemMap::MapAnonymous("MapAnonymous1",
nullptr,
kPageSize,
PROT_READ | PROT_WRITE,
false,
&error_msg));
ASSERT_TRUE(map1.get() != nullptr) << error_msg;
ASSERT_TRUE(error_msg.empty());
ASSERT_TRUE(map1->BaseBegin() != nullptr);
// Attempt to map at the same address, which should fail.
std::unique_ptr<MemMap> map2(MemMap::MapAnonymous("MapAnonymous2",
reinterpret_cast<byte*>(map1->BaseBegin()),
kPageSize,
PROT_READ | PROT_WRITE,
false,
&error_msg));
ASSERT_TRUE(map2.get() == nullptr) << error_msg;
ASSERT_TRUE(!error_msg.empty());
}
TEST_F(MemMapTest, RemapAtEnd) {
RemapAtEndTest(false);
}
#ifdef __LP64__
TEST_F(MemMapTest, RemapAtEnd32bit) {
RemapAtEndTest(true);
}
#endif
TEST_F(MemMapTest, MapAnonymousExactAddr32bitHighAddr) {
std::string error_msg;
std::unique_ptr<MemMap> map(MemMap::MapAnonymous("MapAnonymousExactAddr32bitHighAddr",
reinterpret_cast<byte*>(0x71000000),
0x21000000,
PROT_READ | PROT_WRITE,
true,
&error_msg));
ASSERT_TRUE(map.get() != nullptr) << error_msg;
ASSERT_TRUE(error_msg.empty());
ASSERT_EQ(reinterpret_cast<uintptr_t>(BaseBegin(map.get())), 0x71000000U);
}
TEST_F(MemMapTest, MapAnonymousOverflow) {
std::string error_msg;
uintptr_t ptr = 0;
ptr -= kPageSize; // Now it's close to the top.
std::unique_ptr<MemMap> map(MemMap::MapAnonymous("MapAnonymousOverflow",
reinterpret_cast<byte*>(ptr),
2 * kPageSize, // brings it over the top.
PROT_READ | PROT_WRITE,
false,
&error_msg));
ASSERT_EQ(nullptr, map.get());
ASSERT_FALSE(error_msg.empty());
}
#ifdef __LP64__
TEST_F(MemMapTest, MapAnonymousLow4GBExpectedTooHigh) {
std::string error_msg;
std::unique_ptr<MemMap> map(MemMap::MapAnonymous("MapAnonymousLow4GBExpectedTooHigh",
reinterpret_cast<byte*>(UINT64_C(0x100000000)),
kPageSize,
PROT_READ | PROT_WRITE,
true,
&error_msg));
ASSERT_EQ(nullptr, map.get());
ASSERT_FALSE(error_msg.empty());
}
TEST_F(MemMapTest, MapAnonymousLow4GBRangeTooHigh) {
std::string error_msg;
std::unique_ptr<MemMap> map(MemMap::MapAnonymous("MapAnonymousLow4GBRangeTooHigh",
reinterpret_cast<byte*>(0xF0000000),
0x20000000,
PROT_READ | PROT_WRITE,
true,
&error_msg));
ASSERT_EQ(nullptr, map.get());
ASSERT_FALSE(error_msg.empty());
}
#endif
TEST_F(MemMapTest, CheckNoGaps) {
std::string error_msg;
constexpr size_t kNumPages = 3;
// Map a 3-page mem map.
std::unique_ptr<MemMap> map(MemMap::MapAnonymous("MapAnonymous0",
nullptr,
kPageSize * kNumPages,
PROT_READ | PROT_WRITE,
false,
&error_msg));
ASSERT_TRUE(map.get() != nullptr) << error_msg;
ASSERT_TRUE(error_msg.empty());
// Record the base address.
byte* map_base = reinterpret_cast<byte*>(map->BaseBegin());
// Unmap it.
map.reset();
// Map at the same address, but in page-sized separate mem maps,
// assuming the space at the address is still available.
std::unique_ptr<MemMap> map0(MemMap::MapAnonymous("MapAnonymous0",
map_base,
kPageSize,
PROT_READ | PROT_WRITE,
false,
&error_msg));
ASSERT_TRUE(map0.get() != nullptr) << error_msg;
ASSERT_TRUE(error_msg.empty());
std::unique_ptr<MemMap> map1(MemMap::MapAnonymous("MapAnonymous1",
map_base + kPageSize,
kPageSize,
PROT_READ | PROT_WRITE,
false,
&error_msg));
ASSERT_TRUE(map1.get() != nullptr) << error_msg;
ASSERT_TRUE(error_msg.empty());
std::unique_ptr<MemMap> map2(MemMap::MapAnonymous("MapAnonymous2",
map_base + kPageSize * 2,
kPageSize,
PROT_READ | PROT_WRITE,
false,
&error_msg));
ASSERT_TRUE(map2.get() != nullptr) << error_msg;
ASSERT_TRUE(error_msg.empty());
// One-map cases.
ASSERT_TRUE(MemMap::CheckNoGaps(map0.get(), map0.get()));
ASSERT_TRUE(MemMap::CheckNoGaps(map1.get(), map1.get()));
ASSERT_TRUE(MemMap::CheckNoGaps(map2.get(), map2.get()));
// Two or three-map cases.
ASSERT_TRUE(MemMap::CheckNoGaps(map0.get(), map1.get()));
ASSERT_TRUE(MemMap::CheckNoGaps(map1.get(), map2.get()));
ASSERT_TRUE(MemMap::CheckNoGaps(map0.get(), map2.get()));
// Unmap the middle one.
map1.reset();
// Should return false now that there's a gap in the middle.
ASSERT_FALSE(MemMap::CheckNoGaps(map0.get(), map2.get()));
}
} // namespace art
<commit_msg>am e7608fd7: am 44405a14: Merge "Fix mem_map_test for Mips."<commit_after>/*
* Copyright (C) 2013 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#include "mem_map.h"
#include <memory>
#include "gtest/gtest.h"
namespace art {
class MemMapTest : public testing::Test {
public:
static byte* BaseBegin(MemMap* mem_map) {
return reinterpret_cast<byte*>(mem_map->base_begin_);
}
static size_t BaseSize(MemMap* mem_map) {
return mem_map->base_size_;
}
static void RemapAtEndTest(bool low_4gb) {
std::string error_msg;
// Cast the page size to size_t.
const size_t page_size = static_cast<size_t>(kPageSize);
// Map a two-page memory region.
MemMap* m0 = MemMap::MapAnonymous("MemMapTest_RemapAtEndTest_map0",
nullptr,
2 * page_size,
PROT_READ | PROT_WRITE,
low_4gb,
&error_msg);
// Check its state and write to it.
byte* base0 = m0->Begin();
ASSERT_TRUE(base0 != nullptr) << error_msg;
size_t size0 = m0->Size();
EXPECT_EQ(m0->Size(), 2 * page_size);
EXPECT_EQ(BaseBegin(m0), base0);
EXPECT_EQ(BaseSize(m0), size0);
memset(base0, 42, 2 * page_size);
// Remap the latter half into a second MemMap.
MemMap* m1 = m0->RemapAtEnd(base0 + page_size,
"MemMapTest_RemapAtEndTest_map1",
PROT_READ | PROT_WRITE,
&error_msg);
// Check the states of the two maps.
EXPECT_EQ(m0->Begin(), base0) << error_msg;
EXPECT_EQ(m0->Size(), page_size);
EXPECT_EQ(BaseBegin(m0), base0);
EXPECT_EQ(BaseSize(m0), page_size);
byte* base1 = m1->Begin();
size_t size1 = m1->Size();
EXPECT_EQ(base1, base0 + page_size);
EXPECT_EQ(size1, page_size);
EXPECT_EQ(BaseBegin(m1), base1);
EXPECT_EQ(BaseSize(m1), size1);
// Write to the second region.
memset(base1, 43, page_size);
// Check the contents of the two regions.
for (size_t i = 0; i < page_size; ++i) {
EXPECT_EQ(base0[i], 42);
}
for (size_t i = 0; i < page_size; ++i) {
EXPECT_EQ(base1[i], 43);
}
// Unmap the first region.
delete m0;
// Make sure the second region is still accessible after the first
// region is unmapped.
for (size_t i = 0; i < page_size; ++i) {
EXPECT_EQ(base1[i], 43);
}
delete m1;
}
#if defined(__LP64__) && !defined(__x86_64__)
static uintptr_t GetLinearScanPos() {
return MemMap::next_mem_pos_;
}
#endif
};
#if defined(__LP64__) && !defined(__x86_64__)
#ifdef __BIONIC__
extern uintptr_t CreateStartPos(uint64_t input);
#endif
TEST_F(MemMapTest, Start) {
uintptr_t start = GetLinearScanPos();
EXPECT_LE(64 * KB, start);
EXPECT_LT(start, static_cast<uintptr_t>(ART_BASE_ADDRESS));
#ifdef __BIONIC__
// Test a couple of values. Make sure they are different.
uintptr_t last = 0;
for (size_t i = 0; i < 100; ++i) {
uintptr_t random_start = CreateStartPos(i * kPageSize);
EXPECT_NE(last, random_start);
last = random_start;
}
// Even on max, should be below ART_BASE_ADDRESS.
EXPECT_LT(CreateStartPos(~0), static_cast<uintptr_t>(ART_BASE_ADDRESS));
#endif
// End of test.
}
#endif
TEST_F(MemMapTest, MapAnonymousEmpty) {
std::string error_msg;
std::unique_ptr<MemMap> map(MemMap::MapAnonymous("MapAnonymousEmpty",
nullptr,
0,
PROT_READ,
false,
&error_msg));
ASSERT_TRUE(map.get() != nullptr) << error_msg;
ASSERT_TRUE(error_msg.empty());
map.reset(MemMap::MapAnonymous("MapAnonymousEmpty",
nullptr,
kPageSize,
PROT_READ | PROT_WRITE,
false,
&error_msg));
ASSERT_TRUE(map.get() != nullptr) << error_msg;
ASSERT_TRUE(error_msg.empty());
}
#ifdef __LP64__
TEST_F(MemMapTest, MapAnonymousEmpty32bit) {
std::string error_msg;
std::unique_ptr<MemMap> map(MemMap::MapAnonymous("MapAnonymousEmpty",
nullptr,
kPageSize,
PROT_READ | PROT_WRITE,
true,
&error_msg));
ASSERT_TRUE(map.get() != nullptr) << error_msg;
ASSERT_TRUE(error_msg.empty());
ASSERT_LT(reinterpret_cast<uintptr_t>(BaseBegin(map.get())), 1ULL << 32);
}
#endif
TEST_F(MemMapTest, MapAnonymousExactAddr) {
std::string error_msg;
// Map at an address that should work, which should succeed.
std::unique_ptr<MemMap> map0(MemMap::MapAnonymous("MapAnonymous0",
reinterpret_cast<byte*>(ART_BASE_ADDRESS),
kPageSize,
PROT_READ | PROT_WRITE,
false,
&error_msg));
ASSERT_TRUE(map0.get() != nullptr) << error_msg;
ASSERT_TRUE(error_msg.empty());
ASSERT_TRUE(map0->BaseBegin() == reinterpret_cast<void*>(ART_BASE_ADDRESS));
// Map at an unspecified address, which should succeed.
std::unique_ptr<MemMap> map1(MemMap::MapAnonymous("MapAnonymous1",
nullptr,
kPageSize,
PROT_READ | PROT_WRITE,
false,
&error_msg));
ASSERT_TRUE(map1.get() != nullptr) << error_msg;
ASSERT_TRUE(error_msg.empty());
ASSERT_TRUE(map1->BaseBegin() != nullptr);
// Attempt to map at the same address, which should fail.
std::unique_ptr<MemMap> map2(MemMap::MapAnonymous("MapAnonymous2",
reinterpret_cast<byte*>(map1->BaseBegin()),
kPageSize,
PROT_READ | PROT_WRITE,
false,
&error_msg));
ASSERT_TRUE(map2.get() == nullptr) << error_msg;
ASSERT_TRUE(!error_msg.empty());
}
TEST_F(MemMapTest, RemapAtEnd) {
RemapAtEndTest(false);
}
#ifdef __LP64__
TEST_F(MemMapTest, RemapAtEnd32bit) {
RemapAtEndTest(true);
}
#endif
TEST_F(MemMapTest, MapAnonymousExactAddr32bitHighAddr) {
uintptr_t start_addr = ART_BASE_ADDRESS + 0x1000000;
std::string error_msg;
std::unique_ptr<MemMap> map(MemMap::MapAnonymous("MapAnonymousExactAddr32bitHighAddr",
reinterpret_cast<byte*>(start_addr),
0x21000000,
PROT_READ | PROT_WRITE,
true,
&error_msg));
ASSERT_TRUE(map.get() != nullptr) << error_msg;
ASSERT_TRUE(error_msg.empty());
ASSERT_EQ(reinterpret_cast<uintptr_t>(BaseBegin(map.get())), start_addr);
}
TEST_F(MemMapTest, MapAnonymousOverflow) {
std::string error_msg;
uintptr_t ptr = 0;
ptr -= kPageSize; // Now it's close to the top.
std::unique_ptr<MemMap> map(MemMap::MapAnonymous("MapAnonymousOverflow",
reinterpret_cast<byte*>(ptr),
2 * kPageSize, // brings it over the top.
PROT_READ | PROT_WRITE,
false,
&error_msg));
ASSERT_EQ(nullptr, map.get());
ASSERT_FALSE(error_msg.empty());
}
#ifdef __LP64__
TEST_F(MemMapTest, MapAnonymousLow4GBExpectedTooHigh) {
std::string error_msg;
std::unique_ptr<MemMap> map(MemMap::MapAnonymous("MapAnonymousLow4GBExpectedTooHigh",
reinterpret_cast<byte*>(UINT64_C(0x100000000)),
kPageSize,
PROT_READ | PROT_WRITE,
true,
&error_msg));
ASSERT_EQ(nullptr, map.get());
ASSERT_FALSE(error_msg.empty());
}
TEST_F(MemMapTest, MapAnonymousLow4GBRangeTooHigh) {
std::string error_msg;
std::unique_ptr<MemMap> map(MemMap::MapAnonymous("MapAnonymousLow4GBRangeTooHigh",
reinterpret_cast<byte*>(0xF0000000),
0x20000000,
PROT_READ | PROT_WRITE,
true,
&error_msg));
ASSERT_EQ(nullptr, map.get());
ASSERT_FALSE(error_msg.empty());
}
#endif
TEST_F(MemMapTest, CheckNoGaps) {
std::string error_msg;
constexpr size_t kNumPages = 3;
// Map a 3-page mem map.
std::unique_ptr<MemMap> map(MemMap::MapAnonymous("MapAnonymous0",
nullptr,
kPageSize * kNumPages,
PROT_READ | PROT_WRITE,
false,
&error_msg));
ASSERT_TRUE(map.get() != nullptr) << error_msg;
ASSERT_TRUE(error_msg.empty());
// Record the base address.
byte* map_base = reinterpret_cast<byte*>(map->BaseBegin());
// Unmap it.
map.reset();
// Map at the same address, but in page-sized separate mem maps,
// assuming the space at the address is still available.
std::unique_ptr<MemMap> map0(MemMap::MapAnonymous("MapAnonymous0",
map_base,
kPageSize,
PROT_READ | PROT_WRITE,
false,
&error_msg));
ASSERT_TRUE(map0.get() != nullptr) << error_msg;
ASSERT_TRUE(error_msg.empty());
std::unique_ptr<MemMap> map1(MemMap::MapAnonymous("MapAnonymous1",
map_base + kPageSize,
kPageSize,
PROT_READ | PROT_WRITE,
false,
&error_msg));
ASSERT_TRUE(map1.get() != nullptr) << error_msg;
ASSERT_TRUE(error_msg.empty());
std::unique_ptr<MemMap> map2(MemMap::MapAnonymous("MapAnonymous2",
map_base + kPageSize * 2,
kPageSize,
PROT_READ | PROT_WRITE,
false,
&error_msg));
ASSERT_TRUE(map2.get() != nullptr) << error_msg;
ASSERT_TRUE(error_msg.empty());
// One-map cases.
ASSERT_TRUE(MemMap::CheckNoGaps(map0.get(), map0.get()));
ASSERT_TRUE(MemMap::CheckNoGaps(map1.get(), map1.get()));
ASSERT_TRUE(MemMap::CheckNoGaps(map2.get(), map2.get()));
// Two or three-map cases.
ASSERT_TRUE(MemMap::CheckNoGaps(map0.get(), map1.get()));
ASSERT_TRUE(MemMap::CheckNoGaps(map1.get(), map2.get()));
ASSERT_TRUE(MemMap::CheckNoGaps(map0.get(), map2.get()));
// Unmap the middle one.
map1.reset();
// Should return false now that there's a gap in the middle.
ASSERT_FALSE(MemMap::CheckNoGaps(map0.get(), map2.get()));
}
} // namespace art
<|endoftext|> |
<commit_before>/*************************************************************************
*
* OpenOffice.org - a multi-platform office productivity suite
*
* $RCSfile: TaskPaneFocusManager.cxx,v $
*
* $Revision: 1.4 $
*
* last change: $Author: rt $ $Date: 2005-09-09 06:33:01 $
*
* 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
*
************************************************************************/
#include "TaskPaneFocusManager.hxx"
#include <vcl/window.hxx>
#ifndef _VOS_MUTEX_HXX_
#include <vos/mutex.hxx>
#endif
#ifndef _SV_SVAPP_HXX
#include <vcl/svapp.hxx>
#endif
#ifndef _SV_EVENT_HXX
#include <vcl/event.hxx>
#endif
#include <hash_map>
namespace {
class WindowHash
{
public:
size_t operator()(::Window* argument) const
{ return reinterpret_cast<unsigned long>(argument); }
};
class EventDescriptor
{
public:
EventDescriptor (const KeyCode& rKey, ::Window* pWindow)
: maKeyCode(rKey), mpTargetWindow(pWindow) {}
KeyCode maKeyCode;
::Window* mpTargetWindow;
};
} // end of anonymous namespace
namespace sd { namespace toolpanel {
class FocusManager::LinkMap : public ::std::hash_multimap< ::Window*, EventDescriptor, WindowHash>
{
};
FocusManager* FocusManager::spInstance = NULL;
FocusManager& FocusManager::Instance (void)
{
if (spInstance == NULL)
{
::vos::OGuard aGuard (::Application::GetSolarMutex());
if (spInstance == NULL)
spInstance = new FocusManager ();
}
return *spInstance;
}
FocusManager::FocusManager (void)
: mpLinks(new LinkMap())
{
}
FocusManager::~FocusManager (void)
{
}
void FocusManager::RegisterUpLink (::Window* pSource, ::Window* pTarget)
{
RegisterLink(pSource, pTarget, KEY_ESCAPE);
}
void FocusManager::RegisterDownLink (::Window* pSource, ::Window* pTarget)
{
RegisterLink(pSource, pTarget, KEY_RETURN);
}
void FocusManager::RegisterLink (
::Window* pSource,
::Window* pTarget,
const KeyCode& rKey)
{
// Register this focus manager as event listener at the source window.
if (mpLinks->equal_range(pSource).first == mpLinks->end())
pSource->AddEventListener (LINK (this, FocusManager, WindowEventListener));
mpLinks->insert(LinkMap::value_type(pSource, EventDescriptor(rKey,pTarget)));
}
void FocusManager::RemoveLinks (
::Window* pSourceWindow,
::Window* pTargetWindow)
{
::std::pair<LinkMap::iterator,LinkMap::iterator> aCandidates;
LinkMap::iterator iCandidate;
bool bLoop (mpLinks->size() > 0);
while (bLoop)
{
aCandidates = mpLinks->equal_range(pSourceWindow);
if (aCandidates.first == mpLinks->end())
{
// No links for the source window found -> nothing more to do.
bLoop = false;
}
else
{
// Set the loop control to false so that when no candidate for
// deletion is found the loop is left.
bLoop = false;
for (iCandidate=aCandidates.first; iCandidate!=aCandidates.second; ++iCandidate)
if (iCandidate->second.mpTargetWindow == pTargetWindow)
{
mpLinks->erase(iCandidate);
// One link erased. The iterators have become invalid so
// start the search for links to delete anew.
bLoop = true;
break;
}
}
}
RemoveUnusedEventListener(pSourceWindow);
}
void FocusManager::RemoveLinks (::Window* pWindow)
{
// Remove the links from the given window.
::std::pair<LinkMap::iterator,LinkMap::iterator> aCandidates(mpLinks->equal_range(pWindow));
mpLinks->erase(aCandidates.first, aCandidates.second);
pWindow->RemoveEventListener (LINK (this, FocusManager, WindowEventListener));
// Remove links to the given window.
bool bLinkRemoved (false);
do
{
LinkMap::iterator iLink;
for (iLink=mpLinks->begin(); iLink!=mpLinks->end(); ++iLink)
{
if (iLink->second.mpTargetWindow == pWindow)
{
mpLinks->erase(iLink);
RemoveUnusedEventListener(iLink->first);
bLinkRemoved;
break;
}
}
}
while (bLinkRemoved);
}
void FocusManager::RemoveUnusedEventListener (::Window* pWindow)
{
// When there are no more links from the window to another window
// then remove the event listener from the window.
if (mpLinks->find(pWindow) == mpLinks->end())
pWindow->RemoveEventListener (LINK (this, FocusManager, WindowEventListener));
}
bool FocusManager::TransferFocus (
::Window* pSourceWindow,
const KeyCode& rKeyCode)
{
bool bSuccess (false);
::std::pair<LinkMap::iterator,LinkMap::iterator> aCandidates (
mpLinks->equal_range(pSourceWindow));
LinkMap::const_iterator iCandidate;
for (iCandidate=aCandidates.first; iCandidate!=aCandidates.second; ++iCandidate)
if (iCandidate->second.maKeyCode == rKeyCode)
{
iCandidate->second.mpTargetWindow->GrabFocus();
bSuccess = true;
break;
}
return bSuccess;
}
IMPL_LINK(FocusManager, WindowEventListener, VclSimpleEvent*, pEvent)
{
if (pEvent!=NULL && pEvent->ISA(VclWindowEvent))
{
VclWindowEvent* pWindowEvent = static_cast<VclWindowEvent*>(pEvent);
switch (pWindowEvent->GetId())
{
case VCLEVENT_WINDOW_KEYINPUT:
{
Window* pSource = pWindowEvent->GetWindow();
KeyEvent* pKeyEvent = static_cast<KeyEvent*>(pWindowEvent->GetData());
TransferFocus(pSource, pKeyEvent->GetKeyCode());
}
break;
case VCLEVENT_OBJECT_DYING:
RemoveLinks(pWindowEvent->GetWindow());
break;
}
}
return 1;
}
} } // end of namespace ::sd::toolpanel
<commit_msg>INTEGRATION: CWS pchfix02 (1.4.280); FILE MERGED 2006/09/01 17:37:22 kaib 1.4.280.1: #i68856# Added header markers and pch files<commit_after>/*************************************************************************
*
* OpenOffice.org - a multi-platform office productivity suite
*
* $RCSfile: TaskPaneFocusManager.cxx,v $
*
* $Revision: 1.5 $
*
* last change: $Author: obo $ $Date: 2006-09-16 19:14:24 $
*
* 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_sd.hxx"
#include "TaskPaneFocusManager.hxx"
#include <vcl/window.hxx>
#ifndef _VOS_MUTEX_HXX_
#include <vos/mutex.hxx>
#endif
#ifndef _SV_SVAPP_HXX
#include <vcl/svapp.hxx>
#endif
#ifndef _SV_EVENT_HXX
#include <vcl/event.hxx>
#endif
#include <hash_map>
namespace {
class WindowHash
{
public:
size_t operator()(::Window* argument) const
{ return reinterpret_cast<unsigned long>(argument); }
};
class EventDescriptor
{
public:
EventDescriptor (const KeyCode& rKey, ::Window* pWindow)
: maKeyCode(rKey), mpTargetWindow(pWindow) {}
KeyCode maKeyCode;
::Window* mpTargetWindow;
};
} // end of anonymous namespace
namespace sd { namespace toolpanel {
class FocusManager::LinkMap : public ::std::hash_multimap< ::Window*, EventDescriptor, WindowHash>
{
};
FocusManager* FocusManager::spInstance = NULL;
FocusManager& FocusManager::Instance (void)
{
if (spInstance == NULL)
{
::vos::OGuard aGuard (::Application::GetSolarMutex());
if (spInstance == NULL)
spInstance = new FocusManager ();
}
return *spInstance;
}
FocusManager::FocusManager (void)
: mpLinks(new LinkMap())
{
}
FocusManager::~FocusManager (void)
{
}
void FocusManager::RegisterUpLink (::Window* pSource, ::Window* pTarget)
{
RegisterLink(pSource, pTarget, KEY_ESCAPE);
}
void FocusManager::RegisterDownLink (::Window* pSource, ::Window* pTarget)
{
RegisterLink(pSource, pTarget, KEY_RETURN);
}
void FocusManager::RegisterLink (
::Window* pSource,
::Window* pTarget,
const KeyCode& rKey)
{
// Register this focus manager as event listener at the source window.
if (mpLinks->equal_range(pSource).first == mpLinks->end())
pSource->AddEventListener (LINK (this, FocusManager, WindowEventListener));
mpLinks->insert(LinkMap::value_type(pSource, EventDescriptor(rKey,pTarget)));
}
void FocusManager::RemoveLinks (
::Window* pSourceWindow,
::Window* pTargetWindow)
{
::std::pair<LinkMap::iterator,LinkMap::iterator> aCandidates;
LinkMap::iterator iCandidate;
bool bLoop (mpLinks->size() > 0);
while (bLoop)
{
aCandidates = mpLinks->equal_range(pSourceWindow);
if (aCandidates.first == mpLinks->end())
{
// No links for the source window found -> nothing more to do.
bLoop = false;
}
else
{
// Set the loop control to false so that when no candidate for
// deletion is found the loop is left.
bLoop = false;
for (iCandidate=aCandidates.first; iCandidate!=aCandidates.second; ++iCandidate)
if (iCandidate->second.mpTargetWindow == pTargetWindow)
{
mpLinks->erase(iCandidate);
// One link erased. The iterators have become invalid so
// start the search for links to delete anew.
bLoop = true;
break;
}
}
}
RemoveUnusedEventListener(pSourceWindow);
}
void FocusManager::RemoveLinks (::Window* pWindow)
{
// Remove the links from the given window.
::std::pair<LinkMap::iterator,LinkMap::iterator> aCandidates(mpLinks->equal_range(pWindow));
mpLinks->erase(aCandidates.first, aCandidates.second);
pWindow->RemoveEventListener (LINK (this, FocusManager, WindowEventListener));
// Remove links to the given window.
bool bLinkRemoved (false);
do
{
LinkMap::iterator iLink;
for (iLink=mpLinks->begin(); iLink!=mpLinks->end(); ++iLink)
{
if (iLink->second.mpTargetWindow == pWindow)
{
mpLinks->erase(iLink);
RemoveUnusedEventListener(iLink->first);
bLinkRemoved;
break;
}
}
}
while (bLinkRemoved);
}
void FocusManager::RemoveUnusedEventListener (::Window* pWindow)
{
// When there are no more links from the window to another window
// then remove the event listener from the window.
if (mpLinks->find(pWindow) == mpLinks->end())
pWindow->RemoveEventListener (LINK (this, FocusManager, WindowEventListener));
}
bool FocusManager::TransferFocus (
::Window* pSourceWindow,
const KeyCode& rKeyCode)
{
bool bSuccess (false);
::std::pair<LinkMap::iterator,LinkMap::iterator> aCandidates (
mpLinks->equal_range(pSourceWindow));
LinkMap::const_iterator iCandidate;
for (iCandidate=aCandidates.first; iCandidate!=aCandidates.second; ++iCandidate)
if (iCandidate->second.maKeyCode == rKeyCode)
{
iCandidate->second.mpTargetWindow->GrabFocus();
bSuccess = true;
break;
}
return bSuccess;
}
IMPL_LINK(FocusManager, WindowEventListener, VclSimpleEvent*, pEvent)
{
if (pEvent!=NULL && pEvent->ISA(VclWindowEvent))
{
VclWindowEvent* pWindowEvent = static_cast<VclWindowEvent*>(pEvent);
switch (pWindowEvent->GetId())
{
case VCLEVENT_WINDOW_KEYINPUT:
{
Window* pSource = pWindowEvent->GetWindow();
KeyEvent* pKeyEvent = static_cast<KeyEvent*>(pWindowEvent->GetData());
TransferFocus(pSource, pKeyEvent->GetKeyCode());
}
break;
case VCLEVENT_OBJECT_DYING:
RemoveLinks(pWindowEvent->GetWindow());
break;
}
}
return 1;
}
} } // end of namespace ::sd::toolpanel
<|endoftext|> |
<commit_before>/*************************************************************************
*
* $RCSfile: javachild.cxx,v $
*
* $Revision: 1.4 $
*
* last change: $Author: rt $ $Date: 2005-01-31 09:48:09 $
*
* The Contents of this file are made available subject to the terms of
* either of the following licenses
*
* - GNU Lesser General Public License Version 2.1
* - Sun Industry Standards Source License Version 1.1
*
* Sun Microsystems Inc., October, 2000
*
* GNU Lesser General Public License Version 2.1
* =============================================
* Copyright 2000 by Sun Microsystems, Inc.
* 901 San Antonio Road, Palo Alto, CA 94303, USA
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License version 2.1, as published by the Free Software Foundation.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston,
* MA 02111-1307 USA
*
*
* Sun Industry Standards Source License Version 1.1
* =================================================
* The contents of this file are subject to the Sun Industry Standards
* Source License Version 1.1 (the "License"); You may not use this file
* except in compliance with the License. You may obtain a copy of the
* License at http://www.openoffice.org/license.html.
*
* Software provided under this License is provided on an "AS IS" basis,
* WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING,
* WITHOUT LIMITATION, WARRANTIES THAT THE SOFTWARE IS FREE OF DEFECTS,
* MERCHANTABLE, FIT FOR A PARTICULAR PURPOSE, OR NON-INFRINGING.
* See the License for the specific provisions governing your rights and
* obligations concerning the Software.
*
* The Initial Developer of the Original Code is: Sun Microsystems, Inc.
*
* Copyright: 2000 by Sun Microsystems, Inc.
*
* All Rights Reserved.
*
* Contributor(s): _______________________________________
*
*
************************************************************************/
#ifdef SOLAR_JAVA
#include <jni.h>
#endif
#ifndef _COMPHELPER_PROCESSFACTORY_HXX_
#include <comphelper/processfactory.hxx>
#endif
#include <unohelp.hxx>
#include <rtl/process.h>
#include <rtl/ref.hxx>
#include <jvmaccess/virtualmachine.hxx>
#include <com/sun/star/java/XJavaVM.hpp>
#include <com/sun/star/java/XJavaThreadRegister_11.hpp>
#include <com/sun/star/lang/XMultiServiceFactory.hpp>
#ifndef _SV_SVSYS_HXX
#include <svsys.h>
#endif
#ifndef _SV_SALINST_HXX
#include <salinst.hxx>
#endif
#ifndef _SV_SALFRAME_HXX
#include <salframe.hxx>
#endif
#include <window.hxx>
#ifndef _SV_SALOBJ_HXX
#include <salobj.hxx>
#endif
#include "javachild.hxx"
#include <svdata.hxx>
#include <sysdata.hxx>
using namespace ::com::sun::star;
// -------------------
// - JavaChildWindow -
// -------------------
JavaChildWindow::JavaChildWindow( Window* pParent, WinBits nStyle ) :
SystemChildWindow( pParent, nStyle )
{
}
// -----------------------------------------------------------------------
JavaChildWindow::JavaChildWindow( Window* pParent, const ResId& rResId ) :
SystemChildWindow( pParent, rResId )
{
}
// -----------------------------------------------------------------------
JavaChildWindow::~JavaChildWindow()
{
}
// -----------------------------------------------------------------------
void JavaChildWindow::implTestJavaException( void* pEnv )
{
#ifdef SOLAR_JAVA
JNIEnv* pJavaEnv = reinterpret_cast< JNIEnv* >( pEnv );
jthrowable jtThrowable = pJavaEnv->ExceptionOccurred();
if( jtThrowable )
{ // is it a java exception ?
#if OSL_DEBUG_LEVEL > 1
pJavaEnv->ExceptionDescribe();
#endif // OSL_DEBUG_LEVEL > 1
pJavaEnv->ExceptionClear();
jclass jcThrowable = pJavaEnv->FindClass("java/lang/Throwable");
jmethodID jmThrowable_getMessage = pJavaEnv->GetMethodID(jcThrowable, "getMessage", "()Ljava/lang/String;");
jstring jsMessage = (jstring) pJavaEnv->CallObjectMethod(jtThrowable, jmThrowable_getMessage);
::rtl::OUString ouMessage;
if(jsMessage)
{
const jchar * jcMessage = pJavaEnv->GetStringChars(jsMessage, NULL);
ouMessage = ::rtl::OUString(jcMessage);
pJavaEnv->ReleaseStringChars(jsMessage, jcMessage);
}
throw uno::RuntimeException(ouMessage, uno::Reference<uno::XInterface>());
}
#endif // SOLAR_JAVA
}
// -----------------------------------------------------------------------
sal_Int32 JavaChildWindow::getParentWindowHandleForJava()
{
sal_Int32 nRet = 0;
#if defined WNT
nRet = reinterpret_cast< sal_Int32 >( GetSystemData()->hWnd );
#elif defined UNX
#ifdef SOLAR_JAVA
uno::Reference< lang::XMultiServiceFactory > xFactory( vcl::unohelper::GetMultiServiceFactory() );
if( xFactory.is() && ( GetSystemData()->aWindow > 0 ) )
{
try
{
JavaVM* pJVM;
::rtl::Reference< ::jvmaccess::VirtualMachine > xVM;
uno::Reference< java::XJavaVM > xJavaVM( xFactory->createInstance( rtl::OUString(RTL_CONSTASCII_USTRINGPARAM("com.sun.star.java.JavaVirtualMachine") ) ), uno::UNO_QUERY );
uno::Sequence< sal_Int8 > aProcessID( 17 );
rtl_getGlobalProcessId( (sal_uInt8*) aProcessID.getArray() );
aProcessID[ 16 ] = 0;
OSL_ENSURE(sizeof (sal_Int64) >= sizeof (jvmaccess::VirtualMachine *), "Pointer cannot be represented as sal_Int64");
sal_Int64 nPointer = reinterpret_cast< sal_Int64 >( static_cast< jvmaccess::VirtualMachine * >(0));
xJavaVM->getJavaVM(aProcessID) >>= nPointer;
xVM = reinterpret_cast< jvmaccess::VirtualMachine * >(nPointer);
if( xVM.is() )
{
try
{
::jvmaccess::VirtualMachine::AttachGuard aVMAttachGuard( xVM );
JNIEnv* pEnv = aVMAttachGuard.getEnvironment();
jclass jcToolkit = pEnv->FindClass("java/awt/Toolkit");
implTestJavaException(pEnv);
jmethodID jmToolkit_getDefaultToolkit = pEnv->GetStaticMethodID( jcToolkit, "getDefaultToolkit", "()Ljava/awt/Toolkit;" );
implTestJavaException(pEnv);
pEnv->CallStaticObjectMethod(jcToolkit, jmToolkit_getDefaultToolkit);
implTestJavaException(pEnv);
jclass jcMotifAppletViewer = pEnv->FindClass("sun/plugin/navig/motif/MotifAppletViewer");
if( pEnv->ExceptionOccurred() )
{
pEnv->ExceptionClear();
jcMotifAppletViewer = pEnv->FindClass( "sun/plugin/viewer/MNetscapePluginContext");
implTestJavaException(pEnv);
}
jclass jcClassLoader = pEnv->FindClass("java/lang/ClassLoader");
implTestJavaException(pEnv);
jmethodID jmClassLoader_loadLibrary = pEnv->GetStaticMethodID( jcClassLoader, "loadLibrary", "(Ljava/lang/Class;Ljava/lang/String;Z)V");
implTestJavaException(pEnv);
jstring jsplugin = pEnv->NewStringUTF("javaplugin_jni");
implTestJavaException(pEnv);
pEnv->CallStaticVoidMethod(jcClassLoader, jmClassLoader_loadLibrary, jcMotifAppletViewer, jsplugin, JNI_FALSE);
implTestJavaException(pEnv);
jmethodID jmMotifAppletViewer_getWidget = pEnv->GetStaticMethodID( jcMotifAppletViewer, "getWidget", "(IIIII)I" );
implTestJavaException(pEnv);
const Size aSize( GetOutputSizePixel() );
jint ji_widget = pEnv->CallStaticIntMethod( jcMotifAppletViewer, jmMotifAppletViewer_getWidget,
GetSystemData()->aWindow, 0, 0, aSize.Width(), aSize.Height() );
implTestJavaException(pEnv);
nRet = static_cast< sal_Int32 >( ji_widget );
}
catch( uno::RuntimeException& )
{
}
if( !nRet )
nRet = static_cast< sal_Int32 >( GetSystemData()->aWindow );
}
}
catch( ... )
{
}
}
#endif // SOLAR_JAVA
#else // WNT || UNX
// TBD
#endif
return nRet;
}
<commit_msg>INTEGRATION: CWS ooo19126 (1.4.246); FILE MERGED 2005/09/05 14:45:14 rt 1.4.246.1: #i54170# Change license header: remove SISSL<commit_after>/*************************************************************************
*
* OpenOffice.org - a multi-platform office productivity suite
*
* $RCSfile: javachild.cxx,v $
*
* $Revision: 1.5 $
*
* last change: $Author: rt $ $Date: 2005-09-09 12:26:20 $
*
* 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
*
************************************************************************/
#ifdef SOLAR_JAVA
#include <jni.h>
#endif
#ifndef _COMPHELPER_PROCESSFACTORY_HXX_
#include <comphelper/processfactory.hxx>
#endif
#include <unohelp.hxx>
#include <rtl/process.h>
#include <rtl/ref.hxx>
#include <jvmaccess/virtualmachine.hxx>
#include <com/sun/star/java/XJavaVM.hpp>
#include <com/sun/star/java/XJavaThreadRegister_11.hpp>
#include <com/sun/star/lang/XMultiServiceFactory.hpp>
#ifndef _SV_SVSYS_HXX
#include <svsys.h>
#endif
#ifndef _SV_SALINST_HXX
#include <salinst.hxx>
#endif
#ifndef _SV_SALFRAME_HXX
#include <salframe.hxx>
#endif
#include <window.hxx>
#ifndef _SV_SALOBJ_HXX
#include <salobj.hxx>
#endif
#include "javachild.hxx"
#include <svdata.hxx>
#include <sysdata.hxx>
using namespace ::com::sun::star;
// -------------------
// - JavaChildWindow -
// -------------------
JavaChildWindow::JavaChildWindow( Window* pParent, WinBits nStyle ) :
SystemChildWindow( pParent, nStyle )
{
}
// -----------------------------------------------------------------------
JavaChildWindow::JavaChildWindow( Window* pParent, const ResId& rResId ) :
SystemChildWindow( pParent, rResId )
{
}
// -----------------------------------------------------------------------
JavaChildWindow::~JavaChildWindow()
{
}
// -----------------------------------------------------------------------
void JavaChildWindow::implTestJavaException( void* pEnv )
{
#ifdef SOLAR_JAVA
JNIEnv* pJavaEnv = reinterpret_cast< JNIEnv* >( pEnv );
jthrowable jtThrowable = pJavaEnv->ExceptionOccurred();
if( jtThrowable )
{ // is it a java exception ?
#if OSL_DEBUG_LEVEL > 1
pJavaEnv->ExceptionDescribe();
#endif // OSL_DEBUG_LEVEL > 1
pJavaEnv->ExceptionClear();
jclass jcThrowable = pJavaEnv->FindClass("java/lang/Throwable");
jmethodID jmThrowable_getMessage = pJavaEnv->GetMethodID(jcThrowable, "getMessage", "()Ljava/lang/String;");
jstring jsMessage = (jstring) pJavaEnv->CallObjectMethod(jtThrowable, jmThrowable_getMessage);
::rtl::OUString ouMessage;
if(jsMessage)
{
const jchar * jcMessage = pJavaEnv->GetStringChars(jsMessage, NULL);
ouMessage = ::rtl::OUString(jcMessage);
pJavaEnv->ReleaseStringChars(jsMessage, jcMessage);
}
throw uno::RuntimeException(ouMessage, uno::Reference<uno::XInterface>());
}
#endif // SOLAR_JAVA
}
// -----------------------------------------------------------------------
sal_Int32 JavaChildWindow::getParentWindowHandleForJava()
{
sal_Int32 nRet = 0;
#if defined WNT
nRet = reinterpret_cast< sal_Int32 >( GetSystemData()->hWnd );
#elif defined UNX
#ifdef SOLAR_JAVA
uno::Reference< lang::XMultiServiceFactory > xFactory( vcl::unohelper::GetMultiServiceFactory() );
if( xFactory.is() && ( GetSystemData()->aWindow > 0 ) )
{
try
{
JavaVM* pJVM;
::rtl::Reference< ::jvmaccess::VirtualMachine > xVM;
uno::Reference< java::XJavaVM > xJavaVM( xFactory->createInstance( rtl::OUString(RTL_CONSTASCII_USTRINGPARAM("com.sun.star.java.JavaVirtualMachine") ) ), uno::UNO_QUERY );
uno::Sequence< sal_Int8 > aProcessID( 17 );
rtl_getGlobalProcessId( (sal_uInt8*) aProcessID.getArray() );
aProcessID[ 16 ] = 0;
OSL_ENSURE(sizeof (sal_Int64) >= sizeof (jvmaccess::VirtualMachine *), "Pointer cannot be represented as sal_Int64");
sal_Int64 nPointer = reinterpret_cast< sal_Int64 >( static_cast< jvmaccess::VirtualMachine * >(0));
xJavaVM->getJavaVM(aProcessID) >>= nPointer;
xVM = reinterpret_cast< jvmaccess::VirtualMachine * >(nPointer);
if( xVM.is() )
{
try
{
::jvmaccess::VirtualMachine::AttachGuard aVMAttachGuard( xVM );
JNIEnv* pEnv = aVMAttachGuard.getEnvironment();
jclass jcToolkit = pEnv->FindClass("java/awt/Toolkit");
implTestJavaException(pEnv);
jmethodID jmToolkit_getDefaultToolkit = pEnv->GetStaticMethodID( jcToolkit, "getDefaultToolkit", "()Ljava/awt/Toolkit;" );
implTestJavaException(pEnv);
pEnv->CallStaticObjectMethod(jcToolkit, jmToolkit_getDefaultToolkit);
implTestJavaException(pEnv);
jclass jcMotifAppletViewer = pEnv->FindClass("sun/plugin/navig/motif/MotifAppletViewer");
if( pEnv->ExceptionOccurred() )
{
pEnv->ExceptionClear();
jcMotifAppletViewer = pEnv->FindClass( "sun/plugin/viewer/MNetscapePluginContext");
implTestJavaException(pEnv);
}
jclass jcClassLoader = pEnv->FindClass("java/lang/ClassLoader");
implTestJavaException(pEnv);
jmethodID jmClassLoader_loadLibrary = pEnv->GetStaticMethodID( jcClassLoader, "loadLibrary", "(Ljava/lang/Class;Ljava/lang/String;Z)V");
implTestJavaException(pEnv);
jstring jsplugin = pEnv->NewStringUTF("javaplugin_jni");
implTestJavaException(pEnv);
pEnv->CallStaticVoidMethod(jcClassLoader, jmClassLoader_loadLibrary, jcMotifAppletViewer, jsplugin, JNI_FALSE);
implTestJavaException(pEnv);
jmethodID jmMotifAppletViewer_getWidget = pEnv->GetStaticMethodID( jcMotifAppletViewer, "getWidget", "(IIIII)I" );
implTestJavaException(pEnv);
const Size aSize( GetOutputSizePixel() );
jint ji_widget = pEnv->CallStaticIntMethod( jcMotifAppletViewer, jmMotifAppletViewer_getWidget,
GetSystemData()->aWindow, 0, 0, aSize.Width(), aSize.Height() );
implTestJavaException(pEnv);
nRet = static_cast< sal_Int32 >( ji_widget );
}
catch( uno::RuntimeException& )
{
}
if( !nRet )
nRet = static_cast< sal_Int32 >( GetSystemData()->aWindow );
}
}
catch( ... )
{
}
}
#endif // SOLAR_JAVA
#else // WNT || UNX
// TBD
#endif
return nRet;
}
<|endoftext|> |
<commit_before>/* pilot.cc KPilot
**
** Copyright (C) 1998-2001 by Dan Pilone <dan@kpilot.org>
** Copyright (C) 2003-2004 Reinhold Kainhofer <reinhold@kainhofer.com>
** Copyright (C) 2003-2006 Adriaan de Groot <groot@kde.org>
**
** These are the base class structures that reside on the
** handheld device -- databases and their parts.
*/
/*
** This program 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 program 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 program in a file called COPYING; if not, write to
** the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston,
** MA 02110-1301, USA.
*/
/*
** Bug reports and questions can be sent to kde-pim@kde.org
*/
#include "pilot.h"
#include <QtCore/QTextCodec>
#include <kcharsets.h>
#include <kglobal.h>
#include "options.h"
#include "pilotDatabase.h"
#include "pilotAppInfo.h"
#include "pilotRecord.h"
namespace Pilot
{
static QTextCodec *codec = 0L;
QString fromPilot( const char *c, int len )
{
// Obviously bogus length
if (len<1)
{
return QString();
}
// See if the C string is short
for (int i=0; i<len; ++i)
{
if (!c[i])
{
return codec->toUnicode(c,i);
}
}
// Use the whole length
return codec->toUnicode(c,len);
}
QString fromPilot( const char *c )
{
return codec->toUnicode(c);
}
QByteArray toPilot( const QString &s )
{
return codec->fromUnicode(s);
}
int toPilot( const QString &s, char *buf, int len)
{
// See toPilot() below.
memset( buf, 0, len );
int used = len;
QByteArray cbuf = codec->fromUnicode(s.constData(),used);
if (used > len)
{
used=len;
}
memcpy( buf, cbuf.data(), used );
return used;
}
int toPilot( const QString &s, unsigned char *buf, int len)
{
// Clear the buffer
memset( buf, 0, len );
// Convert to 8-bit encoding
int used = len;
QByteArray cbuf = codec->fromUnicode(s.constData(),used);
// Will it fit in the buffer?
if (used > len)
{
// Ought to be impossible, anyway, since 8-bit encodings
// are shorter than the UTF-8 encodings (1 byte per character
// vs. 1-or-more byte per character).
used=len;
}
// Fill the buffer with encoded data.
memcpy( buf, cbuf.data(), used );
return used;
}
bool setupPilotCodec(const QString &s)
{
FUNCTIONSETUP;
QString encoding(KGlobal::charsets()->encodingForName(s));
DEBUGKPILOT << "Using codec name" << s;
DEBUGKPILOT << "Creating codec" << encoding;
// if the desired codec can't be found, latin1 will be returned anyway, no need to do this manually
codec = KGlobal::charsets()->codecForName(encoding);
if (codec)
{
DEBUGKPILOT << "Got codec" << codec->name().constData();
}
return codec;
}
QString codecName()
{
return QString::fromLatin1(codec->name());
}
QString category(const struct CategoryAppInfo *info, unsigned int i)
{
if (!info || (i>=CATEGORY_COUNT))
{
return QString();
}
return codec->toUnicode(info->name[i],CATEGORY_SIZE-1);
}
int findCategory(const struct CategoryAppInfo *info,
const QString &selectedCategory,
bool unknownIsUnfiled)
{
FUNCTIONSETUP;
if (!info)
{
WARNINGKPILOT << "Bad CategoryAppInfo pointer";
return -1;
}
int currentCatID = -1;
for (unsigned int i=0; i<CATEGORY_COUNT; i++)
{
if (!info->name[i][0]) continue;
if (selectedCategory == category(info, i))
{
currentCatID = i;
break;
}
}
if (-1 == currentCatID)
{
DEBUGKPILOT << "Category name ["
<< selectedCategory << "] not found.";
}
else
{
DEBUGKPILOT << "Matched category" << currentCatID;
}
if ((currentCatID == -1) && unknownIsUnfiled)
currentCatID = 0;
return currentCatID;
}
int insertCategory(struct CategoryAppInfo *info,
const QString &label,
bool unknownIsUnfiled)
{
FUNCTIONSETUP;
if (!info)
{
WARNINGKPILOT << "Bad CategoryAppInfo pointer";
return -1;
}
int c = findCategory(info,label,unknownIsUnfiled);
if (c<0)
{
// This is the case when the category is not known
// and unknownIsUnfiled is false.
for (unsigned int i=0; i<CATEGORY_COUNT; i++)
{
if (!info->name[i][0])
{
c = i;
break;
}
}
if ((c>0) && (c < (int)CATEGORY_COUNT))
{
// 0 is always unfiled, can't change that.
toPilot(label,info->name[c],CATEGORY_SIZE);
}
else
{
WARNINGKPILOT << "Category name ["
<< label
<< "] could not be added.";
c = -1;
}
}
return c;
}
void dumpCategories(const struct CategoryAppInfo *info)
{
FUNCTIONSETUP;
if (!info)
{
WARNINGKPILOT << "Dumping bad pointer.";
return;
}
DEBUGKPILOT << "lastUniqueId:"
<< (int) info->lastUniqueID;
for (unsigned int i = 0; i < CATEGORY_COUNT; i++)
{
if (!info->name[i][0]) continue;
DEBUGKPILOT << i << '='
<< (int)(info->ID[i]) << " ["
<< info->name[i] << ']';
}
}
}
<commit_msg>Try to make toPilot() more sane. Reduce code duplication.<commit_after>/* pilot.cc KPilot
**
** Copyright (C) 1998-2001 by Dan Pilone <dan@kpilot.org>
** Copyright (C) 2003-2004 Reinhold Kainhofer <reinhold@kainhofer.com>
** Copyright (C) 2003-2006 Adriaan de Groot <groot@kde.org>
**
** These are the base class structures that reside on the
** handheld device -- databases and their parts.
*/
/*
** This program 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 program 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 program in a file called COPYING; if not, write to
** the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston,
** MA 02110-1301, USA.
*/
/*
** Bug reports and questions can be sent to kde-pim@kde.org
*/
#include "pilot.h"
#include <QtCore/QTextCodec>
#include <kcharsets.h>
#include <kglobal.h>
#include "options.h"
#include "pilotDatabase.h"
#include "pilotAppInfo.h"
#include "pilotRecord.h"
namespace Pilot
{
static QTextCodec *codec = 0L;
QString fromPilot( const char *c, int len )
{
// Obviously bogus length
if (len<1)
{
return QString();
}
// See if the C string is short
for (int i=0; i<len; ++i)
{
if (!c[i])
{
return codec->toUnicode(c,i);
}
}
// Use the whole length
return codec->toUnicode(c,len);
}
QString fromPilot( const char *c )
{
return codec->toUnicode(c);
}
QByteArray toPilot( const QString &s )
{
return codec->fromUnicode(s);
}
int toPilot( const QString &s, char *buf, int len)
{
FUNCTIONSETUPL(4);
// Clear out the entire buffer
memset( buf, 0, len );
if (len<1) // short-circuit for bad input
{
return 0;
}
// Convert at most len characters of s
QByteArray cbuf = codec->fromUnicode(
(s.length() > len) ? s.left(len) : s );
// How many characters was that, then?
int used = cbuf.size();
if (used > len)
{
// This ought to be impossible: converting len
// unicode characters to 8-bit should never
// generate more characters.
used=len;
WARNINGKPILOT << "Conversion to 8-bit of "
<< len << " characters yielded " << used;
}
// Get what's left (note no NUL termination)
memcpy( buf, cbuf.data(), used );
return used;
}
int toPilot( const QString &s, unsigned char *buf, int len)
{
return toPilot(s,reinterpret_cast<char *>(buf),len);
}
bool setupPilotCodec(const QString &s)
{
FUNCTIONSETUP;
QString encoding(KGlobal::charsets()->encodingForName(s));
DEBUGKPILOT << "Using codec name" << s;
DEBUGKPILOT << "Creating codec" << encoding;
// if the desired codec can't be found, latin1 will be returned anyway, no need to do this manually
codec = KGlobal::charsets()->codecForName(encoding);
if (codec)
{
DEBUGKPILOT << "Got codec" << codec->name().constData();
}
return codec;
}
QString codecName()
{
return QString::fromLatin1(codec->name());
}
QString category(const struct CategoryAppInfo *info, unsigned int i)
{
if (!info || (i>=CATEGORY_COUNT))
{
return QString();
}
return codec->toUnicode(info->name[i],CATEGORY_SIZE-1);
}
int findCategory(const struct CategoryAppInfo *info,
const QString &selectedCategory,
bool unknownIsUnfiled)
{
FUNCTIONSETUP;
if (!info)
{
WARNINGKPILOT << "Bad CategoryAppInfo pointer";
return -1;
}
int currentCatID = -1;
for (unsigned int i=0; i<CATEGORY_COUNT; i++)
{
if (!info->name[i][0]) continue;
if (selectedCategory == category(info, i))
{
currentCatID = i;
break;
}
}
if (-1 == currentCatID)
{
DEBUGKPILOT << "Category name ["
<< selectedCategory << "] not found.";
}
else
{
DEBUGKPILOT << "Matched category" << currentCatID;
}
if ((currentCatID == -1) && unknownIsUnfiled)
currentCatID = 0;
return currentCatID;
}
int insertCategory(struct CategoryAppInfo *info,
const QString &label,
bool unknownIsUnfiled)
{
FUNCTIONSETUP;
if (!info)
{
WARNINGKPILOT << "Bad CategoryAppInfo pointer";
return -1;
}
int c = findCategory(info,label,unknownIsUnfiled);
if (c<0)
{
// This is the case when the category is not known
// and unknownIsUnfiled is false.
for (unsigned int i=0; i<CATEGORY_COUNT; i++)
{
if (!info->name[i][0])
{
c = i;
break;
}
}
if ((c>0) && (c < (int)CATEGORY_COUNT))
{
// 0 is always unfiled, can't change that.
toPilot(label,info->name[c],CATEGORY_SIZE);
}
else
{
WARNINGKPILOT << "Category name ["
<< label
<< "] could not be added.";
c = -1;
}
}
return c;
}
void dumpCategories(const struct CategoryAppInfo *info)
{
FUNCTIONSETUP;
if (!info)
{
WARNINGKPILOT << "Dumping bad pointer.";
return;
}
DEBUGKPILOT << "lastUniqueId:"
<< (int) info->lastUniqueID;
for (unsigned int i = 0; i < CATEGORY_COUNT; i++)
{
if (!info->name[i][0]) continue;
DEBUGKPILOT << i << '='
<< (int)(info->ID[i]) << " ["
<< info->name[i] << ']';
}
}
}
<|endoftext|> |
<commit_before>/*=========================================================================
Program: Insight Segmentation & Registration Toolkit
Module: itkBioGene.cxx
Language: C++
Date: $Date$
Version: $Revision$
Copyright (c) 2002 Insight Consortium. All rights reserved.
See ITKCopyright.txt or http://www.itk.org/HTML/Copyright.htm for details.
This software is distributed WITHOUT ANY WARRANTY; without even
the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR
PURPOSE. See the above copyright notices for more information.
=========================================================================*/
#include "itkBioGene.h"
#include <algorithm>
namespace itk {
namespace bio {
/**
* Constructor
*/
Gene
::Gene()
{
m_Name = "Unknown";
}
/**
* Destructor
*/
Gene
::~Gene()
{
}
/**
* Copy from another genome
*/
void
Gene
::Copy( const Gene & gene )
{
m_Name = gene.m_Name;
m_ControlDomains.insert( m_ControlDomains.begin(),
gene.m_ControlDomains.begin(),
gene.m_ControlDomains.end() );
m_ProteinDomains.insert( gene.m_ProteinDomains.begin(),
gene.m_ProteinDomains.end() );
}
} // end namespace bio
} // end namespace itk
<commit_msg>FIX: std::map Insert problem<commit_after>/*=========================================================================
Program: Insight Segmentation & Registration Toolkit
Module: itkBioGene.cxx
Language: C++
Date: $Date$
Version: $Revision$
Copyright (c) 2002 Insight Consortium. All rights reserved.
See ITKCopyright.txt or http://www.itk.org/HTML/Copyright.htm for details.
This software is distributed WITHOUT ANY WARRANTY; without even
the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR
PURPOSE. See the above copyright notices for more information.
=========================================================================*/
#include "itkBioGene.h"
#include <algorithm>
namespace itk {
namespace bio {
/**
* Constructor
*/
Gene
::Gene()
{
m_Name = "Unknown";
}
/**
* Destructor
*/
Gene
::~Gene()
{
}
/**
* Copy from another genome
*/
void
Gene
::Copy( const Gene & gene )
{
m_Name = gene.m_Name;
m_ControlDomains.insert( m_ControlDomains.begin(),
gene.m_ControlDomains.begin(),
gene.m_ControlDomains.end() );
ProteinDomainsType::value_type first = (*gene.m_ProteinDomains.begin());
ProteinDomainsType::value_type last = (*gene.m_ProteinDomains.end());
m_ProteinDomains.insert(
&first,
&last);
}
} // end namespace bio
} // end namespace itk
<|endoftext|> |
<commit_before>#include "Main.h"
using namespace std;
using namespace experimental::filesystem;
int main() {
string PATH;
cout << "AudioFile Wizard Started" << endl;
cout << "Input file path" << endl;
cout << "Example: C:\\Program Files\\Java\\" << endl;
cout << "Enter Path: ", cin >> PATH;
return 0;
};<commit_msg>control print screen<commit_after>#include "Main.h"
using namespace std;
using namespace experimental::filesystem;
int main()
{
string PATH;
cout << "AudioFile Wizard Started" << endl;
cout << "Input file path" << endl;
cout << "Example: C:\\Program Files\\Java\\" << endl;
cout << "Enter Path: ", cin >> PATH;
return 0;
};
<|endoftext|> |
<commit_before>/*
Copyright (c) 2015-2016 Advanced Micro Devices, Inc. All rights reserved.
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.
*/
/* HIT_START
* BUILD: %t %s
* RUN: %t
* HIT_END
*/
#include <hip/hip_runtime_api.h>
#include <hip/hip_runtime.h>
#include <iostream>
#include "test_common.h"
#include <hip/device_functions.h>
#define HIP_ASSERT(x) (assert((x) == hipSuccess))
#define LEN 512
#define SIZE LEN << 2
#define TEST_DEBUG (0)
__global__ void kernel_trig(hipLaunchParm lp, float* In, float* sin_d, float* cos_d, float* tan_d,
float* sin_pd, float* cos_pd) {
int tid = threadIdx.x + blockIdx.x * blockDim.x;
sin_d[tid] = __sinf(In[tid]);
cos_d[tid] = __cosf(In[tid]);
tan_d[tid] = __tanf(In[tid]);
__sincosf(In[tid], &sin_pd[tid], &cos_pd[tid]);
}
int main() {
float *In, *sin_h, *cos_h, *tan_h, *sin_ph, *cos_ph;
float *In_d, *sin_d, *cos_d, *tan_d, *sin_pd, *cos_pd;
int errors = 0;
In = new float[LEN];
sin_h = new float[LEN];
cos_h = new float[LEN];
tan_h = new float[LEN];
sin_ph = new float[LEN];
cos_ph = new float[LEN];
for (int i = 0; i < LEN; i++) {
In[i] = 1.0f;
sin_h[i] = 0.0f;
cos_h[i] = 0.0f;
tan_h[i] = 0.0f;
sin_ph[i] = 0.0f;
cos_ph[i] = 0.0f;
}
HIP_ASSERT(hipMalloc((void**)&In_d, SIZE));
HIP_ASSERT(hipMalloc((void**)&sin_d, SIZE));
HIP_ASSERT(hipMalloc((void**)&cos_d, SIZE));
HIP_ASSERT(hipMalloc((void**)&tan_d, SIZE));
HIP_ASSERT(hipMalloc((void**)&sin_pd, SIZE));
HIP_ASSERT(hipMalloc((void**)&cos_pd, SIZE));
hipMemcpy(In_d, In, SIZE, hipMemcpyHostToDevice);
hipLaunchKernel(kernel_trig, dim3(LEN, 1, 1), dim3(1, 1, 1), 0, 0,
In_d, sin_d, cos_d, tan_d,
sin_pd, cos_pd);
hipMemcpy(sin_h, sin_d, SIZE, hipMemcpyDeviceToHost);
hipMemcpy(cos_h, cos_d, SIZE, hipMemcpyDeviceToHost);
hipMemcpy(tan_h, tan_d, SIZE, hipMemcpyDeviceToHost);
hipMemcpy(sin_ph, sin_pd, SIZE, hipMemcpyDeviceToHost);
hipMemcpy(cos_ph, cos_pd, SIZE, hipMemcpyDeviceToHost);
for (int i = 0; i < LEN; i++) {
if (sin_h[i] != sin_ph[i] || cos_h[i] != cos_ph[i] || tan_h[i] * cos_h[i] != sin_h[i]) {
errors++;
#if TEST_DEBUG
std::cout << "Check Failed!" << std::endl;
std::cout << " sin_h: " << sin_h[i] << " sin_ph: " << sin_ph[i] << "\n"
<< " cos_h: " << cos_h[i] << " cos_ph:" << cos_ph[i] << "\n"
<< " tan_h * cos_h: " << tan_h[i] * cos_h[i] << " sin_h[i]: " << sin_h[i] << "\n";
#endif
}
}
HIP_ASSERT(hipFree(In_d));
HIP_ASSERT(hipFree(sin_d));
HIP_ASSERT(hipFree(cos_d));
HIP_ASSERT(hipFree(tan_d));
HIP_ASSERT(hipFree(sin_pd));
HIP_ASSERT(hipFree(cos_pd));
if (errors != 0) {
std::cout << "hip_trig FAILED!" << std::endl;
return -1;
} else {
std::cout << "hip_trig PASSED!" << std::endl;
}
return errors;
}
<commit_msg>Use trig functions from ocml instead<commit_after>/*
Copyright (c) 2015-2016 Advanced Micro Devices, Inc. All rights reserved.
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.
*/
/* HIT_START
* BUILD: %t %s
* RUN: %t
* HIT_END
*/
#include <hip/hip_runtime_api.h>
#include <hip/hip_runtime.h>
#include <iostream>
#include "test_common.h"
#include <hip/device_functions.h>
#define HIP_ASSERT(x) (assert((x) == hipSuccess))
#define LEN 512
#define SIZE LEN << 2
#define TEST_DEBUG (0)
__global__ void kernel_trig(hipLaunchParm lp, float* In, float* sin_d, float* cos_d, float* tan_d,
float* sin_pd, float* cos_pd) {
int tid = threadIdx.x + blockIdx.x * blockDim.x;
sin_d[tid] = sinf(In[tid]);
cos_d[tid] = cosf(In[tid]);
tan_d[tid] = tanf(In[tid]);
sincosf(In[tid], &sin_pd[tid], &cos_pd[tid]);
}
int main() {
float *In, *sin_h, *cos_h, *tan_h, *sin_ph, *cos_ph;
float *In_d, *sin_d, *cos_d, *tan_d, *sin_pd, *cos_pd;
int errors = 0;
In = new float[LEN];
sin_h = new float[LEN];
cos_h = new float[LEN];
tan_h = new float[LEN];
sin_ph = new float[LEN];
cos_ph = new float[LEN];
for (int i = 0; i < LEN; i++) {
In[i] = 1.0f;
sin_h[i] = 0.0f;
cos_h[i] = 0.0f;
tan_h[i] = 0.0f;
sin_ph[i] = 0.0f;
cos_ph[i] = 0.0f;
}
HIP_ASSERT(hipMalloc((void**)&In_d, SIZE));
HIP_ASSERT(hipMalloc((void**)&sin_d, SIZE));
HIP_ASSERT(hipMalloc((void**)&cos_d, SIZE));
HIP_ASSERT(hipMalloc((void**)&tan_d, SIZE));
HIP_ASSERT(hipMalloc((void**)&sin_pd, SIZE));
HIP_ASSERT(hipMalloc((void**)&cos_pd, SIZE));
hipMemcpy(In_d, In, SIZE, hipMemcpyHostToDevice);
hipLaunchKernel(kernel_trig, dim3(LEN, 1, 1), dim3(1, 1, 1), 0, 0,
In_d, sin_d, cos_d, tan_d,
sin_pd, cos_pd);
hipMemcpy(sin_h, sin_d, SIZE, hipMemcpyDeviceToHost);
hipMemcpy(cos_h, cos_d, SIZE, hipMemcpyDeviceToHost);
hipMemcpy(tan_h, tan_d, SIZE, hipMemcpyDeviceToHost);
hipMemcpy(sin_ph, sin_pd, SIZE, hipMemcpyDeviceToHost);
hipMemcpy(cos_ph, cos_pd, SIZE, hipMemcpyDeviceToHost);
for (int i = 0; i < LEN; i++) {
if (sin_h[i] != sin_ph[i] || cos_h[i] != cos_ph[i] || tan_h[i] * cos_h[i] != sin_h[i]) {
errors++;
#if TEST_DEBUG
std::cout << "Check Failed!" << std::endl;
std::cout << " sin_h: " << sin_h[i] << " sin_ph: " << sin_ph[i] << "\n"
<< " cos_h: " << cos_h[i] << " cos_ph:" << cos_ph[i] << "\n"
<< " tan_h * cos_h: " << tan_h[i] * cos_h[i] << " sin_h[i]: " << sin_h[i] << "\n";
#endif
}
}
HIP_ASSERT(hipFree(In_d));
HIP_ASSERT(hipFree(sin_d));
HIP_ASSERT(hipFree(cos_d));
HIP_ASSERT(hipFree(tan_d));
HIP_ASSERT(hipFree(sin_pd));
HIP_ASSERT(hipFree(cos_pd));
if (errors != 0) {
std::cout << "hip_trig FAILED!" << std::endl;
return -1;
} else {
std::cout << "hip_trig PASSED!" << std::endl;
}
return errors;
}
<|endoftext|> |
<commit_before>/*
* Copyright (C) 2008-2010 The QXmpp developers
*
* Author:
* Manjeet Dahiya
*
* Source:
* http://code.google.com/p/qxmpp
*
* This file is a part of QXmpp library.
*
* 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.
*
*/
#include "capabilitiesCollection.h"
#include "QXmppClient.h"
#include "QXmppDiscoveryManager.h"
#include <utils.h>
#include <QCoreApplication>
#include <QXmlStreamWriter>
#include <QDir>
capabilitiesCollection::capabilitiesCollection(QXmppClient* client) :
QObject(client), m_client(client)
{
QXmppDiscoveryManager* ext = m_client->findExtension<QXmppDiscoveryManager>();
if(ext)
{
bool check = connect(ext, SIGNAL(infoReceived(const QXmppDiscoveryIq&)),
SLOT(infoReceived(const QXmppDiscoveryIq&)));
Q_ASSERT(check);
}
}
bool capabilitiesCollection::isCapabilityAvailable(const QString& nodeVer)
{
return m_mapCapabilities.contains(nodeVer);
}
void capabilitiesCollection::requestInfo(const QString& jid, const QString& node)
{
QXmppDiscoveryManager* ext = m_client->findExtension<QXmppDiscoveryManager>();
if(ext)
{
bool alreadyRequested = false;
foreach(QString key, m_mapIdNodeVer.keys())
{
if(m_mapIdNodeVer[key] == node)
{
alreadyRequested = true;
break;
}
}
if(!alreadyRequested)
{
QString id = ext->requestInfo(jid, node);
m_mapIdNodeVer[id] = node;
}
}
}
void capabilitiesCollection::infoReceived(const QXmppDiscoveryIq& discoIqRcv)
{
QXmppDiscoveryIq discoIq = discoIqRcv;
if(discoIq.queryType() == QXmppDiscoveryIq::InfoQuery &&
discoIq.type() == QXmppIq::Result)
{
if(discoIq.queryNode().isEmpty())
{
discoIq.setQueryNode(m_mapIdNodeVer[discoIq.id()]);
m_mapIdNodeVer.remove(discoIq.id());
}
discoIq.setTo("");
discoIq.setFrom("");
discoIq.setId("");
m_mapCapabilities[discoIq.queryNode()] = discoIq;
saveToCache(discoIq.queryNode());
}
}
void capabilitiesCollection::loadAllFromCache()
{
QDir dirCaps(getSettingsDir(m_client->configuration().jidBare())+ "capabilities/");
if(dirCaps.exists())
{
QStringList list = dirCaps.entryList(QStringList("*.xml"));
foreach(QString fileName, list)
{
QFile file(getSettingsDir(m_client->configuration().jidBare())+ "capabilities/" + fileName);
if(file.open(QIODevice::ReadOnly))
{
QDomDocument doc;
if(doc.setContent(&file, true))
{
QXmppDiscoveryIq discoIq;
discoIq.parse(doc.documentElement());
m_mapCapabilities[discoIq.queryNode()] = discoIq;
QCoreApplication::processEvents(QEventLoop::ExcludeUserInputEvents);
}
}
}
}
}
void capabilitiesCollection::saveToCache(const QString& nodeVer)
{
if(!m_mapCapabilities.contains(nodeVer))
return;
QString fileName = getImageHash(nodeVer.toUtf8());
QDir dir;
if(!dir.exists(getSettingsDir(m_client->configuration().jidBare())))
dir.mkpath(getSettingsDir(m_client->configuration().jidBare()));
QDir dir2;
if(!dir2.exists(getSettingsDir(m_client->configuration().jidBare())+ "capabilities/"))
dir2.mkpath(getSettingsDir(m_client->configuration().jidBare())+ "capabilities/");
QString fileCapability = getSettingsDir(m_client->configuration().jidBare()) + "capabilities/" + fileName + ".xml";
QFile file(fileCapability);
if(file.open(QIODevice::ReadWrite))
{
QXmlStreamWriter stream(&file);
m_mapCapabilities[nodeVer].toXml(&stream);
file.close();
}
}
<commit_msg>clear map on startup<commit_after>/*
* Copyright (C) 2008-2010 The QXmpp developers
*
* Author:
* Manjeet Dahiya
*
* Source:
* http://code.google.com/p/qxmpp
*
* This file is a part of QXmpp library.
*
* 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.
*
*/
#include "capabilitiesCollection.h"
#include "QXmppClient.h"
#include "QXmppDiscoveryManager.h"
#include <utils.h>
#include <QCoreApplication>
#include <QXmlStreamWriter>
#include <QDir>
capabilitiesCollection::capabilitiesCollection(QXmppClient* client) :
QObject(client), m_client(client)
{
QXmppDiscoveryManager* ext = m_client->findExtension<QXmppDiscoveryManager>();
if(ext)
{
bool check = connect(ext, SIGNAL(infoReceived(const QXmppDiscoveryIq&)),
SLOT(infoReceived(const QXmppDiscoveryIq&)));
Q_ASSERT(check);
}
}
bool capabilitiesCollection::isCapabilityAvailable(const QString& nodeVer)
{
return m_mapCapabilities.contains(nodeVer);
}
void capabilitiesCollection::requestInfo(const QString& jid, const QString& node)
{
QXmppDiscoveryManager* ext = m_client->findExtension<QXmppDiscoveryManager>();
if(ext)
{
bool alreadyRequested = false;
foreach(QString key, m_mapIdNodeVer.keys())
{
if(m_mapIdNodeVer[key] == node)
{
alreadyRequested = true;
break;
}
}
if(!alreadyRequested)
{
QString id = ext->requestInfo(jid, node);
m_mapIdNodeVer[id] = node;
}
}
}
void capabilitiesCollection::infoReceived(const QXmppDiscoveryIq& discoIqRcv)
{
QXmppDiscoveryIq discoIq = discoIqRcv;
if(discoIq.queryType() == QXmppDiscoveryIq::InfoQuery &&
discoIq.type() == QXmppIq::Result)
{
if(discoIq.queryNode().isEmpty())
{
discoIq.setQueryNode(m_mapIdNodeVer[discoIq.id()]);
m_mapIdNodeVer.remove(discoIq.id());
}
discoIq.setTo("");
discoIq.setFrom("");
discoIq.setId("");
m_mapCapabilities[discoIq.queryNode()] = discoIq;
saveToCache(discoIq.queryNode());
}
}
void capabilitiesCollection::loadAllFromCache()
{
m_mapCapabilities.clear();
QDir dirCaps(getSettingsDir(m_client->configuration().jidBare())+ "capabilities/");
if(dirCaps.exists())
{
QStringList list = dirCaps.entryList(QStringList("*.xml"));
foreach(QString fileName, list)
{
QFile file(getSettingsDir(m_client->configuration().jidBare())+ "capabilities/" + fileName);
if(file.open(QIODevice::ReadOnly))
{
QDomDocument doc;
if(doc.setContent(&file, true))
{
QXmppDiscoveryIq discoIq;
discoIq.parse(doc.documentElement());
m_mapCapabilities[discoIq.queryNode()] = discoIq;
QCoreApplication::processEvents(QEventLoop::ExcludeUserInputEvents);
}
}
}
}
}
void capabilitiesCollection::saveToCache(const QString& nodeVer)
{
if(!m_mapCapabilities.contains(nodeVer))
return;
QString fileName = getImageHash(nodeVer.toUtf8());
QDir dir;
if(!dir.exists(getSettingsDir(m_client->configuration().jidBare())))
dir.mkpath(getSettingsDir(m_client->configuration().jidBare()));
QDir dir2;
if(!dir2.exists(getSettingsDir(m_client->configuration().jidBare())+ "capabilities/"))
dir2.mkpath(getSettingsDir(m_client->configuration().jidBare())+ "capabilities/");
QString fileCapability = getSettingsDir(m_client->configuration().jidBare()) + "capabilities/" + fileName + ".xml";
QFile file(fileCapability);
if(file.open(QIODevice::ReadWrite))
{
QXmlStreamWriter stream(&file);
m_mapCapabilities[nodeVer].toXml(&stream);
file.close();
}
}
<|endoftext|> |
<commit_before>/*
*
* This file is part of the open-source SeetaFace engine, which includes three modules:
* SeetaFace Detection, SeetaFace Alignment, and SeetaFace Identification.
*
* This file is an example of how to use SeetaFace engine for face alignment, the
* face alignment method described in the following paper:
*
*
* Coarse-to-Fine Auto-Encoder Networks (CFAN) for Real-Time Face Alignment,
* Jie Zhang, Shiguang Shan, Meina Kan, Xilin Chen. In Proceeding of the
* European Conference on Computer Vision (ECCV), 2014
*
*
* Copyright (C) 2016, Visual Information Processing and Learning (VIPL) group,
* Institute of Computing Technology, Chinese Academy of Sciences, Beijing, China.
*
* The codes are mainly developed by Jie Zhang (a Ph.D supervised by Prof. Shiguang Shan)
*
* As an open-source face recognition engine: you can redistribute SeetaFace source codes
* and/or modify it under the terms of the BSD 2-Clause License.
*
* You should have received a copy of the BSD 2-Clause License along with the software.
* If not, see < https://opensource.org/licenses/BSD-2-Clause>.
*
* Contact Info: you can send an email to SeetaFace@vipl.ict.ac.cn for any problems.
*
* Note: the above information must be kept whenever or wherever the codes are used.
*
*/
#include <cstdint>
#include <fstream>
#include <iostream>
#include <string>
#include "cv.h"
#include "highgui.h"
#include "face_detection.h"
#include "face_alignment.h"
int main(int argc, char** argv)
{
// Initialize face detection model
seeta::FaceDetection detector("seeta_fd_frontal_v1.0.bin");
detector.SetMinFaceSize(40);
detector.SetScoreThresh(2.f);
detector.SetImagePyramidScaleFactor(0.8f);
detector.SetWindowStep(4, 4);
// Initialize face alignment model
seeta::FaceAlignment point_detector("seeta_fa_v1.0.bin");
//load image
IplImage *img_grayscale = NULL;
img_grayscale = cvLoadImage("image_0001.png", 0);
if (img_grayscale == NULL)
{
return 0;
}
IplImage *img_color = cvLoadImage("image_0001.png", 1);
int pts_num = 5;
int im_width = img_grayscale->width;
int im_height = img_grayscale->height;
unsigned char* data = new unsigned char[im_width * im_height];
unsigned char* data_ptr = data;
unsigned char* image_data_ptr = (unsigned char*)img_grayscale->imageData;
int h = 0;
for (h = 0; h < im_height; h++) {
memcpy(data_ptr, image_data_ptr, im_width);
data_ptr += im_width;
image_data_ptr += img_grayscale->widthStep;
}
seeta::ImageData image_data;
image_data.data = data;
image_data.width = im_width;
image_data.height = im_height;
image_data.num_channels = 1;
// Detect faces
std::vector<seeta::FaceInfo> faces = detector.Detect(img_data);
int32_t face_num = static_cast<int32_t>(faces.size());
if (face_num == 0)
{
delete[]data;
cvReleaseImage(&img_grayscale);
cvReleaseImage(&img_color);
return 0;
}
// Detect 5 facial landmarks
seeta::FacialLandmark points[5];
point_detector.PointDetectLandmarks(image_data, faces[0], points);
// Visualize the results
cvRectangle(img_color, cvPoint(faces[0].bbox.x, faces[0].bbox.y), cvPoint(faces[0].bbox.x + faces[0].bbox.width - 1, faces[0].bbox.y + faces[0].bbox.height - 1), CV_RGB(255, 0, 0));
for (int i = 0; i<pts_num; i++)
{
cvCircle(img_color, cvPoint(points[i].x, points[i].y), 2, CV_RGB(0, 255, 0), CV_FILLED);
}
cvSaveImage("result.jpg", img_color);
// Release memory
cvReleaseImage(&img_color);
cvReleaseImage(&img_grayscale);
delete[]data;
return 0;
}
<commit_msg>update face_alignment_test.cpp<commit_after>/*
*
* This file is part of the open-source SeetaFace engine, which includes three modules:
* SeetaFace Detection, SeetaFace Alignment, and SeetaFace Identification.
*
* This file is an example of how to use SeetaFace engine for face alignment, the
* face alignment method described in the following paper:
*
*
* Coarse-to-Fine Auto-Encoder Networks (CFAN) for Real-Time Face Alignment,
* Jie Zhang, Shiguang Shan, Meina Kan, Xilin Chen. In Proceeding of the
* European Conference on Computer Vision (ECCV), 2014
*
*
* Copyright (C) 2016, Visual Information Processing and Learning (VIPL) group,
* Institute of Computing Technology, Chinese Academy of Sciences, Beijing, China.
*
* The codes are mainly developed by Jie Zhang (a Ph.D supervised by Prof. Shiguang Shan)
*
* As an open-source face recognition engine: you can redistribute SeetaFace source codes
* and/or modify it under the terms of the BSD 2-Clause License.
*
* You should have received a copy of the BSD 2-Clause License along with the software.
* If not, see < https://opensource.org/licenses/BSD-2-Clause>.
*
* Contact Info: you can send an email to SeetaFace@vipl.ict.ac.cn for any problems.
*
* Note: the above information must be kept whenever or wherever the codes are used.
*
*/
#include <cstdint>
#include <fstream>
#include <iostream>
#include <string>
#include "cv.h"
#include "highgui.h"
#include "face_detection.h"
#include "face_alignment.h"
int main(int argc, char** argv)
{
// Initialize face detection model
seeta::FaceDetection detector("seeta_fd_frontal_v1.0.bin");
detector.SetMinFaceSize(40);
detector.SetScoreThresh(2.f);
detector.SetImagePyramidScaleFactor(0.8f);
detector.SetWindowStep(4, 4);
// Initialize face alignment model
seeta::FaceAlignment point_detector("seeta_fa_v1.0.bin");
//load image
IplImage *img_grayscale = NULL;
img_grayscale = cvLoadImage("image_0001.png", 0);
if (img_grayscale == NULL)
{
return 0;
}
IplImage *img_color = cvLoadImage("image_0001.png", 1);
int pts_num = 5;
int im_width = img_grayscale->width;
int im_height = img_grayscale->height;
unsigned char* data = new unsigned char[im_width * im_height];
unsigned char* data_ptr = data;
unsigned char* image_data_ptr = (unsigned char*)img_grayscale->imageData;
int h = 0;
for (h = 0; h < im_height; h++) {
memcpy(data_ptr, image_data_ptr, im_width);
data_ptr += im_width;
image_data_ptr += img_grayscale->widthStep;
}
seeta::ImageData image_data;
image_data.data = data;
image_data.width = im_width;
image_data.height = im_height;
image_data.num_channels = 1;
// Detect faces
std::vector<seeta::FaceInfo> faces = detector.Detect(image_data);
int32_t face_num = static_cast<int32_t>(faces.size());
if (face_num == 0)
{
delete[]data;
cvReleaseImage(&img_grayscale);
cvReleaseImage(&img_color);
return 0;
}
// Detect 5 facial landmarks
seeta::FacialLandmark points[5];
point_detector.PointDetectLandmarks(image_data, faces[0], points);
// Visualize the results
cvRectangle(img_color, cvPoint(faces[0].bbox.x, faces[0].bbox.y), cvPoint(faces[0].bbox.x + faces[0].bbox.width - 1, faces[0].bbox.y + faces[0].bbox.height - 1), CV_RGB(255, 0, 0));
for (int i = 0; i<pts_num; i++)
{
cvCircle(img_color, cvPoint(points[i].x, points[i].y), 2, CV_RGB(0, 255, 0), CV_FILLED);
}
cvSaveImage("result.jpg", img_color);
// Release memory
cvReleaseImage(&img_color);
cvReleaseImage(&img_grayscale);
delete[]data;
return 0;
}
<|endoftext|> |
<commit_before>// HexEditor.cpp : implementation file
//
#include "stdafx.h"
#include "HexEditor.h"
#include "SmartView\SmartView.h"
#include "FileDialogEx.h"
#include "ImportProcs.h"
static wstring CLASS = L"CHexEditor";
enum __HexEditorFields
{
HEXED_ANSI,
HEXED_UNICODE,
HEXED_BASE64,
HEXED_HEX,
HEXED_SMARTVIEW
};
CHexEditor::CHexEditor(_In_ CParentWnd* pParentWnd, _In_ CMapiObjects* lpMapiObjects) :
CEditor(pParentWnd, IDS_HEXEDITOR, NULL, 0, CEDITOR_BUTTON_ACTION1 | CEDITOR_BUTTON_ACTION2 | CEDITOR_BUTTON_ACTION3, IDS_IMPORT, IDS_EXPORT, IDS_CLOSE)
{
TRACE_CONSTRUCTOR(CLASS);
m_lpMapiObjects = lpMapiObjects;
if (m_lpMapiObjects) m_lpMapiObjects->AddRef();
CreateControls(5);
InitPane(HEXED_ANSI, CreateCollapsibleTextPane(IDS_ANSISTRING, false));
InitPane(HEXED_UNICODE, CreateCollapsibleTextPane(IDS_UNISTRING, false));
InitPane(HEXED_BASE64, CreateCountedTextPane(IDS_BASE64STRING, false, IDS_CCH));
InitPane(HEXED_HEX, CreateCountedTextPane(IDS_HEX, false, IDS_CB));
InitPane(HEXED_SMARTVIEW, CreateSmartViewPane(IDS_SMARTVIEW));
DisplayParentedDialog(pParentWnd, 1000);
} // CHexEditor::CHexEditor
CHexEditor::~CHexEditor()
{
TRACE_DESTRUCTOR(CLASS);
if (m_lpMapiObjects) m_lpMapiObjects->Release();
} // CHexEditor::~CHexEditor
void CHexEditor::OnOK()
{
ShowWindow(SW_HIDE);
delete this;
} // CHexEditor::OnOK
void CHexEditor::OnCancel()
{
OnOK();
} // CHexEditor::OnCancel
void CleanString(_In_ CString* lpString)
{
if (!lpString) return;
// remove any whitespace
lpString->Replace(_T("\r"), _T("")); // STRING_OK
lpString->Replace(_T("\n"), _T("")); // STRING_OK
lpString->Replace(_T("\t"), _T("")); // STRING_OK
lpString->Replace(_T(" "), _T("")); // STRING_OK
}
_Check_return_ ULONG CHexEditor::HandleChange(UINT nID)
{
HRESULT hRes = S_OK;
ULONG i = CEditor::HandleChange(nID);
if ((ULONG)-1 == i) return (ULONG)-1;
CString szTmpString;
LPBYTE lpb = NULL;
size_t cb = 0;
wstring szEncodeStr;
size_t cchEncodeStr = 0;
switch (i)
{
case HEXED_ANSI:
{
size_t cchStr = NULL;
lpb = (LPBYTE)GetEditBoxTextA(HEXED_ANSI, &cchStr);
SetStringA(HEXED_UNICODE, (LPCSTR)lpb, cchStr);
// What we just read includes a NULL terminator, in both the string and count.
// When we write binary/base64, we don't want to include this NULL
if (cchStr) cchStr -= 1;
cb = cchStr * sizeof(CHAR);
szEncodeStr = Base64Encode(cb, lpb);
SetStringW(HEXED_BASE64, szEncodeStr.c_str());
SetBinary(HEXED_HEX, lpb, cb);
}
break;
case HEXED_UNICODE: // Unicode string changed
{
size_t cchStr = NULL;
lpb = (LPBYTE)GetEditBoxTextW(HEXED_UNICODE, &cchStr);
SetStringW(HEXED_ANSI, (LPWSTR)lpb, cchStr);
// What we just read includes a NULL terminator, in both the string and count.
// When we write binary/base64, we don't want to include this NULL
if (cchStr) cchStr -= 1;
cb = cchStr * sizeof(WCHAR);
szEncodeStr = Base64Encode(cb, lpb);
SetStringW(HEXED_BASE64, szEncodeStr.c_str());
SetBinary(HEXED_HEX, lpb, cb);
}
break;
case HEXED_BASE64: // base64 changed
{
szTmpString = GetStringUseControl(HEXED_BASE64);
// remove any whitespace before decoding
CleanString(&szTmpString);
cchEncodeStr = szTmpString.GetLength();
vector<BYTE> bin = Base64Decode(LPCTSTRToWstring((LPCTSTR)szTmpString));
lpb = ByteVectorToLPBYTE(bin);
cb = bin.size();
if (S_OK == hRes)
{
SetStringA(HEXED_ANSI, (LPCSTR)lpb, cb);
if (!(cb % 2)) // Set Unicode String
{
SetStringW(HEXED_UNICODE, (LPWSTR)lpb, cb / sizeof(WCHAR));
}
else
{
SetString(HEXED_UNICODE, _T(""));
}
SetBinary(HEXED_HEX, lpb, cb);
}
else
{
SetString(HEXED_ANSI, _T(""));
SetString(HEXED_UNICODE, _T(""));
SetBinary(HEXED_HEX, 0, 0);
}
delete[] lpb;
}
break;
case HEXED_HEX: // binary changed
{
if (GetBinaryUseControl(HEXED_HEX, &cb, &lpb))
{
// Treat as a NULL terminated string
// GetBinaryUseControl includes extra NULLs at the end of the buffer to make this work
SetStringA(HEXED_ANSI, (LPCSTR)lpb, cb + 1); // ansi string
if (!(cb % 2)) // Set Unicode String
{
// Treat as a NULL terminated string
// GetBinaryUseControl includes extra NULLs at the end of the buffer to make this work
SetStringW(HEXED_UNICODE, (LPWSTR)lpb, cb / sizeof(WCHAR) + 1);
}
else
{
SetString(HEXED_UNICODE, _T(""));
}
szEncodeStr = Base64Encode(cb, lpb);
SetStringW(HEXED_BASE64, szEncodeStr.c_str());
}
else
{
SetString(HEXED_ANSI, _T(""));
SetString(HEXED_UNICODE, _T(""));
SetString(HEXED_BASE64, _T(""));
}
delete[] lpb;
}
break;
default:
break;
}
if (HEXED_SMARTVIEW != i)
{
// length of base64 encoded string
CountedTextPane* lpPane = (CountedTextPane*)GetControl(HEXED_BASE64);
if (lpPane)
{
lpPane->SetCount(cchEncodeStr);
}
lpPane = (CountedTextPane*)GetControl(HEXED_HEX);
if (lpPane)
{
lpPane->SetCount(cb);
}
}
// Update any parsing we've got:
UpdateParser();
// Force the new layout
OnRecalcLayout();
return i;
}
void CHexEditor::UpdateParser()
{
// Find out how to interpret the data
SmartViewPane* lpPane = (SmartViewPane*)GetControl(HEXED_SMARTVIEW);
if (lpPane)
{
SBinary Bin = { 0 };
if (GetBinaryUseControl(HEXED_HEX, (size_t*)&Bin.cb, &Bin.lpb))
{
lpPane->Parse(Bin);
delete[] Bin.lpb;
}
}
}
// Import
void CHexEditor::OnEditAction1()
{
HRESULT hRes = S_OK;
if (S_OK == hRes)
{
INT_PTR iDlgRet = IDOK;
CStringW szFileSpec;
EC_B(szFileSpec.LoadString(IDS_ALLFILES));
CFileDialogExW dlgFilePicker;
EC_D_DIALOG(dlgFilePicker.DisplayDialog(
true,
NULL,
NULL,
OFN_FILEMUSTEXIST,
szFileSpec,
this));
if (iDlgRet == IDOK && dlgFilePicker.GetFileName())
{
if (m_lpMapiObjects) m_lpMapiObjects->MAPIInitialize(NULL);
LPSTREAM lpStream = NULL;
// Get a Stream interface on the input file
EC_H(MyOpenStreamOnFile(
MAPIAllocateBuffer,
MAPIFreeBuffer,
STGM_READ,
dlgFilePicker.GetFileName(),
NULL,
&lpStream));
if (lpStream)
{
TextPane* lpPane = (TextPane*)GetControl(HEXED_HEX);
if (lpPane)
{
lpPane->InitEditFromBinaryStream(lpStream);
}
lpStream->Release();
}
}
}
}
// Export
void CHexEditor::OnEditAction2()
{
HRESULT hRes = S_OK;
if (S_OK == hRes)
{
INT_PTR iDlgRet = IDOK;
CStringW szFileSpec;
EC_B(szFileSpec.LoadString(IDS_ALLFILES));
CFileDialogExW dlgFilePicker;
EC_D_DIALOG(dlgFilePicker.DisplayDialog(
false,
NULL,
NULL,
OFN_HIDEREADONLY | OFN_OVERWRITEPROMPT,
szFileSpec,
this));
if (iDlgRet == IDOK && dlgFilePicker.GetFileName())
{
if (m_lpMapiObjects) m_lpMapiObjects->MAPIInitialize(NULL);
LPSTREAM lpStream = NULL;
// Get a Stream interface on the input file
EC_H(MyOpenStreamOnFile(
MAPIAllocateBuffer,
MAPIFreeBuffer,
STGM_CREATE | STGM_READWRITE,
dlgFilePicker.GetFileName(),
NULL,
&lpStream));
if (lpStream)
{
TextPane* lpPane = (TextPane*)GetControl(HEXED_HEX);
if (lpPane)
{
lpPane->WriteToBinaryStream(lpStream);
}
lpStream->Release();
}
}
}
}
// Close
void CHexEditor::OnEditAction3()
{
OnOK();
}<commit_msg>fix character count for hex editor base 64<commit_after>// HexEditor.cpp : implementation file
//
#include "stdafx.h"
#include "HexEditor.h"
#include "SmartView\SmartView.h"
#include "FileDialogEx.h"
#include "ImportProcs.h"
static wstring CLASS = L"CHexEditor";
enum __HexEditorFields
{
HEXED_ANSI,
HEXED_UNICODE,
HEXED_BASE64,
HEXED_HEX,
HEXED_SMARTVIEW
};
CHexEditor::CHexEditor(_In_ CParentWnd* pParentWnd, _In_ CMapiObjects* lpMapiObjects) :
CEditor(pParentWnd, IDS_HEXEDITOR, NULL, 0, CEDITOR_BUTTON_ACTION1 | CEDITOR_BUTTON_ACTION2 | CEDITOR_BUTTON_ACTION3, IDS_IMPORT, IDS_EXPORT, IDS_CLOSE)
{
TRACE_CONSTRUCTOR(CLASS);
m_lpMapiObjects = lpMapiObjects;
if (m_lpMapiObjects) m_lpMapiObjects->AddRef();
CreateControls(5);
InitPane(HEXED_ANSI, CreateCollapsibleTextPane(IDS_ANSISTRING, false));
InitPane(HEXED_UNICODE, CreateCollapsibleTextPane(IDS_UNISTRING, false));
InitPane(HEXED_BASE64, CreateCountedTextPane(IDS_BASE64STRING, false, IDS_CCH));
InitPane(HEXED_HEX, CreateCountedTextPane(IDS_HEX, false, IDS_CB));
InitPane(HEXED_SMARTVIEW, CreateSmartViewPane(IDS_SMARTVIEW));
DisplayParentedDialog(pParentWnd, 1000);
} // CHexEditor::CHexEditor
CHexEditor::~CHexEditor()
{
TRACE_DESTRUCTOR(CLASS);
if (m_lpMapiObjects) m_lpMapiObjects->Release();
} // CHexEditor::~CHexEditor
void CHexEditor::OnOK()
{
ShowWindow(SW_HIDE);
delete this;
} // CHexEditor::OnOK
void CHexEditor::OnCancel()
{
OnOK();
} // CHexEditor::OnCancel
void CleanString(_In_ CString* lpString)
{
if (!lpString) return;
// remove any whitespace
lpString->Replace(_T("\r"), _T("")); // STRING_OK
lpString->Replace(_T("\n"), _T("")); // STRING_OK
lpString->Replace(_T("\t"), _T("")); // STRING_OK
lpString->Replace(_T(" "), _T("")); // STRING_OK
}
_Check_return_ ULONG CHexEditor::HandleChange(UINT nID)
{
HRESULT hRes = S_OK;
ULONG i = CEditor::HandleChange(nID);
if ((ULONG)-1 == i) return (ULONG)-1;
CString szTmpString;
LPBYTE lpb = NULL;
size_t cb = 0;
wstring szEncodeStr;
size_t cchEncodeStr = 0;
switch (i)
{
case HEXED_ANSI:
{
size_t cchStr = NULL;
lpb = (LPBYTE)GetEditBoxTextA(HEXED_ANSI, &cchStr);
SetStringA(HEXED_UNICODE, (LPCSTR)lpb, cchStr);
// What we just read includes a NULL terminator, in both the string and count.
// When we write binary/base64, we don't want to include this NULL
if (cchStr) cchStr -= 1;
cb = cchStr * sizeof(CHAR);
szEncodeStr = Base64Encode(cb, lpb);
cchEncodeStr = szEncodeStr.length();
SetStringW(HEXED_BASE64, szEncodeStr.c_str());
SetBinary(HEXED_HEX, lpb, cb);
}
break;
case HEXED_UNICODE: // Unicode string changed
{
size_t cchStr = NULL;
lpb = (LPBYTE)GetEditBoxTextW(HEXED_UNICODE, &cchStr);
SetStringW(HEXED_ANSI, (LPWSTR)lpb, cchStr);
// What we just read includes a NULL terminator, in both the string and count.
// When we write binary/base64, we don't want to include this NULL
if (cchStr) cchStr -= 1;
cb = cchStr * sizeof(WCHAR);
szEncodeStr = Base64Encode(cb, lpb);
cchEncodeStr = szEncodeStr.length();
SetStringW(HEXED_BASE64, szEncodeStr.c_str());
SetBinary(HEXED_HEX, lpb, cb);
}
break;
case HEXED_BASE64: // base64 changed
{
szTmpString = GetStringUseControl(HEXED_BASE64);
// remove any whitespace before decoding
CleanString(&szTmpString);
cchEncodeStr = szTmpString.GetLength();
vector<BYTE> bin = Base64Decode(LPCTSTRToWstring((LPCTSTR)szTmpString));
lpb = ByteVectorToLPBYTE(bin);
cb = bin.size();
if (S_OK == hRes)
{
SetStringA(HEXED_ANSI, (LPCSTR)lpb, cb);
if (!(cb % 2)) // Set Unicode String
{
SetStringW(HEXED_UNICODE, (LPWSTR)lpb, cb / sizeof(WCHAR));
}
else
{
SetString(HEXED_UNICODE, _T(""));
}
SetBinary(HEXED_HEX, lpb, cb);
}
else
{
SetString(HEXED_ANSI, _T(""));
SetString(HEXED_UNICODE, _T(""));
SetBinary(HEXED_HEX, 0, 0);
}
delete[] lpb;
}
break;
case HEXED_HEX: // binary changed
{
if (GetBinaryUseControl(HEXED_HEX, &cb, &lpb))
{
// Treat as a NULL terminated string
// GetBinaryUseControl includes extra NULLs at the end of the buffer to make this work
SetStringA(HEXED_ANSI, (LPCSTR)lpb, cb + 1); // ansi string
if (!(cb % 2)) // Set Unicode String
{
// Treat as a NULL terminated string
// GetBinaryUseControl includes extra NULLs at the end of the buffer to make this work
SetStringW(HEXED_UNICODE, (LPWSTR)lpb, cb / sizeof(WCHAR) + 1);
}
else
{
SetString(HEXED_UNICODE, _T(""));
}
szEncodeStr = Base64Encode(cb, lpb);
SetStringW(HEXED_BASE64, szEncodeStr.c_str());
}
else
{
SetString(HEXED_ANSI, _T(""));
SetString(HEXED_UNICODE, _T(""));
SetString(HEXED_BASE64, _T(""));
}
delete[] lpb;
}
break;
default:
break;
}
if (HEXED_SMARTVIEW != i)
{
// length of base64 encoded string
CountedTextPane* lpPane = (CountedTextPane*)GetControl(HEXED_BASE64);
if (lpPane)
{
lpPane->SetCount(cchEncodeStr);
}
lpPane = (CountedTextPane*)GetControl(HEXED_HEX);
if (lpPane)
{
lpPane->SetCount(cb);
}
}
// Update any parsing we've got:
UpdateParser();
// Force the new layout
OnRecalcLayout();
return i;
}
void CHexEditor::UpdateParser()
{
// Find out how to interpret the data
SmartViewPane* lpPane = (SmartViewPane*)GetControl(HEXED_SMARTVIEW);
if (lpPane)
{
SBinary Bin = { 0 };
if (GetBinaryUseControl(HEXED_HEX, (size_t*)&Bin.cb, &Bin.lpb))
{
lpPane->Parse(Bin);
delete[] Bin.lpb;
}
}
}
// Import
void CHexEditor::OnEditAction1()
{
HRESULT hRes = S_OK;
if (S_OK == hRes)
{
INT_PTR iDlgRet = IDOK;
CStringW szFileSpec;
EC_B(szFileSpec.LoadString(IDS_ALLFILES));
CFileDialogExW dlgFilePicker;
EC_D_DIALOG(dlgFilePicker.DisplayDialog(
true,
NULL,
NULL,
OFN_FILEMUSTEXIST,
szFileSpec,
this));
if (iDlgRet == IDOK && dlgFilePicker.GetFileName())
{
if (m_lpMapiObjects) m_lpMapiObjects->MAPIInitialize(NULL);
LPSTREAM lpStream = NULL;
// Get a Stream interface on the input file
EC_H(MyOpenStreamOnFile(
MAPIAllocateBuffer,
MAPIFreeBuffer,
STGM_READ,
dlgFilePicker.GetFileName(),
NULL,
&lpStream));
if (lpStream)
{
TextPane* lpPane = (TextPane*)GetControl(HEXED_HEX);
if (lpPane)
{
lpPane->InitEditFromBinaryStream(lpStream);
}
lpStream->Release();
}
}
}
}
// Export
void CHexEditor::OnEditAction2()
{
HRESULT hRes = S_OK;
if (S_OK == hRes)
{
INT_PTR iDlgRet = IDOK;
CStringW szFileSpec;
EC_B(szFileSpec.LoadString(IDS_ALLFILES));
CFileDialogExW dlgFilePicker;
EC_D_DIALOG(dlgFilePicker.DisplayDialog(
false,
NULL,
NULL,
OFN_HIDEREADONLY | OFN_OVERWRITEPROMPT,
szFileSpec,
this));
if (iDlgRet == IDOK && dlgFilePicker.GetFileName())
{
if (m_lpMapiObjects) m_lpMapiObjects->MAPIInitialize(NULL);
LPSTREAM lpStream = NULL;
// Get a Stream interface on the input file
EC_H(MyOpenStreamOnFile(
MAPIAllocateBuffer,
MAPIFreeBuffer,
STGM_CREATE | STGM_READWRITE,
dlgFilePicker.GetFileName(),
NULL,
&lpStream));
if (lpStream)
{
TextPane* lpPane = (TextPane*)GetControl(HEXED_HEX);
if (lpPane)
{
lpPane->WriteToBinaryStream(lpStream);
}
lpStream->Release();
}
}
}
}
// Close
void CHexEditor::OnEditAction3()
{
OnOK();
}<|endoftext|> |
<commit_before>//
// Name: sdlSimple/app.cpp
// Purpose: Example SDL/vtlib application.
//
// Copyright (c) 2001-2004 Virtual Terrain Project
// Free for all uses, see license.txt for details.
//
#include "SDL.h"
#ifdef __FreeBSD__
# include <ieeefp.h>
#endif
#include "vtlib/vtlib.h"
#include "vtlib/core/Terrain.h"
#include "vtlib/core/TerrainScene.h"
#include "vtlib/core/NavEngines.h"
class App
{
public:
bool CreateScene();
void videosettings(bool same_video_mode, bool fullscreen);
void display();
void run();
int main();
void process_mouse_button(const SDL_Event &event);
void process_mouse_motion(const SDL_Event &event);
bool process_event(const SDL_Event &event);
bool process_events();
public:
vtTerrainScene *m_ts;
vtCamera *m_pCamera;
};
//
// Initialize the SDL display. This code originated from another project,
// so i am not sure of the details, but it should work well on each
// platform.
//
void App::videosettings(bool same_video_mode, bool fullscreen)
{
int width, height;
if ( ( SDL_Init( SDL_INIT_VIDEO | SDL_INIT_AUDIO ) == -1 ) )
{
std::cerr << "Could not initialize SDL: " << SDL_GetError() << std::endl;
exit( -1 );
}
atexit( SDL_Quit );
SDL_VideoInfo const * info = SDL_GetVideoInfo();
if( !info )
{
std::cerr << "Video query failed: " << SDL_GetError( ) << std::endl;
exit( -1 );
}
int num_modes;
SDL_Rect ** modes = SDL_ListModes(NULL, SDL_FULLSCREEN);
if ( (modes != NULL) && (modes != (SDL_Rect **)-1) )
{
for (num_modes = 0; modes[num_modes]; num_modes++);
if ( same_video_mode )
{
// EEERRR should get the surface and use its parameters
width = modes[0]->w;
height = modes[0]->h;
}
else
{
for ( int i=num_modes-1; i >= 0; i-- )
{
width = modes[i]->w;
height = modes[i]->h;
if ( (modes[i]->w >= 1024) && (modes[i]->h >= 768) ) {
break;
}
}
}
}
else
{
std::cerr << "Video list modes failed: " << SDL_GetError( ) << std::endl;
exit( -1 );
}
std::cerr << width << " " << height << std::endl;
SDL_GL_SetAttribute( SDL_GL_RED_SIZE, 5 );
SDL_GL_SetAttribute( SDL_GL_GREEN_SIZE, 5 );
SDL_GL_SetAttribute( SDL_GL_BLUE_SIZE, 5 );
SDL_GL_SetAttribute( SDL_GL_DEPTH_SIZE, 16 );
SDL_GL_SetAttribute( SDL_GL_DOUBLEBUFFER, 1 );
int flags = SDL_OPENGL | SDL_DOUBLEBUF;
if (fullscreen)
flags |= SDL_FULLSCREEN;
if ( info->hw_available )
flags |= SDL_HWSURFACE;
else
flags |= SDL_SWSURFACE;
if ( info->blit_hw )
flags |= SDL_HWACCEL;
if( SDL_SetVideoMode( width, height, 16, flags ) == 0 )
{
std::cerr << "Video mode set failed: " << SDL_GetError( ) << std::endl;
exit( -1 );
}
// Tell the SDL output size to vtlib
vtGetScene()->SetWindowSize(width, height);
}
//--------------------------------------------------------------------------
//
// Create the 3d scene: call vtlib to load the terrain and prepare for
// user interaction.
//
bool App::CreateScene()
{
// Get a handle to the vtScene - one is already created for you
vtScene *pScene = vtGetScene();
pScene->Init();
// Look up the camera
m_pCamera = pScene->GetCamera();
m_pCamera->SetHither(10);
m_pCamera->SetYon(100000);
// Create a new terrain scene. This will contain all the terrain
// that are created.
m_ts = new vtTerrainScene();
vtGroup *pTopGroup = m_ts->BeginTerrainScene();
// Set the global data path
vtStringArray paths;
paths.push_back(vtString("Data/"));
m_ts->SetDataPath(paths);
// Tell the scene graph to point to this terrain scene
pScene->SetRoot(pTopGroup);
// Create a new vtTerrain, read its paramters from a file
vtTerrain *pTerr = new vtTerrain();
pTerr->SetParamFile("Data/Simple.ini");
// Add the terrain to the scene, and contruct it
m_ts->AppendTerrain(pTerr);
if (!m_ts->BuildTerrain(pTerr))
{
printf("Terrain creation failed.");
return false;
}
m_ts->SetCurrentTerrain(pTerr);
// Create a navigation engine to move around on the terrain
// Flight speed is 400 m/frame
// Height over terrain is 100 m
vtTerrainFlyer *pFlyer = new vtTerrainFlyer(400, 100, true);
pFlyer->SetTarget(m_pCamera);
pFlyer->SetHeightField(pTerr->GetHeightField());
pScene->AddEngine(pFlyer);
return true;
}
void App::display()
{
#if !VTLIB_PSM
glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
vtGetScene()->DoUpdate();
SDL_GL_SwapBuffers();
#endif
}
void App::process_mouse_button(const SDL_Event &sdle)
{
// turn SDL mouse button event into a VT mouse event
vtMouseEvent event;
event.type = (sdle.button.type == SDL_MOUSEBUTTONDOWN) ? VT_DOWN : VT_UP;
if (sdle.button.button == 1)
event.button = VT_LEFT;
else if (sdle.button.button == 2)
event.button = VT_MIDDLE;
else if (sdle.button.button == 3)
event.button = VT_RIGHT;
event.flags = 0;
event.pos.Set(sdle.button.x, sdle.button.y);
vtGetScene()->OnMouse(event);
}
void App::process_mouse_motion(const SDL_Event &sdle)
{
// turn SDL mouse move event into a VT mouse event
vtMouseEvent event;
event.type = VT_MOVE;
event.button = VT_NONE;
event.flags = 0;
event.pos.Set(sdle.motion.x, sdle.motion.y);
vtGetScene()->OnMouse(event);
}
bool App::process_event(const SDL_Event &event)
{
int key;
switch( event.type )
{
case SDL_QUIT:
return true;;
case SDL_KEYDOWN:
break;
case SDL_KEYUP:
// turn SDL key event into a VT mouse event
key = event.key.keysym.sym;
if ( key == 27 /* ESC */ || key == 'q' || key == 'Q' )
return true;
vtGetScene()->OnKey(key, 0);
break;
case SDL_MOUSEMOTION:
process_mouse_motion(event);
break;
case SDL_MOUSEBUTTONDOWN:
case SDL_MOUSEBUTTONUP:
process_mouse_button(event);
break;
case SDL_VIDEORESIZE:
// Tell vtlib
vtGetScene()->SetWindowSize(event.resize.w, event.resize.h);
break;
}
return false;
}
bool App::process_events()
{
SDL_Event event;
while ( SDL_PollEvent( &event ) )
{
if (process_event(event))
return true;
}
return false;
}
void App::run()
{
while ( true )
{
display(); // draw scene
if (process_events()) // handle user events
return;
}
}
/*
The works.
*/
int App::main()
{
#ifdef __FreeBSD__
/* FreeBSD is more stringent with FP ops by default, and OSG is */
/* doing silly things sqrt(Inf) (computing lengths of MAXFLOAT */
/* and NaN Vec3's). This turns off FP bug core dumps, ignoring */
/* the error like most platforms do by default. */
fpsetmask(0);
#endif
printf("Initializing SDL..\n");
videosettings(true, false);
printf("Creating the terrain..\n");
if (!CreateScene())
return 0;
printf("Running..\n");
run();
printf("Cleaning up..\n");
m_ts->CleanupScene();
m_pCamera->Release();
delete m_ts;
return 0;
}
int main(int, char ** )
{
#if WIN32 && defined(_MSC_VER) && DEBUG
// sometimes, MSVC seems to need to be told to show unfreed memory on exit
_CrtSetDbgFlag(_CRTDBG_ALLOC_MEM_DF | _CRTDBG_LEAK_CHECK_DF);
#endif
App app;
return app.main();
}
<commit_msg>tweak test code<commit_after>//
// Name: sdlSimple/app.cpp
// Purpose: Example SDL/vtlib application.
//
// Copyright (c) 2001-2004 Virtual Terrain Project
// Free for all uses, see license.txt for details.
//
#include "SDL.h"
#ifdef __FreeBSD__
# include <ieeefp.h>
#endif
#include "vtlib/vtlib.h"
#include "vtlib/core/Terrain.h"
#include "vtlib/core/TerrainScene.h"
#include "vtlib/core/NavEngines.h"
class App
{
public:
bool CreateScene();
void videosettings(bool same_video_mode, bool fullscreen);
void display();
void run();
int main();
void process_mouse_button(const SDL_Event &event);
void process_mouse_motion(const SDL_Event &event);
bool process_event(const SDL_Event &event);
bool process_events();
public:
vtTerrainScene *m_ts;
vtCamera *m_pCamera;
};
//
// Initialize the SDL display. This code originated from another project,
// so i am not sure of the details, but it should work well on each
// platform.
//
void App::videosettings(bool same_video_mode, bool fullscreen)
{
int width, height;
if ( ( SDL_Init( SDL_INIT_VIDEO | SDL_INIT_AUDIO ) == -1 ) )
{
std::cerr << "Could not initialize SDL: " << SDL_GetError() << std::endl;
exit( -1 );
}
atexit( SDL_Quit );
SDL_VideoInfo const * info = SDL_GetVideoInfo();
if( !info )
{
std::cerr << "Video query failed: " << SDL_GetError( ) << std::endl;
exit( -1 );
}
int num_modes;
SDL_Rect ** modes = SDL_ListModes(NULL, SDL_FULLSCREEN);
if ( (modes != NULL) && (modes != (SDL_Rect **)-1) )
{
for (num_modes = 0; modes[num_modes]; num_modes++);
if ( same_video_mode )
{
// EEERRR should get the surface and use its parameters
width = modes[0]->w;
height = modes[0]->h;
}
else
{
for ( int i=num_modes-1; i >= 0; i-- )
{
width = modes[i]->w;
height = modes[i]->h;
if ( (modes[i]->w >= 1024) && (modes[i]->h >= 768) ) {
break;
}
}
}
}
else
{
std::cerr << "Video list modes failed: " << SDL_GetError( ) << std::endl;
exit( -1 );
}
std::cerr << width << " " << height << std::endl;
SDL_GL_SetAttribute( SDL_GL_RED_SIZE, 5 );
SDL_GL_SetAttribute( SDL_GL_GREEN_SIZE, 5 );
SDL_GL_SetAttribute( SDL_GL_BLUE_SIZE, 5 );
SDL_GL_SetAttribute( SDL_GL_DEPTH_SIZE, 16 );
SDL_GL_SetAttribute( SDL_GL_DOUBLEBUFFER, 1 );
int flags = SDL_OPENGL | SDL_DOUBLEBUF;
if (fullscreen)
flags |= SDL_FULLSCREEN;
if ( info->hw_available )
flags |= SDL_HWSURFACE;
else
flags |= SDL_SWSURFACE;
if ( info->blit_hw )
flags |= SDL_HWACCEL;
if( SDL_SetVideoMode( width, height, 16, flags ) == 0 )
{
std::cerr << "Video mode set failed: " << SDL_GetError( ) << std::endl;
exit( -1 );
}
// Tell the SDL output size to vtlib
vtGetScene()->SetWindowSize(width, height);
}
//--------------------------------------------------------------------------
//
// Create the 3d scene: call vtlib to load the terrain and prepare for
// user interaction.
//
bool App::CreateScene()
{
// Get a handle to the vtScene - one is already created for you
vtScene *pScene = vtGetScene();
pScene->Init();
// Look up the camera
m_pCamera = pScene->GetCamera();
m_pCamera->SetHither(10);
m_pCamera->SetYon(100000);
// Create a new terrain scene. This will contain all the terrain
// that are created.
m_ts = new vtTerrainScene();
vtGroup *pTopGroup = m_ts->BeginTerrainScene();
// Set the global data path
vtStringArray paths;
paths.push_back(vtString("Data/"));
m_ts->SetDataPath(paths);
// Tell the scene graph to point to this terrain scene
pScene->SetRoot(pTopGroup);
// Create a new vtTerrain, read its paramters from a file
vtTerrain *pTerr = new vtTerrain();
pTerr->SetParamFile("Data/Simple.ini");
// Add the terrain to the scene, and contruct it
m_ts->AppendTerrain(pTerr);
if (!m_ts->BuildTerrain(pTerr))
{
printf("Terrain creation failed.");
return false;
}
m_ts->SetCurrentTerrain(pTerr);
// Create a navigation engine to move around on the terrain
// Flight speed is 400 m/frame
// Height over terrain is 100 m
vtTerrainFlyer *pFlyer = new vtTerrainFlyer(400, 100, true);
pFlyer->SetTarget(m_pCamera);
pFlyer->SetHeightField(pTerr->GetHeightField());
pScene->AddEngine(pFlyer);
#if 0
// Test code - you can ignore it.
vtMaterialArray *pMats = new vtMaterialArray();
pMats->AddRGBMaterial1(RGBf(1, 1, 0), false, false); // yellow
vtGeom *ball = CreateSphereGeom(pMats, 0, VT_Normals, 100, 16);
pMats->Release();
vtTransform *trans1 = new vtTransform();
vtTransform *trans2 = new vtTransform();
pTopGroup->AddChild(trans1);
pTopGroup->AddChild(trans2);
trans1->AddChild(ball);
trans2->AddChild(ball);
#endif
return true;
}
void App::display()
{
#if !VTLIB_PSM
glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
vtGetScene()->DoUpdate();
SDL_GL_SwapBuffers();
#endif
}
void App::process_mouse_button(const SDL_Event &sdle)
{
// turn SDL mouse button event into a VT mouse event
vtMouseEvent event;
event.type = (sdle.button.type == SDL_MOUSEBUTTONDOWN) ? VT_DOWN : VT_UP;
if (sdle.button.button == 1)
event.button = VT_LEFT;
else if (sdle.button.button == 2)
event.button = VT_MIDDLE;
else if (sdle.button.button == 3)
event.button = VT_RIGHT;
event.flags = 0;
event.pos.Set(sdle.button.x, sdle.button.y);
vtGetScene()->OnMouse(event);
}
void App::process_mouse_motion(const SDL_Event &sdle)
{
// turn SDL mouse move event into a VT mouse event
vtMouseEvent event;
event.type = VT_MOVE;
event.button = VT_NONE;
event.flags = 0;
event.pos.Set(sdle.motion.x, sdle.motion.y);
vtGetScene()->OnMouse(event);
}
bool App::process_event(const SDL_Event &event)
{
int key;
switch( event.type )
{
case SDL_QUIT:
return true;;
case SDL_KEYDOWN:
break;
case SDL_KEYUP:
// turn SDL key event into a VT mouse event
key = event.key.keysym.sym;
if ( key == 27 /* ESC */ || key == 'q' || key == 'Q' )
return true;
vtGetScene()->OnKey(key, 0);
break;
case SDL_MOUSEMOTION:
process_mouse_motion(event);
break;
case SDL_MOUSEBUTTONDOWN:
case SDL_MOUSEBUTTONUP:
process_mouse_button(event);
break;
case SDL_VIDEORESIZE:
// Tell vtlib
vtGetScene()->SetWindowSize(event.resize.w, event.resize.h);
break;
}
return false;
}
bool App::process_events()
{
SDL_Event event;
while ( SDL_PollEvent( &event ) )
{
if (process_event(event))
return true;
}
return false;
}
void App::run()
{
while ( true )
{
display(); // draw scene
if (process_events()) // handle user events
return;
}
}
/*
The works.
*/
int App::main()
{
#ifdef __FreeBSD__
/* FreeBSD is more stringent with FP ops by default, and OSG is */
/* doing silly things sqrt(Inf) (computing lengths of MAXFLOAT */
/* and NaN Vec3's). This turns off FP bug core dumps, ignoring */
/* the error like most platforms do by default. */
fpsetmask(0);
#endif
printf("Initializing SDL..\n");
videosettings(true, false);
printf("Creating the terrain..\n");
if (!CreateScene())
return 0;
printf("Running..\n");
run();
printf("Cleaning up..\n");
m_ts->CleanupScene();
m_pCamera->Release();
delete m_ts;
return 0;
}
int main(int, char ** )
{
#if WIN32 && defined(_MSC_VER) && DEBUG
// sometimes, MSVC seems to need to be told to show unfreed memory on exit
_CrtSetDbgFlag(_CRTDBG_ALLOC_MEM_DF | _CRTDBG_LEAK_CHECK_DF);
#endif
App app;
return app.main();
}
<|endoftext|> |
<commit_before>#include "hornet/java.hh"
#include "hornet/opcode.hh"
#include <hornet/vm.hh>
#include <classfile_constants.h>
#include <cassert>
#include <stack>
namespace hornet {
bool verbose_verifier;
unsigned char unsupported_opcode[JVM_OPC_MAX+1];
unsigned char opcode_length[JVM_OPC_MAX+1] = JVM_OPCODE_LENGTH_INITIALIZER;
bool verify_method(std::shared_ptr<method> method)
{
unsigned int pc = 0;
for (;;) {
if (pc >= method->code_length)
break;
uint8_t opc = method->code[pc];
assert(opc < JVM_OPC_MAX);
if (is_switch(opc)) {
auto len = switch_opc_len(method->code, pc);
pc += len;
continue;
}
switch (opc) {
case JVM_OPC_iconst_m1:
case JVM_OPC_iconst_0:
case JVM_OPC_iconst_1:
case JVM_OPC_iconst_2:
case JVM_OPC_iconst_3:
case JVM_OPC_iconst_4:
case JVM_OPC_iconst_5: {
break;
}
case JVM_OPC_lconst_0:
case JVM_OPC_lconst_1: {
break;
}
case JVM_OPC_fconst_0:
case JVM_OPC_fconst_1: {
break;
}
case JVM_OPC_dconst_0:
case JVM_OPC_dconst_1: {
break;
}
case JVM_OPC_iload_0:
case JVM_OPC_iload_1:
case JVM_OPC_iload_2:
case JVM_OPC_iload_3: {
uint16_t idx = opc - JVM_OPC_iload_0;
if (idx >= method->max_locals)
return false;
break;
}
case JVM_OPC_aload_0:
case JVM_OPC_aload_1:
case JVM_OPC_aload_2:
case JVM_OPC_aload_3: {
uint16_t idx = opc - JVM_OPC_aload_0;
if (idx >= method->max_locals)
return false;
break;
}
case JVM_OPC_istore: {
auto idx = read_opc_u1(method->code + pc);
if (idx >= method->max_locals)
return false;
break;
}
case JVM_OPC_lstore: {
auto idx = read_opc_u1(method->code + pc);
if (idx >= method->max_locals)
return false;
break;
}
case JVM_OPC_istore_0:
case JVM_OPC_istore_1:
case JVM_OPC_istore_2:
case JVM_OPC_istore_3: {
uint16_t idx = opc - JVM_OPC_istore_0;
if (idx >= method->max_locals)
return false;
break;
}
case JVM_OPC_lstore_0:
case JVM_OPC_lstore_1:
case JVM_OPC_lstore_2:
case JVM_OPC_lstore_3: {
uint16_t idx = opc - JVM_OPC_lstore_0;
if (idx >= method->max_locals)
return false;
break;
}
case JVM_OPC_iadd: {
break;
}
case JVM_OPC_ladd: {
break;
}
case JVM_OPC_isub: {
break;
}
case JVM_OPC_lsub: {
break;
}
case JVM_OPC_imul: {
break;
}
case JVM_OPC_lmul: {
break;
}
case JVM_OPC_idiv: {
break;
}
case JVM_OPC_ldiv: {
break;
}
case JVM_OPC_irem: {
break;
}
case JVM_OPC_lrem: {
break;
}
case JVM_OPC_return: {
break;
}
default:
unsupported_opcode[opc]++;
break;
}
pc += opcode_length[opc];
}
return true;
}
void verifier_stats()
{
if (!verbose_verifier) {
return;
}
fprintf(stderr, "Unsupported opcodes:\n");
fprintf(stderr, " # opcode\n");
for (auto opc = 0; opc < JVM_OPC_MAX; opc++) {
if (unsupported_opcode[opc]) {
fprintf(stderr, "%5d %d\n", unsupported_opcode[opc], opc);
}
}
}
}
<commit_msg>java/verify: Fail assertion instead of looping infinitely<commit_after>#include "hornet/java.hh"
#include "hornet/opcode.hh"
#include <hornet/vm.hh>
#include <classfile_constants.h>
#include <cassert>
#include <stack>
namespace hornet {
bool verbose_verifier;
unsigned char unsupported_opcode[JVM_OPC_MAX+1];
unsigned char opcode_length[JVM_OPC_MAX+1] = JVM_OPCODE_LENGTH_INITIALIZER;
bool verify_method(std::shared_ptr<method> method)
{
unsigned int pc = 0;
for (;;) {
if (pc >= method->code_length)
break;
uint8_t opc = method->code[pc];
assert(opc < JVM_OPC_MAX);
if (is_switch(opc)) {
auto len = switch_opc_len(method->code, pc);
pc += len;
continue;
}
switch (opc) {
case JVM_OPC_iconst_m1:
case JVM_OPC_iconst_0:
case JVM_OPC_iconst_1:
case JVM_OPC_iconst_2:
case JVM_OPC_iconst_3:
case JVM_OPC_iconst_4:
case JVM_OPC_iconst_5: {
break;
}
case JVM_OPC_lconst_0:
case JVM_OPC_lconst_1: {
break;
}
case JVM_OPC_fconst_0:
case JVM_OPC_fconst_1: {
break;
}
case JVM_OPC_dconst_0:
case JVM_OPC_dconst_1: {
break;
}
case JVM_OPC_iload_0:
case JVM_OPC_iload_1:
case JVM_OPC_iload_2:
case JVM_OPC_iload_3: {
uint16_t idx = opc - JVM_OPC_iload_0;
if (idx >= method->max_locals)
return false;
break;
}
case JVM_OPC_aload_0:
case JVM_OPC_aload_1:
case JVM_OPC_aload_2:
case JVM_OPC_aload_3: {
uint16_t idx = opc - JVM_OPC_aload_0;
if (idx >= method->max_locals)
return false;
break;
}
case JVM_OPC_istore: {
auto idx = read_opc_u1(method->code + pc);
if (idx >= method->max_locals)
return false;
break;
}
case JVM_OPC_lstore: {
auto idx = read_opc_u1(method->code + pc);
if (idx >= method->max_locals)
return false;
break;
}
case JVM_OPC_istore_0:
case JVM_OPC_istore_1:
case JVM_OPC_istore_2:
case JVM_OPC_istore_3: {
uint16_t idx = opc - JVM_OPC_istore_0;
if (idx >= method->max_locals)
return false;
break;
}
case JVM_OPC_lstore_0:
case JVM_OPC_lstore_1:
case JVM_OPC_lstore_2:
case JVM_OPC_lstore_3: {
uint16_t idx = opc - JVM_OPC_lstore_0;
if (idx >= method->max_locals)
return false;
break;
}
case JVM_OPC_iadd: {
break;
}
case JVM_OPC_ladd: {
break;
}
case JVM_OPC_isub: {
break;
}
case JVM_OPC_lsub: {
break;
}
case JVM_OPC_imul: {
break;
}
case JVM_OPC_lmul: {
break;
}
case JVM_OPC_idiv: {
break;
}
case JVM_OPC_ldiv: {
break;
}
case JVM_OPC_irem: {
break;
}
case JVM_OPC_lrem: {
break;
}
case JVM_OPC_return: {
break;
}
default:
unsupported_opcode[opc]++;
break;
}
if (opcode_length[opc] <= 0) {
fprintf(stderr, "opcode %u length is %d\n", opc, opcode_length[opc]);
assert(0);
}
pc += opcode_length[opc];
}
return true;
}
void verifier_stats()
{
if (!verbose_verifier) {
return;
}
fprintf(stderr, "Unsupported opcodes:\n");
fprintf(stderr, " # opcode\n");
for (auto opc = 0; opc < JVM_OPC_MAX; opc++) {
if (unsupported_opcode[opc]) {
fprintf(stderr, "%5d %d\n", unsupported_opcode[opc], opc);
}
}
}
}
<|endoftext|> |
<commit_before><commit_msg>disable adding histograms to directory also for root merging<commit_after><|endoftext|> |
<commit_before>#include "chunkstream.cpp" //chunkstream decoding
#include "amf.cpp" //simple AMF0 parsing
std::string streamname = "/tmp/shared_socket";
//gets and parses one chunk
void parseChunk(){
static chunkpack next;
static AMFType amfdata("empty", (unsigned char)0xFF);
static AMFType amfelem("empty", (unsigned char)0xFF);
next = getWholeChunk();
switch (next.msg_type_id){
case 0://does not exist
break;//happens when connection breaks unexpectedly
case 1://set chunk size
chunk_rec_max = ntohl(*(int*)next.data);
#if DEBUG >= 4
fprintf(stderr, "CTRL: Set chunk size: %i\n", chunk_rec_max);
#endif
break;
case 2://abort message - we ignore this one
#if DEBUG >= 4
fprintf(stderr, "CTRL: Abort message\n");
#endif
//4 bytes of stream id to drop
break;
case 3://ack
#if DEBUG >= 4
fprintf(stderr, "CTRL: Acknowledgement\n");
#endif
snd_window_at = ntohl(*(int*)next.data);
snd_window_at = snd_cnt;
break;
case 4:{
#if DEBUG >= 4
short int ucmtype = ntohs(*(short int*)next.data);
fprintf(stderr, "CTRL: User control message %hi\n", ucmtype);
#endif
//2 bytes event type, rest = event data
//types:
//0 = stream begin, 4 bytes ID
//1 = stream EOF, 4 bytes ID
//2 = stream dry, 4 bytes ID
//3 = setbufferlen, 4 bytes ID, 4 bytes length
//4 = streamisrecorded, 4 bytes ID
//6 = pingrequest, 4 bytes data
//7 = pingresponse, 4 bytes data
//we don't need to process this
SendCTL(3, rec_cnt);//send ack (msg 3)
} break;
case 5://window size of other end
#if DEBUG >= 4
fprintf(stderr, "CTRL: Window size\n");
#endif
rec_window_size = ntohl(*(int*)next.data);
rec_window_at = rec_cnt;
SendCTL(3, rec_cnt);//send ack (msg 3)
break;
case 6:
#if DEBUG >= 4
fprintf(stderr, "CTRL: Set peer bandwidth\n");
#endif
//4 bytes window size, 1 byte limit type (ignored)
snd_window_size = ntohl(*(int*)next.data);
SendCTL(5, snd_window_size);//send window acknowledgement size (msg 5)
break;
case 8:
#if DEBUG >= 4
fprintf(stderr, "Received audio data\n");
#endif
break;
case 9:
#if DEBUG >= 4
fprintf(stderr, "Received video data\n");
#endif
break;
case 15:
#if DEBUG >= 4
fprintf(stderr, "Received AFM3 data message\n");
#endif
break;
case 16:
#if DEBUG >= 4
fprintf(stderr, "Received AFM3 shared object\n");
#endif
break;
case 17:
#if DEBUG >= 4
fprintf(stderr, "Received AFM3 command message\n");
#endif
break;
case 18:
#if DEBUG >= 4
fprintf(stderr, "Received AFM0 data message\n");
#endif
break;
case 19:
#if DEBUG >= 4
fprintf(stderr, "Received AFM0 shared object\n");
#endif
break;
case 20:{//AMF0 command message
bool parsed = false;
amfdata = parseAMF(next.data, next.real_len);
#if DEBUG >= 4
amfdata.Print();
#endif
if (amfdata.getContentP(0)->StrValue() == "connect"){
#if DEBUG >= 4
int tmpint;
tmpint = amfdata.getContentP(2)->getContentP("videoCodecs")->NumValue();
if (tmpint & 0x04){fprintf(stderr, "Sorensen video support detected\n");}
if (tmpint & 0x80){fprintf(stderr, "H264 video support detected\n");}
tmpint = amfdata.getContentP(2)->getContentP("audioCodecs")->NumValue();
if (tmpint & 0x04){fprintf(stderr, "MP3 audio support detected\n");}
if (tmpint & 0x400){fprintf(stderr, "AAC video support detected\n");}
#endif
SendCTL(6, rec_window_size, 0);//send peer bandwidth (msg 6)
SendCTL(5, snd_window_size);//send window acknowledgement size (msg 5)
SendUSR(0, 0);//send UCM StreamBegin (0), stream 0
//send a _result reply
AMFType amfreply("container", (unsigned char)0xFF);
amfreply.addContent(AMFType("", "_result"));//result success
amfreply.addContent(amfdata.getContent(1));//same transaction ID
// amfreply.addContent(AMFType("", (double)0, 0x05));//null - command info
amfreply.addContent(AMFType(""));//server properties
amfreply.getContentP(2)->addContent(AMFType("fmsVer", "FMS/3,0,1,123"));//stolen from examples
amfreply.getContentP(2)->addContent(AMFType("capabilities", (double)31));//stolen from examples
amfreply.addContent(AMFType(""));//info
amfreply.getContentP(3)->addContent(AMFType("level", "status"));
amfreply.getContentP(3)->addContent(AMFType("code", "NetConnection.Connect.Success"));
amfreply.getContentP(3)->addContent(AMFType("description", "Connection succeeded."));
amfreply.getContentP(3)->addContent(AMFType("capabilities", (double)33));//from red5 server
amfreply.getContentP(3)->addContent(AMFType("fmsVer", "PLS/1,0,0,0"));//from red5 server
#if DEBUG >= 4
amfreply.Print();
#endif
SendChunk(3, 20, next.msg_stream_id, amfreply.Pack());
//send onBWDone packet
//amfreply = AMFType("container", (unsigned char)0xFF);
//amfreply.addContent(AMFType("", "onBWDone"));//result success
//amfreply.addContent(AMFType("", (double)0));//zero
//amfreply.addContent(AMFType("", (double)0, 0x05));//null
//SendChunk(3, 20, next.msg_stream_id, amfreply.Pack());
parsed = true;
}//connect
if (amfdata.getContentP(0)->StrValue() == "createStream"){
//send a _result reply
AMFType amfreply("container", (unsigned char)0xFF);
amfreply.addContent(AMFType("", "_result"));//result success
amfreply.addContent(amfdata.getContent(1));//same transaction ID
amfreply.addContent(AMFType("", (double)0, 0x05));//null - command info
amfreply.addContent(AMFType("", (double)1));//stream ID - we use 1
#if DEBUG >= 4
amfreply.Print();
#endif
SendChunk(3, 20, next.msg_stream_id, amfreply.Pack());
SendUSR(0, 0);//send UCM StreamBegin (0), stream 0
parsed = true;
}//createStream
if ((amfdata.getContentP(0)->StrValue() == "getStreamLength") || (amfdata.getContentP(0)->StrValue() == "getMovLen")){
//send a _result reply
AMFType amfreply("container", (unsigned char)0xFF);
amfreply.addContent(AMFType("", "_result"));//result success
amfreply.addContent(amfdata.getContent(1));//same transaction ID
amfreply.addContent(AMFType("", (double)0, 0x05));//null - command info
amfreply.addContent(AMFType("", (double)0));//zero length
#if DEBUG >= 4
amfreply.Print();
#endif
SendChunk(3, 20, next.msg_stream_id, amfreply.Pack());
parsed = true;
}//getStreamLength
if (amfdata.getContentP(0)->StrValue() == "checkBandwidth"){
//send a _result reply
AMFType amfreply("container", (unsigned char)0xFF);
amfreply.addContent(AMFType("", "_result"));//result success
amfreply.addContent(amfdata.getContent(1));//same transaction ID
amfreply.addContent(AMFType("", (double)0, 0x05));//null - command info
amfreply.addContent(AMFType("", (double)0, 0x05));//null - command info
#if DEBUG >= 4
amfreply.Print();
#endif
SendChunk(3, 20, 1, amfreply.Pack());
parsed = true;
}//checkBandwidth
if ((amfdata.getContentP(0)->StrValue() == "play") || (amfdata.getContentP(0)->StrValue() == "play2")){
//send streambegin
streamname = amfdata.getContentP(3)->StrValue();
for (std::string::iterator i=streamname.end()-1; i>=streamname.begin(); --i){
if (!isalpha(*i) && !isdigit(*i)){streamname.erase(i);}else{*i=tolower(*i);}
}
streamname = "/tmp/shared_socket_" + streamname;
SendUSR(0, 1);//send UCM StreamBegin (0), stream 1
//send a status reply
AMFType amfreply("container", (unsigned char)0xFF);
amfreply.addContent(AMFType("", "onStatus"));//status reply
amfreply.addContent(amfdata.getContent(1));//same transaction ID
amfreply.addContent(AMFType("", (double)0, 0x05));//null - command info
amfreply.addContent(AMFType(""));//info
amfreply.getContentP(3)->addContent(AMFType("level", "status"));
amfreply.getContentP(3)->addContent(AMFType("code", "NetStream.Play.Reset"));
amfreply.getContentP(3)->addContent(AMFType("description", "Playing and resetting..."));
amfreply.getContentP(3)->addContent(AMFType("details", "PLS"));
amfreply.getContentP(3)->addContent(AMFType("clientid", (double)1));
#if DEBUG >= 4
amfreply.Print();
#endif
SendChunk(4, 20, next.msg_stream_id, amfreply.Pack());
amfreply = AMFType("container", (unsigned char)0xFF);
amfreply.addContent(AMFType("", "onStatus"));//status reply
amfreply.addContent(amfdata.getContent(1));//same transaction ID
amfreply.addContent(AMFType("", (double)0, 0x05));//null - command info
amfreply.addContent(AMFType(""));//info
amfreply.getContentP(3)->addContent(AMFType("level", "status"));
amfreply.getContentP(3)->addContent(AMFType("code", "NetStream.Play.Start"));
amfreply.getContentP(3)->addContent(AMFType("description", "Playing!"));
amfreply.getContentP(3)->addContent(AMFType("details", "PLS"));
amfreply.getContentP(3)->addContent(AMFType("clientid", (double)1));
#if DEBUG >= 4
amfreply.Print();
#endif
SendChunk(4, 20, 1, amfreply.Pack());
//No clue what this does. Most real servers send it, though...
// amfreply = AMFType("container", (unsigned char)0xFF);
// amfreply.addContent(AMFType("", "|RtmpSampleAccess"));//status reply
// amfreply.addContent(AMFType("", (double)1, 0x01));//bool true - audioaccess
// amfreply.addContent(AMFType("", (double)1, 0x01));//bool true - videoaccess
// SendChunk(4, 20, next.msg_stream_id, amfreply.Pack());
chunk_snd_max = 1024*1024;
SendCTL(1, chunk_snd_max);//send chunk size max (msg 1)
ready4data = true;//start sending video data!
parsed = true;
}//createStream
#if DEBUG >= 3
fprintf(stderr, "AMF0 command: %s\n", amfdata.getContentP(0)->StrValue().c_str());
#endif
if (!parsed){
#if DEBUG >= 2
fprintf(stderr, "AMF0 command not processed! :(\n");
#endif
}
} break;
case 22:
#if DEBUG >= 4
fprintf(stderr, "Received aggregate message\n");
#endif
break;
default:
#if DEBUG >= 1
fprintf(stderr, "Unknown chunk received! Probably protocol corruption, stopping parsing of incoming data.\n");
#endif
stopparsing = true;
break;
}
}//parseChunk
<commit_msg>Contd<commit_after>#include "chunkstream.cpp" //chunkstream decoding
#include "amf.cpp" //simple AMF0 parsing
std::string streamname = "/tmp/shared_socket";
//gets and parses one chunk
void parseChunk(){
static chunkpack next;
static AMFType amfdata("empty", (unsigned char)0xFF);
static AMFType amfelem("empty", (unsigned char)0xFF);
next = getWholeChunk();
switch (next.msg_type_id){
case 0://does not exist
break;//happens when connection breaks unexpectedly
case 1://set chunk size
chunk_rec_max = ntohl(*(int*)next.data);
#if DEBUG >= 4
fprintf(stderr, "CTRL: Set chunk size: %i\n", chunk_rec_max);
#endif
break;
case 2://abort message - we ignore this one
#if DEBUG >= 4
fprintf(stderr, "CTRL: Abort message\n");
#endif
//4 bytes of stream id to drop
break;
case 3://ack
#if DEBUG >= 4
fprintf(stderr, "CTRL: Acknowledgement\n");
#endif
snd_window_at = ntohl(*(int*)next.data);
snd_window_at = snd_cnt;
break;
case 4:{
#if DEBUG >= 4
short int ucmtype = ntohs(*(short int*)next.data);
fprintf(stderr, "CTRL: User control message %hi\n", ucmtype);
#endif
//2 bytes event type, rest = event data
//types:
//0 = stream begin, 4 bytes ID
//1 = stream EOF, 4 bytes ID
//2 = stream dry, 4 bytes ID
//3 = setbufferlen, 4 bytes ID, 4 bytes length
//4 = streamisrecorded, 4 bytes ID
//6 = pingrequest, 4 bytes data
//7 = pingresponse, 4 bytes data
//we don't need to process this
SendCTL(3, rec_cnt);//send ack (msg 3)
} break;
case 5://window size of other end
#if DEBUG >= 4
fprintf(stderr, "CTRL: Window size\n");
#endif
rec_window_size = ntohl(*(int*)next.data);
rec_window_at = rec_cnt;
SendCTL(3, rec_cnt);//send ack (msg 3)
break;
case 6:
#if DEBUG >= 4
fprintf(stderr, "CTRL: Set peer bandwidth\n");
#endif
//4 bytes window size, 1 byte limit type (ignored)
snd_window_size = ntohl(*(int*)next.data);
SendCTL(5, snd_window_size);//send window acknowledgement size (msg 5)
break;
case 8:
#if DEBUG >= 4
fprintf(stderr, "Received audio data\n");
#endif
break;
case 9:
#if DEBUG >= 4
fprintf(stderr, "Received video data\n");
#endif
break;
case 15:
#if DEBUG >= 4
fprintf(stderr, "Received AFM3 data message\n");
#endif
break;
case 16:
#if DEBUG >= 4
fprintf(stderr, "Received AFM3 shared object\n");
#endif
break;
case 17:
#if DEBUG >= 4
fprintf(stderr, "Received AFM3 command message\n");
#endif
break;
case 18:
#if DEBUG >= 4
fprintf(stderr, "Received AFM0 data message\n");
#endif
break;
case 19:
#if DEBUG >= 4
fprintf(stderr, "Received AFM0 shared object\n");
#endif
break;
case 20:{//AMF0 command message
bool parsed = false;
amfdata = parseAMF(next.data, next.real_len);
#if DEBUG >= 4
amfdata.Print();
#endif
if (amfdata.getContentP(0)->StrValue() == "connect"){
#if DEBUG >= 4
int tmpint;
tmpint = amfdata.getContentP(2)->getContentP("videoCodecs")->NumValue();
if (tmpint & 0x04){fprintf(stderr, "Sorensen video support detected\n");}
if (tmpint & 0x80){fprintf(stderr, "H264 video support detected\n");}
tmpint = amfdata.getContentP(2)->getContentP("audioCodecs")->NumValue();
if (tmpint & 0x04){fprintf(stderr, "MP3 audio support detected\n");}
if (tmpint & 0x400){fprintf(stderr, "AAC video support detected\n");}
#endif
SendCTL(6, rec_window_size, 0);//send peer bandwidth (msg 6)
SendCTL(5, snd_window_size);//send window acknowledgement size (msg 5)
SendUSR(0, 1);//send UCM StreamBegin (0), stream 1
//send a _result reply
AMFType amfreply("container", (unsigned char)0xFF);
amfreply.addContent(AMFType("", "_result"));//result success
amfreply.addContent(amfdata.getContent(1));//same transaction ID
// amfreply.addContent(AMFType("", (double)0, 0x05));//null - command info
amfreply.addContent(AMFType(""));//server properties
amfreply.getContentP(2)->addContent(AMFType("fmsVer", "FMS/3,0,1,123"));//stolen from examples
amfreply.getContentP(2)->addContent(AMFType("capabilities", (double)31));//stolen from examples
amfreply.addContent(AMFType(""));//info
amfreply.getContentP(3)->addContent(AMFType("level", "status"));
amfreply.getContentP(3)->addContent(AMFType("code", "NetConnection.Connect.Success"));
amfreply.getContentP(3)->addContent(AMFType("description", "Connection succeeded."));
amfreply.getContentP(3)->addContent(AMFType("capabilities", (double)33));//from red5 server
amfreply.getContentP(3)->addContent(AMFType("fmsVer", "PLS/1,0,0,0"));//from red5 server
#if DEBUG >= 4
amfreply.Print();
#endif
SendChunk(3, 20, next.msg_stream_id, amfreply.Pack());
//send onBWDone packet
//amfreply = AMFType("container", (unsigned char)0xFF);
//amfreply.addContent(AMFType("", "onBWDone"));//result success
//amfreply.addContent(AMFType("", (double)0));//zero
//amfreply.addContent(AMFType("", (double)0, 0x05));//null
//SendChunk(3, 20, next.msg_stream_id, amfreply.Pack());
parsed = true;
}//connect
if (amfdata.getContentP(0)->StrValue() == "createStream"){
//send a _result reply
AMFType amfreply("container", (unsigned char)0xFF);
amfreply.addContent(AMFType("", "_result"));//result success
amfreply.addContent(amfdata.getContent(1));//same transaction ID
amfreply.addContent(AMFType("", (double)0, 0x05));//null - command info
amfreply.addContent(AMFType("", (double)1));//stream ID - we use 1
#if DEBUG >= 4
amfreply.Print();
#endif
SendChunk(3, 20, next.msg_stream_id, amfreply.Pack());
SendUSR(0, 1);//send UCM StreamBegin (0), stream 1
parsed = true;
}//createStream
if ((amfdata.getContentP(0)->StrValue() == "getStreamLength") || (amfdata.getContentP(0)->StrValue() == "getMovLen")){
//send a _result reply
AMFType amfreply("container", (unsigned char)0xFF);
amfreply.addContent(AMFType("", "_result"));//result success
amfreply.addContent(amfdata.getContent(1));//same transaction ID
amfreply.addContent(AMFType("", (double)0, 0x05));//null - command info
amfreply.addContent(AMFType("", (double)0));//zero length
#if DEBUG >= 4
amfreply.Print();
#endif
SendChunk(3, 20, next.msg_stream_id, amfreply.Pack());
parsed = true;
}//getStreamLength
if (amfdata.getContentP(0)->StrValue() == "checkBandwidth"){
//send a _result reply
AMFType amfreply("container", (unsigned char)0xFF);
amfreply.addContent(AMFType("", "_result"));//result success
amfreply.addContent(amfdata.getContent(1));//same transaction ID
amfreply.addContent(AMFType("", (double)0, 0x05));//null - command info
amfreply.addContent(AMFType("", (double)0, 0x05));//null - command info
#if DEBUG >= 4
amfreply.Print();
#endif
SendChunk(3, 20, 1, amfreply.Pack());
parsed = true;
}//checkBandwidth
if ((amfdata.getContentP(0)->StrValue() == "play") || (amfdata.getContentP(0)->StrValue() == "play2")){
//send streambegin
streamname = amfdata.getContentP(3)->StrValue();
for (std::string::iterator i=streamname.end()-1; i>=streamname.begin(); --i){
if (!isalpha(*i) && !isdigit(*i)){streamname.erase(i);}else{*i=tolower(*i);}
}
streamname = "/tmp/shared_socket_" + streamname;
SendUSR(0, 1);//send UCM StreamBegin (0), stream 1
//send a status reply
AMFType amfreply("container", (unsigned char)0xFF);
amfreply.addContent(AMFType("", "onStatus"));//status reply
amfreply.addContent(amfdata.getContent(1));//same transaction ID
amfreply.addContent(AMFType("", (double)0, 0x05));//null - command info
amfreply.addContent(AMFType(""));//info
amfreply.getContentP(3)->addContent(AMFType("level", "status"));
amfreply.getContentP(3)->addContent(AMFType("code", "NetStream.Play.Reset"));
amfreply.getContentP(3)->addContent(AMFType("description", "Playing and resetting..."));
amfreply.getContentP(3)->addContent(AMFType("details", "PLS"));
amfreply.getContentP(3)->addContent(AMFType("clientid", (double)1));
#if DEBUG >= 4
amfreply.Print();
#endif
SendChunk(4, 20, next.msg_stream_id, amfreply.Pack());
amfreply = AMFType("container", (unsigned char)0xFF);
amfreply.addContent(AMFType("", "onStatus"));//status reply
amfreply.addContent(amfdata.getContent(1));//same transaction ID
amfreply.addContent(AMFType("", (double)0, 0x05));//null - command info
amfreply.addContent(AMFType(""));//info
amfreply.getContentP(3)->addContent(AMFType("level", "status"));
amfreply.getContentP(3)->addContent(AMFType("code", "NetStream.Play.Start"));
amfreply.getContentP(3)->addContent(AMFType("description", "Playing!"));
amfreply.getContentP(3)->addContent(AMFType("details", "PLS"));
amfreply.getContentP(3)->addContent(AMFType("clientid", (double)1));
#if DEBUG >= 4
amfreply.Print();
#endif
SendChunk(4, 20, 1, amfreply.Pack());
//No clue what this does. Most real servers send it, though...
// amfreply = AMFType("container", (unsigned char)0xFF);
// amfreply.addContent(AMFType("", "|RtmpSampleAccess"));//status reply
// amfreply.addContent(AMFType("", (double)1, 0x01));//bool true - audioaccess
// amfreply.addContent(AMFType("", (double)1, 0x01));//bool true - videoaccess
// SendChunk(4, 20, next.msg_stream_id, amfreply.Pack());
chunk_snd_max = 1024*1024;
SendCTL(1, chunk_snd_max);//send chunk size max (msg 1)
ready4data = true;//start sending video data!
parsed = true;
}//createStream
#if DEBUG >= 3
fprintf(stderr, "AMF0 command: %s\n", amfdata.getContentP(0)->StrValue().c_str());
#endif
if (!parsed){
#if DEBUG >= 2
fprintf(stderr, "AMF0 command not processed! :(\n");
#endif
}
} break;
case 22:
#if DEBUG >= 4
fprintf(stderr, "Received aggregate message\n");
#endif
break;
default:
#if DEBUG >= 1
fprintf(stderr, "Unknown chunk received! Probably protocol corruption, stopping parsing of incoming data.\n");
#endif
stopparsing = true;
break;
}
}//parseChunk
<|endoftext|> |
<commit_before>/*
Copyright (c) 2009-2013, Jack Poulson
All rights reserved.
This file is part of Elemental and is under the BSD 2-Clause License,
which can be found in the LICENSE file in the root directory, or at
http://opensource.org/licenses/BSD-2-Clause
*/
// NOTE: It is possible to simply include "elemental.hpp" instead
#include "elemental-lite.hpp"
#include "elemental/matrices/Fourier.hpp"
#include "elemental/io.hpp"
using namespace elem;
int
main( int argc, char* argv[] )
{
Initialize( argc, argv );
try
{
const int n = Input("--size","size of matrix",10);
const bool display = Input("--display","display matrix?",true);
const bool print = Input("--print","print matrix?",false);
ProcessInput();
PrintInputReport();
DistMatrix<Complex<double> > A;
Fourier( A, n );
if( display )
Display( A, "Fourier Matrix" );
if( print )
A.Print("Fourier matrix:");
}
catch( std::exception& e ) { ReportException(e); }
Finalize();
return 0;
}
<commit_msg>Extending Fourier transform example to demonstrate low-rank property of submatrices<commit_after>/*
Copyright (c) 2009-2013, Jack Poulson
All rights reserved.
This file is part of Elemental and is under the BSD 2-Clause License,
which can be found in the LICENSE file in the root directory, or at
http://opensource.org/licenses/BSD-2-Clause
*/
// NOTE: It is possible to simply include "elemental.hpp" instead
#include "elemental-lite.hpp"
#include "elemental/lapack-like/SVD.hpp"
#include "elemental/matrices/Fourier.hpp"
#include "elemental/io.hpp"
using namespace elem;
int
main( int argc, char* argv[] )
{
Initialize( argc, argv );
try
{
const int n = Input("--size","size of matrix",10);
const bool display = Input("--display","display matrix?",true);
const bool print = Input("--print","print matrix?",false);
ProcessInput();
PrintInputReport();
DistMatrix<Complex<double> > A;
Fourier( A, n );
if( display )
Display( A, "Fourier Matrix" );
if( print )
A.Print("Fourier matrix:");
if( n >= 50 )
{
const int nSqrt = Sqrt( double(n) );
DistMatrix<Complex<double> > AMid, AMidCopy;
if( mpi::WorldRank() == 0 )
std::cout << "Viewing " << nSqrt << " x " << nSqrt << " block "
<< "starting at ("
<< (n-nSqrt)/2 << "," << (n-nSqrt)/2 << ")"
<< std::endl;
View( AMid, A, (n-nSqrt)/2, (n-nSqrt)/2, nSqrt, nSqrt );
if( display )
Display( AMid, "Middle block" );
if( print )
AMid.Print("Middle block");
AMidCopy = AMid;
DistMatrix<double,VR,STAR> s;
SVD( AMidCopy, s );
s.Print("singular values of middle block");
}
}
catch( std::exception& e ) { ReportException(e); }
Finalize();
return 0;
}
<|endoftext|> |
<commit_before>// Copyright (c) 2011-2013 The Bitcoin developers
// Distributed under the MIT/X11 software license, see the accompanying
// file COPYING or http://www.opensource.org/licenses/mit-license.php.
#include "bitcoinunits.h"
#include <QStringList>
BitcoinUnits::BitcoinUnits(QObject *parent):
QAbstractListModel(parent),
unitlist(availableUnits())
{
}
QList<BitcoinUnits::Unit> BitcoinUnits::availableUnits()
{
QList<BitcoinUnits::Unit> unitlist;
unitlist.append(BTC);
unitlist.append(mBTC);
unitlist.append(uBTC);
return unitlist;
}
bool BitcoinUnits::valid(int unit)
{
switch(unit)
{
case BTC:
case mBTC:
case uBTC:
return true;
default:
return false;
}
}
QString BitcoinUnits::id(int unit)
{
switch(unit)
{
case BTC: return QString("rdd");
case mBTC: return QString("mrdd");
case uBTC: return QString("urdd");
default: return QString("???");
}
}
QString BitcoinUnits::name(int unit)
{
switch(unit)
{
case BTC: return QString("RDD");
case mBTC: return QString("mRDD");
case uBTC: return QString::fromUtf8("μRDD");
default: return QString("???");
}
}
QString BitcoinUnits::description(int unit)
{
switch(unit)
{
case BTC: return QString("Reddcoins");
case mBTC: return QString("Milli-Reddcoins (1 / 1" THIN_SP_UTF8 "000)");
case uBTC: return QString("Micro-Reddcoins (1 / 1" THIN_SP_UTF8 "000" THIN_SP_UTF8 "000)");
default: return QString("???");
}
}
qint64 BitcoinUnits::factor(int unit)
{
switch(unit)
{
case BTC: return 100000000;
case mBTC: return 100000;
case uBTC: return 100;
default: return 100000000;
}
}
qint64 BitcoinUnits::maxAmount(int unit)
{
switch(unit)
{
case BTC: return Q_INT64_C(99999999);
case mBTC: return Q_INT64_C(99999999999);
case uBTC: return Q_INT64_C(99999999999999);
default: return 0;
}
}
int BitcoinUnits::amountDigits(int unit)
{
switch(unit)
{
case BTC: return 8; // 21,000,000 (# digits, without commas)
case mBTC: return 11; // 21,000,000,000
case uBTC: return 14; // 21,000,000,000,000
default: return 0;
}
}
int BitcoinUnits::decimals(int unit)
{
switch(unit)
{
case BTC: return 8;
case mBTC: return 5;
case uBTC: return 2;
default: return 0;
}
}
QString BitcoinUnits::format(int unit, qint64 n, bool fPlus, SeparatorStyle separators)
{
// Note: not using straight sprintf here because we do NOT want
// localized number formatting.
if(!valid(unit))
return QString(); // Refuse to format invalid unit
qint64 coin = factor(unit);
int num_decimals = decimals(unit);
qint64 n_abs = (n > 0 ? n : -n);
qint64 quotient = n_abs / coin;
qint64 remainder = n_abs % coin;
QString quotient_str = QString::number(quotient);
QString remainder_str = QString::number(remainder).rightJustified(num_decimals, '0');
// Use SI-stule separators as these are locale indendent and can't be
// confused with the decimal marker. Rule is to use a thin space every
// three digits on *both* sides of the decimal point - but only if there
// are five or more digits
QChar thin_sp(THIN_SP_CP);
int q_size = quotient_str.size();
if (separators == separatorAlways || (separators == separatorStandard && q_size > 4))
for (int i = 3; i < q_size; i += 3)
quotient_str.insert(q_size - i, thin_sp);
int r_size = remainder_str.size();
if (separators == separatorAlways || (separators == separatorStandard && r_size > 4))
for (int i = 3, adj = 0; i < r_size ; i += 3, adj++)
remainder_str.insert(i + adj, thin_sp);
if (n < 0)
quotient_str.insert(0, '-');
else if (fPlus && n > 0)
quotient_str.insert(0, '+');
return quotient_str + QString(".") + remainder_str;
}
QString BitcoinUnits::formatWithUnit(int unit, qint64 amount, bool plussign, SeparatorStyle separators)
{
return format(unit, amount, plussign, separators) + QString(" ") + name(unit);
}
QString BitcoinUnits::formatHtmlWithUnit(int unit, qint64 amount, bool plussign, SeparatorStyle separators)
{
QString str(formatWithUnit(unit, amount, plussign, separators));
str.replace(QChar(THIN_SP_CP), QString(THIN_SP_HTML));
return QString("<span style='white-space: nowrap;'>%1</span>").arg(str);
}
bool BitcoinUnits::parse(int unit, const QString &value, qint64 *val_out)
{
if(!valid(unit) || value.isEmpty())
return false; // Refuse to parse invalid unit or empty string
int num_decimals = decimals(unit);
// Ignore spaces and thin spaces when parsing
QStringList parts = removeSpaces(value).split(".");
if(parts.size() > 2)
{
return false; // More than one dot
}
QString whole = parts[0];
QString decimals;
if(parts.size() > 1)
{
decimals = parts[1];
}
if(decimals.size() > num_decimals)
{
return false; // Exceeds max precision
}
bool ok = false;
QString str = whole + decimals.leftJustified(num_decimals, '0');
if(str.size() > 18)
{
return false; // Longer numbers will exceed 63 bits
}
qint64 retvalue = str.toLongLong(&ok);
if(val_out)
{
*val_out = retvalue;
}
return ok;
}
QString BitcoinUnits::getAmountColumnTitle(int unit)
{
QString amountTitle = QObject::tr("Amount");
if (BitcoinUnits::valid(unit))
{
amountTitle += " ("+BitcoinUnits::name(unit) + ")";
}
return amountTitle;
}
int BitcoinUnits::rowCount(const QModelIndex &parent) const
{
Q_UNUSED(parent);
return unitlist.size();
}
QVariant BitcoinUnits::data(const QModelIndex &index, int role) const
{
int row = index.row();
if(row >= 0 && row < unitlist.size())
{
Unit unit = unitlist.at(row);
switch(role)
{
case Qt::EditRole:
case Qt::DisplayRole:
return QVariant(name(unit));
case Qt::ToolTipRole:
return QVariant(description(unit));
case UnitRole:
return QVariant(static_cast<int>(unit));
}
}
return QVariant();
}
<commit_msg>Add comments re BitcoinUnits::formatWithUnit/formatHtmlWithUnit<commit_after>// Copyright (c) 2011-2013 The Bitcoin developers
// Distributed under the MIT/X11 software license, see the accompanying
// file COPYING or http://www.opensource.org/licenses/mit-license.php.
#include "bitcoinunits.h"
#include <QStringList>
BitcoinUnits::BitcoinUnits(QObject *parent):
QAbstractListModel(parent),
unitlist(availableUnits())
{
}
QList<BitcoinUnits::Unit> BitcoinUnits::availableUnits()
{
QList<BitcoinUnits::Unit> unitlist;
unitlist.append(BTC);
unitlist.append(mBTC);
unitlist.append(uBTC);
return unitlist;
}
bool BitcoinUnits::valid(int unit)
{
switch(unit)
{
case BTC:
case mBTC:
case uBTC:
return true;
default:
return false;
}
}
QString BitcoinUnits::id(int unit)
{
switch(unit)
{
case BTC: return QString("rdd");
case mBTC: return QString("mrdd");
case uBTC: return QString("urdd");
default: return QString("???");
}
}
QString BitcoinUnits::name(int unit)
{
switch(unit)
{
case BTC: return QString("RDD");
case mBTC: return QString("mRDD");
case uBTC: return QString::fromUtf8("μRDD");
default: return QString("???");
}
}
QString BitcoinUnits::description(int unit)
{
switch(unit)
{
case BTC: return QString("Reddcoins");
case mBTC: return QString("Milli-Reddcoins (1 / 1" THIN_SP_UTF8 "000)");
case uBTC: return QString("Micro-Reddcoins (1 / 1" THIN_SP_UTF8 "000" THIN_SP_UTF8 "000)");
default: return QString("???");
}
}
qint64 BitcoinUnits::factor(int unit)
{
switch(unit)
{
case BTC: return 100000000;
case mBTC: return 100000;
case uBTC: return 100;
default: return 100000000;
}
}
qint64 BitcoinUnits::maxAmount(int unit)
{
switch(unit)
{
case BTC: return Q_INT64_C(99999999);
case mBTC: return Q_INT64_C(99999999999);
case uBTC: return Q_INT64_C(99999999999999);
default: return 0;
}
}
int BitcoinUnits::amountDigits(int unit)
{
switch(unit)
{
case BTC: return 8; // 21,000,000 (# digits, without commas)
case mBTC: return 11; // 21,000,000,000
case uBTC: return 14; // 21,000,000,000,000
default: return 0;
}
}
int BitcoinUnits::decimals(int unit)
{
switch(unit)
{
case BTC: return 8;
case mBTC: return 5;
case uBTC: return 2;
default: return 0;
}
}
QString BitcoinUnits::format(int unit, qint64 n, bool fPlus, SeparatorStyle separators)
{
// Note: not using straight sprintf here because we do NOT want
// localized number formatting.
if(!valid(unit))
return QString(); // Refuse to format invalid unit
qint64 coin = factor(unit);
int num_decimals = decimals(unit);
qint64 n_abs = (n > 0 ? n : -n);
qint64 quotient = n_abs / coin;
qint64 remainder = n_abs % coin;
QString quotient_str = QString::number(quotient);
QString remainder_str = QString::number(remainder).rightJustified(num_decimals, '0');
// Use SI-stule separators as these are locale indendent and can't be
// confused with the decimal marker. Rule is to use a thin space every
// three digits on *both* sides of the decimal point - but only if there
// are five or more digits
QChar thin_sp(THIN_SP_CP);
int q_size = quotient_str.size();
if (separators == separatorAlways || (separators == separatorStandard && q_size > 4))
for (int i = 3; i < q_size; i += 3)
quotient_str.insert(q_size - i, thin_sp);
int r_size = remainder_str.size();
if (separators == separatorAlways || (separators == separatorStandard && r_size > 4))
for (int i = 3, adj = 0; i < r_size ; i += 3, adj++)
remainder_str.insert(i + adj, thin_sp);
if (n < 0)
quotient_str.insert(0, '-');
else if (fPlus && n > 0)
quotient_str.insert(0, '+');
return quotient_str + QString(".") + remainder_str;
}
// TODO: Review all remaining calls to BitcoinUnits::formatWithUnit to
// TODO: determine whether the output is used in a plain text context
// TODO: or an HTML context (and replace with
// TODO: BtcoinUnits::formatHtmlWithUnit in the latter case). Hopefully
// TODO: there aren't instances where the result could be used in
// TODO: either context.
// NOTE: Using formatWithUnit in an HTML context risks wrapping
// quantities at the thousands separator. More subtly, it also results
// in a standard space rather than a thin space, due to a bug in Qt's
// XML whitespace canonicalisation
//
// Please take care to use formatHtmlWithUnit instead, when
// appropriate.
QString BitcoinUnits::formatWithUnit(int unit, qint64 amount, bool plussign, SeparatorStyle separators)
{
return format(unit, amount, plussign, separators) + QString(" ") + name(unit);
}
QString BitcoinUnits::formatHtmlWithUnit(int unit, qint64 amount, bool plussign, SeparatorStyle separators)
{
QString str(formatWithUnit(unit, amount, plussign, separators));
str.replace(QChar(THIN_SP_CP), QString(THIN_SP_HTML));
return QString("<span style='white-space: nowrap;'>%1</span>").arg(str);
}
bool BitcoinUnits::parse(int unit, const QString &value, qint64 *val_out)
{
if(!valid(unit) || value.isEmpty())
return false; // Refuse to parse invalid unit or empty string
int num_decimals = decimals(unit);
// Ignore spaces and thin spaces when parsing
QStringList parts = removeSpaces(value).split(".");
if(parts.size() > 2)
{
return false; // More than one dot
}
QString whole = parts[0];
QString decimals;
if(parts.size() > 1)
{
decimals = parts[1];
}
if(decimals.size() > num_decimals)
{
return false; // Exceeds max precision
}
bool ok = false;
QString str = whole + decimals.leftJustified(num_decimals, '0');
if(str.size() > 18)
{
return false; // Longer numbers will exceed 63 bits
}
qint64 retvalue = str.toLongLong(&ok);
if(val_out)
{
*val_out = retvalue;
}
return ok;
}
QString BitcoinUnits::getAmountColumnTitle(int unit)
{
QString amountTitle = QObject::tr("Amount");
if (BitcoinUnits::valid(unit))
{
amountTitle += " ("+BitcoinUnits::name(unit) + ")";
}
return amountTitle;
}
int BitcoinUnits::rowCount(const QModelIndex &parent) const
{
Q_UNUSED(parent);
return unitlist.size();
}
QVariant BitcoinUnits::data(const QModelIndex &index, int role) const
{
int row = index.row();
if(row >= 0 && row < unitlist.size())
{
Unit unit = unitlist.at(row);
switch(role)
{
case Qt::EditRole:
case Qt::DisplayRole:
return QVariant(name(unit));
case Qt::ToolTipRole:
return QVariant(description(unit));
case UnitRole:
return QVariant(static_cast<int>(unit));
}
}
return QVariant();
}
<|endoftext|> |
<commit_before>#include "xbeepacket.h"
#include <QDebug>
namespace QtXBee {
/**
* @brief XBeePacket's constructor
* @param parent
*/
XBeePacket::XBeePacket(QObject *parent) :
QObject(parent),
m_startDelimiter(0x7E),
m_length(0),
m_frameType(UndefinedId),
m_frameId(0),
m_checksum(0)
{
}
/**
* @brief Sets the frame's start delimiter.
* By default the start delemiter is set to 0x7E
* @sa XBeePacket::startDelimiter()
* @param sd
*/
void XBeePacket::setStartDelimiter(unsigned sd) {
m_startDelimiter = sd;
}
/**
* @brief Sets the frame's length
* @param l
* @sa XBeePacket::length()
*/
void XBeePacket::setLength(unsigned l) {
m_length = l;
}
/**
* @brief Sets the frame's type
* @param type
* @sa XBeePacket::frameType()
*/
void XBeePacket::setFrameType(ApiId type) {
m_frameType = type;
}
/**
* @brief Sets the frame's id
* @param id
* @sa XBeePacket::frameType()
*/
void XBeePacket::setFrameId(unsigned id) {
m_frameId = id;
}
/**
* @brief Sets the checksum
* @param cs
* @sa XBeePacket::checksum()
*/
void XBeePacket::setChecksum(unsigned cs) {
m_checksum = cs;
}
/**
* @brief Returns the frame's start delimiter
* @returns the frame's start delimiter
* @sa XBeePacket::setStartDelimiter()
*/
unsigned XBeePacket::startDelimiter() const {
return m_startDelimiter;
}
/**
* @brief Returns the frame-specific data length (Number of bytes between the length and the checksum)
* @returns the packet's length
* @sa XBeePacket::setLength()
*/
quint16 XBeePacket::length() const {
return m_length;
}
/**
* @brief Returns the frame's type
* @returns the frame's type
* @sa XBeePacket::setFrameType()
* @sa XBeePacket::APIFrameType
*/
XBeePacket::ApiId XBeePacket::frameType() const {
return m_frameType;
}
/**
* @brief Returns the frame's id
* @returns the frame's id
* @sa XBeePacket::setFrameId()
*/
unsigned XBeePacket::frameId() const {
return m_frameId;
}
/**
* @brief Returns the packet's checksum
* @returns the packet's checksum
* @sa XBeePacket::setChecksum()
*/
unsigned XBeePacket::checksum() const {
return m_checksum;
}
/**
* @brief Computes the checksum of the given QByteArray, and set it.
* @param array
* @sa XBeePacket::setChecksum()
* @sa XBeePacket::checksum()
*/
void XBeePacket::createChecksum(QByteArray array) {
int len = array.size();
unsigned int sum = 0x00;
unsigned int ff = 0xFF;
unsigned int fe = 0xFE;
for(int i=0;i<len;i++)
{
unsigned int a = array.at(i);
if (a == (unsigned int)4294967295){
a = ff;
} else if (a == (unsigned int)4294967294){
a = fe;
}
sum += a;
}
setChecksum((ff - sum) & 0x000000FF);
}
/**
* @brief Returns the frame's packet (raw data)
* @returns the frame's packet (raw data)
*/
QByteArray XBeePacket::packet() const {
return m_packet;
}
bool XBeePacket::setPacket(const QByteArray &packet) {
ApiId apiId = UndefinedId;
quint8 apiSpecificOffset = 4; // 5th byte
QByteArray specificData;
clear();
m_packet = packet;
if(packet.size() < 5) {
qDebug() << Q_FUNC_INFO << "bad packet !";
return false;
}
setStartDelimiter(packet.at(0));
setLength((unsigned char)packet.at(2) + ((unsigned char)packet.at(1)<<8));
apiId = (ApiId)(packet.at(3)&0xff);
// qDebug() << "apiid" << apiId << ",frame type" << m_frameType;
// if(apiId != m_frameType) {
// qDebug() << Q_FUNC_INFO << "Bad API frame ID !" << qPrintable(QString("(expected 0x%1, got 0x%2)").arg(m_frameType,0,16).arg(apiId,0,16));
// return false;
// }
setFrameType(apiId);
if(packet.size() > 5) {
for(int i=apiSpecificOffset; i< packet.size(); i++) {
specificData.append(packet.at(i));
}
parseApiSpecificData(specificData);
}
setChecksum(packet.at(packet.size()-1));
assemblePacket();
return true;
}
bool XBeePacket::parseApiSpecificData(const QByteArray &data) {
Q_UNUSED(data)
return false;
}
/**
* @brief Assembles the packet to be able to send it.
*
* Overload this function to create your own packet.
*/
void XBeePacket::assemblePacket() {
}
void XBeePacket::clear() {
m_packet.clear();
m_startDelimiter = 0x7E;
m_length = 0;
m_frameType = UndefinedId;
m_frameId = -1;
m_checksum = -1;
}
/**
* @brief Returns a debug string containing all packet's informations.
* @returns a debug string containing all packet's informations.
*/
QString XBeePacket::toString() {
QString str;
str.append(QString("Raw packet : 0x%1\n").arg(QString(packet().toHex())));
str.append(QString("Frame id : %1 (0x%2)\n").arg(frameId(), 0, 16).arg(frameId(), 0, 16));
str.append(QString("Frame type : %1 (0x%2)\n").arg(frameTypeToString(frameType())).arg(QString::number(frameType(), 16)));
str.append(QString("Start delimiter : 0x%1\n").arg(QString::number(startDelimiter(), 16)));
str.append(QString("Length : %1 bytes\n").arg(m_length));
str.append(QString("Checksum : %1\n").arg(checksum()));
return str;
}
/**
* @brief Returns the given frame type APIFrameType into a human readable string
* @returns the given frame type APIFrameType into a human readable string
* @param type
*/
QString XBeePacket::frameTypeToString(const ApiId type) {
QString str;
switch(type) {
case TXRequest64Id : str = "Tx 16 bits Address Request" ; break;
case TXRequest16Id : str = "Tx 16 bits Address Request" ; break;
case ATCommandId : str = "AT Command Request" ; break;
case ATCommandQueueId : str = "AT Command - Queue Parameter Request" ; break;
case ZBTXRequestId : str = "ZigBee Tx Request" ; break;
case ZBExplicitTxRequest : str = "ZigBee Explicit Tx Request" ; break;
case RemoteATCommandRequestId : str = "Remote AT Command Request" ; break;
case CreateSourceRouteId : str = "Create Source Route" ; break;
case RX64ResponseId : str = "Rx 64 bits Address Response" ; break;
case RX16ResponseId : str = "Rx 16 bits Address Response" ; break;
case RX64IOResponseId : str = "Rx 64 bits Address I/O Response" ; break;
case RX16IOResponseId : str = "Rx 16 bits Address I/O Response" ; break;
case ATCommandResponseId : str = "AT Command Response" ; break;
case TXStatusResponseId : str = "Tx Status Response" ; break;
case ModemStatusResponseId : str = "Modem Status Response" ; break;
case ZBTXStatusResponseId : str = "ZigBee Tx Status Response" ; break;
case ZBRXResponseId : str = "ZigBee Rx Response" ; break;
case ZBExplicitRxResponseId : str = "ZigBee Explicit Rx Response" ; break;
case ZBIOSampleResponseId : str = "ZigBee I/O Sample Response" ; break;
case XBeeSensorReadIndicatorId : str = "XBee Sensore Read Indicator" ; break;
case ZBIONodeIdentificationId : str = "ZigBee I/O Node Indentification Indicator" ; break;
case RemoteATCommandResponseId : str = "Remote AT Command Response" ; break;
case OverTheAirFirmwareUpdateId : str = "Over-the-air Firmware Update" ; break;
case RouteRecordIndicatorId : str = "Route Record Indicator" ; break;
case ManyToOneRouteRequestId : str = "Many-to-one Route Request" ; break;
default : str = "Unkown" ; break;
}
return str;
}
void XBeePacket::escapePacket()
{
int escapeBytes = 0;
QByteArray escapedPacked;
int i;
// Skip byte 0 (start delimiter)
for (i=1; i<m_packet.size(); i++) {
if (isSpecialByte(m_packet.at(i))) {
qDebug() << Q_FUNC_INFO << "packet requires escaping for byte" << i << "(" <<QByteArray().append(m_packet.at(i)).toHex() << ")";
escapeBytes++;
}
}
if (escapeBytes == 0) {
qDebug() << "No need to escape packet" << m_packet.toHex();
return;
}
else {
qDebug() << Q_FUNC_INFO << "packet need to be escaped";
int pos = 1;
escapedPacked.reserve(m_packet.size() + escapeBytes);
escapedPacked[0] = startDelimiter();
for (i = 1; i < m_packet.size(); i++) {
if (isSpecialByte(m_packet[i])) {
escapedPacked[pos] = StartDelimiter;
escapedPacked[++pos] = 0x20 ^ m_packet[i];
qDebug() << Q_FUNC_INFO << "xor'd byte is" << QString("0x%1").arg(escapedPacked[pos]);
} else {
escapedPacked[pos] = m_packet[i];
}
pos++;
}
qDebug() << Q_FUNC_INFO << m_packet.toHex() << "===>" << escapedPacked.toHex();
m_packet.clear();
m_packet = escapedPacked;
}
}
bool XBeePacket::unescapePacket()
{
QByteArray unEscapedPacket;
int escapeBytes = 0;
int i = 0;
int pos = 0;
for(i=0; i<m_packet.size(); i++) {
if(m_packet.at(i) == Escape) {
escapeBytes++;
}
}
if (escapeBytes == 0) {
return true;
}
unEscapedPacket.reserve(m_packet.size() - escapeBytes);
for(i = 0; i<m_packet.size(); i++) {
if (m_packet[i] == (char)Escape) {
// discard escape byte and un-escape following byte
unEscapedPacket[pos] = 0x20 ^ m_packet[++i];
} else {
unEscapedPacket[pos] = m_packet[i];
}
pos++;
}
qDebug() << Q_FUNC_INFO << m_packet.toHex() << "====>" << unEscapedPacket.toHex();
return true;
}
bool XBeePacket::isSpecialByte(const char c)
{
return c == StartDelimiter ||
c == Escape ||
c == XON ||
c == XOFF;
}
} // END namepsace
<commit_msg>Fixed size of API specific data in XBeePacket class<commit_after>#include "xbeepacket.h"
#include <QDebug>
namespace QtXBee {
/**
* @brief XBeePacket's constructor
* @param parent
*/
XBeePacket::XBeePacket(QObject *parent) :
QObject(parent),
m_startDelimiter(0x7E),
m_length(0),
m_frameType(UndefinedId),
m_frameId(0),
m_checksum(0)
{
}
/**
* @brief Sets the frame's start delimiter.
* By default the start delemiter is set to 0x7E
* @sa XBeePacket::startDelimiter()
* @param sd
*/
void XBeePacket::setStartDelimiter(unsigned sd) {
m_startDelimiter = sd;
}
/**
* @brief Sets the frame's length
* @param l
* @sa XBeePacket::length()
*/
void XBeePacket::setLength(unsigned l) {
m_length = l;
}
/**
* @brief Sets the frame's type
* @param type
* @sa XBeePacket::frameType()
*/
void XBeePacket::setFrameType(ApiId type) {
m_frameType = type;
}
/**
* @brief Sets the frame's id
* @param id
* @sa XBeePacket::frameType()
*/
void XBeePacket::setFrameId(unsigned id) {
m_frameId = id;
}
/**
* @brief Sets the checksum
* @param cs
* @sa XBeePacket::checksum()
*/
void XBeePacket::setChecksum(unsigned cs) {
m_checksum = cs;
}
/**
* @brief Returns the frame's start delimiter
* @returns the frame's start delimiter
* @sa XBeePacket::setStartDelimiter()
*/
unsigned XBeePacket::startDelimiter() const {
return m_startDelimiter;
}
/**
* @brief Returns the frame-specific data length (Number of bytes between the length and the checksum)
* @returns the packet's length
* @sa XBeePacket::setLength()
*/
quint16 XBeePacket::length() const {
return m_length;
}
/**
* @brief Returns the frame's type
* @returns the frame's type
* @sa XBeePacket::setFrameType()
* @sa XBeePacket::APIFrameType
*/
XBeePacket::ApiId XBeePacket::frameType() const {
return m_frameType;
}
/**
* @brief Returns the frame's id
* @returns the frame's id
* @sa XBeePacket::setFrameId()
*/
unsigned XBeePacket::frameId() const {
return m_frameId;
}
/**
* @brief Returns the packet's checksum
* @returns the packet's checksum
* @sa XBeePacket::setChecksum()
*/
unsigned XBeePacket::checksum() const {
return m_checksum;
}
/**
* @brief Computes the checksum of the given QByteArray, and set it.
* @param array
* @sa XBeePacket::setChecksum()
* @sa XBeePacket::checksum()
*/
void XBeePacket::createChecksum(QByteArray array) {
int len = array.size();
unsigned int sum = 0x00;
unsigned int ff = 0xFF;
unsigned int fe = 0xFE;
for(int i=0;i<len;i++)
{
unsigned int a = array.at(i);
if (a == (unsigned int)4294967295){
a = ff;
} else if (a == (unsigned int)4294967294){
a = fe;
}
sum += a;
}
setChecksum((ff - sum) & 0x000000FF);
}
/**
* @brief Returns the frame's packet (raw data)
* @returns the frame's packet (raw data)
*/
QByteArray XBeePacket::packet() const {
return m_packet;
}
bool XBeePacket::setPacket(const QByteArray &packet) {
ApiId apiId = UndefinedId;
quint8 apiSpecificOffset = 4; // 5th byte
QByteArray specificData;
clear();
m_packet = packet;
if(packet.size() < 5) {
qDebug() << Q_FUNC_INFO << "bad packet !";
return false;
}
setStartDelimiter(packet.at(0));
setLength((unsigned char)packet.at(2) + ((unsigned char)packet.at(1)<<8));
apiId = (ApiId)(packet.at(3)&0xff);
// qDebug() << "apiid" << apiId << ",frame type" << m_frameType;
// if(apiId != m_frameType) {
// qDebug() << Q_FUNC_INFO << "Bad API frame ID !" << qPrintable(QString("(expected 0x%1, got 0x%2)").arg(m_frameType,0,16).arg(apiId,0,16));
// return false;
// }
setFrameType(apiId);
if(packet.size() > 5) {
for(int i=apiSpecificOffset; i< packet.size()-1; i++) {
specificData.append(packet.at(i));
}
parseApiSpecificData(specificData);
}
setChecksum(packet.at(packet.size()-1));
assemblePacket();
return true;
}
bool XBeePacket::parseApiSpecificData(const QByteArray &data) {
Q_UNUSED(data)
return false;
}
/**
* @brief Assembles the packet to be able to send it.
*
* Overload this function to create your own packet.
*/
void XBeePacket::assemblePacket() {
}
void XBeePacket::clear() {
m_packet.clear();
m_startDelimiter = 0x7E;
m_length = 0;
m_frameType = UndefinedId;
m_frameId = -1;
m_checksum = -1;
}
/**
* @brief Returns a debug string containing all packet's informations.
* @returns a debug string containing all packet's informations.
*/
QString XBeePacket::toString() {
QString str;
str.append(QString("Raw packet : 0x%1\n").arg(QString(packet().toHex())));
str.append(QString("Frame id : %1 (0x%2)\n").arg(frameId(), 0, 16).arg(frameId(), 0, 16));
str.append(QString("Frame type : %1 (0x%2)\n").arg(frameTypeToString(frameType())).arg(QString::number(frameType(), 16)));
str.append(QString("Start delimiter : 0x%1\n").arg(QString::number(startDelimiter(), 16)));
str.append(QString("Length : %1 bytes\n").arg(m_length));
str.append(QString("Checksum : %1\n").arg(checksum()));
return str;
}
/**
* @brief Returns the given frame type APIFrameType into a human readable string
* @returns the given frame type APIFrameType into a human readable string
* @param type
*/
QString XBeePacket::frameTypeToString(const ApiId type) {
QString str;
switch(type) {
case TXRequest64Id : str = "Tx 16 bits Address Request" ; break;
case TXRequest16Id : str = "Tx 16 bits Address Request" ; break;
case ATCommandId : str = "AT Command Request" ; break;
case ATCommandQueueId : str = "AT Command - Queue Parameter Request" ; break;
case ZBTXRequestId : str = "ZigBee Tx Request" ; break;
case ZBExplicitTxRequest : str = "ZigBee Explicit Tx Request" ; break;
case RemoteATCommandRequestId : str = "Remote AT Command Request" ; break;
case CreateSourceRouteId : str = "Create Source Route" ; break;
case RX64ResponseId : str = "Rx 64 bits Address Response" ; break;
case RX16ResponseId : str = "Rx 16 bits Address Response" ; break;
case RX64IOResponseId : str = "Rx 64 bits Address I/O Response" ; break;
case RX16IOResponseId : str = "Rx 16 bits Address I/O Response" ; break;
case ATCommandResponseId : str = "AT Command Response" ; break;
case TXStatusResponseId : str = "Tx Status Response" ; break;
case ModemStatusResponseId : str = "Modem Status Response" ; break;
case ZBTXStatusResponseId : str = "ZigBee Tx Status Response" ; break;
case ZBRXResponseId : str = "ZigBee Rx Response" ; break;
case ZBExplicitRxResponseId : str = "ZigBee Explicit Rx Response" ; break;
case ZBIOSampleResponseId : str = "ZigBee I/O Sample Response" ; break;
case XBeeSensorReadIndicatorId : str = "XBee Sensore Read Indicator" ; break;
case ZBIONodeIdentificationId : str = "ZigBee I/O Node Indentification Indicator" ; break;
case RemoteATCommandResponseId : str = "Remote AT Command Response" ; break;
case OverTheAirFirmwareUpdateId : str = "Over-the-air Firmware Update" ; break;
case RouteRecordIndicatorId : str = "Route Record Indicator" ; break;
case ManyToOneRouteRequestId : str = "Many-to-one Route Request" ; break;
default : str = "Unkown" ; break;
}
return str;
}
void XBeePacket::escapePacket()
{
int escapeBytes = 0;
QByteArray escapedPacked;
int i;
// Skip byte 0 (start delimiter)
for (i=1; i<m_packet.size(); i++) {
if (isSpecialByte(m_packet.at(i))) {
qDebug() << Q_FUNC_INFO << "packet requires escaping for byte" << i << "(" <<QByteArray().append(m_packet.at(i)).toHex() << ")";
escapeBytes++;
}
}
if (escapeBytes == 0) {
qDebug() << "No need to escape packet" << m_packet.toHex();
return;
}
else {
qDebug() << Q_FUNC_INFO << "packet need to be escaped";
int pos = 1;
escapedPacked.reserve(m_packet.size() + escapeBytes);
escapedPacked[0] = startDelimiter();
for (i = 1; i < m_packet.size(); i++) {
if (isSpecialByte(m_packet[i])) {
escapedPacked[pos] = StartDelimiter;
escapedPacked[++pos] = 0x20 ^ m_packet[i];
qDebug() << Q_FUNC_INFO << "xor'd byte is" << QString("0x%1").arg(escapedPacked[pos]);
} else {
escapedPacked[pos] = m_packet[i];
}
pos++;
}
qDebug() << Q_FUNC_INFO << m_packet.toHex() << "===>" << escapedPacked.toHex();
m_packet.clear();
m_packet = escapedPacked;
}
}
bool XBeePacket::unescapePacket()
{
QByteArray unEscapedPacket;
int escapeBytes = 0;
int i = 0;
int pos = 0;
for(i=0; i<m_packet.size(); i++) {
if(m_packet.at(i) == Escape) {
escapeBytes++;
}
}
if (escapeBytes == 0) {
return true;
}
unEscapedPacket.reserve(m_packet.size() - escapeBytes);
for(i = 0; i<m_packet.size(); i++) {
if (m_packet[i] == (char)Escape) {
// discard escape byte and un-escape following byte
unEscapedPacket[pos] = 0x20 ^ m_packet[++i];
} else {
unEscapedPacket[pos] = m_packet[i];
}
pos++;
}
qDebug() << Q_FUNC_INFO << m_packet.toHex() << "====>" << unEscapedPacket.toHex();
return true;
}
bool XBeePacket::isSpecialByte(const char c)
{
return c == StartDelimiter ||
c == Escape ||
c == XON ||
c == XOFF;
}
} // END namepsace
<|endoftext|> |
<commit_before>// @(#)root/mathcore:$Id$
// Author: David Gonzalez Maline Wed Aug 28 15:33:03 2009
/**********************************************************************
* *
* Copyright (c) 2006 LCG ROOT Math Team, CERN/PH-SFT *
* *
* *
**********************************************************************/
// Implementation file for class BinData
#include <iostream>
#include <iterator>
#include <algorithm>
#include <vector>
#include <list>
#include <stdexcept>
#include <cmath>
#include "Fit/SparseData.h"
using namespace std;
namespace ROOT {
namespace Fit {
//This class is a helper. It represents a bin in N
//dimensions. The change in the name is to avoid name collision.
class Box
{
public:
// Creates a Box with limits specified by the vectors and
// content=value and error=error
Box(const vector<double>& min, const vector<double>& max,
const double value = 0.0, const double error = 1.0):
_min(min), _max(max), _val(value), _error(error)
{ }
// Compares to Boxes to see if they are equal in all its
// variables. This is to be used by the std::find algorithm
bool operator==(const Box& b)
{ return (_min == b._min) && (_max == b._max)
&& (_val == b._val) && (_error == b._error); }
// Get the list of minimum coordinates
const vector<double>& getMin() const { return _min; }
// Get the list of maximum coordinates
const vector<double>& getMax() const { return _max; }
// Get the value of the Box
double getVal() const { return _val; }
// Get the rror of the Box
double getError() const { return _error; }
// Add an amount to the content of the Box
void addVal(const double value) { _val += value; }
friend class BoxContainer;
friend ostream& operator <<(ostream& os, const Box& b);
private:
vector<double> _min;
vector<double> _max;
double _val;
double _error;
};
// This class is just a helper to be used in std::for_each to
// simplify the code later. It's just a definition of a method
// that will discern whether a Box is included into another one
class BoxContainer
{
private:
const Box& _b;
public:
//Constructs the BoxContainer object with a Box that is meant
//to include another one that will be provided later
BoxContainer(const Box& b): _b(b) {}
bool operator() (const Box& b1)
{ return operator()(_b, b1); }
// Looks if b2 is included in b1
bool operator() (const Box& b1, const Box& b2)
{
bool isIn = true;
vector<double>::const_iterator boxit = b2._min.begin();
vector<double>::const_iterator bigit = b1._max.begin();
while ( isIn && boxit != b2._min.end() )
{
if ( (*boxit) >= (*bigit) ) isIn = false;
boxit++;
bigit++;
}
boxit = b2._max.begin();
bigit = b1._min.begin();
while ( isIn && boxit != b2._max.end() )
{
if ( (*boxit) <= (*bigit) ) isIn = false;
boxit++;
bigit++;
}
return isIn;
}
};
// Another helper class to be used in std::for_each to simplify
// the code later. It implements the operator() to know if a
// specified Box is big enough to contain any 'space' inside.
class AreaComparer
{
public:
AreaComparer(vector<double>::iterator iter, double cmpLimit = 1e-16):
thereIsArea(true),
it(iter),
limit(cmpLimit)
{};
void operator() (double value)
{
if ( fabs(value- (*it)) < limit )
thereIsArea = false;
it++;
}
bool isThereArea() { return thereIsArea; }
private:
bool thereIsArea;
vector<double>::iterator it;
double limit;
};
// This is the key of the SparseData structure. This method
// will, by recursion, divide the area passed as an argument in
// min and max into pieces to insert the Box defined by bmin and
// bmax. It will do so from the highest dimension until it gets
// to 1 and create the corresponding boxes to divide the
// original space.
void DivideBox( const vector<double>& min, const vector<double>& max,
const vector<double>& bmin, const vector<double>& bmax,
const unsigned int size, const unsigned int n,
list<Box>& l, const double val, const double error)
{
vector<double> boxmin(min);
vector<double> boxmax(max);
boxmin[n] = min[n];
boxmax[n] = bmin[n];
if ( for_each(boxmin.begin(), boxmin.end(), AreaComparer(boxmax.begin())).isThereArea() )
l.push_back(Box(boxmin, boxmax));
boxmin[n] = bmin[n];
boxmax[n] = bmax[n];
if ( n == 0 )
{
if ( for_each(boxmin.begin(), boxmin.end(), AreaComparer(boxmax.begin())).isThereArea() )
l.push_back(Box(boxmin, boxmax, val, error));
}
else
DivideBox(boxmin, boxmax, bmin, bmax, size, n-1, l, val, error);
boxmin[n] = bmax[n];
boxmax[n] = max[n];
if ( for_each(boxmin.begin(), boxmin.end(), AreaComparer(boxmax.begin())).isThereArea() )
l.push_back(Box(boxmin, boxmax));
}
class ProxyListBox
{
public:
void push_back(Box& box) { l.push_back(box); }
list<Box>::iterator begin() { return l.begin(); }
list<Box>::iterator end() { return l.end(); }
void remove(list<Box>::iterator it) { l.erase(it); }
list<Box>& getList() { return l; }
private:
list<Box> l;
};
SparseData::SparseData(vector<double>& min, vector<double>& max)
{
Box originalBox(min, max);
l = new ProxyListBox();
l->push_back(originalBox);
}
SparseData::SparseData(const unsigned int dim, double min[], double max[])
{
vector<double> minv(min,min+dim);
vector<double> maxv(max,max+dim);
Box originalBox(minv, maxv);
l = new ProxyListBox();
l->push_back(originalBox);
}
SparseData::~SparseData()
{ delete l; }
unsigned int SparseData::NPoints() const
{
return l->getList().size();
}
unsigned int SparseData::NDim() const
{
return l->begin()->getMin().size();
}
void SparseData::Add(std::vector<double>& min, std::vector<double>& max,
const double content, const double error)
{
// Little box is the new Bin to be added
Box littleBox(min, max);
list<Box>::iterator it;
// So we look for the Bin already in the list that contains
// littleBox
it = std::find_if(l->begin(), l->end(), BoxContainer(littleBox));
if ( it != l->end() )
// cout << "Found: " << *it << endl;
;
else {
cout << "SparseData::Add -> FAILED! box not found! " << endl;
cout << littleBox << endl;
return; // Does not add the box, as it is part of the
// underflow/overflow bin
}
// If it happens to have a value, then we add the value,
if ( it->getVal() )
it->addVal( content );
else
{
// otherwise, we divide the container!
DivideBox(it->getMin(), it->getMax(),
littleBox.getMin(), littleBox.getMax(),
it->getMin().size(), it->getMin().size() - 1,
l->getList(), content, error );
// and remove it from the list
l->remove(it);
}
}
void SparseData::GetPoint(const unsigned int i,
std::vector<double>& min, std::vector<double>&max,
double& content, double& error)
{
unsigned int counter = 0;
list<Box>::iterator it = l->begin();
while ( it != l->end() && counter != i ) {
++it;
++counter;
}
if ( (it == l->end()) || (counter != i) )
throw std::out_of_range("SparseData::GetPoint");
min = it->getMin();
max = it->getMax();
content = it->getVal();
error = it->getError();
}
void SparseData::PrintList() const
{
copy(l->begin(), l->end(), ostream_iterator<Box>(cout, "\n------\n"));
}
void SparseData::GetBinData(BinData& bd) const
{
list<Box>::iterator it = l->begin();
const unsigned int dim = it->getMin().size();
bd.Initialize(l->getList().size(), dim);
// Visit all the stored Boxes
for ( ; it != l->end(); ++it )
{
vector<double> mid(dim);
// fill up the vector with the mid point of the Bin
for ( unsigned int i = 0; i < dim; ++i)
{
mid[i] = ((it->getMax()[i] - it->getMin()[i]) /2) + it->getMin()[i];
}
// And store it into the BinData structure
bd.Add(&mid[0], it->getVal(), it->getError());
}
}
void SparseData::GetBinDataIntegral(BinData& bd) const
{
list<Box>::iterator it = l->begin();
bd.Initialize(l->getList().size(), it->getMin().size());
// Visit all the stored Boxes
for ( ; it != l->end(); ++it )
{
//Store the minimum value
bd.Add(&(it->getMin()[0]), it->getVal(), it->getError());
//and the maximum
bd.AddBinUpEdge(&(it->getMax()[0]));
}
}
void SparseData::GetBinDataNoZeros(BinData& bd) const
{
list<Box>::iterator it = l->begin();
const unsigned int dim = it->getMin().size();
bd.Initialize(l->getList().size(), dim);
// Visit all the stored Boxes
for ( ; it != l->end(); ++it )
{
// if the value is zero, jump to the next
if ( it->getVal() == 0 ) continue;
vector<double> mid(dim);
// fill up the vector with the mid point of the Bin
for ( unsigned int i = 0; i < dim; ++i)
{
mid[i] = ((it->getMax()[i] - it->getMin()[i]) /2) + it->getMin()[i];
}
// And store it into the BinData structure
bd.Add(&mid[0], it->getVal(), it->getError());
}
}
// Just for debugging pourposes
ostream& operator <<(ostream& os, const ROOT::Fit::Box& b)
{
os << "min: ";
copy(b.getMin().begin(), b.getMin().end(), ostream_iterator<double>(os, " "));
os << "max: ";
copy(b.getMax().begin(), b.getMax().end(), ostream_iterator<double>(os, " "));
os << "val: " << b.getVal();
return os;
}
} // end namespace Fit
} // end namespace ROOT
<commit_msg>fix a precision problem observed on 32 bits machines (tolerance for comparing doubles was too small)<commit_after>// @(#)root/mathcore:$Id$
// Author: David Gonzalez Maline Wed Aug 28 15:33:03 2009
/**********************************************************************
* *
* Copyright (c) 2006 LCG ROOT Math Team, CERN/PH-SFT *
* *
* *
**********************************************************************/
// Implementation file for class BinData
#include <iostream>
#include <iterator>
#include <algorithm>
#include <vector>
#include <list>
#include <stdexcept>
#include <cmath>
#include "Fit/SparseData.h"
#include <limits>
using namespace std;
namespace ROOT {
namespace Fit {
//This class is a helper. It represents a bin in N
//dimensions. The change in the name is to avoid name collision.
class Box
{
public:
// Creates a Box with limits specified by the vectors and
// content=value and error=error
Box(const vector<double>& min, const vector<double>& max,
const double value = 0.0, const double error = 1.0):
_min(min), _max(max), _val(value), _error(error)
{ }
// Compares to Boxes to see if they are equal in all its
// variables. This is to be used by the std::find algorithm
bool operator==(const Box& b)
{ return (_min == b._min) && (_max == b._max)
&& (_val == b._val) && (_error == b._error); }
// Get the list of minimum coordinates
const vector<double>& getMin() const { return _min; }
// Get the list of maximum coordinates
const vector<double>& getMax() const { return _max; }
// Get the value of the Box
double getVal() const { return _val; }
// Get the rror of the Box
double getError() const { return _error; }
// Add an amount to the content of the Box
void addVal(const double value) { _val += value; }
friend class BoxContainer;
friend ostream& operator <<(ostream& os, const Box& b);
private:
vector<double> _min;
vector<double> _max;
double _val;
double _error;
};
// This class is just a helper to be used in std::for_each to
// simplify the code later. It's just a definition of a method
// that will discern whether a Box is included into another one
class BoxContainer
{
private:
const Box& _b;
public:
//Constructs the BoxContainer object with a Box that is meant
//to include another one that will be provided later
BoxContainer(const Box& b): _b(b) {}
bool operator() (const Box& b1)
{ return operator()(_b, b1); }
// Looks if b2 is included in b1
bool operator() (const Box& b1, const Box& b2)
{
bool isIn = true;
vector<double>::const_iterator boxit = b2._min.begin();
vector<double>::const_iterator bigit = b1._max.begin();
while ( isIn && boxit != b2._min.end() )
{
if ( (*boxit) >= (*bigit) ) isIn = false;
boxit++;
bigit++;
}
boxit = b2._max.begin();
bigit = b1._min.begin();
while ( isIn && boxit != b2._max.end() )
{
if ( (*boxit) <= (*bigit) ) isIn = false;
boxit++;
bigit++;
}
return isIn;
}
};
// Another helper class to be used in std::for_each to simplify
// the code later. It implements the operator() to know if a
// specified Box is big enough to contain any 'space' inside.
class AreaComparer
{
public:
AreaComparer(vector<double>::iterator iter, double cmpLimit = 8*std::numeric_limits<double>::epsilon() ):
thereIsArea(true),
it(iter),
limit(cmpLimit)
{};
void operator() (double value)
{
if ( fabs(value- (*it)) < limit )
thereIsArea = false;
it++;
}
bool isThereArea() { return thereIsArea; }
private:
bool thereIsArea;
vector<double>::iterator it;
double limit;
};
// This is the key of the SparseData structure. This method
// will, by recursion, divide the area passed as an argument in
// min and max into pieces to insert the Box defined by bmin and
// bmax. It will do so from the highest dimension until it gets
// to 1 and create the corresponding boxes to divide the
// original space.
void DivideBox( const vector<double>& min, const vector<double>& max,
const vector<double>& bmin, const vector<double>& bmax,
const unsigned int size, const unsigned int n,
list<Box>& l, const double val, const double error)
{
vector<double> boxmin(min);
vector<double> boxmax(max);
boxmin[n] = min[n];
boxmax[n] = bmin[n];
if ( for_each(boxmin.begin(), boxmin.end(), AreaComparer(boxmax.begin())).isThereArea() )
l.push_back(Box(boxmin, boxmax));
boxmin[n] = bmin[n];
boxmax[n] = bmax[n];
if ( n == 0 )
{
if ( for_each(boxmin.begin(), boxmin.end(), AreaComparer(boxmax.begin())).isThereArea() )
l.push_back(Box(boxmin, boxmax, val, error));
}
else
DivideBox(boxmin, boxmax, bmin, bmax, size, n-1, l, val, error);
boxmin[n] = bmax[n];
boxmax[n] = max[n];
if ( for_each(boxmin.begin(), boxmin.end(), AreaComparer(boxmax.begin())).isThereArea() )
l.push_back(Box(boxmin, boxmax));
}
class ProxyListBox
{
public:
void push_back(Box& box) { l.push_back(box); }
list<Box>::iterator begin() { return l.begin(); }
list<Box>::iterator end() { return l.end(); }
void remove(list<Box>::iterator it) { l.erase(it); }
list<Box>& getList() { return l; }
private:
list<Box> l;
};
SparseData::SparseData(vector<double>& min, vector<double>& max)
{
Box originalBox(min, max);
l = new ProxyListBox();
l->push_back(originalBox);
}
SparseData::SparseData(const unsigned int dim, double min[], double max[])
{
vector<double> minv(min,min+dim);
vector<double> maxv(max,max+dim);
Box originalBox(minv, maxv);
l = new ProxyListBox();
l->push_back(originalBox);
}
SparseData::~SparseData()
{ delete l; }
unsigned int SparseData::NPoints() const
{
return l->getList().size();
}
unsigned int SparseData::NDim() const
{
return l->begin()->getMin().size();
}
void SparseData::Add(std::vector<double>& min, std::vector<double>& max,
const double content, const double error)
{
// Little box is the new Bin to be added
Box littleBox(min, max);
list<Box>::iterator it;
// So we look for the Bin already in the list that contains
// littleBox
it = std::find_if(l->begin(), l->end(), BoxContainer(littleBox));
if ( it != l->end() )
// cout << "Found: " << *it << endl;
;
else {
cout << "SparseData::Add -> FAILED! box not found! " << endl;
cout << littleBox << endl;
return; // Does not add the box, as it is part of the
// underflow/overflow bin
}
// If it happens to have a value, then we add the value,
if ( it->getVal() )
it->addVal( content );
else
{
// otherwise, we divide the container!
DivideBox(it->getMin(), it->getMax(),
littleBox.getMin(), littleBox.getMax(),
it->getMin().size(), it->getMin().size() - 1,
l->getList(), content, error );
// and remove it from the list
l->remove(it);
}
}
void SparseData::GetPoint(const unsigned int i,
std::vector<double>& min, std::vector<double>&max,
double& content, double& error)
{
unsigned int counter = 0;
list<Box>::iterator it = l->begin();
while ( it != l->end() && counter != i ) {
++it;
++counter;
}
if ( (it == l->end()) || (counter != i) )
throw std::out_of_range("SparseData::GetPoint");
min = it->getMin();
max = it->getMax();
content = it->getVal();
error = it->getError();
}
void SparseData::PrintList() const
{
copy(l->begin(), l->end(), ostream_iterator<Box>(cout, "\n------\n"));
}
void SparseData::GetBinData(BinData& bd) const
{
list<Box>::iterator it = l->begin();
const unsigned int dim = it->getMin().size();
bd.Initialize(l->getList().size(), dim);
// Visit all the stored Boxes
for ( ; it != l->end(); ++it )
{
vector<double> mid(dim);
// fill up the vector with the mid point of the Bin
for ( unsigned int i = 0; i < dim; ++i)
{
mid[i] = ((it->getMax()[i] - it->getMin()[i]) /2) + it->getMin()[i];
}
// And store it into the BinData structure
bd.Add(&mid[0], it->getVal(), it->getError());
}
}
void SparseData::GetBinDataIntegral(BinData& bd) const
{
list<Box>::iterator it = l->begin();
bd.Initialize(l->getList().size(), it->getMin().size());
// Visit all the stored Boxes
for ( ; it != l->end(); ++it )
{
//Store the minimum value
bd.Add(&(it->getMin()[0]), it->getVal(), it->getError());
//and the maximum
bd.AddBinUpEdge(&(it->getMax()[0]));
}
}
void SparseData::GetBinDataNoZeros(BinData& bd) const
{
list<Box>::iterator it = l->begin();
const unsigned int dim = it->getMin().size();
bd.Initialize(l->getList().size(), dim);
// Visit all the stored Boxes
for ( ; it != l->end(); ++it )
{
// if the value is zero, jump to the next
if ( it->getVal() == 0 ) continue;
vector<double> mid(dim);
// fill up the vector with the mid point of the Bin
for ( unsigned int i = 0; i < dim; ++i)
{
mid[i] = ((it->getMax()[i] - it->getMin()[i]) /2) + it->getMin()[i];
}
// And store it into the BinData structure
bd.Add(&mid[0], it->getVal(), it->getError());
}
}
// Just for debugging pourposes
ostream& operator <<(ostream& os, const ROOT::Fit::Box& b)
{
os << "min: ";
copy(b.getMin().begin(), b.getMin().end(), ostream_iterator<double>(os, " "));
os << "max: ";
copy(b.getMax().begin(), b.getMax().end(), ostream_iterator<double>(os, " "));
os << "val: " << b.getVal();
return os;
}
} // end namespace Fit
} // end namespace ROOT
<|endoftext|> |
<commit_before>/*
This file is part of the clazy static checker.
Copyright (C) 2015 Klarälvdalens Datakonsult AB, a KDAB Group company, info@kdab.com
Author: Sérgio Martins <sergio.martins@kdab.com>
Copyright (C) 2015 Sergio Martins <smartins@kde.org>
This library is free software; you can redistribute it and/or
modify it under the terms of the GNU Library General Public
License as published by the Free Software Foundation; either
version 2 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
Library General Public License for more details.
You should have received a copy of the GNU Library General Public License
along with this library; see the file COPYING.LIB. If not, write to
the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
Boston, MA 02110-1301, USA.
*/
#include "dynamic_cast.h"
#include "Utils.h"
#include "checkmanager.h"
#include <clang/AST/DeclCXX.h>
#include <clang/AST/ExprCXX.h>
using namespace clang;
BogusDynamicCast::BogusDynamicCast(const std::string &name, const clang::CompilerInstance &ci)
: CheckBase(name, ci)
{
}
void BogusDynamicCast::VisitStmt(clang::Stmt *stm)
{
auto dynExp = dyn_cast<CXXDynamicCastExpr>(stm);
if (dynExp == nullptr)
return;
auto namedCast = dyn_cast<CXXNamedCastExpr>(stm);
CXXRecordDecl *castFrom = Utils::namedCastInnerDecl(namedCast);
if (castFrom == nullptr)
return;
//if (QtUtils::isQObject(castFrom)) // Very noisy and not very useful, and qobject_cast can fail too
//emitWarning(dynExp->getLocStart(), "Use qobject_cast rather than dynamic_cast");
//if (dynExp->isAlwaysNull()) { // Crashing in Type.h assert(isa<T>(CanonicalType))
// emitWarning(dynExp->getLocStart(), "That dynamic_cast is always null");
// return;
// }
CXXRecordDecl *castTo = Utils::namedCastOuterDecl(namedCast);
if (castTo == nullptr)
return;
if (castFrom == castTo) {
emitWarning(stm->getLocStart(), "Casting to itself");
} else if (Utils::isChildOf(/*child=*/castFrom, castTo)) {
emitWarning(stm->getLocStart(), "explicitly casting to base is unnecessary");
}
}
REGISTER_CHECK_WITH_FLAGS("bogus-dynamic-cast", BogusDynamicCast, CheckLevel3)
<commit_msg>dynamic_cast: coding style and cleanup old comment<commit_after>/*
This file is part of the clazy static checker.
Copyright (C) 2015 Klarälvdalens Datakonsult AB, a KDAB Group company, info@kdab.com
Author: Sérgio Martins <sergio.martins@kdab.com>
Copyright (C) 2015 Sergio Martins <smartins@kde.org>
This library is free software; you can redistribute it and/or
modify it under the terms of the GNU Library General Public
License as published by the Free Software Foundation; either
version 2 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
Library General Public License for more details.
You should have received a copy of the GNU Library General Public License
along with this library; see the file COPYING.LIB. If not, write to
the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
Boston, MA 02110-1301, USA.
*/
#include "dynamic_cast.h"
#include "Utils.h"
#include "checkmanager.h"
#include <clang/AST/DeclCXX.h>
#include <clang/AST/ExprCXX.h>
using namespace clang;
BogusDynamicCast::BogusDynamicCast(const std::string &name, const clang::CompilerInstance &ci)
: CheckBase(name, ci)
{
}
void BogusDynamicCast::VisitStmt(clang::Stmt *stm)
{
auto dynExp = dyn_cast<CXXDynamicCastExpr>(stm);
if (!dynExp)
return;
auto namedCast = dyn_cast<CXXNamedCastExpr>(stm);
CXXRecordDecl *castFrom = Utils::namedCastInnerDecl(namedCast);
if (!castFrom)
return;
//if (QtUtils::isQObject(castFrom)) // Very noisy and not very useful, and qobject_cast can fail too
//emitWarning(dynExp->getLocStart(), "Use qobject_cast rather than dynamic_cast");
CXXRecordDecl *castTo = Utils::namedCastOuterDecl(namedCast);
if (!castTo)
return;
if (castFrom == castTo) {
emitWarning(stm->getLocStart(), "Casting to itself");
} else if (Utils::isChildOf(/*child=*/castFrom, castTo)) {
emitWarning(stm->getLocStart(), "explicitly casting to base is unnecessary");
}
}
REGISTER_CHECK_WITH_FLAGS("bogus-dynamic-cast", BogusDynamicCast, CheckLevel3)
<|endoftext|> |
<commit_before>#include "OgreFramework.h"
#include "macUtils.h"
using namespace Ogre;
namespace Ogre
{
template<> OgreFramework* Ogre::Singleton<OgreFramework>::msSingleton = 0;
};
OgreFramework::OgreFramework()
{
m_MoveSpeed = 6.0f;
m_RotateSpeed = 0.3f;
m_bShutDownOgre = false;
m_iNumScreenShots = 0;
m_pRoot = 0;
m_pSceneMgr = 0;
m_pRenderWnd = 0;
m_pCamera = 0;
m_pViewport = 0;
m_pLog = 0;
m_pTimer = 0;
m_pInputMgr = 0;
m_pKeyboard = 0;
m_pMouse = 0;
#if OGRE_PLATFORM == OGRE_PLATFORM_APPLE
m_ResourcePath = macBundlePath() + "/Contents/Resources/";
#elif defined(OGRE_IS_IOS)
m_ResourcePath = macBundlePath() + "/";
#else
m_ResourcePath = "";
#endif
m_pTrayMgr = 0;
m_FrameEvent = Ogre::FrameEvent();
}
//|||||||||||||||||||||||||||||||||||||||||||||||
#if defined(OGRE_IS_IOS)
bool OgreFramework::initOgre(Ogre::String wndTitle, OIS::KeyListener *pKeyListener, OIS::MultiTouchListener *pMouseListener)
#else
bool OgreFramework::initOgre(Ogre::String wndTitle, OIS::KeyListener *pKeyListener, OIS::MouseListener *pMouseListener)
#endif
{
Ogre::LogManager* logMgr = new Ogre::LogManager();
m_pLog = Ogre::LogManager::getSingleton().createLog("OgreLogfile.log", true, true, false);
m_pLog->setDebugOutputEnabled(true);
String pluginsPath;
// only use plugins.cfg if not static
#ifndef OGRE_STATIC_LIB
pluginsPath = m_ResourcePath + "plugins.cfg";
#endif
m_pRoot = new Ogre::Root(pluginsPath, Ogre::macBundlePath() + "/ogre.cfg");
#ifdef OGRE_STATIC_LIB
m_StaticPluginLoader.load();
#endif
RenderSystem *rs = m_pRoot->getRenderSystemByName("OpenGL Rendering Subsystem");
m_pRoot->setRenderSystem(rs);
rs->setConfigOption("Video Mode", "1440 x 900 @ 32-bit colour");
m_pRenderWnd = m_pRoot->initialise(true, wndTitle);
m_pSceneMgr = m_pRoot->createSceneManager(ST_GENERIC, "SceneManager");
m_pSceneMgr->setAmbientLight(Ogre::ColourValue(0.6f, 0.6f, 0.6f));
m_pOverlaySystem = new Ogre::OverlaySystem();
m_pSceneMgr->addRenderQueueListener(m_pOverlaySystem);
m_pCamera = m_pSceneMgr->createCamera("Camera");
m_pCamera->setPosition(Vector3(8, 10, 10));
m_pCamera->lookAt(Vector3(8, 9, 8));
m_pCamera->setNearClipDistance(1);
m_pViewport = m_pRenderWnd->addViewport(m_pCamera);
m_pViewport->setBackgroundColour(ColourValue(0.4f, 0.2f, 0.2f, 1.0f));
m_pCamera->setAspectRatio(Real(m_pViewport->getActualWidth()) / Real(m_pViewport->getActualHeight()));
m_pViewport->setCamera(m_pCamera);
unsigned long hWnd = 0;
OIS::ParamList paramList;
m_pRenderWnd->getCustomAttribute("WINDOW", &hWnd);
paramList.insert(OIS::ParamList::value_type("WINDOW", Ogre::StringConverter::toString(hWnd)));
m_pInputMgr = OIS::InputManager::createInputSystem(paramList);
#if !defined(OGRE_IS_IOS)
m_pKeyboard = static_cast<OIS::Keyboard*>(m_pInputMgr->createInputObject(OIS::OISKeyboard, true));
m_pMouse = static_cast<OIS::Mouse*>(m_pInputMgr->createInputObject(OIS::OISMouse, true));
m_pMouse->getMouseState().height = m_pRenderWnd->getHeight();
m_pMouse->getMouseState().width = m_pRenderWnd->getWidth();
#else
m_pMouse = static_cast<OIS::MultiTouch*>(m_pInputMgr->createInputObject(OIS::OISMultiTouch, true));
#endif
#if !defined(OGRE_IS_IOS)
if(pKeyListener == 0)
m_pKeyboard->setEventCallback(this);
else
m_pKeyboard->setEventCallback(pKeyListener);
#endif
if(pMouseListener == 0)
m_pMouse->setEventCallback(this);
else
m_pMouse->setEventCallback(pMouseListener);
Ogre::String secName, typeName, archName;
Ogre::ConfigFile cf;
cf.load(m_ResourcePath + "resources.cfg");
Ogre::ConfigFile::SectionIterator seci = cf.getSectionIterator();
while (seci.hasMoreElements())
{
secName = seci.peekNextKey();
Ogre::ConfigFile::SettingsMultiMap *settings = seci.getNext();
Ogre::ConfigFile::SettingsMultiMap::iterator i;
for (i = settings->begin(); i != settings->end(); ++i)
{
typeName = i->first;
archName = i->second;
#if OGRE_PLATFORM == OGRE_PLATFORM_APPLE || defined(OGRE_IS_IOS)
// OS X does not set the working directory relative to the app,
// In order to make things portable on OS X we need to provide
// the loading with it's own bundle path location
if (!Ogre::StringUtil::startsWith(archName, "/", false)) // only adjust relative dirs
archName = Ogre::String(m_ResourcePath + archName);
#endif
Ogre::ResourceGroupManager::getSingleton().addResourceLocation(archName, typeName, secName);
}
}
Ogre::TextureManager::getSingleton().setDefaultNumMipmaps(5);
Ogre::ResourceGroupManager::getSingleton().initialiseAllResourceGroups();
m_pTimer = OGRE_NEW Ogre::Timer();
m_pTimer->reset();
OgreBites::InputContext inputContext;
inputContext.mMouse = m_pMouse;
inputContext.mKeyboard = m_pKeyboard;
m_pTrayMgr = new OgreBites::SdkTrayManager("TrayMgr", m_pRenderWnd, inputContext, this);
m_pTrayMgr->showFrameStats(OgreBites::TL_BOTTOMLEFT);
m_pTrayMgr->hideCursor();
m_pRenderWnd->setActive(true);
return true;
}
OgreFramework::~OgreFramework()
{
if(m_pInputMgr) OIS::InputManager::destroyInputSystem(m_pInputMgr);
if(m_pTrayMgr) delete m_pTrayMgr;
#ifdef OGRE_STATIC_LIB
m_StaticPluginLoader.unload();
#endif
if(m_pRoot) delete m_pRoot;
}
bool OgreFramework::keyPressed(const OIS::KeyEvent &keyEventRef)
{
#if !defined(OGRE_IS_IOS)
if(m_pKeyboard->isKeyDown(OIS::KC_ESCAPE))
{
m_bShutDownOgre = true;
return true;
}
if(m_pKeyboard->isKeyDown(OIS::KC_SYSRQ))
{
m_pRenderWnd->writeContentsToTimestampedFile("BOF_Screenshot_", ".png");
return true;
}
if(m_pKeyboard->isKeyDown(OIS::KC_M))
{
static int mode = 0;
if(mode == 2)
{
m_pCamera->setPolygonMode(PM_SOLID);
mode = 0;
}
else if(mode == 0)
{
m_pCamera->setPolygonMode(PM_WIREFRAME);
mode = 1;
}
else if(mode == 1)
{
m_pCamera->setPolygonMode(PM_POINTS);
mode = 2;
}
}
if(m_pKeyboard->isKeyDown(OIS::KC_O))
{
if(m_pTrayMgr->isLogoVisible()) {
m_pTrayMgr->hideLogo();
m_pTrayMgr->hideFrameStats();
} else {
m_pTrayMgr->showFrameStats(OgreBites::TL_BOTTOMLEFT);
}
}
#endif
return true;
}
bool OgreFramework::keyReleased(const OIS::KeyEvent &keyEventRef)
{
return true;
}
//|||||||||||||||||||||||||||||||||||||||||||||||
#if defined(OGRE_IS_IOS)
bool OgreFramework::touchMoved(const OIS::MultiTouchEvent &evt)
{
OIS::MultiTouchState state = evt.state;
int origTransX = 0, origTransY = 0;
#if !OGRE_NO_VIEWPORT_ORIENTATIONMODE
switch(m_pCamera->getViewport()->getOrientationMode())
{
case Ogre::OR_LANDSCAPELEFT:
origTransX = state.X.rel;
origTransY = state.Y.rel;
state.X.rel = -origTransY;
state.Y.rel = origTransX;
break;
case Ogre::OR_LANDSCAPERIGHT:
origTransX = state.X.rel;
origTransY = state.Y.rel;
state.X.rel = origTransY;
state.Y.rel = origTransX;
break;
// Portrait doesn't need any change
case Ogre::OR_PORTRAIT:
default:
break;
}
#endif
m_pCamera->yaw(Degree(state.X.rel * -0.1));
m_pCamera->pitch(Degree(state.Y.rel * -0.1));
return true;
}
//|||||||||||||||||||||||||||||||||||||||||||||||
bool OgreFramework::touchPressed(const OIS:: MultiTouchEvent &evt)
{
#pragma unused(evt)
return true;
}
//|||||||||||||||||||||||||||||||||||||||||||||||
bool OgreFramework::touchReleased(const OIS:: MultiTouchEvent &evt)
{
#pragma unused(evt)
return true;
}
bool OgreFramework::touchCancelled(const OIS:: MultiTouchEvent &evt)
{
#pragma unused(evt)
return true;
}
#else
bool OgreFramework::mouseMoved(const OIS::MouseEvent &evt)
{
// m_pCamera->yaw(Degree(evt.state.X.rel * -0.1f));
// m_pCamera->pitch(Degree(evt.state.Y.rel * -0.1f));
//
return true;
}
bool OgreFramework::mousePressed(const OIS::MouseEvent &evt, OIS::MouseButtonID id)
{
return true;
}
bool OgreFramework::mouseReleased(const OIS::MouseEvent &evt, OIS::MouseButtonID id)
{
return true;
}
#endif
void OgreFramework::updateOgre(double timeSinceLastFrame)
{
m_MoveScale = m_MoveSpeed * (float)timeSinceLastFrame;
m_RotScale = m_RotateSpeed * (float)timeSinceLastFrame;
#if OGRE_VERSION >= 0x10800
m_pSceneMgr->setSkyBoxEnabled(true);
#endif
m_TranslateVector = Vector3::ZERO;
getInput();
moveCamera();
m_FrameEvent.timeSinceLastFrame = timeSinceLastFrame;
m_pTrayMgr->frameRenderingQueued(m_FrameEvent);
}
void OgreFramework::moveCamera()
{
#if !defined(OGRE_IS_IOS)
if(m_pKeyboard->isKeyDown(OIS::KC_LSHIFT))
m_pCamera->moveRelative(m_TranslateVector);
else
#endif
m_pCamera->moveRelative(m_TranslateVector / 10);
}
void OgreFramework::getInput()
{
#if !defined(OGRE_IS_IOS)
if(m_pKeyboard->isKeyDown(OIS::KC_A))
m_TranslateVector.x = -m_MoveScale;
if(m_pKeyboard->isKeyDown(OIS::KC_D))
m_TranslateVector.x = m_MoveScale;
if(m_pKeyboard->isKeyDown(OIS::KC_W))
m_TranslateVector.z = -m_MoveScale;
if(m_pKeyboard->isKeyDown(OIS::KC_S))
m_TranslateVector.z = m_MoveScale;
if(m_pKeyboard->isKeyDown(OIS::KC_HOME)) {
m_pCamera->setPosition(-10.861927, 6.726564, -7.668012);
m_pCamera->lookAt(0,4,-8);
}
#endif
}
<commit_msg>don't show stats<commit_after>#include "OgreFramework.h"
#include "macUtils.h"
using namespace Ogre;
namespace Ogre
{
template<> OgreFramework* Ogre::Singleton<OgreFramework>::msSingleton = 0;
};
OgreFramework::OgreFramework()
{
m_MoveSpeed = 6.0f;
m_RotateSpeed = 0.3f;
m_bShutDownOgre = false;
m_iNumScreenShots = 0;
m_pRoot = 0;
m_pSceneMgr = 0;
m_pRenderWnd = 0;
m_pCamera = 0;
m_pViewport = 0;
m_pLog = 0;
m_pTimer = 0;
m_pInputMgr = 0;
m_pKeyboard = 0;
m_pMouse = 0;
#if OGRE_PLATFORM == OGRE_PLATFORM_APPLE
m_ResourcePath = macBundlePath() + "/Contents/Resources/";
#elif defined(OGRE_IS_IOS)
m_ResourcePath = macBundlePath() + "/";
#else
m_ResourcePath = "";
#endif
m_pTrayMgr = 0;
m_FrameEvent = Ogre::FrameEvent();
}
//|||||||||||||||||||||||||||||||||||||||||||||||
#if defined(OGRE_IS_IOS)
bool OgreFramework::initOgre(Ogre::String wndTitle, OIS::KeyListener *pKeyListener, OIS::MultiTouchListener *pMouseListener)
#else
bool OgreFramework::initOgre(Ogre::String wndTitle, OIS::KeyListener *pKeyListener, OIS::MouseListener *pMouseListener)
#endif
{
Ogre::LogManager* logMgr = new Ogre::LogManager();
m_pLog = Ogre::LogManager::getSingleton().createLog("OgreLogfile.log", true, true, false);
m_pLog->setDebugOutputEnabled(true);
String pluginsPath;
// only use plugins.cfg if not static
#ifndef OGRE_STATIC_LIB
pluginsPath = m_ResourcePath + "plugins.cfg";
#endif
m_pRoot = new Ogre::Root(pluginsPath, Ogre::macBundlePath() + "/ogre.cfg");
#ifdef OGRE_STATIC_LIB
m_StaticPluginLoader.load();
#endif
RenderSystem *rs = m_pRoot->getRenderSystemByName("OpenGL Rendering Subsystem");
m_pRoot->setRenderSystem(rs);
rs->setConfigOption("Video Mode", "1440 x 900 @ 32-bit colour");
m_pRenderWnd = m_pRoot->initialise(true, wndTitle);
m_pSceneMgr = m_pRoot->createSceneManager(ST_GENERIC, "SceneManager");
m_pSceneMgr->setAmbientLight(Ogre::ColourValue(0.6f, 0.6f, 0.6f));
m_pOverlaySystem = new Ogre::OverlaySystem();
m_pSceneMgr->addRenderQueueListener(m_pOverlaySystem);
m_pCamera = m_pSceneMgr->createCamera("Camera");
m_pCamera->setPosition(Vector3(8, 10, 10));
m_pCamera->lookAt(Vector3(8, 9, 8));
m_pCamera->setNearClipDistance(1);
m_pViewport = m_pRenderWnd->addViewport(m_pCamera);
m_pViewport->setBackgroundColour(ColourValue(0.4f, 0.2f, 0.2f, 1.0f));
m_pCamera->setAspectRatio(Real(m_pViewport->getActualWidth()) / Real(m_pViewport->getActualHeight()));
m_pViewport->setCamera(m_pCamera);
unsigned long hWnd = 0;
OIS::ParamList paramList;
m_pRenderWnd->getCustomAttribute("WINDOW", &hWnd);
paramList.insert(OIS::ParamList::value_type("WINDOW", Ogre::StringConverter::toString(hWnd)));
m_pInputMgr = OIS::InputManager::createInputSystem(paramList);
#if !defined(OGRE_IS_IOS)
m_pKeyboard = static_cast<OIS::Keyboard*>(m_pInputMgr->createInputObject(OIS::OISKeyboard, true));
m_pMouse = static_cast<OIS::Mouse*>(m_pInputMgr->createInputObject(OIS::OISMouse, true));
m_pMouse->getMouseState().height = m_pRenderWnd->getHeight();
m_pMouse->getMouseState().width = m_pRenderWnd->getWidth();
#else
m_pMouse = static_cast<OIS::MultiTouch*>(m_pInputMgr->createInputObject(OIS::OISMultiTouch, true));
#endif
#if !defined(OGRE_IS_IOS)
if(pKeyListener == 0)
m_pKeyboard->setEventCallback(this);
else
m_pKeyboard->setEventCallback(pKeyListener);
#endif
if(pMouseListener == 0)
m_pMouse->setEventCallback(this);
else
m_pMouse->setEventCallback(pMouseListener);
Ogre::String secName, typeName, archName;
Ogre::ConfigFile cf;
cf.load(m_ResourcePath + "resources.cfg");
Ogre::ConfigFile::SectionIterator seci = cf.getSectionIterator();
while (seci.hasMoreElements())
{
secName = seci.peekNextKey();
Ogre::ConfigFile::SettingsMultiMap *settings = seci.getNext();
Ogre::ConfigFile::SettingsMultiMap::iterator i;
for (i = settings->begin(); i != settings->end(); ++i)
{
typeName = i->first;
archName = i->second;
#if OGRE_PLATFORM == OGRE_PLATFORM_APPLE || defined(OGRE_IS_IOS)
// OS X does not set the working directory relative to the app,
// In order to make things portable on OS X we need to provide
// the loading with it's own bundle path location
if (!Ogre::StringUtil::startsWith(archName, "/", false)) // only adjust relative dirs
archName = Ogre::String(m_ResourcePath + archName);
#endif
Ogre::ResourceGroupManager::getSingleton().addResourceLocation(archName, typeName, secName);
}
}
Ogre::TextureManager::getSingleton().setDefaultNumMipmaps(5);
Ogre::ResourceGroupManager::getSingleton().initialiseAllResourceGroups();
m_pTimer = OGRE_NEW Ogre::Timer();
m_pTimer->reset();
OgreBites::InputContext inputContext;
inputContext.mMouse = m_pMouse;
inputContext.mKeyboard = m_pKeyboard;
m_pTrayMgr = new OgreBites::SdkTrayManager("TrayMgr", m_pRenderWnd, inputContext, this);
// m_pTrayMgr->showFrameStats(OgreBites::TL_BOTTOMLEFT);
m_pTrayMgr->hideCursor();
m_pRenderWnd->setActive(true);
return true;
}
OgreFramework::~OgreFramework()
{
if(m_pInputMgr) OIS::InputManager::destroyInputSystem(m_pInputMgr);
if(m_pTrayMgr) delete m_pTrayMgr;
#ifdef OGRE_STATIC_LIB
m_StaticPluginLoader.unload();
#endif
if(m_pRoot) delete m_pRoot;
}
bool OgreFramework::keyPressed(const OIS::KeyEvent &keyEventRef)
{
#if !defined(OGRE_IS_IOS)
if(m_pKeyboard->isKeyDown(OIS::KC_ESCAPE))
{
m_bShutDownOgre = true;
return true;
}
if(m_pKeyboard->isKeyDown(OIS::KC_SYSRQ))
{
m_pRenderWnd->writeContentsToTimestampedFile("BOF_Screenshot_", ".png");
return true;
}
if(m_pKeyboard->isKeyDown(OIS::KC_M))
{
static int mode = 0;
if(mode == 2)
{
m_pCamera->setPolygonMode(PM_SOLID);
mode = 0;
}
else if(mode == 0)
{
m_pCamera->setPolygonMode(PM_WIREFRAME);
mode = 1;
}
else if(mode == 1)
{
m_pCamera->setPolygonMode(PM_POINTS);
mode = 2;
}
}
if(m_pKeyboard->isKeyDown(OIS::KC_O))
{
if(m_pTrayMgr->isLogoVisible()) {
m_pTrayMgr->hideLogo();
m_pTrayMgr->hideFrameStats();
} else {
m_pTrayMgr->showFrameStats(OgreBites::TL_BOTTOMLEFT);
}
}
#endif
return true;
}
bool OgreFramework::keyReleased(const OIS::KeyEvent &keyEventRef)
{
return true;
}
//|||||||||||||||||||||||||||||||||||||||||||||||
#if defined(OGRE_IS_IOS)
bool OgreFramework::touchMoved(const OIS::MultiTouchEvent &evt)
{
OIS::MultiTouchState state = evt.state;
int origTransX = 0, origTransY = 0;
#if !OGRE_NO_VIEWPORT_ORIENTATIONMODE
switch(m_pCamera->getViewport()->getOrientationMode())
{
case Ogre::OR_LANDSCAPELEFT:
origTransX = state.X.rel;
origTransY = state.Y.rel;
state.X.rel = -origTransY;
state.Y.rel = origTransX;
break;
case Ogre::OR_LANDSCAPERIGHT:
origTransX = state.X.rel;
origTransY = state.Y.rel;
state.X.rel = origTransY;
state.Y.rel = origTransX;
break;
// Portrait doesn't need any change
case Ogre::OR_PORTRAIT:
default:
break;
}
#endif
m_pCamera->yaw(Degree(state.X.rel * -0.1));
m_pCamera->pitch(Degree(state.Y.rel * -0.1));
return true;
}
//|||||||||||||||||||||||||||||||||||||||||||||||
bool OgreFramework::touchPressed(const OIS:: MultiTouchEvent &evt)
{
#pragma unused(evt)
return true;
}
//|||||||||||||||||||||||||||||||||||||||||||||||
bool OgreFramework::touchReleased(const OIS:: MultiTouchEvent &evt)
{
#pragma unused(evt)
return true;
}
bool OgreFramework::touchCancelled(const OIS:: MultiTouchEvent &evt)
{
#pragma unused(evt)
return true;
}
#else
bool OgreFramework::mouseMoved(const OIS::MouseEvent &evt)
{
// m_pCamera->yaw(Degree(evt.state.X.rel * -0.1f));
// m_pCamera->pitch(Degree(evt.state.Y.rel * -0.1f));
//
return true;
}
bool OgreFramework::mousePressed(const OIS::MouseEvent &evt, OIS::MouseButtonID id)
{
return true;
}
bool OgreFramework::mouseReleased(const OIS::MouseEvent &evt, OIS::MouseButtonID id)
{
return true;
}
#endif
void OgreFramework::updateOgre(double timeSinceLastFrame)
{
m_MoveScale = m_MoveSpeed * (float)timeSinceLastFrame;
m_RotScale = m_RotateSpeed * (float)timeSinceLastFrame;
#if OGRE_VERSION >= 0x10800
m_pSceneMgr->setSkyBoxEnabled(true);
#endif
m_TranslateVector = Vector3::ZERO;
getInput();
moveCamera();
m_FrameEvent.timeSinceLastFrame = timeSinceLastFrame;
m_pTrayMgr->frameRenderingQueued(m_FrameEvent);
}
void OgreFramework::moveCamera()
{
#if !defined(OGRE_IS_IOS)
if(m_pKeyboard->isKeyDown(OIS::KC_LSHIFT))
m_pCamera->moveRelative(m_TranslateVector);
else
#endif
m_pCamera->moveRelative(m_TranslateVector / 10);
}
void OgreFramework::getInput()
{
#if !defined(OGRE_IS_IOS)
if(m_pKeyboard->isKeyDown(OIS::KC_A))
m_TranslateVector.x = -m_MoveScale;
if(m_pKeyboard->isKeyDown(OIS::KC_D))
m_TranslateVector.x = m_MoveScale;
if(m_pKeyboard->isKeyDown(OIS::KC_W))
m_TranslateVector.z = -m_MoveScale;
if(m_pKeyboard->isKeyDown(OIS::KC_S))
m_TranslateVector.z = m_MoveScale;
if(m_pKeyboard->isKeyDown(OIS::KC_HOME)) {
m_pCamera->setPosition(-10.861927, 6.726564, -7.668012);
m_pCamera->lookAt(0,4,-8);
}
#endif
}
<|endoftext|> |
<commit_before>/**
* @copyright Copyright 2018 The J-PET Framework Authors. All rights reserved.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may find a copy of the License in the LICENCE file.
*
* 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.
*
* @file JPetHaddTest.cpp
*/
#define BOOST_TEST_DYN_LINK
#define BOOST_TEST_MODULE JPetHaddTest
#include "JPetBarrelSlot/JPetBarrelSlot.h"
#include "JPetEvent/JPetEvent.h"
#include "JPetReader/JPetReader.h"
#include "JPetScin/JPetScin.h"
#include "JPetTimeWindow/JPetTimeWindow.h"
#include <boost/test/unit_test.hpp>
#include <iostream>
#include <stdexcept>
#include <stdio.h>
#include <string>
BOOST_AUTO_TEST_SUITE(JPetHaddTestSuite)
std::string exec(std::string cmd) {
char buffer[128];
std::string result = "";
FILE* pipe = popen(cmd.c_str(), "r");
if (!pipe)
throw std::runtime_error("popen() failed!");
try {
while (!feof(pipe)) {
if (fgets(buffer, 128, pipe) != NULL)
result += buffer;
}
} catch (...) {
pclose(pipe);
throw;
}
pclose(pipe);
return result;
}
BOOST_AUTO_TEST_CASE(hadd_test) {
std::string haddedFileName = "";
std::string firstFileName = "unitTestData/JPetHaddTest/single_link_def/dabc_17237091818.hadd.test.root";
std::string secondFileName = "unitTestData/JPetHaddTest/single_link_def/dabc_17237093844.hadd.test.root";
#if ROOT_VERSION_CODE < ROOT_VERSION(6, 0, 0)
haddedFileName = "unitTestData/JPetHaddTest/hadded_root5.hadd.test.root";
#else
haddedFileName = "unitTestData/JPetHaddTest/hadded_root6.hadd.test.root";
#endif
exec("hadd -f " + haddedFileName + " " + firstFileName + " " + secondFileName);
JPetReader readerFirstFile(firstFileName.c_str());
JPetReader readerSecondFile(secondFileName.c_str());
JPetReader readerHaddedFile(haddedFileName.c_str());
BOOST_REQUIRE(readerFirstFile.isOpen());
BOOST_REQUIRE(readerSecondFile.isOpen());
BOOST_REQUIRE(readerHaddedFile.isOpen());
BOOST_REQUIRE_EQUAL(std::string(readerFirstFile.getCurrentEntry().GetName()), std::string("JPetTimeWindow"));
BOOST_REQUIRE_EQUAL(std::string(readerSecondFile.getCurrentEntry().GetName()), std::string("JPetTimeWindow"));
BOOST_REQUIRE_EQUAL(std::string(readerHaddedFile.getCurrentEntry().GetName()), std::string("JPetTimeWindow"));
const auto firstParamBank = readerFirstFile.getObjectFromFile("ParamBank");
const auto secondParamBank = readerSecondFile.getObjectFromFile("ParamBank");
const auto haddedParamBank = readerHaddedFile.getObjectFromFile("ParamBank");
BOOST_CHECK(firstParamBank);
BOOST_CHECK(secondParamBank);
BOOST_CHECK(haddedParamBank);
long long firstFileNumberOfEntries = readerFirstFile.getNbOfAllEntries();
long long secondFileNumberOfEntries = readerSecondFile.getNbOfAllEntries();
long long haddedFileNumberOfEntries = readerHaddedFile.getNbOfAllEntries();
BOOST_REQUIRE_EQUAL(haddedFileNumberOfEntries, firstFileNumberOfEntries + secondFileNumberOfEntries);
for (long long i = 0; i < haddedFileNumberOfEntries; i++) {
const auto& haddedTimeWindow = static_cast<const JPetTimeWindow&>(readerHaddedFile.getCurrentEntry());
const auto& compareTimeWindow = i < firstFileNumberOfEntries ? static_cast<const JPetTimeWindow&>(readerFirstFile.getCurrentEntry())
: static_cast<const JPetTimeWindow&>(readerSecondFile.getCurrentEntry());
BOOST_REQUIRE_EQUAL(haddedTimeWindow.getNumberOfEvents(), compareTimeWindow.getNumberOfEvents());
BOOST_CHECK_PREDICATE(std::not_equal_to<size_t>(), (haddedTimeWindow.getNumberOfEvents())(0));
for (size_t i = 0; i < haddedTimeWindow.getNumberOfEvents(); i++) {
const auto& haddedEvent = static_cast<const JPetEvent&>(haddedTimeWindow[i]);
const auto& compareEvent = static_cast<const JPetEvent&>(compareTimeWindow[i]);
const auto& haddedHits = haddedEvent.getHits();
const auto& compareHits = compareEvent.getHits();
BOOST_REQUIRE_EQUAL(haddedHits.size(), compareHits.size());
for (unsigned int i = 0; i < haddedHits.size(); i++) {
BOOST_REQUIRE_EQUAL(haddedHits[i].getPosX(), compareHits[i].getPosX());
BOOST_REQUIRE_EQUAL(haddedHits[i].getPosY(), compareHits[i].getPosY());
BOOST_REQUIRE_EQUAL(haddedHits[i].getPosZ(), compareHits[i].getPosZ());
BOOST_REQUIRE_EQUAL(haddedHits[i].getEnergy(), compareHits[i].getEnergy());
BOOST_REQUIRE_EQUAL(haddedHits[i].getQualityOfEnergy(), compareHits[i].getQualityOfEnergy());
BOOST_REQUIRE_EQUAL(haddedHits[i].getTime(), compareHits[i].getTime());
BOOST_REQUIRE_EQUAL(haddedHits[i].getTimeDiff(), compareHits[i].getTimeDiff());
BOOST_REQUIRE_EQUAL(haddedHits[i].getQualityOfTime(), compareHits[i].getQualityOfTime());
BOOST_REQUIRE_EQUAL(haddedHits[i].getQualityOfTimeDiff(), compareHits[i].getQualityOfTimeDiff());
BOOST_REQUIRE(haddedHits[i].getScintillator() == compareHits[i].getScintillator());
BOOST_REQUIRE(haddedHits[i].getBarrelSlot() == compareHits[i].getBarrelSlot());
}
}
readerHaddedFile.nextEntry();
if (i < firstFileNumberOfEntries)
readerFirstFile.nextEntry();
else
readerSecondFile.nextEntry();
}
}
BOOST_AUTO_TEST_SUITE_END()
<commit_msg>Add ParamBank test<commit_after>/**
* @copyright Copyright 2018 The J-PET Framework Authors. All rights reserved.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may find a copy of the License in the LICENCE file.
*
* 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.
*
* @file JPetHaddTest.cpp
*/
#define BOOST_TEST_DYN_LINK
#define BOOST_TEST_MODULE JPetHaddTest
#include "JPetBarrelSlot/JPetBarrelSlot.h"
#include "JPetEvent/JPetEvent.h"
#include "JPetReader/JPetReader.h"
#include "JPetScin/JPetScin.h"
#include "JPetTimeWindow/JPetTimeWindow.h"
#include <boost/test/unit_test.hpp>
#include <iostream>
#include <stdexcept>
#include <stdio.h>
#include <string>
BOOST_AUTO_TEST_SUITE(JPetHaddTestSuite)
std::string exec(std::string cmd) {
char buffer[128];
std::string result = "";
FILE* pipe = popen(cmd.c_str(), "r");
if (!pipe)
throw std::runtime_error("popen() failed!");
try {
while (!feof(pipe)) {
if (fgets(buffer, 128, pipe) != NULL)
result += buffer;
}
} catch (...) {
pclose(pipe);
throw;
}
pclose(pipe);
return result;
}
BOOST_AUTO_TEST_CASE(check_same_data) {
std::string haddedFileName = "";
std::string firstFileName = "unitTestData/JPetHaddTest/single_link_def/dabc_17237091818.hadd.test.root";
std::string secondFileName = "unitTestData/JPetHaddTest/single_link_def/dabc_17237093844.hadd.test.root";
#if ROOT_VERSION_CODE < ROOT_VERSION(6, 0, 0)
haddedFileName = "unitTestData/JPetHaddTest/hadded_root5.hadd.test.root";
#else
haddedFileName = "unitTestData/JPetHaddTest/hadded_root6.hadd.test.root";
#endif
exec("hadd -f " + haddedFileName + " " + firstFileName + " " + secondFileName);
JPetReader readerFirstFile(firstFileName.c_str());
JPetReader readerSecondFile(secondFileName.c_str());
JPetReader readerHaddedFile(haddedFileName.c_str());
BOOST_REQUIRE(readerFirstFile.isOpen());
BOOST_REQUIRE(readerSecondFile.isOpen());
BOOST_REQUIRE(readerHaddedFile.isOpen());
BOOST_REQUIRE_EQUAL(std::string(readerFirstFile.getCurrentEntry().GetName()), std::string("JPetTimeWindow"));
BOOST_REQUIRE_EQUAL(std::string(readerSecondFile.getCurrentEntry().GetName()), std::string("JPetTimeWindow"));
BOOST_REQUIRE_EQUAL(std::string(readerHaddedFile.getCurrentEntry().GetName()), std::string("JPetTimeWindow"));
const auto firstParamBank = readerFirstFile.getObjectFromFile("ParamBank");
const auto secondParamBank = readerSecondFile.getObjectFromFile("ParamBank");
const auto haddedParamBank = readerHaddedFile.getObjectFromFile("ParamBank");
BOOST_CHECK(firstParamBank);
BOOST_CHECK(secondParamBank);
BOOST_CHECK(haddedParamBank);
long long firstFileNumberOfEntries = readerFirstFile.getNbOfAllEntries();
long long secondFileNumberOfEntries = readerSecondFile.getNbOfAllEntries();
long long haddedFileNumberOfEntries = readerHaddedFile.getNbOfAllEntries();
BOOST_REQUIRE_EQUAL(haddedFileNumberOfEntries, firstFileNumberOfEntries + secondFileNumberOfEntries);
for (long long i = 0; i < haddedFileNumberOfEntries; i++) {
const auto& haddedTimeWindow = static_cast<const JPetTimeWindow&>(readerHaddedFile.getCurrentEntry());
const auto& compareTimeWindow = i < firstFileNumberOfEntries ? static_cast<const JPetTimeWindow&>(readerFirstFile.getCurrentEntry())
: static_cast<const JPetTimeWindow&>(readerSecondFile.getCurrentEntry());
BOOST_REQUIRE_EQUAL(haddedTimeWindow.getNumberOfEvents(), compareTimeWindow.getNumberOfEvents());
BOOST_CHECK_PREDICATE(std::not_equal_to<size_t>(), (haddedTimeWindow.getNumberOfEvents())(0));
for (size_t i = 0; i < haddedTimeWindow.getNumberOfEvents(); i++) {
const auto& haddedEvent = static_cast<const JPetEvent&>(haddedTimeWindow[i]);
const auto& compareEvent = static_cast<const JPetEvent&>(compareTimeWindow[i]);
const auto& haddedHits = haddedEvent.getHits();
const auto& compareHits = compareEvent.getHits();
BOOST_REQUIRE_EQUAL(haddedHits.size(), compareHits.size());
for (unsigned int i = 0; i < haddedHits.size(); i++) {
BOOST_REQUIRE_EQUAL(haddedHits[i].getPosX(), compareHits[i].getPosX());
BOOST_REQUIRE_EQUAL(haddedHits[i].getPosY(), compareHits[i].getPosY());
BOOST_REQUIRE_EQUAL(haddedHits[i].getPosZ(), compareHits[i].getPosZ());
BOOST_REQUIRE_EQUAL(haddedHits[i].getEnergy(), compareHits[i].getEnergy());
BOOST_REQUIRE_EQUAL(haddedHits[i].getQualityOfEnergy(), compareHits[i].getQualityOfEnergy());
BOOST_REQUIRE_EQUAL(haddedHits[i].getTime(), compareHits[i].getTime());
BOOST_REQUIRE_EQUAL(haddedHits[i].getTimeDiff(), compareHits[i].getTimeDiff());
BOOST_REQUIRE_EQUAL(haddedHits[i].getQualityOfTime(), compareHits[i].getQualityOfTime());
BOOST_REQUIRE_EQUAL(haddedHits[i].getQualityOfTimeDiff(), compareHits[i].getQualityOfTimeDiff());
BOOST_REQUIRE(haddedHits[i].getScintillator() == compareHits[i].getScintillator());
BOOST_REQUIRE(haddedHits[i].getBarrelSlot() == compareHits[i].getBarrelSlot());
}
}
readerHaddedFile.nextEntry();
if (i < firstFileNumberOfEntries)
readerFirstFile.nextEntry();
else
readerSecondFile.nextEntry();
}
delete firstParamBank;
delete secondParamBank;
delete haddedParamBank;
}
BOOST_AUTO_TEST_CASE(check_param_bank) {
std::string haddedFileName = "";
std::string firstFileName = "unitTestData/JPetHaddTest/single_link_def/dabc_17237091818.hadd.test.root";
std::string secondFileName = "unitTestData/JPetHaddTest/single_link_def/dabc_17237093844.hadd.test.root";
#if ROOT_VERSION_CODE < ROOT_VERSION(6, 0, 0)
haddedFileName = "unitTestData/JPetHaddTest/hadded_parambank_root5.hadd.test.root";
#else
haddedFileName = "unitTestData/JPetHaddTest/hadded_parambank_root6.hadd.test.root";
#endif
exec("hadd -f " + haddedFileName + " " + firstFileName + " " + secondFileName);
JPetReader readerHaddedFile(haddedFileName.c_str());
BOOST_REQUIRE(readerHaddedFile.isOpen());
BOOST_REQUIRE_EQUAL(std::string(readerHaddedFile.getCurrentEntry().GetName()), std::string("JPetTimeWindow"));
const auto haddedParamBank = readerHaddedFile.getObjectFromFile("ParamBank");
BOOST_CHECK(haddedParamBank);
long long haddedFileNumberOfEntries = readerHaddedFile.getNbOfAllEntries();
for (long long i = 0; i < haddedFileNumberOfEntries; i++) {
const auto& haddedTimeWindow = static_cast<const JPetTimeWindow&>(readerHaddedFile.getCurrentEntry());
BOOST_CHECK_PREDICATE(std::not_equal_to<size_t>(), (haddedTimeWindow.getNumberOfEvents())(0));
for (size_t i = 0; i < haddedTimeWindow.getNumberOfEvents(); i++) {
const auto& haddedEvent = static_cast<const JPetEvent&>(haddedTimeWindow[i]);
const auto& haddedHits = haddedEvent.getHits();
for (unsigned int i = 0; i < haddedHits.size(); i++) {
BOOST_CHECK_PREDICATE(std::not_equal_to<size_t>(), (haddedHits[i].getScintillator().getID())(0));
}
}
readerHaddedFile.nextEntry();
}
delete haddedParamBank;
}
BOOST_AUTO_TEST_SUITE_END()
<|endoftext|> |
<commit_before>#include <stdio.h>
#include <ctype.h>
#include <math.h>
#include <stdlib.h>
#include <string.h>
#include <ctype.h>
#include <errno.h>
#include "linear.h"
#define Malloc(type,n) (type *)malloc((n)*sizeof(type))
#define INF HUGE_VAL
struct feature_node *x;
typedef struct svmlines {
int* data;
int classifier;
int classifier2;
} svmlines;
int max_nr_attr = 64;
struct model* model_;
int flag_predict_probability=0;
static char *line = NULL;
static int max_line_len;
void print_null(const char *s) {}
void exit_with_help()
{
printf(
"Usage: train [options] training_set_file [model_file]\n"
"options:\n"
"-s type : set type of solver (default 1)\n"
" 0 -- L2-regularized logistic regression\n"
" 1 -- L2-regularized L2-loss support vector classification (dual)\n"
" 2 -- L2-regularized L2-loss support vector classification (primal)\n"
" 3 -- L2-regularized L1-loss support vector classification (dual)\n"
" 4 -- multi-class support vector classification by Crammer and Singer\n"
" 5 -- L1-regularized L2-loss support vector classification\n"
" 6 -- L1-regularized logistic regression\n"
"-c cost : set the parameter C (default 1)\n"
"-e epsilon : set tolerance of termination criterion\n"
" -s 0 and 2\n"
" |f'(w)|_2 <= eps*min(pos,neg)/l*|f'(w0)|_2,\n"
" where f is the primal function and pos/neg are # of\n"
" positive/negative data (default 0.01)\n"
" -s 1, 3, and 4\n"
" Dual maximal violation <= eps; similar to libsvm (default 0.1)\n"
" -s 5 and 6\n"
" |f'(w)|_inf <= eps*min(pos,neg)/l*|f'(w0)|_inf,\n"
" where f is the primal function (default 0.01)\n"
"-B bias : if bias >= 0, instance x becomes [x; bias]; if < 0, no bias term added (default -1)\n"
"-wi weight: weights adjust the parameter C of different classes (see README for details)\n"
"-v n: n-fold cross validation mode\n"
"-q : quiet mode (no outputs)\n"
);
exit(1);
}
void exit_input_error(int line_num)
{
fprintf(stderr,"Wrong input format at line %d\n", line_num);
exit(1);
}
static char* readline(FILE *input)
{
int len;
if(fgets(line,max_line_len,input) == NULL)
return NULL;
while(strrchr(line,'\n') == NULL)
{
max_line_len *= 2;
line = (char *) realloc(line,max_line_len);
len = (int) strlen(line);
if(fgets(line+len,max_line_len-len,input) == NULL)
break;
}
return line;
}
int correct = 0;
int total = 0;
void do_predict(svmlines* classifier, FILE *output, struct model* model_, int startloc, int numlines, int numfeatures, int* prediction)
{
int nr_class=get_nr_class(model_);
double *prob_estimates=NULL;
int j, n;
int nr_feature=get_nr_feature(model_);
if(model_->bias>=0)
n=nr_feature+1;
else
n=nr_feature;
if(flag_predict_probability)
{
int *labels;
if(model_->param.solver_type!=L2R_LR)
{
fprintf(stderr, "probability output is only supported for logistic regression\n");
exit(1);
}
labels=(int *) malloc(nr_class*sizeof(int));
get_labels(model_,labels);
prob_estimates = (double *) malloc(nr_class*sizeof(double));
fprintf(output,"labels");
for(j=0;j<nr_class;j++)
fprintf(output," %d",labels[j]);
fprintf(output,"\n");
free(labels);
}
int linesread = startloc;
while(linesread < startloc+numlines)
{
linesread++;
int i = 0;
int target_label, predict_label;
int inst_max_index = 0; // strtol gives 0 if wrong format
target_label = classifier[linesread].classifier;
for (int j = 0; j < numfeatures; j++)
{
if(i>=max_nr_attr-2) // need one more for index = -1
{
max_nr_attr *= 2;
x = (struct feature_node *) realloc(x,max_nr_attr*sizeof(struct feature_node));
}
x[i].index = j+1;
x[i].value = classifier[linesread].data[j];
i++;
}
if(model_->bias>=0)
{
x[i].index = n;
x[i].value = model_->bias;
i++;
}
x[i].index = -1;
if(flag_predict_probability)
{
int j;
predict_label = (int)predict_probability(model_,x,prob_estimates);
fprintf(output,"%d",predict_label);
for(j=0;j<model_->nr_class;j++)
fprintf(output," %g",prob_estimates[j]);
fprintf(output,"\n");
}
else
{
predict_label = (int)predict(model_,x);
fprintf(output,"%d %d\n",predict_label, target_label);
*prediction = predict_label;
}
if(predict_label == target_label)
++correct;
++total;
}
if(flag_predict_probability)
free(prob_estimates);
}
void parse_command_line(int argc, char **argv);
void read_problem( svmlines* classifier, int numlines,int numfeatures, problem* prob, int pred);
struct feature_node *x_space;
struct parameter param;
int flag_cross_validation;
int nr_fold;
double bias;
int main(int argc, char *argv[])
{
int* data;
int * net;
int datalen,netlen;
struct problem prob, prob2;
int numVMs = 1;
if (argc > 1) {
numVMs = atoi(argv[1]);
}
FILE* in;
if (argc > 2) {
in = fopen(argv[2],"r");
} else {
in = fopen("data1","r");
}
//FILE* in2 = fopen("net.in","r");
FILE *output = fopen("test.out","w");
char VMname[20];
for (int ind = 0; ind < numVMs; ind++) {
fscanf(in,"%s",VMname);
fscanf(in,"%d",&datalen);
//fscanf(in2,"%d",&netlen);
fprintf(output,"%s ", VMname);
data = new int[datalen];
//net = new int[netlen];
for (int i = 0; i < datalen; i++) {
fscanf(in,"%d",&data[i]);
}
/*for (int i = 0; i < netlen; i++) {
fscanf(in2,"%d",&net[i]);
}*/
int n = 3;
int numlines = datalen-n;
int numruns = 1;
prob.numpos = 0;
svmlines* classifier = new svmlines[datalen-n];
for (int i = 0; i < datalen-n; i++) {
if (data[i+n] > data[i+n-1]) {
classifier[i].classifier = 1;
if (i < numlines)
prob.numpos++;
}
else
classifier[i].classifier = -1;
if (abs(data[i+n] -data[i+n-1]) > 5)
classifier[i].classifier2 = 1;
else
classifier[i].classifier2 = -1;
classifier[i].data = new int[2*n];
classifier[i].data[0] = data[i];
for (int j = 1; j < n; j++) {
classifier[i].data[j] = data[i+j] - data[i+j-1];
}
classifier[i].data[n] = 0;
for (int j = 1; j < n; j++) {
classifier[i].data[n+j] = 0;//classifier[i].data[j]-classifier[i].data[j-1];
}
}
prob.SV = new int*[101];
prob.nSV = new int[101];
for (int i = 0; i < 101; i++)
prob.SV[i] = NULL;
for (int s = 0; s < numruns; s++) {
parse_command_line(argc, argv);
read_problem(classifier,numlines+s-2,2*n,&prob,0);
model_=train(&prob, ¶m);
x = (struct feature_node *) malloc(max_nr_attr*sizeof(struct feature_node));
int prediction;
do_predict(classifier, output, model_,numlines+s-2,1,2*n,&prediction);
free(line);
free(x);
free(prob.y);
free(prob.x);
free(x_space);
read_problem(classifier,numlines+s,2*n,&prob,prediction);
free(line);
//free(x);
free(prob.y);
free(prob.x);
free(x_space);
//free(line);
if (classifier[numlines+s].classifier == 1)
prob.numpos++;
free_and_destroy_model(&model_);
}
printf("Accuracy = %g%% (%d/%d)\n",(double) correct/total*100,correct,total);
fclose(output);
}
return 0;
}
void parse_command_line(int argc, char **argv)
{
// default values
param.solver_type = 2;
param.C = 5;
param.eps = INF; // see setting below
param.nr_weight = 0;
param.weight_label = NULL;
param.weight = NULL;
flag_cross_validation = 0;
bias = 10;
// parse options
// determine filenames
if(param.eps == INF)
{
if(param.solver_type == L2R_LR || param.solver_type == L2R_L2LOSS_SVC)
param.eps = 0.01;
else if(param.solver_type == L2R_L2LOSS_SVC_DUAL || param.solver_type == L2R_L1LOSS_SVC_DUAL || param.solver_type == MCSVM_CS)
param.eps = 0.1;
else if(param.solver_type == L1R_L2LOSS_SVC || param.solver_type == L1R_LR)
param.eps = 0.01;
}
}
// read in a problem (in libsvm format)
void read_problem( svmlines* classifier, int numlines, int numfeatures, problem * prob, int pred)
{
int max_index, i;
long int elements, j;
elements = numlines*(numfeatures+1);
switch(pred) {
case 0:
prob->l = numlines;
break;
case 1:
prob->l = prob->numpos;
break;
case -1:
prob->l = numlines-prob->numpos;
break;
}
prob->y = new double[prob->l];
prob->x = Malloc(struct feature_node *,prob->l);
x_space = Malloc(struct feature_node,elements+prob->l);
prob->bias=bias;
max_index = numfeatures;
int s = 0;
for(i=0;i<numlines;i++)
{
if (pred == -classifier[i].classifier)
continue;
prob->x[s] = &x_space[s*(numfeatures+2)];
feature_node* tmp = &x_space[s*(numfeatures+2)];
prob->y[s] = classifier[i].classifier;
for (j=0; j <numfeatures;j++) {
tmp[j].index = j+1;
tmp[j].value = classifier[i].data[j];
}
if(prob->bias >= 0)
tmp[numfeatures].value = prob->bias;
tmp[numfeatures+1].index = -1;
s++;
}
if(prob->bias >= 0)
{
prob->n=max_index+1;
for(i=1;i<prob->l;i++)
(prob->x[i]-2)->index = prob->n;
j = (prob->n+1)*prob->l;
x_space[j-2].index = prob->n;
}
else
prob->n=max_index;
}
<commit_msg>Memory management<commit_after>#include <stdio.h>
#include <ctype.h>
#include <math.h>
#include <stdlib.h>
#include <string.h>
#include <ctype.h>
#include <errno.h>
#include "linear.h"
#define Malloc(type,n) (type *)malloc((n)*sizeof(type))
#define INF HUGE_VAL
struct feature_node *x;
typedef struct svmlines {
int* data;
int classifier;
int classifier2;
} svmlines;
int max_nr_attr = 64;
struct model* model_;
int flag_predict_probability=0;
static char *line = NULL;
static int max_line_len;
void print_null(const char *s) {}
void exit_with_help()
{
printf(
"Usage: train [options] training_set_file [model_file]\n"
"options:\n"
"-s type : set type of solver (default 1)\n"
" 0 -- L2-regularized logistic regression\n"
" 1 -- L2-regularized L2-loss support vector classification (dual)\n"
" 2 -- L2-regularized L2-loss support vector classification (primal)\n"
" 3 -- L2-regularized L1-loss support vector classification (dual)\n"
" 4 -- multi-class support vector classification by Crammer and Singer\n"
" 5 -- L1-regularized L2-loss support vector classification\n"
" 6 -- L1-regularized logistic regression\n"
"-c cost : set the parameter C (default 1)\n"
"-e epsilon : set tolerance of termination criterion\n"
" -s 0 and 2\n"
" |f'(w)|_2 <= eps*min(pos,neg)/l*|f'(w0)|_2,\n"
" where f is the primal function and pos/neg are # of\n"
" positive/negative data (default 0.01)\n"
" -s 1, 3, and 4\n"
" Dual maximal violation <= eps; similar to libsvm (default 0.1)\n"
" -s 5 and 6\n"
" |f'(w)|_inf <= eps*min(pos,neg)/l*|f'(w0)|_inf,\n"
" where f is the primal function (default 0.01)\n"
"-B bias : if bias >= 0, instance x becomes [x; bias]; if < 0, no bias term added (default -1)\n"
"-wi weight: weights adjust the parameter C of different classes (see README for details)\n"
"-v n: n-fold cross validation mode\n"
"-q : quiet mode (no outputs)\n"
);
exit(1);
}
void exit_input_error(int line_num)
{
fprintf(stderr,"Wrong input format at line %d\n", line_num);
exit(1);
}
static char* readline(FILE *input)
{
int len;
if(fgets(line,max_line_len,input) == NULL)
return NULL;
while(strrchr(line,'\n') == NULL)
{
max_line_len *= 2;
line = (char *) realloc(line,max_line_len);
len = (int) strlen(line);
if(fgets(line+len,max_line_len-len,input) == NULL)
break;
}
return line;
}
int correct = 0;
int total = 0;
void do_predict(svmlines* classifier, FILE *output, struct model* model_, int startloc, int numlines, int numfeatures, int* prediction)
{
int nr_class=get_nr_class(model_);
double *prob_estimates=NULL;
int j, n;
int nr_feature=get_nr_feature(model_);
if(model_->bias>=0)
n=nr_feature+1;
else
n=nr_feature;
if(flag_predict_probability)
{
int *labels;
if(model_->param.solver_type!=L2R_LR)
{
fprintf(stderr, "probability output is only supported for logistic regression\n");
exit(1);
}
labels=(int *) malloc(nr_class*sizeof(int));
get_labels(model_,labels);
prob_estimates = (double *) malloc(nr_class*sizeof(double));
fprintf(output,"labels");
for(j=0;j<nr_class;j++)
fprintf(output," %d",labels[j]);
fprintf(output,"\n");
free(labels);
}
int linesread = startloc;
while(linesread < startloc+numlines)
{
linesread++;
int i = 0;
int target_label, predict_label;
int inst_max_index = 0; // strtol gives 0 if wrong format
target_label = classifier[linesread].classifier;
for (int j = 0; j < numfeatures; j++)
{
if(i>=max_nr_attr-2) // need one more for index = -1
{
max_nr_attr *= 2;
x = (struct feature_node *) realloc(x,max_nr_attr*sizeof(struct feature_node));
}
x[i].index = j+1;
x[i].value = classifier[linesread].data[j];
i++;
}
if(model_->bias>=0)
{
x[i].index = n;
x[i].value = model_->bias;
i++;
}
x[i].index = -1;
if(flag_predict_probability)
{
int j;
predict_label = (int)predict_probability(model_,x,prob_estimates);
fprintf(output,"%d",predict_label);
for(j=0;j<model_->nr_class;j++)
fprintf(output," %g",prob_estimates[j]);
fprintf(output,"\n");
}
else
{
predict_label = (int)predict(model_,x);
fprintf(output,"%d %d\n",predict_label, target_label);
*prediction = predict_label;
}
if(predict_label == target_label)
++correct;
++total;
}
if(flag_predict_probability)
free(prob_estimates);
}
void parse_command_line(int argc, char **argv);
void read_problem( svmlines* classifier, int numlines,int numfeatures, problem* prob, int pred);
struct feature_node *x_space;
struct parameter param;
int flag_cross_validation;
int nr_fold;
double bias;
int main(int argc, char *argv[])
{
int* data;
int * net;
int datalen,netlen;
struct problem prob, prob2;
int numVMs = 1;
if (argc > 1) {
numVMs = atoi(argv[1]);
}
FILE* in;
if (argc > 2) {
in = fopen(argv[2],"r");
} else {
in = fopen("data1","r");
}
//FILE* in2 = fopen("net.in","r");
FILE *output = fopen("test.out","w");
char VMname[20];
for (int ind = 0; ind < numVMs; ind++) {
fscanf(in,"%s",VMname);
fscanf(in,"%d",&datalen);
//fscanf(in2,"%d",&netlen);
fprintf(output,"%s ", VMname);
data = new int[datalen];
//net = new int[netlen];
for (int i = 0; i < datalen; i++) {
fscanf(in,"%d",&data[i]);
}
/*for (int i = 0; i < netlen; i++) {
fscanf(in2,"%d",&net[i]);
}*/
int n = 3;
int numlines = datalen-n;
int numruns = 1;
prob.numpos = 0;
svmlines* classifier = new svmlines[datalen-n];
for (int i = 0; i < datalen-n; i++) {
if (data[i+n] > data[i+n-1]) {
classifier[i].classifier = 1;
if (i < numlines)
prob.numpos++;
}
else
classifier[i].classifier = -1;
if (abs(data[i+n] -data[i+n-1]) > 5)
classifier[i].classifier2 = 1;
else
classifier[i].classifier2 = -1;
classifier[i].data = new int[2*n];
classifier[i].data[0] = data[i];
for (int j = 1; j < n; j++) {
classifier[i].data[j] = data[i+j] - data[i+j-1];
}
classifier[i].data[n] = 0;
for (int j = 1; j < n; j++) {
classifier[i].data[n+j] = 0;//classifier[i].data[j]-classifier[i].data[j-1];
}
}
prob.SV = new int*[101];
prob.nSV = new int[101];
for (int i = 0; i < 101; i++)
prob.SV[i] = NULL;
for (int s = 0; s < numruns; s++) {
parse_command_line(argc, argv);
read_problem(classifier,numlines+s-2,2*n,&prob,0);
model_=train(&prob, ¶m);
x = (struct feature_node *) malloc(max_nr_attr*sizeof(struct feature_node));
int prediction;
do_predict(classifier, output, model_,numlines+s-2,1,2*n,&prediction);
free(line);
free(x);
free(prob.y);
free(prob.x);
free(x_space);
read_problem(classifier,numlines+s,2*n,&prob,prediction);
free(line);
//free(x);
free(prob.y);
free(prob.x);
free(x_space);
//free(line);
if (classifier[numlines+s].classifier == 1)
prob.numpos++;
free_and_destroy_model(&model_);
}
printf("Accuracy = %g%% (%d/%d)\n",(double) correct/total*100,correct,total);
delete(classifier);
}
fclose(output);
return 0;
}
void parse_command_line(int argc, char **argv)
{
// default values
param.solver_type = 2;
param.C = 5;
param.eps = INF; // see setting below
param.nr_weight = 0;
param.weight_label = NULL;
param.weight = NULL;
flag_cross_validation = 0;
bias = 10;
// parse options
// determine filenames
if(param.eps == INF)
{
if(param.solver_type == L2R_LR || param.solver_type == L2R_L2LOSS_SVC)
param.eps = 0.01;
else if(param.solver_type == L2R_L2LOSS_SVC_DUAL || param.solver_type == L2R_L1LOSS_SVC_DUAL || param.solver_type == MCSVM_CS)
param.eps = 0.1;
else if(param.solver_type == L1R_L2LOSS_SVC || param.solver_type == L1R_LR)
param.eps = 0.01;
}
}
// read in a problem (in libsvm format)
void read_problem( svmlines* classifier, int numlines, int numfeatures, problem * prob, int pred)
{
int max_index, i;
long int elements, j;
elements = numlines*(numfeatures+1);
switch(pred) {
case 0:
prob->l = numlines;
break;
case 1:
prob->l = prob->numpos;
break;
case -1:
prob->l = numlines-prob->numpos;
break;
}
prob->y = new double[prob->l];
prob->x = Malloc(struct feature_node *,prob->l);
x_space = Malloc(struct feature_node,elements+prob->l);
prob->bias=bias;
max_index = numfeatures;
int s = 0;
for(i=0;i<numlines;i++)
{
if (pred == -classifier[i].classifier)
continue;
prob->x[s] = &x_space[s*(numfeatures+2)];
feature_node* tmp = &x_space[s*(numfeatures+2)];
prob->y[s] = classifier[i].classifier;
for (j=0; j <numfeatures;j++) {
tmp[j].index = j+1;
tmp[j].value = classifier[i].data[j];
}
if(prob->bias >= 0)
tmp[numfeatures].value = prob->bias;
tmp[numfeatures+1].index = -1;
s++;
}
if(prob->bias >= 0)
{
prob->n=max_index+1;
for(i=1;i<prob->l;i++)
(prob->x[i]-2)->index = prob->n;
j = (prob->n+1)*prob->l;
x_space[j-2].index = prob->n;
}
else
prob->n=max_index;
}
<|endoftext|> |
<commit_before>/**************************************************************************
* Copyright(c) 1998-2003, ALICE Experiment at CERN, All rights reserved. *
* *
* Author: The ALICE Off-line Project. *
* Contributors are mentioned in the code where appropriate. *
* *
* Permission to use, copy, modify and distribute this software and its *
* documentation strictly for non-commercial purposes is hereby granted *
* without fee, provided that the above copyright notice appears in all *
* copies and that both the copyright notice and this permission notice *
* appear in the supporting documentation. The authors make no claims *
* about the suitability of this software for any purpose. It is *
* provided "as is" without express or implied warranty. *
**************************************************************************/
/////////////////////////////////////////////////////////////////////////
// ALICE DISPLAY CLUSTERS CLASS //
// Author: Mayeul ROUSSELET //
// e-mail: Mayeul.Rousselet@cern.ch //
// Last update:26/08/2003 //
/////////////////////////////////////////////////////////////////////////
#include <Riostream.h>
#include <TFile.h>
#include <TPolyMarker3D.h>
#include "AliClusters.h"
#include "AliDisplay2.h"
#include "AliDisplayClusters.h"
#include "AliITS.h"
#include "AliITSLoader.h"
#include "AliITSclusterV2.h"
#include "AliITSgeom.h"
#include "AliModuleInfo.h"
#include "AliRun.h"
#include "AliRunLoader.h"
#include "AliTPCLoader.h"
#include "AliTPCParam.h"
#include "AliTPCcluster.h"
ClassImp(AliDisplayClusters)
//_____________________________________________________________
AliDisplayClusters::AliDisplayClusters()
{
//Default constructor
fPoints = new TPolyMarker3D[gAliDisplay2->GetNbModules()];
fName = new char*[gAliDisplay2->GetNbModules()];
fNb=0;
for(Int_t i=0;i<gAliDisplay2->GetNbModules();i++){
fPoints[i].SetMarkerSize(0.2);
fPoints[i].SetMarkerColor(2);
fPoints[i].SetMarkerStyle(1);
}
}
//_____________________________________________________________
AliDisplayClusters::~AliDisplayClusters()
{
// Destructor
delete [] fPoints;
}
//_____________________________________________________________
Int_t AliDisplayClusters::GetNbClusters()
{
// Returns the number of clusters
Int_t r=0;
for(Int_t i=0;i<fNb;i++){
if(gAliDisplay2->GetModuleInfo()->IsEnabled(fName[i])) r+=fPoints[i].GetN();
}
return r;
}
//_____________________________________________________________
void AliDisplayClusters::LoadClusters(const char *name,Int_t nevent)
{
// Loads ITS and TPC clusters
if(strstr(name,"ITS")) LoadITSClusters(nevent);
if(strstr(name,"TPC")) LoadTPCClusters(nevent);
}
//_____________________________________________________________
void AliDisplayClusters::LoadITSClusters(Int_t nevent)
{
// Loads ITS clusters
fName[fNb]=new char[strlen("ITS")];
strcpy(fName[fNb],"ITS");
AliRunLoader *rl = AliRunLoader::Open("galice.root");
if(!rl) {
cerr<<"Can't open galice.root";
return;
}
AliITSLoader *itsl = (AliITSLoader*)rl->GetLoader("ITSLoader");
AliITS *its = (AliITS*)gAlice->GetModule("ITS");
rl->GetEvent(nevent);
itsl->LoadRecPoints();
TTree *cTree=itsl->TreeR();
if(!cTree)
{
cerr<<"Error occured during ITS clusters load";
return;
}
AliITSgeom *geom=its->GetITSgeom();
Int_t count = 0;
TClonesArray *clusters=new TClonesArray("AliITSclusterV2",10000);
TBranch *branch=cTree->GetBranch("Clusters");
branch->SetAddress(&clusters);
Int_t nentr=(Int_t)cTree->GetEntries();
for (Int_t i=0; i<nentr; i++) {
if (!cTree->GetEvent(i)) continue;
Double_t rot[9];
geom->GetRotMatrix(i,rot);
Int_t lay,lad,det;
geom->GetModuleId(i,lay,lad,det);
Float_t tx,ty,tz;
geom->GetTrans(lay,lad,det,tx,ty,tz);
Double_t r=-tx*rot[1]+ty*rot[0];
if (lay==1) r=-r;
Double_t phi=TMath::ATan2(rot[1],rot[0]);
if (lay==1) phi-=3.1415927;
Double_t cp=TMath::Cos(phi), sp=TMath::Sin(phi);
Int_t ncl=clusters->GetEntriesFast();
while (ncl--) {
AliITSclusterV2 *c=(AliITSclusterV2*)clusters->UncheckedAt(ncl);
Double_t g[3];
g[0]= r*cp + c->GetY()*sp; //
g[1]=-r*sp + c->GetY()*cp; //
g[2]=c->GetZ();
fPoints[fNb].SetPoint(count,g[0],g[1],g[2]);
count++;
}
}
fNb++;
}
//_____________________________________________________________
void AliDisplayClusters::LoadTPCClusters(Int_t nevent)
{
// Loads TPC clusters
fName[fNb]=new char[strlen("TPC")];
strcpy(fName[fNb],"TPC");
TFile *file = TFile::Open("galice.root");
AliTPCParam *dig=(AliTPCParam *)file->Get("75x40_100x60_150x60");
if (!dig) {cerr<<"TPC parameters have not been found !\n";}
file->Close();
AliRunLoader *rl = AliRunLoader::Open("galice.root");
if(!rl) {
cerr<<"Can't open galice.root";
return;
}
AliTPCLoader *itsl = (AliTPCLoader*)rl->GetLoader("TPCLoader");
if(!itsl){
cerr<<"Can't find Loader";
return;
}
rl->GetEvent(nevent);
itsl->LoadRecPoints();
TTree *cTree=itsl->TreeR();
if(!cTree)
{
cerr<<"Error during TPC clusters load";
return;
}
Int_t count = 0;
Float_t noiseth = 10;
AliClusters *clusters=new AliClusters();
clusters->SetClass("AliTPCcluster");
cTree->SetBranchAddress("Segment",&clusters);
Int_t nrows=Int_t(cTree->GetEntries());
for (Int_t n=0; n<nrows; n++) {
cTree->GetEvent(n);
Int_t sec,row;
dig->AdjustSectorRow(clusters->GetID(),sec,row);
TClonesArray &clrow=*clusters->GetArray();
Int_t ncl=clrow.GetEntriesFast();
while (ncl--) {
AliTPCcluster *cl=(AliTPCcluster*)clrow[ncl];
Double_t x=dig->GetPadRowRadii(sec,row), y=cl->GetY(), z=cl->GetZ();
if (cl->GetQ()<noiseth) continue;
Float_t cs, sn, tmp;
dig->AdjustCosSin(sec,cs,sn);
tmp = x*cs-y*sn; y= x*sn+y*cs; x=tmp;
fPoints[fNb].SetPoint(count,x,y,z);
count++;
}
clrow.Clear();
}
delete cTree;
delete dig;
fNb++;
}
//_____________________________________________________________
void AliDisplayClusters::Draw()
{
// Draws clusters
for(Int_t i=0;i<fNb;i++){
if(gAliDisplay2->GetModuleInfo()->IsEnabled(fName[i])) fPoints[i].Draw();
}
}
<commit_msg>Using clusters of Marian (C.Cheshkov)<commit_after>/**************************************************************************
* Copyright(c) 1998-2003, ALICE Experiment at CERN, All rights reserved. *
* *
* Author: The ALICE Off-line Project. *
* Contributors are mentioned in the code where appropriate. *
* *
* Permission to use, copy, modify and distribute this software and its *
* documentation strictly for non-commercial purposes is hereby granted *
* without fee, provided that the above copyright notice appears in all *
* copies and that both the copyright notice and this permission notice *
* appear in the supporting documentation. The authors make no claims *
* about the suitability of this software for any purpose. It is *
* provided "as is" without express or implied warranty. *
**************************************************************************/
/////////////////////////////////////////////////////////////////////////
// ALICE DISPLAY CLUSTERS CLASS //
// Author: Mayeul ROUSSELET //
// e-mail: Mayeul.Rousselet@cern.ch //
// Last update:26/08/2003 //
/////////////////////////////////////////////////////////////////////////
#include <Riostream.h>
#include <TFile.h>
#include <TPolyMarker3D.h>
#include "AliClusters.h"
#include "AliDisplay2.h"
#include "AliDisplayClusters.h"
#include "AliITS.h"
#include "AliITSLoader.h"
#include "AliITSclusterV2.h"
#include "AliITSgeom.h"
#include "AliModuleInfo.h"
#include "AliRun.h"
#include "AliRunLoader.h"
#include "AliTPCLoader.h"
#include "AliTPCParam.h"
#include "AliTPCclusterMI.h"
ClassImp(AliDisplayClusters)
//_____________________________________________________________
AliDisplayClusters::AliDisplayClusters()
{
//Default constructor
fPoints = new TPolyMarker3D[gAliDisplay2->GetNbModules()];
fName = new char*[gAliDisplay2->GetNbModules()];
fNb=0;
for(Int_t i=0;i<gAliDisplay2->GetNbModules();i++){
fPoints[i].SetMarkerSize(0.2);
fPoints[i].SetMarkerColor(2);
fPoints[i].SetMarkerStyle(1);
}
}
//_____________________________________________________________
AliDisplayClusters::~AliDisplayClusters()
{
// Destructor
delete [] fPoints;
}
//_____________________________________________________________
Int_t AliDisplayClusters::GetNbClusters()
{
// Returns the number of clusters
Int_t r=0;
for(Int_t i=0;i<fNb;i++){
if(gAliDisplay2->GetModuleInfo()->IsEnabled(fName[i])) r+=fPoints[i].GetN();
}
return r;
}
//_____________________________________________________________
void AliDisplayClusters::LoadClusters(const char *name,Int_t nevent)
{
// Loads ITS and TPC clusters
if(strstr(name,"ITS")) LoadITSClusters(nevent);
if(strstr(name,"TPC")) LoadTPCClusters(nevent);
}
//_____________________________________________________________
void AliDisplayClusters::LoadITSClusters(Int_t nevent)
{
// Loads ITS clusters
fName[fNb]=new char[strlen("ITS")];
strcpy(fName[fNb],"ITS");
AliRunLoader *rl = AliRunLoader::Open("galice.root");
if(!rl) {
cerr<<"Can't open galice.root";
return;
}
AliITSLoader *itsl = (AliITSLoader*)rl->GetLoader("ITSLoader");
AliITS *its = (AliITS*)gAlice->GetModule("ITS");
rl->GetEvent(nevent);
itsl->LoadRecPoints();
TTree *cTree=itsl->TreeR();
if(!cTree)
{
cerr<<"Error occured during ITS clusters load";
return;
}
AliITSgeom *geom=its->GetITSgeom();
Int_t count = 0;
TClonesArray *clusters=new TClonesArray("AliITSclusterV2",10000);
TBranch *branch=cTree->GetBranch("Clusters");
branch->SetAddress(&clusters);
Int_t nentr=(Int_t)cTree->GetEntries();
for (Int_t i=0; i<nentr; i++) {
if (!cTree->GetEvent(i)) continue;
Double_t rot[9];
geom->GetRotMatrix(i,rot);
Int_t lay,lad,det;
geom->GetModuleId(i,lay,lad,det);
Float_t tx,ty,tz;
geom->GetTrans(lay,lad,det,tx,ty,tz);
Double_t r=-tx*rot[1]+ty*rot[0];
if (lay==1) r=-r;
Double_t phi=TMath::ATan2(rot[1],rot[0]);
if (lay==1) phi-=3.1415927;
Double_t cp=TMath::Cos(phi), sp=TMath::Sin(phi);
Int_t ncl=clusters->GetEntriesFast();
while (ncl--) {
AliITSclusterV2 *c=(AliITSclusterV2*)clusters->UncheckedAt(ncl);
Double_t g[3];
g[0]= r*cp + c->GetY()*sp; //
g[1]=-r*sp + c->GetY()*cp; //
g[2]=c->GetZ();
fPoints[fNb].SetPoint(count,g[0],g[1],g[2]);
count++;
}
}
fNb++;
}
//_____________________________________________________________
void AliDisplayClusters::LoadTPCClusters(Int_t nevent)
{
// Loads TPC clusters
fName[fNb]=new char[strlen("TPC")];
strcpy(fName[fNb],"TPC");
TFile *file = TFile::Open("galice.root");
AliTPCParam *dig=(AliTPCParam *)file->Get("75x40_100x60_150x60");
if (!dig) {cerr<<"TPC parameters have not been found !\n";}
file->Close();
AliRunLoader *rl = AliRunLoader::Open("galice.root");
if(!rl) {
cerr<<"Can't open galice.root";
return;
}
AliTPCLoader *itsl = (AliTPCLoader*)rl->GetLoader("TPCLoader");
if(!itsl){
cerr<<"Can't find Loader";
return;
}
rl->GetEvent(nevent);
itsl->LoadRecPoints();
TTree *cTree=itsl->TreeR();
if(!cTree)
{
cerr<<"Error during TPC clusters load";
return;
}
Int_t count = 0;
Float_t noiseth = 10;
AliClusters *clusters=new AliClusters();
clusters->SetClass("AliTPCclusterMI");
cTree->SetBranchAddress("Segment",&clusters);
Int_t nrows=Int_t(cTree->GetEntries());
for (Int_t n=0; n<nrows; n++) {
cTree->GetEvent(n);
Int_t sec,row;
dig->AdjustSectorRow(clusters->GetID(),sec,row);
TClonesArray &clrow=*clusters->GetArray();
Int_t ncl=clrow.GetEntriesFast();
while (ncl--) {
AliTPCclusterMI *cl=(AliTPCclusterMI*)clrow[ncl];
Double_t x=dig->GetPadRowRadii(sec,row), y=cl->GetY(), z=cl->GetZ();
if (cl->GetQ()<noiseth) continue;
Float_t cs, sn, tmp;
dig->AdjustCosSin(sec,cs,sn);
tmp = x*cs-y*sn; y= x*sn+y*cs; x=tmp;
fPoints[fNb].SetPoint(count,x,y,z);
count++;
}
clrow.Clear();
}
delete cTree;
delete dig;
fNb++;
}
//_____________________________________________________________
void AliDisplayClusters::Draw()
{
// Draws clusters
for(Int_t i=0;i<fNb;i++){
if(gAliDisplay2->GetModuleInfo()->IsEnabled(fName[i])) fPoints[i].Draw();
}
}
<|endoftext|> |
<commit_before>//===-Caching.cpp - LLVM Link Time Optimizer Cache Handling ---------------===//
//
// The LLVM Compiler Infrastructure
//
// This file is distributed under the University of Illinois Open Source
// License. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//
//
// This file implements the Caching for ThinLTO.
//
//===----------------------------------------------------------------------===//
#include "llvm/LTO/Caching.h"
#include "llvm/ADT/StringExtras.h"
#include "llvm/Support/FileSystem.h"
#include "llvm/Support/MemoryBuffer.h"
#include "llvm/Support/Path.h"
#include "llvm/Support/raw_ostream.h"
using namespace llvm;
using namespace llvm::lto;
static void commitEntry(StringRef TempFilename, StringRef EntryPath) {
// Rename to final destination (hopefully race condition won't matter here)
auto EC = sys::fs::rename(TempFilename, EntryPath);
if (EC) {
// Renaming failed, probably not the same filesystem, copy and delete.
// FIXME: Avoid needing to do this by creating the temporary file in the
// cache directory.
{
auto ReloadedBufferOrErr = MemoryBuffer::getFile(TempFilename);
if (auto EC = ReloadedBufferOrErr.getError())
report_fatal_error(Twine("Failed to open temp file '") + TempFilename +
"': " + EC.message() + "\n");
raw_fd_ostream OS(EntryPath, EC, sys::fs::F_None);
if (EC)
report_fatal_error(Twine("Failed to open ") + EntryPath +
" to save cached entry\n");
// I'm not sure what are the guarantee if two processes are doing this
// at the same time.
OS << (*ReloadedBufferOrErr)->getBuffer();
}
sys::fs::remove(TempFilename);
}
}
Expected<NativeObjectCache> lto::localCache(StringRef CacheDirectoryPath,
AddFileFn AddFile) {
if (std::error_code EC = sys::fs::create_directories(CacheDirectoryPath))
return errorCodeToError(EC);
return [=](unsigned Task, StringRef Key) -> AddStreamFn {
// First, see if we have a cache hit.
SmallString<64> EntryPath;
sys::path::append(EntryPath, CacheDirectoryPath, Key);
if (sys::fs::exists(EntryPath)) {
AddFile(Task, EntryPath);
return AddStreamFn();
}
// This native object stream is responsible for commiting the resulting
// file to the cache and calling AddFile to add it to the link.
struct CacheStream : NativeObjectStream {
AddFileFn AddFile;
std::string TempFilename;
std::string EntryPath;
unsigned Task;
CacheStream(std::unique_ptr<raw_pwrite_stream> OS, AddFileFn AddFile,
std::string TempFilename, std::string EntryPath,
unsigned Task)
: NativeObjectStream(std::move(OS)), AddFile(std::move(AddFile)),
TempFilename(std::move(TempFilename)),
EntryPath(std::move(EntryPath)), Task(Task) {}
~CacheStream() {
// Make sure the file is closed before committing it.
OS.reset();
commitEntry(TempFilename, EntryPath);
AddFile(Task, EntryPath);
}
};
return [=](size_t Task) -> std::unique_ptr<NativeObjectStream> {
// Write to a temporary to avoid race condition
int TempFD;
SmallString<64> TempFilename;
std::error_code EC =
sys::fs::createTemporaryFile("Thin", "tmp.o", TempFD, TempFilename);
if (EC) {
errs() << "Error: " << EC.message() << "\n";
report_fatal_error("ThinLTO: Can't get a temporary file");
}
// This CacheStream will move the temporary file into the cache when done.
return llvm::make_unique<CacheStream>(
llvm::make_unique<raw_fd_ostream>(TempFD, /* ShouldClose */ true),
AddFile, TempFilename.str(), EntryPath.str(), Task);
};
};
}
<commit_msg>LTO: Create temporary cache files in the cache directory instead of $TMPDIR.<commit_after>//===-Caching.cpp - LLVM Link Time Optimizer Cache Handling ---------------===//
//
// The LLVM Compiler Infrastructure
//
// This file is distributed under the University of Illinois Open Source
// License. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//
//
// This file implements the Caching for ThinLTO.
//
//===----------------------------------------------------------------------===//
#include "llvm/LTO/Caching.h"
#include "llvm/ADT/StringExtras.h"
#include "llvm/Support/FileSystem.h"
#include "llvm/Support/MemoryBuffer.h"
#include "llvm/Support/Path.h"
#include "llvm/Support/raw_ostream.h"
using namespace llvm;
using namespace llvm::lto;
Expected<NativeObjectCache> lto::localCache(StringRef CacheDirectoryPath,
AddFileFn AddFile) {
if (std::error_code EC = sys::fs::create_directories(CacheDirectoryPath))
return errorCodeToError(EC);
return [=](unsigned Task, StringRef Key) -> AddStreamFn {
// First, see if we have a cache hit.
SmallString<64> EntryPath;
sys::path::append(EntryPath, CacheDirectoryPath, Key);
if (sys::fs::exists(EntryPath)) {
AddFile(Task, EntryPath);
return AddStreamFn();
}
// This native object stream is responsible for commiting the resulting
// file to the cache and calling AddFile to add it to the link.
struct CacheStream : NativeObjectStream {
AddFileFn AddFile;
std::string TempFilename;
std::string EntryPath;
unsigned Task;
CacheStream(std::unique_ptr<raw_pwrite_stream> OS, AddFileFn AddFile,
std::string TempFilename, std::string EntryPath,
unsigned Task)
: NativeObjectStream(std::move(OS)), AddFile(std::move(AddFile)),
TempFilename(std::move(TempFilename)),
EntryPath(std::move(EntryPath)), Task(Task) {}
~CacheStream() {
// Make sure the file is closed before committing it.
OS.reset();
// This is atomic on POSIX systems.
if (auto EC = sys::fs::rename(TempFilename, EntryPath))
report_fatal_error(Twine("Failed to rename temporary file ") +
TempFilename + ": " + EC.message() + "\n");
AddFile(Task, EntryPath);
}
};
return [=](size_t Task) -> std::unique_ptr<NativeObjectStream> {
// Write to a temporary to avoid race condition
int TempFD;
SmallString<64> TempFilenameModel, TempFilename;
sys::path::append(TempFilenameModel, CacheDirectoryPath, "Thin-%%%%%%.tmp.o");
std::error_code EC =
sys::fs::createUniqueFile(TempFilenameModel, TempFD, TempFilename,
sys::fs::owner_read | sys::fs::owner_write);
if (EC) {
errs() << "Error: " << EC.message() << "\n";
report_fatal_error("ThinLTO: Can't get a temporary file");
}
// This CacheStream will move the temporary file into the cache when done.
return llvm::make_unique<CacheStream>(
llvm::make_unique<raw_fd_ostream>(TempFD, /* ShouldClose */ true),
AddFile, TempFilename.str(), EntryPath.str(), Task);
};
};
}
<|endoftext|> |
<commit_before>
#include "GuiObject.hpp"
#include "PythonHelpers.h"
int GuiObject::init(PyObject* args, PyObject* kwds) {
// If the GuiObject type has no base set,
// grab _GuiObject from the gui module and set it as the base.
PyTypeObject* const selfType = &GuiObject_Type;
if(selfType->tp_base == NULL || selfType->tp_base == &PyBaseObject_Type) {
uninitTypeObject(selfType);
PyObject* base = modAttrChain("gui", "_GuiObject");
if(!base || PyErr_Occurred()) {
if(PyErr_Occurred())
PyErr_Print();
Py_FatalError("Did not found gui._GuiObject.");
}
if(!PyClass_Check(base))
Py_FatalError("gui._GuiObject is not a class.");
selfType->tp_bases = PyTuple_Pack(1, base);
Py_DECREF(base);
if(PyType_Ready(selfType) < 0)
Py_FatalError("Was not able to reinit type GuiObject.");
}
DefaultSpace = Vec(8,8);
OuterSpace = Vec(8,8);
return 0;
}
PyObject* Vec::asPyObject() const {
PyObject* t = PyTuple_New(2);
if(!t) return NULL;
PyTuple_SET_ITEM(t, 0, PyInt_FromLong(x));
PyTuple_SET_ITEM(t, 1, PyInt_FromLong(y));
return t;
}
PyObject* Autoresize::asPyObject() const {
PyObject* t = PyTuple_New(4);
if(!t) return NULL;
PyTuple_SET_ITEM(t, 0, PyBool_FromLong(x));
PyTuple_SET_ITEM(t, 1, PyBool_FromLong(y));
PyTuple_SET_ITEM(t, 2, PyBool_FromLong(w));
PyTuple_SET_ITEM(t, 3, PyBool_FromLong(h));
return t;
}
bool Vec::initFromPyObject(PyObject* obj) {
if(!PyTuple_Check(obj)) {
PyErr_Format(PyExc_ValueError, "Vec: We expect a tuple");
return false;
}
if(PyTuple_GET_SIZE(obj) != 2) {
PyErr_Format(PyExc_ValueError, "Vec: We expect a tuple with 2 elements");
return false;
}
x = (int)PyInt_AsLong(PyTuple_GET_ITEM(obj, 0));
y = (int)PyInt_AsLong(PyTuple_GET_ITEM(obj, 1));
if(PyErr_Occurred())
return false;
return true;
}
bool Autoresize::initFromPyObject(PyObject* obj) {
if(!PyTuple_Check(obj)) {
PyErr_Format(PyExc_ValueError, "Autoresize: We expect a tuple");
return false;
}
if(PyTuple_GET_SIZE(obj) != 4) {
PyErr_Format(PyExc_ValueError, "Autoresize: We expect a tuple with 4 elements");
return false;
}
x = PyObject_IsTrue(PyTuple_GET_ITEM(obj, 0));
y = PyObject_IsTrue(PyTuple_GET_ITEM(obj, 1));
w = PyObject_IsTrue(PyTuple_GET_ITEM(obj, 2));
h = PyObject_IsTrue(PyTuple_GET_ITEM(obj, 3));
if(PyErr_Occurred())
return false;
return true;
}
static
PyObject* guiObject_method_addChild(PyObject* _self, PyObject* _arg) {
GuiObject* self = (GuiObject*) _self;
if(!PyType_IsSubtype(Py_TYPE(_arg), &GuiObject_Type)) {
PyErr_Format(PyExc_ValueError, "GuiObject.addChild: we expect a GuiObject");
return NULL;
}
GuiObject* arg = (GuiObject*) _arg;
auto func = self->meth_addChild;
if(!func) {
PyErr_Format(PyExc_AttributeError, "GuiObject.addChild: must be specified in subclass");
return NULL;
}
Py_BEGIN_ALLOW_THREADS
func(self, arg);
Py_END_ALLOW_THREADS
Py_INCREF(Py_None);
return Py_None;
}
static PyMethodDef md_addChild = {
"addChild",
guiObject_method_addChild,
METH_O,
NULL
};
static PyObject* returnObj(PyObject* obj) {
if(!obj) obj = Py_None;
Py_INCREF(obj);
return obj;
}
#define _ReturnAttr(attr) { if(strcmp(key, #attr) == 0) return returnObj(attr); }
#define _ReturnAttrVec(attr) { if(strcmp(key, #attr) == 0) return attr.asPyObject(); }
#define _ReturnCustomAttr(attr) { \
if(strcmp(key, #attr) == 0) { \
if(get_ ## attr == 0) { \
PyErr_Format(PyExc_AttributeError, "GuiObject attribute '%.400s' must be specified in subclass", key); \
return NULL; \
} \
PyThreadState *_save = PyEval_SaveThread(); \
auto res = (* get_ ## attr)(this); \
PyEval_RestoreThread(_save); \
return res.asPyObject(); \
} }
PyObject* GuiObject::getattr(const char* key) {
_ReturnAttr(root);
_ReturnAttr(parent);
_ReturnAttr(attr);
_ReturnAttr(nativeGuiObject);
_ReturnAttr(subjectObject);
_ReturnAttrVec(DefaultSpace);
_ReturnAttrVec(OuterSpace);
_ReturnCustomAttr(pos);
_ReturnCustomAttr(size);
_ReturnCustomAttr(innerSize);
_ReturnCustomAttr(autoresize);
if(strcmp(key, "addChild") == 0) {
return PyCFunction_New(&md_addChild, (PyObject*) this);
}
if(strcmp(key, "__dict__") == 0) {
if(!__dict__)
__dict__ = PyDict_New();
if(!__dict__)
return NULL;
return returnObj(__dict__);
}
// Fallthrough to generic getattr. In case we got another base type, this might work.
PyObject* s = PyString_FromString(key);
if(!s) return NULL;
return PyObject_GenericGetAttr((PyObject*) this, s);
}
#define _SetAttr(attr) { \
if(strcmp(key, #attr) == 0) { \
attr = value; \
Py_INCREF(value); \
return 0; \
} }
#define _SetCustomAttr(attr, ValueType) { \
if(strcmp(key, #attr) == 0) { \
if(set_ ## attr == 0) { \
PyErr_Format(PyExc_AttributeError, "GuiObject attribute '%.400s' must be specified in subclass", key); \
return -1; \
} \
ValueType v; \
if(!v.initFromPyObject(value)) \
return -1; \
Py_BEGIN_ALLOW_THREADS \
(* set_ ## attr)(this, v); \
Py_END_ALLOW_THREADS \
return 0; \
} }
int GuiObject::setattr(const char* key, PyObject* value) {
_SetAttr(root);
_SetAttr(parent);
_SetAttr(attr);
_SetAttr(subjectObject);
_SetAttr(nativeGuiObject);
_SetCustomAttr(pos, Vec);
_SetCustomAttr(size, Vec);
_SetCustomAttr(autoresize, Autoresize);
// Fallthrough to generic setattr. In case we got another base type, this might work.
PyObject* s = PyString_FromString(key);
if(!s) return -1;
int ret = PyObject_GenericSetAttr((PyObject*) this, s, value);
Py_XDECREF(s);
return ret;
}
<commit_msg>fix: setattr: handle missing cases<commit_after>
#include "GuiObject.hpp"
#include "PythonHelpers.h"
int GuiObject::init(PyObject* args, PyObject* kwds) {
// If the GuiObject type has no base set,
// grab _GuiObject from the gui module and set it as the base.
PyTypeObject* const selfType = &GuiObject_Type;
if(selfType->tp_base == NULL || selfType->tp_base == &PyBaseObject_Type) {
uninitTypeObject(selfType);
PyObject* base = modAttrChain("gui", "_GuiObject");
if(!base || PyErr_Occurred()) {
if(PyErr_Occurred())
PyErr_Print();
Py_FatalError("Did not found gui._GuiObject.");
}
if(!PyClass_Check(base))
Py_FatalError("gui._GuiObject is not a class.");
selfType->tp_bases = PyTuple_Pack(1, base);
Py_DECREF(base);
if(PyType_Ready(selfType) < 0)
Py_FatalError("Was not able to reinit type GuiObject.");
}
DefaultSpace = Vec(8,8);
OuterSpace = Vec(8,8);
return 0;
}
PyObject* Vec::asPyObject() const {
PyObject* t = PyTuple_New(2);
if(!t) return NULL;
PyTuple_SET_ITEM(t, 0, PyInt_FromLong(x));
PyTuple_SET_ITEM(t, 1, PyInt_FromLong(y));
return t;
}
PyObject* Autoresize::asPyObject() const {
PyObject* t = PyTuple_New(4);
if(!t) return NULL;
PyTuple_SET_ITEM(t, 0, PyBool_FromLong(x));
PyTuple_SET_ITEM(t, 1, PyBool_FromLong(y));
PyTuple_SET_ITEM(t, 2, PyBool_FromLong(w));
PyTuple_SET_ITEM(t, 3, PyBool_FromLong(h));
return t;
}
bool Vec::initFromPyObject(PyObject* obj) {
if(!PyTuple_Check(obj)) {
PyErr_Format(PyExc_ValueError, "Vec: We expect a tuple");
return false;
}
if(PyTuple_GET_SIZE(obj) != 2) {
PyErr_Format(PyExc_ValueError, "Vec: We expect a tuple with 2 elements");
return false;
}
x = (int)PyInt_AsLong(PyTuple_GET_ITEM(obj, 0));
y = (int)PyInt_AsLong(PyTuple_GET_ITEM(obj, 1));
if(PyErr_Occurred())
return false;
return true;
}
bool Autoresize::initFromPyObject(PyObject* obj) {
if(!PyTuple_Check(obj)) {
PyErr_Format(PyExc_ValueError, "Autoresize: We expect a tuple");
return false;
}
if(PyTuple_GET_SIZE(obj) != 4) {
PyErr_Format(PyExc_ValueError, "Autoresize: We expect a tuple with 4 elements");
return false;
}
x = PyObject_IsTrue(PyTuple_GET_ITEM(obj, 0));
y = PyObject_IsTrue(PyTuple_GET_ITEM(obj, 1));
w = PyObject_IsTrue(PyTuple_GET_ITEM(obj, 2));
h = PyObject_IsTrue(PyTuple_GET_ITEM(obj, 3));
if(PyErr_Occurred())
return false;
return true;
}
static
PyObject* guiObject_method_addChild(PyObject* _self, PyObject* _arg) {
GuiObject* self = (GuiObject*) _self;
if(!PyType_IsSubtype(Py_TYPE(_arg), &GuiObject_Type)) {
PyErr_Format(PyExc_ValueError, "GuiObject.addChild: we expect a GuiObject");
return NULL;
}
GuiObject* arg = (GuiObject*) _arg;
auto func = self->meth_addChild;
if(!func) {
PyErr_Format(PyExc_AttributeError, "GuiObject.addChild: must be specified in subclass");
return NULL;
}
Py_BEGIN_ALLOW_THREADS
func(self, arg);
Py_END_ALLOW_THREADS
Py_INCREF(Py_None);
return Py_None;
}
static PyMethodDef md_addChild = {
"addChild",
guiObject_method_addChild,
METH_O,
NULL
};
static PyObject* returnObj(PyObject* obj) {
if(!obj) obj = Py_None;
Py_INCREF(obj);
return obj;
}
#define _ReturnAttr(attr) { if(strcmp(key, #attr) == 0) return returnObj(attr); }
#define _ReturnAttrVec(attr) { if(strcmp(key, #attr) == 0) return attr.asPyObject(); }
#define _ReturnCustomAttr(attr) { \
if(strcmp(key, #attr) == 0) { \
if(get_ ## attr == 0) { \
PyErr_Format(PyExc_AttributeError, "GuiObject attribute '%.400s' must be specified in subclass", key); \
return NULL; \
} \
PyThreadState *_save = PyEval_SaveThread(); \
auto res = (* get_ ## attr)(this); \
PyEval_RestoreThread(_save); \
return res.asPyObject(); \
} }
PyObject* GuiObject::getattr(const char* key) {
_ReturnAttr(root);
_ReturnAttr(parent);
_ReturnAttr(attr);
_ReturnAttr(nativeGuiObject);
_ReturnAttr(subjectObject);
_ReturnAttrVec(DefaultSpace);
_ReturnAttrVec(OuterSpace);
_ReturnCustomAttr(pos);
_ReturnCustomAttr(size);
_ReturnCustomAttr(innerSize);
_ReturnCustomAttr(autoresize);
if(strcmp(key, "addChild") == 0) {
return PyCFunction_New(&md_addChild, (PyObject*) this);
}
if(strcmp(key, "__dict__") == 0) {
if(!__dict__)
__dict__ = PyDict_New();
if(!__dict__)
return NULL;
return returnObj(__dict__);
}
// Fallthrough to generic getattr. In case we got another base type, this might work.
PyObject* s = PyString_FromString(key);
if(!s) return NULL;
return PyObject_GenericGetAttr((PyObject*) this, s);
}
#define _SetAttr(attr) { \
if(strcmp(key, #attr) == 0) { \
attr = value; \
Py_INCREF(value); \
return 0; \
} }
#define _SetAttrVec(attr) { \
if(strcmp(key, #attr) == 0) { \
Vec v; \
if(!v.initFromPyObject(value)) \
return -1; \
attr = v; \
return 0; \
} }
#define _SetCustomAttr(attr, ValueType) { \
if(strcmp(key, #attr) == 0) { \
if(set_ ## attr == 0) { \
PyErr_Format(PyExc_AttributeError, "GuiObject attribute '%.400s' must be specified in subclass", key); \
return -1; \
} \
ValueType v; \
if(!v.initFromPyObject(value)) \
return -1; \
Py_BEGIN_ALLOW_THREADS \
(* set_ ## attr)(this, v); \
Py_END_ALLOW_THREADS \
return 0; \
} }
#define _SetAttr_ErrReadOnly(attr) { \
if(strcmp(key, #attr) == 0) { \
PyErr_Format(PyExc_AttributeError, "GuiObject attribute '%.400s' is readonly", key); \
return -1; \
} }
int GuiObject::setattr(const char* key, PyObject* value) {
_SetAttr(root);
_SetAttr(parent);
_SetAttr(attr);
_SetAttr(subjectObject);
_SetAttr(nativeGuiObject);
_SetAttrVec(DefaultSpace);
_SetAttrVec(OuterSpace);
_SetCustomAttr(pos, Vec);
_SetCustomAttr(size, Vec);
_SetCustomAttr(autoresize, Autoresize);
_SetAttr_ErrReadOnly(innerSize);
_SetAttr_ErrReadOnly(addChild);
// Fallthrough to generic setattr. In case we got another base type, this might work.
PyObject* s = PyString_FromString(key);
if(!s) return -1;
int ret = PyObject_GenericSetAttr((PyObject*) this, s, value);
Py_XDECREF(s);
return ret;
}
<|endoftext|> |
<commit_before>/*
Copyright (c) 2007, Arvid Norberg
All rights reserved.
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions
are met:
* Redistributions of source code must retain the above copyright
notice, this list of conditions and the following disclaimer.
* Redistributions in binary form must reproduce the above copyright
notice, this list of conditions and the following disclaimer in
the documentation and/or other materials provided with the distribution.
* Neither the name of the author nor the names of its
contributors may be used to endorse or promote products derived
from this software without specific prior written permission.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE
LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
POSSIBILITY OF SUCH DAMAGE.
*/
#include "libtorrent/http_connection.hpp"
#include <boost/bind.hpp>
#include <boost/lexical_cast.hpp>
#include <asio/ip/tcp.hpp>
#include <string>
using boost::bind;
namespace libtorrent
{
void http_connection::get(std::string const& url, time_duration timeout)
{
std::string protocol;
std::string hostname;
std::string path;
int port;
boost::tie(protocol, hostname, port, path) = parse_url_components(url);
std::stringstream headers;
headers << "GET " << path << " HTTP/1.0\r\n"
"Host:" << hostname <<
"Connection: close\r\n"
"\r\n\r\n";
sendbuffer = headers.str();
start(hostname, boost::lexical_cast<std::string>(port), timeout);
}
void http_connection::start(std::string const& hostname, std::string const& port
, time_duration timeout)
{
m_timeout = timeout;
m_timer.expires_from_now(m_timeout);
m_timer.async_wait(bind(&http_connection::on_timeout
, boost::weak_ptr<http_connection>(shared_from_this()), _1));
m_called = false;
if (m_sock.is_open() && m_hostname == hostname && m_port == port)
{
m_parser.reset();
asio::async_write(m_sock, asio::buffer(sendbuffer)
, bind(&http_connection::on_write, shared_from_this(), _1));
}
else
{
m_sock.close();
tcp::resolver::query query(hostname, port);
m_resolver.async_resolve(query, bind(&http_connection::on_resolve
, shared_from_this(), _1, _2));
m_hostname = hostname;
m_port = port;
}
}
void http_connection::on_timeout(boost::weak_ptr<http_connection> p
, asio::error_code const& e)
{
if (e == asio::error::operation_aborted) return;
boost::shared_ptr<http_connection> c = p.lock();
if (!c) return;
if (c->m_bottled && c->m_called) return;
if (c->m_last_receive + c->m_timeout < time_now())
{
c->m_called = true;
c->m_handler(asio::error::timed_out, c->m_parser, 0, 0);
return;
}
c->m_timer.expires_at(c->m_last_receive + c->m_timeout);
c->m_timer.async_wait(bind(&http_connection::on_timeout, p, _1));
}
void http_connection::close()
{
m_timer.cancel();
m_limiter_timer.cancel();
m_limiter_timer_active = false;
m_sock.close();
m_hostname.clear();
m_port.clear();
}
void http_connection::on_resolve(asio::error_code const& e
, tcp::resolver::iterator i)
{
if (e)
{
close();
if (m_bottled && m_called) return;
m_called = true;
m_handler(e, m_parser, 0, 0);
return;
}
assert(i != tcp::resolver::iterator());
m_sock.async_connect(*i, boost::bind(&http_connection::on_connect
, shared_from_this(), _1/*, ++i*/));
}
void http_connection::on_connect(asio::error_code const& e
/*, tcp::resolver::iterator i*/)
{
if (!e)
{
m_last_receive = time_now();
asio::async_write(m_sock, asio::buffer(sendbuffer)
, bind(&http_connection::on_write, shared_from_this(), _1));
}
/* else if (i != tcp::resolver::iterator())
{
// The connection failed. Try the next endpoint in the list.
m_sock.close();
m_sock.async_connect(*i, bind(&http_connection::on_connect
, shared_from_this(), _1, ++i));
}
*/ else
{
close();
if (m_bottled && m_called) return;
m_called = true;
m_handler(e, m_parser, 0, 0);
}
}
void http_connection::on_write(asio::error_code const& e)
{
if (e)
{
close();
if (m_bottled && m_called) return;
m_called = true;
m_handler(e, m_parser, 0, 0);
return;
}
std::string().swap(sendbuffer);
m_recvbuffer.resize(4096);
int amount_to_read = m_recvbuffer.size() - m_read_pos;
if (m_rate_limit > 0 && amount_to_read > m_download_quota)
{
amount_to_read = m_download_quota;
if (m_download_quota == 0)
{
if (!m_limiter_timer_active)
on_assign_bandwidth(asio::error_code());
return;
}
}
m_sock.async_read_some(asio::buffer(&m_recvbuffer[0] + m_read_pos
, amount_to_read)
, bind(&http_connection::on_read
, shared_from_this(), _1, _2));
}
void http_connection::on_read(asio::error_code const& e
, std::size_t bytes_transferred)
{
if (m_rate_limit)
{
m_download_quota -= bytes_transferred;
assert(m_download_quota >= 0);
}
if (e == asio::error::eof)
{
close();
if (m_bottled && m_called) return;
m_called = true;
m_handler(asio::error_code(), m_parser, 0, 0);
return;
}
if (e)
{
close();
if (m_bottled && m_called) return;
m_called = true;
m_handler(e, m_parser, 0, 0);
return;
}
m_read_pos += bytes_transferred;
assert(m_read_pos <= int(m_recvbuffer.size()));
if (m_bottled || !m_parser.header_finished())
{
libtorrent::buffer::const_interval rcv_buf(&m_recvbuffer[0]
, &m_recvbuffer[0] + m_read_pos);
m_parser.incoming(rcv_buf);
if (!m_bottled && m_parser.header_finished())
{
if (m_read_pos > m_parser.body_start())
m_handler(e, m_parser, &m_recvbuffer[0] + m_parser.body_start()
, m_read_pos - m_parser.body_start());
m_read_pos = 0;
m_last_receive = time_now();
}
else if (m_bottled && m_parser.finished())
{
m_timer.cancel();
if (m_bottled && m_called) return;
m_called = true;
m_handler(e, m_parser, 0, 0);
}
}
else
{
assert(!m_bottled);
m_handler(e, m_parser, &m_recvbuffer[0], m_read_pos);
m_read_pos = 0;
m_last_receive = time_now();
}
if (int(m_recvbuffer.size()) == m_read_pos)
m_recvbuffer.resize((std::min)(m_read_pos + 2048, 1024*500));
if (m_read_pos == 1024 * 500)
{
close();
if (m_bottled && m_called) return;
m_called = true;
m_handler(asio::error::eof, m_parser, 0, 0);
return;
}
int amount_to_read = m_recvbuffer.size() - m_read_pos;
if (m_rate_limit > 0 && amount_to_read > m_download_quota)
{
amount_to_read = m_download_quota;
if (m_download_quota == 0)
{
if (!m_limiter_timer_active)
on_assign_bandwidth(asio::error_code());
return;
}
}
m_sock.async_read_some(asio::buffer(&m_recvbuffer[0] + m_read_pos
, amount_to_read)
, bind(&http_connection::on_read
, shared_from_this(), _1, _2));
}
void http_connection::on_assign_bandwidth(asio::error_code const& e)
{
if (e == asio::error::operation_aborted
&& m_limiter_timer_active)
{
if (!m_bottled || !m_called)
m_handler(e, m_parser, 0, 0);
}
m_limiter_timer_active = false;
if (e) return;
if (m_download_quota > 0) return;
m_download_quota = m_rate_limit / 4;
int amount_to_read = m_recvbuffer.size() - m_read_pos;
if (amount_to_read > m_download_quota)
amount_to_read = m_download_quota;
m_sock.async_read_some(asio::buffer(&m_recvbuffer[0] + m_read_pos
, amount_to_read)
, bind(&http_connection::on_read
, shared_from_this(), _1, _2));
m_limiter_timer_active = true;
m_limiter_timer.expires_from_now(milliseconds(250));
m_limiter_timer.async_wait(bind(&http_connection::on_assign_bandwidth
, shared_from_this(), _1));
}
void http_connection::rate_limit(int limit)
{
if (!m_limiter_timer_active)
{
m_limiter_timer_active = true;
m_limiter_timer.expires_from_now(milliseconds(250));
m_limiter_timer.async_wait(bind(&http_connection::on_assign_bandwidth
, shared_from_this(), _1));
}
m_rate_limit = limit;
}
}
<commit_msg>fixed issue when aborting an http connection<commit_after>/*
Copyright (c) 2007, Arvid Norberg
All rights reserved.
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions
are met:
* Redistributions of source code must retain the above copyright
notice, this list of conditions and the following disclaimer.
* Redistributions in binary form must reproduce the above copyright
notice, this list of conditions and the following disclaimer in
the documentation and/or other materials provided with the distribution.
* Neither the name of the author nor the names of its
contributors may be used to endorse or promote products derived
from this software without specific prior written permission.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE
LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
POSSIBILITY OF SUCH DAMAGE.
*/
#include "libtorrent/http_connection.hpp"
#include <boost/bind.hpp>
#include <boost/lexical_cast.hpp>
#include <asio/ip/tcp.hpp>
#include <string>
using boost::bind;
namespace libtorrent
{
void http_connection::get(std::string const& url, time_duration timeout)
{
std::string protocol;
std::string hostname;
std::string path;
int port;
boost::tie(protocol, hostname, port, path) = parse_url_components(url);
std::stringstream headers;
headers << "GET " << path << " HTTP/1.0\r\n"
"Host:" << hostname <<
"Connection: close\r\n"
"\r\n\r\n";
sendbuffer = headers.str();
start(hostname, boost::lexical_cast<std::string>(port), timeout);
}
void http_connection::start(std::string const& hostname, std::string const& port
, time_duration timeout)
{
m_timeout = timeout;
m_timer.expires_from_now(m_timeout);
m_timer.async_wait(bind(&http_connection::on_timeout
, boost::weak_ptr<http_connection>(shared_from_this()), _1));
m_called = false;
if (m_sock.is_open() && m_hostname == hostname && m_port == port)
{
m_parser.reset();
asio::async_write(m_sock, asio::buffer(sendbuffer)
, bind(&http_connection::on_write, shared_from_this(), _1));
}
else
{
m_sock.close();
tcp::resolver::query query(hostname, port);
m_resolver.async_resolve(query, bind(&http_connection::on_resolve
, shared_from_this(), _1, _2));
m_hostname = hostname;
m_port = port;
}
}
void http_connection::on_timeout(boost::weak_ptr<http_connection> p
, asio::error_code const& e)
{
if (e == asio::error::operation_aborted) return;
boost::shared_ptr<http_connection> c = p.lock();
if (!c) return;
if (c->m_bottled && c->m_called) return;
if (c->m_last_receive + c->m_timeout < time_now())
{
c->m_called = true;
c->m_handler(asio::error::timed_out, c->m_parser, 0, 0);
return;
}
c->m_timer.expires_at(c->m_last_receive + c->m_timeout);
c->m_timer.async_wait(bind(&http_connection::on_timeout, p, _1));
}
void http_connection::close()
{
m_timer.cancel();
m_limiter_timer.cancel();
m_sock.close();
m_hostname.clear();
m_port.clear();
}
void http_connection::on_resolve(asio::error_code const& e
, tcp::resolver::iterator i)
{
if (e)
{
close();
if (m_bottled && m_called) return;
m_called = true;
m_handler(e, m_parser, 0, 0);
return;
}
assert(i != tcp::resolver::iterator());
m_sock.async_connect(*i, boost::bind(&http_connection::on_connect
, shared_from_this(), _1/*, ++i*/));
}
void http_connection::on_connect(asio::error_code const& e
/*, tcp::resolver::iterator i*/)
{
if (!e)
{
m_last_receive = time_now();
asio::async_write(m_sock, asio::buffer(sendbuffer)
, bind(&http_connection::on_write, shared_from_this(), _1));
}
/* else if (i != tcp::resolver::iterator())
{
// The connection failed. Try the next endpoint in the list.
m_sock.close();
m_sock.async_connect(*i, bind(&http_connection::on_connect
, shared_from_this(), _1, ++i));
}
*/ else
{
close();
if (m_bottled && m_called) return;
m_called = true;
m_handler(e, m_parser, 0, 0);
}
}
void http_connection::on_write(asio::error_code const& e)
{
if (e)
{
close();
if (m_bottled && m_called) return;
m_called = true;
m_handler(e, m_parser, 0, 0);
return;
}
std::string().swap(sendbuffer);
m_recvbuffer.resize(4096);
int amount_to_read = m_recvbuffer.size() - m_read_pos;
if (m_rate_limit > 0 && amount_to_read > m_download_quota)
{
amount_to_read = m_download_quota;
if (m_download_quota == 0)
{
if (!m_limiter_timer_active)
on_assign_bandwidth(asio::error_code());
return;
}
}
m_sock.async_read_some(asio::buffer(&m_recvbuffer[0] + m_read_pos
, amount_to_read)
, bind(&http_connection::on_read
, shared_from_this(), _1, _2));
}
void http_connection::on_read(asio::error_code const& e
, std::size_t bytes_transferred)
{
if (m_rate_limit)
{
m_download_quota -= bytes_transferred;
assert(m_download_quota >= 0);
}
if (e == asio::error::eof)
{
close();
if (m_bottled && m_called) return;
m_called = true;
m_handler(asio::error_code(), m_parser, 0, 0);
return;
}
if (e)
{
close();
if (m_bottled && m_called) return;
m_called = true;
m_handler(e, m_parser, 0, 0);
return;
}
m_read_pos += bytes_transferred;
assert(m_read_pos <= int(m_recvbuffer.size()));
if (m_bottled || !m_parser.header_finished())
{
libtorrent::buffer::const_interval rcv_buf(&m_recvbuffer[0]
, &m_recvbuffer[0] + m_read_pos);
m_parser.incoming(rcv_buf);
if (!m_bottled && m_parser.header_finished())
{
if (m_read_pos > m_parser.body_start())
m_handler(e, m_parser, &m_recvbuffer[0] + m_parser.body_start()
, m_read_pos - m_parser.body_start());
m_read_pos = 0;
m_last_receive = time_now();
}
else if (m_bottled && m_parser.finished())
{
m_timer.cancel();
if (m_bottled && m_called) return;
m_called = true;
m_handler(e, m_parser, 0, 0);
}
}
else
{
assert(!m_bottled);
m_handler(e, m_parser, &m_recvbuffer[0], m_read_pos);
m_read_pos = 0;
m_last_receive = time_now();
}
if (int(m_recvbuffer.size()) == m_read_pos)
m_recvbuffer.resize((std::min)(m_read_pos + 2048, 1024*500));
if (m_read_pos == 1024 * 500)
{
close();
if (m_bottled && m_called) return;
m_called = true;
m_handler(asio::error::eof, m_parser, 0, 0);
return;
}
int amount_to_read = m_recvbuffer.size() - m_read_pos;
if (m_rate_limit > 0 && amount_to_read > m_download_quota)
{
amount_to_read = m_download_quota;
if (m_download_quota == 0)
{
if (!m_limiter_timer_active)
on_assign_bandwidth(asio::error_code());
return;
}
}
m_sock.async_read_some(asio::buffer(&m_recvbuffer[0] + m_read_pos
, amount_to_read)
, bind(&http_connection::on_read
, shared_from_this(), _1, _2));
}
void http_connection::on_assign_bandwidth(asio::error_code const& e)
{
if ((e == asio::error::operation_aborted
&& m_limiter_timer_active)
|| !m_sock.is_open())
{
if (!m_bottled || !m_called)
m_handler(e, m_parser, 0, 0);
}
m_limiter_timer_active = false;
if (e) return;
if (m_download_quota > 0) return;
m_download_quota = m_rate_limit / 4;
int amount_to_read = m_recvbuffer.size() - m_read_pos;
if (amount_to_read > m_download_quota)
amount_to_read = m_download_quota;
m_sock.async_read_some(asio::buffer(&m_recvbuffer[0] + m_read_pos
, amount_to_read)
, bind(&http_connection::on_read
, shared_from_this(), _1, _2));
m_limiter_timer_active = true;
m_limiter_timer.expires_from_now(milliseconds(250));
m_limiter_timer.async_wait(bind(&http_connection::on_assign_bandwidth
, shared_from_this(), _1));
}
void http_connection::rate_limit(int limit)
{
if (!m_limiter_timer_active)
{
m_limiter_timer_active = true;
m_limiter_timer.expires_from_now(milliseconds(250));
m_limiter_timer.async_wait(bind(&http_connection::on_assign_bandwidth
, shared_from_this(), _1));
}
m_rate_limit = limit;
}
}
<|endoftext|> |
<commit_before>// Copyright (c) 2015, Matthew Malensek.
// Distributed under the BSD 2-Clause License (see LICENSE.txt for details)
#include "SkinManager.h"
#include "Shlwapi.h"
#include "../Error.h"
#include "../Settings.h"
#include "ErrorSkin.h"
#include "MeterComponent.h"
#include "OSDComponent.h"
#include "Skin.h"
#include "SkinV2.h"
#include "SkinV3.h"
#include "SliderComponent.h"
SkinManager *SkinManager::instance;
SkinManager *SkinManager::Instance() {
if (instance == NULL) {
instance = new SkinManager();
}
return instance;
}
void SkinManager::LoadSkin(std::wstring skinXML) {
DisposeComponents();
/* First, make sure the skin directory exists. */
Settings *settings = Settings::Instance();
std::wstring skinDir = settings->SkinDir();
if (PathFileExists(skinDir.c_str()) == FALSE) {
Error::ErrorMessageDie(Error::SKINERR_SKINDIR, skinDir);
}
Skin *skin;
SkinInfo info(skinXML, false);
if (info.FormatVersion() == 2) {
skin = new SkinV2(skinXML);
} else {
skin = new SkinV3(skinXML);
}
std::vector<Skin *> skins;
skins.push_back(skin);
skins.push_back(new SkinV3(settings->SkinXML(L"Classic")));
skins.push_back(new ErrorSkin());
for (Skin *skin : skins) {
if (_volumeOSD == nullptr) {
_volumeOSD = skin->VolumeOSD();
}
if (_volumeIconset.size() == 0) {
_volumeIconset = skin->VolumeIconset();
}
if (_volumeSlider == nullptr) {
_volumeSlider = skin->VolumeSlider();
}
if (_muteOSD == nullptr) {
_muteOSD = skin->MuteOSD();
}
if (_ejectOSD == nullptr) {
_ejectOSD = skin->EjectOSD();
}
if (_ejectIcon == nullptr) {
_ejectIcon = skin->EjectIcon();
}
if (_brightnessOSD == nullptr) {
_brightnessOSD = skin->BrightnessOSD();
}
}
for (Skin *skin : skins) {
delete skin;
}
}
OSDComponent *SkinManager::VolumeOSD() {
return _volumeOSD;
}
std::vector<HICON> &SkinManager::VolumeIconset() {
return _volumeIconset;
}
SliderComponent *SkinManager::VolumeSlider() {
return _volumeSlider;
}
OSDComponent *SkinManager::MuteOSD() {
return _muteOSD;
}
OSDComponent *SkinManager::EjectOSD() {
return _ejectOSD;
}
HICON &SkinManager::EjectIcon() {
return _ejectIcon;
}
OSDComponent * SkinManager::BrightnessOSD() {
return _brightnessOSD;
}
SkinManager::~SkinManager() {
DisposeComponents();
}
void SkinManager::DisposeComponents() {
delete _volumeOSD;
_volumeOSD = NULL;
for (HICON icon : _volumeIconset) {
DestroyIcon(icon);
}
_volumeIconset.clear();
delete _volumeSlider;
_volumeSlider = NULL;
delete _muteOSD;
_muteOSD = NULL;
delete _ejectOSD;
_ejectOSD = NULL;
DestroyIcon(_ejectIcon);
delete _brightnessOSD;
_brightnessOSD = NULL;
}<commit_msg>Fix invisible eject icon bug<commit_after>// Copyright (c) 2015, Matthew Malensek.
// Distributed under the BSD 2-Clause License (see LICENSE.txt for details)
#include "SkinManager.h"
#include "Shlwapi.h"
#include "../Error.h"
#include "../Settings.h"
#include "ErrorSkin.h"
#include "MeterComponent.h"
#include "OSDComponent.h"
#include "Skin.h"
#include "SkinV2.h"
#include "SkinV3.h"
#include "SliderComponent.h"
SkinManager *SkinManager::instance;
SkinManager *SkinManager::Instance() {
if (instance == NULL) {
instance = new SkinManager();
}
return instance;
}
void SkinManager::LoadSkin(std::wstring skinXML) {
DisposeComponents();
/* First, make sure the skin directory exists. */
Settings *settings = Settings::Instance();
std::wstring skinDir = settings->SkinDir();
if (PathFileExists(skinDir.c_str()) == FALSE) {
Error::ErrorMessageDie(Error::SKINERR_SKINDIR, skinDir);
}
Skin *skin;
SkinInfo info(skinXML, false);
if (info.FormatVersion() == 2) {
skin = new SkinV2(skinXML);
} else {
skin = new SkinV3(skinXML);
}
std::vector<Skin *> skins;
skins.push_back(skin);
skins.push_back(new SkinV3(settings->SkinXML(L"Classic")));
skins.push_back(new ErrorSkin());
for (Skin *skin : skins) {
if (_volumeOSD == nullptr) {
_volumeOSD = skin->VolumeOSD();
}
if (_volumeIconset.size() == 0) {
_volumeIconset = skin->VolumeIconset();
}
if (_volumeSlider == nullptr) {
_volumeSlider = skin->VolumeSlider();
}
if (_muteOSD == nullptr) {
_muteOSD = skin->MuteOSD();
}
if (_ejectOSD == nullptr) {
_ejectOSD = skin->EjectOSD();
}
if (_ejectIcon == nullptr) {
_ejectIcon = skin->EjectIcon();
}
if (_brightnessOSD == nullptr) {
_brightnessOSD = skin->BrightnessOSD();
}
}
for (Skin *skin : skins) {
delete skin;
}
}
OSDComponent *SkinManager::VolumeOSD() {
return _volumeOSD;
}
std::vector<HICON> &SkinManager::VolumeIconset() {
return _volumeIconset;
}
SliderComponent *SkinManager::VolumeSlider() {
return _volumeSlider;
}
OSDComponent *SkinManager::MuteOSD() {
return _muteOSD;
}
OSDComponent *SkinManager::EjectOSD() {
return _ejectOSD;
}
HICON &SkinManager::EjectIcon() {
return _ejectIcon;
}
OSDComponent * SkinManager::BrightnessOSD() {
return _brightnessOSD;
}
SkinManager::~SkinManager() {
DisposeComponents();
}
void SkinManager::DisposeComponents() {
delete _volumeOSD;
_volumeOSD = NULL;
for (HICON icon : _volumeIconset) {
DestroyIcon(icon);
}
_volumeIconset.clear();
delete _volumeSlider;
_volumeSlider = NULL;
delete _muteOSD;
_muteOSD = NULL;
delete _ejectOSD;
_ejectOSD = NULL;
DestroyIcon(_ejectIcon);
_ejectIcon = nullptr;
delete _brightnessOSD;
_brightnessOSD = NULL;
}<|endoftext|> |
<commit_before>/**
* For conditions of distribution and use, see copyright notice in license.txt
*
* @file UiService.cpp
* @brief Light-weight UI service. Implements UiServiceInterface and provides
* means of embedding Qt widgets to the same scene/canvas as the 3D in-world
* view. Uses only one UI scene for everything.
*/
#include "StableHeaders.h"
#include "DebugOperatorNew.h"
#include "AssetAPI.h"
#include "UiService.h"
#include "UiProxyWidget.h"
#include "MemoryLeakCheck.h"
#include "LoggingFunctions.h"
#include "BinaryAsset.h"
#include <QDomDocument>
#include <QUiLoader>
#include <QDebug>
DEFINE_POCO_LOGGING_FUNCTIONS("UiService")
UiService::UiService(Foundation::Framework *framework, QGraphicsView *view)
:view_(view),
scene_(view->scene()),
framework_(framework)
{
assert(view_);
assert(scene_);
connect(scene_, SIGNAL(sceneRectChanged(const QRectF &)), SLOT(SceneRectChanged(const QRectF &)));
}
UiService::~UiService()
{
}
UiProxyWidget *UiService::AddWidgetToScene(QWidget *widget, Qt::WindowFlags flags)
{
if (!widget)
{
LogError("UiService::AddWidgetToScene called with a null proxywidget!");
return 0;
}
/* QGraphicsProxyWidget maintains symmetry for the following states:
* state, enabled, visible, geometry, layoutDirection, style, palette,
* font, cursor, sizeHint, getContentsMargins and windowTitle
*/
UiProxyWidget *proxy = new UiProxyWidget(widget, flags);
assert(proxy->widget() == widget);
// Synchronize windowState flags
proxy->widget()->setWindowState(widget->windowState());
AddWidgetToScene(proxy);
// If the widget has WA_DeleteOnClose on, connect its proxy's visibleChanged()
// signal to a slot which handles the deletion. This must be done because closing
// proxy window in our system doesn't yield closeEvent, but hideEvent instead.
if (widget->testAttribute(Qt::WA_DeleteOnClose))
connect(proxy, SIGNAL(visibleChanged()), SLOT(DeleteCallingWidgetOnClose()));
return proxy;
}
bool UiService::AddProxyWidgetToScene(UiProxyWidget *proxy) { return AddWidgetToScene(proxy); }
bool UiService::AddWidgetToScene(UiProxyWidget *widget)
{
if (!widget)
{
LogError("UiService::AddWidgetToScene called with a null proxywidget!");
return false;
}
if (!widget->widget())
{
LogError("UiService::AddWidgetToScene called for proxywidget that does not embed a widget!");
return false;
}
if (widgets_.contains(widget))
{
LogWarning("UiService::AddWidgetToScene: Scene already contains the given widget!");
return false;
}
QObject::connect(widget, SIGNAL(destroyed(QObject *)), this, SLOT(OnProxyDestroyed(QObject *)));
widgets_.append(widget);
if (widget->isVisible())
widget->hide();
// If no position has been set for Qt::Dialog widget, use default one so that the window's title
// bar - or any other critical part, doesn't go outside the view.
if ((widget->windowFlags() & Qt::Dialog) && widget->pos() == QPointF() && !(widget->widget()->windowState() & Qt::WindowFullScreen))
widget->setPos(10.0, 200.0);
// Resize full screen widgets to fit the scene rect.
if (widget->widget()->windowState() & Qt::WindowFullScreen)
{
fullScreenWidgets_ << widget;
widget->setGeometry(scene_->sceneRect().toRect());
}
scene_->addItem(widget);
return true;
}
void UiService::AddWidgetToMenu(QWidget *widget)
{
}
void UiService::AddWidgetToMenu(QWidget *widget, const QString &entry, const QString &menu, const QString &icon)
{
}
void UiService::AddWidgetToMenu(UiProxyWidget *widget, const QString &entry, const QString &menu, const QString &icon)
{
}
void UiService::RemoveWidgetFromScene(QWidget *widget)
{
if (!widget)
return;
if (scene_)
scene_->removeItem(widget->graphicsProxyWidget());
widgets_.removeOne(widget->graphicsProxyWidget());
fullScreenWidgets_.removeOne(widget->graphicsProxyWidget());
}
void UiService::RemoveWidgetFromScene(QGraphicsProxyWidget *widget)
{
if (!widget)
return;
if (scene_)
scene_->removeItem(widget);
widgets_.removeOne(widget);
fullScreenWidgets_.removeOne(widget);
}
void UiService::OnProxyDestroyed(QObject* obj)
{
// Make sure we don't get dangling pointers
// Note: at this point it's a QObject, not a QGraphicsProxyWidget anymore
QGraphicsProxyWidget* proxy = static_cast<QGraphicsProxyWidget*>(obj);
widgets_.removeOne(proxy);
fullScreenWidgets_.removeOne(proxy);
}
QByteArray UiService::UpdateAssetPaths(const QByteArray& data)
{
QDomDocument document;
QString str;
if ( document.setContent(data) )
{
AssetAPI *assetAPI = framework_->Asset();
str = document.toString();
while(str.contains("local://", Qt::CaseInsensitive) || str.contains("file://", Qt::CaseInsensitive))
{
int sIndex = str.indexOf("local://",0,Qt::CaseInsensitive);
if ( sIndex == -1 )
{
sIndex = str.indexOf("file://", 0, Qt::CaseInsensitive);
if ( sIndex == -1)
break;
}
int eIndex = 0;
int i = str.size();
for (i = sIndex; i < str.size(); ++i )
{
if ( QString(str[i]) == QString(")") || QString(str[i]) == QString("<") )
{
eIndex = i;
break;
}
}
if ( i < str.size())
{
QString name = str.mid(sIndex, eIndex-sIndex);
// Ok we have possible asset candidate check that is it loaded, if it is not loaded assume that currently we have not loaded anything.
AssetPtr asset;
asset = assetAPI->GetAsset(name);
if (!asset)
{
LogError(("UiService::UpdateAssetPaths: Asset \"" + name + "\" is not loaded to the asset system. Call RequestAsset prior to use!").toStdString());
return data;
}
// Get absolute path where this asset is ..
QString fileName = asset->DiskSource();
str.replace(name, fileName);
}
else
{
// We are end-of-file
break;
}
}
// External asset ref (example, http:// or something)
while(str.contains("://", Qt::CaseInsensitive) )
{
int sIndex = str.indexOf("://",0,Qt::CaseInsensitive);
if ( sIndex == -1 )
break;
// Get type
int eIndex = 0;
for (int j = sIndex; j--;)
{
if ( QString(str[j]) == QString("(") || QString(str[j]) == QString(">") )
{
eIndex = j+1;
break;
}
}
int typeSize = sIndex - eIndex;
sIndex = sIndex - typeSize;
QString tmp = str.mid(sIndex, typeSize);
int i = str.size();
for (i = sIndex; i < str.size(); ++i )
{
if ( QString(str[i]) == QString(")") || QString(str[i]) == QString("<") )
{
eIndex = i;
break;
}
}
if ( i < str.size())
{
QString name = str.mid(sIndex, eIndex-sIndex);
// Ok we have possible asset candidate check that is it loaded, if it is not loaded assume that currently we have not loaded anything.
AssetPtr asset;
asset = assetAPI->GetAsset(name);
if (!asset)
{
LogError(("UiService::UpdateAssetPaths: Asset \"" + name + "\" is not loaded to the asset system. Call RequestAsset prior to use!").toStdString());
return data;
}
// Get absolute path where this asset is ..
QString fileName = asset->DiskSource();
str.replace(name, fileName);
}
else
{
// We are end-of-file
break;
}
}
}
else
{
LogError("UiService::UpdateAssetNames given data was not valid xml file");
return data;
}
return str.toUtf8();
}
QWidget *UiService::LoadFromFile(const QString &file_path, bool add_to_scene, QWidget *parent)
{
AssetAPI *assetAPI = framework_->Asset();
QString outPath = "";
AssetPtr asset;
QWidget *widget = 0;
if (AssetAPI::ParseAssetRefType(file_path) != AssetAPI::AssetRefLocalPath)
{
asset = assetAPI->GetAsset(file_path);
if (!asset)
{
LogError(("UiService::LoadFromFile: Asset \"" + file_path + "\" is not loaded to the asset system. Call RequestAsset prior to use!").toStdString());
return 0;
}
BinaryAssetPtr binaryAsset = boost::dynamic_pointer_cast<BinaryAsset>(asset);
if (!binaryAsset)
{
LogError(("UiService::LoadFromFile: Asset \"" + file_path + "\" is not of type BinaryAsset!").toStdString());
return 0;
}
if (binaryAsset->data.size() == 0)
{
LogError(("UiService::LoadFromFile: Asset \"" + file_path + "\" size is zero!").toStdString());
return 0;
}
QByteArray data((char*)&binaryAsset->data[0], binaryAsset->data.size());
// Update asset paths
data = UpdateAssetPaths(data);
QDataStream dataStream(&data, QIODevice::ReadOnly);
QUiLoader loader;
widget = loader.load(dataStream.device(), parent);
}
else // The file is from absolute source location.
{
QFile file(file_path);
QUiLoader loader;
file.open(QFile::ReadOnly);
widget = loader.load(&file, parent);
}
if (!widget)
{
LogError(("UiService::LoadFromFile: Failed to load widget from file \"" + file_path + "\"!").toStdString());
return 0;
}
if (add_to_scene && widget)
AddWidgetToScene(widget);
return widget;
}
void UiService::RemoveWidgetFromMenu(QWidget *widget)
{
}
void UiService::RemoveWidgetFromMenu(QGraphicsProxyWidget *widget)
{
}
void UiService::ShowWidget(QWidget *widget) const
{
if (!widget)
{
LogError("UiService::ShowWidget called on a null widget!");
return;
}
if (widget->graphicsProxyWidget())
widget->graphicsProxyWidget()->show();
else
widget->show();
}
void UiService::HideWidget(QWidget *widget) const
{
if (!widget)
{
LogError("UiService::HideWidget called on a null widget!");
return;
}
if (widget->graphicsProxyWidget())
widget->graphicsProxyWidget()->hide();
else
widget->hide();
}
void UiService::BringWidgetToFront(QWidget *widget) const
{
if (!widget)
{
LogError("UiService::BringWidgetToFront called on a null widget!");
return;
}
ShowWidget(widget);
scene_->setActiveWindow(widget->graphicsProxyWidget());
scene_->setFocusItem(widget->graphicsProxyWidget(), Qt::ActiveWindowFocusReason);
}
void UiService::BringWidgetToFront(QGraphicsProxyWidget *widget) const
{
if (!widget)
{
LogError("UiService::BringWidgetToFront called on a null QGraphicsProxyWidget!");
return;
}
scene_->setActiveWindow(widget);
scene_->setFocusItem(widget, Qt::ActiveWindowFocusReason);
}
void UiService::SceneRectChanged(const QRectF &rect)
{
foreach(QGraphicsProxyWidget *widget, fullScreenWidgets_)
widget->setGeometry(rect);
}
void UiService::DeleteCallingWidgetOnClose()
{
QGraphicsProxyWidget *proxy = dynamic_cast<QGraphicsProxyWidget *>(sender());
if (proxy && !proxy->isVisible())
proxy->deleteLater();
}
<commit_msg>Remove the error prints where they were not rational, tweaked the whole logic to work a little better.<commit_after>/**
* For conditions of distribution and use, see copyright notice in license.txt
*
* @file UiService.cpp
* @brief Light-weight UI service. Implements UiServiceInterface and provides
* means of embedding Qt widgets to the same scene/canvas as the 3D in-world
* view. Uses only one UI scene for everything.
*/
#include "StableHeaders.h"
#include "DebugOperatorNew.h"
#include "AssetAPI.h"
#include "UiService.h"
#include "UiProxyWidget.h"
#include "MemoryLeakCheck.h"
#include "LoggingFunctions.h"
#include "BinaryAsset.h"
#include <QDomDocument>
#include <QUiLoader>
#include <QDebug>
DEFINE_POCO_LOGGING_FUNCTIONS("UiService")
UiService::UiService(Foundation::Framework *framework, QGraphicsView *view)
:view_(view),
scene_(view->scene()),
framework_(framework)
{
assert(view_);
assert(scene_);
connect(scene_, SIGNAL(sceneRectChanged(const QRectF &)), SLOT(SceneRectChanged(const QRectF &)));
}
UiService::~UiService()
{
}
UiProxyWidget *UiService::AddWidgetToScene(QWidget *widget, Qt::WindowFlags flags)
{
if (!widget)
{
LogError("UiService::AddWidgetToScene called with a null proxywidget!");
return 0;
}
/* QGraphicsProxyWidget maintains symmetry for the following states:
* state, enabled, visible, geometry, layoutDirection, style, palette,
* font, cursor, sizeHint, getContentsMargins and windowTitle
*/
UiProxyWidget *proxy = new UiProxyWidget(widget, flags);
assert(proxy->widget() == widget);
// Synchronize windowState flags
proxy->widget()->setWindowState(widget->windowState());
AddWidgetToScene(proxy);
// If the widget has WA_DeleteOnClose on, connect its proxy's visibleChanged()
// signal to a slot which handles the deletion. This must be done because closing
// proxy window in our system doesn't yield closeEvent, but hideEvent instead.
if (widget->testAttribute(Qt::WA_DeleteOnClose))
connect(proxy, SIGNAL(visibleChanged()), SLOT(DeleteCallingWidgetOnClose()));
return proxy;
}
bool UiService::AddProxyWidgetToScene(UiProxyWidget *proxy) { return AddWidgetToScene(proxy); }
bool UiService::AddWidgetToScene(UiProxyWidget *widget)
{
if (!widget)
{
LogError("UiService::AddWidgetToScene called with a null proxywidget!");
return false;
}
if (!widget->widget())
{
LogError("UiService::AddWidgetToScene called for proxywidget that does not embed a widget!");
return false;
}
if (widgets_.contains(widget))
{
LogWarning("UiService::AddWidgetToScene: Scene already contains the given widget!");
return false;
}
QObject::connect(widget, SIGNAL(destroyed(QObject *)), this, SLOT(OnProxyDestroyed(QObject *)));
widgets_.append(widget);
if (widget->isVisible())
widget->hide();
// If no position has been set for Qt::Dialog widget, use default one so that the window's title
// bar - or any other critical part, doesn't go outside the view.
if ((widget->windowFlags() & Qt::Dialog) && widget->pos() == QPointF() && !(widget->widget()->windowState() & Qt::WindowFullScreen))
widget->setPos(10.0, 200.0);
// Resize full screen widgets to fit the scene rect.
if (widget->widget()->windowState() & Qt::WindowFullScreen)
{
fullScreenWidgets_ << widget;
widget->setGeometry(scene_->sceneRect().toRect());
}
scene_->addItem(widget);
return true;
}
void UiService::AddWidgetToMenu(QWidget *widget)
{
}
void UiService::AddWidgetToMenu(QWidget *widget, const QString &entry, const QString &menu, const QString &icon)
{
}
void UiService::AddWidgetToMenu(UiProxyWidget *widget, const QString &entry, const QString &menu, const QString &icon)
{
}
void UiService::RemoveWidgetFromScene(QWidget *widget)
{
if (!widget)
return;
if (scene_)
scene_->removeItem(widget->graphicsProxyWidget());
widgets_.removeOne(widget->graphicsProxyWidget());
fullScreenWidgets_.removeOne(widget->graphicsProxyWidget());
}
void UiService::RemoveWidgetFromScene(QGraphicsProxyWidget *widget)
{
if (!widget)
return;
if (scene_)
scene_->removeItem(widget);
widgets_.removeOne(widget);
fullScreenWidgets_.removeOne(widget);
}
void UiService::OnProxyDestroyed(QObject* obj)
{
// Make sure we don't get dangling pointers
// Note: at this point it's a QObject, not a QGraphicsProxyWidget anymore
QGraphicsProxyWidget* proxy = static_cast<QGraphicsProxyWidget*>(obj);
widgets_.removeOne(proxy);
fullScreenWidgets_.removeOne(proxy);
}
QByteArray UiService::UpdateAssetPaths(const QByteArray& data)
{
QDomDocument document;
QString parseError;
if (!document.setContent(data, &parseError))
{
LogError("Could not process .ui file content, error: " + parseError.toStdString());
return data;
}
AssetAPI *assetAPI = framework_->Asset();
QString str = document.toString();
int fromIndex = 0;
// Check for local:// if not gound check for file://
while(str.contains("local://", Qt::CaseInsensitive) || str.contains("file://", Qt::CaseInsensitive))
{
if (fromIndex > str.size())
break;
int sIndex = str.indexOf("local://", fromIndex, Qt::CaseInsensitive);
if (sIndex == -1)
{
sIndex = str.indexOf("file://", fromIndex, Qt::CaseInsensitive);
if (sIndex == -1)
break;
}
int eIndex = str.size();
for (int i = sIndex; i < str.size(); ++i )
{
QString compareString(str[i]);
if (compareString == ")" || compareString == "<")
{
eIndex = i;
break;
}
}
if (eIndex < str.size())
{
fromIndex = eIndex;
QString name = str.mid(sIndex, eIndex-sIndex);
// Ok we have possible asset candidate check that is it loaded,
// if it is not loaded assume that currently we have not loaded anything.
AssetPtr asset;
asset = assetAPI->GetAsset(name);
if (!asset)
continue;
// Get absolute path where this asset is ..
QString fileName = asset->DiskSource();
str.replace(name, fileName);
}
else
{
// We are end-of-file
break;
}
}
// External asset ref eg http://server.com/mypic.com
fromIndex = 0;
while(str.contains("://", Qt::CaseInsensitive) )
{
int sIndex = str.indexOf("://", fromIndex, Qt::CaseInsensitive);
if (sIndex == -1)
break;
// Get type
int eIndex = 0;
for (int j = sIndex; j--;)
{
QString compareString(str[j]);
if (compareString == "(" || compareString == ">")
{
eIndex = j+1;
break;
}
}
int typeSize = sIndex - eIndex;
sIndex = sIndex - typeSize;
QString tmp = str.mid(sIndex, typeSize);
int i = str.size();
for (i = sIndex; i < str.size(); ++i )
{
QString compareString(str[i]);
if (compareString == ")" || compareString == "<")
{
eIndex = i;
break;
}
}
if (i < str.size())
{
fromIndex = eIndex;
QString name = str.mid(sIndex, eIndex-sIndex);
// Ok we have possible asset candidate check that is it loaded, if it is not loaded assume that currently we have not loaded anything.
AssetPtr asset;
asset = assetAPI->GetAsset(name);
if (!asset)
continue;
// Get absolute path where this asset is ..
QString fileName = asset->DiskSource();
str.replace(name, fileName);
}
else
{
// We are end-of-file
break;
}
}
return str.toUtf8();
}
QWidget *UiService::LoadFromFile(const QString &file_path, bool add_to_scene, QWidget *parent)
{
AssetAPI *assetAPI = framework_->Asset();
QString outPath = "";
AssetPtr asset;
QWidget *widget = 0;
if (AssetAPI::ParseAssetRefType(file_path) != AssetAPI::AssetRefLocalPath)
{
asset = assetAPI->GetAsset(file_path);
if (!asset)
{
LogError(("UiService::LoadFromFile: Asset \"" + file_path + "\" is not loaded to the asset system. Call RequestAsset prior to use!").toStdString());
return 0;
}
BinaryAssetPtr binaryAsset = boost::dynamic_pointer_cast<BinaryAsset>(asset);
if (!binaryAsset)
{
LogError(("UiService::LoadFromFile: Asset \"" + file_path + "\" is not of type BinaryAsset!").toStdString());
return 0;
}
if (binaryAsset->data.size() == 0)
{
LogError(("UiService::LoadFromFile: Asset \"" + file_path + "\" size is zero!").toStdString());
return 0;
}
QByteArray data((char*)&binaryAsset->data[0], binaryAsset->data.size());
// Update asset paths
data = UpdateAssetPaths(data);
QDataStream dataStream(&data, QIODevice::ReadOnly);
QUiLoader loader;
widget = loader.load(dataStream.device(), parent);
}
else // The file is from absolute source location.
{
QFile file(file_path);
QUiLoader loader;
file.open(QFile::ReadOnly);
widget = loader.load(&file, parent);
}
if (!widget)
{
LogError(("UiService::LoadFromFile: Failed to load widget from file \"" + file_path + "\"!").toStdString());
return 0;
}
if (add_to_scene && widget)
AddWidgetToScene(widget);
return widget;
}
void UiService::RemoveWidgetFromMenu(QWidget *widget)
{
}
void UiService::RemoveWidgetFromMenu(QGraphicsProxyWidget *widget)
{
}
void UiService::ShowWidget(QWidget *widget) const
{
if (!widget)
{
LogError("UiService::ShowWidget called on a null widget!");
return;
}
if (widget->graphicsProxyWidget())
widget->graphicsProxyWidget()->show();
else
widget->show();
}
void UiService::HideWidget(QWidget *widget) const
{
if (!widget)
{
LogError("UiService::HideWidget called on a null widget!");
return;
}
if (widget->graphicsProxyWidget())
widget->graphicsProxyWidget()->hide();
else
widget->hide();
}
void UiService::BringWidgetToFront(QWidget *widget) const
{
if (!widget)
{
LogError("UiService::BringWidgetToFront called on a null widget!");
return;
}
ShowWidget(widget);
scene_->setActiveWindow(widget->graphicsProxyWidget());
scene_->setFocusItem(widget->graphicsProxyWidget(), Qt::ActiveWindowFocusReason);
}
void UiService::BringWidgetToFront(QGraphicsProxyWidget *widget) const
{
if (!widget)
{
LogError("UiService::BringWidgetToFront called on a null QGraphicsProxyWidget!");
return;
}
scene_->setActiveWindow(widget);
scene_->setFocusItem(widget, Qt::ActiveWindowFocusReason);
}
void UiService::SceneRectChanged(const QRectF &rect)
{
foreach(QGraphicsProxyWidget *widget, fullScreenWidgets_)
widget->setGeometry(rect);
}
void UiService::DeleteCallingWidgetOnClose()
{
QGraphicsProxyWidget *proxy = dynamic_cast<QGraphicsProxyWidget *>(sender());
if (proxy && !proxy->isVisible())
proxy->deleteLater();
}
<|endoftext|> |
<commit_before>/*
Copyright (c) 2003, Arvid Norberg
All rights reserved.
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions
are met:
* Redistributions of source code must retain the above copyright
notice, this list of conditions and the following disclaimer.
* Redistributions in binary form must reproduce the above copyright
notice, this list of conditions and the following disclaimer in
the documentation and/or other materials provided with the distribution.
* Neither the name of the author nor the names of its
contributors may be used to endorse or promote products derived
from this software without specific prior written permission.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE
LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
POSSIBILITY OF SUCH DAMAGE.
*/
#include "libtorrent/pch.hpp"
#include <cctype>
#include <algorithm>
#ifdef _MSC_VER
#pragma warning(push, 1)
#endif
#include <boost/optional.hpp>
#ifdef _MSC_VER
#pragma warning(pop)
#endif
#include "libtorrent/identify_client.hpp"
#include "libtorrent/fingerprint.hpp"
namespace
{
using namespace libtorrent;
int decode_digit(char c)
{
if (std::isdigit(c)) return c - '0';
return unsigned(c) - 'A' + 10;
}
// takes a peer id and returns a valid boost::optional
// object if the peer id matched the azureus style encoding
// the returned fingerprint contains information about the
// client's id
boost::optional<fingerprint> parse_az_style(const peer_id& id)
{
fingerprint ret("..", 0, 0, 0, 0);
if (id[0] != '-' || !std::isprint(id[1]) || (id[2] < '0')
|| (id[3] < '0') || (id[4] < '0')
|| (id[5] < '0') || (id[6] < '0')
|| id[7] != '-')
return boost::optional<fingerprint>();
ret.name[0] = id[1];
ret.name[1] = id[2];
ret.major_version = decode_digit(id[3]);
ret.minor_version = decode_digit(id[4]);
ret.revision_version = decode_digit(id[5]);
ret.tag_version = decode_digit(id[6]);
return boost::optional<fingerprint>(ret);
}
// checks if a peer id can possibly contain a shadow-style
// identification
boost::optional<fingerprint> parse_shadow_style(const peer_id& id)
{
fingerprint ret("..", 0, 0, 0, 0);
if (!std::isalnum(id[0]))
return boost::optional<fingerprint>();
if (std::equal(id.begin()+4, id.begin()+6, "--"))
{
if ((id[1] < '0') || (id[2] < '0')
|| (id[3] < '0'))
return boost::optional<fingerprint>();
ret.major_version = decode_digit(id[1]);
ret.minor_version = decode_digit(id[2]);
ret.revision_version = decode_digit(id[3]);
}
else
{
if (id[8] != 0 || id[1] > 127 || id[2] > 127 || id[3] > 127)
return boost::optional<fingerprint>();
ret.major_version = id[1];
ret.minor_version = id[2];
ret.revision_version = id[3];
}
ret.name[0] = id[0];
ret.name[1] = 0;
ret.tag_version = 0;
return boost::optional<fingerprint>(ret);
}
// checks if a peer id can possibly contain a mainline-style
// identification
boost::optional<fingerprint> parse_mainline_style(const peer_id& id)
{
char ids[21];
std::copy(id.begin(), id.end(), ids);
ids[20] = 0;
fingerprint ret("..", 0, 0, 0, 0);
ret.name[1] = 0;
ret.tag_version = 0;
if (sscanf(ids, "%c%d-%d-%d--", &ret.name[0], &ret.major_version, &ret.minor_version
, &ret.revision_version) != 4
|| !std::isprint(ret.name[0]))
return boost::optional<fingerprint>();
return boost::optional<fingerprint>(ret);
}
typedef std::pair<char const*, char const*> map_entry;
// only support BitTorrentSpecification
// must be ordered alphabetically
map_entry name_map[] =
{
map_entry("A", "ABC")
, map_entry("AR", "Arctic Torrent")
, map_entry("AX", "BitPump")
, map_entry("AZ", "Azureus")
, map_entry("BB", "BitBuddy")
, map_entry("BC", "BitComet")
, map_entry("BF", "Bitflu")
, map_entry("BG", "btgdaemon")
, map_entry("BR", "BitRocket")
, map_entry("BS", "BTSlave")
, map_entry("BX", "BittorrentX")
, map_entry("CD", "Enhanced CTorrent")
, map_entry("CT", "CTorrent")
, map_entry("DE", "Deluge")
, map_entry("ES", "electric sheep")
, map_entry("HL", "Halite")
, map_entry("KT", "KTorrent")
, map_entry("LK", "Linkage")
, map_entry("LP", "lphant")
, map_entry("LT", "libtorrent")
, map_entry("M", "Mainline")
, map_entry("ML", "MLDonkey")
, map_entry("MO", "Mono Torrent")
, map_entry("MP", "MooPolice")
, map_entry("MT", "Moonlight Torrent")
, map_entry("O", "Osprey Permaseed")
, map_entry("QT", "Qt 4")
, map_entry("R", "Tribler")
, map_entry("S", "Shadow")
, map_entry("SB", "Swiftbit")
, map_entry("SN", "ShareNet")
, map_entry("SS", "SwarmScope")
, map_entry("SZ", "Shareaza")
, map_entry("T", "BitTornado")
, map_entry("TN", "Torrent.NET")
, map_entry("TR", "Transmission")
, map_entry("TS", "TorrentStorm")
, map_entry("U", "UPnP")
, map_entry("UL", "uLeecher")
, map_entry("UT", "MicroTorrent")
, map_entry("XT", "XanTorrent")
, map_entry("XX", "Xtorrent")
, map_entry("ZT", "ZipTorrent")
, map_entry("lt", "libTorrent (libtorrent.rakshasa.no/)")
, map_entry("pX", "pHoeniX")
, map_entry("qB", "qBittorrent")
};
bool compare_first_string(map_entry const& lhs, map_entry const& rhs)
{
return lhs.first[0] < rhs.first[0]
|| ((lhs.first[0] == rhs.first[0]) && (lhs.first[1] < rhs.first[1]));
}
std::string lookup(fingerprint const& f)
{
std::stringstream identity;
const int size = sizeof(name_map)/sizeof(name_map[0]);
map_entry* i =
std::lower_bound(name_map, name_map + size
, map_entry(f.name, ""), &compare_first_string);
#ifndef NDEBUG
for (int i = 1; i < size; ++i)
{
assert(compare_first_string(name_map[i-1]
, name_map[i]));
}
#endif
if (i < name_map + size && std::equal(f.name, f.name + 2, i->first))
identity << i->second;
else
{
identity << f.name[0];
if (f.name[1] != 0) identity << f.name[1];
}
identity << " " << (int)f.major_version
<< "." << (int)f.minor_version
<< "." << (int)f.revision_version;
if (f.name[1] != 0)
identity << "." << (int)f.tag_version;
return identity.str();
}
bool find_string(unsigned char const* id, char const* search)
{
return std::equal(search, search + std::strlen(search), id);
}
}
namespace libtorrent
{
boost::optional<fingerprint> client_fingerprint(peer_id const& p)
{
// look for azureus style id
boost::optional<fingerprint> f;
f = parse_az_style(p);
if (f) return f;
// look for shadow style id
f = parse_shadow_style(p);
if (f) return f;
// look for mainline style id
f = parse_mainline_style(p);
if (f) return f;
return f;
}
std::string identify_client(peer_id const& p)
{
peer_id::const_iterator PID = p.begin();
boost::optional<fingerprint> f;
if (p.is_all_zeros()) return "Unknown";
// ----------------------
// non standard encodings
// ----------------------
if (find_string(PID, "Deadman Walking-")) return "Deadman";
if (find_string(PID + 5, "Azureus")) return "Azureus 2.0.3.2";
if (find_string(PID, "DansClient")) return "XanTorrent";
if (find_string(PID + 4, "btfans")) return "SimpleBT";
if (find_string(PID, "PRC.P---")) return "Bittorrent Plus! II";
if (find_string(PID, "P87.P---")) return "Bittorrent Plus!";
if (find_string(PID, "S587Plus")) return "Bittorrent Plus!";
if (find_string(PID, "martini")) return "Martini Man";
if (find_string(PID, "Plus---")) return "Bittorrent Plus";
if (find_string(PID, "turbobt")) return "TurboBT";
if (find_string(PID, "a00---0")) return "Swarmy";
if (find_string(PID, "a02---0")) return "Swarmy";
if (find_string(PID, "T00---0")) return "Teeweety";
if (find_string(PID, "BTDWV-")) return "Deadman Walking";
if (find_string(PID + 2, "BS")) return "BitSpirit";
if (find_string(PID, "btuga")) return "BTugaXP";
if (find_string(PID, "oernu")) return "BTugaXP";
if (find_string(PID, "Mbrst")) return "Burst!";
if (find_string(PID, "Plus")) return "Plus!";
if (find_string(PID, "-Qt-")) return "Qt";
if (find_string(PID, "exbc")) return "BitComet";
if (find_string(PID, "-G3")) return "G3 Torrent";
if (find_string(PID, "XBT")) return "XBT";
if (find_string(PID, "OP")) return "Opera";
if (find_string(PID, "-BOW") && PID[7] == '-')
return "Bits on Wheels " + std::string(PID + 4, PID + 7);
if (find_string(PID, "eX"))
{
std::string user(PID + 2, PID + 14);
return std::string("eXeem ('") + user.c_str() + "')";
}
if (std::equal(PID, PID + 13, "\0\0\0\0\0\0\0\0\0\0\0\0\x97"))
return "Experimental 3.2.1b2";
if (std::equal(PID, PID + 13, "\0\0\0\0\0\0\0\0\0\0\0\0\0"))
return "Experimental 3.1";
// look for azureus style id
f = parse_az_style(p);
if (f) return lookup(*f);
// look for shadow style id
f = parse_shadow_style(p);
if (f) return lookup(*f);
// look for mainline style id
f = parse_mainline_style(p);
if (f) return lookup(*f);
if (std::equal(PID, PID + 12, "\0\0\0\0\0\0\0\0\0\0\0\0"))
return "Generic";
std::string unknown("Unknown [");
for (peer_id::const_iterator i = p.begin(); i != p.end(); ++i)
{
unknown += std::isprint(*i)?*i:'.';
}
unknown += "]";
return unknown;
}
}
<commit_msg>added new knoen peer-ids<commit_after>/*
Copyright (c) 2003, Arvid Norberg
All rights reserved.
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions
are met:
* Redistributions of source code must retain the above copyright
notice, this list of conditions and the following disclaimer.
* Redistributions in binary form must reproduce the above copyright
notice, this list of conditions and the following disclaimer in
the documentation and/or other materials provided with the distribution.
* Neither the name of the author nor the names of its
contributors may be used to endorse or promote products derived
from this software without specific prior written permission.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE
LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
POSSIBILITY OF SUCH DAMAGE.
*/
#include "libtorrent/pch.hpp"
#include <cctype>
#include <algorithm>
#ifdef _MSC_VER
#pragma warning(push, 1)
#endif
#include <boost/optional.hpp>
#ifdef _MSC_VER
#pragma warning(pop)
#endif
#include "libtorrent/identify_client.hpp"
#include "libtorrent/fingerprint.hpp"
namespace
{
using namespace libtorrent;
int decode_digit(char c)
{
if (std::isdigit(c)) return c - '0';
return unsigned(c) - 'A' + 10;
}
// takes a peer id and returns a valid boost::optional
// object if the peer id matched the azureus style encoding
// the returned fingerprint contains information about the
// client's id
boost::optional<fingerprint> parse_az_style(const peer_id& id)
{
fingerprint ret("..", 0, 0, 0, 0);
if (id[0] != '-' || !std::isprint(id[1]) || (id[2] < '0')
|| (id[3] < '0') || (id[4] < '0')
|| (id[5] < '0') || (id[6] < '0')
|| id[7] != '-')
return boost::optional<fingerprint>();
ret.name[0] = id[1];
ret.name[1] = id[2];
ret.major_version = decode_digit(id[3]);
ret.minor_version = decode_digit(id[4]);
ret.revision_version = decode_digit(id[5]);
ret.tag_version = decode_digit(id[6]);
return boost::optional<fingerprint>(ret);
}
// checks if a peer id can possibly contain a shadow-style
// identification
boost::optional<fingerprint> parse_shadow_style(const peer_id& id)
{
fingerprint ret("..", 0, 0, 0, 0);
if (!std::isalnum(id[0]))
return boost::optional<fingerprint>();
if (std::equal(id.begin()+4, id.begin()+6, "--"))
{
if ((id[1] < '0') || (id[2] < '0')
|| (id[3] < '0'))
return boost::optional<fingerprint>();
ret.major_version = decode_digit(id[1]);
ret.minor_version = decode_digit(id[2]);
ret.revision_version = decode_digit(id[3]);
}
else
{
if (id[8] != 0 || id[1] > 127 || id[2] > 127 || id[3] > 127)
return boost::optional<fingerprint>();
ret.major_version = id[1];
ret.minor_version = id[2];
ret.revision_version = id[3];
}
ret.name[0] = id[0];
ret.name[1] = 0;
ret.tag_version = 0;
return boost::optional<fingerprint>(ret);
}
// checks if a peer id can possibly contain a mainline-style
// identification
boost::optional<fingerprint> parse_mainline_style(const peer_id& id)
{
char ids[21];
std::copy(id.begin(), id.end(), ids);
ids[20] = 0;
fingerprint ret("..", 0, 0, 0, 0);
ret.name[1] = 0;
ret.tag_version = 0;
if (sscanf(ids, "%c%d-%d-%d--", &ret.name[0], &ret.major_version, &ret.minor_version
, &ret.revision_version) != 4
|| !std::isprint(ret.name[0]))
return boost::optional<fingerprint>();
return boost::optional<fingerprint>(ret);
}
typedef std::pair<char const*, char const*> map_entry;
// only support BitTorrentSpecification
// must be ordered alphabetically
map_entry name_map[] =
{
map_entry("A", "ABC")
, map_entry("A~", "Ares")
, map_entry("AG", "Ares")
, map_entry("AR", "Arctic Torrent")
, map_entry("AV", "Avicora")
, map_entry("AX", "BitPump")
, map_entry("AZ", "Azureus")
, map_entry("BB", "BitBuddy")
, map_entry("BC", "BitComet")
, map_entry("BF", "Bitflu")
, map_entry("BG", "BTG")
, map_entry("BR", "BitRocket")
, map_entry("BS", "BTSlave")
, map_entry("BX", "BittorrentX")
, map_entry("CD", "Enhanced CTorrent")
, map_entry("CT", "CTorrent")
, map_entry("DE", "Deluge Torrent")
, map_entry("ES", "electric sheep")
, map_entry("EB", "EBit")
, map_entry("HL", "Halite")
, map_entry("HN", "Hydranode")
, map_entry("KT", "KTorrent")
, map_entry("LK", "Linkage")
, map_entry("LP", "lphant")
, map_entry("LT", "libtorrent")
, map_entry("M", "Mainline")
, map_entry("ML", "MLDonkey")
, map_entry("MO", "Mono Torrent")
, map_entry("MP", "MooPolice")
, map_entry("MT", "Moonlight Torrent")
, map_entry("O", "Osprey Permaseed")
, map_entry("PD", "Pando")
, map_entry("QT", "Qt 4")
, map_entry("R", "Tribler")
, map_entry("S", "Shadow")
, map_entry("S~", "Shareaza (beta)")
, map_entry("SB", "Swiftbit")
, map_entry("SN", "ShareNet")
, map_entry("SS", "SwarmScope")
, map_entry("SZ", "Shareaza")
, map_entry("T", "BitTornado")
, map_entry("TN", "Torrent.NET")
, map_entry("TR", "Transmission")
, map_entry("TS", "TorrentStorm")
, map_entry("TT", "TuoTu")
, map_entry("U", "UPnP")
, map_entry("UL", "uLeecher")
, map_entry("UT", "MicroTorrent")
, map_entry("XT", "XanTorrent")
, map_entry("XX", "Xtorrent")
, map_entry("ZT", "ZipTorrent")
, map_entry("lt", "libTorrent (libtorrent.rakshasa.no/)")
, map_entry("pX", "pHoeniX")
, map_entry("qB", "qBittorrent")
};
bool compare_first_string(map_entry const& lhs, map_entry const& rhs)
{
return lhs.first[0] < rhs.first[0]
|| ((lhs.first[0] == rhs.first[0]) && (lhs.first[1] < rhs.first[1]));
}
std::string lookup(fingerprint const& f)
{
std::stringstream identity;
const int size = sizeof(name_map)/sizeof(name_map[0]);
map_entry* i =
std::lower_bound(name_map, name_map + size
, map_entry(f.name, ""), &compare_first_string);
#ifndef NDEBUG
for (int i = 1; i < size; ++i)
{
assert(compare_first_string(name_map[i-1]
, name_map[i]));
}
#endif
if (i < name_map + size && std::equal(f.name, f.name + 2, i->first))
identity << i->second;
else
{
identity << f.name[0];
if (f.name[1] != 0) identity << f.name[1];
}
identity << " " << (int)f.major_version
<< "." << (int)f.minor_version
<< "." << (int)f.revision_version;
if (f.name[1] != 0)
identity << "." << (int)f.tag_version;
return identity.str();
}
bool find_string(unsigned char const* id, char const* search)
{
return std::equal(search, search + std::strlen(search), id);
}
}
namespace libtorrent
{
boost::optional<fingerprint> client_fingerprint(peer_id const& p)
{
// look for azureus style id
boost::optional<fingerprint> f;
f = parse_az_style(p);
if (f) return f;
// look for shadow style id
f = parse_shadow_style(p);
if (f) return f;
// look for mainline style id
f = parse_mainline_style(p);
if (f) return f;
return f;
}
std::string identify_client(peer_id const& p)
{
peer_id::const_iterator PID = p.begin();
boost::optional<fingerprint> f;
if (p.is_all_zeros()) return "Unknown";
// ----------------------
// non standard encodings
// ----------------------
if (find_string(PID, "Deadman Walking-")) return "Deadman";
if (find_string(PID + 5, "Azureus")) return "Azureus 2.0.3.2";
if (find_string(PID, "DansClient")) return "XanTorrent";
if (find_string(PID + 4, "btfans")) return "SimpleBT";
if (find_string(PID, "PRC.P---")) return "Bittorrent Plus! II";
if (find_string(PID, "P87.P---")) return "Bittorrent Plus!";
if (find_string(PID, "S587Plus")) return "Bittorrent Plus!";
if (find_string(PID, "martini")) return "Martini Man";
if (find_string(PID, "Plus---")) return "Bittorrent Plus";
if (find_string(PID, "turbobt")) return "TurboBT";
if (find_string(PID, "a00---0")) return "Swarmy";
if (find_string(PID, "a02---0")) return "Swarmy";
if (find_string(PID, "T00---0")) return "Teeweety";
if (find_string(PID, "BTDWV-")) return "Deadman Walking";
if (find_string(PID + 2, "BS")) return "BitSpirit";
if (find_string(PID, "btuga")) return "BTugaXP";
if (find_string(PID, "oernu")) return "BTugaXP";
if (find_string(PID, "Mbrst")) return "Burst!";
if (find_string(PID, "Plus")) return "Plus!";
if (find_string(PID, "-Qt-")) return "Qt";
if (find_string(PID, "exbc")) return "BitComet";
if (find_string(PID, "-G3")) return "G3 Torrent";
if (find_string(PID, "XBT")) return "XBT";
if (find_string(PID, "OP")) return "Opera";
if (find_string(PID, "-BOW") && PID[7] == '-')
return "Bits on Wheels " + std::string(PID + 4, PID + 7);
if (find_string(PID, "eX"))
{
std::string user(PID + 2, PID + 14);
return std::string("eXeem ('") + user.c_str() + "')";
}
if (std::equal(PID, PID + 13, "\0\0\0\0\0\0\0\0\0\0\0\0\x97"))
return "Experimental 3.2.1b2";
if (std::equal(PID, PID + 13, "\0\0\0\0\0\0\0\0\0\0\0\0\0"))
return "Experimental 3.1";
// look for azureus style id
f = parse_az_style(p);
if (f) return lookup(*f);
// look for shadow style id
f = parse_shadow_style(p);
if (f) return lookup(*f);
// look for mainline style id
f = parse_mainline_style(p);
if (f) return lookup(*f);
if (std::equal(PID, PID + 12, "\0\0\0\0\0\0\0\0\0\0\0\0"))
return "Generic";
std::string unknown("Unknown [");
for (peer_id::const_iterator i = p.begin(); i != p.end(); ++i)
{
unknown += std::isprint(*i)?*i:'.';
}
unknown += "]";
return unknown;
}
}
<|endoftext|> |
<commit_before>/*
Copyright (c) 2003, Arvid Norberg
All rights reserved.
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions
are met:
* Redistributions of source code must retain the above copyright
notice, this list of conditions and the following disclaimer.
* Redistributions in binary form must reproduce the above copyright
notice, this list of conditions and the following disclaimer in
the documentation and/or other materials provided with the distribution.
* Neither the name of the author nor the names of its
contributors may be used to endorse or promote products derived
from this software without specific prior written permission.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE
LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
POSSIBILITY OF SUCH DAMAGE.
*/
#include <cctype>
#ifdef _MSC_VER
#pragma warning(push, 1)
#endif
#include <boost/optional.hpp>
#ifdef _MSC_VER
#pragma warning(pop)
#endif
#include "libtorrent/identify_client.hpp"
#include "libtorrent/fingerprint.hpp"
#if defined(_MSC_VER) && _MSC_VER < 1300
namespace std
{
using ::isprint;
using ::isdigit;
using ::toupper;
using ::isalnum;
}
#endif
namespace
{
using namespace libtorrent;
int decode_digit(char c)
{
if (std::isdigit(c)) return c - '0';
return std::toupper(c) - 'A' + 10;
}
// takes a peer id and returns a valid boost::optional
// object if the peer id matched the azureus style encoding
// the returned fingerprint contains information about the
// client's id
boost::optional<fingerprint> parse_az_style(const peer_id& id)
{
fingerprint ret("..", 0, 0, 0, 0);
if (id[0] != '-' || !std::isprint(id[1]) || !std::isprint(id[2])
|| !std::isalnum(id[3]) || !std::isalnum(id[4])
|| !std::isalnum(id[5]) || !std::isalnum(id[6])
|| id[7] != '-')
return boost::optional<fingerprint>();
ret.id[0] = id[1];
ret.id[1] = id[2];
ret.major_version = decode_digit(id[3]);
ret.minor_version = decode_digit(id[4]);
ret.revision_version = decode_digit(id[5]);
ret.tag_version = decode_digit(id[6]);
return boost::optional<fingerprint>(ret);
}
// checks if a peer id can possibly contain a shadow-style
// identification
boost::optional<fingerprint> parse_shadow_style(const peer_id& id)
{
fingerprint ret("..", 0, 0, 0, 0);
if (!std::isalnum(id[0]))
return boost::optional<fingerprint>();
if (std::equal(id.begin()+4, id.begin()+8, "----"))
{
if (!std::isalnum(id[1]) || !std::isalnum(id[2])
|| !std::isalnum(id[3]))
return boost::optional<fingerprint>();
ret.major_version = decode_digit(id[1]);
ret.minor_version = decode_digit(id[2]);
ret.revision_version = decode_digit(id[3]);
}
else
{
if (id[8] != 0 || id[1] > 127 || id[2] > 127 || id[3] > 127)
return boost::optional<fingerprint>();
ret.major_version = id[1];
ret.minor_version = id[2];
ret.revision_version = id[3];
}
ret.id[0] = id[0];
ret.id[1] = 0;
ret.tag_version = 0;
return boost::optional<fingerprint>(ret);
}
// checks if a peer id can possibly contain a mainline-style
// identification
boost::optional<fingerprint> parse_mainline_style(const peer_id& id)
{
if (!std::isprint(id[0])
|| !std::isalnum(id[1])
|| id[2] != '-'
|| !std::isalnum(id[3])
|| id[4] != '-'
|| !std::isalnum(id[5])
|| !std::equal(id.begin() + 6, id.begin() + 8, "--"))
return boost::optional<fingerprint>();
fingerprint ret("..", 0, 0, 0, 0);
ret.id[0] = id[0];
ret.id[1] = 0;
ret.major_version = decode_digit(id[1]);
ret.minor_version = decode_digit(id[3]);
ret.revision_version = decode_digit(id[5]);
ret.tag_version = 0;
return boost::optional<fingerprint>(ret);
}
typedef std::pair<char const*, char const*> map_entry;
// only support BitTorrentSpecification
// must be ordered alphabetically
map_entry name_map[] =
{
map_entry("A", "ABC")
, map_entry("AR", "Arctic Torrent")
, map_entry("AZ", "Azureus")
, map_entry("BB", "BitBuddy")
, map_entry("BS", "BTSlave")
, map_entry("BX", "BittorrentX")
, map_entry("CT", "CTorrent")
, map_entry("LT", "libtorrent")
, map_entry("M", "Mainline")
. map_emtry("MP", "MooPolice")
, map_entry("MT", "Moonlight Torrent")
, map_entry("S", "Shadow")
, map_entry("SN", "ShareNet")
, map_entry("SS", "SwarmScope")
, map_entry("T", "BitTornado")
, map_entry("TN", "Torrent.NET")
, map_entry("TS", "TorrentStorm")
, map_entry("U", "UPnP")
, map_entry("XT", "XanTorrent")
, map_entry("ZT", "ZipTorrent")
};
bool compare_first_string(map_entry const& e, char const* str)
{
return e.first[0] < str[0]
|| ((e.first[0] == str[0]) && (e.first[1] < str[1]));
}
std::string lookup(fingerprint const& f)
{
std::stringstream identity;
const int size = sizeof(name_map)/sizeof(name_map[0]);
map_entry* i =
std::lower_bound(name_map, name_map + size
, f.id, &compare_first_string);
if (i < name_map + size && std::equal(f.id, f.id + 2, i->first))
identity << i->second;
else
identity << std::string(f.id, f.id + 2);
identity << " " << (int)f.major_version
<< "." << (int)f.minor_version
<< "." << (int)f.revision_version
<< "." << (int)f.tag_version;
return identity.str();
}
bool find_string(unsigned char const* id, char const* search)
{
return std::equal(search, search + std::strlen(search), id);
}
}
namespace libtorrent
{
std::string identify_client(const peer_id& p)
{
peer_id::const_iterator PID = p.begin();
boost::optional<fingerprint> f;
if (p.is_all_zeros()) return "Unknown";
// ----------------------
// non standard encodings
// ----------------------
if (find_string(PID, "Deadman Walking-")) return "Deadman";
if (find_string(PID + 5, "Azureus")) return "Azureus 2.0.3.2";
if (find_string(PID, "DansClient")) return "XanTorrent";
if (find_string(PID + 4, "btfans")) return "SimpleBT";
if (find_string(PID, "PRC.P---")) return "Bittorrent Plus! II";
if (find_string(PID, "P87.P---")) return "Bittorrent Plus!";
if (find_string(PID, "S587Plus")) return "Bittorrent Plus!";
if (find_string(PID, "martini")) return "Martini Man";
if (find_string(PID, "Plus---")) return "Bittorrent Plus";
if (find_string(PID, "turbobt")) return "TurboBT";
if (find_string(PID, "a00---0")) return "Swarmy";
if (find_string(PID, "a02---0")) return "Swarmy";
if (find_string(PID, "T00---0")) return "Teeweety";
if (find_string(PID, "BTDWV-")) return "Deadman Walking";
if (find_string(PID + 2, "BS")) return "BitSpirit";
if (find_string(PID, "btuga")) return "BTugaXP";
if (find_string(PID, "oernu")) return "BTugaXP";
if (find_string(PID, "Mbrst")) return "Burst!";
if (find_string(PID, "Plus")) return "Plus!";
if (find_string(PID, "exbc")) return "BitComet";
if (find_string(PID, "-G3")) return "G3 Torrent";
if (find_string(PID, "XBT")) return "XBT";
if (find_string(PID, "-BOW") && PID[7] == '-')
return "Bits on Wheels " + std::string(PID + 4, PID + 7);
if (find_string(PID, "eX"))
{
std::string user(PID + 2, PID + 14);
return std::string("eXeem ('") + user.c_str() + "')";
}
if (std::equal(PID, PID + 13, "\0\0\0\0\0\0\0\0\0\0\0\0\x97"))
return "Experimental 3.2.1b2";
if (std::equal(PID, PID + 13, "\0\0\0\0\0\0\0\0\0\0\0\0\0"))
return "Experimental 3.1";
if (p.is_all_zeros()) return "Unknown";
// look for azureus style id
f = parse_az_style(p);
if (f) return lookup(*f);
// look for shadow style id
f = parse_shadow_style(p);
if (f) return lookup(*f);
// look for mainline style id
f = parse_mainline_style(p);
if (f) return lookup(*f);
if (std::equal(PID, PID + 12, "\0\0\0\0\0\0\0\0\0\0\0\0"))
return "Generic";
std::string unknown("Unknown [");
for (peer_id::const_iterator i = p.begin(); i != p.end(); ++i)
{
unknown += std::isprint(*i)?*i:'.';
}
unknown += "]";
return unknown;
}
}
<commit_msg>*** empty log message ***<commit_after>/*
Copyright (c) 2003, Arvid Norberg
All rights reserved.
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions
are met:
* Redistributions of source code must retain the above copyright
notice, this list of conditions and the following disclaimer.
* Redistributions in binary form must reproduce the above copyright
notice, this list of conditions and the following disclaimer in
the documentation and/or other materials provided with the distribution.
* Neither the name of the author nor the names of its
contributors may be used to endorse or promote products derived
from this software without specific prior written permission.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE
LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
POSSIBILITY OF SUCH DAMAGE.
*/
#include <cctype>
#include <algorithm>
#ifdef _MSC_VER
#pragma warning(push, 1)
#endif
#include <boost/optional.hpp>
#ifdef _MSC_VER
#pragma warning(pop)
#endif
#include "libtorrent/identify_client.hpp"
#include "libtorrent/fingerprint.hpp"
#if defined(_MSC_VER) && _MSC_VER < 1300
namespace std
{
using ::isprint;
using ::isdigit;
using ::toupper;
using ::isalnum;
}
#endif
namespace
{
using namespace libtorrent;
int decode_digit(char c)
{
if (std::isdigit(c)) return c - '0';
return std::toupper(c) - 'A' + 10;
}
// takes a peer id and returns a valid boost::optional
// object if the peer id matched the azureus style encoding
// the returned fingerprint contains information about the
// client's id
boost::optional<fingerprint> parse_az_style(const peer_id& id)
{
fingerprint ret("..", 0, 0, 0, 0);
if (id[0] != '-' || !std::isprint(id[1]) || !std::isprint(id[2])
|| !std::isalnum(id[3]) || !std::isalnum(id[4])
|| !std::isalnum(id[5]) || !std::isalnum(id[6])
|| id[7] != '-')
return boost::optional<fingerprint>();
ret.id[0] = id[1];
ret.id[1] = id[2];
ret.major_version = decode_digit(id[3]);
ret.minor_version = decode_digit(id[4]);
ret.revision_version = decode_digit(id[5]);
ret.tag_version = decode_digit(id[6]);
return boost::optional<fingerprint>(ret);
}
// checks if a peer id can possibly contain a shadow-style
// identification
boost::optional<fingerprint> parse_shadow_style(const peer_id& id)
{
fingerprint ret("..", 0, 0, 0, 0);
if (!std::isalnum(id[0]))
return boost::optional<fingerprint>();
if (std::equal(id.begin()+4, id.begin()+8, "----"))
{
if (!std::isalnum(id[1]) || !std::isalnum(id[2])
|| !std::isalnum(id[3]))
return boost::optional<fingerprint>();
ret.major_version = decode_digit(id[1]);
ret.minor_version = decode_digit(id[2]);
ret.revision_version = decode_digit(id[3]);
}
else
{
if (id[8] != 0 || id[1] > 127 || id[2] > 127 || id[3] > 127)
return boost::optional<fingerprint>();
ret.major_version = id[1];
ret.minor_version = id[2];
ret.revision_version = id[3];
}
ret.id[0] = id[0];
ret.id[1] = 0;
ret.tag_version = 0;
return boost::optional<fingerprint>(ret);
}
// checks if a peer id can possibly contain a mainline-style
// identification
boost::optional<fingerprint> parse_mainline_style(const peer_id& id)
{
if (!std::isprint(id[0])
|| !std::isalnum(id[1])
|| id[2] != '-'
|| !std::isalnum(id[3])
|| id[4] != '-'
|| !std::isalnum(id[5])
|| !std::equal(id.begin() + 6, id.begin() + 8, "--"))
return boost::optional<fingerprint>();
fingerprint ret("..", 0, 0, 0, 0);
ret.id[0] = id[0];
ret.id[1] = 0;
ret.major_version = decode_digit(id[1]);
ret.minor_version = decode_digit(id[3]);
ret.revision_version = decode_digit(id[5]);
ret.tag_version = 0;
return boost::optional<fingerprint>(ret);
}
typedef std::pair<char const*, char const*> map_entry;
// only support BitTorrentSpecification
// must be ordered alphabetically
map_entry name_map[] =
{
map_entry("A", "ABC")
, map_entry("AR", "Arctic Torrent")
, map_entry("AZ", "Azureus")
, map_entry("BB", "BitBuddy")
, map_entry("BS", "BTSlave")
, map_entry("BX", "BittorrentX")
, map_entry("CT", "CTorrent")
, map_entry("LT", "libtorrent")
, map_entry("M", "Mainline")
, map_entry("MP", "MooPolice")
, map_entry("MT", "Moonlight Torrent")
, map_entry("S", "Shadow")
, map_entry("SN", "ShareNet")
, map_entry("SS", "SwarmScope")
, map_entry("T", "BitTornado")
, map_entry("TN", "Torrent.NET")
, map_entry("TS", "TorrentStorm")
, map_entry("U", "UPnP")
, map_entry("XT", "XanTorrent")
, map_entry("ZT", "ZipTorrent")
};
bool compare_first_string(map_entry const& e, char const* str)
{
return e.first[0] < str[0]
|| ((e.first[0] == str[0]) && (e.first[1] < str[1]));
}
std::string lookup(fingerprint const& f)
{
std::stringstream identity;
const int size = sizeof(name_map)/sizeof(name_map[0]);
map_entry* i =
std::lower_bound(name_map, name_map + size
, f.id, &compare_first_string);
#ifndef NDEBUG
for (int i = 1; i < size; ++i)
{
assert(compare_first_string(name_map[i-1]
, name_map[i].first));
}
#endif
if (i < name_map + size && std::equal(f.id, f.id + 2, i->first))
identity << i->second;
else
identity << std::string(f.id, f.id + 2);
identity << " " << (int)f.major_version
<< "." << (int)f.minor_version
<< "." << (int)f.revision_version
<< "." << (int)f.tag_version;
return identity.str();
}
bool find_string(unsigned char const* id, char const* search)
{
return std::equal(search, search + std::strlen(search), id);
}
}
namespace libtorrent
{
std::string identify_client(const peer_id& p)
{
peer_id::const_iterator PID = p.begin();
boost::optional<fingerprint> f;
if (p.is_all_zeros()) return "Unknown";
// ----------------------
// non standard encodings
// ----------------------
if (find_string(PID, "Deadman Walking-")) return "Deadman";
if (find_string(PID + 5, "Azureus")) return "Azureus 2.0.3.2";
if (find_string(PID, "DansClient")) return "XanTorrent";
if (find_string(PID + 4, "btfans")) return "SimpleBT";
if (find_string(PID, "PRC.P---")) return "Bittorrent Plus! II";
if (find_string(PID, "P87.P---")) return "Bittorrent Plus!";
if (find_string(PID, "S587Plus")) return "Bittorrent Plus!";
if (find_string(PID, "martini")) return "Martini Man";
if (find_string(PID, "Plus---")) return "Bittorrent Plus";
if (find_string(PID, "turbobt")) return "TurboBT";
if (find_string(PID, "a00---0")) return "Swarmy";
if (find_string(PID, "a02---0")) return "Swarmy";
if (find_string(PID, "T00---0")) return "Teeweety";
if (find_string(PID, "BTDWV-")) return "Deadman Walking";
if (find_string(PID + 2, "BS")) return "BitSpirit";
if (find_string(PID, "btuga")) return "BTugaXP";
if (find_string(PID, "oernu")) return "BTugaXP";
if (find_string(PID, "Mbrst")) return "Burst!";
if (find_string(PID, "Plus")) return "Plus!";
if (find_string(PID, "exbc")) return "BitComet";
if (find_string(PID, "-G3")) return "G3 Torrent";
if (find_string(PID, "XBT")) return "XBT";
if (find_string(PID, "-BOW") && PID[7] == '-')
return "Bits on Wheels " + std::string(PID + 4, PID + 7);
if (find_string(PID, "eX"))
{
std::string user(PID + 2, PID + 14);
return std::string("eXeem ('") + user.c_str() + "')";
}
if (std::equal(PID, PID + 13, "\0\0\0\0\0\0\0\0\0\0\0\0\x97"))
return "Experimental 3.2.1b2";
if (std::equal(PID, PID + 13, "\0\0\0\0\0\0\0\0\0\0\0\0\0"))
return "Experimental 3.1";
// look for azureus style id
f = parse_az_style(p);
if (f) return lookup(*f);
// look for shadow style id
f = parse_shadow_style(p);
if (f) return lookup(*f);
// look for mainline style id
f = parse_mainline_style(p);
if (f) return lookup(*f);
if (std::equal(PID, PID + 12, "\0\0\0\0\0\0\0\0\0\0\0\0"))
return "Generic";
std::string unknown("Unknown [");
for (peer_id::const_iterator i = p.begin(); i != p.end(); ++i)
{
unknown += std::isprint(*i)?*i:'.';
}
unknown += "]";
return unknown;
}
}
<|endoftext|> |
<commit_before>/*
Copyright (c) 2003, Arvid Norberg
All rights reserved.
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions
are met:
* Redistributions of source code must retain the above copyright
notice, this list of conditions and the following disclaimer.
* Redistributions in binary form must reproduce the above copyright
notice, this list of conditions and the following disclaimer in
the documentation and/or other materials provided with the distribution.
* Neither the name of the author nor the names of its
contributors may be used to endorse or promote products derived
from this software without specific prior written permission.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE
LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
POSSIBILITY OF SUCH DAMAGE.
*/
#include <cctype>
#include <algorithm>
#ifdef _MSC_VER
#pragma warning(push, 1)
#endif
#include <boost/optional.hpp>
#ifdef _MSC_VER
#pragma warning(pop)
#endif
#include "libtorrent/identify_client.hpp"
#include "libtorrent/fingerprint.hpp"
namespace
{
using namespace libtorrent;
int decode_digit(char c)
{
if (std::isdigit(c)) return c - '0';
return unsigned(c) - 'A' + 10;
}
// takes a peer id and returns a valid boost::optional
// object if the peer id matched the azureus style encoding
// the returned fingerprint contains information about the
// client's id
boost::optional<fingerprint> parse_az_style(const peer_id& id)
{
fingerprint ret("..", 0, 0, 0, 0);
if (id[0] != '-' || !std::isprint(id[1]) || (id[2] < '0')
|| (id[3] < '0') || (id[4] < '0')
|| (id[5] < '0') || (id[6] < '0')
|| id[7] != '-')
return boost::optional<fingerprint>();
ret.name[0] = id[1];
ret.name[1] = id[2];
ret.major_version = decode_digit(id[3]);
ret.minor_version = decode_digit(id[4]);
ret.revision_version = decode_digit(id[5]);
ret.tag_version = decode_digit(id[6]);
return boost::optional<fingerprint>(ret);
}
// checks if a peer id can possibly contain a shadow-style
// identification
boost::optional<fingerprint> parse_shadow_style(const peer_id& id)
{
fingerprint ret("..", 0, 0, 0, 0);
if (!std::isalnum(id[0]))
return boost::optional<fingerprint>();
if (std::equal(id.begin()+4, id.begin()+6, "--"))
{
if ((id[1] < '0') || (id[2] < '0')
|| (id[3] < '0'))
return boost::optional<fingerprint>();
ret.major_version = decode_digit(id[1]);
ret.minor_version = decode_digit(id[2]);
ret.revision_version = decode_digit(id[3]);
}
else
{
if (id[8] != 0 || id[1] > 127 || id[2] > 127 || id[3] > 127)
return boost::optional<fingerprint>();
ret.major_version = id[1];
ret.minor_version = id[2];
ret.revision_version = id[3];
}
ret.name[0] = id[0];
ret.name[1] = 0;
ret.tag_version = 0;
return boost::optional<fingerprint>(ret);
}
// checks if a peer id can possibly contain a mainline-style
// identification
boost::optional<fingerprint> parse_mainline_style(const peer_id& id)
{
char ids[21];
std::copy(id.begin(), id.end(), ids);
ids[20] = 0;
fingerprint ret("..", 0, 0, 0, 0);
ret.name[1] = 0;
ret.tag_version = 0;
if (sscanf(ids, "%c%d-%d-%d--", &ret.name[0], &ret.major_version, &ret.minor_version
, &ret.revision_version) != 4
|| !std::isprint(ret.name[0]))
return boost::optional<fingerprint>();
return boost::optional<fingerprint>(ret);
}
typedef std::pair<char const*, char const*> map_entry;
// only support BitTorrentSpecification
// must be ordered alphabetically
map_entry name_map[] =
{
map_entry("A", "ABC")
, map_entry("AR", "Arctic Torrent")
, map_entry("AX", "BitPump")
, map_entry("AZ", "Azureus")
, map_entry("BB", "BitBuddy")
, map_entry("BC", "BitComet")
, map_entry("BS", "BTSlave")
, map_entry("BX", "BittorrentX")
, map_entry("CD", "Enhanced CTorrent")
, map_entry("CT", "CTorrent")
, map_entry("ES", "electric sheep")
, map_entry("KT", "KTorrent")
, map_entry("LP", "lphant")
, map_entry("LT", "libtorrent")
, map_entry("M", "Mainline")
, map_entry("MP", "MooPolice")
, map_entry("MT", "Moonlight Torrent")
, map_entry("O", "Osprey Permaseed")
, map_entry("R", "Tribler")
, map_entry("S", "Shadow")
, map_entry("SB", "Swiftbit")
, map_entry("SN", "ShareNet")
, map_entry("SS", "SwarmScope")
, map_entry("SZ", "Shareaza")
, map_entry("T", "BitTornado")
, map_entry("TN", "Torrent.NET")
, map_entry("TR", "Transmission")
, map_entry("TS", "TorrentStorm")
, map_entry("U", "UPnP")
, map_entry("UT", "MicroTorrent")
, map_entry("XT", "XanTorrent")
, map_entry("ZT", "ZipTorrent")
, map_entry("lt", "libTorrent (libtorrent.rakshasa.no/)")
, map_entry("pX", "pHoeniX")
};
bool compare_first_string(map_entry const& lhs, map_entry const& rhs)
{
return lhs.first[0] < rhs.first[0]
|| ((lhs.first[0] == rhs.first[0]) && (lhs.first[1] < rhs.first[1]));
}
std::string lookup(fingerprint const& f)
{
std::stringstream identity;
const int size = sizeof(name_map)/sizeof(name_map[0]);
map_entry* i =
std::lower_bound(name_map, name_map + size
, map_entry(f.name, ""), &compare_first_string);
#ifndef NDEBUG
for (int i = 1; i < size; ++i)
{
assert(compare_first_string(name_map[i-1]
, name_map[i]));
}
#endif
if (i < name_map + size && std::equal(f.name, f.name + 2, i->first))
identity << i->second;
else
{
identity << f.name[0];
if (f.name[1] != 0) identity << f.name[1];
}
identity << " " << (int)f.major_version
<< "." << (int)f.minor_version
<< "." << (int)f.revision_version;
if (f.name[1] != 0)
identity << "." << (int)f.tag_version;
return identity.str();
}
bool find_string(unsigned char const* id, char const* search)
{
return std::equal(search, search + std::strlen(search), id);
}
}
namespace libtorrent
{
boost::optional<fingerprint> client_fingerprint(peer_id const& p)
{
// look for azureus style id
boost::optional<fingerprint> f;
f = parse_az_style(p);
if (f) return f;
// look for shadow style id
f = parse_shadow_style(p);
if (f) return f;
// look for mainline style id
f = parse_mainline_style(p);
if (f) return f;
return f;
}
std::string identify_client(peer_id const& p)
{
peer_id::const_iterator PID = p.begin();
boost::optional<fingerprint> f;
if (p.is_all_zeros()) return "Unknown";
// ----------------------
// non standard encodings
// ----------------------
if (find_string(PID, "Deadman Walking-")) return "Deadman";
if (find_string(PID + 5, "Azureus")) return "Azureus 2.0.3.2";
if (find_string(PID, "DansClient")) return "XanTorrent";
if (find_string(PID + 4, "btfans")) return "SimpleBT";
if (find_string(PID, "PRC.P---")) return "Bittorrent Plus! II";
if (find_string(PID, "P87.P---")) return "Bittorrent Plus!";
if (find_string(PID, "S587Plus")) return "Bittorrent Plus!";
if (find_string(PID, "martini")) return "Martini Man";
if (find_string(PID, "Plus---")) return "Bittorrent Plus";
if (find_string(PID, "turbobt")) return "TurboBT";
if (find_string(PID, "a00---0")) return "Swarmy";
if (find_string(PID, "a02---0")) return "Swarmy";
if (find_string(PID, "T00---0")) return "Teeweety";
if (find_string(PID, "BTDWV-")) return "Deadman Walking";
if (find_string(PID + 2, "BS")) return "BitSpirit";
if (find_string(PID, "btuga")) return "BTugaXP";
if (find_string(PID, "oernu")) return "BTugaXP";
if (find_string(PID, "Mbrst")) return "Burst!";
if (find_string(PID, "Plus")) return "Plus!";
if (find_string(PID, "-Qt-")) return "Qt";
if (find_string(PID, "exbc")) return "BitComet";
if (find_string(PID, "-G3")) return "G3 Torrent";
if (find_string(PID, "XBT")) return "XBT";
if (find_string(PID, "OP")) return "Opera";
if (find_string(PID, "-BOW") && PID[7] == '-')
return "Bits on Wheels " + std::string(PID + 4, PID + 7);
if (find_string(PID, "eX"))
{
std::string user(PID + 2, PID + 14);
return std::string("eXeem ('") + user.c_str() + "')";
}
if (std::equal(PID, PID + 13, "\0\0\0\0\0\0\0\0\0\0\0\0\x97"))
return "Experimental 3.2.1b2";
if (std::equal(PID, PID + 13, "\0\0\0\0\0\0\0\0\0\0\0\0\0"))
return "Experimental 3.1";
// look for azureus style id
f = parse_az_style(p);
if (f) return lookup(*f);
// look for shadow style id
f = parse_shadow_style(p);
if (f) return lookup(*f);
// look for mainline style id
f = parse_mainline_style(p);
if (f) return lookup(*f);
if (std::equal(PID, PID + 12, "\0\0\0\0\0\0\0\0\0\0\0\0"))
return "Generic";
std::string unknown("Unknown [");
for (peer_id::const_iterator i = p.begin(); i != p.end(); ++i)
{
unknown += std::isprint(*i)?*i:'.';
}
unknown += "]";
return unknown;
}
}
<commit_msg>added uLeacher and qBittorrent<commit_after>/*
Copyright (c) 2003, Arvid Norberg
All rights reserved.
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions
are met:
* Redistributions of source code must retain the above copyright
notice, this list of conditions and the following disclaimer.
* Redistributions in binary form must reproduce the above copyright
notice, this list of conditions and the following disclaimer in
the documentation and/or other materials provided with the distribution.
* Neither the name of the author nor the names of its
contributors may be used to endorse or promote products derived
from this software without specific prior written permission.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE
LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
POSSIBILITY OF SUCH DAMAGE.
*/
#include <cctype>
#include <algorithm>
#ifdef _MSC_VER
#pragma warning(push, 1)
#endif
#include <boost/optional.hpp>
#ifdef _MSC_VER
#pragma warning(pop)
#endif
#include "libtorrent/identify_client.hpp"
#include "libtorrent/fingerprint.hpp"
namespace
{
using namespace libtorrent;
int decode_digit(char c)
{
if (std::isdigit(c)) return c - '0';
return unsigned(c) - 'A' + 10;
}
// takes a peer id and returns a valid boost::optional
// object if the peer id matched the azureus style encoding
// the returned fingerprint contains information about the
// client's id
boost::optional<fingerprint> parse_az_style(const peer_id& id)
{
fingerprint ret("..", 0, 0, 0, 0);
if (id[0] != '-' || !std::isprint(id[1]) || (id[2] < '0')
|| (id[3] < '0') || (id[4] < '0')
|| (id[5] < '0') || (id[6] < '0')
|| id[7] != '-')
return boost::optional<fingerprint>();
ret.name[0] = id[1];
ret.name[1] = id[2];
ret.major_version = decode_digit(id[3]);
ret.minor_version = decode_digit(id[4]);
ret.revision_version = decode_digit(id[5]);
ret.tag_version = decode_digit(id[6]);
return boost::optional<fingerprint>(ret);
}
// checks if a peer id can possibly contain a shadow-style
// identification
boost::optional<fingerprint> parse_shadow_style(const peer_id& id)
{
fingerprint ret("..", 0, 0, 0, 0);
if (!std::isalnum(id[0]))
return boost::optional<fingerprint>();
if (std::equal(id.begin()+4, id.begin()+6, "--"))
{
if ((id[1] < '0') || (id[2] < '0')
|| (id[3] < '0'))
return boost::optional<fingerprint>();
ret.major_version = decode_digit(id[1]);
ret.minor_version = decode_digit(id[2]);
ret.revision_version = decode_digit(id[3]);
}
else
{
if (id[8] != 0 || id[1] > 127 || id[2] > 127 || id[3] > 127)
return boost::optional<fingerprint>();
ret.major_version = id[1];
ret.minor_version = id[2];
ret.revision_version = id[3];
}
ret.name[0] = id[0];
ret.name[1] = 0;
ret.tag_version = 0;
return boost::optional<fingerprint>(ret);
}
// checks if a peer id can possibly contain a mainline-style
// identification
boost::optional<fingerprint> parse_mainline_style(const peer_id& id)
{
char ids[21];
std::copy(id.begin(), id.end(), ids);
ids[20] = 0;
fingerprint ret("..", 0, 0, 0, 0);
ret.name[1] = 0;
ret.tag_version = 0;
if (sscanf(ids, "%c%d-%d-%d--", &ret.name[0], &ret.major_version, &ret.minor_version
, &ret.revision_version) != 4
|| !std::isprint(ret.name[0]))
return boost::optional<fingerprint>();
return boost::optional<fingerprint>(ret);
}
typedef std::pair<char const*, char const*> map_entry;
// only support BitTorrentSpecification
// must be ordered alphabetically
map_entry name_map[] =
{
map_entry("A", "ABC")
, map_entry("AR", "Arctic Torrent")
, map_entry("AX", "BitPump")
, map_entry("AZ", "Azureus")
, map_entry("BB", "BitBuddy")
, map_entry("BC", "BitComet")
, map_entry("BS", "BTSlave")
, map_entry("BX", "BittorrentX")
, map_entry("CD", "Enhanced CTorrent")
, map_entry("CT", "CTorrent")
, map_entry("ES", "electric sheep")
, map_entry("KT", "KTorrent")
, map_entry("LP", "lphant")
, map_entry("LT", "libtorrent")
, map_entry("M", "Mainline")
, map_entry("MP", "MooPolice")
, map_entry("MT", "Moonlight Torrent")
, map_entry("O", "Osprey Permaseed")
, map_entry("R", "Tribler")
, map_entry("S", "Shadow")
, map_entry("SB", "Swiftbit")
, map_entry("SN", "ShareNet")
, map_entry("SS", "SwarmScope")
, map_entry("SZ", "Shareaza")
, map_entry("T", "BitTornado")
, map_entry("TN", "Torrent.NET")
, map_entry("TR", "Transmission")
, map_entry("TS", "TorrentStorm")
, map_entry("U", "UPnP")
, map_entry("UL", "uLeecher")
, map_entry("UT", "MicroTorrent")
, map_entry("XT", "XanTorrent")
, map_entry("ZT", "ZipTorrent")
, map_entry("lt", "libTorrent (libtorrent.rakshasa.no/)")
, map_entry("pX", "pHoeniX")
, map_entry("qB", "qBittorrent")
};
bool compare_first_string(map_entry const& lhs, map_entry const& rhs)
{
return lhs.first[0] < rhs.first[0]
|| ((lhs.first[0] == rhs.first[0]) && (lhs.first[1] < rhs.first[1]));
}
std::string lookup(fingerprint const& f)
{
std::stringstream identity;
const int size = sizeof(name_map)/sizeof(name_map[0]);
map_entry* i =
std::lower_bound(name_map, name_map + size
, map_entry(f.name, ""), &compare_first_string);
#ifndef NDEBUG
for (int i = 1; i < size; ++i)
{
assert(compare_first_string(name_map[i-1]
, name_map[i]));
}
#endif
if (i < name_map + size && std::equal(f.name, f.name + 2, i->first))
identity << i->second;
else
{
identity << f.name[0];
if (f.name[1] != 0) identity << f.name[1];
}
identity << " " << (int)f.major_version
<< "." << (int)f.minor_version
<< "." << (int)f.revision_version;
if (f.name[1] != 0)
identity << "." << (int)f.tag_version;
return identity.str();
}
bool find_string(unsigned char const* id, char const* search)
{
return std::equal(search, search + std::strlen(search), id);
}
}
namespace libtorrent
{
boost::optional<fingerprint> client_fingerprint(peer_id const& p)
{
// look for azureus style id
boost::optional<fingerprint> f;
f = parse_az_style(p);
if (f) return f;
// look for shadow style id
f = parse_shadow_style(p);
if (f) return f;
// look for mainline style id
f = parse_mainline_style(p);
if (f) return f;
return f;
}
std::string identify_client(peer_id const& p)
{
peer_id::const_iterator PID = p.begin();
boost::optional<fingerprint> f;
if (p.is_all_zeros()) return "Unknown";
// ----------------------
// non standard encodings
// ----------------------
if (find_string(PID, "Deadman Walking-")) return "Deadman";
if (find_string(PID + 5, "Azureus")) return "Azureus 2.0.3.2";
if (find_string(PID, "DansClient")) return "XanTorrent";
if (find_string(PID + 4, "btfans")) return "SimpleBT";
if (find_string(PID, "PRC.P---")) return "Bittorrent Plus! II";
if (find_string(PID, "P87.P---")) return "Bittorrent Plus!";
if (find_string(PID, "S587Plus")) return "Bittorrent Plus!";
if (find_string(PID, "martini")) return "Martini Man";
if (find_string(PID, "Plus---")) return "Bittorrent Plus";
if (find_string(PID, "turbobt")) return "TurboBT";
if (find_string(PID, "a00---0")) return "Swarmy";
if (find_string(PID, "a02---0")) return "Swarmy";
if (find_string(PID, "T00---0")) return "Teeweety";
if (find_string(PID, "BTDWV-")) return "Deadman Walking";
if (find_string(PID + 2, "BS")) return "BitSpirit";
if (find_string(PID, "btuga")) return "BTugaXP";
if (find_string(PID, "oernu")) return "BTugaXP";
if (find_string(PID, "Mbrst")) return "Burst!";
if (find_string(PID, "Plus")) return "Plus!";
if (find_string(PID, "-Qt-")) return "Qt";
if (find_string(PID, "exbc")) return "BitComet";
if (find_string(PID, "-G3")) return "G3 Torrent";
if (find_string(PID, "XBT")) return "XBT";
if (find_string(PID, "OP")) return "Opera";
if (find_string(PID, "-BOW") && PID[7] == '-')
return "Bits on Wheels " + std::string(PID + 4, PID + 7);
if (find_string(PID, "eX"))
{
std::string user(PID + 2, PID + 14);
return std::string("eXeem ('") + user.c_str() + "')";
}
if (std::equal(PID, PID + 13, "\0\0\0\0\0\0\0\0\0\0\0\0\x97"))
return "Experimental 3.2.1b2";
if (std::equal(PID, PID + 13, "\0\0\0\0\0\0\0\0\0\0\0\0\0"))
return "Experimental 3.1";
// look for azureus style id
f = parse_az_style(p);
if (f) return lookup(*f);
// look for shadow style id
f = parse_shadow_style(p);
if (f) return lookup(*f);
// look for mainline style id
f = parse_mainline_style(p);
if (f) return lookup(*f);
if (std::equal(PID, PID + 12, "\0\0\0\0\0\0\0\0\0\0\0\0"))
return "Generic";
std::string unknown("Unknown [");
for (peer_id::const_iterator i = p.begin(); i != p.end(); ++i)
{
unknown += std::isprint(*i)?*i:'.';
}
unknown += "]";
return unknown;
}
}
<|endoftext|> |
<commit_before>#include "qtmonkey.hpp"
#include <cstdio>
#include <cassert>
#include <atomic>
#ifdef _WIN32 // windows both 32 bit and 64 bit
# include <windows.h>
#else
# include <unistd.h>
#endif
#include <QtCore/QCoreApplication>
#include <QtCore/QTextCodec>
#include <QtCore/QThread>
#include "common.hpp"
#include "qtmonkey_app_api.hpp"
using qt_monkey_app::QtMonkey;
using qt_monkey_agent::Private::Script;
using qt_monkey_agent::Private::PacketTypeForAgent;
using qt_monkey_app::Private::StdinReader;
namespace
{
static constexpr int waitBeforeExitMs = 300;
/*
win32 not allow overlapped I/O (see CreateFile [Consoles section]
plus QWinEventNotifier private on Qt 4.x and become public only on Qt 5.x
so just create thread for both win32 and posix
*/
class ReadStdinThread final : public QThread {
public:
ReadStdinThread(QObject *parent, StdinReader &reader);
void run() override;
void stop();
private:
StdinReader &reader_;
std::atomic<bool> timeToExit_{ false };
#ifdef _WIN32
HANDLE stdinHandle_;
#endif
};
#ifdef _WIN32
ReadStdinThread::ReadStdinThread(QObject *parent, StdinReader &reader) : QThread(parent), reader_(reader)
{
stdinHandle_ = ::GetStdHandle(STD_INPUT_HANDLE);
if (stdinHandle_ == INVALID_HANDLE_VALUE)
throw std::runtime_error("GetStdHandle(STD_INPUT_HANDLE) return error: " + std::to_string(GetLastError()));
}
void ReadStdinThread::run()
{
while (!timeToExit_) {
char ch;
DWORD readBytes = 0;
if (!::ReadFile(stdinHandle_, &ch, sizeof(ch), &readBytes, nullptr)) {
reader_.emitError(T_("reading from stdin error: %1").arg(GetLastError()));
return;
}
if (readBytes == 0)
break;
{
auto ptr = reader_.data.get();
ptr->append(ch);
}
reader_.emitDataReady();
}
}
void ReadStdinThread::stop()
{
timeToExit_ = true;
if (!::CloseHandle(stdinHandle_))
throw std::runtime_error("CloseHandle(stdin) error: " + std::to_string(GetLastError()));
}
#else
ReadStdinThread::ReadStdinThread(QObject *parent, StdinReader &reader) : QThread(parent), reader_(reader)
{
}
void ReadStdinThread::run()
{
while (!timeToExit_) {
char ch;
const ssize_t nBytes = ::read(STDIN_FILENO, &ch, sizeof(ch));
if (nBytes < 0) {
emit error(T_("reading from stdin error: %1").arg(errno));
return;
} else if (nBytes == 0) {
break;
}
{
auto ptr = data.get();
ptr->append(ch);
}
emit dataReady();
}
}
void ReadStdinThread::stop()
{
timeToExit_ = true;
do {
if (::close(STDIN_FILENO) == 0)
return;
} while (errno == EINTR);
throw std::runtime_error("close(stdin) failure: " + std::to_string(errno));
}
)
#endif
}
QtMonkey::QtMonkey(bool exitOnScriptError)
: exitOnScriptError_(exitOnScriptError)
{
if (!stdout_.open(stdout, QIODevice::WriteOnly, QFile::DontCloseHandle)
|| !stderr_.open(stderr, QIODevice::WriteOnly, QFile::DontCloseHandle))
throw std::runtime_error("File -> QFile failed");
cout_.setDevice(&stdout_);
cerr_.setDevice(&stderr_);
connect(&userApp_, SIGNAL(error(QProcess::ProcessError)), this,
SLOT(userAppError(QProcess::ProcessError)));
connect(&userApp_, SIGNAL(finished(int, QProcess::ExitStatus)), this,
SLOT(userAppFinished(int, QProcess::ExitStatus)));
connect(&userApp_, SIGNAL(readyReadStandardOutput()), this,
SLOT(userAppNewOutput()));
connect(&userApp_, SIGNAL(readyReadStandardError()), this,
SLOT(userAppNewErrOutput()));
connect(&channelWithAgent_, SIGNAL(error(QString)), this,
SLOT(communicationWithAgentError(const QString &)));
connect(&channelWithAgent_, SIGNAL(newUserAppEvent(QString)), this,
SLOT(onNewUserAppEvent(QString)));
connect(&channelWithAgent_, SIGNAL(scriptError(QString)), this,
SLOT(onScriptError(QString)));
connect(&channelWithAgent_, SIGNAL(agentReadyToRunScript()), this,
SLOT(onAgentReadyToRunScript()));
connect(&channelWithAgent_, SIGNAL(scriptEnd()), this, SLOT(onScriptEnd()));
connect(&channelWithAgent_, SIGNAL(scriptLog(QString)), this,
SLOT(onScriptLog(QString)));
if (std::setvbuf(stdin, nullptr, _IONBF, 0))
throw std::runtime_error("setvbuf failed");
#ifdef _WIN32
readStdinThread_ = new ReadStdinThread(this, stdinReader_);
stdinReader_.moveToThread(readStdinThread_);
readStdinThread_->start();
connect(&stdinReader_, SIGNAL(dataReady()), this, SLOT(stdinDataReady()));
#else
int stdinHandler = ::fileno(stdin);
if (stdinHandler < 0)
throw std::runtime_error("fileno(stdin) return error");
auto stdinNotifier
= new QSocketNotifier(stdinHandler, QSocketNotifier::Read, this);
connect(stdinNotifier, SIGNAL(activated(int)), this,
SLOT(stdinDataReady()));
#endif
}
QtMonkey::~QtMonkey()
{
assert(readStdinThread_ != nullptr);
auto thread = static_cast<ReadStdinThread *>(readStdinThread_);
thread->stop();
thread->wait(100/*ms*/);
thread->terminate();
if (userApp_.state() != QProcess::NotRunning) {
userApp_.terminate();
QCoreApplication::processEvents(QEventLoop::AllEvents, 3000 /*ms*/);
userApp_.kill();
QCoreApplication::processEvents(QEventLoop::AllEvents, 1000 /*ms*/);
}
// so any signals from channel will be disconected
channelWithAgent_.close();
}
void QtMonkey::communicationWithAgentError(const QString &errStr)
{
qWarning("%s: errStr %s", Q_FUNC_INFO, qPrintable(errStr));
}
void QtMonkey::onNewUserAppEvent(QString scriptLines)
{
cout_ << qt_monkey_app::createPacketFromUserAppEvent(scriptLines) << "\n";
cout_.flush();
}
void QtMonkey::userAppError(QProcess::ProcessError err)
{
qDebug("%s: begin err %d", Q_FUNC_INFO, static_cast<int>(err));
throw std::runtime_error(
qPrintable(qt_monkey_common::processErrorToString(err)));
}
void QtMonkey::userAppFinished(int exitCode, QProcess::ExitStatus exitStatus)
{
qDebug("%s: begin exitCode %d, exitStatus %d", Q_FUNC_INFO, exitCode,
static_cast<int>(exitStatus));
qt_monkey_common::processEventsFor(waitBeforeExitMs);
if (exitCode != EXIT_SUCCESS)
throw std::runtime_error(T_("user app exit status not %1: %2")
.arg(EXIT_SUCCESS)
.arg(exitCode)
.toUtf8()
.data());
QCoreApplication::exit(EXIT_SUCCESS);
}
void QtMonkey::userAppNewOutput()
{
// just ignore for now
userApp_.readAllStandardOutput();
}
void QtMonkey::userAppNewErrOutput()
{
const QString errOut
= QString::fromLocal8Bit(userApp_.readAllStandardError());
cout_ << createPacketFromUserAppErrors(errOut) << "\n";
cout_.flush();
}
void QtMonkey::stdinDataReady()
{
auto dataPtr = stdinReader_.data.get();
size_t parserStopPos;
parseOutputFromGui(
*dataPtr, parserStopPos,
[this](QString script, QString scriptFileName) {
toRunList_.push(Script{std::move(script)});
onAgentReadyToRunScript();
},
[this](QString errMsg) {
cerr_
<< T_("Can not parse gui<->monkey protocol: %1\n").arg(errMsg);
});
if (parserStopPos != 0)
dataPtr->remove(0, parserStopPos);
}
void QtMonkey::onScriptError(QString errMsg)
{
qDebug("%s: begin %s", Q_FUNC_INFO, qPrintable(errMsg));
setScriptRunningState(false);
cout_ << createPacketFromUserAppErrors(errMsg) << "\n";
cout_.flush();
if (exitOnScriptError_) {
qt_monkey_common::processEventsFor(waitBeforeExitMs);
throw std::runtime_error(T_("script return error: %1")
.arg(errMsg).toUtf8().data());
}
}
bool QtMonkey::runScriptFromFile(QStringList scriptPathList,
const char *encoding)
{
if (encoding == nullptr)
encoding = "UTF-8";
QString script;
for (const QString &fn : scriptPathList) {
QFile f(fn);
if (!f.open(QIODevice::ReadOnly)) {
cerr_ << T_("Error: can not open %1\n").arg(fn);
return false;
}
QTextStream t(&f);
t.setCodec(QTextCodec::codecForName(encoding));
if (!script.isEmpty())
script += "\n<<<RESTART FROM HERE>>>\n";
script += t.readAll();
}
toRunList_.push(Script{std::move(script)});
return true;
}
void QtMonkey::onAgentReadyToRunScript()
{
qDebug("%s: begin", Q_FUNC_INFO);
if (!channelWithAgent_.isConnectedState() || toRunList_.empty()
|| scriptRunning_)
return;
Script script = std::move(toRunList_.front());
toRunList_.pop();
QString code;
script.releaseCode(code);
channelWithAgent_.sendCommand(PacketTypeForAgent::RunScript,
std::move(code));
setScriptRunningState(true);
}
void QtMonkey::onScriptEnd()
{
setScriptRunningState(false);
cout_ << createPacketFromScriptEnd() << "\n";
cout_.flush();
}
void QtMonkey::onScriptLog(QString msg)
{
cout_ << createPacketFromUserAppScriptLog(msg) << "\n";
cout_.flush();
}
void QtMonkey::setScriptRunningState(bool val)
{
scriptRunning_ = val;
if (!scriptRunning_)
onAgentReadyToRunScript();
}
<commit_msg>fix build on linux<commit_after>#include "qtmonkey.hpp"
#include <atomic>
#include <cassert>
#include <cstdio>
#ifdef _WIN32 // windows both 32 bit and 64 bit
#include <windows.h>
#else
#include <cerrno>
#include <unistd.h>
#endif
#include <QtCore/QCoreApplication>
#include <QtCore/QTextCodec>
#include <QtCore/QThread>
#include "common.hpp"
#include "qtmonkey_app_api.hpp"
using qt_monkey_app::QtMonkey;
using qt_monkey_agent::Private::Script;
using qt_monkey_agent::Private::PacketTypeForAgent;
using qt_monkey_app::Private::StdinReader;
namespace
{
static constexpr int waitBeforeExitMs = 300;
/*
win32 not allow overlapped I/O (see CreateFile [Consoles section]
plus QWinEventNotifier private on Qt 4.x and become public only on Qt 5.x
so just create thread for both win32 and posix
*/
class ReadStdinThread final : public QThread
{
public:
ReadStdinThread(QObject *parent, StdinReader &reader);
void run() override;
void stop();
private:
StdinReader &reader_;
std::atomic<bool> timeToExit_{false};
#ifdef _WIN32
HANDLE stdinHandle_;
#endif
};
#ifdef _WIN32
ReadStdinThread::ReadStdinThread(QObject *parent, StdinReader &reader)
: QThread(parent), reader_(reader)
{
stdinHandle_ = ::GetStdHandle(STD_INPUT_HANDLE);
if (stdinHandle_ == INVALID_HANDLE_VALUE)
throw std::runtime_error("GetStdHandle(STD_INPUT_HANDLE) return error: "
+ std::to_string(GetLastError()));
}
void ReadStdinThread::run()
{
while (!timeToExit_) {
char ch;
DWORD readBytes = 0;
if (!::ReadFile(stdinHandle_, &ch, sizeof(ch), &readBytes, nullptr)) {
reader_.emitError(
T_("reading from stdin error: %1").arg(GetLastError()));
return;
}
if (readBytes == 0)
break;
{
auto ptr = reader_.data.get();
ptr->append(ch);
}
reader_.emitDataReady();
}
}
void ReadStdinThread::stop()
{
timeToExit_ = true;
if (!::CloseHandle(stdinHandle_))
throw std::runtime_error("CloseHandle(stdin) error: "
+ std::to_string(GetLastError()));
}
#else
ReadStdinThread::ReadStdinThread(QObject *parent, StdinReader &reader)
: QThread(parent), reader_(reader)
{
}
void ReadStdinThread::run()
{
while (!timeToExit_) {
char ch;
const ssize_t nBytes = ::read(STDIN_FILENO, &ch, sizeof(ch));
if (nBytes < 0) {
reader_.emitError(T_("reading from stdin error: %1").arg(errno));
return;
} else if (nBytes == 0) {
break;
}
{
auto ptr = reader_.data.get();
ptr->append(ch);
}
reader_.emitDataReady();
}
}
void ReadStdinThread::stop()
{
timeToExit_ = true;
do {
if (::close(STDIN_FILENO) == 0)
return;
} while (errno == EINTR);
throw std::runtime_error("close(stdin) failure: " + std::to_string(errno));
}
#endif
} //namespace {
QtMonkey::QtMonkey(bool exitOnScriptError)
: exitOnScriptError_(exitOnScriptError)
{
if (!stdout_.open(stdout, QIODevice::WriteOnly, QFile::DontCloseHandle)
|| !stderr_.open(stderr, QIODevice::WriteOnly, QFile::DontCloseHandle))
throw std::runtime_error("File -> QFile failed");
cout_.setDevice(&stdout_);
cerr_.setDevice(&stderr_);
connect(&userApp_, SIGNAL(error(QProcess::ProcessError)), this,
SLOT(userAppError(QProcess::ProcessError)));
connect(&userApp_, SIGNAL(finished(int, QProcess::ExitStatus)), this,
SLOT(userAppFinished(int, QProcess::ExitStatus)));
connect(&userApp_, SIGNAL(readyReadStandardOutput()), this,
SLOT(userAppNewOutput()));
connect(&userApp_, SIGNAL(readyReadStandardError()), this,
SLOT(userAppNewErrOutput()));
connect(&channelWithAgent_, SIGNAL(error(QString)), this,
SLOT(communicationWithAgentError(const QString &)));
connect(&channelWithAgent_, SIGNAL(newUserAppEvent(QString)), this,
SLOT(onNewUserAppEvent(QString)));
connect(&channelWithAgent_, SIGNAL(scriptError(QString)), this,
SLOT(onScriptError(QString)));
connect(&channelWithAgent_, SIGNAL(agentReadyToRunScript()), this,
SLOT(onAgentReadyToRunScript()));
connect(&channelWithAgent_, SIGNAL(scriptEnd()), this, SLOT(onScriptEnd()));
connect(&channelWithAgent_, SIGNAL(scriptLog(QString)), this,
SLOT(onScriptLog(QString)));
readStdinThread_ = new ReadStdinThread(this, stdinReader_);
stdinReader_.moveToThread(readStdinThread_);
readStdinThread_->start();
connect(&stdinReader_, SIGNAL(dataReady()), this, SLOT(stdinDataReady()));
}
QtMonkey::~QtMonkey()
{
assert(readStdinThread_ != nullptr);
auto thread = static_cast<ReadStdinThread *>(readStdinThread_);
thread->stop();
thread->wait(100 /*ms*/);
thread->terminate();
if (userApp_.state() != QProcess::NotRunning) {
userApp_.terminate();
QCoreApplication::processEvents(QEventLoop::AllEvents, 3000 /*ms*/);
userApp_.kill();
QCoreApplication::processEvents(QEventLoop::AllEvents, 1000 /*ms*/);
}
// so any signals from channel will be disconected
channelWithAgent_.close();
}
void QtMonkey::communicationWithAgentError(const QString &errStr)
{
qWarning("%s: errStr %s", Q_FUNC_INFO, qPrintable(errStr));
}
void QtMonkey::onNewUserAppEvent(QString scriptLines)
{
cout_ << qt_monkey_app::createPacketFromUserAppEvent(scriptLines) << "\n";
cout_.flush();
}
void QtMonkey::userAppError(QProcess::ProcessError err)
{
qDebug("%s: begin err %d", Q_FUNC_INFO, static_cast<int>(err));
throw std::runtime_error(
qPrintable(qt_monkey_common::processErrorToString(err)));
}
void QtMonkey::userAppFinished(int exitCode, QProcess::ExitStatus exitStatus)
{
qDebug("%s: begin exitCode %d, exitStatus %d", Q_FUNC_INFO, exitCode,
static_cast<int>(exitStatus));
qt_monkey_common::processEventsFor(waitBeforeExitMs);
if (exitCode != EXIT_SUCCESS)
throw std::runtime_error(T_("user app exit status not %1: %2")
.arg(EXIT_SUCCESS)
.arg(exitCode)
.toUtf8()
.data());
QCoreApplication::exit(EXIT_SUCCESS);
}
void QtMonkey::userAppNewOutput()
{
// just ignore for now
userApp_.readAllStandardOutput();
}
void QtMonkey::userAppNewErrOutput()
{
const QString errOut
= QString::fromLocal8Bit(userApp_.readAllStandardError());
cout_ << createPacketFromUserAppErrors(errOut) << "\n";
cout_.flush();
}
void QtMonkey::stdinDataReady()
{
auto dataPtr = stdinReader_.data.get();
size_t parserStopPos;
parseOutputFromGui(
*dataPtr, parserStopPos,
[this](QString script, QString scriptFileName) {
toRunList_.push(Script{std::move(script)});
onAgentReadyToRunScript();
},
[this](QString errMsg) {
cerr_
<< T_("Can not parse gui<->monkey protocol: %1\n").arg(errMsg);
});
if (parserStopPos != 0)
dataPtr->remove(0, parserStopPos);
}
void QtMonkey::onScriptError(QString errMsg)
{
qDebug("%s: begin %s", Q_FUNC_INFO, qPrintable(errMsg));
setScriptRunningState(false);
cout_ << createPacketFromUserAppErrors(errMsg) << "\n";
cout_.flush();
if (exitOnScriptError_) {
qt_monkey_common::processEventsFor(waitBeforeExitMs);
throw std::runtime_error(
T_("script return error: %1").arg(errMsg).toUtf8().data());
}
}
bool QtMonkey::runScriptFromFile(QStringList scriptPathList,
const char *encoding)
{
if (encoding == nullptr)
encoding = "UTF-8";
QString script;
for (const QString &fn : scriptPathList) {
QFile f(fn);
if (!f.open(QIODevice::ReadOnly)) {
cerr_ << T_("Error: can not open %1\n").arg(fn);
return false;
}
QTextStream t(&f);
t.setCodec(QTextCodec::codecForName(encoding));
if (!script.isEmpty())
script += "\n<<<RESTART FROM HERE>>>\n";
script += t.readAll();
}
toRunList_.push(Script{std::move(script)});
return true;
}
void QtMonkey::onAgentReadyToRunScript()
{
qDebug("%s: begin", Q_FUNC_INFO);
if (!channelWithAgent_.isConnectedState() || toRunList_.empty()
|| scriptRunning_)
return;
Script script = std::move(toRunList_.front());
toRunList_.pop();
QString code;
script.releaseCode(code);
channelWithAgent_.sendCommand(PacketTypeForAgent::RunScript,
std::move(code));
setScriptRunningState(true);
}
void QtMonkey::onScriptEnd()
{
setScriptRunningState(false);
cout_ << createPacketFromScriptEnd() << "\n";
cout_.flush();
}
void QtMonkey::onScriptLog(QString msg)
{
cout_ << createPacketFromUserAppScriptLog(msg) << "\n";
cout_.flush();
}
void QtMonkey::setScriptRunningState(bool val)
{
scriptRunning_ = val;
if (!scriptRunning_)
onAgentReadyToRunScript();
}
<|endoftext|> |
<commit_before>/*
Copyright (c) 2003, Arvid Norberg
All rights reserved.
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions
are met:
* Redistributions of source code must retain the above copyright
notice, this list of conditions and the following disclaimer.
* Redistributions in binary form must reproduce the above copyright
notice, this list of conditions and the following disclaimer in
the documentation and/or other materials provided with the distribution.
* Neither the name of the author nor the names of its
contributors may be used to endorse or promote products derived
from this software without specific prior written permission.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE
LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
POSSIBILITY OF SUCH DAMAGE.
*/
#include "libtorrent/pch.hpp"
#include <cctype>
#include <algorithm>
#ifdef _MSC_VER
#pragma warning(push, 1)
#endif
#include <boost/optional.hpp>
#ifdef _MSC_VER
#pragma warning(pop)
#endif
#include "libtorrent/identify_client.hpp"
#include "libtorrent/fingerprint.hpp"
namespace
{
using namespace libtorrent;
int decode_digit(char c)
{
if (std::isdigit(c)) return c - '0';
return unsigned(c) - 'A' + 10;
}
// takes a peer id and returns a valid boost::optional
// object if the peer id matched the azureus style encoding
// the returned fingerprint contains information about the
// client's id
boost::optional<fingerprint> parse_az_style(const peer_id& id)
{
fingerprint ret("..", 0, 0, 0, 0);
if (id[0] != '-' || !std::isprint(id[1]) || (id[2] < '0')
|| (id[3] < '0') || (id[4] < '0')
|| (id[5] < '0') || (id[6] < '0')
|| id[7] != '-')
return boost::optional<fingerprint>();
ret.name[0] = id[1];
ret.name[1] = id[2];
ret.major_version = decode_digit(id[3]);
ret.minor_version = decode_digit(id[4]);
ret.revision_version = decode_digit(id[5]);
ret.tag_version = decode_digit(id[6]);
return boost::optional<fingerprint>(ret);
}
// checks if a peer id can possibly contain a shadow-style
// identification
boost::optional<fingerprint> parse_shadow_style(const peer_id& id)
{
fingerprint ret("..", 0, 0, 0, 0);
if (!std::isalnum(id[0]))
return boost::optional<fingerprint>();
if (std::equal(id.begin()+4, id.begin()+6, "--"))
{
if ((id[1] < '0') || (id[2] < '0')
|| (id[3] < '0'))
return boost::optional<fingerprint>();
ret.major_version = decode_digit(id[1]);
ret.minor_version = decode_digit(id[2]);
ret.revision_version = decode_digit(id[3]);
}
else
{
if (id[8] != 0 || id[1] > 127 || id[2] > 127 || id[3] > 127)
return boost::optional<fingerprint>();
ret.major_version = id[1];
ret.minor_version = id[2];
ret.revision_version = id[3];
}
ret.name[0] = id[0];
ret.name[1] = 0;
ret.tag_version = 0;
return boost::optional<fingerprint>(ret);
}
// checks if a peer id can possibly contain a mainline-style
// identification
boost::optional<fingerprint> parse_mainline_style(const peer_id& id)
{
char ids[21];
std::copy(id.begin(), id.end(), ids);
ids[20] = 0;
fingerprint ret("..", 0, 0, 0, 0);
ret.name[1] = 0;
ret.tag_version = 0;
if (sscanf(ids, "%c%d-%d-%d--", &ret.name[0], &ret.major_version, &ret.minor_version
, &ret.revision_version) != 4
|| !std::isprint(ret.name[0]))
return boost::optional<fingerprint>();
return boost::optional<fingerprint>(ret);
}
typedef std::pair<char const*, char const*> map_entry;
// only support BitTorrentSpecification
// must be ordered alphabetically
map_entry name_map[] =
{
map_entry("A", "ABC")
, map_entry("AR", "Arctic Torrent")
, map_entry("AX", "BitPump")
, map_entry("AZ", "Azureus")
, map_entry("BB", "BitBuddy")
, map_entry("BC", "BitComet")
, map_entry("BF", "Bitflu")
, map_entry("BG", "btgdaemon")
, map_entry("BS", "BTSlave")
, map_entry("BX", "BittorrentX")
, map_entry("CD", "Enhanced CTorrent")
, map_entry("CT", "CTorrent")
, map_entry("DE", "Deluge")
, map_entry("ES", "electric sheep")
, map_entry("HL", "Halite")
, map_entry("KT", "KTorrent")
, map_entry("LK", "Linkage")
, map_entry("LP", "lphant")
, map_entry("LT", "libtorrent")
, map_entry("M", "Mainline")
, map_entry("ML", "MLDonkey")
, map_entry("MO", "Mono Torrent")
, map_entry("MP", "MooPolice")
, map_entry("MT", "Moonlight Torrent")
, map_entry("O", "Osprey Permaseed")
, map_entry("QT", "Qt 4")
, map_entry("R", "Tribler")
, map_entry("S", "Shadow")
, map_entry("SB", "Swiftbit")
, map_entry("SN", "ShareNet")
, map_entry("SS", "SwarmScope")
, map_entry("SZ", "Shareaza")
, map_entry("T", "BitTornado")
, map_entry("TN", "Torrent.NET")
, map_entry("TR", "Transmission")
, map_entry("TS", "TorrentStorm")
, map_entry("U", "UPnP")
, map_entry("UL", "uLeecher")
, map_entry("UT", "MicroTorrent")
, map_entry("XT", "XanTorrent")
, map_entry("XX", "Xtorrent")
, map_entry("ZT", "ZipTorrent")
, map_entry("lt", "libTorrent (libtorrent.rakshasa.no/)")
, map_entry("pX", "pHoeniX")
, map_entry("qB", "qBittorrent")
};
bool compare_first_string(map_entry const& lhs, map_entry const& rhs)
{
return lhs.first[0] < rhs.first[0]
|| ((lhs.first[0] == rhs.first[0]) && (lhs.first[1] < rhs.first[1]));
}
std::string lookup(fingerprint const& f)
{
std::stringstream identity;
const int size = sizeof(name_map)/sizeof(name_map[0]);
map_entry* i =
std::lower_bound(name_map, name_map + size
, map_entry(f.name, ""), &compare_first_string);
#ifndef NDEBUG
for (int i = 1; i < size; ++i)
{
assert(compare_first_string(name_map[i-1]
, name_map[i]));
}
#endif
if (i < name_map + size && std::equal(f.name, f.name + 2, i->first))
identity << i->second;
else
{
identity << f.name[0];
if (f.name[1] != 0) identity << f.name[1];
}
identity << " " << (int)f.major_version
<< "." << (int)f.minor_version
<< "." << (int)f.revision_version;
if (f.name[1] != 0)
identity << "." << (int)f.tag_version;
return identity.str();
}
bool find_string(unsigned char const* id, char const* search)
{
return std::equal(search, search + std::strlen(search), id);
}
}
namespace libtorrent
{
boost::optional<fingerprint> client_fingerprint(peer_id const& p)
{
// look for azureus style id
boost::optional<fingerprint> f;
f = parse_az_style(p);
if (f) return f;
// look for shadow style id
f = parse_shadow_style(p);
if (f) return f;
// look for mainline style id
f = parse_mainline_style(p);
if (f) return f;
return f;
}
std::string identify_client(peer_id const& p)
{
peer_id::const_iterator PID = p.begin();
boost::optional<fingerprint> f;
if (p.is_all_zeros()) return "Unknown";
// ----------------------
// non standard encodings
// ----------------------
if (find_string(PID, "Deadman Walking-")) return "Deadman";
if (find_string(PID + 5, "Azureus")) return "Azureus 2.0.3.2";
if (find_string(PID, "DansClient")) return "XanTorrent";
if (find_string(PID + 4, "btfans")) return "SimpleBT";
if (find_string(PID, "PRC.P---")) return "Bittorrent Plus! II";
if (find_string(PID, "P87.P---")) return "Bittorrent Plus!";
if (find_string(PID, "S587Plus")) return "Bittorrent Plus!";
if (find_string(PID, "martini")) return "Martini Man";
if (find_string(PID, "Plus---")) return "Bittorrent Plus";
if (find_string(PID, "turbobt")) return "TurboBT";
if (find_string(PID, "a00---0")) return "Swarmy";
if (find_string(PID, "a02---0")) return "Swarmy";
if (find_string(PID, "T00---0")) return "Teeweety";
if (find_string(PID, "BTDWV-")) return "Deadman Walking";
if (find_string(PID + 2, "BS")) return "BitSpirit";
if (find_string(PID, "btuga")) return "BTugaXP";
if (find_string(PID, "oernu")) return "BTugaXP";
if (find_string(PID, "Mbrst")) return "Burst!";
if (find_string(PID, "Plus")) return "Plus!";
if (find_string(PID, "-Qt-")) return "Qt";
if (find_string(PID, "exbc")) return "BitComet";
if (find_string(PID, "-G3")) return "G3 Torrent";
if (find_string(PID, "XBT")) return "XBT";
if (find_string(PID, "OP")) return "Opera";
if (find_string(PID, "-BOW") && PID[7] == '-')
return "Bits on Wheels " + std::string(PID + 4, PID + 7);
if (find_string(PID, "eX"))
{
std::string user(PID + 2, PID + 14);
return std::string("eXeem ('") + user.c_str() + "')";
}
if (std::equal(PID, PID + 13, "\0\0\0\0\0\0\0\0\0\0\0\0\x97"))
return "Experimental 3.2.1b2";
if (std::equal(PID, PID + 13, "\0\0\0\0\0\0\0\0\0\0\0\0\0"))
return "Experimental 3.1";
// look for azureus style id
f = parse_az_style(p);
if (f) return lookup(*f);
// look for shadow style id
f = parse_shadow_style(p);
if (f) return lookup(*f);
// look for mainline style id
f = parse_mainline_style(p);
if (f) return lookup(*f);
if (std::equal(PID, PID + 12, "\0\0\0\0\0\0\0\0\0\0\0\0"))
return "Generic";
std::string unknown("Unknown [");
for (peer_id::const_iterator i = p.begin(); i != p.end(); ++i)
{
unknown += std::isprint(*i)?*i:'.';
}
unknown += "]";
return unknown;
}
}
<commit_msg>added BitRocket to known clients<commit_after>/*
Copyright (c) 2003, Arvid Norberg
All rights reserved.
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions
are met:
* Redistributions of source code must retain the above copyright
notice, this list of conditions and the following disclaimer.
* Redistributions in binary form must reproduce the above copyright
notice, this list of conditions and the following disclaimer in
the documentation and/or other materials provided with the distribution.
* Neither the name of the author nor the names of its
contributors may be used to endorse or promote products derived
from this software without specific prior written permission.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE
LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
POSSIBILITY OF SUCH DAMAGE.
*/
#include "libtorrent/pch.hpp"
#include <cctype>
#include <algorithm>
#ifdef _MSC_VER
#pragma warning(push, 1)
#endif
#include <boost/optional.hpp>
#ifdef _MSC_VER
#pragma warning(pop)
#endif
#include "libtorrent/identify_client.hpp"
#include "libtorrent/fingerprint.hpp"
namespace
{
using namespace libtorrent;
int decode_digit(char c)
{
if (std::isdigit(c)) return c - '0';
return unsigned(c) - 'A' + 10;
}
// takes a peer id and returns a valid boost::optional
// object if the peer id matched the azureus style encoding
// the returned fingerprint contains information about the
// client's id
boost::optional<fingerprint> parse_az_style(const peer_id& id)
{
fingerprint ret("..", 0, 0, 0, 0);
if (id[0] != '-' || !std::isprint(id[1]) || (id[2] < '0')
|| (id[3] < '0') || (id[4] < '0')
|| (id[5] < '0') || (id[6] < '0')
|| id[7] != '-')
return boost::optional<fingerprint>();
ret.name[0] = id[1];
ret.name[1] = id[2];
ret.major_version = decode_digit(id[3]);
ret.minor_version = decode_digit(id[4]);
ret.revision_version = decode_digit(id[5]);
ret.tag_version = decode_digit(id[6]);
return boost::optional<fingerprint>(ret);
}
// checks if a peer id can possibly contain a shadow-style
// identification
boost::optional<fingerprint> parse_shadow_style(const peer_id& id)
{
fingerprint ret("..", 0, 0, 0, 0);
if (!std::isalnum(id[0]))
return boost::optional<fingerprint>();
if (std::equal(id.begin()+4, id.begin()+6, "--"))
{
if ((id[1] < '0') || (id[2] < '0')
|| (id[3] < '0'))
return boost::optional<fingerprint>();
ret.major_version = decode_digit(id[1]);
ret.minor_version = decode_digit(id[2]);
ret.revision_version = decode_digit(id[3]);
}
else
{
if (id[8] != 0 || id[1] > 127 || id[2] > 127 || id[3] > 127)
return boost::optional<fingerprint>();
ret.major_version = id[1];
ret.minor_version = id[2];
ret.revision_version = id[3];
}
ret.name[0] = id[0];
ret.name[1] = 0;
ret.tag_version = 0;
return boost::optional<fingerprint>(ret);
}
// checks if a peer id can possibly contain a mainline-style
// identification
boost::optional<fingerprint> parse_mainline_style(const peer_id& id)
{
char ids[21];
std::copy(id.begin(), id.end(), ids);
ids[20] = 0;
fingerprint ret("..", 0, 0, 0, 0);
ret.name[1] = 0;
ret.tag_version = 0;
if (sscanf(ids, "%c%d-%d-%d--", &ret.name[0], &ret.major_version, &ret.minor_version
, &ret.revision_version) != 4
|| !std::isprint(ret.name[0]))
return boost::optional<fingerprint>();
return boost::optional<fingerprint>(ret);
}
typedef std::pair<char const*, char const*> map_entry;
// only support BitTorrentSpecification
// must be ordered alphabetically
map_entry name_map[] =
{
map_entry("A", "ABC")
, map_entry("AR", "Arctic Torrent")
, map_entry("AX", "BitPump")
, map_entry("AZ", "Azureus")
, map_entry("BB", "BitBuddy")
, map_entry("BC", "BitComet")
, map_entry("BF", "Bitflu")
, map_entry("BG", "btgdaemon")
, map_entry("BR", "BitRocket")
, map_entry("BS", "BTSlave")
, map_entry("BX", "BittorrentX")
, map_entry("CD", "Enhanced CTorrent")
, map_entry("CT", "CTorrent")
, map_entry("DE", "Deluge")
, map_entry("ES", "electric sheep")
, map_entry("HL", "Halite")
, map_entry("KT", "KTorrent")
, map_entry("LK", "Linkage")
, map_entry("LP", "lphant")
, map_entry("LT", "libtorrent")
, map_entry("M", "Mainline")
, map_entry("ML", "MLDonkey")
, map_entry("MO", "Mono Torrent")
, map_entry("MP", "MooPolice")
, map_entry("MT", "Moonlight Torrent")
, map_entry("O", "Osprey Permaseed")
, map_entry("QT", "Qt 4")
, map_entry("R", "Tribler")
, map_entry("S", "Shadow")
, map_entry("SB", "Swiftbit")
, map_entry("SN", "ShareNet")
, map_entry("SS", "SwarmScope")
, map_entry("SZ", "Shareaza")
, map_entry("T", "BitTornado")
, map_entry("TN", "Torrent.NET")
, map_entry("TR", "Transmission")
, map_entry("TS", "TorrentStorm")
, map_entry("U", "UPnP")
, map_entry("UL", "uLeecher")
, map_entry("UT", "MicroTorrent")
, map_entry("XT", "XanTorrent")
, map_entry("XX", "Xtorrent")
, map_entry("ZT", "ZipTorrent")
, map_entry("lt", "libTorrent (libtorrent.rakshasa.no/)")
, map_entry("pX", "pHoeniX")
, map_entry("qB", "qBittorrent")
};
bool compare_first_string(map_entry const& lhs, map_entry const& rhs)
{
return lhs.first[0] < rhs.first[0]
|| ((lhs.first[0] == rhs.first[0]) && (lhs.first[1] < rhs.first[1]));
}
std::string lookup(fingerprint const& f)
{
std::stringstream identity;
const int size = sizeof(name_map)/sizeof(name_map[0]);
map_entry* i =
std::lower_bound(name_map, name_map + size
, map_entry(f.name, ""), &compare_first_string);
#ifndef NDEBUG
for (int i = 1; i < size; ++i)
{
assert(compare_first_string(name_map[i-1]
, name_map[i]));
}
#endif
if (i < name_map + size && std::equal(f.name, f.name + 2, i->first))
identity << i->second;
else
{
identity << f.name[0];
if (f.name[1] != 0) identity << f.name[1];
}
identity << " " << (int)f.major_version
<< "." << (int)f.minor_version
<< "." << (int)f.revision_version;
if (f.name[1] != 0)
identity << "." << (int)f.tag_version;
return identity.str();
}
bool find_string(unsigned char const* id, char const* search)
{
return std::equal(search, search + std::strlen(search), id);
}
}
namespace libtorrent
{
boost::optional<fingerprint> client_fingerprint(peer_id const& p)
{
// look for azureus style id
boost::optional<fingerprint> f;
f = parse_az_style(p);
if (f) return f;
// look for shadow style id
f = parse_shadow_style(p);
if (f) return f;
// look for mainline style id
f = parse_mainline_style(p);
if (f) return f;
return f;
}
std::string identify_client(peer_id const& p)
{
peer_id::const_iterator PID = p.begin();
boost::optional<fingerprint> f;
if (p.is_all_zeros()) return "Unknown";
// ----------------------
// non standard encodings
// ----------------------
if (find_string(PID, "Deadman Walking-")) return "Deadman";
if (find_string(PID + 5, "Azureus")) return "Azureus 2.0.3.2";
if (find_string(PID, "DansClient")) return "XanTorrent";
if (find_string(PID + 4, "btfans")) return "SimpleBT";
if (find_string(PID, "PRC.P---")) return "Bittorrent Plus! II";
if (find_string(PID, "P87.P---")) return "Bittorrent Plus!";
if (find_string(PID, "S587Plus")) return "Bittorrent Plus!";
if (find_string(PID, "martini")) return "Martini Man";
if (find_string(PID, "Plus---")) return "Bittorrent Plus";
if (find_string(PID, "turbobt")) return "TurboBT";
if (find_string(PID, "a00---0")) return "Swarmy";
if (find_string(PID, "a02---0")) return "Swarmy";
if (find_string(PID, "T00---0")) return "Teeweety";
if (find_string(PID, "BTDWV-")) return "Deadman Walking";
if (find_string(PID + 2, "BS")) return "BitSpirit";
if (find_string(PID, "btuga")) return "BTugaXP";
if (find_string(PID, "oernu")) return "BTugaXP";
if (find_string(PID, "Mbrst")) return "Burst!";
if (find_string(PID, "Plus")) return "Plus!";
if (find_string(PID, "-Qt-")) return "Qt";
if (find_string(PID, "exbc")) return "BitComet";
if (find_string(PID, "-G3")) return "G3 Torrent";
if (find_string(PID, "XBT")) return "XBT";
if (find_string(PID, "OP")) return "Opera";
if (find_string(PID, "-BOW") && PID[7] == '-')
return "Bits on Wheels " + std::string(PID + 4, PID + 7);
if (find_string(PID, "eX"))
{
std::string user(PID + 2, PID + 14);
return std::string("eXeem ('") + user.c_str() + "')";
}
if (std::equal(PID, PID + 13, "\0\0\0\0\0\0\0\0\0\0\0\0\x97"))
return "Experimental 3.2.1b2";
if (std::equal(PID, PID + 13, "\0\0\0\0\0\0\0\0\0\0\0\0\0"))
return "Experimental 3.1";
// look for azureus style id
f = parse_az_style(p);
if (f) return lookup(*f);
// look for shadow style id
f = parse_shadow_style(p);
if (f) return lookup(*f);
// look for mainline style id
f = parse_mainline_style(p);
if (f) return lookup(*f);
if (std::equal(PID, PID + 12, "\0\0\0\0\0\0\0\0\0\0\0\0"))
return "Generic";
std::string unknown("Unknown [");
for (peer_id::const_iterator i = p.begin(); i != p.end(); ++i)
{
unknown += std::isprint(*i)?*i:'.';
}
unknown += "]";
return unknown;
}
}
<|endoftext|> |
<commit_before><commit_msg>use the center of the chart as camera direction<commit_after><|endoftext|> |
<commit_before><commit_msg>add scroll animation for benchmark<commit_after><|endoftext|> |
<commit_before><commit_msg>remove global variable<commit_after><|endoftext|> |
<commit_before>// Copyright (c) 2011 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "chrome/browser/chromeos/frame/bubble_window.h"
#include <gtk/gtk.h>
#include "chrome/browser/chromeos/frame/bubble_frame_view.h"
#include "chrome/browser/chromeos/wm_ipc.h"
#include "third_party/cros/chromeos_wm_ipc_enums.h"
#include "ui/gfx/skia_utils_gtk.h"
#include "views/window/non_client_view.h"
namespace {
bool IsInsideCircle(int x0, int y0, int x1, int y1, int r) {
return (x0 - x1) * (x0 - x1) + (y0 - y1) * (y0 - y1) <= r * r;
}
void SetRegionUnionWithPoint(int i, int j, GdkRegion* region) {
GdkRectangle rect = {i, j, 1, 1};
gdk_region_union_with_rect(region, &rect);
}
} // namespace
namespace chromeos {
// static
const SkColor BubbleWindow::kBackgroundColor = SK_ColorWHITE;
BubbleWindow::BubbleWindow() {
MakeTransparent();
}
void BubbleWindow::InitNativeWidget(const views::Widget::InitParams& params) {
views::WindowGtk::InitNativeWidget(params);
// Turn on double buffering so that the hosted GtkWidgets does not
// flash as in http://crosbug.com/9065.
EnableDoubleBuffer(true);
GdkColor background_color = gfx::SkColorToGdkColor(kBackgroundColor);
gtk_widget_modify_bg(GetNativeView(), GTK_STATE_NORMAL, &background_color);
// A work-around for http://crosbug.com/8538. All GdkWindow of top-level
// GtkWindow should participate _NET_WM_SYNC_REQUEST protocol and window
// manager should only show the window after getting notified. And we
// should only notify window manager after at least one paint is done.
// TODO(xiyuan): Figure out the right fix.
gtk_widget_realize(GetNativeView());
gdk_window_set_back_pixmap(GetNativeView()->window, NULL, FALSE);
gtk_widget_realize(window_contents());
gdk_window_set_back_pixmap(window_contents()->window, NULL, FALSE);
}
void BubbleWindow::TrimMargins(int margin_left, int margin_right,
int margin_top, int margin_bottom,
int border_radius) {
gfx::Size size = non_client_view()->GetPreferredSize();
const int w = size.width() - margin_left - margin_right;
const int h = size.height() - margin_top - margin_bottom;
GdkRectangle rect0 = {0, border_radius, w, h - 2 * border_radius};
GdkRectangle rect1 = {border_radius, 0, w - 2 * border_radius, h};
GdkRegion* region = gdk_region_rectangle(&rect0);
gdk_region_union_with_rect(region, &rect1);
// Top Left
for (int i = 0; i < border_radius; ++i) {
for (int j = 0; j < border_radius; ++j) {
if (IsInsideCircle(i + 0.5, j + 0.5, border_radius, border_radius,
border_radius)) {
SetRegionUnionWithPoint(i, j, region);
}
}
}
// Top Right
for (int i = w - border_radius - 1; i < w; ++i) {
for (int j = 0; j < border_radius; ++j) {
if (IsInsideCircle(i + 0.5, j + 0.5, w - border_radius - 1,
border_radius, border_radius)) {
SetRegionUnionWithPoint(i, j, region);
}
}
}
// Bottom Left
for (int i = 0; i < border_radius; ++i) {
for (int j = h - border_radius - 1; j < h; ++j) {
if (IsInsideCircle(i + 0.5, j + 0.5, border_radius, h - border_radius - 1,
border_radius)) {
SetRegionUnionWithPoint(i, j, region);
}
}
}
// Bottom Right
for (int i = w - border_radius - 1; i < w; ++i) {
for (int j = h - border_radius - 1; j < h; ++j) {
if (IsInsideCircle(i + 0.5, j + 0.5, w - border_radius - 1,
h - border_radius - 1, border_radius)) {
SetRegionUnionWithPoint(i, j, region);
}
}
}
gdk_window_shape_combine_region(window_contents()->window, region,
margin_left, margin_top);
gdk_region_destroy(region);
}
views::Window* BubbleWindow::Create(
gfx::NativeWindow parent,
const gfx::Rect& bounds,
Style style,
views::WindowDelegate* window_delegate) {
views::Window* window = new BubbleWindow();
window->non_client_view()->SetFrameView(
new BubbleFrameView(window, window_delegate, style));
views::Window::InitParams params(window_delegate);
params.parent_window = parent;
params.widget_init_params.bounds = bounds;
window->InitWindow(params);
if (style == STYLE_XSHAPE) {
const int kMarginLeft = 14;
const int kMarginRight = 14;
const int kMarginTop = 12;
const int kMarginBottom = 16;
const int kBorderRadius = 8;
static_cast<BubbleWindow*>(window->native_window())->
TrimMargins(kMarginLeft, kMarginRight, kMarginTop, kMarginBottom,
kBorderRadius);
}
return window;
}
} // namespace chromeos
<commit_msg>Partial fix for ChromeOS regression from chrome:72040 Set the widget parent for BubbleWindow.<commit_after>// Copyright (c) 2011 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "chrome/browser/chromeos/frame/bubble_window.h"
#include <gtk/gtk.h>
#include "chrome/browser/chromeos/frame/bubble_frame_view.h"
#include "chrome/browser/chromeos/wm_ipc.h"
#include "third_party/cros/chromeos_wm_ipc_enums.h"
#include "ui/gfx/skia_utils_gtk.h"
#include "views/window/non_client_view.h"
namespace {
bool IsInsideCircle(int x0, int y0, int x1, int y1, int r) {
return (x0 - x1) * (x0 - x1) + (y0 - y1) * (y0 - y1) <= r * r;
}
void SetRegionUnionWithPoint(int i, int j, GdkRegion* region) {
GdkRectangle rect = {i, j, 1, 1};
gdk_region_union_with_rect(region, &rect);
}
} // namespace
namespace chromeos {
// static
const SkColor BubbleWindow::kBackgroundColor = SK_ColorWHITE;
BubbleWindow::BubbleWindow() {
MakeTransparent();
}
void BubbleWindow::InitNativeWidget(const views::Widget::InitParams& params) {
views::WindowGtk::InitNativeWidget(params);
// Turn on double buffering so that the hosted GtkWidgets does not
// flash as in http://crosbug.com/9065.
EnableDoubleBuffer(true);
GdkColor background_color = gfx::SkColorToGdkColor(kBackgroundColor);
gtk_widget_modify_bg(GetNativeView(), GTK_STATE_NORMAL, &background_color);
// A work-around for http://crosbug.com/8538. All GdkWindow of top-level
// GtkWindow should participate _NET_WM_SYNC_REQUEST protocol and window
// manager should only show the window after getting notified. And we
// should only notify window manager after at least one paint is done.
// TODO(xiyuan): Figure out the right fix.
gtk_widget_realize(GetNativeView());
gdk_window_set_back_pixmap(GetNativeView()->window, NULL, FALSE);
gtk_widget_realize(window_contents());
gdk_window_set_back_pixmap(window_contents()->window, NULL, FALSE);
}
void BubbleWindow::TrimMargins(int margin_left, int margin_right,
int margin_top, int margin_bottom,
int border_radius) {
gfx::Size size = non_client_view()->GetPreferredSize();
const int w = size.width() - margin_left - margin_right;
const int h = size.height() - margin_top - margin_bottom;
GdkRectangle rect0 = {0, border_radius, w, h - 2 * border_radius};
GdkRectangle rect1 = {border_radius, 0, w - 2 * border_radius, h};
GdkRegion* region = gdk_region_rectangle(&rect0);
gdk_region_union_with_rect(region, &rect1);
// Top Left
for (int i = 0; i < border_radius; ++i) {
for (int j = 0; j < border_radius; ++j) {
if (IsInsideCircle(i + 0.5, j + 0.5, border_radius, border_radius,
border_radius)) {
SetRegionUnionWithPoint(i, j, region);
}
}
}
// Top Right
for (int i = w - border_radius - 1; i < w; ++i) {
for (int j = 0; j < border_radius; ++j) {
if (IsInsideCircle(i + 0.5, j + 0.5, w - border_radius - 1,
border_radius, border_radius)) {
SetRegionUnionWithPoint(i, j, region);
}
}
}
// Bottom Left
for (int i = 0; i < border_radius; ++i) {
for (int j = h - border_radius - 1; j < h; ++j) {
if (IsInsideCircle(i + 0.5, j + 0.5, border_radius, h - border_radius - 1,
border_radius)) {
SetRegionUnionWithPoint(i, j, region);
}
}
}
// Bottom Right
for (int i = w - border_radius - 1; i < w; ++i) {
for (int j = h - border_radius - 1; j < h; ++j) {
if (IsInsideCircle(i + 0.5, j + 0.5, w - border_radius - 1,
h - border_radius - 1, border_radius)) {
SetRegionUnionWithPoint(i, j, region);
}
}
}
gdk_window_shape_combine_region(window_contents()->window, region,
margin_left, margin_top);
gdk_region_destroy(region);
}
views::Window* BubbleWindow::Create(
gfx::NativeWindow parent,
const gfx::Rect& bounds,
Style style,
views::WindowDelegate* window_delegate) {
views::Window* window = new BubbleWindow();
window->non_client_view()->SetFrameView(
new BubbleFrameView(window, window_delegate, style));
views::Window::InitParams params(window_delegate);
params.parent_window = parent;
params.widget_init_params.parent = GTK_WIDGET(parent);
params.widget_init_params.bounds = bounds;
window->InitWindow(params);
if (style == STYLE_XSHAPE) {
const int kMarginLeft = 14;
const int kMarginRight = 14;
const int kMarginTop = 12;
const int kMarginBottom = 16;
const int kBorderRadius = 8;
static_cast<BubbleWindow*>(window->native_window())->
TrimMargins(kMarginLeft, kMarginRight, kMarginTop, kMarginBottom,
kBorderRadius);
}
return window;
}
} // namespace chromeos
<|endoftext|> |
<commit_before>// Licensed GNU LGPL v2.1 or later: http://www.gnu.org/licenses/lgpl.html
#ifndef __BSE_BCORE_HH__
#define __BSE_BCORE_HH__
#ifdef BSE_CONVENIENCE
#define RAPICORN_CONVENIENCE BSE_CONVENIENCE
#endif
#include <rapicorn-core.hh>
#ifdef RAPICORN_CONVENIENCE
#undef fatal // avoid easy clashes
#endif
#include <sfi/glib-extra.hh>
namespace Bse {
using namespace Rapicorn;
using Rapicorn::uint8;
using Rapicorn::uint16;
using Rapicorn::uint32;
using Rapicorn::uint64;
using Rapicorn::int8;
using Rapicorn::int16;
using Rapicorn::int32;
using Rapicorn::int64;
using Rapicorn::unichar;
using Rapicorn::String;
using Rapicorn::string_format;
using Rapicorn::printout;
using Rapicorn::printerr;
namespace Path = Rapicorn::Path;
// == Utility Macros ==
#define BSE_ISLIKELY(expr) RAPICORN_ISLIKELY(expr) ///< Compiler hint that @a expr is likely to be true.
#define BSE_UNLIKELY(expr) RAPICORN_UNLIKELY(expr) ///< Compiler hint that @a expr is unlikely to be true.
#define BSE_LIKELY BSE_ISLIKELY ///< Compiler hint that @a expr is likely to be true.
#define BSE_ABS(a) ((a) < 0 ? -(a) : (a)) ///< Yield the absolute value of @a a.
#define BSE_MIN(a,b) ((a) <= (b) ? (a) : (b)) ///< Yield the smaller value of @a a and @a b.
#define BSE_MAX(a,b) ((a) >= (b) ? (a) : (b)) ///< Yield the greater value of @a a and @a b.
#define BSE_CLAMP(v,mi,ma) ((v) < (mi) ? (mi) : ((v) > (ma) ? (ma) : (v))) ///< Yield @a v clamped to [ @a mi .. @a ma ].
#define BSE_ARRAY_SIZE(array) (sizeof (array) / sizeof ((array)[0])) ///< Yield the number of C @a array elements.
#define BSE_ALIGN(size, base) ((base) * (((size) + (base) - 1) / (base))) ///< Round up @a size to multiples of @a base.
#define BSE_CPP_STRINGIFY(s) RAPICORN_CPP_STRINGIFY(s) ///< Turn @a s into a C string literal.
#define BSE__HERE__ RAPICORN__HERE__ ///< Shorthand for a string literal containing __FILE__ ":" __LINE__
#define BSE_PURE RAPICORN_PURE ///< A <a href="https://gcc.gnu.org/onlinedocs/gcc/Common-Function-Attributes.html">GCC Attribute</a>.
#define BSE_MALLOC RAPICORN_MALLOC ///< A <a href="https://gcc.gnu.org/onlinedocs/gcc/Common-Function-Attributes.html">GCC Attribute</a>.
#define BSE_SENTINEL RAPICORN_SENTINEL ///< A <a href="https://gcc.gnu.org/onlinedocs/gcc/Common-Function-Attributes.html">GCC Attribute</a>.
#define BSE_NORETURN RAPICORN_NORETURN ///< A <a href="https://gcc.gnu.org/onlinedocs/gcc/Common-Function-Attributes.html">GCC Attribute</a>.
#define BSE_CONST RAPICORN_CONST ///< A <a href="https://gcc.gnu.org/onlinedocs/gcc/Common-Function-Attributes.html">GCC Attribute</a>.
#define BSE_UNUSED RAPICORN_UNUSED ///< A <a href="https://gcc.gnu.org/onlinedocs/gcc/Common-Function-Attributes.html">GCC Attribute</a>.
#define BSE_USED RAPICORN_USED ///< A <a href="https://gcc.gnu.org/onlinedocs/gcc/Common-Function-Attributes.html">GCC Attribute</a>.
#define BSE_NO_INSTRUMENT RAPICORN_NO_INSTRUMENT ///< A <a href="https://gcc.gnu.org/onlinedocs/gcc/Common-Function-Attributes.html">GCC Attribute</a>.
#define BSE_DEPRECATED RAPICORN_DEPRECATED ///< A <a href="https://gcc.gnu.org/onlinedocs/gcc/Common-Function-Attributes.html">GCC Attribute</a>.
#define BSE_ALWAYS_INLINE RAPICORN_ALWAYS_INLINE ///< A <a href="https://gcc.gnu.org/onlinedocs/gcc/Common-Function-Attributes.html">GCC Attribute</a>.
#define BSE_NOINLINE RAPICORN_NOINLINE ///< A <a href="https://gcc.gnu.org/onlinedocs/gcc/Common-Function-Attributes.html">GCC Attribute</a>.
#define BSE_CONSTRUCTOR RAPICORN_CONSTRUCTOR ///< A <a href="https://gcc.gnu.org/onlinedocs/gcc/Common-Function-Attributes.html">GCC Attribute</a>.
#define BSE_MAY_ALIAS RAPICORN_MAY_ALIAS ///< A <a href="https://gcc.gnu.org/onlinedocs/gcc/Common-Type-Attributes.html">GCC Attribute</a>.
#define BSE_CLASS_NON_COPYABLE(ClassName) RAPICORN_CLASS_NON_COPYABLE (ClassName) ///< Delete copy ctor and assignment operator.
#define BSE_DECLARE_VLA(Type, var, count) RAPICORN_DECLARE_VLA (Type, var, count) ///< Declare a variable length array (clang++ uses std::vector<>).
// == Path Name Macros ==
#ifdef _WIN32 // includes _WIN64
#undef BSE_UNIX_PATHS ///< Undefined on _WIN32 and _WIN64, defined on Unix.
#define BSE_DOS_PATHS 1 ///< Undefined on Unix-like systems, defined on _WIN32 and _WIN64.
#else // !_WIN32
#define BSE_UNIX_PATHS 1 ///< Undefined on _WIN32 and _WIN64, defined on Unix.
#undef BSE_DOS_PATHS ///< Undefined on Unix-like systems, defined on _WIN32 and _WIN64.
#endif // !_WIN32
#define BSE_DIR_SEPARATOR RAPICORN_DIR_SEPARATOR ///< A '/' on Unix-like systems, a '\\' on _WIN32.
#define BSE_DIR_SEPARATOR_S RAPICORN_DIR_SEPARATOR_S ///< A "/" on Unix-like systems, a "\\" on _WIN32.
#define BSE_SEARCHPATH_SEPARATOR RAPICORN_SEARCHPATH_SEPARATOR ///< A ':' on Unix-like systems, a ';' on _WIN32.
#define BSE_SEARCHPATH_SEPARATOR_S RAPICORN_SEARCHPATH_SEPARATOR_S ///< A ":" on Unix-like systems, a ";" on _WIN32.
#define BSE_IS_ABSPATH(p) RAPICORN_IS_ABSPATH (p) ///< Checks root directory path component, plus drive letter on _WIN32.
// == Diagnostics ==
template<class ...Args> void fatal (const char *format, const Args &...args) RAPICORN_NORETURN;
template<class ...Args> void warning (const char *format, const Args &...args);
template<class ...Args> void warn (const char *format, const Args &...args);
template<class ...Args> void info (const char *format, const Args &...args);
template<class ...Args> inline void dump (const char *conditional, const char *format, const Args &...args) RAPICORN_ALWAYS_INLINE;
template<class ...Args> inline void debug (const char *conditional, const char *format, const Args &...args) RAPICORN_ALWAYS_INLINE;
inline bool debug_enabled (const char *conditional) RAPICORN_ALWAYS_INLINE BSE_PURE;
// == Legacy ==
inline bool BSE_DEPRECATED bse_debug_enabled (const char *k) { return debug_enabled (k); }
// == Internal Implementation Details ==
namespace Internal {
extern bool debug_any_enabled; //< Indicates if $BSE_DEBUG enables some debug settings.
bool debug_key_enabled (const char *conditional) BSE_PURE;
void diagnostic (char kind, const std::string &message);
void force_abort () RAPICORN_NORETURN;
} // Internal
/// Issue a printf-like message if @a conditional is enabled by $BSE_DEBUG.
template<class ...Args> inline void RAPICORN_ALWAYS_INLINE
dump (const char *conditional, const char *format, const Args &...args)
{
if (BSE_UNLIKELY (Internal::debug_any_enabled) && Internal::debug_key_enabled (conditional))
Internal::diagnostic (' ', string_format (format, args...));
}
/// Issue a printf-like debugging message if @a conditional is enabled by $BSE_DEBUG.
template<class ...Args> inline void RAPICORN_ALWAYS_INLINE
debug (const char *conditional, const char *format, const Args &...args)
{
if (BSE_UNLIKELY (Internal::debug_any_enabled) && Internal::debug_key_enabled (conditional))
Internal::diagnostic ('D', string_format (format, args...));
}
/// Check if @a conditional is enabled by $BSE_DEBUG.
inline bool RAPICORN_ALWAYS_INLINE BSE_PURE
debug_enabled (const char *conditional)
{
if (BSE_UNLIKELY (Internal::debug_any_enabled))
return Internal::debug_key_enabled (conditional);
return false;
}
/// Issue a printf-like message and abort the program, this function will not return.
template<class ...Args> void RAPICORN_NORETURN
fatal (const char *format, const Args &...args)
{
Internal::diagnostic ('F', string_format (format, args...));
Internal::force_abort();
}
/// Issue a printf-like warning message.
template<class ...Args> void RAPICORN_NORETURN
warn (const char *format, const Args &...args)
{
Internal::diagnostic ('W', string_format (format, args...));
}
/// Issue a printf-like warning message.
template<class ...Args> void RAPICORN_NORETURN
warning (const char *format, const Args &...args)
{
Internal::diagnostic ('W', string_format (format, args...));
}
/// Issue an informative printf-like message.
template<class ...Args> void RAPICORN_NORETURN
info (const char *format, const Args &...args)
{
Internal::diagnostic ('I', string_format (format, args...));
}
} // Bse
#endif // __BSE_BCORE_HH__
<commit_msg>SFI: remove deprecated bse_debug_enabled<commit_after>// Licensed GNU LGPL v2.1 or later: http://www.gnu.org/licenses/lgpl.html
#ifndef __BSE_BCORE_HH__
#define __BSE_BCORE_HH__
#ifdef BSE_CONVENIENCE
#define RAPICORN_CONVENIENCE BSE_CONVENIENCE
#endif
#include <rapicorn-core.hh>
#ifdef RAPICORN_CONVENIENCE
#undef fatal // avoid easy clashes
#endif
#include <sfi/glib-extra.hh>
namespace Bse {
using namespace Rapicorn;
using Rapicorn::uint8;
using Rapicorn::uint16;
using Rapicorn::uint32;
using Rapicorn::uint64;
using Rapicorn::int8;
using Rapicorn::int16;
using Rapicorn::int32;
using Rapicorn::int64;
using Rapicorn::unichar;
using Rapicorn::String;
using Rapicorn::string_format;
using Rapicorn::printout;
using Rapicorn::printerr;
namespace Path = Rapicorn::Path;
// == Utility Macros ==
#define BSE_ISLIKELY(expr) RAPICORN_ISLIKELY(expr) ///< Compiler hint that @a expr is likely to be true.
#define BSE_UNLIKELY(expr) RAPICORN_UNLIKELY(expr) ///< Compiler hint that @a expr is unlikely to be true.
#define BSE_LIKELY BSE_ISLIKELY ///< Compiler hint that @a expr is likely to be true.
#define BSE_ABS(a) ((a) < 0 ? -(a) : (a)) ///< Yield the absolute value of @a a.
#define BSE_MIN(a,b) ((a) <= (b) ? (a) : (b)) ///< Yield the smaller value of @a a and @a b.
#define BSE_MAX(a,b) ((a) >= (b) ? (a) : (b)) ///< Yield the greater value of @a a and @a b.
#define BSE_CLAMP(v,mi,ma) ((v) < (mi) ? (mi) : ((v) > (ma) ? (ma) : (v))) ///< Yield @a v clamped to [ @a mi .. @a ma ].
#define BSE_ARRAY_SIZE(array) (sizeof (array) / sizeof ((array)[0])) ///< Yield the number of C @a array elements.
#define BSE_ALIGN(size, base) ((base) * (((size) + (base) - 1) / (base))) ///< Round up @a size to multiples of @a base.
#define BSE_CPP_STRINGIFY(s) RAPICORN_CPP_STRINGIFY(s) ///< Turn @a s into a C string literal.
#define BSE__HERE__ RAPICORN__HERE__ ///< Shorthand for a string literal containing __FILE__ ":" __LINE__
#define BSE_PURE RAPICORN_PURE ///< A <a href="https://gcc.gnu.org/onlinedocs/gcc/Common-Function-Attributes.html">GCC Attribute</a>.
#define BSE_MALLOC RAPICORN_MALLOC ///< A <a href="https://gcc.gnu.org/onlinedocs/gcc/Common-Function-Attributes.html">GCC Attribute</a>.
#define BSE_SENTINEL RAPICORN_SENTINEL ///< A <a href="https://gcc.gnu.org/onlinedocs/gcc/Common-Function-Attributes.html">GCC Attribute</a>.
#define BSE_NORETURN RAPICORN_NORETURN ///< A <a href="https://gcc.gnu.org/onlinedocs/gcc/Common-Function-Attributes.html">GCC Attribute</a>.
#define BSE_CONST RAPICORN_CONST ///< A <a href="https://gcc.gnu.org/onlinedocs/gcc/Common-Function-Attributes.html">GCC Attribute</a>.
#define BSE_UNUSED RAPICORN_UNUSED ///< A <a href="https://gcc.gnu.org/onlinedocs/gcc/Common-Function-Attributes.html">GCC Attribute</a>.
#define BSE_USED RAPICORN_USED ///< A <a href="https://gcc.gnu.org/onlinedocs/gcc/Common-Function-Attributes.html">GCC Attribute</a>.
#define BSE_NO_INSTRUMENT RAPICORN_NO_INSTRUMENT ///< A <a href="https://gcc.gnu.org/onlinedocs/gcc/Common-Function-Attributes.html">GCC Attribute</a>.
#define BSE_DEPRECATED RAPICORN_DEPRECATED ///< A <a href="https://gcc.gnu.org/onlinedocs/gcc/Common-Function-Attributes.html">GCC Attribute</a>.
#define BSE_ALWAYS_INLINE RAPICORN_ALWAYS_INLINE ///< A <a href="https://gcc.gnu.org/onlinedocs/gcc/Common-Function-Attributes.html">GCC Attribute</a>.
#define BSE_NOINLINE RAPICORN_NOINLINE ///< A <a href="https://gcc.gnu.org/onlinedocs/gcc/Common-Function-Attributes.html">GCC Attribute</a>.
#define BSE_CONSTRUCTOR RAPICORN_CONSTRUCTOR ///< A <a href="https://gcc.gnu.org/onlinedocs/gcc/Common-Function-Attributes.html">GCC Attribute</a>.
#define BSE_MAY_ALIAS RAPICORN_MAY_ALIAS ///< A <a href="https://gcc.gnu.org/onlinedocs/gcc/Common-Type-Attributes.html">GCC Attribute</a>.
#define BSE_CLASS_NON_COPYABLE(ClassName) RAPICORN_CLASS_NON_COPYABLE (ClassName) ///< Delete copy ctor and assignment operator.
#define BSE_DECLARE_VLA(Type, var, count) RAPICORN_DECLARE_VLA (Type, var, count) ///< Declare a variable length array (clang++ uses std::vector<>).
// == Path Name Macros ==
#ifdef _WIN32 // includes _WIN64
#undef BSE_UNIX_PATHS ///< Undefined on _WIN32 and _WIN64, defined on Unix.
#define BSE_DOS_PATHS 1 ///< Undefined on Unix-like systems, defined on _WIN32 and _WIN64.
#else // !_WIN32
#define BSE_UNIX_PATHS 1 ///< Undefined on _WIN32 and _WIN64, defined on Unix.
#undef BSE_DOS_PATHS ///< Undefined on Unix-like systems, defined on _WIN32 and _WIN64.
#endif // !_WIN32
#define BSE_DIR_SEPARATOR RAPICORN_DIR_SEPARATOR ///< A '/' on Unix-like systems, a '\\' on _WIN32.
#define BSE_DIR_SEPARATOR_S RAPICORN_DIR_SEPARATOR_S ///< A "/" on Unix-like systems, a "\\" on _WIN32.
#define BSE_SEARCHPATH_SEPARATOR RAPICORN_SEARCHPATH_SEPARATOR ///< A ':' on Unix-like systems, a ';' on _WIN32.
#define BSE_SEARCHPATH_SEPARATOR_S RAPICORN_SEARCHPATH_SEPARATOR_S ///< A ":" on Unix-like systems, a ";" on _WIN32.
#define BSE_IS_ABSPATH(p) RAPICORN_IS_ABSPATH (p) ///< Checks root directory path component, plus drive letter on _WIN32.
// == Diagnostics ==
template<class ...Args> void fatal (const char *format, const Args &...args) RAPICORN_NORETURN;
template<class ...Args> void warning (const char *format, const Args &...args);
template<class ...Args> void warn (const char *format, const Args &...args);
template<class ...Args> void info (const char *format, const Args &...args);
template<class ...Args> inline void dump (const char *conditional, const char *format, const Args &...args) RAPICORN_ALWAYS_INLINE;
template<class ...Args> inline void debug (const char *conditional, const char *format, const Args &...args) RAPICORN_ALWAYS_INLINE;
inline bool debug_enabled (const char *conditional) RAPICORN_ALWAYS_INLINE BSE_PURE;
// == Internal Implementation Details ==
namespace Internal {
extern bool debug_any_enabled; //< Indicates if $BSE_DEBUG enables some debug settings.
bool debug_key_enabled (const char *conditional) BSE_PURE;
void diagnostic (char kind, const std::string &message);
void force_abort () RAPICORN_NORETURN;
} // Internal
/// Issue a printf-like message if @a conditional is enabled by $BSE_DEBUG.
template<class ...Args> inline void RAPICORN_ALWAYS_INLINE
dump (const char *conditional, const char *format, const Args &...args)
{
if (BSE_UNLIKELY (Internal::debug_any_enabled) && Internal::debug_key_enabled (conditional))
Internal::diagnostic (' ', string_format (format, args...));
}
/// Issue a printf-like debugging message if @a conditional is enabled by $BSE_DEBUG.
template<class ...Args> inline void RAPICORN_ALWAYS_INLINE
debug (const char *conditional, const char *format, const Args &...args)
{
if (BSE_UNLIKELY (Internal::debug_any_enabled) && Internal::debug_key_enabled (conditional))
Internal::diagnostic ('D', string_format (format, args...));
}
/// Check if @a conditional is enabled by $BSE_DEBUG.
inline bool RAPICORN_ALWAYS_INLINE BSE_PURE
debug_enabled (const char *conditional)
{
if (BSE_UNLIKELY (Internal::debug_any_enabled))
return Internal::debug_key_enabled (conditional);
return false;
}
/// Issue a printf-like message and abort the program, this function will not return.
template<class ...Args> void RAPICORN_NORETURN
fatal (const char *format, const Args &...args)
{
Internal::diagnostic ('F', string_format (format, args...));
Internal::force_abort();
}
/// Issue a printf-like warning message.
template<class ...Args> void RAPICORN_NORETURN
warn (const char *format, const Args &...args)
{
Internal::diagnostic ('W', string_format (format, args...));
}
/// Issue a printf-like warning message.
template<class ...Args> void RAPICORN_NORETURN
warning (const char *format, const Args &...args)
{
Internal::diagnostic ('W', string_format (format, args...));
}
/// Issue an informative printf-like message.
template<class ...Args> void RAPICORN_NORETURN
info (const char *format, const Args &...args)
{
Internal::diagnostic ('I', string_format (format, args...));
}
} // Bse
#endif // __BSE_BCORE_HH__
<|endoftext|> |
<commit_before>#include "messages.h"
Messages::Messages(peer *peerToConnect, QObject *parent) : QObject(parent), mPeer(peerToConnect)
{
//here we create peerconnection session
}
Messages::~Messages()
{
}
Messages::ArmaMessage Messages::createRegularMessage(Session & session, const QString & message) {
ArmaMessage ret;
SessionKey & key = session.getKey();
ret.append(session.getMyName());
ret.append(Messages::armaSeparator);
ret.append(session.getPartnerName());
ret.append(Messages::armaSeparator);
ret.append(QDateTime::currentMSecsSinceEpoch());
ret.append(Messages::armaSeparator);
if (!key.isMyDHCreated()) {
ret.append('A' + Messages::RegularMessageDH);
ret.append(Messages::armaSeparator);
ret.append(key.getDH().toBase64());
}
else {
ret.append('A' + Messages::RegularMessage);
}
ret.append(Messages::armaSeparator);
ret.append(key.encrypt(message.toUtf8(), ret));
key.generateKey();
return ret;
}
bool Messages::parseMessage(Session &session, const ArmaMessage &message, Messages::ReceivedMessage &parsedMessage) {
QByteArray senderNick, receiverNick, dh;
QDateTime timestamp;
short type;
QList<QByteArray> list = message.split(armaSeparator);
if (list.size() < 4) throw new MessageException("incomplete message");
//senderNick = list[0];
//receiverNick = list[1];
timestamp.setMSecsSinceEpoch(list[2].toLongLong());
parsedMessage.timestamp = timestamp;
type = list[3].toShort();
parsedMessage.timestamp = timestamp;
QByteArray messageText;
//regularMessage
if (type == RegularMessage) {
if (list.size() != 5) throw new MessageException("incomplete message");
SessionKey& sk = session.getKey();
int contextDataLength = list[0].size() + list[1].size() + list[2].size() + list[3].size() + 1;
try{
messageText = sk.decrypt(list[4], message.left(contextDataLength));
}
catch (KryptoException e) {
return false;
}
parsedMessage.messageText = messageText;
}
//regularMessageDH
if (type == RegularMessageDH) {
if (list.size() != 6) throw new MessageException("incomplete message");
dh = list[4];
SessionKey& sk = session.getKey();
sk.setDH(dh);
int contextDataLength = list[0].size() + list[1].size() + list[2].size() + list[3].size() + list[4].size() + 1;
QByteArray messageText;
try {
messageText = sk.decrypt(list[5], message.left(contextDataLength));
}
catch (KryptoException e) {
return false;
}
parsedMessage.messageText = messageText;
}
//fileTypes
return true;
}
<commit_msg>Fixed typo<commit_after>#include "messages.h"
Messages::Messages(peer *peerToConnect, QObject *parent) : QObject(parent), mPeer(peerToConnect)
{
//here we create peerconnection session
}
Messages::~Messages()
{
}
Messages::ArmaMessage Messages::createRegularMessage(Session & session, const QString & message) {
ArmaMessage ret;
SessionKey & key = session.getKey();
ret.append(session.getMyName());
ret.append(Messages::armaSeparator);
ret.append(session.getPartnerName());
ret.append(Messages::armaSeparator);
ret.append(QDateTime::currentMSecsSinceEpoch());
ret.append(Messages::armaSeparator);
if (!key.isMyDHCreated()) {
ret.append('A' + Messages::RegularMessageDH);
ret.append(Messages::armaSeparator);
ret.append(key.getDH().toBase64());
}
else {
ret.append('A' + Messages::RegularMessage);
}
ret.append(Messages::armaSeparator);
ret.append(key.encrypt(message.toUtf8(), ret));
key.generateKey();
return ret;
}
bool Messages::parseMessage(Session &session, const ArmaMessage &message, Messages::ReceivedMessage &parsedMessage) {
QByteArray senderNick, receiverNick, dh;
QDateTime timestamp;
short type;
QList<QByteArray> list = message.split(armaSeparator);
if (list.size() < 4) throw new MessageException("incomplete message");
//senderNick = list[0];
//receiverNick = list[1];
timestamp.setMSecsSinceEpoch(list[2].toLongLong());
parsedMessage.timestamp = timestamp;
type = list[3].toShort();
QByteArray messageText;
//regularMessage
if (type == RegularMessage) {
if (list.size() != 5) throw new MessageException("incomplete message");
SessionKey& sk = session.getKey();
int contextDataLength = list[0].size() + list[1].size() + list[2].size() + list[3].size() + 1;
try{
messageText = sk.decrypt(list[4], message.left(contextDataLength));
}
catch (KryptoException e) {
return false;
}
parsedMessage.messageText = messageText;
}
//regularMessageDH
if (type == RegularMessageDH) {
if (list.size() != 6) throw new MessageException("incomplete message");
dh = list[4];
SessionKey& sk = session.getKey();
sk.setDH(dh);
int contextDataLength = list[0].size() + list[1].size() + list[2].size() + list[3].size() + list[4].size() + 1;
QByteArray messageText;
try {
messageText = sk.decrypt(list[5], message.left(contextDataLength));
}
catch (KryptoException e) {
return false;
}
parsedMessage.messageText = messageText;
}
//fileTypes
return true;
}
<|endoftext|> |
<commit_before>#include "inference_result.h"
#include "factor_graph.h"
#include <iostream>
#include <memory>
namespace dd {
InferenceResult::InferenceResult(const CompactFactorGraph &fg,
const CmdParser &opts)
: fg(fg),
opts(opts),
weight_values_normalizer(1),
nvars(fg.size.num_variables),
nweights(fg.size.num_weights),
ntallies(0),
categorical_tallies(),
agg_means(new variable_value_t[nvars]),
agg_nsamples(new num_samples_t[nvars]),
assignments_free(new variable_value_t[nvars]),
assignments_evid(new variable_value_t[nvars]),
weight_values(new weight_value_t[nweights]),
weights_isfixed(new bool[nweights]) {}
InferenceResult::InferenceResult(const CompactFactorGraph &fg,
const Weight weights[], const CmdParser &opts)
: InferenceResult(fg, opts) {
for (weight_id_t t = 0; t < nweights; ++t) {
const Weight &weight = weights[t];
weight_values[weight.id] = weight.weight;
weights_isfixed[weight.id] = weight.isfixed;
}
ntallies = 0;
for (variable_id_t t = 0; t < nvars; ++t) {
const Variable &variable = fg.variables[t];
assignments_free[variable.id] = variable.assignment_free;
assignments_evid[variable.id] = variable.assignment_evid;
if (variable.domain_type == DTYPE_CATEGORICAL) {
ntallies += variable.cardinality;
}
}
categorical_tallies.reset(new num_samples_t[ntallies]);
clear_variabletally();
}
InferenceResult::InferenceResult(const InferenceResult &other)
: InferenceResult(other.fg, other.opts) {
COPY_ARRAY_UNIQUE_PTR_MEMBER(assignments_evid, nvars);
COPY_ARRAY_UNIQUE_PTR_MEMBER(agg_means, nvars);
COPY_ARRAY_UNIQUE_PTR_MEMBER(agg_nsamples, nvars);
COPY_ARRAY_UNIQUE_PTR_MEMBER(weight_values, nweights);
COPY_ARRAY_UNIQUE_PTR_MEMBER(weights_isfixed, nweights);
ntallies = other.ntallies;
categorical_tallies.reset(new num_samples_t[ntallies]);
COPY_ARRAY_UNIQUE_PTR_MEMBER(categorical_tallies, ntallies);
}
void InferenceResult::merge_weights_from(const InferenceResult &other) {
assert(nweights == other.nweights);
for (weight_id_t j = 0; j < nweights; ++j)
weight_values[j] += other.weight_values[j];
++weight_values_normalizer;
}
void InferenceResult::average_regularize_weights(double current_stepsize) {
for (weight_id_t j = 0; j < nweights; ++j) {
weight_values[j] /= weight_values_normalizer;
if (!weights_isfixed[j]) {
switch (opts.regularization) {
case REG_L2: {
weight_values[j] *= (1.0 / (1.0 + opts.reg_param * current_stepsize));
break;
}
case REG_L1: {
weight_values[j] += opts.reg_param * (weight_values[j] < 0);
break;
}
default:
std::abort();
}
}
}
weight_values_normalizer = 1;
}
void InferenceResult::copy_weights_to(InferenceResult &other) const {
assert(nweights == other.nweights);
for (weight_id_t j = 0; j < nweights; ++j)
if (!weights_isfixed[j]) other.weight_values[j] = weight_values[j];
}
void InferenceResult::show_weights_snippet(std::ostream &output) const {
output << "LEARNING SNIPPETS (QUERY WEIGHTS):" << std::endl;
num_weights_t ct = 0;
for (weight_id_t j = 0; j < nweights; ++j) {
++ct;
output << " " << j << " " << weight_values[j] << std::endl;
if (ct % 10 == 0) {
break;
}
}
output << " ..." << std::endl;
}
void InferenceResult::dump_weights_in_text(std::ostream &text_output) const {
for (weight_id_t j = 0; j < nweights; ++j) {
text_output << j << " " << weight_values[j] << std::endl;
}
}
void InferenceResult::clear_variabletally() {
for (variable_id_t i = 0; i < nvars; ++i) {
agg_means[i] = 0.0;
agg_nsamples[i] = 0.0;
}
for (num_tallies_t i = 0; i < ntallies; ++i) {
categorical_tallies[i] = 0;
}
}
void InferenceResult::aggregate_marginals_from(const InferenceResult &other) {
// TODO maybe make this an operator+ after separating marginals from weights
assert(nvars == other.nvars);
assert(ntallies == other.ntallies);
for (variable_id_t j = 0; j < other.nvars; ++j) {
const Variable &variable = other.fg.variables[j];
agg_means[variable.id] += other.agg_means[variable.id];
agg_nsamples[variable.id] += other.agg_nsamples[variable.id];
}
for (num_tallies_t j = 0; j < other.ntallies; ++j) {
categorical_tallies[j] += other.categorical_tallies[j];
}
}
void InferenceResult::show_marginal_snippet(std::ostream &output) const {
output << "INFERENCE SNIPPETS (QUERY VARIABLES):" << std::endl;
num_variables_t ct = 0;
for (variable_id_t j = 0; j < fg.size.num_variables; ++j) {
const Variable &variable = fg.variables[j];
if (!variable.is_evid || opts.should_sample_evidence) {
++ct;
output << " " << variable.id
<< " NSAMPLE=" << agg_nsamples[variable.id] << std::endl;
switch (variable.domain_type) {
case DTYPE_BOOLEAN:
output << " @ 1 -> EXP="
<< (double)agg_means[variable.id] / agg_nsamples[variable.id]
<< std::endl;
break;
case DTYPE_CATEGORICAL: {
const auto &print_snippet = [this, &output, variable](
variable_value_t domain_value,
variable_value_index_t domain_index) {
output << " @ " << domain_value << " -> EXP="
<< 1.0 * categorical_tallies[variable.n_start_i_tally +
domain_index] /
agg_nsamples[variable.id]
<< std::endl;
};
if (variable.domain_map) { // sparse case
for (const auto &entry : *variable.domain_map)
print_snippet(entry.first, entry.second);
} else { // dense case, full domain implied
for (variable_value_index_t j = 0; j < variable.cardinality; ++j)
print_snippet(j, j);
}
break;
}
default:
std::abort();
}
if (ct % 10 == 0) {
break;
}
}
}
output << " ..." << std::endl;
}
void InferenceResult::show_marginal_histogram(std::ostream &output) const {
// show a histogram of inference results
output << "INFERENCE CALIBRATION (QUERY BINS):" << std::endl;
std::vector<num_variables_t> abc;
for (int i = 0; i <= 10; ++i) {
abc.push_back(0);
}
num_variables_t bad = 0;
for (variable_id_t j = 0; j < nvars; ++j) {
const Variable &variable = fg.variables[j];
if (!opts.should_sample_evidence && variable.is_evid) {
continue;
}
int bin =
(int)((double)agg_means[variable.id] / agg_nsamples[variable.id] * 10);
if (bin >= 0 && bin <= 10) {
++abc[bin];
} else {
++bad;
}
}
abc[9] += abc[10];
for (int i = 0; i < 10; ++i) {
output << "PROB BIN 0." << i << "~0." << (i + 1) << " --> # " << abc[i]
<< std::endl;
}
}
void InferenceResult::dump_marginals_in_text(std::ostream &text_output) const {
for (variable_id_t j = 0; j < nvars; ++j) {
const Variable &variable = fg.variables[j];
if (variable.is_evid && !opts.should_sample_evidence) {
continue;
}
switch (variable.domain_type) {
case DTYPE_BOOLEAN: {
text_output << variable.id << " " << 1 << " "
<< ((double)agg_means[variable.id] /
agg_nsamples[variable.id])
<< std::endl;
break;
}
case DTYPE_CATEGORICAL: {
const auto &print_result = [this, &text_output, variable](
variable_value_t domain_value,
variable_value_index_t domain_index) {
text_output
<< variable.id << " " << domain_value << " "
<< (1.0 *
categorical_tallies[variable.n_start_i_tally + domain_index] /
agg_nsamples[variable.id])
<< std::endl;
};
if (variable.domain_map) { // sparse domain
for (const auto &entry : *variable.domain_map)
print_result(entry.first, entry.second);
} else { // dense, full domain implied
for (variable_value_index_t k = 0; k < variable.cardinality; ++k)
print_result(k, k);
}
break;
}
default:
std::abort();
}
}
}
} // namespace dd
<commit_msg>Remove unnecessary Variable copy in lambda captures<commit_after>#include "inference_result.h"
#include "factor_graph.h"
#include <iostream>
#include <memory>
namespace dd {
InferenceResult::InferenceResult(const CompactFactorGraph &fg,
const CmdParser &opts)
: fg(fg),
opts(opts),
weight_values_normalizer(1),
nvars(fg.size.num_variables),
nweights(fg.size.num_weights),
ntallies(0),
categorical_tallies(),
agg_means(new variable_value_t[nvars]),
agg_nsamples(new num_samples_t[nvars]),
assignments_free(new variable_value_t[nvars]),
assignments_evid(new variable_value_t[nvars]),
weight_values(new weight_value_t[nweights]),
weights_isfixed(new bool[nweights]) {}
InferenceResult::InferenceResult(const CompactFactorGraph &fg,
const Weight weights[], const CmdParser &opts)
: InferenceResult(fg, opts) {
for (weight_id_t t = 0; t < nweights; ++t) {
const Weight &weight = weights[t];
weight_values[weight.id] = weight.weight;
weights_isfixed[weight.id] = weight.isfixed;
}
ntallies = 0;
for (variable_id_t t = 0; t < nvars; ++t) {
const Variable &variable = fg.variables[t];
assignments_free[variable.id] = variable.assignment_free;
assignments_evid[variable.id] = variable.assignment_evid;
if (variable.domain_type == DTYPE_CATEGORICAL) {
ntallies += variable.cardinality;
}
}
categorical_tallies.reset(new num_samples_t[ntallies]);
clear_variabletally();
}
InferenceResult::InferenceResult(const InferenceResult &other)
: InferenceResult(other.fg, other.opts) {
COPY_ARRAY_UNIQUE_PTR_MEMBER(assignments_evid, nvars);
COPY_ARRAY_UNIQUE_PTR_MEMBER(agg_means, nvars);
COPY_ARRAY_UNIQUE_PTR_MEMBER(agg_nsamples, nvars);
COPY_ARRAY_UNIQUE_PTR_MEMBER(weight_values, nweights);
COPY_ARRAY_UNIQUE_PTR_MEMBER(weights_isfixed, nweights);
ntallies = other.ntallies;
categorical_tallies.reset(new num_samples_t[ntallies]);
COPY_ARRAY_UNIQUE_PTR_MEMBER(categorical_tallies, ntallies);
}
void InferenceResult::merge_weights_from(const InferenceResult &other) {
assert(nweights == other.nweights);
for (weight_id_t j = 0; j < nweights; ++j)
weight_values[j] += other.weight_values[j];
++weight_values_normalizer;
}
void InferenceResult::average_regularize_weights(double current_stepsize) {
for (weight_id_t j = 0; j < nweights; ++j) {
weight_values[j] /= weight_values_normalizer;
if (!weights_isfixed[j]) {
switch (opts.regularization) {
case REG_L2: {
weight_values[j] *= (1.0 / (1.0 + opts.reg_param * current_stepsize));
break;
}
case REG_L1: {
weight_values[j] += opts.reg_param * (weight_values[j] < 0);
break;
}
default:
std::abort();
}
}
}
weight_values_normalizer = 1;
}
void InferenceResult::copy_weights_to(InferenceResult &other) const {
assert(nweights == other.nweights);
for (weight_id_t j = 0; j < nweights; ++j)
if (!weights_isfixed[j]) other.weight_values[j] = weight_values[j];
}
void InferenceResult::show_weights_snippet(std::ostream &output) const {
output << "LEARNING SNIPPETS (QUERY WEIGHTS):" << std::endl;
num_weights_t ct = 0;
for (weight_id_t j = 0; j < nweights; ++j) {
++ct;
output << " " << j << " " << weight_values[j] << std::endl;
if (ct % 10 == 0) {
break;
}
}
output << " ..." << std::endl;
}
void InferenceResult::dump_weights_in_text(std::ostream &text_output) const {
for (weight_id_t j = 0; j < nweights; ++j) {
text_output << j << " " << weight_values[j] << std::endl;
}
}
void InferenceResult::clear_variabletally() {
for (variable_id_t i = 0; i < nvars; ++i) {
agg_means[i] = 0.0;
agg_nsamples[i] = 0.0;
}
for (num_tallies_t i = 0; i < ntallies; ++i) {
categorical_tallies[i] = 0;
}
}
void InferenceResult::aggregate_marginals_from(const InferenceResult &other) {
// TODO maybe make this an operator+ after separating marginals from weights
assert(nvars == other.nvars);
assert(ntallies == other.ntallies);
for (variable_id_t j = 0; j < other.nvars; ++j) {
const Variable &variable = other.fg.variables[j];
agg_means[variable.id] += other.agg_means[variable.id];
agg_nsamples[variable.id] += other.agg_nsamples[variable.id];
}
for (num_tallies_t j = 0; j < other.ntallies; ++j) {
categorical_tallies[j] += other.categorical_tallies[j];
}
}
void InferenceResult::show_marginal_snippet(std::ostream &output) const {
output << "INFERENCE SNIPPETS (QUERY VARIABLES):" << std::endl;
num_variables_t ct = 0;
for (variable_id_t j = 0; j < fg.size.num_variables; ++j) {
const Variable &variable = fg.variables[j];
if (!variable.is_evid || opts.should_sample_evidence) {
++ct;
output << " " << variable.id
<< " NSAMPLE=" << agg_nsamples[variable.id] << std::endl;
switch (variable.domain_type) {
case DTYPE_BOOLEAN:
output << " @ 1 -> EXP="
<< (double)agg_means[variable.id] / agg_nsamples[variable.id]
<< std::endl;
break;
case DTYPE_CATEGORICAL: {
const auto &print_snippet = [this, &output, &variable](
variable_value_t domain_value,
variable_value_index_t domain_index) {
output << " @ " << domain_value << " -> EXP="
<< 1.0 * categorical_tallies[variable.n_start_i_tally +
domain_index] /
agg_nsamples[variable.id]
<< std::endl;
};
if (variable.domain_map) { // sparse case
for (const auto &entry : *variable.domain_map)
print_snippet(entry.first, entry.second);
} else { // dense case, full domain implied
for (variable_value_index_t j = 0; j < variable.cardinality; ++j)
print_snippet(j, j);
}
break;
}
default:
std::abort();
}
if (ct % 10 == 0) {
break;
}
}
}
output << " ..." << std::endl;
}
void InferenceResult::show_marginal_histogram(std::ostream &output) const {
// show a histogram of inference results
output << "INFERENCE CALIBRATION (QUERY BINS):" << std::endl;
std::vector<num_variables_t> abc;
for (int i = 0; i <= 10; ++i) {
abc.push_back(0);
}
num_variables_t bad = 0;
for (variable_id_t j = 0; j < nvars; ++j) {
const Variable &variable = fg.variables[j];
if (!opts.should_sample_evidence && variable.is_evid) {
continue;
}
int bin =
(int)((double)agg_means[variable.id] / agg_nsamples[variable.id] * 10);
if (bin >= 0 && bin <= 10) {
++abc[bin];
} else {
++bad;
}
}
abc[9] += abc[10];
for (int i = 0; i < 10; ++i) {
output << "PROB BIN 0." << i << "~0." << (i + 1) << " --> # " << abc[i]
<< std::endl;
}
}
void InferenceResult::dump_marginals_in_text(std::ostream &text_output) const {
for (variable_id_t j = 0; j < nvars; ++j) {
const Variable &variable = fg.variables[j];
if (variable.is_evid && !opts.should_sample_evidence) {
continue;
}
switch (variable.domain_type) {
case DTYPE_BOOLEAN: {
text_output << variable.id << " " << 1 << " "
<< ((double)agg_means[variable.id] /
agg_nsamples[variable.id])
<< std::endl;
break;
}
case DTYPE_CATEGORICAL: {
const auto &print_result = [this, &text_output, &variable](
variable_value_t domain_value,
variable_value_index_t domain_index) {
text_output
<< variable.id << " " << domain_value << " "
<< (1.0 *
categorical_tallies[variable.n_start_i_tally + domain_index] /
agg_nsamples[variable.id])
<< std::endl;
};
if (variable.domain_map) { // sparse domain
for (const auto &entry : *variable.domain_map)
print_result(entry.first, entry.second);
} else { // dense, full domain implied
for (variable_value_index_t k = 0; k < variable.cardinality; ++k)
print_result(k, k);
}
break;
}
default:
std::abort();
}
}
}
} // namespace dd
<|endoftext|> |
<commit_before>/*
* (C) Copyright 2015 ETH Zurich Systems Group (http://www.systems.ethz.ch/) and others.
*
* 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.
*
* Contributors:
* Markus Pilman <mpilman@inf.ethz.ch>
* Simon Loesing <sloesing@inf.ethz.ch>
* Thomas Etter <etterth@gmail.com>
* Kevin Bocksrocker <kevin.bocksrocker@gmail.com>
* Lucas Braun <braunl@inf.ethz.ch>
*/
#include "Transactions.hpp"
using namespace tell::db;
namespace tpcc {
StockLevelResult Transactions::stockLevel(Transaction& tx, const StockLevelIn& in) {
StockLevelResult result;
try {
auto dTableF = tx.openTable("district");
auto oTableF = tx.openTable("order");
auto olTableF = tx.openTable("order-line");
auto sTableF = tx.openTable("stock");
auto sTable = sTableF.get();
auto olTable = olTableF.get();
auto oTable = oTableF.get();
auto dTable = dTableF.get();
// get District
DistrictKey dKey{in.w_id, in.d_id};
auto districtF = tx.get(dTable, dKey.key());
auto district = districtF.get();
auto d_next_o_id = district.at("d_next_o_id").value<int32_t>();
OrderKey oKey{in.w_id, in.d_id, 0};
// get the 20 newest orders - this is not required in the benchmark,
// but it allows us to not use an index
std::vector<std::pair<int32_t, Future<Tuple>>> ordersF;
ordersF.reserve(20);
for (decltype(d_next_o_id) ol_o_id = d_next_o_id - 20; ol_o_id < d_next_o_id; ++ol_o_id) {
oKey.o_id = ol_o_id;
ordersF.emplace_back(ol_o_id, tx.get(oTable, oKey.key()));
}
// get the order-lines
std::vector<Future<Tuple>> orderlinesF;
OrderlineKey olKey{in.w_id, in.d_id, 0, 0};
for (auto& orderF : ordersF) {
olKey.o_id = orderF.first;
auto order = orderF.second.get();
auto o_ol_cnt = order.at("o_ol_cnt").value<int16_t>();
for (decltype(o_ol_cnt) ol_number = 1; ol_number <= o_ol_cnt; ++ol_number) {
olKey.ol_number = ol_number;
orderlinesF.emplace_back(tx.get(olTable, olKey.key()));
}
}
result.low_stock = 0;
// count low_stock
std::unordered_map<int32_t, Future<Tuple>> stocksF;
for (auto& olF : orderlinesF) {
auto ol = olF.get();
auto ol_i_id = ol.at("ol_i_id").value<int32_t>();
if (stocksF.count(ol_i_id) == 0) {
stocksF.emplace(ol_i_id, tx.get(sTable, tell::db::key_t{(uint64_t(in.w_id) << 4*8) | uint64_t(ol_i_id)}));
}
}
for (auto& p : stocksF) {
auto stock = p.second.get();
result.low_stock += stock.at("s_quantity").value<int32_t>();
}
tx.commit();
result.success = true;
return result;
} catch (std::exception& ex) {
result.success = false;
result.error = ex.what();
}
return result;
}
} // namespace tpcc
<commit_msg>Fixed bug in StockLevel tx (TellDB)<commit_after>/*
* (C) Copyright 2015 ETH Zurich Systems Group (http://www.systems.ethz.ch/) and others.
*
* 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.
*
* Contributors:
* Markus Pilman <mpilman@inf.ethz.ch>
* Simon Loesing <sloesing@inf.ethz.ch>
* Thomas Etter <etterth@gmail.com>
* Kevin Bocksrocker <kevin.bocksrocker@gmail.com>
* Lucas Braun <braunl@inf.ethz.ch>
*/
#include "Transactions.hpp"
using namespace tell::db;
namespace tpcc {
StockLevelResult Transactions::stockLevel(Transaction& tx, const StockLevelIn& in) {
StockLevelResult result;
try {
auto dTableF = tx.openTable("district");
auto oTableF = tx.openTable("order");
auto olTableF = tx.openTable("order-line");
auto sTableF = tx.openTable("stock");
auto sTable = sTableF.get();
auto olTable = olTableF.get();
auto oTable = oTableF.get();
auto dTable = dTableF.get();
// get District
DistrictKey dKey{in.w_id, in.d_id};
auto districtF = tx.get(dTable, dKey.key());
auto district = districtF.get();
auto d_next_o_id = district.at("d_next_o_id").value<int32_t>();
OrderKey oKey{in.w_id, in.d_id, 0};
// get the 20 newest orders - this is not required in the benchmark,
// but it allows us to not use an index
std::vector<std::pair<int32_t, Future<Tuple>>> ordersF;
ordersF.reserve(20);
for (decltype(d_next_o_id) ol_o_id = d_next_o_id - 20; ol_o_id < d_next_o_id; ++ol_o_id) {
oKey.o_id = ol_o_id;
ordersF.emplace_back(ol_o_id, tx.get(oTable, oKey.key()));
}
// get the order-lines
std::vector<Future<Tuple>> orderlinesF;
OrderlineKey olKey{in.w_id, in.d_id, 0, 0};
for (auto& orderF : ordersF) {
olKey.o_id = orderF.first;
auto order = orderF.second.get();
auto o_ol_cnt = order.at("o_ol_cnt").value<int16_t>();
for (decltype(o_ol_cnt) ol_number = 1; ol_number <= o_ol_cnt; ++ol_number) {
olKey.ol_number = ol_number;
orderlinesF.emplace_back(tx.get(olTable, olKey.key()));
}
}
result.low_stock = 0;
// count low_stock
std::unordered_map<int32_t, Future<Tuple>> stocksF;
for (auto& olF : orderlinesF) {
auto ol = olF.get();
auto ol_i_id = ol.at("ol_i_id").value<int32_t>();
if (stocksF.count(ol_i_id) == 0) {
stocksF.emplace(ol_i_id, tx.get(sTable, tell::db::key_t{(uint64_t(in.w_id) << 4*8) | uint64_t(ol_i_id)}));
}
}
for (auto& p : stocksF) {
auto stock = p.second.get();
auto quantity = stock.at("s_quantity").value<int32_t>();
if (quantity < in.threshold) {
++result.low_stock;
}
}
tx.commit();
result.success = true;
return result;
} catch (std::exception& ex) {
result.success = false;
result.error = ex.what();
}
return result;
}
} // namespace tpcc
<|endoftext|> |
<commit_before>/*
* author: Max Kellermann <mk@cm4all.com>
*/
#include "istream_deflate.hxx"
#include "istream_internal.hxx"
#include "pool.hxx"
#include "util/Cast.hxx"
#include "util/ConstBuffer.hxx"
#include "util/WritableBuffer.hxx"
#include "util/StaticFifoBuffer.hxx"
#include <daemon/log.h>
#include <zlib.h>
#include <assert.h>
struct istream_deflate {
struct istream output;
struct istream *input;
bool z_initialized, z_stream_end;
z_stream z;
bool had_input, had_output;
StaticFifoBuffer<uint8_t, 4096> buffer;
};
gcc_const
static GQuark
zlib_quark(void)
{
return g_quark_from_static_string("zlib");
}
static void
deflate_close(struct istream_deflate *defl)
{
if (defl->z_initialized) {
defl->z_initialized = false;
deflateEnd(&defl->z);
}
}
static void
deflate_abort(struct istream_deflate *defl, GError *error)
{
deflate_close(defl);
if (defl->input != nullptr)
istream_free_handler(&defl->input);
istream_deinit_abort(&defl->output, error);
}
static voidpf z_alloc
(voidpf opaque, uInt items, uInt size)
{
struct pool *pool = (struct pool *)opaque;
return p_malloc(pool, items * size);
}
static void
z_free(voidpf opaque, voidpf address)
{
(void)opaque;
(void)address;
}
static int
deflate_initialize_z(struct istream_deflate *defl)
{
if (defl->z_initialized)
return Z_OK;
defl->z.zalloc = z_alloc;
defl->z.zfree = z_free;
defl->z.opaque = defl->output.pool;
int err = deflateInit(&defl->z, Z_DEFAULT_COMPRESSION);
if (err != Z_OK) {
GError *error =
g_error_new(zlib_quark(), err,
"deflateInit(Z_FINISH) failed: %d", err);
deflate_abort(defl, error);
return err;
}
defl->z_initialized = true;
return Z_OK;
}
/**
* Submit data from the buffer to our istream handler.
*
* @return the number of bytes which were handled, or 0 if the stream
* was closed
*/
static size_t
deflate_try_write(struct istream_deflate *defl)
{
auto r = defl->buffer.Read();
assert(!r.IsEmpty());
size_t nbytes = istream_invoke_data(&defl->output, r.data, r.size);
if (nbytes == 0)
return 0;
defl->buffer.Consume(nbytes);
if (nbytes == r.size && defl->input == nullptr && defl->z_stream_end) {
deflate_close(defl);
istream_deinit_eof(&defl->output);
return 0;
}
return nbytes;
}
/**
* Starts to write to the buffer.
*
* @return a pointer to the writable buffer, or nullptr if there is no
* room (our istream handler blocks) or if the stream was closed
*/
static WritableBuffer<void>
deflate_buffer_write(struct istream_deflate *defl)
{
auto w = defl->buffer.Write();
if (w.IsEmpty() && deflate_try_write(defl) > 0)
w = defl->buffer.Write();
return w.ToVoid();
}
static void
deflate_try_flush(struct istream_deflate *defl)
{
assert(!defl->z_stream_end);
auto w = deflate_buffer_write(defl);
if (w.IsEmpty())
return;
defl->z.next_out = (Bytef *)w.data;
defl->z.avail_out = (uInt)w.size;
defl->z.next_in = nullptr;
defl->z.avail_in = 0;
int err = deflate(&defl->z, Z_SYNC_FLUSH);
if (err != Z_OK) {
GError *error =
g_error_new(zlib_quark(), err,
"deflate(Z_SYNC_FLUSH) failed: %d", err);
deflate_abort(defl, error);
return;
}
defl->buffer.Append(w.size - (size_t)defl->z.avail_out);
if (!defl->buffer.IsEmpty())
deflate_try_write(defl);
}
/**
* Read from our input until we have submitted some bytes to our
* istream handler.
*/
static void
istream_deflate_force_read(struct istream_deflate *defl)
{
bool had_input = false;
defl->had_output = false;
pool_ref(defl->output.pool);
while (1) {
defl->had_input = false;
istream_read(defl->input);
if (defl->input == nullptr || defl->had_output) {
pool_unref(defl->output.pool);
return;
}
if (!defl->had_input)
break;
had_input = true;
}
pool_unref(defl->output.pool);
if (had_input)
deflate_try_flush(defl);
}
static void
deflate_try_finish(struct istream_deflate *defl)
{
assert(!defl->z_stream_end);
auto w = deflate_buffer_write(defl);
if (w.IsEmpty())
return;
defl->z.next_out = (Bytef *)w.data;
defl->z.avail_out = (uInt)w.size;
defl->z.next_in = nullptr;
defl->z.avail_in = 0;
int err = deflate(&defl->z, Z_FINISH);
if (err == Z_STREAM_END)
defl->z_stream_end = true;
else if (err != Z_OK) {
GError *error =
g_error_new(zlib_quark(), err,
"deflate(Z_FINISH) failed: %d", err);
deflate_abort(defl, error);
return;
}
defl->buffer.Append(w.size - (size_t)defl->z.avail_out);
if (defl->z_stream_end && defl->buffer.IsEmpty()) {
deflate_close(defl);
istream_deinit_eof(&defl->output);
} else
deflate_try_write(defl);
}
/*
* istream handler
*
*/
static size_t
deflate_input_data(const void *data, size_t length, void *ctx)
{
struct istream_deflate *defl = (struct istream_deflate *)ctx;
assert(defl->input != nullptr);
auto w = deflate_buffer_write(defl);
if (w.size < 64) /* reserve space for end-of-stream marker */
return 0;
int err = deflate_initialize_z(defl);
if (err != Z_OK)
return 0;
defl->had_input = true;
defl->z.next_out = (Bytef *)w.data;
defl->z.avail_out = (uInt)w.size;
defl->z.next_in = (Bytef *)const_cast<void *>(data);
defl->z.avail_in = (uInt)length;
do {
err = deflate(&defl->z, Z_NO_FLUSH);
if (err != Z_OK) {
GError *error =
g_error_new(zlib_quark(), err,
"deflate() failed: %d", err);
deflate_abort(defl, error);
return 0;
}
size_t nbytes = w.size - (size_t)defl->z.avail_out;
if (nbytes > 0) {
defl->had_output = true;
defl->buffer.Append(nbytes);
pool_ref(defl->output.pool);
deflate_try_write(defl);
if (!defl->z_initialized) {
pool_unref(defl->output.pool);
return 0;
}
pool_unref(defl->output.pool);
} else
break;
w = deflate_buffer_write(defl);
if (w.size < 64) /* reserve space for end-of-stream marker */
break;
defl->z.next_out = (Bytef *)w.data;
defl->z.avail_out = (uInt)w.size;
} while (defl->z.avail_in > 0);
return length - (size_t)defl->z.avail_in;
}
static void
deflate_input_eof(void *ctx)
{
struct istream_deflate *defl = (struct istream_deflate *)ctx;
assert(defl->input != nullptr);
defl->input = nullptr;
int err = deflate_initialize_z(defl);
if (err != Z_OK)
return;
deflate_try_finish(defl);
}
static void
deflate_input_abort(GError *error, void *ctx)
{
struct istream_deflate *defl = (struct istream_deflate *)ctx;
assert(defl->input != nullptr);
defl->input = nullptr;
deflate_close(defl);
istream_deinit_abort(&defl->output, error);
}
static const struct istream_handler deflate_input_handler = {
.data = deflate_input_data,
.eof = deflate_input_eof,
.abort = deflate_input_abort,
};
/*
* istream implementation
*
*/
static inline struct istream_deflate *
istream_to_deflate(struct istream *istream)
{
return &ContainerCast2(*istream, &istream_deflate::output);
}
static void
istream_deflate_read(struct istream *istream)
{
struct istream_deflate *defl = istream_to_deflate(istream);
if (!defl->buffer.IsEmpty())
deflate_try_write(defl);
else if (defl->input == nullptr)
deflate_try_finish(defl);
else
istream_deflate_force_read(defl);
}
static void
istream_deflate_close(struct istream *istream)
{
struct istream_deflate *defl = istream_to_deflate(istream);
deflate_close(defl);
if (defl->input != nullptr)
istream_close_handler(defl->input);
istream_deinit(&defl->output);
}
static const struct istream_class istream_deflate = {
.read = istream_deflate_read,
.close = istream_deflate_close,
};
/*
* constructor
*
*/
struct istream *
istream_deflate_new(struct pool *pool, struct istream *input)
{
assert(input != nullptr);
assert(!istream_has_handler(input));
auto *defl = NewFromPool<struct istream_deflate>(*pool);
istream_init(&defl->output, &istream_deflate, pool);
defl->buffer.Clear();
defl->z_initialized = false;
defl->z_stream_end = false;
istream_assign_handler(&defl->input, input,
&deflate_input_handler, defl,
0);
return &defl->output;
}
<commit_msg>istream_deflate: rename the struct using CamelCase<commit_after>/*
* author: Max Kellermann <mk@cm4all.com>
*/
#include "istream_deflate.hxx"
#include "istream_internal.hxx"
#include "pool.hxx"
#include "util/Cast.hxx"
#include "util/ConstBuffer.hxx"
#include "util/WritableBuffer.hxx"
#include "util/StaticFifoBuffer.hxx"
#include <daemon/log.h>
#include <zlib.h>
#include <assert.h>
struct DeflateIstream {
struct istream output;
struct istream *input;
bool z_initialized, z_stream_end;
z_stream z;
bool had_input, had_output;
StaticFifoBuffer<uint8_t, 4096> buffer;
};
gcc_const
static GQuark
zlib_quark(void)
{
return g_quark_from_static_string("zlib");
}
static void
deflate_close(DeflateIstream *defl)
{
if (defl->z_initialized) {
defl->z_initialized = false;
deflateEnd(&defl->z);
}
}
static void
deflate_abort(DeflateIstream *defl, GError *error)
{
deflate_close(defl);
if (defl->input != nullptr)
istream_free_handler(&defl->input);
istream_deinit_abort(&defl->output, error);
}
static voidpf z_alloc
(voidpf opaque, uInt items, uInt size)
{
struct pool *pool = (struct pool *)opaque;
return p_malloc(pool, items * size);
}
static void
z_free(voidpf opaque, voidpf address)
{
(void)opaque;
(void)address;
}
static int
deflate_initialize_z(DeflateIstream *defl)
{
if (defl->z_initialized)
return Z_OK;
defl->z.zalloc = z_alloc;
defl->z.zfree = z_free;
defl->z.opaque = defl->output.pool;
int err = deflateInit(&defl->z, Z_DEFAULT_COMPRESSION);
if (err != Z_OK) {
GError *error =
g_error_new(zlib_quark(), err,
"deflateInit(Z_FINISH) failed: %d", err);
deflate_abort(defl, error);
return err;
}
defl->z_initialized = true;
return Z_OK;
}
/**
* Submit data from the buffer to our istream handler.
*
* @return the number of bytes which were handled, or 0 if the stream
* was closed
*/
static size_t
deflate_try_write(DeflateIstream *defl)
{
auto r = defl->buffer.Read();
assert(!r.IsEmpty());
size_t nbytes = istream_invoke_data(&defl->output, r.data, r.size);
if (nbytes == 0)
return 0;
defl->buffer.Consume(nbytes);
if (nbytes == r.size && defl->input == nullptr && defl->z_stream_end) {
deflate_close(defl);
istream_deinit_eof(&defl->output);
return 0;
}
return nbytes;
}
/**
* Starts to write to the buffer.
*
* @return a pointer to the writable buffer, or nullptr if there is no
* room (our istream handler blocks) or if the stream was closed
*/
static WritableBuffer<void>
deflate_buffer_write(DeflateIstream *defl)
{
auto w = defl->buffer.Write();
if (w.IsEmpty() && deflate_try_write(defl) > 0)
w = defl->buffer.Write();
return w.ToVoid();
}
static void
deflate_try_flush(DeflateIstream *defl)
{
assert(!defl->z_stream_end);
auto w = deflate_buffer_write(defl);
if (w.IsEmpty())
return;
defl->z.next_out = (Bytef *)w.data;
defl->z.avail_out = (uInt)w.size;
defl->z.next_in = nullptr;
defl->z.avail_in = 0;
int err = deflate(&defl->z, Z_SYNC_FLUSH);
if (err != Z_OK) {
GError *error =
g_error_new(zlib_quark(), err,
"deflate(Z_SYNC_FLUSH) failed: %d", err);
deflate_abort(defl, error);
return;
}
defl->buffer.Append(w.size - (size_t)defl->z.avail_out);
if (!defl->buffer.IsEmpty())
deflate_try_write(defl);
}
/**
* Read from our input until we have submitted some bytes to our
* istream handler.
*/
static void
istream_deflate_force_read(DeflateIstream *defl)
{
bool had_input = false;
defl->had_output = false;
pool_ref(defl->output.pool);
while (1) {
defl->had_input = false;
istream_read(defl->input);
if (defl->input == nullptr || defl->had_output) {
pool_unref(defl->output.pool);
return;
}
if (!defl->had_input)
break;
had_input = true;
}
pool_unref(defl->output.pool);
if (had_input)
deflate_try_flush(defl);
}
static void
deflate_try_finish(DeflateIstream *defl)
{
assert(!defl->z_stream_end);
auto w = deflate_buffer_write(defl);
if (w.IsEmpty())
return;
defl->z.next_out = (Bytef *)w.data;
defl->z.avail_out = (uInt)w.size;
defl->z.next_in = nullptr;
defl->z.avail_in = 0;
int err = deflate(&defl->z, Z_FINISH);
if (err == Z_STREAM_END)
defl->z_stream_end = true;
else if (err != Z_OK) {
GError *error =
g_error_new(zlib_quark(), err,
"deflate(Z_FINISH) failed: %d", err);
deflate_abort(defl, error);
return;
}
defl->buffer.Append(w.size - (size_t)defl->z.avail_out);
if (defl->z_stream_end && defl->buffer.IsEmpty()) {
deflate_close(defl);
istream_deinit_eof(&defl->output);
} else
deflate_try_write(defl);
}
/*
* istream handler
*
*/
static size_t
deflate_input_data(const void *data, size_t length, void *ctx)
{
DeflateIstream *defl = (DeflateIstream *)ctx;
assert(defl->input != nullptr);
auto w = deflate_buffer_write(defl);
if (w.size < 64) /* reserve space for end-of-stream marker */
return 0;
int err = deflate_initialize_z(defl);
if (err != Z_OK)
return 0;
defl->had_input = true;
defl->z.next_out = (Bytef *)w.data;
defl->z.avail_out = (uInt)w.size;
defl->z.next_in = (Bytef *)const_cast<void *>(data);
defl->z.avail_in = (uInt)length;
do {
err = deflate(&defl->z, Z_NO_FLUSH);
if (err != Z_OK) {
GError *error =
g_error_new(zlib_quark(), err,
"deflate() failed: %d", err);
deflate_abort(defl, error);
return 0;
}
size_t nbytes = w.size - (size_t)defl->z.avail_out;
if (nbytes > 0) {
defl->had_output = true;
defl->buffer.Append(nbytes);
pool_ref(defl->output.pool);
deflate_try_write(defl);
if (!defl->z_initialized) {
pool_unref(defl->output.pool);
return 0;
}
pool_unref(defl->output.pool);
} else
break;
w = deflate_buffer_write(defl);
if (w.size < 64) /* reserve space for end-of-stream marker */
break;
defl->z.next_out = (Bytef *)w.data;
defl->z.avail_out = (uInt)w.size;
} while (defl->z.avail_in > 0);
return length - (size_t)defl->z.avail_in;
}
static void
deflate_input_eof(void *ctx)
{
DeflateIstream *defl = (DeflateIstream *)ctx;
assert(defl->input != nullptr);
defl->input = nullptr;
int err = deflate_initialize_z(defl);
if (err != Z_OK)
return;
deflate_try_finish(defl);
}
static void
deflate_input_abort(GError *error, void *ctx)
{
DeflateIstream *defl = (DeflateIstream *)ctx;
assert(defl->input != nullptr);
defl->input = nullptr;
deflate_close(defl);
istream_deinit_abort(&defl->output, error);
}
static const struct istream_handler deflate_input_handler = {
.data = deflate_input_data,
.eof = deflate_input_eof,
.abort = deflate_input_abort,
};
/*
* istream implementation
*
*/
static inline DeflateIstream *
istream_to_deflate(struct istream *istream)
{
return &ContainerCast2(*istream, &DeflateIstream::output);
}
static void
istream_deflate_read(struct istream *istream)
{
DeflateIstream *defl = istream_to_deflate(istream);
if (!defl->buffer.IsEmpty())
deflate_try_write(defl);
else if (defl->input == nullptr)
deflate_try_finish(defl);
else
istream_deflate_force_read(defl);
}
static void
istream_deflate_close(struct istream *istream)
{
DeflateIstream *defl = istream_to_deflate(istream);
deflate_close(defl);
if (defl->input != nullptr)
istream_close_handler(defl->input);
istream_deinit(&defl->output);
}
static const struct istream_class istream_deflate = {
.read = istream_deflate_read,
.close = istream_deflate_close,
};
/*
* constructor
*
*/
struct istream *
istream_deflate_new(struct pool *pool, struct istream *input)
{
assert(input != nullptr);
assert(!istream_has_handler(input));
auto *defl = NewFromPool<DeflateIstream>(*pool);
istream_init(&defl->output, &istream_deflate, pool);
defl->buffer.Clear();
defl->z_initialized = false;
defl->z_stream_end = false;
istream_assign_handler(&defl->input, input,
&deflate_input_handler, defl,
0);
return &defl->output;
}
<|endoftext|> |
<commit_before>#ifndef __CLITL_HPP__
#define __CLITL_HPP__
#include <cstdio>
#include <iosfwd>
#include <locale>
#include <utility>
#ifdef UNIX
#include <sys/ioctl.h>
#include <termios.h>
#include <unistd.h>
#elif WIN32
#include <conio.h>
#include <Windows.h>
#endif
namespace clitl {
/* Color class */
enum class color {
#ifdef UNIX
VOIDSPACE = -1,
DEFAULT = 0,
BLACK = 30,
RED = 31,
GREEN = 32,
BROWN = 33,
BLUE = 34,
MAGENTA = 35,
CYAN = 36,
#elif WIN32
VOIDSPACE = -1,
DEFAULT = 7,
BLACK = 0,
RED = 4,
GREEN = 2,
BROWN = 7, // Worthless
BLUE = 1,
MAGENTA = 7, // Worthless
CYAN = 9,
#endif
};
/* Basic definitions and containers */
typedef int coord_t;
typedef int colornum_t;
template <typename T>
struct rect {
std::pair<T, T> origin;
std::pair<T, T> endpoint;
color foreground;
};
/* Output buffer */
template <typename charT, typename traits = std::char_traits<charT> >
class basic_outbuf : public std::basic_streambuf<charT, traits> {
protected:
virtual typename traits::int_type
overflow(typename traits::int_type c)
{
if (std::putchar(c) == EOF) {
return traits::eof();
}
return traits::not_eof(c);
}
};
typedef basic_outbuf<char> outbuf;
typedef basic_outbuf<wchar_t> woutbuf;
/* Output stream */
template <typename charT, typename traits = std::char_traits<charT> >
class basic_ostream : public std::basic_ostream<charT, traits> {
public:
#ifdef UNIX
struct winsize wsize;
#endif
#ifdef WIN32
HANDLE termout_handle;
CONSOLE_CURSOR_INFO termout_curinfo;
CONSOLE_SCREEN_BUFFER_INFO termout_sbufinfo;
#endif
explicit basic_ostream(basic_outbuf<charT, traits>* sb)
: std::basic_ostream<charT, traits>(sb)
{
#ifdef UNIX
wsize = { 0 };
#elif WIN32
termout_handle = GetStdHandle(STD_OUTPUT_HANDLE);
#endif
}
basic_ostream<charT, traits>& moveto(const std::pair<coord_t, coord_t>& coord)
{
#ifdef TARGET_IS_POSIX
cout << "\033[" << coord.second << ";" << coord.first << "f";
#elif WIN32
COORD pos = { static_cast<SHORT>(coord.first), static_cast<SHORT>(coord.second) };
SetConsoleCursorPosition(termout_handle, pos);
#endif
return *this;
}
std::pair<coord_t, coord_t> screensize()
{
static coord_t column;
static coord_t row;
#ifdef UNIX
column = wsize.ws_col;
row = wsize.ws_row;
#elif WIN32
GetConsoleScreenBufferInfo(termout_handle, &termout_sbufinfo);
column = static_cast<coord_t>(termout_sbufinfo.dwSize.X);
row = static_cast<coord_t>(termout_sbufinfo.dwSize.Y);
#endif
return std::pair<coord_t, coord_t>(column, row);
}
basic_ostream<charT, traits>& operator<<
(basic_ostream<charT, traits>& (*op)(basic_ostream<charT, traits>&))
{
return (*op)(*this);
}
};
typedef basic_ostream<char> ostream;
typedef basic_ostream<wchar_t> wostream;
template <typename charT, typename traits>
basic_ostream<charT, traits>& pre_process(basic_ostream<charT, traits>& os)
{
os << alternative_system_screenbuffer;
os << hide_cursor;
os << clear;
return os;
}
template <typename charT, typename traits>
basic_ostream<charT, traits>& post_process(basic_ostream<charT, traits>& os)
{
os << normal_system_screenbuffer;
os << show_cursor;
return os;
}
template <typename charT, typename traits>
basic_ostream<charT, traits>& alternative_system_screenbuffer(basic_ostream<charT, traits>& os)
{
#if UNIX
cout << "\033[?1049h"; // Use alternate screen buffer
#endif
return os;
}
template <typename charT, typename traits>
basic_ostream<charT, traits>& clear(basic_ostream<charT, traits>& os)
{
#ifdef UNIX
cout << "\033[2J";
#elif WIN32
COORD startpoint = { 0, 0 };
DWORD dw;
GetConsoleScreenBufferInfo(os.termout_handle, &os.termout_sbufinfo);
FillConsoleOutputCharacterA(os.termout_handle, ' ',
os.termout_sbufinfo.dwSize.X * os.termout_sbufinfo.dwSize.Y,
startpoint, &dw);
FillConsoleOutputAttribute(os.termout_handle,
FOREGROUND_GREEN | FOREGROUND_RED | FOREGROUND_BLUE,
os.termout_sbufinfo.dwSize.X * os.termout_sbufinfo.dwSize.Y,
startpoint, &dw);
#endif
return os;
}
template <typename charT, typename traits>
basic_ostream<charT, traits>& hide_cursor(basic_ostream<charT, traits>& os)
{
#ifdef UNIX
cout << "\033[?25l"; // Hide cursor
#elif WIN32
GetConsoleCursorInfo(os.termout_handle, &os.termout_curinfo);
os.termout_curinfo.bVisible = 0;
SetConsoleCursorInfo(os.termout_handle, &os.termout_curinfo);
#endif
return os;
}
template <typename charT, typename traits>
basic_ostream<charT, traits>& normal_system_screenbuffer(basic_ostream<charT, traits>& os)
{
#if UNIX
cout << "\033[?1049l"; // Use normal screen buffer
#endif
return os;
}
template <typename charT, typename traits>
basic_ostream<charT, traits>& refresh(basic_ostream<charT, traits>& os)
{
fflush(stdout);
return os;
}
template <typename charT, typename traits>
basic_ostream<charT, traits>& show_cursor(basic_ostream<charT, traits>& os)
{
#if UNIX
cout << "\033[?25h"; // Show cursor
#elif WIN32
CONSOLE_CURSOR_INFO termout_curinfo;
GetConsoleCursorInfo(os.termout_handle, &termout_curinfo);
termout_curinfo.bVisible = 1;
SetConsoleCursorInfo(os.termout_handle, &termout_curinfo);
#endif
return os;
}
/* Input buffer */
/* Input stream */
template <typename charT, typename traits = std::char_traits<charT> >
class basic_istream : public std::basic_istream<charT, traits> {
};
typedef basic_istream<char> istream;
typedef basic_istream<wchar_t> wistream;
}
#endif
<commit_msg>Add operator<<(, pair<string, color>)<commit_after>#ifndef __CLITL_HPP__
#define __CLITL_HPP__
#include <cstdio>
#include <iosfwd>
#include <locale>
#include <string>
#include <utility>
#ifdef UNIX
#include <sys/ioctl.h>
#include <termios.h>
#include <unistd.h>
#elif WIN32
#include <conio.h>
#include <Windows.h>
#endif
namespace clitl {
/* Color class */
enum class color {
#ifdef UNIX
VOIDSPACE = -1,
DEFAULT = 0,
BLACK = 30,
RED = 31,
GREEN = 32,
BROWN = 33,
BLUE = 34,
MAGENTA = 35,
CYAN = 36,
#elif WIN32
VOIDSPACE = -1,
DEFAULT = 7,
BLACK = 0,
RED = 4,
GREEN = 2,
BROWN = 7, // Worthless
BLUE = 1,
MAGENTA = 7, // Worthless
CYAN = 9,
#endif
};
/* Basic definitions and containers */
typedef int coord_t;
typedef int colornum_t;
template <typename T>
struct rect {
std::pair<T, T> origin;
std::pair<T, T> endpoint;
color foreground;
};
template <typename charT,
class traits = char_traits<charT>,
class Alloc = allocator<charT> >
struct colorstring {
std::basic_string<charT, traits, Alloc> str;
color foreground;
};
/* Output buffer */
template <typename charT, typename traits = std::char_traits<charT> >
class basic_outbuf : public std::basic_streambuf<charT, traits> {
protected:
virtual typename traits::int_type
overflow(typename traits::int_type c)
{
if (std::putchar(c) == EOF) {
return traits::eof();
}
return traits::not_eof(c);
}
};
typedef basic_outbuf<char> outbuf;
typedef basic_outbuf<wchar_t> woutbuf;
/* Output stream */
template <typename charT, typename traits = std::char_traits<charT> >
class basic_ostream : public std::basic_ostream<charT, traits> {
public:
#ifdef UNIX
struct winsize wsize;
#endif
#ifdef WIN32
HANDLE termout_handle;
CONSOLE_CURSOR_INFO termout_curinfo;
CONSOLE_SCREEN_BUFFER_INFO termout_sbufinfo;
#endif
explicit basic_ostream(basic_outbuf<charT, traits>* sb)
: std::basic_ostream<charT, traits>(sb)
{
#ifdef UNIX
wsize = { 0 };
#elif WIN32
termout_handle = GetStdHandle(STD_OUTPUT_HANDLE);
#endif
}
basic_ostream<charT, traits>& moveto(const std::pair<coord_t, coord_t>& coord)
{
#ifdef TARGET_IS_POSIX
cout << "\033[" << coord.second << ";" << coord.first << "f";
#elif WIN32
COORD pos = { static_cast<SHORT>(coord.first), static_cast<SHORT>(coord.second) };
SetConsoleCursorPosition(termout_handle, pos);
#endif
return *this;
}
std::pair<coord_t, coord_t> screensize()
{
static coord_t column;
static coord_t row;
#ifdef UNIX
column = wsize.ws_col;
row = wsize.ws_row;
#elif WIN32
GetConsoleScreenBufferInfo(termout_handle, &termout_sbufinfo);
column = static_cast<coord_t>(termout_sbufinfo.dwSize.X);
row = static_cast<coord_t>(termout_sbufinfo.dwSize.Y);
#endif
return std::pair<coord_t, coord_t>(column, row);
}
basic_ostream<charT, traits>& operator<<
(basic_ostream<charT, traits>& (*op)(basic_ostream<charT, traits>&))
{
return (*op)(*this);
}
};
typedef basic_ostream<char> ostream;
typedef basic_ostream<wchar_t> wostream;
template <typename charT, typename traits>
basic_ostream<charT, traits>& pre_process(basic_ostream<charT, traits>& os)
{
os << alternative_system_screenbuffer;
os << hide_cursor;
os << clear;
return os;
}
template <typename charT, typename traits>
basic_ostream<charT, traits>& post_process(basic_ostream<charT, traits>& os)
{
os << normal_system_screenbuffer;
os << show_cursor;
return os;
}
template <typename charT, typename traits>
basic_ostream<charT, traits>& alternative_system_screenbuffer(basic_ostream<charT, traits>& os)
{
#if UNIX
cout << "\033[?1049h"; // Use alternate screen buffer
#endif
return os;
}
template <typename charT, typename traits>
basic_ostream<charT, traits>& clear(basic_ostream<charT, traits>& os)
{
#ifdef UNIX
cout << "\033[2J";
#elif WIN32
COORD startpoint = { 0, 0 };
DWORD dw;
GetConsoleScreenBufferInfo(os.termout_handle, &os.termout_sbufinfo);
FillConsoleOutputCharacterA(os.termout_handle, ' ',
os.termout_sbufinfo.dwSize.X * os.termout_sbufinfo.dwSize.Y,
startpoint, &dw);
FillConsoleOutputAttribute(os.termout_handle,
FOREGROUND_GREEN | FOREGROUND_RED | FOREGROUND_BLUE,
os.termout_sbufinfo.dwSize.X * os.termout_sbufinfo.dwSize.Y,
startpoint, &dw);
#endif
return os;
}
template <typename charT, typename traits>
basic_ostream<charT, traits>& hide_cursor(basic_ostream<charT, traits>& os)
{
#ifdef UNIX
cout << "\033[?25l"; // Hide cursor
#elif WIN32
GetConsoleCursorInfo(os.termout_handle, &os.termout_curinfo);
os.termout_curinfo.bVisible = 0;
SetConsoleCursorInfo(os.termout_handle, &os.termout_curinfo);
#endif
return os;
}
template <typename charT, typename traits>
basic_ostream<charT, traits>& normal_system_screenbuffer(basic_ostream<charT, traits>& os)
{
#if UNIX
cout << "\033[?1049l"; // Use normal screen buffer
#endif
return os;
}
template <typename charT, typename traits>
basic_ostream<charT, traits>& refresh(basic_ostream<charT, traits>& os)
{
fflush(stdout);
return os;
}
template <typename charT, typename traits>
basic_ostream<charT, traits>& show_cursor(basic_ostream<charT, traits>& os)
{
#if UNIX
cout << "\033[?25h"; // Show cursor
#elif WIN32
CONSOLE_CURSOR_INFO termout_curinfo;
GetConsoleCursorInfo(os.termout_handle, &termout_curinfo);
termout_curinfo.bVisible = 1;
SetConsoleCursorInfo(os.termout_handle, &termout_curinfo);
#endif
return os;
}
template <typename charT, typename traits>
basic_ostream<charT, traits>& operator<<
(basic_ostream<charT, traits>& os, const std::pair<std::string, color> tu)
{
#ifdef UNIX
cout << "\033[" << static_cast<coord_t>(std::get<1>(tu)) << "m" << std::get<0>(tu).c_str() << "\033[0m";
#elif WIN32
WORD termout_attribute;
GetConsoleScreenBufferInfo(os.termout_handle, &os.termout_sbufinfo);
termout_attribute = os.termout_sbufinfo.wAttributes;
SetConsoleTextAttribute(os.termout_handle, static_cast<coord_t>(std::get<1>(tu)));
os << std::get<0>(tu);
SetConsoleTextAttribute(os.termout_handle, termout_attribute);
#endif
return os;
}
/* Input buffer */
/* Input stream */
template <typename charT, typename traits = std::char_traits<charT> >
class basic_istream : public std::basic_istream<charT, traits> {
};
typedef basic_istream<char> istream;
typedef basic_istream<wchar_t> wistream;
}
#endif
<|endoftext|> |
<commit_before>/*
Copyright (c) by respective owners including Yahoo!, Microsoft, and
individual contributors. All rights reserved. Released under a BSD (revised)
license as described in the file LICENSE.
*/
#include <fstream>
#include <iostream>
using namespace std;
#ifndef _WIN32
#include <unistd.h>
#endif
#include <stdlib.h>
#include <stdint.h>
#include <math.h>
#include "parse_regressor.h"
#include "loss_functions.h"
#include "global_data.h"
#include "io_buf.h"
#include "rand48.h"
/* Define the last version where files are backward compatible. */
#define LAST_COMPATIBLE_VERSION "6.1.3"
#define VERSION_FILE_WITH_CUBIC "6.1.3"
void initialize_regressor(vw& all)
{
size_t length = ((size_t)1) << all.num_bits;
all.weight_mask = (all.stride * length) - 1;
all.reg.weight_vector = (weight *)calloc(all.stride*length, sizeof(weight));
if (all.reg.weight_vector == NULL)
{
cerr << all.program_name << ": Failed to allocate weight array with " << all.num_bits << " bits: try decreasing -b <bits>" << endl;
exit (1);
}
if (all.random_weights)
{
for (size_t j = 0; j < length; j++)
all.reg.weight_vector[j*all.stride] = (float)(frand48() - 0.5);
}
if (all.initial_weight != 0.)
for (size_t j = 0; j < all.stride*length; j+=all.stride)
all.reg.weight_vector[j] = all.initial_weight;
}
const size_t buf_size = 512;
void save_load_header(vw& all, io_buf& model_file, bool read, bool text)
{
char buff[buf_size];
char buff2[buf_size];
uint32_t text_len;
if (model_file.files.size() > 0)
{
uint32_t v_length = (uint32_t)version.to_string().length()+1;
text_len = sprintf(buff, "Version %s\n", version.to_string().c_str());
memcpy(buff2,version.to_string().c_str(),v_length);
if (read)
v_length = buf_size;
bin_text_read_write(model_file, buff2, v_length,
"", read,
buff, text_len, text);
version_struct v_tmp(buff2);
if (v_tmp < LAST_COMPATIBLE_VERSION)
{
cout << "Model has possibly incompatible version! " << v_tmp.to_string() << endl;
exit(1);
}
char model = 'm';
bin_text_read_write_fixed(model_file,&model,1,
"file is not a model file", read,
"", 0, text);
text_len = sprintf(buff, "Min label:%f\n", all.sd->min_label);
bin_text_read_write_fixed(model_file,(char*)&all.sd->min_label, sizeof(all.sd->min_label),
"", read,
buff, text_len, text);
text_len = sprintf(buff, "Max label:%f\n", all.sd->max_label);
bin_text_read_write_fixed(model_file,(char*)&all.sd->max_label, sizeof(all.sd->max_label),
"", read,
buff, text_len, text);
text_len = sprintf(buff, "bits:%d\n", (int)all.num_bits);
uint32_t local_num_bits = all.num_bits;
bin_text_read_write_fixed(model_file,(char *)&local_num_bits, sizeof(local_num_bits),
"", read,
buff, text_len, text);
if (all.default_bits != true && all.num_bits != local_num_bits)
{
cout << "Wrong number of bits for source!" << endl;
exit (1);
}
all.default_bits = false;
all.num_bits = local_num_bits;
uint32_t pair_len = (uint32_t)all.pairs.size();
text_len = sprintf(buff, "%d pairs: ", (int)pair_len);
bin_text_read_write_fixed(model_file,(char *)&pair_len, sizeof(pair_len),
"", read,
buff, text_len, text);
for (size_t i = 0; i < pair_len; i++)
{
char pair[2];
if (!read)
{
memcpy(pair,all.pairs[i].c_str(),2);
text_len = sprintf(buff, "%s ", all.pairs[i].c_str());
}
bin_text_read_write_fixed(model_file, pair,2,
"", read,
buff, text_len, text);
if (read)
{
string temp(pair, 2);
all.pairs.push_back(temp);
}
}
bin_text_read_write_fixed(model_file,buff,0,
"", read,
"\n",1,text);
uint32_t triple_len = (uint32_t)all.triples.size();
text_len = sprintf(buff, "%d triples: ", (int)triple_len);
bin_text_read_write_fixed(model_file,(char *)&triple_len, sizeof(triple_len),
"", read,
buff,text_len, text);
for (size_t i = 0; i < triple_len; i++)
{
text_len = sprintf(buff, "%s ", all.triples[i].c_str());
char triple[3];
if (!read)
memcpy(triple, all.triples[i].c_str(), 3);
bin_text_read_write_fixed(model_file,triple,3,
"", read,
buff,text_len,text);
if (read)
{
string temp(triple,3);
all.triples.push_back(temp);
}
}
bin_text_read_write_fixed(model_file,buff,0,
"", read,
"\n",1, text);
text_len = sprintf(buff, "rank:%d\n", (int)all.rank);
bin_text_read_write_fixed(model_file,(char*)&all.rank, sizeof(all.rank),
"", read,
buff,text_len, text);
text_len = sprintf(buff, "lda:%d\n", (int)all.lda);
bin_text_read_write_fixed(model_file,(char*)&all.lda, sizeof(all.lda),
"", read,
buff, text_len,text);
text_len = sprintf(buff, "ngram:%d\n", (int)all.ngram);
bin_text_read_write_fixed(model_file,(char*)&all.ngram, sizeof(all.ngram),
"", read,
buff, text_len, text);
text_len = sprintf(buff, "skips:%d\n", (int)all.skips);
bin_text_read_write_fixed(model_file,(char*)&all.skips, sizeof(all.skips),
"", read,
buff, text_len, text);
text_len = sprintf(buff, "options:%s\n", all.options_from_file.c_str());
uint32_t len = (uint32_t)all.options_from_file.length()+1;
memcpy(buff2, all.options_from_file.c_str(),len);
if (read)
len = buf_size;
bin_text_read_write(model_file,buff2, len,
"", read,
buff, text_len, text);
if (read)
all.options_from_file.assign(buff2);
}
}
void dump_regressor(vw& all, string reg_name, bool as_text)
{
if (reg_name == string(""))
return;
string start_name = reg_name+string(".writing");
io_buf io_temp;
io_temp.open_file(start_name.c_str(), all.stdin_off, io_buf::WRITE);
save_load_header(all, io_temp, false, as_text);
all.l.save_load(&all, all.l.data, io_temp, false, as_text);
io_temp.flush(); // close_file() should do this for me ...
io_temp.close_file();
remove(reg_name.c_str());
rename(start_name.c_str(),reg_name.c_str());
}
void save_predictor(vw& all, string reg_name, size_t current_pass)
{
char* filename = new char[reg_name.length()+4];
if (all.save_per_pass)
sprintf(filename,"%s.%lu",reg_name.c_str(),(long unsigned)current_pass);
else
sprintf(filename,"%s",reg_name.c_str());
dump_regressor(all, string(filename), false);
delete[] filename;
}
void finalize_regressor(vw& all, string reg_name)
{
if (all.per_feature_regularizer_output.length() > 0)
dump_regressor(all, all.per_feature_regularizer_output, false);
else
dump_regressor(all, reg_name, false);
if (all.per_feature_regularizer_text.length() > 0)
dump_regressor(all, all.per_feature_regularizer_text, true);
else
dump_regressor(all, all.text_regressor_name, true);
}
void parse_regressor_args(vw& all, po::variables_map& vm, io_buf& io_temp)
{
if (vm.count("final_regressor")) {
all.final_regressor_name = vm["final_regressor"].as<string>();
if (!all.quiet)
cerr << "final_regressor = " << vm["final_regressor"].as<string>() << endl;
}
else
all.final_regressor_name = "";
vector<string> regs;
if (vm.count("initial_regressor") || vm.count("i"))
regs = vm["initial_regressor"].as< vector<string> >();
if (regs.size() > 0)
io_temp.open_file(regs[0].c_str(), all.stdin_off, io_buf::READ);
save_load_header(all, io_temp, true, false);
}
<commit_msg>fix double pairing bug<commit_after>/*
Copyright (c) by respective owners including Yahoo!, Microsoft, and
individual contributors. All rights reserved. Released under a BSD (revised)
license as described in the file LICENSE.
*/
#include <fstream>
#include <iostream>
using namespace std;
#ifndef _WIN32
#include <unistd.h>
#endif
#include <stdlib.h>
#include <stdint.h>
#include <math.h>
#include <algorithm>
#include "parse_regressor.h"
#include "loss_functions.h"
#include "global_data.h"
#include "io_buf.h"
#include "rand48.h"
/* Define the last version where files are backward compatible. */
#define LAST_COMPATIBLE_VERSION "6.1.3"
#define VERSION_FILE_WITH_CUBIC "6.1.3"
void initialize_regressor(vw& all)
{
size_t length = ((size_t)1) << all.num_bits;
all.weight_mask = (all.stride * length) - 1;
all.reg.weight_vector = (weight *)calloc(all.stride*length, sizeof(weight));
if (all.reg.weight_vector == NULL)
{
cerr << all.program_name << ": Failed to allocate weight array with " << all.num_bits << " bits: try decreasing -b <bits>" << endl;
exit (1);
}
if (all.random_weights)
{
for (size_t j = 0; j < length; j++)
all.reg.weight_vector[j*all.stride] = (float)(frand48() - 0.5);
}
if (all.initial_weight != 0.)
for (size_t j = 0; j < all.stride*length; j+=all.stride)
all.reg.weight_vector[j] = all.initial_weight;
}
const size_t buf_size = 512;
void save_load_header(vw& all, io_buf& model_file, bool read, bool text)
{
char buff[buf_size];
char buff2[buf_size];
uint32_t text_len;
if (model_file.files.size() > 0)
{
uint32_t v_length = (uint32_t)version.to_string().length()+1;
text_len = sprintf(buff, "Version %s\n", version.to_string().c_str());
memcpy(buff2,version.to_string().c_str(),v_length);
if (read)
v_length = buf_size;
bin_text_read_write(model_file, buff2, v_length,
"", read,
buff, text_len, text);
version_struct v_tmp(buff2);
if (v_tmp < LAST_COMPATIBLE_VERSION)
{
cout << "Model has possibly incompatible version! " << v_tmp.to_string() << endl;
exit(1);
}
char model = 'm';
bin_text_read_write_fixed(model_file,&model,1,
"file is not a model file", read,
"", 0, text);
text_len = sprintf(buff, "Min label:%f\n", all.sd->min_label);
bin_text_read_write_fixed(model_file,(char*)&all.sd->min_label, sizeof(all.sd->min_label),
"", read,
buff, text_len, text);
text_len = sprintf(buff, "Max label:%f\n", all.sd->max_label);
bin_text_read_write_fixed(model_file,(char*)&all.sd->max_label, sizeof(all.sd->max_label),
"", read,
buff, text_len, text);
text_len = sprintf(buff, "bits:%d\n", (int)all.num_bits);
uint32_t local_num_bits = all.num_bits;
bin_text_read_write_fixed(model_file,(char *)&local_num_bits, sizeof(local_num_bits),
"", read,
buff, text_len, text);
if (all.default_bits != true && all.num_bits != local_num_bits)
{
cout << "Wrong number of bits for source!" << endl;
exit (1);
}
all.default_bits = false;
all.num_bits = local_num_bits;
uint32_t pair_len = (uint32_t)all.pairs.size();
text_len = sprintf(buff, "%d pairs: ", (int)pair_len);
bin_text_read_write_fixed(model_file,(char *)&pair_len, sizeof(pair_len),
"", read,
buff, text_len, text);
for (size_t i = 0; i < pair_len; i++)
{
char pair[2];
if (!read)
{
memcpy(pair,all.pairs[i].c_str(),2);
text_len = sprintf(buff, "%s ", all.pairs[i].c_str());
}
bin_text_read_write_fixed(model_file, pair,2,
"", read,
buff, text_len, text);
if (read)
{
string temp(pair, 2);
if (count(all.pairs.begin(), all.pairs.end(), temp) == 0)
all.pairs.push_back(temp);
}
}
bin_text_read_write_fixed(model_file,buff,0,
"", read,
"\n",1,text);
uint32_t triple_len = (uint32_t)all.triples.size();
text_len = sprintf(buff, "%d triples: ", (int)triple_len);
bin_text_read_write_fixed(model_file,(char *)&triple_len, sizeof(triple_len),
"", read,
buff,text_len, text);
for (size_t i = 0; i < triple_len; i++)
{
text_len = sprintf(buff, "%s ", all.triples[i].c_str());
char triple[3];
if (!read)
memcpy(triple, all.triples[i].c_str(), 3);
bin_text_read_write_fixed(model_file,triple,3,
"", read,
buff,text_len,text);
if (read)
{
string temp(triple,3);
all.triples.push_back(temp);
}
}
bin_text_read_write_fixed(model_file,buff,0,
"", read,
"\n",1, text);
text_len = sprintf(buff, "rank:%d\n", (int)all.rank);
bin_text_read_write_fixed(model_file,(char*)&all.rank, sizeof(all.rank),
"", read,
buff,text_len, text);
text_len = sprintf(buff, "lda:%d\n", (int)all.lda);
bin_text_read_write_fixed(model_file,(char*)&all.lda, sizeof(all.lda),
"", read,
buff, text_len,text);
text_len = sprintf(buff, "ngram:%d\n", (int)all.ngram);
bin_text_read_write_fixed(model_file,(char*)&all.ngram, sizeof(all.ngram),
"", read,
buff, text_len, text);
text_len = sprintf(buff, "skips:%d\n", (int)all.skips);
bin_text_read_write_fixed(model_file,(char*)&all.skips, sizeof(all.skips),
"", read,
buff, text_len, text);
text_len = sprintf(buff, "options:%s\n", all.options_from_file.c_str());
uint32_t len = (uint32_t)all.options_from_file.length()+1;
memcpy(buff2, all.options_from_file.c_str(),len);
if (read)
len = buf_size;
bin_text_read_write(model_file,buff2, len,
"", read,
buff, text_len, text);
if (read)
all.options_from_file.assign(buff2);
}
}
void dump_regressor(vw& all, string reg_name, bool as_text)
{
if (reg_name == string(""))
return;
string start_name = reg_name+string(".writing");
io_buf io_temp;
io_temp.open_file(start_name.c_str(), all.stdin_off, io_buf::WRITE);
save_load_header(all, io_temp, false, as_text);
all.l.save_load(&all, all.l.data, io_temp, false, as_text);
io_temp.flush(); // close_file() should do this for me ...
io_temp.close_file();
remove(reg_name.c_str());
rename(start_name.c_str(),reg_name.c_str());
}
void save_predictor(vw& all, string reg_name, size_t current_pass)
{
char* filename = new char[reg_name.length()+4];
if (all.save_per_pass)
sprintf(filename,"%s.%lu",reg_name.c_str(),(long unsigned)current_pass);
else
sprintf(filename,"%s",reg_name.c_str());
dump_regressor(all, string(filename), false);
delete[] filename;
}
void finalize_regressor(vw& all, string reg_name)
{
if (all.per_feature_regularizer_output.length() > 0)
dump_regressor(all, all.per_feature_regularizer_output, false);
else
dump_regressor(all, reg_name, false);
if (all.per_feature_regularizer_text.length() > 0)
dump_regressor(all, all.per_feature_regularizer_text, true);
else
dump_regressor(all, all.text_regressor_name, true);
}
void parse_regressor_args(vw& all, po::variables_map& vm, io_buf& io_temp)
{
if (vm.count("final_regressor")) {
all.final_regressor_name = vm["final_regressor"].as<string>();
if (!all.quiet)
cerr << "final_regressor = " << vm["final_regressor"].as<string>() << endl;
}
else
all.final_regressor_name = "";
vector<string> regs;
if (vm.count("initial_regressor") || vm.count("i"))
regs = vm["initial_regressor"].as< vector<string> >();
if (regs.size() > 0)
io_temp.open_file(regs[0].c_str(), all.stdin_off, io_buf::READ);
save_load_header(all, io_temp, true, false);
}
<|endoftext|> |
<commit_before>// Copyright 2012 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
// option. This file may not be copied, modified, or distributed
// except according to those terms.
#include "boxed_region.h"
#include "rust_globals.h"
#include "rust_task.h"
#include "rust_env.h"
#include "rust_util.h"
// #define DUMP_BOXED_REGION
rust_opaque_box *boxed_region::malloc(type_desc *td, size_t body_size) {
size_t total_size = get_box_size(body_size, td->align);
rust_opaque_box *box =
(rust_opaque_box*)backing_region->malloc(total_size, "@");
box->td = td;
box->ref_count = 1;
box->prev = NULL;
box->next = live_allocs;
if (live_allocs) live_allocs->prev = box;
live_allocs = box;
/*LOG(rust_get_current_task(), box,
"@malloc()=%p with td %p, size %lu==%lu+%lu, "
"align %lu, prev %p, next %p\n",
box, td, total_size, sizeof(rust_opaque_box), body_size,
td->align, box->prev, box->next);*/
return box;
}
rust_opaque_box *boxed_region::realloc(rust_opaque_box *box,
size_t new_size) {
// We also get called on the unique-vec-in-managed-heap path.
assert(box->ref_count == 1 ||
box->ref_count == (size_t)(-2));
size_t total_size = new_size + sizeof(rust_opaque_box);
rust_opaque_box *new_box =
(rust_opaque_box*)backing_region->realloc(box, total_size);
if (new_box->prev) new_box->prev->next = new_box;
if (new_box->next) new_box->next->prev = new_box;
if (live_allocs == box) live_allocs = new_box;
/*LOG(rust_get_current_task(), box,
"@realloc()=%p with orig=%p, size %lu==%lu+%lu",
new_box, box, total_size, sizeof(rust_opaque_box), new_size);*/
return new_box;
}
rust_opaque_box *boxed_region::calloc(type_desc *td, size_t body_size) {
rust_opaque_box *box = malloc(td, body_size);
memset(box_body(box), 0, td->size);
return box;
}
void boxed_region::free(rust_opaque_box *box) {
// This turns out to not be true in various situations,
// like when we are unwinding after a failure.
//
// assert(box->ref_count == 0);
// This however should always be true. Helps to detect
// double frees (kind of).
assert(box->td != NULL);
/*LOG(rust_get_current_task(), box,
"@free(%p) with td %p, prev %p, next %p\n",
box, box->td, box->prev, box->next);*/
if (box->prev) box->prev->next = box->next;
if (box->next) box->next->prev = box->prev;
if (live_allocs == box) live_allocs = box->next;
if (poison_on_free) {
memset(box_body(box), 0xab, box->td->size);
}
box->prev = NULL;
box->next = NULL;
box->td = NULL;
backing_region->free(box);
}
//
// Local Variables:
// mode: C++
// fill-column: 78;
// indent-tabs-mode: nil
// c-basic-offset: 4
// buffer-file-coding-system: utf-8-unix
// End:
//
<commit_msg>This assert does not necessarily hold; sometimes we temporarily increase ref-count<commit_after>// Copyright 2012 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
// option. This file may not be copied, modified, or distributed
// except according to those terms.
#include "boxed_region.h"
#include "rust_globals.h"
#include "rust_task.h"
#include "rust_env.h"
#include "rust_util.h"
// #define DUMP_BOXED_REGION
rust_opaque_box *boxed_region::malloc(type_desc *td, size_t body_size) {
size_t total_size = get_box_size(body_size, td->align);
rust_opaque_box *box =
(rust_opaque_box*)backing_region->malloc(total_size, "@");
box->td = td;
box->ref_count = 1;
box->prev = NULL;
box->next = live_allocs;
if (live_allocs) live_allocs->prev = box;
live_allocs = box;
/*LOG(rust_get_current_task(), box,
"@malloc()=%p with td %p, size %lu==%lu+%lu, "
"align %lu, prev %p, next %p\n",
box, td, total_size, sizeof(rust_opaque_box), body_size,
td->align, box->prev, box->next);*/
return box;
}
rust_opaque_box *boxed_region::realloc(rust_opaque_box *box,
size_t new_size) {
// We also get called on the unique-vec-in-managed-heap path.
// assert(box->ref_count == 1 ||
// box->ref_count == (size_t)(-2));
size_t total_size = new_size + sizeof(rust_opaque_box);
rust_opaque_box *new_box =
(rust_opaque_box*)backing_region->realloc(box, total_size);
if (new_box->prev) new_box->prev->next = new_box;
if (new_box->next) new_box->next->prev = new_box;
if (live_allocs == box) live_allocs = new_box;
/*LOG(rust_get_current_task(), box,
"@realloc()=%p with orig=%p, size %lu==%lu+%lu",
new_box, box, total_size, sizeof(rust_opaque_box), new_size);*/
return new_box;
}
rust_opaque_box *boxed_region::calloc(type_desc *td, size_t body_size) {
rust_opaque_box *box = malloc(td, body_size);
memset(box_body(box), 0, td->size);
return box;
}
void boxed_region::free(rust_opaque_box *box) {
// This turns out to not be true in various situations,
// like when we are unwinding after a failure.
//
// assert(box->ref_count == 0);
// This however should always be true. Helps to detect
// double frees (kind of).
assert(box->td != NULL);
/*LOG(rust_get_current_task(), box,
"@free(%p) with td %p, prev %p, next %p\n",
box, box->td, box->prev, box->next);*/
if (box->prev) box->prev->next = box->next;
if (box->next) box->next->prev = box->prev;
if (live_allocs == box) live_allocs = box->next;
if (poison_on_free) {
memset(box_body(box), 0xab, box->td->size);
}
box->prev = NULL;
box->next = NULL;
box->td = NULL;
backing_region->free(box);
}
//
// Local Variables:
// mode: C++
// fill-column: 78;
// indent-tabs-mode: nil
// c-basic-offset: 4
// buffer-file-coding-system: utf-8-unix
// End:
//
<|endoftext|> |
<commit_before>/*=========================================================================
Program: Visomics
Copyright (c) Kitware, Inc.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
=========================================================================*/
// Qt includes
#include <QHash>
#include <QSharedPointer>
#include <QDebug>
#include <QMainWindow>
// QtPropertyBrowser includes
#include <QtVariantPropertyManager>
// Visomics includes
#include "voAnalysis.h"
#include "voAnalysisDriver.h"
#include "voAnalysisFactory.h"
#include "voApplication.h"
#include "voDataModelItem.h"
#include "voDataObject.h"
// --------------------------------------------------------------------------
class voAnalysisDriverPrivate
{
public:
voAnalysisDriverPrivate();
virtual ~voAnalysisDriverPrivate();
};
// --------------------------------------------------------------------------
// voAnalysisDriverPrivate methods
// --------------------------------------------------------------------------
voAnalysisDriverPrivate::voAnalysisDriverPrivate()
{
}
// --------------------------------------------------------------------------
voAnalysisDriverPrivate::~voAnalysisDriverPrivate()
{
}
// --------------------------------------------------------------------------
// voAnalysisDriver methods
// --------------------------------------------------------------------------
voAnalysisDriver::voAnalysisDriver(QObject* newParent):
Superclass(newParent), d_ptr(new voAnalysisDriverPrivate)
{
}
// --------------------------------------------------------------------------
voAnalysisDriver::~voAnalysisDriver()
{
}
// --------------------------------------------------------------------------
void voAnalysisDriver::runAnalysisForAllInputs(const QString& analysisName, bool acceptDefaultParameter)
{
if (analysisName.isEmpty())
{
qWarning() << "Failed to runAnalysisForAllInputs - AnalysisName is empty";
return;
}
voDataModel * model = voApplication::application()->dataModel();
// Collect inputs
QList<voDataModelItem*> targetInputs = model->selectedInputObjects();
foreach(voDataModelItem* targetInput, targetInputs)
{
this->runAnalysis(analysisName, targetInput, acceptDefaultParameter);
}
}
// --------------------------------------------------------------------------
void voAnalysisDriver::runAnalysis(const QString& analysisName, voDataModelItem* inputTarget, bool acceptDefaultParameter)
{
if (analysisName.isEmpty())
{
qWarning() << "Failed to runAnalysis - AnalysisName is an empty string";
return;
}
if (!inputTarget)
{
qWarning() << "Failed to runAnalysis - InputTarget is NULL";
return;
}
voAnalysisFactory * analysisFactory = voApplication::application()->analysisFactory();
voAnalysis * analysis = analysisFactory->createAnalysis(
analysisFactory->analysisNameFromPrettyName(analysisName));
Q_ASSERT(analysis);
analysis->setParent(qApp);
analysis->setAcceptDefaultParameterValues(acceptDefaultParameter);
this->runAnalysis(analysis, inputTarget);
}
// --------------------------------------------------------------------------
void voAnalysisDriver::runAnalysis(voAnalysis * analysis, voDataModelItem* inputTarget)
{
if (!analysis)
{
qWarning() << "Failed to runAnalysis - Analysis is NULL";
return;
}
if (!inputTarget)
{
qWarning() << "Failed to runAnalysis - InputTarget is NULL";
return;
}
QScopedPointer<voAnalysis> analysisScopedPtr(analysis);
// Reset abort execution flag
analysis->setAbortExecution(false);
// Clear inputs and outputs
analysis->removeAllInputs();
analysis->removeAllOutputs();
// Initialize input and output
analysis->initializeInputInformation();
analysis->initializeOutputInformation();
//qDebug() << " " << analysis->numberOfInput() << " inputs expected";
QStringList inputNames = analysis->inputNames();
voDataObject * dataObject;
QString inputName;
if ( inputNames.size() == 1 )
{// for most analysis, only one input is required
dataObject = inputTarget->dataObject();
inputName = inputNames.value(0);
// Does the type of the provided input match the expected one ?
QString expectedInputType = analysis->inputType(inputName);
QString providedInputType = dataObject->type();
if (expectedInputType != providedInputType)
{
qWarning() << QObject::tr("Failed to runAnalysis - Provided input type %1 is "
"different from the expected input type %2").
arg(providedInputType).arg(expectedInputType);
return;
}
analysis->addInput(inputName, dataObject);
}
else
{//require multiple inputs
if (inputNames.size() == inputTarget->childItems().size())
{
for (int i = 0; i < inputNames.size(); i++)
{
voDataModelItem * childItem = dynamic_cast<voDataModelItem*>(inputTarget->child(i));
dataObject = childItem->dataObject();
inputName = inputNames.value(i);
// Does the type of the provided input match the expected one ?
QString expectedInputType = analysis->inputType(inputName);
QString providedInputType = dataObject->type();
if (expectedInputType != providedInputType)
{
qWarning() << QObject::tr("Failed to runAnalysis - Provided input type %1 is "
"different from the expected input type %2").
arg(providedInputType).arg(expectedInputType);
return;
}
analysis->addInput(inputName, dataObject);
}
}
else
{//error report
qWarning() << QObject::tr("Failed to runAnalysis - Provided input number %1 is "
"different from the expected input number %2").
arg(inputTarget->childItems().size()).arg(inputNames.size());
return;
}
}
// Initialize parameter
analysis->initializeParameterInformation();
emit this->aboutToRunAnalysis(analysis);
if (analysis->abortExecution())
{
return;
}
bool ret = analysis->run();
if (!ret)
{
qCritical() << "Analysis failed to run " << analysis->objectName();
return;
}
voAnalysisDriver::addAnalysisToObjectModel(analysisScopedPtr.take(), inputTarget);
connect(analysis, SIGNAL(outputSet(const QString&, voDataObject*, voAnalysis*)),
SLOT(onAnalysisOutputSet(const QString&,voDataObject*,voAnalysis*)));
emit this->analysisAddedToObjectModel(analysis);
qDebug() << " => Analysis" << analysis->objectName() << " DONE";
}
// --------------------------------------------------------------------------
void voAnalysisDriver::runAnalysisForCurrentInput(
const QString& analysisName, const QHash<QString, QVariant>& parameters)
{
qDebug() << "runAnalysisForCurrentInput" << analysisName;
voDataModel * model = voApplication::application()->dataModel();
voDataModelItem * inputTarget = model->inputTargetForAnalysis(model->activeAnalysis());
Q_ASSERT(inputTarget);
voAnalysisFactory * analysisFactory = voApplication::application()->analysisFactory();
voAnalysis * newAnalysis = analysisFactory->createAnalysis(
analysisFactory->analysisNameFromPrettyName(analysisName));
Q_ASSERT(newAnalysis);
newAnalysis->initializeParameterInformation(parameters);
newAnalysis->setAcceptDefaultParameterValues(true);
this->runAnalysis(newAnalysis, inputTarget);
}
// --------------------------------------------------------------------------
void voAnalysisDriver::updateAnalysis(
voAnalysis * analysis, const QHash<QString, QVariant>& parameters)
{
if (!analysis || parameters.count() == 0)
{
return;
}
// qDebug() << "voAnalysisDriver::updateAnalysis";
// Update analysis parameter
analysis->setParameterValues(parameters);
analysis->setAcceptDefaultParameterValues(true);
// Clear outputs
analysis->removeAllOutputs();
analysis->initializeOutputInformation();
emit this->aboutToRunAnalysis(analysis);
bool ret = analysis->run();
if (!ret)
{
qCritical() << "Analysis failed to run " << analysis->objectName();
return;
}
}
// --------------------------------------------------------------------------
void voAnalysisDriver::onAnalysisOutputSet(
const QString& outputName, voDataObject* dataObject, voAnalysis* analysis)
{
if (outputName.isEmpty() || !dataObject || !analysis)
{
return;
}
voDataModel * model = voApplication::application()->dataModel();
voDataModelItem * analysisContainer = model->itemForAnalysis(analysis);
Q_ASSERT(analysisContainer);
QList<voDataModelItem*> items =
model->findItemsWithRole(voDataModelItem::OutputNameRole, outputName, analysisContainer);
foreach(voDataModelItem* item, items)
{
item->setDataObject(dataObject);
}
}
// --------------------------------------------------------------------------
void voAnalysisDriver::addAnalysisToObjectModel(voAnalysis * analysis,
voDataModelItem* insertLocation)
{
if (!analysis || !insertLocation)
{
return;
}
voDataModel * model = voApplication::application()->dataModel();
// Analysis container
voDataModelItem * analysisContainer =
model->addContainer(model->getNextName(analysis->objectName()), insertLocation);
analysisContainer->setData(QVariant(analysis->uuid()), voDataModelItem::UuidRole);
analysisContainer->setData(QVariant(true), voDataModelItem::IsAnalysisContainerRole);
analysisContainer->setData(QVariant(QMetaType::VoidStar, &analysis), voDataModelItem::AnalysisVoidStarRole);
// Outputs container
voDataModelItem * outputsContainer = analysisContainer;
// model->addContainer(QObject::tr("outputs"), analysisContainer);
// Views container
voDataModelItem * viewContainer = analysisContainer;
// model->addContainer(QObject::tr("views"), analysisContainer);
// Loop over outputs
foreach(const QString& outputName, analysis->outputNames())
{
voDataObject * dataObject = analysis->output(outputName);
if (!dataObject || dataObject->data().isNull())
{
qCritical() << QObject::tr("Analysis ran, but output [%1] is missing.").arg(outputName);
continue;
}
// Append output only if it is associated with a non-empty rawViewType
QString rawViewType = analysis->rawViewTypeForOutput(outputName);
if (!rawViewType.isEmpty())
{
QString rawViewPrettyName = analysis->rawViewPrettyName(outputName, rawViewType);
voDataModelItem * outputItem =
model->addOutput(dataObject, outputsContainer, rawViewType, rawViewPrettyName);
outputItem->setData(outputName, voDataModelItem::OutputNameRole);
}
foreach(const QString& viewType, analysis->viewTypesForOutput(outputName))
{
if (viewType.isEmpty()) { continue; }
QString viewPrettyName = analysis->viewPrettyName(outputName, viewType);
voDataModelItem * viewItem =
model->addView(viewType, viewPrettyName, dataObject, viewContainer);
viewItem->setData(outputName, voDataModelItem::OutputNameRole);
}
}
}
<commit_msg>make OneZoom visualization less picky about its input data<commit_after>/*=========================================================================
Program: Visomics
Copyright (c) Kitware, Inc.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
=========================================================================*/
// Qt includes
#include <QHash>
#include <QSharedPointer>
#include <QDebug>
#include <QMainWindow>
// QtPropertyBrowser includes
#include <QtVariantPropertyManager>
// Visomics includes
#include "voAnalysis.h"
#include "voAnalysisDriver.h"
#include "voAnalysisFactory.h"
#include "voApplication.h"
#include "voDataModelItem.h"
#include "voDataObject.h"
// --------------------------------------------------------------------------
class voAnalysisDriverPrivate
{
public:
voAnalysisDriverPrivate();
virtual ~voAnalysisDriverPrivate();
};
// --------------------------------------------------------------------------
// voAnalysisDriverPrivate methods
// --------------------------------------------------------------------------
voAnalysisDriverPrivate::voAnalysisDriverPrivate()
{
}
// --------------------------------------------------------------------------
voAnalysisDriverPrivate::~voAnalysisDriverPrivate()
{
}
// --------------------------------------------------------------------------
// voAnalysisDriver methods
// --------------------------------------------------------------------------
voAnalysisDriver::voAnalysisDriver(QObject* newParent):
Superclass(newParent), d_ptr(new voAnalysisDriverPrivate)
{
}
// --------------------------------------------------------------------------
voAnalysisDriver::~voAnalysisDriver()
{
}
// --------------------------------------------------------------------------
void voAnalysisDriver::runAnalysisForAllInputs(const QString& analysisName, bool acceptDefaultParameter)
{
if (analysisName.isEmpty())
{
qWarning() << "Failed to runAnalysisForAllInputs - AnalysisName is empty";
return;
}
voDataModel * model = voApplication::application()->dataModel();
// Collect inputs
QList<voDataModelItem*> targetInputs = model->selectedInputObjects();
foreach(voDataModelItem* targetInput, targetInputs)
{
this->runAnalysis(analysisName, targetInput, acceptDefaultParameter);
}
}
// --------------------------------------------------------------------------
void voAnalysisDriver::runAnalysis(const QString& analysisName, voDataModelItem* inputTarget, bool acceptDefaultParameter)
{
if (analysisName.isEmpty())
{
qWarning() << "Failed to runAnalysis - AnalysisName is an empty string";
return;
}
if (!inputTarget)
{
qWarning() << "Failed to runAnalysis - InputTarget is NULL";
return;
}
voAnalysisFactory * analysisFactory = voApplication::application()->analysisFactory();
voAnalysis * analysis = analysisFactory->createAnalysis(
analysisFactory->analysisNameFromPrettyName(analysisName));
Q_ASSERT(analysis);
analysis->setParent(qApp);
analysis->setAcceptDefaultParameterValues(acceptDefaultParameter);
this->runAnalysis(analysis, inputTarget);
}
// --------------------------------------------------------------------------
void voAnalysisDriver::runAnalysis(voAnalysis * analysis, voDataModelItem* inputTarget)
{
if (!analysis)
{
qWarning() << "Failed to runAnalysis - Analysis is NULL";
return;
}
if (!inputTarget)
{
qWarning() << "Failed to runAnalysis - InputTarget is NULL";
return;
}
QScopedPointer<voAnalysis> analysisScopedPtr(analysis);
// Reset abort execution flag
analysis->setAbortExecution(false);
// Clear inputs and outputs
analysis->removeAllInputs();
analysis->removeAllOutputs();
// Initialize input and output
analysis->initializeInputInformation();
analysis->initializeOutputInformation();
//qDebug() << " " << analysis->numberOfInput() << " inputs expected";
QStringList inputNames = analysis->inputNames();
voDataObject * dataObject = NULL;
QString inputName = inputNames.value(0);
QString expectedInputType = analysis->inputType(inputName);
QString providedInputType = "";
voDataModelItem * childItemForSingleInput = NULL;
if ( inputNames.size() == 1 )
{
// for most analysis, only one input is required
// nonetheless, for the convenience of our users, we'll handle the case
// where they passed in a group of inputs.
if (inputTarget->childItems().size() > 0)
{
for (int i = 0; i < inputTarget->childItems().size(); ++i)
{
childItemForSingleInput =
dynamic_cast<voDataModelItem*>(inputTarget->child(i));
if (childItemForSingleInput->dataObject()->type() == expectedInputType)
{
dataObject = childItemForSingleInput->dataObject();
providedInputType = dataObject->type();
break;
}
childItemForSingleInput = NULL;
}
}
else
// "normal" case: single input specified
{
dataObject = inputTarget->dataObject();
providedInputType = dataObject->type();
}
// Does the type of the provided input match the expected one ?
if (expectedInputType != providedInputType)
{
qWarning() << QObject::tr("Failed to runAnalysis - Provided input type %1 is "
"different from the expected input type %2").
arg(providedInputType).arg(expectedInputType);
return;
}
analysis->addInput(inputName, dataObject);
}
else
{//require multiple inputs
if (inputNames.size() == inputTarget->childItems().size())
{
for (int i = 0; i < inputNames.size(); i++)
{
voDataModelItem * childItem = dynamic_cast<voDataModelItem*>(inputTarget->child(i));
dataObject = childItem->dataObject();
inputName = inputNames.value(i);
// Does the type of the provided input match the expected one ?
QString expectedInputType = analysis->inputType(inputName);
QString providedInputType = dataObject->type();
if (expectedInputType != providedInputType)
{
qWarning() << QObject::tr("Failed to runAnalysis - Provided input type %1 is "
"different from the expected input type %2").
arg(providedInputType).arg(expectedInputType);
return;
}
analysis->addInput(inputName, dataObject);
}
}
else
{//error report
qWarning() << QObject::tr("Failed to runAnalysis - Provided input number %1 is "
"different from the expected input number %2").
arg(inputTarget->childItems().size()).arg(inputNames.size());
return;
}
}
// Initialize parameter
analysis->initializeParameterInformation();
emit this->aboutToRunAnalysis(analysis);
if (analysis->abortExecution())
{
return;
}
bool ret = analysis->run();
if (!ret)
{
qCritical() << "Analysis failed to run " << analysis->objectName();
return;
}
if (childItemForSingleInput == NULL)
{
voAnalysisDriver::addAnalysisToObjectModel(
analysisScopedPtr.take(), inputTarget);
}
else
{
voAnalysisDriver::addAnalysisToObjectModel(
analysisScopedPtr.take(), childItemForSingleInput);
}
connect(analysis, SIGNAL(outputSet(const QString&, voDataObject*, voAnalysis*)),
SLOT(onAnalysisOutputSet(const QString&,voDataObject*,voAnalysis*)));
emit this->analysisAddedToObjectModel(analysis);
qDebug() << " => Analysis" << analysis->objectName() << " DONE";
}
// --------------------------------------------------------------------------
void voAnalysisDriver::runAnalysisForCurrentInput(
const QString& analysisName, const QHash<QString, QVariant>& parameters)
{
qDebug() << "runAnalysisForCurrentInput" << analysisName;
voDataModel * model = voApplication::application()->dataModel();
voDataModelItem * inputTarget = model->inputTargetForAnalysis(model->activeAnalysis());
Q_ASSERT(inputTarget);
voAnalysisFactory * analysisFactory = voApplication::application()->analysisFactory();
voAnalysis * newAnalysis = analysisFactory->createAnalysis(
analysisFactory->analysisNameFromPrettyName(analysisName));
Q_ASSERT(newAnalysis);
newAnalysis->initializeParameterInformation(parameters);
newAnalysis->setAcceptDefaultParameterValues(true);
this->runAnalysis(newAnalysis, inputTarget);
}
// --------------------------------------------------------------------------
void voAnalysisDriver::updateAnalysis(
voAnalysis * analysis, const QHash<QString, QVariant>& parameters)
{
if (!analysis || parameters.count() == 0)
{
return;
}
// qDebug() << "voAnalysisDriver::updateAnalysis";
// Update analysis parameter
analysis->setParameterValues(parameters);
analysis->setAcceptDefaultParameterValues(true);
// Clear outputs
analysis->removeAllOutputs();
analysis->initializeOutputInformation();
emit this->aboutToRunAnalysis(analysis);
bool ret = analysis->run();
if (!ret)
{
qCritical() << "Analysis failed to run " << analysis->objectName();
return;
}
}
// --------------------------------------------------------------------------
void voAnalysisDriver::onAnalysisOutputSet(
const QString& outputName, voDataObject* dataObject, voAnalysis* analysis)
{
if (outputName.isEmpty() || !dataObject || !analysis)
{
return;
}
voDataModel * model = voApplication::application()->dataModel();
voDataModelItem * analysisContainer = model->itemForAnalysis(analysis);
Q_ASSERT(analysisContainer);
QList<voDataModelItem*> items =
model->findItemsWithRole(voDataModelItem::OutputNameRole, outputName, analysisContainer);
foreach(voDataModelItem* item, items)
{
item->setDataObject(dataObject);
}
}
// --------------------------------------------------------------------------
void voAnalysisDriver::addAnalysisToObjectModel(voAnalysis * analysis,
voDataModelItem* insertLocation)
{
if (!analysis || !insertLocation)
{
return;
}
voDataModel * model = voApplication::application()->dataModel();
// Analysis container
voDataModelItem * analysisContainer =
model->addContainer(model->getNextName(analysis->objectName()), insertLocation);
analysisContainer->setData(QVariant(analysis->uuid()), voDataModelItem::UuidRole);
analysisContainer->setData(QVariant(true), voDataModelItem::IsAnalysisContainerRole);
analysisContainer->setData(QVariant(QMetaType::VoidStar, &analysis), voDataModelItem::AnalysisVoidStarRole);
// Outputs container
voDataModelItem * outputsContainer = analysisContainer;
// model->addContainer(QObject::tr("outputs"), analysisContainer);
// Views container
voDataModelItem * viewContainer = analysisContainer;
// model->addContainer(QObject::tr("views"), analysisContainer);
// Loop over outputs
foreach(const QString& outputName, analysis->outputNames())
{
voDataObject * dataObject = analysis->output(outputName);
if (!dataObject || dataObject->data().isNull())
{
qCritical() << QObject::tr("Analysis ran, but output [%1] is missing.").arg(outputName);
continue;
}
// Append output only if it is associated with a non-empty rawViewType
QString rawViewType = analysis->rawViewTypeForOutput(outputName);
if (!rawViewType.isEmpty())
{
QString rawViewPrettyName = analysis->rawViewPrettyName(outputName, rawViewType);
voDataModelItem * outputItem =
model->addOutput(dataObject, outputsContainer, rawViewType, rawViewPrettyName);
outputItem->setData(outputName, voDataModelItem::OutputNameRole);
}
foreach(const QString& viewType, analysis->viewTypesForOutput(outputName))
{
if (viewType.isEmpty()) { continue; }
QString viewPrettyName = analysis->viewPrettyName(outputName, viewType);
voDataModelItem * viewItem =
model->addView(viewType, viewPrettyName, dataObject, viewContainer);
viewItem->setData(outputName, voDataModelItem::OutputNameRole);
}
}
}
<|endoftext|> |
<commit_before>#include "OurCornerKick_pass.hpp"
#include <framework/RobotConfig.hpp>
#include <boost/foreach.hpp>
#include <iostream>
#include "../ReceivePointEvaluator.hpp"
using namespace std;
using namespace Geometry2d;
static const int requiredBotCount = 2;
REGISTER_PLAY_CATEGORY(Gameplay::Plays::OurCornerKick_Pass, "Restarts")
namespace Gameplay
{
namespace Plays
{
REGISTER_CONFIGURABLE(OurCornerKick_Pass)
}
}
ConfigDouble *Gameplay::Plays::OurCornerKick_Pass::_targetSegmentWidth;
ConfigDouble *Gameplay::Plays::OurCornerKick_Pass::_receiverChoiceHysterisis;
void Gameplay::Plays::OurCornerKick_Pass::createConfiguration(Configuration *cfg)
{
_targetSegmentWidth = new ConfigDouble(cfg, "OurCornerKick_Pass/Window Width", Field_Length / 4.);
_receiverChoiceHysterisis = new ConfigDouble(cfg, "OurCornerKick_Pass/Receiver Choice Hysterisis", 0);
}
Gameplay::Plays::OurCornerKick_Pass::OurCornerKick_Pass(GameplayModule *gameplay):
Play(gameplay),
_passer(gameplay),
_receiver1(gameplay),
_receiver2(gameplay),
_fullback1(gameplay, Behaviors::Fullback::Left),
_fullback2(gameplay, Behaviors::Fullback::Right),
_pdt(gameplay, &_passer)
{
// _center1.target = Point(0.0, Field_Length /2.0);
_passDone = false;
}
float Gameplay::Plays::OurCornerKick_Pass::score ( Gameplay::GameplayModule* gameplay )
{
const GameState &gs = gameplay->state()->gameState;
Point ballPos = gameplay->state()->ball.pos;
bool chipper_available = false;
BOOST_FOREACH(OurRobot * r, gameplay->playRobots())
{
if (r && r->chipper_available())
{
chipper_available = true;
break;
}
}
chipper_available = true; // FIXME: hack
bool enoughBots = gameplay->playRobots().size() >= 3;
// return (gs.setupRestart() && gs.ourDirect() && chipper_available && ballPos.y > (Field_Length - 1.5)) ? 1 : INFINITY;
return (enoughBots && gs.ourDirect() && chipper_available && ballPos.y > (Field_Length - 2.5)) ? 1 : INFINITY;
}
bool Gameplay::Plays::OurCornerKick_Pass::run()
{
set<OurRobot *> available = _gameplay->playRobots();
if ( available.size() < requiredBotCount ) return false;
// choose a target for the kick
// if straight shot on goal is available, take it
float goal_x = (ball().pos.x < 0) ? Field_GoalWidth / 2.0 : -Field_GoalWidth / 2.0;
Segment target(Point(goal_x, Field_Length), Point(goal_x, Field_Length - *_targetSegmentWidth));
if ( !_passDone ) {
if ( _receiver1.isDone() || _receiver2.isDone() ) {
_passDone = true;
}
}
// if the pass isn't done yet, setup for the pass
if ( !_passDone ) {
// Geometry2d::Point FindReceivingPoint(SystemState* state, Robot* robot, Geometry2d::Point ballPos, Geometry2d::Segment receivingLine);
Segment receiver1Segment(Point(-1.0f, Field_Length - 1.5f), Point(-2, Field_Length - 1.0f));
Segment receiver2Segment(Point(1.0f, Field_Length - 1.5f), Point(2.0f, Field_Length - 1.0f));
Point passTarget1;
Point passTarget2;
float target1Score = -1;
float target2Score = -1;
if ( _receiver1.robot ) {
Point pt = ReceivePointEvaluator::FindReceivingPoint(state(), _receiver1.robot->pos, ball().pos, receiver1Segment, &target1Score);
passTarget1 = pt;
state()->drawLine(receiver1Segment.pt[0], receiver1Segment.pt[1], Qt::black);
// state()->drawCircle(passTarget1, )
// state()->drawCircle(receivePosition(), Robot_Radius + 0.05, Qt::yellow, QString("DumbReceive"));
} else {
passTarget1 = receiver1Segment.center();
}
if ( _receiver2.robot ) {
Point pt = ReceivePointEvaluator::FindReceivingPoint(state(), _receiver2.robot->pos, ball().pos, receiver2Segment, &target1Score);
passTarget2 = pt;
state()->drawLine(receiver2Segment.pt[0], receiver2Segment.pt[1], Qt::black);
} else {
passTarget2 = receiver2Segment.center();
}
Point passerTarget;
// choose which receiver to pass to
bool firstIsBetter;
if ( target1Score == -1 ) {
firstIsBetter = false;
} else if ( target2Score == -1 ) {
firstIsBetter = true;
} else if ( _passingToFirstReceiver && (target2Score - target1Score) > *_receiverChoiceHysterisis ) {
firstIsBetter = false;
} else if ( !_passingToFirstReceiver && (target1Score - target2Score) > *_receiverChoiceHysterisis ) {
firstIsBetter = true;
} else {
firstIsBetter = _passingToFirstReceiver;
}
_passingToFirstReceiver = firstIsBetter;
// setup passer && receivers appropriately for the chosen point
if ( firstIsBetter ) {
passerTarget = passTarget1;
_passer.partner = &_receiver1;
_receiver1.partner = &_passer;
_receiver2.partner = NULL;
if ( _receiver2.robot ) _receiver2.robot->addText("Dummy");
} else {
passerTarget = passTarget2;
_passer.partner = &_receiver2;
_receiver2.partner = &_passer;
_receiver1.partner = NULL;
}
_passer.actionTarget = passerTarget;
_receiver1.actionTarget = passTarget1;
_receiver2.actionTarget = passTarget2;
assignNearest(_passer.robot, available, ball().pos);
assignNearest(_receiver1.robot, available, passTarget1);
assignNearest(_receiver2.robot, available, passTarget2);
const GameState &gs = _gameplay->state()->gameState;
if ( gs.canKick() ) {
_passer.robot->disableAvoidBall();
}
_pdt.backoff.robots.clear();
_pdt.backoff.robots.insert(_passer.robot);
// run passing behaviors
_pdt.run(); // runs passer
_receiver1.run();
_receiver2.run();
uint8_t dspeed = 60;
if ( _receiver1.robot ) _receiver1.robot->dribble(dspeed);
if ( _receiver2.robot ) _receiver2.robot->dribble(dspeed);
}
assignNearest(_fullback1.robot, available, Geometry2d::Point(-Field_GoalHeight/2.0, 0.0));
assignNearest(_fullback2.robot, available, Geometry2d::Point( Field_GoalHeight/2.0, 0.0));
_fullback2.run();
_fullback1.run();
return !_passDone;
}
<commit_msg>OurCornerKick_pass now resets kickers on the receivers before running<commit_after>#include "OurCornerKick_pass.hpp"
#include <framework/RobotConfig.hpp>
#include <boost/foreach.hpp>
#include <iostream>
#include "../ReceivePointEvaluator.hpp"
using namespace std;
using namespace Geometry2d;
static const int requiredBotCount = 2;
REGISTER_PLAY_CATEGORY(Gameplay::Plays::OurCornerKick_Pass, "Restarts")
namespace Gameplay
{
namespace Plays
{
REGISTER_CONFIGURABLE(OurCornerKick_Pass)
}
}
ConfigDouble *Gameplay::Plays::OurCornerKick_Pass::_targetSegmentWidth;
ConfigDouble *Gameplay::Plays::OurCornerKick_Pass::_receiverChoiceHysterisis;
void Gameplay::Plays::OurCornerKick_Pass::createConfiguration(Configuration *cfg)
{
_targetSegmentWidth = new ConfigDouble(cfg, "OurCornerKick_Pass/Window Width", Field_Length / 4.);
_receiverChoiceHysterisis = new ConfigDouble(cfg, "OurCornerKick_Pass/Receiver Choice Hysterisis", 0);
}
Gameplay::Plays::OurCornerKick_Pass::OurCornerKick_Pass(GameplayModule *gameplay):
Play(gameplay),
_passer(gameplay),
_receiver1(gameplay),
_receiver2(gameplay),
_fullback1(gameplay, Behaviors::Fullback::Left),
_fullback2(gameplay, Behaviors::Fullback::Right),
_pdt(gameplay, &_passer)
{
// _center1.target = Point(0.0, Field_Length /2.0);
_passDone = false;
}
float Gameplay::Plays::OurCornerKick_Pass::score ( Gameplay::GameplayModule* gameplay )
{
const GameState &gs = gameplay->state()->gameState;
Point ballPos = gameplay->state()->ball.pos;
bool chipper_available = false;
BOOST_FOREACH(OurRobot * r, gameplay->playRobots())
{
if (r && r->chipper_available())
{
chipper_available = true;
break;
}
}
chipper_available = true; // FIXME: hack
bool enoughBots = gameplay->playRobots().size() >= 3;
// return (gs.setupRestart() && gs.ourDirect() && chipper_available && ballPos.y > (Field_Length - 1.5)) ? 1 : INFINITY;
return (enoughBots && gs.ourDirect() && chipper_available && ballPos.y > (Field_Length - 2.5)) ? 1 : INFINITY;
}
bool Gameplay::Plays::OurCornerKick_Pass::run()
{
set<OurRobot *> available = _gameplay->playRobots();
if ( available.size() < requiredBotCount ) return false;
// choose a target for the kick
// if straight shot on goal is available, take it
float goal_x = (ball().pos.x < 0) ? Field_GoalWidth / 2.0 : -Field_GoalWidth / 2.0;
Segment target(Point(goal_x, Field_Length), Point(goal_x, Field_Length - *_targetSegmentWidth));
if ( !_passDone ) {
if ( _receiver1.isDone() || _receiver2.isDone() ) {
_passDone = true;
}
}
// if the pass isn't done yet, setup for the pass
if ( !_passDone ) {
// Geometry2d::Point FindReceivingPoint(SystemState* state, Robot* robot, Geometry2d::Point ballPos, Geometry2d::Segment receivingLine);
Segment receiver1Segment(Point(-1.0f, Field_Length - 1.5f), Point(-2, Field_Length - 1.0f));
Segment receiver2Segment(Point(1.0f, Field_Length - 1.5f), Point(2.0f, Field_Length - 1.0f));
Point passTarget1;
Point passTarget2;
float target1Score = -1;
float target2Score = -1;
if ( _receiver1.robot ) {
Point pt = ReceivePointEvaluator::FindReceivingPoint(state(), _receiver1.robot->pos, ball().pos, receiver1Segment, &target1Score);
passTarget1 = pt;
state()->drawLine(receiver1Segment.pt[0], receiver1Segment.pt[1], Qt::black);
// state()->drawCircle(passTarget1, )
// state()->drawCircle(receivePosition(), Robot_Radius + 0.05, Qt::yellow, QString("DumbReceive"));
} else {
passTarget1 = receiver1Segment.center();
}
if ( _receiver2.robot ) {
Point pt = ReceivePointEvaluator::FindReceivingPoint(state(), _receiver2.robot->pos, ball().pos, receiver2Segment, &target1Score);
passTarget2 = pt;
state()->drawLine(receiver2Segment.pt[0], receiver2Segment.pt[1], Qt::black);
} else {
passTarget2 = receiver2Segment.center();
}
Point passerTarget;
// choose which receiver to pass to
bool firstIsBetter;
if ( target1Score == -1 ) {
firstIsBetter = false;
} else if ( target2Score == -1 ) {
firstIsBetter = true;
} else if ( _passingToFirstReceiver && (target2Score - target1Score) > *_receiverChoiceHysterisis ) {
firstIsBetter = false;
} else if ( !_passingToFirstReceiver && (target1Score - target2Score) > *_receiverChoiceHysterisis ) {
firstIsBetter = true;
} else {
firstIsBetter = _passingToFirstReceiver;
}
_passingToFirstReceiver = firstIsBetter;
// setup passer && receivers appropriately for the chosen point
if ( firstIsBetter ) {
passerTarget = passTarget1;
_passer.partner = &_receiver1;
_receiver1.partner = &_passer;
_receiver2.partner = NULL;
if ( _receiver2.robot ) _receiver2.robot->addText("Dummy");
} else {
passerTarget = passTarget2;
_passer.partner = &_receiver2;
_receiver2.partner = &_passer;
_receiver1.partner = NULL;
}
_passer.actionTarget = passerTarget;
_receiver1.actionTarget = passTarget1;
_receiver2.actionTarget = passTarget2;
assignNearest(_passer.robot, available, ball().pos);
assignNearest(_receiver1.robot, available, passTarget1);
assignNearest(_receiver2.robot, available, passTarget2);
const GameState &gs = _gameplay->state()->gameState;
if ( gs.canKick() ) {
_passer.robot->disableAvoidBall();
}
_pdt.backoff.robots.clear();
_pdt.backoff.robots.insert(_passer.robot);
// run passing behaviors
_pdt.run(); // runs passer
_receiver1.run();
_receiver2.run();
uint8_t dspeed = 60;
if ( _receiver1.robot ) {
_receiver1.robot->dribble(dspeed);
_receiver1.robot->kick(0); // undo kick
}
if ( _receiver2.robot ) {
_receiver2.robot->dribble(dspeed);
_receiver2.robot->kick(0);
}
}
assignNearest(_fullback1.robot, available, Geometry2d::Point(-Field_GoalHeight/2.0, 0.0));
assignNearest(_fullback2.robot, available, Geometry2d::Point( Field_GoalHeight/2.0, 0.0));
_fullback2.run();
_fullback1.run();
return !_passDone;
}
<|endoftext|> |
<commit_before>#include "../../include/cutehmi/Notifier.hpp"
namespace cutehmi {
Notifier::Notifier(QObject * parent):
QObject(parent),
m(new Members)
{
}
NotificationListModel * Notifier::model() const
{
return m->model.get();
}
int Notifier::maxNotifications() const
{
return m->maxNotifications;
}
void Notifier::setMaxNotifications(int maxNotifications)
{
if (m->maxNotifications != maxNotifications) {
m->maxNotifications = maxNotifications;
if (m->model->rowCount() > maxNotifications)
m->model->removeLast(m->model->rowCount() - maxNotifications);
emit maxNotificationsChanged();
}
}
void Notifier::add(Notification * notification_l)
{
QMutexLocker locker(& m->modelMutex);
#ifndef CUTEHMI_NDEBUG
switch (notification_l->type()) {
case Notification::INFO:
CUTEHMI_INFO("[NOTIFICATION] " << notification_l->text());
break;
case Notification::WARNING:
CUTEHMI_WARNING("[NOTIFICATION] " << notification_l->text());
break;
case Notification::CRITICAL:
CUTEHMI_CRITICAL("[NOTIFICATION] " << notification_l->text());
break;
default:
CUTEHMI_CRITICAL("Unrecognized code ('" << notification_l->type() << "') of 'Notification::type()'. Assuming 'Notification::CRITICAL'.");
CUTEHMI_CRITICAL("[NOTIFICATION] " << notification_l->text());
}
#endif
m->model->prepend(notification_l->clone());
if (m->model->rowCount() > maxNotifications())
m->model->removeLast();
}
void Notifier::clear()
{
m->model->clear();
}
}
//(c)C: Copyright © 2019, Michał Policht <michal@policht.pl>. All rights reserved.
//(c)C: This file is a part of CuteHMI.
//(c)C: CuteHMI is free software: you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version.
//(c)C: CuteHMI 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.
//(c)C: You should have received a copy of the GNU Lesser General Public License along with CuteHMI. If not, see <https://www.gnu.org/licenses/>.
<commit_msg>Forward notifications to logs in release mode.<commit_after>#include "../../include/cutehmi/Notifier.hpp"
namespace cutehmi {
Notifier::Notifier(QObject * parent):
QObject(parent),
m(new Members)
{
}
NotificationListModel * Notifier::model() const
{
return m->model.get();
}
int Notifier::maxNotifications() const
{
return m->maxNotifications;
}
void Notifier::setMaxNotifications(int maxNotifications)
{
if (m->maxNotifications != maxNotifications) {
m->maxNotifications = maxNotifications;
if (m->model->rowCount() > maxNotifications)
m->model->removeLast(m->model->rowCount() - maxNotifications);
emit maxNotificationsChanged();
}
}
void Notifier::add(Notification * notification_l)
{
QMutexLocker locker(& m->modelMutex);
switch (notification_l->type()) {
case Notification::INFO:
CUTEHMI_INFO("[NOTIFICATION] " << notification_l->text());
break;
case Notification::WARNING:
CUTEHMI_WARNING("[NOTIFICATION] " << notification_l->text());
break;
case Notification::CRITICAL:
CUTEHMI_CRITICAL("[NOTIFICATION] " << notification_l->text());
break;
default:
CUTEHMI_CRITICAL("Unrecognized code ('" << notification_l->type() << "') of 'Notification::type()'. Assuming 'Notification::CRITICAL'.");
CUTEHMI_CRITICAL("[NOTIFICATION] " << notification_l->text());
}
m->model->prepend(notification_l->clone());
if (m->model->rowCount() > maxNotifications())
m->model->removeLast();
}
void Notifier::clear()
{
m->model->clear();
}
}
//(c)C: Copyright © 2019, Michał Policht <michal@policht.pl>. All rights reserved.
//(c)C: This file is a part of CuteHMI.
//(c)C: CuteHMI is free software: you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version.
//(c)C: CuteHMI 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.
//(c)C: You should have received a copy of the GNU Lesser General Public License along with CuteHMI. If not, see <https://www.gnu.org/licenses/>.
<|endoftext|> |
<commit_before>/*=========================================================================
Program: Monteverdi2
Language: C++
Copyright (c) Centre National d'Etudes Spatiales. All rights reserved.
See Copyright.txt for details.
Monteverdi2 is distributed under the CeCILL licence version 2. See
Licence_CeCILL_V2-en.txt or
http://www.cecill.info/licences/Licence_CeCILL_V2-en.txt for more details.
This software is distributed WITHOUT ANY WARRANTY; without even
the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR
PURPOSE. See the above copyright notices for more information.
=========================================================================*/
#include "Gui/mvdColorDynamicsWidget.h"
#include "Gui/ui_mvdColorDynamicsWidget.h"
//
// Qt includes (sorted by alphabetic order)
//// Must be included before system/custom includes.
//
// System includes (sorted by alphabetic order)
//
// ITK includes (sorted by alphabetic order)
//
// OTB includes (sorted by alphabetic order)
//
// Monteverdi includes (sorted by alphabetic order)
namespace mvd
{
/*
TRANSLATOR mvd::ColorDynamicsWidget
Necessary for lupdate to be aware of C++ namespaces.
Context comment for translator.
*/
/*****************************************************************************/
/* CONSTANTS */
const char*
ColorDynamicsWidget::COLOR_BAND_DYNAMICS_WIDGET_NAMES[] = {
"redWidget",
"greenWidget",
"blueWidget",
"whiteWidget"
};
const double GAMMA_FACTOR = -0.25;
const double GAMMA_POWER = 1.1;
/*****************************************************************************/
/* STATIC IMPLEMENTATION SECTION */
/*****************************************************************************/
/* CLASS IMPLEMENTATION SECTION */
/*****************************************************************************/
ColorDynamicsWidget
::ColorDynamicsWidget( QWidget* parent, Qt::WindowFlags flags ):
QWidget( parent, flags ),
m_UI( new mvd::Ui::ColorDynamicsWidget() ),
m_NoDataValidator( NULL ),
m_IsGrayscaleActivated( false )
{
//
// Qt setup.
m_UI->setupUi( this );
//
// Colors.
CountType begin;
CountType end;
RgbwBounds( begin, end, RGBW_CHANNEL_ALL );
for( CountType i=begin; i<end; ++i )
{
RgbwChannel channel( static_cast< RgbwChannel >( i ) );
ConnectChild( GetChannel( channel ), channel );
}
SetGrayscaleActivated( false );
//
// No-data.
m_NoDataValidator = new QDoubleValidator( m_UI->noDataLineEdit );
m_UI->noDataLineEdit->setValidator( m_NoDataValidator );
}
/*******************************************************************************/
ColorDynamicsWidget
::~ColorDynamicsWidget()
{
delete m_UI;
m_UI = NULL;
}
/*****************************************************************************/
void
ColorDynamicsWidget
::SetGrayscaleActivated( bool activated )
{
m_IsGrayscaleActivated = activated;
//
// First, force WHITE channel to be invisible.
//
// Cause: prevent layout re-calculation to be resized taking RGB+W
// into account when switching from grayscale-mode activated to
// non-activated.
if( !activated )
{
GetChannel( RGBW_CHANNEL_WHITE )->setVisible( false );
}
//
// Then, show/hide relevant components.
CountType begin;
CountType end;
RgbwBounds( begin, end, RGBW_CHANNEL_RGB );
for( CountType i=begin; i<end; ++i )
{
RgbwChannel channel( static_cast< RgbwChannel >( i ) );
GetChannel( channel )->setVisible( !activated );
}
GetChannel( RGBW_CHANNEL_WHITE )->setVisible( activated );
m_UI->bwLine->setVisible( false );
m_UI->rgLine->setVisible( !activated );
m_UI->gbLine->setVisible( !activated );
}
/*******************************************************************************/
bool
ColorDynamicsWidget
::IsNoDataChecked() const
{
return m_UI->noDataCheckBox->isChecked();
}
/*******************************************************************************/
void
ColorDynamicsWidget
::SetNoDataChecked( bool checked )
{
m_UI->noDataCheckBox->setChecked( checked );
}
/*******************************************************************************/
double
ColorDynamicsWidget
::GetNoDataValue() const
{
bool isOk = true;
double value = m_UI->noDataLineEdit->text().toDouble( &isOk );
if( !isOk )
{
}
return value;
}
/*******************************************************************************/
void
ColorDynamicsWidget
::SetNoDataValue( double value )
{
QString number(
QString::number( value, 'g', m_NoDataValidator->decimals() ) );
m_UI->noDataLineEdit->setText( number );
}
/*******************************************************************************/
void
ColorDynamicsWidget
::SetGamma( double value )
{
int gamma =
itk::Math::Round< int, double >(
GAMMA_FACTOR * vcl_log( value ) / vcl_log( GAMMA_POWER )
);
int min = GetMinGamma();
if( gamma<min )
gamma = min;
int max = GetMaxGamma();
if( gamma>max )
gamma = max;
SetGammaCursorPosition( gamma );
}
/*******************************************************************************/
double
ColorDynamicsWidget
::GetGamma() const
{
return
vcl_pow(
GAMMA_POWER,
GAMMA_FACTOR * static_cast< double >( GetGammaCursorPosition() )
);
}
/*******************************************************************************/
void
ColorDynamicsWidget
::SetGammaCursorPosition( int value )
{
m_UI->gammaSlider->setValue( value );
}
/*******************************************************************************/
int
ColorDynamicsWidget
::GetGammaCursorPosition() const
{
return m_UI->gammaSlider->value();
}
/*******************************************************************************/
void
ColorDynamicsWidget
::SetMinGamma( int value )
{
m_UI->gammaSlider->setMinimum( value );
}
/*******************************************************************************/
int
ColorDynamicsWidget
::GetMinGamma() const
{
return m_UI->gammaSlider->minimum();
}
/*******************************************************************************/
void
ColorDynamicsWidget
::SetMaxGamma( int value )
{
m_UI->gammaSlider->setMaximum( value );
}
/*******************************************************************************/
int
ColorDynamicsWidget
::GetMaxGamma() const
{
return m_UI->gammaSlider->maximum();
}
/*******************************************************************************/
void
ColorDynamicsWidget
::SetGammaStep( int value )
{
m_UI->gammaSlider->setPageStep( value );
}
/*******************************************************************************/
int
ColorDynamicsWidget
::GetGammaStep() const
{
return m_UI->gammaSlider->pageStep();
}
/*******************************************************************************/
void
ColorDynamicsWidget
::ConnectChild( ColorBandDynamicsWidget* child, RgbwChannel channel )
{
child->SetChannelLabel( channel );
//
// Concentrate and forward signals of each channels.
QObject::connect(
child,
SIGNAL( LowQuantileChanged( RgbwChannel, double ) ),
// TO:
this,
SIGNAL( LowQuantileChanged( RgbwChannel, double ) )
);
QObject::connect(
child,
SIGNAL( HighQuantileChanged( RgbwChannel, double ) ),
// TO:
this,
SIGNAL( HighQuantileChanged( RgbwChannel, double ) )
);
QObject::connect(
child,
SIGNAL( LowIntensityChanged( RgbwChannel, double ) ),
// TO:
this,
SIGNAL( LowIntensityChanged( RgbwChannel, double ) )
);
QObject::connect(
child,
SIGNAL( HighIntensityChanged( RgbwChannel, double ) ),
// TO:
this,
SIGNAL( HighIntensityChanged( RgbwChannel, double ) )
);
QObject::connect(
child,
SIGNAL( ResetQuantileClicked( RgbwChannel ) ),
// TO:
this,
SIGNAL( ResetQuantileClicked( RgbwChannel ) )
);
QObject::connect(
child,
SIGNAL( ResetIntensityClicked( RgbwChannel ) ),
// TO:
this,
SIGNAL( ResetIntensityClicked( RgbwChannel ) )
);
QObject::connect(
child,
SIGNAL( ApplyAllClicked( RgbwChannel, double, double ) ),
// TO:
this,
SIGNAL( ApplyAllClicked( RgbwChannel, double, double ) )
);
QObject::connect(
child,
SIGNAL( LinkToggled( RgbwChannel, bool ) ),
// TO:
this,
SIGNAL( LinkToggled( RgbwChannel, bool ) )
);
}
/*****************************************************************************/
/* PUBLIC SLOTS */
/*****************************************************************************/
void
ColorDynamicsWidget
::SetNoDataButtonChecked( bool checked )
{
if( checked )
{
m_UI->noDataButton->setEnabled( false );
m_UI->noDataButton->setChecked( true );
// m_UI->noDataButton->setText( tr( "Done" ) );
}
else
{
m_UI->noDataButton->setEnabled( true );
m_UI->noDataButton->setChecked( false );
// m_UI->noDataButton->setText( tr( "GO" ) );
}
}
/*******************************************************************************/
/* SLOTS */
/*****************************************************************************/
void
ColorDynamicsWidget
::on_noDataCheckBox_toggled( bool enabled )
{
emit NoDataFlagToggled( enabled );
}
/*****************************************************************************/
void
ColorDynamicsWidget
::on_noDataLineEdit_textChanged( const QString& text )
{
bool isOk = true;
double value = text.toDouble( &isOk );
if( !isOk )
{
}
emit NoDataValueChanged( value );
}
/*****************************************************************************/
void
ColorDynamicsWidget
::on_noDataButton_toggled( bool checked )
{
bool thisSB = this->blockSignals( true );
{
bool uiSB = m_UI->noDataButton->blockSignals( true );
{
SetNoDataButtonChecked( checked );
}
m_UI->noDataButton->blockSignals( uiSB );
}
this->blockSignals( thisSB );
if( checked )
{
emit NoDataButtonPressed();
}
}
/*****************************************************************************/
void
ColorDynamicsWidget
::on_gammaSlider_valueChanged( int value )
{
emit GammaCursorPositionChanged( value );
emit GammaValueChanged( GetGamma() );
}
} // end namespace 'mvd'
<commit_msg>ENH: display gamma value in a tooltip when value changed<commit_after>/*=========================================================================
Program: Monteverdi2
Language: C++
Copyright (c) Centre National d'Etudes Spatiales. All rights reserved.
See Copyright.txt for details.
Monteverdi2 is distributed under the CeCILL licence version 2. See
Licence_CeCILL_V2-en.txt or
http://www.cecill.info/licences/Licence_CeCILL_V2-en.txt for more details.
This software is distributed WITHOUT ANY WARRANTY; without even
the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR
PURPOSE. See the above copyright notices for more information.
=========================================================================*/
#include "Gui/mvdColorDynamicsWidget.h"
#include "Gui/ui_mvdColorDynamicsWidget.h"
//
// Qt includes (sorted by alphabetic order)
//// Must be included before system/custom includes.
//
// System includes (sorted by alphabetic order)
//
// ITK includes (sorted by alphabetic order)
//
// OTB includes (sorted by alphabetic order)
//
// Monteverdi includes (sorted by alphabetic order)
namespace mvd
{
/*
TRANSLATOR mvd::ColorDynamicsWidget
Necessary for lupdate to be aware of C++ namespaces.
Context comment for translator.
*/
/*****************************************************************************/
/* CONSTANTS */
const char*
ColorDynamicsWidget::COLOR_BAND_DYNAMICS_WIDGET_NAMES[] = {
"redWidget",
"greenWidget",
"blueWidget",
"whiteWidget"
};
const double GAMMA_FACTOR = -0.25;
const double GAMMA_POWER = 1.1;
/*****************************************************************************/
/* STATIC IMPLEMENTATION SECTION */
/*****************************************************************************/
/* CLASS IMPLEMENTATION SECTION */
/*****************************************************************************/
ColorDynamicsWidget
::ColorDynamicsWidget( QWidget* parent, Qt::WindowFlags flags ):
QWidget( parent, flags ),
m_UI( new mvd::Ui::ColorDynamicsWidget() ),
m_NoDataValidator( NULL ),
m_IsGrayscaleActivated( false )
{
//
// Qt setup.
m_UI->setupUi( this );
//
// Colors.
CountType begin;
CountType end;
RgbwBounds( begin, end, RGBW_CHANNEL_ALL );
for( CountType i=begin; i<end; ++i )
{
RgbwChannel channel( static_cast< RgbwChannel >( i ) );
ConnectChild( GetChannel( channel ), channel );
}
SetGrayscaleActivated( false );
//
// No-data.
m_NoDataValidator = new QDoubleValidator( m_UI->noDataLineEdit );
m_UI->noDataLineEdit->setValidator( m_NoDataValidator );
}
/*******************************************************************************/
ColorDynamicsWidget
::~ColorDynamicsWidget()
{
delete m_UI;
m_UI = NULL;
}
/*****************************************************************************/
void
ColorDynamicsWidget
::SetGrayscaleActivated( bool activated )
{
m_IsGrayscaleActivated = activated;
//
// First, force WHITE channel to be invisible.
//
// Cause: prevent layout re-calculation to be resized taking RGB+W
// into account when switching from grayscale-mode activated to
// non-activated.
if( !activated )
{
GetChannel( RGBW_CHANNEL_WHITE )->setVisible( false );
}
//
// Then, show/hide relevant components.
CountType begin;
CountType end;
RgbwBounds( begin, end, RGBW_CHANNEL_RGB );
for( CountType i=begin; i<end; ++i )
{
RgbwChannel channel( static_cast< RgbwChannel >( i ) );
GetChannel( channel )->setVisible( !activated );
}
GetChannel( RGBW_CHANNEL_WHITE )->setVisible( activated );
m_UI->bwLine->setVisible( false );
m_UI->rgLine->setVisible( !activated );
m_UI->gbLine->setVisible( !activated );
}
/*******************************************************************************/
bool
ColorDynamicsWidget
::IsNoDataChecked() const
{
return m_UI->noDataCheckBox->isChecked();
}
/*******************************************************************************/
void
ColorDynamicsWidget
::SetNoDataChecked( bool checked )
{
m_UI->noDataCheckBox->setChecked( checked );
}
/*******************************************************************************/
double
ColorDynamicsWidget
::GetNoDataValue() const
{
bool isOk = true;
double value = m_UI->noDataLineEdit->text().toDouble( &isOk );
if( !isOk )
{
}
return value;
}
/*******************************************************************************/
void
ColorDynamicsWidget
::SetNoDataValue( double value )
{
QString number(
QString::number( value, 'g', m_NoDataValidator->decimals() ) );
m_UI->noDataLineEdit->setText( number );
}
/*******************************************************************************/
void
ColorDynamicsWidget
::SetGamma( double value )
{
int gamma =
itk::Math::Round< int, double >(
GAMMA_FACTOR * vcl_log( value ) / vcl_log( GAMMA_POWER )
);
int min = GetMinGamma();
if( gamma<min )
gamma = min;
int max = GetMaxGamma();
if( gamma>max )
gamma = max;
SetGammaCursorPosition( gamma );
}
/*******************************************************************************/
double
ColorDynamicsWidget
::GetGamma() const
{
return
vcl_pow(
GAMMA_POWER,
GAMMA_FACTOR * static_cast< double >( GetGammaCursorPosition() )
);
}
/*******************************************************************************/
void
ColorDynamicsWidget
::SetGammaCursorPosition( int value )
{
m_UI->gammaSlider->setValue( value );
}
/*******************************************************************************/
int
ColorDynamicsWidget
::GetGammaCursorPosition() const
{
return m_UI->gammaSlider->value();
}
/*******************************************************************************/
void
ColorDynamicsWidget
::SetMinGamma( int value )
{
m_UI->gammaSlider->setMinimum( value );
}
/*******************************************************************************/
int
ColorDynamicsWidget
::GetMinGamma() const
{
return m_UI->gammaSlider->minimum();
}
/*******************************************************************************/
void
ColorDynamicsWidget
::SetMaxGamma( int value )
{
m_UI->gammaSlider->setMaximum( value );
}
/*******************************************************************************/
int
ColorDynamicsWidget
::GetMaxGamma() const
{
return m_UI->gammaSlider->maximum();
}
/*******************************************************************************/
void
ColorDynamicsWidget
::SetGammaStep( int value )
{
m_UI->gammaSlider->setPageStep( value );
}
/*******************************************************************************/
int
ColorDynamicsWidget
::GetGammaStep() const
{
return m_UI->gammaSlider->pageStep();
}
/*******************************************************************************/
void
ColorDynamicsWidget
::ConnectChild( ColorBandDynamicsWidget* child, RgbwChannel channel )
{
child->SetChannelLabel( channel );
//
// Concentrate and forward signals of each channels.
QObject::connect(
child,
SIGNAL( LowQuantileChanged( RgbwChannel, double ) ),
// TO:
this,
SIGNAL( LowQuantileChanged( RgbwChannel, double ) )
);
QObject::connect(
child,
SIGNAL( HighQuantileChanged( RgbwChannel, double ) ),
// TO:
this,
SIGNAL( HighQuantileChanged( RgbwChannel, double ) )
);
QObject::connect(
child,
SIGNAL( LowIntensityChanged( RgbwChannel, double ) ),
// TO:
this,
SIGNAL( LowIntensityChanged( RgbwChannel, double ) )
);
QObject::connect(
child,
SIGNAL( HighIntensityChanged( RgbwChannel, double ) ),
// TO:
this,
SIGNAL( HighIntensityChanged( RgbwChannel, double ) )
);
QObject::connect(
child,
SIGNAL( ResetQuantileClicked( RgbwChannel ) ),
// TO:
this,
SIGNAL( ResetQuantileClicked( RgbwChannel ) )
);
QObject::connect(
child,
SIGNAL( ResetIntensityClicked( RgbwChannel ) ),
// TO:
this,
SIGNAL( ResetIntensityClicked( RgbwChannel ) )
);
QObject::connect(
child,
SIGNAL( ApplyAllClicked( RgbwChannel, double, double ) ),
// TO:
this,
SIGNAL( ApplyAllClicked( RgbwChannel, double, double ) )
);
QObject::connect(
child,
SIGNAL( LinkToggled( RgbwChannel, bool ) ),
// TO:
this,
SIGNAL( LinkToggled( RgbwChannel, bool ) )
);
}
/*****************************************************************************/
/* PUBLIC SLOTS */
/*****************************************************************************/
void
ColorDynamicsWidget
::SetNoDataButtonChecked( bool checked )
{
if( checked )
{
m_UI->noDataButton->setEnabled( false );
m_UI->noDataButton->setChecked( true );
// m_UI->noDataButton->setText( tr( "Done" ) );
}
else
{
m_UI->noDataButton->setEnabled( true );
m_UI->noDataButton->setChecked( false );
// m_UI->noDataButton->setText( tr( "GO" ) );
}
}
/*******************************************************************************/
/* SLOTS */
/*****************************************************************************/
void
ColorDynamicsWidget
::on_noDataCheckBox_toggled( bool enabled )
{
emit NoDataFlagToggled( enabled );
}
/*****************************************************************************/
void
ColorDynamicsWidget
::on_noDataLineEdit_textChanged( const QString& text )
{
bool isOk = true;
double value = text.toDouble( &isOk );
if( !isOk )
{
}
emit NoDataValueChanged( value );
}
/*****************************************************************************/
void
ColorDynamicsWidget
::on_noDataButton_toggled( bool checked )
{
bool thisSB = this->blockSignals( true );
{
bool uiSB = m_UI->noDataButton->blockSignals( true );
{
SetNoDataButtonChecked( checked );
}
m_UI->noDataButton->blockSignals( uiSB );
}
this->blockSignals( thisSB );
if( checked )
{
emit NoDataButtonPressed();
}
}
/*****************************************************************************/
void
ColorDynamicsWidget
::on_gammaSlider_valueChanged( int value )
{
emit GammaCursorPositionChanged( value );
emit GammaValueChanged( GetGamma() );
//Display Gamma value as a tooltip when value changed
QToolTip::showText(mapToGlobal(m_UI->gammaSlider->pos()),tr("Gamma : ") % QString::number(GetGamma()) );
}
} // end namespace 'mvd'
<|endoftext|> |
<commit_before>#include <iostream>
#include <ostream>
#include <fstream>
#include <sstream>
#include "parse.h"
#include <stdio.h>
#include <stdlib.h>
#include <sys/types.h>
#include <unistd.h>
#include <sys/wait.h>
using namespace std;
//Base Executable
Executable::Executable(string info)
{
this->info = info;
}
string Executable::getInfo() { return this->info; }
char Executable::getValidate() { return this->validate; }
void Executable::changeValidate(char validate)
{
this->validate = validate;
}
void Executable::insert(Executable* entry, string object)
{
output.push_back(entry);
input.push_back(object);
}
void Executable::print()
{
for(unsigned int i = 0; i < output.size(); ++i)
{
cout << output.at(i)->info << " ";
cout << input.at(i) << " ";
}
cout << endl << "Test case successfully printed." << endl << endl;
}
//http://stackoverflow.com/questions/347949/how-to-convert-a-stdstring-to-const-char-or-char
//Loop up the arguments for execvp()
void Executable::execute()
{
// if(this->output.size() == 1)
// {
// if (output.at(0)->getInfo() == "exit") //working properly
// {
// cout << "Return command (rtn) was called. Terminating." << endl << endl;
// this->deleteVector();
// exit (EXIT_SUCCESS);
// }
// char* c[3];
// c[0] = (char*)this->output.at(0)->info.c_str();
// c[1] = (char*)this->input.at(0).c_str();
// c[2] = NULL;
// if(execvp(c[0],c) == -1)
// {
// perror("exec");
// }
// return;
// }
for(unsigned int i = 0; i < this->output.size(); ++i)
{
if (output.at(i)->getInfo() == "exit") //working properly
{
cout << "Return command (exit) was called. Terminating." << endl << endl;
this->deleteVector();
exit (EXIT_SUCCESS);
}
// if (input.at(i) == "rtn") //working properly
// {
// cout << "Return command (rtn) was called. Terminating." << endl << endl;
// return;
// }
this->output.at(i)->apply(i, this->output, this->input);
}
this->deleteVector();
//cout << "Successful; exit command not called" << endl << endl;
}
void Executable::deleteVector()
{
this->output.resize(0);
this->input.resize(0);
}
void Executable::apply(int x, vector<Executable*> out, vector<string> in)
{
//will only call reeolved sub-class functions
}
//Semicolon
Semicolon::Semicolon():Executable() {}
Semicolon::Semicolon(string info):Executable(info) {}
void Semicolon::apply(int x, vector<Executable*> out, vector<string> in)
{
//cout << x << endl; //test output
if(out.at(x)->getInfo() == "exit") {exit (EXIT_SUCCESS);;}
char* c[3];
c[0] = (char*)out.at(x)->getInfo().c_str();
c[1] = (char*)in.at(x).c_str();
c[2] = NULL;
pid_t pid = fork();
if(pid < 0)
{
perror("fork()");
}
else if(pid == 0)
{
execvp(c[0], c);
exit(0);
}
else
{
int status;
if(wait(&status) == -1)
{
perror("wait()");
}
if(WIFEXITED(status))
{
if(WEXITSTATUS(status) == 0)
{
out.at(x)->changeValidate('y');
}
else
{
out.at(x)->changeValidate('n');
}
}
else
{
perror("execvp error");
}
}
}
//Ampersand
Ampersand::Ampersand():Executable() {}
Ampersand::Ampersand(string info):Executable(info) {}
void Ampersand::apply(int x, vector<Executable*> out, vector<string> in)
{
//cout << x << endl; //test output
if(out.at(x)->getInfo() == "exit") {exit (EXIT_SUCCESS);}
if( out.at(x - 1)->getValidate() == 'n')
{
out.at(x)->changeValidate('n');
return;
}
char* c[3];
c[0] = (char*)out.at(x)->getInfo().c_str();
c[1] = (char*)in.at(x).c_str();
c[2] = NULL;
pid_t pid = fork();
if(pid < 0)
{
perror("fork()");
}
else if(pid == 0)
{
execvp(c[0], c);
exit(0);
}
else
{
int status;
if(wait(&status) == -1)
{
perror("wait()");
}
if(WIFEXITED(status))
{
if(WEXITSTATUS(status) == 0)
{
out.at(x)->changeValidate('y');
}
else
{
out.at(x)->changeValidate('n');
}
}
else
{
perror("execvp error");
}
}
}
//vertical
Vertical::Vertical():Executable() {}
Vertical::Vertical(string info):Executable(info) {}
void Vertical::apply(int x, vector<Executable*> out, vector<string> in)
{
if( out.at(x - 1)->getValidate() == 'y')
{
out.at(x)->changeValidate('n');
return;
}
//cout << x << endl; //test output
char* c[3];
c[0] = (char*)out.at(x)->getInfo().c_str();
c[1] = (char*)in.at(x).c_str();
c[2] = NULL;
pid_t pid = fork();
if(pid < 0)
{
perror("fork()");
}
else if(pid == 0)
{
execvp(c[0], c);
exit(0);
}
else
{
int status;
if(wait(&status) == -1)
{
perror("wait()");
}
if(WIFEXITED(status))
{
if(WEXITSTATUS(status) == 0)
{
out.at(x)->changeValidate('y');
}
else
{
out.at(x)->changeValidate('n');
}
}
else
{
perror("execvp error");
}
}
}
<commit_msg>Delete parse.cpp<commit_after><|endoftext|> |
<commit_before>#include "text_editor.h"
#include "string_constants.h"
#include "printutils.h"
#include "utils.h"
using namespace std;
void TextEditor::clearWindows()
{
x = 0;
y = 0;
done = 0;
delwin(headerWindow);
delwin(mainWindow);
clear();
}
vector<string> TextEditor::edit(string header,vector<string> startText)
{
text = join(0,startText," ");
x = 0;
y = 0;
pos = 0;
headerWindow = newwin(1,getCols(),0,0);
mainWindow = newwin(LINES-1,getCols(),1,0);
printHeader(headerWindow,header);
keypad(mainWindow,true); //turns on arrows and f keys
wrefresh(headerWindow);
wrefresh(mainWindow);
while(!done)
{
printBuff();
int input = wgetch(mainWindow);
handleInput(input);
}
clearWindows();
return split(text,CHR_SPACE);
}
string TextEditor::remTabs(string line) {
int tab = line.find("\t");
if(tab == line.npos)
return line;
else
return remTabs(line.replace(tab,1,STR_TAB));
}
void TextEditor::moveLeft() {
if (pos > 0) pos--;
}
void TextEditor::moveRight() {
if (pos < text.size()) pos++;
}
void TextEditor::moveUp() {
if(y > 0)
y--;
wmove(mainWindow,y,x);
}
void TextEditor::moveDown() {
y++;
wmove(mainWindow,y,x);
}
void TextEditor::handleInput(int c) {
switch(c)
{
case KEY_HOME:
x = 0;
break;
case KEY_END:
x = getCols();
break;
case KEY_LEFT:
moveLeft();
break;
case KEY_RIGHT:
moveRight();
break;
case KEY_UP:
moveUp();
break;
case KEY_DOWN:
moveDown();
break;
case 27: //escape key
done = 1;
break;
case KEY_BACKSPACE:
case 127: // Mac OSX delete key
case 8: // backspace
// The Backspace key
if(pos != 0)
{
pos--;
text.erase(pos,1);
}
break;
case KEY_DC:
if(pos < text.size())
{
text.erase(pos,1);
pos--;
}
break;
case KEY_ENTER:
case 10:
text.insert(pos,1,char(CHR_NEWLINE));
pos++;
break;
case KEY_BTAB:
case KEY_CTAB:
case KEY_STAB:
case KEY_CATAB:
case 9:
// The Tab key
text.insert(pos,4,CHR_SPACE);
pos += 4;
break;
default:
// Any other character insert
text.insert(pos,1,char(c));
pos++;
break;
}
}
void TextEditor::printBuff() {
wclear(mainWindow);
lineLengths.clear();
size_t px=0;
size_t py = 0;
x=0;
y=0;
vector<string> tokens = splitOnSpaceAndEnter(text);
size_t counter = 0;
for(auto token : tokens) {
int remainingWidth = getCols() - px;
if(token[0] == CHR_SPACE)
{
for(size_t i = 0; i < token.size(); i++)
{
if(px >= getCols()){
lineLengths.push_back(px);
py++;
px = 0;
}
mvwaddch(mainWindow,py,px,CHR_SPACE);
if(counter == pos)
{
x = px;
y = py;
}
counter++;
px++;
}
}
else
{
if(token.size() > remainingWidth ) {
lineLengths.push_back(px);
py++;
px = 0;
}
for(size_t i = 0; i < token.size(); i++)
{
mvwprintw(mainWindow,py,px,&token[i]);
if(counter == pos)
{
x = px;
y = py;
}
if(i == token.size()-1 && (unsigned char)token[i] == CHR_NEWLINE)
{
px = 0;
py++;
}
else
{
px++;
}
counter++;
}
}
}
if(counter == pos)
{
x = px;
y = py;
}
wmove(mainWindow,y,x);
}
<commit_msg>text editor! complete! ishgit add *<commit_after>#include "text_editor.h"
#include "string_constants.h"
#include "printutils.h"
#include "utils.h"
using namespace std;
void TextEditor::clearWindows()
{
x = 0;
y = 0;
done = 0;
delwin(headerWindow);
delwin(mainWindow);
clear();
}
vector<string> TextEditor::edit(string header,vector<string> startText)
{
text = join(0,startText," ");
x = 0;
y = 0;
pos = 0;
headerWindow = newwin(1,getCols(),0,0);
mainWindow = newwin(LINES-1,getCols(),1,0);
printHeader(headerWindow,header);
keypad(mainWindow,true); //turns on arrows and f keys
wrefresh(headerWindow);
wrefresh(mainWindow);
while(!done)
{
printBuff();
int input = wgetch(mainWindow);
handleInput(input);
}
clearWindows();
return split(text,CHR_SPACE);
}
string TextEditor::remTabs(string line) {
int tab = line.find("\t");
if(tab == line.npos)
return line;
else
return remTabs(line.replace(tab,1,STR_TAB));
}
void TextEditor::moveLeft() {
if(pos > 0) pos--;
}
// abcd 1234
// efgh 5431
void TextEditor::moveRight() {
if(pos < text.size()) pos++;
}
void TextEditor::moveUp() {
if(y > 0) {
pos = pos - x; //pop us to the start of this line
if(x < lineLengths[y-1])
{
pos = pos - (lineLengths[y-1] - x); //then to the proper position of the previous line
}
else
{
pos--;
}
}
}
void TextEditor::moveDown() {
if(y < lineLengths.size()-1)
{
pos = pos + (lineLengths[y]-x);
if(x < lineLengths[y+1])
{
pos = pos + x;
}
else {
pos = pos + lineLengths[y+1]-1;
}
}
}
void TextEditor::handleInput(int c) {
switch(c)
{
case KEY_HOME:
pos = pos - x;
break;
case KEY_END:
pos = pos + lineLengths[y] - x -1;
break;
case KEY_LEFT:
moveLeft();
break;
case KEY_RIGHT:
moveRight();
break;
case KEY_UP:
moveUp();
break;
case KEY_DOWN:
moveDown();
break;
case 27: //escape key
done = 1;
break;
case KEY_BACKSPACE:
case 127: // Mac OSX delete key
case 8: // backspace
// The Backspace key
if(pos != 0)
{
pos--;
text.erase(pos,1);
}
break;
case KEY_DC:
if(pos < text.size())
{
text.erase(pos,1);
}
break;
case KEY_ENTER:
case 10:
text.insert(pos,1,char(CHR_NEWLINE));
pos++;
break;
case KEY_BTAB:
case KEY_CTAB:
case KEY_STAB:
case KEY_CATAB:
case 9:
// The Tab key
text.insert(pos,4,CHR_SPACE);
pos += 4;
break;
default:
// Any other character insert
text.insert(pos,1,char(c));
pos++;
break;
}
}
void TextEditor::printBuff() {
wclear(mainWindow);
lineLengths.clear();
size_t px=0;
size_t py = 0;
x=0;
y=0;
vector<string> tokens = splitOnSpaceAndEnter(text);
size_t counter = 0;
for(auto token : tokens) {
int remainingWidth = getCols() - px;
if(token[0] == CHR_SPACE)
{
for(size_t i = 0; i < token.size(); i++)
{
if(px >= getCols()){
lineLengths.push_back(px);
py++;
px = 0;
}
mvwaddch(mainWindow,py,px,CHR_SPACE);
if(counter == pos)
{
x = px;
y = py;
}
counter++;
px++;
}
}
else
{
if(token.size() > remainingWidth) {
lineLengths.push_back(px);
py++;
px = 0;
}
for(size_t i = 0; i < token.size(); i++)
{
mvwprintw(mainWindow,py,px,&token[i]);
if(counter == pos)
{
x = px;
y = py;
}
if(i == token.size()-1 && (unsigned char)token[i] == CHR_NEWLINE)
{
lineLengths.push_back(px+1);
py++;
px = 0;
}
else
{
px++;
}
counter++;
}
}
}
lineLengths.push_back(px);
if(counter == pos)
{
x = px;
y = py;
}
wmove(mainWindow,y,x);
}
<|endoftext|> |
<commit_before>#include <exception>
#include <iomanip>
#include <iostream>
#include <iterator>
#include <memory>
#include <sstream>
#include <string>
#include <utility>
#include <vector>
#include "../algorithm.h"
#include "testbench.h"
using namespace std;
using namespace xp;
struct instrumented {
int val;
int& count;
instrumented(int& count, int val) : val(val), count(count) {}
bool operator() (int other) const {
++count;
return val == other;
}
};
template<typename T>
struct first_less {
bool operator()(pair<T, T> x, pair<T, T> y) {
return x.first < y.first;
}
};
TESTBENCH()
TEST(check_find_backwards) {
vector<int> v{0, 11, 22, 33, 44, 55, 66, 77, 88, 99};
auto found = find_backwards(v.cbegin(), v.cend(), 44);
auto d = distance(v.cbegin(), found);
VERIFY(d == 4);
auto not_found = find_backwards(v.cbegin(), v.cend(), 60);
VERIFY(not_found == v.cend());
}
TEST(check_find_with_hint) {
using namespace std;
vector<int> v{0, 11, 22, 33, 44, 55, 66, 77, 88, 99};
auto found = find(v.cbegin(), v.cend(), v.cbegin() + 5, 44);
auto d = distance(v.cbegin(), found);
VERIFY(d == 4);
auto not_found = find(v.cbegin(), v.cend(), v.cbegin() + 5, 60);
VERIFY(not_found == v.cend());
not_found = find(v.cbegin(), v.cend(), v.cbegin() + 3, 60);
VERIFY(not_found == v.cend());
}
TEST(check_find_if_with_hint) {
using namespace std;
vector<int> v{0, 11, 22, 33, 44, 55, 66, 77, 88, 99};
int count = 0;
instrumented pred(count, 44);
auto found = find_if(v.cbegin(), v.cend(), v.cbegin() + 5, pred);
auto d = distance(v.cbegin(), found);
VERIFY(d == 4);
VERIFY(count < 4);
count = 0;
instrumented bad(count, 60);
auto not_found = find_if(v.cbegin(), v.cend(), v.cbegin() + 5, bad);
VERIFY(not_found == v.cend());
VERIFY(count == 10);
count = 0;
not_found = find_if(v.cbegin(), v.cend(), v.cbegin() + 3, bad);
VERIFY(not_found == v.cend());
VERIFY(count == 10);
}
TEST(check_tighten) {
unsigned char lb = 5;
unsigned char hb = 25;
auto result = tighten(70, lb, hb);
VERIFY(typeid(result) == typeid(lb));
VERIFY(result == 25);
}
TEST(check_tighten_with_overflow) {
auto result = tighten<unsigned char>(300, 100, 150);
VERIFY(typeid(result) == typeid(unsigned char));
VERIFY(result == 150);
}
TEST(check_min_cost_element) {
vector<int> v { 2, 5, 7, 8, 2, 42, 8, 42, 1, 23, 1 };
auto result = min_cost_element(v.begin(), v.end(), [](int i) { return i * i; });
VERIFY(distance(v.begin(), result) == 8);
}
TEST(check_max_cost_element) {
vector<int> v {2, 5, 7, 8, 2, 42, 8, 42, 1, 23, 1};
auto result = max_cost_element(v.begin(), v.end(), [](int i) { return i * i; });
VERIFY(distance(v.begin(), result) == 5);
}
TEST(check_minmax_cost_element) {
vector<int> v {2, 5, 7, 8, 2, 42, 8, 42, 1, 23, 1};
auto result = minmax_cost_element(v.begin(), v.end(), [](int i) { return i * i; });
VERIFY(distance(v.begin(), result.first) == 8);
// Different from max_cost_element but consistent with minmax_element
VERIFY(distance(v.begin(), result.second) == 7);
}
TEST(check_count_while_adjacent) {
vector<int> v {1, 1, 1, 2, 2, 3, 4, 4, 4, 4};
auto f = v.begin();
auto l = v.end();
int c = 0;
tie(c, f) = count_while_adjacent(f, l);
VERIFY(c == 3);
tie(c, f) = count_while_adjacent(f, l);
VERIFY(c == 2);
tie(c, f) = count_while_adjacent(f, l);
VERIFY(c == 1);
tie(c, f) = count_while_adjacent(f, l);
VERIFY(c == 4);
}
TEST(check_unique_copy_with_count) {
vector<int> v {1, 1, 1, 2, 2, 3, 4, 4, 4, 4};
vector<pair<int, int>> expected {{3, 1}, {2, 2}, {1, 3}, {4, 4}};
vector<pair<int, int>> actual;
unique_copy_with_count(v.begin(), v.end(), back_inserter(actual));
VERIFY(expected.size() == actual.size());
VERIFY(equal(actual.begin(), actual.end(), expected.begin()));
}
TEST(check_stable_max) {
first_less<int> cmp;
pair<int, int> x {0, 1};
pair<int, int> y {0, 2};
VERIFY(std::max(x, y, cmp).second == 1);
VERIFY(stable_max(x, y, cmp).second == 2);
}
TEST(check_stable_max_element) {
first_less<int> cmp;
vector<pair<int, int>> v {{3, 1}, {2, 2}, {1, 3}, {3, 4}};
VERIFY(std::max_element(v.begin(), v.end(), cmp)->second == 1);
VERIFY(stable_max_element(v.begin(), v.end(), cmp)->second == 4);
}
TESTFIXTURE(algorithm)
<commit_msg>Tests for _while algorithms.<commit_after>#include <exception>
#include <iomanip>
#include <iostream>
#include <iterator>
#include <memory>
#include <sstream>
#include <string>
#include <utility>
#include <vector>
#include "../algorithm.h"
#include "testbench.h"
using namespace std;
using namespace xp;
struct instrumented {
int val;
int& count;
instrumented(int& count, int val) : val(val), count(count) {}
bool operator() (int other) const {
++count;
return val == other;
}
};
struct is_not_end_of_string {
bool operator()(const char * c) {
return *c != '\0';
}
};
template<typename T>
struct first_less {
bool operator()(pair<T, T> x, pair<T, T> y) {
return x.first < y.first;
}
};
TESTBENCH()
TEST(check_find_backwards) {
vector<int> v{0, 11, 22, 33, 44, 55, 66, 77, 88, 99};
auto found = find_backwards(v.cbegin(), v.cend(), 44);
auto d = distance(v.cbegin(), found);
VERIFY(d == 4);
auto not_found = find_backwards(v.cbegin(), v.cend(), 60);
VERIFY(not_found == v.cend());
}
TEST(check_find_with_hint) {
using namespace std;
vector<int> v{0, 11, 22, 33, 44, 55, 66, 77, 88, 99};
auto found = find(v.cbegin(), v.cend(), v.cbegin() + 5, 44);
auto d = distance(v.cbegin(), found);
VERIFY(d == 4);
auto not_found = find(v.cbegin(), v.cend(), v.cbegin() + 5, 60);
VERIFY(not_found == v.cend());
not_found = find(v.cbegin(), v.cend(), v.cbegin() + 3, 60);
VERIFY(not_found == v.cend());
}
TEST(check_find_if_with_hint) {
using namespace std;
vector<int> v{0, 11, 22, 33, 44, 55, 66, 77, 88, 99};
int count = 0;
instrumented pred(count, 44);
auto found = find_if(v.cbegin(), v.cend(), v.cbegin() + 5, pred);
auto d = distance(v.cbegin(), found);
VERIFY(d == 4);
VERIFY(count < 4);
count = 0;
instrumented bad(count, 60);
auto not_found = find_if(v.cbegin(), v.cend(), v.cbegin() + 5, bad);
VERIFY(not_found == v.cend());
VERIFY(count == 10);
count = 0;
not_found = find_if(v.cbegin(), v.cend(), v.cbegin() + 3, bad);
VERIFY(not_found == v.cend());
VERIFY(count == 10);
}
TEST(check_tighten) {
unsigned char lb = 5;
unsigned char hb = 25;
auto result = tighten(70, lb, hb);
VERIFY(typeid(result) == typeid(lb));
VERIFY(result == 25);
}
TEST(check_tighten_with_overflow) {
auto result = tighten<unsigned char>(300, 100, 150);
VERIFY(typeid(result) == typeid(unsigned char));
VERIFY(result == 150);
}
TEST(check_min_cost_element) {
vector<int> v { 2, 5, 7, 8, 2, 42, 8, 42, 1, 23, 1 };
auto result = min_cost_element(v.begin(), v.end(), [](int i) { return i * i; });
VERIFY(distance(v.begin(), result) == 8);
}
TEST(check_max_cost_element) {
vector<int> v {2, 5, 7, 8, 2, 42, 8, 42, 1, 23, 1};
auto result = max_cost_element(v.begin(), v.end(), [](int i) { return i * i; });
VERIFY(distance(v.begin(), result) == 5);
}
TEST(check_minmax_cost_element) {
vector<int> v {2, 5, 7, 8, 2, 42, 8, 42, 1, 23, 1};
auto result = minmax_cost_element(v.begin(), v.end(), [](int i) { return i * i; });
VERIFY(distance(v.begin(), result.first) == 8);
// Different from max_cost_element but consistent with minmax_element
VERIFY(distance(v.begin(), result.second) == 7);
}
TEST(check_count_while_adjacent) {
vector<int> v {1, 1, 1, 2, 2, 3, 4, 4, 4, 4};
auto f = v.begin();
auto l = v.end();
int c = 0;
tie(c, f) = count_while_adjacent(f, l);
VERIFY(c == 3);
tie(c, f) = count_while_adjacent(f, l);
VERIFY(c == 2);
tie(c, f) = count_while_adjacent(f, l);
VERIFY(c == 1);
tie(c, f) = count_while_adjacent(f, l);
VERIFY(c == 4);
}
TEST(check_unique_copy_with_count) {
vector<int> v {1, 1, 1, 2, 2, 3, 4, 4, 4, 4};
vector<pair<int, int>> expected {{3, 1}, {2, 2}, {1, 3}, {4, 4}};
vector<pair<int, int>> actual;
unique_copy_with_count(v.begin(), v.end(), back_inserter(actual));
VERIFY(expected.size() == actual.size());
VERIFY(equal(actual.begin(), actual.end(), expected.begin()));
}
TEST(check_stable_max) {
first_less<int> cmp;
pair<int, int> x {0, 1};
pair<int, int> y {0, 2};
VERIFY(std::max(x, y, cmp).second == 1);
VERIFY(stable_max(x, y, cmp).second == 2);
}
TEST(check_stable_max_element) {
first_less<int> cmp;
vector<pair<int, int>> v {{3, 1}, {2, 2}, {1, 3}, {3, 4}};
VERIFY(std::max_element(v.begin(), v.end(), cmp)->second == 1);
VERIFY(stable_max_element(v.begin(), v.end(), cmp)->second == 4);
}
TEST(check_copy_while) {
vector<char> v;
copy_while("hello world!", is_not_end_of_string {}, back_inserter(v));
VERIFY(v.size() == 12);
VERIFY(v.front() == 'h');
VERIFY(v.back() == '!');
}
TEST(check_fill_while) {
char s[] = "hello world!";
fill_while(s, is_not_end_of_string {}, '_');
VERIFY(*s == '_');
VERIFY(count(s, s + 12, '_') == 12);
}
TEST(check_find_while) {
auto s = "hello world!";
auto w = find_while(s, is_not_end_of_string {}, ' ');
VERIFY(distance(s, w) == 5);
}
TESTFIXTURE(algorithm)
<|endoftext|> |
<commit_before>#include "stdafx.h"
#include "Sling.h"
#include "GameManager.h"
#include "FileStuff.h"
#include <SimpleAudioEngine.h>
Sling::Sling() : m_shotAngle(Vec2::ZERO), m_shotPower(0),
m_arm(nullptr), m_character(nullptr),
m_status(STATUS::EMPTY)
{
m_expectLine.reserve(DOTNUM_OF_LINE);
m_beforeLine.reserve(DOTNUM_OF_LINE);
}
bool Sling::init()
{
if (Node::init() == false)
{
return false;
}
//set Name
setName("Sling");
//set Empey status
ChangeToEmpty();
//set some frame work variable
Size visibleSize = Director::getInstance()->getVisibleSize();
Vec2 origin = Director::getInstance()->getVisibleOrigin();
//set position of character
setPosition(SLING_POSITION);
/*Make Expect line*/
for (int i = 0; i < DOTNUM_OF_LINE; i++)
{
Sprite* dot = Sprite::create(FileStuff::SLING_LINE_DOT);
float r = -((2.f / DOTNUM_OF_LINE)*(2.f / DOTNUM_OF_LINE) * (i*1.f - DOTNUM_OF_LINE / 2.f) * (i*1.f - DOTNUM_OF_LINE / 2.f)) + 1;
dot->setOpacity(r * 100);
dot->setScale(r * 2);
dot->setVisible(false);
m_expectLine.pushBack(dot);
addChild(dot, 1);
}
/*Make Before line*/
for (int i = 0; i < DOTNUM_OF_LINE; i++)
{
Sprite* dot = Sprite::create(FileStuff::SLING_LINE_DOT);
float r = -((2.f / DOTNUM_OF_LINE)*(2.f / DOTNUM_OF_LINE) * (i*1.f - DOTNUM_OF_LINE / 2.f) * (i*1.f - DOTNUM_OF_LINE / 2.f)) + 1;
dot->setOpacity(r * 100 * 0.5);
dot->setScale(r * 2);
dot->setVisible(false);
m_beforeLine.pushBack(dot);
addChild(dot, 1);
}
m_arm = Sprite::createWithSpriteFrameName(FileStuff::CHARACTER_ARM);
m_arm->setScale(SLING_SCALE);
m_arm->setRotation(DEFAULT_ARM);
m_arm->setAnchorPoint(Point(0.5, 0.4));
m_arm->setPosition(Vec2(0, 10));
addChild(m_arm, 1);
m_character = LoadCharacter();
addChild(m_character, 2);
EventListenerMouse* mouseListener = EventListenerMouse::create();
mouseListener->onMouseUp = CC_CALLBACK_1(Sling::Shot, this);
mouseListener->onMouseDown = CC_CALLBACK_1(Sling::PullStart, this);
mouseListener->onMouseMove = CC_CALLBACK_1(Sling::Pull, this);
_eventDispatcher->addEventListenerWithSceneGraphPriority(mouseListener, this);
return true;
}
void Sling::Reset()
{
ChangeToEmpty();
}
void Sling::ShotComplete()
{
ChangeToEmpty();
}
void Sling::LoadBullet()
{
ChangeToLoaded();
}
Point Sling::GetStartLocation()
{
return getPosition();
}
Sprite* Sling::LoadCharacter()
{
Sprite* character = Sprite::createWithSpriteFrameName(FileStuff::CHARACTER_HARDPIXEL);
character->setPosition(Vec2::ZERO);
return character;
}
void Sling::PullStart(Event* e)
{
if (m_status != STATUS::LOADED)
{
return;
}
/*Pull mouse ġ Ÿ */
EventMouse* evMouse = static_cast<EventMouse*>(e);
Point mouseLocation = evMouse->getLocationInView();
Point startLocation = GetStartLocation();
float distance = startLocation.getDistance(mouseLocation);
if (distance > CLICK_RANGE)
{
return;
}
m_character->removeFromParent();
m_character = Sprite::createWithSpriteFrameName(FileStuff::CHARACTER_SELECTED);
addChild(m_character, 2);
ChangeToPulling();
}
void Sling::Pull(Event* e)
{
if (m_status != STATUS::PULLING)
{
return;
}
EventMouse* evMouse = static_cast<EventMouse*>(e);
Point mouseLocation = evMouse->getLocationInView();
Point startLocation = GetStartLocation();
m_shotPower = startLocation.getDistance(mouseLocation);
m_shotAngle = (mouseLocation - startLocation) / m_shotPower;
//power ̸̻ max
if (m_shotPower > MAX_POWER)
{
m_shotPower = MAX_POWER;
}
//angle °쿡 .
if (m_shotAngle.getAngle() <= Vec2::ZERO.getAngle())
{
m_shotAngle = Vec2::ZERO;
return;
}
/*Set Position expect line */
for (int i = 0; i < m_expectLine.size(); i++)
{
Sprite* dot = m_expectLine.at(i);
float dot_interval = m_shotPower / m_expectLine.size() / getScale();
dot->setPosition(m_shotAngle * dot_interval * (i+1));
}
// set rotation arm angle
m_arm->setRotation(-m_shotAngle.getAngle()*60 + 90);
}
void Sling::Shot(Event* e)
{
if (m_status != STATUS::PULLING)
{
return;
}
if (m_shotAngle.getAngle() <= Vec2::ZERO.getAngle())
{
m_shotAngle = Vec2::ZERO;
m_status = STATUS::LOADED;
for (int i = 0; i < m_expectLine.size(); i++)
{
Sprite* dot = m_expectLine.at(i);
dot->setVisible(false);
}
return;
}
//fix shot angle,power from last pointer position.
Pull(e);
/*Set Position before line */
for (int i = 0; i < m_beforeLine.size(); i++)
{
Sprite* dot = m_beforeLine.at(i);
float dot_interval = m_shotPower / m_expectLine.size() / getScale();
dot->setPosition(m_shotAngle * dot_interval * (i + 1));
dot->setVisible(true);
}
ChangeToShotted();
GameManager* gm = GameManager::GetInstance();
gm->ShotBullet();
m_character->removeFromParent();
m_character = Sprite::createWithSpriteFrameName(FileStuff::CHARACTER_HARDPIXEL);
addChild(m_character, 2);
}
void Sling::RemoveDots()
{
for (Sprite* dot : m_expectLine)
{
dot->removeFromParent();
}
for (Sprite* dot : m_beforeLine)
{
dot->removeFromParent();
}
}
Vec2 Sling::GetDirection()
{
return m_shotAngle;
}
float Sling::GetAngleInRadian()
{
return m_shotAngle.getAngle();
}
float Sling::GetRotationAngle()
{
return -GetAngleInRadian() / 3.14 * 180 + 90;
}
float Sling::GetSpeed()
{
return m_shotPower;
}
bool Sling::IsShotted() // --> üũ
{
if (m_status == STATUS::SHOTTED)
return true;
else
return false;
}
void Sling::ChangeToLoaded() //empty -> load
{
if (m_status != STATUS::EMPTY)
return;
m_status = STATUS::LOADED;
}
void Sling::ChangeToPulling() //loaded -> pulling
{
if (m_status != STATUS::LOADED)
return;
m_status = STATUS::PULLING;
for (Sprite* dot : m_expectLine)
{
dot->setVisible(true);
}
}
void Sling::ChangeToShotted() //pullig -> shotted
{
if (m_status != STATUS::PULLING)
return;
m_status = STATUS::SHOTTED;
for (Sprite* dot : m_expectLine)
{
dot->setVisible(false);
}
}
void Sling::ChangeToEmpty() //shotted -> empty
{
m_status = STATUS::EMPTY;
}
<commit_msg>fix bug if player just click the man then it's not shooted<commit_after>#include "stdafx.h"
#include "Sling.h"
#include "GameManager.h"
#include "FileStuff.h"
#include <SimpleAudioEngine.h>
Sling::Sling() : m_shotAngle(Vec2::ZERO), m_shotPower(0),
m_arm(nullptr), m_character(nullptr),
m_status(STATUS::EMPTY)
{
m_expectLine.reserve(DOTNUM_OF_LINE);
m_beforeLine.reserve(DOTNUM_OF_LINE);
}
bool Sling::init()
{
if (Node::init() == false)
{
return false;
}
//set Name
setName("Sling");
//set Empey status
ChangeToEmpty();
//set some frame work variable
Size visibleSize = Director::getInstance()->getVisibleSize();
Vec2 origin = Director::getInstance()->getVisibleOrigin();
//set position of character
setPosition(SLING_POSITION);
/*Make Expect line*/
for (int i = 0; i < DOTNUM_OF_LINE; i++)
{
Sprite* dot = Sprite::create(FileStuff::SLING_LINE_DOT);
float r = -((2.f / DOTNUM_OF_LINE)*(2.f / DOTNUM_OF_LINE) * (i*1.f - DOTNUM_OF_LINE / 2.f) * (i*1.f - DOTNUM_OF_LINE / 2.f)) + 1;
dot->setOpacity(r * 100);
dot->setScale(r * 2);
dot->setVisible(false);
m_expectLine.pushBack(dot);
addChild(dot, 1);
}
/*Make Before line*/
for (int i = 0; i < DOTNUM_OF_LINE; i++)
{
Sprite* dot = Sprite::create(FileStuff::SLING_LINE_DOT);
float r = -((2.f / DOTNUM_OF_LINE)*(2.f / DOTNUM_OF_LINE) * (i*1.f - DOTNUM_OF_LINE / 2.f) * (i*1.f - DOTNUM_OF_LINE / 2.f)) + 1;
dot->setOpacity(r * 100 * 0.5);
dot->setScale(r * 2);
dot->setVisible(false);
m_beforeLine.pushBack(dot);
addChild(dot, 1);
}
m_arm = Sprite::createWithSpriteFrameName(FileStuff::CHARACTER_ARM);
m_arm->setScale(SLING_SCALE);
m_arm->setRotation(DEFAULT_ARM);
m_arm->setAnchorPoint(Point(0.5, 0.4));
m_arm->setPosition(Vec2(0, 10));
addChild(m_arm, 1);
m_character = LoadCharacter();
addChild(m_character, 2);
EventListenerMouse* mouseListener = EventListenerMouse::create();
mouseListener->onMouseUp = CC_CALLBACK_1(Sling::Shot, this);
mouseListener->onMouseDown = CC_CALLBACK_1(Sling::PullStart, this);
mouseListener->onMouseMove = CC_CALLBACK_1(Sling::Pull, this);
_eventDispatcher->addEventListenerWithSceneGraphPriority(mouseListener, this);
return true;
}
void Sling::Reset()
{
ChangeToEmpty();
}
void Sling::ShotComplete()
{
ChangeToEmpty();
}
void Sling::LoadBullet()
{
ChangeToLoaded();
}
Point Sling::GetStartLocation()
{
return getPosition();
}
Sprite* Sling::LoadCharacter()
{
Sprite* character = Sprite::createWithSpriteFrameName(FileStuff::CHARACTER_HARDPIXEL);
character->setPosition(Vec2::ZERO);
return character;
}
void Sling::PullStart(Event* e)
{
if (m_status != STATUS::LOADED)
{
return;
}
/*Pull mouse ġ Ÿ */
EventMouse* evMouse = static_cast<EventMouse*>(e);
Point mouseLocation = evMouse->getLocationInView();
Point startLocation = GetStartLocation();
float distance = startLocation.getDistance(mouseLocation);
if (distance > CLICK_RANGE)
{
return;
}
m_character->removeFromParent();
m_character = Sprite::createWithSpriteFrameName(FileStuff::CHARACTER_SELECTED);
addChild(m_character, 2);
ChangeToPulling();
Pull(e);
}
void Sling::Pull(Event* e)
{
if (m_status != STATUS::PULLING)
{
return;
}
EventMouse* evMouse = static_cast<EventMouse*>(e);
Point mouseLocation = evMouse->getLocationInView();
Point startLocation = GetStartLocation();
m_shotPower = startLocation.getDistance(mouseLocation);
m_shotAngle = (mouseLocation - startLocation) / m_shotPower;
//power ̸̻ max
if (m_shotPower > MAX_POWER)
{
m_shotPower = MAX_POWER;
}
//angle °쿡 .
if (m_shotAngle.getAngle() <= Vec2::ZERO.getAngle())
{
m_shotAngle = Vec2::ZERO;
return;
}
/*Set Position expect line */
for (int i = 0; i < m_expectLine.size(); i++)
{
Sprite* dot = m_expectLine.at(i);
float dot_interval = m_shotPower / m_expectLine.size() / getScale();
dot->setPosition(m_shotAngle * dot_interval * (i+1));
}
// set rotation arm angle
m_arm->setRotation(-m_shotAngle.getAngle()*60 + 90);
}
void Sling::Shot(Event* e)
{
if (m_status != STATUS::PULLING)
{
return;
}
if (m_shotAngle.getAngle() <= Vec2::ZERO.getAngle())
{
m_shotAngle = Vec2::ZERO;
m_status = STATUS::LOADED;
for (int i = 0; i < m_expectLine.size(); i++)
{
Sprite* dot = m_expectLine.at(i);
dot->setVisible(false);
}
return;
}
//fix shot angle,power from last pointer position.
Pull(e);
/*Set Position before line */
for (int i = 0; i < m_beforeLine.size(); i++)
{
Sprite* dot = m_beforeLine.at(i);
float dot_interval = m_shotPower / m_expectLine.size() / getScale();
dot->setPosition(m_shotAngle * dot_interval * (i + 1));
dot->setVisible(true);
}
ChangeToShotted();
GameManager* gm = GameManager::GetInstance();
gm->ShotBullet();
m_character->removeFromParent();
m_character = Sprite::createWithSpriteFrameName(FileStuff::CHARACTER_HARDPIXEL);
addChild(m_character, 2);
}
void Sling::RemoveDots()
{
for (Sprite* dot : m_expectLine)
{
dot->removeFromParent();
}
for (Sprite* dot : m_beforeLine)
{
dot->removeFromParent();
}
}
Vec2 Sling::GetDirection()
{
return m_shotAngle;
}
float Sling::GetAngleInRadian()
{
return m_shotAngle.getAngle();
}
float Sling::GetRotationAngle()
{
return -GetAngleInRadian() / 3.14 * 180 + 90;
}
float Sling::GetSpeed()
{
return m_shotPower;
}
bool Sling::IsShotted() // --> üũ
{
if (m_status == STATUS::SHOTTED)
return true;
else
return false;
}
void Sling::ChangeToLoaded() //empty -> load
{
if (m_status != STATUS::EMPTY)
return;
m_status = STATUS::LOADED;
}
void Sling::ChangeToPulling() //loaded -> pulling
{
if (m_status != STATUS::LOADED)
return;
m_status = STATUS::PULLING;
for (Sprite* dot : m_expectLine)
{
dot->setVisible(true);
}
}
void Sling::ChangeToShotted() //pullig -> shotted
{
if (m_status != STATUS::PULLING)
return;
m_status = STATUS::SHOTTED;
for (Sprite* dot : m_expectLine)
{
dot->setVisible(false);
}
}
void Sling::ChangeToEmpty() //shotted -> empty
{
m_status = STATUS::EMPTY;
}
<|endoftext|> |
<commit_before>/*Copyright 2014 George Karagoulis
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.*/
#include "application.h"
#include "mainwindow.h"
#include "about.h"
#include "settings.h"
#include <grypto_common.h>
#include <gutil/globallogger.h>
#include <gutil/grouplogger.h>
#include <gutil/filelogger.h>
#include <gutil/messageboxlogger.h>
#include <gutil/cryptopp_rng.h>
#include <gutil/commandlineargs.h>
#include <QStandardPaths>
#include <QMessageBox>
#include <QStandardPaths>
USING_NAMESPACE_GUTIL;
using namespace std;
#define APPLICATION_LOG GRYPTO_APP_NAME ".log"
// The global RNG should be a good one (from Crypto++)
static GUtil::CryptoPP::RNG __cryptopp_rng;
static GUtil::RNG_Initializer __rng_init(&__cryptopp_rng);
static void __init_default_settings(GUtil::Qt::Settings &settings)
{
if(!settings.Contains(GRYPTONITE_SETTING_AUTOLAUNCH_URLS)){
settings.SetValue(GRYPTONITE_SETTING_AUTOLAUNCH_URLS, true);
settings.SetValue(GRYPTONITE_SETTING_AUTOLOAD_LAST_FILE, true);
settings.SetValue(GRYPTONITE_SETTING_CLOSE_MINIMIZES_TO_TRAY, true);
settings.SetValue(GRYPTONITE_SETTING_TIME_FORMAT_24HR, true);
settings.SetValue(GRYPTONITE_SETTING_LOCKOUT_TIMEOUT, 15);
settings.SetValue(GRYPTONITE_SETTING_CLIPBOARD_TIMEOUT, 30);
settings.CommitChanges();
}
}
Application::Application(int &argc, char **argv)
:GUtil::Qt::Application(argc, argv, GRYPTO_APP_NAME, GRYPTO_VERSION_STRING),
settings(GRYPTO_SETTINGS_IDENTIFIER),
main_window(NULL)
{
// Log global messages to a group logger, which writes to all loggers in the group
SetGlobalLogger(new GroupLogger{
// Comment this line for release (silently show errors only in log)
new GUtil::Qt::MessageBoxLogger,
new FileLogger(QString("%1/" APPLICATION_LOG)
.arg(QStandardPaths::writableLocation(QStandardPaths::DataLocation)).toUtf8()),
});
CommandLineArgs args(argc, argv);
String open_file;
if(args.Length() > 1){
open_file = args[1];
}
// Don't let exceptions crash us, they will be logged to the global logger
SetTrapExceptions(true);
// Initialize resources in case we have a static build
Q_INIT_RESOURCE(grypto_ui);
// Register the metatypes we are going to use
qRegisterMetaType<shared_ptr<Exception<>>>("std::shared_ptr<GUtil::Exception<>>");
qRegisterMetaType<Grypt::EntryId>("Grypt::EntryId");
qRegisterMetaTypeStreamOperators<Grypt::IdType>("Grypt::IdType");
try{
__init_default_settings(settings);
main_window = new MainWindow(&settings, open_file);
// This only gets set if no exception is hit. Otherwise we DO want the application
// to close after it has shown the error message
setQuitOnLastWindowClosed(false);
}
catch(exception &ex){
handle_exception(ex);
}
}
void Application::about_to_quit()
{
if(main_window){
main_window->AboutToQuit();
main_window->deleteLater();
}
SetGlobalLogger(NULL);
}
void Application::handle_exception(std::exception &ex)
{
if(0 != dynamic_cast<GUtil::CancelledOperationException<> *>(&ex)){
QMessageBox::information(main_window, "Cancelled", "The operation has been cancelled");
}
else{
GUtil::Qt::Application::handle_exception(ex);
}
}
void Application::show_about(QWidget *)
{
(new ::About(main_window))->ShowAbout();
}
<commit_msg>I forgot to initialize the default for the new recent file history setting<commit_after>/*Copyright 2014 George Karagoulis
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.*/
#include "application.h"
#include "mainwindow.h"
#include "about.h"
#include "settings.h"
#include <grypto_common.h>
#include <gutil/globallogger.h>
#include <gutil/grouplogger.h>
#include <gutil/filelogger.h>
#include <gutil/messageboxlogger.h>
#include <gutil/cryptopp_rng.h>
#include <gutil/commandlineargs.h>
#include <QStandardPaths>
#include <QMessageBox>
#include <QStandardPaths>
USING_NAMESPACE_GUTIL;
using namespace std;
#define APPLICATION_LOG GRYPTO_APP_NAME ".log"
// The global RNG should be a good one (from Crypto++)
static GUtil::CryptoPP::RNG __cryptopp_rng;
static GUtil::RNG_Initializer __rng_init(&__cryptopp_rng);
static void __init_default_settings(GUtil::Qt::Settings &settings)
{
if(!settings.Contains(GRYPTONITE_SETTING_AUTOLAUNCH_URLS)){
settings.SetValue(GRYPTONITE_SETTING_AUTOLAUNCH_URLS, true);
settings.SetValue(GRYPTONITE_SETTING_AUTOLOAD_LAST_FILE, true);
settings.SetValue(GRYPTONITE_SETTING_RECENT_FILES_LENGTH, 10);
settings.SetValue(GRYPTONITE_SETTING_CLOSE_MINIMIZES_TO_TRAY, true);
settings.SetValue(GRYPTONITE_SETTING_TIME_FORMAT_24HR, true);
settings.SetValue(GRYPTONITE_SETTING_LOCKOUT_TIMEOUT, 15);
settings.SetValue(GRYPTONITE_SETTING_CLIPBOARD_TIMEOUT, 30);
settings.CommitChanges();
}
}
Application::Application(int &argc, char **argv)
:GUtil::Qt::Application(argc, argv, GRYPTO_APP_NAME, GRYPTO_VERSION_STRING),
settings(GRYPTO_SETTINGS_IDENTIFIER),
main_window(NULL)
{
// Log global messages to a group logger, which writes to all loggers in the group
SetGlobalLogger(new GroupLogger{
// Comment this line for release (silently show errors only in log)
new GUtil::Qt::MessageBoxLogger,
new FileLogger(QString("%1/" APPLICATION_LOG)
.arg(QStandardPaths::writableLocation(QStandardPaths::DataLocation)).toUtf8()),
});
CommandLineArgs args(argc, argv);
String open_file;
if(args.Length() > 1){
open_file = args[1];
}
// Don't let exceptions crash us, they will be logged to the global logger
SetTrapExceptions(true);
// Initialize resources in case we have a static build
Q_INIT_RESOURCE(grypto_ui);
// Register the metatypes we are going to use
qRegisterMetaType<shared_ptr<Exception<>>>("std::shared_ptr<GUtil::Exception<>>");
qRegisterMetaType<Grypt::EntryId>("Grypt::EntryId");
qRegisterMetaTypeStreamOperators<Grypt::IdType>("Grypt::IdType");
try{
__init_default_settings(settings);
main_window = new MainWindow(&settings, open_file);
// This only gets set if no exception is hit. Otherwise we DO want the application
// to close after it has shown the error message
setQuitOnLastWindowClosed(false);
}
catch(exception &ex){
handle_exception(ex);
}
}
void Application::about_to_quit()
{
if(main_window){
main_window->AboutToQuit();
main_window->deleteLater();
}
SetGlobalLogger(NULL);
}
void Application::handle_exception(std::exception &ex)
{
if(0 != dynamic_cast<GUtil::CancelledOperationException<> *>(&ex)){
QMessageBox::information(main_window, "Cancelled", "The operation has been cancelled");
}
else{
GUtil::Qt::Application::handle_exception(ex);
}
}
void Application::show_about(QWidget *)
{
(new ::About(main_window))->ShowAbout();
}
<|endoftext|> |
<commit_before>/*
* Copyright (C) 2011, 2012 Daniele E. Domenichelli <daniele.domenichelli@gmail.com>
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 2.1 of the License, or (at your option) any later version.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
*/
#include "debug.h"
#include <TelepathyQt/Debug>
#include <QLoggingCategory>
Q_DECLARE_LOGGING_CATEGORY(TELEPATHY_QT)
namespace KTp
{
namespace {
QString libraryString;
static void tpDebugCallback(const QString &libraryName,
const QString &libraryVersion,
QtMsgType type,
const QString &msg)
{
if (Q_UNLIKELY(libraryString.isEmpty())) {
libraryString = QString::fromLatin1("%1:%2()").arg(libraryName, libraryVersion);
}
qCDebug(TELEPATHY_QT) << libraryString << qPrintable(msg);
}
} // namespace
} // namespace KTp
void KTp::Debug::installCallback(bool debug, bool warning)
{
// Redirect Tp debug and warnings to KDebug output
Tp::setDebugCallback(&tpDebugCallback);
// Enable telepathy-Qt4 debug
Tp::enableDebug(debug);
Tp::enableWarnings(warning);
}
Q_LOGGING_CATEGORY(KTP_COMMONINTERNALS, "ktp-logger")
Q_LOGGING_CATEGORY(TELEPATHY_QT, "ktp-logger")
<commit_msg>Fix Q_LOGGING_CATEGORY strings so they're not all ktp-logger<commit_after>/*
* Copyright (C) 2011, 2012 Daniele E. Domenichelli <daniele.domenichelli@gmail.com>
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 2.1 of the License, or (at your option) any later version.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
*/
#include "debug.h"
#include <TelepathyQt/Debug>
#include <QLoggingCategory>
Q_DECLARE_LOGGING_CATEGORY(TELEPATHY_QT)
namespace KTp
{
namespace {
QString libraryString;
static void tpDebugCallback(const QString &libraryName,
const QString &libraryVersion,
QtMsgType type,
const QString &msg)
{
if (Q_UNLIKELY(libraryString.isEmpty())) {
libraryString = QString::fromLatin1("%1:%2()").arg(libraryName, libraryVersion);
}
qCDebug(TELEPATHY_QT) << libraryString << qPrintable(msg);
}
} // namespace
} // namespace KTp
void KTp::Debug::installCallback(bool debug, bool warning)
{
// Redirect Tp debug and warnings to KDebug output
Tp::setDebugCallback(&tpDebugCallback);
// Enable telepathy-Qt4 debug
Tp::enableDebug(debug);
Tp::enableWarnings(warning);
}
Q_LOGGING_CATEGORY(KTP_COMMONINTERNALS, "ktp-common-internals")
Q_LOGGING_CATEGORY(TELEPATHY_QT, "telepathy-qt")
<|endoftext|> |
<commit_before>/*=========================================================================
*
* Copyright Leiden University Medical Center, Erasmus University Medical
* Center and contributors
*
* 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.txt
*
* 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.
*
*=========================================================================*/
#ifndef InterfaceAcceptor_hxx
#define InterfaceAcceptor_hxx
namespace selx
{
template< class InterfaceT >
int
InterfaceAcceptor< InterfaceT >::Connect( ComponentBase::Pointer providerComponent )
{
// Here the core of the handshake mechanism takes place: One specific
// interface of the Providing Component is taken (by dynamic_cast) and
// passed to the accepting Component.
// The function returns the number of successful connects (1 or 0)
std::shared_ptr< InterfaceT > providerInterface = std::dynamic_pointer_cast< InterfaceT >( providerComponent );
if( !providerInterface )
{
// casting failed: this Providing Component does not have the specific interface.
return 0;
}
// connect value interfaces
this->Accept( providerInterface ); // due to the input argument being uniquely defined in the multiple inheritance tree, all versions of Set() are accessible at component level
// store the interface for access by the user defined component
this->m_AcceptedInterface = providerInterface;
// TODO: see if we can get rid of all (dynamic) casts below.
auto providerConnectionInfo = std::dynamic_pointer_cast<ConnectionInfo< InterfaceT >>( providerComponent);
if (!providerConnectionInfo) // by definition should not fail
{
throw std::runtime_error( "std::dynamic_pointer_cast<ConnectionInfo< InterfaceT > should not fail by definition " );
}
ComponentBase* AcceptorBaseComponent = dynamic_cast<ComponentBase*>( this );
if (!AcceptorBaseComponent) // by definition should not fail
{
throw std::runtime_error("dynamic_cast<ComponentBase*> should not fail by definition ");
}
providerConnectionInfo->SetProvidedTo(AcceptorBaseComponent->m_Name);
return 1;
}
template< class InterfaceT >
bool
InterfaceAcceptor< InterfaceT >::CanAcceptConnectionFrom( ComponentBase::ConstPointer providerComponent )
{
std::shared_ptr< const InterfaceT > providerInterface = std::dynamic_pointer_cast< const InterfaceT >( providerComponent );
return bool(providerInterface);
}
} //end namespace selx
#endif // InterfaceAcceptor_hxx
<commit_msg>COMP: added missing include spotted by gcc<commit_after>/*=========================================================================
*
* Copyright Leiden University Medical Center, Erasmus University Medical
* Center and contributors
*
* 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.txt
*
* 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.
*
*=========================================================================*/
#ifndef InterfaceAcceptor_hxx
#define InterfaceAcceptor_hxx
#include "selxConnectionInfo.h"
namespace selx
{
template< class InterfaceT >
int
InterfaceAcceptor< InterfaceT >::Connect( ComponentBase::Pointer providerComponent )
{
// Here the core of the handshake mechanism takes place: One specific
// interface of the Providing Component is taken (by dynamic_cast) and
// passed to the accepting Component.
// The function returns the number of successful connects (1 or 0)
std::shared_ptr< InterfaceT > providerInterface = std::dynamic_pointer_cast< InterfaceT >( providerComponent );
if( !providerInterface )
{
// casting failed: this Providing Component does not have the specific interface.
return 0;
}
// connect value interfaces
this->Accept( providerInterface ); // due to the input argument being uniquely defined in the multiple inheritance tree, all versions of Set() are accessible at component level
// store the interface for access by the user defined component
this->m_AcceptedInterface = providerInterface;
// TODO: see if we can get rid of all (dynamic) casts below.
auto providerConnectionInfo = std::dynamic_pointer_cast<ConnectionInfo< InterfaceT >>( providerComponent);
if (!providerConnectionInfo) // by definition should not fail
{
throw std::runtime_error( "std::dynamic_pointer_cast<ConnectionInfo< InterfaceT > should not fail by definition " );
}
ComponentBase* AcceptorBaseComponent = dynamic_cast<ComponentBase*>( this );
if (!AcceptorBaseComponent) // by definition should not fail
{
throw std::runtime_error("dynamic_cast<ComponentBase*> should not fail by definition ");
}
providerConnectionInfo->SetProvidedTo(AcceptorBaseComponent->m_Name);
return 1;
}
template< class InterfaceT >
bool
InterfaceAcceptor< InterfaceT >::CanAcceptConnectionFrom( ComponentBase::ConstPointer providerComponent )
{
std::shared_ptr< const InterfaceT > providerInterface = std::dynamic_pointer_cast< const InterfaceT >( providerComponent );
return bool(providerInterface);
}
} //end namespace selx
#endif // InterfaceAcceptor_hxx
<|endoftext|> |
<commit_before>/*
* File: ZooKeeperRouter.cpp
* Author: Paolo D'Apice
*
* Created on February 17, 2012, 2:32 PM
*/
#include "net/sf1r/distributed/ZooKeeperRouter.hpp"
#include "net/sf1r/distributed/Sf1Topology.hpp"
#include "../PoolFactory.hpp"
#include "../RawClient.hpp"
#include "RoundRobinPolicy.hpp"
#include "Sf1Watcher.hpp"
#include "ZooKeeperNamespace.hpp"
#include "util/kv2string.h"
#include <boost/foreach.hpp>
#include <boost/regex.hpp>
#include <glog/logging.h>
NS_IZENELIB_SF1R_BEGIN
using iz::ZooKeeper;
using std::string;
using std::vector;
namespace {
const bool AUTO_RECONNECT = true;
typedef vector<string> strvector;
}
ZooKeeperRouter::ZooKeeperRouter(PoolFactory* poolFactory,
const string& hosts, int timeout) : factory(poolFactory) {
// 0. connect to ZooKeeper
LOG(INFO) << "Connecting to ZooKeeper servers: " << hosts;
client.reset(new iz::ZooKeeper(hosts, timeout, AUTO_RECONNECT));
if (not client->isConnected()) {
// XXX: this should be done in the ZooKeeper client
throw iz::ZooKeeperException("Not connected to (servers): " + hosts);
}
// 1. register a watcher that will control the Sf1Driver instances
LOG(INFO) << "Registering watcher ...";
watcher.reset(new Sf1Watcher(*this));
client->registerEventHandler(watcher.get());
// 2. obtain the list of actually running SF1 servers
LOG(INFO) << "Getting actual topology ...";
topology.reset(new Sf1Topology);
loadTopology();
// 3. set the routing policy
LOG(INFO) << "Routing policy ...";
policy.reset(new RoundRobinPolicy(*topology));
LOG(INFO) << "ZooKeeperRouter ready";
}
ZooKeeperRouter::~ZooKeeperRouter() {
BOOST_FOREACH(PoolContainer::value_type& i, pools) {
delete i.second;
}
LOG(INFO) << "ZooKeeperRouter closed";
}
void
ZooKeeperRouter::loadTopology() {
strvector clusters;
client->getZNodeChildren(ROOT_NODE, clusters, ZooKeeper::WATCH);
DLOG(INFO) << "Scanning root node ...";
BOOST_FOREACH(const string& s, clusters) {
if (boost::regex_match(s, NODE_REGEX)) { // this is a SF1 node
DLOG(INFO) << "node: " << s;
addSearchTopology(s + TOPOLOGY);
}
}
LOG(INFO) << "found (" << topology->count() << ") active nodes";
}
void
ZooKeeperRouter::addSearchTopology(const string& searchTopology) {
if (client->isZNodeExists(searchTopology, ZooKeeper::WATCH)) {
DLOG(INFO) << "found search topology: " << searchTopology;
DLOG(INFO) << "Searching for replicas ...";
strvector replicas;
client->getZNodeChildren(searchTopology, replicas, ZooKeeper::WATCH);
if (replicas.empty()) {
DLOG(INFO) << "no replica found";
return;
}
BOOST_FOREACH(const string& replica, replicas) {
DLOG(INFO) << "replica: " << replica;
DLOG(INFO) << "Searching for nodes ...";
strvector nodes;
client->getZNodeChildren(replica, nodes, ZooKeeper::WATCH);
if (nodes.empty()) {
DLOG(INFO) << "no node found";
return;
}
BOOST_FOREACH(const string& path, nodes) {
addSf1Node(path);
}
}
}
}
void
ZooKeeperRouter::addSf1Node(const string& path) {
boost::lock_guard<boost::mutex> lock(mutex);
LOG(INFO) << "adding SF1 node: [" << path << "]";
if (topology->isPresent(path)) {
DLOG(INFO) << "node already exists, skipping";
return;
}
string data;
client->getZNodeData(path, data, ZooKeeper::WATCH);
LOG(INFO) << "node data: [" << data << "]";
// add node into topology
topology->addNode(path, data);
#ifdef ENABLE_ZK_TEST
if (factory == NULL) { // Should be NULL only in tests
LOG(WARNING) << "factory is NULL, is this a test?";
return;
}
#endif
// add pool for the node
const Sf1Node& node = topology->getNodeAt(path);
DLOG(INFO) << "Getting connection pool for node: " << node.getPath();
ConnectionPool* pool = factory->newConnectionPool(node);
pools.insert(PoolContainer::value_type(node.getPath(), pool));
}
void
ZooKeeperRouter::updateNodeData(const string& path) {
boost::lock_guard<boost::mutex> lock(mutex);
LOG(INFO) << "updating SF1 node: [" << path << "]";
string data;
client->getZNodeData(path, data, iz::ZooKeeper::WATCH);
LOG(INFO) << "node data: [" << data << "]";
topology->updateNode(path, data);
}
void
ZooKeeperRouter::removeSf1Node(const string& path) {
boost::unique_lock<boost::mutex> lock(mutex);
LOG(INFO) << "SF1 node: [" << path << "]";
// remove node from topology
topology->removeNode(path);
#ifdef ENABLE_ZK_TEST
if (factory == NULL) { // Should be NULL only in tests
LOG(WARNING) << "factory is NULL, is this a test?";
return;
}
#endif
// remove its pool
const PoolContainer::iterator& it = pools.find(path);
CHECK(pools.end() != it) << "pool not found";
ConnectionPool* pool = it->second;
CHECK_NOTNULL(pool);
while (pool->isBusy()) {
DLOG(INFO) << "pool is currently in use, waiting";
condition.wait(lock);
}
DLOG(INFO) << "removing pool";
CHECK_EQ(1, pools.erase(path));
delete pool;
}
void
ZooKeeperRouter::watchChildren(const string& path) {
if (not client->isZNodeExists(path, ZooKeeper::WATCH)) {
DLOG(INFO) << "node [" << path << "] does not exist";
boost::smatch what;
CHECK(boost::regex_search(path, what, NODE_REGEX));
CHECK(not what.empty());
DLOG(INFO) << "recurse to [" << what[0] << "] ...";
watchChildren(what[0]);
return;
}
strvector children;
client->getZNodeChildren(path, children, ZooKeeper::WATCH);
DLOG(INFO) << "Watching children of: " << path;
BOOST_FOREACH(const string& s, children) {
DLOG(INFO) << "child: " << s;
if (boost::regex_match(s, SEARCH_NODE_REGEX)) {
DLOG(INFO) << "Adding node: " << s;
addSf1Node(s);
} else if (boost::regex_search(s, NODE_REGEX)) {
DLOG(INFO) << "recurse";
watchChildren(s);
}
}
}
#ifdef ENABLE_ZK_TEST
NodeListRange
ZooKeeperRouter::getSf1Nodes() const {
return topology->getNodes();
}
NodeCollectionsRange
ZooKeeperRouter::getSf1Nodes(const string& collection) const {
return topology->getNodesFor(collection);
}
#endif
const Sf1Node&
ZooKeeperRouter::resolve(const string collection) const {
if (topology->count() == 0) {
LOG(WARNING) << "Empty topology, throwing RoutingError";
throw RoutingError("Empty topology");
}
if (collection.empty()) {
DLOG(INFO) << "No collection specified, resolving to all nodes ...";
// choose a node according to the routing policy
return policy->getNode();
} else {
DLOG(INFO) << "Resolving nodes for collection: " << collection << " ...";
if (topology->count(collection) == 0) {
LOG(WARNING) << "No routes for collection: " << collection
<< ", throwing RoutingError";
throw RoutingError("No routes for " + collection);
}
// choose a node according to the routing policy
return policy->getNodeFor(collection);
}
}
RawClient&
ZooKeeperRouter::getConnection(const string& collection) {
boost::lock_guard<boost::mutex> lock(mutex);
const Sf1Node& node = resolve(collection);
DLOG(INFO) << "Resolved to node: " << node.getPath();
// get a connection from the node
ConnectionPool* pool = pools[node.getPath()]; // TODO: do not use operator[]
CHECK(pool) << "NULL pool";
return pool->acquire();
}
void
ZooKeeperRouter::releaseConnection(const RawClient& connection) {
boost::lock_guard<boost::mutex> lock(mutex);
DLOG(INFO) << "releasing connection";
ConnectionPool* pool = pools[connection.getPath()]; // TODO: do not use operator[]
pool->release(connection);
if (not pool->isBusy()) {
DLOG(INFO) << "notifying for condition";
condition.notify_one();
}
}
NS_IZENELIB_SF1R_END
<commit_msg>Not using operator[] on std::map for element retrieval<commit_after>/*
* File: ZooKeeperRouter.cpp
* Author: Paolo D'Apice
*
* Created on February 17, 2012, 2:32 PM
*/
#include "net/sf1r/distributed/ZooKeeperRouter.hpp"
#include "net/sf1r/distributed/Sf1Topology.hpp"
#include "../PoolFactory.hpp"
#include "../RawClient.hpp"
#include "RoundRobinPolicy.hpp"
#include "Sf1Watcher.hpp"
#include "ZooKeeperNamespace.hpp"
#include "util/kv2string.h"
#include <boost/foreach.hpp>
#include <boost/regex.hpp>
#include <glog/logging.h>
NS_IZENELIB_SF1R_BEGIN
using iz::ZooKeeper;
using std::string;
using std::vector;
namespace {
const bool AUTO_RECONNECT = true;
typedef vector<string> strvector;
}
ZooKeeperRouter::ZooKeeperRouter(PoolFactory* poolFactory,
const string& hosts, int timeout) : factory(poolFactory) {
// 0. connect to ZooKeeper
LOG(INFO) << "Connecting to ZooKeeper servers: " << hosts;
client.reset(new iz::ZooKeeper(hosts, timeout, AUTO_RECONNECT));
if (not client->isConnected()) {
// XXX: this should be done in the ZooKeeper client
throw iz::ZooKeeperException("Not connected to (servers): " + hosts);
}
// 1. register a watcher that will control the Sf1Driver instances
LOG(INFO) << "Registering watcher ...";
watcher.reset(new Sf1Watcher(*this));
client->registerEventHandler(watcher.get());
// 2. obtain the list of actually running SF1 servers
LOG(INFO) << "Getting actual topology ...";
topology.reset(new Sf1Topology);
loadTopology();
// 3. set the routing policy
LOG(INFO) << "Routing policy ...";
policy.reset(new RoundRobinPolicy(*topology));
LOG(INFO) << "ZooKeeperRouter ready";
}
ZooKeeperRouter::~ZooKeeperRouter() {
BOOST_FOREACH(PoolContainer::value_type& i, pools) {
delete i.second;
}
LOG(INFO) << "ZooKeeperRouter closed";
}
void
ZooKeeperRouter::loadTopology() {
strvector clusters;
client->getZNodeChildren(ROOT_NODE, clusters, ZooKeeper::WATCH);
DLOG(INFO) << "Scanning root node ...";
BOOST_FOREACH(const string& s, clusters) {
if (boost::regex_match(s, NODE_REGEX)) { // this is a SF1 node
DLOG(INFO) << "node: " << s;
addSearchTopology(s + TOPOLOGY);
}
}
LOG(INFO) << "found (" << topology->count() << ") active nodes";
}
void
ZooKeeperRouter::addSearchTopology(const string& searchTopology) {
if (client->isZNodeExists(searchTopology, ZooKeeper::WATCH)) {
DLOG(INFO) << "found search topology: " << searchTopology;
DLOG(INFO) << "Searching for replicas ...";
strvector replicas;
client->getZNodeChildren(searchTopology, replicas, ZooKeeper::WATCH);
if (replicas.empty()) {
DLOG(INFO) << "no replica found";
return;
}
BOOST_FOREACH(const string& replica, replicas) {
DLOG(INFO) << "replica: " << replica;
DLOG(INFO) << "Searching for nodes ...";
strvector nodes;
client->getZNodeChildren(replica, nodes, ZooKeeper::WATCH);
if (nodes.empty()) {
DLOG(INFO) << "no node found";
return;
}
BOOST_FOREACH(const string& path, nodes) {
addSf1Node(path);
}
}
}
}
void
ZooKeeperRouter::addSf1Node(const string& path) {
boost::lock_guard<boost::mutex> lock(mutex);
LOG(INFO) << "adding SF1 node: [" << path << "]";
if (topology->isPresent(path)) {
DLOG(INFO) << "node already exists, skipping";
return;
}
string data;
client->getZNodeData(path, data, ZooKeeper::WATCH);
LOG(INFO) << "node data: [" << data << "]";
// add node into topology
topology->addNode(path, data);
#ifdef ENABLE_ZK_TEST
if (factory == NULL) { // Should be NULL only in tests
LOG(WARNING) << "factory is NULL, is this a test?";
return;
}
#endif
// add pool for the node
const Sf1Node& node = topology->getNodeAt(path);
DLOG(INFO) << "Getting connection pool for node: " << node.getPath();
ConnectionPool* pool = factory->newConnectionPool(node);
pools.insert(PoolContainer::value_type(node.getPath(), pool));
}
void
ZooKeeperRouter::updateNodeData(const string& path) {
boost::lock_guard<boost::mutex> lock(mutex);
LOG(INFO) << "updating SF1 node: [" << path << "]";
string data;
client->getZNodeData(path, data, iz::ZooKeeper::WATCH);
LOG(INFO) << "node data: [" << data << "]";
topology->updateNode(path, data);
}
void
ZooKeeperRouter::removeSf1Node(const string& path) {
boost::unique_lock<boost::mutex> lock(mutex);
LOG(INFO) << "SF1 node: [" << path << "]";
// remove node from topology
topology->removeNode(path);
#ifdef ENABLE_ZK_TEST
if (factory == NULL) { // Should be NULL only in tests
LOG(WARNING) << "factory is NULL, is this a test?";
return;
}
#endif
// remove its pool
const PoolContainer::iterator& it = pools.find(path);
CHECK(pools.end() != it) << "pool not found";
ConnectionPool* pool = it->second;
CHECK_NOTNULL(pool);
while (pool->isBusy()) {
DLOG(INFO) << "pool is currently in use, waiting";
condition.wait(lock);
}
DLOG(INFO) << "removing pool";
CHECK_EQ(1, pools.erase(path));
delete pool;
}
void
ZooKeeperRouter::watchChildren(const string& path) {
if (not client->isZNodeExists(path, ZooKeeper::WATCH)) {
DLOG(INFO) << "node [" << path << "] does not exist";
boost::smatch what;
CHECK(boost::regex_search(path, what, NODE_REGEX));
CHECK(not what.empty());
DLOG(INFO) << "recurse to [" << what[0] << "] ...";
watchChildren(what[0]);
return;
}
strvector children;
client->getZNodeChildren(path, children, ZooKeeper::WATCH);
DLOG(INFO) << "Watching children of: " << path;
BOOST_FOREACH(const string& s, children) {
DLOG(INFO) << "child: " << s;
if (boost::regex_match(s, SEARCH_NODE_REGEX)) {
DLOG(INFO) << "Adding node: " << s;
addSf1Node(s);
} else if (boost::regex_search(s, NODE_REGEX)) {
DLOG(INFO) << "recurse";
watchChildren(s);
}
}
}
#ifdef ENABLE_ZK_TEST
NodeListRange
ZooKeeperRouter::getSf1Nodes() const {
return topology->getNodes();
}
NodeCollectionsRange
ZooKeeperRouter::getSf1Nodes(const string& collection) const {
return topology->getNodesFor(collection);
}
#endif
const Sf1Node&
ZooKeeperRouter::resolve(const string collection) const {
if (topology->count() == 0) {
LOG(WARNING) << "Empty topology, throwing RoutingError";
throw RoutingError("Empty topology");
}
if (collection.empty()) {
DLOG(INFO) << "No collection specified, resolving to all nodes ...";
// choose a node according to the routing policy
return policy->getNode();
} else {
DLOG(INFO) << "Resolving nodes for collection: " << collection << " ...";
if (topology->count(collection) == 0) {
LOG(WARNING) << "No routes for collection: " << collection
<< ", throwing RoutingError";
throw RoutingError("No routes for " + collection);
}
// choose a node according to the routing policy
return policy->getNodeFor(collection);
}
}
RawClient&
ZooKeeperRouter::getConnection(const string& collection) {
boost::lock_guard<boost::mutex> lock(mutex);
const Sf1Node& node = resolve(collection);
DLOG(INFO) << "Resolved to node: " << node.getPath();
// get a connection from the node
ConnectionPool* pool = pools.find(node.getPath())->second;
CHECK(pool) << "NULL pool";
return pool->acquire();
}
void
ZooKeeperRouter::releaseConnection(const RawClient& connection) {
boost::lock_guard<boost::mutex> lock(mutex);
DLOG(INFO) << "releasing connection";
ConnectionPool* pool = pools.find(connection.getPath())->second;
pool->release(connection);
if (not pool->isBusy()) {
DLOG(INFO) << "notifying for condition";
condition.notify_one();
}
}
NS_IZENELIB_SF1R_END
<|endoftext|> |
<commit_before>/*************************************************************************
*
* $RCSfile: ColumnControlWindow.cxx,v $
*
* $Revision: 1.2 $
*
* last change: $Author: kz $ $Date: 2004-05-19 13:53:33 $
*
* The Contents of this file are made available subject to the terms of
* either of the following licenses
*
* - GNU Lesser General Public License Version 2.1
* - Sun Industry Standards Source License Version 1.1
*
* Sun Microsystems Inc., October, 2000
*
* GNU Lesser General Public License Version 2.1
* =============================================
* Copyright 2000 by Sun Microsystems, Inc.
* 901 San Antonio Road, Palo Alto, CA 94303, USA
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License version 2.1, as published by the Free Software Foundation.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston,
* MA 02111-1307 USA
*
*
* Sun Industry Standards Source License Version 1.1
* =================================================
* The contents of this file are subject to the Sun Industry Standards
* Source License Version 1.1 (the License); You may not use this file
* except in compliance with the License. You may obtain a copy of the
* License at http://www.openoffice.org/license.html.
*
* Software provided under this License is provided on an AS IS basis,
* WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING,
* WITHOUT LIMITATION, WARRANTIES THAT THE SOFTWARE IS FREE OF DEFECTS,
* MERCHANTABLE, FIT FOR A PARTICULAR PURPOSE, OR NON-INFRINGING.
* See the License for the specific provisions governing your rights and
* obligations concerning the Software.
*
* The Initial Developer of the Original Code is: Sun Microsystems, Inc.
*
* Copyright: 2000 by Sun Microsystems, Inc.
*
* All Rights Reserved.
*
* Contributor(s): _______________________________________
*
*
************************************************************************/
#ifndef DBAUI_COLUMNCONTROLWINDOW_HXX
#include "ColumnControlWindow.hxx"
#endif
#ifndef DBAUI_FIELDCONTROLS_HXX
#include "FieldControls.hxx"
#endif
#ifndef INCLUDED_SVTOOLS_SYSLOCALE_HXX
#include <svtools/syslocale.hxx>
#endif
#ifndef _CONNECTIVITY_DBTOOLS_HXX_
#include <connectivity/dbtools.hxx>
#endif
#ifndef DBAUI_TOOLS_HXX
#include "UITools.hxx"
#endif
#ifndef _DBU_RESOURCE_HRC_
#include "dbu_resource.hrc"
#endif
using namespace ::dbaui;
using namespace ::com::sun::star::uno;
using namespace ::com::sun::star::beans;
using namespace ::com::sun::star::container;
using namespace ::com::sun::star::util;
using namespace ::com::sun::star::sdbc;
using namespace ::com::sun::star::lang;
//========================================================================
// OColumnControlWindow
//========================================================================
OColumnControlWindow::OColumnControlWindow(Window* pParent
,const Reference<XMultiServiceFactory>& _rxFactory)
: OFieldDescControl(pParent,NULL)
, m_xORB(_rxFactory)
, m_sTypeNames(ModuleRes(STR_TABLEDESIGN_DBFIELDTYPES))
, m_bAutoIncrementEnabled(sal_True)
{
try
{
m_aLocale = SvtSysLocale().GetLocaleData().getLocale();
}
catch(Exception&)
{
}
}
// -----------------------------------------------------------------------------
OColumnControlWindow::~OColumnControlWindow()
{
}
// -----------------------------------------------------------------------
void OColumnControlWindow::ActivateAggregate( EControlType eType )
{
switch(eType )
{
case tpFormat:
case tpDefault:
case tpAutoIncrement:
case tpColumnName:
break;
default:
OFieldDescControl::ActivateAggregate( eType );
}
}
// -----------------------------------------------------------------------
void OColumnControlWindow::DeactivateAggregate( EControlType eType )
{
switch(eType )
{
case tpFormat:
case tpDefault:
case tpAutoIncrement:
case tpColumnName:
break;
default:
OFieldDescControl::DeactivateAggregate( eType );
}
}
// -----------------------------------------------------------------------
void OColumnControlWindow::SetModified(sal_Bool bModified)
{
}
// -----------------------------------------------------------------------------
void OColumnControlWindow::CellModified(long nRow, USHORT nColId )
{
SaveData(pActFieldDescr);
}
// -----------------------------------------------------------------------------
::com::sun::star::lang::Locale OColumnControlWindow::GetLocale() const
{
return m_aLocale;
}
// -----------------------------------------------------------------------------
Reference< XNumberFormatter > OColumnControlWindow::GetFormatter() const
{
if ( !m_xFormatter.is() )
try
{
Reference< XNumberFormatsSupplier > xSupplier(::dbtools::getNumberFormats(m_xConnection, sal_True,m_xORB));
if ( xSupplier.is() )
{
// create a new formatter
m_xFormatter.set( m_xORB->createInstance(::rtl::OUString(RTL_CONSTASCII_USTRINGPARAM("com.sun.star.util.NumberFormatter"))), UNO_QUERY);
if (m_xFormatter.is())
m_xFormatter->attachNumberFormatsSupplier(xSupplier);
}
}
catch(Exception&)
{
}
return m_xFormatter;
}
// -----------------------------------------------------------------------------
TOTypeInfoSP OColumnControlWindow::getTypeInfo(sal_Int32 _nPos)
{
return ( _nPos >= 0 && _nPos < static_cast<sal_Int32>(m_aDestTypeInfoIndex.size())) ? m_aDestTypeInfoIndex[_nPos]->second : TOTypeInfoSP();
}
// -----------------------------------------------------------------------------
const OTypeInfoMap* OColumnControlWindow::getTypeInfo() const
{
return &m_aDestTypeInfo;
}
// -----------------------------------------------------------------------------
Reference< XDatabaseMetaData> OColumnControlWindow::getMetaData()
{
if ( m_xConnection.is() )
return m_xConnection->getMetaData();
return Reference< XDatabaseMetaData>();
}
// -----------------------------------------------------------------------------
Reference< XConnection> OColumnControlWindow::getConnection()
{
return m_xConnection;
}
// -----------------------------------------------------------------------------
void OColumnControlWindow::setConnection(const Reference< XConnection>& _xCon)
{
m_xConnection = _xCon;
m_xFormatter = NULL;
m_aDestTypeInfoIndex.clear();
m_aDestTypeInfo.clear();
if ( m_xConnection.is() )
{
Init();
::dbaui::fillTypeInfo(m_xConnection,m_sTypeNames,m_aDestTypeInfo,m_aDestTypeInfoIndex);
}
}
// -----------------------------------------------------------------------------
sal_Bool OColumnControlWindow::isAutoIncrementValueEnabled() const
{
return m_bAutoIncrementEnabled;
}
// -----------------------------------------------------------------------------
::rtl::OUString OColumnControlWindow::getAutoIncrementValue() const
{
return m_sAutoIncrementValue;
}
// -----------------------------------------------------------------------------
TOTypeInfoSP OColumnControlWindow::getDefaultTyp() const
{
if ( !m_pTypeInfo.get() )
{
m_pTypeInfo = TOTypeInfoSP(new OTypeInfo());
m_pTypeInfo->aUIName = m_sTypeNames.GetToken(TYPE_OTHER);
}
return m_pTypeInfo;
}
// -----------------------------------------------------------------------------
<commit_msg>INTEGRATION: CWS dbwizard1 (1.2.40); FILE MERGED 2004/10/22 12:52:44 oj 1.2.40.1: #i33924# new property for the edit width<commit_after>/*************************************************************************
*
* $RCSfile: ColumnControlWindow.cxx,v $
*
* $Revision: 1.3 $
*
* last change: $Author: pjunck $ $Date: 2004-10-27 12:56:28 $
*
* The Contents of this file are made available subject to the terms of
* either of the following licenses
*
* - GNU Lesser General Public License Version 2.1
* - Sun Industry Standards Source License Version 1.1
*
* Sun Microsystems Inc., October, 2000
*
* GNU Lesser General Public License Version 2.1
* =============================================
* Copyright 2000 by Sun Microsystems, Inc.
* 901 San Antonio Road, Palo Alto, CA 94303, USA
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License version 2.1, as published by the Free Software Foundation.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston,
* MA 02111-1307 USA
*
*
* Sun Industry Standards Source License Version 1.1
* =================================================
* The contents of this file are subject to the Sun Industry Standards
* Source License Version 1.1 (the License); You may not use this file
* except in compliance with the License. You may obtain a copy of the
* License at http://www.openoffice.org/license.html.
*
* Software provided under this License is provided on an AS IS basis,
* WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING,
* WITHOUT LIMITATION, WARRANTIES THAT THE SOFTWARE IS FREE OF DEFECTS,
* MERCHANTABLE, FIT FOR A PARTICULAR PURPOSE, OR NON-INFRINGING.
* See the License for the specific provisions governing your rights and
* obligations concerning the Software.
*
* The Initial Developer of the Original Code is: Sun Microsystems, Inc.
*
* Copyright: 2000 by Sun Microsystems, Inc.
*
* All Rights Reserved.
*
* Contributor(s): _______________________________________
*
*
************************************************************************/
#ifndef DBAUI_COLUMNCONTROLWINDOW_HXX
#include "ColumnControlWindow.hxx"
#endif
#ifndef DBAUI_FIELDCONTROLS_HXX
#include "FieldControls.hxx"
#endif
#ifndef INCLUDED_SVTOOLS_SYSLOCALE_HXX
#include <svtools/syslocale.hxx>
#endif
#ifndef _CONNECTIVITY_DBTOOLS_HXX_
#include <connectivity/dbtools.hxx>
#endif
#ifndef DBAUI_TOOLS_HXX
#include "UITools.hxx"
#endif
#ifndef _DBU_RESOURCE_HRC_
#include "dbu_resource.hrc"
#endif
using namespace ::dbaui;
using namespace ::com::sun::star::uno;
using namespace ::com::sun::star::beans;
using namespace ::com::sun::star::container;
using namespace ::com::sun::star::util;
using namespace ::com::sun::star::sdbc;
using namespace ::com::sun::star::lang;
//========================================================================
// OColumnControlWindow
//========================================================================
OColumnControlWindow::OColumnControlWindow(Window* pParent
,const Reference<XMultiServiceFactory>& _rxFactory)
: OFieldDescControl(pParent,NULL)
, m_xORB(_rxFactory)
, m_sTypeNames(ModuleRes(STR_TABLEDESIGN_DBFIELDTYPES))
, m_bAutoIncrementEnabled(sal_True)
{
m_bRight = sal_True;
try
{
m_aLocale = SvtSysLocale().GetLocaleData().getLocale();
}
catch(Exception&)
{
}
}
// -----------------------------------------------------------------------------
OColumnControlWindow::~OColumnControlWindow()
{
}
// -----------------------------------------------------------------------
void OColumnControlWindow::ActivateAggregate( EControlType eType )
{
switch(eType )
{
case tpFormat:
case tpDefault:
case tpAutoIncrement:
case tpColumnName:
break;
default:
OFieldDescControl::ActivateAggregate( eType );
}
}
// -----------------------------------------------------------------------
void OColumnControlWindow::DeactivateAggregate( EControlType eType )
{
switch(eType )
{
case tpFormat:
case tpDefault:
case tpAutoIncrement:
case tpColumnName:
break;
default:
OFieldDescControl::DeactivateAggregate( eType );
}
}
// -----------------------------------------------------------------------
void OColumnControlWindow::SetModified(sal_Bool bModified)
{
}
// -----------------------------------------------------------------------------
void OColumnControlWindow::CellModified(long nRow, USHORT nColId )
{
SaveData(pActFieldDescr);
}
// -----------------------------------------------------------------------------
::com::sun::star::lang::Locale OColumnControlWindow::GetLocale() const
{
return m_aLocale;
}
// -----------------------------------------------------------------------------
Reference< XNumberFormatter > OColumnControlWindow::GetFormatter() const
{
if ( !m_xFormatter.is() )
try
{
Reference< XNumberFormatsSupplier > xSupplier(::dbtools::getNumberFormats(m_xConnection, sal_True,m_xORB));
if ( xSupplier.is() )
{
// create a new formatter
m_xFormatter.set( m_xORB->createInstance(::rtl::OUString(RTL_CONSTASCII_USTRINGPARAM("com.sun.star.util.NumberFormatter"))), UNO_QUERY);
if (m_xFormatter.is())
m_xFormatter->attachNumberFormatsSupplier(xSupplier);
}
}
catch(Exception&)
{
}
return m_xFormatter;
}
// -----------------------------------------------------------------------------
TOTypeInfoSP OColumnControlWindow::getTypeInfo(sal_Int32 _nPos)
{
return ( _nPos >= 0 && _nPos < static_cast<sal_Int32>(m_aDestTypeInfoIndex.size())) ? m_aDestTypeInfoIndex[_nPos]->second : TOTypeInfoSP();
}
// -----------------------------------------------------------------------------
const OTypeInfoMap* OColumnControlWindow::getTypeInfo() const
{
return &m_aDestTypeInfo;
}
// -----------------------------------------------------------------------------
Reference< XDatabaseMetaData> OColumnControlWindow::getMetaData()
{
if ( m_xConnection.is() )
return m_xConnection->getMetaData();
return Reference< XDatabaseMetaData>();
}
// -----------------------------------------------------------------------------
Reference< XConnection> OColumnControlWindow::getConnection()
{
return m_xConnection;
}
// -----------------------------------------------------------------------------
void OColumnControlWindow::setConnection(const Reference< XConnection>& _xCon)
{
m_xConnection = _xCon;
m_xFormatter = NULL;
m_aDestTypeInfoIndex.clear();
m_aDestTypeInfo.clear();
if ( m_xConnection.is() )
{
Init();
::dbaui::fillTypeInfo(m_xConnection,m_sTypeNames,m_aDestTypeInfo,m_aDestTypeInfoIndex);
}
}
// -----------------------------------------------------------------------------
sal_Bool OColumnControlWindow::isAutoIncrementValueEnabled() const
{
return m_bAutoIncrementEnabled;
}
// -----------------------------------------------------------------------------
::rtl::OUString OColumnControlWindow::getAutoIncrementValue() const
{
return m_sAutoIncrementValue;
}
// -----------------------------------------------------------------------------
TOTypeInfoSP OColumnControlWindow::getDefaultTyp() const
{
if ( !m_pTypeInfo.get() )
{
m_pTypeInfo = TOTypeInfoSP(new OTypeInfo());
m_pTypeInfo->aUIName = m_sTypeNames.GetToken(TYPE_OTHER);
}
return m_pTypeInfo;
}
// -----------------------------------------------------------------------------
<|endoftext|> |
<commit_before>#pragma once
#ifndef WTL_PRANDOM_HPP_
#define WTL_PRANDOM_HPP_
#include <vector>
#include <random>
#include <unordered_set>
/////////1/////////2/////////3/////////4/////////5/////////6/////////7/////////
namespace wtl {
/////////1/////////2/////////3/////////4/////////5/////////6/////////7/////////
template <class Iter, class RNG> inline
Iter choice(Iter begin_, Iter end_, RNG& rng) {
using diff_t = decltype(std::distance(begin_, end_));
std::uniform_int_distribution<diff_t> uniform(0, std::distance(begin_, end_) - 1);
std::advance(begin_, uniform(rng));
return begin_;
}
template <class Container, class RNG> inline
std::vector<typename Container::value_type>
sample(const Container& src, const size_t k, RNG& rng) {
const size_t n = src.size();
if (100 * k < n) {return sample_set(src, k, rng);}
else if (5 * k < n) {return sample_fisher(src, k, rng);}
else {return sample_knuth(src, k, rng);}
}
//! fast if k << n
template <class Container, class RNG> inline
std::vector<typename Container::value_type>
sample_set(const Container& src, const size_t k, RNG& rng) {
const size_t n = src.size();
if (n < k) throw std::runtime_error(std::string(__PRETTY_FUNCTION__) + ": n < k");
std::unordered_set<size_t> existing_indices;
std::vector<typename Container::value_type> dst;
dst.reserve(k);
std::uniform_int_distribution<size_t> uniform(0, n - 1);
size_t idx = 0;
for (size_t i=0; i<k; ++i) {
do {
idx = uniform(rng);
} while (!std::get<1>(existing_indices.insert(idx)));
dst.push_back(src[idx]);
}
return dst;
}
//! Fisher-Yates algorithm; Durstenfeld; Knuth's P
//! consistently fast; note that whole src is copied first
template <class Container, class RNG> inline
std::vector<typename Container::value_type>
sample_fisher(const Container& src, const size_t k, RNG& rng) {
std::vector<typename Container::value_type> dst(std::begin(src), std::end(src));
const size_t n = dst.size();
if (n < k) throw std::runtime_error(std::string(__PRETTY_FUNCTION__) + ": n < k");
const size_t last = n - 1;
for (size_t i=0; i<k; ++i) {
std::swap(dst[std::uniform_int_distribution<size_t>(i, last)(rng)], dst[i]);
}
dst.resize(k);
return dst;
}
//! Knuth's algorithm S
//! fast if k / n is large
//! The order is not random
template <class Container, class RNG> inline
std::vector<typename Container::value_type>
sample_knuth(const Container& src, const size_t k, RNG& rng) {
const size_t n = src.size();
if (n < k) throw std::runtime_error(std::string(__PRETTY_FUNCTION__) + ": n < k");
std::vector<typename Container::value_type> dst;
dst.reserve(k);
size_t i = 0;
for (; i<k; ++i) {
dst.push_back(src[i]);
}
std::uniform_int_distribution<size_t> uniform(0, k - 1);
while (i < n) {
if (std::bernoulli_distribution((1.0 / ++i) * k)(rng)) {
dst[uniform(rng)] = src[i - 1];
}
}
return dst;
}
/////////1/////////2/////////3/////////4/////////5/////////6/////////7/////////
//! Pythonic RNG object
template <class Generator>
class Prandom{
public:
// typedefs
typedef unsigned int result_type;
typedef result_type argument_type;
static constexpr result_type min() {return Generator::min();}
static constexpr result_type max() {return Generator::max();}
// constructors
explicit Prandom(const result_type s=std::random_device{}())
: seed_(s), generator_(s) {seed(s);}
Prandom(const Prandom&) = delete;
////////////////////////////////////////
// methods
void seed(const result_type s) {seed_ = s; generator_.seed(seed_);}
void discard(unsigned long long n) {generator_.discard(n);}
////////////////////
// integer
// [0, 2^32-1]
result_type operator()() {return generator_();}
// [0, n-1]
unsigned int randrange(unsigned int n) {
return std::uniform_int_distribution<unsigned int>(0, --n)(generator_);
}
// [a, b-1]
int randrange(const int a, int b) {
return randint(a, --b);
}
// [a, b]
int randint(const int a, const int b) {
return std::uniform_int_distribution<int>(a, b)(generator_);
}
////////////////////
// uniform real
// [0.0, 1.0)
double random() {
return std::uniform_real_distribution<double>()(generator_);
}
// (0.0, 1.0]
double random_oc() {return 1.0 - random();}
// [0.0, n)
double uniform(double n) {
return std::uniform_real_distribution<double>(0, n)(generator_);
}
// [a, b)
double uniform(double a, double b) {
return std::uniform_real_distribution<double>(a, b)(generator_);
}
////////////////////
// continuous
// E = 1/lambda, V = 1/lambda^2
double exponential(const double lambda=1.0) {
return std::exponential_distribution<double>(lambda)(generator_);
}
// Scale-free: E = ?, V = ?
double power(const double k=1.0, const double min=1.0) {
return min * std::pow(random_oc(), -1.0 / k);
}
// E = mu, V = sigma^2
double gauss(const double mu=0.0, const double sigma=1.0) {
return std::normal_distribution<double>(mu, sigma)(generator_);
}
double normal(const double mu=0.0, const double sigma=1.0) {return gauss(mu, sigma);}
////////////////////
// discrete
// return true with probability p
// E = p, V = p(1-p)
bool bernoulli(const double p=0.5) {
return std::bernoulli_distribution(p)(generator_);
}
// The number of true in n trials with probability p
// E = np, V = np(1-p)
unsigned int binomial(const unsigned int n, const double p=0.5) {
return std::binomial_distribution<unsigned int>(n, p)(generator_);
}
// The expected number of occurrences in an unit of time/space
// E = V = lambda
unsigned int poisson(const double lambda) {
return std::poisson_distribution<unsigned int>(lambda)(generator_);
}
// The number of trials needed to get first true
// E = (1-p)/p, V = (1-p)/p^2
unsigned int geometric(const double p) {
return std::geometric_distribution<unsigned int>(p)(generator_);
}
////////////////////
// sequence
template <class Iter>
Iter choice(Iter begin_, Iter end_) {
return wtl::choice(begin_, end_, generator_);
}
template <class Container>
Container sample(Container src, const size_t k) {
wtl::sample(&src, k, generator_);
return src;
}
private:
unsigned int seed_;
Generator generator_;
};
/////////1/////////2/////////3/////////4/////////5/////////6/////////7/////////
// Global definition/declaration
inline std::mt19937& mt() {
static std::mt19937 generator(std::random_device{}());
return generator;
}
inline std::mt19937_64& mt64() {
static std::mt19937_64 generator(std::random_device{}());
return generator;
}
inline Prandom<std::mt19937>& prandom() {
static Prandom<std::mt19937> generator;
return generator;
}
/////////1/////////2/////////3/////////4/////////5/////////6/////////7/////////
} // namespace wtl
/////////1/////////2/////////3/////////4/////////5/////////6/////////7/////////
#endif /* WTL_PRANDOM_HPP_ */
<commit_msg>Add generate_canonical() for shortcut<commit_after>#pragma once
#ifndef WTL_PRANDOM_HPP_
#define WTL_PRANDOM_HPP_
#include <vector>
#include <random>
#include <unordered_set>
/////////1/////////2/////////3/////////4/////////5/////////6/////////7/////////
namespace wtl {
/////////1/////////2/////////3/////////4/////////5/////////6/////////7/////////
template <class URBG> inline
double generate_canonical(URBG& gen) {
return std::generate_canonical<double, std::numeric_limits<double>::digits>(gen);
}
template <class Iter, class RNG> inline
Iter choice(Iter begin_, Iter end_, RNG& rng) {
using diff_t = decltype(std::distance(begin_, end_));
std::uniform_int_distribution<diff_t> uniform(0, std::distance(begin_, end_) - 1);
std::advance(begin_, uniform(rng));
return begin_;
}
template <class Container, class RNG> inline
std::vector<typename Container::value_type>
sample(const Container& src, const size_t k, RNG& rng) {
const size_t n = src.size();
if (100 * k < n) {return sample_set(src, k, rng);}
else if (5 * k < n) {return sample_fisher(src, k, rng);}
else {return sample_knuth(src, k, rng);}
}
//! fast if k << n
template <class Container, class RNG> inline
std::vector<typename Container::value_type>
sample_set(const Container& src, const size_t k, RNG& rng) {
const size_t n = src.size();
if (n < k) throw std::runtime_error(std::string(__PRETTY_FUNCTION__) + ": n < k");
std::unordered_set<size_t> existing_indices;
std::vector<typename Container::value_type> dst;
dst.reserve(k);
std::uniform_int_distribution<size_t> uniform(0, n - 1);
size_t idx = 0;
for (size_t i=0; i<k; ++i) {
do {
idx = uniform(rng);
} while (!std::get<1>(existing_indices.insert(idx)));
dst.push_back(src[idx]);
}
return dst;
}
//! Fisher-Yates algorithm; Durstenfeld; Knuth's P
//! consistently fast; note that whole src is copied first
template <class Container, class RNG> inline
std::vector<typename Container::value_type>
sample_fisher(const Container& src, const size_t k, RNG& rng) {
std::vector<typename Container::value_type> dst(std::begin(src), std::end(src));
const size_t n = dst.size();
if (n < k) throw std::runtime_error(std::string(__PRETTY_FUNCTION__) + ": n < k");
const size_t last = n - 1;
for (size_t i=0; i<k; ++i) {
std::swap(dst[std::uniform_int_distribution<size_t>(i, last)(rng)], dst[i]);
}
dst.resize(k);
return dst;
}
//! Knuth's algorithm S
//! fast if k / n is large
//! The order is not random
template <class Container, class RNG> inline
std::vector<typename Container::value_type>
sample_knuth(const Container& src, const size_t k, RNG& rng) {
const size_t n = src.size();
if (n < k) throw std::runtime_error(std::string(__PRETTY_FUNCTION__) + ": n < k");
std::vector<typename Container::value_type> dst;
dst.reserve(k);
size_t i = 0;
for (; i<k; ++i) {
dst.push_back(src[i]);
}
std::uniform_int_distribution<size_t> uniform(0, k - 1);
while (i < n) {
if (std::bernoulli_distribution((1.0 / ++i) * k)(rng)) {
dst[uniform(rng)] = src[i - 1];
}
}
return dst;
}
/////////1/////////2/////////3/////////4/////////5/////////6/////////7/////////
//! Pythonic RNG object
template <class Generator>
class Prandom{
public:
// typedefs
typedef unsigned int result_type;
typedef result_type argument_type;
static constexpr result_type min() {return Generator::min();}
static constexpr result_type max() {return Generator::max();}
// constructors
explicit Prandom(const result_type s=std::random_device{}())
: seed_(s), generator_(s) {seed(s);}
Prandom(const Prandom&) = delete;
////////////////////////////////////////
// methods
void seed(const result_type s) {seed_ = s; generator_.seed(seed_);}
void discard(unsigned long long n) {generator_.discard(n);}
////////////////////
// integer
// [0, 2^32-1]
result_type operator()() {return generator_();}
// [0, n-1]
unsigned int randrange(unsigned int n) {
return std::uniform_int_distribution<unsigned int>(0, --n)(generator_);
}
// [a, b-1]
int randrange(const int a, int b) {
return randint(a, --b);
}
// [a, b]
int randint(const int a, const int b) {
return std::uniform_int_distribution<int>(a, b)(generator_);
}
////////////////////
// uniform real
// [0.0, 1.0)
double random() {
return std::uniform_real_distribution<double>()(generator_);
}
// (0.0, 1.0]
double random_oc() {return 1.0 - random();}
// [0.0, n)
double uniform(double n) {
return std::uniform_real_distribution<double>(0, n)(generator_);
}
// [a, b)
double uniform(double a, double b) {
return std::uniform_real_distribution<double>(a, b)(generator_);
}
////////////////////
// continuous
// E = 1/lambda, V = 1/lambda^2
double exponential(const double lambda=1.0) {
return std::exponential_distribution<double>(lambda)(generator_);
}
// Scale-free: E = ?, V = ?
double power(const double k=1.0, const double min=1.0) {
return min * std::pow(random_oc(), -1.0 / k);
}
// E = mu, V = sigma^2
double gauss(const double mu=0.0, const double sigma=1.0) {
return std::normal_distribution<double>(mu, sigma)(generator_);
}
double normal(const double mu=0.0, const double sigma=1.0) {return gauss(mu, sigma);}
////////////////////
// discrete
// return true with probability p
// E = p, V = p(1-p)
bool bernoulli(const double p=0.5) {
return std::bernoulli_distribution(p)(generator_);
}
// The number of true in n trials with probability p
// E = np, V = np(1-p)
unsigned int binomial(const unsigned int n, const double p=0.5) {
return std::binomial_distribution<unsigned int>(n, p)(generator_);
}
// The expected number of occurrences in an unit of time/space
// E = V = lambda
unsigned int poisson(const double lambda) {
return std::poisson_distribution<unsigned int>(lambda)(generator_);
}
// The number of trials needed to get first true
// E = (1-p)/p, V = (1-p)/p^2
unsigned int geometric(const double p) {
return std::geometric_distribution<unsigned int>(p)(generator_);
}
////////////////////
// sequence
template <class Iter>
Iter choice(Iter begin_, Iter end_) {
return wtl::choice(begin_, end_, generator_);
}
template <class Container>
Container sample(Container src, const size_t k) {
wtl::sample(&src, k, generator_);
return src;
}
private:
unsigned int seed_;
Generator generator_;
};
/////////1/////////2/////////3/////////4/////////5/////////6/////////7/////////
// Global definition/declaration
inline std::mt19937& mt() {
static std::mt19937 generator(std::random_device{}());
return generator;
}
inline std::mt19937_64& mt64() {
static std::mt19937_64 generator(std::random_device{}());
return generator;
}
inline Prandom<std::mt19937>& prandom() {
static Prandom<std::mt19937> generator;
return generator;
}
/////////1/////////2/////////3/////////4/////////5/////////6/////////7/////////
} // namespace wtl
/////////1/////////2/////////3/////////4/////////5/////////6/////////7/////////
#endif /* WTL_PRANDOM_HPP_ */
<|endoftext|> |
<commit_before>/****************************************************************************
*
* Copyright (c) 2014, 2015 PX4 Development Team. All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
*
* 1. Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* 2. Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in
* the documentation and/or other materials provided with the
* distribution.
* 3. Neither the name PX4 nor the names of its contributors may be
* used to endorse or promote products derived from this software
* without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
* "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
* LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
* FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
* COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
* INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
* BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS
* OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED
* AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
* LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN
* ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
* POSSIBILITY OF SUCH DAMAGE.
*
****************************************************************************/
/**
* @file mavlink_orb_subscription.cpp
* uORB subscription implementation.
*
* @author Anton Babushkin <anton.babushkin@me.com>
* @author Lorenz Meier <lorenz@px4.io>
*/
#include <unistd.h>
#include <stdlib.h>
#include <string.h>
#include <uORB/uORB.h>
#include <stdio.h>
#include "mavlink_orb_subscription.h"
MavlinkOrbSubscription::MavlinkOrbSubscription(const orb_id_t topic, int instance) :
next(nullptr),
_topic(topic),
_instance(instance),
_fd(-1),
_published(false),
_last_pub_check(0),
_subscribe_from_beginning(false)
{
}
MavlinkOrbSubscription::~MavlinkOrbSubscription()
{
if (_fd >= 0) {
orb_unsubscribe(_fd);
}
}
orb_id_t
MavlinkOrbSubscription::get_topic() const
{
return _topic;
}
int
MavlinkOrbSubscription::get_instance() const
{
return _instance;
}
bool
MavlinkOrbSubscription::update(uint64_t *time, void *data)
{
// TODO this is NOT atomic operation, we can get data newer than time
// if topic was published between orb_stat and orb_copy calls.
uint64_t time_topic;
if (orb_stat(_fd, &time_topic)) {
/* error getting last topic publication time */
time_topic = 0;
}
if (update(data)) {
/* data copied successfully */
if (time_topic == 0 || (time_topic != *time)) {
*time = time_topic;
return true;
} else {
return false;
}
}
return false;
}
bool
MavlinkOrbSubscription::update(void *data)
{
if (!is_published()) {
return false;
}
if (orb_copy(_topic, _fd, data)) {
if (data != nullptr) {
/* error copying topic data */
memset(data, 0, _topic->o_size);
}
return false;
}
return true;
}
bool
MavlinkOrbSubscription::update_if_changed(void *data)
{
bool prevpub = _published;
if (!is_published()) {
return false;
}
bool updated;
if (orb_check(_fd, &updated)) {
return false;
}
// If we didn't update and this topic did not change
// its publication status then nothing really changed
if (!updated && prevpub == _published) {
return false;
}
return update(data);
}
bool
MavlinkOrbSubscription::is_published()
{
// If we marked it as published no need to check again
if (_published) {
return true;
}
// Telemetry can sustain an initial published check at 10 Hz
hrt_abstime now = hrt_absolute_time();
if (now - _last_pub_check < 100000) {
return false;
}
// We are checking now
_last_pub_check = now;
#if defined(__PX4_QURT) || defined(__PX4_POSIX_EAGLE)
if (_fd < 0) {
_fd = orb_subscribe_multi(_topic, _instance);
}
#else
// We don't want to subscribe to anything that does not exist
// in order to save memory and file descriptors.
// However, for some topics like vehicle_command_ack, we want to subscribe
// from the beginning in order not to miss the first publish respective advertise.
if (!_subscribe_from_beginning && orb_exists(_topic, _instance)) {
return false;
}
if (_fd < 0) {
_fd = orb_subscribe_multi(_topic, _instance);
}
#endif
bool updated;
orb_check(_fd, &updated);
if (updated) {
_published = true;
}
return _published;
}
void
MavlinkOrbSubscription::subscribe_from_beginning(bool subscribe_from_beginning)
{
_subscribe_from_beginning = subscribe_from_beginning;
}
<commit_msg>mavlink: add comment for Snapdragon<commit_after>/****************************************************************************
*
* Copyright (c) 2014, 2015 PX4 Development Team. All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
*
* 1. Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* 2. Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in
* the documentation and/or other materials provided with the
* distribution.
* 3. Neither the name PX4 nor the names of its contributors may be
* used to endorse or promote products derived from this software
* without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
* "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
* LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
* FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
* COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
* INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
* BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS
* OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED
* AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
* LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN
* ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
* POSSIBILITY OF SUCH DAMAGE.
*
****************************************************************************/
/**
* @file mavlink_orb_subscription.cpp
* uORB subscription implementation.
*
* @author Anton Babushkin <anton.babushkin@me.com>
* @author Lorenz Meier <lorenz@px4.io>
*/
#include <unistd.h>
#include <stdlib.h>
#include <string.h>
#include <uORB/uORB.h>
#include <stdio.h>
#include "mavlink_orb_subscription.h"
MavlinkOrbSubscription::MavlinkOrbSubscription(const orb_id_t topic, int instance) :
next(nullptr),
_topic(topic),
_instance(instance),
_fd(-1),
_published(false),
_last_pub_check(0),
_subscribe_from_beginning(false)
{
}
MavlinkOrbSubscription::~MavlinkOrbSubscription()
{
if (_fd >= 0) {
orb_unsubscribe(_fd);
}
}
orb_id_t
MavlinkOrbSubscription::get_topic() const
{
return _topic;
}
int
MavlinkOrbSubscription::get_instance() const
{
return _instance;
}
bool
MavlinkOrbSubscription::update(uint64_t *time, void *data)
{
// TODO this is NOT atomic operation, we can get data newer than time
// if topic was published between orb_stat and orb_copy calls.
uint64_t time_topic;
if (orb_stat(_fd, &time_topic)) {
/* error getting last topic publication time */
time_topic = 0;
}
if (update(data)) {
/* data copied successfully */
if (time_topic == 0 || (time_topic != *time)) {
*time = time_topic;
return true;
} else {
return false;
}
}
return false;
}
bool
MavlinkOrbSubscription::update(void *data)
{
if (!is_published()) {
return false;
}
if (orb_copy(_topic, _fd, data)) {
if (data != nullptr) {
/* error copying topic data */
memset(data, 0, _topic->o_size);
}
return false;
}
return true;
}
bool
MavlinkOrbSubscription::update_if_changed(void *data)
{
bool prevpub = _published;
if (!is_published()) {
return false;
}
bool updated;
if (orb_check(_fd, &updated)) {
return false;
}
// If we didn't update and this topic did not change
// its publication status then nothing really changed
if (!updated && prevpub == _published) {
return false;
}
return update(data);
}
bool
MavlinkOrbSubscription::is_published()
{
// If we marked it as published no need to check again
if (_published) {
return true;
}
// Telemetry can sustain an initial published check at 10 Hz
hrt_abstime now = hrt_absolute_time();
if (now - _last_pub_check < 100000) {
return false;
}
// We are checking now
_last_pub_check = now;
#if defined(__PX4_QURT) || defined(__PX4_POSIX_EAGLE)
// Snapdragon has currently no support for orb_exists, therefore
// we're not using it.
if (_fd < 0) {
_fd = orb_subscribe_multi(_topic, _instance);
}
#else
// We don't want to subscribe to anything that does not exist
// in order to save memory and file descriptors.
// However, for some topics like vehicle_command_ack, we want to subscribe
// from the beginning in order not to miss the first publish respective advertise.
if (!_subscribe_from_beginning && orb_exists(_topic, _instance)) {
return false;
}
if (_fd < 0) {
_fd = orb_subscribe_multi(_topic, _instance);
}
#endif
bool updated;
orb_check(_fd, &updated);
if (updated) {
_published = true;
}
return _published;
}
void
MavlinkOrbSubscription::subscribe_from_beginning(bool subscribe_from_beginning)
{
_subscribe_from_beginning = subscribe_from_beginning;
}
<|endoftext|> |
<commit_before>#ifndef __CLITL_HPP__
#define __CLITL_HPP__
#include <cstdio>
#include <iosfwd>
#include <locale>
#include <string>
#include <utility>
#ifdef UNIX
#include <sys/ioctl.h>
#include <termios.h>
#include <unistd.h>
#elif WIN32
#include <conio.h>
#include <Windows.h>
#endif
namespace clitl {
/* Color class */
enum class color {
#ifdef UNIX
VOIDSPACE = -1,
DEFAULT = 0,
BLACK = 30,
RED = 31,
GREEN = 32,
BROWN = 33,
BLUE = 34,
MAGENTA = 35,
CYAN = 36,
#elif WIN32
VOIDSPACE = -1,
DEFAULT = 7,
BLACK = 0,
RED = 4,
GREEN = 2,
BROWN = 7, // Worthless
BLUE = 1,
MAGENTA = 7, // Worthless
CYAN = 9,
#endif
};
/* Basic definitions and containers */
typedef int coord_t;
typedef int colornum_t;
template <typename T>
class rect {
std::pair<T, T> origin;
std::pair<T, T> endpoint;
color foreground;
public:
explicit rect(const std::pair<T, T>& origin,
const std::pair<T, T>& endpoint,
const color& foreground)
: origin(origin), endpoint(endpoint), foreground(foreground) {}
explicit rect(const std::pair<T, T>& origin,
const std::pair<T, T>& endpoint)
: rect(origin, endpoint, color::DEFAULT) {}
explicit rect() : rect(std::pair<T, T>(0, 0),
std::pair<T, T>(0, 0), color::DEFAULT) {}
rect<T>& set_origin(const std::pair<T, T>& coord)
{
origin = coord;
return *this;
}
rect<T>& set_endpoint(const std::pair<T, T>& coord)
{
endpoint = coord;
return *this;
}
rect<T>& set_foreground(const color& foreg)
{
foreground = foreg;
return *this;
}
const std::pair<T, T>& get_origin()
{
return origin;
}
const std::pair<T, T>& get_endpoint()
{
return endpoint;
}
const color& get_foreground()
{
return foreground;
}
};
template <typename charT,
class traits = char_traits<charT>,
class Alloc = allocator<charT> >
struct colorstring {
std::basic_string<charT, traits, Alloc> str;
color foreground;
};
/* Output buffer */
template <typename charT, typename traits = std::char_traits<charT> >
class basic_outbuf : public std::basic_streambuf<charT, traits> {
protected:
virtual typename traits::int_type
overflow(typename traits::int_type c)
{
if (std::putchar(c) == EOF) {
return traits::eof();
}
return traits::not_eof(c);
}
};
typedef basic_outbuf<char> outbuf;
typedef basic_outbuf<wchar_t> woutbuf;
/* Output stream */
template <typename charT, typename traits = std::char_traits<charT> >
class basic_ostream : public std::basic_ostream<charT, traits> {
public:
#ifdef UNIX
struct winsize wsize;
#endif
#ifdef WIN32
HANDLE termout_handle;
CONSOLE_CURSOR_INFO termout_curinfo;
CONSOLE_SCREEN_BUFFER_INFO termout_sbufinfo;
#endif
explicit basic_ostream(basic_outbuf<charT, traits>* sb)
: std::basic_ostream<charT, traits>(sb)
{
#ifdef UNIX
wsize = { 0 };
#elif WIN32
termout_handle = GetStdHandle(STD_OUTPUT_HANDLE);
#endif
}
basic_ostream<charT, traits>& moveto(const std::pair<coord_t, coord_t>& coord)
{
#ifdef TARGET_IS_POSIX
cout << "\033[" << coord.second << ";" << coord.first << "f";
#elif WIN32
COORD pos = { static_cast<SHORT>(coord.first), static_cast<SHORT>(coord.second) };
SetConsoleCursorPosition(termout_handle, pos);
#endif
return *this;
}
std::pair<coord_t, coord_t> screensize()
{
static coord_t column;
static coord_t row;
#ifdef UNIX
column = wsize.ws_col;
row = wsize.ws_row;
#elif WIN32
GetConsoleScreenBufferInfo(termout_handle, &termout_sbufinfo);
column = static_cast<coord_t>(termout_sbufinfo.dwSize.X);
row = static_cast<coord_t>(termout_sbufinfo.dwSize.Y);
#endif
return std::pair<coord_t, coord_t>(column, row);
}
basic_ostream<charT, traits>& operator<<
(basic_ostream<charT, traits>& (*op)(basic_ostream<charT, traits>&))
{
return (*op)(*this);
}
};
typedef basic_ostream<char> ostream;
typedef basic_ostream<wchar_t> wostream;
template <typename charT, typename traits>
basic_ostream<charT, traits>& pre_process(basic_ostream<charT, traits>& os)
{
os << alternative_system_screenbuffer;
os << hide_cursor;
os << clear;
return os;
}
template <typename charT, typename traits>
basic_ostream<charT, traits>& post_process(basic_ostream<charT, traits>& os)
{
os << normal_system_screenbuffer;
os << show_cursor;
return os;
}
template <typename charT, typename traits>
basic_ostream<charT, traits>& alternative_system_screenbuffer(basic_ostream<charT, traits>& os)
{
#if UNIX
cout << "\033[?1049h"; // Use alternate screen buffer
#endif
return os;
}
template <typename charT, typename traits>
basic_ostream<charT, traits>& clear(basic_ostream<charT, traits>& os)
{
#ifdef UNIX
cout << "\033[2J";
#elif WIN32
COORD startpoint = { 0, 0 };
DWORD dw;
GetConsoleScreenBufferInfo(os.termout_handle, &os.termout_sbufinfo);
FillConsoleOutputCharacterA(os.termout_handle, ' ',
os.termout_sbufinfo.dwSize.X * os.termout_sbufinfo.dwSize.Y,
startpoint, &dw);
FillConsoleOutputAttribute(os.termout_handle,
FOREGROUND_GREEN | FOREGROUND_RED | FOREGROUND_BLUE,
os.termout_sbufinfo.dwSize.X * os.termout_sbufinfo.dwSize.Y,
startpoint, &dw);
#endif
return os;
}
template <typename charT, typename traits>
basic_ostream<charT, traits>& hide_cursor(basic_ostream<charT, traits>& os)
{
#ifdef UNIX
cout << "\033[?25l"; // Hide cursor
#elif WIN32
GetConsoleCursorInfo(os.termout_handle, &os.termout_curinfo);
os.termout_curinfo.bVisible = 0;
SetConsoleCursorInfo(os.termout_handle, &os.termout_curinfo);
#endif
return os;
}
template <typename charT, typename traits>
basic_ostream<charT, traits>& normal_system_screenbuffer(basic_ostream<charT, traits>& os)
{
#if UNIX
cout << "\033[?1049l"; // Use normal screen buffer
#endif
return os;
}
template <typename charT, typename traits>
basic_ostream<charT, traits>& refresh(basic_ostream<charT, traits>& os)
{
fflush(stdout);
return os;
}
template <typename charT, typename traits>
basic_ostream<charT, traits>& show_cursor(basic_ostream<charT, traits>& os)
{
#if UNIX
cout << "\033[?25h"; // Show cursor
#elif WIN32
CONSOLE_CURSOR_INFO termout_curinfo;
GetConsoleCursorInfo(os.termout_handle, &termout_curinfo);
termout_curinfo.bVisible = 1;
SetConsoleCursorInfo(os.termout_handle, &termout_curinfo);
#endif
return os;
}
template <typename charT, typename traits, typename Alloc>
basic_ostream<charT, traits>& operator<<
(basic_ostream<charT, traits>& os,
const std::pair<std::basic_string<charT, traits, Alloc>, color>& tu)
{
#ifdef UNIX
os << "\033[" << static_cast<coord_t>(std::get<1>(tu))
<< "m" << std::get<0>(tu).c_str() << "\033[0m";
#elif WIN32
WORD termout_attribute;
GetConsoleScreenBufferInfo(os.termout_handle, &os.termout_sbufinfo);
termout_attribute = os.termout_sbufinfo.wAttributes;
SetConsoleTextAttribute(os.termout_handle, static_cast<coord_t>(std::get<1>(tu)));
os << std::get<0>(tu);
SetConsoleTextAttribute(os.termout_handle, termout_attribute);
#endif
return os;
}
template <typename charT, typename traits, typename Alloc, typename coordT>
basic_ostream<charT, traits>& operator<<
(basic_ostream<charT, traits>& os,
const std::pair<std::basic_string<charT, traits, Alloc>, rect<coordT> >& pr)
{
}
/* Input buffer */
/* Input stream */
template <typename charT, typename traits = std::char_traits<charT> >
class basic_istream : public std::basic_istream<charT, traits> {
};
typedef basic_istream<char> istream;
typedef basic_istream<wchar_t> wistream;
}
#endif
<commit_msg>Add opeartor<<(basic_ostream<>, rect<>)<commit_after>#ifndef __CLITL_HPP__
#define __CLITL_HPP__
#include <cstdio>
#include <iosfwd>
#include <locale>
#include <string>
#include <tuple>
#include <utility>
#ifdef UNIX
#include <sys/ioctl.h>
#include <termios.h>
#include <unistd.h>
#elif WIN32
#include <conio.h>
#include <Windows.h>
#endif
namespace clitl {
/* Color class */
enum class color {
#ifdef UNIX
VOIDSPACE = -1,
DEFAULT = 0,
BLACK = 30,
RED = 31,
GREEN = 32,
BROWN = 33,
BLUE = 34,
MAGENTA = 35,
CYAN = 36,
#elif WIN32
VOIDSPACE = -1,
DEFAULT = 7,
BLACK = 0,
RED = 4,
GREEN = 2,
BROWN = 7, // Worthless
BLUE = 1,
MAGENTA = 7, // Worthless
CYAN = 9,
#endif
};
/* Basic definitions and containers */
typedef int coord_t;
typedef int colornum_t;
template <typename T>
class rect {
std::pair<T, T> origin;
std::pair<T, T> endpoint;
color foreground;
public:
explicit rect(const std::pair<T, T>& origin,
const std::pair<T, T>& endpoint,
const color& foreground)
: origin(origin), endpoint(endpoint), foreground(foreground) {}
explicit rect(const std::pair<T, T>& origin,
const std::pair<T, T>& endpoint)
: rect(origin, endpoint, color::DEFAULT) {}
explicit rect() : rect(std::pair<T, T>(0, 0),
std::pair<T, T>(0, 0), color::DEFAULT) {}
const rect<T>& set_origin(const std::pair<T, T>& coord)
{
origin = coord;
return *this;
}
const rect<T>& set_endpoint(const std::pair<T, T>& coord)
{
endpoint = coord;
return *this;
}
const rect<T>& set_foreground(const color& foreg)
{
foreground = foreg;
return *this;
}
const std::pair<T, T>& get_origin() const
{
return origin;
}
const std::pair<T, T>& get_endpoint() const
{
return endpoint;
}
const color& get_foreground() const
{
return foreground;
}
};
template <typename charT,
class traits = char_traits<charT>,
class Alloc = allocator<charT> >
struct colorstring {
std::basic_string<charT, traits, Alloc> str;
color foreground;
};
/* Output buffer */
template <typename charT, typename traits = std::char_traits<charT> >
class basic_outbuf : public std::basic_streambuf<charT, traits> {
protected:
virtual typename traits::int_type
overflow(typename traits::int_type c)
{
if (std::putchar(c) == EOF) {
return traits::eof();
}
return traits::not_eof(c);
}
};
typedef basic_outbuf<char> outbuf;
typedef basic_outbuf<wchar_t> woutbuf;
/* Output stream */
template <typename charT, typename traits = std::char_traits<charT> >
class basic_ostream : public std::basic_ostream<charT, traits> {
public:
#ifdef UNIX
struct winsize wsize;
#endif
#ifdef WIN32
HANDLE termout_handle;
CONSOLE_CURSOR_INFO termout_curinfo;
CONSOLE_SCREEN_BUFFER_INFO termout_sbufinfo;
#endif
explicit basic_ostream(basic_outbuf<charT, traits>* sb)
: std::basic_ostream<charT, traits>(sb)
{
#ifdef UNIX
wsize = { 0 };
#elif WIN32
termout_handle = GetStdHandle(STD_OUTPUT_HANDLE);
#endif
}
basic_ostream<charT, traits>& moveto(const std::pair<coord_t, coord_t>& coord)
{
#ifdef TARGET_IS_POSIX
cout << "\033[" << coord.second << ";" << coord.first << "f";
#elif WIN32
COORD pos = { static_cast<SHORT>(coord.first), static_cast<SHORT>(coord.second) };
SetConsoleCursorPosition(termout_handle, pos);
#endif
return *this;
}
std::pair<coord_t, coord_t> screensize()
{
static coord_t column;
static coord_t row;
#ifdef UNIX
column = wsize.ws_col;
row = wsize.ws_row;
#elif WIN32
GetConsoleScreenBufferInfo(termout_handle, &termout_sbufinfo);
column = static_cast<coord_t>(termout_sbufinfo.dwSize.X);
row = static_cast<coord_t>(termout_sbufinfo.dwSize.Y);
#endif
return std::pair<coord_t, coord_t>(column, row);
}
basic_ostream<charT, traits>& operator<<
(basic_ostream<charT, traits>& (*op)(basic_ostream<charT, traits>&))
{
return (*op)(*this);
}
};
typedef basic_ostream<char> ostream;
typedef basic_ostream<wchar_t> wostream;
template <typename charT, typename traits>
basic_ostream<charT, traits>& pre_process(basic_ostream<charT, traits>& os)
{
os << alternative_system_screenbuffer;
os << hide_cursor;
os << clear;
return os;
}
template <typename charT, typename traits>
basic_ostream<charT, traits>& post_process(basic_ostream<charT, traits>& os)
{
os << normal_system_screenbuffer;
os << show_cursor;
return os;
}
template <typename charT, typename traits>
basic_ostream<charT, traits>& alternative_system_screenbuffer(basic_ostream<charT, traits>& os)
{
#if UNIX
cout << "\033[?1049h"; // Use alternate screen buffer
#endif
return os;
}
template <typename charT, typename traits>
basic_ostream<charT, traits>& clear(basic_ostream<charT, traits>& os)
{
#ifdef UNIX
cout << "\033[2J";
#elif WIN32
COORD startpoint = { 0, 0 };
DWORD dw;
GetConsoleScreenBufferInfo(os.termout_handle, &os.termout_sbufinfo);
FillConsoleOutputCharacterA(os.termout_handle, ' ',
os.termout_sbufinfo.dwSize.X * os.termout_sbufinfo.dwSize.Y,
startpoint, &dw);
FillConsoleOutputAttribute(os.termout_handle,
FOREGROUND_GREEN | FOREGROUND_RED | FOREGROUND_BLUE,
os.termout_sbufinfo.dwSize.X * os.termout_sbufinfo.dwSize.Y,
startpoint, &dw);
#endif
return os;
}
template <typename charT, typename traits>
basic_ostream<charT, traits>& hide_cursor(basic_ostream<charT, traits>& os)
{
#ifdef UNIX
cout << "\033[?25l"; // Hide cursor
#elif WIN32
GetConsoleCursorInfo(os.termout_handle, &os.termout_curinfo);
os.termout_curinfo.bVisible = 0;
SetConsoleCursorInfo(os.termout_handle, &os.termout_curinfo);
#endif
return os;
}
template <typename charT, typename traits>
basic_ostream<charT, traits>& normal_system_screenbuffer(basic_ostream<charT, traits>& os)
{
#if UNIX
cout << "\033[?1049l"; // Use normal screen buffer
#endif
return os;
}
template <typename charT, typename traits>
basic_ostream<charT, traits>& refresh(basic_ostream<charT, traits>& os)
{
fflush(stdout);
return os;
}
template <typename charT, typename traits>
basic_ostream<charT, traits>& show_cursor(basic_ostream<charT, traits>& os)
{
#if UNIX
cout << "\033[?25h"; // Show cursor
#elif WIN32
CONSOLE_CURSOR_INFO termout_curinfo;
GetConsoleCursorInfo(os.termout_handle, &termout_curinfo);
termout_curinfo.bVisible = 1;
SetConsoleCursorInfo(os.termout_handle, &termout_curinfo);
#endif
return os;
}
template <typename charT, typename traits, typename Alloc>
basic_ostream<charT, traits>& operator<<
(basic_ostream<charT, traits>& os,
const std::tuple<std::basic_string<charT, traits, Alloc>, color>& tu)
{
#ifdef UNIX
os << "\033[" << static_cast<coord_t>(std::get<1>(tu))
<< "m" << std::get<0>(tu).c_str() << "\033[0m";
#elif WIN32
WORD termout_attribute;
GetConsoleScreenBufferInfo(os.termout_handle, &os.termout_sbufinfo);
termout_attribute = os.termout_sbufinfo.wAttributes;
SetConsoleTextAttribute(os.termout_handle, static_cast<coord_t>(std::get<1>(tu)));
os << std::get<0>(tu);
SetConsoleTextAttribute(os.termout_handle, termout_attribute);
#endif
return os;
}
template <typename charT, typename traits, typename coordT>
basic_ostream<charT, traits>& operator<<
(basic_ostream<charT, traits>& os, const rect<coordT>& re)
{
for (int i = re.get_origin().first; i <= re.get_endpoint().first; ++i) {
for (int j = re.get_origin().second; j <= re.get_endpoint().second; ++j) {
os.moveto(std::pair<coord_t, coord_t>(i, j));
os << std::tuple<std::basic_string<charT>, color>
("@", re.get_foreground());
}
}
return os;
}
/* Input buffer */
/* Input stream */
template <typename charT, typename traits = std::char_traits<charT> >
class basic_istream : public std::basic_istream<charT, traits> {
};
typedef basic_istream<char> istream;
typedef basic_istream<wchar_t> wistream;
}
#endif
<|endoftext|> |
<commit_before>// Object stacks, used in lieu of dynamically-sized frames.
#include <algorithm>
#include <cassert>
#include <cstdlib>
#include <new>
#include <stdint.h>
#include "rust_internal.h"
#include "rust_obstack.h"
#include "rust_task.h"
// ISAAC, let go of max()!
#ifdef max
#undef max
#endif
//#define DPRINT(fmt,...) fprintf(stderr, fmt, ##__VA_ARGS__)
#define DPRINT(fmt,...)
//const size_t DEFAULT_CHUNK_SIZE = 4096;
const size_t DEFAULT_CHUNK_SIZE = 500000;
const size_t DEFAULT_ALIGNMENT = 16;
// A single type-tagged allocation in a chunk.
struct rust_obstack_alloc {
size_t len;
const type_desc *tydesc;
uint8_t data[];
rust_obstack_alloc(size_t in_len, const type_desc *in_tydesc)
: len(in_len), tydesc(in_tydesc) {}
};
// A contiguous set of allocations.
struct rust_obstack_chunk {
rust_obstack_chunk *prev;
size_t size;
size_t alen;
size_t pad;
uint8_t data[];
rust_obstack_chunk(rust_obstack_chunk *in_prev, size_t in_size)
: prev(in_prev), size(in_size), alen(0) {}
void *alloc(size_t len, type_desc *tydesc);
bool free(void *ptr);
void *mark();
};
void *
rust_obstack_chunk::alloc(size_t len, type_desc *tydesc) {
alen = align_to(alen, DEFAULT_ALIGNMENT);
if (sizeof(rust_obstack_alloc) + len > size - alen) {
DPRINT("Not enough space, len=%lu!\n", len);
assert(0); // FIXME
return NULL; // Not enough space.
}
rust_obstack_alloc *a = new(data + alen) rust_obstack_alloc(len, tydesc);
alen += sizeof(*a) + len;
return &a->data;
}
bool
rust_obstack_chunk::free(void *ptr) {
uint8_t *p = (uint8_t *)ptr;
if (p < data || p > data + size)
return false;
assert(p <= data + alen);
alen = (size_t)(p - data);
return true;
}
void *
rust_obstack_chunk::mark() {
return data + alen;
}
// Allocates the given number of bytes in a new chunk.
void *
rust_obstack::alloc_new(size_t len, type_desc *tydesc) {
size_t chunk_size = std::max(sizeof(rust_obstack_alloc) + len,
DEFAULT_CHUNK_SIZE);
void *ptr = task->malloc(sizeof(chunk) + chunk_size, "obstack");
DPRINT("making new chunk at %p, len %lu\n", ptr, chunk_size);
chunk = new(ptr) rust_obstack_chunk(chunk, chunk_size);
return chunk->alloc(len, tydesc);
}
rust_obstack::~rust_obstack() {
while (chunk) {
rust_obstack_chunk *prev = chunk->prev;
task->free(chunk);
chunk = prev;
}
}
void *
rust_obstack::alloc(size_t len, type_desc *tydesc) {
if (!chunk)
return alloc_new(len, tydesc);
DPRINT("alloc sz %u", (uint32_t)len);
void *ptr = chunk->alloc(len, tydesc);
ptr = ptr ? ptr : alloc_new(len, tydesc);
return ptr;
}
void
rust_obstack::free(void *ptr) {
if (!ptr)
return;
DPRINT("free ptr %p\n", ptr);
assert(chunk);
while (!chunk->free(ptr)) {
DPRINT("deleting chunk at %p\n", chunk);
rust_obstack_chunk *prev = chunk->prev;
task->free(chunk);
chunk = prev;
assert(chunk);
}
}
void *
rust_obstack::mark() {
return chunk ? chunk->mark() : NULL;
}
<commit_msg>rt: Include rust_shape.h in rust_obstack.cpp and remove the duplicate DPRINT() macro<commit_after>// Object stacks, used in lieu of dynamically-sized frames.
#include <algorithm>
#include <cassert>
#include <cstdlib>
#include <iostream>
#include <new>
#include <stdint.h>
#include "rust_internal.h"
#include "rust_obstack.h"
#include "rust_shape.h"
#include "rust_task.h"
// ISAAC, let go of max()!
#ifdef max
#undef max
#endif
//const size_t DEFAULT_CHUNK_SIZE = 4096;
const size_t DEFAULT_CHUNK_SIZE = 500000;
const size_t DEFAULT_ALIGNMENT = 16;
// A single type-tagged allocation in a chunk.
struct rust_obstack_alloc {
size_t len;
const type_desc *tydesc;
uint8_t data[];
rust_obstack_alloc(size_t in_len, const type_desc *in_tydesc)
: len(in_len), tydesc(in_tydesc) {}
};
// A contiguous set of allocations.
struct rust_obstack_chunk {
rust_obstack_chunk *prev;
size_t size;
size_t alen;
size_t pad;
uint8_t data[];
rust_obstack_chunk(rust_obstack_chunk *in_prev, size_t in_size)
: prev(in_prev), size(in_size), alen(0) {}
void *alloc(size_t len, type_desc *tydesc);
bool free(void *ptr);
void *mark();
};
void *
rust_obstack_chunk::alloc(size_t len, type_desc *tydesc) {
alen = align_to(alen, DEFAULT_ALIGNMENT);
if (sizeof(rust_obstack_alloc) + len > size - alen) {
DPRINT("Not enough space, len=%lu!\n", len);
assert(0); // FIXME
return NULL; // Not enough space.
}
rust_obstack_alloc *a = new(data + alen) rust_obstack_alloc(len, tydesc);
alen += sizeof(*a) + len;
return &a->data;
}
bool
rust_obstack_chunk::free(void *ptr) {
uint8_t *p = (uint8_t *)ptr;
if (p < data || p > data + size)
return false;
assert(p <= data + alen);
alen = (size_t)(p - data);
return true;
}
void *
rust_obstack_chunk::mark() {
return data + alen;
}
// Allocates the given number of bytes in a new chunk.
void *
rust_obstack::alloc_new(size_t len, type_desc *tydesc) {
size_t chunk_size = std::max(sizeof(rust_obstack_alloc) + len,
DEFAULT_CHUNK_SIZE);
void *ptr = task->malloc(sizeof(chunk) + chunk_size, "obstack");
DPRINT("making new chunk at %p, len %lu\n", ptr, chunk_size);
chunk = new(ptr) rust_obstack_chunk(chunk, chunk_size);
return chunk->alloc(len, tydesc);
}
rust_obstack::~rust_obstack() {
while (chunk) {
rust_obstack_chunk *prev = chunk->prev;
task->free(chunk);
chunk = prev;
}
}
void *
rust_obstack::alloc(size_t len, type_desc *tydesc) {
if (!chunk)
return alloc_new(len, tydesc);
DPRINT("alloc sz %u", (uint32_t)len);
void *ptr = chunk->alloc(len, tydesc);
ptr = ptr ? ptr : alloc_new(len, tydesc);
return ptr;
}
void
rust_obstack::free(void *ptr) {
if (!ptr)
return;
DPRINT("free ptr %p\n", ptr);
assert(chunk);
while (!chunk->free(ptr)) {
DPRINT("deleting chunk at %p\n", chunk);
rust_obstack_chunk *prev = chunk->prev;
task->free(chunk);
chunk = prev;
assert(chunk);
}
}
void *
rust_obstack::mark() {
return chunk ? chunk->mark() : NULL;
}
<|endoftext|> |
<commit_before>#include "profile.hpp"
#include "../../utils/utils.hpp"
#include <limits>
AnytimeProfile::AnytimeProfile(unsigned int cb, unsigned int tb,
const std::vector<SolutionStream> &stream) {
initbins(cb, tb);
seesolutions(stream);
}
AnytimeProfile::AnytimeProfile(const std::string &path) {
FILE *f = fopen(path.c_str(), "r");
if (!f)
fatalx(errno,"failed to open %s for reading", path.c_str());
read(f);
fclose(f);
}
AnytimeProfile::AnytimeProfile(FILE *in) {
read(in);
}
void AnytimeProfile::read(FILE *in) {
if (fscanf(in, "%u %u\n", &ncost, &ntime) != 2)
fatal("failed to read number of bins");
if (fscanf(in, "%lg %lg\n", &mincost, &maxcost) != 2)
fatal("failed to read min and max cost");
if (fscanf(in, "%lg %lg\n", &mintime, &maxtime) != 2)
fatal("failed to read min and max time");
initbins(ncost, ntime);
for (unsigned int i = 0; i < ncost*ntime; i++) {
if (fscanf(in, "%u\n", &qtcounts[i]) != 1)
fatal("failed to read %uth qtcount", i);
}
for (unsigned int i = 0; i < ncost*ncost*ntime; i++) {
if (fscanf(in, "%u\n", &qqtcounts[i]) != 1)
fatal("failed to read the %uth qqtcount");
}
for (unsigned int i = 0; i < ncost*ncost*ntime; i++) {
if (fscanf(in, "%lg\n", &qqtprobs[i]) != 1)
fatal("failed to read the %uth qqtprob");
}
}
void AnytimeProfile::save(FILE *out) const {
fprintf(out, "%u %u\n", ncost, ntime);
fprintf(out, "%g %g\n", mincost, maxcost);
fprintf(out, "%g %g\n", mintime, maxtime);
for (unsigned int i = 0; i < ncost*ntime; i++)
fprintf(out, "%u\n", qtcounts[i]);
for (unsigned int i = 0; i < ncost*ncost*ntime; i++)
fprintf(out, "%u\n", qqtcounts[i]);
for (unsigned int i = 0; i < ncost*ncost*ntime; i++)
fprintf(out, "%15.15g\n", qqtprobs[i]);
}
void AnytimeProfile::initbins(unsigned int cb, unsigned int tb) {
ncost = cb;
ntime = tb;
qtcounts.resize(ncost*ntime, 0);
qqtcounts.resize(ncost*ncost*ntime, 0);
qqtprobs.resize(ncost*ncost*ntime, 0);
}
void AnytimeProfile::seesolutions(const std::vector<SolutionStream> &streams) {
getextents(streams);
countsolutions(streams);
mkprobs();
}
void AnytimeProfile::getextents(const std::vector<SolutionStream> &streams) {
mintime = std::numeric_limits<double>::infinity();
maxtime = -std::numeric_limits<double>::infinity();
mincost = std::numeric_limits<double>::infinity();
maxcost = -std::numeric_limits<double>::infinity();
for (auto stream = streams.begin(); stream != streams.end(); stream++) {
for (auto sol = stream->begin(); sol != stream->end(); sol++) {
if (sol->cost < mincost)
mincost = sol->cost;
if (sol->cost > maxcost)
maxcost = sol->cost;
if (sol->time < mintime)
mintime = sol->time;
if (sol->time > maxtime)
maxtime = sol->time;
}
}
}
void AnytimeProfile::countsolutions(const std::vector<SolutionStream> &streams) {
for (auto s = streams.begin(); s != streams.end(); s++) {
const SolutionStream &stream = *s;
for (unsigned int i = 0; i < stream.size(); i++) {
unsigned int qi = costbin(stream[i].cost);
unsigned int curq = qi;
unsigned int curdt = 0;
for (unsigned int j = i+1; j < stream.size(); j++) {
assert(stream[j].time > stream[i].time);
assert(stream[j].cost < stream[i].cost);
unsigned int nextq = costbin(stream[j].cost);
unsigned int nextdt = timebin(stream[j].time - stream[i].time);
for (unsigned int dt = curdt; dt < nextdt; dt++) {
qtcounts[qtindex(qi, dt)]++;
qqtcounts[qqtindex(curq, qi, dt)]++;
}
curq = nextq;
curdt = nextdt;
}
for (unsigned int dt = curdt; dt < ntime; dt++) {
qtcounts[qtindex(qi, dt)]++;
qqtcounts[qqtindex(curq, qi, dt)]++;
}
}
}
}
void AnytimeProfile::mkprobs() {
double small = std::numeric_limits<double>::infinity();
for (unsigned int qi = 0; qi < ncost; qi++) {
for (unsigned int dt = 0; dt < ntime; dt++) {
unsigned int n = qtcounts[qtindex(qi, dt)];
if (n == 0)
continue;
for (unsigned int qj = 0; qj < ncost; qj++) {
unsigned int i = qqtindex(qj, qi, dt);
unsigned int m = qqtcounts[i];
// solutions must be improving.
assert (qj <= qi || m == 0);
qqtprobs[i] = m / (double) n;
if (qqtprobs[i] > 0 && qqtprobs[i] < small)
small = qqtprobs[i];
}
}
}
// smoothing
printf("Adding %g for smoothing\n", small/2);
for (unsigned int qi = 0; qi < ncost; qi++) {
for (unsigned int dt = 0; dt < ntime; dt++) {
for (unsigned int qj = 0; qj <= qi; qj++) {
qqtprobs[qqtindex(qj, qi, dt)] += small/2;
}
}
}
// normalize
for (unsigned int qi = 0; qi < ncost; qi++) {
for (unsigned int dt = 0; dt < ntime; dt++) {
double sum = 0;
for (unsigned int qj = 0; qj < ncost; qj++)
sum += qqtprobs[qqtindex(qj, qi, dt)];
assert (sum > 0);
for (unsigned int qj = 0; qj <= qi; qj++)
qqtprobs[qqtindex(qj, qi, dt)] /= sum;
// Some sanity checks.
sum = 0;
for (unsigned int qj = 0; qj <= qi; qj++) {
sum += qqtprobs[qqtindex(qj, qi, dt)];
assert (qj <= qi || qqtprobs[qqtindex(qj, qi, dt)] == 0);
}
assert (sum > 1-1e-8);
assert (sum < 1+1e-8);
}
}
}
AnytimeMonitor::AnytimeMonitor(const AnytimeProfile &p, double fw, double tw) :
prof(p), wf(fw), wt(tw),
qwidth((p.maxcost - p.mincost)/p.ncost),
twidth((p.maxtime - p.mintime)/p.ntime) {
policy.resize(prof.ncost*prof.ntime);
value.resize(prof.ncost*prof.ntime);
seen.resize(prof.ncost*prof.ntime, false);
// max time
for (unsigned int q = 0; q < prof.ncost; q++) {
unsigned int i = index(q, prof.ntime-1);
value[i] = binutil(q, prof.ntime-1);
seen[i] = true;
policy[i] = true;
}
// min cost
for (unsigned int t = 0; t < prof.ntime; t++) {
unsigned int i = index(0, t);
value[i] = binutil(0, t);
seen[i] = true;
policy[i] = true;
}
for (unsigned int q1 = 1; q1 < prof.ncost; q1++) {
for (long t = prof.ntime-2; t >= 0; t--) {
double vgo = 0;
double psum = 0;
for (long q2 = q1; q2 >= 0; q2--) {
double prob = prof.binprob(q2, q1, 1);
psum += prob;
double val = value[index(q2, t+1)];
assert (seen[index(q2, t+1)]);
vgo += prob*val;
}
assert (psum > 1 - 1e-8);
assert (psum < 1 + 1e-8);
if (psum == 0)
vgo = -std::numeric_limits<double>::infinity();
double vstop = binutil(q1, t);
unsigned int i = index(q1, t);
if (vgo > vstop) {
value[i] = vgo;
policy[i] = false;
} else {
value[i] = vstop;
policy[i] = true;
}
seen[i] = true;
}
}
}
<commit_msg>search: weaken an assert.<commit_after>#include "profile.hpp"
#include "../../utils/utils.hpp"
#include <limits>
AnytimeProfile::AnytimeProfile(unsigned int cb, unsigned int tb,
const std::vector<SolutionStream> &stream) {
initbins(cb, tb);
seesolutions(stream);
}
AnytimeProfile::AnytimeProfile(const std::string &path) {
FILE *f = fopen(path.c_str(), "r");
if (!f)
fatalx(errno,"failed to open %s for reading", path.c_str());
read(f);
fclose(f);
}
AnytimeProfile::AnytimeProfile(FILE *in) {
read(in);
}
void AnytimeProfile::read(FILE *in) {
if (fscanf(in, "%u %u\n", &ncost, &ntime) != 2)
fatal("failed to read number of bins");
if (fscanf(in, "%lg %lg\n", &mincost, &maxcost) != 2)
fatal("failed to read min and max cost");
if (fscanf(in, "%lg %lg\n", &mintime, &maxtime) != 2)
fatal("failed to read min and max time");
initbins(ncost, ntime);
for (unsigned int i = 0; i < ncost*ntime; i++) {
if (fscanf(in, "%u\n", &qtcounts[i]) != 1)
fatal("failed to read %uth qtcount", i);
}
for (unsigned int i = 0; i < ncost*ncost*ntime; i++) {
if (fscanf(in, "%u\n", &qqtcounts[i]) != 1)
fatal("failed to read the %uth qqtcount");
}
for (unsigned int i = 0; i < ncost*ncost*ntime; i++) {
if (fscanf(in, "%lg\n", &qqtprobs[i]) != 1)
fatal("failed to read the %uth qqtprob");
}
}
void AnytimeProfile::save(FILE *out) const {
fprintf(out, "%u %u\n", ncost, ntime);
fprintf(out, "%g %g\n", mincost, maxcost);
fprintf(out, "%g %g\n", mintime, maxtime);
for (unsigned int i = 0; i < ncost*ntime; i++)
fprintf(out, "%u\n", qtcounts[i]);
for (unsigned int i = 0; i < ncost*ncost*ntime; i++)
fprintf(out, "%u\n", qqtcounts[i]);
for (unsigned int i = 0; i < ncost*ncost*ntime; i++)
fprintf(out, "%15.15g\n", qqtprobs[i]);
}
void AnytimeProfile::initbins(unsigned int cb, unsigned int tb) {
ncost = cb;
ntime = tb;
qtcounts.resize(ncost*ntime, 0);
qqtcounts.resize(ncost*ncost*ntime, 0);
qqtprobs.resize(ncost*ncost*ntime, 0);
}
void AnytimeProfile::seesolutions(const std::vector<SolutionStream> &streams) {
getextents(streams);
countsolutions(streams);
mkprobs();
}
void AnytimeProfile::getextents(const std::vector<SolutionStream> &streams) {
mintime = std::numeric_limits<double>::infinity();
maxtime = -std::numeric_limits<double>::infinity();
mincost = std::numeric_limits<double>::infinity();
maxcost = -std::numeric_limits<double>::infinity();
for (auto stream = streams.begin(); stream != streams.end(); stream++) {
for (auto sol = stream->begin(); sol != stream->end(); sol++) {
if (sol->cost < mincost)
mincost = sol->cost;
if (sol->cost > maxcost)
maxcost = sol->cost;
if (sol->time < mintime)
mintime = sol->time;
if (sol->time > maxtime)
maxtime = sol->time;
}
}
}
void AnytimeProfile::countsolutions(const std::vector<SolutionStream> &streams) {
for (auto s = streams.begin(); s != streams.end(); s++) {
const SolutionStream &stream = *s;
for (unsigned int i = 0; i < stream.size(); i++) {
unsigned int qi = costbin(stream[i].cost);
unsigned int curq = qi;
unsigned int curdt = 0;
for (unsigned int j = i+1; j < stream.size(); j++) {
assert(stream[j].time > stream[i].time);
assert(stream[j].cost <= stream[i].cost);
unsigned int nextq = costbin(stream[j].cost);
unsigned int nextdt = timebin(stream[j].time - stream[i].time);
for (unsigned int dt = curdt; dt < nextdt; dt++) {
qtcounts[qtindex(qi, dt)]++;
qqtcounts[qqtindex(curq, qi, dt)]++;
}
curq = nextq;
curdt = nextdt;
}
for (unsigned int dt = curdt; dt < ntime; dt++) {
qtcounts[qtindex(qi, dt)]++;
qqtcounts[qqtindex(curq, qi, dt)]++;
}
}
}
}
void AnytimeProfile::mkprobs() {
double small = std::numeric_limits<double>::infinity();
for (unsigned int qi = 0; qi < ncost; qi++) {
for (unsigned int dt = 0; dt < ntime; dt++) {
unsigned int n = qtcounts[qtindex(qi, dt)];
if (n == 0)
continue;
for (unsigned int qj = 0; qj < ncost; qj++) {
unsigned int i = qqtindex(qj, qi, dt);
unsigned int m = qqtcounts[i];
// solutions must be improving.
assert (qj <= qi || m == 0);
qqtprobs[i] = m / (double) n;
if (qqtprobs[i] > 0 && qqtprobs[i] < small)
small = qqtprobs[i];
}
}
}
// smoothing
printf("Adding %g for smoothing\n", small/2);
for (unsigned int qi = 0; qi < ncost; qi++) {
for (unsigned int dt = 0; dt < ntime; dt++) {
for (unsigned int qj = 0; qj <= qi; qj++) {
qqtprobs[qqtindex(qj, qi, dt)] += small/2;
}
}
}
// normalize
for (unsigned int qi = 0; qi < ncost; qi++) {
for (unsigned int dt = 0; dt < ntime; dt++) {
double sum = 0;
for (unsigned int qj = 0; qj < ncost; qj++)
sum += qqtprobs[qqtindex(qj, qi, dt)];
assert (sum > 0);
for (unsigned int qj = 0; qj <= qi; qj++)
qqtprobs[qqtindex(qj, qi, dt)] /= sum;
// Some sanity checks.
sum = 0;
for (unsigned int qj = 0; qj <= qi; qj++) {
sum += qqtprobs[qqtindex(qj, qi, dt)];
assert (qj <= qi || qqtprobs[qqtindex(qj, qi, dt)] == 0);
}
assert (sum > 1-1e-8);
assert (sum < 1+1e-8);
}
}
}
AnytimeMonitor::AnytimeMonitor(const AnytimeProfile &p, double fw, double tw) :
prof(p), wf(fw), wt(tw),
qwidth((p.maxcost - p.mincost)/p.ncost),
twidth((p.maxtime - p.mintime)/p.ntime) {
policy.resize(prof.ncost*prof.ntime);
value.resize(prof.ncost*prof.ntime);
seen.resize(prof.ncost*prof.ntime, false);
// max time
for (unsigned int q = 0; q < prof.ncost; q++) {
unsigned int i = index(q, prof.ntime-1);
value[i] = binutil(q, prof.ntime-1);
seen[i] = true;
policy[i] = true;
}
// min cost
for (unsigned int t = 0; t < prof.ntime; t++) {
unsigned int i = index(0, t);
value[i] = binutil(0, t);
seen[i] = true;
policy[i] = true;
}
for (unsigned int q1 = 1; q1 < prof.ncost; q1++) {
for (long t = prof.ntime-2; t >= 0; t--) {
double vgo = 0;
double psum = 0;
for (long q2 = q1; q2 >= 0; q2--) {
double prob = prof.binprob(q2, q1, 1);
psum += prob;
double val = value[index(q2, t+1)];
assert (seen[index(q2, t+1)]);
vgo += prob*val;
}
assert (psum > 1 - 1e-8);
assert (psum < 1 + 1e-8);
if (psum == 0)
vgo = -std::numeric_limits<double>::infinity();
double vstop = binutil(q1, t);
unsigned int i = index(q1, t);
if (vgo > vstop) {
value[i] = vgo;
policy[i] = false;
} else {
value[i] = vstop;
policy[i] = true;
}
seen[i] = true;
}
}
}
<|endoftext|> |
<commit_before>/*************************************************************************
*
* OpenOffice.org - a multi-platform office productivity suite
*
* $RCSfile: commoncontrol.cxx,v $
*
* $Revision: 1.8 $
*
* last change: $Author: kz $ $Date: 2006-12-13 11:57:02 $
*
* 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_extensions.hxx"
#ifndef _EXTENSIONS_PROPCTRLR_COMMONCONTROL_HXX_
#include "commoncontrol.hxx"
#endif
#ifndef _EXTENSIONS_PROPCTRLR_PCRCOMMON_HXX_
#include "pcrcommon.hxx"
#endif
#ifndef _TOOLS_DEBUG_HXX
#include <tools/debug.hxx>
#endif
#ifndef _SV_COMBOBOX_HXX
#include <vcl/combobox.hxx>
#endif
#ifndef _TOOLKIT_HELPER_VCLUNOHELPER_HXX_
#include <toolkit/helper/vclunohelper.hxx>
#endif
//............................................................................
namespace pcr
{
//............................................................................
/** === begin UNO using === **/
using ::com::sun::star::uno::RuntimeException;
using ::com::sun::star::uno::Reference;
using ::com::sun::star::inspection::XPropertyControlContext;
using ::com::sun::star::awt::XWindow;
using ::com::sun::star::uno::Exception;
using ::com::sun::star::inspection::XPropertyControl;
/** === end UNO using === **/
//==================================================================
//= ControlHelper
//==================================================================
//------------------------------------------------------------------
ControlHelper::ControlHelper( Window* _pControlWindow, sal_Int16 _nControlType, XPropertyControl& _rAntiImpl, IModifyListener* _pModifyListener )
:m_pControlWindow( _pControlWindow )
,m_nControlType( _nControlType )
,m_rAntiImpl( _rAntiImpl )
,m_pModifyListener( _pModifyListener )
,m_bModified( sal_False )
{
DBG_ASSERT( m_pControlWindow != NULL, "ControlHelper::ControlHelper: invalid window!" );
}
//------------------------------------------------------------------
ControlHelper::~ControlHelper()
{
}
//--------------------------------------------------------------------
::sal_Int16 SAL_CALL ControlHelper::getControlType() throw (RuntimeException)
{
return m_nControlType;
}
//--------------------------------------------------------------------
Reference< XPropertyControlContext > SAL_CALL ControlHelper::getControlContext() throw (RuntimeException)
{
return m_xContext;
}
//--------------------------------------------------------------------
void SAL_CALL ControlHelper::setControlContext( const Reference< XPropertyControlContext >& _controlcontext ) throw (RuntimeException)
{
m_xContext = _controlcontext;
}
//--------------------------------------------------------------------
Reference< XWindow > SAL_CALL ControlHelper::getControlWindow() throw (RuntimeException)
{
return VCLUnoHelper::GetInterface( m_pControlWindow );
}
//--------------------------------------------------------------------
::sal_Bool SAL_CALL ControlHelper::isModified( ) throw (RuntimeException)
{
return m_bModified;
}
//--------------------------------------------------------------------
void SAL_CALL ControlHelper::notifyModifiedValue( ) throw (RuntimeException)
{
if ( isModified() && m_xContext.is() )
{
try
{
m_xContext->valueChanged( &m_rAntiImpl );
m_bModified = sal_False;
}
catch( const Exception& e )
{
#if OSL_DEBUG_LEVEL > 0
::rtl::OString sMessage( "ControlHelper::notifyModifiedValue: caught an exception!\n" );
sMessage += "message:\n";
sMessage += ::rtl::OString( e.Message.getStr(), e.Message.getLength(), osl_getThreadTextEncoding() );
OSL_ENSURE( false, sMessage );
#else
e; // make compiler happy
#endif
}
}
}
//------------------------------------------------------------------
void SAL_CALL ControlHelper::dispose()
{
DELETEZ( m_pControlWindow );
}
//------------------------------------------------------------------
void ControlHelper::autoSizeWindow()
{
OSL_PRECOND( m_pControlWindow, "ControlHelper::autoSizeWindow: no window!" );
if ( !m_pControlWindow )
return;
ComboBox aComboBox(m_pControlWindow, WB_DROPDOWN);
aComboBox.SetPosSizePixel(Point(0,0), Size(100,100));
m_pControlWindow->SetSizePixel(aComboBox.GetSizePixel());
// TODO/UNOize: why do the controls this themselves? Shouldn't this be the task
// of the the browser listbox/line?
}
//------------------------------------------------------------------
void ControlHelper::impl_activateNextControl_nothrow() const
{
try
{
if ( m_xContext.is() )
m_xContext->activateNextControl( const_cast< XPropertyControl* >( &m_rAntiImpl ) );
}
catch( const Exception& e )
{
#if OSL_DEBUG_LEVEL > 0
::rtl::OString sMessage( "ControlHelper::impl_activateNextControl_nothrow: caught an exception!\n" );
sMessage += "message:\n";
sMessage += ::rtl::OString( e.Message.getStr(), e.Message.getLength(), osl_getThreadTextEncoding() );
OSL_ENSURE( false, sMessage );
#else
e; // make compiler happy
#endif
}
}
//------------------------------------------------------------------
bool ControlHelper::handlePreNotify(NotifyEvent& rNEvt)
{
if (EVENT_KEYINPUT == rNEvt.GetType())
{
const KeyCode& aKeyCode = rNEvt.GetKeyEvent()->GetKeyCode();
sal_uInt16 nKey = aKeyCode.GetCode();
if (nKey == KEY_RETURN && !aKeyCode.IsShift())
{
LoseFocusHdl(m_pControlWindow);
impl_activateNextControl_nothrow();
return true;
}
}
return false;
}
//------------------------------------------------------------------
IMPL_LINK( ControlHelper, ModifiedHdl, Window*, /*_pWin*/ )
{
if ( m_pModifyListener )
m_pModifyListener->modified();
return 0;
}
//------------------------------------------------------------------
IMPL_LINK( ControlHelper, GetFocusHdl, Window*, /*_pWin*/ )
{
try
{
if ( m_xContext.is() )
m_xContext->focusGained( &m_rAntiImpl );
}
catch( const Exception& e )
{
#if OSL_DEBUG_LEVEL > 0
::rtl::OString sMessage( "ControlHelper, GetFocusHdl: caught an exception!\n" );
sMessage += "message:\n";
sMessage += ::rtl::OString( e.Message.getStr(), e.Message.getLength(), osl_getThreadTextEncoding() );
OSL_ENSURE( false, sMessage );
#else
e; // make compiler happy
#endif
}
return 0;
}
//------------------------------------------------------------------
IMPL_LINK( ControlHelper, LoseFocusHdl, Window*, /*_pWin*/ )
{
// TODO/UNOize: should this be outside the default control's implementations? If somebody
// has an own control implementation, which does *not* do this - would this be allowed?
// If not, then we must move this logic out of here.
notifyModifiedValue();
return 0;
}
//............................................................................
} // namespace pcr
//............................................................................
<commit_msg>INTEGRATION: CWS dba23a (1.8.44); FILE MERGED 2007/03/21 13:20:16 fs 1.8.44.2: #i73260# 2007/02/22 11:27:16 fs 1.8.44.1: #i73260# misc warning issues<commit_after>/*************************************************************************
*
* OpenOffice.org - a multi-platform office productivity suite
*
* $RCSfile: commoncontrol.cxx,v $
*
* $Revision: 1.9 $
*
* last change: $Author: kz $ $Date: 2007-05-10 10:46:51 $
*
* 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_extensions.hxx"
#ifndef _EXTENSIONS_PROPCTRLR_COMMONCONTROL_HXX_
#include "commoncontrol.hxx"
#endif
#ifndef _EXTENSIONS_PROPCTRLR_PCRCOMMON_HXX_
#include "pcrcommon.hxx"
#endif
#ifndef _TOOLS_DEBUG_HXX
#include <tools/debug.hxx>
#endif
#ifndef TOOLS_DIAGNOSE_EX_H
#include <tools/diagnose_ex.h>
#endif
#ifndef _SV_COMBOBOX_HXX
#include <vcl/combobox.hxx>
#endif
#ifndef _TOOLKIT_HELPER_VCLUNOHELPER_HXX_
#include <toolkit/helper/vclunohelper.hxx>
#endif
//............................................................................
namespace pcr
{
//............................................................................
/** === begin UNO using === **/
using ::com::sun::star::uno::RuntimeException;
using ::com::sun::star::uno::Reference;
using ::com::sun::star::inspection::XPropertyControlContext;
using ::com::sun::star::awt::XWindow;
using ::com::sun::star::uno::Exception;
using ::com::sun::star::inspection::XPropertyControl;
/** === end UNO using === **/
//==================================================================
//= ControlHelper
//==================================================================
//------------------------------------------------------------------
ControlHelper::ControlHelper( Window* _pControlWindow, sal_Int16 _nControlType, XPropertyControl& _rAntiImpl, IModifyListener* _pModifyListener )
:m_pControlWindow( _pControlWindow )
,m_nControlType( _nControlType )
,m_rAntiImpl( _rAntiImpl )
,m_pModifyListener( _pModifyListener )
,m_bModified( sal_False )
{
DBG_ASSERT( m_pControlWindow != NULL, "ControlHelper::ControlHelper: invalid window!" );
}
//------------------------------------------------------------------
ControlHelper::~ControlHelper()
{
}
//--------------------------------------------------------------------
::sal_Int16 SAL_CALL ControlHelper::getControlType() throw (RuntimeException)
{
return m_nControlType;
}
//--------------------------------------------------------------------
Reference< XPropertyControlContext > SAL_CALL ControlHelper::getControlContext() throw (RuntimeException)
{
return m_xContext;
}
//--------------------------------------------------------------------
void SAL_CALL ControlHelper::setControlContext( const Reference< XPropertyControlContext >& _controlcontext ) throw (RuntimeException)
{
m_xContext = _controlcontext;
}
//--------------------------------------------------------------------
Reference< XWindow > SAL_CALL ControlHelper::getControlWindow() throw (RuntimeException)
{
return VCLUnoHelper::GetInterface( m_pControlWindow );
}
//--------------------------------------------------------------------
::sal_Bool SAL_CALL ControlHelper::isModified( ) throw (RuntimeException)
{
return m_bModified;
}
//--------------------------------------------------------------------
void SAL_CALL ControlHelper::notifyModifiedValue( ) throw (RuntimeException)
{
if ( isModified() && m_xContext.is() )
{
try
{
m_xContext->valueChanged( &m_rAntiImpl );
m_bModified = sal_False;
}
catch( const Exception& )
{
DBG_UNHANDLED_EXCEPTION();
}
}
}
//------------------------------------------------------------------
void SAL_CALL ControlHelper::dispose()
{
DELETEZ( m_pControlWindow );
}
//------------------------------------------------------------------
void ControlHelper::autoSizeWindow()
{
OSL_PRECOND( m_pControlWindow, "ControlHelper::autoSizeWindow: no window!" );
if ( !m_pControlWindow )
return;
ComboBox aComboBox(m_pControlWindow, WB_DROPDOWN);
aComboBox.SetPosSizePixel(Point(0,0), Size(100,100));
m_pControlWindow->SetSizePixel(aComboBox.GetSizePixel());
// TODO/UNOize: why do the controls this themselves? Shouldn't this be the task
// of the the browser listbox/line?
}
//------------------------------------------------------------------
void ControlHelper::impl_activateNextControl_nothrow() const
{
try
{
if ( m_xContext.is() )
m_xContext->activateNextControl( const_cast< XPropertyControl* >( &m_rAntiImpl ) );
}
catch( const Exception& )
{
DBG_UNHANDLED_EXCEPTION();
}
}
//------------------------------------------------------------------
bool ControlHelper::handlePreNotify(NotifyEvent& rNEvt)
{
if (EVENT_KEYINPUT == rNEvt.GetType())
{
const KeyCode& aKeyCode = rNEvt.GetKeyEvent()->GetKeyCode();
sal_uInt16 nKey = aKeyCode.GetCode();
if (nKey == KEY_RETURN && !aKeyCode.IsShift())
{
LoseFocusHdl(m_pControlWindow);
impl_activateNextControl_nothrow();
return true;
}
}
return false;
}
//------------------------------------------------------------------
IMPL_LINK( ControlHelper, ModifiedHdl, Window*, /*_pWin*/ )
{
if ( m_pModifyListener )
m_pModifyListener->modified();
return 0;
}
//------------------------------------------------------------------
IMPL_LINK( ControlHelper, GetFocusHdl, Window*, /*_pWin*/ )
{
try
{
if ( m_xContext.is() )
m_xContext->focusGained( &m_rAntiImpl );
}
catch( const Exception& )
{
DBG_UNHANDLED_EXCEPTION();
}
return 0;
}
//------------------------------------------------------------------
IMPL_LINK( ControlHelper, LoseFocusHdl, Window*, /*_pWin*/ )
{
// TODO/UNOize: should this be outside the default control's implementations? If somebody
// has an own control implementation, which does *not* do this - would this be allowed?
// If not, then we must move this logic out of here.
notifyModifiedValue();
return 0;
}
//............................................................................
} // namespace pcr
//............................................................................
<|endoftext|> |
<commit_before>/*
* Assignment Title
* Full Name - ID Numbers
*
* Short problem description
*
*/
#include <iostream>
#include <cassert>
using namespace std;
// Function Declarations
void test();
// Calculates the positive square root using the quadratic formula
// Assumes the answer is real, that is: b^2 >= 4ac
// a - the x^2 term. The function assumes a is not zero
// b - the x term.
// c - the 1 term.
// return - the positive root of ax^2 + bx + c
double quadratic(double a, double b, double c);
// Calculates the distance between two points
// x1 - The x value of the first point
// y1 - The y value of the first point
// x2 - The x value of the second point
// y2 - The y value of the second point
// return - the distance between (x1,y1) and (x2,y2)
double distance(double x1, double y1, double x2, double y2);
int main() {
// Statements
test();
// Exit Program
return 0;
}
// Tests
void test() {
// test quadratic
assert(quadratic(1,2,-15),3);
assert(quadratic(1,6,8),-2);
// Write at least 3 additional tests here
// test distance
assert(distance(5,2,2,-2),5);
assert(distance(-5,13,-10,1),13);
// Write at least 3 additional tests here
}
// Function Definitions
double distance(double x1, double y1, double x2, double y2) {
return 0; // calculate your answer here
}
double quadratic(double a, double b, double c) {
return 0; // calculate your answer here
}
<commit_msg>fixed assert to take booleans<commit_after>/*
* Assignment Title
* Full Name - ID Numbers
*
* Short problem description
*
*/
#include <iostream>
#include <cassert>
using namespace std;
// Function Declarations
void test();
// Calculates the positive square root using the quadratic formula
// Assumes the answer is real, that is: b^2 >= 4ac
// a - the x^2 term. The function assumes a is not zero
// b - the x term.
// c - the 1 term.
// return - the positive root of ax^2 + bx + c
double quadratic(double a, double b, double c);
// Calculates the distance between two points
// x1 - The x value of the first point
// y1 - The y value of the first point
// x2 - The x value of the second point
// y2 - The y value of the second point
// return - the distance between (x1,y1) and (x2,y2)
double distance(double x1, double y1, double x2, double y2);
int main() {
// Statements
test();
// Exit Program
return 0;
}
// Tests
void test() {
// test quadratic
assert(quadratic(1,2,-15) == 3);
assert(quadratic(1,6,8) == -2);
// Write at least 3 additional tests here
// test distance
assert(distance(5,2,2,-2) == 5);
assert(distance(-5,13,-10,1) == 13);
// Write at least 3 additional tests here
}
// Function Definitions
double distance(double x1, double y1, double x2, double y2) {
return 0; // calculate your answer here
}
double quadratic(double a, double b, double c) {
return 0; // calculate your answer here
}
<|endoftext|> |
<commit_before>#ifndef HMLIB_ALIGNEDMEMORY_INC
#define HMLIB_ALIGNEDMEMORY_INC 100
#include<memory>
namespace hmLib{
template<typename T, std::size_t StackSize>
struct aligned_stack final{
using this_type = aligned_stack<T,StackSize>;
using pointer = T*;
using const_pointer = const T*;
public:
aligned_stack() = default;
aligned_stack(this_type&&) = delete;
this_type& operator=(this_type&&) = delete;
aligned_stack(const this_type&) = delete;
this_type& operator=(const this_type&) = delete;
~aligned_stack() = default;
public: //common functions for aligned memory classes
operator bool()const{return true;}
pointer begin(){return static_cast<pointer>(static_cast<void*>(Buf));}
pointer end(){return static_cast<pointer>(static_cast<void*>(Buf))+StackSize;}
const_pointer begin()const{return cbegin();}
const_pointer end()const{return cend();}
const_pointer cbegin()const{return static_cast<pointer>(static_cast<void*>(Buf));}
const_pointer cend()const{return static_cast<pointer>(static_cast<void*>(Buf))+StackSize;}
std::size_t size()const{return static_size();}
public:
static std::size_t static_size(){return StackSize;}
private:
alignas(alignof(T)) unsigned char Buf[sizeof(T)*StackSize];
};
template<typename T>
struct aligned_heap final{
using this_type = aligned_heap<T>;
using pointer = T*;
using const_pointer = const T*;
public:
aligned_heap()noexcept:Ptr(nullptr),Beg(nullptr),End(nullptr){}
explicit aligned_heap(std::size_t n):aligned_heap(){
allocate(n);
}
aligned_heap(this_type&& other):aligned_heap(){
swap(other);
}
this_type& operator=(this_type&& other){
if(this != &other){
swap(other);
}
}
aligned_heap(const this_type&)=delete;
this_type& operator=(const this_type&)=delete;
~aligned_heap()noexcept{deallocate();}
public: //common functions for aligned memory classes
operator bool()const{return Beg!=nullptr;}
pointer begin(){return Beg;}
pointer end(){return End;}
const_pointer begin()const{return cbegin();}
const_pointer end()const{return cend();}
const_pointer cbegin()const{return Beg;}
const_pointer cend()const{return End;}
std::size_t size()const{return End-Beg;}
public:
void allocate(unsigned int n){
deallocate();
std::size_t bufsize = sizeof(T)*n + alignof(T);
Ptr = new unsigned char[bufsize];
void* vPtr = Ptr;
std::align(alignof(T), sizeof(T), vPtr,bufsize);
Beg = static_cast<pointer>(vPtr);
if(Beg)End = Beg + n;
}
void deallocate()noexcept{
if(Ptr){
delete[] Ptr;
Ptr = nullptr;
Beg = nullptr;
End = nullptr;
}
}
void swap(this_type& other){
std::swap(Ptr, other.Ptr);
std::swap(Beg, other.Beg);
std::swap(End, other.End);
}
private:
unsigned char* Ptr;
pointer Beg;
pointer End;
};
template<typename T, unsigned int SOOSize>
struct aligned_soo final{
using this_type = aligned_soo<T,SOOSize>;
using pointer = T*;
using const_pointer = const T*;
public:
aligned_soo()noexcept:Ptr(nullptr),Beg(nullptr),End(nullptr){}
explicit aligned_soo(std::size_t n):soo_aligned_memory(){
allocate(n);
}
aligned_soo(this_type&&) = delete;
this_type& operator=(this_type&&) = delete;
soo_aligned_memory(const this_type&) = delete;
this_type& operator=(const this_type&) = delete;
~soo_aligned_memory(){deallocate();}
public: //common functions for aligned memory classes
operator bool()const{return Beg!=nullptr;}
pointer begin(){return Beg;}
pointer end(){return End;}
const_pointer begin()const{return cbegin();}
const_pointer end()const{return cend();}
const_pointer cbegin()const{return Beg;}
const_pointer cend()const{return End;}
std::size_t size()const{return End-Beg;}
public:
void allocate(unsigned int n){
if(on_heap()){
delete[] Ptr;
Ptr = nullptr;
}
if(n>soo_size()){
std::size_t bufsize = sizeof(T)*n + alignof(T);
Ptr = new unsigned char[bufsize];
void* vPtr = Ptr;
std::align(alignof(T), sizeof(T), vPtr,bufsize);
Beg = static_cast<pointer>(vPtr);
if(Beg)End = Beg + n;
}else{
Beg = static_cast<pointer>(static_cast<void*>(Ptr));
End = Beg + n;
}
}
void deallocate()noexcept{
if(on_heap()){
delete[] Ptr;
Ptr = nullptr;
}
Beg = nullptr;
End = nullptr;
}
bool try_move(this_type&& other)noexcept{
if(!other.on_heap()) return true;
if(on_heap())delete[] Ptr;
Ptr = other.Ptr;
Beg = other.Beg;
End = other.End;
other.Ptr = nullptr;
other.Beg = nullptr;
other.End = nullptr;
return false;
}
bool try_swap(this_type& other)noexcept{
if(!on_heap() || !other.on_heap()) return true;
std::swap(Ptr, other.Ptr);
std::swap(Beg, other.Beg);
std::swap(End, other.End);
return false;
}
bool on_heap()noexcept const{return Ptr!=nullptr;}
static std::size_t soo_size(){return SOOSize;}
private:
alignas(alignof(T)) unsigned char Buf[sizeof(T)*SOOSize];
unsigned char* Ptr;
pointer Beg;
pointer End;
};
}
#
#endif
<commit_msg>Remove aligned_memory; it just confuse to use align<commit_after><|endoftext|> |
<commit_before>/*
* Copyright (c) 2008 James Molloy, Jörg Pfähler, Matthew Iselin
*
* Permission to use, copy, modify, and distribute this software for any
* purpose with or without fee is hereby granted, provided that the above
* copyright notice and this permission notice appear in all copies.
*
* THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
* WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
* MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
* ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
* WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
* ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
* OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
*/
#include "RoutingTable.h"
#include <config/Config.h>
#include <machine/DeviceHashTree.h>
#include <LockGuard.h>
RoutingTable RoutingTable::m_Instance;
RoutingTable::RoutingTable() : m_bHasRoutes(false), m_TableLock(false)
{
}
RoutingTable::~RoutingTable()
{
}
void RoutingTable::Add(Type type, IpAddress dest, IpAddress subIp, String meta, Network *card)
{
LockGuard<Mutex> guard(m_TableLock);
// Add to the hash tree, if not already done. This ensures the loopback
// device is definitely available as an interface.
DeviceHashTree::instance().add(card);
// Add the route to the database directly
String str;
size_t hash = DeviceHashTree::instance().getHash(card);
str.sprintf("INSERT INTO routes (ipaddr, subip, name, type, iface) VALUES (%u, %u, '%s', %u, %u)", dest.getIp(), subIp.getIp(), static_cast<const char*>(meta), static_cast<int>(type), hash);
Config::Result *pResult = Config::instance().query(str);
if(!pResult->succeeded())
{
ERROR("Routing table query failed: " << pResult->errorMessage());
}
NOTICE("RoutingTable: Adding IP match route for " << dest.toString() << ", sub " << subIp.toString() << ".");
m_bHasRoutes = true;
delete pResult;
}
void RoutingTable::Add(Type type, IpAddress dest, IpAddress subnet, IpAddress subIp, String meta, Network *card)
{
LockGuard<Mutex> guard(m_TableLock);
// Add to the hash tree, if not already done. This ensures the loopback
// device is definitely available as an interface.
DeviceHashTree::instance().add(card);
// Invert the subnet to get an IP range
IpAddress invSubnet(subnet.getIp() ^ 0xFFFFFFFF);
IpAddress bottomOfRange = dest & subnet;
IpAddress topOfRange = (dest & subnet) + invSubnet;
NOTICE("RoutingTable: Adding " << (type == DestSubnetComplement ? "complement of " : "") << "subnet match for range " << bottomOfRange.toString() << " - " << topOfRange.toString());
// Add to the database
String str;
size_t hash = DeviceHashTree::instance().getHash(card);
str.sprintf("INSERT INTO routes (ipstart, ipend, subip, name, type, iface) VALUES (%u, %u, %u, '%s', %u, %u)",
bottomOfRange.getIp(),
topOfRange.getIp(),
subIp.getIp(),
static_cast<const char*>(meta),
static_cast<int>(type),
hash);
Config::Result *pResult = Config::instance().query(str);
if(!pResult->succeeded())
{
ERROR("Routing table query failed: " << pResult->errorMessage());
}
m_bHasRoutes = true;
delete pResult;
}
Network *RoutingTable::route(IpAddress *ip, Config::Result *pResult)
{
// Grab the interface
Network *pCard = dynamic_cast<Network*>(DeviceHashTree::instance().getDevice(pResult->getNum(0, "iface")));
// If we are to perform substitution, do so
Type t = static_cast<Type>(pResult->getNum(0, "type"));
if(t == DestIpSub || t == DestSubnetComplement)
ip->setIp(pResult->getNum(0, "subip"));
// Return the interface to use
delete pResult;
return pCard;
}
Network *RoutingTable::DetermineRoute(IpAddress *ip, bool bGiveDefault)
{
LockGuard<Mutex> guard(m_TableLock);
// Build a query to search for a direct match
String str;
str.sprintf("SELECT * FROM routes WHERE ipaddr=%u", ip->getIp());
Config::Result *pResult = Config::instance().query(str);
if(!pResult->succeeded())
ERROR("Routing table query failed: " << pResult->errorMessage());
else if(pResult->rows())
{
return route(ip, pResult);
}
delete pResult;
// No rows! Try a subnet lookup first, without a complement.
str.sprintf("SELECT * FROM routes WHERE ((ipstart >= %u) AND (ipend <= %u)) AND (type == %u)", ip->getIp(), ip->getIp(), static_cast<int>(DestSubnet));
pResult = Config::instance().query(str);
if(!pResult->succeeded())
ERROR("Routing table query failed: " << pResult->errorMessage());
else if(pResult->rows())
{
return route(ip, pResult);
}
delete pResult;
// Still nothing, try a complement subnet search
str.sprintf("SELECT * FROM routes WHERE (NOT ((ipstart >= %u) AND (ipend <= %u))) AND (type == %u)", ip->getIp(), ip->getIp(), static_cast<int>(DestSubnetComplement));
pResult = Config::instance().query(str);
if(!pResult->succeeded())
ERROR("Routing table query failed: " << pResult->errorMessage());
else if(pResult->rows())
{
return route(ip, pResult);
}
delete pResult;
// Nothing even still, try the default route if we're allowed
if(bGiveDefault)
return DefaultRoute();
// Not even the default route worked!
return 0;
}
Network *RoutingTable::DefaultRoute()
{
// If already locked, will return false, so we don't unlock (DetermineRoute calls this function)
bool bLocked = m_TableLock.tryAcquire();
String str;
str.sprintf("SELECT * FROM routes WHERE name='default'");
Config::Result *pResult = Config::instance().query(str);
if(!pResult->succeeded())
ERROR("Routing table query failed: " << pResult->errorMessage());
else if(pResult->rows())
{
if(bLocked)
m_TableLock.release();
return route(0, pResult);
}
delete pResult;
if(bLocked)
m_TableLock.release();
return 0;
}
<commit_msg>Network: fixed route lookups (again).<commit_after>/*
* Copyright (c) 2008 James Molloy, Jörg Pfähler, Matthew Iselin
*
* Permission to use, copy, modify, and distribute this software for any
* purpose with or without fee is hereby granted, provided that the above
* copyright notice and this permission notice appear in all copies.
*
* THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
* WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
* MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
* ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
* WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
* ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
* OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
*/
#include "RoutingTable.h"
#include <config/Config.h>
#include <machine/DeviceHashTree.h>
#include <LockGuard.h>
RoutingTable RoutingTable::m_Instance;
RoutingTable::RoutingTable() : m_bHasRoutes(false), m_TableLock(false)
{
}
RoutingTable::~RoutingTable()
{
}
void RoutingTable::Add(Type type, IpAddress dest, IpAddress subIp, String meta, Network *card)
{
LockGuard<Mutex> guard(m_TableLock);
// Add to the hash tree, if not already done. This ensures the loopback
// device is definitely available as an interface.
DeviceHashTree::instance().add(card);
// Add the route to the database directly
String str;
size_t hash = DeviceHashTree::instance().getHash(card);
str.sprintf("INSERT INTO routes (ipaddr, subip, name, type, iface) VALUES (%u, %u, '%s', %u, %u)", dest.getIp(), subIp.getIp(), static_cast<const char*>(meta), static_cast<int>(type), hash);
Config::Result *pResult = Config::instance().query(str);
if(!pResult->succeeded())
{
ERROR("Routing table query failed: " << pResult->errorMessage());
}
NOTICE("RoutingTable: Adding IP match route for " << dest.toString() << ", sub " << subIp.toString() << ".");
m_bHasRoutes = true;
delete pResult;
}
void RoutingTable::Add(Type type, IpAddress dest, IpAddress subnet, IpAddress subIp, String meta, Network *card)
{
LockGuard<Mutex> guard(m_TableLock);
// Add to the hash tree, if not already done. This ensures the loopback
// device is definitely available as an interface.
DeviceHashTree::instance().add(card);
// Invert the subnet to get an IP range
IpAddress invSubnet(subnet.getIp() ^ 0xFFFFFFFF);
IpAddress bottomOfRange = dest & subnet;
IpAddress topOfRange = (dest & subnet) + invSubnet;
NOTICE("RoutingTable: Adding " << (type == DestSubnetComplement ? "complement of " : "") << "subnet match for range " << bottomOfRange.toString() << " - " << topOfRange.toString());
// Add to the database
String str;
size_t hash = DeviceHashTree::instance().getHash(card);
str.sprintf("INSERT INTO routes (ipstart, ipend, subip, name, type, iface) VALUES (%u, %u, %u, '%s', %u, %u)",
bottomOfRange.getIp(),
topOfRange.getIp(),
subIp.getIp(),
static_cast<const char*>(meta),
static_cast<int>(type),
hash);
Config::Result *pResult = Config::instance().query(str);
if(!pResult->succeeded())
{
ERROR("Routing table query failed: " << pResult->errorMessage());
}
m_bHasRoutes = true;
delete pResult;
}
Network *RoutingTable::route(IpAddress *ip, Config::Result *pResult)
{
// Grab the interface
Network *pCard = dynamic_cast<Network*>(DeviceHashTree::instance().getDevice(pResult->getNum(0, "iface")));
// If we are to perform substitution, do so
Type t = static_cast<Type>(pResult->getNum(0, "type"));
if(t == DestIpSub || t == DestSubnetComplement)
ip->setIp(pResult->getNum(0, "subip"));
// Return the interface to use
delete pResult;
return pCard;
}
Network *RoutingTable::DetermineRoute(IpAddress *ip, bool bGiveDefault)
{
LockGuard<Mutex> guard(m_TableLock);
// Build a query to search for a direct match
String str;
str.sprintf("SELECT * FROM routes WHERE ipaddr=%u", ip->getIp());
Config::Result *pResult = Config::instance().query(str);
if(!pResult->succeeded())
ERROR("Routing table query failed: " << pResult->errorMessage());
else if(pResult->rows())
{
return route(ip, pResult);
}
delete pResult;
// No rows! Try a subnet lookup first, without a complement.
str.sprintf("SELECT * FROM routes WHERE ((ipstart <= %u) AND (ipend >= %u)) AND (type == %u)", ip->getIp(), ip->getIp(), static_cast<int>(DestSubnet));
pResult = Config::instance().query(str);
if(!pResult->succeeded())
ERROR("Routing table query failed: " << pResult->errorMessage());
else if(pResult->rows())
{
return route(ip, pResult);
}
delete pResult;
// Still nothing, try a complement subnet search
str.sprintf("SELECT * FROM routes WHERE (NOT ((ipstart <= %u) AND (ipend >= %u))) AND (type == %u)", ip->getIp(), ip->getIp(), static_cast<int>(DestSubnetComplement));
pResult = Config::instance().query(str);
if(!pResult->succeeded())
ERROR("Routing table query failed: " << pResult->errorMessage());
else if(pResult->rows())
{
return route(ip, pResult);
}
delete pResult;
// Nothing even still, try the default route if we're allowed
if(bGiveDefault)
{
return DefaultRoute();
}
// Not even the default route worked!
return 0;
}
Network *RoutingTable::DefaultRoute()
{
// If already locked, will return false, so we don't unlock (DetermineRoute calls this function)
bool bLocked = m_TableLock.tryAcquire();
String str;
str.sprintf("SELECT * FROM routes WHERE name='default'");
Config::Result *pResult = Config::instance().query(str);
if(!pResult->succeeded())
ERROR("Routing table query failed: " << pResult->errorMessage());
else if(pResult->rows())
{
if(bLocked)
m_TableLock.release();
return route(0, pResult);
}
delete pResult;
if(bLocked)
m_TableLock.release();
return 0;
}
<|endoftext|> |
<commit_before>#ifndef __CLITL_HPP__
#define __CLITL_HPP__
#include <cstdio>
#include <locale>
#include <ostream>
#include <string>
#include <tuple>
#include <utility>
#ifdef UNIX
#include <sys/ioctl.h>
#include <termios.h>
#include <unistd.h>
#elif WIN32
#include <conio.h>
#include <Windows.h>
#endif
namespace clitl {
/* Color class */
enum class color {
#ifdef UNIX
VOIDSPACE = -1,
DEFAULT = 0,
BLACK = 30,
RED = 31,
GREEN = 32,
BROWN = 33,
BLUE = 34,
MAGENTA = 35,
CYAN = 36,
#elif WIN32
VOIDSPACE = -1,
DEFAULT = 7,
BLACK = 0,
RED = 4,
GREEN = 2,
BROWN = 7, // Worthless
BLUE = 1,
MAGENTA = 7, // Worthless
CYAN = 9,
#endif
};
/* Basic definitions and containers */
typedef int coord_t;
typedef int colornum_t;
template <typename T>
class rect {
std::pair<T, T> origin;
std::pair<T, T> endpoint;
color foreground;
public:
explicit rect(const std::pair<T, T>& origin,
const std::pair<T, T>& endpoint,
const color& foreground)
: origin(origin), endpoint(endpoint), foreground(foreground) {}
explicit rect(const std::pair<T, T>& origin,
const std::pair<T, T>& endpoint)
: rect(origin, endpoint, color::DEFAULT) {}
explicit rect() : rect(std::pair<T, T>(0, 0),
std::pair<T, T>(0, 0), color::DEFAULT) {}
const rect<T>& set_origin(const std::pair<T, T>& coord)
{
origin = coord;
return *this;
}
const rect<T>& set_endpoint(const std::pair<T, T>& coord)
{
endpoint = coord;
return *this;
}
const rect<T>& set_foreground(const color& foreg)
{
foreground = foreg;
return *this;
}
const std::pair<T, T>& get_origin() const
{
return origin;
}
const std::pair<T, T>& get_endpoint() const
{
return endpoint;
}
const color& get_foreground() const
{
return foreground;
}
};
template <typename charT,
typename traits = std::char_traits<charT>,
typename Alloc = std::allocator<charT> >
struct colorstring {
std::basic_string<charT, traits, Alloc> str;
color foreground;
};
/* Output buffer */
template <typename charT, typename traits = std::char_traits<charT> >
class basic_outbuf : public std::basic_streambuf<charT, traits> {
protected:
virtual typename traits::int_type
overflow(typename traits::int_type c)
{
if (std::putchar(c) == EOF) {
return traits::eof();
}
return traits::not_eof(c);
}
};
typedef basic_outbuf<char> outbuf;
typedef basic_outbuf<wchar_t> woutbuf;
/* Output stream */
template <typename charT, typename traits = std::char_traits<charT> >
class basic_ostream : public std::basic_ostream<charT, traits> {
public:
#ifdef UNIX
struct winsize wsize;
#endif
#ifdef WIN32
HANDLE termout_handle;
CONSOLE_CURSOR_INFO termout_curinfo;
CONSOLE_SCREEN_BUFFER_INFO termout_sbufinfo;
#endif
explicit basic_ostream(basic_outbuf<charT, traits>* sb)
: std::basic_ostream<charT, traits>(sb)
{
#ifdef UNIX
wsize = { 0 };
#elif WIN32
termout_handle = GetStdHandle(STD_OUTPUT_HANDLE);
#endif
}
basic_ostream<charT, traits>& moveto(const std::pair<coord_t, coord_t>& coord)
{
#ifdef UNIX
*this << "\033[" << coord.second << ";" << coord.first << "f";
#elif WIN32
COORD pos = { static_cast<SHORT>(coord.first) - 1, static_cast<SHORT>(coord.second) - 1 };
SetConsoleCursorPosition(termout_handle, pos);
#endif
return *this;
}
std::pair<coord_t, coord_t> screensize()
{
static coord_t column;
static coord_t row;
#ifdef UNIX
column = wsize.ws_col;
row = wsize.ws_row;
#elif WIN32
GetConsoleScreenBufferInfo(termout_handle, &termout_sbufinfo);
column = static_cast<coord_t>(termout_sbufinfo.dwSize.X);
row = static_cast<coord_t>(termout_sbufinfo.dwSize.Y);
#endif
return std::pair<coord_t, coord_t>(column, row);
}
basic_ostream<charT, traits>& operator<<
(basic_ostream<charT, traits>& (*op)(basic_ostream<charT, traits>&))
{
return (*op)(*this);
}
};
typedef basic_ostream<char> ostream;
typedef basic_ostream<wchar_t> wostream;
template <typename charT, typename traits>
basic_ostream<charT, traits>& alternative_system_screenbuffer(basic_ostream<charT, traits>& os)
{
#if UNIX
os << "\033[?1049h"; // Use alternate screen buffer
#endif
return os;
}
template <typename charT, typename traits>
basic_ostream<charT, traits>& clear(basic_ostream<charT, traits>& os)
{
#ifdef UNIX
os << "\033[2J";
#elif WIN32
COORD startpoint = { 0, 0 };
DWORD dw;
GetConsoleScreenBufferInfo(os.termout_handle, &os.termout_sbufinfo);
FillConsoleOutputCharacterA(os.termout_handle, ' ',
os.termout_sbufinfo.dwSize.X * os.termout_sbufinfo.dwSize.Y,
startpoint, &dw);
FillConsoleOutputAttribute(os.termout_handle,
FOREGROUND_GREEN | FOREGROUND_RED | FOREGROUND_BLUE,
os.termout_sbufinfo.dwSize.X * os.termout_sbufinfo.dwSize.Y,
startpoint, &dw);
#endif
return os;
}
template <typename charT, typename traits>
basic_ostream<charT, traits>& hide_cursor(basic_ostream<charT, traits>& os)
{
#ifdef UNIX
os << "\033[?25l"; // Hide cursor
#elif WIN32
GetConsoleCursorInfo(os.termout_handle, &os.termout_curinfo);
os.termout_curinfo.bVisible = 0;
SetConsoleCursorInfo(os.termout_handle, &os.termout_curinfo);
#endif
return os;
}
template <typename charT, typename traits>
basic_ostream<charT, traits>& normal_system_screenbuffer(basic_ostream<charT, traits>& os)
{
#if UNIX
os << "\033[?1049l"; // Use normal screen buffer
#endif
return os;
}
template <typename charT, typename traits>
basic_ostream<charT, traits>& refresh(basic_ostream<charT, traits>& os)
{
fflush(stdout);
return os;
}
template <typename charT, typename traits>
basic_ostream<charT, traits>& show_cursor(basic_ostream<charT, traits>& os)
{
#if UNIX
os << "\033[?25h"; // Show cursor
#elif WIN32
CONSOLE_CURSOR_INFO termout_curinfo;
GetConsoleCursorInfo(os.termout_handle, &termout_curinfo);
termout_curinfo.bVisible = 1;
SetConsoleCursorInfo(os.termout_handle, &termout_curinfo);
#endif
return os;
}
template <typename charT, typename traits>
basic_ostream<charT, traits>& pre_process(basic_ostream<charT, traits>& os)
{
os << alternative_system_screenbuffer;
os << hide_cursor;
os << clear;
return os;
}
template <typename charT, typename traits>
basic_ostream<charT, traits>& post_process(basic_ostream<charT, traits>& os)
{
os << normal_system_screenbuffer;
os << show_cursor;
return os;
}
template <typename charT, typename traits, typename Alloc>
basic_ostream<charT, traits>& operator<<
(basic_ostream<charT, traits>& os,
const std::tuple<std::basic_string<charT, traits, Alloc>, color>& tu)
{
#ifdef UNIX
os << "\033[" << static_cast<coord_t>(std::get<1>(tu))
<< "m" << std::get<0>(tu).c_str() << "\033[0m";
#elif WIN32
WORD termout_attribute;
GetConsoleScreenBufferInfo(os.termout_handle, &os.termout_sbufinfo);
termout_attribute = os.termout_sbufinfo.wAttributes;
SetConsoleTextAttribute(os.termout_handle, static_cast<coord_t>(std::get<1>(tu)));
os << std::get<0>(tu);
SetConsoleTextAttribute(os.termout_handle, termout_attribute);
#endif
return os;
}
template <typename charT, typename traits, typename coordT>
basic_ostream<charT, traits>& operator<<
(basic_ostream<charT, traits>& os, const rect<coordT>& re)
{
for (int i = re.get_origin().first; i <= re.get_endpoint().first; ++i) {
for (int j = re.get_origin().second; j <= re.get_endpoint().second; ++j) {
os.moveto(std::pair<coord_t, coord_t>(i, j));
os << std::tuple<std::basic_string<charT>, color>
("@", re.get_foreground());
}
}
return os;
}
/* Input buffer */
/* Input stream */
template <typename charT, typename traits = std::char_traits<charT> >
class basic_istream : public std::basic_istream<charT, traits> {
};
typedef basic_istream<char> istream;
typedef basic_istream<wchar_t> wistream;
}
#endif
<commit_msg>Make basic cli-object classes<commit_after>#ifndef __CLITL_HPP__
#define __CLITL_HPP__
#include <cstdio>
#include <locale>
#include <ostream>
#include <string>
#include <tuple>
#include <utility>
#ifdef UNIX
#include <sys/ioctl.h>
#include <termios.h>
#include <unistd.h>
#elif WIN32
#include <conio.h>
#include <Windows.h>
#endif
namespace clitl {
/* Color class */
enum class color {
#ifdef UNIX
DEFAULT = 0,
BLACK = 0,
RED = 1,
GREEN = 2,
BROWN = 3,
BLUE = 4,
MAGENTA = 5,
CYAN = 6,
WHITE = 7,
#elif WIN32
DEFAULT = 0x7,
BLACK = 0x0,
RED = 0x4,
GREEN = 0x2,
BROWN = 0x7, // Worthless
BLUE = 0x1,
MAGENTA = 0x7, // Worthless
CYAN = 0x9,
WHITE = 0x7,
#endif
};
/* Basic definitions and containers */
typedef int coord_t;
typedef int colornum_t;
template <typename coordT, typename charT,
typename traits = std::char_traits<charT>, typename Alloc = std::allocator<charT> >
class basic_cli_object {
std::pair<coordT, coordT> origin;
std::pair<coordT, coordT> endpoint;
std::basic_string<charT, traits, Alloc> str;
color foreground;
color background;
public:
explicit basic_cli_object(
const std::pair<coordT, coordT>& origin = std::pair<coordT, coordT>(0, 0),
const std::pair<coordT, coordT>& endpoint = std::pair<coordT, coordT>(0, 0),
const std::basic_string<charT, traits, Alloc>& str
= std::basic_string<charT, traits, Alloc>(),
const color& foreground = clitl::color::WHITE,
const color& background = clitl::color::BLACK)
: origin(origin), endpoint(endpoint), str(str),
foreground(foreground), background(background) {}
const basic_cli_object<coordT, charT>& set_origin(const std::pair<coordT, coordT>& coord)
{
origin = coord;
return *this;
}
const basic_cli_object<coordT, charT>& set_endpoint(const std::pair<coordT, coordT>& coord)
{
endpoint = coord;
return *this;
}
const basic_cli_object<coordT, charT>& set_string(const std::basic_string<charT, traits, Alloc>& stri)
{
str = stri;
return *this
}
const basic_cli_object<coordT, charT>& set_foreground(const color& foreg)
{
foreground = foreg;
return *this;
}
const basic_cli_object<coordT, charT>& set_background(const color& backg)
{
background = backg;
return *this;
}
const std::pair<coordT, coordT>& get_origin() const
{
return origin;
}
const std::pair<coordT, coordT>& get_endpoint() const
{
return endpoint;
}
const std::basic_string<charT, traits, Alloc>& get_string() const
{
return str;
}
const color& get_foreground() const
{
return foreground;
}
const color& get_background() const
{
return background;
}
};
template <typename coordT, typename charT = char,
typename traits = std::char_traits<charT>, typename Alloc = std::allocator<charT> >
class rect : public basic_cli_object<coordT, charT, traits, Alloc> {
public:
explicit rect(
const std::pair<coordT, coordT>& origin = std::pair<coordT, coordT>(0, 0),
const std::pair<coordT, coordT>& endpoint = std::pair<coordT, coordT>(0, 0),
const color& background = color::WHITE)
: basic_cli_object<coordT, charT, traits, Alloc>(origin, endpoint,
std::basic_string<charT, traits, Alloc>(), color::DEFAULT, background) {}
};
template <typename coordT, typename charT,
typename traits = std::char_traits<charT>, typename Alloc = std::allocator<charT> >
class coloredstring : public basic_cli_object<coordT, charT, traits, Alloc> {
public:
explicit coloredstring(
const std::pair<coordT, coordT>& origin = std::pair<coordT, coordT>(0, 0),
const std::pair<coordT, coordT>& endpoint = std::pair<coordT, coordT>(0, 0),
const std::basic_string<charT, traits, Alloc>& str
= std::basic_string<charT, traits, Alloc>(),
const color& foreground = clitl::color::WHITE,
const color& background = clitl::color::BLACK)
: basic_cli_object<coordT, charT, traits, Alloc>(
origin, endpoint, str, foreground, background) {}
explicit coloredstring(
const std::basic_string<charT, traits, Alloc>& str
= std::basic_string<charT, traits, Alloc>(),
const color& foreground = clitl::color::WHITE,
const color& background = clitl::color::BLACK)
: basic_cli_object<coordT, charT, traits, Alloc>(
std::pair<coordT, coordT>(0, 0), std::pair<coordT, coordT>(0, 0),
str, foreground, background) {}
};
/* Output buffer */
template <typename charT, typename traits = std::char_traits<charT> >
class basic_outbuf : public std::basic_streambuf<charT, traits> {
protected:
virtual typename traits::int_type
overflow(typename traits::int_type c)
{
if (std::putchar(c) == EOF) {
return traits::eof();
}
return traits::not_eof(c);
}
};
typedef basic_outbuf<char> outbuf;
typedef basic_outbuf<wchar_t> woutbuf;
/* Output stream */
template <typename charT, typename traits = std::char_traits<charT> >
class basic_ostream : public std::basic_ostream<charT, traits> {
public:
#ifdef UNIX
struct winsize wsize;
#endif
#ifdef WIN32
HANDLE termout_handle;
CONSOLE_CURSOR_INFO termout_curinfo;
CONSOLE_SCREEN_BUFFER_INFO termout_sbufinfo;
#endif
explicit basic_ostream(basic_outbuf<charT, traits>* sb)
: std::basic_ostream<charT, traits>(sb)
{
#ifdef UNIX
wsize = { 0 };
#elif WIN32
termout_handle = GetStdHandle(STD_OUTPUT_HANDLE);
#endif
}
basic_ostream<charT, traits>& moveto(const std::pair<coord_t, coord_t>& coord)
{
#ifdef UNIX
*this << "\033[" << coord.second << ";" << coord.first << "f";
#elif WIN32
COORD pos = { static_cast<SHORT>(coord.first) - 1, static_cast<SHORT>(coord.second) - 1 };
SetConsoleCursorPosition(termout_handle, pos);
#endif
return *this;
}
std::pair<coord_t, coord_t> screensize()
{
static coord_t column;
static coord_t row;
#ifdef UNIX
column = wsize.ws_col;
row = wsize.ws_row;
#elif WIN32
GetConsoleScreenBufferInfo(termout_handle, &termout_sbufinfo);
column = static_cast<coord_t>(termout_sbufinfo.dwSize.X);
row = static_cast<coord_t>(termout_sbufinfo.dwSize.Y);
#endif
return std::pair<coord_t, coord_t>(column, row);
}
basic_ostream<charT, traits>& operator<<
(basic_ostream<charT, traits>& (*op)(basic_ostream<charT, traits>&))
{
return (*op)(*this);
}
};
typedef basic_ostream<char> ostream;
typedef basic_ostream<wchar_t> wostream;
template <typename charT, typename traits>
basic_ostream<charT, traits>& alternative_system_screenbuffer(basic_ostream<charT, traits>& os)
{
#if UNIX
os << "\033[?1049h"; // Use alternate screen buffer
#endif
return os;
}
template <typename charT, typename traits>
basic_ostream<charT, traits>& clear(basic_ostream<charT, traits>& os)
{
#ifdef UNIX
os << "\033[2J";
#elif WIN32
COORD startpoint = { 0, 0 };
DWORD dw;
GetConsoleScreenBufferInfo(os.termout_handle, &os.termout_sbufinfo);
FillConsoleOutputCharacterA(os.termout_handle, ' ',
os.termout_sbufinfo.dwSize.X * os.termout_sbufinfo.dwSize.Y,
startpoint, &dw);
FillConsoleOutputAttribute(os.termout_handle,
FOREGROUND_GREEN | FOREGROUND_RED | FOREGROUND_BLUE,
os.termout_sbufinfo.dwSize.X * os.termout_sbufinfo.dwSize.Y,
startpoint, &dw);
#endif
return os;
}
template <typename charT, typename traits>
basic_ostream<charT, traits>& hide_cursor(basic_ostream<charT, traits>& os)
{
#ifdef UNIX
os << "\033[?25l"; // Hide cursor
#elif WIN32
GetConsoleCursorInfo(os.termout_handle, &os.termout_curinfo);
os.termout_curinfo.bVisible = 0;
SetConsoleCursorInfo(os.termout_handle, &os.termout_curinfo);
#endif
return os;
}
template <typename charT, typename traits>
basic_ostream<charT, traits>& normal_system_screenbuffer(basic_ostream<charT, traits>& os)
{
#if UNIX
os << "\033[?1049l"; // Use normal screen buffer
#endif
return os;
}
template <typename charT, typename traits>
basic_ostream<charT, traits>& refresh(basic_ostream<charT, traits>& os)
{
std::fflush(stdout);
return os;
}
template <typename charT, typename traits>
basic_ostream<charT, traits>& show_cursor(basic_ostream<charT, traits>& os)
{
#if UNIX
os << "\033[?25h"; // Show cursor
#elif WIN32
CONSOLE_CURSOR_INFO termout_curinfo;
GetConsoleCursorInfo(os.termout_handle, &termout_curinfo);
termout_curinfo.bVisible = 1;
SetConsoleCursorInfo(os.termout_handle, &termout_curinfo);
#endif
return os;
}
template <typename charT, typename traits>
basic_ostream<charT, traits>& pre_process(basic_ostream<charT, traits>& os)
{
os << alternative_system_screenbuffer;
os << hide_cursor;
os << clear;
return os;
}
template <typename charT, typename traits>
basic_ostream<charT, traits>& post_process(basic_ostream<charT, traits>& os)
{
os << normal_system_screenbuffer;
os << show_cursor;
return os;
}
template <typename coordT, typename charT, typename traits, typename Alloc>
basic_ostream<charT, traits>& operator<<
(basic_ostream<charT, traits>& os,
const coloredstring<coordT, charT, traits, Alloc>& cs)
{
#ifdef UNIX
os << "\033["
<< static_cast<int>(30 + cs.get_foreground())
<< ";"
<< static_cast<int>(40 + cs.get_background())
<< "m" << ;
/* Recovery code
os << "\033[0m";
*/
#elif WIN32
/* Recovery code
WORD termout_attribute;
GetConsoleScreenBufferInfo(os.termout_handle, &os.termout_sbufinfo);
termout_attribute = os.termout_sbufinfo.wAttributes;
*/
SetConsoleTextAttribute(os.termout_handle,
static_cast<WORD>(static_cast<char>(cs.get_foreground())
+ 0x10 * static_cast<char>(cs.get_background())));
os << cs.get_string().c_str();
/* Recovery code
SetConsoleTextAttribute(os.termout_handle, termout_attribute);
*/
#endif
return os;
}
template <typename coordT, typename charT, typename traits, typename Alloc>
basic_ostream<charT, traits>& operator<<
(basic_ostream<charT, traits>& os, const rect<coordT, charT, traits, Alloc>& re)
{
for (int i = re.get_origin().first; i <= re.get_endpoint().first; ++i) {
for (int j = re.get_origin().second; j <= re.get_endpoint().second; ++j) {
os.moveto(std::pair<coord_t, coord_t>(i, j));
os << coloredstring<coordT, charT, traits, Alloc>(
re.get_string(), re.get_foreground(), re.get_background());
//os << std::tuple<std::basic_string<charT>, color, color>
("@", re.get_foreground(), re.get_background());
}
}
return os;
}
/* Input buffer */
/* Input stream */
template <typename charT, typename traits = std::char_traits<charT> >
class basic_istream : public std::basic_istream<charT, traits> {
};
typedef basic_istream<char> istream;
typedef basic_istream<wchar_t> wistream;
}
#endif
<|endoftext|> |
<commit_before>/*
* Strategy pattern
* Author: reimen
* Data: Oct.13.2014
*
*/
#include <iostream>
#include <cstdlib>
using std::cout;
using std::endl;
class Strategy
{
public:
virtual ~Strategy() {}
virtual void algorithm() = 0;
};
class ConcreteStrategy : public Strategy
{
public:
virtual ~ConcreteStrategy() {}
void algorithm()
{
cout << "Hello" << endl;
}
};
class Context
{
protected:
Strategy* _strategy;
public:
Context(): _strategy(new ConcreteStrategy) {}
virtual ~Context()
{
delete _strategy;
}
void operate()
{
_strategy->algorithm();
}
};
int main()
{
Context a;
a.operate();
return EXIT_SUCCESS;
}
<commit_msg>add comments to Strategy.cpp<commit_after>/*
* Strategy pattern
* Author: reimen
* Date: Oct.13.2014
* Define a family of algorithms, encapsulate each one, make them
* interchangeable Strategy lets the algorithm vary independently from
* clients that use it.
*/
#include <iostream>
#include <cstdlib>
using std::cout;
using std::endl;
class Strategy
{
public:
virtual ~Strategy() {}
virtual void algorithm() = 0;
};
class ConcreteStrategy : public Strategy
{
public:
virtual ~ConcreteStrategy() {}
void algorithm()
{
cout << "Hello" << endl;
}
};
class Context
{
protected:
Strategy* _strategy;
public:
Context(): _strategy(new ConcreteStrategy) {}
virtual ~Context()
{
delete _strategy;
}
void operate()
{
_strategy->algorithm();
}
};
int main()
{
Context a;
a.operate();
return EXIT_SUCCESS;
}
<|endoftext|> |
<commit_before>/*************************************************************************
*
* OpenOffice.org - a multi-platform office productivity suite
*
* $RCSfile: commoncontrol.hxx,v $
*
* $Revision: 1.9 $
*
* last change: $Author: kz $ $Date: 2007-05-10 10:47: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
*
************************************************************************/
#ifndef _EXTENSIONS_PROPCTRLR_COMMONCONTROL_HXX_
#define _EXTENSIONS_PROPCTRLR_COMMONCONTROL_HXX_
/** === begin UNO includes === **/
#ifndef _COM_SUN_STAR_INSPECTION_XPROPERTYCONTROL_HPP_
#include <com/sun/star/inspection/XPropertyControl.hpp>
#endif
#ifndef _COM_SUN_STAR_LANG_DISPOSEDEXCEPTION_HPP_
#include <com/sun/star/lang/DisposedException.hpp>
#endif
/** === end UNO includes === **/
#ifndef _CPPUHELPER_COMPBASE1_HXX_
#include <cppuhelper/compbase1.hxx>
#endif
#ifndef _COMPHELPER_BROADCASTHELPER_HXX_
#include <comphelper/broadcasthelper.hxx>
#endif
#ifndef _LINK_HXX
#include <tools/link.hxx>
#endif
#ifndef _SV_WINDOW_HXX
#include <vcl/window.hxx>
#endif
class NotifyEvent;
//............................................................................
namespace pcr
{
//............................................................................
class ControlHelper;
//========================================================================
//= ControlWindow
//========================================================================
template< class WINDOW >
class ControlWindow : public WINDOW
{
protected:
typedef WINDOW WindowType;
protected:
ControlHelper* m_pHelper;
public:
ControlWindow( Window* _pParent, WinBits _nStyle )
:WindowType( _pParent, _nStyle )
,m_pHelper( NULL )
{
}
/// sets a ControlHelper instance which some functionality is delegated to
inline virtual void setControlHelper( ControlHelper& _rControlHelper );
protected:
// Window overridables
inline virtual long PreNotify( NotifyEvent& rNEvt );
};
//========================================================================
//= IModifyListener
//========================================================================
class SAL_NO_VTABLE IModifyListener
{
public:
virtual void modified() = 0;
};
//========================================================================
//= ControlHelper
//========================================================================
/** A helper class for implementing the <type scope="com::sun::star::inspection">XPropertyControl</type>
or one of its derived interfaces.
This class is intended to be held as member of another class which implements the
<type scope="com::sun::star::inspection">XPropertyControl</type> interface. The pointer
to this interface is to be passed to the ctor.
*/
class ControlHelper
{
private:
Window* m_pControlWindow;
sal_Int16 m_nControlType;
::com::sun::star::uno::Reference< ::com::sun::star::inspection::XPropertyControlContext >
m_xContext;
::com::sun::star::inspection::XPropertyControl&
m_rAntiImpl;
IModifyListener* m_pModifyListener;
sal_Bool m_bModified;
public:
/** creates the instance
@param _rControlWindow
the window which is associated with the <type scope="com::sun::star::inspection">XPropertyControl</type>.
Must not be <NULL/>.<br/>
Ownership for this window is taken by the ControlHelper - it will be deleted in <member>disposing</member>.
@param _nControlType
the type of the control - one of the <type scope="com::sun::star::inspection">PropertyControlType</type>
constants
@param _pAntiImpl
Reference to the instance as whose "impl-class" we act. This reference is held during lifetime
of the <type>ControlHelper</type> class, within acquiring it. Thus, the owner of the
<type>ControlHelper</type> is responsible for assuring the lifetime of the instance
pointed to by <arg>_pAntiImpl</arg>.
@param _pModifyListener
a listener to be modfied when the user modified the control's value. the
<member>IModifyListener::modified</member> of this listener is called from within our
ModifiedHdl. A default implementation of <member>IModifyListener::modified</member>
would just call our <member>setModified</member>.
*/
ControlHelper(
Window* _pControlWindow,
sal_Int16 _nControlType,
::com::sun::star::inspection::XPropertyControl& _rAntiImpl,
IModifyListener* _pModifyListener );
virtual ~ControlHelper();
/** sets our "modified" flag to <TRUE/>
*/
inline void setModified() { m_bModified = sal_True; }
inline Window* getVclControlWindow() { return m_pControlWindow; }
inline const Window* getVclControlWindow() const { return m_pControlWindow; }
public:
// XPropertyControl
::sal_Int16 SAL_CALL getControlType() throw (::com::sun::star::uno::RuntimeException);
::com::sun::star::uno::Reference< ::com::sun::star::inspection::XPropertyControlContext > SAL_CALL getControlContext() throw (::com::sun::star::uno::RuntimeException);
void SAL_CALL setControlContext( const ::com::sun::star::uno::Reference< ::com::sun::star::inspection::XPropertyControlContext >& _controlcontext ) throw (::com::sun::star::uno::RuntimeException);
::com::sun::star::uno::Reference< ::com::sun::star::awt::XWindow > SAL_CALL getControlWindow() throw (::com::sun::star::uno::RuntimeException);
::sal_Bool SAL_CALL isModified( ) throw (::com::sun::star::uno::RuntimeException);
void SAL_CALL notifyModifiedValue( ) throw (::com::sun::star::uno::RuntimeException);
// XComponent
virtual void SAL_CALL dispose();
/** (fail-safe) wrapper around calling our context's activateNextControl
*/
inline void activateNextControl() const { impl_activateNextControl_nothrow(); }
public:
/// may be used to implement the default handling in PreNotify; returns sal_True if handled
bool handlePreNotify(NotifyEvent& _rNEvt);
/// automatically size the window given in the ctor
void autoSizeWindow();
/// may be used by derived classes, they forward the event to the PropCtrListener
DECL_LINK( ModifiedHdl, Window* );
DECL_LINK( GetFocusHdl, Window* );
DECL_LINK( LoseFocusHdl, Window* );
private:
/** fail-safe wrapper around calling our context's activateNextControl
*/
void impl_activateNextControl_nothrow() const;
};
//========================================================================
//= CommonBehaviourControl
//========================================================================
/** implements a base class for <type scope="com::sun::star::inspection">XPropertyControl</type>
implementations, which delegates the generic functionality of this interface to a
<type>ControlHelper</type> member.
@param CONTROL_INTERFACE
an interface class which is derived from (or identical to) <type scope="com::sun::star::inspection">XPropertyControl</type>
@param CONTROL_WINDOW
a class which is derived from ControlWindow
*/
template < class CONTROL_INTERFACE, class CONTROL_WINDOW >
class CommonBehaviourControl :public ::comphelper::OBaseMutex
,public ::cppu::WeakComponentImplHelper1< CONTROL_INTERFACE >
,public IModifyListener
{
protected:
typedef CONTROL_INTERFACE InterfaceType;
typedef CONTROL_WINDOW WindowType;
typedef ::comphelper::OBaseMutex MutexBaseClass;
typedef ::cppu::WeakComponentImplHelper1< CONTROL_INTERFACE > ComponentBaseClass;
protected:
ControlHelper m_aImplControl;
protected:
inline CommonBehaviourControl( sal_Int16 _nControlType, Window* _pParentWindow, WinBits _nWindowStyle, bool _bDoSetHandlers = true );
// XPropertyControl - delegated to ->m_aImplControl
inline ::sal_Int16 SAL_CALL getControlType() throw (::com::sun::star::uno::RuntimeException);
inline ::com::sun::star::uno::Reference< ::com::sun::star::inspection::XPropertyControlContext > SAL_CALL getControlContext() throw (::com::sun::star::uno::RuntimeException);
inline void SAL_CALL setControlContext( const ::com::sun::star::uno::Reference< ::com::sun::star::inspection::XPropertyControlContext >& _controlcontext ) throw (::com::sun::star::uno::RuntimeException);
inline ::com::sun::star::uno::Reference< ::com::sun::star::awt::XWindow > SAL_CALL getControlWindow() throw (::com::sun::star::uno::RuntimeException);
inline ::sal_Bool SAL_CALL isModified( ) throw (::com::sun::star::uno::RuntimeException);
inline void SAL_CALL notifyModifiedValue( ) throw (::com::sun::star::uno::RuntimeException);
// XComponent
inline virtual void SAL_CALL disposing();
// IModifyListener
inline virtual void modified();
/// returns a typed pointer to our control window
WindowType* getTypedControlWindow() { return static_cast< WindowType* > ( m_aImplControl.getVclControlWindow() ); }
const WindowType* getTypedControlWindow() const { return static_cast< const WindowType* >( m_aImplControl.getVclControlWindow() ); }
protected:
/** checks whether the instance is already disposed
@throws DisposedException
if the instance is already disposed
*/
inline void impl_checkDisposed_throw();
};
//========================================================================
//= ControlWindow - implementation
//========================================================================
//------------------------------------------------------------------------
template< class WINDOW >
inline void ControlWindow< WINDOW >::setControlHelper( ControlHelper& _rControlHelper )
{
m_pHelper = &_rControlHelper;
}
//------------------------------------------------------------------------
template< class WINDOW >
inline long ControlWindow< WINDOW >::PreNotify( NotifyEvent& rNEvt )
{
if ( m_pHelper && m_pHelper->handlePreNotify( rNEvt ) )
return 1;
return WindowType::PreNotify( rNEvt );
}
//========================================================================
//= CommonBehaviourControl - implementation
//========================================================================
//------------------------------------------------------------------------
template< class CONTROL_INTERFACE, class CONTROL_WINDOW >
inline CommonBehaviourControl< CONTROL_INTERFACE, CONTROL_WINDOW >::CommonBehaviourControl ( sal_Int16 _nControlType, Window* _pParentWindow, WinBits _nWindowStyle, bool _bDoSetHandlers )
:ComponentBaseClass( m_aMutex )
,m_aImplControl( new WindowType( _pParentWindow, _nWindowStyle ), _nControlType, *this, this )
{
WindowType* pControlWindow( getTypedControlWindow() );
pControlWindow->setControlHelper( m_aImplControl );
if ( _bDoSetHandlers )
{
pControlWindow->SetModifyHdl( LINK( &m_aImplControl, ControlHelper, ModifiedHdl ) );
pControlWindow->SetGetFocusHdl( LINK( &m_aImplControl, ControlHelper, GetFocusHdl ) );
pControlWindow->SetLoseFocusHdl( LINK( &m_aImplControl, ControlHelper, LoseFocusHdl ) );
}
m_aImplControl.autoSizeWindow();
}
//--------------------------------------------------------------------
template< class CONTROL_INTERFACE, class CONTROL_WINDOW >
inline ::sal_Int16 SAL_CALL CommonBehaviourControl< CONTROL_INTERFACE, CONTROL_WINDOW >::getControlType() throw (::com::sun::star::uno::RuntimeException)
{
return m_aImplControl.getControlType();
}
//--------------------------------------------------------------------
template< class CONTROL_INTERFACE, class CONTROL_WINDOW >
inline ::com::sun::star::uno::Reference< ::com::sun::star::inspection::XPropertyControlContext > SAL_CALL CommonBehaviourControl< CONTROL_INTERFACE, CONTROL_WINDOW >::getControlContext() throw (::com::sun::star::uno::RuntimeException)
{
return m_aImplControl.getControlContext();
}
//--------------------------------------------------------------------
template< class CONTROL_INTERFACE, class CONTROL_WINDOW >
inline void SAL_CALL CommonBehaviourControl< CONTROL_INTERFACE, CONTROL_WINDOW >::setControlContext( const ::com::sun::star::uno::Reference< ::com::sun::star::inspection::XPropertyControlContext >& _controlcontext ) throw (::com::sun::star::uno::RuntimeException)
{
m_aImplControl.setControlContext( _controlcontext );
}
//--------------------------------------------------------------------
template< class CONTROL_INTERFACE, class CONTROL_WINDOW >
inline ::com::sun::star::uno::Reference< ::com::sun::star::awt::XWindow > SAL_CALL CommonBehaviourControl< CONTROL_INTERFACE, CONTROL_WINDOW >::getControlWindow() throw (::com::sun::star::uno::RuntimeException)
{
return m_aImplControl.getControlWindow();
}
//--------------------------------------------------------------------
template< class CONTROL_INTERFACE, class CONTROL_WINDOW >
inline ::sal_Bool SAL_CALL CommonBehaviourControl< CONTROL_INTERFACE, CONTROL_WINDOW >::isModified( ) throw (::com::sun::star::uno::RuntimeException)
{
return m_aImplControl.isModified();
}
//--------------------------------------------------------------------
template< class CONTROL_INTERFACE, class CONTROL_WINDOW >
inline void SAL_CALL CommonBehaviourControl< CONTROL_INTERFACE, CONTROL_WINDOW >::notifyModifiedValue( ) throw (::com::sun::star::uno::RuntimeException)
{
m_aImplControl.notifyModifiedValue();
}
//--------------------------------------------------------------------
template< class CONTROL_INTERFACE, class CONTROL_WINDOW >
inline void SAL_CALL CommonBehaviourControl< CONTROL_INTERFACE, CONTROL_WINDOW >::disposing()
{
m_aImplControl.dispose();
}
//--------------------------------------------------------------------
template< class CONTROL_INTERFACE, class CONTROL_WINDOW >
inline void CommonBehaviourControl< CONTROL_INTERFACE, CONTROL_WINDOW >::modified()
{
m_aImplControl.setModified();
}
//--------------------------------------------------------------------
template< class CONTROL_INTERFACE, class CONTROL_WINDOW >
inline void CommonBehaviourControl< CONTROL_INTERFACE, CONTROL_WINDOW >::impl_checkDisposed_throw()
{
if ( ComponentBaseClass::rBHelper.bDisposed )
throw ::com::sun::star::lang::DisposedException( ::rtl::OUString(), *this );
}
//............................................................................
} // namespace pcr
//............................................................................
#endif // _EXTENSIONS_PROPCTRLR_COMMONCONTROL_HXX_
<commit_msg>INTEGRATION: CWS changefileheader (1.9.162); FILE MERGED 2008/04/01 15:15:13 thb 1.9.162.3: #i85898# Stripping all external header guards 2008/04/01 12:29:48 thb 1.9.162.2: #i85898# Stripping all external header guards 2008/03/31 12:31:40 rt 1.9.162.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: commoncontrol.hxx,v $
* $Revision: 1.10 $
*
* 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.
*
************************************************************************/
#ifndef _EXTENSIONS_PROPCTRLR_COMMONCONTROL_HXX_
#define _EXTENSIONS_PROPCTRLR_COMMONCONTROL_HXX_
/** === begin UNO includes === **/
#include <com/sun/star/inspection/XPropertyControl.hpp>
#include <com/sun/star/lang/DisposedException.hpp>
/** === end UNO includes === **/
#include <cppuhelper/compbase1.hxx>
#include <comphelper/broadcasthelper.hxx>
#include <tools/link.hxx>
#include <vcl/window.hxx>
class NotifyEvent;
//............................................................................
namespace pcr
{
//............................................................................
class ControlHelper;
//========================================================================
//= ControlWindow
//========================================================================
template< class WINDOW >
class ControlWindow : public WINDOW
{
protected:
typedef WINDOW WindowType;
protected:
ControlHelper* m_pHelper;
public:
ControlWindow( Window* _pParent, WinBits _nStyle )
:WindowType( _pParent, _nStyle )
,m_pHelper( NULL )
{
}
/// sets a ControlHelper instance which some functionality is delegated to
inline virtual void setControlHelper( ControlHelper& _rControlHelper );
protected:
// Window overridables
inline virtual long PreNotify( NotifyEvent& rNEvt );
};
//========================================================================
//= IModifyListener
//========================================================================
class SAL_NO_VTABLE IModifyListener
{
public:
virtual void modified() = 0;
};
//========================================================================
//= ControlHelper
//========================================================================
/** A helper class for implementing the <type scope="com::sun::star::inspection">XPropertyControl</type>
or one of its derived interfaces.
This class is intended to be held as member of another class which implements the
<type scope="com::sun::star::inspection">XPropertyControl</type> interface. The pointer
to this interface is to be passed to the ctor.
*/
class ControlHelper
{
private:
Window* m_pControlWindow;
sal_Int16 m_nControlType;
::com::sun::star::uno::Reference< ::com::sun::star::inspection::XPropertyControlContext >
m_xContext;
::com::sun::star::inspection::XPropertyControl&
m_rAntiImpl;
IModifyListener* m_pModifyListener;
sal_Bool m_bModified;
public:
/** creates the instance
@param _rControlWindow
the window which is associated with the <type scope="com::sun::star::inspection">XPropertyControl</type>.
Must not be <NULL/>.<br/>
Ownership for this window is taken by the ControlHelper - it will be deleted in <member>disposing</member>.
@param _nControlType
the type of the control - one of the <type scope="com::sun::star::inspection">PropertyControlType</type>
constants
@param _pAntiImpl
Reference to the instance as whose "impl-class" we act. This reference is held during lifetime
of the <type>ControlHelper</type> class, within acquiring it. Thus, the owner of the
<type>ControlHelper</type> is responsible for assuring the lifetime of the instance
pointed to by <arg>_pAntiImpl</arg>.
@param _pModifyListener
a listener to be modfied when the user modified the control's value. the
<member>IModifyListener::modified</member> of this listener is called from within our
ModifiedHdl. A default implementation of <member>IModifyListener::modified</member>
would just call our <member>setModified</member>.
*/
ControlHelper(
Window* _pControlWindow,
sal_Int16 _nControlType,
::com::sun::star::inspection::XPropertyControl& _rAntiImpl,
IModifyListener* _pModifyListener );
virtual ~ControlHelper();
/** sets our "modified" flag to <TRUE/>
*/
inline void setModified() { m_bModified = sal_True; }
inline Window* getVclControlWindow() { return m_pControlWindow; }
inline const Window* getVclControlWindow() const { return m_pControlWindow; }
public:
// XPropertyControl
::sal_Int16 SAL_CALL getControlType() throw (::com::sun::star::uno::RuntimeException);
::com::sun::star::uno::Reference< ::com::sun::star::inspection::XPropertyControlContext > SAL_CALL getControlContext() throw (::com::sun::star::uno::RuntimeException);
void SAL_CALL setControlContext( const ::com::sun::star::uno::Reference< ::com::sun::star::inspection::XPropertyControlContext >& _controlcontext ) throw (::com::sun::star::uno::RuntimeException);
::com::sun::star::uno::Reference< ::com::sun::star::awt::XWindow > SAL_CALL getControlWindow() throw (::com::sun::star::uno::RuntimeException);
::sal_Bool SAL_CALL isModified( ) throw (::com::sun::star::uno::RuntimeException);
void SAL_CALL notifyModifiedValue( ) throw (::com::sun::star::uno::RuntimeException);
// XComponent
virtual void SAL_CALL dispose();
/** (fail-safe) wrapper around calling our context's activateNextControl
*/
inline void activateNextControl() const { impl_activateNextControl_nothrow(); }
public:
/// may be used to implement the default handling in PreNotify; returns sal_True if handled
bool handlePreNotify(NotifyEvent& _rNEvt);
/// automatically size the window given in the ctor
void autoSizeWindow();
/// may be used by derived classes, they forward the event to the PropCtrListener
DECL_LINK( ModifiedHdl, Window* );
DECL_LINK( GetFocusHdl, Window* );
DECL_LINK( LoseFocusHdl, Window* );
private:
/** fail-safe wrapper around calling our context's activateNextControl
*/
void impl_activateNextControl_nothrow() const;
};
//========================================================================
//= CommonBehaviourControl
//========================================================================
/** implements a base class for <type scope="com::sun::star::inspection">XPropertyControl</type>
implementations, which delegates the generic functionality of this interface to a
<type>ControlHelper</type> member.
@param CONTROL_INTERFACE
an interface class which is derived from (or identical to) <type scope="com::sun::star::inspection">XPropertyControl</type>
@param CONTROL_WINDOW
a class which is derived from ControlWindow
*/
template < class CONTROL_INTERFACE, class CONTROL_WINDOW >
class CommonBehaviourControl :public ::comphelper::OBaseMutex
,public ::cppu::WeakComponentImplHelper1< CONTROL_INTERFACE >
,public IModifyListener
{
protected:
typedef CONTROL_INTERFACE InterfaceType;
typedef CONTROL_WINDOW WindowType;
typedef ::comphelper::OBaseMutex MutexBaseClass;
typedef ::cppu::WeakComponentImplHelper1< CONTROL_INTERFACE > ComponentBaseClass;
protected:
ControlHelper m_aImplControl;
protected:
inline CommonBehaviourControl( sal_Int16 _nControlType, Window* _pParentWindow, WinBits _nWindowStyle, bool _bDoSetHandlers = true );
// XPropertyControl - delegated to ->m_aImplControl
inline ::sal_Int16 SAL_CALL getControlType() throw (::com::sun::star::uno::RuntimeException);
inline ::com::sun::star::uno::Reference< ::com::sun::star::inspection::XPropertyControlContext > SAL_CALL getControlContext() throw (::com::sun::star::uno::RuntimeException);
inline void SAL_CALL setControlContext( const ::com::sun::star::uno::Reference< ::com::sun::star::inspection::XPropertyControlContext >& _controlcontext ) throw (::com::sun::star::uno::RuntimeException);
inline ::com::sun::star::uno::Reference< ::com::sun::star::awt::XWindow > SAL_CALL getControlWindow() throw (::com::sun::star::uno::RuntimeException);
inline ::sal_Bool SAL_CALL isModified( ) throw (::com::sun::star::uno::RuntimeException);
inline void SAL_CALL notifyModifiedValue( ) throw (::com::sun::star::uno::RuntimeException);
// XComponent
inline virtual void SAL_CALL disposing();
// IModifyListener
inline virtual void modified();
/// returns a typed pointer to our control window
WindowType* getTypedControlWindow() { return static_cast< WindowType* > ( m_aImplControl.getVclControlWindow() ); }
const WindowType* getTypedControlWindow() const { return static_cast< const WindowType* >( m_aImplControl.getVclControlWindow() ); }
protected:
/** checks whether the instance is already disposed
@throws DisposedException
if the instance is already disposed
*/
inline void impl_checkDisposed_throw();
};
//========================================================================
//= ControlWindow - implementation
//========================================================================
//------------------------------------------------------------------------
template< class WINDOW >
inline void ControlWindow< WINDOW >::setControlHelper( ControlHelper& _rControlHelper )
{
m_pHelper = &_rControlHelper;
}
//------------------------------------------------------------------------
template< class WINDOW >
inline long ControlWindow< WINDOW >::PreNotify( NotifyEvent& rNEvt )
{
if ( m_pHelper && m_pHelper->handlePreNotify( rNEvt ) )
return 1;
return WindowType::PreNotify( rNEvt );
}
//========================================================================
//= CommonBehaviourControl - implementation
//========================================================================
//------------------------------------------------------------------------
template< class CONTROL_INTERFACE, class CONTROL_WINDOW >
inline CommonBehaviourControl< CONTROL_INTERFACE, CONTROL_WINDOW >::CommonBehaviourControl ( sal_Int16 _nControlType, Window* _pParentWindow, WinBits _nWindowStyle, bool _bDoSetHandlers )
:ComponentBaseClass( m_aMutex )
,m_aImplControl( new WindowType( _pParentWindow, _nWindowStyle ), _nControlType, *this, this )
{
WindowType* pControlWindow( getTypedControlWindow() );
pControlWindow->setControlHelper( m_aImplControl );
if ( _bDoSetHandlers )
{
pControlWindow->SetModifyHdl( LINK( &m_aImplControl, ControlHelper, ModifiedHdl ) );
pControlWindow->SetGetFocusHdl( LINK( &m_aImplControl, ControlHelper, GetFocusHdl ) );
pControlWindow->SetLoseFocusHdl( LINK( &m_aImplControl, ControlHelper, LoseFocusHdl ) );
}
m_aImplControl.autoSizeWindow();
}
//--------------------------------------------------------------------
template< class CONTROL_INTERFACE, class CONTROL_WINDOW >
inline ::sal_Int16 SAL_CALL CommonBehaviourControl< CONTROL_INTERFACE, CONTROL_WINDOW >::getControlType() throw (::com::sun::star::uno::RuntimeException)
{
return m_aImplControl.getControlType();
}
//--------------------------------------------------------------------
template< class CONTROL_INTERFACE, class CONTROL_WINDOW >
inline ::com::sun::star::uno::Reference< ::com::sun::star::inspection::XPropertyControlContext > SAL_CALL CommonBehaviourControl< CONTROL_INTERFACE, CONTROL_WINDOW >::getControlContext() throw (::com::sun::star::uno::RuntimeException)
{
return m_aImplControl.getControlContext();
}
//--------------------------------------------------------------------
template< class CONTROL_INTERFACE, class CONTROL_WINDOW >
inline void SAL_CALL CommonBehaviourControl< CONTROL_INTERFACE, CONTROL_WINDOW >::setControlContext( const ::com::sun::star::uno::Reference< ::com::sun::star::inspection::XPropertyControlContext >& _controlcontext ) throw (::com::sun::star::uno::RuntimeException)
{
m_aImplControl.setControlContext( _controlcontext );
}
//--------------------------------------------------------------------
template< class CONTROL_INTERFACE, class CONTROL_WINDOW >
inline ::com::sun::star::uno::Reference< ::com::sun::star::awt::XWindow > SAL_CALL CommonBehaviourControl< CONTROL_INTERFACE, CONTROL_WINDOW >::getControlWindow() throw (::com::sun::star::uno::RuntimeException)
{
return m_aImplControl.getControlWindow();
}
//--------------------------------------------------------------------
template< class CONTROL_INTERFACE, class CONTROL_WINDOW >
inline ::sal_Bool SAL_CALL CommonBehaviourControl< CONTROL_INTERFACE, CONTROL_WINDOW >::isModified( ) throw (::com::sun::star::uno::RuntimeException)
{
return m_aImplControl.isModified();
}
//--------------------------------------------------------------------
template< class CONTROL_INTERFACE, class CONTROL_WINDOW >
inline void SAL_CALL CommonBehaviourControl< CONTROL_INTERFACE, CONTROL_WINDOW >::notifyModifiedValue( ) throw (::com::sun::star::uno::RuntimeException)
{
m_aImplControl.notifyModifiedValue();
}
//--------------------------------------------------------------------
template< class CONTROL_INTERFACE, class CONTROL_WINDOW >
inline void SAL_CALL CommonBehaviourControl< CONTROL_INTERFACE, CONTROL_WINDOW >::disposing()
{
m_aImplControl.dispose();
}
//--------------------------------------------------------------------
template< class CONTROL_INTERFACE, class CONTROL_WINDOW >
inline void CommonBehaviourControl< CONTROL_INTERFACE, CONTROL_WINDOW >::modified()
{
m_aImplControl.setModified();
}
//--------------------------------------------------------------------
template< class CONTROL_INTERFACE, class CONTROL_WINDOW >
inline void CommonBehaviourControl< CONTROL_INTERFACE, CONTROL_WINDOW >::impl_checkDisposed_throw()
{
if ( ComponentBaseClass::rBHelper.bDisposed )
throw ::com::sun::star::lang::DisposedException( ::rtl::OUString(), *this );
}
//............................................................................
} // namespace pcr
//............................................................................
#endif // _EXTENSIONS_PROPCTRLR_COMMONCONTROL_HXX_
<|endoftext|> |
<commit_before>#include "exon.h"
#include <cstdlib>
#include <iostream>
#include <sstream>
#include <cassert>
#include <cstdio>
exon::exon(const string &s)
{
parse(s);
}
int exon::parse(const string &s)
{
char buf[10240];
stringstream sstr(s);
sstr>>buf;
seqname.assign(buf);
sstr>>buf;
source.assign(buf);
sstr>>buf;
feature.assign(buf);
sstr>>start>>end;
end++; // TODO check gtf end is inclusive
sstr>>buf;
if(buf[0] == '.') score = -1;
else score = atof(buf);
sstr>>buf;
strand = buf[0];
sstr>>buf;
frame = buf[0];
char buf2[10240];
while(sstr.eof() == false)
{
sstr>>buf>>buf2;
if(string(buf) == "transcript_id")
{
string ss(buf2);
transcript_id = ss.substr(1, ss.size() - 3);
}
else if(string(buf) == "gene_id")
{
string ss(buf2);
gene_id = ss.substr(1, ss.size() - 3);
}
else if(string(buf) == "expression")
{
string ss(buf2);
expression = (int32_t)(atoi(ss.substr(1, ss.size() - 2).c_str()));
}
}
return 0;
}
int exon::print() const
{
printf("%s\t%s\t%s\t%d\t%d\t%.1lf\t%c\t%c\ttranscript_id \"%s\"; gene_id \"%s\"; expression \"%d\"\n",
seqname.c_str(), source.c_str(), feature.c_str(), start, end, score, strand, frame,
transcript_id.c_str(), gene_id.c_str(), expression);
return 0;
}
bool exon::operator<(const exon &ge) const
{
if(start < ge.start) return true;
else return false;
}
int exon::length() const
{
assert(end > start);
return end - start;
}
<commit_msg>fix bug for extracting features in gtf file<commit_after>#include "exon.h"
#include <cstdlib>
#include <iostream>
#include <sstream>
#include <cassert>
#include <cstdio>
exon::exon(const string &s)
{
parse(s);
}
int exon::parse(const string &s)
{
char buf[10240];
stringstream sstr(s);
sstr>>buf;
seqname.assign(buf);
sstr>>buf;
source.assign(buf);
sstr>>buf;
feature.assign(buf);
sstr>>start>>end;
end++; // TODO check gtf end is inclusive
sstr>>buf;
if(buf[0] == '.') score = -1;
else score = atof(buf);
sstr>>buf;
strand = buf[0];
sstr>>buf;
frame = buf[0];
char buf2[10240];
while(sstr.eof() == false)
{
sstr>>buf;
sstr.getline(buf2, 10240, ';');
string k(buf2);
if(string(buf) == "" || k == "") break;
size_t p1 = k.find_first_of('"');
size_t p2 = k.find_last_of('"');
assert(p1 != string::npos);
assert(p2 != string::npos);
assert(p1 != p2);
string v = k.substr(p1 + 1, p2 - p1 - 1);
//printf(" |%s|%s|\n", buf, v.c_str());
if(string(buf) == "transcript_id") transcript_id = v;
else if(string(buf) == "gene_id") gene_id = v;
else if(string(buf) == "expression") expression = atoi(v.c_str());
}
return 0;
}
int exon::print() const
{
printf("%s\t%s\t%s\t%d\t%d\t%.1lf\t%c\t%c\ttranscript_id \"%s\"; gene_id \"%s\"; expression \"%d\"\n",
seqname.c_str(), source.c_str(), feature.c_str(), start, end, score, strand, frame,
transcript_id.c_str(), gene_id.c_str(), expression);
return 0;
}
bool exon::operator<(const exon &ge) const
{
if(start < ge.start) return true;
else return false;
}
int exon::length() const
{
assert(end > start);
return end - start;
}
<|endoftext|> |
<commit_before>/// Tests for tuple tranfers
/// (c) Koheron
#ifndef __TUPLE_TESTS_HPP__
#define __TUPLE_TESTS_HPP__
#include <tuple>
#include "../drivers/core/dev_mem.hpp" // Unused but needed for now
//> \description Tests for tuple tranfers
class TupleTests
{
public:
TupleTests(Klib::DevMem& dvm_unused_) {}
//> \io_type READ
std::tuple<int,
float,
double>
get_tuple()
{
return std::make_tuple(2, 3.14159F, 2345.678);
}
};
#endif // __TUPLE_TESTS_HPP__
<commit_msg>Update include path<commit_after>/// Tests for tuple tranfers
/// (c) Koheron
#ifndef __TUPLE_TESTS_HPP__
#define __TUPLE_TESTS_HPP__
#include <tuple>
#include "../drivers/dev_mem.hpp" // Unused but needed for now
//> \description Tests for tuple tranfers
class TupleTests
{
public:
TupleTests(Klib::DevMem& dvm_unused_) {}
//> \io_type READ
std::tuple<int,
float,
double>
get_tuple()
{
return std::make_tuple(2, 3.14159F, 2345.678);
}
};
#endif // __TUPLE_TESTS_HPP__
<|endoftext|> |
<commit_before>/*
-----------------------------------------------------------------------------
This source file is part of OGRE
(Object-oriented Graphics Rendering Engine)
For the latest info, see http://www.ogre3d.org/
Copyright (c) 2000-2006 Torus Knot Software Ltd
Also see acknowledgements in Readme.html
This program 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 of the License, or (at your option) any later
version.
This program 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 program; if not, write to the Free Software Foundation, Inc., 59 Temple
Place - Suite 330, Boston, MA 02111-1307, USA, or go to
http://www.gnu.org/copyleft/lesser.txt.
You may alternatively use this source under the terms of a specific version of
the OGRE Unrestricted License provided you have obtained such a license from
Torus Knot Software Ltd.
-----------------------------------------------------------------------------
*/
#include "OgreStableHeaders.h"
#include "OgreDynLib.h"
#include "OgreException.h"
#include "OgreLogManager.h"
#if OGRE_PLATFORM == OGRE_PLATFORM_WIN32
# define WIN32_LEAN_AND_MEAN
# define NOMINMAX // required to stop windows.h messing up std::min
# include <windows.h>
#endif
#if OGRE_PLATFORM == OGRE_PLATFORM_APPLE
# include "macPlugins.h"
#endif
namespace Ogre {
//-----------------------------------------------------------------------
DynLib::DynLib( const String& name )
{
mName = name;
m_hInst = NULL;
}
//-----------------------------------------------------------------------
DynLib::~DynLib()
{
}
//-----------------------------------------------------------------------
void DynLib::load()
{
// Log library load
LogManager::getSingleton().logMessage("Loading library " + mName);
String name = mName;
#if OGRE_PLATFORM == OGRE_PLATFORM_LINUX
// dlopen() does not add .so to the filename, like windows does for .dll
if (name.substr(name.length() - 3, 3) != ".so")
name += ".so";
#endif
#if OGRE_PLATFORM == OGRE_PLATFORM_APPLE
// dlopen() does not add .dylib to the filename, like windows does for .dll
if (name.substr(name.length() - 6, 6) != ".dylib")
name += ".dylib";
#endif
m_hInst = (DYNLIB_HANDLE)DYNLIB_LOAD( name.c_str() );
if( !m_hInst )
OGRE_EXCEPT(
Exception::ERR_INTERNAL_ERROR,
"Could not load dynamic library " + mName +
". System Error: " + dynlibError(),
"DynLib::load" );
}
//-----------------------------------------------------------------------
void DynLib::unload()
{
// Log library unload
LogManager::getSingleton().logMessage("Unloading library " + mName);
if( DYNLIB_UNLOAD( m_hInst ) )
{
OGRE_EXCEPT(
Exception::ERR_INTERNAL_ERROR,
"Could not unload dynamic library " + mName +
". System Error: " + dynlibError(),
"DynLib::unload");
}
}
//-----------------------------------------------------------------------
void* DynLib::getSymbol( const String& strName ) const throw()
{
return (void*)DYNLIB_GETSYM( m_hInst, strName.c_str() );
}
//-----------------------------------------------------------------------
String DynLib::dynlibError( void )
{
#if OGRE_PLATFORM == OGRE_PLATFORM_WIN32
LPVOID lpMsgBuf;
FormatMessage(
FORMAT_MESSAGE_ALLOCATE_BUFFER |
FORMAT_MESSAGE_FROM_SYSTEM |
FORMAT_MESSAGE_IGNORE_INSERTS,
NULL,
GetLastError(),
MAKELANGID(LANG_NEUTRAL, SUBLANG_DEFAULT),
(LPTSTR) &lpMsgBuf,
0,
NULL
);
String ret = (char*)lpMsgBuf;
// Free the buffer.
LocalFree( lpMsgBuf );
return ret;
#elif OGRE_PLATFORM == OGRE_PLATFORM_LINUX
return String(dlerror());
#elif OGRE_PLATFORM == OGRE_PLATFORM_APPLE
return String(mac_errorBundle());
#else
return String("");
#endif
}
}
<commit_msg>Add .dll to Win32 DynLib loading, this allows dlls to be loaded from relative paths without the suffix too<commit_after>/*
-----------------------------------------------------------------------------
This source file is part of OGRE
(Object-oriented Graphics Rendering Engine)
For the latest info, see http://www.ogre3d.org/
Copyright (c) 2000-2006 Torus Knot Software Ltd
Also see acknowledgements in Readme.html
This program 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 of the License, or (at your option) any later
version.
This program 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 program; if not, write to the Free Software Foundation, Inc., 59 Temple
Place - Suite 330, Boston, MA 02111-1307, USA, or go to
http://www.gnu.org/copyleft/lesser.txt.
You may alternatively use this source under the terms of a specific version of
the OGRE Unrestricted License provided you have obtained such a license from
Torus Knot Software Ltd.
-----------------------------------------------------------------------------
*/
#include "OgreStableHeaders.h"
#include "OgreDynLib.h"
#include "OgreException.h"
#include "OgreLogManager.h"
#if OGRE_PLATFORM == OGRE_PLATFORM_WIN32
# define WIN32_LEAN_AND_MEAN
# define NOMINMAX // required to stop windows.h messing up std::min
# include <windows.h>
#endif
#if OGRE_PLATFORM == OGRE_PLATFORM_APPLE
# include "macPlugins.h"
#endif
namespace Ogre {
//-----------------------------------------------------------------------
DynLib::DynLib( const String& name )
{
mName = name;
m_hInst = NULL;
}
//-----------------------------------------------------------------------
DynLib::~DynLib()
{
}
//-----------------------------------------------------------------------
void DynLib::load()
{
// Log library load
LogManager::getSingleton().logMessage("Loading library " + mName);
String name = mName;
#if OGRE_PLATFORM == OGRE_PLATFORM_LINUX
// dlopen() does not add .so to the filename, like windows does for .dll
if (name.substr(name.length() - 3, 3) != ".so")
name += ".so";
#elif OGRE_PLATFORM == OGRE_PLATFORM_APPLE
// dlopen() does not add .dylib to the filename, like windows does for .dll
if (name.substr(name.length() - 6, 6) != ".dylib")
name += ".dylib";
#elif OGRE_PLATFORM == OGRE_PLATFORM_WIN32
// Although LoadLibraryEx will add .dll itself when you only specify the library name,
// if you include a relative path then it does not. So, add it to be sure.
if (name.substr(name.length() - 4, 4) != ".dll")
name += ".dll";
#endif
m_hInst = (DYNLIB_HANDLE)DYNLIB_LOAD( name.c_str() );
if( !m_hInst )
OGRE_EXCEPT(
Exception::ERR_INTERNAL_ERROR,
"Could not load dynamic library " + mName +
". System Error: " + dynlibError(),
"DynLib::load" );
}
//-----------------------------------------------------------------------
void DynLib::unload()
{
// Log library unload
LogManager::getSingleton().logMessage("Unloading library " + mName);
if( DYNLIB_UNLOAD( m_hInst ) )
{
OGRE_EXCEPT(
Exception::ERR_INTERNAL_ERROR,
"Could not unload dynamic library " + mName +
". System Error: " + dynlibError(),
"DynLib::unload");
}
}
//-----------------------------------------------------------------------
void* DynLib::getSymbol( const String& strName ) const throw()
{
return (void*)DYNLIB_GETSYM( m_hInst, strName.c_str() );
}
//-----------------------------------------------------------------------
String DynLib::dynlibError( void )
{
#if OGRE_PLATFORM == OGRE_PLATFORM_WIN32
LPVOID lpMsgBuf;
FormatMessage(
FORMAT_MESSAGE_ALLOCATE_BUFFER |
FORMAT_MESSAGE_FROM_SYSTEM |
FORMAT_MESSAGE_IGNORE_INSERTS,
NULL,
GetLastError(),
MAKELANGID(LANG_NEUTRAL, SUBLANG_DEFAULT),
(LPTSTR) &lpMsgBuf,
0,
NULL
);
String ret = (char*)lpMsgBuf;
// Free the buffer.
LocalFree( lpMsgBuf );
return ret;
#elif OGRE_PLATFORM == OGRE_PLATFORM_LINUX
return String(dlerror());
#elif OGRE_PLATFORM == OGRE_PLATFORM_APPLE
return String(mac_errorBundle());
#else
return String("");
#endif
}
}
<|endoftext|> |
<commit_before>/****************************************************************************
*
* Copyright (c) 2012-2016 PX4 Development Team. All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
*
* 1. Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* 2. Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in
* the documentation and/or other materials provided with the
* distribution.
* 3. Neither the name PX4 nor the names of its contributors may be
* used to endorse or promote products derived from this software
* without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
* "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
* LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
* FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
* COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
* INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
* BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS
* OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED
* AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
* LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN
* ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
* POSSIBILITY OF SUCH DAMAGE.
*
****************************************************************************/
/**
* @file mixer_multirotor.cpp
*
* Multi-rotor mixers.
*/
#include <px4_config.h>
#include <sys/types.h>
#include <stdint.h>
#include <stdbool.h>
#include <stdlib.h>
#include <string.h>
#include <fcntl.h>
#include <poll.h>
#include <errno.h>
#include <stdio.h>
#include <math.h>
#include <unistd.h>
#include <math.h>
#include <px4iofirmware/protocol.h>
#include "mixer.h"
// This file is generated by the multi_tables script which is invoked during the build process
#include "mixer_multirotor.generated.h"
#define debug(fmt, args...) do { } while(0)
//#define debug(fmt, args...) do { printf("[mixer] " fmt "\n", ##args); } while(0)
//#include <debug.h>
//#define debug(fmt, args...) lowsyslog(fmt "\n", ##args)
/*
* Clockwise: 1
* Counter-clockwise: -1
*/
namespace
{
float constrain(float val, float min, float max)
{
return (val < min) ? min : ((val > max) ? max : val);
}
} // anonymous namespace
MultirotorMixer::MultirotorMixer(ControlCallback control_cb,
uintptr_t cb_handle,
MultirotorGeometry geometry,
float roll_scale,
float pitch_scale,
float yaw_scale,
float idle_speed) :
Mixer(control_cb, cb_handle),
_roll_scale(roll_scale),
_pitch_scale(pitch_scale),
_yaw_scale(yaw_scale),
_idle_speed(-1.0f + idle_speed * 2.0f), /* shift to output range here to avoid runtime calculation */
_limits_pub(),
_rotor_count(_config_rotor_count[(MultirotorGeometryUnderlyingType)geometry]),
_rotors(_config_index[(MultirotorGeometryUnderlyingType)geometry])
{
}
MultirotorMixer::~MultirotorMixer()
{
}
MultirotorMixer *
MultirotorMixer::from_text(Mixer::ControlCallback control_cb, uintptr_t cb_handle, const char *buf, unsigned &buflen)
{
MultirotorGeometry geometry;
char geomname[8];
int s[4];
int used;
/* enforce that the mixer ends with space or a new line */
for (int i = buflen - 1; i >= 0; i--) {
if (buf[i] == '\0') {
continue;
}
/* require a space or newline at the end of the buffer, fail on printable chars */
if (buf[i] == ' ' || buf[i] == '\n' || buf[i] == '\r') {
/* found a line ending or space, so no split symbols / numbers. good. */
break;
} else {
debug("simple parser rejected: No newline / space at end of buf. (#%d/%d: 0x%02x)", i, buflen - 1, buf[i]);
return nullptr;
}
}
if (sscanf(buf, "R: %s %d %d %d %d%n", geomname, &s[0], &s[1], &s[2], &s[3], &used) != 5) {
debug("multirotor parse failed on '%s'", buf);
return nullptr;
}
if (used > (int)buflen) {
debug("OVERFLOW: multirotor spec used %d of %u", used, buflen);
return nullptr;
}
buf = skipline(buf, buflen);
if (buf == nullptr) {
debug("no line ending, line is incomplete");
return nullptr;
}
debug("remaining in buf: %d, first char: %c", buflen, buf[0]);
if (!strcmp(geomname, "4+")) {
geometry = MultirotorGeometry::QUAD_PLUS;
} else if (!strcmp(geomname, "4x")) {
geometry = MultirotorGeometry::QUAD_X;
} else if (!strcmp(geomname, "4h")) {
geometry = MultirotorGeometry::QUAD_H;
} else if (!strcmp(geomname, "4v")) {
geometry = MultirotorGeometry::QUAD_V;
} else if (!strcmp(geomname, "4w")) {
geometry = MultirotorGeometry::QUAD_WIDE;
} else if (!strcmp(geomname, "4dc")) {
geometry = MultirotorGeometry::QUAD_DEADCAT;
} else if (!strcmp(geomname, "6+")) {
geometry = MultirotorGeometry::HEX_PLUS;
} else if (!strcmp(geomname, "6x")) {
geometry = MultirotorGeometry::HEX_X;
} else if (!strcmp(geomname, "6c")) {
geometry = MultirotorGeometry::HEX_COX;
} else if (!strcmp(geomname, "8+")) {
geometry = MultirotorGeometry::OCTA_PLUS;
} else if (!strcmp(geomname, "8x")) {
geometry = MultirotorGeometry::OCTA_X;
} else if (!strcmp(geomname, "8c")) {
geometry = MultirotorGeometry::OCTA_COX;
#if 0
} else if (!strcmp(geomname, "8cw")) {
geometry = MultirotorGeometry::OCTA_COX_WIDE;
#endif
} else if (!strcmp(geomname, "2-")) {
geometry = MultirotorGeometry::TWIN_ENGINE;
} else if (!strcmp(geomname, "3y")) {
geometry = MultirotorGeometry::TRI_Y;
} else {
debug("unrecognised geometry '%s'", geomname);
return nullptr;
}
debug("adding multirotor mixer '%s'", geomname);
return new MultirotorMixer(
control_cb,
cb_handle,
geometry,
s[0] / 10000.0f,
s[1] / 10000.0f,
s[2] / 10000.0f,
s[3] / 10000.0f);
}
unsigned
MultirotorMixer::mix(float *outputs, unsigned space, uint16_t *status_reg)
{
/* Summary of mixing strategy:
1) mix roll, pitch and thrust without yaw.
2) if some outputs violate range [0,1] then try to shift all outputs to minimize violation ->
increase or decrease total thrust (boost). The total increase or decrease of thrust is limited
(max_thrust_diff). If after the shift some outputs still violate the bounds then scale roll & pitch.
In case there is violation at the lower and upper bound then try to shift such that violation is equal
on both sides.
3) mix in yaw and scale if it leads to limit violation.
4) scale all outputs to range [idle_speed,1]
*/
float roll = constrain(get_control(0, 0) * _roll_scale, -1.0f, 1.0f);
float pitch = constrain(get_control(0, 1) * _pitch_scale, -1.0f, 1.0f);
float yaw = constrain(get_control(0, 2) * _yaw_scale, -1.0f, 1.0f);
float thrust = constrain(get_control(0, 3), 0.0f, 1.0f);
float min_out = 0.0f;
float max_out = 0.0f;
// clean register for saturation status flags
if (status_reg != NULL) {
(*status_reg) = 0;
}
// thrust boost parameters
float thrust_increase_factor = 1.5f;
float thrust_decrease_factor = 0.6f;
/* perform initial mix pass yielding unbounded outputs, ignore yaw */
for (unsigned i = 0; i < _rotor_count; i++) {
float out = roll * _rotors[i].roll_scale +
pitch * _rotors[i].pitch_scale +
thrust;
out *= _rotors[i].out_scale;
/* calculate min and max output values */
if (out < min_out) {
min_out = out;
}
if (out > max_out) {
max_out = out;
}
outputs[i] = out;
}
float boost = 0.0f; // value added to demanded thrust (can also be negative)
float roll_pitch_scale = 1.0f; // scale for demanded roll and pitch
if (min_out < 0.0f && max_out < 1.0f && -min_out <= 1.0f - max_out) {
float max_thrust_diff = thrust * thrust_increase_factor - thrust;
if (max_thrust_diff >= -min_out) {
boost = -min_out;
} else {
boost = max_thrust_diff;
roll_pitch_scale = (thrust + boost) / (thrust - min_out);
}
} else if (max_out > 1.0f && min_out > 0.0f && min_out >= max_out - 1.0f) {
float max_thrust_diff = thrust - thrust_decrease_factor * thrust;
if (max_thrust_diff >= max_out - 1.0f) {
boost = -(max_out - 1.0f);
} else {
boost = -max_thrust_diff;
roll_pitch_scale = (1 - (thrust + boost)) / (max_out - thrust);
}
} else if (min_out < 0.0f && max_out < 1.0f && -min_out > 1.0f - max_out) {
float max_thrust_diff = thrust * thrust_increase_factor - thrust;
boost = constrain(-min_out - (1.0f - max_out) / 2.0f, 0.0f, max_thrust_diff);
roll_pitch_scale = (thrust + boost) / (thrust - min_out);
} else if (max_out > 1.0f && min_out > 0.0f && min_out < max_out - 1.0f) {
float max_thrust_diff = thrust - thrust_decrease_factor * thrust;
boost = constrain(-(max_out - 1.0f - min_out) / 2.0f, -max_thrust_diff, 0.0f);
roll_pitch_scale = (1 - (thrust + boost)) / (max_out - thrust);
} else if (min_out < 0.0f && max_out > 1.0f) {
boost = constrain(-(max_out - 1.0f + min_out) / 2.0f, thrust_decrease_factor * thrust - thrust,
thrust_increase_factor * thrust - thrust);
roll_pitch_scale = (thrust + boost) / (thrust - min_out);
}
// notify if saturation has occurred
if (min_out < 0.0f) {
if (status_reg != NULL) {
(*status_reg) |= PX4IO_P_STATUS_MIXER_LOWER_LIMIT;
}
}
if (max_out > 1.0f) {
if (status_reg != NULL) {
(*status_reg) |= PX4IO_P_STATUS_MIXER_UPPER_LIMIT;
}
}
// mix again but now with thrust boost, scale roll/pitch and also add yaw
for (unsigned i = 0; i < _rotor_count; i++) {
float out = (roll * _rotors[i].roll_scale +
pitch * _rotors[i].pitch_scale) * roll_pitch_scale +
yaw * _rotors[i].yaw_scale +
thrust + boost;
out *= _rotors[i].out_scale;
// scale yaw if it violates limits. inform about yaw limit reached
if (out < 0.0f) {
if (fabsf(_rotors[i].yaw_scale) <= FLT_EPSILON) {
yaw = 0.0f;
} else {
yaw = -((roll * _rotors[i].roll_scale + pitch * _rotors[i].pitch_scale) *
roll_pitch_scale + thrust + boost) / _rotors[i].yaw_scale;
}
if (status_reg != NULL) {
(*status_reg) |= PX4IO_P_STATUS_MIXER_YAW_LIMIT;
}
} else if (out > 1.0f) {
// allow to reduce thrust to get some yaw response
float thrust_reduction = fminf(0.15f, out - 1.0f);
thrust -= thrust_reduction;
if (fabsf(_rotors[i].yaw_scale) <= FLT_EPSILON) {
yaw = 0.0f;
} else {
yaw = (1.0f - ((roll * _rotors[i].roll_scale + pitch * _rotors[i].pitch_scale) *
roll_pitch_scale + thrust + boost)) / _rotors[i].yaw_scale;
}
if (status_reg != NULL) {
(*status_reg) |= PX4IO_P_STATUS_MIXER_YAW_LIMIT;
}
}
}
/* add yaw and scale outputs to range idle_speed...1 */
for (unsigned i = 0; i < _rotor_count; i++) {
outputs[i] = (roll * _rotors[i].roll_scale +
pitch * _rotors[i].pitch_scale) * roll_pitch_scale +
yaw * _rotors[i].yaw_scale +
thrust + boost;
outputs[i] = constrain(_idle_speed + (outputs[i] * (1.0f - _idle_speed)), _idle_speed, 1.0f);
}
return _rotor_count;
}
void
MultirotorMixer::groups_required(uint32_t &groups)
{
/* XXX for now, hardcoded to indexes 0-3 in control group zero */
groups |= (1 << 0);
}
<commit_msg>mixer multirotor: initialise min_out with correct value<commit_after>/****************************************************************************
*
* Copyright (c) 2012-2016 PX4 Development Team. All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
*
* 1. Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* 2. Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in
* the documentation and/or other materials provided with the
* distribution.
* 3. Neither the name PX4 nor the names of its contributors may be
* used to endorse or promote products derived from this software
* without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
* "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
* LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
* FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
* COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
* INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
* BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS
* OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED
* AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
* LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN
* ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
* POSSIBILITY OF SUCH DAMAGE.
*
****************************************************************************/
/**
* @file mixer_multirotor.cpp
*
* Multi-rotor mixers.
*/
#include <px4_config.h>
#include <sys/types.h>
#include <stdint.h>
#include <stdbool.h>
#include <stdlib.h>
#include <string.h>
#include <fcntl.h>
#include <poll.h>
#include <errno.h>
#include <stdio.h>
#include <math.h>
#include <unistd.h>
#include <math.h>
#include <px4iofirmware/protocol.h>
#include "mixer.h"
// This file is generated by the multi_tables script which is invoked during the build process
#include "mixer_multirotor.generated.h"
#define debug(fmt, args...) do { } while(0)
//#define debug(fmt, args...) do { printf("[mixer] " fmt "\n", ##args); } while(0)
//#include <debug.h>
//#define debug(fmt, args...) lowsyslog(fmt "\n", ##args)
/*
* Clockwise: 1
* Counter-clockwise: -1
*/
namespace
{
float constrain(float val, float min, float max)
{
return (val < min) ? min : ((val > max) ? max : val);
}
} // anonymous namespace
MultirotorMixer::MultirotorMixer(ControlCallback control_cb,
uintptr_t cb_handle,
MultirotorGeometry geometry,
float roll_scale,
float pitch_scale,
float yaw_scale,
float idle_speed) :
Mixer(control_cb, cb_handle),
_roll_scale(roll_scale),
_pitch_scale(pitch_scale),
_yaw_scale(yaw_scale),
_idle_speed(-1.0f + idle_speed * 2.0f), /* shift to output range here to avoid runtime calculation */
_limits_pub(),
_rotor_count(_config_rotor_count[(MultirotorGeometryUnderlyingType)geometry]),
_rotors(_config_index[(MultirotorGeometryUnderlyingType)geometry])
{
}
MultirotorMixer::~MultirotorMixer()
{
}
MultirotorMixer *
MultirotorMixer::from_text(Mixer::ControlCallback control_cb, uintptr_t cb_handle, const char *buf, unsigned &buflen)
{
MultirotorGeometry geometry;
char geomname[8];
int s[4];
int used;
/* enforce that the mixer ends with space or a new line */
for (int i = buflen - 1; i >= 0; i--) {
if (buf[i] == '\0') {
continue;
}
/* require a space or newline at the end of the buffer, fail on printable chars */
if (buf[i] == ' ' || buf[i] == '\n' || buf[i] == '\r') {
/* found a line ending or space, so no split symbols / numbers. good. */
break;
} else {
debug("simple parser rejected: No newline / space at end of buf. (#%d/%d: 0x%02x)", i, buflen - 1, buf[i]);
return nullptr;
}
}
if (sscanf(buf, "R: %s %d %d %d %d%n", geomname, &s[0], &s[1], &s[2], &s[3], &used) != 5) {
debug("multirotor parse failed on '%s'", buf);
return nullptr;
}
if (used > (int)buflen) {
debug("OVERFLOW: multirotor spec used %d of %u", used, buflen);
return nullptr;
}
buf = skipline(buf, buflen);
if (buf == nullptr) {
debug("no line ending, line is incomplete");
return nullptr;
}
debug("remaining in buf: %d, first char: %c", buflen, buf[0]);
if (!strcmp(geomname, "4+")) {
geometry = MultirotorGeometry::QUAD_PLUS;
} else if (!strcmp(geomname, "4x")) {
geometry = MultirotorGeometry::QUAD_X;
} else if (!strcmp(geomname, "4h")) {
geometry = MultirotorGeometry::QUAD_H;
} else if (!strcmp(geomname, "4v")) {
geometry = MultirotorGeometry::QUAD_V;
} else if (!strcmp(geomname, "4w")) {
geometry = MultirotorGeometry::QUAD_WIDE;
} else if (!strcmp(geomname, "4dc")) {
geometry = MultirotorGeometry::QUAD_DEADCAT;
} else if (!strcmp(geomname, "6+")) {
geometry = MultirotorGeometry::HEX_PLUS;
} else if (!strcmp(geomname, "6x")) {
geometry = MultirotorGeometry::HEX_X;
} else if (!strcmp(geomname, "6c")) {
geometry = MultirotorGeometry::HEX_COX;
} else if (!strcmp(geomname, "8+")) {
geometry = MultirotorGeometry::OCTA_PLUS;
} else if (!strcmp(geomname, "8x")) {
geometry = MultirotorGeometry::OCTA_X;
} else if (!strcmp(geomname, "8c")) {
geometry = MultirotorGeometry::OCTA_COX;
#if 0
} else if (!strcmp(geomname, "8cw")) {
geometry = MultirotorGeometry::OCTA_COX_WIDE;
#endif
} else if (!strcmp(geomname, "2-")) {
geometry = MultirotorGeometry::TWIN_ENGINE;
} else if (!strcmp(geomname, "3y")) {
geometry = MultirotorGeometry::TRI_Y;
} else {
debug("unrecognised geometry '%s'", geomname);
return nullptr;
}
debug("adding multirotor mixer '%s'", geomname);
return new MultirotorMixer(
control_cb,
cb_handle,
geometry,
s[0] / 10000.0f,
s[1] / 10000.0f,
s[2] / 10000.0f,
s[3] / 10000.0f);
}
unsigned
MultirotorMixer::mix(float *outputs, unsigned space, uint16_t *status_reg)
{
/* Summary of mixing strategy:
1) mix roll, pitch and thrust without yaw.
2) if some outputs violate range [0,1] then try to shift all outputs to minimize violation ->
increase or decrease total thrust (boost). The total increase or decrease of thrust is limited
(max_thrust_diff). If after the shift some outputs still violate the bounds then scale roll & pitch.
In case there is violation at the lower and upper bound then try to shift such that violation is equal
on both sides.
3) mix in yaw and scale if it leads to limit violation.
4) scale all outputs to range [idle_speed,1]
*/
float roll = constrain(get_control(0, 0) * _roll_scale, -1.0f, 1.0f);
float pitch = constrain(get_control(0, 1) * _pitch_scale, -1.0f, 1.0f);
float yaw = constrain(get_control(0, 2) * _yaw_scale, -1.0f, 1.0f);
float thrust = constrain(get_control(0, 3), 0.0f, 1.0f);
float min_out = 1.0f;
float max_out = 0.0f;
// clean register for saturation status flags
if (status_reg != NULL) {
(*status_reg) = 0;
}
// thrust boost parameters
float thrust_increase_factor = 1.5f;
float thrust_decrease_factor = 0.6f;
/* perform initial mix pass yielding unbounded outputs, ignore yaw */
for (unsigned i = 0; i < _rotor_count; i++) {
float out = roll * _rotors[i].roll_scale +
pitch * _rotors[i].pitch_scale +
thrust;
out *= _rotors[i].out_scale;
/* calculate min and max output values */
if (out < min_out) {
min_out = out;
}
if (out > max_out) {
max_out = out;
}
outputs[i] = out;
}
float boost = 0.0f; // value added to demanded thrust (can also be negative)
float roll_pitch_scale = 1.0f; // scale for demanded roll and pitch
if (min_out < 0.0f && max_out < 1.0f && -min_out <= 1.0f - max_out) {
float max_thrust_diff = thrust * thrust_increase_factor - thrust;
if (max_thrust_diff >= -min_out) {
boost = -min_out;
} else {
boost = max_thrust_diff;
roll_pitch_scale = (thrust + boost) / (thrust - min_out);
}
} else if (max_out > 1.0f && min_out > 0.0f && min_out >= max_out - 1.0f) {
float max_thrust_diff = thrust - thrust_decrease_factor * thrust;
if (max_thrust_diff >= max_out - 1.0f) {
boost = -(max_out - 1.0f);
} else {
boost = -max_thrust_diff;
roll_pitch_scale = (1 - (thrust + boost)) / (max_out - thrust);
}
} else if (min_out < 0.0f && max_out < 1.0f && -min_out > 1.0f - max_out) {
float max_thrust_diff = thrust * thrust_increase_factor - thrust;
boost = constrain(-min_out - (1.0f - max_out) / 2.0f, 0.0f, max_thrust_diff);
roll_pitch_scale = (thrust + boost) / (thrust - min_out);
} else if (max_out > 1.0f && min_out > 0.0f && min_out < max_out - 1.0f) {
float max_thrust_diff = thrust - thrust_decrease_factor * thrust;
boost = constrain(-(max_out - 1.0f - min_out) / 2.0f, -max_thrust_diff, 0.0f);
roll_pitch_scale = (1 - (thrust + boost)) / (max_out - thrust);
} else if (min_out < 0.0f && max_out > 1.0f) {
boost = constrain(-(max_out - 1.0f + min_out) / 2.0f, thrust_decrease_factor * thrust - thrust,
thrust_increase_factor * thrust - thrust);
roll_pitch_scale = (thrust + boost) / (thrust - min_out);
}
// notify if saturation has occurred
if (min_out < 0.0f) {
if (status_reg != NULL) {
(*status_reg) |= PX4IO_P_STATUS_MIXER_LOWER_LIMIT;
}
}
if (max_out > 1.0f) {
if (status_reg != NULL) {
(*status_reg) |= PX4IO_P_STATUS_MIXER_UPPER_LIMIT;
}
}
// mix again but now with thrust boost, scale roll/pitch and also add yaw
for (unsigned i = 0; i < _rotor_count; i++) {
float out = (roll * _rotors[i].roll_scale +
pitch * _rotors[i].pitch_scale) * roll_pitch_scale +
yaw * _rotors[i].yaw_scale +
thrust + boost;
out *= _rotors[i].out_scale;
// scale yaw if it violates limits. inform about yaw limit reached
if (out < 0.0f) {
if (fabsf(_rotors[i].yaw_scale) <= FLT_EPSILON) {
yaw = 0.0f;
} else {
yaw = -((roll * _rotors[i].roll_scale + pitch * _rotors[i].pitch_scale) *
roll_pitch_scale + thrust + boost) / _rotors[i].yaw_scale;
}
if (status_reg != NULL) {
(*status_reg) |= PX4IO_P_STATUS_MIXER_YAW_LIMIT;
}
} else if (out > 1.0f) {
// allow to reduce thrust to get some yaw response
float thrust_reduction = fminf(0.15f, out - 1.0f);
thrust -= thrust_reduction;
if (fabsf(_rotors[i].yaw_scale) <= FLT_EPSILON) {
yaw = 0.0f;
} else {
yaw = (1.0f - ((roll * _rotors[i].roll_scale + pitch * _rotors[i].pitch_scale) *
roll_pitch_scale + thrust + boost)) / _rotors[i].yaw_scale;
}
if (status_reg != NULL) {
(*status_reg) |= PX4IO_P_STATUS_MIXER_YAW_LIMIT;
}
}
}
/* add yaw and scale outputs to range idle_speed...1 */
for (unsigned i = 0; i < _rotor_count; i++) {
outputs[i] = (roll * _rotors[i].roll_scale +
pitch * _rotors[i].pitch_scale) * roll_pitch_scale +
yaw * _rotors[i].yaw_scale +
thrust + boost;
outputs[i] = constrain(_idle_speed + (outputs[i] * (1.0f - _idle_speed)), _idle_speed, 1.0f);
}
return _rotor_count;
}
void
MultirotorMixer::groups_required(uint32_t &groups)
{
/* XXX for now, hardcoded to indexes 0-3 in control group zero */
groups |= (1 << 0);
}
<|endoftext|> |
<commit_before>/*************************************************************************
*
* $RCSfile: treechangefactory.cxx,v $
*
* $Revision: 1.4 $
*
* last change: $Author: hr $ $Date: 2003-03-19 16:19:38 $
*
* The Contents of this file are made available subject to the terms of
* either of the following licenses
*
* - GNU Lesser General Public License Version 2.1
* - Sun Industry Standards Source License Version 1.1
*
* Sun Microsystems Inc., October, 2000
*
* GNU Lesser General Public License Version 2.1
* =============================================
* Copyright 2000 by Sun Microsystems, Inc.
* 901 San Antonio Road, Palo Alto, CA 94303, USA
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License version 2.1, as published by the Free Software Foundation.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston,
* MA 02111-1307 USA
*
*
* Sun Industry Standards Source License Version 1.1
* =================================================
* The contents of this file are subject to the Sun Industry Standards
* Source License Version 1.1 (the "License"); You may not use this file
* except in compliance with the License. You may obtain a copy of the
* License at http://www.openoffice.org/license.html.
*
* Software provided under this License is provided on an "AS IS" basis,
* WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING,
* WITHOUT LIMITATION, WARRANTIES THAT THE SOFTWARE IS FREE OF DEFECTS,
* MERCHANTABLE, FIT FOR A PARTICULAR PURPOSE, OR NON-INFRINGING.
* See the License for the specific provisions governing your rights and
* obligations concerning the Software.
*
* The Initial Developer of the Original Code is: Sun Microsystems, Inc.
*
* Copyright: 2000 by Sun Microsystems, Inc.
*
* All Rights Reserved.
*
* Contributor(s): _______________________________________
*
*
************************************************************************/
#include <stdio.h>
#include "treechangefactory.hxx"
#ifndef CONFIGMGR_CHANGE_HXX
#include "change.hxx"
#endif
#ifndef CONFIGMGR_CONFIGPATH_HXX_
#include "configpath.hxx"
#endif
namespace configmgr
{
//= dummy helpe ============================================================
bool isGenericSetElementType(OUString const& _aElementType)
{
return !! _aElementType.equals( getGenericSetElementType().toString() );
}
bool isDummySetElementModule(OUString const& _aElementModule)
{
return !! _aElementModule.equals( getDummySetElementModule().toString() );
}
configuration::Name getGenericSetElementType()
{
using namespace configuration;
static const Name c_aGenericTypeName =
makeName( OUString(RTL_CONSTASCII_USTRINGPARAM("*")), Name::NoValidate() );
return c_aGenericTypeName;
}
configuration::Name getDummySetElementModule()
{
using namespace configuration;
static const Name c_aDummyModuleName =
makeName( OUString(RTL_CONSTASCII_USTRINGPARAM("cfg:dummy-change")), Name::NoValidate() );
return c_aDummyModuleName;
}
//= static default ============================================================
OTreeChangeFactory& getDefaultTreeChangeFactory()
{
static OTreeChangeFactory aDefaultFactory;
return aDefaultFactory;
}
//= ValueNodes ============================================================
std::auto_ptr<ValueChange> OTreeChangeFactory::createValueChange(
Name const& _aName,
node::Attributes _aAttrs,
ValueChange::Mode _eMode,
uno::Any const& _aNewValue,
uno::Any const& _aOldValue
)
{
return std::auto_ptr<ValueChange>(new ValueChange(_aName,_aAttrs,_eMode,_aNewValue,_aOldValue));
}
//-----------------------------------------------
std::auto_ptr<ValueChange> OTreeChangeFactory::createValueChange(ValueNode const& _aNewValue, bool _bWasDefault)
{
Name aName = _aNewValue.getName();
uno::Any aValue = _aNewValue.getValue();
node::Attributes aAttrs = _aNewValue.getAttributes();
ValueChange::Mode eMode = aAttrs.isDefault() ?
_bWasDefault ? ValueChange::changeDefault : ValueChange:: setToDefault:
_bWasDefault ? ValueChange::wasDefault : ValueChange::changeValue;
if (aValue.hasValue())
{
return std::auto_ptr<ValueChange>(new ValueChange(aName,aAttrs,eMode,aValue));
}
else
{
return std::auto_ptr<ValueChange>(new ValueChange(aName,aAttrs,eMode,_aNewValue.getValueType()));
}
}
//-----------------------------------------------
std::auto_ptr<ValueChange> OTreeChangeFactory::createValueChange(
uno::Any const& _aNewValue,
ValueNode const& _aOldValue
)
{
return std::auto_ptr<ValueChange>(new ValueChange(_aNewValue,_aOldValue));
}
//-----------------------------------------------
std::auto_ptr<ValueChange> OTreeChangeFactory::createValueChange(
ValueChange::SetToDefault _aSetToDefault,
ValueNode const& _aOldValue
)
{
return std::auto_ptr<ValueChange>(new ValueChange(_aSetToDefault,_aOldValue));
}
//= SubtreeChanges ============================================================
std::auto_ptr<SubtreeChange> OTreeChangeFactory::createDummyChange(
configuration::Name const& _aName,
configuration::Name const& _aElementTypeName)
{
std::auto_ptr<SubtreeChange> pResult;
if (_aElementTypeName.isEmpty())
{
pResult.reset( new SubtreeChange(_aName.toString(),node::Attributes()) );
}
else
{
pResult.reset( new SubtreeChange(_aName.toString(),
_aElementTypeName.toString(),
getDummySetElementModule().toString(),
node::Attributes()) );
}
return pResult;
}
//-----------------------------------------------
std::auto_ptr<SubtreeChange> OTreeChangeFactory::createGroupNodeChange(
Name const& _aName,
node::Attributes _aAttrs,
bool _bToDefault)
{
return std::auto_ptr<SubtreeChange>(new SubtreeChange(_aName,_aAttrs,_bToDefault));
}
//-----------------------------------------------
std::auto_ptr<SubtreeChange> OTreeChangeFactory::createSetNodeChange(
Name const& _aName,
Name const& _aTemplateName,
Name const& _aTemplateModule,
node::Attributes _aAttrs,
bool _bToDefault)
{
return std::auto_ptr<SubtreeChange>(new SubtreeChange(_aName,
_aTemplateName,
_aTemplateModule,
_aAttrs,_bToDefault));
}
//-----------------------------------------------
//= Set Changes ============================================================
std::auto_ptr<AddNode> OTreeChangeFactory::createAddNodeChange(
data::TreeSegment const & _aNewTree,
Name const& _aName,
bool _bToDefault)
{
return std::auto_ptr<AddNode>(new AddNode(_aNewTree,_aName,_bToDefault));
}
//-----------------------------------------------
std::auto_ptr<RemoveNode> OTreeChangeFactory::createRemoveNodeChange(
Name const& _aName,
bool _bToDefault)
{
return std::auto_ptr<RemoveNode>(new RemoveNode(_aName,_bToDefault));
}
//-----------------------------------------------
} // namespace configmgr
<commit_msg>INTEGRATION: CWS ooo19126 (1.4.194); FILE MERGED 2005/09/05 17:05:09 rt 1.4.194.1: #i54170# Change license header: remove SISSL<commit_after>/*************************************************************************
*
* OpenOffice.org - a multi-platform office productivity suite
*
* $RCSfile: treechangefactory.cxx,v $
*
* $Revision: 1.5 $
*
* last change: $Author: rt $ $Date: 2005-09-08 04:20:08 $
*
* 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
*
************************************************************************/
#include <stdio.h>
#include "treechangefactory.hxx"
#ifndef CONFIGMGR_CHANGE_HXX
#include "change.hxx"
#endif
#ifndef CONFIGMGR_CONFIGPATH_HXX_
#include "configpath.hxx"
#endif
namespace configmgr
{
//= dummy helpe ============================================================
bool isGenericSetElementType(OUString const& _aElementType)
{
return !! _aElementType.equals( getGenericSetElementType().toString() );
}
bool isDummySetElementModule(OUString const& _aElementModule)
{
return !! _aElementModule.equals( getDummySetElementModule().toString() );
}
configuration::Name getGenericSetElementType()
{
using namespace configuration;
static const Name c_aGenericTypeName =
makeName( OUString(RTL_CONSTASCII_USTRINGPARAM("*")), Name::NoValidate() );
return c_aGenericTypeName;
}
configuration::Name getDummySetElementModule()
{
using namespace configuration;
static const Name c_aDummyModuleName =
makeName( OUString(RTL_CONSTASCII_USTRINGPARAM("cfg:dummy-change")), Name::NoValidate() );
return c_aDummyModuleName;
}
//= static default ============================================================
OTreeChangeFactory& getDefaultTreeChangeFactory()
{
static OTreeChangeFactory aDefaultFactory;
return aDefaultFactory;
}
//= ValueNodes ============================================================
std::auto_ptr<ValueChange> OTreeChangeFactory::createValueChange(
Name const& _aName,
node::Attributes _aAttrs,
ValueChange::Mode _eMode,
uno::Any const& _aNewValue,
uno::Any const& _aOldValue
)
{
return std::auto_ptr<ValueChange>(new ValueChange(_aName,_aAttrs,_eMode,_aNewValue,_aOldValue));
}
//-----------------------------------------------
std::auto_ptr<ValueChange> OTreeChangeFactory::createValueChange(ValueNode const& _aNewValue, bool _bWasDefault)
{
Name aName = _aNewValue.getName();
uno::Any aValue = _aNewValue.getValue();
node::Attributes aAttrs = _aNewValue.getAttributes();
ValueChange::Mode eMode = aAttrs.isDefault() ?
_bWasDefault ? ValueChange::changeDefault : ValueChange:: setToDefault:
_bWasDefault ? ValueChange::wasDefault : ValueChange::changeValue;
if (aValue.hasValue())
{
return std::auto_ptr<ValueChange>(new ValueChange(aName,aAttrs,eMode,aValue));
}
else
{
return std::auto_ptr<ValueChange>(new ValueChange(aName,aAttrs,eMode,_aNewValue.getValueType()));
}
}
//-----------------------------------------------
std::auto_ptr<ValueChange> OTreeChangeFactory::createValueChange(
uno::Any const& _aNewValue,
ValueNode const& _aOldValue
)
{
return std::auto_ptr<ValueChange>(new ValueChange(_aNewValue,_aOldValue));
}
//-----------------------------------------------
std::auto_ptr<ValueChange> OTreeChangeFactory::createValueChange(
ValueChange::SetToDefault _aSetToDefault,
ValueNode const& _aOldValue
)
{
return std::auto_ptr<ValueChange>(new ValueChange(_aSetToDefault,_aOldValue));
}
//= SubtreeChanges ============================================================
std::auto_ptr<SubtreeChange> OTreeChangeFactory::createDummyChange(
configuration::Name const& _aName,
configuration::Name const& _aElementTypeName)
{
std::auto_ptr<SubtreeChange> pResult;
if (_aElementTypeName.isEmpty())
{
pResult.reset( new SubtreeChange(_aName.toString(),node::Attributes()) );
}
else
{
pResult.reset( new SubtreeChange(_aName.toString(),
_aElementTypeName.toString(),
getDummySetElementModule().toString(),
node::Attributes()) );
}
return pResult;
}
//-----------------------------------------------
std::auto_ptr<SubtreeChange> OTreeChangeFactory::createGroupNodeChange(
Name const& _aName,
node::Attributes _aAttrs,
bool _bToDefault)
{
return std::auto_ptr<SubtreeChange>(new SubtreeChange(_aName,_aAttrs,_bToDefault));
}
//-----------------------------------------------
std::auto_ptr<SubtreeChange> OTreeChangeFactory::createSetNodeChange(
Name const& _aName,
Name const& _aTemplateName,
Name const& _aTemplateModule,
node::Attributes _aAttrs,
bool _bToDefault)
{
return std::auto_ptr<SubtreeChange>(new SubtreeChange(_aName,
_aTemplateName,
_aTemplateModule,
_aAttrs,_bToDefault));
}
//-----------------------------------------------
//= Set Changes ============================================================
std::auto_ptr<AddNode> OTreeChangeFactory::createAddNodeChange(
data::TreeSegment const & _aNewTree,
Name const& _aName,
bool _bToDefault)
{
return std::auto_ptr<AddNode>(new AddNode(_aNewTree,_aName,_bToDefault));
}
//-----------------------------------------------
std::auto_ptr<RemoveNode> OTreeChangeFactory::createRemoveNodeChange(
Name const& _aName,
bool _bToDefault)
{
return std::auto_ptr<RemoveNode>(new RemoveNode(_aName,_bToDefault));
}
//-----------------------------------------------
} // namespace configmgr
<|endoftext|> |
<commit_before>// Copyright (c) 2012 Plenluno All rights reserved.
#include <algorithm>
#include "libj/js_array_buffer.h"
#include "libj/string.h"
namespace libj {
class JsArrayBufferImpl : public JsArrayBuffer {
private:
static const union endian_u {
UShort one;
UByte isLittle;
} endian;
template <typename T>
T load(Size byteOffset, Boolean littleEndian) const {
Boolean swap = endian.isLittle != littleEndian;
if (swap) {
union {
T w;
UByte b[sizeof(T)];
} d;
const UByte* src = reinterpret_cast<const UByte*>(buf64_);
src += byteOffset;
UByte* dst = d.b + sizeof(T) - 1;
for (Size i = 0; i < sizeof(T); i++)
*dst-- = *src++;
return d.w;
} else {
const T* buf = reinterpret_cast<const T*>(buf64_);
Size idx = byteOffset / sizeof(T);
Size mod = byteOffset % sizeof(T);
T d0 = buf[idx];
if (mod) {
T d1 = buf[idx + 1];
Size sh = mod * 8;
if (endian.isLittle) {
d0 = d0 >> sh;
d1 = d1 << (8 * sizeof(T) - sh);
} else {
d0 = d0 << sh;
d1 = d1 >> (8 * sizeof(T) - sh);
}
d0 = d0 | d1;
}
return d0;
}
}
template <typename T>
void store(Size byteOffset, T value, Boolean littleEndian) {
Boolean swap = endian.isLittle != littleEndian;
if (swap || byteOffset % sizeof(T)) {
union {
T w;
UByte b[sizeof(T)];
} d;
d.w = value;
UByte* dst = reinterpret_cast<UByte*>(buf64_);
dst += byteOffset;
if (swap) {
const UByte* src = d.b + sizeof(T) - 1;
for (Size i = 0; i < sizeof(T); i++)
*dst++ = *src--;
} else {
const UByte* src = d.b;
for (Size i = 0; i < sizeof(T); i++)
*dst++ = *src++;
}
} else {
T* buf = reinterpret_cast<T*>(buf64_);
Size idx = byteOffset / sizeof(T);
buf[idx] = value;
}
}
Boolean isAscii() const {
Size len64 = (length_ + 7) / 8;
for (Size i = 0; i < len64; i++) {
if (buf64_[i] & 0x8080808080808080LL) return false;
}
return true;
}
public:
Size length() const {
return length_;
}
JsArrayBuffer::Ptr slice(Size begin) const {
return this->slice(begin, length_);
}
JsArrayBuffer::Ptr slice(Size begin, Size end) const {
Size len = 0;
if (begin < end && begin < length_) {
if (end >= length_) end = length_;
len = end - begin;
}
JsArrayBufferImpl* buf = new JsArrayBufferImpl(len);
JsArrayBuffer::Ptr p(buf);
if (len) {
const Byte* src = reinterpret_cast<const Byte*>(buf64_);
Byte *dst = reinterpret_cast<Byte*>(buf->buf64_);
std::copy(src + begin, src + end, dst);
}
return p;
}
Boolean getInt8(Size byteOffset, Byte* value) const {
UByte v;
Boolean ret = getUInt8(byteOffset, &v);
*value = v;
return ret;
}
Boolean getUInt8(Size byteOffset, UByte* value) const {
if (byteOffset >= length_) {
return false;
} else {
const UByte* buf8 = reinterpret_cast<const UByte*>(buf64_);
*value = buf8[byteOffset];
return true;
}
}
Boolean getInt16(
Size byteOffset, Short* value, Boolean littleEndian = false) const {
UShort v;
Boolean ret = getUInt16(byteOffset, &v, littleEndian);
*value = v;
return ret;
}
Boolean getUInt16(
Size byteOffset, UShort* value, Boolean littleEndian = false) const {
if (byteOffset + 1 >= length_) {
return false;
} else {
*value = load<UShort>(byteOffset, littleEndian);
return true;
}
}
Boolean getInt32(
Size byteOffset, Int* value, Boolean littleEndian = false) const {
UInt v;
Boolean ret = getUInt32(byteOffset, &v, littleEndian);
*value = v;
return ret;
}
Boolean getUInt32(
Size byteOffset, UInt* value, Boolean littleEndian = false) const {
if (byteOffset + 3 >= length_) {
return false;
} else {
*value = load<UInt>(byteOffset, littleEndian);
return true;
}
}
Boolean getFloat32(
Size byteOffset, Float* value, Boolean littleEndian = false) const {
union {
Float f;
UInt i;
} v;
Boolean ret = getUInt32(byteOffset, &v.i, littleEndian);
*value = v.f;
return ret;
}
Boolean getFloat64(
Size byteOffset, Double* value, Boolean littleEndian = false) const {
if (byteOffset + 7 >= length_) {
return false;
} else {
union {
ULong i;
Double f;
} v;
v.i = load<ULong>(byteOffset, littleEndian);
*value = v.f;
return true;
}
}
Boolean setInt8(Size byteOffset, Byte value) {
return setUInt8(byteOffset, value);
}
Boolean setUInt8(Size byteOffset, UByte value) {
if (byteOffset >= length_) {
return false;
} else {
UByte* buf8 = reinterpret_cast<UByte*>(buf64_);
buf8[byteOffset] = value;
return true;
}
}
Boolean setInt16(
Size byteOffset, Short value, Boolean littleEndian = false) {
return setUInt16(byteOffset, value, littleEndian);
}
Boolean setUInt16(
Size byteOffset, UShort value, Boolean littleEndian = false) {
if (byteOffset + 1 >= length_) {
return false;
} else {
store<UShort>(byteOffset, value, littleEndian);
return true;
}
}
Boolean setInt32(
Size byteOffset, Int value, Boolean littleEndian = false) {
return setUInt32(byteOffset, value, littleEndian);
}
Boolean setUInt32(
Size byteOffset, UInt value, Boolean littleEndian = false) {
if (byteOffset + 3 >= length_) {
return false;
} else {
store<UInt>(byteOffset, value, littleEndian);
return true;
}
}
Boolean setFloat32(
Size byteOffset, Float value, Boolean littleEndian = false) {
union {
Float f;
UInt i;
} v;
v.f = value;
return setUInt32(byteOffset, v.i, littleEndian);
}
Boolean setFloat64(
Size byteOffset, Double value, Boolean littleEndian = false) {
if (byteOffset + 7 >= length_) {
return false;
} else {
union {
Double f;
ULong i;
} v;
v.f = value;
store<ULong>(byteOffset, v.i, littleEndian);
return true;
}
}
String::CPtr toString() const {
if (isAscii())
return String::create(buf64_, String::ASCII, length_);
else
return String::create(buf64_, String::UTF8);
}
private:
Size length_;
ULong* buf64_;
JsArrayBufferImpl(Size length = 0)
: length_(length)
, buf64_(0) {
if (length) {
Size len64 = (length >> 3) + !!(length & 0x7);
buf64_ = new ULong[len64 + 1];
buf64_[len64] = 0;
}
}
public:
~JsArrayBufferImpl() {
delete[] buf64_;
}
static JsArrayBuffer::Ptr create(Size length = 0) {
JsArrayBuffer::Ptr p(new JsArrayBufferImpl(length));
return p;
}
}; // JsArrayBufferImpl
const union JsArrayBufferImpl::endian_u JsArrayBufferImpl::endian = {1};
JsArrayBuffer::Ptr JsArrayBuffer::create(Size length) {
return JsArrayBufferImpl::create(length);
}
} // namespace libj
<commit_msg>fix a bug of JsArrayBuffer constructor<commit_after>// Copyright (c) 2012 Plenluno All rights reserved.
#include <algorithm>
#include "libj/js_array_buffer.h"
#include "libj/string.h"
namespace libj {
class JsArrayBufferImpl : public JsArrayBuffer {
private:
static const union endian_u {
UShort one;
UByte isLittle;
} endian;
template <typename T>
T load(Size byteOffset, Boolean littleEndian) const {
Boolean swap = endian.isLittle != littleEndian;
if (swap) {
union {
T w;
UByte b[sizeof(T)];
} d;
const UByte* src = reinterpret_cast<const UByte*>(buf64_);
src += byteOffset;
UByte* dst = d.b + sizeof(T) - 1;
for (Size i = 0; i < sizeof(T); i++)
*dst-- = *src++;
return d.w;
} else {
const T* buf = reinterpret_cast<const T*>(buf64_);
Size idx = byteOffset / sizeof(T);
Size mod = byteOffset % sizeof(T);
T d0 = buf[idx];
if (mod) {
T d1 = buf[idx + 1];
Size sh = mod * 8;
if (endian.isLittle) {
d0 = d0 >> sh;
d1 = d1 << (8 * sizeof(T) - sh);
} else {
d0 = d0 << sh;
d1 = d1 >> (8 * sizeof(T) - sh);
}
d0 = d0 | d1;
}
return d0;
}
}
template <typename T>
void store(Size byteOffset, T value, Boolean littleEndian) {
Boolean swap = endian.isLittle != littleEndian;
if (swap || byteOffset % sizeof(T)) {
union {
T w;
UByte b[sizeof(T)];
} d;
d.w = value;
UByte* dst = reinterpret_cast<UByte*>(buf64_);
dst += byteOffset;
if (swap) {
const UByte* src = d.b + sizeof(T) - 1;
for (Size i = 0; i < sizeof(T); i++)
*dst++ = *src--;
} else {
const UByte* src = d.b;
for (Size i = 0; i < sizeof(T); i++)
*dst++ = *src++;
}
} else {
T* buf = reinterpret_cast<T*>(buf64_);
Size idx = byteOffset / sizeof(T);
buf[idx] = value;
}
}
Boolean isAscii() const {
Size len64 = (length_ + 7) / 8;
for (Size i = 0; i < len64; i++) {
if (buf64_[i] & 0x8080808080808080LL)
return false;
}
return true;
}
public:
Size length() const {
return length_;
}
JsArrayBuffer::Ptr slice(Size begin) const {
return this->slice(begin, length_);
}
JsArrayBuffer::Ptr slice(Size begin, Size end) const {
Size len = 0;
if (begin < end && begin < length_) {
if (end >= length_) end = length_;
len = end - begin;
}
JsArrayBufferImpl* buf = new JsArrayBufferImpl(len);
JsArrayBuffer::Ptr p(buf);
if (len) {
const Byte* src = reinterpret_cast<const Byte*>(buf64_);
Byte *dst = reinterpret_cast<Byte*>(buf->buf64_);
std::copy(src + begin, src + end, dst);
}
return p;
}
Boolean getInt8(Size byteOffset, Byte* value) const {
UByte v;
Boolean ret = getUInt8(byteOffset, &v);
*value = v;
return ret;
}
Boolean getUInt8(Size byteOffset, UByte* value) const {
if (byteOffset >= length_) {
return false;
} else {
const UByte* buf8 = reinterpret_cast<const UByte*>(buf64_);
*value = buf8[byteOffset];
return true;
}
}
Boolean getInt16(
Size byteOffset, Short* value, Boolean littleEndian = false) const {
UShort v;
Boolean ret = getUInt16(byteOffset, &v, littleEndian);
*value = v;
return ret;
}
Boolean getUInt16(
Size byteOffset, UShort* value, Boolean littleEndian = false) const {
if (byteOffset + 1 >= length_) {
return false;
} else {
*value = load<UShort>(byteOffset, littleEndian);
return true;
}
}
Boolean getInt32(
Size byteOffset, Int* value, Boolean littleEndian = false) const {
UInt v;
Boolean ret = getUInt32(byteOffset, &v, littleEndian);
*value = v;
return ret;
}
Boolean getUInt32(
Size byteOffset, UInt* value, Boolean littleEndian = false) const {
if (byteOffset + 3 >= length_) {
return false;
} else {
*value = load<UInt>(byteOffset, littleEndian);
return true;
}
}
Boolean getFloat32(
Size byteOffset, Float* value, Boolean littleEndian = false) const {
union {
Float f;
UInt i;
} v;
Boolean ret = getUInt32(byteOffset, &v.i, littleEndian);
*value = v.f;
return ret;
}
Boolean getFloat64(
Size byteOffset, Double* value, Boolean littleEndian = false) const {
if (byteOffset + 7 >= length_) {
return false;
} else {
union {
ULong i;
Double f;
} v;
v.i = load<ULong>(byteOffset, littleEndian);
*value = v.f;
return true;
}
}
Boolean setInt8(Size byteOffset, Byte value) {
return setUInt8(byteOffset, value);
}
Boolean setUInt8(Size byteOffset, UByte value) {
if (byteOffset >= length_) {
return false;
} else {
UByte* buf8 = reinterpret_cast<UByte*>(buf64_);
buf8[byteOffset] = value;
return true;
}
}
Boolean setInt16(
Size byteOffset, Short value, Boolean littleEndian = false) {
return setUInt16(byteOffset, value, littleEndian);
}
Boolean setUInt16(
Size byteOffset, UShort value, Boolean littleEndian = false) {
if (byteOffset + 1 >= length_) {
return false;
} else {
store<UShort>(byteOffset, value, littleEndian);
return true;
}
}
Boolean setInt32(
Size byteOffset, Int value, Boolean littleEndian = false) {
return setUInt32(byteOffset, value, littleEndian);
}
Boolean setUInt32(
Size byteOffset, UInt value, Boolean littleEndian = false) {
if (byteOffset + 3 >= length_) {
return false;
} else {
store<UInt>(byteOffset, value, littleEndian);
return true;
}
}
Boolean setFloat32(
Size byteOffset, Float value, Boolean littleEndian = false) {
union {
Float f;
UInt i;
} v;
v.f = value;
return setUInt32(byteOffset, v.i, littleEndian);
}
Boolean setFloat64(
Size byteOffset, Double value, Boolean littleEndian = false) {
if (byteOffset + 7 >= length_) {
return false;
} else {
union {
Double f;
ULong i;
} v;
v.f = value;
store<ULong>(byteOffset, v.i, littleEndian);
return true;
}
}
String::CPtr toString() const {
if (isAscii())
return String::create(buf64_, String::ASCII, length_);
else
return String::create(buf64_, String::UTF8);
}
private:
Size length_;
ULong* buf64_;
JsArrayBufferImpl(Size length = 0)
: length_(length)
, buf64_(0) {
if (length) {
Size len64 = (length + 7) >> 3;
buf64_ = new ULong[len64 + 1];
for (Size i = 0; i <= len64; i++)
buf64_[i] = 0;
}
}
public:
~JsArrayBufferImpl() {
delete[] buf64_;
}
static JsArrayBuffer::Ptr create(Size length = 0) {
JsArrayBuffer::Ptr p(new JsArrayBufferImpl(length));
return p;
}
}; // JsArrayBufferImpl
const union JsArrayBufferImpl::endian_u JsArrayBufferImpl::endian = {1};
JsArrayBuffer::Ptr JsArrayBuffer::create(Size length) {
return JsArrayBufferImpl::create(length);
}
} // namespace libj
<|endoftext|> |
<commit_before>/*
* Copyright (C) 2014 Cloudius Systems, Ltd.
*/
#ifndef FUTURE_HH_
#define FUTURE_HH_
#include "apply.hh"
#include <stdexcept>
#include <memory>
template <class... T>
class promise;
template <class... T>
class future;
template <typename... T, typename... A>
future<T...> make_ready_future(A&&... value);
template <typename... T>
future<T...> make_exception_future(std::exception_ptr value);
class task {
public:
virtual ~task() {}
virtual void run() = 0;
};
void schedule(std::unique_ptr<task> t);
template <typename Func>
class lambda_task : public task {
Func _func;
public:
lambda_task(const Func& func) : _func(func) {}
lambda_task(Func&& func) : _func(std::move(func)) {}
virtual void run() { _func(); }
};
template <typename Func>
std::unique_ptr<task>
make_task(const Func& func) {
return std::unique_ptr<task>(new lambda_task<Func>(func));
}
template <typename Func>
std::unique_ptr<task>
make_task(Func&& func) {
return std::unique_ptr<task>(new lambda_task<Func>(std::move(func)));
}
template <typename... T>
struct future_state {
promise<T...>* _promise = nullptr;
future<T...>* _future = nullptr;
std::unique_ptr<task> _task;
enum class state {
invalid,
future,
result,
exception,
} _state = state::future;
union any {
any() {}
~any() {}
std::tuple<T...> value;
std::exception_ptr ex;
} _u;
~future_state() noexcept {
switch (_state) {
case state::future:
break;
case state::result:
_u.value.~tuple();
break;
case state::exception:
_u.ex.~exception_ptr();
break;
default:
abort();
}
}
bool available() const { return _state == state::result || _state == state::exception; }
bool has_promise() const { return _promise; }
bool has_future() const { return _future; }
void wait();
void make_ready();
void set(const std::tuple<T...>& value) {
assert(_state == state::future);
_state = state::result;
new (&_u.value) std::tuple<T...>(value);
make_ready();
}
void set(std::tuple<T...>&& value) {
assert(_state == state::future);
_state = state::result;
new (&_u.value) std::tuple<T...>(std::move(value));
make_ready();
}
template <typename... A>
void set(A&&... a) {
assert(_state == state::future);
_state = state::result;
new (&_u.value) std::tuple<T...>(std::forward<A>(a)...);
make_ready();
}
void set_exception(std::exception_ptr ex) {
assert(_state == state::future);
_state = state::exception;
new (&_u.ex) std::exception_ptr(ex);
make_ready();
}
std::tuple<T...> get() {
while (_state == state::future) {
abort();
}
if (_state == state::exception) {
std::rethrow_exception(_u.ex);
}
return std::move(_u.value);
}
template <typename Func>
void schedule(Func&& func) {
_task = make_task(std::forward<Func>(func));
if (available()) {
make_ready();
}
}
friend future<T...> make_ready_future<T...>(T&&... value);
};
template <typename... T>
class promise {
future_state<T...>* _state;
public:
promise() : _state(new future_state<T...>()) { _state->_promise = this; }
promise(promise&& x) : _state(std::move(x._state)) { x._state = nullptr; }
promise(const promise&) = delete;
~promise() {
if (_state) {
_state->_promise = nullptr;
if (!_state->has_future()) {
delete _state;
}
}
}
promise& operator=(promise&& x) {
this->~promise();
_state = x._state;
x._state = nullptr;
return *this;
}
void operator=(const promise&) = delete;
future<T...> get_future();
void set_value(const std::tuple<T...>& result) { _state->set(result); }
void set_value(std::tuple<T...>&& result) { _state->set(std::move(result)); }
template <typename... A>
void set_value(A&&... a) { _state->set(std::forward<A>(a)...); }
void set_exception(std::exception_ptr ex) { _state->set_exception(std::move(ex)); }
};
template <typename... T> struct is_future : std::false_type {};
template <typename... T> struct is_future<future<T...>> : std::true_type {};
template <typename... T>
class future {
future_state<T...>* _state;
private:
future(future_state<T...>* state) : _state(state) { _state->_future = this; }
public:
using value_type = std::tuple<T...>;
using promise_type = promise<T...>;
future(future&& x) : _state(x._state) { x._state = nullptr; }
future(const future&) = delete;
future& operator=(future&& x);
void operator=(const future&) = delete;
~future() {
if (_state) {
_state->_future = nullptr;
if (!_state->has_promise()) {
delete _state;
}
}
}
std::tuple<T...> get() {
return _state->get();
}
template <typename Func, typename Enable>
void then(Func, Enable);
template <typename Func>
future<> then(Func&& func,
std::enable_if_t<std::is_same<std::result_of_t<Func(T&&...)>, void>::value, void*> = nullptr) {
auto state = _state;
if (state->available()) {
try {
apply(std::move(func), std::move(_state->get()));
return make_ready_future<>();
} catch (...) {
return make_exception_future(std::current_exception());
}
}
promise<> pr;
auto fut = pr.get_future();
state->schedule([fut = std::move(*this), pr = std::move(pr), func = std::forward<Func>(func)] () mutable {
try {
apply(std::move(func), fut.get());
pr.set_value();
} catch (...) {
pr.set_exception(std::current_exception());
}
});
return fut;
}
template <typename Func>
std::result_of_t<Func(T&&...)>
then(Func&& func,
std::enable_if_t<is_future<std::result_of_t<Func(T&&...)>>::value, void*> = nullptr) {
auto state = _state;
using P = typename std::result_of_t<Func(T&&...)>::promise_type;
if (state->available()) {
try {
return apply(std::move(func), std::move(_state->get()));
} catch (...) {
P pr;
pr.set_exception(std::current_exception());
return pr.get_future();
}
}
P pr;
auto next_fut = pr.get_future();
state->schedule([fut = std::move(*this), func = std::forward<Func>(func), pr = std::move(pr)] () mutable {
try {
auto result = fut.get();
auto next_fut = apply(std::move(func), std::move(result));
next_fut.then([pr = std::move(pr)] (auto... next) mutable {
pr.set_value(std::move(next)...);
});
} catch (...) {
pr.set_exception(std::current_exception());
}
});
return next_fut;
}
template <typename Func>
void rescue(Func&& func) {
auto state = _state;
state->schedule([fut = std::move(*this), func = std::forward<Func>(func)] () mutable {
func([fut = std::move(fut)] () mutable { fut.get(); });
});
}
template <typename... A>
static future do_make_ready_future(A&&... value) {
auto s = std::make_unique<future_state<T...>>();
s->set(std::forward<A>(value)...);
return future(s.release());
}
static future do_make_exception_future(std::exception_ptr ex) {
auto s = std::make_unique<future_state<T...>>();
s->set_exception(std::move(ex));
return future(s.release());
}
friend class promise<T...>;
};
template <typename... T>
inline
future<T...>
promise<T...>::get_future()
{
assert(!_state->_future);
return future<T...>(_state);
}
template <typename... T>
inline
void future_state<T...>::make_ready() {
if (_task) {
::schedule(std::move(_task));
}
}
template <typename... T, typename... A>
inline
future<T...> make_ready_future(A&&... value) {
return future<T...>::do_make_ready_future(std::forward<A>(value)...);
}
template <typename... T>
inline
future<T...> make_exception_future(std::exception_ptr ex) {
return future<T...>::do_make_exception_future(std::move(ex));
}
#endif /* FUTURE_HH_ */
<commit_msg>core: fix promise move assignment<commit_after>/*
* Copyright (C) 2014 Cloudius Systems, Ltd.
*/
#ifndef FUTURE_HH_
#define FUTURE_HH_
#include "apply.hh"
#include <stdexcept>
#include <memory>
template <class... T>
class promise;
template <class... T>
class future;
template <typename... T, typename... A>
future<T...> make_ready_future(A&&... value);
template <typename... T>
future<T...> make_exception_future(std::exception_ptr value);
class task {
public:
virtual ~task() {}
virtual void run() = 0;
};
void schedule(std::unique_ptr<task> t);
template <typename Func>
class lambda_task : public task {
Func _func;
public:
lambda_task(const Func& func) : _func(func) {}
lambda_task(Func&& func) : _func(std::move(func)) {}
virtual void run() { _func(); }
};
template <typename Func>
std::unique_ptr<task>
make_task(const Func& func) {
return std::unique_ptr<task>(new lambda_task<Func>(func));
}
template <typename Func>
std::unique_ptr<task>
make_task(Func&& func) {
return std::unique_ptr<task>(new lambda_task<Func>(std::move(func)));
}
template <typename... T>
struct future_state {
promise<T...>* _promise = nullptr;
future<T...>* _future = nullptr;
std::unique_ptr<task> _task;
enum class state {
invalid,
future,
result,
exception,
} _state = state::future;
union any {
any() {}
~any() {}
std::tuple<T...> value;
std::exception_ptr ex;
} _u;
~future_state() noexcept {
switch (_state) {
case state::future:
break;
case state::result:
_u.value.~tuple();
break;
case state::exception:
_u.ex.~exception_ptr();
break;
default:
abort();
}
}
bool available() const { return _state == state::result || _state == state::exception; }
bool has_promise() const { return _promise; }
bool has_future() const { return _future; }
void wait();
void make_ready();
void set(const std::tuple<T...>& value) {
assert(_state == state::future);
_state = state::result;
new (&_u.value) std::tuple<T...>(value);
make_ready();
}
void set(std::tuple<T...>&& value) {
assert(_state == state::future);
_state = state::result;
new (&_u.value) std::tuple<T...>(std::move(value));
make_ready();
}
template <typename... A>
void set(A&&... a) {
assert(_state == state::future);
_state = state::result;
new (&_u.value) std::tuple<T...>(std::forward<A>(a)...);
make_ready();
}
void set_exception(std::exception_ptr ex) {
assert(_state == state::future);
_state = state::exception;
new (&_u.ex) std::exception_ptr(ex);
make_ready();
}
std::tuple<T...> get() {
while (_state == state::future) {
abort();
}
if (_state == state::exception) {
std::rethrow_exception(_u.ex);
}
return std::move(_u.value);
}
template <typename Func>
void schedule(Func&& func) {
_task = make_task(std::forward<Func>(func));
if (available()) {
make_ready();
}
}
friend future<T...> make_ready_future<T...>(T&&... value);
};
template <typename... T>
class promise {
future_state<T...>* _state;
public:
promise() : _state(new future_state<T...>()) { _state->_promise = this; }
promise(promise&& x) : _state(std::move(x._state)) { x._state = nullptr; }
promise(const promise&) = delete;
~promise() {
if (_state) {
_state->_promise = nullptr;
if (!_state->has_future()) {
delete _state;
}
}
}
promise& operator=(promise&& x) {
if (this != &x) {
this->~promise();
new (this) promise(std::move(x));
}
return *this;
}
void operator=(const promise&) = delete;
future<T...> get_future();
void set_value(const std::tuple<T...>& result) { _state->set(result); }
void set_value(std::tuple<T...>&& result) { _state->set(std::move(result)); }
template <typename... A>
void set_value(A&&... a) { _state->set(std::forward<A>(a)...); }
void set_exception(std::exception_ptr ex) { _state->set_exception(std::move(ex)); }
};
template <typename... T> struct is_future : std::false_type {};
template <typename... T> struct is_future<future<T...>> : std::true_type {};
template <typename... T>
class future {
future_state<T...>* _state;
private:
future(future_state<T...>* state) : _state(state) { _state->_future = this; }
public:
using value_type = std::tuple<T...>;
using promise_type = promise<T...>;
future(future&& x) : _state(x._state) { x._state = nullptr; }
future(const future&) = delete;
future& operator=(future&& x);
void operator=(const future&) = delete;
~future() {
if (_state) {
_state->_future = nullptr;
if (!_state->has_promise()) {
delete _state;
}
}
}
std::tuple<T...> get() {
return _state->get();
}
template <typename Func, typename Enable>
void then(Func, Enable);
template <typename Func>
future<> then(Func&& func,
std::enable_if_t<std::is_same<std::result_of_t<Func(T&&...)>, void>::value, void*> = nullptr) {
auto state = _state;
if (state->available()) {
try {
apply(std::move(func), std::move(_state->get()));
return make_ready_future<>();
} catch (...) {
return make_exception_future(std::current_exception());
}
}
promise<> pr;
auto fut = pr.get_future();
state->schedule([fut = std::move(*this), pr = std::move(pr), func = std::forward<Func>(func)] () mutable {
try {
apply(std::move(func), fut.get());
pr.set_value();
} catch (...) {
pr.set_exception(std::current_exception());
}
});
return fut;
}
template <typename Func>
std::result_of_t<Func(T&&...)>
then(Func&& func,
std::enable_if_t<is_future<std::result_of_t<Func(T&&...)>>::value, void*> = nullptr) {
auto state = _state;
using P = typename std::result_of_t<Func(T&&...)>::promise_type;
if (state->available()) {
try {
return apply(std::move(func), std::move(_state->get()));
} catch (...) {
P pr;
pr.set_exception(std::current_exception());
return pr.get_future();
}
}
P pr;
auto next_fut = pr.get_future();
state->schedule([fut = std::move(*this), func = std::forward<Func>(func), pr = std::move(pr)] () mutable {
try {
auto result = fut.get();
auto next_fut = apply(std::move(func), std::move(result));
next_fut.then([pr = std::move(pr)] (auto... next) mutable {
pr.set_value(std::move(next)...);
});
} catch (...) {
pr.set_exception(std::current_exception());
}
});
return next_fut;
}
template <typename Func>
void rescue(Func&& func) {
auto state = _state;
state->schedule([fut = std::move(*this), func = std::forward<Func>(func)] () mutable {
func([fut = std::move(fut)] () mutable { fut.get(); });
});
}
template <typename... A>
static future do_make_ready_future(A&&... value) {
auto s = std::make_unique<future_state<T...>>();
s->set(std::forward<A>(value)...);
return future(s.release());
}
static future do_make_exception_future(std::exception_ptr ex) {
auto s = std::make_unique<future_state<T...>>();
s->set_exception(std::move(ex));
return future(s.release());
}
friend class promise<T...>;
};
template <typename... T>
inline
future<T...>
promise<T...>::get_future()
{
assert(!_state->_future);
return future<T...>(_state);
}
template <typename... T>
inline
void future_state<T...>::make_ready() {
if (_task) {
::schedule(std::move(_task));
}
}
template <typename... T, typename... A>
inline
future<T...> make_ready_future(A&&... value) {
return future<T...>::do_make_ready_future(std::forward<A>(value)...);
}
template <typename... T>
inline
future<T...> make_exception_future(std::exception_ptr ex) {
return future<T...>::do_make_exception_future(std::move(ex));
}
#endif /* FUTURE_HH_ */
<|endoftext|> |
<commit_before>// This file is a part of the IncludeOS unikernel - www.includeos.org
//
// Copyright 2015-2016 Oslo and Akershus University College of Applied Sciences
// and Alfred Bratterud
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
#include "connection.hpp"
#include "server.hpp"
#include <kernel/syscalls.hpp>
using namespace server;
Connection::OnConnection Connection::on_connection_ = []{};
Connection::Connection(Server& serv, Connection_ptr conn, size_t idx)
: server_(serv), conn_(conn), idx_(idx)
{
conn_->on_read(BUFSIZE, OnData::from<Connection, &Connection::on_data>(this));
conn_->on_disconnect(OnDisconnect::from<Connection, &Connection::on_disconnect>(this));
conn_->on_close(OnClose::from<Connection, &Connection::close>(this));
conn_->on_error(OnError::from<Connection, &Connection::on_error>(this));
//conn_->on_rtx_timeout([](auto, auto) { printf("<TCP> RtxTimeout\n"); });
on_connection_();
idle_since_ = RTC::now();
}
void Connection::on_data(buffer_t buf, size_t n) {
//printf("Connection::on_data: %*s", n, buf.get());
SET_CRASH_CONTEXT("Connection::on_data: data from %s\n\n%*s",
conn_->to_string().c_str(), n, buf.get());
#ifdef VERBOSE_WEBSERVER
printf("<%s> @on_data, size=%u\n", to_string().c_str(), n);
#endif
// if it's a new request
if(!request_) {
try {
request_ = std::make_shared<Request>(buf, n);
update_idle();
// return early to read payload
if((request_->method() == http::POST or request_->method() == http::PUT)
and !request_->is_complete())
{
printf("<%s> POST/PUT: [ConLen (%u) > Payload (%u)] => Buffering\n",
to_string().c_str(), request_->content_length(), request_->payload_length());
return;
}
}
catch(std::exception& e) {
printf("<%s> Error - %s\n",
to_string().c_str(), e.what());
// close tcp connection
close_tcp();
return;
}
}
// else we assume it's payload
else {
update_idle();
request_->add_body(request_->get_body() + std::string((const char*)buf.get(), n));
// if we haven't received all data promised
printf("<%s> Received payload - Expected: %u - Recv: %u\n",
to_string().c_str(), request_->content_length(), request_->payload_length());
if(!request_->is_complete())
return;
}
request_->complete();
#ifdef VERBOSE_WEBSERVER
printf("<%s> Complete Request: [%s] Payload (%u/%u B)\n",
to_string().c_str(),
request_->route_string().c_str(),
request_->payload_length(),
request_->content_length()
);
#endif
response_ = std::make_shared<Response>(conn_);
server_.process(request_, response_);
request_ = nullptr;
}
void Connection::on_disconnect(Connection_ptr, Disconnect reason) {
update_idle();
(void)reason;
#ifdef VERBOSE_WEBSERVER
printf("<%s> Disconnect: %s\n",
to_string().c_str(), reason.to_string().c_str());
#endif
close_tcp();
}
void Connection::on_error(TCPException err) {
printf("<%s> TCP Error: %s\n",
to_string().c_str(), err.what());
}
void Connection::on_packet_dropped(Packet_ptr, std::string reason) {
printf("<%s> Packet dropped: %s\n",
to_string().c_str(), reason.c_str());
}
void Connection::close() {
request_ = nullptr;
response_ = nullptr;
server_.close(idx_);
}
void Connection::timeout() {
conn_->is_closing() ? conn_->abort() : conn_->close();
}
Connection::~Connection() {
#ifdef VERBOSE_WEBSERVER
printf("<%s> Deleted\n", to_string().c_str());
#endif
}
<commit_msg>Server: Connection now prints dropped packets<commit_after>// This file is a part of the IncludeOS unikernel - www.includeos.org
//
// Copyright 2015-2016 Oslo and Akershus University College of Applied Sciences
// and Alfred Bratterud
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
#include "connection.hpp"
#include "server.hpp"
#include <kernel/syscalls.hpp>
using namespace server;
Connection::OnConnection Connection::on_connection_ = []{};
Connection::Connection(Server& serv, Connection_ptr conn, size_t idx)
: server_(serv), conn_(conn), idx_(idx)
{
conn_->on_read(BUFSIZE, OnData::from<Connection, &Connection::on_data>(this));
conn_->on_disconnect(OnDisconnect::from<Connection, &Connection::on_disconnect>(this));
conn_->on_close(OnClose::from<Connection, &Connection::close>(this));
conn_->on_error(OnError::from<Connection, &Connection::on_error>(this));
conn_->on_packet_dropped(OnPacketDropped::from<Connection, &Connection::on_packet_dropped>(this));
//conn_->on_rtx_timeout([](auto, auto) { printf("<TCP> RtxTimeout\n"); });
on_connection_();
idle_since_ = RTC::now();
}
void Connection::on_data(buffer_t buf, size_t n) {
//printf("Connection::on_data: %*s", n, buf.get());
SET_CRASH_CONTEXT("Connection::on_data: data from %s\n\n%*s",
conn_->to_string().c_str(), n, buf.get());
#ifdef VERBOSE_WEBSERVER
printf("<%s> @on_data, size=%u\n", to_string().c_str(), n);
#endif
// if it's a new request
if(!request_) {
try {
request_ = std::make_shared<Request>(buf, n);
update_idle();
// return early to read payload
if((request_->method() == http::POST or request_->method() == http::PUT)
and !request_->is_complete())
{
printf("<%s> POST/PUT: [ConLen (%u) > Payload (%u)] => Buffering\n",
to_string().c_str(), request_->content_length(), request_->payload_length());
return;
}
}
catch(std::exception& e) {
printf("<%s> HTTP Error - %s\n",
to_string().c_str(), e.what());
// close tcp connection
close_tcp();
return;
}
}
// else we assume it's payload
else {
update_idle();
request_->add_body(request_->get_body() + std::string((const char*)buf.get(), n));
// if we haven't received all data promised
printf("<%s> Received payload - Expected: %u - Recv: %u\n",
to_string().c_str(), request_->content_length(), request_->payload_length());
if(!request_->is_complete())
return;
}
request_->complete();
#ifdef VERBOSE_WEBSERVER
printf("<%s> Complete Request: [%s] Payload (%u/%u B)\n",
to_string().c_str(),
request_->route_string().c_str(),
request_->payload_length(),
request_->content_length()
);
#endif
response_ = std::make_shared<Response>(conn_);
server_.process(request_, response_);
request_ = nullptr;
}
void Connection::on_disconnect(Connection_ptr, Disconnect reason) {
update_idle();
(void)reason;
#ifdef VERBOSE_WEBSERVER
printf("<%s> Disconnect: %s\n",
to_string().c_str(), reason.to_string().c_str());
#endif
close_tcp();
}
void Connection::on_error(TCPException err) {
printf("<%s> TCP Error: %s\n",
to_string().c_str(), err.what());
}
void Connection::on_packet_dropped(Packet_ptr, std::string reason) {
printf("<%s> Packet dropped: %s\n",
to_string().c_str(), reason.c_str());
}
void Connection::close() {
request_ = nullptr;
response_ = nullptr;
server_.close(idx_);
}
void Connection::timeout() {
conn_->is_closing() ? conn_->abort() : conn_->close();
}
Connection::~Connection() {
#ifdef VERBOSE_WEBSERVER
printf("<%s> Deleted\n", to_string().c_str());
#endif
}
<|endoftext|> |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.