text
stringlengths 54
60.6k
|
---|
<commit_before>/*
* (C) 2014,2015 Jack Lloyd
*
* Botan is released under the Simplified BSD License (see license.txt)
*/
#include "cli.h"
#if defined(BOTAN_HAS_ASN1) && defined(BOTAN_HAS_PEM_CODEC)
#include <botan/bigint.h>
#include <botan/hex.h>
#include <botan/der_enc.h>
#include <botan/ber_dec.h>
#include <botan/asn1_time.h>
#include <botan/asn1_str.h>
#include <botan/oids.h>
#include <botan/pem.h>
#include <botan/charset.h>
#include <iostream>
#include <iomanip>
#include <sstream>
#include <ctype.h>
// Set this if your terminal understands UTF-8; otherwise output is in Latin-1
#define UTF8_TERMINAL 1
/*
What level the outermost layer of stuff is at. Probably 0 or 1; asn1parse
uses 0 as the outermost, while 1 makes more sense to me. 2+ doesn't make
much sense at all.
*/
#define INITIAL_LEVEL 0
namespace Botan_CLI {
namespace {
std::string url_encode(const std::vector<uint8_t>& in)
{
std::ostringstream out;
size_t unprintable = 0;
for(size_t i = 0; i != in.size(); ++i)
{
const int c = in[i];
if(::isprint(c))
{
out << static_cast<char>(c);
}
else
{
out << "%" << std::hex << static_cast<int>(c) << std::dec;
++unprintable;
}
}
if(unprintable >= in.size() / 4)
{
return Botan::hex_encode(in);
}
return out.str();
}
void emit(const std::string& type, size_t level, size_t length, const std::string& value = "")
{
const size_t LIMIT = 4 * 1024;
const size_t BIN_LIMIT = 1024;
std::ostringstream out;
out << " d=" << std::setw(2) << level
<< ", l=" << std::setw(4) << length << ": ";
for(size_t i = INITIAL_LEVEL; i != level; ++i)
{
out << ' ';
}
out << type;
bool should_skip = false;
if(value.length() > LIMIT)
{
should_skip = true;
}
if((type == "OCTET STRING" || type == "BIT STRING") && value.length() > BIN_LIMIT)
{
should_skip = true;
}
if(value != "" && !should_skip)
{
if(out.tellp() % 2 == 0)
{
out << ' ';
}
while(out.tellp() < 50)
{
out << ' ';
}
out << value;
}
std::cout << out.str() << std::endl;
}
std::string type_name(Botan::ASN1_Tag type)
{
switch(type)
{
case Botan::PRINTABLE_STRING:
return "PRINTABLE STRING";
case Botan::NUMERIC_STRING:
return "NUMERIC STRING";
case Botan::IA5_STRING:
return "IA5 STRING";
case Botan::T61_STRING:
return "T61 STRING";
case Botan::UTF8_STRING:
return "UTF8 STRING";
case Botan::VISIBLE_STRING:
return "VISIBLE STRING";
case Botan::BMP_STRING:
return "BMP STRING";
case Botan::UTC_TIME:
return "UTC TIME";
case Botan::GENERALIZED_TIME:
return "GENERALIZED TIME";
case Botan::OCTET_STRING:
return "OCTET STRING";
case Botan::BIT_STRING:
return "BIT STRING";
case Botan::ENUMERATED:
return "ENUMERATED";
case Botan::INTEGER:
return "INTEGER";
case Botan::NULL_TAG:
return "NULL";
case Botan::OBJECT_ID:
return "OBJECT";
case Botan::BOOLEAN:
return "BOOLEAN";
default:
return "TAG(" + std::to_string(static_cast<size_t>(type)) + ")";
}
}
void decode(Botan::BER_Decoder& decoder, size_t level)
{
Botan::BER_Object obj = decoder.get_next_object();
while(obj.type_tag != Botan::NO_OBJECT)
{
const Botan::ASN1_Tag type_tag = obj.type_tag;
const Botan::ASN1_Tag class_tag = obj.class_tag;
const size_t length = obj.value.size();
/* hack to insert the tag+length back in front of the stuff now
that we've gotten the type info */
Botan::DER_Encoder encoder;
encoder.add_object(type_tag, class_tag, obj.value);
std::vector<uint8_t> bits = encoder.get_contents_unlocked();
Botan::BER_Decoder data(bits);
if(class_tag & Botan::CONSTRUCTED)
{
Botan::BER_Decoder cons_info(obj.value);
if(type_tag == Botan::SEQUENCE)
{
emit("SEQUENCE", level, length);
decode(cons_info, level + 1);
}
else if(type_tag == Botan::SET)
{
emit("SET", level, length);
decode(cons_info, level + 1);
}
else
{
std::string name;
if((class_tag & Botan::APPLICATION) || (class_tag & Botan::CONTEXT_SPECIFIC))
{
name = "cons [" + std::to_string(type_tag) + "]";
if(class_tag & Botan::APPLICATION)
{
name += " appl";
}
if(class_tag & Botan::CONTEXT_SPECIFIC)
{
name += " context";
}
}
else
{
name = type_name(type_tag) + " (cons)";
}
emit(name, level, length);
decode(cons_info, level + 1);
}
}
else if((class_tag & Botan::APPLICATION) || (class_tag & Botan::CONTEXT_SPECIFIC))
{
#if 0
std::vector<uint8_t> bits;
data.decode(bits, type_tag);
try
{
Botan::BER_Decoder inner(bits);
decode(inner, level + 1);
}
catch(...)
{
emit("[" + std::to_string(type_tag) + "]", level, length, url_encode(bits));
}
#else
emit("[" + std::to_string(type_tag) + "]", level, length, url_encode(bits));
#endif
}
else if(type_tag == Botan::OBJECT_ID)
{
Botan::OID oid;
data.decode(oid);
std::string out = Botan::OIDS::lookup(oid);
if(out != oid.as_string())
{
out += " [" + oid.as_string() + "]";
}
emit(type_name(type_tag), level, length, out);
}
else if(type_tag == Botan::INTEGER || type_tag == Botan::ENUMERATED)
{
Botan::BigInt number;
if(type_tag == Botan::INTEGER)
{
data.decode(number);
}
else if(type_tag == Botan::ENUMERATED)
{
data.decode(number, Botan::ENUMERATED, class_tag);
}
std::vector<uint8_t> rep;
/* If it's small, it's probably a number, not a hash */
if(number.bits() <= 20)
{
rep = Botan::BigInt::encode(number, Botan::BigInt::Decimal);
}
else
{
rep = Botan::BigInt::encode(number, Botan::BigInt::Hexadecimal);
}
std::string str;
for(size_t i = 0; i != rep.size(); ++i)
{
str += static_cast<char>(rep[i]);
}
emit(type_name(type_tag), level, length, str);
}
else if(type_tag == Botan::BOOLEAN)
{
bool boolean;
data.decode(boolean);
emit(type_name(type_tag), level, length, (boolean ? "true" : "false"));
}
else if(type_tag == Botan::NULL_TAG)
{
emit(type_name(type_tag), level, length);
}
else if(type_tag == Botan::OCTET_STRING)
{
std::vector<uint8_t> decoded_bits;
data.decode(decoded_bits, type_tag);
try
{
Botan::BER_Decoder inner(decoded_bits);
decode(inner, level + 1);
}
catch(...)
{
emit(type_name(type_tag), level, length, url_encode(decoded_bits));
}
}
else if(type_tag == Botan::BIT_STRING)
{
std::vector<uint8_t> decoded_bits;
data.decode(decoded_bits, type_tag);
std::vector<bool> bit_set;
for(size_t i = 0; i != decoded_bits.size(); ++i)
{
for(size_t j = 0; j != 8; ++j)
{
const bool bit = static_cast<bool>((decoded_bits[decoded_bits.size() - i - 1] >> (7 - j)) & 1);
bit_set.push_back(bit);
}
}
std::string bit_str;
for(size_t i = 0; i != bit_set.size(); ++i)
{
bool the_bit = bit_set[bit_set.size() - i - 1];
if(!the_bit && bit_str.size() == 0)
{
continue;
}
bit_str += (the_bit ? "1" : "0");
}
emit(type_name(type_tag), level, length, bit_str);
}
else if(type_tag == Botan::PRINTABLE_STRING ||
type_tag == Botan::NUMERIC_STRING ||
type_tag == Botan::IA5_STRING ||
type_tag == Botan::T61_STRING ||
type_tag == Botan::VISIBLE_STRING ||
type_tag == Botan::UTF8_STRING ||
type_tag == Botan::BMP_STRING)
{
Botan::ASN1_String str;
data.decode(str);
if(UTF8_TERMINAL)
{
emit(type_name(type_tag), level, length,
Botan::Charset::transcode(str.iso_8859(),
Botan::LATIN1_CHARSET,
Botan::UTF8_CHARSET));
}
else
{
emit(type_name(type_tag), level, length, str.iso_8859());
}
}
else if(type_tag == Botan::UTC_TIME || type_tag == Botan::GENERALIZED_TIME)
{
Botan::X509_Time time;
data.decode(time);
emit(type_name(type_tag), level, length, time.readable_string());
}
else
{
std::cout << "Unknown ASN.1 tag class="
<< static_cast<int>(class_tag)
<< " type="
<< static_cast<int>(type_tag) << std::endl;
}
obj = decoder.get_next_object();
}
}
}
class ASN1_Printer final : public Command
{
public:
ASN1_Printer() : Command("asn1print file") {}
void go() override
{
Botan::DataSource_Stream in(get_arg("file"));
if(!Botan::PEM_Code::matches(in))
{
Botan::BER_Decoder decoder(in);
decode(decoder, INITIAL_LEVEL);
}
else
{
std::string label; // ignored
Botan::BER_Decoder decoder(Botan::PEM_Code::decode(in, label));
decode(decoder, INITIAL_LEVEL);
}
}
};
BOTAN_REGISTER_COMMAND("asn1print", ASN1_Printer);
}
#endif // BOTAN_HAS_ASN1 && BOTAN_HAS_PEM_CODEC
<commit_msg>Fix transcoding of asn1print strings to UTF-8<commit_after>/*
* (C) 2014,2015 Jack Lloyd
*
* Botan is released under the Simplified BSD License (see license.txt)
*/
#include "cli.h"
#if defined(BOTAN_HAS_ASN1) && defined(BOTAN_HAS_PEM_CODEC)
#include <botan/bigint.h>
#include <botan/hex.h>
#include <botan/der_enc.h>
#include <botan/ber_dec.h>
#include <botan/asn1_time.h>
#include <botan/asn1_str.h>
#include <botan/oids.h>
#include <botan/pem.h>
#include <botan/charset.h>
#include <iostream>
#include <iomanip>
#include <sstream>
#include <ctype.h>
// Set this if your terminal understands UTF-8; otherwise output is in Latin-1
#define UTF8_TERMINAL 1
/*
What level the outermost layer of stuff is at. Probably 0 or 1; asn1parse
uses 0 as the outermost, while 1 makes more sense to me. 2+ doesn't make
much sense at all.
*/
#define INITIAL_LEVEL 0
namespace Botan_CLI {
namespace {
std::string url_encode(const std::vector<uint8_t>& in)
{
std::ostringstream out;
size_t unprintable = 0;
for(size_t i = 0; i != in.size(); ++i)
{
const int c = in[i];
if(::isprint(c))
{
out << static_cast<char>(c);
}
else
{
out << "%" << std::hex << static_cast<int>(c) << std::dec;
++unprintable;
}
}
if(unprintable >= in.size() / 4)
{
return Botan::hex_encode(in);
}
return out.str();
}
void emit(const std::string& type, size_t level, size_t length, const std::string& value = "")
{
const size_t LIMIT = 4 * 1024;
const size_t BIN_LIMIT = 1024;
std::ostringstream out;
out << " d=" << std::setw(2) << level
<< ", l=" << std::setw(4) << length << ": ";
for(size_t i = INITIAL_LEVEL; i != level; ++i)
{
out << ' ';
}
out << type;
bool should_skip = false;
if(value.length() > LIMIT)
{
should_skip = true;
}
if((type == "OCTET STRING" || type == "BIT STRING") && value.length() > BIN_LIMIT)
{
should_skip = true;
}
if(value != "" && !should_skip)
{
if(out.tellp() % 2 == 0)
{
out << ' ';
}
while(out.tellp() < 50)
{
out << ' ';
}
out << value;
}
std::cout << out.str() << std::endl;
}
std::string type_name(Botan::ASN1_Tag type)
{
switch(type)
{
case Botan::PRINTABLE_STRING:
return "PRINTABLE STRING";
case Botan::NUMERIC_STRING:
return "NUMERIC STRING";
case Botan::IA5_STRING:
return "IA5 STRING";
case Botan::T61_STRING:
return "T61 STRING";
case Botan::UTF8_STRING:
return "UTF8 STRING";
case Botan::VISIBLE_STRING:
return "VISIBLE STRING";
case Botan::BMP_STRING:
return "BMP STRING";
case Botan::UTC_TIME:
return "UTC TIME";
case Botan::GENERALIZED_TIME:
return "GENERALIZED TIME";
case Botan::OCTET_STRING:
return "OCTET STRING";
case Botan::BIT_STRING:
return "BIT STRING";
case Botan::ENUMERATED:
return "ENUMERATED";
case Botan::INTEGER:
return "INTEGER";
case Botan::NULL_TAG:
return "NULL";
case Botan::OBJECT_ID:
return "OBJECT";
case Botan::BOOLEAN:
return "BOOLEAN";
default:
return "TAG(" + std::to_string(static_cast<size_t>(type)) + ")";
}
}
void decode(Botan::BER_Decoder& decoder, size_t level)
{
Botan::BER_Object obj = decoder.get_next_object();
while(obj.type_tag != Botan::NO_OBJECT)
{
const Botan::ASN1_Tag type_tag = obj.type_tag;
const Botan::ASN1_Tag class_tag = obj.class_tag;
const size_t length = obj.value.size();
/* hack to insert the tag+length back in front of the stuff now
that we've gotten the type info */
Botan::DER_Encoder encoder;
encoder.add_object(type_tag, class_tag, obj.value);
std::vector<uint8_t> bits = encoder.get_contents_unlocked();
Botan::BER_Decoder data(bits);
if(class_tag & Botan::CONSTRUCTED)
{
Botan::BER_Decoder cons_info(obj.value);
if(type_tag == Botan::SEQUENCE)
{
emit("SEQUENCE", level, length);
decode(cons_info, level + 1);
}
else if(type_tag == Botan::SET)
{
emit("SET", level, length);
decode(cons_info, level + 1);
}
else
{
std::string name;
if((class_tag & Botan::APPLICATION) || (class_tag & Botan::CONTEXT_SPECIFIC))
{
name = "cons [" + std::to_string(type_tag) + "]";
if(class_tag & Botan::APPLICATION)
{
name += " appl";
}
if(class_tag & Botan::CONTEXT_SPECIFIC)
{
name += " context";
}
}
else
{
name = type_name(type_tag) + " (cons)";
}
emit(name, level, length);
decode(cons_info, level + 1);
}
}
else if((class_tag & Botan::APPLICATION) || (class_tag & Botan::CONTEXT_SPECIFIC))
{
#if 0
std::vector<uint8_t> bits;
data.decode(bits, type_tag);
try
{
Botan::BER_Decoder inner(bits);
decode(inner, level + 1);
}
catch(...)
{
emit("[" + std::to_string(type_tag) + "]", level, length, url_encode(bits));
}
#else
emit("[" + std::to_string(type_tag) + "]", level, length, url_encode(bits));
#endif
}
else if(type_tag == Botan::OBJECT_ID)
{
Botan::OID oid;
data.decode(oid);
std::string out = Botan::OIDS::lookup(oid);
if(out != oid.as_string())
{
out += " [" + oid.as_string() + "]";
}
emit(type_name(type_tag), level, length, out);
}
else if(type_tag == Botan::INTEGER || type_tag == Botan::ENUMERATED)
{
Botan::BigInt number;
if(type_tag == Botan::INTEGER)
{
data.decode(number);
}
else if(type_tag == Botan::ENUMERATED)
{
data.decode(number, Botan::ENUMERATED, class_tag);
}
std::vector<uint8_t> rep;
/* If it's small, it's probably a number, not a hash */
if(number.bits() <= 20)
{
rep = Botan::BigInt::encode(number, Botan::BigInt::Decimal);
}
else
{
rep = Botan::BigInt::encode(number, Botan::BigInt::Hexadecimal);
}
std::string str;
for(size_t i = 0; i != rep.size(); ++i)
{
str += static_cast<char>(rep[i]);
}
emit(type_name(type_tag), level, length, str);
}
else if(type_tag == Botan::BOOLEAN)
{
bool boolean;
data.decode(boolean);
emit(type_name(type_tag), level, length, (boolean ? "true" : "false"));
}
else if(type_tag == Botan::NULL_TAG)
{
emit(type_name(type_tag), level, length);
}
else if(type_tag == Botan::OCTET_STRING)
{
std::vector<uint8_t> decoded_bits;
data.decode(decoded_bits, type_tag);
try
{
Botan::BER_Decoder inner(decoded_bits);
decode(inner, level + 1);
}
catch(...)
{
emit(type_name(type_tag), level, length, url_encode(decoded_bits));
}
}
else if(type_tag == Botan::BIT_STRING)
{
std::vector<uint8_t> decoded_bits;
data.decode(decoded_bits, type_tag);
std::vector<bool> bit_set;
for(size_t i = 0; i != decoded_bits.size(); ++i)
{
for(size_t j = 0; j != 8; ++j)
{
const bool bit = static_cast<bool>((decoded_bits[decoded_bits.size() - i - 1] >> (7 - j)) & 1);
bit_set.push_back(bit);
}
}
std::string bit_str;
for(size_t i = 0; i != bit_set.size(); ++i)
{
bool the_bit = bit_set[bit_set.size() - i - 1];
if(!the_bit && bit_str.size() == 0)
{
continue;
}
bit_str += (the_bit ? "1" : "0");
}
emit(type_name(type_tag), level, length, bit_str);
}
else if(type_tag == Botan::PRINTABLE_STRING ||
type_tag == Botan::NUMERIC_STRING ||
type_tag == Botan::IA5_STRING ||
type_tag == Botan::T61_STRING ||
type_tag == Botan::VISIBLE_STRING ||
type_tag == Botan::UTF8_STRING ||
type_tag == Botan::BMP_STRING)
{
Botan::ASN1_String str;
data.decode(str);
if(UTF8_TERMINAL)
{
emit(type_name(type_tag), level, length,
Botan::Charset::transcode(str.iso_8859(),
Botan::UTF8_CHARSET,
Botan::LATIN1_CHARSET));
}
else
{
emit(type_name(type_tag), level, length, str.iso_8859());
}
}
else if(type_tag == Botan::UTC_TIME || type_tag == Botan::GENERALIZED_TIME)
{
Botan::X509_Time time;
data.decode(time);
emit(type_name(type_tag), level, length, time.readable_string());
}
else
{
std::cout << "Unknown ASN.1 tag class="
<< static_cast<int>(class_tag)
<< " type="
<< static_cast<int>(type_tag) << std::endl;
}
obj = decoder.get_next_object();
}
}
}
class ASN1_Printer final : public Command
{
public:
ASN1_Printer() : Command("asn1print file") {}
void go() override
{
Botan::DataSource_Stream in(get_arg("file"));
if(!Botan::PEM_Code::matches(in))
{
Botan::BER_Decoder decoder(in);
decode(decoder, INITIAL_LEVEL);
}
else
{
std::string label; // ignored
Botan::BER_Decoder decoder(Botan::PEM_Code::decode(in, label));
decode(decoder, INITIAL_LEVEL);
}
}
};
BOTAN_REGISTER_COMMAND("asn1print", ASN1_Printer);
}
#endif // BOTAN_HAS_ASN1 && BOTAN_HAS_PEM_CODEC
<|endoftext|> |
<commit_before>// Copyright 2010-2014 RethinkDB, all rights reserved.
#ifndef BTREE_KEYS_HPP_
#define BTREE_KEYS_HPP_
#include <stddef.h>
#include <stdio.h>
#include <string.h>
#include <string>
#include "config/args.hpp"
#include "containers/archive/archive.hpp"
#include "rpc/serialize_macros.hpp"
#if defined(__GNUC__) && (100 * __GNUC__ + __GNUC_MINOR__ >= 406)
#pragma GCC diagnostic push
#pragma GCC diagnostic ignored "-Warray-bounds"
#endif
// Fast string compare
int sized_strcmp(const uint8_t *str1, int len1, const uint8_t *str2, int len2);
// Note: Changing this struct changes the format of the data stored on disk.
// If you change this struct, previous stored data will be misinterpreted.
struct btree_key_t {
uint8_t size;
uint8_t contents[];
uint16_t full_size() const {
return size + offsetof(btree_key_t, contents);
}
bool fits(int space) const {
return space > 0 && space > size;
}
} __attribute__((__packed__));
inline int btree_key_cmp(const btree_key_t *left, const btree_key_t *right) {
return sized_strcmp(left->contents, left->size, right->contents, right->size);
}
struct store_key_t {
public:
store_key_t() {
set_size(0);
}
store_key_t(int sz, const uint8_t *buf) {
assign(sz, buf);
}
store_key_t(const store_key_t &_key) {
assign(_key.size(), _key.contents());
}
explicit store_key_t(const btree_key_t *key) {
assign(key->size, key->contents);
}
explicit store_key_t(const std::string &s) {
assign(s.size(), reinterpret_cast<const uint8_t *>(s.data()));
}
btree_key_t *btree_key() { return reinterpret_cast<btree_key_t *>(buffer); }
const btree_key_t *btree_key() const {
return reinterpret_cast<const btree_key_t *>(buffer);
}
void set_size(int s) {
rassert(s <= MAX_KEY_SIZE);
btree_key()->size = s;
}
int size() const { return btree_key()->size; }
uint8_t *contents() { return btree_key()->contents; }
const uint8_t *contents() const { return btree_key()->contents; }
void assign(int sz, const uint8_t *buf) {
set_size(sz);
memcpy(contents(), buf, sz);
}
void assign(const btree_key_t *key) {
assign(key->size, key->contents);
}
static store_key_t min() {
return store_key_t(0, NULL);
}
static store_key_t max() {
uint8_t buf[MAX_KEY_SIZE];
for (int i = 0; i < MAX_KEY_SIZE; i++) {
buf[i] = 255;
}
return store_key_t(MAX_KEY_SIZE, buf);
}
bool increment() {
if (size() < MAX_KEY_SIZE) {
contents()[size()] = 0;
set_size(size() + 1);
return true;
}
while (size() > 0 && contents()[size()-1] == 255) {
set_size(size() - 1);
}
if (size() == 0) {
/* We were the largest possible key. Oops. Restore our previous
state and return `false`. */
*this = store_key_t::max();
return false;
}
(reinterpret_cast<uint8_t *>(contents()))[size()-1]++;
return true;
}
bool decrement() {
if (size() == 0) {
return false;
} else if ((reinterpret_cast<uint8_t *>(contents()))[size()-1] > 0) {
(reinterpret_cast<uint8_t *>(contents()))[size()-1]--;
for (int i = size(); i < MAX_KEY_SIZE; i++) {
contents()[i] = 255;
}
set_size(MAX_KEY_SIZE);
return true;
} else {
set_size(size() - 1);
return true;
}
}
int compare(const store_key_t& k) const {
return sized_strcmp(contents(), size(), k.contents(), k.size());
}
void rdb_serialize(write_message_t &msg /* NOLINT */) const {
uint8_t sz = size();
msg << sz;
msg.append(contents(), sz);
}
template <class T> friend archive_result_t deserialize(read_stream_t *, T *);
archive_result_t rdb_deserialize(read_stream_t *s) {
uint8_t sz;
archive_result_t res = deserialize(s, &sz);
if (bad(res)) { return res; }
int64_t num_read = force_read(s, contents(), sz);
if (num_read == -1) {
return archive_result_t::SOCK_ERROR;
}
if (num_read < sz) {
return archive_result_t::SOCK_EOF;
}
rassert(num_read == sz);
set_size(sz);
return archive_result_t::SUCCESS;
}
private:
char buffer[sizeof(btree_key_t) + MAX_KEY_SIZE];
};
inline bool operator==(const store_key_t &k1, const store_key_t &k2) {
return k1.size() == k2.size() && memcmp(k1.contents(), k2.contents(), k1.size()) == 0;
}
inline bool operator!=(const store_key_t &k1, const store_key_t &k2) {
return !(k1 == k2);
}
inline bool operator<(const store_key_t &k1, const store_key_t &k2) {
return k1.compare(k2) < 0;
}
inline bool operator>(const store_key_t &k1, const store_key_t &k2) {
return k2 < k1;
}
inline bool operator<=(const store_key_t &k1, const store_key_t &k2) {
return k1.compare(k2) <= 0;
}
inline bool operator>=(const store_key_t &k1, const store_key_t &k2) {
return k2 <= k1;
}
bool unescaped_str_to_key(const char *str, int len, store_key_t *buf);
std::string key_to_unescaped_str(const store_key_t &key);
std::string key_to_debug_str(const store_key_t &key);
std::string key_to_debug_str(const btree_key_t *key);
/* `key_range_t` represents a contiguous set of keys. */
struct key_range_t {
/* If `right.unbounded`, then the range contains all keys greater than or
equal to `left`. If `right.bounded`, then the range contains all keys
greater than or equal to `left` and less than `right.key`. */
struct right_bound_t {
right_bound_t() : unbounded(true) { }
explicit right_bound_t(store_key_t k) : unbounded(false), key(k) { }
bool unbounded;
store_key_t key;
};
enum bound_t {
open,
closed,
none
};
key_range_t(); /* creates a range containing no keys */
key_range_t(bound_t lm, const store_key_t &l,
bound_t rm, const store_key_t &r);
static key_range_t empty() THROWS_NOTHING {
return key_range_t();
}
static key_range_t universe() THROWS_NOTHING {
store_key_t k;
return key_range_t(key_range_t::none, k, key_range_t::none, k);
}
bool is_empty() const {
if (right.unbounded) {
return false;
} else {
rassert(left <= right.key);
return left == right.key;
}
}
bool contains_key(const store_key_t& key) const {
bool left_ok = left <= key;
bool right_ok = right.unbounded || key < right.key;
return left_ok && right_ok;
}
bool contains_key(const uint8_t *key, uint8_t size) const {
bool left_ok = sized_strcmp(left.contents(), left.size(), key, size) <= 0;
bool right_ok = right.unbounded || sized_strcmp(key, size, right.key.contents(), right.key.size()) < 0;
return left_ok && right_ok;
}
store_key_t last_key_in_range() const {
if (right.unbounded) {
return store_key_t::max();
} else {
return right.key;
}
}
bool is_superset(const key_range_t &other) const;
bool overlaps(const key_range_t &other) const;
key_range_t intersection(const key_range_t &other) const;
store_key_t left;
right_bound_t right;
};
RDB_DECLARE_SERIALIZABLE(key_range_t::right_bound_t);
RDB_DECLARE_SERIALIZABLE(key_range_t);
void debug_print(printf_buffer_t *buf, const store_key_t &k);
void debug_print(printf_buffer_t *buf, const store_key_t *k);
void debug_print(printf_buffer_t *buf, const key_range_t &kr);
std::string key_range_to_string(const key_range_t &kr);
bool operator==(const key_range_t::right_bound_t &a, const key_range_t::right_bound_t &b);
bool operator!=(const key_range_t::right_bound_t &a, const key_range_t::right_bound_t &b);
bool operator<(const key_range_t::right_bound_t &a, const key_range_t::right_bound_t &b);
bool operator<=(const key_range_t::right_bound_t &a, const key_range_t::right_bound_t &b);
bool operator>(const key_range_t::right_bound_t &a, const key_range_t::right_bound_t &b);
bool operator>=(const key_range_t::right_bound_t &a, const key_range_t::right_bound_t &b);
bool operator==(key_range_t, key_range_t) THROWS_NOTHING;
bool operator!=(key_range_t, key_range_t) THROWS_NOTHING;
bool operator<(const key_range_t &, const key_range_t &) THROWS_NOTHING;
#if defined(__GNUC__) && (100 * __GNUC__ + __GNUC_MINOR__ >= 406)
#pragma GCC diagnostic pop
#endif
#endif // BTREE_KEYS_HPP_
<commit_msg>btree: keys: remove unused method<commit_after>// Copyright 2010-2014 RethinkDB, all rights reserved.
#ifndef BTREE_KEYS_HPP_
#define BTREE_KEYS_HPP_
#include <stddef.h>
#include <stdio.h>
#include <string.h>
#include <string>
#include "config/args.hpp"
#include "containers/archive/archive.hpp"
#include "rpc/serialize_macros.hpp"
#if defined(__GNUC__) && (100 * __GNUC__ + __GNUC_MINOR__ >= 406)
#pragma GCC diagnostic push
#pragma GCC diagnostic ignored "-Warray-bounds"
#endif
// Fast string compare
int sized_strcmp(const uint8_t *str1, int len1, const uint8_t *str2, int len2);
// Note: Changing this struct changes the format of the data stored on disk.
// If you change this struct, previous stored data will be misinterpreted.
struct btree_key_t {
uint8_t size;
uint8_t contents[];
uint16_t full_size() const {
return size + offsetof(btree_key_t, contents);
}
} __attribute__((__packed__));
inline int btree_key_cmp(const btree_key_t *left, const btree_key_t *right) {
return sized_strcmp(left->contents, left->size, right->contents, right->size);
}
struct store_key_t {
public:
store_key_t() {
set_size(0);
}
store_key_t(int sz, const uint8_t *buf) {
assign(sz, buf);
}
store_key_t(const store_key_t &_key) {
assign(_key.size(), _key.contents());
}
explicit store_key_t(const btree_key_t *key) {
assign(key->size, key->contents);
}
explicit store_key_t(const std::string &s) {
assign(s.size(), reinterpret_cast<const uint8_t *>(s.data()));
}
btree_key_t *btree_key() { return reinterpret_cast<btree_key_t *>(buffer); }
const btree_key_t *btree_key() const {
return reinterpret_cast<const btree_key_t *>(buffer);
}
void set_size(int s) {
rassert(s <= MAX_KEY_SIZE);
btree_key()->size = s;
}
int size() const { return btree_key()->size; }
uint8_t *contents() { return btree_key()->contents; }
const uint8_t *contents() const { return btree_key()->contents; }
void assign(int sz, const uint8_t *buf) {
set_size(sz);
memcpy(contents(), buf, sz);
}
void assign(const btree_key_t *key) {
assign(key->size, key->contents);
}
static store_key_t min() {
return store_key_t(0, NULL);
}
static store_key_t max() {
uint8_t buf[MAX_KEY_SIZE];
for (int i = 0; i < MAX_KEY_SIZE; i++) {
buf[i] = 255;
}
return store_key_t(MAX_KEY_SIZE, buf);
}
bool increment() {
if (size() < MAX_KEY_SIZE) {
contents()[size()] = 0;
set_size(size() + 1);
return true;
}
while (size() > 0 && contents()[size()-1] == 255) {
set_size(size() - 1);
}
if (size() == 0) {
/* We were the largest possible key. Oops. Restore our previous
state and return `false`. */
*this = store_key_t::max();
return false;
}
(reinterpret_cast<uint8_t *>(contents()))[size()-1]++;
return true;
}
bool decrement() {
if (size() == 0) {
return false;
} else if ((reinterpret_cast<uint8_t *>(contents()))[size()-1] > 0) {
(reinterpret_cast<uint8_t *>(contents()))[size()-1]--;
for (int i = size(); i < MAX_KEY_SIZE; i++) {
contents()[i] = 255;
}
set_size(MAX_KEY_SIZE);
return true;
} else {
set_size(size() - 1);
return true;
}
}
int compare(const store_key_t& k) const {
return sized_strcmp(contents(), size(), k.contents(), k.size());
}
void rdb_serialize(write_message_t &msg /* NOLINT */) const {
uint8_t sz = size();
msg << sz;
msg.append(contents(), sz);
}
template <class T> friend archive_result_t deserialize(read_stream_t *, T *);
archive_result_t rdb_deserialize(read_stream_t *s) {
uint8_t sz;
archive_result_t res = deserialize(s, &sz);
if (bad(res)) { return res; }
int64_t num_read = force_read(s, contents(), sz);
if (num_read == -1) {
return archive_result_t::SOCK_ERROR;
}
if (num_read < sz) {
return archive_result_t::SOCK_EOF;
}
rassert(num_read == sz);
set_size(sz);
return archive_result_t::SUCCESS;
}
private:
char buffer[sizeof(btree_key_t) + MAX_KEY_SIZE];
};
inline bool operator==(const store_key_t &k1, const store_key_t &k2) {
return k1.size() == k2.size() && memcmp(k1.contents(), k2.contents(), k1.size()) == 0;
}
inline bool operator!=(const store_key_t &k1, const store_key_t &k2) {
return !(k1 == k2);
}
inline bool operator<(const store_key_t &k1, const store_key_t &k2) {
return k1.compare(k2) < 0;
}
inline bool operator>(const store_key_t &k1, const store_key_t &k2) {
return k2 < k1;
}
inline bool operator<=(const store_key_t &k1, const store_key_t &k2) {
return k1.compare(k2) <= 0;
}
inline bool operator>=(const store_key_t &k1, const store_key_t &k2) {
return k2 <= k1;
}
bool unescaped_str_to_key(const char *str, int len, store_key_t *buf);
std::string key_to_unescaped_str(const store_key_t &key);
std::string key_to_debug_str(const store_key_t &key);
std::string key_to_debug_str(const btree_key_t *key);
/* `key_range_t` represents a contiguous set of keys. */
struct key_range_t {
/* If `right.unbounded`, then the range contains all keys greater than or
equal to `left`. If `right.bounded`, then the range contains all keys
greater than or equal to `left` and less than `right.key`. */
struct right_bound_t {
right_bound_t() : unbounded(true) { }
explicit right_bound_t(store_key_t k) : unbounded(false), key(k) { }
bool unbounded;
store_key_t key;
};
enum bound_t {
open,
closed,
none
};
key_range_t(); /* creates a range containing no keys */
key_range_t(bound_t lm, const store_key_t &l,
bound_t rm, const store_key_t &r);
static key_range_t empty() THROWS_NOTHING {
return key_range_t();
}
static key_range_t universe() THROWS_NOTHING {
store_key_t k;
return key_range_t(key_range_t::none, k, key_range_t::none, k);
}
bool is_empty() const {
if (right.unbounded) {
return false;
} else {
rassert(left <= right.key);
return left == right.key;
}
}
bool contains_key(const store_key_t& key) const {
bool left_ok = left <= key;
bool right_ok = right.unbounded || key < right.key;
return left_ok && right_ok;
}
bool contains_key(const uint8_t *key, uint8_t size) const {
bool left_ok = sized_strcmp(left.contents(), left.size(), key, size) <= 0;
bool right_ok = right.unbounded || sized_strcmp(key, size, right.key.contents(), right.key.size()) < 0;
return left_ok && right_ok;
}
store_key_t last_key_in_range() const {
if (right.unbounded) {
return store_key_t::max();
} else {
return right.key;
}
}
bool is_superset(const key_range_t &other) const;
bool overlaps(const key_range_t &other) const;
key_range_t intersection(const key_range_t &other) const;
store_key_t left;
right_bound_t right;
};
RDB_DECLARE_SERIALIZABLE(key_range_t::right_bound_t);
RDB_DECLARE_SERIALIZABLE(key_range_t);
void debug_print(printf_buffer_t *buf, const store_key_t &k);
void debug_print(printf_buffer_t *buf, const store_key_t *k);
void debug_print(printf_buffer_t *buf, const key_range_t &kr);
std::string key_range_to_string(const key_range_t &kr);
bool operator==(const key_range_t::right_bound_t &a, const key_range_t::right_bound_t &b);
bool operator!=(const key_range_t::right_bound_t &a, const key_range_t::right_bound_t &b);
bool operator<(const key_range_t::right_bound_t &a, const key_range_t::right_bound_t &b);
bool operator<=(const key_range_t::right_bound_t &a, const key_range_t::right_bound_t &b);
bool operator>(const key_range_t::right_bound_t &a, const key_range_t::right_bound_t &b);
bool operator>=(const key_range_t::right_bound_t &a, const key_range_t::right_bound_t &b);
bool operator==(key_range_t, key_range_t) THROWS_NOTHING;
bool operator!=(key_range_t, key_range_t) THROWS_NOTHING;
bool operator<(const key_range_t &, const key_range_t &) THROWS_NOTHING;
#if defined(__GNUC__) && (100 * __GNUC__ + __GNUC_MINOR__ >= 406)
#pragma GCC diagnostic pop
#endif
#endif // BTREE_KEYS_HPP_
<|endoftext|> |
<commit_before>#ifndef _C4_SSTREAM_HPP_
#define _C4_SSTREAM_HPP_
#include "c4/config.hpp"
#include "c4/span.hpp"
#include <limits>
#include <inttypes.h>
C4_BEGIN_NAMESPACE(c4)
//-----------------------------------------------------------------------------
template< class T > struct fmt_tag {};
#define _C4_DEFINE_FMT_TAG(_ty, fmtstr) \
template<>\
struct fmt_tag< _ty >\
{\
static constexpr const char fmt[] = fmtstr;\
static constexpr const char fmt_with_num_chars_arg[] = fmtstr "%n";\
}
_C4_DEFINE_FMT_TAG(void * , "%p" );
_C4_DEFINE_FMT_TAG(char , "%c" );
_C4_DEFINE_FMT_TAG(char * , "%s" );
_C4_DEFINE_FMT_TAG(double , "%lg" );
_C4_DEFINE_FMT_TAG(float , "%g" );
_C4_DEFINE_FMT_TAG( int64_t, /*"%lld"*/"%"PRId64);
_C4_DEFINE_FMT_TAG(uint64_t, /*"%llu"*/"%"PRIu64);
_C4_DEFINE_FMT_TAG( int32_t, /*"%d" */"%"PRId32);
_C4_DEFINE_FMT_TAG(uint32_t, /*"%u" */"%"PRIu32);
_C4_DEFINE_FMT_TAG( int16_t, /*"%hd" */"%"PRId16);
_C4_DEFINE_FMT_TAG(uint16_t, /*"%hu" */"%"PRIu16);
_C4_DEFINE_FMT_TAG( int8_t , /*"%hhd"*/"%"PRId8 );
_C4_DEFINE_FMT_TAG(uint8_t , /*"%hhu"*/"%"PRIu8 );
//-----------------------------------------------------------------------------
//-----------------------------------------------------------------------------
//-----------------------------------------------------------------------------
class sstream
{
private:
char* m_buf;
size_t m_size;
size_t m_putpos;
size_t m_getpos;
size_t m_status;
public:
static constexpr const size_t npos = size_t(-1);
using char_type = char;
using size_type = size_t;
using span_type = span<char, size_t>;
using cspan_type = cspan<char, size_t>;
public:
sstream();
~sstream();
sstream(sstream const&) = delete;
sstream(sstream &&) = default;
sstream& operator=(sstream const&) = delete;
sstream& operator=(sstream &&) = default;
constexpr size_t max_size() const
{
return std::numeric_limits< size_t >::max() - 1;
}
void reset()
{
seekp(0);
seekg(0);
clear_err();
}
public:
// conversion to/from string
/* COMING UP
template< class T >
const char* to_string(T const& v);
template< class T >
void from_string(const char *s, size_t size, T& v);
*/
public:
// Raw writing of characters
void write(const char *str, size_t sz); ///< write a sequence of characters
void read (char *str, size_t sz); ///< read a sequence of characters
///< write a null-terminated sequence of characters
void write(const char *cstr);
///< write a sequence of characters
C4_ALWAYS_INLINE void write(cspan_type const& s) { write(s.data(), s.size()); }
///< read a sequence of characters
C4_ALWAYS_INLINE void read ( span_type & s) { read(s.data(), s.size()); }
public:
/* C-style formatted print. */
void printf(const char *fmt, ...) C4_ATTR_FORMAT(printf, 1, 2);
void vprintf(const char *fmt, va_list args);
/* Due to how std::*scanf() is implemented, we do not provide public
* scanf functions, as it is impossible to determine the number
* of characters read from the buffer unless a %n argument is
* used as the last format spec. This is something which we have no way
* of imposing on the clients (and could not act on, either way,
* because we're blind to the arguments passed by the client). */
public:
/* python-style type-safe write/read with arguments indicated as {}.
* This is a minimal version:
* ---> no positional arguments (eg {0} or {1})
* ---> no named arguments (eg {foo} or {bar})
* ---> no formatting of the arguments themselves
* If any the above are needed then consider the C-style printf/scanf functions.
* If type-safety is needed, then consider using fmtlib: https://github.com/fmtlib/fmt */
/** python-style type-safe formatted print. Eg: stream.printp("hello I am {} years old", age); */
template <class... Args>
C4_ALWAYS_INLINE void printp(const char* fmt, Args&& ...more)
{
printp_(fmt, std::forward<Args>(more)...);
}
/** python-style type-safe formatted scan. Eg: stream.scanp("hello I am {} years old", age);
*
* @warning the format string is not checked against the stream; it is
* merely used for skipping (the same number of) characters until the
* next argument. */
template <class... Args>
C4_ALWAYS_INLINE void scanp(const char* fmt, Args&& ...more)
{
scanp_(fmt, std::forward<Args>(more)...);
}
public:
// R-style: append several arguments, formatting them each as a string
// and writing them together WITHOUT separation
/// put the given arguments into the stream, without any separation character
template <class T, class... MoreArgs>
void cat(T const& arg, MoreArgs&& ...more)
{
*this << arg;
cat(std::forward< MoreArgs >(more)...);
}
/// read the given arguments from the stream, without any separation character
template <class T, class... MoreArgs>
void uncat(T & arg, MoreArgs&& ...more)
{
*this >> arg;
uncat(std::forward< MoreArgs >(more)...);
}
public:
/** R-style: append several arguments, formatting them each as a string
* and writing them together separated by the given character */
template <class... Args>
C4_ALWAYS_INLINE void catsep(char sep, Args&& ...args)
{
catsep_(sep, std::forward<Args>(args)...);
}
template <class... Args>
C4_ALWAYS_INLINE void uncatsep(char sep, Args&& ...args)
{
uncatsep_(std::forward<Args>(args)...);
}
public:
/// get the full resulting string (from 0 to tellp)
C4_ALWAYS_INLINE const char* c_str() const { C4_XASSERT(m_buf[m_putpos] == '\0'); return m_buf; }
/// get the current reading string (from tellg to tellp)
C4_ALWAYS_INLINE const char* c_strg() const { C4_XASSERT(m_getpos < m_putpos && m_buf[m_putpos] == '\0'); return m_buf + m_getpos; }
/// get the full resulting span (from 0 to tellp)
C4_ALWAYS_INLINE cspan_type span() const { return cspan_type(m_buf, m_putpos); }
/// get the current reading span (from tellg to to tellp)
C4_ALWAYS_INLINE cspan_type spang() const { return cspan_type(m_buf + m_getpos, m_putpos - m_getpos); }
public:
/// get the current write (ie, put) position
C4_ALWAYS_INLINE size_t tellp() const { return m_putpos; }
/// get the current read (ie, get) position
C4_ALWAYS_INLINE size_t tellg() const { return m_getpos; }
/// set the current write (ie, put) position
C4_ALWAYS_INLINE void seekp(size_t p) { C4_CHECK(p <= m_size); m_putpos = p; }
/// set the current read (ie, get) position
C4_ALWAYS_INLINE void seekg(size_t g) { C4_CHECK(g <= m_size && g <= m_putpos); m_getpos = g; }
/// advance the current write (ie, put) position
C4_ALWAYS_INLINE void advp(size_t p) { C4_CHECK(m_size - m_putpos >= p); m_putpos += p; }
/// advance the current read (ie, get) position
C4_ALWAYS_INLINE void advg(size_t g) { C4_CHECK(m_putpos - m_getpos >= g); m_getpos += g; }
/// remaining size for writing (ie, put), WITHOUT terminating null character
C4_ALWAYS_INLINE size_t remp() const { C4_XASSERT(m_putpos <= m_size); return m_size - m_putpos; }
/// remaining size for reading (ie, get)
C4_ALWAYS_INLINE size_t remg() const { C4_XASSERT(m_getpos <= m_putpos); return m_putpos - m_getpos; }
/// true if sz chars can be written (from tellp to the current max_size())
C4_ALWAYS_INLINE bool okp(size_t sz) const { return sz <= (max_size() - m_putpos); }
/// true if sz chars can be read (from tellg to the current tellp)
C4_ALWAYS_INLINE bool okg(size_t sz) const { return sz <= remg(); }
public:
C4_ALWAYS_INLINE char get() { char c; read(&c, 1); return c; }
C4_ALWAYS_INLINE sstream& get(char &c) { read(&c, 1); return *this; }
C4_ALWAYS_INLINE sstream& put(char c) { write(&c, 1); return *this; }
C4_ALWAYS_INLINE char peek() { return peek(1); }
char peek(size_t ahead);
public:
// error handling and recovery
typedef enum {
/** The write buffer has been exhausted and cannot be further increased.
* Trying to write again will cause a C4_ERROR unless IGNORE_ERR is set. */
EOFP = 0x01,
/** The read buffer has been exhausted (ie, it has reached the end of the write buffer).
* Trying to read again will cause a C4_ERROR unless IGNORE_ERR is set. */
EOFG = 0x01 << 1,
/** a reading error has occurred: could not convert the string to the argument's
* intrinsic type. Trying to read further will cause a C4_ERROR unless IGNORE_ERR is set. */
FAIL = 0x01 << 2,
/** do not call C4_ERROR when errors occur; silently continue. */
IGNORE_ERR = 0x01 << 3
} Status_e;
C4_ALWAYS_INLINE size_t stat() const { return m_status; }
C4_ALWAYS_INLINE void clear_err() { m_status &= ~(EOFG|EOFP|FAIL); }
C4_ALWAYS_INLINE void ignore_err(bool yes) { if(yes) m_status |= IGNORE_ERR; else m_status &= ~IGNORE_ERR; }
C4_ALWAYS_INLINE bool ignore_err() const { return m_status & IGNORE_ERR; }
C4_ALWAYS_INLINE bool eofp() const { return m_status & EOFP; }
C4_ALWAYS_INLINE bool eofg() const { return m_status & EOFG; }
C4_ALWAYS_INLINE bool fail() const { return m_status & FAIL; }
private:
void errp_();
void errg_();
void resize_(size_t sz);
bool growto_(size_t sz);
template <class T, class... MoreArgs>
void printp_(const char* fmt, T const& arg, MoreArgs&& ...more);
template <class T, class... MoreArgs>
void scanp_(const char* fmt, T & arg, MoreArgs&& ...more);
static size_t nextarg_(const char *fmt) ;
template <class T, class... MoreArgs>
void catsep_(char sep, T const& arg, MoreArgs&& ...more)
{
*this << arg << sep;
catsep_(sep, std::forward<MoreArgs>(more)...);
}
template <class T, class... MoreArgs>
void uncatsep_(T & arg, MoreArgs&& ...more)
{
char sep;
*this >> arg >> sep;
uncatsep_(std::forward<MoreArgs>(more)...);
}
// terminate recursion for variadic templates
C4_ALWAYS_INLINE void cat() {}
C4_ALWAYS_INLINE void uncat() {}
C4_ALWAYS_INLINE void catsep_(char) {}
C4_ALWAYS_INLINE void uncatsep_() {}
C4_ALWAYS_INLINE void printp_(const char* fmt)
{
write(fmt);
}
void scanp_(const char *fmt)
{
while(*fmt != '\0')
{
++m_getpos; // skip as many chars as those from the fmt
++fmt;
}
}
public:
void scanf____(const char *fmt, void *arg);
};
//-----------------------------------------------------------------------------
template< class T, C4_REQUIRE_T(std::is_scalar< T >::value) >
C4_ALWAYS_INLINE sstream& operator<< (sstream& ss, T const& var)
{
using tag = fmt_tag< typename std::remove_const<T>::type >;
ss.printf(tag::fmt, var);
return ss;
}
template< class T, C4_REQUIRE_T(std::is_scalar< T >::value) >
C4_ALWAYS_INLINE sstream& operator>> (sstream& ss, T & var)
{
using tag = fmt_tag< typename std::remove_const<T>::type >;
ss.scanf____(tag::fmt_with_num_chars_arg, (void*)&var);
return ss;
}
C4_ALWAYS_INLINE sstream& operator<< (sstream& ss, char const& var)
{
ss.write(&var, 1);
return ss;
}
C4_ALWAYS_INLINE sstream& operator>> (sstream& ss, char & var)
{
ss.read(&var, 1);
return ss;
}
template< size_t N >
C4_ALWAYS_INLINE sstream& operator<< (sstream& ss, const char (&var)[N])
{
ss.printf("%.*s", (int)(N-1), &var[0]);
return ss;
}
template< size_t N >
C4_ALWAYS_INLINE sstream& operator>> (sstream& ss, char (&var)[N])
{
ss.scanf("%.*s", (int)(N-1), &var[0]);
return ss;
}
C4_END_NAMESPACE(c4)
#include "c4/sstream.def.hpp"
#endif /* _C4_SSTREAM_HPP_ */
<commit_msg>sstream chevron operator: use overloads instead of a template<commit_after>#ifndef _C4_SSTREAM_HPP_
#define _C4_SSTREAM_HPP_
#include "c4/config.hpp"
#include "c4/span.hpp"
#include <limits>
#include <inttypes.h>
C4_BEGIN_NAMESPACE(c4)
//-----------------------------------------------------------------------------
//-----------------------------------------------------------------------------
//-----------------------------------------------------------------------------
class sstream
{
private:
char* m_buf;
size_t m_size;
size_t m_putpos;
size_t m_getpos;
size_t m_status;
public:
static constexpr const size_t npos = size_t(-1);
using char_type = char;
using size_type = size_t;
using span_type = span<char, size_t>;
using cspan_type = cspan<char, size_t>;
public:
sstream();
~sstream();
sstream(sstream const&) = delete;
sstream(sstream &&) = default;
sstream& operator=(sstream const&) = delete;
sstream& operator=(sstream &&) = default;
constexpr size_t max_size() const
{
return std::numeric_limits< size_t >::max() - 1;
}
void reset()
{
seekp(0);
seekg(0);
clear_err();
}
public:
// conversion to/from string
/* COMING UP
template< class T >
const char* to_string(T const& v);
template< class T >
void from_string(const char *s, size_t size, T& v);
*/
public:
// Raw writing of characters
void write(const char *str, size_t sz); ///< write a sequence of characters
void read (char *str, size_t sz); ///< read a sequence of characters
///< write a null-terminated sequence of characters
void write(const char *cstr);
///< write a sequence of characters
C4_ALWAYS_INLINE void write(cspan_type const& s) { write(s.data(), s.size()); }
///< read a sequence of characters
C4_ALWAYS_INLINE void read ( span_type & s) { read(s.data(), s.size()); }
public:
/* C-style formatted print. */
void printf(const char *fmt, ...) C4_ATTR_FORMAT(printf, 1, 2);
void vprintf(const char *fmt, va_list args);
/* Due to how std::*scanf() is implemented, we do not provide public
* scanf functions, as it is impossible to determine the number
* of characters read from the buffer unless a %n argument is
* used as the last format spec. This is something which we have no way
* of imposing on the clients (and could not act on, either way,
* because we're blind to the arguments passed by the client). */
public:
/* python-style type-safe write/read with arguments indicated as {}.
* This is a minimal version:
* ---> no positional arguments (eg {0} or {1})
* ---> no named arguments (eg {foo} or {bar})
* ---> no formatting of the arguments themselves
* If any the above are needed then consider the C-style printf/scanf functions.
* If type-safety is needed, then consider using fmtlib: https://github.com/fmtlib/fmt */
/** python-style type-safe formatted print. Eg: stream.printp("hello I am {} years old", age); */
template <class... Args>
C4_ALWAYS_INLINE void printp(const char* fmt, Args&& ...more)
{
printp_(fmt, std::forward<Args>(more)...);
}
/** python-style type-safe formatted scan. Eg: stream.scanp("hello I am {} years old", age);
*
* @warning the format string is not checked against the stream; it is
* merely used for skipping (the same number of) characters until the
* next argument. */
template <class... Args>
C4_ALWAYS_INLINE void scanp(const char* fmt, Args&& ...more)
{
scanp_(fmt, std::forward<Args>(more)...);
}
public:
// R-style: append several arguments, formatting them each as a string
// and writing them together WITHOUT separation
/// put the given arguments into the stream, without any separation character
template <class T, class... MoreArgs>
void cat(T const& arg, MoreArgs&& ...more)
{
*this << arg;
cat(std::forward< MoreArgs >(more)...);
}
/// read the given arguments from the stream, without any separation character
template <class T, class... MoreArgs>
void uncat(T & arg, MoreArgs&& ...more)
{
*this >> arg;
uncat(std::forward< MoreArgs >(more)...);
}
public:
/** R-style: append several arguments, formatting them each as a string
* and writing them together separated by the given character */
template <class... Args>
C4_ALWAYS_INLINE void catsep(char sep, Args&& ...args)
{
catsep_(sep, std::forward<Args>(args)...);
}
template <class... Args>
C4_ALWAYS_INLINE void uncatsep(char sep, Args&& ...args)
{
uncatsep_(std::forward<Args>(args)...);
}
public:
/// get the full resulting string (from 0 to tellp)
C4_ALWAYS_INLINE const char* c_str() const { C4_XASSERT(m_buf[m_putpos] == '\0'); return m_buf; }
/// get the current reading string (from tellg to tellp)
C4_ALWAYS_INLINE const char* c_strg() const { C4_XASSERT(m_getpos < m_putpos && m_buf[m_putpos] == '\0'); return m_buf + m_getpos; }
/// get the full resulting span (from 0 to tellp)
C4_ALWAYS_INLINE cspan_type span() const { return cspan_type(m_buf, m_putpos); }
/// get the current reading span (from tellg to to tellp)
C4_ALWAYS_INLINE cspan_type spang() const { return cspan_type(m_buf + m_getpos, m_putpos - m_getpos); }
public:
/// get the current write (ie, put) position
C4_ALWAYS_INLINE size_t tellp() const { return m_putpos; }
/// get the current read (ie, get) position
C4_ALWAYS_INLINE size_t tellg() const { return m_getpos; }
/// set the current write (ie, put) position
C4_ALWAYS_INLINE void seekp(size_t p) { C4_CHECK(p <= m_size); m_putpos = p; }
/// set the current read (ie, get) position
C4_ALWAYS_INLINE void seekg(size_t g) { C4_CHECK(g <= m_size && g <= m_putpos); m_getpos = g; }
/// advance the current write (ie, put) position
C4_ALWAYS_INLINE void advp(size_t p) { C4_CHECK(m_size - m_putpos >= p); m_putpos += p; }
/// advance the current read (ie, get) position
C4_ALWAYS_INLINE void advg(size_t g) { C4_CHECK(m_putpos - m_getpos >= g); m_getpos += g; }
/// remaining size for writing (ie, put), WITHOUT terminating null character
C4_ALWAYS_INLINE size_t remp() const { C4_XASSERT(m_putpos <= m_size); return m_size - m_putpos; }
/// remaining size for reading (ie, get)
C4_ALWAYS_INLINE size_t remg() const { C4_XASSERT(m_getpos <= m_putpos); return m_putpos - m_getpos; }
/// true if sz chars can be written (from tellp to the current max_size())
C4_ALWAYS_INLINE bool okp(size_t sz) const { return sz <= (max_size() - m_putpos); }
/// true if sz chars can be read (from tellg to the current tellp)
C4_ALWAYS_INLINE bool okg(size_t sz) const { return sz <= remg(); }
public:
C4_ALWAYS_INLINE char get() { char c; read(&c, 1); return c; }
C4_ALWAYS_INLINE sstream& get(char &c) { read(&c, 1); return *this; }
C4_ALWAYS_INLINE sstream& put(char c) { write(&c, 1); return *this; }
C4_ALWAYS_INLINE char peek() { return peek(1); }
char peek(size_t ahead);
public:
// error handling and recovery
typedef enum {
/** The write buffer has been exhausted and cannot be further increased.
* Trying to write again will cause a C4_ERROR unless IGNORE_ERR is set. */
EOFP = 0x01,
/** The read buffer has been exhausted (ie, it has reached the end of the write buffer).
* Trying to read again will cause a C4_ERROR unless IGNORE_ERR is set. */
EOFG = 0x01 << 1,
/** a reading error has occurred: could not convert the string to the argument's
* intrinsic type. Trying to read further will cause a C4_ERROR unless IGNORE_ERR is set. */
FAIL = 0x01 << 2,
/** do not call C4_ERROR when errors occur; silently continue. */
IGNORE_ERR = 0x01 << 3
} Status_e;
C4_ALWAYS_INLINE size_t stat() const { return m_status; }
C4_ALWAYS_INLINE void clear_err() { m_status &= ~(EOFG|EOFP|FAIL); }
C4_ALWAYS_INLINE void ignore_err(bool yes) { if(yes) m_status |= IGNORE_ERR; else m_status &= ~IGNORE_ERR; }
C4_ALWAYS_INLINE bool ignore_err() const { return m_status & IGNORE_ERR; }
C4_ALWAYS_INLINE bool eofp() const { return m_status & EOFP; }
C4_ALWAYS_INLINE bool eofg() const { return m_status & EOFG; }
C4_ALWAYS_INLINE bool fail() const { return m_status & FAIL; }
private:
void errp_();
void errg_();
void resize_(size_t sz);
bool growto_(size_t sz);
template <class T, class... MoreArgs>
void printp_(const char* fmt, T const& arg, MoreArgs&& ...more);
template <class T, class... MoreArgs>
void scanp_(const char* fmt, T & arg, MoreArgs&& ...more);
static size_t nextarg_(const char *fmt) ;
template <class T, class... MoreArgs>
void catsep_(char sep, T const& arg, MoreArgs&& ...more)
{
*this << arg << sep;
catsep_(sep, std::forward<MoreArgs>(more)...);
}
template <class T, class... MoreArgs>
void uncatsep_(T & arg, MoreArgs&& ...more)
{
char sep;
*this >> arg >> sep;
uncatsep_(std::forward<MoreArgs>(more)...);
}
// terminate recursion for variadic templates
C4_ALWAYS_INLINE void cat() {}
C4_ALWAYS_INLINE void uncat() {}
C4_ALWAYS_INLINE void catsep_(char) {}
C4_ALWAYS_INLINE void uncatsep_() {}
C4_ALWAYS_INLINE void printp_(const char* fmt)
{
write(fmt);
}
void scanp_(const char *fmt)
{
while(*fmt != '\0')
{
++m_getpos; // skip as many chars as those from the fmt
++fmt;
}
}
public:
void scanf____(const char *fmt, void *arg);
};
//-----------------------------------------------------------------------------
template< class T > struct fmt_tag {};
#define _C4_DEFINE_FMT_TAG(_ty, fmtstr) \
template<>\
struct fmt_tag< _ty >\
{\
static constexpr const char fmt[] = fmtstr;\
static constexpr const char fmtn[] = fmtstr "%n";\
}
#define _C4_DEFINE_SCALAR_IO_OPERATOR(ty) \
C4_ALWAYS_INLINE sstream& operator<< (sstream& ss, ty var) { ss.printf (fmt_tag< ty >::fmt , var); return ss; }\
C4_ALWAYS_INLINE sstream& operator>> (sstream& ss, ty& var) { ss.scanf____(fmt_tag< ty >::fmtn, &var); return ss; }
_C4_DEFINE_FMT_TAG(void * , "%p" );
_C4_DEFINE_FMT_TAG(char , "%c" );
_C4_DEFINE_FMT_TAG(char * , "%s" );
_C4_DEFINE_FMT_TAG(double , "%lg" );
_C4_DEFINE_FMT_TAG(float , "%g" );
_C4_DEFINE_FMT_TAG( int64_t, /*"%lld"*/"%"PRId64);
_C4_DEFINE_FMT_TAG(uint64_t, /*"%llu"*/"%"PRIu64);
_C4_DEFINE_FMT_TAG( int32_t, /*"%d" */"%"PRId32);
_C4_DEFINE_FMT_TAG(uint32_t, /*"%u" */"%"PRIu32);
_C4_DEFINE_FMT_TAG( int16_t, /*"%hd" */"%"PRId16);
_C4_DEFINE_FMT_TAG(uint16_t, /*"%hu" */"%"PRIu16);
_C4_DEFINE_FMT_TAG( int8_t , /*"%hhd"*/"%"PRId8 );
_C4_DEFINE_FMT_TAG(uint8_t , /*"%hhu"*/"%"PRIu8 );
_C4_DEFINE_SCALAR_IO_OPERATOR(void* )
_C4_DEFINE_SCALAR_IO_OPERATOR(char* )
_C4_DEFINE_SCALAR_IO_OPERATOR( int8_t )
_C4_DEFINE_SCALAR_IO_OPERATOR(uint8_t )
_C4_DEFINE_SCALAR_IO_OPERATOR( int16_t)
_C4_DEFINE_SCALAR_IO_OPERATOR(uint16_t)
_C4_DEFINE_SCALAR_IO_OPERATOR( int32_t)
_C4_DEFINE_SCALAR_IO_OPERATOR(uint32_t)
_C4_DEFINE_SCALAR_IO_OPERATOR( int64_t)
_C4_DEFINE_SCALAR_IO_OPERATOR(uint64_t)
_C4_DEFINE_SCALAR_IO_OPERATOR(float )
_C4_DEFINE_SCALAR_IO_OPERATOR(double )
C4_ALWAYS_INLINE sstream& operator<< (sstream& ss, char var) { ss.write(&var, 1); return ss; }\
C4_ALWAYS_INLINE sstream& operator>> (sstream& ss, char& var) { ss.read(&var, 1); return ss; }
template< size_t N >
C4_ALWAYS_INLINE sstream& operator<< (sstream& ss, const char (&var)[N])
{
ss.printf("%.*s", (int)(N-1), &var[0]);
return ss;
}
template< size_t N >
C4_ALWAYS_INLINE sstream& operator>> (sstream& ss, char (&var)[N])
{
ss.scanf("%.*s", (int)(N-1), &var[0]);
return ss;
}
C4_END_NAMESPACE(c4)
#include "c4/sstream.def.hpp"
#endif /* _C4_SSTREAM_HPP_ */
<|endoftext|> |
<commit_before>/* BEGIN_COMMON_COPYRIGHT_HEADER
* (c)LGPL2+
*
* Razor - a lightweight, Qt based, desktop toolset
* http://razor-qt.org
*
* Copyright: 2012 Razor team
* Authors:
* Łukasz Twarduś <ltwardus@gmail.com>
*
* This program or 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 Street, Fifth Floor,
* Boston, MA 02110-1301 USA
*
* END_COMMON_COPYRIGHT_HEADER */
#include "razorsensors.h"
#include "razorsensorsconfiguration.h"
#include "../panel/irazorpanelplugin.h"
#include "../panel/irazorpanel.h"
#include <QtGui/QMessageBox>
#include <QtGui/QPalette>
#include <QtCore/QDebug>
#include <QBoxLayout>
RazorSensors::RazorSensors(IRazorPanelPlugin *plugin, QWidget* parent):
QFrame(parent),
mPlugin(plugin),
mSettings(plugin->settings())
{
mDetectedChips = mSensors.getDetectedChips();
/**
* We have all needed data to initialize default settings, we have to do it here as later
* we are using them.
*/
initDefaultSettings();
// Add GUI elements
ProgressBar* pg = NULL;
mLayout = new QBoxLayout(QBoxLayout::LeftToRight, this);
mLayout->setSpacing(0);
QString chipFeatureLabel;
mSettings->beginGroup("chips");
for (unsigned int i = 0; i < mDetectedChips.size(); ++i)
{
mSettings->beginGroup(QString::fromStdString(mDetectedChips[i].getName()));
const std::vector<Feature>& features = mDetectedChips[i].getFeatures();
for (unsigned int j = 0; j < features.size(); ++j)
{
if (features[j].getType() == SENSORS_FEATURE_TEMP)
{
chipFeatureLabel = QString::fromStdString(features[j].getLabel());
mSettings->beginGroup(chipFeatureLabel);
pg = new ProgressBar(this);
pg->setSizePolicy(QSizePolicy::Preferred, QSizePolicy::Preferred);
// Hide progress bar if it is not enabled
if (!mSettings->value("enabled").toBool())
{
pg->hide();
}
pg->setToolTip(chipFeatureLabel);
pg->setTextVisible(false);
QPalette pal = pg->palette();
QColor color(mSettings->value("color").toString());
pal.setColor(QPalette::Active, QPalette::Highlight, color);
pal.setColor(QPalette::Inactive, QPalette::Highlight, color);
pg->setPalette(pal);
mTemperatureProgressBars.push_back(pg);
mLayout->addWidget(pg);
mSettings->endGroup();
}
}
mSettings->endGroup();
}
mSettings->endGroup();
// Fit plugin to current panel
realign();
// Updated sensors readings to display actual values at start
updateSensorReadings();
// Run timer that will be updating sensor readings
mUpdateSensorReadingsTimer.setParent(this);
connect(&mUpdateSensorReadingsTimer, SIGNAL(timeout()), this, SLOT(updateSensorReadings()));
mUpdateSensorReadingsTimer.start(mSettings->value("updateInterval").toInt() * 1000);
// Run timer that will be showin warning
mWarningAboutHighTemperatureTimer.setParent(this);
connect(&mWarningAboutHighTemperatureTimer, SIGNAL(timeout()), this,
SLOT(warningAboutHighTemperature()));
if (mSettings->value("warningAboutHighTemperature").toBool())
{
mWarningAboutHighTemperatureTimer.start(mWarningAboutHighTemperatureTimerFreq);
}
}
RazorSensors::~RazorSensors()
{
}
void RazorSensors::updateSensorReadings()
{
QString tooltip;
double critTemp = 0;
double maxTemp = 0;
double minTemp = 0;
double curTemp = 0;
bool highTemperature = false;
// Iterator for temperature progress bars
std::vector<ProgressBar*>::iterator temperatureProgressBarsIt =
mTemperatureProgressBars.begin();
for (unsigned int i = 0; i < mDetectedChips.size(); ++i)
{
const std::vector<Feature>& features = mDetectedChips[i].getFeatures();
for (unsigned int j = 0; j < features.size(); ++j)
{
if (features[j].getType() == SENSORS_FEATURE_TEMP)
{
tooltip = QString::fromStdString(features[j].getLabel()) + " (" + QChar(0x00B0);
if (mSettings->value("useFahrenheitScale").toBool())
{
critTemp = celsiusToFahrenheit(
features[j].getValue(SENSORS_SUBFEATURE_TEMP_CRIT));
maxTemp = celsiusToFahrenheit(
features[j].getValue(SENSORS_SUBFEATURE_TEMP_MAX));
minTemp = celsiusToFahrenheit(
features[j].getValue(SENSORS_SUBFEATURE_TEMP_MIN));
curTemp = celsiusToFahrenheit(
features[j].getValue(SENSORS_SUBFEATURE_TEMP_INPUT));
tooltip += "F)";
}
else
{
critTemp = features[j].getValue(SENSORS_SUBFEATURE_TEMP_CRIT);
maxTemp = features[j].getValue(SENSORS_SUBFEATURE_TEMP_MAX);
minTemp = features[j].getValue(SENSORS_SUBFEATURE_TEMP_MIN);
curTemp = features[j].getValue(SENSORS_SUBFEATURE_TEMP_INPUT);
tooltip += "C)";
}
// Check if temperature is too high
if (curTemp >= maxTemp)
{
if (mSettings->value("warningAboutHighTemperature").toBool())
{
// Add current progress bar to the "warning container"
mHighTemperatureProgressBars.insert(*temperatureProgressBarsIt);
}
highTemperature = true;
}
else
{
mHighTemperatureProgressBars.erase(*temperatureProgressBarsIt);
highTemperature = false;
}
// Set maximum temperature
(*temperatureProgressBarsIt)->setMaximum(critTemp);
// Set minimum temperature
(*temperatureProgressBarsIt)->setMinimum(minTemp);
// Set current temperature
(*temperatureProgressBarsIt)->setValue(curTemp);
tooltip += "<br><br>Crit: ";
tooltip += QString::number((*temperatureProgressBarsIt)->maximum());
tooltip += "<br>Max: ";
tooltip += QString::number(int(maxTemp));
tooltip += "<br>Cur: ";
// Mark high temperature in the tooltip
if (highTemperature)
{
tooltip += "<span style=\"font-size:8pt; font-weight:600; color:#FF0000;\">";
tooltip += QString::number((*temperatureProgressBarsIt)->value());
tooltip += " !</span>";
}
else
{
tooltip += QString::number((*temperatureProgressBarsIt)->value());
}
tooltip += "<br>Min: ";
tooltip += QString::number((*temperatureProgressBarsIt)->minimum());
(*temperatureProgressBarsIt)->setToolTip(tooltip);
// Go to the next temperature progress bar
++temperatureProgressBarsIt;
}
}
}
update();
}
void RazorSensors::warningAboutHighTemperature()
{
// Iterator for temperature progress bars
std::set<ProgressBar*>::iterator temperatureProgressBarsIt =
mHighTemperatureProgressBars.begin();
int curValue;
int maxValue;
for (; temperatureProgressBarsIt != mHighTemperatureProgressBars.end();
++temperatureProgressBarsIt)
{
curValue = (*temperatureProgressBarsIt)->value();
maxValue = (*temperatureProgressBarsIt)->maximum();
if (maxValue > curValue)
{
(*temperatureProgressBarsIt)->setValue(maxValue);
}
else
{
(*temperatureProgressBarsIt)->setValue((*temperatureProgressBarsIt)->minimum());
}
}
update();
}
void RazorSensors::settingsChanged()
{
mUpdateSensorReadingsTimer.setInterval(mSettings->value("updateInterval").toInt() * 1000);
// Iterator for temperature progress bars
std::vector<ProgressBar*>::iterator temperatureProgressBarsIt =
mTemperatureProgressBars.begin();
mSettings->beginGroup("chips");
for (unsigned int i = 0; i < mDetectedChips.size(); ++i)
{
mSettings->beginGroup(QString::fromStdString(mDetectedChips[i].getName()));
const std::vector<Feature>& features = mDetectedChips[i].getFeatures();
for (unsigned int j = 0; j < features.size(); ++j)
{
if (features[j].getType() == SENSORS_FEATURE_TEMP)
{
mSettings->beginGroup(QString::fromStdString(features[j].getLabel()));
if (mSettings->value("enabled").toBool())
{
(*temperatureProgressBarsIt)->show();
}
else
{
(*temperatureProgressBarsIt)->hide();
}
QPalette pal = (*temperatureProgressBarsIt)->palette();
QColor color(mSettings->value("color").toString());
pal.setColor(QPalette::Active, QPalette::Highlight, color);
pal.setColor(QPalette::Inactive, QPalette::Highlight, color);
(*temperatureProgressBarsIt)->setPalette(pal);
mSettings->endGroup();
// Go to the next temperature progress bar
++temperatureProgressBarsIt;
}
}
mSettings->endGroup();
}
mSettings->endGroup();
if (mSettings->value("warningAboutHighTemperature").toBool())
{
// Update sensors readings to get the list of high temperature progress bars
updateSensorReadings();
mWarningAboutHighTemperatureTimer.start(mWarningAboutHighTemperatureTimerFreq);
}
else if (mWarningAboutHighTemperatureTimer.isActive())
{
mWarningAboutHighTemperatureTimer.stop();
// Update sensors readings to set progress bar values to "normal" height
updateSensorReadings();
}
realign();
update();
}
void RazorSensors::realign()
{
// Default values for RazorPanel::PositionBottom or RazorPanel::PositionTop
Qt::Orientation cur_orient = Qt::Vertical;
Qt::LayoutDirection cur_layout_dir = Qt::LeftToRight;
if (mPlugin->panel()->isHorizontal())
{
mLayout->setDirection(QBoxLayout::LeftToRight);
}
else
{
mLayout->setDirection(QBoxLayout::TopToBottom);
}
switch (mPlugin->panel()->position())
{
case IRazorPanel::PositionLeft:
cur_orient = Qt::Horizontal;
break;
case IRazorPanel::PositionRight:
cur_orient = Qt::Horizontal;
cur_layout_dir = Qt::RightToLeft;
break;
default:
break;
}
for (unsigned int i = 0; i < mTemperatureProgressBars.size(); ++i)
{
mTemperatureProgressBars[i]->setOrientation(cur_orient);
mTemperatureProgressBars[i]->setLayoutDirection(cur_layout_dir);
if (mPlugin->panel()->isHorizontal())
{
mTemperatureProgressBars[i]->setFixedWidth(settings().value("tempBarWidth").toInt());
mTemperatureProgressBars[i]->setFixedHeight(QWIDGETSIZE_MAX);
}
else
{
mTemperatureProgressBars[i]->setFixedHeight(settings().value("tempBarWidth").toInt());
mTemperatureProgressBars[i]->setFixedWidth(QWIDGETSIZE_MAX);
}
}
}
double RazorSensors::celsiusToFahrenheit(double celsius)
{
// Fahrenheit = 32 * (9/5) * Celsius
return 32 + 1.8 * celsius;
}
void RazorSensors::initDefaultSettings()
{
if (!mSettings->contains("updateInterval"))
{
mSettings->setValue("updateInterval", 1);
}
if (!mSettings->contains("tempBarWidth"))
{
mSettings->setValue("tempBarWidth", 8);
}
if (!mSettings->contains("useFahrenheitScale"))
{
mSettings->setValue("useFahrenheitScale", false);
}
mSettings->beginGroup("chips");
// Initialize default sensors settings
for (unsigned int i = 0; i < mDetectedChips.size(); ++i)
{
mSettings->beginGroup(QString::fromStdString(mDetectedChips[i].getName()));
const std::vector<Feature>& features = mDetectedChips[i].getFeatures();
for (unsigned int j = 0; j < features.size(); ++j)
{
if (features[j].getType() == SENSORS_FEATURE_TEMP)
{
mSettings->beginGroup(QString::fromStdString(features[j].getLabel()));
if (!mSettings->contains("enabled"))
{
mSettings->setValue("enabled", true);
}
if (!mSettings->contains("color"))
{
// This is the default from QtDesigner
mSettings->setValue("color", QColor(qRgb(98, 140, 178)).name());
}
mSettings->endGroup();
}
}
mSettings->endGroup();
}
mSettings->endGroup();
if (!mSettings->contains("warningAboutHighTemperature"))
{
mSettings->setValue("warningAboutHighTemperature", true);
}
}
ProgressBar::ProgressBar(QWidget *parent):
QProgressBar(parent)
{
}
QSize ProgressBar::sizeHint() const
{
return QSize(20, 20);
}
<commit_msg>The Sensors plugin: settings().value to mPlugin->settings()->value<commit_after>/* BEGIN_COMMON_COPYRIGHT_HEADER
* (c)LGPL2+
*
* Razor - a lightweight, Qt based, desktop toolset
* http://razor-qt.org
*
* Copyright: 2012 Razor team
* Authors:
* Łukasz Twarduś <ltwardus@gmail.com>
*
* This program or 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 Street, Fifth Floor,
* Boston, MA 02110-1301 USA
*
* END_COMMON_COPYRIGHT_HEADER */
#include "razorsensors.h"
#include "razorsensorsconfiguration.h"
#include "../panel/irazorpanelplugin.h"
#include "../panel/irazorpanel.h"
#include <QtGui/QMessageBox>
#include <QtGui/QPalette>
#include <QtCore/QDebug>
#include <QBoxLayout>
RazorSensors::RazorSensors(IRazorPanelPlugin *plugin, QWidget* parent):
QFrame(parent),
mPlugin(plugin),
mSettings(plugin->settings())
{
mDetectedChips = mSensors.getDetectedChips();
/**
* We have all needed data to initialize default settings, we have to do it here as later
* we are using them.
*/
initDefaultSettings();
// Add GUI elements
ProgressBar* pg = NULL;
mLayout = new QBoxLayout(QBoxLayout::LeftToRight, this);
mLayout->setSpacing(0);
QString chipFeatureLabel;
mSettings->beginGroup("chips");
for (unsigned int i = 0; i < mDetectedChips.size(); ++i)
{
mSettings->beginGroup(QString::fromStdString(mDetectedChips[i].getName()));
const std::vector<Feature>& features = mDetectedChips[i].getFeatures();
for (unsigned int j = 0; j < features.size(); ++j)
{
if (features[j].getType() == SENSORS_FEATURE_TEMP)
{
chipFeatureLabel = QString::fromStdString(features[j].getLabel());
mSettings->beginGroup(chipFeatureLabel);
pg = new ProgressBar(this);
pg->setSizePolicy(QSizePolicy::Preferred, QSizePolicy::Preferred);
// Hide progress bar if it is not enabled
if (!mSettings->value("enabled").toBool())
{
pg->hide();
}
pg->setToolTip(chipFeatureLabel);
pg->setTextVisible(false);
QPalette pal = pg->palette();
QColor color(mSettings->value("color").toString());
pal.setColor(QPalette::Active, QPalette::Highlight, color);
pal.setColor(QPalette::Inactive, QPalette::Highlight, color);
pg->setPalette(pal);
mTemperatureProgressBars.push_back(pg);
mLayout->addWidget(pg);
mSettings->endGroup();
}
}
mSettings->endGroup();
}
mSettings->endGroup();
// Fit plugin to current panel
realign();
// Updated sensors readings to display actual values at start
updateSensorReadings();
// Run timer that will be updating sensor readings
mUpdateSensorReadingsTimer.setParent(this);
connect(&mUpdateSensorReadingsTimer, SIGNAL(timeout()), this, SLOT(updateSensorReadings()));
mUpdateSensorReadingsTimer.start(mSettings->value("updateInterval").toInt() * 1000);
// Run timer that will be showin warning
mWarningAboutHighTemperatureTimer.setParent(this);
connect(&mWarningAboutHighTemperatureTimer, SIGNAL(timeout()), this,
SLOT(warningAboutHighTemperature()));
if (mSettings->value("warningAboutHighTemperature").toBool())
{
mWarningAboutHighTemperatureTimer.start(mWarningAboutHighTemperatureTimerFreq);
}
}
RazorSensors::~RazorSensors()
{
}
void RazorSensors::updateSensorReadings()
{
QString tooltip;
double critTemp = 0;
double maxTemp = 0;
double minTemp = 0;
double curTemp = 0;
bool highTemperature = false;
// Iterator for temperature progress bars
std::vector<ProgressBar*>::iterator temperatureProgressBarsIt =
mTemperatureProgressBars.begin();
for (unsigned int i = 0; i < mDetectedChips.size(); ++i)
{
const std::vector<Feature>& features = mDetectedChips[i].getFeatures();
for (unsigned int j = 0; j < features.size(); ++j)
{
if (features[j].getType() == SENSORS_FEATURE_TEMP)
{
tooltip = QString::fromStdString(features[j].getLabel()) + " (" + QChar(0x00B0);
if (mSettings->value("useFahrenheitScale").toBool())
{
critTemp = celsiusToFahrenheit(
features[j].getValue(SENSORS_SUBFEATURE_TEMP_CRIT));
maxTemp = celsiusToFahrenheit(
features[j].getValue(SENSORS_SUBFEATURE_TEMP_MAX));
minTemp = celsiusToFahrenheit(
features[j].getValue(SENSORS_SUBFEATURE_TEMP_MIN));
curTemp = celsiusToFahrenheit(
features[j].getValue(SENSORS_SUBFEATURE_TEMP_INPUT));
tooltip += "F)";
}
else
{
critTemp = features[j].getValue(SENSORS_SUBFEATURE_TEMP_CRIT);
maxTemp = features[j].getValue(SENSORS_SUBFEATURE_TEMP_MAX);
minTemp = features[j].getValue(SENSORS_SUBFEATURE_TEMP_MIN);
curTemp = features[j].getValue(SENSORS_SUBFEATURE_TEMP_INPUT);
tooltip += "C)";
}
// Check if temperature is too high
if (curTemp >= maxTemp)
{
if (mSettings->value("warningAboutHighTemperature").toBool())
{
// Add current progress bar to the "warning container"
mHighTemperatureProgressBars.insert(*temperatureProgressBarsIt);
}
highTemperature = true;
}
else
{
mHighTemperatureProgressBars.erase(*temperatureProgressBarsIt);
highTemperature = false;
}
// Set maximum temperature
(*temperatureProgressBarsIt)->setMaximum(critTemp);
// Set minimum temperature
(*temperatureProgressBarsIt)->setMinimum(minTemp);
// Set current temperature
(*temperatureProgressBarsIt)->setValue(curTemp);
tooltip += "<br><br>Crit: ";
tooltip += QString::number((*temperatureProgressBarsIt)->maximum());
tooltip += "<br>Max: ";
tooltip += QString::number(int(maxTemp));
tooltip += "<br>Cur: ";
// Mark high temperature in the tooltip
if (highTemperature)
{
tooltip += "<span style=\"font-size:8pt; font-weight:600; color:#FF0000;\">";
tooltip += QString::number((*temperatureProgressBarsIt)->value());
tooltip += " !</span>";
}
else
{
tooltip += QString::number((*temperatureProgressBarsIt)->value());
}
tooltip += "<br>Min: ";
tooltip += QString::number((*temperatureProgressBarsIt)->minimum());
(*temperatureProgressBarsIt)->setToolTip(tooltip);
// Go to the next temperature progress bar
++temperatureProgressBarsIt;
}
}
}
update();
}
void RazorSensors::warningAboutHighTemperature()
{
// Iterator for temperature progress bars
std::set<ProgressBar*>::iterator temperatureProgressBarsIt =
mHighTemperatureProgressBars.begin();
int curValue;
int maxValue;
for (; temperatureProgressBarsIt != mHighTemperatureProgressBars.end();
++temperatureProgressBarsIt)
{
curValue = (*temperatureProgressBarsIt)->value();
maxValue = (*temperatureProgressBarsIt)->maximum();
if (maxValue > curValue)
{
(*temperatureProgressBarsIt)->setValue(maxValue);
}
else
{
(*temperatureProgressBarsIt)->setValue((*temperatureProgressBarsIt)->minimum());
}
}
update();
}
void RazorSensors::settingsChanged()
{
mUpdateSensorReadingsTimer.setInterval(mSettings->value("updateInterval").toInt() * 1000);
// Iterator for temperature progress bars
std::vector<ProgressBar*>::iterator temperatureProgressBarsIt =
mTemperatureProgressBars.begin();
mSettings->beginGroup("chips");
for (unsigned int i = 0; i < mDetectedChips.size(); ++i)
{
mSettings->beginGroup(QString::fromStdString(mDetectedChips[i].getName()));
const std::vector<Feature>& features = mDetectedChips[i].getFeatures();
for (unsigned int j = 0; j < features.size(); ++j)
{
if (features[j].getType() == SENSORS_FEATURE_TEMP)
{
mSettings->beginGroup(QString::fromStdString(features[j].getLabel()));
if (mSettings->value("enabled").toBool())
{
(*temperatureProgressBarsIt)->show();
}
else
{
(*temperatureProgressBarsIt)->hide();
}
QPalette pal = (*temperatureProgressBarsIt)->palette();
QColor color(mSettings->value("color").toString());
pal.setColor(QPalette::Active, QPalette::Highlight, color);
pal.setColor(QPalette::Inactive, QPalette::Highlight, color);
(*temperatureProgressBarsIt)->setPalette(pal);
mSettings->endGroup();
// Go to the next temperature progress bar
++temperatureProgressBarsIt;
}
}
mSettings->endGroup();
}
mSettings->endGroup();
if (mSettings->value("warningAboutHighTemperature").toBool())
{
// Update sensors readings to get the list of high temperature progress bars
updateSensorReadings();
mWarningAboutHighTemperatureTimer.start(mWarningAboutHighTemperatureTimerFreq);
}
else if (mWarningAboutHighTemperatureTimer.isActive())
{
mWarningAboutHighTemperatureTimer.stop();
// Update sensors readings to set progress bar values to "normal" height
updateSensorReadings();
}
realign();
update();
}
void RazorSensors::realign()
{
// Default values for RazorPanel::PositionBottom or RazorPanel::PositionTop
Qt::Orientation cur_orient = Qt::Vertical;
Qt::LayoutDirection cur_layout_dir = Qt::LeftToRight;
if (mPlugin->panel()->isHorizontal())
{
mLayout->setDirection(QBoxLayout::LeftToRight);
}
else
{
mLayout->setDirection(QBoxLayout::TopToBottom);
}
switch (mPlugin->panel()->position())
{
case IRazorPanel::PositionLeft:
cur_orient = Qt::Horizontal;
break;
case IRazorPanel::PositionRight:
cur_orient = Qt::Horizontal;
cur_layout_dir = Qt::RightToLeft;
break;
default:
break;
}
for (unsigned int i = 0; i < mTemperatureProgressBars.size(); ++i)
{
mTemperatureProgressBars[i]->setOrientation(cur_orient);
mTemperatureProgressBars[i]->setLayoutDirection(cur_layout_dir);
if (mPlugin->panel()->isHorizontal())
{
mTemperatureProgressBars[i]->setFixedWidth(mPlugin->settings()->value("tempBarWidth").toInt());
mTemperatureProgressBars[i]->setFixedHeight(QWIDGETSIZE_MAX);
}
else
{
mTemperatureProgressBars[i]->setFixedHeight(mPlugin->settings()->value("tempBarWidth").toInt());
mTemperatureProgressBars[i]->setFixedWidth(QWIDGETSIZE_MAX);
}
}
}
double RazorSensors::celsiusToFahrenheit(double celsius)
{
// Fahrenheit = 32 * (9/5) * Celsius
return 32 + 1.8 * celsius;
}
void RazorSensors::initDefaultSettings()
{
if (!mSettings->contains("updateInterval"))
{
mSettings->setValue("updateInterval", 1);
}
if (!mSettings->contains("tempBarWidth"))
{
mSettings->setValue("tempBarWidth", 8);
}
if (!mSettings->contains("useFahrenheitScale"))
{
mSettings->setValue("useFahrenheitScale", false);
}
mSettings->beginGroup("chips");
// Initialize default sensors settings
for (unsigned int i = 0; i < mDetectedChips.size(); ++i)
{
mSettings->beginGroup(QString::fromStdString(mDetectedChips[i].getName()));
const std::vector<Feature>& features = mDetectedChips[i].getFeatures();
for (unsigned int j = 0; j < features.size(); ++j)
{
if (features[j].getType() == SENSORS_FEATURE_TEMP)
{
mSettings->beginGroup(QString::fromStdString(features[j].getLabel()));
if (!mSettings->contains("enabled"))
{
mSettings->setValue("enabled", true);
}
if (!mSettings->contains("color"))
{
// This is the default from QtDesigner
mSettings->setValue("color", QColor(qRgb(98, 140, 178)).name());
}
mSettings->endGroup();
}
}
mSettings->endGroup();
}
mSettings->endGroup();
if (!mSettings->contains("warningAboutHighTemperature"))
{
mSettings->setValue("warningAboutHighTemperature", true);
}
}
ProgressBar::ProgressBar(QWidget *parent):
QProgressBar(parent)
{
}
QSize ProgressBar::sizeHint() const
{
return QSize(20, 20);
}
<|endoftext|> |
<commit_before>/* bzflag
* Copyright (c) 1993 - 2006 Tim Riker
*
* This package is free software; you can redistribute it and/or
* modify it under the terms of the license found in the file
* named COPYING that should have accompanied this file.
*
* THIS PACKAGE IS PROVIDED ``AS IS'' AND WITHOUT ANY EXPRESS OR
* IMPLIED WARRANTIES, INCLUDING, WITHOUT LIMITATION, THE IMPLIED
* WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE.
*/
// logDetail.cpp : Plugin module for logging server events to stdout
//
#include <iostream>
#include "bzfsAPI.h"
BZ_GET_PLUGIN_VERSION
using namespace std;
class logDetail : public bz_EventHandler
{
public:
logDetail() {};
virtual ~logDetail() {};
virtual void process( bz_EventData *eventData );
private:
void displayPlayerPrivs( int playerID );
void displayCallsign( bzApiString callsign );
void displayCallsign( int playerID );
void displayTeam( bz_eTeamType team );
};
logDetail logDetailHandler;
BZF_PLUGIN_CALL int bz_Load ( const char* /*commandLine*/ )
{
bz_registerEvent(bz_eSlashCommandEvent, &logDetailHandler);
bz_registerEvent(bz_eChatMessageEvent, &logDetailHandler);
bz_registerEvent(bz_eServerMsgEvent, &logDetailHandler);
bz_registerEvent(bz_ePlayerJoinEvent, &logDetailHandler);
bz_registerEvent(bz_ePlayerPartEvent, &logDetailHandler);
bz_registerEvent(bz_ePlayerAuthEvent, &logDetailHandler);
bz_debugMessage(4, "logDetail plugin loaded");
return 0;
}
BZF_PLUGIN_CALL int bz_Unload ( void )
{
bz_removeEvent(bz_eSlashCommandEvent, &logDetailHandler);
bz_removeEvent(bz_eChatMessageEvent, &logDetailHandler);
bz_removeEvent(bz_eServerMsgEvent, &logDetailHandler);
bz_removeEvent(bz_ePlayerJoinEvent, &logDetailHandler);
bz_removeEvent(bz_ePlayerPartEvent, &logDetailHandler);
bz_removeEvent(bz_ePlayerAuthEvent, &logDetailHandler);
bz_debugMessage(4, "logDetail plugin unloaded");
return 0;
}
void logDetail::process( bz_EventData *eventData )
{
bz_ChatEventData *chatData = (bz_ChatEventData *) eventData;
bz_ServerMsgEventData *serverMsgData = (bz_ServerMsgEventData *) eventData;
bz_SlashCommandEventData *cmdData = (bz_SlashCommandEventData *) eventData;
bz_PlayerJoinPartEventData *joinPartData = (bz_PlayerJoinPartEventData *) eventData;
bz_PlayerAuthEventData *authData = (bz_PlayerAuthEventData *) eventData;
if (eventData) {
switch (eventData->eventType) {
case bz_eSlashCommandEvent:
// Slash commands are case insensitive
// Tokenize the stream and check the first word
// /report -> MSG-REPORT
// anything -> MSG-COMMAND
if (strncasecmp( cmdData->message.c_str(), "/REPORT ", 8 ) == 0 ) {
cout << "MSG-REPORT ";
displayCallsign( cmdData->from );
cout << " " << cmdData->message.c_str()+8 << endl;
} else {
cout << "MSG-COMMAND ";
displayCallsign( cmdData->from );
cout << " " << cmdData->message.c_str()+1 << endl;
}
break;
case bz_eChatMessageEvent:
if ((chatData->to == BZ_ALLUSERS) and (chatData->team == eNoTeam)) {
cout << "MSG-BROADCAST ";
displayCallsign( chatData->from );
cout << " " << chatData->message.c_str() << endl;
} else if (chatData->to == BZ_NULLUSER) {
if (chatData->team == eAdministrators) {
cout << "MSG-ADMIN ";
displayCallsign( chatData->from );
cout << " " << chatData->message.c_str() << endl;
} else {
cout << "MSG-TEAM ";
displayCallsign( chatData->from );
displayTeam( chatData->team );
cout << " " << chatData->message.c_str() << endl;
}
} else {
cout << "MSG-DIRECT ";
displayCallsign( chatData->from );
cout << " ";
displayCallsign( chatData->to );
cout << " " << chatData->message.c_str() << endl;
}
break;
case bz_eServerMsgEvent:
if ((serverMsgData->to == BZ_ALLUSERS) and (serverMsgData->team == eNoTeam)) {
cout << "MSG-BROADCAST 6:SERVER";
cout << " " << serverMsgData->message.c_str() << endl;
} else if (serverMsgData->to == BZ_NULLUSER) {
if (serverMsgData->team == eAdministrators) {
cout << "MSG-ADMIN 6:SERVER";
cout << " " << serverMsgData->message.c_str() << endl;
} else {
cout << "MSG-TEAM 6:SERVER";
displayTeam( serverMsgData->team );
cout << " " << chatData->message.c_str() << endl;
}
} else {
cout << "MSG-DIRECT 6:SERVER";
cout << " ";
displayCallsign( serverMsgData->to );
cout << " " << serverMsgData->message.c_str() << endl;
}
break;
case bz_ePlayerJoinEvent:
{
bz_PlayerRecord *player = bz_getPlayerByIndex( joinPartData->playerID );
if (player) {
cout << "PLAYER-JOIN ";
displayCallsign( player->callsign );
cout << " #" << joinPartData->playerID;
displayTeam( joinPartData->team );
displayPlayerPrivs( joinPartData->playerID );
cout << endl;
}
}
break;
case bz_ePlayerPartEvent:
cout << "PLAYER-PART ";
displayCallsign( joinPartData->playerID );
cout << " #" << joinPartData->playerID;
cout << " " << joinPartData->reason.c_str();
cout << endl;
break;
case bz_ePlayerAuthEvent:
cout << "PLAYER-AUTH ";
displayCallsign( authData->playerID );
displayPlayerPrivs( authData->playerID );
cout << endl;
break;
default :
break;
}
}
}
void logDetail::displayPlayerPrivs( int playerID )
{
bz_PlayerRecord *player = bz_getPlayerByIndex( playerID );
if (player) {
cout << " IP:" << player->ipAddress.c_str();
if (player->verified ) cout << " VERIFIED";
if (player->globalUser ) cout << " GLOBALUSER";
if (player->admin ) cout << " ADMIN";
if (player->op ) cout << " OPERATOR";
} else {
cout << " IP:0.0.0.0";
}
}
void logDetail::displayCallsign( bzApiString callsign )
{
cout << strlen( callsign.c_str() ) << ":";
cout << callsign.c_str();
}
void logDetail::displayCallsign( int playerID )
{
bz_PlayerRecord *player = bz_getPlayerByIndex( playerID );
if (player) {
cout << strlen( player->callsign.c_str() ) << ":";
cout << player->callsign.c_str();
} else {
cout << "7:UNKNOWN";
}
}
void logDetail::displayTeam( bz_eTeamType team )
{
// Display the player team
switch ( team ) {
case eRogueTeam:
cout << " ROGUE";
break;
case eRedTeam:
cout << " RED";
break;
case eGreenTeam:
cout << " GREEN";
break;
case eBlueTeam:
cout << " BLUE";
break;
case ePurpleTeam:
cout << " PURPLE";
break;
case eRabbitTeam:
cout << " RABBIT";
break;
case eHunterTeam:
cout << " HUNTER";
break;
case eObservers:
cout << " OBSERVER";
break;
default :
cout << " NOTEAM";
break;
}
}
// Local Variables: ***
// mode:C++ ***
// tab-width: 8 ***
// c-basic-offset: 2 ***
// indent-tabs-mode: t ***
// End: ***
// ex: shiftwidth=2 tabstop=8
<commit_msg>Update for new plugin API Use strcasecmp not strncasecmp<commit_after>/* bzflag
* Copyright (c) 1993 - 2006 Tim Riker
*
* This package is free software; you can redistribute it and/or
* modify it under the terms of the license found in the file
* named COPYING that should have accompanied this file.
*
* THIS PACKAGE IS PROVIDED ``AS IS'' AND WITHOUT ANY EXPRESS OR
* IMPLIED WARRANTIES, INCLUDING, WITHOUT LIMITATION, THE IMPLIED
* WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE.
*/
// logDetail.cpp : Plugin module for logging server events to stdout
//
#include <iostream>
#include "bzfsAPI.h"
BZ_GET_PLUGIN_VERSION
using namespace std;
class logDetail : public bz_EventHandler
{
public:
logDetail() {};
virtual ~logDetail() {};
virtual void process( bz_EventData *eventData );
private:
void displayPlayerPrivs( int playerID );
void displayCallsign( bzApiString callsign );
void displayCallsign( int playerID );
void displayTeam( bz_eTeamType team );
};
logDetail logDetailHandler;
BZF_PLUGIN_CALL int bz_Load ( const char* /*commandLine*/ )
{
bz_registerEvent(bz_eSlashCommandEvent, &logDetailHandler);
bz_registerEvent(bz_eChatMessageEvent, &logDetailHandler);
bz_registerEvent(bz_eServerMsgEvent, &logDetailHandler);
bz_registerEvent(bz_ePlayerJoinEvent, &logDetailHandler);
bz_registerEvent(bz_ePlayerPartEvent, &logDetailHandler);
bz_registerEvent(bz_ePlayerAuthEvent, &logDetailHandler);
bz_debugMessage(4, "logDetail plugin loaded");
return 0;
}
BZF_PLUGIN_CALL int bz_Unload ( void )
{
bz_removeEvent(bz_eSlashCommandEvent, &logDetailHandler);
bz_removeEvent(bz_eChatMessageEvent, &logDetailHandler);
bz_removeEvent(bz_eServerMsgEvent, &logDetailHandler);
bz_removeEvent(bz_ePlayerJoinEvent, &logDetailHandler);
bz_removeEvent(bz_ePlayerPartEvent, &logDetailHandler);
bz_removeEvent(bz_ePlayerAuthEvent, &logDetailHandler);
bz_debugMessage(4, "logDetail plugin unloaded");
return 0;
}
void logDetail::process( bz_EventData *eventData )
{
bz_ChatEventData_V1 *chatData = (bz_ChatEventData_V1 *) eventData;
bz_ServerMsgEventData_V1 *serverMsgData = (bz_ServerMsgEventData_V1 *) eventData;
bz_SlashCommandEventData_V1 *cmdData = (bz_SlashCommandEventData_V1 *) eventData;
bz_PlayerJoinPartEventData_V1 *joinPartData = (bz_PlayerJoinPartEventData_V1 *) eventData;
bz_PlayerAuthEventData_V1 *authData = (bz_PlayerAuthEventData_V1 *) eventData;
if (eventData) {
switch (eventData->eventType) {
case bz_eSlashCommandEvent:
// Slash commands are case insensitive
// Tokenize the stream and check the first word
// /report -> MSG-REPORT
// anything -> MSG-COMMAND
if (strcasecmp( cmdData->message.c_str(), "/REPORT ") == 0 ) {
cout << "MSG-REPORT ";
displayCallsign( cmdData->from );
cout << " " << cmdData->message.c_str()+8 << endl;
} else {
cout << "MSG-COMMAND ";
displayCallsign( cmdData->from );
cout << " " << cmdData->message.c_str()+1 << endl;
}
break;
case bz_eChatMessageEvent:
if ((chatData->to == BZ_ALLUSERS) and (chatData->team == eNoTeam)) {
cout << "MSG-BROADCAST ";
displayCallsign( chatData->from );
cout << " " << chatData->message.c_str() << endl;
} else if (chatData->to == BZ_NULLUSER) {
if (chatData->team == eAdministrators) {
cout << "MSG-ADMIN ";
displayCallsign( chatData->from );
cout << " " << chatData->message.c_str() << endl;
} else {
cout << "MSG-TEAM ";
displayCallsign( chatData->from );
displayTeam( chatData->team );
cout << " " << chatData->message.c_str() << endl;
}
} else {
cout << "MSG-DIRECT ";
displayCallsign( chatData->from );
cout << " ";
displayCallsign( chatData->to );
cout << " " << chatData->message.c_str() << endl;
}
break;
case bz_eServerMsgEvent:
if ((serverMsgData->to == BZ_ALLUSERS) and (serverMsgData->team == eNoTeam)) {
cout << "MSG-BROADCAST 6:SERVER";
cout << " " << serverMsgData->message.c_str() << endl;
} else if (serverMsgData->to == BZ_NULLUSER) {
if (serverMsgData->team == eAdministrators) {
cout << "MSG-ADMIN 6:SERVER";
cout << " " << serverMsgData->message.c_str() << endl;
} else {
cout << "MSG-TEAM 6:SERVER";
displayTeam( serverMsgData->team );
cout << " " << chatData->message.c_str() << endl;
}
} else {
cout << "MSG-DIRECT 6:SERVER";
cout << " ";
displayCallsign( serverMsgData->to );
cout << " " << serverMsgData->message.c_str() << endl;
}
break;
case bz_ePlayerJoinEvent:
{
bz_BasePlayerRecord *player = bz_getPlayerByIndex( joinPartData->playerID );
if (player) {
cout << "PLAYER-JOIN ";
displayCallsign( player->callsign );
cout << " #" << joinPartData->playerID;
displayTeam( joinPartData->team );
displayPlayerPrivs( joinPartData->playerID );
cout << endl;
}
}
break;
case bz_ePlayerPartEvent:
cout << "PLAYER-PART ";
displayCallsign( joinPartData->playerID );
cout << " #" << joinPartData->playerID;
cout << " " << joinPartData->reason.c_str();
cout << endl;
break;
case bz_ePlayerAuthEvent:
cout << "PLAYER-AUTH ";
displayCallsign( authData->playerID );
displayPlayerPrivs( authData->playerID );
cout << endl;
break;
default :
break;
}
}
}
void logDetail::displayPlayerPrivs( int playerID )
{
bz_BasePlayerRecord *player = bz_getPlayerByIndex( playerID );
if (player) {
cout << " IP:" << player->ipAddress.c_str();
if (player->verified ) cout << " VERIFIED";
if (player->globalUser ) cout << " GLOBALUSER";
if (player->admin ) cout << " ADMIN";
if (player->op ) cout << " OPERATOR";
} else {
cout << " IP:0.0.0.0";
}
}
void logDetail::displayCallsign( bzApiString callsign )
{
cout << strlen( callsign.c_str() ) << ":";
cout << callsign.c_str();
}
void logDetail::displayCallsign( int playerID )
{
bz_BasePlayerRecord *player = bz_getPlayerByIndex( playerID );
if (player) {
cout << strlen( player->callsign.c_str() ) << ":";
cout << player->callsign.c_str();
} else {
cout << "7:UNKNOWN";
}
}
void logDetail::displayTeam( bz_eTeamType team )
{
// Display the player team
switch ( team ) {
case eRogueTeam:
cout << " ROGUE";
break;
case eRedTeam:
cout << " RED";
break;
case eGreenTeam:
cout << " GREEN";
break;
case eBlueTeam:
cout << " BLUE";
break;
case ePurpleTeam:
cout << " PURPLE";
break;
case eRabbitTeam:
cout << " RABBIT";
break;
case eHunterTeam:
cout << " HUNTER";
break;
case eObservers:
cout << " OBSERVER";
break;
default :
cout << " NOTEAM";
break;
}
}
// Local Variables: ***
// mode:C++ ***
// tab-width: 8 ***
// c-basic-offset: 2 ***
// indent-tabs-mode: t ***
// End: ***
// ex: shiftwidth=2 tabstop=8
<|endoftext|> |
<commit_before>/*
Copyright (C) 2001 by W.C.A. Wijngaards
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; if not, write to the Free
Software Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
*/
#include "cssysdef.h"
#include "isoview.h"
#include "isorview.h"
#include "ivideo/graph3d.h"
#include "csgeom/polyclip.h"
#include "qint.h"
IMPLEMENT_IBASE (csIsoView)
IMPLEMENTS_INTERFACE (iIsoView)
IMPLEMENT_IBASE_END
csIsoView::csIsoView (iBase *iParent, iIsoEngine *eng, iIsoWorld *world)
{
CONSTRUCT_IBASE (iParent);
engine = eng;
csIsoView::world = world;
rect.Set(0,0,engine->GetG3D()->GetWidth(), engine->GetG3D()->GetHeight());
scroll.Set(0,0);
// set directions
// now assumes that screeny 0=bottom, max=top
x_axis.Set(1.0,-1.0);
y_axis.Set(0.0,1.0);
z_axis.Set(1.0,1.0);
const float startscale = 30.0; // default scale.
x_axis *= startscale;
y_axis *= startscale;
z_axis *= startscale;
invx_axis_y = 1.0 / x_axis.y;
// prealloc a renderview
rview = new csIsoRenderView(this);
}
csIsoView::~csIsoView ()
{
delete rview;
}
void csIsoView::W2S(const csVector3& world, csVector2& screen)
{
screen.x = world.x*x_axis.x + world.z*z_axis.x;
screen.y = world.x*x_axis.y + world.y*y_axis.y + world.z*z_axis.y;
screen += scroll;
}
void csIsoView::W2S(const csVector3& world, csVector3& screen)
{
screen.x = scroll.x+ world.x*x_axis.x + world.z*z_axis.x;
screen.y = scroll.y+ world.x*x_axis.y + world.y*y_axis.y + world.z*z_axis.y;
// the depth is the same, no matter the particular scale on the screen
// or the slightly differnt directions of the axis,
// since the z axis always is 'towards further away' (topright),
// and the x axis always 'closer to the camera' (bottomright).
screen.z = world.z - world.x;
}
void csIsoView::S2W(const csVector2& screen, csVector3& world)
{
// make x_axis.x + alpha*x_axis.y = 0.
float alpha = -x_axis.x * invx_axis_y;
csVector2 off = screen - scroll;
// so that screen.x + alpha*screen.y has only z component
world.z = (off.x + alpha*off.y) / (z_axis.x + alpha*z_axis.y);
world.x = (off.y - z_axis.y * world.z) * invx_axis_y;
world.y = 0.0;
}
void csIsoView::Draw()
{
//printf("IsoView::Draw\n");
rview->SetView(this);
rview->SetG3D(engine->GetG3D());
csBoxClipper* clipper = new csBoxClipper(rect.xmin, rect.ymin,
rect.xmax, rect.ymax);
rview->SetClipper(clipper);
PreCalc();
for(int pass = CSISO_RENDERPASS_PRE; pass <= CSISO_RENDERPASS_POST; pass++)
{
rview->SetRenderPass(pass);
world->Draw(rview);
}
delete clipper;
}
void csIsoView::SetScroll(const csVector3& worldpos, const csVector2& coord)
{
csVector2 screenpos;
W2S(worldpos, screenpos);
// pos now shown at screenpos, but should be at 'coord'.
// shift accordingly
scroll += coord - screenpos;
}
void csIsoView::MoveScroll(const csVector3& delta)
{
csVector2 screen;
screen.x = delta.x*x_axis.x + delta.z*z_axis.x;
screen.y = delta.x*x_axis.y + delta.y*y_axis.y + delta.z*z_axis.y;
scroll -= screen;
}
void csIsoView::PreCalc()
{
csVector3 topleft, topright, botleft, botright;
csVector2 botleft2(rect.xmin, rect.ymin);
csVector2 topright2(rect.xmax, rect.ymax);
csVector2 topleft2(rect.xmin, rect.ymax);
csVector2 botright2(rect.xmax, rect.ymin);
S2W(botleft2, botleft);
S2W(topleft2, topleft);
S2W(botright2, botright);
S2W(topright2, topright);
int startx = QInt(topright.z)+1;
int starty = QInt(topright.x)-1;
int scanw = QInt(topright.z) - QInt(topleft.z) + 2;
int scanh = QInt(botright.x) - QInt(topright.x) + 2;
//printf("scanw, scasnh %d %d\n", scanw, scanh);
rview->SetPrecalcGrid(startx, starty, scanw, scanh);
}
<commit_msg>Made the display scale resolution independent.<commit_after>/*
Copyright (C) 2001 by W.C.A. Wijngaards
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; if not, write to the Free
Software Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
*/
#include "cssysdef.h"
#include "isoview.h"
#include "isorview.h"
#include "ivideo/graph3d.h"
#include "csgeom/polyclip.h"
#include "qint.h"
IMPLEMENT_IBASE (csIsoView)
IMPLEMENTS_INTERFACE (iIsoView)
IMPLEMENT_IBASE_END
csIsoView::csIsoView (iBase *iParent, iIsoEngine *eng, iIsoWorld *world)
{
CONSTRUCT_IBASE (iParent);
engine = eng;
csIsoView::world = world;
rect.Set(0,0,engine->GetG3D()->GetWidth(), engine->GetG3D()->GetHeight());
scroll.Set(0,0);
// set directions
// now assumes that screeny 0=bottom, max=top
x_axis.Set(1.0,-1.0);
y_axis.Set(0.0,1.0);
z_axis.Set(1.0,1.0);
// default scale.
float startscale = float(engine->GetG3D()->GetHeight())/16.0;
x_axis *= startscale;
y_axis *= startscale;
z_axis *= startscale;
invx_axis_y = 1.0 / x_axis.y;
// prealloc a renderview
rview = new csIsoRenderView(this);
}
csIsoView::~csIsoView ()
{
delete rview;
}
void csIsoView::W2S(const csVector3& world, csVector2& screen)
{
screen.x = world.x*x_axis.x + world.z*z_axis.x;
screen.y = world.x*x_axis.y + world.y*y_axis.y + world.z*z_axis.y;
screen += scroll;
}
void csIsoView::W2S(const csVector3& world, csVector3& screen)
{
screen.x = scroll.x+ world.x*x_axis.x + world.z*z_axis.x;
screen.y = scroll.y+ world.x*x_axis.y + world.y*y_axis.y + world.z*z_axis.y;
// the depth is the same, no matter the particular scale on the screen
// or the slightly differnt directions of the axis,
// since the z axis always is 'towards further away' (topright),
// and the x axis always 'closer to the camera' (bottomright).
screen.z = world.z - world.x;
}
void csIsoView::S2W(const csVector2& screen, csVector3& world)
{
// make x_axis.x + alpha*x_axis.y = 0.
float alpha = -x_axis.x * invx_axis_y;
csVector2 off = screen - scroll;
// so that screen.x + alpha*screen.y has only z component
world.z = (off.x + alpha*off.y) / (z_axis.x + alpha*z_axis.y);
world.x = (off.y - z_axis.y * world.z) * invx_axis_y;
world.y = 0.0;
}
void csIsoView::Draw()
{
//printf("IsoView::Draw\n");
rview->SetView(this);
rview->SetG3D(engine->GetG3D());
csBoxClipper* clipper = new csBoxClipper(rect.xmin, rect.ymin,
rect.xmax, rect.ymax);
rview->SetClipper(clipper);
PreCalc();
for(int pass = CSISO_RENDERPASS_PRE; pass <= CSISO_RENDERPASS_POST; pass++)
{
rview->SetRenderPass(pass);
world->Draw(rview);
}
delete clipper;
}
void csIsoView::SetScroll(const csVector3& worldpos, const csVector2& coord)
{
csVector2 screenpos;
W2S(worldpos, screenpos);
// pos now shown at screenpos, but should be at 'coord'.
// shift accordingly
scroll += coord - screenpos;
}
void csIsoView::MoveScroll(const csVector3& delta)
{
csVector2 screen;
screen.x = delta.x*x_axis.x + delta.z*z_axis.x;
screen.y = delta.x*x_axis.y + delta.y*y_axis.y + delta.z*z_axis.y;
scroll -= screen;
}
void csIsoView::PreCalc()
{
csVector3 topleft, topright, botleft, botright;
csVector2 botleft2(rect.xmin, rect.ymin);
csVector2 topright2(rect.xmax, rect.ymax);
csVector2 topleft2(rect.xmin, rect.ymax);
csVector2 botright2(rect.xmax, rect.ymin);
S2W(botleft2, botleft);
S2W(topleft2, topleft);
S2W(botright2, botright);
S2W(topright2, topright);
int startx = QInt(topright.z)+1;
int starty = QInt(topright.x)-1;
int scanw = QInt(topright.z) - QInt(topleft.z) + 2;
int scanh = QInt(botright.x) - QInt(topright.x) + 2;
//printf("scanw, scasnh %d %d\n", scanw, scanh);
rview->SetPrecalcGrid(startx, starty, scanw, scanh);
}
<|endoftext|> |
<commit_before>// Copyright (c) 2006-2008 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 "net/base/x509_certificate.h"
// Work around https://bugzilla.mozilla.org/show_bug.cgi?id=455424
// until NSS 3.12.2 comes out and we update to it.
#define Lock FOO_NSS_Lock
#include <cert.h>
#include <prtime.h>
#include <secder.h>
#include <sechash.h>
#undef Lock
#include "base/logging.h"
#include "base/pickle.h"
#include "base/time.h"
#include "base/nss_init.h"
#include "net/base/net_errors.h"
namespace net {
namespace {
// TODO(port): Implement this more simply, and put it in the right place
base::Time PRTimeToBaseTime(PRTime prtime) {
PRExplodedTime prxtime;
PR_ExplodeTime(prtime, PR_GMTParameters, &prxtime);
base::Time::Exploded exploded;
exploded.year = prxtime.tm_year;
exploded.month = prxtime.tm_month + 1;
exploded.day_of_week = prxtime.tm_wday;
exploded.day_of_month = prxtime.tm_mday;
exploded.hour = prxtime.tm_hour;
exploded.minute = prxtime.tm_min;
exploded.second = prxtime.tm_sec;
exploded.millisecond = prxtime.tm_usec / 1000;
return base::Time::FromUTCExploded(exploded);
}
void ParsePrincipal(SECItem* der_name,
X509Certificate::Principal* principal) {
CERTName name;
PRArenaPool* arena = NULL;
arena = PORT_NewArena(DER_DEFAULT_CHUNKSIZE);
DCHECK(arena != NULL);
if (arena == NULL)
return;
// TODO(dkegel): is CERT_NameTemplate what we always want here?
SECStatus rv;
rv = SEC_QuickDERDecodeItem(arena, &name, CERT_NameTemplate, der_name);
DCHECK(rv == SECSuccess);
if ( rv != SECSuccess ) {
PORT_FreeArena(arena, PR_FALSE);
return;
}
std::vector<std::string> common_names, locality_names, state_names,
country_names;
// TODO(jcampan): add business_category and serial_number.
static const SECOidTag kOIDs[] = {
SEC_OID_AVA_COMMON_NAME,
SEC_OID_AVA_LOCALITY,
SEC_OID_AVA_STATE_OR_PROVINCE,
SEC_OID_AVA_COUNTRY_NAME,
SEC_OID_AVA_STREET_ADDRESS,
SEC_OID_AVA_ORGANIZATION_NAME,
SEC_OID_AVA_ORGANIZATIONAL_UNIT_NAME,
SEC_OID_AVA_DC };
std::vector<std::string>* values[] = {
&common_names, &locality_names,
&state_names, &country_names,
&principal->street_addresses,
&principal->organization_names,
&principal->organization_unit_names,
&principal->domain_components };
DCHECK(arraysize(kOIDs) == arraysize(values));
CERTRDN** rdns = name.rdns;
for (size_t rdn = 0; rdns[rdn]; ++rdn) {
CERTAVA** avas = rdns[rdn]->avas;
for (size_t pair = 0; avas[pair] != 0; ++pair) {
SECOidTag tag = CERT_GetAVATag(avas[pair]);
for (size_t oid = 0; oid < arraysize(kOIDs); ++oid) {
if (kOIDs[oid] == tag) {
SECItem* decode_item = CERT_DecodeAVAValue(&avas[pair]->value);
if (!decode_item)
break;
std::string value(reinterpret_cast<char*>(decode_item->data),
decode_item->len);
values[oid]->push_back(value);
SECITEM_FreeItem(decode_item, PR_TRUE);
break;
}
}
}
}
// We don't expect to have more than one CN, L, S, and C.
std::vector<std::string>* single_value_lists[4] = {
&common_names, &locality_names, &state_names, &country_names };
std::string* single_values[4] = {
&principal->common_name, &principal->locality_name,
&principal->state_or_province_name, &principal->country_name };
for (size_t i = 0; i < arraysize(single_value_lists); ++i) {
DCHECK(single_value_lists[i]->size() <= 1);
if (single_value_lists[i]->size() > 0)
*(single_values[i]) = (*(single_value_lists[i]))[0];
}
PORT_FreeArena(arena, PR_FALSE);
}
void ParseDate(SECItem* der_date, base::Time* result) {
PRTime prtime;
SECStatus rv = DER_DecodeTimeChoice(&prtime, der_date);
DCHECK(rv == SECSuccess);
*result = PRTimeToBaseTime(prtime);
}
void GetCertSubjectAltNamesOfType(X509Certificate::OSCertHandle cert_handle,
CERTGeneralNameType name_type,
std::vector<std::string>* result) {
SECItem alt_name;
SECStatus rv = CERT_FindCertExtension(cert_handle,
SEC_OID_X509_SUBJECT_ALT_NAME, &alt_name);
if (rv != SECSuccess)
return;
PRArenaPool* arena = PORT_NewArena(DER_DEFAULT_CHUNKSIZE);
DCHECK(arena != NULL);
CERTGeneralName* alt_name_list;
alt_name_list = CERT_DecodeAltNameExtension(arena, &alt_name);
CERTGeneralName* name = alt_name_list;
while (name) {
// For future extension: We're assuming that these values are of types
// RFC822Name, DNSName or URI. See the mac code for notes.
DCHECK(name->type == certRFC822Name ||
name->type == certDNSName ||
name->type == certURI);
if (name->type == name_type) {
unsigned char* p = name->name.other.data;
int len = name->name.other.len;
std::string value = std::string(reinterpret_cast<char*>(p), len);
result->push_back(value);
}
name = CERT_GetNextGeneralName(name);
if (name == alt_name_list)
break;
}
PORT_FreeArena(arena, PR_FALSE);
}
} // namespace
void X509Certificate::Initialize() {
ParsePrincipal(&cert_handle_->derSubject, &subject_);
ParsePrincipal(&cert_handle_->derIssuer, &issuer_);
ParseDate(&cert_handle_->validity.notBefore, &valid_start_);
ParseDate(&cert_handle_->validity.notAfter, &valid_expiry_);
fingerprint_ = CalculateFingerprint(cert_handle_);
// Store the certificate in the cache in case we need it later.
X509Certificate::Cache::GetInstance()->Insert(this);
}
// static
X509Certificate* X509Certificate::CreateFromPickle(const Pickle& pickle,
void** pickle_iter) {
const char* data;
int length;
if (!pickle.ReadData(pickle_iter, &data, &length))
return NULL;
return CreateFromBytes(data, length);
}
void X509Certificate::Persist(Pickle* pickle) {
pickle->WriteData(reinterpret_cast<const char*>(cert_handle_->derCert.data),
cert_handle_->derCert.len);
}
void X509Certificate::GetDNSNames(std::vector<std::string>* dns_names) const {
dns_names->clear();
// Compare with CERT_VerifyCertName().
GetCertSubjectAltNamesOfType(cert_handle_, certDNSName, dns_names);
// TODO(port): suppress nss's support of the obsolete extension
// SEC_OID_NS_CERT_EXT_SSL_SERVER_NAME
// by providing our own authCertificate callback.
if (dns_names->empty())
dns_names->push_back(subject_.common_name);
}
bool X509Certificate::HasExpired() const {
NOTIMPLEMENTED();
return false;
}
int X509Certificate::Verify(const std::string& hostname,
bool rev_checking_enabled,
CertVerifyResult* verify_result) const {
NOTIMPLEMENTED();
return ERR_NOT_IMPLEMENTED;
}
// static
X509Certificate::OSCertHandle X509Certificate::CreateOSCertHandleFromBytes(
const char* data, int length) {
base::EnsureNSSInit();
SECItem der_cert;
der_cert.data = reinterpret_cast<unsigned char*>(const_cast<char*>(data));
der_cert.len = length;
return CERT_NewTempCertificate(CERT_GetDefaultCertDB(), &der_cert,
NULL, PR_FALSE, PR_TRUE);
}
// static
void X509Certificate::FreeOSCertHandle(OSCertHandle cert_handle) {
CERT_DestroyCertificate(cert_handle);
}
// static
X509Certificate::Fingerprint X509Certificate::CalculateFingerprint(
OSCertHandle cert) {
Fingerprint sha1;
memset(sha1.data, 0, sizeof(sha1.data));
DCHECK(NULL != cert->derCert.data);
DCHECK(0 != cert->derCert.len);
SECStatus rv = HASH_HashBuf(HASH_AlgSHA1, sha1.data,
cert->derCert.data, cert->derCert.len);
DCHECK(rv == SECSuccess);
return sha1;
}
} // namespace net
<commit_msg>Fix leak in GetCertSubjectAltNamesOfType(). Found by valgrind.<commit_after>// Copyright (c) 2006-2008 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 "net/base/x509_certificate.h"
// Work around https://bugzilla.mozilla.org/show_bug.cgi?id=455424
// until NSS 3.12.2 comes out and we update to it.
#define Lock FOO_NSS_Lock
#include <cert.h>
#include <prtime.h>
#include <secder.h>
#include <sechash.h>
#undef Lock
#include "base/logging.h"
#include "base/pickle.h"
#include "base/time.h"
#include "base/nss_init.h"
#include "net/base/net_errors.h"
namespace net {
namespace {
// TODO(port): Implement this more simply, and put it in the right place
base::Time PRTimeToBaseTime(PRTime prtime) {
PRExplodedTime prxtime;
PR_ExplodeTime(prtime, PR_GMTParameters, &prxtime);
base::Time::Exploded exploded;
exploded.year = prxtime.tm_year;
exploded.month = prxtime.tm_month + 1;
exploded.day_of_week = prxtime.tm_wday;
exploded.day_of_month = prxtime.tm_mday;
exploded.hour = prxtime.tm_hour;
exploded.minute = prxtime.tm_min;
exploded.second = prxtime.tm_sec;
exploded.millisecond = prxtime.tm_usec / 1000;
return base::Time::FromUTCExploded(exploded);
}
void ParsePrincipal(SECItem* der_name,
X509Certificate::Principal* principal) {
CERTName name;
PRArenaPool* arena = NULL;
arena = PORT_NewArena(DER_DEFAULT_CHUNKSIZE);
DCHECK(arena != NULL);
if (arena == NULL)
return;
// TODO(dkegel): is CERT_NameTemplate what we always want here?
SECStatus rv;
rv = SEC_QuickDERDecodeItem(arena, &name, CERT_NameTemplate, der_name);
DCHECK(rv == SECSuccess);
if ( rv != SECSuccess ) {
PORT_FreeArena(arena, PR_FALSE);
return;
}
std::vector<std::string> common_names, locality_names, state_names,
country_names;
// TODO(jcampan): add business_category and serial_number.
static const SECOidTag kOIDs[] = {
SEC_OID_AVA_COMMON_NAME,
SEC_OID_AVA_LOCALITY,
SEC_OID_AVA_STATE_OR_PROVINCE,
SEC_OID_AVA_COUNTRY_NAME,
SEC_OID_AVA_STREET_ADDRESS,
SEC_OID_AVA_ORGANIZATION_NAME,
SEC_OID_AVA_ORGANIZATIONAL_UNIT_NAME,
SEC_OID_AVA_DC };
std::vector<std::string>* values[] = {
&common_names, &locality_names,
&state_names, &country_names,
&principal->street_addresses,
&principal->organization_names,
&principal->organization_unit_names,
&principal->domain_components };
DCHECK(arraysize(kOIDs) == arraysize(values));
CERTRDN** rdns = name.rdns;
for (size_t rdn = 0; rdns[rdn]; ++rdn) {
CERTAVA** avas = rdns[rdn]->avas;
for (size_t pair = 0; avas[pair] != 0; ++pair) {
SECOidTag tag = CERT_GetAVATag(avas[pair]);
for (size_t oid = 0; oid < arraysize(kOIDs); ++oid) {
if (kOIDs[oid] == tag) {
SECItem* decode_item = CERT_DecodeAVAValue(&avas[pair]->value);
if (!decode_item)
break;
std::string value(reinterpret_cast<char*>(decode_item->data),
decode_item->len);
values[oid]->push_back(value);
SECITEM_FreeItem(decode_item, PR_TRUE);
break;
}
}
}
}
// We don't expect to have more than one CN, L, S, and C.
std::vector<std::string>* single_value_lists[4] = {
&common_names, &locality_names, &state_names, &country_names };
std::string* single_values[4] = {
&principal->common_name, &principal->locality_name,
&principal->state_or_province_name, &principal->country_name };
for (size_t i = 0; i < arraysize(single_value_lists); ++i) {
DCHECK(single_value_lists[i]->size() <= 1);
if (single_value_lists[i]->size() > 0)
*(single_values[i]) = (*(single_value_lists[i]))[0];
}
PORT_FreeArena(arena, PR_FALSE);
}
void ParseDate(SECItem* der_date, base::Time* result) {
PRTime prtime;
SECStatus rv = DER_DecodeTimeChoice(&prtime, der_date);
DCHECK(rv == SECSuccess);
*result = PRTimeToBaseTime(prtime);
}
void GetCertSubjectAltNamesOfType(X509Certificate::OSCertHandle cert_handle,
CERTGeneralNameType name_type,
std::vector<std::string>* result) {
SECItem alt_name;
SECStatus rv = CERT_FindCertExtension(cert_handle,
SEC_OID_X509_SUBJECT_ALT_NAME, &alt_name);
if (rv != SECSuccess)
return;
PRArenaPool* arena = PORT_NewArena(DER_DEFAULT_CHUNKSIZE);
DCHECK(arena != NULL);
CERTGeneralName* alt_name_list;
alt_name_list = CERT_DecodeAltNameExtension(arena, &alt_name);
CERTGeneralName* name = alt_name_list;
while (name) {
// For future extension: We're assuming that these values are of types
// RFC822Name, DNSName or URI. See the mac code for notes.
DCHECK(name->type == certRFC822Name ||
name->type == certDNSName ||
name->type == certURI);
if (name->type == name_type) {
unsigned char* p = name->name.other.data;
int len = name->name.other.len;
std::string value = std::string(reinterpret_cast<char*>(p), len);
result->push_back(value);
}
name = CERT_GetNextGeneralName(name);
if (name == alt_name_list)
break;
}
PORT_FreeArena(arena, PR_FALSE);
PORT_Free(alt_name.data);
}
} // namespace
void X509Certificate::Initialize() {
ParsePrincipal(&cert_handle_->derSubject, &subject_);
ParsePrincipal(&cert_handle_->derIssuer, &issuer_);
ParseDate(&cert_handle_->validity.notBefore, &valid_start_);
ParseDate(&cert_handle_->validity.notAfter, &valid_expiry_);
fingerprint_ = CalculateFingerprint(cert_handle_);
// Store the certificate in the cache in case we need it later.
X509Certificate::Cache::GetInstance()->Insert(this);
}
// static
X509Certificate* X509Certificate::CreateFromPickle(const Pickle& pickle,
void** pickle_iter) {
const char* data;
int length;
if (!pickle.ReadData(pickle_iter, &data, &length))
return NULL;
return CreateFromBytes(data, length);
}
void X509Certificate::Persist(Pickle* pickle) {
pickle->WriteData(reinterpret_cast<const char*>(cert_handle_->derCert.data),
cert_handle_->derCert.len);
}
void X509Certificate::GetDNSNames(std::vector<std::string>* dns_names) const {
dns_names->clear();
// Compare with CERT_VerifyCertName().
GetCertSubjectAltNamesOfType(cert_handle_, certDNSName, dns_names);
// TODO(port): suppress nss's support of the obsolete extension
// SEC_OID_NS_CERT_EXT_SSL_SERVER_NAME
// by providing our own authCertificate callback.
if (dns_names->empty())
dns_names->push_back(subject_.common_name);
}
bool X509Certificate::HasExpired() const {
NOTIMPLEMENTED();
return false;
}
int X509Certificate::Verify(const std::string& hostname,
bool rev_checking_enabled,
CertVerifyResult* verify_result) const {
NOTIMPLEMENTED();
return ERR_NOT_IMPLEMENTED;
}
// static
X509Certificate::OSCertHandle X509Certificate::CreateOSCertHandleFromBytes(
const char* data, int length) {
base::EnsureNSSInit();
SECItem der_cert;
der_cert.data = reinterpret_cast<unsigned char*>(const_cast<char*>(data));
der_cert.len = length;
return CERT_NewTempCertificate(CERT_GetDefaultCertDB(), &der_cert,
NULL, PR_FALSE, PR_TRUE);
}
// static
void X509Certificate::FreeOSCertHandle(OSCertHandle cert_handle) {
CERT_DestroyCertificate(cert_handle);
}
// static
X509Certificate::Fingerprint X509Certificate::CalculateFingerprint(
OSCertHandle cert) {
Fingerprint sha1;
memset(sha1.data, 0, sizeof(sha1.data));
DCHECK(NULL != cert->derCert.data);
DCHECK(0 != cert->derCert.len);
SECStatus rv = HASH_HashBuf(HASH_AlgSHA1, sha1.data,
cert->derCert.data, cert->derCert.len);
DCHECK(rv == SECSuccess);
return sha1;
}
} // namespace net
<|endoftext|> |
<commit_before>/*
Copyright (C) 2002 by Anders Stenberg
Written by Anders Stenberg
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; if not, write to the Free
Software Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
*/
#include <cssysdef.h>
#include <cstypes.h>
#include <csutil/csvector.h>
#include <csutil/scf.h>
#include <csutil/hashmap.h>
#include <csutil/strset.h>
#include <csutil/util.h>
#include "ivideo/effects/efdef.h"
#include "efdef.h"
#include "ivideo/effects/eftech.h"
#include "eftech.h"
iEffectTechnique* csEffectDefinition::CreateTechnique()
{
csEffectTechnique* techniqueobj = new csEffectTechnique();
iEffectTechnique* technique = SCF_QUERY_INTERFACE(
techniqueobj, iEffectTechnique );
techniques.Push( technique );
return technique;
}
int csEffectDefinition::GetTechniqueCount()
{
return techniques.Length();
}
iEffectTechnique* csEffectDefinition::GetTechnique( int technique )
{
return (iEffectTechnique*)(techniques.Get( technique ));
}
void csEffectDefinition::SetName( const char* name )
{
techniquename = csStrNew( name );
}
const char* csEffectDefinition::GetName()
{
return techniquename;
}
float csEffectDefinition::GetVariableFloat(int variableID)
{
if ( (variableID < 0 ) || (variableID > variables.Length() ) )
return 0.0f;
if ( ((efvariable*)variables[variableID])->type == CS_EFVARIABLETYPE_FLOAT )
return ((efvariable*)variables[variableID])->float_value;
else
return 0.0f;
}
csEffectVector4 csEffectDefinition::GetVariableVector4(int variableID)
{
if ( (variableID < 0 ) || (variableID > variables.Length() ) )
return csEffectVector4();
if ( ((efvariable*)variables[variableID])->type == CS_EFVARIABLETYPE_VECTOR4 )
return ((efvariable*)variables[variableID])->vector_value;
else
return csEffectVector4();
}
void csEffectDefinition::SetVariableFloat(int variableID, float value)
{
if ( (variableID < 0 ) || (variableID > variables.Length() ) )
return;
if ( ((efvariable*)variables[variableID])->type == CS_EFVARIABLETYPE_FLOAT )
((efvariable*)variables[variableID])->float_value = value;
else if ( ((efvariable*)variables[variableID])->type == CS_EFVARIABLETYPE_UNDEFINED )
{
((efvariable*)variables[variableID])->float_value = value;
((efvariable*)variables[variableID])->type = CS_EFVARIABLETYPE_FLOAT;
}
}
void csEffectDefinition::SetVariableVector4(int variableID, csEffectVector4 value)
{
if ( (variableID < 0 ) || (variableID > variables.Length() ) )
return;
if ( ((efvariable*)variables[variableID])->type == CS_EFVARIABLETYPE_VECTOR4 )
((efvariable*)variables[variableID])->vector_value = value;
else if ( ((efvariable*)variables[variableID])->type == CS_EFVARIABLETYPE_UNDEFINED )
{
((efvariable*)variables[variableID])->vector_value = value;
((efvariable*)variables[variableID])->type = CS_EFVARIABLETYPE_VECTOR4;
}
}
int csEffectDefinition::GetTopmostVariableID(int id)
{
if ((id < 0) || (id > variables.Length() ) )
return -1;
int curid = id;
int parent = ((efvariable*)variables[curid])->point_to;
while (parent >= 0)
{
curid = parent;
int parent = ((efvariable*)variables[curid])->point_to;
}
return curid;
}
int csEffectDefinition::GetVariableID(csStringID string, bool create )
{
for (int i = 0; i<variables.Length();i++)
{
if ( ((efvariable*)variables[i])->id == string )
{
if( ((efvariable*)variables[i])->point_to >= 0 )
return GetTopmostVariableID( i );
else
return i;
}
}
if (create)
{
variables.Push(new efvariable(string) );
return variables.Length()-1;
}
else
return -1;
}
csBasicVector csEffectDefinition::GetAllVariableNames()
{
return variables;
}
char csEffectDefinition::GetVariableType(int variableID)
{
if ( (variableID < 0 ) || (variableID > variables.Length() ) )
return CS_EFVARIABLETYPE_UNDEFINED;
return ((efvariable*)variables[variableID])->type;
}<commit_msg>Added newline to end of file.<commit_after>/*
Copyright (C) 2002 by Anders Stenberg
Written by Anders Stenberg
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; if not, write to the Free
Software Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
*/
#include <cssysdef.h>
#include <cstypes.h>
#include <csutil/csvector.h>
#include <csutil/scf.h>
#include <csutil/hashmap.h>
#include <csutil/strset.h>
#include <csutil/util.h>
#include "ivideo/effects/efdef.h"
#include "efdef.h"
#include "ivideo/effects/eftech.h"
#include "eftech.h"
iEffectTechnique* csEffectDefinition::CreateTechnique()
{
csEffectTechnique* techniqueobj = new csEffectTechnique();
iEffectTechnique* technique = SCF_QUERY_INTERFACE(
techniqueobj, iEffectTechnique );
techniques.Push( technique );
return technique;
}
int csEffectDefinition::GetTechniqueCount()
{
return techniques.Length();
}
iEffectTechnique* csEffectDefinition::GetTechnique( int technique )
{
return (iEffectTechnique*)(techniques.Get( technique ));
}
void csEffectDefinition::SetName( const char* name )
{
techniquename = csStrNew( name );
}
const char* csEffectDefinition::GetName()
{
return techniquename;
}
float csEffectDefinition::GetVariableFloat(int variableID)
{
if ( (variableID < 0 ) || (variableID > variables.Length() ) )
return 0.0f;
if ( ((efvariable*)variables[variableID])->type == CS_EFVARIABLETYPE_FLOAT )
return ((efvariable*)variables[variableID])->float_value;
else
return 0.0f;
}
csEffectVector4 csEffectDefinition::GetVariableVector4(int variableID)
{
if ( (variableID < 0 ) || (variableID > variables.Length() ) )
return csEffectVector4();
if ( ((efvariable*)variables[variableID])->type == CS_EFVARIABLETYPE_VECTOR4 )
return ((efvariable*)variables[variableID])->vector_value;
else
return csEffectVector4();
}
void csEffectDefinition::SetVariableFloat(int variableID, float value)
{
if ( (variableID < 0 ) || (variableID > variables.Length() ) )
return;
if ( ((efvariable*)variables[variableID])->type == CS_EFVARIABLETYPE_FLOAT )
((efvariable*)variables[variableID])->float_value = value;
else if ( ((efvariable*)variables[variableID])->type == CS_EFVARIABLETYPE_UNDEFINED )
{
((efvariable*)variables[variableID])->float_value = value;
((efvariable*)variables[variableID])->type = CS_EFVARIABLETYPE_FLOAT;
}
}
void csEffectDefinition::SetVariableVector4(int variableID, csEffectVector4 value)
{
if ( (variableID < 0 ) || (variableID > variables.Length() ) )
return;
if ( ((efvariable*)variables[variableID])->type == CS_EFVARIABLETYPE_VECTOR4 )
((efvariable*)variables[variableID])->vector_value = value;
else if ( ((efvariable*)variables[variableID])->type == CS_EFVARIABLETYPE_UNDEFINED )
{
((efvariable*)variables[variableID])->vector_value = value;
((efvariable*)variables[variableID])->type = CS_EFVARIABLETYPE_VECTOR4;
}
}
int csEffectDefinition::GetTopmostVariableID(int id)
{
if ((id < 0) || (id > variables.Length() ) )
return -1;
int curid = id;
int parent = ((efvariable*)variables[curid])->point_to;
while (parent >= 0)
{
curid = parent;
int parent = ((efvariable*)variables[curid])->point_to;
}
return curid;
}
int csEffectDefinition::GetVariableID(csStringID string, bool create )
{
for (int i = 0; i<variables.Length();i++)
{
if ( ((efvariable*)variables[i])->id == string )
{
if( ((efvariable*)variables[i])->point_to >= 0 )
return GetTopmostVariableID( i );
else
return i;
}
}
if (create)
{
variables.Push(new efvariable(string) );
return variables.Length()-1;
}
else
return -1;
}
csBasicVector csEffectDefinition::GetAllVariableNames()
{
return variables;
}
char csEffectDefinition::GetVariableType(int variableID)
{
if ( (variableID < 0 ) || (variableID > variables.Length() ) )
return CS_EFVARIABLETYPE_UNDEFINED;
return ((efvariable*)variables[variableID])->type;
}
<|endoftext|> |
<commit_before>// 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/at_exit.h"
#include "base/bind.h"
#include "base/command_line.h"
#include "base/i18n/icu_util.h"
#include "base/memory/scoped_ptr.h"
#include "base/message_loop.h"
#include "base/string_split.h"
#include "base/time.h"
#include "third_party/khronos/GLES2/gl2.h"
#include "third_party/skia/include/core/SkXfermode.h"
#include "ui/aura/env.h"
#include "ui/aura/root_window.h"
#include "ui/aura/single_display_manager.h"
#include "ui/aura/shared/root_window_capture_client.h"
#include "ui/aura/window.h"
#include "ui/base/hit_test.h"
#include "ui/base/resource/resource_bundle.h"
#include "ui/base/ui_base_paths.h"
#include "ui/compositor/compositor.h"
#include "ui/compositor/compositor_observer.h"
#include "ui/compositor/debug_utils.h"
#include "ui/compositor/layer.h"
#include "ui/compositor/test/compositor_test_support.h"
#include "ui/gfx/canvas.h"
#include "ui/gfx/rect.h"
#include "ui/gfx/skia_util.h"
#ifndef GL_GLEXT_PROTOTYPES
#define GL_GLEXT_PROTOTYPES 1
#endif
#include "third_party/khronos/GLES2/gl2ext.h"
#include "third_party/WebKit/Source/WebKit/chromium/public/platform/WebGraphicsContext3D.h"
#if defined(USE_X11)
#include "base/message_pump_aurax11.h"
#endif
using base::TimeTicks;
using ui::Compositor;
using ui::Layer;
using ui::LayerDelegate;
using WebKit::WebGraphicsContext3D;
namespace {
class ColoredLayer : public Layer, public LayerDelegate {
public:
explicit ColoredLayer(SkColor color)
: Layer(ui::LAYER_TEXTURED),
color_(color),
draw_(true) {
set_delegate(this);
}
virtual ~ColoredLayer() {}
// Overridden from LayerDelegate:
virtual void OnPaintLayer(gfx::Canvas* canvas) OVERRIDE {
if (draw_) {
canvas->DrawColor(color_);
}
}
virtual void OnDeviceScaleFactorChanged(float device_scale_factor) OVERRIDE {
}
virtual base::Closure PrepareForLayerBoundsChange() OVERRIDE {
return base::Closure();
}
void set_color(SkColor color) { color_ = color; }
void set_draw(bool draw) { draw_ = draw; }
private:
SkColor color_;
bool draw_;
DISALLOW_COPY_AND_ASSIGN(ColoredLayer);
};
const int kFrames = 100;
// Benchmark base class, hooks up drawing callback and displaying FPS.
class BenchCompositorObserver : public ui::CompositorObserver {
public:
explicit BenchCompositorObserver(int max_frames)
: start_time_(),
frames_(0),
max_frames_(max_frames) {
}
virtual void OnCompositingDidCommit(ui::Compositor* compositor) OVERRIDE {}
virtual void OnCompositingWillStart(Compositor* compositor) OVERRIDE {}
virtual void OnCompositingStarted(Compositor* compositor) OVERRIDE {}
virtual void OnCompositingEnded(Compositor* compositor) OVERRIDE {
if (start_time_.is_null()) {
start_time_ = TimeTicks::Now();
} else {
++frames_;
if (frames_ % kFrames == 0) {
TimeTicks now = TimeTicks::Now();
double ms = (now - start_time_).InMillisecondsF() / kFrames;
LOG(INFO) << "FPS: " << 1000.f / ms << " (" << ms << " ms)";
start_time_ = now;
}
}
if (max_frames_ && frames_ == max_frames_) {
MessageLoop::current()->Quit();
} else {
Draw();
}
}
virtual void OnCompositingAborted(Compositor* compositor) OVERRIDE {}
virtual void Draw() {}
int frames() const { return frames_; }
private:
TimeTicks start_time_;
int frames_;
int max_frames_;
DISALLOW_COPY_AND_ASSIGN(BenchCompositorObserver);
};
class WebGLTexture : public ui::Texture {
public:
WebGLTexture(WebGraphicsContext3D* context, const gfx::Size& size)
: ui::Texture(false, size),
context_(context) {
set_texture_id(context_->createTexture());
context_->bindTexture(GL_TEXTURE_2D, texture_id());
context_->texParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR);
context_->texParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR);
context_->texParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE);
context_->texParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_EDGE);
context_->texImage2D(GL_TEXTURE_2D, 0, GL_RGBA,
size.width(), size.height(), 0,
GL_RGBA, GL_UNSIGNED_BYTE, NULL);
}
virtual WebGraphicsContext3D* HostContext3D() OVERRIDE {
return context_;
}
private:
virtual ~WebGLTexture() {
context_->deleteTexture(texture_id());
}
WebGraphicsContext3D* context_;
DISALLOW_COPY_AND_ASSIGN(WebGLTexture);
};
// A benchmark that adds a texture layer that is updated every frame.
class WebGLBench : public BenchCompositorObserver {
public:
WebGLBench(Layer* parent, Compositor* compositor, int max_frames)
: BenchCompositorObserver(max_frames),
parent_(parent),
webgl_(ui::LAYER_TEXTURED),
compositor_(compositor),
context_(),
texture_(),
fbo_(0),
do_draw_(true) {
CommandLine* command_line = CommandLine::ForCurrentProcess();
do_draw_ = !command_line->HasSwitch("disable-draw");
std::string webgl_size = command_line->GetSwitchValueASCII("webgl-size");
int width = 0;
int height = 0;
if (!webgl_size.empty()) {
std::vector<std::string> split_size;
base::SplitString(webgl_size, 'x', &split_size);
if (split_size.size() == 2) {
width = atoi(split_size[0].c_str());
height = atoi(split_size[1].c_str());
}
}
if (!width || !height) {
width = 800;
height = 600;
}
gfx::Rect bounds(width, height);
webgl_.SetBounds(bounds);
parent_->Add(&webgl_);
context_.reset(ui::ContextFactory::GetInstance()->CreateOffscreenContext());
context_->makeContextCurrent();
texture_ = new WebGLTexture(context_.get(), bounds.size());
fbo_ = context_->createFramebuffer();
compositor->AddObserver(this);
webgl_.SetExternalTexture(texture_);
context_->bindFramebuffer(GL_FRAMEBUFFER, fbo_);
context_->framebufferTexture2D(
GL_FRAMEBUFFER, GL_COLOR_ATTACHMENT0,
GL_TEXTURE_2D, texture_->texture_id(), 0);
context_->clearColor(0.f, 1.f, 0.f, 1.f);
context_->clear(GL_COLOR_BUFFER_BIT);
context_->flush();
}
virtual ~WebGLBench() {
context_->makeContextCurrent();
context_->deleteFramebuffer(fbo_);
webgl_.SetExternalTexture(NULL);
texture_ = NULL;
compositor_->RemoveObserver(this);
}
virtual void Draw() OVERRIDE {
if (do_draw_) {
context_->makeContextCurrent();
context_->clearColor((frames() % kFrames)*1.0/kFrames, 1.f, 0.f, 1.f);
context_->clear(GL_COLOR_BUFFER_BIT);
context_->flush();
}
webgl_.SetExternalTexture(texture_);
webgl_.SchedulePaint(gfx::Rect(webgl_.bounds().size()));
compositor_->ScheduleDraw();
}
private:
Layer* parent_;
Layer webgl_;
Compositor* compositor_;
scoped_ptr<WebGraphicsContext3D> context_;
scoped_refptr<WebGLTexture> texture_;
// The FBO that is used to render to the texture.
unsigned int fbo_;
// Whether or not to draw to the texture every frame.
bool do_draw_;
DISALLOW_COPY_AND_ASSIGN(WebGLBench);
};
// A benchmark that paints (in software) all tiles every frame.
class SoftwareScrollBench : public BenchCompositorObserver {
public:
SoftwareScrollBench(ColoredLayer* layer,
Compositor* compositor,
int max_frames)
: BenchCompositorObserver(max_frames),
layer_(layer),
compositor_(compositor) {
compositor->AddObserver(this);
layer_->set_draw(
!CommandLine::ForCurrentProcess()->HasSwitch("disable-draw"));
}
virtual ~SoftwareScrollBench() {
compositor_->RemoveObserver(this);
}
virtual void Draw() OVERRIDE {
layer_->set_color(
SkColorSetARGBInline(255*(frames() % kFrames)/kFrames, 255, 0, 255));
layer_->SchedulePaint(gfx::Rect(layer_->bounds().size()));
}
private:
ColoredLayer* layer_;
Compositor* compositor_;
DISALLOW_COPY_AND_ASSIGN(SoftwareScrollBench);
};
} // namespace
int main(int argc, char** argv) {
CommandLine::Init(argc, argv);
base::AtExitManager exit_manager;
ui::RegisterPathProvider();
icu_util::Initialize();
ResourceBundle::InitSharedInstanceWithLocale("en-US", NULL);
MessageLoop message_loop(MessageLoop::TYPE_UI);
ui::CompositorTestSupport::Initialize();
aura::SingleDisplayManager* manager = new aura::SingleDisplayManager;
manager->set_use_fullscreen_host_window(true);
aura::Env::GetInstance()->SetDisplayManager(manager);
scoped_ptr<aura::RootWindow> root_window(
aura::DisplayManager::CreateRootWindowForPrimaryDisplay());
aura::client::SetCaptureClient(
root_window.get(),
new aura::shared::RootWindowCaptureClient(root_window.get()));
// add layers
ColoredLayer background(SK_ColorRED);
background.SetBounds(root_window->bounds());
root_window->layer()->Add(&background);
ColoredLayer window(SK_ColorBLUE);
window.SetBounds(gfx::Rect(background.bounds().size()));
background.Add(&window);
Layer content_layer(ui::LAYER_NOT_DRAWN);
CommandLine* command_line = CommandLine::ForCurrentProcess();
bool force = command_line->HasSwitch("force-render-surface");
content_layer.SetForceRenderSurface(force);
gfx::Rect bounds(window.bounds().size());
bounds.Inset(0, 30, 0, 0);
content_layer.SetBounds(bounds);
window.Add(&content_layer);
ColoredLayer page_background(SK_ColorWHITE);
page_background.SetBounds(gfx::Rect(content_layer.bounds().size()));
content_layer.Add(&page_background);
int frames = atoi(command_line->GetSwitchValueASCII("frames").c_str());
scoped_ptr<BenchCompositorObserver> bench;
if (command_line->HasSwitch("bench-software-scroll")) {
bench.reset(new SoftwareScrollBench(&page_background,
root_window->compositor(),
frames));
} else {
bench.reset(new WebGLBench(&page_background,
root_window->compositor(),
frames));
}
#ifndef NDEBUG
ui::PrintLayerHierarchy(root_window->layer(), gfx::Point(100, 100));
#endif
root_window->ShowRootWindow();
MessageLoopForUI::current()->Run();
root_window.reset();
ui::CompositorTestSupport::Terminate();
return 0;
}
<commit_msg>aura_bench: Add a focus manager so that we don't crash on key press.<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/at_exit.h"
#include "base/bind.h"
#include "base/command_line.h"
#include "base/i18n/icu_util.h"
#include "base/memory/scoped_ptr.h"
#include "base/message_loop.h"
#include "base/string_split.h"
#include "base/time.h"
#include "third_party/khronos/GLES2/gl2.h"
#include "third_party/skia/include/core/SkXfermode.h"
#include "ui/aura/env.h"
#include "ui/aura/focus_manager.h"
#include "ui/aura/root_window.h"
#include "ui/aura/single_display_manager.h"
#include "ui/aura/shared/root_window_capture_client.h"
#include "ui/aura/window.h"
#include "ui/base/hit_test.h"
#include "ui/base/resource/resource_bundle.h"
#include "ui/base/ui_base_paths.h"
#include "ui/compositor/compositor.h"
#include "ui/compositor/compositor_observer.h"
#include "ui/compositor/debug_utils.h"
#include "ui/compositor/layer.h"
#include "ui/compositor/test/compositor_test_support.h"
#include "ui/gfx/canvas.h"
#include "ui/gfx/rect.h"
#include "ui/gfx/skia_util.h"
#ifndef GL_GLEXT_PROTOTYPES
#define GL_GLEXT_PROTOTYPES 1
#endif
#include "third_party/khronos/GLES2/gl2ext.h"
#include "third_party/WebKit/Source/WebKit/chromium/public/platform/WebGraphicsContext3D.h"
#if defined(USE_X11)
#include "base/message_pump_aurax11.h"
#endif
using base::TimeTicks;
using ui::Compositor;
using ui::Layer;
using ui::LayerDelegate;
using WebKit::WebGraphicsContext3D;
namespace {
class ColoredLayer : public Layer, public LayerDelegate {
public:
explicit ColoredLayer(SkColor color)
: Layer(ui::LAYER_TEXTURED),
color_(color),
draw_(true) {
set_delegate(this);
}
virtual ~ColoredLayer() {}
// Overridden from LayerDelegate:
virtual void OnPaintLayer(gfx::Canvas* canvas) OVERRIDE {
if (draw_) {
canvas->DrawColor(color_);
}
}
virtual void OnDeviceScaleFactorChanged(float device_scale_factor) OVERRIDE {
}
virtual base::Closure PrepareForLayerBoundsChange() OVERRIDE {
return base::Closure();
}
void set_color(SkColor color) { color_ = color; }
void set_draw(bool draw) { draw_ = draw; }
private:
SkColor color_;
bool draw_;
DISALLOW_COPY_AND_ASSIGN(ColoredLayer);
};
const int kFrames = 100;
// Benchmark base class, hooks up drawing callback and displaying FPS.
class BenchCompositorObserver : public ui::CompositorObserver {
public:
explicit BenchCompositorObserver(int max_frames)
: start_time_(),
frames_(0),
max_frames_(max_frames) {
}
virtual void OnCompositingDidCommit(ui::Compositor* compositor) OVERRIDE {}
virtual void OnCompositingWillStart(Compositor* compositor) OVERRIDE {}
virtual void OnCompositingStarted(Compositor* compositor) OVERRIDE {}
virtual void OnCompositingEnded(Compositor* compositor) OVERRIDE {
if (start_time_.is_null()) {
start_time_ = TimeTicks::Now();
} else {
++frames_;
if (frames_ % kFrames == 0) {
TimeTicks now = TimeTicks::Now();
double ms = (now - start_time_).InMillisecondsF() / kFrames;
LOG(INFO) << "FPS: " << 1000.f / ms << " (" << ms << " ms)";
start_time_ = now;
}
}
if (max_frames_ && frames_ == max_frames_) {
MessageLoop::current()->Quit();
} else {
Draw();
}
}
virtual void OnCompositingAborted(Compositor* compositor) OVERRIDE {}
virtual void Draw() {}
int frames() const { return frames_; }
private:
TimeTicks start_time_;
int frames_;
int max_frames_;
DISALLOW_COPY_AND_ASSIGN(BenchCompositorObserver);
};
class WebGLTexture : public ui::Texture {
public:
WebGLTexture(WebGraphicsContext3D* context, const gfx::Size& size)
: ui::Texture(false, size),
context_(context) {
set_texture_id(context_->createTexture());
context_->bindTexture(GL_TEXTURE_2D, texture_id());
context_->texParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR);
context_->texParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR);
context_->texParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE);
context_->texParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_EDGE);
context_->texImage2D(GL_TEXTURE_2D, 0, GL_RGBA,
size.width(), size.height(), 0,
GL_RGBA, GL_UNSIGNED_BYTE, NULL);
}
virtual WebGraphicsContext3D* HostContext3D() OVERRIDE {
return context_;
}
private:
virtual ~WebGLTexture() {
context_->deleteTexture(texture_id());
}
WebGraphicsContext3D* context_;
DISALLOW_COPY_AND_ASSIGN(WebGLTexture);
};
// A benchmark that adds a texture layer that is updated every frame.
class WebGLBench : public BenchCompositorObserver {
public:
WebGLBench(Layer* parent, Compositor* compositor, int max_frames)
: BenchCompositorObserver(max_frames),
parent_(parent),
webgl_(ui::LAYER_TEXTURED),
compositor_(compositor),
context_(),
texture_(),
fbo_(0),
do_draw_(true) {
CommandLine* command_line = CommandLine::ForCurrentProcess();
do_draw_ = !command_line->HasSwitch("disable-draw");
std::string webgl_size = command_line->GetSwitchValueASCII("webgl-size");
int width = 0;
int height = 0;
if (!webgl_size.empty()) {
std::vector<std::string> split_size;
base::SplitString(webgl_size, 'x', &split_size);
if (split_size.size() == 2) {
width = atoi(split_size[0].c_str());
height = atoi(split_size[1].c_str());
}
}
if (!width || !height) {
width = 800;
height = 600;
}
gfx::Rect bounds(width, height);
webgl_.SetBounds(bounds);
parent_->Add(&webgl_);
context_.reset(ui::ContextFactory::GetInstance()->CreateOffscreenContext());
context_->makeContextCurrent();
texture_ = new WebGLTexture(context_.get(), bounds.size());
fbo_ = context_->createFramebuffer();
compositor->AddObserver(this);
webgl_.SetExternalTexture(texture_);
context_->bindFramebuffer(GL_FRAMEBUFFER, fbo_);
context_->framebufferTexture2D(
GL_FRAMEBUFFER, GL_COLOR_ATTACHMENT0,
GL_TEXTURE_2D, texture_->texture_id(), 0);
context_->clearColor(0.f, 1.f, 0.f, 1.f);
context_->clear(GL_COLOR_BUFFER_BIT);
context_->flush();
}
virtual ~WebGLBench() {
context_->makeContextCurrent();
context_->deleteFramebuffer(fbo_);
webgl_.SetExternalTexture(NULL);
texture_ = NULL;
compositor_->RemoveObserver(this);
}
virtual void Draw() OVERRIDE {
if (do_draw_) {
context_->makeContextCurrent();
context_->clearColor((frames() % kFrames)*1.0/kFrames, 1.f, 0.f, 1.f);
context_->clear(GL_COLOR_BUFFER_BIT);
context_->flush();
}
webgl_.SetExternalTexture(texture_);
webgl_.SchedulePaint(gfx::Rect(webgl_.bounds().size()));
compositor_->ScheduleDraw();
}
private:
Layer* parent_;
Layer webgl_;
Compositor* compositor_;
scoped_ptr<WebGraphicsContext3D> context_;
scoped_refptr<WebGLTexture> texture_;
// The FBO that is used to render to the texture.
unsigned int fbo_;
// Whether or not to draw to the texture every frame.
bool do_draw_;
DISALLOW_COPY_AND_ASSIGN(WebGLBench);
};
// A benchmark that paints (in software) all tiles every frame.
class SoftwareScrollBench : public BenchCompositorObserver {
public:
SoftwareScrollBench(ColoredLayer* layer,
Compositor* compositor,
int max_frames)
: BenchCompositorObserver(max_frames),
layer_(layer),
compositor_(compositor) {
compositor->AddObserver(this);
layer_->set_draw(
!CommandLine::ForCurrentProcess()->HasSwitch("disable-draw"));
}
virtual ~SoftwareScrollBench() {
compositor_->RemoveObserver(this);
}
virtual void Draw() OVERRIDE {
layer_->set_color(
SkColorSetARGBInline(255*(frames() % kFrames)/kFrames, 255, 0, 255));
layer_->SchedulePaint(gfx::Rect(layer_->bounds().size()));
}
private:
ColoredLayer* layer_;
Compositor* compositor_;
DISALLOW_COPY_AND_ASSIGN(SoftwareScrollBench);
};
} // namespace
int main(int argc, char** argv) {
CommandLine::Init(argc, argv);
base::AtExitManager exit_manager;
ui::RegisterPathProvider();
icu_util::Initialize();
ResourceBundle::InitSharedInstanceWithLocale("en-US", NULL);
MessageLoop message_loop(MessageLoop::TYPE_UI);
ui::CompositorTestSupport::Initialize();
aura::SingleDisplayManager* manager = new aura::SingleDisplayManager;
manager->set_use_fullscreen_host_window(true);
aura::Env::GetInstance()->SetDisplayManager(manager);
scoped_ptr<aura::RootWindow> root_window(
aura::DisplayManager::CreateRootWindowForPrimaryDisplay());
aura::client::SetCaptureClient(
root_window.get(),
new aura::shared::RootWindowCaptureClient(root_window.get()));
scoped_ptr<aura::FocusManager> focus_manager(new aura::FocusManager);
root_window->set_focus_manager(focus_manager.get());
// add layers
ColoredLayer background(SK_ColorRED);
background.SetBounds(root_window->bounds());
root_window->layer()->Add(&background);
ColoredLayer window(SK_ColorBLUE);
window.SetBounds(gfx::Rect(background.bounds().size()));
background.Add(&window);
Layer content_layer(ui::LAYER_NOT_DRAWN);
CommandLine* command_line = CommandLine::ForCurrentProcess();
bool force = command_line->HasSwitch("force-render-surface");
content_layer.SetForceRenderSurface(force);
gfx::Rect bounds(window.bounds().size());
bounds.Inset(0, 30, 0, 0);
content_layer.SetBounds(bounds);
window.Add(&content_layer);
ColoredLayer page_background(SK_ColorWHITE);
page_background.SetBounds(gfx::Rect(content_layer.bounds().size()));
content_layer.Add(&page_background);
int frames = atoi(command_line->GetSwitchValueASCII("frames").c_str());
scoped_ptr<BenchCompositorObserver> bench;
if (command_line->HasSwitch("bench-software-scroll")) {
bench.reset(new SoftwareScrollBench(&page_background,
root_window->compositor(),
frames));
} else {
bench.reset(new WebGLBench(&page_background,
root_window->compositor(),
frames));
}
#ifndef NDEBUG
ui::PrintLayerHierarchy(root_window->layer(), gfx::Point(100, 100));
#endif
root_window->ShowRootWindow();
MessageLoopForUI::current()->Run();
focus_manager.reset();
root_window.reset();
ui::CompositorTestSupport::Terminate();
return 0;
}
<|endoftext|> |
<commit_before>#ifndef RADIUMENGINE_COLOR_PRESET_HPP_
#define RADIUMENGINE_COLOR_PRESET_HPP_
#include <Core/Math/LinearAlgebra.hpp>
namespace Ra{
namespace Core{
/// Colors are defined as vector4, i.e. 4 floats in RGBA order.
/// displayable colors should have all their coordinates between 0 and 1.
namespace Colors
{
// Primary and secondary colors.
// TODO (Val) : check if we can make these constexpr
inline Color Black() { return Color(0,0,0,1); }
inline Color Red() { return Color(1,0,0,1); }
inline Color Green() { return Color(0,1,0,1); }
inline Color Blue() { return Color(0,0,1,1); }
inline Color Yellow() { return Color(1,1,0,1); }
inline Color Magenta() { return Color(1,0,1,1); }
inline Color Cyan() { return Color(0,1,1,1); }
inline Color White() { return Color(1,1,1,1); }
inline Color Grey( Scalar f = 0.5f) { return Color(f,f,f,1);}
// Convert to/from various int formats
inline Color FromChars(uchar r, uchar g, uchar b, uchar a = 0xff)
{
return Color(Scalar(r)/255.0f, Scalar(g)/255.0f, Scalar(b)/255.0f, Scalar(a)/255.0f );
}
inline Color FromRGBA32(uint32_t rgba)
{
uchar r = uchar((rgba >> 24) & 0xff);
uchar g = uchar((rgba >> 16) & 0xff);
uchar b = uchar((rgba >> 8) & 0xff);
uchar a = uchar((rgba >> 0) & 0xff);
return FromChars(r,g,b,a);
}
inline uint32_t ToRGBA32(const Color& color)
{
Vector4i scaled = (color * 255).cast<int>();
return (uint32_t(scaled[0])<<24) | (uint32_t(scaled[1])<<16) |(uint32_t(scaled[2])<<12) |(uint32_t(scaled[3])<<0);
}
}
}
}
#endif //RADIUMENGINE_COLOR_PRESET_HPP_
<commit_msg>Added the Alpha color static function<commit_after>#ifndef RADIUMENGINE_COLOR_PRESET_HPP_
#define RADIUMENGINE_COLOR_PRESET_HPP_
#include <Core/Math/LinearAlgebra.hpp>
namespace Ra{
namespace Core{
/// Colors are defined as vector4, i.e. 4 floats in RGBA order.
/// displayable colors should have all their coordinates between 0 and 1.
namespace Colors
{
// Primary and secondary colors.
// TODO (Val) : check if we can make these constexpr
inline Color Alpha() { return Color( 0.0, 0.0, 0.0, 0.0 ); }
inline Color Black() { return Color(0,0,0,1); }
inline Color Red() { return Color(1,0,0,1); }
inline Color Green() { return Color(0,1,0,1); }
inline Color Blue() { return Color(0,0,1,1); }
inline Color Yellow() { return Color(1,1,0,1); }
inline Color Magenta() { return Color(1,0,1,1); }
inline Color Cyan() { return Color(0,1,1,1); }
inline Color White() { return Color(1,1,1,1); }
inline Color Grey( Scalar f = 0.5f) { return Color(f,f,f,1);}
// Convert to/from various int formats
inline Color FromChars(uchar r, uchar g, uchar b, uchar a = 0xff)
{
return Color(Scalar(r)/255.0f, Scalar(g)/255.0f, Scalar(b)/255.0f, Scalar(a)/255.0f );
}
inline Color FromRGBA32(uint32_t rgba)
{
uchar r = uchar((rgba >> 24) & 0xff);
uchar g = uchar((rgba >> 16) & 0xff);
uchar b = uchar((rgba >> 8) & 0xff);
uchar a = uchar((rgba >> 0) & 0xff);
return FromChars(r,g,b,a);
}
inline uint32_t ToRGBA32(const Color& color)
{
Vector4i scaled = (color * 255).cast<int>();
return (uint32_t(scaled[0])<<24) | (uint32_t(scaled[1])<<16) |(uint32_t(scaled[2])<<12) |(uint32_t(scaled[3])<<0);
}
}
}
}
#endif //RADIUMENGINE_COLOR_PRESET_HPP_
<|endoftext|> |
<commit_before>#include <algorithm>
#include <cctype>
#include <Utils/MathUtils.hpp>
#include <Utils/StringUtils.hpp>
#include <Utils/VectorUtils.hpp>
namespace obe::Utils::String
{
std::vector<std::string> split(const std::string& str, const std::string& delimiters)
{
std::vector<std::string> tokens;
std::string::size_type lastPos = str.find_first_not_of(delimiters, 0);
std::string::size_type pos = str.find_first_of(delimiters, lastPos);
while (std::string::npos != pos || std::string::npos != lastPos)
{
tokens.push_back(str.substr(lastPos, pos - lastPos));
lastPos = str.find_first_not_of(delimiters, pos);
pos = str.find_first_of(delimiters, lastPos);
}
return tokens;
}
int occurencesInString(const std::string& str, const std::string& occur)
{
int occurrences = 0;
std::string::size_type start = 0;
while ((start = str.find(occur, start)) != std::string::npos)
{
++occurrences;
start += occur.length();
}
return occurrences;
}
bool isStringAlpha(const std::string& str)
{
if (!str.empty())
return all_of(str.begin(), str.end(), isalpha);
return false;
}
bool isStringAlphaNumeric(const std::string& str)
{
if (!str.empty())
return all_of(str.begin(), str.end(), isalnum);
return false;
}
bool isStringInt(const std::string& str)
{
if (!str.empty())
{
if (str.substr(0, 1) == "-")
{
std::string withoutSign = str.substr(1);
return all_of(withoutSign.begin(), withoutSign.end(), isdigit);
}
return all_of(str.begin(), str.end(), isdigit);
}
return false;
}
bool isStringFloat(const std::string& str)
{
std::string modifyStr = str;
bool isFloat = false;
if (!modifyStr.empty())
{
if (modifyStr.substr(0, 1) == "-")
modifyStr = modifyStr.substr(1);
if (occurencesInString(modifyStr, ".") == 1)
{
isFloat = true;
replaceInPlace(modifyStr, ".", "");
}
return (all_of(modifyStr.begin(), modifyStr.end(), isdigit) && isFloat);
}
return false;
}
bool isStringNumeric(const std::string& str)
{
return (isStringFloat(str) || isStringInt(str));
}
void replaceInPlace(
std::string& subject, const std::string& search, const std::string& replace)
{
size_t pos = 0;
while ((pos = subject.find(search, pos)) != std::string::npos)
{
subject.replace(pos, search.length(), replace);
pos += replace.length();
}
}
std::string replace(
std::string subject, const std::string& search, const std::string& replace)
{
size_t pos = 0;
while ((pos = subject.find(search, pos)) != std::string::npos)
{
subject.replace(pos, search.length(), replace);
pos += replace.length();
}
return subject;
}
bool isSurroundedBy(const std::string& string, const std::string& bet)
{
return (string.substr(0, bet.size()) == bet
&& string.substr(string.size() - bet.size(), bet.size()) == bet);
}
std::string getRandomKey(const std::string& set, const int len)
{
std::string r;
for (int i = 0; i < len; i++)
r.push_back(set.at(size_t(Math::randint(0, 100000) % set.size())));
return r;
}
bool contains(const std::string& string, const std::string& search)
{
return (string.find(search) != std::string::npos);
}
bool startsWith(const std::string& string, const std::string& search)
{
if (string.size() < search.size())
return false;
return (std::mismatch(search.begin(), search.end(), string.begin()).first
== search.end());
}
bool endsWith(const std::string& string, const std::string& search)
{
if (string.size() < search.size())
{
return false;
}
return (std::mismatch(search.rbegin(), search.rend(), string.rbegin()).first
== search.rend());
}
std::size_t distance(std::string_view source, std::string_view target)
{
if (source.size() > target.size())
{
return distance(target, source);
}
const std::size_t min_size = source.size(), max_size = target.size();
std::vector<std::size_t> lev_dist(min_size + 1);
for (std::size_t i = 0; i <= min_size; ++i)
{
lev_dist[i] = i;
}
for (std::size_t j = 1; j <= max_size; ++j)
{
std::size_t previous_diagonal = lev_dist[0];
++lev_dist[0];
for (std::size_t i = 1; i <= min_size; ++i)
{
const std::size_t previous_diagonal_save = lev_dist[i];
if (source[i - 1] == target[j - 1])
{
lev_dist[i] = previous_diagonal;
}
else
{
lev_dist[i] = std::min(std::min(lev_dist[i - 1], lev_dist[i]),
previous_diagonal)
+ 1;
}
previous_diagonal = previous_diagonal_save;
}
}
return lev_dist[min_size];
}
std::vector<std::string> sortByDistance(const std::string& source,
const std::vector<std::string>& words, std::size_t limit)
{
std::vector<std::string> sortedByDistance = words;
std::sort(sortedByDistance.begin(), sortedByDistance.end(),
[source](const std::string& s1, const std::string& s2) {
return Utils::String::distance(s1, source)
< Utils::String::distance(s2, source);
});
if (limit)
return std::vector<std::string>(
sortedByDistance.begin(), sortedByDistance.begin() + limit);
else
return sortedByDistance;
}
std::string quote(const std::string& source)
{
return "\"" + source + "\"";
}
} // namespace obe::Utils::String<commit_msg>Fix sortedByDistance limit overflow<commit_after>#include <algorithm>
#include <cctype>
#include <Utils/MathUtils.hpp>
#include <Utils/StringUtils.hpp>
#include <Utils/VectorUtils.hpp>
namespace obe::Utils::String
{
std::vector<std::string> split(const std::string& str, const std::string& delimiters)
{
std::vector<std::string> tokens;
std::string::size_type lastPos = str.find_first_not_of(delimiters, 0);
std::string::size_type pos = str.find_first_of(delimiters, lastPos);
while (std::string::npos != pos || std::string::npos != lastPos)
{
tokens.push_back(str.substr(lastPos, pos - lastPos));
lastPos = str.find_first_not_of(delimiters, pos);
pos = str.find_first_of(delimiters, lastPos);
}
return tokens;
}
int occurencesInString(const std::string& str, const std::string& occur)
{
int occurrences = 0;
std::string::size_type start = 0;
while ((start = str.find(occur, start)) != std::string::npos)
{
++occurrences;
start += occur.length();
}
return occurrences;
}
bool isStringAlpha(const std::string& str)
{
if (!str.empty())
return all_of(str.begin(), str.end(), isalpha);
return false;
}
bool isStringAlphaNumeric(const std::string& str)
{
if (!str.empty())
return all_of(str.begin(), str.end(), isalnum);
return false;
}
bool isStringInt(const std::string& str)
{
if (!str.empty())
{
if (str.substr(0, 1) == "-")
{
std::string withoutSign = str.substr(1);
return all_of(withoutSign.begin(), withoutSign.end(), isdigit);
}
return all_of(str.begin(), str.end(), isdigit);
}
return false;
}
bool isStringFloat(const std::string& str)
{
std::string modifyStr = str;
bool isFloat = false;
if (!modifyStr.empty())
{
if (modifyStr.substr(0, 1) == "-")
modifyStr = modifyStr.substr(1);
if (occurencesInString(modifyStr, ".") == 1)
{
isFloat = true;
replaceInPlace(modifyStr, ".", "");
}
return (all_of(modifyStr.begin(), modifyStr.end(), isdigit) && isFloat);
}
return false;
}
bool isStringNumeric(const std::string& str)
{
return (isStringFloat(str) || isStringInt(str));
}
void replaceInPlace(
std::string& subject, const std::string& search, const std::string& replace)
{
size_t pos = 0;
while ((pos = subject.find(search, pos)) != std::string::npos)
{
subject.replace(pos, search.length(), replace);
pos += replace.length();
}
}
std::string replace(
std::string subject, const std::string& search, const std::string& replace)
{
size_t pos = 0;
while ((pos = subject.find(search, pos)) != std::string::npos)
{
subject.replace(pos, search.length(), replace);
pos += replace.length();
}
return subject;
}
bool isSurroundedBy(const std::string& string, const std::string& bet)
{
return (string.substr(0, bet.size()) == bet
&& string.substr(string.size() - bet.size(), bet.size()) == bet);
}
std::string getRandomKey(const std::string& set, const int len)
{
std::string r;
for (int i = 0; i < len; i++)
r.push_back(set.at(size_t(Math::randint(0, 100000) % set.size())));
return r;
}
bool contains(const std::string& string, const std::string& search)
{
return (string.find(search) != std::string::npos);
}
bool startsWith(const std::string& string, const std::string& search)
{
if (string.size() < search.size())
return false;
return (std::mismatch(search.begin(), search.end(), string.begin()).first
== search.end());
}
bool endsWith(const std::string& string, const std::string& search)
{
if (string.size() < search.size())
{
return false;
}
return (std::mismatch(search.rbegin(), search.rend(), string.rbegin()).first
== search.rend());
}
std::size_t distance(std::string_view source, std::string_view target)
{
if (source.size() > target.size())
{
return distance(target, source);
}
const std::size_t min_size = source.size(), max_size = target.size();
std::vector<std::size_t> lev_dist(min_size + 1);
for (std::size_t i = 0; i <= min_size; ++i)
{
lev_dist[i] = i;
}
for (std::size_t j = 1; j <= max_size; ++j)
{
std::size_t previous_diagonal = lev_dist[0];
++lev_dist[0];
for (std::size_t i = 1; i <= min_size; ++i)
{
const std::size_t previous_diagonal_save = lev_dist[i];
if (source[i - 1] == target[j - 1])
{
lev_dist[i] = previous_diagonal;
}
else
{
lev_dist[i] = std::min(std::min(lev_dist[i - 1], lev_dist[i]),
previous_diagonal)
+ 1;
}
previous_diagonal = previous_diagonal_save;
}
}
return lev_dist[min_size];
}
std::vector<std::string> sortByDistance(const std::string& source,
const std::vector<std::string>& words, std::size_t limit)
{
std::vector<std::string> sortedByDistance = words;
std::sort(sortedByDistance.begin(), sortedByDistance.end(),
[source](const std::string& s1, const std::string& s2) {
return Utils::String::distance(s1, source)
< Utils::String::distance(s2, source);
});
if (limit)
return std::vector<std::string>(sortedByDistance.begin(),
sortedByDistance.begin() + std::min(sortedByDistance.size() - 1, limit));
else
return sortedByDistance;
}
std::string quote(const std::string& source)
{
return "\"" + source + "\"";
}
} // namespace obe::Utils::String<|endoftext|> |
<commit_before>/*
* The Apache Software License, Version 1.1
*
*
* Copyright (c) 1999-2001 The Apache Software Foundation. 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. The end-user documentation included with the redistribution,
* if any, must include the following acknowledgment:
* "This product includes software developed by the
* Apache Software Foundation (http://www.apache.org/)."
* Alternately, this acknowledgment may appear in the software itself,
* if and wherever such third-party acknowledgments normally appear.
*
* 4. The names "Xalan" and "Apache Software Foundation" must
* not be used to endorse or promote products derived from this
* software without prior written permission. For written
* permission, please contact apache@apache.org.
*
* 5. Products derived from this software may not be called "Apache",
* nor may "Apache" appear in their name, without prior written
* permission of the Apache Software Foundation.
*
* THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED 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 APACHE SOFTWARE FOUNDATION OR
* ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
* SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
* LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF
* USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
* ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
* OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT
* OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
* SUCH DAMAGE.
* ====================================================================
*
* This software consists of voluntary contributions made by many
* individuals on behalf of the Apache Software Foundation and was
* originally based on software copyright (c) 1999, International
* Business Machines, Inc., http://www.ibm.com. For more
* information on the Apache Software Foundation, please see
* <http://www.apache.org/>.
*/
#if defined(XALAN_OLD_STREAM_HEADERS)
#include <iostream.h>
//#include <strstream.h>
#include <sstream>
#else
#include <iostream>
//#include <strstream>
#include <sstream>
#endif
#include <stdio.h>
#if !defined(XALAN_NO_NAMESPACES)
using std::cerr;
using std::cout;
using std::cin;
using std::endl;
using std::ostringstream;
#endif
// XERCES HEADERS...
// Most are included by HarnessInit.hpp
#include <parsers/DOMParser.hpp>
// XALAN HEADERS...
// Most are included by FileUtility.hpp
#include <XalanTransformer/XercesDOMWrapperParsedSource.hpp>
// HARNESS HEADERS...
#include <Harness/XMLFileReporter.hpp>
#include <Harness/FileUtility.hpp>
#include <Harness/HarnessInit.hpp>
#if defined(XALAN_NO_NAMESPACES)
typedef map<XalanDOMString, XalanDOMString, less<XalanDOMString> > Hashtable;
#else
typedef std::map<XalanDOMString, XalanDOMString> Hashtable;
#endif
// This is here for memory leak testing.
#if !defined(NDEBUG) && defined(_MSC_VER)
#include <crtdbg.h>
#endif
FileUtility h;
void
setHelp()
{
h.args.help << endl
<< "conf dir [-category -out -gold -source (XST | XPL | DOM)]"
<< endl
<< endl
<< "dir (base directory for testcases)"
<< endl
<< "-sub dir (specific directory)"
<< endl
<< "-out dir (base directory for output)"
<< endl
<< "-gold dir (base directory for gold files)"
<< endl
<< "-src type (parsed source; XalanSourceTree(d), XercesParserLiasion, XercesDOM)"
<< endl;
}
static const char* const excludeStylesheets[] =
{
"output22.xsl", // Excluded because it outputs EBCDIC
0
};
inline bool
checkForExclusion(const XalanDOMString& currentFile)
{
for (size_t i = 0; excludeStylesheets[i] != 0; ++i)
{
if (equals(currentFile, excludeStylesheets[i]))
{
return true;
}
}
return false;
}
void
parseWithTransformer(int sourceType, XalanTransformer &xalan, const XSLTInputSource &xmlInput,
const XalanCompiledStylesheet* styleSheet, const XSLTResultTarget &output,
XMLFileReporter &logFile)
{
const XalanParsedSource* parsedSource = 0;
// Parse the XML source accordingly.
//
if (sourceType != 0 )
{
xalan.parseSource(xmlInput, parsedSource, true);
h.data.xmlFormat = XalanDOMString("XercesParserLiasion");
}
else
{
xalan.parseSource(xmlInput, parsedSource, false);
h.data.xmlFormat = XalanDOMString("XalanSourceTree");
}
// If the source was parsed correctly then perform the transform else report the failure.
//
if (parsedSource == 0)
{
// Report the failure and be sure to increment fail count.
//
cout << "ParseWTransformer - Failed to PARSE source document for " << h.data.testOrFile << endl;
++h.data.fail;
logFile.logErrorResult(h.data.testOrFile, XalanDOMString("Failed to PARSE source document."));
}
else
{
xalan.transform(*parsedSource, styleSheet, output);
xalan.destroyParsedSource(parsedSource);
}
}
void
parseWithXerces(XalanTransformer &xalan, const XSLTInputSource &xmlInput,
const XalanCompiledStylesheet* styleSheet, const XSLTResultTarget &output,
XMLFileReporter &logFile)
{
h.data.xmlFormat = XalanDOMString("Xerces_DOM");
DOMParser theParser;
theParser.setToCreateXMLDeclTypeNode(false);
theParser.setDoValidation(true);
theParser.setDoNamespaces(true);
theParser.parse(xmlInput);
DOM_Document theDOM = theParser.getDocument();
theDOM.normalize();
XercesDOMSupport theDOMSupport;
XercesParserLiaison theParserLiaison;
try
{
const XercesDOMWrapperParsedSource parsedSource(
theDOM,
theParserLiaison,
theDOMSupport,
XalanDOMString(xmlInput.getSystemId()));
xalan.transform(parsedSource, styleSheet, output);
}
catch(...)
{
// Report the failure and be sure to increment fail count.
//
cout << "parseWXerces - Failed to PARSE source document for " << h.data.testOrFile << endl;
++h.data.fail;
logFile.logErrorResult(h.data.testOrFile, XalanDOMString("Failed to PARSE source document."));
}
}
int
main(int argc,
const char* argv[])
{
#if !defined(NDEBUG) && defined(_MSC_VER)
_CrtSetDbgFlag(_CrtSetDbgFlag(_CRTDBG_REPORT_FLAG) | _CRTDBG_LEAK_CHECK_DF);
_CrtSetReportMode(_CRT_WARN, _CRTDBG_MODE_FILE);
_CrtSetReportFile(_CRT_WARN, _CRTDBG_FILE_STDERR);
#endif
// Set the program help string, then get the command line parameters.
//
setHelp();
if (h.getParams(argc, argv, "CONF-RESULTS") == true)
{
// Call the static initializers for xerces and xalan, and create a transformer
//
HarnessInit xmlPlatformUtils;
XalanTransformer::initialize();
XalanTransformer xalan;
// Get drive designation for final analysis and generate Unique name for results log.
//
const XalanDOMString drive(h.getDrive()); // This is used to get stylesheet for final analysis
const XalanDOMString resultFilePrefix("conf"); // This & UniqRunid used for log file name.
const XalanDOMString UniqRunid = h.generateUniqRunid();
const XalanDOMString resultsFile(drive + h.args.output + resultFilePrefix + UniqRunid + XMLSuffix);
// Open results log, and do some initialization of result data.
//
XMLFileReporter logFile(resultsFile);
logFile.logTestFileInit("Conformance Testing:");
h.data.xmlFormat = XalanDOMString("NotSet");
// Get the list of Directories that are below conf and iterate through them
//
bool foundDir = false; // Flag indicates directory found. Used in conjunction with -sub cmd-line arg.
const FileNameVectorType dirs = h.getDirectoryNames(h.args.base);
for(FileNameVectorType::size_type j = 0; j < dirs.size(); ++j)
{
// Skip all but the specified directory if the -sub cmd-line option was used.
//
const XalanDOMString currentDir(dirs[j]);
if (length(h.args.sub) > 0 && !equals(currentDir, h.args.sub))
{
continue;
}
// Check that output directory is there.
//
const XalanDOMString theOutputDir = h.args.output + currentDir;
h.checkAndCreateDir(theOutputDir);
// Indicate that directory was processed and get test files from the directory
//
foundDir = true;
const FileNameVectorType files = h.getTestFileNames(h.args.base, currentDir, true);
// Log directory in results log and process it's files.
//
logFile.logTestCaseInit(currentDir);
for(FileNameVectorType::size_type i = 0; i < files.size(); i++)
{
Hashtable attrs;
const XalanDOMString currentFile(files[i]);
if (checkForExclusion(currentFile))
continue;
h.data.testOrFile = currentFile;
const XalanDOMString theXSLFile = h.args.base + currentDir + pathSep + currentFile;
// Check and see if the .xml file exists. If not skip this .xsl file and continue.
bool fileStatus = true;
const XalanDOMString theXMLFile = h.generateFileName(theXSLFile, "xml", &fileStatus);
if (!fileStatus)
continue;
h.data.xmlFileURL = theXMLFile;
h.data.xslFileURL = theXSLFile;
XalanDOMString theGoldFile = h.args.gold + currentDir + pathSep + currentFile;
theGoldFile = h.generateFileName(theGoldFile, "out");
const XalanDOMString outbase = h.args.output + currentDir + pathSep + currentFile;
const XalanDOMString theOutputFile = h.generateFileName(outbase, "out");
const XSLTInputSource xslInputSource(c_wstr(theXSLFile));
const XSLTInputSource xmlInputSource(c_wstr(theXMLFile));
const XSLTResultTarget resultFile(theOutputFile);
// Parsing(compile) the XSL stylesheet and report the results..
//
const XalanCompiledStylesheet* compiledSS = 0;
xalan.compileStylesheet(xslInputSource, compiledSS);
if (compiledSS == 0 )
{
// Report the failure and be sure to increment fail count.
//
cout << "Failed to PARSE stylesheet for " << currentFile << endl;
h.data.fail += 1;
logFile.logErrorResult(currentFile, XalanDOMString("Failed to PARSE stylesheet."));
continue;
}
// Parse the Source XML based on input parameters, and then perform transform.
//
switch (h.args.source)
{
case 0:
case 1:
parseWithTransformer(h.args.source, xalan, xmlInputSource, compiledSS, resultFile, logFile);
break;
case 2:
parseWithXerces(xalan, xmlInputSource, compiledSS, resultFile, logFile);
break;
}
// Check and report results... Then delete compiled stylesheet.
//
h.checkResults(theOutputFile, theGoldFile, logFile);
xalan.destroyStylesheet(compiledSS);
}
logFile.logTestCaseClose("Done", "Pass");
}
// Check to see if -sub cmd-line directory was processed correctly.
//
if (!foundDir)
{
cout << "Specified test directory: \"" << c_str(TranscodeToLocalCodePage(h.args.sub)) << "\" not found" << endl;
}
h.reportPassFail(logFile, UniqRunid);
logFile.logTestFileClose("Conformance ", "Done");
logFile.close();
h.analyzeResults(xalan, resultsFile);
}
XalanTransformer::terminate();
return 0;
}
<commit_msg>Better exception handling.<commit_after>/*
* The Apache Software License, Version 1.1
*
*
* Copyright (c) 1999-2001 The Apache Software Foundation. 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. The end-user documentation included with the redistribution,
* if any, must include the following acknowledgment:
* "This product includes software developed by the
* Apache Software Foundation (http://www.apache.org/)."
* Alternately, this acknowledgment may appear in the software itself,
* if and wherever such third-party acknowledgments normally appear.
*
* 4. The names "Xalan" and "Apache Software Foundation" must
* not be used to endorse or promote products derived from this
* software without prior written permission. For written
* permission, please contact apache@apache.org.
*
* 5. Products derived from this software may not be called "Apache",
* nor may "Apache" appear in their name, without prior written
* permission of the Apache Software Foundation.
*
* THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED 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 APACHE SOFTWARE FOUNDATION OR
* ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
* SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
* LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF
* USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
* ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
* OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT
* OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
* SUCH DAMAGE.
* ====================================================================
*
* This software consists of voluntary contributions made by many
* individuals on behalf of the Apache Software Foundation and was
* originally based on software copyright (c) 1999, International
* Business Machines, Inc., http://www.ibm.com. For more
* information on the Apache Software Foundation, please see
* <http://www.apache.org/>.
*/
#if defined(XALAN_OLD_STREAM_HEADERS)
#include <iostream.h>
//#include <strstream.h>
#include <sstream>
#else
#include <iostream>
//#include <strstream>
#include <sstream>
#endif
#include <stdio.h>
#if !defined(XALAN_NO_NAMESPACES)
using std::cerr;
using std::cout;
using std::cin;
using std::endl;
using std::ostringstream;
#endif
#include <parsers/DOMParser.hpp>
#include <XalanTransformer/XalanTransformer.hpp>
#include <XalanTransformer/XercesDOMWrapperParsedSource.hpp>
// HARNESS HEADERS...
#include <Harness/XMLFileReporter.hpp>
#include <Harness/FileUtility.hpp>
#include <Harness/HarnessInit.hpp>
#if defined(XALAN_NO_NAMESPACES)
typedef map<XalanDOMString, XalanDOMString, less<XalanDOMString> > Hashtable;
#else
typedef std::map<XalanDOMString, XalanDOMString> Hashtable;
#endif
// This is here for memory leak testing.
#if !defined(NDEBUG) && defined(_MSC_VER)
#include <crtdbg.h>
#endif
void
setHelp(FileUtility& h)
{
h.args.getHelpStream() << endl
<< "conf dir [-category -out -gold -source (XST | XPL | DOM)]"
<< endl
<< endl
<< "dir (base directory for testcases)"
<< endl
<< "-sub dir (specific directory)"
<< endl
<< "-out dir (base directory for output)"
<< endl
<< "-gold dir (base directory for gold files)"
<< endl
<< "-src type (parsed source; XalanSourceTree(d), XercesParserLiasion, XercesDOM)"
<< endl;
}
static const char* const excludeStylesheets[] =
{
"output22.xsl", // Excluded because it outputs EBCDIC
0
};
inline bool
checkForExclusion(const XalanDOMString& currentFile)
{
for (size_t i = 0; excludeStylesheets[i] != 0; ++i)
{
if (equals(currentFile, excludeStylesheets[i]))
{
return true;
}
}
return false;
}
void
parseWithTransformer(
int sourceType,
XalanTransformer& xalan,
const XSLTInputSource& xmlInput,
const XalanCompiledStylesheet* styleSheet,
const XSLTResultTarget& output,
XMLFileReporter& logFile,
FileUtility& h)
{
const XalanParsedSource* parsedSource = 0;
// Parse the XML source accordingly.
//
if (sourceType != 0 )
{
xalan.parseSource(xmlInput, parsedSource, true);
h.data.xmlFormat = XalanDOMString("XercesParserLiasion");
}
else
{
xalan.parseSource(xmlInput, parsedSource, false);
h.data.xmlFormat = XalanDOMString("XalanSourceTree");
}
// If the source was parsed correctly then perform the transform else report the failure.
//
if (parsedSource == 0)
{
// Report the failure and be sure to increment fail count.
//
cout << "ParseWTransformer - Failed to PARSE source document for " << h.data.testOrFile << endl;
++h.data.fail;
logFile.logErrorResult(h.data.testOrFile, XalanDOMString("Failed to PARSE source document."));
}
else
{
xalan.transform(*parsedSource, styleSheet, output);
xalan.destroyParsedSource(parsedSource);
}
}
void
parseWithXerces(
XalanTransformer& xalan,
const XSLTInputSource& xmlInput,
const XalanCompiledStylesheet* styleSheet,
const XSLTResultTarget& output,
XMLFileReporter& logFile,
FileUtility& h)
{
h.data.xmlFormat = XalanDOMString("Xerces_DOM");
DOMParser theParser;
theParser.setToCreateXMLDeclTypeNode(false);
theParser.setDoValidation(true);
theParser.setDoNamespaces(true);
theParser.parse(xmlInput);
DOM_Document theDOM = theParser.getDocument();
theDOM.normalize();
XercesDOMSupport theDOMSupport;
XercesParserLiaison theParserLiaison;
try
{
const XercesDOMWrapperParsedSource parsedSource(
theDOM,
theParserLiaison,
theDOMSupport,
XalanDOMString(xmlInput.getSystemId()));
xalan.transform(parsedSource, styleSheet, output);
}
catch(...)
{
// Report the failure and be sure to increment fail count.
//
cout << "parseWXerces - Failed to PARSE source document for " << h.data.testOrFile << endl;
++h.data.fail;
logFile.logErrorResult(h.data.testOrFile, XalanDOMString("Failed to PARSE source document."));
}
}
int
main(int argc,
const char* argv[])
{
#if !defined(NDEBUG) && defined(_MSC_VER)
_CrtSetDbgFlag(_CrtSetDbgFlag(_CRTDBG_REPORT_FLAG) | _CRTDBG_LEAK_CHECK_DF);
_CrtSetReportMode(_CRT_WARN, _CRTDBG_MODE_FILE);
_CrtSetReportFile(_CRT_WARN, _CRTDBG_FILE_STDERR);
#endif
try
{
HarnessInit xmlPlatformUtils;
FileUtility h;
// Set the program help string, then get the command line parameters.
//
setHelp(h);
if (h.getParams(argc, argv, "CONF-RESULTS") == true)
{
// Call the static initializers for xerces and xalan, and create a transformer
//
XalanTransformer::initialize();
{
XalanTransformer xalan;
// Get drive designation for final analysis and generate Unique name for results log.
//
const XalanDOMString drive(h.getDrive()); // This is used to get stylesheet for final analysis
const XalanDOMString resultFilePrefix("conf"); // This & UniqRunid used for log file name.
const XalanDOMString UniqRunid = h.generateUniqRunid();
const XalanDOMString resultsFile(drive + h.args.output + resultFilePrefix + UniqRunid + FileUtility::s_xmlSuffix);
// Open results log, and do some initialization of result data.
//
XMLFileReporter logFile(resultsFile);
logFile.logTestFileInit("Conformance Testing:");
h.data.xmlFormat = XalanDOMString("NotSet");
// Get the list of Directories that are below conf and iterate through them
//
// Flag indicates directory found. Used in conjunction with -sub cmd-line arg.
bool foundDir = false;
const FileNameVectorType dirs = h.getDirectoryNames(h.args.base);
for(FileNameVectorType::size_type j = 0; j < dirs.size(); ++j)
{
// Skip all but the specified directory if the -sub cmd-line option was used.
//
const XalanDOMString currentDir(dirs[j]);
if (length(h.args.sub) > 0 && !equals(currentDir, h.args.sub))
{
continue;
}
// Check that output directory is there.
//
const XalanDOMString theOutputDir = h.args.output + currentDir;
h.checkAndCreateDir(theOutputDir);
// Indicate that directory was processed and get test files from the directory
//
foundDir = true;
const FileNameVectorType files = h.getTestFileNames(h.args.base, currentDir, true);
// Log directory in results log and process it's files.
//
logFile.logTestCaseInit(currentDir);
for(FileNameVectorType::size_type i = 0; i < files.size(); i++)
{
Hashtable attrs;
const XalanDOMString currentFile(files[i]);
if (checkForExclusion(currentFile))
continue;
h.data.testOrFile = currentFile;
const XalanDOMString theXSLFile = h.args.base + currentDir + FileUtility::s_pathSep + currentFile;
// Check and see if the .xml file exists. If not skip this .xsl file and continue.
bool fileStatus = true;
const XalanDOMString theXMLFile = h.generateFileName(theXSLFile, "xml", &fileStatus);
if (!fileStatus)
continue;
h.data.xmlFileURL = theXMLFile;
h.data.xslFileURL = theXSLFile;
XalanDOMString theGoldFile = h.args.gold + currentDir + FileUtility::s_pathSep + currentFile;
theGoldFile = h.generateFileName(theGoldFile, "out");
const XalanDOMString outbase = h.args.output + currentDir + FileUtility::s_pathSep + currentFile;
const XalanDOMString theOutputFile = h.generateFileName(outbase, "out");
const XSLTInputSource xslInputSource(c_wstr(theXSLFile));
const XSLTInputSource xmlInputSource(c_wstr(theXMLFile));
const XSLTResultTarget resultFile(theOutputFile);
// Parsing(compile) the XSL stylesheet and report the results..
//
const XalanCompiledStylesheet* compiledSS = 0;
xalan.compileStylesheet(xslInputSource, compiledSS);
if (compiledSS == 0 )
{
// Report the failure and be sure to increment fail count.
//
cout << "Failed to PARSE stylesheet for " << currentFile << endl;
h.data.fail += 1;
logFile.logErrorResult(currentFile, XalanDOMString("Failed to PARSE stylesheet."));
continue;
}
// Parse the Source XML based on input parameters, and then perform transform.
//
switch (h.args.source)
{
case 0:
case 1:
parseWithTransformer(h.args.source, xalan, xmlInputSource, compiledSS, resultFile, logFile, h);
break;
case 2:
parseWithXerces(xalan, xmlInputSource, compiledSS, resultFile, logFile, h);
break;
}
// Check and report results... Then delete compiled stylesheet.
//
h.checkResults(theOutputFile, theGoldFile, logFile);
xalan.destroyStylesheet(compiledSS);
}
logFile.logTestCaseClose("Done", "Pass");
}
// Check to see if -sub cmd-line directory was processed correctly.
//
if (!foundDir)
{
cout << "Specified test directory: \"" << c_str(TranscodeToLocalCodePage(h.args.sub)) << "\" not found" << endl;
}
h.reportPassFail(logFile, UniqRunid);
logFile.logTestFileClose("Conformance ", "Done");
logFile.close();
h.analyzeResults(xalan, resultsFile);
}
}
XalanTransformer::terminate();
}
catch(...)
{
cerr << "Initialization failed!!!" << endl << endl;
}
return 0;
}
<|endoftext|> |
<commit_before>/*
* Copyright 1999-2004 The Apache Software Foundation.
*
* 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.
*/
// Base header file. Must be first.
#include <xalanc/Include/PlatformDefinitions.hpp>
#if defined(XALAN_CLASSIC_IOSTREAMS)
#include <iostream.h>
#else
#include <iostream>
#endif
#include <cstdio>
XALAN_USING_STD(cerr)
XALAN_USING_STD(cout)
XALAN_USING_STD(endl)
#include "xercesc/util/PlatformUtils.hpp"
#include "xercesc/parsers/XercesDOMParser.hpp"
#include "xalanc/PlatformSupport/XalanMemoryManagerDefault.hpp"
#include "xalanc/XercesParserLiaison/XercesParserLiaison.hpp"
#include "xalanc/XercesParserLiaison/XercesDOMSupport.hpp"
#include "xalanc/XalanTransformer/XalanTransformer.hpp"
#include "xalanc/XalanTransformer/XercesDOMWrapperParsedSource.hpp"
// HARNESS HEADERS...
#include "xalanc/Harness/XalanFileUtility.hpp"
#include "xalanc/Harness/XalanDiagnosticMemoryManager.hpp"
#include "xalanc/Harness/XalanXMLFileReporter.hpp"
//#define XALAN_VQ_SPECIAL_TRACE
#if defined(XALAN_VQ_SPECIAL_TRACE)
#include "C:/Program Files/Rational/Quantify/pure.h"
#endif
// Just hoist everything...
XALAN_CPP_NAMESPACE_USE
// This is here for memory leak testing.
#if !defined(NDEBUG) && defined(_MSC_VER)
#include <crtdbg.h>
#endif
XALAN_USING_XERCES(MemoryManager)
void
setHelp(XalanFileUtility& h)
{
h.args.getHelpStream() << endl
<< "conf dir [-sub -out -gold -source (XST | XPL | DOM)]"
<< endl
<< endl
<< "dir (base directory for testcases)"
<< endl
<< "-sub dir (specific directory)"
<< endl
<< "-out dir (base directory for output)"
<< endl
<< "-gold dir (base directory for gold files)"
<< endl
<< "-src type (parsed source; XalanSourceTree(d), XercesParserLiasion, XercesDOM)"
<< endl;
}
static const char* const excludeStylesheets[] =
{
// "output22.xsl", // Excluded because it outputs EBCDIC
0
};
inline bool
checkForExclusion(
const XalanDOMString& currentFile,
MemoryManager& theMemoryManager)
{
for (size_t i = 0; excludeStylesheets[i] != 0; ++i)
{
if (currentFile == XalanDOMString(excludeStylesheets[i], theMemoryManager))
{
return true;
}
}
return false;
}
int
parseWithTransformer(
int sourceType,
XalanTransformer& xalan,
const XSLTInputSource& xmlInput,
const XalanCompiledStylesheet* styleSheet,
const XSLTResultTarget& output,
XalanXMLFileReporter& logFile,
XalanFileUtility& h)
{
const XalanParsedSource* parsedSource = 0;
MemoryManagerType& mgr = h.getMemoryManager();
int theResult = 0;
// Parse the XML source accordingly.
//
if (sourceType != 0 )
{
theResult = xalan.parseSource(xmlInput, parsedSource, true);
h.data.xmlFormat = XalanDOMString("XercesParserLiasion", mgr);
}
else
{
theResult = xalan.parseSource(xmlInput, parsedSource, false);
h.data.xmlFormat = XalanDOMString("XalanSourceTree", mgr);
}
// If the source was parsed correctly then perform the transform else report the failure.
//
if (parsedSource == 0)
{
// Report the failure and be sure to increment fail count.
//
cout << "ParseWTransformer - Failed to parse source document for " << h.data.testOrFile << endl;
++h.data.fail;
XalanDOMString tmp("Failed to parse source document. ", mgr);
tmp.append(xalan.getLastError());
logFile.logErrorResult(h.data.testOrFile, tmp );
}
else
{
theResult = xalan.transform(*parsedSource, styleSheet, output);
xalan.destroyParsedSource(parsedSource);
}
return theResult;
}
int
parseWithXerces(
XalanTransformer& xalan,
const XSLTInputSource& xmlInput,
const XalanCompiledStylesheet* styleSheet,
const XSLTResultTarget& output,
XalanXMLFileReporter& logFile,
XalanFileUtility& h)
{
XALAN_USING_XERCES(XercesDOMParser)
XALAN_USING_XERCES(DOMDocument)
MemoryManagerType& mgr = XalanMemMgrs::getDefaultXercesMemMgr();
h.data.xmlFormat = XalanDOMString("Xerces_DOM", mgr);
XercesDOMParser theParser;
theParser.setDoValidation(true);
theParser.setDoNamespaces(true);
theParser.parse(xmlInput);
DOMDocument* const theDOM = theParser.getDocument();
theDOM->normalize();
XercesDOMSupport theDOMSupport(mgr);
XercesParserLiaison theParserLiaison(mgr);
int theResult = 0;
try
{
const XercesDOMWrapperParsedSource parsedSource(
theDOM,
theParserLiaison,
theDOMSupport,
XalanDOMString(xmlInput.getSystemId(), mgr),
mgr);
theResult = xalan.transform(parsedSource, styleSheet, output);
}
catch(...)
{
// Report the failure and be sure to increment fail count.
//
cout << "parseWXerces - Failed to parse source document for " << h.data.testOrFile << endl;
++h.data.fail;
XalanDOMString resultString("Failed to parse source document. ", mgr);
resultString.append( xalan.getLastError());
logFile.logErrorResult(h.data.testOrFile, resultString);
}
return theResult;
}
int
runTests(
int argc,
char* argv[],
MemoryManager& theMemoryManager)
{
int theResult = 0;
try
{
XalanFileUtility h(theMemoryManager);
// Set the program help string, then get the command line parameters.
//
setHelp(h);
if (h.getParams(argc, argv, "CONF-RESULTS") == true)
{
XalanTransformer xalan(theMemoryManager);
// Get drive designation for final analysis and generate Unique name for results log.
//
XalanDOMString drive(theMemoryManager); // This is used to get stylesheet for final analysis
h.getDrive(drive);
const XalanDOMString resultFilePrefix("conf", theMemoryManager); // This & UniqRunid used for log file name.
XalanDOMString UniqRunid(theMemoryManager);
h.generateUniqRunid(UniqRunid);
XalanDOMString resultsFile(drive, theMemoryManager);
resultsFile += h.args.output;
resultsFile += resultFilePrefix;
resultsFile += UniqRunid;
resultsFile += XalanFileUtility::s_xmlSuffix;
// Open results log, and do some initialization of result data.
//
XalanXMLFileReporter logFile(theMemoryManager, resultsFile);
logFile.logTestFileInit("Conformance Testing:");
h.data.xmlFormat = XalanDOMString("NotSet", theMemoryManager);
// Get the list of Directories that are below conf and iterate through them
//
// Flag indicates directory found. Used in conjunction with -sub cmd-line arg.
bool foundDir = false;
typedef XalanFileUtility::FileNameVectorType FileNameVectorType;
FileNameVectorType dirs(theMemoryManager);
h.getDirectoryNames(h.args.base, dirs);
int theResult = 0;
for(FileNameVectorType::size_type j = 0;
j < dirs.size() && theResult == 0;
++j)
{
// Skip all but the specified directory if the -sub cmd-line option was used.
//
const XalanDOMString& currentDir = dirs[j];
if (length(h.args.sub) == 0 || equals(currentDir, h.args.sub) == true)
{
// Check that output directory is there.
//
XalanDOMString theOutputDir(theMemoryManager);
theOutputDir = h.args.output;
theOutputDir += currentDir;
h.checkAndCreateDir(theOutputDir);
// Indicate that directory was processed and get test files from the directory
//
foundDir = true;
FileNameVectorType files(theMemoryManager);
h.getTestFileNames(h.args.base, currentDir, true, files);
// Log directory in results log and process it's files.
//
logFile.logTestCaseInit(currentDir);
for(FileNameVectorType::size_type i = 0; i < files.size(); i++)
{
XalanXMLFileReporter::Hashtable attrs(theMemoryManager);
const XalanDOMString& currentFile = files[i];
if (checkForExclusion(currentFile, theMemoryManager))
continue;
h.data.testOrFile = currentFile;
XalanDOMString theXSLFile( h.args.base, theMemoryManager);
theXSLFile += currentDir;
theXSLFile += XalanFileUtility::s_pathSep;
theXSLFile += currentFile;
// Check and see if the .xml file exists. If not skip this .xsl file and continue.
bool fileStatus = true;
XalanDOMString theXMLFile(theMemoryManager);
h.generateFileName(theXSLFile, "xml", theXMLFile, &fileStatus);
if (!fileStatus)
continue;
h.data.xmlFileURL = theXMLFile;
h.data.xslFileURL = theXSLFile;
XalanDOMString theGoldFile(h.args.gold, theMemoryManager);
theGoldFile += currentDir;
theGoldFile += XalanFileUtility::s_pathSep;
theGoldFile += currentFile;
h.generateFileName(theGoldFile, "out", theGoldFile);
XalanDOMString outbase (h.args.output, theMemoryManager);
outbase += currentDir;
outbase += XalanFileUtility::s_pathSep;
outbase += currentFile;
XalanDOMString theOutputFile(theMemoryManager);
h.generateFileName(outbase, "out", theOutputFile);
const XSLTInputSource xslInputSource(theXSLFile, theMemoryManager);
const XSLTInputSource xmlInputSource(theXMLFile, theMemoryManager);
const XSLTResultTarget resultFile(theOutputFile, theMemoryManager);
// Parsing(compile) the XSL stylesheet and report the results..
//
const XalanCompiledStylesheet* compiledSS = 0;
xalan.compileStylesheet(xslInputSource, compiledSS);
if (compiledSS == 0 )
{
// Report the failure and be sure to increment fail count.
//
CharVectorType theVector(theMemoryManager);
TranscodeToLocalCodePage(currentFile, theVector);
cout << "Failed to parse stylesheet for "
<< theVector
<< endl;
h.data.fail += 1;
XalanDOMString tmp("Failed to parse stylesheet. ", theMemoryManager);
tmp += XalanDOMString(xalan.getLastError(), theMemoryManager);
logFile.logErrorResult(currentFile, theMemoryManager);
continue;
}
// Parse the Source XML based on input parameters, and then perform transform.
//
switch (h.args.source)
{
case 0:
case 1:
theResult = parseWithTransformer(h.args.source, xalan, xmlInputSource, compiledSS, resultFile, logFile, h);
break;
case 2:
theResult = parseWithXerces(xalan, xmlInputSource, compiledSS, resultFile, logFile, h);
break;
}
// Check and report results... Then delete compiled stylesheet.
//
h.checkResults(theOutputFile, theGoldFile, logFile);
xalan.destroyStylesheet(compiledSS);
}
logFile.logTestCaseClose("Done", "Pass");
}
}
// Check to see if -sub cmd-line directory was processed correctly.
//
if (!foundDir)
{
CharVectorType vect(theMemoryManager);
TranscodeToLocalCodePage(h.args.sub, vect);
cout << "Specified test directory: \"" << c_str(vect) << "\" not found" << endl;
}
else if (theResult != 0)
{
cout << "An unexpected tranformer error occurred. The error code is "
<< theResult
<< "\n"
<< "The error message is \""
<< xalan.getLastError()
<< endl;
}
h.reportPassFail(logFile, UniqRunid);
logFile.logTestFileClose("Conformance ", "Done");
logFile.close();
h.analyzeResults(xalan, resultsFile);
}
}
catch(const XalanDiagnosticMemoryManager::LockException&)
{
cerr << "An attempt was made to allocate memory "
"from a locked XalanDiagnosticMemoryManager "
"instance!"
<< endl
<< endl;
theResult = -1;
}
catch(...)
{
cerr << "Initialization of testing harness failed!" << endl << endl;
}
return theResult;
}
int
main(
int argc,
char* argv[])
{
#if !defined(NDEBUG) && defined(_MSC_VER)
_CrtSetDbgFlag(_CrtSetDbgFlag(_CRTDBG_REPORT_FLAG) | _CRTDBG_LEAK_CHECK_DF);
_CrtSetReportMode(_CRT_WARN, _CRTDBG_MODE_FILE);
_CrtSetReportFile(_CRT_WARN, _CRTDBG_FILE_STDERR);
#endif
#if defined(XALAN_VQ_SPECIAL_TRACE)
QuantifyStopRecordingData();
QuantifyClearData();
#endif
int theResult = 0;
try
{
XALAN_USING_XERCES(XMLPlatformUtils)
XALAN_USING_XERCES(XMLUni)
XalanMemoryManagerDefault theGlobalMemoryManager;
XalanDiagnosticMemoryManager theDiagnosticMemoryManager(theGlobalMemoryManager);
XalanMemoryManagerDefault theTestingMemoryManager;
// Call the static initializers for xerces and xalan, and create a transformer
//
XMLPlatformUtils::Initialize(
XMLUni::fgXercescDefaultLocale,
0,
0,
&theDiagnosticMemoryManager,
true);
XalanTransformer::initialize(theDiagnosticMemoryManager);
theDiagnosticMemoryManager.lock();
{
theResult = runTests(argc, argv, theTestingMemoryManager);
}
theDiagnosticMemoryManager.unlock();
XalanTransformer::terminate();
XMLPlatformUtils::Terminate();
XalanTransformer::ICUCleanUp();
}
catch(...)
{
cerr << "Initialization failed!" << endl << endl;
theResult = -1;
}
return theResult;
}
<commit_msg>Modified to use new XalanDiagnosticMemoryManager constructor arguments.<commit_after>/*
* Copyright 1999-2004 The Apache Software Foundation.
*
* 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.
*/
// Base header file. Must be first.
#include <xalanc/Include/PlatformDefinitions.hpp>
#if defined(XALAN_CLASSIC_IOSTREAMS)
#include <iostream.h>
#else
#include <iostream>
#endif
#include <cstdio>
XALAN_USING_STD(cerr)
XALAN_USING_STD(cout)
XALAN_USING_STD(endl)
#include "xercesc/util/PlatformUtils.hpp"
#include "xercesc/parsers/XercesDOMParser.hpp"
#include "xalanc/PlatformSupport/XalanMemoryManagerDefault.hpp"
#include "xalanc/XercesParserLiaison/XercesParserLiaison.hpp"
#include "xalanc/XercesParserLiaison/XercesDOMSupport.hpp"
#include "xalanc/XalanTransformer/XalanTransformer.hpp"
#include "xalanc/XalanTransformer/XercesDOMWrapperParsedSource.hpp"
// HARNESS HEADERS...
#include "xalanc/Harness/XalanFileUtility.hpp"
#include "xalanc/Harness/XalanDiagnosticMemoryManager.hpp"
#include "xalanc/Harness/XalanXMLFileReporter.hpp"
//#define XALAN_VQ_SPECIAL_TRACE
#if defined(XALAN_VQ_SPECIAL_TRACE)
#include "C:/Program Files/Rational/Quantify/pure.h"
#endif
// Just hoist everything...
XALAN_CPP_NAMESPACE_USE
// This is here for memory leak testing.
#if !defined(NDEBUG) && defined(_MSC_VER)
#include <crtdbg.h>
#endif
XALAN_USING_XERCES(MemoryManager)
void
setHelp(XalanFileUtility& h)
{
h.args.getHelpStream() << endl
<< "conf dir [-sub -out -gold -source (XST | XPL | DOM)]"
<< endl
<< endl
<< "dir (base directory for testcases)"
<< endl
<< "-sub dir (specific directory)"
<< endl
<< "-out dir (base directory for output)"
<< endl
<< "-gold dir (base directory for gold files)"
<< endl
<< "-src type (parsed source; XalanSourceTree(d), XercesParserLiasion, XercesDOM)"
<< endl;
}
static const char* const excludeStylesheets[] =
{
// "output22.xsl", // Excluded because it outputs EBCDIC
0
};
inline bool
checkForExclusion(
const XalanDOMString& currentFile,
MemoryManager& theMemoryManager)
{
for (size_t i = 0; excludeStylesheets[i] != 0; ++i)
{
if (currentFile == XalanDOMString(excludeStylesheets[i], theMemoryManager))
{
return true;
}
}
return false;
}
int
parseWithTransformer(
int sourceType,
XalanTransformer& xalan,
const XSLTInputSource& xmlInput,
const XalanCompiledStylesheet* styleSheet,
const XSLTResultTarget& output,
XalanXMLFileReporter& logFile,
XalanFileUtility& h)
{
const XalanParsedSource* parsedSource = 0;
MemoryManagerType& mgr = h.getMemoryManager();
int theResult = 0;
// Parse the XML source accordingly.
//
if (sourceType != 0 )
{
theResult = xalan.parseSource(xmlInput, parsedSource, true);
h.data.xmlFormat = XalanDOMString("XercesParserLiasion", mgr);
}
else
{
theResult = xalan.parseSource(xmlInput, parsedSource, false);
h.data.xmlFormat = XalanDOMString("XalanSourceTree", mgr);
}
// If the source was parsed correctly then perform the transform else report the failure.
//
if (parsedSource == 0)
{
// Report the failure and be sure to increment fail count.
//
cout << "ParseWTransformer - Failed to parse source document for " << h.data.testOrFile << endl;
++h.data.fail;
XalanDOMString tmp("Failed to parse source document. ", mgr);
tmp.append(xalan.getLastError());
logFile.logErrorResult(h.data.testOrFile, tmp );
}
else
{
theResult = xalan.transform(*parsedSource, styleSheet, output);
xalan.destroyParsedSource(parsedSource);
}
return theResult;
}
int
parseWithXerces(
XalanTransformer& xalan,
const XSLTInputSource& xmlInput,
const XalanCompiledStylesheet* styleSheet,
const XSLTResultTarget& output,
XalanXMLFileReporter& logFile,
XalanFileUtility& h)
{
XALAN_USING_XERCES(XercesDOMParser)
XALAN_USING_XERCES(DOMDocument)
MemoryManagerType& mgr = XalanMemMgrs::getDefaultXercesMemMgr();
h.data.xmlFormat = XalanDOMString("Xerces_DOM", mgr);
XercesDOMParser theParser;
theParser.setDoValidation(true);
theParser.setDoNamespaces(true);
theParser.parse(xmlInput);
DOMDocument* const theDOM = theParser.getDocument();
theDOM->normalize();
XercesDOMSupport theDOMSupport(mgr);
XercesParserLiaison theParserLiaison(mgr);
int theResult = 0;
try
{
const XercesDOMWrapperParsedSource parsedSource(
theDOM,
theParserLiaison,
theDOMSupport,
XalanDOMString(xmlInput.getSystemId(), mgr),
mgr);
theResult = xalan.transform(parsedSource, styleSheet, output);
}
catch(...)
{
// Report the failure and be sure to increment fail count.
//
cout << "parseWXerces - Failed to parse source document for " << h.data.testOrFile << endl;
++h.data.fail;
XalanDOMString resultString("Failed to parse source document. ", mgr);
resultString.append( xalan.getLastError());
logFile.logErrorResult(h.data.testOrFile, resultString);
}
return theResult;
}
int
runTests(
int argc,
char* argv[],
MemoryManager& theMemoryManager)
{
int theResult = 0;
try
{
XalanFileUtility h(theMemoryManager);
// Set the program help string, then get the command line parameters.
//
setHelp(h);
if (h.getParams(argc, argv, "CONF-RESULTS") == true)
{
XalanTransformer xalan(theMemoryManager);
// Get drive designation for final analysis and generate Unique name for results log.
//
XalanDOMString drive(theMemoryManager); // This is used to get stylesheet for final analysis
h.getDrive(drive);
const XalanDOMString resultFilePrefix("conf", theMemoryManager); // This & UniqRunid used for log file name.
XalanDOMString UniqRunid(theMemoryManager);
h.generateUniqRunid(UniqRunid);
XalanDOMString resultsFile(drive, theMemoryManager);
resultsFile += h.args.output;
resultsFile += resultFilePrefix;
resultsFile += UniqRunid;
resultsFile += XalanFileUtility::s_xmlSuffix;
// Open results log, and do some initialization of result data.
//
XalanXMLFileReporter logFile(theMemoryManager, resultsFile);
logFile.logTestFileInit("Conformance Testing:");
h.data.xmlFormat = XalanDOMString("NotSet", theMemoryManager);
// Get the list of Directories that are below conf and iterate through them
//
// Flag indicates directory found. Used in conjunction with -sub cmd-line arg.
bool foundDir = false;
typedef XalanFileUtility::FileNameVectorType FileNameVectorType;
FileNameVectorType dirs(theMemoryManager);
h.getDirectoryNames(h.args.base, dirs);
int theResult = 0;
for(FileNameVectorType::size_type j = 0;
j < dirs.size() && theResult == 0;
++j)
{
// Skip all but the specified directory if the -sub cmd-line option was used.
//
const XalanDOMString& currentDir = dirs[j];
if (length(h.args.sub) == 0 || equals(currentDir, h.args.sub) == true)
{
// Check that output directory is there.
//
XalanDOMString theOutputDir(theMemoryManager);
theOutputDir = h.args.output;
theOutputDir += currentDir;
h.checkAndCreateDir(theOutputDir);
// Indicate that directory was processed and get test files from the directory
//
foundDir = true;
FileNameVectorType files(theMemoryManager);
h.getTestFileNames(h.args.base, currentDir, true, files);
// Log directory in results log and process it's files.
//
logFile.logTestCaseInit(currentDir);
for(FileNameVectorType::size_type i = 0; i < files.size(); i++)
{
XalanXMLFileReporter::Hashtable attrs(theMemoryManager);
const XalanDOMString& currentFile = files[i];
if (checkForExclusion(currentFile, theMemoryManager))
continue;
h.data.testOrFile = currentFile;
XalanDOMString theXSLFile( h.args.base, theMemoryManager);
theXSLFile += currentDir;
theXSLFile += XalanFileUtility::s_pathSep;
theXSLFile += currentFile;
// Check and see if the .xml file exists. If not skip this .xsl file and continue.
bool fileStatus = true;
XalanDOMString theXMLFile(theMemoryManager);
h.generateFileName(theXSLFile, "xml", theXMLFile, &fileStatus);
if (!fileStatus)
continue;
h.data.xmlFileURL = theXMLFile;
h.data.xslFileURL = theXSLFile;
XalanDOMString theGoldFile(h.args.gold, theMemoryManager);
theGoldFile += currentDir;
theGoldFile += XalanFileUtility::s_pathSep;
theGoldFile += currentFile;
h.generateFileName(theGoldFile, "out", theGoldFile);
XalanDOMString outbase (h.args.output, theMemoryManager);
outbase += currentDir;
outbase += XalanFileUtility::s_pathSep;
outbase += currentFile;
XalanDOMString theOutputFile(theMemoryManager);
h.generateFileName(outbase, "out", theOutputFile);
const XSLTInputSource xslInputSource(theXSLFile, theMemoryManager);
const XSLTInputSource xmlInputSource(theXMLFile, theMemoryManager);
const XSLTResultTarget resultFile(theOutputFile, theMemoryManager);
// Parsing(compile) the XSL stylesheet and report the results..
//
const XalanCompiledStylesheet* compiledSS = 0;
xalan.compileStylesheet(xslInputSource, compiledSS);
if (compiledSS == 0 )
{
// Report the failure and be sure to increment fail count.
//
CharVectorType theVector(theMemoryManager);
TranscodeToLocalCodePage(currentFile, theVector);
cout << "Failed to parse stylesheet for "
<< theVector
<< endl;
h.data.fail += 1;
XalanDOMString tmp("Failed to parse stylesheet. ", theMemoryManager);
tmp += XalanDOMString(xalan.getLastError(), theMemoryManager);
logFile.logErrorResult(currentFile, theMemoryManager);
continue;
}
// Parse the Source XML based on input parameters, and then perform transform.
//
switch (h.args.source)
{
case 0:
case 1:
theResult = parseWithTransformer(h.args.source, xalan, xmlInputSource, compiledSS, resultFile, logFile, h);
break;
case 2:
theResult = parseWithXerces(xalan, xmlInputSource, compiledSS, resultFile, logFile, h);
break;
}
// Check and report results... Then delete compiled stylesheet.
//
h.checkResults(theOutputFile, theGoldFile, logFile);
xalan.destroyStylesheet(compiledSS);
}
logFile.logTestCaseClose("Done", "Pass");
}
}
// Check to see if -sub cmd-line directory was processed correctly.
//
if (!foundDir)
{
CharVectorType vect(theMemoryManager);
TranscodeToLocalCodePage(h.args.sub, vect);
cout << "Specified test directory: \"" << c_str(vect) << "\" not found" << endl;
}
else if (theResult != 0)
{
cout << "An unexpected tranformer error occurred. The error code is "
<< theResult
<< "\n"
<< "The error message is \""
<< xalan.getLastError()
<< endl;
}
h.reportPassFail(logFile, UniqRunid);
logFile.logTestFileClose("Conformance ", "Done");
logFile.close();
h.analyzeResults(xalan, resultsFile);
}
}
catch(const XalanDiagnosticMemoryManager::LockException&)
{
cerr << "An attempt was made to allocate memory "
"from a locked XalanDiagnosticMemoryManager "
"instance!"
<< endl
<< endl;
theResult = -1;
}
catch(...)
{
cerr << "Initialization of testing harness failed!" << endl << endl;
}
return theResult;
}
int
main(
int argc,
char* argv[])
{
#if !defined(NDEBUG) && defined(_MSC_VER)
_CrtSetDbgFlag(_CrtSetDbgFlag(_CRTDBG_REPORT_FLAG) | _CRTDBG_LEAK_CHECK_DF);
_CrtSetReportMode(_CRT_WARN, _CRTDBG_MODE_FILE);
_CrtSetReportFile(_CRT_WARN, _CRTDBG_FILE_STDERR);
#endif
#if defined(XALAN_VQ_SPECIAL_TRACE)
QuantifyStopRecordingData();
QuantifyClearData();
#endif
int theResult = 0;
try
{
XALAN_USING_XERCES(XMLPlatformUtils)
XALAN_USING_XERCES(XMLUni)
XalanMemoryManagerDefault theGlobalMemoryManager;
XalanDiagnosticMemoryManager theDiagnosticMemoryManager(theGlobalMemoryManager, true, &cerr);
XalanMemoryManagerDefault theTestingMemoryManager;
// Call the static initializers for xerces and xalan, and create a transformer
//
XMLPlatformUtils::Initialize(
XMLUni::fgXercescDefaultLocale,
0,
0,
&theDiagnosticMemoryManager,
true);
XalanTransformer::initialize(theDiagnosticMemoryManager);
theDiagnosticMemoryManager.lock();
{
theResult = runTests(argc, argv, theTestingMemoryManager);
}
theDiagnosticMemoryManager.unlock();
XalanTransformer::terminate();
XMLPlatformUtils::Terminate();
XalanTransformer::ICUCleanUp();
}
catch(...)
{
cerr << "Initialization failed!" << endl << endl;
theResult = -1;
}
return theResult;
}
<|endoftext|> |
<commit_before>
/*
* Copyright (c) 2012 Karl N. Redgate
*
* 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.
*/
/** \file TCL_Interface.cc
* \brief
*
*/
#include <stdint.h>
#include <stdlib.h> // for exit()
#include "logger.h"
#include "PlatformInterface.h"
#include "Interface.h"
#include "tcl_util.h"
#include "AppInit.h"
/**
*/
static int
Interface_obj( ClientData data, Tcl_Interp *interp,
int objc, Tcl_Obj * CONST *objv )
{
using namespace Network;
Interface *interface = (Interface *)data;
if ( objc == 1 ) {
Tcl_SetObjResult( interp, Tcl_NewLongObj((long)(interface)) );
return TCL_OK;
}
char *command = Tcl_GetStringFromObj( objv[1], NULL );
if ( Tcl_StringMatch(command, "type") ) {
Tcl_StaticSetResult( interp, "Network::Interface" );
return TCL_OK;
}
if ( Tcl_StringMatch(command, "create") ) {
const char *result = NULL; // interface->create();
if ( result == NULL ) {
Tcl_ResetResult( interp );
return TCL_OK;
}
Tcl_SetResult( interp, (char *)result, TCL_STATIC );
return TCL_ERROR;
}
/**
*/
if ( Tcl_StringMatch(command, "rename") ) {
if ( objc != 3 ) {
Tcl_ResetResult( interp );
Tcl_WrongNumArgs( interp, 1, objv, "rename new_name" );
return TCL_ERROR;
}
char *newname = Tcl_GetStringFromObj( objv[2], NULL );
bool result = interface->rename( newname );
Tcl_SetObjResult( interp, Tcl_NewBooleanObj(result) );
return TCL_ERROR;
}
/**
*/
if ( Tcl_StringMatch(command, "negotiate") ) {
bool result = interface->negotiate();
Tcl_SetObjResult( interp, Tcl_NewBooleanObj(result) );
if ( result ) return TCL_OK;
return TCL_ERROR;
}
/**
*/
if ( Tcl_StringMatch(command, "destroy") ) {
const char *result = NULL; // interface->destroy();
if ( result == NULL ) {
Tcl_ResetResult( interp );
return TCL_OK;
}
Tcl_SetResult( interp, (char *)result, TCL_STATIC );
return TCL_ERROR;
}
/**
*/
if ( Tcl_StringMatch(command, "primary_address") ) {
struct in6_addr primary_address;
interface->lladdr( &primary_address );
char buffer[80];
const char *llname = inet_ntop( AF_INET6, &primary_address, buffer, sizeof(buffer) );
Tcl_SetResult( interp, (char *)llname, TCL_VOLATILE );
return TCL_OK;
}
Tcl_StaticSetResult( interp, "Unknown command for Interface object" );
return TCL_ERROR;
}
/**
*/
static void
Interface_delete( ClientData data ) {
using namespace Network;
Interface *message = (Interface *)data;
delete message;
}
/**
*/
static int
Interface_cmd( ClientData data, Tcl_Interp *interp,
int objc, Tcl_Obj * CONST *objv )
{
if ( objc != 2 ) {
Tcl_ResetResult( interp );
Tcl_WrongNumArgs( interp, 1, objv, "name" );
return TCL_ERROR;
}
char *name = Tcl_GetStringFromObj( objv[1], NULL );
using namespace Network;
//
// Interface *object = new Interface( name );
//
// maybe want there to be a constructor that looks up the interface by name?
//
Interface *object = new Interface( interp, name );
Tcl_CreateObjCommand( interp, name, Interface_obj, (ClientData)object, Interface_delete );
Tcl_SetResult( interp, name, TCL_VOLATILE );
return TCL_OK;
}
/**
*/
bool NetworkInterface_Module( Tcl_Interp *interp ) {
Tcl_Command command;
Tcl_Namespace *ns = Tcl_CreateNamespace(interp, "Network::Interface", (ClientData)0, NULL);
if ( ns == NULL ) {
return false;
}
if ( Tcl_LinkVar(interp, "Network::Interface::debug", (char *)&debug, TCL_LINK_INT) != TCL_OK ) {
log_err( "failed to link Network::Interface::debug" );
_exit( 1 );
}
if ( Tcl_LinkVar(interp, "link_bounce_interval", (char *)&link_bounce_interval, TCL_LINK_INT) != TCL_OK ) {
log_err( "failed to link Network::Interface::link_bounce_interval" );
exit( 1 );
}
if ( Tcl_LinkVar(interp, "link_bounce_attempts", (char *)&link_bounce_attempts, TCL_LINK_INT) != TCL_OK ) {
log_err( "failed to link Network::Interface::link_bounce_attempts" );
exit( 1 );
}
if ( Tcl_LinkVar(interp, "link_bounce_reattempt", (char *)&link_bounce_reattempt, TCL_LINK_INT) != TCL_OK ) {
log_err( "failed to link Network::Interface::link_bounce_reattempt" );
exit( 1 );
}
command = Tcl_CreateObjCommand(interp, "Network::Interface::new", Interface_cmd, (ClientData)0, NULL);
if ( command == NULL ) {
// logger ?? want to report TCL Error
return false;
}
// Create a namespace for the platform configuration of interface names
ns = Tcl_CreateNamespace(interp, "interface", (ClientData)0, NULL);
if ( ns == NULL ) {
return false;
}
char *script =
"namespace eval interface { array set name {} }\n"
"proc interface {config} {\n"
" namespace eval interface $config\n"
"}\n";
int retcode = Tcl_EvalEx( interp, script, -1, TCL_EVAL_GLOBAL );
if ( retcode != TCL_OK ) return false;
return true;
}
app_init( NetworkInterface_Module );
/* vim: set autoindent expandtab sw=4 : */
<commit_msg>fix compile errs<commit_after>
/*
* Copyright (c) 2012 Karl N. Redgate
*
* 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.
*/
/** \file TCL_Interface.cc
* \brief
*
*/
#include <stdint.h>
#include <stdlib.h> // for exit()
#include <arpa/inet.h> // for inet_ntop()
#include "logger.h"
#include "PlatformInterface.h"
#include "Interface.h"
#include "tcl_util.h"
#include "AppInit.h"
// Need a way to connect the real vars to the TCL implementation
// without the TCL interfaces present in the real interface
namespace {
int debug = 0;
// These may not really be necessary anymore
int link_bounce_interval = 1200;
int link_bounce_attempts = 2;
int link_bounce_reattempt = 1200; // 1 hour total
}
/**
*/
static int
Interface_obj( ClientData data, Tcl_Interp *interp,
int objc, Tcl_Obj * CONST *objv )
{
using namespace Network;
Interface *interface = (Interface *)data;
if ( objc == 1 ) {
Tcl_SetObjResult( interp, Tcl_NewLongObj((long)(interface)) );
return TCL_OK;
}
char *command = Tcl_GetStringFromObj( objv[1], NULL );
if ( Tcl_StringMatch(command, "type") ) {
Tcl_StaticSetResult( interp, "Network::Interface" );
return TCL_OK;
}
if ( Tcl_StringMatch(command, "create") ) {
const char *result = NULL; // interface->create();
if ( result == NULL ) {
Tcl_ResetResult( interp );
return TCL_OK;
}
Tcl_SetResult( interp, (char *)result, TCL_STATIC );
return TCL_ERROR;
}
/**
*/
if ( Tcl_StringMatch(command, "rename") ) {
if ( objc != 3 ) {
Tcl_ResetResult( interp );
Tcl_WrongNumArgs( interp, 1, objv, "rename new_name" );
return TCL_ERROR;
}
char *newname = Tcl_GetStringFromObj( objv[2], NULL );
bool result = interface->rename( newname );
Tcl_SetObjResult( interp, Tcl_NewBooleanObj(result) );
return TCL_ERROR;
}
/**
*/
if ( Tcl_StringMatch(command, "negotiate") ) {
bool result = interface->negotiate();
Tcl_SetObjResult( interp, Tcl_NewBooleanObj(result) );
if ( result ) return TCL_OK;
return TCL_ERROR;
}
/**
*/
if ( Tcl_StringMatch(command, "destroy") ) {
const char *result = NULL; // interface->destroy();
if ( result == NULL ) {
Tcl_ResetResult( interp );
return TCL_OK;
}
Tcl_SetResult( interp, (char *)result, TCL_STATIC );
return TCL_ERROR;
}
/**
*/
if ( Tcl_StringMatch(command, "primary_address") ) {
struct in6_addr primary_address;
interface->lladdr( &primary_address );
char buffer[80];
const char *llname = inet_ntop( AF_INET6, &primary_address, buffer, sizeof(buffer) );
Tcl_SetResult( interp, (char *)llname, TCL_VOLATILE );
return TCL_OK;
}
Tcl_StaticSetResult( interp, "Unknown command for Interface object" );
return TCL_ERROR;
}
/**
*/
static void
Interface_delete( ClientData data ) {
using namespace Network;
Interface *message = (Interface *)data;
delete message;
}
/**
*/
static int
Interface_cmd( ClientData data, Tcl_Interp *interp,
int objc, Tcl_Obj * CONST *objv )
{
if ( objc != 2 ) {
Tcl_ResetResult( interp );
Tcl_WrongNumArgs( interp, 1, objv, "name" );
return TCL_ERROR;
}
char *name = Tcl_GetStringFromObj( objv[1], NULL );
using namespace Network;
//
// Interface *object = new Interface( name );
//
// maybe want there to be a constructor that looks up the interface by name?
//
Interface *object = new Interface( interp, name );
Tcl_CreateObjCommand( interp, name, Interface_obj, (ClientData)object, Interface_delete );
Tcl_SetResult( interp, name, TCL_VOLATILE );
return TCL_OK;
}
/**
*/
bool NetworkInterface_Module( Tcl_Interp *interp ) {
Tcl_Command command;
Tcl_Namespace *ns = Tcl_CreateNamespace(interp, "Network::Interface", (ClientData)0, NULL);
if ( ns == NULL ) {
return false;
}
if ( Tcl_LinkVar(interp, "Network::Interface::debug", (char *)&debug, TCL_LINK_INT) != TCL_OK ) {
log_err( "failed to link Network::Interface::debug" );
_exit( 1 );
}
if ( Tcl_LinkVar(interp, "link_bounce_interval", (char *)&link_bounce_interval, TCL_LINK_INT) != TCL_OK ) {
log_err( "failed to link Network::Interface::link_bounce_interval" );
exit( 1 );
}
if ( Tcl_LinkVar(interp, "link_bounce_attempts", (char *)&link_bounce_attempts, TCL_LINK_INT) != TCL_OK ) {
log_err( "failed to link Network::Interface::link_bounce_attempts" );
exit( 1 );
}
if ( Tcl_LinkVar(interp, "link_bounce_reattempt", (char *)&link_bounce_reattempt, TCL_LINK_INT) != TCL_OK ) {
log_err( "failed to link Network::Interface::link_bounce_reattempt" );
exit( 1 );
}
command = Tcl_CreateObjCommand(interp, "Network::Interface::new", Interface_cmd, (ClientData)0, NULL);
if ( command == NULL ) {
// logger ?? want to report TCL Error
return false;
}
// Create a namespace for the platform configuration of interface names
ns = Tcl_CreateNamespace(interp, "interface", (ClientData)0, NULL);
if ( ns == NULL ) {
return false;
}
const char *script =
"namespace eval interface { array set name {} }\n"
"proc interface {config} {\n"
" namespace eval interface $config\n"
"}\n";
int retcode = Tcl_EvalEx( interp, script, -1, TCL_EVAL_GLOBAL );
if ( retcode != TCL_OK ) return false;
return true;
}
app_init( NetworkInterface_Module );
/* vim: set autoindent expandtab sw=4 : */
<|endoftext|> |
<commit_before>/*****************************************************************************
* crossbar.c : DirectShow access module for vlc
*****************************************************************************
* Copyright (C) 2002 VideoLAN
* $Id$
*
* Author: Damien Fouilleul <damien dot fouilleul at laposte dot net>
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU 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 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., 59 Temple Place - Suite 330, Boston, MA 02111, USA.
*****************************************************************************/
/*****************************************************************************
* Preamble
*****************************************************************************/
#include <stdlib.h>
#include <stdio.h>
#include <string.h>
#include <vlc/vlc.h>
#include <vlc/input.h>
#include <vlc/vout.h>
#include "common.h"
/*****************************************************************************
* DeleteCrossbarRoutes
*****************************************************************************/
void DeleteCrossbarRoutes( access_sys_t *p_sys )
{
/* Remove crossbar filters from graph */
for( int i = 0; i < p_sys->i_crossbar_route_depth; i++ )
{
p_sys->crossbar_routes[i].pXbar->Release();
}
p_sys->i_crossbar_route_depth = 0;
}
/*****************************************************************************
* RouteCrossbars (Does not AddRef the returned *Pin)
*****************************************************************************/
static HRESULT GetCrossbarIPinAtIndex( IAMCrossbar *pXbar, LONG PinIndex,
BOOL IsInputPin, IPin ** ppPin )
{
LONG cntInPins, cntOutPins;
IPin *pP = 0;
IBaseFilter *pFilter = NULL;
IEnumPins *pins=0;
ULONG n;
if( !pXbar || !ppPin ) return E_POINTER;
*ppPin = 0;
if( S_OK != pXbar->get_PinCounts(&cntOutPins, &cntInPins) ) return E_FAIL;
LONG TrueIndex = IsInputPin ? PinIndex : PinIndex + cntInPins;
if( pXbar->QueryInterface(IID_IBaseFilter, (void **)&pFilter) == S_OK )
{
if( SUCCEEDED(pFilter->EnumPins(&pins)) )
{
LONG i = 0;
while( pins->Next(1, &pP, &n) == S_OK )
{
pP->Release();
if( i == TrueIndex )
{
*ppPin = pP;
break;
}
i++;
}
pins->Release();
}
pFilter->Release();
}
return *ppPin ? S_OK : E_FAIL;
}
/*****************************************************************************
* GetCrossbarIndexFromIPin: Find corresponding index of an IPin on a crossbar
*****************************************************************************/
static HRESULT GetCrossbarIndexFromIPin( IAMCrossbar * pXbar, LONG * PinIndex,
BOOL IsInputPin, IPin * pPin )
{
LONG cntInPins, cntOutPins;
IPin *pP = 0;
IBaseFilter *pFilter = NULL;
IEnumPins *pins = 0;
ULONG n;
BOOL fOK = FALSE;
if(!pXbar || !PinIndex || !pPin )
return E_POINTER;
if( S_OK != pXbar->get_PinCounts(&cntOutPins, &cntInPins) )
return E_FAIL;
if( pXbar->QueryInterface(IID_IBaseFilter, (void **)&pFilter) == S_OK )
{
if( SUCCEEDED(pFilter->EnumPins(&pins)) )
{
LONG i=0;
while( pins->Next(1, &pP, &n) == S_OK )
{
pP->Release();
if( pPin == pP )
{
*PinIndex = IsInputPin ? i : i - cntInPins;
fOK = TRUE;
break;
}
i++;
}
pins->Release();
}
pFilter->Release();
}
return fOK ? S_OK : E_FAIL;
}
/*****************************************************************************
* FindCrossbarRoutes
*****************************************************************************/
HRESULT FindCrossbarRoutes( vlc_object_t *p_this, access_sys_t *p_sys,
IPin *p_input_pin, LONG physicalType, int depth )
{
HRESULT result = S_FALSE;
IPin *p_output_pin;
if( FAILED(p_input_pin->ConnectedTo(&p_output_pin)) ) return S_FALSE;
// It is connected, so now find out if the filter supports IAMCrossbar
PIN_INFO pinInfo;
if( FAILED(p_output_pin->QueryPinInfo(&pinInfo)) ||
PINDIR_OUTPUT != pinInfo.dir )
{
p_output_pin->Release ();
return S_FALSE;
}
IAMCrossbar *pXbar=0;
if( FAILED(pinInfo.pFilter->QueryInterface(IID_IAMCrossbar,
(void **)&pXbar)) )
{
pinInfo.pFilter->Release();
p_output_pin->Release ();
return S_FALSE;
}
LONG inputPinCount, outputPinCount;
if( FAILED(pXbar->get_PinCounts(&outputPinCount, &inputPinCount)) )
{
pXbar->Release();
pinInfo.pFilter->Release();
p_output_pin->Release ();
return S_FALSE;
}
LONG inputPinIndexRelated, outputPinIndexRelated;
LONG inputPinPhysicalType, outputPinPhysicalType;
LONG inputPinIndex, outputPinIndex;
if( FAILED(GetCrossbarIndexFromIPin( pXbar, &outputPinIndex,
FALSE, p_output_pin )) ||
FAILED(pXbar->get_CrossbarPinInfo( FALSE, outputPinIndex,
&outputPinIndexRelated,
&outputPinPhysicalType )) )
{
pXbar->Release();
pinInfo.pFilter->Release();
p_output_pin->Release ();
return S_FALSE;
}
//
// for all input pins
//
for( inputPinIndex = 0; S_OK != result && inputPinIndex < inputPinCount;
inputPinIndex++ )
{
if( FAILED(pXbar->get_CrossbarPinInfo( TRUE, inputPinIndex,
&inputPinIndexRelated, &inputPinPhysicalType )) ) continue;
// Is the pin a video pin?
if( inputPinPhysicalType != physicalType ) continue;
// Can we route it?
if( FAILED(pXbar->CanRoute(outputPinIndex, inputPinIndex)) ) continue;
IPin *pPin;
if( FAILED(GetCrossbarIPinAtIndex( pXbar, inputPinIndex,
TRUE, &pPin)) ) continue;
result = FindCrossbarRoutes( p_this, p_sys, pPin,
physicalType, depth+1 );
if( S_OK == result || (S_FALSE == result &&
physicalType == inputPinPhysicalType &&
(p_sys->i_crossbar_route_depth = depth+1) < MAX_CROSSBAR_DEPTH) )
{
// hold on crossbar
pXbar->AddRef();
// remember crossbar route
p_sys->crossbar_routes[depth].pXbar = pXbar;
p_sys->crossbar_routes[depth].VideoInputIndex = inputPinIndex;
p_sys->crossbar_routes[depth].VideoOutputIndex = outputPinIndex;
p_sys->crossbar_routes[depth].AudioInputIndex = inputPinIndexRelated;
p_sys->crossbar_routes[depth].AudioOutputIndex = outputPinIndexRelated;
msg_Dbg( p_this, "Crossbar at depth %d, Found Route For "
"ouput %ld (type %ld) to input %ld (type %ld)", depth,
outputPinIndex, outputPinPhysicalType, inputPinIndex,
inputPinPhysicalType );
result = S_OK;
}
}
pXbar->Release();
pinInfo.pFilter->Release();
p_output_pin->Release ();
return result;
}
<commit_msg>* modules/access/dshow/crossbar.cpp: compilation fix.<commit_after>/*****************************************************************************
* crossbar.c : DirectShow access module for vlc
*****************************************************************************
* Copyright (C) 2002 VideoLAN
* $Id$
*
* Author: Damien Fouilleul <damien dot fouilleul at laposte dot net>
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU 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 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., 59 Temple Place - Suite 330, Boston, MA 02111, USA.
*****************************************************************************/
/*****************************************************************************
* Preamble
*****************************************************************************/
#include <stdlib.h>
#include <stdio.h>
#include <string.h>
#include <vlc/vlc.h>
#include <vlc/input.h>
#include <vlc/vout.h>
#ifndef _MSC_VER
/* Work-around a bug in w32api-2.5 */
# define QACONTAINERFLAGS QACONTAINERFLAGS_SOMETHINGELSE
#endif
#include "common.h"
/*****************************************************************************
* DeleteCrossbarRoutes
*****************************************************************************/
void DeleteCrossbarRoutes( access_sys_t *p_sys )
{
/* Remove crossbar filters from graph */
for( int i = 0; i < p_sys->i_crossbar_route_depth; i++ )
{
p_sys->crossbar_routes[i].pXbar->Release();
}
p_sys->i_crossbar_route_depth = 0;
}
/*****************************************************************************
* RouteCrossbars (Does not AddRef the returned *Pin)
*****************************************************************************/
static HRESULT GetCrossbarIPinAtIndex( IAMCrossbar *pXbar, LONG PinIndex,
BOOL IsInputPin, IPin ** ppPin )
{
LONG cntInPins, cntOutPins;
IPin *pP = 0;
IBaseFilter *pFilter = NULL;
IEnumPins *pins=0;
ULONG n;
if( !pXbar || !ppPin ) return E_POINTER;
*ppPin = 0;
if( S_OK != pXbar->get_PinCounts(&cntOutPins, &cntInPins) ) return E_FAIL;
LONG TrueIndex = IsInputPin ? PinIndex : PinIndex + cntInPins;
if( pXbar->QueryInterface(IID_IBaseFilter, (void **)&pFilter) == S_OK )
{
if( SUCCEEDED(pFilter->EnumPins(&pins)) )
{
LONG i = 0;
while( pins->Next(1, &pP, &n) == S_OK )
{
pP->Release();
if( i == TrueIndex )
{
*ppPin = pP;
break;
}
i++;
}
pins->Release();
}
pFilter->Release();
}
return *ppPin ? S_OK : E_FAIL;
}
/*****************************************************************************
* GetCrossbarIndexFromIPin: Find corresponding index of an IPin on a crossbar
*****************************************************************************/
static HRESULT GetCrossbarIndexFromIPin( IAMCrossbar * pXbar, LONG * PinIndex,
BOOL IsInputPin, IPin * pPin )
{
LONG cntInPins, cntOutPins;
IPin *pP = 0;
IBaseFilter *pFilter = NULL;
IEnumPins *pins = 0;
ULONG n;
BOOL fOK = FALSE;
if(!pXbar || !PinIndex || !pPin )
return E_POINTER;
if( S_OK != pXbar->get_PinCounts(&cntOutPins, &cntInPins) )
return E_FAIL;
if( pXbar->QueryInterface(IID_IBaseFilter, (void **)&pFilter) == S_OK )
{
if( SUCCEEDED(pFilter->EnumPins(&pins)) )
{
LONG i=0;
while( pins->Next(1, &pP, &n) == S_OK )
{
pP->Release();
if( pPin == pP )
{
*PinIndex = IsInputPin ? i : i - cntInPins;
fOK = TRUE;
break;
}
i++;
}
pins->Release();
}
pFilter->Release();
}
return fOK ? S_OK : E_FAIL;
}
/*****************************************************************************
* FindCrossbarRoutes
*****************************************************************************/
HRESULT FindCrossbarRoutes( vlc_object_t *p_this, access_sys_t *p_sys,
IPin *p_input_pin, LONG physicalType, int depth )
{
HRESULT result = S_FALSE;
IPin *p_output_pin;
if( FAILED(p_input_pin->ConnectedTo(&p_output_pin)) ) return S_FALSE;
// It is connected, so now find out if the filter supports IAMCrossbar
PIN_INFO pinInfo;
if( FAILED(p_output_pin->QueryPinInfo(&pinInfo)) ||
PINDIR_OUTPUT != pinInfo.dir )
{
p_output_pin->Release ();
return S_FALSE;
}
IAMCrossbar *pXbar=0;
if( FAILED(pinInfo.pFilter->QueryInterface(IID_IAMCrossbar,
(void **)&pXbar)) )
{
pinInfo.pFilter->Release();
p_output_pin->Release ();
return S_FALSE;
}
LONG inputPinCount, outputPinCount;
if( FAILED(pXbar->get_PinCounts(&outputPinCount, &inputPinCount)) )
{
pXbar->Release();
pinInfo.pFilter->Release();
p_output_pin->Release ();
return S_FALSE;
}
LONG inputPinIndexRelated, outputPinIndexRelated;
LONG inputPinPhysicalType, outputPinPhysicalType;
LONG inputPinIndex, outputPinIndex;
if( FAILED(GetCrossbarIndexFromIPin( pXbar, &outputPinIndex,
FALSE, p_output_pin )) ||
FAILED(pXbar->get_CrossbarPinInfo( FALSE, outputPinIndex,
&outputPinIndexRelated,
&outputPinPhysicalType )) )
{
pXbar->Release();
pinInfo.pFilter->Release();
p_output_pin->Release ();
return S_FALSE;
}
//
// for all input pins
//
for( inputPinIndex = 0; S_OK != result && inputPinIndex < inputPinCount;
inputPinIndex++ )
{
if( FAILED(pXbar->get_CrossbarPinInfo( TRUE, inputPinIndex,
&inputPinIndexRelated, &inputPinPhysicalType )) ) continue;
// Is the pin a video pin?
if( inputPinPhysicalType != physicalType ) continue;
// Can we route it?
if( FAILED(pXbar->CanRoute(outputPinIndex, inputPinIndex)) ) continue;
IPin *pPin;
if( FAILED(GetCrossbarIPinAtIndex( pXbar, inputPinIndex,
TRUE, &pPin)) ) continue;
result = FindCrossbarRoutes( p_this, p_sys, pPin,
physicalType, depth+1 );
if( S_OK == result || (S_FALSE == result &&
physicalType == inputPinPhysicalType &&
(p_sys->i_crossbar_route_depth = depth+1) < MAX_CROSSBAR_DEPTH) )
{
// hold on crossbar
pXbar->AddRef();
// remember crossbar route
p_sys->crossbar_routes[depth].pXbar = pXbar;
p_sys->crossbar_routes[depth].VideoInputIndex = inputPinIndex;
p_sys->crossbar_routes[depth].VideoOutputIndex = outputPinIndex;
p_sys->crossbar_routes[depth].AudioInputIndex = inputPinIndexRelated;
p_sys->crossbar_routes[depth].AudioOutputIndex = outputPinIndexRelated;
msg_Dbg( p_this, "Crossbar at depth %d, Found Route For "
"ouput %ld (type %ld) to input %ld (type %ld)", depth,
outputPinIndex, outputPinPhysicalType, inputPinIndex,
inputPinPhysicalType );
result = S_OK;
}
}
pXbar->Release();
pinInfo.pFilter->Release();
p_output_pin->Release ();
return result;
}
<|endoftext|> |
<commit_before>/* -*- Mode: C++; tab-width: 2; indent-tabs-mode: nil; c-basic-offset: 2 -*-
*
* XPLC - Cross-Platform Lightweight Components
* Copyright (C) 2000, Pierre Phaneuf
*
* 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; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA
* 02111-1307, USA.
*/
#include <stdlib.h>
#include "servmgr.h"
IObject* ServiceManager::getInterface(const UUID& uuid) {
do {
if(uuid.equals(IObject::IID))
break;
if(uuid.equals(IServiceManager::IID))
break;
return NULL;
} while(0);
addRef();
return this;
}
void ServiceManager::addObject(const UUID& aUuid, IObject* aObj) {
ObjectNode* node;
node = objects;
while(node) {
if(node->uuid.equals(aUuid))
break;
node = node->next;
}
/*
* FIXME: maybe add a "replace" bool parameter? Or would this
* encourage UUID hijacking too much?
*/
if(node)
return;
node = new ObjectNode(aUuid, aObj, objects);
objects = node;
}
void ServiceManager::removeObject(const UUID& aUuid) {
ObjectNode* node;
ObjectNode** ptr;
node = objects;
ptr = &objects;
while(node) {
if(node->uuid.equals(aUuid)) {
*ptr = node->next;
delete node;
break;
}
ptr = &node->next;
node = *ptr;
}
}
IObject* ServiceManager::getObject(const UUID& aUuid) {
ObjectNode* obj;
/*
* We look through the objects listand return if we find a match.
*/
obj = objects;
while(obj) {
if(obj->uuid.equals(aUuid)) {
obj->obj->addRef();
return obj->obj;
}
obj = obj->next;
}
/*
* No match was found, we return empty-handed.
*/
return NULL;
}
void ServiceManager::shutdown() {
ObjectNode* node;
ObjectNode* ptr;
node = objects;
while(node) {
ptr = node;
node = node->next;
delete ptr;
}
objects = NULL;
}
<commit_msg>Fixed a typo.<commit_after>/* -*- Mode: C++; tab-width: 2; indent-tabs-mode: nil; c-basic-offset: 2 -*-
*
* XPLC - Cross-Platform Lightweight Components
* Copyright (C) 2000, Pierre Phaneuf
*
* 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; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA
* 02111-1307, USA.
*/
#include <stdlib.h>
#include "servmgr.h"
IObject* ServiceManager::getInterface(const UUID& uuid) {
do {
if(uuid.equals(IObject::IID))
break;
if(uuid.equals(IServiceManager::IID))
break;
return NULL;
} while(0);
addRef();
return this;
}
void ServiceManager::addObject(const UUID& aUuid, IObject* aObj) {
ObjectNode* node;
node = objects;
while(node) {
if(node->uuid.equals(aUuid))
break;
node = node->next;
}
/*
* FIXME: maybe add a "replace" bool parameter? Or would this
* encourage UUID hijacking too much?
*/
if(node)
return;
node = new ObjectNode(aUuid, aObj, objects);
objects = node;
}
void ServiceManager::removeObject(const UUID& aUuid) {
ObjectNode* node;
ObjectNode** ptr;
node = objects;
ptr = &objects;
while(node) {
if(node->uuid.equals(aUuid)) {
*ptr = node->next;
delete node;
break;
}
ptr = &node->next;
node = *ptr;
}
}
IObject* ServiceManager::getObject(const UUID& aUuid) {
ObjectNode* obj;
/*
* We look through the objects list and return if we find a match.
*/
obj = objects;
while(obj) {
if(obj->uuid.equals(aUuid)) {
obj->obj->addRef();
return obj->obj;
}
obj = obj->next;
}
/*
* No match was found, we return empty-handed.
*/
return NULL;
}
void ServiceManager::shutdown() {
ObjectNode* node;
ObjectNode* ptr;
node = objects;
while(node) {
ptr = node;
node = node->next;
delete ptr;
}
objects = NULL;
}
<|endoftext|> |
<commit_before>/*
* Author: Landon Fuller <landon@landonf.org>
*
* Copyright (c) 2015 Landon Fuller <landon@landonf.org>.
* 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.
*/
#pragma once
#include "PMLog.h"
#include <mach-o/loader.h>
#include <mach-o/dyld.h>
#include <assert.h>
#include <stdio.h>
#include <stdint.h>
#include <inttypes.h>
#include <dlfcn.h>
#include <vector>
#include <map>
#include <string>
#include "SymbolName.hpp"
namespace patchmaster {
/* Architecture-specific Mach-O types and constants */
#ifdef __LP64__
typedef struct mach_header_64 pl_mach_header_t;
typedef struct segment_command_64 pl_segment_command_t;
typedef struct section_64 pl_section_t;
typedef struct nlist_64 pl_nlist_t;
static constexpr uint32_t PL_LC_SEGMENT = LC_SEGMENT_64;
#else
typedef struct mach_header pl_mach_header_t;
typedef struct segment_command pl_segment_command_t;
typedef struct section pl_section_t;
typedef struct nlist pl_nlist_t;
static constexpr uint32_t PL_LC_SEGMENT = LC_SEGMENT;
#endif
uint64_t read_uleb128 (const void *location, std::size_t *size);
int64_t read_sleb128 (const void *location, std::size_t *size);
/* Forward declaration */
class LocalImage;
/**
* A simple byte-based opcode stream reader.
*
* This was adapted from our DWARF opcode evaluation code in PLCrashReporter.
*/
class bind_opstream {
/** Current position within the op stream */
const uint8_t *_p;
/** Starting address. */
const uint8_t *_instr;
/** Ending address. */
const uint8_t *_instr_max;
/** Current immediate value */
uint8_t _immd = 0;
/**
* If true, this is a lazy opcode section; BIND_OPCODE_DONE is automatically skipped at the end of
* each entry (the lazy section is written to terminate evaluation after each entry, as each symbol within
* the lazy section is by dyld on-demand, and is supposed to terminate after resolving one symbol).
*/
bool _isLazy;
/**
* Opcode evaluation state.
*/
struct evaluation_state {
/* dylib path from which the symbol will be resolved, or an empty string if unspecified or flat binding. */
std::string sym_image = "";
/* bind type (one of BIND_TYPE_POINTER, BIND_TYPE_TEXT_ABSOLUTE32, or BIND_TYPE_TEXT_PCREL32) */
uint8_t bind_type = BIND_TYPE_POINTER;
/* symbol name */
const char *sym_name = "";
/* symbol flags (one of BIND_SYMBOL_FLAGS_WEAK_IMPORT, BIND_SYMBOL_FLAGS_NON_WEAK_DEFINITION) */
uint8_t sym_flags = 0;
/* A value to be added to the resolved symbol's address before binding. */
int64_t addend = 0;
/* The actual in-memory bind target address. */
uintptr_t bind_address = 0;
};
/** The current evaluation state. */
evaluation_state _eval_state;
public:
bind_opstream (const uint8_t *opcodes, const size_t opcodes_len, bool isLazy) : _p(opcodes), _instr(_p), _instr_max(_p + opcodes_len), _isLazy(isLazy) {}
bind_opstream (const bind_opstream &other) : _p(other._p), _instr(other._instr), _instr_max(other._instr_max), _isLazy(other._isLazy) {}
/**
* The parsed bind procedure for a single symbol.
*/
class symbol_proc {
public:
/**
* Construct a new symbol procedure record.
*
* @param name The two-level symbol name bound by this procedure.
* @param type The bind type for this symbol.
* @param flags The bind flags for this symbol.
* @param addend A value to be added to the resolved symbol's address before binding.
* @param bind_address The actual in-memory bind target address.
*/
symbol_proc (const SymbolName &name, uint8_t type, uint8_t flags, int64_t addend, uintptr_t bind_address) :
_name(name), _type(type), _flags(flags), _addend(addend), _bind_address(bind_address) {}
symbol_proc (SymbolName &&name, uint8_t type, uint8_t flags, int64_t addend, uintptr_t bind_address) :
_name(std::move(name)), _type(type), _flags(flags), _addend(addend), _bind_address(bind_address) {}
/** The two-level symbol name bound by this procedure. */
const SymbolName &name () const { return _name; }
/* The bind type for this symbol (one of BIND_TYPE_POINTER, BIND_TYPE_TEXT_ABSOLUTE32, or BIND_TYPE_TEXT_PCREL32) */
uint8_t type () const { return _type; }
/* The bind flags for this symbol (one of BIND_SYMBOL_FLAGS_WEAK_IMPORT, BIND_SYMBOL_FLAGS_NON_WEAK_DEFINITION) */
uint8_t flags () const { return _flags; }
/* A value to be added to the resolved symbol's address before binding. */
int64_t addend () const { return _addend; }
/* The actual in-memory bind target address. */
uintptr_t bind_address () const { return _bind_address; }
private:
/** The two-level symbol name bound by this procedure. */
SymbolName _name;
/* The bind type for this symbol (one of BIND_TYPE_POINTER, BIND_TYPE_TEXT_ABSOLUTE32, or BIND_TYPE_TEXT_PCREL32) */
uint8_t _type;
/* The bind flags for this symbol (one of BIND_SYMBOL_FLAGS_WEAK_IMPORT, BIND_SYMBOL_FLAGS_NON_WEAK_DEFINITION) */
uint8_t _flags = 0;
/* A value to be added to the resolved symbol's address before binding. */
int64_t _addend = 0;
/* The actual in-memory bind target address. */
uintptr_t _bind_address = 0;
};
void evaluate (const LocalImage &image, const std::function<void(const symbol_proc &)> &bind);
uint8_t step (const LocalImage &image, const std::function<void(const symbol_proc &)> &bind);
/** Read a ULEB128 value and advance the stream */
inline uint64_t uleb128 () {
size_t len;
uint64_t result = read_uleb128(_p, &len);
_p += len;
assert(_p <= _instr_max);
return result;
}
/** Read a SLEB128 value and advance the stream */
inline int64_t sleb128 () {
size_t len;
int64_t result = read_sleb128(_p, &len);
_p += len;
assert(_p <= _instr_max);
return result;
}
/** Skip @a offset bytes. */
inline void skip (size_t offset) {
_p += offset;
assert(_p <= _instr_max);
}
/** Read a single opcode from the stream. */
inline uint8_t opcode () {
assert(_p < _instr_max);
uint8_t value = (*_p) & BIND_OPCODE_MASK;
_immd = (*_p) & BIND_IMMEDIATE_MASK;
_p++;
/* Skip BIND_OPCODE_DONE if it occurs within a lazy binding opcode stream */
if (_isLazy && *_p == BIND_OPCODE_DONE && !isEmpty())
skip(1);
return value;
};
/** Return the current stream position. */
inline const uint8_t *position () { return _p; };
/** Return true if there are no additional opcodes to be read. */
inline bool isEmpty () { return _p >= _instr_max; }
/** Read a NUL-terminated C string from the stream, advancing the current position past the string. */
inline const char *cstring () {
const char *result = (const char *) _p;
skip(strlen(result) + 1);
return result;
}
/** Return the immediate value from the last opcode */
inline uint8_t immd () { return _immd; }
/** Return the signed representation of immd */
inline int8_t signed_immd () {
/* All other constants are negative */
if (immd() == 0)
return 0;
/* Sign-extend the immediate value */
return (~BIND_IMMEDIATE_MASK) | (immd() & BIND_IMMEDIATE_MASK);
}
};
/**
* An in-memory Mach-O image.
*/
class LocalImage {
private:
friend class bind_opstream;
/**
* Construct a new local image.
*/
LocalImage (
const std::string &path,
const pl_mach_header_t *header,
const intptr_t vmaddr_slide,
std::shared_ptr<std::vector<const std::string>> &libraries,
std::shared_ptr<std::vector<const pl_segment_command_t *>> &segments,
std::shared_ptr<std::vector<const bind_opstream>> &bindings
) : _header(header), _vmaddr_slide(vmaddr_slide), _libraries(libraries), _segments(segments), _bindOpcodes(bindings), _path(path) {}
public:
/** Symbol binding function */
using bind_fn = std::function<void (const SymbolName &name, uintptr_t *target, int64_t addend)>;
static const std::string &MainExecutablePath ();
static LocalImage Analyze (const std::string &path, const pl_mach_header_t *header);
void rebind_symbols (const bind_fn &binder);
private:
/** Mach-O image header */
const pl_mach_header_t *_header;
/** Offset applied when the image was loaded; required to compute in-memory addresses from on-disk VM addresses.. */
const intptr_t _vmaddr_slide;
/** Linked libraries, indexed by reference order. */
std::shared_ptr<std::vector<const std::string>> _libraries;
/** Segment commands, indexed by declaration order. */
std::shared_ptr<std::vector<const pl_segment_command_t *>> _segments;
/** All symbol binding opcodes. */
std::shared_ptr<std::vector<const bind_opstream>> _bindOpcodes;
/** Image path */
const std::string _path;
};
} /* namespace patchmaster */<commit_msg>Provide a getter for LocalImage's bind opcode streams.<commit_after>/*
* Author: Landon Fuller <landon@landonf.org>
*
* Copyright (c) 2015 Landon Fuller <landon@landonf.org>.
* 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.
*/
#pragma once
#include "PMLog.h"
#include <mach-o/loader.h>
#include <mach-o/dyld.h>
#include <assert.h>
#include <stdio.h>
#include <stdint.h>
#include <inttypes.h>
#include <dlfcn.h>
#include <vector>
#include <map>
#include <string>
#include "SymbolName.hpp"
namespace patchmaster {
/* Architecture-specific Mach-O types and constants */
#ifdef __LP64__
typedef struct mach_header_64 pl_mach_header_t;
typedef struct segment_command_64 pl_segment_command_t;
typedef struct section_64 pl_section_t;
typedef struct nlist_64 pl_nlist_t;
static constexpr uint32_t PL_LC_SEGMENT = LC_SEGMENT_64;
#else
typedef struct mach_header pl_mach_header_t;
typedef struct segment_command pl_segment_command_t;
typedef struct section pl_section_t;
typedef struct nlist pl_nlist_t;
static constexpr uint32_t PL_LC_SEGMENT = LC_SEGMENT;
#endif
uint64_t read_uleb128 (const void *location, std::size_t *size);
int64_t read_sleb128 (const void *location, std::size_t *size);
/* Forward declaration */
class LocalImage;
/**
* A simple byte-based opcode stream reader.
*
* This was adapted from our DWARF opcode evaluation code in PLCrashReporter.
*/
class bind_opstream {
/** Current position within the op stream */
const uint8_t *_p;
/** Starting address. */
const uint8_t *_instr;
/** Ending address. */
const uint8_t *_instr_max;
/** Current immediate value */
uint8_t _immd = 0;
/**
* If true, this is a lazy opcode section; BIND_OPCODE_DONE is automatically skipped at the end of
* each entry (the lazy section is written to terminate evaluation after each entry, as each symbol within
* the lazy section is by dyld on-demand, and is supposed to terminate after resolving one symbol).
*/
bool _isLazy;
/**
* Opcode evaluation state.
*/
struct evaluation_state {
/* dylib path from which the symbol will be resolved, or an empty string if unspecified or flat binding. */
std::string sym_image = "";
/* bind type (one of BIND_TYPE_POINTER, BIND_TYPE_TEXT_ABSOLUTE32, or BIND_TYPE_TEXT_PCREL32) */
uint8_t bind_type = BIND_TYPE_POINTER;
/* symbol name */
const char *sym_name = "";
/* symbol flags (one of BIND_SYMBOL_FLAGS_WEAK_IMPORT, BIND_SYMBOL_FLAGS_NON_WEAK_DEFINITION) */
uint8_t sym_flags = 0;
/* A value to be added to the resolved symbol's address before binding. */
int64_t addend = 0;
/* The actual in-memory bind target address. */
uintptr_t bind_address = 0;
};
/** The current evaluation state. */
evaluation_state _eval_state;
public:
bind_opstream (const uint8_t *opcodes, const size_t opcodes_len, bool isLazy) : _p(opcodes), _instr(_p), _instr_max(_p + opcodes_len), _isLazy(isLazy) {}
bind_opstream (const bind_opstream &other) : _p(other._p), _instr(other._instr), _instr_max(other._instr_max), _isLazy(other._isLazy) {}
/**
* The parsed bind procedure for a single symbol.
*/
class symbol_proc {
public:
/**
* Construct a new symbol procedure record.
*
* @param name The two-level symbol name bound by this procedure.
* @param type The bind type for this symbol.
* @param flags The bind flags for this symbol.
* @param addend A value to be added to the resolved symbol's address before binding.
* @param bind_address The actual in-memory bind target address.
*/
symbol_proc (const SymbolName &name, uint8_t type, uint8_t flags, int64_t addend, uintptr_t bind_address) :
_name(name), _type(type), _flags(flags), _addend(addend), _bind_address(bind_address) {}
symbol_proc (SymbolName &&name, uint8_t type, uint8_t flags, int64_t addend, uintptr_t bind_address) :
_name(std::move(name)), _type(type), _flags(flags), _addend(addend), _bind_address(bind_address) {}
/** The two-level symbol name bound by this procedure. */
const SymbolName &name () const { return _name; }
/* The bind type for this symbol (one of BIND_TYPE_POINTER, BIND_TYPE_TEXT_ABSOLUTE32, or BIND_TYPE_TEXT_PCREL32) */
uint8_t type () const { return _type; }
/* The bind flags for this symbol (one of BIND_SYMBOL_FLAGS_WEAK_IMPORT, BIND_SYMBOL_FLAGS_NON_WEAK_DEFINITION) */
uint8_t flags () const { return _flags; }
/* A value to be added to the resolved symbol's address before binding. */
int64_t addend () const { return _addend; }
/* The actual in-memory bind target address. */
uintptr_t bind_address () const { return _bind_address; }
private:
/** The two-level symbol name bound by this procedure. */
SymbolName _name;
/* The bind type for this symbol (one of BIND_TYPE_POINTER, BIND_TYPE_TEXT_ABSOLUTE32, or BIND_TYPE_TEXT_PCREL32) */
uint8_t _type;
/* The bind flags for this symbol (one of BIND_SYMBOL_FLAGS_WEAK_IMPORT, BIND_SYMBOL_FLAGS_NON_WEAK_DEFINITION) */
uint8_t _flags = 0;
/* A value to be added to the resolved symbol's address before binding. */
int64_t _addend = 0;
/* The actual in-memory bind target address. */
uintptr_t _bind_address = 0;
};
void evaluate (const LocalImage &image, const std::function<void(const symbol_proc &)> &bind);
uint8_t step (const LocalImage &image, const std::function<void(const symbol_proc &)> &bind);
/** Read a ULEB128 value and advance the stream */
inline uint64_t uleb128 () {
size_t len;
uint64_t result = read_uleb128(_p, &len);
_p += len;
assert(_p <= _instr_max);
return result;
}
/** Read a SLEB128 value and advance the stream */
inline int64_t sleb128 () {
size_t len;
int64_t result = read_sleb128(_p, &len);
_p += len;
assert(_p <= _instr_max);
return result;
}
/** Skip @a offset bytes. */
inline void skip (size_t offset) {
_p += offset;
assert(_p <= _instr_max);
}
/** Read a single opcode from the stream. */
inline uint8_t opcode () {
assert(_p < _instr_max);
uint8_t value = (*_p) & BIND_OPCODE_MASK;
_immd = (*_p) & BIND_IMMEDIATE_MASK;
_p++;
/* Skip BIND_OPCODE_DONE if it occurs within a lazy binding opcode stream */
if (_isLazy && *_p == BIND_OPCODE_DONE && !isEmpty())
skip(1);
return value;
};
/** Return the current stream position. */
inline const uint8_t *position () { return _p; };
/** Return true if there are no additional opcodes to be read. */
inline bool isEmpty () { return _p >= _instr_max; }
/** Return true if this is a lazy opcode stream. */
inline bool isLazy () { return _isLazy; }
/** Read a NUL-terminated C string from the stream, advancing the current position past the string. */
inline const char *cstring () {
const char *result = (const char *) _p;
skip(strlen(result) + 1);
return result;
}
/** Return the immediate value from the last opcode */
inline uint8_t immd () { return _immd; }
/** Return the signed representation of immd */
inline int8_t signed_immd () {
/* All other constants are negative */
if (immd() == 0)
return 0;
/* Sign-extend the immediate value */
return (~BIND_IMMEDIATE_MASK) | (immd() & BIND_IMMEDIATE_MASK);
}
};
/**
* An in-memory Mach-O image.
*/
class LocalImage {
private:
friend class bind_opstream;
/**
* Construct a new local image.
*/
LocalImage (
const std::string &path,
const pl_mach_header_t *header,
const intptr_t vmaddr_slide,
std::shared_ptr<std::vector<const std::string>> &libraries,
std::shared_ptr<std::vector<const pl_segment_command_t *>> &segments,
std::shared_ptr<std::vector<const bind_opstream>> &bindings
) : _header(header), _vmaddr_slide(vmaddr_slide), _libraries(libraries), _segments(segments), _bindOpcodes(bindings), _path(path) {}
public:
/** Symbol binding function */
using bind_fn = std::function<void (const SymbolName &name, uintptr_t *target, int64_t addend)>;
static const std::string &MainExecutablePath ();
static LocalImage Analyze (const std::string &path, const pl_mach_header_t *header);
void rebind_symbols (const bind_fn &binder);
/**
* Return the image's symbol binding opcode streams.
*/
std::shared_ptr<std::vector<const bind_opstream>> bindOpcodes() const { return _bindOpcodes; }
private:
/** Mach-O image header */
const pl_mach_header_t *_header;
/** Offset applied when the image was loaded; required to compute in-memory addresses from on-disk VM addresses.. */
const intptr_t _vmaddr_slide;
/** Linked libraries, indexed by reference order. */
std::shared_ptr<std::vector<const std::string>> _libraries;
/** Segment commands, indexed by declaration order. */
std::shared_ptr<std::vector<const pl_segment_command_t *>> _segments;
/** All symbol binding opcodes. */
std::shared_ptr<std::vector<const bind_opstream>> _bindOpcodes;
/** Image path */
const std::string _path;
};
} /* namespace patchmaster */<|endoftext|> |
<commit_before>/* Copyright (c) 2017-2018 Hans-Kristian Arntzen
*
* 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.
*/
#pragma once
#include "intrusive_list.hpp"
#include "hash.hpp"
#include "object_pool.hpp"
#include "read_write_lock.hpp"
#include "util.hpp"
#include <vector>
#include <assert.h>
namespace Util
{
template <typename T>
class IntrusiveHashMapEnabled : public IntrusiveListEnabled<T>
{
public:
IntrusiveHashMapEnabled() = default;
IntrusiveHashMapEnabled(Util::Hash hash)
: intrusive_hashmap_key(hash)
{
}
void set_hash(Util::Hash hash)
{
intrusive_hashmap_key = hash;
}
Util::Hash get_hash() const
{
return intrusive_hashmap_key;
}
private:
Hash intrusive_hashmap_key = 0;
};
template <typename T>
struct IntrusivePODWrapper : public IntrusiveHashMapEnabled<IntrusivePODWrapper<T>>
{
template <typename U>
IntrusivePODWrapper(U&& value_)
: value(std::forward<U>(value_))
{
}
IntrusivePODWrapper() = default;
T& get()
{
return value;
}
const T& get() const
{
return value;
}
T value = {};
};
// This HashMap is non-owning. It just arranges a list of pointers.
// It's kind of special purpose container used by the Vulkan backend.
// Dealing with memory ownership is done through composition by a different class.
// T must inherit from IntrusiveHashMapEnabled<T>.
// Each instance of T can only be part of one hashmap.
template <typename T>
class IntrusiveHashMapHolder
{
public:
enum { InitialSize = 64, InitialLoadCount = 4 };
T *find(Hash hash) const
{
if (values.empty())
return nullptr;
auto masked = hash & hash_mask;
for (unsigned i = 0; i < load_count; i++)
{
if (values[masked] && get_hash(values[masked]) == hash)
return values[masked];
masked = (masked + 1) & hash_mask;
}
return nullptr;
}
template <typename P>
bool find_and_consume_pod(Hash hash, P &p) const
{
T *t = find(hash);
if (t)
{
p = t->get();
return true;
}
else
return false;
}
// Inserts, if value already exists, insertion does not happen.
// Return value is the data which is not part of the hashmap.
// It should be deleted or similar.
// Returns nullptr if nothing was in the hashmap for this key.
T *insert_yield(T *&value)
{
if (values.empty())
grow();
auto hash = get_hash(value);
auto masked = hash & hash_mask;
for (unsigned i = 0; i < load_count; i++)
{
if (values[masked] && get_hash(values[masked]) == hash)
{
T *ret = value;
value = values[masked];
return ret;
}
else if (!values[masked])
{
values[masked] = value;
list.insert_front(value);
return nullptr;
}
masked = (masked + 1) & hash_mask;
}
grow();
return insert_yield(value);
}
T *insert_replace(T *value)
{
if (values.empty())
grow();
auto hash = get_hash(value);
auto masked = hash & hash_mask;
for (unsigned i = 0; i < load_count; i++)
{
if (values[masked] && get_hash(values[masked]) == hash)
{
std::swap(values[masked], value);
list.erase(value);
list.insert_front(values[masked]);
return value;
}
else if (!values[masked])
{
assert(!values[masked]);
values[masked] = value;
list.insert_front(value);
return nullptr;
}
masked = (masked + 1) & hash_mask;
}
grow();
return insert_replace(value);
}
T *erase(Hash hash)
{
auto masked = hash & hash_mask;
for (unsigned i = 0; i < load_count; i++)
{
if (values[masked] && get_hash(values[masked]) == hash)
{
auto *value = values[masked];
list.erase(value);
values[masked] = nullptr;
return value;
}
masked = (masked + 1) & hash_mask;
}
return nullptr;
}
void erase(T *value)
{
erase(get_hash(value));
}
void clear()
{
list.clear();
values.clear();
hash_mask = 0;
load_count = 0;
}
typename IntrusiveList<T>::Iterator begin()
{
return list.begin();
}
typename IntrusiveList<T>::Iterator end()
{
return list.end();
}
IntrusiveList<T> &inner_list()
{
return list;
}
private:
inline bool compare_key(Hash masked, Hash hash) const
{
return get_key_for_index(masked) == hash;
}
inline Hash get_hash(const T *value) const
{
return static_cast<const IntrusiveHashMapEnabled<T> *>(value)->get_hash();
}
inline Hash get_key_for_index(Hash masked) const
{
return get_hash(values[masked]);
}
bool insert_inner(T *value)
{
auto hash = get_hash(value);
auto masked = hash & hash_mask;
for (unsigned i = 0; i < load_count; i++)
{
if (!values[masked])
{
values[masked] = value;
return true;
}
masked = (masked + 1) & hash_mask;
}
return false;
}
void grow()
{
bool success;
do
{
for (auto &v : values)
v = nullptr;
if (values.empty())
{
values.resize(InitialSize);
load_count = InitialLoadCount;
//LOGI("Growing hashmap to %u elements.\n", InitialSize);
}
else
{
values.resize(values.size() * 2);
//LOGI("Growing hashmap to %u elements.\n", unsigned(values.size()));
load_count++;
}
hash_mask = Hash(values.size()) - 1;
// Re-insert.
success = true;
for (auto &t : list)
{
if (!insert_inner(&t))
{
success = false;
break;
}
}
} while (!success);
}
std::vector<T *> values;
IntrusiveList<T> list;
Hash hash_mask = 0;
size_t count = 0;
unsigned load_count = 0;
};
template <typename T>
class IntrusiveHashMap
{
public:
~IntrusiveHashMap()
{
clear();
}
IntrusiveHashMap() = default;
IntrusiveHashMap(const IntrusiveHashMap &) = delete;
void operator=(const IntrusiveHashMap &) = delete;
void clear()
{
auto &list = hashmap.inner_list();
auto itr = list.begin();
while (itr != list.end())
{
auto *to_free = itr.get();
itr = list.erase(itr);
pool.free(to_free);
}
hashmap.clear();
}
T *find(Hash hash) const
{
return hashmap.find(hash);
}
T &operator[](Hash hash)
{
auto *t = find(hash);
if (!t)
t = emplace_yield(hash);
return *t;
}
template <typename P>
bool find_and_consume_pod(Hash hash, P &p) const
{
return hashmap.find_and_consume_pod(hash, p);
}
void erase(T *value)
{
hashmap.erase(value);
pool.free(value);
}
void erase(Hash hash)
{
auto *value = hashmap.erase(hash);
if (value)
pool.free(value);
}
template <typename... P>
T *emplace_replace(Hash hash, P&&... p)
{
T *t = allocate(std::forward<P>(p)...);
return insert_replace(hash, t);
}
template <typename... P>
T *emplace_yield(Hash hash, P&&... p)
{
T *t = allocate(std::forward<P>(p)...);
return insert_yield(hash, t);
}
template <typename... P>
T *allocate(P&&... p)
{
return pool.allocate(std::forward<P>(p)...);
}
void free(T *value)
{
pool.free(value);
}
T *insert_replace(Hash hash, T *value)
{
static_cast<IntrusiveHashMapEnabled<T> *>(value)->set_hash(hash);
T *to_delete = hashmap.insert_replace(value);
if (to_delete)
pool.free(to_delete);
return value;
}
T *insert_yield(Hash hash, T *value)
{
static_cast<IntrusiveHashMapEnabled<T> *>(value)->set_hash(hash);
T *to_delete = hashmap.insert_yield(value);
if (to_delete)
pool.free(to_delete);
return value;
}
typename IntrusiveList<T>::Iterator begin()
{
return hashmap.begin();
}
typename IntrusiveList<T>::Iterator end()
{
return hashmap.end();
}
IntrusiveHashMap &get_thread_unsafe()
{
return *this;
}
private:
IntrusiveHashMapHolder<T> hashmap;
ObjectPool<T> pool;
};
template <typename T>
using IntrusiveHashMapWrapper = IntrusiveHashMap<IntrusivePODWrapper<T>>;
template <typename T>
class ThreadSafeIntrusiveHashMap
{
public:
T *find(Hash hash) const
{
lock.lock_read();
T *t = hashmap.find(hash);
lock.unlock_read();
// We can race with the intrusive list internal pointers,
// but that's an internal detail which should never be touched outside the hashmap.
return t;
}
template <typename P>
bool find_and_consume_pod(Hash hash, P &p) const
{
lock.lock_read();
bool ret = hashmap.find_and_consume_pod(hash, p);
lock.unlock_read();
return ret;
}
void clear()
{
lock.lock_write();
hashmap.clear();
lock.unlock_write();
}
// Assumption is that readers will not be erased while in use by any other thread.
void erase(T *value)
{
lock.lock_write();
hashmap.erase(value);
lock.unlock_write();
}
void erase(Hash hash)
{
lock.lock_write();
hashmap.erase(hash);
lock.unlock_write();
}
template <typename... P>
T *allocate(P&&... p)
{
lock.lock_write();
T *t = hashmap.allocate(std::forward<P>(p)...);
lock.unlock_write();
return t;
}
void free(T *value)
{
lock.lock_write();
hashmap.free(value);
lock.unlock_write();
}
T *insert_replace(Hash hash, T *value)
{
lock.lock_write();
value = hashmap.insert_replace(hash, value);
lock.unlock_write();
return value;
}
T *insert_yield(Hash hash, T *value)
{
lock.lock_write();
value = hashmap.insert_yield(hash, value);
lock.unlock_write();
return value;
}
// This one is very sketchy, since callers need to make sure there are no readers of this hash.
template <typename... P>
T *emplace_replace(Hash hash, P&&... p)
{
lock.lock_write();
T *t = hashmap.emplace_replace(hash, std::forward<P>(p)...);
lock.unlock_write();
return t;
}
template <typename... P>
T *emplace_yield(Hash hash, P&&... p)
{
lock.lock_write();
T *t = hashmap.emplace_yield(hash, std::forward<P>(p)...);
lock.unlock_write();
return t;
}
// Not supposed to be called in racy conditions,
// we could have a global read lock and unlock while iterating if necessary.
typename IntrusiveList<T>::Iterator begin()
{
return hashmap.begin();
}
typename IntrusiveList<T>::Iterator end()
{
return hashmap.end();
}
IntrusiveHashMap<T> &get_thread_unsafe()
{
return hashmap;
}
private:
IntrusiveHashMap<T> hashmap;
mutable RWSpinLock lock;
};
}<commit_msg>Reduce initial size for hashmap.<commit_after>/* Copyright (c) 2017-2018 Hans-Kristian Arntzen
*
* 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.
*/
#pragma once
#include "intrusive_list.hpp"
#include "hash.hpp"
#include "object_pool.hpp"
#include "read_write_lock.hpp"
#include "util.hpp"
#include <vector>
#include <assert.h>
namespace Util
{
template <typename T>
class IntrusiveHashMapEnabled : public IntrusiveListEnabled<T>
{
public:
IntrusiveHashMapEnabled() = default;
IntrusiveHashMapEnabled(Util::Hash hash)
: intrusive_hashmap_key(hash)
{
}
void set_hash(Util::Hash hash)
{
intrusive_hashmap_key = hash;
}
Util::Hash get_hash() const
{
return intrusive_hashmap_key;
}
private:
Hash intrusive_hashmap_key = 0;
};
template <typename T>
struct IntrusivePODWrapper : public IntrusiveHashMapEnabled<IntrusivePODWrapper<T>>
{
template <typename U>
IntrusivePODWrapper(U&& value_)
: value(std::forward<U>(value_))
{
}
IntrusivePODWrapper() = default;
T& get()
{
return value;
}
const T& get() const
{
return value;
}
T value = {};
};
// This HashMap is non-owning. It just arranges a list of pointers.
// It's kind of special purpose container used by the Vulkan backend.
// Dealing with memory ownership is done through composition by a different class.
// T must inherit from IntrusiveHashMapEnabled<T>.
// Each instance of T can only be part of one hashmap.
template <typename T>
class IntrusiveHashMapHolder
{
public:
enum { InitialSize = 16, InitialLoadCount = 3 };
T *find(Hash hash) const
{
if (values.empty())
return nullptr;
Hash hash_mask = values.size() - 1;
auto masked = hash & hash_mask;
for (unsigned i = 0; i < load_count; i++)
{
if (values[masked] && get_hash(values[masked]) == hash)
return values[masked];
masked = (masked + 1) & hash_mask;
}
return nullptr;
}
template <typename P>
bool find_and_consume_pod(Hash hash, P &p) const
{
T *t = find(hash);
if (t)
{
p = t->get();
return true;
}
else
return false;
}
// Inserts, if value already exists, insertion does not happen.
// Return value is the data which is not part of the hashmap.
// It should be deleted or similar.
// Returns nullptr if nothing was in the hashmap for this key.
T *insert_yield(T *&value)
{
if (values.empty())
grow();
Hash hash_mask = values.size() - 1;
auto hash = get_hash(value);
auto masked = hash & hash_mask;
for (unsigned i = 0; i < load_count; i++)
{
if (values[masked] && get_hash(values[masked]) == hash)
{
T *ret = value;
value = values[masked];
return ret;
}
else if (!values[masked])
{
values[masked] = value;
list.insert_front(value);
return nullptr;
}
masked = (masked + 1) & hash_mask;
}
grow();
return insert_yield(value);
}
T *insert_replace(T *value)
{
if (values.empty())
grow();
Hash hash_mask = values.size() - 1;
auto hash = get_hash(value);
auto masked = hash & hash_mask;
for (unsigned i = 0; i < load_count; i++)
{
if (values[masked] && get_hash(values[masked]) == hash)
{
std::swap(values[masked], value);
list.erase(value);
list.insert_front(values[masked]);
return value;
}
else if (!values[masked])
{
assert(!values[masked]);
values[masked] = value;
list.insert_front(value);
return nullptr;
}
masked = (masked + 1) & hash_mask;
}
grow();
return insert_replace(value);
}
T *erase(Hash hash)
{
Hash hash_mask = values.size() - 1;
auto masked = hash & hash_mask;
for (unsigned i = 0; i < load_count; i++)
{
if (values[masked] && get_hash(values[masked]) == hash)
{
auto *value = values[masked];
list.erase(value);
values[masked] = nullptr;
return value;
}
masked = (masked + 1) & hash_mask;
}
return nullptr;
}
void erase(T *value)
{
erase(get_hash(value));
}
void clear()
{
list.clear();
values.clear();
load_count = 0;
}
typename IntrusiveList<T>::Iterator begin()
{
return list.begin();
}
typename IntrusiveList<T>::Iterator end()
{
return list.end();
}
IntrusiveList<T> &inner_list()
{
return list;
}
private:
inline bool compare_key(Hash masked, Hash hash) const
{
return get_key_for_index(masked) == hash;
}
inline Hash get_hash(const T *value) const
{
return static_cast<const IntrusiveHashMapEnabled<T> *>(value)->get_hash();
}
inline Hash get_key_for_index(Hash masked) const
{
return get_hash(values[masked]);
}
bool insert_inner(T *value)
{
Hash hash_mask = values.size() - 1;
auto hash = get_hash(value);
auto masked = hash & hash_mask;
for (unsigned i = 0; i < load_count; i++)
{
if (!values[masked])
{
values[masked] = value;
return true;
}
masked = (masked + 1) & hash_mask;
}
return false;
}
void grow()
{
bool success;
do
{
for (auto &v : values)
v = nullptr;
if (values.empty())
{
values.resize(InitialSize);
load_count = InitialLoadCount;
//LOGI("Growing hashmap to %u elements.\n", InitialSize);
}
else
{
values.resize(values.size() * 2);
//LOGI("Growing hashmap to %u elements.\n", unsigned(values.size()));
load_count++;
}
// Re-insert.
success = true;
for (auto &t : list)
{
if (!insert_inner(&t))
{
success = false;
break;
}
}
} while (!success);
}
std::vector<T *> values;
IntrusiveList<T> list;
size_t count = 0;
unsigned load_count = 0;
};
template <typename T>
class IntrusiveHashMap
{
public:
~IntrusiveHashMap()
{
clear();
}
IntrusiveHashMap() = default;
IntrusiveHashMap(const IntrusiveHashMap &) = delete;
void operator=(const IntrusiveHashMap &) = delete;
void clear()
{
auto &list = hashmap.inner_list();
auto itr = list.begin();
while (itr != list.end())
{
auto *to_free = itr.get();
itr = list.erase(itr);
pool.free(to_free);
}
hashmap.clear();
}
T *find(Hash hash) const
{
return hashmap.find(hash);
}
T &operator[](Hash hash)
{
auto *t = find(hash);
if (!t)
t = emplace_yield(hash);
return *t;
}
template <typename P>
bool find_and_consume_pod(Hash hash, P &p) const
{
return hashmap.find_and_consume_pod(hash, p);
}
void erase(T *value)
{
hashmap.erase(value);
pool.free(value);
}
void erase(Hash hash)
{
auto *value = hashmap.erase(hash);
if (value)
pool.free(value);
}
template <typename... P>
T *emplace_replace(Hash hash, P&&... p)
{
T *t = allocate(std::forward<P>(p)...);
return insert_replace(hash, t);
}
template <typename... P>
T *emplace_yield(Hash hash, P&&... p)
{
T *t = allocate(std::forward<P>(p)...);
return insert_yield(hash, t);
}
template <typename... P>
T *allocate(P&&... p)
{
return pool.allocate(std::forward<P>(p)...);
}
void free(T *value)
{
pool.free(value);
}
T *insert_replace(Hash hash, T *value)
{
static_cast<IntrusiveHashMapEnabled<T> *>(value)->set_hash(hash);
T *to_delete = hashmap.insert_replace(value);
if (to_delete)
pool.free(to_delete);
return value;
}
T *insert_yield(Hash hash, T *value)
{
static_cast<IntrusiveHashMapEnabled<T> *>(value)->set_hash(hash);
T *to_delete = hashmap.insert_yield(value);
if (to_delete)
pool.free(to_delete);
return value;
}
typename IntrusiveList<T>::Iterator begin()
{
return hashmap.begin();
}
typename IntrusiveList<T>::Iterator end()
{
return hashmap.end();
}
IntrusiveHashMap &get_thread_unsafe()
{
return *this;
}
private:
IntrusiveHashMapHolder<T> hashmap;
ObjectPool<T> pool;
};
template <typename T>
using IntrusiveHashMapWrapper = IntrusiveHashMap<IntrusivePODWrapper<T>>;
template <typename T>
class ThreadSafeIntrusiveHashMap
{
public:
T *find(Hash hash) const
{
lock.lock_read();
T *t = hashmap.find(hash);
lock.unlock_read();
// We can race with the intrusive list internal pointers,
// but that's an internal detail which should never be touched outside the hashmap.
return t;
}
template <typename P>
bool find_and_consume_pod(Hash hash, P &p) const
{
lock.lock_read();
bool ret = hashmap.find_and_consume_pod(hash, p);
lock.unlock_read();
return ret;
}
void clear()
{
lock.lock_write();
hashmap.clear();
lock.unlock_write();
}
// Assumption is that readers will not be erased while in use by any other thread.
void erase(T *value)
{
lock.lock_write();
hashmap.erase(value);
lock.unlock_write();
}
void erase(Hash hash)
{
lock.lock_write();
hashmap.erase(hash);
lock.unlock_write();
}
template <typename... P>
T *allocate(P&&... p)
{
lock.lock_write();
T *t = hashmap.allocate(std::forward<P>(p)...);
lock.unlock_write();
return t;
}
void free(T *value)
{
lock.lock_write();
hashmap.free(value);
lock.unlock_write();
}
T *insert_replace(Hash hash, T *value)
{
lock.lock_write();
value = hashmap.insert_replace(hash, value);
lock.unlock_write();
return value;
}
T *insert_yield(Hash hash, T *value)
{
lock.lock_write();
value = hashmap.insert_yield(hash, value);
lock.unlock_write();
return value;
}
// This one is very sketchy, since callers need to make sure there are no readers of this hash.
template <typename... P>
T *emplace_replace(Hash hash, P&&... p)
{
lock.lock_write();
T *t = hashmap.emplace_replace(hash, std::forward<P>(p)...);
lock.unlock_write();
return t;
}
template <typename... P>
T *emplace_yield(Hash hash, P&&... p)
{
lock.lock_write();
T *t = hashmap.emplace_yield(hash, std::forward<P>(p)...);
lock.unlock_write();
return t;
}
// Not supposed to be called in racy conditions,
// we could have a global read lock and unlock while iterating if necessary.
typename IntrusiveList<T>::Iterator begin()
{
return hashmap.begin();
}
typename IntrusiveList<T>::Iterator end()
{
return hashmap.end();
}
IntrusiveHashMap<T> &get_thread_unsafe()
{
return hashmap;
}
private:
IntrusiveHashMap<T> hashmap;
mutable RWSpinLock lock;
};
}<|endoftext|> |
<commit_before>#include <Eigen/Core> // Cholesky decomposition + solving
#include <Eigen/Cholesky> // of system of linear equations.
#include "nao_igm.h"
#include "maple_functions.h"
/**
* @brief Get feet positions.
*
* @param[out] left_foot_expected 3x1 expected position vector
* @param[out] right_foot_expected 3x1 expected position vector
* @param[out] left_foot_computed 3x1 position vector determined using sensor data
* @param[out] right_foot_computed 3x1 position vector determined using sensor data
*
* @note Support foot position is assumed to be correct and there is no difference
* between the expected and 'real' positions.
*
* @note swing_foot_posture member is updated.
*/
void nao_igm::getFeetPositions (
double *left_foot_expected,
double *right_foot_expected,
double *left_foot_computed,
double *right_foot_computed)
{
if (support_foot == IGM_SUPPORT_LEFT)
{
Vector3d::Map(left_foot_expected) = Vector3d::Map(left_foot_computed) = left_foot_posture.translation();
Vector3d::Map(right_foot_expected) = right_foot_posture.translation();
getSwingFootPosition (state_sensor, right_foot_computed);
}
else
{
Vector3d::Map(right_foot_expected) = Vector3d::Map(right_foot_computed) = right_foot_posture.translation();
Vector3d::Map(left_foot_expected) = left_foot_posture.translation();
getSwingFootPosition (state_sensor, left_foot_computed);
}
}
/**
* @brief Set coordinates of center of mass.
*
* @param[in] x coordinate
* @param[in] y coordinate
* @param[in] z coordinate
*/
void nao_igm::setCoM (const double x, const double y, const double z)
{
CoM_position[0] = x;
CoM_position[1] = y;
CoM_position[2] = z;
}
/** @brief Initialize model.
@param[in] support_foot_ current support foot.
@param[in] x x-position
@param[in] y y-position
@param[in] z z-position
@param[in] roll x-rotation
@param[in] pitch y-rotation
@param[in] yaw z-rotation
@attention Joint angles in state_sensor must be set.
*/
void nao_igm::init(
const igmSupportFoot support_foot_,
const double x,
const double y,
const double z,
const double roll,
const double pitch,
const double yaw)
{
Transform <double, 3> support_foot_posture =
Translation<double,3>(x, y, z) *
AngleAxisd(roll, Vector3d::UnitX()) *
AngleAxisd(pitch, Vector3d::UnitY()) *
AngleAxisd(yaw, Vector3d::UnitZ());
support_foot = support_foot_;
state_model = state_sensor;
Transform<double,3> torso_posture;
if (support_foot == IGM_SUPPORT_LEFT)
{
left_foot_posture = support_foot_posture;
LLeg2Torso(state_sensor.q, left_foot_posture.data(), torso_posture.data());
LLeg2RLeg(state_sensor.q, left_foot_posture.data(), right_foot_posture.data());
swing_foot_posture = right_foot_posture;
}
else
{
right_foot_posture = support_foot_posture;
RLeg2Torso(state_sensor.q, right_foot_posture.data(), torso_posture.data());
RLeg2LLeg(state_sensor.q, right_foot_posture.data(), left_foot_posture.data());
swing_foot_posture = left_foot_posture;
}
Matrix3d::Map (torso_orientation) = torso_posture.matrix().corner(TopLeft,3,3);
getCoM (state_sensor, CoM_position);
}
/**
* @brief Switch support foot.
*
* @return A 4x4 homogeneous matrix, which contains position and orientation
* (computed using sensor data) of the new support foot.
*
* @note swing_foot_posture member is updated.
*/
double* nao_igm::switchSupportFoot()
{
getSwingFootPosture (state_sensor);
state_model = state_sensor;
if (support_foot == IGM_SUPPORT_LEFT)
{
support_foot = IGM_SUPPORT_RIGHT;
}
else
{
support_foot = IGM_SUPPORT_LEFT;
}
return (swing_foot_posture.data());
}
/**
* @brief Compute position of the CoM from joint angles.
*
* @param[in] joints state of the joints.
* @param[in,out] CoM_pos 3x1 vector of coordinates.
*/
void nao_igm::getCoM (jointState& joints, double *CoM_pos)
{
if (support_foot == IGM_SUPPORT_LEFT)
{
LLeg2CoM(joints.q, left_foot_posture.data(), CoM_pos);
}
else
{
RLeg2CoM(joints.q, right_foot_posture.data(), CoM_pos);
}
}
/**
* @brief Compute position of the swing foot from joint angles.
*
* @param[in] joints state of the joints.
* @param[in,out] swing_foot_position 3x1 vector of coordinates.
*
* @note swing_foot_posture member is updated.
*/
void nao_igm::getSwingFootPosition (jointState& joints, double * swing_foot_position)
{
getSwingFootPosture(joints);
Vector3d::Map(swing_foot_position) = swing_foot_posture.translation();
}
/**
* @brief Compute position of the swing foot from joint angles.
*
* @param[in] joints state of the joints.
*
* @note swing_foot_posture member is updated.
*/
void nao_igm::getSwingFootPosture (jointState& joints)
{
if (support_foot == IGM_SUPPORT_LEFT)
{
LLeg2RLeg(joints.q, left_foot_posture.data(), swing_foot_posture.data());
}
else
{
RLeg2LLeg(joints.q, right_foot_posture.data(), swing_foot_posture.data());
}
}
/** \brief Solves the Inverse Geometric Problem (IGM). Constraints for (x, y, z, X(alpha), Y(beta),
Z(gamma)) of the foot not in support as well as (x, y, z) position of the CoM, and X(alpha),
Y(beta) rotation of the torso can be imposed.
\return int iter - the number of iterations performed until convergence, or -1 if the algorithm
did not converge within max_iter number of iterations.
\note It is assumed that the leading matrix of the constraints is nonsingular.
@note On input, the entries of q are the joint angles from where to start the
search for a solution (i.e., the initial guess). On output q contains a solution of the
inverse kinematics problem (if iter != -1). Only q[0]...q[11] are altered.
*/
int nao_igm::igm()
{
const int num_constraints = LOWER_JOINTS_NUM-1; // one is skipped
Matrix<double, num_constraints, num_constraints> AAT;
Matrix<double, LOWER_JOINTS_NUM, 1> dq;
double out[num_constraints*LOWER_JOINTS_NUM + num_constraints];
Map<MatrixXd> A(out,num_constraints,LOWER_JOINTS_NUM);
Map<VectorXd> err(out+num_constraints*LOWER_JOINTS_NUM,num_constraints);
double tol = 0.0005;
int max_iter = 20;
int iter;
double norm_dq = 1.0;
for (iter = 0; (norm_dq > tol) && (iter <= max_iter); ++iter)
{
// Form data
if (support_foot == IGM_SUPPORT_LEFT)
{
from_LLeg_3 (
state_model.q,
left_foot_posture.data(),
right_foot_posture.data(),
CoM_position,
torso_orientation,
out);
}
else
{
from_RLeg_3 (
state_model.q,
right_foot_posture.data(),
left_foot_posture.data(),
CoM_position,
torso_orientation,
out);
}
// Solve KKT system
AAT = A*A.transpose();
AAT.llt().solveInPlace(err);
dq = A.transpose()*err;
// Update angles (of legs)
VectorXd::Map (state_model.q, LOWER_JOINTS_NUM) += dq;
// Compute the norm of dq
norm_dq = dq.norm();
}
if (iter > max_iter)
{
iter = -1;
}
return(iter);
}
<commit_msg>Use Hessian matrix in IK, it allows to penalize joints.<commit_after>#include <Eigen/Core> // Cholesky decomposition + solving
#include <Eigen/Cholesky> // of system of linear equations.
#include "nao_igm.h"
#include "maple_functions.h"
/**
* @brief Get feet positions.
*
* @param[out] left_foot_expected 3x1 expected position vector
* @param[out] right_foot_expected 3x1 expected position vector
* @param[out] left_foot_computed 3x1 position vector determined using sensor data
* @param[out] right_foot_computed 3x1 position vector determined using sensor data
*
* @note Support foot position is assumed to be correct and there is no difference
* between the expected and 'real' positions.
*
* @note swing_foot_posture member is updated.
*/
void nao_igm::getFeetPositions (
double *left_foot_expected,
double *right_foot_expected,
double *left_foot_computed,
double *right_foot_computed)
{
if (support_foot == IGM_SUPPORT_LEFT)
{
Vector3d::Map(left_foot_expected) = Vector3d::Map(left_foot_computed) = left_foot_posture.translation();
Vector3d::Map(right_foot_expected) = right_foot_posture.translation();
getSwingFootPosition (state_sensor, right_foot_computed);
}
else
{
Vector3d::Map(right_foot_expected) = Vector3d::Map(right_foot_computed) = right_foot_posture.translation();
Vector3d::Map(left_foot_expected) = left_foot_posture.translation();
getSwingFootPosition (state_sensor, left_foot_computed);
}
}
/**
* @brief Set coordinates of center of mass.
*
* @param[in] x coordinate
* @param[in] y coordinate
* @param[in] z coordinate
*/
void nao_igm::setCoM (const double x, const double y, const double z)
{
CoM_position[0] = x;
CoM_position[1] = y;
CoM_position[2] = z;
}
/** @brief Initialize model.
@param[in] support_foot_ current support foot.
@param[in] x x-position
@param[in] y y-position
@param[in] z z-position
@param[in] roll x-rotation
@param[in] pitch y-rotation
@param[in] yaw z-rotation
@attention Joint angles in state_sensor must be set.
*/
void nao_igm::init(
const igmSupportFoot support_foot_,
const double x,
const double y,
const double z,
const double roll,
const double pitch,
const double yaw)
{
Transform <double, 3> support_foot_posture =
Translation<double,3>(x, y, z) *
AngleAxisd(roll, Vector3d::UnitX()) *
AngleAxisd(pitch, Vector3d::UnitY()) *
AngleAxisd(yaw, Vector3d::UnitZ());
support_foot = support_foot_;
state_model = state_sensor;
Transform<double,3> torso_posture;
if (support_foot == IGM_SUPPORT_LEFT)
{
left_foot_posture = support_foot_posture;
LLeg2Torso(state_sensor.q, left_foot_posture.data(), torso_posture.data());
LLeg2RLeg(state_sensor.q, left_foot_posture.data(), right_foot_posture.data());
swing_foot_posture = right_foot_posture;
}
else
{
right_foot_posture = support_foot_posture;
RLeg2Torso(state_sensor.q, right_foot_posture.data(), torso_posture.data());
RLeg2LLeg(state_sensor.q, right_foot_posture.data(), left_foot_posture.data());
swing_foot_posture = left_foot_posture;
}
Matrix3d::Map (torso_orientation) = torso_posture.matrix().corner(TopLeft,3,3);
getCoM (state_sensor, CoM_position);
}
/**
* @brief Switch support foot.
*
* @return A 4x4 homogeneous matrix, which contains position and orientation
* (computed using sensor data) of the new support foot.
*
* @note swing_foot_posture member is updated.
*/
double* nao_igm::switchSupportFoot()
{
getSwingFootPosture (state_sensor);
state_model = state_sensor;
if (support_foot == IGM_SUPPORT_LEFT)
{
support_foot = IGM_SUPPORT_RIGHT;
}
else
{
support_foot = IGM_SUPPORT_LEFT;
}
return (swing_foot_posture.data());
}
/**
* @brief Compute position of the CoM from joint angles.
*
* @param[in] joints state of the joints.
* @param[in,out] CoM_pos 3x1 vector of coordinates.
*/
void nao_igm::getCoM (jointState& joints, double *CoM_pos)
{
if (support_foot == IGM_SUPPORT_LEFT)
{
LLeg2CoM(joints.q, left_foot_posture.data(), CoM_pos);
}
else
{
RLeg2CoM(joints.q, right_foot_posture.data(), CoM_pos);
}
}
/**
* @brief Compute position of the swing foot from joint angles.
*
* @param[in] joints state of the joints.
* @param[in,out] swing_foot_position 3x1 vector of coordinates.
*
* @note swing_foot_posture member is updated.
*/
void nao_igm::getSwingFootPosition (jointState& joints, double * swing_foot_position)
{
getSwingFootPosture(joints);
Vector3d::Map(swing_foot_position) = swing_foot_posture.translation();
}
/**
* @brief Compute position of the swing foot from joint angles.
*
* @param[in] joints state of the joints.
*
* @note swing_foot_posture member is updated.
*/
void nao_igm::getSwingFootPosture (jointState& joints)
{
if (support_foot == IGM_SUPPORT_LEFT)
{
LLeg2RLeg(joints.q, left_foot_posture.data(), swing_foot_posture.data());
}
else
{
RLeg2LLeg(joints.q, right_foot_posture.data(), swing_foot_posture.data());
}
}
/** \brief Solves the Inverse Geometric Problem (IGM). Constraints for (x, y, z, X(alpha), Y(beta),
Z(gamma)) of the foot not in support as well as (x, y, z) position of the CoM, and X(alpha),
Y(beta) rotation of the torso can be imposed.
\return int iter - the number of iterations performed until convergence, or -1 if the algorithm
did not converge within max_iter number of iterations.
\note It is assumed that the leading matrix of the constraints is nonsingular.
@note On input, the entries of q are the joint angles from where to start the
search for a solution (i.e., the initial guess). On output q contains a solution of the
inverse kinematics problem (if iter != -1). Only q[0]...q[11] are altered.
*/
int nao_igm::igm()
{
const int num_constraints = LOWER_JOINTS_NUM-1; // one is skipped
Matrix<double, num_constraints, num_constraints> AAT;
Matrix<double, LOWER_JOINTS_NUM, 1> dq;
Matrix<double, LOWER_JOINTS_NUM, 1> iH; // inverted Hessian
iH.setConstant(1.0);
// joints can be penalized here:
//iH(L_HIP_ROLL) = 0.5;
//iH(R_HIP_ROLL) = 0.5;
double out[num_constraints*LOWER_JOINTS_NUM + num_constraints];
Map<MatrixXd> A(out,num_constraints,LOWER_JOINTS_NUM);
Map<VectorXd> err(out+num_constraints*LOWER_JOINTS_NUM,num_constraints);
double tol = 0.0005;
int max_iter = 20;
int iter;
double norm_dq = 1.0;
for (iter = 0; (norm_dq > tol) && (iter <= max_iter); ++iter)
{
// Form data
if (support_foot == IGM_SUPPORT_LEFT)
{
from_LLeg_3 (
state_model.q,
left_foot_posture.data(),
right_foot_posture.data(),
CoM_position,
torso_orientation,
out);
}
else
{
from_RLeg_3 (
state_model.q,
right_foot_posture.data(),
left_foot_posture.data(),
CoM_position,
torso_orientation,
out);
}
// Solve KKT system
AAT = A*iH.asDiagonal()*A.transpose();
AAT.llt().solveInPlace(err);
dq = iH.asDiagonal()*A.transpose()*err;
// Update angles (of legs)
VectorXd::Map (state_model.q, LOWER_JOINTS_NUM) += dq;
// Compute the norm of dq
norm_dq = dq.norm();
}
if (iter > max_iter)
{
iter = -1;
}
return(iter);
}
<|endoftext|> |
<commit_before>/*****************************************************************************
*
* This file is part of Mapnik (c++ mapping toolkit)
*
* Copyright (C) 2009 Artem Pavlenko
*
* 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
*
*****************************************************************************/
//$Id$
#include <mapnik/datasource.hpp>
#include <mapnik/wkb.hpp>
#include "connection_manager.hpp"
#include "cursorresultset.hpp"
// boost
#include <boost/cstdint.hpp>
#include <boost/optional.hpp>
#include <boost/scoped_ptr.hpp>
#include <boost/shared_ptr.hpp>
#include <boost/lexical_cast.hpp>
#include <boost/format.hpp>
#include <boost/algorithm/string/replace.hpp>
#include <boost/program_options.hpp>
//stl
#include <iostream>
#include <fstream>
/*
osm_id | integer |
access | text |
addr:flats | text |
addr:housenumber | text |
addr:interpolation | text |
admin_level | text |
aerialway | text |
aeroway | text |
amenity | text |
area | text |
barrier | text |
bicycle | text |
bridge | text |
boundary | text |
building | text |
cutting | text |
disused | text |
embankment | text |
foot | text |
highway | text |
historic | text |
horse | text |
junction | text |
landuse | text |
layer | text |
learning | text |
leisure | text |
lock | text |
man_made | text |
military | text |
motorcar | text |
name | text |
natural | text |
oneway | text |
power | text |
power_source | text |
place | text |
railway | text |
ref | text |
religion | text |
residence | text |
route | text |
sport | text |
tourism | text |
tracktype | text |
tunnel | text |
waterway | text |
width | text |
wood | text |
z_order | integer |
way_area | real |
way | geometry |
*/
struct blob_to_hex
{
std::string operator() (const char* blob, unsigned size)
{
std::string buf;
buf.reserve(size*2);
std::ostringstream s(buf);
s.seekp(0);
char hex[3];
std::memset(hex,0,3);
for ( unsigned pos=0; pos < size; ++pos)
{
std::sprintf (hex, "%02X", int(blob[pos]) & 0xff);
s << hex;
}
return s.str();
}
};
template <typename Connection, typename OUT>
void pgsql2sqlite(Connection conn, std::string const& table_name, OUT & out, unsigned tolerance)
{
using namespace mapnik;
boost::shared_ptr<ResultSet> rs = conn->executeQuery("select * from " + table_name + " limit 0;");
int count = rs->getNumFields();
std::ostringstream select_sql;
select_sql << "select ";
for (int i=0; i<count; ++i)
{
if (i!=0) select_sql << ",";
select_sql << "\"" << rs->getFieldName(i) << "\"";
}
select_sql << " from " << table_name ;
std::ostringstream geom_col_sql;
geom_col_sql << "select f_geometry_column,srid,type from geometry_columns ";
geom_col_sql << "where f_table_name='" << table_name << "'";
rs = conn->executeQuery(geom_col_sql.str());
int srid = -1;
std::string geom_col = "UNKNOWN";
std::string geom_type = "UNKNOWN";
if ( rs->next())
{
try
{
srid = boost::lexical_cast<int>(rs->getValue("srid"));
}
catch (boost::bad_lexical_cast &ex)
{
std::clog << ex.what() << std::endl;
}
geom_col = rs->getValue("f_geometry_column");
geom_type = rs->getValue("type");
}
// add AsBinary(<geometry_column>) modifier
std::string select_sql_str = select_sql.str();
if (tolerance > 0)
{
std::string from = "\"" + geom_col + "\"";
std::string to = (boost::format("AsBinary(Simplify(%1%,%2%)) as %1%") % geom_col % tolerance).str();
boost::algorithm::replace_all(select_sql_str,from ,to);
}
else
{
boost::algorithm::replace_all(select_sql_str, "\"" + geom_col + "\"","AsBinary(" + geom_col+") as " + geom_col);
}
std::cout << select_sql_str << "\n";
//std::string select_sql = "select asBinary(way) as way,name,highway,osm_id from " + table_name;
std::ostringstream cursor_sql;
std::string cursor_name("my_cursor");
cursor_sql << "DECLARE " << cursor_name << " BINARY INSENSITIVE NO SCROLL CURSOR WITH HOLD FOR " << select_sql_str << " FOR READ ONLY";
conn->execute(cursor_sql.str());
boost::shared_ptr<CursorResultSet> cursor(new CursorResultSet(conn,cursor_name,10000));
unsigned num_fields = cursor->getNumFields();
std::ostringstream create_sql;
create_sql << "create table " << table_name << "(PK_UID INTEGER PRIMARY KEY AUTOINCREMENT,";
int geometry_oid = -1;
for ( unsigned pos = 0; pos < num_fields ; ++pos)
{
if (pos > 0) create_sql << ",";
if (geom_col == cursor->getFieldName(pos))
{
geometry_oid = cursor->getTypeOID(pos);
create_sql << "'" << cursor->getFieldName(pos) << "' BLOB";
}
else
{
create_sql << "'" << cursor->getFieldName(pos) << "' TEXT";
}
}
create_sql << ");";
std::cout << "client_encoding=" << conn->client_encoding() << "\n";
std::cout << "geometry_column=" << geom_col << "(" << geom_type
<< ") srid=" << srid << " oid=" << geometry_oid << "\n";
// begin
out << "begin;\n";
out << create_sql.str() << "\n";
// spatial index sql
out << "create virtual table idx_"<< table_name << "_" << geom_col << " using rtree(pkid, xmin, xmax, ymin, ymax);\n";
blob_to_hex hex;
int pkid = 0;
while (cursor->next())
{
++pkid;
std::ostringstream insert_sql;
insert_sql << "insert into " << table_name << " values(" << pkid;
for (unsigned pos=0 ; pos < num_fields; ++pos)
{
insert_sql << ",";
if (! cursor->isNull(pos))
{
int size=cursor->getFieldLength(pos);
int oid = cursor->getTypeOID(pos);
const char* buf=cursor->getValue(pos);
switch (oid)
{
case 25:
case 1042:
case 1043:
{
std::string text(buf);
boost::algorithm::replace_all(text,"'","''");
insert_sql << "'"<< text << "'";
break;
}
case 23:
insert_sql << int4net(buf);
break;
default:
{
if (oid == geometry_oid)
{
mapnik::Feature feat(pkid);
geometry_utils::from_wkb(feat,buf,size,false,wkbGeneric);
if (feat.num_geometries() > 0)
{
geometry2d const& geom=feat.get_geometry(0);
Envelope<double> bbox = geom.envelope();
out << "insert into idx_" << table_name << "_" << geom_col << " values (" ;
out << pkid << "," << bbox.minx() << "," << bbox.maxx();
out << "," << bbox.miny() << "," << bbox.maxy() << ");\n";
}
insert_sql << "X'" << hex(buf,size) << "'";
}
else
{
insert_sql << "NULL";
}
break;
}
}
}
else
{
insert_sql << "NULL";
}
}
insert_sql << ");";
out << insert_sql.str() << "\n";
if (pkid % 1000 == 0)
{
std::cout << "\r processing " << pkid << " features";
std::cout.flush();
}
if (pkid % 100000 == 0)
{
out << "commit;\n";
out << "begin;\n";
}
}
// commit
out << "commit;\n";
std::cout << "\r processed " << pkid << " features";
std::cout << "\n Done!" << std::endl;
}
int main ( int argc, char** argv)
{
namespace po = boost::program_options;
po::options_description desc("Postgresql/PostGIS to SQLite3 converter\n Options");
desc.add_options()
("help,?","Display this help screen.")
("host,h",po::value<std::string>(),"Allows you to specify connection to a database on a machine other than the default.")
("port,p",po::value<std::string>(),"Allows you to specify a database port other than the default.")
("user,u",po::value<std::string>(),"Connect to the database as the specified user.")
("dbname,d",po::value<std::string>(),"postgresql database name")
("password,P",po::value<std::string>(),"Connect to the database with the specified password.")
("table,t",po::value<std::string>(),"Name of the table to export")
("simplify,s",po::value<unsigned>(),"Use this option to reduce the complexity\nand weight of a geometry using the Douglas-Peucker algorithm.")
("file,f",po::value<std::string>(),"Use this option to specify the name of the file to create.")
;
po::positional_options_description p;
p.add("table",1);
po::variables_map vm;
try
{
po::store(po::command_line_parser(argc,argv).options(desc).positional(p).run(),vm);
po::notify(vm);
if (vm.count("help") || !vm.count("file") || !vm.count("table"))
{
std::cout << desc << "\n";
return EXIT_SUCCESS;
}
}
catch (...)
{
std::cout << desc << "\n";
return EXIT_FAILURE;
}
boost::optional<std::string> host;
boost::optional<std::string> port ;
boost::optional<std::string> dbname;
boost::optional<std::string> user;
boost::optional<std::string> password;
if (vm.count("host")) host = vm["host"].as<std::string>();
if (vm.count("port")) port = vm["port"].as<std::string>();
if (vm.count("dbname")) dbname = vm["dbname"].as<std::string>();
if (vm.count("user")) user = vm["user"].as<std::string>();
if (vm.count("password")) password = vm["password"].as<std::string>();
unsigned tolerance = 0;
if (vm.count("simplify")) tolerance = vm["simplify"].as<unsigned>();
ConnectionCreator<Connection> creator(host,port,dbname,user,password);
try
{
boost::shared_ptr<Connection> conn(creator());
std::string table_name = vm["table"].as<std::string>();
std::string output_file = vm["file"].as<std::string>();
std::ofstream file(output_file.c_str());
if (file)
{
pgsql2sqlite(conn,table_name,file,tolerance);
}
file.close();
}
catch (mapnik::datasource_exception & ex)
{
std::cerr << ex.what() << "\n";
}
return EXIT_SUCCESS;
}
<commit_msg>+ discard empty geometries from output<commit_after>/*****************************************************************************
*
* This file is part of Mapnik (c++ mapping toolkit)
*
* Copyright (C) 2009 Artem Pavlenko
*
* 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
*
*****************************************************************************/
//$Id$
#include <mapnik/datasource.hpp>
#include <mapnik/wkb.hpp>
#include "connection_manager.hpp"
#include "cursorresultset.hpp"
// boost
#include <boost/cstdint.hpp>
#include <boost/optional.hpp>
#include <boost/scoped_ptr.hpp>
#include <boost/shared_ptr.hpp>
#include <boost/lexical_cast.hpp>
#include <boost/format.hpp>
#include <boost/algorithm/string/replace.hpp>
#include <boost/program_options.hpp>
//stl
#include <iostream>
#include <fstream>
struct blob_to_hex
{
std::string operator() (const char* blob, unsigned size)
{
std::string buf;
buf.reserve(size*2);
std::ostringstream s(buf);
s.seekp(0);
char hex[3];
std::memset(hex,0,3);
for ( unsigned pos=0; pos < size; ++pos)
{
std::sprintf (hex, "%02X", int(blob[pos]) & 0xff);
s << hex;
}
return s.str();
}
};
bool valid_envelope(mapnik::Envelope<double> const& e)
{
return (e.minx() < e.maxx() && e.miny() < e.maxy()) ;
}
template <typename Connection, typename OUT>
void pgsql2sqlite(Connection conn, std::string const& table_name, OUT & out, unsigned tolerance)
{
using namespace mapnik;
boost::shared_ptr<ResultSet> rs = conn->executeQuery("select * from " + table_name + " limit 0;");
int count = rs->getNumFields();
std::ostringstream select_sql;
select_sql << "select ";
for (int i=0; i<count; ++i)
{
if (i!=0) select_sql << ",";
select_sql << "\"" << rs->getFieldName(i) << "\"";
}
select_sql << " from " << table_name ;
std::ostringstream geom_col_sql;
geom_col_sql << "select f_geometry_column,srid,type from geometry_columns ";
geom_col_sql << "where f_table_name='" << table_name << "'";
rs = conn->executeQuery(geom_col_sql.str());
int srid = -1;
std::string geom_col = "UNKNOWN";
std::string geom_type = "UNKNOWN";
if ( rs->next())
{
try
{
srid = boost::lexical_cast<int>(rs->getValue("srid"));
}
catch (boost::bad_lexical_cast &ex)
{
std::clog << ex.what() << std::endl;
}
geom_col = rs->getValue("f_geometry_column");
geom_type = rs->getValue("type");
}
// add AsBinary(<geometry_column>) modifier
std::string select_sql_str = select_sql.str();
if (tolerance > 0)
{
std::string from = "\"" + geom_col + "\"";
std::string to = (boost::format("AsBinary(Simplify(%1%,%2%)) as %1%") % geom_col % tolerance).str();
boost::algorithm::replace_all(select_sql_str,from ,to);
}
else
{
boost::algorithm::replace_all(select_sql_str, "\"" + geom_col + "\"","AsBinary(" + geom_col+") as " + geom_col);
}
std::cout << select_sql_str << "\n";
std::ostringstream cursor_sql;
std::string cursor_name("my_cursor");
cursor_sql << "DECLARE " << cursor_name << " BINARY INSENSITIVE NO SCROLL CURSOR WITH HOLD FOR " << select_sql_str << " FOR READ ONLY";
conn->execute(cursor_sql.str());
boost::shared_ptr<CursorResultSet> cursor(new CursorResultSet(conn,cursor_name,10000));
unsigned num_fields = cursor->getNumFields();
std::ostringstream create_sql;
create_sql << "create table " << table_name << "(PK_UID INTEGER PRIMARY KEY AUTOINCREMENT,";
int geometry_oid = -1;
for ( unsigned pos = 0; pos < num_fields ; ++pos)
{
if (pos > 0) create_sql << ",";
if (geom_col == cursor->getFieldName(pos))
{
geometry_oid = cursor->getTypeOID(pos);
create_sql << "'" << cursor->getFieldName(pos) << "' BLOB";
}
else
{
create_sql << "'" << cursor->getFieldName(pos) << "' TEXT";
}
}
create_sql << ");";
std::cout << "client_encoding=" << conn->client_encoding() << "\n";
std::cout << "geometry_column=" << geom_col << "(" << geom_type
<< ") srid=" << srid << " oid=" << geometry_oid << "\n";
// begin
out << "begin;\n";
out << create_sql.str() << "\n";
// spatial index sql
out << "create virtual table idx_"<< table_name << "_" << geom_col << " using rtree(pkid, xmin, xmax, ymin, ymax);\n";
blob_to_hex hex;
int pkid = 0;
while (cursor->next())
{
++pkid;
std::ostringstream insert_sql;
insert_sql << "insert into " << table_name << " values(" << pkid;
bool empty_geom = true;
for (unsigned pos=0 ; pos < num_fields; ++pos)
{
insert_sql << ",";
if (! cursor->isNull(pos))
{
int size=cursor->getFieldLength(pos);
int oid = cursor->getTypeOID(pos);
const char* buf=cursor->getValue(pos);
switch (oid)
{
case 25:
case 1042:
case 1043:
{
std::string text(buf);
boost::algorithm::replace_all(text,"'","''");
insert_sql << "'"<< text << "'";
break;
}
case 23:
insert_sql << int4net(buf);
break;
default:
{
if (oid == geometry_oid)
{
mapnik::Feature feat(pkid);
geometry_utils::from_wkb(feat,buf,size,false,wkbGeneric);
if (feat.num_geometries() > 0)
{
geometry2d const& geom=feat.get_geometry(0);
Envelope<double> bbox = geom.envelope();
if (valid_envelope(bbox))
{
out << "insert into idx_" << table_name << "_" << geom_col << " values (" ;
out << pkid << "," << bbox.minx() << "," << bbox.maxx();
out << "," << bbox.miny() << "," << bbox.maxy() << ");\n";
empty_geom = false;
}
}
insert_sql << "X'" << hex(buf,size) << "'";
}
else
{
insert_sql << "NULL";
}
break;
}
}
}
else
{
insert_sql << "NULL";
}
}
insert_sql << ");";
if (!empty_geom) out << insert_sql.str() << "\n";
if (pkid % 1000 == 0)
{
std::cout << "\r processing " << pkid << " features";
std::cout.flush();
}
if (pkid % 100000 == 0)
{
out << "commit;\n";
out << "begin;\n";
}
}
// commit
out << "commit;\n";
std::cout << "\r processed " << pkid << " features";
std::cout << "\n Done!" << std::endl;
}
int main ( int argc, char** argv)
{
namespace po = boost::program_options;
po::options_description desc("Postgresql/PostGIS to SQLite3 converter\n Options");
desc.add_options()
("help,?","Display this help screen.")
("host,h",po::value<std::string>(),"Allows you to specify connection to a database on a machine other than the default.")
("port,p",po::value<std::string>(),"Allows you to specify a database port other than the default.")
("user,u",po::value<std::string>(),"Connect to the database as the specified user.")
("dbname,d",po::value<std::string>(),"postgresql database name")
("password,P",po::value<std::string>(),"Connect to the database with the specified password.")
("table,t",po::value<std::string>(),"Name of the table to export")
("simplify,s",po::value<unsigned>(),"Use this option to reduce the complexity\nand weight of a geometry using the Douglas-Peucker algorithm.")
("file,f",po::value<std::string>(),"Use this option to specify the name of the file to create.")
;
po::positional_options_description p;
p.add("table",1);
po::variables_map vm;
try
{
po::store(po::command_line_parser(argc,argv).options(desc).positional(p).run(),vm);
po::notify(vm);
if (vm.count("help") || !vm.count("file") || !vm.count("table"))
{
std::cout << desc << "\n";
return EXIT_SUCCESS;
}
}
catch (...)
{
std::cout << desc << "\n";
return EXIT_FAILURE;
}
boost::optional<std::string> host;
boost::optional<std::string> port ;
boost::optional<std::string> dbname;
boost::optional<std::string> user;
boost::optional<std::string> password;
if (vm.count("host")) host = vm["host"].as<std::string>();
if (vm.count("port")) port = vm["port"].as<std::string>();
if (vm.count("dbname")) dbname = vm["dbname"].as<std::string>();
if (vm.count("user")) user = vm["user"].as<std::string>();
if (vm.count("password")) password = vm["password"].as<std::string>();
unsigned tolerance = 0;
if (vm.count("simplify")) tolerance = vm["simplify"].as<unsigned>();
ConnectionCreator<Connection> creator(host,port,dbname,user,password);
try
{
boost::shared_ptr<Connection> conn(creator());
std::string table_name = vm["table"].as<std::string>();
std::string output_file = vm["file"].as<std::string>();
std::ofstream file(output_file.c_str());
if (file)
{
pgsql2sqlite(conn,table_name,file,tolerance);
}
file.close();
}
catch (mapnik::datasource_exception & ex)
{
std::cerr << ex.what() << "\n";
}
return EXIT_SUCCESS;
}
<|endoftext|> |
<commit_before>/*
* Copyright 2011 Troels Blum <troels@blum.dk>
*
* This file is part of cphVB <http://code.google.com/p/cphvb/>.
*
* cphVB is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* cphVB 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 cphVB. If not, see <http://www.gnu.org/licenses/>.
*/
#include <iostream>
#include <functional>
#include <algorithm>
#include <sstream>
#include <cassert>
#include <stdexcept>
#include <cphvb.h>
#include "InstructionBatch.hpp"
#include "GenerateSourceCode.hpp"
InstructionBatch::KernelMap InstructionBatch::kernelMap = InstructionBatch::KernelMap();
InstructionBatch::InstructionBatch(cphvb_instruction* inst, const std::vector<KernelParameter*>& operands)
: arraynum(0)
, scalarnum(0)
, variablenum(0)
, float16(false)
, float64(false)
{
#ifdef STATS
gettimeofday(&createTime,NULL);
#endif
if (inst->operand[0]->ndim > 3)
throw std::runtime_error("More than 3 dimensions not supported.");
shape = std::vector<cphvb_index>(inst->operand[0]->shape, inst->operand[0]->shape + inst->operand[0]->ndim);
add(inst, operands);
}
bool InstructionBatch::shapeMatch(cphvb_intp ndim,const cphvb_index dims[])
{
int size = shape.size();
if (ndim == size)
{
for (int i = 0; i < ndim; ++i)
{
if (dims[i] != shape[i])
return false;
}
return true;
}
return false;
}
bool InstructionBatch::sameView(const cphvb_array* a, const cphvb_array* b)
{
//assumes the the views shape are the same and they have the same base
if (a == b)
return true;
if (a->start != b->start)
return false;
for (size_t i = 0; i < shape.size(); ++i)
{
if (a->stride[i] != b->stride[i])
return false;
}
return true;
}
inline int gcd(int a, int b)
{
int c = a % b;
while(c != 0)
{
a = b;
b = c;
c = a % b;
}
return b;
}
bool InstructionBatch::disjointView(const cphvb_array* a, const cphvb_array* b)
{
//assumes the the views shape are the same and they have the same base
int astart = a->start;
int bstart = b->start;
int stride = 1;
for (int i = 0; i < a->ndim; ++i)
{
stride = gcd(a->stride[i], b->stride[i]);
int as = astart / stride;
int bs = bstart / stride;
int ae = as + a->shape[i] * (a->stride[i]/stride);
int be = bs + b->shape[i] * (b->stride[i]/stride);
if (ae <= bs || be <= as)
return true;
astart %= stride;
bstart %= stride;
}
if (stride > 1 && a->start % stride != b->start % stride)
return true;
return false;
}
void InstructionBatch::add(cphvb_instruction* inst, const std::vector<KernelParameter*>& operands)
{
assert(!isScalar(operands[0]));
// Check that the shape matches
if (!shapeMatch(inst->operand[0]->ndim, inst->operand[0]->shape))
throw BatchException(0);
std::vector<bool> known(operands.size(),false);
for (size_t op = 0; op < operands.size(); ++op)
{
BaseArray* ba = dynamic_cast<BaseArray*>(operands[op]);
if (ba) // not a scalar
{
// If any operand's base is already used as output, it has to be alligned or disjoint
ArrayRange orange = output.equal_range(ba);
for (ArrayMap::iterator oit = orange.first ; oit != orange.second; ++oit)
{
if (sameView(oit->second, inst->operand[op]))
{
// Same view so we use the same cphvb_array* for it
inst->operand[op] = oit->second;
known[op] = true;
}
else if (!disjointView(oit->second, inst->operand[op]))
{
throw BatchException(0);
}
}
// If the output operans is allready used as input it has to be alligned or disjoint
ArrayRange irange = input.equal_range(ba);
for (ArrayMap::iterator iit = irange.first ; iit != irange.second; ++iit)
{
if (sameView(iit->second, inst->operand[op]))
{
// Same view so we use the same cphvb_array* for it
inst->operand[op] = iit->second;
}
else if (op == 0 && !disjointView(iit->second, inst->operand[0]))
{
throw BatchException(0);
}
}
}
}
// OK so we can accept the instruction
instructions.push_back(inst);
// Register unknow parameters
for (size_t op = 0; op < operands.size(); ++op)
{
if (!known[op])
{
std::stringstream ss;
KernelParameter* kp = operands[op];
BaseArray* ba = dynamic_cast<BaseArray*>(kp);
if (ba)
{
if (op == 0)
{
output.insert(std::make_pair(ba, inst->operand[op]));
outputList.push_back(std::make_pair(ba, inst->operand[op]));
}
else
{
input.insert(std::make_pair(ba, inst->operand[op]));
inputList.push_back(std::make_pair(ba, inst->operand[op]));
}
if (parameters.find(kp) == parameters.end())
{
ss << "a" << arraynum++;
parameters[kp] = ss.str();
parameterList.push_back(kp);
}
if (ba->type() == OCL_FLOAT64)
{
float64 = true;
}
else if (ba->type() == OCL_FLOAT16)
{
float16 = true;
}
}
else //scalar
{
ss << "s" << scalarnum++;
kernelVariables[&(inst->operand[op])] = ss.str();
parameters[kp] = ss.str();
parameterList.push_back(kp);
}
}
}
}
Kernel InstructionBatch::generateKernel(ResourceManager* resourceManager)
{
#ifdef STATS
timeval start, end;
gettimeofday(&start,NULL);
#endif
std::string code = generateCode();
#ifdef STATS
gettimeofday(&end,NULL);
resourceManager->batchSource += (end.tv_sec - start.tv_sec)*1000000.0 + (end.tv_usec - start.tv_usec);
#endif
size_t codeHash = string_hasher(code);
KernelMap::iterator kit = kernelMap.find(codeHash);
if (kit == kernelMap.end())
{
std::stringstream source, kname;
kname << "kernel" << std::hex << codeHash;
if (float16)
{
source << "#pragma OPENCL EXTENSION cl_khr_fp16 : enable\n";
}
if (float64)
{
source << "#pragma OPENCL EXTENSION cl_khr_fp64 : enable\n";
}
source << "__kernel void " << kname.str() << code;
Kernel kernel(resourceManager, shape.size(), source.str(), kname.str());
kernelMap.insert(std::make_pair(codeHash, kernel));
return kernel;
} else {
return kit->second;
}
}
void InstructionBatch::run(ResourceManager* resourceManager)
{
#ifdef STATS
timeval now;
gettimeofday(&now,NULL);
resourceManager->batchBuild += (now.tv_sec - createTime.tv_sec)*1000000.0 + (now.tv_usec - createTime.tv_usec);
#endif
if (output.begin() != output.end())
{
Kernel kernel = generateKernel(resourceManager);
Kernel::Parameters kernelParameters;
for (ParameterList::iterator pit = parameterList.begin(); pit != parameterList.end(); ++pit)
{
if (output.find(static_cast<BaseArray*>(*pit)) == output.end())
kernelParameters.push_back(std::make_pair(*pit, false));
else
kernelParameters.push_back(std::make_pair(*pit, true));
}
std::vector<size_t> globalShape;
for (int i = shape.size()-1; i>=0; --i)
globalShape.push_back(shape[i]);
kernel.call(kernelParameters, globalShape);
}
}
std::string InstructionBatch::generateCode()
{
std::stringstream source;
source << "( ";
// Add Array kernel parameters
ParameterList::iterator pit = parameterList.begin();
source << **pit << " " << parameters[*pit];
for (++pit; pit != parameterList.end(); ++pit)
{
source << "\n , " << **pit << " " << parameters[*pit];
}
source << ")\n{\n";
generateGIDSource(shape, source);
// Load input parameters
for (ArrayList::iterator iit = inputList.begin(); iit != inputList.end(); ++iit)
{
std::stringstream ss;
ss << "v" << variablenum++;
kernelVariables[iit->second] = ss.str();
source << "\t" << oclTypeStr(iit->first->type()) << " " << ss.str() << " = " <<
parameters[iit->first] << "[";
generateOffsetSource(iit->second, source);
source << "];\n";
}
// Generate code for instructions
for (std::vector<cphvb_instruction*>::iterator iit = instructions.begin(); iit != instructions.end(); ++iit)
{
std::vector<std::string> operands;
// Has the output operand been assigned a variable name?
VariableMap::iterator kvit = kernelVariables.find((*iit)->operand[0]);
if (kvit == kernelVariables.end())
{
std::stringstream ss;
ss << "v" << variablenum++;
kernelVariables[(*iit)->operand[0]] = ss.str();
operands.push_back(ss.str());
source << "\t" << oclTypeStr(oclType((*iit)->operand[0]->type)) << " " << ss.str() << ";\n";
}
else
{
operands.push_back(kvit->second);
}
// find variable names for input operands
for (int op = 1; op < cphvb_operands((*iit)->opcode); ++op)
{
if (cphvb_is_constant((*iit)->operand[op]))
operands.push_back(kernelVariables[&((*iit)->operand[op])]);
else
operands.push_back(kernelVariables[(*iit)->operand[op]]);
}
// generate source code for the instruction
generateInstructionSource((*iit)->opcode, oclType((*iit)->operand[0]->type), operands, source);
}
// Save output parameters
for (ArrayList::iterator oit = outputList.begin(); oit != outputList.end(); ++oit)
{
source << "\t" << parameters[oit->first] << "[";
generateOffsetSource(oit->second, source);
source << "] = " << kernelVariables[oit->second] << ";\n";
}
source << "}\n";
return source.str();
}
bool InstructionBatch::read(BaseArray* array)
{
if (input.find(array) == input.end())
return false;
return true;
}
bool InstructionBatch::write(BaseArray* array)
{
// if (output.find(array) == output.end())
// return false;
return true;
}
bool InstructionBatch::access(BaseArray* array)
{
return (read(array) || write(array));
}
struct Compare : public std::binary_function<std::pair<BaseArray*,cphvb_array*>,BaseArray*,bool>
{
bool operator() (const std::pair<BaseArray*,cphvb_array*> p, const BaseArray* k) const
{return (p.first==k);}
};
bool InstructionBatch::discard(BaseArray* array)
{
output.erase(array);
outputList.remove_if(std::binder2nd<Compare>(Compare(),array));
bool r = read(array);
if (!r)
{
parameters.erase(static_cast<KernelParameter*>(array));
parameterList.remove(static_cast<KernelParameter*>(array));
}
return !r;
}
<commit_msg>catch when same input is used twice and avoid loading mem twice<commit_after>/*
* Copyright 2011 Troels Blum <troels@blum.dk>
*
* This file is part of cphVB <http://code.google.com/p/cphvb/>.
*
* cphVB is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* cphVB 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 cphVB. If not, see <http://www.gnu.org/licenses/>.
*/
#include <iostream>
#include <functional>
#include <algorithm>
#include <sstream>
#include <cassert>
#include <stdexcept>
#include <cphvb.h>
#include "InstructionBatch.hpp"
#include "GenerateSourceCode.hpp"
InstructionBatch::KernelMap InstructionBatch::kernelMap = InstructionBatch::KernelMap();
InstructionBatch::InstructionBatch(cphvb_instruction* inst, const std::vector<KernelParameter*>& operands)
: arraynum(0)
, scalarnum(0)
, variablenum(0)
, float16(false)
, float64(false)
{
#ifdef STATS
gettimeofday(&createTime,NULL);
#endif
if (inst->operand[0]->ndim > 3)
throw std::runtime_error("More than 3 dimensions not supported.");
shape = std::vector<cphvb_index>(inst->operand[0]->shape, inst->operand[0]->shape + inst->operand[0]->ndim);
add(inst, operands);
}
bool InstructionBatch::shapeMatch(cphvb_intp ndim,const cphvb_index dims[])
{
int size = shape.size();
if (ndim == size)
{
for (int i = 0; i < ndim; ++i)
{
if (dims[i] != shape[i])
return false;
}
return true;
}
return false;
}
bool InstructionBatch::sameView(const cphvb_array* a, const cphvb_array* b)
{
//assumes the the views shape are the same and they have the same base
if (a == b)
return true;
if (a->start != b->start)
return false;
for (size_t i = 0; i < shape.size(); ++i)
{
if (a->stride[i] != b->stride[i])
return false;
}
return true;
}
inline int gcd(int a, int b)
{
int c = a % b;
while(c != 0)
{
a = b;
b = c;
c = a % b;
}
return b;
}
bool InstructionBatch::disjointView(const cphvb_array* a, const cphvb_array* b)
{
//assumes the the views shape are the same and they have the same base
int astart = a->start;
int bstart = b->start;
int stride = 1;
for (int i = 0; i < a->ndim; ++i)
{
stride = gcd(a->stride[i], b->stride[i]);
int as = astart / stride;
int bs = bstart / stride;
int ae = as + a->shape[i] * (a->stride[i]/stride);
int be = bs + b->shape[i] * (b->stride[i]/stride);
if (ae <= bs || be <= as)
return true;
astart %= stride;
bstart %= stride;
}
if (stride > 1 && a->start % stride != b->start % stride)
return true;
return false;
}
void InstructionBatch::add(cphvb_instruction* inst, const std::vector<KernelParameter*>& operands)
{
assert(!isScalar(operands[0]));
// Check that the shape matches
if (!shapeMatch(inst->operand[0]->ndim, inst->operand[0]->shape))
throw BatchException(0);
std::vector<bool> known(operands.size(),false);
for (size_t op = 0; op < operands.size(); ++op)
{
BaseArray* ba = dynamic_cast<BaseArray*>(operands[op]);
if (ba) // not a scalar
{
// If any operand's base is already used as output, it has to be alligned or disjoint
ArrayRange orange = output.equal_range(ba);
for (ArrayMap::iterator oit = orange.first ; oit != orange.second; ++oit)
{
if (sameView(oit->second, inst->operand[op]))
{
// Same view so we use the same cphvb_array* for it
inst->operand[op] = oit->second;
known[op] = true;
}
else if (!disjointView(oit->second, inst->operand[op]))
{
throw BatchException(0);
}
}
// If the output operans is allready used as input it has to be alligned or disjoint
ArrayRange irange = input.equal_range(ba);
for (ArrayMap::iterator iit = irange.first ; iit != irange.second; ++iit)
{
if (sameView(iit->second, inst->operand[op]))
{
// Same view so we use the same cphvb_array* for it
inst->operand[op] = iit->second;
}
else if (op == 0 && !disjointView(iit->second, inst->operand[0]))
{
throw BatchException(0);
}
}
}
}
// OK so we can accept the instruction
instructions.push_back(inst);
// Register unknow parameters
//catch when same input is used twice
if (operands.size() == 3 && cphvb_base_array(inst->operand[1]) == cphvb_base_array(inst->operand[2]))
{
if(sameView(inst->operand[1], inst->operand[2]))
{
inst->operand[2] = inst->operand[1];
known[2] = true;
}
}
for (size_t op = 0; op < operands.size(); ++op)
{
if (!known[op])
{
std::stringstream ss;
KernelParameter* kp = operands[op];
BaseArray* ba = dynamic_cast<BaseArray*>(kp);
if (ba)
{
if (op == 0)
{
output.insert(std::make_pair(ba, inst->operand[op]));
outputList.push_back(std::make_pair(ba, inst->operand[op]));
}
else
{
input.insert(std::make_pair(ba, inst->operand[op]));
inputList.push_back(std::make_pair(ba, inst->operand[op]));
}
if (parameters.find(kp) == parameters.end())
{
ss << "a" << arraynum++;
parameters[kp] = ss.str();
parameterList.push_back(kp);
}
if (ba->type() == OCL_FLOAT64)
{
float64 = true;
}
else if (ba->type() == OCL_FLOAT16)
{
float16 = true;
}
}
else //scalar
{
ss << "s" << scalarnum++;
kernelVariables[&(inst->operand[op])] = ss.str();
parameters[kp] = ss.str();
parameterList.push_back(kp);
}
}
}
}
Kernel InstructionBatch::generateKernel(ResourceManager* resourceManager)
{
#ifdef STATS
timeval start, end;
gettimeofday(&start,NULL);
#endif
std::string code = generateCode();
#ifdef STATS
gettimeofday(&end,NULL);
resourceManager->batchSource += (end.tv_sec - start.tv_sec)*1000000.0 + (end.tv_usec - start.tv_usec);
#endif
size_t codeHash = string_hasher(code);
KernelMap::iterator kit = kernelMap.find(codeHash);
if (kit == kernelMap.end())
{
std::stringstream source, kname;
kname << "kernel" << std::hex << codeHash;
if (float16)
{
source << "#pragma OPENCL EXTENSION cl_khr_fp16 : enable\n";
}
if (float64)
{
source << "#pragma OPENCL EXTENSION cl_khr_fp64 : enable\n";
}
source << "__kernel void " << kname.str() << code;
Kernel kernel(resourceManager, shape.size(), source.str(), kname.str());
kernelMap.insert(std::make_pair(codeHash, kernel));
return kernel;
} else {
return kit->second;
}
}
void InstructionBatch::run(ResourceManager* resourceManager)
{
#ifdef STATS
timeval now;
gettimeofday(&now,NULL);
resourceManager->batchBuild += (now.tv_sec - createTime.tv_sec)*1000000.0 + (now.tv_usec - createTime.tv_usec);
#endif
if (output.begin() != output.end())
{
Kernel kernel = generateKernel(resourceManager);
Kernel::Parameters kernelParameters;
for (ParameterList::iterator pit = parameterList.begin(); pit != parameterList.end(); ++pit)
{
if (output.find(static_cast<BaseArray*>(*pit)) == output.end())
kernelParameters.push_back(std::make_pair(*pit, false));
else
kernelParameters.push_back(std::make_pair(*pit, true));
}
std::vector<size_t> globalShape;
for (int i = shape.size()-1; i>=0; --i)
globalShape.push_back(shape[i]);
kernel.call(kernelParameters, globalShape);
}
}
std::string InstructionBatch::generateCode()
{
std::stringstream source;
source << "( ";
// Add Array kernel parameters
ParameterList::iterator pit = parameterList.begin();
source << **pit << " " << parameters[*pit];
for (++pit; pit != parameterList.end(); ++pit)
{
source << "\n , " << **pit << " " << parameters[*pit];
}
source << ")\n{\n";
generateGIDSource(shape, source);
// Load input parameters
for (ArrayList::iterator iit = inputList.begin(); iit != inputList.end(); ++iit)
{
std::stringstream ss;
ss << "v" << variablenum++;
kernelVariables[iit->second] = ss.str();
source << "\t" << oclTypeStr(iit->first->type()) << " " << ss.str() << " = " <<
parameters[iit->first] << "[";
generateOffsetSource(iit->second, source);
source << "];\n";
}
// Generate code for instructions
for (std::vector<cphvb_instruction*>::iterator iit = instructions.begin(); iit != instructions.end(); ++iit)
{
std::vector<std::string> operands;
// Has the output operand been assigned a variable name?
VariableMap::iterator kvit = kernelVariables.find((*iit)->operand[0]);
if (kvit == kernelVariables.end())
{
std::stringstream ss;
ss << "v" << variablenum++;
kernelVariables[(*iit)->operand[0]] = ss.str();
operands.push_back(ss.str());
source << "\t" << oclTypeStr(oclType((*iit)->operand[0]->type)) << " " << ss.str() << ";\n";
}
else
{
operands.push_back(kvit->second);
}
// find variable names for input operands
for (int op = 1; op < cphvb_operands((*iit)->opcode); ++op)
{
if (cphvb_is_constant((*iit)->operand[op]))
operands.push_back(kernelVariables[&((*iit)->operand[op])]);
else
operands.push_back(kernelVariables[(*iit)->operand[op]]);
}
// generate source code for the instruction
generateInstructionSource((*iit)->opcode, oclType((*iit)->operand[0]->type), operands, source);
}
// Save output parameters
for (ArrayList::iterator oit = outputList.begin(); oit != outputList.end(); ++oit)
{
source << "\t" << parameters[oit->first] << "[";
generateOffsetSource(oit->second, source);
source << "] = " << kernelVariables[oit->second] << ";\n";
}
source << "}\n";
return source.str();
}
bool InstructionBatch::read(BaseArray* array)
{
if (input.find(array) == input.end())
return false;
return true;
}
bool InstructionBatch::write(BaseArray* array)
{
// if (output.find(array) == output.end())
// return false;
return true;
}
bool InstructionBatch::access(BaseArray* array)
{
return (read(array) || write(array));
}
struct Compare : public std::binary_function<std::pair<BaseArray*,cphvb_array*>,BaseArray*,bool>
{
bool operator() (const std::pair<BaseArray*,cphvb_array*> p, const BaseArray* k) const
{return (p.first==k);}
};
bool InstructionBatch::discard(BaseArray* array)
{
output.erase(array);
outputList.remove_if(std::binder2nd<Compare>(Compare(),array));
bool r = read(array);
if (!r)
{
parameters.erase(static_cast<KernelParameter*>(array));
parameterList.remove(static_cast<KernelParameter*>(array));
}
return !r;
}
<|endoftext|> |
<commit_before>/*
* Copyright (C) 2011
* Alessio Sclocco <a.sclocco@vu.nl>
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 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 General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*
*/
#define __CL_ENABLE_EXCEPTIONS
#include <CL/cl.hpp>
#include <string>
#include <cstring>
#include <fstream>
#include <vector>
using std::string;
using std::ofstream;
using std::vector;
#include <utils.hpp>
#include <Exceptions.hpp>
#include <Timer.hpp>
using isa::utils::toStringValue;
using isa::Exceptions::OpenCLError;
using isa::utils::Timer;
#ifndef CL_DATA_HPP
#define CL_DATA_HPP
namespace isa {
namespace OpenCL {
template< typename T > class CLData {
public:
CLData(string name, bool deletePolicy = false);
~CLData();
inline string getName() const;
// Allocation of host data
void allocateHostData(vector < T > & data);
void allocateHostData(long long unsigned int nrElements);
void deleteHostData();
// Allocation of device data
void allocateDeviceData(cl::Buffer * data, size_t size);
void allocateDeviceData(long long unsigned int nrElements) throw (OpenCLError);
void allocateDeviceData() throw (OpenCLError);
void allocateSharedDeviceData() throw (OpenCLError);
void deleteDeviceData();
inline void setDeviceReadOnly();
inline void setDeviceWriteOnly();
inline void setDeviceReadWrite();
// Memory transfers
void copyHostToDevice(bool async = false) throw (OpenCLError);
void copyDeviceToHost(bool async = false) throw (OpenCLError);
void dumpDeviceToDisk() throw (OpenCLError);
// OpenCL
inline void setCLContext(cl::Context * context);
inline void setCLQueue(cl::CommandQueue * queue);
// Access host data
inline T * getHostData();
inline T * getHostDataAt(long long unsigned int startingPoint);
inline void * getRawHostData();
inline void * getRawHostDataAt(long long unsigned int startingPoint);
inline size_t getHostDataSize() const;
inline const T operator[](long long unsigned int item) const;
inline const T getHostDataItem(long long unsigned int item) const;
// Modify host data
inline void setHostDataItem(long long unsigned int item, T value);
// Access device data
inline cl::Buffer * getDeviceData();
inline size_t getDeviceDataSize() const;
// Timers
inline Timer & getH2DTimer();
inline Timer & getD2HTimer();
private:
cl::Context * clContext;
cl::CommandQueue * clQueue;
Timer timerH2D;
Timer timerD2H;
bool deleteHost;
bool deviceReadOnly;
bool deviceWriteOnly;
vector< T > hostData;
size_t hostDataSize;
cl::Buffer * deviceData;
size_t deviceDataSize;
string name;
};
// Implementations
template< typename T > CLData< T >::CLData(string name, bool deletePolicy) : clContext(0), clQueue(0), timerH2D(Timer("H2D")), timerD2H(Timer("D2H")), deleteHost(deletePolicy), deviceReadOnly(false), deviceWriteOnly(false), hostData(vector< T >()), hostDataSize(0), deviceData(0), deviceDataSize(0), name(name) {}
template< typename T > CLData< T >::~CLData() {
deleteHostData();
deleteDeviceData();
}
template< typename T > void CLData< T >::allocateHostData(vector< T > & data) {
hostData = data;
hostDataSize = hostData.size() * sizeof(T);
}
template< typename T > void CLData< T >::allocateHostData(long long unsigned int nrElements) {
hostData = vector< T >(nrElements, 0);
hostDataSize = nrElements * sizeof(T);
}
template< typename T > void CLData< T >::deleteHostData() {
if ( deleteHost ) {
hostData = vector< T >();
}
}
template< typename T > void CLData< T >::allocateDeviceData(cl::Buffer * data, size_t size) {
deleteDeviceData();
deviceData = data;
deviceDataSize = size;
}
template< typename T > void CLData< T >::allocateDeviceData(long long unsigned int nrElements) throw (OpenCLError) {
size_t newSize = nrElements * sizeof(T);
if ( newSize != deviceDataSize ) {
deleteDeviceData();
try {
if ( deviceReadOnly ) {
deviceData = new cl::Buffer(*clContext, CL_MEM_READ_ONLY, newSize, NULL, NULL);
} else if ( deviceWriteOnly ) {
deviceData = new cl::Buffer(*clContext, CL_MEM_WRITE_ONLY, newSize, NULL, NULL);
} else {
deviceData = new cl::Buffer(*clContext, CL_MEM_READ_WRITE, newSize, NULL, NULL);
}
} catch ( cl::Error err ) {
deviceDataSize = 0;
throw OpenCLError("Impossible to allocate " + name + " device memory: " + toStringValue< cl_int >(err.err()));
}
deviceDataSize = newSize;
}
}
template< typename T > void CLData< T >::allocateDeviceData() throw (OpenCLError) {
deleteDeviceData();
try {
if ( deviceReadOnly ) {
deviceData = new cl::Buffer(*clContext, CL_MEM_READ_ONLY, hostDataSize, NULL, NULL);
} else if ( deviceWriteOnly ) {
deviceData = new cl::Buffer(*clContext, CL_MEM_WRITE_ONLY, hostDataSize, NULL, NULL);
} else {
deviceData = new cl::Buffer(*clContext, CL_MEM_READ_WRITE, hostDataSize, NULL, NULL);
}
} catch ( cl::Error err ) {
deviceDataSize = 0;
throw OpenCLError("Impossible to allocate " + name + " device memory: " + toStringValue< cl_int >(err.err()));
}
deviceDataSize = hostDataSize;
}
template< typename T > void CLData< T >::allocateSharedDeviceData() throw (OpenCLError) {
deleteDeviceData();
try {
if ( deviceReadOnly ) {
deviceData = new cl::Buffer(*clContext, CL_MEM_USE_HOST_PTR | CL_MEM_READ_ONLY, hostDataSize, getRawHostData(), NULL);
} else if ( deviceWriteOnly ) {
deviceData = new cl::Buffer(*clContext, CL_MEM_USE_HOST_PTR | CL_MEM_WRITE_ONLY, hostDataSize, getRawHostData(), NULL);
} else {
deviceData = new cl::Buffer(*clContext, CL_MEM_USE_HOST_PTR | CL_MEM_READ_WRITE, hostDataSize, getRawHostData(), NULL);
}
} catch ( cl::Error err ) {
deviceDataSize = 0;
throw OpenCLError("Impossible to allocate " + name + " device memory: " + toStringValue< cl_int >(err.err()));
}
deviceDataSize = hostDataSize;
}
template< typename T > void CLData< T >::deleteDeviceData() {
if ( deviceDataSize != 0 ) {
delete deviceData;
deviceData = 0;
deviceDataSize = 0;
}
}
template< typename T > inline void CLData< T >::setDeviceReadOnly() {
deviceReadOnly = true;
deviceWriteOnly = false;
}
template< typename T > inline void CLData< T >::setDeviceWriteOnly() {
deviceWriteOnly = true;
deviceReadOnly = false;
}
template< typename T > inline void CLData< T >::setDeviceReadWrite() {
deviceWriteOnly = false;
deviceReadOnly = false;
}
template< typename T > void CLData< T >::copyHostToDevice(bool async) throw (OpenCLError) {
if ( hostDataSize != deviceDataSize ) {
throw OpenCLError("Impossible to copy " + name + ": different memory sizes.");
}
if ( async ) {
try {
clQueue->enqueueWriteBuffer(*deviceData, CL_FALSE, 0, deviceDataSize, getRawHostData(), NULL, NULL);
} catch ( cl::Error err ) {
throw OpenCLError("Impossible to copy " + name + " to device: " + toStringValue< cl_int >(err.err()));
}
} else {
cl::Event clEvent;
try {
timerH2D.start();
clQueue->enqueueWriteBuffer(*deviceData, CL_TRUE, 0, deviceDataSize, getRawHostData(), NULL, &clEvent);
clEvent.wait();
timerH2D.stop();
} catch ( cl::Error err ) {
timerH2D.reset();
throw OpenCLError("Impossible to copy " + name + " to device: " + toStringValue< cl_int >(err.err()));
}
}
}
template< typename T > void CLData< T >::copyDeviceToHost(bool async) throw (OpenCLError) {
if ( hostDataSize != deviceDataSize ) {
throw OpenCLError("Impossible to copy " + name + ": different memory sizes.");
}
if ( async ) {
try {
clQueue->enqueueReadBuffer(*deviceData, CL_FALSE, 0, hostDataSize, getRawHostData(), NULL, NULL);
} catch ( cl::Error err ) {
throw OpenCLError("Impossible to copy " + name + " to host: " + toStringValue< cl_int >(err.err()));
}
} else {
cl::Event clEvent;
try {
timerD2H.start();
clQueue->enqueueReadBuffer(*deviceData, CL_TRUE, 0, hostDataSize, getRawHostData(), NULL, &clEvent);
clEvent.wait();
timerD2H.stop();
} catch ( cl::Error err ) {
timerD2H.reset();
throw OpenCLError("Impossible to copy " + name + " to host: " + toStringValue< cl_int >(err.err()));
}
}
}
template< typename T > void CLData< T >::dumpDeviceToDisk() throw (OpenCLError) {
CLData< T > temp = CLData< T >("temp", true);
temp.setCLContext(clContext);
temp.setCLQueue(clQueue);
temp.allocateHostData(hostData.size());
temp.allocateDeviceData(deviceData, deviceDataSize);
temp.copyDeviceToHost();
ofstream oFile(("./" + name + ".bin").c_str(), ofstream::binary);
oFile.write(reinterpret_cast< char * >(temp.getRawHostData()), temp.getHostDataSize());
oFile.close();
}
template< typename T > inline void CLData< T >::setCLContext(cl::Context * context) {
clContext = context;
}
template< typename T > inline void CLData< T >::setCLQueue(cl::CommandQueue * queue) {
clQueue = queue;
}
template< typename T > inline T * CLData< T >::getHostData() {
return hostData.data();
}
template< typename T > inline T * CLData< T >::getHostDataAt(long long unsigned int startingPoint) {
return hostData.data() + startingPoint;
}
template< typename T > inline void * CLData< T >::getRawHostData() {
return reinterpret_cast< void * >(hostData.data());
}
template< typename T > inline void * CLData< T >::getRawHostDataAt(long long unsigned int startingPoint) {
return reinterpret_cast< void * >(hostData.data() + startingPoint);
}
template< typename T > inline size_t CLData< T >::getHostDataSize() const {
return hostDataSize;
}
template< typename T > inline const T CLData< T >::operator[](long long unsigned int item) const {
return hostData[item];
}
template< typename T > inline const T CLData< T >::getHostDataItem(long long unsigned int item) const {
return hostData[item];
}
template< typename T > inline cl::Buffer * CLData< T >::getDeviceData() {
return deviceData;
}
template< typename T > inline size_t CLData< T >::getDeviceDataSize() const {
return deviceDataSize;
}
template< typename T > inline void CLData< T >::setHostDataItem(long long unsigned int item, T value) {
hostData[item] = value;
}
template< typename T > inline string CLData< T >::getName() const {
return name;
}
template< typename T > inline Timer & CLData< T >::getH2DTimer() {
return timerH2D;
}
template< typename T > inline Timer & CLData< T >::getD2HTimer() {
return timerD2H;
}
} // OpenCL
} // isa
#endif // CL_DATA_HPP
<commit_msg>Added getHostDataReference to access the std::vector that contains the data on the host.<commit_after>/*
* Copyright (C) 2011
* Alessio Sclocco <a.sclocco@vu.nl>
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 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 General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*
*/
#define __CL_ENABLE_EXCEPTIONS
#include <CL/cl.hpp>
#include <string>
#include <cstring>
#include <fstream>
#include <vector>
using std::string;
using std::ofstream;
using std::vector;
#include <utils.hpp>
#include <Exceptions.hpp>
#include <Timer.hpp>
using isa::utils::toStringValue;
using isa::Exceptions::OpenCLError;
using isa::utils::Timer;
#ifndef CL_DATA_HPP
#define CL_DATA_HPP
namespace isa {
namespace OpenCL {
template< typename T > class CLData {
public:
CLData(string name, bool deletePolicy = false);
~CLData();
inline string getName() const;
// Allocation of host data
void allocateHostData(vector < T > & data);
void allocateHostData(long long unsigned int nrElements);
void deleteHostData();
// Allocation of device data
void allocateDeviceData(cl::Buffer * data, size_t size);
void allocateDeviceData(long long unsigned int nrElements) throw (OpenCLError);
void allocateDeviceData() throw (OpenCLError);
void allocateSharedDeviceData() throw (OpenCLError);
void deleteDeviceData();
inline void setDeviceReadOnly();
inline void setDeviceWriteOnly();
inline void setDeviceReadWrite();
// Memory transfers
void copyHostToDevice(bool async = false) throw (OpenCLError);
void copyDeviceToHost(bool async = false) throw (OpenCLError);
void dumpDeviceToDisk() throw (OpenCLError);
// OpenCL
inline void setCLContext(cl::Context * context);
inline void setCLQueue(cl::CommandQueue * queue);
// Access host data
inline T * getHostData();
inline T * getHostDataAt(long long unsigned int startingPoint);
inline void * getRawHostData();
inline void * getRawHostDataAt(long long unsigned int startingPoint);
inline vector< T > & getHostDataReference();
inline size_t getHostDataSize() const;
inline const T operator[](long long unsigned int item) const;
inline const T getHostDataItem(long long unsigned int item) const;
// Modify host data
inline void setHostDataItem(long long unsigned int item, T value);
// Access device data
inline cl::Buffer * getDeviceData();
inline size_t getDeviceDataSize() const;
// Timers
inline Timer & getH2DTimer();
inline Timer & getD2HTimer();
private:
cl::Context * clContext;
cl::CommandQueue * clQueue;
Timer timerH2D;
Timer timerD2H;
bool deleteHost;
bool deviceReadOnly;
bool deviceWriteOnly;
vector< T > hostData;
size_t hostDataSize;
cl::Buffer * deviceData;
size_t deviceDataSize;
string name;
};
// Implementations
template< typename T > CLData< T >::CLData(string name, bool deletePolicy) : clContext(0), clQueue(0), timerH2D(Timer("H2D")), timerD2H(Timer("D2H")), deleteHost(deletePolicy), deviceReadOnly(false), deviceWriteOnly(false), hostData(vector< T >()), hostDataSize(0), deviceData(0), deviceDataSize(0), name(name) {}
template< typename T > CLData< T >::~CLData() {
deleteHostData();
deleteDeviceData();
}
template< typename T > void CLData< T >::allocateHostData(vector< T > & data) {
hostData = data;
hostDataSize = hostData.size() * sizeof(T);
}
template< typename T > void CLData< T >::allocateHostData(long long unsigned int nrElements) {
hostData = vector< T >(nrElements, 0);
hostDataSize = nrElements * sizeof(T);
}
template< typename T > void CLData< T >::deleteHostData() {
if ( deleteHost ) {
hostData = vector< T >();
}
}
template< typename T > void CLData< T >::allocateDeviceData(cl::Buffer * data, size_t size) {
deleteDeviceData();
deviceData = data;
deviceDataSize = size;
}
template< typename T > void CLData< T >::allocateDeviceData(long long unsigned int nrElements) throw (OpenCLError) {
size_t newSize = nrElements * sizeof(T);
if ( newSize != deviceDataSize ) {
deleteDeviceData();
try {
if ( deviceReadOnly ) {
deviceData = new cl::Buffer(*clContext, CL_MEM_READ_ONLY, newSize, NULL, NULL);
} else if ( deviceWriteOnly ) {
deviceData = new cl::Buffer(*clContext, CL_MEM_WRITE_ONLY, newSize, NULL, NULL);
} else {
deviceData = new cl::Buffer(*clContext, CL_MEM_READ_WRITE, newSize, NULL, NULL);
}
} catch ( cl::Error err ) {
deviceDataSize = 0;
throw OpenCLError("Impossible to allocate " + name + " device memory: " + toStringValue< cl_int >(err.err()));
}
deviceDataSize = newSize;
}
}
template< typename T > void CLData< T >::allocateDeviceData() throw (OpenCLError) {
deleteDeviceData();
try {
if ( deviceReadOnly ) {
deviceData = new cl::Buffer(*clContext, CL_MEM_READ_ONLY, hostDataSize, NULL, NULL);
} else if ( deviceWriteOnly ) {
deviceData = new cl::Buffer(*clContext, CL_MEM_WRITE_ONLY, hostDataSize, NULL, NULL);
} else {
deviceData = new cl::Buffer(*clContext, CL_MEM_READ_WRITE, hostDataSize, NULL, NULL);
}
} catch ( cl::Error err ) {
deviceDataSize = 0;
throw OpenCLError("Impossible to allocate " + name + " device memory: " + toStringValue< cl_int >(err.err()));
}
deviceDataSize = hostDataSize;
}
template< typename T > void CLData< T >::allocateSharedDeviceData() throw (OpenCLError) {
deleteDeviceData();
try {
if ( deviceReadOnly ) {
deviceData = new cl::Buffer(*clContext, CL_MEM_USE_HOST_PTR | CL_MEM_READ_ONLY, hostDataSize, getRawHostData(), NULL);
} else if ( deviceWriteOnly ) {
deviceData = new cl::Buffer(*clContext, CL_MEM_USE_HOST_PTR | CL_MEM_WRITE_ONLY, hostDataSize, getRawHostData(), NULL);
} else {
deviceData = new cl::Buffer(*clContext, CL_MEM_USE_HOST_PTR | CL_MEM_READ_WRITE, hostDataSize, getRawHostData(), NULL);
}
} catch ( cl::Error err ) {
deviceDataSize = 0;
throw OpenCLError("Impossible to allocate " + name + " device memory: " + toStringValue< cl_int >(err.err()));
}
deviceDataSize = hostDataSize;
}
template< typename T > void CLData< T >::deleteDeviceData() {
if ( deviceDataSize != 0 ) {
delete deviceData;
deviceData = 0;
deviceDataSize = 0;
}
}
template< typename T > inline void CLData< T >::setDeviceReadOnly() {
deviceReadOnly = true;
deviceWriteOnly = false;
}
template< typename T > inline void CLData< T >::setDeviceWriteOnly() {
deviceWriteOnly = true;
deviceReadOnly = false;
}
template< typename T > inline void CLData< T >::setDeviceReadWrite() {
deviceWriteOnly = false;
deviceReadOnly = false;
}
template< typename T > void CLData< T >::copyHostToDevice(bool async) throw (OpenCLError) {
if ( hostDataSize != deviceDataSize ) {
throw OpenCLError("Impossible to copy " + name + ": different memory sizes.");
}
if ( async ) {
try {
clQueue->enqueueWriteBuffer(*deviceData, CL_FALSE, 0, deviceDataSize, getRawHostData(), NULL, NULL);
} catch ( cl::Error err ) {
throw OpenCLError("Impossible to copy " + name + " to device: " + toStringValue< cl_int >(err.err()));
}
} else {
cl::Event clEvent;
try {
timerH2D.start();
clQueue->enqueueWriteBuffer(*deviceData, CL_TRUE, 0, deviceDataSize, getRawHostData(), NULL, &clEvent);
clEvent.wait();
timerH2D.stop();
} catch ( cl::Error err ) {
timerH2D.reset();
throw OpenCLError("Impossible to copy " + name + " to device: " + toStringValue< cl_int >(err.err()));
}
}
}
template< typename T > void CLData< T >::copyDeviceToHost(bool async) throw (OpenCLError) {
if ( hostDataSize != deviceDataSize ) {
throw OpenCLError("Impossible to copy " + name + ": different memory sizes.");
}
if ( async ) {
try {
clQueue->enqueueReadBuffer(*deviceData, CL_FALSE, 0, hostDataSize, getRawHostData(), NULL, NULL);
} catch ( cl::Error err ) {
throw OpenCLError("Impossible to copy " + name + " to host: " + toStringValue< cl_int >(err.err()));
}
} else {
cl::Event clEvent;
try {
timerD2H.start();
clQueue->enqueueReadBuffer(*deviceData, CL_TRUE, 0, hostDataSize, getRawHostData(), NULL, &clEvent);
clEvent.wait();
timerD2H.stop();
} catch ( cl::Error err ) {
timerD2H.reset();
throw OpenCLError("Impossible to copy " + name + " to host: " + toStringValue< cl_int >(err.err()));
}
}
}
template< typename T > void CLData< T >::dumpDeviceToDisk() throw (OpenCLError) {
CLData< T > temp = CLData< T >("temp", true);
temp.setCLContext(clContext);
temp.setCLQueue(clQueue);
temp.allocateHostData(hostData.size());
temp.allocateDeviceData(deviceData, deviceDataSize);
temp.copyDeviceToHost();
ofstream oFile(("./" + name + ".bin").c_str(), ofstream::binary);
oFile.write(reinterpret_cast< char * >(temp.getRawHostData()), temp.getHostDataSize());
oFile.close();
}
template< typename T > inline void CLData< T >::setCLContext(cl::Context * context) {
clContext = context;
}
template< typename T > inline void CLData< T >::setCLQueue(cl::CommandQueue * queue) {
clQueue = queue;
}
template< typename T > inline T * CLData< T >::getHostData() {
return hostData.data();
}
template< typename T > inline T * CLData< T >::getHostDataAt(long long unsigned int startingPoint) {
return hostData.data() + startingPoint;
}
template< typename T > inline void * CLData< T >::getRawHostData() {
return reinterpret_cast< void * >(hostData.data());
}
template< typename T > inline void * CLData< T >::getRawHostDataAt(long long unsigned int startingPoint) {
return reinterpret_cast< void * >(hostData.data() + startingPoint);
}
template< typename T > inline size_t CLData< T >::getHostDataSize() const {
return hostDataSize;
}
template< typename T > inline vector< T > & CLData< T >::getHostDataReference() {
return hostData;
}
template< typename T > inline const T CLData< T >::operator[](long long unsigned int item) const {
return hostData[item];
}
template< typename T > inline const T CLData< T >::getHostDataItem(long long unsigned int item) const {
return hostData[item];
}
template< typename T > inline cl::Buffer * CLData< T >::getDeviceData() {
return deviceData;
}
template< typename T > inline size_t CLData< T >::getDeviceDataSize() const {
return deviceDataSize;
}
template< typename T > inline void CLData< T >::setHostDataItem(long long unsigned int item, T value) {
hostData[item] = value;
}
template< typename T > inline string CLData< T >::getName() const {
return name;
}
template< typename T > inline Timer & CLData< T >::getH2DTimer() {
return timerH2D;
}
template< typename T > inline Timer & CLData< T >::getD2HTimer() {
return timerD2H;
}
} // OpenCL
} // isa
#endif // CL_DATA_HPP
<|endoftext|> |
<commit_before>#ifndef Matrix_hpp
#define Matrix_hpp
//https://msdn.microsoft.com/ru-ru/library/f1b2td24.aspx
#include <iostream>
#include <fstream>
#include "MatrixException.hpp"
template <class MatrixT> class Matrix;
template <class MatrixT> std::istream& operator>> (std::istream& stream, Matrix<MatrixT>& matrix);
template <class MatrixT> std::ostream& operator<< (std::ostream& stream, const Matrix<MatrixT>& matrix);
template <class MatrixT = int>
class Matrix {
public:
Matrix() : lines(0), columns(0), elements(nullptr) {}
Matrix(unsigned int _lines, unsigned int _columns);
Matrix(const Matrix<MatrixT>& source_matrix);
Matrix& operator= (const Matrix& source_matrix);
void InitFromRandom();
void InitFromFile(const char *filename) throw (FileException);
MatrixT* operator[](unsigned int index) const throw (IndexException);
Matrix<MatrixT> operator+(const Matrix<MatrixT>& right_matrix) const throw (AddException);
Matrix<MatrixT> operator*(const Matrix<MatrixT>& right_matrix) const throw (MultiplyException);
bool operator==(const Matrix<MatrixT>& right_matrix) const;
bool operator!=(const Matrix<MatrixT>& right_matrix) const;
unsigned int GetNumberOfLines() const;
unsigned int GetNumberOfColumns() const;
~Matrix();
//template <class MatrixT>
friend std::istream& operator>> <>(std::istream& stream, Matrix<MatrixT>& matrix) throw (StreamException);
//template <class MatrixT>
friend std::ostream& operator<< <>(std::ostream& stream, const Matrix<MatrixT>& matrix);
private:
MatrixT **elements;
unsigned int lines, columns;
};
template <class MatrixT>
std::istream& operator>> (std::istream& stream, Matrix<MatrixT>& matrix) throw (StreamException){
for (unsigned int i = 0; i < matrix.lines; i++) {
for (unsigned int j = 0; j < matrix.columns; j++) {
if (!(stream >> matrix[i][j])) {
throw StreamException();
}
}
}
return stream;
}
template <class MatrixT>
std::ostream& operator<< (std::ostream& stream, const Matrix<MatrixT>& matrix) {
for (unsigned int i = 0; i < matrix.lines; i++) {
for (unsigned int j = 0; j < matrix.columns; j++) {
stream << matrix[i][j] << " ";
}
stream << '\n';
}
return stream;
}
template <typename MatrixT>
Matrix<MatrixT>::Matrix(unsigned int _lines, unsigned int _columns) :
lines(_lines), columns(_columns), elements(new MatrixT*[_lines]) {
for (unsigned int i = 0; i < lines; i++) {
elements[i] = new MatrixT[columns];
for (unsigned int j = 0; j < columns; j++) {
elements[i][j] = 0;
}
}
}
template <typename MatrixT>
Matrix<MatrixT>::Matrix(const Matrix<MatrixT>& source_matrix)
: lines(source_matrix.lines), columns(source_matrix.columns) {
elements = new MatrixT*[lines];
for (unsigned int i = 0; i < lines; i++) {
elements[i] = new MatrixT[columns];
for (unsigned int j = 0; j < columns; j++) {
elements[i][j] = source_matrix[i][j];
}
}
}
template <typename MatrixT>
Matrix<MatrixT>& Matrix<MatrixT>::operator= (const Matrix<MatrixT>& source_matrix) {
if (lines != source_matrix.lines || columns != source_matrix.columns) {
this -> ~Matrix();
lines = source_matrix.lines;
columns = source_matrix.columns;
elements = new int*[lines];
for (int i = 0; i < lines; i++) {
elements[i] = new int[columns];
for (int j = 0; j < columns; j++) {
elements[i][j] = source_matrix[i][j];
}
}
}
else {
for (int i = 0; i < lines; i++) {
for (int j = 0; j < columns; j++) {
elements[i][j] = source_matrix[i][j];
}
}
}
return *this;
}
template <typename MatrixT>
void Matrix<MatrixT>::InitFromRandom() {
for (int i = 0; i < lines; i++) {
for (int j = 0; j < columns; j++) {
elements[i][j] = rand() % 90 + 10;
}
}
}
template <typename MatrixT>
void Matrix<MatrixT>::InitFromFile(const char *filename) throw (FileException){
std::fstream file(filename);
if (!file) throw FileException();
file >> *this;
}
template <typename MatrixT>
MatrixT* Matrix<MatrixT>::operator[](unsigned int index) const throw (IndexException){
if (index >= lines) throw IndexException();
return elements[index];
}
template <typename MatrixT>
Matrix<MatrixT> Matrix<MatrixT>::operator+(const Matrix<MatrixT>& right_matrix) const throw (AddException){
if (columns != right_matrix.GetNumberOfColumns()
|| lines != right_matrix.GetNumberOfLines())
throw AddException();
Matrix<MatrixT> result(lines, columns);
for (int i = 0; i < lines; i++) {
for (int j = 0; j < columns; j++) {
result[i][j] = elements[i][j] + right_matrix[i][j];
}
}
return result;
}
template <typename MatrixT>
Matrix<MatrixT> Matrix<MatrixT>::operator*(const Matrix& right_matrix) const throw (MultiplyException) {
if (columns != right_matrix.lines) throw MultiplyException();
Matrix<MatrixT> result(lines, right_matrix.columns);
for (int i = 0; i < lines; i++) {
for (int j = 0; j < right_matrix.columns; j++) {
result[i][j] = 0;
for (int k = 0; k < right_matrix.lines; k++)
result[i][j] += elements[i][k] * right_matrix[k][j];
}
}
return result;
}
template<typename MatrixT>
bool Matrix<MatrixT>::operator==(const Matrix<MatrixT>& right_matrix) const
{
if (lines != right_matrix.lines || columns != right_matrix.columns) {
return false;
}
else {
for (unsigned i = 0; i < lines; i++) {
for (unsigned j = 0; j < columns; j++) {
if (operator[](i)[j] != right_matrix[i][j]) {
return false;
}
}
}
return true;
}
}
template<typename MatrixT>
bool Matrix<MatrixT>::operator!=(const Matrix<MatrixT>& right_matrix) const
{
return !(operator==(right_matrix));
}
template <typename MatrixT>
unsigned int Matrix<MatrixT>::GetNumberOfLines() const {
return lines;
}
template <typename MatrixT>
unsigned int Matrix<MatrixT>::GetNumberOfColumns() const {
return columns;
}
template <typename MatrixT>
Matrix<MatrixT>::~Matrix() {
for (unsigned int i = 0; i < lines; i++)
delete[] elements[i];
delete[] elements;
}
#endif
<commit_msg>Update Matrix.hpp<commit_after>#ifndef Matrix_hpp
#define Matrix_hpp
//https://msdn.microsoft.com/ru-ru/library/f1b2td24.aspx
#include <iostream>
#include <fstream>
#include "MatrixException.hpp"
template <class MatrixT> class Matrix;
template <class MatrixT> std::istream& operator>> (std::istream& stream, Matrix<MatrixT>& matrix) throw (StreamException);
template <class MatrixT> std::ostream& operator<< (std::ostream& stream, const Matrix<MatrixT>& matrix);
template <class MatrixT = int>
class Matrix {
public:
Matrix() : lines(0), columns(0), elements(nullptr) {}
Matrix(unsigned int _lines, unsigned int _columns);
Matrix(const Matrix<MatrixT>& source_matrix);
Matrix& operator= (const Matrix& source_matrix);
void InitFromRandom();
void InitFromFile(const char *filename) throw (FileException);
MatrixT* operator[](unsigned int index) const throw (IndexException);
Matrix<MatrixT> operator+(const Matrix<MatrixT>& right_matrix) const throw (AddException);
Matrix<MatrixT> operator*(const Matrix<MatrixT>& right_matrix) const throw (MultiplyException);
bool operator==(const Matrix<MatrixT>& right_matrix) const;
bool operator!=(const Matrix<MatrixT>& right_matrix) const;
unsigned int GetNumberOfLines() const;
unsigned int GetNumberOfColumns() const;
~Matrix();
//template <class MatrixT>
friend std::istream& operator>> <>(std::istream& stream, Matrix<MatrixT>& matrix) throw (StreamException);
//template <class MatrixT>
friend std::ostream& operator<< <>(std::ostream& stream, const Matrix<MatrixT>& matrix);
private:
MatrixT **elements;
unsigned int lines, columns;
};
template <class MatrixT>
std::istream& operator>> (std::istream& stream, Matrix<MatrixT>& matrix) throw (StreamException){
for (unsigned int i = 0; i < matrix.lines; i++) {
for (unsigned int j = 0; j < matrix.columns; j++) {
if (!(stream >> matrix[i][j])) {
throw StreamException();
}
}
}
return stream;
}
template <class MatrixT>
std::ostream& operator<< (std::ostream& stream, const Matrix<MatrixT>& matrix) {
for (unsigned int i = 0; i < matrix.lines; i++) {
for (unsigned int j = 0; j < matrix.columns; j++) {
stream << matrix[i][j] << " ";
}
stream << '\n';
}
return stream;
}
template <typename MatrixT>
Matrix<MatrixT>::Matrix(unsigned int _lines, unsigned int _columns) :
lines(_lines), columns(_columns), elements(new MatrixT*[_lines]) {
for (unsigned int i = 0; i < lines; i++) {
elements[i] = new MatrixT[columns];
for (unsigned int j = 0; j < columns; j++) {
elements[i][j] = 0;
}
}
}
template <typename MatrixT>
Matrix<MatrixT>::Matrix(const Matrix<MatrixT>& source_matrix)
: lines(source_matrix.lines), columns(source_matrix.columns) {
elements = new MatrixT*[lines];
for (unsigned int i = 0; i < lines; i++) {
elements[i] = new MatrixT[columns];
for (unsigned int j = 0; j < columns; j++) {
elements[i][j] = source_matrix[i][j];
}
}
}
template <typename MatrixT>
Matrix<MatrixT>& Matrix<MatrixT>::operator= (const Matrix<MatrixT>& source_matrix) {
if (lines != source_matrix.lines || columns != source_matrix.columns) {
this -> ~Matrix();
lines = source_matrix.lines;
columns = source_matrix.columns;
elements = new int*[lines];
for (int i = 0; i < lines; i++) {
elements[i] = new int[columns];
for (int j = 0; j < columns; j++) {
elements[i][j] = source_matrix[i][j];
}
}
}
else {
for (int i = 0; i < lines; i++) {
for (int j = 0; j < columns; j++) {
elements[i][j] = source_matrix[i][j];
}
}
}
return *this;
}
template <typename MatrixT>
void Matrix<MatrixT>::InitFromRandom() {
for (int i = 0; i < lines; i++) {
for (int j = 0; j < columns; j++) {
elements[i][j] = rand() % 90 + 10;
}
}
}
template <typename MatrixT>
void Matrix<MatrixT>::InitFromFile(const char *filename) throw (FileException){
std::fstream file(filename);
if (!file) throw FileException();
file >> *this;
}
template <typename MatrixT>
MatrixT* Matrix<MatrixT>::operator[](unsigned int index) const throw (IndexException){
if (index >= lines) throw IndexException();
return elements[index];
}
template <typename MatrixT>
Matrix<MatrixT> Matrix<MatrixT>::operator+(const Matrix<MatrixT>& right_matrix) const throw (AddException){
if (columns != right_matrix.GetNumberOfColumns()
|| lines != right_matrix.GetNumberOfLines())
throw AddException();
Matrix<MatrixT> result(lines, columns);
for (int i = 0; i < lines; i++) {
for (int j = 0; j < columns; j++) {
result[i][j] = elements[i][j] + right_matrix[i][j];
}
}
return result;
}
template <typename MatrixT>
Matrix<MatrixT> Matrix<MatrixT>::operator*(const Matrix& right_matrix) const throw (MultiplyException) {
if (columns != right_matrix.lines) throw MultiplyException();
Matrix<MatrixT> result(lines, right_matrix.columns);
for (int i = 0; i < lines; i++) {
for (int j = 0; j < right_matrix.columns; j++) {
result[i][j] = 0;
for (int k = 0; k < right_matrix.lines; k++)
result[i][j] += elements[i][k] * right_matrix[k][j];
}
}
return result;
}
template<typename MatrixT>
bool Matrix<MatrixT>::operator==(const Matrix<MatrixT>& right_matrix) const
{
if (lines != right_matrix.lines || columns != right_matrix.columns) {
return false;
}
else {
for (unsigned i = 0; i < lines; i++) {
for (unsigned j = 0; j < columns; j++) {
if (operator[](i)[j] != right_matrix[i][j]) {
return false;
}
}
}
return true;
}
}
template<typename MatrixT>
bool Matrix<MatrixT>::operator!=(const Matrix<MatrixT>& right_matrix) const
{
return !(operator==(right_matrix));
}
template <typename MatrixT>
unsigned int Matrix<MatrixT>::GetNumberOfLines() const {
return lines;
}
template <typename MatrixT>
unsigned int Matrix<MatrixT>::GetNumberOfColumns() const {
return columns;
}
template <typename MatrixT>
Matrix<MatrixT>::~Matrix() {
for (unsigned int i = 0; i < lines; i++)
delete[] elements[i];
delete[] elements;
}
#endif
<|endoftext|> |
<commit_before>/*
* Copyright 2004 The WebRTC Project Authors. All rights reserved.
*
* Use of this source code is governed by a BSD-style license
* that can be found in the LICENSE file in the root of the source
* tree. An additional intellectual property rights grant can be found
* in the file PATENTS. All contributing project authors may
* be found in the AUTHORS file in the root of the source tree.
*/
#ifdef HAVE_DBUS_GLIB
#include "webrtc/base/dbus.h"
#include <glib.h>
#include "webrtc/base/logging.h"
#include "webrtc/base/thread.h"
namespace rtc {
// Avoid static object construction/destruction on startup/shutdown.
static pthread_once_t g_dbus_init_once = PTHREAD_ONCE_INIT;
static LibDBusGlibSymbolTable *g_dbus_symbol = NULL;
// Releases DBus-Glib symbols.
static void ReleaseDBusGlibSymbol() {
if (g_dbus_symbol != NULL) {
delete g_dbus_symbol;
g_dbus_symbol = NULL;
}
}
// Loads DBus-Glib symbols.
static void InitializeDBusGlibSymbol() {
// This is thread safe.
if (NULL == g_dbus_symbol) {
g_dbus_symbol = new LibDBusGlibSymbolTable();
// Loads dbus-glib
if (NULL == g_dbus_symbol || !g_dbus_symbol->Load()) {
LOG(LS_WARNING) << "Failed to load dbus-glib symbol table.";
ReleaseDBusGlibSymbol();
} else {
// Nothing we can do if atexit() failed. Just ignore its returned value.
atexit(ReleaseDBusGlibSymbol);
}
}
}
inline static LibDBusGlibSymbolTable *GetSymbols() {
return DBusMonitor::GetDBusGlibSymbolTable();
}
// Implementation of class DBusSigMessageData
DBusSigMessageData::DBusSigMessageData(DBusMessage *message)
: TypedMessageData<DBusMessage *>(message) {
GetSymbols()->dbus_message_ref()(data());
}
DBusSigMessageData::~DBusSigMessageData() {
GetSymbols()->dbus_message_unref()(data());
}
// Implementation of class DBusSigFilter
// Builds a DBus filter string from given DBus path, interface and member.
std::string DBusSigFilter::BuildFilterString(const std::string &path,
const std::string &interface,
const std::string &member) {
std::string ret(DBUS_TYPE "='" DBUS_SIGNAL "'");
if (!path.empty()) {
ret += ("," DBUS_PATH "='");
ret += path;
ret += "'";
}
if (!interface.empty()) {
ret += ("," DBUS_INTERFACE "='");
ret += interface;
ret += "'";
}
if (!member.empty()) {
ret += ("," DBUS_MEMBER "='");
ret += member;
ret += "'";
}
return ret;
}
// Forwards the message to the given instance.
DBusHandlerResult DBusSigFilter::DBusCallback(DBusConnection *dbus_conn,
DBusMessage *message,
void *instance) {
ASSERT(instance);
if (instance) {
return static_cast<DBusSigFilter *>(instance)->Callback(message);
}
return DBUS_HANDLER_RESULT_NOT_YET_HANDLED;
}
// Posts a message to caller thread.
DBusHandlerResult DBusSigFilter::Callback(DBusMessage *message) {
if (caller_thread_) {
caller_thread_->Post(this, DSM_SIGNAL, new DBusSigMessageData(message));
}
// Don't "eat" the message here. Let it pop up.
return DBUS_HANDLER_RESULT_NOT_YET_HANDLED;
}
// From MessageHandler.
void DBusSigFilter::OnMessage(Message *message) {
if (message != NULL && DSM_SIGNAL == message->message_id) {
DBusSigMessageData *msg =
static_cast<DBusSigMessageData *>(message->pdata);
if (msg) {
ProcessSignal(msg->data());
delete msg;
}
}
}
// Definition of private class DBusMonitoringThread.
// It creates a worker-thread to listen signals on DBus. The worker-thread will
// be running in a priate GMainLoop forever until either Stop() has been invoked
// or it hits an error.
class DBusMonitor::DBusMonitoringThread : public rtc::Thread {
public:
explicit DBusMonitoringThread(DBusMonitor *monitor,
GMainContext *context,
GMainLoop *mainloop,
std::vector<DBusSigFilter *> *filter_list)
: monitor_(monitor),
context_(context),
mainloop_(mainloop),
connection_(NULL),
idle_source_(NULL),
filter_list_(filter_list) {
ASSERT(monitor_);
ASSERT(context_);
ASSERT(mainloop_);
ASSERT(filter_list_);
}
virtual ~DBusMonitoringThread() {
Stop();
}
// Override virtual method of Thread. Context: worker-thread.
virtual void Run() {
ASSERT(NULL == connection_);
// Setup DBus connection and start monitoring.
monitor_->OnMonitoringStatusChanged(DMS_INITIALIZING);
if (!Setup()) {
LOG(LS_ERROR) << "DBus monitoring setup failed.";
monitor_->OnMonitoringStatusChanged(DMS_FAILED);
CleanUp();
return;
}
monitor_->OnMonitoringStatusChanged(DMS_RUNNING);
g_main_loop_run(mainloop_);
monitor_->OnMonitoringStatusChanged(DMS_STOPPED);
// Done normally. Clean up DBus connection.
CleanUp();
return;
}
// Override virtual method of Thread. Context: caller-thread.
virtual void Stop() {
ASSERT(NULL == idle_source_);
// Add an idle source and let the gmainloop quit on idle.
idle_source_ = g_idle_source_new();
if (idle_source_) {
g_source_set_callback(idle_source_, &Idle, this, NULL);
g_source_attach(idle_source_, context_);
} else {
LOG(LS_ERROR) << "g_idle_source_new() failed.";
QuitGMainloop(); // Try to quit anyway.
}
Thread::Stop(); // Wait for the thread.
}
private:
// Registers all DBus filters.
void RegisterAllFilters() {
ASSERT(NULL != GetSymbols()->dbus_g_connection_get_connection()(
connection_));
for (std::vector<DBusSigFilter *>::iterator it = filter_list_->begin();
it != filter_list_->end(); ++it) {
DBusSigFilter *filter = (*it);
if (!filter) {
LOG(LS_ERROR) << "DBusSigFilter list corrupted.";
continue;
}
GetSymbols()->dbus_bus_add_match()(
GetSymbols()->dbus_g_connection_get_connection()(connection_),
filter->filter().c_str(), NULL);
if (!GetSymbols()->dbus_connection_add_filter()(
GetSymbols()->dbus_g_connection_get_connection()(connection_),
&DBusSigFilter::DBusCallback, filter, NULL)) {
LOG(LS_ERROR) << "dbus_connection_add_filter() failed."
<< "Filter: " << filter->filter();
continue;
}
}
}
// Unregisters all DBus filters.
void UnRegisterAllFilters() {
ASSERT(NULL != GetSymbols()->dbus_g_connection_get_connection()(
connection_));
for (std::vector<DBusSigFilter *>::iterator it = filter_list_->begin();
it != filter_list_->end(); ++it) {
DBusSigFilter *filter = (*it);
if (!filter) {
LOG(LS_ERROR) << "DBusSigFilter list corrupted.";
continue;
}
GetSymbols()->dbus_connection_remove_filter()(
GetSymbols()->dbus_g_connection_get_connection()(connection_),
&DBusSigFilter::DBusCallback, filter);
}
}
// Sets up the monitoring thread.
bool Setup() {
g_main_context_push_thread_default(context_);
// Start connection to dbus.
// If dbus daemon is not running, returns false immediately.
connection_ = GetSymbols()->dbus_g_bus_get_private()(monitor_->type_,
context_, NULL);
if (NULL == connection_) {
LOG(LS_ERROR) << "dbus_g_bus_get_private() unable to get connection.";
return false;
}
if (NULL == GetSymbols()->dbus_g_connection_get_connection()(connection_)) {
LOG(LS_ERROR) << "dbus_g_connection_get_connection() returns NULL. "
<< "DBus daemon is probably not running.";
return false;
}
// Application don't exit if DBus daemon die.
GetSymbols()->dbus_connection_set_exit_on_disconnect()(
GetSymbols()->dbus_g_connection_get_connection()(connection_), FALSE);
// Connect all filters.
RegisterAllFilters();
return true;
}
// Cleans up the monitoring thread.
void CleanUp() {
if (idle_source_) {
// We did an attach() with the GSource, so we need to destroy() it.
g_source_destroy(idle_source_);
// We need to unref() the GSource to end the last reference we got.
g_source_unref(idle_source_);
idle_source_ = NULL;
}
if (connection_) {
if (GetSymbols()->dbus_g_connection_get_connection()(connection_)) {
UnRegisterAllFilters();
GetSymbols()->dbus_connection_close()(
GetSymbols()->dbus_g_connection_get_connection()(connection_));
}
GetSymbols()->dbus_g_connection_unref()(connection_);
connection_ = NULL;
}
g_main_loop_unref(mainloop_);
mainloop_ = NULL;
g_main_context_unref(context_);
context_ = NULL;
}
// Handles callback on Idle. We only add this source when ready to stop.
static gboolean Idle(gpointer data) {
static_cast<DBusMonitoringThread *>(data)->QuitGMainloop();
return TRUE;
}
// We only hit this when ready to quit.
void QuitGMainloop() {
g_main_loop_quit(mainloop_);
}
DBusMonitor *monitor_;
GMainContext *context_;
GMainLoop *mainloop_;
DBusGConnection *connection_;
GSource *idle_source_;
std::vector<DBusSigFilter *> *filter_list_;
};
// Implementation of class DBusMonitor
// Returns DBus-Glib symbol handle. Initialize it first if hasn't.
LibDBusGlibSymbolTable *DBusMonitor::GetDBusGlibSymbolTable() {
// This is multi-thread safe.
pthread_once(&g_dbus_init_once, InitializeDBusGlibSymbol);
return g_dbus_symbol;
};
// Creates an instance of DBusMonitor
DBusMonitor *DBusMonitor::Create(DBusBusType type) {
if (NULL == DBusMonitor::GetDBusGlibSymbolTable()) {
return NULL;
}
return new DBusMonitor(type);
}
DBusMonitor::DBusMonitor(DBusBusType type)
: type_(type),
status_(DMS_NOT_INITIALIZED),
monitoring_thread_(NULL) {
ASSERT(type_ == DBUS_BUS_SYSTEM || type_ == DBUS_BUS_SESSION);
}
DBusMonitor::~DBusMonitor() {
StopMonitoring();
}
bool DBusMonitor::AddFilter(DBusSigFilter *filter) {
if (monitoring_thread_) {
return false;
}
if (!filter) {
return false;
}
filter_list_.push_back(filter);
return true;
}
bool DBusMonitor::StartMonitoring() {
if (!monitoring_thread_) {
g_type_init();
g_thread_init(NULL);
GetSymbols()->dbus_g_thread_init()();
GMainContext *context = g_main_context_new();
if (NULL == context) {
LOG(LS_ERROR) << "g_main_context_new() failed.";
return false;
}
GMainLoop *mainloop = g_main_loop_new(context, FALSE);
if (NULL == mainloop) {
LOG(LS_ERROR) << "g_main_loop_new() failed.";
g_main_context_unref(context);
return false;
}
monitoring_thread_ = new DBusMonitoringThread(this, context, mainloop,
&filter_list_);
if (monitoring_thread_ == NULL) {
LOG(LS_ERROR) << "Failed to create DBus monitoring thread.";
g_main_context_unref(context);
g_main_loop_unref(mainloop);
return false;
}
monitoring_thread_->Start();
}
return true;
}
bool DBusMonitor::StopMonitoring() {
if (monitoring_thread_) {
monitoring_thread_->Stop();
monitoring_thread_ = NULL;
}
return true;
}
DBusMonitor::DBusMonitorStatus DBusMonitor::GetStatus() {
return status_;
}
void DBusMonitor::OnMonitoringStatusChanged(DBusMonitorStatus status) {
status_ = status;
}
#undef LATE
} // namespace rtc
#endif // HAVE_DBUS_GLIB
<commit_msg>Don't call g_thread_init on glib >=2.31.0<commit_after>/*
* Copyright 2004 The WebRTC Project Authors. All rights reserved.
*
* Use of this source code is governed by a BSD-style license
* that can be found in the LICENSE file in the root of the source
* tree. An additional intellectual property rights grant can be found
* in the file PATENTS. All contributing project authors may
* be found in the AUTHORS file in the root of the source tree.
*/
#ifdef HAVE_DBUS_GLIB
#include "webrtc/base/dbus.h"
#include <glib.h>
#include "webrtc/base/logging.h"
#include "webrtc/base/thread.h"
namespace rtc {
// Avoid static object construction/destruction on startup/shutdown.
static pthread_once_t g_dbus_init_once = PTHREAD_ONCE_INIT;
static LibDBusGlibSymbolTable *g_dbus_symbol = NULL;
// Releases DBus-Glib symbols.
static void ReleaseDBusGlibSymbol() {
if (g_dbus_symbol != NULL) {
delete g_dbus_symbol;
g_dbus_symbol = NULL;
}
}
// Loads DBus-Glib symbols.
static void InitializeDBusGlibSymbol() {
// This is thread safe.
if (NULL == g_dbus_symbol) {
g_dbus_symbol = new LibDBusGlibSymbolTable();
// Loads dbus-glib
if (NULL == g_dbus_symbol || !g_dbus_symbol->Load()) {
LOG(LS_WARNING) << "Failed to load dbus-glib symbol table.";
ReleaseDBusGlibSymbol();
} else {
// Nothing we can do if atexit() failed. Just ignore its returned value.
atexit(ReleaseDBusGlibSymbol);
}
}
}
inline static LibDBusGlibSymbolTable *GetSymbols() {
return DBusMonitor::GetDBusGlibSymbolTable();
}
// Implementation of class DBusSigMessageData
DBusSigMessageData::DBusSigMessageData(DBusMessage *message)
: TypedMessageData<DBusMessage *>(message) {
GetSymbols()->dbus_message_ref()(data());
}
DBusSigMessageData::~DBusSigMessageData() {
GetSymbols()->dbus_message_unref()(data());
}
// Implementation of class DBusSigFilter
// Builds a DBus filter string from given DBus path, interface and member.
std::string DBusSigFilter::BuildFilterString(const std::string &path,
const std::string &interface,
const std::string &member) {
std::string ret(DBUS_TYPE "='" DBUS_SIGNAL "'");
if (!path.empty()) {
ret += ("," DBUS_PATH "='");
ret += path;
ret += "'";
}
if (!interface.empty()) {
ret += ("," DBUS_INTERFACE "='");
ret += interface;
ret += "'";
}
if (!member.empty()) {
ret += ("," DBUS_MEMBER "='");
ret += member;
ret += "'";
}
return ret;
}
// Forwards the message to the given instance.
DBusHandlerResult DBusSigFilter::DBusCallback(DBusConnection *dbus_conn,
DBusMessage *message,
void *instance) {
ASSERT(instance);
if (instance) {
return static_cast<DBusSigFilter *>(instance)->Callback(message);
}
return DBUS_HANDLER_RESULT_NOT_YET_HANDLED;
}
// Posts a message to caller thread.
DBusHandlerResult DBusSigFilter::Callback(DBusMessage *message) {
if (caller_thread_) {
caller_thread_->Post(this, DSM_SIGNAL, new DBusSigMessageData(message));
}
// Don't "eat" the message here. Let it pop up.
return DBUS_HANDLER_RESULT_NOT_YET_HANDLED;
}
// From MessageHandler.
void DBusSigFilter::OnMessage(Message *message) {
if (message != NULL && DSM_SIGNAL == message->message_id) {
DBusSigMessageData *msg =
static_cast<DBusSigMessageData *>(message->pdata);
if (msg) {
ProcessSignal(msg->data());
delete msg;
}
}
}
// Definition of private class DBusMonitoringThread.
// It creates a worker-thread to listen signals on DBus. The worker-thread will
// be running in a priate GMainLoop forever until either Stop() has been invoked
// or it hits an error.
class DBusMonitor::DBusMonitoringThread : public rtc::Thread {
public:
explicit DBusMonitoringThread(DBusMonitor *monitor,
GMainContext *context,
GMainLoop *mainloop,
std::vector<DBusSigFilter *> *filter_list)
: monitor_(monitor),
context_(context),
mainloop_(mainloop),
connection_(NULL),
idle_source_(NULL),
filter_list_(filter_list) {
ASSERT(monitor_);
ASSERT(context_);
ASSERT(mainloop_);
ASSERT(filter_list_);
}
virtual ~DBusMonitoringThread() {
Stop();
}
// Override virtual method of Thread. Context: worker-thread.
virtual void Run() {
ASSERT(NULL == connection_);
// Setup DBus connection and start monitoring.
monitor_->OnMonitoringStatusChanged(DMS_INITIALIZING);
if (!Setup()) {
LOG(LS_ERROR) << "DBus monitoring setup failed.";
monitor_->OnMonitoringStatusChanged(DMS_FAILED);
CleanUp();
return;
}
monitor_->OnMonitoringStatusChanged(DMS_RUNNING);
g_main_loop_run(mainloop_);
monitor_->OnMonitoringStatusChanged(DMS_STOPPED);
// Done normally. Clean up DBus connection.
CleanUp();
return;
}
// Override virtual method of Thread. Context: caller-thread.
virtual void Stop() {
ASSERT(NULL == idle_source_);
// Add an idle source and let the gmainloop quit on idle.
idle_source_ = g_idle_source_new();
if (idle_source_) {
g_source_set_callback(idle_source_, &Idle, this, NULL);
g_source_attach(idle_source_, context_);
} else {
LOG(LS_ERROR) << "g_idle_source_new() failed.";
QuitGMainloop(); // Try to quit anyway.
}
Thread::Stop(); // Wait for the thread.
}
private:
// Registers all DBus filters.
void RegisterAllFilters() {
ASSERT(NULL != GetSymbols()->dbus_g_connection_get_connection()(
connection_));
for (std::vector<DBusSigFilter *>::iterator it = filter_list_->begin();
it != filter_list_->end(); ++it) {
DBusSigFilter *filter = (*it);
if (!filter) {
LOG(LS_ERROR) << "DBusSigFilter list corrupted.";
continue;
}
GetSymbols()->dbus_bus_add_match()(
GetSymbols()->dbus_g_connection_get_connection()(connection_),
filter->filter().c_str(), NULL);
if (!GetSymbols()->dbus_connection_add_filter()(
GetSymbols()->dbus_g_connection_get_connection()(connection_),
&DBusSigFilter::DBusCallback, filter, NULL)) {
LOG(LS_ERROR) << "dbus_connection_add_filter() failed."
<< "Filter: " << filter->filter();
continue;
}
}
}
// Unregisters all DBus filters.
void UnRegisterAllFilters() {
ASSERT(NULL != GetSymbols()->dbus_g_connection_get_connection()(
connection_));
for (std::vector<DBusSigFilter *>::iterator it = filter_list_->begin();
it != filter_list_->end(); ++it) {
DBusSigFilter *filter = (*it);
if (!filter) {
LOG(LS_ERROR) << "DBusSigFilter list corrupted.";
continue;
}
GetSymbols()->dbus_connection_remove_filter()(
GetSymbols()->dbus_g_connection_get_connection()(connection_),
&DBusSigFilter::DBusCallback, filter);
}
}
// Sets up the monitoring thread.
bool Setup() {
g_main_context_push_thread_default(context_);
// Start connection to dbus.
// If dbus daemon is not running, returns false immediately.
connection_ = GetSymbols()->dbus_g_bus_get_private()(monitor_->type_,
context_, NULL);
if (NULL == connection_) {
LOG(LS_ERROR) << "dbus_g_bus_get_private() unable to get connection.";
return false;
}
if (NULL == GetSymbols()->dbus_g_connection_get_connection()(connection_)) {
LOG(LS_ERROR) << "dbus_g_connection_get_connection() returns NULL. "
<< "DBus daemon is probably not running.";
return false;
}
// Application don't exit if DBus daemon die.
GetSymbols()->dbus_connection_set_exit_on_disconnect()(
GetSymbols()->dbus_g_connection_get_connection()(connection_), FALSE);
// Connect all filters.
RegisterAllFilters();
return true;
}
// Cleans up the monitoring thread.
void CleanUp() {
if (idle_source_) {
// We did an attach() with the GSource, so we need to destroy() it.
g_source_destroy(idle_source_);
// We need to unref() the GSource to end the last reference we got.
g_source_unref(idle_source_);
idle_source_ = NULL;
}
if (connection_) {
if (GetSymbols()->dbus_g_connection_get_connection()(connection_)) {
UnRegisterAllFilters();
GetSymbols()->dbus_connection_close()(
GetSymbols()->dbus_g_connection_get_connection()(connection_));
}
GetSymbols()->dbus_g_connection_unref()(connection_);
connection_ = NULL;
}
g_main_loop_unref(mainloop_);
mainloop_ = NULL;
g_main_context_unref(context_);
context_ = NULL;
}
// Handles callback on Idle. We only add this source when ready to stop.
static gboolean Idle(gpointer data) {
static_cast<DBusMonitoringThread *>(data)->QuitGMainloop();
return TRUE;
}
// We only hit this when ready to quit.
void QuitGMainloop() {
g_main_loop_quit(mainloop_);
}
DBusMonitor *monitor_;
GMainContext *context_;
GMainLoop *mainloop_;
DBusGConnection *connection_;
GSource *idle_source_;
std::vector<DBusSigFilter *> *filter_list_;
};
// Implementation of class DBusMonitor
// Returns DBus-Glib symbol handle. Initialize it first if hasn't.
LibDBusGlibSymbolTable *DBusMonitor::GetDBusGlibSymbolTable() {
// This is multi-thread safe.
pthread_once(&g_dbus_init_once, InitializeDBusGlibSymbol);
return g_dbus_symbol;
};
// Creates an instance of DBusMonitor
DBusMonitor *DBusMonitor::Create(DBusBusType type) {
if (NULL == DBusMonitor::GetDBusGlibSymbolTable()) {
return NULL;
}
return new DBusMonitor(type);
}
DBusMonitor::DBusMonitor(DBusBusType type)
: type_(type),
status_(DMS_NOT_INITIALIZED),
monitoring_thread_(NULL) {
ASSERT(type_ == DBUS_BUS_SYSTEM || type_ == DBUS_BUS_SESSION);
}
DBusMonitor::~DBusMonitor() {
StopMonitoring();
}
bool DBusMonitor::AddFilter(DBusSigFilter *filter) {
if (monitoring_thread_) {
return false;
}
if (!filter) {
return false;
}
filter_list_.push_back(filter);
return true;
}
bool DBusMonitor::StartMonitoring() {
if (!monitoring_thread_) {
g_type_init();
// g_thread_init API is deprecated since glib 2.31.0, see release note:
// http://mail.gnome.org/archives/gnome-announce-list/2011-October/msg00041.html
#if !GLIB_CHECK_VERSION(2, 31, 0)
g_thread_init(NULL);
#endif
GetSymbols()->dbus_g_thread_init()();
GMainContext *context = g_main_context_new();
if (NULL == context) {
LOG(LS_ERROR) << "g_main_context_new() failed.";
return false;
}
GMainLoop *mainloop = g_main_loop_new(context, FALSE);
if (NULL == mainloop) {
LOG(LS_ERROR) << "g_main_loop_new() failed.";
g_main_context_unref(context);
return false;
}
monitoring_thread_ = new DBusMonitoringThread(this, context, mainloop,
&filter_list_);
if (monitoring_thread_ == NULL) {
LOG(LS_ERROR) << "Failed to create DBus monitoring thread.";
g_main_context_unref(context);
g_main_loop_unref(mainloop);
return false;
}
monitoring_thread_->Start();
}
return true;
}
bool DBusMonitor::StopMonitoring() {
if (monitoring_thread_) {
monitoring_thread_->Stop();
monitoring_thread_ = NULL;
}
return true;
}
DBusMonitor::DBusMonitorStatus DBusMonitor::GetStatus() {
return status_;
}
void DBusMonitor::OnMonitoringStatusChanged(DBusMonitorStatus status) {
status_ = status;
}
#undef LATE
} // namespace rtc
#endif // HAVE_DBUS_GLIB
<|endoftext|> |
<commit_before>//+ Fitting 1-D histograms with cmaes
// Author: L. Moneta 10/2005
// Author: E. Benazera 05/2014
/**********************************************************************
* *
* Copyright (c) 2014 INRIA *
* Copyright (c) 2005 ROOT Foundation, CERN/PH-SFT *
* *
**********************************************************************/
#include "TH1.h"
#include "TF1.h"
#include "TCanvas.h"
#include "TStopwatch.h"
#include "TSystem.h"
#include "TRandom3.h"
#include "TVirtualFitter.h"
#include "TPaveLabel.h"
#include "TStyle.h"
#include "TMath.h"
#include "TROOT.h"
#include "TFrame.h"
#include "TSystem.h"
//#include "Fit/FitConfig.h"
TF1 *fitFcn;
TH1 *histo;
bool libloaded = false;
// Quadratic background function
Double_t background(Double_t *x, Double_t *par) {
return par[0] + par[1]*x[0] + par[2]*x[0]*x[0];
}
// Lorenzian Peak function
Double_t lorentzianPeak(Double_t *x, Double_t *par) {
return (0.5*par[0]*par[1]/TMath::Pi()) /
TMath::Max( 1.e-10,(x[0]-par[2])*(x[0]-par[2]) + .25*par[1]*par[1]);
}
// Sum of background and peak function
Double_t fitFunction(Double_t *x, Double_t *par) {
return background(x,par) + lorentzianPeak(x,&par[3]);
}
void DoFit(const char* fitter, TVirtualPad *pad, Int_t npass) {
printf("\n*********************************************************************************\n");
printf("\t %s \n",fitter);
printf("*********************************************************************************\n");
gRandom = new TRandom3();
TStopwatch timer;
// timer.Start();
TVirtualFitter::SetDefaultFitter(fitter);
//ROOT::Fit::FitConfig::SetDefaultMinimizer(fitter);
ROOT::Math::IOptions &opts = ROOT::Math::MinimizerOptions::Default(fitter);
opts.SetIntValue("lambda",100);
pad->SetGrid();
pad->SetLogy();
fitFcn->SetParameters(1,1,1,6,.03,1);
fitFcn->Update();
std::string title = std::string(fitter) + " fit bench";
histo = new TH1D(fitter,title.c_str(),200,0,3);
timer.Start();
for (Int_t pass=0;pass<npass;pass++) {
if (pass%100 == 0) printf("pass : %d\n",pass);
fitFcn->SetParameters(1,1,1,6,.03,1);
for (Int_t i=0;i<5000;i++) {
histo->Fill(fitFcn->GetRandom());
}
//histo->Print("all");
histo->Fit(fitFcn,"Q0"); // from TH1.cxx: Q: quiet, 0: do not plot
}
histo->Fit(fitFcn,"V"); // E: use Minos, V: verbose.
timer.Stop();
(histo->GetFunction("fitFcn"))->SetLineColor(kRed+3);
gPad->SetFillColor(kYellow-10);
Double_t cputime = timer.CpuTime();
printf("%s, npass=%d : RT=%7.3f s, Cpu=%7.3f s\n",fitter,npass,timer.RealTime(),cputime);
TPaveLabel *p = new TPaveLabel(0.45,0.7,0.88,0.8,Form("%s CPU= %g s",fitter,cputime),"brNDC");
p->Draw();
p->SetTextColor(kRed+3);
p->SetFillColor(kYellow-8);
pad->Update();
}
void cmaesFitBench(Int_t npass=20) {
if (!libloaded)
{
gSystem->Load("/usr/lib/x86_64-linux-gnu/libglog.so");
gSystem->Load("/usr/lib/x86_64-linux-gnu/libgflags.so");
libloaded = true;
}
TH1::AddDirectory(kFALSE);
TCanvas *c1 = new TCanvas("FitBench","Fitting Demo",10,10,900,900);
c1->Divide(2,2);
c1->SetFillColor(kYellow-9);
// create a TF1 with the range from 0 to 3 and 6 parameters
fitFcn = new TF1("fitFcn",fitFunction,0,3,6);
fitFcn->SetNpx(200);
gStyle->SetOptFit();
gStyle->SetStatY(0.6);
//with Minuit2
c1->cd(1);
DoFit("Minuit2",gPad,npass);
//with Fumili
c1->cd(2);
DoFit("Fumili",gPad,npass);
//with cmaes
c1->cd(3);
DoFit("cmaes",gPad,npass);
//with acmaes
c1->cd(4);
DoFit("acmaes",gPad,npass);
//c1->SaveAs("FitBench.root");
}
<commit_msg>updated CMA-ES lorentz tutorial with control of sigma and lambda<commit_after>//+ Fitting 1-D histograms with cmaes
// Author: L. Moneta 10/2005
// Author: E. Benazera 05/2014
/**********************************************************************
* *
* Copyright (c) 2014 INRIA *
* Copyright (c) 2005 ROOT Foundation, CERN/PH-SFT *
* *
**********************************************************************/
#include "TH1.h"
#include "TF1.h"
#include "TCanvas.h"
#include "TStopwatch.h"
#include "TSystem.h"
#include "TRandom3.h"
#include "TVirtualFitter.h"
#include "TPaveLabel.h"
#include "TStyle.h"
#include "TMath.h"
#include "TROOT.h"
#include "TFrame.h"
#include "TSystem.h"
//#include "Fit/FitConfig.h"
TF1 *fitFcn;
TH1 *histo;
bool libloaded = false;
// Quadratic background function
Double_t background(Double_t *x, Double_t *par) {
return par[0] + par[1]*x[0] + par[2]*x[0]*x[0];
}
// Lorenzian Peak function
Double_t lorentzianPeak(Double_t *x, Double_t *par) {
return (0.5*par[0]*par[1]/TMath::Pi()) /
TMath::Max( 1.e-10,(x[0]-par[2])*(x[0]-par[2]) + .25*par[1]*par[1]);
}
// Sum of background and peak function
Double_t fitFunction(Double_t *x, Double_t *par) {
return background(x,par) + lorentzianPeak(x,&par[3]);
}
void DoFit(const char* fitter, TVirtualPad *pad, Int_t npass, Double_t sigma, Int_t lambda) {
printf("\n*********************************************************************************\n");
printf("\t %s \n",fitter);
printf("*********************************************************************************\n");
gRandom = new TRandom3();
TStopwatch timer;
// timer.Start();
TVirtualFitter::SetDefaultFitter(fitter);
//ROOT::Fit::FitConfig::SetDefaultMinimizer(fitter);
ROOT::Math::IOptions &opts = ROOT::Math::MinimizerOptions::Default(fitter);
opts.SetIntValue("lambda",lambda);
opts.SetIntValue("lscaling",1);
opts.SetRealValue("sigma",sigma);
pad->SetGrid();
pad->SetLogy();
fitFcn->SetParameters(1,1,1,6,.03,1);
fitFcn->Update();
std::string title = std::string(fitter) + " fit bench";
histo = new TH1D(fitter,title.c_str(),200,0,3);
timer.Start();
for (Int_t pass=0;pass<npass;pass++) {
if (pass%100 == 0) printf("pass : %d\n",pass);
fitFcn->SetParameters(1,1,1,6,.03,1);
for (Int_t i=0;i<5000;i++) {
histo->Fill(fitFcn->GetRandom());
}
//histo->Print("all");
//histo->Fit(fitFcn,"Q0"); // from TH1.cxx: Q: quiet, 0: do not plot
}
histo->Fit(fitFcn,"V"); // E: use Minos, V: verbose.
timer.Stop();
(histo->GetFunction("fitFcn"))->SetLineColor(kRed+3);
gPad->SetFillColor(kYellow-10);
Double_t cputime = timer.CpuTime();
printf("%s, npass=%d : RT=%7.3f s, Cpu=%7.3f s\n",fitter,npass,timer.RealTime(),cputime);
TPaveLabel *p = new TPaveLabel(0.45,0.7,0.88,0.8,Form("%s CPU= %g s",fitter,cputime),"brNDC");
p->Draw();
p->SetTextColor(kRed+3);
p->SetFillColor(kYellow-8);
pad->Update();
//delete p;
//delete histo;
delete gRandom;
}
void cmaesFitBench(Int_t npass=20, Double_t sigma=0.1, Int_t lambda=-1) {
if (!libloaded)
{
gSystem->Load("/usr/lib/x86_64-linux-gnu/libglog.so");
gSystem->Load("/usr/lib/x86_64-linux-gnu/libgflags.so");
libloaded = true;
}
TH1::AddDirectory(kFALSE);
TCanvas *c1 = new TCanvas("FitBench","Fitting Demo",10,10,900,900);
c1->Divide(2,2);
c1->SetFillColor(kYellow-9);
// create a TF1 with the range from 0 to 3 and 6 parameters
fitFcn = new TF1("fitFcn",fitFunction,0,3,6);
fitFcn->SetNpx(200);
gStyle->SetOptFit();
gStyle->SetStatY(0.6);
//with Minuit2
c1->cd(1);
DoFit("Minuit2",gPad,npass,sigma,lambda);
//with Fumili
c1->cd(2);
DoFit("Fumili",gPad,npass,sigma,lambda);
//with cmaes
c1->cd(3);
DoFit("cmaes",gPad,npass,sigma,lambda);
//with acmaes
c1->cd(4);
DoFit("acmaes",gPad,npass,sigma,lambda);
//c1->SaveAs("FitBench.root");
//delete c1;
delete fitFcn;
}
<|endoftext|> |
<commit_before>#pragma once
template<class A, class B>
class pair {
public:
A _a;
B _b;
pair(const A &a, const B &b) : _a(a), _b(b) {}
bool operator==(const pair<A, B> &other) {
return _a == other._a && _b == other._b;
}
};
template<int N>
class strbuf {
public:
char _buf[N];
strbuf(const char *s) {
strncpy(_buf, s, N);
}
bool operator==(const strbuf<N> &other) {
return !strncmp(_buf, other._buf, N);
}
};
template<class A, class B>
pair<A, B>
mkpair(const A &a, const B &b)
{
return pair<A, B>(a, b);
}
class scoped_acquire {
private:
spinlock *_l;
public:
scoped_acquire(spinlock *l) : _l(0) { acquire(l); }
~scoped_acquire() { release(); }
void release() { if (_l) { ::release(_l); _l = 0; } }
void acquire(spinlock *l) { assert(!_l); ::acquire(l); _l = l; }
};
namespace std {
template<class T>
struct remove_reference
{ typedef T type; };
template<class T>
struct remove_reference<T&>
{ typedef T type; };
template<class T>
struct remove_reference<T&&>
{ typedef T type; };
template<class T>
typename remove_reference<T>::type&&
move(T&& a)
{
return static_cast<typename remove_reference<T>::type&&>(a);
}
struct ostream { int next_width; };
extern ostream cout;
static inline
ostream& operator<<(ostream &s, const char *str) {
if (!str)
str = "(null)";
int len = strlen(str);
cprintf("%s", str);
while (len < s.next_width) {
cprintf(" ");
len++;
}
s.next_width = 0;
return s;
}
static inline
ostream& operator<<(ostream &s, u32 v) {
char buf[32];
snprintf(buf, sizeof(buf), "%d", v);
return s << buf;
}
static inline
ostream& operator<<(ostream &s, u64 v) {
char buf[32];
snprintf(buf, sizeof(buf), "%ld", v);
return s << buf;
}
static inline
ostream& operator<<(ostream &s, ostream& (*xform)(ostream&)) {
return xform(s);
}
static inline ostream& endl(ostream &s) { s << "\n"; return s; }
static inline ostream& left(ostream &s) { return s; }
struct ssetw { int _n; };
static inline ssetw setw(int n) { return { n }; }
static inline
ostream& operator<<(ostream &s, const ssetw &sw) {
s.next_width = sw._n;
return s;
}
}
/* C++ runtime */
// void *operator new(unsigned long nbytes);
// void *operator new(unsigned long nbytes, void *buf);
void *operator new[](unsigned long nbytes);
// void operator delete(void *p);
void operator delete[](void *p);
/* Ref: http://sourcery.mentor.com/public/cxx-abi/abi.html */
extern "C" void __cxa_pure_virtual(void);
extern "C" int __cxa_guard_acquire(s64 *guard_object);
extern "C" void __cxa_guard_release(s64 *guard_object);
extern "C" void __cxa_guard_abort(s64 *guard_object);
extern "C" int __cxa_atexit(void (*f)(void *), void *p, void *d);
extern void *__dso_handle;
#define NEW_DELETE_OPS(classname) \
static void* operator new(unsigned long nbytes) { \
assert(nbytes == sizeof(classname)); \
return kmalloc(sizeof(classname)); \
} \
\
static void operator delete(void *p) { \
kmfree(p, sizeof(classname)); \
}
<commit_msg>placement new operators<commit_after>#pragma once
template<class A, class B>
class pair {
public:
A _a;
B _b;
pair(const A &a, const B &b) : _a(a), _b(b) {}
bool operator==(const pair<A, B> &other) {
return _a == other._a && _b == other._b;
}
};
template<int N>
class strbuf {
public:
char _buf[N];
strbuf(const char *s) {
strncpy(_buf, s, N);
}
bool operator==(const strbuf<N> &other) {
return !strncmp(_buf, other._buf, N);
}
};
template<class A, class B>
pair<A, B>
mkpair(const A &a, const B &b)
{
return pair<A, B>(a, b);
}
class scoped_acquire {
private:
spinlock *_l;
public:
scoped_acquire(spinlock *l) : _l(0) { acquire(l); }
~scoped_acquire() { release(); }
void release() { if (_l) { ::release(_l); _l = 0; } }
void acquire(spinlock *l) { assert(!_l); ::acquire(l); _l = l; }
};
namespace std {
template<class T>
struct remove_reference
{ typedef T type; };
template<class T>
struct remove_reference<T&>
{ typedef T type; };
template<class T>
struct remove_reference<T&&>
{ typedef T type; };
template<class T>
typename remove_reference<T>::type&&
move(T&& a)
{
return static_cast<typename remove_reference<T>::type&&>(a);
}
struct ostream { int next_width; };
extern ostream cout;
static inline
ostream& operator<<(ostream &s, const char *str) {
if (!str)
str = "(null)";
int len = strlen(str);
cprintf("%s", str);
while (len < s.next_width) {
cprintf(" ");
len++;
}
s.next_width = 0;
return s;
}
static inline
ostream& operator<<(ostream &s, u32 v) {
char buf[32];
snprintf(buf, sizeof(buf), "%d", v);
return s << buf;
}
static inline
ostream& operator<<(ostream &s, u64 v) {
char buf[32];
snprintf(buf, sizeof(buf), "%ld", v);
return s << buf;
}
static inline
ostream& operator<<(ostream &s, ostream& (*xform)(ostream&)) {
return xform(s);
}
static inline ostream& endl(ostream &s) { s << "\n"; return s; }
static inline ostream& left(ostream &s) { return s; }
struct ssetw { int _n; };
static inline ssetw setw(int n) { return { n }; }
static inline
ostream& operator<<(ostream &s, const ssetw &sw) {
s.next_width = sw._n;
return s;
}
}
/* C++ runtime */
// void *operator new(unsigned long nbytes);
// void *operator new(unsigned long nbytes, void *buf);
void *operator new[](unsigned long nbytes);
// void operator delete(void *p);
void operator delete[](void *p);
/* Ref: http://sourcery.mentor.com/public/cxx-abi/abi.html */
extern "C" void __cxa_pure_virtual(void);
extern "C" int __cxa_guard_acquire(s64 *guard_object);
extern "C" void __cxa_guard_release(s64 *guard_object);
extern "C" void __cxa_guard_abort(s64 *guard_object);
extern "C" int __cxa_atexit(void (*f)(void *), void *p, void *d);
extern void *__dso_handle;
#define NEW_DELETE_OPS(classname) \
static void* operator new(unsigned long nbytes) { \
assert(nbytes == sizeof(classname)); \
return kmalloc(sizeof(classname)); \
} \
\
static void* operator new(unsigned long nbytes, classname *buf) { \
assert(nbytes == sizeof(classname)); \
return buf; \
} \
\
static void operator delete(void *p) { \
kmfree(p, sizeof(classname)); \
}
<|endoftext|> |
<commit_before>//-----------------------------------------------------------------------------
// Copyright 2012-2016 Masanori Morise. All Rights Reserved.
// Author: mmorise [at] yamanashi.ac.jp (Masanori Morise)
//
// Spectral envelope estimation on the basis of the idea of CheapTrick.
//-----------------------------------------------------------------------------
#include "./cheaptrick.h"
#include <math.h>
#include "./common.h"
#include "./constantnumbers.h"
#include "./matlabfunctions.h"
namespace {
//-----------------------------------------------------------------------------
// SmoothingWithRecovery() carries out the spectral smoothing and spectral
// recovery on the Cepstrum domain.
//-----------------------------------------------------------------------------
void SmoothingWithRecovery(double current_f0, int fs, int fft_size, double q1,
const ForwardRealFFT *forward_real_fft,
const InverseRealFFT *inverse_real_fft, double *spectral_envelope) {
// We can control q1 as the parameter. 2015/9/22 by M. Morise
// const double q1 = -0.09; // Please see the reference in CheapTrick.
double *smoothing_lifter = new double[fft_size];
double *compensation_lifter = new double[fft_size];
smoothing_lifter[0] = 1;
compensation_lifter[0] = (1.0 - 2.0 * q1) + 2.0 * q1;
double quefrency;
for (int i = 1; i <= forward_real_fft->fft_size / 2; ++i) {
quefrency = static_cast<double>(i) / fs;
smoothing_lifter[i] = sin(world::kPi * current_f0 * quefrency) /
(world::kPi * current_f0 * quefrency);
compensation_lifter[i] = (1.0 - 2.0 * q1) + 2.0 * q1 *
cos(2.0 * world::kPi * quefrency * current_f0);
}
for (int i = 0; i <= fft_size / 2; ++i)
forward_real_fft->waveform[i] = log(forward_real_fft->waveform[i]);
for (int i = 1; i < fft_size / 2; ++i)
forward_real_fft->waveform[fft_size - i] = forward_real_fft->waveform[i];
fft_execute(forward_real_fft->forward_fft);
for (int i = 0; i <= fft_size / 2; ++i) {
inverse_real_fft->spectrum[i][0] = forward_real_fft->spectrum[i][0] *
smoothing_lifter[i] * compensation_lifter[i] / fft_size;
inverse_real_fft->spectrum[i][1] = 0.0;
}
fft_execute(inverse_real_fft->inverse_fft);
for (int i = 0; i <= fft_size / 2; ++i)
spectral_envelope[i] = exp(inverse_real_fft->waveform[i]);
delete[] smoothing_lifter;
delete[] compensation_lifter;
}
//-----------------------------------------------------------------------------
// GetPowerSpectrum() calculates the power_spectrum with DC correction.
// DC stands for Direct Current. In this case, the component from 0 to F0 Hz
// is corrected.
//-----------------------------------------------------------------------------
void GetPowerSpectrum(int fs, double current_f0, int fft_size,
const ForwardRealFFT *forward_real_fft) {
int half_window_length = matlab_round(1.5 * fs / current_f0);
// FFT
for (int i = half_window_length * 2 + 1; i < fft_size; ++i)
forward_real_fft->waveform[i] = 0.0;
fft_execute(forward_real_fft->forward_fft);
// Calculation of the power spectrum.
double *power_spectrum = forward_real_fft->waveform;
for (int i = 0; i <= fft_size / 2; ++i)
power_spectrum[i] =
forward_real_fft->spectrum[i][0] * forward_real_fft->spectrum[i][0] +
forward_real_fft->spectrum[i][1] * forward_real_fft->spectrum[i][1];
// DC correction
DCCorrection(power_spectrum, current_f0, fs, fft_size, power_spectrum);
}
//-----------------------------------------------------------------------------
// SetParametersForGetWindowedWaveform()
//-----------------------------------------------------------------------------
void SetParametersForGetWindowedWaveform(int half_window_length, int x_length,
double temporal_position, int fs, double current_f0, int *base_index,
int *index, double *window) {
for (int i = -half_window_length; i <= half_window_length; ++i)
base_index[i + half_window_length] = i;
for (int i = 0; i <= half_window_length * 2; ++i)
index[i] = MyMinInt(x_length - 1, MyMaxInt(0,
matlab_round(temporal_position * fs + base_index[i])));
// Designing of the window function
double average = 0.0;
double position;
double bias = temporal_position * fs - matlab_round(temporal_position * fs);
for (int i = 0; i <= half_window_length * 2; ++i) {
position = (static_cast<double>(base_index[i]) / 1.5 + bias) / fs;
window[i] = 0.5 * cos(world::kPi * position * current_f0) + 0.5;
average += window[i] * window[i];
}
average = sqrt(average);
for (int i = 0; i <= half_window_length * 2; ++i) window[i] /= average;
}
//-----------------------------------------------------------------------------
// GetWindowedWaveform() windows the waveform by F0-adaptive window
//-----------------------------------------------------------------------------
void GetWindowedWaveform(const double *x, int x_length, int fs,
double current_f0, double temporal_position,
const ForwardRealFFT *forward_real_fft) {
int half_window_length = matlab_round(1.5 * fs / current_f0);
int *base_index = new int[half_window_length * 2 + 1];
int *index = new int[half_window_length * 2 + 1];
double *window = new double[half_window_length * 2 + 1];
SetParametersForGetWindowedWaveform(half_window_length, x_length,
temporal_position, fs, current_f0, base_index, index, window);
// F0-adaptive windowing
double *waveform = forward_real_fft->waveform;
for (int i = 0; i <= half_window_length * 2; ++i)
waveform[i] = x[index[i]] * window[i] + randn() * 0.000000000000001;
double tmp_weight1 = 0;
double tmp_weight2 = 0;
for (int i = 0; i <= half_window_length * 2; ++i) {
tmp_weight1 += waveform[i];
tmp_weight2 += window[i];
}
double weighting_coefficient = tmp_weight1 / tmp_weight2;
for (int i = 0; i <= half_window_length * 2; ++i)
waveform[i] -= window[i] * weighting_coefficient;
delete[] base_index;
delete[] index;
delete[] window;
}
//-----------------------------------------------------------------------------
// CheapTrickGeneralBody() calculates a spectral envelope at a temporal
// position. This function is only used in CheapTrick().
// Caution:
// forward_fft is allocated in advance to speed up the processing.
//-----------------------------------------------------------------------------
void CheapTrickGeneralBody(const double *x, int x_length, int fs,
double current_f0, int fft_size, double temporal_position, double q1,
const ForwardRealFFT *forward_real_fft,
const InverseRealFFT *inverse_real_fft, double *spectral_envelope) {
// F0-adaptive windowing
GetWindowedWaveform(x, x_length, fs, current_f0, temporal_position,
forward_real_fft);
// Calculate power spectrum with DC correction
// Note: The calculated power spectrum is stored in an array for waveform.
// In this imprementation, power spectrum is transformed by FFT (NOT IFFT).
// However, the same result is obtained.
// This is tricky but important for simple implementation.
GetPowerSpectrum(fs, current_f0, fft_size, forward_real_fft);
// Smoothing of the power (linear axis)
// forward_real_fft.waveform is the power spectrum.
LinearSmoothing(forward_real_fft->waveform, current_f0 * 2.0 / 3.0,
fs, fft_size, forward_real_fft->waveform);
// Smoothing (log axis) and spectral recovery on the cepstrum domain.
SmoothingWithRecovery(current_f0, fs, fft_size, q1, forward_real_fft,
inverse_real_fft, spectral_envelope);
}
} // namespace
int GetFFTSizeForCheapTrick(int fs, const CheapTrickOption *option) {
return static_cast<int>(pow(2.0, 1.0 +
static_cast<int>(log(3.0 * fs / option->f0_floor + 1) / world::kLog2)));
}
void CheapTrick(const double *x, int x_length, int fs, const double *time_axis,
const double *f0, int f0_length, const CheapTrickOption *option,
double **spectrogram) {
int fft_size = GetFFTSizeForCheapTrick(fs, option);
double *spectral_envelope = new double[fft_size];
ForwardRealFFT forward_real_fft = {0};
InitializeForwardRealFFT(fft_size, &forward_real_fft);
InverseRealFFT inverse_real_fft = {0};
InitializeInverseRealFFT(fft_size, &inverse_real_fft);
double current_f0;
for (int i = 0; i < f0_length; ++i) {
current_f0 = f0[i] <= option->f0_floor ? world::kDefaultF0 : f0[i];
CheapTrickGeneralBody(x, x_length, fs, current_f0, fft_size,
time_axis[i], option->q1, &forward_real_fft, &inverse_real_fft,
spectral_envelope);
for (int j = 0; j <= fft_size / 2; ++j)
spectrogram[i][j] = spectral_envelope[j];
}
DestroyForwardRealFFT(&forward_real_fft);
DestroyInverseRealFFT(&inverse_real_fft);
delete[] spectral_envelope;
}
void InitializeCheapTrickOption(CheapTrickOption *option) {
// q1 is the parameter used for the spectral recovery.
// Since The parameter is optimized, you don't need to change the parameter.
option->q1 = -0.09;
// f0_floor and fs is used to determine fft_size;
// We strongly recommend not to change this value unless you have enough
// knowledge of the signal processing in CheapTrick.
option->f0_floor = world::kFloorF0;
}
<commit_msg>Added static keyword to functions in anonymous namespace in cheaptrick.cpp.<commit_after>//-----------------------------------------------------------------------------
// Copyright 2012-2016 Masanori Morise. All Rights Reserved.
// Author: mmorise [at] yamanashi.ac.jp (Masanori Morise)
//
// Spectral envelope estimation on the basis of the idea of CheapTrick.
//-----------------------------------------------------------------------------
#include "./cheaptrick.h"
#include <math.h>
#include "./common.h"
#include "./constantnumbers.h"
#include "./matlabfunctions.h"
namespace {
//-----------------------------------------------------------------------------
// SmoothingWithRecovery() carries out the spectral smoothing and spectral
// recovery on the Cepstrum domain.
//-----------------------------------------------------------------------------
static void SmoothingWithRecovery(double current_f0, int fs, int fft_size, double q1,
const ForwardRealFFT *forward_real_fft,
const InverseRealFFT *inverse_real_fft, double *spectral_envelope) {
// We can control q1 as the parameter. 2015/9/22 by M. Morise
// const double q1 = -0.09; // Please see the reference in CheapTrick.
double *smoothing_lifter = new double[fft_size];
double *compensation_lifter = new double[fft_size];
smoothing_lifter[0] = 1;
compensation_lifter[0] = (1.0 - 2.0 * q1) + 2.0 * q1;
double quefrency;
for (int i = 1; i <= forward_real_fft->fft_size / 2; ++i) {
quefrency = static_cast<double>(i) / fs;
smoothing_lifter[i] = sin(world::kPi * current_f0 * quefrency) /
(world::kPi * current_f0 * quefrency);
compensation_lifter[i] = (1.0 - 2.0 * q1) + 2.0 * q1 *
cos(2.0 * world::kPi * quefrency * current_f0);
}
for (int i = 0; i <= fft_size / 2; ++i)
forward_real_fft->waveform[i] = log(forward_real_fft->waveform[i]);
for (int i = 1; i < fft_size / 2; ++i)
forward_real_fft->waveform[fft_size - i] = forward_real_fft->waveform[i];
fft_execute(forward_real_fft->forward_fft);
for (int i = 0; i <= fft_size / 2; ++i) {
inverse_real_fft->spectrum[i][0] = forward_real_fft->spectrum[i][0] *
smoothing_lifter[i] * compensation_lifter[i] / fft_size;
inverse_real_fft->spectrum[i][1] = 0.0;
}
fft_execute(inverse_real_fft->inverse_fft);
for (int i = 0; i <= fft_size / 2; ++i)
spectral_envelope[i] = exp(inverse_real_fft->waveform[i]);
delete[] smoothing_lifter;
delete[] compensation_lifter;
}
//-----------------------------------------------------------------------------
// GetPowerSpectrum() calculates the power_spectrum with DC correction.
// DC stands for Direct Current. In this case, the component from 0 to F0 Hz
// is corrected.
//-----------------------------------------------------------------------------
static void GetPowerSpectrum(int fs, double current_f0, int fft_size,
const ForwardRealFFT *forward_real_fft) {
int half_window_length = matlab_round(1.5 * fs / current_f0);
// FFT
for (int i = half_window_length * 2 + 1; i < fft_size; ++i)
forward_real_fft->waveform[i] = 0.0;
fft_execute(forward_real_fft->forward_fft);
// Calculation of the power spectrum.
double *power_spectrum = forward_real_fft->waveform;
for (int i = 0; i <= fft_size / 2; ++i)
power_spectrum[i] =
forward_real_fft->spectrum[i][0] * forward_real_fft->spectrum[i][0] +
forward_real_fft->spectrum[i][1] * forward_real_fft->spectrum[i][1];
// DC correction
DCCorrection(power_spectrum, current_f0, fs, fft_size, power_spectrum);
}
//-----------------------------------------------------------------------------
// SetParametersForGetWindowedWaveform()
//-----------------------------------------------------------------------------
static void SetParametersForGetWindowedWaveform(int half_window_length, int x_length,
double temporal_position, int fs, double current_f0, int *base_index,
int *index, double *window) {
for (int i = -half_window_length; i <= half_window_length; ++i)
base_index[i + half_window_length] = i;
for (int i = 0; i <= half_window_length * 2; ++i)
index[i] = MyMinInt(x_length - 1, MyMaxInt(0,
matlab_round(temporal_position * fs + base_index[i])));
// Designing of the window function
double average = 0.0;
double position;
double bias = temporal_position * fs - matlab_round(temporal_position * fs);
for (int i = 0; i <= half_window_length * 2; ++i) {
position = (static_cast<double>(base_index[i]) / 1.5 + bias) / fs;
window[i] = 0.5 * cos(world::kPi * position * current_f0) + 0.5;
average += window[i] * window[i];
}
average = sqrt(average);
for (int i = 0; i <= half_window_length * 2; ++i) window[i] /= average;
}
//-----------------------------------------------------------------------------
// GetWindowedWaveform() windows the waveform by F0-adaptive window
//-----------------------------------------------------------------------------
static void GetWindowedWaveform(const double *x, int x_length, int fs,
double current_f0, double temporal_position,
const ForwardRealFFT *forward_real_fft) {
int half_window_length = matlab_round(1.5 * fs / current_f0);
int *base_index = new int[half_window_length * 2 + 1];
int *index = new int[half_window_length * 2 + 1];
double *window = new double[half_window_length * 2 + 1];
SetParametersForGetWindowedWaveform(half_window_length, x_length,
temporal_position, fs, current_f0, base_index, index, window);
// F0-adaptive windowing
double *waveform = forward_real_fft->waveform;
for (int i = 0; i <= half_window_length * 2; ++i)
waveform[i] = x[index[i]] * window[i] + randn() * 0.000000000000001;
double tmp_weight1 = 0;
double tmp_weight2 = 0;
for (int i = 0; i <= half_window_length * 2; ++i) {
tmp_weight1 += waveform[i];
tmp_weight2 += window[i];
}
double weighting_coefficient = tmp_weight1 / tmp_weight2;
for (int i = 0; i <= half_window_length * 2; ++i)
waveform[i] -= window[i] * weighting_coefficient;
delete[] base_index;
delete[] index;
delete[] window;
}
//-----------------------------------------------------------------------------
// CheapTrickGeneralBody() calculates a spectral envelope at a temporal
// position. This function is only used in CheapTrick().
// Caution:
// forward_fft is allocated in advance to speed up the processing.
//-----------------------------------------------------------------------------
static void CheapTrickGeneralBody(const double *x, int x_length, int fs,
double current_f0, int fft_size, double temporal_position, double q1,
const ForwardRealFFT *forward_real_fft,
const InverseRealFFT *inverse_real_fft, double *spectral_envelope) {
// F0-adaptive windowing
GetWindowedWaveform(x, x_length, fs, current_f0, temporal_position,
forward_real_fft);
// Calculate power spectrum with DC correction
// Note: The calculated power spectrum is stored in an array for waveform.
// In this imprementation, power spectrum is transformed by FFT (NOT IFFT).
// However, the same result is obtained.
// This is tricky but important for simple implementation.
GetPowerSpectrum(fs, current_f0, fft_size, forward_real_fft);
// Smoothing of the power (linear axis)
// forward_real_fft.waveform is the power spectrum.
LinearSmoothing(forward_real_fft->waveform, current_f0 * 2.0 / 3.0,
fs, fft_size, forward_real_fft->waveform);
// Smoothing (log axis) and spectral recovery on the cepstrum domain.
SmoothingWithRecovery(current_f0, fs, fft_size, q1, forward_real_fft,
inverse_real_fft, spectral_envelope);
}
} // namespace
int GetFFTSizeForCheapTrick(int fs, const CheapTrickOption *option) {
return static_cast<int>(pow(2.0, 1.0 +
static_cast<int>(log(3.0 * fs / option->f0_floor + 1) / world::kLog2)));
}
void CheapTrick(const double *x, int x_length, int fs, const double *time_axis,
const double *f0, int f0_length, const CheapTrickOption *option,
double **spectrogram) {
int fft_size = GetFFTSizeForCheapTrick(fs, option);
double *spectral_envelope = new double[fft_size];
ForwardRealFFT forward_real_fft = {0};
InitializeForwardRealFFT(fft_size, &forward_real_fft);
InverseRealFFT inverse_real_fft = {0};
InitializeInverseRealFFT(fft_size, &inverse_real_fft);
double current_f0;
for (int i = 0; i < f0_length; ++i) {
current_f0 = f0[i] <= option->f0_floor ? world::kDefaultF0 : f0[i];
CheapTrickGeneralBody(x, x_length, fs, current_f0, fft_size,
time_axis[i], option->q1, &forward_real_fft, &inverse_real_fft,
spectral_envelope);
for (int j = 0; j <= fft_size / 2; ++j)
spectrogram[i][j] = spectral_envelope[j];
}
DestroyForwardRealFFT(&forward_real_fft);
DestroyInverseRealFFT(&inverse_real_fft);
delete[] spectral_envelope;
}
void InitializeCheapTrickOption(CheapTrickOption *option) {
// q1 is the parameter used for the spectral recovery.
// Since The parameter is optimized, you don't need to change the parameter.
option->q1 = -0.09;
// f0_floor and fs is used to determine fft_size;
// We strongly recommend not to change this value unless you have enough
// knowledge of the signal processing in CheapTrick.
option->f0_floor = world::kFloorF0;
}
<|endoftext|> |
<commit_before>#include <iostream>
#include <string>
#include <QApplication>
#include "framework/ModuleManager.hpp"
#include "framework/Configuration.hpp"
// foor Boost:
#include <boost/program_options/options_description.hpp>
#include <boost/program_options/parsers.hpp>
#include <boost/program_options/variables_map.hpp>
namespace po = boost::program_options;
using namespace std;
using namespace uipf;
string firstPart(string s);
string secondPart(string s);
string rename(string s);
// argument is a configFile
int main(int argc, char** argv){
if (argc < 2) {
std::cerr << "Usage Error, at least one argument is required!\n\n";
std::cerr << "Usage: " << argv[0] << " <configFile>"<< std::endl;
return 1;
}
// used by the module manager to access Qt components, TODO maybe move to module manager?
QApplication app (argc,argv);
ModuleManager mm;
Configuration conf;
if (string(argv[1]).compare("-c") == 0){
// run a processing chain from a config file.
// ./uipf -c example.yam
// loads the configFile and create a Configuration
string configFileName = argv[2];
conf.load(configFileName);
// only for debug, print the loaded config
conf.store("test.yaml");
} else{
// run a single module.
// ./uipf <moduleName> ...options...
//~ try {
// Declare three groups of options.
// Declare a group of options that will be allowed only on command line
po::options_description generic("Generic options");
generic.add_options()
("version,v", "print version string")
("help", "produce help message")
;
// Declare a group of options that will be
// allowed both on command line and in
// config file
po::options_description config("Configuration");
config.add_options()
("input,i", po::value< vector<string> >()->composing(), "defines an input, can be used multiple times \n format: inputName:fileName \n inputName is optional if there is only one input")
("output,o", po::value< vector<string> >()->composing(), "defines an output, can be used multiple times \n format: outputName:fileName \n outputName is optional if there is only one output \n output itself is optional, if there is only one input and one output, \n the output filename will be choosen from the input name in this case.")
("param,p", po::value< vector<string> >()->composing(), "defines a parameter, format: name:valu")
;
// Hidden options, will be allowed both on command line and
// in config file, but will not be shown to the user.
po::options_description hidden("Hidden options");
hidden.add_options()
("modulename,m", po::value< string>(), "defines the name of the module")
;
// These two lines say that all positional options should be translated into "-modulename" options.
po::positional_options_description p;
p.add("modulename", -1);
// Declare an options description instance which will include all the options
po::options_description all("Allowed options");
all.add(generic).add(config).add(hidden);
// Declare an options description instance which will be shown to the user
po::options_description visible("Allowed options");
visible.add(generic).add(config);
po::variables_map vm;
store(parse_command_line(argc, argv, all), vm);
po::notify(vm);
if (vm.count("version")) {
cout << "Version: 1.0" << "\n";
return 0;
}
if (vm.count("help")) {
//~ cout << visible;
cout << all;
return 0;
}
string modName = vm["modulename"].as<string>();
MetaData md = mm.getModuleMetaData(modName);
ProcessingStep processModule;
processModule.name = "processModule";
processModule.module = modName;
if (vm.count("input")) {
vector<string> inputs = vm["input"].as< vector<string> >();
// this step is repeated as often, as the number of load modules is created
for (unsigned int i=0; i<inputs.size(); i++){
ProcessingStep loadModule;
loadModule.name = "loadModule" + to_string(i);
loadModule.module = "loadImage";
string source = secondPart(inputs[i]);
loadModule.params.insert (pair<string,string>("filename",source) );
conf.addProcessingStep(loadModule);
// the input params of the module are set
map<string, DataDescription> in = md.getInputs();
string name;
// if there is only one input, the name is optional on the command line, will be taken from metadata
if (in.size() == 1) {
auto it = in.cbegin();
name = it->first;
} else {
name = firstPart(inputs[i]);
}
pair<string,string> loadWithValue(loadModule.name, "image");
processModule.inputs.insert(pair<string, pair<string, string> >(name, loadWithValue));
}
// if only one input, create an output automatically, if none is given explicitly
if (inputs.size() == 1 && vm.count("output") == 0){
map<string, DataDescription> out = md.getOutputs();
// if only one output exists
if(out.size() ==1){
auto it = out.cbegin();
string outName = it->first;
pair<string, string> storeSource(processModule.name,outName);
ProcessingStep storeModule;
storeModule.name = "storeModule";
storeModule.module = "storeImage";
// where does the image come from
storeModule.inputs.insert (pair<string, pair<string, string> >("image", storeSource));
// where should it be stored
string newName = rename(secondPart(inputs[0]));
storeModule.params.insert (pair<string,string>("filename", newName));
conf.addProcessingStep(storeModule);
}
}
}
if (vm.count("output")) {
map<string, DataDescription> out = md.getOutputs();
vector<string> outputs = vm["output"].as< vector<string> >();
// this step is repeated as often, as the number of store modules is created
for (unsigned int i=0; i<outputs.size(); i++){
// if there is only one output, the name is optional on the command line, will be taken from metadata
string outName;
if (out.size() == 1) {
auto it = out.cbegin();
outName = it->first;
} else {
outName = firstPart(outputs[i]);
}
pair<string, string> storeSource(processModule.name, outName);
ProcessingStep storeModule;
storeModule.name = "storeModule" + to_string(i);
storeModule.module = "storeImage";
// where does the image come from
storeModule.inputs.insert (pair<string, pair<string, string> >("image",storeSource) );
// where should it be stored
string storeName = secondPart(outputs[i]);
storeModule.params.insert (pair<string,string>("filename",storeName) );
conf.addProcessingStep(storeModule);
}
}
if (vm.count("param")) {
vector<string> params = vm["param"].as< vector<string> >();
// this step is repeated as often, as the number of params is inserted
for (unsigned int i=0; i<params.size(); i++){
processModule.params.insert (pair<string,string>(firstPart(params[i]), secondPart(params[i])));
}
}
conf.addProcessingStep(processModule);
//~ }
//~ catch(exception& e) {
//~ cout << e.what() << "\n";
//~ return 1;
//~ }
}
conf.store("test.yaml");
// loads the Configuration and runs it
mm.run(conf);
return 0;
}
// renames a filename by adding _result before the end, eg. ball.png -> ball_result.png
/*
s old name, which has to be renamed
*/
string rename(string s){
istringstream iss(s);
vector<std::string> tokens;
string token;
while (getline(iss, token, '.')) {
tokens.push_back(token);
}
string end = tokens[tokens.size()-1];
tokens.pop_back();
string beforeEnd = tokens[tokens.size()-1];
tokens.pop_back();
beforeEnd = beforeEnd +"_result";
tokens.push_back(beforeEnd);
tokens.push_back(end);
string newName;
newName = tokens[0];
for (unsigned int i=1; i<tokens.size(); i++){
newName = newName +"." + tokens[i];
}
return newName;
}
// gets the second part of the string, which is divided by : , e.g. source:../ball.png -> ../ball.png
/*
s complete string, or only the second part
*/
string secondPart(string s){
istringstream iss(s);
vector<std::string> tokens;
string token;
while (getline(iss, token, ':')) {
if (!token.empty())
tokens.push_back(token);
}
if(tokens.size() == 1){
return tokens[0];
} else{
return tokens[1];
}
}
// gets the first part of the string, which is divided by : , e.g. source:../ball.png -> source
/*
s complete string
*/
string firstPart(string s){
istringstream iss(s);
vector<std::string> tokens;
string token;
while (getline(iss, token, ':')) {
if (!token.empty())
tokens.push_back(token);
}
return tokens[0];
}
<commit_msg>whitespace<commit_after>#include <iostream>
#include <string>
#include <QApplication>
#include "framework/ModuleManager.hpp"
#include "framework/Configuration.hpp"
// foor Boost:
#include <boost/program_options/options_description.hpp>
#include <boost/program_options/parsers.hpp>
#include <boost/program_options/variables_map.hpp>
namespace po = boost::program_options;
using namespace std;
using namespace uipf;
string firstPart(string s);
string secondPart(string s);
string rename(string s);
// argument is a configFile
int main(int argc, char** argv){
if (argc < 2) {
std::cerr << "Usage Error, at least one argument is required!\n\n";
std::cerr << "Usage: " << argv[0] << " <configFile>"<< std::endl;
return 1;
}
// used by the module manager to access Qt components, TODO maybe move to module manager?
QApplication app (argc,argv);
ModuleManager mm;
Configuration conf;
if (string(argv[1]).compare("-c") == 0){
// run a processing chain from a config file.
// ./uipf -c example.yam
// loads the configFile and create a Configuration
string configFileName = argv[2];
conf.load(configFileName);
// only for debug, print the loaded config
conf.store("test.yaml");
} else{
// run a single module.
// ./uipf <moduleName> ...options...
//~ try {
// Declare three groups of options.
// Declare a group of options that will be allowed only on command line
po::options_description generic("Generic options");
generic.add_options()
("version,v", "print version string")
("help", "produce help message")
;
// Declare a group of options that will be
// allowed both on command line and in
// config file
po::options_description config("Configuration");
config.add_options()
("input,i", po::value< vector<string> >()->composing(), "defines an input, can be used multiple times \n format: inputName:fileName \n inputName is optional if there is only one input")
("output,o", po::value< vector<string> >()->composing(), "defines an output, can be used multiple times \n format: outputName:fileName \n outputName is optional if there is only one output \n output itself is optional, if there is only one input and one output, \n the output filename will be choosen from the input name in this case.")
("param,p", po::value< vector<string> >()->composing(), "defines a parameter, format: name:valu")
;
// Hidden options, will be allowed both on command line and
// in config file, but will not be shown to the user.
po::options_description hidden("Hidden options");
hidden.add_options()
("modulename,m", po::value< string>(), "defines the name of the module")
;
// These two lines say that all positional options should be translated into "-modulename" options.
po::positional_options_description p;
p.add("modulename", -1);
// Declare an options description instance which will include all the options
po::options_description all("Allowed options");
all.add(generic).add(config).add(hidden);
// Declare an options description instance which will be shown to the user
po::options_description visible("Allowed options");
visible.add(generic).add(config);
po::variables_map vm;
store(parse_command_line(argc, argv, all), vm);
po::notify(vm);
if (vm.count("version")) {
cout << "Version: 1.0" << "\n";
return 0;
}
if (vm.count("help")) {
//~ cout << visible;
cout << all;
return 0;
}
string modName = vm["modulename"].as<string>();
MetaData md = mm.getModuleMetaData(modName);
ProcessingStep processModule;
processModule.name = "processModule";
processModule.module = modName;
if (vm.count("input")) {
vector<string> inputs = vm["input"].as< vector<string> >();
// this step is repeated as often, as the number of load modules is created
for (unsigned int i=0; i<inputs.size(); i++){
ProcessingStep loadModule;
loadModule.name = "loadModule" + to_string(i);
loadModule.module = "loadImage";
string source = secondPart(inputs[i]);
loadModule.params.insert (pair<string,string>("filename",source) );
conf.addProcessingStep(loadModule);
// the input params of the module are set
map<string, DataDescription> in = md.getInputs();
string name;
// if there is only one input, the name is optional on the command line, will be taken from metadata
if (in.size() == 1) {
auto it = in.cbegin();
name = it->first;
} else {
name = firstPart(inputs[i]);
}
pair<string,string> loadWithValue(loadModule.name, "image");
processModule.inputs.insert(pair<string, pair<string, string> >(name, loadWithValue));
}
// if only one input, create an output automatically, if none is given explicitly
if (inputs.size() == 1 && vm.count("output") == 0){
map<string, DataDescription> out = md.getOutputs();
// if only one output exists
if(out.size() ==1){
auto it = out.cbegin();
string outName = it->first;
pair<string, string> storeSource(processModule.name,outName);
ProcessingStep storeModule;
storeModule.name = "storeModule";
storeModule.module = "storeImage";
// where does the image come from
storeModule.inputs.insert (pair<string, pair<string, string> >("image", storeSource));
// where should it be stored
string newName = rename(secondPart(inputs[0]));
storeModule.params.insert (pair<string,string>("filename", newName));
conf.addProcessingStep(storeModule);
}
}
}
if (vm.count("output")) {
map<string, DataDescription> out = md.getOutputs();
vector<string> outputs = vm["output"].as< vector<string> >();
// this step is repeated as often, as the number of store modules is created
for (unsigned int i=0; i<outputs.size(); i++){
// if there is only one output, the name is optional on the command line, will be taken from metadata
string outName;
if (out.size() == 1) {
auto it = out.cbegin();
outName = it->first;
} else {
outName = firstPart(outputs[i]);
}
pair<string, string> storeSource(processModule.name, outName);
ProcessingStep storeModule;
storeModule.name = "storeModule" + to_string(i);
storeModule.module = "storeImage";
// where does the image come from
storeModule.inputs.insert (pair<string, pair<string, string> >("image",storeSource) );
// where should it be stored
string storeName = secondPart(outputs[i]);
storeModule.params.insert (pair<string,string>("filename",storeName) );
conf.addProcessingStep(storeModule);
}
}
if (vm.count("param")) {
vector<string> params = vm["param"].as< vector<string> >();
// this step is repeated as often, as the number of params is inserted
for (unsigned int i=0; i<params.size(); i++){
processModule.params.insert (pair<string,string>(firstPart(params[i]), secondPart(params[i])));
}
}
conf.addProcessingStep(processModule);
//~ }
//~ catch(exception& e) {
//~ cout << e.what() << "\n";
//~ return 1;
//~ }
}
conf.store("test.yaml");
// loads the Configuration and runs it
mm.run(conf);
return 0;
}
// renames a filename by adding _result before the end, eg. ball.png -> ball_result.png
/*
s old name, which has to be renamed
*/
string rename(string s){
istringstream iss(s);
vector<std::string> tokens;
string token;
while (getline(iss, token, '.')) {
tokens.push_back(token);
}
string end = tokens[tokens.size()-1];
tokens.pop_back();
string beforeEnd = tokens[tokens.size()-1];
tokens.pop_back();
beforeEnd = beforeEnd +"_result";
tokens.push_back(beforeEnd);
tokens.push_back(end);
string newName;
newName = tokens[0];
for (unsigned int i=1; i<tokens.size(); i++){
newName = newName +"." + tokens[i];
}
return newName;
}
// gets the second part of the string, which is divided by : , e.g. source:../ball.png -> ../ball.png
/*
s complete string, or only the second part
*/
string secondPart(string s){
istringstream iss(s);
vector<std::string> tokens;
string token;
while (getline(iss, token, ':')) {
if (!token.empty())
tokens.push_back(token);
}
if(tokens.size() == 1){
return tokens[0];
} else{
return tokens[1];
}
}
// gets the first part of the string, which is divided by : , e.g. source:../ball.png -> source
/*
s complete string
*/
string firstPart(string s){
istringstream iss(s);
vector<std::string> tokens;
string token;
while (getline(iss, token, ':')) {
if (!token.empty())
tokens.push_back(token);
}
return tokens[0];
}
<|endoftext|> |
<commit_before>#include "Sensor/UltrasoundSensor.h"
#include "Data/UltrasoundData.h"
UltrasoundSensor::UltrasoundSensor(string port, int baudrate) : Sensor("Ultrasound Sensor"), conn(std::make_shared<SerialPort>(port, baudrate)) {
}
UltrasoundSensor::~UltrasoundSensor() {
}
bool UltrasoundSensor::ping() {
return conn->isConnected() == 1;
}
void UltrasoundSensor::fillData(SensorData& sensorData) {
if (conn->isConnected()) {
char data[256];
int bytesRead = conn->read(data, 256);
// Decode the incoming data
R2Protocol::Packet params;
std::vector<uint8_t> input(data, data + bytesRead);
int32_t read;
ptr<UltrasoundData> udata = std::make_shared<UltrasoundData>();
while ((read = R2Protocol::decode(input, params)) >= 0) {
if (params.source == "U1SENSOR") {
udata->distance = std::atof((char *) params.data.data());
}
std::vector<uint8_t>(input.begin() + read, input.end()).swap(input);
}
sensorData["ULTRASOUND"] = udata;
printf("Ultrasound: %f\n", udata->distance);
}
}<commit_msg>Add check in ultrasound sensor when reading from the serial port<commit_after>#include "Sensor/UltrasoundSensor.h"
#include "Data/UltrasoundData.h"
UltrasoundSensor::UltrasoundSensor(string port, int baudrate) : Sensor("Ultrasound Sensor"), conn(std::make_shared<SerialPort>(port, baudrate)) {
}
UltrasoundSensor::~UltrasoundSensor() {
}
bool UltrasoundSensor::ping() {
return conn->isConnected() == 1;
}
void UltrasoundSensor::fillData(SensorData& sensorData) {
if (conn->isConnected()) {
char data[256];
int bytesRead = conn->read(data, 256);
if (bytesRead <= 0) {
return;
}
// Decode the incoming data
R2Protocol::Packet params;
std::vector<uint8_t> input(data, data + bytesRead);
int32_t read;
ptr<UltrasoundData> udata = std::make_shared<UltrasoundData>();
while ((read = R2Protocol::decode(input, params)) >= 0) {
if (params.source == "U1SENSOR") {
udata->distance = std::atof((char *) params.data.data());
}
std::vector<uint8_t> newinput(input.begin() + read, input.end());
newinput.swap(input);
}
sensorData["ULTRASOUND"] = udata;
printf("Ultrasound: %f\n", udata->distance);
}
}<|endoftext|> |
<commit_before>#include "holmes.capnp.h"
#include <capnp/ez-rpc.h>
#include <llvm/Object/Binary.h>
#include <llvm/Object/Archive.h>
#include <llvm/Object/ObjectFile.h>
#include <llvm/ADT/StringRef.h>
#include <llvm/ADT/Triple.h>
#include <llvm/Support/MemoryBuffer.h>
#include <kj/debug.h>
#include <iostream>
#include <memory>
#include <vector>
using llvm::dyn_cast;
using holmes::Holmes;
using capnp::Orphan;
using kj::mv;
using llvm::OwningPtr;
using llvm::object::Binary;
using llvm::MemoryBuffer;
using llvm::Triple;
using llvm::object::ObjectFile;
class DumpObj final : public Holmes::Analysis::Server {
public:
kj::Promise<void> analyze(AnalyzeContext context) {
auto prems = context.getParams().getPremises();
auto orphanage = capnp::Orphanage::getForMessageContaining(context.getResults());
std::vector<capnp::Orphan<Holmes::Fact> > derived;
//TODO: This can be removed once we have problem instancing
for (auto prem : prems) {
auto args = prem.getArgs();
auto fileName = args[0].getStringVal();
auto body = args[1].getBlobVal();
auto sr = llvm::StringRef(reinterpret_cast<const char*>(body.begin()), body.size());
auto mb = llvm::MemoryBuffer::getMemBuffer(sr, "holmes-input", false);
llvm::OwningPtr<llvm::object::Binary> oBin(0);
if (llvm::object::createBinary(mb, oBin)) {
//We failed to parse the binary
Orphan<Holmes::Fact> fact = orphanage.newOrphan<Holmes::Fact>();
auto fb = fact.get();
fb.setFactName("llvm-obj-no-parse");
auto ab = fb.initArgs(1);
ab[0].setStringVal(fileName);
derived.push_back(mv(fact));
continue;
}
llvm::object::Binary *bin = oBin.take();
if (llvm::object::Archive *a = dyn_cast<llvm::object::Archive>(bin)) {
Orphan<Holmes::Fact> fact = orphanage.newOrphan<Holmes::Fact>();
auto fb = fact.get();
fb.setFactName("is-archive");
auto ab = fb.initArgs(1);
ab[0].setStringVal(fileName);
derived.push_back(mv(fact));
for (auto i = a->begin_children(), e = a->end_children(); i != e; ++i) {
OwningPtr<Binary> b;
if (!i->getAsBinary(b)) {
Orphan<Holmes::Fact> fact = orphanage.newOrphan<Holmes::Fact>();
auto fb = fact.get();
fb.setFactName("file");
auto ab = fb.initArgs(2);
ab[0].setStringVal(std::string(fileName) + ":" + std::string(b->getFileName()));
OwningPtr<MemoryBuffer> omb;
i->getMemoryBuffer(omb);
ab[1].setBlobVal(capnp::Data::Reader(reinterpret_cast<const unsigned char*>(omb->getBufferStart()), omb->getBufferSize()));
derived.push_back(mv(fact));
}
}
} else if (llvm::object::ObjectFile *o = dyn_cast<llvm::object::ObjectFile>(bin)) {
{
//Note that it's an object
Orphan<Holmes::Fact> fact = orphanage.newOrphan<Holmes::Fact>();
auto fb = fact.get();
fb.setFactName("is-object");
auto ab = fb.initArgs(1);
ab[0].setStringVal(fileName);
derived.push_back(mv(fact));
}
{
//Export its architecture
Orphan<Holmes::Fact> fact = orphanage.newOrphan<Holmes::Fact>();
auto fb = fact.get();
fb.setFactName("arch");
auto ab = fb.initArgs(2);
ab[0].setStringVal(fileName);
ab[1].setStringVal(Triple::getArchTypeName(Triple::ArchType(o->getArch())));
derived.push_back(mv(fact));
}
llvm::error_code ec_ignore;
for (auto i = o->begin_sections(), e = o->end_sections(); i != e; i = i.increment(ec_ignore)) {
Orphan<Holmes::Fact> fact = orphanage.newOrphan<Holmes::Fact>();
auto fb = fact.get();
fb.setFactName("section");
auto ab = fb.initArgs(6);
llvm::StringRef name;
uint64_t base;
uint64_t size;
llvm::StringRef contents;
i->getName(name);
i->getAddress(base);
i->getSize(size);
i->getContents(contents);
ab[0].setStringVal(std::string(name));
ab[1].setAddrVal(base);
ab[2].setAddrVal(size);
bool text, rodata, data, bss;
i->isText(text);
i->isReadOnlyData(rodata);
i->isData(data);
i->isBSS(bss);
if (!bss) {
ab[3].setBlobVal(capnp::Data::Reader(reinterpret_cast<const unsigned char*>(contents.begin()), contents.size()));
}
if (text) {
ab[4].setStringVal(".text");
} else if (rodata) {
ab[4].setStringVal(".rodata");
} else if (data) {
ab[4].setStringVal(".data");
} else if (bss) {
ab[4].setStringVal(".bss");
} else {
ab[4].setStringVal(".unk");
}
ab[5].setStringVal(fileName);
derived.push_back(mv(fact));
}
} else {
continue;
}
}
auto derivedBuilder = context.getResults().initDerived(derived.size());
auto i = 0;
while (!derived.empty()) {
derivedBuilder.adoptWithCaveats(i++, mv(derived.back()));
derived.pop_back();
}
return kj::READY_NOW;
}
};
int main(int argc, char* argv[]) {
if (argc != 2) {
std::cerr << "usage: " << argv[0] << " HOST:PORT" << std::endl;
return 1;
}
capnp::EzRpcClient client(argv[1]);
holmes::Holmes::Client holmes = client.importCap<holmes::Holmes>("holmes");
auto& waitScope = client.getWaitScope();
auto request = holmes.analyzerRequest();
auto prems = request.initPremises(1);
prems[0].setFactName("file");
auto args = prems[0].initArgs(2);
args[0].setUnbound();
args[1].setUnbound();
request.setAnalysis(kj::heap<DumpObj>());
request.send().wait(waitScope);
return 0;
}
<commit_msg>Dump symbols too<commit_after>#include "holmes.capnp.h"
#include <capnp/ez-rpc.h>
#include <llvm/Object/Binary.h>
#include <llvm/Object/Archive.h>
#include <llvm/Object/ObjectFile.h>
#include <llvm/ADT/StringRef.h>
#include <llvm/ADT/Triple.h>
#include <llvm/Support/MemoryBuffer.h>
#include <kj/debug.h>
#include <iostream>
#include <memory>
#include <vector>
using llvm::dyn_cast;
using holmes::Holmes;
using capnp::Orphan;
using kj::mv;
using llvm::OwningPtr;
using llvm::object::Binary;
using llvm::MemoryBuffer;
using llvm::Triple;
using llvm::object::ObjectFile;
class DumpObj final : public Holmes::Analysis::Server {
public:
kj::Promise<void> analyze(AnalyzeContext context) {
auto prems = context.getParams().getPremises();
auto orphanage = capnp::Orphanage::getForMessageContaining(context.getResults());
std::vector<capnp::Orphan<Holmes::Fact> > derived;
//TODO: This can be removed once we have problem instancing
for (auto prem : prems) {
auto args = prem.getArgs();
auto fileName = args[0].getStringVal();
auto body = args[1].getBlobVal();
auto sr = llvm::StringRef(reinterpret_cast<const char*>(body.begin()), body.size());
auto mb = llvm::MemoryBuffer::getMemBuffer(sr, "holmes-input", false);
llvm::OwningPtr<llvm::object::Binary> oBin(0);
if (llvm::object::createBinary(mb, oBin)) {
//We failed to parse the binary
Orphan<Holmes::Fact> fact = orphanage.newOrphan<Holmes::Fact>();
auto fb = fact.get();
fb.setFactName("llvm-obj-no-parse");
auto ab = fb.initArgs(1);
ab[0].setStringVal(fileName);
derived.push_back(mv(fact));
continue;
}
llvm::object::Binary *bin = oBin.take();
if (llvm::object::Archive *a = dyn_cast<llvm::object::Archive>(bin)) {
Orphan<Holmes::Fact> fact = orphanage.newOrphan<Holmes::Fact>();
auto fb = fact.get();
fb.setFactName("is-archive");
auto ab = fb.initArgs(1);
ab[0].setStringVal(fileName);
derived.push_back(mv(fact));
for (auto i = a->begin_children(), e = a->end_children(); i != e; ++i) {
OwningPtr<Binary> b;
if (!i->getAsBinary(b)) {
Orphan<Holmes::Fact> fact = orphanage.newOrphan<Holmes::Fact>();
auto fb = fact.get();
fb.setFactName("file");
auto ab = fb.initArgs(2);
ab[0].setStringVal(std::string(fileName) + ":" + std::string(b->getFileName()));
OwningPtr<MemoryBuffer> omb;
i->getMemoryBuffer(omb);
ab[1].setBlobVal(capnp::Data::Reader(reinterpret_cast<const unsigned char*>(omb->getBufferStart()), omb->getBufferSize()));
derived.push_back(mv(fact));
}
}
} else if (llvm::object::ObjectFile *o = dyn_cast<llvm::object::ObjectFile>(bin)) {
{
//Note that it's an object
Orphan<Holmes::Fact> fact = orphanage.newOrphan<Holmes::Fact>();
auto fb = fact.get();
fb.setFactName("is-object");
auto ab = fb.initArgs(1);
ab[0].setStringVal(fileName);
derived.push_back(mv(fact));
}
{
//Export its architecture
Orphan<Holmes::Fact> fact = orphanage.newOrphan<Holmes::Fact>();
auto fb = fact.get();
fb.setFactName("arch");
auto ab = fb.initArgs(2);
ab[0].setStringVal(fileName);
ab[1].setStringVal(Triple::getArchTypeName(Triple::ArchType(o->getArch())));
derived.push_back(mv(fact));
}
llvm::error_code ec_ignore;
for (auto i = o->begin_sections(), e = o->end_sections(); i != e; i = i.increment(ec_ignore)) {
Orphan<Holmes::Fact> fact = orphanage.newOrphan<Holmes::Fact>();
auto fb = fact.get();
fb.setFactName("section");
auto ab = fb.initArgs(6);
llvm::StringRef name;
uint64_t base;
uint64_t size;
llvm::StringRef contents;
i->getName(name);
i->getAddress(base);
i->getSize(size);
i->getContents(contents);
ab[0].setStringVal(std::string(name));
ab[1].setAddrVal(base);
ab[2].setAddrVal(size);
bool text, rodata, data, bss;
i->isText(text);
i->isReadOnlyData(rodata);
i->isData(data);
i->isBSS(bss);
if (!bss) {
ab[3].setBlobVal(capnp::Data::Reader(reinterpret_cast<const unsigned char*>(contents.begin()), contents.size()));
}
if (text) {
ab[4].setStringVal(".text");
} else if (rodata) {
ab[4].setStringVal(".rodata");
} else if (data) {
ab[4].setStringVal(".data");
} else if (bss) {
ab[4].setStringVal(".bss");
} else {
ab[4].setStringVal(".unk");
}
ab[5].setStringVal(fileName);
derived.push_back(mv(fact));
}
for (auto i = o->begin_symbols(), e = o->end_symbols(); i != e; i = i.increment(ec_ignore)) {
llvm::StringRef symName;
uint64_t symAddr;
uint64_t symSize;
llvm::object::SymbolRef::Type symType;
uint64_t symVal;
i->getName(symName);
i->getAddress(symAddr);
i->getSize(symSize);
i->getType(symType);
i->getValue(symVal);
std::string symTypeStr;
switch (symType) {
case llvm::object::SymbolRef::Type::ST_Unknown:
symTypeStr = "unknown"; break;
case llvm::object::SymbolRef::Type::ST_Data:
symTypeStr = "data"; break;
case llvm::object::SymbolRef::Type::ST_Debug:
symTypeStr = "debug"; break;
case llvm::object::SymbolRef::Type::ST_File:
symTypeStr = "file"; break;
case llvm::object::SymbolRef::Type::ST_Function:
symTypeStr = "func"; break;
case llvm::object::SymbolRef::Type::ST_Other:
symTypeStr = "other"; break;
}
Orphan<Holmes::Fact> fact = orphanage.newOrphan<Holmes::Fact>();
auto fb = fact.get();
fb.setFactName("symbol");
auto ab = fb.initArgs(6);
ab[0].setStringVal(fileName);
ab[1].setStringVal(std::string(symName));
ab[2].setAddrVal(symAddr);
ab[3].setAddrVal(symSize);
ab[4].setAddrVal(symVal);
ab[5].setStringVal(symTypeStr);
derived.push_back(mv(fact));
}
} else {
continue;
}
}
auto derivedBuilder = context.getResults().initDerived(derived.size());
auto i = 0;
while (!derived.empty()) {
derivedBuilder.adoptWithCaveats(i++, mv(derived.back()));
derived.pop_back();
}
return kj::READY_NOW;
}
};
int main(int argc, char* argv[]) {
if (argc != 2) {
std::cerr << "usage: " << argv[0] << " HOST:PORT" << std::endl;
return 1;
}
capnp::EzRpcClient client(argv[1]);
holmes::Holmes::Client holmes = client.importCap<holmes::Holmes>("holmes");
auto& waitScope = client.getWaitScope();
auto request = holmes.analyzerRequest();
auto prems = request.initPremises(1);
prems[0].setFactName("file");
auto args = prems[0].initArgs(2);
args[0].setUnbound();
args[1].setUnbound();
request.setAnalysis(kj::heap<DumpObj>());
request.send().wait(waitScope);
return 0;
}
<|endoftext|> |
<commit_before>/*************************************************************************
*
* $RCSfile: BCatalog.cxx,v $
*
* $Revision: 1.12 $
*
* last change: $Author: vg $ $Date: 2005-03-10 15:18:53 $
*
* 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 _CONNECTIVITY_ADABAS_CATALOG_HXX_
#include "adabas/BCatalog.hxx"
#endif
#ifndef _CONNECTIVITY_ADABAS_BCONNECTION_HXX_
#include "adabas/BConnection.hxx"
#endif
#ifndef _CONNECTIVITY_ADABAS_GROUPS_HXX_
#include "adabas/BGroups.hxx"
#endif
#ifndef _CONNECTIVITY_ADABAS_USERS_HXX_
#include "adabas/BUsers.hxx"
#endif
#ifndef _CONNECTIVITY_ADABAS_TABLES_HXX_
#include "adabas/BTables.hxx"
#endif
#ifndef _CONNECTIVITY_ADABAS_VIEWS_HXX_
#include "adabas/BViews.hxx"
#endif
#ifndef _COM_SUN_STAR_SDBC_XROW_HPP_
#include <com/sun/star/sdbc/XRow.hpp>
#endif
#ifndef _COM_SUN_STAR_SDBC_XRESULTSET_HPP_
#include <com/sun/star/sdbc/XResultSet.hpp>
#endif
#ifndef _COMPHELPER_TYPES_HXX_
#include <comphelper/types.hxx>
#endif
// -------------------------------------------------------------------------
using namespace connectivity;
using namespace connectivity::adabas;
using namespace ::com::sun::star::uno;
using namespace ::com::sun::star::beans;
using namespace ::com::sun::star::sdbcx;
using namespace ::com::sun::star::sdbc;
using namespace ::com::sun::star::container;
using namespace ::com::sun::star::lang;
// -----------------------------------------------------------------------------
OAdabasCatalog::OAdabasCatalog(SQLHANDLE _aConnectionHdl, OAdabasConnection* _pCon) : connectivity::sdbcx::OCatalog(_pCon)
,m_pConnection(_pCon)
,m_aConnectionHdl(_aConnectionHdl)
{
}
// -----------------------------------------------------------------------------
::rtl::OUString OAdabasCatalog::buildName(const Reference< XRow >& _xRow)
{
::rtl::OUString sName;
sName = _xRow->getString(2);
if ( sName.getLength() )
sName += OAdabasCatalog::getDot();
sName += _xRow->getString(3);
return sName;
}
// -----------------------------------------------------------------------------
void OAdabasCatalog::fillVector(const ::rtl::OUString& _sQuery,TStringVector& _rVector)
{
Reference< XStatement > xStmt = m_pConnection->createStatement( );
OSL_ENSURE(xStmt.is(),"OAdabasCatalog::fillVector: Could not create a statement!");
Reference< XResultSet > xResult = xStmt->executeQuery(_sQuery);
fillNames(xResult,_rVector);
::comphelper::disposeComponent(xStmt);
}
// -------------------------------------------------------------------------
void OAdabasCatalog::refreshTables()
{
TStringVector aVector;
{
Sequence< ::rtl::OUString > aTypes(1);
aTypes[0] = ::rtl::OUString(RTL_CONSTASCII_USTRINGPARAM("%"));
Reference< XResultSet > xResult = m_xMetaData->getTables(Any(),
::rtl::OUString(RTL_CONSTASCII_USTRINGPARAM("%")),
::rtl::OUString(RTL_CONSTASCII_USTRINGPARAM("%")),
aTypes);
fillNames(xResult,aVector);
}
if(m_pTables)
m_pTables->reFill(aVector);
else
m_pTables = new OTables(m_xMetaData,*this,m_aMutex,aVector);
}
// -------------------------------------------------------------------------
void OAdabasCatalog::refreshViews()
{
TStringVector aVector;
static const ::rtl::OUString s_sView(RTL_CONSTASCII_USTRINGPARAM("SELECT DISTINCT NULL,DOMAIN.VIEWDEFS.OWNER, DOMAIN.VIEWDEFS.VIEWNAME FROM DOMAIN.VIEWDEFS"));
fillVector(s_sView,aVector);
if(m_pViews)
m_pViews->reFill(aVector);
else
m_pViews = new OViews(m_xMetaData,*this,m_aMutex,aVector);
}
// -------------------------------------------------------------------------
void OAdabasCatalog::refreshGroups()
{
TStringVector aVector;
static const ::rtl::OUString s_sGroup(RTL_CONSTASCII_USTRINGPARAM("SELECT DISTINCT NULL,NULL,GROUPNAME FROM DOMAIN.USERS WHERE GROUPNAME IS NOT NULL AND GROUPNAME <> ' '"));
fillVector(s_sGroup,aVector);
if(m_pGroups)
m_pGroups->reFill(aVector);
else
m_pGroups = new OGroups(*this,m_aMutex,aVector,m_pConnection,this);
}
// -------------------------------------------------------------------------
void OAdabasCatalog::refreshUsers()
{
TStringVector aVector;
static const ::rtl::OUString s_sUsers(RTL_CONSTASCII_USTRINGPARAM("SELECT DISTINCT NULL,NULL,USERNAME FROM DOMAIN.USERS WHERE USERNAME IS NOT NULL AND USERNAME <> ' ' AND USERNAME <> 'CONTROL'"));
fillVector(s_sUsers,aVector);
if(m_pUsers)
m_pUsers->reFill(aVector);
else
m_pUsers = new OUsers(*this,m_aMutex,aVector,m_pConnection,this);
}
// -------------------------------------------------------------------------
const ::rtl::OUString& OAdabasCatalog::getDot()
{
static const ::rtl::OUString sDot(RTL_CONSTASCII_USTRINGPARAM("."));
return sDot;
}
// -----------------------------------------------------------------------------
void OAdabasCatalog::correctColumnProperties(sal_Int32 _nPrec, sal_Int32& _rnType,::rtl::OUString& _rsTypeName)
{
switch(_rnType)
{
case DataType::DECIMAL:
{
static const ::rtl::OUString sDecimal(RTL_CONSTASCII_USTRINGPARAM("DECIMAL"));
if(_rnType == DataType::DECIMAL && _rsTypeName == sDecimal)
_rnType = DataType::NUMERIC;
}
break;
case DataType::FLOAT:
// if(_nPrec >= 16)
{
static const ::rtl::OUString sDouble(RTL_CONSTASCII_USTRINGPARAM("DOUBLE PRECISION"));
_rsTypeName = sDouble;
_rnType = DataType::DOUBLE;
}
// else if(_nPrec > 15)
// {
// static const ::rtl::OUString sReal = ::rtl::OUString::createFromAscii("REAL");
// _rsTypeName = sReal;
// _rnType = DataType::REAL;
// }
break;
}
}
// -----------------------------------------------------------------------------
<commit_msg>INTEGRATION: CWS ooo19126 (1.12.74); FILE MERGED 2005/09/05 17:23:04 rt 1.12.74.1: #i54170# Change license header: remove SISSL<commit_after>/*************************************************************************
*
* OpenOffice.org - a multi-platform office productivity suite
*
* $RCSfile: BCatalog.cxx,v $
*
* $Revision: 1.13 $
*
* last change: $Author: rt $ $Date: 2005-09-08 05:19:35 $
*
* The Contents of this file are made available subject to
* the terms of GNU Lesser General Public License Version 2.1.
*
*
* GNU Lesser General Public License Version 2.1
* =============================================
* Copyright 2005 by Sun Microsystems, Inc.
* 901 San Antonio Road, Palo Alto, CA 94303, USA
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License version 2.1, as published by the Free Software Foundation.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston,
* MA 02111-1307 USA
*
************************************************************************/
#ifndef _CONNECTIVITY_ADABAS_CATALOG_HXX_
#include "adabas/BCatalog.hxx"
#endif
#ifndef _CONNECTIVITY_ADABAS_BCONNECTION_HXX_
#include "adabas/BConnection.hxx"
#endif
#ifndef _CONNECTIVITY_ADABAS_GROUPS_HXX_
#include "adabas/BGroups.hxx"
#endif
#ifndef _CONNECTIVITY_ADABAS_USERS_HXX_
#include "adabas/BUsers.hxx"
#endif
#ifndef _CONNECTIVITY_ADABAS_TABLES_HXX_
#include "adabas/BTables.hxx"
#endif
#ifndef _CONNECTIVITY_ADABAS_VIEWS_HXX_
#include "adabas/BViews.hxx"
#endif
#ifndef _COM_SUN_STAR_SDBC_XROW_HPP_
#include <com/sun/star/sdbc/XRow.hpp>
#endif
#ifndef _COM_SUN_STAR_SDBC_XRESULTSET_HPP_
#include <com/sun/star/sdbc/XResultSet.hpp>
#endif
#ifndef _COMPHELPER_TYPES_HXX_
#include <comphelper/types.hxx>
#endif
// -------------------------------------------------------------------------
using namespace connectivity;
using namespace connectivity::adabas;
using namespace ::com::sun::star::uno;
using namespace ::com::sun::star::beans;
using namespace ::com::sun::star::sdbcx;
using namespace ::com::sun::star::sdbc;
using namespace ::com::sun::star::container;
using namespace ::com::sun::star::lang;
// -----------------------------------------------------------------------------
OAdabasCatalog::OAdabasCatalog(SQLHANDLE _aConnectionHdl, OAdabasConnection* _pCon) : connectivity::sdbcx::OCatalog(_pCon)
,m_pConnection(_pCon)
,m_aConnectionHdl(_aConnectionHdl)
{
}
// -----------------------------------------------------------------------------
::rtl::OUString OAdabasCatalog::buildName(const Reference< XRow >& _xRow)
{
::rtl::OUString sName;
sName = _xRow->getString(2);
if ( sName.getLength() )
sName += OAdabasCatalog::getDot();
sName += _xRow->getString(3);
return sName;
}
// -----------------------------------------------------------------------------
void OAdabasCatalog::fillVector(const ::rtl::OUString& _sQuery,TStringVector& _rVector)
{
Reference< XStatement > xStmt = m_pConnection->createStatement( );
OSL_ENSURE(xStmt.is(),"OAdabasCatalog::fillVector: Could not create a statement!");
Reference< XResultSet > xResult = xStmt->executeQuery(_sQuery);
fillNames(xResult,_rVector);
::comphelper::disposeComponent(xStmt);
}
// -------------------------------------------------------------------------
void OAdabasCatalog::refreshTables()
{
TStringVector aVector;
{
Sequence< ::rtl::OUString > aTypes(1);
aTypes[0] = ::rtl::OUString(RTL_CONSTASCII_USTRINGPARAM("%"));
Reference< XResultSet > xResult = m_xMetaData->getTables(Any(),
::rtl::OUString(RTL_CONSTASCII_USTRINGPARAM("%")),
::rtl::OUString(RTL_CONSTASCII_USTRINGPARAM("%")),
aTypes);
fillNames(xResult,aVector);
}
if(m_pTables)
m_pTables->reFill(aVector);
else
m_pTables = new OTables(m_xMetaData,*this,m_aMutex,aVector);
}
// -------------------------------------------------------------------------
void OAdabasCatalog::refreshViews()
{
TStringVector aVector;
static const ::rtl::OUString s_sView(RTL_CONSTASCII_USTRINGPARAM("SELECT DISTINCT NULL,DOMAIN.VIEWDEFS.OWNER, DOMAIN.VIEWDEFS.VIEWNAME FROM DOMAIN.VIEWDEFS"));
fillVector(s_sView,aVector);
if(m_pViews)
m_pViews->reFill(aVector);
else
m_pViews = new OViews(m_xMetaData,*this,m_aMutex,aVector);
}
// -------------------------------------------------------------------------
void OAdabasCatalog::refreshGroups()
{
TStringVector aVector;
static const ::rtl::OUString s_sGroup(RTL_CONSTASCII_USTRINGPARAM("SELECT DISTINCT NULL,NULL,GROUPNAME FROM DOMAIN.USERS WHERE GROUPNAME IS NOT NULL AND GROUPNAME <> ' '"));
fillVector(s_sGroup,aVector);
if(m_pGroups)
m_pGroups->reFill(aVector);
else
m_pGroups = new OGroups(*this,m_aMutex,aVector,m_pConnection,this);
}
// -------------------------------------------------------------------------
void OAdabasCatalog::refreshUsers()
{
TStringVector aVector;
static const ::rtl::OUString s_sUsers(RTL_CONSTASCII_USTRINGPARAM("SELECT DISTINCT NULL,NULL,USERNAME FROM DOMAIN.USERS WHERE USERNAME IS NOT NULL AND USERNAME <> ' ' AND USERNAME <> 'CONTROL'"));
fillVector(s_sUsers,aVector);
if(m_pUsers)
m_pUsers->reFill(aVector);
else
m_pUsers = new OUsers(*this,m_aMutex,aVector,m_pConnection,this);
}
// -------------------------------------------------------------------------
const ::rtl::OUString& OAdabasCatalog::getDot()
{
static const ::rtl::OUString sDot(RTL_CONSTASCII_USTRINGPARAM("."));
return sDot;
}
// -----------------------------------------------------------------------------
void OAdabasCatalog::correctColumnProperties(sal_Int32 _nPrec, sal_Int32& _rnType,::rtl::OUString& _rsTypeName)
{
switch(_rnType)
{
case DataType::DECIMAL:
{
static const ::rtl::OUString sDecimal(RTL_CONSTASCII_USTRINGPARAM("DECIMAL"));
if(_rnType == DataType::DECIMAL && _rsTypeName == sDecimal)
_rnType = DataType::NUMERIC;
}
break;
case DataType::FLOAT:
// if(_nPrec >= 16)
{
static const ::rtl::OUString sDouble(RTL_CONSTASCII_USTRINGPARAM("DOUBLE PRECISION"));
_rsTypeName = sDouble;
_rnType = DataType::DOUBLE;
}
// else if(_nPrec > 15)
// {
// static const ::rtl::OUString sReal = ::rtl::OUString::createFromAscii("REAL");
// _rsTypeName = sReal;
// _rnType = DataType::REAL;
// }
break;
}
}
// -----------------------------------------------------------------------------
<|endoftext|> |
<commit_before>/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */
/*
* Software License Agreement (BSD License)
*
* Copyright (c) 2006, ScalingWeb.com
* All rights reserved.
*
* Redistribution and use of this software 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 ScalingWeb.com nor the names of its
* contributors may be used to endorse or promote products
* derived from this software without specific prior
* written permission of ScalingWeb.com.
* 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.
*/
#ifndef INCLUDED_CONNECTIVITY_SOURCE_DRIVERS_MORK_MORKPARSER_HXX
#define INCLUDED_CONNECTIVITY_SOURCE_DRIVERS_MORK_MORKPARSER_HXX
#include <sal/types.h>
#include <string>
#include <map>
#include <set>
#include <vector>
#include "dllapi.h"
// Types
typedef std::map< int, std::string > MorkDict;
typedef std::map< int, int > MorkCells; // ColumnId : ValueId
typedef std::map< int, MorkCells > MorkRowMap; // Row id
typedef std::map< int, MorkRowMap > RowScopeMap; // Row scope
typedef std::map< int, RowScopeMap > MorkTableMap; // Table id
typedef std::map< int, MorkTableMap > TableScopeMap; // Table Scope
// Error codes
enum MorkErrors
{
NoError = 0,
FailedToOpen,
UnsupportedVersion,
DefectedFormat
};
// Mork term types
enum MorkTerm
{
NoneTerm = 0,
DictTerm,
GroupTerm,
TableTerm,
RowTerm,
CellTerm,
CommentTerm,
LiteralTerm
};
/// Class MorkParser
class LO_DLLPUBLIC_MORK MorkParser
{
public:
MorkParser( int defaultScope = 0x80 );
/// Open and parse mork file
bool open( const std::string &path );
/// Return error status
MorkErrors error();
/// Returns all tables of specified scope
MorkTableMap *getTables( int tableScope );
/// Rerturns all rows under specified scope
MorkRowMap *getRows( int rowScope, RowScopeMap *table );
/// Return value of specified value oid
std::string &getValue( int oid );
/// Return value of specified column oid
std::string &getColumn( int oid );
void retrieveLists(std::set<std::string>& lists);
void getRecordKeysForListTable(std::string& listName, std::set<int>& records);
void dump();
protected: // Members
void initVars();
bool isWhiteSpace( char c );
char nextChar();
void parseScopeId( const std::string &TextId, int *Id, int *Scope );
void setCurrentRow( int TableScope, int TableId, int RowScope, int RowId );
// Parse methods
bool parse();
bool parseDict();
bool parseComment();
bool parseCell();
bool parseTable();
bool parseMeta( char c );
bool parseRow( int TableId, int TableScope );
bool parseGroup();
protected: // Data
// Columns in mork means value names
MorkDict columns_;
MorkDict values_;
// All mork file data
TableScopeMap mork_;
MorkCells *currentCells_;
// Error status of last operation
MorkErrors error_;
// All Mork data
std::string morkData_;
unsigned morkPos_;
int nextAddValueId_;
int defaultScope_;
int defaultListScope_;
int defaultTableId_;
// Indicates intity is being parsed
enum { NPColumns, NPValues, NPRows } nowParsing_;
private:
MorkParser(const MorkParser &);
MorkParser &operator=(const MorkParser &);
};
#endif // __MorkParser_h__
/* vim:set shiftwidth=4 softtabstop=4 expandtab: */
<commit_msg>Typo: Rerturns -> Returns<commit_after>/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */
/*
* Software License Agreement (BSD License)
*
* Copyright (c) 2006, ScalingWeb.com
* All rights reserved.
*
* Redistribution and use of this software 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 ScalingWeb.com nor the names of its
* contributors may be used to endorse or promote products
* derived from this software without specific prior
* written permission of ScalingWeb.com.
* 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.
*/
#ifndef INCLUDED_CONNECTIVITY_SOURCE_DRIVERS_MORK_MORKPARSER_HXX
#define INCLUDED_CONNECTIVITY_SOURCE_DRIVERS_MORK_MORKPARSER_HXX
#include <sal/types.h>
#include <string>
#include <map>
#include <set>
#include <vector>
#include "dllapi.h"
// Types
typedef std::map< int, std::string > MorkDict;
typedef std::map< int, int > MorkCells; // ColumnId : ValueId
typedef std::map< int, MorkCells > MorkRowMap; // Row id
typedef std::map< int, MorkRowMap > RowScopeMap; // Row scope
typedef std::map< int, RowScopeMap > MorkTableMap; // Table id
typedef std::map< int, MorkTableMap > TableScopeMap; // Table Scope
// Error codes
enum MorkErrors
{
NoError = 0,
FailedToOpen,
UnsupportedVersion,
DefectedFormat
};
// Mork term types
enum MorkTerm
{
NoneTerm = 0,
DictTerm,
GroupTerm,
TableTerm,
RowTerm,
CellTerm,
CommentTerm,
LiteralTerm
};
/// Class MorkParser
class LO_DLLPUBLIC_MORK MorkParser
{
public:
MorkParser( int defaultScope = 0x80 );
/// Open and parse mork file
bool open( const std::string &path );
/// Return error status
MorkErrors error();
/// Returns all tables of specified scope
MorkTableMap *getTables( int tableScope );
/// Returns all rows under specified scope
MorkRowMap *getRows( int rowScope, RowScopeMap *table );
/// Return value of specified value oid
std::string &getValue( int oid );
/// Return value of specified column oid
std::string &getColumn( int oid );
void retrieveLists(std::set<std::string>& lists);
void getRecordKeysForListTable(std::string& listName, std::set<int>& records);
void dump();
protected: // Members
void initVars();
bool isWhiteSpace( char c );
char nextChar();
void parseScopeId( const std::string &TextId, int *Id, int *Scope );
void setCurrentRow( int TableScope, int TableId, int RowScope, int RowId );
// Parse methods
bool parse();
bool parseDict();
bool parseComment();
bool parseCell();
bool parseTable();
bool parseMeta( char c );
bool parseRow( int TableId, int TableScope );
bool parseGroup();
protected: // Data
// Columns in mork means value names
MorkDict columns_;
MorkDict values_;
// All mork file data
TableScopeMap mork_;
MorkCells *currentCells_;
// Error status of last operation
MorkErrors error_;
// All Mork data
std::string morkData_;
unsigned morkPos_;
int nextAddValueId_;
int defaultScope_;
int defaultListScope_;
int defaultTableId_;
// Indicates intity is being parsed
enum { NPColumns, NPValues, NPRows } nowParsing_;
private:
MorkParser(const MorkParser &);
MorkParser &operator=(const MorkParser &);
};
#endif // __MorkParser_h__
/* vim:set shiftwidth=4 softtabstop=4 expandtab: */
<|endoftext|> |
<commit_before>// ======================================================================== //
// Copyright 2009-2015 Intel Corporation //
// //
// 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 "thread.h"
#include "sysinfo.h"
#include "string.h"
#include <iostream>
#include <xmmintrin.h>
#if defined(PTHREADS_WIN32)
#pragma comment (lib, "pthreadVC.lib")
#endif
////////////////////////////////////////////////////////////////////////////////
/// Windows Platform
////////////////////////////////////////////////////////////////////////////////
#if defined(__WIN32__)
#define WIN32_LEAN_AND_MEAN
#include <windows.h>
namespace embree
{
/*! set the affinity of a given thread */
void setAffinity(HANDLE thread, ssize_t affinity)
{
OSVERSIONINFO osvi;
ZeroMemory(&osvi, sizeof(OSVERSIONINFO));
osvi.dwOSVersionInfoSize = sizeof(OSVERSIONINFO);
GetVersionEx(&osvi);
typedef WORD (WINAPI *GetActiveProcessorGroupCountFunc)();
typedef DWORD (WINAPI *GetActiveProcessorCountFunc)(WORD);
typedef BOOL (WINAPI *SetThreadGroupAffinityFunc)(HANDLE, const GROUP_AFFINITY *, PGROUP_AFFINITY);
typedef BOOL (WINAPI *SetThreadIdealProcessorExFunc)(HANDLE, PPROCESSOR_NUMBER, PPROCESSOR_NUMBER);
HMODULE hlib = LoadLibrary("Kernel32");
GetActiveProcessorGroupCountFunc pGetActiveProcessorGroupCount = (GetActiveProcessorGroupCountFunc)GetProcAddress(hlib, "GetActiveProcessorGroupCount");
GetActiveProcessorCountFunc pGetActiveProcessorCount = (GetActiveProcessorCountFunc)GetProcAddress(hlib, "GetActiveProcessorCount");
SetThreadGroupAffinityFunc pSetThreadGroupAffinity = (SetThreadGroupAffinityFunc)GetProcAddress(hlib, "SetThreadGroupAffinity");
SetThreadIdealProcessorExFunc pSetThreadIdealProcessorEx = (SetThreadIdealProcessorExFunc)GetProcAddress(hlib, "SetThreadIdealProcessorEx");
if (pGetActiveProcessorGroupCount && pGetActiveProcessorCount && pSetThreadGroupAffinity && pSetThreadIdealProcessorEx &&
((osvi.dwMajorVersion > 6) || ((osvi.dwMajorVersion == 6) && (osvi.dwMinorVersion >= 1))))
{
int groups = pGetActiveProcessorGroupCount();
int totalProcessors = 0, group = 0, number = 0;
for (int i = 0; i<groups; i++) {
int processors = pGetActiveProcessorCount(i);
if (totalProcessors + processors > affinity) {
group = i;
number = (int)affinity - totalProcessors;
break;
}
totalProcessors += processors;
}
GROUP_AFFINITY groupAffinity;
groupAffinity.Group = (WORD)group;
groupAffinity.Mask = (KAFFINITY)(uint64_t(1) << number);
groupAffinity.Reserved[0] = 0;
groupAffinity.Reserved[1] = 0;
groupAffinity.Reserved[2] = 0;
if (!pSetThreadGroupAffinity(thread, &groupAffinity, nullptr))
THROW_RUNTIME_ERROR("cannot set thread group affinity");
PROCESSOR_NUMBER processorNumber;
processorNumber.Group = group;
processorNumber.Number = number;
processorNumber.Reserved = 0;
if (!pSetThreadIdealProcessorEx(thread, &processorNumber, nullptr))
THROW_RUNTIME_ERROR("cannot set ideal processor");
} else {
if (!SetThreadAffinityMask(thread, DWORD_PTR(uint64_t(1) << affinity)))
THROW_RUNTIME_ERROR("cannot set thread affinity mask");
if (SetThreadIdealProcessor(thread, (DWORD)affinity) == (DWORD)-1)
THROW_RUNTIME_ERROR("cannot set ideal processor");
}
}
/*! set affinity of the calling thread */
void setAffinity(ssize_t affinity) {
setAffinity(GetCurrentThread(), affinity);
}
struct ThreadStartupData
{
public:
ThreadStartupData (thread_func f, void* arg)
: f(f), arg(arg) {}
public:
thread_func f;
void* arg;
};
static void* threadStartup(ThreadStartupData* parg)
{
_mm_setcsr(_mm_getcsr() | /*FTZ:*/ (1<<15) | /*DAZ:*/ (1<<6));
parg->f(parg->arg);
delete parg;
return nullptr;
}
#if !defined(PTHREADS_WIN32)
/*! creates a hardware thread running on specific core */
thread_t createThread(thread_func f, void* arg, size_t stack_size, ssize_t threadID)
{
HANDLE thread = CreateThread(nullptr, stack_size, (LPTHREAD_START_ROUTINE)threadStartup, new ThreadStartupData(f,arg), 0, nullptr);
if (thread == nullptr) THROW_RUNTIME_ERROR("cannot create thread");
if (threadID >= 0) setAffinity(thread, threadID);
return thread_t(thread);
}
/*! the thread calling this function gets yielded */
void yield() {
SwitchToThread();
}
/*! waits until the given thread has terminated */
void join(thread_t tid) {
WaitForSingleObject(HANDLE(tid), INFINITE);
CloseHandle(HANDLE(tid));
}
/*! destroy a hardware thread by its handle */
void destroyThread(thread_t tid) {
TerminateThread(HANDLE(tid),0);
CloseHandle(HANDLE(tid));
}
/*! creates thread local storage */
tls_t createTls() {
return tls_t(TlsAlloc());
}
/*! set the thread local storage pointer */
void setTls(tls_t tls, void* const ptr) {
TlsSetValue(DWORD(size_t(tls)), ptr);
}
/*! return the thread local storage pointer */
void* getTls(tls_t tls) {
return TlsGetValue(DWORD(size_t(tls)));
}
/*! destroys thread local storage identifier */
void destroyTls(tls_t tls) {
TlsFree(DWORD(size_t(tls)));
}
#endif
}
#endif
////////////////////////////////////////////////////////////////////////////////
/// Linux Platform
////////////////////////////////////////////////////////////////////////////////
#if defined(__LINUX__)
namespace embree
{
/*! set affinity of the calling thread */
void setAffinity(ssize_t affinity)
{
cpu_set_t cset;
CPU_ZERO(&cset);
CPU_SET(affinity, &cset);
if (pthread_setaffinity_np(pthread_self(), sizeof(cset), &cset) != 0)
std::cerr << "Thread: cannot set affinity" << std::endl;
}
ssize_t getThreadAffinity(pthread_t pth)
{
cpu_set_t cset;
CPU_ZERO(&cset);
int error = pthread_getaffinity_np(pth, sizeof(cset), &cset);
if (error != 0) perror("pthread_getaffinity_np");
for (int j=0; j<CPU_COUNT(&cset); j++)
if (CPU_ISSET(j, &cset))
return j;
return -1;
}
}
#endif
////////////////////////////////////////////////////////////////////////////////
/// MacOSX Platform
////////////////////////////////////////////////////////////////////////////////
#if defined(__MACOSX__)
#include <mach/thread_act.h>
#include <mach/thread_policy.h>
#include <mach/mach_init.h>
namespace embree
{
/*! set affinity of the calling thread */
void setAffinity(ssize_t affinity)
{
thread_affinity_policy ap;
ap.affinity_tag = affinity;
if (thread_policy_set(mach_thread_self(),THREAD_AFFINITY_POLICY,(thread_policy_t)&ap,THREAD_AFFINITY_POLICY_COUNT) != KERN_SUCCESS)
std::cerr << "Thread: cannot set affinity" << std::endl;
}
}
#endif
////////////////////////////////////////////////////////////////////////////////
/// Unix Platform
////////////////////////////////////////////////////////////////////////////////
#if defined(__UNIX__) || defined(PTHREADS_WIN32)
#include <pthread.h>
#include <sched.h>
#if defined(__USE_NUMA__)
#include <numa.h>
#endif
namespace embree
{
struct ThreadStartupData
{
public:
ThreadStartupData (thread_func f, void* arg, int affinity)
: f(f), arg(arg), affinity(affinity) {}
public:
thread_func f;
void* arg;
ssize_t affinity;
};
static void* threadStartup(ThreadStartupData* parg)
{
_mm_setcsr(_mm_getcsr() | /*FTZ:*/ (1<<15) | /*DAZ:*/ (1<<6));
#if !defined(__LINUX__)
if (parg->affinity >= 0)
setAffinity(parg->affinity);
#endif
parg->f(parg->arg);
delete parg;
return nullptr;
}
/*! creates a hardware thread running on specific core */
thread_t createThread(thread_func f, void* arg, size_t stack_size, ssize_t threadID)
{
#ifdef __MIC__
threadID++; // start counting at 1 on MIC
#endif
/* set stack size */
pthread_attr_t attr;
pthread_attr_init(&attr);
if (stack_size > 0) pthread_attr_setstacksize (&attr, stack_size);
/* create thread */
pthread_t* tid = new pthread_t;
if (pthread_create(tid,&attr,(void*(*)(void*))threadStartup,new ThreadStartupData(f,arg,threadID)) != 0)
THROW_RUNTIME_ERROR("pthread_create");
/* set affinity */
#if defined(__LINUX__)
if (threadID >= 0) {
cpu_set_t cset;
CPU_ZERO(&cset);
CPU_SET(threadID, &cset);
pthread_setaffinity_np(*tid,sizeof(cpu_set_t),&cset);
}
#endif
return thread_t(tid);
}
/*! the thread calling this function gets yielded */
void yield() {
sched_yield();
}
/*! waits until the given thread has terminated */
void join(thread_t tid) {
if (pthread_join(*(pthread_t*)tid, nullptr) != 0)
THROW_RUNTIME_ERROR("pthread_join");
delete (pthread_t*)tid;
}
/*! destroy a hardware thread by its handle */
void destroyThread(thread_t tid) {
pthread_cancel(*(pthread_t*)tid);
delete (pthread_t*)tid;
}
/*! creates thread local storage */
tls_t createTls() {
static int cntr = 0;
pthread_key_t* key = new pthread_key_t;
if (pthread_key_create(key,nullptr) != 0)
THROW_RUNTIME_ERROR("pthread_key_create");
return tls_t(key);
}
/*! return the thread local storage pointer */
void* getTls(tls_t tls)
{
assert(tls);
return pthread_getspecific(*(pthread_key_t*)tls);
}
/*! set the thread local storage pointer */
void setTls(tls_t tls, void* const ptr)
{
assert(tls);
if (pthread_setspecific(*(pthread_key_t*)tls, ptr) != 0)
THROW_RUNTIME_ERROR("pthread_setspecific");
}
/*! destroys thread local storage identifier */
void destroyTls(tls_t tls)
{
assert(tls);
if (pthread_key_delete(*(pthread_key_t*)tls) != 0)
THROW_RUNTIME_ERROR("pthread_key_delete");
delete (pthread_key_t*)tls;
}
}
#endif
<commit_msg>removed getThreadAffinity function from thread.cpp, it was causing GLIBC2.6 dependency<commit_after>// ======================================================================== //
// Copyright 2009-2015 Intel Corporation //
// //
// 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 "thread.h"
#include "sysinfo.h"
#include "string.h"
#include <iostream>
#include <xmmintrin.h>
#if defined(PTHREADS_WIN32)
#pragma comment (lib, "pthreadVC.lib")
#endif
////////////////////////////////////////////////////////////////////////////////
/// Windows Platform
////////////////////////////////////////////////////////////////////////////////
#if defined(__WIN32__)
#define WIN32_LEAN_AND_MEAN
#include <windows.h>
namespace embree
{
/*! set the affinity of a given thread */
void setAffinity(HANDLE thread, ssize_t affinity)
{
OSVERSIONINFO osvi;
ZeroMemory(&osvi, sizeof(OSVERSIONINFO));
osvi.dwOSVersionInfoSize = sizeof(OSVERSIONINFO);
GetVersionEx(&osvi);
typedef WORD (WINAPI *GetActiveProcessorGroupCountFunc)();
typedef DWORD (WINAPI *GetActiveProcessorCountFunc)(WORD);
typedef BOOL (WINAPI *SetThreadGroupAffinityFunc)(HANDLE, const GROUP_AFFINITY *, PGROUP_AFFINITY);
typedef BOOL (WINAPI *SetThreadIdealProcessorExFunc)(HANDLE, PPROCESSOR_NUMBER, PPROCESSOR_NUMBER);
HMODULE hlib = LoadLibrary("Kernel32");
GetActiveProcessorGroupCountFunc pGetActiveProcessorGroupCount = (GetActiveProcessorGroupCountFunc)GetProcAddress(hlib, "GetActiveProcessorGroupCount");
GetActiveProcessorCountFunc pGetActiveProcessorCount = (GetActiveProcessorCountFunc)GetProcAddress(hlib, "GetActiveProcessorCount");
SetThreadGroupAffinityFunc pSetThreadGroupAffinity = (SetThreadGroupAffinityFunc)GetProcAddress(hlib, "SetThreadGroupAffinity");
SetThreadIdealProcessorExFunc pSetThreadIdealProcessorEx = (SetThreadIdealProcessorExFunc)GetProcAddress(hlib, "SetThreadIdealProcessorEx");
if (pGetActiveProcessorGroupCount && pGetActiveProcessorCount && pSetThreadGroupAffinity && pSetThreadIdealProcessorEx &&
((osvi.dwMajorVersion > 6) || ((osvi.dwMajorVersion == 6) && (osvi.dwMinorVersion >= 1))))
{
int groups = pGetActiveProcessorGroupCount();
int totalProcessors = 0, group = 0, number = 0;
for (int i = 0; i<groups; i++) {
int processors = pGetActiveProcessorCount(i);
if (totalProcessors + processors > affinity) {
group = i;
number = (int)affinity - totalProcessors;
break;
}
totalProcessors += processors;
}
GROUP_AFFINITY groupAffinity;
groupAffinity.Group = (WORD)group;
groupAffinity.Mask = (KAFFINITY)(uint64_t(1) << number);
groupAffinity.Reserved[0] = 0;
groupAffinity.Reserved[1] = 0;
groupAffinity.Reserved[2] = 0;
if (!pSetThreadGroupAffinity(thread, &groupAffinity, nullptr))
THROW_RUNTIME_ERROR("cannot set thread group affinity");
PROCESSOR_NUMBER processorNumber;
processorNumber.Group = group;
processorNumber.Number = number;
processorNumber.Reserved = 0;
if (!pSetThreadIdealProcessorEx(thread, &processorNumber, nullptr))
THROW_RUNTIME_ERROR("cannot set ideal processor");
} else {
if (!SetThreadAffinityMask(thread, DWORD_PTR(uint64_t(1) << affinity)))
THROW_RUNTIME_ERROR("cannot set thread affinity mask");
if (SetThreadIdealProcessor(thread, (DWORD)affinity) == (DWORD)-1)
THROW_RUNTIME_ERROR("cannot set ideal processor");
}
}
/*! set affinity of the calling thread */
void setAffinity(ssize_t affinity) {
setAffinity(GetCurrentThread(), affinity);
}
struct ThreadStartupData
{
public:
ThreadStartupData (thread_func f, void* arg)
: f(f), arg(arg) {}
public:
thread_func f;
void* arg;
};
static void* threadStartup(ThreadStartupData* parg)
{
_mm_setcsr(_mm_getcsr() | /*FTZ:*/ (1<<15) | /*DAZ:*/ (1<<6));
parg->f(parg->arg);
delete parg;
return nullptr;
}
#if !defined(PTHREADS_WIN32)
/*! creates a hardware thread running on specific core */
thread_t createThread(thread_func f, void* arg, size_t stack_size, ssize_t threadID)
{
HANDLE thread = CreateThread(nullptr, stack_size, (LPTHREAD_START_ROUTINE)threadStartup, new ThreadStartupData(f,arg), 0, nullptr);
if (thread == nullptr) THROW_RUNTIME_ERROR("cannot create thread");
if (threadID >= 0) setAffinity(thread, threadID);
return thread_t(thread);
}
/*! the thread calling this function gets yielded */
void yield() {
SwitchToThread();
}
/*! waits until the given thread has terminated */
void join(thread_t tid) {
WaitForSingleObject(HANDLE(tid), INFINITE);
CloseHandle(HANDLE(tid));
}
/*! destroy a hardware thread by its handle */
void destroyThread(thread_t tid) {
TerminateThread(HANDLE(tid),0);
CloseHandle(HANDLE(tid));
}
/*! creates thread local storage */
tls_t createTls() {
return tls_t(TlsAlloc());
}
/*! set the thread local storage pointer */
void setTls(tls_t tls, void* const ptr) {
TlsSetValue(DWORD(size_t(tls)), ptr);
}
/*! return the thread local storage pointer */
void* getTls(tls_t tls) {
return TlsGetValue(DWORD(size_t(tls)));
}
/*! destroys thread local storage identifier */
void destroyTls(tls_t tls) {
TlsFree(DWORD(size_t(tls)));
}
#endif
}
#endif
////////////////////////////////////////////////////////////////////////////////
/// Linux Platform
////////////////////////////////////////////////////////////////////////////////
#if defined(__LINUX__)
namespace embree
{
/*! set affinity of the calling thread */
void setAffinity(ssize_t affinity)
{
cpu_set_t cset;
CPU_ZERO(&cset);
CPU_SET(affinity, &cset);
if (pthread_setaffinity_np(pthread_self(), sizeof(cset), &cset) != 0)
std::cerr << "Thread: cannot set affinity" << std::endl;
}
}
#endif
////////////////////////////////////////////////////////////////////////////////
/// MacOSX Platform
////////////////////////////////////////////////////////////////////////////////
#if defined(__MACOSX__)
#include <mach/thread_act.h>
#include <mach/thread_policy.h>
#include <mach/mach_init.h>
namespace embree
{
/*! set affinity of the calling thread */
void setAffinity(ssize_t affinity)
{
thread_affinity_policy ap;
ap.affinity_tag = affinity;
if (thread_policy_set(mach_thread_self(),THREAD_AFFINITY_POLICY,(thread_policy_t)&ap,THREAD_AFFINITY_POLICY_COUNT) != KERN_SUCCESS)
std::cerr << "Thread: cannot set affinity" << std::endl;
}
}
#endif
////////////////////////////////////////////////////////////////////////////////
/// Unix Platform
////////////////////////////////////////////////////////////////////////////////
#if defined(__UNIX__) || defined(PTHREADS_WIN32)
#include <pthread.h>
#include <sched.h>
#if defined(__USE_NUMA__)
#include <numa.h>
#endif
namespace embree
{
struct ThreadStartupData
{
public:
ThreadStartupData (thread_func f, void* arg, int affinity)
: f(f), arg(arg), affinity(affinity) {}
public:
thread_func f;
void* arg;
ssize_t affinity;
};
static void* threadStartup(ThreadStartupData* parg)
{
_mm_setcsr(_mm_getcsr() | /*FTZ:*/ (1<<15) | /*DAZ:*/ (1<<6));
#if !defined(__LINUX__)
if (parg->affinity >= 0)
setAffinity(parg->affinity);
#endif
parg->f(parg->arg);
delete parg;
return nullptr;
}
/*! creates a hardware thread running on specific core */
thread_t createThread(thread_func f, void* arg, size_t stack_size, ssize_t threadID)
{
#ifdef __MIC__
threadID++; // start counting at 1 on MIC
#endif
/* set stack size */
pthread_attr_t attr;
pthread_attr_init(&attr);
if (stack_size > 0) pthread_attr_setstacksize (&attr, stack_size);
/* create thread */
pthread_t* tid = new pthread_t;
if (pthread_create(tid,&attr,(void*(*)(void*))threadStartup,new ThreadStartupData(f,arg,threadID)) != 0)
THROW_RUNTIME_ERROR("pthread_create");
/* set affinity */
#if defined(__LINUX__)
if (threadID >= 0) {
cpu_set_t cset;
CPU_ZERO(&cset);
CPU_SET(threadID, &cset);
pthread_setaffinity_np(*tid,sizeof(cpu_set_t),&cset);
}
#endif
return thread_t(tid);
}
/*! the thread calling this function gets yielded */
void yield() {
sched_yield();
}
/*! waits until the given thread has terminated */
void join(thread_t tid) {
if (pthread_join(*(pthread_t*)tid, nullptr) != 0)
THROW_RUNTIME_ERROR("pthread_join");
delete (pthread_t*)tid;
}
/*! destroy a hardware thread by its handle */
void destroyThread(thread_t tid) {
pthread_cancel(*(pthread_t*)tid);
delete (pthread_t*)tid;
}
/*! creates thread local storage */
tls_t createTls() {
static int cntr = 0;
pthread_key_t* key = new pthread_key_t;
if (pthread_key_create(key,nullptr) != 0)
THROW_RUNTIME_ERROR("pthread_key_create");
return tls_t(key);
}
/*! return the thread local storage pointer */
void* getTls(tls_t tls)
{
assert(tls);
return pthread_getspecific(*(pthread_key_t*)tls);
}
/*! set the thread local storage pointer */
void setTls(tls_t tls, void* const ptr)
{
assert(tls);
if (pthread_setspecific(*(pthread_key_t*)tls, ptr) != 0)
THROW_RUNTIME_ERROR("pthread_setspecific");
}
/*! destroys thread local storage identifier */
void destroyTls(tls_t tls)
{
assert(tls);
if (pthread_key_delete(*(pthread_key_t*)tls) != 0)
THROW_RUNTIME_ERROR("pthread_key_delete");
delete (pthread_key_t*)tls;
}
}
#endif
<|endoftext|> |
<commit_before>// Virvo - Virtual Reality Volume Rendering
// Copyright (C) 1999-2003 University of Stuttgart, 2004-2005 Brown University
// Contact: Jurgen P. Schulze, jschulze@ucsd.edu
//
// This file is part of Virvo.
//
// Virvo 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 (see license.txt); if not, write to the
// Free Software Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
#include "vvglew.h"
#include "vvibr.h"
#include "vvibrclient.h"
#include "vvibrimage.h"
#include "vvgltools.h"
#include "vvshaderfactory.h"
#include "vvshaderprogram.h"
#include "vvtoolshed.h"
#include "vvsocketio.h"
#include "vvdebugmsg.h"
#include "vvvoldesc.h"
using std::cerr;
using std::endl;
vvIbrClient::vvIbrClient(vvVolDesc *vd, vvRenderState renderState,
const char* slaveName, int slavePort,
const char* slaveFileName)
: vvRemoteClient(vd, renderState, vvRenderer::REMOTE_IBR, slaveName, slavePort, slaveFileName)
{
vvDebugMsg::msg(1, "vvIbrClient::vvIbrClient()");
rendererType = REMOTE_IBR;
_thread = NULL;
glewInit();
glGenBuffers(1, &_pointVBO);
glGenTextures(1, &_rgbaTex);
glGenTextures(1, &_depthTex);
_haveFrame = false; // no rendered frame available
_newFrame = true; // request a new frame
_image = new vvIbrImage;
_shaderFactory = new vvShaderFactory();
_shader = _shaderFactory->createProgram("ibr", "", "");
if(!_shader)
vvDebugMsg::msg(0, "vvIbrClient::vvIbrClient: could not find ibr shader");
createThreads();
}
vvIbrClient::~vvIbrClient()
{
vvDebugMsg::msg(1, "vvIbrClient::~vvIbrClient()");
destroyThreads();
glDeleteBuffers(1, &_pointVBO);
glDeleteTextures(1, &_rgbaTex);
glDeleteTextures(1, &_depthTex);
delete _shaderFactory;
delete _shader;
delete _image;
}
vvRemoteClient::ErrorType vvIbrClient::render()
{
vvDebugMsg::msg(1, "vvIbrClient::render()");
pthread_mutex_lock(&_signalMutex);
bool haveFrame = _haveFrame;
bool newFrame = _newFrame;
pthread_mutex_unlock(&_signalMutex);
// Draw boundary lines
if (_boundaries || !haveFrame)
{
const vvVector3 size(vd->getSize()); // volume size [world coordinates]
drawBoundingBox(&size, &vd->pos, &_boundColor);
}
if (_shader == NULL)
{
return vvRemoteClient::VV_SHADER_ERROR;
}
vvGLTools::getModelviewMatrix(&_currentMv);
vvGLTools::getProjectionMatrix(&_currentPr);
vvMatrix currentMatrix = _currentMv * _currentPr;
if(newFrame && haveFrame)
{
pthread_mutex_lock(&_imageMutex);
initIbrFrame();
pthread_mutex_unlock(&_imageMutex);
}
float drMin = 0.0f;
float drMax = 0.0f;
vvIbr::calcDepthRange(_currentPr, _currentMv,
vd->getBoundingBox(),
drMin, drMax);
const vvGLTools::Viewport vp = vvGLTools::getViewport();
vvMatrix currentImgMatrix = vvIbr::calcImgMatrix(_currentPr, _currentMv, vp, drMin, drMax);
const bool matrixChanged = (!currentImgMatrix.equal(&_imgMatrix));
if (newFrame) // no frame pending
{
_changes |= matrixChanged;
if(_changes)
{
pthread_mutex_lock(&_signalMutex);
vvRemoteClient::ErrorType err = requestIbrFrame();
pthread_cond_signal(&_imageCond);
_newFrame = false;
pthread_mutex_unlock(&_signalMutex);
_changes = false;
if(err != vvRemoteClient::VV_OK)
std::cerr << "vvibrClient::requestIbrFrame() - error() " << err << std::endl;
}
}
if(!haveFrame)
{
// no frame was yet received
return VV_OK;
}
glEnable(GL_BLEND);
glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA);
// prepare VBOs
glBindBuffer(GL_ARRAY_BUFFER, _pointVBO);
glVertexPointer(3, GL_FLOAT, 0, NULL);
glEnableClientState(GL_VERTEX_ARRAY);
vvMatrix reprojectionMatrix;
if (!matrixChanged)
{
reprojectionMatrix.identity();
}
else
{
vvMatrix invOld;
invOld = _imgMv * _imgPr;
invOld.invert();
reprojectionMatrix = invOld * currentMatrix;
}
vvMatrix invMv = _currentMv;
invMv.invert();
vvVector4 viewerObj(0.f, 0.f, 0.f, 1.f);
viewerObj.multiply(&invMv);
viewerObj.multiply(&_imgMv);
bool closer = viewerObj[2] > 0.f; // inverse render order if viewer has moved closer
// project current viewer onto original image along its normal
viewerObj.multiply(&_imgPr);
float splitX = (viewerObj[0]/viewerObj[3]+1.f)*_imgVp[2]*0.5f;
float splitY = (viewerObj[1]/viewerObj[3]+1.f)*_imgVp[3]*0.5f;
splitX = ts_clamp(splitX, 0.f, float(_imgVp[2]-1));
splitY = ts_clamp(splitY, 0.f, float(_imgVp[3]-1));
_shader->enable();
_shader->setParameter1f("vpWidth", _viewportWidth);
_shader->setParameter1f("vpHeight", _viewportHeight);
_shader->setParameter1f("imageWidth", _imgVp[2]);
_shader->setParameter1f("imageHeight", _imgVp[3]);
_shader->setParameterTex2D("rgbaTex", _rgbaTex);
_shader->setParameterTex2D("depthTex", _depthTex);
_shader->setParameter1f("splitX", splitX);
_shader->setParameter1f("splitY", splitY);
_shader->setParameter1f("depthMin", _imgDepthRange[0]);
_shader->setParameter1f("depthRange", _imgDepthRange[1]-_imgDepthRange[0]);
_shader->setParameter1i("closer", closer);
_shader->setParameterMatrix4f("reprojectionMatrix" , reprojectionMatrix);
glEnable(GL_VERTEX_PROGRAM_POINT_SIZE);
glDrawArrays(GL_POINTS, 0, _imgVp[2]*_imgVp[3]);
_shader->disable();
glDisableClientState(GL_VERTEX_ARRAY);
glBindBuffer(GL_ARRAY_BUFFER, 0);
return VV_OK;
}
vvRemoteClient::ErrorType vvIbrClient::requestIbrFrame()
{
vvDebugMsg::msg(1, "vvIbrClient::requestIbrFrame()");
if(_socket->putCommReason(vvSocketIO::VV_MATRIX) != vvSocket::VV_OK)
return vvRemoteClient::VV_SOCKET_ERROR;
if(_socket->putMatrix(&_currentPr) != vvSocket::VV_OK)
return vvRemoteClient::VV_SOCKET_ERROR;
if(_socket->putMatrix(&_currentMv) != vvSocket::VV_OK)
return vvRemoteClient::VV_SOCKET_ERROR;
return vvRemoteClient::VV_OK;
}
void vvIbrClient::initIbrFrame()
{
vvDebugMsg::msg(1, "vvIbrClient::initIbrFrame()");
const int h = _image->getHeight();
const int w = _image->getWidth();
_imgMatrix = _image->getReprojectionMatrix();
_imgPr = _image->getProjectionMatrix();
_imgMv = _image->getModelViewMatrix();
_image->getDepthRange(&_imgDepthRange[0], &_imgDepthRange[1]);
// get pixel and depth-data
glBindTexture(GL_TEXTURE_2D, _rgbaTex);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_CLAMP);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_CLAMP);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_NEAREST);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_NEAREST);
glPixelStorei(GL_UNPACK_ALIGNMENT, 1);
glTexImage2D(GL_TEXTURE_2D, 0, GL_RGBA, w, h, 0, GL_RGBA, GL_UNSIGNED_BYTE, _image->getImagePtr());
glBindTexture(GL_TEXTURE_2D, _depthTex);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_CLAMP);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_CLAMP);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_NEAREST);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_NEAREST);
glPixelStorei(GL_UNPACK_ALIGNMENT, 1);
uchar* depth = _image->getPixelDepth();
switch(_image->getDepthPrecision())
{
case 8:
glTexImage2D(GL_TEXTURE_2D, 0, GL_LUMINANCE, w, h, 0, GL_LUMINANCE, GL_UNSIGNED_BYTE, depth);
break;
case 16:
glTexImage2D(GL_TEXTURE_2D, 0, GL_LUMINANCE16, w, h, 0, GL_LUMINANCE, GL_UNSIGNED_SHORT, depth);
break;
case 32:
glTexImage2D(GL_TEXTURE_2D, 0, GL_LUMINANCE32F_ARB, w, h, 0, GL_LUMINANCE, GL_FLOAT, depth);
break;
}
if(_imgVp[2] == w && _imgVp[3] == h)
return;
_imgVp = _image->getViewport();
std::vector<GLfloat> points(w*h*3);
for(int y = 0; y<h; y++)
{
for(int x = 0; x<w; x++)
{
points[y*w*3+x*3] = x;
points[y*w*3+x*3+1] = y;
points[y*w*3+x*3+2] = 0.f;
}
}
// VBO for points
glBindBuffer(GL_ARRAY_BUFFER, _pointVBO);
glBufferData(GL_ARRAY_BUFFER, points.size() * sizeof(GLfloat), &points[0], GL_STATIC_DRAW);
glBindBuffer(GL_ARRAY_BUFFER, 0);
}
void vvIbrClient::exit()
{
vvDebugMsg::msg(1, "vvIbrClient::exit()");
_socket->putCommReason(vvSocketIO::VV_EXIT);
delete _socket;
}
void vvIbrClient::createThreads()
{
vvDebugMsg::msg(1, "vvIbrClient::createThreads()");
pthread_mutex_init(&_imageMutex, NULL);
pthread_mutex_init(&_signalMutex, NULL);
pthread_cond_init(&_imageCond, NULL);
_thread = new pthread_t;
pthread_create(_thread, NULL, getImageFromSocket, this);
}
void vvIbrClient::destroyThreads()
{
vvDebugMsg::msg(1, "vvIbrClient::destroyThreads()");
exit();
pthread_cancel(*_thread);
pthread_join(*_thread, NULL);
delete _thread;
_thread = NULL;
pthread_mutex_destroy(&_imageMutex);
pthread_mutex_destroy(&_signalMutex);
pthread_cond_destroy(&_imageCond);
}
void* vvIbrClient::getImageFromSocket(void* threadargs)
{
vvDebugMsg::msg(1, "vvIbrClient::getImageFromSocket()");
std::cerr << "Image thread start" << std::endl;
vvIbrClient *ibr = static_cast<vvIbrClient*>(threadargs);
vvIbrImage* img = ibr->_image;
while (1)
{
pthread_mutex_lock( &ibr->_imageMutex );
pthread_cond_wait(&ibr->_imageCond, &ibr->_imageMutex);
vvSocketIO::ErrorType err = ibr->_socket->getIbrImage(img);
img->decode();
if(err != vvSocketIO::VV_OK)
{
std::cerr << "vvIbrClient::getImageFromSocket: socket-error (" << err << ") - exiting..." << std::endl;
pthread_mutex_unlock( &ibr->_imageMutex );
break;
}
pthread_mutex_unlock( &ibr->_imageMutex );
//vvToolshed::sleep(1000);
pthread_mutex_lock( &ibr->_signalMutex );
ibr->_newFrame = true;
ibr->_haveFrame = true;
pthread_mutex_unlock( &ibr->_signalMutex );
}
pthread_exit(NULL);
#ifdef _WIN32
return NULL;
#endif
}
// vim: sw=2:expandtab:softtabstop=2:ts=2:cino=\:0g0t0
<commit_msg>don't decode a possibly faulty image<commit_after>// Virvo - Virtual Reality Volume Rendering
// Copyright (C) 1999-2003 University of Stuttgart, 2004-2005 Brown University
// Contact: Jurgen P. Schulze, jschulze@ucsd.edu
//
// This file is part of Virvo.
//
// Virvo 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 (see license.txt); if not, write to the
// Free Software Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
#include "vvglew.h"
#include "vvibr.h"
#include "vvibrclient.h"
#include "vvibrimage.h"
#include "vvgltools.h"
#include "vvshaderfactory.h"
#include "vvshaderprogram.h"
#include "vvtoolshed.h"
#include "vvsocketio.h"
#include "vvdebugmsg.h"
#include "vvvoldesc.h"
using std::cerr;
using std::endl;
vvIbrClient::vvIbrClient(vvVolDesc *vd, vvRenderState renderState,
const char* slaveName, int slavePort,
const char* slaveFileName)
: vvRemoteClient(vd, renderState, vvRenderer::REMOTE_IBR, slaveName, slavePort, slaveFileName)
{
vvDebugMsg::msg(1, "vvIbrClient::vvIbrClient()");
rendererType = REMOTE_IBR;
_thread = NULL;
glewInit();
glGenBuffers(1, &_pointVBO);
glGenTextures(1, &_rgbaTex);
glGenTextures(1, &_depthTex);
_haveFrame = false; // no rendered frame available
_newFrame = true; // request a new frame
_image = new vvIbrImage;
_shaderFactory = new vvShaderFactory();
_shader = _shaderFactory->createProgram("ibr", "", "");
if(!_shader)
vvDebugMsg::msg(0, "vvIbrClient::vvIbrClient: could not find ibr shader");
createThreads();
}
vvIbrClient::~vvIbrClient()
{
vvDebugMsg::msg(1, "vvIbrClient::~vvIbrClient()");
destroyThreads();
glDeleteBuffers(1, &_pointVBO);
glDeleteTextures(1, &_rgbaTex);
glDeleteTextures(1, &_depthTex);
delete _shaderFactory;
delete _shader;
delete _image;
}
vvRemoteClient::ErrorType vvIbrClient::render()
{
vvDebugMsg::msg(1, "vvIbrClient::render()");
pthread_mutex_lock(&_signalMutex);
bool haveFrame = _haveFrame;
bool newFrame = _newFrame;
pthread_mutex_unlock(&_signalMutex);
// Draw boundary lines
if (_boundaries || !haveFrame)
{
const vvVector3 size(vd->getSize()); // volume size [world coordinates]
drawBoundingBox(&size, &vd->pos, &_boundColor);
}
if (_shader == NULL)
{
return vvRemoteClient::VV_SHADER_ERROR;
}
vvGLTools::getModelviewMatrix(&_currentMv);
vvGLTools::getProjectionMatrix(&_currentPr);
vvMatrix currentMatrix = _currentMv * _currentPr;
if(newFrame && haveFrame)
{
pthread_mutex_lock(&_imageMutex);
initIbrFrame();
pthread_mutex_unlock(&_imageMutex);
}
float drMin = 0.0f;
float drMax = 0.0f;
vvIbr::calcDepthRange(_currentPr, _currentMv,
vd->getBoundingBox(),
drMin, drMax);
const vvGLTools::Viewport vp = vvGLTools::getViewport();
vvMatrix currentImgMatrix = vvIbr::calcImgMatrix(_currentPr, _currentMv, vp, drMin, drMax);
const bool matrixChanged = (!currentImgMatrix.equal(&_imgMatrix));
if (newFrame) // no frame pending
{
_changes |= matrixChanged;
if(_changes)
{
pthread_mutex_lock(&_signalMutex);
vvRemoteClient::ErrorType err = requestIbrFrame();
pthread_cond_signal(&_imageCond);
_newFrame = false;
pthread_mutex_unlock(&_signalMutex);
_changes = false;
if(err != vvRemoteClient::VV_OK)
std::cerr << "vvibrClient::requestIbrFrame() - error() " << err << std::endl;
}
}
if(!haveFrame)
{
// no frame was yet received
return VV_OK;
}
glEnable(GL_BLEND);
glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA);
// prepare VBOs
glBindBuffer(GL_ARRAY_BUFFER, _pointVBO);
glVertexPointer(3, GL_FLOAT, 0, NULL);
glEnableClientState(GL_VERTEX_ARRAY);
vvMatrix reprojectionMatrix;
if (!matrixChanged)
{
reprojectionMatrix.identity();
}
else
{
vvMatrix invOld;
invOld = _imgMv * _imgPr;
invOld.invert();
reprojectionMatrix = invOld * currentMatrix;
}
vvMatrix invMv = _currentMv;
invMv.invert();
vvVector4 viewerObj(0.f, 0.f, 0.f, 1.f);
viewerObj.multiply(&invMv);
viewerObj.multiply(&_imgMv);
bool closer = viewerObj[2] > 0.f; // inverse render order if viewer has moved closer
// project current viewer onto original image along its normal
viewerObj.multiply(&_imgPr);
float splitX = (viewerObj[0]/viewerObj[3]+1.f)*_imgVp[2]*0.5f;
float splitY = (viewerObj[1]/viewerObj[3]+1.f)*_imgVp[3]*0.5f;
splitX = ts_clamp(splitX, 0.f, float(_imgVp[2]-1));
splitY = ts_clamp(splitY, 0.f, float(_imgVp[3]-1));
_shader->enable();
_shader->setParameter1f("vpWidth", _viewportWidth);
_shader->setParameter1f("vpHeight", _viewportHeight);
_shader->setParameter1f("imageWidth", _imgVp[2]);
_shader->setParameter1f("imageHeight", _imgVp[3]);
_shader->setParameterTex2D("rgbaTex", _rgbaTex);
_shader->setParameterTex2D("depthTex", _depthTex);
_shader->setParameter1f("splitX", splitX);
_shader->setParameter1f("splitY", splitY);
_shader->setParameter1f("depthMin", _imgDepthRange[0]);
_shader->setParameter1f("depthRange", _imgDepthRange[1]-_imgDepthRange[0]);
_shader->setParameter1i("closer", closer);
_shader->setParameterMatrix4f("reprojectionMatrix" , reprojectionMatrix);
glEnable(GL_VERTEX_PROGRAM_POINT_SIZE);
glDrawArrays(GL_POINTS, 0, _imgVp[2]*_imgVp[3]);
_shader->disable();
glDisableClientState(GL_VERTEX_ARRAY);
glBindBuffer(GL_ARRAY_BUFFER, 0);
return VV_OK;
}
vvRemoteClient::ErrorType vvIbrClient::requestIbrFrame()
{
vvDebugMsg::msg(1, "vvIbrClient::requestIbrFrame()");
if(_socket->putCommReason(vvSocketIO::VV_MATRIX) != vvSocket::VV_OK)
return vvRemoteClient::VV_SOCKET_ERROR;
if(_socket->putMatrix(&_currentPr) != vvSocket::VV_OK)
return vvRemoteClient::VV_SOCKET_ERROR;
if(_socket->putMatrix(&_currentMv) != vvSocket::VV_OK)
return vvRemoteClient::VV_SOCKET_ERROR;
return vvRemoteClient::VV_OK;
}
void vvIbrClient::initIbrFrame()
{
vvDebugMsg::msg(1, "vvIbrClient::initIbrFrame()");
const int h = _image->getHeight();
const int w = _image->getWidth();
_imgMatrix = _image->getReprojectionMatrix();
_imgPr = _image->getProjectionMatrix();
_imgMv = _image->getModelViewMatrix();
_image->getDepthRange(&_imgDepthRange[0], &_imgDepthRange[1]);
// get pixel and depth-data
glBindTexture(GL_TEXTURE_2D, _rgbaTex);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_CLAMP);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_CLAMP);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_NEAREST);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_NEAREST);
glPixelStorei(GL_UNPACK_ALIGNMENT, 1);
glTexImage2D(GL_TEXTURE_2D, 0, GL_RGBA, w, h, 0, GL_RGBA, GL_UNSIGNED_BYTE, _image->getImagePtr());
glBindTexture(GL_TEXTURE_2D, _depthTex);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_CLAMP);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_CLAMP);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_NEAREST);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_NEAREST);
glPixelStorei(GL_UNPACK_ALIGNMENT, 1);
uchar* depth = _image->getPixelDepth();
switch(_image->getDepthPrecision())
{
case 8:
glTexImage2D(GL_TEXTURE_2D, 0, GL_LUMINANCE, w, h, 0, GL_LUMINANCE, GL_UNSIGNED_BYTE, depth);
break;
case 16:
glTexImage2D(GL_TEXTURE_2D, 0, GL_LUMINANCE16, w, h, 0, GL_LUMINANCE, GL_UNSIGNED_SHORT, depth);
break;
case 32:
glTexImage2D(GL_TEXTURE_2D, 0, GL_LUMINANCE32F_ARB, w, h, 0, GL_LUMINANCE, GL_FLOAT, depth);
break;
}
if(_imgVp[2] == w && _imgVp[3] == h)
return;
_imgVp = _image->getViewport();
std::vector<GLfloat> points(w*h*3);
for(int y = 0; y<h; y++)
{
for(int x = 0; x<w; x++)
{
points[y*w*3+x*3] = x;
points[y*w*3+x*3+1] = y;
points[y*w*3+x*3+2] = 0.f;
}
}
// VBO for points
glBindBuffer(GL_ARRAY_BUFFER, _pointVBO);
glBufferData(GL_ARRAY_BUFFER, points.size() * sizeof(GLfloat), &points[0], GL_STATIC_DRAW);
glBindBuffer(GL_ARRAY_BUFFER, 0);
}
void vvIbrClient::exit()
{
vvDebugMsg::msg(1, "vvIbrClient::exit()");
_socket->putCommReason(vvSocketIO::VV_EXIT);
delete _socket;
}
void vvIbrClient::createThreads()
{
vvDebugMsg::msg(1, "vvIbrClient::createThreads()");
pthread_mutex_init(&_imageMutex, NULL);
pthread_mutex_init(&_signalMutex, NULL);
pthread_cond_init(&_imageCond, NULL);
_thread = new pthread_t;
pthread_create(_thread, NULL, getImageFromSocket, this);
}
void vvIbrClient::destroyThreads()
{
vvDebugMsg::msg(1, "vvIbrClient::destroyThreads()");
exit();
pthread_cancel(*_thread);
pthread_join(*_thread, NULL);
delete _thread;
_thread = NULL;
pthread_mutex_destroy(&_imageMutex);
pthread_mutex_destroy(&_signalMutex);
pthread_cond_destroy(&_imageCond);
}
void* vvIbrClient::getImageFromSocket(void* threadargs)
{
vvDebugMsg::msg(1, "vvIbrClient::getImageFromSocket()");
std::cerr << "Image thread start" << std::endl;
vvIbrClient *ibr = static_cast<vvIbrClient*>(threadargs);
vvIbrImage* img = ibr->_image;
while (1)
{
pthread_mutex_lock( &ibr->_imageMutex );
pthread_cond_wait(&ibr->_imageCond, &ibr->_imageMutex);
vvSocketIO::ErrorType err = ibr->_socket->getIbrImage(img);
if(err != vvSocketIO::VV_OK)
{
std::cerr << "vvIbrClient::getImageFromSocket: socket-error (" << err << ") - exiting..." << std::endl;
pthread_mutex_unlock( &ibr->_imageMutex );
break;
}
img->decode();
pthread_mutex_unlock( &ibr->_imageMutex );
//vvToolshed::sleep(1000);
pthread_mutex_lock( &ibr->_signalMutex );
ibr->_newFrame = true;
ibr->_haveFrame = true;
pthread_mutex_unlock( &ibr->_signalMutex );
}
pthread_exit(NULL);
#ifdef _WIN32
return NULL;
#endif
}
// vim: sw=2:expandtab:softtabstop=2:ts=2:cino=\:0g0t0
<|endoftext|> |
<commit_before>/*************************************************************************
*
* $RCSfile: RTableConnectionData.hxx,v $
*
* $Revision: 1.4 $
*
* last change: $Author: oj $ $Date: 2002-02-06 07:23:39 $
*
* 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_RTABLECONNECTIONDATA_HXX
#define DBAUI_RTABLECONNECTIONDATA_HXX
#ifndef DBAUI_TABLECONNECTIONDATA_HXX
#include "TableConnectionData.hxx"
#endif
#ifndef _COM_SUN_STAR_BEANS_XPROPERTYSET_HPP_
#include <com/sun/star/beans/XPropertySet.hpp>
#endif
#ifndef _COM_SUN_STAR_CONTAINER_XNAMEACCESS_HPP_
#include <com/sun/star/container/XNameAccess.hpp>
#endif
#ifndef DBAUI_ENUMTYPES_HXX
#include "QEnumTypes.hxx"
#endif
#ifndef _UNOTOOLS_EVENTLISTENERADAPTER_HXX_
#include <unotools/eventlisteneradapter.hxx>
#endif
namespace dbaui
{
const UINT16 CARDINAL_UNDEFINED = 0x0000;
const UINT16 CARDINAL_ONE_MANY = 0x0001;
const UINT16 CARDINAL_MANY_ONE = 0x0002;
const UINT16 CARDINAL_ONE_ONE = 0x0004;
class OConnectionLineData;
//==================================================================
class ORelationTableConnectionData : public OTableConnectionData,
public ::utl::OEventListenerAdapter
{
::osl::Mutex m_aMutex;
::rtl::OUString m_sDatabaseName;
::com::sun::star::uno::Reference< ::com::sun::star::container::XNameAccess> m_xTables;
::com::sun::star::uno::Reference< ::com::sun::star::beans::XPropertySet> m_xSource;
::com::sun::star::uno::Reference< ::com::sun::star::beans::XPropertySet> m_xDest;
// @see com.sun.star.sdbc.KeyRule
sal_Int32 m_nUpdateRules;
sal_Int32 m_nDeleteRules;
sal_Int32 m_nCardinality;
BOOL checkPrimaryKey(const ::com::sun::star::uno::Reference< ::com::sun::star::beans::XPropertySet>& _xTable,EConnectionSide _eEConnectionSide) const;
BOOL IsSourcePrimKey() const { return checkPrimaryKey(m_xSource,JTCS_FROM); }
BOOL IsDestPrimKey() const { return checkPrimaryKey(m_xDest,JTCS_TO); }
void addListening(const ::com::sun::star::uno::Reference< ::com::sun::star::uno::XInterface>& _rxComponent);
void removeListening(const ::com::sun::star::uno::Reference< ::com::sun::star::uno::XInterface>& _rxComponent);
protected:
virtual OConnectionLineDataRef CreateLineDataObj();
virtual OConnectionLineDataRef CreateLineDataObj( const OConnectionLineData& rConnLineData );
ORelationTableConnectionData& operator=( const ORelationTableConnectionData& rConnData );
public:
ORelationTableConnectionData();
ORelationTableConnectionData( const ::com::sun::star::uno::Reference< ::com::sun::star::container::XNameAccess>& _xTables);
ORelationTableConnectionData( const ORelationTableConnectionData& rConnData );
ORelationTableConnectionData( const ::com::sun::star::uno::Reference< ::com::sun::star::container::XNameAccess>& _xTables,
const ::rtl::OUString& rSourceWinName,
const ::rtl::OUString& rDestWinName,
const ::rtl::OUString& rConnName = ::rtl::OUString() );
virtual ~ORelationTableConnectionData();
virtual void CopyFrom(const OTableConnectionData& rSource);
virtual OTableConnectionData* NewInstance() const { return new ORelationTableConnectionData(); }
::rtl::OUString GetDatabaseName() const { return m_sDatabaseName; }
::com::sun::star::uno::Reference< ::com::sun::star::container::XNameAccess> getTables() const { return m_xTables;}
::com::sun::star::uno::Reference< ::com::sun::star::beans::XPropertySet> getSource() const { return m_xSource;}
::com::sun::star::uno::Reference< ::com::sun::star::beans::XPropertySet> getDest() const { return m_xDest; }
virtual void SetSourceWinName( const String& rSourceWinName );
virtual void SetDestWinName( const String& rDestWinName );
/** Update create a new relation
@return true if successful
*/
virtual BOOL Update();
void SetCardinality();
void SetUpdateRules( sal_Int32 nAttr ){ m_nUpdateRules = nAttr; }
void SetDeleteRules( sal_Int32 nAttr ){ m_nDeleteRules = nAttr; }
sal_Int32 GetUpdateRules() const { return m_nUpdateRules; }
sal_Int32 GetDeleteRules() const { return m_nDeleteRules; }
sal_Int32 GetCardinality() const { return m_nCardinality; }
BOOL IsConnectionPossible();
void ChangeOrientation();
BOOL DropRelation();
// OEventListenerAdapter
virtual void _disposing( const ::com::sun::star::lang::EventObject& _rSource );
};
}
#endif // DBAUI_RTABLECONNECTIONDATA_HXX
<commit_msg>INTEGRATION: CWS ooo19126 (1.4.480); FILE MERGED 2005/09/05 17:34:23 rt 1.4.480.1: #i54170# Change license header: remove SISSL<commit_after>/*************************************************************************
*
* OpenOffice.org - a multi-platform office productivity suite
*
* $RCSfile: RTableConnectionData.hxx,v $
*
* $Revision: 1.5 $
*
* last change: $Author: rt $ $Date: 2005-09-08 15:31:28 $
*
* 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 DBAUI_RTABLECONNECTIONDATA_HXX
#define DBAUI_RTABLECONNECTIONDATA_HXX
#ifndef DBAUI_TABLECONNECTIONDATA_HXX
#include "TableConnectionData.hxx"
#endif
#ifndef _COM_SUN_STAR_BEANS_XPROPERTYSET_HPP_
#include <com/sun/star/beans/XPropertySet.hpp>
#endif
#ifndef _COM_SUN_STAR_CONTAINER_XNAMEACCESS_HPP_
#include <com/sun/star/container/XNameAccess.hpp>
#endif
#ifndef DBAUI_ENUMTYPES_HXX
#include "QEnumTypes.hxx"
#endif
#ifndef _UNOTOOLS_EVENTLISTENERADAPTER_HXX_
#include <unotools/eventlisteneradapter.hxx>
#endif
namespace dbaui
{
const UINT16 CARDINAL_UNDEFINED = 0x0000;
const UINT16 CARDINAL_ONE_MANY = 0x0001;
const UINT16 CARDINAL_MANY_ONE = 0x0002;
const UINT16 CARDINAL_ONE_ONE = 0x0004;
class OConnectionLineData;
//==================================================================
class ORelationTableConnectionData : public OTableConnectionData,
public ::utl::OEventListenerAdapter
{
::osl::Mutex m_aMutex;
::rtl::OUString m_sDatabaseName;
::com::sun::star::uno::Reference< ::com::sun::star::container::XNameAccess> m_xTables;
::com::sun::star::uno::Reference< ::com::sun::star::beans::XPropertySet> m_xSource;
::com::sun::star::uno::Reference< ::com::sun::star::beans::XPropertySet> m_xDest;
// @see com.sun.star.sdbc.KeyRule
sal_Int32 m_nUpdateRules;
sal_Int32 m_nDeleteRules;
sal_Int32 m_nCardinality;
BOOL checkPrimaryKey(const ::com::sun::star::uno::Reference< ::com::sun::star::beans::XPropertySet>& _xTable,EConnectionSide _eEConnectionSide) const;
BOOL IsSourcePrimKey() const { return checkPrimaryKey(m_xSource,JTCS_FROM); }
BOOL IsDestPrimKey() const { return checkPrimaryKey(m_xDest,JTCS_TO); }
void addListening(const ::com::sun::star::uno::Reference< ::com::sun::star::uno::XInterface>& _rxComponent);
void removeListening(const ::com::sun::star::uno::Reference< ::com::sun::star::uno::XInterface>& _rxComponent);
protected:
virtual OConnectionLineDataRef CreateLineDataObj();
virtual OConnectionLineDataRef CreateLineDataObj( const OConnectionLineData& rConnLineData );
ORelationTableConnectionData& operator=( const ORelationTableConnectionData& rConnData );
public:
ORelationTableConnectionData();
ORelationTableConnectionData( const ::com::sun::star::uno::Reference< ::com::sun::star::container::XNameAccess>& _xTables);
ORelationTableConnectionData( const ORelationTableConnectionData& rConnData );
ORelationTableConnectionData( const ::com::sun::star::uno::Reference< ::com::sun::star::container::XNameAccess>& _xTables,
const ::rtl::OUString& rSourceWinName,
const ::rtl::OUString& rDestWinName,
const ::rtl::OUString& rConnName = ::rtl::OUString() );
virtual ~ORelationTableConnectionData();
virtual void CopyFrom(const OTableConnectionData& rSource);
virtual OTableConnectionData* NewInstance() const { return new ORelationTableConnectionData(); }
::rtl::OUString GetDatabaseName() const { return m_sDatabaseName; }
::com::sun::star::uno::Reference< ::com::sun::star::container::XNameAccess> getTables() const { return m_xTables;}
::com::sun::star::uno::Reference< ::com::sun::star::beans::XPropertySet> getSource() const { return m_xSource;}
::com::sun::star::uno::Reference< ::com::sun::star::beans::XPropertySet> getDest() const { return m_xDest; }
virtual void SetSourceWinName( const String& rSourceWinName );
virtual void SetDestWinName( const String& rDestWinName );
/** Update create a new relation
@return true if successful
*/
virtual BOOL Update();
void SetCardinality();
void SetUpdateRules( sal_Int32 nAttr ){ m_nUpdateRules = nAttr; }
void SetDeleteRules( sal_Int32 nAttr ){ m_nDeleteRules = nAttr; }
sal_Int32 GetUpdateRules() const { return m_nUpdateRules; }
sal_Int32 GetDeleteRules() const { return m_nDeleteRules; }
sal_Int32 GetCardinality() const { return m_nCardinality; }
BOOL IsConnectionPossible();
void ChangeOrientation();
BOOL DropRelation();
// OEventListenerAdapter
virtual void _disposing( const ::com::sun::star::lang::EventObject& _rSource );
};
}
#endif // DBAUI_RTABLECONNECTIONDATA_HXX
<|endoftext|> |
<commit_before>/*************************************************************************
*
* $RCSfile: QTableWindow.cxx,v $
*
* $Revision: 1.14 $
*
* last change: $Author: rt $ $Date: 2003-12-01 10:38:18 $
*
* 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_QUERY_TABLEWINDOWDATA_HXX
#include "QTableWindow.hxx"
#endif
#ifndef DBAUI_QUERYTABLEVIEW_HXX
#include "QueryTableView.hxx"
#endif
#ifndef DBACCESS_SHARED_DBUSTRINGS_HRC
#include "dbustrings.hrc"
#endif
#ifndef _TOOLS_DEBUG_HXX
#include <tools/debug.hxx>
#endif
#include "dbaccess_helpid.hrc"
#ifndef DBAUI_QUERYDESIGNVIEW_HXX
#include "QueryDesignView.hxx"
#endif
#ifndef DBACCESS_UI_BROWSER_ID_HXX
#include "browserids.hxx"
#endif
#ifndef DBAUI_QUERYCONTROLLER_HXX
#include "querycontroller.hxx"
#endif
#ifndef _SV_IMAGE_HXX
#include <vcl/image.hxx>
#endif
#ifndef DBAUI_TABLEWINDOWLISTBOX_HXX
#include "TableWindowListBox.hxx"
#endif
#ifndef _DBU_QRY_HRC_
#include "dbu_qry.hrc"
#endif
#ifndef _DBAUI_MODULE_DBU_HXX_
#include "moduledbu.hxx"
#endif
#ifndef DBAUI_QUERY_HRC
#include "Query.hrc"
#endif
#ifndef _COM_SUN_STAR_SDBCX_XKEYSSUPPLIER_HPP_
#include <com/sun/star/sdbcx/XKeysSupplier.hpp>
#endif
#ifndef _COM_SUN_STAR_CONTAINER_XNAMEACCESS_HPP_
#include <com/sun/star/container/XNameAccess.hpp>
#endif
#ifndef _COM_SUN_STAR_CONTAINER_XINDEXACCESS_HPP_
#include <com/sun/star/container/XIndexAccess.hpp>
#endif
#ifndef _COM_SUN_STAR_BEANS_XPROPERTYSET_HPP_
#include <com/sun/star/beans/XPropertySet.hpp>
#endif
#ifndef _COM_SUN_STAR_SDBCX_KEYTYPE_HPP_
#include <com/sun/star/sdbcx/KeyType.hpp>
#endif
#ifndef _COM_SUN_STAR_SDBCX_XCOLUMNSSUPPLIER_HPP_
#include <com/sun/star/sdbcx/XColumnsSupplier.hpp>
#endif
#ifndef DBAUI_TABLEFIELDINFO_HXX
#include "TableFieldInfo.hxx"
#endif
#ifndef _COMPHELPER_UNO3_HXX_
#include <comphelper/uno3.hxx>
#endif
#ifndef _COMPHELPER_EXTRACT_HXX_
#include <comphelper/extract.hxx>
#endif
#ifndef DBAUI_TOOLS_HXX
#include "UITools.hxx"
#endif
using namespace ::com::sun::star::sdbc;
using namespace ::com::sun::star::sdbcx;
using namespace ::com::sun::star::uno;
using namespace ::com::sun::star::container;
using namespace ::com::sun::star::beans;
using namespace dbaui;
TYPEINIT1(OQueryTableWindow, OTableWindow);
//========================================================================
// class OQueryTableWindow
//========================================================================
DBG_NAME(OQueryTableWindow);
//------------------------------------------------------------------------------
OQueryTableWindow::OQueryTableWindow( Window* pParent, OQueryTableWindowData* pTabWinData, sal_Unicode* pszInitialAlias)
:OTableWindow( pParent, pTabWinData )
,m_nAliasNum(0)
{
DBG_CTOR(OQueryTableWindow,NULL);
if (pszInitialAlias != NULL)
m_strInitialAlias = ::rtl::OUString(pszInitialAlias);
else
m_strInitialAlias = pTabWinData->GetAliasName();
// wenn der Tabellen- gleich dem Aliasnamen ist, dann darf ich das nicht an InitialAlias weiterreichen, denn das Anhaengen
// eines eventuelle Tokens nicht klappen ...
if (m_strInitialAlias == pTabWinData->GetTableName())
m_strInitialAlias = ::rtl::OUString();
SetHelpId(HID_CTL_QRYDGNTAB);
}
//------------------------------------------------------------------------------
OQueryTableWindow::~OQueryTableWindow()
{
DBG_DTOR(OQueryTableWindow,NULL);
}
//------------------------------------------------------------------------------
sal_Bool OQueryTableWindow::Init()
{
sal_Bool bSuccess = OTableWindow::Init();
if(!bSuccess)
return bSuccess;
OQueryTableView* pContainer = static_cast<OQueryTableView*>(getTableView());
// zuerst Alias bestimmen
::rtl::OUString strAliasName;
OTableWindowData* pWinData = GetData();
DBG_ASSERT(pWinData->ISA(OQueryTableWindowData), "OQueryTableWindow::Init() : habe keine OQueryTableWindowData");
if (m_strInitialAlias.getLength() )
// Der Alias wurde explizit mit angegeben
strAliasName = m_strInitialAlias;
else
{
::rtl::OUString aInitialTitle = pWinData->GetTableName();
sal_Bool bOwner = sal_False;
if(GetTable().is())
{
::rtl::OUString sName;
GetTable()->getPropertyValue(PROPERTY_NAME) >>= sName;
strAliasName = sName.getStr();
}
}
// Alias mit fortlaufender Nummer versehen
if (pContainer->CountTableAlias(strAliasName, m_nAliasNum))
{
strAliasName += ::rtl::OUString('_');
strAliasName += ::rtl::OUString::valueOf(m_nAliasNum);
}
strAliasName = String(strAliasName).EraseAllChars('"');
SetAliasName(strAliasName);
// SetAliasName reicht das als WinName weiter, dadurch benutzt es die Basisklasse
// reset the titel
m_aTitle.SetText( pWinData->GetWinName() );
m_aTitle.Show();
// sal_Bool bSuccess(sal_True);
if (!bSuccess)
{ // es soll nur ein Dummy-Window aufgemacht werden ...
DBG_ASSERT(GetAliasName().getLength(), "OQueryTableWindow::Init : kein Alias- UND kein Tabellenname geht nicht !");
// .. aber das braucht wenigstens einen Alias
// ::com::sun::star::form::ListBox anlegen
if (!m_pListBox)
m_pListBox = CreateListBox();
// Titel setzen
m_aTitle.SetText(GetAliasName());
m_aTitle.Show();
clearListBox();
// neu zu fuellen brauche ich die nicht, da ich ja keine Tabelle habe
m_pListBox->Show();
}
getTableView()->getDesignView()->getController()->InvalidateFeature(ID_BROWSER_QUERY_EXECUTE);
return bSuccess;
}
// -----------------------------------------------------------------------------
void* OQueryTableWindow::createUserData(const Reference< XPropertySet>& _xColumn,bool _bPrimaryKey)
{
OTableFieldInfo* pInfo = new OTableFieldInfo();
pInfo->SetKey(_bPrimaryKey ? TAB_PRIMARY_FIELD : TAB_NORMAL_FIELD);
if ( _xColumn.is() )
pInfo->SetDataType(::comphelper::getINT32(_xColumn->getPropertyValue(PROPERTY_TYPE)));
return pInfo;
}
// -----------------------------------------------------------------------------
void OQueryTableWindow::deleteUserData(void*& _pUserData)
{
delete static_cast<OTableFieldInfo*>(_pUserData);
_pUserData = NULL;
}
//------------------------------------------------------------------------------
void OQueryTableWindow::OnEntryDoubleClicked(SvLBoxEntry* pEntry)
{
DBG_ASSERT(pEntry != NULL, "OQueryTableWindow::OnEntryDoubleClicked : pEntry darf nicht NULL sein !");
// man koennte das auch abfragen und dann ein return hinsetzen, aber so weist es vielleicht auf Fehler bei Aufrufer hin
if (getTableView()->getDesignView()->getController()->isReadOnly())
return;
OTableFieldInfo* pInf = static_cast<OTableFieldInfo*>(pEntry->GetUserData());
DBG_ASSERT(pInf != NULL, "OQueryTableWindow::OnEntryDoubleClicked : Feld hat keine FieldInfo !");
// eine DragInfo aufbauen
OTableFieldDescRef aInfo = new OTableFieldDesc(GetTableName(),m_pListBox->GetEntryText(pEntry));
aInfo->SetTabWindow(this);
aInfo->SetAlias(GetAliasName());
aInfo->SetDatabase(GetComposedName());
aInfo->SetFieldIndex(m_pListBox->GetModel()->GetAbsPos(pEntry));
aInfo->SetDataType(pInf->GetDataType());
// und das entsprechende Feld einfuegen
static_cast<OQueryTableView*>(getTableView())->InsertField(aInfo);
}
//------------------------------------------------------------------------------
sal_Bool OQueryTableWindow::ExistsField(const ::rtl::OUString& strFieldName, OTableFieldDescRef& rInfo)
{
DBG_ASSERT(m_pListBox != NULL, "OQueryTableWindow::ExistsField : habe keine ::com::sun::star::form::ListBox !");
OSL_ENSURE(rInfo.isValid(),"OQueryTableWindow::ExistsField: invlid argument for OTableFieldDescRef!");
Reference< XConnection> xConnection = getTableView()->getDesignView()->getController()->getConnection();
sal_Bool bExists = sal_False;
if(xConnection.is())
{
SvLBoxEntry* pEntry = m_pListBox->First();
try
{
Reference<XDatabaseMetaData> xMeta = xConnection->getMetaData();
::comphelper::UStringMixEqual bCase(xMeta.is() && xMeta->storesMixedCaseQuotedIdentifiers());
while (pEntry)
{
if (bCase(strFieldName,::rtl::OUString(m_pListBox->GetEntryText(pEntry))))
{
OTableFieldInfo* pInf = static_cast<OTableFieldInfo*>(pEntry->GetUserData());
DBG_ASSERT(pInf != NULL, "OQueryTableWindow::ExistsField : Feld hat keine FieldInfo !");
rInfo->SetTabWindow(this);
rInfo->SetField(strFieldName);
rInfo->SetTable(GetTableName());
rInfo->SetAlias(GetAliasName());
rInfo->SetDatabase(GetComposedName());
rInfo->SetFieldIndex(m_pListBox->GetModel()->GetAbsPos(pEntry));
rInfo->SetDataType(pInf->GetDataType());
bExists = sal_True;
break;
}
pEntry = m_pListBox->Next(pEntry);
}
}
catch(SQLException&)
{
}
}
return bExists;
}
//------------------------------------------------------------------------------
sal_Bool OQueryTableWindow::ExistsAVisitedConn() const
{
return static_cast<const OQueryTableView*>(getTableView())->ExistsAVisitedConn(this);
}
//------------------------------------------------------------------------------
void OQueryTableWindow::KeyInput( const KeyEvent& rEvt )
{
OTableWindow::KeyInput( rEvt );
}
// -----------------------------------------------------------------------------
<commit_msg>INTEGRATION: CWS ooo19126 (1.14.292); FILE MERGED 2005/09/05 17:35:29 rt 1.14.292.1: #i54170# Change license header: remove SISSL<commit_after>/*************************************************************************
*
* OpenOffice.org - a multi-platform office productivity suite
*
* $RCSfile: QTableWindow.cxx,v $
*
* $Revision: 1.15 $
*
* last change: $Author: rt $ $Date: 2005-09-08 16:22:09 $
*
* 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 DBAUI_QUERY_TABLEWINDOWDATA_HXX
#include "QTableWindow.hxx"
#endif
#ifndef DBAUI_QUERYTABLEVIEW_HXX
#include "QueryTableView.hxx"
#endif
#ifndef DBACCESS_SHARED_DBUSTRINGS_HRC
#include "dbustrings.hrc"
#endif
#ifndef _TOOLS_DEBUG_HXX
#include <tools/debug.hxx>
#endif
#include "dbaccess_helpid.hrc"
#ifndef DBAUI_QUERYDESIGNVIEW_HXX
#include "QueryDesignView.hxx"
#endif
#ifndef DBACCESS_UI_BROWSER_ID_HXX
#include "browserids.hxx"
#endif
#ifndef DBAUI_QUERYCONTROLLER_HXX
#include "querycontroller.hxx"
#endif
#ifndef _SV_IMAGE_HXX
#include <vcl/image.hxx>
#endif
#ifndef DBAUI_TABLEWINDOWLISTBOX_HXX
#include "TableWindowListBox.hxx"
#endif
#ifndef _DBU_QRY_HRC_
#include "dbu_qry.hrc"
#endif
#ifndef _DBAUI_MODULE_DBU_HXX_
#include "moduledbu.hxx"
#endif
#ifndef DBAUI_QUERY_HRC
#include "Query.hrc"
#endif
#ifndef _COM_SUN_STAR_SDBCX_XKEYSSUPPLIER_HPP_
#include <com/sun/star/sdbcx/XKeysSupplier.hpp>
#endif
#ifndef _COM_SUN_STAR_CONTAINER_XNAMEACCESS_HPP_
#include <com/sun/star/container/XNameAccess.hpp>
#endif
#ifndef _COM_SUN_STAR_CONTAINER_XINDEXACCESS_HPP_
#include <com/sun/star/container/XIndexAccess.hpp>
#endif
#ifndef _COM_SUN_STAR_BEANS_XPROPERTYSET_HPP_
#include <com/sun/star/beans/XPropertySet.hpp>
#endif
#ifndef _COM_SUN_STAR_SDBCX_KEYTYPE_HPP_
#include <com/sun/star/sdbcx/KeyType.hpp>
#endif
#ifndef _COM_SUN_STAR_SDBCX_XCOLUMNSSUPPLIER_HPP_
#include <com/sun/star/sdbcx/XColumnsSupplier.hpp>
#endif
#ifndef DBAUI_TABLEFIELDINFO_HXX
#include "TableFieldInfo.hxx"
#endif
#ifndef _COMPHELPER_UNO3_HXX_
#include <comphelper/uno3.hxx>
#endif
#ifndef _COMPHELPER_EXTRACT_HXX_
#include <comphelper/extract.hxx>
#endif
#ifndef DBAUI_TOOLS_HXX
#include "UITools.hxx"
#endif
using namespace ::com::sun::star::sdbc;
using namespace ::com::sun::star::sdbcx;
using namespace ::com::sun::star::uno;
using namespace ::com::sun::star::container;
using namespace ::com::sun::star::beans;
using namespace dbaui;
TYPEINIT1(OQueryTableWindow, OTableWindow);
//========================================================================
// class OQueryTableWindow
//========================================================================
DBG_NAME(OQueryTableWindow);
//------------------------------------------------------------------------------
OQueryTableWindow::OQueryTableWindow( Window* pParent, OQueryTableWindowData* pTabWinData, sal_Unicode* pszInitialAlias)
:OTableWindow( pParent, pTabWinData )
,m_nAliasNum(0)
{
DBG_CTOR(OQueryTableWindow,NULL);
if (pszInitialAlias != NULL)
m_strInitialAlias = ::rtl::OUString(pszInitialAlias);
else
m_strInitialAlias = pTabWinData->GetAliasName();
// wenn der Tabellen- gleich dem Aliasnamen ist, dann darf ich das nicht an InitialAlias weiterreichen, denn das Anhaengen
// eines eventuelle Tokens nicht klappen ...
if (m_strInitialAlias == pTabWinData->GetTableName())
m_strInitialAlias = ::rtl::OUString();
SetHelpId(HID_CTL_QRYDGNTAB);
}
//------------------------------------------------------------------------------
OQueryTableWindow::~OQueryTableWindow()
{
DBG_DTOR(OQueryTableWindow,NULL);
}
//------------------------------------------------------------------------------
sal_Bool OQueryTableWindow::Init()
{
sal_Bool bSuccess = OTableWindow::Init();
if(!bSuccess)
return bSuccess;
OQueryTableView* pContainer = static_cast<OQueryTableView*>(getTableView());
// zuerst Alias bestimmen
::rtl::OUString strAliasName;
OTableWindowData* pWinData = GetData();
DBG_ASSERT(pWinData->ISA(OQueryTableWindowData), "OQueryTableWindow::Init() : habe keine OQueryTableWindowData");
if (m_strInitialAlias.getLength() )
// Der Alias wurde explizit mit angegeben
strAliasName = m_strInitialAlias;
else
{
::rtl::OUString aInitialTitle = pWinData->GetTableName();
sal_Bool bOwner = sal_False;
if(GetTable().is())
{
::rtl::OUString sName;
GetTable()->getPropertyValue(PROPERTY_NAME) >>= sName;
strAliasName = sName.getStr();
}
}
// Alias mit fortlaufender Nummer versehen
if (pContainer->CountTableAlias(strAliasName, m_nAliasNum))
{
strAliasName += ::rtl::OUString('_');
strAliasName += ::rtl::OUString::valueOf(m_nAliasNum);
}
strAliasName = String(strAliasName).EraseAllChars('"');
SetAliasName(strAliasName);
// SetAliasName reicht das als WinName weiter, dadurch benutzt es die Basisklasse
// reset the titel
m_aTitle.SetText( pWinData->GetWinName() );
m_aTitle.Show();
// sal_Bool bSuccess(sal_True);
if (!bSuccess)
{ // es soll nur ein Dummy-Window aufgemacht werden ...
DBG_ASSERT(GetAliasName().getLength(), "OQueryTableWindow::Init : kein Alias- UND kein Tabellenname geht nicht !");
// .. aber das braucht wenigstens einen Alias
// ::com::sun::star::form::ListBox anlegen
if (!m_pListBox)
m_pListBox = CreateListBox();
// Titel setzen
m_aTitle.SetText(GetAliasName());
m_aTitle.Show();
clearListBox();
// neu zu fuellen brauche ich die nicht, da ich ja keine Tabelle habe
m_pListBox->Show();
}
getTableView()->getDesignView()->getController()->InvalidateFeature(ID_BROWSER_QUERY_EXECUTE);
return bSuccess;
}
// -----------------------------------------------------------------------------
void* OQueryTableWindow::createUserData(const Reference< XPropertySet>& _xColumn,bool _bPrimaryKey)
{
OTableFieldInfo* pInfo = new OTableFieldInfo();
pInfo->SetKey(_bPrimaryKey ? TAB_PRIMARY_FIELD : TAB_NORMAL_FIELD);
if ( _xColumn.is() )
pInfo->SetDataType(::comphelper::getINT32(_xColumn->getPropertyValue(PROPERTY_TYPE)));
return pInfo;
}
// -----------------------------------------------------------------------------
void OQueryTableWindow::deleteUserData(void*& _pUserData)
{
delete static_cast<OTableFieldInfo*>(_pUserData);
_pUserData = NULL;
}
//------------------------------------------------------------------------------
void OQueryTableWindow::OnEntryDoubleClicked(SvLBoxEntry* pEntry)
{
DBG_ASSERT(pEntry != NULL, "OQueryTableWindow::OnEntryDoubleClicked : pEntry darf nicht NULL sein !");
// man koennte das auch abfragen und dann ein return hinsetzen, aber so weist es vielleicht auf Fehler bei Aufrufer hin
if (getTableView()->getDesignView()->getController()->isReadOnly())
return;
OTableFieldInfo* pInf = static_cast<OTableFieldInfo*>(pEntry->GetUserData());
DBG_ASSERT(pInf != NULL, "OQueryTableWindow::OnEntryDoubleClicked : Feld hat keine FieldInfo !");
// eine DragInfo aufbauen
OTableFieldDescRef aInfo = new OTableFieldDesc(GetTableName(),m_pListBox->GetEntryText(pEntry));
aInfo->SetTabWindow(this);
aInfo->SetAlias(GetAliasName());
aInfo->SetDatabase(GetComposedName());
aInfo->SetFieldIndex(m_pListBox->GetModel()->GetAbsPos(pEntry));
aInfo->SetDataType(pInf->GetDataType());
// und das entsprechende Feld einfuegen
static_cast<OQueryTableView*>(getTableView())->InsertField(aInfo);
}
//------------------------------------------------------------------------------
sal_Bool OQueryTableWindow::ExistsField(const ::rtl::OUString& strFieldName, OTableFieldDescRef& rInfo)
{
DBG_ASSERT(m_pListBox != NULL, "OQueryTableWindow::ExistsField : habe keine ::com::sun::star::form::ListBox !");
OSL_ENSURE(rInfo.isValid(),"OQueryTableWindow::ExistsField: invlid argument for OTableFieldDescRef!");
Reference< XConnection> xConnection = getTableView()->getDesignView()->getController()->getConnection();
sal_Bool bExists = sal_False;
if(xConnection.is())
{
SvLBoxEntry* pEntry = m_pListBox->First();
try
{
Reference<XDatabaseMetaData> xMeta = xConnection->getMetaData();
::comphelper::UStringMixEqual bCase(xMeta.is() && xMeta->storesMixedCaseQuotedIdentifiers());
while (pEntry)
{
if (bCase(strFieldName,::rtl::OUString(m_pListBox->GetEntryText(pEntry))))
{
OTableFieldInfo* pInf = static_cast<OTableFieldInfo*>(pEntry->GetUserData());
DBG_ASSERT(pInf != NULL, "OQueryTableWindow::ExistsField : Feld hat keine FieldInfo !");
rInfo->SetTabWindow(this);
rInfo->SetField(strFieldName);
rInfo->SetTable(GetTableName());
rInfo->SetAlias(GetAliasName());
rInfo->SetDatabase(GetComposedName());
rInfo->SetFieldIndex(m_pListBox->GetModel()->GetAbsPos(pEntry));
rInfo->SetDataType(pInf->GetDataType());
bExists = sal_True;
break;
}
pEntry = m_pListBox->Next(pEntry);
}
}
catch(SQLException&)
{
}
}
return bExists;
}
//------------------------------------------------------------------------------
sal_Bool OQueryTableWindow::ExistsAVisitedConn() const
{
return static_cast<const OQueryTableView*>(getTableView())->ExistsAVisitedConn(this);
}
//------------------------------------------------------------------------------
void OQueryTableWindow::KeyInput( const KeyEvent& rEvt )
{
OTableWindow::KeyInput( rEvt );
}
// -----------------------------------------------------------------------------
<|endoftext|> |
<commit_before>/*****************************************************************************
* Licensed to Qualys, Inc. (QUALYS) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* QUALYS licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
****************************************************************************/
/**
* @file
* @brief IronBee++ Internals --- ParserSuite adaptors Tests
*
* @author Christopher Alfeld <calfeld@qualys.com>
**/
#include <ironbeepp/parser_suite_adaptors.hpp>
#include <ironbeepp/memory_pool.hpp>
#include "gtest/gtest.h"
using namespace IronBee;
using namespace std;
namespace {
ParserSuite::span_t span(const char* literal)
{
return ParserSuite::span_t(literal, literal + strlen(literal));
}
}
TEST(TestParserSuiteAdpators, basic)
{
typedef ParserSuite::parse_headers_result_t::header_t header_t;
using ParserSuite::span_t;
ScopedMemoryPool smp;
MemoryManager mm = MemoryPool(smp);
ParserSuite::parse_headers_result_t::headers_t headers;
headers.push_back(header_t(span("key1")));
headers.back().value.push_back(span("value1"));
headers.push_back(header_t(span("key2")));
headers.back().value.push_back(span("valu"));
headers.back().value.push_back(span("e2"));
headers.push_back(header_t(span("key3")));
headers.back().value.push_back(span("value3"));
psheader_to_parsed_header_const_range_t result =
psheaders_to_parsed_headers(mm, headers);
ASSERT_EQ(3UL, result.size());
psheader_to_parsed_header_const_range_t::iterator i = result.begin();
EXPECT_EQ("key1", i->name().to_s());
EXPECT_EQ("value1", i->value().to_s());
++i;
EXPECT_EQ("key2", i->name().to_s());
EXPECT_EQ("value2", i->value().to_s());
++i;
EXPECT_EQ("key3", i->name().to_s());
EXPECT_EQ("value3", i->value().to_s());
++i;
EXPECT_EQ(result.end(), i);
}
<commit_msg>tests: Avoid issues with different types for size() on multiple platforms.<commit_after>/*****************************************************************************
* Licensed to Qualys, Inc. (QUALYS) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* QUALYS licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
****************************************************************************/
/**
* @file
* @brief IronBee++ Internals --- ParserSuite adaptors Tests
*
* @author Christopher Alfeld <calfeld@qualys.com>
**/
#include <ironbeepp/parser_suite_adaptors.hpp>
#include <ironbeepp/memory_pool.hpp>
#include "gtest/gtest.h"
using namespace IronBee;
using namespace std;
namespace {
ParserSuite::span_t span(const char* literal)
{
return ParserSuite::span_t(literal, literal + strlen(literal));
}
}
TEST(TestParserSuiteAdpators, basic)
{
typedef ParserSuite::parse_headers_result_t::header_t header_t;
using ParserSuite::span_t;
ScopedMemoryPool smp;
MemoryManager mm = MemoryPool(smp);
ParserSuite::parse_headers_result_t::headers_t headers;
headers.push_back(header_t(span("key1")));
headers.back().value.push_back(span("value1"));
headers.push_back(header_t(span("key2")));
headers.back().value.push_back(span("valu"));
headers.back().value.push_back(span("e2"));
headers.push_back(header_t(span("key3")));
headers.back().value.push_back(span("value3"));
psheader_to_parsed_header_const_range_t result =
psheaders_to_parsed_headers(mm, headers);
ASSERT_EQ(3, (int)result.size());
psheader_to_parsed_header_const_range_t::iterator i = result.begin();
EXPECT_EQ("key1", i->name().to_s());
EXPECT_EQ("value1", i->value().to_s());
++i;
EXPECT_EQ("key2", i->name().to_s());
EXPECT_EQ("value2", i->value().to_s());
++i;
EXPECT_EQ("key3", i->name().to_s());
EXPECT_EQ("value3", i->value().to_s());
++i;
EXPECT_EQ(result.end(), i);
}
<|endoftext|> |
<commit_before>/*
* Copyright deipi.com LLC and contributors. 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.
*/
#include <assert.h>
#include <sys/socket.h>
#include "xapiand.h"
#include "utils.h"
#include "cJSON.h"
#include "client_http.h"
#include "http_parser.h"
//
// Xapian http client
//
HttpClient::HttpClient(XapiandServer *server_, ev::loop_ref *loop, int sock_, DatabasePool *database_pool_, ThreadPool *thread_pool_, double active_timeout_, double idle_timeout_)
: BaseClient(server_, loop, sock_, database_pool_, thread_pool_, active_timeout_, idle_timeout_)
{
parser.data = this;
http_parser_init(&parser, HTTP_REQUEST);
pthread_mutex_lock(&XapiandServer::static_mutex);
int total_clients = XapiandServer::total_clients;
int http_clients = ++XapiandServer::http_clients;
pthread_mutex_unlock(&XapiandServer::static_mutex);
LOG_CONN(this, "Got connection (sock=%d), %d http client(s) of a total of %d connected.\n", sock, http_clients, XapiandServer::total_clients);
LOG_OBJ(this, "CREATED HTTP CLIENT! (%d clients)\n", http_clients);
assert(http_clients <= total_clients);
}
HttpClient::~HttpClient()
{
pthread_mutex_lock(&XapiandServer::static_mutex);
int http_clients = --XapiandServer::http_clients;
pthread_mutex_unlock(&XapiandServer::static_mutex);
if (server->manager->shutdown_asap) {
if (http_clients <= 0) {
server->manager->async_shutdown.send();
}
}
LOG_OBJ(this, "DELETED HTTP CLIENT! (%d clients left)\n", http_clients);
assert(http_clients >= 0);
}
void HttpClient::on_read(const char *buf, ssize_t received)
{
size_t parsed = http_parser_execute(&parser, &settings, buf, received);
if (parsed == received) {
if (parser.state == 1 || parser.state == 18) { // dead or message_complete
io_read.stop();
thread_pool->addTask(this);
}
} else {
enum http_errno err = HTTP_PARSER_ERRNO(&parser);
const char *desc = http_errno_description(err);
const char *msg = err != HPE_OK ? desc : "incomplete request";
LOG_HTTP_PROTO(this, msg);
// Handle error. Just close the connection.
destroy();
}
}
//
// HTTP parser callbacks.
//
const http_parser_settings HttpClient::settings = {
.on_message_begin = HttpClient::on_info,
.on_url = HttpClient::on_data,
.on_status = HttpClient::on_data,
.on_header_field = HttpClient::on_data,
.on_header_value = HttpClient::on_data,
.on_headers_complete = HttpClient::on_info,
.on_body = HttpClient::on_data,
.on_message_complete = HttpClient::on_info
};
int HttpClient::on_info(http_parser* p) {
HttpClient *self = static_cast<HttpClient *>(p->data);
LOG_HTTP_PROTO_PARSER(self, "%3d. (INFO)\n", p->state);
switch (p->state) {
case 18: // message_complete
break;
case 19: // message_begin
self->path.clear();
self->body.clear();
break;
}
return 0;
}
int HttpClient::on_data(http_parser* p, const char *at, size_t length) {
HttpClient *self = static_cast<HttpClient *>(p->data);
LOG_HTTP_PROTO_PARSER(self, "%3d. %s\n", p->state, repr(at, length).c_str());
switch (p->state) {
case 32: // path
self->path = std::string(at, length);
self->body = std::string();
break;
case 44:
if (strcasecmp(std::string(at, length).c_str(),"host") == 0) {
self->ishost = true;
}
break;
case 60: // receiving data from the buffer (1024 bytes)
case 62: // finished receiving data (last data)
self->body += std::string(at, length);
break;
case 50:
if (self->ishost) {
self->host = std::string(at, length);
self->ishost = false;
}
break;
}
return 0;
}
void HttpClient::run()
{
try {
//LOG_HTTP_PROTO(this, "METHOD: %d\n", parser.method);
//LOG_HTTP_PROTO(this, "PATH: '%s'\n", repr(path).c_str());
//LOG_HTTP_PROTO(this, "HOST: '%s'\n", repr(host).c_str());
//LOG_HTTP_PROTO(this, "BODY: '%s'\n", repr(body).c_str());
if (path == "/quit") {
server->manager->async_shutdown.send();
return;
}
struct http_parser_url u;
const char *b = repr(path).c_str();
LOG_CONN_WIRE(this,"URL: %s\n",repr(path).c_str());
if(http_parser_parse_url(b, strlen(b), 0, &u) == 0){
LOG_CONN_WIRE(this,"Parsing done\n");
if (u.field_set & (1 << UF_PATH )){
char path_[u.field_data[3].len];
memcpy(path_, b + u.field_data[3].off, u.field_data[3].len);
path_[u.field_data[3].len] = '\0';
struct parser_url_path_t p;
memset(&p, 0, sizeof(p));
const char *n0 = path_;
std::string endp;
std::string nsp_;
std::string pat_;
std::string hos_;
while (url_path(&n0, &p) == 0) {
command = urldecode(p.off_command,p.len_command);
//_search();
if (p.len_namespace) {
nsp_ = urldecode(p.off_namespace, p.len_namespace) + "/";
} else {
nsp_ = "";
}
if (p.len_path) {
pat_ = urldecode(p.off_path, p.len_path);
} else {
pat_ = "";
}
if (p.len_host) {
hos_ = urldecode(p.off_host, p.len_host);
} else {
hos_ = host;
}
endp = "xapian://" + hos_ + nsp_ + pat_;
//endp = "file://" + nsp_ + pat_;
Endpoint endpoint = Endpoint(endp, std::string(), XAPIAND_BINARY_SERVERPORT);
endpoints.push_back(endpoint);
LOG_CONN_WIRE(this,"Endpoint: -> %s\n", endp.c_str());
}
}
switch (parser.method) {
//DELETE
case 0:
_delete();
break;
//GET (search)
case 1:
switch (look_cmd(command.c_str())) {
case command_search: break;
case command_count: break;
case command_facets: break;
case command_similar: break;
case identifier: break;
}
break;
//PUT
case 4:
_index();
break;
default:
break;
}
} else {
LOG_CONN_WIRE(this,"Parsing not done\n");
}
std::string content;
cJSON *json = cJSON_Parse(body.c_str());
cJSON *query = json ? cJSON_GetObjectItem(json, "query") : NULL;
cJSON *term = query ? cJSON_GetObjectItem(query, "term") : NULL;
cJSON *text = term ? cJSON_GetObjectItem(term, "text") : NULL;
cJSON *root = cJSON_CreateObject();
cJSON *response = cJSON_CreateObject();
cJSON_AddItemToObject(root, "response", response);
if (text) {
cJSON_AddStringToObject(response, "status", "OK");
cJSON_AddStringToObject(response, "query", text->valuestring);
cJSON_AddStringToObject(response, "title", "The title");
cJSON_AddNumberToObject(response, "items", 7);
const char *strings[7] = {"Sunday", "Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday"};
cJSON *results = cJSON_CreateArray();
cJSON_AddItemToObject(response, "results", results);
for (int i = 0; i < 7; i++) {
cJSON *result = cJSON_CreateObject();
cJSON_AddNumberToObject(result, "id", i);
cJSON_AddStringToObject(result, "name", strings[i]);
cJSON_AddItemToArray(results, result);
}
} else {
cJSON_AddStringToObject(response, "status", "ERROR");
const char *message = cJSON_GetErrorPtr();
if (message) {
LOG_HTTP_PROTO(this, "JSON error before: [%s]\n", message);
cJSON_AddStringToObject(response, "message", message);
}
}
cJSON_Delete(json);
bool pretty = false;
char *out;
if (pretty) {
out = cJSON_Print(root);
} else {
out = cJSON_PrintUnformatted(root);
}
content = out;
cJSON_Delete(root);
free(out);
char tmp[20];
content += "\r\n";
std::string http_response;
http_response += "HTTP/";
sprintf(tmp, "%d.%d", parser.http_major, parser.http_minor);
http_response += tmp;
http_response += " 200 OK\r\n";
http_response += "Content-Type: application/json; charset=UTF-8\r\n";
http_response += "Content-Length: ";
sprintf(tmp, "%ld", (unsigned long)content.size());
http_response += tmp;
http_response += "\r\n";
write(http_response + "\r\n" + content);
if (parser.state == 1) {
close();
}
} catch (...) {
LOG_ERR(this, "ERROR!\n");
}
io_read.start();
}
void HttpClient::_delete()
{
Database *database = NULL;
LOG(this, "Delete Document: %s\n", command.c_str());
LOG(this, "Doing the checkout\n");
database_pool->checkout(&database, endpoints, true);
database->drop(command.c_str(), true);
LOG(this, "Doing the checkin.\n");
database_pool->checkin(&database);
LOG(this, "FINISH DELETE\n");
}
void HttpClient::_index()
{
Database *database = NULL;
LOG(this, "Doing the checkout for index\n");
database_pool->checkout(&database, endpoints, true);
Xapian::WritableDatabase *wdb = static_cast<Xapian::WritableDatabase *>(database->db);
LOG(this, "Documents in the database: %d\n", wdb->get_doccount());
LOG(this, "Index %s\n", body.c_str());
database->index(body, command, true);
LOG(this, "Documents in the database: %d\n", wdb->get_doccount());
LOG(this, "Doing the checkin for index.\n");
database_pool->checkin(&database);
LOG(this, "Documents in the database: %d\n", wdb->get_doccount());
LOG(this, "FINISH INDEX\n");
}
void HttpClient::_search()
{
Database *database = NULL;
LOG(this, "Doing the checkout for search\n");
database_pool->checkout(&database, endpoints, false);
Database::query_t query;
std::string search_q("title:Hola como estas description:\"mexican movie\" kind:\"action\" range:12..20");
query.search = search_q;
std::string sort_by("year");
query.sort_by = sort_by;
std::string sort_type("ASC");
query.sort_type = sort_type;
std::string facets("precio");
query.facets = facets;
//query, get_matches, get_data, get_terms, get_size, dead, counting=False
//database->search(query, true, true, true, true, false, false);
LOG(this, "Second search.\n");
search_q = "title:\"mexican life\" description:\"mexican movie\" kind:thriller range:1.2..2.87";
query.search = search_q;
//database->search(query, true, true, true, true, false, false);
LOG(this, "Doing the checkin for search.\n");
database_pool->checkin(&database);
LOG(this, "FINISH SEARCH\n");
}<commit_msg>Endpoint generator method was added<commit_after>/*
* Copyright deipi.com LLC and contributors. 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.
*/
#include <assert.h>
#include <sys/socket.h>
#include "xapiand.h"
#include "utils.h"
#include "cJSON.h"
#include "client_http.h"
#include "http_parser.h"
//
// Xapian http client
//
HttpClient::HttpClient(XapiandServer *server_, ev::loop_ref *loop, int sock_, DatabasePool *database_pool_, ThreadPool *thread_pool_, double active_timeout_, double idle_timeout_)
: BaseClient(server_, loop, sock_, database_pool_, thread_pool_, active_timeout_, idle_timeout_)
{
parser.data = this;
http_parser_init(&parser, HTTP_REQUEST);
pthread_mutex_lock(&XapiandServer::static_mutex);
int total_clients = XapiandServer::total_clients;
int http_clients = ++XapiandServer::http_clients;
pthread_mutex_unlock(&XapiandServer::static_mutex);
LOG_CONN(this, "Got connection (sock=%d), %d http client(s) of a total of %d connected.\n", sock, http_clients, XapiandServer::total_clients);
LOG_OBJ(this, "CREATED HTTP CLIENT! (%d clients)\n", http_clients);
assert(http_clients <= total_clients);
}
HttpClient::~HttpClient()
{
pthread_mutex_lock(&XapiandServer::static_mutex);
int http_clients = --XapiandServer::http_clients;
pthread_mutex_unlock(&XapiandServer::static_mutex);
if (server->manager->shutdown_asap) {
if (http_clients <= 0) {
server->manager->async_shutdown.send();
}
}
LOG_OBJ(this, "DELETED HTTP CLIENT! (%d clients left)\n", http_clients);
assert(http_clients >= 0);
}
void HttpClient::on_read(const char *buf, ssize_t received)
{
size_t parsed = http_parser_execute(&parser, &settings, buf, received);
if (parsed == received) {
if (parser.state == 1 || parser.state == 18) { // dead or message_complete
io_read.stop();
thread_pool->addTask(this);
}
} else {
enum http_errno err = HTTP_PARSER_ERRNO(&parser);
const char *desc = http_errno_description(err);
const char *msg = err != HPE_OK ? desc : "incomplete request";
LOG_HTTP_PROTO(this, msg);
// Handle error. Just close the connection.
destroy();
}
}
//
// HTTP parser callbacks.
//
const http_parser_settings HttpClient::settings = {
.on_message_begin = HttpClient::on_info,
.on_url = HttpClient::on_data,
.on_status = HttpClient::on_data,
.on_header_field = HttpClient::on_data,
.on_header_value = HttpClient::on_data,
.on_headers_complete = HttpClient::on_info,
.on_body = HttpClient::on_data,
.on_message_complete = HttpClient::on_info
};
int HttpClient::on_info(http_parser* p) {
HttpClient *self = static_cast<HttpClient *>(p->data);
LOG_HTTP_PROTO_PARSER(self, "%3d. (INFO)\n", p->state);
switch (p->state) {
case 18: // message_complete
break;
case 19: // message_begin
self->path.clear();
self->body.clear();
break;
}
return 0;
}
int HttpClient::on_data(http_parser* p, const char *at, size_t length) {
HttpClient *self = static_cast<HttpClient *>(p->data);
LOG_HTTP_PROTO_PARSER(self, "%3d. %s\n", p->state, repr(at, length).c_str());
switch (p->state) {
case 32: // path
self->path = std::string(at, length);
self->body = std::string();
break;
case 44:
if (strcasecmp(std::string(at, length).c_str(),"host") == 0) {
self->ishost = true;
}
break;
case 60: // receiving data from the buffer (1024 bytes)
case 62: // finished receiving data (last data)
self->body += std::string(at, length);
break;
case 50:
if (self->ishost) {
self->host = std::string(at, length);
self->ishost = false;
}
break;
}
return 0;
}
void HttpClient::run()
{
try {
//LOG_HTTP_PROTO(this, "METHOD: %d\n", parser.method);
//LOG_HTTP_PROTO(this, "PATH: '%s'\n", repr(path).c_str());
//LOG_HTTP_PROTO(this, "HOST: '%s'\n", repr(host).c_str());
//LOG_HTTP_PROTO(this, "BODY: '%s'\n", repr(body).c_str());
if (path == "/quit") {
server->manager->async_shutdown.send();
return;
}
switch (parser.method) {
//DELETE
case 0:
_delete();
break;
//GET (search)
case 1:
_search();
break;
//PUT
case 4:
_index();
break;
default:
break;
}
//*-------------
std::string content;
cJSON *json = cJSON_Parse(body.c_str());
cJSON *query = json ? cJSON_GetObjectItem(json, "query") : NULL;
cJSON *term = query ? cJSON_GetObjectItem(query, "term") : NULL;
cJSON *text = term ? cJSON_GetObjectItem(term, "text") : NULL;
cJSON *root = cJSON_CreateObject();
cJSON *response = cJSON_CreateObject();
cJSON_AddItemToObject(root, "response", response);
if (text) {
cJSON_AddStringToObject(response, "status", "OK");
cJSON_AddStringToObject(response, "query", text->valuestring);
cJSON_AddStringToObject(response, "title", "The title");
cJSON_AddNumberToObject(response, "items", 7);
const char *strings[7] = {"Sunday", "Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday"};
cJSON *results = cJSON_CreateArray();
cJSON_AddItemToObject(response, "results", results);
for (int i = 0; i < 7; i++) {
cJSON *result = cJSON_CreateObject();
cJSON_AddNumberToObject(result, "id", i);
cJSON_AddStringToObject(result, "name", strings[i]);
cJSON_AddItemToArray(results, result);
}
} else {
cJSON_AddStringToObject(response, "status", "ERROR");
const char *message = cJSON_GetErrorPtr();
if (message) {
LOG_HTTP_PROTO(this, "JSON error before: [%s]\n", message);
cJSON_AddStringToObject(response, "message", message);
}
}
cJSON_Delete(json);
bool pretty = false;
char *out;
if (pretty) {
out = cJSON_Print(root);
} else {
out = cJSON_PrintUnformatted(root);
}
content = out;
cJSON_Delete(root);
free(out);
char tmp[20];
content += "\r\n";
std::string http_response;
http_response += "HTTP/";
sprintf(tmp, "%d.%d", parser.http_major, parser.http_minor);
http_response += tmp;
http_response += " 200 OK\r\n";
http_response += "Content-Type: application/json; charset=UTF-8\r\n";
http_response += "Content-Length: ";
sprintf(tmp, "%ld", (unsigned long)content.size());
http_response += tmp;
http_response += "\r\n";
write(http_response + "\r\n" + content);
if (parser.state == 1) {
close();
}//------------*/
} catch (...) {
LOG_ERR(this, "ERROR!\n");
}
io_read.start();
}
void HttpClient::_delete()
{
struct query_t e;
_endpointgen(e);
Database *database = NULL;
LOG(this, "Delete Document: %s\n", command.c_str());
LOG(this, "Doing the checkout\n");
database_pool->checkout(&database, endpoints, true);
database->drop(command.c_str(), true);
LOG(this, "Doing the checkin.\n");
database_pool->checkin(&database);
LOG(this, "FINISH DELETE\n");
}
void HttpClient::_index()
{
Database *database = NULL;
LOG(this, "Doing the checkout for index\n");
database_pool->checkout(&database, endpoints, true);
Xapian::WritableDatabase *wdb = static_cast<Xapian::WritableDatabase *>(database->db);
LOG(this, "Documents in the database: %d\n", wdb->get_doccount());
LOG(this, "Index %s\n", body.c_str());
database->index(body, command, true);
LOG(this, "Documents in the database: %d\n", wdb->get_doccount());
LOG(this, "Doing the checkin for index.\n");
database_pool->checkin(&database);
LOG(this, "Documents in the database: %d\n", wdb->get_doccount());
LOG(this, "FINISH INDEX\n");
}
void HttpClient::_search()
{
struct query_t e;
_endpointgen(e);
/*Database *database = NULL;
LOG(this, "Doing the checkout for search\n");
database_pool->checkout(&database, endpoints, false);
std::string content = database->search1(e);
LOG(this, "Doing the checkin for search.\n");
database_pool->checkin(&database);
LOG(this, "FINISH SEARCH\n");
char tmp[20];
content += "\r\n";
std::string http_response;
http_response += "HTTP/";
sprintf(tmp, "%d.%d", 1, 1);
http_response += tmp;
http_response += " 200 OK\r\n";
http_response += "Content-Type: application/json; charset=UTF-8\r\n";
http_response += "Content-Length: ";
sprintf(tmp, "%ld", (unsigned long)content.size());
http_response += tmp;
http_response += "\r\n";
write(http_response + "\r\n" + content);*/
/*Database::query_t query;
std::string search_q("title:Hola como estas description:\"mexican movie\" kind:\"action\" range:12..20");
query.search = search_q;
std::string sort_by("year");
query.sort_by = sort_by;
std::string sort_type("ASC");
query.sort_type = sort_type;
std::string facets("precio");
query.facets = facets;*/
//Database::query_t query;
//database->search(query, true, true, true, true, false, false);
/*LOG(this, "Second search.\n");
search_q = "title:\"mexican life\" description:\"mexican movie\" kind:thriller range:1.2..2.87";
query.search = search_q;
database->search(query, true, true, true, true, false, false);
LOG(this, "Doing the checkin for search.\n");
database_pool->checkin(&database);*/
// LOG(this, "FINISH SEARCH\n");
}
void HttpClient::_endpointgen(struct query_t &e)
{
struct http_parser_url u;
std::string b = repr(path);
LOG_CONN_WIRE(this,"URL: %s\n", b.c_str());
if(http_parser_parse_url(b.c_str(), b.size(), 0, &u) == 0){
LOG_CONN_WIRE(this,"Parsing done\n");
if (u.field_set & (1 << UF_PATH )){
size_t path_size = u.field_data[3].len;
std::string path_buf(b.c_str() + u.field_data[3].off, u.field_data[3].len);
struct parser_url_path_t p;
memset(&p, 0, sizeof(p));
std::string endp;
std::string nsp_;
std::string pat_;
std::string hos_;
while (url_path(path_buf.c_str(), path_size, &p) == 0) {
command = urldecode(p.off_command, p.len_command);
if (p.len_namespace) {
nsp_ = urldecode(p.off_namespace, p.len_namespace) + "/";
} else {
nsp_ = "";
}
if (p.len_path) {
pat_ = urldecode(p.off_path, p.len_path);
} else {
pat_ = "";
}
if (p.len_host) {
hos_ = urldecode(p.off_host, p.len_host);
} else {
hos_ = host;
}
endp = "xapian://" + hos_ + nsp_ + pat_;
//endp = "file://" + nsp_ + pat_;
Endpoint endpoint = Endpoint(endp, std::string(), XAPIAND_BINARY_SERVERPORT);
endpoints.push_back(endpoint);
LOG_CONN_WIRE(this,"Endpoint: -> %s\n", endp.c_str());
}
}
/*LOG(this,"FIRST QUERY PARSER SIZE %d\n",u.field_data[4].len);
LOG(this,"FIRST QUERY PARSER OFFSET %d\n",u.field_data[4].off);
LOG(this,"BUFFER %s\n",b.c_str());*/
if (u.field_set & (1 << UF_QUERY )) {
size_t query_size = u.field_data[4].len;
std::string query_buf(b.c_str() + u.field_data[4].off, u.field_data[4].len);
struct parser_query_t q;
memset(&q, 0, sizeof(q));
//LOG(this, "FIRST QUERY PARSER %s\n", query_buf.c_str());
if (url_qs("query", query_buf.c_str(), query_size, &q) != -1) {
e.query = urldecode(q.offset, q.length).c_str();
//LOG(this, "Query---->> %s\n",e.query.c_str());
} else {
e.query = "";
LOG(this, "query parser not done!!\n");
}
if (url_qs("offset", query_buf.c_str(), query_size, &q)!= -1) {
e.offset = atoi(urldecode(q.offset, q.length).c_str());
} else {
e.offset = 0;
LOG(this, "offset parser not done!!\n");
}
if (url_qs("limit", query_buf.c_str(), query_size, &q) != -1) {
e.limit = atoi(urldecode(q.offset, q.length).c_str());
} else {
e.limit = 1;
LOG(this, "limit parser not done!!\n");
}
if (url_qs("order", query_buf.c_str(), query_size, &q) != -1) {
e.order = urldecode(q.offset, q.length).c_str();
} else {
e.order = "";
}
while(url_qs("terms", query_buf.c_str(), query_size, &q) != -1) {
e.terms.push_back(urldecode(q.offset, q.length));
}
}
} else {
LOG_CONN_WIRE(this,"Parsing not done\n");
}
}<|endoftext|> |
<commit_before><?hh //strict
/**
* This file is part of hhpack/migrate.
*
* (c) Noritaka Horio <holy.shared.design@gmail.com>
*
* This source file is subject to the MIT license that is bundled
* with this source code in the file LICENSE.
*/
namespace HHPack\Migrate\Application;
use HHPack\Getopt as cli;
use HHPack\Getopt\Parser\{ OptionParser };
use HHPack\Migrate\{ File, Output, Logger };
use HHPack\Migrate\Application\Command\{
CreateDatabaseCommand, DropDatabaseCommand, UpCommand, DownCommand,
ResetCommand, GenerateMigrationCommand
};
use HHPack\Migrate\Logger\{ PlainLogger, ColoredLogger };
final class MigrateApplication
{
const PROGRAM_NAME = 'migrate';
const PROGRAM_VERSION = '2.0.1';
const PROGRAM_LICENCE = 'The MIT Licence';
private bool $help = false;
private bool $version = false;
private bool $outputColor = true;
private string $configurationPath = 'config/database.json';
private OptionParser $optionParser;
private ImmMap<string, Command> $commands;
public function __construct(
private Output $output
)
{
$parserOptions = shape('stopAtNonOption' => true);
$this->optionParser = cli\optparser([
cli\take_on(['-c', '--config'], 'FILE', 'Path of configuration file', ($path) ==> {
$this->configurationPath = $path;
}),
cli\on(['--no-color'], 'If specified, color output will not be performed', () ==> {
$this->outputColor = false;
}),
cli\on(['-h', '--help'], 'Display help message', () ==> {
$this->help = true;
}),
cli\on(['-v', '--version'], 'Display version', () ==> {
$this->version = true;
})
], $parserOptions);
$this->commands = ImmMap {
"create" => new CreateDatabaseCommand(),
"drop" => new DropDatabaseCommand(),
"up" => new UpCommand(),
"down" => new DownCommand(),
"reset" => new ResetCommand(),
"gen" => new GenerateMigrationCommand()
};
}
public function run(Traversable<string> $argv): void
{
$cliArgv = Vector::fromItems($argv)->skip(1);
$remainArgv = $this->optionParser->parse($cliArgv);
if ($this->help) {
$this->displayHelp();
} else if ($this->version) {
$this->displayVersion();
} else if (!$remainArgv->containsKey(0)) {
$this->displayHelp();
} else {
$commandName = $remainArgv->at(0);
$this->runCommand($commandName, $remainArgv->skip(1));
}
}
private function runCommand(string $name, ImmVector<string> $argv): void
{
if (!$this->commands->contains($name)) {
$this->displayHelp();
} else {
$loader = new ConfigurationLoader(File\absolutePath(getcwd() . '/' . $this->configurationPath));
$env = getenv('HHVM_ENV') ? getenv('HHVM_ENV') : 'development';
$configuration = $loader->load($env);
$context = new MigrateContext($argv, $configuration, $this->outputLogger());
$command = $this->commands->at($name);
$command->run($context);
}
}
private function outputLogger(): Logger {
if ($this->outputColor) {
return new ColoredLogger($this->output);
} else {
return new PlainLogger($this->output);
}
}
private function displayHelp(): void
{
$this->output->write("Migration tool for database.\n");
$this->output->write("https://github.com/hhpack/migrate");
$this->output->write(sprintf("\n\n %s %s %s\n\n",
static::PROGRAM_NAME,
"[OPTIONS]", "[COMMAND]"));
$this->output->write("Commands:\n");
$this->displayCommands();
$this->output->write("\n");
$this->optionParser->displayHelp();
}
private function displayCommands(): void
{
$keys = $this->commands->keys()->toValuesArray();
$maxLength = (int) array_reduce($keys, (int $max, string $key) ==> {
return ($max < strlen($key)) ? strlen($key) : $max;
}, 0);
foreach ($this->commands->lazy() as $name => $command) {
$this->output->write(sprintf(" %s %s\n", str_pad($name, $maxLength), $command->description()));
}
}
private function displayVersion(): void
{
$this->output->write(sprintf("%s %s\n", static::PROGRAM_NAME, static::PROGRAM_VERSION));
}
}
<commit_msg>v2.0.2<commit_after><?hh //strict
/**
* This file is part of hhpack/migrate.
*
* (c) Noritaka Horio <holy.shared.design@gmail.com>
*
* This source file is subject to the MIT license that is bundled
* with this source code in the file LICENSE.
*/
namespace HHPack\Migrate\Application;
use HHPack\Getopt as cli;
use HHPack\Getopt\Parser\{ OptionParser };
use HHPack\Migrate\{ File, Output, Logger };
use HHPack\Migrate\Application\Command\{
CreateDatabaseCommand, DropDatabaseCommand, UpCommand, DownCommand,
ResetCommand, GenerateMigrationCommand
};
use HHPack\Migrate\Logger\{ PlainLogger, ColoredLogger };
final class MigrateApplication
{
const PROGRAM_NAME = 'migrate';
const PROGRAM_VERSION = '2.0.2';
const PROGRAM_LICENCE = 'The MIT Licence';
private bool $help = false;
private bool $version = false;
private bool $outputColor = true;
private string $configurationPath = 'config/database.json';
private OptionParser $optionParser;
private ImmMap<string, Command> $commands;
public function __construct(
private Output $output
)
{
$parserOptions = shape('stopAtNonOption' => true);
$this->optionParser = cli\optparser([
cli\take_on(['-c', '--config'], 'FILE', 'Path of configuration file', ($path) ==> {
$this->configurationPath = $path;
}),
cli\on(['--no-color'], 'If specified, color output will not be performed', () ==> {
$this->outputColor = false;
}),
cli\on(['-h', '--help'], 'Display help message', () ==> {
$this->help = true;
}),
cli\on(['-v', '--version'], 'Display version', () ==> {
$this->version = true;
})
], $parserOptions);
$this->commands = ImmMap {
"create" => new CreateDatabaseCommand(),
"drop" => new DropDatabaseCommand(),
"up" => new UpCommand(),
"down" => new DownCommand(),
"reset" => new ResetCommand(),
"gen" => new GenerateMigrationCommand()
};
}
public function run(Traversable<string> $argv): void
{
$cliArgv = Vector::fromItems($argv)->skip(1);
$remainArgv = $this->optionParser->parse($cliArgv);
if ($this->help) {
$this->displayHelp();
} else if ($this->version) {
$this->displayVersion();
} else if (!$remainArgv->containsKey(0)) {
$this->displayHelp();
} else {
$commandName = $remainArgv->at(0);
$this->runCommand($commandName, $remainArgv->skip(1));
}
}
private function runCommand(string $name, ImmVector<string> $argv): void
{
if (!$this->commands->contains($name)) {
$this->displayHelp();
} else {
$loader = new ConfigurationLoader(File\absolutePath(getcwd() . '/' . $this->configurationPath));
$env = getenv('HHVM_ENV') ? getenv('HHVM_ENV') : 'development';
$configuration = $loader->load($env);
$context = new MigrateContext($argv, $configuration, $this->outputLogger());
$command = $this->commands->at($name);
$command->run($context);
}
}
private function outputLogger(): Logger {
if ($this->outputColor) {
return new ColoredLogger($this->output);
} else {
return new PlainLogger($this->output);
}
}
private function displayHelp(): void
{
$this->output->write("Migration tool for database.\n");
$this->output->write("https://github.com/hhpack/migrate");
$this->output->write(sprintf("\n\n %s %s %s\n\n",
static::PROGRAM_NAME,
"[OPTIONS]", "[COMMAND]"));
$this->output->write("Commands:\n");
$this->displayCommands();
$this->output->write("\n");
$this->optionParser->displayHelp();
}
private function displayCommands(): void
{
$keys = $this->commands->keys()->toValuesArray();
$maxLength = (int) array_reduce($keys, (int $max, string $key) ==> {
return ($max < strlen($key)) ? strlen($key) : $max;
}, 0);
foreach ($this->commands->lazy() as $name => $command) {
$this->output->write(sprintf(" %s %s\n", str_pad($name, $maxLength), $command->description()));
}
}
private function displayVersion(): void
{
$this->output->write(sprintf("%s %s\n", static::PROGRAM_NAME, static::PROGRAM_VERSION));
}
}
<|endoftext|> |
<commit_before>#include <iostream>
#include "mminfo.h"
#include "hshgtest.h"
namespace
{
void DiffAddMid()
{
// Add new block in the middle
MemMon::MemoryMap m1, m2;
m1.Clear( 10 );
m2.Clear( 10 );
MemMon::Region r;
r.base = 0;
r.type = MemMon::Region::free;
r.size = 30;
m1.AddBlock( r );
r.size = 10;
m2.AddBlock( r );
r.base = 10;
r.type = MemMon::Region::committed;
m2.AddBlock( r );
r.base = 20;
r.type = MemMon::Region::free;
m2.AddBlock( r );
MemMon::MemoryDiff d( m1, m2 );
const MemMon::MemoryDiff::Changes& c = d.GetChanges();
HSHG_ASSERT( c.size() == 1 );
MemMon::MemoryDiff::Changes::const_iterator cit = c.begin();
HSHG_ASSERT( cit->first == MemMon::MemoryDiff::addition );
const MemMon::Region* rr = &cit->second.second;
HSHG_ASSERT( rr->base == 10 );
HSHG_ASSERT( rr->size == 10 );
HSHG_ASSERT( rr->type == MemMon::Region::committed );
MemMon::MemoryDiff drev( m2, m1 );
const MemMon::MemoryDiff::Changes& crev = drev.GetChanges();
HSHG_ASSERT( crev.size() == 1 );
cit = crev.begin();
HSHG_ASSERT( cit->first == MemMon::MemoryDiff::removal );
rr = &cit->second.first;
HSHG_ASSERT( rr->base == 10 );
HSHG_ASSERT( rr->size == 10 );
HSHG_ASSERT( rr->type == MemMon::Region::committed );
}
void DiffAddStart()
{
// Add new block in the middle
MemMon::MemoryMap m1, m2;
m1.Clear( 10 );
m2.Clear( 10 );
MemMon::Region r;
r.base = 0;
r.type = MemMon::Region::free;
r.size = 30;
m1.AddBlock( r );
r.size = 10;
r.type = MemMon::Region::committed;
m2.AddBlock( r );
r.size = 20;
r.base = 10;
r.type = MemMon::Region::free;
m2.AddBlock( r );
MemMon::MemoryDiff d( m1, m2 );
const MemMon::MemoryDiff::Changes& c = d.GetChanges();
HSHG_ASSERT( c.size() == 1 );
MemMon::MemoryDiff::Changes::const_iterator cit = c.begin();
HSHG_ASSERT( cit->first == MemMon::MemoryDiff::addition );
const MemMon::Region* rr = &cit->second.second;
HSHG_ASSERT( rr->base == 0 );
HSHG_ASSERT( rr->size == 10 );
HSHG_ASSERT( rr->type == MemMon::Region::committed );
MemMon::MemoryDiff drev( m2, m1 );
const MemMon::MemoryDiff::Changes& crev = drev.GetChanges();
HSHG_ASSERT( crev.size() == 1 );
cit = crev.begin();
HSHG_ASSERT( cit->first == MemMon::MemoryDiff::removal );
rr = &cit->second.first;
HSHG_ASSERT( rr->base == 0 );
HSHG_ASSERT( rr->size == 10 );
HSHG_ASSERT( rr->type == MemMon::Region::committed );
}
void DiffAddEnd()
{
// Add new block in the middle
MemMon::MemoryMap m1, m2;
m1.Clear( 10 );
m2.Clear( 10 );
MemMon::Region r;
r.base = 0;
r.type = MemMon::Region::free;
r.size = 30;
m1.AddBlock( r );
r.size = 20;
m2.AddBlock( r );
r.size = 10;
r.base = 20;
r.type = MemMon::Region::committed;
m2.AddBlock( r );
MemMon::MemoryDiff d( m1, m2 );
const MemMon::MemoryDiff::Changes& c = d.GetChanges();
HSHG_ASSERT( c.size() == 1 );
MemMon::MemoryDiff::Changes::const_iterator cit = c.begin();
HSHG_ASSERT( cit->first == MemMon::MemoryDiff::addition );
const MemMon::Region* rr = &cit->second.second;
HSHG_ASSERT( rr->base == 20 );
HSHG_ASSERT( rr->size == 10 );
HSHG_ASSERT( rr->type == MemMon::Region::committed );
MemMon::MemoryDiff drev( m2, m1 );
const MemMon::MemoryDiff::Changes& crev = drev.GetChanges();
HSHG_ASSERT( crev.size() == 1 );
cit = crev.begin();
HSHG_ASSERT( cit->first == MemMon::MemoryDiff::removal );
rr = &cit->second.first;
HSHG_ASSERT( rr->base == 20 );
HSHG_ASSERT( rr->size == 10 );
HSHG_ASSERT( rr->type == MemMon::Region::committed );
}
void PatchAddMid()
{
// Add new block in the middle
MemMon::MemoryMap m1, m2;
m1.Clear( 10 );
m2.Clear( 10 );
MemMon::Region r;
r.base = 0;
r.type = MemMon::Region::free;
r.size = 30;
m1.AddBlock( r );
r.size = 10;
m2.AddBlock( r );
r.base = 10;
r.type = MemMon::Region::committed;
m2.AddBlock( r );
r.base = 20;
r.type = MemMon::Region::free;
m2.AddBlock( r );
r.base = 10;
r.type = MemMon::Region::committed;
r.size = 10;
MemMon::MemoryDiff d;
d.AppendAddition( r );
d.Apply( m1 );
HSHG_ASSERT( m1 == m2 );
}
void PatchAddStart()
{
// Add new block in the start
MemMon::MemoryMap m1, m2;
m1.Clear( 10 );
m2.Clear( 10 );
MemMon::Region r;
r.base = 0;
r.type = MemMon::Region::free;
r.size = 30;
m1.AddBlock( r );
r.type = MemMon::Region::committed;
r.size = 10;
m2.AddBlock( r );
r.base = 10;
r.size = 20;
r.type = MemMon::Region::free;
m2.AddBlock( r );
r.base = 0;
r.type = MemMon::Region::committed;
r.size = 10;
MemMon::MemoryDiff d;
d.AppendAddition( r );
d.Apply( m1 );
HSHG_ASSERT( m1 == m2 );
}
void PatchAddEnd()
{
// Add new block in the end
MemMon::MemoryMap m1, m2;
m1.Clear( 10 );
m2.Clear( 10 );
MemMon::Region r;
r.base = 0;
r.type = MemMon::Region::free;
r.size = 30;
m1.AddBlock( r );
r.size = 20;
m2.AddBlock( r );
r.base = 20;
r.type = MemMon::Region::committed;
r.size = 10;
m2.AddBlock( r );
r.base = 20;
r.type = MemMon::Region::committed;
r.size = 10;
MemMon::MemoryDiff d;
d.AppendAddition( r );
d.Apply( m1 );
HSHG_ASSERT( m1 == m2 );
}
void PatchAddSplit()
{
MemMon::MemoryMap m1, m2;
m1.Clear( 10 );
m2.Clear( 10 );
m1.AddBlock( MemMon::Region( 0, 15, MemMon::Region::free ) );
m1.AddBlock( MemMon::Region( 15, 15, MemMon::Region::reserved ) );
m2.AddBlock( MemMon::Region( 0, 10, MemMon::Region::free ) );
m2.AddBlock( MemMon::Region( 10, 10, MemMon::Region::committed ) );
m2.AddBlock( MemMon::Region( 20, 10, MemMon::Region::reserved ) );
MemMon::MemoryDiff d;
d.AppendAddition( MemMon::Region( 10, 10, MemMon::Region::committed ) );
d.Apply( m1 );
HSHG_ASSERT( m1 == m2 );
}
}
HSHG_BEGIN_TESTS
HSHG_TEST_ENTRY( DiffAddMid )
HSHG_TEST_ENTRY( DiffAddStart )
HSHG_TEST_ENTRY( DiffAddEnd )
HSHG_TEST_ENTRY( PatchAddMid )
HSHG_TEST_ENTRY( PatchAddStart )
HSHG_TEST_ENTRY( PatchAddEnd )
HSHG_TEST_ENTRY( PatchAddSplit )
HSHG_END_TESTS
HSHG_TEST_MAIN
<commit_msg>Shortened all the test setups by using the Region constructor<commit_after>#include <iostream>
#include "mminfo.h"
#include "hshgtest.h"
namespace
{
using MemMon::Region;
void DiffAddMid()
{
// Add new block in the middle
MemMon::MemoryMap m1, m2;
m1.Clear( 10 );
m2.Clear( 10 );
m1.AddBlock( Region( 0, 30, Region::free ) );
m2.AddBlock( Region( 0, 10, Region::free ) );
m2.AddBlock( Region( 10, 10, Region::committed ) );
m2.AddBlock( Region( 20, 10, Region::free ) );
MemMon::MemoryDiff d( m1, m2 );
const MemMon::MemoryDiff::Changes& c = d.GetChanges();
HSHG_ASSERT( c.size() == 1 );
MemMon::MemoryDiff::Changes::const_iterator cit = c.begin();
HSHG_ASSERT( cit->first == MemMon::MemoryDiff::addition );
const Region* rr = &cit->second.second;
HSHG_ASSERT( rr->base == 10 );
HSHG_ASSERT( rr->size == 10 );
HSHG_ASSERT( rr->type == Region::committed );
MemMon::MemoryDiff drev( m2, m1 );
const MemMon::MemoryDiff::Changes& crev = drev.GetChanges();
HSHG_ASSERT( crev.size() == 1 );
cit = crev.begin();
HSHG_ASSERT( cit->first == MemMon::MemoryDiff::removal );
rr = &cit->second.first;
HSHG_ASSERT( rr->base == 10 );
HSHG_ASSERT( rr->size == 10 );
HSHG_ASSERT( rr->type == Region::committed );
}
void DiffAddStart()
{
// Add new block in the middle
MemMon::MemoryMap m1, m2;
m1.Clear( 10 );
m2.Clear( 10 );
m1.AddBlock( Region( 0, 30, Region::free ) );
m2.AddBlock( Region( 0, 10, Region::committed ) );
m2.AddBlock( Region( 10, 20, Region::free ) );
MemMon::MemoryDiff d( m1, m2 );
const MemMon::MemoryDiff::Changes& c = d.GetChanges();
HSHG_ASSERT( c.size() == 1 );
MemMon::MemoryDiff::Changes::const_iterator cit = c.begin();
HSHG_ASSERT( cit->first == MemMon::MemoryDiff::addition );
const Region* rr = &cit->second.second;
HSHG_ASSERT( rr->base == 0 );
HSHG_ASSERT( rr->size == 10 );
HSHG_ASSERT( rr->type == Region::committed );
MemMon::MemoryDiff drev( m2, m1 );
const MemMon::MemoryDiff::Changes& crev = drev.GetChanges();
HSHG_ASSERT( crev.size() == 1 );
cit = crev.begin();
HSHG_ASSERT( cit->first == MemMon::MemoryDiff::removal );
rr = &cit->second.first;
HSHG_ASSERT( rr->base == 0 );
HSHG_ASSERT( rr->size == 10 );
HSHG_ASSERT( rr->type == Region::committed );
}
void DiffAddEnd()
{
// Add new block in the middle
MemMon::MemoryMap m1, m2;
m1.Clear( 10 );
m2.Clear( 10 );
m1.AddBlock( Region( 0, 30, Region::free ) );
m2.AddBlock( Region( 0, 20, Region::free ) );
m2.AddBlock( Region( 20, 10, Region::committed ) );
MemMon::MemoryDiff d( m1, m2 );
const MemMon::MemoryDiff::Changes& c = d.GetChanges();
HSHG_ASSERT( c.size() == 1 );
MemMon::MemoryDiff::Changes::const_iterator cit = c.begin();
HSHG_ASSERT( cit->first == MemMon::MemoryDiff::addition );
const Region* rr = &cit->second.second;
HSHG_ASSERT( rr->base == 20 );
HSHG_ASSERT( rr->size == 10 );
HSHG_ASSERT( rr->type == Region::committed );
MemMon::MemoryDiff drev( m2, m1 );
const MemMon::MemoryDiff::Changes& crev = drev.GetChanges();
HSHG_ASSERT( crev.size() == 1 );
cit = crev.begin();
HSHG_ASSERT( cit->first == MemMon::MemoryDiff::removal );
rr = &cit->second.first;
HSHG_ASSERT( rr->base == 20 );
HSHG_ASSERT( rr->size == 10 );
HSHG_ASSERT( rr->type == Region::committed );
}
void PatchAddMid()
{
// Add new block in the middle
MemMon::MemoryMap m1, m2;
m1.Clear( 10 );
m2.Clear( 10 );
m1.AddBlock( Region( 0, 30, Region::free ) );
m2.AddBlock( Region( 0, 10, Region::free ) );
m2.AddBlock( Region( 10, 10, Region::committed ) );
m2.AddBlock( Region( 20, 10, Region::free ) );
MemMon::MemoryDiff d;
d.AppendAddition( Region( 10, 10, Region::committed ) );
d.Apply( m1 );
HSHG_ASSERT( m1 == m2 );
}
void PatchAddStart()
{
// Add new block in the start
MemMon::MemoryMap m1, m2;
m1.Clear( 10 );
m2.Clear( 10 );
m1.AddBlock( Region( 0, 30, Region::free ) );
m2.AddBlock( Region( 0, 10, Region::committed ) );
m2.AddBlock( Region( 10, 20, Region::free ) );
MemMon::MemoryDiff d;
d.AppendAddition( Region( 0, 10, Region::committed ) );
d.Apply( m1 );
HSHG_ASSERT( m1 == m2 );
}
void PatchAddEnd()
{
// Add new block in the end
MemMon::MemoryMap m1, m2;
m1.Clear( 10 );
m2.Clear( 10 );
m1.AddBlock( Region( 0, 30, Region::free ) );
m2.AddBlock( Region( 0, 20, Region::free ) );
m2.AddBlock( Region( 20, 10, Region::committed ) );
MemMon::MemoryDiff d;
d.AppendAddition( Region( 20, 10, Region::committed ) );
d.Apply( m1 );
HSHG_ASSERT( m1 == m2 );
}
void PatchAddSplit()
{
MemMon::MemoryMap m1, m2;
m1.Clear( 10 );
m2.Clear( 10 );
m1.AddBlock( Region( 0, 15, Region::free ) );
m1.AddBlock( Region( 15, 15, Region::reserved ) );
m2.AddBlock( Region( 0, 10, Region::free ) );
m2.AddBlock( Region( 10, 10, Region::committed ) );
m2.AddBlock( Region( 20, 10, Region::reserved ) );
MemMon::MemoryDiff d;
d.AppendAddition( Region( 10, 10, Region::committed ) );
d.Apply( m1 );
HSHG_ASSERT( m1 == m2 );
}
}
HSHG_BEGIN_TESTS
HSHG_TEST_ENTRY( DiffAddMid )
HSHG_TEST_ENTRY( DiffAddStart )
HSHG_TEST_ENTRY( DiffAddEnd )
HSHG_TEST_ENTRY( PatchAddMid )
HSHG_TEST_ENTRY( PatchAddStart )
HSHG_TEST_ENTRY( PatchAddEnd )
HSHG_TEST_ENTRY( PatchAddSplit )
HSHG_END_TESTS
HSHG_TEST_MAIN
<|endoftext|> |
<commit_before>#ifndef IPOOL_H
#define IPOOL_H
#include <utility>
#include <functional>
class trait_pool_concurrency {
public:
class none{};
class global{};
class granular{};
class lockfree{};
class waitfree{};
};
class trait_pool_size {
public:
class bounded{};
class unbounded{};
};
class trait_pool_method {
public:
class total{};
class partial{};
class synchronous{};
};
class trait_pool_fairness {
public:
class fifo{};
class lifo{};
};
template< class T, template< class > class ContainerType, class PoolSize, class PoolConcurrency, class PoolMethod, class PoolFairness >
class IPool final : public ContainerType<T> {
public:
//container and value traits
using container_type = ContainerType<T>;
using value_type = T;
using reference = T &;
using const_reference = T const &;
using size_type = typename ContainerType<T>::_t_size;
//pool traits
using pool_size = PoolSize;
using pool_concurrency = PoolConcurrency;
using pool_method = PoolMethod;
using pool_fairness = PoolFairness;
template< class... Args >
IPool( Args... args ) : ContainerType<T>( std::forward<Args>(args)... ) {}
~IPool(){}
bool clear(){ return ContainerType<T>::clear(); }
bool empty(){ return ContainerType<T>::empty(); }
size_type size(){ return ContainerType<T>::size(); }
bool put( value_type const & item ){ return ContainerType<T>::put( item ); }
bool get( value_type & item ){ return ContainerType<T>::get( item ); }
void get_fun( std::function<void(bool,reference)> f ){
value_type val;
bool ret = get( val );
f( ret, val );
}
};
#endif
<commit_msg>modified to use alias types.<commit_after>#ifndef IPOOL_H
#define IPOOL_H
#include <utility>
#include <functional>
class trait_pool_concurrency {
public:
class none{};
class global{};
class granular{};
class lockfree{};
class waitfree{};
};
class trait_pool_size {
public:
class bounded{};
class unbounded{};
};
class trait_pool_method {
public:
class total{};
class partial{};
class synchronous{};
};
class trait_pool_fairness {
public:
class fifo{};
class lifo{};
};
template< class T, template< class > class ContainerType, class PoolSize, class PoolConcurrency, class PoolMethod, class PoolFairness >
class IPool final : public ContainerType<T> {
public:
//container and value traits
using container_type = ContainerType<T>;
using value_type = T;
using reference = T &;
using const_reference = T const &;
using size_type = typename ContainerType<T>::_t_size;
//pool traits
using pool_size = PoolSize;
using pool_concurrency = PoolConcurrency;
using pool_method = PoolMethod;
using pool_fairness = PoolFairness;
template< class... Args >
IPool( Args... args ) : ContainerType<T>( std::forward<Args>(args)... ) {}
~IPool(){}
bool clear(){ return ContainerType<T>::clear(); }
bool empty(){ return ContainerType<T>::empty(); }
size_type size(){ return ContainerType<T>::size(); }
bool put( const_reference item ){ return ContainerType<T>::put( item ); }
bool get( reference item ){ return ContainerType<T>::get( item ); }
void get_fun( std::function<void(bool,reference)> f ){
value_type val;
bool ret = get( val );
f( ret, val );
}
};
#endif
<|endoftext|> |
<commit_before>#include "country_status_display.hpp"
#include "framework.hpp"
#include "../gui/controller.hpp"
#include "../gui/button.hpp"
#include "../gui/text_view.hpp"
#include "../graphics/overlay_renderer.hpp"
#include "../graphics/display_list.hpp"
#include "../platform/platform.hpp"
#include "../base/thread.hpp"
#include "../base/string_format.hpp"
#include "../std/bind.hpp"
#include "../std/sstream.hpp"
using namespace storage;
CountryStatusDisplay::CountryStatusDisplay(Params const & p)
: gui::Element(p)
, m_activeMaps(p.m_activeMaps)
{
m_activeMapsSlotID = m_activeMaps.AddListener(this);
gui::Button::Params bp;
bp.m_depth = depth();
bp.m_minWidth = 200;
bp.m_minHeight = 40;
bp.m_position = graphics::EPosCenter;
auto createButtonFn = [this](gui::Button::Params const & params)
{
gui::Button * result = new gui::Button(params);
result->setIsVisible(false);
result->setOnClickListener(bind(&CountryStatusDisplay::OnButtonClicked, this, _1));
result->setFont(EActive, graphics::FontDesc(16, graphics::Color(255, 255, 255, 255)));
result->setFont(EPressed, graphics::FontDesc(16, graphics::Color(255, 255, 255, 255)));
result->setColor(EActive, graphics::Color(0, 0, 0, 0.6 * 255));
result->setColor(EPressed, graphics::Color(0, 0, 0, 0.4 * 255));
return result;
};
m_primaryButton.reset(createButtonFn(bp));
m_secondaryButton.reset(createButtonFn(bp));
gui::TextView::Params tp;
tp.m_depth = depth();
tp.m_position = graphics::EPosCenter;
m_label.reset(new gui::TextView(tp));
m_label->setIsVisible(false);
m_label->setFont(gui::Element::EActive, graphics::FontDesc(18));
setIsVisible(false);
}
CountryStatusDisplay::~CountryStatusDisplay()
{
m_activeMaps.RemoveListener(m_activeMapsSlotID);
}
void CountryStatusDisplay::SetCountryIndex(TIndex const & idx)
{
if (m_countryIdx != idx)
{
m_countryIdx = idx;
if (m_countryIdx.IsValid())
{
m_countryStatus = m_activeMaps.GetCountryStatus(m_countryIdx);
m_displayMapName = m_activeMaps.GetFormatedCountryName(m_countryIdx);
}
Repaint();
}
}
void CountryStatusDisplay::DownloadCurrentCountry(int options)
{
// I don't know why this work, but it's terrible
// This method call only on android, from "AndroidUIThread"
DownloadCountry(options, false);
}
void CountryStatusDisplay::setIsVisible(bool isVisible) const
{
if (isVisible && isVisible != TBase::isVisible())
Repaint();
TBase::setIsVisible(isVisible);
}
void CountryStatusDisplay::setIsDirtyLayout(bool isDirty) const
{
TBase::setIsDirtyLayout(isDirty);
m_label->setIsDirtyLayout(isDirty);
m_primaryButton->setIsDirtyLayout(isDirty);
m_secondaryButton->setIsDirtyLayout(isDirty);
if (isDirty)
SetVisibilityForState();
}
void CountryStatusDisplay::draw(graphics::OverlayRenderer * r,
math::Matrix<double, 3, 3> const & m) const
{
if (isVisible())
{
Lock();
checkDirtyLayout();
m_label->draw(r, m);
m_primaryButton->draw(r, m);
m_secondaryButton->draw(r, m);
Unlock();
}
}
void CountryStatusDisplay::layout()
{
if (!isVisible())
return;
SetContentForState();
auto layoutFn = [] (gui::Element * e)
{
if (e->isVisible())
e->layout();
};
layoutFn(m_label.get());
layoutFn(m_primaryButton.get());
layoutFn(m_secondaryButton.get());
ComposeElementsForState();
// !!!! Hack !!!!
// ComposeElementsForState modify pivot point of elements.
// After setPivot all elements must be relayouted.
// For reduce "cache" operations we call layout secondary
layoutFn(m_label.get());
layoutFn(m_primaryButton.get());
layoutFn(m_secondaryButton.get());
}
void CountryStatusDisplay::purge()
{
m_label->purge();
m_primaryButton->purge();
m_secondaryButton->purge();
}
void CountryStatusDisplay::cache()
{
auto cacheFn = [](gui::Element * e)
{
if (e->isVisible())
e->cache();
};
cacheFn(m_label.get());
cacheFn(m_primaryButton.get());
cacheFn(m_secondaryButton.get());
}
m2::RectD CountryStatusDisplay::GetBoundRect() const
{
ASSERT(isVisible(), ());
m2::RectD r(pivot(), pivot());
if (m_primaryButton->isVisible())
r.Add(m_primaryButton->GetBoundRect());
if (m_secondaryButton->isVisible())
r.Add(m_secondaryButton->GetBoundRect());
return r;
}
void CountryStatusDisplay::setController(gui::Controller * controller)
{
Element::setController(controller);
m_label->setController(controller);
m_primaryButton->setController(controller);
m_secondaryButton->setController(controller);
}
bool CountryStatusDisplay::onTapStarted(m2::PointD const & pt)
{
return OnTapAction(bind(&gui::Button::onTapStarted, _1, _2), pt);
}
bool CountryStatusDisplay::onTapMoved(m2::PointD const & pt)
{
return OnTapAction(bind(&gui::Button::onTapMoved, _1, _2), pt);
}
bool CountryStatusDisplay::onTapEnded(m2::PointD const & pt)
{
return OnTapAction(bind(&gui::Button::onTapEnded, _1, _2), pt);
}
bool CountryStatusDisplay::onTapCancelled(m2::PointD const & pt)
{
return OnTapAction(bind(&gui::Button::onTapCancelled, _1, _2), pt);
}
void CountryStatusDisplay::CountryStatusChanged(ActiveMapsLayout::TGroup const & group, int position)
{
TIndex index = m_activeMaps.GetCoreIndex(group, position);
if (m_countryIdx == index)
{
Lock();
m_countryStatus = m_activeMaps.GetCountryStatus(index);
Repaint();
Unlock();
}
}
void CountryStatusDisplay::DownloadingProgressUpdate(ActiveMapsLayout::TGroup const & group, int position, LocalAndRemoteSizeT const & progress)
{
TIndex index = m_activeMaps.GetCoreIndex(group, position);
if (m_countryIdx == index)
{
Lock();
m_countryStatus = m_activeMaps.GetCountryStatus(index);
m_progressSize = progress;
Repaint();
Unlock();
}
}
template <class T1, class T2>
string CountryStatusDisplay::FormatStatusMessage(string const & msgID, T1 const * t1, T2 const * t2)
{
string msg = m_controller->GetStringsBundle()->GetString(msgID);
if (t1)
{
if (t2)
msg = strings::Format(msg, *t1, *t2);
else
{
msg = strings::Format(msg, *t1);
size_t const count = msg.size();
if (count > 0)
{
if (msg[count-1] == '\n')
msg.erase(count-1, 1);
}
}
}
return msg;
}
void CountryStatusDisplay::SetVisibilityForState() const
{
uint8_t visibilityFlags = 0;
uint8_t const labelVisibility = 0x1;
uint8_t const primeVisibility = 0x2;
uint8_t const secondaryVisibility = 0x4;
if (m_countryIdx.IsValid())
{
switch (m_countryStatus)
{
case TStatus::EDownloadFailed:
visibilityFlags |= labelVisibility;
visibilityFlags |= primeVisibility;
break;
case TStatus::EDownloading:
case TStatus::EInQueue:
visibilityFlags |= labelVisibility;
break;
case TStatus::ENotDownloaded:
visibilityFlags |= labelVisibility;
visibilityFlags |= primeVisibility;
visibilityFlags |= secondaryVisibility;
break;
default:
break;
}
}
m_label->setIsVisible(visibilityFlags & labelVisibility);
m_primaryButton->setIsVisible(visibilityFlags & primeVisibility);
m_secondaryButton->setIsVisible(visibilityFlags & secondaryVisibility);
TBase::setIsVisible(m_label->isVisible() || m_primaryButton->isVisible() || m_secondaryButton->isVisible());
}
void CountryStatusDisplay::SetContentForState()
{
if (!isVisible())
return;
switch (m_countryStatus)
{
case TStatus::EDownloadFailed:
case TStatus::EOutOfMemFailed:
SetContentForError();
break;
case TStatus::ENotDownloaded:
SetContentForDownloadPropose();
break;
case TStatus::EDownloading:
SetContentForProgress();
break;
case TStatus::EInQueue:
SetContentForInQueue();
break;
default:
break;
}
}
namespace
{
void FormatMapSize(int sizeInBytes, string & units, int & sizeToDownload)
{
int const mbInBytes = 1024 * 1024;
int const kbInBytes = 1024;
if (sizeInBytes < mbInBytes)
{
sizeToDownload = sizeInBytes / kbInBytes;
units = "KB";
}
else
{
sizeToDownload = sizeInBytes / mbInBytes;
units = "MB";
}
}
}
void CountryStatusDisplay::SetContentForDownloadPropose()
{
ASSERT(m_label->isVisible(), ());
ASSERT(m_primaryButton->isVisible(), ());
ASSERT(m_secondaryButton->isVisible(), ());
LocalAndRemoteSizeT mapOnlySize = m_activeMaps.GetCountrySize(m_countryIdx, TMapOptions::EMapOnly);
LocalAndRemoteSizeT withRouting = m_activeMaps.GetCountrySize(m_countryIdx, TMapOptions::EMapWithCarRouting);
m_label->setText(m_displayMapName);
int sizeToDownload;
string units;
FormatMapSize(mapOnlySize.second, units, sizeToDownload);
m_primaryButton->setText(FormatStatusMessage<int, string>("country_status_download", &sizeToDownload, &units));
FormatMapSize(withRouting.second, units, sizeToDownload);
m_secondaryButton->setText(FormatStatusMessage<int, string>("country_status_download_routing", &sizeToDownload));
}
void CountryStatusDisplay::SetContentForProgress()
{
ASSERT(m_label->isVisible(), ());
int const percent = m_progressSize.first * 100 / m_progressSize.second;
m_label->setText(FormatStatusMessage<string, int>("country_status_downloading", &m_displayMapName, &percent));
}
void CountryStatusDisplay::SetContentForInQueue()
{
ASSERT(m_label->isVisible(), ());
m_label->setText(FormatStatusMessage<string, int>("country_status_added_to_queue", &m_displayMapName));
}
void CountryStatusDisplay::SetContentForError()
{
ASSERT(m_label->isVisible(), ());
ASSERT(m_primaryButton->isVisible(), ());
if (m_countryStatus == TStatus::EDownloadFailed)
m_label->setText(FormatStatusMessage<string, int>("country_status_download_failed", &m_displayMapName));
else
m_label->setText(FormatStatusMessage<int, int>("not_enough_free_space_on_sdcard"));
m_primaryButton->setText(m_controller->GetStringsBundle()->GetString("try_again"));
}
void CountryStatusDisplay::ComposeElementsForState()
{
ASSERT(isVisible(), ());
int visibleCount = 0;
auto visibleCheckFn = [&visibleCount](gui::Element const * e)
{
if (e->isVisible())
++visibleCount;
};
visibleCheckFn(m_label.get());
visibleCheckFn(m_primaryButton.get());
visibleCheckFn(m_secondaryButton.get());
ASSERT(visibleCount > 0, ());
m2::PointD const & pv = pivot();
if (visibleCount == 1)
m_label->setPivot(pv);
else if (visibleCount == 2)
{
size_t const labelHeight = m_label->GetBoundRect().SizeY();
size_t const buttonHeight = m_primaryButton->GetBoundRect().SizeY();
size_t const commonHeight = buttonHeight + labelHeight + 10 * visualScale();
m_label->setPivot(m2::PointD(pv.x, pv.y - commonHeight / 2 + labelHeight / 2));
m_primaryButton->setPivot(m2::PointD(pv.x, pv.y + commonHeight / 2 - buttonHeight / 2));
}
else
{
size_t const labelHeight = m_label->GetBoundRect().SizeY();
size_t const primButtonHeight = m_primaryButton->GetBoundRect().SizeY();
size_t const secButtonHeight = m_secondaryButton->GetBoundRect().SizeY();
size_t const emptySpace = 10 * visualScale();
double const offsetFromCenter = (primButtonHeight / 2 + emptySpace);
m_label->setPivot(m2::PointD(pv.x, pv.y - offsetFromCenter - labelHeight / 2));
m_primaryButton->setPivot(pv);
m_secondaryButton->setPivot(m2::PointD(pv.x, pv.y + offsetFromCenter + secButtonHeight / 2.0));
}
}
bool CountryStatusDisplay::OnTapAction(TTapActionFn const & action, const m2::PointD & pt)
{
bool result = false;
if (m_primaryButton->isVisible() && m_primaryButton->hitTest(pt))
result |= action(m_primaryButton, pt);
else if (m_secondaryButton->isVisible() && m_secondaryButton->hitTest(pt))
result |= action(m_secondaryButton, pt);
return result;
}
void CountryStatusDisplay::OnButtonClicked(gui::Element const * button)
{
ASSERT(m_countryIdx.IsValid(), ());
TMapOptions options = TMapOptions::EMapOnly;
if (button == m_secondaryButton.get())
options |= TMapOptions::ECarRouting;
DownloadCountry(static_cast<int>(options));
}
void CountryStatusDisplay::DownloadCountry(int options, bool checkCallback)
{
ASSERT(m_countryIdx.IsValid(), ());
if (checkCallback && m_downloadCallback)
m_downloadCallback(options);
else
{
if (IsStatusFailed())
{
m_progressSize = m_activeMaps.GetDownloadableCountrySize(m_countryIdx);
m_activeMaps.RetryDownloading(m_countryIdx);
}
else
{
TMapOptions mapOptions = static_cast<TMapOptions>(options);
m_progressSize = m_activeMaps.GetCountrySize(m_countryIdx, mapOptions);
m_activeMaps.DownloadMap(m_countryIdx, mapOptions);
}
}
}
void CountryStatusDisplay::Repaint() const
{
setIsDirtyLayout(true);
const_cast<CountryStatusDisplay *>(this)->invalidate();
}
bool CountryStatusDisplay::IsStatusFailed() const
{
return m_countryStatus == TStatus::EOutOfMemFailed || m_countryStatus == TStatus::EDownloadFailed;
}
void CountryStatusDisplay::Lock() const
{
#ifdef OMIM_OS_ANDROID
m_mutex.Lock();
#endif
}
void CountryStatusDisplay::Unlock() const
{
#ifdef OMIM_OS_ANDROID
m_mutex.Unlock();
#endif
}
<commit_msg>Fixed file size string formatting.<commit_after>#include "country_status_display.hpp"
#include "framework.hpp"
#include "../gui/controller.hpp"
#include "../gui/button.hpp"
#include "../gui/text_view.hpp"
#include "../graphics/overlay_renderer.hpp"
#include "../graphics/display_list.hpp"
#include "../platform/platform.hpp"
#include "../base/thread.hpp"
#include "../base/string_format.hpp"
#include "../std/bind.hpp"
#include "../std/sstream.hpp"
using namespace storage;
CountryStatusDisplay::CountryStatusDisplay(Params const & p)
: gui::Element(p)
, m_activeMaps(p.m_activeMaps)
{
m_activeMapsSlotID = m_activeMaps.AddListener(this);
gui::Button::Params bp;
bp.m_depth = depth();
bp.m_minWidth = 200;
bp.m_minHeight = 40;
bp.m_position = graphics::EPosCenter;
auto createButtonFn = [this](gui::Button::Params const & params)
{
gui::Button * result = new gui::Button(params);
result->setIsVisible(false);
result->setOnClickListener(bind(&CountryStatusDisplay::OnButtonClicked, this, _1));
result->setFont(EActive, graphics::FontDesc(16, graphics::Color(255, 255, 255, 255)));
result->setFont(EPressed, graphics::FontDesc(16, graphics::Color(255, 255, 255, 255)));
result->setColor(EActive, graphics::Color(0, 0, 0, 0.6 * 255));
result->setColor(EPressed, graphics::Color(0, 0, 0, 0.4 * 255));
return result;
};
m_primaryButton.reset(createButtonFn(bp));
m_secondaryButton.reset(createButtonFn(bp));
gui::TextView::Params tp;
tp.m_depth = depth();
tp.m_position = graphics::EPosCenter;
m_label.reset(new gui::TextView(tp));
m_label->setIsVisible(false);
m_label->setFont(gui::Element::EActive, graphics::FontDesc(18));
setIsVisible(false);
}
CountryStatusDisplay::~CountryStatusDisplay()
{
m_activeMaps.RemoveListener(m_activeMapsSlotID);
}
void CountryStatusDisplay::SetCountryIndex(TIndex const & idx)
{
if (m_countryIdx != idx)
{
m_countryIdx = idx;
if (m_countryIdx.IsValid())
{
m_countryStatus = m_activeMaps.GetCountryStatus(m_countryIdx);
m_displayMapName = m_activeMaps.GetFormatedCountryName(m_countryIdx);
}
Repaint();
}
}
void CountryStatusDisplay::DownloadCurrentCountry(int options)
{
// I don't know why this work, but it's terrible
// This method call only on android, from "AndroidUIThread"
DownloadCountry(options, false);
}
void CountryStatusDisplay::setIsVisible(bool isVisible) const
{
if (isVisible && isVisible != TBase::isVisible())
Repaint();
TBase::setIsVisible(isVisible);
}
void CountryStatusDisplay::setIsDirtyLayout(bool isDirty) const
{
TBase::setIsDirtyLayout(isDirty);
m_label->setIsDirtyLayout(isDirty);
m_primaryButton->setIsDirtyLayout(isDirty);
m_secondaryButton->setIsDirtyLayout(isDirty);
if (isDirty)
SetVisibilityForState();
}
void CountryStatusDisplay::draw(graphics::OverlayRenderer * r,
math::Matrix<double, 3, 3> const & m) const
{
if (isVisible())
{
Lock();
checkDirtyLayout();
m_label->draw(r, m);
m_primaryButton->draw(r, m);
m_secondaryButton->draw(r, m);
Unlock();
}
}
void CountryStatusDisplay::layout()
{
if (!isVisible())
return;
SetContentForState();
auto layoutFn = [] (gui::Element * e)
{
if (e->isVisible())
e->layout();
};
layoutFn(m_label.get());
layoutFn(m_primaryButton.get());
layoutFn(m_secondaryButton.get());
ComposeElementsForState();
// !!!! Hack !!!!
// ComposeElementsForState modify pivot point of elements.
// After setPivot all elements must be relayouted.
// For reduce "cache" operations we call layout secondary
layoutFn(m_label.get());
layoutFn(m_primaryButton.get());
layoutFn(m_secondaryButton.get());
}
void CountryStatusDisplay::purge()
{
m_label->purge();
m_primaryButton->purge();
m_secondaryButton->purge();
}
void CountryStatusDisplay::cache()
{
auto cacheFn = [](gui::Element * e)
{
if (e->isVisible())
e->cache();
};
cacheFn(m_label.get());
cacheFn(m_primaryButton.get());
cacheFn(m_secondaryButton.get());
}
m2::RectD CountryStatusDisplay::GetBoundRect() const
{
ASSERT(isVisible(), ());
m2::RectD r(pivot(), pivot());
if (m_primaryButton->isVisible())
r.Add(m_primaryButton->GetBoundRect());
if (m_secondaryButton->isVisible())
r.Add(m_secondaryButton->GetBoundRect());
return r;
}
void CountryStatusDisplay::setController(gui::Controller * controller)
{
Element::setController(controller);
m_label->setController(controller);
m_primaryButton->setController(controller);
m_secondaryButton->setController(controller);
}
bool CountryStatusDisplay::onTapStarted(m2::PointD const & pt)
{
return OnTapAction(bind(&gui::Button::onTapStarted, _1, _2), pt);
}
bool CountryStatusDisplay::onTapMoved(m2::PointD const & pt)
{
return OnTapAction(bind(&gui::Button::onTapMoved, _1, _2), pt);
}
bool CountryStatusDisplay::onTapEnded(m2::PointD const & pt)
{
return OnTapAction(bind(&gui::Button::onTapEnded, _1, _2), pt);
}
bool CountryStatusDisplay::onTapCancelled(m2::PointD const & pt)
{
return OnTapAction(bind(&gui::Button::onTapCancelled, _1, _2), pt);
}
void CountryStatusDisplay::CountryStatusChanged(ActiveMapsLayout::TGroup const & group, int position)
{
TIndex index = m_activeMaps.GetCoreIndex(group, position);
if (m_countryIdx == index)
{
Lock();
m_countryStatus = m_activeMaps.GetCountryStatus(index);
Repaint();
Unlock();
}
}
void CountryStatusDisplay::DownloadingProgressUpdate(ActiveMapsLayout::TGroup const & group, int position, LocalAndRemoteSizeT const & progress)
{
TIndex index = m_activeMaps.GetCoreIndex(group, position);
if (m_countryIdx == index)
{
Lock();
m_countryStatus = m_activeMaps.GetCountryStatus(index);
m_progressSize = progress;
Repaint();
Unlock();
}
}
template <class T1, class T2>
string CountryStatusDisplay::FormatStatusMessage(string const & msgID, T1 const * t1, T2 const * t2)
{
string msg = m_controller->GetStringsBundle()->GetString(msgID);
if (t1)
{
if (t2)
msg = strings::Format(msg, *t1, *t2);
else
{
msg = strings::Format(msg, *t1);
size_t const count = msg.size();
if (count > 0)
{
if (msg[count-1] == '\n')
msg.erase(count-1, 1);
}
}
}
return msg;
}
void CountryStatusDisplay::SetVisibilityForState() const
{
uint8_t visibilityFlags = 0;
uint8_t const labelVisibility = 0x1;
uint8_t const primeVisibility = 0x2;
uint8_t const secondaryVisibility = 0x4;
if (m_countryIdx.IsValid())
{
switch (m_countryStatus)
{
case TStatus::EDownloadFailed:
visibilityFlags |= labelVisibility;
visibilityFlags |= primeVisibility;
break;
case TStatus::EDownloading:
case TStatus::EInQueue:
visibilityFlags |= labelVisibility;
break;
case TStatus::ENotDownloaded:
visibilityFlags |= labelVisibility;
visibilityFlags |= primeVisibility;
visibilityFlags |= secondaryVisibility;
break;
default:
break;
}
}
m_label->setIsVisible(visibilityFlags & labelVisibility);
m_primaryButton->setIsVisible(visibilityFlags & primeVisibility);
m_secondaryButton->setIsVisible(visibilityFlags & secondaryVisibility);
TBase::setIsVisible(m_label->isVisible() || m_primaryButton->isVisible() || m_secondaryButton->isVisible());
}
void CountryStatusDisplay::SetContentForState()
{
if (!isVisible())
return;
switch (m_countryStatus)
{
case TStatus::EDownloadFailed:
case TStatus::EOutOfMemFailed:
SetContentForError();
break;
case TStatus::ENotDownloaded:
SetContentForDownloadPropose();
break;
case TStatus::EDownloading:
SetContentForProgress();
break;
case TStatus::EInQueue:
SetContentForInQueue();
break;
default:
break;
}
}
namespace
{
void FormatMapSize(uint64_t sizeInBytes, string & units, uint64_t & sizeToDownload)
{
int const mbInBytes = 1024 * 1024;
int const kbInBytes = 1024;
if (sizeInBytes < mbInBytes)
{
sizeToDownload = (sizeInBytes + kbInBytes / 2) / kbInBytes;
units = "KB";
}
else
{
sizeToDownload = (sizeInBytes + mbInBytes / 2) / mbInBytes;
units = "MB";
}
}
}
void CountryStatusDisplay::SetContentForDownloadPropose()
{
ASSERT(m_label->isVisible(), ());
ASSERT(m_primaryButton->isVisible(), ());
ASSERT(m_secondaryButton->isVisible(), ());
LocalAndRemoteSizeT mapOnlySize = m_activeMaps.GetCountrySize(m_countryIdx, TMapOptions::EMapOnly);
LocalAndRemoteSizeT withRouting = m_activeMaps.GetCountrySize(m_countryIdx, TMapOptions::EMapWithCarRouting);
m_label->setText(m_displayMapName);
uint64_t sizeToDownload;
string units;
FormatMapSize(mapOnlySize.second, units, sizeToDownload);
m_primaryButton->setText(FormatStatusMessage("country_status_download", &sizeToDownload, &units));
FormatMapSize(withRouting.second, units, sizeToDownload);
m_secondaryButton->setText(FormatStatusMessage("country_status_download_routing", &sizeToDownload, &units));
}
void CountryStatusDisplay::SetContentForProgress()
{
ASSERT(m_label->isVisible(), ());
int const percent = m_progressSize.first * 100 / m_progressSize.second;
m_label->setText(FormatStatusMessage<string, int>("country_status_downloading", &m_displayMapName, &percent));
}
void CountryStatusDisplay::SetContentForInQueue()
{
ASSERT(m_label->isVisible(), ());
m_label->setText(FormatStatusMessage<string, int>("country_status_added_to_queue", &m_displayMapName));
}
void CountryStatusDisplay::SetContentForError()
{
ASSERT(m_label->isVisible(), ());
ASSERT(m_primaryButton->isVisible(), ());
if (m_countryStatus == TStatus::EDownloadFailed)
m_label->setText(FormatStatusMessage<string, int>("country_status_download_failed", &m_displayMapName));
else
m_label->setText(FormatStatusMessage<int, int>("not_enough_free_space_on_sdcard"));
m_primaryButton->setText(m_controller->GetStringsBundle()->GetString("try_again"));
}
void CountryStatusDisplay::ComposeElementsForState()
{
ASSERT(isVisible(), ());
int visibleCount = 0;
auto visibleCheckFn = [&visibleCount](gui::Element const * e)
{
if (e->isVisible())
++visibleCount;
};
visibleCheckFn(m_label.get());
visibleCheckFn(m_primaryButton.get());
visibleCheckFn(m_secondaryButton.get());
ASSERT(visibleCount > 0, ());
m2::PointD const & pv = pivot();
if (visibleCount == 1)
m_label->setPivot(pv);
else if (visibleCount == 2)
{
size_t const labelHeight = m_label->GetBoundRect().SizeY();
size_t const buttonHeight = m_primaryButton->GetBoundRect().SizeY();
size_t const commonHeight = buttonHeight + labelHeight + 10 * visualScale();
m_label->setPivot(m2::PointD(pv.x, pv.y - commonHeight / 2 + labelHeight / 2));
m_primaryButton->setPivot(m2::PointD(pv.x, pv.y + commonHeight / 2 - buttonHeight / 2));
}
else
{
size_t const labelHeight = m_label->GetBoundRect().SizeY();
size_t const primButtonHeight = m_primaryButton->GetBoundRect().SizeY();
size_t const secButtonHeight = m_secondaryButton->GetBoundRect().SizeY();
size_t const emptySpace = 10 * visualScale();
double const offsetFromCenter = (primButtonHeight / 2 + emptySpace);
m_label->setPivot(m2::PointD(pv.x, pv.y - offsetFromCenter - labelHeight / 2));
m_primaryButton->setPivot(pv);
m_secondaryButton->setPivot(m2::PointD(pv.x, pv.y + offsetFromCenter + secButtonHeight / 2.0));
}
}
bool CountryStatusDisplay::OnTapAction(TTapActionFn const & action, const m2::PointD & pt)
{
bool result = false;
if (m_primaryButton->isVisible() && m_primaryButton->hitTest(pt))
result |= action(m_primaryButton, pt);
else if (m_secondaryButton->isVisible() && m_secondaryButton->hitTest(pt))
result |= action(m_secondaryButton, pt);
return result;
}
void CountryStatusDisplay::OnButtonClicked(gui::Element const * button)
{
ASSERT(m_countryIdx.IsValid(), ());
TMapOptions options = TMapOptions::EMapOnly;
if (button == m_secondaryButton.get())
options |= TMapOptions::ECarRouting;
DownloadCountry(static_cast<int>(options));
}
void CountryStatusDisplay::DownloadCountry(int options, bool checkCallback)
{
ASSERT(m_countryIdx.IsValid(), ());
if (checkCallback && m_downloadCallback)
m_downloadCallback(options);
else
{
if (IsStatusFailed())
{
m_progressSize = m_activeMaps.GetDownloadableCountrySize(m_countryIdx);
m_activeMaps.RetryDownloading(m_countryIdx);
}
else
{
TMapOptions mapOptions = static_cast<TMapOptions>(options);
m_progressSize = m_activeMaps.GetCountrySize(m_countryIdx, mapOptions);
m_activeMaps.DownloadMap(m_countryIdx, mapOptions);
}
}
}
void CountryStatusDisplay::Repaint() const
{
setIsDirtyLayout(true);
const_cast<CountryStatusDisplay *>(this)->invalidate();
}
bool CountryStatusDisplay::IsStatusFailed() const
{
return m_countryStatus == TStatus::EOutOfMemFailed || m_countryStatus == TStatus::EDownloadFailed;
}
void CountryStatusDisplay::Lock() const
{
#ifdef OMIM_OS_ANDROID
m_mutex.Lock();
#endif
}
void CountryStatusDisplay::Unlock() const
{
#ifdef OMIM_OS_ANDROID
m_mutex.Unlock();
#endif
}
<|endoftext|> |
<commit_before>#include <node_buffer.h>
#include <stdint.h>
#include <iostream>
#include <string>
#include "talk/app/webrtc/jsep.h"
#include "webrtc/system_wrappers/interface/ref_count.h"
#include "common.h"
#include "datachannel.h"
using namespace node_webrtc;
v8::Persistent<v8::Function> DataChannel::constructor;
#if NODE_MODULE_VERSION < 0x000C
v8::Persistent<v8::Function> DataChannel::ArrayBufferConstructor;
#endif
DataChannelObserver::DataChannelObserver(rtc::scoped_refptr<webrtc::DataChannelInterface> jingleDataChannel) {
TRACE_CALL;
uv_mutex_init(&lock);
_jingleDataChannel = jingleDataChannel;
_jingleDataChannel->RegisterObserver(this);
TRACE_END;
}
DataChannelObserver::~DataChannelObserver() {
_jingleDataChannel = NULL;
}
void DataChannelObserver::OnStateChange()
{
TRACE_CALL;
DataChannel::StateEvent* data = new DataChannel::StateEvent(_jingleDataChannel->state());
QueueEvent(DataChannel::STATE, static_cast<void*>(data));
TRACE_END;
}
void DataChannelObserver::OnMessage(const webrtc::DataBuffer& buffer)
{
TRACE_CALL;
DataChannel::MessageEvent* data = new DataChannel::MessageEvent(&buffer);
QueueEvent(DataChannel::MESSAGE, static_cast<void*>(data));
TRACE_END;
}
void DataChannelObserver::QueueEvent(DataChannel::AsyncEventType type, void* data) {
TRACE_CALL;
DataChannel::AsyncEvent evt;
evt.type = type;
evt.data = data;
uv_mutex_lock(&lock);
_events.push(evt);
uv_mutex_unlock(&lock);
TRACE_END;
}
DataChannel::DataChannel(node_webrtc::DataChannelObserver* observer)
: loop(uv_default_loop()),
_observer(observer),
_binaryType(DataChannel::ARRAY_BUFFER)
{
uv_mutex_init(&lock);
uv_async_init(loop, &async, reinterpret_cast<uv_async_cb>(Run));
_jingleDataChannel = observer->_jingleDataChannel;
_jingleDataChannel->RegisterObserver(this);
async.data = this;
// Re-queue cached observer events
while(true) {
uv_mutex_lock(&observer->lock);
bool empty = observer->_events.empty();
if(empty)
{
uv_mutex_unlock(&observer->lock);
break;
}
AsyncEvent evt = observer->_events.front();
observer->_events.pop();
uv_mutex_unlock(&observer->lock);
QueueEvent(evt.type, evt.data);
}
delete observer;
}
DataChannel::~DataChannel()
{
TRACE_CALL;
_jingleDataChannel->UnregisterObserver();
_jingleDataChannel = NULL;
TRACE_END;
}
NAN_METHOD(DataChannel::New) {
TRACE_CALL;
NanScope();
if(!args.IsConstructCall()) {
return NanThrowTypeError("Use the new operator to construct the DataChannel.");
}
v8::Local<v8::External> _observer = v8::Local<v8::External>::Cast(args[0]);
node_webrtc::DataChannelObserver* observer = static_cast<node_webrtc::DataChannelObserver*>(_observer->Value());
DataChannel* obj = new DataChannel(observer);
obj->Wrap( args.This() );
TRACE_END;
NanReturnValue( args.This() );
}
void DataChannel::QueueEvent(AsyncEventType type, void* data)
{
TRACE_CALL;
AsyncEvent evt;
evt.type = type;
evt.data = data;
uv_mutex_lock(&lock);
_events.push(evt);
uv_mutex_unlock(&lock);
uv_async_send(&async);
TRACE_END;
}
NAN_WEAK_CALLBACK(MessageWeakCallback)
{
P* parameter = data.GetParameter();
delete[] parameter->message;
parameter->message = NULL;
delete parameter;
//NanAdjustExternalMemory(-parameter->size);
}
void DataChannel::Run(uv_async_t* handle, int status)
{
NanScope();
DataChannel* self = static_cast<DataChannel*>(handle->data);
TRACE_CALL_P((uintptr_t)self);
v8::Handle<v8::Object> dc = NanObjectWrapHandle(self);
bool do_shutdown = false;
while(true)
{
uv_mutex_lock(&self->lock);
bool empty = self->_events.empty();
if(empty)
{
uv_mutex_unlock(&self->lock);
break;
}
AsyncEvent evt = self->_events.front();
self->_events.pop();
uv_mutex_unlock(&self->lock);
TRACE_U("evt.type", evt.type);
if(DataChannel::ERROR & evt.type)
{
DataChannel::ErrorEvent* data = static_cast<DataChannel::ErrorEvent*>(evt.data);
v8::Local<v8::Function> callback = v8::Local<v8::Function>::Cast(dc->Get(NanNew("onerror")));
v8::Local<v8::Value> argv[1];
argv[0] = v8::Exception::Error(NanNew(data->msg));
NanMakeCallback(dc, callback, 1, argv);
} else if(DataChannel::STATE & evt.type)
{
StateEvent* data = static_cast<StateEvent*>(evt.data);
v8::Local<v8::Function> callback = v8::Local<v8::Function>::Cast(dc->Get(NanNew("onstatechange")));
v8::Local<v8::Value> argv[1];
v8::Local<v8::Integer> state = NanNew<v8::Integer>((data->state));
argv[0] = state;
NanMakeCallback(dc, callback, 1, argv);
if(webrtc::DataChannelInterface::kClosed == self->_jingleDataChannel->state()) {
do_shutdown = true;
}
} else if(DataChannel::MESSAGE & evt.type)
{
MessageEvent* data = static_cast<MessageEvent*>(evt.data);
v8::Local<v8::Function> callback = v8::Local<v8::Function>::Cast(dc->Get(NanNew("onmessage")));
v8::Local<v8::Value> argv[1];
if(data->binary) {
#if NODE_MODULE_VERSION > 0x000B
v8::Local<v8::ArrayBuffer> array = v8::ArrayBuffer::New(
v8::Isolate::GetCurrent(), data->message, data->size);
#else
v8::Local<v8::Object> array = NanNew(ArrayBufferConstructor)->NewInstance();
array->SetIndexedPropertiesToExternalArrayData(
data->message, v8::kExternalByteArray, data->size);
array->ForceSet(NanNew("byteLength"), NanNew<v8::Integer>(static_cast<uint32_t>(data->size)));
#endif
NanMakeWeakPersistent(callback, data, &MessageWeakCallback);
argv[0] = array;
NanMakeCallback(dc, callback, 1, argv);
} else {
v8::Local<v8::String> str = NanNew(data->message, data->size);
// cleanup message event
delete[] data->message;
data->message = NULL;
delete data;
argv[0] = str;
NanMakeCallback(dc, callback, 1, argv);
}
}
}
if(do_shutdown) {
uv_close((uv_handle_t*)(&self->async), NULL);
}
TRACE_END;
}
void DataChannel::OnStateChange()
{
TRACE_CALL;
StateEvent* data = new StateEvent(_jingleDataChannel->state());
QueueEvent(DataChannel::STATE, static_cast<void*>(data));
TRACE_END;
}
void DataChannel::OnMessage(const webrtc::DataBuffer& buffer)
{
TRACE_CALL;
MessageEvent* data = new MessageEvent(&buffer);
QueueEvent(DataChannel::MESSAGE, static_cast<void*>(data));
TRACE_END;
}
NAN_METHOD(DataChannel::Send) {
TRACE_CALL;
NanScope();
DataChannel* self = ObjectWrap::Unwrap<DataChannel>( args.This() );
if(args[0]->IsString()) {
v8::Local<v8::String> str = v8::Local<v8::String>::Cast(args[0]);
std::string data = *v8::String::Utf8Value(str);
webrtc::DataBuffer buffer(data);
self->_jingleDataChannel->Send(buffer);
} else {
#if NODE_MINOR_VERSION >= 11
v8::Local<v8::ArrayBuffer> arraybuffer;
if (args[0]->IsArrayBuffer()) {
arraybuffer = v8::Local<v8::ArrayBuffer>::Cast(args[0]);
} else {
v8::Local<v8::ArrayBufferView> view = v8::Local<v8::ArrayBufferView>::Cast(args[0]);
arraybuffer = view->Buffer();
}
v8::ArrayBuffer::Contents content = arraybuffer->Externalize();
rtc::Buffer buffer(content.Data(), content.ByteLength());
#else
v8::Local<v8::Object> arraybuffer = v8::Local<v8::Object>::Cast(args[0]);
void* data = arraybuffer->GetIndexedPropertiesExternalArrayData();
uint32_t data_len = arraybuffer->GetIndexedPropertiesExternalArrayDataLength();
rtc::Buffer buffer(data, data_len);
#endif
webrtc::DataBuffer data_buffer(buffer, true);
self->_jingleDataChannel->Send(data_buffer);
#if NODE_MINOR_VERSION >= 11
arraybuffer->Neuter();
#endif
}
TRACE_END;
NanReturnUndefined();
}
NAN_METHOD(DataChannel::Close) {
TRACE_CALL;
NanScope();
DataChannel* self = ObjectWrap::Unwrap<DataChannel>( args.This() );
self->_jingleDataChannel->Close();
TRACE_END;
NanReturnUndefined();
}
NAN_METHOD(DataChannel::Shutdown) {
TRACE_CALL;
NanScope();
DataChannel* self = ObjectWrap::Unwrap<DataChannel>( args.This() );
if(!uv_is_closing((uv_handle_t*)(&self->async)))
uv_close((uv_handle_t*)(&self->async), NULL);
TRACE_END;
NanReturnUndefined();
}
NAN_GETTER(DataChannel::GetBufferedAmount) {
TRACE_CALL;
NanScope();
DataChannel* self = node::ObjectWrap::Unwrap<DataChannel>( args.Holder() );
uint64_t buffered_amount = self->_jingleDataChannel->buffered_amount();
TRACE_END;
NanReturnValue(NanNew<v8::Number>(buffered_amount));
}
NAN_GETTER(DataChannel::GetLabel) {
TRACE_CALL;
NanScope();
DataChannel* self = node::ObjectWrap::Unwrap<DataChannel>( args.Holder() );
std::string label = self->_jingleDataChannel->label();
TRACE_END;
NanReturnValue(NanNew(label));
}
NAN_GETTER(DataChannel::GetReadyState) {
TRACE_CALL;
NanScope();
DataChannel* self = node::ObjectWrap::Unwrap<DataChannel>( args.Holder() );
webrtc::DataChannelInterface::DataState state = self->_jingleDataChannel->state();
TRACE_END;
NanReturnValue(NanNew<v8::Number>(static_cast<uint32_t>(state)));
}
NAN_GETTER(DataChannel::GetBinaryType) {
TRACE_CALL;
NanScope();
DataChannel* self = node::ObjectWrap::Unwrap<DataChannel>( args.Holder() );
TRACE_END;
NanReturnValue(NanNew<v8::Number>(static_cast<uint32_t>(self->_binaryType)));
}
NAN_SETTER(DataChannel::SetBinaryType) {
TRACE_CALL;
DataChannel* self = node::ObjectWrap::Unwrap<DataChannel>( args.Holder() );
self->_binaryType = static_cast<BinaryType>(value->Uint32Value());
TRACE_END;
}
NAN_SETTER(DataChannel::ReadOnly) {
INFO("PeerConnection::ReadOnly");
}
void DataChannel::Init( v8::Handle<v8::Object> exports ) {
v8::Local<v8::FunctionTemplate> tpl = NanNew<v8::FunctionTemplate>( New );
tpl->SetClassName( NanNew( "DataChannel" ) );
tpl->InstanceTemplate()->SetInternalFieldCount(1);
tpl->PrototypeTemplate()->Set( NanNew( "close" ),
NanNew<v8::FunctionTemplate>( Close )->GetFunction() );
tpl->PrototypeTemplate()->Set( NanNew( "shutdown" ),
NanNew<v8::FunctionTemplate>( Shutdown )->GetFunction() );
tpl->PrototypeTemplate()->Set( NanNew( "send" ),
NanNew<v8::FunctionTemplate>( Send )->GetFunction() );
tpl->InstanceTemplate()->SetAccessor(NanNew("bufferedAmount"), GetBufferedAmount, ReadOnly);
tpl->InstanceTemplate()->SetAccessor(NanNew("label"), GetLabel, ReadOnly);
tpl->InstanceTemplate()->SetAccessor(NanNew("binaryType"), GetBinaryType, SetBinaryType);
tpl->InstanceTemplate()->SetAccessor(NanNew("readyState"), GetReadyState, ReadOnly);
NanAssignPersistent(constructor, tpl->GetFunction());
exports->Set( NanNew("DataChannel"), tpl->GetFunction() );
v8::Local<v8::Object> global = NanGetCurrentContext()->Global();
#if NODE_MODULE_VERSION < 0x000C
v8::Local<v8::Value> obj = global->Get(NanNew("ArrayBuffer"));
NanAssignPersistent(ArrayBufferConstructor, obj.As<v8::Function>());
#endif
}
<commit_msg>Fix crash on DC cleanup<commit_after>#include <node_buffer.h>
#include <stdint.h>
#include <iostream>
#include <string>
#include "talk/app/webrtc/jsep.h"
#include "webrtc/system_wrappers/interface/ref_count.h"
#include "common.h"
#include "datachannel.h"
using namespace node_webrtc;
v8::Persistent<v8::Function> DataChannel::constructor;
#if NODE_MODULE_VERSION < 0x000C
v8::Persistent<v8::Function> DataChannel::ArrayBufferConstructor;
#endif
DataChannelObserver::DataChannelObserver(rtc::scoped_refptr<webrtc::DataChannelInterface> jingleDataChannel) {
TRACE_CALL;
uv_mutex_init(&lock);
_jingleDataChannel = jingleDataChannel;
_jingleDataChannel->RegisterObserver(this);
TRACE_END;
}
DataChannelObserver::~DataChannelObserver() {
_jingleDataChannel = NULL;
}
void DataChannelObserver::OnStateChange()
{
TRACE_CALL;
DataChannel::StateEvent* data = new DataChannel::StateEvent(_jingleDataChannel->state());
QueueEvent(DataChannel::STATE, static_cast<void*>(data));
TRACE_END;
}
void DataChannelObserver::OnMessage(const webrtc::DataBuffer& buffer)
{
TRACE_CALL;
DataChannel::MessageEvent* data = new DataChannel::MessageEvent(&buffer);
QueueEvent(DataChannel::MESSAGE, static_cast<void*>(data));
TRACE_END;
}
void DataChannelObserver::QueueEvent(DataChannel::AsyncEventType type, void* data) {
TRACE_CALL;
DataChannel::AsyncEvent evt;
evt.type = type;
evt.data = data;
uv_mutex_lock(&lock);
_events.push(evt);
uv_mutex_unlock(&lock);
TRACE_END;
}
DataChannel::DataChannel(node_webrtc::DataChannelObserver* observer)
: loop(uv_default_loop()),
_observer(observer),
_binaryType(DataChannel::ARRAY_BUFFER)
{
uv_mutex_init(&lock);
uv_async_init(loop, &async, reinterpret_cast<uv_async_cb>(Run));
_jingleDataChannel = observer->_jingleDataChannel;
_jingleDataChannel->RegisterObserver(this);
async.data = this;
// Re-queue cached observer events
while(true) {
uv_mutex_lock(&observer->lock);
bool empty = observer->_events.empty();
if(empty)
{
uv_mutex_unlock(&observer->lock);
break;
}
AsyncEvent evt = observer->_events.front();
observer->_events.pop();
uv_mutex_unlock(&observer->lock);
QueueEvent(evt.type, evt.data);
}
delete observer;
}
DataChannel::~DataChannel()
{
TRACE_CALL;
TRACE_END;
}
NAN_METHOD(DataChannel::New) {
TRACE_CALL;
NanScope();
if(!args.IsConstructCall()) {
return NanThrowTypeError("Use the new operator to construct the DataChannel.");
}
v8::Local<v8::External> _observer = v8::Local<v8::External>::Cast(args[0]);
node_webrtc::DataChannelObserver* observer = static_cast<node_webrtc::DataChannelObserver*>(_observer->Value());
DataChannel* obj = new DataChannel(observer);
obj->Wrap( args.This() );
TRACE_END;
NanReturnValue( args.This() );
}
void DataChannel::QueueEvent(AsyncEventType type, void* data)
{
TRACE_CALL;
AsyncEvent evt;
evt.type = type;
evt.data = data;
uv_mutex_lock(&lock);
_events.push(evt);
uv_mutex_unlock(&lock);
uv_async_send(&async);
TRACE_END;
}
NAN_WEAK_CALLBACK(MessageWeakCallback)
{
P* parameter = data.GetParameter();
delete[] parameter->message;
parameter->message = NULL;
delete parameter;
//NanAdjustExternalMemory(-parameter->size);
}
void DataChannel::Run(uv_async_t* handle, int status)
{
NanScope();
DataChannel* self = static_cast<DataChannel*>(handle->data);
TRACE_CALL_P((uintptr_t)self);
v8::Handle<v8::Object> dc = NanObjectWrapHandle(self);
bool do_shutdown = false;
while(true)
{
uv_mutex_lock(&self->lock);
bool empty = self->_events.empty();
if(empty)
{
uv_mutex_unlock(&self->lock);
break;
}
AsyncEvent evt = self->_events.front();
self->_events.pop();
uv_mutex_unlock(&self->lock);
TRACE_U("evt.type", evt.type);
if(DataChannel::ERROR & evt.type)
{
DataChannel::ErrorEvent* data = static_cast<DataChannel::ErrorEvent*>(evt.data);
v8::Local<v8::Function> callback = v8::Local<v8::Function>::Cast(dc->Get(NanNew("onerror")));
v8::Local<v8::Value> argv[1];
argv[0] = v8::Exception::Error(NanNew(data->msg));
NanMakeCallback(dc, callback, 1, argv);
} else if(DataChannel::STATE & evt.type)
{
StateEvent* data = static_cast<StateEvent*>(evt.data);
v8::Local<v8::Function> callback = v8::Local<v8::Function>::Cast(dc->Get(NanNew("onstatechange")));
v8::Local<v8::Value> argv[1];
v8::Local<v8::Integer> state = NanNew<v8::Integer>((data->state));
argv[0] = state;
NanMakeCallback(dc, callback, 1, argv);
if(webrtc::DataChannelInterface::kClosed == self->_jingleDataChannel->state()) {
do_shutdown = true;
}
} else if(DataChannel::MESSAGE & evt.type)
{
MessageEvent* data = static_cast<MessageEvent*>(evt.data);
v8::Local<v8::Function> callback = v8::Local<v8::Function>::Cast(dc->Get(NanNew("onmessage")));
v8::Local<v8::Value> argv[1];
if(data->binary) {
#if NODE_MODULE_VERSION > 0x000B
v8::Local<v8::ArrayBuffer> array = v8::ArrayBuffer::New(
v8::Isolate::GetCurrent(), data->message, data->size);
#else
v8::Local<v8::Object> array = NanNew(ArrayBufferConstructor)->NewInstance();
array->SetIndexedPropertiesToExternalArrayData(
data->message, v8::kExternalByteArray, data->size);
array->ForceSet(NanNew("byteLength"), NanNew<v8::Integer>(static_cast<uint32_t>(data->size)));
#endif
NanMakeWeakPersistent(callback, data, &MessageWeakCallback);
argv[0] = array;
NanMakeCallback(dc, callback, 1, argv);
} else {
v8::Local<v8::String> str = NanNew(data->message, data->size);
// cleanup message event
delete[] data->message;
data->message = NULL;
delete data;
argv[0] = str;
NanMakeCallback(dc, callback, 1, argv);
}
}
}
if(do_shutdown) {
uv_close((uv_handle_t*)(&self->async), NULL);
_jingleDataChannel->UnregisterObserver();
_jingleDataChannel = NULL;
}
TRACE_END;
}
void DataChannel::OnStateChange()
{
TRACE_CALL;
StateEvent* data = new StateEvent(_jingleDataChannel->state());
QueueEvent(DataChannel::STATE, static_cast<void*>(data));
TRACE_END;
}
void DataChannel::OnMessage(const webrtc::DataBuffer& buffer)
{
TRACE_CALL;
MessageEvent* data = new MessageEvent(&buffer);
QueueEvent(DataChannel::MESSAGE, static_cast<void*>(data));
TRACE_END;
}
NAN_METHOD(DataChannel::Send) {
TRACE_CALL;
NanScope();
DataChannel* self = ObjectWrap::Unwrap<DataChannel>( args.This() );
if(args[0]->IsString()) {
v8::Local<v8::String> str = v8::Local<v8::String>::Cast(args[0]);
std::string data = *v8::String::Utf8Value(str);
webrtc::DataBuffer buffer(data);
self->_jingleDataChannel->Send(buffer);
} else {
#if NODE_MINOR_VERSION >= 11
v8::Local<v8::ArrayBuffer> arraybuffer;
if (args[0]->IsArrayBuffer()) {
arraybuffer = v8::Local<v8::ArrayBuffer>::Cast(args[0]);
} else {
v8::Local<v8::ArrayBufferView> view = v8::Local<v8::ArrayBufferView>::Cast(args[0]);
arraybuffer = view->Buffer();
}
v8::ArrayBuffer::Contents content = arraybuffer->Externalize();
rtc::Buffer buffer(content.Data(), content.ByteLength());
#else
v8::Local<v8::Object> arraybuffer = v8::Local<v8::Object>::Cast(args[0]);
void* data = arraybuffer->GetIndexedPropertiesExternalArrayData();
uint32_t data_len = arraybuffer->GetIndexedPropertiesExternalArrayDataLength();
rtc::Buffer buffer(data, data_len);
#endif
webrtc::DataBuffer data_buffer(buffer, true);
self->_jingleDataChannel->Send(data_buffer);
#if NODE_MINOR_VERSION >= 11
arraybuffer->Neuter();
#endif
}
TRACE_END;
NanReturnUndefined();
}
NAN_METHOD(DataChannel::Close) {
TRACE_CALL;
NanScope();
DataChannel* self = ObjectWrap::Unwrap<DataChannel>( args.This() );
self->_jingleDataChannel->Close();
TRACE_END;
NanReturnUndefined();
}
NAN_METHOD(DataChannel::Shutdown) {
TRACE_CALL;
NanScope();
DataChannel* self = ObjectWrap::Unwrap<DataChannel>( args.This() );
if(!uv_is_closing((uv_handle_t*)(&self->async)))
uv_close((uv_handle_t*)(&self->async), NULL);
TRACE_END;
NanReturnUndefined();
}
NAN_GETTER(DataChannel::GetBufferedAmount) {
TRACE_CALL;
NanScope();
DataChannel* self = node::ObjectWrap::Unwrap<DataChannel>( args.Holder() );
uint64_t buffered_amount = self->_jingleDataChannel->buffered_amount();
TRACE_END;
NanReturnValue(NanNew<v8::Number>(buffered_amount));
}
NAN_GETTER(DataChannel::GetLabel) {
TRACE_CALL;
NanScope();
DataChannel* self = node::ObjectWrap::Unwrap<DataChannel>( args.Holder() );
std::string label = self->_jingleDataChannel->label();
TRACE_END;
NanReturnValue(NanNew(label));
}
NAN_GETTER(DataChannel::GetReadyState) {
TRACE_CALL;
NanScope();
DataChannel* self = node::ObjectWrap::Unwrap<DataChannel>( args.Holder() );
webrtc::DataChannelInterface::DataState state = self->_jingleDataChannel->state();
TRACE_END;
NanReturnValue(NanNew<v8::Number>(static_cast<uint32_t>(state)));
}
NAN_GETTER(DataChannel::GetBinaryType) {
TRACE_CALL;
NanScope();
DataChannel* self = node::ObjectWrap::Unwrap<DataChannel>( args.Holder() );
TRACE_END;
NanReturnValue(NanNew<v8::Number>(static_cast<uint32_t>(self->_binaryType)));
}
NAN_SETTER(DataChannel::SetBinaryType) {
TRACE_CALL;
DataChannel* self = node::ObjectWrap::Unwrap<DataChannel>( args.Holder() );
self->_binaryType = static_cast<BinaryType>(value->Uint32Value());
TRACE_END;
}
NAN_SETTER(DataChannel::ReadOnly) {
INFO("PeerConnection::ReadOnly");
}
void DataChannel::Init( v8::Handle<v8::Object> exports ) {
v8::Local<v8::FunctionTemplate> tpl = NanNew<v8::FunctionTemplate>( New );
tpl->SetClassName( NanNew( "DataChannel" ) );
tpl->InstanceTemplate()->SetInternalFieldCount(1);
tpl->PrototypeTemplate()->Set( NanNew( "close" ),
NanNew<v8::FunctionTemplate>( Close )->GetFunction() );
tpl->PrototypeTemplate()->Set( NanNew( "shutdown" ),
NanNew<v8::FunctionTemplate>( Shutdown )->GetFunction() );
tpl->PrototypeTemplate()->Set( NanNew( "send" ),
NanNew<v8::FunctionTemplate>( Send )->GetFunction() );
tpl->InstanceTemplate()->SetAccessor(NanNew("bufferedAmount"), GetBufferedAmount, ReadOnly);
tpl->InstanceTemplate()->SetAccessor(NanNew("label"), GetLabel, ReadOnly);
tpl->InstanceTemplate()->SetAccessor(NanNew("binaryType"), GetBinaryType, SetBinaryType);
tpl->InstanceTemplate()->SetAccessor(NanNew("readyState"), GetReadyState, ReadOnly);
NanAssignPersistent(constructor, tpl->GetFunction());
exports->Set( NanNew("DataChannel"), tpl->GetFunction() );
v8::Local<v8::Object> global = NanGetCurrentContext()->Global();
#if NODE_MODULE_VERSION < 0x000C
v8::Local<v8::Value> obj = global->Get(NanNew("ArrayBuffer"));
NanAssignPersistent(ArrayBufferConstructor, obj.As<v8::Function>());
#endif
}
<|endoftext|> |
<commit_before>#include "dds_stream.hpp"
#include "gl_util.hpp"
#include "thirdparty/shaun/sweeper.hpp"
#include "thirdparty/shaun/parser.hpp"
#include <iostream>
#include <fstream>
#include <algorithm>
#include <cmath>
using namespace std;
GLenum DDSFormatToGL(DDSLoader::Format format)
{
switch (format)
{
case DDSLoader::Format::BC1: return GL_COMPRESSED_RGBA_S3TC_DXT1_EXT;
case DDSLoader::Format::BC1_SRGB: return GL_COMPRESSED_SRGB_ALPHA_S3TC_DXT1_EXT;
case DDSLoader::Format::BC2: return GL_COMPRESSED_RGBA_S3TC_DXT3_EXT;
case DDSLoader::Format::BC2_SRGB: return GL_COMPRESSED_SRGB_ALPHA_S3TC_DXT3_EXT;
case DDSLoader::Format::BC3: return GL_COMPRESSED_RGBA_S3TC_DXT5_EXT;
case DDSLoader::Format::BC3_SRGB: return GL_COMPRESSED_SRGB_ALPHA_S3TC_DXT5_EXT;
case DDSLoader::Format::BC4: return GL_COMPRESSED_RED_RGTC1;
case DDSLoader::Format::BC4_SIGNED:return GL_COMPRESSED_SIGNED_RED_RGTC1;
case DDSLoader::Format::BC5: return GL_COMPRESSED_RG_RGTC2;
case DDSLoader::Format::BC5_SIGNED:return GL_COMPRESSED_SIGNED_RG_RGTC2;
case DDSLoader::Format::BC6: return GL_COMPRESSED_RGB_BPTC_UNSIGNED_FLOAT;
case DDSLoader::Format::BC6_SIGNED:return GL_COMPRESSED_RGB_BPTC_SIGNED_FLOAT;
case DDSLoader::Format::BC7: return GL_COMPRESSED_RGBA_BPTC_UNORM;
case DDSLoader::Format::BC7_SRGB: return GL_COMPRESSED_SRGB_ALPHA_BPTC_UNORM;
}
return 0;
}
void DDSStreamer::init(int pageSize, int numPages, int maxSize)
{
_maxSize = maxSize;
_pageSize = pageSize;
_numPages = numPages;
int pboSize = pageSize*numPages;
glCreateBuffers(1, &_pbo);
GLbitfield storageFlags = GL_MAP_WRITE_BIT|GL_MAP_PERSISTENT_BIT;
#ifdef USE_COHERENT_MAPPING
storageFlags = storageFlags | GL_MAP_COHERENT_BIT;
#endif
glNamedBufferStorage(_pbo, pboSize, nullptr, storageFlags);
GLbitfield mapFlags = storageFlags;
#ifndef USE_COHERENT_MAPPING
mapFlags = mapFlags | GL_MAP_FLUSH_EXPLICIT_BIT;
#endif
_pboPtr = glMapNamedBufferRange(
_pbo, 0, pboSize, mapFlags);
_usedPages.resize(numPages, false);
_pageFences.resize(numPages);
_t = thread([this]{
while (true)
{
LoadInfo info{};
{
unique_lock<mutex> lk(_mtx);
_cond.wait(lk, [this]{ return _killThread || !_loadInfoQueue.empty();});
if (_killThread) return;
info = _loadInfoQueue[0];
_loadInfoQueue.erase(_loadInfoQueue.begin());
}
LoadData data = load(info);
{
lock_guard<mutex> lk(_dataMtx);
_loadData.push_back(data);
}
}
});
}
DDSStreamer::~DDSStreamer()
{
if (_pbo)
{
glUnmapNamedBuffer(_pbo);
glDeleteBuffers(1, &_pbo);
}
if (_t.joinable())
{
{
lock_guard<mutex> lk(_mtx);
_killThread = true;
}
_cond.notify_one();
_t.join();
}
}
struct TexInfo
{
int size = 0;
int levels = 0;
};
TexInfo parseInfoFile(const string &filename, int maxSize)
{
ifstream in(filename.c_str(), ios::in | ios::binary);
if (!in) return {};
string contents;
in.seekg(0, ios::end);
contents.resize(in.tellg());
in.seekg(0, ios::beg);
in.read(&contents[0], contents.size());
using namespace shaun;
try
{
parser p{};
object obj = p.parse(contents.c_str());
sweeper swp(&obj);
TexInfo info{};
info.size = swp("size").value<number>();
info.levels = swp("levels").value<number>();
if (maxSize)
{
int maxRows = maxSize/(info.size*2);
int maxLevel = (int)floor(log2(maxRows))+1;
info.levels = max(1,min(info.levels, maxLevel));
}
return info;
}
catch (parse_error &e)
{
cout << e << endl;
return {};
}
}
DDSStreamer::Handle DDSStreamer::createTex(const string &filename)
{
// Get info file
TexInfo info = parseInfoFile(filename + "/info.sn", _maxSize);
// Check if file exists or is valid
if (info.levels == 0) return 0;
const string tailFile = "/level0/0_0.DDS";
// Gen texture
const Handle h = genHandle();
GLuint id;
glCreateTextures(GL_TEXTURE_2D, 1, &id);
_texs.insert(make_pair(h, StreamTexture(id)));
// Tail loader
DDSLoader tailLoader = DDSLoader(filename+tailFile);
// Storage
const int width = info.size<<(info.levels-1);
const int height = width/2;
const GLenum format = DDSFormatToGL(tailLoader.getFormat());
glTextureStorage2D(id, mipmapCount(width), format, width, height);
// Gen jobs
vector<LoadInfo> jobs;
// Tail mipmaps (level0)
const int tailMips = mipmapCount(info.size);
for (int i=tailMips-1;i>=0;--i)
{
LoadInfo tailInfo{};
tailInfo.handle = h;
tailInfo.loader = tailLoader;
tailInfo.fileLevel = i;
tailInfo.offsetX = 0;
tailInfo.offsetY = 0;
tailInfo.level = info.levels-1+i;
tailInfo.imageSize = tailLoader.getImageSize(i);
jobs.push_back(tailInfo);
}
for (int i=1;i<info.levels;++i)
{
const string levelFolder = filename + "/level" + to_string(i) + "/";
const int rows = 1<<(i-1);
const int columns = 2*rows;
for (int x=0;x<columns;++x)
{
for (int y=0;y<rows;++y)
{
const string ddsFile = to_string(x)+"_"+to_string(y)+".DDS";
const string fullFilename = levelFolder+ddsFile;
const DDSLoader loader(fullFilename);
const int fileLevel = 0;
const int imageSize = loader.getImageSize(fileLevel);
LoadInfo loadInfo{};
loadInfo.handle = h;
loadInfo.loader = std::move(loader);
loadInfo.fileLevel = fileLevel;
loadInfo.offsetX = x*info.size;
loadInfo.offsetY = y*info.size;
loadInfo.level = info.levels-i-1;
loadInfo.imageSize = imageSize;
jobs.push_back(loadInfo);
}
}
}
_loadInfoWaiting.insert(_loadInfoWaiting.end(), jobs.begin(), jobs.end());
return h;
}
const StreamTexture &DDSStreamer::getTex(Handle handle)
{
if (!handle) return _nullTex;
auto it = _texs.find(handle);
if (it == _texs.end()) return _nullTex;
return _texs[handle];
}
void DDSStreamer::deleteTex(Handle handle)
{
_texDeleted.push_back(handle);
_texs.erase(handle);
}
void DDSStreamer::update()
{
// Invalidate deleted textures from pre-queue
auto isDeleted = [this](const LoadInfo &info)
{
for (Handle h : _texDeleted)
{
if (h == info.handle)
{
if (info.ptrOffset != -1) releasePages(info.ptrOffset, info.imageSize);
return true;
}
}
return false;
};
remove_if(_loadInfoWaiting.begin(), _loadInfoWaiting.end(), isDeleted);
// Assign offsets
std::vector<LoadInfo> assigned;
std::vector<LoadInfo> nonAssigned;
for_each(_loadInfoWaiting.begin(), _loadInfoWaiting.end(),
[&assigned, &nonAssigned, this](const LoadInfo &info) {
int ptrOffset = acquirePages(info.imageSize);
if (ptrOffset == -1)
{
nonAssigned.push_back(info);
}
else
{
LoadInfo s = info;
s.ptrOffset = ptrOffset;
assigned.push_back(s);
}
});
{
lock_guard<mutex> lk(_mtx);
// Invalidate deleted textures from queue
remove_if(_loadInfoQueue.begin(), _loadInfoQueue.end(), isDeleted);
// Submit created textures
_loadInfoQueue.insert(
_loadInfoQueue.end(),
assigned.begin(),
assigned.end());
}
_cond.notify_one();
_loadInfoWaiting = nonAssigned;
_texDeleted.clear();
// Get loaded slices
vector<LoadData> data;
{
lock_guard<mutex> lk(_dataMtx);
data = _loadData;
_loadData.clear();
}
// Update
glBindBuffer(GL_PIXEL_UNPACK_BUFFER, _pbo);
for (LoadData d : data)
{
#ifndef USE_COHERENT_MAPPING
glFlushMappedNamedBufferRange(_pbo, d.ptrOffset, d.imageSize);
#endif
auto it = _texs.find(d.handle);
if (it != _texs.end())
{
glCompressedTextureSubImage2D(it->second.getId(),
d.level,
d.offsetX,
d.offsetY,
d.width,
d.height,
d.format,
d.imageSize,
(void*)(intptr_t)d.ptrOffset);
}
releasePages(d.ptrOffset, d.imageSize);
}
glBindBuffer(GL_PIXEL_UNPACK_BUFFER, 0);
}
int DDSStreamer::acquirePages(int size)
{
const int pages = ((size-1)/_pageSize)+1;
if (pages > _numPages)
{
throw runtime_error("Not enough pages");
}
int start = 0;
for (int i=0;i<_usedPages.size();++i)
{
if (_usedPages[i] || !_pageFences[i].waitClient(1000))
{
start = i+1;
}
else
{
if (i-start+1 == pages)
{
for (int j=start;j<start+pages;++j)
{
_usedPages[j] = true;
}
return start*_pageSize;
}
}
}
return -1;
}
void DDSStreamer::releasePages(int offset, int size)
{
const int pageStart = offset/_pageSize;
const int pages = ((size-1)/_pageSize)+1;
for (int i=pageStart;i<pageStart+pages;++i)
{
_pageFences[i].lock();
_usedPages[i] = false;
}
}
DDSStreamer::LoadData DDSStreamer::load(const LoadInfo &info)
{
LoadData s{};
int level = info.fileLevel;
int ptrOffset = info.ptrOffset;
s.handle = info.handle;
s.level = info.level;
s.offsetX = info.offsetX;
s.offsetY = info.offsetY;
s.width = info.loader.getWidth(level);
s.height = info.loader.getHeight(level);
s.format = DDSFormatToGL(info.loader.getFormat());
s.imageSize = info.imageSize;
s.ptrOffset = ptrOffset;
info.loader.writeImageData(level, (char*)_pboPtr+ptrOffset);
return s;
}
DDSStreamer::Handle DDSStreamer::genHandle()
{
static Handle h=0;
++h;
if (h == 0) ++h;
return h;
}
StreamTexture::StreamTexture(GLuint id) :_id{id}
{
}
StreamTexture::StreamTexture(StreamTexture &&tex) : _id{tex._id}
{
tex._id = 0;
}
StreamTexture &StreamTexture::operator=(StreamTexture &&tex)
{
if (tex._id != _id) glDeleteTextures(1, &_id);
_id = tex._id;
tex._id = 0;
}
StreamTexture::~StreamTexture()
{
if (_id) glDeleteTextures(1, &_id);
}
GLuint StreamTexture::getId(GLuint def) const
{
if (_id) return _id;
return def;
}<commit_msg>More options for stream assets<commit_after>#include "dds_stream.hpp"
#include "gl_util.hpp"
#include "thirdparty/shaun/sweeper.hpp"
#include "thirdparty/shaun/parser.hpp"
#include <iostream>
#include <fstream>
#include <algorithm>
#include <cmath>
using namespace std;
GLenum DDSFormatToGL(DDSLoader::Format format)
{
switch (format)
{
case DDSLoader::Format::BC1: return GL_COMPRESSED_RGBA_S3TC_DXT1_EXT;
case DDSLoader::Format::BC1_SRGB: return GL_COMPRESSED_SRGB_ALPHA_S3TC_DXT1_EXT;
case DDSLoader::Format::BC2: return GL_COMPRESSED_RGBA_S3TC_DXT3_EXT;
case DDSLoader::Format::BC2_SRGB: return GL_COMPRESSED_SRGB_ALPHA_S3TC_DXT3_EXT;
case DDSLoader::Format::BC3: return GL_COMPRESSED_RGBA_S3TC_DXT5_EXT;
case DDSLoader::Format::BC3_SRGB: return GL_COMPRESSED_SRGB_ALPHA_S3TC_DXT5_EXT;
case DDSLoader::Format::BC4: return GL_COMPRESSED_RED_RGTC1;
case DDSLoader::Format::BC4_SIGNED:return GL_COMPRESSED_SIGNED_RED_RGTC1;
case DDSLoader::Format::BC5: return GL_COMPRESSED_RG_RGTC2;
case DDSLoader::Format::BC5_SIGNED:return GL_COMPRESSED_SIGNED_RG_RGTC2;
case DDSLoader::Format::BC6: return GL_COMPRESSED_RGB_BPTC_UNSIGNED_FLOAT;
case DDSLoader::Format::BC6_SIGNED:return GL_COMPRESSED_RGB_BPTC_SIGNED_FLOAT;
case DDSLoader::Format::BC7: return GL_COMPRESSED_RGBA_BPTC_UNORM;
case DDSLoader::Format::BC7_SRGB: return GL_COMPRESSED_SRGB_ALPHA_BPTC_UNORM;
}
return 0;
}
void DDSStreamer::init(int pageSize, int numPages, int maxSize)
{
_maxSize = maxSize;
_pageSize = pageSize;
_numPages = numPages;
int pboSize = pageSize*numPages;
glCreateBuffers(1, &_pbo);
GLbitfield storageFlags = GL_MAP_WRITE_BIT|GL_MAP_PERSISTENT_BIT;
#ifdef USE_COHERENT_MAPPING
storageFlags = storageFlags | GL_MAP_COHERENT_BIT;
#endif
glNamedBufferStorage(_pbo, pboSize, nullptr, storageFlags);
GLbitfield mapFlags = storageFlags;
#ifndef USE_COHERENT_MAPPING
mapFlags = mapFlags | GL_MAP_FLUSH_EXPLICIT_BIT;
#endif
_pboPtr = glMapNamedBufferRange(
_pbo, 0, pboSize, mapFlags);
_usedPages.resize(numPages, false);
_pageFences.resize(numPages);
_t = thread([this]{
while (true)
{
LoadInfo info{};
{
unique_lock<mutex> lk(_mtx);
_cond.wait(lk, [this]{ return _killThread || !_loadInfoQueue.empty();});
if (_killThread) return;
info = _loadInfoQueue[0];
_loadInfoQueue.erase(_loadInfoQueue.begin());
}
LoadData data = load(info);
{
lock_guard<mutex> lk(_dataMtx);
_loadData.push_back(data);
}
}
});
}
DDSStreamer::~DDSStreamer()
{
if (_pbo)
{
glUnmapNamedBuffer(_pbo);
glDeleteBuffers(1, &_pbo);
}
if (_t.joinable())
{
{
lock_guard<mutex> lk(_mtx);
_killThread = true;
}
_cond.notify_one();
_t.join();
}
}
struct TexInfo
{
int size = 0;
int levels = 0;
string prefix = "";
string separator = "";
string suffix = "";
bool rowColumnOrder = false;
};
TexInfo parseInfoFile(const string &filename, int maxSize)
{
ifstream in(filename.c_str(), ios::in | ios::binary);
if (!in) return {};
string contents;
in.seekg(0, ios::end);
contents.resize(in.tellg());
in.seekg(0, ios::beg);
in.read(&contents[0], contents.size());
using namespace shaun;
try
{
parser p{};
object obj = p.parse(contents.c_str());
sweeper swp(&obj);
TexInfo info{};
info.size = swp("size").value<number>();
info.levels = swp("levels").value<number>();
info.prefix = (std::string)swp("prefix").value<shaun::string>();
info.separator = (std::string)swp("separator").value<shaun::string>();
info.suffix = (std::string)swp("suffix").value<shaun::string>();
info.rowColumnOrder = swp("row_column_order").value<shaun::boolean>();
if (maxSize)
{
int maxRows = maxSize/(info.size*2);
int maxLevel = (int)floor(log2(maxRows))+1;
info.levels = max(1,min(info.levels, maxLevel));
}
return info;
}
catch (parse_error &e)
{
cout << e << endl;
return {};
}
}
DDSStreamer::Handle DDSStreamer::createTex(const string &filename)
{
// Get info file
TexInfo info = parseInfoFile(filename + "/info.sn", _maxSize);
// Check if file exists or is valid
if (info.levels == 0) return 0;
const string tailFile = "/level0/0_0.DDS";
// Gen texture
const Handle h = genHandle();
GLuint id;
glCreateTextures(GL_TEXTURE_2D, 1, &id);
_texs.insert(make_pair(h, StreamTexture(id)));
// Tail loader
DDSLoader tailLoader = DDSLoader(filename+tailFile);
// Storage
const int width = info.size<<(info.levels-1);
const int height = width/2;
const GLenum format = DDSFormatToGL(tailLoader.getFormat());
glTextureStorage2D(id, mipmapCount(width), format, width, height);
// Gen jobs
vector<LoadInfo> jobs;
// Tail mipmaps (level0)
const int tailMips = mipmapCount(info.size);
for (int i=tailMips-1;i>=0;--i)
{
LoadInfo tailInfo{};
tailInfo.handle = h;
tailInfo.loader = tailLoader;
tailInfo.fileLevel = i;
tailInfo.offsetX = 0;
tailInfo.offsetY = 0;
tailInfo.level = info.levels-1+i;
tailInfo.imageSize = tailLoader.getImageSize(i);
jobs.push_back(tailInfo);
}
for (int i=1;i<info.levels;++i)
{
const string levelFolder = filename + "/level" + to_string(i) + "/";
const int rows = 1<<(i-1);
const int columns = 2*rows;
for (int x=0;x<columns;++x)
{
for (int y=0;y<rows;++y)
{
const string ddsFile =
info.prefix+
to_string(info.rowColumnOrder?y:x)+
info.separator+
to_string(info.rowColumnOrder?x:y)+
info.suffix;
const string fullFilename = levelFolder+ddsFile;
const DDSLoader loader(fullFilename);
const int fileLevel = 0;
const int imageSize = loader.getImageSize(fileLevel);
LoadInfo loadInfo{};
loadInfo.handle = h;
loadInfo.loader = std::move(loader);
loadInfo.fileLevel = fileLevel;
loadInfo.offsetX = x*info.size;
loadInfo.offsetY = y*info.size;
loadInfo.level = info.levels-i-1;
loadInfo.imageSize = imageSize;
jobs.push_back(loadInfo);
}
}
}
_loadInfoWaiting.insert(_loadInfoWaiting.end(), jobs.begin(), jobs.end());
return h;
}
const StreamTexture &DDSStreamer::getTex(Handle handle)
{
if (!handle) return _nullTex;
auto it = _texs.find(handle);
if (it == _texs.end()) return _nullTex;
return _texs[handle];
}
void DDSStreamer::deleteTex(Handle handle)
{
_texDeleted.push_back(handle);
_texs.erase(handle);
}
void DDSStreamer::update()
{
// Invalidate deleted textures from pre-queue
auto isDeleted = [this](const LoadInfo &info)
{
for (Handle h : _texDeleted)
{
if (h == info.handle)
{
if (info.ptrOffset != -1) releasePages(info.ptrOffset, info.imageSize);
return true;
}
}
return false;
};
remove_if(_loadInfoWaiting.begin(), _loadInfoWaiting.end(), isDeleted);
// Assign offsets
std::vector<LoadInfo> assigned;
std::vector<LoadInfo> nonAssigned;
for_each(_loadInfoWaiting.begin(), _loadInfoWaiting.end(),
[&assigned, &nonAssigned, this](const LoadInfo &info) {
int ptrOffset = acquirePages(info.imageSize);
if (ptrOffset == -1)
{
nonAssigned.push_back(info);
}
else
{
LoadInfo s = info;
s.ptrOffset = ptrOffset;
assigned.push_back(s);
}
});
{
lock_guard<mutex> lk(_mtx);
// Invalidate deleted textures from queue
remove_if(_loadInfoQueue.begin(), _loadInfoQueue.end(), isDeleted);
// Submit created textures
_loadInfoQueue.insert(
_loadInfoQueue.end(),
assigned.begin(),
assigned.end());
}
_cond.notify_one();
_loadInfoWaiting = nonAssigned;
_texDeleted.clear();
// Get loaded slices
vector<LoadData> data;
{
lock_guard<mutex> lk(_dataMtx);
data = _loadData;
_loadData.clear();
}
// Update
glBindBuffer(GL_PIXEL_UNPACK_BUFFER, _pbo);
for (LoadData d : data)
{
#ifndef USE_COHERENT_MAPPING
glFlushMappedNamedBufferRange(_pbo, d.ptrOffset, d.imageSize);
#endif
auto it = _texs.find(d.handle);
if (it != _texs.end())
{
glCompressedTextureSubImage2D(it->second.getId(),
d.level,
d.offsetX,
d.offsetY,
d.width,
d.height,
d.format,
d.imageSize,
(void*)(intptr_t)d.ptrOffset);
}
releasePages(d.ptrOffset, d.imageSize);
}
glBindBuffer(GL_PIXEL_UNPACK_BUFFER, 0);
}
int DDSStreamer::acquirePages(int size)
{
const int pages = ((size-1)/_pageSize)+1;
if (pages > _numPages)
{
throw runtime_error("Not enough pages");
}
int start = 0;
for (int i=0;i<_usedPages.size();++i)
{
if (_usedPages[i] || !_pageFences[i].waitClient(1000))
{
start = i+1;
}
else
{
if (i-start+1 == pages)
{
for (int j=start;j<start+pages;++j)
{
_usedPages[j] = true;
}
return start*_pageSize;
}
}
}
return -1;
}
void DDSStreamer::releasePages(int offset, int size)
{
const int pageStart = offset/_pageSize;
const int pages = ((size-1)/_pageSize)+1;
for (int i=pageStart;i<pageStart+pages;++i)
{
_pageFences[i].lock();
_usedPages[i] = false;
}
}
DDSStreamer::LoadData DDSStreamer::load(const LoadInfo &info)
{
LoadData s{};
int level = info.fileLevel;
int ptrOffset = info.ptrOffset;
s.handle = info.handle;
s.level = info.level;
s.offsetX = info.offsetX;
s.offsetY = info.offsetY;
s.width = info.loader.getWidth(level);
s.height = info.loader.getHeight(level);
s.format = DDSFormatToGL(info.loader.getFormat());
s.imageSize = info.imageSize;
s.ptrOffset = ptrOffset;
info.loader.writeImageData(level, (char*)_pboPtr+ptrOffset);
return s;
}
DDSStreamer::Handle DDSStreamer::genHandle()
{
static Handle h=0;
++h;
if (h == 0) ++h;
return h;
}
StreamTexture::StreamTexture(GLuint id) :_id{id}
{
}
StreamTexture::StreamTexture(StreamTexture &&tex) : _id{tex._id}
{
tex._id = 0;
}
StreamTexture &StreamTexture::operator=(StreamTexture &&tex)
{
if (tex._id != _id) glDeleteTextures(1, &_id);
_id = tex._id;
tex._id = 0;
}
StreamTexture::~StreamTexture()
{
if (_id) glDeleteTextures(1, &_id);
}
GLuint StreamTexture::getId(GLuint def) const
{
if (_id) return _id;
return def;
}<|endoftext|> |
<commit_before>/*
module: terra-incognita
synopsis: ICFP 2006 contest postmission
author: heisenbug
copyright: 2006 terraincognita team
*/
#include <algorithm>
#include <iostream>
// Alternative (PseudoJIT) Universal Machine
typedef void (*Fun)(void);
void Halt(Fun* array0, unsigned (®s)[10])
{
std::cerr << "Halting.\n" << std::endl;
}
typedef typeof(Halt) *Instruct;
#define genC(NAME, A, B) NAME<A, B, 0>, NAME<A, B, 1>, NAME<A, B, 2>, NAME<A, B, 3>, NAME<A, B, 4>, NAME<A, B, 5>, NAME<A, B, 6>, NAME<A, B, 7>
#define genB(NAME, A) genC(NAME, A, 0), genC(NAME, A, 1), genC(NAME, A, 2), genC(NAME, A, 3), genC(NAME, A, 4), genC(NAME, A, 5), genC(NAME, A, 6), genC(NAME, A, 7)
#define genA(NAME) genB(NAME, 0), genB(NAME, 1), genB(NAME, 2), genB(NAME, 3), genB(NAME, 4), genB(NAME, 5), genB(NAME, 6), genB(NAME, 7)
template <int A, int B, int C>
void Cond(Fun* array0, unsigned (®s)[10])
{
if (regs[C])
regs[A] = regs[B];
++array0;
(*reinterpret_cast<Instruct*>(array0))(array0, regs);
}
template <int A, int B, int C>
void Index(Fun* array0, unsigned (®s)[10])
{
const unsigned* arr(reinterpret_cast<unsigned*>(regs[B]));
regs[A] = arr ? arr[regs[C]] : reinterpret_cast<unsigned*>(regs[8])[regs[C]];
++array0;
(*reinterpret_cast<Instruct*>(array0))(array0, regs);
}
template <int A, int B, int C>
void Add(Fun* array0, unsigned (®s)[10])
{
regs[A] = regs[B] + regs[C];
++array0;
(*reinterpret_cast<Instruct*>(array0))(array0, regs);
}
template <int A, int B, int C>
void Mul(Fun* array0, unsigned (®s)[10])
{
regs[A] = regs[B] * regs[C];
++array0;
(*reinterpret_cast<Instruct*>(array0))(array0, regs);
}
template <int A, int B, int C>
void Div(Fun* array0, unsigned (®s)[10])
{
regs[A] = regs[B] / regs[C];
++array0;
(*reinterpret_cast<Instruct*>(array0))(array0, regs);
}
template <int A, int B, int C>
void Nand(Fun* array0, unsigned (®s)[10])
{
regs[A] = ~(regs[B] & regs[C]);
++array0;
(*reinterpret_cast<Instruct*>(array0))(array0, regs);
}
void Compiler(Fun* array0, unsigned (®s)[10])
{
unsigned* v(reinterpret_cast<unsigned*>(regs[8]));
ptrdiff_t offset = array0 - reinterpret_cast<Fun*>(regs[9]);
unsigned platter = v[offset];
std::cerr << std::hex <<"platter: " << platter << std::dec << std::endl;
Instruct compiled;
switch (platter >> 28)
{
case 0:
{
static Instruct const movers[8 * 8 * 8] = { genA(Cond) };
compiled = movers[platter & 0x1FF];
break;
};
case 1:
{
static Instruct const indexers[8 * 8 * 8] = { genA(Index) };
compiled = indexers[platter & 0x1FF];
break;
};
case 3:
{
static Instruct const adders[8 * 8 * 8] = { genA(Add) };
compiled = adders[platter & 0x1FF];
break;
};
case 4:
{
static Instruct const multipliers[8 * 8 * 8] = { genA(Mul) };
compiled = multipliers[platter & 0x1FF];
break;
};
case 5:
{
static Instruct const dividers[8 * 8 * 8] = { genA(Div) };
compiled = dividers[platter & 0x1FF];
break;
};
case 6:
{
static Instruct const nanders[8 * 8 * 8] = { genA(Nand) };
compiled = nanders[platter & 0x1FF];
break;
};
case 7:
compiled = Halt;
break;
};
array0[0] = reinterpret_cast<Fun>(compiled);
compiled(array0, regs);
}
struct d2cObject
{
const d2cObject& d2cClass;
private: d2cObject(void); // no impl.
};
struct d2cCell : d2cObject
{
unsigned data;
};
struct DylanVector : d2cObject
{
size_t size;
d2cCell arr[];
};
Fun fillWithCompiler(const d2cCell&)
{
std::cerr << "fillWithCompiler." << std::endl;
return reinterpret_cast<Fun>(Compiler);
}
unsigned justCopy(const d2cCell& c)
{
std::cerr << "justCopy." << std::endl;
return c.data;
}
extern "C" void* enterUM(void* dylancookie, const struct DylanVector& v)
{
unsigned* copy = new unsigned[v.size];
std::transform(v.arr, v.arr + v.size, copy, justCopy);
Fun* jitted = new Fun[v.size];
std::transform(v.arr, v.arr + v.size, jitted, fillWithCompiler);
unsigned regs[10] = { 0, 0, 0, 0, 0, 0, 0, 0, unsigned(copy), unsigned(jitted)};
reinterpret_cast<Instruct>(*jitted)(jitted, regs);
return dylancookie;
}
int main(void)
{
std::cerr << "main." << std::endl;
DylanVector& v(*(DylanVector*)new char[100]);
v.size = 2;
v.arr[0].data = (3 << 28) | (5 << 6) | (3 << 3) | 1; // Add: A = 5, B = 3, C = 1
v.arr[1].data = 7 << 28; // Halt
enterUM(NULL, v);
}
<commit_msg>allocate and abandon<commit_after>/*
module: terra-incognita
synopsis: ICFP 2006 contest postmission
author: heisenbug
copyright: 2006 terraincognita team
*/
#include <algorithm>
#include <iostream>
// Alternative (PseudoJIT) Universal Machine
typedef void (*Fun)(void);
void Halt(Fun* array0, unsigned (®s)[10])
{
std::cerr << "Halting." << std::endl;
}
typedef typeof(Halt) *Instruct;
#define genC(NAME, A, B) NAME<A, B, 0>, NAME<A, B, 1>, NAME<A, B, 2>, NAME<A, B, 3>, NAME<A, B, 4>, NAME<A, B, 5>, NAME<A, B, 6>, NAME<A, B, 7>
#define genB(NAME, A) genC(NAME, A, 0), genC(NAME, A, 1), genC(NAME, A, 2), genC(NAME, A, 3), genC(NAME, A, 4), genC(NAME, A, 5), genC(NAME, A, 6), genC(NAME, A, 7)
#define genA(NAME) genB(NAME, 0), genB(NAME, 1), genB(NAME, 2), genB(NAME, 3), genB(NAME, 4), genB(NAME, 5), genB(NAME, 6), genB(NAME, 7)
inline static unsigned getOrig(Fun* array0, unsigned (®s)[10])
{
unsigned* v(reinterpret_cast<unsigned*>(regs[8]));
ptrdiff_t offset = array0 - reinterpret_cast<Fun*>(regs[9]);
return v[offset];
}
template <int, int B, int C>
void Alloc(Fun* array0, unsigned (®s)[10])
{
// const size_t need(getOrig(array0, regs));
enum { mask = (1 << 25) - 1 };
const size_t need(regs[C] & mask);
std::cerr << "Allocating. " << need << " [" << B << "] " << " = alloc[" << C << "] " << std::endl;
regs[B] = reinterpret_cast<unsigned>(new unsigned[need]);
++array0;
(*reinterpret_cast<Instruct*>(array0))(array0, regs);
}
template <int, int, int C>
void Abandon(Fun* array0, unsigned (®s)[10])
{
std::cerr << "Abandoning. " << " [" << C << "] " << std::endl;
delete reinterpret_cast<unsigned*>(regs[C]);
++array0;
(*reinterpret_cast<Instruct*>(array0))(array0, regs);
}
template <int A, int B, int C>
void Cond(Fun* array0, unsigned (®s)[10])
{
if (regs[C])
regs[A] = regs[B];
++array0;
(*reinterpret_cast<Instruct*>(array0))(array0, regs);
}
template <int, int, int A>
void Ortho(Fun* array0, unsigned (®s)[10])
{
regs[A] = getOrig(array0, regs);
++array0;
(*reinterpret_cast<Instruct*>(array0))(array0, regs);
}
template <int A, int B, int C>
void Index(Fun* array0, unsigned (®s)[10])
{
const unsigned* arr(reinterpret_cast<unsigned*>(regs[B]));
regs[A] = arr ? arr[regs[C]] : reinterpret_cast<unsigned*>(regs[8])[regs[C]];
++array0;
(*reinterpret_cast<Instruct*>(array0))(array0, regs);
}
template <int A, int B, int C>
void Add(Fun* array0, unsigned (®s)[10])
{
regs[A] = regs[B] + regs[C];
++array0;
(*reinterpret_cast<Instruct*>(array0))(array0, regs);
}
template <int A, int B, int C>
void Mul(Fun* array0, unsigned (®s)[10])
{
regs[A] = regs[B] * regs[C];
++array0;
(*reinterpret_cast<Instruct*>(array0))(array0, regs);
}
template <int A, int B, int C>
void Div(Fun* array0, unsigned (®s)[10])
{
regs[A] = regs[B] / regs[C];
++array0;
(*reinterpret_cast<Instruct*>(array0))(array0, regs);
}
template <int A, int B, int C>
void Nand(Fun* array0, unsigned (®s)[10])
{
regs[A] = ~(regs[B] & regs[C]);
++array0;
(*reinterpret_cast<Instruct*>(array0))(array0, regs);
}
void Compiler(Fun* array0, unsigned (®s)[10])
{
unsigned* v(reinterpret_cast<unsigned*>(regs[8]));
ptrdiff_t offset = array0 - reinterpret_cast<Fun*>(regs[9]);
unsigned platter = v[offset];
std::cerr << std::hex <<"platter: " << platter << std::dec << std::endl;
Instruct compiled;
switch (platter >> 28)
{
case 0:
{
static Instruct const movers[8 * 8 * 8] = { genA(Cond) };
compiled = movers[platter & 0x1FF];
break;
};
case 1:
{
static Instruct const indexers[8 * 8 * 8] = { genA(Index) };
compiled = indexers[platter & 0x1FF];
break;
};
case 3:
{
static Instruct const adders[8 * 8 * 8] = { genA(Add) };
compiled = adders[platter & 0x1FF];
break;
};
case 4:
{
static Instruct const multipliers[8 * 8 * 8] = { genA(Mul) };
compiled = multipliers[platter & 0x1FF];
break;
};
case 5:
{
static Instruct const dividers[8 * 8 * 8] = { genA(Div) };
compiled = dividers[platter & 0x1FF];
break;
};
case 6:
{
static Instruct const nanders[8 * 8 * 8] = { genA(Nand) };
compiled = nanders[platter & 0x1FF];
break;
};
case 7:
compiled = Halt;
break;
case 8:
{
static Instruct const allocers[8 * 8] = { genB(Alloc, 0) };
compiled = allocers[platter & 0x3F];
break;
}
case 9:
{
static Instruct const abandoners[8] = { genC(Abandon, 0, 0) };
compiled = abandoners[platter & 0x7];
break;
}
case 13:
{
static Instruct const orthographers[8] = { genC(Ortho, 0, 0) };
compiled = orthographers[(platter >> 25) & 0x7];
break;
}
};
array0[0] = reinterpret_cast<Fun>(compiled);
compiled(array0, regs);
}
struct d2cObject
{
const d2cObject& d2cClass;
private: d2cObject(void); // no impl.
};
struct d2cCell : d2cObject
{
unsigned data;
};
struct DylanVector : d2cObject
{
size_t size;
d2cCell arr[];
};
Fun fillWithCompiler(const d2cCell&)
{
std::cerr << "fillWithCompiler." << std::endl;
return reinterpret_cast<Fun>(Compiler);
}
unsigned justCopy(const d2cCell& c)
{
std::cerr << "justCopy." << std::endl;
return c.data;
}
extern "C" void* enterUM(void* dylancookie, const struct DylanVector& v)
{
unsigned* copy = new unsigned[v.size];
std::transform(v.arr, v.arr + v.size, copy, justCopy);
Fun* jitted = new Fun[v.size];
std::transform(v.arr, v.arr + v.size, jitted, fillWithCompiler);
unsigned regs[10] = { 0, 0, 0, 0, 0, 0, 0, 0, unsigned(copy), unsigned(jitted)};
reinterpret_cast<Instruct>(*jitted)(jitted, regs);
return dylancookie;
}
int main(void)
{
std::cerr << "main." << std::endl;
DylanVector& v(*(DylanVector*)new char[100]);
v.size = 4;
v.arr[0].data = (13 << 28) | (1 << 25) | 42; // Ortho: A = 1, val 41
v.arr[1].data = (3 << 28) | (5 << 6) | (3 << 3) | 1; // Add: A = 5, B = 3, C = 1
v.arr[2].data = (8 << 28) | (7 << 3) | 1; // Alloc: B = 7, C = 1
v.arr[3].data = 7 << 28; // Halt
enterUM(NULL, v);
}
<|endoftext|> |
<commit_before>/*
*
* D-Bus++ - C++ bindings for D-Bus
*
* Copyright (C) 2005-2007 Paolo Durante <shackan@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., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
*
*/
#ifdef HAVE_CONFIG_H
#include <config.h>
#endif
#include <dbus-c++/dispatcher.h>
#include <dbus/dbus.h>
#include "dispatcher_p.h"
#include "server_p.h"
#include "connection_p.h"
DBus::Dispatcher *DBus::default_dispatcher = NULL;
using namespace DBus;
Timeout::Timeout(Timeout::Internal *i)
: _int(i)
{
dbus_timeout_set_data((DBusTimeout *)i, this, NULL);
}
int Timeout::interval() const
{
return dbus_timeout_get_interval((DBusTimeout *)_int);
}
bool Timeout::enabled() const
{
return dbus_timeout_get_enabled((DBusTimeout *)_int);
}
bool Timeout::handle()
{
return dbus_timeout_handle((DBusTimeout *)_int);
}
/*
*/
Watch::Watch(Watch::Internal *i)
: _int(i)
{
dbus_watch_set_data((DBusWatch *)i, this, NULL);
}
int Watch::descriptor() const
{
#if HAVE_WIN32
return dbus_watch_get_socket((DBusWatch*)_int);
#else
return dbus_watch_get_unix_fd((DBusWatch*)_int);
#endif
}
int Watch::flags() const
{
return dbus_watch_get_flags((DBusWatch *)_int);
}
bool Watch::enabled() const
{
return dbus_watch_get_enabled((DBusWatch *)_int);
}
bool Watch::handle(int flags)
{
return dbus_watch_handle((DBusWatch *)_int, flags);
}
/*
*/
dbus_bool_t Dispatcher::Private::on_add_watch(DBusWatch *watch, void *data)
{
Dispatcher *d = static_cast<Dispatcher *>(data);
Watch::Internal *w = reinterpret_cast<Watch::Internal *>(watch);
d->add_watch(w);
return true;
}
void Dispatcher::Private::on_rem_watch(DBusWatch *watch, void *data)
{
Dispatcher *d = static_cast<Dispatcher *>(data);
Watch *w = static_cast<Watch *>(dbus_watch_get_data(watch));
d->rem_watch(w);
}
void Dispatcher::Private::on_toggle_watch(DBusWatch *watch, void *data)
{
Watch *w = static_cast<Watch *>(dbus_watch_get_data(watch));
w->toggle();
}
dbus_bool_t Dispatcher::Private::on_add_timeout(DBusTimeout *timeout, void *data)
{
Dispatcher *d = static_cast<Dispatcher *>(data);
Timeout::Internal *t = reinterpret_cast<Timeout::Internal *>(timeout);
d->add_timeout(t);
return true;
}
void Dispatcher::Private::on_rem_timeout(DBusTimeout *timeout, void *data)
{
Dispatcher *d = static_cast<Dispatcher *>(data);
Timeout *t = static_cast<Timeout *>(dbus_timeout_get_data(timeout));
d->rem_timeout(t);
}
void Dispatcher::Private::on_toggle_timeout(DBusTimeout *timeout, void *data)
{
Timeout *t = static_cast<Timeout *>(dbus_timeout_get_data(timeout));
t->toggle();
}
void Dispatcher::queue_connection(Connection::Private *cp)
{
_mutex_p.lock();
_pending_queue.push_back(cp);
_mutex_p.unlock();
}
bool Dispatcher::has_something_to_dispatch()
{
_mutex_p.lock();
bool has_something = false;
for(Connection::PrivatePList::iterator it = _pending_queue.begin();
it != _pending_queue.end() && !has_something;
++it)
{
has_something = (*it)->has_something_to_dispatch();
}
_mutex_p.unlock();
return has_something;
}
void Dispatcher::dispatch_pending()
{
while (1)
{
_mutex_p.lock();
bool queue_empty = _pending_queue.size() <= 0;
_mutex_p.unlock();
if ( queue_empty ) return;
Connection::Private *entry = NULL;
_mutex_p.lock();
Connection::PrivatePList::iterator i = _pending_queue.begin();
if (i != _pending_queue.end())
{
entry = *i;
_pending_queue.erase(i);
}
_mutex_p.unlock();
if ( entry == NULL ) return;
if ( entry->do_dispatch() ) // there is no more data
{
// delete entry;
// A leak???
return;
}
// There is more data - queue connection again
queue_connection( entry );
}
}
void DBus::_init_threading()
{
#ifdef DBUS_HAS_THREADS_INIT_DEFAULT
dbus_threads_init_default();
#else
debug_log("Thread support is not enabled! Your D-Bus version is too old!");
#endif//DBUS_HAS_THREADS_INIT_DEFAULT
}
void DBus::_init_threading(
MutexNewFn m1,
MutexFreeFn m2,
MutexLockFn m3,
MutexUnlockFn m4,
CondVarNewFn c1,
CondVarFreeFn c2,
CondVarWaitFn c3,
CondVarWaitTimeoutFn c4,
CondVarWakeOneFn c5,
CondVarWakeAllFn c6
)
{
#ifndef DBUS_HAS_RECURSIVE_MUTEX
DBusThreadFunctions functions = {
DBUS_THREAD_FUNCTIONS_MUTEX_NEW_MASK |
DBUS_THREAD_FUNCTIONS_MUTEX_FREE_MASK |
DBUS_THREAD_FUNCTIONS_MUTEX_LOCK_MASK |
DBUS_THREAD_FUNCTIONS_MUTEX_UNLOCK_MASK |
DBUS_THREAD_FUNCTIONS_CONDVAR_NEW_MASK |
DBUS_THREAD_FUNCTIONS_CONDVAR_FREE_MASK |
DBUS_THREAD_FUNCTIONS_CONDVAR_WAIT_MASK |
DBUS_THREAD_FUNCTIONS_CONDVAR_WAIT_TIMEOUT_MASK |
DBUS_THREAD_FUNCTIONS_CONDVAR_WAKE_ONE_MASK|
DBUS_THREAD_FUNCTIONS_CONDVAR_WAKE_ALL_MASK,
(DBusMutexNewFunction) m1,
(DBusMutexFreeFunction) m2,
(DBusMutexLockFunction) m3,
(DBusMutexUnlockFunction) m4,
(DBusCondVarNewFunction) c1,
(DBusCondVarFreeFunction) c2,
(DBusCondVarWaitFunction) c3,
(DBusCondVarWaitTimeoutFunction) c4,
(DBusCondVarWakeOneFunction) c5,
(DBusCondVarWakeAllFunction) c6
};
#else
DBusThreadFunctions functions = {
DBUS_THREAD_FUNCTIONS_RECURSIVE_MUTEX_NEW_MASK |
DBUS_THREAD_FUNCTIONS_RECURSIVE_MUTEX_FREE_MASK |
DBUS_THREAD_FUNCTIONS_RECURSIVE_MUTEX_LOCK_MASK |
DBUS_THREAD_FUNCTIONS_RECURSIVE_MUTEX_UNLOCK_MASK |
DBUS_THREAD_FUNCTIONS_CONDVAR_NEW_MASK |
DBUS_THREAD_FUNCTIONS_CONDVAR_FREE_MASK |
DBUS_THREAD_FUNCTIONS_CONDVAR_WAIT_MASK |
DBUS_THREAD_FUNCTIONS_CONDVAR_WAIT_TIMEOUT_MASK |
DBUS_THREAD_FUNCTIONS_CONDVAR_WAKE_ONE_MASK|
DBUS_THREAD_FUNCTIONS_CONDVAR_WAKE_ALL_MASK,
0, 0, 0, 0,
(DBusCondVarNewFunction) c1,
(DBusCondVarFreeFunction) c2,
(DBusCondVarWaitFunction) c3,
(DBusCondVarWaitTimeoutFunction) c4,
(DBusCondVarWakeOneFunction) c5,
(DBusCondVarWakeAllFunction) c6,
(DBusRecursiveMutexNewFunction) m1,
(DBusRecursiveMutexFreeFunction) m2,
(DBusRecursiveMutexLockFunction) m3,
(DBusRecursiveMutexUnlockFunction) m4
};
#endif//DBUS_HAS_RECURSIVE_MUTEX
dbus_threads_init(&functions);
}
<commit_msg>update to dispatcher deadlock fix<commit_after>/*
*
* D-Bus++ - C++ bindings for D-Bus
*
* Copyright (C) 2005-2007 Paolo Durante <shackan@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., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
*
*/
#ifdef HAVE_CONFIG_H
#include <config.h>
#endif
#include <dbus-c++/dispatcher.h>
#include <dbus/dbus.h>
#include "dispatcher_p.h"
#include "server_p.h"
#include "connection_p.h"
DBus::Dispatcher *DBus::default_dispatcher = NULL;
using namespace DBus;
Timeout::Timeout(Timeout::Internal *i)
: _int(i)
{
dbus_timeout_set_data((DBusTimeout *)i, this, NULL);
}
int Timeout::interval() const
{
return dbus_timeout_get_interval((DBusTimeout *)_int);
}
bool Timeout::enabled() const
{
return dbus_timeout_get_enabled((DBusTimeout *)_int);
}
bool Timeout::handle()
{
return dbus_timeout_handle((DBusTimeout *)_int);
}
/*
*/
Watch::Watch(Watch::Internal *i)
: _int(i)
{
dbus_watch_set_data((DBusWatch *)i, this, NULL);
}
int Watch::descriptor() const
{
#if HAVE_WIN32
return dbus_watch_get_socket((DBusWatch*)_int);
#else
return dbus_watch_get_unix_fd((DBusWatch*)_int);
#endif
}
int Watch::flags() const
{
return dbus_watch_get_flags((DBusWatch *)_int);
}
bool Watch::enabled() const
{
return dbus_watch_get_enabled((DBusWatch *)_int);
}
bool Watch::handle(int flags)
{
return dbus_watch_handle((DBusWatch *)_int, flags);
}
/*
*/
dbus_bool_t Dispatcher::Private::on_add_watch(DBusWatch *watch, void *data)
{
Dispatcher *d = static_cast<Dispatcher *>(data);
Watch::Internal *w = reinterpret_cast<Watch::Internal *>(watch);
d->add_watch(w);
return true;
}
void Dispatcher::Private::on_rem_watch(DBusWatch *watch, void *data)
{
Dispatcher *d = static_cast<Dispatcher *>(data);
Watch *w = static_cast<Watch *>(dbus_watch_get_data(watch));
d->rem_watch(w);
}
void Dispatcher::Private::on_toggle_watch(DBusWatch *watch, void *data)
{
Watch *w = static_cast<Watch *>(dbus_watch_get_data(watch));
w->toggle();
}
dbus_bool_t Dispatcher::Private::on_add_timeout(DBusTimeout *timeout, void *data)
{
Dispatcher *d = static_cast<Dispatcher *>(data);
Timeout::Internal *t = reinterpret_cast<Timeout::Internal *>(timeout);
d->add_timeout(t);
return true;
}
void Dispatcher::Private::on_rem_timeout(DBusTimeout *timeout, void *data)
{
Dispatcher *d = static_cast<Dispatcher *>(data);
Timeout *t = static_cast<Timeout *>(dbus_timeout_get_data(timeout));
d->rem_timeout(t);
}
void Dispatcher::Private::on_toggle_timeout(DBusTimeout *timeout, void *data)
{
Timeout *t = static_cast<Timeout *>(dbus_timeout_get_data(timeout));
t->toggle();
}
void Dispatcher::queue_connection(Connection::Private *cp)
{
_mutex_p.lock();
_pending_queue.push_back(cp);
_mutex_p.unlock();
}
bool Dispatcher::has_something_to_dispatch()
{
_mutex_p.lock();
bool has_something = false;
for(Connection::PrivatePList::iterator it = _pending_queue.begin();
it != _pending_queue.end() && !has_something;
++it)
{
has_something = (*it)->has_something_to_dispatch();
}
_mutex_p.unlock();
return has_something;
}
void Dispatcher::dispatch_pending()
{
while (1)
{
_mutex_p.lock();
bool queue_empty = _pending_queue.size() <= 0;
_mutex_p.unlock();
if ( queue_empty ) return;
Connection::PrivatePList q;
_mutex_p.lock();
q = _pending_queue;
_pending_queue.clear();
_mutex_p.unlock();
Connection::PrivatePList::iterator i;
for ( i = q.begin() ; i != q.end() ; ++i )
{
Connection::Private *entry = *i;
if ( entry->do_dispatch() ) // there is no more data
{
continue;
}
queue_connection( entry );
}
}
}
void DBus::_init_threading()
{
#ifdef DBUS_HAS_THREADS_INIT_DEFAULT
dbus_threads_init_default();
#else
debug_log("Thread support is not enabled! Your D-Bus version is too old!");
#endif//DBUS_HAS_THREADS_INIT_DEFAULT
}
void DBus::_init_threading(
MutexNewFn m1,
MutexFreeFn m2,
MutexLockFn m3,
MutexUnlockFn m4,
CondVarNewFn c1,
CondVarFreeFn c2,
CondVarWaitFn c3,
CondVarWaitTimeoutFn c4,
CondVarWakeOneFn c5,
CondVarWakeAllFn c6
)
{
#ifndef DBUS_HAS_RECURSIVE_MUTEX
DBusThreadFunctions functions = {
DBUS_THREAD_FUNCTIONS_MUTEX_NEW_MASK |
DBUS_THREAD_FUNCTIONS_MUTEX_FREE_MASK |
DBUS_THREAD_FUNCTIONS_MUTEX_LOCK_MASK |
DBUS_THREAD_FUNCTIONS_MUTEX_UNLOCK_MASK |
DBUS_THREAD_FUNCTIONS_CONDVAR_NEW_MASK |
DBUS_THREAD_FUNCTIONS_CONDVAR_FREE_MASK |
DBUS_THREAD_FUNCTIONS_CONDVAR_WAIT_MASK |
DBUS_THREAD_FUNCTIONS_CONDVAR_WAIT_TIMEOUT_MASK |
DBUS_THREAD_FUNCTIONS_CONDVAR_WAKE_ONE_MASK|
DBUS_THREAD_FUNCTIONS_CONDVAR_WAKE_ALL_MASK,
(DBusMutexNewFunction) m1,
(DBusMutexFreeFunction) m2,
(DBusMutexLockFunction) m3,
(DBusMutexUnlockFunction) m4,
(DBusCondVarNewFunction) c1,
(DBusCondVarFreeFunction) c2,
(DBusCondVarWaitFunction) c3,
(DBusCondVarWaitTimeoutFunction) c4,
(DBusCondVarWakeOneFunction) c5,
(DBusCondVarWakeAllFunction) c6
};
#else
DBusThreadFunctions functions = {
DBUS_THREAD_FUNCTIONS_RECURSIVE_MUTEX_NEW_MASK |
DBUS_THREAD_FUNCTIONS_RECURSIVE_MUTEX_FREE_MASK |
DBUS_THREAD_FUNCTIONS_RECURSIVE_MUTEX_LOCK_MASK |
DBUS_THREAD_FUNCTIONS_RECURSIVE_MUTEX_UNLOCK_MASK |
DBUS_THREAD_FUNCTIONS_CONDVAR_NEW_MASK |
DBUS_THREAD_FUNCTIONS_CONDVAR_FREE_MASK |
DBUS_THREAD_FUNCTIONS_CONDVAR_WAIT_MASK |
DBUS_THREAD_FUNCTIONS_CONDVAR_WAIT_TIMEOUT_MASK |
DBUS_THREAD_FUNCTIONS_CONDVAR_WAKE_ONE_MASK|
DBUS_THREAD_FUNCTIONS_CONDVAR_WAKE_ALL_MASK,
0, 0, 0, 0,
(DBusCondVarNewFunction) c1,
(DBusCondVarFreeFunction) c2,
(DBusCondVarWaitFunction) c3,
(DBusCondVarWaitTimeoutFunction) c4,
(DBusCondVarWakeOneFunction) c5,
(DBusCondVarWakeAllFunction) c6,
(DBusRecursiveMutexNewFunction) m1,
(DBusRecursiveMutexFreeFunction) m2,
(DBusRecursiveMutexLockFunction) m3,
(DBusRecursiveMutexUnlockFunction) m4
};
#endif//DBUS_HAS_RECURSIVE_MUTEX
dbus_threads_init(&functions);
}
<|endoftext|> |
<commit_before>#include "controls.h"
#include <unordered_map>
namespace controls {
std::unordered_map<util::Direction, std::vector<sf::Keyboard::Key>>
directionKeys;
std::vector<sf::Keyboard::Key> jumpKeys;
void init() {
directionKeys[util::Direction::UP].push_back(sf::Keyboard::Up);
directionKeys[util::Direction::UP].push_back(sf::Keyboard::W);
directionKeys[util::Direction::DOWN].push_back(sf::Keyboard::Down);
directionKeys[util::Direction::DOWN].push_back(sf::Keyboard::S);
directionKeys[util::Direction::LEFT].push_back(sf::Keyboard::Left);
directionKeys[util::Direction::LEFT].push_back(sf::Keyboard::A);
directionKeys[util::Direction::RIGHT].push_back(sf::Keyboard::Right);
directionKeys[util::Direction::RIGHT].push_back(sf::Keyboard::D);
jumpKeys.push_back(sf::Keyboard::Up);
jumpKeys.push_back(sf::Keyboard::W);
jumpKeys.push_back(sf::Keyboard::Space);
}
void setDirectionKeys(const util::Direction direction,
const std::vector<sf::Keyboard::Key>& keys) {
directionKeys[direction].clear();
directionKeys[direction] = keys;
}
bool anyKeyPressed(const std::vector<sf::Keyboard::Key>& keys) {
for (const auto& key : keys) {
if (sf::Keyboard::isKeyPressed(key)) {
return true;
}
}
return false;
}
bool directionPressed(util::Direction direction) {
return anyKeyPressed(directionKeys[direction]);
}
bool jumpPressed() { return anyKeyPressed(jumpKeys); }
} // namespace controls
<commit_msg>Don't be dumb with vectors<commit_after>#include "controls.h"
#include <unordered_map>
namespace controls {
std::unordered_map<util::Direction, std::vector<sf::Keyboard::Key>>
directionKeys;
std::vector<sf::Keyboard::Key> jumpKeys;
void init() {
directionKeys[util::Direction::UP] = {sf::Keyboard::Up, sf::Keyboard::W};
directionKeys[util::Direction::DOWN] = {sf::Keyboard::Down, sf::Keyboard::S};
directionKeys[util::Direction::LEFT] = {sf::Keyboard::Left, sf::Keyboard::A};
directionKeys[util::Direction::RIGHT] = {sf::Keyboard::Right,
sf::Keyboard::D};
jumpKeys.push_back(sf::Keyboard::Up);
jumpKeys.push_back(sf::Keyboard::W);
jumpKeys.push_back(sf::Keyboard::Space);
}
void setDirectionKeys(const util::Direction direction,
const std::vector<sf::Keyboard::Key>& keys) {
directionKeys[direction].clear();
directionKeys[direction] = keys;
}
bool anyKeyPressed(const std::vector<sf::Keyboard::Key>& keys) {
for (const auto& key : keys) {
if (sf::Keyboard::isKeyPressed(key)) {
return true;
}
}
return false;
}
bool directionPressed(util::Direction direction) {
return anyKeyPressed(directionKeys[direction]);
}
bool jumpPressed() { return anyKeyPressed(jumpKeys); }
} // namespace controls
<|endoftext|> |
<commit_before><commit_msg>removed unecessary comments<commit_after><|endoftext|> |
<commit_before>#include "utilities.h"
//------------------------------
//getbit
//------------------------------
boolean getbit(byte x, int n) {
return (x >> n) & 1;
}
boolean getbit(word x, int n) {
return (x >> n) & 1;
}
boolean getbit(dword x, int n) {
return (x >> n) & 1;
}
//------------------------------
//setbit
//------------------------------
byte setbit(byte x, int n, boolean b) {
return x ^ (-b ^ n) & (1 << n);
}
word setbit(word x, int n, boolean b) {
return x ^ (-b ^ n) & (1 << n);
}
dword setbit(dword x, int n, boolean b) {
return x ^ (-b ^ n) & (1 << n);
}
//==============================
// Signalgeneration
//==============================
//------------------------------
// Blink
//------------------------------
Blink::Blink() {
t0 = 0;
enable = false;
last_enable = false;
out = false;
timelow = 0;
timehigh = 0;
}
Blink::Blink(long timelow, long timehigh) {
t0 = 0;
enable = false;
last_enable = false;
out = false;
this->timelow = timelow;
this->timehigh = timehigh;
}
boolean Blink::process() {
if (enable) {
ulong t = millis();
if (enable &! last_enable) {
t0 = t;
}
if (t <= (t0 + timehigh)) {
out = true;
}
else if (t <= (t0 + timehigh + timelow)) {
out = false;
}
else
t0 = t;
}
else
out = false;
last_enable = enable;
return out;
}
boolean Blink::process(boolean enable) {
this->enable = enable;
return this->process();
}
<commit_msg>Changed behaviour for timhigh==0 or timelow==0<commit_after>#include "utilities.h"
//------------------------------
//getbit
//------------------------------
boolean getbit(byte x, int n) {
return (x >> n) & 1;
}
boolean getbit(word x, int n) {
return (x >> n) & 1;
}
boolean getbit(dword x, int n) {
return (x >> n) & 1;
}
//------------------------------
//setbit
//------------------------------
byte setbit(byte x, int n, boolean b) {
return x ^ (-b ^ n) & (1 << n);
}
word setbit(word x, int n, boolean b) {
return x ^ (-b ^ n) & (1 << n);
}
dword setbit(dword x, int n, boolean b) {
return x ^ (-b ^ n) & (1 << n);
}
//==============================
// Signalgeneration
//==============================
//------------------------------
// Blink
//------------------------------
Blink::Blink() {
t0 = 0;
enable = false;
last_enable = false;
out = false;
timelow = 0;
timehigh = 0;
}
Blink::Blink(long timelow, long timehigh) {
t0 = 0;
enable = false;
last_enable = false;
out = false;
this->timelow = timelow;
this->timehigh = timehigh;
}
boolean Blink::process() {
if (enable) {
//current time and starttime
ulong t = millis();
if (enable &! last_enable) t0 = t;
if (t <= (t0 + timehigh)) {
out = true;
}
else if (t <= (t0 + timehigh + timelow)) {
out = false;
}
else
t0 = t;
//if timehigh or timelow == 0 set out to false or true
if (timehigh == 0)
out = false;
else if (timelow == 0)
out = true;
}
else
out = false;
last_enable = enable;
return out;
}
boolean Blink::process(boolean enable) {
this->enable = enable;
return this->process();
}
<|endoftext|> |
<commit_before>/******************************************************************************
* This file is part of the Gluon Development Platform
* Copyright (c) 2010 Arjen Hiemstra <ahiemstra@heimr.nl>
*
* 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 Street, Fifth Floor, Boston, MA 02110-1301 USA
*/
#include "textureasset.h"
#include <QtCore/QUrl>
#include <QtCore/QMimeData>
#include <QtGui/QImage>
#include <QtGui/QImageReader>
#include <core/debughelper.h>
#include <graphics/texture.h>
#include <graphics/engine.h>
REGISTER_OBJECTTYPE(GluonEngine, TextureAsset)
using namespace GluonEngine;
class TextureAsset::TextureAssetPrivate
{
public:
TextureAssetPrivate()
{
}
~TextureAssetPrivate()
{
}
QPixmap icon;
GluonGraphics::Texture* texture;
};
TextureAsset::TextureAsset(QObject *parent)
: Asset(parent)
, d(new TextureAssetPrivate)
{
d->texture = GluonGraphics::Engine::instance()->createTexture(name());
}
TextureAsset::~TextureAsset()
{
GluonGraphics::Engine::instance()->destroyTexture(name());
}
QIcon TextureAsset::icon() const
{
if(d->icon.isNull())
return GluonEngine::Asset::icon();
return QIcon(d->icon);
}
const QStringList TextureAsset::supportedMimeTypes() const
{
QList<QByteArray> supported = QImageReader::supportedImageFormats();
QStringList supportedTypes;
foreach(const QByteArray &type, supported)
{
supportedTypes << QString("image/%1").arg(QString(type));
}
return supportedTypes;
}
void TextureAsset::load()
{
if (!file().isEmpty())
{
if (d->texture->load(file()))
{
mimeData()->setText(name());
//d->icon = QPixmap::fromImage(d->texture->scaled(QSize(128, 128), Qt::KeepAspectRatio));
setLoaded(true);
return;
}
}
debug("Error loading texture: %1", name());
}
void TextureAsset::setName( const QString& newName )
{
GluonGraphics::Engine::instance()->removeTexture(name());
GluonGraphics::Engine::instance()->addTexture(newName, d->texture);
GluonEngine::Asset::setName( newName );
}
Q_EXPORT_PLUGIN2(gluon_asset_texture, GluonEngine::TextureAsset)
#include "textureasset.moc"
<commit_msg>Do not destroy the texture upon deletion of the asset. Somehow that causes crashes later in the process.<commit_after>/******************************************************************************
* This file is part of the Gluon Development Platform
* Copyright (c) 2010 Arjen Hiemstra <ahiemstra@heimr.nl>
*
* 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 Street, Fifth Floor, Boston, MA 02110-1301 USA
*/
#include "textureasset.h"
#include <QtCore/QUrl>
#include <QtCore/QMimeData>
#include <QtGui/QImage>
#include <QtGui/QImageReader>
#include <core/debughelper.h>
#include <graphics/texture.h>
#include <graphics/engine.h>
REGISTER_OBJECTTYPE(GluonEngine, TextureAsset)
using namespace GluonEngine;
class TextureAsset::TextureAssetPrivate
{
public:
TextureAssetPrivate()
{
}
~TextureAssetPrivate()
{
}
QPixmap icon;
GluonGraphics::Texture* texture;
};
TextureAsset::TextureAsset(QObject *parent)
: Asset(parent)
, d(new TextureAssetPrivate)
{
d->texture = GluonGraphics::Engine::instance()->createTexture(name());
}
TextureAsset::~TextureAsset()
{
d->texture = 0;
}
QIcon TextureAsset::icon() const
{
if(d->icon.isNull())
return GluonEngine::Asset::icon();
return QIcon(d->icon);
}
const QStringList TextureAsset::supportedMimeTypes() const
{
QList<QByteArray> supported = QImageReader::supportedImageFormats();
QStringList supportedTypes;
foreach(const QByteArray &type, supported)
{
supportedTypes << QString("image/%1").arg(QString(type));
}
return supportedTypes;
}
void TextureAsset::load()
{
if (!file().isEmpty())
{
if (d->texture->load(file()))
{
mimeData()->setText(name());
//d->icon = QPixmap::fromImage(d->texture->scaled(QSize(128, 128), Qt::KeepAspectRatio));
setLoaded(true);
return;
}
}
debug("Error loading texture: %1", name());
}
void TextureAsset::setName( const QString& newName )
{
GluonGraphics::Engine::instance()->removeTexture(name());
GluonGraphics::Engine::instance()->addTexture(newName, d->texture);
GluonEngine::Asset::setName( newName );
}
Q_EXPORT_PLUGIN2(gluon_asset_texture, GluonEngine::TextureAsset)
#include "textureasset.moc"
<|endoftext|> |
<commit_before>#include "debugger.h"
#include "dbg_impl.h"
#include "dbg_network.h"
#include "bridge/dbg_delayload.h"
#include <base/util/unicode.h>
namespace vscode
{
debugger::debugger(io* io, threadmode mode)
: impl_(new debugger_impl(io, mode))
{ }
debugger::~debugger()
{
delete impl_;
}
void debugger::close()
{
impl_->close();
}
void debugger::update()
{
impl_->update();
}
void debugger::wait_attach()
{
impl_->wait_attach();
}
void debugger::attach_lua(lua_State* L)
{
impl_->attach_lua(L);
}
void debugger::detach_lua(lua_State* L)
{
impl_->detach_lua(L);
}
void debugger::set_custom(custom* custom)
{
impl_->set_custom(custom);
}
void debugger::output(const char* category, const char* buf, size_t len, lua_State* L)
{
impl_->output(category, buf, len, L);
}
void debugger::exception(lua_State* L)
{
impl_->exception(L);
}
bool debugger::is_state(state state) const
{
return impl_->is_state(state);
}
void debugger::redirect_stdout()
{
impl_->redirect_stdout();
}
void debugger::redirect_stderr()
{
impl_->redirect_stderr();
}
bool debugger::set_config(int level, const std::string& cfg, std::string& err)
{
return impl_->set_config(level, cfg, err);
}
}
std::unique_ptr<vscode::network> global_io;
std::unique_ptr<vscode::debugger> global_dbg;
void __cdecl debugger_set_luadll(void* luadll, void* getluaapi)
{
#if defined(DEBUGGER_DELAYLOAD_LUA)
delayload::set_luadll((HMODULE)luadll, (GetLuaApi)getluaapi);
#endif
}
void __cdecl debugger_start_server(const char* ip, uint16_t port, bool launch, bool rebind)
{
if (!global_io || !global_dbg)
{
global_io.reset(new vscode::network(ip, port, rebind));
global_dbg.reset(new vscode::debugger(global_io.get(), vscode::threadmode::async));
if (launch)
global_io->kill_process_when_close();
}
}
void __cdecl debugger_wait_attach()
{
if (global_dbg) {
global_dbg->wait_attach();
global_dbg->redirect_stdout();
global_dbg->redirect_stderr();
}
}
void __cdecl debugger_attach_lua(lua_State* L)
{
if (global_dbg) global_dbg->attach_lua(L);
}
void __cdecl debugger_detach_lua(lua_State* L)
{
if (global_dbg) global_dbg->detach_lua(L);
}
namespace luaw {
int listen(lua_State* L)
{
debugger_start_server(luaL_checkstring(L, 1), (uint16_t)luaL_checkinteger(L, 2), false, lua_toboolean(L, 3));
debugger_attach_lua(L);
lua_pushvalue(L, lua_upvalueindex(1));
return 1;
}
int start(lua_State* L)
{
debugger_attach_lua(L);
debugger_wait_attach();
lua_pushvalue(L, lua_upvalueindex(1));
return 1;
}
int port(lua_State* L)
{
if (global_io && global_dbg) {
lua_pushinteger(L, global_io->get_port());
return 1;
}
return 0;
}
int config(lua_State* L)
{
if (!global_io || !global_dbg) {
return 0;
}
if (lua_type(L, 1) == LUA_TSTRING) {
size_t len = 0;
const char* str = luaL_checklstring(L, 1, &len);
std::string err = "unknown";
if (!global_dbg->set_config(0, std::string(str, len), err)) {
lua_pushlstring(L, err.data(), err.size());
return lua_error(L);
}
}
if (lua_type(L, 2) == LUA_TSTRING) {
size_t len = 0;
const char* str = luaL_checklstring(L, 2, &len);
std::string err = "unknown";
if (!global_dbg->set_config(2, std::string(str, len), err)) {
lua_pushlstring(L, err.data(), err.size());
return lua_error(L);
}
}
return 0;
}
int mt_gc(lua_State* L)
{
if (global_dbg) {
global_dbg->detach_lua(L);
}
return 0;
}
int open(lua_State* L)
{
luaL_checkversion(L);
luaL_Reg f[] = {
{ "listen", listen },
{ "start", start },
{ "port", port },
{ "config", config },
{ "__gc", mt_gc },
{ NULL, NULL },
};
luaL_newlibtable(L, f);
lua_pushvalue(L, -1);
luaL_setfuncs(L, f, 1);
lua_pushvalue(L, -1);
lua_setmetatable(L, -2);
return 1;
}
}
#if defined(DEBUGGER_DELAYLOAD_LUA)
void caller_is_luadll(void* callerAddress)
{
HMODULE caller = NULL;
if (GetModuleHandleExW(GET_MODULE_HANDLE_EX_FLAG_FROM_ADDRESS, (LPCTSTR)callerAddress, &caller) && caller)
{
if (GetProcAddress(caller, "lua_newstate"))
{
delayload::set_luadll(caller);
}
}
}
#endif
int __cdecl luaopen_debugger(lua_State* L)
{
#if defined(DEBUGGER_DELAYLOAD_LUA)
caller_is_luadll(_ReturnAddress());
#endif
MessageBox(0, 0, 0, 0);
return luaw::open(L);
}
<commit_msg>忘了删测试代码...<commit_after>#include "debugger.h"
#include "dbg_impl.h"
#include "dbg_network.h"
#include "bridge/dbg_delayload.h"
#include <base/util/unicode.h>
namespace vscode
{
debugger::debugger(io* io, threadmode mode)
: impl_(new debugger_impl(io, mode))
{ }
debugger::~debugger()
{
delete impl_;
}
void debugger::close()
{
impl_->close();
}
void debugger::update()
{
impl_->update();
}
void debugger::wait_attach()
{
impl_->wait_attach();
}
void debugger::attach_lua(lua_State* L)
{
impl_->attach_lua(L);
}
void debugger::detach_lua(lua_State* L)
{
impl_->detach_lua(L);
}
void debugger::set_custom(custom* custom)
{
impl_->set_custom(custom);
}
void debugger::output(const char* category, const char* buf, size_t len, lua_State* L)
{
impl_->output(category, buf, len, L);
}
void debugger::exception(lua_State* L)
{
impl_->exception(L);
}
bool debugger::is_state(state state) const
{
return impl_->is_state(state);
}
void debugger::redirect_stdout()
{
impl_->redirect_stdout();
}
void debugger::redirect_stderr()
{
impl_->redirect_stderr();
}
bool debugger::set_config(int level, const std::string& cfg, std::string& err)
{
return impl_->set_config(level, cfg, err);
}
}
std::unique_ptr<vscode::network> global_io;
std::unique_ptr<vscode::debugger> global_dbg;
void __cdecl debugger_set_luadll(void* luadll, void* getluaapi)
{
#if defined(DEBUGGER_DELAYLOAD_LUA)
delayload::set_luadll((HMODULE)luadll, (GetLuaApi)getluaapi);
#endif
}
void __cdecl debugger_start_server(const char* ip, uint16_t port, bool launch, bool rebind)
{
if (!global_io || !global_dbg)
{
global_io.reset(new vscode::network(ip, port, rebind));
global_dbg.reset(new vscode::debugger(global_io.get(), vscode::threadmode::async));
if (launch)
global_io->kill_process_when_close();
}
}
void __cdecl debugger_wait_attach()
{
if (global_dbg) {
global_dbg->wait_attach();
global_dbg->redirect_stdout();
global_dbg->redirect_stderr();
}
}
void __cdecl debugger_attach_lua(lua_State* L)
{
if (global_dbg) global_dbg->attach_lua(L);
}
void __cdecl debugger_detach_lua(lua_State* L)
{
if (global_dbg) global_dbg->detach_lua(L);
}
namespace luaw {
int listen(lua_State* L)
{
debugger_start_server(luaL_checkstring(L, 1), (uint16_t)luaL_checkinteger(L, 2), false, lua_toboolean(L, 3));
debugger_attach_lua(L);
lua_pushvalue(L, lua_upvalueindex(1));
return 1;
}
int start(lua_State* L)
{
debugger_attach_lua(L);
debugger_wait_attach();
lua_pushvalue(L, lua_upvalueindex(1));
return 1;
}
int port(lua_State* L)
{
if (global_io && global_dbg) {
lua_pushinteger(L, global_io->get_port());
return 1;
}
return 0;
}
int config(lua_State* L)
{
if (!global_io || !global_dbg) {
return 0;
}
if (lua_type(L, 1) == LUA_TSTRING) {
size_t len = 0;
const char* str = luaL_checklstring(L, 1, &len);
std::string err = "unknown";
if (!global_dbg->set_config(0, std::string(str, len), err)) {
lua_pushlstring(L, err.data(), err.size());
return lua_error(L);
}
}
if (lua_type(L, 2) == LUA_TSTRING) {
size_t len = 0;
const char* str = luaL_checklstring(L, 2, &len);
std::string err = "unknown";
if (!global_dbg->set_config(2, std::string(str, len), err)) {
lua_pushlstring(L, err.data(), err.size());
return lua_error(L);
}
}
return 0;
}
int mt_gc(lua_State* L)
{
if (global_dbg) {
global_dbg->detach_lua(L);
}
return 0;
}
int open(lua_State* L)
{
luaL_checkversion(L);
luaL_Reg f[] = {
{ "listen", listen },
{ "start", start },
{ "port", port },
{ "config", config },
{ "__gc", mt_gc },
{ NULL, NULL },
};
luaL_newlibtable(L, f);
lua_pushvalue(L, -1);
luaL_setfuncs(L, f, 1);
lua_pushvalue(L, -1);
lua_setmetatable(L, -2);
return 1;
}
}
#if defined(DEBUGGER_DELAYLOAD_LUA)
void caller_is_luadll(void* callerAddress)
{
HMODULE caller = NULL;
if (GetModuleHandleExW(GET_MODULE_HANDLE_EX_FLAG_FROM_ADDRESS, (LPCTSTR)callerAddress, &caller) && caller)
{
if (GetProcAddress(caller, "lua_newstate"))
{
delayload::set_luadll(caller);
}
}
}
#endif
int __cdecl luaopen_debugger(lua_State* L)
{
#if defined(DEBUGGER_DELAYLOAD_LUA)
caller_is_luadll(_ReturnAddress());
#endif
return luaw::open(L);
}
<|endoftext|> |
<commit_before>// Copyright 2008 The RE2 Authors. All Rights Reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
// Exhaustive testing of regular expression matching.
#include "util/test.h"
#include "re2/testing/exhaustive_tester.h"
DECLARE_string(regexp_engines);
namespace re2 {
// Test simple repetition operators
TEST(Repetition, Simple) {
vector<string> ops = Split(" ",
"%s{0} %s{0,} %s{1} %s{1,} %s{0,1} %s{0,2} "
"%s{1,2} %s{2} %s{2,} %s{3,4} %s{4,5} "
"%s* %s+ %s? %s*? %s+? %s??");
ExhaustiveTest(3, 2, Explode("abc."), ops,
6, Explode("ab"), "(?:%s)", "");
ExhaustiveTest(3, 2, Explode("abc."), ops,
40, Explode("a"), "(?:%s)", "");
}
// Test capturing parens -- (a) -- inside repetition operators
TEST(Repetition, Capturing) {
vector<string> ops = Split(" ",
"%s{0} %s{0,} %s{1} %s{1,} %s{0,1} %s{0,2} "
"%s{1,2} %s{2} %s{2,} %s{3,4} %s{4,5} "
"%s* %s+ %s? %s*? %s+? %s??");
ExhaustiveTest(3, 2, Split(" ", "a (a) b"), ops,
7, Explode("ab"), "(?:%s)", "");
// This would be a great test, but it runs forever when PCRE is enabled.
if (!StringPiece(FLAGS_regexp_engines).contains("PCRE"))
ExhaustiveTest(4, 3, Split(" ", "a (a)"), ops,
100, Explode("a"), "(?:%s)", "");
}
} // namespace re2
<commit_msg>Speed up the Repetition.Capturing test.<commit_after>// Copyright 2008 The RE2 Authors. All Rights Reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
// Exhaustive testing of regular expression matching.
#include "util/test.h"
#include "re2/testing/exhaustive_tester.h"
DECLARE_string(regexp_engines);
namespace re2 {
// Test simple repetition operators
TEST(Repetition, Simple) {
vector<string> ops = Split(" ",
"%s{0} %s{0,} %s{1} %s{1,} %s{0,1} %s{0,2} "
"%s{1,2} %s{2} %s{2,} %s{3,4} %s{4,5} "
"%s* %s+ %s? %s*? %s+? %s??");
ExhaustiveTest(3, 2, Explode("abc."), ops,
6, Explode("ab"), "(?:%s)", "");
ExhaustiveTest(3, 2, Explode("abc."), ops,
40, Explode("a"), "(?:%s)", "");
}
// Test capturing parens -- (a) -- inside repetition operators
TEST(Repetition, Capturing) {
vector<string> ops = Split(" ",
"%s{0} %s{0,} %s{1} %s{1,} %s{0,1} %s{0,2} "
"%s{1,2} %s{2} %s{2,} %s{3,4} %s{4,5} "
"%s* %s+ %s? %s*? %s+? %s??");
ExhaustiveTest(3, 2, Split(" ", "a (a) b"), ops,
7, Explode("ab"), "(?:%s)", "");
// This would be a great test, but it runs forever when PCRE is enabled.
if (!StringPiece(FLAGS_regexp_engines).contains("PCRE"))
ExhaustiveTest(3, 2, Split(" ", "a (a)"), ops,
50, Explode("a"), "(?:%s)", "");
}
} // namespace re2
<|endoftext|> |
<commit_before>// DIB.CPP
#include <iostream>
#include <cstring>
#include <cstdio>
#include <cstdlib>
#include "cdib.h"
using namespace std;
CDib::CDib() {
m_pDibBytes = NULL;
m_pDibInfo = NULL;
m_pBFH = NULL;
}
CDib::~CDib() {
// 如果位图已经被加载,释放之
if (m_pDibBytes) {
delete[]m_pDibBytes;
}
// 如果位图文件结构已被加载,释放之
if (m_pDibInfo) {
delete[]m_pDibInfo;
}
// 如果位图文件头结构已被加载,释放之
if (m_pBFH) {
delete[]m_pBFH;
}
}
BYTE* CDib::GetpDibBytes() {
return m_pDibBytes;
}
DWORD CDib::GetWidth() {
return m_pDibInfo->bmiHeader.biWidth;
}
DWORD CDib::GetHeight() {
return m_pDibInfo->bmiHeader.biHeight;
}
WORD CDib::GetBitsPerPixel() {
if (!m_pDibInfo) {
return 0;
}
return m_pDibInfo->bmiHeader.biBitCount;
}
DWORD CDib::GetLineBytes() {
return((((m_pDibInfo->bmiHeader.biWidth * GetBitsPerPixel()) + 31) / 32) * 4);
}
DWORD CDib::GetLineBytes(LONG biWidth, LONG biBitCount) {
return ((((biWidth * biBitCount) + 31) / 32) * 4);
}
DWORD CDib::GetBodySize() {
return GetLineBytes() * m_pDibInfo->bmiHeader.biHeight;
}
BOOL CDib::Load(const char *filePath) {
if (!strlen(filePath)) {
cout << "Invalid Or Empty File Path!" << endl;
return FALSE;
}
// 二进制读方式打开指定图像文件
FILE *fp = fopen(filePath, "rb");
if (!fp) {
cout << "Loaded Image File Unsuccessfully!" << endl;
return FALSE;
}
// 分配内存空间
m_pBFH = (BITMAPFILEHEADER*)new BYTE[sizeof(BITMAPFILEHEADER)];
// 读取位图文件头进入内存
fread(m_pBFH, sizeof(BITMAPFILEHEADER), 1, fp);
// 如果文件类型标头不是“0x4d42”,表示该文件不是BMP类型文件
if (m_pBFH->bfType != 0x4d42) {
cout << "Image File Is Not A Bitmap!" << endl;
return FALSE;
}
// 读取位图信息头进入内存
BITMAPINFOHEADER bih;
fread(&bih, sizeof(BITMAPINFOHEADER), 1, fp);
// 定义调色板大小
int paletteSize = 0;
switch (bih.biBitCount) {
case 1:
paletteSize = 2;
break;
case 4:
paletteSize = 16;
break;
case 8:
paletteSize = 256;
break;
}
m_pDibInfo = (BITMAPINFO*)new BYTE[sizeof(BITMAPINFOHEADER) + sizeof(RGBQUAD)*paletteSize];
m_pDibInfo->bmiHeader = bih;
if (paletteSize) {
// 申请颜色表所需空间,读颜色表进内存
fread(m_pDibInfo->bmiColors, sizeof(RGBQUAD), paletteSize, fp);
}
// 申请位图数据所需空间,读位图数据进内存
DWORD bodySize = GetBodySize();
m_pDibBytes = (BYTE*)new BYTE[bodySize];
// 把文件指针移动到DIB像素数组
fseek(fp, m_pBFH->bfOffBits, 0);
fread(m_pDibBytes, sizeof(BYTE) ,bodySize, fp);
// 关闭文件
fclose(fp);
cout << "Loaded Image File: \"" << filePath << "\" Successfully!" << endl;
return TRUE;
}
BOOL CDib::Save(const char *filePath) {
if (!strlen(filePath)) {
cout << "Invalid Saved Path!" << endl;
return FALSE;
}
return Save(filePath, m_pDibBytes, m_pDibInfo->bmiHeader.biWidth, m_pDibInfo->bmiHeader.biHeight, m_pDibInfo->bmiHeader.biBitCount, m_pDibInfo->bmiColors);
}
BOOL CDib::Save(const char *filePath, BYTE *m_pDibBytes, LONG m_width, LONG m_height, LONG m_biBitCount, RGBQUAD *m_pPalette) {
// 如果位图数组指针为空,函数返回
if (!strlen(filePath)) {
cout << "Invalid Saved Path!" << endl;
return FALSE;
}
// 像素数据空指针
if (!m_pDibBytes) {
cout << "Invalid Image File Data!" << endl;
return FALSE;
}
// 颜色表大小,以字节为单位,灰度图像颜色为1024字节,彩色图像颜色表大小为0
int colorTableSize = 0;
if (m_biBitCount == 8) {
colorTableSize = 1024;
}
// 待存储图像数据格式为每行字节数为4的倍数
int lineBytes = GetLineBytes(m_width, m_biBitCount);
// 以二进制写的方式打开文件
FILE *fp = fopen(filePath, "wb");
if (!fp) {
cout << "Writing Image File Unsuccessfully!" << endl;
}
// 申请位图文件头结构变量,填写文件头信息
BITMAPFILEHEADER fileHead;
fileHead.bfType = 0x4D42; // 位图始终为此类型
// bfSize是图像文件4个组成部分之和
fileHead.bfSize = sizeof(BITMAPFILEHEADER) + sizeof(BITMAPINFOHEADER) + colorTableSize + lineBytes*m_height;
fileHead.bfReserved1 = 0;
fileHead.bfReserved2 = 0;
// bfOffBits 是图像文件前3个部分所需空间之和
fileHead.bfOffBits = sizeof(BITMAPFILEHEADER) + sizeof(BITMAPINFOHEADER) + colorTableSize;
// 写文件头进入文件
try
{
fwrite(&fileHead, sizeof(BITMAPFILEHEADER), 1, fp);
}
catch (const std::exception& e)
{
cout << "Writed File Header Unsuccessfully!" << endl;
cout << e.what() << endl;
exit(-1);
}
// 申请位图信息头结构变量,填写信息头信息
BITMAPINFOHEADER infoHead;
infoHead.biBitCount = m_biBitCount;
if (m_biBitCount == 8) {
infoHead.biClrImportant = infoHead.biClrUsed = 256;
}
else {
infoHead.biClrImportant = infoHead.biClrUsed = 0;
}
infoHead.biCompression = BI_RGB;
infoHead.biHeight = m_height;
infoHead.biPlanes = 1;
infoHead.biSize = 40;
infoHead.biSizeImage = lineBytes * m_height;
infoHead.biWidth = m_width;
infoHead.biXPelsPerMeter = 0;
infoHead.biYPelsPerMeter = 0;
// 写位图头信息进文件
try
{
fwrite(&infoHead, sizeof(BITMAPINFOHEADER), 1, fp);
}
catch (const std::exception& e)
{
cout << "Writed Info Header Unsuccessfully!" << endl;
cout << e.what() << endl;
exit(-1);
}
// 如果为灰度图像,有颜色表,写入文件
if (m_biBitCount == 8) {
fwrite(m_pPalette, sizeof(RGBQUAD), 256, fp);
}
// 写位图数据进文件
try
{
fwrite(m_pDibBytes, m_height * lineBytes, 1, fp);
}
catch (const std::exception& e)
{
cout << "Writed Image Data Unsuccessfully!" << endl;
cout << e.what() << endl;
exit(-1);
}
fclose(fp);
cout << "Image File \"" << filePath << "\" Stored Successfully!" << endl;
return TRUE;
}
void CDib::PrintFileHead() {
if (m_pBFH) {
cout << "bfType: " << m_pBFH->bfType
<<" bfSize: "<< m_pBFH->bfSize
<<" bfReserved1: "<< m_pBFH->bfReserved1
<< " bfReserved2: " << m_pBFH->bfReserved2
<< " bfOffBits: " << m_pBFH->bfOffBits
<< endl;
}
else {
cout << "Empty File Header!" << endl;
}
}
void CDib::PrintInfoHead() {
if (m_pDibInfo) {
cout << "width: " << m_pDibInfo->bmiHeader.biWidth
<< " height: " << m_pDibInfo->bmiHeader.biHeight
<< " biBitCount: " << m_pDibInfo->bmiHeader.biBitCount
<< endl;
}
else {
cout << "Empty Info Header!" << endl;
}
}
BOOL CDib::GrayScale() {
if (!m_pDibBytes) {
cout << "Failed To Gray Scale Image File!" << endl
<< "DIB Data Is Empty!" << endl;
return FALSE;
}
// 循环变量,图像横纵坐标
DWORD i, j;
// 每行字节数
DWORD lineBytes = GetLineBytes();
LONG width = m_pDibInfo->bmiHeader.biWidth;
LONG height = m_pDibInfo->bmiHeader.biHeight;
LONG bitCount = m_pDibInfo->bmiHeader.biBitCount;
if (bitCount == 24) {
BYTE r, g, b;
int k;
for (i = 0; i < height; i++) {
for (j = 0; j < width; j++) {
b = *(m_pDibBytes + i*lineBytes + j * 3 + 0);
g = *(m_pDibBytes + i*lineBytes + j * 3 + 1);
r = *(m_pDibBytes + i*lineBytes + j * 3 + 2);
int val = (30 * r + 59 * g + 11 * b) / 100;
val = val > 255 ? 255 : val;
for (k = 0; k < 3; k++) {
*(m_pDibBytes + i*lineBytes + j * 3 + k) = val;
}
}
}
}
cout << "Image Has Gray Scaled Successfully!" << endl;
return TRUE;
}
BOOL CDib::BinaryScale() {
if (!m_pDibBytes) {
cout << "Failed To Binary Scale Image File!" << endl
<< "DIB Data Is Empty!" << endl;
return FALSE;
}
// 循环变量,图像横纵坐标
DWORD i, j;
// 每行字节数
DWORD lineBytes = GetLineBytes();
LONG width = m_pDibInfo->bmiHeader.biWidth;
LONG height = m_pDibInfo->bmiHeader.biHeight;
LONG bitCount = m_pDibInfo->bmiHeader.biBitCount;
if (bitCount == 24) {
BYTE r, g, b;
int k;
for (i = 0; i < height; i++) {
for (j = 0; j < width; j++) {
b = *(m_pDibBytes + i*lineBytes + j * 3 + 0);
g = *(m_pDibBytes + i*lineBytes + j * 3 + 1);
r = *(m_pDibBytes + i*lineBytes + j * 3 + 2);
int val = (30 * r + 59 * g + 11 * b) / 100;
val = val >= BINARY_THRESHOLD ? 255 : 0;
for (k = 0; k < 3; k++) {
*(m_pDibBytes + i*lineBytes + j * 3 + k) = val;
}
}
}
}
// 如果为灰度图
else if (bitCount == 8) {
for (i = 0; i < height; i++) {
for (j = 0; j < width; j++) {
BYTE val = *(m_pDibBytes + i*lineBytes + j);
val = val >= BINARY_THRESHOLD ? 255 : 0;
*(m_pDibBytes + i*lineBytes + j) = val;
}
}
}
cout << "Image Has Binary Scaled Successfully!" << endl;
return TRUE;
}
BOOL CDib::Negative() {
if (!m_pDibBytes) {
cout << "Failed To Negative Image File!" << endl
<< "DIB Data Is Empty!" << endl;
return FALSE;
}
// 循环变量,图像横纵坐标
DWORD i, j;
// 每行字节数
DWORD lineBytes = GetLineBytes();
LONG width = m_pDibInfo->bmiHeader.biWidth;
LONG height = m_pDibInfo->bmiHeader.biHeight;
LONG bitCount = m_pDibInfo->bmiHeader.biBitCount;
BYTE maxVal = 255;
if (bitCount == 24) {
BYTE r, g, b;
for (i = 0; i < height; i++) {
for (j = 0; j < width; j++) {
b = *(m_pDibBytes + i*lineBytes + j * 3 + 0);
*(m_pDibBytes + i*lineBytes + j * 3 + 0) = maxVal - b;
g = *(m_pDibBytes + i*lineBytes + j * 3 + 1);
*(m_pDibBytes + i*lineBytes + j * 3 + 1) = maxVal - g;
r = *(m_pDibBytes + i*lineBytes + j * 3 + 2);
*(m_pDibBytes + i*lineBytes + j * 3 + 2) = maxVal - r;
}
}
}
else if (bitCount == 8) {
for (i = 0; i < height; i++) {
for (j = 0; j < width; j++) {
BYTE val = *(m_pDibBytes + i*lineBytes + j);
*(m_pDibBytes + i*lineBytes + j) = maxVal - val;
}
}
}
cout << "Image Has Negatived Successfully!" << endl;
return TRUE;
}<commit_msg>cdib.cpp bug fix<commit_after>// DIB.CPP
#include <iostream>
#include <cstring>
#include <cstdio>
#include <cstdlib>
#include "cdib.h"
using namespace std;
CDib::CDib() {
m_pDibBytes = NULL;
m_pDibInfo = NULL;
m_pBFH = NULL;
}
CDib::~CDib() {
// 如果位图已经被加载,释放之
if (m_pDibBytes) {
delete[]m_pDibBytes;
}
// 如果位图文件结构已被加载,释放之
if (m_pDibInfo) {
delete[]m_pDibInfo;
}
// 如果位图文件头结构已被加载,释放之
if (m_pBFH) {
delete[]m_pBFH;
}
}
BYTE* CDib::GetpDibBytes() {
return m_pDibBytes;
}
DWORD CDib::GetWidth() {
return m_pDibInfo->bmiHeader.biWidth;
}
DWORD CDib::GetHeight() {
return m_pDibInfo->bmiHeader.biHeight;
}
WORD CDib::GetBitsPerPixel() {
if (!m_pDibInfo) {
return 0;
}
return m_pDibInfo->bmiHeader.biBitCount;
}
DWORD CDib::GetLineBytes() {
return((((m_pDibInfo->bmiHeader.biWidth * GetBitsPerPixel()) + 31) / 32) * 4);
}
DWORD CDib::GetLineBytes(LONG biWidth, LONG biBitCount) {
return ((((biWidth * biBitCount) + 31) / 32) * 4);
}
DWORD CDib::GetBodySize() {
return GetLineBytes() * m_pDibInfo->bmiHeader.biHeight;
}
BOOL CDib::Load(const char *filePath) {
if (!strlen(filePath)) {
cout << "Invalid Or Empty File Path!" << endl;
return FALSE;
}
// 二进制读方式打开指定图像文件
FILE *fp = fopen(filePath, "rb");
if (!fp) {
cout << "Loaded Image File Unsuccessfully!" << endl;
return FALSE;
}
// 分配内存空间
m_pBFH = (BITMAPFILEHEADER*)new BYTE[sizeof(BITMAPFILEHEADER)];
// 读取位图文件头进入内存
fread(m_pBFH, sizeof(BITMAPFILEHEADER), 1, fp);
// 如果文件类型标头不是“0x4d42”,表示该文件不是BMP类型文件
if (m_pBFH->bfType != 0x4d42) {
cout << "Image File Is Not A Bitmap!" << endl;
return FALSE;
}
// 读取位图信息头进入内存
BITMAPINFOHEADER bih;
fread(&bih, sizeof(BITMAPINFOHEADER), 1, fp);
// 定义调色板大小
int paletteSize = 0;
switch (bih.biBitCount) {
case 1:
paletteSize = 2;
break;
case 4:
paletteSize = 16;
break;
case 8:
paletteSize = 256;
break;
}
m_pDibInfo = (BITMAPINFO*)new BYTE[sizeof(BITMAPINFOHEADER) + sizeof(RGBQUAD)*paletteSize];
m_pDibInfo->bmiHeader = bih;
if (paletteSize) {
// 申请颜色表所需空间,读颜色表进内存
fread(m_pDibInfo->bmiColors, sizeof(RGBQUAD), paletteSize, fp);
}
// 申请位图数据所需空间,读位图数据进内存
DWORD bodySize = GetBodySize();
m_pDibBytes = (BYTE*)new BYTE[bodySize];
// 把文件指针移动到DIB像素数组
fseek(fp, m_pBFH->bfOffBits, 0);
fread(m_pDibBytes, sizeof(BYTE) ,bodySize, fp);
// 关闭文件
fclose(fp);
cout << "Loaded Image File: \"" << filePath << "\" Successfully!" << endl;
return TRUE;
}
BOOL CDib::Save(const char *filePath) {
if (!strlen(filePath)) {
cout << "Invalid Saved Path!" << endl;
return FALSE;
}
return Save(filePath, m_pDibBytes, m_pDibInfo->bmiHeader.biWidth, m_pDibInfo->bmiHeader.biHeight, m_pDibInfo->bmiHeader.biBitCount, m_pDibInfo->bmiColors);
}
BOOL CDib::Save(const char *filePath, BYTE *m_pDibBytes, LONG m_width, LONG m_height, LONG m_biBitCount, RGBQUAD *m_pPalette) {
// 如果位图数组指针为空,函数返回
if (!strlen(filePath)) {
cout << "Invalid Saved Path!" << endl;
return FALSE;
}
// 像素数据空指针
if (!m_pDibBytes) {
cout << "Invalid Image File Data!" << endl;
return FALSE;
}
// 颜色表大小,以字节为单位,灰度图像颜色为1024字节,彩色图像颜色表大小为0
int colorTableSize = 0;
if (m_biBitCount == 8) {
colorTableSize = 1024;
}
// 待存储图像数据格式为每行字节数为4的倍数
int lineBytes = GetLineBytes(m_width, m_biBitCount);
// 以二进制写的方式打开文件
FILE *fp = fopen(filePath, "wb");
if (!fp) {
cout << "Writing Image File Unsuccessfully!" << endl;
return FALSE;
}
// 申请位图文件头结构变量,填写文件头信息
BITMAPFILEHEADER fileHead;
fileHead.bfType = 0x4D42; // 位图始终为此类型
// bfSize是图像文件4个组成部分之和
fileHead.bfSize = sizeof(BITMAPFILEHEADER) + sizeof(BITMAPINFOHEADER) + colorTableSize + lineBytes*m_height;
fileHead.bfReserved1 = 0;
fileHead.bfReserved2 = 0;
// bfOffBits 是图像文件前3个部分所需空间之和
fileHead.bfOffBits = sizeof(BITMAPFILEHEADER) + sizeof(BITMAPINFOHEADER) + colorTableSize;
// 写文件头进入文件
try
{
fwrite(&fileHead, sizeof(BITMAPFILEHEADER), 1, fp);
}
catch (const std::exception& e)
{
cout << "Writed File Header Unsuccessfully!" << endl;
cout << e.what() << endl;
exit(-1);
}
// 申请位图信息头结构变量,填写信息头信息
BITMAPINFOHEADER infoHead;
infoHead.biBitCount = m_biBitCount;
if (m_biBitCount == 8) {
infoHead.biClrImportant = infoHead.biClrUsed = 256;
}
else {
infoHead.biClrImportant = infoHead.biClrUsed = 0;
}
infoHead.biCompression = BI_RGB;
infoHead.biHeight = m_height;
infoHead.biPlanes = 1;
infoHead.biSize = 40;
infoHead.biSizeImage = lineBytes * m_height;
infoHead.biWidth = m_width;
infoHead.biXPelsPerMeter = 0;
infoHead.biYPelsPerMeter = 0;
// 写位图头信息进文件
try
{
fwrite(&infoHead, sizeof(BITMAPINFOHEADER), 1, fp);
}
catch (const std::exception& e)
{
cout << "Writed Info Header Unsuccessfully!" << endl;
cout << e.what() << endl;
exit(-1);
}
// 如果为灰度图像,有颜色表,写入文件
if (m_biBitCount == 8) {
fwrite(m_pPalette, sizeof(RGBQUAD), 256, fp);
}
// 写位图数据进文件
try
{
fwrite(m_pDibBytes, m_height * lineBytes, 1, fp);
}
catch (const std::exception& e)
{
cout << "Writed Image Data Unsuccessfully!" << endl;
cout << e.what() << endl;
exit(-1);
}
fclose(fp);
cout << "Image File \"" << filePath << "\" Stored Successfully!" << endl;
return TRUE;
}
void CDib::PrintFileHead() {
if (m_pBFH) {
cout << "bfType: " << m_pBFH->bfType
<<" bfSize: "<< m_pBFH->bfSize
<<" bfReserved1: "<< m_pBFH->bfReserved1
<< " bfReserved2: " << m_pBFH->bfReserved2
<< " bfOffBits: " << m_pBFH->bfOffBits
<< endl;
}
else {
cout << "Empty File Header!" << endl;
}
}
void CDib::PrintInfoHead() {
if (m_pDibInfo) {
cout << "width: " << m_pDibInfo->bmiHeader.biWidth
<< " height: " << m_pDibInfo->bmiHeader.biHeight
<< " biBitCount: " << m_pDibInfo->bmiHeader.biBitCount
<< endl;
}
else {
cout << "Empty Info Header!" << endl;
}
}
BOOL CDib::GrayScale() {
if (!m_pDibBytes) {
cout << "Failed To Gray Scale Image File!" << endl
<< "DIB Data Is Empty!" << endl;
return FALSE;
}
// 循环变量,图像横纵坐标
DWORD i, j;
// 每行字节数
DWORD lineBytes = GetLineBytes();
LONG width = m_pDibInfo->bmiHeader.biWidth;
LONG height = m_pDibInfo->bmiHeader.biHeight;
LONG bitCount = m_pDibInfo->bmiHeader.biBitCount;
if (bitCount == 24) {
BYTE r, g, b;
int k;
for (i = 0; i < height; i++) {
for (j = 0; j < width; j++) {
b = *(m_pDibBytes + i*lineBytes + j * 3 + 0);
g = *(m_pDibBytes + i*lineBytes + j * 3 + 1);
r = *(m_pDibBytes + i*lineBytes + j * 3 + 2);
int val = (30 * r + 59 * g + 11 * b) / 100;
val = val > 255 ? 255 : val;
for (k = 0; k < 3; k++) {
*(m_pDibBytes + i*lineBytes + j * 3 + k) = val;
}
}
}
}
cout << "Image Has Gray Scaled Successfully!" << endl;
return TRUE;
}
BOOL CDib::BinaryScale() {
if (!m_pDibBytes) {
cout << "Failed To Binary Scale Image File!" << endl
<< "DIB Data Is Empty!" << endl;
return FALSE;
}
// 循环变量,图像横纵坐标
DWORD i, j;
// 每行字节数
DWORD lineBytes = GetLineBytes();
LONG width = m_pDibInfo->bmiHeader.biWidth;
LONG height = m_pDibInfo->bmiHeader.biHeight;
LONG bitCount = m_pDibInfo->bmiHeader.biBitCount;
if (bitCount == 24) {
BYTE r, g, b;
int k;
for (i = 0; i < height; i++) {
for (j = 0; j < width; j++) {
b = *(m_pDibBytes + i*lineBytes + j * 3 + 0);
g = *(m_pDibBytes + i*lineBytes + j * 3 + 1);
r = *(m_pDibBytes + i*lineBytes + j * 3 + 2);
int val = (30 * r + 59 * g + 11 * b) / 100;
val = val >= BINARY_THRESHOLD ? 255 : 0;
for (k = 0; k < 3; k++) {
*(m_pDibBytes + i*lineBytes + j * 3 + k) = val;
}
}
}
}
// 如果为灰度图
else if (bitCount == 8) {
for (i = 0; i < height; i++) {
for (j = 0; j < width; j++) {
BYTE val = *(m_pDibBytes + i*lineBytes + j);
val = val >= BINARY_THRESHOLD ? 255 : 0;
*(m_pDibBytes + i*lineBytes + j) = val;
}
}
}
cout << "Image Has Binary Scaled Successfully!" << endl;
return TRUE;
}
BOOL CDib::Negative() {
if (!m_pDibBytes) {
cout << "Failed To Negative Image File!" << endl
<< "DIB Data Is Empty!" << endl;
return FALSE;
}
// 循环变量,图像横纵坐标
DWORD i, j;
// 每行字节数
DWORD lineBytes = GetLineBytes();
LONG width = m_pDibInfo->bmiHeader.biWidth;
LONG height = m_pDibInfo->bmiHeader.biHeight;
LONG bitCount = m_pDibInfo->bmiHeader.biBitCount;
BYTE maxVal = 255;
if (bitCount == 24) {
BYTE r, g, b;
for (i = 0; i < height; i++) {
for (j = 0; j < width; j++) {
b = *(m_pDibBytes + i*lineBytes + j * 3 + 0);
*(m_pDibBytes + i*lineBytes + j * 3 + 0) = maxVal - b;
g = *(m_pDibBytes + i*lineBytes + j * 3 + 1);
*(m_pDibBytes + i*lineBytes + j * 3 + 1) = maxVal - g;
r = *(m_pDibBytes + i*lineBytes + j * 3 + 2);
*(m_pDibBytes + i*lineBytes + j * 3 + 2) = maxVal - r;
}
}
}
else if (bitCount == 8) {
for (i = 0; i < height; i++) {
for (j = 0; j < width; j++) {
BYTE val = *(m_pDibBytes + i*lineBytes + j);
*(m_pDibBytes + i*lineBytes + j) = maxVal - val;
}
}
}
cout << "Image Has Negatived Successfully!" << endl;
return TRUE;
}<|endoftext|> |
<commit_before>#include <iostream>
#include <algorithm>
#include <unistd.h>
#include <fcntl.h>
#include "dasync.h"
#include "service.h"
#include "dinit-log.h"
#include "cpbuffer.h"
// TODO should disarm, not remove, the file descriptor watchers when they are not busy
// (and likewise re-arm instead of re-add them when new data arrives).
extern EventLoop_t eventLoop;
LogLevel log_level = LogLevel::WARN;
LogLevel cons_log_level = LogLevel::WARN;
static bool log_to_console = false; // whether we should output log messages to
// console immediately
static bool log_current_line; // Whether the current line is being logged
static ServiceSet *service_set = nullptr; // Reference to service set
namespace {
class BufferedLogStream : public PosixFdWatcher<NullMutex>
{
private:
// Outgoing:
bool partway = false; // if we are partway throught output of a log message
bool discarded = false; // if we have discarded a message
// A "special message" is not stored in the circular buffer; instead
// it is delivered from an external buffer not managed by BufferedLogger.
bool special = false; // currently outputting special message?
char *special_buf; // buffer containing special message
int msg_index; // index into special message
public:
CPBuffer<4096> log_buffer;
// Incoming:
int current_index = 0; // current/next incoming message index
int fd;
void init(int fd)
{
this->fd = fd;
}
Rearm gotEvent(EventLoop_t *loop, int fd, int flags) noexcept override;
// Check whether the console can be released.
void flushForRelease();
};
}
// Two log streams:
// (One for main log, one for console)
static BufferedLogStream log_stream[2];
constexpr static int DLOG_MAIN = 0; // main log facility
constexpr static int DLOG_CONS = 1; // console
static void release_console()
{
if (! log_to_console) {
int flags = fcntl(1, F_GETFL, 0);
fcntl(1, F_SETFL, flags & ~O_NONBLOCK);
service_set->pullConsoleQueue();
}
}
void BufferedLogStream::flushForRelease()
{
// Try to flush any messages that are currently buffered. (Console is non-blocking
// so it will fail gracefully).
if (gotEvent(&eventLoop, fd, out_events) == Rearm::DISARM) {
// Console has already been released at this point.
setEnabled(&eventLoop, false);
}
// gotEvent didn't want to disarm, so must be partway through a message; will
// release when it's finished.
}
Rearm BufferedLogStream::gotEvent(EventLoop_t *loop, int fd, int flags) noexcept
{
// TODO correct for the case that this is *not* the console log stream.
auto &log_stream = *this;
if ((! partway) && log_stream.special) {
char * start = log_stream.special_buf + log_stream.msg_index;
char * end = std::find(log_stream.special_buf + log_stream.msg_index, (char *)nullptr, '\n');
int r = write(fd, start, end - start + 1);
if (r >= 0) {
if (start + r > end) {
// All written: go on to next message in queue
log_stream.special = false;
log_stream.partway = false;
log_stream.msg_index = 0;
if (!log_to_console) {
release_console();
return Rearm::DISARM;
}
}
else {
log_stream.msg_index += r;
return Rearm::REARM;
}
}
else {
// spurious readiness - EAGAIN or EWOULDBLOCK?
// other error?
// TODO
}
return Rearm::REARM;
}
else {
// Writing from the regular circular buffer
// TODO issue special message if we have discarded a log message
if (log_stream.current_index == 0) {
release_console();
return Rearm::DISARM;
}
char *ptr = log_stream.log_buffer.get_ptr(0);
int len = log_stream.log_buffer.get_contiguous_length(ptr);
char *creptr = ptr + len; // contiguous region end
char *eptr = std::find(ptr, creptr, '\n');
bool will_complete = false; // will complete this message?
if (eptr != creptr) {
eptr++; // include '\n'
will_complete = true;
}
len = eptr - ptr;
int r = write(fd, ptr, len);
if (r >= 0) {
bool complete = (r == len) && will_complete;
log_stream.log_buffer.consume(len);
log_stream.partway = ! complete;
if (complete) {
log_stream.current_index -= len;
if (log_stream.current_index == 0 || !log_to_console) {
// No more messages buffered / stop logging to console:
release_console();
return Rearm::DISARM;
}
}
}
else {
// TODO
// EAGAIN / EWOULDBLOCK?
// error?
return Rearm::REARM;
}
}
// We've written something by the time we get here. We could fall through to below, but
// let's give other events a chance to be processed by returning now.
return Rearm::REARM;
}
void init_log(ServiceSet *sset) noexcept
{
service_set = sset;
log_stream[DLOG_CONS].registerWith(&eventLoop, STDOUT_FILENO, out_events); // TODO register in disabled state
enable_console_log(true);
}
bool is_log_flushed() noexcept
{
return log_stream[DLOG_CONS].current_index == 0;
}
// Enable or disable console logging. If disabled, console logging will be disabled on the
// completion of output of the current message (if any), at which point the first service record
// queued in the service set will acquire the console.
void enable_console_log(bool enable) noexcept
{
if (enable && ! log_to_console) {
// Console is fd 1 - stdout
// Set non-blocking IO:
int flags = fcntl(1, F_GETFL, 0);
fcntl(1, F_SETFL, flags | O_NONBLOCK);
// Activate watcher:
log_stream[DLOG_CONS].init(STDOUT_FILENO);
log_to_console = true;
}
else if (! enable && log_to_console) {
log_to_console = false;
log_stream[DLOG_CONS].flushForRelease();
}
}
// Variadic method to calculate the sum of string lengths:
static int sum_length(const char *arg) noexcept
{
return std::strlen(arg);
}
template <typename U, typename ... T> static int sum_length(U first, T ... args) noexcept
{
return sum_length(first) + sum_length(args...);
}
// Variadic method to append strings to a buffer:
static void append(CPBuffer<4096> &buf, const char *s)
{
buf.append(s, std::strlen(s));
}
template <typename U, typename ... T> static void append(CPBuffer<4096> &buf, U u, T ... t)
{
append(buf, u);
append(buf, t...);
}
// Variadic method to log a sequence of strings as a single message:
template <typename ... T> static void do_log(T ... args) noexcept
{
int amount = sum_length(args...);
if (log_stream[DLOG_CONS].log_buffer.get_free() >= amount) {
append(log_stream[DLOG_CONS].log_buffer, args...);
bool was_first = (log_stream[DLOG_CONS].current_index == 0);
log_stream[DLOG_CONS].current_index += amount;
if (was_first && log_to_console) {
log_stream[DLOG_CONS].setEnabled(&eventLoop, true);
}
}
else {
// TODO mark a discarded message
}
}
// Variadic method to potentially log a sequence of strings as a single message with the given log level:
template <typename ... T> static void do_log(LogLevel lvl, T ... args) noexcept
{
if (lvl >= cons_log_level) {
do_log(args...);
}
}
// Log a message. A newline will be appended.
void log(LogLevel lvl, const char *msg) noexcept
{
do_log(lvl, "dinit: ", msg, "\n");
}
// Log part of a message. A series of calls to do_log_part must be followed by a call to do_log_commit.
template <typename T> static void do_log_part(T arg) noexcept
{
int amount = sum_length(arg);
if (log_stream[DLOG_CONS].log_buffer.get_free() >= amount) {
append(log_stream[DLOG_CONS].log_buffer, arg);
}
else {
// reset
log_stream[DLOG_CONS].log_buffer.trim_to(log_stream[DLOG_CONS].current_index);
log_current_line = false;
// TODO mark discarded message
}
}
// Commit a message that was issued as a series of parts (via do_log_part).
static void do_log_commit() noexcept
{
if (log_current_line) {
bool was_first = log_stream[DLOG_CONS].current_index == 0;
log_stream[DLOG_CONS].current_index = log_stream[DLOG_CONS].log_buffer.get_length();
if (was_first && log_to_console) {
log_stream[DLOG_CONS].setEnabled(&eventLoop, true);
}
}
}
// Log a multi-part message beginning
void logMsgBegin(LogLevel lvl, const char *msg) noexcept
{
// TODO use buffer
log_current_line = lvl >= log_level;
if (log_current_line) {
if (log_to_console) {
do_log_part("dinit: ");
do_log_part(msg);
}
}
}
// Continue a multi-part log message
void logMsgPart(const char *msg) noexcept
{
// TODO use buffer
if (log_current_line) {
if (log_to_console) {
do_log_part(msg);
}
}
}
// Complete a multi-part log message
void logMsgEnd(const char *msg) noexcept
{
// TODO use buffer
if (log_current_line) {
if (log_to_console) {
do_log_part(msg);
do_log_part("\n");
do_log_commit();
}
}
}
void logServiceStarted(const char *service_name) noexcept
{
do_log("[ OK ] ", service_name, "\n");
}
void logServiceFailed(const char *service_name) noexcept
{
do_log("[FAILED] ", service_name, "\n");
}
void logServiceStopped(const char *service_name) noexcept
{
do_log("[STOPPD] ", service_name, "\n");
}
<commit_msg>Remove obseleted TODO comment<commit_after>#include <iostream>
#include <algorithm>
#include <unistd.h>
#include <fcntl.h>
#include "dasync.h"
#include "service.h"
#include "dinit-log.h"
#include "cpbuffer.h"
extern EventLoop_t eventLoop;
LogLevel log_level = LogLevel::WARN;
LogLevel cons_log_level = LogLevel::WARN;
static bool log_to_console = false; // whether we should output log messages to
// console immediately
static bool log_current_line; // Whether the current line is being logged
static ServiceSet *service_set = nullptr; // Reference to service set
namespace {
class BufferedLogStream : public PosixFdWatcher<NullMutex>
{
private:
// Outgoing:
bool partway = false; // if we are partway throught output of a log message
bool discarded = false; // if we have discarded a message
// A "special message" is not stored in the circular buffer; instead
// it is delivered from an external buffer not managed by BufferedLogger.
bool special = false; // currently outputting special message?
char *special_buf; // buffer containing special message
int msg_index; // index into special message
public:
CPBuffer<4096> log_buffer;
// Incoming:
int current_index = 0; // current/next incoming message index
int fd;
void init(int fd)
{
this->fd = fd;
}
Rearm gotEvent(EventLoop_t *loop, int fd, int flags) noexcept override;
// Check whether the console can be released.
void flushForRelease();
};
}
// Two log streams:
// (One for main log, one for console)
static BufferedLogStream log_stream[2];
constexpr static int DLOG_MAIN = 0; // main log facility
constexpr static int DLOG_CONS = 1; // console
static void release_console()
{
if (! log_to_console) {
int flags = fcntl(1, F_GETFL, 0);
fcntl(1, F_SETFL, flags & ~O_NONBLOCK);
service_set->pullConsoleQueue();
}
}
void BufferedLogStream::flushForRelease()
{
// Try to flush any messages that are currently buffered. (Console is non-blocking
// so it will fail gracefully).
if (gotEvent(&eventLoop, fd, out_events) == Rearm::DISARM) {
// Console has already been released at this point.
setEnabled(&eventLoop, false);
}
// gotEvent didn't want to disarm, so must be partway through a message; will
// release when it's finished.
}
Rearm BufferedLogStream::gotEvent(EventLoop_t *loop, int fd, int flags) noexcept
{
// TODO correct for the case that this is *not* the console log stream.
auto &log_stream = *this;
if ((! partway) && log_stream.special) {
char * start = log_stream.special_buf + log_stream.msg_index;
char * end = std::find(log_stream.special_buf + log_stream.msg_index, (char *)nullptr, '\n');
int r = write(fd, start, end - start + 1);
if (r >= 0) {
if (start + r > end) {
// All written: go on to next message in queue
log_stream.special = false;
log_stream.partway = false;
log_stream.msg_index = 0;
if (!log_to_console) {
release_console();
return Rearm::DISARM;
}
}
else {
log_stream.msg_index += r;
return Rearm::REARM;
}
}
else {
// spurious readiness - EAGAIN or EWOULDBLOCK?
// other error?
// TODO
}
return Rearm::REARM;
}
else {
// Writing from the regular circular buffer
// TODO issue special message if we have discarded a log message
if (log_stream.current_index == 0) {
release_console();
return Rearm::DISARM;
}
char *ptr = log_stream.log_buffer.get_ptr(0);
int len = log_stream.log_buffer.get_contiguous_length(ptr);
char *creptr = ptr + len; // contiguous region end
char *eptr = std::find(ptr, creptr, '\n');
bool will_complete = false; // will complete this message?
if (eptr != creptr) {
eptr++; // include '\n'
will_complete = true;
}
len = eptr - ptr;
int r = write(fd, ptr, len);
if (r >= 0) {
bool complete = (r == len) && will_complete;
log_stream.log_buffer.consume(len);
log_stream.partway = ! complete;
if (complete) {
log_stream.current_index -= len;
if (log_stream.current_index == 0 || !log_to_console) {
// No more messages buffered / stop logging to console:
release_console();
return Rearm::DISARM;
}
}
}
else {
// TODO
// EAGAIN / EWOULDBLOCK?
// error?
return Rearm::REARM;
}
}
// We've written something by the time we get here. We could fall through to below, but
// let's give other events a chance to be processed by returning now.
return Rearm::REARM;
}
void init_log(ServiceSet *sset) noexcept
{
service_set = sset;
log_stream[DLOG_CONS].registerWith(&eventLoop, STDOUT_FILENO, out_events); // TODO register in disabled state
enable_console_log(true);
}
bool is_log_flushed() noexcept
{
return log_stream[DLOG_CONS].current_index == 0;
}
// Enable or disable console logging. If disabled, console logging will be disabled on the
// completion of output of the current message (if any), at which point the first service record
// queued in the service set will acquire the console.
void enable_console_log(bool enable) noexcept
{
if (enable && ! log_to_console) {
// Console is fd 1 - stdout
// Set non-blocking IO:
int flags = fcntl(1, F_GETFL, 0);
fcntl(1, F_SETFL, flags | O_NONBLOCK);
// Activate watcher:
log_stream[DLOG_CONS].init(STDOUT_FILENO);
log_to_console = true;
}
else if (! enable && log_to_console) {
log_to_console = false;
log_stream[DLOG_CONS].flushForRelease();
}
}
// Variadic method to calculate the sum of string lengths:
static int sum_length(const char *arg) noexcept
{
return std::strlen(arg);
}
template <typename U, typename ... T> static int sum_length(U first, T ... args) noexcept
{
return sum_length(first) + sum_length(args...);
}
// Variadic method to append strings to a buffer:
static void append(CPBuffer<4096> &buf, const char *s)
{
buf.append(s, std::strlen(s));
}
template <typename U, typename ... T> static void append(CPBuffer<4096> &buf, U u, T ... t)
{
append(buf, u);
append(buf, t...);
}
// Variadic method to log a sequence of strings as a single message:
template <typename ... T> static void do_log(T ... args) noexcept
{
int amount = sum_length(args...);
if (log_stream[DLOG_CONS].log_buffer.get_free() >= amount) {
append(log_stream[DLOG_CONS].log_buffer, args...);
bool was_first = (log_stream[DLOG_CONS].current_index == 0);
log_stream[DLOG_CONS].current_index += amount;
if (was_first && log_to_console) {
log_stream[DLOG_CONS].setEnabled(&eventLoop, true);
}
}
else {
// TODO mark a discarded message
}
}
// Variadic method to potentially log a sequence of strings as a single message with the given log level:
template <typename ... T> static void do_log(LogLevel lvl, T ... args) noexcept
{
if (lvl >= cons_log_level) {
do_log(args...);
}
}
// Log a message. A newline will be appended.
void log(LogLevel lvl, const char *msg) noexcept
{
do_log(lvl, "dinit: ", msg, "\n");
}
// Log part of a message. A series of calls to do_log_part must be followed by a call to do_log_commit.
template <typename T> static void do_log_part(T arg) noexcept
{
int amount = sum_length(arg);
if (log_stream[DLOG_CONS].log_buffer.get_free() >= amount) {
append(log_stream[DLOG_CONS].log_buffer, arg);
}
else {
// reset
log_stream[DLOG_CONS].log_buffer.trim_to(log_stream[DLOG_CONS].current_index);
log_current_line = false;
// TODO mark discarded message
}
}
// Commit a message that was issued as a series of parts (via do_log_part).
static void do_log_commit() noexcept
{
if (log_current_line) {
bool was_first = log_stream[DLOG_CONS].current_index == 0;
log_stream[DLOG_CONS].current_index = log_stream[DLOG_CONS].log_buffer.get_length();
if (was_first && log_to_console) {
log_stream[DLOG_CONS].setEnabled(&eventLoop, true);
}
}
}
// Log a multi-part message beginning
void logMsgBegin(LogLevel lvl, const char *msg) noexcept
{
// TODO use buffer
log_current_line = lvl >= log_level;
if (log_current_line) {
if (log_to_console) {
do_log_part("dinit: ");
do_log_part(msg);
}
}
}
// Continue a multi-part log message
void logMsgPart(const char *msg) noexcept
{
// TODO use buffer
if (log_current_line) {
if (log_to_console) {
do_log_part(msg);
}
}
}
// Complete a multi-part log message
void logMsgEnd(const char *msg) noexcept
{
// TODO use buffer
if (log_current_line) {
if (log_to_console) {
do_log_part(msg);
do_log_part("\n");
do_log_commit();
}
}
}
void logServiceStarted(const char *service_name) noexcept
{
do_log("[ OK ] ", service_name, "\n");
}
void logServiceFailed(const char *service_name) noexcept
{
do_log("[FAILED] ", service_name, "\n");
}
void logServiceStopped(const char *service_name) noexcept
{
do_log("[STOPPD] ", service_name, "\n");
}
<|endoftext|> |
<commit_before>/**
* Copyright (c) 2011-2015 libbitcoin developers (see AUTHORS)
*
* This file is part of libbitcoin-server.
*
* libbitcoin-server is free software: you can redistribute it and/or
* modify it under the terms of the GNU Affero General Public License with
* additional permissions to the one published by the Free Software
* Foundation, either version 3 of the License, or (at your option)
* any later version. For more information see LICENSE.
*
* 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 Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
#include <bitcoin/server/dispatch.hpp>
#include <csignal>
#include <future>
#include <iostream>
#include <boost/format.hpp>
#include <boost/filesystem.hpp>
#include <boost/program_options.hpp>
#include <bitcoin/node.hpp>
#include <bitcoin/server/config/parser.hpp>
#include <bitcoin/server/config/settings.hpp>
#include <bitcoin/server/message.hpp>
#include <bitcoin/server/server_node.hpp>
#include <bitcoin/server/publisher.hpp>
#include <bitcoin/server/subscribe_manager.hpp>
#include <bitcoin/server/version.hpp>
#include <bitcoin/server/worker.hpp>
#include <bitcoin/server/server_node.hpp>
#include <bitcoin/server/service/blockchain.hpp>
#include <bitcoin/server/service/compat.hpp>
#include <bitcoin/server/service/protocol.hpp>
#include <bitcoin/server/service/transaction_pool.hpp>
#define BS_APPLICATION_NAME "bs"
// Localizable messages.
#define BS_SETTINGS_MESSAGE \
"These are the configuration settings that can be set."
#define BS_INFORMATION_MESSAGE \
"Runs a full bitcoin node in the global peer-to-peer network."
#define BS_UNINITIALIZED_CHAIN \
"The %1% directory is not initialized."
#define BS_INITIALIZING_CHAIN \
"Please wait while initializing %1% directory..."
#define BS_INITCHAIN_DIR_NEW \
"Failed to create directory %1% with error, '%2%'."
#define BS_INITCHAIN_DIR_EXISTS \
"Failed because the directory %1% already exists."
#define BS_INITCHAIN_DIR_TEST \
"Failed to test directory %1% with error, '%2%'."
#define BS_SERVER_STARTING \
"Please wait while server is starting."
#define BS_SERVER_START_FAIL \
"Server failed to start with error, %1%."
#define BS_SERVER_STARTED \
"Server started, press CTRL-C to stop."
#define BS_SERVER_STOPPING \
"Please wait while server is stopping (code: %1%)..."
#define BS_SERVER_UNMAPPING \
"Please wait while files are unmapped..."
#define BS_SERVER_STOP_FAIL \
"Server stopped with error, %1%."
#define BS_PUBLISHER_START_FAIL \
"Publisher service failed to start: %1%"
#define BS_PUBLISHER_STOP_FAIL \
"Publisher service failed to stop."
#define BS_WORKER_START_FAIL \
"Query service failed to start."
#define BS_WORKER_STOP_FAIL \
"Query service failed to stop."
#define BS_USING_CONFIG_FILE \
"Using config file: %1%"
#define BS_INVALID_PARAMETER \
"Error: %1%"
#define BS_VERSION_MESSAGE \
"\nVersion Information:\n\n" \
"libbitcoin-server: %1%\n" \
"libbitcoin-node: %2%\n" \
"libbitcoin-blockchain: %3%\n" \
"libbitcoin: %4%"
namespace libbitcoin {
namespace server {
using std::placeholders::_1;
using std::placeholders::_2;
using boost::format;
using namespace bc::blockchain;
using namespace bc::config;
using namespace boost::system;
using namespace boost::filesystem;
static void display_invalid_parameter(std::ostream& stream,
const std::string& message)
{
// English-only hack to patch missing arg name in boost exception message.
std::string clean_message(message);
boost::replace_all(clean_message, "for option is invalid", "is invalid");
stream << format(BS_INVALID_PARAMETER) % clean_message << std::endl;
}
static void show_help(parser& metadata, std::ostream& stream)
{
printer help(metadata.load_options(), metadata.load_arguments(),
BS_APPLICATION_NAME, BS_INFORMATION_MESSAGE);
help.initialize();
help.commandline(stream);
}
static void show_settings(parser& metadata, std::ostream& stream)
{
printer print(metadata.load_settings(), BS_APPLICATION_NAME,
BS_SETTINGS_MESSAGE);
print.initialize();
print.settings(stream);
}
static void show_version(std::ostream& stream)
{
stream << format(BS_VERSION_MESSAGE) % LIBBITCOIN_SERVER_VERSION %
LIBBITCOIN_NODE_VERSION % LIBBITCOIN_BLOCKCHAIN_VERSION %
LIBBITCOIN_VERSION << std::endl;
}
static console_result init_chain(const path& directory, bool testnet,
std::ostream& output, std::ostream& error)
{
// TODO: see github.com/bitcoin/bitcoin/issues/432
// Create the directory as a convenience for the user, and then use it
// as sentinel to guard against inadvertent re-initialization.
error_code code;
if (!create_directories(directory, code))
{
if (code.value() == 0)
error << format(BS_INITCHAIN_DIR_EXISTS) % directory << std::endl;
else
error << format(BS_INITCHAIN_DIR_NEW) % directory % code.message()
<< std::endl;
return console_result::failure;
}
output << format(BS_INITIALIZING_CHAIN) % directory << std::endl;
const auto prefix = directory.string();
auto genesis = testnet ? testnet_genesis_block() :
mainnet_genesis_block();
return database::initialize(prefix, genesis) ?
console_result::okay : console_result::failure;
}
static console_result verify_chain(const path& directory, std::ostream& error)
{
// Use missing directory as a sentinel indicating lack of initialization.
error_code code;
if (!exists(directory, code))
{
if (code.value() == 2)
error << format(BS_UNINITIALIZED_CHAIN) % directory << std::endl;
else
error << format(BS_INITCHAIN_DIR_TEST) % directory %
code.message() << std::endl;
return console_result::failure;
}
return console_result::okay;
}
// Static handler for catching termination signals.
static bool stopped = false;
static void interrupt_handler(int code)
{
bc::cout << format(BS_SERVER_STOPPING) % code << std::endl;
stopped = true;
}
// Attach client-server API.
static void attach_api(request_worker& worker, server_node& node,
subscribe_manager& subscriber)
{
typedef std::function<void(server_node&, const incoming_message&,
queue_send_callback)> basic_command_handler;
auto attach = [&worker, &node](const std::string& command,
basic_command_handler handler)
{
worker.attach(command, std::bind(handler, std::ref(node), _1, _2));
};
// Subscriptions.
worker.attach("address.subscribe",
std::bind(&subscribe_manager::subscribe,
&subscriber, _1, _2));
worker.attach("address.renew",
std::bind(&subscribe_manager::renew,
&subscriber, _1, _2));
// Non-subscription API.
attach("address.fetch_history2", server_node::fullnode_fetch_history);
attach("blockchain.fetch_history", blockchain_fetch_history);
attach("blockchain.fetch_transaction", blockchain_fetch_transaction);
attach("blockchain.fetch_last_height", blockchain_fetch_last_height);
attach("blockchain.fetch_block_header", blockchain_fetch_block_header);
////attach("blockchain.fetch_block_transaction_hashes", blockchain_fetch_block_transaction_hashes);
attach("blockchain.fetch_transaction_index", blockchain_fetch_transaction_index);
attach("blockchain.fetch_spend", blockchain_fetch_spend);
attach("blockchain.fetch_block_height", blockchain_fetch_block_height);
attach("blockchain.fetch_stealth", blockchain_fetch_stealth);
attach("protocol.broadcast_transaction", protocol_broadcast_transaction);
attach("protocol.total_connections", protocol_total_connections);
attach("transaction_pool.validate", transaction_pool_validate);
attach("transaction_pool.fetch_transaction", transaction_pool_fetch_transaction);
// Deprecated command, for backward compatibility.
attach("address.fetch_history", COMPAT_fetch_history);
}
// Run the server.
static console_result run(const configuration& config, std::ostream& output,
std::ostream& error)
{
// Ensure the blockchain directory is initialized (at least exists).
const auto result = verify_chain(config.chain.database_path, error);
if (result != console_result::okay)
return result;
output << BS_SERVER_STARTING << std::endl;
server_node server(config);
publisher publish(server, config.server);
if (config.server.publisher_enabled)
{
if (!publish.start())
{
error << format(BS_PUBLISHER_START_FAIL) %
zmq_strerror(zmq_errno()) << std::endl;
return console_result::not_started;
}
}
request_worker worker(config.server);
subscribe_manager subscriber(server, config.server);
if (config.server.queries_enabled)
{
if (!worker.start())
{
error << BS_WORKER_START_FAIL << std::endl;
return console_result::not_started;
}
attach_api(worker, server, subscriber);
}
std::promise<code> start_promise;
const auto handle_start = [&start_promise](const code& ec)
{
start_promise.set_value(ec);
};
server.start(handle_start);
auto ec = start_promise.get_future().get();
if (ec)
{
error << format(BS_SERVER_START_FAIL) % ec.message() << std::endl;
return console_result::not_started;
}
output << BS_SERVER_STARTED << std::endl;
// Catch C signals for stopping the program.
signal(SIGABRT, interrupt_handler);
signal(SIGTERM, interrupt_handler);
signal(SIGINT, interrupt_handler);
// Main loop.
while (!stopped)
worker.update();
// Stop the worker, publisher and node.
if (config.server.queries_enabled)
if (!worker.stop())
error << BS_WORKER_STOP_FAIL << std::endl;
if (config.server.publisher_enabled)
if (!publish.stop())
error << BS_PUBLISHER_STOP_FAIL << std::endl;
std::promise<code> stop_promise;
const auto handle_stop = [&stop_promise](const code& ec)
{
stop_promise.set_value(ec);
};
server.stop(handle_stop);
ec = stop_promise.get_future().get();
if (ec)
error << format(BS_SERVER_STOP_FAIL) % ec.message() << std::endl;
output << BS_SERVER_UNMAPPING << std::endl;
return ec ? console_result::failure : console_result::okay;
}
// Load argument, environment and config and then run the server.
console_result dispatch(int argc, const char* argv[], std::istream&,
std::ostream& output, std::ostream& error)
{
parser parsed;
std::string message;
if (!parser::parse(parsed, message, argc, argv))
{
display_invalid_parameter(error, message);
return console_result::failure;
}
const auto settings = parsed.settings;
if (!settings.file.empty())
output << format(BS_USING_CONFIG_FILE) % settings.file << std::endl;
if (settings.help)
show_help(parsed, output);
else if (settings.settings)
show_settings(parsed, output);
else if (settings.version)
show_version(output);
else if (settings.mainnet)
return init_chain(settings.chain.database_path, false, output, error);
else if (settings.testnet)
return init_chain(settings.chain.database_path, true, output, error);
else
return run(settings, output, error);
return console_result::okay;
}
} // namespace server
} // namespace libbitcoin
<commit_msg>Whitespace/comment.<commit_after>/**
* Copyright (c) 2011-2015 libbitcoin developers (see AUTHORS)
*
* This file is part of libbitcoin-server.
*
* libbitcoin-server is free software: you can redistribute it and/or
* modify it under the terms of the GNU Affero General Public License with
* additional permissions to the one published by the Free Software
* Foundation, either version 3 of the License, or (at your option)
* any later version. For more information see LICENSE.
*
* 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 Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
#include <bitcoin/server/dispatch.hpp>
#include <csignal>
#include <future>
#include <iostream>
#include <boost/format.hpp>
#include <boost/filesystem.hpp>
#include <boost/program_options.hpp>
#include <bitcoin/node.hpp>
#include <bitcoin/server/config/parser.hpp>
#include <bitcoin/server/config/settings.hpp>
#include <bitcoin/server/message.hpp>
#include <bitcoin/server/server_node.hpp>
#include <bitcoin/server/publisher.hpp>
#include <bitcoin/server/subscribe_manager.hpp>
#include <bitcoin/server/version.hpp>
#include <bitcoin/server/worker.hpp>
#include <bitcoin/server/server_node.hpp>
#include <bitcoin/server/service/blockchain.hpp>
#include <bitcoin/server/service/compat.hpp>
#include <bitcoin/server/service/protocol.hpp>
#include <bitcoin/server/service/transaction_pool.hpp>
#define BS_APPLICATION_NAME "bs"
// Localizable messages.
#define BS_SETTINGS_MESSAGE \
"These are the configuration settings that can be set."
#define BS_INFORMATION_MESSAGE \
"Runs a full bitcoin node in the global peer-to-peer network."
#define BS_UNINITIALIZED_CHAIN \
"The %1% directory is not initialized."
#define BS_INITIALIZING_CHAIN \
"Please wait while initializing %1% directory..."
#define BS_INITCHAIN_DIR_NEW \
"Failed to create directory %1% with error, '%2%'."
#define BS_INITCHAIN_DIR_EXISTS \
"Failed because the directory %1% already exists."
#define BS_INITCHAIN_DIR_TEST \
"Failed to test directory %1% with error, '%2%'."
#define BS_SERVER_STARTING \
"Please wait while server is starting."
#define BS_SERVER_START_FAIL \
"Server failed to start with error, %1%."
#define BS_SERVER_STARTED \
"Server started, press CTRL-C to stop."
#define BS_SERVER_STOPPING \
"Please wait while server is stopping (code: %1%)..."
#define BS_SERVER_UNMAPPING \
"Please wait while files are unmapped..."
#define BS_SERVER_STOP_FAIL \
"Server stopped with error, %1%."
#define BS_PUBLISHER_START_FAIL \
"Publisher service failed to start: %1%"
#define BS_PUBLISHER_STOP_FAIL \
"Publisher service failed to stop."
#define BS_WORKER_START_FAIL \
"Query service failed to start."
#define BS_WORKER_STOP_FAIL \
"Query service failed to stop."
#define BS_USING_CONFIG_FILE \
"Using config file: %1%"
#define BS_INVALID_PARAMETER \
"Error: %1%"
#define BS_VERSION_MESSAGE \
"\nVersion Information:\n\n" \
"libbitcoin-server: %1%\n" \
"libbitcoin-node: %2%\n" \
"libbitcoin-blockchain: %3%\n" \
"libbitcoin: %4%"
namespace libbitcoin {
namespace server {
using std::placeholders::_1;
using std::placeholders::_2;
using boost::format;
using namespace bc::blockchain;
using namespace bc::config;
using namespace boost::system;
using namespace boost::filesystem;
static void display_invalid_parameter(std::ostream& stream,
const std::string& message)
{
// English-only hack to patch missing arg name in boost exception message.
std::string clean_message(message);
boost::replace_all(clean_message, "for option is invalid", "is invalid");
stream << format(BS_INVALID_PARAMETER) % clean_message << std::endl;
}
static void show_help(parser& metadata, std::ostream& stream)
{
printer help(metadata.load_options(), metadata.load_arguments(),
BS_APPLICATION_NAME, BS_INFORMATION_MESSAGE);
help.initialize();
help.commandline(stream);
}
static void show_settings(parser& metadata, std::ostream& stream)
{
printer print(metadata.load_settings(), BS_APPLICATION_NAME,
BS_SETTINGS_MESSAGE);
print.initialize();
print.settings(stream);
}
static void show_version(std::ostream& stream)
{
stream << format(BS_VERSION_MESSAGE) % LIBBITCOIN_SERVER_VERSION %
LIBBITCOIN_NODE_VERSION % LIBBITCOIN_BLOCKCHAIN_VERSION %
LIBBITCOIN_VERSION << std::endl;
}
static console_result init_chain(const path& directory, bool testnet,
std::ostream& output, std::ostream& error)
{
// TODO: see github.com/bitcoin/bitcoin/issues/432
// Create the directory as a convenience for the user, and then use it
// as sentinel to guard against inadvertent re-initialization.
error_code code;
if (!create_directories(directory, code))
{
if (code.value() == 0)
error << format(BS_INITCHAIN_DIR_EXISTS) % directory << std::endl;
else
error << format(BS_INITCHAIN_DIR_NEW) % directory % code.message()
<< std::endl;
return console_result::failure;
}
output << format(BS_INITIALIZING_CHAIN) % directory << std::endl;
const auto prefix = directory.string();
auto genesis = testnet ? testnet_genesis_block() :
mainnet_genesis_block();
return database::initialize(prefix, genesis) ?
console_result::okay : console_result::failure;
}
static console_result verify_chain(const path& directory, std::ostream& error)
{
// Use missing directory as a sentinel indicating lack of initialization.
error_code code;
if (!exists(directory, code))
{
if (code.value() == 2)
error << format(BS_UNINITIALIZED_CHAIN) % directory << std::endl;
else
error << format(BS_INITCHAIN_DIR_TEST) % directory %
code.message() << std::endl;
return console_result::failure;
}
return console_result::okay;
}
// Static handler for catching termination signals.
static bool stopped = false;
static void interrupt_handler(int code)
{
bc::cout << format(BS_SERVER_STOPPING) % code << std::endl;
stopped = true;
}
// Attach client-server API.
static void attach_api(request_worker& worker, server_node& node,
subscribe_manager& subscriber)
{
typedef std::function<void(server_node&, const incoming_message&,
queue_send_callback)> basic_command_handler;
auto attach = [&worker, &node](const std::string& command,
basic_command_handler handler)
{
worker.attach(command, std::bind(handler, std::ref(node), _1, _2));
};
// Subscriptions.
worker.attach("address.subscribe",
std::bind(&subscribe_manager::subscribe,
&subscriber, _1, _2));
worker.attach("address.renew",
std::bind(&subscribe_manager::renew,
&subscriber, _1, _2));
// Non-subscription API.
attach("address.fetch_history2", server_node::fullnode_fetch_history);
attach("blockchain.fetch_history", blockchain_fetch_history);
attach("blockchain.fetch_transaction", blockchain_fetch_transaction);
attach("blockchain.fetch_last_height", blockchain_fetch_last_height);
attach("blockchain.fetch_block_header", blockchain_fetch_block_header);
////attach("blockchain.fetch_block_transaction_hashes", blockchain_fetch_block_transaction_hashes);
attach("blockchain.fetch_transaction_index", blockchain_fetch_transaction_index);
attach("blockchain.fetch_spend", blockchain_fetch_spend);
attach("blockchain.fetch_block_height", blockchain_fetch_block_height);
attach("blockchain.fetch_stealth", blockchain_fetch_stealth);
attach("protocol.broadcast_transaction", protocol_broadcast_transaction);
attach("protocol.total_connections", protocol_total_connections);
attach("transaction_pool.validate", transaction_pool_validate);
attach("transaction_pool.fetch_transaction", transaction_pool_fetch_transaction);
// Deprecated command, for backward compatibility.
attach("address.fetch_history", COMPAT_fetch_history);
}
// Run the server.
static console_result run(const configuration& config, std::ostream& output,
std::ostream& error)
{
// Ensure the blockchain directory is initialized (at least exists).
const auto result = verify_chain(config.chain.database_path, error);
if (result != console_result::okay)
return result;
output << BS_SERVER_STARTING << std::endl;
server_node server(config);
std::promise<code> start_promise;
const auto handle_start = [&start_promise](const code& ec)
{
start_promise.set_value(ec);
};
// Logging initialized here.
server.start(handle_start);
auto ec = start_promise.get_future().get();
if (ec)
{
error << format(BS_SERVER_START_FAIL) % ec.message() << std::endl;
return console_result::not_started;
}
publisher publish(server, config.server);
if (config.server.publisher_enabled)
{
if (!publish.start())
{
error << format(BS_PUBLISHER_START_FAIL) %
zmq_strerror(zmq_errno()) << std::endl;
return console_result::not_started;
}
}
request_worker worker(config.server);
subscribe_manager subscriber(server, config.server);
if (config.server.queries_enabled)
{
if (!worker.start())
{
error << BS_WORKER_START_FAIL << std::endl;
return console_result::not_started;
}
attach_api(worker, server, subscriber);
}
output << BS_SERVER_STARTED << std::endl;
// Catch C signals for stopping the program.
signal(SIGABRT, interrupt_handler);
signal(SIGTERM, interrupt_handler);
signal(SIGINT, interrupt_handler);
// Main loop.
while (!stopped)
worker.update();
// Stop the worker, publisher and node.
if (config.server.queries_enabled)
if (!worker.stop())
error << BS_WORKER_STOP_FAIL << std::endl;
if (config.server.publisher_enabled)
if (!publish.stop())
error << BS_PUBLISHER_STOP_FAIL << std::endl;
std::promise<code> stop_promise;
const auto handle_stop = [&stop_promise](const code& ec)
{
stop_promise.set_value(ec);
};
server.stop(handle_stop);
ec = stop_promise.get_future().get();
if (ec)
error << format(BS_SERVER_STOP_FAIL) % ec.message() << std::endl;
output << BS_SERVER_UNMAPPING << std::endl;
return ec ? console_result::failure : console_result::okay;
}
// Load argument, environment and config and then run the server.
console_result dispatch(int argc, const char* argv[], std::istream&,
std::ostream& output, std::ostream& error)
{
parser parsed;
std::string message;
if (!parser::parse(parsed, message, argc, argv))
{
display_invalid_parameter(error, message);
return console_result::failure;
}
const auto settings = parsed.settings;
if (!settings.file.empty())
output << format(BS_USING_CONFIG_FILE) % settings.file << std::endl;
if (settings.help)
show_help(parsed, output);
else if (settings.settings)
show_settings(parsed, output);
else if (settings.version)
show_version(output);
else if (settings.mainnet)
return init_chain(settings.chain.database_path, false, output, error);
else if (settings.testnet)
return init_chain(settings.chain.database_path, true, output, error);
else
return run(settings, output, error);
return console_result::okay;
}
} // namespace server
} // namespace libbitcoin
<|endoftext|> |
<commit_before>// Copyright 2014 Tom Regan
//
// 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 "encodings.h"
namespace encodings {
namespace binary {
void print_byte(uint8_t byte) {
for (auto i = 0x80; i; i = i >> 1) {
std::cout << (((byte & i) == i) ? "1" : "0");
}
std::cout << '\n';
}
void print_double(uint32_t bits) {
for (uint32_t i = 0x80000000; i; i = i >> 1) {
if (i == 0x80 || i == 0x8000 || i == 0x800000) {
std::cout << ' ';
}
std::cout << (((bits & i) == i) ? "1" : "0");
}
std::cout << '\n';
}
} // binary
namespace base64 {
uint8_t to_byte(uint8_t byte) {
if (byte == '+') {
return 62;
} else if (byte == '/') {
return 63;
} else if (byte < 58) {
return byte + 4;
} else if (byte < 91) {
return byte - 65;
}
return byte - 71;
}
uint8_t from_byte(uint8_t byte) {
if (byte < 26) {
return byte + 65; // ascii A
} else if (byte < 52) {
return byte + 71; // ascii a
} else if (byte < 62) {
return byte - 4; // ascii 0
} else if (byte == 62) {
return '+';
}
return '/';
}
std::string from_hex(std::string hex_string) {
auto buffer = std::stringstream();
while (!hex_string.empty()) {
uint32_t bitset = std::stoul(hex_string.substr(0, 6), 0, 16);
hex_string.erase(0, 6);
while (!(bitset & 0x00ff0000)) {
bitset <<= 8;
}
uint8_t bytemask = 0x3f;
if (bitset & 0x00fc0000) {
buffer << from_byte((bitset >> 18) & bytemask);
}
if (bitset & 0x0003f000) {
buffer << from_byte((bitset >> 12) & bytemask) ;
}
if (bitset & 0x00000fc0) {
buffer << from_byte((bitset >> 6) & bytemask);
}
if (bitset & 0x0000003f) {
buffer << from_byte(bitset & bytemask);
}
while (buffer.str().size() % 4) {
buffer << '=';
}
}
return buffer.str();
}
} // base64
namespace hex {
std::string from_base64(std::string base64_string) {
auto buffer = std::stringstream();
while (base64_string.size()) {
std::string dword = base64_string.substr(0, 4);
base64_string.erase(0, 4);
uint32_t bitset = base64::to_byte(dword[0]);
bitset <<=6;
bitset |= base64::to_byte(dword[1]);
bitset <<= 6;
bitset |= base64::to_byte(dword[2]);
bitset <<=6;
bitset |= base64::to_byte(dword[3]);
if (dword[2] == '=' && dword[3] == '=') {
bitset >>= 16;
}
else if (dword[3] == '=') {
bitset >>= 8;
}
buffer << std::hex << bitset;
}
return buffer.str();
}
} // hex
} // encodings
<commit_msg>simplify the base64 logic minutely<commit_after>// Copyright 2014 Tom Regan
//
// 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 "encodings.h"
namespace encodings {
namespace binary {
void print_byte(uint8_t byte) {
for (auto i = 0x80; i; i = i >> 1) {
std::cout << (((byte & i) == i) ? "1" : "0");
}
std::cout << '\n';
}
void print_double(uint32_t bits) {
for (uint32_t i = 0x80000000; i; i = i >> 1) {
if (i == 0x80 || i == 0x8000 || i == 0x800000) {
std::cout << ' ';
}
std::cout << (((bits & i) == i) ? "1" : "0");
}
std::cout << '\n';
}
} // binary
namespace base64 {
uint8_t to_byte(uint8_t byte) {
if (byte == '+') {
return 62;
} else if (byte == '/') {
return 63;
} else if (byte < 58) {
return byte + 4;
} else if (byte < 91) {
return byte - 65;
}
return byte - 71;
}
uint8_t from_byte(uint8_t byte) {
if (byte < 26) {
return byte + 65; // ascii A
} else if (byte < 52) {
return byte + 71; // ascii a
} else if (byte < 62) {
return byte - 4; // ascii 0
} else if (byte == 62) {
return '+';
}
return '/';
}
std::string from_hex(std::string hex_string) {
auto buffer = std::stringstream();
while (!hex_string.empty()) {
uint32_t bitset = std::stoul(hex_string.substr(0, 6), 0, 16);
hex_string.erase(0, 6);
while (!(bitset & 0x00ff0000)) {
bitset <<= 8;
}
uint8_t bytemask = 0x3f;
buffer << from_byte((bitset >> 18) & bytemask);
buffer << from_byte((bitset >> 12) & bytemask);
if (bitset & 0x00000fc0) {
buffer << from_byte((bitset >> 6) & bytemask);
if (bitset & 0x0000003f) {
buffer << from_byte(bitset & bytemask);
}
}
while (buffer.str().size() % 4) {
buffer << '=';
}
}
return buffer.str();
}
} // base64
namespace hex {
std::string from_base64(std::string base64_string) {
auto buffer = std::stringstream();
while (base64_string.size()) {
std::string dword = base64_string.substr(0, 4);
base64_string.erase(0, 4);
uint32_t bitset = base64::to_byte(dword[0]);
bitset <<=6;
bitset |= base64::to_byte(dword[1]);
bitset <<= 6;
bitset |= base64::to_byte(dword[2]);
bitset <<=6;
bitset |= base64::to_byte(dword[3]);
if (dword[2] == '=' && dword[3] == '=') {
bitset >>= 16;
}
else if (dword[3] == '=') {
bitset >>= 8;
}
buffer << std::hex << bitset;
}
return buffer.str();
}
} // hex
} // encodings
<|endoftext|> |
<commit_before>/*
* Copyright 2007-2018 Content Management AG
* All rights reserved.
*
* author: Max Kellermann <mk@cm4all.com>
*
* 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
* FOUNDATION 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.
*/
#pragma once
#include "FilteredSocket.hxx"
#include "lease.hxx"
/**
* Wrapper for a #FilteredSocket which may be released at some point.
* After that, remaining data in the input buffer can still be read.
*/
class FilteredSocketLease {
FilteredSocket *const socket;
struct lease_ref lease_ref;
public:
template<typename F>
FilteredSocketLease(EventLoop &event_loop,
SocketDescriptor fd, FdType fd_type,
Lease &lease,
const struct timeval *read_timeout,
const struct timeval *write_timeout,
F &&filter,
BufferedSocketHandler &handler) noexcept
:socket(new FilteredSocket(event_loop))
{
socket->Init(fd, fd_type, read_timeout, write_timeout,
std::forward<F>(filter),
handler);
lease_ref.Set(lease);
}
~FilteredSocketLease() noexcept;
EventLoop &GetEventLoop() noexcept {
return socket->GetEventLoop();
}
gcc_pure
bool IsConnected() const noexcept {
return socket->IsConnected();
}
gcc_pure
bool HasFilter() const noexcept {
assert(!IsReleased());
return socket->HasFilter();
}
#ifndef NDEBUG
gcc_pure
bool HasEnded() const noexcept {
assert(!IsReleased());
return socket->ended;
}
#endif
void Release(bool reuse) noexcept;
#ifndef NDEBUG
bool IsReleased() const noexcept {
return lease_ref.released;
}
#endif
gcc_pure
FdType GetType() const noexcept {
assert(!IsReleased());
return socket->GetType();
}
void SetDirect(bool _direct) noexcept {
assert(!IsReleased());
socket->SetDirect(_direct);
}
int AsFD() noexcept {
assert(!IsReleased());
return socket->AsFD();
}
gcc_pure
bool IsEmpty() const noexcept;
gcc_pure
size_t GetAvailable() const noexcept;
WritableBuffer<void> ReadBuffer() const noexcept;
void Consumed(size_t nbytes) noexcept;
bool Read(bool expect_more) noexcept;
void ScheduleReadTimeout(bool expect_more,
const struct timeval *timeout) noexcept {
assert(!IsReleased());
socket->ScheduleReadTimeout(expect_more, timeout);
}
void ScheduleReadNoTimeout(bool expect_more) noexcept {
assert(!IsReleased());
socket->ScheduleReadNoTimeout(expect_more);
}
ssize_t Write(const void *data, size_t size) noexcept {
assert(!IsReleased());
return socket->Write(data, size);
}
void ScheduleWrite() noexcept {
assert(!IsReleased());
socket->ScheduleWrite();
}
void UnscheduleWrite() noexcept {
assert(!IsReleased());
socket->UnscheduleWrite();
}
ssize_t WriteV(const struct iovec *v, size_t n) noexcept {
assert(!IsReleased());
return socket->WriteV(v, n);
}
ssize_t WriteFrom(int fd, FdType fd_type, size_t length) noexcept {
assert(!IsReleased());
return socket->WriteFrom(fd, fd_type, length);
}
};
<commit_msg>fs/Lease: remove bogus assertions<commit_after>/*
* Copyright 2007-2018 Content Management AG
* All rights reserved.
*
* author: Max Kellermann <mk@cm4all.com>
*
* 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
* FOUNDATION 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.
*/
#pragma once
#include "FilteredSocket.hxx"
#include "lease.hxx"
/**
* Wrapper for a #FilteredSocket which may be released at some point.
* After that, remaining data in the input buffer can still be read.
*/
class FilteredSocketLease {
FilteredSocket *const socket;
struct lease_ref lease_ref;
public:
template<typename F>
FilteredSocketLease(EventLoop &event_loop,
SocketDescriptor fd, FdType fd_type,
Lease &lease,
const struct timeval *read_timeout,
const struct timeval *write_timeout,
F &&filter,
BufferedSocketHandler &handler) noexcept
:socket(new FilteredSocket(event_loop))
{
socket->Init(fd, fd_type, read_timeout, write_timeout,
std::forward<F>(filter),
handler);
lease_ref.Set(lease);
}
~FilteredSocketLease() noexcept;
EventLoop &GetEventLoop() noexcept {
return socket->GetEventLoop();
}
gcc_pure
bool IsConnected() const noexcept {
return socket->IsConnected();
}
gcc_pure
bool HasFilter() const noexcept {
assert(!IsReleased());
return socket->HasFilter();
}
#ifndef NDEBUG
gcc_pure
bool HasEnded() const noexcept {
assert(!IsReleased());
return socket->ended;
}
#endif
void Release(bool reuse) noexcept;
#ifndef NDEBUG
bool IsReleased() const noexcept {
return lease_ref.released;
}
#endif
gcc_pure
FdType GetType() const noexcept {
assert(!IsReleased());
return socket->GetType();
}
void SetDirect(bool _direct) noexcept {
assert(!IsReleased());
socket->SetDirect(_direct);
}
int AsFD() noexcept {
assert(!IsReleased());
return socket->AsFD();
}
gcc_pure
bool IsEmpty() const noexcept;
gcc_pure
size_t GetAvailable() const noexcept;
WritableBuffer<void> ReadBuffer() const noexcept;
void Consumed(size_t nbytes) noexcept;
bool Read(bool expect_more) noexcept;
void ScheduleReadTimeout(bool expect_more,
const struct timeval *timeout) noexcept {
socket->ScheduleReadTimeout(expect_more, timeout);
}
void ScheduleReadNoTimeout(bool expect_more) noexcept {
socket->ScheduleReadNoTimeout(expect_more);
}
ssize_t Write(const void *data, size_t size) noexcept {
assert(!IsReleased());
return socket->Write(data, size);
}
void ScheduleWrite() noexcept {
assert(!IsReleased());
socket->ScheduleWrite();
}
void UnscheduleWrite() noexcept {
assert(!IsReleased());
socket->UnscheduleWrite();
}
ssize_t WriteV(const struct iovec *v, size_t n) noexcept {
assert(!IsReleased());
return socket->WriteV(v, n);
}
ssize_t WriteFrom(int fd, FdType fd_type, size_t length) noexcept {
assert(!IsReleased());
return socket->WriteFrom(fd, fd_type, length);
}
};
<|endoftext|> |
<commit_before>#include "../include/configurator.h"
#include "../include/obj.hpp"
GameMap::GameMap(Texture &image) {
sprite_.setTexture(image);
sprite_.scale(SCALE_X, SCALE_Y);
maxX_ = maxY_ = grassNum_ = 0;
}
GameMap::~GameMap() {
for (unsigned int i = 0; i <= maxX_; ++i)
delete [] pMap_[i];
for (unsigned int i = 0; i <= grassNum_; ++i)
delete [] gMap_[i];
delete [] pMap_;
delete [] gMap_;
}
bool GameMap::loadMap(std::string path) {
std::string tempMap_;
unsigned int count = 0;
maxX_ = atoi(configurator(path, "max_x", "", false).c_str());
maxY_ = atoi(configurator(path, "max_y", "", false).c_str());
nextLevelPath_ = configurator(path, "next_level", "", false);
tempMap_ = configurator(path, "map", "", false);
pMap_ = new char* [maxX_ + 1];
for (unsigned int i = 0; i <= maxX_; ++i)
pMap_[i] = new char [maxY_ + 1];
for (unsigned int j = 0; j < maxY_; ++j) // Загрузка карты в массив
for (unsigned int i = 0; i < maxX_; ++i)
{
while ((tempMap_[count] < 'a') || (tempMap_[count] > 'z')) // Чтобы не влезла разная кака на карту
count++;
if (tempMap_[count] == 'g') // Подсчёт кол-ва травы
grassNum_++;
if (tempMap_[count] == 'e')
{
eaglePos_.posX = i;
eaglePos_.posY = j;
}
pMap_[i][j] = tempMap_[count];
count++;
}
gMap_ = new unsigned int* [grassNum_ + 1];
for (unsigned int i = 0; i <= grassNum_; ++i)
gMap_[i] = new unsigned int [2];
count = 0;
for (unsigned int i = 0; i < maxX_; ++i)
for (unsigned int j = 0; j < maxY_; ++j)
if (pMap_[i][j] == 'g')
{
gMap_[count][0] = i;
gMap_[count][1] = j;
count++;
}
return true;
}
char GameMap::getElement(unsigned int x, unsigned int y)
{
return pMap_[x][y];
}
void GameMap::draw(RenderWindow &window)
{
window.clear(Color(0,0,0));
for (unsigned int j = 0; j < maxY_; ++j)
{
for (unsigned int i = 0; i < maxX_; ++i)
{
if (pMap_[i][j] == 'w') // Кирпичная стена
sprite_.setTextureRect(IntRect(256, 0, 16, 16));
else if (pMap_[i][j] == 'a') // Бронь
sprite_.setTextureRect(IntRect(256, 16, 16, 16));
else if (pMap_[i][j] == 'v') // Вода
sprite_.setTextureRect(IntRect(256, 32, 16, 16));
else if (pMap_[i][j] == 'i') // Лёд, я полагаю...
sprite_.setTextureRect(IntRect(288, 32, 16, 16));
else if (pMap_[i][j] == 'e') // Орёл
sprite_.setTextureRect(IntRect(304, 32, 16, 16));
else
continue;
sprite_.setPosition(i * (16 * SCALE_X), j * (16 * SCALE_Y)) ;
window.draw(sprite_);
}
}
}
void GameMap::drawGrass(RenderWindow &window)
{
sprite_.setTextureRect(IntRect(272, 32, 16, 16));
for (unsigned int i = 0; i < grassNum_; ++i)
{
sprite_.setPosition(gMap_[i][0] * (16 * SCALE_X), gMap_[i][1] * (16 * SCALE_Y)) ;
window.draw(sprite_);
}
}
void GameMap::randomMap(){
char block;
int arm = 3;
int grass = 7;
int wall = 10;
int ice = 6;
int water = 5;
int eagle = 1;
bool temp;
int rnd;
for (int j = 0; j < maxY_; ++j)
{
for (int i = 0; i < maxX_; ++i)
{
GameMap::setElement('s', j, i);
}
}
for (int j = 0; j < maxY_; ++j)
{
for (int i = 0; i < maxX_; ++i)
{
temp = true;
if (((j == 0) && (i==0)) || ((j == 0) && (i==6)) || ((j == 0) && (i == 12)) || ((j == 12) && (i == 4)) || ((j == 12) && (i == 8)))
{
block = 's';
} else {
while(temp) {
rnd = rand()%5;
switch(rnd){
case 0:
if (arm >0)
{
arm--;
block = 'a';
}
temp = false;
break;
case 1:
if (grass >0)
{
grass--;
block = 'g';
}
temp = false;
break;
case 2:
if (wall >0)
{
wall--;
block = 'w';
}
temp = false;
break;
case 3:
if (ice >0)
{
ice--;
block = 'i';
}
temp = false;
break;
case 4:
if (water >0)
{
water--;
block = 'w';
}
temp = false;
break;
}
}
}
GameMap::setElement(block, j, i);
}
}
}
unsigned int GameMap::getMaxX()
{
return maxX_;
}
unsigned int GameMap::getMaxY()
{
return maxY_;
}
void GameMap::setElement(char l_char, unsigned int x, unsigned int y)
{
pMap_[x][y] = l_char;
}
coordinate GameMap::getEaglePos()
{
return eaglePos_;
}<commit_msg>fix random maps<commit_after>#include "../include/configurator.h"
#include "../include/obj.hpp"
GameMap::GameMap(Texture &image) {
sprite_.setTexture(image);
sprite_.scale(SCALE_X, SCALE_Y);
maxX_ = maxY_ = grassNum_ = 0;
}
GameMap::~GameMap() {
for (unsigned int i = 0; i <= maxX_; ++i)
delete [] pMap_[i];
for (unsigned int i = 0; i <= grassNum_; ++i)
delete [] gMap_[i];
delete [] pMap_;
delete [] gMap_;
}
bool GameMap::loadMap(std::string path) {
std::string tempMap_;
unsigned int count = 0;
maxX_ = atoi(configurator(path, "max_x", "", false).c_str());
maxY_ = atoi(configurator(path, "max_y", "", false).c_str());
nextLevelPath_ = configurator(path, "next_level", "", false);
tempMap_ = configurator(path, "map", "", false);
pMap_ = new char* [maxX_ + 1];
for (unsigned int i = 0; i <= maxX_; ++i)
pMap_[i] = new char [maxY_ + 1];
for (unsigned int j = 0; j < maxY_; ++j) // Загрузка карты в массив
for (unsigned int i = 0; i < maxX_; ++i)
{
while ((tempMap_[count] < 'a') || (tempMap_[count] > 'z')) // Чтобы не влезла разная кака на карту
count++;
if (tempMap_[count] == 'g') // Подсчёт кол-ва травы
grassNum_++;
if (tempMap_[count] == 'e')
{
eaglePos_.posX = i;
eaglePos_.posY = j;
}
pMap_[i][j] = tempMap_[count];
count++;
}
gMap_ = new unsigned int* [grassNum_ + 1];
for (unsigned int i = 0; i <= grassNum_; ++i)
gMap_[i] = new unsigned int [2];
count = 0;
for (unsigned int i = 0; i < maxX_; ++i)
for (unsigned int j = 0; j < maxY_; ++j)
if (pMap_[i][j] == 'g')
{
gMap_[count][0] = i;
gMap_[count][1] = j;
count++;
}
return true;
}
char GameMap::getElement(unsigned int x, unsigned int y)
{
return pMap_[x][y];
}
void GameMap::draw(RenderWindow &window)
{
window.clear(Color(0,0,0));
for (unsigned int j = 0; j < maxY_; ++j)
{
for (unsigned int i = 0; i < maxX_; ++i)
{
if (pMap_[i][j] == 'w') // Кирпичная стена
sprite_.setTextureRect(IntRect(256, 0, 16, 16));
else if (pMap_[i][j] == 'a') // Бронь
sprite_.setTextureRect(IntRect(256, 16, 16, 16));
else if (pMap_[i][j] == 'v') // Вода
sprite_.setTextureRect(IntRect(256, 32, 16, 16));
else if (pMap_[i][j] == 'i') // Лёд, я полагаю...
sprite_.setTextureRect(IntRect(288, 32, 16, 16));
else if (pMap_[i][j] == 'e') // Орёл
sprite_.setTextureRect(IntRect(304, 32, 16, 16));
else
continue;
sprite_.setPosition(i * (16 * SCALE_X), j * (16 * SCALE_Y)) ;
window.draw(sprite_);
}
}
}
void GameMap::drawGrass(RenderWindow &window)
{
sprite_.setTextureRect(IntRect(272, 32, 16, 16));
for (unsigned int i = 0; i < grassNum_; ++i)
{
sprite_.setPosition(gMap_[i][0] * (16 * SCALE_X), gMap_[i][1] * (16 * SCALE_Y)) ;
window.draw(sprite_);
}
}
void GameMap::randomMap(){
char block;
int arm = 5;
int grass = 7;
int wall = 50;
int ice = 10;
int water = 10;
int eagle = 1;
bool temp;
int rnd;
gMap_ = new unsigned int* [grass + 1];
for (unsigned int i = 0; i <= grass; ++i)
gMap_[i] = new unsigned int [2];
for (int j = 0; j < maxY_; ++j)
{
for (int i = 0; i < maxX_; ++i)
{
GameMap::setElement('s', j, i); // очистка карты
}
}
for (int j = 0; j < maxY_; ++j)
{
for (int i = 0; i < maxX_; ++i)
{
temp = true;
if (((j == 0) && (i==0)) || ((j == 6) && (i==0)) || ((j == 12) && (i == 0)) || ((j == 4) && (i == 12)) || ((j == 8) && (i == 12))) // точки респа стандартно пусты
{
block = 's';
} else {
while(temp) { // пока чем-то не заполним (если рандом выпал, а блоков этого типа уже не надо)
rnd = rand()%6;
switch(rnd){ // рандомно заполняем карту
case 0:
if (arm >0)
{
arm--;
block = 'a';
temp = false;
}
break;
case 1:
if (grass >0)
{
grass--;
block = 'g';
temp = false;
}
break;
case 2:
if (wall >0)
{
wall--;
block = 'w';
temp = false;
}
break;
case 3:
if (ice >0)
{
ice--;
block = 'i';
temp = false;
}
break;
case 4:
if (water >0)
{
water--;
block = 'w';
temp = false;
}
break;
case 5:
block = 's';
temp = false;
break;
}
}
}
GameMap::setElement(block, j, i);
}
}
GameMap::setElement('e', (rand()%(maxY_-2)+1), (rand()%maxX_)); // спавн орла, верняя и нижняя линии не используются чтоб не пересекться с спавнами остальных
rnd = 0;
for (unsigned int i = 0; i < maxX_; ++i)
for (unsigned int j = 0; j < maxY_; ++j)
if (pMap_[i][j] == 'g')
{
gMap_[rnd][0] = i;
gMap_[rnd][1] = j;
rnd++;
}
}
unsigned int GameMap::getMaxX()
{
return maxX_;
}
unsigned int GameMap::getMaxY()
{
return maxY_;
}
void GameMap::setElement(char l_char, unsigned int x, unsigned int y)
{
pMap_[x][y] = l_char;
}
coordinate GameMap::getEaglePos()
{
return eaglePos_;
}<|endoftext|> |
<commit_before>/* Copyright 2012 Brian Ellis
*
* 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 <QtGui>
#include <QtOpenGL>
#include <math.h>
#include "gl_widget.h"
#include "block_manager.h"
#include "diagram.h"
#include "matrix.h"
#include "skybox_renderable.h"
#include "texture.h"
#ifndef GL_MULTISAMPLE_ARB
#define GL_MULTISAMPLE_ARB 0x809D
#endif
#ifndef GL_SAMPLE_ALPHA_TO_COVERAGE_ARB
#define GL_SAMPLE_ALPHA_TO_COVERAGE_ARB 0x809E
#endif
#define DEG_TO_RAD(x) ((x) * M_PI / 180.0f)
GLWidget::GLWidget(QWidget* parent)
: QGLWidget(QGLFormat(QGL::SampleBuffers), parent),
diagram_(NULL),
block_mgr_(NULL),
frame_rate_enabled_(false),
frame_rate_(-1.0f),
scene_dirty_(true) {
setFocusPolicy(Qt::WheelFocus);
QGLFormat f = format();
f.setSwapInterval(1);
setFormat(f);
connect(&frame_timer_, SIGNAL(timeout()), SLOT(updateGL()));
#ifdef NDEBUG
frame_timer_.setDebugMode(false);
#endif
}
GLWidget::~GLWidget() {
}
void GLWidget::setDiagram(Diagram* diagram) {
diagram_ = diagram;
connect(diagram_, SIGNAL(diagramChanged(BlockTransaction)), SLOT(setSceneDirty()));
connect(diagram_, SIGNAL(ephemeralBlocksChanged(BlockTransaction)), SLOT(setSceneDirty()));
}
void GLWidget::setBlockManager(BlockManager* block_mgr) {
block_mgr_ = block_mgr;
}
QSize GLWidget::minimumSizeHint() const {
return QSize(50, 50);
}
QSize GLWidget::sizeHint() const {
return QSize(600, 400);
}
void GLWidget::setSceneDirty(bool dirty) {
scene_dirty_ = dirty;
if (dirty) {
updateGL();
}
}
void GLWidget::initializeGL() {
qglClearColor(QColor(128, 192, 255));
glEnable(GL_DEPTH_TEST);
glEnable(GL_CULL_FACE);
glEnable(GL_BLEND);
glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA);
glEnable(GL_TEXTURE_2D);
glShadeModel(GL_SMOOTH);
glEnable(GL_MULTISAMPLE_ARB);
glEnable(GL_SAMPLE_ALPHA_TO_COVERAGE_ARB);
glAlphaFunc(GL_GREATER, 0.01);
glEnable(GL_ALPHA_TEST);
glEnable(GL_LIGHTING);
glEnable(GL_LIGHT0);
glEnable(GL_FOG);
glFogf(GL_FOG_MODE, GL_LINEAR);
static GLfloat fog_color[] = { 0.5f, 0.75f, 1.0f, 1.0f };
glFogfv(GL_FOG_COLOR, fog_color);
glFogf(GL_FOG_START, 50);
glFogf(GL_FOG_END, 100);
// glEnable(GL_LIGHT1);
static GLfloat light_position[4] = { 0.5, 0.0, 0.0, 1.0 };
static GLfloat light_ambient_intensity[4] = { 0.0, 0.0, 0.0, 1.0 };
static GLfloat light_diffuse_intensity[4] = { 2.0, 2.0, 2.0, 1.0 };
glLightfv(GL_LIGHT0, GL_POSITION, light_position);
glLightfv(GL_LIGHT0, GL_AMBIENT, light_ambient_intensity);
glLightfv(GL_LIGHT0, GL_DIFFUSE, light_diffuse_intensity);
glLightf(GL_LIGHT0, GL_QUADRATIC_ATTENUATION, 0.1f);
GLfloat global_ambient[] = { 0.0f, 0.0f, 0.0f, 1.0f };
glLightModelfv(GL_LIGHT_MODEL_AMBIENT, global_ambient);
ground_plane_display_list_ = glGenLists(1);
scene_display_list_ = glGenLists(2);
glNewList(ground_plane_display_list_, GL_COMPILE);
glPushMatrix();
glTranslatef(-50.0f, -1 / 256, -50.0f);
for (int i = 0; i < 100; ++i) {
glBegin(GL_QUAD_STRIP);
glVertex3f(i, 0, 0);
glVertex3f(i + 1.0f, 0, 0);
for (int j = 0; j < 100; ++j) {
glVertex3f(i, 0, j + 1.0f);
glVertex3f(i + 1.0f, 0, j + 1.0f);
}
glEnd();
}
glPopMatrix();
glEndList();
skybox_.reset(new SkyboxRenderable(QVector3D(10.0f, 10.0f, 10.0f)));
skybox_->initialize();
Texture skybox_up = Texture(this, ":/skybox_up.png");
Texture skybox_out = Texture(this, ":/skybox_east.png");
Texture skybox_down = Texture(this, ":/skybox_down.png");
skybox_->setTexture(kFrontFace, skybox_out);
skybox_->setTexture(kLeftFace, skybox_out);
skybox_->setTexture(kRightFace, skybox_out);
skybox_->setTexture(kBackFace, skybox_out);
skybox_->setTexture(kTopFace, skybox_up);
skybox_->setTexture(kBottomFace, skybox_down);
camera_.translate(QVector3D(0.5, 1, 5));
}
void GLWidget::drawSkybox() {
glPushMatrix();
glLoadIdentity();
camera_.applyRotation();
glPushAttrib(GL_LIGHTING_BIT | GL_DEPTH_BITS | GL_FOG_BIT | GL_ENABLE_BIT);
glDisable(GL_LIGHTING);
glDisable(GL_FOG);
glDisable(GL_DEPTH_TEST);
glDisable(GL_CULL_FACE);
skybox_->renderAt(QVector3D(0, 0, 0), BlockOrientation::noOrientation());
glPopAttrib();
glPopMatrix();
}
void GLWidget::updateScene() {
if (!diagram_) {
return;
}
glNewList(scene_display_list_, GL_COMPILE_AND_EXECUTE);
// Draw the ground plane.
glPushAttrib(GL_LIGHTING_BIT | GL_CURRENT_BIT | GL_ENABLE_BIT);
glDisable(GL_CULL_FACE);
GLfloat color[] = {0, 1, 0, 0.5};
glMaterialfv(GL_FRONT_AND_BACK, GL_AMBIENT_AND_DIFFUSE, color);
glCallList(ground_plane_display_list_);
glDisable(GL_LIGHTING);
glDisable(GL_MULTISAMPLE_ARB);
glDisable(GL_SAMPLE_ALPHA_TO_COVERAGE_ARB);
glBindTexture(GL_TEXTURE_2D, NULL);
glColor4f(1, 1, 1, 0.1);
glPolygonMode( GL_FRONT_AND_BACK, GL_LINE );
glPushMatrix();
glTranslatef(0, 0.01f, 0);
glCallList(ground_plane_display_list_);
glPopMatrix();
glPolygonMode( GL_FRONT_AND_BACK, GL_FILL );
glPopAttrib();
diagram_->render();
glEndList();
}
void GLWidget::paintGL() {
glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
applyPressedKeys();
// Handle frame rate display.
if (frame_rate_enabled_) {
static const int kFrameRateSampleCount = 60;
float elapsed_time = time_since_last_frame_.elapsed() / 1000.0f; // seconds
frame_rate_queue_.enqueue(elapsed_time);
while (frame_rate_queue_.size() > kFrameRateSampleCount) {
frame_rate_queue_.dequeue();
}
float average_frame_time = 0.0f;
foreach(float sample, frame_rate_queue_) {
average_frame_time += sample;
}
average_frame_time /= frame_rate_queue_.size();
frame_rate_ = 1.0f / average_frame_time;
emit frameRateChanged(QString::number(frame_rate_, 'g', 4));
}
time_since_last_frame_.start();
camera_.apply();
static GLfloat light_position[4] = { 0.0, 10.0, 5.0, 0.0 };
static GLfloat light_ambient_intensity[4] = { 3, 3, 3, 1.0 };
static GLfloat light_diffuse_intensity[4] = { 0.8, 0.8, 0.8, 1.0 };
glLightfv(GL_LIGHT0, GL_POSITION, light_position);
glLightfv(GL_LIGHT0, GL_AMBIENT, light_ambient_intensity);
glLightfv(GL_LIGHT0, GL_DIFFUSE, light_diffuse_intensity);
// Can't put this in the display list or it doesn't rotate correctly.
drawSkybox();
if (scene_dirty_) {
updateScene();
scene_dirty_ = false;
} else {
glCallList(scene_display_list_);
}
// Handle frame stats.
if (diagram_) {
emit frameStatsChanged(QString("%1 blocks").arg(diagram_->blockCount()));
} else {
emit frameStatsChanged(QString("0 blocks"));
}
}
void GLWidget::resizeGL(int width, int height) {
const float aspect = float(width) / float(height);
const float near_clip = 0.01;
const float far_clip = 100;
const float tan30 = tanf(DEG_TO_RAD(30));
float top = tan30 * near_clip;
float bottom = -top;
float right = tan30 * near_clip * aspect;
float left = -right;
glMatrixMode(GL_PROJECTION);
glLoadIdentity();
glFrustum(left, right, bottom, top, near_clip, far_clip);
glMatrixMode(GL_MODELVIEW);
glViewport(0, 0, width, height);
}
void GLWidget::mousePressEvent(QMouseEvent* event) {
lastPos = event->pos();
}
void GLWidget::mouseMoveEvent(QMouseEvent* event) {
static const float kCameraSensitivity = 4.0f;
float dx = static_cast<float>(event->x() - lastPos.x()) / height();
float dy = static_cast<float>(event->y() - lastPos.y()) / height();
if (event->buttons() & Qt::LeftButton) {
camera_.rotateX(dx * kCameraSensitivity);
camera_.rotateY(dy * kCameraSensitivity);
}
lastPos = event->pos();
updateGL();
}
void GLWidget::keyPressEvent(QKeyEvent *event) {
if (!event->isAutoRepeat()) {
pressed_keys_.insert(event->key());
time_since_last_frame_.start();
frame_timer_.pushRenderer("Key press handler");
}
}
void GLWidget::keyReleaseEvent(QKeyEvent* event) {
if (!event->isAutoRepeat()) {
pressed_keys_.remove(event->key());
frame_timer_.popRenderer("Key press handler");
}
}
void GLWidget::applyPressedKeys() {
static const QVector3D right(1, 0, 0);
static const QVector3D up(0, 1, 0);
static const QVector3D look(0, 0, -1);
float elapsed_time = time_since_last_frame_.elapsed() / 1000.0f; // seconds.
float desired_velocity = 10.0f; // meters per second.
float distance = elapsed_time * desired_velocity; // meters.
foreach (int key, pressed_keys_) {
switch (key) {
case Qt::Key_W:
camera_.translate(QVector3D(0, 0, -distance));
break;
case Qt::Key_S:
camera_.translate(QVector3D(0, 0, distance));
break;
case Qt::Key_A:
camera_.translate(QVector3D(-distance, 0, 0));
break;
case Qt::Key_D:
camera_.translate(QVector3D(distance, 0, 0));
break;
case Qt::Key_E:
camera_.translateWorld(QVector3D(0, distance, 0));
break;
case Qt::Key_C:
camera_.translateWorld(QVector3D(0, -distance, 0));
break;
default:
break;
}
}
}
void GLWidget::enableFrameRate(bool enable) {
if (enable == frame_rate_enabled_) {
return;
}
if (enable) {
frame_timer_.pushRenderer("Frame rate");
} else {
frame_timer_.popRenderer("Frame rate");
frame_rate_ = -1.0f;
}
frame_rate_enabled_ = enable;
}
<commit_msg>Tweak lighting for better visibility<commit_after>/* Copyright 2012 Brian Ellis
*
* 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 <QtGui>
#include <QtOpenGL>
#include <math.h>
#include "gl_widget.h"
#include "block_manager.h"
#include "diagram.h"
#include "matrix.h"
#include "skybox_renderable.h"
#include "texture.h"
#ifndef GL_MULTISAMPLE_ARB
#define GL_MULTISAMPLE_ARB 0x809D
#endif
#ifndef GL_SAMPLE_ALPHA_TO_COVERAGE_ARB
#define GL_SAMPLE_ALPHA_TO_COVERAGE_ARB 0x809E
#endif
#define DEG_TO_RAD(x) ((x) * M_PI / 180.0f)
GLWidget::GLWidget(QWidget* parent)
: QGLWidget(QGLFormat(QGL::SampleBuffers), parent),
diagram_(NULL),
block_mgr_(NULL),
frame_rate_enabled_(false),
frame_rate_(-1.0f),
scene_dirty_(true) {
setFocusPolicy(Qt::WheelFocus);
QGLFormat f = format();
f.setSwapInterval(1);
setFormat(f);
connect(&frame_timer_, SIGNAL(timeout()), SLOT(updateGL()));
#ifdef NDEBUG
frame_timer_.setDebugMode(false);
#endif
}
GLWidget::~GLWidget() {
}
void GLWidget::setDiagram(Diagram* diagram) {
diagram_ = diagram;
connect(diagram_, SIGNAL(diagramChanged(BlockTransaction)), SLOT(setSceneDirty()));
connect(diagram_, SIGNAL(ephemeralBlocksChanged(BlockTransaction)), SLOT(setSceneDirty()));
}
void GLWidget::setBlockManager(BlockManager* block_mgr) {
block_mgr_ = block_mgr;
}
QSize GLWidget::minimumSizeHint() const {
return QSize(50, 50);
}
QSize GLWidget::sizeHint() const {
return QSize(600, 400);
}
void GLWidget::setSceneDirty(bool dirty) {
scene_dirty_ = dirty;
if (dirty) {
updateGL();
}
}
void GLWidget::initializeGL() {
qglClearColor(QColor(128, 192, 255));
glEnable(GL_DEPTH_TEST);
glEnable(GL_CULL_FACE);
glEnable(GL_BLEND);
glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA);
glEnable(GL_TEXTURE_2D);
glShadeModel(GL_SMOOTH);
glEnable(GL_MULTISAMPLE_ARB);
glEnable(GL_SAMPLE_ALPHA_TO_COVERAGE_ARB);
glAlphaFunc(GL_GREATER, 0.01);
glEnable(GL_ALPHA_TEST);
glEnable(GL_LIGHTING);
glEnable(GL_LIGHT0);
glEnable(GL_LIGHT1);
glEnable(GL_FOG);
glFogf(GL_FOG_MODE, GL_LINEAR);
static GLfloat fog_color[] = { 0.5f, 0.75f, 1.0f, 1.0f };
glFogfv(GL_FOG_COLOR, fog_color);
glFogf(GL_FOG_START, 50);
glFogf(GL_FOG_END, 100);
GLfloat global_ambient[] = { 0.0f, 0.0f, 0.0f, 1.0f };
glLightModelfv(GL_LIGHT_MODEL_AMBIENT, global_ambient);
ground_plane_display_list_ = glGenLists(1);
scene_display_list_ = glGenLists(2);
glNewList(ground_plane_display_list_, GL_COMPILE);
glPushMatrix();
glTranslatef(-50.0f, -1 / 256, -50.0f);
for (int i = 0; i < 100; ++i) {
glBegin(GL_QUAD_STRIP);
glVertex3f(i, 0, 0);
glVertex3f(i + 1.0f, 0, 0);
for (int j = 0; j < 100; ++j) {
glVertex3f(i, 0, j + 1.0f);
glVertex3f(i + 1.0f, 0, j + 1.0f);
}
glEnd();
}
glPopMatrix();
glEndList();
skybox_.reset(new SkyboxRenderable(QVector3D(10.0f, 10.0f, 10.0f)));
skybox_->initialize();
Texture skybox_up = Texture(this, ":/skybox_up.png");
Texture skybox_out = Texture(this, ":/skybox_east.png");
Texture skybox_down = Texture(this, ":/skybox_down.png");
skybox_->setTexture(kFrontFace, skybox_out);
skybox_->setTexture(kLeftFace, skybox_out);
skybox_->setTexture(kRightFace, skybox_out);
skybox_->setTexture(kBackFace, skybox_out);
skybox_->setTexture(kTopFace, skybox_up);
skybox_->setTexture(kBottomFace, skybox_down);
camera_.translate(QVector3D(0.5, 1, 5));
}
void GLWidget::drawSkybox() {
glPushMatrix();
glLoadIdentity();
camera_.applyRotation();
glPushAttrib(GL_LIGHTING_BIT | GL_DEPTH_BITS | GL_FOG_BIT | GL_ENABLE_BIT);
glDisable(GL_LIGHTING);
glDisable(GL_FOG);
glDisable(GL_DEPTH_TEST);
glDisable(GL_CULL_FACE);
skybox_->renderAt(QVector3D(0, 0, 0), BlockOrientation::noOrientation());
glPopAttrib();
glPopMatrix();
}
void GLWidget::updateScene() {
if (!diagram_) {
return;
}
glNewList(scene_display_list_, GL_COMPILE_AND_EXECUTE);
// Draw the ground plane.
glPushAttrib(GL_LIGHTING_BIT | GL_CURRENT_BIT | GL_ENABLE_BIT);
glDisable(GL_CULL_FACE);
GLfloat color[] = {0, 1, 0, 0.5};
glMaterialfv(GL_FRONT_AND_BACK, GL_AMBIENT_AND_DIFFUSE, color);
glCallList(ground_plane_display_list_);
glDisable(GL_LIGHTING);
glDisable(GL_MULTISAMPLE_ARB);
glDisable(GL_SAMPLE_ALPHA_TO_COVERAGE_ARB);
glBindTexture(GL_TEXTURE_2D, NULL);
glColor4f(1, 1, 1, 0.1);
glPolygonMode( GL_FRONT_AND_BACK, GL_LINE );
glPushMatrix();
glTranslatef(0, 0.01f, 0);
glCallList(ground_plane_display_list_);
glPopMatrix();
glPolygonMode( GL_FRONT_AND_BACK, GL_FILL );
glPopAttrib();
diagram_->render();
glEndList();
}
void GLWidget::paintGL() {
glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
applyPressedKeys();
// Handle frame rate display.
if (frame_rate_enabled_) {
static const int kFrameRateSampleCount = 60;
float elapsed_time = time_since_last_frame_.elapsed() / 1000.0f; // seconds
frame_rate_queue_.enqueue(elapsed_time);
while (frame_rate_queue_.size() > kFrameRateSampleCount) {
frame_rate_queue_.dequeue();
}
float average_frame_time = 0.0f;
foreach(float sample, frame_rate_queue_) {
average_frame_time += sample;
}
average_frame_time /= frame_rate_queue_.size();
frame_rate_ = 1.0f / average_frame_time;
emit frameRateChanged(QString::number(frame_rate_, 'g', 4));
}
time_since_last_frame_.start();
camera_.apply();
// Use two lights so that no two sides of a cube are the same shade. This makes it easier to see edges.
static GLfloat light_position[4] = { 2.5, 10.0, 5.0, 0.0 };
static GLfloat light_ambient_intensity[4] = { 2.5, 2.5, 2.5, 1.0 };
static GLfloat light_diffuse_intensity[4] = { 0.8, 0.8, 0.8, 1.0 };
glLightfv(GL_LIGHT0, GL_POSITION, light_position);
glLightfv(GL_LIGHT0, GL_AMBIENT, light_ambient_intensity);
glLightfv(GL_LIGHT0, GL_DIFFUSE, light_diffuse_intensity);
static GLfloat secondary_light_position[4] = { 0, 0, -1.0, 0.0 };
static GLfloat secondary_light_ambient_intensity[4] = { 0, 0, 0, 1.0 };
static GLfloat secondary_light_diffuse_intensity[4] = { 0.1, 0.1, 0.1, 1.0 };
glLightfv(GL_LIGHT1, GL_POSITION, secondary_light_position);
glLightfv(GL_LIGHT1, GL_AMBIENT, secondary_light_ambient_intensity);
glLightfv(GL_LIGHT1, GL_DIFFUSE, secondary_light_diffuse_intensity);
// Can't put this in the display list or it doesn't rotate correctly.
drawSkybox();
if (scene_dirty_) {
updateScene();
scene_dirty_ = false;
} else {
glCallList(scene_display_list_);
}
// Handle frame stats.
if (diagram_) {
emit frameStatsChanged(QString("%1 blocks").arg(diagram_->blockCount()));
} else {
emit frameStatsChanged(QString("0 blocks"));
}
}
void GLWidget::resizeGL(int width, int height) {
const float aspect = float(width) / float(height);
const float near_clip = 0.01;
const float far_clip = 100;
const float tan30 = tanf(DEG_TO_RAD(30));
float top = tan30 * near_clip;
float bottom = -top;
float right = tan30 * near_clip * aspect;
float left = -right;
glMatrixMode(GL_PROJECTION);
glLoadIdentity();
glFrustum(left, right, bottom, top, near_clip, far_clip);
glMatrixMode(GL_MODELVIEW);
glViewport(0, 0, width, height);
}
void GLWidget::mousePressEvent(QMouseEvent* event) {
lastPos = event->pos();
}
void GLWidget::mouseMoveEvent(QMouseEvent* event) {
static const float kCameraSensitivity = 4.0f;
float dx = static_cast<float>(event->x() - lastPos.x()) / height();
float dy = static_cast<float>(event->y() - lastPos.y()) / height();
if (event->buttons() & Qt::LeftButton) {
camera_.rotateX(dx * kCameraSensitivity);
camera_.rotateY(dy * kCameraSensitivity);
}
lastPos = event->pos();
updateGL();
}
void GLWidget::keyPressEvent(QKeyEvent *event) {
if (!event->isAutoRepeat()) {
pressed_keys_.insert(event->key());
time_since_last_frame_.start();
frame_timer_.pushRenderer("Key press handler");
}
}
void GLWidget::keyReleaseEvent(QKeyEvent* event) {
if (!event->isAutoRepeat()) {
pressed_keys_.remove(event->key());
frame_timer_.popRenderer("Key press handler");
}
}
void GLWidget::applyPressedKeys() {
static const QVector3D right(1, 0, 0);
static const QVector3D up(0, 1, 0);
static const QVector3D look(0, 0, -1);
float elapsed_time = time_since_last_frame_.elapsed() / 1000.0f; // seconds.
float desired_velocity = 10.0f; // meters per second.
float distance = elapsed_time * desired_velocity; // meters.
foreach (int key, pressed_keys_) {
switch (key) {
case Qt::Key_W:
camera_.translate(QVector3D(0, 0, -distance));
break;
case Qt::Key_S:
camera_.translate(QVector3D(0, 0, distance));
break;
case Qt::Key_A:
camera_.translate(QVector3D(-distance, 0, 0));
break;
case Qt::Key_D:
camera_.translate(QVector3D(distance, 0, 0));
break;
case Qt::Key_E:
camera_.translateWorld(QVector3D(0, distance, 0));
break;
case Qt::Key_C:
camera_.translateWorld(QVector3D(0, -distance, 0));
break;
default:
break;
}
}
}
void GLWidget::enableFrameRate(bool enable) {
if (enable == frame_rate_enabled_) {
return;
}
if (enable) {
frame_timer_.pushRenderer("Frame rate");
} else {
frame_timer_.popRenderer("Frame rate");
frame_rate_ = -1.0f;
}
frame_rate_enabled_ = enable;
}
<|endoftext|> |
<commit_before>// Copyright (c) 2010 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/path_service.h"
#include "base/basictypes.h"
#include "base/file_util.h"
#include "base/file_path.h"
#if defined(OS_WIN)
#include "base/win/windows_version.h"
#endif
#include "testing/gtest/include/gtest/gtest.h"
#include "testing/gtest/include/gtest/gtest-spi.h"
#include "testing/platform_test.h"
namespace {
// Returns true if PathService::Get returns true and sets the path parameter
// to non-empty for the given PathService::DirType enumeration value.
bool ReturnsValidPath(int dir_type) {
FilePath path;
bool result = PathService::Get(dir_type, &path);
return result && !path.value().empty() && file_util::PathExists(path);
}
#if defined(OS_WIN)
// Function to test DIR_LOCAL_APP_DATA_LOW on Windows XP. Make sure it fails.
bool ReturnsInvalidPath(int dir_type) {
FilePath path;
bool result = PathService::Get(base::DIR_LOCAL_APP_DATA_LOW, &path);
return !result && path.empty();
}
#endif
} // namespace
// On the Mac this winds up using some autoreleased objects, so we need to
// be a PlatformTest.
typedef PlatformTest PathServiceTest;
// Test that all PathService::Get calls return a value and a true result
// in the development environment. (This test was created because a few
// later changes to Get broke the semantics of the function and yielded the
// correct value while returning false.)
TEST_F(PathServiceTest, Get) {
for (int key = base::DIR_CURRENT; key < base::PATH_END; ++key) {
EXPECT_PRED1(ReturnsValidPath, key);
}
#if defined(OS_WIN)
for (int key = base::PATH_WIN_START + 1; key < base::PATH_WIN_END; ++key) {
if (key == base::DIR_LOCAL_APP_DATA_LOW &&
base::win::GetVersion() < base::win::VERSION_VISTA) {
// DIR_LOCAL_APP_DATA_LOW is not supported prior Vista and is expected to
// fail.
EXPECT_TRUE(ReturnsInvalidPath(key)) << key;
} else {
EXPECT_TRUE(ReturnsValidPath(key)) << key;
}
}
#elif defined(OS_MACOSX)
for (int key = base::PATH_MAC_START + 1; key < base::PATH_MAC_END; ++key) {
EXPECT_PRED1(ReturnsValidPath, key);
}
#endif
}
<commit_msg>If chromium has not been started yet, the cache path will not exist.<commit_after>// Copyright (c) 2010 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/path_service.h"
#include "base/basictypes.h"
#include "base/file_util.h"
#include "base/file_path.h"
#if defined(OS_WIN)
#include "base/win/windows_version.h"
#endif
#include "testing/gtest/include/gtest/gtest.h"
#include "testing/gtest/include/gtest/gtest-spi.h"
#include "testing/platform_test.h"
namespace {
// Returns true if PathService::Get returns true and sets the path parameter
// to non-empty for the given PathService::DirType enumeration value.
bool ReturnsValidPath(int dir_type) {
FilePath path;
bool result = PathService::Get(dir_type, &path);
#if defined(OS_POSIX)
// If chromium has never been started on this account, the cache path will not
// exist.
if (dir_type == base::DIR_USER_CACHE)
return result && !path.value().empty();
#endif
return result && !path.value().empty() && file_util::PathExists(path);
}
#if defined(OS_WIN)
// Function to test DIR_LOCAL_APP_DATA_LOW on Windows XP. Make sure it fails.
bool ReturnsInvalidPath(int dir_type) {
FilePath path;
bool result = PathService::Get(base::DIR_LOCAL_APP_DATA_LOW, &path);
return !result && path.empty();
}
#endif
} // namespace
// On the Mac this winds up using some autoreleased objects, so we need to
// be a PlatformTest.
typedef PlatformTest PathServiceTest;
// Test that all PathService::Get calls return a value and a true result
// in the development environment. (This test was created because a few
// later changes to Get broke the semantics of the function and yielded the
// correct value while returning false.)
TEST_F(PathServiceTest, Get) {
for (int key = base::DIR_CURRENT; key < base::PATH_END; ++key) {
EXPECT_PRED1(ReturnsValidPath, key);
}
#if defined(OS_WIN)
for (int key = base::PATH_WIN_START + 1; key < base::PATH_WIN_END; ++key) {
if (key == base::DIR_LOCAL_APP_DATA_LOW &&
base::win::GetVersion() < base::win::VERSION_VISTA) {
// DIR_LOCAL_APP_DATA_LOW is not supported prior Vista and is expected to
// fail.
EXPECT_TRUE(ReturnsInvalidPath(key)) << key;
} else {
EXPECT_TRUE(ReturnsValidPath(key)) << key;
}
}
#elif defined(OS_MACOSX)
for (int key = base::PATH_MAC_START + 1; key < base::PATH_MAC_END; ++key) {
EXPECT_PRED1(ReturnsValidPath, key);
}
#endif
}
<|endoftext|> |
<commit_before>/*
// $ g++ -O3 -o createSortedJaccsFile createSortedJaccsFile.cpp
// $ ./createSortedJaccsFile network.jaccs newSortedNewtwork.jaccs sortedJaccs.csv
*/
#include <math.h>
#include <ctime>
#include <cstdlib>
#include <fstream>
#include <iostream>
#include <set>
#include <map>
#include <utility> // for pairs
#include <algorithm> // for swap
#define MIN_DIFF_BW_JACCS 0.0001
using namespace std;
int main (int argc, char const *argv[]){
//************* make sure args are present:
if (argc != 4){
cout << "ERROR: something wrong with the inputs" << endl;
cout << "usage:\n " << argv[0] << " network.jaccs newSortedNewtwork.jaccs sortedJaccs.csv" << endl;
exit(1);
}
//************* got the args
clock_t begin = clock();
ifstream jaccFile;
jaccFile.open( argv[1] );
if (!jaccFile) {
cout << "ERROR: unable to open jaccards file" << endl;
exit(1); // terminate with error
}
set<pair<float, pair<int, int> > > jaccsEdgeEdgeSet;
int edgeId1,edgeId2;
float jacc;
set<float> thresholdSet;
// read each line from the jacc file
while ( jaccFile >> edgeId1 >> edgeId2 >> jacc ) {
// if this value of jacc does exists
// then add inser the value
jaccsEdgeEdgeSet.insert(make_pair(jacc, make_pair(edgeId1, edgeId2)));
if(thresholdSet.count(jacc) == 0)
thresholdSet.insert(jacc);
}
jaccFile.close();jaccFile.clear();
cout << "Done with thresholdSet creation. total unique jaccs:" << thresholdSet.size() << endl;
// create the file
// if exists then overwrite everything
FILE * sortedJaccsFile = fopen( argv[3], "w" );
set<float> ::reverse_iterator thIt;
for(thIt = thresholdSet.rbegin(); thIt!=thresholdSet.rend(); thIt++){
jacc = *thIt;
// open the file
fprintf( sortedJaccsFile, "%.6f \n", jacc);
}
fclose(sortedJaccsFile);
thresholdSet.clear();
cout << "Done writing unique jaccs! ";
clock_t end1 = clock();
cout << "Time taken = " << double(end1 - begin)/ CLOCKS_PER_SEC << " seconds. "<< endl;
//------------------------
// Create a file with sorted in on-increasing order jaccs with:
// < edgeId edgeId jaccs > on each line
long long done = 0;
float percDone = 0.01;
FILE * sortedNewNWJaccsFile = fopen( argv[2], "w" );
set<pair<float, pair<int, int> > >::reverse_iterator jaccsEdgeEdgeSetIt;
for(jaccsEdgeEdgeSetIt = jaccsEdgeEdgeSet.rbegin();
jaccsEdgeEdgeSetIt!=jaccsEdgeEdgeSet.rend(); jaccsEdgeEdgeSetIt++){
jacc = (*jaccsEdgeEdgeSetIt).first;
edgeId1 = (*jaccsEdgeEdgeSetIt).second.first;
edgeId2 = (*jaccsEdgeEdgeSetIt).second.second;
// open the file
fprintf( sortedNewNWJaccsFile, "%lld %lld %.6f\n", edgeId1, edgeId2, jacc);
done++;
if((float)done/(float)jaccsEdgeEdgeSet.size() >= percDone){
cout << percDone*100 << " pc done.\n" << endl;
percDone += 0.01;
}
}
fclose(sortedNewNWJaccsFile);
jaccsEdgeEdgeSet.clear();
cout << "Done writing sorted New NW JaccsFile! ";
cout << "Time taken = " << double(clock() - end1)/ CLOCKS_PER_SEC << " seconds. "<< endl;
cout << "Total Time taken = " << double(clock() - begin)/ CLOCKS_PER_SEC << " seconds. "<< endl;
return 0;
}
<commit_msg>Update createSortedJaccsFile.cpp<commit_after>/*
1. Treat each edge id as a cluster, unordered map from edgeId to a set
2. also store size of each cluster which will 0 in the begining
// $ g++ -std=c++0x -O3 -o calcDensityForDiffThresh calcDensityForDiffThresh.cpp
// $ ./calcDensityForDiffThresh networkEdgeIdMap.csv network.jaccs sortedjaccs.csv Nthresholds threshDensity.csv
*/
#include <math.h>
#include <ctime>
#include <cstdlib>
#include <fstream>
#include <iostream>
#include <unordered_map>
#include <set>
#include <map>
#include <utility> // for pairs
#include <algorithm> // for swap
using namespace std;
int main (int argc, char const *argv[]){
//************* make sure args are present:
if (argc != 6){
cout << "ERROR: something wrong with the inputs" << endl;
cout << "usage:\n " << argv[0] << " networkEdgeIdMap.csv network.jaccs sortedjaccs.csv "
<< " Nthresholds threshDensity.csv" << endl;
exit(1);
}
// Nthresholds is the total thresholds user wants us to try
int nThresh = atoi(argv[4]);
int gapBetweenthresh = 0;
float threshold = 0;
float D = 0.0;
int mc, nc;
int M = 0, Mns = 0;
double wSum = 0.0;
float highestD=0.0;
float highestDThr = 0.0;
//************* got the args
clock_t begin = clock();
//************* start load edgelist
ifstream inFile;
inFile.open( argv[1] );
if (!inFile) {
cout << "ERROR: unable to open input file" << endl;
exit(1); // terminate with error
}
// store edge ids in a map
// each edge id will be a cluster of it's own in the begining
// each cluster will be og size 1
unordered_map< int, pair<int,int> > idEdgePairMap;
unordered_map< int, set<int > > index2cluster; // O(log n) access too slow?
unordered_map< int, unordered_map< int, set<int > >::iterator > edge2iter;
int ni, nj, edgeId, index = 0;
while (inFile >> ni >> nj >> edgeId){
idEdgePairMap[ edgeId ] = make_pair(ni,nj);
index2cluster[ index ].insert(edgeId); // build cluster index to set of edge-pairs map
edge2iter[edgeId] = index2cluster.find(index);
index++;
}
inFile.close(); inFile.clear();
cout << "There were " << index2cluster.size() << " edges." << endl;
/// end reading edge ids -----
//----- ----- ----- -----
ifstream sortedjaccFile;
sortedjaccFile.open( argv[3] );
if (!sortedjaccFile) {
cout << "ERROR: unable to open sortedjaccFile file" << endl;
exit(1); // terminate with error
}
int totalThresh = 0;
int edgeId1,edgeId2;
float jacc;
// Count totalines in the file, we are setting
while ( sortedjaccFile >> jacc ) {
if(jacc>0 && jacc<=1.0)
totalThresh++;
}
sortedjaccFile.close(); sortedjaccFile.clear();
cout << "Done counting totalines in the file, \nTotal unique Jaccs = " << totalThresh << endl;
if(totalThresh==0){
cout << "ERROR: there are 0 Jaccs!!!" << endl;
exit(1); // terminate with error
}
// now we want gap between two consecutive thresholds
// we want to consider
gapBetweenthresh = totalThresh/nThresh;
if(totalThresh < nThresh)
gapBetweenthresh = totalThresh;
set<float> thresholdSet;
set<float> ::reverse_iterator thIt;
// ----------------------------
totalThresh = -1;
sortedjaccFile.open( argv[3] );
while ( sortedjaccFile >> jacc ){
totalThresh++;
if(totalThresh%gapBetweenthresh!=0){
continue;
}
thresholdSet.insert(jacc);
}
thresholdSet.insert(1.1);
cout << "Done with thresholdSet creation." << endl;
// ---------------------------
ifstream jaccFile;
jaccFile.open(argv[2]);
// read first line
jaccFile >> edgeId1 >> edgeId2 >> jacc ;
// open the outputfile
unordered_map< int, set< int> >::iterator iter_i,iter_j;
set<int>::iterator iterS;
FILE * threshDensityFile = fopen( argv[3], "w" );
fclose(threshDensityFile);
fprintf( threshDensityFile, "thresh D\n" );
long long done = 0;
float percDone = 0.01;
clock_t lastBegin = clock();
for(thIt = thresholdSet.rbegin(); thIt!=thresholdSet.rend(); thIt++){
threshold = *thIt;
if (threshold < 0.0 || threshold > 1.1){
cout << "ERROR: specified threshold not in [0,1]" << endl;
exit(1);
}
do{
if( jacc < threshold )
break;
iter_i = edge2iter[ edgeId1 ];
iter_j = edge2iter[ edgeId2 ];
if ( iter_i != iter_j ) {
// always merge smaller cluster into bigger:
if ( (*iter_j).second.size() > (*iter_i).second.size() ){ // !!!!!!
swap(iter_i, iter_j);
}
// merge cluster j into i and update index for all elements in j:
for (iterS = iter_j->second.begin(); iterS != iter_j->second.end(); iterS++){
iter_i->second.insert( *iterS );
edge2iter[ *iterS ] = iter_i;
}
// delete cluster j:
index2cluster.erase(iter_j);
}
}while ( jaccFile >> edgeId1 >> edgeId2 >> jacc );
// all done clustering, write to file (and calculated partition density):
M = 0, Mns = 0;
wSum = 0.0;
set< int >::iterator S;
set<int> clusterNodes;
unordered_map< int, set< int > >::iterator it;
for ( it = index2cluster.begin(); it != index2cluster.end(); it++ ) {
clusterNodes.clear();
for (S = it->second.begin(); S != it->second.end(); S++ ){
//fprintf( clustersFile, "%i ", *S ); // this leaves a trailing space...!
clusterNodes.insert(idEdgePairMap[*S].first);
clusterNodes.insert(idEdgePairMap[*S].second);
}
mc = it->second.size();
nc = clusterNodes.size();
M += mc;
if (nc > 2) {
Mns += mc;
wSum += mc * (mc - (nc-1.0)) / ((nc-2.0)*(nc-1.0));
}
}
threshDensityFile = fopen( argv[3], "a" );
D = 2.0 * wSum / M;
if (isinf(D)){
fprintf( threshDensityFile, "\nERROR: D == -inf \n\n");
fclose(threshDensityFile);
exit(1);
}
//*************
fprintf( threshDensityFile, "%.6f %.6f \n", threshold, D);
fclose(threshDensityFile);
if(D > highestD){
highestD = D;
highestDThr = threshold;
}
done++;
if((float)done/(float)thresholdSet.size() >= percDone){
cout << percDone*100 << " pc done.\n" << endl;
percDone += 0.01;
}
cout << "Time taken = " << double(clock() - lastBegin)/ CLOCKS_PER_SEC << " seconds. "<< endl;
lastBegin = clock();
}
jaccFile.close(); jaccFile.clear();
fprintf( threshDensityFile, "\n highest D=%.6f at thresh:%.6f.\n", highestD, highestDThr);
fclose(threshDensityFile);
cout << "Time taken = " << double(clock() - begin)/ CLOCKS_PER_SEC << " seconds. "<< endl;
return 0;
}
<|endoftext|> |
<commit_before>/*************************************************************************
*
* OpenOffice.org - a multi-platform office productivity suite
*
* $RCSfile: sbunoobj.hxx,v $
*
* $Revision: 1.13 $
*
* last change: $Author: hr $ $Date: 2005-09-29 16:31:39 $
*
* 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 SB_UNO_OBJ
#define SB_UNO_OBJ
#ifndef _SBX_SBXOBJECT_HXX //autogen
#include <sbxobj.hxx>
#endif
#ifndef __SBX_SBXMETHOD_HXX //autogen
#include <sbxmeth.hxx>
#endif
#ifndef __SBX_SBXPROPERTY_HXX //autogen
#include <sbxprop.hxx>
#endif
#ifndef __SBX_SBX_FACTORY_HXX //autogen
#include <sbxfac.hxx>
#endif
#ifndef __SBX_SBX_HXX //autogen
#include <sbx.hxx>
#endif
#ifndef _COM_SUN_STAR_BEANS_XMATERIALHOLDER_HPP_
#include <com/sun/star/beans/XMaterialHolder.hpp>
#endif
#ifndef _COM_SUN_STAR_BEANS_XEXACTNAME_HPP_
#include <com/sun/star/beans/XExactName.hpp>
#endif
#ifndef _COM_SUN_STAR_BEANS_XINTROSPECTIONACCESS_HPP_
#include <com/sun/star/beans/XIntrospectionAccess.hpp>
#endif
#ifndef _COM_SUN_STAR_BEANS_XINTROSPECTION_HPP_
#include <com/sun/star/beans/XIntrospection.hpp>
#endif
#ifndef _COM_SUN_STAR_SCRIPT_XINVOCATION_HPP_
#include <com/sun/star/script/XInvocation.hpp>
#endif
#ifndef _COM_SUN_STAR_REFLECTION_XIDLCLASS_HPP_
#include <com/sun/star/reflection/XIdlClass.hpp>
#endif
#ifndef _RTL_USTRING_
#include <rtl/ustring>
#endif
using namespace com::sun::star::uno;
using namespace com::sun::star::beans;
using namespace com::sun::star::script;
using namespace com::sun::star::reflection;
class SbUnoObject: public SbxObject
{
Reference< XIntrospectionAccess > mxUnoAccess;
Reference< XMaterialHolder > mxMaterialHolder;
Reference< XInvocation > mxInvocation;
Reference< XExactName > mxExactName;
BOOL bNeedIntrospection;
Any maTmpUnoObj; // Only to save obj for doIntrospection!
// Hilfs-Methode zum Anlegen der dbg_-Properties
void implCreateDbgProperties( void );
// Hilfs-Methode zum Anlegen aller Properties und Methoden
// (Beim on-demand-Mechanismus erforderlich fuer die dbg_-Properties)
void implCreateAll( void );
public:
TYPEINFO();
SbUnoObject( const String& aName, const Any& aUnoObj_ );
~SbUnoObject();
// #76470 Introspection on Demand durchfuehren
void doIntrospection( void );
// Find ueberladen, um z.B. NameAccess zu unterstuetzen
virtual SbxVariable* Find( const String&, SbxClassType );
// Force creation of all properties for debugging
void createAllProperties( void )
{ implCreateAll(); }
// Wert rausgeben
Any getUnoAny( void );
Reference< XIntrospectionAccess > getIntrospectionAccess( void ) { return mxUnoAccess; }
Reference< XInvocation > getInvocation( void ) { return mxInvocation; }
void SFX_NOTIFY( SfxBroadcaster&, const TypeId&, const SfxHint& rHint, const TypeId& );
};
SV_DECL_IMPL_REF(SbUnoObject);
// #67781 Rueckgabewerte der Uno-Methoden loeschen
void clearUnoMethods( void );
class SbUnoMethod : public SbxMethod
{
friend class SbUnoObject;
friend void clearUnoMethods( void );
Reference< XIdlMethod > m_xUnoMethod;
Sequence<ParamInfo>* pParamInfoSeq;
// #67781 Verweis auf vorige und naechste Methode in der Methoden-Liste
SbUnoMethod* pPrev;
SbUnoMethod* pNext;
public:
TYPEINFO();
SbUnoMethod( const String& aName, SbxDataType eSbxType, Reference< XIdlMethod > xUnoMethod_ );
virtual ~SbUnoMethod();
virtual SbxInfo* GetInfo();
const Sequence<ParamInfo>& getParamInfos( void );
};
class SbUnoProperty : public SbxProperty
{
friend class SbUnoObject;
// Daten der Uno-Property
Property aUnoProp;
UINT32 nId;
virtual ~SbUnoProperty();
public:
TYPEINFO();
SbUnoProperty( const String& aName, SbxDataType eSbxType,
const Property& aUnoProp_, UINT32 nId_ );
};
// Factory-Klasse fuer das Anlegen von Uno-Structs per DIM AS NEW
class SbUnoFactory : public SbxFactory
{
public:
virtual SbxBase* Create( UINT16 nSbxId, UINT32 = SBXCR_SBX );
virtual SbxObject* CreateObject( const String& );
};
// Wrapper fuer eine Uno-Klasse
class SbUnoClass: public SbxObject
{
const Reference< XIdlClass > m_xClass;
public:
TYPEINFO();
SbUnoClass( const String& aName )
: SbxObject( aName )
{}
SbUnoClass( const String& aName, const Reference< XIdlClass >& xClass_ )
: SbxObject( aName )
, m_xClass( xClass_ )
{}
//~SbUnoClass();
// Find ueberladen, um Elemente on Demand anzulegen
virtual SbxVariable* Find( const String&, SbxClassType );
// Wert rausgeben
const Reference< XIdlClass >& getUnoClass( void ) { return m_xClass; }
//void SFX_NOTIFY( SfxBroadcaster&, const TypeId&, const SfxHint& rHint, const TypeId& );
};
SV_DECL_IMPL_REF(SbUnoClass);
// Funktion, um einen globalen Bezeichner im
// UnoScope zu suchen und fuer Sbx zu wrappen
SbxVariable* findUnoClass( const String& rName );
// #105565 Special Object to wrap a strongly typed Uno Any
class SbUnoAnyObject: public SbxObject
{
Any mVal;
public:
SbUnoAnyObject( const Any& rVal )
: SbxObject( String() )
, mVal( rVal )
{}
const Any& getValue( void )
{ return mVal; }
TYPEINFO();
};
// #112509 Special SbxArray to transport named parameters for calls
// to OLEAutomation objects through the UNO OLE automation bridge
class AutomationNamedArgsSbxArray : public SbxArray
{
Sequence< ::rtl::OUString > maNameSeq;
public:
TYPEINFO();
AutomationNamedArgsSbxArray( sal_Int32 nSeqSize )
: maNameSeq( nSeqSize )
{}
Sequence< ::rtl::OUString >& getNames( void )
{ return maNameSeq; }
};
class StarBASIC;
// Impl-Methoden fuer RTL
void RTL_Impl_CreateUnoStruct( StarBASIC* pBasic, SbxArray& rPar, BOOL bWrite );
void RTL_Impl_CreateUnoService( StarBASIC* pBasic, SbxArray& rPar, BOOL bWrite );
void RTL_Impl_CreateUnoValue( StarBASIC* pBasic, SbxArray& rPar, BOOL bWrite );
void RTL_Impl_GetProcessServiceManager( StarBASIC* pBasic, SbxArray& rPar, BOOL bWrite );
void RTL_Impl_HasInterfaces( StarBASIC* pBasic, SbxArray& rPar, BOOL bWrite );
void RTL_Impl_IsUnoStruct( StarBASIC* pBasic, SbxArray& rPar, BOOL bWrite );
void RTL_Impl_EqualUnoObjects( StarBASIC* pBasic, SbxArray& rPar, BOOL bWrite );
void RTL_Impl_GetDefaultContext( StarBASIC* pBasic, SbxArray& rPar, BOOL bWrite );
//========================================================================
// #118116 Collection object
class BasicCollection : public SbxObject
{
friend class SbiRuntime;
SbxArrayRef xItemArray;
void Initialize();
virtual ~BasicCollection();
virtual void SFX_NOTIFY( SfxBroadcaster& rBC, const TypeId& rBCType,
const SfxHint& rHint, const TypeId& rHintType );
INT32 implGetIndex( SbxVariable* pIndexVar );
INT32 implGetIndexForName( const String& rName );
void CollAdd( SbxArray* pPar );
void CollItem( SbxArray* pPar );
void CollRemove( SbxArray* pPar );
public:
TYPEINFO();
BasicCollection( const String& rClassname );
virtual SbxVariable* Find( const String&, SbxClassType );
virtual void Clear();
};
#endif
<commit_msg>INTEGRATION: CWS ab23pp2 (1.13.38); FILE MERGED 2006/01/26 15:14:34 ab 1.13.38.1: #i60306# Allow access over invocation in parallel to access using XTypeProvider<commit_after>/*************************************************************************
*
* OpenOffice.org - a multi-platform office productivity suite
*
* $RCSfile: sbunoobj.hxx,v $
*
* $Revision: 1.14 $
*
* last change: $Author: kz $ $Date: 2006-01-31 18:30:30 $
*
* 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 SB_UNO_OBJ
#define SB_UNO_OBJ
#ifndef _SBX_SBXOBJECT_HXX //autogen
#include <sbxobj.hxx>
#endif
#ifndef __SBX_SBXMETHOD_HXX //autogen
#include <sbxmeth.hxx>
#endif
#ifndef __SBX_SBXPROPERTY_HXX //autogen
#include <sbxprop.hxx>
#endif
#ifndef __SBX_SBX_FACTORY_HXX //autogen
#include <sbxfac.hxx>
#endif
#ifndef __SBX_SBX_HXX //autogen
#include <sbx.hxx>
#endif
#ifndef _COM_SUN_STAR_BEANS_XMATERIALHOLDER_HPP_
#include <com/sun/star/beans/XMaterialHolder.hpp>
#endif
#ifndef _COM_SUN_STAR_BEANS_XEXACTNAME_HPP_
#include <com/sun/star/beans/XExactName.hpp>
#endif
#ifndef _COM_SUN_STAR_BEANS_XINTROSPECTIONACCESS_HPP_
#include <com/sun/star/beans/XIntrospectionAccess.hpp>
#endif
#ifndef _COM_SUN_STAR_BEANS_XINTROSPECTION_HPP_
#include <com/sun/star/beans/XIntrospection.hpp>
#endif
#ifndef _COM_SUN_STAR_SCRIPT_XINVOCATION_HPP_
#include <com/sun/star/script/XInvocation.hpp>
#endif
#ifndef _COM_SUN_STAR_REFLECTION_XIDLCLASS_HPP_
#include <com/sun/star/reflection/XIdlClass.hpp>
#endif
#ifndef _RTL_USTRING_
#include <rtl/ustring>
#endif
using namespace com::sun::star::uno;
using namespace com::sun::star::beans;
using namespace com::sun::star::script;
using namespace com::sun::star::reflection;
class SbUnoObject: public SbxObject
{
Reference< XIntrospectionAccess > mxUnoAccess;
Reference< XMaterialHolder > mxMaterialHolder;
Reference< XInvocation > mxInvocation;
Reference< XExactName > mxExactName;
Reference< XExactName > mxExactNameInvocation;
BOOL bNeedIntrospection;
Any maTmpUnoObj; // Only to save obj for doIntrospection!
// Hilfs-Methode zum Anlegen der dbg_-Properties
void implCreateDbgProperties( void );
// Hilfs-Methode zum Anlegen aller Properties und Methoden
// (Beim on-demand-Mechanismus erforderlich fuer die dbg_-Properties)
void implCreateAll( void );
public:
TYPEINFO();
SbUnoObject( const String& aName, const Any& aUnoObj_ );
~SbUnoObject();
// #76470 Introspection on Demand durchfuehren
void doIntrospection( void );
// Find ueberladen, um z.B. NameAccess zu unterstuetzen
virtual SbxVariable* Find( const String&, SbxClassType );
// Force creation of all properties for debugging
void createAllProperties( void )
{ implCreateAll(); }
// Wert rausgeben
Any getUnoAny( void );
Reference< XIntrospectionAccess > getIntrospectionAccess( void ) { return mxUnoAccess; }
Reference< XInvocation > getInvocation( void ) { return mxInvocation; }
void SFX_NOTIFY( SfxBroadcaster&, const TypeId&, const SfxHint& rHint, const TypeId& );
};
SV_DECL_IMPL_REF(SbUnoObject);
// #67781 Rueckgabewerte der Uno-Methoden loeschen
void clearUnoMethods( void );
class SbUnoMethod : public SbxMethod
{
friend class SbUnoObject;
friend void clearUnoMethods( void );
Reference< XIdlMethod > m_xUnoMethod;
Sequence<ParamInfo>* pParamInfoSeq;
// #67781 Verweis auf vorige und naechste Methode in der Methoden-Liste
SbUnoMethod* pPrev;
SbUnoMethod* pNext;
bool mbInvocation; // Method is based on invocation
public:
TYPEINFO();
SbUnoMethod( const String& aName, SbxDataType eSbxType, Reference< XIdlMethod > xUnoMethod_,
bool bInvocation );
virtual ~SbUnoMethod();
virtual SbxInfo* GetInfo();
const Sequence<ParamInfo>& getParamInfos( void );
bool isInvocationBased( void )
{ return mbInvocation; }
};
class SbUnoProperty : public SbxProperty
{
friend class SbUnoObject;
// Daten der Uno-Property
Property aUnoProp;
UINT32 nId;
bool mbInvocation; // Property is based on invocation
virtual ~SbUnoProperty();
public:
TYPEINFO();
SbUnoProperty( const String& aName, SbxDataType eSbxType,
const Property& aUnoProp_, UINT32 nId_, bool bInvocation );
bool isInvocationBased( void )
{ return mbInvocation; }
};
// Factory-Klasse fuer das Anlegen von Uno-Structs per DIM AS NEW
class SbUnoFactory : public SbxFactory
{
public:
virtual SbxBase* Create( UINT16 nSbxId, UINT32 = SBXCR_SBX );
virtual SbxObject* CreateObject( const String& );
};
// Wrapper fuer eine Uno-Klasse
class SbUnoClass: public SbxObject
{
const Reference< XIdlClass > m_xClass;
public:
TYPEINFO();
SbUnoClass( const String& aName )
: SbxObject( aName )
{}
SbUnoClass( const String& aName, const Reference< XIdlClass >& xClass_ )
: SbxObject( aName )
, m_xClass( xClass_ )
{}
//~SbUnoClass();
// Find ueberladen, um Elemente on Demand anzulegen
virtual SbxVariable* Find( const String&, SbxClassType );
// Wert rausgeben
const Reference< XIdlClass >& getUnoClass( void ) { return m_xClass; }
//void SFX_NOTIFY( SfxBroadcaster&, const TypeId&, const SfxHint& rHint, const TypeId& );
};
SV_DECL_IMPL_REF(SbUnoClass);
// Funktion, um einen globalen Bezeichner im
// UnoScope zu suchen und fuer Sbx zu wrappen
SbxVariable* findUnoClass( const String& rName );
// #105565 Special Object to wrap a strongly typed Uno Any
class SbUnoAnyObject: public SbxObject
{
Any mVal;
public:
SbUnoAnyObject( const Any& rVal )
: SbxObject( String() )
, mVal( rVal )
{}
const Any& getValue( void )
{ return mVal; }
TYPEINFO();
};
// #112509 Special SbxArray to transport named parameters for calls
// to OLEAutomation objects through the UNO OLE automation bridge
class AutomationNamedArgsSbxArray : public SbxArray
{
Sequence< ::rtl::OUString > maNameSeq;
public:
TYPEINFO();
AutomationNamedArgsSbxArray( sal_Int32 nSeqSize )
: maNameSeq( nSeqSize )
{}
Sequence< ::rtl::OUString >& getNames( void )
{ return maNameSeq; }
};
class StarBASIC;
// Impl-Methoden fuer RTL
void RTL_Impl_CreateUnoStruct( StarBASIC* pBasic, SbxArray& rPar, BOOL bWrite );
void RTL_Impl_CreateUnoService( StarBASIC* pBasic, SbxArray& rPar, BOOL bWrite );
void RTL_Impl_CreateUnoValue( StarBASIC* pBasic, SbxArray& rPar, BOOL bWrite );
void RTL_Impl_GetProcessServiceManager( StarBASIC* pBasic, SbxArray& rPar, BOOL bWrite );
void RTL_Impl_HasInterfaces( StarBASIC* pBasic, SbxArray& rPar, BOOL bWrite );
void RTL_Impl_IsUnoStruct( StarBASIC* pBasic, SbxArray& rPar, BOOL bWrite );
void RTL_Impl_EqualUnoObjects( StarBASIC* pBasic, SbxArray& rPar, BOOL bWrite );
void RTL_Impl_GetDefaultContext( StarBASIC* pBasic, SbxArray& rPar, BOOL bWrite );
//========================================================================
// #118116 Collection object
class BasicCollection : public SbxObject
{
friend class SbiRuntime;
SbxArrayRef xItemArray;
void Initialize();
virtual ~BasicCollection();
virtual void SFX_NOTIFY( SfxBroadcaster& rBC, const TypeId& rBCType,
const SfxHint& rHint, const TypeId& rHintType );
INT32 implGetIndex( SbxVariable* pIndexVar );
INT32 implGetIndexForName( const String& rName );
void CollAdd( SbxArray* pPar );
void CollItem( SbxArray* pPar );
void CollRemove( SbxArray* pPar );
public:
TYPEINFO();
BasicCollection( const String& rClassname );
virtual SbxVariable* Find( const String&, SbxClassType );
virtual void Clear();
};
#endif
<|endoftext|> |
<commit_before>/* -*- mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */
// vim:sts=4:sw=4:ts=4:noet:sr:cino=>s,f0,{0,g0,(0,\:0,t0,+0,=s
/* Copyright (c) FFLAS-FFPACK
* Written by Clément Pernet <clement.pernet@imag.fr>
* ========LICENCE========
* This file is part of the library FFLAS-FFPACK.
*
* FFLAS-FFPACK 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 Street, Fifth Floor, Boston, MA 02110-1301 USA
* ========LICENCE========
*/
//#define __FFPACK_FSYTRF_BC_RL
#undef __FFPACK_FSYTRF_BC_RL
#define __FFPACK_FSYTRF_BC_CROUT
#include "fflas-ffpack/fflas-ffpack-config.h"
#include <iostream>
#include <givaro/modular.h>
#include "fflas-ffpack/fflas-ffpack.h"
#include "fflas-ffpack/utils/timer.h"
#include "fflas-ffpack/utils/fflas_io.h"
#include "fflas-ffpack/utils/args-parser.h"
using namespace std;
int main(int argc, char** argv) {
size_t iter = 3;
int q = 131071;
size_t n = 1000;
size_t threshold = 64;
size_t rank = 500;
bool up =true;
bool rpm =true;
bool grp =true;
bool par =false;
int t=MAX_THREADS;
std::string file = "";
Argument as[] = {
{ 'q', "-q Q", "Set the field characteristic (-1 for random).", TYPE_INT , &q },
{ 'n', "-n N", "Set the dimension of the matrix.", TYPE_INT , &n },
{ 'u', "-u yes/no", "Computes a UTDU (true) or LDLT decomposition (false).", TYPE_BOOL , &up },
{ 'm', "-m yes/no", "Use the rank profile matrix revealing algorithm.", TYPE_BOOL , &rpm },
{ 'r', "-r R", "Set the rank (for the RPM version).", TYPE_INT , &rank },
{ 'g', "-g yes/no", "Matrix with generic rank profile (yes) or random rank profile matrix (no).", TYPE_BOOL , &grp },
{ 'i', "-i I", "Set number of repetitions.", TYPE_INT , &iter },
{ 't', "-t T", "Set the threshold to the base case.", TYPE_INT , &threshold },
{ 'f', "-f FILE", "Set the input file (empty for random).", TYPE_STR , &file },
{ 'p', "-p P", "whether to run or not the parallel PLUQ", TYPE_BOOL , &par },
{ 't', "-t T", "number of virtual threads to drive the partition.", TYPE_INT , &t },
END_OF_ARGUMENTS
};
FFLAS::parseArguments(argc,argv,as);
rank=std::min(n,rank);
typedef Givaro::ModularBalanced<double> Field;
typedef Field::Element Element;
Field F(q);
Field::Element * A;
FFLAS::Timer chrono;
FFLAS::FFLAS_UPLO uplo = up?FFLAS::FflasUpper:FFLAS::FflasLower;
double *time=new double[iter];
for (size_t i=0; i<iter; i++) time[i]=0;
for (size_t i=0;i<=iter;++i){
if (!file.empty()){
FFLAS::ReadMatrix (file.c_str(),F,n,n,A);
}
else {
A = FFLAS::fflas_new<Element>(n*n);
Field::RandIter G(F);
if (grp){
size_t * cols = FFLAS::fflas_new<size_t>(n);
size_t * rows = FFLAS::fflas_new<size_t>(n);
for (size_t i=0; i<n; ++i)
cols[i] = rows[i] = i;
FFPACK::RandomSymmetricMatrixWithRankandRPM (F, n, rank, A, n, rows, cols, G);
FFLAS::fflas_delete(cols);
FFLAS::fflas_delete(rows);
} else
FFPACK::RandomSymmetricMatrixWithRankandRandomRPM (F, n, rank, A, n, G);
}
size_t*P=FFLAS::fflas_new<size_t>(n);
if (rpm){
chrono.clear();
if (i) chrono.start();
FFPACK::fsytrf_RPM (F, uplo, n, A, n, P, threshold);
if (i) chrono.stop();
}else{
if (!par){
chrono.clear();
if (i) chrono.start();
FFPACK::fsytrf (F, uplo, n, A, n, threshold);
if (i) chrono.stop();
}else{
chrono.clear();
if (i) chrono.start();
PAR_BLOCK{
FFPACK::fsytrf (F, uplo, n, A, n, SPLITTER(t),threshold);
}
if (i) chrono.stop();
}
}
FFLAS::fflas_delete(P);
if (i) time[i-1]=chrono.realtime();
FFLAS::fflas_delete( A);
}
std::sort(time, time+iter);
double mediantime = time[iter/2];
delete[] time;
// -----------
// Standard output for benchmark - Alexis Breust 2014/11/14
#define CUBE(x) ((x)*(x)*(x))
double gfops = 1.0/3.0*CUBE(double(rank)/1000.0) +n/1000.0*n/1000.0*double(rank)/1000.0 - double(rank)/1000.0*double(rank)/1000.0*n/1000;
std::cout << "Time: " << mediantime << " Gfops: " << gfops / mediantime;
FFLAS::writeCommandString(std::cout, as) << std::endl;
return 0;
}
<commit_msg>change option name<commit_after>/* -*- mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */
// vim:sts=4:sw=4:ts=4:noet:sr:cino=>s,f0,{0,g0,(0,\:0,t0,+0,=s
/* Copyright (c) FFLAS-FFPACK
* Written by Clément Pernet <clement.pernet@imag.fr>
* ========LICENCE========
* This file is part of the library FFLAS-FFPACK.
*
* FFLAS-FFPACK 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 Street, Fifth Floor, Boston, MA 02110-1301 USA
* ========LICENCE========
*/
//#define __FFPACK_FSYTRF_BC_RL
#undef __FFPACK_FSYTRF_BC_RL
#define __FFPACK_FSYTRF_BC_CROUT
#include "fflas-ffpack/fflas-ffpack-config.h"
#include <iostream>
#include <givaro/modular.h>
#include "fflas-ffpack/fflas-ffpack.h"
#include "fflas-ffpack/utils/timer.h"
#include "fflas-ffpack/utils/fflas_io.h"
#include "fflas-ffpack/utils/args-parser.h"
using namespace std;
int main(int argc, char** argv) {
size_t iter = 3;
int q = 131071;
size_t n = 1000;
size_t threshold = 64;
size_t rank = 500;
bool up =true;
bool rpm =true;
bool grp =true;
bool par =false;
int t=MAX_THREADS;
std::string file = "";
Argument as[] = {
{ 'q', "-q Q", "Set the field characteristic (-1 for random).", TYPE_INT , &q },
{ 'n', "-n N", "Set the dimension of the matrix.", TYPE_INT , &n },
{ 'u', "-u yes/no", "Computes a UTDU (true) or LDLT decomposition (false).", TYPE_BOOL , &up },
{ 'm', "-m yes/no", "Use the rank profile matrix revealing algorithm.", TYPE_BOOL , &rpm },
{ 'r', "-r R", "Set the rank (for the RPM version).", TYPE_INT , &rank },
{ 'g', "-g yes/no", "Matrix with generic rank profile (yes) or random rank profile matrix (no).", TYPE_BOOL , &grp },
{ 'i', "-i I", "Set number of repetitions.", TYPE_INT , &iter },
{ 'c', "-c C", "Set the cross-over point to the base case.", TYPE_INT , &threshold },
{ 'f', "-f FILE", "Set the input file (empty for random).", TYPE_STR , &file },
{ 'p', "-p P", "whether to run or not the parallel PLUQ", TYPE_BOOL , &par },
{ 't', "-t T", "number of virtual threads to drive the partition.", TYPE_INT , &t },
END_OF_ARGUMENTS
};
FFLAS::parseArguments(argc,argv,as);
rank=std::min(n,rank);
typedef Givaro::ModularBalanced<double> Field;
typedef Field::Element Element;
Field F(q);
Field::Element * A;
FFLAS::Timer chrono;
FFLAS::FFLAS_UPLO uplo = up?FFLAS::FflasUpper:FFLAS::FflasLower;
double *time=new double[iter];
for (size_t i=0; i<iter; i++) time[i]=0;
for (size_t i=0;i<=iter;++i){
if (!file.empty()){
FFLAS::ReadMatrix (file.c_str(),F,n,n,A);
}
else {
A = FFLAS::fflas_new<Element>(n*n);
Field::RandIter G(F);
if (grp){
size_t * cols = FFLAS::fflas_new<size_t>(n);
size_t * rows = FFLAS::fflas_new<size_t>(n);
for (size_t i=0; i<n; ++i)
cols[i] = rows[i] = i;
FFPACK::RandomSymmetricMatrixWithRankandRPM (F, n, rank, A, n, rows, cols, G);
FFLAS::fflas_delete(cols);
FFLAS::fflas_delete(rows);
} else
FFPACK::RandomSymmetricMatrixWithRankandRandomRPM (F, n, rank, A, n, G);
}
size_t*P=FFLAS::fflas_new<size_t>(n);
if (rpm){
chrono.clear();
if (i) chrono.start();
FFPACK::fsytrf_RPM (F, uplo, n, A, n, P, threshold);
if (i) chrono.stop();
}else{
if (!par){
chrono.clear();
if (i) chrono.start();
FFPACK::fsytrf (F, uplo, n, A, n, threshold);
if (i) chrono.stop();
}else{
chrono.clear();
if (i) chrono.start();
PAR_BLOCK{
FFPACK::fsytrf (F, uplo, n, A, n, SPLITTER(t),threshold);
}
if (i) chrono.stop();
}
}
FFLAS::fflas_delete(P);
if (i) time[i-1]=chrono.realtime();
FFLAS::fflas_delete( A);
}
std::sort(time, time+iter);
double mediantime = time[iter/2];
delete[] time;
// -----------
// Standard output for benchmark - Alexis Breust 2014/11/14
#define CUBE(x) ((x)*(x)*(x))
double gfops = 1.0/3.0*CUBE(double(rank)/1000.0) +n/1000.0*n/1000.0*double(rank)/1000.0 - double(rank)/1000.0*double(rank)/1000.0*n/1000;
std::cout << "Time: " << mediantime << " Gfops: " << gfops / mediantime;
FFLAS::writeCommandString(std::cout, as) << std::endl;
return 0;
}
<|endoftext|> |
<commit_before>/****************************************************************************
**
** Copyright (C) 2009 Marcin Juszkiewicz
** All rights reserved.
** Contact: Marcin Juszkiewicz <marcin@juszkiewicz.com.pl>
**
** GNU Lesser General Public License Usage
** This file may be used under the terms of the GNU Lesser General Public
** License version 2.1 as published by the Free Software Foundation and
** appearing in the file LICENSE.LGPL included in the packaging of this
** file. Please review the following information to ensure the GNU
** Lesser General Public License version 2.1 requirements will be met:
** http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
**
****************************************************************************/
#include "modland-player.h"
QString moduleFileName;
ModlandPlayer::ModlandPlayer()
{
qDebug() << "ModlandPlayer::ModlandPlayer()";
mainUI = new DesktopUI();
modulePath = "modules/";
DoConnects();
InitializeAuthorsList();
sound_init(44100, 2);
xmp_ctx = xmp_create_context();
playerThread = new QThread();
}
ModlandPlayer::~ModlandPlayer()
{
sound_deinit();
}
void ModlandPlayer::InitializeAuthorsList()
{
qDebug() << "ModlandPlayer::InitializeAuthorsList()";
QSqlDatabase db = QSqlDatabase::addDatabase("QSQLITE");
db.setDatabaseName("utwory.sqlite");
db.open();
QSqlQuery query("SELECT id, title FROM authors ORDER BY title");
QStringList authors;
while (query.next()) {
authors << query.value(1).toString();
}
UI_PopulateAuthorsList(authors);
};
void ModlandPlayer::UI_PopulateAuthorsList(QStringList authors)
{
qDebug() << "ModlandPlayer::UI_PopulateAuthorsList" ;
mainUI->AuthorsList->insertItems(1, authors);
PopulateSongs(mainUI->AuthorsList->item(0));
}
void ModlandPlayer::UI_SetSongInfo(const xmp_module* mi)
{
mainUI->TitleInfo->setText(mi->name);
mainUI->TypeInfo->setText(mi->type);
mainUI->playBar->setMaximum(mi->len);
QString instruments;
for(int i = 0; i < mi->ins; i++)
{
struct xmp_instrument *ins = &mi->xxi[i];
instruments += QString::asprintf("%02d: ", i);
instruments += ins->name;
instruments += "\n";
}
mainUI->InstrumentsList->setPlainText(instruments);
}
void ModlandPlayer::JustPlay(QString fileName)
{
qDebug() << "ModlandPlayer::JustPlay()";
struct xmp_module_info mi;
QByteArray ba = fileName.toLocal8Bit();
xmp_load_module(xmp_ctx, ba.data());
/* Show module data */
xmp_get_module_info(xmp_ctx, &mi);
UI_SetSongInfo(mi.mod);
if( playerThread->isRunning() )
{
playerThread->exit();
playerThread->wait();
}
playerThread = QThread::create(PlayModule, xmp_ctx, mainUI->playBar);
playerThread->setObjectName(mi.mod->name);
playerThread->start();
}
void PlayModule(xmp_context xmp_ctx, QProgressBar* playBar)
{
struct xmp_frame_info fi;
if (xmp_start_player(xmp_ctx, 44100, 0) == 0) {
/* Play module */
int row = -1;
while (xmp_play_frame(xmp_ctx) == 0) {
xmp_get_frame_info(xmp_ctx, &fi);
if (fi.loop_count > 0)
break;
if ( QThread::currentThread()->isInterruptionRequested() )
{
qDebug() << "PlayModule asked to quit";
break;
}
sound_play(fi.buffer, fi.buffer_size);
if (fi.row != row) {
playBar->setValue(fi.pos);
row = fi.row;
}
}
xmp_end_player(xmp_ctx);
}
// xmp_release_module(xmp_ctx);
}
void ModlandPlayer::PlaySelected(QListWidgetItem* selectedItem)
{
qDebug() << "ModlandPlayer::PlaySelected()";
QString fileName = buildModuleName(selectedItem->text());
qDebug() << "\t" << "PlaySelected - module to play: " << fileName ;
if(!QFile::exists(fileName))
{
qDebug() << "\t" << "PlaySelected - module not available";
FetchSong(buildModuleName(selectedItem->text(), false));
}
else
{
JustPlay(fileName);
}
}
void ModlandPlayer::PopulateSongs(QListWidgetItem* selectedItem)
{
qDebug() << "ModlandPlayer::PopulateSongs()";
CurrentAuthor = selectedItem->text();
qDebug() << "SELECT id FROM authors WHERE title = '" + CurrentAuthor + "'";
QSqlQuery query("SELECT id FROM authors WHERE title = '" + CurrentAuthor + "'");
query.first();
query.exec("SELECT title FROM songs WHERE author_id = " + query.value(0).toString() + " ORDER BY title");
qDebug() << "\t" << "PopulateSongs - switching to author: " << CurrentAuthor;
qDebug() << "\t" << "SELECT title FROM songs WHERE author_id = " + query.value(0).toString() + " ORDER BY title";
QStringList songs;
while (query.next()) {
songs << query.value(0).toString().remove(QRegExp(".mod$"));
}
UI_PopulateSongsList(songs);
}
void ModlandPlayer::UI_PopulateSongsList(QStringList songs)
{
mainUI->SongsList->clear();
mainUI->SongsList->insertItems(0, songs);
}
bool ModlandPlayer::UI_IsItLastSong()
{
return (mainUI->SongsList->currentRow() == (mainUI->SongsList->count() - 1));
}
QListWidgetItem* ModlandPlayer::UI_NextAuthorName()
{
return mainUI->AuthorsList->item(mainUI->AuthorsList->currentRow() + 1);
}
void ModlandPlayer::FinishedPlaying()
{
qDebug() << "ModlandPlayer::FinishedPlaying()";
QListWidgetItem* selectedItem;
if(UI_IsItLastSong())
{
PopulateSongs(UI_NextAuthorName());
selectedItem = mainUI->SongsList->item(0);
mainUI->AuthorsList->setCurrentRow(mainUI->AuthorsList->currentRow() + 1);
mainUI->SongsList->setCurrentRow(0);
}
else
{
selectedItem = mainUI->SongsList->item(mainUI->SongsList->currentRow() + 1);
mainUI->SongsList->setCurrentRow(mainUI->SongsList->currentRow() + 1);
}
qDebug() << "\t" << "play?";
PlaySelected(selectedItem);
}
void ModlandPlayer::FetchSong(QString fileName)
{
qDebug() << "ModlandPlayer::FetchSong()";
QNetworkAccessManager *manager = new QNetworkAccessManager(this);
connect(manager, SIGNAL(finished(QNetworkReply*)), this, SLOT(downloadFinished(QNetworkReply*)));
QString urlSong = "http://ftp.amigascne.org/mirrors/ftp.modland.com/pub/modules/Protracker/" + fileName ;
qDebug() << "\t" << "FetchSong - module to fetch: " << urlSong ;
QNetworkReply* reply = manager->get(QNetworkRequest(QUrl(urlSong)));
connect(reply, SIGNAL(downloadProgress(qint64, qint64)), this, SLOT(handleProgressBar(qint64, qint64)));
connect(reply, SIGNAL(error(QNetworkReply::NetworkError)), this, SLOT(handleError(QNetworkReply::NetworkError)));
mainUI->progressBar->setFormat("Fetching " + fileName);
mainUI->progressBar->show();
qDebug() << "\t" << "FetchSong - end" ;
}
void ModlandPlayer::handleError(QNetworkReply::NetworkError errorcode)
{
qDebug() << "ModlandPlayer::handleError()";
mainUI->progressBar->hide();
if (errorcode != QNetworkReply::NoError)
{
QErrorMessage message;
QString errorValue;
QMetaObject meta = QNetworkReply::staticMetaObject;
for (int i=0; i < meta.enumeratorCount(); ++i)
{
QMetaEnum m = meta.enumerator(i);
if (m.name() == QLatin1String("NetworkError"))
{
errorValue = QLatin1String(m.valueToKey(errorcode));
break;
}
}
message.showMessage(errorValue);
}
}
void ModlandPlayer::handleProgressBar(qint64 bytesfetched, qint64 bytestotal)
{
qDebug() << "ModlandPlayer::handleProgressBar()";
mainUI->progressBar->setMaximum(bytestotal);
mainUI->progressBar->setValue(bytesfetched);
}
void ModlandPlayer::downloadFinished(QNetworkReply *reply)
{
qDebug() << "ModlandPlayer::downloadFinished()";
QUrl url = reply->url();
if(reply->error())
{
//TODO
qDebug() << "\t" << "downloadFinished error: " + reply->errorString();
}
else
{
QDir* katalog = new QDir();
katalog->mkpath(modulePath + CurrentAuthor);
QFileInfo fileinfo(url.path());
QString fileName = buildModuleName(fileinfo.baseName());
qDebug() << "\t" << "downloadFinished - module will be " + fileName;
QFile file(fileName);
if(file.open(QIODevice::WriteOnly))
{
file.write(reply->readAll());
file.close();
qDebug() << "\t" << "downloadFinished - module fetched";
mainUI->progressBar->resetFormat();
mainUI->progressBar->reset();
JustPlay(fileName);
}
else
{
qDebug() << "\t downloadFinished with error: " + file.errorString();
}
}
}
QString ModlandPlayer::buildModuleName(QString title, bool localName)
{
QString fullName;
if(localName)
fullName.append(modulePath);
fullName += CurrentAuthor + "/" + title + ".mod";
return fullName;
}
void ModlandPlayer::handleFavorite()
{
qDebug() << "ModlandPlayer::handleFavorite()";
}
void ModlandPlayer::DoConnects()
{
qDebug() << "ModlandPlayer::DoConnects()";
connect(mainUI->SongsList, SIGNAL(itemClicked(QListWidgetItem*)), this, SLOT(PlaySelected(QListWidgetItem*)));
connect(mainUI->AuthorsList, SIGNAL(itemClicked(QListWidgetItem*)), this, SLOT(PopulateSongs(QListWidgetItem*)));
connect(mainUI->actionNext, SIGNAL(triggered()), this, SLOT(FinishedPlaying()));
connect(mainUI->actionFavorite, SIGNAL(triggered()), this, SLOT(handleFavorite()));
}
void ModlandPlayer::show()
{
mainUI->show();
}
<commit_msg>fix: nie wywala się jak ostatni utwór ostatniego autora<commit_after>/****************************************************************************
**
** Copyright (C) 2009 Marcin Juszkiewicz
** All rights reserved.
** Contact: Marcin Juszkiewicz <marcin@juszkiewicz.com.pl>
**
** GNU Lesser General Public License Usage
** This file may be used under the terms of the GNU Lesser General Public
** License version 2.1 as published by the Free Software Foundation and
** appearing in the file LICENSE.LGPL included in the packaging of this
** file. Please review the following information to ensure the GNU
** Lesser General Public License version 2.1 requirements will be met:
** http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
**
****************************************************************************/
#include "modland-player.h"
QString moduleFileName;
ModlandPlayer::ModlandPlayer()
{
qDebug() << "ModlandPlayer::ModlandPlayer()";
mainUI = new DesktopUI();
modulePath = "modules/";
DoConnects();
InitializeAuthorsList();
sound_init(44100, 2);
xmp_ctx = xmp_create_context();
playerThread = new QThread();
}
ModlandPlayer::~ModlandPlayer()
{
sound_deinit();
}
void ModlandPlayer::InitializeAuthorsList()
{
qDebug() << "ModlandPlayer::InitializeAuthorsList()";
QSqlDatabase db = QSqlDatabase::addDatabase("QSQLITE");
db.setDatabaseName("utwory.sqlite");
db.open();
QSqlQuery query("SELECT id, title FROM authors ORDER BY title");
QStringList authors;
while (query.next()) {
authors << query.value(1).toString();
}
UI_PopulateAuthorsList(authors);
};
void ModlandPlayer::UI_PopulateAuthorsList(QStringList authors)
{
qDebug() << "ModlandPlayer::UI_PopulateAuthorsList" ;
mainUI->AuthorsList->insertItems(1, authors);
PopulateSongs(mainUI->AuthorsList->item(0));
}
void ModlandPlayer::UI_SetSongInfo(const xmp_module* mi)
{
mainUI->TitleInfo->setText(mi->name);
mainUI->TypeInfo->setText(mi->type);
mainUI->playBar->setMaximum(mi->len);
QString instruments;
for(int i = 0; i < mi->ins; i++)
{
struct xmp_instrument *ins = &mi->xxi[i];
instruments += QString::asprintf("%02d: ", i);
instruments += ins->name;
instruments += "\n";
}
mainUI->InstrumentsList->setPlainText(instruments);
}
void ModlandPlayer::JustPlay(QString fileName)
{
qDebug() << "ModlandPlayer::JustPlay()";
struct xmp_module_info mi;
QByteArray ba = fileName.toLocal8Bit();
xmp_load_module(xmp_ctx, ba.data());
/* Show module data */
xmp_get_module_info(xmp_ctx, &mi);
UI_SetSongInfo(mi.mod);
if( playerThread->isRunning() )
{
playerThread->exit();
playerThread->wait();
}
playerThread = QThread::create(PlayModule, xmp_ctx, mainUI->playBar);
playerThread->setObjectName(mi.mod->name);
playerThread->start();
}
void PlayModule(xmp_context xmp_ctx, QProgressBar* playBar)
{
struct xmp_frame_info fi;
if (xmp_start_player(xmp_ctx, 44100, 0) == 0) {
/* Play module */
int row = -1;
while (xmp_play_frame(xmp_ctx) == 0) {
xmp_get_frame_info(xmp_ctx, &fi);
if (fi.loop_count > 0)
break;
if ( QThread::currentThread()->isInterruptionRequested() )
{
qDebug() << "PlayModule asked to quit";
break;
}
sound_play(fi.buffer, fi.buffer_size);
if (fi.row != row) {
playBar->setValue(fi.pos);
row = fi.row;
}
}
xmp_end_player(xmp_ctx);
}
// xmp_release_module(xmp_ctx);
}
void ModlandPlayer::PlaySelected(QListWidgetItem* selectedItem)
{
qDebug() << "ModlandPlayer::PlaySelected()";
QString fileName = buildModuleName(selectedItem->text());
qDebug() << "\t" << "PlaySelected - module to play: " << fileName ;
if(!QFile::exists(fileName))
{
qDebug() << "\t" << "PlaySelected - module not available";
FetchSong(buildModuleName(selectedItem->text(), false));
}
else
{
JustPlay(fileName);
}
}
void ModlandPlayer::PopulateSongs(QListWidgetItem* selectedItem)
{
qDebug() << "ModlandPlayer::PopulateSongs()";
CurrentAuthor = selectedItem->text();
qDebug() << "SELECT id FROM authors WHERE title = '" + CurrentAuthor + "'";
QSqlQuery query("SELECT id FROM authors WHERE title = '" + CurrentAuthor + "'");
query.first();
query.exec("SELECT title FROM songs WHERE author_id = " + query.value(0).toString() + " ORDER BY title");
qDebug() << "\t" << "PopulateSongs - switching to author: " << CurrentAuthor;
qDebug() << "\t" << "SELECT title FROM songs WHERE author_id = " + query.value(0).toString() + " ORDER BY title";
QStringList songs;
while (query.next()) {
songs << query.value(0).toString().remove(QRegExp(".mod$"));
}
UI_PopulateSongsList(songs);
}
void ModlandPlayer::UI_PopulateSongsList(QStringList songs)
{
mainUI->SongsList->clear();
mainUI->SongsList->insertItems(0, songs);
}
bool ModlandPlayer::UI_IsItLastSong()
{
return (mainUI->SongsList->currentRow() == (mainUI->SongsList->count() - 1));
}
QListWidgetItem* ModlandPlayer::UI_NextAuthorName()
{
if(mainUI->AuthorsList->currentRow() < mainUI->AuthorsList->count() - 1)
{
return mainUI->AuthorsList->item(mainUI->AuthorsList->currentRow() + 1);
}
else
{
return mainUI->AuthorsList->item(0);
}
}
void ModlandPlayer::FinishedPlaying()
{
qDebug() << "ModlandPlayer::FinishedPlaying()";
QListWidgetItem* selectedItem;
if(UI_IsItLastSong())
{
PopulateSongs(UI_NextAuthorName());
selectedItem = mainUI->SongsList->item(0);
if(mainUI->AuthorsList->currentRow() < mainUI->AuthorsList->count())
{
mainUI->AuthorsList->setCurrentRow(mainUI->AuthorsList->currentRow() + 1);
}
else
{
mainUI->AuthorsList->setCurrentRow(0);
}
mainUI->SongsList->setCurrentRow(0);
}
else
{
selectedItem = mainUI->SongsList->item(mainUI->SongsList->currentRow() + 1);
mainUI->SongsList->setCurrentRow(mainUI->SongsList->currentRow() + 1);
}
qDebug() << "\t" << "play?";
PlaySelected(selectedItem);
}
void ModlandPlayer::FetchSong(QString fileName)
{
qDebug() << "ModlandPlayer::FetchSong()";
QNetworkAccessManager *manager = new QNetworkAccessManager(this);
connect(manager, SIGNAL(finished(QNetworkReply*)), this, SLOT(downloadFinished(QNetworkReply*)));
QString urlSong = "http://ftp.amigascne.org/mirrors/ftp.modland.com/pub/modules/Protracker/" + fileName ;
qDebug() << "\t" << "FetchSong - module to fetch: " << urlSong ;
QNetworkReply* reply = manager->get(QNetworkRequest(QUrl(urlSong)));
connect(reply, SIGNAL(downloadProgress(qint64, qint64)), this, SLOT(handleProgressBar(qint64, qint64)));
connect(reply, SIGNAL(error(QNetworkReply::NetworkError)), this, SLOT(handleError(QNetworkReply::NetworkError)));
mainUI->progressBar->setFormat("Fetching " + fileName);
mainUI->progressBar->show();
qDebug() << "\t" << "FetchSong - end" ;
}
void ModlandPlayer::handleError(QNetworkReply::NetworkError errorcode)
{
qDebug() << "ModlandPlayer::handleError()";
mainUI->progressBar->hide();
if (errorcode != QNetworkReply::NoError)
{
QErrorMessage message;
QString errorValue;
QMetaObject meta = QNetworkReply::staticMetaObject;
for (int i=0; i < meta.enumeratorCount(); ++i)
{
QMetaEnum m = meta.enumerator(i);
if (m.name() == QLatin1String("NetworkError"))
{
errorValue = QLatin1String(m.valueToKey(errorcode));
break;
}
}
message.showMessage(errorValue);
}
}
void ModlandPlayer::handleProgressBar(qint64 bytesfetched, qint64 bytestotal)
{
qDebug() << "ModlandPlayer::handleProgressBar()";
mainUI->progressBar->setMaximum(bytestotal);
mainUI->progressBar->setValue(bytesfetched);
}
void ModlandPlayer::downloadFinished(QNetworkReply *reply)
{
qDebug() << "ModlandPlayer::downloadFinished()";
QUrl url = reply->url();
if(reply->error())
{
//TODO
qDebug() << "\t" << "downloadFinished error: " + reply->errorString();
}
else
{
QDir* katalog = new QDir();
katalog->mkpath(modulePath + CurrentAuthor);
QFileInfo fileinfo(url.path());
QString fileName = buildModuleName(fileinfo.baseName());
qDebug() << "\t" << "downloadFinished - module will be " + fileName;
QFile file(fileName);
if(file.open(QIODevice::WriteOnly))
{
file.write(reply->readAll());
file.close();
qDebug() << "\t" << "downloadFinished - module fetched";
mainUI->progressBar->resetFormat();
mainUI->progressBar->reset();
JustPlay(fileName);
}
else
{
qDebug() << "\t downloadFinished with error: " + file.errorString();
}
}
}
QString ModlandPlayer::buildModuleName(QString title, bool localName)
{
QString fullName;
if(localName)
fullName.append(modulePath);
fullName += CurrentAuthor + "/" + title + ".mod";
return fullName;
}
void ModlandPlayer::handleFavorite()
{
qDebug() << "ModlandPlayer::handleFavorite()";
}
void ModlandPlayer::DoConnects()
{
qDebug() << "ModlandPlayer::DoConnects()";
connect(mainUI->SongsList, SIGNAL(itemClicked(QListWidgetItem*)), this, SLOT(PlaySelected(QListWidgetItem*)));
connect(mainUI->AuthorsList, SIGNAL(itemClicked(QListWidgetItem*)), this, SLOT(PopulateSongs(QListWidgetItem*)));
connect(mainUI->actionNext, SIGNAL(triggered()), this, SLOT(FinishedPlaying()));
connect(mainUI->actionFavorite, SIGNAL(triggered()), this, SLOT(handleFavorite()));
}
void ModlandPlayer::show()
{
mainUI->show();
}
<|endoftext|> |
<commit_before>//===- llvm/unittest/ADT/ValueMapTest.cpp - ValueMap unit tests -*- C++ -*-===//
//
// The LLVM Compiler Infrastructure
//
// This file is distributed under the University of Illinois Open Source
// License. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//
#include "llvm/ADT/ValueMap.h"
#include "llvm/ADT/OwningPtr.h"
#include "llvm/Config/llvm-config.h"
#include "llvm/IR/Constants.h"
#include "llvm/IR/Instructions.h"
#include "llvm/IR/LLVMContext.h"
#include "gtest/gtest.h"
using namespace llvm;
namespace {
// Test fixture
template<typename T>
class ValueMapTest : public testing::Test {
protected:
Constant *ConstantV;
OwningPtr<BitCastInst> BitcastV;
OwningPtr<BinaryOperator> AddV;
ValueMapTest() :
ConstantV(ConstantInt::get(Type::getInt32Ty(getGlobalContext()), 0)),
BitcastV(new BitCastInst(ConstantV, Type::getInt32Ty(getGlobalContext()))),
AddV(BinaryOperator::CreateAdd(ConstantV, ConstantV)) {
}
};
// Run everything on Value*, a subtype to make sure that casting works as
// expected, and a const subtype to make sure we cast const correctly.
typedef ::testing::Types<Value, Instruction, const Instruction> KeyTypes;
TYPED_TEST_CASE(ValueMapTest, KeyTypes);
TYPED_TEST(ValueMapTest, Null) {
ValueMap<TypeParam*, int> VM1;
VM1[NULL] = 7;
EXPECT_EQ(7, VM1.lookup(NULL));
}
TYPED_TEST(ValueMapTest, FollowsValue) {
ValueMap<TypeParam*, int> VM;
VM[this->BitcastV.get()] = 7;
EXPECT_EQ(7, VM.lookup(this->BitcastV.get()));
EXPECT_EQ(0, VM.count(this->AddV.get()));
this->BitcastV->replaceAllUsesWith(this->AddV.get());
EXPECT_EQ(7, VM.lookup(this->AddV.get()));
EXPECT_EQ(0, VM.count(this->BitcastV.get()));
this->AddV.reset();
EXPECT_EQ(0, VM.count(this->AddV.get()));
EXPECT_EQ(0, VM.count(this->BitcastV.get()));
EXPECT_EQ(0U, VM.size());
}
TYPED_TEST(ValueMapTest, OperationsWork) {
ValueMap<TypeParam*, int> VM;
ValueMap<TypeParam*, int> VM2(16); (void)VM2;
typename ValueMapConfig<TypeParam*>::ExtraData Data;
ValueMap<TypeParam*, int> VM3(Data, 16); (void)VM3;
EXPECT_TRUE(VM.empty());
VM[this->BitcastV.get()] = 7;
// Find:
typename ValueMap<TypeParam*, int>::iterator I =
VM.find(this->BitcastV.get());
ASSERT_TRUE(I != VM.end());
EXPECT_EQ(this->BitcastV.get(), I->first);
EXPECT_EQ(7, I->second);
EXPECT_TRUE(VM.find(this->AddV.get()) == VM.end());
// Const find:
const ValueMap<TypeParam*, int> &CVM = VM;
typename ValueMap<TypeParam*, int>::const_iterator CI =
CVM.find(this->BitcastV.get());
ASSERT_TRUE(CI != CVM.end());
EXPECT_EQ(this->BitcastV.get(), CI->first);
EXPECT_EQ(7, CI->second);
EXPECT_TRUE(CVM.find(this->AddV.get()) == CVM.end());
// Insert:
std::pair<typename ValueMap<TypeParam*, int>::iterator, bool> InsertResult1 =
VM.insert(std::make_pair(this->AddV.get(), 3));
EXPECT_EQ(this->AddV.get(), InsertResult1.first->first);
EXPECT_EQ(3, InsertResult1.first->second);
EXPECT_TRUE(InsertResult1.second);
EXPECT_EQ(true, VM.count(this->AddV.get()));
std::pair<typename ValueMap<TypeParam*, int>::iterator, bool> InsertResult2 =
VM.insert(std::make_pair(this->AddV.get(), 5));
EXPECT_EQ(this->AddV.get(), InsertResult2.first->first);
EXPECT_EQ(3, InsertResult2.first->second);
EXPECT_FALSE(InsertResult2.second);
// Erase:
VM.erase(InsertResult2.first);
EXPECT_EQ(0U, VM.count(this->AddV.get()));
EXPECT_EQ(1U, VM.count(this->BitcastV.get()));
VM.erase(this->BitcastV.get());
EXPECT_EQ(0U, VM.count(this->BitcastV.get()));
EXPECT_EQ(0U, VM.size());
// Range insert:
SmallVector<std::pair<Instruction*, int>, 2> Elems;
Elems.push_back(std::make_pair(this->AddV.get(), 1));
Elems.push_back(std::make_pair(this->BitcastV.get(), 2));
VM.insert(Elems.begin(), Elems.end());
EXPECT_EQ(1, VM.lookup(this->AddV.get()));
EXPECT_EQ(2, VM.lookup(this->BitcastV.get()));
}
template<typename ExpectedType, typename VarType>
void CompileAssertHasType(VarType) {
LLVM_ATTRIBUTE_UNUSED typedef char
NOT_SAME[is_same<ExpectedType, VarType>::value ? 1 : -1];
}
TYPED_TEST(ValueMapTest, Iteration) {
ValueMap<TypeParam*, int> VM;
VM[this->BitcastV.get()] = 2;
VM[this->AddV.get()] = 3;
size_t size = 0;
for (typename ValueMap<TypeParam*, int>::iterator I = VM.begin(), E = VM.end();
I != E; ++I) {
++size;
std::pair<TypeParam*, int> value = *I; (void)value;
CompileAssertHasType<TypeParam*>(I->first);
if (I->second == 2) {
EXPECT_EQ(this->BitcastV.get(), I->first);
I->second = 5;
} else if (I->second == 3) {
EXPECT_EQ(this->AddV.get(), I->first);
I->second = 6;
} else {
ADD_FAILURE() << "Iterated through an extra value.";
}
}
EXPECT_EQ(2U, size);
EXPECT_EQ(5, VM[this->BitcastV.get()]);
EXPECT_EQ(6, VM[this->AddV.get()]);
size = 0;
// Cast to const ValueMap to avoid a bug in DenseMap's iterators.
const ValueMap<TypeParam*, int>& CVM = VM;
for (typename ValueMap<TypeParam*, int>::const_iterator I = CVM.begin(),
E = CVM.end(); I != E; ++I) {
++size;
std::pair<TypeParam*, int> value = *I; (void)value;
CompileAssertHasType<TypeParam*>(I->first);
if (I->second == 5) {
EXPECT_EQ(this->BitcastV.get(), I->first);
} else if (I->second == 6) {
EXPECT_EQ(this->AddV.get(), I->first);
} else {
ADD_FAILURE() << "Iterated through an extra value.";
}
}
EXPECT_EQ(2U, size);
}
TYPED_TEST(ValueMapTest, DefaultCollisionBehavior) {
// By default, we overwrite the old value with the replaced value.
ValueMap<TypeParam*, int> VM;
VM[this->BitcastV.get()] = 7;
VM[this->AddV.get()] = 9;
this->BitcastV->replaceAllUsesWith(this->AddV.get());
EXPECT_EQ(0, VM.count(this->BitcastV.get()));
EXPECT_EQ(9, VM.lookup(this->AddV.get()));
}
TYPED_TEST(ValueMapTest, ConfiguredCollisionBehavior) {
// TODO: Implement this when someone needs it.
}
template<typename KeyT>
struct LockMutex : ValueMapConfig<KeyT> {
struct ExtraData {
sys::Mutex *M;
bool *CalledRAUW;
bool *CalledDeleted;
};
static void onRAUW(const ExtraData &Data, KeyT Old, KeyT New) {
*Data.CalledRAUW = true;
EXPECT_FALSE(Data.M->tryacquire()) << "Mutex should already be locked.";
}
static void onDelete(const ExtraData &Data, KeyT Old) {
*Data.CalledDeleted = true;
EXPECT_FALSE(Data.M->tryacquire()) << "Mutex should already be locked.";
}
static sys::Mutex *getMutex(const ExtraData &Data) { return Data.M; }
};
#if LLVM_ENABLE_THREADS
TYPED_TEST(ValueMapTest, LocksMutex) {
sys::Mutex M(false); // Not recursive.
bool CalledRAUW = false, CalledDeleted = false;
typename LockMutex<TypeParam*>::ExtraData Data =
{&M, &CalledRAUW, &CalledDeleted};
ValueMap<TypeParam*, int, LockMutex<TypeParam*> > VM(Data);
VM[this->BitcastV.get()] = 7;
this->BitcastV->replaceAllUsesWith(this->AddV.get());
this->AddV.reset();
EXPECT_TRUE(CalledRAUW);
EXPECT_TRUE(CalledDeleted);
}
#endif
template<typename KeyT>
struct NoFollow : ValueMapConfig<KeyT> {
enum { FollowRAUW = false };
};
TYPED_TEST(ValueMapTest, NoFollowRAUW) {
ValueMap<TypeParam*, int, NoFollow<TypeParam*> > VM;
VM[this->BitcastV.get()] = 7;
EXPECT_EQ(7, VM.lookup(this->BitcastV.get()));
EXPECT_EQ(0, VM.count(this->AddV.get()));
this->BitcastV->replaceAllUsesWith(this->AddV.get());
EXPECT_EQ(7, VM.lookup(this->BitcastV.get()));
EXPECT_EQ(0, VM.lookup(this->AddV.get()));
this->AddV.reset();
EXPECT_EQ(7, VM.lookup(this->BitcastV.get()));
EXPECT_EQ(0, VM.lookup(this->AddV.get()));
this->BitcastV.reset();
EXPECT_EQ(0, VM.lookup(this->BitcastV.get()));
EXPECT_EQ(0, VM.lookup(this->AddV.get()));
EXPECT_EQ(0U, VM.size());
}
template<typename KeyT>
struct CountOps : ValueMapConfig<KeyT> {
struct ExtraData {
int *Deletions;
int *RAUWs;
};
static void onRAUW(const ExtraData &Data, KeyT Old, KeyT New) {
++*Data.RAUWs;
}
static void onDelete(const ExtraData &Data, KeyT Old) {
++*Data.Deletions;
}
};
TYPED_TEST(ValueMapTest, CallsConfig) {
int Deletions = 0, RAUWs = 0;
typename CountOps<TypeParam*>::ExtraData Data = {&Deletions, &RAUWs};
ValueMap<TypeParam*, int, CountOps<TypeParam*> > VM(Data);
VM[this->BitcastV.get()] = 7;
this->BitcastV->replaceAllUsesWith(this->AddV.get());
EXPECT_EQ(0, Deletions);
EXPECT_EQ(1, RAUWs);
this->AddV.reset();
EXPECT_EQ(1, Deletions);
EXPECT_EQ(1, RAUWs);
this->BitcastV.reset();
EXPECT_EQ(1, Deletions);
EXPECT_EQ(1, RAUWs);
}
template<typename KeyT>
struct ModifyingConfig : ValueMapConfig<KeyT> {
// We'll put a pointer here back to the ValueMap this key is in, so
// that we can modify it (and clobber *this) before the ValueMap
// tries to do the same modification. In previous versions of
// ValueMap, that exploded.
typedef ValueMap<KeyT, int, ModifyingConfig<KeyT> > **ExtraData;
static void onRAUW(ExtraData Map, KeyT Old, KeyT New) {
(*Map)->erase(Old);
}
static void onDelete(ExtraData Map, KeyT Old) {
(*Map)->erase(Old);
}
};
TYPED_TEST(ValueMapTest, SurvivesModificationByConfig) {
ValueMap<TypeParam*, int, ModifyingConfig<TypeParam*> > *MapAddress;
ValueMap<TypeParam*, int, ModifyingConfig<TypeParam*> > VM(&MapAddress);
MapAddress = &VM;
// Now the ModifyingConfig can modify the Map inside a callback.
VM[this->BitcastV.get()] = 7;
this->BitcastV->replaceAllUsesWith(this->AddV.get());
EXPECT_FALSE(VM.count(this->BitcastV.get()));
EXPECT_FALSE(VM.count(this->AddV.get()));
VM[this->AddV.get()] = 7;
this->AddV.reset();
EXPECT_FALSE(VM.count(this->AddV.get()));
}
}
<commit_msg>Use LLVM_STATIC_ASSERT rather than a hand-rolled implementation.<commit_after>//===- llvm/unittest/ADT/ValueMapTest.cpp - ValueMap unit tests -*- C++ -*-===//
//
// The LLVM Compiler Infrastructure
//
// This file is distributed under the University of Illinois Open Source
// License. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//
#include "llvm/ADT/ValueMap.h"
#include "llvm/ADT/OwningPtr.h"
#include "llvm/Config/llvm-config.h"
#include "llvm/IR/Constants.h"
#include "llvm/IR/Instructions.h"
#include "llvm/IR/LLVMContext.h"
#include "gtest/gtest.h"
using namespace llvm;
namespace {
// Test fixture
template<typename T>
class ValueMapTest : public testing::Test {
protected:
Constant *ConstantV;
OwningPtr<BitCastInst> BitcastV;
OwningPtr<BinaryOperator> AddV;
ValueMapTest() :
ConstantV(ConstantInt::get(Type::getInt32Ty(getGlobalContext()), 0)),
BitcastV(new BitCastInst(ConstantV, Type::getInt32Ty(getGlobalContext()))),
AddV(BinaryOperator::CreateAdd(ConstantV, ConstantV)) {
}
};
// Run everything on Value*, a subtype to make sure that casting works as
// expected, and a const subtype to make sure we cast const correctly.
typedef ::testing::Types<Value, Instruction, const Instruction> KeyTypes;
TYPED_TEST_CASE(ValueMapTest, KeyTypes);
TYPED_TEST(ValueMapTest, Null) {
ValueMap<TypeParam*, int> VM1;
VM1[NULL] = 7;
EXPECT_EQ(7, VM1.lookup(NULL));
}
TYPED_TEST(ValueMapTest, FollowsValue) {
ValueMap<TypeParam*, int> VM;
VM[this->BitcastV.get()] = 7;
EXPECT_EQ(7, VM.lookup(this->BitcastV.get()));
EXPECT_EQ(0, VM.count(this->AddV.get()));
this->BitcastV->replaceAllUsesWith(this->AddV.get());
EXPECT_EQ(7, VM.lookup(this->AddV.get()));
EXPECT_EQ(0, VM.count(this->BitcastV.get()));
this->AddV.reset();
EXPECT_EQ(0, VM.count(this->AddV.get()));
EXPECT_EQ(0, VM.count(this->BitcastV.get()));
EXPECT_EQ(0U, VM.size());
}
TYPED_TEST(ValueMapTest, OperationsWork) {
ValueMap<TypeParam*, int> VM;
ValueMap<TypeParam*, int> VM2(16); (void)VM2;
typename ValueMapConfig<TypeParam*>::ExtraData Data;
ValueMap<TypeParam*, int> VM3(Data, 16); (void)VM3;
EXPECT_TRUE(VM.empty());
VM[this->BitcastV.get()] = 7;
// Find:
typename ValueMap<TypeParam*, int>::iterator I =
VM.find(this->BitcastV.get());
ASSERT_TRUE(I != VM.end());
EXPECT_EQ(this->BitcastV.get(), I->first);
EXPECT_EQ(7, I->second);
EXPECT_TRUE(VM.find(this->AddV.get()) == VM.end());
// Const find:
const ValueMap<TypeParam*, int> &CVM = VM;
typename ValueMap<TypeParam*, int>::const_iterator CI =
CVM.find(this->BitcastV.get());
ASSERT_TRUE(CI != CVM.end());
EXPECT_EQ(this->BitcastV.get(), CI->first);
EXPECT_EQ(7, CI->second);
EXPECT_TRUE(CVM.find(this->AddV.get()) == CVM.end());
// Insert:
std::pair<typename ValueMap<TypeParam*, int>::iterator, bool> InsertResult1 =
VM.insert(std::make_pair(this->AddV.get(), 3));
EXPECT_EQ(this->AddV.get(), InsertResult1.first->first);
EXPECT_EQ(3, InsertResult1.first->second);
EXPECT_TRUE(InsertResult1.second);
EXPECT_EQ(true, VM.count(this->AddV.get()));
std::pair<typename ValueMap<TypeParam*, int>::iterator, bool> InsertResult2 =
VM.insert(std::make_pair(this->AddV.get(), 5));
EXPECT_EQ(this->AddV.get(), InsertResult2.first->first);
EXPECT_EQ(3, InsertResult2.first->second);
EXPECT_FALSE(InsertResult2.second);
// Erase:
VM.erase(InsertResult2.first);
EXPECT_EQ(0U, VM.count(this->AddV.get()));
EXPECT_EQ(1U, VM.count(this->BitcastV.get()));
VM.erase(this->BitcastV.get());
EXPECT_EQ(0U, VM.count(this->BitcastV.get()));
EXPECT_EQ(0U, VM.size());
// Range insert:
SmallVector<std::pair<Instruction*, int>, 2> Elems;
Elems.push_back(std::make_pair(this->AddV.get(), 1));
Elems.push_back(std::make_pair(this->BitcastV.get(), 2));
VM.insert(Elems.begin(), Elems.end());
EXPECT_EQ(1, VM.lookup(this->AddV.get()));
EXPECT_EQ(2, VM.lookup(this->BitcastV.get()));
}
template<typename ExpectedType, typename VarType>
void CompileAssertHasType(VarType) {
LLVM_STATIC_ASSERT((is_same<ExpectedType, VarType>::value),
"Not the same type");
}
TYPED_TEST(ValueMapTest, Iteration) {
ValueMap<TypeParam*, int> VM;
VM[this->BitcastV.get()] = 2;
VM[this->AddV.get()] = 3;
size_t size = 0;
for (typename ValueMap<TypeParam*, int>::iterator I = VM.begin(), E = VM.end();
I != E; ++I) {
++size;
std::pair<TypeParam*, int> value = *I; (void)value;
CompileAssertHasType<TypeParam*>(I->first);
if (I->second == 2) {
EXPECT_EQ(this->BitcastV.get(), I->first);
I->second = 5;
} else if (I->second == 3) {
EXPECT_EQ(this->AddV.get(), I->first);
I->second = 6;
} else {
ADD_FAILURE() << "Iterated through an extra value.";
}
}
EXPECT_EQ(2U, size);
EXPECT_EQ(5, VM[this->BitcastV.get()]);
EXPECT_EQ(6, VM[this->AddV.get()]);
size = 0;
// Cast to const ValueMap to avoid a bug in DenseMap's iterators.
const ValueMap<TypeParam*, int>& CVM = VM;
for (typename ValueMap<TypeParam*, int>::const_iterator I = CVM.begin(),
E = CVM.end(); I != E; ++I) {
++size;
std::pair<TypeParam*, int> value = *I; (void)value;
CompileAssertHasType<TypeParam*>(I->first);
if (I->second == 5) {
EXPECT_EQ(this->BitcastV.get(), I->first);
} else if (I->second == 6) {
EXPECT_EQ(this->AddV.get(), I->first);
} else {
ADD_FAILURE() << "Iterated through an extra value.";
}
}
EXPECT_EQ(2U, size);
}
TYPED_TEST(ValueMapTest, DefaultCollisionBehavior) {
// By default, we overwrite the old value with the replaced value.
ValueMap<TypeParam*, int> VM;
VM[this->BitcastV.get()] = 7;
VM[this->AddV.get()] = 9;
this->BitcastV->replaceAllUsesWith(this->AddV.get());
EXPECT_EQ(0, VM.count(this->BitcastV.get()));
EXPECT_EQ(9, VM.lookup(this->AddV.get()));
}
TYPED_TEST(ValueMapTest, ConfiguredCollisionBehavior) {
// TODO: Implement this when someone needs it.
}
template<typename KeyT>
struct LockMutex : ValueMapConfig<KeyT> {
struct ExtraData {
sys::Mutex *M;
bool *CalledRAUW;
bool *CalledDeleted;
};
static void onRAUW(const ExtraData &Data, KeyT Old, KeyT New) {
*Data.CalledRAUW = true;
EXPECT_FALSE(Data.M->tryacquire()) << "Mutex should already be locked.";
}
static void onDelete(const ExtraData &Data, KeyT Old) {
*Data.CalledDeleted = true;
EXPECT_FALSE(Data.M->tryacquire()) << "Mutex should already be locked.";
}
static sys::Mutex *getMutex(const ExtraData &Data) { return Data.M; }
};
#if LLVM_ENABLE_THREADS
TYPED_TEST(ValueMapTest, LocksMutex) {
sys::Mutex M(false); // Not recursive.
bool CalledRAUW = false, CalledDeleted = false;
typename LockMutex<TypeParam*>::ExtraData Data =
{&M, &CalledRAUW, &CalledDeleted};
ValueMap<TypeParam*, int, LockMutex<TypeParam*> > VM(Data);
VM[this->BitcastV.get()] = 7;
this->BitcastV->replaceAllUsesWith(this->AddV.get());
this->AddV.reset();
EXPECT_TRUE(CalledRAUW);
EXPECT_TRUE(CalledDeleted);
}
#endif
template<typename KeyT>
struct NoFollow : ValueMapConfig<KeyT> {
enum { FollowRAUW = false };
};
TYPED_TEST(ValueMapTest, NoFollowRAUW) {
ValueMap<TypeParam*, int, NoFollow<TypeParam*> > VM;
VM[this->BitcastV.get()] = 7;
EXPECT_EQ(7, VM.lookup(this->BitcastV.get()));
EXPECT_EQ(0, VM.count(this->AddV.get()));
this->BitcastV->replaceAllUsesWith(this->AddV.get());
EXPECT_EQ(7, VM.lookup(this->BitcastV.get()));
EXPECT_EQ(0, VM.lookup(this->AddV.get()));
this->AddV.reset();
EXPECT_EQ(7, VM.lookup(this->BitcastV.get()));
EXPECT_EQ(0, VM.lookup(this->AddV.get()));
this->BitcastV.reset();
EXPECT_EQ(0, VM.lookup(this->BitcastV.get()));
EXPECT_EQ(0, VM.lookup(this->AddV.get()));
EXPECT_EQ(0U, VM.size());
}
template<typename KeyT>
struct CountOps : ValueMapConfig<KeyT> {
struct ExtraData {
int *Deletions;
int *RAUWs;
};
static void onRAUW(const ExtraData &Data, KeyT Old, KeyT New) {
++*Data.RAUWs;
}
static void onDelete(const ExtraData &Data, KeyT Old) {
++*Data.Deletions;
}
};
TYPED_TEST(ValueMapTest, CallsConfig) {
int Deletions = 0, RAUWs = 0;
typename CountOps<TypeParam*>::ExtraData Data = {&Deletions, &RAUWs};
ValueMap<TypeParam*, int, CountOps<TypeParam*> > VM(Data);
VM[this->BitcastV.get()] = 7;
this->BitcastV->replaceAllUsesWith(this->AddV.get());
EXPECT_EQ(0, Deletions);
EXPECT_EQ(1, RAUWs);
this->AddV.reset();
EXPECT_EQ(1, Deletions);
EXPECT_EQ(1, RAUWs);
this->BitcastV.reset();
EXPECT_EQ(1, Deletions);
EXPECT_EQ(1, RAUWs);
}
template<typename KeyT>
struct ModifyingConfig : ValueMapConfig<KeyT> {
// We'll put a pointer here back to the ValueMap this key is in, so
// that we can modify it (and clobber *this) before the ValueMap
// tries to do the same modification. In previous versions of
// ValueMap, that exploded.
typedef ValueMap<KeyT, int, ModifyingConfig<KeyT> > **ExtraData;
static void onRAUW(ExtraData Map, KeyT Old, KeyT New) {
(*Map)->erase(Old);
}
static void onDelete(ExtraData Map, KeyT Old) {
(*Map)->erase(Old);
}
};
TYPED_TEST(ValueMapTest, SurvivesModificationByConfig) {
ValueMap<TypeParam*, int, ModifyingConfig<TypeParam*> > *MapAddress;
ValueMap<TypeParam*, int, ModifyingConfig<TypeParam*> > VM(&MapAddress);
MapAddress = &VM;
// Now the ModifyingConfig can modify the Map inside a callback.
VM[this->BitcastV.get()] = 7;
this->BitcastV->replaceAllUsesWith(this->AddV.get());
EXPECT_FALSE(VM.count(this->BitcastV.get()));
EXPECT_FALSE(VM.count(this->AddV.get()));
VM[this->AddV.get()] = 7;
this->AddV.reset();
EXPECT_FALSE(VM.count(this->AddV.get()));
}
}
<|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/webui/flags_ui.h"
#include <string>
#include "base/singleton.h"
#include "base/values.h"
#include "chrome/browser/about_flags.h"
#include "chrome/browser/browser_list.h"
#include "chrome/browser/browser_process.h"
#include "chrome/browser/browser_thread.h"
#include "chrome/browser/dom_ui/chrome_url_data_manager.h"
#include "chrome/browser/prefs/pref_service.h"
#include "chrome/browser/profiles/profile.h"
#include "chrome/browser/tab_contents/tab_contents.h"
#include "chrome/common/jstemplate_builder.h"
#include "chrome/common/pref_names.h"
#include "chrome/common/url_constants.h"
#include "grit/browser_resources.h"
#include "grit/chromium_strings.h"
#include "grit/generated_resources.h"
#include "grit/theme_resources.h"
#include "ui/base/l10n/l10n_util.h"
#include "ui/base/resource/resource_bundle.h"
namespace {
///////////////////////////////////////////////////////////////////////////////
//
// FlagsUIHTMLSource
//
///////////////////////////////////////////////////////////////////////////////
class FlagsUIHTMLSource : public ChromeURLDataManager::DataSource {
public:
FlagsUIHTMLSource()
: DataSource(chrome::kChromeUIFlagsHost, MessageLoop::current()) {}
// Called when the network layer has requested a resource underneath
// the path we registered.
virtual void StartDataRequest(const std::string& path,
bool is_off_the_record,
int request_id);
virtual std::string GetMimeType(const std::string&) const {
return "text/html";
}
private:
~FlagsUIHTMLSource() {}
DISALLOW_COPY_AND_ASSIGN(FlagsUIHTMLSource);
};
void FlagsUIHTMLSource::StartDataRequest(const std::string& path,
bool is_off_the_record,
int request_id) {
// Strings used in the JsTemplate file.
DictionaryValue localized_strings;
localized_strings.SetString("flagsLongTitle",
l10n_util::GetStringUTF16(IDS_FLAGS_LONG_TITLE));
localized_strings.SetString("flagsTableTitle",
l10n_util::GetStringUTF16(IDS_FLAGS_TABLE_TITLE));
localized_strings.SetString("flagsNoExperimentsAvailable",
l10n_util::GetStringUTF16(IDS_FLAGS_NO_EXPERIMENTS_AVAILABLE));
localized_strings.SetString("flagsWarningHeader", l10n_util::GetStringUTF16(
IDS_FLAGS_WARNING_HEADER));
localized_strings.SetString("flagsBlurb", l10n_util::GetStringUTF16(
IDS_FLAGS_WARNING_TEXT));
localized_strings.SetString("flagsRestartNotice", l10n_util::GetStringFUTF16(
IDS_FLAGS_RELAUNCH_NOTICE,
l10n_util::GetStringUTF16(IDS_PRODUCT_NAME)));
localized_strings.SetString("flagsRestartButton",
l10n_util::GetStringUTF16(IDS_FLAGS_RELAUNCH_BUTTON));
localized_strings.SetString("disable",
l10n_util::GetStringUTF16(IDS_FLAGS_DISABLE));
localized_strings.SetString("enable",
l10n_util::GetStringUTF16(IDS_FLAGS_ENABLE));
ChromeURLDataManager::DataSource::SetFontAndTextDirection(&localized_strings);
static const base::StringPiece flags_html(
ResourceBundle::GetSharedInstance().GetRawDataResource(IDR_FLAGS_HTML));
std::string full_html(flags_html.data(), flags_html.size());
jstemplate_builder::AppendJsonHtml(&localized_strings, &full_html);
jstemplate_builder::AppendI18nTemplateSourceHtml(&full_html);
jstemplate_builder::AppendI18nTemplateProcessHtml(&full_html);
jstemplate_builder::AppendJsTemplateSourceHtml(&full_html);
scoped_refptr<RefCountedBytes> html_bytes(new RefCountedBytes);
html_bytes->data.resize(full_html.size());
std::copy(full_html.begin(), full_html.end(), html_bytes->data.begin());
SendResponse(request_id, html_bytes);
}
////////////////////////////////////////////////////////////////////////////////
//
// FlagsDOMHandler
//
////////////////////////////////////////////////////////////////////////////////
// The handler for Javascript messages for the about:flags page.
class FlagsDOMHandler : public WebUIMessageHandler {
public:
FlagsDOMHandler() {}
virtual ~FlagsDOMHandler() {}
// WebUIMessageHandler implementation.
virtual void RegisterMessages();
// Callback for the "requestFlagsExperiments" message.
void HandleRequestFlagsExperiments(const ListValue* args);
// Callback for the "enableFlagsExperiment" message.
void HandleEnableFlagsExperimentMessage(const ListValue* args);
// Callback for the "restartBrowser" message. Restores all tabs on restart.
void HandleRestartBrowser(const ListValue* args);
private:
DISALLOW_COPY_AND_ASSIGN(FlagsDOMHandler);
};
void FlagsDOMHandler::RegisterMessages() {
web_ui_->RegisterMessageCallback("requestFlagsExperiments",
NewCallback(this, &FlagsDOMHandler::HandleRequestFlagsExperiments));
web_ui_->RegisterMessageCallback("enableFlagsExperiment",
NewCallback(this, &FlagsDOMHandler::HandleEnableFlagsExperimentMessage));
web_ui_->RegisterMessageCallback("restartBrowser",
NewCallback(this, &FlagsDOMHandler::HandleRestartBrowser));
}
void FlagsDOMHandler::HandleRequestFlagsExperiments(const ListValue* args) {
DictionaryValue results;
results.Set("flagsExperiments",
about_flags::GetFlagsExperimentsData(
g_browser_process->local_state()));
results.SetBoolean("needsRestart",
about_flags::IsRestartNeededToCommitChanges());
web_ui_->CallJavascriptFunction(L"returnFlagsExperiments", results);
}
void FlagsDOMHandler::HandleEnableFlagsExperimentMessage(
const ListValue* args) {
DCHECK_EQ(2u, args->GetSize());
if (args->GetSize() != 2)
return;
std::string experiment_internal_name;
std::string enable_str;
if (!args->GetString(0, &experiment_internal_name) ||
!args->GetString(1, &enable_str))
return;
about_flags::SetExperimentEnabled(
g_browser_process->local_state(),
experiment_internal_name,
enable_str == "true");
}
void FlagsDOMHandler::HandleRestartBrowser(const ListValue* args) {
// Set the flag to restore state after the restart.
PrefService* pref_service = g_browser_process->local_state();
pref_service->SetBoolean(prefs::kRestartLastSessionOnShutdown, true);
BrowserList::CloseAllBrowsersAndExit();
}
} // namespace
///////////////////////////////////////////////////////////////////////////////
//
// FlagsUI
//
///////////////////////////////////////////////////////////////////////////////
FlagsUI::FlagsUI(TabContents* contents) : WebUI(contents) {
AddMessageHandler((new FlagsDOMHandler())->Attach(this));
FlagsUIHTMLSource* html_source = new FlagsUIHTMLSource();
// Set up the about:flags source.
contents->profile()->GetChromeURLDataManager()->AddDataSource(html_source);
}
// static
RefCountedMemory* FlagsUI::GetFaviconResourceBytes() {
return ResourceBundle::GetSharedInstance().
LoadDataResourceBytes(IDR_FLAGS);
}
// static
void FlagsUI::RegisterPrefs(PrefService* prefs) {
prefs->RegisterListPref(prefs::kEnabledLabsExperiments);
}
<commit_msg>[cros] Perform a clean sign out when restart requested on about:flags.<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/webui/flags_ui.h"
#include <string>
#include "base/singleton.h"
#include "base/values.h"
#include "chrome/browser/about_flags.h"
#include "chrome/browser/browser_list.h"
#include "chrome/browser/browser_process.h"
#include "chrome/browser/browser_thread.h"
#include "chrome/browser/dom_ui/chrome_url_data_manager.h"
#include "chrome/browser/prefs/pref_service.h"
#include "chrome/browser/profiles/profile.h"
#include "chrome/browser/tab_contents/tab_contents.h"
#include "chrome/common/jstemplate_builder.h"
#include "chrome/common/pref_names.h"
#include "chrome/common/url_constants.h"
#include "grit/browser_resources.h"
#include "grit/chromium_strings.h"
#include "grit/generated_resources.h"
#include "grit/theme_resources.h"
#include "ui/base/l10n/l10n_util.h"
#include "ui/base/resource/resource_bundle.h"
namespace {
///////////////////////////////////////////////////////////////////////////////
//
// FlagsUIHTMLSource
//
///////////////////////////////////////////////////////////////////////////////
class FlagsUIHTMLSource : public ChromeURLDataManager::DataSource {
public:
FlagsUIHTMLSource()
: DataSource(chrome::kChromeUIFlagsHost, MessageLoop::current()) {}
// Called when the network layer has requested a resource underneath
// the path we registered.
virtual void StartDataRequest(const std::string& path,
bool is_off_the_record,
int request_id);
virtual std::string GetMimeType(const std::string&) const {
return "text/html";
}
private:
~FlagsUIHTMLSource() {}
DISALLOW_COPY_AND_ASSIGN(FlagsUIHTMLSource);
};
void FlagsUIHTMLSource::StartDataRequest(const std::string& path,
bool is_off_the_record,
int request_id) {
// Strings used in the JsTemplate file.
DictionaryValue localized_strings;
localized_strings.SetString("flagsLongTitle",
l10n_util::GetStringUTF16(IDS_FLAGS_LONG_TITLE));
localized_strings.SetString("flagsTableTitle",
l10n_util::GetStringUTF16(IDS_FLAGS_TABLE_TITLE));
localized_strings.SetString("flagsNoExperimentsAvailable",
l10n_util::GetStringUTF16(IDS_FLAGS_NO_EXPERIMENTS_AVAILABLE));
localized_strings.SetString("flagsWarningHeader", l10n_util::GetStringUTF16(
IDS_FLAGS_WARNING_HEADER));
localized_strings.SetString("flagsBlurb", l10n_util::GetStringUTF16(
IDS_FLAGS_WARNING_TEXT));
localized_strings.SetString("flagsRestartNotice", l10n_util::GetStringFUTF16(
IDS_FLAGS_RELAUNCH_NOTICE,
l10n_util::GetStringUTF16(IDS_PRODUCT_NAME)));
localized_strings.SetString("flagsRestartButton",
l10n_util::GetStringUTF16(IDS_FLAGS_RELAUNCH_BUTTON));
localized_strings.SetString("disable",
l10n_util::GetStringUTF16(IDS_FLAGS_DISABLE));
localized_strings.SetString("enable",
l10n_util::GetStringUTF16(IDS_FLAGS_ENABLE));
ChromeURLDataManager::DataSource::SetFontAndTextDirection(&localized_strings);
static const base::StringPiece flags_html(
ResourceBundle::GetSharedInstance().GetRawDataResource(IDR_FLAGS_HTML));
std::string full_html(flags_html.data(), flags_html.size());
jstemplate_builder::AppendJsonHtml(&localized_strings, &full_html);
jstemplate_builder::AppendI18nTemplateSourceHtml(&full_html);
jstemplate_builder::AppendI18nTemplateProcessHtml(&full_html);
jstemplate_builder::AppendJsTemplateSourceHtml(&full_html);
scoped_refptr<RefCountedBytes> html_bytes(new RefCountedBytes);
html_bytes->data.resize(full_html.size());
std::copy(full_html.begin(), full_html.end(), html_bytes->data.begin());
SendResponse(request_id, html_bytes);
}
////////////////////////////////////////////////////////////////////////////////
//
// FlagsDOMHandler
//
////////////////////////////////////////////////////////////////////////////////
// The handler for Javascript messages for the about:flags page.
class FlagsDOMHandler : public WebUIMessageHandler {
public:
FlagsDOMHandler() {}
virtual ~FlagsDOMHandler() {}
// WebUIMessageHandler implementation.
virtual void RegisterMessages();
// Callback for the "requestFlagsExperiments" message.
void HandleRequestFlagsExperiments(const ListValue* args);
// Callback for the "enableFlagsExperiment" message.
void HandleEnableFlagsExperimentMessage(const ListValue* args);
// Callback for the "restartBrowser" message. Restores all tabs on restart.
void HandleRestartBrowser(const ListValue* args);
private:
DISALLOW_COPY_AND_ASSIGN(FlagsDOMHandler);
};
void FlagsDOMHandler::RegisterMessages() {
web_ui_->RegisterMessageCallback("requestFlagsExperiments",
NewCallback(this, &FlagsDOMHandler::HandleRequestFlagsExperiments));
web_ui_->RegisterMessageCallback("enableFlagsExperiment",
NewCallback(this, &FlagsDOMHandler::HandleEnableFlagsExperimentMessage));
web_ui_->RegisterMessageCallback("restartBrowser",
NewCallback(this, &FlagsDOMHandler::HandleRestartBrowser));
}
void FlagsDOMHandler::HandleRequestFlagsExperiments(const ListValue* args) {
DictionaryValue results;
results.Set("flagsExperiments",
about_flags::GetFlagsExperimentsData(
g_browser_process->local_state()));
results.SetBoolean("needsRestart",
about_flags::IsRestartNeededToCommitChanges());
web_ui_->CallJavascriptFunction(L"returnFlagsExperiments", results);
}
void FlagsDOMHandler::HandleEnableFlagsExperimentMessage(
const ListValue* args) {
DCHECK_EQ(2u, args->GetSize());
if (args->GetSize() != 2)
return;
std::string experiment_internal_name;
std::string enable_str;
if (!args->GetString(0, &experiment_internal_name) ||
!args->GetString(1, &enable_str))
return;
about_flags::SetExperimentEnabled(
g_browser_process->local_state(),
experiment_internal_name,
enable_str == "true");
}
void FlagsDOMHandler::HandleRestartBrowser(const ListValue* args) {
#if !defined(OS_CHROMEOS)
// Set the flag to restore state after the restart.
PrefService* pref_service = g_browser_process->local_state();
pref_service->SetBoolean(prefs::kRestartLastSessionOnShutdown, true);
BrowserList::CloseAllBrowsersAndExit();
#else
// For CrOS instead of browser restart (which is not supported) perform a full
// sign out. Session will be only restored is user has that setting set.
// Same session restore behavior happens in case of full restart after update.
BrowserList::GetLastActive()->Exit();
#endif
}
} // namespace
///////////////////////////////////////////////////////////////////////////////
//
// FlagsUI
//
///////////////////////////////////////////////////////////////////////////////
FlagsUI::FlagsUI(TabContents* contents) : WebUI(contents) {
AddMessageHandler((new FlagsDOMHandler())->Attach(this));
FlagsUIHTMLSource* html_source = new FlagsUIHTMLSource();
// Set up the about:flags source.
contents->profile()->GetChromeURLDataManager()->AddDataSource(html_source);
}
// static
RefCountedMemory* FlagsUI::GetFaviconResourceBytes() {
return ResourceBundle::GetSharedInstance().
LoadDataResourceBytes(IDR_FLAGS);
}
// static
void FlagsUI::RegisterPrefs(PrefService* prefs) {
prefs->RegisterListPref(prefs::kEnabledLabsExperiments);
}
<|endoftext|> |
<commit_before>// Copyright (c) 2006-2008 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.
// This file provides the embedder's side of random webkit glue functions.
#include "build/build_config.h"
#if defined(OS_WIN)
#include <windows.h>
#include <wininet.h>
#endif
#include "base/clipboard.h"
#include "base/scoped_clipboard_writer.h"
#include "base/string_util.h"
#include "chrome/common/chrome_switches.h"
#include "chrome/common/render_messages.h"
#include "chrome/common/resource_bundle.h"
#include "chrome/plugin/npobject_util.h"
#include "chrome/renderer/net/render_dns_master.h"
#include "chrome/renderer/render_process.h"
#include "chrome/renderer/render_thread.h"
#include "googleurl/src/url_util.h"
#include "webkit/glue/scoped_clipboard_writer_glue.h"
#include "webkit/glue/webframe.h"
#include "webkit/glue/webkit_glue.h"
#include "WebKit.h"
#include "WebKitClient.h"
#include "WebString.h"
#include <vector>
#include "SkBitmap.h"
#if defined(OS_WIN)
#include <strsafe.h> // note: per msdn docs, this must *follow* other includes
#endif
template <typename T, size_t stack_capacity>
class ResizableStackArray {
public:
ResizableStackArray()
: cur_buffer_(stack_buffer_), cur_capacity_(stack_capacity) {
}
~ResizableStackArray() {
FreeHeap();
}
T* get() const {
return cur_buffer_;
}
T& operator[](size_t i) {
return cur_buffer_[i];
}
size_t capacity() const {
return cur_capacity_;
}
void Resize(size_t new_size) {
if (new_size < cur_capacity_)
return; // already big enough
FreeHeap();
cur_capacity_ = new_size;
cur_buffer_ = new T[new_size];
}
private:
// Resets the heap buffer, if any
void FreeHeap() {
if (cur_buffer_ != stack_buffer_) {
delete[] cur_buffer_;
cur_buffer_ = stack_buffer_;
cur_capacity_ = stack_capacity;
}
}
T stack_buffer_[stack_capacity];
T* cur_buffer_;
size_t cur_capacity_;
};
#if defined(OS_WIN)
// This definition of WriteBitmapFromPixels uses shared memory to communicate
// across processes.
void ScopedClipboardWriterGlue::WriteBitmapFromPixels(const void* pixels,
const gfx::Size& size) {
// Do not try to write a bitmap more than once
if (shared_buf_)
return;
size_t buf_size = 4 * size.width() * size.height();
// Allocate a shared memory buffer to hold the bitmap bits
shared_buf_ = new base::SharedMemory;
shared_buf_->Create(L"", false /* read write */, true /* open existing */,
buf_size);
if (!shared_buf_ || !shared_buf_->Map(buf_size)) {
NOTREACHED();
return;
}
// Copy the bits into shared memory
memcpy(shared_buf_->memory(), pixels, buf_size);
shared_buf_->Unmap();
Clipboard::ObjectMapParam param1, param2;
base::SharedMemoryHandle smh = shared_buf_->handle();
const char* shared_handle = reinterpret_cast<const char*>(&smh);
for (size_t i = 0; i < sizeof base::SharedMemoryHandle; i++)
param1.push_back(shared_handle[i]);
const char* size_data = reinterpret_cast<const char*>(&size);
for (size_t i = 0; i < sizeof gfx::Size; i++)
param2.push_back(size_data[i]);
Clipboard::ObjectMapParams params;
params.push_back(param1);
params.push_back(param2);
objects_[Clipboard::CBF_SMBITMAP] = params;
}
#endif
// Define a destructor that makes IPCs to flush the contents to the
// system clipboard.
ScopedClipboardWriterGlue::~ScopedClipboardWriterGlue() {
if (objects_.empty())
return;
#if defined(OS_WIN)
if (shared_buf_) {
RenderThread::current()->Send(
new ViewHostMsg_ClipboardWriteObjectsSync(objects_));
delete shared_buf_;
return;
}
#endif
RenderThread::current()->Send(
new ViewHostMsg_ClipboardWriteObjectsAsync(objects_));
}
namespace webkit_glue {
// Global variable set during RenderProcess::GlobalInit if video was enabled
// and our media libraries were successfully loaded.
static bool g_media_player_available = false;
void SetMediaPlayerAvailable(bool value) {
g_media_player_available = value;
}
bool IsMediaPlayerAvailable() {
return g_media_player_available;
}
void PrecacheUrl(const wchar_t* url, int url_length) {
// TBD: jar: Need implementation that loads the targetted URL into our cache.
// For now, at least prefetch DNS lookup
std::string url_string;
WideToUTF8(url, url_length, &url_string);
const std::string host = GURL(url_string).host();
if (!host.empty())
DnsPrefetchCString(host.data(), host.length());
}
void AppendToLog(const char* file, int line, const char* msg) {
logging::LogMessage(file, line).stream() << msg;
}
std::string GetDataResource(int resource_id) {
return ResourceBundle::GetSharedInstance().GetDataResource(resource_id);
}
#if defined(OS_WIN)
HCURSOR LoadCursor(int cursor_id) {
return ResourceBundle::GetSharedInstance().LoadCursor(cursor_id);
}
#endif
// Clipboard glue
Clipboard* ClipboardGetClipboard(){
return NULL;
}
bool ClipboardIsFormatAvailable(const Clipboard::FormatType& format) {
bool result;
RenderThread::current()->Send(
new ViewHostMsg_ClipboardIsFormatAvailable(format, &result));
return result;
}
void ClipboardReadText(string16* result) {
RenderThread::current()->Send(new ViewHostMsg_ClipboardReadText(result));
}
void ClipboardReadAsciiText(std::string* result) {
RenderThread::current()->Send(new ViewHostMsg_ClipboardReadAsciiText(result));
}
void ClipboardReadHTML(string16* markup, GURL* url) {
RenderThread::current()->Send(new ViewHostMsg_ClipboardReadHTML(markup, url));
}
GURL GetInspectorURL() {
return GURL("chrome-ui://inspector/inspector.html");
}
std::string GetUIResourceProtocol() {
return "chrome-ui";
}
bool GetPlugins(bool refresh, std::vector<WebPluginInfo>* plugins) {
return RenderThread::current()->Send(
new ViewHostMsg_GetPlugins(refresh, plugins));
}
webkit_glue::ScreenInfo GetScreenInfo(gfx::NativeViewId window) {
webkit_glue::ScreenInfo results;
RenderThread::current()->Send(
new ViewHostMsg_GetScreenInfo(window, &results));
return results;
}
// static factory function
ResourceLoaderBridge* ResourceLoaderBridge::Create(
const std::string& method,
const GURL& url,
const GURL& policy_url,
const GURL& referrer,
const std::string& frame_origin,
const std::string& main_frame_origin,
const std::string& headers,
int load_flags,
int origin_pid,
ResourceType::Type resource_type,
int routing_id) {
ResourceDispatcher* dispatch = RenderThread::current()->resource_dispatcher();
return dispatch->CreateBridge(method, url, policy_url, referrer,
frame_origin, main_frame_origin, headers,
load_flags, origin_pid, resource_type,
0, routing_id);
}
void NotifyCacheStats() {
// Update the browser about our cache
// NOTE: Since this can be called from the plugin process, we might not have
// a RenderThread. Do nothing in that case.
if (!IsPluginProcess())
RenderThread::current()->InformHostOfCacheStatsLater();
}
} // namespace webkit_glue
<commit_msg>Check return value of SharedMemory::Create<commit_after>// Copyright (c) 2006-2008 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.
// This file provides the embedder's side of random webkit glue functions.
#include "build/build_config.h"
#if defined(OS_WIN)
#include <windows.h>
#include <wininet.h>
#endif
#include "base/clipboard.h"
#include "base/scoped_clipboard_writer.h"
#include "base/string_util.h"
#include "chrome/common/chrome_switches.h"
#include "chrome/common/render_messages.h"
#include "chrome/common/resource_bundle.h"
#include "chrome/plugin/npobject_util.h"
#include "chrome/renderer/net/render_dns_master.h"
#include "chrome/renderer/render_process.h"
#include "chrome/renderer/render_thread.h"
#include "googleurl/src/url_util.h"
#include "webkit/glue/scoped_clipboard_writer_glue.h"
#include "webkit/glue/webframe.h"
#include "webkit/glue/webkit_glue.h"
#include "WebKit.h"
#include "WebKitClient.h"
#include "WebString.h"
#include <vector>
#include "SkBitmap.h"
#if defined(OS_WIN)
#include <strsafe.h> // note: per msdn docs, this must *follow* other includes
#endif
template <typename T, size_t stack_capacity>
class ResizableStackArray {
public:
ResizableStackArray()
: cur_buffer_(stack_buffer_), cur_capacity_(stack_capacity) {
}
~ResizableStackArray() {
FreeHeap();
}
T* get() const {
return cur_buffer_;
}
T& operator[](size_t i) {
return cur_buffer_[i];
}
size_t capacity() const {
return cur_capacity_;
}
void Resize(size_t new_size) {
if (new_size < cur_capacity_)
return; // already big enough
FreeHeap();
cur_capacity_ = new_size;
cur_buffer_ = new T[new_size];
}
private:
// Resets the heap buffer, if any
void FreeHeap() {
if (cur_buffer_ != stack_buffer_) {
delete[] cur_buffer_;
cur_buffer_ = stack_buffer_;
cur_capacity_ = stack_capacity;
}
}
T stack_buffer_[stack_capacity];
T* cur_buffer_;
size_t cur_capacity_;
};
#if defined(OS_WIN)
// This definition of WriteBitmapFromPixels uses shared memory to communicate
// across processes.
void ScopedClipboardWriterGlue::WriteBitmapFromPixels(const void* pixels,
const gfx::Size& size) {
// Do not try to write a bitmap more than once
if (shared_buf_)
return;
size_t buf_size = 4 * size.width() * size.height();
// Allocate a shared memory buffer to hold the bitmap bits
shared_buf_ = new base::SharedMemory;
const bool created = shared_buf_ && shared_buf_->Create(
L"", false /* read write */, true /* open existing */, buf_size);
if (!shared_buf_ || !created || !shared_buf_->Map(buf_size)) {
NOTREACHED();
return;
}
// Copy the bits into shared memory
memcpy(shared_buf_->memory(), pixels, buf_size);
shared_buf_->Unmap();
Clipboard::ObjectMapParam param1, param2;
base::SharedMemoryHandle smh = shared_buf_->handle();
const char* shared_handle = reinterpret_cast<const char*>(&smh);
for (size_t i = 0; i < sizeof base::SharedMemoryHandle; i++)
param1.push_back(shared_handle[i]);
const char* size_data = reinterpret_cast<const char*>(&size);
for (size_t i = 0; i < sizeof gfx::Size; i++)
param2.push_back(size_data[i]);
Clipboard::ObjectMapParams params;
params.push_back(param1);
params.push_back(param2);
objects_[Clipboard::CBF_SMBITMAP] = params;
}
#endif
// Define a destructor that makes IPCs to flush the contents to the
// system clipboard.
ScopedClipboardWriterGlue::~ScopedClipboardWriterGlue() {
if (objects_.empty())
return;
#if defined(OS_WIN)
if (shared_buf_) {
RenderThread::current()->Send(
new ViewHostMsg_ClipboardWriteObjectsSync(objects_));
delete shared_buf_;
return;
}
#endif
RenderThread::current()->Send(
new ViewHostMsg_ClipboardWriteObjectsAsync(objects_));
}
namespace webkit_glue {
// Global variable set during RenderProcess::GlobalInit if video was enabled
// and our media libraries were successfully loaded.
static bool g_media_player_available = false;
void SetMediaPlayerAvailable(bool value) {
g_media_player_available = value;
}
bool IsMediaPlayerAvailable() {
return g_media_player_available;
}
void PrecacheUrl(const wchar_t* url, int url_length) {
// TBD: jar: Need implementation that loads the targetted URL into our cache.
// For now, at least prefetch DNS lookup
std::string url_string;
WideToUTF8(url, url_length, &url_string);
const std::string host = GURL(url_string).host();
if (!host.empty())
DnsPrefetchCString(host.data(), host.length());
}
void AppendToLog(const char* file, int line, const char* msg) {
logging::LogMessage(file, line).stream() << msg;
}
std::string GetDataResource(int resource_id) {
return ResourceBundle::GetSharedInstance().GetDataResource(resource_id);
}
#if defined(OS_WIN)
HCURSOR LoadCursor(int cursor_id) {
return ResourceBundle::GetSharedInstance().LoadCursor(cursor_id);
}
#endif
// Clipboard glue
Clipboard* ClipboardGetClipboard(){
return NULL;
}
bool ClipboardIsFormatAvailable(const Clipboard::FormatType& format) {
bool result;
RenderThread::current()->Send(
new ViewHostMsg_ClipboardIsFormatAvailable(format, &result));
return result;
}
void ClipboardReadText(string16* result) {
RenderThread::current()->Send(new ViewHostMsg_ClipboardReadText(result));
}
void ClipboardReadAsciiText(std::string* result) {
RenderThread::current()->Send(new ViewHostMsg_ClipboardReadAsciiText(result));
}
void ClipboardReadHTML(string16* markup, GURL* url) {
RenderThread::current()->Send(new ViewHostMsg_ClipboardReadHTML(markup, url));
}
GURL GetInspectorURL() {
return GURL("chrome-ui://inspector/inspector.html");
}
std::string GetUIResourceProtocol() {
return "chrome-ui";
}
bool GetPlugins(bool refresh, std::vector<WebPluginInfo>* plugins) {
return RenderThread::current()->Send(
new ViewHostMsg_GetPlugins(refresh, plugins));
}
webkit_glue::ScreenInfo GetScreenInfo(gfx::NativeViewId window) {
webkit_glue::ScreenInfo results;
RenderThread::current()->Send(
new ViewHostMsg_GetScreenInfo(window, &results));
return results;
}
// static factory function
ResourceLoaderBridge* ResourceLoaderBridge::Create(
const std::string& method,
const GURL& url,
const GURL& policy_url,
const GURL& referrer,
const std::string& frame_origin,
const std::string& main_frame_origin,
const std::string& headers,
int load_flags,
int origin_pid,
ResourceType::Type resource_type,
int routing_id) {
ResourceDispatcher* dispatch = RenderThread::current()->resource_dispatcher();
return dispatch->CreateBridge(method, url, policy_url, referrer,
frame_origin, main_frame_origin, headers,
load_flags, origin_pid, resource_type,
0, routing_id);
}
void NotifyCacheStats() {
// Update the browser about our cache
// NOTE: Since this can be called from the plugin process, we might not have
// a RenderThread. Do nothing in that case.
if (!IsPluginProcess())
RenderThread::current()->InformHostOfCacheStatsLater();
}
} // namespace webkit_glue
<|endoftext|> |
<commit_before>// Copyright (c) 2010 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/test/nacl/nacl_ui_test.h"
// TODO(jvoung) see what includes we really need.
#include "base/file_util.h"
#include "base/path_service.h"
#include "chrome/common/chrome_paths.h"
namespace {
// NOTE: The base URL of each HTML file is specified in nacl_test.
const FilePath::CharType kSrpcHwHtmlFileName[] =
FILE_PATH_LITERAL("srpc_hw.html");
const FilePath::CharType kSrpcBasicHtmlFileName[] =
FILE_PATH_LITERAL("srpc_basic.html");
const FilePath::CharType kSrpcSockAddrHtmlFileName[] =
FILE_PATH_LITERAL("srpc_sockaddr.html");
const FilePath::CharType kSrpcShmHtmlFileName[] =
FILE_PATH_LITERAL("srpc_shm.html");
const FilePath::CharType kSrpcPluginHtmlFileName[] =
FILE_PATH_LITERAL("srpc_plugin.html");
const FilePath::CharType kSrpcNrdXferHtmlFileName[] =
FILE_PATH_LITERAL("srpc_nrd_xfer.html");
const FilePath::CharType kServerHtmlFileName[] =
FILE_PATH_LITERAL("server_test.html");
const FilePath::CharType kNpapiHwHtmlFileName[] =
FILE_PATH_LITERAL("npapi_hw.html");
} // namespace
NaClUITest::NaClUITest() {
}
NaClUITest::~NaClUITest() {
}
TEST_F(NaClUITest, ServerTest) {
FilePath test_file(kServerHtmlFileName);
RunTest(test_file, action_max_timeout_ms());
}
TEST_F(NaClUITest, SrpcHelloWorld) {
FilePath test_file(kSrpcHwHtmlFileName);
RunTest(test_file, action_max_timeout_ms());
}
TEST_F(NaClUITest, DISABLED_SrpcBasicTest) {
FilePath test_file(kSrpcBasicHtmlFileName);
RunTest(test_file, action_max_timeout_ms());
}
TEST_F(NaClUITest, SrpcSockAddrTest) {
FilePath test_file(kSrpcSockAddrHtmlFileName);
RunTest(test_file, action_max_timeout_ms());
}
TEST_F(NaClUITest, SrpcShmTest) {
FilePath test_file(kSrpcShmHtmlFileName);
RunTest(test_file, action_max_timeout_ms());
}
TEST_F(NaClUITest, SrpcPluginTest) {
FilePath test_file(kSrpcPluginHtmlFileName);
RunTest(test_file, action_max_timeout_ms());
}
TEST_F(NaClUITest, SrpcNrdXferTest) {
FilePath test_file(kSrpcNrdXferHtmlFileName);
RunTest(test_file, action_max_timeout_ms());
}
TEST_F(NaClUITest, NpapiHwTest) {
FilePath test_file(kNpapiHwHtmlFileName);
RunTest(test_file, action_max_timeout_ms());
}
TEST_F(NaClUITest, MultiarchTest) {
FilePath test_file(kSrpcHwHtmlFileName);
RunMultiarchTest(test_file, action_max_timeout_ms());
}
<commit_msg>Add bug ID to disabled NaClUITest.<commit_after>// Copyright (c) 2010 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/test/nacl/nacl_ui_test.h"
// TODO(jvoung) see what includes we really need.
#include "base/file_util.h"
#include "base/path_service.h"
#include "chrome/common/chrome_paths.h"
namespace {
// NOTE: The base URL of each HTML file is specified in nacl_test.
const FilePath::CharType kSrpcHwHtmlFileName[] =
FILE_PATH_LITERAL("srpc_hw.html");
const FilePath::CharType kSrpcBasicHtmlFileName[] =
FILE_PATH_LITERAL("srpc_basic.html");
const FilePath::CharType kSrpcSockAddrHtmlFileName[] =
FILE_PATH_LITERAL("srpc_sockaddr.html");
const FilePath::CharType kSrpcShmHtmlFileName[] =
FILE_PATH_LITERAL("srpc_shm.html");
const FilePath::CharType kSrpcPluginHtmlFileName[] =
FILE_PATH_LITERAL("srpc_plugin.html");
const FilePath::CharType kSrpcNrdXferHtmlFileName[] =
FILE_PATH_LITERAL("srpc_nrd_xfer.html");
const FilePath::CharType kServerHtmlFileName[] =
FILE_PATH_LITERAL("server_test.html");
const FilePath::CharType kNpapiHwHtmlFileName[] =
FILE_PATH_LITERAL("npapi_hw.html");
} // namespace
NaClUITest::NaClUITest() {
}
NaClUITest::~NaClUITest() {
}
TEST_F(NaClUITest, ServerTest) {
FilePath test_file(kServerHtmlFileName);
RunTest(test_file, action_max_timeout_ms());
}
TEST_F(NaClUITest, SrpcHelloWorld) {
FilePath test_file(kSrpcHwHtmlFileName);
RunTest(test_file, action_max_timeout_ms());
}
// http://crbug.com/64973
TEST_F(NaClUITest, DISABLED_SrpcBasicTest) {
FilePath test_file(kSrpcBasicHtmlFileName);
RunTest(test_file, action_max_timeout_ms());
}
TEST_F(NaClUITest, SrpcSockAddrTest) {
FilePath test_file(kSrpcSockAddrHtmlFileName);
RunTest(test_file, action_max_timeout_ms());
}
TEST_F(NaClUITest, SrpcShmTest) {
FilePath test_file(kSrpcShmHtmlFileName);
RunTest(test_file, action_max_timeout_ms());
}
TEST_F(NaClUITest, SrpcPluginTest) {
FilePath test_file(kSrpcPluginHtmlFileName);
RunTest(test_file, action_max_timeout_ms());
}
TEST_F(NaClUITest, SrpcNrdXferTest) {
FilePath test_file(kSrpcNrdXferHtmlFileName);
RunTest(test_file, action_max_timeout_ms());
}
TEST_F(NaClUITest, NpapiHwTest) {
FilePath test_file(kNpapiHwHtmlFileName);
RunTest(test_file, action_max_timeout_ms());
}
TEST_F(NaClUITest, MultiarchTest) {
FilePath test_file(kSrpcHwHtmlFileName);
RunMultiarchTest(test_file, action_max_timeout_ms());
}
<|endoftext|> |
<commit_before>// Copyright (c) 2010 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 <windows.h>
#include <objbase.h>
#include <urlmon.h>
#include "base/logging.h"
#include "base/string_number_conversions.h"
#include "base/string_util.h"
#include "base/stringprintf.h"
#include "base/utf_string_conversions.h"
#include "chrome_frame/test/test_server.h"
#include "net/base/winsock_init.h"
#include "net/http/http_util.h"
namespace test_server {
const char kDefaultHeaderTemplate[] =
"HTTP/1.1 %hs\r\n"
"Connection: close\r\n"
"Content-Type: %hs\r\n"
"Content-Length: %i\r\n\r\n";
const char kStatusOk[] = "200 OK";
const char kStatusNotFound[] = "404 Not Found";
const char kDefaultContentType[] = "text/html; charset=UTF-8";
void Request::ParseHeaders(const std::string& headers) {
DCHECK(method_.length() == 0);
size_t pos = headers.find("\r\n");
DCHECK(pos != std::string::npos);
if (pos != std::string::npos) {
headers_ = headers.substr(pos + 2);
StringTokenizer tokenizer(headers.begin(), headers.begin() + pos, " ");
std::string* parse[] = { &method_, &path_, &version_ };
int field = 0;
while (tokenizer.GetNext() && field < arraysize(parse)) {
parse[field++]->assign(tokenizer.token_begin(),
tokenizer.token_end());
}
}
// Check for content-length in case we're being sent some data.
net::HttpUtil::HeadersIterator it(headers_.begin(), headers_.end(),
"\r\n");
while (it.GetNext()) {
if (LowerCaseEqualsASCII(it.name(), "content-length")) {
int int_content_length;
base::StringToInt(it.values_begin(),
it.values_end(),
&int_content_length);
content_length_ = int_content_length;
break;
}
}
}
void Request::OnDataReceived(const std::string& data) {
content_ += data;
if (method_.length() == 0) {
size_t index = content_.find("\r\n\r\n");
if (index != std::string::npos) {
// Parse the headers before returning and chop them of the
// data buffer we've already received.
std::string headers(content_.substr(0, index + 2));
ParseHeaders(headers);
content_.erase(0, index + 4);
}
}
}
bool FileResponse::GetContentType(std::string* content_type) const {
size_t length = ContentLength();
char buffer[4096];
void* data = NULL;
if (length) {
// Create a copy of the first few bytes of the file.
// If we try and use the mapped file directly, FindMimeFromData will crash
// 'cause it cheats and temporarily tries to write to the buffer!
length = std::min(arraysize(buffer), length);
memcpy(buffer, file_->data(), length);
data = buffer;
}
LPOLESTR mime_type = NULL;
FindMimeFromData(NULL, file_path_.value().c_str(), data, length, NULL,
FMFD_DEFAULT, &mime_type, 0);
if (mime_type) {
*content_type = WideToASCII(mime_type);
::CoTaskMemFree(mime_type);
}
return content_type->length() > 0;
}
void FileResponse::WriteContents(ListenSocket* socket) const {
DCHECK(file_.get());
if (file_.get()) {
socket->Send(reinterpret_cast<const char*>(file_->data()),
file_->length(), false);
}
}
size_t FileResponse::ContentLength() const {
if (file_.get() == NULL) {
file_.reset(new file_util::MemoryMappedFile());
if (!file_->Initialize(file_path_)) {
NOTREACHED();
file_.reset();
}
}
return file_.get() ? file_->length() : 0;
}
bool RedirectResponse::GetCustomHeaders(std::string* headers) const {
*headers = base::StringPrintf("HTTP/1.1 302 Found\r\n"
"Connection: close\r\n"
"Content-Length: 0\r\n"
"Content-Type: text/html\r\n"
"Location: %hs\r\n\r\n",
redirect_url_.c_str());
return true;
}
SimpleWebServer::SimpleWebServer(int port) {
CHECK(MessageLoop::current()) << "SimpleWebServer requires a message loop";
net::EnsureWinsockInit();
AddResponse(&quit_);
server_ = ListenSocket::Listen("127.0.0.1", port, this);
DCHECK(server_.get() != NULL);
}
SimpleWebServer::~SimpleWebServer() {
ConnectionList::const_iterator it;
for (it = connections_.begin(); it != connections_.end(); ++it)
delete (*it);
connections_.clear();
}
void SimpleWebServer::AddResponse(Response* response) {
responses_.push_back(response);
}
void SimpleWebServer::DeleteAllResponses() {
std::list<Response*>::const_iterator it;
for (it = responses_.begin(); it != responses_.end(); ++it) {
if ((*it) != &quit_)
delete (*it);
}
connections_.clear();
}
Response* SimpleWebServer::FindResponse(const Request& request) const {
std::list<Response*>::const_iterator it;
for (it = responses_.begin(); it != responses_.end(); it++) {
Response* response = (*it);
if (response->Matches(request)) {
return response;
}
}
return NULL;
}
Connection* SimpleWebServer::FindConnection(const ListenSocket* socket) const {
ConnectionList::const_iterator it;
for (it = connections_.begin(); it != connections_.end(); it++) {
if ((*it)->IsSame(socket)) {
return (*it);
}
}
return NULL;
}
void SimpleWebServer::DidAccept(ListenSocket* server,
ListenSocket* connection) {
connections_.push_back(new Connection(connection));
}
void SimpleWebServer::DidRead(ListenSocket* connection,
const char* data,
int len) {
Connection* c = FindConnection(connection);
DCHECK(c);
Request& r = c->request();
std::string str(data, len);
r.OnDataReceived(str);
if (r.AllContentReceived()) {
const Request& request = c->request();
Response* response = FindResponse(request);
if (response) {
std::string headers;
if (!response->GetCustomHeaders(&headers)) {
std::string content_type;
if (!response->GetContentType(&content_type))
content_type = kDefaultContentType;
headers = base::StringPrintf(kDefaultHeaderTemplate, kStatusOk,
content_type.c_str(),
response->ContentLength());
}
connection->Send(headers, false);
response->WriteContents(connection);
response->IncrementAccessCounter();
} else {
std::string payload = "sorry, I can't find " + request.path();
std::string headers(base::StringPrintf(kDefaultHeaderTemplate,
kStatusNotFound,
kDefaultContentType,
payload.length()));
connection->Send(headers, false);
connection->Send(payload, false);
}
}
}
void SimpleWebServer::DidClose(ListenSocket* sock) {
// To keep the historical list of connections reasonably tidy, we delete
// 404's when the connection ends.
Connection* c = FindConnection(sock);
DCHECK(c);
if (!FindResponse(c->request())) {
// extremely inefficient, but in one line and not that common... :)
connections_.erase(std::find(connections_.begin(), connections_.end(), c));
delete c;
}
}
HTTPTestServer::HTTPTestServer(int port, const std::wstring& address,
FilePath root_dir)
: port_(port), address_(address), root_dir_(root_dir) {
net::EnsureWinsockInit();
server_ = ListenSocket::Listen(WideToUTF8(address), port, this);
}
HTTPTestServer::~HTTPTestServer() {
}
std::list<scoped_refptr<ConfigurableConnection>>::iterator
HTTPTestServer::FindConnection(const ListenSocket* socket) {
ConnectionList::iterator it;
for (it = connection_list_.begin(); it != connection_list_.end(); ++it) {
if ((*it)->socket_ == socket) {
break;
}
}
return it;
}
scoped_refptr<ConfigurableConnection> HTTPTestServer::ConnectionFromSocket(
const ListenSocket* socket) {
ConnectionList::iterator it = FindConnection(socket);
if (it != connection_list_.end())
return *it;
return NULL;
}
void HTTPTestServer::DidAccept(ListenSocket* server, ListenSocket* socket) {
connection_list_.push_back(new ConfigurableConnection(socket));
}
void HTTPTestServer::DidRead(ListenSocket* socket,
const char* data,
int len) {
scoped_refptr<ConfigurableConnection> connection =
ConnectionFromSocket(socket);
if (connection) {
std::string str(data, len);
connection->r_.OnDataReceived(str);
if (connection->r_.AllContentReceived()) {
std::wstring path = UTF8ToWide(connection->r_.path());
if (LowerCaseEqualsASCII(connection->r_.method(), "post"))
this->Post(connection, path, connection->r_);
else
this->Get(connection, path, connection->r_);
}
}
}
void HTTPTestServer::DidClose(ListenSocket* socket) {
ConnectionList::iterator it = FindConnection(socket);
DCHECK(it != connection_list_.end());
connection_list_.erase(it);
}
std::wstring HTTPTestServer::Resolve(const std::wstring& path) {
// Remove the first '/' if needed.
std::wstring stripped_path = path;
if (path.size() && path[0] == L'/')
stripped_path = path.substr(1);
if (port_ == 80) {
if (stripped_path.empty()) {
return base::StringPrintf(L"http://%ls", address_.c_str());
} else {
return base::StringPrintf(L"http://%ls/%ls", address_.c_str(),
stripped_path.c_str());
}
} else {
if (stripped_path.empty()) {
return base::StringPrintf(L"http://%ls:%d", address_.c_str(), port_);
} else {
return base::StringPrintf(L"http://%ls:%d/%ls", address_.c_str(), port_,
stripped_path.c_str());
}
}
}
void ConfigurableConnection::SendChunk() {
int size = (int)data_.size();
const char* chunk_ptr = data_.c_str() + cur_pos_;
int bytes_to_send = std::min(options_.chunk_size_, size - cur_pos_);
socket_->Send(chunk_ptr, bytes_to_send);
DVLOG(1) << "Sent(" << cur_pos_ << "," << bytes_to_send << "): "
<< base::StringPiece(chunk_ptr, bytes_to_send);
cur_pos_ += bytes_to_send;
if (cur_pos_ < size) {
MessageLoop::current()->PostDelayedTask(FROM_HERE, NewRunnableMethod(this,
&ConfigurableConnection::SendChunk), options_.timeout_);
} else {
socket_ = 0; // close the connection.
}
}
void ConfigurableConnection::Send(const std::string& headers,
const std::string& content) {
SendOptions options(SendOptions::IMMEDIATE, 0, 0);
SendWithOptions(headers, content, options);
}
void ConfigurableConnection::SendWithOptions(const std::string& headers,
const std::string& content,
const SendOptions& options) {
std::string content_length_header;
if (!content.empty() &&
std::string::npos == headers.find("Context-Length:")) {
content_length_header = base::StringPrintf("Content-Length: %u\r\n",
content.size());
}
// Save the options.
options_ = options;
if (options_.speed_ == SendOptions::IMMEDIATE) {
socket_->Send(headers);
socket_->Send(content_length_header, true);
socket_->Send(content);
socket_ = 0; // close the connection.
return;
}
if (options_.speed_ == SendOptions::IMMEDIATE_HEADERS_DELAYED_CONTENT) {
socket_->Send(headers);
socket_->Send(content_length_header, true);
DVLOG(1) << "Headers sent: " << headers << content_length_header;
data_.append(content);
}
if (options_.speed_ == SendOptions::DELAYED) {
data_ = headers;
data_.append(content_length_header);
data_.append("\r\n");
}
MessageLoop::current()->PostDelayedTask(FROM_HERE,
NewRunnableMethod(this, &ConfigurableConnection::SendChunk),
options.timeout_);
}
} // namespace test_server
<commit_msg>Attempt to fix a chrome frame tests crash consistently seen on the IE9 builder. I was able to reproduce it once and it appears to be occuring when the ListenSocket attempts to pass an OnObjectSignaled notification to a delegate which is the web server which has already been destroyed<commit_after>// Copyright (c) 2010 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 <windows.h>
#include <objbase.h>
#include <urlmon.h>
#include "base/logging.h"
#include "base/string_number_conversions.h"
#include "base/string_util.h"
#include "base/stringprintf.h"
#include "base/utf_string_conversions.h"
#include "chrome_frame/test/test_server.h"
#include "net/base/winsock_init.h"
#include "net/http/http_util.h"
namespace test_server {
const char kDefaultHeaderTemplate[] =
"HTTP/1.1 %hs\r\n"
"Connection: close\r\n"
"Content-Type: %hs\r\n"
"Content-Length: %i\r\n\r\n";
const char kStatusOk[] = "200 OK";
const char kStatusNotFound[] = "404 Not Found";
const char kDefaultContentType[] = "text/html; charset=UTF-8";
void Request::ParseHeaders(const std::string& headers) {
DCHECK(method_.length() == 0);
size_t pos = headers.find("\r\n");
DCHECK(pos != std::string::npos);
if (pos != std::string::npos) {
headers_ = headers.substr(pos + 2);
StringTokenizer tokenizer(headers.begin(), headers.begin() + pos, " ");
std::string* parse[] = { &method_, &path_, &version_ };
int field = 0;
while (tokenizer.GetNext() && field < arraysize(parse)) {
parse[field++]->assign(tokenizer.token_begin(),
tokenizer.token_end());
}
}
// Check for content-length in case we're being sent some data.
net::HttpUtil::HeadersIterator it(headers_.begin(), headers_.end(),
"\r\n");
while (it.GetNext()) {
if (LowerCaseEqualsASCII(it.name(), "content-length")) {
int int_content_length;
base::StringToInt(it.values_begin(),
it.values_end(),
&int_content_length);
content_length_ = int_content_length;
break;
}
}
}
void Request::OnDataReceived(const std::string& data) {
content_ += data;
if (method_.length() == 0) {
size_t index = content_.find("\r\n\r\n");
if (index != std::string::npos) {
// Parse the headers before returning and chop them of the
// data buffer we've already received.
std::string headers(content_.substr(0, index + 2));
ParseHeaders(headers);
content_.erase(0, index + 4);
}
}
}
bool FileResponse::GetContentType(std::string* content_type) const {
size_t length = ContentLength();
char buffer[4096];
void* data = NULL;
if (length) {
// Create a copy of the first few bytes of the file.
// If we try and use the mapped file directly, FindMimeFromData will crash
// 'cause it cheats and temporarily tries to write to the buffer!
length = std::min(arraysize(buffer), length);
memcpy(buffer, file_->data(), length);
data = buffer;
}
LPOLESTR mime_type = NULL;
FindMimeFromData(NULL, file_path_.value().c_str(), data, length, NULL,
FMFD_DEFAULT, &mime_type, 0);
if (mime_type) {
*content_type = WideToASCII(mime_type);
::CoTaskMemFree(mime_type);
}
return content_type->length() > 0;
}
void FileResponse::WriteContents(ListenSocket* socket) const {
DCHECK(file_.get());
if (file_.get()) {
socket->Send(reinterpret_cast<const char*>(file_->data()),
file_->length(), false);
}
}
size_t FileResponse::ContentLength() const {
if (file_.get() == NULL) {
file_.reset(new file_util::MemoryMappedFile());
if (!file_->Initialize(file_path_)) {
NOTREACHED();
file_.reset();
}
}
return file_.get() ? file_->length() : 0;
}
bool RedirectResponse::GetCustomHeaders(std::string* headers) const {
*headers = base::StringPrintf("HTTP/1.1 302 Found\r\n"
"Connection: close\r\n"
"Content-Length: 0\r\n"
"Content-Type: text/html\r\n"
"Location: %hs\r\n\r\n",
redirect_url_.c_str());
return true;
}
SimpleWebServer::SimpleWebServer(int port) {
CHECK(MessageLoop::current()) << "SimpleWebServer requires a message loop";
net::EnsureWinsockInit();
AddResponse(&quit_);
server_ = ListenSocket::Listen("127.0.0.1", port, this);
DCHECK(server_.get() != NULL);
}
SimpleWebServer::~SimpleWebServer() {
ConnectionList::const_iterator it;
for (it = connections_.begin(); it != connections_.end(); ++it)
delete (*it);
connections_.clear();
}
void SimpleWebServer::AddResponse(Response* response) {
responses_.push_back(response);
}
void SimpleWebServer::DeleteAllResponses() {
std::list<Response*>::const_iterator it;
for (it = responses_.begin(); it != responses_.end(); ++it) {
if ((*it) != &quit_)
delete (*it);
}
connections_.clear();
}
Response* SimpleWebServer::FindResponse(const Request& request) const {
std::list<Response*>::const_iterator it;
for (it = responses_.begin(); it != responses_.end(); it++) {
Response* response = (*it);
if (response->Matches(request)) {
return response;
}
}
return NULL;
}
Connection* SimpleWebServer::FindConnection(const ListenSocket* socket) const {
ConnectionList::const_iterator it;
for (it = connections_.begin(); it != connections_.end(); it++) {
if ((*it)->IsSame(socket)) {
return (*it);
}
}
return NULL;
}
void SimpleWebServer::DidAccept(ListenSocket* server,
ListenSocket* connection) {
connections_.push_back(new Connection(connection));
}
void SimpleWebServer::DidRead(ListenSocket* connection,
const char* data,
int len) {
Connection* c = FindConnection(connection);
DCHECK(c);
Request& r = c->request();
std::string str(data, len);
r.OnDataReceived(str);
if (r.AllContentReceived()) {
const Request& request = c->request();
Response* response = FindResponse(request);
if (response) {
std::string headers;
if (!response->GetCustomHeaders(&headers)) {
std::string content_type;
if (!response->GetContentType(&content_type))
content_type = kDefaultContentType;
headers = base::StringPrintf(kDefaultHeaderTemplate, kStatusOk,
content_type.c_str(),
response->ContentLength());
}
connection->Send(headers, false);
response->WriteContents(connection);
response->IncrementAccessCounter();
} else {
std::string payload = "sorry, I can't find " + request.path();
std::string headers(base::StringPrintf(kDefaultHeaderTemplate,
kStatusNotFound,
kDefaultContentType,
payload.length()));
connection->Send(headers, false);
connection->Send(payload, false);
}
}
}
void SimpleWebServer::DidClose(ListenSocket* sock) {
// To keep the historical list of connections reasonably tidy, we delete
// 404's when the connection ends.
Connection* c = FindConnection(sock);
DCHECK(c);
if (!FindResponse(c->request())) {
// extremely inefficient, but in one line and not that common... :)
connections_.erase(std::find(connections_.begin(), connections_.end(), c));
delete c;
}
}
HTTPTestServer::HTTPTestServer(int port, const std::wstring& address,
FilePath root_dir)
: port_(port), address_(address), root_dir_(root_dir) {
net::EnsureWinsockInit();
server_ = ListenSocket::Listen(WideToUTF8(address), port, this);
}
HTTPTestServer::~HTTPTestServer() {
LOG(INFO) << __FUNCTION__;
server_ = NULL;
}
std::list<scoped_refptr<ConfigurableConnection>>::iterator
HTTPTestServer::FindConnection(const ListenSocket* socket) {
ConnectionList::iterator it;
for (it = connection_list_.begin(); it != connection_list_.end(); ++it) {
if ((*it)->socket_ == socket) {
break;
}
}
return it;
}
scoped_refptr<ConfigurableConnection> HTTPTestServer::ConnectionFromSocket(
const ListenSocket* socket) {
ConnectionList::iterator it = FindConnection(socket);
if (it != connection_list_.end())
return *it;
return NULL;
}
void HTTPTestServer::DidAccept(ListenSocket* server, ListenSocket* socket) {
connection_list_.push_back(new ConfigurableConnection(socket));
}
void HTTPTestServer::DidRead(ListenSocket* socket,
const char* data,
int len) {
scoped_refptr<ConfigurableConnection> connection =
ConnectionFromSocket(socket);
if (connection) {
std::string str(data, len);
connection->r_.OnDataReceived(str);
if (connection->r_.AllContentReceived()) {
std::wstring path = UTF8ToWide(connection->r_.path());
if (LowerCaseEqualsASCII(connection->r_.method(), "post"))
this->Post(connection, path, connection->r_);
else
this->Get(connection, path, connection->r_);
}
}
}
void HTTPTestServer::DidClose(ListenSocket* socket) {
ConnectionList::iterator it = FindConnection(socket);
DCHECK(it != connection_list_.end());
connection_list_.erase(it);
}
std::wstring HTTPTestServer::Resolve(const std::wstring& path) {
// Remove the first '/' if needed.
std::wstring stripped_path = path;
if (path.size() && path[0] == L'/')
stripped_path = path.substr(1);
if (port_ == 80) {
if (stripped_path.empty()) {
return base::StringPrintf(L"http://%ls", address_.c_str());
} else {
return base::StringPrintf(L"http://%ls/%ls", address_.c_str(),
stripped_path.c_str());
}
} else {
if (stripped_path.empty()) {
return base::StringPrintf(L"http://%ls:%d", address_.c_str(), port_);
} else {
return base::StringPrintf(L"http://%ls:%d/%ls", address_.c_str(), port_,
stripped_path.c_str());
}
}
}
void ConfigurableConnection::SendChunk() {
int size = (int)data_.size();
const char* chunk_ptr = data_.c_str() + cur_pos_;
int bytes_to_send = std::min(options_.chunk_size_, size - cur_pos_);
socket_->Send(chunk_ptr, bytes_to_send);
DVLOG(1) << "Sent(" << cur_pos_ << "," << bytes_to_send << "): "
<< base::StringPiece(chunk_ptr, bytes_to_send);
cur_pos_ += bytes_to_send;
if (cur_pos_ < size) {
MessageLoop::current()->PostDelayedTask(FROM_HERE, NewRunnableMethod(this,
&ConfigurableConnection::SendChunk), options_.timeout_);
} else {
socket_ = 0; // close the connection.
}
}
void ConfigurableConnection::Send(const std::string& headers,
const std::string& content) {
SendOptions options(SendOptions::IMMEDIATE, 0, 0);
SendWithOptions(headers, content, options);
}
void ConfigurableConnection::SendWithOptions(const std::string& headers,
const std::string& content,
const SendOptions& options) {
std::string content_length_header;
if (!content.empty() &&
std::string::npos == headers.find("Context-Length:")) {
content_length_header = base::StringPrintf("Content-Length: %u\r\n",
content.size());
}
// Save the options.
options_ = options;
if (options_.speed_ == SendOptions::IMMEDIATE) {
socket_->Send(headers);
socket_->Send(content_length_header, true);
socket_->Send(content);
socket_ = 0; // close the connection.
return;
}
if (options_.speed_ == SendOptions::IMMEDIATE_HEADERS_DELAYED_CONTENT) {
socket_->Send(headers);
socket_->Send(content_length_header, true);
DVLOG(1) << "Headers sent: " << headers << content_length_header;
data_.append(content);
}
if (options_.speed_ == SendOptions::DELAYED) {
data_ = headers;
data_.append(content_length_header);
data_.append("\r\n");
}
MessageLoop::current()->PostDelayedTask(FROM_HERE,
NewRunnableMethod(this, &ConfigurableConnection::SendChunk),
options.timeout_);
}
} // namespace test_server
<|endoftext|> |
<commit_before>#pragma unmanaged
#include "IntersonCxxImagingScan2DClass.h"
#pragma managed
#include <vcclr.h>
#include <msclr/marshal_cppstd.h>
#using "Interson.dll"
// For StartReadScan
#using "System.Drawing.dll"
namespace IntersonCxx
{
namespace Imaging
{
class Scan2DClassImpl
{
public:
typedef cli::array< byte, 2 > BmodeArrayType;
typedef Scan2DClass::NewBmodeImageCallbackType NewBmodeImageCallbackType;
Scan2DClassImpl()
{
Wrapped = gcnew Interson::Imaging::Scan2DClass();
BmodeBuffer = gcnew BmodeArrayType( Scan2DClass::MAX_VECTORS, Scan2DClass::MAX_SAMPLES );
}
bool GetScanOn()
{
return Wrapped->ScanOn;
}
bool GetRFData()
{
return Wrapped->RFData;
}
void SetRFData( bool transferOn )
{
Wrapped->RFData = transferOn;
}
void StartReadScan( unsigned char * buffer )
{
Wrapped->StartReadScan( (BmodeArrayType ^)BmodeBuffer );
for( int ii = 0; ii < Scan2DClass::MAX_VECTORS; ++ii )
{
for( int jj = 0; jj < Scan2DClass::MAX_SAMPLES; ++jj )
{
buffer[Scan2DClass::MAX_SAMPLES * ii + jj] = BmodeBuffer[ii, jj];
}
}
}
void StopReadScan()
{
Wrapped->StopReadScan();
}
void DisposeScan()
{
Wrapped->DisposeScan();
}
void AbortScan()
{
Wrapped->AbortScan();
}
void SetNewBmodeImageCallback( NewBmodeImageCallbackType callback, void * clientData = 0)
{
this->NewBmodeImageCallback = callback;
this->NewBmodeImageCallbackClientData = clientData;
}
private:
gcroot< Interson::Imaging::Scan2DClass ^ > Wrapped;
gcroot< BmodeArrayType ^ > BmodeBuffer;
unsigned char * NativeBmodeBuffer;
NewBmodeImageCallbackType NewBmodeImageCallback;
void * NewBmodeImageCallbackClientData;
};
#pragma unmanaged
Scan2DClass
::Scan2DClass():
Impl( new Scan2DClassImpl() ),
BmodeBuffer( new unsigned char[MAX_SAMPLES * MAX_VECTORS] )
{
//this->Impl->SetInterface( this );
}
Scan2DClass
::~Scan2DClass()
{
delete Impl;
delete [] BmodeBuffer;
}
bool
Scan2DClass
::GetScanOn() const
{
return Impl->GetScanOn();
}
bool
Scan2DClass
::GetRFData() const
{
return Impl->GetRFData();
}
void
Scan2DClass
::SetRFData( bool transferOn )
{
Impl->SetRFData( transferOn );
}
void
Scan2DClass
::StartReadScan()
{
Impl->StartReadScan( BmodeBuffer );
}
void
Scan2DClass
::StopReadScan()
{
Impl->StopReadScan();
}
void
Scan2DClass
::DisposeScan()
{
Impl->DisposeScan();
}
void
Scan2DClass
::AbortScan()
{
Impl->AbortScan();
}
void
Scan2DClass
::SetNewBmodeImageCallback( NewBmodeImageCallbackType callback,
void * clientData )
{
Impl->SetNewBmodeImageCallback( callback, clientData );
}
} // end namespace Imaging
} // end namespace IntersonCxx
<commit_msg>ENH: NewBmodeImageHandler<commit_after>#pragma unmanaged
#include "IntersonCxxImagingScan2DClass.h"
#pragma managed
#include <vcclr.h>
#include <msclr/marshal_cppstd.h>
#using "Interson.dll"
// For StartReadScan
//#using "System.Drawing.dll"
namespace IntersonCxx
{
namespace Imaging
{
ref class NewBmodeImageHandler
{
public:
typedef Scan2DClass::NewBmodeImageCallbackType NewBmodeImageCallbackType;
typedef cli::array< byte, 2 > BmodeArrayType;
NewBmodeImageHandler( BmodeArrayType ^ managedBmodeBuffer ):
NewBmodeImageCallback( NULL ),
NewBmodeImageCallbackClientData( NULL ),
NativeBmodeBuffer( new unsigned char[Scan2DClass::MAX_SAMPLES * Scan2DClass::MAX_VECTORS] ),
ManagedBmodeBuffer( managedBmodeBuffer )
{
}
~NewBmodeImageHandler()
{
delete [] NativeBmodeBuffer;
}
void HandleNewBmodeImage( Interson::Imaging::Scan2DClass ^ scan2D, System::EventArgs ^ eventArgs )
{
if( this->NewBmodeImageCallback != NULL )
{
for( int ii = 0; ii < Scan2DClass::MAX_VECTORS; ++ii )
{
for( int jj = 0; jj < Scan2DClass::MAX_SAMPLES; ++jj )
{
this->NativeBmodeBuffer[Scan2DClass::MAX_SAMPLES * ii + jj] = this->ManagedBmodeBuffer[ii, jj];
}
}
this->NewBmodeImageCallback( this->NativeBmodeBuffer, this->NewBmodeImageCallbackClientData );
}
}
void SetNewBmodeImageCallback( NewBmodeImageCallbackType callback, void * clientData )
{
this->NewBmodeImageCallback = callback;
this->NewBmodeImageCallbackClientData = clientData;
}
private:
NewBmodeImageCallbackType NewBmodeImageCallback;
void * NewBmodeImageCallbackClientData;
unsigned char * NativeBmodeBuffer;
BmodeArrayType ^ ManagedBmodeBuffer;
};
class Scan2DClassImpl
{
public:
typedef cli::array< byte, 2 > BmodeArrayType;
typedef Scan2DClass::NewBmodeImageCallbackType NewBmodeImageCallbackType;
Scan2DClassImpl()
{
Wrapped = gcnew Interson::Imaging::Scan2DClass();
BmodeBuffer = gcnew BmodeArrayType( Scan2DClass::MAX_VECTORS, Scan2DClass::MAX_SAMPLES );
BmodeHandler = gcnew NewBmodeImageHandler( BmodeBuffer );
Interson::Imaging::Scan2DClass::NewImageHandler ^ myHandler = gcnew
Interson::Imaging::Scan2DClass::NewImageHandler(BmodeHandler,
&NewBmodeImageHandler::HandleNewBmodeImage );
Wrapped->NewImageTick += myHandler;
}
bool GetScanOn()
{
return Wrapped->ScanOn;
}
bool GetRFData()
{
return Wrapped->RFData;
}
void SetRFData( bool transferOn )
{
Wrapped->RFData = transferOn;
}
void StartReadScan()
{
Wrapped->StartReadScan( (BmodeArrayType ^)BmodeBuffer );
}
void StopReadScan()
{
Wrapped->StopReadScan();
}
void DisposeScan()
{
Wrapped->DisposeScan();
}
void AbortScan()
{
Wrapped->AbortScan();
}
void SetNewBmodeImageCallback( NewBmodeImageCallbackType callback, void * clientData = 0 )
{
this->BmodeHandler->SetNewBmodeImageCallback( callback, clientData );
}
void HandleNewBmodeImage( Interson::Imaging::Scan2DClass ^ scan2D, System::EventArgs ^ eventArgs )
{
}
private:
gcroot< Interson::Imaging::Scan2DClass ^ > Wrapped;
gcroot< BmodeArrayType ^ > BmodeBuffer;
gcroot< NewBmodeImageHandler ^ > BmodeHandler;
};
#pragma unmanaged
Scan2DClass
::Scan2DClass():
Impl( new Scan2DClassImpl() )
{
}
Scan2DClass
::~Scan2DClass()
{
delete Impl;
}
bool
Scan2DClass
::GetScanOn() const
{
return Impl->GetScanOn();
}
bool
Scan2DClass
::GetRFData() const
{
return Impl->GetRFData();
}
void
Scan2DClass
::SetRFData( bool transferOn )
{
Impl->SetRFData( transferOn );
}
void
Scan2DClass
::StartReadScan()
{
Impl->StartReadScan();
}
void
Scan2DClass
::StopReadScan()
{
Impl->StopReadScan();
}
void
Scan2DClass
::DisposeScan()
{
Impl->DisposeScan();
}
void
Scan2DClass
::AbortScan()
{
Impl->AbortScan();
}
void
Scan2DClass
::SetNewBmodeImageCallback( NewBmodeImageCallbackType callback,
void * clientData )
{
Impl->SetNewBmodeImageCallback( callback, clientData );
}
} // end namespace Imaging
} // end namespace IntersonCxx
<|endoftext|> |
<commit_before>/****************************************************************************
**
** Copyright (C) 2013 Digia Plc and/or its subsidiary(-ies).
** Contact: http://www.qt-project.org/legal
**
** This file is part of Qt Creator.
**
** Commercial License Usage
** Licensees holding valid commercial Qt licenses may use this file in
** accordance with the commercial license agreement provided with the
** Software or, alternatively, in accordance with the terms contained in
** a written agreement between you and Digia. For licensing terms and
** conditions see http://qt.digia.com/licensing. For further information
** use the contact form at http://qt.digia.com/contact-us.
**
** GNU Lesser General Public License Usage
** Alternatively, this file may be used under the terms of the GNU Lesser
** General Public License version 2.1 as published by the Free Software
** Foundation and appearing in the file LICENSE.LGPL included in the
** packaging of this file. Please review the following information to
** ensure the GNU Lesser General Public License version 2.1 requirements
** will be met: http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
**
** In addition, as a special exception, Digia gives you certain additional
** rights. These rights are described in the Digia Qt LGPL Exception
** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.
**
****************************************************************************/
#include "helloworldplugin.h"
#include <coreplugin/actionmanager/actionmanager.h>
#include <coreplugin/actionmanager/actioncontainer.h>
#include <coreplugin/coreconstants.h>
#include <coreplugin/icore.h>
#include <coreplugin/imode.h>
#include <coreplugin/modemanager.h>
#include <coreplugin/id.h>
#include <QDebug>
#include <QtPlugin>
#include <QAction>
#include <QMenu>
#include <QMessageBox>
#include <QPushButton>
namespace HelloWorld {
namespace Internal {
/*! A mode with a push button based on BaseMode. */
class HelloMode : public Core::IMode
{
public:
HelloMode()
{
setWidget(new QPushButton(tr("Hello World PushButton!")));
setContext(Core::Context("HelloWorld.MainView"));
setDisplayName(tr("Hello world!"));
setIcon(QIcon());
setPriority(0);
setId("HelloWorld.HelloWorldMode");
setType("HelloWorld.HelloWorldMode");
setContextHelpId(QString());
}
};
/*! Constructs the Hello World plugin. Normally plugins don't do anything in
their constructor except for initializing their member variables. The
actual work is done later, in the initialize() and extensionsInitialized()
methods.
*/
HelloWorldPlugin::HelloWorldPlugin()
{
}
/*! Plugins are responsible for deleting objects they created on the heap, and
to unregister objects from the plugin manager that they registered there.
*/
HelloWorldPlugin::~HelloWorldPlugin()
{
}
/*! Initializes the plugin. Returns true on success.
Plugins want to register objects with the plugin manager here.
\a errorMessage can be used to pass an error message to the plugin system,
if there was any.
*/
bool HelloWorldPlugin::initialize(const QStringList &arguments, QString *errorMessage)
{
Q_UNUSED(arguments)
Q_UNUSED(errorMessage)
// Create a unique context for our own view, that will be used for the
// menu entry later.
Core::Context context("HelloWorld.MainView");
// Create an action to be triggered by a menu entry
QAction *helloWorldAction = new QAction(tr("Say \"&Hello World!\""), this);
connect(helloWorldAction, SIGNAL(triggered()), SLOT(sayHelloWorld()));
// Register the action with the action manager
Core::Command *command =
Core::ActionManager::registerAction(
helloWorldAction, "HelloWorld.HelloWorldAction", context);
// Create our own menu to place in the Tools menu
Core::ActionContainer *helloWorldMenu =
Core::ActionManager::createMenu("HelloWorld.HelloWorldMenu");
QMenu *menu = helloWorldMenu->menu();
menu->setTitle(tr("&Hello World"));
menu->setEnabled(true);
// Add the Hello World action command to the menu
helloWorldMenu->addAction(command);
// Request the Tools menu and add the Hello World menu to it
Core::ActionContainer *toolsMenu =
Core::ActionManager::actionContainer(Core::Constants::M_TOOLS);
toolsMenu->addMenu(helloWorldMenu);
// Add a mode with a push button based on BaseMode. Like the BaseView,
// it will unregister itself from the plugin manager when it is deleted.
Core::IMode *helloMode = new HelloMode;
addAutoReleasedObject(helloMode);
return true;
}
/*! Notification that all extensions that this plugin depends on have been
initialized. The dependencies are defined in the plugins .pluginspec file.
Normally this method is used for things that rely on other plugins to have
added objects to the plugin manager, that implement interfaces that we're
interested in. These objects can now be requested through the
PluginManagerInterface.
The HelloWorldPlugin doesn't need things from other plugins, so it does
nothing here.
*/
void HelloWorldPlugin::extensionsInitialized()
{
}
void HelloWorldPlugin::sayHelloWorld()
{
// When passing 0 for the parent, the message box becomes an
// application-global modal dialog box
QMessageBox::information(
0, tr("Hello World!"), tr("Hello World! Beautiful day today, isn't it?"));
}
} // namespace Internal
} // namespace HelloWorld
Q_EXPORT_PLUGIN(HelloWorld::Internal::HelloWorldPlugin)
<commit_msg>Revert 27aa0e89c9ee9f0d28acea13b72d73b36b7a469f<commit_after>/****************************************************************************
**
** Copyright (C) 2013 Digia Plc and/or its subsidiary(-ies).
** Contact: http://www.qt-project.org/legal
**
** This file is part of Qt Creator.
**
** Commercial License Usage
** Licensees holding valid commercial Qt licenses may use this file in
** accordance with the commercial license agreement provided with the
** Software or, alternatively, in accordance with the terms contained in
** a written agreement between you and Digia. For licensing terms and
** conditions see http://qt.digia.com/licensing. For further information
** use the contact form at http://qt.digia.com/contact-us.
**
** GNU Lesser General Public License Usage
** Alternatively, this file may be used under the terms of the GNU Lesser
** General Public License version 2.1 as published by the Free Software
** Foundation and appearing in the file LICENSE.LGPL included in the
** packaging of this file. Please review the following information to
** ensure the GNU Lesser General Public License version 2.1 requirements
** will be met: http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
**
** In addition, as a special exception, Digia gives you certain additional
** rights. These rights are described in the Digia Qt LGPL Exception
** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.
**
****************************************************************************/
#include "helloworldplugin.h"
#include <coreplugin/actionmanager/actionmanager.h>
#include <coreplugin/actionmanager/actioncontainer.h>
#include <coreplugin/coreconstants.h>
#include <coreplugin/icore.h>
#include <coreplugin/imode.h>
#include <coreplugin/modemanager.h>
#include <coreplugin/id.h>
#include <QDebug>
#include <QtPlugin>
#include <QAction>
#include <QMenu>
#include <QMessageBox>
#include <QPushButton>
namespace HelloWorld {
namespace Internal {
/*! A mode with a push button based on BaseMode. */
class HelloMode : public Core::IMode
{
public:
HelloMode()
{
setWidget(new QPushButton(tr("Hello World PushButton!")));
setContext(Core::Context("HelloWorld.MainView"));
setDisplayName(tr("Hello world!"));
setIcon(QIcon());
setPriority(0);
setId("HelloWorld.HelloWorldMode");
setType("HelloWorld.HelloWorldMode");
setContextHelpId(QString());
}
};
/*! Constructs the Hello World plugin. Normally plugins don't do anything in
their constructor except for initializing their member variables. The
actual work is done later, in the initialize() and extensionsInitialized()
methods.
*/
HelloWorldPlugin::HelloWorldPlugin()
{
}
/*! Plugins are responsible for deleting objects they created on the heap, and
to unregister objects from the plugin manager that they registered there.
*/
HelloWorldPlugin::~HelloWorldPlugin()
{
}
/*! Initializes the plugin. Returns true on success.
Plugins want to register objects with the plugin manager here.
\a errorMessage can be used to pass an error message to the plugin system,
if there was any.
*/
bool HelloWorldPlugin::initialize(const QStringList &arguments, QString *errorMessage)
{
Q_UNUSED(arguments)
Q_UNUSED(errorMessage)
// Create a unique context for our own view, that will be used for the
// menu entry later.
Core::Context context("HelloWorld.MainView");
// Create an action to be triggered by a menu entry
QAction *helloWorldAction = new QAction(tr("Say \"&Hello World!\""), this);
connect(helloWorldAction, SIGNAL(triggered()), SLOT(sayHelloWorld()));
// Register the action with the action manager
Core::Command *command =
Core::ActionManager::registerAction(
helloWorldAction, "HelloWorld.HelloWorldAction", context);
// Create our own menu to place in the Tools menu
Core::ActionContainer *helloWorldMenu =
Core::ActionManager::createMenu("HelloWorld.HelloWorldMenu");
QMenu *menu = helloWorldMenu->menu();
menu->setTitle(tr("&Hello World"));
menu->setEnabled(true);
// Add the Hello World action command to the menu
helloWorldMenu->addAction(command);
// Request the Tools menu and add the Hello World menu to it
Core::ActionContainer *toolsMenu =
Core::ActionManager::actionContainer(Core::Constants::M_TOOLS);
toolsMenu->addMenu(helloWorldMenu);
// Add a mode with a push button based on BaseMode. Like the BaseView,
// it will unregister itself from the plugin manager when it is deleted.
Core::IMode *helloMode = new HelloMode;
addAutoReleasedObject(helloMode);
return true;
}
/*! Notification that all extensions that this plugin depends on have been
initialized. The dependencies are defined in the plugins .pluginspec file.
Normally this method is used for things that rely on other plugins to have
added objects to the plugin manager, that implement interfaces that we're
interested in. These objects can now be requested through the
PluginManagerInterface.
The HelloWorldPlugin doesn't need things from other plugins, so it does
nothing here.
*/
void HelloWorldPlugin::extensionsInitialized()
{
}
void HelloWorldPlugin::sayHelloWorld()
{
// When passing 0 for the parent, the message box becomes an
// application-global modal dialog box
QMessageBox::information(
0, tr("Hello World!"), tr("Hello World! Beautiful day today, isn't it?"));
}
} // namespace Internal
} // namespace HelloWorld
Q_EXPORT_PLUGIN(HelloWorld::Internal::HelloWorldPlugin)
<|endoftext|> |
<commit_before>/*
* Copyright 2016 Open Connectome Project (http://openconnecto.me)
* Written by Da Zheng (zhengda1936@gmail.com)
*
* This file is part of FlashMatrix.
*
* 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 <boost/format.hpp>
#include "cached_matrix_store.h"
#include "combined_matrix_store.h"
#include "EM_dense_matrix.h"
#include "local_matrix_store.h"
namespace fm
{
namespace detail
{
static inline matrix_layout_t decide_layout(size_t num_rows, size_t num_cols)
{
if (num_rows < num_cols)
return matrix_layout_t::L_ROW;
else
return matrix_layout_t::L_COL;
}
// This is created for transpose.
cached_matrix_store::cached_matrix_store(size_t num_rows, size_t num_cols,
const scalar_type &type): matrix_store(num_rows, num_cols, false, type)
{
}
cached_matrix_store::cached_matrix_store(size_t num_rows, size_t num_cols,
int num_nodes, const scalar_type &type,
size_t num_cached_vecs): matrix_store(num_rows, num_cols, false, type)
{
assert(num_cached_vecs > 0);
em_buf = EM_matrix_store::create(num_rows, num_cols,
decide_layout(num_rows, num_cols), type);
matrix_store::const_ptr uncached;
if (em_buf->is_wide()) {
num_cached_vecs = std::min(num_cached_vecs, num_rows);
cached_buf = mem_matrix_store::create(num_cached_vecs, num_cols,
em_buf->store_layout(), type, num_nodes);
std::vector<off_t> row_offs(num_rows - num_cached_vecs);
for (size_t i = 0; i < row_offs.size(); i++)
row_offs[i] = num_cached_vecs + i;
if (!row_offs.empty()) {
uncached = em_buf->get_rows(row_offs);
assert(uncached);
}
}
else {
num_cached_vecs = std::min(num_cached_vecs, num_cols);
cached_buf = mem_matrix_store::create(num_rows, num_cached_vecs,
em_buf->store_layout(), type, num_nodes);
std::vector<off_t> col_offs(num_cols - num_cached_vecs);
for (size_t i = 0; i < col_offs.size(); i++)
col_offs[i] = num_cached_vecs + i;
if (!col_offs.empty()) {
uncached = em_buf->get_cols(col_offs);
assert(uncached);
}
}
// If the entire matrix is cached.
if (uncached == NULL)
mixed = cached_buf;
else {
std::vector<matrix_store::const_ptr> mats(2);
mats[0] = cached_buf;
mats[1] = uncached;
assert(cached_buf->store_layout() == uncached->store_layout());
mixed = combined_matrix_store::create(mats, cached_buf->store_layout());
}
cached = cached_buf;
em_store = em_buf;
}
std::string cached_matrix_store::get_name() const
{
return boost::str(boost::format("cached%1%_mat(%2%)")
% get_num_cached_vecs() % em_store->get_name());
}
matrix_store::const_ptr cached_matrix_store::transpose() const
{
cached_matrix_store *store = new cached_matrix_store(get_num_cols(),
get_num_rows(), get_type());
store->mixed = mixed->transpose();
store->cached = cached->transpose();
store->em_store = EM_matrix_store::cast(em_store->transpose());
// We don't need to set em_buf and cached_buf because these are only
// required for write data to the matrix store.
return matrix_store::const_ptr(store);
}
void cached_matrix_store::write_portion_async(
local_matrix_store::const_ptr portion, off_t start_row, off_t start_col)
{
assert(em_buf);
assert(cached_buf);
if (is_wide()) {
local_matrix_store::const_ptr sub_portion = portion->get_portion(0, 0,
cached_buf->get_num_rows(), portion->get_num_cols());
local_matrix_store &mutable_sub
= const_cast<local_matrix_store &>(*sub_portion);
size_t mem_portion_size = cached_buf->get_portion_size().second;
for (size_t lstart_col = 0; lstart_col < portion->get_num_cols();
lstart_col += mem_portion_size) {
size_t lnum_cols = std::min(mem_portion_size,
portion->get_num_cols() - lstart_col);
mutable_sub.resize(0, lstart_col, sub_portion->get_num_rows(),
lnum_cols);
cached_buf->write_portion_async(sub_portion, start_row,
start_col + lstart_col);
}
}
else {
local_matrix_store::const_ptr sub_portion = portion->get_portion(0, 0,
portion->get_num_rows(), cached_buf->get_num_cols());
local_matrix_store &mutable_sub
= const_cast<local_matrix_store &>(*sub_portion);
size_t mem_portion_size = cached_buf->get_portion_size().first;
for (size_t lstart_row = 0; lstart_row < portion->get_num_rows();
lstart_row += mem_portion_size) {
size_t lnum_rows = std::min(mem_portion_size,
portion->get_num_rows() - lstart_row);
mutable_sub.resize(lstart_row, 0, lnum_rows,
sub_portion->get_num_cols());
cached_buf->write_portion_async(sub_portion, start_row + lstart_row,
start_col);
}
}
em_buf->write_portion_async(portion, start_row, start_col);
}
matrix_store::const_ptr cached_matrix_store::get_rows(
const std::vector<off_t> &idxs) const
{
if (!is_wide()) {
BOOST_LOG_TRIVIAL(error) << "can't get rows from a tall matrix\n";
return matrix_store::const_ptr();
}
// If all rows are cached.
size_t num_cached = get_num_cached_vecs();
bool all_cached = true;
for (size_t i = 0; i < idxs.size(); i++)
if ((size_t) idxs[i] >= num_cached)
all_cached = false;
if (all_cached)
return cached->get_rows(idxs);
return mixed->get_rows(idxs);
}
void cached_matrix_store::set_cache_portion(bool cache_portion)
{
const_cast<matrix_store &>(*mixed).set_cache_portion(cache_portion);
}
}
}
<commit_msg>[Matrix]: get_rows can return the entire cached matrix.<commit_after>/*
* Copyright 2016 Open Connectome Project (http://openconnecto.me)
* Written by Da Zheng (zhengda1936@gmail.com)
*
* This file is part of FlashMatrix.
*
* 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 <boost/format.hpp>
#include "cached_matrix_store.h"
#include "combined_matrix_store.h"
#include "EM_dense_matrix.h"
#include "local_matrix_store.h"
namespace fm
{
namespace detail
{
static inline matrix_layout_t decide_layout(size_t num_rows, size_t num_cols)
{
if (num_rows < num_cols)
return matrix_layout_t::L_ROW;
else
return matrix_layout_t::L_COL;
}
// This is created for transpose.
cached_matrix_store::cached_matrix_store(size_t num_rows, size_t num_cols,
const scalar_type &type): matrix_store(num_rows, num_cols, false, type)
{
}
cached_matrix_store::cached_matrix_store(size_t num_rows, size_t num_cols,
int num_nodes, const scalar_type &type,
size_t num_cached_vecs): matrix_store(num_rows, num_cols, false, type)
{
assert(num_cached_vecs > 0);
em_buf = EM_matrix_store::create(num_rows, num_cols,
decide_layout(num_rows, num_cols), type);
matrix_store::const_ptr uncached;
if (em_buf->is_wide()) {
num_cached_vecs = std::min(num_cached_vecs, num_rows);
cached_buf = mem_matrix_store::create(num_cached_vecs, num_cols,
em_buf->store_layout(), type, num_nodes);
std::vector<off_t> row_offs(num_rows - num_cached_vecs);
for (size_t i = 0; i < row_offs.size(); i++)
row_offs[i] = num_cached_vecs + i;
if (!row_offs.empty()) {
uncached = em_buf->get_rows(row_offs);
assert(uncached);
}
}
else {
num_cached_vecs = std::min(num_cached_vecs, num_cols);
cached_buf = mem_matrix_store::create(num_rows, num_cached_vecs,
em_buf->store_layout(), type, num_nodes);
std::vector<off_t> col_offs(num_cols - num_cached_vecs);
for (size_t i = 0; i < col_offs.size(); i++)
col_offs[i] = num_cached_vecs + i;
if (!col_offs.empty()) {
uncached = em_buf->get_cols(col_offs);
assert(uncached);
}
}
// If the entire matrix is cached.
if (uncached == NULL)
mixed = cached_buf;
else {
std::vector<matrix_store::const_ptr> mats(2);
mats[0] = cached_buf;
mats[1] = uncached;
assert(cached_buf->store_layout() == uncached->store_layout());
mixed = combined_matrix_store::create(mats, cached_buf->store_layout());
}
cached = cached_buf;
em_store = em_buf;
}
std::string cached_matrix_store::get_name() const
{
return boost::str(boost::format("cached%1%_mat(%2%)")
% get_num_cached_vecs() % em_store->get_name());
}
matrix_store::const_ptr cached_matrix_store::transpose() const
{
cached_matrix_store *store = new cached_matrix_store(get_num_cols(),
get_num_rows(), get_type());
store->mixed = mixed->transpose();
store->cached = cached->transpose();
store->em_store = EM_matrix_store::cast(em_store->transpose());
// We don't need to set em_buf and cached_buf because these are only
// required for write data to the matrix store.
return matrix_store::const_ptr(store);
}
void cached_matrix_store::write_portion_async(
local_matrix_store::const_ptr portion, off_t start_row, off_t start_col)
{
assert(em_buf);
assert(cached_buf);
if (is_wide()) {
local_matrix_store::const_ptr sub_portion = portion->get_portion(0, 0,
cached_buf->get_num_rows(), portion->get_num_cols());
local_matrix_store &mutable_sub
= const_cast<local_matrix_store &>(*sub_portion);
size_t mem_portion_size = cached_buf->get_portion_size().second;
for (size_t lstart_col = 0; lstart_col < portion->get_num_cols();
lstart_col += mem_portion_size) {
size_t lnum_cols = std::min(mem_portion_size,
portion->get_num_cols() - lstart_col);
mutable_sub.resize(0, lstart_col, sub_portion->get_num_rows(),
lnum_cols);
cached_buf->write_portion_async(sub_portion, start_row,
start_col + lstart_col);
}
}
else {
local_matrix_store::const_ptr sub_portion = portion->get_portion(0, 0,
portion->get_num_rows(), cached_buf->get_num_cols());
local_matrix_store &mutable_sub
= const_cast<local_matrix_store &>(*sub_portion);
size_t mem_portion_size = cached_buf->get_portion_size().first;
for (size_t lstart_row = 0; lstart_row < portion->get_num_rows();
lstart_row += mem_portion_size) {
size_t lnum_rows = std::min(mem_portion_size,
portion->get_num_rows() - lstart_row);
mutable_sub.resize(lstart_row, 0, lnum_rows,
sub_portion->get_num_cols());
cached_buf->write_portion_async(sub_portion, start_row + lstart_row,
start_col);
}
}
em_buf->write_portion_async(portion, start_row, start_col);
}
matrix_store::const_ptr cached_matrix_store::get_rows(
const std::vector<off_t> &idxs) const
{
if (!is_wide()) {
BOOST_LOG_TRIVIAL(error) << "can't get rows from a tall matrix\n";
return matrix_store::const_ptr();
}
// If all rows are cached.
size_t num_cached = get_num_cached_vecs();
bool all_cached = true;
for (size_t i = 0; i < idxs.size(); i++)
if ((size_t) idxs[i] >= num_cached)
all_cached = false;
// If we want to access all rows of the matrix, we can return
// the entire matrix directly.
if (all_cached && idxs.size() == cached->get_num_rows()
&& std::is_sorted(idxs.begin(), idxs.end()))
return cached;
else if (all_cached)
return cached->get_rows(idxs);
return mixed->get_rows(idxs);
}
void cached_matrix_store::set_cache_portion(bool cache_portion)
{
const_cast<matrix_store &>(*mixed).set_cache_portion(cache_portion);
}
}
}
<|endoftext|> |
<commit_before>/*
* Vulkan examples debug wrapper
*
* Appendix for VK_EXT_Debug_Report can be found at https://github.com/KhronosGroup/Vulkan-Docs/blob/1.0-VK_EXT_debug_report/doc/specs/vulkan/appendices/debug_report.txt
*
* Copyright (C) 2016 by Sascha Willems - www.saschawillems.de
*
* This code is licensed under the MIT license (MIT) (http://opensource.org/licenses/MIT)
*/
#include "VulkanDebug.h"
#include <iostream>
namespace vks
{
namespace debug
{
#if !defined(__ANDROID__)
// On desktop the LunarG loaders exposes a meta layer that contains all layers
int32_t validationLayerCount = 1;
const char *validationLayerNames[] = {
"VK_LAYER_LUNARG_standard_validation"
};
#else
// On Android we need to explicitly select all layers
int32_t validationLayerCount = 7;
const char *validationLayerNames[] = {
"VK_LAYER_GOOGLE_threading",
"VK_LAYER_LUNARG_parameter_validation",
"VK_LAYER_LUNARG_object_tracker",
"VK_LAYER_LUNARG_core_validation",
"VK_LAYER_LUNARG_image",
"VK_LAYER_LUNARG_swapchain",
"VK_LAYER_GOOGLE_unique_objects"
};
#endif
PFN_vkCreateDebugReportCallbackEXT CreateDebugReportCallback = VK_NULL_HANDLE;
PFN_vkDestroyDebugReportCallbackEXT DestroyDebugReportCallback = VK_NULL_HANDLE;
PFN_vkDebugReportMessageEXT dbgBreakCallback = VK_NULL_HANDLE;
VkDebugReportCallbackEXT msgCallback;
VkBool32 messageCallback(
VkDebugReportFlagsEXT flags,
VkDebugReportObjectTypeEXT objType,
uint64_t srcObject,
size_t location,
int32_t msgCode,
const char* pLayerPrefix,
const char* pMsg,
void* pUserData)
{
// Select prefix depending on flags passed to the callback
// Note that multiple flags may be set for a single validation message
std::string prefix("");
// Error that may result in undefined behaviour
if (flags & VK_DEBUG_REPORT_ERROR_BIT_EXT)
{
prefix += "ERROR:";
};
// Warnings may hint at unexpected / non-spec API usage
if (flags & VK_DEBUG_REPORT_WARNING_BIT_EXT)
{
prefix += "WARNING:";
};
// May indicate sub-optimal usage of the API
if (flags & VK_DEBUG_REPORT_PERFORMANCE_WARNING_BIT_EXT)
{
prefix += "PERFORMANCE:";
};
// Informal messages that may become handy during debugging
if (flags & VK_DEBUG_REPORT_INFORMATION_BIT_EXT)
{
prefix += "INFO:";
}
// Diagnostic info from the Vulkan loader and layers
// Usually not helpful in terms of API usage, but may help to debug layer and loader problems
if (flags & VK_DEBUG_REPORT_DEBUG_BIT_EXT)
{
prefix += "DEBUG:";
}
// Display message to default output (console/logcat)
std::stringstream debugMessage;
debugMessage << prefix << " [" << pLayerPrefix << "] Code " << msgCode << " : " << pMsg;
#if defined(__ANDROID__)
if (flags & VK_DEBUG_REPORT_ERROR_BIT_EXT) {
LOGE("%s", debugMessage.str().c_str());
}
else {
LOGD("%s", debugMessage.str().c_str());
}
#else
if (flags & VK_DEBUG_REPORT_ERROR_BIT_EXT) {
std::cerr << debugMessage.str() << "\n";
}
else {
std::cout << debugMessage.str() << "\n";
}
#endif
fflush(stdout);
// The return value of this callback controls wether the Vulkan call that caused
// the validation message will be aborted or not
// We return VK_FALSE as we DON'T want Vulkan calls that cause a validation message
// (and return a VkResult) to abort
// If you instead want to have calls abort, pass in VK_TRUE and the function will
// return VK_ERROR_VALIDATION_FAILED_EXT
return VK_FALSE;
}
void setupDebugging(VkInstance instance, VkDebugReportFlagsEXT flags, VkDebugReportCallbackEXT callBack)
{
CreateDebugReportCallback = reinterpret_cast<PFN_vkCreateDebugReportCallbackEXT>(vkGetInstanceProcAddr(instance, "vkCreateDebugReportCallbackEXT"));
DestroyDebugReportCallback = reinterpret_cast<PFN_vkDestroyDebugReportCallbackEXT>(vkGetInstanceProcAddr(instance, "vkDestroyDebugReportCallbackEXT"));
dbgBreakCallback = reinterpret_cast<PFN_vkDebugReportMessageEXT>(vkGetInstanceProcAddr(instance, "vkDebugReportMessageEXT"));
VkDebugReportCallbackCreateInfoEXT dbgCreateInfo = {};
dbgCreateInfo.sType = VK_STRUCTURE_TYPE_DEBUG_REPORT_CREATE_INFO_EXT;
dbgCreateInfo.pfnCallback = (PFN_vkDebugReportCallbackEXT)messageCallback;
dbgCreateInfo.flags = flags;
VkResult err = CreateDebugReportCallback(
instance,
&dbgCreateInfo,
nullptr,
(callBack != VK_NULL_HANDLE) ? &callBack : &msgCallback);
assert(!err);
}
void freeDebugCallback(VkInstance instance)
{
if (msgCallback != VK_NULL_HANDLE)
{
DestroyDebugReportCallback(instance, msgCallback, nullptr);
}
}
}
namespace debugmarker
{
bool active = false;
PFN_vkDebugMarkerSetObjectTagEXT pfnDebugMarkerSetObjectTag = VK_NULL_HANDLE;
PFN_vkDebugMarkerSetObjectNameEXT pfnDebugMarkerSetObjectName = VK_NULL_HANDLE;
PFN_vkCmdDebugMarkerBeginEXT pfnCmdDebugMarkerBegin = VK_NULL_HANDLE;
PFN_vkCmdDebugMarkerEndEXT pfnCmdDebugMarkerEnd = VK_NULL_HANDLE;
PFN_vkCmdDebugMarkerInsertEXT pfnCmdDebugMarkerInsert = VK_NULL_HANDLE;
void setup(VkDevice device)
{
pfnDebugMarkerSetObjectTag = reinterpret_cast<PFN_vkDebugMarkerSetObjectTagEXT>(vkGetDeviceProcAddr(device, "vkDebugMarkerSetObjectTagEXT"));
pfnDebugMarkerSetObjectName = reinterpret_cast<PFN_vkDebugMarkerSetObjectNameEXT>(vkGetDeviceProcAddr(device, "vkDebugMarkerSetObjectNameEXT"));
pfnCmdDebugMarkerBegin = reinterpret_cast<PFN_vkCmdDebugMarkerBeginEXT>(vkGetDeviceProcAddr(device, "vkCmdDebugMarkerBeginEXT"));
pfnCmdDebugMarkerEnd = reinterpret_cast<PFN_vkCmdDebugMarkerEndEXT>(vkGetDeviceProcAddr(device, "vkCmdDebugMarkerEndEXT"));
pfnCmdDebugMarkerInsert = reinterpret_cast<PFN_vkCmdDebugMarkerInsertEXT>(vkGetDeviceProcAddr(device, "vkCmdDebugMarkerInsertEXT"));
// Set flag if at least one function pointer is present
active = (pfnDebugMarkerSetObjectName != VK_NULL_HANDLE);
}
void setObjectName(VkDevice device, uint64_t object, VkDebugReportObjectTypeEXT objectType, const char *name)
{
// Check for valid function pointer (may not be present if not running in a debugging application)
if (pfnDebugMarkerSetObjectName)
{
VkDebugMarkerObjectNameInfoEXT nameInfo = {};
nameInfo.sType = VK_STRUCTURE_TYPE_DEBUG_MARKER_OBJECT_NAME_INFO_EXT;
nameInfo.objectType = objectType;
nameInfo.object = object;
nameInfo.pObjectName = name;
pfnDebugMarkerSetObjectName(device, &nameInfo);
}
}
void setObjectTag(VkDevice device, uint64_t object, VkDebugReportObjectTypeEXT objectType, uint64_t name, size_t tagSize, const void* tag)
{
// Check for valid function pointer (may not be present if not running in a debugging application)
if (pfnDebugMarkerSetObjectTag)
{
VkDebugMarkerObjectTagInfoEXT tagInfo = {};
tagInfo.sType = VK_STRUCTURE_TYPE_DEBUG_MARKER_OBJECT_TAG_INFO_EXT;
tagInfo.objectType = objectType;
tagInfo.object = object;
tagInfo.tagName = name;
tagInfo.tagSize = tagSize;
tagInfo.pTag = tag;
pfnDebugMarkerSetObjectTag(device, &tagInfo);
}
}
void beginRegion(VkCommandBuffer cmdbuffer, const char* pMarkerName, glm::vec4 color)
{
// Check for valid function pointer (may not be present if not running in a debugging application)
if (pfnCmdDebugMarkerBegin)
{
VkDebugMarkerMarkerInfoEXT markerInfo = {};
markerInfo.sType = VK_STRUCTURE_TYPE_DEBUG_MARKER_MARKER_INFO_EXT;
memcpy(markerInfo.color, &color[0], sizeof(float) * 4);
markerInfo.pMarkerName = pMarkerName;
pfnCmdDebugMarkerBegin(cmdbuffer, &markerInfo);
}
}
void insert(VkCommandBuffer cmdbuffer, std::string markerName, glm::vec4 color)
{
// Check for valid function pointer (may not be present if not running in a debugging application)
if (pfnCmdDebugMarkerInsert)
{
VkDebugMarkerMarkerInfoEXT markerInfo = {};
markerInfo.sType = VK_STRUCTURE_TYPE_DEBUG_MARKER_MARKER_INFO_EXT;
memcpy(markerInfo.color, &color[0], sizeof(float) * 4);
markerInfo.pMarkerName = markerName.c_str();
pfnCmdDebugMarkerInsert(cmdbuffer, &markerInfo);
}
}
void endRegion(VkCommandBuffer cmdBuffer)
{
// Check for valid function (may not be present if not runnin in a debugging application)
if (pfnCmdDebugMarkerEnd)
{
pfnCmdDebugMarkerEnd(cmdBuffer);
}
}
void setCommandBufferName(VkDevice device, VkCommandBuffer cmdBuffer, const char * name)
{
setObjectName(device, (uint64_t)cmdBuffer, VK_DEBUG_REPORT_OBJECT_TYPE_COMMAND_BUFFER_EXT, name);
}
void setQueueName(VkDevice device, VkQueue queue, const char * name)
{
setObjectName(device, (uint64_t)queue, VK_DEBUG_REPORT_OBJECT_TYPE_QUEUE_EXT, name);
}
void setImageName(VkDevice device, VkImage image, const char * name)
{
setObjectName(device, (uint64_t)image, VK_DEBUG_REPORT_OBJECT_TYPE_IMAGE_EXT, name);
}
void setSamplerName(VkDevice device, VkSampler sampler, const char * name)
{
setObjectName(device, (uint64_t)sampler, VK_DEBUG_REPORT_OBJECT_TYPE_SAMPLER_EXT, name);
}
void setBufferName(VkDevice device, VkBuffer buffer, const char * name)
{
setObjectName(device, (uint64_t)buffer, VK_DEBUG_REPORT_OBJECT_TYPE_BUFFER_EXT, name);
}
void setDeviceMemoryName(VkDevice device, VkDeviceMemory memory, const char * name)
{
setObjectName(device, (uint64_t)memory, VK_DEBUG_REPORT_OBJECT_TYPE_DEVICE_MEMORY_EXT, name);
}
void setShaderModuleName(VkDevice device, VkShaderModule shaderModule, const char * name)
{
setObjectName(device, (uint64_t)shaderModule, VK_DEBUG_REPORT_OBJECT_TYPE_SHADER_MODULE_EXT, name);
}
void setPipelineName(VkDevice device, VkPipeline pipeline, const char * name)
{
setObjectName(device, (uint64_t)pipeline, VK_DEBUG_REPORT_OBJECT_TYPE_PIPELINE_EXT, name);
}
void setPipelineLayoutName(VkDevice device, VkPipelineLayout pipelineLayout, const char * name)
{
setObjectName(device, (uint64_t)pipelineLayout, VK_DEBUG_REPORT_OBJECT_TYPE_PIPELINE_LAYOUT_EXT, name);
}
void setRenderPassName(VkDevice device, VkRenderPass renderPass, const char * name)
{
setObjectName(device, (uint64_t)renderPass, VK_DEBUG_REPORT_OBJECT_TYPE_RENDER_PASS_EXT, name);
}
void setFramebufferName(VkDevice device, VkFramebuffer framebuffer, const char * name)
{
setObjectName(device, (uint64_t)framebuffer, VK_DEBUG_REPORT_OBJECT_TYPE_FRAMEBUFFER_EXT, name);
}
void setDescriptorSetLayoutName(VkDevice device, VkDescriptorSetLayout descriptorSetLayout, const char * name)
{
setObjectName(device, (uint64_t)descriptorSetLayout, VK_DEBUG_REPORT_OBJECT_TYPE_DESCRIPTOR_SET_LAYOUT_EXT, name);
}
void setDescriptorSetName(VkDevice device, VkDescriptorSet descriptorSet, const char * name)
{
setObjectName(device, (uint64_t)descriptorSet, VK_DEBUG_REPORT_OBJECT_TYPE_DESCRIPTOR_SET_EXT, name);
}
void setSemaphoreName(VkDevice device, VkSemaphore semaphore, const char * name)
{
setObjectName(device, (uint64_t)semaphore, VK_DEBUG_REPORT_OBJECT_TYPE_SEMAPHORE_EXT, name);
}
void setFenceName(VkDevice device, VkFence fence, const char * name)
{
setObjectName(device, (uint64_t)fence, VK_DEBUG_REPORT_OBJECT_TYPE_FENCE_EXT, name);
}
void setEventName(VkDevice device, VkEvent _event, const char * name)
{
setObjectName(device, (uint64_t)_event, VK_DEBUG_REPORT_OBJECT_TYPE_EVENT_EXT, name);
}
};
}
<commit_msg>Removed VK_LAYER_LUNARG_image (Android) [skip ci]<commit_after>/*
* Vulkan examples debug wrapper
*
* Appendix for VK_EXT_Debug_Report can be found at https://github.com/KhronosGroup/Vulkan-Docs/blob/1.0-VK_EXT_debug_report/doc/specs/vulkan/appendices/debug_report.txt
*
* Copyright (C) 2016 by Sascha Willems - www.saschawillems.de
*
* This code is licensed under the MIT license (MIT) (http://opensource.org/licenses/MIT)
*/
#include "VulkanDebug.h"
#include <iostream>
namespace vks
{
namespace debug
{
#if !defined(__ANDROID__)
// On desktop the LunarG loaders exposes a meta layer that contains all layers
int32_t validationLayerCount = 1;
const char *validationLayerNames[] = {
"VK_LAYER_LUNARG_standard_validation"
};
#else
// On Android we need to explicitly select all layers
int32_t validationLayerCount = 6;
const char *validationLayerNames[] = {
"VK_LAYER_GOOGLE_threading",
"VK_LAYER_LUNARG_parameter_validation",
"VK_LAYER_LUNARG_object_tracker",
"VK_LAYER_LUNARG_core_validation",
"VK_LAYER_LUNARG_swapchain",
"VK_LAYER_GOOGLE_unique_objects"
};
#endif
PFN_vkCreateDebugReportCallbackEXT CreateDebugReportCallback = VK_NULL_HANDLE;
PFN_vkDestroyDebugReportCallbackEXT DestroyDebugReportCallback = VK_NULL_HANDLE;
PFN_vkDebugReportMessageEXT dbgBreakCallback = VK_NULL_HANDLE;
VkDebugReportCallbackEXT msgCallback;
VkBool32 messageCallback(
VkDebugReportFlagsEXT flags,
VkDebugReportObjectTypeEXT objType,
uint64_t srcObject,
size_t location,
int32_t msgCode,
const char* pLayerPrefix,
const char* pMsg,
void* pUserData)
{
// Select prefix depending on flags passed to the callback
// Note that multiple flags may be set for a single validation message
std::string prefix("");
// Error that may result in undefined behaviour
if (flags & VK_DEBUG_REPORT_ERROR_BIT_EXT)
{
prefix += "ERROR:";
};
// Warnings may hint at unexpected / non-spec API usage
if (flags & VK_DEBUG_REPORT_WARNING_BIT_EXT)
{
prefix += "WARNING:";
};
// May indicate sub-optimal usage of the API
if (flags & VK_DEBUG_REPORT_PERFORMANCE_WARNING_BIT_EXT)
{
prefix += "PERFORMANCE:";
};
// Informal messages that may become handy during debugging
if (flags & VK_DEBUG_REPORT_INFORMATION_BIT_EXT)
{
prefix += "INFO:";
}
// Diagnostic info from the Vulkan loader and layers
// Usually not helpful in terms of API usage, but may help to debug layer and loader problems
if (flags & VK_DEBUG_REPORT_DEBUG_BIT_EXT)
{
prefix += "DEBUG:";
}
// Display message to default output (console/logcat)
std::stringstream debugMessage;
debugMessage << prefix << " [" << pLayerPrefix << "] Code " << msgCode << " : " << pMsg;
#if defined(__ANDROID__)
if (flags & VK_DEBUG_REPORT_ERROR_BIT_EXT) {
LOGE("%s", debugMessage.str().c_str());
}
else {
LOGD("%s", debugMessage.str().c_str());
}
#else
if (flags & VK_DEBUG_REPORT_ERROR_BIT_EXT) {
std::cerr << debugMessage.str() << "\n";
}
else {
std::cout << debugMessage.str() << "\n";
}
#endif
fflush(stdout);
// The return value of this callback controls wether the Vulkan call that caused
// the validation message will be aborted or not
// We return VK_FALSE as we DON'T want Vulkan calls that cause a validation message
// (and return a VkResult) to abort
// If you instead want to have calls abort, pass in VK_TRUE and the function will
// return VK_ERROR_VALIDATION_FAILED_EXT
return VK_FALSE;
}
void setupDebugging(VkInstance instance, VkDebugReportFlagsEXT flags, VkDebugReportCallbackEXT callBack)
{
CreateDebugReportCallback = reinterpret_cast<PFN_vkCreateDebugReportCallbackEXT>(vkGetInstanceProcAddr(instance, "vkCreateDebugReportCallbackEXT"));
DestroyDebugReportCallback = reinterpret_cast<PFN_vkDestroyDebugReportCallbackEXT>(vkGetInstanceProcAddr(instance, "vkDestroyDebugReportCallbackEXT"));
dbgBreakCallback = reinterpret_cast<PFN_vkDebugReportMessageEXT>(vkGetInstanceProcAddr(instance, "vkDebugReportMessageEXT"));
VkDebugReportCallbackCreateInfoEXT dbgCreateInfo = {};
dbgCreateInfo.sType = VK_STRUCTURE_TYPE_DEBUG_REPORT_CREATE_INFO_EXT;
dbgCreateInfo.pfnCallback = (PFN_vkDebugReportCallbackEXT)messageCallback;
dbgCreateInfo.flags = flags;
VkResult err = CreateDebugReportCallback(
instance,
&dbgCreateInfo,
nullptr,
(callBack != VK_NULL_HANDLE) ? &callBack : &msgCallback);
assert(!err);
}
void freeDebugCallback(VkInstance instance)
{
if (msgCallback != VK_NULL_HANDLE)
{
DestroyDebugReportCallback(instance, msgCallback, nullptr);
}
}
}
namespace debugmarker
{
bool active = false;
PFN_vkDebugMarkerSetObjectTagEXT pfnDebugMarkerSetObjectTag = VK_NULL_HANDLE;
PFN_vkDebugMarkerSetObjectNameEXT pfnDebugMarkerSetObjectName = VK_NULL_HANDLE;
PFN_vkCmdDebugMarkerBeginEXT pfnCmdDebugMarkerBegin = VK_NULL_HANDLE;
PFN_vkCmdDebugMarkerEndEXT pfnCmdDebugMarkerEnd = VK_NULL_HANDLE;
PFN_vkCmdDebugMarkerInsertEXT pfnCmdDebugMarkerInsert = VK_NULL_HANDLE;
void setup(VkDevice device)
{
pfnDebugMarkerSetObjectTag = reinterpret_cast<PFN_vkDebugMarkerSetObjectTagEXT>(vkGetDeviceProcAddr(device, "vkDebugMarkerSetObjectTagEXT"));
pfnDebugMarkerSetObjectName = reinterpret_cast<PFN_vkDebugMarkerSetObjectNameEXT>(vkGetDeviceProcAddr(device, "vkDebugMarkerSetObjectNameEXT"));
pfnCmdDebugMarkerBegin = reinterpret_cast<PFN_vkCmdDebugMarkerBeginEXT>(vkGetDeviceProcAddr(device, "vkCmdDebugMarkerBeginEXT"));
pfnCmdDebugMarkerEnd = reinterpret_cast<PFN_vkCmdDebugMarkerEndEXT>(vkGetDeviceProcAddr(device, "vkCmdDebugMarkerEndEXT"));
pfnCmdDebugMarkerInsert = reinterpret_cast<PFN_vkCmdDebugMarkerInsertEXT>(vkGetDeviceProcAddr(device, "vkCmdDebugMarkerInsertEXT"));
// Set flag if at least one function pointer is present
active = (pfnDebugMarkerSetObjectName != VK_NULL_HANDLE);
}
void setObjectName(VkDevice device, uint64_t object, VkDebugReportObjectTypeEXT objectType, const char *name)
{
// Check for valid function pointer (may not be present if not running in a debugging application)
if (pfnDebugMarkerSetObjectName)
{
VkDebugMarkerObjectNameInfoEXT nameInfo = {};
nameInfo.sType = VK_STRUCTURE_TYPE_DEBUG_MARKER_OBJECT_NAME_INFO_EXT;
nameInfo.objectType = objectType;
nameInfo.object = object;
nameInfo.pObjectName = name;
pfnDebugMarkerSetObjectName(device, &nameInfo);
}
}
void setObjectTag(VkDevice device, uint64_t object, VkDebugReportObjectTypeEXT objectType, uint64_t name, size_t tagSize, const void* tag)
{
// Check for valid function pointer (may not be present if not running in a debugging application)
if (pfnDebugMarkerSetObjectTag)
{
VkDebugMarkerObjectTagInfoEXT tagInfo = {};
tagInfo.sType = VK_STRUCTURE_TYPE_DEBUG_MARKER_OBJECT_TAG_INFO_EXT;
tagInfo.objectType = objectType;
tagInfo.object = object;
tagInfo.tagName = name;
tagInfo.tagSize = tagSize;
tagInfo.pTag = tag;
pfnDebugMarkerSetObjectTag(device, &tagInfo);
}
}
void beginRegion(VkCommandBuffer cmdbuffer, const char* pMarkerName, glm::vec4 color)
{
// Check for valid function pointer (may not be present if not running in a debugging application)
if (pfnCmdDebugMarkerBegin)
{
VkDebugMarkerMarkerInfoEXT markerInfo = {};
markerInfo.sType = VK_STRUCTURE_TYPE_DEBUG_MARKER_MARKER_INFO_EXT;
memcpy(markerInfo.color, &color[0], sizeof(float) * 4);
markerInfo.pMarkerName = pMarkerName;
pfnCmdDebugMarkerBegin(cmdbuffer, &markerInfo);
}
}
void insert(VkCommandBuffer cmdbuffer, std::string markerName, glm::vec4 color)
{
// Check for valid function pointer (may not be present if not running in a debugging application)
if (pfnCmdDebugMarkerInsert)
{
VkDebugMarkerMarkerInfoEXT markerInfo = {};
markerInfo.sType = VK_STRUCTURE_TYPE_DEBUG_MARKER_MARKER_INFO_EXT;
memcpy(markerInfo.color, &color[0], sizeof(float) * 4);
markerInfo.pMarkerName = markerName.c_str();
pfnCmdDebugMarkerInsert(cmdbuffer, &markerInfo);
}
}
void endRegion(VkCommandBuffer cmdBuffer)
{
// Check for valid function (may not be present if not runnin in a debugging application)
if (pfnCmdDebugMarkerEnd)
{
pfnCmdDebugMarkerEnd(cmdBuffer);
}
}
void setCommandBufferName(VkDevice device, VkCommandBuffer cmdBuffer, const char * name)
{
setObjectName(device, (uint64_t)cmdBuffer, VK_DEBUG_REPORT_OBJECT_TYPE_COMMAND_BUFFER_EXT, name);
}
void setQueueName(VkDevice device, VkQueue queue, const char * name)
{
setObjectName(device, (uint64_t)queue, VK_DEBUG_REPORT_OBJECT_TYPE_QUEUE_EXT, name);
}
void setImageName(VkDevice device, VkImage image, const char * name)
{
setObjectName(device, (uint64_t)image, VK_DEBUG_REPORT_OBJECT_TYPE_IMAGE_EXT, name);
}
void setSamplerName(VkDevice device, VkSampler sampler, const char * name)
{
setObjectName(device, (uint64_t)sampler, VK_DEBUG_REPORT_OBJECT_TYPE_SAMPLER_EXT, name);
}
void setBufferName(VkDevice device, VkBuffer buffer, const char * name)
{
setObjectName(device, (uint64_t)buffer, VK_DEBUG_REPORT_OBJECT_TYPE_BUFFER_EXT, name);
}
void setDeviceMemoryName(VkDevice device, VkDeviceMemory memory, const char * name)
{
setObjectName(device, (uint64_t)memory, VK_DEBUG_REPORT_OBJECT_TYPE_DEVICE_MEMORY_EXT, name);
}
void setShaderModuleName(VkDevice device, VkShaderModule shaderModule, const char * name)
{
setObjectName(device, (uint64_t)shaderModule, VK_DEBUG_REPORT_OBJECT_TYPE_SHADER_MODULE_EXT, name);
}
void setPipelineName(VkDevice device, VkPipeline pipeline, const char * name)
{
setObjectName(device, (uint64_t)pipeline, VK_DEBUG_REPORT_OBJECT_TYPE_PIPELINE_EXT, name);
}
void setPipelineLayoutName(VkDevice device, VkPipelineLayout pipelineLayout, const char * name)
{
setObjectName(device, (uint64_t)pipelineLayout, VK_DEBUG_REPORT_OBJECT_TYPE_PIPELINE_LAYOUT_EXT, name);
}
void setRenderPassName(VkDevice device, VkRenderPass renderPass, const char * name)
{
setObjectName(device, (uint64_t)renderPass, VK_DEBUG_REPORT_OBJECT_TYPE_RENDER_PASS_EXT, name);
}
void setFramebufferName(VkDevice device, VkFramebuffer framebuffer, const char * name)
{
setObjectName(device, (uint64_t)framebuffer, VK_DEBUG_REPORT_OBJECT_TYPE_FRAMEBUFFER_EXT, name);
}
void setDescriptorSetLayoutName(VkDevice device, VkDescriptorSetLayout descriptorSetLayout, const char * name)
{
setObjectName(device, (uint64_t)descriptorSetLayout, VK_DEBUG_REPORT_OBJECT_TYPE_DESCRIPTOR_SET_LAYOUT_EXT, name);
}
void setDescriptorSetName(VkDevice device, VkDescriptorSet descriptorSet, const char * name)
{
setObjectName(device, (uint64_t)descriptorSet, VK_DEBUG_REPORT_OBJECT_TYPE_DESCRIPTOR_SET_EXT, name);
}
void setSemaphoreName(VkDevice device, VkSemaphore semaphore, const char * name)
{
setObjectName(device, (uint64_t)semaphore, VK_DEBUG_REPORT_OBJECT_TYPE_SEMAPHORE_EXT, name);
}
void setFenceName(VkDevice device, VkFence fence, const char * name)
{
setObjectName(device, (uint64_t)fence, VK_DEBUG_REPORT_OBJECT_TYPE_FENCE_EXT, name);
}
void setEventName(VkDevice device, VkEvent _event, const char * name)
{
setObjectName(device, (uint64_t)_event, VK_DEBUG_REPORT_OBJECT_TYPE_EVENT_EXT, name);
}
};
}
<|endoftext|> |
<commit_before>#include <sstream>
#include <iostream>
#include <vector>
#include <cassert>
#include <cmath>
#include "config.h"
#include <boost/shared_ptr.hpp>
#include <boost/program_options.hpp>
#include <boost/program_options/variables_map.hpp>
#include "sentence_metadata.h"
#include "scorer.h"
#include "verbose.h"
#include "viterbi.h"
#include "hg.h"
#include "prob.h"
#include "kbest.h"
#include "ff_register.h"
#include "decoder.h"
#include "filelib.h"
#include "fdict.h"
#include "weights.h"
#include "sparse_vector.h"
using namespace std;
using boost::shared_ptr;
namespace po = boost::program_options;
bool invert_score;
void SanityCheck(const vector<double>& w) {
for (int i = 0; i < w.size(); ++i) {
assert(!isnan(w[i]));
assert(!isinf(w[i]));
}
}
struct FComp {
const vector<double>& w_;
FComp(const vector<double>& w) : w_(w) {}
bool operator()(int a, int b) const {
return fabs(w_[a]) > fabs(w_[b]);
}
};
void ShowLargestFeatures(const vector<double>& w) {
vector<int> fnums(w.size());
for (int i = 0; i < w.size(); ++i)
fnums[i] = i;
vector<int>::iterator mid = fnums.begin();
mid += (w.size() > 10 ? 10 : w.size());
partial_sort(fnums.begin(), mid, fnums.end(), FComp(w));
cerr << "TOP FEATURES:";
for (vector<int>::iterator i = fnums.begin(); i != mid; ++i) {
cerr << ' ' << FD::Convert(*i) << '=' << w[*i];
}
cerr << endl;
}
bool InitCommandLine(int argc, char** argv, po::variables_map* conf) {
po::options_description opts("Configuration options");
opts.add_options()
("input_weights,w",po::value<string>(),"Input feature weights file")
("source,i",po::value<string>(),"Source file for development set")
("passes,p", po::value<int>()->default_value(15), "Number of passes through the training data")
("reference,r",po::value<vector<string> >(), "[REQD] Reference translation(s) (tokenized text file)")
("mt_metric,m",po::value<string>()->default_value("ibm_bleu"), "Scoring metric (ibm_bleu, nist_bleu, koehn_bleu, ter, combi)")
("max_step_size,C", po::value<double>()->default_value(0.001), "maximum step size (C)")
("mt_metric_scale,s", po::value<double>()->default_value(1.0), "Amount to scale MT loss function by")
("k_best_size,k", po::value<int>()->default_value(250), "Size of hypothesis list to evaluate")
("decoder_config,c",po::value<string>(),"Decoder configuration file");
po::options_description clo("Command line options");
clo.add_options()
("config", po::value<string>(), "Configuration file")
("help,h", "Print this help message and exit");
po::options_description dconfig_options, dcmdline_options;
dconfig_options.add(opts);
dcmdline_options.add(opts).add(clo);
po::store(parse_command_line(argc, argv, dcmdline_options), *conf);
if (conf->count("config")) {
ifstream config((*conf)["config"].as<string>().c_str());
po::store(po::parse_config_file(config, dconfig_options), *conf);
}
po::notify(*conf);
if (conf->count("help") || !conf->count("input_weights") || !conf->count("source") || !conf->count("decoder_config") || !conf->count("reference")) {
cerr << dcmdline_options << endl;
return false;
}
return true;
}
static const double kMINUS_EPSILON = -1e-6;
struct HypothesisInfo {
SparseVector<double> features;
double mt_metric;
};
struct GoodBadOracle {
shared_ptr<HypothesisInfo> good;
shared_ptr<HypothesisInfo> bad;
};
struct TrainingObserver : public DecoderObserver {
TrainingObserver(const int k, const DocScorer& d, vector<GoodBadOracle>* o) : ds(d), oracles(*o), kbest_size(k) {}
const DocScorer& ds;
vector<GoodBadOracle>& oracles;
shared_ptr<HypothesisInfo> cur_best;
const int kbest_size;
const HypothesisInfo& GetCurrentBestHypothesis() const {
return *cur_best;
}
virtual void NotifyTranslationForest(const SentenceMetadata& smeta, Hypergraph* hg) {
UpdateOracles(smeta.GetSentenceID(), *hg);
}
shared_ptr<HypothesisInfo> MakeHypothesisInfo(const SparseVector<double>& feats, const double score) {
shared_ptr<HypothesisInfo> h(new HypothesisInfo);
h->features = feats;
h->mt_metric = score;
return h;
}
void UpdateOracles(int sent_id, const Hypergraph& forest) {
shared_ptr<HypothesisInfo>& cur_good = oracles[sent_id].good;
shared_ptr<HypothesisInfo>& cur_bad = oracles[sent_id].bad;
cur_bad.reset(); // TODO get rid of??
KBest::KBestDerivations<vector<WordID>, ESentenceTraversal> kbest(forest, kbest_size);
for (int i = 0; i < kbest_size; ++i) {
const KBest::KBestDerivations<vector<WordID>, ESentenceTraversal>::Derivation* d =
kbest.LazyKthBest(forest.nodes_.size() - 1, i);
if (!d) break;
float sentscore = ds[sent_id]->ScoreCandidate(d->yield)->ComputeScore();
if (invert_score) sentscore *= -1.0;
// cerr << TD::GetString(d->yield) << " ||| " << d->score << " ||| " << sentscore << endl;
if (i == 0)
cur_best = MakeHypothesisInfo(d->feature_values, sentscore);
if (!cur_good || sentscore > cur_good->mt_metric)
cur_good = MakeHypothesisInfo(d->feature_values, sentscore);
if (!cur_bad || sentscore < cur_bad->mt_metric)
cur_bad = MakeHypothesisInfo(d->feature_values, sentscore);
}
//cerr << "GOOD: " << cur_good->mt_metric << endl;
//cerr << " CUR: " << cur_best->mt_metric << endl;
//cerr << " BAD: " << cur_bad->mt_metric << endl;
}
};
void ReadTrainingCorpus(const string& fname, vector<string>* c) {
ReadFile rf(fname);
istream& in = *rf.stream();
string line;
while(in) {
getline(in, line);
if (!in) break;
c->push_back(line);
}
}
bool ApproxEqual(double a, double b) {
if (a == b) return true;
return (fabs(a-b)/fabs(b)) < 0.000001;
}
int main(int argc, char** argv) {
register_feature_functions();
SetSilent(true); // turn off verbose decoder output
po::variables_map conf;
if (!InitCommandLine(argc, argv, &conf)) return 1;
vector<string> corpus;
ReadTrainingCorpus(conf["source"].as<string>(), &corpus);
const string metric_name = conf["mt_metric"].as<string>();
ScoreType type = ScoreTypeFromString(metric_name);
if (type == TER) {
invert_score = true;
} else {
invert_score = false;
}
DocScorer ds(type, conf["reference"].as<vector<string> >(), "");
cerr << "Loaded " << ds.size() << " references for scoring with " << metric_name << endl;
if (ds.size() != corpus.size()) {
cerr << "Mismatched number of references (" << ds.size() << ") and sources (" << corpus.size() << ")\n";
return 1;
}
// load initial weights
Weights weights;
weights.InitFromFile(conf["input_weights"].as<string>());
SparseVector<double> lambdas;
weights.InitSparseVector(&lambdas);
ReadFile ini_rf(conf["decoder_config"].as<string>());
Decoder decoder(ini_rf.stream());
const double max_step_size = conf["max_step_size"].as<double>();
const double mt_metric_scale = conf["mt_metric_scale"].as<double>();
assert(corpus.size() > 0);
vector<GoodBadOracle> oracles(corpus.size());
TrainingObserver observer(conf["k_best_size"].as<int>(), ds, &oracles);
int cur_sent = 0;
int lcount = 0;
double tot_loss = 0;
int dots = 0;
int cur_pass = 0;
bool converged = false;
vector<double> dense_weights;
SparseVector<double> tot;
tot += lambdas; // initial weights
lcount++; // count for initial weights
int max_iteration = conf["passes"].as<int>() * corpus.size();
string msg = "# MIRA tuned weights";
while (lcount <= max_iteration) {
dense_weights.clear();
weights.InitFromVector(lambdas);
weights.InitVector(&dense_weights);
decoder.SetWeights(dense_weights);
if ((cur_sent * 40 / corpus.size()) > dots) { ++dots; cerr << '.'; }
if (corpus.size() == cur_sent) {
cur_sent = 0;
cerr << " [AVG METRIC LAST PASS=" << (tot_loss / corpus.size()) << "]\n";
tot_loss = 0;
dots = 0;
ostringstream os;
os << "weights.mira-pass" << (cur_pass < 10 ? "0" : "") << cur_pass << ".gz";
weights.WriteToFile(os.str(), true, &msg);
++cur_pass;
}
if (cur_sent == 0) { cerr << "PASS " << (lcount / corpus.size() + 1) << endl << lambdas << endl; }
decoder.SetId(cur_sent);
decoder.Decode(corpus[cur_sent], &observer); // update oracles
const HypothesisInfo& cur_hyp = observer.GetCurrentBestHypothesis();
const HypothesisInfo& cur_good = *oracles[cur_sent].good;
const HypothesisInfo& cur_bad = *oracles[cur_sent].bad;
tot_loss += cur_hyp.mt_metric;
if (!ApproxEqual(cur_hyp.mt_metric, cur_good.mt_metric)) {
const double loss = cur_bad.features.dot(dense_weights) - cur_good.features.dot(dense_weights) +
mt_metric_scale * (cur_good.mt_metric - cur_bad.mt_metric);
//cerr << "LOSS: " << loss << endl;
if (loss > 0.0) {
SparseVector<double> diff = cur_good.features;
diff -= cur_bad.features;
double step_size = loss / diff.l2norm_sq();
//cerr << loss << " " << step_size << " " << diff << endl;
if (step_size > max_step_size) step_size = max_step_size;
lambdas += (cur_good.features * step_size);
lambdas -= (cur_bad.features * step_size);
//cerr << "L: " << lambdas << endl;
}
}
tot += lambdas;
++lcount;
++cur_sent;
}
cerr << endl;
weights.WriteToFile("weights.mira-final.gz", true, &msg);
tot /= lcount;
weights.InitFromVector(tot);
msg = "# MIRA tuned weights (averaged vector)";
weights.WriteToFile("weights.mira-final-avg.gz", true, &msg);
cerr << "Optimization complete.\\AVERAGED WEIGHTS: weights.mira-final-avg.gz\n";
return 0;
}
<commit_msg>change default values<commit_after>#include <sstream>
#include <iostream>
#include <vector>
#include <cassert>
#include <cmath>
#include "config.h"
#include <boost/shared_ptr.hpp>
#include <boost/program_options.hpp>
#include <boost/program_options/variables_map.hpp>
#include "sentence_metadata.h"
#include "scorer.h"
#include "verbose.h"
#include "viterbi.h"
#include "hg.h"
#include "prob.h"
#include "kbest.h"
#include "ff_register.h"
#include "decoder.h"
#include "filelib.h"
#include "fdict.h"
#include "weights.h"
#include "sparse_vector.h"
using namespace std;
using boost::shared_ptr;
namespace po = boost::program_options;
bool invert_score;
void SanityCheck(const vector<double>& w) {
for (int i = 0; i < w.size(); ++i) {
assert(!isnan(w[i]));
assert(!isinf(w[i]));
}
}
struct FComp {
const vector<double>& w_;
FComp(const vector<double>& w) : w_(w) {}
bool operator()(int a, int b) const {
return fabs(w_[a]) > fabs(w_[b]);
}
};
void ShowLargestFeatures(const vector<double>& w) {
vector<int> fnums(w.size());
for (int i = 0; i < w.size(); ++i)
fnums[i] = i;
vector<int>::iterator mid = fnums.begin();
mid += (w.size() > 10 ? 10 : w.size());
partial_sort(fnums.begin(), mid, fnums.end(), FComp(w));
cerr << "TOP FEATURES:";
for (vector<int>::iterator i = fnums.begin(); i != mid; ++i) {
cerr << ' ' << FD::Convert(*i) << '=' << w[*i];
}
cerr << endl;
}
bool InitCommandLine(int argc, char** argv, po::variables_map* conf) {
po::options_description opts("Configuration options");
opts.add_options()
("input_weights,w",po::value<string>(),"Input feature weights file")
("source,i",po::value<string>(),"Source file for development set")
("passes,p", po::value<int>()->default_value(15), "Number of passes through the training data")
("reference,r",po::value<vector<string> >(), "[REQD] Reference translation(s) (tokenized text file)")
("mt_metric,m",po::value<string>()->default_value("ibm_bleu"), "Scoring metric (ibm_bleu, nist_bleu, koehn_bleu, ter, combi)")
("max_step_size,C", po::value<double>()->default_value(0.01), "regularization strength (C)")
("mt_metric_scale,s", po::value<double>()->default_value(1.0), "Amount to scale MT loss function by")
("k_best_size,k", po::value<int>()->default_value(250), "Size of hypothesis list to search for oracles")
("decoder_config,c",po::value<string>(),"Decoder configuration file");
po::options_description clo("Command line options");
clo.add_options()
("config", po::value<string>(), "Configuration file")
("help,h", "Print this help message and exit");
po::options_description dconfig_options, dcmdline_options;
dconfig_options.add(opts);
dcmdline_options.add(opts).add(clo);
po::store(parse_command_line(argc, argv, dcmdline_options), *conf);
if (conf->count("config")) {
ifstream config((*conf)["config"].as<string>().c_str());
po::store(po::parse_config_file(config, dconfig_options), *conf);
}
po::notify(*conf);
if (conf->count("help") || !conf->count("input_weights") || !conf->count("source") || !conf->count("decoder_config") || !conf->count("reference")) {
cerr << dcmdline_options << endl;
return false;
}
return true;
}
static const double kMINUS_EPSILON = -1e-6;
struct HypothesisInfo {
SparseVector<double> features;
double mt_metric;
};
struct GoodBadOracle {
shared_ptr<HypothesisInfo> good;
shared_ptr<HypothesisInfo> bad;
};
struct TrainingObserver : public DecoderObserver {
TrainingObserver(const int k, const DocScorer& d, vector<GoodBadOracle>* o) : ds(d), oracles(*o), kbest_size(k) {}
const DocScorer& ds;
vector<GoodBadOracle>& oracles;
shared_ptr<HypothesisInfo> cur_best;
const int kbest_size;
const HypothesisInfo& GetCurrentBestHypothesis() const {
return *cur_best;
}
virtual void NotifyTranslationForest(const SentenceMetadata& smeta, Hypergraph* hg) {
UpdateOracles(smeta.GetSentenceID(), *hg);
}
shared_ptr<HypothesisInfo> MakeHypothesisInfo(const SparseVector<double>& feats, const double score) {
shared_ptr<HypothesisInfo> h(new HypothesisInfo);
h->features = feats;
h->mt_metric = score;
return h;
}
void UpdateOracles(int sent_id, const Hypergraph& forest) {
shared_ptr<HypothesisInfo>& cur_good = oracles[sent_id].good;
shared_ptr<HypothesisInfo>& cur_bad = oracles[sent_id].bad;
cur_bad.reset(); // TODO get rid of??
KBest::KBestDerivations<vector<WordID>, ESentenceTraversal> kbest(forest, kbest_size);
for (int i = 0; i < kbest_size; ++i) {
const KBest::KBestDerivations<vector<WordID>, ESentenceTraversal>::Derivation* d =
kbest.LazyKthBest(forest.nodes_.size() - 1, i);
if (!d) break;
float sentscore = ds[sent_id]->ScoreCandidate(d->yield)->ComputeScore();
if (invert_score) sentscore *= -1.0;
// cerr << TD::GetString(d->yield) << " ||| " << d->score << " ||| " << sentscore << endl;
if (i == 0)
cur_best = MakeHypothesisInfo(d->feature_values, sentscore);
if (!cur_good || sentscore > cur_good->mt_metric)
cur_good = MakeHypothesisInfo(d->feature_values, sentscore);
if (!cur_bad || sentscore < cur_bad->mt_metric)
cur_bad = MakeHypothesisInfo(d->feature_values, sentscore);
}
//cerr << "GOOD: " << cur_good->mt_metric << endl;
//cerr << " CUR: " << cur_best->mt_metric << endl;
//cerr << " BAD: " << cur_bad->mt_metric << endl;
}
};
void ReadTrainingCorpus(const string& fname, vector<string>* c) {
ReadFile rf(fname);
istream& in = *rf.stream();
string line;
while(in) {
getline(in, line);
if (!in) break;
c->push_back(line);
}
}
bool ApproxEqual(double a, double b) {
if (a == b) return true;
return (fabs(a-b)/fabs(b)) < 0.000001;
}
int main(int argc, char** argv) {
register_feature_functions();
SetSilent(true); // turn off verbose decoder output
po::variables_map conf;
if (!InitCommandLine(argc, argv, &conf)) return 1;
vector<string> corpus;
ReadTrainingCorpus(conf["source"].as<string>(), &corpus);
const string metric_name = conf["mt_metric"].as<string>();
ScoreType type = ScoreTypeFromString(metric_name);
if (type == TER) {
invert_score = true;
} else {
invert_score = false;
}
DocScorer ds(type, conf["reference"].as<vector<string> >(), "");
cerr << "Loaded " << ds.size() << " references for scoring with " << metric_name << endl;
if (ds.size() != corpus.size()) {
cerr << "Mismatched number of references (" << ds.size() << ") and sources (" << corpus.size() << ")\n";
return 1;
}
// load initial weights
Weights weights;
weights.InitFromFile(conf["input_weights"].as<string>());
SparseVector<double> lambdas;
weights.InitSparseVector(&lambdas);
ReadFile ini_rf(conf["decoder_config"].as<string>());
Decoder decoder(ini_rf.stream());
const double max_step_size = conf["max_step_size"].as<double>();
const double mt_metric_scale = conf["mt_metric_scale"].as<double>();
assert(corpus.size() > 0);
vector<GoodBadOracle> oracles(corpus.size());
TrainingObserver observer(conf["k_best_size"].as<int>(), ds, &oracles);
int cur_sent = 0;
int lcount = 0;
double tot_loss = 0;
int dots = 0;
int cur_pass = 0;
vector<double> dense_weights;
SparseVector<double> tot;
tot += lambdas; // initial weights
lcount++; // count for initial weights
int max_iteration = conf["passes"].as<int>() * corpus.size();
string msg = "# MIRA tuned weights";
while (lcount <= max_iteration) {
dense_weights.clear();
weights.InitFromVector(lambdas);
weights.InitVector(&dense_weights);
decoder.SetWeights(dense_weights);
if ((cur_sent * 40 / corpus.size()) > dots) { ++dots; cerr << '.'; }
if (corpus.size() == cur_sent) {
cur_sent = 0;
cerr << " [AVG METRIC LAST PASS=" << (tot_loss / corpus.size()) << "]\n";
tot_loss = 0;
dots = 0;
ostringstream os;
os << "weights.mira-pass" << (cur_pass < 10 ? "0" : "") << cur_pass << ".gz";
weights.WriteToFile(os.str(), true, &msg);
++cur_pass;
}
if (cur_sent == 0) { cerr << "PASS " << (lcount / corpus.size() + 1) << endl << lambdas << endl; }
decoder.SetId(cur_sent);
decoder.Decode(corpus[cur_sent], &observer); // update oracles
const HypothesisInfo& cur_hyp = observer.GetCurrentBestHypothesis();
const HypothesisInfo& cur_good = *oracles[cur_sent].good;
const HypothesisInfo& cur_bad = *oracles[cur_sent].bad;
tot_loss += cur_hyp.mt_metric;
if (!ApproxEqual(cur_hyp.mt_metric, cur_good.mt_metric)) {
const double loss = cur_bad.features.dot(dense_weights) - cur_good.features.dot(dense_weights) +
mt_metric_scale * (cur_good.mt_metric - cur_bad.mt_metric);
//cerr << "LOSS: " << loss << endl;
if (loss > 0.0) {
SparseVector<double> diff = cur_good.features;
diff -= cur_bad.features;
double step_size = loss / diff.l2norm_sq();
//cerr << loss << " " << step_size << " " << diff << endl;
if (step_size > max_step_size) step_size = max_step_size;
lambdas += (cur_good.features * step_size);
lambdas -= (cur_bad.features * step_size);
//cerr << "L: " << lambdas << endl;
}
}
tot += lambdas;
++lcount;
++cur_sent;
}
cerr << endl;
weights.WriteToFile("weights.mira-final.gz", true, &msg);
tot /= lcount;
weights.InitFromVector(tot);
msg = "# MIRA tuned weights (averaged vector)";
weights.WriteToFile("weights.mira-final-avg.gz", true, &msg);
cerr << "Optimization complete.\\AVERAGED WEIGHTS: weights.mira-final-avg.gz\n";
return 0;
}
<|endoftext|> |
<commit_before>#include <signal.h> // for signal, SIGINT
#include <zmq.hpp>
#include <uuid.h>
#include <ctime>
#include "util.h"
#include "timesync.h"
#include "h5analogwriter.h"
bool s_interrupted = false;
static void s_signal_handler(int)
{
s_interrupted = true;
printf("\n");
}
static void s_catch_signals(void)
{
struct sigaction action;
action.sa_handler = s_signal_handler;
action.sa_flags = 0;
sigemptyset(&action.sa_mask);
sigaction(SIGINT, &action, NULL);
sigaction(SIGQUIT, &action, NULL);
sigaction(SIGTERM, &action, NULL);
}
int main(int argc, char *argv[])
{
// h5bbsave [zmq_sub] [filename]
if (argc < 3) {
printf("\nh5bbsave - save broadband data to NWB (HDF5)\n");
printf("usage: h5bbsave [zmq_sub] [filename]\n\n");
return 1;
}
std::string zin = argv[1];
std::string fn = argv[2];
printf("ZMQ SUB: %s\n", zin.c_str());
printf("Filename: %s\n", fn.c_str());
printf("\n");
s_catch_signals();
TimeSyncClient *tsc = new TimeSyncClient(); // translates tk and ts
H5AnalogWriter h5;
zmq::context_t zcontext(1); // single zmq thread
zmq::socket_t po8e_query_sock(zcontext, ZMQ_REQ);
po8e_query_sock.connect("ipc:///tmp/po8e-query.zmq");
u64 nnc; // num neural channels
zmq::message_t msg(3);
memcpy(msg.data(), "NNC", 3);
po8e_query_sock.send(msg);
msg.rebuild();
try {
po8e_query_sock.recv(&msg);
} catch (zmq::error_t &e) {
exit(1);
}
memcpy(&nnc, (u64 *)msg.data(), sizeof(u64));
std::vector <std::string> names;
for (u64 ch=0; ch<nnc; ch++) {
// NC : X : NAME
msg.rebuild(2);
memcpy(msg.data(), "NC", 2);
po8e_query_sock.send(msg, ZMQ_SNDMORE);
msg.rebuild(sizeof(u64));
memcpy(msg.data(), &ch, sizeof(u64));
po8e_query_sock.send(msg, ZMQ_SNDMORE);
msg.rebuild(4);
memcpy(msg.data(), "NAME", 4);
po8e_query_sock.send(msg);
msg.rebuild();
po8e_query_sock.recv(&msg);
names.push_back(std::string((const char *)msg.data(), msg.size()));
}
size_t max_str = 0;
for (auto &x : names) {
max_str = max_str > x.size() ? max_str : x.size();
}
auto name = new char[max_str*names.size()];
for (size_t i=0; i<names.size(); i++) {
strncpy(&name[i*max_str], names[i].c_str(), names[i].size());
}
uuid_t u;
uuid_generate(u);
char uu[37];
uuid_unparse(u, uu);
time_t t_create;
time(&t_create);
char create_date[sizeof("YYYY-MM-DDTHH:MM:SSZ")];
strftime(create_date, sizeof(create_date), "%FT%TZ", gmtime(&t_create));
h5.open(fn.c_str(), nnc);
h5.setVersion();
h5.setUUID(uu);
h5.setFileCreateDate(create_date);
h5.setSessionDescription("broadband data");
h5.setMetaData(1.0/3276700, name, max_str);
delete[] name;
zmq::socket_t socket_in(zcontext, ZMQ_SUB);
socket_in.connect(zin.c_str());
socket_in.setsockopt(ZMQ_SUBSCRIBE, "", 0); // subscribe to everything
// init poll set
zmq::pollitem_t items [] = {
{ socket_in, 0, ZMQ_POLLIN, 0 }
};
int waiter = 0;
int counter = 0;
std::vector<const char *> spinner;
spinner.emplace_back(">>> >>>");
spinner.emplace_back(" >>> >>");
spinner.emplace_back(" >>> >");
spinner.emplace_back(" >>> ");
spinner.emplace_back(" >>> ");
spinner.emplace_back("> >>> ");
spinner.emplace_back(">> >>> ");
size_t zin_n = zin.find_last_of("/");
while (!s_interrupted) {
try {
zmq::poll(&items[0], 1, -1); // -1 means block
} catch (zmq::error_t &e) {}
if (items[0].revents & ZMQ_POLLIN) {
socket_in.recv(&msg);
char *ptr = (char *)msg.data();
u64 nc, ns;
// parse message
memcpy(&nc, ptr+0, sizeof(u64));
memcpy(&ns, ptr+8, sizeof(u64));
auto tk = new i64[ns];
auto ts = new double[ns];
memcpy(tk, ptr+16, sizeof(i64));
ts[0] = tsc->getTime(tk[0]);
for (size_t i=1; i < ns; i++) {
tk[i] = tk[i-1] + 1;
ts[i] = tsc->getTime(tk[i]);
}
auto f = new float[nc*ns];
memcpy(f, ptr+24, nc*ns*sizeof(float));
auto x = new i16[nc*ns];
for (size_t i=0; i<nc; i++) {
for (size_t k=0; k<ns; k++) {
// note that we transpose on the fly here to NWB format
x[k*nc+i] = (i16)(f[i*ns+k] * 3276700 / 1e6); // pack
}
}
delete[] f;
h5.write(nc, ns, tk, ts, x); // frees memory when done
if (waiter % 200 == 0) {
time_t now;
time(&now);
double sec = difftime(now, t_create);
int min = sec / 60;
int hr = min / 60;
printf(" [%s]%s[%s] (%02d:%02d:%02d)\r",
zin.substr(zin_n+1).c_str(),
spinner[counter % spinner.size()],
fn.c_str(),
hr,
min % 60,
int(sec) % 60);
fflush(stdout);
counter++;
}
waiter++;
}
}
h5.close();
delete tsc;
}<commit_msg>need to get h5bbsave on the c api<commit_after>#include <signal.h> // for signal, SIGINT
#include <zmq.h>
#include "zmq_packet.h"
#include <uuid.h>
#include <ctime>
#include "util.h"
#include "timesync.h"
#include "h5analogwriter.h"
bool s_interrupted = false;
static void s_signal_handler(int)
{
s_interrupted = true;
printf("\n");
}
static void s_catch_signals(void)
{
struct sigaction action;
action.sa_handler = s_signal_handler;
action.sa_flags = 0;
sigemptyset(&action.sa_mask);
sigaction(SIGINT, &action, NULL);
sigaction(SIGQUIT, &action, NULL);
sigaction(SIGTERM, &action, NULL);
}
int main(int argc, char *argv[])
{
// h5bbsave [zmq_sub] [filename]
if (argc < 3) {
printf("\nh5bbsave - save broadband data to NWB (HDF5)\n");
printf("usage: h5bbsave [zmq_sub] [filename]\n\n");
return 1;
}
std::string zin = argv[1];
std::string fn = argv[2];
printf("ZMQ SUB: %s\n", zin.c_str());
printf("Filename: %s\n", fn.c_str());
printf("\n");
s_catch_signals();
TimeSyncClient *tsc = new TimeSyncClient(); // translates tk and ts
H5AnalogWriter h5;
zmq::context_t zcontext(1); // single zmq thread
zmq::socket_t po8e_query_sock(zcontext, ZMQ_REQ);
po8e_query_sock.connect("ipc:///tmp/po8e-query.zmq");
u64 nnc; // num neural channels
zmq::message_t msg(3);
memcpy(msg.data(), "NNC", 3);
po8e_query_sock.send(msg);
msg.rebuild();
try {
po8e_query_sock.recv(&msg);
} catch (zmq::error_t &e) {
exit(1);
}
memcpy(&nnc, (u64 *)msg.data(), sizeof(u64));
std::vector <std::string> names;
for (u64 ch=0; ch<nnc; ch++) {
// NC : X : NAME
msg.rebuild(2);
memcpy(msg.data(), "NC", 2);
po8e_query_sock.send(msg, ZMQ_SNDMORE);
msg.rebuild(sizeof(u64));
memcpy(msg.data(), &ch, sizeof(u64));
po8e_query_sock.send(msg, ZMQ_SNDMORE);
msg.rebuild(4);
memcpy(msg.data(), "NAME", 4);
po8e_query_sock.send(msg);
msg.rebuild();
po8e_query_sock.recv(&msg);
names.push_back(std::string((const char *)msg.data(), msg.size()));
}
size_t max_str = 0;
for (auto &x : names) {
max_str = max_str > x.size() ? max_str : x.size();
}
auto name = new char[max_str*names.size()];
for (size_t i=0; i<names.size(); i++) {
strncpy(&name[i*max_str], names[i].c_str(), names[i].size());
}
uuid_t u;
uuid_generate(u);
char uu[37];
uuid_unparse(u, uu);
time_t t_create;
time(&t_create);
char create_date[sizeof("YYYY-MM-DDTHH:MM:SSZ")];
strftime(create_date, sizeof(create_date), "%FT%TZ", gmtime(&t_create));
h5.open(fn.c_str(), nnc);
h5.setVersion();
h5.setUUID(uu);
h5.setFileCreateDate(create_date);
h5.setSessionDescription("broadband data");
h5.setMetaData(1.0/3276700, name, max_str);
delete[] name;
zmq::socket_t socket_in(zcontext, ZMQ_SUB);
socket_in.connect(zin.c_str());
socket_in.setsockopt(ZMQ_SUBSCRIBE, "", 0); // subscribe to everything
// init poll set
zmq::pollitem_t items [] = {
{ socket_in, 0, ZMQ_POLLIN, 0 }
};
int waiter = 0;
int counter = 0;
std::vector<const char *> spinner;
spinner.emplace_back(">>> >>>");
spinner.emplace_back(" >>> >>");
spinner.emplace_back(" >>> >");
spinner.emplace_back(" >>> ");
spinner.emplace_back(" >>> ");
spinner.emplace_back("> >>> ");
spinner.emplace_back(">> >>> ");
size_t zin_n = zin.find_last_of("/");
while (!s_interrupted) {
try {
zmq::poll(&items[0], 1, -1); // -1 means block
} catch (zmq::error_t &e) {}
if (items[0].revents & ZMQ_POLLIN) {
socket_in.recv(&msg);
char *ptr = (char *)msg.data();
u64 nc, ns;
// parse message
memcpy(&nc, ptr+0, sizeof(u64));
memcpy(&ns, ptr+8, sizeof(u64));
auto tk = new i64[ns];
auto ts = new double[ns];
memcpy(tk, ptr+16, sizeof(i64));
ts[0] = tsc->getTime(tk[0]);
for (size_t i=1; i < ns; i++) {
tk[i] = tk[i-1] + 1;
ts[i] = tsc->getTime(tk[i]);
}
auto f = new float[nc*ns];
memcpy(f, ptr+24, nc*ns*sizeof(float));
auto x = new i16[nc*ns];
for (size_t i=0; i<nc; i++) {
for (size_t k=0; k<ns; k++) {
// note that we transpose on the fly here to NWB format
x[k*nc+i] = (i16)(f[i*ns+k] * 3276700 / 1e6); // pack
}
}
delete[] f;
h5.write(nc, ns, tk, ts, x); // frees memory when done
if (waiter % 200 == 0) {
time_t now;
time(&now);
double sec = difftime(now, t_create);
int min = sec / 60;
int hr = min / 60;
printf(" [%s]%s[%s] (%02d:%02d:%02d)\r",
zin.substr(zin_n+1).c_str(),
spinner[counter % spinner.size()],
fn.c_str(),
hr,
min % 60,
int(sec) % 60);
fflush(stdout);
counter++;
}
waiter++;
}
}
h5.close();
delete tsc;
}<|endoftext|> |
<commit_before>#include <array>
#include "h5writer.h"
H5Writer::H5Writer()
{
m_enabled = false;
m_h5file = 0;
m_fn.assign("");
m_w = NULL;
}
H5Writer::~H5Writer()
{
close();
}
bool H5Writer::open(const char *fn)
{
if (isEnabled()) {
return false;
}
// Create a new file using default properties.
m_h5file = H5Fcreate(fn, H5F_ACC_TRUNC, H5P_DEFAULT, H5P_DEFAULT);
if (m_h5file < 0) {
return false;
}
m_fn.assign(fn);
fprintf(stdout,"%s: started logging to %s.\n", name(), fn);
// we intentionally don't enable here: rather, enable in the subclasses
return true;
}
bool H5Writer::close()
{
if (isEnabled()) { // subclass should have disabled already honestly.
disable();
fprintf(stdout,"%s: stopped logging to file\n", name());
m_fn.clear();
}
if (m_h5file) {
H5Fclose(m_h5file);
m_h5file = 0;
}
return true;
}
bool H5Writer::isEnabled()
{
return m_enabled;
}
void H5Writer::enable()
{
m_enabled = true;
}
void H5Writer::disable()
{
m_enabled = false;
}
size_t H5Writer::bytes()
{
return 0;
}
string H5Writer::filename()
{
return m_fn;
}
void H5Writer::registerWidget(GtkWidget *w)
{
m_w = w;
}
void H5Writer::draw()
{
if (isEnabled()) {
std::array<std::string, 5> u { {"B", "kB", "MB", "GB", "TB"} };
int i = 0;
double b = bytes();
while (b > 1e3) {
b /= 1e3;
i++;
}
size_t n = filename().find_last_of("/");
char str[256];
snprintf(str, 256, "%s: %.2f %s",
filename().substr(n+1).c_str(), b, u[i].c_str());
gtk_label_set_text(GTK_LABEL(m_w), str);
}
}
<commit_msg>make h5writer print bytes more efficiently<commit_after>#include <array>
#include "h5writer.h"
H5Writer::H5Writer()
{
m_enabled = false;
m_h5file = 0;
m_fn.assign("");
m_w = NULL;
}
H5Writer::~H5Writer()
{
close();
}
bool H5Writer::open(const char *fn)
{
if (isEnabled()) {
return false;
}
// Create a new file using default properties.
m_h5file = H5Fcreate(fn, H5F_ACC_TRUNC, H5P_DEFAULT, H5P_DEFAULT);
if (m_h5file < 0) {
return false;
}
m_fn.assign(fn);
fprintf(stdout,"%s: started logging to %s.\n", name(), fn);
// we intentionally don't enable here: rather, enable in the subclasses
return true;
}
bool H5Writer::close()
{
if (isEnabled()) { // subclass should have disabled already honestly.
disable();
fprintf(stdout,"%s: stopped logging to file\n", name());
m_fn.clear();
}
if (m_h5file) {
H5Fclose(m_h5file);
m_h5file = 0;
}
return true;
}
bool H5Writer::isEnabled()
{
return m_enabled;
}
void H5Writer::enable()
{
m_enabled = true;
}
void H5Writer::disable()
{
m_enabled = false;
}
size_t H5Writer::bytes()
{
return 0;
}
string H5Writer::filename()
{
return m_fn;
}
void H5Writer::registerWidget(GtkWidget *w)
{
m_w = w;
}
void H5Writer::draw()
{
if (isEnabled()) {
size_t n = filename().find_last_of("/");
char str[256];
double b = bytes() / 1e6;
if (b >= 1e3) {
b /= 1e3;
snprintf(str, 256, "%s: %.2f GB",
filename().substr(n+1).c_str(), b);
} else {
snprintf(str, 256, "%s: %.2f MB",
filename().substr(n+1).c_str(), b);
}
gtk_label_set_text(GTK_LABEL(m_w), str);
}
}
<|endoftext|> |
<commit_before>/*
For more information, please see: http://software.sci.utah.edu
The MIT License
Copyright (c) 2012 Scientific Computing and Imaging Institute,
University of Utah.
License for the specific language governing rights and limitations under
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.
*/
#include <Modules/Visualization/ShowMesh.h>
#include <Core/Datatypes/Mesh/Mesh.h>
#include <Core/Datatypes/Mesh/MeshFacade.h>
#include <Core/Datatypes/Geometry.h>
#include <boost/foreach.hpp>
using namespace SCIRun::Modules::Visualization;
using namespace SCIRun::Core::Datatypes;
using namespace SCIRun::Dataflow::Networks;
using namespace SCIRun::Core::Algorithms;
ShowMeshModule::ShowMeshModule() : Module(ModuleLookupInfo("ShowMesh", "Visualization", "SCIRun"))
{
get_state()->setValue(ShowEdges, true);
get_state()->setValue(ShowFaces, true);
}
void ShowMeshModule::execute()
{
auto mesh = getRequiredInput(Mesh);
MeshFacadeHandle facade(mesh->getFacade());
/// \todo Determine a better way of handling all of the various object state.
bool showEdges = get_state()->getValue(ShowEdges).getBool();
bool showFaces = get_state()->getValue(ShowFaces).getBool();
bool nodeTransparency = get_state()->getValue(NodeTransparency).getBool();
bool edgeTransparency = get_state()->getValue(EdgeTransparency).getBool();
bool faceTransparency = get_state()->getValue(FaceTransparency).getBool();
GeometryHandle geom(new GeometryObject(mesh));
geom->objectName = get_id();
/// \todo Split the mesh into chunks of about ~32,000 vertices. May be able to
/// eek out better coherency and use a 16 bit index buffer instead of
/// a 32 bit index buffer.
// We are going to get no lighting in this first pass. The unfortunate reality
// is that I cannot get access to face normals in vertex shaders based off of
// the winding orders of the incoming geometry.
// Allocate memory for vertex buffer (*NOT* the index buffer, which is a
// a function of the number of faces). Only allocating enough memory to hold
// points associated with the faces.
// Edges *and* faces should use the same vbo!
std::shared_ptr<std::vector<uint8_t>> rawVBO(new std::vector<uint8_t>());
size_t vboSize = sizeof(float) * 3 * facade->numNodes();
rawVBO->resize(vboSize); // linear complexity.
float* vbo = reinterpret_cast<float*>(&(*rawVBO)[0]); // Remember, standard guarantees that vectors are contiguous in memory.
// Add shared VBO to the geometry object.
std::string primVBOName = "primaryVBO";
std::vector<std::string> attribs; ///< \todo Switch to initializer lists when msvc supports it.
attribs.push_back("aPos"); ///< \todo Find a good place to pull these names from.
geom->mVBOs.emplace_back(GeometryObject::SpireVBO(primVBOName, attribs, rawVBO));
// Build index buffer. Based off of the node indices that came out of old
// SCIRun, TnL cache coherency will be poor. Maybe room for improvement later.
size_t i = 0;
BOOST_FOREACH(const NodeInfo& node, facade->nodes())
{
vbo[i+0] = node.point().x(); vbo[i+1] = node.point().y(); vbo[i+2] = node.point().z();
i+=3;
}
// Build the edges
size_t iboEdgesSize = sizeof(uint32_t) * facade->numEdges() * 2;
uint32_t* iboEdges = nullptr;
if (showEdges)
{
std::shared_ptr<std::vector<uint8_t>> rawIBO(new std::vector<uint8_t>());
//rawIBO->reserve(iboEdgesSize);
rawIBO->resize(iboEdgesSize); // Linear in complexity... If we need more performance,
// use malloc to generate buffer and then vector::assign.
iboEdges = reinterpret_cast<uint32_t*>(&(*rawIBO)[0]);
i = 0;
BOOST_FOREACH(const EdgeInfo& edge, facade->edges())
{
// There should *only* be two indicies (linestrip would be better...)
VirtualMesh::Node::array_type nodes = edge.nodeIndices();
assert(nodes.size() == 2);
// Winding order looks good from tests.
// Render two triangles.
iboEdges[i] = nodes[0]; iboEdges[i+1] = nodes[1];
i += 2;
}
// Add IBO for the faces.
std::string edgesIBOName = "edgesIBO";
geom->mIBOs.emplace_back(GeometryObject::SpireIBO(edgesIBOName, sizeof(uint32_t), rawIBO));
// Build pass for the faces.
/// \todo Find an appropriate place to put program names like UniformColor.
GeometryObject::SpirePass pass =
GeometryObject::SpirePass("edgesPass", primVBOName,
edgesIBOName, "UniformColor",
Spire::StuInterface::LINES);
// Add appropriate uniforms to the pass (in this case, uColor).
if (edgeTransparency)
pass.addUniform("uColor", Spire::V4(0.6f, 0.6f, 0.6f, 0.5f));
else
pass.addUniform("uColor", Spire::V4(0.6f, 0.6f, 0.6f, 1.0f));
geom->mPasses.emplace_back(pass);
}
//mStuInterface->addPassUniform(obj1, pass1, "uColor", V4(1.0f, 0.0f, 0.0f, 1.0f));
// Build the faces.
size_t iboFacesSize = sizeof(uint32_t) * facade->numFaces() * 6;
uint32_t* iboFaces = nullptr;
if (showFaces)
{
std::shared_ptr<std::vector<uint8_t>> rawIBO(new std::vector<uint8_t>());
//rawIBO->reserve(iboFacesSize);
rawIBO->resize(iboFacesSize); // Linear in complexity... If we need more performance,
// use malloc to generate buffer and then vector::assign.
iboFaces = reinterpret_cast<uint32_t*>(&(*rawIBO)[0]);
i = 0;
BOOST_FOREACH(const FaceInfo& face, facade->faces())
{
// There should *only* be four indicies.
VirtualMesh::Node::array_type nodes = face.nodeIndices();
assert(nodes.size() == 4);
// Winding order looks good from tests.
// Render two triangles.
iboFaces[i ] = nodes[0]; iboFaces[i+1] = nodes[1]; iboFaces[i+2] = nodes[2];
iboFaces[i+3] = nodes[0]; iboFaces[i+4] = nodes[2]; iboFaces[i+5] = nodes[3];
i += 6;
}
// Add IBO for the faces.
std::string facesIBOName = "facesIBO";
geom->mIBOs.emplace_back(GeometryObject::SpireIBO(facesIBOName, sizeof(uint32_t), rawIBO));
// Build pass for the faces.
/// \todo Find an appropriate place to put program names like UniformColor.
GeometryObject::SpirePass pass =
GeometryObject::SpirePass("facesPass", primVBOName,
facesIBOName, "UniformColor",
Spire::StuInterface::TRIANGLES);
if (faceTransparency)
{
pass.addUniform("uColor", Spire::V4(1.0f, 1.0f, 1.0f, 0.2f));
// Modify the GPU state to disable ztesting.
//Spire::GPUState state;
//state.mDepthTestEnable = false;
//pass.addGPUState(state);
}
else
{
pass.addUniform("uColor", Spire::V4(0.3f, 0.3f, 0.3f, 1.0f));
}
geom->mPasses.emplace_back(pass);
}
sendOutput(SceneGraph, geom);
}
AlgorithmParameterName ShowMeshModule::ShowEdges("Show edges");
AlgorithmParameterName ShowMeshModule::ShowFaces("Show faces");
AlgorithmParameterName ShowMeshModule::NodeTransparency("Node Transparency");
AlgorithmParameterName ShowMeshModule::EdgeTransparency("Edge Transparency");
AlgorithmParameterName ShowMeshModule::FaceTransparency("Face Transparency");
<commit_msg>Fixed typo.<commit_after>/*
For more information, please see: http://software.sci.utah.edu
The MIT License
Copyright (c) 2012 Scientific Computing and Imaging Institute,
University of Utah.
License for the specific language governing rights and limitations under
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.
*/
#include <Modules/Visualization/ShowMesh.h>
#include <Core/Datatypes/Mesh/Mesh.h>
#include <Core/Datatypes/Mesh/MeshFacade.h>
#include <Core/Datatypes/Geometry.h>
#include <boost/foreach.hpp>
using namespace SCIRun::Modules::Visualization;
using namespace SCIRun::Core::Datatypes;
using namespace SCIRun::Dataflow::Networks;
using namespace SCIRun::Core::Algorithms;
ShowMeshModule::ShowMeshModule() : Module(ModuleLookupInfo("ShowMesh", "Visualization", "SCIRun"))
{
get_state()->setValue(ShowEdges, true);
get_state()->setValue(ShowFaces, true);
}
void ShowMeshModule::execute()
{
auto mesh = getRequiredInput(Mesh);
MeshFacadeHandle facade(mesh->getFacade());
/// \todo Determine a better way of handling all of the various object state.
bool showEdges = get_state()->getValue(ShowEdges).getBool();
bool showFaces = get_state()->getValue(ShowFaces).getBool();
bool nodeTransparency = get_state()->getValue(NodeTransparency).getBool();
bool edgeTransparency = get_state()->getValue(EdgeTransparency).getBool();
bool faceTransparency = get_state()->getValue(FaceTransparency).getBool();
GeometryHandle geom(new GeometryObject(mesh));
geom->objectName = get_id();
/// \todo Split the mesh into chunks of about ~32,000 vertices. May be able to
/// eek out better coherency and use a 16 bit index buffer instead of
/// a 32 bit index buffer.
// We are going to get no lighting in this first pass. The unfortunate reality
// is that I cannot get access to face normals in vertex shaders based off of
// the winding orders of the incoming geometry.
// Allocate memory for vertex buffer (*NOT* the index buffer, which is a
// a function of the number of faces). Only allocating enough memory to hold
// points associated with the faces.
// Edges *and* faces should use the same vbo!
std::shared_ptr<std::vector<uint8_t>> rawVBO(new std::vector<uint8_t>());
size_t vboSize = sizeof(float) * 3 * facade->numNodes();
rawVBO->resize(vboSize); // linear complexity.
float* vbo = reinterpret_cast<float*>(&(*rawVBO)[0]); // Remember, standard guarantees that vectors are contiguous in memory.
// Add shared VBO to the geometry object.
std::string primVBOName = "primaryVBO";
std::vector<std::string> attribs; ///< \todo Switch to initializer lists when msvc supports it.
attribs.push_back("aPos"); ///< \todo Find a good place to pull these names from.
geom->mVBOs.emplace_back(GeometryObject::SpireVBO(primVBOName, attribs, rawVBO));
// Build index buffer. Based off of the node indices that came out of old
// SCIRun, TnL cache coherency will be poor. Maybe room for improvement later.
size_t i = 0;
BOOST_FOREACH(const NodeInfo& node, facade->nodes())
{
vbo[i+0] = node.point().x(); vbo[i+1] = node.point().y(); vbo[i+2] = node.point().z();
i+=3;
}
// Build the edges
size_t iboEdgesSize = sizeof(uint32_t) * facade->numEdges() * 2;
uint32_t* iboEdges = nullptr;
if (showEdges)
{
std::shared_ptr<std::vector<uint8_t>> rawIBO(new std::vector<uint8_t>());
//rawIBO->reserve(iboEdgesSize);
rawIBO->resize(iboEdgesSize); // Linear in complexity... If we need more performance,
// use malloc to generate buffer and then vector::assign.
iboEdges = reinterpret_cast<uint32_t*>(&(*rawIBO)[0]);
i = 0;
BOOST_FOREACH(const EdgeInfo& edge, facade->edges())
{
// There should *only* be two indicies (linestrip would be better...)
VirtualMesh::Node::array_type nodes = edge.nodeIndices();
assert(nodes.size() == 2);
// Winding order looks good from tests.
// Render two triangles.
iboEdges[i] = nodes[0]; iboEdges[i+1] = nodes[1];
i += 2;
}
// Add IBO for the faces.
std::string edgesIBOName = "edgesIBO";
geom->mIBOs.emplace_back(GeometryObject::SpireIBO(edgesIBOName, sizeof(uint32_t), rawIBO));
// Build pass for the faces.
/// \todo Find an appropriate place to put program names like UniformColor.
GeometryObject::SpirePass pass =
GeometryObject::SpirePass("edgesPass", primVBOName,
edgesIBOName, "UniformColor",
Spire::StuInterface::LINES);
// Add appropriate uniforms to the pass (in this case, uColor).
if (edgeTransparency)
pass.addUniform("uColor", Spire::V4(0.6f, 0.6f, 0.6f, 0.5f));
else
pass.addUniform("uColor", Spire::V4(0.6f, 0.6f, 0.6f, 1.0f));
geom->mPasses.emplace_back(pass);
}
//mStuInterface->addPassUniform(obj1, pass1, "uColor", V4(1.0f, 0.0f, 0.0f, 1.0f));
// Build the faces.
size_t iboFacesSize = sizeof(uint32_t) * facade->numFaces() * 6;
uint32_t* iboFaces = nullptr;
if (showFaces)
{
std::shared_ptr<std::vector<uint8_t>> rawIBO(new std::vector<uint8_t>());
//rawIBO->reserve(iboFacesSize);
rawIBO->resize(iboFacesSize); // Linear in complexity... If we need more performance,
// use malloc to generate buffer and then vector::assign.
iboFaces = reinterpret_cast<uint32_t*>(&(*rawIBO)[0]);
i = 0;
BOOST_FOREACH(const FaceInfo& face, facade->faces())
{
// There should *only* be four indicies.
VirtualMesh::Node::array_type nodes = face.nodeIndices();
assert(nodes.size() == 4);
// Winding order looks good from tests.
// Render two triangles.
iboFaces[i ] = nodes[0]; iboFaces[i+1] = nodes[1]; iboFaces[i+2] = nodes[2];
iboFaces[i+3] = nodes[0]; iboFaces[i+4] = nodes[2]; iboFaces[i+5] = nodes[3];
i += 6;
}
// Add IBO for the faces.
std::string facesIBOName = "facesIBO";
geom->mIBOs.emplace_back(GeometryObject::SpireIBO(facesIBOName, sizeof(uint32_t), rawIBO));
// Build pass for the faces.
/// \todo Find an appropriate place to put program names like UniformColor.
GeometryObject::SpirePass pass =
GeometryObject::SpirePass("facesPass", primVBOName,
facesIBOName, "UniformColor",
Spire::StuInterface::TRIANGLES);
if (faceTransparency)
{
pass.addUniform("uColor", Spire::V4(1.0f, 1.0f, 1.0f, 0.2f));
// Modify the GPU state to disable ztesting.
//Spire::GPUState state;
//state.mDepthTestEnable = false;
//pass.addGPUState(state);
}
else
{
pass.addUniform("uColor", Spire::V4(1.0f, 1.0f, 1.0f, 1.0f));
}
geom->mPasses.emplace_back(pass);
}
sendOutput(SceneGraph, geom);
}
AlgorithmParameterName ShowMeshModule::ShowEdges("Show edges");
AlgorithmParameterName ShowMeshModule::ShowFaces("Show faces");
AlgorithmParameterName ShowMeshModule::NodeTransparency("Node Transparency");
AlgorithmParameterName ShowMeshModule::EdgeTransparency("Edge Transparency");
AlgorithmParameterName ShowMeshModule::FaceTransparency("Face Transparency");
<|endoftext|> |
<commit_before>#include "RoleDecisionPositionFormation.h"
#include "Eigen/Eigen"
#include <iomanip>
#include <limits>
RoleDecisionPositionFormation::RoleDecisionPositionFormation()
{
getDebugParameterList().add(¶ms);
DEBUG_REQUEST_REGISTER("RoleDecision:Position:formation:reset_positions", "resets the role positions to its defaults.", false);
DEBUG_REQUEST_REGISTER("RoleDecision:Position:formation:draw_default_position", "draws the default role positions.", false);
DEBUG_REQUEST_REGISTER("RoleDecision:Position:formation:draw_active_positions", "draws the ACTIVE role positions on the field as simple cross and a circle around it", false);
DEBUG_REQUEST_REGISTER("RoleDecision:Position:formation:draw_active_positions_robots", "draws the ACTIVE role positions on the field as robot with role name", false);
DEBUG_REQUEST_REGISTER("RoleDecision:Position:formation:draw_inactive_positions", "draws the INACTIVE role positions on the field as simple cross", false);
DEBUG_REQUEST_REGISTER("RoleDecision:Position:formation:draw_inactive_positions_robots", "draws the INACTIVE role positions on the field as robot with role name", false);
// init positions with default
resetPositions();
}
RoleDecisionPositionFormation::~RoleDecisionPositionFormation()
{
getDebugParameterList().remove(¶ms);
}
void RoleDecisionPositionFormation::resetPositions() const
{
for (const auto& d : getRoles().defaults) {
getRoleDecisionModel().roles_position[d.first] = d.second;
}
}
void RoleDecisionPositionFormation::execute()
{
DEBUG_REQUEST("RoleDecision:Position:formation:reset_positions", resetPositions(); );
// TODO: make factor function configurable
if(getTeamBallModel().valid) {
double factor = Math::clamp((getTeamBallModel().positionOnField.x - getFieldInfo().xPosOwnGroundline) / getFieldInfo().xLength, 0.0, 1.0);
// an alternative anchor could be simply the center of the own groundline: getFieldInfo().xPosOwnGroundline, 0
const auto& anchor = getRoles().defaults.at(Roles::goalie).home;
const auto angle = (getTeamBallModel().positionOnField - Vector2d(getFieldInfo().xPosOwnGroundline, 0)).angle();
for(const auto& r : getRoles().defaults) {
if(r.first == Roles::goalie) { continue; }
Vector2d shift;
// NOTE: the assumption is that the roles are each divided into three groups!
switch (r.first / 3) {
case 0: // defender
shift.x = (r.second.home.x - anchor.x) * Math::clamp(std::sqrt(2.2*factor), params.defenderMinFactorX, params.defenderMaxFactorX);
shift.y = (r.second.home.y - anchor.y) * Math::clamp(1.2-1.8*std::exp(-4.2*factor), params.defenderMinFactorY, params.defenderMaxFactorY);
shift.rotate(Math::clamp(angle, params.defenderMinAngle, params.defenderMaxAngle));
shift += anchor;
break;
case 1: // midfielder
//0.3+\frac{1}{1+e^{-\left(x-0.5\right)d}}\cdot0.99
//0.4+\frac{1}{1+e^{-xd}}\cdot0.99
shift.x = (r.second.home.x - anchor.x) * Math::clamp(0.3+(1/(1+std::exp(-3.2*(factor-0.5))))*1.0, params.midfielderMinFactorX, params.midfielderMaxFactorX);
shift.y = (r.second.home.y - anchor.y) * Math::clamp(1.2-1.8*std::exp(-4.2*factor), params.midfielderMinFactorY, params.midfielderMaxFactorY);
shift.rotate(Math::clamp(angle, params.midfielderMinAngle, params.midfielderMaxAngle));
shift += anchor;
break;
case 2: // forward
//0.3+\frac{1}{1+e^{-\left(x-0.5\right)d}}\cdot1.1
shift.x = (r.second.home.x - anchor.x) * Math::clamp(0.3+(1/(1+std::exp(-2.4*(factor-0.5))))*1.1, params.forwardMinFactorX, params.forwardMaxFactorX);
shift.y = (r.second.home.y - anchor.y) * Math::clamp(1.2-1.8*std::exp(-4.2*factor), params.forwardMinFactorY, params.forwardMaxFactorY);
shift.rotate(Math::clamp(angle, params.forwardMinAngle, params.forwardMaxAngle));
shift += anchor;
break;
default:
shift = r.second.home;
}
getRoleDecisionModel().roles_position[r.first].home = shift;
}
}
debugDrawings();
}
void RoleDecisionPositionFormation::debugDrawings() const
{
DEBUG_REQUEST("RoleDecision:Position:formation:draw_default_position",
FIELD_DRAWING_CONTEXT;
for(const auto& r : getRoles().defaults) {
if(getRoles().isRoleActive(r.first)) {
PEN("969300", 10);
LINE(r.second.home.x, r.second.home.y-20, r.second.home.x, r.second.home.y+20);
LINE(r.second.home.x-20, r.second.home.y, r.second.home.x+20, r.second.home.y);
}
}
);
// more functional presentation
DEBUG_REQUEST("RoleDecision:Position:formation:draw_active_positions",
FIELD_DRAWING_CONTEXT;
for(const auto& r : getRoleDecisionModel().roles_position) {
if(getRoles().isRoleActive(r.first)) {
PEN("666666", 20);
LINE(r.second.home.x, r.second.home.y-20, r.second.home.x, r.second.home.y+20);
LINE(r.second.home.x-20, r.second.home.y, r.second.home.x+20, r.second.home.y);
// mark active positions with a circle
PEN("666666", 10);
CIRCLE(r.second.home.x, r.second.home.y, 40);
}
}
);
// nicer representation (eg. for images)
DEBUG_REQUEST("RoleDecision:Position:formation:draw_active_positions_robots",
FIELD_DRAWING_CONTEXT;
for(const auto& r : getRoleDecisionModel().roles_position) {
if(getRoles().isRoleActive(r.first)) {
PEN("0000ff", 20);
ROBOT(r.second.home.x, r.second.home.y, 0);
TEXT_DRAWING2(r.second.home.x, r.second.home.y-250, 0.6, Roles::getName(r.first));
}
}
);
// more functional presentation
DEBUG_REQUEST("RoleDecision:Position:formation:draw_inactive_positions",
FIELD_DRAWING_CONTEXT;
for(const auto& r : getRoleDecisionModel().roles_position) {
if(!getRoles().isRoleActive(r.first) && r.first != Roles::unknown) {
PEN("666666", 20);
LINE(r.second.home.x, r.second.home.y-20, r.second.home.x, r.second.home.y+20);
LINE(r.second.home.x-20, r.second.home.y, r.second.home.x+20, r.second.home.y);
}
}
);
// nicer representation (eg. for images)
DEBUG_REQUEST("RoleDecision:Position:formation:draw_inactive_positions_robots",
FIELD_DRAWING_CONTEXT;
for(const auto& r : getRoleDecisionModel().roles_position) {
if(!getRoles().isRoleActive(r.first) && r.first != Roles::unknown) {
PEN("0000ff", 20);
ROBOT(r.second.home.x, r.second.home.y, 0);
TEXT_DRAWING2(r.second.home.x, r.second.home.y-250, 0.6, Roles::getName(r.first));
}
}
);
}
<commit_msg>tried to make the code better readable<commit_after>#include "RoleDecisionPositionFormation.h"
#include "Eigen/Eigen"
#include <iomanip>
#include <limits>
RoleDecisionPositionFormation::RoleDecisionPositionFormation()
{
getDebugParameterList().add(¶ms);
DEBUG_REQUEST_REGISTER("RoleDecision:Position:formation:reset_positions", "resets the role positions to its defaults.", false);
DEBUG_REQUEST_REGISTER("RoleDecision:Position:formation:draw_default_position", "draws the default role positions.", false);
DEBUG_REQUEST_REGISTER("RoleDecision:Position:formation:draw_active_positions", "draws the ACTIVE role positions on the field as simple cross and a circle around it", false);
DEBUG_REQUEST_REGISTER("RoleDecision:Position:formation:draw_active_positions_robots", "draws the ACTIVE role positions on the field as robot with role name", false);
DEBUG_REQUEST_REGISTER("RoleDecision:Position:formation:draw_inactive_positions", "draws the INACTIVE role positions on the field as simple cross", false);
DEBUG_REQUEST_REGISTER("RoleDecision:Position:formation:draw_inactive_positions_robots", "draws the INACTIVE role positions on the field as robot with role name", false);
// init positions with default
resetPositions();
}
RoleDecisionPositionFormation::~RoleDecisionPositionFormation()
{
getDebugParameterList().remove(¶ms);
}
void RoleDecisionPositionFormation::resetPositions() const
{
for (const auto& d : getRoles().defaults) {
getRoleDecisionModel().roles_position[d.first] = d.second;
}
}
void RoleDecisionPositionFormation::execute()
{
DEBUG_REQUEST("RoleDecision:Position:formation:reset_positions", resetPositions(); );
// TODO: make factor function configurable
if(getTeamBallModel().valid) {
double factor = Math::clamp((getTeamBallModel().positionOnField.x - getFieldInfo().xPosOwnGroundline) / getFieldInfo().xLength, 0.0, 1.0);
// an alternative anchor could be simply the center of the own groundline: getFieldInfo().xPosOwnGroundline, 0
const auto& anchor = getRoles().defaults.at(Roles::goalie).home;
const auto angle = (getTeamBallModel().positionOnField - Vector2d(getFieldInfo().xPosOwnGroundline, 0)).angle();
double x, y;
for(const auto& r : getRoles().defaults) {
if(r.first == Roles::goalie) { continue; }
Vector2d shift = r.second.home - anchor;
// NOTE: the assumption is that the roles are each divided into three groups!
switch (r.first / 3) {
case 0: // defender
x = std::sqrt(2.2*factor); // \sqrt{2.2 \cdot \text{factor}}
y = 1.2-1.8*std::exp(-4.2*factor); // 1.2 - 1.8 \cdot e^{-4.2 \cdot \text{factor}}
shift.x *= Math::clamp(x, params.defenderMinFactorX, params.defenderMaxFactorX);
shift.y *= Math::clamp(y, params.defenderMinFactorY, params.defenderMaxFactorY);
shift.rotate(Math::clamp(angle, params.defenderMinAngle, params.defenderMaxAngle));
break;
case 1: // midfielder
x = 0.3+(1/(1+std::exp(-3.2*(factor-0.5))))*1.0; // 0.3 + \frac{1}{1+e^{-3.2 \cdot \left( \text{factor} - 0.5 \right)}} \cdot 1.0
y = 1.2-1.8*std::exp(-4.2*factor); // 1.2 - 1.8 \cdot e^{-4.2 \cdot \text{factor}}
shift.x *= Math::clamp(x, params.midfielderMinFactorX, params.midfielderMaxFactorX);
shift.y *= Math::clamp(y, params.midfielderMinFactorY, params.midfielderMaxFactorY);
shift.rotate(Math::clamp(angle, params.midfielderMinAngle, params.midfielderMaxAngle));
break;
case 2: // forward
x = 0.3+(1/(1+std::exp(-2.4*(factor-0.5))))*1.1; // 0.3 + \frac{1}{1+e^{-2.4 \cdot \left( \text{factor} - 0.5 \right)}} \cdot 1.1
y = 1.2-1.8*std::exp(-4.2*factor); // 1.2 - 1.8 \cdot e^{-4.2 \cdot \text{factor}}
shift.x *= Math::clamp(x, params.forwardMinFactorX, params.forwardMaxFactorX);
shift.y *= Math::clamp(y, params.forwardMinFactorY, params.forwardMaxFactorY);
shift.rotate(Math::clamp(angle, params.forwardMinAngle, params.forwardMaxAngle));
break;
default:
// unknown role, do nothing
break;
}
shift += anchor;
getRoleDecisionModel().roles_position[r.first].home = shift;
}
}
debugDrawings();
}
void RoleDecisionPositionFormation::debugDrawings() const
{
DEBUG_REQUEST("RoleDecision:Position:formation:draw_default_position",
FIELD_DRAWING_CONTEXT;
for(const auto& r : getRoles().defaults) {
if(getRoles().isRoleActive(r.first)) {
PEN("969300", 10);
LINE(r.second.home.x, r.second.home.y-20, r.second.home.x, r.second.home.y+20);
LINE(r.second.home.x-20, r.second.home.y, r.second.home.x+20, r.second.home.y);
}
}
);
// more functional presentation
DEBUG_REQUEST("RoleDecision:Position:formation:draw_active_positions",
FIELD_DRAWING_CONTEXT;
for(const auto& r : getRoleDecisionModel().roles_position) {
if(getRoles().isRoleActive(r.first)) {
PEN("666666", 20);
LINE(r.second.home.x, r.second.home.y-20, r.second.home.x, r.second.home.y+20);
LINE(r.second.home.x-20, r.second.home.y, r.second.home.x+20, r.second.home.y);
// mark active positions with a circle
PEN("666666", 10);
CIRCLE(r.second.home.x, r.second.home.y, 40);
}
}
);
// nicer representation (eg. for images)
DEBUG_REQUEST("RoleDecision:Position:formation:draw_active_positions_robots",
FIELD_DRAWING_CONTEXT;
for(const auto& r : getRoleDecisionModel().roles_position) {
if(getRoles().isRoleActive(r.first)) {
PEN("0000ff", 20);
ROBOT(r.second.home.x, r.second.home.y, 0);
TEXT_DRAWING2(r.second.home.x, r.second.home.y-250, 0.6, Roles::getName(r.first));
}
}
);
// more functional presentation
DEBUG_REQUEST("RoleDecision:Position:formation:draw_inactive_positions",
FIELD_DRAWING_CONTEXT;
for(const auto& r : getRoleDecisionModel().roles_position) {
if(!getRoles().isRoleActive(r.first) && r.first != Roles::unknown) {
PEN("666666", 20);
LINE(r.second.home.x, r.second.home.y-20, r.second.home.x, r.second.home.y+20);
LINE(r.second.home.x-20, r.second.home.y, r.second.home.x+20, r.second.home.y);
}
}
);
// nicer representation (eg. for images)
DEBUG_REQUEST("RoleDecision:Position:formation:draw_inactive_positions_robots",
FIELD_DRAWING_CONTEXT;
for(const auto& r : getRoleDecisionModel().roles_position) {
if(!getRoles().isRoleActive(r.first) && r.first != Roles::unknown) {
PEN("0000ff", 20);
ROBOT(r.second.home.x, r.second.home.y, 0);
TEXT_DRAWING2(r.second.home.x, r.second.home.y-250, 0.6, Roles::getName(r.first));
}
}
);
}
<|endoftext|> |
<commit_before>/*
* File: ScanLineEdgelDetector.cpp
* Author: claas
* Author: Heinrich Mellmann
*
* Created on 14. march 2011, 14:22
*/
#include "ScanLineEdgelDetector.h"
// debug
#include "Tools/Debug/DebugModify.h"
#include "Tools/Debug/DebugRequest.h"
#include "Tools/Debug/DebugImageDrawings.h"
#include "Tools/Debug/DebugDrawings.h"
#include "Tools/Debug/Stopwatch.h"
// tools
#include "Tools/ImageProcessing/BresenhamLineScan.h"
#include "Tools/CameraGeometry.h"
#include "Tools/DataStructures/RingBufferWithSum.h"
ScanLineEdgelDetector::ScanLineEdgelDetector()
:
cameraID(CameraInfo::Top)
{
DEBUG_REQUEST_REGISTER("Vision:Detectors:ScanLineEdgelDetector:scanlines", "mark the scan lines", false);
DEBUG_REQUEST_REGISTER("Vision:Detectors:ScanLineEdgelDetector:mark_edgels", "mark the edgels on the image", false);
DEBUG_REQUEST_REGISTER("Vision:Detectors:ScanLineEdgelDetector:mark_double_edgels", "mark the edgels on the image", false);
DEBUG_REQUEST_REGISTER("Vision:Detectors:ScanLineEdgelDetector:mark_endpoints", "mark the endpints on the image", false);
DEBUG_REQUEST_REGISTER("Vision:Detectors:ScanLineEdgelDetector:mark_scan_segments", "...", false);
}
ScanLineEdgelDetector::~ScanLineEdgelDetector()
{}
void ScanLineEdgelDetector::execute(CameraInfo::CameraID id)
{
cameraID = id;
CANVAS_PX(cameraID);
getScanLineEdgelPercept().reset();
// TODO: implement a general validation for timestamps
if(getBodyContour().timestamp != getFrameInfo().getTime()) {
return;
}
int horizon_height = (int)(std::min(getArtificialHorizon().begin().y, getArtificialHorizon().end().y)+0.5);
// clamp it to the image
horizon_height = Math::clamp(horizon_height,0,(int)getImage().height());
// scan only inside the estimated field region
//horizon_height = getFieldPerceptRaw().getValidField().points[0].y;
// horizontal stepsize between the scanlines
int step = (getImage().width() - 1) / (theParameters.scanline_count - 1);
// don't scan the lower lines in the image
int borderY = getImage().height() - theParameters.pixel_border_y - 1;
// start and endpoints for the scanlines
Vector2i start(step / 2, borderY);
Vector2i end(step / 2, horizon_height );
for (int i = 0; i < theParameters.scanline_count - 1; i++)
{
ASSERT(getImage().isInside(start.x, start.y));
// don't scan the own body
start = getBodyContour().getFirstFreeCell(start);
// execute the scan
ScanLineEdgelPercept::EndPoint endPoint = scanForEdgels(i, start, end);
// check if endpoint is not same as the begin of the scanline
if(endPoint.posInImage == start) {
endPoint.color = ColorClasses::none;
endPoint.posInImage.y = borderY;
}
// try to project it on the ground
endPoint.valid = CameraGeometry::imagePixelToFieldCoord(
getCameraMatrix(),
getCameraInfo(),
endPoint.posInImage.x,
endPoint.posInImage.y,
0.0,
endPoint.posOnField);
//
getScanLineEdgelPercept().endPoints.push_back(endPoint);
start.y = borderY;
start.x += step;
end.x = start.x;
}//end for
DEBUG_REQUEST("Vision:Detectors:ScanLineEdgelDetector:mark_edgels",
for(size_t i = 0; i < getScanLineEdgelPercept().edgels.size(); i++) {
const Edgel& edgel = getScanLineEdgelPercept().edgels[i];
LINE_PX(ColorClasses::black,edgel.point.x, edgel.point.y, edgel.point.x + (int)(edgel.direction.x*10), edgel.point.y + (int)(edgel.direction.y*10));
}
);
// mark finished valid edgels
DEBUG_REQUEST("Vision:Detectors:ScanLineEdgelDetector:mark_double_edgels",
for(size_t i = 0; i < getScanLineEdgelPercept().pairs.size(); i++)
{
const ScanLineEdgelPercept::EdgelPair& pair = getScanLineEdgelPercept().pairs[i];
CIRCLE_PX(ColorClasses::black, (int)pair.point.x, (int)pair.point.y, 3);
LINE_PX(ColorClasses::red ,(int)pair.point.x, (int)pair.point.y, (int)(pair.point.x + pair.direction.x*10), (int)(pair.point.y + pair.direction.y*10));
}
);
DEBUG_REQUEST("Vision:Detectors:ScanLineEdgelDetector:mark_endpoints",
for(size_t i = 0; i < getScanLineEdgelPercept().endPoints.size(); i++)
{
const ScanLineEdgelPercept::EndPoint& point_two = getScanLineEdgelPercept().endPoints[i];
CIRCLE_PX(point_two.color, point_two.posInImage.x, point_two.posInImage.y, 5);
if(i > 0) {
const ScanLineEdgelPercept::EndPoint& point_one = getScanLineEdgelPercept().endPoints[i-1];
LINE_PX(point_one.color,
point_one.posInImage.x, point_one.posInImage.y,
point_two.posInImage.x, point_two.posInImage.y);
}
}
);
}//end execute
ScanLineEdgelPercept::EndPoint ScanLineEdgelDetector::scanForEdgels(int scan_id, const Vector2i& start, const Vector2i& end)
{
ScanLineEdgelPercept::EndPoint endPoint;
endPoint.posInImage = start;
endPoint.color = ColorClasses::none;
endPoint.ScanLineID = scan_id;
const int step = 2;
if(end.y + step > start.y || end.y + step >= (int)getImage().height()) {
endPoint.posInImage.y = end.y;
return endPoint;
}
// no scan if the start is at the top of the image
if(start.y <= step) {
return endPoint;
}
Vector2i point(start);
point.y -= step; // make one step
Vector2i last_down_point(point); // needed for the endpoint
bool begin_found = false;
// calculate the threashold
int t_edge = theParameters.brightness_threshold * 2;
// HACK (TEST): make it dependend on the angle of the camera in the future
if(cameraID == CameraInfo::Bottom) {
t_edge *= 4;
}
Vector2i lastGreenPoint(point); // HACK
RingBufferWithSum<double, 10> movingWindow; // HACK
// initialize the scanner
Vector2i peak_point_max(point);
Vector2i peak_point_min(point);
MaximumScan<int,int> positiveScan(peak_point_max.y, t_edge);
MaximumScan<int,int> negativeScan(peak_point_min.y, t_edge);
int f_last = getImage().getY(point.x, point.y); // scan the first point
// just go up
for(;point.y >= end.y + step; point.y -= step)
{
// get the brightness chanel
Pixel pixel = getImage().get(point.x, point.y);
//int f_y = getImage().getY(point.x, point.y);
int f_y = pixel.y;
int g = f_y - f_last;
f_last = f_y;
// begin found
if(positiveScan.addValue(point.y+1, g))
{
// refine the position of the peak
int f_2 = getImage().getY(point.x, peak_point_max.y-2);
int f0 = getImage().getY(point.x, peak_point_max.y);
int f2 = getImage().getY(point.x, peak_point_max.y+2);
if(f_2-f0 > positiveScan.maxValue()) peak_point_max.y -= 1;
if(f0 -f2 > positiveScan.maxValue()) peak_point_max.y += 1;
if(estimateColorOfSegment(last_down_point, peak_point_max) == ColorClasses::green) {
//endPoint.color = ColorClasses::green;
//endPoint.posInImage = peak_point_max;
//lastGreenPoint = peak_point_max;
} else if (!validDistance(lastGreenPoint, peak_point_max)) {
break;
}
add_edgel(peak_point_max);
begin_found = true;
last_down_point.y = peak_point_max.y;
}//end if
// end found
if(negativeScan.addValue(point.y+1, -g))
{
// refine the position of the peak
int f_2 = getImage().getY(point.x, peak_point_min.y-2);
int f0 = getImage().getY(point.x, peak_point_min.y);
int f2 = getImage().getY(point.x, peak_point_min.y+2);
if(f_2-f0 < negativeScan.maxValue()) peak_point_min.y -= 1;
if(f0 -f2 < negativeScan.maxValue()) peak_point_min.y += 1;
if(estimateColorOfSegment(last_down_point, peak_point_min) == ColorClasses::green) {
//endPoint.color = ColorClasses::green;
//endPoint.posInImage = peak_point_min;
//lastGreenPoint = peak_point_min;
} else if (!validDistance(lastGreenPoint, peak_point_min)) {
break;
}
// new end edgel
// found a new double edgel
if(begin_found) {
add_double_edgel(peak_point_min, scan_id);
begin_found = false;
} else {
add_edgel(peak_point_min);
}
last_down_point.y = peak_point_min.y;
}//end if
// HACK
if(getFieldColorPercept().isFieldColor(pixel.a, pixel.b, pixel.c)) // ignore the ball
{
double greenDensity = movingWindow.getSum()/movingWindow.size();
if(greenDensity > 0.3)
{
lastGreenPoint = point;
}
movingWindow.add(1.0);
}
else
{
movingWindow.add(0.0);
}
DEBUG_REQUEST("Vision:Detectors:ScanLineEdgelDetector:scanlines",
Pixel pixel = getImage().get(point.x, point.y);
ColorClasses::Color thisPixelColor = (getFieldColorPercept().isFieldColor(pixel.a, pixel.b, pixel.c))?ColorClasses::green:ColorClasses::none;
POINT_PX(thisPixelColor, point.x, point.y);
);
}//end for
/*
if(point.y < end.y + step) {
if(estimateColorOfSegment(last_down_point, end) == ColorClasses::green) {
endPoint.color = ColorClasses::green;
endPoint.posInImage = end;
}
}*/
endPoint.posInImage = lastGreenPoint;
endPoint.color = ColorClasses::green;
return endPoint;
}//end scanForEdgels
bool ScanLineEdgelDetector::validDistance(const Vector2i& pointOne, const Vector2i& pointTwo) const
{
if (abs(pointOne.y - pointTwo.y) > 5)
{
Vector2d beginOnTheGround;
if(CameraGeometry::imagePixelToFieldCoord(
getCameraMatrix(),
getCameraInfo(),
pointOne.x,
pointOne.y,
0.0,
beginOnTheGround))
{
Vector2d endOnTheGround;
if(CameraGeometry::imagePixelToFieldCoord(
getCameraMatrix(),
getCameraInfo(),
pointTwo.x,
pointTwo.y,
0.0,
endOnTheGround))
{
if((beginOnTheGround-endOnTheGround).abs2() > 700*700) {
return false;
}
}
else
{
return false;
}
}
else
{
return false;
}
}
return true;
}
ColorClasses::Color ScanLineEdgelDetector::estimateColorOfSegment(const Vector2i& begin, const Vector2i& end) const
{
ASSERT(begin.x == end.x && end.y <= begin.y);
const int numberOfSamples = theParameters.green_sampling_points;
int length = begin.y - end.y;
int numberOfGreen = 0;
Vector2i point(begin);
Pixel pixel;
if(numberOfSamples >= length)
{
for(; point.y > end.y; point.y--)
{
getImage().get(point.x, point.y, pixel);
numberOfGreen += getFieldColorPercept().isFieldColor(pixel.a, pixel.b, pixel.c);
}
}
else
{
int step = length / numberOfSamples;
int offset = Math::random(length); // number in [0,length-1]
for(int i = 0; i < numberOfSamples; i++)
{
int k = (offset + i*step) % length;
point.y = end.y + k;
getImage().get(point.x, point.y, pixel);
numberOfGreen += getFieldColorPercept().isFieldColor(pixel.a, pixel.b, pixel.c);
}
}
ColorClasses::Color c = (numberOfGreen > numberOfSamples/2) ? ColorClasses::green : ColorClasses::none;
DEBUG_REQUEST("Vision:Detectors:ScanLineEdgelDetector:mark_scan_segments",
LINE_PX(c, begin.x, begin.y, end.x, end.y);
);
return c;
}//end estimateColorOfSegment
Vector2d ScanLineEdgelDetector::calculateGradient(const Vector2i& point) const
{
Vector2d gradient;
// no angle at the border (shouldn't happen)
if( point.x < 1 || point.x + 2 > (int)getImage().width() ||
point.y < 1 || point.y + 2 > (int)getImage().height() ) {
return gradient;
}
//apply Sobel Operator on (pointX, pointY)
//and calculate gradient in x and y direction by that means
gradient.x =
getImage().getY(point.x-1, point.y+1)
+2*getImage().getY(point.x , point.y+1)
+ getImage().getY(point.x+1, point.y+1)
- getImage().getY(point.x-1, point.y-1)
-2*getImage().getY(point.x , point.y-1)
- getImage().getY(point.x+1, point.y-1);
gradient.y =
getImage().getY(point.x-1, point.y-1)
+2*getImage().getY(point.x-1, point.y )
+ getImage().getY(point.x-1, point.y+1)
- getImage().getY(point.x+1, point.y-1)
-2*getImage().getY(point.x+1, point.y )
- getImage().getY(point.x+1, point.y+1);
//calculate the angle of the gradient
return gradient.normalize();
}//end calculateGradient
<commit_msg>Hack: stop scanline if point is darker than field should be<commit_after>/*
* File: ScanLineEdgelDetector.cpp
* Author: claas
* Author: Heinrich Mellmann
*
* Created on 14. march 2011, 14:22
*/
#include "ScanLineEdgelDetector.h"
// debug
#include "Tools/Debug/DebugModify.h"
#include "Tools/Debug/DebugRequest.h"
#include "Tools/Debug/DebugImageDrawings.h"
#include "Tools/Debug/DebugDrawings.h"
#include "Tools/Debug/Stopwatch.h"
// tools
#include "Tools/ImageProcessing/BresenhamLineScan.h"
#include "Tools/CameraGeometry.h"
#include "Tools/DataStructures/RingBufferWithSum.h"
ScanLineEdgelDetector::ScanLineEdgelDetector()
:
cameraID(CameraInfo::Top)
{
DEBUG_REQUEST_REGISTER("Vision:Detectors:ScanLineEdgelDetector:scanlines", "mark the scan lines", false);
DEBUG_REQUEST_REGISTER("Vision:Detectors:ScanLineEdgelDetector:mark_edgels", "mark the edgels on the image", false);
DEBUG_REQUEST_REGISTER("Vision:Detectors:ScanLineEdgelDetector:mark_double_edgels", "mark the edgels on the image", false);
DEBUG_REQUEST_REGISTER("Vision:Detectors:ScanLineEdgelDetector:mark_endpoints", "mark the endpints on the image", false);
DEBUG_REQUEST_REGISTER("Vision:Detectors:ScanLineEdgelDetector:mark_scan_segments", "...", false);
}
ScanLineEdgelDetector::~ScanLineEdgelDetector()
{}
void ScanLineEdgelDetector::execute(CameraInfo::CameraID id)
{
cameraID = id;
CANVAS_PX(cameraID);
getScanLineEdgelPercept().reset();
// TODO: implement a general validation for timestamps
if(getBodyContour().timestamp != getFrameInfo().getTime()) {
return;
}
int horizon_height = (int)(std::min(getArtificialHorizon().begin().y, getArtificialHorizon().end().y)+0.5);
// clamp it to the image
horizon_height = Math::clamp(horizon_height,0,(int)getImage().height());
// scan only inside the estimated field region
//horizon_height = getFieldPerceptRaw().getValidField().points[0].y;
// horizontal stepsize between the scanlines
int step = (getImage().width() - 1) / (theParameters.scanline_count - 1);
// don't scan the lower lines in the image
int borderY = getImage().height() - theParameters.pixel_border_y - 1;
// start and endpoints for the scanlines
Vector2i start(step / 2, borderY);
Vector2i end(step / 2, horizon_height );
for (int i = 0; i < theParameters.scanline_count - 1; i++)
{
ASSERT(getImage().isInside(start.x, start.y));
// don't scan the own body
start = getBodyContour().getFirstFreeCell(start);
// execute the scan
ScanLineEdgelPercept::EndPoint endPoint = scanForEdgels(i, start, end);
// check if endpoint is not same as the begin of the scanline
if(endPoint.posInImage == start) {
endPoint.color = ColorClasses::none;
endPoint.posInImage.y = borderY;
}
// try to project it on the ground
endPoint.valid = CameraGeometry::imagePixelToFieldCoord(
getCameraMatrix(),
getCameraInfo(),
endPoint.posInImage.x,
endPoint.posInImage.y,
0.0,
endPoint.posOnField);
//
getScanLineEdgelPercept().endPoints.push_back(endPoint);
start.y = borderY;
start.x += step;
end.x = start.x;
}//end for
DEBUG_REQUEST("Vision:Detectors:ScanLineEdgelDetector:mark_edgels",
for(size_t i = 0; i < getScanLineEdgelPercept().edgels.size(); i++) {
const Edgel& edgel = getScanLineEdgelPercept().edgels[i];
LINE_PX(ColorClasses::black,edgel.point.x, edgel.point.y, edgel.point.x + (int)(edgel.direction.x*10), edgel.point.y + (int)(edgel.direction.y*10));
}
);
// mark finished valid edgels
DEBUG_REQUEST("Vision:Detectors:ScanLineEdgelDetector:mark_double_edgels",
for(size_t i = 0; i < getScanLineEdgelPercept().pairs.size(); i++)
{
const ScanLineEdgelPercept::EdgelPair& pair = getScanLineEdgelPercept().pairs[i];
CIRCLE_PX(ColorClasses::black, (int)pair.point.x, (int)pair.point.y, 3);
LINE_PX(ColorClasses::red ,(int)pair.point.x, (int)pair.point.y, (int)(pair.point.x + pair.direction.x*10), (int)(pair.point.y + pair.direction.y*10));
}
);
DEBUG_REQUEST("Vision:Detectors:ScanLineEdgelDetector:mark_endpoints",
for(size_t i = 0; i < getScanLineEdgelPercept().endPoints.size(); i++)
{
const ScanLineEdgelPercept::EndPoint& point_two = getScanLineEdgelPercept().endPoints[i];
CIRCLE_PX(point_two.color, point_two.posInImage.x, point_two.posInImage.y, 5);
if(i > 0) {
const ScanLineEdgelPercept::EndPoint& point_one = getScanLineEdgelPercept().endPoints[i-1];
LINE_PX(point_one.color,
point_one.posInImage.x, point_one.posInImage.y,
point_two.posInImage.x, point_two.posInImage.y);
}
}
);
}//end execute
ScanLineEdgelPercept::EndPoint ScanLineEdgelDetector::scanForEdgels(int scan_id, const Vector2i& start, const Vector2i& end)
{
ScanLineEdgelPercept::EndPoint endPoint;
endPoint.posInImage = start;
endPoint.color = ColorClasses::none;
endPoint.ScanLineID = scan_id;
const int step = 2;
if(end.y + step > start.y || end.y + step >= (int)getImage().height()) {
endPoint.posInImage.y = end.y;
return endPoint;
}
// no scan if the start is at the top of the image
if(start.y <= step) {
return endPoint;
}
Vector2i point(start);
point.y -= step; // make one step
Vector2i last_down_point(point); // needed for the endpoint
bool begin_found = false;
// calculate the threashold
int t_edge = theParameters.brightness_threshold * 2;
// HACK (TEST): make it dependend on the angle of the camera in the future
if(cameraID == CameraInfo::Bottom) {
t_edge *= 4;
}
Vector2i lastGreenPoint(point); // HACK
RingBufferWithSum<double, 10> movingWindow; // HACK
// initialize the scanner
Vector2i peak_point_max(point);
Vector2i peak_point_min(point);
MaximumScan<int,int> positiveScan(peak_point_max.y, t_edge);
MaximumScan<int,int> negativeScan(peak_point_min.y, t_edge);
int f_last = getImage().getY(point.x, point.y); // scan the first point
// just go up
for(;point.y >= end.y + step; point.y -= step)
{
// get the brightness chanel
Pixel pixel = getImage().get(point.x, point.y);
//int f_y = getImage().getY(point.x, point.y);
int f_y = pixel.y;
int g = f_y - f_last;
f_last = f_y;
// begin found
if(positiveScan.addValue(point.y+1, g))
{
// refine the position of the peak
int f_2 = getImage().getY(point.x, peak_point_max.y-2);
int f0 = getImage().getY(point.x, peak_point_max.y);
int f2 = getImage().getY(point.x, peak_point_max.y+2);
if(f_2-f0 > positiveScan.maxValue()) peak_point_max.y -= 1;
if(f0 -f2 > positiveScan.maxValue()) peak_point_max.y += 1;
if(estimateColorOfSegment(last_down_point, peak_point_max) == ColorClasses::green) {
//endPoint.color = ColorClasses::green;
//endPoint.posInImage = peak_point_max;
//lastGreenPoint = peak_point_max;
} else if (!validDistance(lastGreenPoint, peak_point_max)) {
break;
}
add_edgel(peak_point_max);
begin_found = true;
last_down_point.y = peak_point_max.y;
}//end if
// end found
if(negativeScan.addValue(point.y+1, -g))
{
// refine the position of the peak
int f_2 = getImage().getY(point.x, peak_point_min.y-2);
int f0 = getImage().getY(point.x, peak_point_min.y);
int f2 = getImage().getY(point.x, peak_point_min.y+2);
if(f_2-f0 < negativeScan.maxValue()) peak_point_min.y -= 1;
if(f0 -f2 < negativeScan.maxValue()) peak_point_min.y += 1;
if(estimateColorOfSegment(last_down_point, peak_point_min) == ColorClasses::green) {
//endPoint.color = ColorClasses::green;
//endPoint.posInImage = peak_point_min;
//lastGreenPoint = peak_point_min;
} else if (!validDistance(lastGreenPoint, peak_point_min)) {
break;
}
// new end edgel
// found a new double edgel
if(begin_found) {
add_double_edgel(peak_point_min, scan_id);
begin_found = false;
} else {
add_edgel(peak_point_min);
}
last_down_point.y = peak_point_min.y;
}//end if
// HACK
if(getFieldColorPercept().isFieldColor(pixel.a, pixel.b, pixel.c))
{
double greenDensity = movingWindow.getSum()/movingWindow.size();
if(greenDensity > 0.3)
{
lastGreenPoint = point;
}
movingWindow.add(1.0);
}
else
{
//HACK break if darker than field
if(pixel.y < getFieldColorPercept().range.getMin().y)
{
break;
}
movingWindow.add(0.0);
}
DEBUG_REQUEST("Vision:Detectors:ScanLineEdgelDetector:scanlines",
Pixel pixel = getImage().get(point.x, point.y);
ColorClasses::Color thisPixelColor = (getFieldColorPercept().isFieldColor(pixel.a, pixel.b, pixel.c))?ColorClasses::green:ColorClasses::none;
POINT_PX(thisPixelColor, point.x, point.y);
);
}//end for
/*
if(point.y < end.y + step) {
if(estimateColorOfSegment(last_down_point, end) == ColorClasses::green) {
endPoint.color = ColorClasses::green;
endPoint.posInImage = end;
}
}*/
endPoint.posInImage = lastGreenPoint;
endPoint.color = ColorClasses::green;
return endPoint;
}//end scanForEdgels
bool ScanLineEdgelDetector::validDistance(const Vector2i& pointOne, const Vector2i& pointTwo) const
{
if (abs(pointOne.y - pointTwo.y) > 5)
{
Vector2d beginOnTheGround;
if(CameraGeometry::imagePixelToFieldCoord(
getCameraMatrix(),
getCameraInfo(),
pointOne.x,
pointOne.y,
0.0,
beginOnTheGround))
{
Vector2d endOnTheGround;
if(CameraGeometry::imagePixelToFieldCoord(
getCameraMatrix(),
getCameraInfo(),
pointTwo.x,
pointTwo.y,
0.0,
endOnTheGround))
{
if((beginOnTheGround-endOnTheGround).abs2() > 700*700) {
return false;
}
}
else
{
return false;
}
}
else
{
return false;
}
}
return true;
}
ColorClasses::Color ScanLineEdgelDetector::estimateColorOfSegment(const Vector2i& begin, const Vector2i& end) const
{
ASSERT(begin.x == end.x && end.y <= begin.y);
const int numberOfSamples = theParameters.green_sampling_points;
int length = begin.y - end.y;
int numberOfGreen = 0;
Vector2i point(begin);
Pixel pixel;
if(numberOfSamples >= length)
{
for(; point.y > end.y; point.y--)
{
getImage().get(point.x, point.y, pixel);
numberOfGreen += getFieldColorPercept().isFieldColor(pixel.a, pixel.b, pixel.c);
}
}
else
{
int step = length / numberOfSamples;
int offset = Math::random(length); // number in [0,length-1]
for(int i = 0; i < numberOfSamples; i++)
{
int k = (offset + i*step) % length;
point.y = end.y + k;
getImage().get(point.x, point.y, pixel);
numberOfGreen += getFieldColorPercept().isFieldColor(pixel.a, pixel.b, pixel.c);
}
}
ColorClasses::Color c = (numberOfGreen > numberOfSamples/2) ? ColorClasses::green : ColorClasses::none;
DEBUG_REQUEST("Vision:Detectors:ScanLineEdgelDetector:mark_scan_segments",
LINE_PX(c, begin.x, begin.y, end.x, end.y);
);
return c;
}//end estimateColorOfSegment
Vector2d ScanLineEdgelDetector::calculateGradient(const Vector2i& point) const
{
Vector2d gradient;
// no angle at the border (shouldn't happen)
if( point.x < 1 || point.x + 2 > (int)getImage().width() ||
point.y < 1 || point.y + 2 > (int)getImage().height() ) {
return gradient;
}
//apply Sobel Operator on (pointX, pointY)
//and calculate gradient in x and y direction by that means
gradient.x =
getImage().getY(point.x-1, point.y+1)
+2*getImage().getY(point.x , point.y+1)
+ getImage().getY(point.x+1, point.y+1)
- getImage().getY(point.x-1, point.y-1)
-2*getImage().getY(point.x , point.y-1)
- getImage().getY(point.x+1, point.y-1);
gradient.y =
getImage().getY(point.x-1, point.y-1)
+2*getImage().getY(point.x-1, point.y )
+ getImage().getY(point.x-1, point.y+1)
- getImage().getY(point.x+1, point.y-1)
-2*getImage().getY(point.x+1, point.y )
- getImage().getY(point.x+1, point.y+1);
//calculate the angle of the gradient
return gradient.normalize();
}//end calculateGradient
<|endoftext|> |
<commit_before>#pragma once
// `krbn::probable_stuck_events_manager` can be used safely in a multi-threaded environment.
#include "types.hpp"
#include <set>
namespace krbn {
// `probable_stuck_events_manager` manages events which may be stuck with ungrabbed device.
//
// macOS keeps the key state after the device is grabbed.
// This behavior causes several problems:
// - A key repeating cannot be stopped if the key is held down before the device is grabbed.
// - Modifier keys will be stuck if they are held down before the device is grabbed.
//
// Thus, we should not grab (or should ungrab) the device in such cases.
// `probable_stuck_events_manager` is used to detect such states.
class probable_stuck_events_manager {
public:
probable_stuck_events_manager(void) : last_time_stamp_(0) {
}
bool update(const momentary_switch_event& event,
event_type t,
absolute_time_point time_stamp,
device_state state) {
std::lock_guard<std::mutex> lock(mutex_);
//
// Skip old event
//
if (time_stamp < last_time_stamp_) {
return false;
}
last_time_stamp_ = time_stamp;
//
// Handle event
//
auto previous_size = probable_stuck_events_.size();
switch (t) {
case event_type::key_down:
key_down_arrived_events_.insert(event);
key_up_events_.erase(event);
exceptional_key_up_events_.erase(event);
// We register a key (or button) to probable_stuck_events_
// unless the event is sent from grabbed device.
// (The key may be repeating.)
if (state == device_state::ungrabbed) {
if (event.modifier_flag()) {
// Do nothing (Do not erase existing keys.)
} else {
if (auto usage_pair = event.make_usage_pair()) {
if (usage_pair->get_usage_page() == pqrs::hid::usage_page::button) {
// Do nothing with pointing_button.
} else {
erase_except_modifier_flags(usage_pair->get_usage_page());
}
}
}
probable_stuck_events_.insert(event);
}
break;
case event_type::key_up: {
// Some devices send key_up event periodically without paired `key_down`.
// For example, Swiftpoint ProPoint sends consumer_key_code::play_or_pause key_up after each button1 click.
// So, we ignore such key_up event if key_up event sent twice without key_down event.
auto already_key_up = (key_up_events_.find(event) != std::end(key_up_events_));
if (already_key_up) {
exceptional_key_up_events_.insert(event);
probable_stuck_events_.erase(event);
} else {
// The key was held down before the device is grabbed
// if `key_up` is came without paired `key_down`.
auto key_down_arrived = (key_down_arrived_events_.find(event) != std::end(key_down_arrived_events_));
auto exceptional = exceptional_key_up_events_.find(event) != std::end(exceptional_key_up_events_);
if (!key_down_arrived && !exceptional) {
probable_stuck_events_.insert(event);
} else {
probable_stuck_events_.erase(event);
}
}
key_up_events_.insert(event);
break;
}
case event_type::single:
// Do nothing
break;
}
return probable_stuck_events_.size() != previous_size;
}
void clear(void) {
std::lock_guard<std::mutex> lock(mutex_);
probable_stuck_events_.clear();
key_down_arrived_events_.clear();
key_up_events_.clear();
// Do not clear `exceptional_key_up_events_` here.
last_time_stamp_ = absolute_time_point(0);
}
std::optional<momentary_switch_event> find_probable_stuck_event(void) const {
std::lock_guard<std::mutex> lock(mutex_);
if (!probable_stuck_events_.empty()) {
return *(std::begin(probable_stuck_events_));
}
return std::nullopt;
}
private:
void erase_except_modifier_flags(pqrs::hid::usage_page::value_t usage_page) {
auto it = std::begin(probable_stuck_events_);
while (it != std::end(probable_stuck_events_)) {
if (auto usage_pair = it->make_usage_pair()) {
if (usage_pair->get_usage_page() == usage_page && !it->modifier_flag()) {
it = probable_stuck_events_.erase(it);
continue;
}
}
std::advance(it, 1);
}
}
std::set<momentary_switch_event> probable_stuck_events_;
std::set<momentary_switch_event> key_down_arrived_events_;
std::set<momentary_switch_event> key_up_events_;
// Some devices sends key_up events continuously and never sends paired key_down events.
// Store them into `exceptional_key_up_events_`.
std::set<momentary_switch_event> exceptional_key_up_events_;
absolute_time_point last_time_stamp_;
mutable std::mutex mutex_;
};
} // namespace krbn
<commit_msg>Update comment<commit_after>#pragma once
// `krbn::probable_stuck_events_manager` can be used safely in a multi-threaded environment.
#include "types.hpp"
#include <set>
namespace krbn {
// `probable_stuck_events_manager` manages events which may be stuck with ungrabbed device.
//
// macOS keeps the key state after the device is grabbed.
// This behavior causes several problems:
// - A key repeating cannot be stopped if the key is held down before the device is grabbed.
// - Modifier keys will be stuck if they are held down before the device is grabbed.
//
// Thus, we should not grab (or should ungrab) the device in such cases.
// `probable_stuck_events_manager` is used to detect such states.
class probable_stuck_events_manager {
public:
probable_stuck_events_manager(void) : last_time_stamp_(0) {
}
bool update(const momentary_switch_event& event,
event_type t,
absolute_time_point time_stamp,
device_state state) {
std::lock_guard<std::mutex> lock(mutex_);
//
// Skip old event
//
if (time_stamp < last_time_stamp_) {
return false;
}
last_time_stamp_ = time_stamp;
//
// Handle event
//
auto previous_size = probable_stuck_events_.size();
switch (t) {
case event_type::key_down:
key_down_arrived_events_.insert(event);
key_up_events_.erase(event);
exceptional_key_up_events_.erase(event);
// We register a key (or button) to probable_stuck_events_
// unless the event is sent from grabbed device.
// (The key may be repeating.)
if (state == device_state::ungrabbed) {
if (event.modifier_flag()) {
// Do nothing (Do not erase existing keys.)
} else {
if (auto usage_pair = event.make_usage_pair()) {
if (usage_pair->get_usage_page() == pqrs::hid::usage_page::button) {
// Do nothing with pointing_button.
} else {
erase_except_modifier_flags(usage_pair->get_usage_page());
}
}
}
probable_stuck_events_.insert(event);
}
break;
case event_type::key_up: {
// Some devices send key_up event periodically without paired `key_down`.
// For example, Swiftpoint ProPoint sends pqrs::hid::usage::consumer::play_or_pause key_up after each button1 click.
// So, we ignore such key_up event if key_up event sent twice without key_down event.
auto already_key_up = (key_up_events_.find(event) != std::end(key_up_events_));
if (already_key_up) {
exceptional_key_up_events_.insert(event);
probable_stuck_events_.erase(event);
} else {
// The key was held down before the device is grabbed
// if `key_up` is came without paired `key_down`.
auto key_down_arrived = (key_down_arrived_events_.find(event) != std::end(key_down_arrived_events_));
auto exceptional = exceptional_key_up_events_.find(event) != std::end(exceptional_key_up_events_);
if (!key_down_arrived && !exceptional) {
probable_stuck_events_.insert(event);
} else {
probable_stuck_events_.erase(event);
}
}
key_up_events_.insert(event);
break;
}
case event_type::single:
// Do nothing
break;
}
return probable_stuck_events_.size() != previous_size;
}
void clear(void) {
std::lock_guard<std::mutex> lock(mutex_);
probable_stuck_events_.clear();
key_down_arrived_events_.clear();
key_up_events_.clear();
// Do not clear `exceptional_key_up_events_` here.
last_time_stamp_ = absolute_time_point(0);
}
std::optional<momentary_switch_event> find_probable_stuck_event(void) const {
std::lock_guard<std::mutex> lock(mutex_);
if (!probable_stuck_events_.empty()) {
return *(std::begin(probable_stuck_events_));
}
return std::nullopt;
}
private:
void erase_except_modifier_flags(pqrs::hid::usage_page::value_t usage_page) {
auto it = std::begin(probable_stuck_events_);
while (it != std::end(probable_stuck_events_)) {
if (auto usage_pair = it->make_usage_pair()) {
if (usage_pair->get_usage_page() == usage_page && !it->modifier_flag()) {
it = probable_stuck_events_.erase(it);
continue;
}
}
std::advance(it, 1);
}
}
std::set<momentary_switch_event> probable_stuck_events_;
std::set<momentary_switch_event> key_down_arrived_events_;
std::set<momentary_switch_event> key_up_events_;
// Some devices sends key_up events continuously and never sends paired key_down events.
// Store them into `exceptional_key_up_events_`.
std::set<momentary_switch_event> exceptional_key_up_events_;
absolute_time_point last_time_stamp_;
mutable std::mutex mutex_;
};
} // namespace krbn
<|endoftext|> |
<commit_before>/*
* Copyright (c) 2016 tildearrow
*
* 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.
*/
#ifdef _WIN32
#define FONT "C:\\Windows\\Fonts\\segoeui.ttf"
#elif __APPLE__
#define FONT "/System/Library/Fonts/SFNSDisplay-Regular.otf"
#elif __linux__
#define FONT "/usr/share/fonts/TTF/Ubuntu-R.ttf"
#else
#warning "really? please tell me if you are compiling on this OS"
#endif
#include "includes.h"
#include "font.h"
#include "ui.h"
SDL_Window* mainWindow;
SDL_Renderer* mainRenderer;
SDL_Event* event;
int mouseX;
int mouseY;
unsigned int mouseB;
unsigned int mouseBold;
SDL_Color color;
bool willquit;
uisystem* ui;
font* mainFont;
void doNothing(){
printf("hello world!\n");
}
int main() {
willquit=false;
// init everything
SDL_Init(SDL_INIT_VIDEO);
TTF_Init();
ui=new uisystem;
event=new SDL_Event;
string title;
title="LowerTriad";
mainWindow=SDL_CreateWindow(title.c_str(),0,0,1024,600,SDL_WINDOW_RESIZABLE);
if (!mainWindow) {
printf("i'm sorry, but window can't be created: %s\n",SDL_GetError());
return 1;
}
mainRenderer=SDL_CreateRenderer(mainWindow,-1,SDL_RENDERER_ACCELERATED|SDL_RENDERER_PRESENTVSYNC);
// initialize UI
mainFont=new font;
mainFont->setrenderer(mainRenderer);
if (!mainFont->load(FONT,14)) {
printf("can't load font, which means this application is going to crash now...\n");
}
ui->setrenderer(mainRenderer);
color.r=0; color.g=255; color.b=0; color.a=255;
ui->setfont(mainFont);
ui->addbutton(0,0,48,22,"Prepare","Prepare CMake project",color,color,doNothing);
ui->addbutton(48,0,40,22,"Build","Build game",color,color,doNothing);
ui->addbutton(100,0,32,22,"Run","Run compiled game",color,color,doNothing);
ui->addbutton(132,0,56,22,"Package","Create package",color,color,doNothing);
ui->addbutton(200,0,64,22,"Graphics","",color,color,doNothing);
ui->addbutton(264,0,50,22,"Audio","",color,color,doNothing);
ui->addbutton(314,0,54,22,"Objects","",color,color,doNothing);
ui->addbutton(368,0,50,22,"Scenes","",color,color,doNothing);
ui->addbutton(418,0,72,22,"Functions","",color,color,doNothing);
ui->setmouse(&mouseX,&mouseY,&mouseB,&mouseBold);
while (1) {
// check events
while (SDL_PollEvent(event)) {
if (event->type==SDL_QUIT) {
willquit=true;
}
}
SDL_SetRenderDrawColor(mainRenderer,0,0,0,0);
SDL_RenderClear(mainRenderer);
mouseBold=mouseB;
mouseB=SDL_GetMouseState(&mouseX, &mouseY);
ui->drawall();
SDL_RenderPresent(mainRenderer);
if (willquit) {
break;
}
}
return 0;
}
<commit_msg>adding game-asset-related structs and vectors<commit_after>/*
* Copyright (c) 2016 tildearrow
*
* 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.
*/
#ifdef _WIN32
#define FONT "C:\\Windows\\Fonts\\segoeui.ttf"
#elif __APPLE__
#define FONT "/System/Library/Fonts/SFNSDisplay-Regular.otf"
#elif __linux__
#define FONT "/usr/share/fonts/TTF/Ubuntu-R.ttf"
#else
#warning "really? please tell me if you are compiling on this OS"
#endif
#include "includes.h"
#include "font.h"
#include "ui.h"
SDL_Window* mainWindow;
SDL_Renderer* mainRenderer;
SDL_Event* event;
int mouseX;
int mouseY;
unsigned int mouseB;
unsigned int mouseBold;
SDL_Color color;
bool willquit;
uisystem* ui;
font* mainFont;
int curview;
const char* viewname[6]={"Graphics","Audio","Entity Types","Scenes","Functions"};
struct graphic {
string name;
int id;
int width;
int height;
int originX, originY;
int subgraphics;
bool background;
unsigned char** data;
int colmode;
unsigned char** colmask;
};
struct audio {
string name;
int id;
int size;
float* data;
int finaltype;
};
struct etype {
string name;
int id;
int initialgraphic;
int initialsubgraphic;
int parent;
int category;
std::vector<string> eventcode;
string headercode;
};
struct viewport {
SDL_Rect view, port;
float viewangle, portangle;
};
struct scene {
string name;
int width;
int height;
bool freeze;
std::vector<viewport> viewports;
};
struct function {
string name;
string code;
};
std::vector<graphic> graphics;
std::vector<audio> sounds;
std::vector<etype> etypes;
std::vector<scene> scenes;
void doNothing(){
printf("hello world!\n");
}
void drawscreen() {
SDL_RenderDrawLine(mainRenderer,0,32,1024,32);
SDL_RenderDrawLine(mainRenderer,256,32,256,600);
mainFont->drawf(128,40,color,1,1,"%s List",viewname[curview]);
}
void goGraphicsView() {
curview=0;
}
void goAudioView() {
curview=1;
}
void goETypesView() {
curview=2;
}
void goScenesView() {
curview=3;
}
void goFunctionsView() {
curview=4;
}
int main() {
willquit=false;
// init everything
SDL_Init(SDL_INIT_VIDEO);
TTF_Init();
ui=new uisystem;
event=new SDL_Event;
string title;
title="LowerTriad";
mainWindow=SDL_CreateWindow(title.c_str(),0,0,1024,600,SDL_WINDOW_RESIZABLE);
if (!mainWindow) {
printf("i'm sorry, but window can't be created: %s\n",SDL_GetError());
return 1;
}
mainRenderer=SDL_CreateRenderer(mainWindow,-1,SDL_RENDERER_ACCELERATED|SDL_RENDERER_PRESENTVSYNC);
// initialize UI
mainFont=new font;
mainFont->setrenderer(mainRenderer);
if (!mainFont->load(FONT,14)) {
printf("can't load font, which means this application is going to crash now...\n");
}
ui->setrenderer(mainRenderer);
color.r=0; color.g=255; color.b=0; color.a=255;
ui->setfont(mainFont);
ui->addbutton(0,0,48,22,"Prepare","Prepare CMake project",color,color,doNothing);
ui->addbutton(48,0,40,22,"Build","Build game",color,color,doNothing);
ui->addbutton(100,0,32,22,"Run","Run compiled game",color,color,doNothing);
ui->addbutton(132,0,56,22,"Package","Create package",color,color,doNothing);
ui->addbutton(200,0,64,22,"Graphics","",color,color,goGraphicsView);
ui->addbutton(264,0,50,22,"Audio","",color,color,goAudioView);
ui->addbutton(314,0,80,22,"EntityTypes","",color,color,goETypesView);
ui->addbutton(394,0,50,22,"Scenes","",color,color,goScenesView);
ui->addbutton(444,0,72,22,"Functions","",color,color,goFunctionsView);
ui->setmouse(&mouseX,&mouseY,&mouseB,&mouseBold);
while (1) {
// check events
while (SDL_PollEvent(event)) {
if (event->type==SDL_QUIT) {
willquit=true;
}
}
SDL_SetRenderDrawColor(mainRenderer,0,0,0,0);
SDL_RenderClear(mainRenderer);
mouseBold=mouseB;
mouseB=SDL_GetMouseState(&mouseX, &mouseY);
ui->drawall();
drawscreen();
SDL_RenderPresent(mainRenderer);
if (willquit) {
break;
}
}
return 0;
}
<|endoftext|> |
<commit_before>#include <ros/ros.h>
#include <geometry_msgs/Twist.h>
#include <tf/transform_broadcaster.h>
#include <boost/bind.hpp>
#include <boost/lambda/lambda.hpp>
#include <sys/time.h>
#include "Comm.h"
#include <sensor_msgs/Imu.h>
#include <std_srvs/Trigger.h>
#include <stdexcept>
class CheckSumError : public std::logic_error {
public:
CheckSumError(const std::string &data) :
std::logic_error("Received the Invalid IMU Data: " + data)
{
}
};
float deg_to_rad(float deg) {
return deg / 180.0f * M_PI;
}
float rad_to_deg(float rad){
return rad * 180.0f / M_PI;
}
template<class T>
bool isInRange(T value, T max, T min){
return (value >= min) && (value <= max);
}
struct ImuData {
double angular_deg[3];
bool flag;
ImuData(){
for(int i=0; i < 2; i++){
angular_deg[i] = 0;
}
}
};
// 角度ごとにURGのデータを送信するためのサービス
class IMU {
private:
ros::Publisher imu_pub_;
ros::ServiceServer reset_service_;
ros::ServiceServer carivrate_service_;
CComm* usb_;
double gyro_unit_;
double acc_unit_;
std::string port_name_, imu_frame_;
int baudrate_;
ros::Rate loop_rate_;
int z_axis_dir_;
int y_axis_dir_;
ImuData getImuData(){
ImuData data;
char command[2] = {0};
char command2[50] = {0};
char temp[6];
unsigned long int sum = 0;
const float temp_unit = 0.00565;
sprintf(command, "o");
usb_->Send(command, strlen(command));
ros::Duration(0.03).sleep();
usb_->Recv(command2, 50);
ROS_INFO_STREAM("recv = " << command2);
if (command2[0] == '\0') {
data.flag = false;
return data;
}
data.flag = true;
memmove(temp,command2,4);
sum = sum ^ ((short)strtol(temp, NULL, 16));
data.angular_deg[0] = ((short)strtol(temp, NULL, 16)) * gyro_unit_;
memmove(temp,command2+4,4);
sum = sum ^ ((short)strtol(temp, NULL, 16));
data.angular_deg[1] = std::asin(((short)strtol(temp, NULL, 16)) * acc_unit_) * y_axis_dir_;
memmove(temp,command2+8,4);
sum = sum ^ ((short)strtol(temp, NULL, 16));
data.angular_deg[2] = ((short)strtol(temp, NULL, 16)) * gyro_unit_ * z_axis_dir_;
memmove(temp,command2+12,4);
if(sum != ((short)strtol(temp, NULL, 16))){
ROS_ERROR_STREAM("Recv Checksum: " << ((short)strtol(temp, NULL, 16)));
ROS_ERROR_STREAM("Calculate Checksum: " << sum);
throw CheckSumError(command2);
}
//while(data.angular_deg[2] < -180) data.angular_deg[2] += 180;
//while(data.angular_deg[2] > 180) data.angular_deg[2] -= 180;
return data;
}
public:
bool resetCallback(std_srvs::Trigger::Request &req,
std_srvs::Trigger::Response &res)
{
char command[2] = {0};
sprintf(command, "0");
usb_->Send(command, strlen(command));
sleep(1);
std::cout << "Gyro 0 Reset" << std::endl;
res.success = true;
res.message = "Successful reset angle, gyro angle be zero right now.";
return true;
}
bool caribrateCallback(std_srvs::Trigger::Request &req,
std_srvs::Trigger::Response &res)
{
char command[2] = {0};
std::cout << "Calibration" << std::endl;
sprintf(command, "a");
usb_->Send(command, strlen(command));
std::cout << "Calibrate start ";
for(int i=0; i<8; ++i) {
std::cout << ". ";
sleep(1);
}
res.success = true;
res.message = "ADIS driver is done with calibration.";
ROS_INFO_STREAM(res.message);
return true;
}
IMU(ros::NodeHandle node) :
imu_pub_(node.advertise<sensor_msgs::Imu>("imu", 10)),
reset_service_(node.advertiseService("imu_reset", &IMU::resetCallback, this)),
carivrate_service_(node.advertiseService("imu_caribrate", &IMU::caribrateCallback, this)),
gyro_unit_(0.00836181640625), acc_unit_(0.0008192),imu_frame_("imu_link"),
port_name_("/dev/ttyUSB0"), baudrate_(115200), loop_rate_(50), z_axis_dir_(-1), y_axis_dir_(-1)
{
ros::NodeHandle private_nh("~");
private_nh.getParam("port_name", port_name_);
private_nh.param<std::string>("imu_frame", imu_frame_, imu_frame_);
private_nh.param<double>("gyro_unit", gyro_unit_, gyro_unit_);
private_nh.param<double>("acc_unit", acc_unit_, acc_unit_);
private_nh.param<int>("baud_rate", baudrate_, baudrate_);
private_nh.param<int>("z_axis_dir", z_axis_dir_, z_axis_dir_);
private_nh.param<int>("y_axis_dir", y_axis_dir_, y_axis_dir_);
usb_ = new CComm(port_name_, baudrate_);
}
bool init() {
char command[2] = {0};
char command2[101] = {0};
//シリアルポートオープン
if (!usb_->Open()) {
std::cerr << "open error" << std::endl;
return false;
}
std::cout << "device open success" << std::endl;
sleep(1);
//コンフィギュレーション キャリブレーション
// if(m_calibration == true){
std::cout << "Calibration" << std::endl;
sprintf(command, "a");
usb_->Send(command, strlen(command));
std::cout << "send = " << command << std::endl;
for(int i=0; i<8; ++i) {
printf(". ");
sleep(1);
}
// }
//コンフィギュレーション リセット
// if(m_reset == true){
sprintf(command, "0");
usb_->Send(command, strlen(command)); //送信
std::cout << "send = " << command << std::endl;
sleep(1);
std::cout << "Gyro 0 Reset" << std::endl;
// }
usb_->Recv(command2, 100); //空読み バッファクリアが効かない?
usb_->ClearRecvBuf(); //バッファクリア
return true;
}
void run() {
double old_angular_z_deg = getImuData().angular_deg[2];
double angular_z_deg = 0;
unsigned short abnormal_count = 0;
while (ros::ok()) {
tf::Quaternion q;
sensor_msgs::Imu output_msg;
try{
ImuData data = getImuData();
if (data.flag == false){
usb_->Close();
if(!usb_->Open()) {
std::cerr << "reconnecting" << std::endl;
}
}else{
output_msg.header.frame_id = imu_frame_;
output_msg.header.stamp = ros::Time::now();
// ROS_INFO_STREAM("x_deg = " << data.angular_deg[0]);
ROS_INFO_STREAM("y_deg = " << rad_to_deg(data.angular_deg[1]));
ROS_INFO_STREAM("z_deg = " << data.angular_deg[2]);
if(!isInRange(std::abs(old_angular_z_deg), 180.0, 165.0) && !isInRange(std::abs(data.angular_deg[2]), 180.0, 165.0) &&
std::abs(old_angular_z_deg - data.angular_deg[2]) > 40 && abnormal_count < 4){
ROS_WARN_STREAM("Angle change too large: z = " << data.angular_deg[2]);
ROS_WARN_STREAM("old_z = " << old_angular_z_deg);
abnormal_count++;
continue;
}else{
abnormal_count = 0;
angular_z_deg = data.angular_deg[2];
}
q = tf::createQuaternionFromRPY(data.angular_deg[1], 0.0, deg_to_rad(angular_z_deg));
tf::quaternionTFToMsg(q, output_msg.orientation);
imu_pub_.publish(output_msg);
old_angular_z_deg = angular_z_deg;
}
}catch(const CheckSumError &e){
output_msg.header.stamp = ros::Time::now();
ROS_ERROR_STREAM(e.what());
continue;
}
ros::spinOnce();
//loop_rate.sleep();
}
}
};
int main(int argc, char * argv[])
{
ros::init(argc, argv, "imu_node");
ros::NodeHandle node;
IMU imu(node);
if(!imu.init()) return 1;
imu.run();
return 0;
}
<commit_msg>暫定的にPY角度を配信するようにした<commit_after>#include <ros/ros.h>
#include <geometry_msgs/Twist.h>
#include <tf/transform_broadcaster.h>
#include <boost/bind.hpp>
#include <boost/lambda/lambda.hpp>
#include <sys/time.h>
#include "Comm.h"
#include <sensor_msgs/Imu.h>
#include <std_msgs/Float64MultiArray.h>
#include <std_srvs/Trigger.h>
#include <stdexcept>
class CheckSumError : public std::logic_error {
public:
CheckSumError(const std::string &data) :
std::logic_error("Received the Invalid IMU Data: " + data)
{
}
};
float deg_to_rad(float deg) {
return deg / 180.0f * M_PI;
}
float rad_to_deg(float rad){
return rad * 180.0f / M_PI;
}
template<class T>
bool isInRange(T value, T max, T min){
return (value >= min) && (value <= max);
}
struct ImuData {
double angular_deg[3];
bool flag;
ImuData(){
for(int i=0; i < 2; i++){
angular_deg[i] = 0;
}
}
};
// 角度ごとにURGのデータを送信するためのサービス
class IMU {
private:
ros::Publisher imu_pub_;
ros::Publisher imu_rpy_pub_;
ros::ServiceServer reset_service_;
ros::ServiceServer carivrate_service_;
CComm* usb_;
double gyro_unit_;
double acc_unit_;
std::string port_name_, imu_frame_;
int baudrate_;
ros::Rate loop_rate_;
int z_axis_dir_;
int y_axis_dir_;
ImuData getImuData(){
ImuData data;
char command[2] = {0};
char command2[50] = {0};
char temp[6];
unsigned long int sum = 0;
const float temp_unit = 0.00565;
sprintf(command, "o");
usb_->Send(command, strlen(command));
ros::Duration(0.03).sleep();
usb_->Recv(command2, 50);
ROS_INFO_STREAM("recv = " << command2);
if (command2[0] == '\0') {
data.flag = false;
return data;
}
data.flag = true;
memmove(temp,command2,4);
sum = sum ^ ((short)strtol(temp, NULL, 16));
data.angular_deg[0] = ((short)strtol(temp, NULL, 16)) * gyro_unit_;
memmove(temp,command2+4,4);
sum = sum ^ ((short)strtol(temp, NULL, 16));
data.angular_deg[1] = std::asin(((short)strtol(temp, NULL, 16)) * acc_unit_) * y_axis_dir_;
memmove(temp,command2+8,4);
sum = sum ^ ((short)strtol(temp, NULL, 16));
data.angular_deg[2] = ((short)strtol(temp, NULL, 16)) * gyro_unit_ * z_axis_dir_;
memmove(temp,command2+12,4);
if(sum != ((short)strtol(temp, NULL, 16))){
ROS_ERROR_STREAM("Recv Checksum: " << ((short)strtol(temp, NULL, 16)));
ROS_ERROR_STREAM("Calculate Checksum: " << sum);
throw CheckSumError(command2);
}
//while(data.angular_deg[2] < -180) data.angular_deg[2] += 180;
//while(data.angular_deg[2] > 180) data.angular_deg[2] -= 180;
return data;
}
public:
bool resetCallback(std_srvs::Trigger::Request &req,
std_srvs::Trigger::Response &res)
{
char command[2] = {0};
sprintf(command, "0");
usb_->Send(command, strlen(command));
sleep(1);
std::cout << "Gyro 0 Reset" << std::endl;
res.success = true;
res.message = "Successful reset angle, gyro angle be zero right now.";
return true;
}
bool caribrateCallback(std_srvs::Trigger::Request &req,
std_srvs::Trigger::Response &res)
{
char command[2] = {0};
std::cout << "Calibration" << std::endl;
sprintf(command, "a");
usb_->Send(command, strlen(command));
std::cout << "Calibrate start ";
for(int i=0; i<8; ++i) {
std::cout << ". ";
sleep(1);
}
res.success = true;
res.message = "ADIS driver is done with calibration.";
ROS_INFO_STREAM(res.message);
return true;
}
IMU(ros::NodeHandle node) :
imu_pub_(node.advertise<sensor_msgs::Imu>("imu", 10)),
imu_rpy_pub_(node.advertise<std_msgs::Float64MultiArray>("imu_rpy",10)),
reset_service_(node.advertiseService("imu_reset", &IMU::resetCallback, this)),
carivrate_service_(node.advertiseService("imu_caribrate", &IMU::caribrateCallback, this)),
gyro_unit_(0.00836181640625), acc_unit_(0.0008192),imu_frame_("imu_link"),
port_name_("/dev/ttyUSB0"), baudrate_(115200), loop_rate_(50), z_axis_dir_(-1), y_axis_dir_(-1)
{
ros::NodeHandle private_nh("~");
private_nh.getParam("port_name", port_name_);
private_nh.param<std::string>("imu_frame", imu_frame_, imu_frame_);
private_nh.param<double>("gyro_unit", gyro_unit_, gyro_unit_);
private_nh.param<double>("acc_unit", acc_unit_, acc_unit_);
private_nh.param<int>("baud_rate", baudrate_, baudrate_);
private_nh.param<int>("z_axis_dir", z_axis_dir_, z_axis_dir_);
private_nh.param<int>("y_axis_dir", y_axis_dir_, y_axis_dir_);
usb_ = new CComm(port_name_, baudrate_);
}
bool init() {
char command[2] = {0};
char command2[101] = {0};
//シリアルポートオープン
if (!usb_->Open()) {
std::cerr << "open error" << std::endl;
return false;
}
std::cout << "device open success" << std::endl;
sleep(1);
//コンフィギュレーション キャリブレーション
// if(m_calibration == true){
std::cout << "Calibration" << std::endl;
sprintf(command, "a");
usb_->Send(command, strlen(command));
std::cout << "send = " << command << std::endl;
for(int i=0; i<8; ++i) {
printf(". ");
sleep(1);
}
// }
//コンフィギュレーション リセット
// if(m_reset == true){
sprintf(command, "0");
usb_->Send(command, strlen(command)); //送信
std::cout << "send = " << command << std::endl;
sleep(1);
std::cout << "Gyro 0 Reset" << std::endl;
// }
usb_->Recv(command2, 100); //空読み バッファクリアが効かない?
usb_->ClearRecvBuf(); //バッファクリア
return true;
}
void run() {
double old_angular_z_deg = getImuData().angular_deg[2];
double angular_z_deg = 0;
unsigned short abnormal_count = 0;
while (ros::ok()) {
tf::Quaternion q;
sensor_msgs::Imu output_msg;
std_msgs::Float64MultiArray output_rpy;
try{
ImuData data = getImuData();
if (data.flag == false){
usb_->Close();
if(!usb_->Open()) {
std::cerr << "reconnecting" << std::endl;
}
}else{
output_msg.header.frame_id = imu_frame_;
output_msg.header.stamp = ros::Time::now();
// ROS_INFO_STREAM("x_deg = " << data.angular_deg[0]);
ROS_INFO_STREAM("y_deg = " << rad_to_deg(data.angular_deg[1]));
ROS_INFO_STREAM("z_deg = " << data.angular_deg[2]);
if(!isInRange(std::abs(old_angular_z_deg), 180.0, 165.0) && !isInRange(std::abs(data.angular_deg[2]), 180.0, 165.0) &&
std::abs(old_angular_z_deg - data.angular_deg[2]) > 40 && abnormal_count < 4){
ROS_WARN_STREAM("Angle change too large: z = " << data.angular_deg[2]);
ROS_WARN_STREAM("old_z = " << old_angular_z_deg);
abnormal_count++;
continue;
}else{
abnormal_count = 0;
angular_z_deg = data.angular_deg[2];
}
output_rpy.data.push_back(data.angular_deg[1]);
output_rpy.data.push_back(deg_to_rad(angular_z_deg));
q = tf::createQuaternionFromRPY(data.angular_deg[1], 0.0, deg_to_rad(angular_z_deg));
tf::quaternionTFToMsg(q, output_msg.orientation);
imu_rpy_pub_.publish(output_rpy);
imu_pub_.publish(output_msg);
old_angular_z_deg = angular_z_deg;
}
}catch(const CheckSumError &e){
output_msg.header.stamp = ros::Time::now();
ROS_ERROR_STREAM(e.what());
continue;
}
ros::spinOnce();
//loop_rate.sleep();
}
}
};
int main(int argc, char * argv[])
{
ros::init(argc, argv, "imu_node");
ros::NodeHandle node;
IMU imu(node);
if(!imu.init()) return 1;
imu.run();
return 0;
}
<|endoftext|> |
<commit_before>/*
* C++ wrappers for libevent.
*
* author: Max Kellermann <mk@cm4all.com>
*/
#ifndef EVENT_BASE_HXX
#define EVENT_BASE_HXX
#include <event.h>
class EventBase {
struct event_base *event_base;
public:
EventBase():event_base(::event_init()) {}
~EventBase() {
::event_base_free(event_base);
}
EventBase(const EventBase &other) = delete;
EventBase &operator=(const EventBase &other) = delete;
struct event_base *Get() {
return event_base;
}
void Reinit() {
event_reinit(event_base);
}
void Dispatch() {
::event_base_dispatch(event_base);
}
void Break() {
::event_base_loopbreak(event_base);
}
};
#endif
<commit_msg>event/Base: add method LoopOnce()<commit_after>/*
* C++ wrappers for libevent.
*
* author: Max Kellermann <mk@cm4all.com>
*/
#ifndef EVENT_BASE_HXX
#define EVENT_BASE_HXX
#include <event.h>
class EventBase {
struct event_base *event_base;
public:
EventBase():event_base(::event_init()) {}
~EventBase() {
::event_base_free(event_base);
}
EventBase(const EventBase &other) = delete;
EventBase &operator=(const EventBase &other) = delete;
struct event_base *Get() {
return event_base;
}
void Reinit() {
event_reinit(event_base);
}
void Dispatch() {
::event_base_dispatch(event_base);
}
bool LoopOnce(bool non_block=false) {
int flags = EVLOOP_ONCE;
if (non_block)
flags |= EVLOOP_NONBLOCK;
return ::event_loop(flags) == 0;
}
void Break() {
::event_base_loopbreak(event_base);
}
};
#endif
<|endoftext|> |
<commit_before>#include "facenet_tf.h"
#include <dirent.h>
#include <string.h>
Ptr<ml::KNearest> k_nearest(ml::KNearest::create());
Ptr<ml::ANN_MLP> ann;
#define K_VALUE 1
#define N_LAYERS 3
FacenetClassifier::FacenetClassifier (string operation, string model_path, string svm_model_path, string labels_file_path) {
this->operation = operation;
this->model_path = model_path;
this->svm_model_path = svm_model_path;
this->labels_file_path = labels_file_path;
ReadBinaryProto(tensorflow::Env::Default(), model_path.c_str(), &graph_def);
tensorflow::SessionOptions options;
tensorflow::NewSession (options, &session);
session->Create (graph_def);
}
void FacenetClassifier::save_labels () {
cout << "Saving Labels To " << labels_file_path << endl;
labels_file.open (labels_file_path, fstream::out);
for (Label label: class_labels) {
labels_file << label.class_number << " " << label.class_name << endl;
}
labels_file.close ();
cout << "Done Saving labels" << endl;
}
void FacenetClassifier::load_labels () {
class_labels.clear ();
labels_file.open (labels_file_path, fstream::in);
int count = 0;
while (true) {
if (labels_file.eof())
break;
Label label;
labels_file >> label.class_number >> label.class_name;
class_labels.push_back (label);
count++;
}
labels_file.close ();
cout << class_labels.size() << endl;
}
void FacenetClassifier::parse_images_path (string directory_path, int depth) {
cout << "Parsing Directory: " << directory_path << endl;
DIR *dir;
struct dirent *entry;
static int class_count = -1;
string class_name;
string file_name, file_path;
if ((dir = opendir (directory_path.c_str())) != NULL) {
while ((entry = readdir (dir)) != NULL) {
if (entry->d_type == DT_DIR && strcmp (entry->d_name, ".") !=0 && strcmp (entry->d_name, "..") !=0) {
class_name = string (entry->d_name);
class_count++;
parse_images_path (directory_path + "/" + class_name, depth+1);
Label label;
label.class_number = class_count;
label.class_name = class_name;
class_labels.push_back(label);
}
else if (entry->d_type != DT_DIR) {
file_name = string (entry->d_name);
file_path = directory_path + "/" + file_name;
Mat image = imread (file_path);
if (image.empty() || image.rows !=160 || image.cols !=160)
cout << "Ignoring Image " + file_path << endl;
else {
cout << file_path << ":" << class_count << endl;
input_images.push_back (image);
output_labels.push_back (class_count); //For Training
mat_training_ints.push_back (class_count);
input_files.push_back (file_path); //For Classification
}
}
}
closedir (dir);
}
}
void FacenetClassifier::create_input_tensor () {
cout << "Using " << input_images.size() << " images" << endl;
Tensor input_tensor(DT_FLOAT, TensorShape({(int) input_images.size(), 160, 160, 3}));
// get pointer to memory for that Tensor
float *p = input_tensor.flat<float>().data();
int i;
for (i = 0; i < input_images.size(); i++) {
// create a "fake" cv::Mat from it
Mat camera_image(160 , 160, CV_32FC3, p + i*160*160*3);
input_images[i].convertTo(camera_image, CV_32FC3);
}
cout << input_tensor.DebugString() << endl;
this->input_tensor = input_tensor;
}
void FacenetClassifier::create_phase_tensor () {
tensorflow::Tensor phase_tensor(tensorflow::DT_BOOL, tensorflow::TensorShape());
phase_tensor.scalar<bool>()() = true;
this->phase_tensor = phase_tensor;
}
void FacenetClassifier::run () {
string input_layer = "input:0";
string phase_train_layer = "phase_train:0";
string output_layer = "embeddings:0";
std::vector<tensorflow::Tensor> outputs;
std::vector<std::pair<string, tensorflow::Tensor>> feed_dict = {
{input_layer, input_tensor},
{phase_train_layer, phase_tensor},
};
cout << "Input Tensor: " << input_tensor.DebugString() << endl;
Status run_status = session->Run(feed_dict, {output_layer}, {} , &outputs);
if (!run_status.ok()) {
LOG(ERROR) << "Running model failed: " << run_status << "\n";
return;
}
cout << "Output: " << outputs[0].DebugString() << endl;
float *p = outputs[0].flat<float>().data();
Mat output_mat;
for (int i = 0; i < input_images.size(); i++) {
Mat mat_row (cv::Size (128, 1), CV_32F, p + i*128, Mat::AUTO_STEP);
Mat mat_row_float, mat_tensor_reshaped;
mat_row.convertTo (mat_row_float, CV_32FC3);
mat_tensor_reshaped = mat_row_float.reshape (0,1);
mat_training_tensors.push_back (mat_tensor_reshaped);
if (i == 0)
output_mat = mat_row;
else
vconcat (output_mat, mat_row, output_mat);
}
this->output_mat = output_mat;
}
void FacenetClassifier::save_mlp () {
ann = ann->create ();
Mat train_data = mat_training_tensors;
Mat train_labels = mat_training_ints;
int nfeatures = mat_training_tensors.cols;
cout << "Labels: " << train_labels << endl;
int nclasses = class_labels.size();
cout << "Classes: " << nclasses << endl;
Mat_<int> layers(4,1);
layers(0) = nfeatures; // input
layers(1) = nclasses * 8; // hidden
layers(2) = nclasses * 4; // hidden
layers(3) = nclasses; // output, 1 pin per class.
ann->setLayerSizes(layers);
ann->setActivationFunction(ml::ANN_MLP::SIGMOID_SYM,1,1);
ann->setTermCriteria(TermCriteria(TermCriteria::MAX_ITER+TermCriteria::EPS, 300, 0.0001));
ann->setTrainMethod(ml::ANN_MLP::BACKPROP, 0.0001);
// ann requires "one-hot" encoding of class labels:
Mat train_classes = Mat::zeros(train_data.rows, nclasses, CV_32FC1);
for(int i=0; i<train_classes.rows; i++)
{
cout << i << ":" << train_labels.at<int>(i) << endl;
train_classes.at<float>(i, train_labels.at<int>(i)) = 1.f;
}
cerr << train_data.size() << " " << train_classes.size() << endl;
ann->train(train_data, ml::ROW_SAMPLE, train_classes);
ann->save (svm_model_path);
}
void FacenetClassifier::load_mlp () {
ann = ann->load (svm_model_path);
}
void FacenetClassifier::predict_mlp_labels () {
float prediction;
for (int i = 0; i < input_images.size(); i++) {
Mat input_mat;
Mat result;
output_mat.row(i).convertTo (input_mat, CV_32F);
prediction = ann->predict (input_mat, result);
cout << input_files[i] << " " << prediction << " " << result.size() << " " << result.at<float>(0, prediction) << endl;
/*Point maxP;
minMaxLoc(result, 0,0,0,&maxP);
prediction = maxP.x;
cout << input_files[i] <<" " << prediction << endl;*/
}
}
void FacenetClassifier::save_svm () {
svm = SVM::create();
svm->setKernel(SVM::LINEAR);
svm->train(output_mat, ROW_SAMPLE, output_labels);
svm->save(svm_model_path);
cout << "Training Complete" << endl;
}
void FacenetClassifier::save_knn () {
Mat mat_training_floats;
mat_training_ints.convertTo(mat_training_floats, CV_32FC3);
FileStorage training_labels_file ("labels.xml", FileStorage::WRITE);
training_labels_file << "classifications" << mat_training_floats;
training_labels_file.release ();
FileStorage training_tensors_file (svm_model_path, FileStorage::WRITE);
training_tensors_file << "images" << mat_training_tensors;
training_tensors_file.release ();
}
void FacenetClassifier::load_svm () {
svm = Algorithm::load<SVM>(svm_model_path);
cout << "SVM Model Loaded" << endl;
}
void FacenetClassifier::predict_labels () {
Mat svm_response;
svm->predict (output_mat, svm_response);
//svm->predict (output_mat, svm_response);
cout << "SVM Response: " << svm_response << endl;
for (int i = 0 ; i < svm_response.rows; i++) {
//int class_number = (int) svm_response.at<float>(i,0);
cout << input_files[i] << ": " << svm_response.at<float>(i) << endl;
//cout << input_files[i] << ": " << class_labels[class_number-1].class_name << endl;
}
}
void FacenetClassifier::load_knn () {
FileStorage labels_knn("labels.xml", FileStorage::READ);
labels_knn["classifications"] >> mat_training_ints;
labels_knn.release();
cout << "KNN Labels: " << mat_training_ints.size() << endl;
cout << "Reading " << model_path << endl;
FileStorage tensors (svm_model_path, FileStorage::READ);
tensors["images"] >> mat_training_tensors;
tensors.release();
cout << "KNN Tensors: " << mat_training_tensors.size() << endl;
k_nearest->setDefaultK (1);
cout << "Train: " << k_nearest->train (mat_training_tensors, ml::ROW_SAMPLE, mat_training_ints) << endl;
}
void FacenetClassifier::predict_knn_labels () {
Mat current_class(0, 0, CV_32F);
Mat current_response(0, 0, CV_32F);
Mat current_distance (0, 0, CV_32F);
float current_class_float, response, distance;
float prediction;
for (int i = 0; i < input_images.size(); i++) {
Mat input_mat, input_mat_flattened;
mat_training_tensors.row(i).convertTo (input_mat, CV_32FC3);
input_mat_flattened = input_mat.reshape (0,1);
prediction = k_nearest->findNearest (input_mat_flattened, K_VALUE, current_class, current_response, current_distance);
current_class_float = (float) current_class.at<float>(0,0);
response = (float) current_response.at<float>(0,0);
distance = (float) current_distance.at<float>(0,0);
cout << mat_training_tensors.row(i).size() << " " << prediction << " " << input_files[i] << ": " << current_class_float << " " << distance << endl;
}
}
<commit_msg>Bug Fix To KNN Prediction Function<commit_after>#include "facenet_tf.h"
#include <dirent.h>
#include <string.h>
Ptr<ml::KNearest> k_nearest(ml::KNearest::create());
Ptr<ml::ANN_MLP> ann;
#define K_VALUE 1
#define N_LAYERS 3
FacenetClassifier::FacenetClassifier (string operation, string model_path, string svm_model_path, string labels_file_path) {
this->operation = operation;
this->model_path = model_path;
this->svm_model_path = svm_model_path;
this->labels_file_path = labels_file_path;
ReadBinaryProto(tensorflow::Env::Default(), model_path.c_str(), &graph_def);
tensorflow::SessionOptions options;
tensorflow::NewSession (options, &session);
session->Create (graph_def);
}
void FacenetClassifier::save_labels () {
cout << "Saving Labels To " << labels_file_path << endl;
labels_file.open (labels_file_path, fstream::out);
for (Label label: class_labels) {
labels_file << label.class_number << " " << label.class_name << endl;
}
labels_file.close ();
cout << "Done Saving labels" << endl;
}
void FacenetClassifier::load_labels () {
class_labels.clear ();
labels_file.open (labels_file_path, fstream::in);
int count = 0;
while (true) {
if (labels_file.eof())
break;
Label label;
labels_file >> label.class_number >> label.class_name;
class_labels.push_back (label);
count++;
}
labels_file.close ();
cout << class_labels.size() << endl;
}
void FacenetClassifier::parse_images_path (string directory_path, int depth) {
cout << "Parsing Directory: " << directory_path << endl;
DIR *dir;
struct dirent *entry;
static int class_count = -1;
string class_name;
string file_name, file_path;
if ((dir = opendir (directory_path.c_str())) != NULL) {
while ((entry = readdir (dir)) != NULL) {
if (entry->d_type == DT_DIR && strcmp (entry->d_name, ".") !=0 && strcmp (entry->d_name, "..") !=0) {
class_name = string (entry->d_name);
class_count++;
parse_images_path (directory_path + "/" + class_name, depth+1);
Label label;
label.class_number = class_count;
label.class_name = class_name;
class_labels.push_back(label);
}
else if (entry->d_type != DT_DIR) {
file_name = string (entry->d_name);
file_path = directory_path + "/" + file_name;
Mat image = imread (file_path);
if (image.empty() || image.rows !=160 || image.cols !=160)
cout << "Ignoring Image " + file_path << endl;
else {
cout << file_path << ":" << class_count << endl;
input_images.push_back (image);
output_labels.push_back (class_count); //For Training
mat_training_ints.push_back (class_count);
input_files.push_back (file_path); //For Classification
}
}
}
closedir (dir);
}
}
void FacenetClassifier::create_input_tensor () {
cout << "Using " << input_images.size() << " images" << endl;
Tensor input_tensor(DT_FLOAT, TensorShape({(int) input_images.size(), 160, 160, 3}));
// get pointer to memory for that Tensor
float *p = input_tensor.flat<float>().data();
int i;
for (i = 0; i < input_images.size(); i++) {
// create a "fake" cv::Mat from it
Mat camera_image(160 , 160, CV_32FC3, p + i*160*160*3);
input_images[i].convertTo(camera_image, CV_32FC3);
}
cout << input_tensor.DebugString() << endl;
this->input_tensor = input_tensor;
}
void FacenetClassifier::create_phase_tensor () {
tensorflow::Tensor phase_tensor(tensorflow::DT_BOOL, tensorflow::TensorShape());
phase_tensor.scalar<bool>()() = true;
this->phase_tensor = phase_tensor;
}
void FacenetClassifier::run () {
string input_layer = "input:0";
string phase_train_layer = "phase_train:0";
string output_layer = "embeddings:0";
std::vector<tensorflow::Tensor> outputs;
std::vector<std::pair<string, tensorflow::Tensor>> feed_dict = {
{input_layer, input_tensor},
{phase_train_layer, phase_tensor},
};
cout << "Input Tensor: " << input_tensor.DebugString() << endl;
Status run_status = session->Run(feed_dict, {output_layer}, {} , &outputs);
if (!run_status.ok()) {
LOG(ERROR) << "Running model failed: " << run_status << "\n";
return;
}
cout << "Output: " << outputs[0].DebugString() << endl;
float *p = outputs[0].flat<float>().data();
Mat output_mat;
for (int i = 0; i < input_images.size(); i++) {
Mat mat_row (cv::Size (128, 1), CV_32F, p + i*128, Mat::AUTO_STEP);
Mat mat_row_float, mat_tensor_reshaped;
mat_row.convertTo (mat_row_float, CV_32FC3);
mat_tensor_reshaped = mat_row_float.reshape (0,1);
mat_training_tensors.push_back (mat_tensor_reshaped);
if (i == 0)
output_mat = mat_row;
else
vconcat (output_mat, mat_row, output_mat);
}
this->output_mat = output_mat;
}
void FacenetClassifier::save_mlp () {
ann = ann->create ();
Mat train_data = mat_training_tensors;
Mat train_labels = mat_training_ints;
int nfeatures = mat_training_tensors.cols;
cout << "Labels: " << train_labels << endl;
int nclasses = class_labels.size();
cout << "Classes: " << nclasses << endl;
Mat_<int> layers(4,1);
layers(0) = nfeatures; // input
layers(1) = nclasses * 8; // hidden
layers(2) = nclasses * 4; // hidden
layers(3) = nclasses; // output, 1 pin per class.
ann->setLayerSizes(layers);
ann->setActivationFunction(ml::ANN_MLP::SIGMOID_SYM,1,1);
ann->setTermCriteria(TermCriteria(TermCriteria::MAX_ITER+TermCriteria::EPS, 300, 0.0001));
ann->setTrainMethod(ml::ANN_MLP::BACKPROP, 0.0001);
// ann requires "one-hot" encoding of class labels:
Mat train_classes = Mat::zeros(train_data.rows, nclasses, CV_32FC1);
for(int i=0; i<train_classes.rows; i++)
{
cout << i << ":" << train_labels.at<int>(i) << endl;
train_classes.at<float>(i, train_labels.at<int>(i)) = 1.f;
}
cerr << train_data.size() << " " << train_classes.size() << endl;
ann->train(train_data, ml::ROW_SAMPLE, train_classes);
ann->save (svm_model_path);
}
void FacenetClassifier::load_mlp () {
ann = ann->load (svm_model_path);
}
void FacenetClassifier::predict_mlp_labels () {
float prediction;
for (int i = 0; i < input_images.size(); i++) {
Mat input_mat;
Mat result;
output_mat.row(i).convertTo (input_mat, CV_32F);
prediction = ann->predict (input_mat, result);
cout << input_files[i] << " " << prediction << " " << result.size() << " " << result.at<float>(0, prediction) << endl;
/*Point maxP;
minMaxLoc(result, 0,0,0,&maxP);
prediction = maxP.x;
cout << input_files[i] <<" " << prediction << endl;*/
}
}
void FacenetClassifier::save_svm () {
svm = SVM::create();
svm->setKernel(SVM::LINEAR);
svm->train(output_mat, ROW_SAMPLE, output_labels);
svm->save(svm_model_path);
cout << "Training Complete" << endl;
}
void FacenetClassifier::save_knn () {
Mat mat_training_floats;
mat_training_ints.convertTo(mat_training_floats, CV_32FC3);
FileStorage training_labels_file ("labels.xml", FileStorage::WRITE);
training_labels_file << "classifications" << mat_training_floats;
training_labels_file.release ();
FileStorage training_tensors_file (svm_model_path, FileStorage::WRITE);
training_tensors_file << "images" << mat_training_tensors;
training_tensors_file.release ();
}
void FacenetClassifier::load_svm () {
svm = Algorithm::load<SVM>(svm_model_path);
cout << "SVM Model Loaded" << endl;
}
void FacenetClassifier::predict_labels () {
Mat svm_response;
svm->predict (output_mat, svm_response);
//svm->predict (output_mat, svm_response);
cout << "SVM Response: " << svm_response << endl;
for (int i = 0 ; i < svm_response.rows; i++) {
//int class_number = (int) svm_response.at<float>(i,0);
cout << input_files[i] << ": " << svm_response.at<float>(i) << endl;
//cout << input_files[i] << ": " << class_labels[class_number-1].class_name << endl;
}
}
void FacenetClassifier::load_knn () {
FileStorage labels_knn("labels.xml", FileStorage::READ);
labels_knn["classifications"] >> mat_training_ints;
labels_knn.release();
cout << "KNN Labels: " << mat_training_ints.size() << endl;
cout << "Reading " << model_path << endl;
FileStorage tensors (svm_model_path, FileStorage::READ);
tensors["images"] >> mat_training_tensors;
tensors.release();
cout << "KNN Tensors: " << mat_training_tensors.size() << endl;
k_nearest->setDefaultK (1);
cout << "Train: " << k_nearest->train (mat_training_tensors, ml::ROW_SAMPLE, mat_training_ints) << endl;
}
void FacenetClassifier::predict_knn_labels () {
Mat current_class(0, 0, CV_32F);
Mat current_response(0, 0, CV_32F);
Mat current_distance (0, 0, CV_32F);
float current_class_float, response, distance;
float prediction;
for (int i = 0; i < input_images.size(); i++) {
Mat input_mat, input_mat_flattened;
output_mat.row(i).convertTo (input_mat, CV_32FC3);
input_mat_flattened = input_mat.reshape (0,1);
prediction = k_nearest->findNearest (input_mat_flattened, K_VALUE, current_class, current_response, current_distance);
current_class_float = (float) current_class.at<float>(0,0);
response = (float) current_response.at<float>(0,0);
distance = (float) current_distance.at<float>(0,0);
cout << mat_training_tensors.row(i).size() << " " << prediction << " " << input_files[i] << ": " << current_class_float << " " << distance << endl;
}
}
<|endoftext|> |
<commit_before>/**************************************************************************
* Copyright(c) 1998-1999, 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. *
**************************************************************************/
///////////////////////////////////////////////////////////////////////////////
// //
// ANALYSIS task to perrorm TPC calibration //
// //
///////////////////////////////////////////////////////////////////////////////
#include "AliTPCAnalysisTaskcalib.h"
#include "TChain.h"
#include "AliTPCcalibBase.h"
#include "AliESDEvent.h"
#include "AliESDfriend.h"
#include "AliESDtrack.h"
#include "AliESDfriendTrack.h"
#include "AliTPCseed.h"
#include "AliESDInputHandler.h"
#include "AliAnalysisManager.h"
ClassImp(AliTPCAnalysisTaskcalib)
AliTPCAnalysisTaskcalib::AliTPCAnalysisTaskcalib()
:AliAnalysisTask(),
fCalibJobs(0),
fESD(0),
fESDfriend(0),
fDebugOutputPath()
{
//
// default constructor
//
}
AliTPCAnalysisTaskcalib::AliTPCAnalysisTaskcalib(const char *name)
:AliAnalysisTask(name,""),
fCalibJobs(0),
fESD(0),
fESDfriend(0),
fDebugOutputPath()
{
//
// Constructor
//
DefineInput(0, TChain::Class());
DefineOutput(0, TObjArray::Class());
fCalibJobs = new TObjArray(0);
fCalibJobs->SetOwner(kFALSE);
}
AliTPCAnalysisTaskcalib::~AliTPCAnalysisTaskcalib() {
//
// destructor
//
printf("AliTPCAnalysisTaskcalib::~AliTPCAnalysisTaskcalib");
//fCalibJobs->Delete();
}
void AliTPCAnalysisTaskcalib::Exec(Option_t *) {
//
// Exec function
// Loop over tracks and call Process function
if (!fESD) {
//Printf("ERROR: fESD not available");
return;
}
fESDfriend=static_cast<AliESDfriend*>(fESD->FindListObject("AliESDfriend"));
if (!fESDfriend) {
//Printf("ERROR: fESDfriend not available");
return;
}
Int_t n=fESD->GetNumberOfTracks();
Process(fESD);
Int_t run = fESD->GetRunNumber();
for (Int_t i=0;i<n;++i) {
AliESDfriendTrack *friendTrack=fESDfriend->GetTrack(i);
AliESDtrack *track=fESD->GetTrack(i);
TObject *calibObject=0;
AliTPCseed *seed=0;
for (Int_t j=0;(calibObject=friendTrack->GetCalibObject(j));++j)
if ((seed=dynamic_cast<AliTPCseed*>(calibObject)))
break;
if (track) Process(track, run);
if (seed)
Process(seed);
}
PostData(0,fCalibJobs);
}
void AliTPCAnalysisTaskcalib::ConnectInputData(Option_t *) {
//
//
//
TTree* tree=dynamic_cast<TTree*>(GetInputData(0));
if (!tree) {
//Printf("ERROR: Could not read chain from input slot 0");
}
else {
AliESDInputHandler *esdH = dynamic_cast<AliESDInputHandler*> (AliAnalysisManager::GetAnalysisManager()->GetInputEventHandler());
if (!esdH) {
//Printf("ERROR: Could not get ESDInputHandler");
}
else {
fESD = esdH->GetEvent();
//Printf("*** CONNECTED NEW EVENT ****");
}
}
}
void AliTPCAnalysisTaskcalib::CreateOutputObjects() {
//
//
//
}
void AliTPCAnalysisTaskcalib::Terminate(Option_t */*option*/) {
//
// Terminate
//
AliTPCcalibBase *job=0;
Int_t njobs = fCalibJobs->GetEntriesFast();
for (Int_t i=0;i<njobs;i++){
job = (AliTPCcalibBase*)fCalibJobs->UncheckedAt(i);
if (job) job->Terminate();
}
}
void AliTPCAnalysisTaskcalib::FinishTaskOutput()
{
//
// According description in AliAnalisysTask this method is call
// on the slaves before sending data
//
Terminate("slave");
RegisterDebugOutput();
}
void AliTPCAnalysisTaskcalib::Process(AliESDEvent *event) {
//
// Process ESD event
//
AliTPCcalibBase *job=0;
Int_t njobs = fCalibJobs->GetEntriesFast();
for (Int_t i=0;i<njobs;i++){
job = (AliTPCcalibBase*)fCalibJobs->UncheckedAt(i);
if (job) job->Process(event);
}
}
void AliTPCAnalysisTaskcalib::Process(AliTPCseed *track) {
//
// Process TPC track
//
AliTPCcalibBase *job=0;
Int_t njobs = fCalibJobs->GetEntriesFast();
for (Int_t i=0;i<njobs;i++){
job = (AliTPCcalibBase*)fCalibJobs->UncheckedAt(i);
if (job) job->Process(track);
}
}
void AliTPCAnalysisTaskcalib::Process(AliESDtrack *track, Int_t run) {
//
// Process ESD track
//
AliTPCcalibBase *job=0;
Int_t njobs = fCalibJobs->GetEntriesFast();
for (Int_t i=0;i<njobs;i++){
job = (AliTPCcalibBase*)fCalibJobs->UncheckedAt(i);
if (job) job->Process(track,run);
}
}
Long64_t AliTPCAnalysisTaskcalib::Merge(TCollection *li) {
TIterator *i=fCalibJobs->MakeIterator();
AliTPCcalibBase *job;
Long64_t n=0;
while ((job=dynamic_cast<AliTPCcalibBase*>(i->Next())))
n+=job->Merge(li);
return n;
}
void AliTPCAnalysisTaskcalib::Analyze() {
//
// Analyze the content of the task
//
AliTPCcalibBase *job=0;
Int_t njobs = fCalibJobs->GetEntriesFast();
for (Int_t i=0;i<njobs;i++){
job = (AliTPCcalibBase*)fCalibJobs->UncheckedAt(i);
if (job) job->Analyze();
}
}
void AliTPCAnalysisTaskcalib::RegisterDebugOutput(){
//
//
//
AliTPCcalibBase *job=0;
Int_t njobs = fCalibJobs->GetEntriesFast();
for (Int_t i=0;i<njobs;i++){
job = (AliTPCcalibBase*)fCalibJobs->UncheckedAt(i);
if (job) job->RegisterDebugOutput(fDebugOutputPath.Data());
}
}
<commit_msg>Call destructor of the subtasks - components in the destructor (Marian)<commit_after>/**************************************************************************
* Copyright(c) 1998-1999, 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. *
**************************************************************************/
///////////////////////////////////////////////////////////////////////////////
// //
// ANALYSIS task to perrorm TPC calibration //
// //
///////////////////////////////////////////////////////////////////////////////
#include "AliTPCAnalysisTaskcalib.h"
#include "TChain.h"
#include "AliTPCcalibBase.h"
#include "AliESDEvent.h"
#include "AliESDfriend.h"
#include "AliESDtrack.h"
#include "AliESDfriendTrack.h"
#include "AliTPCseed.h"
#include "AliESDInputHandler.h"
#include "AliAnalysisManager.h"
ClassImp(AliTPCAnalysisTaskcalib)
AliTPCAnalysisTaskcalib::AliTPCAnalysisTaskcalib()
:AliAnalysisTask(),
fCalibJobs(0),
fESD(0),
fESDfriend(0),
fDebugOutputPath()
{
//
// default constructor
//
}
AliTPCAnalysisTaskcalib::AliTPCAnalysisTaskcalib(const char *name)
:AliAnalysisTask(name,""),
fCalibJobs(0),
fESD(0),
fESDfriend(0),
fDebugOutputPath()
{
//
// Constructor
//
DefineInput(0, TChain::Class());
DefineOutput(0, TObjArray::Class());
fCalibJobs = new TObjArray(0);
fCalibJobs->SetOwner(kFALSE);
}
AliTPCAnalysisTaskcalib::~AliTPCAnalysisTaskcalib() {
//
// destructor
//
printf("AliTPCAnalysisTaskcalib::~AliTPCAnalysisTaskcalib");
fCalibJobs->Delete();
}
void AliTPCAnalysisTaskcalib::Exec(Option_t *) {
//
// Exec function
// Loop over tracks and call Process function
if (!fESD) {
//Printf("ERROR: fESD not available");
return;
}
fESDfriend=static_cast<AliESDfriend*>(fESD->FindListObject("AliESDfriend"));
if (!fESDfriend) {
//Printf("ERROR: fESDfriend not available");
return;
}
Int_t n=fESD->GetNumberOfTracks();
Process(fESD);
Int_t run = fESD->GetRunNumber();
for (Int_t i=0;i<n;++i) {
AliESDfriendTrack *friendTrack=fESDfriend->GetTrack(i);
AliESDtrack *track=fESD->GetTrack(i);
TObject *calibObject=0;
AliTPCseed *seed=0;
for (Int_t j=0;(calibObject=friendTrack->GetCalibObject(j));++j)
if ((seed=dynamic_cast<AliTPCseed*>(calibObject)))
break;
if (track) Process(track, run);
if (seed)
Process(seed);
}
PostData(0,fCalibJobs);
}
void AliTPCAnalysisTaskcalib::ConnectInputData(Option_t *) {
//
//
//
TTree* tree=dynamic_cast<TTree*>(GetInputData(0));
if (!tree) {
//Printf("ERROR: Could not read chain from input slot 0");
}
else {
AliESDInputHandler *esdH = dynamic_cast<AliESDInputHandler*> (AliAnalysisManager::GetAnalysisManager()->GetInputEventHandler());
if (!esdH) {
//Printf("ERROR: Could not get ESDInputHandler");
}
else {
fESD = esdH->GetEvent();
//Printf("*** CONNECTED NEW EVENT ****");
}
}
}
void AliTPCAnalysisTaskcalib::CreateOutputObjects() {
//
//
//
}
void AliTPCAnalysisTaskcalib::Terminate(Option_t */*option*/) {
//
// Terminate
//
AliTPCcalibBase *job=0;
Int_t njobs = fCalibJobs->GetEntriesFast();
for (Int_t i=0;i<njobs;i++){
job = (AliTPCcalibBase*)fCalibJobs->UncheckedAt(i);
if (job) job->Terminate();
}
}
void AliTPCAnalysisTaskcalib::FinishTaskOutput()
{
//
// According description in AliAnalisysTask this method is call
// on the slaves before sending data
//
Terminate("slave");
RegisterDebugOutput();
}
void AliTPCAnalysisTaskcalib::Process(AliESDEvent *event) {
//
// Process ESD event
//
AliTPCcalibBase *job=0;
Int_t njobs = fCalibJobs->GetEntriesFast();
for (Int_t i=0;i<njobs;i++){
job = (AliTPCcalibBase*)fCalibJobs->UncheckedAt(i);
if (job) job->Process(event);
}
}
void AliTPCAnalysisTaskcalib::Process(AliTPCseed *track) {
//
// Process TPC track
//
AliTPCcalibBase *job=0;
Int_t njobs = fCalibJobs->GetEntriesFast();
for (Int_t i=0;i<njobs;i++){
job = (AliTPCcalibBase*)fCalibJobs->UncheckedAt(i);
if (job) job->Process(track);
}
}
void AliTPCAnalysisTaskcalib::Process(AliESDtrack *track, Int_t run) {
//
// Process ESD track
//
AliTPCcalibBase *job=0;
Int_t njobs = fCalibJobs->GetEntriesFast();
for (Int_t i=0;i<njobs;i++){
job = (AliTPCcalibBase*)fCalibJobs->UncheckedAt(i);
if (job) job->Process(track,run);
}
}
Long64_t AliTPCAnalysisTaskcalib::Merge(TCollection *li) {
TIterator *i=fCalibJobs->MakeIterator();
AliTPCcalibBase *job;
Long64_t n=0;
while ((job=dynamic_cast<AliTPCcalibBase*>(i->Next())))
n+=job->Merge(li);
return n;
}
void AliTPCAnalysisTaskcalib::Analyze() {
//
// Analyze the content of the task
//
AliTPCcalibBase *job=0;
Int_t njobs = fCalibJobs->GetEntriesFast();
for (Int_t i=0;i<njobs;i++){
job = (AliTPCcalibBase*)fCalibJobs->UncheckedAt(i);
if (job) job->Analyze();
}
}
void AliTPCAnalysisTaskcalib::RegisterDebugOutput(){
//
//
//
AliTPCcalibBase *job=0;
Int_t njobs = fCalibJobs->GetEntriesFast();
for (Int_t i=0;i<njobs;i++){
job = (AliTPCcalibBase*)fCalibJobs->UncheckedAt(i);
if (job) job->RegisterDebugOutput(fDebugOutputPath.Data());
}
}
<|endoftext|> |
<commit_before>//===- CallingConvEmitter.cpp - Generate calling conventions --------------===//
//
// The LLVM Compiler Infrastructure
//
// This file is distributed under the University of Illinois Open Source
// License. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//
//
// This tablegen backend is responsible for emitting descriptions of the calling
// conventions supported by this target.
//
//===----------------------------------------------------------------------===//
#include "CallingConvEmitter.h"
#include "Record.h"
#include "CodeGenTarget.h"
using namespace llvm;
void CallingConvEmitter::run(std::ostream &O) {
EmitSourceFileHeader("Calling Convention Implementation Fragment", O);
std::vector<Record*> CCs = Records.getAllDerivedDefinitions("CallingConv");
// Emit prototypes for all of the CC's so that they can forward ref each
// other.
for (unsigned i = 0, e = CCs.size(); i != e; ++i) {
O << "static bool " << CCs[i]->getName()
<< "(unsigned ValNo, MVT::ValueType ValVT,\n"
<< std::string(CCs[i]->getName().size()+13, ' ')
<< "MVT::ValueType LocVT, CCValAssign::LocInfo LocInfo,\n"
<< std::string(CCs[i]->getName().size()+13, ' ')
<< "unsigned ArgFlags, CCState &State);\n";
}
// Emit each calling convention description in full.
for (unsigned i = 0, e = CCs.size(); i != e; ++i)
EmitCallingConv(CCs[i], O);
}
void CallingConvEmitter::EmitCallingConv(Record *CC, std::ostream &O) {
ListInit *CCActions = CC->getValueAsListInit("Actions");
Counter = 0;
O << "\n\nstatic bool " << CC->getName()
<< "(unsigned ValNo, MVT::ValueType ValVT,\n"
<< std::string(CC->getName().size()+13, ' ')
<< "MVT::ValueType LocVT, CCValAssign::LocInfo LocInfo,\n"
<< std::string(CC->getName().size()+13, ' ')
<< "unsigned ArgFlags, CCState &State) {\n";
// Emit all of the actions, in order.
for (unsigned i = 0, e = CCActions->getSize(); i != e; ++i) {
O << "\n";
EmitAction(CCActions->getElementAsRecord(i), 2, O);
}
O << "\n return true; // CC didn't match.\n";
O << "}\n";
}
void CallingConvEmitter::EmitAction(Record *Action,
unsigned Indent, std::ostream &O) {
std::string IndentStr = std::string(Indent, ' ');
if (Action->isSubClassOf("CCPredicateAction")) {
O << IndentStr << "if (";
if (Action->isSubClassOf("CCIfType")) {
ListInit *VTs = Action->getValueAsListInit("VTs");
for (unsigned i = 0, e = VTs->getSize(); i != e; ++i) {
Record *VT = VTs->getElementAsRecord(i);
if (i != 0) O << " ||\n " << IndentStr;
O << "LocVT == " << getEnumName(getValueType(VT));
}
} else if (Action->isSubClassOf("CCIf")) {
O << Action->getValueAsString("Predicate");
} else {
Action->dump();
throw "Unknown CCPredicateAction!";
}
O << ") {\n";
EmitAction(Action->getValueAsDef("SubAction"), Indent+2, O);
O << IndentStr << "}\n";
} else {
if (Action->isSubClassOf("CCDelegateTo")) {
Record *CC = Action->getValueAsDef("CC");
O << IndentStr << "if (!" << CC->getName()
<< "(ValNo, ValVT, LocVT, LocInfo, ArgFlags, State))\n"
<< IndentStr << " return false;\n";
} else if (Action->isSubClassOf("CCAssignToReg")) {
ListInit *RegList = Action->getValueAsListInit("RegList");
if (RegList->getSize() == 1) {
O << IndentStr << "if (unsigned Reg = State.AllocateReg(";
O << getQualifiedName(RegList->getElementAsRecord(0)) << ")) {\n";
} else {
O << IndentStr << "static const unsigned RegList" << ++Counter
<< "[] = {\n";
O << IndentStr << " ";
for (unsigned i = 0, e = RegList->getSize(); i != e; ++i) {
if (i != 0) O << ", ";
O << getQualifiedName(RegList->getElementAsRecord(i));
}
O << "\n" << IndentStr << "};\n";
O << IndentStr << "if (unsigned Reg = State.AllocateReg(RegList"
<< Counter << ", " << RegList->getSize() << ")) {\n";
}
O << IndentStr << " State.addLoc(CCValAssign::getReg(ValNo, ValVT, "
<< "Reg, LocVT, LocInfo));\n";
O << IndentStr << " return false;\n";
O << IndentStr << "}\n";
} else if (Action->isSubClassOf("CCAssignToStack")) {
int Size = Action->getValueAsInt("Size");
int Align = Action->getValueAsInt("Align");
O << IndentStr << "unsigned Offset" << ++Counter
<< " = State.AllocateStack(";
if (Size)
O << Size << ", ";
else
O << "\n" << IndentStr << " State.getTarget().getTargetData()"
"->getABITypeSize(MVT::getTypeForValueType(LocVT)), ";
if (Align)
O << Align;
else
O << "\n" << IndentStr << " State.getTarget().getTargetData()"
"->getABITypeAlignment(MVT::getTypeForValueType(LocVT))";
O << ");\n" << IndentStr
<< "State.addLoc(CCValAssign::getMem(ValNo, ValVT, Offset"
<< Counter << ", LocVT, LocInfo));\n";
O << IndentStr << "return false;\n";
} else if (Action->isSubClassOf("CCPromoteToType")) {
Record *DestTy = Action->getValueAsDef("DestTy");
O << IndentStr << "LocVT = " << getEnumName(getValueType(DestTy)) <<";\n";
O << IndentStr << "if (ArgFlags & ISD::ParamFlags::SExt)\n"
<< IndentStr << IndentStr << "LocInfo = CCValAssign::SExt;\n"
<< IndentStr << "else if (ArgFlags & ISD::ParamFlags::ZExt)\n"
<< IndentStr << IndentStr << "LocInfo = CCValAssign::ZExt;\n"
<< IndentStr << "else\n"
<< IndentStr << IndentStr << "LocInfo = CCValAssign::AExt;\n";
} else if (Action->isSubClassOf("CCPassByVal")) {
int Size = Action->getValueAsInt("Size");
int Align = Action->getValueAsInt("Align");
O << IndentStr
<< "State.HandleByVal(ValNo, ValVT, LocVT, LocInfo, "
<< Size << ", " << Align << ", ArgFlags);\n";
O << IndentStr << "return false;\n";
} else {
Action->dump();
throw "Unknown CCAction!";
}
}
}
<commit_msg>Increase ISD::ParamFlags to 64 bits. Increase the ByValSize field to 32 bits, thus enabling correct handling of ByVal structs bigger than 0x1ffff. Abstract interface a bit. Fixes gcc.c-torture/execute/pr23135.c and gcc.c-torture/execute/pr28982b.c in gcc testsuite (were ICE'ing on ppc32, quietly producing wrong code on x86-32.)<commit_after>//===- CallingConvEmitter.cpp - Generate calling conventions --------------===//
//
// The LLVM Compiler Infrastructure
//
// This file is distributed under the University of Illinois Open Source
// License. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//
//
// This tablegen backend is responsible for emitting descriptions of the calling
// conventions supported by this target.
//
//===----------------------------------------------------------------------===//
#include "CallingConvEmitter.h"
#include "Record.h"
#include "CodeGenTarget.h"
using namespace llvm;
void CallingConvEmitter::run(std::ostream &O) {
EmitSourceFileHeader("Calling Convention Implementation Fragment", O);
std::vector<Record*> CCs = Records.getAllDerivedDefinitions("CallingConv");
// Emit prototypes for all of the CC's so that they can forward ref each
// other.
for (unsigned i = 0, e = CCs.size(); i != e; ++i) {
O << "static bool " << CCs[i]->getName()
<< "(unsigned ValNo, MVT::ValueType ValVT,\n"
<< std::string(CCs[i]->getName().size()+13, ' ')
<< "MVT::ValueType LocVT, CCValAssign::LocInfo LocInfo,\n"
<< std::string(CCs[i]->getName().size()+13, ' ')
<< "ISD::ParamFlags::ParamFlagsTy ArgFlags, CCState &State);\n";
}
// Emit each calling convention description in full.
for (unsigned i = 0, e = CCs.size(); i != e; ++i)
EmitCallingConv(CCs[i], O);
}
void CallingConvEmitter::EmitCallingConv(Record *CC, std::ostream &O) {
ListInit *CCActions = CC->getValueAsListInit("Actions");
Counter = 0;
O << "\n\nstatic bool " << CC->getName()
<< "(unsigned ValNo, MVT::ValueType ValVT,\n"
<< std::string(CC->getName().size()+13, ' ')
<< "MVT::ValueType LocVT, CCValAssign::LocInfo LocInfo,\n"
<< std::string(CC->getName().size()+13, ' ')
<< "ISD::ParamFlags::ParamFlagsTy ArgFlags, CCState &State) {\n";
// Emit all of the actions, in order.
for (unsigned i = 0, e = CCActions->getSize(); i != e; ++i) {
O << "\n";
EmitAction(CCActions->getElementAsRecord(i), 2, O);
}
O << "\n return true; // CC didn't match.\n";
O << "}\n";
}
void CallingConvEmitter::EmitAction(Record *Action,
unsigned Indent, std::ostream &O) {
std::string IndentStr = std::string(Indent, ' ');
if (Action->isSubClassOf("CCPredicateAction")) {
O << IndentStr << "if (";
if (Action->isSubClassOf("CCIfType")) {
ListInit *VTs = Action->getValueAsListInit("VTs");
for (unsigned i = 0, e = VTs->getSize(); i != e; ++i) {
Record *VT = VTs->getElementAsRecord(i);
if (i != 0) O << " ||\n " << IndentStr;
O << "LocVT == " << getEnumName(getValueType(VT));
}
} else if (Action->isSubClassOf("CCIf")) {
O << Action->getValueAsString("Predicate");
} else {
Action->dump();
throw "Unknown CCPredicateAction!";
}
O << ") {\n";
EmitAction(Action->getValueAsDef("SubAction"), Indent+2, O);
O << IndentStr << "}\n";
} else {
if (Action->isSubClassOf("CCDelegateTo")) {
Record *CC = Action->getValueAsDef("CC");
O << IndentStr << "if (!" << CC->getName()
<< "(ValNo, ValVT, LocVT, LocInfo, ArgFlags, State))\n"
<< IndentStr << " return false;\n";
} else if (Action->isSubClassOf("CCAssignToReg")) {
ListInit *RegList = Action->getValueAsListInit("RegList");
if (RegList->getSize() == 1) {
O << IndentStr << "if (unsigned Reg = State.AllocateReg(";
O << getQualifiedName(RegList->getElementAsRecord(0)) << ")) {\n";
} else {
O << IndentStr << "static const unsigned RegList" << ++Counter
<< "[] = {\n";
O << IndentStr << " ";
for (unsigned i = 0, e = RegList->getSize(); i != e; ++i) {
if (i != 0) O << ", ";
O << getQualifiedName(RegList->getElementAsRecord(i));
}
O << "\n" << IndentStr << "};\n";
O << IndentStr << "if (unsigned Reg = State.AllocateReg(RegList"
<< Counter << ", " << RegList->getSize() << ")) {\n";
}
O << IndentStr << " State.addLoc(CCValAssign::getReg(ValNo, ValVT, "
<< "Reg, LocVT, LocInfo));\n";
O << IndentStr << " return false;\n";
O << IndentStr << "}\n";
} else if (Action->isSubClassOf("CCAssignToStack")) {
int Size = Action->getValueAsInt("Size");
int Align = Action->getValueAsInt("Align");
O << IndentStr << "unsigned Offset" << ++Counter
<< " = State.AllocateStack(";
if (Size)
O << Size << ", ";
else
O << "\n" << IndentStr << " State.getTarget().getTargetData()"
"->getABITypeSize(MVT::getTypeForValueType(LocVT)), ";
if (Align)
O << Align;
else
O << "\n" << IndentStr << " State.getTarget().getTargetData()"
"->getABITypeAlignment(MVT::getTypeForValueType(LocVT))";
O << ");\n" << IndentStr
<< "State.addLoc(CCValAssign::getMem(ValNo, ValVT, Offset"
<< Counter << ", LocVT, LocInfo));\n";
O << IndentStr << "return false;\n";
} else if (Action->isSubClassOf("CCPromoteToType")) {
Record *DestTy = Action->getValueAsDef("DestTy");
O << IndentStr << "LocVT = " << getEnumName(getValueType(DestTy)) <<";\n";
O << IndentStr << "if (ArgFlags & ISD::ParamFlags::SExt)\n"
<< IndentStr << IndentStr << "LocInfo = CCValAssign::SExt;\n"
<< IndentStr << "else if (ArgFlags & ISD::ParamFlags::ZExt)\n"
<< IndentStr << IndentStr << "LocInfo = CCValAssign::ZExt;\n"
<< IndentStr << "else\n"
<< IndentStr << IndentStr << "LocInfo = CCValAssign::AExt;\n";
} else if (Action->isSubClassOf("CCPassByVal")) {
int Size = Action->getValueAsInt("Size");
int Align = Action->getValueAsInt("Align");
O << IndentStr
<< "State.HandleByVal(ValNo, ValVT, LocVT, LocInfo, "
<< Size << ", " << Align << ", ArgFlags);\n";
O << IndentStr << "return false;\n";
} else {
Action->dump();
throw "Unknown CCAction!";
}
}
}
<|endoftext|> |
<commit_before><commit_msg>[macro toolbar walkthrough] change dialog parent to this instead of main window, for avoiding warning message when closing macro execute dialog<commit_after><|endoftext|> |
<commit_before>// $Id: fe_clough.C,v 1.2 2005-02-22 22:17:36 jwpeterson Exp $
// The libMesh Finite Element Library.
// Copyright (C) 2002-2005 Benjamin S. Kirk, John W. Peterson
// This library is free software; you can redistribute it and/or
// modify it under the terms of the GNU Lesser General Public
// License as published by the Free Software Foundation; either
// version 2.1 of the License, or (at your option) any later version.
// This library is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
// Lesser General Public License for more details.
// You should have received a copy of the GNU Lesser General Public
// License along with this library; if not, write to the Free Software
// Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
// Local includes
#include "fe.h"
#include "elem.h"
// ------------------------------------------------------------
// Hierarchic-specific implementations
template <unsigned int Dim, FEFamily T>
void FE<Dim,T>::nodal_soln(const Elem* elem,
const Order order,
const std::vector<Number>& elem_soln,
std::vector<Number>& nodal_soln)
{
const unsigned int n_nodes = elem->n_nodes();
const ElemType type = elem->type();
nodal_soln.resize(n_nodes);
switch (order)
{
// Piecewise cubic shape functions only
case THIRD:
{
const unsigned int n_sf =
FE<Dim,T>::n_shape_functions(type, order);
for (unsigned int n=0; n<n_nodes; n++)
{
const Point mapped_point = FE<Dim,T>::inverse_map(elem,
elem->point(n));
assert (elem_soln.size() == n_sf);
// Zero before summation
nodal_soln[n] = 0;
// u_i = Sum (alpha_i phi_i)
for (unsigned int i=0; i<n_sf; i++)
nodal_soln[n] += elem_soln[i]*FE<Dim,T>::shape(elem,
order,
i,
mapped_point);
}
return;
}
default:
{
error();
}
}
}
template <unsigned int Dim, FEFamily T>
unsigned int FE<Dim,T>::n_dofs(const ElemType t, const Order o)
{
switch (o)
{
// Piecewise cubic Clough-Tocher element
case THIRD:
{
switch (t)
{
case TRI6:
return 12;
default:
{
#ifdef DEBUG
std::cerr << "ERROR: Bad ElemType = " << t
<< " for " << o << "th order approximation!"
<< std::endl;
#endif
error();
}
}
}
default:
{
error();
}
}
error();
return 0;
}
template <unsigned int Dim, FEFamily T>
unsigned int FE<Dim,T>::n_dofs_at_node(const ElemType t,
const Order o,
const unsigned int n)
{
switch (o)
{
// The third-order hierarchic shape functions
case THIRD:
{
switch (t)
{
// The 2D Clough-Tocher defined on a 6-noded triangle
case TRI6:
{
switch (n)
{
case 0:
case 1:
case 2:
return 3;
case 3:
case 4:
case 5:
return 1;
default:
error();
}
}
default:
{
#ifdef DEBUG
std::cerr << "ERROR: Bad ElemType = " << t
<< " for " << o << "th order approximation!"
<< std::endl;
#endif
error();
}
}
}
default:
{
error();
}
}
error();
return 0;
}
template <unsigned int Dim, FEFamily T>
unsigned int FE<Dim,T>::n_dofs_per_elem(const ElemType t,
const Order o)
{
switch (o)
{
// The third-order Clough-Tocher shape functions
case THIRD:
{
switch (t)
{
// The 2D hierarchic defined on a 6-noded triangle
case TRI6:
return 0;
default:
{
#ifdef DEBUG
std::cerr << "ERROR: Bad ElemType = " << t
<< " for " << o << "th order approximation!"
<< std::endl;
#endif
error();
}
}
}
// Otherwise no DOFS per element
default:
error();
return 0;
}
}
template <unsigned int Dim, FEFamily T>
void FE<Dim,T>::compute_constraints (std::map<unsigned int,
std::map<unsigned int,
float> > &,
const unsigned int,
const unsigned int,
const FEType&,
const Elem*)
{
std::cerr << "ERROR: Not yet implemented for Clough-Tocher!"
<< std::endl;
error();
}
template <unsigned int Dim, FEFamily T>
bool FE<Dim,T>::shapes_need_reinit() const
{
return true;
}
//--------------------------------------------------------------
// Explicit instantiations
template class FE<1,CLOUGH>; // FIXME: 1D Not yet functional!
template class FE<2,CLOUGH>;
template class FE<3,CLOUGH>; // FIXME: 2D Not yet functional!
<commit_msg><commit_after>// $Id: fe_clough.C,v 1.3 2005-02-23 03:42:16 roystgnr Exp $
// The libMesh Finite Element Library.
// Copyright (C) 2002-2005 Benjamin S. Kirk, John W. Peterson,
// Roy H. Stogner
// This library is free software; you can redistribute it and/or
// modify it under the terms of the GNU Lesser General Public
// License as published by the Free Software Foundation; either
// version 2.1 of the License, or (at your option) any later version.
// This library is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
// Lesser General Public License for more details.
// You should have received a copy of the GNU Lesser General Public
// License along with this library; if not, write to the Free Software
// Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
// Local includes
#include "dense_matrix.h"
#include "dense_vector.h"
#include "dof_map.h"
#include "elem.h"
#include "fe.h"
#include "fe_interface.h"
#include "quadrature_clough.h"
// ------------------------------------------------------------
// Hierarchic-specific implementations
template <unsigned int Dim, FEFamily T>
void FE<Dim,T>::nodal_soln(const Elem* elem,
const Order order,
const std::vector<Number>& elem_soln,
std::vector<Number>& nodal_soln)
{
const unsigned int n_nodes = elem->n_nodes();
const ElemType type = elem->type();
nodal_soln.resize(n_nodes);
switch (order)
{
// Piecewise cubic shape functions only
case THIRD:
{
const unsigned int n_sf =
FE<Dim,T>::n_shape_functions(type, order);
for (unsigned int n=0; n<n_nodes; n++)
{
const Point mapped_point = FE<Dim,T>::inverse_map(elem,
elem->point(n));
assert (elem_soln.size() == n_sf);
// Zero before summation
nodal_soln[n] = 0;
// u_i = Sum (alpha_i phi_i)
for (unsigned int i=0; i<n_sf; i++)
nodal_soln[n] += elem_soln[i]*FE<Dim,T>::shape(elem,
order,
i,
mapped_point);
}
return;
}
default:
{
error();
}
}
}
template <unsigned int Dim, FEFamily T>
unsigned int FE<Dim,T>::n_dofs(const ElemType t, const Order o)
{
switch (o)
{
// Piecewise cubic Clough-Tocher element
case THIRD:
{
switch (t)
{
case TRI6:
return 12;
default:
{
#ifdef DEBUG
std::cerr << "ERROR: Bad ElemType = " << t
<< " for " << o << "th order approximation!"
<< std::endl;
#endif
error();
}
}
}
default:
{
error();
}
}
error();
return 0;
}
template <unsigned int Dim, FEFamily T>
unsigned int FE<Dim,T>::n_dofs_at_node(const ElemType t,
const Order o,
const unsigned int n)
{
switch (o)
{
// The third-order hierarchic shape functions
case THIRD:
{
switch (t)
{
// The 2D Clough-Tocher defined on a 6-noded triangle
case TRI6:
{
switch (n)
{
case 0:
case 1:
case 2:
return 3;
case 3:
case 4:
case 5:
return 1;
default:
error();
}
}
default:
{
#ifdef DEBUG
std::cerr << "ERROR: Bad ElemType = " << t
<< " for " << o << "th order approximation!"
<< std::endl;
#endif
error();
}
}
}
default:
{
error();
}
}
error();
return 0;
}
template <unsigned int Dim, FEFamily T>
unsigned int FE<Dim,T>::n_dofs_per_elem(const ElemType t,
const Order o)
{
switch (o)
{
// The third-order Clough-Tocher shape functions
case THIRD:
{
switch (t)
{
// The 2D hierarchic defined on a 6-noded triangle
case TRI6:
return 0;
default:
{
#ifdef DEBUG
std::cerr << "ERROR: Bad ElemType = " << t
<< " for " << o << "th order approximation!"
<< std::endl;
#endif
error();
}
}
}
// Otherwise no DOFS per element
default:
error();
return 0;
}
}
template <unsigned int Dim, FEFamily T>
void FE<Dim,T>::compute_constraints (std::map<unsigned int,
std::map<unsigned int, float> > &
constraints,
DofMap &dof_map,
const unsigned int variable_number,
const Elem* elem)
{
// Only constrain elements in 2,3D.
if (Dim == 1)
return;
assert (elem != NULL);
const FEType& fe_type = dof_map.variable_type(variable_number);
AutoPtr<FEBase> my_fe (FEBase::build(Dim, fe_type));
AutoPtr<FEBase> parent_fe (FEBase::build(Dim, fe_type));
QClough my_qface(Dim-1, fe_type.default_quadrature_order());
my_fe->attach_quadrature_rule (&my_qface);
std::vector<Point> parent_qface;
const std::vector<Real>& JxW = my_fe->get_JxW();
const std::vector<Point>& q_point = my_fe->get_xyz();
const std::vector<std::vector<Real> >& phi = my_fe->get_phi();
const std::vector<std::vector<Real> >& parent_phi =
parent_fe->get_phi();
const std::vector<Point>& face_normals = my_fe->get_normals();
const std::vector<std::vector<RealGradient> >& dphi =
my_fe->get_dphi();
const std::vector<std::vector<RealGradient> >& parent_dphi =
parent_fe->get_dphi();
const std::vector<unsigned int> child_dof_indices;
const std::vector<unsigned int> parent_dof_indices;
DenseMatrix<Number> Ke;
DenseVector<Number> Fe;
std::vector<DenseVector<Number> > Ue;
// Look at the element faces. Check to see if we need to
// build constraints.
for (unsigned int s=0; s<elem->n_sides(); s++)
if (elem->neighbor(s) != NULL)
// constrain dofs shared between
// this element and ones coarser
// than this element.
if (elem->neighbor(s)->level() < elem->level())
{
// FIXME: hanging nodes aren't working yet!
std::cerr << "Error: hanging nodes not yet implemented for "
<< "Clough-Tocher elements!" << std::endl;
error();
// Get pointers to the elements of interest and its parent.
const Elem* parent = elem->parent();
// This can't happen... Only level-0 elements have NULL
// parents, and no level-0 elements can be at a higher
// level than their neighbors!
assert (parent != NULL);
my_fe->reinit(elem, s);
const AutoPtr<Elem> my_side (elem->build_side(s));
const AutoPtr<Elem> parent_side (parent->build_side(s));
const unsigned int n_dofs = FEInterface::n_dofs(Dim-1,
fe_type,
my_side->type());
assert(n_dofs == FEInterface::n_dofs(Dim-1, fe_type,
parent_side->type()));
const unsigned int n_qp = my_qface.n_points();
FEInterface::inverse_map (Dim, fe_type, parent, q_point,
parent_qface);
parent_fe->reinit(parent, &parent_qface);
Ke.resize (n_dofs, n_dofs);
Ue.resize(n_dofs);
for (unsigned int i = 0; i != n_dofs; ++i)
for (unsigned int j = 0; j != n_dofs; ++j)
for (unsigned int qp = 0; qp != n_qp; ++qp)
Ke(i,j) += JxW[qp] * (phi[i][qp] * phi[j][qp] +
(dphi[i][qp] *
face_normals[qp]) *
(dphi[j][qp] *
face_normals[qp]));
for (unsigned int i = 0; i != n_dofs; ++i)
{
Fe.resize (n_dofs);
for (unsigned int j = 0; j != n_dofs; ++j)
for (unsigned int qp = 0; qp != n_qp; ++qp)
Fe(j) += JxW[qp] * (parent_phi[i][qp] * phi[j][qp] +
(parent_dphi[i][qp] *
face_normals[qp]) *
(dphi[j][qp] *
face_normals[qp]));
Ke.cholesky_solve(Fe, Ue[i]);
}
}
}
template <unsigned int Dim, FEFamily T>
bool FE<Dim,T>::shapes_need_reinit() const
{
return true;
}
//--------------------------------------------------------------
// Explicit instantiations
template class FE<1,CLOUGH>; // FIXME: 1D Not yet functional!
template class FE<2,CLOUGH>;
template class FE<3,CLOUGH>; // FIXME: 2D Not yet functional!
<|endoftext|> |
<commit_before>/*
* File.cpp
*
* Created on: Jun 24, 2015
* Author: gatanasov
*/
#include "File.h"
#include <sstream>
using namespace std;
namespace tns
{
string File::ReadText(const string& filePath)
{
int len;
bool isNew;
const char *content = ReadText(filePath, len, isNew);
string s(content, len);
if(isNew)
{
delete[] content;
}
return s;
}
const char* File::ReadText(const string& filePath, int& charLength, bool& isNew)
{
FILE *file = fopen(filePath.c_str(), "rb");
fseek(file, 0, SEEK_END);
int len = ftell(file);
if(charLength)
{
charLength = len;
}
bool exceedBuffer = len > BUFFER_SIZE;
if(isNew)
{
isNew = exceedBuffer;
}
rewind(file);
if(exceedBuffer)
{
char* newBuffer = new char[len];
fread(newBuffer, 1, len, file);
fclose(file);
return newBuffer;
}
fread(Buffer, 1, len, file);
fclose(file);
return Buffer;
}
char* File::Buffer = new char[BUFFER_SIZE];
}
<commit_msg>Remove erroneous check for reference params.<commit_after>/*
* File.cpp
*
* Created on: Jun 24, 2015
* Author: gatanasov
*/
#include "File.h"
#include <sstream>
using namespace std;
namespace tns
{
string File::ReadText(const string& filePath)
{
int len;
bool isNew;
const char *content = ReadText(filePath, len, isNew);
string s(content, len);
if(isNew)
{
delete[] content;
}
return s;
}
const char* File::ReadText(const string& filePath, int& charLength, bool& isNew)
{
FILE *file = fopen(filePath.c_str(), "rb");
fseek(file, 0, SEEK_END);
charLength = ftell(file);
isNew = charLength > BUFFER_SIZE;
rewind(file);
if(isNew)
{
char* newBuffer = new char[charLength];
fread(newBuffer, 1, charLength, file);
fclose(file);
return newBuffer;
}
fread(Buffer, 1, charLength, file);
fclose(file);
return Buffer;
}
char* File::Buffer = new char[BUFFER_SIZE];
}
<|endoftext|> |
<commit_before>#include "stan/math/functions/ibeta.hpp"
#include <gtest/gtest.h>
TEST(MathFunctions, ibeta) {
using stan::math::ibeta;
EXPECT_FLOAT_EQ(0.0, ibeta(0.5, 0.5, 0.0)) << "reasonable values for a, b, x";
EXPECT_FLOAT_EQ(0.333333333, ibeta(0.5, 0.5, 0.25)) << "reasonable values for a, b, x";
EXPECT_FLOAT_EQ(0.5, ibeta(0.5, 0.5, 0.5)) << "reasonable values for a, b, x";
EXPECT_FLOAT_EQ(0.666666667, ibeta(0.5, 0.5, 0.75)) << "reasonable values for a, b, x";
EXPECT_FLOAT_EQ(1.0, ibeta(0.5, 0.5, 1.0)) << "reasonable values for a, b, x";
EXPECT_FLOAT_EQ(0.0, ibeta(0.1, 1.5, 0.0)) << "reasonable values for a, b, x";
EXPECT_FLOAT_EQ(0.9117332, ibeta(0.1, 1.5, 0.25)) << "reasonable values for a, b, x";
EXPECT_FLOAT_EQ(0.9645342, ibeta(0.1, 1.5, 0.5)) << "reasonable values for a, b, x";
EXPECT_FLOAT_EQ(0.9897264, ibeta(0.1, 1.5, 0.75)) << "reasonable values for a, b, x";
EXPECT_FLOAT_EQ(1.0, ibeta(0.1, 1.5, 1.0)) << "reasonable values for a, b, x";
}
<commit_msg>adding failing ibeta test with nan input<commit_after>#include <stan/math/functions/ibeta.hpp>
#include <gtest/gtest.h>
TEST(MathFunctions, ibeta) {
using stan::math::ibeta;
EXPECT_FLOAT_EQ(0.0, ibeta(0.5, 0.5, 0.0)) << "reasonable values for a, b, x";
EXPECT_FLOAT_EQ(0.333333333, ibeta(0.5, 0.5, 0.25)) << "reasonable values for a, b, x";
EXPECT_FLOAT_EQ(0.5, ibeta(0.5, 0.5, 0.5)) << "reasonable values for a, b, x";
EXPECT_FLOAT_EQ(0.666666667, ibeta(0.5, 0.5, 0.75)) << "reasonable values for a, b, x";
EXPECT_FLOAT_EQ(1.0, ibeta(0.5, 0.5, 1.0)) << "reasonable values for a, b, x";
EXPECT_FLOAT_EQ(0.0, ibeta(0.1, 1.5, 0.0)) << "reasonable values for a, b, x";
EXPECT_FLOAT_EQ(0.9117332, ibeta(0.1, 1.5, 0.25)) << "reasonable values for a, b, x";
EXPECT_FLOAT_EQ(0.9645342, ibeta(0.1, 1.5, 0.5)) << "reasonable values for a, b, x";
EXPECT_FLOAT_EQ(0.9897264, ibeta(0.1, 1.5, 0.75)) << "reasonable values for a, b, x";
EXPECT_FLOAT_EQ(1.0, ibeta(0.1, 1.5, 1.0)) << "reasonable values for a, b, x";
}
TEST(MathFunctions, ibeta_nan) {
double nan = std::numeric_limits<double>::quiet_NaN();
EXPECT_PRED1(boost::math::isnan<double>,
stan::math::ibeta(0.5, 0.5, nan));
EXPECT_PRED1(boost::math::isnan<double>,
stan::math::ibeta(0.5, nan, 0.0));
EXPECT_PRED1(boost::math::isnan<double>,
stan::math::ibeta(0.5, nan, nan));
EXPECT_PRED1(boost::math::isnan<double>,
stan::math::ibeta(nan, 0.5, 0.0));
EXPECT_PRED1(boost::math::isnan<double>,
stan::math::ibeta(nan, 0.5, nan));
EXPECT_PRED1(boost::math::isnan<double>,
stan::math::ibeta(nan, nan, 0.0));
EXPECT_PRED1(boost::math::isnan<double>,
stan::math::ibeta(nan, nan, nan));
}
<|endoftext|> |
<commit_before>#include <array>
#include <boost/fusion/adapted/array.hpp>
#include <boost/fusion/adapted/std_array.hpp>
#include <boost/fusion/adapted/std_tuple.hpp>
#include <boost/fusion/adapted/std_pair.hpp>
#include <boost/spirit/home/x3.hpp>
#include <boost/spirit/include/support_istream_iterator.hpp>
#include <iostream>
#include <fstream>
#include <vector>
#include <map>
#include <string>
using namespace boost::spirit;
using namespace std;
using box = std::array<int, 4>;
// According to https://wandbox.org/permlink/poeusnilIOwmiEBo
namespace boost {
namespace spirit {
namespace x3 {
namespace traits {
// It can't be specialized because X3 implements is_container as a template aliases,
// thus we need QUITE TERRIBLE DIRTY hack for fixed length container.
//template <> struct is_container<Vertex const> : mpl::false_ { };
//template <> struct is_container<Vertex> : mpl::false_ { };
namespace detail {
template <> struct has_type_value_type<box> : mpl::false_ { };
}
}
}
}
}
template<class T> auto constexpr bracketize(T what)
{
return '[' > what > ']';
}
// Vector of four ints
auto boxrule = bracketize(x3::int_ > ',' > x3::int_ > ',' > x3::int_ > ',' > x3::int_);
// Comma-separated list of such vectors
auto innerboxlist = (boxrule % ',');
auto fullboxlist = x3::lit("array") > '(' > bracketize(innerboxlist ) > ',' > "dtype" > '=' > "int64" > ')';
// The whole first section of the data file
auto boxes = bracketize(*(fullboxlist));
// Array of lists of doubles
auto scorelist = x3::lit("array") > '(' > bracketize(x3::double_ % ',') > ')';
auto scores = bracketize(*(scorelist));
template<class RuleType, class AttrType> void parseToEndWithError(istream& file, const RuleType& rule, AttrType& target)
{
auto parseriter = boost::spirit::istream_iterator(file);
boost::spirit::istream_iterator end;
bool res = phrase_parse(parseriter, end, rule, x3::space - x3::eol, target);
if (!res)
{
std::string val;
file >> val;
throw logic_error("Parsing failed. " + (std::string) __func__ + " " + val);
}
}
struct wordmapper
{
private:
map<string, int> mapping;
map<int, string> inversemapping;
public:
int getMapping(const string& word)
{
auto i = mapping.find(word);
if (i != mapping.end())
{
return i->second;
}
int index = mapping.size();
mapping[word] = index;
inversemapping[index] = word;
return index;
}
string getWord(int mapping)
{
return inversemapping[mapping];
}
} wordmap;
// Coming in C++ 17
template <class T>
constexpr std::add_const_t<T>& as_const(const T& t) noexcept
{
return t;
}
auto word_ = x3::lexeme[+(x3::char_ - x3::space)];
auto linefile = *word_ % x3::eol;
using stateVec = array<double, 1000>;
struct hmmtype
{
vector<vector<box>> ourBoxes;
vector<vector<double>> scoreVals;
vector<bool> lineEnd;
stateVec fwbw[2][1000] = { 0 };
void prepareLineEnd(const vector<vector<int>>& introws)
{
lineEnd.reserve(scoreVals.size());
for (const auto& r : introws)
{
for (int i : r)
{
lineEnd.push_back(false);
}
*(lineEnd.end() - 1) = true;
}
}
void emit(stateVec& state, int pos)
{
for (int i = 0; i < scoreVals[pos].size(); i++)
{
state[i] *= max(1e-9, scoreVals[pos][i]);
}
}
static double transProb(const box& a, const box& b, bool linebreak)
{
bool ok = false;
int height = max(a[3] - a[3], b[3] - b[1]);
if (linebreak)
{
if (b[1] > a[1]) ok = true;
}
else
{
if (b[0] > a[0] && b[1] > a[1] - height && b[1] < a[1] + height) ok = true;
}
return ok ? 1 : 1e-5;
}
template<int dir> void transition(const stateVec& fState, stateVec& tState, int fromPos, int toPos)
{
static_assert(dir == -1 || dir == 1);
for (int i = 0; i < scoreVals[toPos].size(); i++)
{
tState[i] = 0;
}
for (int i = 0; i < scoreVals[fromPos].size(); i++)
{
for (int j = 0; j < scoreVals[toPos].size(); j++)
{
box* fromBox = &ourBoxes[fromPos][i];
box* toBox = &ourBoxes[toPos][j];
int fIndex = fromPos;
if (dir == -1)
{
fIndex = toPos;
swap(fromBox, toBox);
}
tState[j] += fState[i] * transProb(*fromBox, *toBox, lineEnd[fIndex]);
}
}
}
void normalize(stateVec& state, int pos)
{
double sum = 0;
for (int i = 0; i < scoreVals[pos].size(); i++)
{
sum += state[i];
}
if (isnan(sum)) cerr << "Normalization error at " << pos << "\n";
if (sum == 0) cerr << "Zero at " << pos << "\n";
cout << "Sum at " << pos << ":" << sum << "\n";
if (sum < 1e-10)
{
for (int i = 0; i < scoreVals[pos].size(); i++)
{
state[i] *= 1e40;
}
}
}
void computeFB()
{
// FW
for (int i = 0; i < scoreVals[0].size(); i++)
{
fwbw[0][0][i] = 1;
}
for (int i = 0; i < scoreVals.size(); i++)
{
emit(fwbw[0][i], i);
if (i != scoreVals.size() - 1)
{
transition<1>(fwbw[0][i], fwbw[0][i + 1], i, i + 1);
}
normalize(fwbw[0][i + 1], i);
}
// BW
for (int i = 0; i < scoreVals[scoreVals.size() - 1].size(); i++)
{
fwbw[1][scoreVals.size() - 1][i] = 1;
}
for (int i = scoreVals.size() - 1; i != 0; i--)
{
stateVec copy = fwbw[1][i];
emit(copy, i);
transition<-1>(copy, fwbw[1][i - 1], i, i - 1);
normalize(fwbw[1][i - 1], i - 1);
}
}
void fakeFB()
{
// FW
for (int j = 0; j < scoreVals.size(); j++)
{
for (int i = 0; i < scoreVals[j].size(); i++)
{
fwbw[0][j][i] = 1;
}
emit(fwbw[0][j], j);
}
// BW
for (int j = 0; j < scoreVals.size(); j++)
{
for (int i = 0; i < scoreVals[j].size(); i++)
{
fwbw[1][j][i] = 1;
}
}
}
stateVec getProbs(int pos)
{
stateVec toret;
double sum = 0;
for (int i = 0; i < scoreVals[pos].size(); i++)
{
toret[i] = fwbw[0][pos][i] * fwbw[1][pos][i];
sum += toret[i];
}
sum = 1 / sum;
for (int i = 0; i < scoreVals[pos].size(); i++)
{
toret[i] *= sum;
}
return toret;
}
} hmm;
void writeWithSeparator(const string& separator)
{
for (int i = 0; i < hmm.scoreVals.size(); i++)
{
stateVec states = hmm.getProbs(i);
int maxindex = 0;
for (int i = 0; i < hmm.scoreVals[i].size(); i++)
{
if (states[i] > states[maxindex]) maxindex = i;
}
cout << maxindex << ":" << states[maxindex];
/*for (int j = 0; j < 4; j++)
{
cout << ":" << hmm.ourBoxes[i][maxindex][j];
}*/
cout << " ";
if (hmm.lineEnd[i]) cout << separator << "\n";
}
}
int main(int argc, char** argv)
{
if (argc < 2)
{
return -1;
}
ifstream file(argv[1]);
parseToEndWithError(file, boxes > scores, as_const(std::forward_as_tuple(hmm.ourBoxes, hmm.scoreVals)));
cout << "Read " << hmm.ourBoxes.size() << " box lists and " << hmm.scoreVals.size() << " score lists." << "\n";
file = ifstream(argv[2]);
vector<vector<int>> introws;
vector<vector<string>> rows;
file >> noskipws;
parseToEndWithError(file, linefile, rows);
transform(rows.begin(), rows.end(), back_inserter(introws),
[](vector<string>& row)
{
vector<int> introw;
transform(row.begin(), row.end(), back_inserter(introw),
[](const string& word)
{
return wordmap.getMapping(word);
});
return introw;
});
hmm.prepareLineEnd(introws);
hmm.computeFB();
writeWithSeparator("##");
hmm.fakeFB();
writeWithSeparator("//");
}<commit_msg>Don't wait forever just because a later event has been enqueued.<commit_after>#include <array>
#include <boost/lexical_cast.hpp>
#include <Magick++.h>
#include <boost/fusion/adapted/array.hpp>
#include <boost/fusion/adapted/std_array.hpp>
#include <boost/fusion/adapted/std_tuple.hpp>
#include <boost/fusion/adapted/std_pair.hpp>
#include <boost/spirit/home/x3.hpp>
#include <boost/format.hpp>
#include <boost/spirit/include/support_istream_iterator.hpp>
#include <iostream>
#include <fstream>
#include <vector>
#include <map>
#include <string>
using namespace boost::spirit;
using namespace std;
using box = std::array<int, 4>;
// According to https://wandbox.org/permlink/poeusnilIOwmiEBo
namespace boost {
namespace spirit {
namespace x3 {
namespace traits {
// It can't be specialized because X3 implements is_container as a template aliases,
// thus we need QUITE TERRIBLE DIRTY hack for fixed length container.
//template <> struct is_container<Vertex const> : mpl::false_ { };
//template <> struct is_container<Vertex> : mpl::false_ { };
namespace detail {
template <> struct has_type_value_type<box> : mpl::false_ { };
}
}
}
}
}
template<class T> auto constexpr bracketize(T what)
{
return '[' > what > ']';
}
// Vector of four ints
auto boxrule = bracketize(x3::int_ > ',' > x3::int_ > ',' > x3::int_ > ',' > x3::int_);
// Comma-separated list of such vectors
auto innerboxlist = (boxrule % ',');
auto fullboxlist = x3::lit("array") > '(' > bracketize(innerboxlist ) > ',' > "dtype" > '=' > "int64" > ')';
// The whole first section of the data file
auto boxes = bracketize(*(fullboxlist));
// Array of lists of doubles
auto scorelist = x3::lit("array") > '(' > bracketize(x3::double_ % ',') > ')';
auto scores = bracketize(*(scorelist));
template<class RuleType, class AttrType> void parseToEndWithError(istream& file, const RuleType& rule, AttrType& target)
{
auto parseriter = boost::spirit::istream_iterator(file);
boost::spirit::istream_iterator end;
bool res = phrase_parse(parseriter, end, rule, x3::space - x3::eol, target);
if (!res)
{
std::string val;
file >> val;
throw logic_error("Parsing failed. " + (std::string) __func__ + " " + val);
}
}
struct wordmapper
{
private:
map<string, int> mapping;
map<int, string> inversemapping;
public:
int getMapping(const string& word)
{
auto i = mapping.find(word);
if (i != mapping.end())
{
return i->second;
}
int index = mapping.size();
mapping[word] = index;
inversemapping[index] = word;
return index;
}
string getWord(int mapping)
{
return inversemapping[mapping];
}
} wordmap;
// Coming in C++ 17
template <class T>
constexpr std::add_const_t<T>& as_const(const T& t) noexcept
{
return t;
}
auto word_ = x3::lexeme[+(x3::char_ - x3::space)];
auto linefile = *word_ % x3::eol;
using stateVec = array<double, 1000>;
struct hmmtype
{
vector<vector<box>> ourBoxes;
vector<vector<double>> scoreVals;
vector<bool> lineEnd;
stateVec fwbw[2][1000] = { 0 };
void prepareLineEnd(const vector<vector<int>>& introws)
{
lineEnd.reserve(scoreVals.size());
for (const auto& r : introws)
{
for (int i : r)
{
lineEnd.push_back(false);
}
*(lineEnd.end() - 1) = true;
}
}
void emit(stateVec& state, int pos)
{
for (int i = 0; i < scoreVals[pos].size(); i++)
{
state[i] *= max(1e-9, scoreVals[pos][i]);
}
}
static double transProb(const box& a, const box& b, bool linebreak)
{
bool ok = false;
int height = max(a[3] - a[3], b[3] - b[1]);
if (linebreak)
{
if (b[1] > a[1]) ok = true;
}
else
{
if (b[0] > a[0] && b[1] > a[1] - height && b[1] < a[1] + height) ok = true;
}
return ok ? 1 : 1e-5;
}
template<int dir> void transition(const stateVec& fState, stateVec& tState, int fromPos, int toPos)
{
static_assert(dir == -1 || dir == 1);
for (int i = 0; i < scoreVals[toPos].size(); i++)
{
tState[i] = 0;
}
for (int i = 0; i < scoreVals[fromPos].size(); i++)
{
for (int j = 0; j < scoreVals[toPos].size(); j++)
{
box* fromBox = &ourBoxes[fromPos][i];
box* toBox = &ourBoxes[toPos][j];
int fIndex = fromPos;
if (dir == -1)
{
fIndex = toPos;
swap(fromBox, toBox);
}
tState[j] += fState[i] * transProb(*fromBox, *toBox, lineEnd[fIndex]);
}
}
}
void normalize(stateVec& state, int pos)
{
double sum = 0;
for (int i = 0; i < scoreVals[pos].size(); i++)
{
sum += state[i];
}
if (isnan(sum)) cerr << "Normalization error at " << pos << "\n";
if (sum == 0) cerr << "Zero at " << pos << "\n";
cout << "Sum at " << pos << ":" << sum << "\n";
if (sum < 1e-10)
{
for (int i = 0; i < scoreVals[pos].size(); i++)
{
state[i] *= 1e40;
}
}
}
void computeFB()
{
// FW
for (int i = 0; i < scoreVals[0].size(); i++)
{
fwbw[0][0][i] = 1;
}
for (int i = 0; i < scoreVals.size(); i++)
{
emit(fwbw[0][i], i);
if (i != scoreVals.size() - 1)
{
transition<1>(fwbw[0][i], fwbw[0][i + 1], i, i + 1);
}
normalize(fwbw[0][i + 1], i);
}
// BW
for (int i = 0; i < scoreVals[scoreVals.size() - 1].size(); i++)
{
fwbw[1][scoreVals.size() - 1][i] = 1;
}
for (int i = scoreVals.size() - 1; i != 0; i--)
{
stateVec copy = fwbw[1][i];
emit(copy, i);
transition<-1>(copy, fwbw[1][i - 1], i, i - 1);
normalize(fwbw[1][i - 1], i - 1);
}
}
void fakeFB()
{
// FW
for (int j = 0; j < scoreVals.size(); j++)
{
for (int i = 0; i < scoreVals[j].size(); i++)
{
fwbw[0][j][i] = 1;
}
emit(fwbw[0][j], j);
}
// BW
for (int j = 0; j < scoreVals.size(); j++)
{
for (int i = 0; i < scoreVals[j].size(); i++)
{
fwbw[1][j][i] = 1;
}
}
}
stateVec getProbs(int pos)
{
stateVec toret;
double sum = 0;
for (int i = 0; i < scoreVals[pos].size(); i++)
{
toret[i] = fwbw[0][pos][i] * fwbw[1][pos][i];
sum += toret[i];
}
sum = 1 / sum;
for (int i = 0; i < scoreVals[pos].size(); i++)
{
toret[i] *= sum;
}
return toret;
}
} hmm;
void writeWithSeparator(const string& separator, Magick::Image img, string path)
{
std::list<Magick::Drawable> drawList;
drawList.push_back(Magick::DrawableFillOpacity(0));
drawList.push_back(Magick::DrawableStrokeWidth(5));
drawList.push_back(Magick::DrawableStrokeColor("black"));
array<string, 3> colors = { "red", "green", "blue" };
img.strokeWidth(0.5);
//drawList.push_back(Magick::DrawableStrokeOpacity(0.25));
for (int i = 0; i < hmm.scoreVals.size(); i++)
{
stateVec states = hmm.getProbs(i);
int maxindex = 0;
for (int i = 0; i < hmm.scoreVals[i].size(); i++)
{
if (states[i] > states[maxindex]) maxindex = i;
}
cout << maxindex << ":" << states[maxindex];
/*for (int j = 0; j < 4; j++)
{
cout << ":" << hmm.ourBoxes[i][maxindex][j];
}*/
//img.fillColor(Magick::Color::Color(0, 0, 0, 65535 - states[maxindex] * 65535));
const box& b = hmm.ourBoxes[i][maxindex];
drawList.push_back(Magick::DrawableRectangle(b[0], b[1], b[2], b[3]));
img.draw(drawList);
drawList.pop_back();
img.strokeColor(colors[i % 3]);
img.draw(Magick::DrawableText(b[0] + 20, b[1] + 20, boost::lexical_cast<string>(i) + ":" + boost::str(boost::format("%.2f") % states[maxindex])));
cout << " ";
if (hmm.lineEnd[i]) cout << separator << "\n";
}
img.write(path);
}
int main(int argc, char** argv)
{
Magick::InitializeMagick(0);
if (argc < 3)
{
return -1;
}
ifstream file(argv[1]);
parseToEndWithError(file, boxes > scores, as_const(std::forward_as_tuple(hmm.ourBoxes, hmm.scoreVals)));
cout << "Read " << hmm.ourBoxes.size() << " box lists and " << hmm.scoreVals.size() << " score lists." << "\n";
// Do soft-max
for (auto& scoreList : hmm.scoreVals)
{
double maxVal = 0;
for (double& score : scoreList)
{
score *= 10;
maxVal = max(score, maxVal);
}
double sum = 0;
for (double score : scoreList)
{
sum += exp(score - maxVal);
}
for (double& score : scoreList)
{
score = exp(score - maxVal) / sum;
}
}
file = ifstream(argv[2]);
vector<vector<int>> introws;
vector<vector<string>> rows;
file >> noskipws;
parseToEndWithError(file, linefile, rows);
transform(rows.begin(), rows.end(), back_inserter(introws),
[](vector<string>& row)
{
vector<int> introw;
transform(row.begin(), row.end(), back_inserter(introw),
[](const string& word)
{
return wordmap.getMapping(word);
});
return introw;
});
hmm.prepareLineEnd(introws);
Magick::Image origImg(argv[3]);
hmm.computeFB();
writeWithSeparator("##", origImg, string(argv[3]) + ".fb.png");
hmm.fakeFB();
writeWithSeparator("//", origImg, string(argv[3]) + ".naive.png");
}<|endoftext|> |
<commit_before>#ifdef HAVE_CXX11
#include <functional>
#define HAVE_CPP_FUNC_PTR
namespace funcptr = std;
#else
#ifdef HAVE_BOOST
#include <boost/function.hpp>
namespace funcptr = boost;
#define HAVE_CPP_FUNC_PTR
#endif
#endif
#include <fstream>
#include <cctype>
#ifndef WIN32
#include <cstdio>
#include <unistd.h>
#endif
#ifndef YAHTTP_MAX_REQUEST_SIZE
#define YAHTTP_MAX_REQUEST_SIZE 2097152
#endif
#ifndef YAHTTP_MAX_RESPONSE_SIZE
#define YAHTTP_MAX_RESPONSE_SIZE 2097152
#endif
#define YAHTTP_TYPE_REQUEST 1
#define YAHTTP_TYPE_RESPONSE 2
namespace YaHTTP {
typedef std::map<std::string,std::string> strstr_map_t;
typedef std::map<std::string,Cookie> strcookie_map_t;
typedef enum {
urlencoded,
multipart
} postformat_t;
class HTTPBase {
public:
#ifdef HAVE_CPP_FUNC_PTR
class SendBodyRender {
public:
SendBodyRender() {};
size_t operator()(const HTTPBase *doc, std::ostream& os) const {
os << doc->body;
return doc->body.length();
};
};
class SendFileRender {
public:
SendFileRender(const std::string& path) {
this->path = path;
};
size_t operator()(const HTTPBase *doc, std::ostream& os) const {
char buf[4096];
size_t n,k;
#ifdef HAVE_CXX11
std::ifstream ifs(path, std::ifstream::binary);
#else
std::ifstream ifs(path.c_str(), std::ifstream::binary);
#endif
n = 0;
while(ifs && ifs.good()) {
ifs.read(buf, sizeof buf);
n += (k = ifs.gcount());
if (k)
os.write(buf, k);
}
return n;
};
std::string path;
};
#endif
HTTPBase() {
#ifdef HAVE_CPP_FUNC_PTR
renderer = SendBodyRender();
#endif
};
protected:
HTTPBase(const HTTPBase& rhs) {
this->url = rhs.url; this->kind = rhs.kind;
this->status = rhs.status; this->statusText = rhs.statusText;
this->method = rhs.method; this->headers = rhs.headers;
this->jar = rhs.jar; this->postvars = rhs.postvars;
this->params = rhs.params; this->getvars = rhs.getvars;
this->body = rhs.body;
#ifdef HAVE_CPP_FUNC_PTR
this->renderer = rhs.renderer;
#endif
};
HTTPBase& operator=(const HTTPBase& rhs) {
this->url = rhs.url; this->kind = rhs.kind;
this->status = rhs.status; this->statusText = rhs.statusText;
this->method = rhs.method; this->headers = rhs.headers;
this->jar = rhs.jar; this->postvars = rhs.postvars;
this->params = rhs.params; this->getvars = rhs.getvars;
this->body = rhs.body;
#ifdef HAVE_CPP_FUNC_PTR
this->renderer = rhs.renderer;
#endif
return *this;
};
public:
URL url;
int kind;
int status;
std::string statusText;
std::string method;
strstr_map_t headers;
CookieJar jar;
strstr_map_t postvars;
strstr_map_t getvars;
strstr_map_t params;
std::string body;
#ifdef HAVE_CPP_FUNC_PTR
funcptr::function<size_t(const HTTPBase*,std::ostream&)> renderer;
#endif
void write(std::ostream& os) const;
strstr_map_t& GET() { return getvars; };
strstr_map_t& POST() { return postvars; };
strcookie_map_t& COOKIES() { return jar.cookies; };
};
class Response: public HTTPBase {
public:
Response() { this->kind = YAHTTP_TYPE_RESPONSE; };
Response(const HTTPBase& rhs): HTTPBase(rhs) {
this->kind = YAHTTP_TYPE_RESPONSE;
};
Response& operator=(const HTTPBase& rhs) {
HTTPBase::operator=(rhs);
this->kind = YAHTTP_TYPE_RESPONSE;
return *this;
}
friend std::ostream& operator<<(std::ostream& os, const Response &resp);
friend std::istream& operator>>(std::istream& is, Response &resp);
};
class Request: public HTTPBase {
public:
Request() { this->kind = YAHTTP_TYPE_REQUEST; };
Request(const HTTPBase& rhs): HTTPBase(rhs) {
this->kind = YAHTTP_TYPE_REQUEST;
};
Request& operator=(const HTTPBase& rhs) {
HTTPBase::operator=(rhs);
this->kind = YAHTTP_TYPE_REQUEST;
return *this;
}
void prepareAsPost(postformat_t format = urlencoded) {
std::ostringstream postbuf;
if (format == urlencoded) {
for(strstr_map_t::const_iterator i = POST().begin(); i != POST().end(); i++) {
postbuf << Utility::encodeURL(i->first) << "=" << Utility::encodeURL(i->second) << "&";
}
// remove last bit
if (postbuf.str().length()>0)
body = std::string(postbuf.str().begin(), postbuf.str().end()-1);
else
body = "";
headers["content-type"] = "application/x-www-form-urlencoded; charset=utf-8";
} else if (format == multipart) {
headers["content-type"] = "multipart/form-data; boundary=YaHTTP-12ca543";
for(strstr_map_t::const_iterator i = POST().begin(); i != POST().end(); i++) {
postbuf << "--YaHTTP-12ca543\r\nContent-Disposition: form-data; name=\"" << Utility::encodeURL(i->first) << "; charset=UTF-8\r\n\r\n"
<< Utility::encodeURL(i->second) << "\r\n";
}
}
// set method and change headers
method = "POST";
headers["content-length"] = body.length();
};
friend std::ostream& operator<<(std::ostream& os, const Request &resp);
friend std::istream& operator>>(std::istream& is, Request &resp);
};
template <class T>
class AsyncLoader {
public:
T* target;
int state;
size_t pos;
std::string buffer;
bool chunked;
int chunk_size;
std::ostringstream bodybuf;
long maxbody;
long minbody;
void keyValuePair(const std::string &keyvalue, std::string &key, std::string &value);
void initialize(T* target) {
chunked = false; chunk_size = 0;
bodybuf.str(""); maxbody = 0;
pos = 0; state = 0; this->target = target;
};
int feed(const std::string& somedata);
bool ready() { return state > 1 && bodybuf.str().size() <= static_cast<unsigned long>(maxbody) && bodybuf.str().size() >= static_cast<unsigned long>(minbody); };
void finalize() {
bodybuf.flush();
if (ready()) {
strstr_map_t::iterator pos = target->headers.find("content-type");
if (pos != target->headers.end() && Utility::iequals(pos->second, "application/x-www-form-urlencoded", 32)) {
target->postvars = Utility::parseUrlParameters(bodybuf.str());
}
target->body = bodybuf.str();
}
bodybuf.str("");
this->target = NULL;
};
};
class AsyncResponseLoader: public AsyncLoader<Response> {
};
class AsyncRequestLoader: public AsyncLoader<Request> {
};
};
<commit_msg>Added router attributes and setup() helper<commit_after>#ifdef HAVE_CXX11
#include <functional>
#define HAVE_CPP_FUNC_PTR
namespace funcptr = std;
#else
#ifdef HAVE_BOOST
#include <boost/function.hpp>
namespace funcptr = boost;
#define HAVE_CPP_FUNC_PTR
#endif
#endif
#include <fstream>
#include <cctype>
#ifndef WIN32
#include <cstdio>
#include <unistd.h>
#endif
#ifndef YAHTTP_MAX_REQUEST_SIZE
#define YAHTTP_MAX_REQUEST_SIZE 2097152
#endif
#ifndef YAHTTP_MAX_RESPONSE_SIZE
#define YAHTTP_MAX_RESPONSE_SIZE 2097152
#endif
#define YAHTTP_TYPE_REQUEST 1
#define YAHTTP_TYPE_RESPONSE 2
namespace YaHTTP {
typedef std::map<std::string,std::string> strstr_map_t;
typedef std::map<std::string,Cookie> strcookie_map_t;
typedef enum {
urlencoded,
multipart
} postformat_t;
class HTTPBase {
public:
#ifdef HAVE_CPP_FUNC_PTR
class SendBodyRender {
public:
SendBodyRender() {};
size_t operator()(const HTTPBase *doc, std::ostream& os) const {
os << doc->body;
return doc->body.length();
};
};
class SendFileRender {
public:
SendFileRender(const std::string& path) {
this->path = path;
};
size_t operator()(const HTTPBase *doc, std::ostream& os) const {
char buf[4096];
size_t n,k;
#ifdef HAVE_CXX11
std::ifstream ifs(path, std::ifstream::binary);
#else
std::ifstream ifs(path.c_str(), std::ifstream::binary);
#endif
n = 0;
while(ifs && ifs.good()) {
ifs.read(buf, sizeof buf);
n += (k = ifs.gcount());
if (k)
os.write(buf, k);
}
return n;
};
std::string path;
};
#endif
HTTPBase() {
#ifdef HAVE_CPP_FUNC_PTR
renderer = SendBodyRender();
#endif
};
protected:
HTTPBase(const HTTPBase& rhs) {
this->url = rhs.url; this->kind = rhs.kind;
this->status = rhs.status; this->statusText = rhs.statusText;
this->method = rhs.method; this->headers = rhs.headers;
this->jar = rhs.jar; this->postvars = rhs.postvars;
this->params = rhs.params; this->getvars = rhs.getvars;
this->body = rhs.body;
#ifdef HAVE_CPP_FUNC_PTR
this->renderer = rhs.renderer;
#endif
};
HTTPBase& operator=(const HTTPBase& rhs) {
this->url = rhs.url; this->kind = rhs.kind;
this->status = rhs.status; this->statusText = rhs.statusText;
this->method = rhs.method; this->headers = rhs.headers;
this->jar = rhs.jar; this->postvars = rhs.postvars;
this->params = rhs.params; this->getvars = rhs.getvars;
this->body = rhs.body;
#ifdef HAVE_CPP_FUNC_PTR
this->renderer = rhs.renderer;
#endif
return *this;
};
public:
URL url;
int kind;
int status;
std::string statusText;
std::string method;
strstr_map_t headers;
CookieJar jar;
strstr_map_t postvars;
strstr_map_t getvars;
// these two are for Router
strstr_map_t params;
std::string routeName;
std::string body;
#ifdef HAVE_CPP_FUNC_PTR
funcptr::function<size_t(const HTTPBase*,std::ostream&)> renderer;
#endif
void write(std::ostream& os) const;
strstr_map_t& GET() { return getvars; };
strstr_map_t& POST() { return postvars; };
strcookie_map_t& COOKIES() { return jar.cookies; };
};
class Response: public HTTPBase {
public:
Response() { this->kind = YAHTTP_TYPE_RESPONSE; };
Response(const HTTPBase& rhs): HTTPBase(rhs) {
this->kind = YAHTTP_TYPE_RESPONSE;
};
Response& operator=(const HTTPBase& rhs) {
HTTPBase::operator=(rhs);
this->kind = YAHTTP_TYPE_RESPONSE;
return *this;
}
friend std::ostream& operator<<(std::ostream& os, const Response &resp);
friend std::istream& operator>>(std::istream& is, Response &resp);
};
class Request: public HTTPBase {
public:
Request() { this->kind = YAHTTP_TYPE_REQUEST; };
Request(const HTTPBase& rhs): HTTPBase(rhs) {
this->kind = YAHTTP_TYPE_REQUEST;
};
Request& operator=(const HTTPBase& rhs) {
HTTPBase::operator=(rhs);
this->kind = YAHTTP_TYPE_REQUEST;
return *this;
}
void setup(const std::string& method, const std::string& url) {
this->url.parse(url);
this->headers["host"] = this->url.host;
this->method = method;
std::transform(this->method.begin(), this->method.end(), this->method.begin(), ::toupper);
this->headers["user-agent"] = "YaHTTP v1.0";
}
void preparePost(postformat_t format = urlencoded) {
std::ostringstream postbuf;
if (format == urlencoded) {
for(strstr_map_t::const_iterator i = POST().begin(); i != POST().end(); i++) {
postbuf << Utility::encodeURL(i->first) << "=" << Utility::encodeURL(i->second) << "&";
}
// remove last bit
if (postbuf.str().length()>0)
body = std::string(postbuf.str().begin(), postbuf.str().end()-1);
else
body = "";
headers["content-type"] = "application/x-www-form-urlencoded; charset=utf-8";
} else if (format == multipart) {
headers["content-type"] = "multipart/form-data; boundary=YaHTTP-12ca543";
for(strstr_map_t::const_iterator i = POST().begin(); i != POST().end(); i++) {
postbuf << "--YaHTTP-12ca543\r\nContent-Disposition: form-data; name=\"" << Utility::encodeURL(i->first) << "; charset=UTF-8\r\n\r\n"
<< Utility::encodeURL(i->second) << "\r\n";
}
}
// set method and change headers
method = "POST";
headers["content-length"] = body.length();
};
friend std::ostream& operator<<(std::ostream& os, const Request &resp);
friend std::istream& operator>>(std::istream& is, Request &resp);
};
template <class T>
class AsyncLoader {
public:
T* target;
int state;
size_t pos;
std::string buffer;
bool chunked;
int chunk_size;
std::ostringstream bodybuf;
long maxbody;
long minbody;
void keyValuePair(const std::string &keyvalue, std::string &key, std::string &value);
void initialize(T* target) {
chunked = false; chunk_size = 0;
bodybuf.str(""); maxbody = 0;
pos = 0; state = 0; this->target = target;
};
int feed(const std::string& somedata);
bool ready() { return state > 1 && bodybuf.str().size() <= static_cast<unsigned long>(maxbody) && bodybuf.str().size() >= static_cast<unsigned long>(minbody); };
void finalize() {
bodybuf.flush();
if (ready()) {
strstr_map_t::iterator pos = target->headers.find("content-type");
if (pos != target->headers.end() && Utility::iequals(pos->second, "application/x-www-form-urlencoded", 32)) {
target->postvars = Utility::parseUrlParameters(bodybuf.str());
}
target->body = bodybuf.str();
}
bodybuf.str("");
this->target = NULL;
};
};
class AsyncResponseLoader: public AsyncLoader<Response> {
};
class AsyncRequestLoader: public AsyncLoader<Request> {
};
};
<|endoftext|> |
<commit_before>#include <fstream>
#include <sstream>
#include <iostream>
#include <cstdlib>
#include <stdint.h>
#include <cstring>
#include <list>
#include <cmath>
#define FILE_MARKER "\xF0\xE1"
#define FILE_VERSION "fpcl.00001" // increment this number file format change !
std::stringstream *linestream;
std::string token = "";
const char *filename;
// return float from linestream
inline float getFloat() {
if (!getline(*linestream, token, ',')) {
std::cerr << "error: could not parse " << filename << std::endl ;
exit(1);
}
return atof(token.c_str());
}
// return unsigned long from linestream
inline float getUlong() {
if (!getline(*linestream, token, ',')) {
std::cerr << "error: could not parse " << filename << std::endl ;
exit(1);
}
return strtoul(token.c_str(),NULL,0);
}
// skip value from linestream
inline float skip() {
if (!getline(*linestream, token, ',')) {
std::cerr << "error: could not parse " << filename << std::endl ;
exit(1);
}
}
int main(int argc, char **argv) {
std::string line = "";
unsigned int index;
float depth, theta, phi, mn95_x, mn95_y, mn95_z;
int lon, lat;
float r=150.0; // webgl sphere radius
float fx,fy,fz;
std::list<uint32_t> sector[360][180];
float step=M_PI/180.0;
uint32_t point_index=0;
unsigned long nb_points=0;
if (argc!=2) {
std::cerr << "usage: " << argv[0] << " <json_file>" << std::endl ;
return 1;
}
// open json
filename=argv[1];
std::ifstream fs(filename);
if (!fs.is_open()) {
std::cerr << "could not open " << filename << std::endl ;
return 1;
}
// extract "nb_points" from json
while (getline(fs, line)) {
if (const char *pos=strstr(line.c_str(),"nb_points")) {
nb_points=strtoul(strchr(pos,':')+1,NULL,0);
break;
}
}
if (!nb_points) {
std::cerr << "error: could not parse" << filename << std::endl ;
return 1;
}
// remove input filename extension
std::string fname=std::string(filename);
fname.erase(fname.find_last_of("."),std::string::npos);
// create .bin output file
std::string outfname=fname+".bin";
std::ofstream outf;
outf.open(outfname.c_str());
if (!outf.is_open()) {
std::cerr << "could not open " << outfname << std::endl ;
return 1;
}
std::cerr << filename << ": parsing " << nb_points << " points" << std::endl;
// 1. parse lines beginning with [0-9] as a csv formatted as:
// "depth, index, theta, phi, mn95-x, mn95-y, mn95-z" (floats)
// 2. store cartesian coordinates in "sector" array as:
// float x, float y, float z
float *mn95=new float[nb_points*3];
float *positions=new float[nb_points*3];
while (getline(fs, line)) {
// skip line not beginning with [0-9]
if (line[0]<'0' || line[0]>'9') continue;
if (point_index>= nb_points) {
std::cerr << filename << ": error: nb_points is invalid ! " << std::endl;
return 1;
}
// read line
linestream=new std::stringstream(line);
// extract fields
depth=getFloat();
index=getUlong();
theta=getFloat();
phi=getFloat();
mn95_x=getFloat();
mn95_y=getFloat();
mn95_z=getFloat();
// compute sector location
lon=((int)round(theta/step)+180)%360;
lat=round(phi/step);
if (lat<0) lat+=180;
lat=(180-lat)%180;
// reference particle in sector lon,lat
sector[lon][lat].push_back(point_index);
// compute cartesian webgl coordinates
phi=(phi-M_PI/2);
theta=theta-M_PI/2;
fx=depth*sin(phi)*cos(theta);
fz=depth*sin(phi)*sin(theta);
fy=-depth*cos(phi);
// store cartesian coordinates
unsigned long k=point_index*3;
positions[k]=fx;
positions[k+1]=fy;
positions[k+2]=fz;
// store mn95 coordinates
mn95[k]=mn95_x;
mn95[k+1]=mn95_y;
mn95[k+2]=mn95_z;
++point_index;
}
if (point_index!=nb_points) {
std::cerr << filename << ": error: nb_points is invalid !" << std::endl;
return 1;
}
// output file marker and version number
outf.write((char*)FILE_MARKER,strlen(FILE_MARKER));
outf.write((char*)FILE_VERSION,strlen(FILE_VERSION));
std::cerr << filename << ": converting to file version " << FILE_VERSION << std::endl;
long int data_offset=outf.tellp();
// output positions formatted as list of x,y,z for each [lon][lat] pair
// and prepare a 360x180 array index formatted as offset,count
std::list<uint32_t> array_index;
for (lat=0; lat<180; ++lat) {
for (lon=0; lon<360; ++lon) {
std::list<uint32_t> *_sector=§or[lon][lat];
// update array index
uint32_t particle_count=_sector->size();
if (particle_count) {
// particles in this sector: store offset and particle count
array_index.push_back((outf.tellp()-data_offset)/sizeof(fx));
array_index.push_back(particle_count);
} else {
// no particles here
array_index.push_back(0);
array_index.push_back(0);
continue;
}
// output particle positions for sector[lon][lat]
for (std::list<uint32_t>::iterator it=_sector->begin(); it!=_sector->end(); ++it) {
uint32_t index=*it;
outf.write((char*)&positions[index*3],sizeof(*positions)*3);
}
}
}
// check integrity
unsigned long positions_byteCount=outf.tellp()-data_offset;
int failure=(positions_byteCount/nb_points!=sizeof(*positions)*3);
std::cerr << filename << ": positions -> " << positions_byteCount << " bytes" << (failure?" -> Invalid count !":"") << std::endl;
if (failure) {
return 1;
}
// output mn95 coordinates
for (lat=0; lat<180; ++lat) {
for (lon=0; lon<360; ++lon) {
std::list<uint32_t> *_sector=§or[lon][lat];
if (!_sector->size()) {
continue;
}
// output mn95 positions for sector[lon][lat]
for (std::list<uint32_t>::iterator it=_sector->begin(); it!=_sector->end(); ++it) {
uint32_t index=*it;
outf.write((char*)&mn95[index],sizeof(*mn95)*3);
}
}
}
// check integrity
long unsigned int mn95_byteCount=(unsigned long)outf.tellp()-data_offset-positions_byteCount;
failure=(mn95_byteCount!=positions_byteCount);
std::cerr << filename << ": mn95 -> " << mn95_byteCount << " bytes" << (failure?" -> Invalid count !":"") << std::endl;
if (failure) {
return 1;
}
// output index formatted as:
// offset, particle_count
for (std::list<uint32_t>::iterator it=array_index.begin(); it!=array_index.end(); ++it) {
uint32_t value=*it;
outf.write((char*)&value,sizeof(value));
}
// check integrity
flush(outf);
long unsigned int index_byteCount=(unsigned long)outf.tellp()-data_offset-positions_byteCount-mn95_byteCount;
failure=(index_byteCount%4);
std::cerr << filename << ": index -> " << index_byteCount << " bytes" << ((index_byteCount%4)?" -> not a multiple of 4 !":"") << std::endl;
if (failure) {
return 1;
}
outf.write((char*)FILE_MARKER,strlen(FILE_MARKER));
outf.close();
if (mn95_byteCount!=positions_byteCount) {
std::cerr << "error: mn95_byteCount != positions_byteCount ! " << std::endl;
return 1;
}
return 0;
}
<commit_msg>stash<commit_after>#include <fstream>
#include <sstream>
#include <iostream>
#include <cstdlib>
#include <stdint.h>
#include <cstring>
#include <list>
#include <cmath>
#define FILE_MARKER "\xF0\xE1"
#define FILE_VERSION "fpcl.00001" // increment this number file format change !
std::stringstream *linestream;
std::string token = "";
const char *filename;
// return float from linestream
inline float getFloat() {
if (!getline(*linestream, token, ',')) {
std::cerr << "error: could not parse " << filename << std::endl ;
exit(1);
}
return atof(token.c_str());
}
// return unsigned long from linestream
inline float getUlong() {
if (!getline(*linestream, token, ',')) {
std::cerr << "error: could not parse " << filename << std::endl ;
exit(1);
}
return strtoul(token.c_str(),NULL,0);
}
// skip value from linestream
inline float skip() {
if (!getline(*linestream, token, ',')) {
std::cerr << "error: could not parse " << filename << std::endl ;
exit(1);
}
}
int main(int argc, char **argv) {
std::string line = "";
unsigned int index;
float depth, theta, phi, mn95_x, mn95_y, mn95_z;
int lon, lat;
float r=150.0; // webgl sphere radius
float fx,fy,fz;
std::list<uint32_t> sector[360][180];
float step=M_PI/180.0;
uint32_t point_index=0;
unsigned long nb_points=0;
if (argc!=2) {
std::cerr << "usage: " << argv[0] << " <json_file>" << std::endl ;
return 1;
}
// open json
filename=argv[1];
std::ifstream fs(filename);
if (!fs.is_open()) {
std::cerr << "could not open " << filename << std::endl ;
return 1;
}
// extract "nb_points" from json
while (getline(fs, line)) {
if (const char *pos=strstr(line.c_str(),"nb_points")) {
nb_points=strtoul(strchr(pos,':')+1,NULL,0);
break;
}
}
if (!nb_points) {
std::cerr << "error: could not parse" << filename << std::endl ;
return 1;
}
// remove input filename extension
std::string fname=std::string(filename);
fname.erase(fname.find_last_of("."),std::string::npos);
// create .bin output file
std::string outfname=fname+".bin";
std::ofstream outf;
outf.open(outfname.c_str());
if (!outf.is_open()) {
std::cerr << "could not open " << outfname << std::endl ;
return 1;
}
std::cerr << filename << ": parsing " << nb_points << " points" << std::endl;
// 1. parse lines beginning with [0-9] as a csv formatted as:
// "depth, index, theta, phi, mn95-x, mn95-y, mn95-z" (floats)
// 2. store cartesian coordinates in "sector" array as:
// float x, float y, float z
float *mn95=new float[nb_points*3];
float *positions=new float[nb_points*3];
while (getline(fs, line)) {
// skip line not beginning with [0-9]
if (line[0]<'0' || line[0]>'9') continue;
if (point_index>= nb_points) {
std::cerr << filename << ": error: nb_points is invalid ! " << std::endl;
return 1;
}
// read line
linestream=new std::stringstream(line);
// extract fields
depth=getFloat();
index=getUlong();
theta=getFloat();
phi=getFloat();
mn95_x=getFloat();
mn95_y=getFloat();
mn95_z=getFloat();
// compute sector location
lon=((int)round(theta/step)+180)%360;
lat=round(phi/step);
if (lat<0) lat+=180;
lat=(180-lat)%180;
// reference particle in sector lon,lat
unsigned long k=point_index*3;
sector[lon][lat].push_back(k);
// compute cartesian webgl coordinates
phi=(phi-M_PI/2);
theta=theta-M_PI/2;
fx=depth*sin(phi)*cos(theta);
fz=depth*sin(phi)*sin(theta);
fy=-depth*cos(phi);
// store cartesian coordinates
positions[k]=fx;
positions[k+1]=fy;
positions[k+2]=fz;
// store mn95 coordinates
mn95[k]=mn95_x;
mn95[k+1]=mn95_y;
mn95[k+2]=mn95_z;
++point_index;
}
if (point_index!=nb_points) {
std::cerr << filename << ": error: nb_points is invalid !" << std::endl;
return 1;
}
// output file marker and version number
outf.write((char*)FILE_MARKER,strlen(FILE_MARKER));
outf.write((char*)FILE_VERSION,strlen(FILE_VERSION));
std::cerr << filename << ": converting to file version " << FILE_VERSION << std::endl;
long int data_offset=outf.tellp();
// output positions formatted as list of x,y,z for each [lon][lat] pair
// and prepare a 360x180 array index formatted as offset,count
std::list<uint32_t> array_index;
for (lat=0; lat<180; ++lat) {
for (lon=0; lon<360; ++lon) {
std::list<uint32_t> *_sector=§or[lon][lat];
// update array index
uint32_t particle_count=_sector->size();
if (particle_count) {
// particles in this sector: store offset and particle count
array_index.push_back((outf.tellp()-data_offset)/sizeof(fx));
array_index.push_back(particle_count);
} else {
// no particles here
array_index.push_back(0);
array_index.push_back(0);
continue;
}
// output particle positions for sector[lon][lat]
for (std::list<uint32_t>::iterator it=_sector->begin(); it!=_sector->end(); ++it) {
uint32_t index=*it;
outf.write((char*)&positions[index],sizeof(*positions)*3);
}
}
}
// check integrity
unsigned long positions_byteCount=outf.tellp()-data_offset;
int failure=(positions_byteCount/nb_points!=sizeof(*positions)*3);
std::cerr << filename << ": positions -> " << positions_byteCount << " bytes" << (failure?" -> Invalid count !":"") << std::endl;
if (failure) {
return 1;
}
// output mn95 coordinates
for (lat=0; lat<180; ++lat) {
for (lon=0; lon<360; ++lon) {
std::list<uint32_t> *_sector=§or[lon][lat];
if (!_sector->size()) {
continue;
}
// output mn95 positions for sector[lon][lat]
for (std::list<uint32_t>::iterator it=_sector->begin(); it!=_sector->end(); ++it) {
uint32_t index=*it;
outf.write((char*)&mn95[index],sizeof(*mn95)*3);
}
}
}
// check integrity
long unsigned int mn95_byteCount=(unsigned long)outf.tellp()-data_offset-positions_byteCount;
failure=(mn95_byteCount!=positions_byteCount);
std::cerr << filename << ": mn95 -> " << mn95_byteCount << " bytes" << (failure?" -> Invalid count !":"") << std::endl;
if (failure) {
return 1;
}
// output index formatted as:
// offset, particle_count
for (std::list<uint32_t>::iterator it=array_index.begin(); it!=array_index.end(); ++it) {
uint32_t value=*it;
outf.write((char*)&value,sizeof(value));
}
// check integrity
flush(outf);
long unsigned int index_byteCount=(unsigned long)outf.tellp()-data_offset-positions_byteCount-mn95_byteCount;
failure=(index_byteCount%4);
std::cerr << filename << ": index -> " << index_byteCount << " bytes" << ((index_byteCount%4)?" -> not a multiple of 4 !":"") << std::endl;
if (failure) {
return 1;
}
outf.write((char*)FILE_MARKER,strlen(FILE_MARKER));
outf.close();
if (mn95_byteCount!=positions_byteCount) {
std::cerr << "error: mn95_byteCount != positions_byteCount ! " << std::endl;
return 1;
}
return 0;
}
<|endoftext|> |
<commit_before>/*
* face-cleaner.cpp
*
* Created on: Nov 15, 2014
* Author: Michael Williams
*/
#include "face-cleaner.h"
#include <vector>
#include <stdio.h>
#include "load_file.h"
#include <opencv2/highgui/highgui.hpp>
using namespace cv;
using namespace std;
namespace facerecognition{
Mat clean_face(Mat face){
CascadeClassifier filter;
if(!filter.load( FACE_FILTER )){
fprintf(stderr, "Filter failed to load\n");
}
vector<Rect> faces;
Mat gray_face;
if(face.channels()==3){
cvtColor( face, gray_face, CV_BGR2GRAY );
} else {
face.copyTo(gray_face);
}
printf("gray: %d\n", gray_face.total());
filter.detectMultiScale( gray_face, faces, 1.1, 2, 0|CV_HAAR_SCALE_IMAGE, Size(30, 30) );
Rect roi;
vector<Rect>::iterator it;
for(it=faces.begin(); it != faces.end(); it++){
printf("rect_area: %d\n", roi.area());
if(it->area() > roi.area()){
roi = (*it);
}
}
Mat tmp(gray_face, roi);
printf("RECT: %d\n", tmp.total());
tmp.convertTo(tmp, CV_8UC3);
equalizeHist( tmp, tmp );
tmp.copyTo(gray_face);
return gray_face.clone();
}
}
const char* clean_and_save(char* input, char* tmp_base){
Mat img = facerecognition::load_file(input);
printf("INPUT: %d\n", img.total());
Mat output = facerecognition::clean_face(img);
printf("INPUT: %d\n", output.total());
string output_file = TMP_FOLDER;
output_file.append(tmp_base);
output_file.append(".png");
imwrite(output_file, output);
return output_file.c_str();
}
<commit_msg>fixed for non-gif<commit_after>/*
* face-cleaner.cpp
*
* Created on: Nov 15, 2014
* Author: Michael Williams
*/
#include "face-cleaner.h"
#include <vector>
#include <stdio.h>
#include "load_file.h"
#include <opencv2/highgui/highgui.hpp>
using namespace cv;
using namespace std;
namespace facerecognition{
Mat clean_face(Mat face){
CascadeClassifier filter;
if(!filter.load( FACE_FILTER )){
fprintf(stderr, "Filter failed to load\n");
}
vector<Rect> faces;
Mat gray_face;
if(face.channels()==3){
cvtColor( face, gray_face, CV_BGR2GRAY );
} else {
face.copyTo(gray_face);
}
printf("gray: %d\n", gray_face.total());
filter.detectMultiScale( gray_face, faces, 1.1, 2, 0, Size(0, 0) );
Rect roi;
vector<Rect>::iterator it;
for(it=faces.begin(); it != faces.end(); it++){
printf("rect_area: %d\n", it->area());
if(it->area() > roi.area()){
roi = (*it);
}
}
Mat tmp(gray_face, roi);
printf("RECT: %d\n", tmp.total());
tmp.convertTo(tmp, CV_8UC3);
equalizeHist( tmp, tmp );
tmp.copyTo(gray_face);
return gray_face.clone();
}
}
const char* clean_and_save(char* input, char* tmp_base){
Mat img = facerecognition::load_file(input);
printf("INPUT: %d\n", img.total());
Mat output = facerecognition::clean_face(img);
printf("INPUT: %d\n", output.total());
string output_file = TMP_FOLDER;
output_file.append(tmp_base);
output_file.append(".png");
imwrite(output_file, output);
return output_file.c_str();
}
<|endoftext|> |
<commit_before>/*********************************************************************
** Author: Zach Colbert
** Date: 30 November 2017
** Description: Library class
*********************************************************************/
/*********************************************************************
** Includes
*********************************************************************/
#include "Library.hpp"
/*********************************************************************
** Description:
*********************************************************************/
Library::Library()
{
// Initialize the relative date of the library
currentDate = 0;
}
/*********************************************************************
** Description:
*********************************************************************/
void Library::addBook(Book*)
{
}
/*********************************************************************
** Description:
*********************************************************************/
void Library::addPatron(Patron*)
{
}
/*********************************************************************
** Description:
*********************************************************************/
std::string Library::checkOutBook(std::string pID, std::string bID)
{
}
/*********************************************************************
** Description:
*********************************************************************/
std::string Library::returnBook(std::string bID)
{
}
/*********************************************************************
** Description:
*********************************************************************/
std::string Library::requestBook(std::string pID, std::string bID)
{
}
/*********************************************************************
** Description:
*********************************************************************/
std::string Library::payFine(std::string pID, double payment)
{
}
/*********************************************************************
** Description:
*********************************************************************/
void Library::incrementCurrentDate()
{
}
// Description
Patron* Library::getPatron(std::string pID)
{
}
// Description
Book* Library::getBook(std::string bID)
{
}<commit_msg>First draft<commit_after>/*********************************************************************
** Author: Zach Colbert
** Date: 30 November 2017
** Description: Library class
*********************************************************************/
/*********************************************************************
** Includes
*********************************************************************/
#include "Library.hpp"
/*********************************************************************
** Description:
*********************************************************************/
Library::Library()
{
// Initialize the relative date of the library
currentDate = 0;
}
/*********************************************************************
** Description:
*********************************************************************/
void Library::addBook(Book* newBook)
{
// vector::push_back will add Book* to the end of the vector
holdings.push_back(newBook);
}
/*********************************************************************
** Description:
*********************************************************************/
void Library::addPatron(Patron* newPatron)
{
// vector::push_back will add Patron* to the end of the vector
members.push_back(newPatron);
}
/*********************************************************************
** Description:
*********************************************************************/
std::string Library::checkOutBook(std::string pID, std::string bID)
{
// if the specified Book is not in the Library, return "book not found"
Book* chkBook = getBook(bID);
if (chkBook == nullptr)
{
return "book not found";
}
// if the specified Patron is not in the Library, return "patron not found"
Patron* chkPatron = getPatron(pID);
if(chkPatron == nullptr)
{
return "patron not found";
}
// if the specified Book is already checked out, return "book already checked out"
if ((*chkBook).getCheckedOutBy() != nullptr)
{
return "book already checked out";
}
// if the specified Book is on hold by another Patron, return "book on hold by other patron"
if ((*chkBook).getRequestedBy() != nullptr)
{
return "book on hold by other patron";
}
// otherwise update the Book's checkedOutBy, dateCheckedOut and Location; if the Book was on hold for this Patron, update requestedBy; update the Patron's checkedOutBooks; return "check out successful"
(*chkBook).setCheckedOutBy(chkPatron);
(*chkBook).setDateCheckedOut(currentDate);
(*chkBook).setLocation(CHECKED_OUT);
if ((*chkBook).getRequestedBy() == (*chkBook).getCheckedOutBy())
{
(*chkBook).setRequestedBy(nullptr);
}
(*chkPatron).addBook(chkBook);
return "check out successful";
}
/*********************************************************************
** Description:
*********************************************************************/
std::string Library::returnBook(std::string bID)
{
// if the specified Book is not in the Library, return "book not found"
Book* chkBook = getBook(bID);
if (chkBook == nullptr)
{
return "book not found";
}
// if the Book is not checked out, return "book already in library"
if ((*chkBook).getCheckedOutBy() == nullptr)
{
return "book already in library";
}
// update the Patron's checkedOutBooks; update the Book's location depending on whether another Patron has requested it; update the Book's checkedOutBy; return "return successful"
(*(*chkBook).getCheckedOutBy()).removeBook(chkBook);
// If the book is not on hold, location goes to ON_SHELF
if ((*chkBook).getRequestedBy() == nullptr)
{
(*chkBook).setLocation(ON_SHELF);
}
// Otherwise, it is on hold and goes to ON_HOLD_SHELF
else
{
(*chkBook).setLocation(ON_HOLD_SHELF);
}
(*chkBook).setCheckedOutBy(nullptr);
return "return successful";
}
/*********************************************************************
** Description:
*********************************************************************/
std::string Library::requestBook(std::string pID, std::string bID)
{
// if the specified Book is not in the Library, return "book not found"
Book* chkBook = getBook(bID);
if (chkBook == nullptr)
{
return "book not found";
}
// if the specified Patron is not in the Library, return "patron not found"
Patron* chkPatron = getPatron(pID);
if (chkPatron == nullptr)
{
return "patron not found";
}
// if the specified Book is already requested, return "book already on hold"
if ((*chkBook).getRequestedBy() != nullptr)
{
return "book already on hold";
}
// update the Book's requestedBy; if the Book is on the shelf, update its location to on hold; return "request successful"
(*chkBook).setRequestedBy(chkPatron);
if ((*chkBook).getLocation() == ON_SHELF)
{
(*chkBook).setLocation(ON_HOLD_SHELF);
}
}
/*********************************************************************
** Description:
*********************************************************************/
std::string Library::payFine(std::string pID, double payment)
{
// takes as a parameter the amount that is being paid (not the negative of that amount)
if (payment < 0)
{
return "invalid payment amount";
}
// if the specified Patron is not in the Library, return "patron not found"
Patron* chkPatron = getPatron(pID);
if (chkPatron == nullptr)
{
return "patron not found";
}
// use amendFine to update the Patron's fine; return "payment successful"
(*chkPatron).amendFine(payment);
return "payment successful";
}
/*********************************************************************
** Description:
*********************************************************************/
void Library::incrementCurrentDate()
{
currentDate++;
}
// Description
Patron* Library::getPatron(std::string pID)
{
bool patronFound = false;
int patronIndex = -1;
for (Patron* chkPatron : members)
{
patronIndex++;
if ((*chkPatron).getIdNum() == pID)
{
patronFound = true;
break;
}
}
if (patronFound == false)
{
return nullptr;
}
else
{
return members[patronIndex];
}
}
// Description
Book* Library::getBook(std::string bID)
{
bool bookFound = false;
int bookIndex = -1;
for (Book* chkBook : holdings)
{
bookIndex++;
if ((*chkBook).getIdCode() == bID)
{
bookFound = true;
break;
}
}
if (bookFound == false)
{
return nullptr;
}
else
{
return holdings[bookIndex];
}
}<|endoftext|> |
<commit_before>// ======================================================================== //
// Copyright 2009-2015 Intel Corporation //
// //
// 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 "instance_intersector.h"
namespace embree
{
namespace isa
{
namespace // FIXME: required?
{
template<int K>
__forceinline void intersectObject(vint<K>* valid, Accel* object, RayK<K>& ray);
template<int K>
__forceinline void occludedObject(vint<K>* valid, Accel* object, RayK<K>& ray);
#if defined (__SSE__)
template<> __forceinline void intersectObject<4>(vint4* valid, Accel* object, Ray4& ray) { object->intersect4(valid,(RTCRay4&)ray); }
template<> __forceinline void occludedObject <4>(vint4* valid, Accel* object, Ray4& ray) { object->occluded4 (valid,(RTCRay4&)ray); }
#endif
#if defined (__AVX__)
template<> __forceinline void intersectObject<8>(vint8* valid, Accel* object, Ray8& ray) { object->intersect8(valid,(RTCRay8&)ray); }
template<> __forceinline void occludedObject <8>(vint8* valid, Accel* object, Ray8& ray) { object->occluded8 (valid,(RTCRay8&)ray); }
#endif
#if defined (__AVX512F__)
template<> __forceinline void intersectObject<16>(vint16* valid, Accel* object, Ray16& ray) { object->intersect16(valid,(RTCRay16&)ray); }
template<> __forceinline void occludedObject <16>(vint16* valid, Accel* object, Ray16& ray) { object->occluded16 (valid,(RTCRay16&)ray); }
#endif
}
template<int K>
void FastInstanceIntersectorK<K>::intersect(vint<K>* valid, const Instance* instance, RayK<K>& ray, size_t item)
{
typedef Vec3<vfloat<K>> Vec3vfK;
typedef AffineSpaceT<LinearSpace3<Vec3vfK>> AffineSpace3vfK;
const Vec3vfK ray_org = ray.org;
const Vec3vfK ray_dir = ray.dir;
const vint<K> ray_geomID = ray.geomID;
const vint<K> ray_instID = ray.instID;
const AffineSpace3vfK world2local(instance->world2local);
ray.org = xfmPoint (world2local,ray_org);
ray.dir = xfmVector(world2local,ray_dir);
ray.geomID = -1;
ray.instID = instance->id;
intersectObject(valid,instance->object,ray);
ray.org = ray_org;
ray.dir = ray_dir;
vbool<K> nohit = ray.geomID == vint<K>(-1);
ray.geomID = select(nohit,ray_geomID,ray.geomID);
ray.instID = select(nohit,ray_instID,ray.instID);
}
template<int K>
void FastInstanceIntersectorK<K>::occluded(vint<K>* valid, const Instance* instance, RayK<K>& ray, size_t item)
{
typedef Vec3<vfloat<K>> Vec3vfK;
typedef AffineSpaceT<LinearSpace3<Vec3vfK>> AffineSpace3vfK;
const Vec3vfK ray_org = ray.org;
const Vec3vfK ray_dir = ray.dir;
const vint<K> ray_geomID = ray.geomID;
const AffineSpace3vfK world2local(instance->world2local);
ray.org = xfmPoint (world2local,ray_org);
ray.dir = xfmVector(world2local,ray_dir);
ray.instID = instance->id;
occludedObject(valid,instance->object,ray);
ray.org = ray_org;
ray.dir = ray_dir;
}
DEFINE_SET_INTERSECTOR4(InstanceIntersector4,FastInstanceIntersector4);
#if defined(__AVX__)
DEFINE_SET_INTERSECTOR8(InstanceIntersector8,FastInstanceIntersector8);
#endif
#if defined(__AVX512F__)
DEFINE_SET_INTERSECTOR16(InstanceIntersector16,FastInstanceIntersector16);
#endif
}
}
<commit_msg>removed some anonymous namespace<commit_after>// ======================================================================== //
// Copyright 2009-2015 Intel Corporation //
// //
// 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 "instance_intersector.h"
namespace embree
{
namespace isa
{
template<int K>
__forceinline void intersectObject(vint<K>* valid, Accel* object, RayK<K>& ray);
template<int K>
__forceinline void occludedObject(vint<K>* valid, Accel* object, RayK<K>& ray);
#if defined (__SSE__)
template<> __forceinline void intersectObject<4>(vint4* valid, Accel* object, Ray4& ray) { object->intersect4(valid,(RTCRay4&)ray); }
template<> __forceinline void occludedObject <4>(vint4* valid, Accel* object, Ray4& ray) { object->occluded4 (valid,(RTCRay4&)ray); }
#endif
#if defined (__AVX__)
template<> __forceinline void intersectObject<8>(vint8* valid, Accel* object, Ray8& ray) { object->intersect8(valid,(RTCRay8&)ray); }
template<> __forceinline void occludedObject <8>(vint8* valid, Accel* object, Ray8& ray) { object->occluded8 (valid,(RTCRay8&)ray); }
#endif
#if defined (__AVX512F__)
template<> __forceinline void intersectObject<16>(vint16* valid, Accel* object, Ray16& ray) { object->intersect16(valid,(RTCRay16&)ray); }
template<> __forceinline void occludedObject <16>(vint16* valid, Accel* object, Ray16& ray) { object->occluded16 (valid,(RTCRay16&)ray); }
#endif
template<int K>
void FastInstanceIntersectorK<K>::intersect(vint<K>* valid, const Instance* instance, RayK<K>& ray, size_t item)
{
typedef Vec3<vfloat<K>> Vec3vfK;
typedef AffineSpaceT<LinearSpace3<Vec3vfK>> AffineSpace3vfK;
const Vec3vfK ray_org = ray.org;
const Vec3vfK ray_dir = ray.dir;
const vint<K> ray_geomID = ray.geomID;
const vint<K> ray_instID = ray.instID;
const AffineSpace3vfK world2local(instance->world2local);
ray.org = xfmPoint (world2local,ray_org);
ray.dir = xfmVector(world2local,ray_dir);
ray.geomID = -1;
ray.instID = instance->id;
intersectObject(valid,instance->object,ray);
ray.org = ray_org;
ray.dir = ray_dir;
vbool<K> nohit = ray.geomID == vint<K>(-1);
ray.geomID = select(nohit,ray_geomID,ray.geomID);
ray.instID = select(nohit,ray_instID,ray.instID);
}
template<int K>
void FastInstanceIntersectorK<K>::occluded(vint<K>* valid, const Instance* instance, RayK<K>& ray, size_t item)
{
typedef Vec3<vfloat<K>> Vec3vfK;
typedef AffineSpaceT<LinearSpace3<Vec3vfK>> AffineSpace3vfK;
const Vec3vfK ray_org = ray.org;
const Vec3vfK ray_dir = ray.dir;
const vint<K> ray_geomID = ray.geomID;
const AffineSpace3vfK world2local(instance->world2local);
ray.org = xfmPoint (world2local,ray_org);
ray.dir = xfmVector(world2local,ray_dir);
ray.instID = instance->id;
occludedObject(valid,instance->object,ray);
ray.org = ray_org;
ray.dir = ray_dir;
}
DEFINE_SET_INTERSECTOR4(InstanceIntersector4,FastInstanceIntersector4);
#if defined(__AVX__)
DEFINE_SET_INTERSECTOR8(InstanceIntersector8,FastInstanceIntersector8);
#endif
#if defined(__AVX512F__)
DEFINE_SET_INTERSECTOR16(InstanceIntersector16,FastInstanceIntersector16);
#endif
}
}
<|endoftext|> |
<commit_before>/* This file is part of the KDE project
Copyright (C) 2003 Sven Lppken <sven@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., 59 Temple Place - Suite 330,
Boston, MA 02111-1307, USA.
*/
#include <kgenericfactory.h>
#include <kparts/componentfactory.h>
#include <kaboutdata.h>
#include "core.h"
#include "summaryview_part.h"
#include "summaryview_plugin.h"
typedef KGenericFactory< SummaryView, Kontact::Core > SummaryViewFactory;
K_EXPORT_COMPONENT_FACTORY( libkontact_summaryplugin,
SummaryViewFactory( "kontact_summaryplugin" ) )
SummaryView::SummaryView( Kontact::Core *core, const char *name, const QStringList& )
: Kontact::Plugin( core, core, name),
mAboutData( 0 )
{
setInstance( SummaryViewFactory::instance() );
}
SummaryView::~SummaryView()
{
}
KParts::Part *SummaryView::createPart()
{
return new SummaryViewPart( core(), "summarypartframe", aboutData(),
this, "summarypart" );
}
const KAboutData *SummaryView::aboutData()
{
if ( !mAboutData ) {
mAboutData = new KAboutData( "kontact/summary", I18N_NOOP("Kontact Summary"),
"0.1",
I18N_NOOP("Kontact Summary View"),
KAboutData::License_LGPL,
"(c) 2003 The Kontact developers" );
mAboutData->addAuthor( "Sven Lueppken", "", "sven@kde.org" );
mAboutData->addAuthor( "Cornelius Schumacher", "", "schumacher@kde.org" );
mAboutData->addAuthor( "Tobias Koenig", "", "tokoe@kde.org" );
}
return mAboutData;
}
#include "summaryview_plugin.moc"
<commit_msg>Use the new KAboutData::setProductName() to get the actions back... (you have to update kdelibs/kdeui and kdelibs/kdecore to get the stuff compiled)<commit_after>/* This file is part of the KDE project
Copyright (C) 2003 Sven Lppken <sven@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., 59 Temple Place - Suite 330,
Boston, MA 02111-1307, USA.
*/
#include <kgenericfactory.h>
#include <kparts/componentfactory.h>
#include <kaboutdata.h>
#include "core.h"
#include "summaryview_part.h"
#include "summaryview_plugin.h"
typedef KGenericFactory< SummaryView, Kontact::Core > SummaryViewFactory;
K_EXPORT_COMPONENT_FACTORY( libkontact_summaryplugin,
SummaryViewFactory( "kontact_summaryplugin" ) )
SummaryView::SummaryView( Kontact::Core *core, const char *name, const QStringList& )
: Kontact::Plugin( core, core, name),
mAboutData( 0 )
{
setInstance( SummaryViewFactory::instance() );
}
SummaryView::~SummaryView()
{
}
KParts::Part *SummaryView::createPart()
{
return new SummaryViewPart( core(), "summarypartframe", aboutData(),
this, "summarypart" );
}
const KAboutData *SummaryView::aboutData()
{
if ( !mAboutData ) {
mAboutData = new KAboutData( "kontactsummary", I18N_NOOP("Kontact Summary"),
"0.1",
I18N_NOOP("Kontact Summary View"),
KAboutData::License_LGPL,
"(c) 2003 The Kontact developers" );
mAboutData->addAuthor( "Sven Lueppken", "", "sven@kde.org" );
mAboutData->addAuthor( "Cornelius Schumacher", "", "schumacher@kde.org" );
mAboutData->addAuthor( "Tobias Koenig", "", "tokoe@kde.org" );
mAboutData->setProductName( "kontact/summary" );
}
return mAboutData;
}
#include "summaryview_plugin.moc"
<|endoftext|> |
<commit_before>/*************************************************************************
*
* $RCSfile: tabpage.cxx,v $
*
* $Revision: 1.7 $
*
* last change: $Author: rt $ $Date: 2003-12-01 13:40:57 $
*
* 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): _______________________________________
*
*
************************************************************************/
#define _SV_TABPAGE_CXX
#include <tools/ref.hxx>
#ifndef _SV_RC_H
#include <rc.h>
#endif
#ifndef _SV_SVDATA_HXX
#include <svdata.hxx>
#endif
#ifndef _SV_SVAPP_HXX
#include <svapp.hxx>
#endif
#ifndef _SV_EVENT_HXX
#include <event.hxx>
#endif
#ifndef _SV_TABPAGE_HXX
#include <tabpage.hxx>
#endif
#ifndef _SV_TABCTRL_HXX
#include <tabctrl.hxx>
#endif
#ifndef _COM_SUN_STAR_ACCESSIBILITY_XACCESSIBLE_HPP_
#include <com/sun/star/accessibility/XAccessible.hpp>
#endif
// =======================================================================
void TabPage::ImplInit( Window* pParent, WinBits nStyle )
{
if ( !(nStyle & WB_NODIALOGCONTROL) )
nStyle |= WB_DIALOGCONTROL;
Window::ImplInit( pParent, nStyle, NULL );
ImplInitSettings();
}
// -----------------------------------------------------------------------
void TabPage::ImplInitSettings()
{
Window* pParent = GetParent();
if ( pParent->IsChildTransparentModeEnabled() && !IsControlBackground() )
{
EnableChildTransparentMode( TRUE );
SetParentClipMode( PARENTCLIPMODE_NOCLIP );
SetPaintTransparent( TRUE );
SetBackground();
}
else
{
EnableChildTransparentMode( FALSE );
SetParentClipMode( 0 );
SetPaintTransparent( FALSE );
if ( IsControlBackground() )
SetBackground( GetControlBackground() );
else
SetBackground( pParent->GetBackground() );
}
}
// -----------------------------------------------------------------------
TabPage::TabPage( Window* pParent, WinBits nStyle ) :
Window( WINDOW_TABPAGE )
{
ImplInit( pParent, nStyle );
}
// -----------------------------------------------------------------------
TabPage::TabPage( Window* pParent, const ResId& rResId ) :
Window( WINDOW_TABPAGE )
{
rResId.SetRT( RSC_TABPAGE );
WinBits nStyle = ImplInitRes( rResId );
ImplInit( pParent, nStyle );
ImplLoadRes( rResId );
if ( !(nStyle & WB_HIDE) )
Show();
}
// -----------------------------------------------------------------------
void TabPage::StateChanged( StateChangedType nType )
{
Window::StateChanged( nType );
if ( nType == STATE_CHANGE_INITSHOW )
{
if ( GetSettings().GetStyleSettings().GetAutoMnemonic() )
ImplWindowAutoMnemonic( this );
}
else if ( nType == STATE_CHANGE_CONTROLBACKGROUND )
{
ImplInitSettings();
Invalidate();
}
}
// -----------------------------------------------------------------------
void TabPage::DataChanged( const DataChangedEvent& rDCEvt )
{
Window::DataChanged( rDCEvt );
if ( (rDCEvt.GetType() == DATACHANGED_SETTINGS) &&
(rDCEvt.GetFlags() & SETTINGS_STYLE) )
{
ImplInitSettings();
Invalidate();
}
}
// -----------------------------------------------------------------------
void TabPage::ActivatePage()
{
}
// -----------------------------------------------------------------------
void TabPage::DeactivatePage()
{
}
// -----------------------------------------------------------------------
::com::sun::star::uno::Reference< ::com::sun::star::accessibility::XAccessible > TabPage::CreateAccessible()
{
// TODO: remove this method (incompatible)
return Window::CreateAccessible();
}
<commit_msg>INTEGRATION: CWS vclcleanup02 (1.7.4); FILE MERGED 2003/12/17 16:05:57 mt 1.7.4.2: #i23061# header cleanup, remove #ifdef ???_CXX and #define ???_CXX, also removed .impl files and fixed soke windows compiler warnings 2003/12/10 15:59:42 mt 1.7.4.1: #i23061# VCL cleanup, removed headers, methods and types...<commit_after>/*************************************************************************
*
* $RCSfile: tabpage.cxx,v $
*
* $Revision: 1.8 $
*
* last change: $Author: vg $ $Date: 2004-01-06 14:18:29 $
*
* 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 <tools/ref.hxx>
#ifndef _SV_RC_H
#include <tools/rc.h>
#endif
#ifndef _SV_SVDATA_HXX
#include <svdata.hxx>
#endif
#ifndef _SV_SVAPP_HXX
#include <svapp.hxx>
#endif
#ifndef _SV_EVENT_HXX
#include <event.hxx>
#endif
#ifndef _SV_TABPAGE_HXX
#include <tabpage.hxx>
#endif
#ifndef _SV_TABCTRL_HXX
#include <tabctrl.hxx>
#endif
#ifndef _COM_SUN_STAR_ACCESSIBILITY_XACCESSIBLE_HPP_
#include <com/sun/star/accessibility/XAccessible.hpp>
#endif
// =======================================================================
void TabPage::ImplInit( Window* pParent, WinBits nStyle )
{
if ( !(nStyle & WB_NODIALOGCONTROL) )
nStyle |= WB_DIALOGCONTROL;
Window::ImplInit( pParent, nStyle, NULL );
ImplInitSettings();
}
// -----------------------------------------------------------------------
void TabPage::ImplInitSettings()
{
Window* pParent = GetParent();
if ( pParent->IsChildTransparentModeEnabled() && !IsControlBackground() )
{
EnableChildTransparentMode( TRUE );
SetParentClipMode( PARENTCLIPMODE_NOCLIP );
SetPaintTransparent( TRUE );
SetBackground();
}
else
{
EnableChildTransparentMode( FALSE );
SetParentClipMode( 0 );
SetPaintTransparent( FALSE );
if ( IsControlBackground() )
SetBackground( GetControlBackground() );
else
SetBackground( pParent->GetBackground() );
}
}
// -----------------------------------------------------------------------
TabPage::TabPage( Window* pParent, WinBits nStyle ) :
Window( WINDOW_TABPAGE )
{
ImplInit( pParent, nStyle );
}
// -----------------------------------------------------------------------
TabPage::TabPage( Window* pParent, const ResId& rResId ) :
Window( WINDOW_TABPAGE )
{
rResId.SetRT( RSC_TABPAGE );
WinBits nStyle = ImplInitRes( rResId );
ImplInit( pParent, nStyle );
ImplLoadRes( rResId );
if ( !(nStyle & WB_HIDE) )
Show();
}
// -----------------------------------------------------------------------
void TabPage::StateChanged( StateChangedType nType )
{
Window::StateChanged( nType );
if ( nType == STATE_CHANGE_INITSHOW )
{
if ( GetSettings().GetStyleSettings().GetAutoMnemonic() )
ImplWindowAutoMnemonic( this );
}
else if ( nType == STATE_CHANGE_CONTROLBACKGROUND )
{
ImplInitSettings();
Invalidate();
}
}
// -----------------------------------------------------------------------
void TabPage::DataChanged( const DataChangedEvent& rDCEvt )
{
Window::DataChanged( rDCEvt );
if ( (rDCEvt.GetType() == DATACHANGED_SETTINGS) &&
(rDCEvt.GetFlags() & SETTINGS_STYLE) )
{
ImplInitSettings();
Invalidate();
}
}
// -----------------------------------------------------------------------
void TabPage::ActivatePage()
{
}
// -----------------------------------------------------------------------
void TabPage::DeactivatePage()
{
}
// -----------------------------------------------------------------------
::com::sun::star::uno::Reference< ::com::sun::star::accessibility::XAccessible > TabPage::CreateAccessible()
{
// TODO: remove this method (incompatible)
return Window::CreateAccessible();
}
<|endoftext|> |
<commit_before>/*************************************************************************
*
* OpenOffice.org - a multi-platform office productivity suite
*
* $RCSfile: salsys.cxx,v $
*
* $Revision: 1.14 $
*
* last change: $Author: vg $ $Date: 2006-08-16 16:17: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
*
************************************************************************/
#include <salunx.h>
#include <salsys.hxx>
#include <dtint.hxx>
#include <msgbox.hxx>
#include <button.hxx>
#include <svdata.hxx>
#include <saldata.hxx>
#include <salinst.h>
#include <saldisp.hxx>
#include <salsys.h>
SalSystem* X11SalInstance::CreateSalSystem()
{
return new X11SalSystem();
}
// -----------------------------------------------------------------------
X11SalSystem::~X11SalSystem()
{
}
// for the moment only handle xinerama case
unsigned int X11SalSystem::GetDisplayScreenCount()
{
SalDisplay* pSalDisp = GetX11SalData()->GetDisplay();
return pSalDisp->IsXinerama() ? pSalDisp->GetXineramaScreens().size() : 1U;
}
Rectangle X11SalSystem::GetDisplayScreenPosSizePixel( unsigned int nScreen )
{
Rectangle aRet;
SalDisplay* pSalDisp = GetX11SalData()->GetDisplay();
if( pSalDisp->IsXinerama() )
{
const std::vector< Rectangle >& rScreens = pSalDisp->GetXineramaScreens();
if( nScreen < rScreens.size() )
aRet = rScreens[nScreen];
}
else
aRet = Rectangle( Point(), pSalDisp->GetScreenSize() );
return aRet;
}
int X11SalSystem::ShowNativeDialog( const String& rTitle, const String& rMessage, const std::list< String >& rButtons, int nDefButton )
{
int nRet = -1;
ImplSVData* pSVData = ImplGetSVData();
if( pSVData->mpIntroWindow )
pSVData->mpIntroWindow->Hide();
WarningBox aWarn( NULL, WB_STDWORK, rMessage );
aWarn.SetText( rTitle );
aWarn.Clear();
USHORT nButton = 0;
for( std::list< String >::const_iterator it = rButtons.begin(); it != rButtons.end(); ++it )
{
aWarn.AddButton( *it, nButton+1, nButton == (USHORT)nDefButton ? BUTTONDIALOG_DEFBUTTON : 0 );
nButton++;
}
aWarn.SetFocusButton( (USHORT)nDefButton+1 );
nRet = ((int)aWarn.Execute()) - 1;
// normalize behaviour, actually this should never happen
if( nRet < -1 || nRet >= int(rButtons.size()) )
nRet = -1;
return nRet;
}
int X11SalSystem::ShowNativeMessageBox(const String& rTitle, const String& rMessage, int nButtonCombination, int nDefaultButton)
{
int nDefButton = 0;
std::list< String > aButtons;
int nButtonIds[5], nBut = 0;
if( nButtonCombination == SALSYSTEM_SHOWNATIVEMSGBOX_BTNCOMBI_OK ||
nButtonCombination == SALSYSTEM_SHOWNATIVEMSGBOX_BTNCOMBI_OK_CANCEL )
{
aButtons.push_back( Button::GetStandardText( BUTTON_OK ) );
nButtonIds[nBut++] = SALSYSTEM_SHOWNATIVEMSGBOX_BTN_OK;
}
if( nButtonCombination == SALSYSTEM_SHOWNATIVEMSGBOX_BTNCOMBI_YES_NO_CANCEL ||
nButtonCombination == SALSYSTEM_SHOWNATIVEMSGBOX_BTNCOMBI_YES_NO )
{
aButtons.push_back( Button::GetStandardText( BUTTON_YES ) );
nButtonIds[nBut++] = SALSYSTEM_SHOWNATIVEMSGBOX_BTN_YES;
aButtons.push_back( Button::GetStandardText( BUTTON_NO ) );
nButtonIds[nBut++] = SALSYSTEM_SHOWNATIVEMSGBOX_BTN_NO;
if( nDefaultButton == SALSYSTEM_SHOWNATIVEMSGBOX_BTN_NO )
nDefButton = 1;
}
if( nButtonCombination == SALSYSTEM_SHOWNATIVEMSGBOX_BTNCOMBI_OK_CANCEL ||
nButtonCombination == SALSYSTEM_SHOWNATIVEMSGBOX_BTNCOMBI_YES_NO_CANCEL ||
nButtonCombination == SALSYSTEM_SHOWNATIVEMSGBOX_BTNCOMBI_RETRY_CANCEL )
{
if( nButtonCombination == SALSYSTEM_SHOWNATIVEMSGBOX_BTNCOMBI_RETRY_CANCEL )
{
aButtons.push_back( Button::GetStandardText( BUTTON_RETRY ) );
nButtonIds[nBut++] = SALSYSTEM_SHOWNATIVEMSGBOX_BTN_RETRY;
}
aButtons.push_back( Button::GetStandardText( BUTTON_CANCEL ) );
nButtonIds[nBut++] = SALSYSTEM_SHOWNATIVEMSGBOX_BTN_CANCEL;
if( nDefaultButton == SALSYSTEM_SHOWNATIVEMSGBOX_BTN_CANCEL )
nDefButton = aButtons.size()-1;
}
if( nButtonCombination == SALSYSTEM_SHOWNATIVEMSGBOX_BTNCOMBI_ABORT_RETRY_IGNORE )
{
aButtons.push_back( Button::GetStandardText( BUTTON_ABORT ) );
nButtonIds[nBut++] = SALSYSTEM_SHOWNATIVEMSGBOX_BTN_ABORT;
aButtons.push_back( Button::GetStandardText( BUTTON_RETRY ) );
nButtonIds[nBut++] = SALSYSTEM_SHOWNATIVEMSGBOX_BTN_RETRY;
aButtons.push_back( Button::GetStandardText( BUTTON_IGNORE ) );
nButtonIds[nBut++] = SALSYSTEM_SHOWNATIVEMSGBOX_BTN_IGNORE;
switch( nDefaultButton )
{
case SALSYSTEM_SHOWNATIVEMSGBOX_BTN_RETRY: nDefButton = 1;break;
case SALSYSTEM_SHOWNATIVEMSGBOX_BTN_IGNORE: nDefButton = 2;break;
}
}
int nResult = ShowNativeDialog( rTitle, rMessage, aButtons, nDefButton );
return nResult != -1 ? nButtonIds[ nResult ] : 0;
}
<commit_msg>INTEGRATION: CWS pchfix02 (1.14.4); FILE MERGED 2006/09/01 17:58:06 kaib 1.14.4.1: #i68856# Added header markers and pch files<commit_after>/*************************************************************************
*
* OpenOffice.org - a multi-platform office productivity suite
*
* $RCSfile: salsys.cxx,v $
*
* $Revision: 1.15 $
*
* last change: $Author: obo $ $Date: 2006-09-17 12:35:42 $
*
* The Contents of this file are made available subject to
* the terms of GNU Lesser General Public License Version 2.1.
*
*
* GNU Lesser General Public License Version 2.1
* =============================================
* Copyright 2005 by Sun Microsystems, Inc.
* 901 San Antonio Road, Palo Alto, CA 94303, USA
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License version 2.1, as published by the Free Software Foundation.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston,
* MA 02111-1307 USA
*
************************************************************************/
// MARKER(update_precomp.py): autogen include statement, do not remove
#include "precompiled_vcl.hxx"
#include <salunx.h>
#include <salsys.hxx>
#include <dtint.hxx>
#include <msgbox.hxx>
#include <button.hxx>
#include <svdata.hxx>
#include <saldata.hxx>
#include <salinst.h>
#include <saldisp.hxx>
#include <salsys.h>
SalSystem* X11SalInstance::CreateSalSystem()
{
return new X11SalSystem();
}
// -----------------------------------------------------------------------
X11SalSystem::~X11SalSystem()
{
}
// for the moment only handle xinerama case
unsigned int X11SalSystem::GetDisplayScreenCount()
{
SalDisplay* pSalDisp = GetX11SalData()->GetDisplay();
return pSalDisp->IsXinerama() ? pSalDisp->GetXineramaScreens().size() : 1U;
}
Rectangle X11SalSystem::GetDisplayScreenPosSizePixel( unsigned int nScreen )
{
Rectangle aRet;
SalDisplay* pSalDisp = GetX11SalData()->GetDisplay();
if( pSalDisp->IsXinerama() )
{
const std::vector< Rectangle >& rScreens = pSalDisp->GetXineramaScreens();
if( nScreen < rScreens.size() )
aRet = rScreens[nScreen];
}
else
aRet = Rectangle( Point(), pSalDisp->GetScreenSize() );
return aRet;
}
int X11SalSystem::ShowNativeDialog( const String& rTitle, const String& rMessage, const std::list< String >& rButtons, int nDefButton )
{
int nRet = -1;
ImplSVData* pSVData = ImplGetSVData();
if( pSVData->mpIntroWindow )
pSVData->mpIntroWindow->Hide();
WarningBox aWarn( NULL, WB_STDWORK, rMessage );
aWarn.SetText( rTitle );
aWarn.Clear();
USHORT nButton = 0;
for( std::list< String >::const_iterator it = rButtons.begin(); it != rButtons.end(); ++it )
{
aWarn.AddButton( *it, nButton+1, nButton == (USHORT)nDefButton ? BUTTONDIALOG_DEFBUTTON : 0 );
nButton++;
}
aWarn.SetFocusButton( (USHORT)nDefButton+1 );
nRet = ((int)aWarn.Execute()) - 1;
// normalize behaviour, actually this should never happen
if( nRet < -1 || nRet >= int(rButtons.size()) )
nRet = -1;
return nRet;
}
int X11SalSystem::ShowNativeMessageBox(const String& rTitle, const String& rMessage, int nButtonCombination, int nDefaultButton)
{
int nDefButton = 0;
std::list< String > aButtons;
int nButtonIds[5], nBut = 0;
if( nButtonCombination == SALSYSTEM_SHOWNATIVEMSGBOX_BTNCOMBI_OK ||
nButtonCombination == SALSYSTEM_SHOWNATIVEMSGBOX_BTNCOMBI_OK_CANCEL )
{
aButtons.push_back( Button::GetStandardText( BUTTON_OK ) );
nButtonIds[nBut++] = SALSYSTEM_SHOWNATIVEMSGBOX_BTN_OK;
}
if( nButtonCombination == SALSYSTEM_SHOWNATIVEMSGBOX_BTNCOMBI_YES_NO_CANCEL ||
nButtonCombination == SALSYSTEM_SHOWNATIVEMSGBOX_BTNCOMBI_YES_NO )
{
aButtons.push_back( Button::GetStandardText( BUTTON_YES ) );
nButtonIds[nBut++] = SALSYSTEM_SHOWNATIVEMSGBOX_BTN_YES;
aButtons.push_back( Button::GetStandardText( BUTTON_NO ) );
nButtonIds[nBut++] = SALSYSTEM_SHOWNATIVEMSGBOX_BTN_NO;
if( nDefaultButton == SALSYSTEM_SHOWNATIVEMSGBOX_BTN_NO )
nDefButton = 1;
}
if( nButtonCombination == SALSYSTEM_SHOWNATIVEMSGBOX_BTNCOMBI_OK_CANCEL ||
nButtonCombination == SALSYSTEM_SHOWNATIVEMSGBOX_BTNCOMBI_YES_NO_CANCEL ||
nButtonCombination == SALSYSTEM_SHOWNATIVEMSGBOX_BTNCOMBI_RETRY_CANCEL )
{
if( nButtonCombination == SALSYSTEM_SHOWNATIVEMSGBOX_BTNCOMBI_RETRY_CANCEL )
{
aButtons.push_back( Button::GetStandardText( BUTTON_RETRY ) );
nButtonIds[nBut++] = SALSYSTEM_SHOWNATIVEMSGBOX_BTN_RETRY;
}
aButtons.push_back( Button::GetStandardText( BUTTON_CANCEL ) );
nButtonIds[nBut++] = SALSYSTEM_SHOWNATIVEMSGBOX_BTN_CANCEL;
if( nDefaultButton == SALSYSTEM_SHOWNATIVEMSGBOX_BTN_CANCEL )
nDefButton = aButtons.size()-1;
}
if( nButtonCombination == SALSYSTEM_SHOWNATIVEMSGBOX_BTNCOMBI_ABORT_RETRY_IGNORE )
{
aButtons.push_back( Button::GetStandardText( BUTTON_ABORT ) );
nButtonIds[nBut++] = SALSYSTEM_SHOWNATIVEMSGBOX_BTN_ABORT;
aButtons.push_back( Button::GetStandardText( BUTTON_RETRY ) );
nButtonIds[nBut++] = SALSYSTEM_SHOWNATIVEMSGBOX_BTN_RETRY;
aButtons.push_back( Button::GetStandardText( BUTTON_IGNORE ) );
nButtonIds[nBut++] = SALSYSTEM_SHOWNATIVEMSGBOX_BTN_IGNORE;
switch( nDefaultButton )
{
case SALSYSTEM_SHOWNATIVEMSGBOX_BTN_RETRY: nDefButton = 1;break;
case SALSYSTEM_SHOWNATIVEMSGBOX_BTN_IGNORE: nDefButton = 2;break;
}
}
int nResult = ShowNativeDialog( rTitle, rMessage, aButtons, nDefButton );
return nResult != -1 ? nButtonIds[ nResult ] : 0;
}
<|endoftext|> |
<commit_before>/*************************************************************************
*
* OpenOffice.org - a multi-platform office productivity suite
*
* $RCSfile: soicon.cxx,v $
*
* $Revision: 1.17 $
*
* last change: $Author: rt $ $Date: 2005-09-09 13:02:58 $
*
* 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 <salunx.h>
#ifndef _SV_SALDISP_HXX
#include <saldisp.hxx>
#endif
#ifndef _SV_SALBMP_HXX
#include <salbmp.hxx>
#endif
#ifndef _SV_SALBTYPE_HXX
#include <salbtype.hxx>
#endif
#ifndef _SV_IMPBMP_HXX
#include <impbmp.hxx>
#endif
#ifndef _SV_BITMAP_HXX
#include <bitmap.hxx>
#endif
#ifndef _SV_BITMAP_HXX
#include <bitmapex.hxx>
#endif
#ifndef _SV_GRAPH_HXX
#include <graph.hxx>
#endif
#ifndef _SV_SOICON_HXX
#include <soicon.hxx>
#endif
#ifndef _SV_SVDATA_HXX
#include <svdata.hxx>
#endif
#ifndef _SV_SALBMP_H
#include <salbmp.h>
#endif
#include <svids.hrc>
BOOL SelectAppIconPixmap( SalDisplay *pDisplay, USHORT nIcon, USHORT iconSize,
Pixmap& icon_pixmap, Pixmap& icon_mask)
{
USHORT nIconSizeOffset;
if( iconSize >= 48 )
nIconSizeOffset = SV_ICON_SIZE48_START;
else if( iconSize >= 32 )
nIconSizeOffset = SV_ICON_SIZE32_START;
else if( iconSize >= 16 )
nIconSizeOffset = SV_ICON_SIZE16_START;
else
return FALSE;
BitmapEx aIcon( ResId(nIconSizeOffset + nIcon, ImplGetResMgr()));
if( TRUE == aIcon.IsEmpty() )
return FALSE;
SalTwoRect aRect;
aRect.mnSrcX = 0; aRect.mnSrcY = 0;
aRect.mnSrcWidth = iconSize; aRect.mnSrcHeight = iconSize;
aRect.mnDestX = 0; aRect.mnDestY = 0;
aRect.mnDestWidth = iconSize; aRect.mnDestHeight = iconSize;
X11SalBitmap *pBitmap = static_cast < X11SalBitmap * >
(aIcon.ImplGetBitmapImpBitmap()->ImplGetSalBitmap());
icon_pixmap = XCreatePixmap( pDisplay->GetDisplay(), pDisplay->GetRootWindow(),
iconSize, iconSize, pDisplay->GetRootVisual()->GetDepth());
pBitmap->ImplDraw(icon_pixmap, pDisplay->GetRootVisual()->GetDepth(),
aRect, DefaultGC(pDisplay->GetDisplay(), pDisplay->GetScreenNumber()), false);
icon_mask = None;
if( TRANSPARENT_BITMAP == aIcon.GetTransparentType() )
{
icon_mask = XCreatePixmap( pDisplay->GetDisplay(),
pDisplay->GetRootWindow(), iconSize, iconSize, 1);
XGCValues aValues;
aValues.foreground = 0xffffffff;
aValues.background = 0;
aValues.function = GXcopy;
GC aMonoGC = XCreateGC( pDisplay->GetDisplay(), icon_mask,
GCFunction|GCForeground|GCBackground, &aValues );
Bitmap aMask = aIcon.GetMask();
aMask.Invert();
X11SalBitmap *pMask = static_cast < X11SalBitmap * >
(aMask.ImplGetImpBitmap()->ImplGetSalBitmap());
pMask->ImplDraw(icon_mask, 1, aRect, aMonoGC, false);
XFreeGC( pDisplay->GetDisplay(), aMonoGC );
}
return TRUE;
}
<commit_msg>INTEGRATION: CWS vcl39 (1.16.32); FILE MERGED 2005/03/18 14:56:37 pl 1.16.32.1: #i42355# emergency mode without vcl resource<commit_after>/*************************************************************************
*
* OpenOffice.org - a multi-platform office productivity suite
*
* $RCSfile: soicon.cxx,v $
*
* $Revision: 1.18 $
*
* last change: $Author: hr $ $Date: 2005-09-28 15:01:23 $
*
* 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 <salunx.h>
#ifndef _SV_SALDISP_HXX
#include <saldisp.hxx>
#endif
#ifndef _SV_SALBMP_HXX
#include <salbmp.hxx>
#endif
#ifndef _SV_SALBTYPE_HXX
#include <salbtype.hxx>
#endif
#ifndef _SV_IMPBMP_HXX
#include <impbmp.hxx>
#endif
#ifndef _SV_BITMAP_HXX
#include <bitmap.hxx>
#endif
#ifndef _SV_BITMAP_HXX
#include <bitmapex.hxx>
#endif
#ifndef _SV_GRAPH_HXX
#include <graph.hxx>
#endif
#ifndef _SV_SOICON_HXX
#include <soicon.hxx>
#endif
#ifndef _SV_SVDATA_HXX
#include <svdata.hxx>
#endif
#ifndef _SV_SALBMP_H
#include <salbmp.h>
#endif
#include <svids.hrc>
BOOL SelectAppIconPixmap( SalDisplay *pDisplay, USHORT nIcon, USHORT iconSize,
Pixmap& icon_pixmap, Pixmap& icon_mask)
{
if( ! ImplGetResMgr() )
return FALSE;
USHORT nIconSizeOffset;
if( iconSize >= 48 )
nIconSizeOffset = SV_ICON_SIZE48_START;
else if( iconSize >= 32 )
nIconSizeOffset = SV_ICON_SIZE32_START;
else if( iconSize >= 16 )
nIconSizeOffset = SV_ICON_SIZE16_START;
else
return FALSE;
BitmapEx aIcon( ResId(nIconSizeOffset + nIcon, ImplGetResMgr()));
if( TRUE == aIcon.IsEmpty() )
return FALSE;
SalTwoRect aRect;
aRect.mnSrcX = 0; aRect.mnSrcY = 0;
aRect.mnSrcWidth = iconSize; aRect.mnSrcHeight = iconSize;
aRect.mnDestX = 0; aRect.mnDestY = 0;
aRect.mnDestWidth = iconSize; aRect.mnDestHeight = iconSize;
X11SalBitmap *pBitmap = static_cast < X11SalBitmap * >
(aIcon.ImplGetBitmapImpBitmap()->ImplGetSalBitmap());
icon_pixmap = XCreatePixmap( pDisplay->GetDisplay(), pDisplay->GetRootWindow(),
iconSize, iconSize, pDisplay->GetRootVisual()->GetDepth());
pBitmap->ImplDraw(icon_pixmap, pDisplay->GetRootVisual()->GetDepth(),
aRect, DefaultGC(pDisplay->GetDisplay(), pDisplay->GetScreenNumber()), false);
icon_mask = None;
if( TRANSPARENT_BITMAP == aIcon.GetTransparentType() )
{
icon_mask = XCreatePixmap( pDisplay->GetDisplay(),
pDisplay->GetRootWindow(), iconSize, iconSize, 1);
XGCValues aValues;
aValues.foreground = 0xffffffff;
aValues.background = 0;
aValues.function = GXcopy;
GC aMonoGC = XCreateGC( pDisplay->GetDisplay(), icon_mask,
GCFunction|GCForeground|GCBackground, &aValues );
Bitmap aMask = aIcon.GetMask();
aMask.Invert();
X11SalBitmap *pMask = static_cast < X11SalBitmap * >
(aMask.ImplGetImpBitmap()->ImplGetSalBitmap());
pMask->ImplDraw(icon_mask, 1, aRect, aMonoGC, false);
XFreeGC( pDisplay->GetDisplay(), aMonoGC );
}
return TRUE;
}
<|endoftext|> |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.