text stringlengths 54 60.6k |
|---|
<commit_before>#include "blockstream.h"
#define MASK_5BIT 0x000001F
#define MASK_10BIT 0x00003FF
#define MASK_16BIT 0x000FFFF
#define MASK_26BIT 0x3FFFFFF
#define MASK_28BIT 0xFFFFFFF
namespace redsea {
uint16_t syndrome(int vec) {
uint16_t synd_reg = 0x000;
int bit,l;
for (int k=25; k>=0; k--) {
bit = (vec & (1 << k));
l = (synd_reg & 0x200); // Store lefmost bit of register
synd_reg = (synd_reg << 1) & 0x3FF; // Rotate register
synd_reg ^= (bit ? 0x31B : 0x00); // Premultiply input by x^325 mod g(x)
synd_reg ^= (l ? 0x1B9 : 0x00); // Division mod 2 by g(x)
}
return synd_reg;
}
BlockStream::BlockStream() : has_sync_for_(5), group_data_(4), has_block_(5),
bitcount_(0), left_to_read_(0), bit_stream_(), wideblock_(0), block_has_errors_(50)
{
offset_word_ = {0x0FC, 0x198, 0x168, 0x350, 0x1B4};
block_for_offset_ = {0, 1, 2, 2, 3};
error_lookup_ = {
{0x200, 0b1000000000000000},
{0x300, 0b1100000000000000},
{0x180, 0b0110000000000000},
{0x0c0, 0b0011000000000000},
{0x060, 0b0001100000000000},
{0x030, 0b0000110000000000},
{0x018, 0b0000011000000000},
{0x00c, 0b0000001100000000},
{0x006, 0b0000000110000000},
{0x003, 0b0000000011000000},
{0x2dd, 0b0000000001100000},
{0x3b2, 0b0000000000110000},
{0x1d9, 0b0000000000011000},
{0x230, 0b0000000000001100},
{0x118, 0b0000000000000110},
{0x08c, 0b0000000000000011},
{0x046, 0b0000000000000001}
};
}
void BlockStream::uncorrectable() {
printf(":offset %d not received\n",expected_offset_);
int data_length = 0;
// TODO: return partial group
/*if (has_block_[A]) {
data_length = 1;
if (has_block_[B]) {
data_length = 2;
if (has_block_[C] || has_block_[CI]) {
data_length = 3;
}
}
}*/
block_has_errors_[block_counter_ % block_has_errors_.size()] = true;
int erroneous_blocks = 0;
for (bool e : block_has_errors_) {
if (e)
erroneous_blocks ++;
}
// Sync is lost when >45 out of last 50 blocks are erroneous (Section C.1.2)
if (is_in_sync_ && erroneous_blocks > 45) {
is_in_sync_ = false;
for (int i=0; i<(int)block_has_errors_.size(); i++)
block_has_errors_[i] = false;
pi_ = 0x0000;
printf(":too many errors, sync lost\n");
}
for (int o=A; o<=D; o++)
has_block_[o] = false;
}
std::vector<uint16_t> BlockStream::getNextGroup() {
has_whole_group_ = false;
while (!(has_whole_group_ || isEOF())) {
// Compensate for clock slip corrections
bitcount_ += 26 - left_to_read_;
// Read from radio
for (int i=0; i < (is_in_sync_ ? left_to_read_ : 1); i++, bitcount_++) {
wideblock_ = (wideblock_ << 1) + bit_stream_.getNextBit();
}
left_to_read_ = 26;
wideblock_ &= MASK_28BIT;
int block = (wideblock_ >> 1) & MASK_26BIT;
// Find the offsets for which the syndrome is zero
bool has_sync_for_any = false;
for (int o=A; o<=D; o++) {
has_sync_for_[o] = (syndrome(block ^ offset_word_[o]) == 0x000);
has_sync_for_any |= has_sync_for_[o];
}
// Acquire sync
if (!is_in_sync_) {
if (has_sync_for_any) {
for (int o=A; o<=D; o++) {
if (has_sync_for_[o]) {
int dist = bitcount_ - prevbitcount_;
if (dist % 26 == 0 && dist <= 156 &&
(block_for_offset_[prevsync_] + dist/26) % 4 == block_for_offset_[o]) {
is_in_sync_ = true;
expected_offset_ = o;
printf(":sync!\n");
} else {
prevbitcount_ = bitcount_;
prevsync_ = o;
}
}
}
}
}
// Synchronous decoding
if (is_in_sync_) {
block_counter_ ++;
uint16_t message = block >> 10;
if (expected_offset_ == C && !has_sync_for_[C] && has_sync_for_[CI]) {
expected_offset_ = CI;
}
if ( !has_sync_for_[expected_offset_]) {
// If message is a correct PI, error was probably in check bits
if (expected_offset_ == A && message == pi_ && pi_ != 0) {
has_sync_for_[A] = true;
printf(":ignoring error in check bits\n");
} else if (expected_offset_ == C && message == pi_ && pi_ != 0) {
has_sync_for_[CI] = true;
printf(":ignoring error in check bits\n");
// Detect & correct clock slips (Section C.1.2)
} else if (expected_offset_ == A && pi_ != 0 &&
((wideblock_ >> 12) & MASK_16BIT) == pi_) {
message = pi_;
wideblock_ >>= 1;
has_sync_for_[A] = true;
printf(":clock slip corrected\n");
} else if (expected_offset_ == A && pi_ != 0 &&
((wideblock_ >> 10) & MASK_16BIT) == pi_) {
message = pi_;
wideblock_ = (wideblock_ << 1) + bit_stream_.getNextBit();
has_sync_for_[A] = true;
left_to_read_ = 25;
printf(":clock slip corrected\n");
// Detect & correct burst errors (Section B.2.2)
} else {
uint16_t synd_reg = syndrome(block ^ offset_word_[expected_offset_]);
if (pi_ != 0 && expected_offset_ == A) {
printf(":expecting PI%04x, got %04x, xor %04x, syndrome %03x\n",
pi_, block>>10, pi_ ^ (block>>10), synd_reg);
}
if (error_lookup_.find(synd_reg) != error_lookup_.end()) {
message = (block >> 10) ^ error_lookup_[synd_reg];
has_sync_for_[expected_offset_] = true;
printf(":error corrected block %d using vector %04x for syndrome %03x\n",
expected_offset_, error_lookup_[synd_reg], synd_reg);
}
}
// Still no sync pulse
if ( !has_sync_for_[expected_offset_]) {
uncorrectable();
}
}
// Error-free block received
if (has_sync_for_[expected_offset_]) {
group_data_[block_for_offset_[expected_offset_]] = message;
has_block_[expected_offset_] = true;
if (expected_offset_ == A) {
pi_ = message;
}
// Complete group received
if (has_block_[A] && has_block_[B] && (has_block_[C] ||
has_block_[CI]) && has_block_[D]) {
has_whole_group_ = true;
}
}
expected_offset_ = (expected_offset_ == C ? D : (expected_offset_ + 1) % 5);
if (expected_offset_ == A) {
for (int o=A; o<=D; o++)
has_block_[o] = false;
}
}
}
return group_data_;
}
bool BlockStream::isEOF() const {
return bit_stream_.isEOF();
}
} // namespace redsea
<commit_msg>generate error lookup table from scratch<commit_after>#include "blockstream.h"
#define MASK_5BIT 0x000001F
#define MASK_10BIT 0x00003FF
#define MASK_16BIT 0x000FFFF
#define MASK_26BIT 0x3FFFFFF
#define MASK_28BIT 0xFFFFFFF
#define MAX_ERR_LEN 3
namespace redsea {
namespace {
uint16_t rol10(uint16_t word, int k) {
uint16_t result = word;
int l;
for (int i=0; i<k; i++) {
l = (result & 0x200);
result = (result << 1) & 0x3FF;
result += (l ? 1 : 0);
}
return result;
}
uint16_t calcSyndrome(int vec) {
uint16_t synd_reg = 0x000;
int bit,l;
for (int k=25; k>=0; k--) {
bit = (vec & (1 << k));
l = (synd_reg & 0x200); // Store lefmost bit of register
synd_reg = (synd_reg << 1) & 0x3FF; // Rotate register
synd_reg ^= (bit ? 0x31B : 0x00); // Premultiply input by x^325 mod g(x)
synd_reg ^= (l ? 0x1B9 : 0x00); // Division mod 2 by g(x)
}
return synd_reg;
}
uint16_t calcCheckBits(int dataWord) {
uint16_t generator = 0b0110111001;
uint16_t result = 0;
for (int k=0; k<16; k++) {
if ((dataWord >> k) & 1) {
result ^= rol10(generator, k);
}
}
return result;
}
}
BlockStream::BlockStream() : has_sync_for_(5), group_data_(4), has_block_(5),
bitcount_(0), left_to_read_(0), bit_stream_(), wideblock_(0), block_has_errors_(50)
{
offset_word_ = {0x0FC, 0x198, 0x168, 0x350, 0x1B4};
block_for_offset_ = {0, 1, 2, 2, 3};
for (int e=1; e < (1<<MAX_ERR_LEN); e++) {
for (int shift=0; shift < 16; shift++) {
int errvec = (e << shift) & MASK_16BIT;
uint16_t m = calcCheckBits(0b1);
uint16_t sy = calcSyndrome(((1<<10) + m) ^ errvec);
error_lookup_[sy] = errvec;
}
}
}
void BlockStream::uncorrectable() {
printf(":offset %d: not received\n",expected_offset_);
int data_length = 0;
// TODO: return partial group
/*if (has_block_[A]) {
data_length = 1;
if (has_block_[B]) {
data_length = 2;
if (has_block_[C] || has_block_[CI]) {
data_length = 3;
}
}
}*/
block_has_errors_[block_counter_ % block_has_errors_.size()] = true;
int erroneous_blocks = 0;
for (bool e : block_has_errors_) {
if (e)
erroneous_blocks ++;
}
// Sync is lost when >45 out of last 50 blocks are erroneous (Section C.1.2)
if (is_in_sync_ && erroneous_blocks > 45) {
is_in_sync_ = false;
for (int i=0; i<(int)block_has_errors_.size(); i++)
block_has_errors_[i] = false;
pi_ = 0x0000;
printf(":too many errors, sync lost\n");
}
for (int o=A; o<=D; o++)
has_block_[o] = false;
}
std::vector<uint16_t> BlockStream::getNextGroup() {
has_whole_group_ = false;
while (!(has_whole_group_ || isEOF())) {
// Compensate for clock slip corrections
bitcount_ += 26 - left_to_read_;
// Read from radio
for (int i=0; i < (is_in_sync_ ? left_to_read_ : 1); i++, bitcount_++) {
wideblock_ = (wideblock_ << 1) + bit_stream_.getNextBit();
}
left_to_read_ = 26;
wideblock_ &= MASK_28BIT;
int block = (wideblock_ >> 1) & MASK_26BIT;
// Find the offsets for which the calcSyndrome is zero
bool has_sync_for_any = false;
for (int o=A; o<=D; o++) {
has_sync_for_[o] = (calcSyndrome(block ^ offset_word_[o]) == 0x000);
has_sync_for_any |= has_sync_for_[o];
}
// Acquire sync
if (!is_in_sync_) {
if (has_sync_for_any) {
for (int o=A; o<=D; o++) {
if (has_sync_for_[o]) {
int dist = bitcount_ - prevbitcount_;
if (dist % 26 == 0 && dist <= 156 &&
(block_for_offset_[prevsync_] + dist/26) % 4 == block_for_offset_[o]) {
is_in_sync_ = true;
expected_offset_ = o;
printf(":sync!\n");
} else {
prevbitcount_ = bitcount_;
prevsync_ = o;
}
}
}
}
}
// Synchronous decoding
if (is_in_sync_) {
block_counter_ ++;
uint16_t message = block >> 10;
if (expected_offset_ == C && !has_sync_for_[C] && has_sync_for_[CI]) {
expected_offset_ = CI;
}
if ( !has_sync_for_[expected_offset_]) {
// If message is a correct PI, error was probably in check bits
if (expected_offset_ == A && message == pi_ && pi_ != 0) {
has_sync_for_[A] = true;
printf(":offset 0: ignoring error in check bits\n");
} else if (expected_offset_ == C && message == pi_ && pi_ != 0) {
has_sync_for_[CI] = true;
printf(":offset 0: ignoring error in check bits\n");
// Detect & correct clock slips (Section C.1.2)
} else if (expected_offset_ == A && pi_ != 0 &&
((wideblock_ >> 12) & MASK_16BIT) == pi_) {
message = pi_;
wideblock_ >>= 1;
has_sync_for_[A] = true;
printf(":offset 0: clock slip corrected\n");
} else if (expected_offset_ == A && pi_ != 0 &&
((wideblock_ >> 10) & MASK_16BIT) == pi_) {
message = pi_;
wideblock_ = (wideblock_ << 1) + bit_stream_.getNextBit();
has_sync_for_[A] = true;
left_to_read_ = 25;
printf(":offset 0: clock slip corrected\n");
// Detect & correct burst errors (Section B.2.2)
} else {
uint16_t synd_reg = calcSyndrome(block ^ offset_word_[expected_offset_]);
if (pi_ != 0 && expected_offset_ == A) {
printf(":offset 0: expecting PI%04x, got %04x, xor %04x, syndrome %03x\n",
pi_, block>>10, pi_ ^ (block>>10), synd_reg);
}
if (error_lookup_.find(synd_reg) != error_lookup_.end()) {
message = (block >> 10) ^ error_lookup_[synd_reg];
has_sync_for_[expected_offset_] = true;
printf(":offset %d: error corrected using vector %04x for syndrome %03x\n",
expected_offset_, error_lookup_[synd_reg], synd_reg);
}
}
// Still no sync pulse
if ( !has_sync_for_[expected_offset_]) {
uncorrectable();
}
}
// Error-free block received
if (has_sync_for_[expected_offset_]) {
group_data_[block_for_offset_[expected_offset_]] = message;
has_block_[expected_offset_] = true;
if (expected_offset_ == A) {
pi_ = message;
}
// Complete group received
if (has_block_[A] && has_block_[B] && (has_block_[C] ||
has_block_[CI]) && has_block_[D]) {
has_whole_group_ = true;
}
}
expected_offset_ = (expected_offset_ == C ? D : (expected_offset_ + 1) % 5);
if (expected_offset_ == A) {
for (int o=A; o<=D; o++)
has_block_[o] = false;
}
}
}
return group_data_;
}
bool BlockStream::isEOF() const {
return bit_stream_.isEOF();
}
} // namespace redsea
<|endoftext|> |
<commit_before>#include "btree/slice.hpp"
#include "btree/node.hpp"
#include "buffer_cache/transactor.hpp"
#include "buffer_cache/buf_lock.hpp"
#include "concurrency/cond_var.hpp"
#include "btree/get.hpp"
#include "btree/rget.hpp"
#include "btree/set.hpp"
#include "btree/incr_decr.hpp"
#include "btree/append_prepend.hpp"
#include "btree/delete.hpp"
#include "btree/get_cas.hpp"
#include "replication/master.hpp"
#include <boost/scoped_ptr.hpp>
void btree_slice_t::create(translator_serializer_t *serializer,
mirrored_cache_static_config_t *static_config) {
cache_t::create(serializer, static_config);
/* Construct a cache so we can write the superblock */
/* The values we pass here are almost totally irrelevant. The cache-size parameter must
be big enough to hold the patch log so we don't trip an assert, though. */
mirrored_cache_config_t startup_dynamic_config;
int size = static_config->n_patch_log_blocks * serializer->get_block_size().ser_value() + MEGABYTE;
startup_dynamic_config.max_size = size * 2;
startup_dynamic_config.wait_for_flush = false;
startup_dynamic_config.flush_timer_ms = NEVER_FLUSH;
startup_dynamic_config.max_dirty_size = size;
startup_dynamic_config.flush_dirty_size = size;
startup_dynamic_config.flush_waiting_threshold = INT_MAX;
startup_dynamic_config.max_concurrent_flushes = 1;
/* Cache is in a scoped pointer because it may be too big to allocate on the coroutine stack */
boost::scoped_ptr<cache_t> cache(new cache_t(serializer, &startup_dynamic_config));
/* Initialize the root block */
transactor_t transactor(cache.get(), rwi_write);
buf_lock_t superblock(transactor, SUPERBLOCK_ID, rwi_write);
btree_superblock_t *sb = (btree_superblock_t*)(superblock->get_data_major_write());
sb->magic = btree_superblock_t::expected_magic;
sb->root_block = NULL_BLOCK_ID;
// Destructors handle cleanup and stuff
}
btree_slice_t::btree_slice_t(translator_serializer_t *serializer,
mirrored_cache_config_t *dynamic_config)
: cache_(serializer, dynamic_config) { }
btree_slice_t::~btree_slice_t() {
// Cache's destructor handles flushing and stuff
}
get_result_t btree_slice_t::get(const store_key_t &key) {
return btree_get(key, this);
}
rget_result_t btree_slice_t::rget(rget_bound_mode_t left_mode, const store_key_t &left_key, rget_bound_mode_t right_mode, const store_key_t &right_key) {
return btree_rget_slice(this, left_mode, left_key, right_mode, right_key);
}
struct btree_slice_change_visitor_t : public boost::static_visitor<mutation_result_t> {
mutation_result_t operator()(const get_cas_mutation_t &m) {
return btree_get_cas(m.key, parent, ct);
}
mutation_result_t operator()(const set_mutation_t &m) {
return btree_set(m.key, parent, m.data, m.flags, m.exptime, m.add_policy, m.replace_policy, m.old_cas, ct);
}
mutation_result_t operator()(const incr_decr_mutation_t &m) {
return btree_incr_decr(m.key, parent, (m.kind == incr_decr_INCR), m.amount, ct);
}
mutation_result_t operator()(const append_prepend_mutation_t &m) {
return btree_append_prepend(m.key, parent, m.data, (m.kind == append_prepend_APPEND), ct);
}
mutation_result_t operator()(const delete_mutation_t &m) {
return btree_delete(m.key, parent, ct.timestamp);
}
btree_slice_t *parent;
castime_t ct;
};
mutation_result_t btree_slice_t::change(const mutation_t &m, castime_t castime) {
btree_slice_change_visitor_t functor;
functor.parent = this;
functor.ct = castime;
return boost::apply_visitor(functor, m.mutation);
}
// Stats
perfmon_duration_sampler_t
pm_cmd_set("cmd_set", secs_to_ticks(1)),
pm_cmd_get_without_threads("cmd_get_without_threads", secs_to_ticks(1)),
pm_cmd_get("cmd_get", secs_to_ticks(1)),
pm_cmd_rget("cmd_rget", secs_to_ticks(1));
<commit_msg>Fix my previous commit: create was broken<commit_after>#include "btree/slice.hpp"
#include "btree/node.hpp"
#include "buffer_cache/transactor.hpp"
#include "buffer_cache/buf_lock.hpp"
#include "concurrency/cond_var.hpp"
#include "btree/get.hpp"
#include "btree/rget.hpp"
#include "btree/set.hpp"
#include "btree/incr_decr.hpp"
#include "btree/append_prepend.hpp"
#include "btree/delete.hpp"
#include "btree/get_cas.hpp"
#include "replication/master.hpp"
#include <boost/scoped_ptr.hpp>
void btree_slice_t::create(translator_serializer_t *serializer,
mirrored_cache_static_config_t *static_config) {
cache_t::create(serializer, static_config);
/* Construct a cache so we can write the superblock */
/* The values we pass here are almost totally irrelevant. The cache-size parameter must
be big enough to hold the patch log so we don't trip an assert, though. */
mirrored_cache_config_t startup_dynamic_config;
int size = static_config->n_patch_log_blocks * serializer->get_block_size().ser_value() + MEGABYTE;
startup_dynamic_config.max_size = size * 2;
startup_dynamic_config.wait_for_flush = false;
startup_dynamic_config.flush_timer_ms = NEVER_FLUSH;
startup_dynamic_config.max_dirty_size = size;
startup_dynamic_config.flush_dirty_size = size;
startup_dynamic_config.flush_waiting_threshold = INT_MAX;
startup_dynamic_config.max_concurrent_flushes = 1;
/* Cache is in a scoped pointer because it may be too big to allocate on the coroutine stack */
boost::scoped_ptr<cache_t> cache(new cache_t(serializer, &startup_dynamic_config));
/* Initialize the root block */
transactor_t transactor(cache.get(), rwi_write, 1);
buf_lock_t superblock(transactor, SUPERBLOCK_ID, rwi_write);
btree_superblock_t *sb = (btree_superblock_t*)(superblock->get_data_major_write());
sb->magic = btree_superblock_t::expected_magic;
sb->root_block = NULL_BLOCK_ID;
// Destructors handle cleanup and stuff
}
btree_slice_t::btree_slice_t(translator_serializer_t *serializer,
mirrored_cache_config_t *dynamic_config)
: cache_(serializer, dynamic_config) { }
btree_slice_t::~btree_slice_t() {
// Cache's destructor handles flushing and stuff
}
get_result_t btree_slice_t::get(const store_key_t &key) {
return btree_get(key, this);
}
rget_result_t btree_slice_t::rget(rget_bound_mode_t left_mode, const store_key_t &left_key, rget_bound_mode_t right_mode, const store_key_t &right_key) {
return btree_rget_slice(this, left_mode, left_key, right_mode, right_key);
}
struct btree_slice_change_visitor_t : public boost::static_visitor<mutation_result_t> {
mutation_result_t operator()(const get_cas_mutation_t &m) {
return btree_get_cas(m.key, parent, ct);
}
mutation_result_t operator()(const set_mutation_t &m) {
return btree_set(m.key, parent, m.data, m.flags, m.exptime, m.add_policy, m.replace_policy, m.old_cas, ct);
}
mutation_result_t operator()(const incr_decr_mutation_t &m) {
return btree_incr_decr(m.key, parent, (m.kind == incr_decr_INCR), m.amount, ct);
}
mutation_result_t operator()(const append_prepend_mutation_t &m) {
return btree_append_prepend(m.key, parent, m.data, (m.kind == append_prepend_APPEND), ct);
}
mutation_result_t operator()(const delete_mutation_t &m) {
return btree_delete(m.key, parent, ct.timestamp);
}
btree_slice_t *parent;
castime_t ct;
};
mutation_result_t btree_slice_t::change(const mutation_t &m, castime_t castime) {
btree_slice_change_visitor_t functor;
functor.parent = this;
functor.ct = castime;
return boost::apply_visitor(functor, m.mutation);
}
// Stats
perfmon_duration_sampler_t
pm_cmd_set("cmd_set", secs_to_ticks(1)),
pm_cmd_get_without_threads("cmd_get_without_threads", secs_to_ticks(1)),
pm_cmd_get("cmd_get", secs_to_ticks(1)),
pm_cmd_rget("cmd_rget", secs_to_ticks(1));
<|endoftext|> |
<commit_before>#include <gtest/gtest.h>
#include <iostream>
#include "Eigen/Core"
#include "Eigen/Dense"
#include "vio/eigen_utils.h"
TEST(Eigen, Inverse) {
Eigen::Matrix<double, 6, 6> information = Eigen::Matrix<double, 6, 6>::Zero();
information(5, 5) = 1.0e8;
information(0, 0) = 1.0e8;
information(1, 1) = 1.0e8;
information(2, 2) = 1.0e8;
Eigen::Matrix<double, 6, 6> cov = information.inverse();
for (int i = 0; i < 5; ++i) {
EXPECT_TRUE(std::isnan(cov(0, 0)));
}
EXPECT_NEAR(cov(5, 5), 1e-8, 1e-10);
}
TEST(Eigen, SuperDiagonal) {
Eigen::MatrixXd M = Eigen::MatrixXd::Random(3, 5);
ASSERT_LT((vio::superdiagonal(M) - vio::subdiagonal(M.transpose())).norm(),
1e-9);
M = Eigen::MatrixXd::Random(4, 4);
ASSERT_LT((vio::superdiagonal(M) - vio::subdiagonal(M.transpose())).norm(),
1e-9);
M = Eigen::MatrixXd::Random(5, 3);
ASSERT_LT((vio::superdiagonal(M) - vio::subdiagonal(M.transpose())).norm(),
1e-9);
}
TEST(eigen_utils, ReparameterizeJacobians) {
double distances[] = {3, 3e2, 3e4, 3e8}; // close to inifity
std::vector<Eigen::Vector3d, Eigen::aligned_allocator<Eigen::Vector3d>>
expected_abrhoi{{1, -0.378937, 0.488034},
{1, -0.378937, 0.00488034},
{1, -0.378937, 4.88034e-05},
{1, -0.378937, 4.88034e-09}};
std::vector<Eigen::Vector3d, Eigen::aligned_allocator<Eigen::Vector3d>>
expected_abrhoj{{0.225489, -0.287133, 0.507999},
{0.264809, -0.280117, 0.00356978},
{0.267946, -0.277415, 3.57259e-05},
{0.267949, -0.277401, 3.57266e-09}};
for (size_t jack = 0; jack < sizeof(distances) / sizeof(distances[0]);
++jack) {
double dist = distances[jack];
Eigen::Matrix3d Ri = Eigen::Matrix3d::Identity();
Eigen::Vector3d ptini;
ptini << dist * cos(15 * M_PI / 180) * cos(45 * M_PI / 180),
-dist * sin(15 * M_PI / 180),
dist * cos(15 * M_PI / 180) * sin(45 * M_PI / 180);
Eigen::Matrix3d Rj =
Eigen::AngleAxisd(30 * M_PI / 180, Eigen::Vector3d::UnitY())
.toRotationMatrix();
Eigen::Vector3d pi = Eigen::Vector3d::Zero();
Eigen::Vector3d pj = Eigen::Vector3d::Random();
Eigen::Vector3d ptinj = Rj.transpose() * (ptini - pj);
Eigen::Vector3d abrhoi = Eigen::Vector3d(ptini[0], ptini[1], 1) / ptini[2];
Eigen::Vector3d abrhoj;
Eigen::Matrix<double, 3, 9> jacobian;
vio::reparameterize_AIDP(Ri, Rj, abrhoi, pi, pj, abrhoj, &jacobian);
Eigen::Matrix<double, 3, 9> jacobianNumeric;
vio::reparameterizeNumericalJacobian(Ri, Rj, abrhoi, pi, pj, abrhoj,
jacobianNumeric);
EXPECT_TRUE(jacobian.isApprox(jacobianNumeric, 1e-7));
EXPECT_TRUE(expected_abrhoi[jack].isApprox(abrhoi, 1e-6));
EXPECT_LT((expected_abrhoj[jack] - abrhoj).lpNorm<Eigen::Infinity>(), 1e-5);
}
// infinity
Eigen::Matrix3d Ri = Eigen::Matrix3d::Identity();
Eigen::Vector3d ptiniRay;
ptiniRay << cos(15 * M_PI / 180) * cos(45 * M_PI / 180),
-sin(15 * M_PI / 180), cos(15 * M_PI / 180) * sin(45 * M_PI / 180);
Eigen::Matrix3d Rj =
Eigen::AngleAxisd(30 * M_PI / 180, Eigen::Vector3d::UnitY())
.toRotationMatrix();
Eigen::Vector3d pi = Eigen::Vector3d::Zero();
Eigen::Vector3d pj = Eigen::Vector3d::Random();
Eigen::Vector3d ptinjRay = Rj.transpose() * ptiniRay;
ptinjRay /= ptinjRay[2];
ptinjRay[2] = 0;
Eigen::Vector3d abrhoi =
Eigen::Vector3d(1, -tan(15 * M_PI / 180) / sin(45 * M_PI / 180), 0);
Eigen::Vector3d abrhoj;
Eigen::Matrix<double, 3, 9> jacobian;
vio::reparameterize_AIDP(Ri, Rj, abrhoi, pi, pj, abrhoj, &jacobian);
Eigen::Matrix<double, 3, 9> jacobianNumeric;
vio::reparameterizeNumericalJacobian(Ri, Rj, abrhoi, pi, pj, abrhoj,
jacobianNumeric);
EXPECT_TRUE(jacobian.rightCols<6>().isMuchSmallerThan(1, 1e-8));
EXPECT_TRUE(jacobian.isApprox(jacobianNumeric, 1e-8));
EXPECT_TRUE(abrhoj.isApprox(ptinjRay, 1e-8));
}
TEST(eigen_utils, ExtractBlocks) {
Eigen::MatrixXd m(5, 5);
m << 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20,
21, 22, 23, 24, 25;
std::vector<std::pair<size_t, size_t> > vRowStartInterval;
for (size_t jack = 0; jack < 5; ++jack)
vRowStartInterval.push_back(std::make_pair(jack, 1));
// test deleting none entry
Eigen::MatrixXd res = vio::extractBlocks(m, vRowStartInterval, vRowStartInterval);
EXPECT_LT((res - m).lpNorm<Eigen::Infinity>(), 1e-8);
// test deleting odd indexed rows/cols
vRowStartInterval.clear();
for (size_t jack = 0; jack < 5; jack += 2)
vRowStartInterval.push_back(std::make_pair(jack, 1));
res = vio::extractBlocks(m, vRowStartInterval, vRowStartInterval);
Eigen::MatrixXd expected(3, 3);
expected << 1, 3, 5, 11, 13, 15, 21, 23, 25;
EXPECT_LT((res - expected).lpNorm<Eigen::Infinity>(), 1e-8);
// test deleting even indexed rows/cols
vRowStartInterval.clear();
for (size_t jack = 1; jack < 5; jack += 2)
vRowStartInterval.push_back(std::make_pair(jack, 1));
res = vio::extractBlocks(m, vRowStartInterval, vRowStartInterval);
Eigen::MatrixXd expected2(2, 2);
expected2 << 7, 9, 17, 19;
EXPECT_LT((res - expected2).lpNorm<Eigen::Infinity>(), 1e-8);
// test with keeping more than 1 rows/cols each time
vRowStartInterval.clear();
vRowStartInterval.push_back(std::make_pair(0, 2));
vRowStartInterval.push_back(std::make_pair(3, 2));
res = vio::extractBlocks(m, vRowStartInterval, vRowStartInterval);
Eigen::MatrixXd expected3(4, 4);
expected3 << 1, 2, 4, 5, 6, 7, 9, 10, 16, 17, 19, 20, 21, 22, 24, 25;
EXPECT_LT((res - expected3).lpNorm<Eigen::Infinity>(), 1e-8);
// test with different rows and cols to keep
vRowStartInterval.clear();
vRowStartInterval.push_back(std::make_pair(0, 2));
vRowStartInterval.push_back(std::make_pair(3, 2));
std::vector<std::pair<size_t, size_t> > vColStartInterval;
vColStartInterval.push_back(std::make_pair(0, 2));
vColStartInterval.push_back(std::make_pair(3, 1));
res = vio::extractBlocks(m, vRowStartInterval, vColStartInterval);
Eigen::MatrixXd expected4(4, 3);
expected4 << 1, 2, 4, 6, 7, 9, 16, 17, 19, 21, 22, 24;
EXPECT_LT((res - expected4).lpNorm<Eigen::Infinity>(), 1e-8);
}
<commit_msg>test quaternion difference<commit_after>#include <gtest/gtest.h>
#include <iostream>
#include "Eigen/Core"
#include "Eigen/Dense"
#include "vio/eigen_utils.h"
TEST(Eigen, Inverse) {
Eigen::Matrix<double, 6, 6> information = Eigen::Matrix<double, 6, 6>::Zero();
information(5, 5) = 1.0e8;
information(0, 0) = 1.0e8;
information(1, 1) = 1.0e8;
information(2, 2) = 1.0e8;
Eigen::Matrix<double, 6, 6> cov = information.inverse();
for (int i = 0; i < 5; ++i) {
EXPECT_TRUE(std::isnan(cov(0, 0)));
}
EXPECT_NEAR(cov(5, 5), 1e-8, 1e-10);
}
TEST(Eigen, SuperDiagonal) {
Eigen::MatrixXd M = Eigen::MatrixXd::Random(3, 5);
ASSERT_LT((vio::superdiagonal(M) - vio::subdiagonal(M.transpose())).norm(),
1e-9);
M = Eigen::MatrixXd::Random(4, 4);
ASSERT_LT((vio::superdiagonal(M) - vio::subdiagonal(M.transpose())).norm(),
1e-9);
M = Eigen::MatrixXd::Random(5, 3);
ASSERT_LT((vio::superdiagonal(M) - vio::subdiagonal(M.transpose())).norm(),
1e-9);
}
TEST(eigen_utils, ReparameterizeJacobians) {
double distances[] = {3, 3e2, 3e4, 3e8}; // close to inifity
std::vector<Eigen::Vector3d, Eigen::aligned_allocator<Eigen::Vector3d>>
expected_abrhoi{{1, -0.378937, 0.488034},
{1, -0.378937, 0.00488034},
{1, -0.378937, 4.88034e-05},
{1, -0.378937, 4.88034e-09}};
std::vector<Eigen::Vector3d, Eigen::aligned_allocator<Eigen::Vector3d>>
expected_abrhoj{{0.225489, -0.287133, 0.507999},
{0.264809, -0.280117, 0.00356978},
{0.267946, -0.277415, 3.57259e-05},
{0.267949, -0.277401, 3.57266e-09}};
for (size_t jack = 0; jack < sizeof(distances) / sizeof(distances[0]);
++jack) {
double dist = distances[jack];
Eigen::Matrix3d Ri = Eigen::Matrix3d::Identity();
Eigen::Vector3d ptini;
ptini << dist * cos(15 * M_PI / 180) * cos(45 * M_PI / 180),
-dist * sin(15 * M_PI / 180),
dist * cos(15 * M_PI / 180) * sin(45 * M_PI / 180);
Eigen::Matrix3d Rj =
Eigen::AngleAxisd(30 * M_PI / 180, Eigen::Vector3d::UnitY())
.toRotationMatrix();
Eigen::Vector3d pi = Eigen::Vector3d::Zero();
Eigen::Vector3d pj = Eigen::Vector3d::Random();
Eigen::Vector3d ptinj = Rj.transpose() * (ptini - pj);
Eigen::Vector3d abrhoi = Eigen::Vector3d(ptini[0], ptini[1], 1) / ptini[2];
Eigen::Vector3d abrhoj;
Eigen::Matrix<double, 3, 9> jacobian;
vio::reparameterize_AIDP(Ri, Rj, abrhoi, pi, pj, abrhoj, &jacobian);
Eigen::Matrix<double, 3, 9> jacobianNumeric;
vio::reparameterizeNumericalJacobian(Ri, Rj, abrhoi, pi, pj, abrhoj,
jacobianNumeric);
EXPECT_TRUE(jacobian.isApprox(jacobianNumeric, 1e-7));
EXPECT_TRUE(expected_abrhoi[jack].isApprox(abrhoi, 1e-6));
EXPECT_LT((expected_abrhoj[jack] - abrhoj).lpNorm<Eigen::Infinity>(), 1e-5);
}
// infinity
Eigen::Matrix3d Ri = Eigen::Matrix3d::Identity();
Eigen::Vector3d ptiniRay;
ptiniRay << cos(15 * M_PI / 180) * cos(45 * M_PI / 180),
-sin(15 * M_PI / 180), cos(15 * M_PI / 180) * sin(45 * M_PI / 180);
Eigen::Matrix3d Rj =
Eigen::AngleAxisd(30 * M_PI / 180, Eigen::Vector3d::UnitY())
.toRotationMatrix();
Eigen::Vector3d pi = Eigen::Vector3d::Zero();
Eigen::Vector3d pj = Eigen::Vector3d::Random();
Eigen::Vector3d ptinjRay = Rj.transpose() * ptiniRay;
ptinjRay /= ptinjRay[2];
ptinjRay[2] = 0;
Eigen::Vector3d abrhoi =
Eigen::Vector3d(1, -tan(15 * M_PI / 180) / sin(45 * M_PI / 180), 0);
Eigen::Vector3d abrhoj;
Eigen::Matrix<double, 3, 9> jacobian;
vio::reparameterize_AIDP(Ri, Rj, abrhoi, pi, pj, abrhoj, &jacobian);
Eigen::Matrix<double, 3, 9> jacobianNumeric;
vio::reparameterizeNumericalJacobian(Ri, Rj, abrhoi, pi, pj, abrhoj,
jacobianNumeric);
EXPECT_TRUE(jacobian.rightCols<6>().isMuchSmallerThan(1, 1e-8));
EXPECT_TRUE(jacobian.isApprox(jacobianNumeric, 1e-8));
EXPECT_TRUE(abrhoj.isApprox(ptinjRay, 1e-8));
}
TEST(eigen_utils, ExtractBlocks) {
Eigen::MatrixXd m(5, 5);
m << 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20,
21, 22, 23, 24, 25;
std::vector<std::pair<size_t, size_t> > vRowStartInterval;
for (size_t jack = 0; jack < 5; ++jack)
vRowStartInterval.push_back(std::make_pair(jack, 1));
// test deleting none entry
Eigen::MatrixXd res = vio::extractBlocks(m, vRowStartInterval, vRowStartInterval);
EXPECT_LT((res - m).lpNorm<Eigen::Infinity>(), 1e-8);
// test deleting odd indexed rows/cols
vRowStartInterval.clear();
for (size_t jack = 0; jack < 5; jack += 2)
vRowStartInterval.push_back(std::make_pair(jack, 1));
res = vio::extractBlocks(m, vRowStartInterval, vRowStartInterval);
Eigen::MatrixXd expected(3, 3);
expected << 1, 3, 5, 11, 13, 15, 21, 23, 25;
EXPECT_LT((res - expected).lpNorm<Eigen::Infinity>(), 1e-8);
// test deleting even indexed rows/cols
vRowStartInterval.clear();
for (size_t jack = 1; jack < 5; jack += 2)
vRowStartInterval.push_back(std::make_pair(jack, 1));
res = vio::extractBlocks(m, vRowStartInterval, vRowStartInterval);
Eigen::MatrixXd expected2(2, 2);
expected2 << 7, 9, 17, 19;
EXPECT_LT((res - expected2).lpNorm<Eigen::Infinity>(), 1e-8);
// test with keeping more than 1 rows/cols each time
vRowStartInterval.clear();
vRowStartInterval.push_back(std::make_pair(0, 2));
vRowStartInterval.push_back(std::make_pair(3, 2));
res = vio::extractBlocks(m, vRowStartInterval, vRowStartInterval);
Eigen::MatrixXd expected3(4, 4);
expected3 << 1, 2, 4, 5, 6, 7, 9, 10, 16, 17, 19, 20, 21, 22, 24, 25;
EXPECT_LT((res - expected3).lpNorm<Eigen::Infinity>(), 1e-8);
// test with different rows and cols to keep
vRowStartInterval.clear();
vRowStartInterval.push_back(std::make_pair(0, 2));
vRowStartInterval.push_back(std::make_pair(3, 2));
std::vector<std::pair<size_t, size_t> > vColStartInterval;
vColStartInterval.push_back(std::make_pair(0, 2));
vColStartInterval.push_back(std::make_pair(3, 1));
res = vio::extractBlocks(m, vRowStartInterval, vColStartInterval);
Eigen::MatrixXd expected4(4, 3);
expected4 << 1, 2, 4, 6, 7, 9, 16, 17, 19, 21, 22, 24;
EXPECT_LT((res - expected4).lpNorm<Eigen::Infinity>(), 1e-8);
}
TEST(Eigen, QuaternionDiff) {
Eigen::Vector4d xyzw(0.0002580249512621188, 0.0005713455181395015,
0.7010130254309982, 0.7131481929890183);
Eigen::Quaterniond ref(xyzw[3], xyzw[0], xyzw[1], xyzw[2]);
Eigen::Quaterniond actual(xyzw.data());
EXPECT_LT(Eigen::AngleAxisd(ref.inverse() * actual).angle(), 1e-8);
}
<|endoftext|> |
<commit_before>//
// Created by permal on 9/7/17.
//
#include <smooth/application/rgb_led/RGBLed.h>
#include <smooth/core/util/ByteSet.h>
#include <cstring>
#include <driver/periph_ctrl.h>
#include "esp_log.h"
namespace smooth
{
namespace application
{
namespace rgb_led
{
RGBLed::RGBLed(rmt_channel_t channel, gpio_num_t io_pin, uint16_t led_count, const RGBLedTiming& timing)
: led_data(), channel(channel), led_count(led_count)
{
periph_module_enable(PERIPH_RMT_MODULE);
ESP_ERROR_CHECK(rmt_driver_install(channel, 0, 0));
rmt_set_pin(channel, RMT_MODE_TX, io_pin);
rmt_set_mem_block_num(channel, 1);
rmt_set_clk_div(channel, clock_divider);
rmt_set_tx_loop_mode(channel, false);
rmt_set_tx_carrier(channel, false, 0, 0, RMT_CARRIER_LEVEL_LOW);
rmt_set_idle_level(channel, false, RMT_IDLE_LEVEL_LOW);
rmt_set_source_clk(channel, RMT_BASECLK_APB);
// Prepare high and low data
auto t = timing.get_low();
low.level0 = t.level0;
low.duration0 = get_rmt_duration(t.duration0);
low.level1 = t.level1;
low.duration1 = get_rmt_duration(t.duration1);
t = timing.get_high();
hi.level0 = t.level0;
hi.duration0 = get_rmt_duration(t.duration0);
hi.level1 = t.level1;
hi.duration1 = get_rmt_duration(t.duration1);
t = timing.get_reset();
reset.level0 = t.level0;
reset.duration0 = get_rmt_duration(t.duration0);
reset.level1 = t.level1;
reset.duration1 = get_rmt_duration(t.duration1);
// Reserve space for bits_per_pixel for each LED plus one for reset pulse.
auto size = led_count * bits_per_pixel + 1;
led_data.reserve(size);
for (auto i = 0; i < size; ++i)
{
led_data.push_back(reset);
}
}
RGBLed::~RGBLed()
{
rmt_driver_uninstall(channel);
}
uint16_t RGBLed::get_rmt_duration(uint16_t duration_in_ns)
{
return static_cast<uint16_t>( duration_in_ns / (pulse_width * clock_divider));
}
void RGBLed::set_pixel(uint16_t ix, uint8_t red, uint8_t green, uint8_t blue)
{
if (ix < led_count)
{
auto pixel = led_data.begin() + ix * bits_per_pixel;
add_color(pixel, green);
add_color(pixel, red);
add_color(pixel, blue);
}
}
void RGBLed::add_color(std::vector<rmt_item32_t>::iterator& pixel, uint8_t color)
{
core::util::ByteSet b(color);
int bit = 7;
while (bit >= 0 && pixel != led_data.end())
{
*pixel = b.test(bit) ? hi : low;
bit--;
pixel++;
}
}
void RGBLed::apply()
{
// Be sure that the last item we send is the reset-pulse.
led_data[led_data.size() - 1] = reset;
rmt_write_items(channel, led_data.data(), led_data.size(), true);
}
}
}
}<commit_msg>Removed include.<commit_after>//
// Created by permal on 9/7/17.
//
#include <smooth/application/rgb_led/RGBLed.h>
#include <smooth/core/util/ByteSet.h>
#include <cstring>
#include <driver/periph_ctrl.h>
namespace smooth
{
namespace application
{
namespace rgb_led
{
RGBLed::RGBLed(rmt_channel_t channel, gpio_num_t io_pin, uint16_t led_count, const RGBLedTiming& timing)
: led_data(), channel(channel), led_count(led_count)
{
periph_module_enable(PERIPH_RMT_MODULE);
ESP_ERROR_CHECK(rmt_driver_install(channel, 0, 0));
rmt_set_pin(channel, RMT_MODE_TX, io_pin);
rmt_set_mem_block_num(channel, 1);
rmt_set_clk_div(channel, clock_divider);
rmt_set_tx_loop_mode(channel, false);
rmt_set_tx_carrier(channel, false, 0, 0, RMT_CARRIER_LEVEL_LOW);
rmt_set_idle_level(channel, false, RMT_IDLE_LEVEL_LOW);
rmt_set_source_clk(channel, RMT_BASECLK_APB);
// Prepare high and low data
auto t = timing.get_low();
low.level0 = t.level0;
low.duration0 = get_rmt_duration(t.duration0);
low.level1 = t.level1;
low.duration1 = get_rmt_duration(t.duration1);
t = timing.get_high();
hi.level0 = t.level0;
hi.duration0 = get_rmt_duration(t.duration0);
hi.level1 = t.level1;
hi.duration1 = get_rmt_duration(t.duration1);
t = timing.get_reset();
reset.level0 = t.level0;
reset.duration0 = get_rmt_duration(t.duration0);
reset.level1 = t.level1;
reset.duration1 = get_rmt_duration(t.duration1);
// Reserve space for bits_per_pixel for each LED plus one for reset pulse.
auto size = led_count * bits_per_pixel + 1;
led_data.reserve(size);
for (auto i = 0; i < size; ++i)
{
led_data.push_back(reset);
}
}
RGBLed::~RGBLed()
{
rmt_driver_uninstall(channel);
}
uint16_t RGBLed::get_rmt_duration(uint16_t duration_in_ns)
{
return static_cast<uint16_t>( duration_in_ns / (pulse_width * clock_divider));
}
void RGBLed::set_pixel(uint16_t ix, uint8_t red, uint8_t green, uint8_t blue)
{
if (ix < led_count)
{
auto pixel = led_data.begin() + ix * bits_per_pixel;
add_color(pixel, green);
add_color(pixel, red);
add_color(pixel, blue);
}
}
void RGBLed::add_color(std::vector<rmt_item32_t>::iterator& pixel, uint8_t color)
{
core::util::ByteSet b(color);
int bit = 7;
while (bit >= 0 && pixel != led_data.end())
{
*pixel = b.test(bit) ? hi : low;
bit--;
pixel++;
}
}
void RGBLed::apply()
{
// Be sure that the last item we send is the reset-pulse.
led_data[led_data.size() - 1] = reset;
rmt_write_items(channel, led_data.data(), led_data.size(), true);
}
}
}
}<|endoftext|> |
<commit_before>#include "stdafx.h"
typedef std::vector<DWORD> ThreadsVec;
ThreadsVec g_Threads;
unsigned g_EventsCount = 0;
unsigned g_ThreadEventsCount = 0;
unsigned g_CSwitchEventsCount = 0;
unsigned g_ThisProcessThreadEvents = 0;
static const wchar_t* THREAD_V2_CLSID(L"{3d6fa8d1-fe05-11d0-9dda-00c04fd7ba7c}");
static const unsigned CSWITCH_EVENT_TYPE = 36;
template<typename T>
struct default_release
{
void operator()(T* ptr) const {
ptr->Release();
}
};
struct free_variant
{
void operator()(VARIANT* ptr) const {
VariantClear(ptr);
delete ptr;
}
};
std::unique_ptr<IWbemClassObject, default_release<IWbemClassObject>> g_EventCategoryClass;
bool ListThreads(DWORD procId, ThreadsVec& outThreads) {
HANDLE hThreadSnap = INVALID_HANDLE_VALUE;
THREADENTRY32 te32 = {0};
// Take a snapshot of all running threads
hThreadSnap = ::CreateToolhelp32Snapshot(TH32CS_SNAPTHREAD, 0);
if(hThreadSnap == INVALID_HANDLE_VALUE) {
return false;
}
te32.dwSize = sizeof(THREADENTRY32);
if(!Thread32First(hThreadSnap, &te32))
{
std::cerr << "Unable to retrieve threads" << std::endl;
::CloseHandle(hThreadSnap);
return false;
}
// Now walk the thread list of the system,
// and display information about each thread
// associated with the specified process
do
{
if(te32.th32OwnerProcessID == procId) {
outThreads.push_back(te32.th32ThreadID);
}
} while(Thread32Next(hThreadSnap, &te32 ));
::CloseHandle(hThreadSnap);
return true;;
}
struct CSWitchEventData
{
CSWitchEventData(char* ptr) {
FillData(ptr);
}
unsigned NewThreadId;
unsigned OldThreadId;
char NewThreadPriority;
char OldThreadPriority;
unsigned char PreviousCState;
char SpareByte;
char OldThreadWaitReason;
char OldThreadWaitMode;
char OldThreadState;
char OldThreadWaitIdealProcessor;
unsigned NewThreadWaitTime;
unsigned Reserved;
void FillData(char* ptr) {
NewThreadId = *(unsigned*)ptr; ptr += sizeof(unsigned);
OldThreadId = *(unsigned*)ptr; ptr += sizeof(unsigned);
NewThreadPriority = *(char*)ptr; ptr += sizeof(char);
OldThreadPriority = *(char*)ptr; ptr += sizeof(char);
PreviousCState = *(unsigned char*)ptr; ptr += sizeof(unsigned char);
SpareByte = *(char*)ptr; ptr += sizeof(char);
OldThreadWaitReason = *(char*)ptr; ptr += sizeof(char);
OldThreadWaitMode = *(char*)ptr; ptr += sizeof(char);
OldThreadState = *(char*)ptr; ptr += sizeof(char);
OldThreadWaitIdealProcessor = *(char*)ptr; ptr += sizeof(char);
NewThreadWaitTime = *(unsigned*)ptr; ptr += sizeof(unsigned);
Reserved = *(unsigned*)ptr; ptr += sizeof(unsigned);
}
};
void WINAPI ProcessEvent(PEVENT_TRACE event) {
++g_EventsCount;
if(event->MofLength == 0)
return;
wchar_t ClassGUID[50] = {0};
StringFromGUID2(event->Header.Guid, ClassGUID, sizeof(ClassGUID));
// we are interested in Thread_V2 class events
if(lstrcmpiW(ClassGUID, THREAD_V2_CLSID) == 0 && event->Header.Class.Version)
{
++g_ThreadEventsCount;
if(event->Header.Class.Type == CSWITCH_EVENT_TYPE)
{
++g_CSwitchEventsCount;
CSWitchEventData evData((char*)event->MofData);
auto oldThread = std::find(g_Threads.cbegin(), g_Threads.cend(), evData.OldThreadId);
auto newThread = std::find(g_Threads.cbegin(), g_Threads.cend(), evData.NewThreadId);
if(oldThread != g_Threads.cend() || newThread != g_Threads.cend()) {
++g_ThisProcessThreadEvents;
}
}
}
}
void StartTraceConsume(TRACEHANDLE& handle) {
::ProcessTrace(&handle, 1, 0, 0);
}
bool GetEventClass()
{
HRESULT hr = S_OK;
hr = CoInitialize(0);
IWbemLocator* locatorTmp = nullptr;
hr = CoCreateInstance(__uuidof(WbemLocator),
0,
CLSCTX_INPROC_SERVER,
__uuidof(IWbemLocator),
(LPVOID*)&locatorTmp);
std::unique_ptr<IWbemLocator, default_release<IWbemLocator>> pLocator(locatorTmp);
if (FAILED(hr)) {
std::cerr << "CoCreateInstance failed with " << hr <<std::endl;
return false;
}
IWbemServices* servicesTmp = nullptr;
hr = pLocator->ConnectServer(L"root\\wmi",
NULL, NULL, NULL,
0L, NULL, NULL,
&servicesTmp);
std::unique_ptr<IWbemServices, default_release<IWbemServices>> service(servicesTmp);
if (FAILED(hr)) {
std::cerr << "ConnectServer failed with " << hr <<std::endl;
return false;
}
hr = CoSetProxyBlanket(service.get(),
RPC_C_AUTHN_WINNT, RPC_C_AUTHZ_NONE,
NULL,
RPC_C_AUTHN_LEVEL_PKT, RPC_C_IMP_LEVEL_IMPERSONATE,
NULL, EOAC_NONE);
if (FAILED(hr)) {
std::cerr << "CoSetProxyBlanket failed with " << hr << std::endl;
return false;
}
// Get the class category
IEnumWbemClassObject* classesTmp = nullptr;
hr = service->CreateClassEnum(_bstr_t(L"EventTrace"),
WBEM_FLAG_DEEP | WBEM_FLAG_FORWARD_ONLY | WBEM_FLAG_USE_AMENDED_QUALIFIERS,
NULL, &classesTmp);
std::unique_ptr<IEnumWbemClassObject, default_release<IEnumWbemClassObject>> classes(classesTmp);
if(FAILED(hr)) {
std::cerr << "CreateClassEnum failed with " << hr << std::endl;
return false;
}
std::unique_ptr<IWbemClassObject, default_release<IWbemClassObject>> categoryClassObject;
while (S_OK == hr) {
ULONG cnt = 0;
IWbemClassObject* clsTmp = nullptr;
auto hrqual = classes->Next(WBEM_INFINITE, 1, &clsTmp, &cnt);
std::unique_ptr<IWbemClassObject, default_release<IWbemClassObject>> cls(clsTmp);
if(FAILED(hrqual)) {
std::cerr << "Next category failed with " << hrqual << std::endl;
return false;
}
IWbemQualifierSet* qualTmp = nullptr;
cls->GetQualifierSet(&qualTmp);
std::unique_ptr<IWbemQualifierSet, default_release<IWbemQualifierSet>> qualifiers(qualTmp);
if(qualifiers) {
std::unique_ptr<VARIANT, free_variant> varGuid(new VARIANT);
hrqual = qualifiers->Get(L"Guid", 0, varGuid.get(), nullptr);
if(FAILED(hrqual)) {
continue;
}
if(lstrcmpiW(varGuid->bstrVal, THREAD_V2_CLSID) == 0) {
categoryClassObject.reset(cls.release());
break;
}
}
}
std::unique_ptr<VARIANT, free_variant> varClassName(new VARIANT);
// Get the class we are interested in from the category
hr = categoryClassObject->Get(L"__RELPATH", 0, varClassName.get(), nullptr, nullptr);
if(FAILED(hr)) {
std::cerr << "Unable to get relpath " << hr << std::endl;
return false;
}
hr = service->CreateClassEnum(varClassName->bstrVal,
WBEM_FLAG_SHALLOW | WBEM_FLAG_FORWARD_ONLY | WBEM_FLAG_USE_AMENDED_QUALIFIERS,
NULL, &classesTmp);
classes.reset(classesTmp);
if(FAILED(hr)) {
std::cerr << "Unable to get classes for category " << hr << std::endl;
return false;
}
bool found = false;
std::unique_ptr<IWbemClassObject, default_release<IWbemClassObject>> cls;
while(S_OK == hr) {
ULONG cnt = 0;
IWbemClassObject* clsTmp = nullptr;
auto hrqual = classes->Next(WBEM_INFINITE, 1, &clsTmp, &cnt);
cls.reset(clsTmp);
if(FAILED(hrqual)) {
std::cerr << "Next class failed with " << hrqual << std::endl;
return false;
}
IWbemQualifierSet* qualTmp = nullptr;
cls->GetQualifierSet(&qualTmp);
std::unique_ptr<IWbemQualifierSet, default_release<IWbemQualifierSet>> qualifiers(qualTmp);
std::unique_ptr<VARIANT, free_variant> varEventType(new VARIANT);
qualifiers->Get(L"EventType", 0, varEventType.get(), nullptr);
if (varEventType->vt & VT_ARRAY) {
HRESULT hrSafe = S_OK;
int ClassEventType;
SAFEARRAY* pEventTypes = varEventType->parray;
for (LONG i=0; (ULONG)i < pEventTypes->rgsabound->cElements; i++) {
hrSafe = SafeArrayGetElement(pEventTypes, &i, &ClassEventType);
if (ClassEventType == CSWITCH_EVENT_TYPE) {
found = true;
break; //for loop
}
}
}
else {
if (varEventType->intVal == CSWITCH_EVENT_TYPE) {
found = true;
}
}
if (found) {
break; //while loop
}
}
if(found) {
g_EventCategoryClass = std::move(cls);
}
return found;
}
int main(int argc, char* argv[])
{
if(!ListThreads(GetCurrentProcessId(), g_Threads)) {
return 1;
}
std::cout << "Threads belonging to process: " << std::endl;
std::for_each(g_Threads.cbegin(), g_Threads.cend(), [](DWORD threadId) {
std::cout << threadId << std::endl;
});
// get the event class we are interested in
if(!GetEventClass()) {
return 1;
}
// Open the trace
EVENT_TRACE_LOGFILE logDesc = {0};
logDesc.LoggerName = KERNEL_LOGGER_NAME;
logDesc.ProcessTraceMode = PROCESS_TRACE_MODE_REAL_TIME;
logDesc.EventCallback = &ProcessEvent;
TRACEHANDLE consumeHandle = ::OpenTrace(&logDesc);
if(consumeHandle == INVALID_PROCESSTRACE_HANDLE) {
std::cerr << "Unable to open trace!" << std::endl;
return 1;
}
auto propsSize = sizeof(EVENT_TRACE_PROPERTIES) + sizeof(KERNEL_LOGGER_NAME);
std::unique_ptr<unsigned char[]> evtPropertiesMem(new unsigned char[propsSize]);
::memset(evtPropertiesMem.get(), 0, propsSize);
PEVENT_TRACE_PROPERTIES properties = reinterpret_cast<PEVENT_TRACE_PROPERTIES>(evtPropertiesMem.get());
properties->Wnode.BufferSize = propsSize;
properties->Wnode.Guid = SystemTraceControlGuid;
properties->Wnode.ClientContext = 1/*QPC*/;
properties->Wnode.Flags = WNODE_FLAG_TRACED_GUID;
properties->EnableFlags = EVENT_TRACE_FLAG_CSWITCH;
properties->LogFileMode = EVENT_TRACE_REAL_TIME_MODE;
properties->LogFileNameOffset = 0;
properties->LoggerNameOffset = sizeof(EVENT_TRACE_PROPERTIES);
TRACEHANDLE session;
auto error = ::StartTrace(&session, KERNEL_LOGGER_NAME, properties);
if(error != ERROR_SUCCESS) {
std::cerr << "Unable to start trace; error: " << error << std::endl;
}
std::thread consumerThread(std::bind(&StartTraceConsume, consumeHandle));
::Sleep(1);
// Stop the session
properties->LoggerNameOffset = 0;
error = ::ControlTrace(session, KERNEL_LOGGER_NAME, properties, EVENT_TRACE_CONTROL_STOP);
if(error != ERROR_SUCCESS) {
std::cerr << "Unable to stop trace; error: " << error << std::endl;
}
std::cout << "Free buffers: " << properties->FreeBuffers << std::endl;
std::cout << "Events lost: " << properties->EventsLost << std::endl;
std::cout << "Buffers written: " << properties->BuffersWritten << std::endl;
std::cout << "Log buffers lost: " << properties->LogBuffersLost << std::endl;
std::cout << "RealTime buffers lost: " << properties->RealTimeBuffersLost << std::endl;
error = ::CloseTrace(consumeHandle);
if(error != ERROR_SUCCESS) {
std::cerr << "Unable to close consume trace; error: " << error << std::endl;
}
consumerThread.join();
std::cout << "Events received: " << g_EventsCount << std::endl;
std::cout << "Thread events received: " << g_ThreadEventsCount << std::endl;
std::cout << "CSwitch events received: " << g_CSwitchEventsCount << std::endl;
std::cout << "Thread events for this process received: " << g_ThisProcessThreadEvents << std::endl;
return 0;
}
<commit_msg>* Added some additional counters<commit_after>#include "stdafx.h"
typedef std::vector<DWORD> ThreadsVec;
ThreadsVec g_Threads;
unsigned g_EventsCount = 0;
unsigned g_ThreadEventsCount = 0;
unsigned g_CSwitchEventsCount = 0;
unsigned g_ThisProcessThreadEvents = 0;
unsigned g_ThisProcessThreadsScheduled = 0;
unsigned g_ThisProcessThreadsUnscheduled = 0;
unsigned g_ThisProcessThreadsWaits = 0;
static const wchar_t* THREAD_V2_CLSID(L"{3d6fa8d1-fe05-11d0-9dda-00c04fd7ba7c}");
static const unsigned CSWITCH_EVENT_TYPE = 36;
template<typename T>
struct default_release
{
void operator()(T* ptr) const {
ptr->Release();
}
};
struct free_variant
{
void operator()(VARIANT* ptr) const {
VariantClear(ptr);
delete ptr;
}
};
std::unique_ptr<IWbemClassObject, default_release<IWbemClassObject>> g_EventCategoryClass;
bool ListThreads(DWORD procId, ThreadsVec& outThreads) {
HANDLE hThreadSnap = INVALID_HANDLE_VALUE;
THREADENTRY32 te32 = {0};
// Take a snapshot of all running threads
hThreadSnap = ::CreateToolhelp32Snapshot(TH32CS_SNAPTHREAD, 0);
if(hThreadSnap == INVALID_HANDLE_VALUE) {
return false;
}
te32.dwSize = sizeof(THREADENTRY32);
if(!Thread32First(hThreadSnap, &te32))
{
std::cerr << "Unable to retrieve threads" << std::endl;
::CloseHandle(hThreadSnap);
return false;
}
// Now walk the thread list of the system,
// and display information about each thread
// associated with the specified process
do
{
if(te32.th32OwnerProcessID == procId) {
outThreads.push_back(te32.th32ThreadID);
}
} while(Thread32Next(hThreadSnap, &te32 ));
::CloseHandle(hThreadSnap);
return true;;
}
struct CSWitchEventData
{
CSWitchEventData(char* ptr) {
FillData(ptr);
}
unsigned NewThreadId;
unsigned OldThreadId;
char NewThreadPriority;
char OldThreadPriority;
unsigned char PreviousCState;
char SpareByte;
char OldThreadWaitReason;
char OldThreadWaitMode;
char OldThreadState;
char OldThreadWaitIdealProcessor;
unsigned NewThreadWaitTime;
unsigned Reserved;
void FillData(char* ptr) {
NewThreadId = *(unsigned*)ptr; ptr += sizeof(unsigned);
OldThreadId = *(unsigned*)ptr; ptr += sizeof(unsigned);
NewThreadPriority = *(char*)ptr; ptr += sizeof(char);
OldThreadPriority = *(char*)ptr; ptr += sizeof(char);
PreviousCState = *(unsigned char*)ptr; ptr += sizeof(unsigned char);
SpareByte = *(char*)ptr; ptr += sizeof(char);
OldThreadWaitReason = *(char*)ptr; ptr += sizeof(char);
OldThreadWaitMode = *(char*)ptr; ptr += sizeof(char);
OldThreadState = *(char*)ptr; ptr += sizeof(char);
OldThreadWaitIdealProcessor = *(char*)ptr; ptr += sizeof(char);
NewThreadWaitTime = *(unsigned*)ptr; ptr += sizeof(unsigned);
Reserved = *(unsigned*)ptr; ptr += sizeof(unsigned);
}
};
void WINAPI ProcessEvent(PEVENT_TRACE event) {
++g_EventsCount;
if(event->MofLength == 0)
return;
wchar_t ClassGUID[50] = {0};
StringFromGUID2(event->Header.Guid, ClassGUID, sizeof(ClassGUID));
// we are interested in Thread_V2 class events
if(lstrcmpiW(ClassGUID, THREAD_V2_CLSID) == 0 && event->Header.Class.Version)
{
++g_ThreadEventsCount;
if(event->Header.Class.Type == CSWITCH_EVENT_TYPE)
{
++g_CSwitchEventsCount;
CSWitchEventData evData((char*)event->MofData);
auto oldThread = std::find(g_Threads.cbegin(), g_Threads.cend(), evData.OldThreadId);
auto newThread = std::find(g_Threads.cbegin(), g_Threads.cend(), evData.NewThreadId);
if(oldThread != g_Threads.cend() || newThread != g_Threads.cend()) {
++g_ThisProcessThreadEvents;
if(oldThread != g_Threads.cend()) {
++g_ThisProcessThreadsUnscheduled;
if(evData.OldThreadState == 5/*waiting*/) {
++g_ThisProcessThreadsWaits;
}
}
else {
++g_ThisProcessThreadsScheduled;
}
}
}
}
}
void StartTraceConsume(TRACEHANDLE& handle) {
::ProcessTrace(&handle, 1, 0, 0);
}
bool GetEventClass()
{
HRESULT hr = S_OK;
hr = CoInitialize(0);
IWbemLocator* locatorTmp = nullptr;
hr = CoCreateInstance(__uuidof(WbemLocator),
0,
CLSCTX_INPROC_SERVER,
__uuidof(IWbemLocator),
(LPVOID*)&locatorTmp);
std::unique_ptr<IWbemLocator, default_release<IWbemLocator>> pLocator(locatorTmp);
if (FAILED(hr)) {
std::cerr << "CoCreateInstance failed with " << hr <<std::endl;
return false;
}
IWbemServices* servicesTmp = nullptr;
hr = pLocator->ConnectServer(L"root\\wmi",
NULL, NULL, NULL,
0L, NULL, NULL,
&servicesTmp);
std::unique_ptr<IWbemServices, default_release<IWbemServices>> service(servicesTmp);
if (FAILED(hr)) {
std::cerr << "ConnectServer failed with " << hr <<std::endl;
return false;
}
hr = CoSetProxyBlanket(service.get(),
RPC_C_AUTHN_WINNT, RPC_C_AUTHZ_NONE,
NULL,
RPC_C_AUTHN_LEVEL_PKT, RPC_C_IMP_LEVEL_IMPERSONATE,
NULL, EOAC_NONE);
if (FAILED(hr)) {
std::cerr << "CoSetProxyBlanket failed with " << hr << std::endl;
return false;
}
// Get the class category
IEnumWbemClassObject* classesTmp = nullptr;
hr = service->CreateClassEnum(_bstr_t(L"EventTrace"),
WBEM_FLAG_DEEP | WBEM_FLAG_FORWARD_ONLY | WBEM_FLAG_USE_AMENDED_QUALIFIERS,
NULL, &classesTmp);
std::unique_ptr<IEnumWbemClassObject, default_release<IEnumWbemClassObject>> classes(classesTmp);
if(FAILED(hr)) {
std::cerr << "CreateClassEnum failed with " << hr << std::endl;
return false;
}
std::unique_ptr<IWbemClassObject, default_release<IWbemClassObject>> categoryClassObject;
while (S_OK == hr) {
ULONG cnt = 0;
IWbemClassObject* clsTmp = nullptr;
auto hrqual = classes->Next(WBEM_INFINITE, 1, &clsTmp, &cnt);
std::unique_ptr<IWbemClassObject, default_release<IWbemClassObject>> cls(clsTmp);
if(FAILED(hrqual)) {
std::cerr << "Next category failed with " << hrqual << std::endl;
return false;
}
IWbemQualifierSet* qualTmp = nullptr;
cls->GetQualifierSet(&qualTmp);
std::unique_ptr<IWbemQualifierSet, default_release<IWbemQualifierSet>> qualifiers(qualTmp);
if(qualifiers) {
std::unique_ptr<VARIANT, free_variant> varGuid(new VARIANT);
hrqual = qualifiers->Get(L"Guid", 0, varGuid.get(), nullptr);
if(FAILED(hrqual)) {
continue;
}
if(lstrcmpiW(varGuid->bstrVal, THREAD_V2_CLSID) == 0) {
categoryClassObject.reset(cls.release());
break;
}
}
}
std::unique_ptr<VARIANT, free_variant> varClassName(new VARIANT);
// Get the class we are interested in from the category
hr = categoryClassObject->Get(L"__RELPATH", 0, varClassName.get(), nullptr, nullptr);
if(FAILED(hr)) {
std::cerr << "Unable to get relpath " << hr << std::endl;
return false;
}
hr = service->CreateClassEnum(varClassName->bstrVal,
WBEM_FLAG_SHALLOW | WBEM_FLAG_FORWARD_ONLY | WBEM_FLAG_USE_AMENDED_QUALIFIERS,
NULL, &classesTmp);
classes.reset(classesTmp);
if(FAILED(hr)) {
std::cerr << "Unable to get classes for category " << hr << std::endl;
return false;
}
bool found = false;
std::unique_ptr<IWbemClassObject, default_release<IWbemClassObject>> cls;
while(S_OK == hr) {
ULONG cnt = 0;
IWbemClassObject* clsTmp = nullptr;
auto hrqual = classes->Next(WBEM_INFINITE, 1, &clsTmp, &cnt);
cls.reset(clsTmp);
if(FAILED(hrqual)) {
std::cerr << "Next class failed with " << hrqual << std::endl;
return false;
}
IWbemQualifierSet* qualTmp = nullptr;
cls->GetQualifierSet(&qualTmp);
std::unique_ptr<IWbemQualifierSet, default_release<IWbemQualifierSet>> qualifiers(qualTmp);
std::unique_ptr<VARIANT, free_variant> varEventType(new VARIANT);
qualifiers->Get(L"EventType", 0, varEventType.get(), nullptr);
if (varEventType->vt & VT_ARRAY) {
HRESULT hrSafe = S_OK;
int ClassEventType;
SAFEARRAY* pEventTypes = varEventType->parray;
for (LONG i=0; (ULONG)i < pEventTypes->rgsabound->cElements; i++) {
hrSafe = SafeArrayGetElement(pEventTypes, &i, &ClassEventType);
if (ClassEventType == CSWITCH_EVENT_TYPE) {
found = true;
break; //for loop
}
}
}
else {
if (varEventType->intVal == CSWITCH_EVENT_TYPE) {
found = true;
}
}
if (found) {
break; //while loop
}
}
if(found) {
g_EventCategoryClass = std::move(cls);
}
return found;
}
int main(int argc, char* argv[])
{
if(!ListThreads(GetCurrentProcessId(), g_Threads)) {
return 1;
}
std::cout << "Threads belonging to process: " << std::endl;
std::for_each(g_Threads.cbegin(), g_Threads.cend(), [](DWORD threadId) {
std::cout << threadId << std::endl;
});
// get the event class we are interested in
if(!GetEventClass()) {
return 1;
}
// Open the trace
EVENT_TRACE_LOGFILE logDesc = {0};
logDesc.LoggerName = KERNEL_LOGGER_NAME;
logDesc.ProcessTraceMode = PROCESS_TRACE_MODE_REAL_TIME;
logDesc.EventCallback = &ProcessEvent;
TRACEHANDLE consumeHandle = ::OpenTrace(&logDesc);
if(consumeHandle == INVALID_PROCESSTRACE_HANDLE) {
std::cerr << "Unable to open trace!" << std::endl;
return 1;
}
auto propsSize = sizeof(EVENT_TRACE_PROPERTIES) + sizeof(KERNEL_LOGGER_NAME);
std::unique_ptr<unsigned char[]> evtPropertiesMem(new unsigned char[propsSize]);
::memset(evtPropertiesMem.get(), 0, propsSize);
PEVENT_TRACE_PROPERTIES properties = reinterpret_cast<PEVENT_TRACE_PROPERTIES>(evtPropertiesMem.get());
properties->Wnode.BufferSize = propsSize;
properties->Wnode.Guid = SystemTraceControlGuid;
properties->Wnode.ClientContext = 1/*QPC*/;
properties->Wnode.Flags = WNODE_FLAG_TRACED_GUID;
properties->EnableFlags = EVENT_TRACE_FLAG_CSWITCH;
properties->LogFileMode = EVENT_TRACE_REAL_TIME_MODE;
properties->LogFileNameOffset = 0;
properties->LoggerNameOffset = sizeof(EVENT_TRACE_PROPERTIES);
TRACEHANDLE session;
auto error = ::StartTrace(&session, KERNEL_LOGGER_NAME, properties);
if(error != ERROR_SUCCESS) {
std::cerr << "Unable to start trace; error: " << error << std::endl;
}
std::thread consumerThread(std::bind(&StartTraceConsume, consumeHandle));
::Sleep(1000);
// Stop the session
properties->LoggerNameOffset = 0;
error = ::ControlTrace(session, KERNEL_LOGGER_NAME, properties, EVENT_TRACE_CONTROL_STOP);
if(error != ERROR_SUCCESS) {
std::cerr << "Unable to stop trace; error: " << error << std::endl;
}
error = ::CloseTrace(consumeHandle);
if(error != ERROR_SUCCESS) {
std::cerr << "Unable to close consume trace; error: " << error << std::endl;
}
std::cout << "Free buffers: " << properties->FreeBuffers << std::endl;
std::cout << "Events lost: " << properties->EventsLost << std::endl;
std::cout << "Buffers written: " << properties->BuffersWritten << std::endl;
std::cout << "Log buffers lost: " << properties->LogBuffersLost << std::endl;
std::cout << "RealTime buffers lost: " << properties->RealTimeBuffersLost << std::endl;
consumerThread.join();
std::cout << "Events received: " << g_EventsCount << std::endl;
std::cout << "Thread events received: " << g_ThreadEventsCount << std::endl;
std::cout << "CSwitch events received: " << g_CSwitchEventsCount << std::endl;
std::cout << "Thread events for this process received: " << g_ThisProcessThreadEvents << std::endl;
std::cout << "Scheduled thread events for this process received: " << g_ThisProcessThreadsScheduled << std::endl;
std::cout << "Unscheduled thread events for this process received: " << g_ThisProcessThreadsUnscheduled << std::endl;
std::cout << "Wait thread events for this process received: " << g_ThisProcessThreadsWaits << std::endl;
return 0;
}
<|endoftext|> |
<commit_before>/***********************************************************************
* filename: InputAggregator.cpp
* created: 10/7/2013
* author: Timotei Dolean <timotei21@gmail.com>
*************************************************************************/
/***************************************************************************
* Copyright (C) 2004 - 2013 Paul D Turner & The CEGUI Development Team
*
* 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 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 <boost/test/unit_test.hpp>
#include <boost/assign.hpp>
#include <vector>
#include <iostream>
#include <map>
#include "CEGUI/CEGUI.h"
using namespace CEGUI;
struct InputEventHandler
{
virtual void handle(const InputEvent* event) = 0;
};
template <typename TInput, typename TClass>
struct InputEventHandlerImpl : public InputEventHandler
{
typedef void(TClass::*HandlerFunctionType)(const TInput*);
InputEventHandlerImpl(HandlerFunctionType handler_func, TClass* obj) :
d_handlerFunc(handler_func),
d_obj(obj)
{}
void handle(const InputEvent* event)
{
(d_obj->*d_handlerFunc)((const TInput*)event);
}
private:
HandlerFunctionType d_handlerFunc;
TClass* d_obj;
};
class MockInputEventReceiver : public InputEventReceiver
{
public:
std::string d_text;
float d_totalScroll;
Vector2f d_pointerPosition;
Vector2f d_pointerTotalDelta;
std::vector<SemanticValue> d_semanticValues;
MockInputEventReceiver() :
d_text(""),
d_pointerPosition(0.0f, 0.0f),
d_pointerTotalDelta(0.0f, 0.0f),
d_totalScroll(0)
{}
~MockInputEventReceiver()
{
for (HandlersMap::const_iterator itor = d_handlersMap.begin();
itor != d_handlersMap.end(); ++ itor)
{
delete (*itor).second;
}
d_handlersMap.clear();
}
void injectInputEvent(const InputEvent* event)
{
HandlersMap::const_iterator itor = d_handlersMap.find(event->d_eventType);
if (itor != d_handlersMap.end())
{
(*itor).second->handle(event);
}
else
{
std::cout << "No event handler for event type: " << event->d_eventType << std::endl;
}
}
void handleTextEvent(const TextInputEvent* event)
{
d_text += event->d_character;
}
void handleMovementEvent(const PointerMovementInputEvent* event)
{
d_pointerPosition = event->d_position;
d_pointerTotalDelta += event->d_delta;
}
void handleScrollEvent(const ScrollInputEvent* event)
{
d_totalScroll += event->d_delta;
}
void handleSemanticEvent(const SemanticInputEvent* event)
{
d_semanticValues.push_back(event->d_value);
}
void initializeEventHandlers()
{
d_handlersMap.insert(std::make_pair(TextInputEventType,
new InputEventHandlerImpl<TextInputEvent, MockInputEventReceiver>(
&MockInputEventReceiver::handleTextEvent, this)));
d_handlersMap.insert(std::make_pair(MovementInputEventType,
new InputEventHandlerImpl<PointerMovementInputEvent, MockInputEventReceiver>(
&MockInputEventReceiver::handleMovementEvent, this)));
d_handlersMap.insert(std::make_pair(ScrollInputEventType,
new InputEventHandlerImpl<ScrollInputEvent, MockInputEventReceiver>(
&MockInputEventReceiver::handleScrollEvent, this)));
d_handlersMap.insert(std::make_pair(SemanticInputEventType,
new InputEventHandlerImpl<SemanticInputEvent, MockInputEventReceiver>(
&MockInputEventReceiver::handleSemanticEvent, this)));
}
private:
typedef std::map<int, InputEventHandler*> HandlersMap;
HandlersMap d_handlersMap;
};
struct InputAggregatorFixture
{
InputAggregatorFixture()
{
d_inputEventReceiver = new MockInputEventReceiver;
d_inputEventReceiver->initializeEventHandlers();
d_inputAggregator = new InputAggregator(d_inputEventReceiver);
}
~InputAggregatorFixture()
{
delete d_inputEventReceiver;
delete d_inputAggregator;
}
InputAggregator* d_inputAggregator;
MockInputEventReceiver* d_inputEventReceiver;
};
//----------------------------------------------------------------------------//
BOOST_FIXTURE_TEST_SUITE(InputAggregator, InputAggregatorFixture)
BOOST_AUTO_TEST_CASE(TextEventOneChar)
{
d_inputAggregator->injectChar('a');
BOOST_CHECK_EQUAL(d_inputEventReceiver->d_text, "a");
}
BOOST_AUTO_TEST_CASE(TextEventMultipleChars)
{
d_inputAggregator->injectChar('a');
d_inputAggregator->injectChar('b');
d_inputAggregator->injectChar('c');
BOOST_CHECK_EQUAL(d_inputEventReceiver->d_text, "abc");
}
BOOST_AUTO_TEST_CASE(MovementEventNoDelta)
{
d_inputAggregator->injectMouseMove(0, 0);
BOOST_CHECK_EQUAL(d_inputEventReceiver->d_pointerPosition,
d_inputEventReceiver->d_pointerTotalDelta);
BOOST_CHECK_EQUAL(d_inputEventReceiver->d_pointerPosition.d_x, 0);
BOOST_CHECK_EQUAL(d_inputEventReceiver->d_pointerPosition.d_y, 0);
}
BOOST_AUTO_TEST_CASE(MovementEventSingleDelta)
{
d_inputAggregator->injectMouseMove(0, 0);
d_inputAggregator->injectMouseMove(3, 5);
BOOST_CHECK_EQUAL(d_inputEventReceiver->d_pointerPosition,
d_inputEventReceiver->d_pointerTotalDelta);
BOOST_CHECK_EQUAL(d_inputEventReceiver->d_pointerPosition.d_x, 3);
BOOST_CHECK_EQUAL(d_inputEventReceiver->d_pointerPosition.d_y, 5);
}
BOOST_AUTO_TEST_CASE(MovementEventMultipleDeltas)
{
d_inputAggregator->injectMouseMove(0, 0);
d_inputAggregator->injectMouseMove(3, 5);
BOOST_CHECK_EQUAL(d_inputEventReceiver->d_pointerPosition,
d_inputEventReceiver->d_pointerTotalDelta);
BOOST_CHECK_EQUAL(d_inputEventReceiver->d_pointerPosition.d_x, 3);
BOOST_CHECK_EQUAL(d_inputEventReceiver->d_pointerPosition.d_y, 5);
d_inputAggregator->injectMouseMove(3, -3);
BOOST_CHECK_EQUAL(d_inputEventReceiver->d_pointerPosition.d_x, 6);
BOOST_CHECK_EQUAL(d_inputEventReceiver->d_pointerPosition.d_y, 2);
}
BOOST_AUTO_TEST_CASE(MovementEventZeroPosition)
{
d_inputAggregator->injectMousePosition(0, 0);
BOOST_CHECK_EQUAL(d_inputEventReceiver->d_pointerPosition,
d_inputEventReceiver->d_pointerTotalDelta);
BOOST_CHECK_EQUAL(d_inputEventReceiver->d_pointerPosition.d_x, 0);
BOOST_CHECK_EQUAL(d_inputEventReceiver->d_pointerPosition.d_y, 0);
}
BOOST_AUTO_TEST_CASE(MovementEventNonZeroPosition)
{
d_inputAggregator->injectMousePosition(30, 40);
BOOST_CHECK_EQUAL(d_inputEventReceiver->d_pointerPosition,
d_inputEventReceiver->d_pointerTotalDelta);
BOOST_CHECK_EQUAL(d_inputEventReceiver->d_pointerPosition.d_x, 30);
BOOST_CHECK_EQUAL(d_inputEventReceiver->d_pointerPosition.d_y, 40);
}
BOOST_AUTO_TEST_CASE(MovementEventMultiplePositions)
{
d_inputAggregator->injectMousePosition(3, 5);
BOOST_CHECK_EQUAL(d_inputEventReceiver->d_pointerPosition,
d_inputEventReceiver->d_pointerTotalDelta);
BOOST_CHECK_EQUAL(d_inputEventReceiver->d_pointerPosition.d_x, 3);
BOOST_CHECK_EQUAL(d_inputEventReceiver->d_pointerPosition.d_y, 5);
d_inputAggregator->injectMousePosition(3, -3);
BOOST_CHECK_EQUAL(d_inputEventReceiver->d_pointerPosition.d_x, 3);
BOOST_CHECK_EQUAL(d_inputEventReceiver->d_pointerPosition.d_y, -3);
}
BOOST_AUTO_TEST_CASE(ScrollEventNoDelta)
{
d_inputAggregator->injectMouseWheelChange(0);
BOOST_CHECK_EQUAL(d_inputEventReceiver->d_totalScroll, 0);
}
BOOST_AUTO_TEST_CASE(ScrollEventMultipleDelta)
{
d_inputAggregator->injectMouseWheelChange(1);
BOOST_CHECK_EQUAL(d_inputEventReceiver->d_totalScroll, 1);
d_inputAggregator->injectMouseWheelChange(3);
BOOST_CHECK_EQUAL(d_inputEventReceiver->d_totalScroll, 4);
d_inputAggregator->injectMouseWheelChange(5);
BOOST_CHECK_EQUAL(d_inputEventReceiver->d_totalScroll, 9);
d_inputAggregator->injectMouseWheelChange(-2);
BOOST_CHECK_EQUAL(d_inputEventReceiver->d_totalScroll, 7);
}
BOOST_AUTO_TEST_CASE(CutRequestToCut)
{
std::vector<SemanticValue> expected_values =
boost::assign::list_of(Cut);
d_inputAggregator->injectCutRequest();
BOOST_CHECK_EQUAL_COLLECTIONS(expected_values.begin(), expected_values.end(),
d_inputEventReceiver->d_semanticValues.begin(),
d_inputEventReceiver->d_semanticValues.end());
}
BOOST_AUTO_TEST_CASE(CopyRequestToCopy)
{
std::vector<SemanticValue> expected_values =
boost::assign::list_of(Copy);
d_inputAggregator->injectCopyRequest();
BOOST_CHECK_EQUAL_COLLECTIONS(expected_values.begin(), expected_values.end(),
d_inputEventReceiver->d_semanticValues.begin(),
d_inputEventReceiver->d_semanticValues.end());
}
BOOST_AUTO_TEST_CASE(PasteRequestToPaste)
{
std::vector<SemanticValue> expected_values =
boost::assign::list_of(Paste);
d_inputAggregator->injectPasteRequest();
BOOST_CHECK_EQUAL_COLLECTIONS(expected_values.begin(), expected_values.end(),
d_inputEventReceiver->d_semanticValues.begin(),
d_inputEventReceiver->d_semanticValues.end());
}
BOOST_AUTO_TEST_CASE(MouseClickToPointerActivate)
{
std::vector<SemanticValue> expected_values =
boost::assign::list_of(PointerActivate);
d_inputAggregator->injectMouseButtonClick(LeftButton);
BOOST_CHECK_EQUAL_COLLECTIONS(expected_values.begin(), expected_values.end(),
d_inputEventReceiver->d_semanticValues.begin(),
d_inputEventReceiver->d_semanticValues.end());
}
BOOST_AUTO_TEST_SUITE_END()
<commit_msg>Remove the dependency on boost assign<commit_after>/***********************************************************************
* filename: InputAggregator.cpp
* created: 10/7/2013
* author: Timotei Dolean <timotei21@gmail.com>
*************************************************************************/
/***************************************************************************
* Copyright (C) 2004 - 2013 Paul D Turner & The CEGUI Development Team
*
* 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 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 <boost/test/unit_test.hpp>
#include <vector>
#include <iostream>
#include <map>
#include "CEGUI/CEGUI.h"
using namespace CEGUI;
struct InputEventHandler
{
virtual void handle(const InputEvent* event) = 0;
};
template <typename TInput, typename TClass>
struct InputEventHandlerImpl : public InputEventHandler
{
typedef void(TClass::*HandlerFunctionType)(const TInput*);
InputEventHandlerImpl(HandlerFunctionType handler_func, TClass* obj) :
d_handlerFunc(handler_func),
d_obj(obj)
{}
void handle(const InputEvent* event)
{
(d_obj->*d_handlerFunc)((const TInput*)event);
}
private:
HandlerFunctionType d_handlerFunc;
TClass* d_obj;
};
class MockInputEventReceiver : public InputEventReceiver
{
public:
std::string d_text;
float d_totalScroll;
Vector2f d_pointerPosition;
Vector2f d_pointerTotalDelta;
std::vector<SemanticValue> d_semanticValues;
MockInputEventReceiver() :
d_text(""),
d_pointerPosition(0.0f, 0.0f),
d_pointerTotalDelta(0.0f, 0.0f),
d_totalScroll(0)
{}
~MockInputEventReceiver()
{
for (HandlersMap::const_iterator itor = d_handlersMap.begin();
itor != d_handlersMap.end(); ++ itor)
{
delete (*itor).second;
}
d_handlersMap.clear();
}
void injectInputEvent(const InputEvent* event)
{
HandlersMap::const_iterator itor = d_handlersMap.find(event->d_eventType);
if (itor != d_handlersMap.end())
{
(*itor).second->handle(event);
}
else
{
std::cout << "No event handler for event type: " << event->d_eventType << std::endl;
}
}
void handleTextEvent(const TextInputEvent* event)
{
d_text += event->d_character;
}
void handleMovementEvent(const PointerMovementInputEvent* event)
{
d_pointerPosition = event->d_position;
d_pointerTotalDelta += event->d_delta;
}
void handleScrollEvent(const ScrollInputEvent* event)
{
d_totalScroll += event->d_delta;
}
void handleSemanticEvent(const SemanticInputEvent* event)
{
d_semanticValues.push_back(event->d_value);
}
void initializeEventHandlers()
{
d_handlersMap.insert(std::make_pair(TextInputEventType,
new InputEventHandlerImpl<TextInputEvent, MockInputEventReceiver>(
&MockInputEventReceiver::handleTextEvent, this)));
d_handlersMap.insert(std::make_pair(MovementInputEventType,
new InputEventHandlerImpl<PointerMovementInputEvent, MockInputEventReceiver>(
&MockInputEventReceiver::handleMovementEvent, this)));
d_handlersMap.insert(std::make_pair(ScrollInputEventType,
new InputEventHandlerImpl<ScrollInputEvent, MockInputEventReceiver>(
&MockInputEventReceiver::handleScrollEvent, this)));
d_handlersMap.insert(std::make_pair(SemanticInputEventType,
new InputEventHandlerImpl<SemanticInputEvent, MockInputEventReceiver>(
&MockInputEventReceiver::handleSemanticEvent, this)));
}
private:
typedef std::map<int, InputEventHandler*> HandlersMap;
HandlersMap d_handlersMap;
};
struct InputAggregatorFixture
{
InputAggregatorFixture()
{
d_inputEventReceiver = new MockInputEventReceiver;
d_inputEventReceiver->initializeEventHandlers();
d_inputAggregator = new InputAggregator(d_inputEventReceiver);
}
~InputAggregatorFixture()
{
delete d_inputEventReceiver;
delete d_inputAggregator;
}
InputAggregator* d_inputAggregator;
MockInputEventReceiver* d_inputEventReceiver;
};
//----------------------------------------------------------------------------//
BOOST_FIXTURE_TEST_SUITE(InputAggregator, InputAggregatorFixture)
BOOST_AUTO_TEST_CASE(TextEventOneChar)
{
d_inputAggregator->injectChar('a');
BOOST_CHECK_EQUAL(d_inputEventReceiver->d_text, "a");
}
BOOST_AUTO_TEST_CASE(TextEventMultipleChars)
{
d_inputAggregator->injectChar('a');
d_inputAggregator->injectChar('b');
d_inputAggregator->injectChar('c');
BOOST_CHECK_EQUAL(d_inputEventReceiver->d_text, "abc");
}
BOOST_AUTO_TEST_CASE(MovementEventNoDelta)
{
d_inputAggregator->injectMouseMove(0, 0);
BOOST_CHECK_EQUAL(d_inputEventReceiver->d_pointerPosition,
d_inputEventReceiver->d_pointerTotalDelta);
BOOST_CHECK_EQUAL(d_inputEventReceiver->d_pointerPosition.d_x, 0);
BOOST_CHECK_EQUAL(d_inputEventReceiver->d_pointerPosition.d_y, 0);
}
BOOST_AUTO_TEST_CASE(MovementEventSingleDelta)
{
d_inputAggregator->injectMouseMove(0, 0);
d_inputAggregator->injectMouseMove(3, 5);
BOOST_CHECK_EQUAL(d_inputEventReceiver->d_pointerPosition,
d_inputEventReceiver->d_pointerTotalDelta);
BOOST_CHECK_EQUAL(d_inputEventReceiver->d_pointerPosition.d_x, 3);
BOOST_CHECK_EQUAL(d_inputEventReceiver->d_pointerPosition.d_y, 5);
}
BOOST_AUTO_TEST_CASE(MovementEventMultipleDeltas)
{
d_inputAggregator->injectMouseMove(0, 0);
d_inputAggregator->injectMouseMove(3, 5);
BOOST_CHECK_EQUAL(d_inputEventReceiver->d_pointerPosition,
d_inputEventReceiver->d_pointerTotalDelta);
BOOST_CHECK_EQUAL(d_inputEventReceiver->d_pointerPosition.d_x, 3);
BOOST_CHECK_EQUAL(d_inputEventReceiver->d_pointerPosition.d_y, 5);
d_inputAggregator->injectMouseMove(3, -3);
BOOST_CHECK_EQUAL(d_inputEventReceiver->d_pointerPosition.d_x, 6);
BOOST_CHECK_EQUAL(d_inputEventReceiver->d_pointerPosition.d_y, 2);
}
BOOST_AUTO_TEST_CASE(MovementEventZeroPosition)
{
d_inputAggregator->injectMousePosition(0, 0);
BOOST_CHECK_EQUAL(d_inputEventReceiver->d_pointerPosition,
d_inputEventReceiver->d_pointerTotalDelta);
BOOST_CHECK_EQUAL(d_inputEventReceiver->d_pointerPosition.d_x, 0);
BOOST_CHECK_EQUAL(d_inputEventReceiver->d_pointerPosition.d_y, 0);
}
BOOST_AUTO_TEST_CASE(MovementEventNonZeroPosition)
{
d_inputAggregator->injectMousePosition(30, 40);
BOOST_CHECK_EQUAL(d_inputEventReceiver->d_pointerPosition,
d_inputEventReceiver->d_pointerTotalDelta);
BOOST_CHECK_EQUAL(d_inputEventReceiver->d_pointerPosition.d_x, 30);
BOOST_CHECK_EQUAL(d_inputEventReceiver->d_pointerPosition.d_y, 40);
}
BOOST_AUTO_TEST_CASE(MovementEventMultiplePositions)
{
d_inputAggregator->injectMousePosition(3, 5);
BOOST_CHECK_EQUAL(d_inputEventReceiver->d_pointerPosition,
d_inputEventReceiver->d_pointerTotalDelta);
BOOST_CHECK_EQUAL(d_inputEventReceiver->d_pointerPosition.d_x, 3);
BOOST_CHECK_EQUAL(d_inputEventReceiver->d_pointerPosition.d_y, 5);
d_inputAggregator->injectMousePosition(3, -3);
BOOST_CHECK_EQUAL(d_inputEventReceiver->d_pointerPosition.d_x, 3);
BOOST_CHECK_EQUAL(d_inputEventReceiver->d_pointerPosition.d_y, -3);
}
BOOST_AUTO_TEST_CASE(ScrollEventNoDelta)
{
d_inputAggregator->injectMouseWheelChange(0);
BOOST_CHECK_EQUAL(d_inputEventReceiver->d_totalScroll, 0);
}
BOOST_AUTO_TEST_CASE(ScrollEventMultipleDelta)
{
d_inputAggregator->injectMouseWheelChange(1);
BOOST_CHECK_EQUAL(d_inputEventReceiver->d_totalScroll, 1);
d_inputAggregator->injectMouseWheelChange(3);
BOOST_CHECK_EQUAL(d_inputEventReceiver->d_totalScroll, 4);
d_inputAggregator->injectMouseWheelChange(5);
BOOST_CHECK_EQUAL(d_inputEventReceiver->d_totalScroll, 9);
d_inputAggregator->injectMouseWheelChange(-2);
BOOST_CHECK_EQUAL(d_inputEventReceiver->d_totalScroll, 7);
}
BOOST_AUTO_TEST_CASE(CutRequestToCut)
{
std::vector<SemanticValue> expected_values;
expected_values.push_back(Cut);
d_inputAggregator->injectCutRequest();
BOOST_CHECK_EQUAL_COLLECTIONS(expected_values.begin(), expected_values.end(),
d_inputEventReceiver->d_semanticValues.begin(),
d_inputEventReceiver->d_semanticValues.end());
}
BOOST_AUTO_TEST_CASE(CopyRequestToCopy)
{
std::vector<SemanticValue> expected_values;
expected_values.push_back(Copy);
d_inputAggregator->injectCopyRequest();
BOOST_CHECK_EQUAL_COLLECTIONS(expected_values.begin(), expected_values.end(),
d_inputEventReceiver->d_semanticValues.begin(),
d_inputEventReceiver->d_semanticValues.end());
}
BOOST_AUTO_TEST_CASE(PasteRequestToPaste)
{
std::vector<SemanticValue> expected_values;
expected_values.push_back(Paste);
d_inputAggregator->injectPasteRequest();
BOOST_CHECK_EQUAL_COLLECTIONS(expected_values.begin(), expected_values.end(),
d_inputEventReceiver->d_semanticValues.begin(),
d_inputEventReceiver->d_semanticValues.end());
}
BOOST_AUTO_TEST_CASE(MouseClickToPointerActivate)
{
std::vector<SemanticValue> expected_values;
expected_values.push_back(PointerActivate);
d_inputAggregator->injectMouseButtonClick(LeftButton);
BOOST_CHECK_EQUAL_COLLECTIONS(expected_values.begin(), expected_values.end(),
d_inputEventReceiver->d_semanticValues.begin(),
d_inputEventReceiver->d_semanticValues.end());
}
BOOST_AUTO_TEST_SUITE_END()
<|endoftext|> |
<commit_before>//---------------------------- data_out_03.cc ---------------------------
// $Id$
// Version: $Name$
//
// Copyright (C) 2003, 2004 by the deal.II authors
//
// This file is subject to QPL and may not be distributed
// without copyright and license information. Please refer
// to the file deal.II/doc/license.html for the text and
// further information on this license.
//
//---------------------------- data_out_03.cc ---------------------------
// write the data in deal.II intermediate form, read it back in, and
// make sure that the result is the same
#include "../tests.h"
#include "data_out_common.cc"
#include <lac/sparsity_pattern.h>
#include <numerics/data_out.h>
std::string output_file_name = "data_out_03.output";
// have a class that makes sure we can get at the patches and data set
// names that the base class generates
template <int dim>
class XDataOut : public DataOut<dim>
{
public:
const std::vector<typename DataOutBase::Patch<dim,dim> > &
get_patches() const
{ return DataOut<dim>::get_patches(); }
std::vector<std::string>
get_dataset_names () const
{ return DataOut<dim>::get_dataset_names(); }
};
// have a class that makes sure we can get at the patches and data set
// names that the base class generates
template <int dim>
class XDataOutReader : public DataOutReader<dim>
{
public:
const std::vector<typename DataOutBase::Patch<dim,dim> > &
get_patches() const
{ return DataOutReader<dim>::get_patches(); }
std::vector<std::string>
get_dataset_names () const
{ return DataOutReader<dim>::get_dataset_names(); }
};
template <int dim>
void
check_this (const DoFHandler<dim> &dof_handler,
const Vector<double> &v_node,
const Vector<double> &v_cell)
{
XDataOut<dim> data_out;
data_out.attach_dof_handler (dof_handler);
data_out.add_data_vector (v_node, "node_data");
data_out.add_data_vector (v_cell, "cell_data");
data_out.build_patches ();
{
std::ofstream tmp ("data_out_03.tmp");
data_out.write_deal_II_intermediate (tmp);
}
XDataOutReader<dim> reader;
{
std::ifstream tmp ("data_out_03.tmp");
reader.read (tmp);
}
// finally make sure that we have
// read everything back in
// correctly
Assert (data_out.get_dataset_names() == reader.get_dataset_names(),
ExcInternalError());
Assert (data_out.get_patches().size() == reader.get_patches().size(),
ExcInternalError());
for (unsigned int i=0; i<reader.get_patches().size(); ++i)
Assert (data_out.get_patches()[i] == reader.get_patches()[i],
ExcInternalError());
// for good measure, delete tmp file
remove ("data_out_03.tmp");
deallog << "OK" << std::endl;
}
<commit_msg>Add missing ::.<commit_after>//---------------------------- data_out_03.cc ---------------------------
// $Id$
// Version: $Name$
//
// Copyright (C) 2003, 2004 by the deal.II authors
//
// This file is subject to QPL and may not be distributed
// without copyright and license information. Please refer
// to the file deal.II/doc/license.html for the text and
// further information on this license.
//
//---------------------------- data_out_03.cc ---------------------------
// write the data in deal.II intermediate form, read it back in, and
// make sure that the result is the same
#include "../tests.h"
#include "data_out_common.cc"
#include <lac/sparsity_pattern.h>
#include <numerics/data_out.h>
std::string output_file_name = "data_out_03.output";
// have a class that makes sure we can get at the patches and data set
// names that the base class generates
template <int dim>
class XDataOut : public DataOut<dim>
{
public:
const std::vector<typename ::DataOutBase::Patch<dim,dim> > &
get_patches() const
{ return DataOut<dim>::get_patches(); }
std::vector<std::string>
get_dataset_names () const
{ return DataOut<dim>::get_dataset_names(); }
};
// have a class that makes sure we can get at the patches and data set
// names that the base class generates
template <int dim>
class XDataOutReader : public DataOutReader<dim>
{
public:
const std::vector<typename ::DataOutBase::Patch<dim,dim> > &
get_patches() const
{ return DataOutReader<dim>::get_patches(); }
std::vector<std::string>
get_dataset_names () const
{ return DataOutReader<dim>::get_dataset_names(); }
};
template <int dim>
void
check_this (const DoFHandler<dim> &dof_handler,
const Vector<double> &v_node,
const Vector<double> &v_cell)
{
XDataOut<dim> data_out;
data_out.attach_dof_handler (dof_handler);
data_out.add_data_vector (v_node, "node_data");
data_out.add_data_vector (v_cell, "cell_data");
data_out.build_patches ();
{
std::ofstream tmp ("data_out_03.tmp");
data_out.write_deal_II_intermediate (tmp);
}
XDataOutReader<dim> reader;
{
std::ifstream tmp ("data_out_03.tmp");
reader.read (tmp);
}
// finally make sure that we have
// read everything back in
// correctly
Assert (data_out.get_dataset_names() == reader.get_dataset_names(),
ExcInternalError());
Assert (data_out.get_patches().size() == reader.get_patches().size(),
ExcInternalError());
for (unsigned int i=0; i<reader.get_patches().size(); ++i)
Assert (data_out.get_patches()[i] == reader.get_patches()[i],
ExcInternalError());
// for good measure, delete tmp file
remove ("data_out_03.tmp");
deallog << "OK" << std::endl;
}
<|endoftext|> |
<commit_before>// ---------------------------------------------------------------------
//
// Copyright (C) 2004 - 2015 by the deal.II authors
//
// This file is part of the deal.II library.
//
// The deal.II library is free software; you can use it, 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.
// The full text of the license can be found in the file LICENSE at
// the top level of the deal.II distribution.
//
// ---------------------------------------------------------------------
// block vectors
#include "../tests.h"
#include <deal.II/lac/generic_linear_algebra.h>
#include <deal.II/base/index_set.h>
#include <deal.II/lac/constraint_matrix.h>
#include <fstream>
#include <iostream>
#include <iomanip>
#include <vector>
#include "gla.h"
template <class LA>
void test ()
{
unsigned int myid = Utilities::MPI::this_mpi_process (MPI_COMM_WORLD);
unsigned int numproc = Utilities::MPI::n_mpi_processes (MPI_COMM_WORLD);
if (myid==0)
deallog << "numproc=" << numproc << std::endl;
IndexSet block1(10);
if (numproc==1)
block1.add_range(0,10);
if (myid==0)
block1.add_range(0,7);
if (myid==1)
block1.add_range(7,10);
IndexSet block2(6);
if (numproc==1)
block2.add_range(0,6);
if (myid==0)
block2.add_range(0,2);
if (myid==1)
block2.add_range(2,6);
std::vector<IndexSet> partitioning;
partitioning.push_back(block1);
partitioning.push_back(block2);
typename LA::MPI::BlockVector v(partitioning, MPI_COMM_WORLD);
v = 0.1;
deallog << "l2norm: " << v.l2_norm() << std::endl;
v(myid) = myid;
v.compress(VectorOperation::insert);
deallog << "size: " << v.size() << std::endl;
deallog << "block(0).size: " << v.block(0).size() << std::endl;
deallog << "block(1).size: " << v.block(1).size() << std::endl;
if (block1.n_elements()>0)
deallog << "my first entry: " << v(block1.nth_index_in_set(0)) << std::endl;
// done
if (myid==0)
deallog << "OK" << std::endl;
}
int main (int argc, char **argv)
{
Utilities::MPI::MPI_InitFinalize mpi_initialization (argc, argv, 1);
MPILogInitAll log;
{
deallog.push("PETSc");
test<LA_PETSc>();
deallog.pop();
deallog.push("Trilinos");
test<LA_Trilinos>();
deallog.pop();
}
}
<commit_msg>extend gla/block_vec_01 to complex-valued PETSc<commit_after>// ---------------------------------------------------------------------
//
// Copyright (C) 2004 - 2015 by the deal.II authors
//
// This file is part of the deal.II library.
//
// The deal.II library is free software; you can use it, 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.
// The full text of the license can be found in the file LICENSE at
// the top level of the deal.II distribution.
//
// ---------------------------------------------------------------------
// block vectors
#include "../tests.h"
#include <deal.II/lac/generic_linear_algebra.h>
#include <deal.II/base/index_set.h>
#include <deal.II/lac/constraint_matrix.h>
#include <fstream>
#include <iostream>
#include <iomanip>
#include <vector>
#include "gla.h"
template <class LA>
void test ()
{
unsigned int myid = Utilities::MPI::this_mpi_process (MPI_COMM_WORLD);
unsigned int numproc = Utilities::MPI::n_mpi_processes (MPI_COMM_WORLD);
if (myid==0)
deallog << "numproc=" << numproc << std::endl;
IndexSet block1(10);
if (numproc==1)
block1.add_range(0,10);
if (myid==0)
block1.add_range(0,7);
if (myid==1)
block1.add_range(7,10);
IndexSet block2(6);
if (numproc==1)
block2.add_range(0,6);
if (myid==0)
block2.add_range(0,2);
if (myid==1)
block2.add_range(2,6);
std::vector<IndexSet> partitioning;
partitioning.push_back(block1);
partitioning.push_back(block2);
typename LA::MPI::BlockVector v(partitioning, MPI_COMM_WORLD);
v = 0.1;
deallog << "l2norm: " << v.l2_norm() << std::endl;
v(myid) = myid;
v.compress(VectorOperation::insert);
deallog << "size: " << v.size() << std::endl;
deallog << "block(0).size: " << v.block(0).size() << std::endl;
deallog << "block(1).size: " << v.block(1).size() << std::endl;
if (block1.n_elements()>0)
deallog << "my first entry: " << get_real_assert_zero_imag(v(block1.nth_index_in_set(0))) << std::endl;
// done
if (myid==0)
deallog << "OK" << std::endl;
}
int main (int argc, char **argv)
{
Utilities::MPI::MPI_InitFinalize mpi_initialization (argc, argv, 1);
MPILogInitAll log;
{
deallog.push("PETSc");
test<LA_PETSc>();
deallog.pop();
deallog.push("Trilinos");
test<LA_Trilinos>();
deallog.pop();
}
}
<|endoftext|> |
<commit_before>/*
Copyright 2011 Joe Hermaszewski. All rights reserved.
Redistribution and use in source and binary forms, with or without modification, are
permitted provided that the following conditions are met:
1. Redistributions of source code must retain the above copyright notice, this list of
conditions and the following disclaimer.
2. Redistributions in binary form must reproduce the above copyright notice, this list
of conditions and the following disclaimer in the documentation and/or other materials
provided with the distribution.
THIS SOFTWARE IS PROVIDED BY Joe Hermaszewski "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 Joe Hermaszewski 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.
The views and conclusions contained in the software and documentation are those of the
authors and should not be interpreted as representing official policies, either expressed
or implied, of Joe Hermaszewski.
*/
#include <iostream>
#include <unistd.h>
#include <joemath/joemath.hpp>
#include "timer.hpp"
const u32 NUM_ITERATIONS = 100000000;
void testFloatUtil()
{
NTimer::CTimer timer;
std::cout << "float step, ";
float v = 0.0f;
timer.Start();
for(u32 i = 0; i < NUM_ITERATIONS; ++i)
NJoemath::step(v, 0.0f);
timer.Stop();
std::cout << timer.GetElapsedTime() / double(NUM_ITERATIONS) << "\n";
}
int main( int argc, char** argv )
{
testFloatUtil();
return 0;
}
<commit_msg>added float2 test<commit_after>/*
Copyright 2011 Joe Hermaszewski. All rights reserved.
Redistribution and use in source and binary forms, with or without modification, are
permitted provided that the following conditions are met:
1. Redistributions of source code must retain the above copyright notice, this list of
conditions and the following disclaimer.
2. Redistributions in binary form must reproduce the above copyright notice, this list
of conditions and the following disclaimer in the documentation and/or other materials
provided with the distribution.
THIS SOFTWARE IS PROVIDED BY Joe Hermaszewski "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 Joe Hermaszewski 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.
The views and conclusions contained in the software and documentation are those of the
authors and should not be interpreted as representing official policies, either expressed
or implied, of Joe Hermaszewski.
*/
#include <iostream>
#include <joemath/joemath.hpp>
#include "timer.hpp"
const u32 NUM_ITERATIONS = 100000000;
void testFloatUtil()
{
NTimer::CTimer timer;
std::cout << "float step, ";
float v = 0.0f;
timer.Start();
for(u32 i = 0; i < NUM_ITERATIONS; ++i)
NJoemath::Step(v, 0.0f);
timer.Stop();
std::cout << timer.GetElapsedTime() / double(NUM_ITERATIONS) << "\n";
}
void testFloat2()
{
NTimer::CTimer timer;
std::cout << "float2 length, ";
NJoemath::float2 v(1.0f, 1.0f);
timer.Start();
for(u32 i = 0; i < NUM_ITERATIONS; ++i)
v.x = v.Length();
timer.Stop();
std::cout << timer.GetElapsedTime() / double(NUM_ITERATIONS) << "\n";
}
int main( int argc, char** argv )
{
testFloatUtil();
testFloat2();
return 0;
}
<|endoftext|> |
<commit_before>// The MIT License (MIT)
//
// Copyright (c) 2015 Relja Ljubobratovic, ljubobratovic.relja@gmail.com
//
// 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.
#ifndef CV_IGNORE_GUI // ignore compilation of the source file.
#include "../include/gui.hpp"
#include "../include/array.hpp"
namespace cv {
image_window::image_window(QWidget *parent): QDialog(parent) {
QHBoxLayout *lay = new QHBoxLayout(this);
lay->setContentsMargins(QMargins(0, 0, 0, 0));
image_lbl = new QLabel("", this);
lay->addWidget(image_lbl);
this->setLayout(lay);
this->resize(500, 500);
}
image_window::~image_window() {
}
void image_window::set_image(const image_array &image) {
if (!image.is_valid()) {
return;
}
QImage::Format format;
switch (image.depth()) {
case 1:
{
switch (image.channels()) {
case 1: format = QImage::Format_Indexed8; break;
case 3: format = QImage::Format_RGB888; break;
#ifdef WINDOWS
case 4: format = QImage::Format_RGBA8888; break;
#endif
default: std::cerr << "Unsupported image format.\n"; return;
}
}
break;
case 2:
{
switch (image.channels()) {
case 3: format = QImage::Format_RGB16;
default: std::cerr << "Unsupported image format.\n"; return;
}
}
break;
case 4:
{
switch (image.channels()) {
case 3: format = QImage::Format_RGB32;
default: std::cerr << "Unsupported image format.\n"; return;
}
}
default:
std::cerr << "Unsupported image format.\n";
return;
}
// TODO: find neat way to show non-contiguous images.
if (image.is_contiguous()) {
this->image_lbl->setPixmap(
QPixmap::fromImage(QImage(reinterpret_cast<byte*>(image.data()),
image.cols(), image.rows(), format)));
} else {
auto im_c = image.clone();
this->image_lbl->setPixmap(
QPixmap::fromImage(QImage(reinterpret_cast<byte*>(im_c.data()),
im_c.cols(), im_c.rows(), format)));
}
this->resize(image.cols(), image.rows());
}
void image_window::keyPressEvent(QKeyEvent *e) {
global_image_application::singleton()->assign_key(e->text()[0].toAscii());
}
void image_window::closeEvent(QCloseEvent *e) {
}
/****************************************************************************
** Meta object code from reading C++ file 'gui.hpp'
**
** Created by: The Qt Meta Object Compiler version 63 (Qt 4.8.6)
**
** WARNING! All changes made in this file will be lost!
*****************************************************************************/
#if !defined(Q_MOC_OUTPUT_REVISION)
#error "The header file 'gui.hpp' doesn't include <QObject>."
#elif Q_MOC_OUTPUT_REVISION != 63
#error "This file was generated using the moc from 4.8.6. It"
#error "cannot be used with the include files from this version of Qt."
#error "(The moc has changed too much.)"
#endif
QT_BEGIN_MOC_NAMESPACE
static const uint qt_meta_data_cv__image_window[] = {
// content:
6, // revision
0, // classname
0, 0, // classinfo
0, 0, // methods
0, 0, // properties
0, 0, // enums/sets
0, 0, // constructors
0, // flags
0, // signalCount
0 // eod
};
static const char qt_meta_stringdata_cv__image_window[] = {
"cv::image_window\0"
};
void cv::image_window::qt_static_metacall(QObject *_o, QMetaObject::Call _c, int _id, void **_a)
{
Q_UNUSED(_o);
Q_UNUSED(_id);
Q_UNUSED(_c);
Q_UNUSED(_a);
}
const QMetaObjectExtraData cv::image_window::staticMetaObjectExtraData = {
0, qt_static_metacall
};
const QMetaObject cv::image_window::staticMetaObject = {
{ &QDialog::staticMetaObject, qt_meta_stringdata_cv__image_window,
qt_meta_data_cv__image_window, &staticMetaObjectExtraData }
};
#ifdef Q_NO_DATA_RELOCATION
const QMetaObject &cv::image_window::getStaticMetaObject() { return staticMetaObject; }
#endif //Q_NO_DATA_RELOCATION
const QMetaObject *cv::image_window::metaObject() const
{
return QObject::d_ptr->metaObject ? QObject::d_ptr->metaObject : &staticMetaObject;
}
void *cv::image_window::qt_metacast(const char *_clname)
{
if (!_clname) return 0;
if (!strcmp(_clname, qt_meta_stringdata_cv__image_window))
return static_cast<void*>(const_cast< image_window*>(this));
return QDialog::qt_metacast(_clname);
}
int cv::image_window::qt_metacall(QMetaObject::Call _c, int _id, void **_a)
{
_id = QDialog::qt_metacall(_c, _id, _a);
if (_id < 0)
return _id;
return _id;
}
QT_END_MOC_NAMESPACE
// MOC Generated code end /////////////////////////////////////////////
///////////////////////////////////////////////////////////////////////
// class global_image_application
global_image_application* global_image_application::_singleton = nullptr;
global_image_application::global_image_application(int &argc, char** argv) : QApplication(argc, argv), _last_key('\0') {
}
global_image_application::~global_image_application() {
this->destroy_all_windows();
}
global_image_application *global_image_application::singleton() {
if (!global_image_application::_singleton) {
int argc_simulation = 1;
char *argv_simulation[] = {" ", " "};
global_image_application::_singleton = new global_image_application(argc_simulation, argv_simulation);
}
return global_image_application::_singleton;
}
void global_image_application::force_quit() {
this->quit();
}
void global_image_application::assign_key(char key) {
this->_last_key = key;
for (auto w : this->_windows) {
w->close();
}
}
char global_image_application::get_last_key() const {
return this->_last_key;
}
void global_image_application::create_window(const std::string &name, const image_array &image) {
image_window *newWindow = new image_window;
newWindow->setWindowTitle(name.c_str());
newWindow->set_image(image);
newWindow->show();
this->_windows.push_back(newWindow);
}
void global_image_application::destroy_window(const std::string &name) {
int winId = -1;
for (int i = 0; i < this->_windows.size(); i++) {
if (this->_windows[i]->windowTitle() == name.c_str()) {
winId = i;
break;
}
}
if (winId != -1) {
this->_windows[winId]->close();
delete this->_windows[winId];
this->_windows.erase(this->_windows.begin() + winId);
} else {
std::cerr << ("Window by name " + name + " does not exist.\n");
}
}
void global_image_application::destroy_all_windows() {
for (auto window : this->_windows) {
window->close();
delete window;
}
this->_windows.clear();
}
void imshow(const std::string &name, const image_array &image) {
ASSERT(image.is_valid() && (image.channels() == 1 || image.channels() == 3 || image.channels() == 4));
if (image.depth() != 1) {
auto byte_copy = image.clone();
byte_copy.convert_to<byte>();
global_image_application::singleton()->create_window(name, byte_copy);
} else {
global_image_application::singleton()->create_window(name, image);
}
}
void imclose(const std::string &name) {
global_image_application::singleton()->destroy_window(name);
}
void imclose_all() {
global_image_application::singleton()->destroy_all_windows();
}
char wait_key() {
auto ga_inst = global_image_application::singleton();
ga_inst->exec();
return ga_inst->get_last_key();
}
}
#endif // CV_IGNORE_GUI
<commit_msg>moved qt include from header<commit_after>// The MIT License (MIT)
//
// Copyright (c) 2015 Relja Ljubobratovic, ljubobratovic.relja@gmail.com
//
// 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.
#ifndef CV_IGNORE_GUI // ignore compilation of the source file.
#include "../include/gui.hpp"
#include "../include/array.hpp"
#include <QtCore/QtCore>
#include <QtGui/QtGui>
#ifdef WIN32
// TODO: integrate qt include files in thirdParty directory.
#include <QtWidgets/QDialog>
#include <QtWidgets/QKeyEvent>
#include <QtWidgets/QCloseEvent>
#include <QtWidgets/QLabel>
#include <QtWidgets/QApplication>
#include <QtWidgets/QBoxLayout>
#else
#include <QtGui/QDialog>
#include <QtGui/QKeyEvent>
#include <QtGui/QCloseEvent>
#include <QtGui/QLabel>
#include <QtGui/QBoxLayout>
#include <QtGui/QApplication>
#endif
namespace cv {
class CV_EXPORT image_window : public QDialog {
Q_OBJECT
private:
QLabel *image_lbl;
public:
explicit image_window(QWidget *parent = nullptr);
~image_window();
void set_image(const image_array &image);
virtual void keyPressEvent(QKeyEvent *e);
virtual void closeEvent(QCloseEvent *c);
};
class CV_EXPORT global_image_application: public QApplication {
private:
static global_image_application* _singleton;
std::vector<image_window*> _windows;
bool _force_quit;
char _last_key;
global_image_application(int &argc, char** argv);
public:
~global_image_application();
static global_image_application *singleton();
void force_quit();
void assign_key(char key);
char get_last_key() const;
void create_window(const std::string &name, const image_array &image);
void destroy_window(const std::string &name);
void destroy_all_windows();
};
image_window::image_window(QWidget *parent): QDialog(parent) {
QHBoxLayout *lay = new QHBoxLayout(this);
lay->setContentsMargins(QMargins(0, 0, 0, 0));
image_lbl = new QLabel("", this);
lay->addWidget(image_lbl);
this->setLayout(lay);
this->resize(500, 500);
}
image_window::~image_window() {
}
void image_window::set_image(const image_array &image) {
if (!image.is_valid()) {
return;
}
QImage::Format format;
switch (image.depth()) {
case 1:
{
switch (image.channels()) {
case 1: format = QImage::Format_Indexed8; break;
case 3: format = QImage::Format_RGB888; break;
#ifdef WINDOWS
case 4: format = QImage::Format_RGBA8888; break;
#endif
default: std::cerr << "Unsupported image format.\n"; return;
}
}
break;
case 2:
{
switch (image.channels()) {
case 3: format = QImage::Format_RGB16;
default: std::cerr << "Unsupported image format.\n"; return;
}
}
break;
case 4:
{
switch (image.channels()) {
case 3: format = QImage::Format_RGB32;
default: std::cerr << "Unsupported image format.\n"; return;
}
}
default:
std::cerr << "Unsupported image format.\n";
return;
}
// TODO: find neat way to show non-contiguous images.
if (image.is_contiguous()) {
this->image_lbl->setPixmap(
QPixmap::fromImage(QImage(reinterpret_cast<byte*>(image.data()),
image.cols(), image.rows(), format)));
} else {
auto im_c = image.clone();
this->image_lbl->setPixmap(
QPixmap::fromImage(QImage(reinterpret_cast<byte*>(im_c.data()),
im_c.cols(), im_c.rows(), format)));
}
this->resize(image.cols(), image.rows());
}
void image_window::keyPressEvent(QKeyEvent *e) {
global_image_application::singleton()->assign_key(e->text()[0].toAscii());
}
void image_window::closeEvent(QCloseEvent *e) {
}
/****************************************************************************
** Meta object code from reading C++ file 'gui.hpp'
**
** Created by: The Qt Meta Object Compiler version 63 (Qt 4.8.6)
**
** WARNING! All changes made in this file will be lost!
*****************************************************************************/
#if !defined(Q_MOC_OUTPUT_REVISION)
#error "The header file 'gui.hpp' doesn't include <QObject>."
#elif Q_MOC_OUTPUT_REVISION != 63
#error "This file was generated using the moc from 4.8.6. It"
#error "cannot be used with the include files from this version of Qt."
#error "(The moc has changed too much.)"
#endif
QT_BEGIN_MOC_NAMESPACE
static const uint qt_meta_data_cv__image_window[] = {
// content:
6, // revision
0, // classname
0, 0, // classinfo
0, 0, // methods
0, 0, // properties
0, 0, // enums/sets
0, 0, // constructors
0, // flags
0, // signalCount
0 // eod
};
static const char qt_meta_stringdata_cv__image_window[] = {
"cv::image_window\0"
};
void cv::image_window::qt_static_metacall(QObject *_o, QMetaObject::Call _c, int _id, void **_a)
{
Q_UNUSED(_o);
Q_UNUSED(_id);
Q_UNUSED(_c);
Q_UNUSED(_a);
}
const QMetaObjectExtraData cv::image_window::staticMetaObjectExtraData = {
0, qt_static_metacall
};
const QMetaObject cv::image_window::staticMetaObject = {
{ &QDialog::staticMetaObject, qt_meta_stringdata_cv__image_window,
qt_meta_data_cv__image_window, &staticMetaObjectExtraData }
};
#ifdef Q_NO_DATA_RELOCATION
const QMetaObject &cv::image_window::getStaticMetaObject() { return staticMetaObject; }
#endif //Q_NO_DATA_RELOCATION
const QMetaObject *cv::image_window::metaObject() const
{
return QObject::d_ptr->metaObject ? QObject::d_ptr->metaObject : &staticMetaObject;
}
void *cv::image_window::qt_metacast(const char *_clname)
{
if (!_clname) return 0;
if (!strcmp(_clname, qt_meta_stringdata_cv__image_window))
return static_cast<void*>(const_cast< image_window*>(this));
return QDialog::qt_metacast(_clname);
}
int cv::image_window::qt_metacall(QMetaObject::Call _c, int _id, void **_a)
{
_id = QDialog::qt_metacall(_c, _id, _a);
if (_id < 0)
return _id;
return _id;
}
QT_END_MOC_NAMESPACE
// MOC Generated code end /////////////////////////////////////////////
///////////////////////////////////////////////////////////////////////
// class global_image_application
global_image_application* global_image_application::_singleton = nullptr;
global_image_application::global_image_application(int &argc, char** argv) : QApplication(argc, argv), _last_key('\0') {
}
global_image_application::~global_image_application() {
this->destroy_all_windows();
}
global_image_application *global_image_application::singleton() {
if (!global_image_application::_singleton) {
int argc_simulation = 1;
char *argv_simulation[] = {" ", " "};
global_image_application::_singleton = new global_image_application(argc_simulation, argv_simulation);
}
return global_image_application::_singleton;
}
void global_image_application::force_quit() {
this->quit();
}
void global_image_application::assign_key(char key) {
this->_last_key = key;
for (auto w : this->_windows) {
w->close();
}
}
char global_image_application::get_last_key() const {
return this->_last_key;
}
void global_image_application::create_window(const std::string &name, const image_array &image) {
image_window *newWindow = new image_window;
newWindow->setWindowTitle(name.c_str());
newWindow->set_image(image);
newWindow->show();
this->_windows.push_back(newWindow);
}
void global_image_application::destroy_window(const std::string &name) {
int winId = -1;
for (int i = 0; i < this->_windows.size(); i++) {
if (this->_windows[i]->windowTitle() == name.c_str()) {
winId = i;
break;
}
}
if (winId != -1) {
this->_windows[winId]->close();
delete this->_windows[winId];
this->_windows.erase(this->_windows.begin() + winId);
} else {
std::cerr << ("Window by name " + name + " does not exist.\n");
}
}
void global_image_application::destroy_all_windows() {
for (auto window : this->_windows) {
window->close();
delete window;
}
this->_windows.clear();
}
void imshow(const std::string &name, const image_array &image) {
ASSERT(image.is_valid() && (image.channels() == 1 || image.channels() == 3 || image.channels() == 4));
if (image.depth() != 1) {
auto byte_copy = image.clone();
byte_copy.convert_to<byte>();
global_image_application::singleton()->create_window(name, byte_copy);
} else {
global_image_application::singleton()->create_window(name, image);
}
}
void imclose(const std::string &name) {
global_image_application::singleton()->destroy_window(name);
}
void imclose_all() {
global_image_application::singleton()->destroy_all_windows();
}
char wait_key() {
auto ga_inst = global_image_application::singleton();
ga_inst->exec();
return ga_inst->get_last_key();
}
}
#endif // CV_IGNORE_GUI
<|endoftext|> |
<commit_before>/*
Copyright © 2014 Jesse 'Jeaye' Wilkerson
See licensing at:
http://opensource.org/licenses/MIT
File: include/iterator/transmute_back_insert.hpp
Author: Jesse 'Jeaye' Wilkerson
*/
#pragma once
#include <iterator>
namespace jtl
{
namespace iterator
{
/* Transmutes output of T<E> to T2<E>.
*
* The transmute output iterator will allow for outputting
* into a container different from what the algorithm intended.
*
* Example:
* ```cpp
* std::stringstream ss{ "w0|w1|w2" };
* std::vector<std::vector<char>> out;
* std::copy(jtl::iterator::stream_delim<>{ ss, '|' },
* jtl::iterator::stream_delim<>{},
* jtl::iterator::transmute_back_inserter(out));
*
* // would normally expect vector<string>, but transmutation
* // allows for other [compatible] container types.
* // out == { { 'w', '0' }, { 'w', '1' }, { 'w', '2' } }
* ```
*/
template <typename C, typename It>
class transmute_back_insert
: public std::iterator<std::output_iterator_tag,
typename std::iterator_traits
<
decltype(std::begin(std::declval<C&>()))
>::value_type>
{
public:
using iterator = decltype(std::begin(std::declval<C&>()));
using value_type = typename std::iterator_traits<iterator>::value_type;
transmute_back_insert() = delete;
transmute_back_insert(C &c)
: container_{ c }
{ }
template <typename T>
transmute_back_insert& operator =(T &&c)
{
value_type v;
std::copy(std::begin(c), std::end(c), It(v));
container_.emplace_back(std::move(v));
return *this;
}
/* NOP */
transmute_back_insert& operator *() noexcept
{ return *this; }
transmute_back_insert& operator ++() noexcept
{ return *this; }
transmute_back_insert& operator ++(int) noexcept
{ return *this; }
private:
C &container_;
};
/* Creates a <jtl::iterator::transmute_back_insert> iterator. */
template <typename C>
transmute_back_insert<C, std::back_insert_iterator<
typename std::iterator_traits<
decltype(std::begin(std::declval<C&>()))>::value_type>>
transmute_back_inserter(C &c)
{ return { c }; }
}
}
<commit_msg>Add missing namespace.hpp include<commit_after>/*
Copyright © 2014 Jesse 'Jeaye' Wilkerson
See licensing at:
http://opensource.org/licenses/MIT
File: include/iterator/transmute_back_insert.hpp
Author: Jesse 'Jeaye' Wilkerson
*/
#pragma once
#include <iterator>
#include <jtl/namespace.hpp>
namespace jtl
{
namespace iterator
{
/* Transmutes output of T<E> to T2<E>.
*
* The transmute output iterator will allow for outputting
* into a container different from what the algorithm intended.
*
* Example:
* ```cpp
* std::stringstream ss{ "w0|w1|w2" };
* std::vector<std::vector<char>> out;
* std::copy(jtl::iterator::stream_delim<>{ ss, '|' },
* jtl::iterator::stream_delim<>{},
* jtl::iterator::transmute_back_inserter(out));
*
* // would normally expect vector<string>, but transmutation
* // allows for other [compatible] container types.
* // out == { { 'w', '0' }, { 'w', '1' }, { 'w', '2' } }
* ```
*/
template <typename C, typename It>
class transmute_back_insert
: public std::iterator<std::output_iterator_tag,
typename std::iterator_traits
<
decltype(std::begin(std::declval<C&>()))
>::value_type>
{
public:
using iterator = decltype(std::begin(std::declval<C&>()));
using value_type = typename std::iterator_traits<iterator>::value_type;
transmute_back_insert() = delete;
transmute_back_insert(C &c)
: container_{ c }
{ }
template <typename T>
transmute_back_insert& operator =(T &&c)
{
value_type v;
std::copy(std::begin(c), std::end(c), It(v));
container_.emplace_back(std::move(v));
return *this;
}
/* NOP */
transmute_back_insert& operator *() noexcept
{ return *this; }
transmute_back_insert& operator ++() noexcept
{ return *this; }
transmute_back_insert& operator ++(int) noexcept
{ return *this; }
private:
C &container_;
};
/* Creates a <jtl::iterator::transmute_back_insert> iterator. */
template <typename C>
transmute_back_insert<C, std::back_insert_iterator<
typename std::iterator_traits<
decltype(std::begin(std::declval<C&>()))>::value_type>>
transmute_back_inserter(C &c)
{ return { c }; }
}
}
<|endoftext|> |
<commit_before>// Copyright (c) 2009 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/gtk/browser_actions_toolbar_gtk.h"
#include <gtk/gtk.h>
#include <vector>
#include "app/gfx/canvas_paint.h"
#include "app/gfx/gtk_util.h"
#include "chrome/browser/browser.h"
#include "chrome/browser/extensions/extension_browser_event_router.h"
#include "chrome/browser/extensions/extensions_service.h"
#include "chrome/browser/extensions/image_loading_tracker.h"
#include "chrome/browser/gtk/extension_popup_gtk.h"
#include "chrome/browser/gtk/gtk_chrome_button.h"
#include "chrome/browser/gtk/gtk_theme_provider.h"
#include "chrome/browser/profile.h"
#include "chrome/browser/tab_contents/tab_contents.h"
#include "chrome/common/extensions/extension.h"
#include "chrome/common/extensions/extension_action.h"
#include "chrome/common/gtk_util.h"
#include "chrome/common/notification_details.h"
#include "chrome/common/notification_service.h"
#include "chrome/common/notification_source.h"
#include "chrome/common/notification_type.h"
// The size of each button on the toolbar.
static const int kButtonSize = 29;
// The padding between browser action buttons. Visually, the actual number of
// "empty" (non-drawing) pixels is this value + 2 when adjacent browser icons
// use their maximum allowed size.
static const int kBrowserActionButtonPadding = 3;
class BrowserActionButton : public NotificationObserver,
public ImageLoadingTracker::Observer {
public:
BrowserActionButton(BrowserActionsToolbarGtk* toolbar,
Extension* extension)
: toolbar_(toolbar),
extension_(extension),
button_(gtk_chrome_button_new()),
tracker_(NULL),
tab_specific_icon_(NULL),
default_icon_(NULL) {
DCHECK(extension_->browser_action());
gtk_widget_set_size_request(button_.get(), kButtonSize, kButtonSize);
UpdateState();
// The Browser Action API does not allow the default icon path to be
// changed at runtime, so we can load this now and cache it.
std::string path = extension_->browser_action()->default_icon_path();
if (!path.empty()) {
tracker_ = new ImageLoadingTracker(this, 1);
tracker_->PostLoadImageTask(extension_->GetResource(path),
gfx::Size(Extension::kBrowserActionIconMaxSize,
Extension::kBrowserActionIconMaxSize));
}
// We need to hook up extension popups here. http://crbug.com/23897
g_signal_connect(button_.get(), "clicked",
G_CALLBACK(OnButtonClicked), this);
g_signal_connect_after(button_.get(), "expose-event",
G_CALLBACK(OnExposeEvent), this);
registrar_.Add(this, NotificationType::EXTENSION_BROWSER_ACTION_UPDATED,
Source<ExtensionAction>(extension->browser_action()));
registrar_.Add(this, NotificationType::BROWSER_THEME_CHANGED,
NotificationService::AllSources());
OnThemeChanged();
}
~BrowserActionButton() {
if (tab_specific_icon_)
g_object_unref(tab_specific_icon_);
if (default_icon_)
g_object_unref(default_icon_);
button_.Destroy();
if (tracker_)
tracker_->StopTrackingImageLoad();
}
GtkWidget* widget() { return button_.get(); }
void Observe(NotificationType type,
const NotificationSource& source,
const NotificationDetails& details) {
if (type == NotificationType::EXTENSION_BROWSER_ACTION_UPDATED)
UpdateState();
else if (type == NotificationType::BROWSER_THEME_CHANGED)
OnThemeChanged();
else
NOTREACHED();
}
// ImageLoadingTracker::Observer implementation.
void OnImageLoaded(SkBitmap* image, size_t index) {
if (image)
default_icon_ = gfx::GdkPixbufFromSkBitmap(image);
UpdateState();
}
// Updates the button based on the latest state from the associated
// browser action.
void UpdateState() {
int tab_id = toolbar_->GetCurrentTabId();
if (tab_id < 0)
return;
std::string tooltip = extension_->browser_action()->GetTitle(tab_id);
if (tooltip.empty())
gtk_widget_set_has_tooltip(button_.get(), FALSE);
else
gtk_widget_set_tooltip_text(button_.get(), tooltip.c_str());
SkBitmap image = extension_->browser_action()->GetIcon(tab_id);
if (!image.isNull()) {
GdkPixbuf* previous_gdk_icon = tab_specific_icon_;
tab_specific_icon_ = gfx::GdkPixbufFromSkBitmap(&image);
SetImage(tab_specific_icon_);
if (previous_gdk_icon)
g_object_unref(previous_gdk_icon);
} else if (default_icon_) {
SetImage(default_icon_);
}
gtk_widget_queue_draw(button_.get());
}
private:
void SetImage(GdkPixbuf* image) {
gtk_button_set_image(GTK_BUTTON(button_.get()),
gtk_image_new_from_pixbuf(image));
}
void OnThemeChanged() {
gtk_chrome_button_set_use_gtk_rendering(GTK_CHROME_BUTTON(button_.get()),
GtkThemeProvider::GetFrom(
toolbar_->browser()->profile())->UseGtkTheme());
}
static void OnButtonClicked(GtkWidget* widget, BrowserActionButton* action) {
if (action->extension_->browser_action()->has_popup()) {
ExtensionPopupGtk::Show(
action->extension_->browser_action()->popup_url(),
action->toolbar_->browser(),
gtk_util::GetWidgetRectRelativeToToplevel(widget));
} else {
ExtensionBrowserEventRouter::GetInstance()->BrowserActionExecuted(
action->toolbar_->browser()->profile(), action->extension_->id(),
action->toolbar_->browser());
}
}
static gboolean OnExposeEvent(GtkWidget* widget,
GdkEventExpose* event,
BrowserActionButton* button) {
int tab_id = button->toolbar_->GetCurrentTabId();
if (tab_id < 0)
return FALSE;
ExtensionAction* action = button->extension_->browser_action();
if (action->GetBadgeText(tab_id).empty())
return FALSE;
gfx::CanvasPaint canvas(event, false);
gfx::Rect bounding_rect(widget->allocation);
action->PaintBadge(&canvas, bounding_rect, tab_id);
return FALSE;
}
// The toolbar containing this button.
BrowserActionsToolbarGtk* toolbar_;
// The extension that contains this browser action.
Extension* extension_;
// The gtk widget for this browser action.
OwnedWidgetGtk button_;
// Loads the button's icons for us on the file thread.
ImageLoadingTracker* tracker_;
// If we are displaying a tab-specific icon, it will be here.
GdkPixbuf* tab_specific_icon_;
// If the browser action has a default icon, it will be here.
GdkPixbuf* default_icon_;
NotificationRegistrar registrar_;
};
BrowserActionsToolbarGtk::BrowserActionsToolbarGtk(Browser* browser)
: browser_(browser),
profile_(browser->profile()),
hbox_(gtk_hbox_new(FALSE, kBrowserActionButtonPadding)) {
registrar_.Add(this, NotificationType::EXTENSION_LOADED,
Source<Profile>(profile_));
registrar_.Add(this, NotificationType::EXTENSION_UNLOADED,
Source<Profile>(profile_));
registrar_.Add(this, NotificationType::EXTENSION_UNLOADED_DISABLED,
Source<Profile>(profile_));
CreateAllButtons();
}
BrowserActionsToolbarGtk::~BrowserActionsToolbarGtk() {
hbox_.Destroy();
}
int BrowserActionsToolbarGtk::GetCurrentTabId() {
TabContents* selected_tab = browser_->GetSelectedTabContents();
if (!selected_tab)
return -1;
return selected_tab->controller().session_id().id();
}
void BrowserActionsToolbarGtk::Update() {
for (ExtensionButtonMap::iterator iter = extension_button_map_.begin();
iter != extension_button_map_.end(); ++iter) {
iter->second->UpdateState();
}
}
void BrowserActionsToolbarGtk::Observe(NotificationType type,
const NotificationSource& source,
const NotificationDetails& details) {
Extension* extension = Details<Extension>(details).ptr();
if (type == NotificationType::EXTENSION_LOADED) {
CreateButtonForExtension(extension);
} else if (type == NotificationType::EXTENSION_UNLOADED ||
type == NotificationType::EXTENSION_UNLOADED_DISABLED) {
RemoveButtonForExtension(extension);
} else {
NOTREACHED() << "Received unexpected notification";
}
}
void BrowserActionsToolbarGtk::CreateAllButtons() {
ExtensionsService* extension_service = profile_->GetExtensionsService();
if (!extension_service) // The |extension_service| can be NULL in Incognito.
return;
for (size_t i = 0; i < extension_service->extensions()->size(); ++i) {
Extension* extension = extension_service->GetExtensionById(
extension_service->extensions()->at(i)->id());
CreateButtonForExtension(extension);
}
}
void BrowserActionsToolbarGtk::CreateButtonForExtension(Extension* extension) {
// Only show extensions with browser actions.
if (!extension->browser_action())
return;
RemoveButtonForExtension(extension);
linked_ptr<BrowserActionButton> button(
new BrowserActionButton(this, extension));
gtk_box_pack_end(GTK_BOX(hbox_.get()), button->widget(), FALSE, FALSE, 0);
gtk_widget_show(button->widget());
extension_button_map_[extension->id()] = button;
UpdateVisibility();
}
void BrowserActionsToolbarGtk::RemoveButtonForExtension(Extension* extension) {
if (extension_button_map_.erase(extension->id()))
UpdateVisibility();
}
void BrowserActionsToolbarGtk::UpdateVisibility() {
if (button_count() == 0)
gtk_widget_hide(widget());
else
gtk_widget_show(widget());
}
<commit_msg>Fix memory stomping by ImageLoadingTracker in BrowserActionButton.<commit_after>// Copyright (c) 2009 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/gtk/browser_actions_toolbar_gtk.h"
#include <gtk/gtk.h>
#include <vector>
#include "app/gfx/canvas_paint.h"
#include "app/gfx/gtk_util.h"
#include "chrome/browser/browser.h"
#include "chrome/browser/extensions/extension_browser_event_router.h"
#include "chrome/browser/extensions/extensions_service.h"
#include "chrome/browser/extensions/image_loading_tracker.h"
#include "chrome/browser/gtk/extension_popup_gtk.h"
#include "chrome/browser/gtk/gtk_chrome_button.h"
#include "chrome/browser/gtk/gtk_theme_provider.h"
#include "chrome/browser/profile.h"
#include "chrome/browser/tab_contents/tab_contents.h"
#include "chrome/common/extensions/extension.h"
#include "chrome/common/extensions/extension_action.h"
#include "chrome/common/gtk_util.h"
#include "chrome/common/notification_details.h"
#include "chrome/common/notification_service.h"
#include "chrome/common/notification_source.h"
#include "chrome/common/notification_type.h"
// The size of each button on the toolbar.
static const int kButtonSize = 29;
// The padding between browser action buttons. Visually, the actual number of
// "empty" (non-drawing) pixels is this value + 2 when adjacent browser icons
// use their maximum allowed size.
static const int kBrowserActionButtonPadding = 3;
class BrowserActionButton : public NotificationObserver,
public ImageLoadingTracker::Observer {
public:
BrowserActionButton(BrowserActionsToolbarGtk* toolbar,
Extension* extension)
: toolbar_(toolbar),
extension_(extension),
button_(gtk_chrome_button_new()),
tracker_(NULL),
tab_specific_icon_(NULL),
default_icon_(NULL) {
DCHECK(extension_->browser_action());
gtk_widget_set_size_request(button_.get(), kButtonSize, kButtonSize);
UpdateState();
// The Browser Action API does not allow the default icon path to be
// changed at runtime, so we can load this now and cache it.
std::string path = extension_->browser_action()->default_icon_path();
if (!path.empty()) {
tracker_ = new ImageLoadingTracker(this, 1);
tracker_->PostLoadImageTask(extension_->GetResource(path),
gfx::Size(Extension::kBrowserActionIconMaxSize,
Extension::kBrowserActionIconMaxSize));
}
// We need to hook up extension popups here. http://crbug.com/23897
g_signal_connect(button_.get(), "clicked",
G_CALLBACK(OnButtonClicked), this);
g_signal_connect_after(button_.get(), "expose-event",
G_CALLBACK(OnExposeEvent), this);
registrar_.Add(this, NotificationType::EXTENSION_BROWSER_ACTION_UPDATED,
Source<ExtensionAction>(extension->browser_action()));
registrar_.Add(this, NotificationType::BROWSER_THEME_CHANGED,
NotificationService::AllSources());
OnThemeChanged();
}
~BrowserActionButton() {
if (tab_specific_icon_)
g_object_unref(tab_specific_icon_);
if (default_icon_)
g_object_unref(default_icon_);
button_.Destroy();
if (tracker_)
tracker_->StopTrackingImageLoad();
}
GtkWidget* widget() { return button_.get(); }
void Observe(NotificationType type,
const NotificationSource& source,
const NotificationDetails& details) {
if (type == NotificationType::EXTENSION_BROWSER_ACTION_UPDATED)
UpdateState();
else if (type == NotificationType::BROWSER_THEME_CHANGED)
OnThemeChanged();
else
NOTREACHED();
}
// ImageLoadingTracker::Observer implementation.
void OnImageLoaded(SkBitmap* image, size_t index) {
if (image)
default_icon_ = gfx::GdkPixbufFromSkBitmap(image);
tracker_ = NULL; // The tracker object will delete itself when we return.
UpdateState();
}
// Updates the button based on the latest state from the associated
// browser action.
void UpdateState() {
int tab_id = toolbar_->GetCurrentTabId();
if (tab_id < 0)
return;
std::string tooltip = extension_->browser_action()->GetTitle(tab_id);
if (tooltip.empty())
gtk_widget_set_has_tooltip(button_.get(), FALSE);
else
gtk_widget_set_tooltip_text(button_.get(), tooltip.c_str());
SkBitmap image = extension_->browser_action()->GetIcon(tab_id);
if (!image.isNull()) {
GdkPixbuf* previous_gdk_icon = tab_specific_icon_;
tab_specific_icon_ = gfx::GdkPixbufFromSkBitmap(&image);
SetImage(tab_specific_icon_);
if (previous_gdk_icon)
g_object_unref(previous_gdk_icon);
} else if (default_icon_) {
SetImage(default_icon_);
}
gtk_widget_queue_draw(button_.get());
}
private:
void SetImage(GdkPixbuf* image) {
gtk_button_set_image(GTK_BUTTON(button_.get()),
gtk_image_new_from_pixbuf(image));
}
void OnThemeChanged() {
gtk_chrome_button_set_use_gtk_rendering(GTK_CHROME_BUTTON(button_.get()),
GtkThemeProvider::GetFrom(
toolbar_->browser()->profile())->UseGtkTheme());
}
static void OnButtonClicked(GtkWidget* widget, BrowserActionButton* action) {
if (action->extension_->browser_action()->has_popup()) {
ExtensionPopupGtk::Show(
action->extension_->browser_action()->popup_url(),
action->toolbar_->browser(),
gtk_util::GetWidgetRectRelativeToToplevel(widget));
} else {
ExtensionBrowserEventRouter::GetInstance()->BrowserActionExecuted(
action->toolbar_->browser()->profile(), action->extension_->id(),
action->toolbar_->browser());
}
}
static gboolean OnExposeEvent(GtkWidget* widget,
GdkEventExpose* event,
BrowserActionButton* button) {
int tab_id = button->toolbar_->GetCurrentTabId();
if (tab_id < 0)
return FALSE;
ExtensionAction* action = button->extension_->browser_action();
if (action->GetBadgeText(tab_id).empty())
return FALSE;
gfx::CanvasPaint canvas(event, false);
gfx::Rect bounding_rect(widget->allocation);
action->PaintBadge(&canvas, bounding_rect, tab_id);
return FALSE;
}
// The toolbar containing this button.
BrowserActionsToolbarGtk* toolbar_;
// The extension that contains this browser action.
Extension* extension_;
// The gtk widget for this browser action.
OwnedWidgetGtk button_;
// Loads the button's icons for us on the file thread.
ImageLoadingTracker* tracker_;
// If we are displaying a tab-specific icon, it will be here.
GdkPixbuf* tab_specific_icon_;
// If the browser action has a default icon, it will be here.
GdkPixbuf* default_icon_;
NotificationRegistrar registrar_;
};
BrowserActionsToolbarGtk::BrowserActionsToolbarGtk(Browser* browser)
: browser_(browser),
profile_(browser->profile()),
hbox_(gtk_hbox_new(FALSE, kBrowserActionButtonPadding)) {
registrar_.Add(this, NotificationType::EXTENSION_LOADED,
Source<Profile>(profile_));
registrar_.Add(this, NotificationType::EXTENSION_UNLOADED,
Source<Profile>(profile_));
registrar_.Add(this, NotificationType::EXTENSION_UNLOADED_DISABLED,
Source<Profile>(profile_));
CreateAllButtons();
}
BrowserActionsToolbarGtk::~BrowserActionsToolbarGtk() {
hbox_.Destroy();
}
int BrowserActionsToolbarGtk::GetCurrentTabId() {
TabContents* selected_tab = browser_->GetSelectedTabContents();
if (!selected_tab)
return -1;
return selected_tab->controller().session_id().id();
}
void BrowserActionsToolbarGtk::Update() {
for (ExtensionButtonMap::iterator iter = extension_button_map_.begin();
iter != extension_button_map_.end(); ++iter) {
iter->second->UpdateState();
}
}
void BrowserActionsToolbarGtk::Observe(NotificationType type,
const NotificationSource& source,
const NotificationDetails& details) {
Extension* extension = Details<Extension>(details).ptr();
if (type == NotificationType::EXTENSION_LOADED) {
CreateButtonForExtension(extension);
} else if (type == NotificationType::EXTENSION_UNLOADED ||
type == NotificationType::EXTENSION_UNLOADED_DISABLED) {
RemoveButtonForExtension(extension);
} else {
NOTREACHED() << "Received unexpected notification";
}
}
void BrowserActionsToolbarGtk::CreateAllButtons() {
ExtensionsService* extension_service = profile_->GetExtensionsService();
if (!extension_service) // The |extension_service| can be NULL in Incognito.
return;
for (size_t i = 0; i < extension_service->extensions()->size(); ++i) {
Extension* extension = extension_service->GetExtensionById(
extension_service->extensions()->at(i)->id());
CreateButtonForExtension(extension);
}
}
void BrowserActionsToolbarGtk::CreateButtonForExtension(Extension* extension) {
// Only show extensions with browser actions.
if (!extension->browser_action())
return;
RemoveButtonForExtension(extension);
linked_ptr<BrowserActionButton> button(
new BrowserActionButton(this, extension));
gtk_box_pack_end(GTK_BOX(hbox_.get()), button->widget(), FALSE, FALSE, 0);
gtk_widget_show(button->widget());
extension_button_map_[extension->id()] = button;
UpdateVisibility();
}
void BrowserActionsToolbarGtk::RemoveButtonForExtension(Extension* extension) {
if (extension_button_map_.erase(extension->id()))
UpdateVisibility();
}
void BrowserActionsToolbarGtk::UpdateVisibility() {
if (button_count() == 0)
gtk_widget_hide(widget());
else
gtk_widget_show(widget());
}
<|endoftext|> |
<commit_before>/** @file
*
* @ingroup audioGraphLibrary
*
* @brief Represents one connection between two AudioGraph objects
*
* @details TTAudioGraphSource is an upstream connection from a #TTAudioGraphInlet of a #TTAudioGraphObject to a "TTAudioGraphOutlet of an upstream #TTAudioGraphObject.
* The relationship of a source to other parts of the audio graph hierarchy is as follows:
*
* - A graph may have many objects.
* - An object may have many inlets.
* - An inlet may have many signals (sources) connected.
* - A signal may have many channels.
*
* @authors Timothy Place, Trond Lossius
*
* @copyright Copyright © 2010, Timothy Place @n
* This code is licensed under the terms of the "New BSD License" @n
* http://creativecommons.org/licenses/BSD/
*/
#include "TTAudioGraphObject.h"
#include "TTAudioGraphInlet.h"
#include "TTCallback.h"
// C Callback from any AudioGraph Source objects we are observing
void TTAudioGraphSourceObserverCallback(TTAudioGraphSourcePtr self, TTValue& arg)
{
// at the moment we only receive one callback, which is for the object being deleted
self->mSourceObject = NULL;
self->mOutletNumber = 0;
if (self->mOwner)
self->mOwner->drop(*self);
}
// Implementation for AudioGraph Source class
TTAudioGraphSource::TTAudioGraphSource() :
mSourceObject(NULL),
mOutletNumber(0),
mCallbackHandler("callback"),
mOwner(NULL)
{
create();
}
TTAudioGraphSource::TTAudioGraphSource(const TTAudioGraphSource& original) :
mSourceObject(NULL),
mOutletNumber(0),
mCallbackHandler("callback"),
mOwner(NULL)
{
create();
mOwner = original.mOwner;
// NOTE: See notes below in TTAudioGraphInlet copy constructor...
// NOTE: When vector of sources is resized, it is possible for an object to be created and immediately copied -- prior to a 'connect' method call
// NOTE: Are we ever called after connecting? If so, then we need to set up the connection...
if (original.mSourceObject)
connect(original.mSourceObject, original.mOutletNumber);
}
TTAudioGraphSource::~TTAudioGraphSource()
{
if (mSourceObject)
mSourceObject->unregisterObserverForNotifications(mCallbackHandler);
mSourceObject = NULL;
mOutletNumber = 0;
}
void TTAudioGraphSource::create()
{
mCallbackHandler.set("function", TTPtr(&TTAudioGraphSourceObserverCallback));
mCallbackHandler.set("baton", TTPtr(this));
}
void TTAudioGraphSource::setOwner(TTAudioGraphInlet* theOwningInlet)
{
mOwner = theOwningInlet;
}
TTAudioGraphSource& TTAudioGraphSource::operator=(const TTAudioGraphSource& original)
{
mSourceObject = NULL;
mOutletNumber = 0;
mOwner = NULL;
create();
mOwner = original.mOwner;
if (original.mSourceObject && original.mSourceObject->valid)
connect(original.mSourceObject, original.mOutletNumber);
return *this;
}
void TTAudioGraphSource::connect(TTAudioGraphObjectBasePtr anObject, TTUInt16 fromOutletNumber)
{
mSourceObject = anObject;
mOutletNumber = fromOutletNumber;
// dynamically add a message to the callback object so that it can handle the 'objectFreeing' notification
mCallbackHandler.instance()->registerMessage(TT("objectFreeing"), (TTMethod)&TTCallback::notify, kTTMessagePassValue);
// tell the source that is passed in that we want to watch it
mSourceObject->registerObserverForNotifications(mCallbackHandler);
}
<commit_msg>The TTCallback object already provides a notification attribute setter to dynamically change which notification to observe.<commit_after>/** @file
*
* @ingroup audioGraphLibrary
*
* @brief Represents one connection between two AudioGraph objects
*
* @details TTAudioGraphSource is an upstream connection from a #TTAudioGraphInlet of a #TTAudioGraphObject to a "TTAudioGraphOutlet of an upstream #TTAudioGraphObject.
* The relationship of a source to other parts of the audio graph hierarchy is as follows:
*
* - A graph may have many objects.
* - An object may have many inlets.
* - An inlet may have many signals (sources) connected.
* - A signal may have many channels.
*
* @authors Timothy Place, Trond Lossius
*
* @copyright Copyright © 2010, Timothy Place @n
* This code is licensed under the terms of the "New BSD License" @n
* http://creativecommons.org/licenses/BSD/
*/
#include "TTAudioGraphObject.h"
#include "TTAudioGraphInlet.h"
#include "TTCallback.h"
// C Callback from any AudioGraph Source objects we are observing
void TTAudioGraphSourceObserverCallback(TTAudioGraphSourcePtr self, TTValue& arg)
{
// at the moment we only receive one callback, which is for the object being deleted
self->mSourceObject = NULL;
self->mOutletNumber = 0;
if (self->mOwner)
self->mOwner->drop(*self);
}
// Implementation for AudioGraph Source class
TTAudioGraphSource::TTAudioGraphSource() :
mSourceObject(NULL),
mOutletNumber(0),
mCallbackHandler("callback"),
mOwner(NULL)
{
create();
}
TTAudioGraphSource::TTAudioGraphSource(const TTAudioGraphSource& original) :
mSourceObject(NULL),
mOutletNumber(0),
mCallbackHandler("callback"),
mOwner(NULL)
{
create();
mOwner = original.mOwner;
// NOTE: See notes below in TTAudioGraphInlet copy constructor...
// NOTE: When vector of sources is resized, it is possible for an object to be created and immediately copied -- prior to a 'connect' method call
// NOTE: Are we ever called after connecting? If so, then we need to set up the connection...
if (original.mSourceObject)
connect(original.mSourceObject, original.mOutletNumber);
}
TTAudioGraphSource::~TTAudioGraphSource()
{
if (mSourceObject)
mSourceObject->unregisterObserverForNotifications(mCallbackHandler);
mSourceObject = NULL;
mOutletNumber = 0;
}
void TTAudioGraphSource::create()
{
mCallbackHandler.set("function", TTPtr(&TTAudioGraphSourceObserverCallback));
mCallbackHandler.set("baton", TTPtr(this));
mCallbackHandler.set("notification", TTSymbol("objectFreeing"));
}
void TTAudioGraphSource::setOwner(TTAudioGraphInlet* theOwningInlet)
{
mOwner = theOwningInlet;
}
TTAudioGraphSource& TTAudioGraphSource::operator=(const TTAudioGraphSource& original)
{
mSourceObject = NULL;
mOutletNumber = 0;
mOwner = NULL;
create();
mOwner = original.mOwner;
if (original.mSourceObject && original.mSourceObject->valid)
connect(original.mSourceObject, original.mOutletNumber);
return *this;
}
void TTAudioGraphSource::connect(TTAudioGraphObjectBasePtr anObject, TTUInt16 fromOutletNumber)
{
mSourceObject = anObject;
mOutletNumber = fromOutletNumber;
// tell the source that is passed in that we want to watch it
mSourceObject->registerObserverForNotifications(mCallbackHandler);
}
<|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/ui/webui/chromeos/login/oobe_ui.h"
#include <string>
#include "base/command_line.h"
#include "base/logging.h"
#include "base/memory/ref_counted_memory.h"
#include "base/values.h"
#include "chrome/browser/browser_about_handler.h"
#include "chrome/browser/chromeos/login/enrollment/enterprise_enrollment_screen_actor.h"
#include "chrome/browser/chromeos/login/wizard_controller.h"
#include "chrome/browser/profiles/profile.h"
#include "chrome/browser/ui/webui/chrome_url_data_manager.h"
#include "chrome/browser/ui/webui/chromeos/login/base_screen_handler.h"
#include "chrome/browser/ui/webui/chromeos/login/core_oobe_handler.h"
#include "chrome/browser/ui/webui/chromeos/login/enterprise_enrollment_screen_handler.h"
#include "chrome/browser/ui/webui/chromeos/login/enterprise_oauth_enrollment_screen_handler.h"
#include "chrome/browser/ui/webui/chromeos/login/eula_screen_handler.h"
#include "chrome/browser/ui/webui/chromeos/login/network_dropdown_handler.h"
#include "chrome/browser/ui/webui/chromeos/login/network_screen_handler.h"
#include "chrome/browser/ui/webui/chromeos/login/signin_screen_handler.h"
#include "chrome/browser/ui/webui/chromeos/login/update_screen_handler.h"
#include "chrome/browser/ui/webui/chromeos/login/user_image_screen_handler.h"
#include "chrome/browser/ui/webui/options/chromeos/user_image_source.h"
#include "chrome/browser/ui/webui/theme_source.h"
#include "chrome/common/chrome_switches.h"
#include "chrome/common/jstemplate_builder.h"
#include "chrome/common/url_constants.h"
#include "content/browser/tab_contents/tab_contents.h"
#include "grit/browser_resources.h"
#include "ui/base/resource/resource_bundle.h"
namespace {
// Path for a stripped down login page that does not have OOBE elements.
const char kLoginPath[] = "login";
// Path for the enterprise enrollment gaia page hosting.
const char kEnterpriseEnrollmentGaiaLoginPath[] = "gaialogin";
} // namespace
namespace chromeos {
class OobeUIHTMLSource : public ChromeURLDataManager::DataSource {
public:
explicit OobeUIHTMLSource(DictionaryValue* localized_strings);
// Called when the network layer has requested a resource underneath
// the path we registered.
virtual void StartDataRequest(const std::string& path,
bool is_incognito,
int request_id);
virtual std::string GetMimeType(const std::string&) const {
return "text/html";
}
private:
virtual ~OobeUIHTMLSource() {}
scoped_ptr<DictionaryValue> localized_strings_;
DISALLOW_COPY_AND_ASSIGN(OobeUIHTMLSource);
};
// OobeUIHTMLSource -------------------------------------------------------
OobeUIHTMLSource::OobeUIHTMLSource(DictionaryValue* localized_strings)
: DataSource(chrome::kChromeUIOobeHost, MessageLoop::current()),
localized_strings_(localized_strings) {
}
void OobeUIHTMLSource::StartDataRequest(const std::string& path,
bool is_incognito,
int request_id) {
std::string response;
if (path.empty()) {
static const base::StringPiece html(
ResourceBundle::GetSharedInstance().GetRawDataResource(IDR_OOBE_HTML));
response = jstemplate_builder::GetI18nTemplateHtml(
html, localized_strings_.get());
} else if (path == kLoginPath) {
static const base::StringPiece html(
ResourceBundle::GetSharedInstance().GetRawDataResource(IDR_LOGIN_HTML));
response = jstemplate_builder::GetI18nTemplateHtml(
html, localized_strings_.get());
} else if (path == kEnterpriseEnrollmentGaiaLoginPath) {
static const base::StringPiece html(
ResourceBundle::GetSharedInstance().GetRawDataResource(
IDR_GAIA_LOGIN_HTML));
response = jstemplate_builder::GetI18nTemplateHtml(
html, localized_strings_.get());
}
SendResponse(request_id, base::RefCountedString::TakeString(&response));
}
// OobeUI ----------------------------------------------------------------------
OobeUI::OobeUI(TabContents* contents)
: ChromeWebUI(contents),
update_screen_actor_(NULL),
network_screen_actor_(NULL),
eula_screen_actor_(NULL),
signin_screen_handler_(NULL),
user_image_screen_actor_(NULL) {
core_handler_ = new CoreOobeHandler(this);
AddScreenHandler(core_handler_);
AddScreenHandler(new NetworkDropdownHandler);
NetworkScreenHandler* network_screen_handler = new NetworkScreenHandler();
network_screen_actor_ = network_screen_handler;
AddScreenHandler(network_screen_handler);
EulaScreenHandler* eula_screen_handler = new EulaScreenHandler();
eula_screen_actor_ = eula_screen_handler;
AddScreenHandler(eula_screen_handler);
UpdateScreenHandler* update_screen_handler = new UpdateScreenHandler();
update_screen_actor_ = update_screen_handler;
AddScreenHandler(update_screen_handler);
if (CommandLine::ForCurrentProcess()->HasSwitch(switches::kWebUILogin)) {
EnterpriseOAuthEnrollmentScreenHandler*
enterprise_oauth_enrollment_screen_handler =
new EnterpriseOAuthEnrollmentScreenHandler;
enterprise_enrollment_screen_actor_ =
enterprise_oauth_enrollment_screen_handler;
AddScreenHandler(enterprise_oauth_enrollment_screen_handler);
} else {
EnterpriseEnrollmentScreenHandler* enterprise_enrollment_screen_handler =
new EnterpriseEnrollmentScreenHandler;
enterprise_enrollment_screen_actor_ = enterprise_enrollment_screen_handler;
AddScreenHandler(enterprise_enrollment_screen_handler);
}
UserImageScreenHandler* user_image_screen_handler =
new UserImageScreenHandler();
user_image_screen_actor_ = user_image_screen_handler;
AddScreenHandler(user_image_screen_handler);
signin_screen_handler_ = new SigninScreenHandler;
AddScreenHandler(signin_screen_handler_);
DictionaryValue* localized_strings = new DictionaryValue();
GetLocalizedStrings(localized_strings);
Profile* profile = Profile::FromBrowserContext(contents->browser_context());
// Set up the chrome://theme/ source, for Chrome logo.
ThemeSource* theme = new ThemeSource(profile);
profile->GetChromeURLDataManager()->AddDataSource(theme);
// Set up the chrome://terms/ data source, for EULA content.
InitializeAboutDataSource(chrome::kChromeUITermsHost, profile);
// Set up the chrome://oobe/ source.
OobeUIHTMLSource* html_source = new OobeUIHTMLSource(localized_strings);
profile->GetChromeURLDataManager()->AddDataSource(html_source);
// Set up the chrome://userimage/ source.
UserImageSource* user_image_source = new UserImageSource();
profile->GetChromeURLDataManager()->AddDataSource(user_image_source);
}
void OobeUI::ShowScreen(WizardScreen* screen) {
screen->Show();
}
void OobeUI::HideScreen(WizardScreen* screen) {
screen->Hide();
}
UpdateScreenActor* OobeUI::GetUpdateScreenActor() {
return update_screen_actor_;
}
NetworkScreenActor* OobeUI::GetNetworkScreenActor() {
return network_screen_actor_;
}
EulaScreenActor* OobeUI::GetEulaScreenActor() {
return eula_screen_actor_;
}
EnterpriseEnrollmentScreenActor* OobeUI::
GetEnterpriseEnrollmentScreenActor() {
return enterprise_enrollment_screen_actor_;
}
UserImageScreenActor* OobeUI::GetUserImageScreenActor() {
return user_image_screen_actor_;
}
ViewScreenDelegate* OobeUI::GetRegistrationScreenActor() {
NOTIMPLEMENTED();
return NULL;
}
ViewScreenDelegate* OobeUI::GetHTMLPageScreenActor() {
// WebUI implementation of the LoginDisplayHost opens HTML page directly,
// without opening OOBE page.
NOTREACHED();
return NULL;
}
void OobeUI::GetLocalizedStrings(base::DictionaryValue* localized_strings) {
// Note, handlers_[0] is a GenericHandler used by the WebUI.
for (size_t i = 1; i < handlers_.size(); ++i) {
static_cast<BaseScreenHandler*>(handlers_[i])->
GetLocalizedStrings(localized_strings);
}
ChromeURLDataManager::DataSource::SetFontAndTextDirection(localized_strings);
}
void OobeUI::AddScreenHandler(BaseScreenHandler* handler) {
AddMessageHandler(handler->Attach(this));
}
void OobeUI::InitializeHandlers() {
// Note, handlers_[0] is a GenericHandler used by the WebUI.
for (size_t i = 1; i < handlers_.size(); ++i) {
static_cast<BaseScreenHandler*>(handlers_[i])->InitializeBase();
}
}
void OobeUI::ShowOobeUI(bool show) {
core_handler_->ShowOobeUI(show);
}
void OobeUI::ShowSigninScreen() {
signin_screen_handler_->Show(core_handler_->show_oobe_ui());
}
} // namespace chromeos
<commit_msg>[cros] Restrict chrome://oobe to non-user session only. Guest session is also considered a "user session".<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/ui/webui/chromeos/login/oobe_ui.h"
#include <string>
#include "base/command_line.h"
#include "base/logging.h"
#include "base/memory/ref_counted_memory.h"
#include "base/values.h"
#include "chrome/browser/browser_about_handler.h"
#include "chrome/browser/chromeos/login/enrollment/enterprise_enrollment_screen_actor.h"
#include "chrome/browser/chromeos/login/user_manager.h"
#include "chrome/browser/chromeos/login/wizard_controller.h"
#include "chrome/browser/profiles/profile.h"
#include "chrome/browser/ui/webui/chrome_url_data_manager.h"
#include "chrome/browser/ui/webui/chromeos/login/base_screen_handler.h"
#include "chrome/browser/ui/webui/chromeos/login/core_oobe_handler.h"
#include "chrome/browser/ui/webui/chromeos/login/enterprise_enrollment_screen_handler.h"
#include "chrome/browser/ui/webui/chromeos/login/enterprise_oauth_enrollment_screen_handler.h"
#include "chrome/browser/ui/webui/chromeos/login/eula_screen_handler.h"
#include "chrome/browser/ui/webui/chromeos/login/network_dropdown_handler.h"
#include "chrome/browser/ui/webui/chromeos/login/network_screen_handler.h"
#include "chrome/browser/ui/webui/chromeos/login/signin_screen_handler.h"
#include "chrome/browser/ui/webui/chromeos/login/update_screen_handler.h"
#include "chrome/browser/ui/webui/chromeos/login/user_image_screen_handler.h"
#include "chrome/browser/ui/webui/options/chromeos/user_image_source.h"
#include "chrome/browser/ui/webui/theme_source.h"
#include "chrome/common/chrome_switches.h"
#include "chrome/common/jstemplate_builder.h"
#include "chrome/common/url_constants.h"
#include "content/browser/tab_contents/tab_contents.h"
#include "grit/browser_resources.h"
#include "ui/base/resource/resource_bundle.h"
namespace {
// Path for a stripped down login page that does not have OOBE elements.
const char kLoginPath[] = "login";
// Path for the enterprise enrollment gaia page hosting.
const char kEnterpriseEnrollmentGaiaLoginPath[] = "gaialogin";
} // namespace
namespace chromeos {
class OobeUIHTMLSource : public ChromeURLDataManager::DataSource {
public:
explicit OobeUIHTMLSource(DictionaryValue* localized_strings);
// Called when the network layer has requested a resource underneath
// the path we registered.
virtual void StartDataRequest(const std::string& path,
bool is_incognito,
int request_id);
virtual std::string GetMimeType(const std::string&) const {
return "text/html";
}
private:
virtual ~OobeUIHTMLSource() {}
std::string GetDataResource(int resource_id) const;
scoped_ptr<DictionaryValue> localized_strings_;
DISALLOW_COPY_AND_ASSIGN(OobeUIHTMLSource);
};
// OobeUIHTMLSource -------------------------------------------------------
OobeUIHTMLSource::OobeUIHTMLSource(DictionaryValue* localized_strings)
: DataSource(chrome::kChromeUIOobeHost, MessageLoop::current()),
localized_strings_(localized_strings) {
}
void OobeUIHTMLSource::StartDataRequest(const std::string& path,
bool is_incognito,
int request_id) {
if (UserManager::Get()->user_is_logged_in()) {
scoped_refptr<RefCountedBytes> empty_bytes(new RefCountedBytes());
SendResponse(request_id, empty_bytes);
return;
}
std::string response;
if (path.empty())
response = GetDataResource(IDR_OOBE_HTML);
else if (path == kLoginPath)
response = GetDataResource(IDR_LOGIN_HTML);
else if (path == kEnterpriseEnrollmentGaiaLoginPath)
response = GetDataResource(IDR_GAIA_LOGIN_HTML);
SendResponse(request_id, base::RefCountedString::TakeString(&response));
}
std::string OobeUIHTMLSource::GetDataResource(int resource_id) const {
const base::StringPiece html(
ResourceBundle::GetSharedInstance().GetRawDataResource(resource_id));
return jstemplate_builder::GetI18nTemplateHtml(html,
localized_strings_.get());
}
// OobeUI ----------------------------------------------------------------------
OobeUI::OobeUI(TabContents* contents)
: ChromeWebUI(contents),
update_screen_actor_(NULL),
network_screen_actor_(NULL),
eula_screen_actor_(NULL),
signin_screen_handler_(NULL),
user_image_screen_actor_(NULL) {
core_handler_ = new CoreOobeHandler(this);
AddScreenHandler(core_handler_);
AddScreenHandler(new NetworkDropdownHandler);
NetworkScreenHandler* network_screen_handler = new NetworkScreenHandler();
network_screen_actor_ = network_screen_handler;
AddScreenHandler(network_screen_handler);
EulaScreenHandler* eula_screen_handler = new EulaScreenHandler();
eula_screen_actor_ = eula_screen_handler;
AddScreenHandler(eula_screen_handler);
UpdateScreenHandler* update_screen_handler = new UpdateScreenHandler();
update_screen_actor_ = update_screen_handler;
AddScreenHandler(update_screen_handler);
if (CommandLine::ForCurrentProcess()->HasSwitch(switches::kWebUILogin)) {
EnterpriseOAuthEnrollmentScreenHandler*
enterprise_oauth_enrollment_screen_handler =
new EnterpriseOAuthEnrollmentScreenHandler;
enterprise_enrollment_screen_actor_ =
enterprise_oauth_enrollment_screen_handler;
AddScreenHandler(enterprise_oauth_enrollment_screen_handler);
} else {
EnterpriseEnrollmentScreenHandler* enterprise_enrollment_screen_handler =
new EnterpriseEnrollmentScreenHandler;
enterprise_enrollment_screen_actor_ = enterprise_enrollment_screen_handler;
AddScreenHandler(enterprise_enrollment_screen_handler);
}
UserImageScreenHandler* user_image_screen_handler =
new UserImageScreenHandler();
user_image_screen_actor_ = user_image_screen_handler;
AddScreenHandler(user_image_screen_handler);
signin_screen_handler_ = new SigninScreenHandler;
AddScreenHandler(signin_screen_handler_);
DictionaryValue* localized_strings = new DictionaryValue();
GetLocalizedStrings(localized_strings);
Profile* profile = Profile::FromBrowserContext(contents->browser_context());
// Set up the chrome://theme/ source, for Chrome logo.
ThemeSource* theme = new ThemeSource(profile);
profile->GetChromeURLDataManager()->AddDataSource(theme);
// Set up the chrome://terms/ data source, for EULA content.
InitializeAboutDataSource(chrome::kChromeUITermsHost, profile);
// Set up the chrome://oobe/ source.
OobeUIHTMLSource* html_source = new OobeUIHTMLSource(localized_strings);
profile->GetChromeURLDataManager()->AddDataSource(html_source);
// Set up the chrome://userimage/ source.
UserImageSource* user_image_source = new UserImageSource();
profile->GetChromeURLDataManager()->AddDataSource(user_image_source);
}
void OobeUI::ShowScreen(WizardScreen* screen) {
screen->Show();
}
void OobeUI::HideScreen(WizardScreen* screen) {
screen->Hide();
}
UpdateScreenActor* OobeUI::GetUpdateScreenActor() {
return update_screen_actor_;
}
NetworkScreenActor* OobeUI::GetNetworkScreenActor() {
return network_screen_actor_;
}
EulaScreenActor* OobeUI::GetEulaScreenActor() {
return eula_screen_actor_;
}
EnterpriseEnrollmentScreenActor* OobeUI::
GetEnterpriseEnrollmentScreenActor() {
return enterprise_enrollment_screen_actor_;
}
UserImageScreenActor* OobeUI::GetUserImageScreenActor() {
return user_image_screen_actor_;
}
ViewScreenDelegate* OobeUI::GetRegistrationScreenActor() {
NOTIMPLEMENTED();
return NULL;
}
ViewScreenDelegate* OobeUI::GetHTMLPageScreenActor() {
// WebUI implementation of the LoginDisplayHost opens HTML page directly,
// without opening OOBE page.
NOTREACHED();
return NULL;
}
void OobeUI::GetLocalizedStrings(base::DictionaryValue* localized_strings) {
// Note, handlers_[0] is a GenericHandler used by the WebUI.
for (size_t i = 1; i < handlers_.size(); ++i) {
static_cast<BaseScreenHandler*>(handlers_[i])->
GetLocalizedStrings(localized_strings);
}
ChromeURLDataManager::DataSource::SetFontAndTextDirection(localized_strings);
}
void OobeUI::AddScreenHandler(BaseScreenHandler* handler) {
AddMessageHandler(handler->Attach(this));
}
void OobeUI::InitializeHandlers() {
// Note, handlers_[0] is a GenericHandler used by the WebUI.
for (size_t i = 1; i < handlers_.size(); ++i) {
static_cast<BaseScreenHandler*>(handlers_[i])->InitializeBase();
}
}
void OobeUI::ShowOobeUI(bool show) {
core_handler_->ShowOobeUI(show);
}
void OobeUI::ShowSigninScreen() {
signin_screen_handler_->Show(core_handler_->show_oobe_ui());
}
} // namespace chromeos
<|endoftext|> |
<commit_before>#include <string>
#include <iostream>
#include <cstdio>
#include <windows.h>
//#include <math.h>
#include "serial/serial.h"
#include <thread>
#define FLOATSIZE 4
#define MESSAGESIZE FLOATSIZE+1
#define MESSAGESIZE_WRITE MESSAGESIZE
#define LOOPRATE 100
#define LOOPCOUNTS 1
using std::string;
using std::exception;
using std::cout;
using std::cerr;
using std::endl;
using std::vector;
typedef union {
float floatingPoint;
uint8_t binary[FLOATSIZE];
} binaryFloat;
//void my_sleep(unsigned long milliseconds) {
// Sleep(milliseconds); // 100 ms
//}
void enumerate_ports()
{
vector<serial::PortInfo> devices_found = serial::list_ports();
vector<serial::PortInfo>::iterator iter = devices_found.begin();
while (iter != devices_found.end())
{
serial::PortInfo device = *iter++;
printf("(%s, %s, %s)\n", device.port.c_str(), device.description.c_str(),
device.hardware_id.c_str());
}
}
void print_usage()
{
cerr << "Usage: test_serial {-e|<serial port address>} ";
cerr << "<baudrate> [test string]" << endl;
}
binaryFloat sentNumber;
binaryFloat receivedNumber;
uint8_t incomingData[1030];
uint8_t endMessage = 0x0A;
void serial_write_trigger(bool* readyToWrite)
{
std::chrono::milliseconds duraWrite(LOOPRATE);
while (true)
{
*readyToWrite = true;
std::this_thread::sleep_for(duraWrite);
}
}
//void serial_read_thread(serial::Serial* mySerialPtr)
//{
// std::chrono::milliseconds dura(1000);
//
// std::this_thread::sleep_for(dura);
// size_t whatIsAvailable;
// size_t bytes_read;
// unsigned int readCount;
// readCount = 0;
//
// while(true){
// cout << "Bytes Available: " << mySerialPtr->available() << endl;
//
// if (mySerialPtr->waitReadable())
// {
// string result = mySerialPtr->read(1);
// }
// std::this_thread::sleep_for(dura);
//
// }
//}
int main()
{
string port = "COM5";
unsigned long baud = 19200;
// port, baudrate, timeout in milliseconds
serial::Serial my_serial(port, baud, serial::Timeout::simpleTimeout(1000));
my_serial.setTimeout(serial::Timeout::max(), 1, 0, 1, 0);
my_serial.flush();
Sleep(100);
cout << "Is the serial port open?";
if (my_serial.isOpen())
cout << " Yes." << endl;
else
cout << " No." << endl;
// don't forget to pre-allocate memory
//string test_string = "Suppiluluima: the king of the Hittites";
//char newLine[] = "\n";
// uint8_t endMessage = 0;
// endMessage = (uint8_t) newLine;
// cout << endMessage;
//std::thread threadObj(serial_read_thread, &my_serial);
//if (threadObj.joinable())
//{
// //threadObj.join();
// //std::cout << "Joined Thread " << std::endl;
// std::cout << "Detaching Thread " << std::endl;
// threadObj.detach();
//}
bool readyToWrite;
std::thread threadWrite(serial_write_trigger, &readyToWrite);
if (threadWrite.joinable())
{
std::cout << "Detaching Thread " << std::endl;
threadWrite.detach();
}
// Test the timeout, there should be 1 second between prints
//cout << "Timeout == 1000ms, asking for exactly what was written." << endl;
//cout << "Timeout == 10ms, asking for exactly what was written." << endl;
std::chrono::milliseconds duraWrite(LOOPRATE);
//my_serial.flushOutput();
uint8_t message[MESSAGESIZE_WRITE];
message[MESSAGESIZE_WRITE-1] = endMessage;
sentNumber.floatingPoint = 0.41f;
int writeCount = 0;
int writeCountOld = writeCount;
size_t bytes_wrote;
size_t whatIsAvailable;
size_t bytes_read = 0;
unsigned int readCount;
readCount = 0;
while (writeCount < 100000) {
if (readyToWrite)
{
/*size_t bytes_wrote = my_serial.write(test_string);
string result = my_serial.read(test_string.length());*/
sentNumber.floatingPoint = sin( ((double)writeCount / 3.0 * 2.0 * 3.141));
std::memcpy(message, sentNumber.binary, FLOATSIZE);
bytes_wrote = my_serial.write(message, MESSAGESIZE_WRITE);
//my_serial.write(&endMessage, 1);
//size_t theLength= my_serial.read(incomingData, FLOATSIZE);
//for (int i = 1; i < FLOATSIZE; i++)
//receivedNumber.binary[i] = incomingData[i];
writeCount += 1;
//modRes = writeCount % LOOPCOUNTS;
if (writeCount % LOOPCOUNTS == 0)
{
cout << "Read Iter: " << readCount << ", Len: " << bytes_read << ", Val: " << receivedNumber.floatingPoint << " BIN: " << (int)receivedNumber.binary[0] << " " << (int)receivedNumber.binary[1] << " " << (int)receivedNumber.binary[2] << " " << (int)receivedNumber.binary[3] << endl;
cout << "Writ Iter: " << writeCount << ", Len: " << bytes_wrote << ", Val: " << sentNumber.floatingPoint << " BIN: " << (int)sentNumber.binary[0] << " " << (int)sentNumber.binary[1] << " " << (int)sentNumber.binary[2] << " " << (int)sentNumber.binary[3] << endl;
// writeCountOld = writeCount;
}
//if (writeCount == writeCountOld + 1 )
//{
//}
//std::this_thread::sleep_for(duraWrite);
readyToWrite = false;
}
whatIsAvailable = my_serial.available();
//cout << "Bytes Available: " << whatIsAvailable << endl;
if (whatIsAvailable > MESSAGESIZE - 1)
{
if(whatIsAvailable > MESSAGESIZE)
{
cout << "Bytes Available: " << whatIsAvailable << endl;
}
bytes_read = my_serial.read(incomingData, whatIsAvailable);
//cout << "Bytes read: " << length << endl;
if (bytes_read == MESSAGESIZE && incomingData[MESSAGESIZE - 1] == endMessage)
{
// parse the data to the shared float
std::memcpy(receivedNumber.binary, incomingData, FLOATSIZE);
//std::memcpy(otherNumber.binary, &(incomingData[FLOATSIZE]), FLOATSIZE);
readCount++;
//if (readCount % LOOPCOUNTS == 0)
//{
// cout << "Read Iter: " << readCount << ", Len: " << bytes_read << ", Val: " << receivedNumber.floatingPoint << endl;
//}
}
}
}
return 0;
}<commit_msg>increase baud rate<commit_after>#include <string>
#include <iostream>
#include <cstdio>
#include <windows.h>
//#include <math.h>
#include "serial/serial.h"
#include <thread>
#define FLOATSIZE 4
#define MESSAGESIZE FLOATSIZE+1
#define MESSAGESIZE_WRITE MESSAGESIZE
#define LOOPRATE_MS 10
#define LOOPCOUNTS_INT 100
using std::string;
using std::exception;
using std::cout;
using std::cerr;
using std::endl;
using std::vector;
typedef union {
float floatingPoint;
uint8_t binary[FLOATSIZE];
} binaryFloat;
//void my_sleep(unsigned long milliseconds) {
// Sleep(milliseconds); // 100 ms
//}
void enumerate_ports()
{
vector<serial::PortInfo> devices_found = serial::list_ports();
vector<serial::PortInfo>::iterator iter = devices_found.begin();
while (iter != devices_found.end())
{
serial::PortInfo device = *iter++;
printf("(%s, %s, %s)\n", device.port.c_str(), device.description.c_str(),
device.hardware_id.c_str());
}
}
void print_usage()
{
cerr << "Usage: test_serial {-e|<serial port address>} ";
cerr << "<baudrate> [test string]" << endl;
}
binaryFloat sentNumber;
binaryFloat receivedNumber;
uint8_t incomingData[1030];
uint8_t endMessage = 0x0A;
void serial_write_trigger(bool* readyToWrite)
{
std::chrono::milliseconds duraWrite(LOOPRATE_MS);
while (true)
{
*readyToWrite = true;
std::this_thread::sleep_for(duraWrite);
}
}
//void serial_read_thread(serial::Serial* mySerialPtr)
//{
// std::chrono::milliseconds dura(1000);
//
// std::this_thread::sleep_for(dura);
// size_t whatIsAvailable;
// size_t bytes_read;
// unsigned int readCount;
// readCount = 0;
//
// while(true){
// cout << "Bytes Available: " << mySerialPtr->available() << endl;
//
// if (mySerialPtr->waitReadable())
// {
// string result = mySerialPtr->read(1);
// }
// std::this_thread::sleep_for(dura);
//
// }
//}
int main()
{
string port = "COM5";
unsigned long baud = 115200;
// port, baudrate, timeout in milliseconds
serial::Serial my_serial(port, baud, serial::Timeout::simpleTimeout(1000));
my_serial.setTimeout(serial::Timeout::max(), 1, 0, 1, 0);
my_serial.flush();
Sleep(100);
cout << "Is the serial port open?";
if (my_serial.isOpen())
cout << " Yes." << endl;
else
cout << " No." << endl;
// don't forget to pre-allocate memory
//string test_string = "Suppiluluima: the king of the Hittites";
//char newLine[] = "\n";
// uint8_t endMessage = 0;
// endMessage = (uint8_t) newLine;
// cout << endMessage;
//std::thread threadObj(serial_read_thread, &my_serial);
//if (threadObj.joinable())
//{
// //threadObj.join();
// //std::cout << "Joined Thread " << std::endl;
// std::cout << "Detaching Thread " << std::endl;
// threadObj.detach();
//}
bool readyToWrite;
std::thread threadWrite(serial_write_trigger, &readyToWrite);
if (threadWrite.joinable())
{
std::cout << "Detaching Thread " << std::endl;
threadWrite.detach();
}
// Test the timeout, there should be 1 second between prints
//cout << "Timeout == 1000ms, asking for exactly what was written." << endl;
//cout << "Timeout == 10ms, asking for exactly what was written." << endl;
std::chrono::milliseconds duraWrite(LOOPRATE_MS);
//my_serial.flushOutput();
uint8_t message[MESSAGESIZE_WRITE];
message[MESSAGESIZE_WRITE-1] = endMessage;
sentNumber.floatingPoint = 0.41f;
int writeCount = 0;
int writeCountOld = writeCount;
size_t bytes_wrote;
size_t whatIsAvailable;
size_t bytes_read = 0;
unsigned int readCount;
readCount = 0;
while (writeCount < 100000) {
if (readyToWrite)
{
/*size_t bytes_wrote = my_serial.write(test_string);
string result = my_serial.read(test_string.length());*/
sentNumber.floatingPoint = sin( ((double)writeCount / 3.0 * 2.0 * 3.141));
std::memcpy(message, sentNumber.binary, FLOATSIZE);
bytes_wrote = my_serial.write(message, MESSAGESIZE_WRITE);
//my_serial.write(&endMessage, 1);
//size_t theLength= my_serial.read(incomingData, FLOATSIZE);
//for (int i = 1; i < FLOATSIZE; i++)
//receivedNumber.binary[i] = incomingData[i];
writeCount += 1;
//modRes = writeCount % LOOPCOUNTS;
if (writeCount % LOOPCOUNTS_INT == 0)
{
cout << "Writ Iter: " << writeCount << ", Len: " << bytes_wrote << ", Val: " << sentNumber.floatingPoint << " BIN: " << (int)sentNumber.binary[0] << " " << (int)sentNumber.binary[1] << " " << (int)sentNumber.binary[2] << " " << (int)sentNumber.binary[3] << endl;
//writeCountOld = writeCount;
}
if (writeCount % LOOPCOUNTS_INT == 1)
{
cout << "Read Iter: " << readCount << ", Len: " << bytes_read << ", Val: " << receivedNumber.floatingPoint << " BIN: " << (int)receivedNumber.binary[0] << " " << (int)receivedNumber.binary[1] << " " << (int)receivedNumber.binary[2] << " " << (int)receivedNumber.binary[3] << endl;
cout << "-----------------------------------------------------------------------------" << endl;
// writeCountOld = writeCount;
}
//if (writeCount == writeCountOld + 1 )
//{
//}
//std::this_thread::sleep_for(duraWrite);
readyToWrite = false;
}
whatIsAvailable = my_serial.available();
//cout << "Bytes Available: " << whatIsAvailable << endl;
if (whatIsAvailable > MESSAGESIZE - 1)
{
if(whatIsAvailable > MESSAGESIZE)
{
cout << "Bytes Available: " << whatIsAvailable << endl;
}
bytes_read = my_serial.read(incomingData, whatIsAvailable);
//cout << "Bytes read: " << length << endl;
if (bytes_read == MESSAGESIZE && incomingData[MESSAGESIZE - 1] == endMessage)
{
// parse the data to the shared float
std::memcpy(receivedNumber.binary, incomingData, FLOATSIZE);
//std::memcpy(otherNumber.binary, &(incomingData[FLOATSIZE]), FLOATSIZE);
readCount++;
//if (readCount % LOOPCOUNTS_INT == 0)
//{
// cout << "Read Iter: " << readCount << ", Len: " << bytes_read << ", Val: " << receivedNumber.floatingPoint << endl;
//}
}
}
}
return 0;
}<|endoftext|> |
<commit_before>/*
* Adplug - Replayer for many OPL2/OPL3 audio file formats.
* Copyright (C) 1999 - 2002 Simon Peter <dn.tlp@gmx.net>, et al.
*
* 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
*
* imf.cpp - IMF Player by Simon Peter (dn.tlp@gmx.net)
*
* FILE FORMAT:
* There seem to be 2 different flavors of IMF formats out there. One version
* contains just the raw IMF music data. In this case, the first word of the
* file is always 0 (because the music data starts this way). This is already
* the music data! So read in the entire file and play it.
*
* If this word is greater than 0, it specifies the size of the following
* song data in bytes. In this case, the file has a footer that contains
* arbitrary infos about it. Mostly, this is plain ASCII text with some words
* of the author. Read and play the specified amount of song data and display
* the remaining data as ASCII text.
*/
#include <string.h>
#include "imf.h"
#include "imfcrc.h"
/*** public methods *************************************/
CPlayer *CimfPlayer::factory(Copl *newopl)
{
CimfPlayer *p = new CimfPlayer(newopl);
return p;
}
bool CimfPlayer::load(istream &f, const char *filename)
{
unsigned short fsize;
unsigned long filesize;
// file validation section (actually just an extension check)
if(strlen(filename) < 4 || stricmp(filename+strlen(filename)-4,".imf"))
return false;
// load section
f.read((char *)&fsize,2); // try to load music data size
f.seekg(0,ios::end); filesize = f.tellg(); f.seekg(0);
if(!fsize) // footerless file (raw music data)
size = filesize / 4;
else { // file has got footer
size = fsize / 4;
f.ignore(2);
}
data = new Sdata[size];
f.read((char *)data,size * 4);
if(fsize) { // read footer, if any
unsigned long footerlen = filesize - fsize - 2;
footer = new char[footerlen + 1];
f.read(footer,footerlen);
footer[footerlen] = '\0'; // Make ASCIIZ string
}
rate = getrate(crc32((unsigned char *)data,size*4),size*4);
rewind(0);
return true;
}
bool CimfPlayer::update()
{
do {
opl->write(data[pos].reg,data[pos].val);
del = data[pos].time;
pos++;
} while(!del && pos < size);
if(pos >= size) {
pos = 0;
songend = true;
}
else timer = rate / (float)del;
return !songend;
}
void CimfPlayer::rewind(unsigned int subsong)
{
pos = 0; del = 0; timer = rate; songend = false;
opl->init(); opl->write(1,32); // go to OPL2 mode
}
/*** private methods *************************************/
static unsigned long const crctab[256] =
{
0x0,
0x04C11DB7, 0x09823B6E, 0x0D4326D9, 0x130476DC, 0x17C56B6B,
0x1A864DB2, 0x1E475005, 0x2608EDB8, 0x22C9F00F, 0x2F8AD6D6,
0x2B4BCB61, 0x350C9B64, 0x31CD86D3, 0x3C8EA00A, 0x384FBDBD,
0x4C11DB70, 0x48D0C6C7, 0x4593E01E, 0x4152FDA9, 0x5F15ADAC,
0x5BD4B01B, 0x569796C2, 0x52568B75, 0x6A1936C8, 0x6ED82B7F,
0x639B0DA6, 0x675A1011, 0x791D4014, 0x7DDC5DA3, 0x709F7B7A,
0x745E66CD, 0x9823B6E0, 0x9CE2AB57, 0x91A18D8E, 0x95609039,
0x8B27C03C, 0x8FE6DD8B, 0x82A5FB52, 0x8664E6E5, 0xBE2B5B58,
0xBAEA46EF, 0xB7A96036, 0xB3687D81, 0xAD2F2D84, 0xA9EE3033,
0xA4AD16EA, 0xA06C0B5D, 0xD4326D90, 0xD0F37027, 0xDDB056FE,
0xD9714B49, 0xC7361B4C, 0xC3F706FB, 0xCEB42022, 0xCA753D95,
0xF23A8028, 0xF6FB9D9F, 0xFBB8BB46, 0xFF79A6F1, 0xE13EF6F4,
0xE5FFEB43, 0xE8BCCD9A, 0xEC7DD02D, 0x34867077, 0x30476DC0,
0x3D044B19, 0x39C556AE, 0x278206AB, 0x23431B1C, 0x2E003DC5,
0x2AC12072, 0x128E9DCF, 0x164F8078, 0x1B0CA6A1, 0x1FCDBB16,
0x018AEB13, 0x054BF6A4, 0x0808D07D, 0x0CC9CDCA, 0x7897AB07,
0x7C56B6B0, 0x71159069, 0x75D48DDE, 0x6B93DDDB, 0x6F52C06C,
0x6211E6B5, 0x66D0FB02, 0x5E9F46BF, 0x5A5E5B08, 0x571D7DD1,
0x53DC6066, 0x4D9B3063, 0x495A2DD4, 0x44190B0D, 0x40D816BA,
0xACA5C697, 0xA864DB20, 0xA527FDF9, 0xA1E6E04E, 0xBFA1B04B,
0xBB60ADFC, 0xB6238B25, 0xB2E29692, 0x8AAD2B2F, 0x8E6C3698,
0x832F1041, 0x87EE0DF6, 0x99A95DF3, 0x9D684044, 0x902B669D,
0x94EA7B2A, 0xE0B41DE7, 0xE4750050, 0xE9362689, 0xEDF73B3E,
0xF3B06B3B, 0xF771768C, 0xFA325055, 0xFEF34DE2, 0xC6BCF05F,
0xC27DEDE8, 0xCF3ECB31, 0xCBFFD686, 0xD5B88683, 0xD1799B34,
0xDC3ABDED, 0xD8FBA05A, 0x690CE0EE, 0x6DCDFD59, 0x608EDB80,
0x644FC637, 0x7A089632, 0x7EC98B85, 0x738AAD5C, 0x774BB0EB,
0x4F040D56, 0x4BC510E1, 0x46863638, 0x42472B8F, 0x5C007B8A,
0x58C1663D, 0x558240E4, 0x51435D53, 0x251D3B9E, 0x21DC2629,
0x2C9F00F0, 0x285E1D47, 0x36194D42, 0x32D850F5, 0x3F9B762C,
0x3B5A6B9B, 0x0315D626, 0x07D4CB91, 0x0A97ED48, 0x0E56F0FF,
0x1011A0FA, 0x14D0BD4D, 0x19939B94, 0x1D528623, 0xF12F560E,
0xF5EE4BB9, 0xF8AD6D60, 0xFC6C70D7, 0xE22B20D2, 0xE6EA3D65,
0xEBA91BBC, 0xEF68060B, 0xD727BBB6, 0xD3E6A601, 0xDEA580D8,
0xDA649D6F, 0xC423CD6A, 0xC0E2D0DD, 0xCDA1F604, 0xC960EBB3,
0xBD3E8D7E, 0xB9FF90C9, 0xB4BCB610, 0xB07DABA7, 0xAE3AFBA2,
0xAAFBE615, 0xA7B8C0CC, 0xA379DD7B, 0x9B3660C6, 0x9FF77D71,
0x92B45BA8, 0x9675461F, 0x8832161A, 0x8CF30BAD, 0x81B02D74,
0x857130C3, 0x5D8A9099, 0x594B8D2E, 0x5408ABF7, 0x50C9B640,
0x4E8EE645, 0x4A4FFBF2, 0x470CDD2B, 0x43CDC09C, 0x7B827D21,
0x7F436096, 0x7200464F, 0x76C15BF8, 0x68860BFD, 0x6C47164A,
0x61043093, 0x65C52D24, 0x119B4BE9, 0x155A565E, 0x18197087,
0x1CD86D30, 0x029F3D35, 0x065E2082, 0x0B1D065B, 0x0FDC1BEC,
0x3793A651, 0x3352BBE6, 0x3E119D3F, 0x3AD08088, 0x2497D08D,
0x2056CD3A, 0x2D15EBE3, 0x29D4F654, 0xC5A92679, 0xC1683BCE,
0xCC2B1D17, 0xC8EA00A0, 0xD6AD50A5, 0xD26C4D12, 0xDF2F6BCB,
0xDBEE767C, 0xE3A1CBC1, 0xE760D676, 0xEA23F0AF, 0xEEE2ED18,
0xF0A5BD1D, 0xF464A0AA, 0xF9278673, 0xFDE69BC4, 0x89B8FD09,
0x8D79E0BE, 0x803AC667, 0x84FBDBD0, 0x9ABC8BD5, 0x9E7D9662,
0x933EB0BB, 0x97FFAD0C, 0xAFB010B1, 0xAB710D06, 0xA6322BDF,
0xA2F33668, 0xBCB4666D, 0xB8757BDA, 0xB5365D03, 0xB1F740B4
};
unsigned long CimfPlayer::crc32(unsigned char *buf, unsigned long size)
{
unsigned long crc=0,i;
for(i=0;i<size;i++)
crc = (crc << 8) ^ crctab[((crc >> 24) ^ buf[i]) & 0xFF];
for(i=size;i>0;i>>=8)
crc = (crc << 8) ^ crctab[((crc >> 24) ^ i) & 0xFF];
crc = ~crc & 0xFFFFFFFF;
return crc;
}
float CimfPlayer::getrate(unsigned long crc, unsigned long size)
{
unsigned int i;
for(i=0;filetab[i].size;i++)
if(crc == filetab[i].crc && size == filetab[i].size)
return filetab[i].rate;
return 700.0f;
}
<commit_msg>Fixed IMF player to correctly load files with a null-length footer.<commit_after>/*
* Adplug - Replayer for many OPL2/OPL3 audio file formats.
* Copyright (C) 1999 - 2002 Simon Peter <dn.tlp@gmx.net>, et al.
*
* 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
*
* imf.cpp - IMF Player by Simon Peter (dn.tlp@gmx.net)
*
* FILE FORMAT:
* There seem to be 2 different flavors of IMF formats out there. One version
* contains just the raw IMF music data. In this case, the first word of the
* file is always 0 (because the music data starts this way). This is already
* the music data! So read in the entire file and play it.
*
* If this word is greater than 0, it specifies the size of the following
* song data in bytes. In this case, the file has a footer that contains
* arbitrary infos about it. Mostly, this is plain ASCII text with some words
* of the author. Read and play the specified amount of song data and display
* the remaining data as ASCII text.
*/
#include <string.h>
#include "imf.h"
#include "imfcrc.h"
/*** public methods *************************************/
CPlayer *CimfPlayer::factory(Copl *newopl)
{
CimfPlayer *p = new CimfPlayer(newopl);
return p;
}
bool CimfPlayer::load(istream &f, const char *filename)
{
unsigned short fsize;
unsigned long filesize;
// file validation section (actually just an extension check)
if(strlen(filename) < 4 || stricmp(filename+strlen(filename)-4,".imf"))
return false;
// load section
f.read((char *)&fsize,2); // try to load music data size
f.seekg(0,ios::end); filesize = f.tellg(); f.seekg(0);
if(!fsize) // footerless file (raw music data)
size = filesize / 4;
else { // file has got footer
size = fsize / 4;
f.ignore(2);
}
data = new Sdata[size];
f.read((char *)data,size * 4);
if(fsize && (fsize < filesize - 2)) { // read footer, if any
unsigned long footerlen = filesize - fsize - 2;
footer = new char[footerlen + 1];
f.read(footer,footerlen);
footer[footerlen] = '\0'; // Make ASCIIZ string
}
rate = getrate(crc32((unsigned char *)data,size*4),size*4);
rewind(0);
return true;
}
bool CimfPlayer::update()
{
do {
opl->write(data[pos].reg,data[pos].val);
del = data[pos].time;
pos++;
} while(!del && pos < size);
if(pos >= size) {
pos = 0;
songend = true;
}
else timer = rate / (float)del;
return !songend;
}
void CimfPlayer::rewind(unsigned int subsong)
{
pos = 0; del = 0; timer = rate; songend = false;
opl->init(); opl->write(1,32); // go to OPL2 mode
}
/*** private methods *************************************/
static unsigned long const crctab[256] =
{
0x0,
0x04C11DB7, 0x09823B6E, 0x0D4326D9, 0x130476DC, 0x17C56B6B,
0x1A864DB2, 0x1E475005, 0x2608EDB8, 0x22C9F00F, 0x2F8AD6D6,
0x2B4BCB61, 0x350C9B64, 0x31CD86D3, 0x3C8EA00A, 0x384FBDBD,
0x4C11DB70, 0x48D0C6C7, 0x4593E01E, 0x4152FDA9, 0x5F15ADAC,
0x5BD4B01B, 0x569796C2, 0x52568B75, 0x6A1936C8, 0x6ED82B7F,
0x639B0DA6, 0x675A1011, 0x791D4014, 0x7DDC5DA3, 0x709F7B7A,
0x745E66CD, 0x9823B6E0, 0x9CE2AB57, 0x91A18D8E, 0x95609039,
0x8B27C03C, 0x8FE6DD8B, 0x82A5FB52, 0x8664E6E5, 0xBE2B5B58,
0xBAEA46EF, 0xB7A96036, 0xB3687D81, 0xAD2F2D84, 0xA9EE3033,
0xA4AD16EA, 0xA06C0B5D, 0xD4326D90, 0xD0F37027, 0xDDB056FE,
0xD9714B49, 0xC7361B4C, 0xC3F706FB, 0xCEB42022, 0xCA753D95,
0xF23A8028, 0xF6FB9D9F, 0xFBB8BB46, 0xFF79A6F1, 0xE13EF6F4,
0xE5FFEB43, 0xE8BCCD9A, 0xEC7DD02D, 0x34867077, 0x30476DC0,
0x3D044B19, 0x39C556AE, 0x278206AB, 0x23431B1C, 0x2E003DC5,
0x2AC12072, 0x128E9DCF, 0x164F8078, 0x1B0CA6A1, 0x1FCDBB16,
0x018AEB13, 0x054BF6A4, 0x0808D07D, 0x0CC9CDCA, 0x7897AB07,
0x7C56B6B0, 0x71159069, 0x75D48DDE, 0x6B93DDDB, 0x6F52C06C,
0x6211E6B5, 0x66D0FB02, 0x5E9F46BF, 0x5A5E5B08, 0x571D7DD1,
0x53DC6066, 0x4D9B3063, 0x495A2DD4, 0x44190B0D, 0x40D816BA,
0xACA5C697, 0xA864DB20, 0xA527FDF9, 0xA1E6E04E, 0xBFA1B04B,
0xBB60ADFC, 0xB6238B25, 0xB2E29692, 0x8AAD2B2F, 0x8E6C3698,
0x832F1041, 0x87EE0DF6, 0x99A95DF3, 0x9D684044, 0x902B669D,
0x94EA7B2A, 0xE0B41DE7, 0xE4750050, 0xE9362689, 0xEDF73B3E,
0xF3B06B3B, 0xF771768C, 0xFA325055, 0xFEF34DE2, 0xC6BCF05F,
0xC27DEDE8, 0xCF3ECB31, 0xCBFFD686, 0xD5B88683, 0xD1799B34,
0xDC3ABDED, 0xD8FBA05A, 0x690CE0EE, 0x6DCDFD59, 0x608EDB80,
0x644FC637, 0x7A089632, 0x7EC98B85, 0x738AAD5C, 0x774BB0EB,
0x4F040D56, 0x4BC510E1, 0x46863638, 0x42472B8F, 0x5C007B8A,
0x58C1663D, 0x558240E4, 0x51435D53, 0x251D3B9E, 0x21DC2629,
0x2C9F00F0, 0x285E1D47, 0x36194D42, 0x32D850F5, 0x3F9B762C,
0x3B5A6B9B, 0x0315D626, 0x07D4CB91, 0x0A97ED48, 0x0E56F0FF,
0x1011A0FA, 0x14D0BD4D, 0x19939B94, 0x1D528623, 0xF12F560E,
0xF5EE4BB9, 0xF8AD6D60, 0xFC6C70D7, 0xE22B20D2, 0xE6EA3D65,
0xEBA91BBC, 0xEF68060B, 0xD727BBB6, 0xD3E6A601, 0xDEA580D8,
0xDA649D6F, 0xC423CD6A, 0xC0E2D0DD, 0xCDA1F604, 0xC960EBB3,
0xBD3E8D7E, 0xB9FF90C9, 0xB4BCB610, 0xB07DABA7, 0xAE3AFBA2,
0xAAFBE615, 0xA7B8C0CC, 0xA379DD7B, 0x9B3660C6, 0x9FF77D71,
0x92B45BA8, 0x9675461F, 0x8832161A, 0x8CF30BAD, 0x81B02D74,
0x857130C3, 0x5D8A9099, 0x594B8D2E, 0x5408ABF7, 0x50C9B640,
0x4E8EE645, 0x4A4FFBF2, 0x470CDD2B, 0x43CDC09C, 0x7B827D21,
0x7F436096, 0x7200464F, 0x76C15BF8, 0x68860BFD, 0x6C47164A,
0x61043093, 0x65C52D24, 0x119B4BE9, 0x155A565E, 0x18197087,
0x1CD86D30, 0x029F3D35, 0x065E2082, 0x0B1D065B, 0x0FDC1BEC,
0x3793A651, 0x3352BBE6, 0x3E119D3F, 0x3AD08088, 0x2497D08D,
0x2056CD3A, 0x2D15EBE3, 0x29D4F654, 0xC5A92679, 0xC1683BCE,
0xCC2B1D17, 0xC8EA00A0, 0xD6AD50A5, 0xD26C4D12, 0xDF2F6BCB,
0xDBEE767C, 0xE3A1CBC1, 0xE760D676, 0xEA23F0AF, 0xEEE2ED18,
0xF0A5BD1D, 0xF464A0AA, 0xF9278673, 0xFDE69BC4, 0x89B8FD09,
0x8D79E0BE, 0x803AC667, 0x84FBDBD0, 0x9ABC8BD5, 0x9E7D9662,
0x933EB0BB, 0x97FFAD0C, 0xAFB010B1, 0xAB710D06, 0xA6322BDF,
0xA2F33668, 0xBCB4666D, 0xB8757BDA, 0xB5365D03, 0xB1F740B4
};
unsigned long CimfPlayer::crc32(unsigned char *buf, unsigned long size)
{
unsigned long crc=0,i;
for(i=0;i<size;i++)
crc = (crc << 8) ^ crctab[((crc >> 24) ^ buf[i]) & 0xFF];
for(i=size;i>0;i>>=8)
crc = (crc << 8) ^ crctab[((crc >> 24) ^ i) & 0xFF];
crc = ~crc & 0xFFFFFFFF;
return crc;
}
float CimfPlayer::getrate(unsigned long crc, unsigned long size)
{
unsigned int i;
for(i=0;filetab[i].size;i++)
if(crc == filetab[i].crc && size == filetab[i].size)
return filetab[i].rate;
return 700.0f;
}
<|endoftext|> |
<commit_before>/******************************************************************************
* SOFA, Simulation Open-Framework Architecture, development version *
* (c) 2006-2016 INRIA, USTL, UJF, CNRS, MGH *
* *
* 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. *
*******************************************************************************
* SOFA :: Framework *
* *
* Authors: The SOFA Team (see Authors.txt) *
* *
* Contact information: contact@sofa-framework.org *
******************************************************************************/
#include <sofa/helper/BackTrace.h>
#if !defined(_XBOX) && !defined(PS3)
#include <signal.h>
#endif
#if !defined(WIN32) && !defined(_XBOX) && !defined(__APPLE__) && !defined(PS3)
#include <execinfo.h>
#include <unistd.h>
#endif
#if defined(WIN32)
#include "windows.h"
#include "DbgHelp.h"
#pragma comment(lib, "Dbghelp.lib")
#endif
#if defined(__GNUC__) && !defined(PS3)
#include <cxxabi.h>
#endif
#include <iostream>
#include <string>
namespace sofa
{
namespace helper
{
/// Dump current backtrace to stderr.
/// Currently only works on Linux. NOOP on other architectures.
void BackTrace::dump()
{
#if defined(__GNUC__) && !defined(__APPLE__) && !defined(WIN32) && !defined(_XBOX) && !defined(PS3)
void *array[128];
int size = backtrace(array, sizeof(array) / sizeof(array[0]));
if (size > 0)
{
char** symbols = backtrace_symbols(array, size);
if (symbols != NULL)
{
for (int i = 0; i < size; ++i)
{
char* symbol = symbols[i];
// Decode the method's name to a more readable form if possible
char *beginmangled = strrchr(symbol,'(');
if (beginmangled != NULL)
{
++beginmangled;
char *endmangled = strrchr(beginmangled ,')');
if (endmangled != NULL)
{
// remove +0x[0-9a-fA-f]* suffix
char* savedend = endmangled;
while((endmangled[-1]>='0' && endmangled[-1]<='9') ||
(endmangled[-1]>='a' && endmangled[-1]<='f') ||
(endmangled[-1]>='A' && endmangled[-1]<='F'))
--endmangled;
if (endmangled[-1]=='x' && endmangled[-2]=='0' && endmangled[-3]=='+')
endmangled -= 3;
else
endmangled = savedend; // suffix not found
char* name = (char*)malloc(endmangled-beginmangled+1);
memcpy(name, beginmangled, endmangled-beginmangled);
name[endmangled-beginmangled] = '\0';
int status;
char* realname = abi::__cxa_demangle(name, 0, 0, &status);
if (realname != NULL)
{
free(name);
name = realname;
}
fprintf(stderr,"-> %.*s%s%s\n",(int)(beginmangled-symbol),symbol,name,endmangled);
free(name);
}
else
fprintf(stderr,"-> %s\n",symbol);
}
else
fprintf(stderr,"-> %s\n",symbol);
}
free(symbols);
}
else
{
backtrace_symbols_fd(array, size, STDERR_FILENO);
}
}
#else #if !defined(__GNUC__) && !defined(__APPLE__) && defined(WIN32) && !defined(_XBOX) && !defined(PS3)
unsigned int i;
void * stack[100];
unsigned short frames;
SYMBOL_INFO * symbol;
HANDLE process;
process = GetCurrentProcess();
SymInitialize(process, NULL, TRUE);
frames = CaptureStackBackTrace(0, 100, stack, NULL);
symbol = (SYMBOL_INFO *)calloc(sizeof(SYMBOL_INFO) + 256 * sizeof(char), 1);
symbol->MaxNameLen = 255;
symbol->SizeOfStruct = sizeof(SYMBOL_INFO);
for (i = 0; i < frames; i++)
{
SymFromAddr(process, (DWORD64)(stack[i]), 0, symbol);
std::cerr << (frames - i - 1) << ": " << symbol->Name << " - 0x" << std::hex << symbol->Address << std::dec << std::endl;
}
free(symbol);
#endif
}
/// Enable dump of backtrace when a signal is received.
/// Useful to have information about crashes without starting a debugger (as it is not always easy to do, i.e. for parallel/distributed applications).
/// Currently only works on Linux. NOOP on other architectures
void BackTrace::autodump()
{
#if !defined(_XBOX) && !defined(PS3)
signal(SIGABRT, BackTrace::sig);
signal(SIGSEGV, BackTrace::sig);
signal(SIGILL, BackTrace::sig);
signal(SIGFPE, BackTrace::sig);
signal(SIGINT, BackTrace::sig);
signal(SIGTERM, BackTrace::sig);
#if !defined(WIN32)
signal(SIGPIPE, BackTrace::sig);
#endif
#endif
}
static std::string SigDescription(int sig)
{
switch (sig)
{
case SIGABRT:
return "SIGABRT: usually caused by an abort() or assert()";
break;
case SIGFPE:
return "SIGFPE: arithmetic exception, such as divide by zero";
break;
case SIGILL:
return "SIGILL: illegal instruction";
break;
case SIGINT:
return "SIGINT: interactive attention signal, probably a ctrl+c";
break;
case SIGSEGV:
return "SIGSEGV: segfault";
break;
case SIGTERM:
default:
return "SIGTERM: a termination request was sent to the program";
break;
}
return "Unknown signal";
}
void BackTrace::sig(int sig)
{
#if !defined(_XBOX) && !defined(PS3)
std::cerr << std::endl << "########## SIG " << sig << " - " << SigDescription(sig) << " ##########" << std::endl;
dump();
signal(sig,SIG_DFL);
raise(sig);
#else
std::cerr << std::endl << "ERROR: BackTrace::sig(" << sig << " - " << SigDescription(sig) << ") not supported." << std::endl;
#endif
}
} // namespace helper
} // namespace sofa
<commit_msg>FIX: compilation on Linux<commit_after>/******************************************************************************
* SOFA, Simulation Open-Framework Architecture, development version *
* (c) 2006-2016 INRIA, USTL, UJF, CNRS, MGH *
* *
* 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. *
*******************************************************************************
* SOFA :: Framework *
* *
* Authors: The SOFA Team (see Authors.txt) *
* *
* Contact information: contact@sofa-framework.org *
******************************************************************************/
#include <sofa/helper/BackTrace.h>
#if !defined(_XBOX) && !defined(PS3)
#include <signal.h>
#endif
#if !defined(WIN32) && !defined(_XBOX) && !defined(__APPLE__) && !defined(PS3)
#include <execinfo.h>
#include <unistd.h>
#endif
#if defined(WIN32)
#include "windows.h"
#include "DbgHelp.h"
#pragma comment(lib, "Dbghelp.lib")
#endif
#if defined(__GNUC__) && !defined(PS3)
#include <cxxabi.h>
#endif
#include <cstdio>
#include <cstdlib>
#include <cstring>
#include <iostream>
#include <string>
namespace sofa
{
namespace helper
{
/// Dump current backtrace to stderr.
/// Currently only works on Linux. NOOP on other architectures.
void BackTrace::dump()
{
#if defined(__GNUC__) && !defined(__APPLE__) && !defined(WIN32) && !defined(_XBOX) && !defined(PS3)
void *array[128];
int size = backtrace(array, sizeof(array) / sizeof(array[0]));
if (size > 0)
{
char** symbols = backtrace_symbols(array, size);
if (symbols != NULL)
{
for (int i = 0; i < size; ++i)
{
char* symbol = symbols[i];
// Decode the method's name to a more readable form if possible
char *beginmangled = strrchr(symbol,'(');
if (beginmangled != NULL)
{
++beginmangled;
char *endmangled = strrchr(beginmangled ,')');
if (endmangled != NULL)
{
// remove +0x[0-9a-fA-f]* suffix
char* savedend = endmangled;
while((endmangled[-1]>='0' && endmangled[-1]<='9') ||
(endmangled[-1]>='a' && endmangled[-1]<='f') ||
(endmangled[-1]>='A' && endmangled[-1]<='F'))
--endmangled;
if (endmangled[-1]=='x' && endmangled[-2]=='0' && endmangled[-3]=='+')
endmangled -= 3;
else
endmangled = savedend; // suffix not found
char* name = (char*)malloc(endmangled-beginmangled+1);
memcpy(name, beginmangled, endmangled-beginmangled);
name[endmangled-beginmangled] = '\0';
int status;
char* realname = abi::__cxa_demangle(name, 0, 0, &status);
if (realname != NULL)
{
free(name);
name = realname;
}
fprintf(stderr,"-> %.*s%s%s\n",(int)(beginmangled-symbol),symbol,name,endmangled);
free(name);
}
else
fprintf(stderr,"-> %s\n",symbol);
}
else
fprintf(stderr,"-> %s\n",symbol);
}
free(symbols);
}
else
{
backtrace_symbols_fd(array, size, STDERR_FILENO);
}
}
#else #if !defined(__GNUC__) && !defined(__APPLE__) && defined(WIN32) && !defined(_XBOX) && !defined(PS3)
unsigned int i;
void * stack[100];
unsigned short frames;
SYMBOL_INFO * symbol;
HANDLE process;
process = GetCurrentProcess();
SymInitialize(process, NULL, TRUE);
frames = CaptureStackBackTrace(0, 100, stack, NULL);
symbol = (SYMBOL_INFO *)calloc(sizeof(SYMBOL_INFO) + 256 * sizeof(char), 1);
symbol->MaxNameLen = 255;
symbol->SizeOfStruct = sizeof(SYMBOL_INFO);
for (i = 0; i < frames; i++)
{
SymFromAddr(process, (DWORD64)(stack[i]), 0, symbol);
std::cerr << (frames - i - 1) << ": " << symbol->Name << " - 0x" << std::hex << symbol->Address << std::dec << std::endl;
}
free(symbol);
#endif
}
/// Enable dump of backtrace when a signal is received.
/// Useful to have information about crashes without starting a debugger (as it is not always easy to do, i.e. for parallel/distributed applications).
/// Currently only works on Linux. NOOP on other architectures
void BackTrace::autodump()
{
#if !defined(_XBOX) && !defined(PS3)
signal(SIGABRT, BackTrace::sig);
signal(SIGSEGV, BackTrace::sig);
signal(SIGILL, BackTrace::sig);
signal(SIGFPE, BackTrace::sig);
signal(SIGINT, BackTrace::sig);
signal(SIGTERM, BackTrace::sig);
#if !defined(WIN32)
signal(SIGPIPE, BackTrace::sig);
#endif
#endif
}
static std::string SigDescription(int sig)
{
switch (sig)
{
case SIGABRT:
return "SIGABRT: usually caused by an abort() or assert()";
break;
case SIGFPE:
return "SIGFPE: arithmetic exception, such as divide by zero";
break;
case SIGILL:
return "SIGILL: illegal instruction";
break;
case SIGINT:
return "SIGINT: interactive attention signal, probably a ctrl+c";
break;
case SIGSEGV:
return "SIGSEGV: segfault";
break;
case SIGTERM:
default:
return "SIGTERM: a termination request was sent to the program";
break;
}
return "Unknown signal";
}
void BackTrace::sig(int sig)
{
#if !defined(_XBOX) && !defined(PS3)
std::cerr << std::endl << "########## SIG " << sig << " - " << SigDescription(sig) << " ##########" << std::endl;
dump();
signal(sig,SIG_DFL);
raise(sig);
#else
std::cerr << std::endl << "ERROR: BackTrace::sig(" << sig << " - " << SigDescription(sig) << ") not supported." << std::endl;
#endif
}
} // namespace helper
} // namespace sofa
<|endoftext|> |
<commit_before>#include "OpenCV.h"
#include "Point.h"
#include "Matrix.h"
#include "CascadeClassifierWrap.h"
#include "VideoCaptureWrap.h"
#include "VideoWriterWrap.h"
#include "Contours.h"
#include "CamShift.h"
#include "HighGUI.h"
#include "FaceRecognizer.h"
#include "Features2d.h"
#include "Constants.h"
#include "Calib3D.h"
#include "ImgProc.h"
#include "Stereo.h"
#include "BackgroundSubtractor.h"
#include "LDAWrap.h"
#include "Histogram.h"
extern "C" void init(Local<Object> target) {
Nan::HandleScope scope;
OpenCV::Init(target);
Point::Init(target);
Matrix::Init(target);
#ifdef HAVE_OPENCV_OBJDETECT
CascadeClassifierWrap::Init(target);
#endif
#ifdef HAVE_OPENCV_VIDEOIO
VideoCaptureWrap::Init(target);
VideoWriterWrap::Init(target);
#endif
Contour::Init(target);
#ifdef HAVE_OPENCV_VIDEO
TrackedObject::Init(target);
#endif
#ifdef HAVE_OPENCV_HIGHGUI
NamedWindow::Init(target);
#endif
Constants::Init(target);
#ifdef HAVE_OPENCV_CALIB3D
Calib3D::Init(target);
#endif
#ifdef HAVE_OPENCV_IMGPROC
ImgProc::Init(target);
Histogram::Init(target);
#endif
#if CV_MAJOR_VERSION < 3
StereoBM::Init(target);
StereoSGBM::Init(target);
StereoGC::Init(target);
#if CV_MAJOR_VERSION == 2 && CV_MINOR_VERSION >=4
#ifdef HAVE_OPENCV_FEATURES2D
Features::Init(target);
#endif
LDAWrap::Init(target);
#endif
#endif
#ifdef HAVE_BACKGROUNDSUBTRACTOR
BackgroundSubtractorWrap::Init(target);
#endif
#ifdef HAVE_OPENCV_FACE
FaceRecognizerWrap::Init(target);
#endif
};
NODE_MODULE(opencv, init)
<commit_msg>Log OpenCV version in built in init.cc<commit_after>#include "OpenCV.h"
#include "Point.h"
#include "Matrix.h"
#include "CascadeClassifierWrap.h"
#include "VideoCaptureWrap.h"
#include "VideoWriterWrap.h"
#include "Contours.h"
#include "CamShift.h"
#include "HighGUI.h"
#include "FaceRecognizer.h"
#include "Features2d.h"
#include "Constants.h"
#include "Calib3D.h"
#include "ImgProc.h"
#include "Stereo.h"
#include "BackgroundSubtractor.h"
#include "LDAWrap.h"
#include "Histogram.h"
#define STR_HELPER(x) #x
#define STR(x) STR_HELPER(x)
#pragma message ( "Building with OpenCV" STR(CV_MAJOR_VERSION) "." STR(CV_MINOR_VERSION) )
extern "C" void init(Local<Object> target) {
Nan::HandleScope scope;
OpenCV::Init(target);
Point::Init(target);
Matrix::Init(target);
#ifdef HAVE_OPENCV_OBJDETECT
CascadeClassifierWrap::Init(target);
#endif
#ifdef HAVE_OPENCV_VIDEOIO
VideoCaptureWrap::Init(target);
VideoWriterWrap::Init(target);
#endif
Contour::Init(target);
#ifdef HAVE_OPENCV_VIDEO
TrackedObject::Init(target);
#endif
#ifdef HAVE_OPENCV_HIGHGUI
NamedWindow::Init(target);
#endif
Constants::Init(target);
#ifdef HAVE_OPENCV_CALIB3D
Calib3D::Init(target);
#endif
#ifdef HAVE_OPENCV_IMGPROC
ImgProc::Init(target);
Histogram::Init(target);
#endif
#if CV_MAJOR_VERSION < 3
StereoBM::Init(target);
StereoSGBM::Init(target);
StereoGC::Init(target);
#if CV_MAJOR_VERSION == 2 && CV_MINOR_VERSION >=4
#ifdef HAVE_OPENCV_FEATURES2D
Features::Init(target);
#endif
LDAWrap::Init(target);
#endif
#endif
#ifdef HAVE_BACKGROUNDSUBTRACTOR
BackgroundSubtractorWrap::Init(target);
#endif
#ifdef HAVE_OPENCV_FACE
FaceRecognizerWrap::Init(target);
#endif
};
NODE_MODULE(opencv, init)
<|endoftext|> |
<commit_before>/*
* Copyright (c) 2003-2009, John Wiegley. All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are
* met:
*
* - Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
*
* - Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
*
* - Neither the name of New Artisans LLC nor the names of its
* contributors may be used to endorse or promote products derived from
* this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
* "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
* LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
* A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
* OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
* SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
* LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
* DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
* THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
* OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
#include "item.h"
namespace ledger {
bool item_t::has_tag(const string& tag) const
{
if (! metadata)
return false;
string_map::const_iterator i = metadata->find(tag);
return i != metadata->end();
}
optional<string> item_t::get_tag(const string& tag) const
{
if (metadata) {
string_map::const_iterator i = metadata->find(tag);
if (i != metadata->end())
return (*i).second;
}
return none;
}
void item_t::set_tag(const string& tag,
const optional<string>& value)
{
if (! metadata)
metadata = string_map();
DEBUG("item.meta", "Setting tag '" << tag << "' to value '"
<< (value ? *value : string("<none>")) << "'");
std::pair<string_map::iterator, bool> result
= metadata->insert(string_map::value_type(tag, value));
assert(result.second);
}
void item_t::parse_tags(const char * p, int current_year)
{
if (char * b = std::strchr(p, '[')) {
if (char * e = std::strchr(p, ']')) {
char buf[256];
std::strncpy(buf, b + 1, e - b - 1);
buf[e - b - 1] = '\0';
if (char * p = std::strchr(buf, '=')) {
*p++ = '\0';
_date_eff = parse_date(p, current_year);
}
if (buf[0])
_date = parse_date(buf, current_year);
}
}
if (! std::strchr(p, ':'))
return;
scoped_array<char> buf(new char[std::strlen(p) + 1]);
std::strcpy(buf.get(), p);
string tag;
for (char * q = std::strtok(buf.get(), " \t");
q;
q = std::strtok(NULL, " \t")) {
const std::size_t len = std::strlen(q);
if (! tag.empty()) {
set_tag(tag, string(p + (q - buf.get())));
break;
}
else if (q[0] == ':' && q[len - 1] == ':') { // a series of tags
for (char * r = std::strtok(q + 1, ":");
r;
r = std::strtok(NULL, ":"))
set_tag(r);
}
else if (q[len - 1] == ':') { // a metadata setting
tag = string(q, len - 1);
}
}
}
void item_t::append_note(const char * p, int current_year)
{
if (note)
*note += p;
else
note = p;
*note += '\n';
parse_tags(p, current_year);
}
namespace {
value_t get_status(item_t& item) {
return long(item.state());
}
value_t get_uncleared(item_t& item) {
return item.state() == item_t::CLEARED;
}
value_t get_cleared(item_t& item) {
return item.state() == item_t::CLEARED;
}
value_t get_pending(item_t& item) {
return item.state() == item_t::PENDING;
}
value_t get_date(item_t& item) {
if (optional<date_t> date = item.date())
return *date;
else
return 0L;
}
value_t get_note(item_t& item) {
return string_value(item.note ? *item.note : empty_string);
}
value_t has_tag(call_scope_t& args) {
item_t& item(find_scope<item_t>(args));
if (! item.metadata)
return false;
IF_DEBUG("item.meta") {
foreach (const item_t::string_map::value_type& data, *item.metadata) {
*_log_stream << " Tag: " << data.first << "\n";
*_log_stream << "Value: ";
if (data.second)
*_log_stream << *data.second << "\n";
else
*_log_stream << "<none>\n";
}
}
value_t& arg(args[0]);
if (arg.is_string()) {
if (args.size() == 1) {
return item.has_tag(args[0].as_string());
}
else if (optional<string> tag = item.get_tag(args[0].as_string())) {
if (args[1].is_string()) {
return args[1].as_string() == *tag;
}
else if (args[1].is_mask()) {
return args[1].as_mask().match(*tag);
}
}
}
else if (arg.is_mask()) {
foreach (const item_t::string_map::value_type& data, *item.metadata) {
if (arg.as_mask().match(data.first)) {
if (args.size() == 1)
return true;
else if (data.second) {
if (args[1].is_string())
return args[1].as_string() == *data.second;
else if (args[1].is_mask())
return args[1].as_mask().match(*data.second);
}
}
}
}
return false;
}
value_t get_tag(call_scope_t& args) {
item_t& item(find_scope<item_t>(args));
if (optional<string> value = item.get_tag(args[0].as_string()))
return string_value(*value);
return false;
}
value_t get_beg_pos(item_t& item) {
return long(item.beg_pos);
}
value_t get_beg_line(item_t& item) {
return long(item.beg_line);
}
value_t get_end_pos(item_t& item) {
return long(item.end_pos);
}
value_t get_end_line(item_t& item) {
return long(item.end_line);
}
template <value_t (*Func)(item_t&)>
value_t get_wrapper(call_scope_t& scope) {
return (*Func)(find_scope<item_t>(scope));
}
}
value_t get_comment(item_t& item)
{
if (! item.note) {
return false;
} else {
std::ostringstream buf;
buf << "\n ;";
bool need_separator = false;
for (const char * p = item.note->c_str(); *p; p++) {
if (*p == '\n')
need_separator = true;
else {
if (need_separator) {
buf << "\n ;";
need_separator = false;
}
buf << *p;
}
}
return string_value(buf.str());
}
}
expr_t::ptr_op_t item_t::lookup(const string& name)
{
switch (name[0]) {
case 'c':
if (name == "cleared")
return WRAP_FUNCTOR(get_wrapper<&get_cleared>);
else if (name == "comment")
return WRAP_FUNCTOR(get_wrapper<&get_comment>);
break;
case 'd':
if (name[1] == '\0' || name == "date")
return WRAP_FUNCTOR(get_wrapper<&get_date>);
break;
case 'h':
if (name == "has_tag")
return WRAP_FUNCTOR(ledger::has_tag);
else if (name == "has_meta")
return WRAP_FUNCTOR(ledger::has_tag);
break;
case 'm':
if (name == "meta")
return WRAP_FUNCTOR(ledger::get_tag);
break;
case 'n':
if (name == "note")
return WRAP_FUNCTOR(get_wrapper<&get_note>);
break;
case 'p':
if (name == "pending")
return WRAP_FUNCTOR(get_wrapper<&get_pending>);
break;
case 's':
if (name == "status")
return WRAP_FUNCTOR(get_wrapper<&get_status>);
break;
case 't':
if (name == "tag")
return WRAP_FUNCTOR(ledger::get_tag);
break;
case 'u':
if (name == "uncleared")
return WRAP_FUNCTOR(get_wrapper<&get_uncleared>);
break;
case 'X':
if (name[1] == '\0')
return WRAP_FUNCTOR(get_wrapper<&get_cleared>);
break;
case 'Y':
if (name[1] == '\0')
return WRAP_FUNCTOR(get_wrapper<&get_pending>);
break;
}
return NULL;
}
bool item_t::valid() const
{
if (_state != UNCLEARED && _state != CLEARED && _state != PENDING) {
DEBUG("ledger.validate", "item_t: state is bad");
return false;
}
return true;
}
string item_context(const item_t& item)
{
std::size_t len = item.end_pos - item.beg_pos;
assert(len > 0);
assert(len < 2048);
ifstream in(item.pathname);
in.seekg(item.beg_pos, std::ios::beg);
scoped_array<char> buf(new char[len + 1]);
in.read(buf.get(), len);
std::ostringstream out;
out << "While balancing item from \"" << item.pathname.string()
<< "\"";
if (item.beg_line != item.end_line)
out << ", lines " << item.beg_line << "-"
<< item.end_line << ":\n";
else
out << ", line " << item.beg_line << ":\n";
bool first = true;
for (char * p = std::strtok(buf.get(), "\n");
p;
p = std::strtok(NULL, "\n")) {
if (first)
first = false;
else
out << '\n';
out << "> " << p;
}
return out.str();
}
} // namespace ledger
<commit_msg>item_t::get_uncleared was returning true if CLEARED.<commit_after>/*
* Copyright (c) 2003-2009, John Wiegley. All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are
* met:
*
* - Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
*
* - Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
*
* - Neither the name of New Artisans LLC nor the names of its
* contributors may be used to endorse or promote products derived from
* this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
* "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
* LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
* A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
* OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
* SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
* LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
* DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
* THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
* OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
#include "item.h"
namespace ledger {
bool item_t::has_tag(const string& tag) const
{
if (! metadata)
return false;
string_map::const_iterator i = metadata->find(tag);
return i != metadata->end();
}
optional<string> item_t::get_tag(const string& tag) const
{
if (metadata) {
string_map::const_iterator i = metadata->find(tag);
if (i != metadata->end())
return (*i).second;
}
return none;
}
void item_t::set_tag(const string& tag,
const optional<string>& value)
{
if (! metadata)
metadata = string_map();
DEBUG("item.meta", "Setting tag '" << tag << "' to value '"
<< (value ? *value : string("<none>")) << "'");
std::pair<string_map::iterator, bool> result
= metadata->insert(string_map::value_type(tag, value));
assert(result.second);
}
void item_t::parse_tags(const char * p, int current_year)
{
if (char * b = std::strchr(p, '[')) {
if (char * e = std::strchr(p, ']')) {
char buf[256];
std::strncpy(buf, b + 1, e - b - 1);
buf[e - b - 1] = '\0';
if (char * p = std::strchr(buf, '=')) {
*p++ = '\0';
_date_eff = parse_date(p, current_year);
}
if (buf[0])
_date = parse_date(buf, current_year);
}
}
if (! std::strchr(p, ':'))
return;
scoped_array<char> buf(new char[std::strlen(p) + 1]);
std::strcpy(buf.get(), p);
string tag;
for (char * q = std::strtok(buf.get(), " \t");
q;
q = std::strtok(NULL, " \t")) {
const std::size_t len = std::strlen(q);
if (! tag.empty()) {
set_tag(tag, string(p + (q - buf.get())));
break;
}
else if (q[0] == ':' && q[len - 1] == ':') { // a series of tags
for (char * r = std::strtok(q + 1, ":");
r;
r = std::strtok(NULL, ":"))
set_tag(r);
}
else if (q[len - 1] == ':') { // a metadata setting
tag = string(q, len - 1);
}
}
}
void item_t::append_note(const char * p, int current_year)
{
if (note)
*note += p;
else
note = p;
*note += '\n';
parse_tags(p, current_year);
}
namespace {
value_t get_status(item_t& item) {
return long(item.state());
}
value_t get_uncleared(item_t& item) {
return item.state() == item_t::UNCLEARED;
}
value_t get_cleared(item_t& item) {
return item.state() == item_t::CLEARED;
}
value_t get_pending(item_t& item) {
return item.state() == item_t::PENDING;
}
value_t get_date(item_t& item) {
if (optional<date_t> date = item.date())
return *date;
else
return 0L;
}
value_t get_note(item_t& item) {
return string_value(item.note ? *item.note : empty_string);
}
value_t has_tag(call_scope_t& args) {
item_t& item(find_scope<item_t>(args));
if (! item.metadata)
return false;
IF_DEBUG("item.meta") {
foreach (const item_t::string_map::value_type& data, *item.metadata) {
*_log_stream << " Tag: " << data.first << "\n";
*_log_stream << "Value: ";
if (data.second)
*_log_stream << *data.second << "\n";
else
*_log_stream << "<none>\n";
}
}
value_t& arg(args[0]);
if (arg.is_string()) {
if (args.size() == 1) {
return item.has_tag(args[0].as_string());
}
else if (optional<string> tag = item.get_tag(args[0].as_string())) {
if (args[1].is_string()) {
return args[1].as_string() == *tag;
}
else if (args[1].is_mask()) {
return args[1].as_mask().match(*tag);
}
}
}
else if (arg.is_mask()) {
foreach (const item_t::string_map::value_type& data, *item.metadata) {
if (arg.as_mask().match(data.first)) {
if (args.size() == 1)
return true;
else if (data.second) {
if (args[1].is_string())
return args[1].as_string() == *data.second;
else if (args[1].is_mask())
return args[1].as_mask().match(*data.second);
}
}
}
}
return false;
}
value_t get_tag(call_scope_t& args) {
item_t& item(find_scope<item_t>(args));
if (optional<string> value = item.get_tag(args[0].as_string()))
return string_value(*value);
return false;
}
value_t get_beg_pos(item_t& item) {
return long(item.beg_pos);
}
value_t get_beg_line(item_t& item) {
return long(item.beg_line);
}
value_t get_end_pos(item_t& item) {
return long(item.end_pos);
}
value_t get_end_line(item_t& item) {
return long(item.end_line);
}
template <value_t (*Func)(item_t&)>
value_t get_wrapper(call_scope_t& scope) {
return (*Func)(find_scope<item_t>(scope));
}
}
value_t get_comment(item_t& item)
{
if (! item.note) {
return false;
} else {
std::ostringstream buf;
buf << "\n ;";
bool need_separator = false;
for (const char * p = item.note->c_str(); *p; p++) {
if (*p == '\n')
need_separator = true;
else {
if (need_separator) {
buf << "\n ;";
need_separator = false;
}
buf << *p;
}
}
return string_value(buf.str());
}
}
expr_t::ptr_op_t item_t::lookup(const string& name)
{
switch (name[0]) {
case 'c':
if (name == "cleared")
return WRAP_FUNCTOR(get_wrapper<&get_cleared>);
else if (name == "comment")
return WRAP_FUNCTOR(get_wrapper<&get_comment>);
break;
case 'd':
if (name[1] == '\0' || name == "date")
return WRAP_FUNCTOR(get_wrapper<&get_date>);
break;
case 'h':
if (name == "has_tag")
return WRAP_FUNCTOR(ledger::has_tag);
else if (name == "has_meta")
return WRAP_FUNCTOR(ledger::has_tag);
break;
case 'm':
if (name == "meta")
return WRAP_FUNCTOR(ledger::get_tag);
break;
case 'n':
if (name == "note")
return WRAP_FUNCTOR(get_wrapper<&get_note>);
break;
case 'p':
if (name == "pending")
return WRAP_FUNCTOR(get_wrapper<&get_pending>);
break;
case 's':
if (name == "status")
return WRAP_FUNCTOR(get_wrapper<&get_status>);
break;
case 't':
if (name == "tag")
return WRAP_FUNCTOR(ledger::get_tag);
break;
case 'u':
if (name == "uncleared")
return WRAP_FUNCTOR(get_wrapper<&get_uncleared>);
break;
case 'X':
if (name[1] == '\0')
return WRAP_FUNCTOR(get_wrapper<&get_cleared>);
break;
case 'Y':
if (name[1] == '\0')
return WRAP_FUNCTOR(get_wrapper<&get_pending>);
break;
}
return NULL;
}
bool item_t::valid() const
{
if (_state != UNCLEARED && _state != CLEARED && _state != PENDING) {
DEBUG("ledger.validate", "item_t: state is bad");
return false;
}
return true;
}
string item_context(const item_t& item)
{
std::size_t len = item.end_pos - item.beg_pos;
assert(len > 0);
assert(len < 2048);
ifstream in(item.pathname);
in.seekg(item.beg_pos, std::ios::beg);
scoped_array<char> buf(new char[len + 1]);
in.read(buf.get(), len);
std::ostringstream out;
out << "While balancing item from \"" << item.pathname.string()
<< "\"";
if (item.beg_line != item.end_line)
out << ", lines " << item.beg_line << "-"
<< item.end_line << ":\n";
else
out << ", line " << item.beg_line << ":\n";
bool first = true;
for (char * p = std::strtok(buf.get(), "\n");
p;
p = std::strtok(NULL, "\n")) {
if (first)
first = false;
else
out << '\n';
out << "> " << p;
}
return out.str();
}
} // namespace ledger
<|endoftext|> |
<commit_before>/*
* Copyright (C) 2008 Apple Inc. All Rights Reserved.
* Copyright (C) 2009 Torch Mobile, Inc. http://www.torchmobile.com/
* Copyright (C) 2010 Google Inc. All Rights Reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
* 1. Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* 2. Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
*
* THIS SOFTWARE IS PROVIDED BY APPLE INC. ``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 APPLE INC. OR
* CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
* EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
* PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
* PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY
* OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
* OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
#include "config.h"
#include "core/html/parser/HTMLPreloadScanner.h"
#include "HTMLNames.h"
#include "InputTypeNames.h"
#include "RuntimeEnabledFeatures.h"
#include "core/css/MediaList.h"
#include "core/css/MediaQueryEvaluator.h"
#include "core/css/MediaValues.h"
#include "core/html/LinkRelAttribute.h"
#include "core/html/parser/HTMLParserIdioms.h"
#include "core/html/parser/HTMLSrcsetParser.h"
#include "core/html/parser/HTMLTokenizer.h"
#include "platform/TraceEvent.h"
#include "wtf/MainThread.h"
namespace WebCore {
using namespace HTMLNames;
static bool match(const StringImpl* impl, const QualifiedName& qName)
{
return impl == qName.localName().impl();
}
static bool match(const AtomicString& name, const QualifiedName& qName)
{
ASSERT(isMainThread());
return qName.localName() == name;
}
static bool match(const String& name, const QualifiedName& qName)
{
return threadSafeMatch(name, qName);
}
static const StringImpl* tagImplFor(const HTMLToken::DataVector& data)
{
AtomicString tagName(data);
const StringImpl* result = tagName.impl();
if (result->isStatic())
return result;
return 0;
}
static const StringImpl* tagImplFor(const String& tagName)
{
const StringImpl* result = tagName.impl();
if (result->isStatic())
return result;
return 0;
}
static String initiatorFor(const StringImpl* tagImpl)
{
ASSERT(tagImpl);
if (match(tagImpl, imgTag))
return imgTag.localName();
if (match(tagImpl, inputTag))
return inputTag.localName();
if (match(tagImpl, linkTag))
return linkTag.localName();
if (match(tagImpl, scriptTag))
return scriptTag.localName();
ASSERT_NOT_REACHED();
return emptyString();
}
static bool mediaAttributeMatches(const MediaValues& mediaValues, const String& attributeValue)
{
RefPtr<MediaQuerySet> mediaQueries = MediaQuerySet::create(attributeValue);
MediaQueryEvaluator mediaQueryEvaluator("screen", mediaValues);
return mediaQueryEvaluator.eval(mediaQueries.get());
}
class TokenPreloadScanner::StartTagScanner {
public:
StartTagScanner(const StringImpl* tagImpl, PassRefPtr<MediaValues> mediaValues)
: m_tagImpl(tagImpl)
, m_linkIsStyleSheet(false)
, m_matchedMediaAttribute(true)
, m_inputIsImage(false)
, m_encounteredImgSrc(false)
, m_isCORSEnabled(false)
, m_allowCredentials(DoNotAllowStoredCredentials)
, m_mediaValues(mediaValues)
{
if (!match(m_tagImpl, imgTag)
&& !match(m_tagImpl, inputTag)
&& !match(m_tagImpl, linkTag)
&& !match(m_tagImpl, scriptTag))
m_tagImpl = 0;
}
enum URLReplacement {
AllowURLReplacement,
DisallowURLReplacement
};
void processAttributes(const HTMLToken::AttributeList& attributes)
{
ASSERT(isMainThread());
if (!m_tagImpl)
return;
for (HTMLToken::AttributeList::const_iterator iter = attributes.begin(); iter != attributes.end(); ++iter) {
AtomicString attributeName(iter->name);
String attributeValue = StringImpl::create8BitIfPossible(iter->value);
processAttribute(attributeName, attributeValue);
}
}
void processAttributes(const Vector<CompactHTMLToken::Attribute>& attributes)
{
if (!m_tagImpl)
return;
for (Vector<CompactHTMLToken::Attribute>::const_iterator iter = attributes.begin(); iter != attributes.end(); ++iter)
processAttribute(iter->name, iter->value);
}
PassOwnPtr<PreloadRequest> createPreloadRequest(const KURL& predictedBaseURL, const SegmentedString& source)
{
if (!shouldPreload() || !m_matchedMediaAttribute)
return nullptr;
TRACE_EVENT_INSTANT1("net", "PreloadRequest", "url", m_urlToLoad.ascii());
TextPosition position = TextPosition(source.currentLine(), source.currentColumn());
OwnPtr<PreloadRequest> request = PreloadRequest::create(initiatorFor(m_tagImpl), position, m_urlToLoad, predictedBaseURL, resourceType());
if (isCORSEnabled())
request->setCrossOriginEnabled(allowStoredCredentials());
request->setCharset(charset());
return request.release();
}
private:
template<typename NameType>
void processAttribute(const NameType& attributeName, const String& attributeValue)
{
if (match(attributeName, charsetAttr))
m_charset = attributeValue;
if (match(m_tagImpl, scriptTag)) {
if (match(attributeName, srcAttr))
setUrlToLoad(attributeValue, DisallowURLReplacement);
else if (match(attributeName, crossoriginAttr))
setCrossOriginAllowed(attributeValue);
} else if (match(m_tagImpl, imgTag)) {
if (match(attributeName, srcAttr) && !m_encounteredImgSrc) {
m_encounteredImgSrc = true;
setUrlToLoad(bestFitSourceForImageAttributes(m_mediaValues->devicePixelRatio(), attributeValue, m_srcsetImageCandidate), AllowURLReplacement);
} else if (match(attributeName, crossoriginAttr)) {
setCrossOriginAllowed(attributeValue);
} else if (RuntimeEnabledFeatures::srcsetEnabled()
&& match(attributeName, srcsetAttr)
&& m_srcsetImageCandidate.isEmpty()) {
m_srcsetImageCandidate = bestFitSourceForSrcsetAttribute(m_mediaValues->devicePixelRatio(), attributeValue);
setUrlToLoad(bestFitSourceForImageAttributes(m_mediaValues->devicePixelRatio(), m_urlToLoad, m_srcsetImageCandidate), AllowURLReplacement);
}
} else if (match(m_tagImpl, linkTag)) {
if (match(attributeName, hrefAttr))
setUrlToLoad(attributeValue, DisallowURLReplacement);
else if (match(attributeName, relAttr))
m_linkIsStyleSheet = relAttributeIsStyleSheet(attributeValue);
else if (match(attributeName, mediaAttr))
m_matchedMediaAttribute = mediaAttributeMatches(*m_mediaValues, attributeValue);
else if (match(attributeName, crossoriginAttr))
setCrossOriginAllowed(attributeValue);
} else if (match(m_tagImpl, inputTag)) {
if (match(attributeName, srcAttr))
setUrlToLoad(attributeValue, DisallowURLReplacement);
else if (match(attributeName, typeAttr))
m_inputIsImage = equalIgnoringCase(attributeValue, InputTypeNames::image);
}
}
static bool relAttributeIsStyleSheet(const String& attributeValue)
{
LinkRelAttribute rel(attributeValue);
return rel.isStyleSheet() && !rel.isAlternate() && rel.iconType() == InvalidIcon && !rel.isDNSPrefetch();
}
void setUrlToLoad(const String& value, URLReplacement replacement)
{
// We only respect the first src/href, per HTML5:
// http://www.whatwg.org/specs/web-apps/current-work/multipage/tokenization.html#attribute-name-state
if (replacement == DisallowURLReplacement && !m_urlToLoad.isEmpty())
return;
String url = stripLeadingAndTrailingHTMLSpaces(value);
if (url.isEmpty())
return;
m_urlToLoad = url;
}
const String& charset() const
{
// FIXME: Its not clear that this if is needed, the loader probably ignores charset for image requests anyway.
if (match(m_tagImpl, imgTag))
return emptyString();
return m_charset;
}
Resource::Type resourceType() const
{
if (match(m_tagImpl, scriptTag))
return Resource::Script;
if (match(m_tagImpl, imgTag) || (match(m_tagImpl, inputTag) && m_inputIsImage))
return Resource::Image;
if (match(m_tagImpl, linkTag) && m_linkIsStyleSheet)
return Resource::CSSStyleSheet;
ASSERT_NOT_REACHED();
return Resource::Raw;
}
bool shouldPreload() const
{
if (m_urlToLoad.isEmpty())
return false;
if (match(m_tagImpl, linkTag) && !m_linkIsStyleSheet)
return false;
if (match(m_tagImpl, inputTag) && !m_inputIsImage)
return false;
return true;
}
bool isCORSEnabled() const
{
return m_isCORSEnabled;
}
StoredCredentials allowStoredCredentials() const
{
return m_allowCredentials;
}
void setCrossOriginAllowed(const String& corsSetting)
{
m_isCORSEnabled = true;
if (!corsSetting.isNull() && equalIgnoringCase(stripLeadingAndTrailingHTMLSpaces(corsSetting), "use-credentials"))
m_allowCredentials = AllowStoredCredentials;
else
m_allowCredentials = DoNotAllowStoredCredentials;
}
const StringImpl* m_tagImpl;
String m_urlToLoad;
ImageCandidate m_srcsetImageCandidate;
String m_charset;
bool m_linkIsStyleSheet;
bool m_matchedMediaAttribute;
bool m_inputIsImage;
bool m_encounteredImgSrc;
bool m_isCORSEnabled;
StoredCredentials m_allowCredentials;
RefPtr<MediaValues> m_mediaValues;
};
TokenPreloadScanner::TokenPreloadScanner(const KURL& documentURL, PassRefPtr<MediaValues> mediaValues)
: m_documentURL(documentURL)
, m_inStyle(false)
, m_templateCount(0)
, m_mediaValues(mediaValues)
{
}
TokenPreloadScanner::~TokenPreloadScanner()
{
}
TokenPreloadScannerCheckpoint TokenPreloadScanner::createCheckpoint()
{
TokenPreloadScannerCheckpoint checkpoint = m_checkpoints.size();
m_checkpoints.append(Checkpoint(m_predictedBaseElementURL, m_inStyle, m_templateCount));
return checkpoint;
}
void TokenPreloadScanner::rewindTo(TokenPreloadScannerCheckpoint checkpointIndex)
{
ASSERT(checkpointIndex < m_checkpoints.size()); // If this ASSERT fires, checkpointIndex is invalid.
const Checkpoint& checkpoint = m_checkpoints[checkpointIndex];
m_predictedBaseElementURL = checkpoint.predictedBaseElementURL;
m_inStyle = checkpoint.inStyle;
m_templateCount = checkpoint.templateCount;
m_cssScanner.reset();
m_checkpoints.clear();
}
void TokenPreloadScanner::scan(const HTMLToken& token, const SegmentedString& source, PreloadRequestStream& requests)
{
scanCommon(token, source, requests);
}
void TokenPreloadScanner::scan(const CompactHTMLToken& token, const SegmentedString& source, PreloadRequestStream& requests)
{
scanCommon(token, source, requests);
}
template<typename Token>
void TokenPreloadScanner::scanCommon(const Token& token, const SegmentedString& source, PreloadRequestStream& requests)
{
switch (token.type()) {
case HTMLToken::Character: {
if (!m_inStyle)
return;
m_cssScanner.scan(token.data(), source, requests);
return;
}
case HTMLToken::EndTag: {
const StringImpl* tagImpl = tagImplFor(token.data());
if (match(tagImpl, templateTag)) {
if (m_templateCount)
--m_templateCount;
return;
}
if (match(tagImpl, styleTag)) {
if (m_inStyle)
m_cssScanner.reset();
m_inStyle = false;
}
return;
}
case HTMLToken::StartTag: {
if (m_templateCount)
return;
const StringImpl* tagImpl = tagImplFor(token.data());
if (match(tagImpl, templateTag)) {
++m_templateCount;
return;
}
if (match(tagImpl, styleTag)) {
m_inStyle = true;
return;
}
if (match(tagImpl, baseTag)) {
// The first <base> element is the one that wins.
if (!m_predictedBaseElementURL.isEmpty())
return;
updatePredictedBaseURL(token);
return;
}
StartTagScanner scanner(tagImpl, m_mediaValues);
scanner.processAttributes(token.attributes());
OwnPtr<PreloadRequest> request = scanner.createPreloadRequest(m_predictedBaseElementURL, source);
if (request)
requests.append(request.release());
return;
}
default: {
return;
}
}
}
template<typename Token>
void TokenPreloadScanner::updatePredictedBaseURL(const Token& token)
{
ASSERT(m_predictedBaseElementURL.isEmpty());
if (const typename Token::Attribute* hrefAttribute = token.getAttributeItem(hrefAttr))
m_predictedBaseElementURL = KURL(m_documentURL, stripLeadingAndTrailingHTMLSpaces(hrefAttribute->value)).copy();
}
HTMLPreloadScanner::HTMLPreloadScanner(const HTMLParserOptions& options, const KURL& documentURL, PassRefPtr<MediaValues> mediaValues)
: m_scanner(documentURL, mediaValues)
, m_tokenizer(HTMLTokenizer::create(options))
{
}
HTMLPreloadScanner::~HTMLPreloadScanner()
{
}
void HTMLPreloadScanner::appendToEnd(const SegmentedString& source)
{
m_source.append(source);
}
void HTMLPreloadScanner::scan(HTMLResourcePreloader* preloader, const KURL& startingBaseElementURL)
{
ASSERT(isMainThread()); // HTMLTokenizer::updateStateFor only works on the main thread.
// When we start scanning, our best prediction of the baseElementURL is the real one!
if (!startingBaseElementURL.isEmpty())
m_scanner.setPredictedBaseElementURL(startingBaseElementURL);
PreloadRequestStream requests;
while (m_tokenizer->nextToken(m_source, m_token)) {
if (m_token.type() == HTMLToken::StartTag)
m_tokenizer->updateStateFor(attemptStaticStringCreation(m_token.name(), Likely8Bit));
m_scanner.scan(m_token, m_source, requests);
m_token.clear();
}
preloader->takeAndPreload(requests);
}
}
<commit_msg>Oilpan: Build fix after r170314<commit_after>/*
* Copyright (C) 2008 Apple Inc. All Rights Reserved.
* Copyright (C) 2009 Torch Mobile, Inc. http://www.torchmobile.com/
* Copyright (C) 2010 Google Inc. All Rights Reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
* 1. Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* 2. Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
*
* THIS SOFTWARE IS PROVIDED BY APPLE INC. ``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 APPLE INC. OR
* CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
* EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
* PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
* PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY
* OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
* OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
#include "config.h"
#include "core/html/parser/HTMLPreloadScanner.h"
#include "HTMLNames.h"
#include "InputTypeNames.h"
#include "RuntimeEnabledFeatures.h"
#include "core/css/MediaList.h"
#include "core/css/MediaQueryEvaluator.h"
#include "core/css/MediaValues.h"
#include "core/html/LinkRelAttribute.h"
#include "core/html/parser/HTMLParserIdioms.h"
#include "core/html/parser/HTMLSrcsetParser.h"
#include "core/html/parser/HTMLTokenizer.h"
#include "platform/TraceEvent.h"
#include "wtf/MainThread.h"
namespace WebCore {
using namespace HTMLNames;
static bool match(const StringImpl* impl, const QualifiedName& qName)
{
return impl == qName.localName().impl();
}
static bool match(const AtomicString& name, const QualifiedName& qName)
{
ASSERT(isMainThread());
return qName.localName() == name;
}
static bool match(const String& name, const QualifiedName& qName)
{
return threadSafeMatch(name, qName);
}
static const StringImpl* tagImplFor(const HTMLToken::DataVector& data)
{
AtomicString tagName(data);
const StringImpl* result = tagName.impl();
if (result->isStatic())
return result;
return 0;
}
static const StringImpl* tagImplFor(const String& tagName)
{
const StringImpl* result = tagName.impl();
if (result->isStatic())
return result;
return 0;
}
static String initiatorFor(const StringImpl* tagImpl)
{
ASSERT(tagImpl);
if (match(tagImpl, imgTag))
return imgTag.localName();
if (match(tagImpl, inputTag))
return inputTag.localName();
if (match(tagImpl, linkTag))
return linkTag.localName();
if (match(tagImpl, scriptTag))
return scriptTag.localName();
ASSERT_NOT_REACHED();
return emptyString();
}
static bool mediaAttributeMatches(const MediaValues& mediaValues, const String& attributeValue)
{
RefPtrWillBeRawPtr<MediaQuerySet> mediaQueries = MediaQuerySet::create(attributeValue);
MediaQueryEvaluator mediaQueryEvaluator("screen", mediaValues);
return mediaQueryEvaluator.eval(mediaQueries.get());
}
class TokenPreloadScanner::StartTagScanner {
public:
StartTagScanner(const StringImpl* tagImpl, PassRefPtr<MediaValues> mediaValues)
: m_tagImpl(tagImpl)
, m_linkIsStyleSheet(false)
, m_matchedMediaAttribute(true)
, m_inputIsImage(false)
, m_encounteredImgSrc(false)
, m_isCORSEnabled(false)
, m_allowCredentials(DoNotAllowStoredCredentials)
, m_mediaValues(mediaValues)
{
if (!match(m_tagImpl, imgTag)
&& !match(m_tagImpl, inputTag)
&& !match(m_tagImpl, linkTag)
&& !match(m_tagImpl, scriptTag))
m_tagImpl = 0;
}
enum URLReplacement {
AllowURLReplacement,
DisallowURLReplacement
};
void processAttributes(const HTMLToken::AttributeList& attributes)
{
ASSERT(isMainThread());
if (!m_tagImpl)
return;
for (HTMLToken::AttributeList::const_iterator iter = attributes.begin(); iter != attributes.end(); ++iter) {
AtomicString attributeName(iter->name);
String attributeValue = StringImpl::create8BitIfPossible(iter->value);
processAttribute(attributeName, attributeValue);
}
}
void processAttributes(const Vector<CompactHTMLToken::Attribute>& attributes)
{
if (!m_tagImpl)
return;
for (Vector<CompactHTMLToken::Attribute>::const_iterator iter = attributes.begin(); iter != attributes.end(); ++iter)
processAttribute(iter->name, iter->value);
}
PassOwnPtr<PreloadRequest> createPreloadRequest(const KURL& predictedBaseURL, const SegmentedString& source)
{
if (!shouldPreload() || !m_matchedMediaAttribute)
return nullptr;
TRACE_EVENT_INSTANT1("net", "PreloadRequest", "url", m_urlToLoad.ascii());
TextPosition position = TextPosition(source.currentLine(), source.currentColumn());
OwnPtr<PreloadRequest> request = PreloadRequest::create(initiatorFor(m_tagImpl), position, m_urlToLoad, predictedBaseURL, resourceType());
if (isCORSEnabled())
request->setCrossOriginEnabled(allowStoredCredentials());
request->setCharset(charset());
return request.release();
}
private:
template<typename NameType>
void processAttribute(const NameType& attributeName, const String& attributeValue)
{
if (match(attributeName, charsetAttr))
m_charset = attributeValue;
if (match(m_tagImpl, scriptTag)) {
if (match(attributeName, srcAttr))
setUrlToLoad(attributeValue, DisallowURLReplacement);
else if (match(attributeName, crossoriginAttr))
setCrossOriginAllowed(attributeValue);
} else if (match(m_tagImpl, imgTag)) {
if (match(attributeName, srcAttr) && !m_encounteredImgSrc) {
m_encounteredImgSrc = true;
setUrlToLoad(bestFitSourceForImageAttributes(m_mediaValues->devicePixelRatio(), attributeValue, m_srcsetImageCandidate), AllowURLReplacement);
} else if (match(attributeName, crossoriginAttr)) {
setCrossOriginAllowed(attributeValue);
} else if (RuntimeEnabledFeatures::srcsetEnabled()
&& match(attributeName, srcsetAttr)
&& m_srcsetImageCandidate.isEmpty()) {
m_srcsetImageCandidate = bestFitSourceForSrcsetAttribute(m_mediaValues->devicePixelRatio(), attributeValue);
setUrlToLoad(bestFitSourceForImageAttributes(m_mediaValues->devicePixelRatio(), m_urlToLoad, m_srcsetImageCandidate), AllowURLReplacement);
}
} else if (match(m_tagImpl, linkTag)) {
if (match(attributeName, hrefAttr))
setUrlToLoad(attributeValue, DisallowURLReplacement);
else if (match(attributeName, relAttr))
m_linkIsStyleSheet = relAttributeIsStyleSheet(attributeValue);
else if (match(attributeName, mediaAttr))
m_matchedMediaAttribute = mediaAttributeMatches(*m_mediaValues, attributeValue);
else if (match(attributeName, crossoriginAttr))
setCrossOriginAllowed(attributeValue);
} else if (match(m_tagImpl, inputTag)) {
if (match(attributeName, srcAttr))
setUrlToLoad(attributeValue, DisallowURLReplacement);
else if (match(attributeName, typeAttr))
m_inputIsImage = equalIgnoringCase(attributeValue, InputTypeNames::image);
}
}
static bool relAttributeIsStyleSheet(const String& attributeValue)
{
LinkRelAttribute rel(attributeValue);
return rel.isStyleSheet() && !rel.isAlternate() && rel.iconType() == InvalidIcon && !rel.isDNSPrefetch();
}
void setUrlToLoad(const String& value, URLReplacement replacement)
{
// We only respect the first src/href, per HTML5:
// http://www.whatwg.org/specs/web-apps/current-work/multipage/tokenization.html#attribute-name-state
if (replacement == DisallowURLReplacement && !m_urlToLoad.isEmpty())
return;
String url = stripLeadingAndTrailingHTMLSpaces(value);
if (url.isEmpty())
return;
m_urlToLoad = url;
}
const String& charset() const
{
// FIXME: Its not clear that this if is needed, the loader probably ignores charset for image requests anyway.
if (match(m_tagImpl, imgTag))
return emptyString();
return m_charset;
}
Resource::Type resourceType() const
{
if (match(m_tagImpl, scriptTag))
return Resource::Script;
if (match(m_tagImpl, imgTag) || (match(m_tagImpl, inputTag) && m_inputIsImage))
return Resource::Image;
if (match(m_tagImpl, linkTag) && m_linkIsStyleSheet)
return Resource::CSSStyleSheet;
ASSERT_NOT_REACHED();
return Resource::Raw;
}
bool shouldPreload() const
{
if (m_urlToLoad.isEmpty())
return false;
if (match(m_tagImpl, linkTag) && !m_linkIsStyleSheet)
return false;
if (match(m_tagImpl, inputTag) && !m_inputIsImage)
return false;
return true;
}
bool isCORSEnabled() const
{
return m_isCORSEnabled;
}
StoredCredentials allowStoredCredentials() const
{
return m_allowCredentials;
}
void setCrossOriginAllowed(const String& corsSetting)
{
m_isCORSEnabled = true;
if (!corsSetting.isNull() && equalIgnoringCase(stripLeadingAndTrailingHTMLSpaces(corsSetting), "use-credentials"))
m_allowCredentials = AllowStoredCredentials;
else
m_allowCredentials = DoNotAllowStoredCredentials;
}
const StringImpl* m_tagImpl;
String m_urlToLoad;
ImageCandidate m_srcsetImageCandidate;
String m_charset;
bool m_linkIsStyleSheet;
bool m_matchedMediaAttribute;
bool m_inputIsImage;
bool m_encounteredImgSrc;
bool m_isCORSEnabled;
StoredCredentials m_allowCredentials;
RefPtr<MediaValues> m_mediaValues;
};
TokenPreloadScanner::TokenPreloadScanner(const KURL& documentURL, PassRefPtr<MediaValues> mediaValues)
: m_documentURL(documentURL)
, m_inStyle(false)
, m_templateCount(0)
, m_mediaValues(mediaValues)
{
}
TokenPreloadScanner::~TokenPreloadScanner()
{
}
TokenPreloadScannerCheckpoint TokenPreloadScanner::createCheckpoint()
{
TokenPreloadScannerCheckpoint checkpoint = m_checkpoints.size();
m_checkpoints.append(Checkpoint(m_predictedBaseElementURL, m_inStyle, m_templateCount));
return checkpoint;
}
void TokenPreloadScanner::rewindTo(TokenPreloadScannerCheckpoint checkpointIndex)
{
ASSERT(checkpointIndex < m_checkpoints.size()); // If this ASSERT fires, checkpointIndex is invalid.
const Checkpoint& checkpoint = m_checkpoints[checkpointIndex];
m_predictedBaseElementURL = checkpoint.predictedBaseElementURL;
m_inStyle = checkpoint.inStyle;
m_templateCount = checkpoint.templateCount;
m_cssScanner.reset();
m_checkpoints.clear();
}
void TokenPreloadScanner::scan(const HTMLToken& token, const SegmentedString& source, PreloadRequestStream& requests)
{
scanCommon(token, source, requests);
}
void TokenPreloadScanner::scan(const CompactHTMLToken& token, const SegmentedString& source, PreloadRequestStream& requests)
{
scanCommon(token, source, requests);
}
template<typename Token>
void TokenPreloadScanner::scanCommon(const Token& token, const SegmentedString& source, PreloadRequestStream& requests)
{
switch (token.type()) {
case HTMLToken::Character: {
if (!m_inStyle)
return;
m_cssScanner.scan(token.data(), source, requests);
return;
}
case HTMLToken::EndTag: {
const StringImpl* tagImpl = tagImplFor(token.data());
if (match(tagImpl, templateTag)) {
if (m_templateCount)
--m_templateCount;
return;
}
if (match(tagImpl, styleTag)) {
if (m_inStyle)
m_cssScanner.reset();
m_inStyle = false;
}
return;
}
case HTMLToken::StartTag: {
if (m_templateCount)
return;
const StringImpl* tagImpl = tagImplFor(token.data());
if (match(tagImpl, templateTag)) {
++m_templateCount;
return;
}
if (match(tagImpl, styleTag)) {
m_inStyle = true;
return;
}
if (match(tagImpl, baseTag)) {
// The first <base> element is the one that wins.
if (!m_predictedBaseElementURL.isEmpty())
return;
updatePredictedBaseURL(token);
return;
}
StartTagScanner scanner(tagImpl, m_mediaValues);
scanner.processAttributes(token.attributes());
OwnPtr<PreloadRequest> request = scanner.createPreloadRequest(m_predictedBaseElementURL, source);
if (request)
requests.append(request.release());
return;
}
default: {
return;
}
}
}
template<typename Token>
void TokenPreloadScanner::updatePredictedBaseURL(const Token& token)
{
ASSERT(m_predictedBaseElementURL.isEmpty());
if (const typename Token::Attribute* hrefAttribute = token.getAttributeItem(hrefAttr))
m_predictedBaseElementURL = KURL(m_documentURL, stripLeadingAndTrailingHTMLSpaces(hrefAttribute->value)).copy();
}
HTMLPreloadScanner::HTMLPreloadScanner(const HTMLParserOptions& options, const KURL& documentURL, PassRefPtr<MediaValues> mediaValues)
: m_scanner(documentURL, mediaValues)
, m_tokenizer(HTMLTokenizer::create(options))
{
}
HTMLPreloadScanner::~HTMLPreloadScanner()
{
}
void HTMLPreloadScanner::appendToEnd(const SegmentedString& source)
{
m_source.append(source);
}
void HTMLPreloadScanner::scan(HTMLResourcePreloader* preloader, const KURL& startingBaseElementURL)
{
ASSERT(isMainThread()); // HTMLTokenizer::updateStateFor only works on the main thread.
// When we start scanning, our best prediction of the baseElementURL is the real one!
if (!startingBaseElementURL.isEmpty())
m_scanner.setPredictedBaseElementURL(startingBaseElementURL);
PreloadRequestStream requests;
while (m_tokenizer->nextToken(m_source, m_token)) {
if (m_token.type() == HTMLToken::StartTag)
m_tokenizer->updateStateFor(attemptStaticStringCreation(m_token.name(), Likely8Bit));
m_scanner.scan(m_token, m_source, requests);
m_token.clear();
}
preloader->takeAndPreload(requests);
}
}
<|endoftext|> |
<commit_before>/*
* Copyright (C) 2006, 2007 Apple Computer, Inc.
* Copyright (c) 2006, 2007, 2008, 2009, 2012 Google Inc. All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are
* met:
*
* * Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* * 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 Google Inc. nor the names of its
* contributors may be used to endorse or promote products derived from
* this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
* "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
* LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
* A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
* OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
* SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
* LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
* DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
* THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
* OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
#include "config.h"
#include "platform/fonts/FontCache.h"
#include "SkFontMgr.h"
#include "SkTypeface_win.h"
#include "platform/RuntimeEnabledFeatures.h"
#include "platform/fonts/FontDescription.h"
#include "platform/fonts/FontFaceCreationParams.h"
#include "platform/fonts/SimpleFontData.h"
#include "platform/fonts/harfbuzz/FontPlatformDataHarfbuzz.h"
#include "platform/fonts/win/FontFallbackWin.h"
namespace blink {
HashMap<String, RefPtr<SkTypeface> >* FontCache::s_sideloadedFonts = 0;
// static
void FontCache::addSideloadedFontForTesting(SkTypeface* typeface)
{
if (!typeface)
return;
if (!s_sideloadedFonts)
s_sideloadedFonts = new HashMap<String, RefPtr<SkTypeface> >;
SkString name;
typeface->getFamilyName(&name);
s_sideloadedFonts->set(name.c_str(), typeface);
}
FontCache::FontCache()
: m_purgePreventCount(0)
{
SkFontMgr* fontManager;
if (s_useDirectWrite) {
fontManager = SkFontMgr_New_DirectWrite(s_directWriteFactory);
s_useSubpixelPositioning = RuntimeEnabledFeatures::subpixelFontScalingEnabled();
} else {
fontManager = SkFontMgr_New_GDI();
// Subpixel text positioning is not supported by the GDI backend.
s_useSubpixelPositioning = false;
}
ASSERT(fontManager);
m_fontManager = adoptPtr(fontManager);
}
// Given the desired base font, this will create a SimpleFontData for a specific
// font that can be used to render the given range of characters.
PassRefPtr<SimpleFontData> FontCache::fallbackFontForCharacter(const FontDescription& fontDescription, UChar32 character, const SimpleFontData*)
{
// First try the specified font with standard style & weight.
if (fontDescription.style() == FontStyleItalic
|| fontDescription.weight() >= FontWeightBold) {
RefPtr<SimpleFontData> fontData = fallbackOnStandardFontStyle(
fontDescription, character);
if (fontData)
return fontData;
}
// FIXME: Consider passing fontDescription.dominantScript()
// to GetFallbackFamily here.
UScriptCode script;
const wchar_t* family = getFallbackFamily(character,
fontDescription.genericFamily(),
&script,
m_fontManager.get());
FontPlatformData* data = 0;
if (family) {
FontFaceCreationParams createByFamily(AtomicString(family, wcslen(family)));
data = getFontPlatformData(fontDescription, createByFamily);
}
// Last resort font list : PanUnicode. CJK fonts have a pretty
// large repertoire. Eventually, we need to scan all the fonts
// on the system to have a Firefox-like coverage.
// Make sure that all of them are lowercased.
const static wchar_t* const cjkFonts[] = {
L"arial unicode ms",
L"ms pgothic",
L"simsun",
L"gulim",
L"pmingliu",
L"wenquanyi zen hei", // Partial CJK Ext. A coverage but more widely known to Chinese users.
L"ar pl shanheisun uni",
L"ar pl zenkai uni",
L"han nom a", // Complete CJK Ext. A coverage.
L"code2000" // Complete CJK Ext. A coverage.
// CJK Ext. B fonts are not listed here because it's of no use
// with our current non-BMP character handling because we use
// Uniscribe for it and that code path does not go through here.
};
const static wchar_t* const commonFonts[] = {
L"tahoma",
L"arial unicode ms",
L"lucida sans unicode",
L"microsoft sans serif",
L"palatino linotype",
// Six fonts below (and code2000 at the end) are not from MS, but
// once installed, cover a very wide range of characters.
L"dejavu serif",
L"dejavu sasns",
L"freeserif",
L"freesans",
L"gentium",
L"gentiumalt",
L"ms pgothic",
L"simsun",
L"gulim",
L"pmingliu",
L"code2000"
};
const wchar_t* const* panUniFonts = 0;
int numFonts = 0;
if (script == USCRIPT_HAN) {
panUniFonts = cjkFonts;
numFonts = WTF_ARRAY_LENGTH(cjkFonts);
} else {
panUniFonts = commonFonts;
numFonts = WTF_ARRAY_LENGTH(commonFonts);
}
// Font returned from getFallbackFamily may not cover |character|
// because it's based on script to font mapping. This problem is
// critical enough for non-Latin scripts (especially Han) to
// warrant an additional (real coverage) check with fontCotainsCharacter.
int i;
for (i = 0; (!data || !data->fontContainsCharacter(character)) && i < numFonts; ++i) {
family = panUniFonts[i];
FontFaceCreationParams createByFamily(AtomicString(family, wcslen(family)));
data = getFontPlatformData(fontDescription, createByFamily);
}
// When i-th font (0-base) in |panUniFonts| contains a character and
// we get out of the loop, |i| will be |i + 1|. That is, if only the
// last font in the array covers the character, |i| will be numFonts.
// So, we have to use '<=" rather than '<' to see if we found a font
// covering the character.
if (i <= numFonts)
return fontDataFromFontPlatformData(data, DoNotRetain);
return nullptr;
}
static inline bool equalIgnoringCase(const AtomicString& a, const SkString& b)
{
return equalIgnoringCase(a, AtomicString::fromUTF8(b.c_str()));
}
static bool typefacesMatchesFamily(const SkTypeface* tf, const AtomicString& family)
{
SkTypeface::LocalizedStrings* actualFamilies = tf->createFamilyNameIterator();
bool matchesRequestedFamily = false;
SkTypeface::LocalizedString actualFamily;
while (actualFamilies->next(&actualFamily)) {
if (equalIgnoringCase(family, actualFamily.fString)) {
matchesRequestedFamily = true;
break;
}
}
actualFamilies->unref();
// getFamilyName may return a name not returned by the createFamilyNameIterator.
// Specifically in cases where Windows substitutes the font based on the
// HKLM\SOFTWARE\Microsoft\Windows NT\CurrentVersion\FontSubstitutes registry entries.
if (!matchesRequestedFamily) {
SkString familyName;
tf->getFamilyName(&familyName);
if (equalIgnoringCase(family, familyName))
matchesRequestedFamily = true;
}
return matchesRequestedFamily;
}
static bool typefacesHasVariantSuffix(const AtomicString& family,
AtomicString& adjustedName, FontWeight& variantWeight)
{
struct FamilyVariantSuffix {
const wchar_t* suffix;
size_t length;
FontWeight weight;
};
// Mapping from suffix to weight from the DirectWrite documentation.
// http://msdn.microsoft.com/en-us/library/windows/desktop/dd368082(v=vs.85).aspx
const static FamilyVariantSuffix variantForSuffix[] = {
{ L" thin", 5, FontWeight100 },
{ L" extralight", 11, FontWeight200 },
{ L" ultralight", 11, FontWeight200 },
{ L" light", 6, FontWeight300 },
{ L" medium", 7, FontWeight500 },
{ L" demibold", 9, FontWeight600 },
{ L" semibold", 9, FontWeight600 },
{ L" extrabold", 10, FontWeight800 },
{ L" ultrabold", 10, FontWeight800 },
{ L" black", 6, FontWeight900 },
{ L" heavy", 6, FontWeight900 }
};
size_t numVariants = WTF_ARRAY_LENGTH(variantForSuffix);
bool caseSensitive = false;
for (size_t i = 0; i < numVariants; i++) {
const FamilyVariantSuffix& entry = variantForSuffix[i];
if (family.endsWith(entry.suffix, caseSensitive)) {
String familyName = family.string();
familyName.truncate(family.length() - entry.length);
adjustedName = AtomicString(familyName);
variantWeight = entry.weight;
return true;
}
}
return false;
}
FontPlatformData* FontCache::createFontPlatformData(const FontDescription& fontDescription, const FontFaceCreationParams& creationParams, float fontSize)
{
ASSERT(creationParams.creationType() == CreateFontByFamily);
CString name;
RefPtr<SkTypeface> tf = createTypeface(fontDescription, creationParams, name);
// Windows will always give us a valid pointer here, even if the face name
// is non-existent. We have to double-check and see if the family name was
// really used.
if (!tf || !typefacesMatchesFamily(tf.get(), creationParams.family())) {
AtomicString adjustedName;
FontWeight variantWeight;
if (typefacesHasVariantSuffix(creationParams.family(), adjustedName,
variantWeight)) {
FontFaceCreationParams adjustedParams(adjustedName);
FontDescription adjustedFontDescription = fontDescription;
adjustedFontDescription.setWeight(variantWeight);
tf = createTypeface(adjustedFontDescription, adjustedParams, name);
if (!tf || !typefacesMatchesFamily(tf.get(), adjustedName))
return 0;
} else {
return 0;
}
}
FontPlatformData* result = new FontPlatformData(tf,
name.data(),
fontSize,
fontDescription.weight() >= FontWeight600 && !tf->isBold() || fontDescription.isSyntheticBold(),
fontDescription.style() == FontStyleItalic && !tf->isItalic() || fontDescription.isSyntheticItalic(),
fontDescription.orientation(),
s_useSubpixelPositioning);
struct FamilyMinSize {
const wchar_t* family;
unsigned minSize;
};
const static FamilyMinSize minAntiAliasSizeForFont[] = {
{ L"simsun", 11 },
{ L"dotum", 12 },
{ L"gulim", 12 },
{ L"pmingliu", 11 }
};
size_t numFonts = WTF_ARRAY_LENGTH(minAntiAliasSizeForFont);
for (size_t i = 0; i < numFonts; i++) {
FamilyMinSize entry = minAntiAliasSizeForFont[i];
if (typefacesMatchesFamily(tf.get(), entry.family)) {
result->setMinSizeForAntiAlias(entry.minSize);
break;
}
}
// List of fonts that look bad with subpixel text rendering at smaller font
// sizes. This includes all fonts in the Microsoft Core fonts for the Web
// collection.
const static wchar_t* noSubpixelForSmallSizeFont[] = {
L"andale mono",
L"arial",
L"comic sans",
L"courier new",
L"georgia",
L"impact",
L"lucida console",
L"tahoma",
L"times new roman",
L"trebuchet ms",
L"verdana",
L"webdings"
};
const static float minSizeForSubpixelForFont = 16.0f;
numFonts = WTF_ARRAY_LENGTH(noSubpixelForSmallSizeFont);
for (size_t i = 0; i < numFonts; i++) {
const wchar_t* family = noSubpixelForSmallSizeFont[i];
if (typefacesMatchesFamily(tf.get(), family)) {
result->setMinSizeForSubpixel(minSizeForSubpixelForFont);
break;
}
}
return result;
}
} // namespace blink
<commit_msg>Revert 181532 "Gardening: Fix tests failing on Win7(dbg) caused ..."<commit_after>/*
* Copyright (C) 2006, 2007 Apple Computer, Inc.
* Copyright (c) 2006, 2007, 2008, 2009, 2012 Google Inc. All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are
* met:
*
* * Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* * 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 Google Inc. nor the names of its
* contributors may be used to endorse or promote products derived from
* this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
* "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
* LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
* A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
* OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
* SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
* LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
* DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
* THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
* OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
#include "config.h"
#include "platform/fonts/FontCache.h"
#include "SkFontMgr.h"
#include "SkTypeface_win.h"
#include "platform/RuntimeEnabledFeatures.h"
#include "platform/fonts/FontDescription.h"
#include "platform/fonts/FontFaceCreationParams.h"
#include "platform/fonts/SimpleFontData.h"
#include "platform/fonts/harfbuzz/FontPlatformDataHarfbuzz.h"
#include "platform/fonts/win/FontFallbackWin.h"
namespace blink {
HashMap<String, RefPtr<SkTypeface> >* FontCache::s_sideloadedFonts = 0;
// static
void FontCache::addSideloadedFontForTesting(SkTypeface* typeface)
{
if (!s_sideloadedFonts)
s_sideloadedFonts = new HashMap<String, RefPtr<SkTypeface> >;
SkString name;
typeface->getFamilyName(&name);
s_sideloadedFonts->set(name.c_str(), typeface);
}
FontCache::FontCache()
: m_purgePreventCount(0)
{
SkFontMgr* fontManager;
if (s_useDirectWrite) {
fontManager = SkFontMgr_New_DirectWrite(s_directWriteFactory);
s_useSubpixelPositioning = RuntimeEnabledFeatures::subpixelFontScalingEnabled();
} else {
fontManager = SkFontMgr_New_GDI();
// Subpixel text positioning is not supported by the GDI backend.
s_useSubpixelPositioning = false;
}
ASSERT(fontManager);
m_fontManager = adoptPtr(fontManager);
}
// Given the desired base font, this will create a SimpleFontData for a specific
// font that can be used to render the given range of characters.
PassRefPtr<SimpleFontData> FontCache::fallbackFontForCharacter(const FontDescription& fontDescription, UChar32 character, const SimpleFontData*)
{
// First try the specified font with standard style & weight.
if (fontDescription.style() == FontStyleItalic
|| fontDescription.weight() >= FontWeightBold) {
RefPtr<SimpleFontData> fontData = fallbackOnStandardFontStyle(
fontDescription, character);
if (fontData)
return fontData;
}
// FIXME: Consider passing fontDescription.dominantScript()
// to GetFallbackFamily here.
UScriptCode script;
const wchar_t* family = getFallbackFamily(character,
fontDescription.genericFamily(),
&script,
m_fontManager.get());
FontPlatformData* data = 0;
if (family) {
FontFaceCreationParams createByFamily(AtomicString(family, wcslen(family)));
data = getFontPlatformData(fontDescription, createByFamily);
}
// Last resort font list : PanUnicode. CJK fonts have a pretty
// large repertoire. Eventually, we need to scan all the fonts
// on the system to have a Firefox-like coverage.
// Make sure that all of them are lowercased.
const static wchar_t* const cjkFonts[] = {
L"arial unicode ms",
L"ms pgothic",
L"simsun",
L"gulim",
L"pmingliu",
L"wenquanyi zen hei", // Partial CJK Ext. A coverage but more widely known to Chinese users.
L"ar pl shanheisun uni",
L"ar pl zenkai uni",
L"han nom a", // Complete CJK Ext. A coverage.
L"code2000" // Complete CJK Ext. A coverage.
// CJK Ext. B fonts are not listed here because it's of no use
// with our current non-BMP character handling because we use
// Uniscribe for it and that code path does not go through here.
};
const static wchar_t* const commonFonts[] = {
L"tahoma",
L"arial unicode ms",
L"lucida sans unicode",
L"microsoft sans serif",
L"palatino linotype",
// Six fonts below (and code2000 at the end) are not from MS, but
// once installed, cover a very wide range of characters.
L"dejavu serif",
L"dejavu sasns",
L"freeserif",
L"freesans",
L"gentium",
L"gentiumalt",
L"ms pgothic",
L"simsun",
L"gulim",
L"pmingliu",
L"code2000"
};
const wchar_t* const* panUniFonts = 0;
int numFonts = 0;
if (script == USCRIPT_HAN) {
panUniFonts = cjkFonts;
numFonts = WTF_ARRAY_LENGTH(cjkFonts);
} else {
panUniFonts = commonFonts;
numFonts = WTF_ARRAY_LENGTH(commonFonts);
}
// Font returned from getFallbackFamily may not cover |character|
// because it's based on script to font mapping. This problem is
// critical enough for non-Latin scripts (especially Han) to
// warrant an additional (real coverage) check with fontCotainsCharacter.
int i;
for (i = 0; (!data || !data->fontContainsCharacter(character)) && i < numFonts; ++i) {
family = panUniFonts[i];
FontFaceCreationParams createByFamily(AtomicString(family, wcslen(family)));
data = getFontPlatformData(fontDescription, createByFamily);
}
// When i-th font (0-base) in |panUniFonts| contains a character and
// we get out of the loop, |i| will be |i + 1|. That is, if only the
// last font in the array covers the character, |i| will be numFonts.
// So, we have to use '<=" rather than '<' to see if we found a font
// covering the character.
if (i <= numFonts)
return fontDataFromFontPlatformData(data, DoNotRetain);
return nullptr;
}
static inline bool equalIgnoringCase(const AtomicString& a, const SkString& b)
{
return equalIgnoringCase(a, AtomicString::fromUTF8(b.c_str()));
}
static bool typefacesMatchesFamily(const SkTypeface* tf, const AtomicString& family)
{
SkTypeface::LocalizedStrings* actualFamilies = tf->createFamilyNameIterator();
bool matchesRequestedFamily = false;
SkTypeface::LocalizedString actualFamily;
while (actualFamilies->next(&actualFamily)) {
if (equalIgnoringCase(family, actualFamily.fString)) {
matchesRequestedFamily = true;
break;
}
}
actualFamilies->unref();
// getFamilyName may return a name not returned by the createFamilyNameIterator.
// Specifically in cases where Windows substitutes the font based on the
// HKLM\SOFTWARE\Microsoft\Windows NT\CurrentVersion\FontSubstitutes registry entries.
if (!matchesRequestedFamily) {
SkString familyName;
tf->getFamilyName(&familyName);
if (equalIgnoringCase(family, familyName))
matchesRequestedFamily = true;
}
return matchesRequestedFamily;
}
static bool typefacesHasVariantSuffix(const AtomicString& family,
AtomicString& adjustedName, FontWeight& variantWeight)
{
struct FamilyVariantSuffix {
const wchar_t* suffix;
size_t length;
FontWeight weight;
};
// Mapping from suffix to weight from the DirectWrite documentation.
// http://msdn.microsoft.com/en-us/library/windows/desktop/dd368082(v=vs.85).aspx
const static FamilyVariantSuffix variantForSuffix[] = {
{ L" thin", 5, FontWeight100 },
{ L" extralight", 11, FontWeight200 },
{ L" ultralight", 11, FontWeight200 },
{ L" light", 6, FontWeight300 },
{ L" medium", 7, FontWeight500 },
{ L" demibold", 9, FontWeight600 },
{ L" semibold", 9, FontWeight600 },
{ L" extrabold", 10, FontWeight800 },
{ L" ultrabold", 10, FontWeight800 },
{ L" black", 6, FontWeight900 },
{ L" heavy", 6, FontWeight900 }
};
size_t numVariants = WTF_ARRAY_LENGTH(variantForSuffix);
bool caseSensitive = false;
for (size_t i = 0; i < numVariants; i++) {
const FamilyVariantSuffix& entry = variantForSuffix[i];
if (family.endsWith(entry.suffix, caseSensitive)) {
String familyName = family.string();
familyName.truncate(family.length() - entry.length);
adjustedName = AtomicString(familyName);
variantWeight = entry.weight;
return true;
}
}
return false;
}
FontPlatformData* FontCache::createFontPlatformData(const FontDescription& fontDescription, const FontFaceCreationParams& creationParams, float fontSize)
{
ASSERT(creationParams.creationType() == CreateFontByFamily);
CString name;
RefPtr<SkTypeface> tf = createTypeface(fontDescription, creationParams, name);
// Windows will always give us a valid pointer here, even if the face name
// is non-existent. We have to double-check and see if the family name was
// really used.
if (!tf || !typefacesMatchesFamily(tf.get(), creationParams.family())) {
AtomicString adjustedName;
FontWeight variantWeight;
if (typefacesHasVariantSuffix(creationParams.family(), adjustedName,
variantWeight)) {
FontFaceCreationParams adjustedParams(adjustedName);
FontDescription adjustedFontDescription = fontDescription;
adjustedFontDescription.setWeight(variantWeight);
tf = createTypeface(adjustedFontDescription, adjustedParams, name);
if (!tf || !typefacesMatchesFamily(tf.get(), adjustedName))
return 0;
} else {
return 0;
}
}
FontPlatformData* result = new FontPlatformData(tf,
name.data(),
fontSize,
fontDescription.weight() >= FontWeight600 && !tf->isBold() || fontDescription.isSyntheticBold(),
fontDescription.style() == FontStyleItalic && !tf->isItalic() || fontDescription.isSyntheticItalic(),
fontDescription.orientation(),
s_useSubpixelPositioning);
struct FamilyMinSize {
const wchar_t* family;
unsigned minSize;
};
const static FamilyMinSize minAntiAliasSizeForFont[] = {
{ L"simsun", 11 },
{ L"dotum", 12 },
{ L"gulim", 12 },
{ L"pmingliu", 11 }
};
size_t numFonts = WTF_ARRAY_LENGTH(minAntiAliasSizeForFont);
for (size_t i = 0; i < numFonts; i++) {
FamilyMinSize entry = minAntiAliasSizeForFont[i];
if (typefacesMatchesFamily(tf.get(), entry.family)) {
result->setMinSizeForAntiAlias(entry.minSize);
break;
}
}
// List of fonts that look bad with subpixel text rendering at smaller font
// sizes. This includes all fonts in the Microsoft Core fonts for the Web
// collection.
const static wchar_t* noSubpixelForSmallSizeFont[] = {
L"andale mono",
L"arial",
L"comic sans",
L"courier new",
L"georgia",
L"impact",
L"lucida console",
L"tahoma",
L"times new roman",
L"trebuchet ms",
L"verdana",
L"webdings"
};
const static float minSizeForSubpixelForFont = 16.0f;
numFonts = WTF_ARRAY_LENGTH(noSubpixelForSmallSizeFont);
for (size_t i = 0; i < numFonts; i++) {
const wchar_t* family = noSubpixelForSmallSizeFont[i];
if (typefacesMatchesFamily(tf.get(), family)) {
result->setMinSizeForSubpixel(minSizeForSubpixelForFont);
break;
}
}
return result;
}
} // namespace blink
<|endoftext|> |
<commit_before>#include "keys.hh"
#include <unordered_map>
namespace Kakoune
{
static std::unordered_map<String, Character> keynamemap = {
{ "ret", '\n' },
{ "space", ' ' },
{ "esc", 27 }
};
KeyList parse_keys(const String& str)
{
KeyList result;
for (CharCount pos = 0; pos < str.length(); ++pos)
{
if (str[pos] == '<')
{
CharCount end_pos = pos;
while (end_pos < str.length() and str[end_pos] != '>')
++end_pos;
if (end_pos < str.length())
{
Key::Modifiers modifier = Key::Modifiers::None;
String keyname = str.substr(pos+1, end_pos - pos - 1);
if (keyname.length() > 2)
{
if (tolower(keyname[0]) == 'c' and keyname[1] == '-')
{
modifier = Key::Modifiers::Control;
keyname = keyname.substr(2);
}
if (tolower(keyname[0]) == 'a' and keyname[1] == '-')
{
modifier = Key::Modifiers::Alt;
keyname = keyname.substr(2);
}
}
if (keyname.length() == 1)
{
result.push_back(Key{ modifier, keyname[0] });
pos = end_pos;
continue;
}
auto it = keynamemap.find(keyname);
if (it != keynamemap.end())
{
result.push_back(Key{ modifier, it->second });
pos = end_pos;
continue;
}
}
}
result.push_back({Key::Modifiers::None, str[pos]});
}
return result;
}
}
<commit_msg>fix control key parsing<commit_after>#include "keys.hh"
#include <unordered_map>
namespace Kakoune
{
Key canonicalize_ifn(Key key)
{
if (key.key > 0 and key.key < 27)
{
assert(key.modifiers == Key::Modifiers::None);
key.modifiers = Key::Modifiers::Control;
key.key = key.key - 1 + 'a';
}
return key;
}
static std::unordered_map<String, Character> keynamemap = {
{ "ret", '\r' },
{ "space", ' ' },
{ "esc", 27 }
};
KeyList parse_keys(const String& str)
{
KeyList result;
for (CharCount pos = 0; pos < str.length(); ++pos)
{
if (str[pos] == '<')
{
CharCount end_pos = pos;
while (end_pos < str.length() and str[end_pos] != '>')
++end_pos;
if (end_pos < str.length())
{
Key::Modifiers modifier = Key::Modifiers::None;
String keyname = str.substr(pos+1, end_pos - pos - 1);
if (keyname.length() > 2)
{
if (tolower(keyname[0]) == 'c' and keyname[1] == '-')
{
modifier = Key::Modifiers::Control;
keyname = keyname.substr(2);
}
if (tolower(keyname[0]) == 'a' and keyname[1] == '-')
{
modifier = Key::Modifiers::Alt;
keyname = keyname.substr(2);
}
}
if (keyname.length() == 1)
{
result.push_back(Key{ modifier, keyname[0] });
pos = end_pos;
continue;
}
auto it = keynamemap.find(keyname);
if (it != keynamemap.end())
{
Key key = canonicalize_ifn(Key{ modifier, it->second });
result.push_back(key);
pos = end_pos;
continue;
}
}
}
result.push_back({Key::Modifiers::None, str[pos]});
}
return result;
}
}
<|endoftext|> |
<commit_before>// RUN: cat %s | %cling | FileCheck %s
int a = 12;
a // CHECK: (int) 12
const char* b = "b" // CHECK: (const char *) "b"
struct C {int d;} E = {22};
E // CHECK: (struct C) @0x{{[0-9A-Fa-f].*}}
E.d // CHECK: (int) 22
#include <string>
std::string s("xyz")
// CHECK: (std::string) @0x{{[0-9A-Fa-f]{8,}.}}
// CHECK: c_str: "xyz"
class Outer {
public:
struct Inner {
enum E{
// Note max and min ints are platform dependent since we cannot use
//limits.h
A = 2147483647,
B = 2,
C = 2,
D = -2147483648
} ABC;
};
};
Outer::Inner::C
// CHECK: (enum Outer::Inner::E const) @0x{{[0-9A-Fa-f].*}}
// CHECK: (Outer::Inner::E::B) ? (Outer::Inner::E::C) : (int) 2
Outer::Inner::D
// CHECK: (enum Outer::Inner::E const) @0x{{[0-9A-Fa-f].*}}
// CHECK: (Outer::Inner::E::D) : (int) -2147483648
.q
<commit_msg>Test it in language-independent way<commit_after>// RUN: cat %s | %cling | FileCheck %s
int a = 12;
a // CHECK: (int) 12
const char* b = "b" // CHECK: (const char *) "b"
struct C {int d;} E = {22};
E // CHECK: (struct C) @0x{{[0-9A-Fa-f].*}}
E.d // CHECK: (int) 22
#include <string>
std::string s("xyz")
// CHECK: (std::string) @0x{{[0-9A-Fa-f]{8,}.}}
// CHECK: c_str: "xyz"
#include <limits.h>
class Outer {
public:
struct Inner {
enum E{
A = INT_MAX,
B = 2,
C = 2,
D = INT_MIN
} ABC;
};
};
Outer::Inner::C
// CHECK: (enum Outer::Inner::E const) @0x{{[0-9A-Fa-f].*}}
// CHECK: (Outer::Inner::E::B) ? (Outer::Inner::E::C) : (int) {{[0-9].*}}
Outer::Inner::D
// CHECK: (enum Outer::Inner::E const) @0x{{[0-9A-Fa-f].*}}
// CHECK: (Outer::Inner::E::D) : (int) -{{[0-9].*}}
.q
<|endoftext|> |
<commit_before>#include "Runtime/GuiSys/CSplashScreen.hpp"
#include "Runtime/CArchitectureMessage.hpp"
#include "Runtime/CArchitectureQueue.hpp"
#include "Runtime/CSimplePool.hpp"
#include "Runtime/GameGlobalObjects.hpp"
#include "Runtime/Camera/CCameraFilter.hpp"
namespace urde {
static const char* SplashTextures[]{"TXTR_NintendoLogo", "TXTR_RetroLogo", "TXTR_DolbyLogo"};
CSplashScreen::CSplashScreen(ESplashScreen which)
: CIOWin("SplashScreen")
, x14_which(which)
, m_quad(EFilterType::Blend, g_SimplePool->GetObj(SplashTextures[int(which)])) {}
CIOWin::EMessageReturn CSplashScreen::OnMessage(const CArchitectureMessage& msg, CArchitectureQueue& queue) {
switch (msg.GetType()) {
case EArchMsgType::TimerTick: {
if (!x25_textureLoaded) {
if (!m_quad.GetTex().IsLoaded())
return EMessageReturn::Exit;
x25_textureLoaded = true;
}
float dt = MakeMsg::GetParmTimerTick(msg).x4_parm;
x18_splashTimeout -= dt;
if (x18_splashTimeout <= 0.f) {
/* HACK: If we're not compiling with Intel's IPP library we want to skip the Dolby Pro Logic II logo
* This is purely a URDE addition and does not reflect retro's intentions. - Phil
*/
#if INTEL_IPP
if (x14_which != ESplashScreen::Dolby)
#else
if (x14_which != ESplashScreen::Retro)
#endif
queue.Push(MakeMsg::CreateCreateIOWin(EArchMsgTarget::IOWinManager, 9999, 9999,
std::make_shared<CSplashScreen>(ESplashScreen(int(x14_which) + 1))));
return EMessageReturn::RemoveIOWinAndExit;
}
break;
}
default:
break;
}
return EMessageReturn::Exit;
}
void CSplashScreen::Draw() {
if (!x25_textureLoaded) {
return;
}
SCOPED_GRAPHICS_DEBUG_GROUP("CSplashScreen::Draw", zeus::skGreen);
zeus::CColor color;
if (x14_which == ESplashScreen::Nintendo) {
color = zeus::CColor{0.86f, 0.f, 0.f, 1.f};
}
if (x18_splashTimeout > 1.5f) {
color.a() = 1.f - (x18_splashTimeout - 1.5f) * 2.f;
} else if (x18_splashTimeout < 0.5f) {
color.a() = x18_splashTimeout * 2.f;
}
zeus::CRectangle rect;
rect.size.x() = m_quad.GetTex()->GetWidth() / (480.f * g_Viewport.aspect);
rect.size.y() = m_quad.GetTex()->GetHeight() / 480.f;
rect.position.x() = 0.5f - rect.size.x() / 2.f;
rect.position.y() = 0.5f - rect.size.y() / 2.f;
m_quad.draw(color, 1.f, rect);
}
} // namespace urde
<commit_msg>CSplashScreen: Make use of std::array where applicable<commit_after>#include "Runtime/GuiSys/CSplashScreen.hpp"
#include <array>
#include "Runtime/CArchitectureMessage.hpp"
#include "Runtime/CArchitectureQueue.hpp"
#include "Runtime/CSimplePool.hpp"
#include "Runtime/GameGlobalObjects.hpp"
#include "Runtime/Camera/CCameraFilter.hpp"
namespace urde {
constexpr std::array SplashTextures{"TXTR_NintendoLogo"sv, "TXTR_RetroLogo"sv, "TXTR_DolbyLogo"sv};
CSplashScreen::CSplashScreen(ESplashScreen which)
: CIOWin("SplashScreen")
, x14_which(which)
, m_quad(EFilterType::Blend, g_SimplePool->GetObj(SplashTextures[size_t(which)])) {}
CIOWin::EMessageReturn CSplashScreen::OnMessage(const CArchitectureMessage& msg, CArchitectureQueue& queue) {
switch (msg.GetType()) {
case EArchMsgType::TimerTick: {
if (!x25_textureLoaded) {
if (!m_quad.GetTex().IsLoaded())
return EMessageReturn::Exit;
x25_textureLoaded = true;
}
float dt = MakeMsg::GetParmTimerTick(msg).x4_parm;
x18_splashTimeout -= dt;
if (x18_splashTimeout <= 0.f) {
/* HACK: If we're not compiling with Intel's IPP library we want to skip the Dolby Pro Logic II logo
* This is purely a URDE addition and does not reflect retro's intentions. - Phil
*/
#if INTEL_IPP
if (x14_which != ESplashScreen::Dolby)
#else
if (x14_which != ESplashScreen::Retro)
#endif
queue.Push(MakeMsg::CreateCreateIOWin(EArchMsgTarget::IOWinManager, 9999, 9999,
std::make_shared<CSplashScreen>(ESplashScreen(int(x14_which) + 1))));
return EMessageReturn::RemoveIOWinAndExit;
}
break;
}
default:
break;
}
return EMessageReturn::Exit;
}
void CSplashScreen::Draw() {
if (!x25_textureLoaded) {
return;
}
SCOPED_GRAPHICS_DEBUG_GROUP("CSplashScreen::Draw", zeus::skGreen);
zeus::CColor color;
if (x14_which == ESplashScreen::Nintendo) {
color = zeus::CColor{0.86f, 0.f, 0.f, 1.f};
}
if (x18_splashTimeout > 1.5f) {
color.a() = 1.f - (x18_splashTimeout - 1.5f) * 2.f;
} else if (x18_splashTimeout < 0.5f) {
color.a() = x18_splashTimeout * 2.f;
}
zeus::CRectangle rect;
rect.size.x() = m_quad.GetTex()->GetWidth() / (480.f * g_Viewport.aspect);
rect.size.y() = m_quad.GetTex()->GetHeight() / 480.f;
rect.position.x() = 0.5f - rect.size.x() / 2.f;
rect.position.y() = 0.5f - rect.size.y() / 2.f;
m_quad.draw(color, 1.f, rect);
}
} // namespace urde
<|endoftext|> |
<commit_before>#include <SFML\Window.hpp>
int main()
{
sf::Window window(sf::VideoMode(800, 600), "SFML works!");
while (window.isOpen())
{
sf::Event event;
while (window.pollEvent(event))
{
if (event.type == sf::Event::Closed)
window.close();
}
window.display();
}
return 0;
}<commit_msg>ADD fullscreen option for sfml window, press F atm<commit_after>#include <SFML\Window.hpp>
int main()
{
bool fullscreen = false;
sf::Window window(sf::VideoMode(800, 600), "SFML works!");
while (window.isOpen())
{
sf::Event event;
while (window.pollEvent(event))
{
if (event.type == sf::Event::Closed)
window.close();
if (event.type == sf::Event::KeyPressed) {
if (event.key.code == sf::Keyboard::F) {
window.close();
if (fullscreen) {
window.create(sf::VideoMode(800, 600), "SFML works!");
fullscreen = false;
}
else {
window.create(sf::VideoMode(800, 600), "SFML works!", sf::Style::Fullscreen);
fullscreen = true;
}
}
else if (event.key.code == sf::Keyboard::Escape) {
window.close();
}
}
}
window.display();
}
return 0;
}<|endoftext|> |
<commit_before>#include "SelectiveCDGTest.h"
#include "../PageRankNibble.h"
#include "../../community/Modularity.h"
#include "../../community/Conductance.h"
#include "../../graph/Graph.h"
#include "../../io/METISGraphReader.h"
#include "../../auxiliary/Log.h"
#ifndef NOGTEST
namespace NetworKit {
TEST_F(SCDGTest2, testPageRankNibble) {
METISGraphReader reader;
Graph G = reader.read("input/hep-th.graph");
// parameters
node seed = 50;
std::set<unsigned int> seeds = {(unsigned int) seed};
double alpha = 0.1; // loop (or teleport) probability, changed due to DGleich from: // phi * phi / (225.0 * log(100.0 * sqrt(m)));
double epsilon = 1e-5; // changed due to DGleich from: pow(2, exponent) / (48.0 * B);
PageRankNibble prn(G, alpha, epsilon);
// run PageRank-Nibble and partition the graph accordingly
DEBUG("Call PageRank-Nibble(", seed, ")");
auto partition = prn.runPartition(seeds);
EXPECT_GT(partition.numberOfSubsets(), 1u);
int cluster_size = partition.subsetSizeMap()[partition[seed]];
EXPECT_GT(cluster_size, 0u);
// evaluate result
Conductance conductance;
double targetCond = 0.4;
double cond = conductance.getQuality(partition, G);
EXPECT_LT(cond, targetCond);
INFO("Conductance of PR-Nibble: ", cond, "; seed partition size: ", cluster_size, "; number of partitions: ", partition.numberOfSubsets());
}
} /* namespace NetworKit */
#endif /*NOGTEST */
<commit_msg>Add test comparing un-/weighted PRN<commit_after>#include "SelectiveCDGTest.h"
#include "../PageRankNibble.h"
#include "../../community/Modularity.h"
#include "../../community/Conductance.h"
#include "../../graph/Graph.h"
#include "../../io/METISGraphReader.h"
#include "../../auxiliary/Log.h"
#ifndef NOGTEST
namespace NetworKit {
TEST_F(SCDGTest2, testPageRankNibble) {
METISGraphReader reader;
Graph G = reader.read("input/hep-th.graph");
// parameters
node seed = 50;
std::set<unsigned int> seeds = {(unsigned int) seed};
double alpha = 0.1; // loop (or teleport) probability, changed due to DGleich from: // phi * phi / (225.0 * log(100.0 * sqrt(m)));
double epsilon = 1e-5; // changed due to DGleich from: pow(2, exponent) / (48.0 * B);
PageRankNibble prn(G, alpha, epsilon);
// run PageRank-Nibble and partition the graph accordingly
DEBUG("Call PageRank-Nibble(", seed, ")");
auto partition = prn.runPartition(seeds);
EXPECT_GT(partition.numberOfSubsets(), 1u);
int cluster_size = partition.subsetSizeMap()[partition[seed]];
EXPECT_GT(cluster_size, 0u);
// evaluate result
Conductance conductance;
double targetCond = 0.4;
double cond = conductance.getQuality(partition, G);
EXPECT_LT(cond, targetCond);
INFO("Conductance of PR-Nibble: ", cond, "; seed partition size: ", cluster_size, "; number of partitions: ", partition.numberOfSubsets());
}
TEST_F(SCDGTest2, testWeightedPageRankNibble) {
METISGraphReader reader;
Graph wG = reader.read("input/lesmis.graph");
// parameters
node seed = 50;
std::set<unsigned int> seeds = {(unsigned int) seed};
double alpha = 0.1; // loop (or teleport) probability, changed due to DGleich from: // phi * phi / (225.0 * log(100.0 * sqrt(m)));
double epsilon = 1e-5; // changed due to DGleich from: pow(2, exponent) / (48.0 * B);
Graph G = wG.toUnweighted();
PageRankNibble prn(G, alpha, epsilon);
PageRankNibble wPrn(wG, alpha, epsilon);
// run PageRank-Nibble and partition the graph accordingly
DEBUG("Call PageRank-Nibble(", seed, ")");
auto partition = prn.runPartition(seeds);
auto wPartition = wPrn.runPartition(seeds);
EXPECT_GT(partition.numberOfSubsets(), 1u);
EXPECT_GT(wPartition.numberOfSubsets(), 1u);
int size = partition.subsetSizeMap()[partition[seed]];
int wSize = wPartition.subsetSizeMap()[wPartition[seed]];
EXPECT_GT(size, 0u);
EXPECT_GT(wSize, 0u);
EXPECT_NE(size, wSize);
// evaluate result
Conductance conductance;
double cond = conductance.getQuality(partition, G);
double wCond = conductance.getQuality(wPartition, wG);
// 80% of the time the result is better, otherwise the test fails
EXPECT_LT(wCond, cond);
INFO(wCond);
INFO("Conductance of weighted PR-Nibble: ", wCond, "; unweighted: ", cond);
}
} /* namespace NetworKit */
#endif /*NOGTEST */
<|endoftext|> |
<commit_before>/* BEGIN_COMMON_COPYRIGHT_HEADER
* (c)LGPL2+
*
* LXDE-Qt - a lightweight, Qt based, desktop toolset
* http://razor-qt.org
*
* Copyright: 2011 Razor team
* Authors:
* Christian Surlykke <christian@surlykke.dk>
*
* 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 <QDBusConnection>
#include <QDBusReply>
#include <QObject>
#include <QDebug>
#include "lid.h"
Lid::Lid()
{
mUPowerInterface = new QDBusInterface("org.freedesktop.UPower", "/org/freedesktop/UPower", "org.freedesktop.UPower",
QDBusConnection::systemBus(), this);
mUPowerPropertiesInterface = new QDBusInterface("org.freedesktop.UPower", "/org/freedesktop/UPower", "org.freedesktop.DBus.Properties",
QDBusConnection::systemBus(), this);
if (! connect(mUPowerInterface, SIGNAL(Changed()), this, SLOT(uPowerChange())))
{
qDebug() << "Could not connect to org.freedesktop.UPower.changed(), connecting to org.freedesktop.DBus.Properties.PropertiesChanged(..) instead";
QDBusConnection::systemBus().connect("org.freedesktop.UPower",
"/org/freedesktop/UPower",
"org.freedesktop.DBus.Properties",
"PropertiesChanged",
this,
SLOT(uPowerChange()));
}
mIsClosed = mUPowerPropertiesInterface->property("LidIsClosed").toBool();
}
bool Lid::haveLid()
{
return mUPowerInterface->property("LidIsPresent").toBool();
}
bool Lid::onBattery()
{
return mUPowerInterface->property("OnBattery").toBool();
}
void Lid::uPowerChange()
{
bool newIsClosed = mUPowerInterface->property("LidIsClosed").toBool();
if (newIsClosed != mIsClosed)
{
mIsClosed = newIsClosed;
emit changed(mIsClosed);
}
}
<commit_msg>lidwatcher: don't listen to Changed signal<commit_after>/* BEGIN_COMMON_COPYRIGHT_HEADER
* (c)LGPL2+
*
* LXDE-Qt - a lightweight, Qt based, desktop toolset
* http://razor-qt.org
*
* Copyright: 2011 Razor team
* Authors:
* Christian Surlykke <christian@surlykke.dk>
*
* 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 <QDBusConnection>
#include <QDBusReply>
#include <QObject>
#include <QDebug>
#include "lid.h"
Lid::Lid()
{
mUPowerInterface = new QDBusInterface("org.freedesktop.UPower",
"/org/freedesktop/UPower",
"org.freedesktop.UPower",
QDBusConnection::systemBus(), this);
mUPowerPropertiesInterface = new QDBusInterface("org.freedesktop.UPower",
"/org/freedesktop/UPower",
"org.freedesktop.DBus.Properties",
QDBusConnection::systemBus(), this);
if (!QDBusConnection::systemBus().connect("org.freedesktop.UPower",
"/org/freedesktop/UPower",
"org.freedesktop.DBus.Properties",
"PropertiesChanged",
this,
SLOT(uPowerChange())))
qDebug() << "Could not connect to org.freedesktop.DBus.Properties.PropertiesChanged()";
mIsClosed = mUPowerPropertiesInterface->property("LidIsClosed").toBool();
}
bool Lid::haveLid()
{
return mUPowerInterface->property("LidIsPresent").toBool();
}
bool Lid::onBattery()
{
return mUPowerInterface->property("OnBattery").toBool();
}
void Lid::uPowerChange()
{
bool newIsClosed = mUPowerInterface->property("LidIsClosed").toBool();
if (newIsClosed != mIsClosed)
{
mIsClosed = newIsClosed;
emit changed(mIsClosed);
}
}
<|endoftext|> |
<commit_before>#include "glyph_object_creation.hpp"
#include "vector_font.hpp"
#include "text3D.hpp"
#include "object.hpp"
#include "object_struct.hpp"
// Include standard headers
#include <stdint.h> // uint32_t etc.
#include <string> // std::string
namespace yli
{
namespace ontology
{
class Glyph;
void create_glyph_objects(const std::string& text_string, yli::ontology::Text3D* const text3D)
{
const char* text_pointer = text_string.c_str();
while (*text_pointer != '\0')
{
int32_t unicode_value = yli::string::extract_unicode_value_from_string(text_pointer);
yli::ontology::Glyph* glyph_pointer = text3D->parent->get_glyph_pointer(unicode_value);
if (glyph_pointer == nullptr)
{
// nullptr, so skip this character.
std::cerr << "Error: no matching Glyph found for unicode_value 0x" << std::hex << unicode_value << std::dec << "\n";
continue;
}
std::cout << "Creating the glyph Object for unicode_value 0x" << std::hex << unicode_value << std::dec << "\n";
ObjectStruct object_struct;
object_struct.glyph_parent = glyph_pointer;
object_struct.text3D_parent = text3D;
object_struct.original_scale_vector = text3D->original_scale_vector;
object_struct.rotate_angle = text3D->rotate_angle;
object_struct.is_character = true;
object_struct.cartesian_coordinates = text3D->cartesian_coordinates; // TODO: adjust this as needed.
object_struct.rotate_vector = text3D->rotate_vector;
new yli::ontology::Object(text3D->universe, object_struct);
}
// TODO: Add support for Unicode strings.
// TODO: go through `text_string`.
// TODO: extract Unicode.
//
// TODO: If the Unicode exists in the hash map, create the corresponding glyph `Object`.
// If not, continue from the next Unicode of `text_string`.
}
}
}
<commit_msg>`yli::ontology::create_glyph_objects`: use `ontology::EntityFactory`.<commit_after>#include "glyph_object_creation.hpp"
#include "entity_factory.hpp"
#include "universe.hpp"
#include "vector_font.hpp"
#include "text3D.hpp"
#include "object.hpp"
#include "object_struct.hpp"
// Include standard headers
#include <stdint.h> // uint32_t etc.
#include <string> // std::string
namespace yli
{
namespace ontology
{
class Glyph;
void create_glyph_objects(const std::string& text_string, yli::ontology::Text3D* const text3D)
{
const char* text_pointer = text_string.c_str();
while (*text_pointer != '\0')
{
int32_t unicode_value = yli::string::extract_unicode_value_from_string(text_pointer);
yli::ontology::Glyph* glyph_pointer = text3D->parent->get_glyph_pointer(unicode_value);
if (glyph_pointer == nullptr)
{
// nullptr, so skip this character.
std::cerr << "Error: no matching Glyph found for unicode_value 0x" << std::hex << unicode_value << std::dec << "\n";
continue;
}
std::cout << "Creating the glyph Object for unicode_value 0x" << std::hex << unicode_value << std::dec << "\n";
ObjectStruct object_struct;
object_struct.glyph_parent = glyph_pointer;
object_struct.text3D_parent = text3D;
object_struct.original_scale_vector = text3D->original_scale_vector;
object_struct.rotate_angle = text3D->rotate_angle;
object_struct.is_character = true;
object_struct.cartesian_coordinates = text3D->cartesian_coordinates; // TODO: adjust this as needed.
object_struct.rotate_vector = text3D->rotate_vector;
yli::ontology::EntityFactory* const entity_factory = text3D->universe->get_entity_factory();
if (entity_factory != nullptr)
{
entity_factory->create_Object(object_struct);
}
}
// TODO: Add support for Unicode strings.
// TODO: go through `text_string`.
// TODO: extract Unicode.
//
// TODO: If the Unicode exists in the hash map, create the corresponding glyph `Object`.
// If not, continue from the next Unicode of `text_string`.
}
}
}
<|endoftext|> |
<commit_before>/**
* (c) 2019 by Mega Limited, Wellsford, New Zealand
*
* This file is part of the MEGA SDK - Client Access Engine.
*
* Applications using the MEGA API must present a valid application key
* and comply with the the rules set forth in the Terms of Service.
*
* The MEGA SDK 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.
*
* @copyright Simplified (2-clause) BSD License.
*
* You should have received a copy of the license along with this
* program.
*/
#include <array>
#include <tuple>
#include <gtest/gtest.h>
#include <mega/utils.h>
#include <mega/filesystem.h>
#include "megafs.h"
TEST(utils, hashCombine_integer)
{
size_t hash = 0;
mega::hashCombine(hash, 42);
#ifdef _WIN32
// MSVC's std::hash gives different values than that of gcc/clang
ASSERT_EQ(sizeof(hash) == 4 ? 286246808ul : 10203658983813110072ull, hash);
#else
ASSERT_EQ(2654435811ull, hash);
#endif
}
TEST(CharacterSet, IterateUtf8)
{
using mega::unicodeCodepointIterator;
// Single code-unit.
{
auto it = unicodeCodepointIterator("abc");
EXPECT_FALSE(it.end());
EXPECT_EQ(it.get(), 'a');
EXPECT_EQ(it.get(), 'b');
EXPECT_EQ(it.get(), 'c');
EXPECT_TRUE(it.end());
EXPECT_EQ(it.get(), '\0');
}
// Multiple code-unit.
{
auto it = unicodeCodepointIterator("q\xf0\x90\x80\x80r");
EXPECT_FALSE(it.end());
EXPECT_EQ(it.get(), 'q');
EXPECT_EQ(it.get(), 0x10000);
EXPECT_EQ(it.get(), 'r');
EXPECT_TRUE(it.end());
EXPECT_EQ(it.get(), '\0');
}
}
TEST(CharacterSet, IterateUtf16)
{
using mega::unicodeCodepointIterator;
// Single code-unit.
{
auto it = unicodeCodepointIterator(L"abc");
EXPECT_FALSE(it.end());
EXPECT_EQ(it.get(), L'a');
EXPECT_EQ(it.get(), L'b');
EXPECT_EQ(it.get(), L'c');
EXPECT_TRUE(it.end());
EXPECT_EQ(it.get(), L'\0');
}
// Multiple code-unit.
{
auto it = unicodeCodepointIterator(L"q\xd800\xdc00r");
EXPECT_FALSE(it.end());
EXPECT_EQ(it.get(), L'q');
EXPECT_EQ(it.get(), 0x10000);
EXPECT_EQ(it.get(), L'r');
EXPECT_TRUE(it.end());
EXPECT_EQ(it.get(), L'\0');
}
}
using namespace mega;
using namespace std;
// Disambiguate between Microsoft's FileSystemType.
using ::mega::FileSystemType;
class ComparatorTest
: public ::testing::Test
{
public:
ComparatorTest()
: mFSAccess()
{
}
template<typename T, typename U>
int compare(const T& lhs, const U& rhs) const
{
return compareUtf(lhs, true, rhs, true, false);
}
template<typename T, typename U>
int ciCompare(const T& lhs, const U& rhs) const
{
return compareUtf(lhs, true, rhs, true, true);
}
LocalPath fromPath(const string& s)
{
return LocalPath::fromPath(s, mFSAccess);
}
template<typename T, typename U>
int fsCompare(const T& lhs, const U& rhs, const FileSystemType type) const
{
const auto caseInsensitive = isCaseInsensitive(type);
return compareUtf(lhs, true, rhs, true, caseInsensitive);
}
private:
FSACCESS_CLASS mFSAccess;
}; // ComparatorTest
TEST_F(ComparatorTest, CompareLocalPaths)
{
LocalPath lhs;
LocalPath rhs;
// Case insensitive
{
// Make sure basic characters are uppercased.
lhs = fromPath("abc");
rhs = fromPath("ABC");
EXPECT_EQ(ciCompare(lhs, rhs), 0);
EXPECT_EQ(ciCompare(rhs, lhs), 0);
// Make sure comparison invariants are not violated.
lhs = fromPath("abc");
rhs = fromPath("ABCD");
EXPECT_LT(ciCompare(lhs, rhs), 0);
EXPECT_GT(ciCompare(rhs, lhs), 0);
// Make sure escapes are decoded.
lhs = fromPath("a%30b");
rhs = fromPath("A0B");
EXPECT_EQ(ciCompare(lhs, rhs), 0);
EXPECT_EQ(ciCompare(rhs, lhs), 0);
// Make sure decoded characters are uppercased.
lhs = fromPath("%61%62%63");
rhs = fromPath("ABC");
EXPECT_EQ(ciCompare(lhs, rhs), 0);
EXPECT_EQ(ciCompare(rhs, lhs), 0);
// Invalid escapes are left as-is.
lhs = fromPath("a%qb%");
rhs = fromPath("A%qB%");
EXPECT_EQ(ciCompare(lhs, rhs), 0);
EXPECT_EQ(ciCompare(rhs, lhs), 0);
}
// Case sensitive
{
// Basic comparison.
lhs = fromPath("abc");
EXPECT_EQ(compare(lhs, lhs), 0);
// Make sure characters are not uppercased.
rhs = fromPath("ABC");
EXPECT_NE(compare(lhs, rhs), 0);
EXPECT_NE(compare(rhs, lhs), 0);
// Make sure comparison invariants are not violated.
lhs = fromPath("abc");
rhs = fromPath("abcd");
EXPECT_LT(compare(lhs, rhs), 0);
EXPECT_GT(compare(rhs, lhs), 0);
// Make sure escapes are decoded.
lhs = fromPath("a%30b");
rhs = fromPath("a0b");
EXPECT_EQ(compare(lhs, rhs), 0);
EXPECT_EQ(compare(rhs, lhs), 0);
// Invalid escapes are left as-is.
lhs = fromPath("a%qb%");
EXPECT_EQ(compare(lhs, lhs), 0);
}
// Filesystem-specific
{
lhs = fromPath("a\7%30b%31c");
rhs = fromPath("A%070B1C");
// exFAT, FAT32, NTFS and UNKNOWN are case-insensitive.
EXPECT_EQ(fsCompare(lhs, rhs, FS_EXFAT), 0);
EXPECT_EQ(fsCompare(lhs, rhs, FS_FAT32), 0);
EXPECT_EQ(fsCompare(lhs, rhs, FS_NTFS), 0);
EXPECT_EQ(fsCompare(lhs, rhs, FS_UNKNOWN), 0);
#ifndef _WIN32
// Everything else is case-sensitive.
EXPECT_NE(fsCompare(lhs, rhs, FS_EXT), 0);
rhs = fromPath("a%070b1c");
EXPECT_EQ(fsCompare(lhs, rhs, FS_EXT), 0);
#endif // ! _WIN32
}
}
TEST_F(ComparatorTest, CompareLocalPathAgainstString)
{
LocalPath lhs;
string rhs;
// Case insensitive
{
// Simple comparison.
lhs = fromPath("abc");
rhs = "ABC";
EXPECT_EQ(ciCompare(lhs, rhs), 0);
// Invariants.
lhs = fromPath("abc");
rhs = "abcd";
EXPECT_LT(ciCompare(lhs, rhs), 0);
lhs = fromPath("abcd");
rhs = "abc";
EXPECT_GT(ciCompare(lhs, rhs), 0);
// All local escapes are decoded.
lhs = fromPath("a%30b%31c");
rhs = "A0b1C";
EXPECT_EQ(ciCompare(lhs, rhs), 0);
// Escapes are uppercased.
lhs = fromPath("%61%62%63");
rhs = "ABC";
EXPECT_EQ(ciCompare(lhs, rhs), 0);
// Invalid escapes are left as-is.
lhs = fromPath("a%qb%");
rhs = "A%QB%";
EXPECT_EQ(ciCompare(lhs, rhs), 0);
}
// Case sensitive
{
// Simple comparison.
lhs = fromPath("abc");
rhs = "abc";
EXPECT_EQ(compare(lhs, rhs), 0);
// Invariants.
rhs = "abcd";
EXPECT_LT(compare(lhs, rhs), 0);
lhs = fromPath("abcd");
rhs = "abc";
EXPECT_GT(compare(lhs, rhs), 0);
// All local escapes are decoded.
lhs = fromPath("a%30b%31c");
rhs = "a0b1c";
EXPECT_EQ(compare(lhs, rhs), 0);
// Invalid escapes left as-is.
lhs = fromPath("a%qb%r");
rhs = "a%qb%r";
EXPECT_EQ(compare(lhs, rhs), 0);
}
// Filesystem-specific
{
lhs = fromPath("a\7%30b%31c");
rhs = "A%070B1C";
// exFAT, FAT32, NTFS and UNKNOWN are case-insensitive.
EXPECT_EQ(fsCompare(lhs, rhs, FS_EXFAT), 0);
EXPECT_EQ(fsCompare(lhs, rhs, FS_FAT32), 0);
EXPECT_EQ(fsCompare(lhs, rhs, FS_NTFS), 0);
EXPECT_EQ(fsCompare(lhs, rhs, FS_UNKNOWN), 0);
#ifndef _WIN32
// Everything else is case-sensitive.
EXPECT_NE(fsCompare(lhs, rhs, FS_EXT), 0);
rhs = "a%070b1c";
EXPECT_EQ(fsCompare(lhs, rhs, FS_EXT), 0);
#endif // ! _WIN32
}
}
TEST(Conversion, HexVal)
{
// Decimal [0-9]
for (int i = 0x30; i < 0x3a; ++i)
{
EXPECT_EQ(hexval(i), i - 0x30);
}
// Lowercase hexadecimal [a-f]
for (int i = 0x41; i < 0x47; ++i)
{
EXPECT_EQ(hexval(i), i - 0x37);
}
// Uppercase hexadeimcal [A-F]
for (int i = 0x61; i < 0x67; ++i)
{
EXPECT_EQ(hexval(i), i - 0x57);
}
}
TEST(URLCodec, Unescape)
{
string input = "a%4a%4Bc";
string output;
URLCodec::unescape(&input, &output);
EXPECT_EQ(output, "aJKc");
}
TEST(URLCodec, UnescapeInvalidEscape)
{
string input;
string output;
// First character is invalid.
input = "a%qbc";
URLCodec::unescape(&input, &output);
EXPECT_EQ(output, "a%qbc");
// Second character is invalid.
input = "a%bqc";
URLCodec::unescape(&input, &output);
EXPECT_EQ(output, "a%bqc");
}
TEST(URLCodec, UnescapeShortEscape)
{
string input;
string output;
// No hex digits.
input = "a%";
URLCodec::unescape(&input, &output);
EXPECT_EQ(output, "a%");
// Single hex digit.
input = "a%a";
URLCodec::unescape(&input, &output);
EXPECT_EQ(output, "a%a");
}
<commit_msg>Fix Jenkins build failure.<commit_after>/**
* (c) 2019 by Mega Limited, Wellsford, New Zealand
*
* This file is part of the MEGA SDK - Client Access Engine.
*
* Applications using the MEGA API must present a valid application key
* and comply with the the rules set forth in the Terms of Service.
*
* The MEGA SDK 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.
*
* @copyright Simplified (2-clause) BSD License.
*
* You should have received a copy of the license along with this
* program.
*/
#include <array>
#include <tuple>
#include <gtest/gtest.h>
#include <mega/base64.h>
#include <mega/filesystem.h>
#include <mega/utils.h>
#include "megafs.h"
TEST(utils, hashCombine_integer)
{
size_t hash = 0;
mega::hashCombine(hash, 42);
#ifdef _WIN32
// MSVC's std::hash gives different values than that of gcc/clang
ASSERT_EQ(sizeof(hash) == 4 ? 286246808ul : 10203658983813110072ull, hash);
#else
ASSERT_EQ(2654435811ull, hash);
#endif
}
TEST(CharacterSet, IterateUtf8)
{
using mega::unicodeCodepointIterator;
// Single code-unit.
{
auto it = unicodeCodepointIterator("abc");
EXPECT_FALSE(it.end());
EXPECT_EQ(it.get(), 'a');
EXPECT_EQ(it.get(), 'b');
EXPECT_EQ(it.get(), 'c');
EXPECT_TRUE(it.end());
EXPECT_EQ(it.get(), '\0');
}
// Multiple code-unit.
{
auto it = unicodeCodepointIterator("q\xf0\x90\x80\x80r");
EXPECT_FALSE(it.end());
EXPECT_EQ(it.get(), 'q');
EXPECT_EQ(it.get(), 0x10000);
EXPECT_EQ(it.get(), 'r');
EXPECT_TRUE(it.end());
EXPECT_EQ(it.get(), '\0');
}
}
TEST(CharacterSet, IterateUtf16)
{
using mega::unicodeCodepointIterator;
// Single code-unit.
{
auto it = unicodeCodepointIterator(L"abc");
EXPECT_FALSE(it.end());
EXPECT_EQ(it.get(), L'a');
EXPECT_EQ(it.get(), L'b');
EXPECT_EQ(it.get(), L'c');
EXPECT_TRUE(it.end());
EXPECT_EQ(it.get(), L'\0');
}
// Multiple code-unit.
{
auto it = unicodeCodepointIterator(L"q\xd800\xdc00r");
EXPECT_FALSE(it.end());
EXPECT_EQ(it.get(), L'q');
EXPECT_EQ(it.get(), 0x10000);
EXPECT_EQ(it.get(), L'r');
EXPECT_TRUE(it.end());
EXPECT_EQ(it.get(), L'\0');
}
}
using namespace mega;
using namespace std;
// Disambiguate between Microsoft's FileSystemType.
using ::mega::FileSystemType;
class ComparatorTest
: public ::testing::Test
{
public:
ComparatorTest()
: mFSAccess()
{
}
template<typename T, typename U>
int compare(const T& lhs, const U& rhs) const
{
return compareUtf(lhs, true, rhs, true, false);
}
template<typename T, typename U>
int ciCompare(const T& lhs, const U& rhs) const
{
return compareUtf(lhs, true, rhs, true, true);
}
LocalPath fromPath(const string& s)
{
return LocalPath::fromPath(s, mFSAccess);
}
template<typename T, typename U>
int fsCompare(const T& lhs, const U& rhs, const FileSystemType type) const
{
const auto caseInsensitive = isCaseInsensitive(type);
return compareUtf(lhs, true, rhs, true, caseInsensitive);
}
private:
FSACCESS_CLASS mFSAccess;
}; // ComparatorTest
TEST_F(ComparatorTest, CompareLocalPaths)
{
LocalPath lhs;
LocalPath rhs;
// Case insensitive
{
// Make sure basic characters are uppercased.
lhs = fromPath("abc");
rhs = fromPath("ABC");
EXPECT_EQ(ciCompare(lhs, rhs), 0);
EXPECT_EQ(ciCompare(rhs, lhs), 0);
// Make sure comparison invariants are not violated.
lhs = fromPath("abc");
rhs = fromPath("ABCD");
EXPECT_LT(ciCompare(lhs, rhs), 0);
EXPECT_GT(ciCompare(rhs, lhs), 0);
// Make sure escapes are decoded.
lhs = fromPath("a%30b");
rhs = fromPath("A0B");
EXPECT_EQ(ciCompare(lhs, rhs), 0);
EXPECT_EQ(ciCompare(rhs, lhs), 0);
// Make sure decoded characters are uppercased.
lhs = fromPath("%61%62%63");
rhs = fromPath("ABC");
EXPECT_EQ(ciCompare(lhs, rhs), 0);
EXPECT_EQ(ciCompare(rhs, lhs), 0);
// Invalid escapes are left as-is.
lhs = fromPath("a%qb%");
rhs = fromPath("A%qB%");
EXPECT_EQ(ciCompare(lhs, rhs), 0);
EXPECT_EQ(ciCompare(rhs, lhs), 0);
}
// Case sensitive
{
// Basic comparison.
lhs = fromPath("abc");
EXPECT_EQ(compare(lhs, lhs), 0);
// Make sure characters are not uppercased.
rhs = fromPath("ABC");
EXPECT_NE(compare(lhs, rhs), 0);
EXPECT_NE(compare(rhs, lhs), 0);
// Make sure comparison invariants are not violated.
lhs = fromPath("abc");
rhs = fromPath("abcd");
EXPECT_LT(compare(lhs, rhs), 0);
EXPECT_GT(compare(rhs, lhs), 0);
// Make sure escapes are decoded.
lhs = fromPath("a%30b");
rhs = fromPath("a0b");
EXPECT_EQ(compare(lhs, rhs), 0);
EXPECT_EQ(compare(rhs, lhs), 0);
// Invalid escapes are left as-is.
lhs = fromPath("a%qb%");
EXPECT_EQ(compare(lhs, lhs), 0);
}
// Filesystem-specific
{
lhs = fromPath("a\7%30b%31c");
rhs = fromPath("A%070B1C");
// exFAT, FAT32, NTFS and UNKNOWN are case-insensitive.
EXPECT_EQ(fsCompare(lhs, rhs, FS_EXFAT), 0);
EXPECT_EQ(fsCompare(lhs, rhs, FS_FAT32), 0);
EXPECT_EQ(fsCompare(lhs, rhs, FS_NTFS), 0);
EXPECT_EQ(fsCompare(lhs, rhs, FS_UNKNOWN), 0);
#ifndef _WIN32
// Everything else is case-sensitive.
EXPECT_NE(fsCompare(lhs, rhs, FS_EXT), 0);
rhs = fromPath("a%070b1c");
EXPECT_EQ(fsCompare(lhs, rhs, FS_EXT), 0);
#endif // ! _WIN32
}
}
TEST_F(ComparatorTest, CompareLocalPathAgainstString)
{
LocalPath lhs;
string rhs;
// Case insensitive
{
// Simple comparison.
lhs = fromPath("abc");
rhs = "ABC";
EXPECT_EQ(ciCompare(lhs, rhs), 0);
// Invariants.
lhs = fromPath("abc");
rhs = "abcd";
EXPECT_LT(ciCompare(lhs, rhs), 0);
lhs = fromPath("abcd");
rhs = "abc";
EXPECT_GT(ciCompare(lhs, rhs), 0);
// All local escapes are decoded.
lhs = fromPath("a%30b%31c");
rhs = "A0b1C";
EXPECT_EQ(ciCompare(lhs, rhs), 0);
// Escapes are uppercased.
lhs = fromPath("%61%62%63");
rhs = "ABC";
EXPECT_EQ(ciCompare(lhs, rhs), 0);
// Invalid escapes are left as-is.
lhs = fromPath("a%qb%");
rhs = "A%QB%";
EXPECT_EQ(ciCompare(lhs, rhs), 0);
}
// Case sensitive
{
// Simple comparison.
lhs = fromPath("abc");
rhs = "abc";
EXPECT_EQ(compare(lhs, rhs), 0);
// Invariants.
rhs = "abcd";
EXPECT_LT(compare(lhs, rhs), 0);
lhs = fromPath("abcd");
rhs = "abc";
EXPECT_GT(compare(lhs, rhs), 0);
// All local escapes are decoded.
lhs = fromPath("a%30b%31c");
rhs = "a0b1c";
EXPECT_EQ(compare(lhs, rhs), 0);
// Invalid escapes left as-is.
lhs = fromPath("a%qb%r");
rhs = "a%qb%r";
EXPECT_EQ(compare(lhs, rhs), 0);
}
// Filesystem-specific
{
lhs = fromPath("a\7%30b%31c");
rhs = "A%070B1C";
// exFAT, FAT32, NTFS and UNKNOWN are case-insensitive.
EXPECT_EQ(fsCompare(lhs, rhs, FS_EXFAT), 0);
EXPECT_EQ(fsCompare(lhs, rhs, FS_FAT32), 0);
EXPECT_EQ(fsCompare(lhs, rhs, FS_NTFS), 0);
EXPECT_EQ(fsCompare(lhs, rhs, FS_UNKNOWN), 0);
#ifndef _WIN32
// Everything else is case-sensitive.
EXPECT_NE(fsCompare(lhs, rhs, FS_EXT), 0);
rhs = "a%070b1c";
EXPECT_EQ(fsCompare(lhs, rhs, FS_EXT), 0);
#endif // ! _WIN32
}
}
TEST(Conversion, HexVal)
{
// Decimal [0-9]
for (int i = 0x30; i < 0x3a; ++i)
{
EXPECT_EQ(hexval(i), i - 0x30);
}
// Lowercase hexadecimal [a-f]
for (int i = 0x41; i < 0x47; ++i)
{
EXPECT_EQ(hexval(i), i - 0x37);
}
// Uppercase hexadeimcal [A-F]
for (int i = 0x61; i < 0x67; ++i)
{
EXPECT_EQ(hexval(i), i - 0x57);
}
}
TEST(URLCodec, Unescape)
{
string input = "a%4a%4Bc";
string output;
URLCodec::unescape(&input, &output);
EXPECT_EQ(output, "aJKc");
}
TEST(URLCodec, UnescapeInvalidEscape)
{
string input;
string output;
// First character is invalid.
input = "a%qbc";
URLCodec::unescape(&input, &output);
EXPECT_EQ(output, "a%qbc");
// Second character is invalid.
input = "a%bqc";
URLCodec::unescape(&input, &output);
EXPECT_EQ(output, "a%bqc");
}
TEST(URLCodec, UnescapeShortEscape)
{
string input;
string output;
// No hex digits.
input = "a%";
URLCodec::unescape(&input, &output);
EXPECT_EQ(output, "a%");
// Single hex digit.
input = "a%a";
URLCodec::unescape(&input, &output);
EXPECT_EQ(output, "a%a");
}
<|endoftext|> |
<commit_before>#include<iostream>
/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */
/*
* This file is part of the LibreOffice project.
*
* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/.
*/
#include "clang/Lex/Lexer.h"
#include "compat.hxx"
#include "plugin.hxx"
namespace {
class LiteralToBoolConversion:
public RecursiveASTVisitor<LiteralToBoolConversion>,
public loplugin::RewritePlugin
{
public:
explicit LiteralToBoolConversion(InstantiationData const & data):
RewritePlugin(data) {}
virtual void run() override
{ TraverseDecl(compiler.getASTContext().getTranslationUnitDecl()); }
bool VisitImplicitCastExpr(ImplicitCastExpr const * expr);
private:
bool isFromCIncludeFile(SourceLocation spellingLocation) const;
bool isMacroBodyExpansion(SourceLocation location) const;
};
bool LiteralToBoolConversion::VisitImplicitCastExpr(
ImplicitCastExpr const * expr)
{
if (ignoreLocation(expr)) {
return true;
}
if (!expr->getType()->isBooleanType()) {
return true;
}
Expr const * sub = expr->getSubExpr()->IgnoreParenCasts();
if (sub->getType()->isBooleanType()) {
return true;
}
IntegerLiteral const * lit = dyn_cast<IntegerLiteral>(sub);
if (lit != nullptr && lit->getValue().getLimitedValue() <= 1) {
SourceLocation loc { sub->getLocStart() };
while (compiler.getSourceManager().isMacroArgExpansion(loc)) {
loc = compiler.getSourceManager().getImmediateMacroCallerLoc(loc);
}
if (isMacroBodyExpansion(loc)) {
StringRef name { Lexer::getImmediateMacroName(
loc, compiler.getSourceManager(), compiler.getLangOpts()) };
if (name == "sal_False" || name == "sal_True") {
loc = compiler.getSourceManager().getImmediateExpansionRange(
loc).first;
}
if (isFromCIncludeFile(
compiler.getSourceManager().getSpellingLoc(loc)))
{
return true;
}
}
}
if (isa<StringLiteral>(sub)) {
SourceLocation loc { sub->getLocStart() };
if (compiler.getSourceManager().isMacroArgExpansion(loc)
&& (Lexer::getImmediateMacroName(
loc, compiler.getSourceManager(), compiler.getLangOpts())
== "assert"))
{
return true;
}
}
if (isa<IntegerLiteral>(sub) || isa<CharacterLiteral>(sub)
|| isa<FloatingLiteral>(sub) || isa<ImaginaryLiteral>(sub)
|| isa<StringLiteral>(sub))
{
bool rewritten = false;
if (rewriter != nullptr) {
SourceLocation loc { compiler.getSourceManager().getExpansionLoc(
expr->getLocStart()) };
if (compiler.getSourceManager().getExpansionLoc(expr->getLocEnd())
== loc)
{
char const * s = compiler.getSourceManager().getCharacterData(
loc);
unsigned n = Lexer::MeasureTokenLength(
expr->getLocEnd(), compiler.getSourceManager(),
compiler.getLangOpts());
std::string tok { s, n };
if (tok == "sal_False" || tok == "0") {
rewritten = replaceText(
compiler.getSourceManager().getExpansionLoc(
expr->getLocStart()),
n, "false");
} else if (tok == "sal_True" || tok == "1") {
rewritten = replaceText(
compiler.getSourceManager().getExpansionLoc(
expr->getLocStart()),
n, "true");
}
}
}
if (!rewritten) {
report(
DiagnosticsEngine::Warning,
"implicit conversion (%0) of literal of type %1 to %2",
expr->getLocStart())
<< expr->getCastKindName() << expr->getSubExpr()->getType()
<< expr->getType() << expr->getSourceRange();
}
// At least Clang 3.2 would erroneously warn about Cache::add
// (binaryurp/source/cache.hxx:53)
//
// if( !size_) {
//
// as "implicit conversion (IntegralToBoolean) of null pointer constant of type
// 'std::size_t' (aka 'unsigned long') to 'bool'":
#if (__clang_major__ == 3 && __clang_minor__ >= 4) || __clang_major__ > 3
} else if (sub->isNullPointerConstant(
compiler.getASTContext(), Expr::NPC_ValueDependentIsNull)
!= Expr::NPCK_NotNull)
{
report(
DiagnosticsEngine::Warning,
("implicit conversion (%0) of null pointer constant of type %1 to"
" %2"),
expr->getLocStart())
<< expr->getCastKindName() << expr->getSubExpr()->getType()
<< expr->getType() << expr->getSourceRange();
#endif
} else if (sub->isIntegerConstantExpr(compiler.getASTContext())) {
CallExpr const * ce = dyn_cast<CallExpr>(sub);
if (ce == nullptr
|| compat::getBuiltinCallee(*ce) != Builtin::BI__builtin_expect)
{
report(
DiagnosticsEngine::Warning,
("implicit conversion (%0) of integer constant expression of"
" type %1 to %2"),
expr->getLocStart())
<< expr->getCastKindName() << expr->getSubExpr()->getType()
<< expr->getType() << expr->getSourceRange();
}
}
return true;
}
bool LiteralToBoolConversion::isFromCIncludeFile(
SourceLocation spellingLocation) const
{
#if (__clang_major__ == 3 && __clang_minor__ >= 4) || __clang_major__ > 3
if (compiler.getSourceManager().isInMainFile(spellingLocation)) {
return false;
}
#else
if (compiler.getSourceManager().isFromMainFile(spellingLocation)) {
return false;
}
#endif
return compiler.getSourceManager().getFilename(spellingLocation).endswith(
".h");
}
bool LiteralToBoolConversion::isMacroBodyExpansion(SourceLocation location)
const
{
#if (__clang_major__ == 3 && __clang_minor__ >= 3) || __clang_major__ > 3
return compiler.getSourceManager().isMacroBodyExpansion(location);
#else
return location.isMacroID()
&& !compiler.getSourceManager().isMacroArgExpansion(location);
#endif
}
loplugin::Plugin::Registration<LiteralToBoolConversion> X(
"literaltoboolconversion", true);
}
<commit_msg>isIntegerConstantExpr is more general than IntegerLiteral<commit_after>/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */
/*
* This file is part of the LibreOffice project.
*
* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/.
*/
#include "clang/Lex/Lexer.h"
#include "compat.hxx"
#include "plugin.hxx"
namespace {
class LiteralToBoolConversion:
public RecursiveASTVisitor<LiteralToBoolConversion>,
public loplugin::RewritePlugin
{
public:
explicit LiteralToBoolConversion(InstantiationData const & data):
RewritePlugin(data) {}
virtual void run() override
{ TraverseDecl(compiler.getASTContext().getTranslationUnitDecl()); }
bool VisitImplicitCastExpr(ImplicitCastExpr const * expr);
private:
bool isFromCIncludeFile(SourceLocation spellingLocation) const;
bool isMacroBodyExpansion(SourceLocation location) const;
};
bool LiteralToBoolConversion::VisitImplicitCastExpr(
ImplicitCastExpr const * expr)
{
if (ignoreLocation(expr)) {
return true;
}
if (!expr->getType()->isBooleanType()) {
return true;
}
Expr const * sub = expr->getSubExpr()->IgnoreParenCasts();
if (sub->getType()->isBooleanType()) {
return true;
}
APSInt res;
if (sub->isIntegerConstantExpr(res, compiler.getASTContext())
&& res.getLimitedValue() <= 1)
{
SourceLocation loc { sub->getLocStart() };
while (compiler.getSourceManager().isMacroArgExpansion(loc)) {
loc = compiler.getSourceManager().getImmediateMacroCallerLoc(loc);
}
if (isMacroBodyExpansion(loc)) {
StringRef name { Lexer::getImmediateMacroName(
loc, compiler.getSourceManager(), compiler.getLangOpts()) };
if (name == "sal_False" || name == "sal_True") {
loc = compiler.getSourceManager().getImmediateExpansionRange(
loc).first;
}
if (isFromCIncludeFile(
compiler.getSourceManager().getSpellingLoc(loc)))
{
return true;
}
}
}
if (isa<StringLiteral>(sub)) {
SourceLocation loc { sub->getLocStart() };
if (compiler.getSourceManager().isMacroArgExpansion(loc)
&& (Lexer::getImmediateMacroName(
loc, compiler.getSourceManager(), compiler.getLangOpts())
== "assert"))
{
return true;
}
}
if (isa<IntegerLiteral>(sub) || isa<CharacterLiteral>(sub)
|| isa<FloatingLiteral>(sub) || isa<ImaginaryLiteral>(sub)
|| isa<StringLiteral>(sub))
{
bool rewritten = false;
if (rewriter != nullptr) {
SourceLocation loc { compiler.getSourceManager().getExpansionLoc(
expr->getLocStart()) };
if (compiler.getSourceManager().getExpansionLoc(expr->getLocEnd())
== loc)
{
char const * s = compiler.getSourceManager().getCharacterData(
loc);
unsigned n = Lexer::MeasureTokenLength(
expr->getLocEnd(), compiler.getSourceManager(),
compiler.getLangOpts());
std::string tok { s, n };
if (tok == "sal_False" || tok == "0") {
rewritten = replaceText(
compiler.getSourceManager().getExpansionLoc(
expr->getLocStart()),
n, "false");
} else if (tok == "sal_True" || tok == "1") {
rewritten = replaceText(
compiler.getSourceManager().getExpansionLoc(
expr->getLocStart()),
n, "true");
}
}
}
if (!rewritten) {
report(
DiagnosticsEngine::Warning,
"implicit conversion (%0) of literal of type %1 to %2",
expr->getLocStart())
<< expr->getCastKindName() << expr->getSubExpr()->getType()
<< expr->getType() << expr->getSourceRange();
}
// At least Clang 3.2 would erroneously warn about Cache::add
// (binaryurp/source/cache.hxx:53)
//
// if( !size_) {
//
// as "implicit conversion (IntegralToBoolean) of null pointer constant of type
// 'std::size_t' (aka 'unsigned long') to 'bool'":
#if (__clang_major__ == 3 && __clang_minor__ >= 4) || __clang_major__ > 3
} else if (sub->isNullPointerConstant(
compiler.getASTContext(), Expr::NPC_ValueDependentIsNull)
!= Expr::NPCK_NotNull)
{
report(
DiagnosticsEngine::Warning,
("implicit conversion (%0) of null pointer constant of type %1 to"
" %2"),
expr->getLocStart())
<< expr->getCastKindName() << expr->getSubExpr()->getType()
<< expr->getType() << expr->getSourceRange();
#endif
} else if (sub->isIntegerConstantExpr(res, compiler.getASTContext())) {
report(
DiagnosticsEngine::Warning,
("implicit conversion (%0) of integer constant expression of type"
" %1 with value %2 to %3"),
expr->getLocStart())
<< expr->getCastKindName() << expr->getSubExpr()->getType()
<< res.toString(10) << expr->getType() << expr->getSourceRange();
}
return true;
}
bool LiteralToBoolConversion::isFromCIncludeFile(
SourceLocation spellingLocation) const
{
#if (__clang_major__ == 3 && __clang_minor__ >= 4) || __clang_major__ > 3
if (compiler.getSourceManager().isInMainFile(spellingLocation)) {
return false;
}
#else
if (compiler.getSourceManager().isFromMainFile(spellingLocation)) {
return false;
}
#endif
return compiler.getSourceManager().getFilename(spellingLocation).endswith(
".h");
}
bool LiteralToBoolConversion::isMacroBodyExpansion(SourceLocation location)
const
{
#if (__clang_major__ == 3 && __clang_minor__ >= 3) || __clang_major__ > 3
return compiler.getSourceManager().isMacroBodyExpansion(location);
#else
return location.isMacroID()
&& !compiler.getSourceManager().isMacroArgExpansion(location);
#endif
}
loplugin::Plugin::Registration<LiteralToBoolConversion> X(
"literaltoboolconversion", true);
}
<|endoftext|> |
<commit_before>/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */
/*
* This file is part of the LibreOffice project.
*
* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/.
*/
#include "clang/Lex/Lexer.h"
#include "plugin.hxx"
namespace {
class LiteralToBoolConversion:
public RecursiveASTVisitor<LiteralToBoolConversion>,
public loplugin::RewritePlugin
{
public:
explicit LiteralToBoolConversion(InstantiationData const & data):
RewritePlugin(data) {}
virtual void run() override
{ TraverseDecl(compiler.getASTContext().getTranslationUnitDecl()); }
bool VisitImplicitCastExpr(ImplicitCastExpr const * expr);
private:
bool isFromCIncludeFile(SourceLocation spellingLocation) const;
bool isMacroBodyExpansion(SourceLocation location) const;
};
bool LiteralToBoolConversion::VisitImplicitCastExpr(
ImplicitCastExpr const * expr)
{
if (ignoreLocation(expr)) {
return true;
}
if (!expr->getType()->isBooleanType()) {
return true;
}
Expr const * sub = expr->getSubExpr()->IgnoreParenCasts();
if (sub->getType()->isBooleanType()) {
return true;
}
IntegerLiteral const * lit = dyn_cast<IntegerLiteral>(sub);
if (lit != nullptr && lit->getValue().getLimitedValue() <= 1) {
SourceLocation loc { sub->getLocStart() };
while (compiler.getSourceManager().isMacroArgExpansion(loc)) {
loc = compiler.getSourceManager().getImmediateMacroCallerLoc(loc);
}
if (isMacroBodyExpansion(loc)) {
StringRef name { Lexer::getImmediateMacroName(
loc, compiler.getSourceManager(), compiler.getLangOpts()) };
if (name == "sal_False" || name == "sal_True") {
loc = compiler.getSourceManager().getImmediateExpansionRange(
loc).first;
}
if (isFromCIncludeFile(
compiler.getSourceManager().getSpellingLoc(loc)))
{
return true;
}
}
}
if (isa<StringLiteral>(sub)) {
SourceLocation loc { sub->getLocStart() };
if (compiler.getSourceManager().isMacroArgExpansion(loc)
&& (Lexer::getImmediateMacroName(
loc, compiler.getSourceManager(), compiler.getLangOpts())
== "assert"))
{
return true;
}
}
if (isa<IntegerLiteral>(sub) || isa<CharacterLiteral>(sub)
|| isa<FloatingLiteral>(sub) || isa<ImaginaryLiteral>(sub)
|| isa<StringLiteral>(sub))
{
bool rewritten = false;
if (rewriter != nullptr) {
SourceLocation loc { compiler.getSourceManager().getExpansionLoc(
expr->getLocStart()) };
if (compiler.getSourceManager().getExpansionLoc(expr->getLocEnd())
== loc)
{
char const * s = compiler.getSourceManager().getCharacterData(
loc);
unsigned n = Lexer::MeasureTokenLength(
expr->getLocEnd(), compiler.getSourceManager(),
compiler.getLangOpts());
std::string tok { s, n };
if (tok == "sal_False" || tok == "0") {
rewritten = replaceText(
compiler.getSourceManager().getExpansionLoc(
expr->getLocStart()),
n, "false");
} else if (tok == "sal_True" || tok == "1") {
rewritten = replaceText(
compiler.getSourceManager().getExpansionLoc(
expr->getLocStart()),
n, "true");
}
}
}
if (!rewritten) {
report(
DiagnosticsEngine::Warning,
"implicit conversion (%0) of literal of type %1 to %2",
expr->getLocStart())
<< expr->getCastKindName() << expr->getSubExpr()->getType()
<< expr->getType() << expr->getSourceRange();
}
// At least Clang 3.2 would erroneously warn about Cache::add
// (binaryurp/source/cache.hxx:53)
//
// if( !size_) {
//
// as "implicit conversion (IntegralToBoolean) of null pointer constant of type
// 'std::size_t' (aka 'unsigned long') to 'bool'":
#if (__clang_major__ == 3 && __clang_minor__ >= 3) || __clang_major__ > 3
} else if (sub->isNullPointerConstant(
compiler.getASTContext(), Expr::NPC_ValueDependentIsNull)
!= Expr::NPCK_NotNull)
{
report(
DiagnosticsEngine::Warning,
("implicit conversion (%0) of null pointer constant of type %1 to"
" %2"),
expr->getLocStart())
<< expr->getCastKindName() << expr->getSubExpr()->getType()
<< expr->getType() << expr->getSourceRange();
#endif
} else if (sub->isIntegerConstantExpr(compiler.getASTContext())) {
report(
DiagnosticsEngine::Warning,
("implicit conversion (%0) of integer constant expression of type"
" %1 to %2"),
expr->getLocStart())
<< expr->getCastKindName() << expr->getSubExpr()->getType()
<< expr->getType() << expr->getSourceRange();
}
return true;
}
bool LiteralToBoolConversion::isFromCIncludeFile(
SourceLocation spellingLocation) const
{
#if (__clang_major__ == 3 && __clang_minor__ >= 4) || __clang_major__ > 3
if (compiler.getSourceManager().isInMainFile(spellingLocation)) {
return false;
}
#else
if (compiler.getSourceManager().isFromMainFile(spellingLocation)) {
return false;
}
#endif
return compiler.getSourceManager().getFilename(spellingLocation).endswith(
".h");
}
bool LiteralToBoolConversion::isMacroBodyExpansion(SourceLocation location)
const
{
#if (__clang_major__ == 3 && __clang_minor__ >= 3) || __clang_major__ > 3
return compiler.getSourceManager().isMacroBodyExpansion(location);
#else
return location.isMacroID()
&& !compiler.getSourceManager().isMacroArgExpansion(location);
#endif
}
loplugin::Plugin::Registration<LiteralToBoolConversion> X(
"literaltoboolconversion", true);
}
<commit_msg>literaltobool conversion plugin, reduce spurious warnings with clang 3.3<commit_after>/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */
/*
* This file is part of the LibreOffice project.
*
* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/.
*/
#include "clang/Lex/Lexer.h"
#include "plugin.hxx"
namespace {
class LiteralToBoolConversion:
public RecursiveASTVisitor<LiteralToBoolConversion>,
public loplugin::RewritePlugin
{
public:
explicit LiteralToBoolConversion(InstantiationData const & data):
RewritePlugin(data) {}
virtual void run() override
{ TraverseDecl(compiler.getASTContext().getTranslationUnitDecl()); }
bool VisitImplicitCastExpr(ImplicitCastExpr const * expr);
private:
bool isFromCIncludeFile(SourceLocation spellingLocation) const;
bool isMacroBodyExpansion(SourceLocation location) const;
};
bool LiteralToBoolConversion::VisitImplicitCastExpr(
ImplicitCastExpr const * expr)
{
if (ignoreLocation(expr)) {
return true;
}
if (!expr->getType()->isBooleanType()) {
return true;
}
Expr const * sub = expr->getSubExpr()->IgnoreParenCasts();
if (sub->getType()->isBooleanType()) {
return true;
}
IntegerLiteral const * lit = dyn_cast<IntegerLiteral>(sub);
if (lit != nullptr && lit->getValue().getLimitedValue() <= 1) {
SourceLocation loc { sub->getLocStart() };
while (compiler.getSourceManager().isMacroArgExpansion(loc)) {
loc = compiler.getSourceManager().getImmediateMacroCallerLoc(loc);
}
if (isMacroBodyExpansion(loc)) {
StringRef name { Lexer::getImmediateMacroName(
loc, compiler.getSourceManager(), compiler.getLangOpts()) };
if (name == "sal_False" || name == "sal_True") {
loc = compiler.getSourceManager().getImmediateExpansionRange(
loc).first;
}
if (isFromCIncludeFile(
compiler.getSourceManager().getSpellingLoc(loc)))
{
return true;
}
}
}
if (isa<StringLiteral>(sub)) {
SourceLocation loc { sub->getLocStart() };
if (compiler.getSourceManager().isMacroArgExpansion(loc)
&& (Lexer::getImmediateMacroName(
loc, compiler.getSourceManager(), compiler.getLangOpts())
== "assert"))
{
return true;
}
}
if (isa<IntegerLiteral>(sub) || isa<CharacterLiteral>(sub)
|| isa<FloatingLiteral>(sub) || isa<ImaginaryLiteral>(sub)
|| isa<StringLiteral>(sub))
{
bool rewritten = false;
if (rewriter != nullptr) {
SourceLocation loc { compiler.getSourceManager().getExpansionLoc(
expr->getLocStart()) };
if (compiler.getSourceManager().getExpansionLoc(expr->getLocEnd())
== loc)
{
char const * s = compiler.getSourceManager().getCharacterData(
loc);
unsigned n = Lexer::MeasureTokenLength(
expr->getLocEnd(), compiler.getSourceManager(),
compiler.getLangOpts());
std::string tok { s, n };
if (tok == "sal_False" || tok == "0") {
rewritten = replaceText(
compiler.getSourceManager().getExpansionLoc(
expr->getLocStart()),
n, "false");
} else if (tok == "sal_True" || tok == "1") {
rewritten = replaceText(
compiler.getSourceManager().getExpansionLoc(
expr->getLocStart()),
n, "true");
}
}
}
if (!rewritten) {
report(
DiagnosticsEngine::Warning,
"implicit conversion (%0) of literal of type %1 to %2",
expr->getLocStart())
<< expr->getCastKindName() << expr->getSubExpr()->getType()
<< expr->getType() << expr->getSourceRange();
}
// At least Clang 3.2 would erroneously warn about Cache::add
// (binaryurp/source/cache.hxx:53)
//
// if( !size_) {
//
// as "implicit conversion (IntegralToBoolean) of null pointer constant of type
// 'std::size_t' (aka 'unsigned long') to 'bool'":
#if (__clang_major__ == 3 && __clang_minor__ >= 4) || __clang_major__ > 3
} else if (sub->isNullPointerConstant(
compiler.getASTContext(), Expr::NPC_ValueDependentIsNull)
!= Expr::NPCK_NotNull)
{
report(
DiagnosticsEngine::Warning,
("implicit conversion (%0) of null pointer constant of type %1 to"
" %2"),
expr->getLocStart())
<< expr->getCastKindName() << expr->getSubExpr()->getType()
<< expr->getType() << expr->getSourceRange();
#endif
} else if (sub->isIntegerConstantExpr(compiler.getASTContext())) {
report(
DiagnosticsEngine::Warning,
("implicit conversion (%0) of integer constant expression of type"
" %1 to %2"),
expr->getLocStart())
<< expr->getCastKindName() << expr->getSubExpr()->getType()
<< expr->getType() << expr->getSourceRange();
}
return true;
}
bool LiteralToBoolConversion::isFromCIncludeFile(
SourceLocation spellingLocation) const
{
#if (__clang_major__ == 3 && __clang_minor__ >= 4) || __clang_major__ > 3
if (compiler.getSourceManager().isInMainFile(spellingLocation)) {
return false;
}
#else
if (compiler.getSourceManager().isFromMainFile(spellingLocation)) {
return false;
}
#endif
return compiler.getSourceManager().getFilename(spellingLocation).endswith(
".h");
}
bool LiteralToBoolConversion::isMacroBodyExpansion(SourceLocation location)
const
{
#if (__clang_major__ == 3 && __clang_minor__ >= 3) || __clang_major__ > 3
return compiler.getSourceManager().isMacroBodyExpansion(location);
#else
return location.isMacroID()
&& !compiler.getSourceManager().isMacroArgExpansion(location);
#endif
}
loplugin::Plugin::Registration<LiteralToBoolConversion> X(
"literaltoboolconversion", true);
}
<|endoftext|> |
<commit_before>#include "ofApp.h"
void ofApp::setup()
{
femurBone.load("femur.png");
images = { femurBone, femurBone, femurBone, femurBone, femurBone, femurBone, femurBone, femurBone };
angles = { 0, 0, 0, 0, 0, 0, 0, 0 };
anglesMinimum = { -360, -270, -180, -90, -80, -70, -60, -45 };
anglesMaximum = { 360, 270, 180, 90, 80, 70, 60, 45 };
anglesNoiseIncrement = { 0.01, 0.01, 0.01, 0.01, 0.01, 0.01, 0.01, 0.01 };
anglesNoiseOffsets = { ofRandom(100), ofRandom(100), ofRandom(100), ofRandom(100), ofRandom(100), ofRandom(100), ofRandom(100), ofRandom(100) };
anglesNoiseScales = { 2, 2, 2, 2, 2, 2, 2, 2 };
isNewSegment = { false, false, false, false, false, false, false, false };
}
void ofApp::update()
{
// Loop through all of the images!
for (std::size_t i = 0; i < images.size(); ++i)
{
// This is how we move through the Perlin noise. We adjust the offset
// just a tiny bit to get the next value in the neighborhood of noise.
anglesNoiseOffsets[i] += anglesNoiseIncrement[i];
// ... next we ask for the noise at the current offset. It will be a
// value between -1 and 1 for ofSignedNoise.
float noiseAtOffset = ofSignedNoise(anglesNoiseOffsets[i]);
// ... next we scale the noise by multiplying it by a scaler.
noiseAtOffset *= anglesNoiseScales[i];
// Now add some noise to the angle.
angles[i] = angles[i] + noiseAtOffset;
// Now clamp the angle values to keep them in a reasonable range.
angles[i] = ofClamp(angles[i], anglesMinimum[i], anglesMaximum[i]);
}
}
void ofApp::draw()
{
ofBackground(0);
ofSetColor(ofColor::white);
ofDrawBitmapString("Press spacebar for debug mode", 20, 20);
// Move our canvas (translate)
ofPushMatrix();
int x = ofGetMouseX();
int y = ofGetMouseY();
ofTranslate(x, y);
ofPopMatrix();
}
void ofApp::keyPressed(int key)
{
if (key == ' ')
{
showGrid = !showGrid;
}
}
void ofApp::drawGrid(float width, float height, float size)
{
ofPushStyle();
ofNoFill();
ofSetColor(255, 60);
for (int x = 0; x < width; x += size)
{
ofDrawLine(x, 0, x, height);
}
for (int y = 0; y < height; y += size)
{
ofDrawLine(0, y, width, y);
}
ofDrawRectangle(0, 0, width, height);
ofSetColor(ofColor::green);
ofDrawLine(0, 0, width / 2, 0);
ofSetColor(ofColor::red);
ofDrawLine(0, 0, 0, height / 2);
ofPopStyle();
}
<commit_msg>Fix missing code.<commit_after>#include "ofApp.h"
void ofApp::setup()
{
femurBone.load("femur.png");
images = { femurBone, femurBone, femurBone, femurBone, femurBone, femurBone, femurBone, femurBone };
angles = { 0, 0, 0, 0, 0, 0, 0, 0 };
anglesMinimum = { -360, -270, -180, -90, -80, -70, -60, -45 };
anglesMaximum = { 360, 270, 180, 90, 80, 70, 60, 45 };
anglesNoiseIncrement = { 0.01, 0.01, 0.01, 0.01, 0.01, 0.01, 0.01, 0.01 };
anglesNoiseOffsets = { ofRandom(100), ofRandom(100), ofRandom(100), ofRandom(100), ofRandom(100), ofRandom(100), ofRandom(100), ofRandom(100) };
anglesNoiseScales = { 2, 2, 2, 2, 2, 2, 2, 2 };
isNewSegment = { false, false, false, false, false, false, false, false };
}
void ofApp::update()
{
// Loop through all of the images!
for (std::size_t i = 0; i < images.size(); ++i)
{
// This is how we move through the Perlin noise. We adjust the offset
// just a tiny bit to get the next value in the neighborhood of noise.
anglesNoiseOffsets[i] += anglesNoiseIncrement[i];
// ... next we ask for the noise at the current offset. It will be a
// value between -1 and 1 for ofSignedNoise.
float noiseAtOffset = ofSignedNoise(anglesNoiseOffsets[i]);
// ... next we scale the noise by multiplying it by a scaler.
noiseAtOffset *= anglesNoiseScales[i];
// Now add some noise to the angle.
angles[i] = angles[i] + noiseAtOffset;
// Now clamp the angle values to keep them in a reasonable range.
angles[i] = ofClamp(angles[i], anglesMinimum[i], anglesMaximum[i]);
}
}
void ofApp::draw()
{
ofBackground(0);
ofSetColor(ofColor::white);
ofDrawBitmapString("Press spacebar for debug mode", 20, 20);
// Move our canvas (translate)
ofPushMatrix();
int x = ofGetMouseX();
int y = ofGetMouseY();
ofTranslate(x, y);
// Loop through all o fthe images.
for (std::size_t i = 0; i < images.size(); ++i)
{
// If we want to have different attachment points, we must push (or not
// push) a new transoformation matrix.
if (isNewSegment[i])
{
ofPushMatrix();
}
ofRotateZDeg(angles[i]);
images[i].draw(-images[i].getWidth() / 2,
-images[i].getWidth() / 2);
// We draw the debugging here so that it is on top of our image.
if (showGrid)
{
drawGrid(80, 80, 10);
ofDrawBitmapString(ofToString("Transform: " + ofToString(i)), 14, 14);
}
ofTranslate(0, images[i].getHeight());
// If we pushed a new matrix, go ahead and pop it off again.
if (isNewSegment[i])
{
ofPopMatrix();
}
}
ofPopMatrix();
}
void ofApp::keyPressed(int key)
{
if (key == ' ')
{
showGrid = !showGrid;
}
}
void ofApp::drawGrid(float width, float height, float size)
{
ofPushStyle();
ofNoFill();
ofSetColor(255, 60);
for (int x = 0; x < width; x += size)
{
ofDrawLine(x, 0, x, height);
}
for (int y = 0; y < height; y += size)
{
ofDrawLine(0, y, width, y);
}
ofDrawRectangle(0, 0, width, height);
ofSetColor(ofColor::green);
ofDrawLine(0, 0, width / 2, 0);
ofSetColor(ofColor::red);
ofDrawLine(0, 0, 0, height / 2);
ofPopStyle();
}
<|endoftext|> |
<commit_before>#include <string>
#include <map>
#include "EntityManager.h"
#include "Item.h"
#include "Weapon.h"
#include "Armor.h"
EntityManager::EntityManager()
{
}
EntityManager::~EntityManager()
{
for (auto& entity : data)
{
if (entity.second != nullptr)
{
delete entity.second;
entity.second = nullptr;
}
}
}
template <typename T>
void EntityManager::LoadJSON(std::string fileName)
{
JsonBox::Value v;
v.loadFromFile(fileName);
JsonBox::Object obj = v.getObject();
for (auto& entity : obj)
{
std::string key = entity.first;
data[key] = dynamic_cast<Entity*>(new T(key, entity.second, this));
}
}
template <typename T>
T* EntityManager::GetEntity(std::string id)
{
if (id.substr(0, EntityToString<T>().size()) == EntityToString<T>())
return dynamic_cast<T*>(data.at(id));
else
return nullptr;
}
template <> std::string EntityToString<Item>() { return "Item"; }
template <> std::string EntityToString<Weapon>() { return "Weapon"; }
template <> std::string EntityToString<Armor>() { return "Armor"; }
template void EntityManager::LoadJSON<Item>(std::string);
template void EntityManager::LoadJSON<Weapon>(std::string);
template void EntityManager::LoadJSON<Armor>(std::string);
template Item* EntityManager::GetEntity<Item>(std::string);
template Weapon* EntityManager::GetEntity<Weapon>(std::string);
template Armor* EntityManager::GetEntity<Armor>(std::string);<commit_msg>Modify uppercase to lowercase<commit_after>#include <string>
#include <map>
#include "EntityManager.h"
#include "Item.h"
#include "Weapon.h"
#include "Armor.h"
#include "Creature.h"
#include "Area.h"
#include "Door.h"
EntityManager::EntityManager()
{
}
EntityManager::~EntityManager()
{
for (auto& entity : data)
{
if (entity.second != nullptr)
{
delete entity.second;
entity.second = nullptr;
}
}
}
template <typename T>
void EntityManager::LoadJSON(std::string fileName)
{
JsonBox::Value v;
v.loadFromFile(fileName);
JsonBox::Object obj = v.getObject();
for (auto entity : obj)
{
std::string key = entity.first;
data[key] = dynamic_cast<Entity*>(new T(key, entity.second, this));
}
}
template <typename T>
T* EntityManager::GetEntity(std::string id)
{
if (id.substr(0, EntityToString<T>().size()) == EntityToString<T>())
return dynamic_cast<T*>(data.at(id));
else
return nullptr;
}
template <> std::string EntityToString<Item>() { return "item"; }
template <> std::string EntityToString<Weapon>() { return "weapon"; }
template <> std::string EntityToString<Armor>() { return "armor"; }
template <> std::string EntityToString<Creature>() { return "creature"; }
template <> std::string EntityToString<Area>() { return "area"; }
template <> std::string EntityToString<Door>() { return "door"; }
template void EntityManager::LoadJSON<Item>(std::string);
template void EntityManager::LoadJSON<Weapon>(std::string);
template void EntityManager::LoadJSON<Armor>(std::string);
template void EntityManager::LoadJSON<Creature>(std::string);
template void EntityManager::LoadJSON<Area>(std::string);
template void EntityManager::LoadJSON<Door>(std::string);
template Item* EntityManager::GetEntity<Item>(std::string);
template Weapon* EntityManager::GetEntity<Weapon>(std::string);
template Armor* EntityManager::GetEntity<Armor>(std::string);
template Creature* EntityManager::GetEntity<Creature>(std::string);
template Area* EntityManager::GetEntity<Area>(std::string);
template Door* EntityManager::GetEntity<Door>(std::string);
<|endoftext|> |
<commit_before>/*
* Author(s):
* - Chris Kilner <ckilner@aldebaran-robotics.com>
* - Cedric Gestes <gestes@aldebaran-robotics.com>
*
* Copyright (C) 2010, 2011 Aldebaran Robotics
*/
#include <qi/log.hpp>
#include <qi/os.hpp>
#include <list>
#include <map>
#include <qi/log/consoleloghandler.hpp>
#include <boost/thread/thread.hpp>
#include <boost/thread/condition_variable.hpp>
#include <boost/lockfree/fifo.hpp>
#include <boost/function.hpp>
#define RTLOG_BUFFERS (128)
#define CAT_SIZE 64
#define FILE_SIZE 128
#define FUNC_SIZE 64
#define LOG_SIZE 2048
namespace qi {
namespace log {
static LogLevel _glVerbosity;
static bool _glContext;
typedef struct sPrivateLog
{
LogLevel _logLevel;
char _category[CAT_SIZE];
char _file[FILE_SIZE];
char _function[FUNC_SIZE];
int _line;
char _log[LOG_SIZE];
} privateLog;
static privateLog rtLogBuffer[RTLOG_BUFFERS];
static volatile unsigned long rtLogPush = 0;
static ConsoleLogHandler gConsoleLogHandler;
static class rtLog
{
public:
inline rtLog();
inline ~rtLog();
void run();
void printLog();
public:
bool rtLogInit;
boost::thread rtLogThread;
boost::mutex rtLogWriteLock;
boost::condition_variable rtLogReadyCond;
boost::lockfree::fifo<privateLog*> logs;
std::map<std::string, logFuncHandler > logHandlers;
} rtLogInstance;
void rtLog::printLog()
{
privateLog* pl;
while (logs.dequeue(&pl))
{
boost::mutex::scoped_lock lock(rtLogWriteLock);
if (!logHandlers.empty())
{
std::map<std::string, logFuncHandler >::iterator it;
for (it = logHandlers.begin();
it != logHandlers.end(); ++it)
{
(*it).second(pl->_logLevel,
pl->_file,
pl->_function,
pl->_category,
pl->_line,
pl->_log);
}
}
else
{
printf("[MISSING Logger]: %s\n", pl->_log);
}
}
}
void rtLog::run()
{
while (rtLogInit)
{
{
boost::mutex::scoped_lock lock(rtLogWriteLock);
rtLogReadyCond.wait(lock);
}
printLog();
}
};
inline rtLog::rtLog()
{
rtLogInit = true;
rtLogThread = boost::thread(&rtLog::run, &rtLogInstance);
};
inline rtLog::~rtLog()
{
if (!rtLogInit)
return;
rtLogInit = false;
rtLogReadyCond.notify_one();
if (rtLogThread.joinable())
{
rtLogThread.join();
}
printLog();
}
void log(const LogLevel verb,
const char *file,
const char *fct,
const char *category,
const int line,
const char *msg)
{
if (!rtLogInstance.rtLogInit)
return;
int tmpRtLogPush = ++rtLogPush % RTLOG_BUFFERS;
privateLog* pl = &(rtLogBuffer[tmpRtLogPush]);
pl->_logLevel = verb;
pl->_line = line;
#ifdef _MSC_VER
if (category != NULL)
strcpy_s(pl->_category, CAT_SIZE, category);
else
strcpy_s(pl->_category, CAT_SIZE, "(null)");
if (file != NULL)
strcpy_s(pl->_file, FILE_SIZE, file);
else
strcpy_s(pl->_file, CAT_SIZE, "(null)");
if (fct != NULL)
strcpy_s(pl->_function, FUNC_SIZE, fct);
else
strcpy_s(pl->_function, CAT_SIZE, "(null)");
if (msg != NULL)
strcpy_s(pl->_log, LOG_SIZE, msg);
else
strcpy_s(pl->_log, CAT_SIZE, "(null)");
#else
if (category != NULL)
strncpy(pl->_category, category, CAT_SIZE);
else
strncpy(pl->_category, "(null)", CAT_SIZE);
if (file != NULL)
strncpy(pl->_file, file, FILE_SIZE);
else
strncpy(pl->_file, "(null)", FILE_SIZE);
if (fct != NULL)
strncpy(pl->_function, fct, FUNC_SIZE);
else
strncpy(pl->_function, "(null)", FUNC_SIZE);
if (msg != NULL)
strncpy(pl->_log, msg, LOG_SIZE);
else
strncpy(pl->_log, "(null)", LOG_SIZE);
#endif
pl->_category[CAT_SIZE - 1] = '\0';
pl->_file[FILE_SIZE - 1] = '\0';
pl->_function[FUNC_SIZE - 1] = '\0';
pl->_log[LOG_SIZE - 1] = '\0';
rtLogInstance.logs.enqueue(pl);
rtLogInstance.rtLogReadyCond.notify_one();
}
void consoleLogHandler(const LogLevel verb,
const char *file,
const char *fct,
const char *category,
const int line,
const char *msg)
{
gConsoleLogHandler.log(verb, file, fct, category, line, msg);
}
static class LogHandlerInit
{
public:
LogHandlerInit()
{
addLogHandler(consoleLogHandler, "consoleloghandler");
}
} gLogHandlerInit;
void addLogHandler(logFuncHandler fct, const std::string& name)
{
{
boost::mutex::scoped_lock l(rtLogInstance.rtLogWriteLock);
rtLogInstance.logHandlers[name] = fct;
}
}
void removeLogHandler(const std::string& name)
{
{
boost::mutex::scoped_lock l(rtLogInstance.rtLogWriteLock);
rtLogInstance.logHandlers.erase(name);
}
}
const LogLevel stringToLogLevel(const char* verb)
{
std::string v(verb);
if (v == "silent")
return qi::log::silent;
if (v == "fatal")
return qi::log::fatal;
if (v == "error")
return qi::log::error;
if (v == "warning")
return qi::log::warning;
if (v == "info")
return qi::log::info;
if (v == "verbose")
return qi::log::verbose;
if (v == "debug")
return qi::log::debug;
return qi::log::info;
}
const char *logLevelToString(const LogLevel verb)
{
static const char *sverb[] = {
"[SILENT]", // never shown
"[FATAL]",
"[ERROR]",
"[WARN ]",
"[INFO ]",
"[VERB ]",
"[DEBUG]"
};
return sverb[verb];
}
void setVerbosity(const LogLevel lv)
{
_glVerbosity = lv;
};
LogLevel getVerbosity()
{
return _glVerbosity;
};
void setContext(bool ctx)
{
_glContext = ctx;
};
bool getContext()
{
return _glContext;
};
} // namespace log
} // namespace qi
<commit_msg>naoqi: Fix main options (add quite mode)<commit_after>/*
* Author(s):
* - Chris Kilner <ckilner@aldebaran-robotics.com>
* - Cedric Gestes <gestes@aldebaran-robotics.com>
*
* Copyright (C) 2010, 2011 Aldebaran Robotics
*/
#include <qi/log.hpp>
#include <qi/os.hpp>
#include <list>
#include <map>
#include <qi/log/consoleloghandler.hpp>
#include <boost/thread/thread.hpp>
#include <boost/thread/condition_variable.hpp>
#include <boost/lockfree/fifo.hpp>
#include <boost/function.hpp>
#define RTLOG_BUFFERS (128)
#define CAT_SIZE 64
#define FILE_SIZE 128
#define FUNC_SIZE 64
#define LOG_SIZE 2048
namespace qi {
namespace log {
static LogLevel _glVerbosity;
static bool _glContext;
typedef struct sPrivateLog
{
LogLevel _logLevel;
char _category[CAT_SIZE];
char _file[FILE_SIZE];
char _function[FUNC_SIZE];
int _line;
char _log[LOG_SIZE];
} privateLog;
static privateLog rtLogBuffer[RTLOG_BUFFERS];
static volatile unsigned long rtLogPush = 0;
static ConsoleLogHandler gConsoleLogHandler;
static class rtLog
{
public:
inline rtLog();
inline ~rtLog();
void run();
void printLog();
public:
bool rtLogInit;
boost::thread rtLogThread;
boost::mutex rtLogWriteLock;
boost::condition_variable rtLogReadyCond;
boost::lockfree::fifo<privateLog*> logs;
std::map<std::string, logFuncHandler > logHandlers;
} rtLogInstance;
void rtLog::printLog()
{
privateLog* pl;
while (logs.dequeue(&pl))
{
boost::mutex::scoped_lock lock(rtLogWriteLock);
if (!logHandlers.empty())
{
std::map<std::string, logFuncHandler >::iterator it;
for (it = logHandlers.begin();
it != logHandlers.end(); ++it)
{
(*it).second(pl->_logLevel,
pl->_file,
pl->_function,
pl->_category,
pl->_line,
pl->_log);
}
}
}
}
void rtLog::run()
{
while (rtLogInit)
{
{
boost::mutex::scoped_lock lock(rtLogWriteLock);
rtLogReadyCond.wait(lock);
}
printLog();
}
};
inline rtLog::rtLog()
{
rtLogInit = true;
rtLogThread = boost::thread(&rtLog::run, &rtLogInstance);
};
inline rtLog::~rtLog()
{
if (!rtLogInit)
return;
rtLogInit = false;
rtLogReadyCond.notify_one();
if (rtLogThread.joinable())
{
rtLogThread.join();
}
printLog();
}
void log(const LogLevel verb,
const char *file,
const char *fct,
const char *category,
const int line,
const char *msg)
{
if (!rtLogInstance.rtLogInit)
return;
int tmpRtLogPush = ++rtLogPush % RTLOG_BUFFERS;
privateLog* pl = &(rtLogBuffer[tmpRtLogPush]);
pl->_logLevel = verb;
pl->_line = line;
#ifdef _MSC_VER
if (category != NULL)
strcpy_s(pl->_category, CAT_SIZE, category);
else
strcpy_s(pl->_category, CAT_SIZE, "(null)");
if (file != NULL)
strcpy_s(pl->_file, FILE_SIZE, file);
else
strcpy_s(pl->_file, CAT_SIZE, "(null)");
if (fct != NULL)
strcpy_s(pl->_function, FUNC_SIZE, fct);
else
strcpy_s(pl->_function, CAT_SIZE, "(null)");
if (msg != NULL)
strcpy_s(pl->_log, LOG_SIZE, msg);
else
strcpy_s(pl->_log, CAT_SIZE, "(null)");
#else
if (category != NULL)
strncpy(pl->_category, category, CAT_SIZE);
else
strncpy(pl->_category, "(null)", CAT_SIZE);
if (file != NULL)
strncpy(pl->_file, file, FILE_SIZE);
else
strncpy(pl->_file, "(null)", FILE_SIZE);
if (fct != NULL)
strncpy(pl->_function, fct, FUNC_SIZE);
else
strncpy(pl->_function, "(null)", FUNC_SIZE);
if (msg != NULL)
strncpy(pl->_log, msg, LOG_SIZE);
else
strncpy(pl->_log, "(null)", LOG_SIZE);
#endif
pl->_category[CAT_SIZE - 1] = '\0';
pl->_file[FILE_SIZE - 1] = '\0';
pl->_function[FUNC_SIZE - 1] = '\0';
pl->_log[LOG_SIZE - 1] = '\0';
rtLogInstance.logs.enqueue(pl);
rtLogInstance.rtLogReadyCond.notify_one();
}
void consoleLogHandler(const LogLevel verb,
const char *file,
const char *fct,
const char *category,
const int line,
const char *msg)
{
gConsoleLogHandler.log(verb, file, fct, category, line, msg);
}
static class LogHandlerInit
{
public:
LogHandlerInit()
{
addLogHandler(consoleLogHandler, "consoleloghandler");
}
} gLogHandlerInit;
void addLogHandler(logFuncHandler fct, const std::string& name)
{
{
boost::mutex::scoped_lock l(rtLogInstance.rtLogWriteLock);
rtLogInstance.logHandlers[name] = fct;
}
}
void removeLogHandler(const std::string& name)
{
{
boost::mutex::scoped_lock l(rtLogInstance.rtLogWriteLock);
rtLogInstance.logHandlers.erase(name);
}
}
const LogLevel stringToLogLevel(const char* verb)
{
std::string v(verb);
if (v == "silent")
return qi::log::silent;
if (v == "fatal")
return qi::log::fatal;
if (v == "error")
return qi::log::error;
if (v == "warning")
return qi::log::warning;
if (v == "info")
return qi::log::info;
if (v == "verbose")
return qi::log::verbose;
if (v == "debug")
return qi::log::debug;
return qi::log::info;
}
const char *logLevelToString(const LogLevel verb)
{
static const char *sverb[] = {
"[SILENT]", // never shown
"[FATAL]",
"[ERROR]",
"[WARN ]",
"[INFO ]",
"[VERB ]",
"[DEBUG]"
};
return sverb[verb];
}
void setVerbosity(const LogLevel lv)
{
_glVerbosity = lv;
};
LogLevel getVerbosity()
{
return _glVerbosity;
};
void setContext(bool ctx)
{
_glContext = ctx;
};
bool getContext()
{
return _glContext;
};
} // namespace log
} // namespace qi
<|endoftext|> |
<commit_before>#pragma once
#include "GLPersistentBuffer.h"
template <GLenum T>
GLPersistentBuffer<T>::GLPersistentBuffer(const size_t byte_sz): m_byte_sz{byte_sz} {
gl::GenBuffers(1, &m_handle);
// Allocate buffer on GPU
gl::BindBuffer(T, m_handle);
static const GLbitfield map_flags{gl::MAP_PERSISTENT_BIT | // Persistent flag
gl::MAP_COHERENT_BIT | // Make changes auto. visible to GPU
gl::MAP_WRITE_BIT }; // Map it for writing
gl::BufferStorage(T, m_byte_sz, nullptr, map_flags);
// Map the data
m_buffer = gl::MapBufferRange(T, 0, m_byte_sz, map_flags);
}
template <GLenum T>
GLPersistentBuffer<T>::GLPersistentBuffer(const GLPersistentBuffer& pbo): m_byte_sz{pbo.m_byte_sz} {
gl::GenBuffers(1, &m_handle);
// Allocate buffer on GPU
gl::BindBuffer(T, m_handle);
static const GLbitfield map_flags{gl::MAP_PERSISTENT_BIT | // Persistent flag
gl::MAP_COHERENT_BIT | // Make changes auto. visible to GPU
gl::MAP_WRITE_BIT }; // Map it for writing
gl::BufferStorage(T, m_byte_sz, nullptr, map_flags);
// Map the data
m_buffer = gl::MapBufferRange(T, 0, m_byte_sz, map_flags);
}
template <GLenum T>
GLPersistentBuffer<T>& GLPersistentBuffer<T>::operator=(const GLPersistentBuffer& pbo) {
// Destroy the old buffer
// Technically, it may be possible to reuse it, but
// destroying it and creating a new one is simpler and faster
destroy();
// Now copy the data
m_byte_sz = pbo.m_byte_sz;
gl::GenBuffers(1, &m_handle);
// Allocate buffer on GPU
gl::BindBuffer(T, m_handle);
static const GLbitfield map_flags{gl::MAP_PERSISTENT_BIT | // Persistent flag
gl::MAP_COHERENT_BIT | // Make changes auto. visible to GPU
gl::MAP_WRITE_BIT}; // Map it for writing
gl::BufferStorage(T, m_byte_sz, nullptr, map_flags);
// Map the data
m_buffer = gl::MapBufferRange(T, 0, m_byte_sz, map_flags);
return *this;
}
template <GLenum T>
GLPersistentBuffer<T>::GLPersistentBuffer(GLPersistentBuffer&& pbo): m_buffer{pbo.m_buffer},
m_byte_sz{pbo.m_byte_sz},
m_handle{pbo.m_handle} {
// Mark as moved
pbo.m_handle = 0;
}
template <GLenum T>
GLPersistentBuffer<T>& GLPersistentBuffer<T>::operator=(GLPersistentBuffer&& pbo) {
// Destroy the old buffer
// Technically, it may be possible to reuse it, but
// destroying it and creating a new one is simpler and faster
destroy();
// Now copy the data
memcpy(this, &pbo, sizeof(*this));
// Mark as moved
pbo.m_handle = 0;
return *this;
}
template <GLenum T>
GLPersistentBuffer<T>::~GLPersistentBuffer() {
// Check if it was moved
if (m_handle) {
destroy();
}
}
template <GLenum T>
void GLPersistentBuffer<T>::destroy() {
gl::BindBuffer(T, m_handle);
gl::UnmapBuffer(T);
gl::DeleteBuffers(1, &m_handle);
}
template <GLenum T>
void* GLPersistentBuffer<T>::data() {
return m_buffer;
}
template <GLenum T>
const void* GLPersistentBuffer<T>::data() const {
return m_buffer;
}
template <GLenum T>
void GLPersistentBuffer<T>::bind(const GLuint bind_idx) const {
gl::BindBufferBase(T, bind_idx, m_handle);
}
<commit_msg>Vertically aligned comments.<commit_after>#pragma once
#include "GLPersistentBuffer.h"
template <GLenum T>
GLPersistentBuffer<T>::GLPersistentBuffer(const size_t byte_sz): m_byte_sz{byte_sz} {
gl::GenBuffers(1, &m_handle);
// Allocate buffer on GPU
gl::BindBuffer(T, m_handle);
static const GLbitfield map_flags{gl::MAP_PERSISTENT_BIT | // Persistent flag
gl::MAP_COHERENT_BIT | // Make changes auto. visible to GPU
gl::MAP_WRITE_BIT }; // Map it for writing
gl::BufferStorage(T, m_byte_sz, nullptr, map_flags);
// Map the data
m_buffer = gl::MapBufferRange(T, 0, m_byte_sz, map_flags);
}
template <GLenum T>
GLPersistentBuffer<T>::GLPersistentBuffer(const GLPersistentBuffer& pbo): m_byte_sz{pbo.m_byte_sz} {
gl::GenBuffers(1, &m_handle);
// Allocate buffer on GPU
gl::BindBuffer(T, m_handle);
static const GLbitfield map_flags{gl::MAP_PERSISTENT_BIT | // Persistent flag
gl::MAP_COHERENT_BIT | // Make changes auto. visible to GPU
gl::MAP_WRITE_BIT }; // Map it for writing
gl::BufferStorage(T, m_byte_sz, nullptr, map_flags);
// Map the data
m_buffer = gl::MapBufferRange(T, 0, m_byte_sz, map_flags);
}
template <GLenum T>
GLPersistentBuffer<T>& GLPersistentBuffer<T>::operator=(const GLPersistentBuffer& pbo) {
// Destroy the old buffer
// Technically, it may be possible to reuse it, but
// destroying it and creating a new one is simpler and faster
destroy();
// Now copy the data
m_byte_sz = pbo.m_byte_sz;
gl::GenBuffers(1, &m_handle);
// Allocate buffer on GPU
gl::BindBuffer(T, m_handle);
static const GLbitfield map_flags{gl::MAP_PERSISTENT_BIT | // Persistent flag
gl::MAP_COHERENT_BIT | // Make changes auto. visible to GPU
gl::MAP_WRITE_BIT}; // Map it for writing
gl::BufferStorage(T, m_byte_sz, nullptr, map_flags);
// Map the data
m_buffer = gl::MapBufferRange(T, 0, m_byte_sz, map_flags);
return *this;
}
template <GLenum T>
GLPersistentBuffer<T>::GLPersistentBuffer(GLPersistentBuffer&& pbo): m_buffer{pbo.m_buffer},
m_byte_sz{pbo.m_byte_sz},
m_handle{pbo.m_handle} {
// Mark as moved
pbo.m_handle = 0;
}
template <GLenum T>
GLPersistentBuffer<T>& GLPersistentBuffer<T>::operator=(GLPersistentBuffer&& pbo) {
// Destroy the old buffer
// Technically, it may be possible to reuse it, but
// destroying it and creating a new one is simpler and faster
destroy();
// Now copy the data
memcpy(this, &pbo, sizeof(*this));
// Mark as moved
pbo.m_handle = 0;
return *this;
}
template <GLenum T>
GLPersistentBuffer<T>::~GLPersistentBuffer() {
// Check if it was moved
if (m_handle) {
destroy();
}
}
template <GLenum T>
void GLPersistentBuffer<T>::destroy() {
gl::BindBuffer(T, m_handle);
gl::UnmapBuffer(T);
gl::DeleteBuffers(1, &m_handle);
}
template <GLenum T>
void* GLPersistentBuffer<T>::data() {
return m_buffer;
}
template <GLenum T>
const void* GLPersistentBuffer<T>::data() const {
return m_buffer;
}
template <GLenum T>
void GLPersistentBuffer<T>::bind(const GLuint bind_idx) const {
gl::BindBufferBase(T, bind_idx, m_handle);
}
<|endoftext|> |
<commit_before>
#define BOOST_TEST_DYN_LINK
#define BOOST_TEST_MODULE libstorage
#include <boost/test/unit_test.hpp>
#include "storage/Utils/Region.h"
#include "storage/Utils/HumanString.h"
using namespace std;
using namespace storage;
BOOST_AUTO_TEST_CASE(test_output)
{
Region region(2048, 1603584, 512);
ostringstream out;
out << region;
BOOST_CHECK_EQUAL(out.str(), "[2048, 1603584, 512 B]");
}
BOOST_AUTO_TEST_CASE(test_block_size_512)
{
Region region(2048, 1603584, 512);
BOOST_CHECK(!region.empty());
BOOST_CHECK_EQUAL(region.get_start(), 2048);
BOOST_CHECK_EQUAL(region.get_length(), 1603584);
BOOST_CHECK_EQUAL(region.get_end(), 1605631);
BOOST_CHECK_EQUAL(region.get_block_size(), 512);
BOOST_CHECK_EQUAL(region.to_bytes(region.get_start()), 1 * MiB);
BOOST_CHECK_EQUAL(region.to_bytes(region.get_length()), 821035008);
BOOST_CHECK_EQUAL(region.to_bytes(region.get_end()), 822083072);
BOOST_CHECK_EQUAL(region.to_blocks(1 * MiB), region.get_start());
}
BOOST_AUTO_TEST_CASE(test_block_size_4096)
{
Region region(256, 65280, 4096);
BOOST_CHECK(!region.empty());
BOOST_CHECK_EQUAL(region.get_start(), 256);
BOOST_CHECK_EQUAL(region.get_length(), 65280);
BOOST_CHECK_EQUAL(region.get_end(), 65535);
BOOST_CHECK_EQUAL(region.get_block_size(), 4096);
BOOST_CHECK_EQUAL(region.to_bytes(region.get_start()), 1 * MiB);
BOOST_CHECK_EQUAL(region.to_bytes(region.get_length()), 261120 * KiB);
BOOST_CHECK_EQUAL(region.to_bytes(region.get_end()), 262140 * KiB);
BOOST_CHECK_EQUAL(region.to_blocks(1 * MiB), region.get_start());
}
BOOST_AUTO_TEST_CASE(test_set_values)
{
Region region(0, 1024, 32);
BOOST_CHECK_EQUAL(region.get_start(), 0);
BOOST_CHECK_EQUAL(region.get_length(), 1024);
BOOST_CHECK_EQUAL(region.get_end(), 1023);
BOOST_CHECK_EQUAL(region.get_block_size(), 32);
// setting the start does not change the length but the end
region.set_start(256);
BOOST_CHECK_EQUAL(region.get_start(), 256);
BOOST_CHECK_EQUAL(region.get_length(), 1024);
BOOST_CHECK_EQUAL(region.get_end(), 1279);
BOOST_CHECK_EQUAL(region.get_block_size(), 32);
// setting the length does not change the start but the end
region.set_length(512);
BOOST_CHECK_EQUAL(region.get_start(), 256);
BOOST_CHECK_EQUAL(region.get_length(), 512);
BOOST_CHECK_EQUAL(region.get_end(), 767);
BOOST_CHECK_EQUAL(region.get_block_size(), 32);
// setting the block-size does not change the start, length nor end
region.set_block_size(64);
BOOST_CHECK_EQUAL(region.get_start(), 256);
BOOST_CHECK_EQUAL(region.get_length(), 512);
BOOST_CHECK_EQUAL(region.get_end(), 767);
BOOST_CHECK_EQUAL(region.get_block_size(), 64);
}
BOOST_AUTO_TEST_CASE(test_comparisons)
{
// Four regions with block layout:
//
// aaaaaaaaaa
// bbbbbbbbbb
// cccccccccc
// dddddddddddddddddddd
Region a(0, 10, 1);
Region b(10, 10, 1);
Region c(5, 10, 1);
Region d(0, 20, 1);
BOOST_CHECK(a == a);
BOOST_CHECK(a != b);
BOOST_CHECK(a < b);
BOOST_CHECK(c > d);
BOOST_CHECK(a.inside(d));
BOOST_CHECK(!a.inside(c));
BOOST_CHECK(a.intersect(c));
BOOST_CHECK(!a.intersect(b));
BOOST_CHECK(a.intersection(c) == Region(5, 5, 1));
BOOST_CHECK_THROW(a.intersection(b), NoIntersection);
}
BOOST_AUTO_TEST_CASE(test_copy_constructor)
{
Region a(0, 10, 1);
Region b(a);
b.set_start(1);
BOOST_CHECK_EQUAL(a.get_start(), 0);
BOOST_CHECK_EQUAL(b.get_start(), 1);
}
BOOST_AUTO_TEST_CASE(test_copy_assignment)
{
Region a(0, 10, 1);
Region b;
(b = a).set_start(1);
BOOST_CHECK_EQUAL(a.get_start(), 0);
BOOST_CHECK_EQUAL(b.get_start(), 1);
}
BOOST_AUTO_TEST_CASE(test_invalid_block_size)
{
BOOST_CHECK_THROW(Region a(1, 2, 0), InvalidBlockSize);
}
BOOST_AUTO_TEST_CASE(test_different_block_size)
{
Region a(0, 100, 1);
Region b(0, 50, 2);
BOOST_CHECK_THROW((void)(a == b), DifferentBlockSizes);
}
BOOST_AUTO_TEST_CASE(test_big_numbers)
{
Region kb(0, 1ULL << (10 * 5), 1 * KiB);
BOOST_CHECK_EQUAL(kb.to_bytes(kb.get_length()), EiB);
Region mb(0, 1ULL << (10 * 4), 1 * MiB);
BOOST_CHECK_EQUAL(mb.to_bytes(mb.get_length()), EiB);
}
BOOST_AUTO_TEST_CASE(test_unused_regions1)
{
Region region(0, 100, 1);
vector<Region> unused_regions = region.unused_regions({
Region(30, 50, 1),
});
BOOST_CHECK_EQUAL(unused_regions.size(), 2);
BOOST_CHECK_EQUAL(unused_regions[0].get_start(), 0);
BOOST_CHECK_EQUAL(unused_regions[0].get_length(), 30);
BOOST_CHECK_EQUAL(unused_regions[1].get_start(), 80);
BOOST_CHECK_EQUAL(unused_regions[1].get_length(), 20);
}
BOOST_AUTO_TEST_CASE(test_unused_regions2)
{
Region region(0, 100, 1);
vector<Region> unused_regions = region.unused_regions({
Region(0, 10, 1),
Region(90, 10, 1)
});
BOOST_CHECK_EQUAL(unused_regions.size(), 1);
BOOST_CHECK_EQUAL(unused_regions[0].get_start(), 10);
BOOST_CHECK_EQUAL(unused_regions[0].get_length(), 80);
}
BOOST_AUTO_TEST_CASE(test_unused_regions3)
{
Region region(0, 100, 1);
vector<Region> unused_regions = region.unused_regions({
Region(90, 10, 1), // sorted incorrectly with other used region
Region(0, 10, 1) // sorted incorrectly with other used region
});
BOOST_CHECK_EQUAL(unused_regions.size(), 1);
BOOST_CHECK_EQUAL(unused_regions[0].get_start(), 10);
BOOST_CHECK_EQUAL(unused_regions[0].get_length(), 80);
}
BOOST_AUTO_TEST_CASE(test_unused_regions4)
{
Region region(0, 100, 1);
vector<Region> unused_regions = region.unused_regions({
Region(10, 10, 1),
Region(40, 20, 1),
Region(80, 15, 1)
});
BOOST_CHECK_EQUAL(unused_regions.size(), 4);
BOOST_CHECK_EQUAL(unused_regions[0].get_start(), 0);
BOOST_CHECK_EQUAL(unused_regions[0].get_length(), 10);
BOOST_CHECK_EQUAL(unused_regions[1].get_start(), 20);
BOOST_CHECK_EQUAL(unused_regions[1].get_length(), 20);
BOOST_CHECK_EQUAL(unused_regions[2].get_start(), 60);
BOOST_CHECK_EQUAL(unused_regions[2].get_length(), 20);
BOOST_CHECK_EQUAL(unused_regions[3].get_start(), 95);
BOOST_CHECK_EQUAL(unused_regions[3].get_length(), 5);
}
BOOST_AUTO_TEST_CASE(test_unused_regions5)
{
Region region(10, 80, 1);
vector<Region> unused_regions = region.unused_regions({
Region(0, 10, 1), // completely before region
Region(40, 20, 1),
Region(90, 10, 1) // completely behind region
});
BOOST_CHECK_EQUAL(unused_regions.size(), 2);
BOOST_CHECK_EQUAL(unused_regions[0].get_start(), 10);
BOOST_CHECK_EQUAL(unused_regions[0].get_length(), 30);
BOOST_CHECK_EQUAL(unused_regions[1].get_start(), 60);
BOOST_CHECK_EQUAL(unused_regions[1].get_length(), 30);
}
BOOST_AUTO_TEST_CASE(test_unused_regions6)
{
Region region(10, 80, 1);
vector<Region> unused_regions = region.unused_regions({
Region(0, 5, 1), // completely before region
Region(40, 20, 1),
Region(95, 5, 1) // completely behind region
});
BOOST_CHECK_EQUAL(unused_regions.size(), 2);
BOOST_CHECK_EQUAL(unused_regions[0].get_start(), 10);
BOOST_CHECK_EQUAL(unused_regions[0].get_length(), 30);
BOOST_CHECK_EQUAL(unused_regions[1].get_start(), 60);
BOOST_CHECK_EQUAL(unused_regions[1].get_length(), 30);
}
BOOST_AUTO_TEST_CASE(test_unused_regions7)
{
Region region(10, 80, 1);
vector<Region> unused_regions = region.unused_regions({
Region(0, 20, 1), // partly before region
Region(40, 20, 1),
Region(80, 20, 1) // partly behind region
});
BOOST_CHECK_EQUAL(unused_regions.size(), 2);
BOOST_CHECK_EQUAL(unused_regions[0].get_start(), 20);
BOOST_CHECK_EQUAL(unused_regions[0].get_length(), 20);
BOOST_CHECK_EQUAL(unused_regions[1].get_start(), 60);
BOOST_CHECK_EQUAL(unused_regions[1].get_length(), 20);
}
BOOST_AUTO_TEST_CASE(test_unused_regions8)
{
Region region(0, 100, 1);
vector<Region> unused_regions = region.unused_regions({
Region(20, 40, 1), // overlapping with other used region
Region(40, 40, 1) // overlapping with other used region
});
BOOST_CHECK_EQUAL(unused_regions.size(), 2);
BOOST_CHECK_EQUAL(unused_regions[0].get_start(), 0);
BOOST_CHECK_EQUAL(unused_regions[0].get_length(), 20);
BOOST_CHECK_EQUAL(unused_regions[1].get_start(), 80);
BOOST_CHECK_EQUAL(unused_regions[1].get_length(), 20);
}
BOOST_AUTO_TEST_CASE(test_unused_regions9)
{
Region region(0, 100, 1);
vector<Region> unused_regions = region.unused_regions({
Region(20, 60, 1), // overlapping with other used region
Region(40, 20, 1) // overlapping with other used region
});
BOOST_CHECK_EQUAL(unused_regions.size(), 2);
BOOST_CHECK_EQUAL(unused_regions[0].get_start(), 0);
BOOST_CHECK_EQUAL(unused_regions[0].get_length(), 20);
BOOST_CHECK_EQUAL(unused_regions[1].get_start(), 80);
BOOST_CHECK_EQUAL(unused_regions[1].get_length(), 20);
}
BOOST_AUTO_TEST_CASE(test_adjust_block_size1)
{
Region r(100, 1000, 10);
r.adjust_block_size(20);
BOOST_CHECK_EQUAL(r.get_start(), 50);
BOOST_CHECK_EQUAL(r.get_length(), 500);
BOOST_CHECK_EQUAL(r.get_block_size(), 20);
}
BOOST_AUTO_TEST_CASE(test_adjust_block_size2)
{
Region r1(100, 1000, 10);
Region r2(200, 1100, 10);
BOOST_CHECK_THROW(r1.adjust_block_size(2000), InvalidBlockSize);
BOOST_CHECK_THROW(r2.adjust_block_size(2000), InvalidBlockSize);
}
<commit_msg>Revert "add tests for adjust_block_size()"<commit_after>
#define BOOST_TEST_DYN_LINK
#define BOOST_TEST_MODULE libstorage
#include <boost/test/unit_test.hpp>
#include "storage/Utils/Region.h"
#include "storage/Utils/HumanString.h"
using namespace std;
using namespace storage;
BOOST_AUTO_TEST_CASE(test_output)
{
Region region(2048, 1603584, 512);
ostringstream out;
out << region;
BOOST_CHECK_EQUAL(out.str(), "[2048, 1603584, 512 B]");
}
BOOST_AUTO_TEST_CASE(test_block_size_512)
{
Region region(2048, 1603584, 512);
BOOST_CHECK(!region.empty());
BOOST_CHECK_EQUAL(region.get_start(), 2048);
BOOST_CHECK_EQUAL(region.get_length(), 1603584);
BOOST_CHECK_EQUAL(region.get_end(), 1605631);
BOOST_CHECK_EQUAL(region.get_block_size(), 512);
BOOST_CHECK_EQUAL(region.to_bytes(region.get_start()), 1 * MiB);
BOOST_CHECK_EQUAL(region.to_bytes(region.get_length()), 821035008);
BOOST_CHECK_EQUAL(region.to_bytes(region.get_end()), 822083072);
BOOST_CHECK_EQUAL(region.to_blocks(1 * MiB), region.get_start());
}
BOOST_AUTO_TEST_CASE(test_block_size_4096)
{
Region region(256, 65280, 4096);
BOOST_CHECK(!region.empty());
BOOST_CHECK_EQUAL(region.get_start(), 256);
BOOST_CHECK_EQUAL(region.get_length(), 65280);
BOOST_CHECK_EQUAL(region.get_end(), 65535);
BOOST_CHECK_EQUAL(region.get_block_size(), 4096);
BOOST_CHECK_EQUAL(region.to_bytes(region.get_start()), 1 * MiB);
BOOST_CHECK_EQUAL(region.to_bytes(region.get_length()), 261120 * KiB);
BOOST_CHECK_EQUAL(region.to_bytes(region.get_end()), 262140 * KiB);
BOOST_CHECK_EQUAL(region.to_blocks(1 * MiB), region.get_start());
}
BOOST_AUTO_TEST_CASE(test_set_values)
{
Region region(0, 1024, 32);
BOOST_CHECK_EQUAL(region.get_start(), 0);
BOOST_CHECK_EQUAL(region.get_length(), 1024);
BOOST_CHECK_EQUAL(region.get_end(), 1023);
BOOST_CHECK_EQUAL(region.get_block_size(), 32);
// setting the start does not change the length but the end
region.set_start(256);
BOOST_CHECK_EQUAL(region.get_start(), 256);
BOOST_CHECK_EQUAL(region.get_length(), 1024);
BOOST_CHECK_EQUAL(region.get_end(), 1279);
BOOST_CHECK_EQUAL(region.get_block_size(), 32);
// setting the length does not change the start but the end
region.set_length(512);
BOOST_CHECK_EQUAL(region.get_start(), 256);
BOOST_CHECK_EQUAL(region.get_length(), 512);
BOOST_CHECK_EQUAL(region.get_end(), 767);
BOOST_CHECK_EQUAL(region.get_block_size(), 32);
// setting the block-size does not change the start, length nor end
region.set_block_size(64);
BOOST_CHECK_EQUAL(region.get_start(), 256);
BOOST_CHECK_EQUAL(region.get_length(), 512);
BOOST_CHECK_EQUAL(region.get_end(), 767);
BOOST_CHECK_EQUAL(region.get_block_size(), 64);
}
BOOST_AUTO_TEST_CASE(test_comparisons)
{
// Four regions with block layout:
//
// aaaaaaaaaa
// bbbbbbbbbb
// cccccccccc
// dddddddddddddddddddd
Region a(0, 10, 1);
Region b(10, 10, 1);
Region c(5, 10, 1);
Region d(0, 20, 1);
BOOST_CHECK(a == a);
BOOST_CHECK(a != b);
BOOST_CHECK(a < b);
BOOST_CHECK(c > d);
BOOST_CHECK(a.inside(d));
BOOST_CHECK(!a.inside(c));
BOOST_CHECK(a.intersect(c));
BOOST_CHECK(!a.intersect(b));
BOOST_CHECK(a.intersection(c) == Region(5, 5, 1));
BOOST_CHECK_THROW(a.intersection(b), NoIntersection);
}
BOOST_AUTO_TEST_CASE(test_copy_constructor)
{
Region a(0, 10, 1);
Region b(a);
b.set_start(1);
BOOST_CHECK_EQUAL(a.get_start(), 0);
BOOST_CHECK_EQUAL(b.get_start(), 1);
}
BOOST_AUTO_TEST_CASE(test_copy_assignment)
{
Region a(0, 10, 1);
Region b;
(b = a).set_start(1);
BOOST_CHECK_EQUAL(a.get_start(), 0);
BOOST_CHECK_EQUAL(b.get_start(), 1);
}
BOOST_AUTO_TEST_CASE(test_invalid_block_size)
{
BOOST_CHECK_THROW(Region a(1, 2, 0), InvalidBlockSize);
}
BOOST_AUTO_TEST_CASE(test_different_block_size)
{
Region a(0, 100, 1);
Region b(0, 50, 2);
BOOST_CHECK_THROW((void)(a == b), DifferentBlockSizes);
}
BOOST_AUTO_TEST_CASE(test_big_numbers)
{
Region kb(0, 1ULL << (10 * 5), 1 * KiB);
BOOST_CHECK_EQUAL(kb.to_bytes(kb.get_length()), EiB);
Region mb(0, 1ULL << (10 * 4), 1 * MiB);
BOOST_CHECK_EQUAL(mb.to_bytes(mb.get_length()), EiB);
}
BOOST_AUTO_TEST_CASE(test_unused_regions1)
{
Region region(0, 100, 1);
vector<Region> unused_regions = region.unused_regions({
Region(30, 50, 1),
});
BOOST_CHECK_EQUAL(unused_regions.size(), 2);
BOOST_CHECK_EQUAL(unused_regions[0].get_start(), 0);
BOOST_CHECK_EQUAL(unused_regions[0].get_length(), 30);
BOOST_CHECK_EQUAL(unused_regions[1].get_start(), 80);
BOOST_CHECK_EQUAL(unused_regions[1].get_length(), 20);
}
BOOST_AUTO_TEST_CASE(test_unused_regions2)
{
Region region(0, 100, 1);
vector<Region> unused_regions = region.unused_regions({
Region(0, 10, 1),
Region(90, 10, 1)
});
BOOST_CHECK_EQUAL(unused_regions.size(), 1);
BOOST_CHECK_EQUAL(unused_regions[0].get_start(), 10);
BOOST_CHECK_EQUAL(unused_regions[0].get_length(), 80);
}
BOOST_AUTO_TEST_CASE(test_unused_regions3)
{
Region region(0, 100, 1);
vector<Region> unused_regions = region.unused_regions({
Region(90, 10, 1), // sorted incorrectly with other used region
Region(0, 10, 1) // sorted incorrectly with other used region
});
BOOST_CHECK_EQUAL(unused_regions.size(), 1);
BOOST_CHECK_EQUAL(unused_regions[0].get_start(), 10);
BOOST_CHECK_EQUAL(unused_regions[0].get_length(), 80);
}
BOOST_AUTO_TEST_CASE(test_unused_regions4)
{
Region region(0, 100, 1);
vector<Region> unused_regions = region.unused_regions({
Region(10, 10, 1),
Region(40, 20, 1),
Region(80, 15, 1)
});
BOOST_CHECK_EQUAL(unused_regions.size(), 4);
BOOST_CHECK_EQUAL(unused_regions[0].get_start(), 0);
BOOST_CHECK_EQUAL(unused_regions[0].get_length(), 10);
BOOST_CHECK_EQUAL(unused_regions[1].get_start(), 20);
BOOST_CHECK_EQUAL(unused_regions[1].get_length(), 20);
BOOST_CHECK_EQUAL(unused_regions[2].get_start(), 60);
BOOST_CHECK_EQUAL(unused_regions[2].get_length(), 20);
BOOST_CHECK_EQUAL(unused_regions[3].get_start(), 95);
BOOST_CHECK_EQUAL(unused_regions[3].get_length(), 5);
}
BOOST_AUTO_TEST_CASE(test_unused_regions5)
{
Region region(10, 80, 1);
vector<Region> unused_regions = region.unused_regions({
Region(0, 10, 1), // completely before region
Region(40, 20, 1),
Region(90, 10, 1) // completely behind region
});
BOOST_CHECK_EQUAL(unused_regions.size(), 2);
BOOST_CHECK_EQUAL(unused_regions[0].get_start(), 10);
BOOST_CHECK_EQUAL(unused_regions[0].get_length(), 30);
BOOST_CHECK_EQUAL(unused_regions[1].get_start(), 60);
BOOST_CHECK_EQUAL(unused_regions[1].get_length(), 30);
}
BOOST_AUTO_TEST_CASE(test_unused_regions6)
{
Region region(10, 80, 1);
vector<Region> unused_regions = region.unused_regions({
Region(0, 5, 1), // completely before region
Region(40, 20, 1),
Region(95, 5, 1) // completely behind region
});
BOOST_CHECK_EQUAL(unused_regions.size(), 2);
BOOST_CHECK_EQUAL(unused_regions[0].get_start(), 10);
BOOST_CHECK_EQUAL(unused_regions[0].get_length(), 30);
BOOST_CHECK_EQUAL(unused_regions[1].get_start(), 60);
BOOST_CHECK_EQUAL(unused_regions[1].get_length(), 30);
}
BOOST_AUTO_TEST_CASE(test_unused_regions7)
{
Region region(10, 80, 1);
vector<Region> unused_regions = region.unused_regions({
Region(0, 20, 1), // partly before region
Region(40, 20, 1),
Region(80, 20, 1) // partly behind region
});
BOOST_CHECK_EQUAL(unused_regions.size(), 2);
BOOST_CHECK_EQUAL(unused_regions[0].get_start(), 20);
BOOST_CHECK_EQUAL(unused_regions[0].get_length(), 20);
BOOST_CHECK_EQUAL(unused_regions[1].get_start(), 60);
BOOST_CHECK_EQUAL(unused_regions[1].get_length(), 20);
}
BOOST_AUTO_TEST_CASE(test_unused_regions8)
{
Region region(0, 100, 1);
vector<Region> unused_regions = region.unused_regions({
Region(20, 40, 1), // overlapping with other used region
Region(40, 40, 1) // overlapping with other used region
});
BOOST_CHECK_EQUAL(unused_regions.size(), 2);
BOOST_CHECK_EQUAL(unused_regions[0].get_start(), 0);
BOOST_CHECK_EQUAL(unused_regions[0].get_length(), 20);
BOOST_CHECK_EQUAL(unused_regions[1].get_start(), 80);
BOOST_CHECK_EQUAL(unused_regions[1].get_length(), 20);
}
BOOST_AUTO_TEST_CASE(test_unused_regions9)
{
Region region(0, 100, 1);
vector<Region> unused_regions = region.unused_regions({
Region(20, 60, 1), // overlapping with other used region
Region(40, 20, 1) // overlapping with other used region
});
BOOST_CHECK_EQUAL(unused_regions.size(), 2);
BOOST_CHECK_EQUAL(unused_regions[0].get_start(), 0);
BOOST_CHECK_EQUAL(unused_regions[0].get_length(), 20);
BOOST_CHECK_EQUAL(unused_regions[1].get_start(), 80);
BOOST_CHECK_EQUAL(unused_regions[1].get_length(), 20);
}
<|endoftext|> |
<commit_before>/*************************************************************************
*
* $RCSfile: XUnbufferedStream.cxx,v $
*
* $Revision: 1.6 $
*
* last change: $Author: kz $ $Date: 2003-09-11 10:16:55 $
*
* 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): Martin Gallwey (gallwey@sun.com)
*
*
************************************************************************/
#ifndef _XUNBUFFERED_STREAM_HXX
#include <XUnbufferedStream.hxx>
#endif
#ifndef _ENCRYPTION_DATA_HXX_
#include <EncryptionData.hxx>
#endif
#ifndef _COM_SUN_STAR_PACKAGES_ZIP_ZIPCONSTANTS_HPP_
#include <com/sun/star/packages/zip/ZipConstants.hpp>
#endif
#ifndef _COM_SUN_STAR_PACKAGES_ZIP_ZIPIOEXCEPTION_HPP_
#include <com/sun/star/packages/zip/ZipIOException.hpp>
#endif
#ifndef _PACKAGE_CONSTANTS_HXX_
#include <PackageConstants.hxx>
#endif
#ifndef _RTL_CIPHER_H_
#include <rtl/cipher.h>
#endif
#ifndef _ZIP_FILE_HXX
#include <ZipFile.hxx>
#endif
#ifndef _ENCRYPTED_DATA_HEADER_HXX_
#include <EncryptedDataHeader.hxx>
#endif
#include <algorithm>
using namespace com::sun::star::packages::zip::ZipConstants;
using namespace com::sun::star::io;
using namespace com::sun::star::uno;
using com::sun::star::lang::IllegalArgumentException;
using com::sun::star::packages::zip::ZipIOException;
using ::rtl::OUString;
XUnbufferedStream::XUnbufferedStream( ZipEntry & rEntry,
Reference < XInputStream > xNewZipStream,
const vos::ORef < EncryptionData > &rData,
sal_Int8 nStreamMode,
sal_Bool bIsEncrypted,
const ::rtl::OUString& aMediaType )
: maEntry ( rEntry )
, mxData ( rData )
, mbRawStream ( nStreamMode == UNBUFF_STREAM_RAW || nStreamMode == UNBUFF_STREAM_WRAPPEDRAW )
, mbWrappedRaw ( nStreamMode == UNBUFF_STREAM_WRAPPEDRAW )
, mbFinished ( sal_False )
, mxZipStream ( xNewZipStream )
, mxZipSeek ( xNewZipStream, UNO_QUERY )
, maInflater ( sal_True )
, maCipher ( NULL )
, mnMyCurrent ( 0 )
, mnZipEnd ( 0 )
, mnZipSize ( 0 )
, mnZipCurrent ( 0 )
, mnHeaderToRead ( 0 )
, mbCheckCRC( sal_True )
{
mnZipCurrent = maEntry.nOffset;
if ( mbRawStream )
{
mnZipSize = maEntry.nMethod == DEFLATED ? maEntry.nCompressedSize : maEntry.nSize;
mnZipEnd = maEntry.nOffset + mnZipSize;
}
else
{
mnZipSize = maEntry.nSize;
mnZipEnd = maEntry.nMethod == DEFLATED ? maEntry.nOffset + maEntry.nCompressedSize : maEntry.nOffset + maEntry.nSize;
}
sal_Bool bHaveEncryptData = ( !rData.isEmpty() && rData->aSalt.getLength() && rData->aInitVector.getLength() && rData->nIterationCount != 0 ) ? sal_True : sal_False;
sal_Bool bMustDecrypt = ( nStreamMode == UNBUFF_STREAM_DATA && bHaveEncryptData && bIsEncrypted ) ? sal_True : sal_False;
if ( bMustDecrypt )
ZipFile::StaticGetCipher ( rData, maCipher );
if ( bHaveEncryptData && mbWrappedRaw && bIsEncrypted )
{
// if we have the data needed to decrypt it, but didn't want it decrypted (or
// we couldn't decrypt it due to wrong password), then we prepend this
// data to the stream
// Make a buffer big enough to hold both the header and the data itself
maHeader.realloc ( n_ConstHeaderSize +
rData->aInitVector.getLength() +
rData->aSalt.getLength() +
rData->aDigest.getLength() +
aMediaType.getLength() * sizeof( sal_Unicode ) );
sal_Int8 * pHeader = maHeader.getArray();
ZipFile::StaticFillHeader ( rData, rEntry.nSize, aMediaType, pHeader );
mnHeaderToRead = static_cast < sal_Int16 > ( maHeader.getLength() );
}
}
// allows to read package raw stream
XUnbufferedStream::XUnbufferedStream( const Reference < XInputStream >& xRawStream,
const vos::ORef < EncryptionData > &rData )
: mxData ( rData )
, mbRawStream ( sal_False )
, mbWrappedRaw ( sal_False )
, mbFinished ( sal_False )
, mxZipStream ( xRawStream )
, mxZipSeek ( xRawStream, UNO_QUERY )
, maInflater ( sal_True )
, maCipher ( NULL )
, mnMyCurrent ( 0 )
, mnZipEnd ( 0 )
, mnZipSize ( 0 )
, mnZipCurrent ( 0 )
, mnHeaderToRead ( 0 )
, mbCheckCRC( sal_False )
{
// for this scenario maEntry is not set !!!
OSL_ENSURE( mxZipSeek.is(), "The stream must be seekable!\n" );
// skip raw header, it must be already parsed to rData
mnZipCurrent = n_ConstHeaderSize + rData->aInitVector.getLength() +
rData->aSalt.getLength() + rData->aDigest.getLength();
try {
if ( mxZipSeek.is() )
mnZipSize = mxZipSeek->getLength();
} catch( Exception& )
{
// in case of problem the size will stay set to 0
}
mnZipEnd = mnZipCurrent + mnZipSize;
ZipFile::StaticGetCipher ( rData, maCipher );
}
XUnbufferedStream::~XUnbufferedStream()
{
if ( maCipher )
rtl_cipher_destroy ( maCipher );
}
sal_Int32 SAL_CALL XUnbufferedStream::readBytes( Sequence< sal_Int8 >& aData, sal_Int32 nBytesToRead )
throw( NotConnectedException, BufferSizeExceededException, IOException, RuntimeException)
{
sal_Int32 nRequestedBytes = nBytesToRead;
OSL_ENSURE( !mnHeaderToRead || mbWrappedRaw, "Only encrypted raw stream can be provided with header!" );
if ( mnMyCurrent + nRequestedBytes > mnZipSize + mnHeaderToRead )
nRequestedBytes = static_cast < sal_Int32 > ( mnZipSize + mnHeaderToRead - mnMyCurrent );
sal_Int32 nRead = 0, nLastRead = 0, nTotal = 0;
aData.realloc ( nRequestedBytes );
if ( nRequestedBytes )
{
if ( mbRawStream )
{
sal_Int64 nDiff = mnZipEnd - mnZipCurrent;
if ( mbWrappedRaw && mnHeaderToRead )
{
sal_Int16 nHeadRead = static_cast < sal_Int16 > ( nRequestedBytes > mnHeaderToRead ?
mnHeaderToRead : nRequestedBytes );
memcpy ( aData.getArray(), maHeader.getConstArray() + maHeader.getLength() - mnHeaderToRead, nHeadRead );
mnHeaderToRead -= nHeadRead;
if ( mnHeaderToRead == 0 )
maHeader.realloc ( 0 );
if ( nHeadRead < nRequestedBytes )
{
sal_Int32 nToRead = nRequestedBytes - nHeadRead;
nToRead = ( nDiff < nToRead ) ? nDiff : nToRead;
Sequence< sal_Int8 > aPureData( nToRead );
mxZipSeek->seek ( mnZipCurrent );
nRead = mxZipStream->readBytes ( aPureData, nToRead );
mnZipCurrent += nRead;
aPureData.realloc( nRead );
if ( mbCheckCRC )
maCRC.update( aPureData );
aData.realloc( nHeadRead + nRead );
sal_Int8* pPureBuffer = aPureData.getArray();
sal_Int8* pBuffer = aData.getArray();
for ( sal_Int32 nInd = 0; nInd < nRead; nInd++ )
pBuffer[ nHeadRead + nInd ] = pPureBuffer[ nInd ];
}
nRead += nHeadRead;
}
else
{
mxZipSeek->seek ( mnZipCurrent );
nRead = mxZipStream->readBytes (
aData,
static_cast < sal_Int32 > ( nDiff < nRequestedBytes ? nDiff : nRequestedBytes ) );
mnZipCurrent += nRead;
if ( mbWrappedRaw && mbCheckCRC )
maCRC.update( aData );
}
}
else
{
while ( 0 == ( nLastRead = maInflater.doInflateSegment( aData, nRead, aData.getLength() - nRead ) ) ||
( nRead + nLastRead != nRequestedBytes && mnZipCurrent < mnZipEnd ) )
{
nRead += nLastRead;
if ( nRead > nRequestedBytes )
throw RuntimeException(
OUString( RTL_CONSTASCII_USTRINGPARAM( "Should not be possible to read more then requested!" ) ),
Reference< XInterface >() );
if ( maInflater.finished() )
throw ZipIOException( OUString( RTL_CONSTASCII_USTRINGPARAM( "The stream seems to be broken!" ) ),
Reference< XInterface >() );
if ( maInflater.needsDictionary() )
throw ZipIOException( OUString( RTL_CONSTASCII_USTRINGPARAM( "Dictionaries are not supported!" ) ),
Reference< XInterface >() );
sal_Int32 nDiff = static_cast < sal_Int32 > ( mnZipEnd - mnZipCurrent );
if ( nDiff > 0 )
{
mxZipSeek->seek ( mnZipCurrent );
sal_Int32 nToRead = std::min ( nDiff, std::max ( nRequestedBytes, 8192L ) );
sal_Int32 nZipRead = mxZipStream->readBytes ( maCompBuffer, nToRead );
mnZipCurrent += nZipRead;
// maCompBuffer now has the data, check if we need to decrypt
// before passing to the Inflater
if ( maCipher )
{
if ( mbCheckCRC )
maCRC.update( maCompBuffer );
Sequence < sal_Int8 > aCryptBuffer ( nZipRead );
rtlCipherError aResult = rtl_cipher_decode ( maCipher,
maCompBuffer.getConstArray(),
nZipRead,
reinterpret_cast < sal_uInt8 * > (aCryptBuffer.getArray()),
nZipRead);
OSL_ASSERT (aResult == rtl_Cipher_E_None);
maCompBuffer = aCryptBuffer; // Now it holds the decrypted data
}
maInflater.setInput ( maCompBuffer );
}
else
{
throw ZipIOException( OUString( RTL_CONSTASCII_USTRINGPARAM( "The stream seems to be broken!" ) ),
Reference< XInterface >() );
}
}
}
mnMyCurrent += nRead + nLastRead;
nTotal = nRead + nLastRead;
if ( nTotal < nRequestedBytes)
aData.realloc ( nTotal );
if ( mbCheckCRC && ( !mbRawStream || mbWrappedRaw ) )
{
if ( !maCipher && !mbWrappedRaw )
maCRC.update( aData );
if ( mnZipSize == mnMyCurrent && maCRC.getValue() != maEntry.nCrc )
throw ZipIOException( OUString( RTL_CONSTASCII_USTRINGPARAM( "The stream seems to be broken!" ) ),
Reference< XInterface >() );
}
}
return nTotal;
}
sal_Int32 SAL_CALL XUnbufferedStream::readSomeBytes( Sequence< sal_Int8 >& aData, sal_Int32 nMaxBytesToRead )
throw( NotConnectedException, BufferSizeExceededException, IOException, RuntimeException)
{
return readBytes ( aData, nMaxBytesToRead );
}
void SAL_CALL XUnbufferedStream::skipBytes( sal_Int32 nBytesToSkip )
throw( NotConnectedException, BufferSizeExceededException, IOException, RuntimeException)
{
if ( nBytesToSkip )
{
Sequence < sal_Int8 > aSequence ( nBytesToSkip );
readBytes ( aSequence, nBytesToSkip );
}
}
sal_Int32 SAL_CALL XUnbufferedStream::available( )
throw( NotConnectedException, IOException, RuntimeException)
{
return static_cast < sal_Int32 > ( mnZipSize - mnMyCurrent );
}
void SAL_CALL XUnbufferedStream::closeInput( )
throw( NotConnectedException, IOException, RuntimeException)
{
}
/*
void SAL_CALL XUnbufferedStream::seek( sal_Int64 location )
throw( IllegalArgumentException, IOException, RuntimeException)
{
}
sal_Int64 SAL_CALL XUnbufferedStream::getPosition( )
throw(IOException, RuntimeException)
{
return mnMyCurrent;
}
sal_Int64 SAL_CALL XUnbufferedStream::getLength( )
throw(IOException, RuntimeException)
{
return mnZipSize;
}
*/
<commit_msg>INTEGRATION: CWS ooo20031216 (1.6.14); FILE MERGED 2004/01/09 20:10:15 pjanik 1.6.14.2: #i23922#: Fix previous change. 2004/01/08 17:15:54 pjanik 1.6.14.1: #i23922#: Do not add L modifier after constants.<commit_after>/*************************************************************************
*
* $RCSfile: XUnbufferedStream.cxx,v $
*
* $Revision: 1.7 $
*
* last change: $Author: hr $ $Date: 2004-02-04 12:27:47 $
*
* 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): Martin Gallwey (gallwey@sun.com)
*
*
************************************************************************/
#ifndef _XUNBUFFERED_STREAM_HXX
#include <XUnbufferedStream.hxx>
#endif
#ifndef _ENCRYPTION_DATA_HXX_
#include <EncryptionData.hxx>
#endif
#ifndef _COM_SUN_STAR_PACKAGES_ZIP_ZIPCONSTANTS_HPP_
#include <com/sun/star/packages/zip/ZipConstants.hpp>
#endif
#ifndef _COM_SUN_STAR_PACKAGES_ZIP_ZIPIOEXCEPTION_HPP_
#include <com/sun/star/packages/zip/ZipIOException.hpp>
#endif
#ifndef _PACKAGE_CONSTANTS_HXX_
#include <PackageConstants.hxx>
#endif
#ifndef _RTL_CIPHER_H_
#include <rtl/cipher.h>
#endif
#ifndef _ZIP_FILE_HXX
#include <ZipFile.hxx>
#endif
#ifndef _ENCRYPTED_DATA_HEADER_HXX_
#include <EncryptedDataHeader.hxx>
#endif
#include <algorithm>
using namespace com::sun::star::packages::zip::ZipConstants;
using namespace com::sun::star::io;
using namespace com::sun::star::uno;
using com::sun::star::lang::IllegalArgumentException;
using com::sun::star::packages::zip::ZipIOException;
using ::rtl::OUString;
XUnbufferedStream::XUnbufferedStream( ZipEntry & rEntry,
Reference < XInputStream > xNewZipStream,
const vos::ORef < EncryptionData > &rData,
sal_Int8 nStreamMode,
sal_Bool bIsEncrypted,
const ::rtl::OUString& aMediaType )
: maEntry ( rEntry )
, mxData ( rData )
, mbRawStream ( nStreamMode == UNBUFF_STREAM_RAW || nStreamMode == UNBUFF_STREAM_WRAPPEDRAW )
, mbWrappedRaw ( nStreamMode == UNBUFF_STREAM_WRAPPEDRAW )
, mbFinished ( sal_False )
, mxZipStream ( xNewZipStream )
, mxZipSeek ( xNewZipStream, UNO_QUERY )
, maInflater ( sal_True )
, maCipher ( NULL )
, mnMyCurrent ( 0 )
, mnZipEnd ( 0 )
, mnZipSize ( 0 )
, mnZipCurrent ( 0 )
, mnHeaderToRead ( 0 )
, mbCheckCRC( sal_True )
{
mnZipCurrent = maEntry.nOffset;
if ( mbRawStream )
{
mnZipSize = maEntry.nMethod == DEFLATED ? maEntry.nCompressedSize : maEntry.nSize;
mnZipEnd = maEntry.nOffset + mnZipSize;
}
else
{
mnZipSize = maEntry.nSize;
mnZipEnd = maEntry.nMethod == DEFLATED ? maEntry.nOffset + maEntry.nCompressedSize : maEntry.nOffset + maEntry.nSize;
}
sal_Bool bHaveEncryptData = ( !rData.isEmpty() && rData->aSalt.getLength() && rData->aInitVector.getLength() && rData->nIterationCount != 0 ) ? sal_True : sal_False;
sal_Bool bMustDecrypt = ( nStreamMode == UNBUFF_STREAM_DATA && bHaveEncryptData && bIsEncrypted ) ? sal_True : sal_False;
if ( bMustDecrypt )
ZipFile::StaticGetCipher ( rData, maCipher );
if ( bHaveEncryptData && mbWrappedRaw && bIsEncrypted )
{
// if we have the data needed to decrypt it, but didn't want it decrypted (or
// we couldn't decrypt it due to wrong password), then we prepend this
// data to the stream
// Make a buffer big enough to hold both the header and the data itself
maHeader.realloc ( n_ConstHeaderSize +
rData->aInitVector.getLength() +
rData->aSalt.getLength() +
rData->aDigest.getLength() +
aMediaType.getLength() * sizeof( sal_Unicode ) );
sal_Int8 * pHeader = maHeader.getArray();
ZipFile::StaticFillHeader ( rData, rEntry.nSize, aMediaType, pHeader );
mnHeaderToRead = static_cast < sal_Int16 > ( maHeader.getLength() );
}
}
// allows to read package raw stream
XUnbufferedStream::XUnbufferedStream( const Reference < XInputStream >& xRawStream,
const vos::ORef < EncryptionData > &rData )
: mxData ( rData )
, mbRawStream ( sal_False )
, mbWrappedRaw ( sal_False )
, mbFinished ( sal_False )
, mxZipStream ( xRawStream )
, mxZipSeek ( xRawStream, UNO_QUERY )
, maInflater ( sal_True )
, maCipher ( NULL )
, mnMyCurrent ( 0 )
, mnZipEnd ( 0 )
, mnZipSize ( 0 )
, mnZipCurrent ( 0 )
, mnHeaderToRead ( 0 )
, mbCheckCRC( sal_False )
{
// for this scenario maEntry is not set !!!
OSL_ENSURE( mxZipSeek.is(), "The stream must be seekable!\n" );
// skip raw header, it must be already parsed to rData
mnZipCurrent = n_ConstHeaderSize + rData->aInitVector.getLength() +
rData->aSalt.getLength() + rData->aDigest.getLength();
try {
if ( mxZipSeek.is() )
mnZipSize = mxZipSeek->getLength();
} catch( Exception& )
{
// in case of problem the size will stay set to 0
}
mnZipEnd = mnZipCurrent + mnZipSize;
ZipFile::StaticGetCipher ( rData, maCipher );
}
XUnbufferedStream::~XUnbufferedStream()
{
if ( maCipher )
rtl_cipher_destroy ( maCipher );
}
sal_Int32 SAL_CALL XUnbufferedStream::readBytes( Sequence< sal_Int8 >& aData, sal_Int32 nBytesToRead )
throw( NotConnectedException, BufferSizeExceededException, IOException, RuntimeException)
{
sal_Int32 nRequestedBytes = nBytesToRead;
OSL_ENSURE( !mnHeaderToRead || mbWrappedRaw, "Only encrypted raw stream can be provided with header!" );
if ( mnMyCurrent + nRequestedBytes > mnZipSize + mnHeaderToRead )
nRequestedBytes = static_cast < sal_Int32 > ( mnZipSize + mnHeaderToRead - mnMyCurrent );
sal_Int32 nRead = 0, nLastRead = 0, nTotal = 0;
aData.realloc ( nRequestedBytes );
if ( nRequestedBytes )
{
if ( mbRawStream )
{
sal_Int64 nDiff = mnZipEnd - mnZipCurrent;
if ( mbWrappedRaw && mnHeaderToRead )
{
sal_Int16 nHeadRead = static_cast < sal_Int16 > ( nRequestedBytes > mnHeaderToRead ?
mnHeaderToRead : nRequestedBytes );
memcpy ( aData.getArray(), maHeader.getConstArray() + maHeader.getLength() - mnHeaderToRead, nHeadRead );
mnHeaderToRead -= nHeadRead;
if ( mnHeaderToRead == 0 )
maHeader.realloc ( 0 );
if ( nHeadRead < nRequestedBytes )
{
sal_Int32 nToRead = nRequestedBytes - nHeadRead;
nToRead = ( nDiff < nToRead ) ? nDiff : nToRead;
Sequence< sal_Int8 > aPureData( nToRead );
mxZipSeek->seek ( mnZipCurrent );
nRead = mxZipStream->readBytes ( aPureData, nToRead );
mnZipCurrent += nRead;
aPureData.realloc( nRead );
if ( mbCheckCRC )
maCRC.update( aPureData );
aData.realloc( nHeadRead + nRead );
sal_Int8* pPureBuffer = aPureData.getArray();
sal_Int8* pBuffer = aData.getArray();
for ( sal_Int32 nInd = 0; nInd < nRead; nInd++ )
pBuffer[ nHeadRead + nInd ] = pPureBuffer[ nInd ];
}
nRead += nHeadRead;
}
else
{
mxZipSeek->seek ( mnZipCurrent );
nRead = mxZipStream->readBytes (
aData,
static_cast < sal_Int32 > ( nDiff < nRequestedBytes ? nDiff : nRequestedBytes ) );
mnZipCurrent += nRead;
if ( mbWrappedRaw && mbCheckCRC )
maCRC.update( aData );
}
}
else
{
while ( 0 == ( nLastRead = maInflater.doInflateSegment( aData, nRead, aData.getLength() - nRead ) ) ||
( nRead + nLastRead != nRequestedBytes && mnZipCurrent < mnZipEnd ) )
{
nRead += nLastRead;
if ( nRead > nRequestedBytes )
throw RuntimeException(
OUString( RTL_CONSTASCII_USTRINGPARAM( "Should not be possible to read more then requested!" ) ),
Reference< XInterface >() );
if ( maInflater.finished() )
throw ZipIOException( OUString( RTL_CONSTASCII_USTRINGPARAM( "The stream seems to be broken!" ) ),
Reference< XInterface >() );
if ( maInflater.needsDictionary() )
throw ZipIOException( OUString( RTL_CONSTASCII_USTRINGPARAM( "Dictionaries are not supported!" ) ),
Reference< XInterface >() );
sal_Int32 nDiff = static_cast < sal_Int32 > ( mnZipEnd - mnZipCurrent );
if ( nDiff > 0 )
{
mxZipSeek->seek ( mnZipCurrent );
sal_Int32 nToRead = std::min ( nDiff, std::max ( nRequestedBytes, static_cast< sal_Int32 >( 8192 ) ) );
sal_Int32 nZipRead = mxZipStream->readBytes ( maCompBuffer, nToRead );
mnZipCurrent += nZipRead;
// maCompBuffer now has the data, check if we need to decrypt
// before passing to the Inflater
if ( maCipher )
{
if ( mbCheckCRC )
maCRC.update( maCompBuffer );
Sequence < sal_Int8 > aCryptBuffer ( nZipRead );
rtlCipherError aResult = rtl_cipher_decode ( maCipher,
maCompBuffer.getConstArray(),
nZipRead,
reinterpret_cast < sal_uInt8 * > (aCryptBuffer.getArray()),
nZipRead);
OSL_ASSERT (aResult == rtl_Cipher_E_None);
maCompBuffer = aCryptBuffer; // Now it holds the decrypted data
}
maInflater.setInput ( maCompBuffer );
}
else
{
throw ZipIOException( OUString( RTL_CONSTASCII_USTRINGPARAM( "The stream seems to be broken!" ) ),
Reference< XInterface >() );
}
}
}
mnMyCurrent += nRead + nLastRead;
nTotal = nRead + nLastRead;
if ( nTotal < nRequestedBytes)
aData.realloc ( nTotal );
if ( mbCheckCRC && ( !mbRawStream || mbWrappedRaw ) )
{
if ( !maCipher && !mbWrappedRaw )
maCRC.update( aData );
if ( mnZipSize == mnMyCurrent && maCRC.getValue() != maEntry.nCrc )
throw ZipIOException( OUString( RTL_CONSTASCII_USTRINGPARAM( "The stream seems to be broken!" ) ),
Reference< XInterface >() );
}
}
return nTotal;
}
sal_Int32 SAL_CALL XUnbufferedStream::readSomeBytes( Sequence< sal_Int8 >& aData, sal_Int32 nMaxBytesToRead )
throw( NotConnectedException, BufferSizeExceededException, IOException, RuntimeException)
{
return readBytes ( aData, nMaxBytesToRead );
}
void SAL_CALL XUnbufferedStream::skipBytes( sal_Int32 nBytesToSkip )
throw( NotConnectedException, BufferSizeExceededException, IOException, RuntimeException)
{
if ( nBytesToSkip )
{
Sequence < sal_Int8 > aSequence ( nBytesToSkip );
readBytes ( aSequence, nBytesToSkip );
}
}
sal_Int32 SAL_CALL XUnbufferedStream::available( )
throw( NotConnectedException, IOException, RuntimeException)
{
return static_cast < sal_Int32 > ( mnZipSize - mnMyCurrent );
}
void SAL_CALL XUnbufferedStream::closeInput( )
throw( NotConnectedException, IOException, RuntimeException)
{
}
/*
void SAL_CALL XUnbufferedStream::seek( sal_Int64 location )
throw( IllegalArgumentException, IOException, RuntimeException)
{
}
sal_Int64 SAL_CALL XUnbufferedStream::getPosition( )
throw(IOException, RuntimeException)
{
return mnMyCurrent;
}
sal_Int64 SAL_CALL XUnbufferedStream::getLength( )
throw(IOException, RuntimeException)
{
return mnZipSize;
}
*/
<|endoftext|> |
<commit_before>#include "level2.h"
Level2::Level2(int screenWidthCamera, int screenHeightCamera) : Level::Level(screenWidthCamera, screenHeightCamera)
{
this->player->localPosition = glm::vec2(480.0f, 100.0f);
// We need to update the player otherwise the position will not be set because of the player using velocity and the velocity overrride it's position
this->player->UpdateChilderen(this, 0.0f);
enemy = new Enemy(player, 900.0f, 0.1f, 0.5f, 1, 5, 1, 70, 70, ResourceManager::GetTexture("enemy")->GetId(), world);
enemy->localPosition = glm::vec2(0, -300);
enemy->CreateBoxCollider(70, 70, glm::vec2(0, 0), true, false);
enemy->SetDebugColor(glm::vec3(1, 0, 1));
enemy->UpdateChilderen(this, 0.0f);
this->AddChild(enemy);
enemy1 = new Enemy(player, 900.0f, 0.1f, 0.5f, 1, 5, 1, 70, 70, ResourceManager::GetTexture("enemy")->GetId(), world);
enemy1->localPosition = glm::vec2(1, -300);
enemy1->CreateBoxCollider(70, 70, glm::vec2(0, 0), true, false);
enemy1->SetDebugColor(glm::vec3(1, 0, 1));
enemy1->UpdateChilderen(this, 0.0f);
this->AddChild(enemy1);
enemy2 = new Enemy(player, 900.0f, 0.1f, 0.5f, 1, 5, 1, 70, 70, ResourceManager::GetTexture("enemy")->GetId(), world);
enemy2->localPosition = glm::vec2(800, -300);
enemy2->CreateBoxCollider(70, 70, glm::vec2(0, 0), true, false);
enemy2->SetDebugColor(glm::vec3(1, 0, 1));
enemy2->UpdateChilderen(this, 0.0f);
this->AddChild(enemy2);
wall = new B2Entity(720, 750, ResourceManager::GetTexture("wall")->GetId(), world);
wall->localPosition = glm::vec2(450, 450);
wall->CreateBoxCollider(720, 100, glm::vec2(0, 0), false, false);
AddChild(wall);
mirror = new Mirror(true, 45.0f, 240.0f, ResourceManager::GetTexture("mirror")->GetId(), world);
mirror->localPosition = glm::vec2(700.0f, 1000.0f);
mirror->CreateBoxCollider(45.0f, 240.0f, glm::vec2(0.0f, 0.0f), false, false);
mirror->SetRotation(-90.0f);
AddChild(mirror);
CreateFinish(10000, 540, 400, 100);
}
Level2::~Level2()
{
if (player != nullptr) {
delete enemy;
delete enemy1;
delete enemy2;
}
delete wall;
delete mirror;
}<commit_msg>Changed the force towards the player of the enemy<commit_after>#include "level2.h"
Level2::Level2(int screenWidthCamera, int screenHeightCamera) : Level::Level(screenWidthCamera, screenHeightCamera)
{
this->player->localPosition = glm::vec2(480.0f, 100.0f);
// We need to update the player otherwise the position will not be set because of the player using velocity and the velocity overrride it's position
this->player->UpdateChilderen(this, 0.0f);
enemy = new Enemy(player, 900.0f, 0.6f, 0.5f, 1, 5, 1, 70, 70, ResourceManager::GetTexture("enemy")->GetId(), world);
enemy->localPosition = glm::vec2(0, -300);
enemy->CreateBoxCollider(70, 70, glm::vec2(0, 0), true, false);
enemy->SetDebugColor(glm::vec3(1, 0, 1));
enemy->UpdateChilderen(this, 0.0f);
this->AddChild(enemy);
enemy1 = new Enemy(player, 900.0f, 0.6f, 0.5f, 1, 5, 1, 70, 70, ResourceManager::GetTexture("enemy")->GetId(), world);
enemy1->localPosition = glm::vec2(1, -300);
enemy1->CreateBoxCollider(70, 70, glm::vec2(0, 0), true, false);
enemy1->SetDebugColor(glm::vec3(1, 0, 1));
enemy1->UpdateChilderen(this, 0.0f);
this->AddChild(enemy1);
enemy2 = new Enemy(player, 900.0f, 0.6f, 0.5f, 1, 5, 1, 70, 70, ResourceManager::GetTexture("enemy")->GetId(), world);
enemy2->localPosition = glm::vec2(800, -300);
enemy2->CreateBoxCollider(70, 70, glm::vec2(0, 0), true, false);
enemy2->SetDebugColor(glm::vec3(1, 0, 1));
enemy2->UpdateChilderen(this, 0.0f);
this->AddChild(enemy2);
wall = new B2Entity(720, 750, ResourceManager::GetTexture("wall")->GetId(), world);
wall->localPosition = glm::vec2(450, 450);
wall->CreateBoxCollider(720, 100, glm::vec2(0, 0), false, false);
AddChild(wall);
mirror = new Mirror(true, 45.0f, 240.0f, ResourceManager::GetTexture("mirror")->GetId(), world);
mirror->localPosition = glm::vec2(700.0f, 1000.0f);
mirror->CreateBoxCollider(45.0f, 240.0f, glm::vec2(0.0f, 0.0f), false, false);
mirror->SetRotation(-90.0f);
AddChild(mirror);
CreateFinish(10000, 540, 400, 100);
}
Level2::~Level2()
{
if (player != nullptr) {
delete enemy;
delete enemy1;
delete enemy2;
}
delete wall;
delete mirror;
}<|endoftext|> |
<commit_before>//
// PCMPatchedTrack.cpp
// Clock Signal
//
// Created by Thomas Harte on 15/12/2016.
// Copyright © 2016 Thomas Harte. All rights reserved.
//
#include "PCMPatchedTrack.hpp"
using namespace Storage::Disk;
PCMPatchedTrack::PCMPatchedTrack(std::shared_ptr<Track> underlying_track) :
underlying_track_(underlying_track)
{
const Time zero(0);
const Time one(1);
periods_.emplace_back(zero, one, zero, nullptr);
active_period_ = periods_.begin();
underlying_track_->seek_to(zero);
}
void PCMPatchedTrack::add_segment(const Time &start_time, const PCMSegment &segment)
{
event_sources_.emplace_back(segment);
Time zero(0);
Time end_time = start_time + event_sources_.back().get_length();
Period insertion_period(start_time, end_time, zero, &event_sources_.back());
// the new segment may wrap around, so divide it up into track-length parts if required
Time one = Time(1);
while(insertion_period.end_time > one)
{
Time next_end_time = insertion_period.end_time - one;
insertion_period.end_time = one;
insert_period(insertion_period);
insertion_period.start_time = zero;
insertion_period.end_time = next_end_time;
}
insert_period(insertion_period);
// the vector may have been resized, potentially invalidating active_period_ even if
// the thing it pointed to is still the same thing. So work it out afresh.
active_period_ = periods_.begin();
while(active_period_->start_time > current_time_) active_period_++;
}
void PCMPatchedTrack::insert_period(const Period &period)
{
// find the existing period that the new period starts in
size_t start_index = 0;
while(periods_[start_index].start_time >= period.end_time) start_index++;
// find the existing period that the new period end in
size_t end_index = start_index;
while(periods_[end_index].end_time < period.end_time) end_index++;
// perform a division if called for
if(start_index == end_index)
{
Period right_period = periods_[start_index];
Time adjustment = period.end_time - right_period.start_time;
right_period.start_time += adjustment;
right_period.segment_start_time += adjustment;
periods_[start_index].end_time = period.start_time;
periods_.insert(periods_.begin() + (int)start_index + 1, period);
periods_.insert(periods_.begin() + (int)start_index + 2, right_period);
}
else
{
// perform a left chop on the thing at the start and a right chop on the thing at the end
periods_[start_index].end_time = period.start_time;
Time adjustment = period.end_time - periods_[end_index].start_time;
periods_[end_index].start_time += adjustment;
periods_[end_index].segment_start_time += adjustment;
// remove anything in between
periods_.erase(periods_.begin() + (int)start_index + 1, periods_.begin() + (int)end_index - 1);
// insert the new period
periods_.insert(periods_.begin() + (int)start_index + 1, period);
}
}
Track::Event PCMPatchedTrack::get_next_event()
{
const Time one(1);
const Time zero(0);
Time extra_time(0);
Time period_error(0);
while(1)
{
// get the next event from the current active period
Track::Event event;
if(active_period_->event_source) event = active_period_->event_source->get_next_event();
else event = underlying_track_->get_next_event();
// see what time that gets us to. If it's still within the current period, return the found event
current_time_ += event.length;
if(current_time_ < active_period_->end_time)
{
event.length += extra_time - period_error;
return event;
}
// otherwise move time back to the end of the outgoing period, accumulating the error into
// extra_time, and advance the extra period
extra_time += (current_time_ - active_period_->end_time);
current_time_ = active_period_->end_time;
active_period_++;
// test for having reached the end of the track
if(active_period_ == periods_.end())
{
// if this is the end of the track then jump the active pointer back to the beginning
// of the list of periods and reset current_time_ to zero
active_period_ = periods_.begin();
if(active_period_->event_source) active_period_->event_source->reset();
else underlying_track_->seek_to(zero);
current_time_ = zero;
// then return an index hole that is the aggregation of accumulated extra_time away
event.type = Storage::Disk::Track::Event::IndexHole;
event.length = extra_time;
return event;
}
else
{
// if this is not the end of the track then move to the next period and note how much will need
// to be subtracted if an event is found here
if(active_period_->event_source) period_error = active_period_->segment_start_time - active_period_->event_source->seek_to(active_period_->segment_start_time);
else period_error = underlying_track_->seek_to(current_time_) - current_time_;
}
}
}
Storage::Time PCMPatchedTrack::seek_to(const Time &time_since_index_hole)
{
// start at the beginning and continue while segments start after the time sought
active_period_ = periods_.begin();
while(active_period_->start_time > time_since_index_hole) active_period_++;
// allow whatever storage represents the period found to perform its seek
if(active_period_->event_source)
return active_period_->event_source->seek_to(time_since_index_hole - active_period_->start_time) + active_period_->start_time;
else
return underlying_track_->seek_to(time_since_index_hole);
}
<commit_msg>Still by manual inspection: the time for the next event should be provisional until proven acceptable, allowing a proper measurement of time until exiting the period to be taken; also fixed the accumulated period error when seeking back onto the underlying track.<commit_after>//
// PCMPatchedTrack.cpp
// Clock Signal
//
// Created by Thomas Harte on 15/12/2016.
// Copyright © 2016 Thomas Harte. All rights reserved.
//
#include "PCMPatchedTrack.hpp"
using namespace Storage::Disk;
PCMPatchedTrack::PCMPatchedTrack(std::shared_ptr<Track> underlying_track) :
underlying_track_(underlying_track)
{
const Time zero(0);
const Time one(1);
periods_.emplace_back(zero, one, zero, nullptr);
active_period_ = periods_.begin();
underlying_track_->seek_to(zero);
}
void PCMPatchedTrack::add_segment(const Time &start_time, const PCMSegment &segment)
{
event_sources_.emplace_back(segment);
Time zero(0);
Time end_time = start_time + event_sources_.back().get_length();
Period insertion_period(start_time, end_time, zero, &event_sources_.back());
// the new segment may wrap around, so divide it up into track-length parts if required
Time one = Time(1);
while(insertion_period.end_time > one)
{
Time next_end_time = insertion_period.end_time - one;
insertion_period.end_time = one;
insert_period(insertion_period);
insertion_period.start_time = zero;
insertion_period.end_time = next_end_time;
}
insert_period(insertion_period);
// the vector may have been resized, potentially invalidating active_period_ even if
// the thing it pointed to is still the same thing. So work it out afresh.
active_period_ = periods_.begin();
while(active_period_->start_time > current_time_) active_period_++;
}
void PCMPatchedTrack::insert_period(const Period &period)
{
// find the existing period that the new period starts in
size_t start_index = 0;
while(periods_[start_index].start_time >= period.end_time) start_index++;
// find the existing period that the new period end in
size_t end_index = start_index;
while(periods_[end_index].end_time < period.end_time) end_index++;
// perform a division if called for
if(start_index == end_index)
{
Period right_period = periods_[start_index];
Time adjustment = period.end_time - right_period.start_time;
right_period.start_time += adjustment;
right_period.segment_start_time += adjustment;
periods_[start_index].end_time = period.start_time;
periods_.insert(periods_.begin() + (int)start_index + 1, period);
periods_.insert(periods_.begin() + (int)start_index + 2, right_period);
}
else
{
// perform a left chop on the thing at the start and a right chop on the thing at the end
periods_[start_index].end_time = period.start_time;
Time adjustment = period.end_time - periods_[end_index].start_time;
periods_[end_index].start_time += adjustment;
periods_[end_index].segment_start_time += adjustment;
// remove anything in between
periods_.erase(periods_.begin() + (int)start_index + 1, periods_.begin() + (int)end_index - 1);
// insert the new period
periods_.insert(periods_.begin() + (int)start_index + 1, period);
}
}
Track::Event PCMPatchedTrack::get_next_event()
{
const Time one(1);
const Time zero(0);
Time extra_time(0);
Time period_error(0);
while(1)
{
// get the next event from the current active period
Track::Event event;
if(active_period_->event_source) event = active_period_->event_source->get_next_event();
else event = underlying_track_->get_next_event();
// see what time that gets us to. If it's still within the current period, return the found event
Time event_time = current_time_ + event.length;
if(event_time < active_period_->end_time)
{
current_time_ = event_time;
event.length += extra_time - period_error;
return event;
}
// otherwise move time back to the end of the outgoing period, accumulating the error into
// extra_time, and advance the extra period
extra_time += (active_period_->end_time - current_time_);
current_time_ = active_period_->end_time;
active_period_++;
// test for having reached the end of the track
if(active_period_ == periods_.end())
{
// if this is the end of the track then jump the active pointer back to the beginning
// of the list of periods and reset current_time_ to zero
active_period_ = periods_.begin();
if(active_period_->event_source) active_period_->event_source->reset();
else underlying_track_->seek_to(zero);
current_time_ = zero;
// then return an index hole that is the aggregation of accumulated extra_time away
event.type = Storage::Disk::Track::Event::IndexHole;
event.length = extra_time;
return event;
}
else
{
// if this is not the end of the track then move to the next period and note how much will need
// to be subtracted if an event is found here
if(active_period_->event_source) period_error = active_period_->segment_start_time - active_period_->event_source->seek_to(active_period_->segment_start_time);
else period_error = current_time_ - underlying_track_->seek_to(current_time_);
}
}
}
Storage::Time PCMPatchedTrack::seek_to(const Time &time_since_index_hole)
{
// start at the beginning and continue while segments start after the time sought
active_period_ = periods_.begin();
while(active_period_->start_time > time_since_index_hole) active_period_++;
// allow whatever storage represents the period found to perform its seek
if(active_period_->event_source)
return active_period_->event_source->seek_to(time_since_index_hole - active_period_->start_time) + active_period_->start_time;
else
return underlying_track_->seek_to(time_since_index_hole);
}
<|endoftext|> |
<commit_before>/*=========================================================================
Program: ORFEO Toolbox
Language: C++
Date: $Date$
Version: $Revision$
Copyright (c) Centre National d'Etudes Spatiales. All rights reserved.
See OTBCopyright.txt for details.
This software is distributed WITHOUT ANY WARRANTY; without even
the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR
PURPOSE. See the above copyright notices for more information.
=========================================================================*/
// Software Guide : BeginCommandLineArgs
// INPUTS: {QB_Suburb.png}
// OUTPUTS: {MarkovRandomField3_gray_value.png}, {MarkovRandomField3_color_value.png}
// 1.0 20 1.0 1
// Software Guide : EndCommandLineArgs
// Software Guide : BeginLatex
//
// This example illustrates the details of the MarkovRandomFieldFilter by using the Fisher distribution
// to model the likelihood energy.
// This filter is an application of the Markov Random Fields for classification.
//
// This example applies the MarkovRandomFieldFilter to
// classify an image into four classes defined by their Fisher distribution parameters L, M and mu.
// The optimization is done using a Metropolis algorithm with a random sampler. The
// regularization energy is defined by a Potts model and the fidelity or likelihood energy is modelled by a
// Fisher distribution.
// The parameter of the Fisher distribution was determined for each class in a supervised step.
// ( See the File OtbParameterEstimatioOfFisherDistribution )
// This example is a contribution from Jan Wegner.
//
// Software Guide : EndLatex
#include "otbImageFileReader.h"
#include "otbStreamingImageFileWriter.h"
#include "otbImage.h"
#include "otbMarkovRandomFieldFilter.h"
#include "itkRescaleIntensityImageFilter.h"
#include "itkUnaryFunctorImageFilter.h"
#include "itkScalarToRGBPixelFunctor.h"
#include "otbMRFEnergyPotts.h"
#include "otbMRFEnergyFisherClassification.h"
#include "otbMRFOptimizerMetropolis.h"
#include "otbMRFSamplerRandom.h"
int main(int argc, char* argv[] )
{
if( argc != 8 )
{
std::cerr << "Missing Parameters "<< argc << std::endl;
std::cerr << "Usage: " << argv[0];
std::cerr << " inputImage output_gray_label output_color_label lambda iterations "
"optimizerTemperature useRandomValue " << std::endl;
return 1;
}
// Software Guide : BeginLatex
//
// Then we must decide what pixel type to use for the image. We
// choose to make all computations with double precision.
// The labeled image is of type unsigned char which allows up to 256 different
// classes.
//
// Software Guide : EndLatex
// Software Guide : BeginCodeSnippet
const unsigned int Dimension = 2;
typedef double InternalPixelType;
typedef unsigned char LabelledPixelType;
typedef otb::Image<InternalPixelType, Dimension> InputImageType;
typedef otb::Image<LabelledPixelType, Dimension> LabelledImageType;
// Software Guide : EndCodeSnippet
// Software Guide : BeginLatex
//
// We define a reader for the image to be classified, an initialization for the
// classification (which could be random) and a writer for the final
// classification.
//
// Software Guide : EndLatex
// Software Guide : BeginCodeSnippet
typedef otb::ImageFileReader< InputImageType > ReaderType;
typedef otb::StreamingImageFileWriter< LabelledImageType > WriterType;
ReaderType::Pointer reader = ReaderType::New();
WriterType::Pointer writer = WriterType::New();
// Software Guide : EndCodeSnippet
const char * inputFilename = argv[1];
const char * outputFilename = argv[2];
const char * outputRescaledImageFileName = argv[3];
reader->SetFileName( inputFilename );
writer->SetFileName( outputFilename );
// Software Guide : BeginLatex
//
// Finally, we define the different classes necessary for the Markov classification.
// A MarkovRandomFieldFilter is instantiated, this is the
// main class which connect the other to do the Markov classification.
//
// Software Guide : EndLatex
// Software Guide : BeginCodeSnippet
typedef otb::MarkovRandomFieldFilter
<InputImageType, LabelledImageType> MarkovRandomFieldFilterType;
// Software Guide : EndCodeSnippet
// Software Guide : BeginLatex
//
// An MRFSamplerRandomMAP, which derives from the
// MRFSampler, is instanciated. The sampler is in charge of
// proposing a modification for a given site. The
// MRFSamplerRandomMAP, randomly pick one possible value
// according to the MAP probability.
//
// Software Guide : EndLatex
// Software Guide : BeginCodeSnippet
typedef otb::MRFSamplerRandom< InputImageType, LabelledImageType> SamplerType;
// Software Guide : EndCodeSnippet
// Software Guide : BeginLatex
//
// An MRFOptimizerMetropolis, which derives from the
// MRFOptimizer, is instanciated. The optimizer is in charge
// of accepting or rejecting the value proposed by the sampler. The
// MRFSamplerRandomMAP, accept the proposal according to the
// variation of energy it causes and a temperature parameter.
//
// Software Guide : EndLatex
// Software Guide : BeginCodeSnippet
typedef otb::MRFOptimizerMetropolis OptimizerType;
// Software Guide : EndCodeSnippet
// Software Guide : BeginLatex
//
// Two energy, deriving from the MRFEnergy class need to be instantiated. One energy
// is required for the regularization, taking into account the relationship between neighboring pixels
// in the classified image. Here it is done with the MRFEnergyPotts, which implements
// a Potts model.
//
// The second energy is used for the fidelity to the original data. Here it is done with a
// MRFEnergyFisherClassification class, which defines a Fisher distribution to model the data.
//
// Software Guide : EndLatex
// Software Guide : BeginCodeSnippet
typedef otb::MRFEnergyPotts
<LabelledImageType, LabelledImageType> EnergyRegularizationType;
typedef otb::MRFEnergyFisherClassification
<InputImageType, LabelledImageType> EnergyFidelityType;
// Software Guide : EndCodeSnippet
// Software Guide : BeginLatex
//
// The different filters composing our pipeline are created by invoking their
// New() methods, assigning the results to smart pointers.
//
// Software Guide : EndLatex
// Software Guide : BeginCodeSnippet
MarkovRandomFieldFilterType::Pointer markovFilter = MarkovRandomFieldFilterType::New();
EnergyRegularizationType::Pointer energyRegularization = EnergyRegularizationType::New();
EnergyFidelityType::Pointer energyFidelity = EnergyFidelityType::New();
OptimizerType::Pointer optimizer = OptimizerType::New();
SamplerType::Pointer sampler = SamplerType::New();
// Software Guide : EndCodeSnippet
// Software Guide : BeginLatex
//
// Parameter for the MRFEnergyFisherClassification class are created. The shape parameters M, L
// and the weighting parameter mu are computed in a supervised step
//
// Software Guide : EndLatex
if ((bool)(atoi(argv[6])) == true)
{
// Overpass random calculation(for test only):
sampler->InitializeSeed(0);
optimizer->InitializeSeed(1);
markovFilter->InitializeSeed(1);
}
// Software Guide : BeginCodeSnippet
unsigned int nClass =4;
energyFidelity->SetNumberOfParameters(3*nClass);
EnergyFidelityType::ParametersType parameters;
parameters.SetSize(energyFidelity->GetNumberOfParameters());
//Class 0
parameters[0] = 12.353042; //Class 0 mu
parameters[1] = 2.156422; //Class 0 L
parameters[2] = 4.920403; //Class 0 M
//Class 1
parameters[3] = 72.068291; //Class 1 mu
parameters[4] = 11.000000; //Class 1 L
parameters[5] = 50.950001; //Class 1 M
//Class 2
parameters[6] = 146.665985; //Class 2 mu
parameters[7] = 11.000000; //Class 2 L
parameters[8] = 50.900002; //Class 2 M
//Class 3
parameters[9] = 200.010132; //Class 3 mu
parameters[10] = 11.000000; //Class 3 L
parameters[11] = 50.950001; //Class 3 M
energyFidelity->SetParameters(parameters);
// Software Guide : EndCodeSnippet
// Software Guide : BeginLatex
//
// Parameters are given to the different classes and the sampler, optimizer and
// energies are connected with the Markov filter.
//
// Software Guide : EndLatex
// Software Guide : BeginCodeSnippet
OptimizerType::ParametersType param(1);
param.Fill(atof(argv[6]));
optimizer->SetParameters(param);
markovFilter->SetNumberOfClasses(nClass);
markovFilter->SetMaximumNumberOfIterations(atoi(argv[5]));
markovFilter->SetErrorTolerance(0.0);
markovFilter->SetLambda(atof(argv[4]));
markovFilter->SetNeighborhoodRadius(1);
markovFilter->SetEnergyRegularization(energyRegularization);
markovFilter->SetEnergyFidelity(energyFidelity);
markovFilter->SetOptimizer(optimizer);
markovFilter->SetSampler(sampler);
// Software Guide : EndCodeSnippet
// Software Guide : BeginLatex
//
// The pipeline is connected. An itkRescaleIntensityImageFilter
// rescales the classified image before saving it.
//
// Software Guide : EndLatex
// Software Guide : BeginCodeSnippet
markovFilter->SetInput(reader->GetOutput());
typedef itk::RescaleIntensityImageFilter
< LabelledImageType, LabelledImageType > RescaleType;
RescaleType::Pointer rescaleFilter = RescaleType::New();
rescaleFilter->SetOutputMinimum(0);
rescaleFilter->SetOutputMaximum(255);
rescaleFilter->SetInput( markovFilter->GetOutput() );
writer->SetInput( rescaleFilter->GetOutput() );
writer->Update();
// Software Guide : EndCodeSnippet
//convert output image to color
typedef itk::RGBPixel<unsigned char> RGBPixelType;
typedef otb::Image<RGBPixelType, 2> RGBImageType;
typedef itk::Functor::ScalarToRGBPixelFunctor<unsigned long> ColorMapFunctorType;
typedef itk::UnaryFunctorImageFilter< LabelledImageType, RGBImageType, ColorMapFunctorType> ColorMapFilterType;
ColorMapFilterType::Pointer colormapper = ColorMapFilterType::New();
colormapper->SetInput( rescaleFilter->GetOutput() );
// Software Guide : BeginLatex
//
// We can now create an image file writer and save the image.
//
// Software Guide : EndLatex
// Software Guide : BeginCodeSnippet
typedef otb::StreamingImageFileWriter<RGBImageType> WriterRescaledType;
WriterRescaledType::Pointer writerRescaled = WriterRescaledType::New();
writerRescaled->SetFileName( outputRescaledImageFileName );
writerRescaled->SetInput( colormapper->GetOutput() );
writerRescaled->Update();
// Software Guide : EndCodeSnippet
// Software Guide : BeginLatex
//
// Figure~\ref{fig:MRF_CLASSIFICATION3} shows the output of the Markov Random
// Field classification into four classes using the
// Fisher-distribution as likelihood term.
//
// \begin{figure}
// \center
// \includegraphics[width=0.44\textwidth]{QB_Suburb.eps}
// \includegraphics[width=0.44\textwidth]{MarkovRandomField3_color_value.eps}
// \itkcaption[MRF restauration]{Result of applying
// the \doxygen{otb}{MarkovRandomFieldFilter} to an extract from a PAN Quickbird
// image for classification into fourt classes using the Fisher-distribution as
// likehood term. From left to right : original image,
// classification.}
// \label{fig:MRF_CLASSIFICATION3}
// \end{figure}
//
// Software Guide : EndLatex
return EXIT_SUCCESS;
}
<commit_msg>DOC:typo in MRF classification example<commit_after>/*=========================================================================
Program: ORFEO Toolbox
Language: C++
Date: $Date$
Version: $Revision$
Copyright (c) Centre National d'Etudes Spatiales. All rights reserved.
See OTBCopyright.txt for details.
This software is distributed WITHOUT ANY WARRANTY; without even
the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR
PURPOSE. See the above copyright notices for more information.
=========================================================================*/
// Software Guide : BeginCommandLineArgs
// INPUTS: {QB_Suburb.png}
// OUTPUTS: {MarkovRandomField3_gray_value.png}, {MarkovRandomField3_color_value.png}
// 1.0 20 1.0 1
// Software Guide : EndCommandLineArgs
// Software Guide : BeginLatex
//
// This example illustrates the details of the MarkovRandomFieldFilter by using the Fisher distribution
// to model the likelihood energy.
// This filter is an application of the Markov Random Fields for classification.
//
// This example applies the MarkovRandomFieldFilter to
// classify an image into four classes defined by their Fisher distribution parameters L, M and mu.
// The optimization is done using a Metropolis algorithm with a random sampler. The
// regularization energy is defined by a Potts model and the fidelity or likelihood energy is modelled by a
// Fisher distribution.
// The parameter of the Fisher distribution was determined for each class in a supervised step.
// ( See the File OtbParameterEstimatioOfFisherDistribution )
// This example is a contribution from Jan Wegner.
//
// Software Guide : EndLatex
#include "otbImageFileReader.h"
#include "otbStreamingImageFileWriter.h"
#include "otbImage.h"
#include "otbMarkovRandomFieldFilter.h"
#include "itkRescaleIntensityImageFilter.h"
#include "itkUnaryFunctorImageFilter.h"
#include "itkScalarToRGBPixelFunctor.h"
#include "otbMRFEnergyPotts.h"
#include "otbMRFEnergyFisherClassification.h"
#include "otbMRFOptimizerMetropolis.h"
#include "otbMRFSamplerRandom.h"
int main(int argc, char* argv[] )
{
if( argc != 8 )
{
std::cerr << "Missing Parameters "<< argc << std::endl;
std::cerr << "Usage: " << argv[0];
std::cerr << " inputImage output_gray_label output_color_label lambda iterations "
"optimizerTemperature useRandomValue " << std::endl;
return 1;
}
// Software Guide : BeginLatex
//
// Then we must decide what pixel type to use for the image. We
// choose to make all computations with double precision.
// The labeled image is of type unsigned char which allows up to 256 different
// classes.
//
// Software Guide : EndLatex
// Software Guide : BeginCodeSnippet
const unsigned int Dimension = 2;
typedef double InternalPixelType;
typedef unsigned char LabelledPixelType;
typedef otb::Image<InternalPixelType, Dimension> InputImageType;
typedef otb::Image<LabelledPixelType, Dimension> LabelledImageType;
// Software Guide : EndCodeSnippet
// Software Guide : BeginLatex
//
// We define a reader for the image to be classified, an initialization for the
// classification (which could be random) and a writer for the final
// classification.
//
// Software Guide : EndLatex
// Software Guide : BeginCodeSnippet
typedef otb::ImageFileReader< InputImageType > ReaderType;
typedef otb::StreamingImageFileWriter< LabelledImageType > WriterType;
ReaderType::Pointer reader = ReaderType::New();
WriterType::Pointer writer = WriterType::New();
// Software Guide : EndCodeSnippet
const char * inputFilename = argv[1];
const char * outputFilename = argv[2];
const char * outputRescaledImageFileName = argv[3];
reader->SetFileName( inputFilename );
writer->SetFileName( outputFilename );
// Software Guide : BeginLatex
//
// Finally, we define the different classes necessary for the Markov classification.
// A MarkovRandomFieldFilter is instantiated, this is the
// main class which connect the other to do the Markov classification.
//
// Software Guide : EndLatex
// Software Guide : BeginCodeSnippet
typedef otb::MarkovRandomFieldFilter
<InputImageType, LabelledImageType> MarkovRandomFieldFilterType;
// Software Guide : EndCodeSnippet
// Software Guide : BeginLatex
//
// An MRFSamplerRandomMAP, which derives from the
// MRFSampler, is instanciated. The sampler is in charge of
// proposing a modification for a given site. The
// MRFSamplerRandomMAP, randomly pick one possible value
// according to the MAP probability.
//
// Software Guide : EndLatex
// Software Guide : BeginCodeSnippet
typedef otb::MRFSamplerRandom< InputImageType, LabelledImageType> SamplerType;
// Software Guide : EndCodeSnippet
// Software Guide : BeginLatex
//
// An MRFOptimizerMetropolis, which derives from the
// MRFOptimizer, is instanciated. The optimizer is in charge
// of accepting or rejecting the value proposed by the sampler. The
// MRFSamplerRandomMAP, accept the proposal according to the
// variation of energy it causes and a temperature parameter.
//
// Software Guide : EndLatex
// Software Guide : BeginCodeSnippet
typedef otb::MRFOptimizerMetropolis OptimizerType;
// Software Guide : EndCodeSnippet
// Software Guide : BeginLatex
//
// Two energy, deriving from the MRFEnergy class need to be instantiated. One energy
// is required for the regularization, taking into account the relationship between neighboring pixels
// in the classified image. Here it is done with the MRFEnergyPotts, which implements
// a Potts model.
//
// The second energy is used for the fidelity to the original data. Here it is done with a
// MRFEnergyFisherClassification class, which defines a Fisher distribution to model the data.
//
// Software Guide : EndLatex
// Software Guide : BeginCodeSnippet
typedef otb::MRFEnergyPotts
<LabelledImageType, LabelledImageType> EnergyRegularizationType;
typedef otb::MRFEnergyFisherClassification
<InputImageType, LabelledImageType> EnergyFidelityType;
// Software Guide : EndCodeSnippet
// Software Guide : BeginLatex
//
// The different filters composing our pipeline are created by invoking their
// New() methods, assigning the results to smart pointers.
//
// Software Guide : EndLatex
// Software Guide : BeginCodeSnippet
MarkovRandomFieldFilterType::Pointer markovFilter = MarkovRandomFieldFilterType::New();
EnergyRegularizationType::Pointer energyRegularization = EnergyRegularizationType::New();
EnergyFidelityType::Pointer energyFidelity = EnergyFidelityType::New();
OptimizerType::Pointer optimizer = OptimizerType::New();
SamplerType::Pointer sampler = SamplerType::New();
// Software Guide : EndCodeSnippet
// Software Guide : BeginLatex
//
// Parameter for the MRFEnergyFisherClassification class are created. The shape parameters M, L
// and the weighting parameter mu are computed in a supervised step
//
// Software Guide : EndLatex
if ((bool)(atoi(argv[6])) == true)
{
// Overpass random calculation(for test only):
sampler->InitializeSeed(0);
optimizer->InitializeSeed(1);
markovFilter->InitializeSeed(1);
}
// Software Guide : BeginCodeSnippet
unsigned int nClass =4;
energyFidelity->SetNumberOfParameters(3*nClass);
EnergyFidelityType::ParametersType parameters;
parameters.SetSize(energyFidelity->GetNumberOfParameters());
//Class 0
parameters[0] = 12.353042; //Class 0 mu
parameters[1] = 2.156422; //Class 0 L
parameters[2] = 4.920403; //Class 0 M
//Class 1
parameters[3] = 72.068291; //Class 1 mu
parameters[4] = 11.000000; //Class 1 L
parameters[5] = 50.950001; //Class 1 M
//Class 2
parameters[6] = 146.665985; //Class 2 mu
parameters[7] = 11.000000; //Class 2 L
parameters[8] = 50.900002; //Class 2 M
//Class 3
parameters[9] = 200.010132; //Class 3 mu
parameters[10] = 11.000000; //Class 3 L
parameters[11] = 50.950001; //Class 3 M
energyFidelity->SetParameters(parameters);
// Software Guide : EndCodeSnippet
// Software Guide : BeginLatex
//
// Parameters are given to the different classes and the sampler, optimizer and
// energies are connected with the Markov filter.
//
// Software Guide : EndLatex
// Software Guide : BeginCodeSnippet
OptimizerType::ParametersType param(1);
param.Fill(atof(argv[6]));
optimizer->SetParameters(param);
markovFilter->SetNumberOfClasses(nClass);
markovFilter->SetMaximumNumberOfIterations(atoi(argv[5]));
markovFilter->SetErrorTolerance(0.0);
markovFilter->SetLambda(atof(argv[4]));
markovFilter->SetNeighborhoodRadius(1);
markovFilter->SetEnergyRegularization(energyRegularization);
markovFilter->SetEnergyFidelity(energyFidelity);
markovFilter->SetOptimizer(optimizer);
markovFilter->SetSampler(sampler);
// Software Guide : EndCodeSnippet
// Software Guide : BeginLatex
//
// The pipeline is connected. An itkRescaleIntensityImageFilter
// rescales the classified image before saving it.
//
// Software Guide : EndLatex
// Software Guide : BeginCodeSnippet
markovFilter->SetInput(reader->GetOutput());
typedef itk::RescaleIntensityImageFilter
< LabelledImageType, LabelledImageType > RescaleType;
RescaleType::Pointer rescaleFilter = RescaleType::New();
rescaleFilter->SetOutputMinimum(0);
rescaleFilter->SetOutputMaximum(255);
rescaleFilter->SetInput( markovFilter->GetOutput() );
writer->SetInput( rescaleFilter->GetOutput() );
writer->Update();
// Software Guide : EndCodeSnippet
//convert output image to color
typedef itk::RGBPixel<unsigned char> RGBPixelType;
typedef otb::Image<RGBPixelType, 2> RGBImageType;
typedef itk::Functor::ScalarToRGBPixelFunctor<unsigned long> ColorMapFunctorType;
typedef itk::UnaryFunctorImageFilter< LabelledImageType, RGBImageType, ColorMapFunctorType> ColorMapFilterType;
ColorMapFilterType::Pointer colormapper = ColorMapFilterType::New();
colormapper->SetInput( rescaleFilter->GetOutput() );
// Software Guide : BeginLatex
//
// We can now create an image file writer and save the image.
//
// Software Guide : EndLatex
// Software Guide : BeginCodeSnippet
typedef otb::StreamingImageFileWriter<RGBImageType> WriterRescaledType;
WriterRescaledType::Pointer writerRescaled = WriterRescaledType::New();
writerRescaled->SetFileName( outputRescaledImageFileName );
writerRescaled->SetInput( colormapper->GetOutput() );
writerRescaled->Update();
// Software Guide : EndCodeSnippet
// Software Guide : BeginLatex
//
// Figure~\ref{fig:MRF_CLASSIFICATION3} shows the output of the Markov Random
// Field classification into four classes using the
// Fisher-distribution as likelihood term.
//
// \begin{figure}
// \center
// \includegraphics[width=0.44\textwidth]{QB_Suburb.eps}
// \includegraphics[width=0.44\textwidth]{MarkovRandomField3_color_value.eps}
// \itkcaption[MRF restauration]{Result of applying
// the \doxygen{otb}{MarkovRandomFieldFilter} to an extract from a PAN Quickbird
// image for classification into four classes using the Fisher-distribution as
// likehood term. From left to right : original image,
// classification.}
// \label{fig:MRF_CLASSIFICATION3}
// \end{figure}
//
// Software Guide : EndLatex
return EXIT_SUCCESS;
}
<|endoftext|> |
<commit_before>/* This file is part of the Vc library.
Copyright (C) 2010 Matthias Kretz <kretz@kde.org>
Vc is free software: you can redistribute it and/or modify
it under the terms of the GNU Lesser General Public License as
published by the Free Software Foundation, either version 3 of
the License, or (at your option) any later version.
Vc 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 Vc. If not, see <http://www.gnu.org/licenses/>.
*/
#include "../include/Vc/global.h"
#include "support.h"
#include "../cpuid.h"
namespace Vc
{
bool isImplementationSupported(Implementation impl)
{
// for AVX we need to check for OSXSAVE and AVX
switch (impl) {
case ScalarImpl:
return true;
case SSE2Impl:
return CpuId::hasSse2();
case SSE3Impl:
return CpuId::hasSse3();
case SSSE3Impl:
return CpuId::hasSsse3();
case SSE41Impl:
return CpuId::hasSse41();
case SSE42Impl:
return CpuId::hasSse42();
case SSE4aImpl:
return CpuId::hasSse4a();
case AVXImpl:
#ifndef VC_NO_XGETBV
if (CpuId::hasOsxsave() && CpuId::hasAvx()) {
unsigned int eax;
asm("xgetbv" : "=a"(eax) : "c"(0) : "edx");
return (eax & 0x06) == 0x06;
}
#endif
return false;
}
return false;
}
} // namespace Vc
// vim: sw=4 sts=4 et tw=100
<commit_msg>make sure CpuId was initialized before checking the flags<commit_after>/* This file is part of the Vc library.
Copyright (C) 2010 Matthias Kretz <kretz@kde.org>
Vc is free software: you can redistribute it and/or modify
it under the terms of the GNU Lesser General Public License as
published by the Free Software Foundation, either version 3 of
the License, or (at your option) any later version.
Vc 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 Vc. If not, see <http://www.gnu.org/licenses/>.
*/
#include "../include/Vc/global.h"
#include "support.h"
#include "../cpuid.h"
namespace Vc
{
bool isImplementationSupported(Implementation impl)
{
CpuId::init();
// for AVX we need to check for OSXSAVE and AVX
switch (impl) {
case ScalarImpl:
return true;
case SSE2Impl:
return CpuId::hasSse2();
case SSE3Impl:
return CpuId::hasSse3();
case SSSE3Impl:
return CpuId::hasSsse3();
case SSE41Impl:
return CpuId::hasSse41();
case SSE42Impl:
return CpuId::hasSse42();
case SSE4aImpl:
return CpuId::hasSse4a();
case AVXImpl:
#ifndef VC_NO_XGETBV
if (CpuId::hasOsxsave() && CpuId::hasAvx()) {
unsigned int eax;
asm("xgetbv" : "=a"(eax) : "c"(0) : "edx");
return (eax & 0x06) == 0x06;
}
#endif
return false;
}
return false;
}
} // namespace Vc
// vim: sw=4 sts=4 et tw=100
<|endoftext|> |
<commit_before>// This file is a part of the OpenSurgSim project.
// Copyright 2013, SimQuest Solutions Inc.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
#include "SurgSim/Framework/Log.h"
#include "SurgSim/Math/Geometry.h"
#include "SurgSim/Math/OdeState.h"
#include "SurgSim/Math/SparseMatrix.h"
#include "SurgSim/Physics/LinearSpring.h"
using SurgSim::Math::Matrix;
using SurgSim::Math::Matrix33d;
using SurgSim::Math::OdeState;
using SurgSim::Math::SparseMatrix;
using SurgSim::Math::Vector;
using SurgSim::Math::Vector3d;
namespace SurgSim
{
namespace Physics
{
LinearSpring::LinearSpring(size_t nodeId0, size_t nodeId1) :
Spring(), m_restLength(-1.0), m_stiffness(-1.0), m_damping(0.0)
{
m_nodeIds.push_back(nodeId0);
m_nodeIds.push_back(nodeId1);
}
void LinearSpring::initialize(const OdeState& state)
{
Spring::initialize(state);
SURGSIM_ASSERT(m_restLength >= 0.0) << "Spring rest length was not set, please call setRestLength()";
SURGSIM_ASSERT(m_stiffness >= 0.0) << "Spring stiffness was not set, please call setStiffness()";
}
void LinearSpring::setStiffness(double stiffness)
{
SURGSIM_ASSERT(stiffness >= 0.0) << "Spring stiffness cannot be negative";
m_stiffness = stiffness;
}
double LinearSpring::getStiffness() const
{
return m_stiffness;
}
void LinearSpring::setDamping(double damping)
{
SURGSIM_ASSERT(damping >= 0.0) << "Spring damping cannot be negative";
m_damping = damping;
}
double LinearSpring::getDamping() const
{
return m_damping;
}
void LinearSpring::setRestLength(double restLength)
{
SURGSIM_ASSERT(restLength >= 0.0) << "Spring rest length cannot be negative";
m_restLength = restLength;
}
double LinearSpring::getRestLength() const
{
return m_restLength;
}
void LinearSpring::addForce(const OdeState& state, Vector* F, double scale)
{
const auto& x0 = state.getPositions().segment<3>(3 * m_nodeIds[0]);
const auto& x1 = state.getPositions().segment<3>(3 * m_nodeIds[1]);
const auto& v0 = state.getVelocities().segment<3>(3 * m_nodeIds[0]);
const auto& v1 = state.getVelocities().segment<3>(3 * m_nodeIds[1]);
Vector3d u = x1 - x0;
double length = u.norm();
if (length < SurgSim::Math::Geometry::DistanceEpsilon)
{
SURGSIM_LOG_WARNING(SurgSim::Framework::Logger::getDefaultLogger()) <<
"Spring (initial length = " << m_restLength << ") became degenerated " <<
"with 0 length => no force generated";
return;
}
u /= length;
double elongationPosition = length - m_restLength;
double elongationVelocity = (v1 - v0).dot(u);
const Vector3d f = scale * (m_stiffness * elongationPosition + m_damping * elongationVelocity) * u;
// Assembly stage in F
F->segment<3>(3 * m_nodeIds[0]) += f;
F->segment<3>(3 * m_nodeIds[1]) -= f;
}
void LinearSpring::addDamping(const OdeState& state, Math::SparseMatrix* D, double scale)
{
Matrix33d De;
// The spring has 2 nodes with positions {x1, x2}, velocities {v1, v2} and force {F1, F2=-F1}
// Also note from addForce that the positions and velocities play a symmetric role in the force calculation
// i.e. dFi/dx1 = -dFi/dx2 and dFi/dv1 = -dFi/dv2
// The damping matrix is D = -dF/dv = (-dF1/dv1 -dF1/dv2) = (-dF1/dv1 dF1/dv1)
// (-dF2/dv1 -dF2/dv2) ( dF1/dv1 -dF1/dv1)
// Let's compute De = -dF1/dv1
if (!computeDampingAndStiffness(state, &De, nullptr))
{
return;
}
De *= scale;
// Assembly stage in D
Math::addSubMatrix(De, static_cast<SparseMatrix::Index>(m_nodeIds[0]),
static_cast<SparseMatrix::Index>(m_nodeIds[0]),
D, false);
Math::addSubMatrix((-De).eval(), static_cast<SparseMatrix::Index>(m_nodeIds[0]),
static_cast<SparseMatrix::Index>(m_nodeIds[1]),
D, false);
Math::addSubMatrix((-De).eval(), static_cast<SparseMatrix::Index>(m_nodeIds[1]),
static_cast<SparseMatrix::Index>(m_nodeIds[0]),
D, false);
Math::addSubMatrix(De, static_cast<SparseMatrix::Index>(m_nodeIds[1]),
static_cast<SparseMatrix::Index>(m_nodeIds[1]),
D, false);
}
void LinearSpring::addStiffness(const OdeState& state, Math::SparseMatrix* K, double scale)
{
Matrix33d Ke;
// The spring has 2 nodes with positions {x1, x2}, velocities {v1, v2} and force {F1, F2=-F1}
// Also note from addForce that the positions and velocities play a symmetric role in the force calculation
// i.e. dFi/dx1 = -dFi/dx2 and dFi/dv1 = -dFi/dv2
// The stiffness matrix is K = -dF/dx = (-dF1/dx1 -dF1/dx2) = (-dF1/dx1 dF1/dx1)
// (-dF2/dx1 -dF2/dx2) ( dF1/dx1 -dF1/dx1)
// Let's compute Ke = -dF1/dx1
if (!computeDampingAndStiffness(state, nullptr, &Ke))
{
return;
}
Ke *= scale;
// Assembly stage in K
Math::addSubMatrix(Ke, static_cast<SparseMatrix::Index>(m_nodeIds[0]),
static_cast<SparseMatrix::Index>(m_nodeIds[0]),
K, false);
Math::addSubMatrix((-Ke).eval(), static_cast<SparseMatrix::Index>(m_nodeIds[0]),
static_cast<SparseMatrix::Index>(m_nodeIds[1]),
K, false);
Math::addSubMatrix((-Ke).eval(), static_cast<SparseMatrix::Index>(m_nodeIds[1]),
static_cast<SparseMatrix::Index>(m_nodeIds[0]),
K, false);
Math::addSubMatrix(Ke, static_cast<SparseMatrix::Index>(m_nodeIds[1]),
static_cast<SparseMatrix::Index>(m_nodeIds[1]),
K, false);
}
void LinearSpring::addFDK(const OdeState& state, Vector* F, Math::SparseMatrix* D, Math::SparseMatrix* K)
{
Matrix33d De, Ke;
// Assembly stage in F. Note that the force calculation does not rely on any matrices.
addForce(state, F);
// The spring has 2 nodes with positions {x1, x2}, velocities {v1, v2} and force {F1, F2=-F1}
// Also note from addForce that the positions and velocities play a symmetric role in the force calculation
// i.e. dFi/dx1 = -dFi/dx2 and dFi/dv1 = -dFi/dv2
// The stiffness matrix is K = -dF/dx = (-dF1/dx1 -dF1/dx2) = (-dF1/dx1 dF1/dx1)
// (-dF2/dx1 -dF2/dx2) ( dF1/dx1 -dF1/dx1)
// The damping matrix is D = -dF/dv = (-dF1/dv1 -dF1/dv2) = (-dF1/dv1 dF1/dv1)
// (-dF2/dv1 -dF2/dv2) ( dF1/dv1 -dF1/dv1)
// Let's compute De = -dF1/dv1 and Ke = -dF1/dx1
if (!computeDampingAndStiffness(state, &De, &Ke))
{
return;
}
// Assembly stage in K
Math::addSubMatrix(Ke, static_cast<SparseMatrix::Index>(m_nodeIds[0]),
static_cast<SparseMatrix::Index>(m_nodeIds[0]),
K, false);
Math::addSubMatrix((-Ke).eval(), static_cast<SparseMatrix::Index>(m_nodeIds[0]),
static_cast<SparseMatrix::Index>(m_nodeIds[1]),
K, false);
Math::addSubMatrix((-Ke).eval(), static_cast<SparseMatrix::Index>(m_nodeIds[1]),
static_cast<SparseMatrix::Index>(m_nodeIds[0]),
K, false);
Math::addSubMatrix(Ke, static_cast<SparseMatrix::Index>(m_nodeIds[1]),
static_cast<SparseMatrix::Index>(m_nodeIds[1]),
K, false);
// Assembly stage in D
Math::addSubMatrix(De, static_cast<SparseMatrix::Index>(m_nodeIds[0]),
static_cast<SparseMatrix::Index>(m_nodeIds[0]),
D, false);
Math::addSubMatrix((-De).eval(), static_cast<SparseMatrix::Index>(m_nodeIds[0]),
static_cast<SparseMatrix::Index>(m_nodeIds[1]),
D, false);
Math::addSubMatrix((-De).eval(), static_cast<SparseMatrix::Index>(m_nodeIds[1]),
static_cast<SparseMatrix::Index>(m_nodeIds[0]),
D, false);
Math::addSubMatrix(De, static_cast<SparseMatrix::Index>(m_nodeIds[1]),
static_cast<SparseMatrix::Index>(m_nodeIds[1]),
D, false);
}
void LinearSpring::addMatVec(const OdeState& state, double alphaD, double alphaK, const Vector& vector, Vector* F)
{
// Premature return if both factors are zero
if (alphaK == 0.0 && alphaD == 0.0)
{
return;
}
Matrix33d De, Ke;
if (!computeDampingAndStiffness(state, (alphaD != 0 ? &De : nullptr), (alphaK != 0 ? &Ke : nullptr)))
{
return;
}
// Shared data: the 2x 3D vectors to multiply the matrices with
const auto& vector1 = vector.segment<3>(3 * m_nodeIds[0]);
const auto& vector2 = vector.segment<3>(3 * m_nodeIds[1]);
if (alphaD != 0.0)
{
const Vector3d force = alphaD * (De * (vector1 - vector2));
F->segment<3>(3 * m_nodeIds[0]) += force;
F->segment<3>(3 * m_nodeIds[1]) -= force;
}
if (alphaK != 0.0)
{
const Vector3d force = alphaK * (Ke * (vector1 - vector2));
F->segment<3>(3 * m_nodeIds[0]) += force;
F->segment<3>(3 * m_nodeIds[1]) -= force;
}
}
bool LinearSpring::computeDampingAndStiffness(const OdeState& state, Matrix33d* De, Matrix33d* Ke)
{
const auto& x0 = state.getPositions().segment<3>(3 * m_nodeIds[0]);
const auto& x1 = state.getPositions().segment<3>(3 * m_nodeIds[1]);
const auto& v0 = state.getVelocities().segment<3>(3 * m_nodeIds[0]);
const auto& v1 = state.getVelocities().segment<3>(3 * m_nodeIds[1]);
Vector3d u = x1 - x0;
double length = u.norm();
if (length < SurgSim::Math::Geometry::DistanceEpsilon)
{
SURGSIM_LOG_WARNING(SurgSim::Framework::Logger::getDefaultLogger()) <<
"Spring (initial length = " << m_restLength <<
") became degenerated with 0 length => force derivative degenerated";
return false;
}
u /= length;
double lRatio = (length - m_restLength) / length;
double vRatio = (v1 - v0).dot(u) / length;
Matrix33d uuT = u * u.transpose();
// Update the stiffness matrix
if (Ke != nullptr)
{
*Ke = Matrix33d::Identity() * (m_stiffness * lRatio + m_damping * vRatio);
*Ke -= uuT * (m_stiffness * (lRatio - 1.0) + 2.0 * m_damping * vRatio);
*Ke += m_damping * (u * (v1 - v0).transpose()) / length;
}
// Update the damping matrix
if (De != nullptr)
{
*De = m_damping * uuT;
}
return true;
}
bool LinearSpring::operator ==(const Spring& spring) const
{
const LinearSpring* ls = dynamic_cast<const LinearSpring*>(&spring);
if (! ls)
{
return false;
}
return m_nodeIds == ls->m_nodeIds &&
m_restLength == ls->m_restLength && m_stiffness == ls->m_stiffness && m_damping == ls->m_damping;
}
bool LinearSpring::operator !=(const Spring& spring) const
{
return !((*this) == spring);
}
} // namespace Physics
} // namespace SurgSim
<commit_msg>LinearSpring only evaluates negative operation on Ke or De once per fn.<commit_after>// This file is a part of the OpenSurgSim project.
// Copyright 2013, SimQuest Solutions Inc.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
#include "SurgSim/Framework/Log.h"
#include "SurgSim/Math/Geometry.h"
#include "SurgSim/Math/OdeState.h"
#include "SurgSim/Math/SparseMatrix.h"
#include "SurgSim/Physics/LinearSpring.h"
using SurgSim::Math::Matrix;
using SurgSim::Math::Matrix33d;
using SurgSim::Math::OdeState;
using SurgSim::Math::SparseMatrix;
using SurgSim::Math::Vector;
using SurgSim::Math::Vector3d;
namespace SurgSim
{
namespace Physics
{
LinearSpring::LinearSpring(size_t nodeId0, size_t nodeId1) :
Spring(), m_restLength(-1.0), m_stiffness(-1.0), m_damping(0.0)
{
m_nodeIds.push_back(nodeId0);
m_nodeIds.push_back(nodeId1);
}
void LinearSpring::initialize(const OdeState& state)
{
Spring::initialize(state);
SURGSIM_ASSERT(m_restLength >= 0.0) << "Spring rest length was not set, please call setRestLength()";
SURGSIM_ASSERT(m_stiffness >= 0.0) << "Spring stiffness was not set, please call setStiffness()";
}
void LinearSpring::setStiffness(double stiffness)
{
SURGSIM_ASSERT(stiffness >= 0.0) << "Spring stiffness cannot be negative";
m_stiffness = stiffness;
}
double LinearSpring::getStiffness() const
{
return m_stiffness;
}
void LinearSpring::setDamping(double damping)
{
SURGSIM_ASSERT(damping >= 0.0) << "Spring damping cannot be negative";
m_damping = damping;
}
double LinearSpring::getDamping() const
{
return m_damping;
}
void LinearSpring::setRestLength(double restLength)
{
SURGSIM_ASSERT(restLength >= 0.0) << "Spring rest length cannot be negative";
m_restLength = restLength;
}
double LinearSpring::getRestLength() const
{
return m_restLength;
}
void LinearSpring::addForce(const OdeState& state, Vector* F, double scale)
{
const auto& x0 = state.getPositions().segment<3>(3 * m_nodeIds[0]);
const auto& x1 = state.getPositions().segment<3>(3 * m_nodeIds[1]);
const auto& v0 = state.getVelocities().segment<3>(3 * m_nodeIds[0]);
const auto& v1 = state.getVelocities().segment<3>(3 * m_nodeIds[1]);
Vector3d u = x1 - x0;
double length = u.norm();
if (length < SurgSim::Math::Geometry::DistanceEpsilon)
{
SURGSIM_LOG_WARNING(SurgSim::Framework::Logger::getDefaultLogger()) <<
"Spring (initial length = " << m_restLength << ") became degenerated " <<
"with 0 length => no force generated";
return;
}
u /= length;
double elongationPosition = length - m_restLength;
double elongationVelocity = (v1 - v0).dot(u);
const Vector3d f = scale * (m_stiffness * elongationPosition + m_damping * elongationVelocity) * u;
// Assembly stage in F
F->segment<3>(3 * m_nodeIds[0]) += f;
F->segment<3>(3 * m_nodeIds[1]) -= f;
}
void LinearSpring::addDamping(const OdeState& state, Math::SparseMatrix* D, double scale)
{
Matrix33d De;
// The spring has 2 nodes with positions {x1, x2}, velocities {v1, v2} and force {F1, F2=-F1}
// Also note from addForce that the positions and velocities play a symmetric role in the force calculation
// i.e. dFi/dx1 = -dFi/dx2 and dFi/dv1 = -dFi/dv2
// The damping matrix is D = -dF/dv = (-dF1/dv1 -dF1/dv2) = (-dF1/dv1 dF1/dv1)
// (-dF2/dv1 -dF2/dv2) ( dF1/dv1 -dF1/dv1)
// Let's compute De = -dF1/dv1
if (!computeDampingAndStiffness(state, &De, nullptr))
{
return;
}
De *= scale;
// Assembly stage in D
Math::addSubMatrix(De, static_cast<SparseMatrix::Index>(m_nodeIds[0]),
static_cast<SparseMatrix::Index>(m_nodeIds[0]),
D, false);
Matrix33d negativeDe = -De;
Math::addSubMatrix(negativeDe, static_cast<SparseMatrix::Index>(m_nodeIds[0]),
static_cast<SparseMatrix::Index>(m_nodeIds[1]),
D, false);
Math::addSubMatrix(negativeDe, static_cast<SparseMatrix::Index>(m_nodeIds[1]),
static_cast<SparseMatrix::Index>(m_nodeIds[0]),
D, false);
Math::addSubMatrix(De, static_cast<SparseMatrix::Index>(m_nodeIds[1]),
static_cast<SparseMatrix::Index>(m_nodeIds[1]),
D, false);
}
void LinearSpring::addStiffness(const OdeState& state, Math::SparseMatrix* K, double scale)
{
Matrix33d Ke;
// The spring has 2 nodes with positions {x1, x2}, velocities {v1, v2} and force {F1, F2=-F1}
// Also note from addForce that the positions and velocities play a symmetric role in the force calculation
// i.e. dFi/dx1 = -dFi/dx2 and dFi/dv1 = -dFi/dv2
// The stiffness matrix is K = -dF/dx = (-dF1/dx1 -dF1/dx2) = (-dF1/dx1 dF1/dx1)
// (-dF2/dx1 -dF2/dx2) ( dF1/dx1 -dF1/dx1)
// Let's compute Ke = -dF1/dx1
if (!computeDampingAndStiffness(state, nullptr, &Ke))
{
return;
}
Ke *= scale;
// Assembly stage in K
Math::addSubMatrix(Ke, static_cast<SparseMatrix::Index>(m_nodeIds[0]),
static_cast<SparseMatrix::Index>(m_nodeIds[0]),
K, false);
Matrix33d negativeKe = -Ke;
Math::addSubMatrix(negativeKe, static_cast<SparseMatrix::Index>(m_nodeIds[0]),
static_cast<SparseMatrix::Index>(m_nodeIds[1]),
K, false);
Math::addSubMatrix(negativeKe, static_cast<SparseMatrix::Index>(m_nodeIds[1]),
static_cast<SparseMatrix::Index>(m_nodeIds[0]),
K, false);
Math::addSubMatrix(Ke, static_cast<SparseMatrix::Index>(m_nodeIds[1]),
static_cast<SparseMatrix::Index>(m_nodeIds[1]),
K, false);
}
void LinearSpring::addFDK(const OdeState& state, Vector* F, Math::SparseMatrix* D, Math::SparseMatrix* K)
{
Matrix33d De, Ke;
// Assembly stage in F. Note that the force calculation does not rely on any matrices.
addForce(state, F);
// The spring has 2 nodes with positions {x1, x2}, velocities {v1, v2} and force {F1, F2=-F1}
// Also note from addForce that the positions and velocities play a symmetric role in the force calculation
// i.e. dFi/dx1 = -dFi/dx2 and dFi/dv1 = -dFi/dv2
// The stiffness matrix is K = -dF/dx = (-dF1/dx1 -dF1/dx2) = (-dF1/dx1 dF1/dx1)
// (-dF2/dx1 -dF2/dx2) ( dF1/dx1 -dF1/dx1)
// The damping matrix is D = -dF/dv = (-dF1/dv1 -dF1/dv2) = (-dF1/dv1 dF1/dv1)
// (-dF2/dv1 -dF2/dv2) ( dF1/dv1 -dF1/dv1)
// Let's compute De = -dF1/dv1 and Ke = -dF1/dx1
if (!computeDampingAndStiffness(state, &De, &Ke))
{
return;
}
// Assembly stage in K
Math::addSubMatrix(Ke, static_cast<SparseMatrix::Index>(m_nodeIds[0]),
static_cast<SparseMatrix::Index>(m_nodeIds[0]),
K, false);
Matrix33d negativeKe = -Ke;
Math::addSubMatrix(negativeKe, static_cast<SparseMatrix::Index>(m_nodeIds[0]),
static_cast<SparseMatrix::Index>(m_nodeIds[1]),
K, false);
Math::addSubMatrix(negativeKe, static_cast<SparseMatrix::Index>(m_nodeIds[1]),
static_cast<SparseMatrix::Index>(m_nodeIds[0]),
K, false);
Math::addSubMatrix(Ke, static_cast<SparseMatrix::Index>(m_nodeIds[1]),
static_cast<SparseMatrix::Index>(m_nodeIds[1]),
K, false);
// Assembly stage in D
Math::addSubMatrix(De, static_cast<SparseMatrix::Index>(m_nodeIds[0]),
static_cast<SparseMatrix::Index>(m_nodeIds[0]),
D, false);
Matrix33d negativeDe = -De;
Math::addSubMatrix(negativeDe, static_cast<SparseMatrix::Index>(m_nodeIds[0]),
static_cast<SparseMatrix::Index>(m_nodeIds[1]),
D, false);
Math::addSubMatrix(negativeDe, static_cast<SparseMatrix::Index>(m_nodeIds[1]),
static_cast<SparseMatrix::Index>(m_nodeIds[0]),
D, false);
Math::addSubMatrix(De, static_cast<SparseMatrix::Index>(m_nodeIds[1]),
static_cast<SparseMatrix::Index>(m_nodeIds[1]),
D, false);
}
void LinearSpring::addMatVec(const OdeState& state, double alphaD, double alphaK, const Vector& vector, Vector* F)
{
// Premature return if both factors are zero
if (alphaK == 0.0 && alphaD == 0.0)
{
return;
}
Matrix33d De, Ke;
if (!computeDampingAndStiffness(state, (alphaD != 0 ? &De : nullptr), (alphaK != 0 ? &Ke : nullptr)))
{
return;
}
// Shared data: the 2x 3D vectors to multiply the matrices with
const auto& vector1 = vector.segment<3>(3 * m_nodeIds[0]);
const auto& vector2 = vector.segment<3>(3 * m_nodeIds[1]);
if (alphaD != 0.0)
{
const Vector3d force = alphaD * (De * (vector1 - vector2));
F->segment<3>(3 * m_nodeIds[0]) += force;
F->segment<3>(3 * m_nodeIds[1]) -= force;
}
if (alphaK != 0.0)
{
const Vector3d force = alphaK * (Ke * (vector1 - vector2));
F->segment<3>(3 * m_nodeIds[0]) += force;
F->segment<3>(3 * m_nodeIds[1]) -= force;
}
}
bool LinearSpring::computeDampingAndStiffness(const OdeState& state, Matrix33d* De, Matrix33d* Ke)
{
const auto& x0 = state.getPositions().segment<3>(3 * m_nodeIds[0]);
const auto& x1 = state.getPositions().segment<3>(3 * m_nodeIds[1]);
const auto& v0 = state.getVelocities().segment<3>(3 * m_nodeIds[0]);
const auto& v1 = state.getVelocities().segment<3>(3 * m_nodeIds[1]);
Vector3d u = x1 - x0;
double length = u.norm();
if (length < SurgSim::Math::Geometry::DistanceEpsilon)
{
SURGSIM_LOG_WARNING(SurgSim::Framework::Logger::getDefaultLogger()) <<
"Spring (initial length = " << m_restLength <<
") became degenerated with 0 length => force derivative degenerated";
return false;
}
u /= length;
double lRatio = (length - m_restLength) / length;
double vRatio = (v1 - v0).dot(u) / length;
Matrix33d uuT = u * u.transpose();
// Update the stiffness matrix
if (Ke != nullptr)
{
*Ke = Matrix33d::Identity() * (m_stiffness * lRatio + m_damping * vRatio);
*Ke -= uuT * (m_stiffness * (lRatio - 1.0) + 2.0 * m_damping * vRatio);
*Ke += m_damping * (u * (v1 - v0).transpose()) / length;
}
// Update the damping matrix
if (De != nullptr)
{
*De = m_damping * uuT;
}
return true;
}
bool LinearSpring::operator ==(const Spring& spring) const
{
const LinearSpring* ls = dynamic_cast<const LinearSpring*>(&spring);
if (! ls)
{
return false;
}
return m_nodeIds == ls->m_nodeIds &&
m_restLength == ls->m_restLength && m_stiffness == ls->m_stiffness && m_damping == ls->m_damping;
}
bool LinearSpring::operator !=(const Spring& spring) const
{
return !((*this) == spring);
}
} // namespace Physics
} // namespace SurgSim
<|endoftext|> |
<commit_before>/*=====================================================================
QGroundControl Open Source Ground Control Station
(c) 2009 - 2011 QGROUNDCONTROL PROJECT <http://www.qgroundcontrol.org>
This file is part of the QGROUNDCONTROL project
QGROUNDCONTROL 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.
QGROUNDCONTROL 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 QGROUNDCONTROL. If not, see <http://www.gnu.org/licenses/>.
======================================================================*/
/**
* @file
* @brief Main executable
* @author Lorenz Meier <mavteam@student.ethz.ch>
*
*/
#include <QtGlobal>
#include <QApplication>
#include <QSslSocket>
#include <QProcessEnvironment>
#ifndef __mobile__
#include <QSerialPortInfo>
#endif
#include "QGCApplication.h"
#include "MainWindow.h"
#ifdef QT_DEBUG
#ifndef __mobile__
#include "UnitTest.h"
#endif
#include "CmdLineOptParser.h"
#ifdef Q_OS_WIN
#include <crtdbg.h>
#endif
#endif
#include <iostream>
/* SDL does ugly things to main() */
#ifdef main
#undef main
#endif
#ifndef __mobile__
Q_DECLARE_METATYPE(QSerialPortInfo)
#endif
#ifdef Q_OS_WIN
/// @brief Message handler which is installed using qInstallMsgHandler so you do not need
/// the MSFT debug tools installed to see qDebug(), qWarning(), qCritical and qAbort
void msgHandler(QtMsgType type, const QMessageLogContext &context, const QString &msg)
{
const char symbols[] = { 'I', 'E', '!', 'X' };
QString output = QString("[%1] at %2:%3 - \"%4\"").arg(symbols[type]).arg(context.file).arg(context.line).arg(msg);
std::cerr << output.toStdString() << std::endl;
if( type == QtFatalMsg ) abort();
}
/// @brief CRT Report Hook installed using _CrtSetReportHook. We install this hook when
/// we don't want asserts to pop a dialog on windows.
int WindowsCrtReportHook(int reportType, char* message, int* returnValue)
{
Q_UNUSED(reportType);
std::cerr << message << std::endl; // Output message to stderr
*returnValue = 0; // Don't break into debugger
return true; // We handled this fully ourselves
}
#endif
#ifdef __android__
#include <jni.h>
#include "qserialport.h"
jint JNI_OnLoad(JavaVM* vm, void* reserved)
{
Q_UNUSED(reserved);
JNIEnv* env;
if (vm->GetEnv(reinterpret_cast<void**>(&env), JNI_VERSION_1_6) != JNI_OK) {
return -1;
}
QSerialPort::setNativeMethods();
return JNI_VERSION_1_6;
}
#endif
/**
* @brief Starts the application
*
* @param argc Number of commandline arguments
* @param argv Commandline arguments
* @return exit code, 0 for normal exit and !=0 for error cases
*/
int main(int argc, char *argv[])
{
#ifdef Q_OS_MAC
#ifndef __ios__
// Prevent Apple's app nap from screwing us over
// tip: the domain can be cross-checked on the command line with <defaults domains>
QProcess::execute("defaults write org.qgroundcontrol.qgroundcontrol NSAppSleepDisabled -bool YES");
#endif
#endif
// install the message handler
#ifdef Q_OS_WIN
qInstallMessageHandler(msgHandler);
#endif
// The following calls to qRegisterMetaType are done to silence debug output which warns
// that we use these types in signals, and without calling qRegisterMetaType we can't queue
// these signals. In general we don't queue these signals, but we do what the warning says
// anyway to silence the debug output.
#ifndef __ios__
qRegisterMetaType<QSerialPort::SerialPortError>();
#endif
qRegisterMetaType<QAbstractSocket::SocketError>();
#ifndef __mobile__
qRegisterMetaType<QSerialPortInfo>();
#endif
// We statically link to the google QtLocation plugin
#ifdef Q_OS_WIN
// In Windows, the compiler doesn't see the use of the class created by Q_IMPORT_PLUGIN
#pragma warning( disable : 4930 4101 )
#endif
Q_IMPORT_PLUGIN(QGeoServiceProviderFactoryQGC)
bool runUnitTests = false; // Run unit tests
bool stressUnitTests = false; // Stress test unit tests
#ifdef QT_DEBUG
// We parse a small set of command line options here prior to QGCApplication in order to handle the ones
// which need to be handled before a QApplication object is started.
bool quietWindowsAsserts = false; // Don't let asserts pop dialog boxes
QString unitTestOptions;
CmdLineOpt_t rgCmdLineOptions[] = {
{ "--unittest", &runUnitTests, &unitTestOptions },
{ "--unittest-stress", &stressUnitTests, &unitTestOptions },
{ "--no-windows-assert-ui", &quietWindowsAsserts, NULL },
// Add additional command line option flags here
};
ParseCmdLineOptions(argc, argv, rgCmdLineOptions, sizeof(rgCmdLineOptions)/sizeof(rgCmdLineOptions[0]), false);
if (stressUnitTests) {
runUnitTests = true;
}
if (quietWindowsAsserts) {
#ifdef Q_OS_WIN
_CrtSetReportHook(WindowsCrtReportHook);
#endif
}
#ifdef Q_OS_WIN
if (runUnitTests) {
// Don't pop up Windows Error Reporting dialog when app crashes. This prevents TeamCity from
// hanging.
DWORD dwMode = SetErrorMode(SEM_NOGPFAULTERRORBOX);
SetErrorMode(dwMode | SEM_NOGPFAULTERRORBOX);
}
#endif
#endif // QT_DEBUG
QGCApplication* app = new QGCApplication(argc, argv, runUnitTests);
Q_CHECK_PTR(app);
// There appears to be a threading issue in qRegisterMetaType which can cause it to throw a qWarning
// about duplicate type converters. This is caused by a race condition in the Qt code. Still working
// with them on tracking down the bug. For now we register the type which is giving us problems here
// while we only have the main thread. That should prevent it from hitting the race condition later
// on in the code.
qRegisterMetaType<QList<QPair<QByteArray,QByteArray> > >();
app->_initCommon();
int exitCode = 0;
#ifndef __mobile__
#ifdef QT_DEBUG
if (runUnitTests) {
for (int i=0; i < (stressUnitTests ? 20 : 1); i++) {
if (!app->_initForUnitTests()) {
return -1;
}
// Run the test
int failures = UnitTest::run(unitTestOptions);
if (failures == 0) {
qDebug() << "ALL TESTS PASSED";
exitCode = 0;
} else {
qDebug() << failures << " TESTS FAILED!";
exitCode = -failures;
break;
}
}
} else
#endif
#endif
{
if (!app->_initForNormalAppBoot()) {
return -1;
}
exitCode = app->exec();
}
delete app;
qDebug() << "After app delete";
return exitCode;
}
<commit_msg>Fix compiler warning<commit_after>/*=====================================================================
QGroundControl Open Source Ground Control Station
(c) 2009 - 2011 QGROUNDCONTROL PROJECT <http://www.qgroundcontrol.org>
This file is part of the QGROUNDCONTROL project
QGROUNDCONTROL 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.
QGROUNDCONTROL 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 QGROUNDCONTROL. If not, see <http://www.gnu.org/licenses/>.
======================================================================*/
/**
* @file
* @brief Main executable
* @author Lorenz Meier <mavteam@student.ethz.ch>
*
*/
#include <QtGlobal>
#include <QApplication>
#include <QSslSocket>
#include <QProcessEnvironment>
#ifndef __mobile__
#include <QSerialPortInfo>
#endif
#include "QGCApplication.h"
#include "MainWindow.h"
#ifdef QT_DEBUG
#ifndef __mobile__
#include "UnitTest.h"
#endif
#include "CmdLineOptParser.h"
#ifdef Q_OS_WIN
#include <crtdbg.h>
#endif
#endif
#include <iostream>
/* SDL does ugly things to main() */
#ifdef main
#undef main
#endif
#ifndef __mobile__
Q_DECLARE_METATYPE(QSerialPortInfo)
#endif
#ifdef Q_OS_WIN
/// @brief Message handler which is installed using qInstallMsgHandler so you do not need
/// the MSFT debug tools installed to see qDebug(), qWarning(), qCritical and qAbort
void msgHandler(QtMsgType type, const QMessageLogContext &context, const QString &msg)
{
const char symbols[] = { 'I', 'E', '!', 'X' };
QString output = QString("[%1] at %2:%3 - \"%4\"").arg(symbols[type]).arg(context.file).arg(context.line).arg(msg);
std::cerr << output.toStdString() << std::endl;
if( type == QtFatalMsg ) abort();
}
/// @brief CRT Report Hook installed using _CrtSetReportHook. We install this hook when
/// we don't want asserts to pop a dialog on windows.
int WindowsCrtReportHook(int reportType, char* message, int* returnValue)
{
Q_UNUSED(reportType);
std::cerr << message << std::endl; // Output message to stderr
*returnValue = 0; // Don't break into debugger
return true; // We handled this fully ourselves
}
#endif
#ifdef __android__
#include <jni.h>
#include "qserialport.h"
jint JNI_OnLoad(JavaVM* vm, void* reserved)
{
Q_UNUSED(reserved);
JNIEnv* env;
if (vm->GetEnv(reinterpret_cast<void**>(&env), JNI_VERSION_1_6) != JNI_OK) {
return -1;
}
QSerialPort::setNativeMethods();
return JNI_VERSION_1_6;
}
#endif
/**
* @brief Starts the application
*
* @param argc Number of commandline arguments
* @param argv Commandline arguments
* @return exit code, 0 for normal exit and !=0 for error cases
*/
int main(int argc, char *argv[])
{
#ifdef Q_OS_MAC
#ifndef __ios__
// Prevent Apple's app nap from screwing us over
// tip: the domain can be cross-checked on the command line with <defaults domains>
QProcess::execute("defaults write org.qgroundcontrol.qgroundcontrol NSAppSleepDisabled -bool YES");
#endif
#endif
// install the message handler
#ifdef Q_OS_WIN
qInstallMessageHandler(msgHandler);
#endif
// The following calls to qRegisterMetaType are done to silence debug output which warns
// that we use these types in signals, and without calling qRegisterMetaType we can't queue
// these signals. In general we don't queue these signals, but we do what the warning says
// anyway to silence the debug output.
#ifndef __ios__
qRegisterMetaType<QSerialPort::SerialPortError>();
#endif
qRegisterMetaType<QAbstractSocket::SocketError>();
#ifndef __mobile__
qRegisterMetaType<QSerialPortInfo>();
#endif
// We statically link to the google QtLocation plugin
#ifdef Q_OS_WIN
// In Windows, the compiler doesn't see the use of the class created by Q_IMPORT_PLUGIN
#pragma warning( disable : 4930 4101 )
#endif
Q_IMPORT_PLUGIN(QGeoServiceProviderFactoryQGC)
bool runUnitTests = false; // Run unit tests
#ifdef QT_DEBUG
// We parse a small set of command line options here prior to QGCApplication in order to handle the ones
// which need to be handled before a QApplication object is started.
bool stressUnitTests = false; // Stress test unit tests
bool quietWindowsAsserts = false; // Don't let asserts pop dialog boxes
QString unitTestOptions;
CmdLineOpt_t rgCmdLineOptions[] = {
{ "--unittest", &runUnitTests, &unitTestOptions },
{ "--unittest-stress", &stressUnitTests, &unitTestOptions },
{ "--no-windows-assert-ui", &quietWindowsAsserts, NULL },
// Add additional command line option flags here
};
ParseCmdLineOptions(argc, argv, rgCmdLineOptions, sizeof(rgCmdLineOptions)/sizeof(rgCmdLineOptions[0]), false);
if (stressUnitTests) {
runUnitTests = true;
}
if (quietWindowsAsserts) {
#ifdef Q_OS_WIN
_CrtSetReportHook(WindowsCrtReportHook);
#endif
}
#ifdef Q_OS_WIN
if (runUnitTests) {
// Don't pop up Windows Error Reporting dialog when app crashes. This prevents TeamCity from
// hanging.
DWORD dwMode = SetErrorMode(SEM_NOGPFAULTERRORBOX);
SetErrorMode(dwMode | SEM_NOGPFAULTERRORBOX);
}
#endif
#endif // QT_DEBUG
QGCApplication* app = new QGCApplication(argc, argv, runUnitTests);
Q_CHECK_PTR(app);
// There appears to be a threading issue in qRegisterMetaType which can cause it to throw a qWarning
// about duplicate type converters. This is caused by a race condition in the Qt code. Still working
// with them on tracking down the bug. For now we register the type which is giving us problems here
// while we only have the main thread. That should prevent it from hitting the race condition later
// on in the code.
qRegisterMetaType<QList<QPair<QByteArray,QByteArray> > >();
app->_initCommon();
int exitCode = 0;
#ifndef __mobile__
#ifdef QT_DEBUG
if (runUnitTests) {
for (int i=0; i < (stressUnitTests ? 20 : 1); i++) {
if (!app->_initForUnitTests()) {
return -1;
}
// Run the test
int failures = UnitTest::run(unitTestOptions);
if (failures == 0) {
qDebug() << "ALL TESTS PASSED";
exitCode = 0;
} else {
qDebug() << failures << " TESTS FAILED!";
exitCode = -failures;
break;
}
}
} else
#endif
#endif
{
if (!app->_initForNormalAppBoot()) {
return -1;
}
exitCode = app->exec();
}
delete app;
qDebug() << "After app delete";
return exitCode;
}
<|endoftext|> |
<commit_before>#include <QApplication>
#include "mainwindow.h"
int main(int argc, char *argv[])
{
QApplication app(argc, argv);
// Retina display support for Mac OS, iOS and X11:
// http://blog.qt.digia.com/blog/2013/04/25/retina-display-support-for-mac-os-ios-and-x11/
//
// AA_UseHighDpiPixmaps attribute is off by default in Qt 5.1 but will most
// likely be on by default in a future release of Qt.
app.setAttribute(Qt::AA_UseHighDpiPixmaps);
QIcon appIcon;
appIcon.addFile(":/Icons/AppIcon32");
appIcon.addFile(":/Icons/AppIcon128");
app.setWindowIcon(appIcon);
MainWindow mainWindow;
mainWindow.show();
return app.exec();
}
<commit_msg>Fix a broken link<commit_after>#include <QApplication>
#include "mainwindow.h"
int main(int argc, char *argv[])
{
QApplication app(argc, argv);
// Retina display support for Mac OS, iOS and X11:
// http://blog.qt.io/blog/2013/04/25/retina-display-support-for-mac-os-ios-and-x11/
//
// AA_UseHighDpiPixmaps attribute is off by default in Qt 5.1 but will most
// likely be on by default in a future release of Qt.
app.setAttribute(Qt::AA_UseHighDpiPixmaps);
QIcon appIcon;
appIcon.addFile(":/Icons/AppIcon32");
appIcon.addFile(":/Icons/AppIcon128");
app.setWindowIcon(appIcon);
MainWindow mainWindow;
mainWindow.show();
return app.exec();
}
<|endoftext|> |
<commit_before>
#include <ugdk/system/engine.h>
#include <ugdk/action/3D/camera.h>
#include <ugdk/input/events.h>
#include <ugdk/input/module.h>
#include <ugdk/action/3D/element.h>
#include <ugdk/action/3D/scene3d.h>
#include <ugdk/action/3D/physics.h>
#include <ugdk/action/3D/component/physicsbody.h>
#include <ugdk/action/3D/component/view.h>
#include <BtOgreGP.h>
#include <memory>
#include <iostream>
#include <OgreCamera.h>
#include <OgreEntity.h>
#include <OgreLogManager.h>
#include <OgreRoot.h>
#include <OgreViewport.h>
#include <OgreSceneManager.h>
#include <OgreRenderWindow.h>
#include <OgreConfigFile.h>
#include <OgreMeshManager.h>
#define AREA_RANGE 200.0
using std::weak_ptr;
using std::shared_ptr;
using std::unique_ptr;
using std::make_shared;
using std::cout;
using std::endl;
using ugdk::action::mode3d::Element;
using ugdk::action::mode3d::component::PhysicsBody;
using ugdk::action::mode3d::component::Body;
using ugdk::action::mode3d::component::View;
using ugdk::action::mode3d::component::CollisionAction;
using ugdk::action::mode3d::component::ElementPtr;
using ugdk::action::mode3d::component::ContactPointVector;
namespace {
ugdk::action::mode3d::Scene3D *ourscene;
struct {
double angle;
} player;
} // unnamed namespace
#define BIT(x) (1<<(x))
enum CollisionGroup {
HEADS = BIT(6),
WALLS = BIT(7),
WAT2 = BIT(8),
WAT3 = BIT(9),
WAT4 = BIT(10)
};
shared_ptr<Element> createOgreHead(const std::string& name, bool useBox=false) {
Ogre::SceneManager *mSceneMgr = ourscene->manager();
// Element
auto head = ourscene->AddElement();
// View
auto headEnt = mSceneMgr->createEntity(name, "Mage.mesh");
head->AddComponent(make_shared<View>());
head->component<View>()->AddEntity(headEnt);
// Body
PhysicsBody::PhysicsData headData;
auto meshShapeConv = BtOgre::StaticMeshToShapeConverter(headEnt);
if (useBox)
headData.shape = meshShapeConv.createBox();
else
headData.shape = meshShapeConv.createSphere();
headData.mass = 80;
headData.collision_group = CollisionGroup::HEADS;
headData.collides_with = CollisionGroup::WALLS | CollisionGroup::HEADS;
headData.apply_orientation = false;
head->AddComponent(make_shared<PhysicsBody>(*ourscene->physics(), headData));
head->component<Body>()->set_damping(.8, .8);
return head;
}
shared_ptr<Element> createWall(const std::string& name, const Ogre::Vector3& dir, double dist, double width = AREA_RANGE, double height = AREA_RANGE) {
Ogre::SceneManager *mSceneMgr = ourscene->manager();
// Element
auto wall = ourscene->AddElement();
// View
Ogre::Plane plane(dir, dist);
auto mesh_ptr = Ogre::MeshManager::getSingleton().createPlane(name, Ogre::ResourceGroupManager::DEFAULT_RESOURCE_GROUP_NAME,
plane, width, height, 5, 5, true, 1, 5, 5, dir.perpendicular());
const std::string wat = name + "Entity";
Ogre::Entity* wallEnt = mSceneMgr->createEntity(wat, mesh_ptr);
wallEnt->setMaterialName("Ogre/Tusks");
wall->AddComponent(make_shared<View>());
wall->component<View>()->AddEntity(wallEnt);
// Body
PhysicsBody::PhysicsData wallData;
wallData.shape = new btStaticPlaneShape(btVector3(dir.x, dir.y, dir.z), dist);
wallData.mass = 0;
wallData.collision_group = CollisionGroup::WALLS;
wallData.collides_with = CollisionGroup::HEADS;
wall->AddComponent(make_shared<PhysicsBody>(*ourscene->physics(), wallData));
wall->component<Body>()->set_friction(20);
return wall;
}
int main(int argc, char* argv[]) {
using Ogre::Vector3;
ugdk::system::Configuration config;
config.base_path = "assets/";
ugdk::system::Initialize(config);
ourscene = new ugdk::action::mode3d::Scene3D(btVector3(0.0, -10.0, 0.0));
ourscene->physics()->set_debug_draw_enabled(true);
ourscene->ShowFrameStats();
{
player.angle = 0.0;
weak_ptr<Element> head1 = createOgreHead("Head");
weak_ptr<Element> head2 = createOgreHead("Head2", true);
auto body2 = head2.lock()->component<Body>();
body2->Translate(0, 0, 80);
body2->set_angular_factor(0.0, 0.0, 0.0);
body2->AddCollisionAction(CollisionGroup::HEADS,
[](const ElementPtr& self, const ElementPtr& target, const ContactPointVector& pts) {
cout << "CARAS COLIDINDO MANO (" << pts.size() << ")" << endl;
});
weak_ptr<Element> wall = createWall("ground", Vector3::UNIT_Y, -5.0);
ourscene->camera()->AttachTo(*head2.lock());
ourscene->camera()->SetParameters(Vector3::UNIT_Y*10.0, 5000.0);
ourscene->camera()->SetDistance(80.0);
ourscene->camera()->Rotate(0.0, Ogre::Degree(20.0).valueDegrees());
ourscene->AddTask(ugdk::system::Task(
[head2, body2](double dt) {
auto& keyboard = ugdk::input::manager()->keyboard();
Vector3 move = Vector3::ZERO;
if (keyboard.IsDown(ugdk::input::Scancode::RIGHT))
player.angle -= dt*135.0;
else if (keyboard.IsDown(ugdk::input::Scancode::LEFT))
player.angle += dt*135.0;
if (keyboard.IsDown(ugdk::input::Scancode::UP))
move.z += 1.0;
else if (keyboard.IsDown(ugdk::input::Scancode::DOWN))
move.z += -1.0;
Ogre::Quaternion rot(Ogre::Degree(player.angle), Vector3::UNIT_Y);
move.normalise();
move = rot * move;
move.y = 0.0;
move.normalise();
body2->ApplyImpulse(move * 200);
Ogre::SceneNode &node = head2.lock()->node();
node.setOrientation(rot);
}));
ourscene->event_handler().AddListener<ugdk::input::KeyPressedEvent>(
[] (const ugdk::input::KeyPressedEvent& ev) -> void {
if (ev.scancode == ugdk::input::Scancode::ESCAPE)
ourscene->Finish();
});
//ourscene->event_handler().AddListener<ugdk::input::MouseMotionEvent>(
// [] (const ugdk::input::MouseMotionEvent& ev) -> void {
// ourscene->camera()->Rotate(-ev.motion.x, ev.motion.y);
// });
ourscene->manager()->setAmbientLight(Ogre::ColourValue(.7, .7, .7));
ugdk::system::PushScene(unique_ptr<ugdk::action::Scene>(ourscene));
}
ugdk::system::Run();
ugdk::system::Release();
return 0;
}
<commit_msg>Jumps!<commit_after>
#include <ugdk/system/engine.h>
#include <ugdk/action/3D/camera.h>
#include <ugdk/input/events.h>
#include <ugdk/input/module.h>
#include <ugdk/action/3D/element.h>
#include <ugdk/action/3D/scene3d.h>
#include <ugdk/action/3D/physics.h>
#include <ugdk/action/3D/component/physicsbody.h>
#include <ugdk/action/3D/component/view.h>
#include <BtOgreGP.h>
#include <memory>
#include <iostream>
#include <OgreCamera.h>
#include <OgreEntity.h>
#include <OgreLogManager.h>
#include <OgreRoot.h>
#include <OgreViewport.h>
#include <OgreSceneManager.h>
#include <OgreRenderWindow.h>
#include <OgreConfigFile.h>
#include <OgreMeshManager.h>
#define AREA_RANGE 200.0
using std::weak_ptr;
using std::shared_ptr;
using std::unique_ptr;
using std::make_shared;
using std::cout;
using std::endl;
using ugdk::action::mode3d::Element;
using ugdk::action::mode3d::component::PhysicsBody;
using ugdk::action::mode3d::component::Body;
using ugdk::action::mode3d::component::View;
using ugdk::action::mode3d::component::CollisionAction;
using ugdk::action::mode3d::component::ElementPtr;
using ugdk::action::mode3d::component::ContactPointVector;
namespace {
ugdk::action::mode3d::Scene3D *ourscene;
struct {
double angle;
} player;
} // unnamed namespace
#define BIT(x) (1<<(x))
enum CollisionGroup {
HEADS = BIT(6),
WALLS = BIT(7),
WAT2 = BIT(8),
WAT3 = BIT(9),
WAT4 = BIT(10)
};
shared_ptr<Element> createOgreHead(const std::string& name, bool useBox=false) {
Ogre::SceneManager *mSceneMgr = ourscene->manager();
// Element
auto head = ourscene->AddElement();
// View
auto headEnt = mSceneMgr->createEntity(name, "Mage.mesh");
head->AddComponent(make_shared<View>());
head->component<View>()->AddEntity(headEnt);
// Body
PhysicsBody::PhysicsData headData;
auto meshShapeConv = BtOgre::StaticMeshToShapeConverter(headEnt);
if (useBox)
headData.shape = meshShapeConv.createBox();
else
headData.shape = meshShapeConv.createSphere();
headData.mass = 80;
headData.collision_group = CollisionGroup::HEADS;
headData.collides_with = CollisionGroup::WALLS | CollisionGroup::HEADS;
headData.apply_orientation = false;
head->AddComponent(make_shared<PhysicsBody>(*ourscene->physics(), headData));
//head->component<Body>()->set_damping(.4, .4);
return head;
}
shared_ptr<Element> createWall(const std::string& name, const Ogre::Vector3& dir, double dist,
double width = AREA_RANGE, double height = AREA_RANGE) {
Ogre::SceneManager *mSceneMgr = ourscene->manager();
// Element
auto wall = ourscene->AddElement();
// View
Ogre::Plane plane(dir, dist);
auto mesh_ptr = Ogre::MeshManager::getSingleton()
.createPlane(name, Ogre::ResourceGroupManager::DEFAULT_RESOURCE_GROUP_NAME,
plane, width, height, 5, 5, true, 1, 5, 5, dir.perpendicular());
const std::string wat = name + "Entity";
Ogre::Entity* wallEnt = mSceneMgr->createEntity(wat, mesh_ptr);
wallEnt->setMaterialName("Ogre/Tusks");
wall->AddComponent(make_shared<View>());
wall->component<View>()->AddEntity(wallEnt);
// Body
PhysicsBody::PhysicsData wallData;
wallData.shape = new btStaticPlaneShape(btVector3(dir.x, dir.y, dir.z), dist);
wallData.mass = 0;
wallData.collision_group = CollisionGroup::WALLS;
wallData.collides_with = CollisionGroup::HEADS;
wall->AddComponent(make_shared<PhysicsBody>(*ourscene->physics(), wallData));
//wall->component<Body>()->set_friction(30);
return wall;
}
int main(int argc, char* argv[]) {
using Ogre::Vector3;
ugdk::system::Configuration config;
config.base_path = "assets/";
ugdk::system::Initialize(config);
ourscene = new ugdk::action::mode3d::Scene3D(btVector3(0.0, -10.0, 0.0));
ourscene->physics()->set_debug_draw_enabled(true);
ourscene->ShowFrameStats();
{
player.angle = 0.0;
weak_ptr<Element> head1 = createOgreHead("Head");
weak_ptr<Element> head2 = createOgreHead("Head2", true);
auto body2 = head2.lock()->component<Body>();
body2->Translate(0, 0, 80);
body2->set_angular_factor(0.0, 0.0, 0.0);
body2->AddCollisionAction(CollisionGroup::HEADS,
[](const ElementPtr& self, const ElementPtr& target, const ContactPointVector& pts) {
cout << "CARAS COLIDINDO MANO (" << pts.size() << ")" << endl;
});
weak_ptr<Element> wall = createWall("ground", Vector3::UNIT_Y, -5.0);
ourscene->camera()->AttachTo(*head2.lock());
ourscene->camera()->SetParameters(Vector3::UNIT_Y*2.0, 5000.0);
ourscene->camera()->SetDistance(10.0);
ourscene->camera()->Rotate(0.0, Ogre::Degree(20.0).valueDegrees());
ourscene->AddTask(ugdk::system::Task(
[head2, body2](double dt) {
auto& keyboard = ugdk::input::manager()->keyboard();
Vector3 move = Vector3::ZERO;
if (keyboard.IsDown(ugdk::input::Scancode::RIGHT))
player.angle -= dt*135.0;
else if (keyboard.IsDown(ugdk::input::Scancode::LEFT))
player.angle += dt*135.0;
if (keyboard.IsDown(ugdk::input::Scancode::UP))
move.z += 1.0;
else if (keyboard.IsDown(ugdk::input::Scancode::DOWN))
move.z += -1.0;
Ogre::Quaternion rot(Ogre::Degree(player.angle), Vector3::UNIT_Y);
move.normalise();
move = rot * move;
move.y = 0.0;
move.normalise();
//body2->ApplyImpulse(move * 200);
body2->Translate(move * dt * 5);
Ogre::SceneNode &node = head2.lock()->node();
node.setOrientation(rot);
}));
ourscene->event_handler().AddListener<ugdk::input::KeyPressedEvent>(
[body2] (const ugdk::input::KeyPressedEvent& ev) -> void {
if (ev.scancode == ugdk::input::Scancode::ESCAPE)
ourscene->Finish();
else if (ev.scancode == ugdk::input::Scancode::A)
body2->ApplyImpulse(Vector3::UNIT_Y * 500.0);
});
//ourscene->event_handler().AddListener<ugdk::input::MouseMotionEvent>(
// [] (const ugdk::input::MouseMotionEvent& ev) -> void {
// ourscene->camera()->Rotate(-ev.motion.x, ev.motion.y);
// });
ourscene->manager()->setAmbientLight(Ogre::ColourValue(.7, .7, .7));
ugdk::system::PushScene(unique_ptr<ugdk::action::Scene>(ourscene));
}
ugdk::system::Run();
ugdk::system::Release();
return 0;
}
<|endoftext|> |
<commit_before>/*
* Copyright (C) 2011, Paul Tagliamonte <paultag@fluxbox.org>
*
* 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 <string>
#include <string.h>
#include <iostream>
#include <fstream>
#include <cstdlib>
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include "exceptions.hh"
#include "main.hh"
#include "state.hh"
#include "entry.hh"
#include "machine.hh"
#include "xdg_spec.hh"
#include "xdg_parse.hh"
#include "xdg_model.hh"
#include "xdg_autostart.hh"
bool noexec = false;
/**
* Run a given command (as if we were invoking from a shell)
*
* This will fork and run the `appl` command in either $SHELL (if set), or
* /bin/sh if $SHELL is unset. This will fork to the background and return
* control very quickly. Don't use this to do a blocking read on a process
* or something.
*
* @param appl application to run
* @return 0 (for the parent fork, which should be what you get), pid for child.
*/
int run_command( std::string appl ) {
if ( appl == "" )
return 0;
pid_t pid = fork();
if (pid)
return pid;
std::string shell = getenv("SHELL");
if ( shell != "" )
shell = "/bin/sh";
if ( ! noexec ) { // we'll do it live
execl(
shell.c_str(),
shell.c_str(),
"-c",
appl.c_str(),
static_cast<void*>(NULL)
);
exit ( EXIT_SUCCESS );
return pid;
} else {
std::cout << " Would have run: " << appl << std::endl;
exit(0);
return 0;
}
}
/**
* pre exec routines, such as setup, setting the internal state and checks
*
* all of these should be safe to run more then once, and it should *always*
* be run before allowing a stateful parse to happen.
*
* It'll also print out a fairly useful block of text to aid with debugging
* problems down the road.
*/
void pre_exec() {
const char * home = getenv("XDG_CONFIG_HOME");
const char * dirs = getenv("XDG_CONFIG_DIRS");
const char * userhome = getenv("HOME");
const char * desktopenv = getenv("FBXDG_DE");
const char * execmodel = getenv("FBXDG_EXEC");
/* TABLE OF ENV VARS
*
* +------------------+----------------------------+
* | XDG_CONFIG_HOME | XDG Local dir (~/.config) |
* | XDG_CONFIG_DIRS | XDG Global dir (/etc/xdg) |
* | HOME | User home (/home/tag) |
* | FBXDG_DE | Who to act on behalf of |
* | FBXDG_EXEC | 0 for exec, 1 for noexec |
* +------------------+----------------------------+
*
*/
const char * blank = ""; /* -Waddress errrs.
( to avoid using strcmp, which we actually
do use later, so XXX: Fixme ) */
home = home == NULL ? blank : home;
dirs = dirs == NULL ? blank : dirs;
desktopenv = desktopenv == NULL ? blank : desktopenv;
execmodel = execmodel == NULL ? blank : execmodel;
/*
* If we're null, set to "" rather then keep NULL.
*/
_xdg_default_global = dirs == blank ? _xdg_default_global : dirs;
_xdg_default_local = home == blank ? _xdg_default_local : home;
_xdg_window_manager = desktopenv == blank ? _xdg_window_manager : desktopenv;
/*
* If we have a env var, set them to the global prefs.
*/
if ( strcmp(execmodel,"0") == 0 )
noexec = false;
else if ( strcmp(execmodel,"1") == 0 )
noexec = true;
/*
* Fuck this mess. Someone needs to clean this up to use true/false
* and have it relate in a sane way.
* XXX: Fixme
*/
_xdg_default_global = fix_home_pathing( _xdg_default_global, userhome );
_xdg_default_local = fix_home_pathing( _xdg_default_local, userhome );
/*
* If the luser gives us (or we default to) a path with tlde in it,
* let's expand it to use $HOME to figure out where the real path actually
* is.
*/
std::cout << "" << std::endl;
std::cout << "Hello! I'll be your friendly XDG Autostarter today." << std::endl;
std::cout << "Here's what's on the menu:" << std::endl;
std::cout << "" << std::endl;
std::cout << " Appetizers" << std::endl;
std::cout << "" << std::endl;
std::cout << " * $XDG_CONFIG_HOME: " << home << std::endl;
std::cout << " * $XDG_CONFIG_DIRS: " << dirs << std::endl;
std::cout << " * $FBXDG_DE: " << desktopenv << std::endl;
std::cout << " * $FBXDG_EXEC: " << execmodel << std::endl;
std::cout << "" << std::endl;
std::cout << " Entrées" << std::endl;
std::cout << "" << std::endl;
std::cout << " * Desktop Environment: " << _xdg_window_manager << std::endl;
std::cout << " * Global XDG Directory: " << _xdg_default_global << std::endl;
std::cout << " * Local XDG Directory: " << _xdg_default_local << std::endl;
std::cout << " * Current exec Model: " << noexec << std::endl;
std::cout << "" << std::endl;
std::cout << " - Chef Tagliamonte" << std::endl;
std::cout << " & The Fluxbox Crew" << std::endl;
std::cout << "" << std::endl;
}
/**
* expand tildes to the user's actual home
*
* @param ref string to expand
* @param home path to user's home
* @return either a newly expanded string or the old string
*/
std::string fix_home_pathing( std::string ref, std::string home ) {
// std::cout << "preref: " << ref << std::endl;
if ( ref[0] == '~' && ref[1] == '/' ) {
// std::cout << " +-> confirmed." << std::endl;
ref.replace(0, 1, home );
// std::cout << " +-> postref: " << ref << std::endl;
}
return ref;
}
/**
* XXX: Doc me
*/
void command_line_overrides( int argc, char ** arv ) {
for ( int i = 1; i < argc; ++i ) {
// process argv[i]
}
}
int main ( int argc, char ** argv ) {
pre_exec(); /* pre_exec allows us to read goodies and set up
the env for us. */
xdg_autostart_map binaries; /* the map of what stuff to start
up or ignore or whatever. */
parse_folder( &binaries, _xdg_default_global + "/autostart/" );
parse_folder( &binaries, _xdg_default_local + "/autostart/" );
/* Let's kick off the parse routines on the directories. */
std::cout << "" << std::endl;
std::cout << "Finished parsing all files." << std::endl;
std::cout << "" << std::endl;
for ( xdg_autostart_map::iterator i = binaries.begin();
i != binaries.end(); ++i
) {
std::cout << " Handling stub for: " << i->first << std::endl;
run_command( i->second );
/* foreach command, let's run it :) */
}
}
<commit_msg>Starting to lay groundwork to solve bug #2.<commit_after>/*
* Copyright (C) 2011, Paul Tagliamonte <paultag@fluxbox.org>
*
* 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 <string>
#include <vector>
#include <fstream>
#include <cstdlib>
#include <stdio.h>
#include <string.h>
#include <sstream>
#include <iostream>
#include <stdlib.h>
#include <unistd.h>
#include "exceptions.hh"
#include "main.hh"
#include "state.hh"
#include "entry.hh"
#include "machine.hh"
#include "xdg_spec.hh"
#include "xdg_parse.hh"
#include "xdg_model.hh"
#include "xdg_autostart.hh"
bool noexec = false;
/**
* Run a given command (as if we were invoking from a shell)
*
* This will fork and run the `appl` command in either $SHELL (if set), or
* /bin/sh if $SHELL is unset. This will fork to the background and return
* control very quickly. Don't use this to do a blocking read on a process
* or something.
*
* @param appl application to run
* @return 0 (for the parent fork, which should be what you get), pid for child.
*/
int run_command( std::string appl ) {
if ( appl == "" )
return 0;
pid_t pid = fork();
if (pid)
return pid;
std::string shell = getenv("SHELL");
if ( shell != "" )
shell = "/bin/sh";
if ( ! noexec ) { // we'll do it live
execl(
shell.c_str(),
shell.c_str(),
"-c",
appl.c_str(),
static_cast<void*>(NULL)
);
exit ( EXIT_SUCCESS );
return pid;
} else {
std::cout << " Would have run: " << appl << std::endl;
exit(0);
return 0;
}
}
/**
*
*/
std::vector<std::string> split_path( std::string input ) {
std::vector<std::string> ret;
std::stringstream ss(input);
std::string word;
char delim = ':';
while ( std::getline( ss, word, delim ) ) {
ret.push_back(word);
}
return ret;
}
/**
* pre exec routines, such as setup, setting the internal state and checks
*
* all of these should be safe to run more then once, and it should *always*
* be run before allowing a stateful parse to happen.
*
* It'll also print out a fairly useful block of text to aid with debugging
* problems down the road.
*/
void pre_exec() {
const char * home = getenv("XDG_CONFIG_HOME");
const char * dirs = getenv("XDG_CONFIG_DIRS");
const char * desktopenv = getenv("FBXDG_DE");
const char * execmodel = getenv("FBXDG_EXEC");
/* TABLE OF ENV VARS
*
* +------------------+----------------------------+
* | XDG_CONFIG_HOME | XDG Local dir (~/.config) |
* | XDG_CONFIG_DIRS | XDG Global dir (/etc/xdg) |
* | HOME | User home (/home/tag) |
* | FBXDG_DE | Who to act on behalf of |
* | FBXDG_EXEC | 0 for exec, 1 for noexec |
* +------------------+----------------------------+
*
*/
const char * blank = ""; /* -Waddress errrs.
( to avoid using strcmp, which we actually
do use later, so XXX: Fixme ) */
home = home == NULL ? blank : home;
dirs = dirs == NULL ? blank : dirs;
desktopenv = desktopenv == NULL ? blank : desktopenv;
execmodel = execmodel == NULL ? blank : execmodel;
/*
* If we're null, set to "" rather then keep NULL.
*/
_xdg_default_global = dirs == blank ? _xdg_default_global : dirs;
_xdg_default_local = home == blank ? _xdg_default_local : home;
_xdg_window_manager = desktopenv == blank ? _xdg_window_manager : desktopenv;
/*
* If we have a env var, set them to the global prefs.
*/
if ( strcmp(execmodel,"0") == 0 ) {
noexec = false;
} else if ( strcmp(execmodel,"1") == 0 ) {
noexec = true;
}
/*
* Fuck this mess. Someone needs to clean this up to use true/false
* and have it relate in a sane way.
* XXX: Fixme
*/
std::cout << "" << std::endl;
std::cout << "Hello! I'll be your friendly XDG Autostarter today." << std::endl;
std::cout << "Here's what's on the menu:" << std::endl;
std::cout << "" << std::endl;
std::cout << " Appetizers" << std::endl;
std::cout << "" << std::endl;
std::cout << " * $XDG_CONFIG_HOME: " << home << std::endl;
std::cout << " * $XDG_CONFIG_DIRS: " << dirs << std::endl;
std::cout << " * $FBXDG_DE: " << desktopenv << std::endl;
std::cout << " * $FBXDG_EXEC: " << execmodel << std::endl;
std::cout << "" << std::endl;
std::cout << " Entrées" << std::endl;
std::cout << "" << std::endl;
std::cout << " * Desktop Environment: " << _xdg_window_manager << std::endl;
std::cout << " * Global XDG Directory: " << _xdg_default_global << std::endl;
std::cout << " * Local XDG Directory: " << _xdg_default_local << std::endl;
std::cout << " * Current exec Model: " << noexec << std::endl;
std::cout << "" << std::endl;
std::cout << " - Chef Tagliamonte" << std::endl;
std::cout << " & The Fluxbox Crew" << std::endl;
std::cout << "" << std::endl;
}
/**
* expand tildes to the user's actual home
*
* @param ref string to expand
* @param home path to user's home
* @return either a newly expanded string or the old string
*/
std::string fix_home_pathing( std::string ref, std::string home ) {
// std::cout << "preref: " << ref << std::endl;
if ( ref[0] == '~' && ref[1] == '/' ) {
// std::cout << " +-> confirmed." << std::endl;
ref.replace(0, 1, home );
// std::cout << " +-> postref: " << ref << std::endl;
}
return ref;
}
/**
* XXX: Doc me
*/
void command_line_overrides( int argc, char ** arv ) {
for ( int i = 1; i < argc; ++i ) {
// process argv[i]
}
}
int main ( int argc, char ** argv ) {
const char * userhome = getenv("HOME");
pre_exec(); /* pre_exec allows us to read goodies and set up
the env for us. */
xdg_autostart_map binaries; /* the map of what stuff to start
up or ignore or whatever. */
std::vector<std::string> global = split_path(_xdg_default_global);
std::vector<std::string> local = split_path(_xdg_default_local);
for ( unsigned int i = 0; i < global.size(); ++i ) {
std::string path = fix_home_pathing(global.at(i), userhome);
parse_folder( &binaries, path + "/autostart/" );
}
for ( unsigned int i = 0; i < local.size(); ++i ) {
std::string path = fix_home_pathing(local.at(i), userhome);
parse_folder( &binaries, path + "/autostart/" );
}
std::cout << "" << std::endl;
std::cout << "Finished parsing all files." << std::endl;
std::cout << "" << std::endl;
for ( xdg_autostart_map::iterator i = binaries.begin();
i != binaries.end(); ++i
) {
std::cout << " Handling stub for: " << i->first << std::endl;
run_command( i->second );
/* foreach command, let's run it :) */
}
}
<|endoftext|> |
<commit_before><commit_msg>ATO-453- bug fix in coding q (spotted by Andreas Morsch) (#1090)<commit_after><|endoftext|> |
<commit_before>/**
* @file main.cpp
*
* @author <a href="mailto:xu@informatik.hu-berlin.de">Xu, Yuan</a>
* @author <a href="mailto:mellmann@informatik.hu-berlin.de">Mellmann, Heinrich</a>
*/
#include "NaoController.h"
#include <glib.h>
#include <glib-object.h>
#include <signal.h>
//#include <rttools/rtthread.h>
using namespace naoth;
void got_signal(int t)
{
if(t == SIGTERM) {
std::cout << "shutdown requested by kill signal" << t << std::endl;
} else if(t == SIGSEGV) {
std::cerr << "SEGMENTATION FAULT" << std::endl;
} else {
std::cerr << "catched unknown signal " << t << std::endl;
}
std::cout << "dumping traces" << std::endl;
Trace::getInstance().dump();
StopwatchManager::getInstance().dump("cognition");
std::cout << "syncing file system..." ;
sync();
std::cout << " finished." << std::endl;
exit(0);
}//end got_signal
// a semaphore for sychronization with the DCM
sem_t* dcm_sem = SEM_FAILED;
/*
// Just some experiments with the RT-Threads
// not used yet
class TestThread : public RtThread
{
public:
TestThread(){}
~TestThread(){}
NaoController* theController;
virtual void *execute()
{
Stopwatch stopwatch;
while(true)
{
theController->callMotion();
if(sem_wait(dcm_sem) == -1)
{
cerr << "lock errno: " << errno << endl;
}
StopwatchManager::getInstance().notifyStop(stopwatch);
StopwatchManager::getInstance().notifyStart(stopwatch);
PLOT("_MotionCycle", stopwatch.lastValue);
}//end while
return NULL;
}
virtual void postExecute(){}
virtual void preExecute(){}
} motionRtThread;
*/
void* cognitionThreadCallback(void* ref)
{
NaoController* theController = static_cast<NaoController*> (ref);
while(true) {
theController->runCognition();
g_thread_yield();
}
return NULL;
}//end cognitionThreadCallback
void* motionThreadCallback(void* ref)
{
NaoController* theController = static_cast<NaoController*> (ref);
Stopwatch stopwatch;
while(true)
{
theController->runMotion();
if(sem_wait(dcm_sem) == -1) {
cerr << "lock errno: " << errno << endl;
}
stopwatch.stop();
stopwatch.start();
}//end while
return NULL;
}//end motionThreadCallback
#define TO_STRING_INT(x) #x
#define TO_STRING(x) TO_STRING_INT(x)
int main(int argc, char *argv[])
{
std::cout << "==========================================" << std::endl;
std::cout << "NaoTH compiled on: " << __DATE__ << " at " << __TIME__ << std::endl;
#ifdef REVISION
std::cout << "Revision number: " << TO_STRING(REVISION) << std::endl;
#endif
#ifdef USER_NAME
std::cout << "Owner: " << TO_STRING(USER_NAME) << std::endl;
#endif
#ifdef BRANCH_PATH
std::cout << "Branch path: " << TO_STRING(BRANCH_PATH) << std::endl;
#endif
std::cout << "==========================================\n" << std::endl;
// init glib
g_type_init();
if (!g_thread_supported())
g_thread_init(NULL);
// react on "kill" and segmentation fault
struct sigaction saKill;
memset( &saKill, 0, sizeof(saKill) );
saKill.sa_handler = got_signal;
sigfillset(&saKill.sa_mask);
sigaction(SIGTERM,&saKill,NULL);
struct sigaction saSeg;
memset( &saSeg, 0, sizeof(saSeg) );
saSeg.sa_handler = got_signal;
sigfillset(&saSeg.sa_mask);
sigaction(SIGSEGV,&saSeg,NULL);
int retChDir = chdir("/home/nao");
if(retChDir != 0)
{
std::cerr << "Could not change working directory" << std::endl;
}
// O_CREAT - create a new semaphore if not existing
// open semaphore
if((dcm_sem = sem_open("motion_trigger", O_CREAT | O_RDWR, S_IRUSR | S_IWUSR, 0)) == SEM_FAILED)
{
perror("NaoController: sem_open");
exit(-1);
}
// create the controller
NaoController theController;
naoth::init_agent(theController);
// waiting for the first rise of the semaphore
// bevore starting the threads
sem_wait(dcm_sem);
// create the motion thread
// !!we use here a pthread directly, because glib doesn't support priorities
pthread_t motionThread;
pthread_create(&motionThread, 0, motionThreadCallback, (void*)&theController);
// set the pririty of the motion thread to 50
sched_param param;
param.sched_priority = 50;
pthread_setschedparam(motionThread, SCHED_FIFO, ¶m);
/*
GThread* motionThread = g_thread_create(motionThreadCallback, &theController, true, &err);
if(err)
{
g_warning("Could not create motion thread: %s", err->message);
}
g_thread_set_priority(motionThread, G_THREAD_PRIORITY_HIGH);
*/
GError* err = NULL;
GThread* cognitionThread = g_thread_create(cognitionThreadCallback, (void*)&theController, true, &err);
if(err)
{
g_warning("Could not create cognition thread: %s", err->message);
}
//if(motionThread != NULL)
{
pthread_join(motionThread, NULL);
//g_thread_join(motionThread);
}
if(cognitionThread != NULL)
{
g_thread_join(cognitionThread);
}
return 0;
}//end main
<commit_msg>add atomic integer based watchdog for cognition in DCM controller<commit_after>/**
* @file main.cpp
*
* @author <a href="mailto:xu@informatik.hu-berlin.de">Xu, Yuan</a>
* @author <a href="mailto:mellmann@informatik.hu-berlin.de">Mellmann, Heinrich</a>
*/
#include "NaoController.h"
#include <glib.h>
#include <glib-object.h>
#include <signal.h>
//#include <rttools/rtthread.h>
using namespace naoth;
gint framesSinceCognitionLastSeen;
void got_signal(int t)
{
if(t == SIGTERM) {
std::cout << "shutdown requested by kill signal" << t << std::endl;
} else if(t == SIGSEGV) {
std::cerr << "SEGMENTATION FAULT" << std::endl;
} else {
std::cerr << "catched unknown signal " << t << std::endl;
}
std::cout << "dumping traces" << std::endl;
Trace::getInstance().dump();
StopwatchManager::getInstance().dump("cognition");
std::cout << "syncing file system..." ;
sync();
std::cout << " finished." << std::endl;
exit(0);
}//end got_signal
// a semaphore for sychronization with the DCM
sem_t* dcm_sem = SEM_FAILED;
/*
// Just some experiments with the RT-Threads
// not used yet
class TestThread : public RtThread
{
public:
TestThread(){}
~TestThread(){}
NaoController* theController;
virtual void *execute()
{
Stopwatch stopwatch;
while(true)
{
theController->callMotion();
if(sem_wait(dcm_sem) == -1)
{
cerr << "lock errno: " << errno << endl;
}
StopwatchManager::getInstance().notifyStop(stopwatch);
StopwatchManager::getInstance().notifyStart(stopwatch);
PLOT("_MotionCycle", stopwatch.lastValue);
}//end while
return NULL;
}
virtual void postExecute(){}
virtual void preExecute(){}
} motionRtThread;
*/
void* cognitionThreadCallback(void* ref)
{
NaoController* theController = static_cast<NaoController*> (ref);
while(true) {
theController->runCognition();
g_atomic_int_set(&framesSinceCognitionLastSeen, 0);
g_thread_yield();
}
return NULL;
}//end cognitionThreadCallback
void* motionThreadCallback(void* ref)
{
g_atomic_int_set(&framesSinceCognitionLastSeen, 0);
NaoController* theController = static_cast<NaoController*> (ref);
Stopwatch stopwatch;
while(true)
{
if(g_atomic_int_get(&framesSinceCognitionLastSeen) > 1000)
{
std::cerr << "+==================================+" << std::endl;
std::cerr << "| NO MORE MESSAGES FROM COGNITION! |" << std::endl;
std::cerr << "+==================================+" << std::endl;
std::cerr << "dumping traces" << std::endl;
Trace::getInstance().dump();
StopwatchManager::getInstance().dump("cognition");
#ifndef WIN32
std::cerr << "syncing file system..." ;
sync();
std::cerr << " finished." << std::endl;
#endif
ASSERT(false && "Cognition seems to be dead");
}//end if
g_atomic_int_inc(&framesSinceCognitionLastSeen);
theController->runMotion();
if(sem_wait(dcm_sem) == -1) {
cerr << "lock errno: " << errno << endl;
}
stopwatch.stop();
stopwatch.start();
}//end while
return NULL;
}//end motionThreadCallback
#define TO_STRING_INT(x) #x
#define TO_STRING(x) TO_STRING_INT(x)
int main(int argc, char *argv[])
{
std::cout << "==========================================" << std::endl;
std::cout << "NaoTH compiled on: " << __DATE__ << " at " << __TIME__ << std::endl;
#ifdef REVISION
std::cout << "Revision number: " << TO_STRING(REVISION) << std::endl;
#endif
#ifdef USER_NAME
std::cout << "Owner: " << TO_STRING(USER_NAME) << std::endl;
#endif
#ifdef BRANCH_PATH
std::cout << "Branch path: " << TO_STRING(BRANCH_PATH) << std::endl;
#endif
std::cout << "==========================================\n" << std::endl;
// init glib
g_type_init();
if (!g_thread_supported())
g_thread_init(NULL);
// react on "kill" and segmentation fault
struct sigaction saKill;
memset( &saKill, 0, sizeof(saKill) );
saKill.sa_handler = got_signal;
sigfillset(&saKill.sa_mask);
sigaction(SIGTERM,&saKill,NULL);
struct sigaction saSeg;
memset( &saSeg, 0, sizeof(saSeg) );
saSeg.sa_handler = got_signal;
sigfillset(&saSeg.sa_mask);
sigaction(SIGSEGV,&saSeg,NULL);
int retChDir = chdir("/home/nao");
if(retChDir != 0)
{
std::cerr << "Could not change working directory" << std::endl;
}
// O_CREAT - create a new semaphore if not existing
// open semaphore
if((dcm_sem = sem_open("motion_trigger", O_CREAT | O_RDWR, S_IRUSR | S_IWUSR, 0)) == SEM_FAILED)
{
perror("NaoController: sem_open");
exit(-1);
}
// create the controller
NaoController theController;
naoth::init_agent(theController);
// waiting for the first rise of the semaphore
// bevore starting the threads
sem_wait(dcm_sem);
// create the motion thread
// !!we use here a pthread directly, because glib doesn't support priorities
pthread_t motionThread;
pthread_create(&motionThread, 0, motionThreadCallback, (void*)&theController);
// set the pririty of the motion thread to 50
sched_param param;
param.sched_priority = 50;
pthread_setschedparam(motionThread, SCHED_FIFO, ¶m);
/*
GThread* motionThread = g_thread_create(motionThreadCallback, &theController, true, &err);
if(err)
{
g_warning("Could not create motion thread: %s", err->message);
}
g_thread_set_priority(motionThread, G_THREAD_PRIORITY_HIGH);
*/
GError* err = NULL;
GThread* cognitionThread = g_thread_create(cognitionThreadCallback, (void*)&theController, true, &err);
if(err)
{
g_warning("Could not create cognition thread: %s", err->message);
}
//if(motionThread != NULL)
{
pthread_join(motionThread, NULL);
//g_thread_join(motionThread);
}
if(cognitionThread != NULL)
{
g_thread_join(cognitionThread);
}
return 0;
}//end main
<|endoftext|> |
<commit_before>/**
* This file is part of TelepathyQt
*
* @copyright Copyright (C) 2012 Collabora Ltd. <http://www.collabora.co.uk/>
* @license LGPL 2.1
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 2.1 of the License, or (at your option) any later version.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
*/
#include "pending-captchas.h"
#include "captcha-authentication.h"
#include "captcha-authentication-internal.h"
#include "cli-channel.h"
namespace Tp {
class TP_QT_NO_EXPORT CaptchaData : public QSharedData
{
public:
CaptchaData();
CaptchaData(const CaptchaData &other);
~CaptchaData();
QString mimeType;
QString label;
QByteArray captchaData;
CaptchaAuthentication::ChallengeType type;
int id;
};
CaptchaData::CaptchaData()
{
}
CaptchaData::CaptchaData(const CaptchaData &other)
: QSharedData(other),
mimeType(other.mimeType),
label(other.label),
captchaData(other.captchaData),
type(other.type),
id(other.id)
{
}
CaptchaData::~CaptchaData()
{
}
/**
* \class Captcha
* \ingroup client
* \headerfile TelepathyQt/pending-captchas.h <TelepathyQt/PendingCaptchas>
*
* \brief The Captcha class represents a Captcha ready to be answered.
*
* It exposes all the parameters needed for a handler to present the user with a captcha.
*
* Please note this class is meant to be read-only. It is usually created by PendingCaptchas
* once a Captcha request operation succeeds.
*
* Note: this class is implicitly shared
*/
/**
* Default constructor.
*/
Captcha::Captcha()
: mPriv(new CaptchaData)
{
}
/**
* Copy constructor.
*/
Captcha::Captcha(const Captcha &other)
: mPriv(other.mPriv)
{
}
Captcha::Captcha(const QString &mimeType, const QString &label,
const QByteArray &data, CaptchaAuthentication::ChallengeType type, int id)
: mPriv(new CaptchaData)
{
mPriv->mimeType = mimeType;
mPriv->label = label;
mPriv->captchaData = data;
mPriv->type = type;
mPriv->id = id;
}
/**
* Class destructor.
*/
Captcha::~Captcha()
{
}
/**
* Return the mimetype of the captcha.
*
* \return The captcha's mimetype.
* \sa data()
*/
QString Captcha::mimeType() const
{
return mPriv->mimeType;
}
/**
* Return the label of the captcha. For some captcha types, such as
* CaptchaAuthentication::TextQuestionChallenge, the label is also
* the challenge the user has to answer
*
* \return The captcha's label.
* \sa data()
* type()
*/
QString Captcha::label() const
{
return mPriv->label;
}
/**
* Return the raw data of the captcha. The handler can check its type and
* metatype to know how to parse the blob.
*
* \return The captcha's data.
* \sa mimeType(), type()
*/
QByteArray Captcha::data() const
{
return mPriv->captchaData;
}
/**
* Return the type of the captcha.
*
* \return The captcha's type.
* \sa data()
*/
CaptchaAuthentication::ChallengeType Captcha::type() const
{
return mPriv->type;
}
/**
* Return the id of the captcha. This parameter should be used to identify
* the captcha when answering its challenge.
*
* \return The captcha's id.
* \sa CaptchaAuthentication::answer()
*/
int Captcha::id() const
{
return mPriv->id;
}
struct TP_QT_NO_EXPORT PendingCaptchas::Private
{
Private(PendingCaptchas *parent);
~Private();
CaptchaAuthentication::ChallengeType stringToChallengeType(const QString &string) const;
// Public object
PendingCaptchas *parent;
CaptchaAuthentication::ChallengeTypes preferredTypes;
QStringList preferredMimeTypes;
bool multipleRequired;
QList<Captcha> captchas;
int captchasLeft;
CaptchaAuthenticationPtr channel;
};
PendingCaptchas::Private::Private(PendingCaptchas *parent)
: parent(parent)
{
}
PendingCaptchas::Private::~Private()
{
}
CaptchaAuthentication::ChallengeType PendingCaptchas::Private::stringToChallengeType(const QString &string) const
{
if (string == "audio_recog") {
return CaptchaAuthentication::AudioRecognitionChallenge;
} else if (string == "ocr") {
return CaptchaAuthentication::OCRChallenge;
} else if (string == "picture_q") {
return CaptchaAuthentication::PictureQuestionChallenge;
} else if (string == "picture_recog") {
return CaptchaAuthentication::PictureRecognitionChallenge;
} else if (string == "qa") {
return CaptchaAuthentication::TextQuestionChallenge;
} else if (string == "speech_q") {
return CaptchaAuthentication::SpeechQuestionChallenge;
} else if (string == "speech_recog") {
return CaptchaAuthentication::SpeechRecognitionChallenge;
} else if (string == "video_q") {
return CaptchaAuthentication::VideoQuestionChallenge;
} else if (string == "video_recog") {
return CaptchaAuthentication::VideoRecognitionChallenge;
}
// Not really making sense...
return CaptchaAuthentication::UnknownChallenge;
}
/**
* \class PendingCaptchas
* \ingroup client
* \headerfile TelepathyQt/pending-captchas.h <TelepathyQt/PendingCaptchas>
*
* \brief The PendingCaptchas class represents an asynchronous
* operation for retrieving a captcha challenge from a connection manager.
*
* See \ref async_model
*/
PendingCaptchas::PendingCaptchas(
const QDBusPendingCall &call,
const QStringList &preferredMimeTypes,
CaptchaAuthentication::ChallengeTypes preferredTypes,
const CaptchaAuthenticationPtr &channel)
: PendingOperation(channel),
mPriv(new Private(this))
{
mPriv->channel = channel;
mPriv->preferredMimeTypes = preferredMimeTypes;
mPriv->preferredTypes = preferredTypes;
/* keep track of channel invalidation */
connect(channel.data(),
SIGNAL(invalidated(Tp::DBusProxy*,QString,QString)),
SLOT(onChannelInvalidated(Tp::DBusProxy*,QString,QString)));
connect(new QDBusPendingCallWatcher(call),
SIGNAL(finished(QDBusPendingCallWatcher*)),
this,
SLOT(onGetCaptchasWatcherFinished(QDBusPendingCallWatcher*)));
}
PendingCaptchas::PendingCaptchas(
const QString& errorName,
const QString& errorMessage,
const CaptchaAuthenticationPtr &channel)
: PendingOperation(channel),
mPriv(new PendingCaptchas::Private(this))
{
setFinishedWithError(errorName, errorMessage);
}
/**
* Class destructor.
*/
PendingCaptchas::~PendingCaptchas()
{
delete mPriv;
}
void PendingCaptchas::onChannelInvalidated(Tp::DBusProxy *proxy,
const QString &errorName, const QString &errorMessage)
{
Q_UNUSED(proxy);
if (isFinished()) {
return;
}
qWarning().nospace() << "StreamTube.Accept failed because channel was invalidated with " <<
errorName << ": " << errorMessage;
setFinishedWithError(errorName, errorMessage);
}
void PendingCaptchas::onGetCaptchasWatcherFinished(QDBusPendingCallWatcher *watcher)
{
QDBusPendingReply<Tp::CaptchaInfoList, uint, QString> reply = *watcher;
if (reply.isError()) {
qDebug().nospace() << "PendingDBusCall failed: " <<
reply.error().name() << ": " << reply.error().message();
setFinishedWithError(reply.error());
watcher->deleteLater();
return;
}
qDebug() << "Got reply to PendingDBusCall";
Tp::CaptchaInfoList list = reply.argumentAt(0).value<Tp::CaptchaInfoList>();
int howManyRequired = reply.argumentAt(1).toUInt();
// Compute which captchas are required
QList<QPair<Tp::CaptchaInfo,QString> > finalList;
Q_FOREACH (const Tp::CaptchaInfo &info, list) {
// First of all, mimetype check
QString mimeType;
if (mPriv->preferredMimeTypes.isEmpty()) {
// No preference, let's take the first of the list
mimeType = info.availableMIMETypes.first();
} else {
QSet<QString> supportedMimeTypes = info.availableMIMETypes.toSet().intersect(
mPriv->preferredMimeTypes.toSet());
if (supportedMimeTypes.isEmpty()) {
// Apparently our handler does not support any of this captcha's mimetypes, skip
continue;
}
// Ok, use the first one
mimeType = *supportedMimeTypes.constBegin();
}
// If it's required, easy
if (info.flags & CaptchaFlagRequired) {
finalList.append(qMakePair(info, mimeType));
continue;
}
// Otherwise, let's see if the mimetype matches
if (mPriv->preferredTypes & mPriv->stringToChallengeType(info.type)) {
finalList.append(qMakePair(info, mimeType));
}
if (finalList.size() == howManyRequired) {
break;
}
}
if (finalList.size() != howManyRequired) {
// No captchas available with our preferences
setFinishedWithError(TP_QT_ERROR_NOT_AVAILABLE,
"No captchas matching the handler's request");
return;
}
// Now, get the infos for all the required captchas in our final list.
mPriv->captchasLeft = finalList.size();
mPriv->multipleRequired = howManyRequired > 1 ? true : false;
for (QList<QPair<Tp::CaptchaInfo,QString> >::const_iterator i = finalList.constBegin();
i != finalList.constEnd(); ++i) {
QDBusPendingCall call =
mPriv->channel->mPriv->channel->interface<Client::ChannelInterfaceCaptchaAuthenticationInterface>()->GetCaptchaData(
(*i).first.ID, (*i).second);
QDBusPendingCallWatcher *dataWatcher = new QDBusPendingCallWatcher(call);
dataWatcher->setProperty("__Tp_Qt_CaptchaID", (*i).first.ID);
dataWatcher->setProperty("__Tp_Qt_CaptchaLabel", (*i).first.label);
dataWatcher->setProperty("__Tp_Qt_CaptchaType",
mPriv->stringToChallengeType((*i).first.type));
connect(dataWatcher,
SIGNAL(finished(QDBusPendingCallWatcher*)),
this,
SLOT(onGetCaptchaDataWatcherFinished(QDBusPendingCallWatcher*)));
}
watcher->deleteLater();
}
void PendingCaptchas::onGetCaptchaDataWatcherFinished(QDBusPendingCallWatcher *watcher)
{
QDBusPendingReply<QString, QByteArray> reply = *watcher;
if (reply.isError()) {
qDebug().nospace() << "PendingDBusCall failed: " <<
reply.error().name() << ": " << reply.error().message();
setFinishedWithError(reply.error());
watcher->deleteLater();
return;
}
qDebug() << "Got reply to PendingDBusCall";
// Add to the list
Captcha captchaItem(reply.argumentAt(0).toString(),
watcher->property("__Tp_Qt_CaptchaLabel").toString(),
reply.argumentAt(1).toByteArray(), (CaptchaAuthentication::ChallengeType)
watcher->property("__Tp_Qt_CaptchaType").toUInt(),
watcher->property("__Tp_Qt_CaptchaID").toInt());
mPriv->captchas.append(captchaItem);
--mPriv->captchasLeft;
if (!mPriv->captchasLeft) {
setFinished();
}
watcher->deleteLater();
}
/**
* Return the main captcha of the request. This captcha is guaranteed to be compatible
* with any constraint specified in CaptchaAuthentication::requestCaptchas().
*
* This is a convenience method which should be used when requiresMultipleCaptchas()
* is false - otherwise, you should use captchaList.
*
* The returned Captcha can be answered through CaptchaAuthentication::answer() by
* using its id.
*
* This method will return a meaningful value only if the operation was completed
* successfully.
*
* \return The main captcha for the pending request.
*
* \sa captchaList()
* CaptchaAuthentication::requestCaptchas()
* requiresMultipleCaptchas()
* CaptchaAuthentication::answer()
*/
Captcha PendingCaptchas::captcha() const
{
if (!isFinished()) {
return Captcha();
}
return mPriv->captchas.first();
}
/**
* Return all the captchas of the request. These captchas are guaranteed to be compatible
* with any constraint specified in CaptchaAuthentication::requestCaptchas().
*
* If requiresMultipleCaptchas() is false, you probably want to use the convenience method
* captcha() instead.
*
* The returned Captchas can be answered through CaptchaAuthentication::answer() by
* using their ids.
*
* This method will return a meaningful value only if the operation was completed
* successfully.
*
* \return All the captchas for the pending request.
*
* \sa captcha()
* CaptchaAuthentication::requestCaptchas()
* requiresMultipleCaptchas()
* CaptchaAuthentication::answer()
*/
QList<Captcha> PendingCaptchas::captchaList() const
{
if (!isFinished()) {
return QList<Captcha>();
}
return mPriv->captchas;
}
/**
* Return whether this request requires more than one captcha to be answered or not.
*
* This method should always be checked before answering to find out what the
* connection manager expects. Depending on the result, you might want to use the
* result from captcha() if just a single answer is required, or from captchaList()
* otherwise.
*
* This method will return a meaningful value only if the operation was completed
* successfully.
*
* \return The main captcha for the pending request.
* \sa captcha()
* captchaList()
*/
bool PendingCaptchas::requiresMultipleCaptchas() const
{
return mPriv->multipleRequired;
}
}
<commit_msg>captcha-authentication: Some captchas don't have a payload. Handle those in the right way<commit_after>/**
* This file is part of TelepathyQt
*
* @copyright Copyright (C) 2012 Collabora Ltd. <http://www.collabora.co.uk/>
* @license LGPL 2.1
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 2.1 of the License, or (at your option) any later version.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
*/
#include "pending-captchas.h"
#include "captcha-authentication.h"
#include "captcha-authentication-internal.h"
#include "cli-channel.h"
namespace Tp {
class TP_QT_NO_EXPORT CaptchaData : public QSharedData
{
public:
CaptchaData();
CaptchaData(const CaptchaData &other);
~CaptchaData();
QString mimeType;
QString label;
QByteArray captchaData;
CaptchaAuthentication::ChallengeType type;
int id;
};
CaptchaData::CaptchaData()
{
}
CaptchaData::CaptchaData(const CaptchaData &other)
: QSharedData(other),
mimeType(other.mimeType),
label(other.label),
captchaData(other.captchaData),
type(other.type),
id(other.id)
{
}
CaptchaData::~CaptchaData()
{
}
/**
* \class Captcha
* \ingroup client
* \headerfile TelepathyQt/pending-captchas.h <TelepathyQt/PendingCaptchas>
*
* \brief The Captcha class represents a Captcha ready to be answered.
*
* It exposes all the parameters needed for a handler to present the user with a captcha.
*
* Please note this class is meant to be read-only. It is usually created by PendingCaptchas
* once a Captcha request operation succeeds.
*
* Note: this class is implicitly shared
*/
/**
* Default constructor.
*/
Captcha::Captcha()
: mPriv(new CaptchaData)
{
}
/**
* Copy constructor.
*/
Captcha::Captcha(const Captcha &other)
: mPriv(other.mPriv)
{
}
Captcha::Captcha(const QString &mimeType, const QString &label,
const QByteArray &data, CaptchaAuthentication::ChallengeType type, int id)
: mPriv(new CaptchaData)
{
mPriv->mimeType = mimeType;
mPriv->label = label;
mPriv->captchaData = data;
mPriv->type = type;
mPriv->id = id;
}
/**
* Class destructor.
*/
Captcha::~Captcha()
{
}
/**
* Return the mimetype of the captcha.
*
* \return The captcha's mimetype.
* \sa data()
*/
QString Captcha::mimeType() const
{
return mPriv->mimeType;
}
/**
* Return the label of the captcha. For some captcha types, such as
* CaptchaAuthentication::TextQuestionChallenge, the label is also
* the challenge the user has to answer
*
* \return The captcha's label.
* \sa data()
* type()
*/
QString Captcha::label() const
{
return mPriv->label;
}
/**
* Return the raw data of the captcha. The handler can check its type and
* metatype to know how to parse the blob.
*
* \return The captcha's data.
* \sa mimeType(), type()
*/
QByteArray Captcha::data() const
{
return mPriv->captchaData;
}
/**
* Return the type of the captcha.
*
* \return The captcha's type.
* \sa data()
*/
CaptchaAuthentication::ChallengeType Captcha::type() const
{
return mPriv->type;
}
/**
* Return the id of the captcha. This parameter should be used to identify
* the captcha when answering its challenge.
*
* \return The captcha's id.
* \sa CaptchaAuthentication::answer()
*/
int Captcha::id() const
{
return mPriv->id;
}
struct TP_QT_NO_EXPORT PendingCaptchas::Private
{
Private(PendingCaptchas *parent);
~Private();
CaptchaAuthentication::ChallengeType stringToChallengeType(const QString &string) const;
void appendCaptchaResult(const QString &mimeType, const QString &label,
const QByteArray &data, CaptchaAuthentication::ChallengeType type, int id);
// Public object
PendingCaptchas *parent;
CaptchaAuthentication::ChallengeTypes preferredTypes;
QStringList preferredMimeTypes;
bool multipleRequired;
QList<Captcha> captchas;
int captchasLeft;
CaptchaAuthenticationPtr channel;
};
PendingCaptchas::Private::Private(PendingCaptchas *parent)
: parent(parent)
{
}
PendingCaptchas::Private::~Private()
{
}
CaptchaAuthentication::ChallengeType PendingCaptchas::Private::stringToChallengeType(const QString &string) const
{
if (string == "audio_recog") {
return CaptchaAuthentication::AudioRecognitionChallenge;
} else if (string == "ocr") {
return CaptchaAuthentication::OCRChallenge;
} else if (string == "picture_q") {
return CaptchaAuthentication::PictureQuestionChallenge;
} else if (string == "picture_recog") {
return CaptchaAuthentication::PictureRecognitionChallenge;
} else if (string == "qa") {
return CaptchaAuthentication::TextQuestionChallenge;
} else if (string == "speech_q") {
return CaptchaAuthentication::SpeechQuestionChallenge;
} else if (string == "speech_recog") {
return CaptchaAuthentication::SpeechRecognitionChallenge;
} else if (string == "video_q") {
return CaptchaAuthentication::VideoQuestionChallenge;
} else if (string == "video_recog") {
return CaptchaAuthentication::VideoRecognitionChallenge;
}
// Not really making sense...
return CaptchaAuthentication::UnknownChallenge;
}
void PendingCaptchas::Private::appendCaptchaResult(const QString &mimeType, const QString &label,
const QByteArray &data, CaptchaAuthentication::ChallengeType type, int id)
{
// Add to the list
Captcha captchaItem(mimeType, label, data, type, id);
captchas.append(captchaItem);
--captchasLeft;
if (!captchasLeft) {
parent->setFinished();
}
}
/**
* \class PendingCaptchas
* \ingroup client
* \headerfile TelepathyQt/pending-captchas.h <TelepathyQt/PendingCaptchas>
*
* \brief The PendingCaptchas class represents an asynchronous
* operation for retrieving a captcha challenge from a connection manager.
*
* See \ref async_model
*/
PendingCaptchas::PendingCaptchas(
const QDBusPendingCall &call,
const QStringList &preferredMimeTypes,
CaptchaAuthentication::ChallengeTypes preferredTypes,
const CaptchaAuthenticationPtr &channel)
: PendingOperation(channel),
mPriv(new Private(this))
{
mPriv->channel = channel;
mPriv->preferredMimeTypes = preferredMimeTypes;
mPriv->preferredTypes = preferredTypes;
/* keep track of channel invalidation */
connect(channel.data(),
SIGNAL(invalidated(Tp::DBusProxy*,QString,QString)),
SLOT(onChannelInvalidated(Tp::DBusProxy*,QString,QString)));
connect(new QDBusPendingCallWatcher(call),
SIGNAL(finished(QDBusPendingCallWatcher*)),
this,
SLOT(onGetCaptchasWatcherFinished(QDBusPendingCallWatcher*)));
}
PendingCaptchas::PendingCaptchas(
const QString& errorName,
const QString& errorMessage,
const CaptchaAuthenticationPtr &channel)
: PendingOperation(channel),
mPriv(new PendingCaptchas::Private(this))
{
setFinishedWithError(errorName, errorMessage);
}
/**
* Class destructor.
*/
PendingCaptchas::~PendingCaptchas()
{
delete mPriv;
}
void PendingCaptchas::onChannelInvalidated(Tp::DBusProxy *proxy,
const QString &errorName, const QString &errorMessage)
{
Q_UNUSED(proxy);
if (isFinished()) {
return;
}
qWarning().nospace() << "StreamTube.Accept failed because channel was invalidated with " <<
errorName << ": " << errorMessage;
setFinishedWithError(errorName, errorMessage);
}
void PendingCaptchas::onGetCaptchasWatcherFinished(QDBusPendingCallWatcher *watcher)
{
QDBusPendingReply<Tp::CaptchaInfoList, uint, QString> reply = *watcher;
if (reply.isError()) {
qDebug().nospace() << "PendingDBusCall failed: " <<
reply.error().name() << ": " << reply.error().message();
setFinishedWithError(reply.error());
watcher->deleteLater();
return;
}
qDebug() << "Got reply to PendingDBusCall";
Tp::CaptchaInfoList list = reply.argumentAt(0).value<Tp::CaptchaInfoList>();
int howManyRequired = reply.argumentAt(1).toUInt();
// Compute which captchas are required
QList<QPair<Tp::CaptchaInfo,QString> > finalList;
Q_FOREACH (const Tp::CaptchaInfo &info, list) {
// First of all, mimetype check
QString mimeType;
if (info.availableMIMETypes.isEmpty()) {
// If it's one of the types which might not have a payload, go for it
CaptchaAuthentication::ChallengeTypes noPayloadChallenges =
CaptchaAuthentication::TextQuestionChallenge &
CaptchaAuthentication::UnknownChallenge;
if (mPriv->stringToChallengeType(info.type) & noPayloadChallenges) {
// Ok, move on
} else {
// In this case, there's something wrong
qWarning() << "Got a captcha with type " << info.type << " which does not "
"expose any available mimetype for its payload. Something might be "
"wrong with the connection manager.";
continue;
}
} else if (mPriv->preferredMimeTypes.isEmpty()) {
// No preference, let's take the first of the list
mimeType = info.availableMIMETypes.first();
} else {
QSet<QString> supportedMimeTypes = info.availableMIMETypes.toSet().intersect(
mPriv->preferredMimeTypes.toSet());
if (supportedMimeTypes.isEmpty()) {
// Apparently our handler does not support any of this captcha's mimetypes, skip
continue;
}
// Ok, use the first one
mimeType = *supportedMimeTypes.constBegin();
}
// If it's required, easy
if (info.flags & CaptchaFlagRequired) {
finalList.append(qMakePair(info, mimeType));
continue;
}
// Otherwise, let's see if the mimetype matches
if (mPriv->preferredTypes & mPriv->stringToChallengeType(info.type)) {
finalList.append(qMakePair(info, mimeType));
}
if (finalList.size() == howManyRequired) {
break;
}
}
if (finalList.size() != howManyRequired) {
// No captchas available with our preferences
setFinishedWithError(TP_QT_ERROR_NOT_AVAILABLE,
"No captchas matching the handler's request");
return;
}
// Now, get the infos for all the required captchas in our final list.
mPriv->captchasLeft = finalList.size();
mPriv->multipleRequired = howManyRequired > 1 ? true : false;
for (QList<QPair<Tp::CaptchaInfo,QString> >::const_iterator i = finalList.constBegin();
i != finalList.constEnd(); ++i) {
// If the captcha does not have a mimetype, we can add it straight
if ((*i).second.isEmpty()) {
mPriv->appendCaptchaResult((*i).second, (*i).first.label, QByteArray(),
mPriv->stringToChallengeType((*i).first.type), (*i).first.ID);
continue;
}
QDBusPendingCall call =
mPriv->channel->mPriv->channel->interface<Client::ChannelInterfaceCaptchaAuthenticationInterface>()->GetCaptchaData(
(*i).first.ID, (*i).second);
QDBusPendingCallWatcher *dataWatcher = new QDBusPendingCallWatcher(call);
dataWatcher->setProperty("__Tp_Qt_CaptchaID", (*i).first.ID);
dataWatcher->setProperty("__Tp_Qt_CaptchaMimeType", (*i).second);
dataWatcher->setProperty("__Tp_Qt_CaptchaLabel", (*i).first.label);
dataWatcher->setProperty("__Tp_Qt_CaptchaType",
mPriv->stringToChallengeType((*i).first.type));
connect(dataWatcher,
SIGNAL(finished(QDBusPendingCallWatcher*)),
this,
SLOT(onGetCaptchaDataWatcherFinished(QDBusPendingCallWatcher*)));
}
watcher->deleteLater();
}
void PendingCaptchas::onGetCaptchaDataWatcherFinished(QDBusPendingCallWatcher *watcher)
{
QDBusPendingReply<QString, QByteArray> reply = *watcher;
if (reply.isError()) {
qDebug().nospace() << "PendingDBusCall failed: " <<
reply.error().name() << ": " << reply.error().message();
setFinishedWithError(reply.error());
watcher->deleteLater();
return;
}
qDebug() << "Got reply to PendingDBusCall";
// Add to the list
mPriv->appendCaptchaResult(watcher->property("__Tp_Qt_CaptchaMimeType").toString(),
watcher->property("__Tp_Qt_CaptchaLabel").toString(),
reply.argumentAt(1).toByteArray(), (CaptchaAuthentication::ChallengeType)
watcher->property("__Tp_Qt_CaptchaType").toUInt(),
watcher->property("__Tp_Qt_CaptchaID").toInt());
watcher->deleteLater();
}
/**
* Return the main captcha of the request. This captcha is guaranteed to be compatible
* with any constraint specified in CaptchaAuthentication::requestCaptchas().
*
* This is a convenience method which should be used when requiresMultipleCaptchas()
* is false - otherwise, you should use captchaList.
*
* The returned Captcha can be answered through CaptchaAuthentication::answer() by
* using its id.
*
* This method will return a meaningful value only if the operation was completed
* successfully.
*
* \return The main captcha for the pending request.
*
* \sa captchaList()
* CaptchaAuthentication::requestCaptchas()
* requiresMultipleCaptchas()
* CaptchaAuthentication::answer()
*/
Captcha PendingCaptchas::captcha() const
{
if (!isFinished()) {
return Captcha();
}
return mPriv->captchas.first();
}
/**
* Return all the captchas of the request. These captchas are guaranteed to be compatible
* with any constraint specified in CaptchaAuthentication::requestCaptchas().
*
* If requiresMultipleCaptchas() is false, you probably want to use the convenience method
* captcha() instead.
*
* The returned Captchas can be answered through CaptchaAuthentication::answer() by
* using their ids.
*
* This method will return a meaningful value only if the operation was completed
* successfully.
*
* \return All the captchas for the pending request.
*
* \sa captcha()
* CaptchaAuthentication::requestCaptchas()
* requiresMultipleCaptchas()
* CaptchaAuthentication::answer()
*/
QList<Captcha> PendingCaptchas::captchaList() const
{
if (!isFinished()) {
return QList<Captcha>();
}
return mPriv->captchas;
}
/**
* Return whether this request requires more than one captcha to be answered or not.
*
* This method should always be checked before answering to find out what the
* connection manager expects. Depending on the result, you might want to use the
* result from captcha() if just a single answer is required, or from captchaList()
* otherwise.
*
* This method will return a meaningful value only if the operation was completed
* successfully.
*
* \return The main captcha for the pending request.
* \sa captcha()
* captchaList()
*/
bool PendingCaptchas::requiresMultipleCaptchas() const
{
return mPriv->multipleRequired;
}
}
<|endoftext|> |
<commit_before>#include <UnitTest/stdafx.h>
#include <UnitTest/UnitTest.h>
#include <core/mapi/cache/namedProps.h>
#include <core/mapi/cache/namedPropCache.h>
#include <core/mapi/extraPropTags.h>
namespace namedproptest
{
TEST_CLASS(namedproptest)
{
public:
// Without this, clang gets weird
static const bool dummy_var = true;
const std::vector<BYTE> sig1 = {1, 2, 3, 4};
const std::vector<BYTE> sig2 = {5, 6, 7, 8, 9};
const MAPINAMEID formStorageID = {const_cast<LPGUID>(&guid::PSETID_Common), MNID_ID, dispidFormStorage};
const MAPINAMEID formStorageIDLog = {const_cast<LPGUID>(&guid::PSETID_Log), MNID_ID, dispidFormStorage};
const MAPINAMEID formStorageName = {
const_cast<LPGUID>(&guid::PSETID_Common), MNID_STRING, {.lpwstrName = L"name"}};
const MAPINAMEID formStorageName2 = {
const_cast<LPGUID>(&guid::PSETID_Common), MNID_STRING, {.lpwstrName = L"name2"}};
const MAPINAMEID pageDirStreamID = {const_cast<LPGUID>(&guid::PSETID_Common), MNID_ID, dispidPageDirStream};
TEST_CLASS_INITIALIZE(initialize) { unittest::init(); }
TEST_METHOD(Test_Match)
{
const auto formStorage1 = cache::namedPropCacheEntry::make(&formStorageID, 0x1111, sig1);
const auto formStorage2 = cache::namedPropCacheEntry::make(&formStorageID, 0x1111, sig2);
const auto formStorageLog = cache::namedPropCacheEntry::make(&formStorageIDLog, 0x1111, sig1);
const auto formStorageProp = cache::namedPropCacheEntry::make(&formStorageName, 0x1111, sig1);
const auto formStorageProp1 = cache::namedPropCacheEntry::make(&formStorageName2, 0x1111, sig1);
// Test all forms of match
Assert::AreEqual(true, formStorage1->match(formStorage1, true, true, true));
Assert::AreEqual(true, formStorage1->match(formStorage1, false, true, true));
Assert::AreEqual(true, formStorage1->match(formStorage1, true, false, true));
Assert::AreEqual(true, formStorage1->match(formStorage1, true, true, false));
Assert::AreEqual(true, formStorage1->match(formStorage1, true, false, false));
Assert::AreEqual(true, formStorage1->match(formStorage1, false, true, false));
Assert::AreEqual(true, formStorage1->match(formStorage1, false, false, true));
Assert::AreEqual(true, formStorage1->match(formStorage1, false, false, false));
// Odd comparisons
Assert::AreEqual(
true,
formStorage1->match(cache::namedPropCacheEntry::make(&formStorageID, 0x1111, sig1), true, true, true));
Assert::AreEqual(
true,
formStorage1->match(cache::namedPropCacheEntry::make(&formStorageID, 0x1112, sig1), true, false, true));
Assert::AreEqual(
true,
formStorage1->match(
cache::namedPropCacheEntry::make(&pageDirStreamID, 0x1111, sig1), true, true, false));
Assert::AreEqual(
true,
formStorage1->match(
cache::namedPropCacheEntry::make(&formStorageName, 0x1111, sig1), true, true, false));
Assert::AreEqual(
false,
formStorage1->match(
cache::namedPropCacheEntry::make(&formStorageName, 0x1111, sig1), true, true, true));
// Should fail
Assert::AreEqual(
false,
formStorage1->match(cache::namedPropCacheEntry::make(&formStorageID, 0x1110, sig1), true, true, true));
Assert::AreEqual(
false,
formStorage1->match(
cache::namedPropCacheEntry::make(&pageDirStreamID, 0x1111, sig1), true, true, true));
Assert::AreEqual(false, formStorage1->match(nullptr, true, true, true));
Assert::AreEqual(false, formStorage1->match(formStorage2, true, true, true));
Assert::AreEqual(false, formStorage1->match(formStorageLog, true, true, true));
// Should all work
Assert::AreEqual(true, formStorage1->match(formStorage2, false, true, true));
Assert::AreEqual(true, formStorage1->match(formStorage2, false, false, true));
Assert::AreEqual(true, formStorage1->match(formStorage2, false, true, false));
Assert::AreEqual(true, formStorage1->match(formStorage2, false, false, false));
// Compare given a signature, MAPINAMEID
// _Check_return_ bool match(_In_ const std::vector<BYTE>& _sig, _In_ const MAPINAMEID& _mapiNameId) const;
Assert::AreEqual(true, formStorage1->match(sig1, formStorageID));
Assert::AreEqual(false, formStorage1->match(sig2, formStorageID));
Assert::AreEqual(false, formStorage1->match(sig1, formStorageName));
Assert::AreEqual(false, formStorage1->match(sig1, formStorageIDLog));
Assert::AreEqual(false, formStorage1->match(sig1, pageDirStreamID));
Assert::AreEqual(true, formStorageProp->match(sig1, formStorageName));
Assert::AreEqual(false, formStorageProp->match(sig1, formStorageName2));
// Compare given a signature and property ID (ulPropID)
// _Check_return_ bool match(_In_ const std::vector<BYTE>& _sig, ULONG _ulPropID) const;
Assert::AreEqual(true, formStorage1->match(sig1, 0x1111));
Assert::AreEqual(false, formStorage1->match(sig1, 0x1112));
Assert::AreEqual(false, formStorage1->match(sig2, 0x1111));
// Compare given a id, MAPINAMEID
// _Check_return_ bool match(ULONG _ulPropID, _In_ const MAPINAMEID& _mapiNameId) const noexcept;
Assert::AreEqual(true, formStorage1->match(0x1111, formStorageID));
Assert::AreEqual(false, formStorage1->match(0x1112, formStorageID));
Assert::AreEqual(false, formStorage1->match(0x1111, pageDirStreamID));
Assert::AreEqual(false, formStorage1->match(0x1111, formStorageName));
Assert::AreEqual(false, formStorage1->match(0x1111, formStorageIDLog));
Assert::AreEqual(true, formStorageProp->match(0x1111, formStorageName));
Assert::AreEqual(false, formStorageProp->match(0x1111, formStorageName2));
// String prop
Assert::AreEqual(true, formStorageProp->match(formStorageProp, true, true, true));
Assert::AreEqual(false, formStorageProp->match(formStorageProp1, true, true, true));
}
TEST_METHOD(Test_Cache)
{
const auto prop1 = cache::namedPropCacheEntry::make(&formStorageID, 0x1111);
const auto prop2 = cache::namedPropCacheEntry::make(&formStorageName, 0x2222);
const auto prop3 = cache::namedPropCacheEntry::make(&pageDirStreamID, 0x3333);
auto ids = std::vector<std::shared_ptr<cache::namedPropCacheEntry>>{};
ids.emplace_back(prop1);
ids.emplace_back(prop2);
ids.emplace_back(prop3);
cache::namedPropCache::add(ids, sig1);
Assert::AreEqual(
true, cache::namedPropCache::find(prop1, true, true, true)->match(prop1, true, true, true));
Assert::AreEqual(
true, cache::namedPropCache::find(prop2, true, true, true)->match(prop2, true, true, true));
Assert::AreEqual(
true, cache::namedPropCache::find(prop3, true, true, true)->match(prop3, true, true, true));
Assert::AreEqual(true, cache::namedPropCache::find(0x1111, formStorageID)->match(prop1, true, true, true));
Assert::AreEqual(true, cache::namedPropCache::find(sig1, 0x1111)->match(prop1, true, true, true));
Assert::AreEqual(true, cache::namedPropCache::find(sig1, formStorageID)->match(prop1, true, true, true));
Assert::AreEqual(
true,
cache::namedPropCache::find(0x1110, formStorageID)
->match(cache::namedPropCacheEntry::empty(), true, true, true));
Assert::AreEqual(false, cache::namedPropCache::find(0x1110, formStorageID)->match(prop1, true, true, true));
Assert::AreEqual(false, cache::namedPropCache::find(sig2, 0x1111)->match(prop1, true, true, true));
Assert::AreEqual(false, cache::namedPropCache::find(sig2, formStorageID)->match(prop1, true, true, true));
}
TEST_METHOD(Test_Valid)
{
Assert::AreEqual(false, cache::namedPropCacheEntry::valid(cache::namedPropCacheEntry::empty()));
Assert::AreEqual(
true,
cache::namedPropCacheEntry::valid(cache::namedPropCacheEntry::make(&formStorageName, 0x1111, sig1)));
Assert::AreEqual(
true, cache::namedPropCacheEntry::valid(cache::namedPropCacheEntry::make(&formStorageName, 0x1111)));
Assert::AreEqual(
false, cache::namedPropCacheEntry::valid(cache::namedPropCacheEntry::make(&formStorageName, 0)));
Assert::AreEqual(
false, cache::namedPropCacheEntry::valid(cache::namedPropCacheEntry::make(nullptr, 0x1111)));
Assert::AreEqual(false, cache::namedPropCacheEntry::valid(cache::namedPropCacheEntry::make(nullptr, 0)));
Assert::AreEqual(false, cache::namedPropCacheEntry::valid(nullptr));
}
};
} // namespace namedproptest<commit_msg>more test cases<commit_after>#include <UnitTest/stdafx.h>
#include <UnitTest/UnitTest.h>
#include <core/mapi/cache/namedProps.h>
#include <core/mapi/cache/namedPropCache.h>
#include <core/mapi/extraPropTags.h>
#include <core/utility/output.h>
#include <core/utility/registry.h>
namespace namedproptest
{
TEST_CLASS(namedproptest)
{
public:
// Without this, clang gets weird
static const bool dummy_var = true;
const std::vector<BYTE> sig1 = {1, 2, 3, 4};
const std::vector<BYTE> sig2 = {5, 6, 7, 8, 9};
const MAPINAMEID formStorageID = {const_cast<LPGUID>(&guid::PSETID_Common), MNID_ID, dispidFormStorage};
const MAPINAMEID formStorageIDLog = {const_cast<LPGUID>(&guid::PSETID_Log), MNID_ID, dispidFormStorage};
const MAPINAMEID formStorageName = {
const_cast<LPGUID>(&guid::PSETID_Common), MNID_STRING, {.lpwstrName = L"name"}};
const MAPINAMEID formStorageName2 = {
const_cast<LPGUID>(&guid::PSETID_Common), MNID_STRING, {.lpwstrName = L"name2"}};
const MAPINAMEID pageDirStreamID = {const_cast<LPGUID>(&guid::PSETID_Common), MNID_ID, dispidPageDirStream};
TEST_CLASS_INITIALIZE(initialize) { unittest::init(); }
TEST_METHOD(Test_Match)
{
const auto formStorage1 = cache::namedPropCacheEntry::make(&formStorageID, 0x1111, sig1);
const auto formStorage2 = cache::namedPropCacheEntry::make(&formStorageID, 0x1111, sig2);
const auto formStorageLog = cache::namedPropCacheEntry::make(&formStorageIDLog, 0x1111, sig1);
const auto formStorageProp = cache::namedPropCacheEntry::make(&formStorageName, 0x1111, sig1);
const auto formStorageProp1 = cache::namedPropCacheEntry::make(&formStorageName2, 0x1111, sig1);
// Test all forms of match
Assert::AreEqual(true, formStorage1->match(formStorage1, true, true, true));
Assert::AreEqual(true, formStorage1->match(formStorage1, false, true, true));
Assert::AreEqual(true, formStorage1->match(formStorage1, true, false, true));
Assert::AreEqual(true, formStorage1->match(formStorage1, true, true, false));
Assert::AreEqual(true, formStorage1->match(formStorage1, true, false, false));
Assert::AreEqual(true, formStorage1->match(formStorage1, false, true, false));
Assert::AreEqual(true, formStorage1->match(formStorage1, false, false, true));
Assert::AreEqual(true, formStorage1->match(formStorage1, false, false, false));
// Odd comparisons
Assert::AreEqual(
true,
formStorage1->match(cache::namedPropCacheEntry::make(&formStorageID, 0x1111, sig1), true, true, true));
Assert::AreEqual(
true,
formStorage1->match(cache::namedPropCacheEntry::make(&formStorageID, 0x1112, sig1), true, false, true));
Assert::AreEqual(
true,
formStorage1->match(
cache::namedPropCacheEntry::make(&pageDirStreamID, 0x1111, sig1), true, true, false));
Assert::AreEqual(
true,
formStorage1->match(
cache::namedPropCacheEntry::make(&formStorageName, 0x1111, sig1), true, true, false));
Assert::AreEqual(
false,
formStorage1->match(
cache::namedPropCacheEntry::make(&formStorageName, 0x1111, sig1), true, true, true));
// Should fail
Assert::AreEqual(
false,
formStorage1->match(cache::namedPropCacheEntry::make(&formStorageID, 0x1110, sig1), true, true, true));
Assert::AreEqual(
false,
formStorage1->match(
cache::namedPropCacheEntry::make(&pageDirStreamID, 0x1111, sig1), true, true, true));
Assert::AreEqual(false, formStorage1->match(nullptr, true, true, true));
Assert::AreEqual(false, formStorage1->match(formStorage2, true, true, true));
Assert::AreEqual(false, formStorage1->match(formStorageLog, true, true, true));
// Should all work
Assert::AreEqual(true, formStorage1->match(formStorage2, false, true, true));
Assert::AreEqual(true, formStorage1->match(formStorage2, false, false, true));
Assert::AreEqual(true, formStorage1->match(formStorage2, false, true, false));
Assert::AreEqual(true, formStorage1->match(formStorage2, false, false, false));
// Compare given a signature, MAPINAMEID
// _Check_return_ bool match(_In_ const std::vector<BYTE>& _sig, _In_ const MAPINAMEID& _mapiNameId) const;
Assert::AreEqual(true, formStorage1->match(sig1, formStorageID));
Assert::AreEqual(false, formStorage1->match(sig2, formStorageID));
Assert::AreEqual(false, formStorage1->match(sig1, formStorageName));
Assert::AreEqual(false, formStorage1->match(sig1, formStorageIDLog));
Assert::AreEqual(false, formStorage1->match(sig1, pageDirStreamID));
Assert::AreEqual(true, formStorageProp->match(sig1, formStorageName));
Assert::AreEqual(false, formStorageProp->match(sig1, formStorageName2));
// Compare given a signature and property ID (ulPropID)
// _Check_return_ bool match(_In_ const std::vector<BYTE>& _sig, ULONG _ulPropID) const;
Assert::AreEqual(true, formStorage1->match(sig1, 0x1111));
Assert::AreEqual(false, formStorage1->match(sig1, 0x1112));
Assert::AreEqual(false, formStorage1->match(sig2, 0x1111));
// Compare given a id, MAPINAMEID
// _Check_return_ bool match(ULONG _ulPropID, _In_ const MAPINAMEID& _mapiNameId) const noexcept;
Assert::AreEqual(true, formStorage1->match(0x1111, formStorageID));
Assert::AreEqual(false, formStorage1->match(0x1112, formStorageID));
Assert::AreEqual(false, formStorage1->match(0x1111, pageDirStreamID));
Assert::AreEqual(false, formStorage1->match(0x1111, formStorageName));
Assert::AreEqual(false, formStorage1->match(0x1111, formStorageIDLog));
Assert::AreEqual(true, formStorageProp->match(0x1111, formStorageName));
Assert::AreEqual(false, formStorageProp->match(0x1111, formStorageName2));
// String prop
Assert::AreEqual(true, formStorageProp->match(formStorageProp, true, true, true));
Assert::AreEqual(false, formStorageProp->match(formStorageProp1, true, true, true));
}
TEST_METHOD(Test_Cache)
{
registry::debugTag |= static_cast<DWORD>(output::dbgLevel::NamedPropCacheMisses);
const auto prop1 = cache::namedPropCacheEntry::make(&formStorageID, 0x1111);
const auto prop2 = cache::namedPropCacheEntry::make(&formStorageName, 0x2222);
const auto prop3 = cache::namedPropCacheEntry::make(&pageDirStreamID, 0x3333);
auto ids = std::vector<std::shared_ptr<cache::namedPropCacheEntry>>{};
ids.emplace_back(prop1);
ids.emplace_back(prop2);
ids.emplace_back(prop3);
cache::namedPropCache::add(ids, sig1);
cache::namedPropCache::add(ids, {});
Assert::AreEqual(
true, cache::namedPropCache::find(prop1, true, true, true)->match(prop1, true, true, true));
Assert::AreEqual(
true, cache::namedPropCache::find(prop2, true, true, true)->match(prop2, true, true, true));
Assert::AreEqual(
true, cache::namedPropCache::find(prop3, true, true, true)->match(prop3, true, true, true));
Assert::AreEqual(true, cache::namedPropCache::find(0x1111, formStorageID)->match(prop1, true, true, true));
Assert::AreEqual(true, cache::namedPropCache::find(sig1, 0x1111)->match(prop1, true, true, true));
Assert::AreEqual(true, cache::namedPropCache::find(sig1, formStorageID)->match(prop1, true, true, true));
Assert::AreEqual(
true,
cache::namedPropCache::find(0x1110, formStorageID)
->match(cache::namedPropCacheEntry::empty(), true, true, true));
Assert::AreEqual(false, cache::namedPropCache::find(0x1110, formStorageID)->match(prop1, true, true, true));
Assert::AreEqual(false, cache::namedPropCache::find(sig2, 0x1111)->match(prop1, true, true, true));
Assert::AreEqual(false, cache::namedPropCache::find(sig2, formStorageID)->match(prop1, true, true, true));
}
TEST_METHOD(Test_Valid)
{
Assert::AreEqual(false, cache::namedPropCacheEntry::valid(cache::namedPropCacheEntry::empty()));
Assert::AreEqual(
true,
cache::namedPropCacheEntry::valid(cache::namedPropCacheEntry::make(&formStorageName, 0x1111, sig1)));
Assert::AreEqual(
true, cache::namedPropCacheEntry::valid(cache::namedPropCacheEntry::make(&formStorageName, 0x1111)));
Assert::AreEqual(
false, cache::namedPropCacheEntry::valid(cache::namedPropCacheEntry::make(&formStorageName, 0)));
Assert::AreEqual(
false, cache::namedPropCacheEntry::valid(cache::namedPropCacheEntry::make(nullptr, 0x1111)));
Assert::AreEqual(false, cache::namedPropCacheEntry::valid(cache::namedPropCacheEntry::make(nullptr, 0)));
Assert::AreEqual(false, cache::namedPropCacheEntry::valid(nullptr));
}
};
} // namespace namedproptest<|endoftext|> |
<commit_before>/*
* Software License Agreement (BSD License)
*
* Point Cloud Library (PCL) - www.pointclouds.org
* Copyright (c) 2010-2011, Willow Garage, Inc.
*
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
*
* * Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* * Redistributions in binary form must reproduce the above
* copyright notice, this list of conditions and the following
* disclaimer in the documentation and/or other materials provided
* with the distribution.
* * Neither the name of the copyright holder(s) nor the names of its
* contributors may be used to endorse or promote products derived
* from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
* "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
* LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
* FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
* COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
* INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
* BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
* CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
* LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN
* ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
* POSSIBILITY OF SUCH DAMAGE.
*
*
*/
#include <pcl/PCLPointCloud2.h>
#include <pcl/point_types.h>
#include <pcl/io/pcd_io.h>
#include <pcl/console/print.h>
#include <pcl/console/parse.h>
#include <pcl/console/time.h>
#include <pcl/features/normal_3d.h>
#include <pcl/features/fpfh.h>
#include <pcl/features/pfh.h>
#include <pcl/features/vfh.h>
using namespace pcl;
using namespace pcl::io;
using namespace pcl::console;
std::string default_feature_name = "FPFHEstimation";
int default_n_k = 0;
double default_n_radius = 0.0;
int default_f_k = 0;
double default_f_radius = 0.0;
void
printHelp (int, char **argv)
{
print_error ("Syntax is: %s input.pcd output.pcd <options>\n", argv[0]);
print_info (" where options are:\n");
print_info (" -feature X = the feature descriptor algorithm to be used (default: ");
print_value ("%s", default_feature_name.c_str ()); print_info (")\n");
print_info (" -n_radius X = use a radius of Xm around each point to determine the neighborhood in normal estimation (default: ");
print_value ("%f", default_n_radius); print_info (")\n");
print_info (" -n_k X = use a fixed number of X-nearest neighbors around each point in normal estimation (default: ");
print_value ("%f", default_n_k); print_info (")\n");
print_info (" -f_radius X = use a radius of Xm around each point to determine the neighborhood in feature extraction (default: ");
print_value ("%f", default_f_radius); print_info (")\n");
print_info (" -f_k X = use a fixed number of X-nearest neighbors around each point in feature extraction(default: ");
print_value ("%f", default_f_k); print_info (")\n");
}
bool
loadCloud (const std::string &filename, pcl::PCLPointCloud2 &cloud)
{
TicToc tt;
print_highlight ("Loading "); print_value ("%s ", filename.c_str ());
tt.tic ();
if (loadPCDFile (filename, cloud) < 0)
return (false);
print_info ("[done, "); print_value ("%g", tt.toc ()); print_info (" ms : "); print_value ("%d", cloud.width * cloud.height); print_info (" points]\n");
print_info ("Available dimensions: "); print_value ("%s\n", pcl::getFieldsList (cloud).c_str ());
return (true);
}
template <typename FeatureAlgorithm, typename PointIn, typename NormalT, typename PointOut>
void
computeFeatureViaNormals (const pcl::PCLPointCloud2::ConstPtr &input, pcl::PCLPointCloud2 &output,
int argc, char** argv, bool set_search_flag = true)
{
int n_k = default_n_k;
int f_k = default_f_k;
double n_radius = default_n_radius;
double f_radius = default_f_radius;
parse_argument (argc, argv, "-n_k", n_k);
parse_argument (argc, argv, "-n_radius", n_radius);
parse_argument (argc, argv, "-f_k", f_k);
parse_argument (argc, argv, "-f_radius", f_radius);
// Convert data to PointCloud<PointIn>
typename PointCloud<PointIn>::Ptr xyz (new PointCloud<PointIn>);
fromPCLPointCloud2 (*input, *xyz);
// Estimate
TicToc tt;
tt.tic ();
print_highlight (stderr, "Computing ");
NormalEstimation<PointIn, NormalT> ne;
ne.setInputCloud (xyz);
ne.setSearchMethod (typename pcl::search::KdTree<PointIn>::Ptr (new pcl::search::KdTree<PointIn>));
ne.setKSearch (n_k);
ne.setRadiusSearch (n_radius);
typename PointCloud<NormalT>::Ptr normals = typename PointCloud<NormalT>::Ptr (new PointCloud<NormalT>);
ne.compute (*normals);
FeatureAlgorithm feature_est;
feature_est.setInputCloud (xyz);
feature_est.setInputNormals (normals);
feature_est.setSearchMethod (typename pcl::search::KdTree<PointIn>::Ptr (new pcl::search::KdTree<PointIn>));
PointCloud<PointOut> output_features;
if (set_search_flag) {
feature_est.setKSearch (f_k);
feature_est.setRadiusSearch (f_radius);
}
feature_est.compute (output_features);
print_info ("[done, "); print_value ("%g", tt.toc ()); print_info (" ms : "); print_value ("%d", output.width * output.height); print_info (" points]\n");
// Convert data back
toPCLPointCloud2 (output_features, output);
}
void
saveCloud (const std::string &filename, const pcl::PCLPointCloud2 &output)
{
TicToc tt;
tt.tic ();
print_highlight ("Saving "); print_value ("%s ", filename.c_str ());
pcl::io::savePCDFile (filename, output);
print_info ("[done, "); print_value ("%g", tt.toc ()); print_info (" ms : "); print_value ("%d", output.width * output.height); print_info (" points]\n");
}
/* ---[ */
int
main (int argc, char** argv)
{
print_info ("Extract features from a point cloud. For more information, use: %s -h\n", argv[0]);
if (argc < 3)
{
printHelp (argc, argv);
return (-1);
}
// Parse the command line arguments for .pcd files
std::vector<int> p_file_indices;
p_file_indices = parse_file_extension_argument (argc, argv, ".pcd");
if (p_file_indices.size () != 2)
{
print_error ("Need one input PCD file and one output PCD file to continue.\n");
return (-1);
}
// Command line parsing
std::string feature_name = default_feature_name;
parse_argument (argc, argv, "-feature", feature_name);
// Load the first file
pcl::PCLPointCloud2::Ptr cloud (new pcl::PCLPointCloud2);
if (!loadCloud (argv[p_file_indices[0]], *cloud))
return (-1);
// Perform the feature estimation
pcl::PCLPointCloud2 output;
if (feature_name == "PFHEstimation")
computeFeatureViaNormals< PFHEstimation<PointXYZ, Normal, PFHSignature125>, PointXYZ, Normal, PFHSignature125>
(cloud, output, argc, argv);
else if (feature_name == "FPFHEstimation")
computeFeatureViaNormals< FPFHEstimation<PointXYZ, Normal, FPFHSignature33>, PointXYZ, Normal, FPFHSignature33>
(cloud, output, argc, argv);
else if (feature_name == "VFHEstimation")
computeFeatureViaNormals< VFHEstimation<PointXYZ, Normal, VFHSignature308>, PointXYZ, Normal, VFHSignature308>
(cloud, output, argc, argv, false);
// Save into the second file
saveCloud (argv[p_file_indices[1]], output);
}
<commit_msg>Error message on non-recognized feature names (#2178)<commit_after>/*
* Software License Agreement (BSD License)
*
* Point Cloud Library (PCL) - www.pointclouds.org
* Copyright (c) 2010-2011, Willow Garage, Inc.
*
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
*
* * Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* * Redistributions in binary form must reproduce the above
* copyright notice, this list of conditions and the following
* disclaimer in the documentation and/or other materials provided
* with the distribution.
* * Neither the name of the copyright holder(s) nor the names of its
* contributors may be used to endorse or promote products derived
* from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
* "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
* LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
* FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
* COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
* INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
* BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
* CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
* LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN
* ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
* POSSIBILITY OF SUCH DAMAGE.
*
*
*/
#include <pcl/PCLPointCloud2.h>
#include <pcl/point_types.h>
#include <pcl/io/pcd_io.h>
#include <pcl/console/print.h>
#include <pcl/console/parse.h>
#include <pcl/console/time.h>
#include <pcl/features/normal_3d.h>
#include <pcl/features/fpfh.h>
#include <pcl/features/pfh.h>
#include <pcl/features/vfh.h>
using namespace pcl;
using namespace pcl::io;
using namespace pcl::console;
std::string default_feature_name = "FPFHEstimation";
int default_n_k = 0;
double default_n_radius = 0.0;
int default_f_k = 0;
double default_f_radius = 0.0;
void
printHelp (int, char **argv)
{
print_error ("Syntax is: %s input.pcd output.pcd <options>\n", argv[0]);
print_info (" where options are:\n");
print_info (" -feature X = the feature descriptor algorithm to be used (default: ");
print_value ("%s", default_feature_name.c_str ()); print_info (")\n");
print_info (" -n_radius X = use a radius of Xm around each point to determine the neighborhood in normal estimation (default: ");
print_value ("%f", default_n_radius); print_info (")\n");
print_info (" -n_k X = use a fixed number of X-nearest neighbors around each point in normal estimation (default: ");
print_value ("%f", default_n_k); print_info (")\n");
print_info (" -f_radius X = use a radius of Xm around each point to determine the neighborhood in feature extraction (default: ");
print_value ("%f", default_f_radius); print_info (")\n");
print_info (" -f_k X = use a fixed number of X-nearest neighbors around each point in feature extraction(default: ");
print_value ("%f", default_f_k); print_info (")\n");
}
bool
loadCloud (const std::string &filename, pcl::PCLPointCloud2 &cloud)
{
TicToc tt;
print_highlight ("Loading "); print_value ("%s ", filename.c_str ());
tt.tic ();
if (loadPCDFile (filename, cloud) < 0)
return (false);
print_info ("[done, "); print_value ("%g", tt.toc ()); print_info (" ms : "); print_value ("%d", cloud.width * cloud.height); print_info (" points]\n");
print_info ("Available dimensions: "); print_value ("%s\n", pcl::getFieldsList (cloud).c_str ());
return (true);
}
template <typename FeatureAlgorithm, typename PointIn, typename NormalT, typename PointOut>
void
computeFeatureViaNormals (const pcl::PCLPointCloud2::ConstPtr &input, pcl::PCLPointCloud2 &output,
int argc, char** argv, bool set_search_flag = true)
{
int n_k = default_n_k;
int f_k = default_f_k;
double n_radius = default_n_radius;
double f_radius = default_f_radius;
parse_argument (argc, argv, "-n_k", n_k);
parse_argument (argc, argv, "-n_radius", n_radius);
parse_argument (argc, argv, "-f_k", f_k);
parse_argument (argc, argv, "-f_radius", f_radius);
// Convert data to PointCloud<PointIn>
typename PointCloud<PointIn>::Ptr xyz (new PointCloud<PointIn>);
fromPCLPointCloud2 (*input, *xyz);
// Estimate
TicToc tt;
tt.tic ();
print_highlight (stderr, "Computing ");
NormalEstimation<PointIn, NormalT> ne;
ne.setInputCloud (xyz);
ne.setSearchMethod (typename pcl::search::KdTree<PointIn>::Ptr (new pcl::search::KdTree<PointIn>));
ne.setKSearch (n_k);
ne.setRadiusSearch (n_radius);
typename PointCloud<NormalT>::Ptr normals = typename PointCloud<NormalT>::Ptr (new PointCloud<NormalT>);
ne.compute (*normals);
FeatureAlgorithm feature_est;
feature_est.setInputCloud (xyz);
feature_est.setInputNormals (normals);
feature_est.setSearchMethod (typename pcl::search::KdTree<PointIn>::Ptr (new pcl::search::KdTree<PointIn>));
PointCloud<PointOut> output_features;
if (set_search_flag) {
feature_est.setKSearch (f_k);
feature_est.setRadiusSearch (f_radius);
}
feature_est.compute (output_features);
print_info ("[done, "); print_value ("%g", tt.toc ()); print_info (" ms : "); print_value ("%d", output.width * output.height); print_info (" points]\n");
// Convert data back
toPCLPointCloud2 (output_features, output);
}
void
saveCloud (const std::string &filename, const pcl::PCLPointCloud2 &output)
{
TicToc tt;
tt.tic ();
print_highlight ("Saving "); print_value ("%s ", filename.c_str ());
pcl::io::savePCDFile (filename, output);
print_info ("[done, "); print_value ("%g", tt.toc ()); print_info (" ms : "); print_value ("%d", output.width * output.height); print_info (" points]\n");
}
/* ---[ */
int
main (int argc, char** argv)
{
print_info ("Extract features from a point cloud. For more information, use: %s -h\n", argv[0]);
if (argc < 3)
{
printHelp (argc, argv);
return (-1);
}
// Parse the command line arguments for .pcd files
std::vector<int> p_file_indices;
p_file_indices = parse_file_extension_argument (argc, argv, ".pcd");
if (p_file_indices.size () != 2)
{
print_error ("Need one input PCD file and one output PCD file to continue.\n");
return (-1);
}
// Command line parsing
std::string feature_name = default_feature_name;
parse_argument (argc, argv, "-feature", feature_name);
// Load the first file
pcl::PCLPointCloud2::Ptr cloud (new pcl::PCLPointCloud2);
if (!loadCloud (argv[p_file_indices[0]], *cloud))
return (-1);
// Perform the feature estimation
pcl::PCLPointCloud2 output;
if (feature_name == "PFHEstimation")
computeFeatureViaNormals< PFHEstimation<PointXYZ, Normal, PFHSignature125>, PointXYZ, Normal, PFHSignature125>
(cloud, output, argc, argv);
else if (feature_name == "FPFHEstimation")
computeFeatureViaNormals< FPFHEstimation<PointXYZ, Normal, FPFHSignature33>, PointXYZ, Normal, FPFHSignature33>
(cloud, output, argc, argv);
else if (feature_name == "VFHEstimation")
computeFeatureViaNormals< VFHEstimation<PointXYZ, Normal, VFHSignature308>, PointXYZ, Normal, VFHSignature308>
(cloud, output, argc, argv, false);
else
{
print_error ("Valid feature names are PFHEstimation, FPFHEstimation, VFHEstimation.\n");
return (-1);
}
// Save into the second file
saveCloud (argv[p_file_indices[1]], output);
}
<|endoftext|> |
<commit_before>//===- tools/seec-ld/seec-ld.cpp ------------------------------------------===//
//
// SeeC
//
// This file is distributed under The MIT License (MIT). See LICENSE.TXT for
// details.
//
//===----------------------------------------------------------------------===//
///
/// \file
///
//===----------------------------------------------------------------------===//
#include "seec/Transforms/RecordExternal/RecordExternal.hpp"
#include "seec/Util/MakeUnique.hpp"
#include "llvm/Linker.h"
#include "llvm/ADT/Triple.h"
#include "llvm/Analysis/Verifier.h"
#include "llvm/Bitcode/ReaderWriter.h"
#include "llvm/CodeGen/LinkAllAsmWriterComponents.h"
#include "llvm/CodeGen/LinkAllCodegenComponents.h"
#include "llvm/IR/DataLayout.h"
#include "llvm/IR/LLVMContext.h"
#include "llvm/IR/Module.h"
#include "llvm/IRReader/IRReader.h"
#include "llvm/PassManager.h"
#include "llvm/Support/CommandLine.h"
#include "llvm/Support/FileSystem.h"
#include "llvm/Support/FormattedStream.h"
#include "llvm/Support/Host.h"
#include "llvm/Support/ManagedStatic.h"
#include "llvm/Support/Program.h"
#include "llvm/Support/raw_ostream.h"
#include "llvm/Support/Signals.h"
#include "llvm/Support/SourceMgr.h"
#include "llvm/Support/TargetRegistry.h"
#include "llvm/Support/TargetSelect.h"
#include "llvm/Support/ToolOutputFile.h"
#include "llvm/Target/TargetLibraryInfo.h"
#include "llvm/Target/TargetMachine.h"
#include <memory>
#include <unistd.h>
namespace {
using namespace llvm;
static cl::opt<std::string>
LDPath("use-ld",
cl::desc("linker"),
cl::init("/usr/bin/ld"),
cl::value_desc("filename"));
}
static void InitializeCodegen()
{
using namespace llvm;
// Initialize targets.
InitializeAllTargets();
InitializeAllTargetMCs();
InitializeAllAsmPrinters();
InitializeAllAsmParsers();
// Initialize codegen and IR passes.
PassRegistry *Registry = PassRegistry::getPassRegistry();
initializeCore(*Registry);
initializeCodeGen(*Registry);
initializeLoopStrengthReducePass(*Registry);
initializeLowerIntrinsicsPass(*Registry);
initializeUnreachableBlockElimPass(*Registry);
}
static std::unique_ptr<llvm::Module> LoadFile(char const *ProgramName,
std::string const &Filename,
llvm::LLVMContext &Context)
{
llvm::SMDiagnostic Err;
auto Result = std::unique_ptr<llvm::Module>
(llvm::ParseIRFile(Filename, Err, Context));
if (!Result)
Err.print(ProgramName, llvm::errs());
return Result;
}
/// \brief Add SeeC's instrumentation to the given Module.
/// \return true if the instrumentation was successful.
///
static bool Instrument(char const *ProgramName, llvm::Module &Module)
{
llvm::PassManager Passes;
// Add an appropriate TargetLibraryInfo pass for the module's triple.
auto Triple = llvm::Triple(Module.getTargetTriple());
if (Triple.getTriple().empty())
Triple.setTriple(llvm::sys::getDefaultTargetTriple());
Passes.add(new llvm::TargetLibraryInfo(Triple));
// Add an appropriate DataLayout instance for this module.
auto const &ModuleDataLayout = Module.getDataLayout();
if (!ModuleDataLayout.empty())
Passes.add(new llvm::DataLayout(ModuleDataLayout));
// Add SeeC's recording instrumentation pass
auto const Pass = new llvm::InsertExternalRecording();
Passes.add(Pass);
// Verify the final module
Passes.add(llvm::createVerifierPass());
// Run the passes
Passes.run(Module);
// Check if there were unhandled external functions.
for (auto Fn : Pass->getUnhandledFunctions()) {
llvm::errs() << ProgramName << ": function \""
<< Fn->getName()
<< "\" is not handled. If this function modifies memory state,"
" then SeeC will not be aware of it.\n";
}
return true;
}
static std::unique_ptr<llvm::tool_output_file>
GetTemporaryObjectStream(char const *ProgramName, llvm::SmallString<256> &Path)
{
// TODO: If we ever support Win32 then extension should be ".obj".
int FD;
auto const Err =
llvm::sys::fs::createUniqueFile("seec-instr-%%%%%%%%%%.o", FD, Path);
if (Err != llvm::errc::success) {
llvm::errs() << ProgramName << ": couldn't create temporary file.\n";
exit(EXIT_FAILURE);
}
auto Out = seec::makeUnique<llvm::tool_output_file>(Path.c_str(), FD);
if (!Out) {
llvm::errs() << ProgramName << ": couldn't create temporary file.\n";
exit(EXIT_FAILURE);
}
return Out;
}
static std::unique_ptr<llvm::tool_output_file>
Compile(char const *ProgramName,
llvm::Module &Module,
llvm::SmallString<256> &TempObjPath)
{
auto Triple = llvm::Triple(Module.getTargetTriple());
if (Triple.getTriple().empty())
Triple.setTriple(llvm::sys::getDefaultTargetTriple());
std::string ErrorMessage;
auto const Target = llvm::TargetRegistry::lookupTarget(Triple.getTriple(),
ErrorMessage);
if (!Target) {
llvm::errs() << ProgramName << ": " << ErrorMessage << "\n";
exit(EXIT_FAILURE);
}
// Target machine options.
llvm::TargetOptions Options;
std::unique_ptr<llvm::TargetMachine> Machine {
Target->createTargetMachine(Triple.getTriple(),
/* cpu */ std::string{},
/* features */ std::string{},
Options,
llvm::Reloc::Default,
llvm::CodeModel::Default,
llvm::CodeGenOpt::Default)
};
assert(Machine && "Could not allocate target machine!");
// Get an output file for the object.
auto Out = GetTemporaryObjectStream(ProgramName, TempObjPath);
// Setup all of the passes for the codegen.
llvm::PassManager Passes;
Passes.add(new llvm::TargetLibraryInfo(Triple));
Machine->addAnalysisPasses(Passes);
if (auto const *DL = Machine->getDataLayout())
Passes.add(new llvm::DataLayout(*DL));
else
Passes.add(new llvm::DataLayout(&Module));
llvm::formatted_raw_ostream FOS(Out->os());
if (Machine->addPassesToEmitFile(Passes,
FOS,
llvm::TargetMachine::CGFT_ObjectFile)) {
llvm::errs() << ProgramName << ": can't generate object file!\n";
exit(EXIT_FAILURE);
}
Passes.run(Module);
return Out;
}
static bool MaybeModule(char const *File)
{
if (File[0] == '-')
return false;
llvm::sys::fs::file_status Status;
if (llvm::sys::fs::status(File, Status) != llvm::errc::success)
return false;
if (!llvm::sys::fs::exists(Status))
return false;
// Don't attempt to read directories.
if (llvm::sys::fs::is_directory(Status))
return false;
llvm::sys::fs::file_magic Magic;
if (llvm::sys::fs::identify_magic(File, Magic) != llvm::errc::success)
return false;
switch (Magic) {
// We will attempt to read files as assembly iff they end with ".ll".
case llvm::sys::fs::file_magic::unknown:
return llvm::StringRef(File).endswith(".ll");
// Accept LLVM bitcode files.
case llvm::sys::fs::file_magic::bitcode:
return true;
// Leave all other files for the real linker.
default:
return false;
}
}
int main(int argc, char **argv)
{
llvm::llvm_shutdown_obj Y; // Call llvm_shutdown() on exit.
auto &Context = llvm::getGlobalContext();
// Setup the targets and passes required by codegen.
InitializeCodegen();
// Take all arguments that refer to LLVM bitcode files and link all of those
// files together. The remaining arguments should be placed into ForwardArgs.
std::vector<char const *> ForwardArgs;
std::unique_ptr<llvm::Module> Composite;
std::unique_ptr<llvm::Linker> Linker;
std::size_t InsertCompositePathAt = 0;
std::string ErrorMessage;
ForwardArgs.push_back(argv[0]);
for (auto i = 1; i < argc; ++i) {
if (llvm::StringRef(argv[i]) == "--seec") {
// Everything from here on in is a seec argument.
argv[i] = argv[0];
cl::ParseCommandLineOptions(argc - i, argv + i, "seec linker shim\n");
break;
}
else if (MaybeModule(argv[i])) {
// This argument is a file. Attempt to load it as an llvm::Module. If the
// load fails then silently ignore it, as the file may be a native object
// that we will pass to the real linker.
auto Module = LoadFile(argv[0], argv[i], Context);
if (Module) {
if (Linker) {
// Attempt to link this new Module to the existing Module.
if (Linker->linkInModule(Module.get(), &ErrorMessage)) {
llvm::errs() << argv[0] << ": error linking '" << argv[i] << "': "
<< ErrorMessage << "\n";
exit(EXIT_FAILURE);
}
}
else {
// This becomes our base Module.
Composite = std::move(Module);
Linker.reset(new llvm::Linker(Composite.get()));
InsertCompositePathAt = ForwardArgs.size();
}
continue;
}
}
// Whatever that argument was, it wasn't an llvm::Module, so we should
// forward it to the real linker.
ForwardArgs.push_back(argv[i]);
}
llvm::SmallString<256> TempObjPath;
std::unique_ptr<llvm::tool_output_file> TempObj;
if (Composite) {
// Instrument the linked Module, if it exists.
Instrument(argv[0], *Composite);
// Codegen this Module to an object format and write it to a temporary file.
TempObj = Compile(argv[0], *Composite, TempObjPath);
// Insert the temporary file's path into the forwarding arguments.
ForwardArgs.insert(ForwardArgs.begin() + InsertCompositePathAt,
TempObjPath.c_str());
}
else {
llvm::errs() << argv[0] << ": didn't find any llvm modules.\n";
}
// Call the real ld with the unused original arguments and the new temporary
// object file.
ForwardArgs.push_back(nullptr);
return llvm::sys::ExecuteAndWait(LDPath, ForwardArgs.data());
}
<commit_msg>Write a copy of the instrumented Module in LLVM IR to the file specified by the environment variable "SEEC_WRITE_INSTRUMENTED", if it is present.<commit_after>//===- tools/seec-ld/seec-ld.cpp ------------------------------------------===//
//
// SeeC
//
// This file is distributed under The MIT License (MIT). See LICENSE.TXT for
// details.
//
//===----------------------------------------------------------------------===//
///
/// \file
///
//===----------------------------------------------------------------------===//
#include "seec/Transforms/RecordExternal/RecordExternal.hpp"
#include "seec/Util/MakeUnique.hpp"
#include "llvm/Linker.h"
#include "llvm/ADT/Triple.h"
#include "llvm/Analysis/Verifier.h"
#include "llvm/Bitcode/ReaderWriter.h"
#include "llvm/CodeGen/LinkAllAsmWriterComponents.h"
#include "llvm/CodeGen/LinkAllCodegenComponents.h"
#include "llvm/IR/DataLayout.h"
#include "llvm/IR/LLVMContext.h"
#include "llvm/IR/Module.h"
#include "llvm/IRReader/IRReader.h"
#include "llvm/PassManager.h"
#include "llvm/Support/CommandLine.h"
#include "llvm/Support/FileSystem.h"
#include "llvm/Support/FormattedStream.h"
#include "llvm/Support/Host.h"
#include "llvm/Support/ManagedStatic.h"
#include "llvm/Support/Program.h"
#include "llvm/Support/raw_ostream.h"
#include "llvm/Support/Signals.h"
#include "llvm/Support/SourceMgr.h"
#include "llvm/Support/TargetRegistry.h"
#include "llvm/Support/TargetSelect.h"
#include "llvm/Support/ToolOutputFile.h"
#include "llvm/Target/TargetLibraryInfo.h"
#include "llvm/Target/TargetMachine.h"
#include <memory>
#include <cstdlib>
#include <unistd.h>
namespace {
using namespace llvm;
static cl::opt<std::string>
LDPath("use-ld",
cl::desc("linker"),
cl::init("/usr/bin/ld"),
cl::value_desc("filename"));
}
static void InitializeCodegen()
{
using namespace llvm;
// Initialize targets.
InitializeAllTargets();
InitializeAllTargetMCs();
InitializeAllAsmPrinters();
InitializeAllAsmParsers();
// Initialize codegen and IR passes.
PassRegistry *Registry = PassRegistry::getPassRegistry();
initializeCore(*Registry);
initializeCodeGen(*Registry);
initializeLoopStrengthReducePass(*Registry);
initializeLowerIntrinsicsPass(*Registry);
initializeUnreachableBlockElimPass(*Registry);
}
static std::unique_ptr<llvm::Module> LoadFile(char const *ProgramName,
std::string const &Filename,
llvm::LLVMContext &Context)
{
llvm::SMDiagnostic Err;
auto Result = std::unique_ptr<llvm::Module>
(llvm::ParseIRFile(Filename, Err, Context));
if (!Result)
Err.print(ProgramName, llvm::errs());
return Result;
}
/// \brief Add SeeC's instrumentation to the given Module.
/// \return true if the instrumentation was successful.
///
static bool Instrument(char const *ProgramName, llvm::Module &Module)
{
llvm::PassManager Passes;
// Add an appropriate TargetLibraryInfo pass for the module's triple.
auto Triple = llvm::Triple(Module.getTargetTriple());
if (Triple.getTriple().empty())
Triple.setTriple(llvm::sys::getDefaultTargetTriple());
Passes.add(new llvm::TargetLibraryInfo(Triple));
// Add an appropriate DataLayout instance for this module.
auto const &ModuleDataLayout = Module.getDataLayout();
if (!ModuleDataLayout.empty())
Passes.add(new llvm::DataLayout(ModuleDataLayout));
// Add SeeC's recording instrumentation pass
auto const Pass = new llvm::InsertExternalRecording();
Passes.add(Pass);
// Verify the final module
Passes.add(llvm::createVerifierPass());
// Run the passes
Passes.run(Module);
// Check if there were unhandled external functions.
for (auto Fn : Pass->getUnhandledFunctions()) {
llvm::errs() << ProgramName << ": function \""
<< Fn->getName()
<< "\" is not handled. If this function modifies memory state,"
" then SeeC will not be aware of it.\n";
}
if (auto const Path = std::getenv("SEEC_WRITE_INSTRUMENTED")) {
std::string ErrorInfo;
raw_fd_ostream Out(Path, ErrorInfo, llvm::sys::fs::OpenFlags::F_Excl);
if (ErrorInfo.empty())
Out << Module;
else
llvm::errs() << ProgramName << ": couldn't write to " << Path << ".\n";
}
return true;
}
static std::unique_ptr<llvm::tool_output_file>
GetTemporaryObjectStream(char const *ProgramName, llvm::SmallString<256> &Path)
{
// TODO: If we ever support Win32 then extension should be ".obj".
int FD;
auto const Err =
llvm::sys::fs::createUniqueFile("seec-instr-%%%%%%%%%%.o", FD, Path);
if (Err != llvm::errc::success) {
llvm::errs() << ProgramName << ": couldn't create temporary file.\n";
exit(EXIT_FAILURE);
}
auto Out = seec::makeUnique<llvm::tool_output_file>(Path.c_str(), FD);
if (!Out) {
llvm::errs() << ProgramName << ": couldn't create temporary file.\n";
exit(EXIT_FAILURE);
}
return Out;
}
static std::unique_ptr<llvm::tool_output_file>
Compile(char const *ProgramName,
llvm::Module &Module,
llvm::SmallString<256> &TempObjPath)
{
auto Triple = llvm::Triple(Module.getTargetTriple());
if (Triple.getTriple().empty())
Triple.setTriple(llvm::sys::getDefaultTargetTriple());
std::string ErrorMessage;
auto const Target = llvm::TargetRegistry::lookupTarget(Triple.getTriple(),
ErrorMessage);
if (!Target) {
llvm::errs() << ProgramName << ": " << ErrorMessage << "\n";
exit(EXIT_FAILURE);
}
// Target machine options.
llvm::TargetOptions Options;
std::unique_ptr<llvm::TargetMachine> Machine {
Target->createTargetMachine(Triple.getTriple(),
/* cpu */ std::string{},
/* features */ std::string{},
Options,
llvm::Reloc::Default,
llvm::CodeModel::Default,
llvm::CodeGenOpt::Default)
};
assert(Machine && "Could not allocate target machine!");
// Get an output file for the object.
auto Out = GetTemporaryObjectStream(ProgramName, TempObjPath);
// Setup all of the passes for the codegen.
llvm::PassManager Passes;
Passes.add(new llvm::TargetLibraryInfo(Triple));
Machine->addAnalysisPasses(Passes);
if (auto const *DL = Machine->getDataLayout())
Passes.add(new llvm::DataLayout(*DL));
else
Passes.add(new llvm::DataLayout(&Module));
llvm::formatted_raw_ostream FOS(Out->os());
if (Machine->addPassesToEmitFile(Passes,
FOS,
llvm::TargetMachine::CGFT_ObjectFile)) {
llvm::errs() << ProgramName << ": can't generate object file!\n";
exit(EXIT_FAILURE);
}
Passes.run(Module);
return Out;
}
static bool MaybeModule(char const *File)
{
if (File[0] == '-')
return false;
llvm::sys::fs::file_status Status;
if (llvm::sys::fs::status(File, Status) != llvm::errc::success)
return false;
if (!llvm::sys::fs::exists(Status))
return false;
// Don't attempt to read directories.
if (llvm::sys::fs::is_directory(Status))
return false;
llvm::sys::fs::file_magic Magic;
if (llvm::sys::fs::identify_magic(File, Magic) != llvm::errc::success)
return false;
switch (Magic) {
// We will attempt to read files as assembly iff they end with ".ll".
case llvm::sys::fs::file_magic::unknown:
return llvm::StringRef(File).endswith(".ll");
// Accept LLVM bitcode files.
case llvm::sys::fs::file_magic::bitcode:
return true;
// Leave all other files for the real linker.
default:
return false;
}
}
int main(int argc, char **argv)
{
llvm::llvm_shutdown_obj Y; // Call llvm_shutdown() on exit.
auto &Context = llvm::getGlobalContext();
// Setup the targets and passes required by codegen.
InitializeCodegen();
// Take all arguments that refer to LLVM bitcode files and link all of those
// files together. The remaining arguments should be placed into ForwardArgs.
std::vector<char const *> ForwardArgs;
std::unique_ptr<llvm::Module> Composite;
std::unique_ptr<llvm::Linker> Linker;
std::size_t InsertCompositePathAt = 0;
std::string ErrorMessage;
ForwardArgs.push_back(argv[0]);
for (auto i = 1; i < argc; ++i) {
if (llvm::StringRef(argv[i]) == "--seec") {
// Everything from here on in is a seec argument.
argv[i] = argv[0];
cl::ParseCommandLineOptions(argc - i, argv + i, "seec linker shim\n");
break;
}
else if (MaybeModule(argv[i])) {
// This argument is a file. Attempt to load it as an llvm::Module. If the
// load fails then silently ignore it, as the file may be a native object
// that we will pass to the real linker.
auto Module = LoadFile(argv[0], argv[i], Context);
if (Module) {
if (Linker) {
// Attempt to link this new Module to the existing Module.
if (Linker->linkInModule(Module.get(), &ErrorMessage)) {
llvm::errs() << argv[0] << ": error linking '" << argv[i] << "': "
<< ErrorMessage << "\n";
exit(EXIT_FAILURE);
}
}
else {
// This becomes our base Module.
Composite = std::move(Module);
Linker.reset(new llvm::Linker(Composite.get()));
InsertCompositePathAt = ForwardArgs.size();
}
continue;
}
}
// Whatever that argument was, it wasn't an llvm::Module, so we should
// forward it to the real linker.
ForwardArgs.push_back(argv[i]);
}
llvm::SmallString<256> TempObjPath;
std::unique_ptr<llvm::tool_output_file> TempObj;
if (Composite) {
// Instrument the linked Module, if it exists.
Instrument(argv[0], *Composite);
// Codegen this Module to an object format and write it to a temporary file.
TempObj = Compile(argv[0], *Composite, TempObjPath);
// Insert the temporary file's path into the forwarding arguments.
ForwardArgs.insert(ForwardArgs.begin() + InsertCompositePathAt,
TempObjPath.c_str());
}
else {
llvm::errs() << argv[0] << ": didn't find any llvm modules.\n";
}
// Call the real ld with the unused original arguments and the new temporary
// object file.
ForwardArgs.push_back(nullptr);
return llvm::sys::ExecuteAndWait(LDPath, ForwardArgs.data());
}
<|endoftext|> |
<commit_before>/********************************************************************
* AUTHORS: Vijay Ganesh, Trevor Hansen, Mate Soos
*
* BEGIN DATE: November, 2005
*
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 "main_common.h"
#include "extlib-abc/cnf_short.h"
extern int smtparse(void*);
extern int smt2parse();
extern int cvcparse(void*);
extern int cvclex_destroy(void);
extern int smtlex_destroy(void);
extern int smt2lex_destroy(void);
extern void errorHandler(const char* error_msg);
// Amount of memory to ask for at beginning of main.
extern const intptr_t INITIAL_MEMORY_PREALLOCATION_SIZE;
extern FILE* cvcin;
extern FILE* smtin;
extern FILE* smt2in;
#ifdef EXT_HASH_MAP
using namespace __gnu_cxx;
#endif
using namespace BEEV;
using std::auto_ptr;
using std::cout;
using std::cerr;
using std::endl;
void errorHandler(const char* error_msg)
{
cerr << prog << ": Error: " << error_msg << endl;
exit(-1);
}
// Amount of memory to ask for at beginning of main.
const intptr_t INITIAL_MEMORY_PREALLOCATION_SIZE = 4000000;
Main::Main() : onePrintBack(false)
{
bm = NULL;
toClose = NULL;
cvcin = NULL;
smtin = NULL;
smt2in = NULL;
// Register the error handler
vc_error_hdlr = errorHandler;
#if !defined(__MINGW32__) && !defined(__MINGW64__) && !defined(_MSC_VER)
// Grab some memory from the OS upfront to reduce system time when
// individual hash tables are being allocated
if (sbrk(INITIAL_MEMORY_PREALLOCATION_SIZE) == ((void*)-1))
{
FatalError("Initial allocation of memory failed.");
}
#endif
bm = new STPMgr();
GlobalParserBM = bm;
}
Main::~Main()
{
delete bm;
}
void Main::parse_file(ASTVec* AssertsQuery)
{
TypeChecker nfTypeCheckSimp(*bm->defaultNodeFactory, *bm);
TypeChecker nfTypeCheckDefault(*bm->hashingNodeFactory, *bm);
Cpp_interface piTypeCheckSimp(*bm, &nfTypeCheckSimp);
Cpp_interface piTypeCheckDefault(*bm, &nfTypeCheckDefault);
// If you are converting formats, you probably don't want it simplifying (at
// least I dont).
if (onePrintBack)
{
GlobalParserInterface = &piTypeCheckDefault;
}
else
{
GlobalParserInterface = &piTypeCheckSimp;
}
GlobalParserInterface->startup();
if (onePrintBack)
{
if (bm->UserFlags.smtlib2_parser_flag)
{
cerr << "Printback from SMTLIB2 inputs isn't currently working." << endl;
cerr << "Please try again later" << endl;
cerr << "It works prior to revision 1354" << endl;
exit(1);
}
}
if (bm->UserFlags.smtlib1_parser_flag)
{
smtparse((void*)AssertsQuery);
smtlex_destroy();
}
else if (bm->UserFlags.smtlib2_parser_flag)
{
smt2parse();
smt2lex_destroy();
}
else
{
cvcparse((void*)AssertsQuery);
cvclex_destroy();
}
GlobalParserInterface = NULL;
if (toClose != NULL)
{
fclose(toClose);
}
}
void Main::print_back(ASTNode& query, ASTNode& asserts)
{
ASTNode original_input =
bm->CreateNode(AND, bm->CreateNode(NOT, query), asserts);
if (bm->UserFlags.print_STPinput_back_flag)
{
if (bm->UserFlags.smtlib1_parser_flag)
{
bm->UserFlags.print_STPinput_back_SMTLIB2_flag = true;
}
else
{
bm->UserFlags.print_STPinput_back_CVC_flag = true;
}
}
if (bm->UserFlags.print_STPinput_back_CVC_flag)
{
// needs just the query. Reads the asserts out of the data structure.
print_STPInput_Back(original_input);
}
if (bm->UserFlags.print_STPinput_back_SMTLIB1_flag)
{
printer::SMTLIB1_PrintBack(cout, original_input);
}
if (bm->UserFlags.print_STPinput_back_SMTLIB2_flag)
{
printer::SMTLIB2_PrintBack(cout, original_input);
}
if (bm->UserFlags.print_STPinput_back_C_flag)
{
printer::C_Print(cout, original_input);
}
if (bm->UserFlags.print_STPinput_back_GDL_flag)
{
printer::GDL_Print(cout, original_input);
}
if (bm->UserFlags.print_STPinput_back_dot_flag)
{
printer::Dot_Print(cout, original_input);
}
}
void Main::read_file()
{
bool error = false;
if (bm->UserFlags.smtlib1_parser_flag)
{
smtin = fopen(infile.c_str(), "r");
toClose = smtin;
if (smtin == NULL)
{
error = true;
}
}
else if (bm->UserFlags.smtlib2_parser_flag)
{
smt2in = fopen(infile.c_str(), "r");
toClose = smt2in;
if (smt2in == NULL)
{
error = true;
}
}
else
{
cvcin = fopen(infile.c_str(), "r");
toClose = cvcin;
if (cvcin == NULL)
{
error = true;
}
}
if (error)
{
std::string errorMsg("Cannot open ");
errorMsg += infile;
FatalError(errorMsg.c_str());
}
}
int Main::create_and_parse_options(int argc, char** argv)
{
return 0;
}
void Main::check_infile_type()
{
if (infile.size() >= 5)
{
if (!infile.compare(infile.length() - 4, 4, ".smt"))
{
bm->UserFlags.division_by_zero_returns_one_flag = true;
bm->UserFlags.smtlib1_parser_flag = true;
}
if (!infile.compare(infile.length() - 5, 5, ".smt2"))
{
bm->UserFlags.division_by_zero_returns_one_flag = true;
bm->UserFlags.smtlib2_parser_flag = true;
}
}
}
int Main::main(int argc, char** argv)
{
auto_ptr<SimplifyingNodeFactory> simplifyingNF(
new SimplifyingNodeFactory(*bm->hashingNodeFactory, *bm));
bm->defaultNodeFactory = simplifyingNF.get();
auto_ptr<Simplifier> simp(new Simplifier(bm));
auto_ptr<ArrayTransformer> arrayTransformer(new ArrayTransformer(bm, simp.get()));
auto_ptr<ToSAT> tosat(new ToSAT(bm));
auto_ptr<AbsRefine_CounterExample> Ctr_Example(
new AbsRefine_CounterExample(bm, simp.get(), arrayTransformer.get()));
int ret = create_and_parse_options(argc, argv);
if (ret != 0)
{
return ret;
}
GlobalSTP = new STP(bm, simp.get(), arrayTransformer.get(), tosat.get(),
Ctr_Example.get());
// If we're not reading the file from stdin.
if (!infile.empty())
read_file();
// want to print the output always from the commandline.
bm->UserFlags.print_output_flag = true;
ASTVec* AssertsQuery = new ASTVec;
bm->GetRunTimes()->start(RunTimes::Parsing);
parse_file(AssertsQuery);
bm->GetRunTimes()->stop(RunTimes::Parsing);
/* The SMTLIB2 has a command language. The parser calls all the functions,
* so when we get to here the parser has already called "exit". i.e. if the
* language is smt2 then all the work has already been done, and all we need
* to do is cleanup...
* */
if (!bm->UserFlags.smtlib2_parser_flag)
{
if (AssertsQuery->empty())
FatalError("Input is Empty. Please enter some asserts and query\n");
if (AssertsQuery->size() != 2)
FatalError("Input must contain a query\n");
ASTNode asserts = (*AssertsQuery)[0];
ASTNode query = (*AssertsQuery)[1];
if (onePrintBack)
{
print_back(query, asserts);
return 0;
}
SOLVER_RETURN_TYPE ret = GlobalSTP->TopLevelSTP(asserts, query);
if (bm->UserFlags.quick_statistics_flag)
{
bm->GetRunTimes()->print();
}
GlobalSTP->tosat->PrintOutput(ret);
asserts = ASTNode();
query = ASTNode();
}
// Without cleanup
if (bm->UserFlags.isSet("fast-exit", "1"))
exit(0);
//Cleanup
AssertsQuery->clear();
delete AssertsQuery;
_empty_ASTVec.clear();
delete GlobalSTP;
Cnf_ClearMemory();
return 0;
}<commit_msg>Removing useless comment<commit_after>/********************************************************************
* AUTHORS: Vijay Ganesh, Trevor Hansen, Mate Soos
*
* BEGIN DATE: November, 2005
*
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 "main_common.h"
#include "extlib-abc/cnf_short.h"
extern int smtparse(void*);
extern int smt2parse();
extern int cvcparse(void*);
extern int cvclex_destroy(void);
extern int smtlex_destroy(void);
extern int smt2lex_destroy(void);
extern void errorHandler(const char* error_msg);
// Amount of memory to ask for at beginning of main.
extern const intptr_t INITIAL_MEMORY_PREALLOCATION_SIZE;
extern FILE* cvcin;
extern FILE* smtin;
extern FILE* smt2in;
#ifdef EXT_HASH_MAP
using namespace __gnu_cxx;
#endif
using namespace BEEV;
using std::auto_ptr;
using std::cout;
using std::cerr;
using std::endl;
void errorHandler(const char* error_msg)
{
cerr << prog << ": Error: " << error_msg << endl;
exit(-1);
}
// Amount of memory to ask for at beginning of main.
const intptr_t INITIAL_MEMORY_PREALLOCATION_SIZE = 4000000;
Main::Main() : onePrintBack(false)
{
bm = NULL;
toClose = NULL;
cvcin = NULL;
smtin = NULL;
smt2in = NULL;
// Register the error handler
vc_error_hdlr = errorHandler;
#if !defined(__MINGW32__) && !defined(__MINGW64__) && !defined(_MSC_VER)
// Grab some memory from the OS upfront to reduce system time when
// individual hash tables are being allocated
if (sbrk(INITIAL_MEMORY_PREALLOCATION_SIZE) == ((void*)-1))
{
FatalError("Initial allocation of memory failed.");
}
#endif
bm = new STPMgr();
GlobalParserBM = bm;
}
Main::~Main()
{
delete bm;
}
void Main::parse_file(ASTVec* AssertsQuery)
{
TypeChecker nfTypeCheckSimp(*bm->defaultNodeFactory, *bm);
TypeChecker nfTypeCheckDefault(*bm->hashingNodeFactory, *bm);
Cpp_interface piTypeCheckSimp(*bm, &nfTypeCheckSimp);
Cpp_interface piTypeCheckDefault(*bm, &nfTypeCheckDefault);
// If you are converting formats, you probably don't want it simplifying
if (onePrintBack)
{
GlobalParserInterface = &piTypeCheckDefault;
}
else
{
GlobalParserInterface = &piTypeCheckSimp;
}
GlobalParserInterface->startup();
if (onePrintBack)
{
if (bm->UserFlags.smtlib2_parser_flag)
{
cerr << "Printback from SMTLIB2 inputs isn't currently working." << endl;
cerr << "Please try again later" << endl;
cerr << "It works prior to revision 1354" << endl;
exit(1);
}
}
if (bm->UserFlags.smtlib1_parser_flag)
{
smtparse((void*)AssertsQuery);
smtlex_destroy();
}
else if (bm->UserFlags.smtlib2_parser_flag)
{
smt2parse();
smt2lex_destroy();
}
else
{
cvcparse((void*)AssertsQuery);
cvclex_destroy();
}
GlobalParserInterface = NULL;
if (toClose != NULL)
{
fclose(toClose);
}
}
void Main::print_back(ASTNode& query, ASTNode& asserts)
{
ASTNode original_input =
bm->CreateNode(AND, bm->CreateNode(NOT, query), asserts);
if (bm->UserFlags.print_STPinput_back_flag)
{
if (bm->UserFlags.smtlib1_parser_flag)
{
bm->UserFlags.print_STPinput_back_SMTLIB2_flag = true;
}
else
{
bm->UserFlags.print_STPinput_back_CVC_flag = true;
}
}
if (bm->UserFlags.print_STPinput_back_CVC_flag)
{
// needs just the query. Reads the asserts out of the data structure.
print_STPInput_Back(original_input);
}
if (bm->UserFlags.print_STPinput_back_SMTLIB1_flag)
{
printer::SMTLIB1_PrintBack(cout, original_input);
}
if (bm->UserFlags.print_STPinput_back_SMTLIB2_flag)
{
printer::SMTLIB2_PrintBack(cout, original_input);
}
if (bm->UserFlags.print_STPinput_back_C_flag)
{
printer::C_Print(cout, original_input);
}
if (bm->UserFlags.print_STPinput_back_GDL_flag)
{
printer::GDL_Print(cout, original_input);
}
if (bm->UserFlags.print_STPinput_back_dot_flag)
{
printer::Dot_Print(cout, original_input);
}
}
void Main::read_file()
{
bool error = false;
if (bm->UserFlags.smtlib1_parser_flag)
{
smtin = fopen(infile.c_str(), "r");
toClose = smtin;
if (smtin == NULL)
{
error = true;
}
}
else if (bm->UserFlags.smtlib2_parser_flag)
{
smt2in = fopen(infile.c_str(), "r");
toClose = smt2in;
if (smt2in == NULL)
{
error = true;
}
}
else
{
cvcin = fopen(infile.c_str(), "r");
toClose = cvcin;
if (cvcin == NULL)
{
error = true;
}
}
if (error)
{
std::string errorMsg("Cannot open ");
errorMsg += infile;
FatalError(errorMsg.c_str());
}
}
int Main::create_and_parse_options(int argc, char** argv)
{
return 0;
}
void Main::check_infile_type()
{
if (infile.size() >= 5)
{
if (!infile.compare(infile.length() - 4, 4, ".smt"))
{
bm->UserFlags.division_by_zero_returns_one_flag = true;
bm->UserFlags.smtlib1_parser_flag = true;
}
if (!infile.compare(infile.length() - 5, 5, ".smt2"))
{
bm->UserFlags.division_by_zero_returns_one_flag = true;
bm->UserFlags.smtlib2_parser_flag = true;
}
}
}
int Main::main(int argc, char** argv)
{
auto_ptr<SimplifyingNodeFactory> simplifyingNF(
new SimplifyingNodeFactory(*bm->hashingNodeFactory, *bm));
bm->defaultNodeFactory = simplifyingNF.get();
auto_ptr<Simplifier> simp(new Simplifier(bm));
auto_ptr<ArrayTransformer> arrayTransformer(new ArrayTransformer(bm, simp.get()));
auto_ptr<ToSAT> tosat(new ToSAT(bm));
auto_ptr<AbsRefine_CounterExample> Ctr_Example(
new AbsRefine_CounterExample(bm, simp.get(), arrayTransformer.get()));
int ret = create_and_parse_options(argc, argv);
if (ret != 0)
{
return ret;
}
GlobalSTP = new STP(bm, simp.get(), arrayTransformer.get(), tosat.get(),
Ctr_Example.get());
// If we're not reading the file from stdin.
if (!infile.empty())
read_file();
// want to print the output always from the commandline.
bm->UserFlags.print_output_flag = true;
ASTVec* AssertsQuery = new ASTVec;
bm->GetRunTimes()->start(RunTimes::Parsing);
parse_file(AssertsQuery);
bm->GetRunTimes()->stop(RunTimes::Parsing);
/* The SMTLIB2 has a command language. The parser calls all the functions,
* so when we get to here the parser has already called "exit". i.e. if the
* language is smt2 then all the work has already been done, and all we need
* to do is cleanup...
* */
if (!bm->UserFlags.smtlib2_parser_flag)
{
if (AssertsQuery->empty())
FatalError("Input is Empty. Please enter some asserts and query\n");
if (AssertsQuery->size() != 2)
FatalError("Input must contain a query\n");
ASTNode asserts = (*AssertsQuery)[0];
ASTNode query = (*AssertsQuery)[1];
if (onePrintBack)
{
print_back(query, asserts);
return 0;
}
SOLVER_RETURN_TYPE ret = GlobalSTP->TopLevelSTP(asserts, query);
if (bm->UserFlags.quick_statistics_flag)
{
bm->GetRunTimes()->print();
}
GlobalSTP->tosat->PrintOutput(ret);
asserts = ASTNode();
query = ASTNode();
}
// Without cleanup
if (bm->UserFlags.isSet("fast-exit", "1"))
exit(0);
//Cleanup
AssertsQuery->clear();
delete AssertsQuery;
_empty_ASTVec.clear();
delete GlobalSTP;
Cnf_ClearMemory();
return 0;
}<|endoftext|> |
<commit_before>/*************************************************************************
*
* $RCSfile: hashtbl.cxx,v $
*
* $Revision: 1.2 $
*
* last change: $Author: hr $ $Date: 2001-10-12 16:14:16 $
*
* The Contents of this file are made available subject to the terms of
* either of the following licenses
*
* - GNU Lesser General Public License Version 2.1
* - Sun Industry Standards Source License Version 1.1
*
* Sun Microsystems Inc., October, 2000
*
* GNU Lesser General Public License Version 2.1
* =============================================
* Copyright 2000 by Sun Microsystems, Inc.
* 901 San Antonio Road, Palo Alto, CA 94303, USA
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License version 2.1, as published by the Free Software Foundation.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston,
* MA 02111-1307 USA
*
*
* Sun Industry Standards Source License Version 1.1
* =================================================
* The contents of this file are subject to the Sun Industry Standards
* Source License Version 1.1 (the "License"); You may not use this file
* except in compliance with the License. You may obtain a copy of the
* License at http://www.openoffice.org/license.html.
*
* Software provided under this License is provided on an "AS IS" basis,
* WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING,
* WITHOUT LIMITATION, WARRANTIES THAT THE SOFTWARE IS FREE OF DEFECTS,
* MERCHANTABLE, FIT FOR A PARTICULAR PURPOSE, OR NON-INFRINGING.
* See the License for the specific provisions governing your rights and
* obligations concerning the Software.
*
* The Initial Developer of the Original Code is: Sun Microsystems, Inc.
*
* Copyright: 2000 by Sun Microsystems, Inc.
*
* All Rights Reserved.
*
* Contributor(s): _______________________________________
*
*
************************************************************************/
#include <tlgen.hxx>
#include "hashtbl.hxx"
#include <algorithm>
// -------------------------------------------------------------
// class HashItem
//
class HashItem
{
enum ETag { TAG_EMPTY, TAG_USED, TAG_DELETED };
void* m_pObject;
ETag m_Tag;
String m_Key;
public:
HashItem() { m_Tag = TAG_EMPTY; m_pObject = NULL; }
BOOL IsDeleted() const
{ return m_Tag == TAG_DELETED; }
BOOL IsEmpty() const
{ return m_Tag == TAG_DELETED || m_Tag == TAG_EMPTY; }
BOOL IsFree() const
{ return m_Tag == TAG_EMPTY; }
BOOL IsUsed() const
{ return m_Tag == TAG_USED; }
void Delete()
{ m_Tag = TAG_DELETED; m_Key = ""; m_pObject = NULL; }
String const& GetKey() const
{ return m_Key; }
void* GetObject() const
{ return m_pObject; }
void SetObject(String const Key, void *pObject)
{ m_Tag = TAG_USED; m_Key = Key; m_pObject = pObject; }
};
// #define MIN(a,b) (a)<(b)?(a):(b)
// #define MAX(a,b) (a)>(b)?(a):(b)
// -------------------------------------------------------------
// class HashTable
//
/*static*/ double HashTable::m_defMaxLoadFactor = 0.8;
/*static*/ double HashTable::m_defDefGrowFactor = 2.0;
HashTable::HashTable(ULONG lSize, BOOL bOwner, double dMaxLoadFactor, double dGrowFactor)
{
m_lSize = lSize;
m_bOwner = bOwner;
m_lElem = 0;
m_dMaxLoadFactor = std::max(0.5,std::min(1.0,dMaxLoadFactor)); // 0.5 ... 1.0
m_dGrowFactor = std::max(1.3,(5.0,dGrowFactor)); // 1.3 ... 5.0
m_pData = new HashItem [lSize];
// Statistik
#ifdef DBG_UTIL
m_aStatistic.m_lSingleHash = 0;
m_aStatistic.m_lDoubleHash = 0;
m_aStatistic.m_lProbe = 0;
#endif
}
HashTable::~HashTable()
{
// Wenn die HashTable der Owner der Objecte ist,
// mssen die Destruktoren separat gerufen werden.
// Dies geschieht ber die virtuelle Methode OnDeleteObject()
//
// Problem: Virtuelle Funktionen sind im Destructor nicht virtuell!!
// Der Code mu deshalb ins Macro
/*
if (m_bOwner)
{
for (ULONG i=0; i<GetSize(); i++)
{
void *pObject = GetObjectAt(i);
if (pObject != NULL)
OnDeleteObject(pObject());
}
}
*/
// Speicher fr HashItems freigeben
delete [] m_pData;
}
void* HashTable::GetObjectAt(ULONG lPos) const
// Gibt Objekt zurck, wenn es eines gibt, sonst NULL;
{
DBG_ASSERT(lPos<m_lSize, "HashTable::GetObjectAt()");
HashItem *pItem = &m_pData[lPos];
return pItem->IsUsed() ? pItem->GetObject() : NULL;
}
void HashTable::OnDeleteObject(void*)
{
DBG_ERROR("HashTable::OnDeleteObject(void*) nicht berladen")
}
ULONG HashTable::Hash(String const& Key) const
{
/*
ULONG lHash = 0;
ULONG i,n;
for (i=0,n=Key.Len(); i<n; i++)
{
lHash *= 256L;
lHash += (ULONG)(USHORT)Key.GetStr()[i];
lHash %= m_lSize;
}
return lHash;
*/
// Hashfunktion von P.J. Weinberger
// aus dem "Drachenbuch" von Aho/Sethi/Ullman
ULONG i,n;
ULONG h = 0;
ULONG g = 0;
for (i=0,n=Key.Len(); i<n; i++)
{
h = (h<<4) + (ULONG)(USHORT)Key.GetStr()[i];
g = h & 0xf0000000;
if (g != 0)
{
h = h ^ (g >> 24);
h = h ^ g;
}
}
return h % m_lSize;
}
ULONG HashTable::DHash(String const& Key, ULONG lOldHash) const
{
ULONG lHash = lOldHash;
ULONG i,n;
for (i=0,n=Key.Len(); i<n; i++)
{
lHash *= 256L;
lHash += (ULONG)(USHORT)Key.GetStr()[i];
lHash %= m_lSize;
}
return lHash;
/* return
(
lHash
+ (char)Key.GetStr()[0] * 256
+ (char)Key.GetStr()[Key.Len()-1]
+ 1
)
% m_lSize;
*/
}
ULONG HashTable::Probe(ULONG lPos) const
// gibt den Folgewert von lPos zurck
{
lPos++; if (lPos==m_lSize) lPos=0;
return lPos;
}
BOOL HashTable::IsFull() const
{
return m_lElem>=m_lSize;
}
BOOL HashTable::Insert(String const& Key, void* pObject)
// pre: Key ist nicht im Dictionary enthalten, sonst return FALSE
// Dictionary ist nicht voll, sonst return FALSE
// post: pObject ist unter Key im Dictionary; m_nElem wurde erhht
{
SmartGrow();
if (IsFull())
{
DBG_ERROR("HashTable::Insert() is full");
return FALSE;
}
if (FindPos(Key) != NULL )
return FALSE;
ULONG lPos = Hash(Key);
HashItem *pItem = &m_pData[lPos];
// first hashing
//
if (pItem->IsEmpty())
{
pItem->SetObject(Key, pObject);
m_lElem++;
#ifdef DBG_UTIL
m_aStatistic.m_lSingleHash++;
#endif
return TRUE;
}
// double hashing
//
lPos = DHash(Key,lPos);
pItem = &m_pData[lPos];
if (pItem->IsEmpty())
{
pItem->SetObject(Key, pObject);
m_lElem++;
#ifdef DBG_UTIL
m_aStatistic.m_lDoubleHash++;
#endif
return TRUE;
}
// linear probing
//
do
{
#ifdef DBG_UTIL
m_aStatistic.m_lProbe++;
#endif
lPos = Probe(lPos);
pItem = &m_pData[lPos];
}
while(!pItem->IsEmpty());
pItem->SetObject(Key, pObject);
m_lElem++;
return TRUE;
}
HashItem* HashTable::FindPos(String const& Key) const
// sucht den Key; gibt Refrenz auf den Eintrag (gefunden)
// oder NULL (nicht gefunden) zurck
//
// pre: -
// post: -
{
// first hashing
//
ULONG lPos = Hash(Key);
HashItem *pItem = &m_pData[lPos];
if (pItem->IsUsed()
&& pItem->GetKey() == Key)
{
return pItem;
}
// double hashing
//
if (pItem->IsDeleted() || pItem->IsUsed())
{
lPos = DHash(Key,lPos);
pItem = &m_pData[lPos];
if (pItem->IsUsed()
&& pItem->GetKey() == Key)
{
return pItem;
}
// linear probing
//
if (pItem->IsDeleted() || pItem->IsUsed())
{
ULONG n = 0;
BOOL bFound = FALSE;
BOOL bEnd = FALSE;
do
{
n++;
lPos = Probe(lPos);
pItem = &m_pData[lPos];
bFound = pItem->IsUsed()
&& pItem->GetKey() == Key;
bEnd = !(n<m_lSize || pItem->IsFree());
}
while(!bFound && !bEnd);
return bFound ? pItem : NULL;
}
}
// nicht gefunden
//
return NULL;
}
void* HashTable::Find(String const& Key) const
// Gibt Verweis des Objektes zurck, das unter Key abgespeichert ist,
// oder NULL wenn nicht vorhanden.
//
// pre: -
// post: -
{
HashItem *pItem = FindPos(Key);
if (pItem != NULL
&& pItem->GetKey() == Key)
return pItem->GetObject();
else
return NULL;
}
void* HashTable::Delete(String const& Key)
// Lscht Objekt, das unter Key abgespeichert ist und gibt Verweis
// darauf zurck.
// Gibt NULL zurck, wenn Key nicht vorhanden ist.
//
// pre: -
// post: Objekt ist nicht mehr enthalten; m_lElem dekrementiert
// Wenn die HashTable der Owner ist, wurde das Object gelscht
{
HashItem *pItem = FindPos(Key);
if (pItem != NULL
&& pItem->GetKey() == Key)
{
void* pObject = pItem->GetObject();
if (m_bOwner)
OnDeleteObject(pObject);
pItem->Delete();
m_lElem--;
return pObject;
}
else
{
return NULL;
}
}
double HashTable::CalcLoadFactor() const
// prozentuale Belegung der Hashtabelle berechnen
{
return double(m_lElem) / double(m_lSize);
}
void HashTable::SmartGrow()
// Achtung: da die Objekte umkopiert werden, darf die OnDeleteObject-Methode
// nicht gerufen werden
{
double dLoadFactor = CalcLoadFactor();
if (dLoadFactor <= m_dMaxLoadFactor)
return; // nothing to grow
ULONG lOldSize = m_lSize; // alte Daten sichern
HashItem* pOldData = m_pData;
m_lSize = ULONG (m_dGrowFactor * m_lSize); // neue Gre
m_pData = new HashItem[m_lSize]; // neue Daten holen
// kein Speicher:
// Zustand "Tabelle voll" wird in Insert abgefangen
//
if (m_pData == NULL)
{
m_lSize = lOldSize;
m_pData = pOldData;
return;
}
m_lElem = 0; // noch keine neuen Daten
// Umkopieren der Daten
//
for (ULONG i=0; i<lOldSize; i++)
{
HashItem *pItem = &pOldData[i];
if (pItem->IsUsed())
Insert(pItem->GetKey(),pItem->GetObject());
}
delete [] pOldData;
}
// Iterator ---------------------------------------------------------
//
HashTableIterator::HashTableIterator(HashTable const& aTable)
: m_aTable(aTable)
{
m_lAt = 0;
}
void* HashTableIterator::GetFirst()
{
m_lAt = 0;
return FindValidObject(TRUE /* forward */);
}
void* HashTableIterator::GetLast()
{
m_lAt = m_aTable.GetSize() -1;
return FindValidObject(FALSE /* backward */);
}
void* HashTableIterator::GetNext()
{
if (m_lAt+1 >= m_aTable.GetSize())
return NULL;
m_lAt++;
return FindValidObject(TRUE /* forward */);
}
void* HashTableIterator::GetPrev()
{
if (m_lAt <= 0)
return NULL;
m_lAt--;
return FindValidObject(FALSE /* backward */);
}
void* HashTableIterator::FindValidObject(BOOL bForward)
// Sucht nach einem vorhandenen Objekt ab der aktuellen
// Position.
//
// pre: ab inkl. m_lAt soll die Suche beginnen
// post: if not found then
// if bForward == TRUE then
// m_lAt == m_aTable.GetSize() -1
// else
// m_lAt == 0
// else
// m_lAt ist die gefundene Position
{
void *pObject = m_aTable.GetObjectAt(m_lAt);
if (pObject != NULL)
return pObject;
while (pObject == NULL
&& (bForward ? ((m_lAt+1) < m_aTable.GetSize())
: m_lAt > 0))
{
if (bForward)
m_lAt++;
else
m_lAt--;
pObject = m_aTable.GetObjectAt(m_lAt);
}
#ifdef DBG_UTIL
if (pObject == NULL)
{
DBG_ASSERT(bForward ? m_lAt == m_aTable.GetSize() -1 : m_lAt == 0,
"HashTableIterator::FindValidObject()");
}
#endif
return pObject;
}
<commit_msg>INTEGRATION: CWS ooo19126 (1.2.406); FILE MERGED 2005/09/05 13:59:51 rt 1.2.406.1: #i54170# Change license header: remove SISSL<commit_after>/*************************************************************************
*
* OpenOffice.org - a multi-platform office productivity suite
*
* $RCSfile: hashtbl.cxx,v $
*
* $Revision: 1.3 $
*
* last change: $Author: rt $ $Date: 2005-09-09 14:52:12 $
*
* 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 <tlgen.hxx>
#include "hashtbl.hxx"
#include <algorithm>
// -------------------------------------------------------------
// class HashItem
//
class HashItem
{
enum ETag { TAG_EMPTY, TAG_USED, TAG_DELETED };
void* m_pObject;
ETag m_Tag;
String m_Key;
public:
HashItem() { m_Tag = TAG_EMPTY; m_pObject = NULL; }
BOOL IsDeleted() const
{ return m_Tag == TAG_DELETED; }
BOOL IsEmpty() const
{ return m_Tag == TAG_DELETED || m_Tag == TAG_EMPTY; }
BOOL IsFree() const
{ return m_Tag == TAG_EMPTY; }
BOOL IsUsed() const
{ return m_Tag == TAG_USED; }
void Delete()
{ m_Tag = TAG_DELETED; m_Key = ""; m_pObject = NULL; }
String const& GetKey() const
{ return m_Key; }
void* GetObject() const
{ return m_pObject; }
void SetObject(String const Key, void *pObject)
{ m_Tag = TAG_USED; m_Key = Key; m_pObject = pObject; }
};
// #define MIN(a,b) (a)<(b)?(a):(b)
// #define MAX(a,b) (a)>(b)?(a):(b)
// -------------------------------------------------------------
// class HashTable
//
/*static*/ double HashTable::m_defMaxLoadFactor = 0.8;
/*static*/ double HashTable::m_defDefGrowFactor = 2.0;
HashTable::HashTable(ULONG lSize, BOOL bOwner, double dMaxLoadFactor, double dGrowFactor)
{
m_lSize = lSize;
m_bOwner = bOwner;
m_lElem = 0;
m_dMaxLoadFactor = std::max(0.5,std::min(1.0,dMaxLoadFactor)); // 0.5 ... 1.0
m_dGrowFactor = std::max(1.3,(5.0,dGrowFactor)); // 1.3 ... 5.0
m_pData = new HashItem [lSize];
// Statistik
#ifdef DBG_UTIL
m_aStatistic.m_lSingleHash = 0;
m_aStatistic.m_lDoubleHash = 0;
m_aStatistic.m_lProbe = 0;
#endif
}
HashTable::~HashTable()
{
// Wenn die HashTable der Owner der Objecte ist,
// mssen die Destruktoren separat gerufen werden.
// Dies geschieht ber die virtuelle Methode OnDeleteObject()
//
// Problem: Virtuelle Funktionen sind im Destructor nicht virtuell!!
// Der Code mu deshalb ins Macro
/*
if (m_bOwner)
{
for (ULONG i=0; i<GetSize(); i++)
{
void *pObject = GetObjectAt(i);
if (pObject != NULL)
OnDeleteObject(pObject());
}
}
*/
// Speicher fr HashItems freigeben
delete [] m_pData;
}
void* HashTable::GetObjectAt(ULONG lPos) const
// Gibt Objekt zurck, wenn es eines gibt, sonst NULL;
{
DBG_ASSERT(lPos<m_lSize, "HashTable::GetObjectAt()");
HashItem *pItem = &m_pData[lPos];
return pItem->IsUsed() ? pItem->GetObject() : NULL;
}
void HashTable::OnDeleteObject(void*)
{
DBG_ERROR("HashTable::OnDeleteObject(void*) nicht berladen")
}
ULONG HashTable::Hash(String const& Key) const
{
/*
ULONG lHash = 0;
ULONG i,n;
for (i=0,n=Key.Len(); i<n; i++)
{
lHash *= 256L;
lHash += (ULONG)(USHORT)Key.GetStr()[i];
lHash %= m_lSize;
}
return lHash;
*/
// Hashfunktion von P.J. Weinberger
// aus dem "Drachenbuch" von Aho/Sethi/Ullman
ULONG i,n;
ULONG h = 0;
ULONG g = 0;
for (i=0,n=Key.Len(); i<n; i++)
{
h = (h<<4) + (ULONG)(USHORT)Key.GetStr()[i];
g = h & 0xf0000000;
if (g != 0)
{
h = h ^ (g >> 24);
h = h ^ g;
}
}
return h % m_lSize;
}
ULONG HashTable::DHash(String const& Key, ULONG lOldHash) const
{
ULONG lHash = lOldHash;
ULONG i,n;
for (i=0,n=Key.Len(); i<n; i++)
{
lHash *= 256L;
lHash += (ULONG)(USHORT)Key.GetStr()[i];
lHash %= m_lSize;
}
return lHash;
/* return
(
lHash
+ (char)Key.GetStr()[0] * 256
+ (char)Key.GetStr()[Key.Len()-1]
+ 1
)
% m_lSize;
*/
}
ULONG HashTable::Probe(ULONG lPos) const
// gibt den Folgewert von lPos zurck
{
lPos++; if (lPos==m_lSize) lPos=0;
return lPos;
}
BOOL HashTable::IsFull() const
{
return m_lElem>=m_lSize;
}
BOOL HashTable::Insert(String const& Key, void* pObject)
// pre: Key ist nicht im Dictionary enthalten, sonst return FALSE
// Dictionary ist nicht voll, sonst return FALSE
// post: pObject ist unter Key im Dictionary; m_nElem wurde erhht
{
SmartGrow();
if (IsFull())
{
DBG_ERROR("HashTable::Insert() is full");
return FALSE;
}
if (FindPos(Key) != NULL )
return FALSE;
ULONG lPos = Hash(Key);
HashItem *pItem = &m_pData[lPos];
// first hashing
//
if (pItem->IsEmpty())
{
pItem->SetObject(Key, pObject);
m_lElem++;
#ifdef DBG_UTIL
m_aStatistic.m_lSingleHash++;
#endif
return TRUE;
}
// double hashing
//
lPos = DHash(Key,lPos);
pItem = &m_pData[lPos];
if (pItem->IsEmpty())
{
pItem->SetObject(Key, pObject);
m_lElem++;
#ifdef DBG_UTIL
m_aStatistic.m_lDoubleHash++;
#endif
return TRUE;
}
// linear probing
//
do
{
#ifdef DBG_UTIL
m_aStatistic.m_lProbe++;
#endif
lPos = Probe(lPos);
pItem = &m_pData[lPos];
}
while(!pItem->IsEmpty());
pItem->SetObject(Key, pObject);
m_lElem++;
return TRUE;
}
HashItem* HashTable::FindPos(String const& Key) const
// sucht den Key; gibt Refrenz auf den Eintrag (gefunden)
// oder NULL (nicht gefunden) zurck
//
// pre: -
// post: -
{
// first hashing
//
ULONG lPos = Hash(Key);
HashItem *pItem = &m_pData[lPos];
if (pItem->IsUsed()
&& pItem->GetKey() == Key)
{
return pItem;
}
// double hashing
//
if (pItem->IsDeleted() || pItem->IsUsed())
{
lPos = DHash(Key,lPos);
pItem = &m_pData[lPos];
if (pItem->IsUsed()
&& pItem->GetKey() == Key)
{
return pItem;
}
// linear probing
//
if (pItem->IsDeleted() || pItem->IsUsed())
{
ULONG n = 0;
BOOL bFound = FALSE;
BOOL bEnd = FALSE;
do
{
n++;
lPos = Probe(lPos);
pItem = &m_pData[lPos];
bFound = pItem->IsUsed()
&& pItem->GetKey() == Key;
bEnd = !(n<m_lSize || pItem->IsFree());
}
while(!bFound && !bEnd);
return bFound ? pItem : NULL;
}
}
// nicht gefunden
//
return NULL;
}
void* HashTable::Find(String const& Key) const
// Gibt Verweis des Objektes zurck, das unter Key abgespeichert ist,
// oder NULL wenn nicht vorhanden.
//
// pre: -
// post: -
{
HashItem *pItem = FindPos(Key);
if (pItem != NULL
&& pItem->GetKey() == Key)
return pItem->GetObject();
else
return NULL;
}
void* HashTable::Delete(String const& Key)
// Lscht Objekt, das unter Key abgespeichert ist und gibt Verweis
// darauf zurck.
// Gibt NULL zurck, wenn Key nicht vorhanden ist.
//
// pre: -
// post: Objekt ist nicht mehr enthalten; m_lElem dekrementiert
// Wenn die HashTable der Owner ist, wurde das Object gelscht
{
HashItem *pItem = FindPos(Key);
if (pItem != NULL
&& pItem->GetKey() == Key)
{
void* pObject = pItem->GetObject();
if (m_bOwner)
OnDeleteObject(pObject);
pItem->Delete();
m_lElem--;
return pObject;
}
else
{
return NULL;
}
}
double HashTable::CalcLoadFactor() const
// prozentuale Belegung der Hashtabelle berechnen
{
return double(m_lElem) / double(m_lSize);
}
void HashTable::SmartGrow()
// Achtung: da die Objekte umkopiert werden, darf die OnDeleteObject-Methode
// nicht gerufen werden
{
double dLoadFactor = CalcLoadFactor();
if (dLoadFactor <= m_dMaxLoadFactor)
return; // nothing to grow
ULONG lOldSize = m_lSize; // alte Daten sichern
HashItem* pOldData = m_pData;
m_lSize = ULONG (m_dGrowFactor * m_lSize); // neue Gre
m_pData = new HashItem[m_lSize]; // neue Daten holen
// kein Speicher:
// Zustand "Tabelle voll" wird in Insert abgefangen
//
if (m_pData == NULL)
{
m_lSize = lOldSize;
m_pData = pOldData;
return;
}
m_lElem = 0; // noch keine neuen Daten
// Umkopieren der Daten
//
for (ULONG i=0; i<lOldSize; i++)
{
HashItem *pItem = &pOldData[i];
if (pItem->IsUsed())
Insert(pItem->GetKey(),pItem->GetObject());
}
delete [] pOldData;
}
// Iterator ---------------------------------------------------------
//
HashTableIterator::HashTableIterator(HashTable const& aTable)
: m_aTable(aTable)
{
m_lAt = 0;
}
void* HashTableIterator::GetFirst()
{
m_lAt = 0;
return FindValidObject(TRUE /* forward */);
}
void* HashTableIterator::GetLast()
{
m_lAt = m_aTable.GetSize() -1;
return FindValidObject(FALSE /* backward */);
}
void* HashTableIterator::GetNext()
{
if (m_lAt+1 >= m_aTable.GetSize())
return NULL;
m_lAt++;
return FindValidObject(TRUE /* forward */);
}
void* HashTableIterator::GetPrev()
{
if (m_lAt <= 0)
return NULL;
m_lAt--;
return FindValidObject(FALSE /* backward */);
}
void* HashTableIterator::FindValidObject(BOOL bForward)
// Sucht nach einem vorhandenen Objekt ab der aktuellen
// Position.
//
// pre: ab inkl. m_lAt soll die Suche beginnen
// post: if not found then
// if bForward == TRUE then
// m_lAt == m_aTable.GetSize() -1
// else
// m_lAt == 0
// else
// m_lAt ist die gefundene Position
{
void *pObject = m_aTable.GetObjectAt(m_lAt);
if (pObject != NULL)
return pObject;
while (pObject == NULL
&& (bForward ? ((m_lAt+1) < m_aTable.GetSize())
: m_lAt > 0))
{
if (bForward)
m_lAt++;
else
m_lAt--;
pObject = m_aTable.GetObjectAt(m_lAt);
}
#ifdef DBG_UTIL
if (pObject == NULL)
{
DBG_ASSERT(bForward ? m_lAt == m_aTable.GetSize() -1 : m_lAt == 0,
"HashTableIterator::FindValidObject()");
}
#endif
return pObject;
}
<|endoftext|> |
<commit_before>#include "debug.h"
#include "mvar.h"
#include "file.h"
#include "esmb.h"
#include "para.h"
#include "seidner.h"
#include "polar.h"
#include "output.h"
#include "complex.h"
//#include <cstdlib>
#define complex std::complex<double>
// ------------------------------------------------------------
// The following 3 functions should be defined by user
void mvar_update( long is, long i_esmb, struct parameters *ps );
void mvar_output_grid( para_file::file_type type, parameters *ps );
// ------------------------------------------------------------
#include <gsl/gsl_rng.h>
// void mvar_calc_esmb( parameters *ps )
// {
// // 1d array: nt * n_dim
// complex **ptot = prepare_pol_array( 1, ps );
// gsl_rng_set( (gsl_rng*) ps->esmb->rng, ps->mpic->rank + 1 );
// long i_esmb_0 = ps->mpic->idx0;
// long i_esmb_1 = i_esmb_0 + ps->mpic->njob;
// // fprintf( stdout, "rank=%-3ld, i_esmb_0=%-6ld, i_esmb_1=%-6ld\n",
// // ps->mpic->rank, i_esmb_0, i_esmb_1 );
// int file_idx[1] = { (int)ps->mpic->rank };
// open_para_file_write( para_file::RL, NULL, ps, 1, file_idx );
// open_para_file_write( para_file::ORIENT, NULL, ps, 1, file_idx );
// open_para_file_write( para_file::PTOT_1D, NULL, ps, 1, file_idx );
// open_para_file_write( para_file::KL, NULL, ps, 1, file_idx );
// output_ef_kL( ps->file->one[para_file::KL]->fptr, ps );
// close_para_file( para_file::KL, ps );
// for (long i_esmb = i_esmb_0; i_esmb < i_esmb_1; i_esmb ++) {
// para_esmb_update( i_esmb, ps );
// // mvar_update( is, i_esmb, ps );
// calc_ptot( ptot, ps, 0 ); // note ig = 0 for 1D
// io_rl_write( ps );
// // each line output ptot_1d as (P=2Re(.), so we dont' put Im part)
// // Re_x(t1) Re_y(t1) Re_z(t1) Re_x(t2) Re_y(t2) Re_z(t2) ..
// for (long it = 0; it < ps->nt; it ++)
// for (int i_dim = 0; i_dim < ps->n_dim; i_dim ++)
// fprintf( ps->file->one[para_file::PTOT_1D]->fptr, "%le ",
// real( ptot[it][i_dim] ) );
// fprintf( ps->file->one[para_file::PTOT_1D]->fptr, "\n" );
// }
// close_para_file( para_file::PTOT_1D, ps );
// close_para_file( para_file::ORIENT, ps );
// close_para_file( para_file::RL, ps );
// clean_pol_array( 1, ptot, ps );
// }
#include <stdexcept>
void mvar_calc_grid_seidner( parameters *ps )
{
long ns = ps->mpic->njob;
long nt = ps->nt;
// 2d array: n_phase * (ns * nt) * n_dim
complex ****ppar_2d = prepare_pol_array_seidner( 2, ps );
complex ****ptot_2d = prepare_pol_array_seidner( 2, ps );
// If there are old results for ensemble for the same parameters,
// one can choose to continue the calculation from old data
if (ps->esmb->with_old == 1) {
try {
io_pol_dir_read( para_file::PPAR_2D, ppar_2d, ps->seid->n_phase, NULL, ps );
} catch (std::runtime_error& e) {
error( ps, "%s", "Cannot open old data file." );
clean_pol_array_seidner( 2, ppar_2d, ps );
clean_pol_array_seidner( 2, ptot_2d, ps );
return;
}
}
// 1d array: n_phase * nt * n_dim
complex ****ppar_1d = prepare_pol_array_seidner( 1, ps );
complex ****ptot_1d = prepare_pol_array_seidner( 1, ps );
gsl_rng_set( (gsl_rng*) ps->esmb->rng, 4 );
gsl_rng_set( (gsl_rng*) ps->seid->rng, 4 );
for (long i_esmb = 0; i_esmb < ps->esmb->n_esmb; i_esmb ++) {
para_esmb_update( i_esmb, ps );
for (long is = 0; is < ns; is ++) {
mvar_update( is, i_esmb, ps );
calc_ptot_seidner( ptot_1d, ps );
calc_ppar_seidner( ppar_1d, ptot_1d, ps );
for (int i_dir = 0; i_dir < ps->seid->n_phase; i_dir ++)
for (long it = 0; it < nt; it ++) {
long index = is * nt + it;
for (int i_dpl = 0; i_dpl < ps->pols->n_dpl; i_dpl ++)
for (int i_dim = 0; i_dim < ps->n_dim; i_dim ++) {
ppar_2d[i_dir][index][i_dpl][i_dim] +=
ppar_1d[i_dir][it][i_dpl][i_dim];
if (i_esmb == 0)
ptot_2d[i_dir][index][i_dpl][i_dim] =
ptot_1d[i_dir][it][i_dpl][i_dim];
}
}
}
if (ps->mpic->rank == 0)
if (i_esmb % 10 == 0)
fprintf( stdout, "Finished sample number: %ld of %ld\n",
i_esmb, ps->esmb->n_esmb );
}
clean_pol_array_seidner( 1, ppar_1d, ps );
clean_pol_array_seidner( 1, ptot_1d, ps );
mvar_output_grid( para_file::GRID_2D, ps );
io_pol_dir_write( para_file::PPAR_2D, ppar_2d, ps->seid->n_phase, NULL, ps );
io_pol_dir_write( para_file::PTOT_2D, ptot_2d, ps->seid->n_phase, NULL, ps );
clean_pol_array_seidner( 2, ppar_2d, ps );
clean_pol_array_seidner( 2, ptot_2d, ps );
}
// void mvar_calc_grid( parameters *ps )
// {
// long ns = ps->mpic->njob;
// long nt = ps->nt;
// gsl_rng_set( (gsl_rng*) ps->esmb->rng, 1 );
// mvar_output_grid( para_file::GRID_2D, ps );
// int file_idx[1] = { (int)ps->mpic->rank };
// open_para_file_write( para_file::RL, NULL, ps, 1, file_idx );
// open_para_file_write( para_file::PTOT_2D, NULL, ps, 1, file_idx );
// // ptot: (ns * nt) * n_dim ptot_1d: nt * n_dim;
// complex** ptot = prepare_pol_array( 2, ps );
// for (long i_esmb = 0; i_esmb < ps->esmb->n_esmb; i_esmb ++) {
// para_esmb_update( i_esmb, ps );
// for (long is = 0; is < ns; is ++) {
// mvar_update( is, i_esmb, ps );
// calc_ptot( ptot, ps, is * nt ); // note ig = is * nt for 2D
// }
// io_pol_write( ps->file->mul[para_file::PTOT_2D]->fptr, ptot, ps );
// io_rl_write( ps );
// // display progress
// if (ps->mpic->rank == 0)
// if (i_esmb % 100 == 0)
// fprintf( stdout, "Finished sample number: %ld of %ld\n",
// i_esmb, ps->esmb->n_esmb );
// }
// clean_pol_array( 2, ptot, ps );
// close_para_file( para_file::RL, ps );
// close_para_file( para_file::PTOT_2D, ps );
// }
void para_mvar_config( config_t* cfg, parameters* ps );
void para_mvar_set( parameters* ps );
void para_mvar_ini( config_t* cfg, parameters* ps )
{
ps->mvar = new para_mvar;
para_mvar_config( cfg, ps );
para_mvar_set( ps );
}
void para_mvar_del( parameters* ps )
{
delete ps->mvar;
}
void para_mvar_set( parameters* ps )
{
if (ps->mvar->ny == 1) {
ps->mvar->dy = 0.0;
} else {
ps->mvar->dy = (ps->mvar->y1 - ps->mvar->y0) / (ps->mvar->ny - 1.0);
}
}
#include <libconfig.h>
void para_mvar_config( config_t* cfg, parameters* ps )
{
int ny;
config_lookup_int( cfg, "mvar.ny", &ny );
ps->mvar->ny = ny;
config_lookup_float( cfg, "mvar.y0", &(ps->mvar->y0) );
config_lookup_float( cfg, "mvar.y1", &(ps->mvar->y1) );
// may need units conversion!!!
ps->mvar->y0 *= C_fs2au;
ps->mvar->y1 *= C_fs2au;
}
void para_mvar_update( parameters* ps )
{
}
///////////////////////////////////////////////////////////////
// User-defined func - coherence time with tau or population time with T
void mvar_update( long is, long i_esmb, parameters *ps )
{
// the current value of variable
double y = ps->mvar->y0 + (ps->mpic->idx0 + is) * ps->mvar->dy;
// coherence time (2D echo)
// 2nd pulse is not changed, 1st pulse is changed
ps->ef[0]->tc = ps->ef[1]->tc - y;
// // population time
// double tau = ps->ef[1] - ps->ef[0];
// ps->ef[1]->tc = 0.0 - y;
// ps->ef[0]->tc = ps->ef[1]->tc - tau;
}
void mvar_output_grid( para_file::file_type type, parameters *ps )
{
double *s = new double[ps->mpic->njob];
for (long is = 0; is < ps->mpic->njob; is ++) {
s[is] = ps->mvar->y0 + (ps->mpic->idx0 + is) * ps->mvar->dy;
s[is] /= C_fs2au;
}
io_grid_write( para_file::GRID_2D, s, NULL, ps );
delete[] s;
}
<commit_msg>uncomment for pullerits' method. The code is not yet compilable.<commit_after>#include "debug.h"
#include "mvar.h"
#include "file.h"
#include "esmb.h"
#include "para.h"
#include "seidner.h"
#include "polar.h"
#include "output.h"
#include "complex.h"
//#include <cstdlib>
#define complex std::complex<double>
// ------------------------------------------------------------
// The following 3 functions should be defined by user
void mvar_update( long is, long i_esmb, struct parameters *ps );
void mvar_output_grid( para_file::file_type type, parameters *ps );
// ------------------------------------------------------------
#include <gsl/gsl_rng.h>
// void mvar_calc_esmb( parameters *ps )
// {
// // 1d array: nt * n_dim
// complex **ptot = prepare_pol_array( 1, ps );
// gsl_rng_set( (gsl_rng*) ps->esmb->rng, ps->mpic->rank + 1 );
// long i_esmb_0 = ps->mpic->idx0;
// long i_esmb_1 = i_esmb_0 + ps->mpic->njob;
// // fprintf( stdout, "rank=%-3ld, i_esmb_0=%-6ld, i_esmb_1=%-6ld\n",
// // ps->mpic->rank, i_esmb_0, i_esmb_1 );
// int file_idx[1] = { (int)ps->mpic->rank };
// open_para_file_write( para_file::RL, NULL, ps, 1, file_idx );
// open_para_file_write( para_file::ORIENT, NULL, ps, 1, file_idx );
// open_para_file_write( para_file::PTOT_1D, NULL, ps, 1, file_idx );
// open_para_file_write( para_file::KL, NULL, ps, 1, file_idx );
// output_ef_kL( ps->file->one[para_file::KL]->fptr, ps );
// close_para_file( para_file::KL, ps );
// for (long i_esmb = i_esmb_0; i_esmb < i_esmb_1; i_esmb ++) {
// para_esmb_update( i_esmb, ps );
// // mvar_update( is, i_esmb, ps );
// calc_ptot( ptot, ps, 0 ); // note ig = 0 for 1D
// io_rl_write( ps );
// // each line output ptot_1d as (P=2Re(.), so we dont' put Im part)
// // Re_x(t1) Re_y(t1) Re_z(t1) Re_x(t2) Re_y(t2) Re_z(t2) ..
// for (long it = 0; it < ps->nt; it ++)
// for (int i_dim = 0; i_dim < ps->n_dim; i_dim ++)
// fprintf( ps->file->one[para_file::PTOT_1D]->fptr, "%le ",
// real( ptot[it][i_dim] ) );
// fprintf( ps->file->one[para_file::PTOT_1D]->fptr, "\n" );
// }
// close_para_file( para_file::PTOT_1D, ps );
// close_para_file( para_file::ORIENT, ps );
// close_para_file( para_file::RL, ps );
// clean_pol_array( 1, ptot, ps );
// }
#include <stdexcept>
void mvar_calc_grid_seidner( parameters *ps )
{
long ns = ps->mpic->njob;
long nt = ps->nt;
// 2d array: n_phase * (ns * nt) * n_dim
complex ****ppar_2d = prepare_pol_array_seidner( 2, ps );
complex ****ptot_2d = prepare_pol_array_seidner( 2, ps );
// If there are old results for ensemble for the same parameters,
// one can choose to continue the calculation from old data
if (ps->esmb->with_old == 1) {
try {
io_pol_dir_read( para_file::PPAR_2D, ppar_2d, ps->seid->n_phase, NULL, ps );
} catch (std::runtime_error& e) {
error( ps, "%s", "Cannot open old data file." );
clean_pol_array_seidner( 2, ppar_2d, ps );
clean_pol_array_seidner( 2, ptot_2d, ps );
return;
}
}
// 1d array: n_phase * nt * n_dim
complex ****ppar_1d = prepare_pol_array_seidner( 1, ps );
complex ****ptot_1d = prepare_pol_array_seidner( 1, ps );
gsl_rng_set( (gsl_rng*) ps->esmb->rng, 4 );
gsl_rng_set( (gsl_rng*) ps->seid->rng, 4 );
for (long i_esmb = 0; i_esmb < ps->esmb->n_esmb; i_esmb ++) {
para_esmb_update( i_esmb, ps );
for (long is = 0; is < ns; is ++) {
mvar_update( is, i_esmb, ps );
calc_ptot_seidner( ptot_1d, ps );
calc_ppar_seidner( ppar_1d, ptot_1d, ps );
for (int i_dir = 0; i_dir < ps->seid->n_phase; i_dir ++)
for (long it = 0; it < nt; it ++) {
long index = is * nt + it;
for (int i_dpl = 0; i_dpl < ps->pols->n_dpl; i_dpl ++)
for (int i_dim = 0; i_dim < ps->n_dim; i_dim ++) {
ppar_2d[i_dir][index][i_dpl][i_dim] +=
ppar_1d[i_dir][it][i_dpl][i_dim];
if (i_esmb == 0)
ptot_2d[i_dir][index][i_dpl][i_dim] =
ptot_1d[i_dir][it][i_dpl][i_dim];
}
}
}
if (ps->mpic->rank == 0)
if (i_esmb % 10 == 0)
fprintf( stdout, "Finished sample number: %ld of %ld\n",
i_esmb, ps->esmb->n_esmb );
}
clean_pol_array_seidner( 1, ppar_1d, ps );
clean_pol_array_seidner( 1, ptot_1d, ps );
mvar_output_grid( para_file::GRID_2D, ps );
io_pol_dir_write( para_file::PPAR_2D, ppar_2d, ps->seid->n_phase, NULL, ps );
io_pol_dir_write( para_file::PTOT_2D, ptot_2d, ps->seid->n_phase, NULL, ps );
clean_pol_array_seidner( 2, ppar_2d, ps );
clean_pol_array_seidner( 2, ptot_2d, ps );
}
void mvar_calc_grid( parameters *ps )
{
long ns = ps->mpic->njob;
long nt = ps->nt;
gsl_rng_set( (gsl_rng*) ps->esmb->rng, 1 );
mvar_output_grid( para_file::GRID_2D, ps );
int file_idx[1] = { (int)ps->mpic->rank };
open_para_file_write( para_file::RL, NULL, ps, 1, file_idx );
open_para_file_write( para_file::PTOT_2D, NULL, ps, 1, file_idx );
// ptot: (ns * nt) * n_dim ptot_1d: nt * n_dim;
complex** ptot = prepare_pol_array( 2, ps );
for (long i_esmb = 0; i_esmb < ps->esmb->n_esmb; i_esmb ++) {
para_esmb_update( i_esmb, ps );
for (long is = 0; is < ns; is ++) {
mvar_update( is, i_esmb, ps );
calc_ptot( ptot, ps, is * nt ); // note ig = is * nt for 2D
}
io_pol_write( ps->file->mul[para_file::PTOT_2D]->fptr, ptot, ps );
io_rl_write( ps );
// display progress
if (ps->mpic->rank == 0)
if (i_esmb % 100 == 0)
fprintf( stdout, "Finished sample number: %ld of %ld\n",
i_esmb, ps->esmb->n_esmb );
}
clean_pol_array( 2, ptot, ps );
close_para_file( para_file::RL, ps );
close_para_file( para_file::PTOT_2D, ps );
}
void para_mvar_config( config_t* cfg, parameters* ps );
void para_mvar_set( parameters* ps );
void para_mvar_ini( config_t* cfg, parameters* ps )
{
ps->mvar = new para_mvar;
para_mvar_config( cfg, ps );
para_mvar_set( ps );
}
void para_mvar_del( parameters* ps )
{
delete ps->mvar;
}
void para_mvar_set( parameters* ps )
{
if (ps->mvar->ny == 1) {
ps->mvar->dy = 0.0;
} else {
ps->mvar->dy = (ps->mvar->y1 - ps->mvar->y0) / (ps->mvar->ny - 1.0);
}
}
#include <libconfig.h>
void para_mvar_config( config_t* cfg, parameters* ps )
{
int ny;
config_lookup_int( cfg, "mvar.ny", &ny );
ps->mvar->ny = ny;
config_lookup_float( cfg, "mvar.y0", &(ps->mvar->y0) );
config_lookup_float( cfg, "mvar.y1", &(ps->mvar->y1) );
// may need units conversion!!!
ps->mvar->y0 *= C_fs2au;
ps->mvar->y1 *= C_fs2au;
}
void para_mvar_update( parameters* ps )
{
}
///////////////////////////////////////////////////////////////
// User-defined func - coherence time with tau or population time with T
void mvar_update( long is, long i_esmb, parameters *ps )
{
// the current value of variable
double y = ps->mvar->y0 + (ps->mpic->idx0 + is) * ps->mvar->dy;
// coherence time (2D echo)
// 2nd pulse is not changed, 1st pulse is changed
ps->ef[0]->tc = ps->ef[1]->tc - y;
// // population time
// double tau = ps->ef[1] - ps->ef[0];
// ps->ef[1]->tc = 0.0 - y;
// ps->ef[0]->tc = ps->ef[1]->tc - tau;
}
void mvar_output_grid( para_file::file_type type, parameters *ps )
{
double *s = new double[ps->mpic->njob];
for (long is = 0; is < ps->mpic->njob; is ++) {
s[is] = ps->mvar->y0 + (ps->mpic->idx0 + is) * ps->mvar->dy;
s[is] /= C_fs2au;
}
io_grid_write( para_file::GRID_2D, s, NULL, ps );
delete[] s;
}
<|endoftext|> |
<commit_before>///////////////////////////////////////////////////////////////////////
// File: lstmtraining.cpp
// Description: Training program for LSTM-based networks.
// Author: Ray Smith
// Created: Fri May 03 11:05:06 PST 2013
//
// (C) Copyright 2013, Google Inc.
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
// http://www.apache.org/licenses/LICENSE-2.0
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
///////////////////////////////////////////////////////////////////////
#ifdef GOOGLE_TESSERACT
#include "base/commandlineflags.h"
#endif
#include "commontraining.h"
#include "lstmtester.h"
#include "lstmtrainer.h"
#include "params.h"
#include "strngs.h"
#include "tprintf.h"
#include "unicharset_training_utils.h"
INT_PARAM_FLAG(debug_interval, 0, "How often to display the alignment.");
STRING_PARAM_FLAG(net_spec, "", "Network specification");
INT_PARAM_FLAG(net_mode, 192, "Controls network behavior.");
INT_PARAM_FLAG(perfect_sample_delay, 0,
"How many imperfect samples between perfect ones.");
DOUBLE_PARAM_FLAG(target_error_rate, 0.01, "Final error rate in percent.");
DOUBLE_PARAM_FLAG(weight_range, 0.1, "Range of initial random weights.");
DOUBLE_PARAM_FLAG(learning_rate, 10.0e-4, "Weight factor for new deltas.");
DOUBLE_PARAM_FLAG(momentum, 0.5, "Decay factor for repeating deltas.");
DOUBLE_PARAM_FLAG(adam_beta, 0.999, "Decay factor for repeating deltas.");
INT_PARAM_FLAG(max_image_MB, 6000, "Max memory to use for images.");
STRING_PARAM_FLAG(continue_from, "", "Existing model to extend");
STRING_PARAM_FLAG(model_output, "lstmtrain", "Basename for output models");
STRING_PARAM_FLAG(train_listfile, "",
"File listing training files in lstmf training format.");
STRING_PARAM_FLAG(eval_listfile, "",
"File listing eval files in lstmf training format.");
BOOL_PARAM_FLAG(stop_training, false,
"Just convert the training model to a runtime model.");
BOOL_PARAM_FLAG(convert_to_int, false,
"Convert the recognition model to an integer model.");
BOOL_PARAM_FLAG(sequential_training, false,
"Use the training files sequentially instead of round-robin.");
INT_PARAM_FLAG(append_index, -1, "Index in continue_from Network at which to"
" attach the new network defined by net_spec");
BOOL_PARAM_FLAG(debug_network, false,
"Get info on distribution of weight values");
INT_PARAM_FLAG(max_iterations, 0, "If set, exit after this many iterations");
STRING_PARAM_FLAG(traineddata, "",
"Combined Dawgs/Unicharset/Recoder for language model");
STRING_PARAM_FLAG(old_traineddata, "",
"When changing the character set, this specifies the old"
" character set that is to be replaced");
BOOL_PARAM_FLAG(randomly_rotate, false,
"Train OSD and randomly turn training samples upside-down");
// Number of training images to train between calls to MaintainCheckpoints.
const int kNumPagesPerBatch = 100;
// Apart from command-line flags, input is a collection of lstmf files, that
// were previously created using tesseract with the lstm.train config file.
// The program iterates over the inputs, feeding the data to the network,
// until the error rate reaches a specified target or max_iterations is reached.
int main(int argc, char **argv) {
tesseract::CheckSharedLibraryVersion();
ParseArguments(&argc, &argv);
// Purify the model name in case it is based on the network string.
if (FLAGS_model_output.empty()) {
tprintf("Must provide a --model_output!\n");
return 1;
}
if (FLAGS_traineddata.empty()) {
tprintf("Must provide a --traineddata see training wiki\n");
return 1;
}
STRING model_output = FLAGS_model_output.c_str();
for (int i = 0; i < model_output.length(); ++i) {
if (model_output[i] == '[' || model_output[i] == ']')
model_output[i] = '-';
if (model_output[i] == '(' || model_output[i] == ')')
model_output[i] = '_';
}
// Setup the trainer.
STRING checkpoint_file = FLAGS_model_output.c_str();
checkpoint_file += "_checkpoint";
STRING checkpoint_bak = checkpoint_file + ".bak";
tesseract::LSTMTrainer trainer(
nullptr, nullptr, nullptr, nullptr, FLAGS_model_output.c_str(),
checkpoint_file.c_str(), FLAGS_debug_interval,
static_cast<int64_t>(FLAGS_max_image_MB) * 1048576);
trainer.InitCharSet(FLAGS_traineddata.c_str());
// Reading something from an existing model doesn't require many flags,
// so do it now and exit.
if (FLAGS_stop_training || FLAGS_debug_network) {
if (!trainer.TryLoadingCheckpoint(FLAGS_continue_from.c_str(), nullptr)) {
tprintf("Failed to read continue from: %s\n",
FLAGS_continue_from.c_str());
return 1;
}
if (FLAGS_debug_network) {
trainer.DebugNetwork();
} else {
if (FLAGS_convert_to_int) trainer.ConvertToInt();
if (!trainer.SaveTraineddata(FLAGS_model_output.c_str())) {
tprintf("Failed to write recognition model : %s\n",
FLAGS_model_output.c_str());
}
}
return 0;
}
// Get the list of files to process.
if (FLAGS_train_listfile.empty()) {
tprintf("Must supply a list of training filenames! --train_listfile\n");
return 1;
}
GenericVector<STRING> filenames;
if (!tesseract::LoadFileLinesToStrings(FLAGS_train_listfile.c_str(),
&filenames)) {
tprintf("Failed to load list of training filenames from %s\n",
FLAGS_train_listfile.c_str());
return 1;
}
// Checkpoints always take priority if they are available.
if (trainer.TryLoadingCheckpoint(checkpoint_file.string(), nullptr) ||
trainer.TryLoadingCheckpoint(checkpoint_bak.string(), nullptr)) {
tprintf("Successfully restored trainer from %s\n",
checkpoint_file.string());
} else {
if (!FLAGS_continue_from.empty()) {
// Load a past model file to improve upon.
if (!trainer.TryLoadingCheckpoint(FLAGS_continue_from.c_str(),
FLAGS_append_index >= 0
? FLAGS_continue_from.c_str()
: FLAGS_old_traineddata.c_str())) {
tprintf("Failed to continue from: %s\n", FLAGS_continue_from.c_str());
return 1;
}
tprintf("Continuing from %s\n", FLAGS_continue_from.c_str());
trainer.InitIterations();
}
if (FLAGS_continue_from.empty() || FLAGS_append_index >= 0) {
if (FLAGS_append_index >= 0) {
tprintf("Appending a new network to an old one!!");
if (FLAGS_continue_from.empty()) {
tprintf("Must set --continue_from for appending!\n");
return 1;
}
}
// We are initializing from scratch.
if (!trainer.InitNetwork(FLAGS_net_spec.c_str(), FLAGS_append_index,
FLAGS_net_mode, FLAGS_weight_range,
FLAGS_learning_rate, FLAGS_momentum,
FLAGS_adam_beta)) {
tprintf("Failed to create network from spec: %s\n",
FLAGS_net_spec.c_str());
return 1;
}
trainer.set_perfect_delay(FLAGS_perfect_sample_delay);
}
}
if (!trainer.LoadAllTrainingData(filenames,
FLAGS_sequential_training
? tesseract::CS_SEQUENTIAL
: tesseract::CS_ROUND_ROBIN,
FLAGS_randomly_rotate)) {
tprintf("Load of images failed!!\n");
return 1;
}
tesseract::LSTMTester tester(static_cast<int64_t>(FLAGS_max_image_MB) *
1048576);
tesseract::TestCallback tester_callback = nullptr;
if (!FLAGS_eval_listfile.empty()) {
if (!tester.LoadAllEvalData(FLAGS_eval_listfile.c_str())) {
tprintf("Failed to load eval data from: %s\n",
FLAGS_eval_listfile.c_str());
return 1;
}
tester_callback =
NewPermanentTessCallback(&tester, &tesseract::LSTMTester::RunEvalAsync);
}
do {
// Train a few.
int iteration = trainer.training_iteration();
for (int target_iteration = iteration + kNumPagesPerBatch;
iteration < target_iteration;
iteration = trainer.training_iteration()) {
trainer.TrainOnLine(&trainer, false);
}
STRING log_str;
trainer.MaintainCheckpoints(tester_callback, &log_str);
tprintf("%s\n", log_str.string());
} while (trainer.best_error_rate() > FLAGS_target_error_rate &&
(trainer.training_iteration() < FLAGS_max_iterations ||
FLAGS_max_iterations == 0));
delete tester_callback;
tprintf("Finished! Error rate = %g\n", trainer.best_error_rate());
return 0;
} /* main */
<commit_msg>lstmtraining: Fix handling of --max_iterations<commit_after>///////////////////////////////////////////////////////////////////////
// File: lstmtraining.cpp
// Description: Training program for LSTM-based networks.
// Author: Ray Smith
// Created: Fri May 03 11:05:06 PST 2013
//
// (C) Copyright 2013, Google Inc.
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
// http://www.apache.org/licenses/LICENSE-2.0
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
///////////////////////////////////////////////////////////////////////
#ifdef GOOGLE_TESSERACT
#include "base/commandlineflags.h"
#endif
#include "commontraining.h"
#include "lstmtester.h"
#include "lstmtrainer.h"
#include "params.h"
#include "strngs.h"
#include "tprintf.h"
#include "unicharset_training_utils.h"
INT_PARAM_FLAG(debug_interval, 0, "How often to display the alignment.");
STRING_PARAM_FLAG(net_spec, "", "Network specification");
INT_PARAM_FLAG(net_mode, 192, "Controls network behavior.");
INT_PARAM_FLAG(perfect_sample_delay, 0,
"How many imperfect samples between perfect ones.");
DOUBLE_PARAM_FLAG(target_error_rate, 0.01, "Final error rate in percent.");
DOUBLE_PARAM_FLAG(weight_range, 0.1, "Range of initial random weights.");
DOUBLE_PARAM_FLAG(learning_rate, 10.0e-4, "Weight factor for new deltas.");
DOUBLE_PARAM_FLAG(momentum, 0.5, "Decay factor for repeating deltas.");
DOUBLE_PARAM_FLAG(adam_beta, 0.999, "Decay factor for repeating deltas.");
INT_PARAM_FLAG(max_image_MB, 6000, "Max memory to use for images.");
STRING_PARAM_FLAG(continue_from, "", "Existing model to extend");
STRING_PARAM_FLAG(model_output, "lstmtrain", "Basename for output models");
STRING_PARAM_FLAG(train_listfile, "",
"File listing training files in lstmf training format.");
STRING_PARAM_FLAG(eval_listfile, "",
"File listing eval files in lstmf training format.");
BOOL_PARAM_FLAG(stop_training, false,
"Just convert the training model to a runtime model.");
BOOL_PARAM_FLAG(convert_to_int, false,
"Convert the recognition model to an integer model.");
BOOL_PARAM_FLAG(sequential_training, false,
"Use the training files sequentially instead of round-robin.");
INT_PARAM_FLAG(append_index, -1, "Index in continue_from Network at which to"
" attach the new network defined by net_spec");
BOOL_PARAM_FLAG(debug_network, false,
"Get info on distribution of weight values");
INT_PARAM_FLAG(max_iterations, 0, "If set, exit after this many iterations");
STRING_PARAM_FLAG(traineddata, "",
"Combined Dawgs/Unicharset/Recoder for language model");
STRING_PARAM_FLAG(old_traineddata, "",
"When changing the character set, this specifies the old"
" character set that is to be replaced");
BOOL_PARAM_FLAG(randomly_rotate, false,
"Train OSD and randomly turn training samples upside-down");
// Number of training images to train between calls to MaintainCheckpoints.
const int kNumPagesPerBatch = 100;
// Apart from command-line flags, input is a collection of lstmf files, that
// were previously created using tesseract with the lstm.train config file.
// The program iterates over the inputs, feeding the data to the network,
// until the error rate reaches a specified target or max_iterations is reached.
int main(int argc, char **argv) {
tesseract::CheckSharedLibraryVersion();
ParseArguments(&argc, &argv);
// Purify the model name in case it is based on the network string.
if (FLAGS_model_output.empty()) {
tprintf("Must provide a --model_output!\n");
return 1;
}
if (FLAGS_traineddata.empty()) {
tprintf("Must provide a --traineddata see training wiki\n");
return 1;
}
STRING model_output = FLAGS_model_output.c_str();
for (int i = 0; i < model_output.length(); ++i) {
if (model_output[i] == '[' || model_output[i] == ']')
model_output[i] = '-';
if (model_output[i] == '(' || model_output[i] == ')')
model_output[i] = '_';
}
// Setup the trainer.
STRING checkpoint_file = FLAGS_model_output.c_str();
checkpoint_file += "_checkpoint";
STRING checkpoint_bak = checkpoint_file + ".bak";
tesseract::LSTMTrainer trainer(
nullptr, nullptr, nullptr, nullptr, FLAGS_model_output.c_str(),
checkpoint_file.c_str(), FLAGS_debug_interval,
static_cast<int64_t>(FLAGS_max_image_MB) * 1048576);
trainer.InitCharSet(FLAGS_traineddata.c_str());
// Reading something from an existing model doesn't require many flags,
// so do it now and exit.
if (FLAGS_stop_training || FLAGS_debug_network) {
if (!trainer.TryLoadingCheckpoint(FLAGS_continue_from.c_str(), nullptr)) {
tprintf("Failed to read continue from: %s\n",
FLAGS_continue_from.c_str());
return 1;
}
if (FLAGS_debug_network) {
trainer.DebugNetwork();
} else {
if (FLAGS_convert_to_int) trainer.ConvertToInt();
if (!trainer.SaveTraineddata(FLAGS_model_output.c_str())) {
tprintf("Failed to write recognition model : %s\n",
FLAGS_model_output.c_str());
}
}
return 0;
}
// Get the list of files to process.
if (FLAGS_train_listfile.empty()) {
tprintf("Must supply a list of training filenames! --train_listfile\n");
return 1;
}
GenericVector<STRING> filenames;
if (!tesseract::LoadFileLinesToStrings(FLAGS_train_listfile.c_str(),
&filenames)) {
tprintf("Failed to load list of training filenames from %s\n",
FLAGS_train_listfile.c_str());
return 1;
}
// Checkpoints always take priority if they are available.
if (trainer.TryLoadingCheckpoint(checkpoint_file.string(), nullptr) ||
trainer.TryLoadingCheckpoint(checkpoint_bak.string(), nullptr)) {
tprintf("Successfully restored trainer from %s\n",
checkpoint_file.string());
} else {
if (!FLAGS_continue_from.empty()) {
// Load a past model file to improve upon.
if (!trainer.TryLoadingCheckpoint(FLAGS_continue_from.c_str(),
FLAGS_append_index >= 0
? FLAGS_continue_from.c_str()
: FLAGS_old_traineddata.c_str())) {
tprintf("Failed to continue from: %s\n", FLAGS_continue_from.c_str());
return 1;
}
tprintf("Continuing from %s\n", FLAGS_continue_from.c_str());
trainer.InitIterations();
}
if (FLAGS_continue_from.empty() || FLAGS_append_index >= 0) {
if (FLAGS_append_index >= 0) {
tprintf("Appending a new network to an old one!!");
if (FLAGS_continue_from.empty()) {
tprintf("Must set --continue_from for appending!\n");
return 1;
}
}
// We are initializing from scratch.
if (!trainer.InitNetwork(FLAGS_net_spec.c_str(), FLAGS_append_index,
FLAGS_net_mode, FLAGS_weight_range,
FLAGS_learning_rate, FLAGS_momentum,
FLAGS_adam_beta)) {
tprintf("Failed to create network from spec: %s\n",
FLAGS_net_spec.c_str());
return 1;
}
trainer.set_perfect_delay(FLAGS_perfect_sample_delay);
}
}
if (!trainer.LoadAllTrainingData(filenames,
FLAGS_sequential_training
? tesseract::CS_SEQUENTIAL
: tesseract::CS_ROUND_ROBIN,
FLAGS_randomly_rotate)) {
tprintf("Load of images failed!!\n");
return 1;
}
tesseract::LSTMTester tester(static_cast<int64_t>(FLAGS_max_image_MB) *
1048576);
tesseract::TestCallback tester_callback = nullptr;
if (!FLAGS_eval_listfile.empty()) {
if (!tester.LoadAllEvalData(FLAGS_eval_listfile.c_str())) {
tprintf("Failed to load eval data from: %s\n",
FLAGS_eval_listfile.c_str());
return 1;
}
tester_callback =
NewPermanentTessCallback(&tester, &tesseract::LSTMTester::RunEvalAsync);
}
do {
// Train a few.
int iteration = trainer.training_iteration();
for (int target_iteration = iteration + kNumPagesPerBatch;
iteration < target_iteration &&
(iteration < FLAGS_max_iterations || FLAGS_max_iterations == 0);
iteration = trainer.training_iteration()) {
trainer.TrainOnLine(&trainer, false);
}
STRING log_str;
trainer.MaintainCheckpoints(tester_callback, &log_str);
tprintf("%s\n", log_str.string());
} while (trainer.best_error_rate() > FLAGS_target_error_rate &&
(trainer.training_iteration() < FLAGS_max_iterations ||
FLAGS_max_iterations == 0));
delete tester_callback;
tprintf("Finished! Error rate = %g\n", trainer.best_error_rate());
return 0;
} /* main */
<|endoftext|> |
<commit_before>/*
This file is part of KAddressBook.
Copyright (c) 2002 Mike Pilone <mpilone@slac.com>
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., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
As a special exception, permission is given to link this program
with any edition of Qt, and distribute the resulting executable,
without including the source code for Qt in the source distribution.
*/
#include <QString>
#include <QLayout>
#include <QLabel>
#include <QCheckBox>
#include <kvbox.h>
#include <q3groupbox.h>
#include <QSpinBox>
#include <QTabWidget>
//Added by qt3to4:
#include <QFrame>
#include <QGridLayout>
#include <kdebug.h>
#include <kglobal.h>
#include <kglobalsettings.h>
#include <klocale.h>
#include <kiconloader.h>
#include <kconfig.h>
#include <kfontdialog.h>
#include <kpushbutton.h>
#include <libkdepim/colorlistbox.h>
#include "configurecardviewdialog.h"
/////////////////////////////////
// ConfigureCardViewDialog
ConfigureCardViewWidget::ConfigureCardViewWidget( KABC::AddressBook *ab, QWidget *parent )
: ViewConfigureWidget( ab, parent )
{
QWidget *page = addPage( i18n( "Look & Feel" ), QString(),
DesktopIcon( "looknfeel" ) );
mAdvancedPage = new CardViewLookNFeelPage( page );
}
ConfigureCardViewWidget::~ConfigureCardViewWidget()
{
}
void ConfigureCardViewWidget::restoreSettings( const KConfigGroup &config )
{
ViewConfigureWidget::restoreSettings( config );
mAdvancedPage->restoreSettings( config );
}
void ConfigureCardViewWidget::saveSettings( KConfigGroup &config )
{
ViewConfigureWidget::saveSettings( config );
mAdvancedPage->saveSettings( config );
}
////////////////////////
// CardViewLookNFeelPage
CardViewLookNFeelPage::CardViewLookNFeelPage( QWidget *parent )
: KVBox( parent )
{
initGUI();
}
CardViewLookNFeelPage::~CardViewLookNFeelPage()
{
}
void CardViewLookNFeelPage::restoreSettings( const KConfigGroup &config )
{
// colors
cbEnableCustomColors->setChecked( config.readEntry( "EnableCustomColors", false ) );
QColor c;
c = KGlobalSettings::baseColor();
lbColors->addColor( i18n("Background Color"),
config.readEntry( "BackgroundColor", c ) );
c = palette().color( QPalette::Foreground );
lbColors->addColor( i18n("Text Color"),
config.readEntry( "TextColor", c ) );
c = palette().color( QPalette::Button );
lbColors->addColor( i18n("Header, Border & Separator Color"),
config.readEntry( "HeaderColor", c ) );
c = palette().color( QPalette::ButtonText );
lbColors->addColor( i18n("Header Text Color"),
config.readEntry( "HeaderTextColor", c ) );
c = palette().color( QPalette::Highlight );
lbColors->addColor( i18n("Highlight Color"),
config.readEntry( "HighlightColor", c ) );
c = palette().color( QPalette::HighlightedText );
lbColors->addColor( i18n("Highlighted Text Color"),
config.readEntry( "HighlightedTextColor", c ) );
enableColors();
// fonts
QFont fnt = font();
updateFontLabel( config.readEntry( "TextFont", fnt ), (QLabel*)lTextFont );
fnt.setBold( true );
updateFontLabel( config.readEntry( "HeaderFont", fnt ), (QLabel*)lHeaderFont );
cbEnableCustomFonts->setChecked( config.readEntry( "EnableCustomFonts", false ) );
enableFonts();
// layout
sbMargin->setValue( config.readEntry( "ItemMargin", 0 ) );
sbSpacing->setValue( config.readEntry( "ItemSpacing", 10 ) );
sbSepWidth->setValue( config.readEntry( "SeparatorWidth", 2 ) );
cbDrawSeps->setChecked( config.readEntry( "DrawSeparators", true ) );
cbDrawBorders->setChecked( config.readEntry( "DrawBorder", true ) );
// behaviour
cbShowFieldLabels->setChecked( config.readEntry( "DrawFieldLabels", false ) );
cbShowEmptyFields->setChecked( config.readEntry( "ShowEmptyFields", false ) );
}
void CardViewLookNFeelPage::saveSettings( KConfigGroup &config )
{
// colors
config.writeEntry( "EnableCustomColors", cbEnableCustomColors->isChecked() );
if ( cbEnableCustomColors->isChecked() ) // ?? - Hmmm.
{
config.writeEntry( "BackgroundColor", lbColors->color( 0 ) );
config.writeEntry( "TextColor", lbColors->color( 1 ) );
config.writeEntry( "HeaderColor", lbColors->color( 2 ) );
config.writeEntry( "HeaderTextColor", lbColors->color( 3 ) );
config.writeEntry( "HighlightColor", lbColors->color( 4 ) );
config.writeEntry( "HighlightedTextColor", lbColors->color( 5 ) );
}
// fonts
config.writeEntry( "EnableCustomFonts", cbEnableCustomFonts->isChecked() );
if ( cbEnableCustomFonts->isChecked() )
{
config.writeEntry( "TextFont", lTextFont->font() );
config.writeEntry( "HeaderFont", lHeaderFont->font() );
}
// layout
config.writeEntry( "ItemMargin", sbMargin->value() );
config.writeEntry( "ItemSpacing", sbSpacing->value() );
config.writeEntry( "SeparatorWidth", sbSepWidth->value() );
config.writeEntry("DrawBorder", cbDrawBorders->isChecked());
config.writeEntry("DrawSeparators", cbDrawSeps->isChecked());
// behaviour
config.writeEntry("DrawFieldLabels", cbShowFieldLabels->isChecked());
config.writeEntry("ShowEmptyFields", cbShowEmptyFields->isChecked());
}
void CardViewLookNFeelPage::setTextFont()
{
QFont f( lTextFont->font() );
if ( KFontDialog::getFont( f, false, this ) == QDialog::Accepted )
updateFontLabel( f, lTextFont );
}
void CardViewLookNFeelPage::setHeaderFont()
{
QFont f( lHeaderFont->font() );
if ( KFontDialog::getFont( f,false, this ) == QDialog::Accepted )
updateFontLabel( f, lHeaderFont );
}
void CardViewLookNFeelPage::enableFonts()
{
vbFonts->setEnabled( cbEnableCustomFonts->isChecked() );
}
void CardViewLookNFeelPage::enableColors()
{
lbColors->setEnabled( cbEnableCustomColors->isChecked() );
}
void CardViewLookNFeelPage::initGUI()
{
int spacing = KDialog::spacingHint();
int margin = KDialog::marginHint();
QTabWidget *tabs = new QTabWidget( this );
// Layout
KVBox *loTab = new KVBox( this );
loTab->setSpacing( spacing );
loTab->setMargin( margin );
Q3GroupBox *gbGeneral = new Q3GroupBox( 1, Qt::Horizontal, i18n("General"), loTab );
cbDrawSeps = new QCheckBox( i18n("Draw &separators"), gbGeneral );
KHBox *hbSW = new KHBox( gbGeneral );
QLabel *lSW = new QLabel( i18n("Separator &width:"), hbSW );
sbSepWidth = new QSpinBox( hbSW );
sbSepWidth->setRange( 1, 50 );
lSW->setBuddy( sbSepWidth);
KHBox *hbPadding = new KHBox( gbGeneral );
QLabel *lSpacing = new QLabel( i18n("&Padding:"), hbPadding );
sbSpacing = new QSpinBox( hbPadding );
sbSpacing->setRange( 0, 100 );
lSpacing->setBuddy( sbSpacing );
Q3GroupBox *gbCards = new Q3GroupBox( 1, Qt::Horizontal, i18n("Cards"), loTab );
KHBox *hbMargin = new KHBox( gbCards );
QLabel *lMargin = new QLabel( i18n("&Margin:"), hbMargin );
sbMargin = new QSpinBox( hbMargin );
sbMargin->setRange( 0, 100 );
lMargin->setBuddy( sbMargin );
cbDrawBorders = new QCheckBox( i18n("Draw &borders"), gbCards );
loTab->setStretchFactor( new QWidget( loTab ), 1 );
QString text = i18n(
"The item margin is the distance (in pixels) between the item edge and the item data. Most noticeably, "
"incrementing the item margin will add space between the focus rectangle and the item data."
);
sbMargin->setWhatsThis( text );
lMargin->setWhatsThis( text );
text = i18n(
"The item spacing decides the distance (in pixels) between the items and anything else: the view "
"borders, other items or column separators."
);
sbSpacing->setWhatsThis( text );
lSpacing->setWhatsThis( text );
text = i18n("Sets the width of column separators");
sbSepWidth->setWhatsThis( text );
lSW->setWhatsThis( text );
tabs->addTab( loTab, i18n("&Layout") );
// Colors
KVBox *colorTab = new KVBox( this );
colorTab->setSpacing( spacing );
colorTab->setMargin( spacing );
cbEnableCustomColors = new QCheckBox( i18n("&Enable custom colors"), colorTab );
connect( cbEnableCustomColors, SIGNAL(clicked()), this, SLOT(enableColors()) );
lbColors = new KPIM::ColorListBox( colorTab );
tabs->addTab( colorTab, i18n("&Colors") );
cbEnableCustomColors->setWhatsThis( i18n(
"If custom colors is enabled, you may choose the colors for the view below. "
"Otherwise colors from your current KDE color scheme are used."
) );
lbColors->setWhatsThis( i18n(
"Double click or press RETURN on a item to select a color for the related strings in the view."
) );
// Fonts
KVBox *fntTab = new KVBox( this );
fntTab->setSpacing( spacing );
fntTab->setMargin( spacing );
cbEnableCustomFonts = new QCheckBox( i18n("&Enable custom fonts"), fntTab );
connect( cbEnableCustomFonts, SIGNAL(clicked()), this, SLOT(enableFonts()) );
vbFonts = new QWidget( fntTab );
QGridLayout *gFnts = new QGridLayout( vbFonts );
gFnts->setSpacing( spacing );
gFnts->setAutoAdd( true );
gFnts->setColumnStretch( 1, 1 );
QLabel *lTFnt = new QLabel( i18n("&Text font:"), vbFonts );
lTextFont = new QLabel( vbFonts );
lTextFont->setFrameStyle( QFrame::Panel|QFrame::Sunken );
btnFont = new KPushButton( i18n("Choose..."), vbFonts );
lTFnt->setBuddy( btnFont );
connect( btnFont, SIGNAL(clicked()), this, SLOT(setTextFont()) );
QLabel *lHFnt = new QLabel( i18n("&Header font:"), vbFonts );
lHeaderFont = new QLabel( vbFonts );
lHeaderFont->setFrameStyle( QFrame::Panel|QFrame::Sunken );
btnHeaderFont = new KPushButton( i18n("Choose..."), vbFonts );
lHFnt->setBuddy( btnHeaderFont );
connect( btnHeaderFont, SIGNAL(clicked()), this, SLOT(setHeaderFont()) );
fntTab->setStretchFactor( new QWidget( fntTab ), 1 );
cbEnableCustomFonts->setWhatsThis( i18n(
"If custom fonts are enabled, you may choose which fonts to use for this view below. "
"Otherwise the default KDE font will be used, in bold style for the header and "
"normal style for the data."
) );
tabs->addTab( fntTab, i18n("&Fonts") );
// Behaviour
KVBox *behaviourTab = new KVBox( this );
behaviourTab->setMargin( margin );
behaviourTab->setSpacing( spacing );
cbShowEmptyFields = new QCheckBox( i18n("Show &empty fields"), behaviourTab );
cbShowFieldLabels = new QCheckBox( i18n("Show field &labels"), behaviourTab );
behaviourTab->setStretchFactor( new QWidget( behaviourTab ), 1 );
tabs->addTab( behaviourTab, i18n("Be&havior") );
}
void CardViewLookNFeelPage::updateFontLabel( QFont fnt, QLabel *l )
{
l->setFont( fnt );
l->setText( QString( fnt.family() + " %1" ).arg( fnt.pointSize() ) );
}
#include "configurecardviewdialog.moc"
<commit_msg>remove use of deprecated KGlobalSettings color getter<commit_after>/*
This file is part of KAddressBook.
Copyright (c) 2002 Mike Pilone <mpilone@slac.com>
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., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
As a special exception, permission is given to link this program
with any edition of Qt, and distribute the resulting executable,
without including the source code for Qt in the source distribution.
*/
#include <QString>
#include <QLayout>
#include <QLabel>
#include <QCheckBox>
#include <kvbox.h>
#include <q3groupbox.h>
#include <QSpinBox>
#include <QTabWidget>
//Added by qt3to4:
#include <QFrame>
#include <QGridLayout>
#include <kdebug.h>
#include <kglobal.h>
#include <KColorScheme>
#include <klocale.h>
#include <kiconloader.h>
#include <kconfig.h>
#include <kfontdialog.h>
#include <kpushbutton.h>
#include <libkdepim/colorlistbox.h>
#include "configurecardviewdialog.h"
/////////////////////////////////
// ConfigureCardViewDialog
ConfigureCardViewWidget::ConfigureCardViewWidget( KABC::AddressBook *ab, QWidget *parent )
: ViewConfigureWidget( ab, parent )
{
QWidget *page = addPage( i18n( "Look & Feel" ), QString(),
DesktopIcon( "looknfeel" ) );
mAdvancedPage = new CardViewLookNFeelPage( page );
}
ConfigureCardViewWidget::~ConfigureCardViewWidget()
{
}
void ConfigureCardViewWidget::restoreSettings( const KConfigGroup &config )
{
ViewConfigureWidget::restoreSettings( config );
mAdvancedPage->restoreSettings( config );
}
void ConfigureCardViewWidget::saveSettings( KConfigGroup &config )
{
ViewConfigureWidget::saveSettings( config );
mAdvancedPage->saveSettings( config );
}
////////////////////////
// CardViewLookNFeelPage
CardViewLookNFeelPage::CardViewLookNFeelPage( QWidget *parent )
: KVBox( parent )
{
initGUI();
}
CardViewLookNFeelPage::~CardViewLookNFeelPage()
{
}
void CardViewLookNFeelPage::restoreSettings( const KConfigGroup &config )
{
// colors
cbEnableCustomColors->setChecked( config.readEntry( "EnableCustomColors", false ) );
QColor c = KColorScheme(QPalette::Active).background().color();
lbColors->addColor( i18n("Background Color"),
config.readEntry( "BackgroundColor", c ) );
c = palette().color( QPalette::Foreground );
lbColors->addColor( i18n("Text Color"),
config.readEntry( "TextColor", c ) );
c = palette().color( QPalette::Button );
lbColors->addColor( i18n("Header, Border & Separator Color"),
config.readEntry( "HeaderColor", c ) );
c = palette().color( QPalette::ButtonText );
lbColors->addColor( i18n("Header Text Color"),
config.readEntry( "HeaderTextColor", c ) );
c = palette().color( QPalette::Highlight );
lbColors->addColor( i18n("Highlight Color"),
config.readEntry( "HighlightColor", c ) );
c = palette().color( QPalette::HighlightedText );
lbColors->addColor( i18n("Highlighted Text Color"),
config.readEntry( "HighlightedTextColor", c ) );
enableColors();
// fonts
QFont fnt = font();
updateFontLabel( config.readEntry( "TextFont", fnt ), (QLabel*)lTextFont );
fnt.setBold( true );
updateFontLabel( config.readEntry( "HeaderFont", fnt ), (QLabel*)lHeaderFont );
cbEnableCustomFonts->setChecked( config.readEntry( "EnableCustomFonts", false ) );
enableFonts();
// layout
sbMargin->setValue( config.readEntry( "ItemMargin", 0 ) );
sbSpacing->setValue( config.readEntry( "ItemSpacing", 10 ) );
sbSepWidth->setValue( config.readEntry( "SeparatorWidth", 2 ) );
cbDrawSeps->setChecked( config.readEntry( "DrawSeparators", true ) );
cbDrawBorders->setChecked( config.readEntry( "DrawBorder", true ) );
// behaviour
cbShowFieldLabels->setChecked( config.readEntry( "DrawFieldLabels", false ) );
cbShowEmptyFields->setChecked( config.readEntry( "ShowEmptyFields", false ) );
}
void CardViewLookNFeelPage::saveSettings( KConfigGroup &config )
{
// colors
config.writeEntry( "EnableCustomColors", cbEnableCustomColors->isChecked() );
if ( cbEnableCustomColors->isChecked() ) // ?? - Hmmm.
{
config.writeEntry( "BackgroundColor", lbColors->color( 0 ) );
config.writeEntry( "TextColor", lbColors->color( 1 ) );
config.writeEntry( "HeaderColor", lbColors->color( 2 ) );
config.writeEntry( "HeaderTextColor", lbColors->color( 3 ) );
config.writeEntry( "HighlightColor", lbColors->color( 4 ) );
config.writeEntry( "HighlightedTextColor", lbColors->color( 5 ) );
}
// fonts
config.writeEntry( "EnableCustomFonts", cbEnableCustomFonts->isChecked() );
if ( cbEnableCustomFonts->isChecked() )
{
config.writeEntry( "TextFont", lTextFont->font() );
config.writeEntry( "HeaderFont", lHeaderFont->font() );
}
// layout
config.writeEntry( "ItemMargin", sbMargin->value() );
config.writeEntry( "ItemSpacing", sbSpacing->value() );
config.writeEntry( "SeparatorWidth", sbSepWidth->value() );
config.writeEntry("DrawBorder", cbDrawBorders->isChecked());
config.writeEntry("DrawSeparators", cbDrawSeps->isChecked());
// behaviour
config.writeEntry("DrawFieldLabels", cbShowFieldLabels->isChecked());
config.writeEntry("ShowEmptyFields", cbShowEmptyFields->isChecked());
}
void CardViewLookNFeelPage::setTextFont()
{
QFont f( lTextFont->font() );
if ( KFontDialog::getFont( f, false, this ) == QDialog::Accepted )
updateFontLabel( f, lTextFont );
}
void CardViewLookNFeelPage::setHeaderFont()
{
QFont f( lHeaderFont->font() );
if ( KFontDialog::getFont( f,false, this ) == QDialog::Accepted )
updateFontLabel( f, lHeaderFont );
}
void CardViewLookNFeelPage::enableFonts()
{
vbFonts->setEnabled( cbEnableCustomFonts->isChecked() );
}
void CardViewLookNFeelPage::enableColors()
{
lbColors->setEnabled( cbEnableCustomColors->isChecked() );
}
void CardViewLookNFeelPage::initGUI()
{
int spacing = KDialog::spacingHint();
int margin = KDialog::marginHint();
QTabWidget *tabs = new QTabWidget( this );
// Layout
KVBox *loTab = new KVBox( this );
loTab->setSpacing( spacing );
loTab->setMargin( margin );
Q3GroupBox *gbGeneral = new Q3GroupBox( 1, Qt::Horizontal, i18n("General"), loTab );
cbDrawSeps = new QCheckBox( i18n("Draw &separators"), gbGeneral );
KHBox *hbSW = new KHBox( gbGeneral );
QLabel *lSW = new QLabel( i18n("Separator &width:"), hbSW );
sbSepWidth = new QSpinBox( hbSW );
sbSepWidth->setRange( 1, 50 );
lSW->setBuddy( sbSepWidth);
KHBox *hbPadding = new KHBox( gbGeneral );
QLabel *lSpacing = new QLabel( i18n("&Padding:"), hbPadding );
sbSpacing = new QSpinBox( hbPadding );
sbSpacing->setRange( 0, 100 );
lSpacing->setBuddy( sbSpacing );
Q3GroupBox *gbCards = new Q3GroupBox( 1, Qt::Horizontal, i18n("Cards"), loTab );
KHBox *hbMargin = new KHBox( gbCards );
QLabel *lMargin = new QLabel( i18n("&Margin:"), hbMargin );
sbMargin = new QSpinBox( hbMargin );
sbMargin->setRange( 0, 100 );
lMargin->setBuddy( sbMargin );
cbDrawBorders = new QCheckBox( i18n("Draw &borders"), gbCards );
loTab->setStretchFactor( new QWidget( loTab ), 1 );
QString text = i18n(
"The item margin is the distance (in pixels) between the item edge and the item data. Most noticeably, "
"incrementing the item margin will add space between the focus rectangle and the item data."
);
sbMargin->setWhatsThis( text );
lMargin->setWhatsThis( text );
text = i18n(
"The item spacing decides the distance (in pixels) between the items and anything else: the view "
"borders, other items or column separators."
);
sbSpacing->setWhatsThis( text );
lSpacing->setWhatsThis( text );
text = i18n("Sets the width of column separators");
sbSepWidth->setWhatsThis( text );
lSW->setWhatsThis( text );
tabs->addTab( loTab, i18n("&Layout") );
// Colors
KVBox *colorTab = new KVBox( this );
colorTab->setSpacing( spacing );
colorTab->setMargin( spacing );
cbEnableCustomColors = new QCheckBox( i18n("&Enable custom colors"), colorTab );
connect( cbEnableCustomColors, SIGNAL(clicked()), this, SLOT(enableColors()) );
lbColors = new KPIM::ColorListBox( colorTab );
tabs->addTab( colorTab, i18n("&Colors") );
cbEnableCustomColors->setWhatsThis( i18n(
"If custom colors is enabled, you may choose the colors for the view below. "
"Otherwise colors from your current KDE color scheme are used."
) );
lbColors->setWhatsThis( i18n(
"Double click or press RETURN on a item to select a color for the related strings in the view."
) );
// Fonts
KVBox *fntTab = new KVBox( this );
fntTab->setSpacing( spacing );
fntTab->setMargin( spacing );
cbEnableCustomFonts = new QCheckBox( i18n("&Enable custom fonts"), fntTab );
connect( cbEnableCustomFonts, SIGNAL(clicked()), this, SLOT(enableFonts()) );
vbFonts = new QWidget( fntTab );
QGridLayout *gFnts = new QGridLayout( vbFonts );
gFnts->setSpacing( spacing );
gFnts->setAutoAdd( true );
gFnts->setColumnStretch( 1, 1 );
QLabel *lTFnt = new QLabel( i18n("&Text font:"), vbFonts );
lTextFont = new QLabel( vbFonts );
lTextFont->setFrameStyle( QFrame::Panel|QFrame::Sunken );
btnFont = new KPushButton( i18n("Choose..."), vbFonts );
lTFnt->setBuddy( btnFont );
connect( btnFont, SIGNAL(clicked()), this, SLOT(setTextFont()) );
QLabel *lHFnt = new QLabel( i18n("&Header font:"), vbFonts );
lHeaderFont = new QLabel( vbFonts );
lHeaderFont->setFrameStyle( QFrame::Panel|QFrame::Sunken );
btnHeaderFont = new KPushButton( i18n("Choose..."), vbFonts );
lHFnt->setBuddy( btnHeaderFont );
connect( btnHeaderFont, SIGNAL(clicked()), this, SLOT(setHeaderFont()) );
fntTab->setStretchFactor( new QWidget( fntTab ), 1 );
cbEnableCustomFonts->setWhatsThis( i18n(
"If custom fonts are enabled, you may choose which fonts to use for this view below. "
"Otherwise the default KDE font will be used, in bold style for the header and "
"normal style for the data."
) );
tabs->addTab( fntTab, i18n("&Fonts") );
// Behaviour
KVBox *behaviourTab = new KVBox( this );
behaviourTab->setMargin( margin );
behaviourTab->setSpacing( spacing );
cbShowEmptyFields = new QCheckBox( i18n("Show &empty fields"), behaviourTab );
cbShowFieldLabels = new QCheckBox( i18n("Show field &labels"), behaviourTab );
behaviourTab->setStretchFactor( new QWidget( behaviourTab ), 1 );
tabs->addTab( behaviourTab, i18n("Be&havior") );
}
void CardViewLookNFeelPage::updateFontLabel( QFont fnt, QLabel *l )
{
l->setFont( fnt );
l->setText( QString( fnt.family() + " %1" ).arg( fnt.pointSize() ) );
}
#include "configurecardviewdialog.moc"
<|endoftext|> |
<commit_before>/*
Copyright (c) 2011, Arvid Norberg, Magnus Jonsson
All rights reserved.
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions
are met:
* Redistributions of source code must retain the above copyright
notice, this list of conditions and the following disclaimer.
* Redistributions in binary form must reproduce the above copyright
notice, this list of conditions and the following disclaimer in
the documentation and/or other materials provided with the distribution.
* Neither the name of the author nor the names of its
contributors may be used to endorse or promote products derived
from this software without specific prior written permission.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE
LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
POSSIBILITY OF SUCH DAMAGE.
*/
#include "libtorrent/rsa.hpp"
#include "libtorrent/hasher.hpp"
#if defined TORRENT_USE_OPENSSL
extern "C"
{
#include <openssl/rsa.h>
#include <openssl/objects.h> // for NID_sha1
}
namespace libtorrent
{
// returns the size of the resulting signature
int sign_rsa(sha1_hash const& digest
, char const* private_key, int private_len
, char* signature, int sig_len)
{
// convert bytestring to internal representation
// of the private key
RSA* priv = 0;
unsigned char const* key = (unsigned char const*)private_key;
priv = d2i_RSAPrivateKey(&priv, &key, private_len);
if (priv == 0) return -1;
if (RSA_size(priv) > sig_len)
{
RSA_free(priv);
return -1;
}
RSA_sign(NID_sha1, &digest[0], 20, (unsigned char*)signature, (unsigned int*)&sig_len, priv);
RSA_free(priv);
return sig_len;
}
// returns true if the signature is valid
bool verify_rsa(sha1_hash const& digest
, char const* public_key, int public_len
, char const* signature, int sig_len)
{
// convert bytestring to internal representation
// of the public key
RSA* pub = 0;
unsigned char const* key = (unsigned char const*)public_key;
pub = d2i_RSAPublicKey(&pub, &key, public_len);
if (pub == 0) return false;
int ret = RSA_verify(NID_sha1, &digest[0], 20, (unsigned char*)signature, sig_len, pub);
RSA_free(pub);
return ret;
}
bool generate_rsa_keys(char* public_key, int* public_len
, char* private_key, int* private_len, int key_size)
{
RSA* keypair = RSA_generate_key(key_size, 3, 0, 0);
if (keypair == 0) return false;
bool ret = false;
if (RSA_size(keypair) > *public_len) goto getout;
if (RSA_size(keypair) > *private_len) goto getout;
unsigned char* pub = (unsigned char*)public_key;
unsigned char* priv = (unsigned char*)private_key;
*public_len = i2d_RSAPublicKey(keypair, &pub);
*private_len = i2d_RSAPrivateKey(keypair, &priv);
ret = true;
getout:
RSA_free(keypair);
return ret;
}
} // namespace libtorrent
#else
// just stub these out for now, since they're not used anywhere yet
namespace libtorrent
{
// returns the size of the resulting signature
int sign_rsa(sha1_hash const& digest
, char const* private_key, int private_len
, char* signature, int sig_len)
{
return 0;
}
// returns true if the signature is valid
bool verify_rsa(sha1_hash const& digest
, char const* public_key, int public_len
, char const* signature, int sig_len)
{
return false;
}
bool generate_rsa_keys(char* public_key, int* public_len
, char* private_key, int* private_len, int key_size)
{
return false;
}
} // namespace libtorrent
#endif
<commit_msg>fixed build issue<commit_after>/*
Copyright (c) 2011, Arvid Norberg, Magnus Jonsson
All rights reserved.
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions
are met:
* Redistributions of source code must retain the above copyright
notice, this list of conditions and the following disclaimer.
* Redistributions in binary form must reproduce the above copyright
notice, this list of conditions and the following disclaimer in
the documentation and/or other materials provided with the distribution.
* Neither the name of the author nor the names of its
contributors may be used to endorse or promote products derived
from this software without specific prior written permission.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE
LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
POSSIBILITY OF SUCH DAMAGE.
*/
#include "libtorrent/rsa.hpp"
#include "libtorrent/hasher.hpp"
#if defined TORRENT_USE_OPENSSL
extern "C"
{
#include <openssl/rsa.h>
#include <openssl/objects.h> // for NID_sha1
}
namespace libtorrent
{
// returns the size of the resulting signature
int sign_rsa(sha1_hash const& digest
, char const* private_key, int private_len
, char* signature, int sig_len)
{
// convert bytestring to internal representation
// of the private key
RSA* priv = 0;
unsigned char const* key = (unsigned char const*)private_key;
priv = d2i_RSAPrivateKey(&priv, &key, private_len);
if (priv == 0) return -1;
if (RSA_size(priv) > sig_len)
{
RSA_free(priv);
return -1;
}
RSA_sign(NID_sha1, &digest[0], 20, (unsigned char*)signature, (unsigned int*)&sig_len, priv);
RSA_free(priv);
return sig_len;
}
// returns true if the signature is valid
bool verify_rsa(sha1_hash const& digest
, char const* public_key, int public_len
, char const* signature, int sig_len)
{
// convert bytestring to internal representation
// of the public key
RSA* pub = 0;
unsigned char const* key = (unsigned char const*)public_key;
pub = d2i_RSAPublicKey(&pub, &key, public_len);
if (pub == 0) return false;
int ret = RSA_verify(NID_sha1, &digest[0], 20, (unsigned char*)signature, sig_len, pub);
RSA_free(pub);
return ret;
}
bool generate_rsa_keys(char* public_key, int* public_len
, char* private_key, int* private_len, int key_size)
{
RSA* keypair = RSA_generate_key(key_size, 3, 0, 0);
if (keypair == 0) return false;
bool ret = false;
unsigned char* pub = (unsigned char*)public_key;
unsigned char* priv = (unsigned char*)private_key;
if (RSA_size(keypair) > *public_len) goto getout;
if (RSA_size(keypair) > *private_len) goto getout;
*public_len = i2d_RSAPublicKey(keypair, &pub);
*private_len = i2d_RSAPrivateKey(keypair, &priv);
ret = true;
getout:
RSA_free(keypair);
return ret;
}
} // namespace libtorrent
#else
// just stub these out for now, since they're not used anywhere yet
namespace libtorrent
{
// returns the size of the resulting signature
int sign_rsa(sha1_hash const& digest
, char const* private_key, int private_len
, char* signature, int sig_len)
{
return 0;
}
// returns true if the signature is valid
bool verify_rsa(sha1_hash const& digest
, char const* public_key, int public_len
, char const* signature, int sig_len)
{
return false;
}
bool generate_rsa_keys(char* public_key, int* public_len
, char* private_key, int* private_len, int key_size)
{
return false;
}
} // namespace libtorrent
#endif
<|endoftext|> |
<commit_before>#include <uri>
#include <regex>
#include <iostream>
using namespace uri;
///////////////////////////////////////////////////////////////////////////////
const URI::Span_t URI::zero_span_;
///////////////////////////////////////////////////////////////////////////////
URI::URI(const char* uri)
: URI{std::string{uri}}
{}
///////////////////////////////////////////////////////////////////////////////
URI::URI(const std::string& uri)
: uri_str_{uri}
, port_{}
{
parse(uri_str_);
load_queries();
}
///////////////////////////////////////////////////////////////////////////////
const std::string& URI::scheme() const {
static std::string scheme;
if (scheme.empty()) {
scheme = uri_str_.substr(scheme_.begin, scheme_.end);
}
return scheme;
}
///////////////////////////////////////////////////////////////////////////////
const std::string& URI::userinfo() const {
static std::string userinfo;
if (userinfo.empty()) {
userinfo = uri_str_.substr(userinfo_.begin, userinfo_.end);
}
return userinfo;
}
///////////////////////////////////////////////////////////////////////////////
const std::string& URI::host() const {
static std::string host;
if (host.empty()) {
host = uri_str_.substr(host_.begin, host_.end);
}
return host;
}
///////////////////////////////////////////////////////////////////////////////
const std::string& URI::port_str() const {
static std::string port;
if (port.empty()) {
port = uri_str_.substr(port_str_.begin, port_str_.end);
}
return port;
}
///////////////////////////////////////////////////////////////////////////////
uint16_t URI::port() const noexcept {
if (not port_) {
port_ = port_str_.begin ? static_cast<uint16_t>(std::stoi(port_str())) : 0;
}
return port_;
}
///////////////////////////////////////////////////////////////////////////////
const std::string& URI::path() const {
static std::string path;
if (path.empty()) {
path = uri_str_.substr(path_.begin, path_.end);
}
return path;
}
///////////////////////////////////////////////////////////////////////////////
const std::string& URI::query() const {
static std::string query;
if (query.empty()){
query = uri_str_.substr(query_.begin, query_.end);
}
return query;
}
///////////////////////////////////////////////////////////////////////////////
const std::string& URI::fragment() const {
static std::string fragment;
if (fragment.empty()) {
fragment = uri_str_.substr(fragment_.begin, fragment_.end);
}
return fragment;
}
///////////////////////////////////////////////////////////////////////////////
const std::string& URI::query(const std::string& key) {
auto target = queries_.find(key);
return (target not_eq queries_.end()) ? target->second : "";
}
///////////////////////////////////////////////////////////////////////////////
std::string URI::to_string() const{
return uri_str_;
}
///////////////////////////////////////////////////////////////////////////////
URI::operator std::string () const {
return uri_str_;
}
///////////////////////////////////////////////////////////////////////////////
void URI::parse(const std::string& uri) {
static const std::regex uri_pattern_matcher
{
"^([a-zA-z]+[\\w\\+\\-\\.]+)?(\\://)?" //< scheme
"(([^:@]+)(\\:([^@]+))?@)?" //< username && password
"([^/:?#]+)?(\\:(\\d+))?" //< hostname && port
"([^?#]+)" //< path
"(\\?([^#]*))?" //< query
"(#(.*))?$" //< fragment
};
static std::smatch uri_parts;
if (std::regex_match(uri, uri_parts, uri_pattern_matcher)) {
path_ = Span_t(uri_parts.position(10), uri_parts.length(10));
scheme_ = uri_parts.length(1) ? Span_t(uri_parts.position(1), uri_parts.length(1)) : zero_span_;
userinfo_ = uri_parts.length(3) ? Span_t(uri_parts.position(3), uri_parts.length(3)) : zero_span_;
host_ = uri_parts.length(7) ? Span_t(uri_parts.position(7), uri_parts.length(7)) : zero_span_;
port_str_ = uri_parts.length(9) ? Span_t(uri_parts.position(9), uri_parts.length(9)) : zero_span_;
query_ = uri_parts.length(11) ? Span_t(uri_parts.position(11), uri_parts.length(11)) : zero_span_;
fragment_ = uri_parts.length(13) ? Span_t(uri_parts.position(13), uri_parts.length(13)) : zero_span_;
}
}
///////////////////////////////////////////////////////////////////////////////
void URI::load_queries() {
const std::regex queries_matcher
{
"([^?=&]+)"
};
auto& queries = query();
auto position = std::sregex_iterator(queries.begin(), queries.end(), queries_matcher);
auto end = std::sregex_iterator();
while (position not_eq end) {
auto key = (*position).str();
if ((++position) not_eq end) {
queries_[key] = (*position++).str();
continue;
} else {
queries_[key];
}
}
}
///////////////////////////////////////////////////////////////////////////////
std::ostream& uri::operator<< (std::ostream& out, const URI& uri) {
return out << uri.to_string();
}
<commit_msg>Added <no value> representation in URI::query(const std::string&)<commit_after>#include <uri>
#include <regex>
#include <iostream>
using namespace uri;
///////////////////////////////////////////////////////////////////////////////
const URI::Span_t URI::zero_span_;
///////////////////////////////////////////////////////////////////////////////
URI::URI(const char* uri)
: URI{std::string{uri}}
{}
///////////////////////////////////////////////////////////////////////////////
URI::URI(const std::string& uri)
: uri_str_{uri}
, port_{}
{
parse(uri_str_);
load_queries();
}
///////////////////////////////////////////////////////////////////////////////
const std::string& URI::scheme() const {
static std::string scheme;
if (scheme.empty()) {
scheme = uri_str_.substr(scheme_.begin, scheme_.end);
}
return scheme;
}
///////////////////////////////////////////////////////////////////////////////
const std::string& URI::userinfo() const {
static std::string userinfo;
if (userinfo.empty()) {
userinfo = uri_str_.substr(userinfo_.begin, userinfo_.end);
}
return userinfo;
}
///////////////////////////////////////////////////////////////////////////////
const std::string& URI::host() const {
static std::string host;
if (host.empty()) {
host = uri_str_.substr(host_.begin, host_.end);
}
return host;
}
///////////////////////////////////////////////////////////////////////////////
const std::string& URI::port_str() const {
static std::string port;
if (port.empty()) {
port = uri_str_.substr(port_str_.begin, port_str_.end);
}
return port;
}
///////////////////////////////////////////////////////////////////////////////
uint16_t URI::port() const noexcept {
if (not port_) {
port_ = port_str_.begin ? static_cast<uint16_t>(std::stoi(port_str())) : 0;
}
return port_;
}
///////////////////////////////////////////////////////////////////////////////
const std::string& URI::path() const {
static std::string path;
if (path.empty()) {
path = uri_str_.substr(path_.begin, path_.end);
}
return path;
}
///////////////////////////////////////////////////////////////////////////////
const std::string& URI::query() const {
static std::string query;
if (query.empty()){
query = uri_str_.substr(query_.begin, query_.end);
}
return query;
}
///////////////////////////////////////////////////////////////////////////////
const std::string& URI::fragment() const {
static std::string fragment;
if (fragment.empty()) {
fragment = uri_str_.substr(fragment_.begin, fragment_.end);
}
return fragment;
}
///////////////////////////////////////////////////////////////////////////////
const std::string& URI::query(const std::string& key) {
static std::string no_entry_value;
auto target = queries_.find(key);
return (target not_eq queries_.end()) ? target->second : no_entry_value;
}
///////////////////////////////////////////////////////////////////////////////
std::string URI::to_string() const{
return uri_str_;
}
///////////////////////////////////////////////////////////////////////////////
URI::operator std::string () const {
return uri_str_;
}
///////////////////////////////////////////////////////////////////////////////
void URI::parse(const std::string& uri) {
static const std::regex uri_pattern_matcher
{
"^([a-zA-z]+[\\w\\+\\-\\.]+)?(\\://)?" //< scheme
"(([^:@]+)(\\:([^@]+))?@)?" //< username && password
"([^/:?#]+)?(\\:(\\d+))?" //< hostname && port
"([^?#]+)" //< path
"(\\?([^#]*))?" //< query
"(#(.*))?$" //< fragment
};
static std::smatch uri_parts;
if (std::regex_match(uri, uri_parts, uri_pattern_matcher)) {
path_ = Span_t(uri_parts.position(10), uri_parts.length(10));
scheme_ = uri_parts.length(1) ? Span_t(uri_parts.position(1), uri_parts.length(1)) : zero_span_;
userinfo_ = uri_parts.length(3) ? Span_t(uri_parts.position(3), uri_parts.length(3)) : zero_span_;
host_ = uri_parts.length(7) ? Span_t(uri_parts.position(7), uri_parts.length(7)) : zero_span_;
port_str_ = uri_parts.length(9) ? Span_t(uri_parts.position(9), uri_parts.length(9)) : zero_span_;
query_ = uri_parts.length(11) ? Span_t(uri_parts.position(11), uri_parts.length(11)) : zero_span_;
fragment_ = uri_parts.length(13) ? Span_t(uri_parts.position(13), uri_parts.length(13)) : zero_span_;
}
}
///////////////////////////////////////////////////////////////////////////////
void URI::load_queries() {
const std::regex queries_matcher
{
"([^?=&]+)"
};
auto& queries = query();
auto position = std::sregex_iterator(queries.begin(), queries.end(), queries_matcher);
auto end = std::sregex_iterator();
while (position not_eq end) {
auto key = (*position).str();
if ((++position) not_eq end) {
queries_[key] = (*position++).str();
continue;
} else {
queries_[key];
}
}
}
///////////////////////////////////////////////////////////////////////////////
std::ostream& uri::operator<< (std::ostream& out, const URI& uri) {
return out << uri.to_string();
}
<|endoftext|> |
<commit_before>// Copyright 2011 Google Inc. All Rights Reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may 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 "util.h"
#ifdef _WIN32
#include <windows.h>
#include <io.h>
#include <share.h>
#endif
#include <assert.h>
#include <errno.h>
#include <fcntl.h>
#include <stdarg.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <sys/stat.h>
#include <sys/types.h>
#ifndef _WIN32
#include <unistd.h>
#include <sys/time.h>
#endif
#include <vector>
#if defined(__APPLE__) || defined(__FreeBSD__)
#include <sys/sysctl.h>
#elif defined(__SVR4) && defined(__sun)
#include <unistd.h>
#include <sys/loadavg.h>
#elif defined(linux) || defined(__GLIBC__)
#include <sys/sysinfo.h>
#endif
#include "edit_distance.h"
#include "metrics.h"
void Fatal(const char* msg, ...) {
va_list ap;
fprintf(stderr, "ninja: fatal: ");
va_start(ap, msg);
vfprintf(stderr, msg, ap);
va_end(ap);
fprintf(stderr, "\n");
#ifdef _WIN32
// On Windows, some tools may inject extra threads.
// exit() may block on locks held by those threads, so forcibly exit.
fflush(stderr);
fflush(stdout);
ExitProcess(1);
#else
exit(1);
#endif
}
void Warning(const char* msg, ...) {
va_list ap;
fprintf(stderr, "ninja: warning: ");
va_start(ap, msg);
vfprintf(stderr, msg, ap);
va_end(ap);
fprintf(stderr, "\n");
}
void Error(const char* msg, ...) {
va_list ap;
fprintf(stderr, "ninja: error: ");
va_start(ap, msg);
vfprintf(stderr, msg, ap);
va_end(ap);
fprintf(stderr, "\n");
}
bool CanonicalizePath(string* path, string* err) {
METRIC_RECORD("canonicalize str");
size_t len = path->size();
char* str = 0;
if (len > 0)
str = &(*path)[0];
if (!CanonicalizePath(str, &len, err))
return false;
path->resize(len);
return true;
}
bool CanonicalizePath(char* path, size_t* len, string* err) {
// WARNING: this function is performance-critical; please benchmark
// any changes you make to it.
METRIC_RECORD("canonicalize path");
if (*len == 0) {
*err = "empty path";
return false;
}
const int kMaxPathComponents = 30;
char* components[kMaxPathComponents];
int component_count = 0;
char* start = path;
char* dst = start;
const char* src = start;
const char* end = start + *len;
if (*src == '/') {
#ifdef _WIN32
// network path starts with //
if (*len > 1 && *(src + 1) == '/') {
src += 2;
dst += 2;
} else {
++src;
++dst;
}
#else
++src;
++dst;
#endif
}
while (src < end) {
if (*src == '.') {
if (src + 1 == end || src[1] == '/') {
// '.' component; eliminate.
src += 2;
continue;
} else if (src[1] == '.' && (src + 2 == end || src[2] == '/')) {
// '..' component. Back up if possible.
if (component_count > 0) {
dst = components[component_count - 1];
src += 3;
--component_count;
} else {
*dst++ = *src++;
*dst++ = *src++;
*dst++ = *src++;
}
continue;
}
}
if (*src == '/') {
src++;
continue;
}
if (component_count == kMaxPathComponents)
Fatal("path has too many components : %s", path);
components[component_count] = dst;
++component_count;
while (*src != '/' && src != end)
*dst++ = *src++;
*dst++ = *src++; // Copy '/' or final \0 character as well.
}
if (dst == start) {
*err = "path canonicalizes to the empty path";
return false;
}
*len = dst - start - 1;
return true;
}
static inline bool IsKnownShellSafeCharacter(char ch) {
if ('A' <= ch && ch <= 'Z') return true;
if ('a' <= ch && ch <= 'z') return true;
if ('0' <= ch && ch <= '9') return true;
switch (ch) {
case '_':
case '+':
case '-':
case '.':
case '/':
return true;
default:
return false;
}
}
static inline bool IsKnownWin32SafeCharacter(char ch) {
switch (ch) {
case ' ':
case '"':
return false;
default:
return true;
}
}
static inline bool StringNeedsShellEscaping(const string& input) {
for (size_t i = 0; i < input.size(); ++i) {
if (!IsKnownShellSafeCharacter(input[i])) return true;
}
return false;
}
static inline bool StringNeedsWin32Escaping(const string& input) {
for (size_t i = 0; i < input.size(); ++i) {
if (!IsKnownWin32SafeCharacter(input[i])) return true;
}
return false;
}
void GetShellEscapedString(const string& input, string* result) {
assert(result);
if (!StringNeedsShellEscaping(input)) {
result->append(input);
return;
}
const char kQuote = '\'';
const char kEscapeSequence[] = "'\\'";
result->push_back(kQuote);
string::const_iterator span_begin = input.begin();
for (string::const_iterator it = input.begin(), end = input.end(); it != end;
++it) {
if (*it == kQuote) {
result->append(span_begin, it);
result->append(kEscapeSequence);
span_begin = it;
}
}
result->append(span_begin, input.end());
result->push_back(kQuote);
}
void GetWin32EscapedString(const string& input, string* result) {
assert(result);
if (!StringNeedsWin32Escaping(input)) {
result->append(input);
return;
}
const char kQuote = '"';
const char kBackslash = '\\';
result->push_back(kQuote);
size_t consecutive_backslash_count = 0;
string::const_iterator span_begin = input.begin();
for (string::const_iterator it = input.begin(), end = input.end(); it != end;
++it) {
switch (*it) {
case kBackslash:
++consecutive_backslash_count;
break;
case kQuote:
result->append(span_begin, it);
result->append(consecutive_backslash_count + 1, kBackslash);
span_begin = it;
consecutive_backslash_count = 0;
break;
default:
consecutive_backslash_count = 0;
break;
}
}
result->append(span_begin, input.end());
result->append(consecutive_backslash_count, kBackslash);
result->push_back(kQuote);
}
int ReadFile(const string& path, string* contents, string* err) {
FILE* f = fopen(path.c_str(), "r");
if (!f) {
err->assign(strerror(errno));
return -errno;
}
char buf[64 << 10];
size_t len;
while ((len = fread(buf, 1, sizeof(buf), f)) > 0) {
contents->append(buf, len);
}
if (ferror(f)) {
err->assign(strerror(errno)); // XXX errno?
contents->clear();
fclose(f);
return -errno;
}
fclose(f);
return 0;
}
void SetCloseOnExec(int fd) {
#ifndef _WIN32
int flags = fcntl(fd, F_GETFD);
if (flags < 0) {
perror("fcntl(F_GETFD)");
} else {
if (fcntl(fd, F_SETFD, flags | FD_CLOEXEC) < 0)
perror("fcntl(F_SETFD)");
}
#else
HANDLE hd = (HANDLE) _get_osfhandle(fd);
if (! SetHandleInformation(hd, HANDLE_FLAG_INHERIT, 0)) {
fprintf(stderr, "SetHandleInformation(): %s", GetLastErrorString().c_str());
}
#endif // ! _WIN32
}
const char* SpellcheckStringV(const string& text,
const vector<const char*>& words) {
const bool kAllowReplacements = true;
const int kMaxValidEditDistance = 3;
int min_distance = kMaxValidEditDistance + 1;
const char* result = NULL;
for (vector<const char*>::const_iterator i = words.begin();
i != words.end(); ++i) {
int distance = EditDistance(*i, text, kAllowReplacements,
kMaxValidEditDistance);
if (distance < min_distance) {
min_distance = distance;
result = *i;
}
}
return result;
}
const char* SpellcheckString(const char* text, ...) {
// Note: This takes a const char* instead of a string& because using
// va_start() with a reference parameter is undefined behavior.
va_list ap;
va_start(ap, text);
vector<const char*> words;
const char* word;
while ((word = va_arg(ap, const char*)))
words.push_back(word);
va_end(ap);
return SpellcheckStringV(text, words);
}
#ifdef _WIN32
string GetLastErrorString() {
DWORD err = GetLastError();
char* msg_buf;
FormatMessageA(
FORMAT_MESSAGE_ALLOCATE_BUFFER |
FORMAT_MESSAGE_FROM_SYSTEM |
FORMAT_MESSAGE_IGNORE_INSERTS,
NULL,
err,
MAKELANGID(LANG_NEUTRAL, SUBLANG_DEFAULT),
(char*)&msg_buf,
0,
NULL);
string msg = msg_buf;
LocalFree(msg_buf);
return msg;
}
void Win32Fatal(const char* function) {
Fatal("%s: %s", function, GetLastErrorString().c_str());
}
#endif
static bool islatinalpha(int c) {
// isalpha() is locale-dependent.
return (c >= 'a' && c <= 'z') || (c >= 'A' && c <= 'Z');
}
string StripAnsiEscapeCodes(const string& in) {
string stripped;
stripped.reserve(in.size());
for (size_t i = 0; i < in.size(); ++i) {
if (in[i] != '\33') {
// Not an escape code.
stripped.push_back(in[i]);
continue;
}
// Only strip CSIs for now.
if (i + 1 >= in.size()) break;
if (in[i + 1] != '[') continue; // Not a CSI.
i += 2;
// Skip everything up to and including the next [a-zA-Z].
while (i < in.size() && !islatinalpha(in[i]))
++i;
}
return stripped;
}
int GetProcessorCount() {
#ifdef _WIN32
SYSTEM_INFO info;
GetSystemInfo(&info);
return info.dwNumberOfProcessors;
#else
return sysconf(_SC_NPROCESSORS_ONLN);
#endif
}
#if defined(_WIN32) || defined(__CYGWIN__)
double GetLoadAverage() {
// TODO(nicolas.despres@gmail.com): Find a way to implement it on Windows.
// Remember to also update Usage() when this is fixed.
return -0.0f;
}
#else
double GetLoadAverage() {
double loadavg[3] = { 0.0f, 0.0f, 0.0f };
if (getloadavg(loadavg, 3) < 0) {
// Maybe we should return an error here or the availability of
// getloadavg(3) should be checked when ninja is configured.
return -0.0f;
}
return loadavg[0];
}
#endif // _WIN32
string ElideMiddle(const string& str, size_t width) {
const int kMargin = 3; // Space for "...".
string result = str;
if (result.size() + kMargin > width) {
size_t elide_size = (width - kMargin) / 2;
result = result.substr(0, elide_size)
+ "..."
+ result.substr(result.size() - elide_size, elide_size);
}
return result;
}
bool Truncate(const string& path, size_t size, string* err) {
#ifdef _WIN32
int fh = _sopen(path.c_str(), _O_RDWR | _O_CREAT, _SH_DENYNO,
_S_IREAD | _S_IWRITE);
int success = _chsize(fh, size);
_close(fh);
#else
int success = truncate(path.c_str(), size);
#endif
// Both truncate() and _chsize() return 0 on success and set errno and return
// -1 on failure.
if (success < 0) {
*err = strerror(errno);
return false;
}
return true;
}
<commit_msg>Prepared load (-l N) support for windows.<commit_after>// Copyright 2011 Google Inc. All Rights Reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may 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 "util.h"
#ifdef _WIN32
#include <windows.h>
#include <io.h>
#include <share.h>
#endif
#include <assert.h>
#include <errno.h>
#include <fcntl.h>
#include <stdarg.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <sys/stat.h>
#include <sys/types.h>
#ifndef _WIN32
#include <unistd.h>
#include <sys/time.h>
#endif
#include <vector>
#if defined(__APPLE__) || defined(__FreeBSD__)
#include <sys/sysctl.h>
#elif defined(__SVR4) && defined(__sun)
#include <unistd.h>
#include <sys/loadavg.h>
#elif defined(linux) || defined(__GLIBC__)
#include <sys/sysinfo.h>
#endif
#include "edit_distance.h"
#include "metrics.h"
void Fatal(const char* msg, ...) {
va_list ap;
fprintf(stderr, "ninja: fatal: ");
va_start(ap, msg);
vfprintf(stderr, msg, ap);
va_end(ap);
fprintf(stderr, "\n");
#ifdef _WIN32
// On Windows, some tools may inject extra threads.
// exit() may block on locks held by those threads, so forcibly exit.
fflush(stderr);
fflush(stdout);
ExitProcess(1);
#else
exit(1);
#endif
}
void Warning(const char* msg, ...) {
va_list ap;
fprintf(stderr, "ninja: warning: ");
va_start(ap, msg);
vfprintf(stderr, msg, ap);
va_end(ap);
fprintf(stderr, "\n");
}
void Error(const char* msg, ...) {
va_list ap;
fprintf(stderr, "ninja: error: ");
va_start(ap, msg);
vfprintf(stderr, msg, ap);
va_end(ap);
fprintf(stderr, "\n");
}
bool CanonicalizePath(string* path, string* err) {
METRIC_RECORD("canonicalize str");
size_t len = path->size();
char* str = 0;
if (len > 0)
str = &(*path)[0];
if (!CanonicalizePath(str, &len, err))
return false;
path->resize(len);
return true;
}
bool CanonicalizePath(char* path, size_t* len, string* err) {
// WARNING: this function is performance-critical; please benchmark
// any changes you make to it.
METRIC_RECORD("canonicalize path");
if (*len == 0) {
*err = "empty path";
return false;
}
const int kMaxPathComponents = 30;
char* components[kMaxPathComponents];
int component_count = 0;
char* start = path;
char* dst = start;
const char* src = start;
const char* end = start + *len;
if (*src == '/') {
#ifdef _WIN32
// network path starts with //
if (*len > 1 && *(src + 1) == '/') {
src += 2;
dst += 2;
} else {
++src;
++dst;
}
#else
++src;
++dst;
#endif
}
while (src < end) {
if (*src == '.') {
if (src + 1 == end || src[1] == '/') {
// '.' component; eliminate.
src += 2;
continue;
} else if (src[1] == '.' && (src + 2 == end || src[2] == '/')) {
// '..' component. Back up if possible.
if (component_count > 0) {
dst = components[component_count - 1];
src += 3;
--component_count;
} else {
*dst++ = *src++;
*dst++ = *src++;
*dst++ = *src++;
}
continue;
}
}
if (*src == '/') {
src++;
continue;
}
if (component_count == kMaxPathComponents)
Fatal("path has too many components : %s", path);
components[component_count] = dst;
++component_count;
while (*src != '/' && src != end)
*dst++ = *src++;
*dst++ = *src++; // Copy '/' or final \0 character as well.
}
if (dst == start) {
*err = "path canonicalizes to the empty path";
return false;
}
*len = dst - start - 1;
return true;
}
static inline bool IsKnownShellSafeCharacter(char ch) {
if ('A' <= ch && ch <= 'Z') return true;
if ('a' <= ch && ch <= 'z') return true;
if ('0' <= ch && ch <= '9') return true;
switch (ch) {
case '_':
case '+':
case '-':
case '.':
case '/':
return true;
default:
return false;
}
}
static inline bool IsKnownWin32SafeCharacter(char ch) {
switch (ch) {
case ' ':
case '"':
return false;
default:
return true;
}
}
static inline bool StringNeedsShellEscaping(const string& input) {
for (size_t i = 0; i < input.size(); ++i) {
if (!IsKnownShellSafeCharacter(input[i])) return true;
}
return false;
}
static inline bool StringNeedsWin32Escaping(const string& input) {
for (size_t i = 0; i < input.size(); ++i) {
if (!IsKnownWin32SafeCharacter(input[i])) return true;
}
return false;
}
void GetShellEscapedString(const string& input, string* result) {
assert(result);
if (!StringNeedsShellEscaping(input)) {
result->append(input);
return;
}
const char kQuote = '\'';
const char kEscapeSequence[] = "'\\'";
result->push_back(kQuote);
string::const_iterator span_begin = input.begin();
for (string::const_iterator it = input.begin(), end = input.end(); it != end;
++it) {
if (*it == kQuote) {
result->append(span_begin, it);
result->append(kEscapeSequence);
span_begin = it;
}
}
result->append(span_begin, input.end());
result->push_back(kQuote);
}
void GetWin32EscapedString(const string& input, string* result) {
assert(result);
if (!StringNeedsWin32Escaping(input)) {
result->append(input);
return;
}
const char kQuote = '"';
const char kBackslash = '\\';
result->push_back(kQuote);
size_t consecutive_backslash_count = 0;
string::const_iterator span_begin = input.begin();
for (string::const_iterator it = input.begin(), end = input.end(); it != end;
++it) {
switch (*it) {
case kBackslash:
++consecutive_backslash_count;
break;
case kQuote:
result->append(span_begin, it);
result->append(consecutive_backslash_count + 1, kBackslash);
span_begin = it;
consecutive_backslash_count = 0;
break;
default:
consecutive_backslash_count = 0;
break;
}
}
result->append(span_begin, input.end());
result->append(consecutive_backslash_count, kBackslash);
result->push_back(kQuote);
}
int ReadFile(const string& path, string* contents, string* err) {
FILE* f = fopen(path.c_str(), "r");
if (!f) {
err->assign(strerror(errno));
return -errno;
}
char buf[64 << 10];
size_t len;
while ((len = fread(buf, 1, sizeof(buf), f)) > 0) {
contents->append(buf, len);
}
if (ferror(f)) {
err->assign(strerror(errno)); // XXX errno?
contents->clear();
fclose(f);
return -errno;
}
fclose(f);
return 0;
}
void SetCloseOnExec(int fd) {
#ifndef _WIN32
int flags = fcntl(fd, F_GETFD);
if (flags < 0) {
perror("fcntl(F_GETFD)");
} else {
if (fcntl(fd, F_SETFD, flags | FD_CLOEXEC) < 0)
perror("fcntl(F_SETFD)");
}
#else
HANDLE hd = (HANDLE) _get_osfhandle(fd);
if (! SetHandleInformation(hd, HANDLE_FLAG_INHERIT, 0)) {
fprintf(stderr, "SetHandleInformation(): %s", GetLastErrorString().c_str());
}
#endif // ! _WIN32
}
const char* SpellcheckStringV(const string& text,
const vector<const char*>& words) {
const bool kAllowReplacements = true;
const int kMaxValidEditDistance = 3;
int min_distance = kMaxValidEditDistance + 1;
const char* result = NULL;
for (vector<const char*>::const_iterator i = words.begin();
i != words.end(); ++i) {
int distance = EditDistance(*i, text, kAllowReplacements,
kMaxValidEditDistance);
if (distance < min_distance) {
min_distance = distance;
result = *i;
}
}
return result;
}
const char* SpellcheckString(const char* text, ...) {
// Note: This takes a const char* instead of a string& because using
// va_start() with a reference parameter is undefined behavior.
va_list ap;
va_start(ap, text);
vector<const char*> words;
const char* word;
while ((word = va_arg(ap, const char*)))
words.push_back(word);
va_end(ap);
return SpellcheckStringV(text, words);
}
#ifdef _WIN32
string GetLastErrorString() {
DWORD err = GetLastError();
char* msg_buf;
FormatMessageA(
FORMAT_MESSAGE_ALLOCATE_BUFFER |
FORMAT_MESSAGE_FROM_SYSTEM |
FORMAT_MESSAGE_IGNORE_INSERTS,
NULL,
err,
MAKELANGID(LANG_NEUTRAL, SUBLANG_DEFAULT),
(char*)&msg_buf,
0,
NULL);
string msg = msg_buf;
LocalFree(msg_buf);
return msg;
}
void Win32Fatal(const char* function) {
Fatal("%s: %s", function, GetLastErrorString().c_str());
}
#endif
static bool islatinalpha(int c) {
// isalpha() is locale-dependent.
return (c >= 'a' && c <= 'z') || (c >= 'A' && c <= 'Z');
}
string StripAnsiEscapeCodes(const string& in) {
string stripped;
stripped.reserve(in.size());
for (size_t i = 0; i < in.size(); ++i) {
if (in[i] != '\33') {
// Not an escape code.
stripped.push_back(in[i]);
continue;
}
// Only strip CSIs for now.
if (i + 1 >= in.size()) break;
if (in[i + 1] != '[') continue; // Not a CSI.
i += 2;
// Skip everything up to and including the next [a-zA-Z].
while (i < in.size() && !islatinalpha(in[i]))
++i;
}
return stripped;
}
int GetProcessorCount() {
#ifdef _WIN32
SYSTEM_INFO info;
GetSystemInfo(&info);
return info.dwNumberOfProcessors;
#else
return sysconf(_SC_NPROCESSORS_ONLN);
#endif
}
#if defined(_WIN32) || defined(__CYGWIN__)
static double CalculateProcessorLoad(uint64_t idleTicks, uint64_t totalTicks)
{
static uint64_t previousIdleTicks = 0;
static uint64_t previousTotalTicks = 0;
uint64_t idleTicksSinceLastTime = idleTicks - previousIdleTicks;
uint64_t totalTicksSinceLastTime = totalTicks - previousTotalTicks;
double load;
if( previousTotalTicks > 0) {
//return error for first call
load = -0.0;
} else if(totalTicksSinceLastTime == 0) {
//return error when load cannot be calculated
load = -0.0;
} else {
double idleToTotalRatio = ((double)idleTicksSinceLastTime) / totalTicksSinceLastTime;
load = 1.0 - idleToTotalRatio;
}
previousTotalTicks = totalTicks;
previousIdleTicks = idleTicks;
return load;
}
static uint64_t FileTimeToTickCount(const FILETIME & ft)
{
uint64_t high = (((uint64_t)(ft.dwHighDateTime)) << 32);
uint64_t low = ft.dwLowDateTime;
return (high | low);
}
double GetLoadAverage() {
FILETIME idleTime, kernelTime, userTime;
BOOL getSystemTimeSucceeded = GetSystemTimes(&idleTime, &kernelTime, &userTime);
double result;
if (getSystemTimeSucceeded) {
uint64_t idleTicks = FileTimeToTickCount(idleTime);
uint64_t totalTicks = FileTimeToTickCount(kernelTime) + FileTimeToTickCount(userTime);
result = CalculateProcessorLoad(idleTicks, totalTicks);
} else {
result = -0.0;
}
return result;
}
#else
double GetLoadAverage() {
double loadavg[3] = { 0.0f, 0.0f, 0.0f };
if (getloadavg(loadavg, 3) < 0) {
// Maybe we should return an error here or the availability of
// getloadavg(3) should be checked when ninja is configured.
return -0.0f;
}
return loadavg[0];
}
#endif // _WIN32
string ElideMiddle(const string& str, size_t width) {
const int kMargin = 3; // Space for "...".
string result = str;
if (result.size() + kMargin > width) {
size_t elide_size = (width - kMargin) / 2;
result = result.substr(0, elide_size)
+ "..."
+ result.substr(result.size() - elide_size, elide_size);
}
return result;
}
bool Truncate(const string& path, size_t size, string* err) {
#ifdef _WIN32
int fh = _sopen(path.c_str(), _O_RDWR | _O_CREAT, _SH_DENYNO,
_S_IREAD | _S_IWRITE);
int success = _chsize(fh, size);
_close(fh);
#else
int success = truncate(path.c_str(), size);
#endif
// Both truncate() and _chsize() return 0 on success and set errno and return
// -1 on failure.
if (success < 0) {
*err = strerror(errno);
return false;
}
return true;
}
<|endoftext|> |
<commit_before>/// @file
/// @author Boris Mikic
/// @author Kresimir Spes
/// @version 3.0
///
/// @section LICENSE
///
/// This program is free software; you can redistribute it and/or modify it under
/// the terms of the BSD license: http://www.opensource.org/licenses/bsd-license.php
#include <stdio.h>
#include <hltypes/harray.h>
#include <hltypes/hlog.h>
#include <hltypes/hplatform.h>
#include <hltypes/hstring.h>
#ifdef __APPLE__
#include <TargetConditionals.h>
#endif
#include "AudioManager.h"
#ifdef _DIRECTSOUND
#include "DirectSound_AudioManager.h"
#endif
#ifdef _OPENAL
#include "OpenAL_AudioManager.h"
#endif
#ifdef _SDL
#include "SDL_AudioManager.h"
#endif
#ifdef _XAUDIO2
#include "XAudio2_AudioManager.h"
#endif
#include "NoAudio_AudioManager.h"
#include "xal.h"
#ifdef _COREAUDIO
#include "CoreAudio_AudioManager.h"
//#include "AVFoundation_AudioManager.h" // TODO: iOS maybe? probably leagacy code
#endif
#ifdef _WIN32
#if !_HL_WINRT
#ifdef _DIRECTSOUND
#define XAL_AS_INTERNAL_DEFAULT XAL_AS_DIRECTSOUND
#elif defined(_SDL)
#define XAL_AS_INTERNAL_DEFAULT XAL_AS_SDL
#elif defined(_OPENAL)
#define XAL_AS_INTERNAL_DEFAULT XAL_AS_OPENAL
#else
#define XAL_AS_INTERNAL_DEFAULT XAL_AS_DISABLED
#endif
#else
#ifdef _XAUDIO2
#define XAL_AS_INTERNAL_DEFAULT XAL_AS_XAUDIO2
#else
#define XAL_AS_INTERNAL_DEFAULT XAL_AS_DISABLED
#endif
#endif
#elif defined(__APPLE__) && !defined(_IOS)
#ifdef _COREAUDIO
#define XAL_AS_INTERNAL_DEFAULT XAL_AS_COREAUDIO
#elif defined(_SDL)
#define XAL_AS_INTERNAL_DEFAULT XAL_AS_SDL
#elif defined(_OPENAL)
#define XAL_AS_INTERNAL_DEFAULT XAL_AS_OPENAL
#else
#define XAL_AS_INTERNAL_DEFAULT XAL_AS_DISABLED
#endif
#elif defined(__APPLE__) && defined(_IOS)
#ifdef _COREAUDIO
#define XAL_AS_INTERNAL_DEFAULT XAL_AS_COREAUDIO
#elif defined(_OPENAL)
#define XAL_AS_INTERNAL_DEFAULT XAL_AS_OPENAL
#elif defined(_AVFOUNDATION)
#define XAL_AS_INTERNAL_DEFAULT XAL_AS_AVFOUNDATION
#else
#define XAL_AS_INTERNAL_DEFAULT XAL_AS_DISABLED
#endif
//XAL_AS_AVFOUNDATION
#elif defined(_UNIX)
#ifdef _SDL
#define XAL_AS_INTERNAL_DEFAULT XAL_AS_SDL
#elif defined(_OPENAL)
#define XAL_AS_INTERNAL_DEFAULT XAL_AS_OPENAL
#else
#define XAL_AS_INTERNAL_DEFAULT XAL_AS_DISABLED
#endif
#elif defined(_ANDROID)
#ifdef _OPENAL
#define XAL_AS_INTERNAL_DEFAULT XAL_AS_OPENAL
#else
#define XAL_AS_INTERNAL_DEFAULT XAL_AS_DISABLED
#endif
#else
#define XAL_AS_INTERNAL_DEFAULT XAL_AS_DISABLED
#endif
namespace xal
{
hstr logTag = "xal";
void init(chstr systemName, void* backendId, bool threaded, float updateTime, chstr deviceName)
{
hlog::write(xal::logTag, "Initializing XAL.");
hstr name = systemName;
if (name == XAL_AS_DEFAULT)
{
name = XAL_AS_INTERNAL_DEFAULT;
}
if (name == XAL_AS_DISABLED)
{
xal::mgr = new NoAudio_AudioManager(name, backendId, threaded, updateTime, deviceName);
hlog::write(xal::logTag, "Audio is disabled.");
return;
}
#ifdef _DIRECTSOUND
if (name == XAL_AS_DIRECTSOUND)
{
xal::mgr = new DirectSound_AudioManager(name, backendId, threaded, updateTime, deviceName);
}
#endif
#ifdef _OPENAL
if (name == XAL_AS_OPENAL)
{
xal::mgr = new OpenAL_AudioManager(name, backendId, threaded, updateTime, deviceName);
}
#endif
#ifdef _SDL
if (name == XAL_AS_SDL)
{
xal::mgr = new SDL_AudioManager(name, backendId, threaded, updateTime, deviceName);
}
#endif
#ifdef _XAUDIO2
if (name == XAL_AS_XAUDIO2)
{
xal::mgr = new XAudio2_AudioManager(name, backendId, threaded, updateTime, deviceName);
}
#endif
/*
#ifdef _IOS
if (name == XAL_AS_AVFOUNDATION)
{
xal::mgr = new AVFoundation_AudioManager(name, backendId, threaded, updateTime, deviceName);
}
#endif
*/
#ifdef _COREAUDIO
if (name == XAL_AS_COREAUDIO)
{
xal::mgr = new CoreAudio_AudioManager(name, backendId, threaded, updateTime, deviceName);
}
#endif
if (xal::mgr == NULL)
{
hlog::write(xal::logTag, "Audio system does not exist: " + name);
xal::mgr = new NoAudio_AudioManager(XAL_AS_DISABLED, backendId, threaded, updateTime, deviceName);
hlog::write(xal::logTag, "Audio is disabled.");
return;
}
hlog::write(xal::logTag, "Audio system created: " + name);
// actually starts threading
xal::mgr->init();
}
void destroy()
{
if (xal::mgr != NULL)
{
hlog::write(xal::logTag, "Destroying XAL.");
xal::mgr->clear();
delete xal::mgr;
xal::mgr = NULL;
}
}
bool hasAudioSystem(chstr name)
{
#ifdef _DIRECTSOUND
if (name == XAL_AS_DIRECTSOUND)
{
return true;
}
#endif
#ifdef _OPENAL
if (name == XAL_AS_OPENAL)
{
return true;
}
#endif
#ifdef _SDL
if (name == XAL_AS_SDL)
{
return true;
}
#endif
#ifdef _XAUDIO2
if (name == XAL_AS_XAUDIO2)
{
return true;
}
#endif
if (name == XAL_AS_DISABLED)
{
return true;
}
return false;
}
}
<commit_msg>- WinRT update<commit_after>/// @file
/// @author Boris Mikic
/// @author Kresimir Spes
/// @version 3.0
///
/// @section LICENSE
///
/// This program is free software; you can redistribute it and/or modify it under
/// the terms of the BSD license: http://www.opensource.org/licenses/bsd-license.php
#include <stdio.h>
#include <hltypes/harray.h>
#include <hltypes/hlog.h>
#include <hltypes/hplatform.h>
#include <hltypes/hstring.h>
#ifdef __APPLE__
#include <TargetConditionals.h>
#endif
#include "AudioManager.h"
#ifdef _DIRECTSOUND
#include "DirectSound_AudioManager.h"
#endif
#ifdef _OPENAL
#include "OpenAL_AudioManager.h"
#endif
#ifdef _SDL
#include "SDL_AudioManager.h"
#endif
#ifdef _XAUDIO2
#include "XAudio2_AudioManager.h"
#endif
#include "NoAudio_AudioManager.h"
#include "xal.h"
#ifdef _COREAUDIO
#include "CoreAudio_AudioManager.h"
//#include "AVFoundation_AudioManager.h" // TODO: iOS maybe? probably leagacy code
#endif
#ifdef _WIN32
#ifndef _WINRT
#ifdef _DIRECTSOUND
#define XAL_AS_INTERNAL_DEFAULT XAL_AS_DIRECTSOUND
#elif defined(_SDL)
#define XAL_AS_INTERNAL_DEFAULT XAL_AS_SDL
#elif defined(_OPENAL)
#define XAL_AS_INTERNAL_DEFAULT XAL_AS_OPENAL
#else
#define XAL_AS_INTERNAL_DEFAULT XAL_AS_DISABLED
#endif
#else
#ifdef _XAUDIO2
#define XAL_AS_INTERNAL_DEFAULT XAL_AS_XAUDIO2
#else
#define XAL_AS_INTERNAL_DEFAULT XAL_AS_DISABLED
#endif
#endif
#elif defined(__APPLE__) && !defined(_IOS)
#ifdef _COREAUDIO
#define XAL_AS_INTERNAL_DEFAULT XAL_AS_COREAUDIO
#elif defined(_SDL)
#define XAL_AS_INTERNAL_DEFAULT XAL_AS_SDL
#elif defined(_OPENAL)
#define XAL_AS_INTERNAL_DEFAULT XAL_AS_OPENAL
#else
#define XAL_AS_INTERNAL_DEFAULT XAL_AS_DISABLED
#endif
#elif defined(__APPLE__) && defined(_IOS)
#ifdef _COREAUDIO
#define XAL_AS_INTERNAL_DEFAULT XAL_AS_COREAUDIO
#elif defined(_OPENAL)
#define XAL_AS_INTERNAL_DEFAULT XAL_AS_OPENAL
#elif defined(_AVFOUNDATION)
#define XAL_AS_INTERNAL_DEFAULT XAL_AS_AVFOUNDATION
#else
#define XAL_AS_INTERNAL_DEFAULT XAL_AS_DISABLED
#endif
//XAL_AS_AVFOUNDATION
#elif defined(_UNIX)
#ifdef _SDL
#define XAL_AS_INTERNAL_DEFAULT XAL_AS_SDL
#elif defined(_OPENAL)
#define XAL_AS_INTERNAL_DEFAULT XAL_AS_OPENAL
#else
#define XAL_AS_INTERNAL_DEFAULT XAL_AS_DISABLED
#endif
#elif defined(_ANDROID)
#ifdef _OPENAL
#define XAL_AS_INTERNAL_DEFAULT XAL_AS_OPENAL
#else
#define XAL_AS_INTERNAL_DEFAULT XAL_AS_DISABLED
#endif
#else
#define XAL_AS_INTERNAL_DEFAULT XAL_AS_DISABLED
#endif
namespace xal
{
hstr logTag = "xal";
void init(chstr systemName, void* backendId, bool threaded, float updateTime, chstr deviceName)
{
hlog::write(xal::logTag, "Initializing XAL.");
hstr name = systemName;
if (name == XAL_AS_DEFAULT)
{
name = XAL_AS_INTERNAL_DEFAULT;
}
if (name == XAL_AS_DISABLED)
{
xal::mgr = new NoAudio_AudioManager(name, backendId, threaded, updateTime, deviceName);
hlog::write(xal::logTag, "Audio is disabled.");
return;
}
#ifdef _DIRECTSOUND
if (name == XAL_AS_DIRECTSOUND)
{
xal::mgr = new DirectSound_AudioManager(name, backendId, threaded, updateTime, deviceName);
}
#endif
#ifdef _OPENAL
if (name == XAL_AS_OPENAL)
{
xal::mgr = new OpenAL_AudioManager(name, backendId, threaded, updateTime, deviceName);
}
#endif
#ifdef _SDL
if (name == XAL_AS_SDL)
{
xal::mgr = new SDL_AudioManager(name, backendId, threaded, updateTime, deviceName);
}
#endif
#ifdef _XAUDIO2
if (name == XAL_AS_XAUDIO2)
{
xal::mgr = new XAudio2_AudioManager(name, backendId, threaded, updateTime, deviceName);
}
#endif
/*
#ifdef _IOS
if (name == XAL_AS_AVFOUNDATION)
{
xal::mgr = new AVFoundation_AudioManager(name, backendId, threaded, updateTime, deviceName);
}
#endif
*/
#ifdef _COREAUDIO
if (name == XAL_AS_COREAUDIO)
{
xal::mgr = new CoreAudio_AudioManager(name, backendId, threaded, updateTime, deviceName);
}
#endif
if (xal::mgr == NULL)
{
hlog::write(xal::logTag, "Audio system does not exist: " + name);
xal::mgr = new NoAudio_AudioManager(XAL_AS_DISABLED, backendId, threaded, updateTime, deviceName);
hlog::write(xal::logTag, "Audio is disabled.");
return;
}
hlog::write(xal::logTag, "Audio system created: " + name);
// actually starts threading
xal::mgr->init();
}
void destroy()
{
if (xal::mgr != NULL)
{
hlog::write(xal::logTag, "Destroying XAL.");
xal::mgr->clear();
delete xal::mgr;
xal::mgr = NULL;
}
}
bool hasAudioSystem(chstr name)
{
#ifdef _DIRECTSOUND
if (name == XAL_AS_DIRECTSOUND)
{
return true;
}
#endif
#ifdef _OPENAL
if (name == XAL_AS_OPENAL)
{
return true;
}
#endif
#ifdef _SDL
if (name == XAL_AS_SDL)
{
return true;
}
#endif
#ifdef _XAUDIO2
if (name == XAL_AS_XAUDIO2)
{
return true;
}
#endif
if (name == XAL_AS_DISABLED)
{
return true;
}
return false;
}
}
<|endoftext|> |
<commit_before>#include "SimulationModel.h"
#include "PositionBasedDynamics/PositionBasedRigidBodyDynamics.h"
#include "Constraints.h"
using namespace PBD;
SimulationModel::SimulationModel()
{
m_cloth_stiffness = 1.0f;
m_cloth_bendingStiffness = 0.01f;
m_cloth_xxStiffness = 1.0f;
m_cloth_yyStiffness = 1.0f;
m_cloth_xyStiffness = 1.0f;
m_cloth_xyPoissonRatio = 0.3f;
m_cloth_yxPoissonRatio = 0.3f;
m_cloth_normalizeShear = false;
m_cloth_normalizeStretch = false;
m_solid_stiffness = 1.0f;
m_solid_poissonRatio = 0.3f;
m_solid_normalizeShear = false;
m_solid_normalizeStretch = false;
m_groupsInitialized = false;
}
SimulationModel::~SimulationModel(void)
{
cleanup();
}
void SimulationModel::cleanup()
{
for (unsigned int i = 0; i < m_rigidBodies.size(); i++)
delete m_rigidBodies[i];
m_rigidBodies.clear();
for (unsigned int i = 0; i < m_triangleModels.size(); i++)
delete m_triangleModels[i];
m_triangleModels.clear();
for (unsigned int i = 0; i < m_constraints.size(); i++)
delete m_constraints[i];
m_constraints.clear();
m_particles.release();
}
void SimulationModel::reset()
{
// rigid bodies
for (size_t i = 0; i < m_rigidBodies.size(); i++)
m_rigidBodies[i]->reset();
// particles
for (unsigned int i = 0; i < m_particles.size(); i++)
{
const Eigen::Vector3f& x0 = m_particles.getPosition0(i);
m_particles.getPosition(i) = x0;
m_particles.getLastPosition(i) = m_particles.getPosition(i);
m_particles.getOldPosition(i) = m_particles.getPosition(i);
m_particles.getVelocity(i).setZero();
m_particles.getAcceleration(i).setZero();
}
updateConstraints();
}
SimulationModel::RigidBodyVector & SimulationModel::getRigidBodies()
{
return m_rigidBodies;
}
ParticleData & SimulationModel::getParticles()
{
return m_particles;
}
SimulationModel::TriangleModelVector & SimulationModel::getTriangleModels()
{
return m_triangleModels;
}
SimulationModel::TetModelVector & SimulationModel::getTetModels()
{
return m_tetModels;
}
SimulationModel::ConstraintVector & SimulationModel::getConstraints()
{
return m_constraints;
}
SimulationModel::ConstraintGroupVector & SimulationModel::getConstraintGroups()
{
return m_constraintGroups;
}
void SimulationModel::updateConstraints()
{
for (unsigned int i = 0; i < m_constraints.size(); i++)
m_constraints[i]->updateConstraint(*this);
}
bool SimulationModel::addBallJoint(const unsigned int rbIndex1, const unsigned int rbIndex2, const Eigen::Vector3f &pos)
{
BallJoint *bj = new BallJoint();
const bool res = bj->initConstraint(*this, rbIndex1, rbIndex2, pos);
if (res)
{
m_constraints.push_back(bj);
m_groupsInitialized = false;
}
return res;
}
bool SimulationModel::addBallOnLineJoint(const unsigned int rbIndex1, const unsigned int rbIndex2, const Eigen::Vector3f &pos, const Eigen::Vector3f &dir)
{
BallOnLineJoint *bj = new BallOnLineJoint();
const bool res = bj->initConstraint(*this, rbIndex1, rbIndex2, pos, dir);
if (res)
{
m_constraints.push_back(bj);
m_groupsInitialized = false;
}
return res;
}
bool SimulationModel::addHingeJoint(const unsigned int rbIndex1, const unsigned int rbIndex2, const Eigen::Vector3f &pos, const Eigen::Vector3f &axis)
{
HingeJoint *hj = new HingeJoint();
const bool res = hj->initConstraint(*this, rbIndex1, rbIndex2, pos, axis);
if (res)
{
m_constraints.push_back(hj);
m_groupsInitialized = false;
}
return res;
}
bool SimulationModel::addUniversalJoint(const unsigned int rbIndex1, const unsigned int rbIndex2, const Eigen::Vector3f &pos, const Eigen::Vector3f &axis1, const Eigen::Vector3f &axis2)
{
UniversalJoint *uj = new UniversalJoint();
const bool res = uj->initConstraint(*this, rbIndex1, rbIndex2, pos, axis1, axis2);
if (res)
{
m_constraints.push_back(uj);
m_groupsInitialized = false;
}
return res;
}
bool SimulationModel::addSliderJoint(const unsigned int rbIndex1, const unsigned int rbIndex2, const Eigen::Vector3f &pos, const Eigen::Vector3f &axis)
{
SliderJoint *joint = new SliderJoint();
const bool res = joint->initConstraint(*this, rbIndex1, rbIndex2, pos, axis);
if (res)
{
m_constraints.push_back(joint);
m_groupsInitialized = false;
}
return res;
}
bool SimulationModel::addTargetPositionMotorSliderJoint(const unsigned int rbIndex1, const unsigned int rbIndex2, const Eigen::Vector3f &pos, const Eigen::Vector3f &axis)
{
TargetPositionMotorSliderJoint *joint = new TargetPositionMotorSliderJoint();
const bool res = joint->initConstraint(*this, rbIndex1, rbIndex2, pos, axis);
if (res)
{
m_constraints.push_back(joint);
m_groupsInitialized = false;
}
return res;
}
bool SimulationModel::addTargetAngleMotorHingeJoint(const unsigned int rbIndex1, const unsigned int rbIndex2, const Eigen::Vector3f &pos, const Eigen::Vector3f &axis)
{
TargetAngleMotorHingeJoint *hj = new TargetAngleMotorHingeJoint();
const bool res = hj->initConstraint(*this, rbIndex1, rbIndex2, pos, axis);
if (res)
{
m_constraints.push_back(hj);
m_groupsInitialized = false;
}
return res;
}
bool SimulationModel::addTargetVelocityMotorHingeJoint(const unsigned int rbIndex1, const unsigned int rbIndex2, const Eigen::Vector3f &pos, const Eigen::Vector3f &axis)
{
TargetVelocityMotorHingeJoint *hj = new TargetVelocityMotorHingeJoint();
const bool res = hj->initConstraint(*this, rbIndex1, rbIndex2, pos, axis);
if (res)
{
m_constraints.push_back(hj);
m_groupsInitialized = false;
}
return res;
}
bool SimulationModel::addRigidBodyParticleBallJoint(const unsigned int rbIndex, const unsigned int particleIndex)
{
RigidBodyParticleBallJoint *bj = new RigidBodyParticleBallJoint();
const bool res = bj->initConstraint(*this, rbIndex, particleIndex);
if (res)
{
m_constraints.push_back(bj);
m_groupsInitialized = false;
}
return res;
}
bool SimulationModel::addDistanceConstraint(const unsigned int particle1, const unsigned int particle2)
{
DistanceConstraint *c = new DistanceConstraint();
const bool res = c->initConstraint(*this, particle1, particle2);
if (res)
{
m_constraints.push_back(c);
m_groupsInitialized = false;
}
return res;
}
bool SimulationModel::addDihedralConstraint(const unsigned int particle1, const unsigned int particle2,
const unsigned int particle3, const unsigned int particle4)
{
DihedralConstraint *c = new DihedralConstraint();
const bool res = c->initConstraint(*this, particle1, particle2, particle3, particle4);
if (res)
{
m_constraints.push_back(c);
m_groupsInitialized = false;
}
return res;
}
bool SimulationModel::addIsometricBendingConstraint(const unsigned int particle1, const unsigned int particle2,
const unsigned int particle3, const unsigned int particle4)
{
IsometricBendingConstraint *c = new IsometricBendingConstraint();
const bool res = c->initConstraint(*this, particle1, particle2, particle3, particle4);
if (res)
{
m_constraints.push_back(c);
m_groupsInitialized = false;
}
return res;
}
bool SimulationModel::addFEMTriangleConstraint(const unsigned int particle1, const unsigned int particle2,
const unsigned int particle3)
{
FEMTriangleConstraint *c = new FEMTriangleConstraint();
const bool res = c->initConstraint(*this, particle1, particle2, particle3);
if (res)
{
m_constraints.push_back(c);
m_groupsInitialized = false;
}
return res;
}
bool SimulationModel::addStrainTriangleConstraint(const unsigned int particle1, const unsigned int particle2,
const unsigned int particle3)
{
StrainTriangleConstraint *c = new StrainTriangleConstraint();
const bool res = c->initConstraint(*this, particle1, particle2, particle3);
if (res)
{
m_constraints.push_back(c);
m_groupsInitialized = false;
}
return res;
}
bool SimulationModel::addVolumeConstraint(const unsigned int particle1, const unsigned int particle2,
const unsigned int particle3, const unsigned int particle4)
{
VolumeConstraint *c = new VolumeConstraint();
const bool res = c->initConstraint(*this, particle1, particle2, particle3, particle4);
if (res)
{
m_constraints.push_back(c);
m_groupsInitialized = false;
}
return res;
}
bool SimulationModel::addFEMTetConstraint(const unsigned int particle1, const unsigned int particle2,
const unsigned int particle3, const unsigned int particle4)
{
FEMTetConstraint *c = new FEMTetConstraint();
const bool res = c->initConstraint(*this, particle1, particle2, particle3, particle4);
if (res)
{
m_constraints.push_back(c);
m_groupsInitialized = false;
}
return res;
}
bool SimulationModel::addStrainTetConstraint(const unsigned int particle1, const unsigned int particle2,
const unsigned int particle3, const unsigned int particle4)
{
StrainTetConstraint *c = new StrainTetConstraint();
const bool res = c->initConstraint(*this, particle1, particle2, particle3, particle4);
if (res)
{
m_constraints.push_back(c);
m_groupsInitialized = false;
}
return res;
}
bool SimulationModel::addShapeMatchingConstraint(const unsigned int numberOfParticles, const unsigned int particleIndices[], const unsigned int numClusters[])
{
ShapeMatchingConstraint *c = new ShapeMatchingConstraint(numberOfParticles);
const bool res = c->initConstraint(*this, particleIndices, numClusters);
if (res)
{
m_constraints.push_back(c);
m_groupsInitialized = false;
}
return res;
}
void SimulationModel::addTriangleModel(
const unsigned int nPoints,
const unsigned int nFaces,
Eigen::Vector3f *points,
unsigned int* indices,
const TriangleModel::ParticleMesh::UVIndices& uvIndices,
const TriangleModel::ParticleMesh::UVs& uvs)
{
TriangleModel *triModel = new TriangleModel();
m_triangleModels.push_back(triModel);
unsigned int startIndex = m_particles.size();
m_particles.reserve(startIndex + nPoints);
for (unsigned int i = 0; i < nPoints; i++)
m_particles.addVertex(points[i]);
triModel->initMesh(nPoints, nFaces, startIndex, indices, uvIndices, uvs);
// Update normals
triModel->updateMeshNormals(m_particles);
}
void SimulationModel::addTetModel(
const unsigned int nPoints,
const unsigned int nTets,
Eigen::Vector3f *points,
unsigned int* indices)
{
TetModel *tetModel = new TetModel();
m_tetModels.push_back(tetModel);
unsigned int startIndex = m_particles.size();
m_particles.reserve(startIndex + nPoints);
for (unsigned int i = 0; i < nPoints; i++)
m_particles.addVertex(points[i]);
tetModel->initMesh(nPoints, nTets, startIndex, indices);
}
void SimulationModel::initConstraintGroups()
{
if (m_groupsInitialized)
return;
const unsigned int numConstraints = (unsigned int) m_constraints.size();
const unsigned int numParticles = (unsigned int) m_particles.size();
const unsigned int numRigidBodies = (unsigned int) m_rigidBodies.size();
const unsigned int numBodies = numParticles + numRigidBodies;
m_constraintGroups.clear();
// Maps in which group a particle is or 0 if not yet mapped
std::vector<unsigned char*> mapping;
for (unsigned int i = 0; i < numConstraints; i++)
{
Constraint *constraint = m_constraints[i];
bool addToNewGroup = true;
for (unsigned int j = 0; j < m_constraintGroups.size(); j++)
{
bool addToThisGroup = true;
for (unsigned int k = 0; k < constraint->m_numberOfBodies; k++)
{
if (mapping[j][constraint->m_bodies[k]] != 0)
{
addToThisGroup = false;
break;
}
}
if (addToThisGroup)
{
m_constraintGroups[j].push_back(i);
for (unsigned int k = 0; k < constraint->m_numberOfBodies; k++)
mapping[j][constraint->m_bodies[k]] = 1;
addToNewGroup = false;
break;
}
}
if (addToNewGroup)
{
mapping.push_back(new unsigned char[numBodies]);
memset(mapping[mapping.size() - 1], 0, sizeof(unsigned char)*numBodies);
m_constraintGroups.resize(m_constraintGroups.size() + 1);
m_constraintGroups[m_constraintGroups.size()-1].push_back(i);
for (unsigned int k = 0; k < constraint->m_numberOfBodies; k++)
mapping[m_constraintGroups.size() - 1][constraint->m_bodies[k]] = 1;
}
}
for (unsigned int i = 0; i < mapping.size(); i++)
{
delete[] mapping[i];
}
mapping.clear();
m_groupsInitialized = true;
}
<commit_msg>- small bugfix<commit_after>#include "SimulationModel.h"
#include "PositionBasedDynamics/PositionBasedRigidBodyDynamics.h"
#include "Constraints.h"
using namespace PBD;
SimulationModel::SimulationModel()
{
m_cloth_stiffness = 1.0f;
m_cloth_bendingStiffness = 0.01f;
m_cloth_xxStiffness = 1.0f;
m_cloth_yyStiffness = 1.0f;
m_cloth_xyStiffness = 1.0f;
m_cloth_xyPoissonRatio = 0.3f;
m_cloth_yxPoissonRatio = 0.3f;
m_cloth_normalizeShear = false;
m_cloth_normalizeStretch = false;
m_solid_stiffness = 1.0f;
m_solid_poissonRatio = 0.3f;
m_solid_normalizeShear = false;
m_solid_normalizeStretch = false;
m_groupsInitialized = false;
}
SimulationModel::~SimulationModel(void)
{
cleanup();
}
void SimulationModel::cleanup()
{
for (unsigned int i = 0; i < m_rigidBodies.size(); i++)
delete m_rigidBodies[i];
m_rigidBodies.clear();
for (unsigned int i = 0; i < m_triangleModels.size(); i++)
delete m_triangleModels[i];
m_triangleModels.clear();
for (unsigned int i = 0; i < m_tetModels.size(); i++)
delete m_tetModels[i];
m_tetModels.clear();
for (unsigned int i = 0; i < m_constraints.size(); i++)
delete m_constraints[i];
m_constraints.clear();
m_particles.release();
}
void SimulationModel::reset()
{
// rigid bodies
for (size_t i = 0; i < m_rigidBodies.size(); i++)
m_rigidBodies[i]->reset();
// particles
for (unsigned int i = 0; i < m_particles.size(); i++)
{
const Eigen::Vector3f& x0 = m_particles.getPosition0(i);
m_particles.getPosition(i) = x0;
m_particles.getLastPosition(i) = m_particles.getPosition(i);
m_particles.getOldPosition(i) = m_particles.getPosition(i);
m_particles.getVelocity(i).setZero();
m_particles.getAcceleration(i).setZero();
}
updateConstraints();
}
SimulationModel::RigidBodyVector & SimulationModel::getRigidBodies()
{
return m_rigidBodies;
}
ParticleData & SimulationModel::getParticles()
{
return m_particles;
}
SimulationModel::TriangleModelVector & SimulationModel::getTriangleModels()
{
return m_triangleModels;
}
SimulationModel::TetModelVector & SimulationModel::getTetModels()
{
return m_tetModels;
}
SimulationModel::ConstraintVector & SimulationModel::getConstraints()
{
return m_constraints;
}
SimulationModel::ConstraintGroupVector & SimulationModel::getConstraintGroups()
{
return m_constraintGroups;
}
void SimulationModel::updateConstraints()
{
for (unsigned int i = 0; i < m_constraints.size(); i++)
m_constraints[i]->updateConstraint(*this);
}
bool SimulationModel::addBallJoint(const unsigned int rbIndex1, const unsigned int rbIndex2, const Eigen::Vector3f &pos)
{
BallJoint *bj = new BallJoint();
const bool res = bj->initConstraint(*this, rbIndex1, rbIndex2, pos);
if (res)
{
m_constraints.push_back(bj);
m_groupsInitialized = false;
}
return res;
}
bool SimulationModel::addBallOnLineJoint(const unsigned int rbIndex1, const unsigned int rbIndex2, const Eigen::Vector3f &pos, const Eigen::Vector3f &dir)
{
BallOnLineJoint *bj = new BallOnLineJoint();
const bool res = bj->initConstraint(*this, rbIndex1, rbIndex2, pos, dir);
if (res)
{
m_constraints.push_back(bj);
m_groupsInitialized = false;
}
return res;
}
bool SimulationModel::addHingeJoint(const unsigned int rbIndex1, const unsigned int rbIndex2, const Eigen::Vector3f &pos, const Eigen::Vector3f &axis)
{
HingeJoint *hj = new HingeJoint();
const bool res = hj->initConstraint(*this, rbIndex1, rbIndex2, pos, axis);
if (res)
{
m_constraints.push_back(hj);
m_groupsInitialized = false;
}
return res;
}
bool SimulationModel::addUniversalJoint(const unsigned int rbIndex1, const unsigned int rbIndex2, const Eigen::Vector3f &pos, const Eigen::Vector3f &axis1, const Eigen::Vector3f &axis2)
{
UniversalJoint *uj = new UniversalJoint();
const bool res = uj->initConstraint(*this, rbIndex1, rbIndex2, pos, axis1, axis2);
if (res)
{
m_constraints.push_back(uj);
m_groupsInitialized = false;
}
return res;
}
bool SimulationModel::addSliderJoint(const unsigned int rbIndex1, const unsigned int rbIndex2, const Eigen::Vector3f &pos, const Eigen::Vector3f &axis)
{
SliderJoint *joint = new SliderJoint();
const bool res = joint->initConstraint(*this, rbIndex1, rbIndex2, pos, axis);
if (res)
{
m_constraints.push_back(joint);
m_groupsInitialized = false;
}
return res;
}
bool SimulationModel::addTargetPositionMotorSliderJoint(const unsigned int rbIndex1, const unsigned int rbIndex2, const Eigen::Vector3f &pos, const Eigen::Vector3f &axis)
{
TargetPositionMotorSliderJoint *joint = new TargetPositionMotorSliderJoint();
const bool res = joint->initConstraint(*this, rbIndex1, rbIndex2, pos, axis);
if (res)
{
m_constraints.push_back(joint);
m_groupsInitialized = false;
}
return res;
}
bool SimulationModel::addTargetAngleMotorHingeJoint(const unsigned int rbIndex1, const unsigned int rbIndex2, const Eigen::Vector3f &pos, const Eigen::Vector3f &axis)
{
TargetAngleMotorHingeJoint *hj = new TargetAngleMotorHingeJoint();
const bool res = hj->initConstraint(*this, rbIndex1, rbIndex2, pos, axis);
if (res)
{
m_constraints.push_back(hj);
m_groupsInitialized = false;
}
return res;
}
bool SimulationModel::addTargetVelocityMotorHingeJoint(const unsigned int rbIndex1, const unsigned int rbIndex2, const Eigen::Vector3f &pos, const Eigen::Vector3f &axis)
{
TargetVelocityMotorHingeJoint *hj = new TargetVelocityMotorHingeJoint();
const bool res = hj->initConstraint(*this, rbIndex1, rbIndex2, pos, axis);
if (res)
{
m_constraints.push_back(hj);
m_groupsInitialized = false;
}
return res;
}
bool SimulationModel::addRigidBodyParticleBallJoint(const unsigned int rbIndex, const unsigned int particleIndex)
{
RigidBodyParticleBallJoint *bj = new RigidBodyParticleBallJoint();
const bool res = bj->initConstraint(*this, rbIndex, particleIndex);
if (res)
{
m_constraints.push_back(bj);
m_groupsInitialized = false;
}
return res;
}
bool SimulationModel::addDistanceConstraint(const unsigned int particle1, const unsigned int particle2)
{
DistanceConstraint *c = new DistanceConstraint();
const bool res = c->initConstraint(*this, particle1, particle2);
if (res)
{
m_constraints.push_back(c);
m_groupsInitialized = false;
}
return res;
}
bool SimulationModel::addDihedralConstraint(const unsigned int particle1, const unsigned int particle2,
const unsigned int particle3, const unsigned int particle4)
{
DihedralConstraint *c = new DihedralConstraint();
const bool res = c->initConstraint(*this, particle1, particle2, particle3, particle4);
if (res)
{
m_constraints.push_back(c);
m_groupsInitialized = false;
}
return res;
}
bool SimulationModel::addIsometricBendingConstraint(const unsigned int particle1, const unsigned int particle2,
const unsigned int particle3, const unsigned int particle4)
{
IsometricBendingConstraint *c = new IsometricBendingConstraint();
const bool res = c->initConstraint(*this, particle1, particle2, particle3, particle4);
if (res)
{
m_constraints.push_back(c);
m_groupsInitialized = false;
}
return res;
}
bool SimulationModel::addFEMTriangleConstraint(const unsigned int particle1, const unsigned int particle2,
const unsigned int particle3)
{
FEMTriangleConstraint *c = new FEMTriangleConstraint();
const bool res = c->initConstraint(*this, particle1, particle2, particle3);
if (res)
{
m_constraints.push_back(c);
m_groupsInitialized = false;
}
return res;
}
bool SimulationModel::addStrainTriangleConstraint(const unsigned int particle1, const unsigned int particle2,
const unsigned int particle3)
{
StrainTriangleConstraint *c = new StrainTriangleConstraint();
const bool res = c->initConstraint(*this, particle1, particle2, particle3);
if (res)
{
m_constraints.push_back(c);
m_groupsInitialized = false;
}
return res;
}
bool SimulationModel::addVolumeConstraint(const unsigned int particle1, const unsigned int particle2,
const unsigned int particle3, const unsigned int particle4)
{
VolumeConstraint *c = new VolumeConstraint();
const bool res = c->initConstraint(*this, particle1, particle2, particle3, particle4);
if (res)
{
m_constraints.push_back(c);
m_groupsInitialized = false;
}
return res;
}
bool SimulationModel::addFEMTetConstraint(const unsigned int particle1, const unsigned int particle2,
const unsigned int particle3, const unsigned int particle4)
{
FEMTetConstraint *c = new FEMTetConstraint();
const bool res = c->initConstraint(*this, particle1, particle2, particle3, particle4);
if (res)
{
m_constraints.push_back(c);
m_groupsInitialized = false;
}
return res;
}
bool SimulationModel::addStrainTetConstraint(const unsigned int particle1, const unsigned int particle2,
const unsigned int particle3, const unsigned int particle4)
{
StrainTetConstraint *c = new StrainTetConstraint();
const bool res = c->initConstraint(*this, particle1, particle2, particle3, particle4);
if (res)
{
m_constraints.push_back(c);
m_groupsInitialized = false;
}
return res;
}
bool SimulationModel::addShapeMatchingConstraint(const unsigned int numberOfParticles, const unsigned int particleIndices[], const unsigned int numClusters[])
{
ShapeMatchingConstraint *c = new ShapeMatchingConstraint(numberOfParticles);
const bool res = c->initConstraint(*this, particleIndices, numClusters);
if (res)
{
m_constraints.push_back(c);
m_groupsInitialized = false;
}
return res;
}
void SimulationModel::addTriangleModel(
const unsigned int nPoints,
const unsigned int nFaces,
Eigen::Vector3f *points,
unsigned int* indices,
const TriangleModel::ParticleMesh::UVIndices& uvIndices,
const TriangleModel::ParticleMesh::UVs& uvs)
{
TriangleModel *triModel = new TriangleModel();
m_triangleModels.push_back(triModel);
unsigned int startIndex = m_particles.size();
m_particles.reserve(startIndex + nPoints);
for (unsigned int i = 0; i < nPoints; i++)
m_particles.addVertex(points[i]);
triModel->initMesh(nPoints, nFaces, startIndex, indices, uvIndices, uvs);
// Update normals
triModel->updateMeshNormals(m_particles);
}
void SimulationModel::addTetModel(
const unsigned int nPoints,
const unsigned int nTets,
Eigen::Vector3f *points,
unsigned int* indices)
{
TetModel *tetModel = new TetModel();
m_tetModels.push_back(tetModel);
unsigned int startIndex = m_particles.size();
m_particles.reserve(startIndex + nPoints);
for (unsigned int i = 0; i < nPoints; i++)
m_particles.addVertex(points[i]);
tetModel->initMesh(nPoints, nTets, startIndex, indices);
}
void SimulationModel::initConstraintGroups()
{
if (m_groupsInitialized)
return;
const unsigned int numConstraints = (unsigned int) m_constraints.size();
const unsigned int numParticles = (unsigned int) m_particles.size();
const unsigned int numRigidBodies = (unsigned int) m_rigidBodies.size();
const unsigned int numBodies = numParticles + numRigidBodies;
m_constraintGroups.clear();
// Maps in which group a particle is or 0 if not yet mapped
std::vector<unsigned char*> mapping;
for (unsigned int i = 0; i < numConstraints; i++)
{
Constraint *constraint = m_constraints[i];
bool addToNewGroup = true;
for (unsigned int j = 0; j < m_constraintGroups.size(); j++)
{
bool addToThisGroup = true;
for (unsigned int k = 0; k < constraint->m_numberOfBodies; k++)
{
if (mapping[j][constraint->m_bodies[k]] != 0)
{
addToThisGroup = false;
break;
}
}
if (addToThisGroup)
{
m_constraintGroups[j].push_back(i);
for (unsigned int k = 0; k < constraint->m_numberOfBodies; k++)
mapping[j][constraint->m_bodies[k]] = 1;
addToNewGroup = false;
break;
}
}
if (addToNewGroup)
{
mapping.push_back(new unsigned char[numBodies]);
memset(mapping[mapping.size() - 1], 0, sizeof(unsigned char)*numBodies);
m_constraintGroups.resize(m_constraintGroups.size() + 1);
m_constraintGroups[m_constraintGroups.size()-1].push_back(i);
for (unsigned int k = 0; k < constraint->m_numberOfBodies; k++)
mapping[m_constraintGroups.size() - 1][constraint->m_bodies[k]] = 1;
}
}
for (unsigned int i = 0; i < mapping.size(); i++)
{
delete[] mapping[i];
}
mapping.clear();
m_groupsInitialized = true;
}
<|endoftext|> |
<commit_before>#ifndef AMGCL_BACKEND_EIGEN_HPP
#define AMGCL_BACKEND_EIGEN_HPP
/*
The MIT License
Copyright (c) 2012-2014 Denis Demidov <dennis.demidov@gmail.com>
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 amgcl/backend/eigen.hpp
* \author Denis Demidov <dennis.demidov@gmail.com>
* \brief Sparse matrix in CRS format.
*/
#include <boost/type_traits.hpp>
#include <boost/shared_ptr.hpp>
#include <boost/make_shared.hpp>
#include <Eigen/Sparse>
#include <amgcl/backend/builtin.hpp>
#include <amgcl/solver/skyline_lu.hpp>
namespace amgcl {
namespace backend {
/// Eigen backend.
/**
* This is a backend that uses types defined in the Eigen library
* (http://eigen.tuxfamily.org).
*
* \param real Value type.
* \ingroup backends
*/
template <typename real>
struct eigen {
typedef real value_type;
typedef long index_type;
typedef
Eigen::MappedSparseMatrix<value_type, Eigen::RowMajor, index_type>
matrix;
typedef
Eigen::Matrix<value_type, Eigen::Dynamic, 1>
vector;
typedef solver::skyline_lu<real> direct_solver;
/// Backend parameters.
struct params {};
/// Copy matrix from builtin backend.
static boost::shared_ptr<matrix>
copy_matrix(boost::shared_ptr< typename builtin<real>::matrix > A, const params&)
{
return boost::shared_ptr<matrix>(
new matrix(rows(*A), cols(*A), nonzeros(*A),
A->ptr.data(), A->col.data(), A->val.data()),
hold_host(A)
);
}
/// Copy vector from builtin backend.
static boost::shared_ptr<vector>
copy_vector(typename builtin<real>::vector const &x, const params&)
{
return boost::make_shared<vector>(
Eigen::Map<const vector>(x.data(), x.size())
);
}
/// Copy vector from builtin backend.
static boost::shared_ptr<vector>
copy_vector(boost::shared_ptr< typename builtin<real>::vector > x, const params &prm)
{
return copy_vector(*x, prm);
}
/// Create vector of the specified size.
static boost::shared_ptr<vector>
create_vector(size_t size, const params&)
{
return boost::make_shared<vector>(size);
}
/// Create direct solver for coarse level
static boost::shared_ptr<direct_solver>
create_solver(boost::shared_ptr< typename builtin<real>::matrix > A, const params&)
{
return boost::make_shared<direct_solver>(*A);
}
private:
struct hold_host {
typedef boost::shared_ptr< crs<real, long, long> > host_matrix;
host_matrix host;
hold_host( host_matrix host ) : host(host) {}
void operator()(matrix *ptr) const {
delete ptr;
}
};
};
//---------------------------------------------------------------------------
// Backend interface specialization for Eigen types
//---------------------------------------------------------------------------
template <class T, class Enable = void>
struct is_eigen_sparse_matrix : boost::false_type {};
template <class T, class Enable = void>
struct is_eigen_type : boost::false_type {};
template <class T>
struct is_eigen_sparse_matrix<
T,
typename boost::enable_if<
typename boost::mpl::and_<
typename boost::is_arithmetic<typename T::Scalar>::type,
typename boost::is_base_of<Eigen::SparseMatrixBase<T>, T>::type
>::type
>::type
> : boost::true_type
{};
template <class T>
struct is_eigen_type<
T,
typename boost::enable_if<
typename boost::mpl::and_<
typename boost::is_arithmetic<typename T::Scalar>::type,
typename boost::is_base_of<Eigen::EigenBase<T>, T>::type
>::type
>::type
> : boost::true_type
{};
template <class T>
struct value_type<
T,
typename boost::enable_if<
typename is_eigen_type<T>::type>::type
>
{
typedef typename T::Scalar type;
};
template <class T>
struct rows_impl<
T,
typename boost::enable_if<typename is_eigen_sparse_matrix<T>::type>::type
>
{
static size_t get(const T &matrix) {
return matrix.rows();
}
};
template <class T>
struct cols_impl<
T,
typename boost::enable_if<typename is_eigen_sparse_matrix<T>::type>::type
>
{
static size_t get(const T &matrix) {
return matrix.cols();
}
};
template <class T>
struct nonzeros_impl<
T,
typename boost::enable_if<typename is_eigen_type<T>::type>::type
>
{
static size_t get(const T &matrix) {
return matrix.nonZeros();
}
};
template <class T>
struct row_iterator <
T,
typename boost::enable_if<typename is_eigen_sparse_matrix<T>::type>::type
>
{
typedef typename T::InnerIterator type;
};
template <class T>
struct row_begin_impl <
T,
typename boost::enable_if<typename is_eigen_sparse_matrix<T>::type>::type
>
{
typedef typename row_iterator<T>::type iterator;
static iterator get(const T &matrix, size_t row) {
return iterator(matrix, row);
}
};
template < class M, class V >
struct spmv_impl<
M, V, V,
typename boost::enable_if<
typename boost::mpl::and_<
typename is_eigen_sparse_matrix<M>::type,
typename is_eigen_type<V>::type
>::type
>::type
>
{
typedef typename value_type<M>::type real;
static void apply(real alpha, const M &A, const V &x, real beta, V &y)
{
if (beta)
y = alpha * A * x + beta * y;
else
y = alpha * A * x;
}
};
template < class M, class V >
struct residual_impl<
M, V, V, V,
typename boost::enable_if<
typename boost::mpl::and_<
typename is_eigen_sparse_matrix<M>::type,
typename is_eigen_type<V>::type
>::type
>::type
>
{
static void apply(const V &rhs, const M &A, const V &x, V &r)
{
r = rhs - A * x;
}
};
template < typename V >
struct clear_impl<
V,
typename boost::enable_if< typename is_eigen_type<V>::type >::type
>
{
static void apply(V &x)
{
x.setZero();
}
};
template < typename V >
struct inner_product_impl<
V, V,
typename boost::enable_if< typename is_eigen_type<V>::type >::type
>
{
typedef typename value_type<V>::type real;
static real get(const V &x, const V &y)
{
return x.dot(y);
}
};
template < typename V >
struct axpby_impl<
V, V,
typename boost::enable_if< typename is_eigen_type<V>::type >::type
>
{
typedef typename value_type<V>::type real;
static void apply(real a, const V &x, real b, V &y)
{
if (b)
y = a * x + b * y;
else
y = a * x;
}
};
template < typename V >
struct axpbypcz_impl<
V, V, V,
typename boost::enable_if< typename is_eigen_type<V>::type >::type
>
{
typedef typename value_type<V>::type real;
static void apply(
real a, const V &x,
real b, const V &y,
real c, V &z
)
{
if (c)
z = a * x + b * y + c * y;
else
z = a * x + b * y;
}
};
template < typename V >
struct vmul_impl<
V, V, V,
typename boost::enable_if< typename is_eigen_type<V>::type >::type
>
{
typedef typename value_type<V>::type real;
static void apply(real a, const V &x, const V &y, real b, V &z)
{
if (b)
z.array() = a * x.array() * y.array() + b * z.array();
else
z.array() = a * x.array() * y.array();
}
};
template < typename V >
struct copy_impl<
V, V,
typename boost::enable_if< typename is_eigen_type<V>::type >::type
>
{
static void apply(const V &x, V &y)
{
y = x;
}
};
} // namespace backend
} // namespace amgcl
#endif
<commit_msg>Accept heterogeneous eigen vectors in eigen backend<commit_after>#ifndef AMGCL_BACKEND_EIGEN_HPP
#define AMGCL_BACKEND_EIGEN_HPP
/*
The MIT License
Copyright (c) 2012-2014 Denis Demidov <dennis.demidov@gmail.com>
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 amgcl/backend/eigen.hpp
* \author Denis Demidov <dennis.demidov@gmail.com>
* \brief Sparse matrix in CRS format.
*/
#include <boost/type_traits.hpp>
#include <boost/shared_ptr.hpp>
#include <boost/make_shared.hpp>
#include <Eigen/Sparse>
#include <amgcl/backend/builtin.hpp>
#include <amgcl/solver/skyline_lu.hpp>
namespace amgcl {
namespace backend {
/// Eigen backend.
/**
* This is a backend that uses types defined in the Eigen library
* (http://eigen.tuxfamily.org).
*
* \param real Value type.
* \ingroup backends
*/
template <typename real>
struct eigen {
typedef real value_type;
typedef long index_type;
typedef
Eigen::MappedSparseMatrix<value_type, Eigen::RowMajor, index_type>
matrix;
typedef
Eigen::Matrix<value_type, Eigen::Dynamic, 1>
vector;
typedef solver::skyline_lu<real> direct_solver;
/// Backend parameters.
struct params {};
/// Copy matrix from builtin backend.
static boost::shared_ptr<matrix>
copy_matrix(boost::shared_ptr< typename builtin<real>::matrix > A, const params&)
{
return boost::shared_ptr<matrix>(
new matrix(rows(*A), cols(*A), nonzeros(*A),
A->ptr.data(), A->col.data(), A->val.data()),
hold_host(A)
);
}
/// Copy vector from builtin backend.
static boost::shared_ptr<vector>
copy_vector(typename builtin<real>::vector const &x, const params&)
{
return boost::make_shared<vector>(
Eigen::Map<const vector>(x.data(), x.size())
);
}
/// Copy vector from builtin backend.
static boost::shared_ptr<vector>
copy_vector(boost::shared_ptr< typename builtin<real>::vector > x, const params &prm)
{
return copy_vector(*x, prm);
}
/// Create vector of the specified size.
static boost::shared_ptr<vector>
create_vector(size_t size, const params&)
{
return boost::make_shared<vector>(size);
}
/// Create direct solver for coarse level
static boost::shared_ptr<direct_solver>
create_solver(boost::shared_ptr< typename builtin<real>::matrix > A, const params&)
{
return boost::make_shared<direct_solver>(*A);
}
private:
struct hold_host {
typedef boost::shared_ptr< crs<real, long, long> > host_matrix;
host_matrix host;
hold_host( host_matrix host ) : host(host) {}
void operator()(matrix *ptr) const {
delete ptr;
}
};
};
//---------------------------------------------------------------------------
// Backend interface specialization for Eigen types
//---------------------------------------------------------------------------
template <class T, class Enable = void>
struct is_eigen_sparse_matrix : boost::false_type {};
template <class T, class Enable = void>
struct is_eigen_type : boost::false_type {};
template <class T>
struct is_eigen_sparse_matrix<
T,
typename boost::enable_if<
typename boost::mpl::and_<
typename boost::is_arithmetic<typename T::Scalar>::type,
typename boost::is_base_of<Eigen::SparseMatrixBase<T>, T>::type
>::type
>::type
> : boost::true_type
{};
template <class T>
struct is_eigen_type<
T,
typename boost::enable_if<
typename boost::mpl::and_<
typename boost::is_arithmetic<typename T::Scalar>::type,
typename boost::is_base_of<Eigen::EigenBase<T>, T>::type
>::type
>::type
> : boost::true_type
{};
template <class T>
struct value_type<
T,
typename boost::enable_if<
typename is_eigen_type<T>::type>::type
>
{
typedef typename T::Scalar type;
};
template <class T>
struct rows_impl<
T,
typename boost::enable_if<typename is_eigen_sparse_matrix<T>::type>::type
>
{
static size_t get(const T &matrix) {
return matrix.rows();
}
};
template <class T>
struct cols_impl<
T,
typename boost::enable_if<typename is_eigen_sparse_matrix<T>::type>::type
>
{
static size_t get(const T &matrix) {
return matrix.cols();
}
};
template <class T>
struct nonzeros_impl<
T,
typename boost::enable_if<typename is_eigen_type<T>::type>::type
>
{
static size_t get(const T &matrix) {
return matrix.nonZeros();
}
};
template <class T>
struct row_iterator <
T,
typename boost::enable_if<typename is_eigen_sparse_matrix<T>::type>::type
>
{
typedef typename T::InnerIterator type;
};
template <class T>
struct row_begin_impl <
T,
typename boost::enable_if<typename is_eigen_sparse_matrix<T>::type>::type
>
{
typedef typename row_iterator<T>::type iterator;
static iterator get(const T &matrix, size_t row) {
return iterator(matrix, row);
}
};
template < class M, class V1, class V2 >
struct spmv_impl<
M, V1, V2,
typename boost::enable_if<
typename boost::mpl::and_<
typename is_eigen_sparse_matrix<M>::type,
typename is_eigen_type<V1>::type,
typename is_eigen_type<V2>::type
>::type
>::type
>
{
typedef typename value_type<M>::type real;
static void apply(real alpha, const M &A, const V1 &x, real beta, V2 &y)
{
if (beta)
y = alpha * A * x + beta * y;
else
y = alpha * A * x;
}
};
template < class M, class V1, class V2, class V3 >
struct residual_impl<
M, V1, V2, V3,
typename boost::enable_if<
typename boost::mpl::and_<
typename is_eigen_sparse_matrix<M>::type,
typename is_eigen_type<V1>::type,
typename is_eigen_type<V2>::type,
typename is_eigen_type<V3>::type
>::type
>::type
>
{
static void apply(const V1 &rhs, const M &A, const V2 &x, V3 &r)
{
r = rhs - A * x;
}
};
template < typename V >
struct clear_impl<
V,
typename boost::enable_if< typename is_eigen_type<V>::type >::type
>
{
static void apply(V &x)
{
x.setZero();
}
};
template < class V1, class V2 >
struct inner_product_impl<
V1, V2,
typename boost::enable_if<
typename boost::mpl::and_<
typename is_eigen_type<V1>::type,
typename is_eigen_type<V2>::type
>::type
>::type
>
{
typedef typename value_type<V1>::type real;
static real get(const V1 &x, const V2 &y)
{
return x.dot(y);
}
};
template < class V1, class V2 >
struct axpby_impl<
V1, V2,
typename boost::enable_if<
typename boost::mpl::and_<
typename is_eigen_type<V1>::type,
typename is_eigen_type<V2>::type
>::type
>::type
>
{
typedef typename value_type<V1>::type real;
static void apply(real a, const V1 &x, real b, V2 &y)
{
if (b)
y = a * x + b * y;
else
y = a * x;
}
};
template < class V1, class V2, class V3 >
struct axpbypcz_impl<
V1, V2, V3,
typename boost::enable_if<
typename boost::mpl::and_<
typename is_eigen_type<V1>::type,
typename is_eigen_type<V2>::type,
typename is_eigen_type<V3>::type
>::type
>::type
>
{
typedef typename value_type<V1>::type real;
static void apply(
real a, const V1 &x,
real b, const V2 &y,
real c, V3 &z
)
{
if (c)
z = a * x + b * y + c * y;
else
z = a * x + b * y;
}
};
template < class V1, class V2, class V3 >
struct vmul_impl<
V1, V2, V3,
typename boost::enable_if<
typename boost::mpl::and_<
typename is_eigen_type<V1>::type,
typename is_eigen_type<V2>::type,
typename is_eigen_type<V3>::type
>::type
>::type
>
{
typedef typename value_type<V1>::type real;
static void apply(real a, const V1 &x, const V2 &y, real b, V3 &z)
{
if (b)
z.array() = a * x.array() * y.array() + b * z.array();
else
z.array() = a * x.array() * y.array();
}
};
template < class V1, class V2 >
struct copy_impl<
V1, V2,
typename boost::enable_if<
typename boost::mpl::and_<
typename is_eigen_type<V1>::type,
typename is_eigen_type<V2>::type
>::type
>::type
>
{
static void apply(const V1 &x, V2 &y)
{
y = x;
}
};
} // namespace backend
} // namespace amgcl
#endif
<|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 "base/basictypes.h"
#include "base/gfx/png_encoder.h"
#include "base/logging.h"
#include "base/scoped_ptr.h"
#include "third_party/skia/include/core/SkBitmap.h"
extern "C" {
#include "third_party/libpng/png.h"
}
namespace {
// Converts BGRA->RGBA and RGBA->BGRA.
void ConvertBetweenBGRAandRGBA(const unsigned char* input, int pixel_width,
unsigned char* output) {
for (int x = 0; x < pixel_width; x++) {
const unsigned char* pixel_in = &input[x * 4];
unsigned char* pixel_out = &output[x * 4];
pixel_out[0] = pixel_in[2];
pixel_out[1] = pixel_in[1];
pixel_out[2] = pixel_in[0];
pixel_out[3] = pixel_in[3];
}
}
void ConvertRGBAtoRGB(const unsigned char* rgba, int pixel_width,
unsigned char* rgb) {
for (int x = 0; x < pixel_width; x++) {
const unsigned char* pixel_in = &rgba[x * 4];
unsigned char* pixel_out = &rgb[x * 3];
pixel_out[0] = pixel_in[0];
pixel_out[1] = pixel_in[1];
pixel_out[2] = pixel_in[2];
}
}
} // namespace
// Encoder --------------------------------------------------------------------
//
// This section of the code is based on nsPNGEncoder.cpp in Mozilla
// (Copyright 2005 Google Inc.)
namespace {
// Passed around as the io_ptr in the png structs so our callbacks know where
// to write data.
struct PngEncoderState {
PngEncoderState(std::vector<unsigned char>* o) : out(o) {}
std::vector<unsigned char>* out;
};
// Called by libpng to flush its internal buffer to ours.
void EncoderWriteCallback(png_structp png, png_bytep data, png_size_t size) {
PngEncoderState* state = static_cast<PngEncoderState*>(png_get_io_ptr(png));
DCHECK(state->out);
size_t old_size = state->out->size();
state->out->resize(old_size + size);
memcpy(&(*state->out)[old_size], data, size);
}
void ConvertBGRAtoRGB(const unsigned char* bgra, int pixel_width,
unsigned char* rgb) {
for (int x = 0; x < pixel_width; x++) {
const unsigned char* pixel_in = &bgra[x * 4];
unsigned char* pixel_out = &rgb[x * 3];
pixel_out[0] = pixel_in[2];
pixel_out[1] = pixel_in[1];
pixel_out[2] = pixel_in[0];
}
}
// Automatically destroys the given write structs on destruction to make
// cleanup and error handling code cleaner.
class PngWriteStructDestroyer {
public:
PngWriteStructDestroyer(png_struct** ps, png_info** pi) : ps_(ps), pi_(pi) {
}
~PngWriteStructDestroyer() {
png_destroy_write_struct(ps_, pi_);
}
private:
png_struct** ps_;
png_info** pi_;
DISALLOW_EVIL_CONSTRUCTORS(PngWriteStructDestroyer);
};
} // namespace
// static
bool PNGEncoder::Encode(const unsigned char* input, ColorFormat format,
int w, int h, int row_byte_width,
bool discard_transparency,
std::vector<unsigned char>* output) {
// Run to convert an input row into the output row format, NULL means no
// conversion is necessary.
void (*converter)(const unsigned char* in, int w, unsigned char* out) = NULL;
int input_color_components, output_color_components;
int png_output_color_type;
switch (format) {
case FORMAT_RGB:
input_color_components = 3;
output_color_components = 3;
png_output_color_type = PNG_COLOR_TYPE_RGB;
discard_transparency = false;
break;
case FORMAT_RGBA:
input_color_components = 4;
if (discard_transparency) {
output_color_components = 3;
png_output_color_type = PNG_COLOR_TYPE_RGB;
converter = ConvertRGBAtoRGB;
} else {
output_color_components = 4;
png_output_color_type = PNG_COLOR_TYPE_RGB_ALPHA;
converter = NULL;
}
break;
case FORMAT_BGRA:
input_color_components = 4;
if (discard_transparency) {
output_color_components = 3;
png_output_color_type = PNG_COLOR_TYPE_RGB;
converter = ConvertBGRAtoRGB;
} else {
output_color_components = 4;
png_output_color_type = PNG_COLOR_TYPE_RGB_ALPHA;
converter = ConvertBetweenBGRAandRGBA;
}
break;
default:
NOTREACHED() << "Unknown pixel format";
return false;
}
// Row stride should be at least as long as the length of the data.
DCHECK(input_color_components * w <= row_byte_width);
png_struct* png_ptr = png_create_write_struct(PNG_LIBPNG_VER_STRING,
png_voidp_NULL,
png_error_ptr_NULL,
png_error_ptr_NULL);
if (!png_ptr)
return false;
png_info* info_ptr = png_create_info_struct(png_ptr);
if (!info_ptr) {
png_destroy_write_struct(&png_ptr, NULL);
return false;
}
PngWriteStructDestroyer destroyer(&png_ptr, &info_ptr);
if (setjmp(png_jmpbuf(png_ptr))) {
// The destroyer will ensure that the structures are cleaned up in this
// case, even though we may get here as a jump from random parts of the
// PNG library called below.
return false;
}
// Set our callback for libpng to give us the data.
PngEncoderState state(output);
png_set_write_fn(png_ptr, &state, EncoderWriteCallback, NULL);
png_set_IHDR(png_ptr, info_ptr, w, h, 8, png_output_color_type,
PNG_INTERLACE_NONE, PNG_COMPRESSION_TYPE_DEFAULT,
PNG_FILTER_TYPE_DEFAULT);
png_write_info(png_ptr, info_ptr);
if (!converter) {
// No conversion needed, give the data directly to libpng.
for (int y = 0; y < h; y ++)
png_write_row(png_ptr,
const_cast<unsigned char*>(&input[y * row_byte_width]));
} else {
// Needs conversion using a separate buffer.
unsigned char* row = new unsigned char[w * output_color_components];
for (int y = 0; y < h; y ++) {
converter(&input[y * row_byte_width], w, row);
png_write_row(png_ptr, row);
}
delete[] row;
}
png_write_end(png_ptr, info_ptr);
return true;
}
// static
bool PNGEncoder::EncodeBGRASkBitmap(const SkBitmap& input,
bool discard_transparency,
std::vector<unsigned char>* output) {
// This only works with images with four bytes per pixel.
static const int bbp = 4;
DCHECK(!input.empty());
DCHECK(input.bytesPerPixel() == bbp);
DCHECK(input.config() == SkBitmap::kARGB_8888_Config);
// SkBitmaps are premultiplied, we need to unpremultiply them.
scoped_array<unsigned char> divided(
new unsigned char[input.width() * input.height() * bbp]);
SkAutoLockPixels lock_input(input);
int i = 0;
for (int y = 0; y < input.height(); y++) {
uint32* src_row = input.getAddr32(0, y);
for (int x = 0; x < input.width(); x++) {
uint32 pixel = src_row[x];
int alpha = SkColorGetA(pixel);
if (alpha != 0 && alpha != 255) {
divided[i + 0] = (SkColorGetR(pixel) << 8) / alpha;
divided[i + 1] = (SkColorGetG(pixel) << 8) / alpha;
divided[i + 2] = (SkColorGetB(pixel) << 8) / alpha;
divided[i + 3] = alpha;
} else {
divided[i + 0] = SkColorGetR(pixel);
divided[i + 1] = SkColorGetG(pixel);
divided[i + 2] = SkColorGetB(pixel);
divided[i + 3] = SkColorGetA(pixel);
}
i += bbp;
}
}
return Encode(divided.get(),
PNGEncoder::FORMAT_RGBA, input.width(), input.height(),
input.rowBytes(), discard_transparency, output);
}
<commit_msg>Revert png encoder changes.<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 "base/basictypes.h"
#include "base/gfx/png_encoder.h"
#include "base/logging.h"
#include "third_party/skia/include/core/SkBitmap.h"
extern "C" {
#include "third_party/libpng/png.h"
}
namespace {
// Converts BGRA->RGBA and RGBA->BGRA.
void ConvertBetweenBGRAandRGBA(const unsigned char* input, int pixel_width,
unsigned char* output) {
for (int x = 0; x < pixel_width; x++) {
const unsigned char* pixel_in = &input[x * 4];
unsigned char* pixel_out = &output[x * 4];
pixel_out[0] = pixel_in[2];
pixel_out[1] = pixel_in[1];
pixel_out[2] = pixel_in[0];
pixel_out[3] = pixel_in[3];
}
}
void ConvertRGBAtoRGB(const unsigned char* rgba, int pixel_width,
unsigned char* rgb) {
for (int x = 0; x < pixel_width; x++) {
const unsigned char* pixel_in = &rgba[x * 4];
unsigned char* pixel_out = &rgb[x * 3];
pixel_out[0] = pixel_in[0];
pixel_out[1] = pixel_in[1];
pixel_out[2] = pixel_in[2];
}
}
} // namespace
// Encoder --------------------------------------------------------------------
//
// This section of the code is based on nsPNGEncoder.cpp in Mozilla
// (Copyright 2005 Google Inc.)
namespace {
// Passed around as the io_ptr in the png structs so our callbacks know where
// to write data.
struct PngEncoderState {
PngEncoderState(std::vector<unsigned char>* o) : out(o) {}
std::vector<unsigned char>* out;
};
// Called by libpng to flush its internal buffer to ours.
void EncoderWriteCallback(png_structp png, png_bytep data, png_size_t size) {
PngEncoderState* state = static_cast<PngEncoderState*>(png_get_io_ptr(png));
DCHECK(state->out);
size_t old_size = state->out->size();
state->out->resize(old_size + size);
memcpy(&(*state->out)[old_size], data, size);
}
void ConvertBGRAtoRGB(const unsigned char* bgra, int pixel_width,
unsigned char* rgb) {
for (int x = 0; x < pixel_width; x++) {
const unsigned char* pixel_in = &bgra[x * 4];
unsigned char* pixel_out = &rgb[x * 3];
pixel_out[0] = pixel_in[2];
pixel_out[1] = pixel_in[1];
pixel_out[2] = pixel_in[0];
}
}
// Automatically destroys the given write structs on destruction to make
// cleanup and error handling code cleaner.
class PngWriteStructDestroyer {
public:
PngWriteStructDestroyer(png_struct** ps, png_info** pi) : ps_(ps), pi_(pi) {
}
~PngWriteStructDestroyer() {
png_destroy_write_struct(ps_, pi_);
}
private:
png_struct** ps_;
png_info** pi_;
DISALLOW_EVIL_CONSTRUCTORS(PngWriteStructDestroyer);
};
} // namespace
// static
bool PNGEncoder::Encode(const unsigned char* input, ColorFormat format,
int w, int h, int row_byte_width,
bool discard_transparency,
std::vector<unsigned char>* output) {
// Run to convert an input row into the output row format, NULL means no
// conversion is necessary.
void (*converter)(const unsigned char* in, int w, unsigned char* out) = NULL;
int input_color_components, output_color_components;
int png_output_color_type;
switch (format) {
case FORMAT_RGB:
input_color_components = 3;
output_color_components = 3;
png_output_color_type = PNG_COLOR_TYPE_RGB;
discard_transparency = false;
break;
case FORMAT_RGBA:
input_color_components = 4;
if (discard_transparency) {
output_color_components = 3;
png_output_color_type = PNG_COLOR_TYPE_RGB;
converter = ConvertRGBAtoRGB;
} else {
output_color_components = 4;
png_output_color_type = PNG_COLOR_TYPE_RGB_ALPHA;
converter = NULL;
}
break;
case FORMAT_BGRA:
input_color_components = 4;
if (discard_transparency) {
output_color_components = 3;
png_output_color_type = PNG_COLOR_TYPE_RGB;
converter = ConvertBGRAtoRGB;
} else {
output_color_components = 4;
png_output_color_type = PNG_COLOR_TYPE_RGB_ALPHA;
converter = ConvertBetweenBGRAandRGBA;
}
break;
default:
NOTREACHED() << "Unknown pixel format";
return false;
}
// Row stride should be at least as long as the length of the data.
DCHECK(input_color_components * w <= row_byte_width);
png_struct* png_ptr = png_create_write_struct(PNG_LIBPNG_VER_STRING,
png_voidp_NULL,
png_error_ptr_NULL,
png_error_ptr_NULL);
if (!png_ptr)
return false;
png_info* info_ptr = png_create_info_struct(png_ptr);
if (!info_ptr) {
png_destroy_write_struct(&png_ptr, NULL);
return false;
}
PngWriteStructDestroyer destroyer(&png_ptr, &info_ptr);
if (setjmp(png_jmpbuf(png_ptr))) {
// The destroyer will ensure that the structures are cleaned up in this
// case, even though we may get here as a jump from random parts of the
// PNG library called below.
return false;
}
// Set our callback for libpng to give us the data.
PngEncoderState state(output);
png_set_write_fn(png_ptr, &state, EncoderWriteCallback, NULL);
png_set_IHDR(png_ptr, info_ptr, w, h, 8, png_output_color_type,
PNG_INTERLACE_NONE, PNG_COMPRESSION_TYPE_DEFAULT,
PNG_FILTER_TYPE_DEFAULT);
png_write_info(png_ptr, info_ptr);
if (!converter) {
// No conversion needed, give the data directly to libpng.
for (int y = 0; y < h; y ++)
png_write_row(png_ptr,
const_cast<unsigned char*>(&input[y * row_byte_width]));
} else {
// Needs conversion using a separate buffer.
unsigned char* row = new unsigned char[w * output_color_components];
for (int y = 0; y < h; y ++) {
converter(&input[y * row_byte_width], w, row);
png_write_row(png_ptr, row);
}
delete[] row;
}
png_write_end(png_ptr, info_ptr);
return true;
}
// static
bool PNGEncoder::EncodeBGRASkBitmap(const SkBitmap& input,
bool discard_transparency,
std::vector<unsigned char>* output) {
SkAutoLockPixels input_lock(input);
DCHECK(input.empty() || input.bytesPerPixel() == 4);
return Encode(static_cast<unsigned char*>(input.getPixels()),
PNGEncoder::FORMAT_BGRA, input.width(), input.height(),
input.rowBytes(), discard_transparency, output);
}
<|endoftext|> |
<commit_before>#include "AdaptiveBoole.h"
#include <queue>
#include <algorithm>
#include <limits>
struct BooleHelper
{
BooleHelper() : error(0.0){};
std::vector<double> fa, fb, fc, fd, fe, ff, fg, fh, fi;
std::vector<double> S, Sleft, Sright;
double lowerlimit;
double upperlimit;
double epsilon;
double error;
bool operator<(const BooleHelper &rhs) const { return this->error / this->epsilon < rhs.error / rhs.epsilon; }
};
class AdaptiveBoole::BooleImpl
{
public:
BooleImpl() : m_epsilon(1.0e-5), m_maximumDivisions(10){};
std::vector<double> sumPieces(std::priority_queue<BooleHelper> &pieces);
void createElement(const BooleHelper &mostError,BooleHelper &element, bool first);
void splitElement(const BooleHelper &mostError,BooleHelper &element1,BooleHelper &element2);
std::vector<double> integrate();
std::function<std::vector<double>(std::deque<double> &evaluationPoints)> m_integrand;
double m_lowerBound, m_upperBound, m_epsilon;
std::vector<double> m_lowerBoundsInnerDimensions, m_upperBoundsInnerDimensions;
std::deque<double> m_evaluationPointsOuterDimensions;
int m_maximumDivisions;
std::unique_ptr<BooleImpl> clone();
};
std::unique_ptr<AdaptiveBoole::BooleImpl> AdaptiveBoole::BooleImpl::clone()
{
return std::unique_ptr<AdaptiveBoole::BooleImpl>(new BooleImpl(*this));
}
void AdaptiveBoole::BooleImpl::createElement(const BooleHelper &mostError, BooleHelper& element, bool first)
{
double a, b;
if (first)
{
a = mostError.lowerlimit;
b = (mostError.lowerlimit + mostError.upperlimit) / 2.0;
}
else
{
a = (mostError.lowerlimit + mostError.upperlimit) / 2.0;
b = mostError.upperlimit;
}
double tmp = (b - a) / 8.0;
double c = a + tmp;
double e = a + 3.0 * tmp;
double g = a + 5.0 * tmp;
double i = a + 7.0 * tmp;
if (first)
{
element.fa = std::move(mostError.fa);
element.fb = mostError.ff;
element.fd = std::move(mostError.fc);
element.ff = std::move(mostError.fd);
element.fh = std::move(mostError.fe);
element.S = std::move(mostError.Sleft);
}
else
{
element.fa = std::move(mostError.ff);
element.fb = std::move(mostError.fb);
element.fd = std::move(mostError.fg);
element.ff = std::move(mostError.fh);
element.fh = std::move(mostError.fi);
element.S = std::move(mostError.Sright);
}
if (m_lowerBoundsInnerDimensions.size() > 0)
{
AdaptiveBoole test;
test.setFunction(m_integrand);
test.setInterval(m_lowerBoundsInnerDimensions, m_upperBoundsInnerDimensions);
test.setMaximumDivisions(m_maximumDivisions);
test.setPrecision(m_epsilon);
m_evaluationPointsOuterDimensions[0] = c;
test.setAdditionalEvaluationPoints(m_evaluationPointsOuterDimensions);
element.fc = test.integrate();
m_evaluationPointsOuterDimensions[0] = e;
test.setAdditionalEvaluationPoints(m_evaluationPointsOuterDimensions);
element.fe = test.integrate();
m_evaluationPointsOuterDimensions[0] = g;
test.setAdditionalEvaluationPoints(m_evaluationPointsOuterDimensions);
element.fg = test.integrate();
m_evaluationPointsOuterDimensions[0] = i;
test.setAdditionalEvaluationPoints(m_evaluationPointsOuterDimensions);
element.fi = test.integrate();
}
else
{
m_evaluationPointsOuterDimensions[0] = c;
element.fc = m_integrand(m_evaluationPointsOuterDimensions);
m_evaluationPointsOuterDimensions[0] = e;
element.fe = m_integrand(m_evaluationPointsOuterDimensions);
m_evaluationPointsOuterDimensions[0] = g;
element.fg = m_integrand(m_evaluationPointsOuterDimensions);
m_evaluationPointsOuterDimensions[0] = i;
element.fi = m_integrand(m_evaluationPointsOuterDimensions);
}
std::size_t size = element.fa.size();
double prefactor = (b - a) / 180.0;
element.Sleft.reserve(size);
element.Sright.reserve(size);
for (std::size_t i = 0; i < size; i++)
{
element.Sleft.emplace_back(prefactor * (7.0 * element.fa[i] + 32.0 * element.fc[i] + 12.0 * element.fd[i] +
32.0 * element.fe[i] + 7.0 * element.ff[i]));
element.Sright.emplace_back(prefactor * (7.0 * element.ff[i] + 32.0 * element.fg[i] + 12.0 * element.fh[i] +
32.0 * element.fi[i] + 7.0 * element.fb[i]));
element.error = std::max(element.error, std::abs(63.0 * (element.Sleft[i] + element.Sright[i] - element.S[i])));
}
element.lowerlimit = a;
element.upperlimit = b;
element.epsilon = std::max(mostError.epsilon * M_SQRT1_2, std::numeric_limits<double>::epsilon());
// std::cout << element.epsilon << " " << element.error << std::endl;
}
void AdaptiveBoole::BooleImpl::splitElement(const BooleHelper &mostError, BooleHelper &element1, BooleHelper &element2)
{
this->createElement(mostError, element1,true);
this->createElement(mostError, element2,false);
//return std::make_pair(element1, element2);
}
std::vector<double> AdaptiveBoole::BooleImpl::sumPieces(std::priority_queue<BooleHelper> &pieces)
{
std::size_t size = pieces.top().Sleft.size();
std::vector<double> sum(size);
while (pieces.size() > 0)
{
auto element = pieces.top();
for (std::size_t i = 0; i < size; i++)
{
double S2 = element.Sleft[i] + element.Sright[i];
sum[i] += S2 + (S2 - element.S[i]) / 63.0;
}
pieces.pop();
}
return sum;
}
std::vector<double> AdaptiveBoole::BooleImpl::integrate()
{
BooleHelper first;
double a = m_lowerBound;
double b = m_upperBound;
double tmp = (b - a) / 8.0;
double c = a + tmp;
double d = a + 2.0 * tmp;
double e = a + 3.0 * tmp;
double f = a + 4.0 * tmp;
double g = a + 5.0 * tmp;
double h = a + 6.0 * tmp;
double i = a + 7.0 * tmp;
//std::cout << b << " " << a + 8.0 * tmp << std::endl;
if (m_lowerBoundsInnerDimensions.size() > 0)
{
AdaptiveBoole test;
test.setFunction(m_integrand);
test.setInterval(m_lowerBoundsInnerDimensions, m_upperBoundsInnerDimensions);
test.setMaximumDivisions(m_maximumDivisions);
test.setPrecision(m_epsilon);
m_evaluationPointsOuterDimensions.push_front(a);
test.setAdditionalEvaluationPoints(m_evaluationPointsOuterDimensions);
first.fa = test.integrate();
m_evaluationPointsOuterDimensions[0] = b;
test.setAdditionalEvaluationPoints(m_evaluationPointsOuterDimensions);
first.fb = test.integrate();
m_evaluationPointsOuterDimensions[0] = c;
test.setAdditionalEvaluationPoints(m_evaluationPointsOuterDimensions);
first.fc = test.integrate();
m_evaluationPointsOuterDimensions[0] = d;
test.setAdditionalEvaluationPoints(m_evaluationPointsOuterDimensions);
first.fd = test.integrate();
m_evaluationPointsOuterDimensions[0] = e;
test.setAdditionalEvaluationPoints(m_evaluationPointsOuterDimensions);
first.fe = test.integrate();
m_evaluationPointsOuterDimensions[0] = f;
test.setAdditionalEvaluationPoints(m_evaluationPointsOuterDimensions);
first.ff = test.integrate();
m_evaluationPointsOuterDimensions[0] = g;
test.setAdditionalEvaluationPoints(m_evaluationPointsOuterDimensions);
first.fg = test.integrate();
m_evaluationPointsOuterDimensions[0] = h;
test.setAdditionalEvaluationPoints(m_evaluationPointsOuterDimensions);
first.fh = test.integrate();
m_evaluationPointsOuterDimensions[0] = i;
test.setAdditionalEvaluationPoints(m_evaluationPointsOuterDimensions);
first.fi = test.integrate();
}
else
{
m_evaluationPointsOuterDimensions.push_front(a);
first.fa = m_integrand(m_evaluationPointsOuterDimensions);
m_evaluationPointsOuterDimensions[0] = b;
first.fb = m_integrand(m_evaluationPointsOuterDimensions);
m_evaluationPointsOuterDimensions[0] = c;
first.fc = m_integrand(m_evaluationPointsOuterDimensions);
m_evaluationPointsOuterDimensions[0] = d;
first.fd = m_integrand(m_evaluationPointsOuterDimensions);
m_evaluationPointsOuterDimensions[0] = e;
first.fe = m_integrand(m_evaluationPointsOuterDimensions);
m_evaluationPointsOuterDimensions[0] = f;
first.ff = m_integrand(m_evaluationPointsOuterDimensions);
m_evaluationPointsOuterDimensions[0] = g;
first.fg = m_integrand(m_evaluationPointsOuterDimensions);
m_evaluationPointsOuterDimensions[0] = h;
first.fh = m_integrand(m_evaluationPointsOuterDimensions);
m_evaluationPointsOuterDimensions[0] = i;
first.fi = m_integrand(m_evaluationPointsOuterDimensions);
}
std::size_t size = first.fa.size();
double prefactor = (b - a) / 180.0;
first.S.reserve(size);
first.Sleft.reserve(size);
first.Sright.reserve(size);
for (std::size_t i = 0; i < size; i++)
{
first.S.emplace_back(2.0 * prefactor * (7.0 * first.fa[i] + 32.0 * first.fd[i] + 12.0 * first.ff[i] +
32.0 * first.fh[i] + 7.0 * first.fb[i]));
first.Sleft.emplace_back(prefactor * (7.0 * first.fa[i] + 32.0 * first.fc[i] + 12.0 * first.fd[i] +
32.0 * first.fe[i] + 7.0 * first.ff[i]));
first.Sright.emplace_back(prefactor * (7.0 * first.ff[i] + 32.0 * first.fg[i] + 12.0 * first.fh[i] +
32.0 * first.fi[i] + 7.0 * first.fb[i]));
first.error = std::max(first.error, std::abs(63.0 * (first.Sleft[i] + first.Sright[i] - first.S[i])));
}
first.lowerlimit = m_lowerBound;
first.upperlimit = m_upperBound;
first.epsilon = m_epsilon;
std::priority_queue<BooleHelper> myqueue;
myqueue.emplace(first);
while (myqueue.size() < m_maximumDivisions)
{
const BooleHelper& mostError = myqueue.top();
if (mostError.error < mostError.epsilon)
break;
// std::cout << mostError.error << " " << mostError.epsilon << std::endl;
// std::cout << "mostError: " << mostError.S[0] << " " << mostError.Sleft[0] << " " << mostError.Sright[0] << " "
// << mostError.error << std::endl;
BooleHelper element1, element2;
splitElement(mostError,element1,element2);
// std::cout << "element1: " << element1.S[0] << " " << element1.Sleft[0] << " " << element1.Sright[0] << " " <<
// element1.error << " " << element1.epsilon << " " << myqueue.size() << std::endl;
// std::cout << "element2: " << element2.S[0] << " " << element2.Sleft[0] << " " << element2.Sright[0] << " " <<
// element2.error << " " << element1.epsilon << std::endl;
myqueue.pop();
myqueue.emplace(std::move(element1));
myqueue.emplace(std::move(element2));
}
return sumPieces(myqueue);
}
AdaptiveBoole::AdaptiveBoole() : m_p{new BooleImpl{}} {}
AdaptiveBoole::AdaptiveBoole(const AdaptiveBoole &other) : m_p(other.m_p->clone()) {}
AdaptiveBoole &AdaptiveBoole::operator=(const AdaptiveBoole &other)
{
m_p = move(other.m_p->clone());
return *this;
}
AdaptiveBoole::AdaptiveBoole(AdaptiveBoole &&other)
{
m_p = move(other.m_p);
other.m_p = NULL;
}
AdaptiveBoole &AdaptiveBoole::operator=(AdaptiveBoole &&other)
{
if (m_p != other.m_p)
{
m_p = move(other.m_p);
other.m_p = NULL;
}
return *this;
}
void
AdaptiveBoole::setFunction(const std::function<std::vector<double>(std::deque<double> &evaluationPoints)> &integrand)
{
m_p->m_integrand = integrand;
}
void AdaptiveBoole::setInterval(const std::vector<double> &lowerBounds, const std::vector<double> &upperBounds)
{
assert(lowerBounds.size() == upperBounds.size());
m_p->m_lowerBound = lowerBounds.back();
m_p->m_upperBound = upperBounds.back();
if (lowerBounds.size() > 1)
{
m_p->m_lowerBoundsInnerDimensions = lowerBounds;
m_p->m_lowerBoundsInnerDimensions.pop_back();
m_p->m_upperBoundsInnerDimensions = upperBounds;
m_p->m_upperBoundsInnerDimensions.pop_back();
}
}
void AdaptiveBoole::setPrecision(double epsilon) { m_p->m_epsilon = epsilon; }
void AdaptiveBoole::setMaximumDivisions(int maximumDivisions) { m_p->m_maximumDivisions = maximumDivisions; }
std::vector<double> AdaptiveBoole::integrate() { return m_p->integrate(); }
void AdaptiveBoole::setAdditionalEvaluationPoints(const std::deque<double> &evaluationPoints)
{
m_p->m_evaluationPointsOuterDimensions = evaluationPoints;
}
AdaptiveBoole::~AdaptiveBoole(){};
<commit_msg>update Boole integrator<commit_after>#include "AdaptiveBoole.h"
#include <queue>
#include <algorithm>
#include <limits>
struct BooleHelper
{
BooleHelper() : error(0.0){};
std::vector<double> fa, fb, fc, fd, fe, ff, fg, fh, fi;
std::vector<double> S, Sleft, Sright;
double lowerlimit;
double upperlimit;
double epsilon;
double error;
bool operator<(const BooleHelper &rhs) const { return this->error / this->epsilon < rhs.error / rhs.epsilon; }
};
class AdaptiveBoole::BooleImpl
{
public:
BooleImpl() : m_epsilon(1.0e-5), m_maximumDivisions(10){};
std::vector<double> sumPieces(std::priority_queue<BooleHelper> &pieces);
void createElement(const BooleHelper &mostError,BooleHelper &element, bool first);
void splitElement(const BooleHelper &mostError,BooleHelper &element1,BooleHelper &element2);
std::vector<double> integrate();
std::function<std::vector<double>(std::deque<double> &evaluationPoints)> m_integrand;
double m_lowerBound, m_upperBound, m_epsilon;
std::vector<double> m_lowerBoundsInnerDimensions, m_upperBoundsInnerDimensions;
std::deque<double> m_evaluationPointsOuterDimensions;
int m_maximumDivisions;
std::unique_ptr<BooleImpl> clone();
};
std::unique_ptr<AdaptiveBoole::BooleImpl> AdaptiveBoole::BooleImpl::clone()
{
return std::unique_ptr<AdaptiveBoole::BooleImpl>(new BooleImpl(*this));
}
void AdaptiveBoole::BooleImpl::createElement(const BooleHelper &mostError, BooleHelper& element, bool first)
{
double a, b;
if (first)
{
a = mostError.lowerlimit;
b = (mostError.lowerlimit + mostError.upperlimit) / 2.0;
}
else
{
a = (mostError.lowerlimit + mostError.upperlimit) / 2.0;
b = mostError.upperlimit;
}
double tmp = (b - a) / 8.0;
double c = a + tmp;
double e = a + 3.0 * tmp;
double g = a + 5.0 * tmp;
double i = a + 7.0 * tmp;
if (first)
{
element.fa = std::move(mostError.fa);
element.fb = mostError.ff;
element.fd = std::move(mostError.fc);
element.ff = std::move(mostError.fd);
element.fh = std::move(mostError.fe);
element.S = std::move(mostError.Sleft);
}
else
{
element.fa = std::move(mostError.ff);
element.fb = std::move(mostError.fb);
element.fd = std::move(mostError.fg);
element.ff = std::move(mostError.fh);
element.fh = std::move(mostError.fi);
element.S = std::move(mostError.Sright);
}
if (m_lowerBoundsInnerDimensions.size() > 0)
{
AdaptiveBoole test;
test.setFunction(m_integrand);
test.setInterval(m_lowerBoundsInnerDimensions, m_upperBoundsInnerDimensions);
test.setMaximumDivisions(m_maximumDivisions);
test.setPrecision(m_epsilon);
m_evaluationPointsOuterDimensions[0] = c;
test.setAdditionalEvaluationPoints(m_evaluationPointsOuterDimensions);
element.fc = test.integrate();
m_evaluationPointsOuterDimensions[0] = e;
test.setAdditionalEvaluationPoints(m_evaluationPointsOuterDimensions);
element.fe = test.integrate();
m_evaluationPointsOuterDimensions[0] = g;
test.setAdditionalEvaluationPoints(m_evaluationPointsOuterDimensions);
element.fg = test.integrate();
m_evaluationPointsOuterDimensions[0] = i;
test.setAdditionalEvaluationPoints(m_evaluationPointsOuterDimensions);
element.fi = test.integrate();
}
else
{
m_evaluationPointsOuterDimensions[0] = c;
element.fc = m_integrand(m_evaluationPointsOuterDimensions);
m_evaluationPointsOuterDimensions[0] = e;
element.fe = m_integrand(m_evaluationPointsOuterDimensions);
m_evaluationPointsOuterDimensions[0] = g;
element.fg = m_integrand(m_evaluationPointsOuterDimensions);
m_evaluationPointsOuterDimensions[0] = i;
element.fi = m_integrand(m_evaluationPointsOuterDimensions);
}
std::size_t size = element.fa.size();
double prefactor = (b - a) / 180.0;
element.Sleft.reserve(size);
element.Sright.reserve(size);
for (std::size_t i = 0; i < size; i++)
{
element.Sleft.emplace_back(prefactor * (7.0 * element.fa[i] + 32.0 * element.fc[i] + 12.0 * element.fd[i] +
32.0 * element.fe[i] + 7.0 * element.ff[i]));
element.Sright.emplace_back(prefactor * (7.0 * element.ff[i] + 32.0 * element.fg[i] + 12.0 * element.fh[i] +
32.0 * element.fi[i] + 7.0 * element.fb[i]));
element.error = std::max(element.error, std::abs(63.0 * (element.Sleft[i] + element.Sright[i] - element.S[i])));
}
element.lowerlimit = a;
element.upperlimit = b;
element.epsilon = std::max(mostError.epsilon * M_SQRT1_2, std::numeric_limits<double>::epsilon());
// std::cout << element.epsilon << " " << element.error << std::endl;
}
void AdaptiveBoole::BooleImpl::splitElement(const BooleHelper &mostError, BooleHelper &element1, BooleHelper &element2)
{
this->createElement(mostError, element1,true);
this->createElement(mostError, element2,false);
//return std::make_pair(element1, element2);
}
std::vector<double> AdaptiveBoole::BooleImpl::sumPieces(std::priority_queue<BooleHelper> &pieces)
{
std::size_t size = pieces.top().Sleft.size();
std::vector<double> sum(size);
while (pieces.size() > 0)
{
const BooleHelper& element = pieces.top();
for (std::size_t i = 0; i < size; i++)
{
double S2 = element.Sleft[i] + element.Sright[i];
sum[i] += S2 + (S2 - element.S[i]) / 63.0;
}
pieces.pop();
}
return sum;
}
std::vector<double> AdaptiveBoole::BooleImpl::integrate()
{
BooleHelper first;
double a = m_lowerBound;
double b = m_upperBound;
double tmp = (b - a) / 8.0;
double c = a + tmp;
double d = a + 2.0 * tmp;
double e = a + 3.0 * tmp;
double f = a + 4.0 * tmp;
double g = a + 5.0 * tmp;
double h = a + 6.0 * tmp;
double i = a + 7.0 * tmp;
//std::cout << b << " " << a + 8.0 * tmp << std::endl;
if (m_lowerBoundsInnerDimensions.size() > 0)
{
AdaptiveBoole test;
test.setFunction(m_integrand);
test.setInterval(m_lowerBoundsInnerDimensions, m_upperBoundsInnerDimensions);
test.setMaximumDivisions(m_maximumDivisions);
test.setPrecision(m_epsilon);
m_evaluationPointsOuterDimensions.push_front(a);
test.setAdditionalEvaluationPoints(m_evaluationPointsOuterDimensions);
first.fa = test.integrate();
m_evaluationPointsOuterDimensions[0] = b;
test.setAdditionalEvaluationPoints(m_evaluationPointsOuterDimensions);
first.fb = test.integrate();
m_evaluationPointsOuterDimensions[0] = c;
test.setAdditionalEvaluationPoints(m_evaluationPointsOuterDimensions);
first.fc = test.integrate();
m_evaluationPointsOuterDimensions[0] = d;
test.setAdditionalEvaluationPoints(m_evaluationPointsOuterDimensions);
first.fd = test.integrate();
m_evaluationPointsOuterDimensions[0] = e;
test.setAdditionalEvaluationPoints(m_evaluationPointsOuterDimensions);
first.fe = test.integrate();
m_evaluationPointsOuterDimensions[0] = f;
test.setAdditionalEvaluationPoints(m_evaluationPointsOuterDimensions);
first.ff = test.integrate();
m_evaluationPointsOuterDimensions[0] = g;
test.setAdditionalEvaluationPoints(m_evaluationPointsOuterDimensions);
first.fg = test.integrate();
m_evaluationPointsOuterDimensions[0] = h;
test.setAdditionalEvaluationPoints(m_evaluationPointsOuterDimensions);
first.fh = test.integrate();
m_evaluationPointsOuterDimensions[0] = i;
test.setAdditionalEvaluationPoints(m_evaluationPointsOuterDimensions);
first.fi = test.integrate();
}
else
{
m_evaluationPointsOuterDimensions.push_front(a);
first.fa = m_integrand(m_evaluationPointsOuterDimensions);
m_evaluationPointsOuterDimensions[0] = b;
first.fb = m_integrand(m_evaluationPointsOuterDimensions);
m_evaluationPointsOuterDimensions[0] = c;
first.fc = m_integrand(m_evaluationPointsOuterDimensions);
m_evaluationPointsOuterDimensions[0] = d;
first.fd = m_integrand(m_evaluationPointsOuterDimensions);
m_evaluationPointsOuterDimensions[0] = e;
first.fe = m_integrand(m_evaluationPointsOuterDimensions);
m_evaluationPointsOuterDimensions[0] = f;
first.ff = m_integrand(m_evaluationPointsOuterDimensions);
m_evaluationPointsOuterDimensions[0] = g;
first.fg = m_integrand(m_evaluationPointsOuterDimensions);
m_evaluationPointsOuterDimensions[0] = h;
first.fh = m_integrand(m_evaluationPointsOuterDimensions);
m_evaluationPointsOuterDimensions[0] = i;
first.fi = m_integrand(m_evaluationPointsOuterDimensions);
}
std::size_t size = first.fa.size();
double prefactor = (b - a) / 180.0;
first.S.reserve(size);
first.Sleft.reserve(size);
first.Sright.reserve(size);
for (std::size_t i = 0; i < size; i++)
{
first.S.emplace_back(2.0 * prefactor * (7.0 * first.fa[i] + 32.0 * first.fd[i] + 12.0 * first.ff[i] +
32.0 * first.fh[i] + 7.0 * first.fb[i]));
first.Sleft.emplace_back(prefactor * (7.0 * first.fa[i] + 32.0 * first.fc[i] + 12.0 * first.fd[i] +
32.0 * first.fe[i] + 7.0 * first.ff[i]));
first.Sright.emplace_back(prefactor * (7.0 * first.ff[i] + 32.0 * first.fg[i] + 12.0 * first.fh[i] +
32.0 * first.fi[i] + 7.0 * first.fb[i]));
first.error = std::max(first.error, std::abs(63.0 * (first.Sleft[i] + first.Sright[i] - first.S[i])));
}
first.lowerlimit = m_lowerBound;
first.upperlimit = m_upperBound;
first.epsilon = m_epsilon;
std::priority_queue<BooleHelper> myqueue;
myqueue.emplace(first);
while (myqueue.size() < m_maximumDivisions)
{
const BooleHelper& mostError = myqueue.top();
if (mostError.error < mostError.epsilon)
break;
// std::cout << mostError.error << " " << mostError.epsilon << std::endl;
// std::cout << "mostError: " << mostError.S[0] << " " << mostError.Sleft[0] << " " << mostError.Sright[0] << " "
// << mostError.error << std::endl;
BooleHelper element1, element2;
splitElement(mostError,element1,element2);
// std::cout << "element1: " << element1.S[0] << " " << element1.Sleft[0] << " " << element1.Sright[0] << " " <<
// element1.error << " " << element1.epsilon << " " << myqueue.size() << std::endl;
// std::cout << "element2: " << element2.S[0] << " " << element2.Sleft[0] << " " << element2.Sright[0] << " " <<
// element2.error << " " << element1.epsilon << std::endl;
myqueue.pop();
myqueue.emplace(std::move(element1));
myqueue.emplace(std::move(element2));
}
return sumPieces(myqueue);
}
AdaptiveBoole::AdaptiveBoole() : m_p{new BooleImpl{}} {}
AdaptiveBoole::AdaptiveBoole(const AdaptiveBoole &other) : m_p(other.m_p->clone()) {}
AdaptiveBoole &AdaptiveBoole::operator=(const AdaptiveBoole &other)
{
m_p = move(other.m_p->clone());
return *this;
}
AdaptiveBoole::AdaptiveBoole(AdaptiveBoole &&other)
{
m_p = move(other.m_p);
other.m_p = NULL;
}
AdaptiveBoole &AdaptiveBoole::operator=(AdaptiveBoole &&other)
{
if (m_p != other.m_p)
{
m_p = move(other.m_p);
other.m_p = NULL;
}
return *this;
}
void
AdaptiveBoole::setFunction(const std::function<std::vector<double>(std::deque<double> &evaluationPoints)> &integrand)
{
m_p->m_integrand = integrand;
}
void AdaptiveBoole::setInterval(const std::vector<double> &lowerBounds, const std::vector<double> &upperBounds)
{
assert(lowerBounds.size() == upperBounds.size());
m_p->m_lowerBound = lowerBounds.back();
m_p->m_upperBound = upperBounds.back();
if (lowerBounds.size() > 1)
{
m_p->m_lowerBoundsInnerDimensions = lowerBounds;
m_p->m_lowerBoundsInnerDimensions.pop_back();
m_p->m_upperBoundsInnerDimensions = upperBounds;
m_p->m_upperBoundsInnerDimensions.pop_back();
}
}
void AdaptiveBoole::setPrecision(double epsilon) { m_p->m_epsilon = epsilon; }
void AdaptiveBoole::setMaximumDivisions(int maximumDivisions) { m_p->m_maximumDivisions = maximumDivisions; }
std::vector<double> AdaptiveBoole::integrate() { return m_p->integrate(); }
void AdaptiveBoole::setAdditionalEvaluationPoints(const std::deque<double> &evaluationPoints)
{
m_p->m_evaluationPointsOuterDimensions = evaluationPoints;
}
AdaptiveBoole::~AdaptiveBoole(){};
<|endoftext|> |
<commit_before>/* Sirikata
* TextureAtlasFilter.cpp
*
* Copyright (c) 2011, Ewen Cheslack-Postava
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are
* met:
* * Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* * Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in
* the documentation and/or other materials provided with the
* distribution.
* * Neither the name of Sirikata nor the names of its contributors may
* be used to endorse or promote products derived from this software
* without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS
* IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED
* TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A
* PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER
* OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
* EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
* PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
* PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
* LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
* NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
#include "TextureAtlasFilter.hpp"
#include "FreeImage.hpp"
#include <nvtt/nvtt.h>
namespace Sirikata {
namespace Mesh {
namespace {
struct Rect;
struct Region;
// Rect is used to define the size in pixels of a rectangular region
struct Rect {
int32 min_x;
int32 min_y;
int32 max_x;
int32 max_y;
int32 width() const { return max_x - min_x + 1; }
int32 height() const { return max_y - min_y + 1; }
int32 x() const { return min_x; }
int32 y() const { return min_y; }
static Rect fromBaseOffset(int32 _min_x, int32 _min_y, int32 _width, int32 _height) {
Rect ret;
ret.min_x = _min_x;
ret.min_y = _min_y;
ret.max_x = _min_x + _width - 1;
ret.max_y = _min_y + _height - 1;
return ret;
}
static Rect fromBounds(int32 _min_x, int32 _min_y, int32 _max_x, int32 _max_y) {
Rect ret;
ret.min_x = _min_x;
ret.min_y = _min_y;
ret.max_x = _max_x;
ret.max_y = _max_y;
return ret;
}
Region region(const Rect& subrect);
Rect region(const Region& subreg);
};
// Region is used to define a region of a Rect. It's values are always in the
// range 0 to 1
struct Region {
float min_x;
float min_y;
float max_x;
float max_y;
static Region fromBaseOffset(float _min_x, float _min_y, float _width, float _height) {
Region ret;
ret.min_x = _min_x;
ret.min_y = _min_y;
ret.max_x = _min_x + _width;
ret.max_y = _min_y + _height;
return ret;
}
static Region fromBounds(float _min_x, float _min_y, float _max_x, float _max_y) {
Region ret;
ret.min_x = _min_x;
ret.min_y = _min_y;
ret.max_x = _max_x;
ret.max_y = _max_y;
return ret;
}
float width() const { return max_x - min_x; }
float height() const { return max_y - min_y; }
float x() const { return min_x; }
float y() const { return min_y; }
// Convert a (u,v) in this region's coordinates (u and v between 0 and 1) to
// parent coordinates.
void convert(float u, float v, float* u_out, float* v_out) {
float u_o = min_x + u * width();
float v_o = min_y + v * height();
*u_out = min_x + u * width();
*v_out = min_y + v * height();
}
};
Region Rect::region(const Rect& subrect) {
return Region::fromBounds(
(subrect.min_x/(float)width()), (subrect.min_y/(float)height()),
((subrect.max_x+1)/(float)width()), ((subrect.max_y+1)/(float)height())
);
}
Rect Rect::region(const Region& subreg) {
return Rect::fromBaseOffset(
(int32)(subreg.min_x * width()), (int32)(subreg.min_y * height()),
(int32)(subreg.width() * width()), (int32)(subreg.height() * height())
);
}
// Track some information about the texture that we need as we process it.
struct TexInfo {
String url;
Rect orig_size;
FIBITMAP* image;
Region atlas_region;
};
// Compute a hash value for texture sets in a Meshdata.
int TextureSetHash(MeshdataPtr md, int sub_mesh_idx, int tex_set_idx) {
return (tex_set_idx * md->geometry.size()) + sub_mesh_idx;
}
} // namespace
TextureAtlasFilter::TextureAtlasFilter(const String& args) {
}
MeshdataPtr TextureAtlasFilter::apply(MeshdataPtr md) {
// Currently we use a very simple approach: take all textures and
// tile them into equal size regions, tiling in 2D.
typedef std::map<String, TexInfo> TexInfoMap;
TexInfoMap tex_info;
// We only know how to handle local files
if (md->uri.size() < 7 || md->uri.substr(0, 7) != "file://") return md;
String uri_dir = md->uri.substr(7);
size_t slash_pos = uri_dir.rfind("/");
if (slash_pos == std::string::npos || slash_pos == uri_dir.size()-1)
uri_dir = "./";
else
uri_dir = uri_dir.substr(0, slash_pos+1);
// If the same texUVs in a SubMeshGeometry are referenced by instances with
// different materials, then this code doesn't know how to handle them (we'd
// probably have to duplicate texUVs, and in doing so, decide whether the
// memory increase is worth it).
std::map<int, int> tex_set_materials; // Unique tex coord hash -> material
// idx
{
// We need to run through all instances and look for conflicts. A
// texture coordinate set is uniquely identified by SubMeshGeometry
// index and the index in SubMeshGeometry::texUVs. Since we know the
// number of SubMeshGeometries, we use
// (tex coord index * num sub mesh geometries) + sub mesh geo index
// to generate a unique index. Many instances may map to one of these
// and we just want to check that no two instances use different textures
Meshdata::GeometryInstanceIterator geo_inst_it = md->getGeometryInstanceIterator();
uint32 geo_inst_idx;
Matrix4x4f pos_xform;
bool conflicts = false;
while( geo_inst_it.next(&geo_inst_idx, &pos_xform) ) {
GeometryInstance& geo_inst = md->instances[geo_inst_idx];
int sub_mesh_idx = geo_inst.geometryIndex;
for(GeometryInstance::MaterialBindingMap::iterator mat_it = geo_inst.materialBindingMap.begin(); mat_it != geo_inst.materialBindingMap.end(); mat_it++) {
int texset_idx = mat_it->first;
int mat_idx = mat_it->second;
int tex_set_hash = TextureSetHash(md, sub_mesh_idx, texset_idx);
if (tex_set_materials.find(tex_set_hash) != tex_set_materials.end() &&
tex_set_materials[tex_set_hash] != mat_idx)
{
// Conflict, can't handle, pass on without any processing
SILOG(textureatlas, error, "[TEXTUREATLAS] Found two instances using different materials referencing the same geometry -- can't safely generate atlas.");
return md;
}
tex_set_materials[tex_set_hash] = mat_idx;
}
}
}
// First compute some stats.
for(uint32 tex_i = 0; tex_i < md->textures.size(); tex_i++) {
String tex_url = md->textures[tex_i];
String texfile = uri_dir + tex_url;
tex_info[tex_url] = TexInfo();
tex_info[tex_url].url = tex_url;
// Load the data from the original file
FIBITMAP* input_image = GenericLoader(texfile.c_str(), 0);
if (input_image == NULL) { // Couldn't figure out how to load it
tex_info[tex_url].image = NULL;
continue;
}
// Make sure we get the data in BGRA 8UB and properly packed
FIBITMAP* input_image_32 = FreeImage_ConvertTo32Bits(input_image);
FreeImage_Unload(input_image);
tex_info[tex_url].image = input_image_32;
int32 width = FreeImage_GetWidth(input_image_32);
int32 height = FreeImage_GetHeight(input_image_32);
tex_info[tex_url].orig_size = Rect::fromBaseOffset(0, 0, width, height);
}
// Select the block size and layout, create target image
int ntextures = tex_info.size();
int ntextures_side = (int)(sqrtf((float)ntextures) + 1.f);
// FIXME
uint32 atlas_element_width = 256, atlas_element_height = 256;
uint32 atlas_width = ntextures_side * atlas_element_width,
atlas_height = ntextures_side * atlas_element_height;
FIBITMAP* atlas = FreeImage_Allocate(atlas_width, atlas_height, 32);
// Scale images to desired size, copy data into the target image
int idx = 0;
Rect atlas_rect = Rect::fromBaseOffset(0, 0, atlas_width, atlas_height);
for(TexInfoMap::iterator tex_it = tex_info.begin(); tex_it != tex_info.end(); tex_it++) {
TexInfo& tex = tex_it->second;
// Resize
uint32 new_width = atlas_element_width, new_height = atlas_element_height; // FIXME
FIBITMAP* resized = FreeImage_Rescale(tex.image, new_width, new_height, FILTER_LANCZOS3);
// Copy into place
int x_idx = idx % ntextures_side;
int y_idx = idx / ntextures_side;
Rect tex_sub_rect = Rect::fromBaseOffset(
x_idx * atlas_element_width, y_idx * atlas_element_height,
atlas_element_width, atlas_element_height
);
tex.atlas_region = atlas_rect.region(tex_sub_rect);
FreeImage_Paste(atlas, resized, tex_sub_rect.min_x, tex_sub_rect.min_y, 256);
FreeImage_Unload(resized);
FreeImage_Unload(tex_it->second.image);
tex_it->second.image = NULL;
idx++;
}
// Generate the texture atlas
String atlas_url = uri_dir + "atlas.png";
FreeImage_Save(FIF_PNG, atlas, atlas_url.c_str());
FreeImage_Unload(atlas);
// Now we need to run through and fix up texture references and texture
// coordinates
// 1. Replace old textures with new one
TextureList orig_texture_list = md->textures;
md->textures.clear();
md->textures.push_back(atlas_url);
// 2. Update texture coordinates. Since we've stored texture set hash ->
// material indices, we can easily work from this to quickly iterate over
// items and transform the coordinates.
for(uint32 geo_idx = 0; geo_idx < md->geometry.size(); geo_idx++) {
// Each submesh has texUVs that need updating
SubMeshGeometry& submesh = md->geometry[geo_idx];
// We need to modify each texture coordinate set in this geometry. We
// put this as the outer loop so we replace the entire uv set with a
// new, filtered copy so we make sure we don't double-transform any of
// the coordinates.
for(int tex_set_idx = 0; tex_set_idx < submesh.texUVs.size(); tex_set_idx++) {
SubMeshGeometry::TextureSet& tex_set = submesh.texUVs[tex_set_idx];
std::vector<float> new_uvs = tex_set.uvs;
// Each prim defines a material mapping, so we need to split the
// texture coordinates up by prim.
for(int prim_idx = 0; prim_idx < submesh.primitives.size(); prim_idx++) {
SubMeshGeometry::Primitive& prim = submesh.primitives[prim_idx];
int mat_id = prim.materialId;
int tex_set_hash = TextureSetHash(md, geo_idx, mat_id);
// We stored up the correct material index to find it in the
// Meshdata in the tex_set_materials when we were sanity checking
// that there were no conflicts.
int mat_idx = tex_set_materials[tex_set_hash];
// Finally, having extracted all the material mapping info, we
// can loop through referenced indices and transform them.
MaterialEffectInfo& mat = md->materials[mat_idx];
// Do transformation for each texture that has a URI. Some may
// be duplicates, some may not have a URI, but doing them all
// ensures we catch everything.
for(int mat_tex_idx = 0; mat_tex_idx < mat.textures.size(); mat_tex_idx++) {
MaterialEffectInfo::Texture& real_tex = mat.textures[mat_tex_idx];
if (tex_info.find(real_tex.uri) == tex_info.end()) continue;
TexInfo& final_tex_info = tex_info[real_tex.uri];
for(int index_idx = 0; index_idx < prim.indices.size(); index_idx++) {
int index = prim.indices[index_idx];
float new_u, new_v;
assert(tex_set.stride >= 2);
final_tex_info.atlas_region.convert(
tex_set.uvs[index * tex_set.stride],
tex_set.uvs[index * tex_set.stride + 1],
&new_u, &new_v);
new_uvs[ index * tex_set.stride ] = new_u;
new_uvs[ index * tex_set.stride + 1 ] = new_v;
}
}
}
tex_set.uvs = new_uvs;
}
}
// 3. Replace references in materials to old URI's with new one
for(MaterialEffectInfoList::iterator mat_it = md->materials.begin(); mat_it != md->materials.end(); mat_it++) {
MaterialEffectInfo& mat_info = *mat_it;
for(MaterialEffectInfo::TextureList::iterator tex_it = mat_info.textures.begin(); tex_it != mat_info.textures.end(); tex_it++) {
if (!tex_it->uri.empty())
tex_it->uri = atlas_url;
}
}
return md;
}
FilterDataPtr TextureAtlasFilter::apply(FilterDataPtr input) {
using namespace nvtt;
InitFreeImage();
MutableFilterDataPtr output(new FilterData());
for(FilterData::const_iterator mesh_it = input->begin(); mesh_it != input->end(); mesh_it++) {
MeshdataPtr mesh = *mesh_it;
MeshdataPtr ta_mesh = apply(mesh);
output->push_back(ta_mesh);
}
return output;
}
} // namespace Mesh
} // namespace Sirikata
<commit_msg>Fix handling of inverted v texture coordinates in TextureAtlasFilter, which was causing it to index into the wrong section of the texture atlas.<commit_after>/* Sirikata
* TextureAtlasFilter.cpp
*
* Copyright (c) 2011, Ewen Cheslack-Postava
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are
* met:
* * Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* * Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in
* the documentation and/or other materials provided with the
* distribution.
* * Neither the name of Sirikata nor the names of its contributors may
* be used to endorse or promote products derived from this software
* without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS
* IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED
* TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A
* PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER
* OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
* EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
* PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
* PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
* LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
* NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
#include "TextureAtlasFilter.hpp"
#include "FreeImage.hpp"
#include <nvtt/nvtt.h>
namespace Sirikata {
namespace Mesh {
namespace {
struct Rect;
struct Region;
// Rect is used to define the size in pixels of a rectangular region
struct Rect {
int32 min_x;
int32 min_y;
int32 max_x;
int32 max_y;
int32 width() const { return max_x - min_x + 1; }
int32 height() const { return max_y - min_y + 1; }
int32 x() const { return min_x; }
int32 y() const { return min_y; }
static Rect fromBaseOffset(int32 _min_x, int32 _min_y, int32 _width, int32 _height) {
Rect ret;
ret.min_x = _min_x;
ret.min_y = _min_y;
ret.max_x = _min_x + _width - 1;
ret.max_y = _min_y + _height - 1;
return ret;
}
static Rect fromBounds(int32 _min_x, int32 _min_y, int32 _max_x, int32 _max_y) {
Rect ret;
ret.min_x = _min_x;
ret.min_y = _min_y;
ret.max_x = _max_x;
ret.max_y = _max_y;
return ret;
}
Region region(const Rect& subrect);
Rect region(const Region& subreg);
};
// Region is used to define a region of a Rect. It's values are always in the
// range 0 to 1
struct Region {
float min_x;
float min_y;
float max_x;
float max_y;
static Region fromBaseOffset(float _min_x, float _min_y, float _width, float _height) {
Region ret;
ret.min_x = _min_x;
ret.min_y = _min_y;
ret.max_x = _min_x + _width;
ret.max_y = _min_y + _height;
return ret;
}
static Region fromBounds(float _min_x, float _min_y, float _max_x, float _max_y) {
Region ret;
ret.min_x = _min_x;
ret.min_y = _min_y;
ret.max_x = _max_x;
ret.max_y = _max_y;
return ret;
}
float width() const { return max_x - min_x; }
float height() const { return max_y - min_y; }
float x() const { return min_x; }
float y() const { return min_y; }
// Convert a (u,v) in this region's coordinates (u and v between 0 and 1) to
// parent coordinates.
void convert(float u, float v, float* u_out, float* v_out) {
float u_o = min_x + u * width();
float v_o = min_y + v * height();
*u_out = min_x + u * width();
*v_out = min_y + v * height();
}
};
Region Rect::region(const Rect& subrect) {
return Region::fromBounds(
(subrect.min_x/(float)width()), (subrect.min_y/(float)height()),
((subrect.max_x+1)/(float)width()), ((subrect.max_y+1)/(float)height())
);
}
Rect Rect::region(const Region& subreg) {
return Rect::fromBaseOffset(
(int32)(subreg.min_x * width()), (int32)(subreg.min_y * height()),
(int32)(subreg.width() * width()), (int32)(subreg.height() * height())
);
}
// Track some information about the texture that we need as we process it.
struct TexInfo {
String url;
Rect orig_size;
FIBITMAP* image;
Region atlas_region;
};
// Compute a hash value for texture sets in a Meshdata.
int TextureSetHash(MeshdataPtr md, int sub_mesh_idx, int tex_set_idx) {
return (tex_set_idx * md->geometry.size()) + sub_mesh_idx;
}
} // namespace
TextureAtlasFilter::TextureAtlasFilter(const String& args) {
}
MeshdataPtr TextureAtlasFilter::apply(MeshdataPtr md) {
// Currently we use a very simple approach: take all textures and
// tile them into equal size regions, tiling in 2D.
typedef std::map<String, TexInfo> TexInfoMap;
TexInfoMap tex_info;
// We only know how to handle local files
if (md->uri.size() < 7 || md->uri.substr(0, 7) != "file://") return md;
String uri_dir = md->uri.substr(7);
size_t slash_pos = uri_dir.rfind("/");
if (slash_pos == std::string::npos || slash_pos == uri_dir.size()-1)
uri_dir = "./";
else
uri_dir = uri_dir.substr(0, slash_pos+1);
// If the same texUVs in a SubMeshGeometry are referenced by instances with
// different materials, then this code doesn't know how to handle them (we'd
// probably have to duplicate texUVs, and in doing so, decide whether the
// memory increase is worth it).
std::map<int, int> tex_set_materials; // Unique tex coord hash -> material
// idx
{
// We need to run through all instances and look for conflicts. A
// texture coordinate set is uniquely identified by SubMeshGeometry
// index and the index in SubMeshGeometry::texUVs. Since we know the
// number of SubMeshGeometries, we use
// (tex coord index * num sub mesh geometries) + sub mesh geo index
// to generate a unique index. Many instances may map to one of these
// and we just want to check that no two instances use different textures
Meshdata::GeometryInstanceIterator geo_inst_it = md->getGeometryInstanceIterator();
uint32 geo_inst_idx;
Matrix4x4f pos_xform;
bool conflicts = false;
while( geo_inst_it.next(&geo_inst_idx, &pos_xform) ) {
GeometryInstance& geo_inst = md->instances[geo_inst_idx];
int sub_mesh_idx = geo_inst.geometryIndex;
for(GeometryInstance::MaterialBindingMap::iterator mat_it = geo_inst.materialBindingMap.begin(); mat_it != geo_inst.materialBindingMap.end(); mat_it++) {
int texset_idx = mat_it->first;
int mat_idx = mat_it->second;
int tex_set_hash = TextureSetHash(md, sub_mesh_idx, texset_idx);
if (tex_set_materials.find(tex_set_hash) != tex_set_materials.end() &&
tex_set_materials[tex_set_hash] != mat_idx)
{
// Conflict, can't handle, pass on without any processing
SILOG(textureatlas, error, "[TEXTUREATLAS] Found two instances using different materials referencing the same geometry -- can't safely generate atlas.");
return md;
}
tex_set_materials[tex_set_hash] = mat_idx;
}
}
}
// First compute some stats.
for(uint32 tex_i = 0; tex_i < md->textures.size(); tex_i++) {
String tex_url = md->textures[tex_i];
String texfile = uri_dir + tex_url;
tex_info[tex_url] = TexInfo();
tex_info[tex_url].url = tex_url;
// Load the data from the original file
FIBITMAP* input_image = GenericLoader(texfile.c_str(), 0);
if (input_image == NULL) { // Couldn't figure out how to load it
tex_info[tex_url].image = NULL;
continue;
}
// Make sure we get the data in BGRA 8UB and properly packed
FIBITMAP* input_image_32 = FreeImage_ConvertTo32Bits(input_image);
FreeImage_Unload(input_image);
tex_info[tex_url].image = input_image_32;
int32 width = FreeImage_GetWidth(input_image_32);
int32 height = FreeImage_GetHeight(input_image_32);
tex_info[tex_url].orig_size = Rect::fromBaseOffset(0, 0, width, height);
}
// Select the block size and layout, create target image
int ntextures = tex_info.size();
int ntextures_side = (int)(sqrtf((float)ntextures) + 1.f);
// FIXME
uint32 atlas_element_width = 256, atlas_element_height = 256;
uint32 atlas_width = ntextures_side * atlas_element_width,
atlas_height = ntextures_side * atlas_element_height;
FIBITMAP* atlas = FreeImage_Allocate(atlas_width, atlas_height, 32);
// Scale images to desired size, copy data into the target image
int idx = 0;
Rect atlas_rect = Rect::fromBaseOffset(0, 0, atlas_width, atlas_height);
for(TexInfoMap::iterator tex_it = tex_info.begin(); tex_it != tex_info.end(); tex_it++) {
TexInfo& tex = tex_it->second;
// Resize
uint32 new_width = atlas_element_width, new_height = atlas_element_height; // FIXME
FIBITMAP* resized = FreeImage_Rescale(tex.image, new_width, new_height, FILTER_LANCZOS3);
// Copy into place
int x_idx = idx % ntextures_side;
int y_idx = idx / ntextures_side;
Rect tex_sub_rect = Rect::fromBaseOffset(
x_idx * atlas_element_width, y_idx * atlas_element_height,
atlas_element_width, atlas_element_height
);
tex.atlas_region = atlas_rect.region(tex_sub_rect);
FreeImage_Paste(atlas, resized, tex_sub_rect.min_x, tex_sub_rect.min_y, 256);
FreeImage_Unload(resized);
FreeImage_Unload(tex_it->second.image);
tex_it->second.image = NULL;
idx++;
}
// Generate the texture atlas
String atlas_url = uri_dir + "atlas.png";
FreeImage_Save(FIF_PNG, atlas, atlas_url.c_str());
FreeImage_Unload(atlas);
// Now we need to run through and fix up texture references and texture
// coordinates
// 1. Replace old textures with new one
TextureList orig_texture_list = md->textures;
md->textures.clear();
md->textures.push_back(atlas_url);
// 2. Update texture coordinates. Since we've stored texture set hash ->
// material indices, we can easily work from this to quickly iterate over
// items and transform the coordinates.
for(uint32 geo_idx = 0; geo_idx < md->geometry.size(); geo_idx++) {
// Each submesh has texUVs that need updating
SubMeshGeometry& submesh = md->geometry[geo_idx];
// We need to modify each texture coordinate set in this geometry. We
// put this as the outer loop so we replace the entire uv set with a
// new, filtered copy so we make sure we don't double-transform any of
// the coordinates.
for(int tex_set_idx = 0; tex_set_idx < submesh.texUVs.size(); tex_set_idx++) {
SubMeshGeometry::TextureSet& tex_set = submesh.texUVs[tex_set_idx];
std::vector<float> new_uvs = tex_set.uvs;
// Each prim defines a material mapping, so we need to split the
// texture coordinates up by prim.
for(int prim_idx = 0; prim_idx < submesh.primitives.size(); prim_idx++) {
SubMeshGeometry::Primitive& prim = submesh.primitives[prim_idx];
int mat_id = prim.materialId;
int tex_set_hash = TextureSetHash(md, geo_idx, mat_id);
// We stored up the correct material index to find it in the
// Meshdata in the tex_set_materials when we were sanity checking
// that there were no conflicts.
int mat_idx = tex_set_materials[tex_set_hash];
// Finally, having extracted all the material mapping info, we
// can loop through referenced indices and transform them.
MaterialEffectInfo& mat = md->materials[mat_idx];
// Do transformation for each texture that has a URI. Some may
// be duplicates, some may not have a URI, but doing them all
// ensures we catch everything.
for(int mat_tex_idx = 0; mat_tex_idx < mat.textures.size(); mat_tex_idx++) {
MaterialEffectInfo::Texture& real_tex = mat.textures[mat_tex_idx];
if (tex_info.find(real_tex.uri) == tex_info.end()) continue;
TexInfo& final_tex_info = tex_info[real_tex.uri];
for(int index_idx = 0; index_idx < prim.indices.size(); index_idx++) {
int index = prim.indices[index_idx];
float new_u, new_v;
assert(tex_set.stride >= 2);
final_tex_info.atlas_region.convert(
tex_set.uvs[index * tex_set.stride],
(1.f-tex_set.uvs[index * tex_set.stride + 1]), // inverted
// v coords
&new_u, &new_v);
new_uvs[ index * tex_set.stride ] = new_u;
new_uvs[ index * tex_set.stride + 1 ] = 1.f - new_v; // inverted
// v coords
}
}
}
tex_set.uvs = new_uvs;
}
}
// 3. Replace references in materials to old URI's with new one
for(MaterialEffectInfoList::iterator mat_it = md->materials.begin(); mat_it != md->materials.end(); mat_it++) {
MaterialEffectInfo& mat_info = *mat_it;
for(MaterialEffectInfo::TextureList::iterator tex_it = mat_info.textures.begin(); tex_it != mat_info.textures.end(); tex_it++) {
if (!tex_it->uri.empty())
tex_it->uri = atlas_url;
}
}
return md;
}
FilterDataPtr TextureAtlasFilter::apply(FilterDataPtr input) {
using namespace nvtt;
InitFreeImage();
MutableFilterDataPtr output(new FilterData());
for(FilterData::const_iterator mesh_it = input->begin(); mesh_it != input->end(); mesh_it++) {
MeshdataPtr mesh = *mesh_it;
MeshdataPtr ta_mesh = apply(mesh);
output->push_back(ta_mesh);
}
return output;
}
} // namespace Mesh
} // namespace Sirikata
<|endoftext|> |
<commit_before>/* Sirikata Graphical Object Host
* Camera.cpp
*
* Copyright (c) 2009, Patrick Reiter Horn
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are
* met:
* * Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* * Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in
* the documentation and/or other materials provided with the
* distribution.
* * Neither the name of Sirikata nor the names of its contributors may
* be used to endorse or promote products derived from this software
* without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS
* IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED
* TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A
* PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER
* OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
* EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
* PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
* PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
* LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
* NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
#include "ProxyCamera.hpp"
#include "ProxyEntity.hpp"
#include <sirikata/ogre/OgreRenderer.hpp>
#include <sirikata/core/options/Options.hpp>
namespace Sirikata {
namespace Graphics {
ProxyCamera::ProxyCamera(OgreRenderer *scene, ProxyEntity* follow)
: Camera(scene, ogreCameraName(follow->id())),
mFollowing(follow)
{
}
ProxyCamera::~ProxyCamera() {
}
Vector3d ProxyCamera::getGoalPosition() {
return mFollowing->getProxyPtr()->getPosition();
}
Quaternion ProxyCamera::getGoalOrientation() {
return mFollowing->getProxyPtr()->getOrientation();
}
BoundingSphere3f ProxyCamera::getGoalBounds() {
return mFollowing->getProxyPtr()->getBounds();
}
void ProxyCamera::setMode(Mode m) {
Camera::setMode(m);
mFollowing->setVisible( mMode == FirstPerson ? false : true );
}
ProxyEntity* ProxyCamera::following() const {
return mFollowing;
}
std::string ProxyCamera::ogreCameraName(const String& ref) {
return "Camera:"+ref;
}
}
}
<commit_msg>Fix ProxyCamera's goal position and orientation to use the target Entity's current position rather than the proxy's starting position (and orientation).<commit_after>/* Sirikata Graphical Object Host
* Camera.cpp
*
* Copyright (c) 2009, Patrick Reiter Horn
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are
* met:
* * Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* * Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in
* the documentation and/or other materials provided with the
* distribution.
* * Neither the name of Sirikata nor the names of its contributors may
* be used to endorse or promote products derived from this software
* without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS
* IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED
* TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A
* PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER
* OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
* EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
* PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
* PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
* LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
* NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
#include "ProxyCamera.hpp"
#include "ProxyEntity.hpp"
#include <sirikata/ogre/OgreRenderer.hpp>
#include <sirikata/core/options/Options.hpp>
namespace Sirikata {
namespace Graphics {
ProxyCamera::ProxyCamera(OgreRenderer *scene, ProxyEntity* follow)
: Camera(scene, ogreCameraName(follow->id())),
mFollowing(follow)
{
}
ProxyCamera::~ProxyCamera() {
}
Vector3d ProxyCamera::getGoalPosition() {
return mFollowing->getOgrePosition();
}
Quaternion ProxyCamera::getGoalOrientation() {
return mFollowing->getOgreOrientation();
}
BoundingSphere3f ProxyCamera::getGoalBounds() {
return mFollowing->getProxyPtr()->getBounds();
}
void ProxyCamera::setMode(Mode m) {
Camera::setMode(m);
mFollowing->setVisible( mMode == FirstPerson ? false : true );
}
ProxyEntity* ProxyCamera::following() const {
return mFollowing;
}
std::string ProxyCamera::ogreCameraName(const String& ref) {
return "Camera:"+ref;
}
}
}
<|endoftext|> |
<commit_before>/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */
/*
* This file is part of the LibreOffice project.
*
* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/.
*
* This file incorporates work covered by the following license notice:
*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed
* with this work for additional information regarding copyright
* ownership. The ASF 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 .
*/
#if defined(WNT)
#include <windows.h>
#endif
#include <osl/thread.h>
#include <osl/file.hxx>
#include <tools/debug.hxx>
#include <tools/urlobj.hxx>
#include <i18nlangtag/languagetag.hxx>
#include <i18nlangtag/mslangid.hxx>
#include <unotools/lingucfg.hxx>
#include <unotools/pathoptions.hxx>
#include <rtl/ustring.hxx>
#include <rtl/string.hxx>
#include <rtl/tencinfo.h>
#include <linguistic/misc.hxx>
#include <set>
#include <vector>
#include <string.h>
#include <lingutil.hxx>
#include <sal/macros.h>
using ::com::sun::star::lang::Locale;
using namespace ::com::sun::star;
#if defined(WNT)
OString Win_GetShortPathName( const OUString &rLongPathName )
{
OString aRes;
sal_Unicode aShortBuffer[1024] = {0};
sal_Int32 nShortBufSize = SAL_N_ELEMENTS( aShortBuffer );
// use the version of 'GetShortPathName' that can deal with Unicode...
sal_Int32 nShortLen = GetShortPathNameW(
reinterpret_cast<LPCWSTR>( rLongPathName.getStr() ),
reinterpret_cast<LPWSTR>( aShortBuffer ),
nShortBufSize );
if (nShortLen < nShortBufSize) // conversion successful?
aRes = OString( OU2ENC( OUString( aShortBuffer, nShortLen ), osl_getThreadTextEncoding()) );
else
OSL_FAIL( "Win_GetShortPathName: buffer to short" );
return aRes;
}
#endif //defined(WNT)
//////////////////////////////////////////////////////////////////////
// build list of old style diuctionaries (not as extensions) to use.
// User installed dictionaries (the ones residing in the user paths)
// will get precedence over system installed ones for the same language.
std::vector< SvtLinguConfigDictionaryEntry > GetOldStyleDics( const char *pDicType )
{
std::vector< SvtLinguConfigDictionaryEntry > aRes;
if (!pDicType)
return aRes;
OUString aFormatName;
String aDicExtension;
#ifdef SYSTEM_DICTS
OUString aSystemDir;
OUString aSystemPrefix;
OUString aSystemSuffix;
#endif
if (strcmp( pDicType, "DICT" ) == 0)
{
aFormatName = "DICT_SPELL";
aDicExtension = ".dic";
#ifdef SYSTEM_DICTS
aSystemDir = DICT_SYSTEM_DIR;
aSystemSuffix = aDicExtension;
#endif
}
else if (strcmp( pDicType, "HYPH" ) == 0)
{
aFormatName = "DICT_HYPH";
aDicExtension = ".dic";
#ifdef SYSTEM_DICTS
aSystemDir = HYPH_SYSTEM_DIR;
aSystemPrefix = "hyph_";
aSystemSuffix = aDicExtension;
#endif
}
else if (strcmp( pDicType, "THES" ) == 0)
{
aFormatName = "DICT_THES";
aDicExtension = ".dat";
#ifdef SYSTEM_DICTS
aSystemDir = THES_SYSTEM_DIR;
aSystemPrefix = "th_";
aSystemSuffix = "_v2.dat";
#endif
}
if (aFormatName.isEmpty() || aDicExtension.Len() == 0)
return aRes;
#ifdef SYSTEM_DICTS
osl::Directory aSystemDicts(aSystemDir);
if (aSystemDicts.open() == osl::FileBase::E_None)
{
// set of languages to remember the language where it is already
// decided to make use of the dictionary.
std::set< OUString > aDicLangInUse;
osl::DirectoryItem aItem;
osl::FileStatus aFileStatus(osl_FileStatus_Mask_FileURL);
while (aSystemDicts.getNextItem(aItem) == osl::FileBase::E_None)
{
aItem.getFileStatus(aFileStatus);
OUString sPath = aFileStatus.getFileURL();
if (sPath.lastIndexOf(aSystemSuffix) == sPath.getLength()-aSystemSuffix.getLength())
{
sal_Int32 nStartIndex = sPath.lastIndexOf(sal_Unicode('/')) + 1;
if (!sPath.match(aSystemPrefix, nStartIndex))
continue;
OUString sChunk = sPath.copy(nStartIndex + aSystemPrefix.getLength(),
sPath.getLength() - aSystemSuffix.getLength() -
nStartIndex - aSystemPrefix.getLength());
if (sChunk.isEmpty())
continue;
// We prefer (now) to use language tags.
// Avoid feeding in the older LANG_REGION scheme to the BCP47
// ctor as that triggers use of liblangtag and initializes its
// database which we do not want during startup. Convert
// instead.
sal_Int32 nPos;
if (sChunk.indexOf('-') < 0 && ((nPos = sChunk.indexOf('_')) > 0))
sChunk = sChunk.replaceAt( nPos, 1, OUString('-'));
LanguageTag aLangTag(sChunk, true);
if (!aLangTag.isValidBcp47())
continue;
// Thus we first get the language of the dictionary
OUString aLocaleName(aLangTag.getBcp47());
if (aDicLangInUse.count(aLocaleName) == 0)
{
// remember the new language in use
aDicLangInUse.insert(aLocaleName);
// add the dictionary to the resulting vector
SvtLinguConfigDictionaryEntry aDicEntry;
aDicEntry.aLocations.realloc(1);
aDicEntry.aLocaleNames.realloc(1);
aDicEntry.aLocations[0] = sPath;
aDicEntry.aFormatName = aFormatName;
aDicEntry.aLocaleNames[0] = aLocaleName;
aRes.push_back( aDicEntry );
}
}
}
}
#endif
return aRes;
}
void MergeNewStyleDicsAndOldStyleDics(
std::list< SvtLinguConfigDictionaryEntry > &rNewStyleDics,
const std::vector< SvtLinguConfigDictionaryEntry > &rOldStyleDics )
{
// get list of languages supported by new style dictionaries
std::set< LanguageType > aNewStyleLanguages;
std::list< SvtLinguConfigDictionaryEntry >::const_iterator aIt;
for (aIt = rNewStyleDics.begin() ; aIt != rNewStyleDics.end(); ++aIt)
{
const uno::Sequence< OUString > aLocaleNames( aIt->aLocaleNames );
sal_Int32 nLocaleNames = aLocaleNames.getLength();
for (sal_Int32 k = 0; k < nLocaleNames; ++k)
{
LanguageType nLang = LanguageTag::convertToLanguageType( aLocaleNames[k] );
aNewStyleLanguages.insert( nLang );
}
}
// now check all old style dictionaries if they will add a not yet
// added language. If so add them to the resulting vector
std::vector< SvtLinguConfigDictionaryEntry >::const_iterator aIt2;
for (aIt2 = rOldStyleDics.begin(); aIt2 != rOldStyleDics.end(); ++aIt2)
{
sal_Int32 nOldStyleDics = aIt2->aLocaleNames.getLength();
// old style dics should only have one language listed...
DBG_ASSERT( nOldStyleDics, "old style dictionary with more then one language found!");
if (nOldStyleDics > 0)
{
LanguageType nLang = LanguageTag::convertToLanguageType( aIt2->aLocaleNames[0] );
if (nLang == LANGUAGE_DONTKNOW || linguistic::LinguIsUnspecified( nLang))
{
OSL_FAIL( "old style dictionary with invalid language found!" );
continue;
}
// language not yet added?
if (aNewStyleLanguages.count( nLang ) == 0)
rNewStyleDics.push_back( *aIt2 );
}
else
{
OSL_FAIL( "old style dictionary with no language found!" );
}
}
}
rtl_TextEncoding getTextEncodingFromCharset(const sal_Char* pCharset)
{
// default result: used to indicate that we failed to get the proper encoding
rtl_TextEncoding eRet = RTL_TEXTENCODING_DONTKNOW;
if (pCharset)
{
eRet = rtl_getTextEncodingFromMimeCharset(pCharset);
if (eRet == RTL_TEXTENCODING_DONTKNOW)
eRet = rtl_getTextEncodingFromUnixCharset(pCharset);
if (eRet == RTL_TEXTENCODING_DONTKNOW)
{
if (strcmp("ISCII-DEVANAGARI", pCharset) == 0)
eRet = RTL_TEXTENCODING_ISCII_DEVANAGARI;
}
}
return eRet;
}
//////////////////////////////////////////////////////////////////////
/* vim:set shiftwidth=4 softtabstop=4 expandtab: */
<commit_msg>was convertIsoStringToLanguage(), use convertToLanguageTypeWithFallback()<commit_after>/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */
/*
* This file is part of the LibreOffice project.
*
* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/.
*
* This file incorporates work covered by the following license notice:
*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed
* with this work for additional information regarding copyright
* ownership. The ASF 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 .
*/
#if defined(WNT)
#include <windows.h>
#endif
#include <osl/thread.h>
#include <osl/file.hxx>
#include <tools/debug.hxx>
#include <tools/urlobj.hxx>
#include <i18nlangtag/languagetag.hxx>
#include <i18nlangtag/mslangid.hxx>
#include <unotools/lingucfg.hxx>
#include <unotools/pathoptions.hxx>
#include <rtl/ustring.hxx>
#include <rtl/string.hxx>
#include <rtl/tencinfo.h>
#include <linguistic/misc.hxx>
#include <set>
#include <vector>
#include <string.h>
#include <lingutil.hxx>
#include <sal/macros.h>
using ::com::sun::star::lang::Locale;
using namespace ::com::sun::star;
#if defined(WNT)
OString Win_GetShortPathName( const OUString &rLongPathName )
{
OString aRes;
sal_Unicode aShortBuffer[1024] = {0};
sal_Int32 nShortBufSize = SAL_N_ELEMENTS( aShortBuffer );
// use the version of 'GetShortPathName' that can deal with Unicode...
sal_Int32 nShortLen = GetShortPathNameW(
reinterpret_cast<LPCWSTR>( rLongPathName.getStr() ),
reinterpret_cast<LPWSTR>( aShortBuffer ),
nShortBufSize );
if (nShortLen < nShortBufSize) // conversion successful?
aRes = OString( OU2ENC( OUString( aShortBuffer, nShortLen ), osl_getThreadTextEncoding()) );
else
OSL_FAIL( "Win_GetShortPathName: buffer to short" );
return aRes;
}
#endif //defined(WNT)
//////////////////////////////////////////////////////////////////////
// build list of old style diuctionaries (not as extensions) to use.
// User installed dictionaries (the ones residing in the user paths)
// will get precedence over system installed ones for the same language.
std::vector< SvtLinguConfigDictionaryEntry > GetOldStyleDics( const char *pDicType )
{
std::vector< SvtLinguConfigDictionaryEntry > aRes;
if (!pDicType)
return aRes;
OUString aFormatName;
String aDicExtension;
#ifdef SYSTEM_DICTS
OUString aSystemDir;
OUString aSystemPrefix;
OUString aSystemSuffix;
#endif
if (strcmp( pDicType, "DICT" ) == 0)
{
aFormatName = "DICT_SPELL";
aDicExtension = ".dic";
#ifdef SYSTEM_DICTS
aSystemDir = DICT_SYSTEM_DIR;
aSystemSuffix = aDicExtension;
#endif
}
else if (strcmp( pDicType, "HYPH" ) == 0)
{
aFormatName = "DICT_HYPH";
aDicExtension = ".dic";
#ifdef SYSTEM_DICTS
aSystemDir = HYPH_SYSTEM_DIR;
aSystemPrefix = "hyph_";
aSystemSuffix = aDicExtension;
#endif
}
else if (strcmp( pDicType, "THES" ) == 0)
{
aFormatName = "DICT_THES";
aDicExtension = ".dat";
#ifdef SYSTEM_DICTS
aSystemDir = THES_SYSTEM_DIR;
aSystemPrefix = "th_";
aSystemSuffix = "_v2.dat";
#endif
}
if (aFormatName.isEmpty() || aDicExtension.Len() == 0)
return aRes;
#ifdef SYSTEM_DICTS
osl::Directory aSystemDicts(aSystemDir);
if (aSystemDicts.open() == osl::FileBase::E_None)
{
// set of languages to remember the language where it is already
// decided to make use of the dictionary.
std::set< OUString > aDicLangInUse;
osl::DirectoryItem aItem;
osl::FileStatus aFileStatus(osl_FileStatus_Mask_FileURL);
while (aSystemDicts.getNextItem(aItem) == osl::FileBase::E_None)
{
aItem.getFileStatus(aFileStatus);
OUString sPath = aFileStatus.getFileURL();
if (sPath.lastIndexOf(aSystemSuffix) == sPath.getLength()-aSystemSuffix.getLength())
{
sal_Int32 nStartIndex = sPath.lastIndexOf(sal_Unicode('/')) + 1;
if (!sPath.match(aSystemPrefix, nStartIndex))
continue;
OUString sChunk = sPath.copy(nStartIndex + aSystemPrefix.getLength(),
sPath.getLength() - aSystemSuffix.getLength() -
nStartIndex - aSystemPrefix.getLength());
if (sChunk.isEmpty())
continue;
// We prefer (now) to use language tags.
// Avoid feeding in the older LANG_REGION scheme to the BCP47
// ctor as that triggers use of liblangtag and initializes its
// database which we do not want during startup. Convert
// instead.
sal_Int32 nPos;
if (sChunk.indexOf('-') < 0 && ((nPos = sChunk.indexOf('_')) > 0))
sChunk = sChunk.replaceAt( nPos, 1, OUString('-'));
LanguageTag aLangTag(sChunk, true);
if (!aLangTag.isValidBcp47())
continue;
// Thus we first get the language of the dictionary
OUString aLocaleName(aLangTag.getBcp47());
if (aDicLangInUse.count(aLocaleName) == 0)
{
// remember the new language in use
aDicLangInUse.insert(aLocaleName);
// add the dictionary to the resulting vector
SvtLinguConfigDictionaryEntry aDicEntry;
aDicEntry.aLocations.realloc(1);
aDicEntry.aLocaleNames.realloc(1);
aDicEntry.aLocations[0] = sPath;
aDicEntry.aFormatName = aFormatName;
aDicEntry.aLocaleNames[0] = aLocaleName;
aRes.push_back( aDicEntry );
}
}
}
}
#endif
return aRes;
}
void MergeNewStyleDicsAndOldStyleDics(
std::list< SvtLinguConfigDictionaryEntry > &rNewStyleDics,
const std::vector< SvtLinguConfigDictionaryEntry > &rOldStyleDics )
{
// get list of languages supported by new style dictionaries
std::set< LanguageType > aNewStyleLanguages;
std::list< SvtLinguConfigDictionaryEntry >::const_iterator aIt;
for (aIt = rNewStyleDics.begin() ; aIt != rNewStyleDics.end(); ++aIt)
{
const uno::Sequence< OUString > aLocaleNames( aIt->aLocaleNames );
sal_Int32 nLocaleNames = aLocaleNames.getLength();
for (sal_Int32 k = 0; k < nLocaleNames; ++k)
{
LanguageType nLang = LanguageTag::convertToLanguageTypeWithFallback( aLocaleNames[k] );
aNewStyleLanguages.insert( nLang );
}
}
// now check all old style dictionaries if they will add a not yet
// added language. If so add them to the resulting vector
std::vector< SvtLinguConfigDictionaryEntry >::const_iterator aIt2;
for (aIt2 = rOldStyleDics.begin(); aIt2 != rOldStyleDics.end(); ++aIt2)
{
sal_Int32 nOldStyleDics = aIt2->aLocaleNames.getLength();
// old style dics should only have one language listed...
DBG_ASSERT( nOldStyleDics, "old style dictionary with more then one language found!");
if (nOldStyleDics > 0)
{
LanguageType nLang = LanguageTag::convertToLanguageTypeWithFallback( aIt2->aLocaleNames[0] );
if (nLang == LANGUAGE_DONTKNOW || linguistic::LinguIsUnspecified( nLang))
{
OSL_FAIL( "old style dictionary with invalid language found!" );
continue;
}
// language not yet added?
if (aNewStyleLanguages.count( nLang ) == 0)
rNewStyleDics.push_back( *aIt2 );
}
else
{
OSL_FAIL( "old style dictionary with no language found!" );
}
}
}
rtl_TextEncoding getTextEncodingFromCharset(const sal_Char* pCharset)
{
// default result: used to indicate that we failed to get the proper encoding
rtl_TextEncoding eRet = RTL_TEXTENCODING_DONTKNOW;
if (pCharset)
{
eRet = rtl_getTextEncodingFromMimeCharset(pCharset);
if (eRet == RTL_TEXTENCODING_DONTKNOW)
eRet = rtl_getTextEncodingFromUnixCharset(pCharset);
if (eRet == RTL_TEXTENCODING_DONTKNOW)
{
if (strcmp("ISCII-DEVANAGARI", pCharset) == 0)
eRet = RTL_TEXTENCODING_ISCII_DEVANAGARI;
}
}
return eRet;
}
//////////////////////////////////////////////////////////////////////
/* vim:set shiftwidth=4 softtabstop=4 expandtab: */
<|endoftext|> |
<commit_before>////////////////////////////////////////////////////////////////////////////////
/// DISCLAIMER
///
/// Copyright 2014-2016 ArangoDB GmbH, Cologne, Germany
/// Copyright 2004-2014 triAGENS GmbH, Cologne, Germany
///
/// 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.
///
/// Copyright holder is ArangoDB GmbH, Cologne, Germany
///
/// @author Jan Steemann
////////////////////////////////////////////////////////////////////////////////
#include "MMFilesWalRecoveryFeature.h"
#include "Basics/Exceptions.h"
#include "Logger/Logger.h"
#include "ProgramOptions/ProgramOptions.h"
#include "ProgramOptions/Section.h"
#include "MMFiles/MMFilesLogfileManager.h"
using namespace arangodb;
using namespace arangodb::application_features;
using namespace arangodb::basics;
using namespace arangodb::options;
MMFilesWalRecoveryFeature::MMFilesWalRecoveryFeature(ApplicationServer* server)
: ApplicationFeature(server, "MMFilesWalRecovery") {
setOptional(true);
requiresElevatedPrivileges(false);
startsAfter("Database");
startsAfter("MMFilesLogfileManager");
startsAfter("MMFilesPersistentIndex");
onlyEnabledWith("MMFilesEngine");
onlyEnabledWith("MMFilesLogfileManager");
}
/// @brief run the recovery procedure
/// this is called after the logfiles have been scanned completely and
/// recovery state has been build. additionally, all databases have been
/// opened already so we can use collections
void MMFilesWalRecoveryFeature::start() {
MMFilesLogfileManager* logfileManager = ApplicationServer::getFeature<MMFilesLogfileManager>("MMFilesLogfileManager");
TRI_ASSERT(!logfileManager->allowWrites());
int res = logfileManager->runRecovery();
if (res != TRI_ERROR_NO_ERROR) {
LOG_TOPIC(FATAL, arangodb::Logger::FIXME) << "unable to finish WAL recovery: " << TRI_errno_string(res);
FATAL_ERROR_EXIT();
}
if (!logfileManager->open()) {
// if we got here, the MMFilesLogfileManager has already logged a fatal error and we can simply abort
FATAL_ERROR_EXIT();
}
}
<commit_msg>try to fix startup order<commit_after>////////////////////////////////////////////////////////////////////////////////
/// DISCLAIMER
///
/// Copyright 2014-2016 ArangoDB GmbH, Cologne, Germany
/// Copyright 2004-2014 triAGENS GmbH, Cologne, Germany
///
/// 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.
///
/// Copyright holder is ArangoDB GmbH, Cologne, Germany
///
/// @author Jan Steemann
////////////////////////////////////////////////////////////////////////////////
#include "MMFilesWalRecoveryFeature.h"
#include "Basics/Exceptions.h"
#include "Logger/Logger.h"
#include "ProgramOptions/ProgramOptions.h"
#include "ProgramOptions/Section.h"
#include "MMFiles/MMFilesLogfileManager.h"
using namespace arangodb;
using namespace arangodb::application_features;
using namespace arangodb::basics;
using namespace arangodb::options;
MMFilesWalRecoveryFeature::MMFilesWalRecoveryFeature(ApplicationServer* server)
: ApplicationFeature(server, "MMFilesWalRecovery") {
setOptional(true);
requiresElevatedPrivileges(false);
startsAfter("Database");
startsAfter("MMFilesLogfileManager");
startsAfter("MMFilesPersistentIndex");
startsAfter("Scheduler");
onlyEnabledWith("MMFilesEngine");
onlyEnabledWith("MMFilesLogfileManager");
}
/// @brief run the recovery procedure
/// this is called after the logfiles have been scanned completely and
/// recovery state has been build. additionally, all databases have been
/// opened already so we can use collections
void MMFilesWalRecoveryFeature::start() {
MMFilesLogfileManager* logfileManager = ApplicationServer::getFeature<MMFilesLogfileManager>("MMFilesLogfileManager");
TRI_ASSERT(!logfileManager->allowWrites());
int res = logfileManager->runRecovery();
if (res != TRI_ERROR_NO_ERROR) {
LOG_TOPIC(FATAL, arangodb::Logger::FIXME) << "unable to finish WAL recovery: " << TRI_errno_string(res);
FATAL_ERROR_EXIT();
}
if (!logfileManager->open()) {
// if we got here, the MMFilesLogfileManager has already logged a fatal error and we can simply abort
FATAL_ERROR_EXIT();
}
}
<|endoftext|> |
<commit_before>////////////////////////////////////////////////////////////////////////////////
/// DISCLAIMER
///
/// Copyright 2014-2017 ArangoDB GmbH, Cologne, Germany
/// Copyright 2004-2014 triAGENS GmbH, Cologne, Germany
///
/// 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.
///
/// Copyright holder is ArangoDB GmbH, Cologne, Germany
///
/// @author Michael Hackstein
////////////////////////////////////////////////////////////////////////////////
#include "RocksDBIndexFactory.h"
#include "Basics/StaticStrings.h"
#include "Basics/StringUtils.h"
#include "Basics/VelocyPackHelper.h"
#include "Indexes/Index.h"
#include "RocksDBEngine/RocksDBEdgeIndex.h"
#include "RocksDBEngine/RocksDBEngine.h"
#include "RocksDBEngine/RocksDBHashIndex.h"
#include "RocksDBEngine/RocksDBPersistentIndex.h"
#include "RocksDBEngine/RocksDBPrimaryIndex.h"
#include "RocksDBEngine/RocksDBSkiplistIndex.h"
#include "StorageEngine/EngineSelectorFeature.h"
#include "VocBase/ticks.h"
#include "VocBase/voc-types.h"
#include <velocypack/Builder.h>
#include <velocypack/Iterator.h>
#include <velocypack/Slice.h>
#include <velocypack/velocypack-aliases.h>
using namespace arangodb;
////////////////////////////////////////////////////////////////////////////////
/// @brief process the fields list and add them to the json
////////////////////////////////////////////////////////////////////////////////
static int ProcessIndexFields(VPackSlice const definition,
VPackBuilder& builder, int numFields,
bool create) {
TRI_ASSERT(builder.isOpenObject());
std::unordered_set<StringRef> fields;
try {
VPackSlice fieldsSlice = definition.get("fields");
builder.add(VPackValue("fields"));
builder.openArray();
if (fieldsSlice.isArray()) {
// "fields" is a list of fields
for (auto const& it : VPackArrayIterator(fieldsSlice)) {
if (!it.isString()) {
return TRI_ERROR_BAD_PARAMETER;
}
StringRef f(it);
if (f.empty() || (create && f == StaticStrings::IdString)) {
// accessing internal attributes is disallowed
return TRI_ERROR_BAD_PARAMETER;
}
if (fields.find(f) != fields.end()) {
// duplicate attribute name
return TRI_ERROR_BAD_PARAMETER;
}
fields.insert(f);
builder.add(it);
}
}
if (fields.empty() || (numFields > 0 && (int)fields.size() != numFields)) {
return TRI_ERROR_BAD_PARAMETER;
}
builder.close();
} catch (...) {
return TRI_ERROR_OUT_OF_MEMORY;
}
return TRI_ERROR_NO_ERROR;
}
////////////////////////////////////////////////////////////////////////////////
/// @brief process the unique flag and add it to the json
////////////////////////////////////////////////////////////////////////////////
static void ProcessIndexUniqueFlag(VPackSlice const definition,
VPackBuilder& builder) {
bool unique =
basics::VelocyPackHelper::getBooleanValue(definition, "unique", false);
builder.add("unique", VPackValue(unique));
}
////////////////////////////////////////////////////////////////////////////////
/// @brief process the sparse flag and add it to the json
////////////////////////////////////////////////////////////////////////////////
static void ProcessIndexSparseFlag(VPackSlice const definition,
VPackBuilder& builder, bool create) {
if (definition.hasKey("sparse")) {
bool sparseBool =
basics::VelocyPackHelper::getBooleanValue(definition, "sparse", false);
builder.add("sparse", VPackValue(sparseBool));
} else if (create) {
// not set. now add a default value
builder.add("sparse", VPackValue(false));
}
}
////////////////////////////////////////////////////////////////////////////////
/// @brief enhances the json of a hash index
////////////////////////////////////////////////////////////////////////////////
static int EnhanceJsonIndexHash(VPackSlice const definition,
VPackBuilder& builder, bool create) {
int res = ProcessIndexFields(definition, builder, 0, create);
if (res == TRI_ERROR_NO_ERROR) {
ProcessIndexSparseFlag(definition, builder, create);
ProcessIndexUniqueFlag(definition, builder);
}
return res;
}
////////////////////////////////////////////////////////////////////////////////
/// @brief enhances the json of a skiplist index
////////////////////////////////////////////////////////////////////////////////
static int EnhanceJsonIndexSkiplist(VPackSlice const definition,
VPackBuilder& builder, bool create) {
int res = ProcessIndexFields(definition, builder, 0, create);
if (res == TRI_ERROR_NO_ERROR) {
ProcessIndexSparseFlag(definition, builder, create);
ProcessIndexUniqueFlag(definition, builder);
}
return res;
}
////////////////////////////////////////////////////////////////////////////////
/// @brief enhances the json of a persistent index
////////////////////////////////////////////////////////////////////////////////
static int EnhanceJsonIndexPersistent(VPackSlice const definition,
VPackBuilder& builder, bool create) {
int res = ProcessIndexFields(definition, builder, 0, create);
if (res == TRI_ERROR_NO_ERROR) {
ProcessIndexSparseFlag(definition, builder, create);
ProcessIndexUniqueFlag(definition, builder);
}
return res;
}
////////////////////////////////////////////////////////////////////////////////
/// @brief process the geojson flag and add it to the json
////////////////////////////////////////////////////////////////////////////////
static void ProcessIndexGeoJsonFlag(VPackSlice const definition,
VPackBuilder& builder) {
bool geoJson =
basics::VelocyPackHelper::getBooleanValue(definition, "geoJson", false);
builder.add("geoJson", VPackValue(geoJson));
}
////////////////////////////////////////////////////////////////////////////////
/// @brief enhances the json of a geo1 index
////////////////////////////////////////////////////////////////////////////////
static int EnhanceJsonIndexGeo1(VPackSlice const definition,
VPackBuilder& builder, bool create) {
int res = ProcessIndexFields(definition, builder, 1, create);
if (res == TRI_ERROR_NO_ERROR) {
if (ServerState::instance()->isCoordinator()) {
builder.add("ignoreNull", VPackValue(true));
builder.add("constraint", VPackValue(false));
}
builder.add("sparse", VPackValue(true));
builder.add("unique", VPackValue(false));
ProcessIndexGeoJsonFlag(definition, builder);
}
return res;
}
////////////////////////////////////////////////////////////////////////////////
/// @brief enhances the json of a geo2 index
////////////////////////////////////////////////////////////////////////////////
static int EnhanceJsonIndexGeo2(VPackSlice const definition,
VPackBuilder& builder, bool create) {
int res = ProcessIndexFields(definition, builder, 2, create);
if (res == TRI_ERROR_NO_ERROR) {
if (ServerState::instance()->isCoordinator()) {
builder.add("ignoreNull", VPackValue(true));
builder.add("constraint", VPackValue(false));
}
builder.add("sparse", VPackValue(true));
builder.add("unique", VPackValue(false));
ProcessIndexGeoJsonFlag(definition, builder);
}
return res;
}
int RocksDBIndexFactory::enhanceIndexDefinition(VPackSlice const definition,
VPackBuilder& enhanced,
bool create) const {
// extract index type
Index::IndexType type = Index::TRI_IDX_TYPE_UNKNOWN;
VPackSlice current = definition.get("type");
if (current.isString()) {
std::string t = current.copyString();
// rewrite type "geo" into either "geo1" or "geo2", depending on the number
// of fields
if (t == "geo") {
t = "geo1";
current = definition.get("fields");
if (current.isArray() && current.length() == 2) {
t = "geo2";
}
}
type = Index::type(t);
}
if (type == Index::TRI_IDX_TYPE_UNKNOWN) {
return TRI_ERROR_BAD_PARAMETER;
}
if (create) {
if (type == Index::TRI_IDX_TYPE_PRIMARY_INDEX ||
type == Index::TRI_IDX_TYPE_EDGE_INDEX) {
// creating these indexes yourself is forbidden
return TRI_ERROR_FORBIDDEN;
}
}
TRI_ASSERT(enhanced.isEmpty());
int res = TRI_ERROR_INTERNAL;
try {
VPackObjectBuilder b(&enhanced);
current = definition.get("id");
uint64_t id = 0;
if (current.isNumber()) {
id = current.getNumericValue<uint64_t>();
} else if (current.isString()) {
id = basics::StringUtils::uint64(current.copyString());
}
if (id > 0) {
enhanced.add("id", VPackValue(std::to_string(id)));
}
if (create) {
if (!definition.hasKey("objectId")) {
enhanced.add("objectId",
VPackValue(std::to_string(TRI_NewTickServer())));
}
} else {
if (!definition.hasKey("objectId")) {
// objectId missing, but must be present
return TRI_ERROR_INTERNAL;
}
}
enhanced.add("type", VPackValue(Index::oldtypeName(type)));
switch (type) {
case Index::TRI_IDX_TYPE_PRIMARY_INDEX:
case Index::TRI_IDX_TYPE_EDGE_INDEX: {
break;
}
case Index::TRI_IDX_TYPE_GEO1_INDEX:
res = EnhanceJsonIndexGeo1(definition, enhanced, create);
break;
case Index::TRI_IDX_TYPE_GEO2_INDEX:
res = EnhanceJsonIndexGeo2(definition, enhanced, create);
break;
case Index::TRI_IDX_TYPE_HASH_INDEX:
res = EnhanceJsonIndexHash(definition, enhanced, create);
break;
case Index::TRI_IDX_TYPE_SKIPLIST_INDEX:
res = EnhanceJsonIndexSkiplist(definition, enhanced, create);
break;
case Index::TRI_IDX_TYPE_PERSISTENT_INDEX:
res = EnhanceJsonIndexPersistent(definition, enhanced, create);
break;
case Index::TRI_IDX_TYPE_UNKNOWN:
default: {
res = TRI_ERROR_BAD_PARAMETER;
break;
}
}
} catch (...) {
// TODO Check for different type of Errors
return TRI_ERROR_OUT_OF_MEMORY;
}
return res;
}
std::shared_ptr<Index> RocksDBIndexFactory::prepareIndexFromSlice(
arangodb::velocypack::Slice info, bool generateKey, LogicalCollection* col,
bool isClusterConstructor) const {
if (!info.isObject()) {
THROW_ARANGO_EXCEPTION(TRI_ERROR_BAD_PARAMETER);
}
// extract type
VPackSlice value = info.get("type");
if (!value.isString()) {
// Compatibility with old v8-vocindex.
if (generateKey) {
THROW_ARANGO_EXCEPTION(TRI_ERROR_OUT_OF_MEMORY);
} else {
THROW_ARANGO_EXCEPTION_MESSAGE(TRI_ERROR_INTERNAL,
"invalid index type definition");
}
}
std::string tmp = value.copyString();
arangodb::Index::IndexType const type = arangodb::Index::type(tmp.c_str());
std::shared_ptr<Index> newIdx;
TRI_idx_iid_t iid = 0;
value = info.get("id");
if (value.isString()) {
iid = basics::StringUtils::uint64(value.copyString());
} else if (value.isNumber()) {
iid =
basics::VelocyPackHelper::getNumericValue<TRI_idx_iid_t>(info, "id", 0);
} else if (!generateKey) {
// In the restore case it is forbidden to NOT have id
THROW_ARANGO_EXCEPTION_MESSAGE(
TRI_ERROR_INTERNAL, "cannot restore index without index identifier");
}
if (iid == 0 && !isClusterConstructor) {
// Restore is not allowed to generate an id
TRI_ASSERT(generateKey);
iid = arangodb::Index::generateId();
}
switch (type) {
case arangodb::Index::TRI_IDX_TYPE_PRIMARY_INDEX: {
if (!isClusterConstructor) {
// this indexes cannot be created directly
THROW_ARANGO_EXCEPTION_MESSAGE(TRI_ERROR_INTERNAL,
"cannot create primary index");
}
newIdx.reset(new arangodb::RocksDBPrimaryIndex(col, info));
break;
}
case arangodb::Index::TRI_IDX_TYPE_EDGE_INDEX: {
if (!isClusterConstructor) {
// this indexes cannot be created directly
THROW_ARANGO_EXCEPTION_MESSAGE(TRI_ERROR_INTERNAL,
"cannot create edge index");
}
VPackSlice fields = info.get("fields");
TRI_ASSERT(fields.isArray() && fields.length() == 1);
std::string direction = fields.at(0).copyString();
TRI_ASSERT(direction == StaticStrings::FromString ||
direction == StaticStrings::ToString);
newIdx.reset(new arangodb::RocksDBEdgeIndex(iid, col, info, direction));
break;
}
// case arangodb::Index::TRI_IDX_TYPE_GEO1_INDEX:
// case arangodb::Index::TRI_IDX_TYPE_GEO2_INDEX:
case arangodb::Index::TRI_IDX_TYPE_HASH_INDEX: {
newIdx.reset(new arangodb::RocksDBHashIndex(iid, col, info));
break;
}
case arangodb::Index::TRI_IDX_TYPE_SKIPLIST_INDEX: {
newIdx.reset(new arangodb::RocksDBSkiplistIndex(iid, col, info));
break;
}
case arangodb::Index::TRI_IDX_TYPE_PERSISTENT_INDEX: {
newIdx.reset(new arangodb::RocksDBPersistentIndex(iid, col, info));
break;
}
case arangodb::Index::TRI_IDX_TYPE_UNKNOWN:
default: {
THROW_ARANGO_EXCEPTION_MESSAGE(TRI_ERROR_INTERNAL, "invalid index type");
}
}
TRI_ASSERT(newIdx != nullptr);
return newIdx;
}
void RocksDBIndexFactory::fillSystemIndexes(
arangodb::LogicalCollection* col,
std::vector<std::shared_ptr<arangodb::Index>>& systemIndexes) const {
// create primary index
VPackBuilder builder;
builder.openObject();
builder.close();
systemIndexes.emplace_back(
std::make_shared<arangodb::RocksDBPrimaryIndex>(col, builder.slice()));
// create edges indexes
if (col->type() == TRI_COL_TYPE_EDGE) {
systemIndexes.emplace_back(std::make_shared<arangodb::RocksDBEdgeIndex>(
1, col, builder.slice(), StaticStrings::FromString));
systemIndexes.emplace_back(std::make_shared<arangodb::RocksDBEdgeIndex>(
2, col, builder.slice(), StaticStrings::ToString));
}
}
std::vector<std::string> RocksDBIndexFactory::supportedIndexes() const {
return std::vector<std::string>{"primary", "edge", "hash", "skiplist",
"persistent"};
}
<commit_msg>Fixing index lookup<commit_after>////////////////////////////////////////////////////////////////////////////////
/// DISCLAIMER
///
/// Copyright 2014-2017 ArangoDB GmbH, Cologne, Germany
/// Copyright 2004-2014 triAGENS GmbH, Cologne, Germany
///
/// 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.
///
/// Copyright holder is ArangoDB GmbH, Cologne, Germany
///
/// @author Michael Hackstein
////////////////////////////////////////////////////////////////////////////////
#include "RocksDBIndexFactory.h"
#include "Basics/StaticStrings.h"
#include "Basics/StringUtils.h"
#include "Basics/VelocyPackHelper.h"
#include "Indexes/Index.h"
#include "RocksDBEngine/RocksDBEdgeIndex.h"
#include "RocksDBEngine/RocksDBEngine.h"
#include "RocksDBEngine/RocksDBHashIndex.h"
#include "RocksDBEngine/RocksDBPersistentIndex.h"
#include "RocksDBEngine/RocksDBPrimaryIndex.h"
#include "RocksDBEngine/RocksDBSkiplistIndex.h"
#include "StorageEngine/EngineSelectorFeature.h"
#include "VocBase/ticks.h"
#include "VocBase/voc-types.h"
#include <velocypack/Builder.h>
#include <velocypack/Iterator.h>
#include <velocypack/Slice.h>
#include <velocypack/velocypack-aliases.h>
using namespace arangodb;
////////////////////////////////////////////////////////////////////////////////
/// @brief process the fields list and add them to the json
////////////////////////////////////////////////////////////////////////////////
static int ProcessIndexFields(VPackSlice const definition,
VPackBuilder& builder, int numFields,
bool create) {
TRI_ASSERT(builder.isOpenObject());
std::unordered_set<StringRef> fields;
try {
VPackSlice fieldsSlice = definition.get("fields");
builder.add(VPackValue("fields"));
builder.openArray();
if (fieldsSlice.isArray()) {
// "fields" is a list of fields
for (auto const& it : VPackArrayIterator(fieldsSlice)) {
if (!it.isString()) {
return TRI_ERROR_BAD_PARAMETER;
}
StringRef f(it);
if (f.empty() || (create && f == StaticStrings::IdString)) {
// accessing internal attributes is disallowed
return TRI_ERROR_BAD_PARAMETER;
}
if (fields.find(f) != fields.end()) {
// duplicate attribute name
return TRI_ERROR_BAD_PARAMETER;
}
fields.insert(f);
builder.add(it);
}
}
if (fields.empty() || (numFields > 0 && (int)fields.size() != numFields)) {
return TRI_ERROR_BAD_PARAMETER;
}
builder.close();
} catch (...) {
return TRI_ERROR_OUT_OF_MEMORY;
}
return TRI_ERROR_NO_ERROR;
}
////////////////////////////////////////////////////////////////////////////////
/// @brief process the unique flag and add it to the json
////////////////////////////////////////////////////////////////////////////////
static void ProcessIndexUniqueFlag(VPackSlice const definition,
VPackBuilder& builder) {
bool unique =
basics::VelocyPackHelper::getBooleanValue(definition, "unique", false);
builder.add("unique", VPackValue(unique));
}
////////////////////////////////////////////////////////////////////////////////
/// @brief process the sparse flag and add it to the json
////////////////////////////////////////////////////////////////////////////////
static void ProcessIndexSparseFlag(VPackSlice const definition,
VPackBuilder& builder, bool create) {
if (definition.hasKey("sparse")) {
bool sparseBool =
basics::VelocyPackHelper::getBooleanValue(definition, "sparse", false);
builder.add("sparse", VPackValue(sparseBool));
} else if (create) {
// not set. now add a default value
builder.add("sparse", VPackValue(false));
}
}
////////////////////////////////////////////////////////////////////////////////
/// @brief enhances the json of a hash index
////////////////////////////////////////////////////////////////////////////////
static int EnhanceJsonIndexHash(VPackSlice const definition,
VPackBuilder& builder, bool create) {
int res = ProcessIndexFields(definition, builder, 0, create);
if (res == TRI_ERROR_NO_ERROR) {
ProcessIndexSparseFlag(definition, builder, create);
ProcessIndexUniqueFlag(definition, builder);
}
return res;
}
////////////////////////////////////////////////////////////////////////////////
/// @brief enhances the json of a skiplist index
////////////////////////////////////////////////////////////////////////////////
static int EnhanceJsonIndexSkiplist(VPackSlice const definition,
VPackBuilder& builder, bool create) {
int res = ProcessIndexFields(definition, builder, 0, create);
if (res == TRI_ERROR_NO_ERROR) {
ProcessIndexSparseFlag(definition, builder, create);
ProcessIndexUniqueFlag(definition, builder);
}
return res;
}
////////////////////////////////////////////////////////////////////////////////
/// @brief enhances the json of a persistent index
////////////////////////////////////////////////////////////////////////////////
static int EnhanceJsonIndexPersistent(VPackSlice const definition,
VPackBuilder& builder, bool create) {
int res = ProcessIndexFields(definition, builder, 0, create);
if (res == TRI_ERROR_NO_ERROR) {
ProcessIndexSparseFlag(definition, builder, create);
ProcessIndexUniqueFlag(definition, builder);
}
return res;
}
////////////////////////////////////////////////////////////////////////////////
/// @brief process the geojson flag and add it to the json
////////////////////////////////////////////////////////////////////////////////
static void ProcessIndexGeoJsonFlag(VPackSlice const definition,
VPackBuilder& builder) {
bool geoJson =
basics::VelocyPackHelper::getBooleanValue(definition, "geoJson", false);
builder.add("geoJson", VPackValue(geoJson));
}
////////////////////////////////////////////////////////////////////////////////
/// @brief enhances the json of a geo1 index
////////////////////////////////////////////////////////////////////////////////
static int EnhanceJsonIndexGeo1(VPackSlice const definition,
VPackBuilder& builder, bool create) {
int res = ProcessIndexFields(definition, builder, 1, create);
if (res == TRI_ERROR_NO_ERROR) {
if (ServerState::instance()->isCoordinator()) {
builder.add("ignoreNull", VPackValue(true));
builder.add("constraint", VPackValue(false));
}
builder.add("sparse", VPackValue(true));
builder.add("unique", VPackValue(false));
ProcessIndexGeoJsonFlag(definition, builder);
}
return res;
}
////////////////////////////////////////////////////////////////////////////////
/// @brief enhances the json of a geo2 index
////////////////////////////////////////////////////////////////////////////////
static int EnhanceJsonIndexGeo2(VPackSlice const definition,
VPackBuilder& builder, bool create) {
int res = ProcessIndexFields(definition, builder, 2, create);
if (res == TRI_ERROR_NO_ERROR) {
if (ServerState::instance()->isCoordinator()) {
builder.add("ignoreNull", VPackValue(true));
builder.add("constraint", VPackValue(false));
}
builder.add("sparse", VPackValue(true));
builder.add("unique", VPackValue(false));
ProcessIndexGeoJsonFlag(definition, builder);
}
return res;
}
int RocksDBIndexFactory::enhanceIndexDefinition(VPackSlice const definition,
VPackBuilder& enhanced,
bool create) const {
// extract index type
Index::IndexType type = Index::TRI_IDX_TYPE_UNKNOWN;
VPackSlice current = definition.get("type");
if (current.isString()) {
std::string t = current.copyString();
// rewrite type "geo" into either "geo1" or "geo2", depending on the number
// of fields
if (t == "geo") {
t = "geo1";
current = definition.get("fields");
if (current.isArray() && current.length() == 2) {
t = "geo2";
}
}
type = Index::type(t);
}
if (type == Index::TRI_IDX_TYPE_UNKNOWN) {
return TRI_ERROR_BAD_PARAMETER;
}
if (create) {
if (type == Index::TRI_IDX_TYPE_PRIMARY_INDEX ||
type == Index::TRI_IDX_TYPE_EDGE_INDEX) {
// creating these indexes yourself is forbidden
return TRI_ERROR_FORBIDDEN;
}
}
TRI_ASSERT(enhanced.isEmpty());
int res = TRI_ERROR_INTERNAL;
try {
VPackObjectBuilder b(&enhanced);
current = definition.get("id");
uint64_t id = 0;
if (current.isNumber()) {
id = current.getNumericValue<uint64_t>();
} else if (current.isString()) {
id = basics::StringUtils::uint64(current.copyString());
}
if (id > 0) {
enhanced.add("id", VPackValue(std::to_string(id)));
}
if (create) {
if (!definition.hasKey("objectId")) {
enhanced.add("objectId",
VPackValue(std::to_string(TRI_NewTickServer())));
}
}
// breaks lookupIndex()
/*else {
if (!definition.hasKey("objectId")) {
// objectId missing, but must be present
return TRI_ERROR_INTERNAL;
}
}*/
enhanced.add("type", VPackValue(Index::oldtypeName(type)));
switch (type) {
case Index::TRI_IDX_TYPE_PRIMARY_INDEX:
case Index::TRI_IDX_TYPE_EDGE_INDEX: {
break;
}
case Index::TRI_IDX_TYPE_GEO1_INDEX:
res = EnhanceJsonIndexGeo1(definition, enhanced, create);
break;
case Index::TRI_IDX_TYPE_GEO2_INDEX:
res = EnhanceJsonIndexGeo2(definition, enhanced, create);
break;
case Index::TRI_IDX_TYPE_HASH_INDEX:
res = EnhanceJsonIndexHash(definition, enhanced, create);
break;
case Index::TRI_IDX_TYPE_SKIPLIST_INDEX:
res = EnhanceJsonIndexSkiplist(definition, enhanced, create);
break;
case Index::TRI_IDX_TYPE_PERSISTENT_INDEX:
res = EnhanceJsonIndexPersistent(definition, enhanced, create);
break;
case Index::TRI_IDX_TYPE_UNKNOWN:
default: {
res = TRI_ERROR_BAD_PARAMETER;
break;
}
}
} catch (...) {
// TODO Check for different type of Errors
return TRI_ERROR_OUT_OF_MEMORY;
}
return res;
}
std::shared_ptr<Index> RocksDBIndexFactory::prepareIndexFromSlice(
arangodb::velocypack::Slice info, bool generateKey, LogicalCollection* col,
bool isClusterConstructor) const {
if (!info.isObject()) {
THROW_ARANGO_EXCEPTION(TRI_ERROR_BAD_PARAMETER);
}
// extract type
VPackSlice value = info.get("type");
if (!value.isString()) {
// Compatibility with old v8-vocindex.
if (generateKey) {
THROW_ARANGO_EXCEPTION(TRI_ERROR_OUT_OF_MEMORY);
} else {
THROW_ARANGO_EXCEPTION_MESSAGE(TRI_ERROR_INTERNAL,
"invalid index type definition");
}
}
std::string tmp = value.copyString();
arangodb::Index::IndexType const type = arangodb::Index::type(tmp.c_str());
std::shared_ptr<Index> newIdx;
TRI_idx_iid_t iid = 0;
value = info.get("id");
if (value.isString()) {
iid = basics::StringUtils::uint64(value.copyString());
} else if (value.isNumber()) {
iid =
basics::VelocyPackHelper::getNumericValue<TRI_idx_iid_t>(info, "id", 0);
} else if (!generateKey) {
// In the restore case it is forbidden to NOT have id
THROW_ARANGO_EXCEPTION_MESSAGE(
TRI_ERROR_INTERNAL, "cannot restore index without index identifier");
}
if (iid == 0 && !isClusterConstructor) {
// Restore is not allowed to generate an id
TRI_ASSERT(generateKey);
iid = arangodb::Index::generateId();
}
switch (type) {
case arangodb::Index::TRI_IDX_TYPE_PRIMARY_INDEX: {
if (!isClusterConstructor) {
// this indexes cannot be created directly
THROW_ARANGO_EXCEPTION_MESSAGE(TRI_ERROR_INTERNAL,
"cannot create primary index");
}
newIdx.reset(new arangodb::RocksDBPrimaryIndex(col, info));
break;
}
case arangodb::Index::TRI_IDX_TYPE_EDGE_INDEX: {
if (!isClusterConstructor) {
// this indexes cannot be created directly
THROW_ARANGO_EXCEPTION_MESSAGE(TRI_ERROR_INTERNAL,
"cannot create edge index");
}
VPackSlice fields = info.get("fields");
TRI_ASSERT(fields.isArray() && fields.length() == 1);
std::string direction = fields.at(0).copyString();
TRI_ASSERT(direction == StaticStrings::FromString ||
direction == StaticStrings::ToString);
newIdx.reset(new arangodb::RocksDBEdgeIndex(iid, col, info, direction));
break;
}
// case arangodb::Index::TRI_IDX_TYPE_GEO1_INDEX:
// case arangodb::Index::TRI_IDX_TYPE_GEO2_INDEX:
case arangodb::Index::TRI_IDX_TYPE_HASH_INDEX: {
newIdx.reset(new arangodb::RocksDBHashIndex(iid, col, info));
break;
}
case arangodb::Index::TRI_IDX_TYPE_SKIPLIST_INDEX: {
newIdx.reset(new arangodb::RocksDBSkiplistIndex(iid, col, info));
break;
}
case arangodb::Index::TRI_IDX_TYPE_PERSISTENT_INDEX: {
newIdx.reset(new arangodb::RocksDBPersistentIndex(iid, col, info));
break;
}
case arangodb::Index::TRI_IDX_TYPE_UNKNOWN:
default: {
THROW_ARANGO_EXCEPTION_MESSAGE(TRI_ERROR_INTERNAL, "invalid index type");
}
}
TRI_ASSERT(newIdx != nullptr);
return newIdx;
}
void RocksDBIndexFactory::fillSystemIndexes(
arangodb::LogicalCollection* col,
std::vector<std::shared_ptr<arangodb::Index>>& systemIndexes) const {
// create primary index
VPackBuilder builder;
builder.openObject();
builder.close();
systemIndexes.emplace_back(
std::make_shared<arangodb::RocksDBPrimaryIndex>(col, builder.slice()));
// create edges indexes
if (col->type() == TRI_COL_TYPE_EDGE) {
systemIndexes.emplace_back(std::make_shared<arangodb::RocksDBEdgeIndex>(
1, col, builder.slice(), StaticStrings::FromString));
systemIndexes.emplace_back(std::make_shared<arangodb::RocksDBEdgeIndex>(
2, col, builder.slice(), StaticStrings::ToString));
}
}
std::vector<std::string> RocksDBIndexFactory::supportedIndexes() const {
return std::vector<std::string>{"primary", "edge", "hash", "skiplist",
"persistent"};
}
<|endoftext|> |
<commit_before>#pragma GCC diagnostic push
#ifdef __clang__
#pragma GCC diagnostic ignored "-Wglobal-constructors"
#endif
// ----------------------------------------------------------------------
/// Local Variables:
/// eval: (if (fboundp 'eu-rename-buffer) (eu-rename-buffer))
/// End:
<commit_msg>clang diagnostics updated<commit_after>#pragma GCC diagnostic push
#ifdef __clang__
#pragma GCC diagnostic ignored "-Wglobal-constructors"
#pragma GCC diagnostic ignored "-Wexit-time-destructors"
#endif
// ----------------------------------------------------------------------
/// Local Variables:
/// eval: (if (fboundp 'eu-rename-buffer) (eu-rename-buffer))
/// End:
<|endoftext|> |
<commit_before>#include "SmoothControl.h"
void SmoothControl::getTrajectory(igvc_msgs::velocity_pair& vel, nav_msgs::Path& trajectory,
Eigen::Vector3d cur_pos, Eigen::Vector3d target, Eigen::Vector2d egocentric_heading)
{
double dt = rollOutTime / 10;
for (int i = 0; i < 15; i++)
{
Eigen::Vector3d action;
getAction(action, cur_pos, target, egocentric_heading);
action[2] = dt;
if (i == 0)
{
vel.left_velocity = action[0] - action[1] * axle_length / 2;
vel.right_velocity = action[0] + action[1] * axle_length / 2;
}
Eigen::Vector3d end_pos;
getResult(end_pos, egocentric_heading, cur_pos, action);
if (i == 0)
{
geometry_msgs::PoseStamped start;
start.pose.position.x = cur_pos[0];
start.pose.position.y = cur_pos[1];
trajectory.poses.push_back(start);
}
geometry_msgs::PoseStamped pose;
pose.pose.position.x = end_pos[0];
pose.pose.position.y = end_pos[1];
trajectory.poses.push_back(pose);
cur_pos = end_pos;
}
}
void SmoothControl::getAction(Eigen::Vector3d& result, Eigen::Vector3d cur_pos,
Eigen::Vector3d target, Eigen::Vector2d egocentric_heading)
{
/**
Computes the radius of curvature to obtain a new angular velocity value.
*/
// get egocentric polar coordinates for delta and theta
double delta = egocentric_heading[0], theta = egocentric_heading[1];
// adjust both angles to lie between -PI and PI
fitToPolar(delta);
fitToPolar(theta);
// calculate the radius of curvature, K
double d = sqrt(pow(target[0] - cur_pos[0], 2) + pow(target[1] - cur_pos[1], 2));
double K = k2 * (delta - atan(-k1 * theta));
K += (1 + (k1 / (1 + pow(k1 * theta, 2)))) * sin(delta);
K /= -d;
// calculate angular velocity using radius of curvature
double w = K * v;
result[0] = v;
result[1] = w;
}
void SmoothControl::getResult(Eigen::Vector3d& result, Eigen::Vector2d& egocentric_heading,
Eigen::Vector3d cur_pos, Eigen::Vector3d action)
{
/**
Obtains the resultant pose given the current velocity and angular velocity command.
Makes extensive use of differential drive odometry equations to calculate resultant
pose
Source: http://www8.cs.umu.se/kurser/5DV122/HT13/material/Hellstrom-ForwardKinematics.pdf
*/
double v = action[0];
double w = action[1];
double dt = action[2];
if (std::abs(w) > 1e-10)
{
// calculate instantaneous center of curvature
double R = v / w;
double ICCx = cur_pos[0] - (R * sin(cur_pos[2]));
double ICCy = cur_pos[1] + (R * cos(cur_pos[2]));
using namespace Eigen;
Matrix3d T;
double wdt = w * dt;
T << cos(wdt), -sin(wdt), 0, sin(wdt), cos(wdt), 0, 0, 0, 1;
Vector3d a(cur_pos[0] - ICCx, cur_pos[1] - ICCy, cur_pos[2]);
Vector3d b = T * a;
Vector3d c = b + Vector3d(ICCx, ICCy, wdt);
egocentric_heading[0] += wdt; // update delta
result[0] = c[0];
result[1] = c[1];
result[2] = c[2];
fitToPolar(result[2]);
}
else
{
result[0] = cur_pos[0] + (cos(cur_pos[2]) * v * dt);
result[1] = cur_pos[1] + (sin(cur_pos[2]) * v * dt);
result[2] = cur_pos[2];
}
}
void SmoothControl::fitToPolar(double& angle) {
/**
Adjust angle to lie within the polar range [-PI, PI]
*/
while (angle > M_PI)
angle -= 2 * M_PI;
while (angle < -M_PI)
angle += 2 * M_PI;
}
<commit_msg>add TODO<commit_after>#include "SmoothControl.h"
void SmoothControl::getTrajectory(igvc_msgs::velocity_pair& vel, nav_msgs::Path& trajectory,
Eigen::Vector3d cur_pos, Eigen::Vector3d target, Eigen::Vector2d egocentric_heading)
{
double dt = rollOutTime / 10;
for (int i = 0; i < 15; i++)
{
Eigen::Vector3d action;
getAction(action, cur_pos, target, egocentric_heading);
action[2] = dt;
if (i == 0)
{
vel.left_velocity = action[0] - action[1] * axle_length / 2;
vel.right_velocity = action[0] + action[1] * axle_length / 2;
}
Eigen::Vector3d end_pos;
getResult(end_pos, egocentric_heading, cur_pos, action);
if (i == 0)
{
geometry_msgs::PoseStamped start;
start.pose.position.x = cur_pos[0];
start.pose.position.y = cur_pos[1];
trajectory.poses.push_back(start);
}
geometry_msgs::PoseStamped pose;
pose.pose.position.x = end_pos[0];
pose.pose.position.y = end_pos[1];
trajectory.poses.push_back(pose);
cur_pos = end_pos;
}
}
void SmoothControl::getAction(Eigen::Vector3d& result, Eigen::Vector3d cur_pos,
Eigen::Vector3d target, Eigen::Vector2d egocentric_heading)
{
/**
Computes the radius of curvature to obtain a new angular velocity value.
*/
// get egocentric polar coordinates for delta and theta
double delta = egocentric_heading[0], theta = egocentric_heading[1];
// adjust both angles to lie between -PI and PI
fitToPolar(delta);
fitToPolar(theta);
// calculate the radius of curvature, K
double d = sqrt(pow(target[0] - cur_pos[0], 2) + pow(target[1] - cur_pos[1], 2));
double K = k2 * (delta - atan(-k1 * theta));
K += (1 + (k1 / (1 + pow(k1 * theta, 2)))) * sin(delta);
K /= -d;
// calculate angular velocity using radius of curvature
double w = K * v;
result[0] = v;
result[1] = w;
}
void SmoothControl::getResult(Eigen::Vector3d& result, Eigen::Vector2d& egocentric_heading,
Eigen::Vector3d cur_pos, Eigen::Vector3d action)
{
/**
Obtains the resultant pose given the current velocity and angular velocity command.
Makes extensive use of differential drive odometry equations to calculate resultant
pose
Source: http://www8.cs.umu.se/kurser/5DV122/HT13/material/Hellstrom-ForwardKinematics.pdf
*/
double v = action[0];
double w = action[1];
double dt = action[2];
if (std::abs(w) > 1e-10)
{
// calculate instantaneous center of curvature
double R = v / w;
double ICCx = cur_pos[0] - (R * sin(cur_pos[2]));
double ICCy = cur_pos[1] + (R * cos(cur_pos[2]));
using namespace Eigen;
Matrix3d T;
double wdt = w * dt;
T << cos(wdt), -sin(wdt), 0, sin(wdt), cos(wdt), 0, 0, 0, 1;
Vector3d a(cur_pos[0] - ICCx, cur_pos[1] - ICCy, cur_pos[2]);
Vector3d b = T * a;
Vector3d c = b + Vector3d(ICCx, ICCy, wdt);
// TODO correct delta and theta updates to implement same heading calculation as in path_follower
egocentric_heading[0] += wdt; // update delta
result[0] = c[0];
result[1] = c[1];
result[2] = c[2];
fitToPolar(result[2]);
}
else
{
result[0] = cur_pos[0] + (cos(cur_pos[2]) * v * dt);
result[1] = cur_pos[1] + (sin(cur_pos[2]) * v * dt);
result[2] = cur_pos[2];
}
}
void SmoothControl::fitToPolar(double& angle) {
/**
Adjust angle to lie within the polar range [-PI, PI]
*/
while (angle > M_PI)
angle -= 2 * M_PI;
while (angle < -M_PI)
angle += 2 * M_PI;
}
<|endoftext|> |
<commit_before>#include "chasky/core/common/status.h"
#include "chasky/core/framework/graph.h"
namespace chasky {
std::unique_ptr<Graph> Graph::Create() {
return std::unique_ptr<Graph>(new Graph);
}
std::shared_ptr<Argument> Graph::Param(const std::string &name) {
auto it = params_.find(name);
if (it == params_.end())
return nullptr;
return it->second;
}
Status Graph::RegisterEdge(StringPiece sign, edge_ptr_t edge) {
Status status;
DLOG(INFO) << "register edge called " << sign;
std::string signature = sign.tostring();
auto it = edges_.find(signature);
CH_STEST_RETURN2(it != edges_.end(), error::INVALID_ARGUMENT,
"an edge called %s already exists", signature.c_str());
CH_STEST_RETURN2(edges_.insert({signature, edge}).second, error::UNKNOWN,
"edges_ insert map error");
#define REGISTER_EDGE(EDGES, KEY) \
if (EDGES.find(KEY) == EDGES.end()) { \
EDGES.emplace(KEY, std::vector<edge_ptr_t>()); \
} \
EDGES[KEY].push_back(edge);
REGISTER_EDGE(trg2edges_, edge->SrcSign().tostring())
REGISTER_EDGE(src2edges_, edge->TrgSign().tostring())
#undef REGISTER_EDGE
return status;
}
Status Graph::GetEdgeBySign(StringPiece sign, edge_ptr_t *edge) {
Status status;
std::string signature = sign.tostring();
auto it = edges_.find(signature);
CH_STEST_RETURN2(it != edges_.end(), error::OUT_OF_RANGE,
"no edges exists called [%s]", signature.c_str());
*edge = it->second;
return status;
}
Status Graph::GetEdgesByTarget(const std::string &signature,
std::vector<edge_ptr_t> **edges) {
Status status;
auto it = trg2edges_.find(signature);
CH_STEST_RETURN2(it != trg2edges_.end(), error::OUT_OF_RANGE,
"no key called %s exists in trg2edges_", signature.c_str());
*edges = &it->second;
return status;
}
Status Graph::GetEdgeByTarget(const std::string &signature, edge_ptr_t *edge) {
std::vector<edge_ptr_t> *edges;
Status status = GetEdgesByTarget(signature, &edges);
if (!status.ok())
return status;
CH_STEST_RETURN2(
edges->size() == 1, error::OUT_OF_RANGE,
"there are [%lu] edges registered by target [%s] is registered",
edges->size(), signature.c_str());
*edge = edges->at(0);
return status;
}
} // namespace chasky
<commit_msg>add GetEdgeBySource implementation<commit_after>#include "chasky/core/common/status.h"
#include "chasky/core/framework/graph.h"
namespace chasky {
std::unique_ptr<Graph> Graph::Create() {
return std::unique_ptr<Graph>(new Graph);
}
std::shared_ptr<Argument> Graph::Param(const std::string &name) {
auto it = params_.find(name);
if (it == params_.end())
return nullptr;
return it->second;
}
Status Graph::RegisterEdge(StringPiece sign, edge_ptr_t edge) {
Status status;
DLOG(INFO) << "register edge called " << sign;
std::string signature = sign.tostring();
auto it = edges_.find(signature);
CH_STEST_RETURN2(it != edges_.end(), error::INVALID_ARGUMENT,
"an edge called %s already exists", signature.c_str());
CH_STEST_RETURN2(edges_.insert({signature, edge}).second, error::UNKNOWN,
"edges_ insert map error");
#define REGISTER_EDGE(EDGES, KEY) \
if (EDGES.find(KEY) == EDGES.end()) { \
EDGES.emplace(KEY, std::vector<edge_ptr_t>()); \
} \
EDGES[KEY].push_back(edge);
REGISTER_EDGE(trg2edges_, edge->SrcSign().tostring())
REGISTER_EDGE(src2edges_, edge->TrgSign().tostring())
#undef REGISTER_EDGE
return status;
}
Status Graph::GetEdgeBySign(StringPiece sign, edge_ptr_t *edge) {
Status status;
std::string signature = sign.tostring();
auto it = edges_.find(signature);
CH_STEST_RETURN2(it != edges_.end(), error::OUT_OF_RANGE,
"no edges exists called [%s]", signature.c_str());
*edge = it->second;
return status;
}
Status Graph::GetEdgesByTarget(const std::string &signature,
std::vector<edge_ptr_t> **edges) {
Status status;
auto it = trg2edges_.find(signature);
CH_STEST_RETURN2(it != trg2edges_.end(), error::OUT_OF_RANGE,
"no key called %s exists in trg2edges_", signature.c_str());
*edges = &it->second;
return status;
}
Status Graph::GetEdgeByTarget(const std::string &signature, edge_ptr_t *edge) {
std::vector<edge_ptr_t> *edges;
Status status = GetEdgesByTarget(signature, &edges);
if (!status.ok())
return status;
CH_STEST_RETURN2(
edges->size() == 1, error::OUT_OF_RANGE,
"there are [%lu] edges registered by target [%s] is registered",
edges->size(), signature.c_str());
*edge = edges->at(0);
return status;
}
Status Graph::GetEdgesBySource(const std::string &signature,
std::vector<edge_ptr_t> *edges) {
Status status;
auto it = src2edges_.find(signature);
CH_STEST_RETURN2(it != src2edges_.end(), error::OUT_OF_RANGE,
"no key called %s exists in src2edges_", signature.c_str());
*edges = it->second;
return status;
}
} // namespace chasky
<|endoftext|> |
<commit_before>/*
* Copyright Andrey Semashev 2007 - 2014.
* Distributed under the Boost Software License, Version 1.0.
* (See accompanying file LICENSE_1_0.txt or copy at
* http://www.boost.org/LICENSE_1_0.txt)
*/
/*!
* \file attachable_sstream_buf.hpp
* \author Andrey Semashev
* \date 29.07.2007
*
* \brief This header is the Boost.Log library implementation, see the library documentation
* at http://www.boost.org/doc/libs/release/libs/log/doc/html/index.html.
*/
#ifndef BOOST_LOG_ATTACHABLE_SSTREAM_BUF_HPP_INCLUDED_
#define BOOST_LOG_ATTACHABLE_SSTREAM_BUF_HPP_INCLUDED_
#include <memory>
#include <string>
#include <streambuf>
#include <boost/assert.hpp>
#include <boost/utility/addressof.hpp>
#include <boost/log/detail/config.hpp>
#include <boost/log/detail/header.hpp>
#ifdef BOOST_HAS_PRAGMA_ONCE
#pragma once
#endif
namespace boost {
BOOST_LOG_OPEN_NAMESPACE
namespace aux {
//! A streambuf that puts the formatted data to an external string
template<
typename CharT,
typename TraitsT = std::char_traits< CharT >,
typename AllocatorT = std::allocator< CharT >
>
class basic_ostringstreambuf :
public std::basic_streambuf< CharT, TraitsT >
{
//! Self type
typedef basic_ostringstreambuf< CharT, TraitsT, AllocatorT > this_type;
//! Base type
typedef std::basic_streambuf< CharT, TraitsT > base_type;
//! Buffer size
enum { buffer_size = 16 };
public:
//! Character type
typedef typename base_type::char_type char_type;
//! Traits type
typedef typename base_type::traits_type traits_type;
//! String type
typedef std::basic_string< char_type, traits_type, AllocatorT > string_type;
//! Int type
typedef typename base_type::int_type int_type;
private:
//! A reference to the string that will be filled
string_type* m_Storage;
//! A buffer used to temporarily store output
char_type m_Buffer[buffer_size];
public:
//! Constructor
explicit basic_ostringstreambuf() : m_Storage(0)
{
base_type::setp(m_Buffer, m_Buffer + (sizeof(m_Buffer) / sizeof(*m_Buffer)));
}
//! Constructor
explicit basic_ostringstreambuf(string_type& storage) : m_Storage(boost::addressof(storage))
{
base_type::setp(m_Buffer, m_Buffer + (sizeof(m_Buffer) / sizeof(*m_Buffer)));
}
//! Clears the buffer to the initial state
void clear()
{
char_type* pBase = this->pbase();
char_type* pPtr = this->pptr();
if (pBase != pPtr)
this->pbump(static_cast< int >(pBase - pPtr));
}
//! Detaches the buffer from the string
void detach()
{
if (m_Storage)
{
this_type::sync();
m_Storage = 0;
}
}
//! Attaches the buffer to another string
void attach(string_type& storage)
{
detach();
m_Storage = boost::addressof(storage);
}
//! Returns a pointer to the attached string
string_type* storage() const { return m_Storage; }
protected:
//! Puts all buffered data to the string
int sync()
{
BOOST_ASSERT(m_Storage != 0);
char_type* pBase = this->pbase();
char_type* pPtr = this->pptr();
if (pBase != pPtr)
{
m_Storage->append(pBase, pPtr);
this->pbump(static_cast< int >(pBase - pPtr));
}
return 0;
}
//! Puts an unbuffered character to the string
int_type overflow(int_type c)
{
BOOST_ASSERT(m_Storage != 0);
basic_ostringstreambuf::sync();
if (!traits_type::eq_int_type(c, traits_type::eof()))
{
m_Storage->push_back(traits_type::to_char_type(c));
return c;
}
else
return traits_type::not_eof(c);
}
//! Puts a character sequence to the string
std::streamsize xsputn(const char_type* s, std::streamsize n)
{
BOOST_ASSERT(m_Storage != 0);
basic_ostringstreambuf::sync();
typedef typename string_type::size_type string_size_type;
register const string_size_type max_storage_left =
m_Storage->max_size() - m_Storage->size();
if (static_cast< string_size_type >(n) < max_storage_left)
{
m_Storage->append(s, static_cast< string_size_type >(n));
return n;
}
else
{
m_Storage->append(s, max_storage_left);
return static_cast< std::streamsize >(max_storage_left);
}
}
//! Copy constructor (closed)
BOOST_DELETED_FUNCTION(basic_ostringstreambuf(basic_ostringstreambuf const& that))
//! Assignment (closed)
BOOST_DELETED_FUNCTION(basic_ostringstreambuf& operator= (basic_ostringstreambuf const& that))
};
} // namespace aux
BOOST_LOG_CLOSE_NAMESPACE // namespace log
} // namespace boost
#include <boost/log/detail/footer.hpp>
#endif // BOOST_LOG_ATTACHABLE_SSTREAM_BUF_HPP_INCLUDED_
<commit_msg>Removed register keyword.<commit_after>/*
* Copyright Andrey Semashev 2007 - 2014.
* Distributed under the Boost Software License, Version 1.0.
* (See accompanying file LICENSE_1_0.txt or copy at
* http://www.boost.org/LICENSE_1_0.txt)
*/
/*!
* \file attachable_sstream_buf.hpp
* \author Andrey Semashev
* \date 29.07.2007
*
* \brief This header is the Boost.Log library implementation, see the library documentation
* at http://www.boost.org/doc/libs/release/libs/log/doc/html/index.html.
*/
#ifndef BOOST_LOG_ATTACHABLE_SSTREAM_BUF_HPP_INCLUDED_
#define BOOST_LOG_ATTACHABLE_SSTREAM_BUF_HPP_INCLUDED_
#include <memory>
#include <string>
#include <streambuf>
#include <boost/assert.hpp>
#include <boost/utility/addressof.hpp>
#include <boost/log/detail/config.hpp>
#include <boost/log/detail/header.hpp>
#ifdef BOOST_HAS_PRAGMA_ONCE
#pragma once
#endif
namespace boost {
BOOST_LOG_OPEN_NAMESPACE
namespace aux {
//! A streambuf that puts the formatted data to an external string
template<
typename CharT,
typename TraitsT = std::char_traits< CharT >,
typename AllocatorT = std::allocator< CharT >
>
class basic_ostringstreambuf :
public std::basic_streambuf< CharT, TraitsT >
{
//! Self type
typedef basic_ostringstreambuf< CharT, TraitsT, AllocatorT > this_type;
//! Base type
typedef std::basic_streambuf< CharT, TraitsT > base_type;
//! Buffer size
enum { buffer_size = 16 };
public:
//! Character type
typedef typename base_type::char_type char_type;
//! Traits type
typedef typename base_type::traits_type traits_type;
//! String type
typedef std::basic_string< char_type, traits_type, AllocatorT > string_type;
//! Int type
typedef typename base_type::int_type int_type;
private:
//! A reference to the string that will be filled
string_type* m_Storage;
//! A buffer used to temporarily store output
char_type m_Buffer[buffer_size];
public:
//! Constructor
explicit basic_ostringstreambuf() : m_Storage(0)
{
base_type::setp(m_Buffer, m_Buffer + (sizeof(m_Buffer) / sizeof(*m_Buffer)));
}
//! Constructor
explicit basic_ostringstreambuf(string_type& storage) : m_Storage(boost::addressof(storage))
{
base_type::setp(m_Buffer, m_Buffer + (sizeof(m_Buffer) / sizeof(*m_Buffer)));
}
//! Clears the buffer to the initial state
void clear()
{
char_type* pBase = this->pbase();
char_type* pPtr = this->pptr();
if (pBase != pPtr)
this->pbump(static_cast< int >(pBase - pPtr));
}
//! Detaches the buffer from the string
void detach()
{
if (m_Storage)
{
this_type::sync();
m_Storage = 0;
}
}
//! Attaches the buffer to another string
void attach(string_type& storage)
{
detach();
m_Storage = boost::addressof(storage);
}
//! Returns a pointer to the attached string
string_type* storage() const { return m_Storage; }
protected:
//! Puts all buffered data to the string
int sync()
{
BOOST_ASSERT(m_Storage != 0);
char_type* pBase = this->pbase();
char_type* pPtr = this->pptr();
if (pBase != pPtr)
{
m_Storage->append(pBase, pPtr);
this->pbump(static_cast< int >(pBase - pPtr));
}
return 0;
}
//! Puts an unbuffered character to the string
int_type overflow(int_type c)
{
BOOST_ASSERT(m_Storage != 0);
basic_ostringstreambuf::sync();
if (!traits_type::eq_int_type(c, traits_type::eof()))
{
m_Storage->push_back(traits_type::to_char_type(c));
return c;
}
else
return traits_type::not_eof(c);
}
//! Puts a character sequence to the string
std::streamsize xsputn(const char_type* s, std::streamsize n)
{
BOOST_ASSERT(m_Storage != 0);
basic_ostringstreambuf::sync();
typedef typename string_type::size_type string_size_type;
const string_size_type max_storage_left =
m_Storage->max_size() - m_Storage->size();
if (static_cast< string_size_type >(n) < max_storage_left)
{
m_Storage->append(s, static_cast< string_size_type >(n));
return n;
}
else
{
m_Storage->append(s, max_storage_left);
return static_cast< std::streamsize >(max_storage_left);
}
}
//! Copy constructor (closed)
BOOST_DELETED_FUNCTION(basic_ostringstreambuf(basic_ostringstreambuf const& that))
//! Assignment (closed)
BOOST_DELETED_FUNCTION(basic_ostringstreambuf& operator= (basic_ostringstreambuf const& that))
};
} // namespace aux
BOOST_LOG_CLOSE_NAMESPACE // namespace log
} // namespace boost
#include <boost/log/detail/footer.hpp>
#endif // BOOST_LOG_ATTACHABLE_SSTREAM_BUF_HPP_INCLUDED_
<|endoftext|> |
<commit_before>//
// Copyright (c) 2013-2014 Christoph Malek
// See LICENSE for more information.
//
#ifndef RJ_GAME_COMPONENTS_GRADIENT_RECT_HPP
#define RJ_GAME_COMPONENTS_GRADIENT_RECT_HPP
#include <rectojump/global/common.hpp>
#include <mlk/graphics/graphics_utl.h>
#include <SFML/Graphics.hpp>
namespace rj
{
class gradient_rect : public sf::Drawable
{
vec2f m_position{0.f, 0.f};
vec2f m_size;
sf::VertexArray m_verts{sf::Quads};
sf::Color m_startcolor;
sf::Color m_endcolor;
std::size_t m_num_gradient_points;
float m_step_ratio;
public:
gradient_rect(const vec2f& size, const sf::Color& startcolor, const sf::Color& endcolor, std::size_t gradient_points) :
m_size{size},
m_startcolor{startcolor},
m_endcolor{endcolor},
m_num_gradient_points{gradient_points},
m_step_ratio{1.f / m_num_gradient_points}
{this->recalculate();}
void set_size(const vec2f& size) noexcept
{m_size = size; this->recalculate();}
void set_position(const vec2f& pos) noexcept
{m_position = pos; this->recalculate();}
void set_startcolor(const sf::Color& color) noexcept
{m_startcolor = color; this->recalculate();}
void set_endcolor(const sf::Color& color) noexcept
{m_endcolor = color; this->recalculate();}
void set_gradient_points(std::size_t num) noexcept
{m_num_gradient_points = num; this->recalculate();}
void move(const vec2f& offset) noexcept
{this->set_position(m_position + offset);}
const vec2f& get_size() const noexcept
{return m_size;}
const vec2f& get_position() const noexcept
{return m_position;}
const sf::Color& get_startcolor() const noexcept
{return m_startcolor;}
const sf::Color& get_endcolor() const noexcept
{return m_endcolor;}
std::size_t num_gradient_points() const noexcept
{return m_num_gradient_points;}
private:
void recalculate() noexcept
{
m_verts.clear();
auto single_size(m_size.y / m_num_gradient_points);
auto pos_y(m_position.y);
auto current_ratio(0.f);
for(auto i(0); i < m_num_gradient_points; ++i)
{
auto current_color(mlk::gcs::color_diff(m_startcolor, m_endcolor, current_ratio));
m_verts.append({{m_position.x, pos_y + single_size}, current_color});
m_verts.append({{m_position.x, pos_y}, current_color});
m_verts.append({{m_size.x + m_position.x, pos_y}, current_color});
m_verts.append({{m_size.x + m_position.x, pos_y + single_size}, current_color});
pos_y += single_size;
current_ratio += m_step_ratio;
}
}
void draw(sf::RenderTarget& target, sf::RenderStates states) const override
{target.draw(m_verts, states);}
};
}
#endif // RJ_GAME_COMPONENTS_GRADIENT_RECT_HPP
<commit_msg>default args<commit_after>//
// Copyright (c) 2013-2014 Christoph Malek
// See LICENSE for more information.
//
#ifndef RJ_GAME_COMPONENTS_GRADIENT_RECT_HPP
#define RJ_GAME_COMPONENTS_GRADIENT_RECT_HPP
#include <rectojump/global/common.hpp>
#include <mlk/graphics/graphics_utl.h>
#include <SFML/Graphics.hpp>
namespace rj
{
class gradient_rect : public sf::Drawable
{
vec2f m_position{0.f, 0.f};
vec2f m_size;
sf::VertexArray m_verts{sf::Quads};
sf::Color m_startcolor;
sf::Color m_endcolor;
std::size_t m_num_gradient_points;
float m_step_ratio;
public:
gradient_rect(const vec2f& size = {0.f, 0.f}, const sf::Color& startcolor = {255, 255, 255},
const sf::Color& endcolor = {255, 255, 255}, std::size_t gradient_points = 1) :
m_size{size},
m_startcolor{startcolor},
m_endcolor{endcolor},
m_num_gradient_points{gradient_points},
m_step_ratio{1.f / m_num_gradient_points}
{this->recalculate();}
void set_size(const vec2f& size) noexcept
{m_size = size; this->recalculate();}
void set_position(const vec2f& pos) noexcept
{m_position = pos; this->recalculate();}
void set_startcolor(const sf::Color& color) noexcept
{m_startcolor = color; this->recalculate();}
void set_endcolor(const sf::Color& color) noexcept
{m_endcolor = color; this->recalculate();}
void set_gradient_points(std::size_t num) noexcept
{m_num_gradient_points = num; this->recalculate();}
void move(const vec2f& offset) noexcept
{this->set_position(m_position + offset);}
const vec2f& get_size() const noexcept
{return m_size;}
const vec2f& get_position() const noexcept
{return m_position;}
const sf::Color& get_startcolor() const noexcept
{return m_startcolor;}
const sf::Color& get_endcolor() const noexcept
{return m_endcolor;}
std::size_t num_gradient_points() const noexcept
{return m_num_gradient_points;}
private:
void recalculate() noexcept
{
m_verts.clear();
auto single_size(m_size.y / m_num_gradient_points);
auto pos_y(m_position.y);
auto current_ratio(0.f);
for(auto i(0); i < m_num_gradient_points; ++i)
{
auto current_color(mlk::gcs::color_diff(m_startcolor, m_endcolor, current_ratio));
m_verts.append({{m_position.x, pos_y + single_size}, current_color});
m_verts.append({{m_position.x, pos_y}, current_color});
m_verts.append({{m_size.x + m_position.x, pos_y}, current_color});
m_verts.append({{m_size.x + m_position.x, pos_y + single_size}, current_color});
pos_y += single_size;
current_ratio += m_step_ratio;
}
}
void draw(sf::RenderTarget& target, sf::RenderStates states) const override
{target.draw(m_verts, states);}
};
}
#endif // RJ_GAME_COMPONENTS_GRADIENT_RECT_HPP
<|endoftext|> |
<commit_before>//
// main.cpp
// chip
//
// Created by lex on 21/08/2017.
// Copyright © 2017 lex. All rights reserved.
//
#include <iostream>
int main(int argc, const char * argv[]) {
// insert code here...
std::cout << "Hello, World!\n";
return 0;
}
<commit_msg>add rom loading<commit_after>//
// main.cpp
// chip
//
// Created by lex on 21/08/2017.
// Copyright © 2017 lex. All rights reserved.
//
#include <iostream>
#include <fstream>
#include <cstdint>
#include <array>
std::array<uint8_t, 4096> rom{0};
int readRom(const std::string& file) {
std::ifstream i(file, std::ios::binary);
if (!i.is_open()) {
std::cout << "couldn't open file " << file << std::endl;
return 1;
}
i.read(reinterpret_cast<char*>(&rom), sizeof rom);
i.close();
for (const auto& b : rom) {
std::cout << b;
}
std::cout << std::endl;
return 0;
}
int main(int argc, const char * argv[]) {
if (argc < 2) {
std::cout << "need rom" << std::endl;
return 1;
}
const std::string file = argv[1];
int r = readRom(file);
return r;
}
<|endoftext|> |
<commit_before>/*************************************************************************
*
* OpenOffice.org - a multi-platform office productivity suite
*
* $RCSfile: adc_cmd_parse.hxx,v $
*
* $Revision: 1.3 $
*
* last change: $Author: rt $ $Date: 2005-09-07 18:04: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 ADC_ADC_CMD_PARSE_HXX
#define ADC_ADC_CMD_PARSE_HXX
// USED SERVICES
// BASE CLASSES
#include "adc_cmd.hxx"
// COMPONENTS
#include <cosv/ploc.hxx>
// PARAMETERS
namespace autodoc
{
namespace command
{
/** A command context which holds the currently parsed programing language
and its valid file extensions.
*/
struct S_LanguageInfo : public Context
{
enum E_ProgrammingLanguage
{
none,
cpp,
idl,
java
};
S_LanguageInfo()
: eLanguage(none),
aExtensions() {}
~S_LanguageInfo();
void InitExtensions(
opt_iter & it,
opt_iter itEnd );
// DATA
E_ProgrammingLanguage
eLanguage;
StringVector aExtensions; // An empty string is possible and means exactly that: files without extension.
private:
// Interface Context:
virtual void do_Init(
opt_iter & it,
opt_iter itEnd );
};
class S_ProjectData;
/** A command that parses source code into the Autodoc Repository.
*/
class Parse : public Command
{
public:
typedef std::vector< DYN S_ProjectData * > ProjectList;
typedef ProjectList::const_iterator ProjectIterator;
Parse();
~Parse();
// INQUIRY
const String & ReposyName() const;
const S_LanguageInfo &
GlobalLanguage() const;
ProjectIterator ProjectsBegin() const;
ProjectIterator ProjectsEnd() const;
const String & DevelopersManual_RefFilePath() const
{ return sDevelopersManual_RefFilePath; }
private:
// Interface Context:
virtual void do_Init(
opt_iter & i_nCurArgsBegin,
opt_iter i_nEndOfAllArgs );
// Interface Command:
virtual bool do_Run() const;
virtual int inq_RunningRank() const;
// Locals
void do_clName(
opt_iter & it,
opt_iter itEnd );
void do_clDevManual(
opt_iter & it,
opt_iter itEnd );
void do_clProject(
opt_iter & it,
opt_iter itEnd );
void do_clDefaultProject(
opt_iter & it,
opt_iter itEnd );
// DATA
String sRepositoryName;
S_LanguageInfo aGlobalLanguage;
ProjectList aProjects;
String sDevelopersManual_RefFilePath;
};
inline const String &
Parse::ReposyName() const
{ return sRepositoryName; }
inline const S_LanguageInfo &
Parse::GlobalLanguage() const
{ return aGlobalLanguage; }
inline Parse::ProjectIterator
Parse::ProjectsBegin() const
{ return aProjects.begin(); }
inline Parse::ProjectIterator
Parse::ProjectsEnd() const
{ return aProjects.end(); }
//inline const String &
//Parse::DevelopersManual_RefFilePath() const
// { return sDevelopersManual_RefFilePath; }
//inline const String &
//Parse::DevelopersManual_HtmlRoot() const
// { return sDevelopersManual_HtmlRoot; }
struct S_Sources : public Context
{
StringVector aTrees;
StringVector aDirectories;
StringVector aFiles;
private:
// Interface Context:
virtual void do_Init(
opt_iter & it,
opt_iter itEnd );
};
class S_ProjectData : public Context
{
public:
enum E_Default { default_prj };
S_ProjectData(
const S_LanguageInfo &
i_globalLanguage );
S_ProjectData(
const S_LanguageInfo &
i_globalLanguage,
E_Default unused );
~S_ProjectData();
bool IsDefault() const { return bIsDefault; }
const String & Name() const { return sName; }
const csv::ploc::Path &
RootDirectory() const { return aRootDirectory; }
const S_LanguageInfo &
Language() const { return aLanguage; }
const S_Sources Sources() const { return aFiles; }
private:
// Interface Context:
virtual void do_Init(
opt_iter & it,
opt_iter itEnd );
// Locals
// DATA
String sName;
csv::ploc::Path aRootDirectory;
S_LanguageInfo aLanguage;
S_Sources aFiles;
bool bIsDefault;
};
} // namespace command
} // namespace autodoc
#endif
<commit_msg>INTEGRATION: CWS changefileheader (1.3.80); FILE MERGED 2008/03/28 16:02:16 rt 1.3.80.1: #i87441# Change license header to LPGL v3.<commit_after>/*************************************************************************
*
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* Copyright 2008 by Sun Microsystems, Inc.
*
* OpenOffice.org - a multi-platform office productivity suite
*
* $RCSfile: adc_cmd_parse.hxx,v $
* $Revision: 1.4 $
*
* This file is part of OpenOffice.org.
*
* OpenOffice.org is free software: you can redistribute it and/or modify
* it under the terms of the GNU Lesser General Public License version 3
* only, as published by the Free Software Foundation.
*
* OpenOffice.org is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Lesser General Public License version 3 for more details
* (a copy is included in the LICENSE file that accompanied this code).
*
* You should have received a copy of the GNU Lesser General Public License
* version 3 along with OpenOffice.org. If not, see
* <http://www.openoffice.org/license.html>
* for a copy of the LGPLv3 License.
*
************************************************************************/
#ifndef ADC_ADC_CMD_PARSE_HXX
#define ADC_ADC_CMD_PARSE_HXX
// USED SERVICES
// BASE CLASSES
#include "adc_cmd.hxx"
// COMPONENTS
#include <cosv/ploc.hxx>
// PARAMETERS
namespace autodoc
{
namespace command
{
/** A command context which holds the currently parsed programing language
and its valid file extensions.
*/
struct S_LanguageInfo : public Context
{
enum E_ProgrammingLanguage
{
none,
cpp,
idl,
java
};
S_LanguageInfo()
: eLanguage(none),
aExtensions() {}
~S_LanguageInfo();
void InitExtensions(
opt_iter & it,
opt_iter itEnd );
// DATA
E_ProgrammingLanguage
eLanguage;
StringVector aExtensions; // An empty string is possible and means exactly that: files without extension.
private:
// Interface Context:
virtual void do_Init(
opt_iter & it,
opt_iter itEnd );
};
class S_ProjectData;
/** A command that parses source code into the Autodoc Repository.
*/
class Parse : public Command
{
public:
typedef std::vector< DYN S_ProjectData * > ProjectList;
typedef ProjectList::const_iterator ProjectIterator;
Parse();
~Parse();
// INQUIRY
const String & ReposyName() const;
const S_LanguageInfo &
GlobalLanguage() const;
ProjectIterator ProjectsBegin() const;
ProjectIterator ProjectsEnd() const;
const String & DevelopersManual_RefFilePath() const
{ return sDevelopersManual_RefFilePath; }
private:
// Interface Context:
virtual void do_Init(
opt_iter & i_nCurArgsBegin,
opt_iter i_nEndOfAllArgs );
// Interface Command:
virtual bool do_Run() const;
virtual int inq_RunningRank() const;
// Locals
void do_clName(
opt_iter & it,
opt_iter itEnd );
void do_clDevManual(
opt_iter & it,
opt_iter itEnd );
void do_clProject(
opt_iter & it,
opt_iter itEnd );
void do_clDefaultProject(
opt_iter & it,
opt_iter itEnd );
// DATA
String sRepositoryName;
S_LanguageInfo aGlobalLanguage;
ProjectList aProjects;
String sDevelopersManual_RefFilePath;
};
inline const String &
Parse::ReposyName() const
{ return sRepositoryName; }
inline const S_LanguageInfo &
Parse::GlobalLanguage() const
{ return aGlobalLanguage; }
inline Parse::ProjectIterator
Parse::ProjectsBegin() const
{ return aProjects.begin(); }
inline Parse::ProjectIterator
Parse::ProjectsEnd() const
{ return aProjects.end(); }
//inline const String &
//Parse::DevelopersManual_RefFilePath() const
// { return sDevelopersManual_RefFilePath; }
//inline const String &
//Parse::DevelopersManual_HtmlRoot() const
// { return sDevelopersManual_HtmlRoot; }
struct S_Sources : public Context
{
StringVector aTrees;
StringVector aDirectories;
StringVector aFiles;
private:
// Interface Context:
virtual void do_Init(
opt_iter & it,
opt_iter itEnd );
};
class S_ProjectData : public Context
{
public:
enum E_Default { default_prj };
S_ProjectData(
const S_LanguageInfo &
i_globalLanguage );
S_ProjectData(
const S_LanguageInfo &
i_globalLanguage,
E_Default unused );
~S_ProjectData();
bool IsDefault() const { return bIsDefault; }
const String & Name() const { return sName; }
const csv::ploc::Path &
RootDirectory() const { return aRootDirectory; }
const S_LanguageInfo &
Language() const { return aLanguage; }
const S_Sources Sources() const { return aFiles; }
private:
// Interface Context:
virtual void do_Init(
opt_iter & it,
opt_iter itEnd );
// Locals
// DATA
String sName;
csv::ploc::Path aRootDirectory;
S_LanguageInfo aLanguage;
S_Sources aFiles;
bool bIsDefault;
};
} // namespace command
} // namespace autodoc
#endif
<|endoftext|> |
<commit_before>// Copyright (c) 2009 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/gtk/nine_box.h"
#include "app/resource_bundle.h"
#include "base/gfx/gtk_util.h"
#include "base/gfx/point.h"
#include "base/logging.h"
namespace {
// Draw pixbuf |src| into |dst| at position (x, y).
void DrawPixbuf(cairo_t* cr, GdkPixbuf* src, int x, int y) {
gdk_cairo_set_source_pixbuf(cr, src, x, y);
cairo_paint(cr);
}
// Tile pixbuf |src| across |cr| at |x|, |y| for |width| and |height|.
void TileImage(cairo_t* cr, GdkPixbuf* src,
int x, int y, int width, int height) {
gdk_cairo_set_source_pixbuf(cr, src, x, y);
cairo_pattern_set_extend(cairo_get_source(cr), CAIRO_EXTEND_REPEAT);
cairo_rectangle(cr, x, y, width, height);
cairo_fill(cr);
}
} // namespace
NineBox::NineBox(int top_left, int top, int top_right, int left, int center,
int right, int bottom_left, int bottom, int bottom_right) {
ResourceBundle& rb = ResourceBundle::GetSharedInstance();
images_[0] = top_left ? rb.GetPixbufNamed(top_left) : NULL;
images_[1] = top ? rb.GetPixbufNamed(top) : NULL;
images_[2] = top_right ? rb.GetPixbufNamed(top_right) : NULL;
images_[3] = left ? rb.GetPixbufNamed(left) : NULL;
images_[4] = center ? rb.GetPixbufNamed(center) : NULL;
images_[5] = right ? rb.GetPixbufNamed(right) : NULL;
images_[6] = bottom_left ? rb.GetPixbufNamed(bottom_left) : NULL;
images_[7] = bottom ? rb.GetPixbufNamed(bottom) : NULL;
images_[8] = bottom_right ? rb.GetPixbufNamed(bottom_right) : NULL;
}
NineBox::~NineBox() {
}
void NineBox::RenderToWidget(GtkWidget* dst) const {
int dst_width = dst->allocation.width;
int dst_height = dst->allocation.height;
cairo_t* cr = gdk_cairo_create(GDK_DRAWABLE(dst->window));
// Transform our cairo from window to widget coordinates.
cairo_translate(cr, dst->allocation.x, dst->allocation.y);
// The upper-left and lower-right corners of the center square in the
// rendering of the ninebox.
int x1 = gdk_pixbuf_get_width(images_[0]);
int y1 = gdk_pixbuf_get_height(images_[0]);
int x2 = images_[2] ? dst_width - gdk_pixbuf_get_width(images_[2]) : x1;
int y2 = images_[6] ? dst_height - gdk_pixbuf_get_height(images_[6]) : y1;
DCHECK_GE(x2, x1);
DCHECK_GE(y2, y1);
// Top row, center image is horizontally tiled.
if (images_[0])
DrawPixbuf(cr, images_[0], 0, 0);
if (images_[1])
RenderTopCenterStrip(cr, x1, 0, x2 - x1);
if (images_[2])
DrawPixbuf(cr, images_[2], x2, 0);
// Center row, all images are vertically tiled, center is horizontally tiled.
if (images_[3])
TileImage(cr, images_[3], 0, y1, x1, y2 - y1);
if (images_[4])
TileImage(cr, images_[4], x1, y1, x2 - x1, y2 - y1);
if (images_[5])
TileImage(cr, images_[5], x2, y1, dst_width - x2, y2 - y1);
// Bottom row, center image is horizontally tiled.
if (images_[6])
DrawPixbuf(cr, images_[6], 0, y2);
if (images_[7])
TileImage(cr, images_[7], x1, y2, x2 - x1, dst_height - y2);
if (images_[8])
DrawPixbuf(cr, images_[8], x2, y2);
cairo_destroy(cr);
}
void NineBox::RenderTopCenterStrip(cairo_t* cr,
int x, int y, int width) const {
const int height = gdk_pixbuf_get_height(images_[1]);
TileImage(cr, images_[1], x, y, width, height);
}
void NineBox::ChangeWhiteToTransparent() {
for (int image_idx = 0; image_idx < 9; ++image_idx) {
GdkPixbuf* pixbuf = images_[image_idx];
if (!pixbuf)
continue;
guchar* pixels = gdk_pixbuf_get_pixels(pixbuf);
int rowstride = gdk_pixbuf_get_rowstride(pixbuf);
for (int i = 0; i < gdk_pixbuf_get_height(pixbuf); ++i) {
for (int j = 0; j < gdk_pixbuf_get_width(pixbuf); ++j) {
guchar* pixel = &pixels[i * rowstride + j * 4];
if (pixel[0] == 0xff && pixel[1] == 0xff && pixel[2] == 0xff) {
pixel[3] = 0;
}
}
}
}
}
void NineBox::ContourWidget(GtkWidget* widget) const {
int x1 = gdk_pixbuf_get_width(images_[0]);
int x2 = widget->allocation.width - gdk_pixbuf_get_width(images_[2]);
// Paint the left and right sides.
GdkBitmap* mask = gdk_pixmap_new(NULL, widget->allocation.width,
widget->allocation.height, 1);
gdk_pixbuf_render_threshold_alpha(images_[0], mask,
0, 0,
0, 0, -1, -1,
1);
gdk_pixbuf_render_threshold_alpha(images_[2], mask,
0, 0,
x2, 0, -1, -1,
1);
// Assume no transparency in the middle rectangle.
cairo_t* cr = gdk_cairo_create(mask);
cairo_rectangle(cr, x1, 0, x2 - x1, widget->allocation.height);
cairo_fill(cr);
// Mask the widget's window's shape.
gtk_widget_shape_combine_mask(widget, mask, 0, 0);
g_object_unref(mask);
cairo_destroy(cr);
}
<commit_msg>Gtk: fix find bar rendering following NineBox improvements.<commit_after>// Copyright (c) 2009 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/gtk/nine_box.h"
#include "app/resource_bundle.h"
#include "base/gfx/gtk_util.h"
#include "base/gfx/point.h"
#include "base/logging.h"
namespace {
// Draw pixbuf |src| into |dst| at position (x, y).
void DrawPixbuf(cairo_t* cr, GdkPixbuf* src, int x, int y) {
gdk_cairo_set_source_pixbuf(cr, src, x, y);
cairo_paint(cr);
}
// Tile pixbuf |src| across |cr| at |x|, |y| for |width| and |height|.
void TileImage(cairo_t* cr, GdkPixbuf* src,
int x, int y, int width, int height) {
gdk_cairo_set_source_pixbuf(cr, src, x, y);
cairo_pattern_set_extend(cairo_get_source(cr), CAIRO_EXTEND_REPEAT);
cairo_rectangle(cr, x, y, width, height);
cairo_fill(cr);
}
} // namespace
NineBox::NineBox(int top_left, int top, int top_right, int left, int center,
int right, int bottom_left, int bottom, int bottom_right) {
ResourceBundle& rb = ResourceBundle::GetSharedInstance();
images_[0] = top_left ? rb.GetPixbufNamed(top_left) : NULL;
images_[1] = top ? rb.GetPixbufNamed(top) : NULL;
images_[2] = top_right ? rb.GetPixbufNamed(top_right) : NULL;
images_[3] = left ? rb.GetPixbufNamed(left) : NULL;
images_[4] = center ? rb.GetPixbufNamed(center) : NULL;
images_[5] = right ? rb.GetPixbufNamed(right) : NULL;
images_[6] = bottom_left ? rb.GetPixbufNamed(bottom_left) : NULL;
images_[7] = bottom ? rb.GetPixbufNamed(bottom) : NULL;
images_[8] = bottom_right ? rb.GetPixbufNamed(bottom_right) : NULL;
}
NineBox::~NineBox() {
}
void NineBox::RenderToWidget(GtkWidget* dst) const {
int dst_width = dst->allocation.width;
int dst_height = dst->allocation.height;
cairo_t* cr = gdk_cairo_create(GDK_DRAWABLE(dst->window));
// For widgets that have their own window, the allocation (x,y) coordinates
// are GdkWindow relative. For other widgets, the coordinates are relative
// to their container.
if (GTK_WIDGET_NO_WINDOW(dst)) {
// Transform our cairo from window to widget coordinates.
cairo_translate(cr, dst->allocation.x, dst->allocation.y);
}
// The upper-left and lower-right corners of the center square in the
// rendering of the ninebox.
int x1 = gdk_pixbuf_get_width(images_[0]);
int y1 = gdk_pixbuf_get_height(images_[0]);
int x2 = images_[2] ? dst_width - gdk_pixbuf_get_width(images_[2]) : x1;
int y2 = images_[6] ? dst_height - gdk_pixbuf_get_height(images_[6]) : y1;
DCHECK_GE(x2, x1);
DCHECK_GE(y2, y1);
// Top row, center image is horizontally tiled.
if (images_[0])
DrawPixbuf(cr, images_[0], 0, 0);
if (images_[1])
RenderTopCenterStrip(cr, x1, 0, x2 - x1);
if (images_[2])
DrawPixbuf(cr, images_[2], x2, 0);
// Center row, all images are vertically tiled, center is horizontally tiled.
if (images_[3])
TileImage(cr, images_[3], 0, y1, x1, y2 - y1);
if (images_[4])
TileImage(cr, images_[4], x1, y1, x2 - x1, y2 - y1);
if (images_[5])
TileImage(cr, images_[5], x2, y1, dst_width - x2, y2 - y1);
// Bottom row, center image is horizontally tiled.
if (images_[6])
DrawPixbuf(cr, images_[6], 0, y2);
if (images_[7])
TileImage(cr, images_[7], x1, y2, x2 - x1, dst_height - y2);
if (images_[8])
DrawPixbuf(cr, images_[8], x2, y2);
cairo_destroy(cr);
}
void NineBox::RenderTopCenterStrip(cairo_t* cr,
int x, int y, int width) const {
const int height = gdk_pixbuf_get_height(images_[1]);
TileImage(cr, images_[1], x, y, width, height);
}
void NineBox::ChangeWhiteToTransparent() {
for (int image_idx = 0; image_idx < 9; ++image_idx) {
GdkPixbuf* pixbuf = images_[image_idx];
if (!pixbuf)
continue;
guchar* pixels = gdk_pixbuf_get_pixels(pixbuf);
int rowstride = gdk_pixbuf_get_rowstride(pixbuf);
for (int i = 0; i < gdk_pixbuf_get_height(pixbuf); ++i) {
for (int j = 0; j < gdk_pixbuf_get_width(pixbuf); ++j) {
guchar* pixel = &pixels[i * rowstride + j * 4];
if (pixel[0] == 0xff && pixel[1] == 0xff && pixel[2] == 0xff) {
pixel[3] = 0;
}
}
}
}
}
void NineBox::ContourWidget(GtkWidget* widget) const {
int x1 = gdk_pixbuf_get_width(images_[0]);
int x2 = widget->allocation.width - gdk_pixbuf_get_width(images_[2]);
// Paint the left and right sides.
GdkBitmap* mask = gdk_pixmap_new(NULL, widget->allocation.width,
widget->allocation.height, 1);
gdk_pixbuf_render_threshold_alpha(images_[0], mask,
0, 0,
0, 0, -1, -1,
1);
gdk_pixbuf_render_threshold_alpha(images_[2], mask,
0, 0,
x2, 0, -1, -1,
1);
// Assume no transparency in the middle rectangle.
cairo_t* cr = gdk_cairo_create(mask);
cairo_rectangle(cr, x1, 0, x2 - x1, widget->allocation.height);
cairo_fill(cr);
// Mask the widget's window's shape.
gtk_widget_shape_combine_mask(widget, mask, 0, 0);
g_object_unref(mask);
cairo_destroy(cr);
}
<|endoftext|> |
<commit_before>// Copyright 2008, Google Inc.
// All rights reserved.
//
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions are
// met:
//
// * Redistributions of source code must retain the above copyright
// notice, this list of conditions and the following disclaimer.
// * 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 Google Inc. nor the names of its
// contributors may be used to endorse or promote products derived from
// this software without specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
#include "chrome/browser/login_prompt.h"
#include "base/command_line.h"
#include "base/lock.h"
#include "base/message_loop.h"
#include "chrome/browser/browser_process.h"
#include "chrome/browser/constrained_window.h"
#include "chrome/browser/controller.h"
#include "chrome/browser/navigation_controller.h"
#include "chrome/browser/password_manager.h"
#include "chrome/browser/render_process_host.h"
#include "chrome/browser/resource_dispatcher_host.h"
#include "chrome/browser/web_contents.h"
#include "chrome/browser/tab_util.h"
#include "chrome/browser/views/login_view.h"
#include "chrome/common/chrome_switches.h"
#include "chrome/common/l10n_util.h"
#include "chrome/common/notification_service.h"
#include "chrome/views/dialog_delegate.h"
#include "net/base/auth.h"
#include "net/url_request/url_request.h"
#include "generated_resources.h"
using namespace std;
using ChromeViews::LoginView;
class LoginHandlerImpl;
// Helper to remove the ref from an URLRequest to the LoginHandler.
// Should only be called from the IO thread, since it accesses an URLRequest.
static void ResetLoginHandlerForRequest(URLRequest* request) {
ResourceDispatcherHost::ExtraRequestInfo* info =
ResourceDispatcherHost::ExtraInfoForRequest(request);
if (!info)
return;
info->login_handler = NULL;
}
// ----------------------------------------------------------------------------
// LoginHandlerImpl
// This class simply forwards the authentication from the LoginView (on
// the UI thread) to the URLRequest (on the I/O thread).
// This class uses ref counting to ensure that it lives until all InvokeLaters
// have been called.
class LoginHandlerImpl : public LoginHandler,
public base::RefCountedThreadSafe<LoginHandlerImpl>,
public ChromeViews::DialogDelegate {
public:
LoginHandlerImpl(URLRequest* request, MessageLoop* ui_loop)
: dialog_(NULL),
handled_auth_(false),
request_(request),
request_loop_(MessageLoop::current()),
ui_loop_(ui_loop),
password_manager_(NULL) {
DCHECK(request_) << "LoginHandler constructed with NULL request";
AddRef(); // matched by ReleaseLater.
if (!tab_util::GetTabContentsID(request_, &render_process_host_id_,
&tab_contents_id_)) {
NOTREACHED();
}
}
~LoginHandlerImpl() {
}
// Initialize the UI part of the LoginHandler.
// Scary thread safety note: This can potentially be called *after* SetAuth
// or CancelAuth (say, if the request was cancelled before the UI thread got
// control). However, that's OK since any UI interaction in those functions
// will occur via an InvokeLater on the UI thread, which is guaranteed
// to happen after this is called (since this was InvokeLater'd first).
void InitWithDialog(ConstrainedWindow* dlg) {
DCHECK(MessageLoop::current() == ui_loop_);
dialog_ = dlg;
SendNotifications();
}
// Returns the TabContents that needs authentication.
TabContents* GetTabContentsForLogin() {
DCHECK(MessageLoop::current() == ui_loop_);
return tab_util::GetTabContentsByID(render_process_host_id_,
tab_contents_id_);
}
void set_login_view(LoginView* login_view) {
login_view_ = login_view;
}
void set_password_form(const PasswordForm& form) {
password_form_ = form;
}
void set_password_manager(PasswordManager* password_manager) {
password_manager_ = password_manager;
}
// ChromeViews::DialogDelegate methods:
virtual std::wstring GetDialogButtonLabel(DialogButton button) const {
if (button == DIALOGBUTTON_OK)
return l10n_util::GetString(IDS_LOGIN_DIALOG_OK_BUTTON_LABEL);
return DialogDelegate::GetDialogButtonLabel(button);
}
virtual std::wstring GetWindowTitle() const {
return l10n_util::GetString(IDS_LOGIN_DIALOG_TITLE);
}
virtual void WindowClosing() {
DCHECK(MessageLoop::current() == ui_loop_);
// Reference is no longer valid.
dialog_ = NULL;
if (!WasAuthHandled(true)) {
request_loop_->PostTask(FROM_HERE, NewRunnableMethod(
this, &LoginHandlerImpl::CancelAuthDeferred));
SendNotifications();
}
// Delete this object once all InvokeLaters have been called.
request_loop_->ReleaseSoon(FROM_HERE, this);
}
virtual bool Cancel() {
DCHECK(MessageLoop::current() == ui_loop_);
DCHECK(dialog_) << "LoginHandler invoked without being attached";
CancelAuth();
return true;
}
virtual bool Accept() {
DCHECK(MessageLoop::current() == ui_loop_);
DCHECK(dialog_) << "LoginHandler invoked without being attached";
SetAuth(login_view_->GetUsername(), login_view_->GetPassword());
return true;
}
virtual ChromeViews::View* GetContentsView() {
return login_view_;
}
// LoginHandler:
virtual void SetAuth(const std::wstring& username,
const std::wstring& password) {
if (WasAuthHandled(true))
return;
// Tell the password manager the credentials were submitted / accepted.
if (password_manager_) {
password_form_.username_value = username;
password_form_.password_value = password;
password_manager_->ProvisionallySavePassword(password_form_);
}
ui_loop_->PostTask(FROM_HERE, NewRunnableMethod(
this, &LoginHandlerImpl::CloseContentsDeferred));
ui_loop_->PostTask(FROM_HERE, NewRunnableMethod(
this, &LoginHandlerImpl::SendNotifications));
request_loop_->PostTask(FROM_HERE, NewRunnableMethod(
this, &LoginHandlerImpl::SetAuthDeferred, username, password));
}
virtual void CancelAuth() {
if (WasAuthHandled(true))
return;
ui_loop_->PostTask(FROM_HERE, NewRunnableMethod(
this, &LoginHandlerImpl::CloseContentsDeferred));
ui_loop_->PostTask(FROM_HERE, NewRunnableMethod(
this, &LoginHandlerImpl::SendNotifications));
request_loop_->PostTask(FROM_HERE, NewRunnableMethod(
this, &LoginHandlerImpl::CancelAuthDeferred));
}
virtual void OnRequestCancelled() {
DCHECK(MessageLoop::current() == request_loop_) <<
"Why is OnRequestCancelled called from the UI thread?";
// Reference is no longer valid.
request_ = NULL;
// Give up on auth if the request was cancelled.
CancelAuth();
}
private:
// Calls SetAuth from the request_loop.
void SetAuthDeferred(const std::wstring& username,
const std::wstring& password) {
DCHECK(MessageLoop::current() == request_loop_);
if (request_) {
request_->SetAuth(username, password);
ResetLoginHandlerForRequest(request_);
}
}
// Calls CancelAuth from the request_loop.
void CancelAuthDeferred() {
DCHECK(MessageLoop::current() == request_loop_);
if (request_) {
request_->CancelAuth();
// Verify that CancelAuth does destroy the request via our delegate.
DCHECK(request_ != NULL);
ResetLoginHandlerForRequest(request_);
}
}
// Closes the view_contents from the UI loop.
void CloseContentsDeferred() {
DCHECK(MessageLoop::current() == ui_loop_);
// The hosting ConstrainedWindow may have been freed.
if (dialog_)
dialog_->CloseConstrainedWindow();
}
// Returns whether authentication had been handled (SetAuth or CancelAuth).
// If |set_handled| is true, it will mark authentication as handled.
bool WasAuthHandled(bool set_handled) {
AutoLock lock(handled_auth_lock_);
bool was_handled = handled_auth_;
if (set_handled)
handled_auth_ = true;
return was_handled;
}
// Notify observers that authentication is needed or received. The automation
// proxy uses this for testing.
void SendNotifications() {
DCHECK(MessageLoop::current() == ui_loop_);
NotificationService* service = NotificationService::current();
TabContents* requesting_contents = GetTabContentsForLogin();
if (!requesting_contents)
return;
NavigationController* controller = requesting_contents->controller();
if (WasAuthHandled(false)) {
LoginNotificationDetails details(this);
service->Notify(NOTIFY_AUTH_NEEDED,
Source<NavigationController>(controller),
Details<LoginNotificationDetails>(&details));
} else {
service->Notify(NOTIFY_AUTH_SUPPLIED,
Source<NavigationController>(controller),
NotificationService::NoDetails());
}
}
// True if we've handled auth (SetAuth or CancelAuth has been called).
bool handled_auth_;
Lock handled_auth_lock_;
// The ConstrainedWindow that is hosting our LoginView.
// This should only be accessed on the ui_loop_.
ConstrainedWindow* dialog_;
// The MessageLoop of the thread that the ChromeViewContents lives in.
MessageLoop* ui_loop_;
// The request that wants login data.
// This should only be accessed on the request_loop_.
URLRequest* request_;
// The MessageLoop of the thread that the URLRequest lives in.
MessageLoop* request_loop_;
// The LoginView that contains the user's login information
LoginView* login_view_;
// The PasswordForm sent to the PasswordManager. This is so we can refer to it
// when later notifying the password manager if the credentials were accepted
// or rejected.
// This should only be accessed on the ui_loop_.
PasswordForm password_form_;
// Points to the password manager owned by the TabContents requesting auth.
// Can be null if the TabContents is not a WebContents.
// This should only be accessed on the ui_loop_.
PasswordManager* password_manager_;
// Cached from the URLRequest, in case it goes NULL on us.
int render_process_host_id_;
int tab_contents_id_;
DISALLOW_EVIL_CONSTRUCTORS(LoginHandlerImpl);
};
// ----------------------------------------------------------------------------
// LoginDialogTask
// This task is run on the UI thread and creates a constrained window with
// a LoginView to prompt the user. The response will be sent to LoginHandler,
// which then routes it to the URLRequest on the I/O thread.
class LoginDialogTask : public Task {
public:
LoginDialogTask(net::AuthChallengeInfo* auth_info, LoginHandlerImpl* handler)
: auth_info_(auth_info), handler_(handler) {
}
virtual ~LoginDialogTask() {
}
void Run() {
TabContents* parent_contents = handler_->GetTabContentsForLogin();
if (!parent_contents) {
// The request was probably cancelled.
return;
}
wstring explanation = l10n_util::GetStringF(IDS_LOGIN_DIALOG_DESCRIPTION,
auth_info_->host,
auth_info_->realm);
LoginView* view = new LoginView(explanation);
// Tell the password manager to look for saved passwords. There is only
// a password manager when dealing with a WebContents type.
if (parent_contents->type() == TAB_CONTENTS_WEB) {
PasswordManager* password_manager =
parent_contents->AsWebContents()->GetPasswordManager();
// Set the model for the login view. The model (password manager) is owned
// by the view's parent TabContents, so natural destruction order means we
// don't have to worry about calling SetModel(NULL), because the view will
// be deleted before the password manager.
view->SetModel(password_manager);
std::vector<PasswordForm> v;
MakeInputForPasswordManager(parent_contents->GetURL(), &v);
password_manager->PasswordFormsSeen(v);
handler_->set_password_manager(password_manager);
}
handler_->set_login_view(view);
ConstrainedWindow* dialog =
parent_contents->CreateConstrainedDialog(handler_, view);
handler_->InitWithDialog(dialog);
}
private:
// Helper to create a PasswordForm and stuff it into a vector as input
// for PasswordManager::PasswordFormsSeen, the hook into PasswordManager.
void MakeInputForPasswordManager(
const GURL& origin_url,
std::vector<PasswordForm>* password_manager_input) {
PasswordForm dialog_form;
if (LowerCaseEqualsASCII(auth_info_->scheme, "basic")) {
dialog_form.scheme = PasswordForm::SCHEME_BASIC;
} else if (LowerCaseEqualsASCII(auth_info_->scheme, "digest")) {
dialog_form.scheme = PasswordForm::SCHEME_DIGEST;
} else {
dialog_form.scheme = PasswordForm::SCHEME_OTHER;
}
dialog_form.origin = origin_url;
// TODO(timsteele): Shouldn't depend on HttpKey since a change to the
// format would result in not being able to retrieve existing logins
// for a site. Refactor HttpKey behavior to be more reusable.
dialog_form.signon_realm =
net::AuthCache::HttpKey(dialog_form.origin, *auth_info_);
password_manager_input->push_back(dialog_form);
// Set the password form for the handler (by copy).
handler_->set_password_form(dialog_form);
}
// Info about who/where/what is asking for authentication.
scoped_refptr<net::AuthChallengeInfo> auth_info_;
// Where to send the authentication when obtained.
// This is owned by the ResourceDispatcherHost that invoked us.
LoginHandlerImpl* handler_;
DISALLOW_EVIL_CONSTRUCTORS(LoginDialogTask);
};
// ----------------------------------------------------------------------------
// Public API
LoginHandler* CreateLoginPrompt(net::AuthChallengeInfo* auth_info,
URLRequest* request,
MessageLoop* ui_loop) {
LoginHandlerImpl* handler = new LoginHandlerImpl(request, ui_loop);
ui_loop->PostTask(FROM_HERE, new LoginDialogTask(auth_info, handler));
return handler;
}
<commit_msg>Fix a bug introduced with the locking changes to login_prompt.cc :\<commit_after>// Copyright 2008, Google Inc.
// All rights reserved.
//
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions are
// met:
//
// * Redistributions of source code must retain the above copyright
// notice, this list of conditions and the following disclaimer.
// * 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 Google Inc. nor the names of its
// contributors may be used to endorse or promote products derived from
// this software without specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
#include "chrome/browser/login_prompt.h"
#include "base/command_line.h"
#include "base/lock.h"
#include "base/message_loop.h"
#include "chrome/browser/browser_process.h"
#include "chrome/browser/constrained_window.h"
#include "chrome/browser/controller.h"
#include "chrome/browser/navigation_controller.h"
#include "chrome/browser/password_manager.h"
#include "chrome/browser/render_process_host.h"
#include "chrome/browser/resource_dispatcher_host.h"
#include "chrome/browser/web_contents.h"
#include "chrome/browser/tab_util.h"
#include "chrome/browser/views/login_view.h"
#include "chrome/common/chrome_switches.h"
#include "chrome/common/l10n_util.h"
#include "chrome/common/notification_service.h"
#include "chrome/views/dialog_delegate.h"
#include "net/base/auth.h"
#include "net/url_request/url_request.h"
#include "generated_resources.h"
using namespace std;
using ChromeViews::LoginView;
class LoginHandlerImpl;
// Helper to remove the ref from an URLRequest to the LoginHandler.
// Should only be called from the IO thread, since it accesses an URLRequest.
static void ResetLoginHandlerForRequest(URLRequest* request) {
ResourceDispatcherHost::ExtraRequestInfo* info =
ResourceDispatcherHost::ExtraInfoForRequest(request);
if (!info)
return;
info->login_handler = NULL;
}
// ----------------------------------------------------------------------------
// LoginHandlerImpl
// This class simply forwards the authentication from the LoginView (on
// the UI thread) to the URLRequest (on the I/O thread).
// This class uses ref counting to ensure that it lives until all InvokeLaters
// have been called.
class LoginHandlerImpl : public LoginHandler,
public base::RefCountedThreadSafe<LoginHandlerImpl>,
public ChromeViews::DialogDelegate {
public:
LoginHandlerImpl(URLRequest* request, MessageLoop* ui_loop)
: dialog_(NULL),
handled_auth_(false),
request_(request),
request_loop_(MessageLoop::current()),
ui_loop_(ui_loop),
password_manager_(NULL) {
DCHECK(request_) << "LoginHandler constructed with NULL request";
AddRef(); // matched by ReleaseLater.
if (!tab_util::GetTabContentsID(request_, &render_process_host_id_,
&tab_contents_id_)) {
NOTREACHED();
}
}
~LoginHandlerImpl() {
}
// Initialize the UI part of the LoginHandler.
// Scary thread safety note: This can potentially be called *after* SetAuth
// or CancelAuth (say, if the request was cancelled before the UI thread got
// control). However, that's OK since any UI interaction in those functions
// will occur via an InvokeLater on the UI thread, which is guaranteed
// to happen after this is called (since this was InvokeLater'd first).
void InitWithDialog(ConstrainedWindow* dlg) {
DCHECK(MessageLoop::current() == ui_loop_);
dialog_ = dlg;
SendNotifications();
}
// Returns the TabContents that needs authentication.
TabContents* GetTabContentsForLogin() {
DCHECK(MessageLoop::current() == ui_loop_);
return tab_util::GetTabContentsByID(render_process_host_id_,
tab_contents_id_);
}
void set_login_view(LoginView* login_view) {
login_view_ = login_view;
}
void set_password_form(const PasswordForm& form) {
password_form_ = form;
}
void set_password_manager(PasswordManager* password_manager) {
password_manager_ = password_manager;
}
// ChromeViews::DialogDelegate methods:
virtual std::wstring GetDialogButtonLabel(DialogButton button) const {
if (button == DIALOGBUTTON_OK)
return l10n_util::GetString(IDS_LOGIN_DIALOG_OK_BUTTON_LABEL);
return DialogDelegate::GetDialogButtonLabel(button);
}
virtual std::wstring GetWindowTitle() const {
return l10n_util::GetString(IDS_LOGIN_DIALOG_TITLE);
}
virtual void WindowClosing() {
DCHECK(MessageLoop::current() == ui_loop_);
// Reference is no longer valid.
dialog_ = NULL;
if (!WasAuthHandled(true)) {
request_loop_->PostTask(FROM_HERE, NewRunnableMethod(
this, &LoginHandlerImpl::CancelAuthDeferred));
SendNotifications();
}
// Delete this object once all InvokeLaters have been called.
request_loop_->ReleaseSoon(FROM_HERE, this);
}
virtual bool Cancel() {
DCHECK(MessageLoop::current() == ui_loop_);
DCHECK(dialog_) << "LoginHandler invoked without being attached";
CancelAuth();
return true;
}
virtual bool Accept() {
DCHECK(MessageLoop::current() == ui_loop_);
DCHECK(dialog_) << "LoginHandler invoked without being attached";
SetAuth(login_view_->GetUsername(), login_view_->GetPassword());
return true;
}
virtual ChromeViews::View* GetContentsView() {
return login_view_;
}
// LoginHandler:
virtual void SetAuth(const std::wstring& username,
const std::wstring& password) {
if (WasAuthHandled(true))
return;
// Tell the password manager the credentials were submitted / accepted.
if (password_manager_) {
password_form_.username_value = username;
password_form_.password_value = password;
password_manager_->ProvisionallySavePassword(password_form_);
}
ui_loop_->PostTask(FROM_HERE, NewRunnableMethod(
this, &LoginHandlerImpl::CloseContentsDeferred));
ui_loop_->PostTask(FROM_HERE, NewRunnableMethod(
this, &LoginHandlerImpl::SendNotifications));
request_loop_->PostTask(FROM_HERE, NewRunnableMethod(
this, &LoginHandlerImpl::SetAuthDeferred, username, password));
}
virtual void CancelAuth() {
if (WasAuthHandled(true))
return;
ui_loop_->PostTask(FROM_HERE, NewRunnableMethod(
this, &LoginHandlerImpl::CloseContentsDeferred));
ui_loop_->PostTask(FROM_HERE, NewRunnableMethod(
this, &LoginHandlerImpl::SendNotifications));
request_loop_->PostTask(FROM_HERE, NewRunnableMethod(
this, &LoginHandlerImpl::CancelAuthDeferred));
}
virtual void OnRequestCancelled() {
DCHECK(MessageLoop::current() == request_loop_) <<
"Why is OnRequestCancelled called from the UI thread?";
// Reference is no longer valid.
request_ = NULL;
// Give up on auth if the request was cancelled.
CancelAuth();
}
private:
// Calls SetAuth from the request_loop.
void SetAuthDeferred(const std::wstring& username,
const std::wstring& password) {
DCHECK(MessageLoop::current() == request_loop_);
if (request_) {
request_->SetAuth(username, password);
ResetLoginHandlerForRequest(request_);
}
}
// Calls CancelAuth from the request_loop.
void CancelAuthDeferred() {
DCHECK(MessageLoop::current() == request_loop_);
if (request_) {
request_->CancelAuth();
// Verify that CancelAuth does destroy the request via our delegate.
DCHECK(request_ != NULL);
ResetLoginHandlerForRequest(request_);
}
}
// Closes the view_contents from the UI loop.
void CloseContentsDeferred() {
DCHECK(MessageLoop::current() == ui_loop_);
// The hosting ConstrainedWindow may have been freed.
if (dialog_)
dialog_->CloseConstrainedWindow();
}
// Returns whether authentication had been handled (SetAuth or CancelAuth).
// If |set_handled| is true, it will mark authentication as handled.
bool WasAuthHandled(bool set_handled) {
AutoLock lock(handled_auth_lock_);
bool was_handled = handled_auth_;
if (set_handled)
handled_auth_ = true;
return was_handled;
}
// Notify observers that authentication is needed or received. The automation
// proxy uses this for testing.
void SendNotifications() {
DCHECK(MessageLoop::current() == ui_loop_);
NotificationService* service = NotificationService::current();
TabContents* requesting_contents = GetTabContentsForLogin();
if (!requesting_contents)
return;
NavigationController* controller = requesting_contents->controller();
if (!WasAuthHandled(false)) {
LoginNotificationDetails details(this);
service->Notify(NOTIFY_AUTH_NEEDED,
Source<NavigationController>(controller),
Details<LoginNotificationDetails>(&details));
} else {
service->Notify(NOTIFY_AUTH_SUPPLIED,
Source<NavigationController>(controller),
NotificationService::NoDetails());
}
}
// True if we've handled auth (SetAuth or CancelAuth has been called).
bool handled_auth_;
Lock handled_auth_lock_;
// The ConstrainedWindow that is hosting our LoginView.
// This should only be accessed on the ui_loop_.
ConstrainedWindow* dialog_;
// The MessageLoop of the thread that the ChromeViewContents lives in.
MessageLoop* ui_loop_;
// The request that wants login data.
// This should only be accessed on the request_loop_.
URLRequest* request_;
// The MessageLoop of the thread that the URLRequest lives in.
MessageLoop* request_loop_;
// The LoginView that contains the user's login information
LoginView* login_view_;
// The PasswordForm sent to the PasswordManager. This is so we can refer to it
// when later notifying the password manager if the credentials were accepted
// or rejected.
// This should only be accessed on the ui_loop_.
PasswordForm password_form_;
// Points to the password manager owned by the TabContents requesting auth.
// Can be null if the TabContents is not a WebContents.
// This should only be accessed on the ui_loop_.
PasswordManager* password_manager_;
// Cached from the URLRequest, in case it goes NULL on us.
int render_process_host_id_;
int tab_contents_id_;
DISALLOW_EVIL_CONSTRUCTORS(LoginHandlerImpl);
};
// ----------------------------------------------------------------------------
// LoginDialogTask
// This task is run on the UI thread and creates a constrained window with
// a LoginView to prompt the user. The response will be sent to LoginHandler,
// which then routes it to the URLRequest on the I/O thread.
class LoginDialogTask : public Task {
public:
LoginDialogTask(net::AuthChallengeInfo* auth_info, LoginHandlerImpl* handler)
: auth_info_(auth_info), handler_(handler) {
}
virtual ~LoginDialogTask() {
}
void Run() {
TabContents* parent_contents = handler_->GetTabContentsForLogin();
if (!parent_contents) {
// The request was probably cancelled.
return;
}
wstring explanation = l10n_util::GetStringF(IDS_LOGIN_DIALOG_DESCRIPTION,
auth_info_->host,
auth_info_->realm);
LoginView* view = new LoginView(explanation);
// Tell the password manager to look for saved passwords. There is only
// a password manager when dealing with a WebContents type.
if (parent_contents->type() == TAB_CONTENTS_WEB) {
PasswordManager* password_manager =
parent_contents->AsWebContents()->GetPasswordManager();
// Set the model for the login view. The model (password manager) is owned
// by the view's parent TabContents, so natural destruction order means we
// don't have to worry about calling SetModel(NULL), because the view will
// be deleted before the password manager.
view->SetModel(password_manager);
std::vector<PasswordForm> v;
MakeInputForPasswordManager(parent_contents->GetURL(), &v);
password_manager->PasswordFormsSeen(v);
handler_->set_password_manager(password_manager);
}
handler_->set_login_view(view);
ConstrainedWindow* dialog =
parent_contents->CreateConstrainedDialog(handler_, view);
handler_->InitWithDialog(dialog);
}
private:
// Helper to create a PasswordForm and stuff it into a vector as input
// for PasswordManager::PasswordFormsSeen, the hook into PasswordManager.
void MakeInputForPasswordManager(
const GURL& origin_url,
std::vector<PasswordForm>* password_manager_input) {
PasswordForm dialog_form;
if (LowerCaseEqualsASCII(auth_info_->scheme, "basic")) {
dialog_form.scheme = PasswordForm::SCHEME_BASIC;
} else if (LowerCaseEqualsASCII(auth_info_->scheme, "digest")) {
dialog_form.scheme = PasswordForm::SCHEME_DIGEST;
} else {
dialog_form.scheme = PasswordForm::SCHEME_OTHER;
}
dialog_form.origin = origin_url;
// TODO(timsteele): Shouldn't depend on HttpKey since a change to the
// format would result in not being able to retrieve existing logins
// for a site. Refactor HttpKey behavior to be more reusable.
dialog_form.signon_realm =
net::AuthCache::HttpKey(dialog_form.origin, *auth_info_);
password_manager_input->push_back(dialog_form);
// Set the password form for the handler (by copy).
handler_->set_password_form(dialog_form);
}
// Info about who/where/what is asking for authentication.
scoped_refptr<net::AuthChallengeInfo> auth_info_;
// Where to send the authentication when obtained.
// This is owned by the ResourceDispatcherHost that invoked us.
LoginHandlerImpl* handler_;
DISALLOW_EVIL_CONSTRUCTORS(LoginDialogTask);
};
// ----------------------------------------------------------------------------
// Public API
LoginHandler* CreateLoginPrompt(net::AuthChallengeInfo* auth_info,
URLRequest* request,
MessageLoop* ui_loop) {
LoginHandlerImpl* handler = new LoginHandlerImpl(request, ui_loop);
ui_loop->PostTask(FROM_HERE, new LoginDialogTask(auth_info, handler));
return handler;
}
<|endoftext|> |
<commit_before>// Copyright (c) 2009 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/basictypes.h"
#include "base/file_path.h"
#include "base/platform_thread.h"
#include "base/string_util.h"
#include "chrome/test/ui/ui_test.h"
#include "net/base/net_util.h"
class MediaTest : public UITest {
protected:
void PlayMedia(const char* tag, const char* media_file) {
FilePath test_file(test_data_directory_);
test_file = test_file.AppendASCII("/media/player.html");
GURL player_gurl = net::FilePathToFileURL(test_file);
std::string url = StringPrintf("%s?%s=%s",
player_gurl.spec().c_str(),
tag,
media_file);
NavigateToURL(GURL(url));
// Allow the media file to be loaded.
const std::wstring kPlaying = L"PLAYING";
const std::wstring kFailed = L"FAILED";
const std::wstring kError = L"ERROR";
for (int i = 0; i < 10; ++i) {
PlatformThread::Sleep(sleep_timeout_ms());
const std::wstring& title = GetActiveTabTitle();
if (title == kPlaying || title == kFailed ||
StartsWith(title, kError, true))
break;
}
EXPECT_EQ(kPlaying, GetActiveTabTitle());
}
void PlayAudio(const char* url) {
PlayMedia("audio", url);
}
void PlayVideo(const char* url) {
PlayMedia("video", url);
}
};
TEST_F(MediaTest, DISABLED_VideoBearH264) {
PlayVideo("bear.mp4");
}
<commit_msg>Enable a ui test that plays video without audio stream TEST=MediaTest.VideoBearSilentTheora BUG=16012<commit_after>// Copyright (c) 2009 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/basictypes.h"
#include "base/file_path.h"
#include "base/platform_thread.h"
#include "base/string_util.h"
#include "chrome/test/ui/ui_test.h"
#include "net/base/net_util.h"
class MediaTest : public UITest {
protected:
void PlayMedia(const char* tag, const char* media_file) {
FilePath test_file(test_data_directory_);
test_file = test_file.AppendASCII("/media/player.html");
GURL player_gurl = net::FilePathToFileURL(test_file);
std::string url = StringPrintf("%s?%s=%s",
player_gurl.spec().c_str(),
tag,
media_file);
NavigateToURL(GURL(url));
// Allow the media file to be loaded.
const std::wstring kPlaying = L"PLAYING";
const std::wstring kFailed = L"FAILED";
const std::wstring kError = L"ERROR";
for (int i = 0; i < 10; ++i) {
PlatformThread::Sleep(sleep_timeout_ms());
const std::wstring& title = GetActiveTabTitle();
if (title == kPlaying || title == kFailed ||
StartsWith(title, kError, true))
break;
}
EXPECT_EQ(kPlaying, GetActiveTabTitle());
}
void PlayAudio(const char* url) {
PlayMedia("audio", url);
}
void PlayVideo(const char* url) {
PlayMedia("video", url);
}
};
// <video> and <audio> only works stably on Windows.
#if defined(OS_WIN)
// TODO(hclam): The following test is disabled because it contains audio and
// this test doesn't work with audio device.
TEST_F(MediaTest, DISABLED_VideoBearH264) {
PlayVideo("bear.mp4");
}
TEST_F(MediaTest, VideoBearSilentTheora) {
PlayVideo("bear_silent.ogv");
}
#endif
<|endoftext|> |
<commit_before>/*=========================================================================
*
* Copyright RTK Consortium
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0.txt
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
*=========================================================================*/
#include "rtkTestConfiguration.h"
#include "rtkfdk_ggo.h"
#include "rtkGgoFunctions.h"
#include "rtkConfiguration.h"
#include "rtkThreeDCircularProjectionGeometryXMLFile.h"
#include "rtkProjectionsReader.h"
#include "rtkDisplacedDetectorImageFilter.h"
#include "rtkParkerShortScanImageFilter.h"
#include "rtkFDKConeBeamReconstructionFilter.h"
#if CUDA_FOUND
# include "rtkCudaFDKConeBeamReconstructionFilter.h"
#endif
#if OPENCL_FOUND
# include "rtkOpenCLFDKConeBeamReconstructionFilter.h"
#endif
#include "rtkFDKWarpBackProjectionImageFilter.h"
#include "rtkCyclicDeformationImageFilter.h"
#include <itkRegularExpressionSeriesFileNames.h>
#include <itkStreamingImageFilter.h>
#include <itkImageFileWriter.h>
int main(int argc, char * argv[])
{
GGO(rtkfdk, args_info);
typedef float OutputPixelType;
const unsigned int Dimension = 3;
typedef itk::Image< OutputPixelType, Dimension > OutputImageType;
// Generate file names
itk::RegularExpressionSeriesFileNames::Pointer names = itk::RegularExpressionSeriesFileNames::New();
names->SetDirectory(args_info.path_arg);
names->SetNumericSort(false);
names->SetRegularExpression(args_info.regexp_arg);
names->SetSubMatch(0);
if(args_info.verbose_flag)
std::cout << "Regular expression matches "
<< names->GetFileNames().size()
<< " file(s)..."
<< std::endl;
// Projections reader
typedef rtk::ProjectionsReader< OutputImageType > ReaderType;
ReaderType::Pointer reader = ReaderType::New();
reader->SetFileNames( names->GetFileNames() );
TRY_AND_EXIT_ON_ITK_EXCEPTION( reader->GenerateOutputInformation() );
itk::TimeProbe readerProbe;
if(!args_info.lowmem_flag)
{
if(args_info.verbose_flag)
std::cout << "Reading... " << std::flush;
readerProbe.Start();
TRY_AND_EXIT_ON_ITK_EXCEPTION( reader->Update() )
readerProbe.Stop();
if(args_info.verbose_flag)
std::cout << "It took " << readerProbe.GetMean() << ' ' << readerProbe.GetUnit() << std::endl;
}
// Geometry
if(args_info.verbose_flag)
std::cout << "Reading geometry information from "
<< args_info.geometry_arg
<< "..."
<< std::endl;
rtk::ThreeDCircularProjectionGeometryXMLFileReader::Pointer geometryReader;
geometryReader = rtk::ThreeDCircularProjectionGeometryXMLFileReader::New();
geometryReader->SetFilename(args_info.geometry_arg);
TRY_AND_EXIT_ON_ITK_EXCEPTION( geometryReader->GenerateOutputInformation() )
// Displaced detector weighting
typedef rtk::DisplacedDetectorImageFilter< OutputImageType > DDFType;
DDFType::Pointer ddf = DDFType::New();
ddf->SetInput( reader->GetOutput() );
ddf->SetGeometry( geometryReader->GetOutputObject() );
// Short scan image filter
typedef rtk::ParkerShortScanImageFilter< OutputImageType > PSSFType;
PSSFType::Pointer pssf = PSSFType::New();
pssf->SetInput( ddf->GetOutput() );
pssf->SetGeometry( geometryReader->GetOutputObject() );
pssf->InPlaceOff();
// Create reconstructed image
typedef rtk::ConstantImageSource< OutputImageType > ConstantImageSourceType;
ConstantImageSourceType::Pointer constantImageSource = ConstantImageSourceType::New();
rtk::SetConstantImageSourceFromGgo<ConstantImageSourceType, args_info_rtkfdk>(constantImageSource, args_info);
// Motion-compensated objects for the compensation of a cyclic deformation.
// Although these will only be used if the command line options for motion
// compensation are set, we still create the object before hand to avoid auto
// destruction.
typedef itk::Vector<float,3> DVFPixelType;
typedef itk::Image< DVFPixelType, 3 > DVFImageType;
typedef rtk::CyclicDeformationImageFilter< DVFImageType > DeformationType;
typedef itk::ImageFileReader<DeformationType::InputImageType> DVFReaderType;
DVFReaderType::Pointer dvfReader = DVFReaderType::New();
DeformationType::Pointer def = DeformationType::New();
def->SetInput(dvfReader->GetOutput());
typedef rtk::FDKWarpBackProjectionImageFilter<OutputImageType, OutputImageType, DeformationType> WarpBPType;
WarpBPType::Pointer bp = WarpBPType::New();
bp->SetDeformation(def);
bp->SetGeometry( geometryReader->GetOutputObject() );
// This macro sets options for fdk filter which I can not see how to do better
// because TFFTPrecision is not the same, e.g. for CPU and CUDA (SR)
#define SET_FELDKAMP_OPTIONS(f) \
f->SetInput( 0, constantImageSource->GetOutput() ); \
f->SetInput( 1, pssf->GetOutput() ); \
f->SetGeometry( geometryReader->GetOutputObject() ); \
f->GetRampFilter()->SetTruncationCorrection(args_info.pad_arg); \
f->GetRampFilter()->SetHannCutFrequency(args_info.hann_arg); \
f->GetRampFilter()->SetHannCutFrequencyY(args_info.hannY_arg);
// FDK reconstruction filtering
itk::ImageToImageFilter<OutputImageType, OutputImageType>::Pointer feldkamp;
typedef rtk::FDKConeBeamReconstructionFilter< OutputImageType > FDKCPUType;
#if CUDA_FOUND
typedef rtk::CudaFDKConeBeamReconstructionFilter FDKCUDAType;
#endif
#if OPENCL_FOUND
typedef rtk::OpenCLFDKConeBeamReconstructionFilter FDKOPENCLType;
#endif
if(!strcmp(args_info.hardware_arg, "cpu") )
{
feldkamp = FDKCPUType::New();
SET_FELDKAMP_OPTIONS( dynamic_cast<FDKCPUType*>(feldkamp.GetPointer()) );
// Motion compensated CBCT settings
if(args_info.signal_given && args_info.dvf_given)
{
dvfReader->SetFileName(args_info.dvf_arg);
def->SetSignalFilename(args_info.signal_arg);
dynamic_cast<FDKCPUType*>(feldkamp.GetPointer())->SetBackProjectionFilter( bp.GetPointer() );
}
}
else if(!strcmp(args_info.hardware_arg, "cuda") )
{
#if CUDA_FOUND
feldkamp = FDKCUDAType::New();
SET_FELDKAMP_OPTIONS( static_cast<FDKCUDAType*>(feldkamp.GetPointer()) );
#else
std::cerr << "The program has not been compiled with cuda option" << std::endl;
return EXIT_FAILURE;
#endif
}
else if(!strcmp(args_info.hardware_arg, "opencl") )
{
#if OPENCL_FOUND
feldkamp = FDKOPENCLType::New();
SET_FELDKAMP_OPTIONS( static_cast<FDKOPENCLType*>(feldkamp.GetPointer()) );
#else
std::cerr << "The program has not been compiled with opencl option" << std::endl;
return EXIT_FAILURE;
#endif
}
// Streaming depending on streaming capability of writer
typedef itk::StreamingImageFilter<OutputImageType, OutputImageType> StreamerType;
StreamerType::Pointer streamerBP = StreamerType::New();
streamerBP->SetInput( feldkamp->GetOutput() );
streamerBP->SetNumberOfStreamDivisions( args_info.divisions_arg );
// Write
typedef itk::ImageFileWriter< OutputImageType > WriterType;
WriterType::Pointer writer = WriterType::New();
writer->SetFileName( args_info.output_arg );
writer->SetInput( streamerBP->GetOutput() );
if(args_info.verbose_flag)
std::cout << "Reconstructing and writing... " << std::flush;
itk::TimeProbe writerProbe;
writerProbe.Start();
TRY_AND_EXIT_ON_ITK_EXCEPTION( writer->Update() );
writerProbe.Stop();
if(args_info.verbose_flag)
{
std::cout << "It took " << writerProbe.GetMean() << ' ' << readerProbe.GetUnit() << std::endl;
if(!strcmp(args_info.hardware_arg, "cpu") )
static_cast<FDKCPUType* >(feldkamp.GetPointer())->PrintTiming(std::cout);
#if CUDA_FOUND
else if(!strcmp(args_info.hardware_arg, "cuda") )
static_cast<FDKCUDAType*>(feldkamp.GetPointer())->PrintTiming(std::cout);
#endif
#if OPENCL_FOUND
else if(!strcmp(args_info.hardware_arg, "opencl") )
static_cast<FDKOPENCLType*>(feldkamp.GetPointer())->PrintTiming(std::cout);
#endif
std::cout << std::endl;
}
return EXIT_SUCCESS;
}
<commit_msg>Was not compiling with BUILD_TESTING=OFF<commit_after>/*=========================================================================
*
* Copyright RTK Consortium
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0.txt
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
*=========================================================================*/
#include "rtkfdk_ggo.h"
#include "rtkGgoFunctions.h"
#include "rtkConfiguration.h"
#include "rtkThreeDCircularProjectionGeometryXMLFile.h"
#include "rtkProjectionsReader.h"
#include "rtkDisplacedDetectorImageFilter.h"
#include "rtkParkerShortScanImageFilter.h"
#include "rtkFDKConeBeamReconstructionFilter.h"
#if CUDA_FOUND
# include "rtkCudaFDKConeBeamReconstructionFilter.h"
#endif
#if OPENCL_FOUND
# include "rtkOpenCLFDKConeBeamReconstructionFilter.h"
#endif
#include "rtkFDKWarpBackProjectionImageFilter.h"
#include "rtkCyclicDeformationImageFilter.h"
#include <itkRegularExpressionSeriesFileNames.h>
#include <itkStreamingImageFilter.h>
#include <itkImageFileWriter.h>
int main(int argc, char * argv[])
{
GGO(rtkfdk, args_info);
typedef float OutputPixelType;
const unsigned int Dimension = 3;
typedef itk::Image< OutputPixelType, Dimension > OutputImageType;
// Generate file names
itk::RegularExpressionSeriesFileNames::Pointer names = itk::RegularExpressionSeriesFileNames::New();
names->SetDirectory(args_info.path_arg);
names->SetNumericSort(false);
names->SetRegularExpression(args_info.regexp_arg);
names->SetSubMatch(0);
if(args_info.verbose_flag)
std::cout << "Regular expression matches "
<< names->GetFileNames().size()
<< " file(s)..."
<< std::endl;
// Projections reader
typedef rtk::ProjectionsReader< OutputImageType > ReaderType;
ReaderType::Pointer reader = ReaderType::New();
reader->SetFileNames( names->GetFileNames() );
TRY_AND_EXIT_ON_ITK_EXCEPTION( reader->GenerateOutputInformation() );
itk::TimeProbe readerProbe;
if(!args_info.lowmem_flag)
{
if(args_info.verbose_flag)
std::cout << "Reading... " << std::flush;
readerProbe.Start();
TRY_AND_EXIT_ON_ITK_EXCEPTION( reader->Update() )
readerProbe.Stop();
if(args_info.verbose_flag)
std::cout << "It took " << readerProbe.GetMean() << ' ' << readerProbe.GetUnit() << std::endl;
}
// Geometry
if(args_info.verbose_flag)
std::cout << "Reading geometry information from "
<< args_info.geometry_arg
<< "..."
<< std::endl;
rtk::ThreeDCircularProjectionGeometryXMLFileReader::Pointer geometryReader;
geometryReader = rtk::ThreeDCircularProjectionGeometryXMLFileReader::New();
geometryReader->SetFilename(args_info.geometry_arg);
TRY_AND_EXIT_ON_ITK_EXCEPTION( geometryReader->GenerateOutputInformation() )
// Displaced detector weighting
typedef rtk::DisplacedDetectorImageFilter< OutputImageType > DDFType;
DDFType::Pointer ddf = DDFType::New();
ddf->SetInput( reader->GetOutput() );
ddf->SetGeometry( geometryReader->GetOutputObject() );
// Short scan image filter
typedef rtk::ParkerShortScanImageFilter< OutputImageType > PSSFType;
PSSFType::Pointer pssf = PSSFType::New();
pssf->SetInput( ddf->GetOutput() );
pssf->SetGeometry( geometryReader->GetOutputObject() );
pssf->InPlaceOff();
// Create reconstructed image
typedef rtk::ConstantImageSource< OutputImageType > ConstantImageSourceType;
ConstantImageSourceType::Pointer constantImageSource = ConstantImageSourceType::New();
rtk::SetConstantImageSourceFromGgo<ConstantImageSourceType, args_info_rtkfdk>(constantImageSource, args_info);
// Motion-compensated objects for the compensation of a cyclic deformation.
// Although these will only be used if the command line options for motion
// compensation are set, we still create the object before hand to avoid auto
// destruction.
typedef itk::Vector<float,3> DVFPixelType;
typedef itk::Image< DVFPixelType, 3 > DVFImageType;
typedef rtk::CyclicDeformationImageFilter< DVFImageType > DeformationType;
typedef itk::ImageFileReader<DeformationType::InputImageType> DVFReaderType;
DVFReaderType::Pointer dvfReader = DVFReaderType::New();
DeformationType::Pointer def = DeformationType::New();
def->SetInput(dvfReader->GetOutput());
typedef rtk::FDKWarpBackProjectionImageFilter<OutputImageType, OutputImageType, DeformationType> WarpBPType;
WarpBPType::Pointer bp = WarpBPType::New();
bp->SetDeformation(def);
bp->SetGeometry( geometryReader->GetOutputObject() );
// This macro sets options for fdk filter which I can not see how to do better
// because TFFTPrecision is not the same, e.g. for CPU and CUDA (SR)
#define SET_FELDKAMP_OPTIONS(f) \
f->SetInput( 0, constantImageSource->GetOutput() ); \
f->SetInput( 1, pssf->GetOutput() ); \
f->SetGeometry( geometryReader->GetOutputObject() ); \
f->GetRampFilter()->SetTruncationCorrection(args_info.pad_arg); \
f->GetRampFilter()->SetHannCutFrequency(args_info.hann_arg); \
f->GetRampFilter()->SetHannCutFrequencyY(args_info.hannY_arg);
// FDK reconstruction filtering
itk::ImageToImageFilter<OutputImageType, OutputImageType>::Pointer feldkamp;
typedef rtk::FDKConeBeamReconstructionFilter< OutputImageType > FDKCPUType;
#if CUDA_FOUND
typedef rtk::CudaFDKConeBeamReconstructionFilter FDKCUDAType;
#endif
#if OPENCL_FOUND
typedef rtk::OpenCLFDKConeBeamReconstructionFilter FDKOPENCLType;
#endif
if(!strcmp(args_info.hardware_arg, "cpu") )
{
feldkamp = FDKCPUType::New();
SET_FELDKAMP_OPTIONS( dynamic_cast<FDKCPUType*>(feldkamp.GetPointer()) );
// Motion compensated CBCT settings
if(args_info.signal_given && args_info.dvf_given)
{
dvfReader->SetFileName(args_info.dvf_arg);
def->SetSignalFilename(args_info.signal_arg);
dynamic_cast<FDKCPUType*>(feldkamp.GetPointer())->SetBackProjectionFilter( bp.GetPointer() );
}
}
else if(!strcmp(args_info.hardware_arg, "cuda") )
{
#if CUDA_FOUND
feldkamp = FDKCUDAType::New();
SET_FELDKAMP_OPTIONS( static_cast<FDKCUDAType*>(feldkamp.GetPointer()) );
#else
std::cerr << "The program has not been compiled with cuda option" << std::endl;
return EXIT_FAILURE;
#endif
}
else if(!strcmp(args_info.hardware_arg, "opencl") )
{
#if OPENCL_FOUND
feldkamp = FDKOPENCLType::New();
SET_FELDKAMP_OPTIONS( static_cast<FDKOPENCLType*>(feldkamp.GetPointer()) );
#else
std::cerr << "The program has not been compiled with opencl option" << std::endl;
return EXIT_FAILURE;
#endif
}
// Streaming depending on streaming capability of writer
typedef itk::StreamingImageFilter<OutputImageType, OutputImageType> StreamerType;
StreamerType::Pointer streamerBP = StreamerType::New();
streamerBP->SetInput( feldkamp->GetOutput() );
streamerBP->SetNumberOfStreamDivisions( args_info.divisions_arg );
// Write
typedef itk::ImageFileWriter< OutputImageType > WriterType;
WriterType::Pointer writer = WriterType::New();
writer->SetFileName( args_info.output_arg );
writer->SetInput( streamerBP->GetOutput() );
if(args_info.verbose_flag)
std::cout << "Reconstructing and writing... " << std::flush;
itk::TimeProbe writerProbe;
writerProbe.Start();
TRY_AND_EXIT_ON_ITK_EXCEPTION( writer->Update() );
writerProbe.Stop();
if(args_info.verbose_flag)
{
std::cout << "It took " << writerProbe.GetMean() << ' ' << readerProbe.GetUnit() << std::endl;
if(!strcmp(args_info.hardware_arg, "cpu") )
static_cast<FDKCPUType* >(feldkamp.GetPointer())->PrintTiming(std::cout);
#if CUDA_FOUND
else if(!strcmp(args_info.hardware_arg, "cuda") )
static_cast<FDKCUDAType*>(feldkamp.GetPointer())->PrintTiming(std::cout);
#endif
#if OPENCL_FOUND
else if(!strcmp(args_info.hardware_arg, "opencl") )
static_cast<FDKOPENCLType*>(feldkamp.GetPointer())->PrintTiming(std::cout);
#endif
std::cout << std::endl;
}
return EXIT_SUCCESS;
}
<|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/file_util.h"
#include "base/path_service.h"
#include "build/build_config.h"
#include "chrome/common/chrome_switches.h"
#include "chrome/test/automation/tab_proxy.h"
#include "chrome/test/ui/ui_test.h"
#include "net/base/net_util.h"
namespace {
// Platform-specific filename relative to the chrome executable.
#if defined(OS_WIN)
const wchar_t library_name[] = L"ppapi_tests.dll";
#elif defined(OS_MACOSX)
const char library_name[] = "ppapi_tests.plugin";
#elif defined(OS_POSIX)
const char library_name[] = "libppapi_tests.so";
#endif
} // namespace
class PPAPITest : public UITest {
public:
PPAPITest() {
// Append the switch to register the pepper plugin.
// library name = <out dir>/<test_name>.<library_extension>
// MIME type = application/x-ppapi-<test_name>
FilePath plugin_dir;
PathService::Get(base::DIR_EXE, &plugin_dir);
FilePath plugin_lib = plugin_dir.Append(library_name);
EXPECT_TRUE(file_util::PathExists(plugin_lib));
#if defined(OS_WIN)
std::wstring pepper_plugin = plugin_lib.value();
#else
std::wstring pepper_plugin = UTF8ToWide(plugin_lib.value());
#endif
pepper_plugin.append(L";application/x-ppapi-tests");
launch_arguments_.AppendSwitchWithValue(switches::kRegisterPepperPlugins,
pepper_plugin);
// The test sends us the result via a cookie.
launch_arguments_.AppendSwitch(switches::kEnableFileCookies);
}
void RunTest(const FilePath::StringType& test_file_name) {
FilePath test_path;
PathService::Get(base::DIR_SOURCE_ROOT, &test_path);
test_path = test_path.Append(FILE_PATH_LITERAL("third_party"));
test_path = test_path.Append(FILE_PATH_LITERAL("ppapi"));
test_path = test_path.Append(FILE_PATH_LITERAL("tests"));
test_path = test_path.Append(test_file_name);
// Sanity check the file name.
EXPECT_TRUE(file_util::PathExists(test_path));
GURL test_url = net::FilePathToFileURL(test_path);
scoped_refptr<TabProxy> tab(GetActiveTab());
ASSERT_TRUE(tab.get());
ASSERT_TRUE(tab->NavigateToURL(test_url));
std::string escaped_value =
WaitUntilCookieNonEmpty(tab.get(), test_url,
"COMPLETION_COOKIE", action_max_timeout_ms());
EXPECT_STREQ("PASS", escaped_value.c_str());
}
};
#if defined(OS_WIN)
TEST_F(PPAPITest, DeviceContext2D) {
#else
// TODO(brettw) currently fails on Mac & Linux 64 for unknown reasons.
TEST_F(PPAPITest, DISABLED_DeviceContext2D) {
#endif
RunTest(FILE_PATH_LITERAL("test_device_context_2d.html"));
}
#if defined(OS_MACOSX)
// TODO(brettw) this fails on Mac for unknown reasons.
TEST_F(PPAPITest, DISABLED_ImageData) {
#else
TEST_F(PPAPITest, ImageData) {
#endif
RunTest(FILE_PATH_LITERAL("test_image_data.html"));
}
<commit_msg>Disable PPAPITest.DeviceContext2D on Win as well. It failed on multiple win bots:<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/file_util.h"
#include "base/path_service.h"
#include "build/build_config.h"
#include "chrome/common/chrome_switches.h"
#include "chrome/test/automation/tab_proxy.h"
#include "chrome/test/ui/ui_test.h"
#include "net/base/net_util.h"
namespace {
// Platform-specific filename relative to the chrome executable.
#if defined(OS_WIN)
const wchar_t library_name[] = L"ppapi_tests.dll";
#elif defined(OS_MACOSX)
const char library_name[] = "ppapi_tests.plugin";
#elif defined(OS_POSIX)
const char library_name[] = "libppapi_tests.so";
#endif
} // namespace
class PPAPITest : public UITest {
public:
PPAPITest() {
// Append the switch to register the pepper plugin.
// library name = <out dir>/<test_name>.<library_extension>
// MIME type = application/x-ppapi-<test_name>
FilePath plugin_dir;
PathService::Get(base::DIR_EXE, &plugin_dir);
FilePath plugin_lib = plugin_dir.Append(library_name);
EXPECT_TRUE(file_util::PathExists(plugin_lib));
#if defined(OS_WIN)
std::wstring pepper_plugin = plugin_lib.value();
#else
std::wstring pepper_plugin = UTF8ToWide(plugin_lib.value());
#endif
pepper_plugin.append(L";application/x-ppapi-tests");
launch_arguments_.AppendSwitchWithValue(switches::kRegisterPepperPlugins,
pepper_plugin);
// The test sends us the result via a cookie.
launch_arguments_.AppendSwitch(switches::kEnableFileCookies);
}
void RunTest(const FilePath::StringType& test_file_name) {
FilePath test_path;
PathService::Get(base::DIR_SOURCE_ROOT, &test_path);
test_path = test_path.Append(FILE_PATH_LITERAL("third_party"));
test_path = test_path.Append(FILE_PATH_LITERAL("ppapi"));
test_path = test_path.Append(FILE_PATH_LITERAL("tests"));
test_path = test_path.Append(test_file_name);
// Sanity check the file name.
EXPECT_TRUE(file_util::PathExists(test_path));
GURL test_url = net::FilePathToFileURL(test_path);
scoped_refptr<TabProxy> tab(GetActiveTab());
ASSERT_TRUE(tab.get());
ASSERT_TRUE(tab->NavigateToURL(test_url));
std::string escaped_value =
WaitUntilCookieNonEmpty(tab.get(), test_url,
"COMPLETION_COOKIE", action_max_timeout_ms());
EXPECT_STREQ("PASS", escaped_value.c_str());
}
};
// TODO(brettw) fails on Mac, Linux 64 & Windows for unknown reasons.
TEST_F(PPAPITest, DISABLED_DeviceContext2D) {
RunTest(FILE_PATH_LITERAL("test_device_context_2d.html"));
}
#if defined(OS_MACOSX)
// TODO(brettw) this fails on Mac for unknown reasons.
TEST_F(PPAPITest, DISABLED_ImageData) {
#else
TEST_F(PPAPITest, ImageData) {
#endif
RunTest(FILE_PATH_LITERAL("test_image_data.html"));
}
<|endoftext|> |
<commit_before>// Copyright (c) 2009 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/string_util.h"
#include "chrome/browser/worker_host/worker_service.h"
#include "chrome/common/chrome_switches.h"
#include "chrome/test/automation/browser_proxy.h"
#include "chrome/test/automation/tab_proxy.h"
#include "chrome/test/ui/ui_layout_test.h"
static const char kTestCompleteCookie[] = "status";
static const char kTestCompleteSuccess[] = "OK";
class WorkerTest : public UILayoutTest {
protected:
virtual ~WorkerTest() { }
void RunTest(const std::wstring& test_case) {
scoped_refptr<TabProxy> tab(GetActiveTab());
ASSERT_TRUE(tab.get());
GURL url = GetTestUrl(L"workers", test_case);
ASSERT_TRUE(tab->NavigateToURL(url));
std::string value = WaitUntilCookieNonEmpty(tab.get(), url,
kTestCompleteCookie, kTestIntervalMs, kTestWaitTimeoutMs);
ASSERT_STREQ(kTestCompleteSuccess, value.c_str());
}
bool WaitForProcessCountToBe(int tabs, int workers) {
// The 1 is for the browser process.
int number_of_processes = 1 + workers +
(UITest::in_process_renderer() ? 0 : tabs);
#if defined(OS_LINUX)
// On Linux, we also have a zygote process and a sandbox host process.
number_of_processes += 2;
#endif
int cur_process_count;
for (int i = 0; i < 10; ++i) {
cur_process_count = GetBrowserProcessCount();
if (cur_process_count == number_of_processes)
return true;
PlatformThread::Sleep(sleep_timeout_ms() / 10);
}
EXPECT_EQ(number_of_processes, cur_process_count);
return false;
}
};
TEST_F(WorkerTest, SingleWorker) {
RunTest(L"single_worker.html");
}
TEST_F(WorkerTest, MultipleWorkers) {
RunTest(L"multi_worker.html");
}
#if defined(OS_LINUX)
#define WorkerFastLayoutTests DISABLED_WorkerFastLayoutTests
#endif
TEST_F(WorkerTest, WorkerFastLayoutTests) {
static const char* kLayoutTestFiles[] = {
"stress-js-execution.html",
"use-machine-stack.html",
"worker-call.html",
"worker-cloneport.html",
"worker-close.html",
"worker-constructor.html",
"worker-context-gc.html",
"worker-context-multi-port.html",
"worker-event-listener.html",
"worker-gc.html",
// worker-lifecycle.html relies on layoutTestController.workerThreadCount
// which is not currently implemented.
// "worker-lifecycle.html",
"worker-location.html",
"worker-messageport.html",
// Disabled after r27089 (WebKit merge), http://crbug.com/22947
// "worker-messageport-gc.html",
"worker-multi-port.html",
"worker-navigator.html",
"worker-replace-global-constructor.html",
"worker-replace-self.html",
"worker-script-error.html",
"worker-terminate.html",
"worker-timeout.html"
};
FilePath fast_test_dir;
fast_test_dir = fast_test_dir.AppendASCII("LayoutTests");
fast_test_dir = fast_test_dir.AppendASCII("fast");
FilePath worker_test_dir;
worker_test_dir = worker_test_dir.AppendASCII("workers");
InitializeForLayoutTest(fast_test_dir, worker_test_dir, false);
// Worker tests also rely on common files in js/resources.
FilePath js_dir = fast_test_dir.AppendASCII("js");
FilePath resource_dir;
resource_dir = resource_dir.AppendASCII("resources");
AddResourceForLayoutTest(js_dir, resource_dir);
for (size_t i = 0; i < arraysize(kLayoutTestFiles); ++i)
RunLayoutTest(kLayoutTestFiles[i], false);
}
#if defined(OS_WIN)
// http://crbug.com/27636 - incorrect URL_MISMATCH exceptions sometimes get
// generated on the windows try bots.
#define SharedWorkerFastLayoutTests DISABLED_SharedWorkerFastLayoutTests
#endif
TEST_F(WorkerTest, SharedWorkerFastLayoutTests) {
static const char* kLayoutTestFiles[] = {
"shared-worker-constructor.html",
"shared-worker-context-gc.html",
"shared-worker-event-listener.html",
"shared-worker-exception.html",
"shared-worker-gc.html",
// Lifecycle tests rely on layoutTestController.workerThreadCount which is
// not currently implemented.
//"shared-worker-frame-lifecycle.html",
//"shared-worker-lifecycle.html",
"shared-worker-load-error.html",
"shared-worker-location.html",
"shared-worker-name.html",
"shared-worker-navigator.html",
"shared-worker-replace-global-constructor.html",
"shared-worker-replace-self.html",
"shared-worker-script-error.html",
"shared-worker-shared.html",
"shared-worker-simple.html",
};
FilePath fast_test_dir;
fast_test_dir = fast_test_dir.AppendASCII("LayoutTests");
fast_test_dir = fast_test_dir.AppendASCII("fast");
FilePath worker_test_dir;
worker_test_dir = worker_test_dir.AppendASCII("workers");
InitializeForLayoutTest(fast_test_dir, worker_test_dir, false);
// Worker tests also rely on common files in js/resources.
FilePath js_dir = fast_test_dir.AppendASCII("js");
FilePath resource_dir;
resource_dir = resource_dir.AppendASCII("resources");
AddResourceForLayoutTest(js_dir, resource_dir);
for (size_t i = 0; i < arraysize(kLayoutTestFiles); ++i)
RunLayoutTest(kLayoutTestFiles[i], false);
}
TEST_F(WorkerTest, WorkerHttpLayoutTests) {
static const char* kLayoutTestFiles[] = {
"shared-worker-importScripts.html",
"shared-worker-redirect.html",
// flakey? BUG 16934 "text-encoding.html",
#if defined(OS_WIN)
// Fails on the mac (and linux?):
// http://code.google.com/p/chromium/issues/detail?id=22599
"worker-importScripts.html",
#endif
"worker-redirect.html",
};
FilePath http_test_dir;
http_test_dir = http_test_dir.AppendASCII("LayoutTests");
http_test_dir = http_test_dir.AppendASCII("http");
http_test_dir = http_test_dir.AppendASCII("tests");
FilePath worker_test_dir;
worker_test_dir = worker_test_dir.AppendASCII("workers");
InitializeForLayoutTest(http_test_dir, worker_test_dir, true);
StartHttpServer(new_http_root_dir_);
for (size_t i = 0; i < arraysize(kLayoutTestFiles); ++i)
RunLayoutTest(kLayoutTestFiles[i], true);
StopHttpServer();
}
TEST_F(WorkerTest, WorkerXhrHttpLayoutTests) {
static const char* kLayoutTestFiles[] = {
"abort-exception-assert.html",
#if defined(OS_WIN)
// Fails on the mac (and linux?):
// http://code.google.com/p/chromium/issues/detail?id=22599
"close.html",
#endif
// These tests (and the shared-worker versions below) are disabled due to
// limitations in lighttpd (doesn't handle all of the HTTP methods).
//"methods-async.html",
//"methods.html",
"shared-worker-close.html",
// Disabled due to limitations in lighttpd (does not handle methods other
// than GET/PUT/POST).
//"shared-worker-methods-async.html",
//"shared-worker-methods.html",
"shared-worker-xhr-file-not-found.html",
"xmlhttprequest-file-not-found.html"
};
FilePath http_test_dir;
http_test_dir = http_test_dir.AppendASCII("LayoutTests");
http_test_dir = http_test_dir.AppendASCII("http");
http_test_dir = http_test_dir.AppendASCII("tests");
FilePath worker_test_dir;
worker_test_dir = worker_test_dir.AppendASCII("xmlhttprequest");
worker_test_dir = worker_test_dir.AppendASCII("workers");
InitializeForLayoutTest(http_test_dir, worker_test_dir, true);
StartHttpServer(new_http_root_dir_);
for (size_t i = 0; i < arraysize(kLayoutTestFiles); ++i)
RunLayoutTest(kLayoutTestFiles[i], true);
StopHttpServer();
}
TEST_F(WorkerTest, MessagePorts) {
static const char* kLayoutTestFiles[] = {
"message-channel-gc.html",
"message-channel-gc-2.html",
"message-channel-gc-3.html",
"message-channel-gc-4.html",
"message-port.html",
"message-port-clone.html",
"message-port-constructor-for-deleted-document.html",
"message-port-deleted-document.html",
"message-port-deleted-frame.html",
"message-port-inactive-document.html",
"message-port-multi.html",
"message-port-no-wrapper.html",
// Only works with run-webkit-tests --leaks.
//"message-channel-listener-circular-ownership.html",
};
FilePath fast_test_dir;
fast_test_dir = fast_test_dir.AppendASCII("LayoutTests");
fast_test_dir = fast_test_dir.AppendASCII("fast");
FilePath worker_test_dir;
worker_test_dir = worker_test_dir.AppendASCII("events");
InitializeForLayoutTest(fast_test_dir, worker_test_dir, false);
// MessagePort tests also rely on common files in js/resources.
FilePath js_dir = fast_test_dir.AppendASCII("js");
FilePath resource_dir;
resource_dir = resource_dir.AppendASCII("resources");
AddResourceForLayoutTest(js_dir, resource_dir);
for (size_t i = 0; i < arraysize(kLayoutTestFiles); ++i)
RunLayoutTest(kLayoutTestFiles[i], false);
}
// Disable LimitPerPage on Linux. Seems to work on Mac though:
// http://code.google.com/p/chromium/issues/detail?id=22608
#if !defined(OS_LINUX)
// This test fails after WebKit merge 49414:49432. (BUG=24652)
TEST_F(WorkerTest, LimitPerPage) {
int max_workers_per_tab = WorkerService::kMaxWorkersPerTabWhenSeparate;
GURL url = GetTestUrl(L"workers", L"many_workers.html");
url = GURL(url.spec() + StringPrintf("?count=%d", max_workers_per_tab + 1));
scoped_refptr<TabProxy> tab(GetActiveTab());
ASSERT_TRUE(tab.get());
ASSERT_TRUE(tab->NavigateToURL(url));
EXPECT_EQ(max_workers_per_tab + 1 + (UITest::in_process_renderer() ? 0 : 1),
UITest::GetBrowserProcessCount());
}
#endif
TEST_F(WorkerTest, LimitTotal) {
int max_workers_per_tab = WorkerService::kMaxWorkersPerTabWhenSeparate;
int total_workers = WorkerService::kMaxWorkersWhenSeparate;
int tab_count = (total_workers / max_workers_per_tab) + 1;
GURL url = GetTestUrl(L"workers", L"many_workers.html");
url = GURL(url.spec() + StringPrintf("?count=%d", max_workers_per_tab));
scoped_refptr<TabProxy> tab(GetActiveTab());
ASSERT_TRUE(tab.get());
ASSERT_TRUE(tab->NavigateToURL(url));
scoped_refptr<BrowserProxy> window(automation()->GetBrowserWindow(0));
for (int i = 1; i < tab_count; ++i)
window->AppendTab(url);
// Check that we didn't create more than the max number of workers.
ASSERT_TRUE(WaitForProcessCountToBe(tab_count, total_workers));
// Now close a page and check that the queued workers were started.
tab->NavigateToURL(GetTestUrl(L"google", L"google.html"));
ASSERT_TRUE(WaitForProcessCountToBe(tab_count, total_workers));
}
<commit_msg>Mark worker tests as flaky on mac.<commit_after>// Copyright (c) 2009 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/string_util.h"
#include "chrome/browser/worker_host/worker_service.h"
#include "chrome/common/chrome_switches.h"
#include "chrome/test/automation/browser_proxy.h"
#include "chrome/test/automation/tab_proxy.h"
#include "chrome/test/ui/ui_layout_test.h"
static const char kTestCompleteCookie[] = "status";
static const char kTestCompleteSuccess[] = "OK";
class WorkerTest : public UILayoutTest {
protected:
virtual ~WorkerTest() { }
void RunTest(const std::wstring& test_case) {
scoped_refptr<TabProxy> tab(GetActiveTab());
ASSERT_TRUE(tab.get());
GURL url = GetTestUrl(L"workers", test_case);
ASSERT_TRUE(tab->NavigateToURL(url));
std::string value = WaitUntilCookieNonEmpty(tab.get(), url,
kTestCompleteCookie, kTestIntervalMs, kTestWaitTimeoutMs);
ASSERT_STREQ(kTestCompleteSuccess, value.c_str());
}
bool WaitForProcessCountToBe(int tabs, int workers) {
// The 1 is for the browser process.
int number_of_processes = 1 + workers +
(UITest::in_process_renderer() ? 0 : tabs);
#if defined(OS_LINUX)
// On Linux, we also have a zygote process and a sandbox host process.
number_of_processes += 2;
#endif
int cur_process_count;
for (int i = 0; i < 10; ++i) {
cur_process_count = GetBrowserProcessCount();
if (cur_process_count == number_of_processes)
return true;
PlatformThread::Sleep(sleep_timeout_ms() / 10);
}
EXPECT_EQ(number_of_processes, cur_process_count);
return false;
}
};
TEST_F(WorkerTest, SingleWorker) {
RunTest(L"single_worker.html");
}
TEST_F(WorkerTest, MultipleWorkers) {
RunTest(L"multi_worker.html");
}
#if defined(OS_LINUX)
#define WorkerFastLayoutTests DISABLED_WorkerFastLayoutTests
#elif defined(OS_MACOSX)
#define WorkerFastLayoutTests FLAKY_WorkerFastLayoutTests
#endif
TEST_F(WorkerTest, WorkerFastLayoutTests) {
static const char* kLayoutTestFiles[] = {
"stress-js-execution.html",
"use-machine-stack.html",
"worker-call.html",
"worker-cloneport.html",
"worker-close.html",
"worker-constructor.html",
"worker-context-gc.html",
"worker-context-multi-port.html",
"worker-event-listener.html",
"worker-gc.html",
// worker-lifecycle.html relies on layoutTestController.workerThreadCount
// which is not currently implemented.
// "worker-lifecycle.html",
"worker-location.html",
"worker-messageport.html",
// Disabled after r27089 (WebKit merge), http://crbug.com/22947
// "worker-messageport-gc.html",
"worker-multi-port.html",
"worker-navigator.html",
"worker-replace-global-constructor.html",
"worker-replace-self.html",
"worker-script-error.html",
"worker-terminate.html",
"worker-timeout.html"
};
FilePath fast_test_dir;
fast_test_dir = fast_test_dir.AppendASCII("LayoutTests");
fast_test_dir = fast_test_dir.AppendASCII("fast");
FilePath worker_test_dir;
worker_test_dir = worker_test_dir.AppendASCII("workers");
InitializeForLayoutTest(fast_test_dir, worker_test_dir, false);
// Worker tests also rely on common files in js/resources.
FilePath js_dir = fast_test_dir.AppendASCII("js");
FilePath resource_dir;
resource_dir = resource_dir.AppendASCII("resources");
AddResourceForLayoutTest(js_dir, resource_dir);
for (size_t i = 0; i < arraysize(kLayoutTestFiles); ++i)
RunLayoutTest(kLayoutTestFiles[i], false);
}
#if defined(OS_WIN)
// http://crbug.com/27636 - incorrect URL_MISMATCH exceptions sometimes get
// generated on the windows try bots.
#define SharedWorkerFastLayoutTests DISABLED_SharedWorkerFastLayoutTests
#elif defined(OS_MACOSX)
#define SharedWorkerFastLayoutTests FLAKY_SharedWorkerFastLayoutTests
#endif
TEST_F(WorkerTest, SharedWorkerFastLayoutTests) {
static const char* kLayoutTestFiles[] = {
"shared-worker-constructor.html",
"shared-worker-context-gc.html",
"shared-worker-event-listener.html",
"shared-worker-exception.html",
"shared-worker-gc.html",
// Lifecycle tests rely on layoutTestController.workerThreadCount which is
// not currently implemented.
//"shared-worker-frame-lifecycle.html",
//"shared-worker-lifecycle.html",
"shared-worker-load-error.html",
"shared-worker-location.html",
"shared-worker-name.html",
"shared-worker-navigator.html",
"shared-worker-replace-global-constructor.html",
"shared-worker-replace-self.html",
"shared-worker-script-error.html",
"shared-worker-shared.html",
"shared-worker-simple.html",
};
FilePath fast_test_dir;
fast_test_dir = fast_test_dir.AppendASCII("LayoutTests");
fast_test_dir = fast_test_dir.AppendASCII("fast");
FilePath worker_test_dir;
worker_test_dir = worker_test_dir.AppendASCII("workers");
InitializeForLayoutTest(fast_test_dir, worker_test_dir, false);
// Worker tests also rely on common files in js/resources.
FilePath js_dir = fast_test_dir.AppendASCII("js");
FilePath resource_dir;
resource_dir = resource_dir.AppendASCII("resources");
AddResourceForLayoutTest(js_dir, resource_dir);
for (size_t i = 0; i < arraysize(kLayoutTestFiles); ++i)
RunLayoutTest(kLayoutTestFiles[i], false);
}
TEST_F(WorkerTest, WorkerHttpLayoutTests) {
static const char* kLayoutTestFiles[] = {
"shared-worker-importScripts.html",
"shared-worker-redirect.html",
// flakey? BUG 16934 "text-encoding.html",
#if defined(OS_WIN)
// Fails on the mac (and linux?):
// http://code.google.com/p/chromium/issues/detail?id=22599
"worker-importScripts.html",
#endif
"worker-redirect.html",
};
FilePath http_test_dir;
http_test_dir = http_test_dir.AppendASCII("LayoutTests");
http_test_dir = http_test_dir.AppendASCII("http");
http_test_dir = http_test_dir.AppendASCII("tests");
FilePath worker_test_dir;
worker_test_dir = worker_test_dir.AppendASCII("workers");
InitializeForLayoutTest(http_test_dir, worker_test_dir, true);
StartHttpServer(new_http_root_dir_);
for (size_t i = 0; i < arraysize(kLayoutTestFiles); ++i)
RunLayoutTest(kLayoutTestFiles[i], true);
StopHttpServer();
}
TEST_F(WorkerTest, WorkerXhrHttpLayoutTests) {
static const char* kLayoutTestFiles[] = {
"abort-exception-assert.html",
#if defined(OS_WIN)
// Fails on the mac (and linux?):
// http://code.google.com/p/chromium/issues/detail?id=22599
"close.html",
#endif
// These tests (and the shared-worker versions below) are disabled due to
// limitations in lighttpd (doesn't handle all of the HTTP methods).
//"methods-async.html",
//"methods.html",
"shared-worker-close.html",
// Disabled due to limitations in lighttpd (does not handle methods other
// than GET/PUT/POST).
//"shared-worker-methods-async.html",
//"shared-worker-methods.html",
"shared-worker-xhr-file-not-found.html",
"xmlhttprequest-file-not-found.html"
};
FilePath http_test_dir;
http_test_dir = http_test_dir.AppendASCII("LayoutTests");
http_test_dir = http_test_dir.AppendASCII("http");
http_test_dir = http_test_dir.AppendASCII("tests");
FilePath worker_test_dir;
worker_test_dir = worker_test_dir.AppendASCII("xmlhttprequest");
worker_test_dir = worker_test_dir.AppendASCII("workers");
InitializeForLayoutTest(http_test_dir, worker_test_dir, true);
StartHttpServer(new_http_root_dir_);
for (size_t i = 0; i < arraysize(kLayoutTestFiles); ++i)
RunLayoutTest(kLayoutTestFiles[i], true);
StopHttpServer();
}
TEST_F(WorkerTest, MessagePorts) {
static const char* kLayoutTestFiles[] = {
"message-channel-gc.html",
"message-channel-gc-2.html",
"message-channel-gc-3.html",
"message-channel-gc-4.html",
"message-port.html",
"message-port-clone.html",
"message-port-constructor-for-deleted-document.html",
"message-port-deleted-document.html",
"message-port-deleted-frame.html",
"message-port-inactive-document.html",
"message-port-multi.html",
"message-port-no-wrapper.html",
// Only works with run-webkit-tests --leaks.
//"message-channel-listener-circular-ownership.html",
};
FilePath fast_test_dir;
fast_test_dir = fast_test_dir.AppendASCII("LayoutTests");
fast_test_dir = fast_test_dir.AppendASCII("fast");
FilePath worker_test_dir;
worker_test_dir = worker_test_dir.AppendASCII("events");
InitializeForLayoutTest(fast_test_dir, worker_test_dir, false);
// MessagePort tests also rely on common files in js/resources.
FilePath js_dir = fast_test_dir.AppendASCII("js");
FilePath resource_dir;
resource_dir = resource_dir.AppendASCII("resources");
AddResourceForLayoutTest(js_dir, resource_dir);
for (size_t i = 0; i < arraysize(kLayoutTestFiles); ++i)
RunLayoutTest(kLayoutTestFiles[i], false);
}
// Disable LimitPerPage on Linux. Seems to work on Mac though:
// http://code.google.com/p/chromium/issues/detail?id=22608
#if !defined(OS_LINUX)
// This test fails after WebKit merge 49414:49432. (BUG=24652)
TEST_F(WorkerTest, LimitPerPage) {
int max_workers_per_tab = WorkerService::kMaxWorkersPerTabWhenSeparate;
GURL url = GetTestUrl(L"workers", L"many_workers.html");
url = GURL(url.spec() + StringPrintf("?count=%d", max_workers_per_tab + 1));
scoped_refptr<TabProxy> tab(GetActiveTab());
ASSERT_TRUE(tab.get());
ASSERT_TRUE(tab->NavigateToURL(url));
EXPECT_EQ(max_workers_per_tab + 1 + (UITest::in_process_renderer() ? 0 : 1),
UITest::GetBrowserProcessCount());
}
#endif
TEST_F(WorkerTest, LimitTotal) {
int max_workers_per_tab = WorkerService::kMaxWorkersPerTabWhenSeparate;
int total_workers = WorkerService::kMaxWorkersWhenSeparate;
int tab_count = (total_workers / max_workers_per_tab) + 1;
GURL url = GetTestUrl(L"workers", L"many_workers.html");
url = GURL(url.spec() + StringPrintf("?count=%d", max_workers_per_tab));
scoped_refptr<TabProxy> tab(GetActiveTab());
ASSERT_TRUE(tab.get());
ASSERT_TRUE(tab->NavigateToURL(url));
scoped_refptr<BrowserProxy> window(automation()->GetBrowserWindow(0));
for (int i = 1; i < tab_count; ++i)
window->AppendTab(url);
// Check that we didn't create more than the max number of workers.
ASSERT_TRUE(WaitForProcessCountToBe(tab_count, total_workers));
// Now close a page and check that the queued workers were started.
tab->NavigateToURL(GetTestUrl(L"google", L"google.html"));
ASSERT_TRUE(WaitForProcessCountToBe(tab_count, total_workers));
}
<|endoftext|> |
<commit_before>/*
* Copyright (C) 2018 German Aerospace Center (DLR/SC)
*
* Created: 2018-08-06 Martin Siggel <Martin.Siggel@dlr.de>
*
* 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 "CTiglPointsToBSplineInterpolation.h"
#include "CTiglError.h"
#include "CTiglBSplineAlgorithms.h"
#include <BSplCLib.hxx>
#include <math_Gauss.hxx>
#include <GeomConvert.hxx>
#include <Geom_TrimmedCurve.hxx>
#include <algorithm>
#include <cassert>
namespace
{
Handle(TColStd_HArray1OfReal) toArray(const std::vector<double>& vector)
{
Handle(TColStd_HArray1OfReal) array = new TColStd_HArray1OfReal(1, static_cast<int>(vector.size()));
int ipos = 1;
for (std::vector<double>::const_iterator it = vector.begin(); it != vector.end(); ++it, ipos++) {
array->SetValue(ipos, *it);
}
return array;
}
void clamp(Handle(Geom_BSplineCurve) & curve, double min, double max)
{
Handle(Geom_Curve) c = new Geom_TrimmedCurve(curve, min, max);
curve = GeomConvert::CurveToBSplineCurve(c);
}
} // namespace
namespace tigl
{
CTiglPointsToBSplineInterpolation::CTiglPointsToBSplineInterpolation(const Handle(TColgp_HArray1OfPnt) & points,
unsigned int maxDegree, bool continuousIfClosed)
: m_pnts(points)
, m_degree(maxDegree)
, m_C2Continuous(continuousIfClosed)
{
m_params = CTiglBSplineAlgorithms::computeParamsBSplineCurve(points);
}
CTiglPointsToBSplineInterpolation::CTiglPointsToBSplineInterpolation(const Handle(TColgp_HArray1OfPnt) & points,
const std::vector<double>& parameters,
unsigned int maxDegree, bool continuousIfClosed)
: m_pnts(points)
, m_params(parameters)
, m_degree(maxDegree)
, m_C2Continuous(continuousIfClosed)
{
if (m_params.size() != m_pnts->Length()) {
throw CTiglError("Number of parameters and points don't match in CTiglPointsToBSplineInterpolation");
}
}
Handle(Geom_BSplineCurve) CTiglPointsToBSplineInterpolation::Curve() const
{
int degree = static_cast<int>(Degree());
std::vector<double> params = m_params;
std::vector<double> knots =
CTiglBSplineAlgorithms::knotsFromCurveParameters(params, static_cast<unsigned int>(degree), isClosed());
if (isClosed()) {
// we remove the last parameter, since it is implicitly
// included by wrapping the control points
params.pop_back();
}
math_Matrix bsplMat =
CTiglBSplineAlgorithms::bsplineBasisMat(degree, toArray(knots)->Array1(), toArray(params)->Array1());
// build left hand side of the linear system
int nParams = static_cast<int>(params.size());
math_Matrix lhs(1, nParams, 1, nParams, 0.);
for (int iCol = 1; iCol <= nParams; ++iCol) {
lhs.SetCol(iCol, bsplMat.Col(iCol));
}
if (isClosed()) {
// sets the continuity constraints for closed curves on the left hand side if requested
// by wrapping around the control points
// This is a trick to make the matrix square and enforce the endpoint conditions
for (int iCol = 1; iCol <= degree; ++iCol) {
lhs.SetCol(iCol, lhs.Col(iCol) + bsplMat.Col(nParams + iCol));
}
}
// right hand side
math_Vector rhsx(1, nParams, 0.);
math_Vector rhsy(1, nParams, 0.);
math_Vector rhsz(1, nParams, 0.);
for (int i = 1; i <= nParams; ++i) {
const gp_Pnt& p = m_pnts->Value(i);
rhsx(i) = p.X();
rhsy(i) = p.Y();
rhsz(i) = p.Z();
}
math_Gauss solver(lhs);
math_Vector cp_x(1, nParams);
math_Vector cp_y(1, nParams);
math_Vector cp_z(1, nParams);
solver.Solve(rhsx, cp_x);
if (!solver.IsDone()) {
throw CTiglError("Singular Matrix", TIGL_MATH_ERROR);
}
solver.Solve(rhsy, cp_y);
if (!solver.IsDone()) {
throw CTiglError("Singular Matrix", TIGL_MATH_ERROR);
}
solver.Solve(rhsz, cp_z);
if (!solver.IsDone()) {
throw CTiglError("Singular Matrix", TIGL_MATH_ERROR);
}
int nCtrPnts = static_cast<int>(m_params.size());
if (isClosed()) {
nCtrPnts += degree - 1;
}
if (needsShifting()) {
nCtrPnts += 1;
}
TColgp_Array1OfPnt poles(1, nCtrPnts);
for (Standard_Integer icp = 1; icp <= nParams; ++icp) {
gp_Pnt pnt(cp_x.Value(icp), cp_y.Value(icp), cp_z.Value(icp));
poles.SetValue(icp, pnt);
}
if (isClosed()) {
// wrap control points
for (Standard_Integer icp = 1; icp <= degree; ++icp) {
gp_Pnt pnt(cp_x.Value(icp), cp_y.Value(icp), cp_z.Value(icp));
poles.SetValue(nParams + icp, pnt);
}
}
if (needsShifting()) {
// add a new control point and knot
knots.push_back(knots.back() + knots[2 * degree + 1] - knots[2 * degree]);
poles.SetValue(nParams + degree + 1, poles.Value(degree + 1));
// shift back the knots
for (size_t iknot = 0; iknot < knots.size(); ++iknot) {
knots[iknot] -= params[0];
}
}
Handle(TColStd_HArray1OfReal) occFlatKnots = toArray(knots);
int knotsLen = BSplCLib::KnotsLength(occFlatKnots->Array1());
TColStd_Array1OfReal occKnots(1, knotsLen);
TColStd_Array1OfInteger occMults(1, knotsLen);
BSplCLib::Knots(occFlatKnots->Array1(), occKnots, occMults);
Handle(Geom_BSplineCurve) result = new Geom_BSplineCurve(poles, occKnots, occMults, degree, false);
// clamp bspline
if (isClosed()) {
clamp(result, m_params.front(), m_params.back());
}
return result;
}
double CTiglPointsToBSplineInterpolation::maxDistanceOfBoundingBox(const TColgp_Array1OfPnt& points) const
{
double maxDistance = 0.;
for (int i = points.Lower(); i <= points.Upper(); ++i) {
for (int j = points.Lower(); j <= points.Upper(); ++j) {
double dist = points.Value(i).Distance(points.Value(j));
maxDistance = std::max(maxDistance, dist);
}
}
return maxDistance;
}
bool CTiglPointsToBSplineInterpolation::isClosed() const
{
double maxDistance = maxDistanceOfBoundingBox(m_pnts->Array1());
double error = 1e-6 * maxDistance;
return m_pnts->Value(m_pnts->Lower()).IsEqual(m_pnts->Value(m_pnts->Upper()), error) && m_C2Continuous;
}
bool CTiglPointsToBSplineInterpolation::needsShifting() const
{
return (Degree() % 2) == 0 && isClosed();
}
CTiglPointsToBSplineInterpolation::operator Handle(Geom_BSplineCurve)() const
{
return Curve();
}
const std::vector<double>& CTiglPointsToBSplineInterpolation::Parameters() const
{
return m_params;
}
unsigned int CTiglPointsToBSplineInterpolation::Degree() const
{
int maxDegree = m_pnts->Length() - 1;
if (isClosed()) {
maxDegree -= 1;
}
int degree = std::min(maxDegree, m_degree);
assert(degree > 0);
return static_cast<unsigned int>(degree);
}
} // namespace tigl
<commit_msg>More error checking in CTiglPointsToBSplineInterpolation<commit_after>/*
* Copyright (C) 2018 German Aerospace Center (DLR/SC)
*
* Created: 2018-08-06 Martin Siggel <Martin.Siggel@dlr.de>
*
* 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 "CTiglPointsToBSplineInterpolation.h"
#include "CTiglError.h"
#include "CTiglBSplineAlgorithms.h"
#include <BSplCLib.hxx>
#include <math_Gauss.hxx>
#include <GeomConvert.hxx>
#include <Geom_TrimmedCurve.hxx>
#include <algorithm>
#include <cassert>
namespace
{
Handle(TColStd_HArray1OfReal) toArray(const std::vector<double>& vector)
{
Handle(TColStd_HArray1OfReal) array = new TColStd_HArray1OfReal(1, static_cast<int>(vector.size()));
int ipos = 1;
for (std::vector<double>::const_iterator it = vector.begin(); it != vector.end(); ++it, ipos++) {
array->SetValue(ipos, *it);
}
return array;
}
void clamp(Handle(Geom_BSplineCurve) & curve, double min, double max)
{
Handle(Geom_Curve) c = new Geom_TrimmedCurve(curve, min, max);
curve = GeomConvert::CurveToBSplineCurve(c);
}
} // namespace
namespace tigl
{
CTiglPointsToBSplineInterpolation::CTiglPointsToBSplineInterpolation(const Handle(TColgp_HArray1OfPnt) & points,
unsigned int maxDegree, bool continuousIfClosed)
: m_pnts(points)
, m_degree(static_cast<int>(maxDegree))
, m_C2Continuous(continuousIfClosed)
{
m_params = CTiglBSplineAlgorithms::computeParamsBSplineCurve(points);
if (maxDegree < 1) {
throw CTiglError("Degree must be larger than 1 in CTiglPointsToBSplineInterpolation!");
}
if (points.IsNull()) {
throw CTiglError("No points given in CTiglPointsToBSplineInterpolation", TIGL_NULL_POINTER);
}
if (points->Length() < 2) {
throw CTiglError("Too few points in CTiglPointsToBSplineInterpolation", TIGL_MATH_ERROR);
}
}
CTiglPointsToBSplineInterpolation::CTiglPointsToBSplineInterpolation(const Handle(TColgp_HArray1OfPnt) & points,
const std::vector<double>& parameters,
unsigned int maxDegree, bool continuousIfClosed)
: m_pnts(points)
, m_params(parameters)
, m_degree(static_cast<int>(maxDegree))
, m_C2Continuous(continuousIfClosed)
{
if (static_cast<int>(m_params.size()) != m_pnts->Length()) {
throw CTiglError("Number of parameters and points don't match in CTiglPointsToBSplineInterpolation");
}
if (maxDegree < 1) {
throw CTiglError("Degree must be larger than 1 in CTiglPointsToBSplineInterpolation!");
}
if (points.IsNull()) {
throw CTiglError("No points given in CTiglPointsToBSplineInterpolation", TIGL_NULL_POINTER);
}
if (points->Length() < 2) {
throw CTiglError("Too few points in CTiglPointsToBSplineInterpolation", TIGL_MATH_ERROR);
}
}
Handle(Geom_BSplineCurve) CTiglPointsToBSplineInterpolation::Curve() const
{
int degree = static_cast<int>(Degree());
std::vector<double> params = m_params;
std::vector<double> knots =
CTiglBSplineAlgorithms::knotsFromCurveParameters(params, static_cast<unsigned int>(degree), isClosed());
if (isClosed()) {
// we remove the last parameter, since it is implicitly
// included by wrapping the control points
params.pop_back();
}
math_Matrix bsplMat =
CTiglBSplineAlgorithms::bsplineBasisMat(degree, toArray(knots)->Array1(), toArray(params)->Array1());
// build left hand side of the linear system
int nParams = static_cast<int>(params.size());
math_Matrix lhs(1, nParams, 1, nParams, 0.);
for (int iCol = 1; iCol <= nParams; ++iCol) {
lhs.SetCol(iCol, bsplMat.Col(iCol));
}
if (isClosed()) {
// sets the continuity constraints for closed curves on the left hand side if requested
// by wrapping around the control points
// This is a trick to make the matrix square and enforce the endpoint conditions
for (int iCol = 1; iCol <= degree; ++iCol) {
lhs.SetCol(iCol, lhs.Col(iCol) + bsplMat.Col(nParams + iCol));
}
}
// right hand side
math_Vector rhsx(1, nParams, 0.);
math_Vector rhsy(1, nParams, 0.);
math_Vector rhsz(1, nParams, 0.);
for (int i = 1; i <= nParams; ++i) {
const gp_Pnt& p = m_pnts->Value(i);
rhsx(i) = p.X();
rhsy(i) = p.Y();
rhsz(i) = p.Z();
}
math_Gauss solver(lhs);
math_Vector cp_x(1, nParams);
math_Vector cp_y(1, nParams);
math_Vector cp_z(1, nParams);
solver.Solve(rhsx, cp_x);
if (!solver.IsDone()) {
throw CTiglError("Singular Matrix", TIGL_MATH_ERROR);
}
solver.Solve(rhsy, cp_y);
if (!solver.IsDone()) {
throw CTiglError("Singular Matrix", TIGL_MATH_ERROR);
}
solver.Solve(rhsz, cp_z);
if (!solver.IsDone()) {
throw CTiglError("Singular Matrix", TIGL_MATH_ERROR);
}
int nCtrPnts = static_cast<int>(m_params.size());
if (isClosed()) {
nCtrPnts += degree - 1;
}
if (needsShifting()) {
nCtrPnts += 1;
}
TColgp_Array1OfPnt poles(1, nCtrPnts);
for (Standard_Integer icp = 1; icp <= nParams; ++icp) {
gp_Pnt pnt(cp_x.Value(icp), cp_y.Value(icp), cp_z.Value(icp));
poles.SetValue(icp, pnt);
}
if (isClosed()) {
// wrap control points
for (Standard_Integer icp = 1; icp <= degree; ++icp) {
gp_Pnt pnt(cp_x.Value(icp), cp_y.Value(icp), cp_z.Value(icp));
poles.SetValue(nParams + icp, pnt);
}
}
if (needsShifting()) {
// add a new control point and knot
size_t deg = static_cast<size_t>(degree);
knots.push_back(knots.back() + knots[2 * deg + 1] - knots[2 * deg]);
poles.SetValue(nParams + degree + 1, poles.Value(degree + 1));
// shift back the knots
for (size_t iknot = 0; iknot < knots.size(); ++iknot) {
knots[iknot] -= params[0];
}
}
Handle(TColStd_HArray1OfReal) occFlatKnots = toArray(knots);
int knotsLen = BSplCLib::KnotsLength(occFlatKnots->Array1());
TColStd_Array1OfReal occKnots(1, knotsLen);
TColStd_Array1OfInteger occMults(1, knotsLen);
BSplCLib::Knots(occFlatKnots->Array1(), occKnots, occMults);
Handle(Geom_BSplineCurve) result = new Geom_BSplineCurve(poles, occKnots, occMults, degree, false);
// clamp bspline
if (isClosed()) {
clamp(result, m_params.front(), m_params.back());
}
return result;
}
double CTiglPointsToBSplineInterpolation::maxDistanceOfBoundingBox(const TColgp_Array1OfPnt& points) const
{
double maxDistance = 0.;
for (int i = points.Lower(); i <= points.Upper(); ++i) {
for (int j = points.Lower(); j <= points.Upper(); ++j) {
double dist = points.Value(i).Distance(points.Value(j));
maxDistance = std::max(maxDistance, dist);
}
}
return maxDistance;
}
bool CTiglPointsToBSplineInterpolation::isClosed() const
{
double maxDistance = maxDistanceOfBoundingBox(m_pnts->Array1());
double error = 1e-6 * maxDistance;
return m_pnts->Value(m_pnts->Lower()).IsEqual(m_pnts->Value(m_pnts->Upper()), error) && m_C2Continuous;
}
bool CTiglPointsToBSplineInterpolation::needsShifting() const
{
return (Degree() % 2) == 0 && isClosed();
}
CTiglPointsToBSplineInterpolation::operator Handle(Geom_BSplineCurve)() const
{
return Curve();
}
const std::vector<double>& CTiglPointsToBSplineInterpolation::Parameters() const
{
return m_params;
}
unsigned int CTiglPointsToBSplineInterpolation::Degree() const
{
int maxDegree = m_pnts->Length() - 1;
if (isClosed()) {
maxDegree -= 1;
}
int degree = std::min(maxDegree, m_degree);
assert(degree > 0);
return static_cast<unsigned int>(degree);
}
} // namespace tigl
<|endoftext|> |
<commit_before>// Copyright (c) 2009 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/worker_host/worker_service.h"
#include "chrome/test/automation/browser_proxy.h"
#include "chrome/test/automation/tab_proxy.h"
#include "chrome/test/ui/ui_layout_test.h"
static const char kTestCompleteCookie[] = "status";
static const char kTestCompleteSuccess[] = "OK";
class WorkerTest : public UILayoutTest {
protected:
virtual ~WorkerTest() { }
void RunTest(const std::wstring& test_case) {
scoped_refptr<TabProxy> tab(GetActiveTab());
ASSERT_TRUE(tab.get());
GURL url = GetTestUrl(L"workers", test_case);
ASSERT_TRUE(tab->NavigateToURL(url));
std::string value = WaitUntilCookieNonEmpty(tab.get(), url,
kTestCompleteCookie, kTestIntervalMs, kTestWaitTimeoutMs);
ASSERT_STREQ(kTestCompleteSuccess, value.c_str());
}
};
TEST_F(WorkerTest, SingleWorker) {
RunTest(L"single_worker.html");
}
TEST_F(WorkerTest, MultipleWorkers) {
RunTest(L"multi_worker.html");
}
TEST_F(WorkerTest, DISABLED_WorkerFastLayoutTests) {
static const char* kLayoutTestFiles[] = {
"stress-js-execution.html",
#if defined(OS_WIN)
// Workers don't properly initialize the V8 stack guard.
// (http://code.google.com/p/chromium/issues/detail?id=21653).
"use-machine-stack.html",
#endif
"worker-call.html",
// Disabled because cloning ports are too slow in Chromium to meet the
// thresholds in this test.
// http://code.google.com/p/chromium/issues/detail?id=22780
// "worker-cloneport.html",
"worker-close.html",
"worker-constructor.html",
"worker-context-gc.html",
"worker-context-multi-port.html",
"worker-event-listener.html",
"worker-gc.html",
// worker-lifecycle.html relies on layoutTestController.workerThreadCount
// which is not currently implemented.
// "worker-lifecycle.html",
"worker-location.html",
"worker-messageport.html",
// Disabled after r27089 (WebKit merge), http://crbug.com/22947
// "worker-messageport-gc.html",
"worker-multi-port.html",
"worker-navigator.html",
"worker-replace-global-constructor.html",
"worker-replace-self.html",
"worker-script-error.html",
"worker-terminate.html",
"worker-timeout.html"
};
FilePath fast_test_dir;
fast_test_dir = fast_test_dir.AppendASCII("LayoutTests");
fast_test_dir = fast_test_dir.AppendASCII("fast");
FilePath worker_test_dir;
worker_test_dir = worker_test_dir.AppendASCII("workers");
InitializeForLayoutTest(fast_test_dir, worker_test_dir, false);
// Worker tests also rely on common files in js/resources.
FilePath js_dir = fast_test_dir.AppendASCII("js");
FilePath resource_dir;
resource_dir = resource_dir.AppendASCII("resources");
AddResourceForLayoutTest(js_dir, resource_dir);
for (size_t i = 0; i < arraysize(kLayoutTestFiles); ++i)
RunLayoutTest(kLayoutTestFiles[i], false);
}
TEST_F(WorkerTest, WorkerHttpLayoutTests) {
static const char* kLayoutTestFiles[] = {
// flakey? BUG 16934 "text-encoding.html",
#if defined(OS_WIN)
// Fails on the mac (and linux?):
// http://code.google.com/p/chromium/issues/detail?id=22599
"worker-importScripts.html",
#endif
"worker-redirect.html",
};
FilePath http_test_dir;
http_test_dir = http_test_dir.AppendASCII("LayoutTests");
http_test_dir = http_test_dir.AppendASCII("http");
http_test_dir = http_test_dir.AppendASCII("tests");
FilePath worker_test_dir;
worker_test_dir = worker_test_dir.AppendASCII("workers");
InitializeForLayoutTest(http_test_dir, worker_test_dir, true);
StartHttpServer(new_http_root_dir_);
for (size_t i = 0; i < arraysize(kLayoutTestFiles); ++i)
RunLayoutTest(kLayoutTestFiles[i], true);
StopHttpServer();
}
TEST_F(WorkerTest, WorkerXhrHttpLayoutTests) {
static const char* kLayoutTestFiles[] = {
"abort-exception-assert.html",
#if defined(OS_WIN)
// Fails on the mac (and linux?):
// http://code.google.com/p/chromium/issues/detail?id=22599
"close.html",
#endif
//"methods-async.html",
//"methods.html",
"xmlhttprequest-file-not-found.html"
};
FilePath http_test_dir;
http_test_dir = http_test_dir.AppendASCII("LayoutTests");
http_test_dir = http_test_dir.AppendASCII("http");
http_test_dir = http_test_dir.AppendASCII("tests");
FilePath worker_test_dir;
worker_test_dir = worker_test_dir.AppendASCII("xmlhttprequest");
worker_test_dir = worker_test_dir.AppendASCII("workers");
InitializeForLayoutTest(http_test_dir, worker_test_dir, true);
StartHttpServer(new_http_root_dir_);
for (size_t i = 0; i < arraysize(kLayoutTestFiles); ++i)
RunLayoutTest(kLayoutTestFiles[i], true);
StopHttpServer();
}
TEST_F(WorkerTest, MessagePorts) {
static const char* kLayoutTestFiles[] = {
"message-channel-gc.html",
"message-channel-gc-2.html",
"message-channel-gc-3.html",
"message-channel-gc-4.html",
"message-port.html",
"message-port-clone.html",
"message-port-constructor-for-deleted-document.html",
"message-port-deleted-document.html",
"message-port-deleted-frame.html",
"message-port-inactive-document.html",
"message-port-multi.html",
"message-port-no-wrapper.html",
// Only works with run-webkit-tests --leaks.
//"message-channel-listener-circular-ownership.html",
};
FilePath fast_test_dir;
fast_test_dir = fast_test_dir.AppendASCII("LayoutTests");
fast_test_dir = fast_test_dir.AppendASCII("fast");
FilePath worker_test_dir;
worker_test_dir = worker_test_dir.AppendASCII("events");
InitializeForLayoutTest(fast_test_dir, worker_test_dir, false);
// MessagePort tests also rely on common files in js/resources.
FilePath js_dir = fast_test_dir.AppendASCII("js");
FilePath resource_dir;
resource_dir = resource_dir.AppendASCII("resources");
AddResourceForLayoutTest(js_dir, resource_dir);
for (size_t i = 0; i < arraysize(kLayoutTestFiles); ++i)
RunLayoutTest(kLayoutTestFiles[i], false);
}
// Disable LimitPerPage on Linux. Seems to work on Mac though:
// http://code.google.com/p/chromium/issues/detail?id=22608
#if !defined(OS_LINUX)
TEST_F(WorkerTest, LimitPerPage) {
int max_workers_per_tab = WorkerService::kMaxWorkersPerTabWhenSeparate;
GURL url = GetTestUrl(L"workers", L"many_workers.html");
url = GURL(url.spec() + StringPrintf("?count=%d", max_workers_per_tab + 1));
scoped_refptr<TabProxy> tab(GetActiveTab());
ASSERT_TRUE(tab.get());
ASSERT_TRUE(tab->NavigateToURL(url));
EXPECT_EQ(max_workers_per_tab + 1 + (UITest::in_process_renderer() ? 0 : 1),
UITest::GetBrowserProcessCount());
}
#endif
// Disable LimitTotal on Linux and Mac.
// http://code.google.com/p/chromium/issues/detail?id=22608
#if defined(OS_WIN)
TEST_F(WorkerTest, LimitTotal) {
int max_workers_per_tab = WorkerService::kMaxWorkersPerTabWhenSeparate;
int total_workers = WorkerService::kMaxWorkersWhenSeparate;
int tab_count = (total_workers / max_workers_per_tab) + 1;
GURL url = GetTestUrl(L"workers", L"many_workers.html");
url = GURL(url.spec() + StringPrintf("?count=%d", max_workers_per_tab));
scoped_refptr<TabProxy> tab(GetActiveTab());
ASSERT_TRUE(tab.get());
ASSERT_TRUE(tab->NavigateToURL(url));
scoped_refptr<BrowserProxy> window(automation()->GetBrowserWindow(0));
for (int i = 1; i < tab_count; ++i)
window->AppendTab(url);
// Check that we didn't create more than the max number of workers.
EXPECT_EQ(total_workers + 1 + (UITest::in_process_renderer() ? 0 : tab_count),
UITest::GetBrowserProcessCount());
// Now close the first tab and check that the queued workers were started.
tab->Close(true);
tab->NavigateToURL(GetTestUrl(L"google", L"google.html"));
EXPECT_EQ(total_workers + 1 + (UITest::in_process_renderer() ? 0 : tab_count),
UITest::GetBrowserProcessCount());
}
#endif
<commit_msg>More fixes for WorkerFastLayoutTests: enable them on Mac and Win, reintroduce Linux guard that was removed by http://codereview.chromium.org/220034, since the test that fails on all platforms was disabled earlier: http://codereview.chromium.org/219033 BUG=none TEST=none TBR=jshin Review URL: http://codereview.chromium.org/224022<commit_after>// Copyright (c) 2009 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/worker_host/worker_service.h"
#include "chrome/test/automation/browser_proxy.h"
#include "chrome/test/automation/tab_proxy.h"
#include "chrome/test/ui/ui_layout_test.h"
static const char kTestCompleteCookie[] = "status";
static const char kTestCompleteSuccess[] = "OK";
class WorkerTest : public UILayoutTest {
protected:
virtual ~WorkerTest() { }
void RunTest(const std::wstring& test_case) {
scoped_refptr<TabProxy> tab(GetActiveTab());
ASSERT_TRUE(tab.get());
GURL url = GetTestUrl(L"workers", test_case);
ASSERT_TRUE(tab->NavigateToURL(url));
std::string value = WaitUntilCookieNonEmpty(tab.get(), url,
kTestCompleteCookie, kTestIntervalMs, kTestWaitTimeoutMs);
ASSERT_STREQ(kTestCompleteSuccess, value.c_str());
}
};
TEST_F(WorkerTest, SingleWorker) {
RunTest(L"single_worker.html");
}
TEST_F(WorkerTest, MultipleWorkers) {
RunTest(L"multi_worker.html");
}
// WorkerFastLayoutTests works on the linux try servers, but fails on the
// build bots.
#if defined(OS_LINUX)
#define WorkerFastLayoutTests DISABLED_WorkerFastLayoutTests
#endif
TEST_F(WorkerTest, WorkerFastLayoutTests) {
static const char* kLayoutTestFiles[] = {
"stress-js-execution.html",
#if defined(OS_WIN)
// Workers don't properly initialize the V8 stack guard.
// (http://code.google.com/p/chromium/issues/detail?id=21653).
"use-machine-stack.html",
#endif
"worker-call.html",
// Disabled because cloning ports are too slow in Chromium to meet the
// thresholds in this test.
// http://code.google.com/p/chromium/issues/detail?id=22780
// "worker-cloneport.html",
"worker-close.html",
"worker-constructor.html",
"worker-context-gc.html",
"worker-context-multi-port.html",
"worker-event-listener.html",
"worker-gc.html",
// worker-lifecycle.html relies on layoutTestController.workerThreadCount
// which is not currently implemented.
// "worker-lifecycle.html",
"worker-location.html",
"worker-messageport.html",
// Disabled after r27089 (WebKit merge), http://crbug.com/22947
// "worker-messageport-gc.html",
"worker-multi-port.html",
"worker-navigator.html",
"worker-replace-global-constructor.html",
"worker-replace-self.html",
"worker-script-error.html",
"worker-terminate.html",
"worker-timeout.html"
};
FilePath fast_test_dir;
fast_test_dir = fast_test_dir.AppendASCII("LayoutTests");
fast_test_dir = fast_test_dir.AppendASCII("fast");
FilePath worker_test_dir;
worker_test_dir = worker_test_dir.AppendASCII("workers");
InitializeForLayoutTest(fast_test_dir, worker_test_dir, false);
// Worker tests also rely on common files in js/resources.
FilePath js_dir = fast_test_dir.AppendASCII("js");
FilePath resource_dir;
resource_dir = resource_dir.AppendASCII("resources");
AddResourceForLayoutTest(js_dir, resource_dir);
for (size_t i = 0; i < arraysize(kLayoutTestFiles); ++i)
RunLayoutTest(kLayoutTestFiles[i], false);
}
TEST_F(WorkerTest, WorkerHttpLayoutTests) {
static const char* kLayoutTestFiles[] = {
// flakey? BUG 16934 "text-encoding.html",
#if defined(OS_WIN)
// Fails on the mac (and linux?):
// http://code.google.com/p/chromium/issues/detail?id=22599
"worker-importScripts.html",
#endif
"worker-redirect.html",
};
FilePath http_test_dir;
http_test_dir = http_test_dir.AppendASCII("LayoutTests");
http_test_dir = http_test_dir.AppendASCII("http");
http_test_dir = http_test_dir.AppendASCII("tests");
FilePath worker_test_dir;
worker_test_dir = worker_test_dir.AppendASCII("workers");
InitializeForLayoutTest(http_test_dir, worker_test_dir, true);
StartHttpServer(new_http_root_dir_);
for (size_t i = 0; i < arraysize(kLayoutTestFiles); ++i)
RunLayoutTest(kLayoutTestFiles[i], true);
StopHttpServer();
}
TEST_F(WorkerTest, WorkerXhrHttpLayoutTests) {
static const char* kLayoutTestFiles[] = {
"abort-exception-assert.html",
#if defined(OS_WIN)
// Fails on the mac (and linux?):
// http://code.google.com/p/chromium/issues/detail?id=22599
"close.html",
#endif
//"methods-async.html",
//"methods.html",
"xmlhttprequest-file-not-found.html"
};
FilePath http_test_dir;
http_test_dir = http_test_dir.AppendASCII("LayoutTests");
http_test_dir = http_test_dir.AppendASCII("http");
http_test_dir = http_test_dir.AppendASCII("tests");
FilePath worker_test_dir;
worker_test_dir = worker_test_dir.AppendASCII("xmlhttprequest");
worker_test_dir = worker_test_dir.AppendASCII("workers");
InitializeForLayoutTest(http_test_dir, worker_test_dir, true);
StartHttpServer(new_http_root_dir_);
for (size_t i = 0; i < arraysize(kLayoutTestFiles); ++i)
RunLayoutTest(kLayoutTestFiles[i], true);
StopHttpServer();
}
TEST_F(WorkerTest, MessagePorts) {
static const char* kLayoutTestFiles[] = {
"message-channel-gc.html",
"message-channel-gc-2.html",
"message-channel-gc-3.html",
"message-channel-gc-4.html",
"message-port.html",
"message-port-clone.html",
"message-port-constructor-for-deleted-document.html",
"message-port-deleted-document.html",
"message-port-deleted-frame.html",
"message-port-inactive-document.html",
"message-port-multi.html",
"message-port-no-wrapper.html",
// Only works with run-webkit-tests --leaks.
//"message-channel-listener-circular-ownership.html",
};
FilePath fast_test_dir;
fast_test_dir = fast_test_dir.AppendASCII("LayoutTests");
fast_test_dir = fast_test_dir.AppendASCII("fast");
FilePath worker_test_dir;
worker_test_dir = worker_test_dir.AppendASCII("events");
InitializeForLayoutTest(fast_test_dir, worker_test_dir, false);
// MessagePort tests also rely on common files in js/resources.
FilePath js_dir = fast_test_dir.AppendASCII("js");
FilePath resource_dir;
resource_dir = resource_dir.AppendASCII("resources");
AddResourceForLayoutTest(js_dir, resource_dir);
for (size_t i = 0; i < arraysize(kLayoutTestFiles); ++i)
RunLayoutTest(kLayoutTestFiles[i], false);
}
// Disable LimitPerPage on Linux. Seems to work on Mac though:
// http://code.google.com/p/chromium/issues/detail?id=22608
#if !defined(OS_LINUX)
TEST_F(WorkerTest, LimitPerPage) {
int max_workers_per_tab = WorkerService::kMaxWorkersPerTabWhenSeparate;
GURL url = GetTestUrl(L"workers", L"many_workers.html");
url = GURL(url.spec() + StringPrintf("?count=%d", max_workers_per_tab + 1));
scoped_refptr<TabProxy> tab(GetActiveTab());
ASSERT_TRUE(tab.get());
ASSERT_TRUE(tab->NavigateToURL(url));
EXPECT_EQ(max_workers_per_tab + 1 + (UITest::in_process_renderer() ? 0 : 1),
UITest::GetBrowserProcessCount());
}
#endif
// Disable LimitTotal on Linux and Mac.
// http://code.google.com/p/chromium/issues/detail?id=22608
#if defined(OS_WIN)
TEST_F(WorkerTest, LimitTotal) {
int max_workers_per_tab = WorkerService::kMaxWorkersPerTabWhenSeparate;
int total_workers = WorkerService::kMaxWorkersWhenSeparate;
int tab_count = (total_workers / max_workers_per_tab) + 1;
GURL url = GetTestUrl(L"workers", L"many_workers.html");
url = GURL(url.spec() + StringPrintf("?count=%d", max_workers_per_tab));
scoped_refptr<TabProxy> tab(GetActiveTab());
ASSERT_TRUE(tab.get());
ASSERT_TRUE(tab->NavigateToURL(url));
scoped_refptr<BrowserProxy> window(automation()->GetBrowserWindow(0));
for (int i = 1; i < tab_count; ++i)
window->AppendTab(url);
// Check that we didn't create more than the max number of workers.
EXPECT_EQ(total_workers + 1 + (UITest::in_process_renderer() ? 0 : tab_count),
UITest::GetBrowserProcessCount());
// Now close the first tab and check that the queued workers were started.
tab->Close(true);
tab->NavigateToURL(GetTestUrl(L"google", L"google.html"));
EXPECT_EQ(total_workers + 1 + (UITest::in_process_renderer() ? 0 : tab_count),
UITest::GetBrowserProcessCount());
}
#endif
<|endoftext|> |
<commit_before>// @(#)root/reflex:$Id$
// Author: Stefan Roiser 2004
// Copyright CERN, CH-1211 Geneva 23, 2004-2006, All rights reserved.
//
// Permission to use, copy, modify, and distribute this software for any
// purpose is hereby granted without fee, provided that this copyright and
// permissions notice appear in all copies and derivatives.
//
// This software is provided "as is" without express or implied warranty.
#ifndef REFLEX_BUILD
# define REFLEX_BUILD
#endif
#include "Reflex/internal/MemberBase.h"
#include "Reflex/internal/OwnedMember.h"
#include "Reflex/Scope.h"
#include "Reflex/Type.h"
#include "Reflex/Base.h"
#include "Reflex/Object.h"
#include "Reflex/internal/OwnedPropertyList.h"
#include "Reflex/DictionaryGenerator.h"
#include "Reflex/Tools.h"
#include "Class.h"
//-------------------------------------------------------------------------------
Reflex::MemberBase::MemberBase(const char* name,
const Type& type,
TYPE memberType,
unsigned int modifiers)
//-------------------------------------------------------------------------------
: fType(type, modifiers & (CONST | VOLATILE | REFERENCE), Type::APPEND),
fModifiers(modifiers),
fName(name),
fScope(Scope()),
fMemberType(memberType),
fPropertyList(OwnedPropertyList(new PropertyListImpl())) {
// Construct the dictionary info for a member
fThisMember = new Member(this);
}
//-------------------------------------------------------------------------------
Reflex::MemberBase::~MemberBase() {
//-------------------------------------------------------------------------------
// Destructor.
delete fThisMember;
fPropertyList.Delete();
}
//-------------------------------------------------------------------------------
Reflex::MemberBase::operator
Reflex::Member() const {
//-------------------------------------------------------------------------------
// Conversion operator to Member.
return *fThisMember;
}
//-------------------------------------------------------------------------------
void*
Reflex::MemberBase::CalculateBaseObject(const Object& obj) const {
//-------------------------------------------------------------------------------
// Return the object address a member lives in.
char* mem = (char*) obj.Address();
// check if its a dummy object
Type cl = obj.TypeOf();
// if the object type is not implemented return the Address of the object
if (!cl) {
return mem;
}
if (cl.IsClass()) {
if (DeclaringScope() && (cl.Id() != (dynamic_cast<const Class*>(DeclaringScope().ToScopeBase()))->ThisType().Id())) {
// now we know that the Member type is an inherited one
std::vector<OffsetFunction> basePath = (dynamic_cast<const Class*>(cl.ToTypeBase()))->PathToBase(DeclaringScope());
if (basePath.size()) {
// there is a path described from the object to the class containing the Member
std::vector<OffsetFunction>::iterator pIter;
for (pIter = basePath.begin(); pIter != basePath.end(); ++pIter) {
mem += (*pIter)(mem);
}
} else {
throw RuntimeError(std::string(": ERROR: There is no path available from class ")
+ cl.Name(SCOPED) + " to " + Name(SCOPED));
}
}
} else {
throw RuntimeError(std::string("Object ") + cl.Name(SCOPED) + " does not represent a class");
}
return (void*) mem;
} // CalculateBaseObject
//-------------------------------------------------------------------------------
Reflex::Scope
Reflex::MemberBase::DeclaringScope() const {
//-------------------------------------------------------------------------------
// Return the scope the member lives in.
return fScope;
}
//-------------------------------------------------------------------------------
Reflex::Type
Reflex::MemberBase::DeclaringType() const {
//-------------------------------------------------------------------------------
// Return the type the member lives in.
return DeclaringScope();
}
//-------------------------------------------------------------------------------
std::string
Reflex::MemberBase::MemberTypeAsString() const {
//-------------------------------------------------------------------------------
// Remember type of the member as a string.
switch (fMemberType) {
case DATAMEMBER:
return "DataMember";
break;
case FUNCTIONMEMBER:
return "FunctionMember";
break;
default:
return Reflex::Argv0() + ": ERROR: Member " + Name() +
" has no Species associated";
}
}
//-------------------------------------------------------------------------------
Reflex::PropertyList
Reflex::MemberBase::Properties() const {
//-------------------------------------------------------------------------------
// Return the property list attached to this member.
return fPropertyList;
}
//-------------------------------------------------------------------------------
Reflex::Type
Reflex::MemberBase::TemplateArgumentAt(size_t /* nth */) const {
//-------------------------------------------------------------------------------
// Return the nth template argument (in FunMemTemplInstance)
return Dummy::Type();
}
//-------------------------------------------------------------------------------
void
Reflex::MemberBase::GenerateDict(DictionaryGenerator& /* generator */) const {
//-------------------------------------------------------------------------------
// Generate Dictionary information about itself.
}
<commit_msg>From Josh Kelley: If Reflex::Member::Get is used on an object that's an instance of a typedef to a class, rather than an object that's an instance of a class, it throws a RuntimeError: "Object ... does not represent a class."<commit_after>// @(#)root/reflex:$Id$
// Author: Stefan Roiser 2004
// Copyright CERN, CH-1211 Geneva 23, 2004-2006, All rights reserved.
//
// Permission to use, copy, modify, and distribute this software for any
// purpose is hereby granted without fee, provided that this copyright and
// permissions notice appear in all copies and derivatives.
//
// This software is provided "as is" without express or implied warranty.
#ifndef REFLEX_BUILD
# define REFLEX_BUILD
#endif
#include "Reflex/internal/MemberBase.h"
#include "Reflex/internal/OwnedMember.h"
#include "Reflex/Scope.h"
#include "Reflex/Type.h"
#include "Reflex/Base.h"
#include "Reflex/Object.h"
#include "Reflex/internal/OwnedPropertyList.h"
#include "Reflex/DictionaryGenerator.h"
#include "Reflex/Tools.h"
#include "Class.h"
//-------------------------------------------------------------------------------
Reflex::MemberBase::MemberBase(const char* name,
const Type& type,
TYPE memberType,
unsigned int modifiers)
//-------------------------------------------------------------------------------
: fType(type, modifiers & (CONST | VOLATILE | REFERENCE), Type::APPEND),
fModifiers(modifiers),
fName(name),
fScope(Scope()),
fMemberType(memberType),
fPropertyList(OwnedPropertyList(new PropertyListImpl())) {
// Construct the dictionary info for a member
fThisMember = new Member(this);
}
//-------------------------------------------------------------------------------
Reflex::MemberBase::~MemberBase() {
//-------------------------------------------------------------------------------
// Destructor.
delete fThisMember;
fPropertyList.Delete();
}
//-------------------------------------------------------------------------------
Reflex::MemberBase::operator
Reflex::Member() const {
//-------------------------------------------------------------------------------
// Conversion operator to Member.
return *fThisMember;
}
//-------------------------------------------------------------------------------
void*
Reflex::MemberBase::CalculateBaseObject(const Object& obj) const {
//-------------------------------------------------------------------------------
// Return the object address a member lives in.
char* mem = (char*) obj.Address();
// check if its a dummy object
Type cl = obj.TypeOf();
while (cl && cl.IsTypedef()) {
cl = cl.ToType();
}
// if the object type is not implemented return the Address of the object
if (!cl) {
return mem;
}
if (cl.IsClass()) {
if (DeclaringScope() && (cl.Id() != (dynamic_cast<const Class*>(DeclaringScope().ToScopeBase()))->ThisType().Id())) {
// now we know that the Member type is an inherited one
std::vector<OffsetFunction> basePath = (dynamic_cast<const Class*>(cl.ToTypeBase()))->PathToBase(DeclaringScope());
if (basePath.size()) {
// there is a path described from the object to the class containing the Member
std::vector<OffsetFunction>::iterator pIter;
for (pIter = basePath.begin(); pIter != basePath.end(); ++pIter) {
mem += (*pIter)(mem);
}
} else {
throw RuntimeError(std::string(": ERROR: There is no path available from class ")
+ cl.Name(SCOPED) + " to " + Name(SCOPED));
}
}
} else {
throw RuntimeError(std::string("Object ") + cl.Name(SCOPED) + " does not represent a class");
}
return (void*) mem;
} // CalculateBaseObject
//-------------------------------------------------------------------------------
Reflex::Scope
Reflex::MemberBase::DeclaringScope() const {
//-------------------------------------------------------------------------------
// Return the scope the member lives in.
return fScope;
}
//-------------------------------------------------------------------------------
Reflex::Type
Reflex::MemberBase::DeclaringType() const {
//-------------------------------------------------------------------------------
// Return the type the member lives in.
return DeclaringScope();
}
//-------------------------------------------------------------------------------
std::string
Reflex::MemberBase::MemberTypeAsString() const {
//-------------------------------------------------------------------------------
// Remember type of the member as a string.
switch (fMemberType) {
case DATAMEMBER:
return "DataMember";
break;
case FUNCTIONMEMBER:
return "FunctionMember";
break;
default:
return Reflex::Argv0() + ": ERROR: Member " + Name() +
" has no Species associated";
}
}
//-------------------------------------------------------------------------------
Reflex::PropertyList
Reflex::MemberBase::Properties() const {
//-------------------------------------------------------------------------------
// Return the property list attached to this member.
return fPropertyList;
}
//-------------------------------------------------------------------------------
Reflex::Type
Reflex::MemberBase::TemplateArgumentAt(size_t /* nth */) const {
//-------------------------------------------------------------------------------
// Return the nth template argument (in FunMemTemplInstance)
return Dummy::Type();
}
//-------------------------------------------------------------------------------
void
Reflex::MemberBase::GenerateDict(DictionaryGenerator& /* generator */) const {
//-------------------------------------------------------------------------------
// Generate Dictionary information about itself.
}
<|endoftext|> |
<commit_before>/* IBM_PROLOG_BEGIN_TAG */
/* This is an automatically generated prolog. */
/* */
/* $Source: src/import/generic/memory/lib/utils/endian_utils.H $ */
/* */
/* OpenPOWER HostBoot Project */
/* */
/* Contributors Listed Below - COPYRIGHT 2018,2019 */
/* [+] International Business Machines Corp. */
/* */
/* */
/* Licensed under the Apache License, Version 2.0 (the "License"); */
/* you may not use this file except in compliance with the License. */
/* You may obtain a copy of the License at */
/* */
/* http://www.apache.org/licenses/LICENSE-2.0 */
/* */
/* Unless required by applicable law or agreed to in writing, software */
/* distributed under the License is distributed on an "AS IS" BASIS, */
/* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or */
/* implied. See the License for the specific language governing */
/* permissions and limitations under the License. */
/* */
/* IBM_PROLOG_END_TAG */
///
/// @file endian_utils.H
/// @brief Util functions to help with endianess
///
// *HWP HWP Owner: Ben Gass <bgass@us.ibm.com>
// *HWP HWP Backup: Christian Geddes <crgeddes@us.ibm.com>
// *HWP Team:
// *HWP Level: 2
// *HWP Consumed by: HB:FSP
#ifndef _ENDIAN_UTILS_H_
#define _ENDIAN_UTILS_H_
#include <cstdint>
#include <vector>
#include <generic/memory/lib/utils/shared/mss_generic_consts.H>
namespace mss
{
///
/// @brief Forces native data into LE order
/// @tparam T the data type to process
/// @param[in] i_input inputted data to process
/// @param[in,out] io_data vector to append data to
///
template < typename T >
void forceLE(const T& i_input, std::vector<uint8_t>& io_data)
{
// Temporary variable to process - we'll be doing bit shifts below
T l_temp = i_input;
for(size_t i = 0; i < sizeof(i_input); i++)
{
// Grab the lowe rorder byte and add it to the back of the vector
const uint8_t l_byte = l_temp & 0xFF;
io_data.push_back(l_byte);
// Shift higher byte value into lowest no matter existing endianness
l_temp >>= BITS_PER_BYTE;
}
}
///
/// @brief Forces native data into LE order for an array
/// @tparam T the data type to process
/// @param[in] i_input inputted data to process
/// @param[in] i_size size of the array
/// @param[in,out] io_data vector to append data to
///
template < typename T >
inline void forceLEArray(const T* i_input, const uint64_t i_size, std::vector<uint8_t>& io_data)
{
for(size_t i = 0; i < i_size; i++)
{
forceLE(i_input[i], io_data);
}
}
///
/// @brief Converts LE data into native order
/// @tparam T the data type to output to
/// @param[in] i_input inputted data to process
/// @param[in,out] io_idx current index
/// @param[out] o_data data that has been converted into native endianness
/// @return bool true if passing false if failing
/// @note Real FFDC will be handled outside
///
template < typename T >
bool readLE(const std::vector<uint8_t>& i_input, uint32_t& io_idx, T& o_data)
{
const uint32_t l_sz = static_cast<uint32_t>(sizeof(o_data));
io_idx = l_sz + io_idx;
// Checks that our final index is within the data range
// Note: we decrement the index prior, so equal to is ok
if(io_idx > i_input.size())
{
return false;
}
uint64_t l_idx = io_idx;
o_data = 0;
for(uint64_t i = 0; i < l_sz; i++)
{
l_idx--;
uint8_t v = i_input[l_idx];
o_data <<= BITS_PER_BYTE;
o_data |= v;
}
return true;
}
///
/// @brief Converts LE data into native order
/// @tparam T the data type to output to
/// @param[in] i_input inputted data to process
/// @param[in] i_size size of the array
/// @param[in,out] io_idx current index
/// @param[out] o_data data that has been converted into native endianness
/// @return bool true if passing false if failing
/// @note Real FFDC will be handled outside
///
template < typename T >
bool readLEArray(const std::vector<uint8_t>& i_input, const uint32_t i_size, uint32_t& io_idx, T* o_data)
{
// Loop while the readLE is still passing and we haven't looped through the array's boundaries
bool l_passing = true;
for(uint32_t i = 0; i < i_size && l_passing; ++i)
{
l_passing = readLE(i_input, io_idx, o_data[i]);
}
return l_passing;
}
}
#endif
<commit_msg>Add forceBE option to endian_utils.H<commit_after>/* IBM_PROLOG_BEGIN_TAG */
/* This is an automatically generated prolog. */
/* */
/* $Source: src/import/generic/memory/lib/utils/endian_utils.H $ */
/* */
/* OpenPOWER HostBoot Project */
/* */
/* Contributors Listed Below - COPYRIGHT 2018,2019 */
/* [+] International Business Machines Corp. */
/* */
/* */
/* Licensed under the Apache License, Version 2.0 (the "License"); */
/* you may not use this file except in compliance with the License. */
/* You may obtain a copy of the License at */
/* */
/* http://www.apache.org/licenses/LICENSE-2.0 */
/* */
/* Unless required by applicable law or agreed to in writing, software */
/* distributed under the License is distributed on an "AS IS" BASIS, */
/* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or */
/* implied. See the License for the specific language governing */
/* permissions and limitations under the License. */
/* */
/* IBM_PROLOG_END_TAG */
///
/// @file endian_utils.H
/// @brief Util functions to help with endianess
///
// *HWP HWP Owner: Ben Gass <bgass@us.ibm.com>
// *HWP HWP Backup: Christian Geddes <crgeddes@us.ibm.com>
// *HWP Team:
// *HWP Level: 2
// *HWP Consumed by: HB:FSP
#ifndef _ENDIAN_UTILS_H_
#define _ENDIAN_UTILS_H_
#include <cstdint>
#include <vector>
#include <generic/memory/lib/utils/shared/mss_generic_consts.H>
namespace mss
{
///
/// @brief Forces native data into LE order
/// @tparam T the data type to process
/// @param[in] i_input inputted data to process
/// @param[in,out] io_data vector to append data to
///
template < typename T >
void forceLE(const T& i_input, std::vector<uint8_t>& io_data)
{
// Temporary variable to process - we'll be doing bit shifts below
T l_temp = i_input;
for(size_t i = 0; i < sizeof(i_input); i++)
{
// Grab the lowest order byte and add it to the back of the vector
const uint8_t l_byte = l_temp & 0xFF;
io_data.push_back(l_byte);
// Shift higher byte value into lowest no matter existing endianness
l_temp >>= BITS_PER_BYTE;
}
}
///
/// @brief Forces native data into LE order for an array
/// @tparam T the data type to process
/// @param[in] i_input inputted data to process
/// @param[in] i_size size of the array
/// @param[in,out] io_data vector to append data to
///
template < typename T >
inline void forceLEArray(const T* i_input, const uint64_t i_size, std::vector<uint8_t>& io_data)
{
for(size_t i = 0; i < i_size; i++)
{
forceLE(i_input[i], io_data);
}
}
///
/// @brief Forces native data into BE order
/// @tparam T the data type to process
/// @param[in] i_input inputted data to process
/// @param[in,out] io_data vector to append data to
///
template < typename T >
void forceBE(const T& i_input, std::vector<uint8_t>& io_data)
{
// Temporary variable to process - we'll be doing bit shifts below
T l_temp = i_input;
std::vector<uint8_t> l_tempBuffer;
// This loop will put i_input into l_tempBuffer in BE order
for(size_t i = 0; i < sizeof(i_input); i++)
{
// Grab the lowest order byte and add it to the front of the vector
const uint8_t l_byte = l_temp & 0xFF;
l_tempBuffer.insert(l_tempBuffer.begin(), l_byte);
// Shift higher byte value into lowest no matter existing endianness
l_temp >>= BITS_PER_BYTE;
}
// Put the new BE formatted data at the end of the input buffer
io_data.insert(io_data.end(), l_tempBuffer.begin(), l_tempBuffer.end());
}
///
/// @brief Forces native data into BE order for an array
/// @tparam T the data type to process
/// @param[in] i_input inputted data to process
/// @param[in] i_size size of the array
/// @param[in,out] io_data vector to append data to
///
template < typename T >
inline void forceBEArray(const T* i_input, const uint64_t i_size, std::vector<uint8_t>& io_data)
{
for(size_t i = 0; i < i_size; i++)
{
forceBE(i_input[i], io_data);
}
}
///
/// @brief Converts LE data into native order
/// @tparam T the data type to output to
/// @param[in] i_input inputted data to process
/// @param[in,out] io_idx current index
/// @param[out] o_data data that has been converted into native endianness
/// @return bool true if passing false if failing
/// @note Real FFDC will be handled outside
///
template < typename T >
bool readLE(const std::vector<uint8_t>& i_input, uint32_t& io_idx, T& o_data)
{
const uint32_t l_sz = static_cast<uint32_t>(sizeof(o_data));
io_idx = l_sz + io_idx;
// Checks that our final index is within the data range
// Note: we decrement the index prior, so equal to is ok
if(io_idx > i_input.size())
{
return false;
}
uint64_t l_idx = io_idx;
o_data = 0;
for(uint64_t i = 0; i < l_sz; i++)
{
l_idx--;
uint8_t v = i_input[l_idx];
o_data <<= BITS_PER_BYTE;
o_data |= v;
}
return true;
}
///
/// @brief Converts LE data into native order
/// @tparam T the data type to output to
/// @param[in] i_input inputted data to process
/// @param[in] i_size size of the array
/// @param[in,out] io_idx current index
/// @param[out] o_data data that has been converted into native endianness
/// @return bool true if passing false if failing
/// @note Real FFDC will be handled outside
///
template < typename T >
bool readLEArray(const std::vector<uint8_t>& i_input, const uint32_t i_size, uint32_t& io_idx, T* o_data)
{
// Loop while the readLE is still passing and we haven't looped through the array's boundaries
bool l_passing = true;
for(uint32_t i = 0; i < i_size && l_passing; ++i)
{
l_passing = readLE(i_input, io_idx, o_data[i]);
}
return l_passing;
}
}
#endif
<|endoftext|> |
<commit_before>/**************************************************************
*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF 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.
*
*************************************************************/
#include <pyuno_impl.hxx>
#include <osl/thread.hxx>
namespace pyuno
{
bool g_destructorsOfStaticObjectsHaveBeenCalled;
class StaticDestructorGuard
{
public:
~StaticDestructorGuard()
{
g_destructorsOfStaticObjectsHaveBeenCalled = true;
}
};
StaticDestructorGuard guard;
static bool isAfterUnloadOrPy_Finalize()
{
return g_destructorsOfStaticObjectsHaveBeenCalled ||
!Py_IsInitialized();
}
class GCThread : public ::osl::Thread
{
PyObject *mPyObject;
PyInterpreterState *mPyInterpreter;
GCThread( const GCThread & ); // not implemented
GCThread &operator =( const GCThread & ); // not implemented
public:
GCThread( PyInterpreterState *interpreter, PyObject * object );
virtual void SAL_CALL run();
virtual void SAL_CALL onTerminated();
};
GCThread::GCThread( PyInterpreterState *interpreter, PyObject * object ) :
mPyObject( object ), mPyInterpreter( interpreter )
{}
void GCThread::run()
{
// otherwise we crash here, when main has been left already
if( isAfterUnloadOrPy_Finalize() )
return;
try
{
PyThreadAttach g( (PyInterpreterState*)mPyInterpreter );
{
Runtime runtime;
// remove the reference from the pythonobject2adapter map
PyRef2Adapter::iterator ii =
runtime.getImpl()->cargo->mappedObjects.find( mPyObject );
if( ii != runtime.getImpl()->cargo->mappedObjects.end() )
{
runtime.getImpl()->cargo->mappedObjects.erase( ii );
}
Py_XDECREF( mPyObject );
}
}
catch( com::sun::star::uno::RuntimeException & e )
{
rtl::OString msg;
msg = rtl::OUStringToOString( e.Message, RTL_TEXTENCODING_ASCII_US );
fprintf( stderr, "Leaking python objects bridged to UNO for reason %s\n",msg.getStr());
}
}
void GCThread::onTerminated()
{
delete this;
}
void decreaseRefCount( PyInterpreterState *interpreter, PyObject *object )
{
// otherwise we crash in the last after main ...
if( isAfterUnloadOrPy_Finalize() )
return;
// delegate to a new thread, because there does not seem
// to be a method, which tells, whether the global
// interpreter lock is held or not
// TODO: Look for a more efficient solution
osl::Thread *t = new GCThread( interpreter, object );
t->create();
}
}
<commit_msg>Change pyuno_impl.hxx to local include<commit_after>/**************************************************************
*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF 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.
*
*************************************************************/
#include "pyuno_impl.hxx"
#include <osl/thread.hxx>
namespace pyuno
{
bool g_destructorsOfStaticObjectsHaveBeenCalled;
class StaticDestructorGuard
{
public:
~StaticDestructorGuard()
{
g_destructorsOfStaticObjectsHaveBeenCalled = true;
}
};
StaticDestructorGuard guard;
static bool isAfterUnloadOrPy_Finalize()
{
return g_destructorsOfStaticObjectsHaveBeenCalled ||
!Py_IsInitialized();
}
class GCThread : public ::osl::Thread
{
PyObject *mPyObject;
PyInterpreterState *mPyInterpreter;
GCThread( const GCThread & ); // not implemented
GCThread &operator =( const GCThread & ); // not implemented
public:
GCThread( PyInterpreterState *interpreter, PyObject * object );
virtual void SAL_CALL run();
virtual void SAL_CALL onTerminated();
};
GCThread::GCThread( PyInterpreterState *interpreter, PyObject * object ) :
mPyObject( object ), mPyInterpreter( interpreter )
{}
void GCThread::run()
{
// otherwise we crash here, when main has been left already
if( isAfterUnloadOrPy_Finalize() )
return;
try
{
PyThreadAttach g( (PyInterpreterState*)mPyInterpreter );
{
Runtime runtime;
// remove the reference from the pythonobject2adapter map
PyRef2Adapter::iterator ii =
runtime.getImpl()->cargo->mappedObjects.find( mPyObject );
if( ii != runtime.getImpl()->cargo->mappedObjects.end() )
{
runtime.getImpl()->cargo->mappedObjects.erase( ii );
}
Py_XDECREF( mPyObject );
}
}
catch( com::sun::star::uno::RuntimeException & e )
{
rtl::OString msg;
msg = rtl::OUStringToOString( e.Message, RTL_TEXTENCODING_ASCII_US );
fprintf( stderr, "Leaking python objects bridged to UNO for reason %s\n",msg.getStr());
}
}
void GCThread::onTerminated()
{
delete this;
}
void decreaseRefCount( PyInterpreterState *interpreter, PyObject *object )
{
// otherwise we crash in the last after main ...
if( isAfterUnloadOrPy_Finalize() )
return;
// delegate to a new thread, because there does not seem
// to be a method, which tells, whether the global
// interpreter lock is held or not
// TODO: Look for a more efficient solution
osl::Thread *t = new GCThread( interpreter, object );
t->create();
}
}
<|endoftext|> |
<commit_before>#include <string.h>
#include <Wire.h>
#include "MPU6050.h"
#include "nt.h"
#define NT_TASK_RATE 58
#define TWI_FREQ 400000L
int main(void)
{
tNTBusGetImuData imuData;
memset(&imuData, 0, sizeof(imuData));
imuData.ImuStatus = NTBUS_IMU_IMUSTATUS_BASE | NTBUS_IMU_IMUSTATUS_GYRODATA_OK | NTBUS_IMU_IMUSTATUS_ACCDATA_OK;
sei();
Wire.begin();
MPU6050 imu = MPU6050();
imu.initialize();
imu.setClockSource(MPU6050_CLOCK_PLL_ZGYRO);
imu.setFullScaleGyroRange(MPU6050_GYRO_FS_1000);
imu.setExternalFrameSync(MPU6050_EXT_SYNC_DISABLED);
imu.setDLPFMode(MPU6050_DLPF_BW_256);
imu.setRate(0); // sample at full speed
NtNodeImu ntNode = NtNodeImu::getNodeWithNtBuffer(NTBUS_ID_IMU1, "ArduNT IMU", &imuData, NTBUS_IMU_CONFIG_MPU6000);
uint8_t dataProcessCount = 0;
for (;;)
{
if (dataProcessCount >= NT_TASK_RATE)
{
// lower priority and thus occurs less frequent than NT tasks
imu.getMotion6WithTemp(&imuData.AccX, &imuData.AccY, &imuData.AccZ, &imuData.Temp, &imuData.GyroX, &imuData.GyroY, &imuData.GyroZ);
dataProcessCount = 0;
}
uint8_t recv;
ntNode.processBusData(&recv);
dataProcessCount++;
}
return 0;
}
<commit_msg>Changed NT_TASK_RATE so that IMU response has an interval of 1.5ms.<commit_after>#include <string.h>
#include <Wire.h>
#include "MPU6050.h"
#include "nt.h"
#define NT_TASK_RATE 95
#define TWI_FREQ 400000L
int main(void)
{
tNTBusGetImuData imuData;
memset(&imuData, 0, sizeof(imuData));
imuData.ImuStatus = NTBUS_IMU_IMUSTATUS_BASE | NTBUS_IMU_IMUSTATUS_GYRODATA_OK | NTBUS_IMU_IMUSTATUS_ACCDATA_OK;
sei();
Wire.begin();
MPU6050 imu = MPU6050();
imu.initialize();
imu.setClockSource(MPU6050_CLOCK_PLL_ZGYRO);
imu.setFullScaleGyroRange(MPU6050_GYRO_FS_1000);
imu.setExternalFrameSync(MPU6050_EXT_SYNC_DISABLED);
imu.setDLPFMode(MPU6050_DLPF_BW_256);
imu.setRate(0); // sample at full speed
NtNodeImu ntNode = NtNodeImu::getNodeWithNtBuffer(NTBUS_ID_IMU1, "ArduNT IMU", &imuData, NTBUS_IMU_CONFIG_MPU6000);
uint8_t dataProcessCount = 0;
for (;;)
{
if (dataProcessCount >= NT_TASK_RATE)
{
// lower priority and thus occurs less frequent than NT tasks
imu.getMotion6WithTemp(&imuData.AccX, &imuData.AccY, &imuData.AccZ, &imuData.Temp, &imuData.GyroX, &imuData.GyroY, &imuData.GyroZ);
dataProcessCount = 0;
}
uint8_t recv;
ntNode.processBusData(&recv);
dataProcessCount++;
}
return 0;
}
<|endoftext|> |
<commit_before>/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */
/*************************************************************************
*
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* Copyright 2000, 2010 Oracle and/or its affiliates.
*
* OpenOffice.org - a multi-platform office productivity suite
*
* This file is part of OpenOffice.org.
*
* OpenOffice.org is free software: you can redistribute it and/or modify
* it under the terms of the GNU Lesser General Public License version 3
* only, as published by the Free Software Foundation.
*
* OpenOffice.org is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Lesser General Public License version 3 for more details
* (a copy is included in the LICENSE file that accompanied this code).
*
* You should have received a copy of the GNU Lesser General Public License
* version 3 along with OpenOffice.org. If not, see
* <http://www.openoffice.org/license.html>
* for a copy of the LGPLv3 License.
*
************************************************************************/
#include "uno/mapping.h"
#include <typeinfo>
#include <exception>
#include <cstddef>
// As this code is used both for the simulatos (x86) and device (ARM),
// this file is a combination of the share.hxx in ../gcc3_linux_intel
// and in ../gcc3_linux_arm.
#ifdef __arm
namespace CPPU_CURRENT_NAMESPACE
{
void dummy_can_throw_anything( char const * );
// -- following decl from libstdc++-v3/libsupc++/unwind-cxx.h and unwind.h
struct __cxa_exception
{
::std::type_info *exceptionType;
void (*exceptionDestructor)(void *);
::std::unexpected_handler unexpectedHandler;
::std::terminate_handler terminateHandler;
__cxa_exception *nextException;
int handlerCount;
#ifdef __ARM_EABI__
__cxa_exception *nextPropagatingException;
int propagationCount;
#else
int handlerSwitchValue;
const unsigned char *actionRecord;
const unsigned char *languageSpecificData;
void *catchTemp;
void *adjustedPtr;
#endif
_Unwind_Exception unwindHeader;
};
extern "C" void *__cxa_allocate_exception(
std::size_t thrown_size ) throw();
extern "C" void __cxa_throw (
void *thrown_exception, std::type_info *tinfo,
void (*dest) (void *) ) __attribute__((noreturn));
struct __cxa_eh_globals
{
__cxa_exception *caughtExceptions;
unsigned int uncaughtExceptions;
#ifdef __ARM_EABI__
__cxa_exception *propagatingExceptions;
#endif
};
extern "C" __cxa_eh_globals *__cxa_get_globals () throw();
// -----
//====================================================================
void raiseException(
uno_Any * pUnoExc, uno_Mapping * pUno2Cpp );
//====================================================================
void fillUnoException(
__cxa_exception * header, uno_Any *, uno_Mapping * pCpp2Uno );
}
namespace arm
{
enum armlimits { MAX_GPR_REGS = 4 };
bool return_in_hidden_param( typelib_TypeDescriptionReference *pTypeRef );
}
#else
namespace CPPU_CURRENT_NAMESPACE
{
void dummy_can_throw_anything( char const * );
// ----- following decl from libstdc++-v3/libsupc++/unwind-cxx.h and unwind.h
struct _Unwind_Exception
{
unsigned exception_class __attribute__((__mode__(__DI__)));
void * exception_cleanup;
unsigned private_1 __attribute__((__mode__(__word__)));
unsigned private_2 __attribute__((__mode__(__word__)));
} __attribute__((__aligned__));
struct __cxa_exception
{
::std::type_info *exceptionType;
void (*exceptionDestructor)(void *);
::std::unexpected_handler unexpectedHandler;
::std::terminate_handler terminateHandler;
__cxa_exception *nextException;
int handlerCount;
int handlerSwitchValue;
const unsigned char *actionRecord;
const unsigned char *languageSpecificData;
void *catchTemp;
void *adjustedPtr;
_Unwind_Exception unwindHeader;
};
extern "C" void *__cxa_allocate_exception(
std::size_t thrown_size ) throw();
extern "C" void __cxa_throw (
void *thrown_exception, std::type_info *tinfo, void (*dest) (void *) ) __attribute__((noreturn));
struct __cxa_eh_globals
{
__cxa_exception *caughtExceptions;
unsigned int uncaughtExceptions;
};
extern "C" __cxa_eh_globals *__cxa_get_globals () throw();
// -----
//==================================================================================================
void raiseException(
uno_Any * pUnoExc, uno_Mapping * pUno2Cpp );
//==================================================================================================
void fillUnoException(
__cxa_exception * header, uno_Any *, uno_Mapping * pCpp2Uno );
bool isSimpleReturnType(typelib_TypeDescription * pTD, bool recursive = false);
}
/* vim:set shiftwidth=4 softtabstop=4 expandtab: */
<commit_msg>Missing #endif<commit_after>/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */
/*************************************************************************
*
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* Copyright 2000, 2010 Oracle and/or its affiliates.
*
* OpenOffice.org - a multi-platform office productivity suite
*
* This file is part of OpenOffice.org.
*
* OpenOffice.org is free software: you can redistribute it and/or modify
* it under the terms of the GNU Lesser General Public License version 3
* only, as published by the Free Software Foundation.
*
* OpenOffice.org is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Lesser General Public License version 3 for more details
* (a copy is included in the LICENSE file that accompanied this code).
*
* You should have received a copy of the GNU Lesser General Public License
* version 3 along with OpenOffice.org. If not, see
* <http://www.openoffice.org/license.html>
* for a copy of the LGPLv3 License.
*
************************************************************************/
#include "uno/mapping.h"
#include <typeinfo>
#include <exception>
#include <cstddef>
// As this code is used both for the simulatos (x86) and device (ARM),
// this file is a combination of the share.hxx in ../gcc3_linux_intel
// and in ../gcc3_linux_arm.
#ifdef __arm
namespace CPPU_CURRENT_NAMESPACE
{
void dummy_can_throw_anything( char const * );
// -- following decl from libstdc++-v3/libsupc++/unwind-cxx.h and unwind.h
struct __cxa_exception
{
::std::type_info *exceptionType;
void (*exceptionDestructor)(void *);
::std::unexpected_handler unexpectedHandler;
::std::terminate_handler terminateHandler;
__cxa_exception *nextException;
int handlerCount;
#ifdef __ARM_EABI__
__cxa_exception *nextPropagatingException;
int propagationCount;
#else
int handlerSwitchValue;
const unsigned char *actionRecord;
const unsigned char *languageSpecificData;
void *catchTemp;
void *adjustedPtr;
#endif
_Unwind_Exception unwindHeader;
};
extern "C" void *__cxa_allocate_exception(
std::size_t thrown_size ) throw();
extern "C" void __cxa_throw (
void *thrown_exception, std::type_info *tinfo,
void (*dest) (void *) ) __attribute__((noreturn));
struct __cxa_eh_globals
{
__cxa_exception *caughtExceptions;
unsigned int uncaughtExceptions;
#ifdef __ARM_EABI__
__cxa_exception *propagatingExceptions;
#endif
};
extern "C" __cxa_eh_globals *__cxa_get_globals () throw();
// -----
//====================================================================
void raiseException(
uno_Any * pUnoExc, uno_Mapping * pUno2Cpp );
//====================================================================
void fillUnoException(
__cxa_exception * header, uno_Any *, uno_Mapping * pCpp2Uno );
}
namespace arm
{
enum armlimits { MAX_GPR_REGS = 4 };
bool return_in_hidden_param( typelib_TypeDescriptionReference *pTypeRef );
}
#else
namespace CPPU_CURRENT_NAMESPACE
{
void dummy_can_throw_anything( char const * );
// ----- following decl from libstdc++-v3/libsupc++/unwind-cxx.h and unwind.h
struct _Unwind_Exception
{
unsigned exception_class __attribute__((__mode__(__DI__)));
void * exception_cleanup;
unsigned private_1 __attribute__((__mode__(__word__)));
unsigned private_2 __attribute__((__mode__(__word__)));
} __attribute__((__aligned__));
struct __cxa_exception
{
::std::type_info *exceptionType;
void (*exceptionDestructor)(void *);
::std::unexpected_handler unexpectedHandler;
::std::terminate_handler terminateHandler;
__cxa_exception *nextException;
int handlerCount;
int handlerSwitchValue;
const unsigned char *actionRecord;
const unsigned char *languageSpecificData;
void *catchTemp;
void *adjustedPtr;
_Unwind_Exception unwindHeader;
};
extern "C" void *__cxa_allocate_exception(
std::size_t thrown_size ) throw();
extern "C" void __cxa_throw (
void *thrown_exception, std::type_info *tinfo, void (*dest) (void *) ) __attribute__((noreturn));
struct __cxa_eh_globals
{
__cxa_exception *caughtExceptions;
unsigned int uncaughtExceptions;
};
extern "C" __cxa_eh_globals *__cxa_get_globals () throw();
// -----
//==================================================================================================
void raiseException(
uno_Any * pUnoExc, uno_Mapping * pUno2Cpp );
//==================================================================================================
void fillUnoException(
__cxa_exception * header, uno_Any *, uno_Mapping * pCpp2Uno );
bool isSimpleReturnType(typelib_TypeDescription * pTD, bool recursive = false);
}
#endif
/* vim:set shiftwidth=4 softtabstop=4 expandtab: */
<|endoftext|> |
<commit_before>// xmlhelp.cc
// support routines for XML reading/writing
#include "xmlhelp.h" // this module
#include <stdlib.h> // atof, atol
#include <ctype.h> // isprint, isdigit, isxdigit
#include <stdio.h> // sprintf
// #include "strtokp.h" // StrtokParse
#include "exc.h" // xformat
#include "ptrintmap.h" // PtrIntMap
// FIX: pull this out into the configuration script
#define CANONICAL_XML_IDS
#ifdef CANONICAL_XML_IDS
xmlUniqueId_t nextXmlUniqueId = 0;
PtrIntMap<void const, xmlUniqueId_t> addr2id;
#endif
xmlUniqueId_t mapAddrToUniqueId(void const * const addr) {
#ifdef CANONICAL_XML_IDS
// special case the NULL pointer
if (addr == 0) return 0;
// otherwise, maintain a map to a canonical address
xmlUniqueId_t id0 = addr2id.get(addr);
if (!id0) {
id0 = nextXmlUniqueId++;
addr2id.add(addr, id0);
}
return id0;
#else
// avoid using the map
return reinterpret_cast<xmlUniqueId_t>(addr);
#endif
}
// manage identity of AST nodes
xmlUniqueId_t uniqueIdAST(void const * const obj) {
return mapAddrToUniqueId(obj);
}
string xmlPrintPointer(char const *label, xmlUniqueId_t id) {
stringBuilder sb;
sb.reserve(20);
if (!id) {
// sm: previously, the code for this function just inserted 'p'
// as a 'void const *', but that is nonportable, as gcc-3 inserts
// "0" while gcc-2 emits "(nil)"
sb << label << "0";
}
else {
sb << label;
// sm: I question whether this is portable, but it may not matter
// since null pointers are the only ones that are treated
// specially (as far as I can tell)
// sb << stringBuilder::Hex(reinterpret_cast<long unsigned>(p));
// dsw: just using ints now
sb << id;
}
return sb;
}
// string toXml_bool(bool b) {
// if (b) return "true";
// else return "false";
// }
void fromXml_bool(bool &b, const char *str) {
b = streq(str, "true");
}
// string toXml_int(int i) {
// return stringc << i;
// }
void fromXml_int(int &i, const char *str) {
long i0 = strtol(str, NULL, 10);
i = i0;
}
// string toXml_long(long i) {
// return stringc << i;
// }
void fromXml_long(long &i, const char *str) {
long i0 = strtol(str, NULL, 10);
i = i0;
}
// string toXml_unsigned_int(unsigned int i) {
// return stringc << i;
// }
void fromXml_unsigned_int(unsigned int &i, const char *str) {
unsigned long i0 = strtoul(str, NULL, 10);
i = i0;
}
// string toXml_unsigned_long(unsigned long i) {
// return stringc << i;
// }
void fromXml_unsigned_long(unsigned long &i, const char *str) {
unsigned long i0 = strtoul(str, NULL, 10);
i = i0;
}
// string toXml_double(double x) {
// return stringc << x;
// }
void fromXml_double(double &x, const char *str) {
x = atof(str);
}
string toXml_SourceLoc(SourceLoc loc) {
// NOTE: the nohashline here is very important; never change it
return sourceLocManager->getString_nohashline(loc);
}
// Avoid allocating memory to construct a substring, by being sneaky. This
// isn't thread safe. When put on the stack, the optimizer should only end up
// using one word, for 'save'.
class SneakySubstring {
public:
SneakySubstring(const char *begin0, const char *end0)
: begin(begin0), end(end0), save(*end0)
{
const_cast<char*>(end) [0] = '\0';
}
~SneakySubstring() {
const_cast<char*>(end) [0] = save;
}
operator const char *() const {
return begin;
}
const char *begin;
const char *end;
char save;
};
// #define string_prefix_match(s, prefix) (0==strncmp(s, prefix, sizeof(prefix)-1))
// Note: this function is performance-critical for deserialization, so don't
// use StrtokParse.
void fromXml_SourceLoc(SourceLoc &loc, const char *str) {
// the file format is filename:line:column
if (streq(str, "<noloc>:1:1")) {
loc = SL_UNKNOWN;
return;
}
if (streq(str, "<init>:1:1")) {
loc = SL_INIT;
return;
}
char const *end = str + strlen(str);
int line;
int col;
while (true) {
if (end <= str) {
// FIX: this is a parsing error but I don't want to throw an
// exception out of this library function
loc = SL_UNKNOWN;
return;
}
end--;
if (*end == ':') {
col = atoi(end+1);
if (!col) {
loc = SL_UNKNOWN;
return;
}
break;
}
if (!isdigit(*end)) {
loc = SL_UNKNOWN;
return;
}
}
while (true) {
if (end <= str) {
loc = SL_UNKNOWN;
return;
}
end--;
if (*end == ':') {
line = atoi(end+1);
if (!line) {
loc = SL_UNKNOWN;
return;
}
break;
}
if (!isdigit(*end)) {
loc = SL_UNKNOWN;
return;
}
}
if (end <= str) {
loc = SL_UNKNOWN;
return;
}
// the substring (str, end] is the filename.
SneakySubstring file(str, end);
loc = sourceLocManager->encodeLineCol(file, line, col);
}
// named escape codes
#define lt_CODE "lt;"
#define gt_CODE "gt;"
#define amp_CODE "amp;"
#define quot_CODE "quot;"
#define apos_CODE "apos;"
// int const lt_codelen = strlen(lt_CODE);
// int const gt_codelen = strlen(gt_CODE);
// int const amp_codelen = strlen(amp_CODE);
// int const quot_codelen = strlen(quot_CODE);
// Output SRC with escaping and quotes to output stream directly. This is
// more efficient than constructing strings and then outputting that.
ostream &outputXmlAttrQuoted(ostream &o, const char *src)
{
o << '\'';
for (; *src; ++src) {
unsigned char c = *src;
// escape those special to xml attributes;
// http://www.w3.org/TR/2004/REC-xml-20040204/#NT-AttValue
switch (c) {
default: break; // try below
case '<': o << "&" lt_CODE; continue;
case '>': o << "&" gt_CODE; continue; // this one not strictly required here
case '&': o << "&" amp_CODE; continue;
// Don't need to escape '"' if surrounding quote is "'"
// case '"': o << "&" quot_CODE; continue;
case '\'': o << "&" apos_CODE; continue;
}
// try itself
if (isprint(c)) {
o << c;
continue;
}
// use the most general notation
char tmp[7];
// dsw: the sillyness of XML knows no bounds: it is actually more
// efficient to use the decimal encoding since sometimes you only
// need 4 or 5 characters, whereas with hex you are guaranteed to
// need 6, however the uniformity makes it easier to decode hex.
// Why not make the shorter encoding also the default so that it
// really is shorter in the big picture?
sprintf(tmp, "&#x%02X;", c);
o << tmp;
}
return o << '\'';
}
string xmlAttrEncode(char const *p, int len) {
stringBuilder sb;
sb.reserve(len*3/2);
for(int i=0; i<len; ++i) {
unsigned char c = p[i];
// escape those special to xml attributes;
// http://www.w3.org/TR/2004/REC-xml-20040204/#NT-AttValue
switch (c) {
default: break; // try below
case '<': sb << "&" lt_CODE; continue;
case '>': sb << "&" gt_CODE; continue; // this one not strictly required here
case '&': sb << "&" amp_CODE; continue;
case '"': sb << "&" quot_CODE; continue;
case '\'': sb << "&" apos_CODE; continue;
}
// try itself
if (isprint(c)) {
sb << c;
continue;
}
// use the most general notation
char tmp[7];
// dsw: the sillyness of XML knows no bounds: it is actually more
// efficient to use the decimal encoding since sometimes you only
// need 4 or 5 characters, whereas with hex you are guaranteed to
// need 6, however the uniformity makes it easier to decode hex.
// Why not make the shorter encoding also the default so that it
// really is shorter in the big picture?
sprintf(tmp, "&#x%02X;", c);
sb << tmp;
}
return sb;
}
string xmlAttrEncode(const char *src) {
return xmlAttrEncode(src, strlen(src));
}
string xmlAttrQuote(const char *src) {
return stringc << '\''
<< xmlAttrEncode(src)
<< '\'';
}
// XML dequoting and unescaping is now done in the lexer: see
// xml_lex_extra.cc.
// string xmlAttrDeQuote(const char *text) {
// int len = strlen(text);
// if ( text[0] == '\'' && text[len-1] == '\'' ) {
// // decode escapes
// return xmlAttrDecode(text+1, text+len-1, '\'');
// }
// if ( text[0] == '"' && text[len-1] == '"' ) {
// // decode escapes
// return xmlAttrDecode(text+1, text+len-1, '"');
// }
// xformat(stringc << "quoted string is missing quotes: " << text);
// }
// // process characters between 'src' and 'end'. The 'end' is so we don't have
// // to create a new string just to strip quotes.
// string xmlAttrDecode(char const *src, const char *end, char delim)
// {
// stringBuilder result;
// result.reserve(end-src);
// while (src != end) {
// // check for newlines
// if (*src == '\n') {
// xformat("unescaped newline (unterminated string)");
// }
// // check for the delimiter
// if (*src == delim) {
// xformat(stringc << "unescaped delimiter (" << delim << ") in "
// << substring(src,end-src));
// }
// // check for normal characters
// if (*src != '&') {
// // normal character
// result << char(*src);
// src++;
// continue;
// }
// src++; // advance past amperstand
// // checked for named escape codes
// #define DO_ESCAPE(NAME, CHAR)
// if (strncmp(NAME ##_CODE, src, (sizeof(NAME ##_CODE)-1)) == 0) {
// result << char(CHAR);
// src += (sizeof(NAME ##_CODE)-1);
// continue;
// }
// DO_ESCAPE(lt, '<');
// DO_ESCAPE(gt, '>');
// DO_ESCAPE(amp, '&');
// DO_ESCAPE(quot, '"');
// DO_ESCAPE(apos, '\'');
// #undef DO_ESCAPE
// // check for numerical escapes
// if (*src != '#') {
// xformat(stringc << "use of an unimplemented or illegal amperstand escape (" << *src << ")");
// }
// ++src;
// // process decimal and hex escapes: decimal '&#DDD;' where D is a
// // decimal digit or hexadecimal '&#xHH;' where H is a hex digit.
// if (!(*src == 'x' || isdigit(*src))) {
// xformat(stringc << "illegal charcter after '&#' (" << *src << ")");
// }
// // are we doing hex or decimal processing?
// //
// // http://www.w3.org/TR/2004/REC-xml-20040204/#NT-CharRef "If the
// // character reference begins with "&#x", the digits and letters
// // up to the terminating ; provide a hexadecimal representation of
// // the character's code point in ISO/IEC 10646. If it begins just
// // with "&#", the digits up to the terminating ; provide a decimal
// // representation of the character's code point."
// bool hex = (*src == 'x');
// if (hex) {
// src++;
// // strtoul is willing to skip leading whitespace, so I need
// // to catch it myself
// if (!isxdigit(*src)) {
// // dsw: NOTE: in the non-hex case, the leading digit has
// // already been seen
// xformat("non-hex digit following '&#x' escape");
// }
// xassert(isxdigit(*src));
// } else {
// xassert(isdigit(*src));
// }
// // parse the digit
// char const *endptr;
// unsigned long val = strtoul(src, (char**)&endptr, hex? 16 : 10);
// if (src == endptr) {
// // this can't happen with the octal escapes because
// // there is always at least one valid digit
// xformat("invalid '&#' escape");
// }
// // keep it
// result << ((char)(unsigned char)val); // possible truncation..
// src = endptr;
// }
// return result;
// }
<commit_msg>Encode SL_INIT locations as (init) instead of <init><commit_after>// xmlhelp.cc
// support routines for XML reading/writing
#include "xmlhelp.h" // this module
#include <stdlib.h> // atof, atol
#include <ctype.h> // isprint, isdigit, isxdigit
#include <stdio.h> // sprintf
// #include "strtokp.h" // StrtokParse
#include "exc.h" // xformat
#include "ptrintmap.h" // PtrIntMap
// FIX: pull this out into the configuration script
#define CANONICAL_XML_IDS
#ifdef CANONICAL_XML_IDS
xmlUniqueId_t nextXmlUniqueId = 0;
PtrIntMap<void const, xmlUniqueId_t> addr2id;
#endif
xmlUniqueId_t mapAddrToUniqueId(void const * const addr) {
#ifdef CANONICAL_XML_IDS
// special case the NULL pointer
if (addr == 0) return 0;
// otherwise, maintain a map to a canonical address
xmlUniqueId_t id0 = addr2id.get(addr);
if (!id0) {
id0 = nextXmlUniqueId++;
addr2id.add(addr, id0);
}
return id0;
#else
// avoid using the map
return reinterpret_cast<xmlUniqueId_t>(addr);
#endif
}
// manage identity of AST nodes
xmlUniqueId_t uniqueIdAST(void const * const obj) {
return mapAddrToUniqueId(obj);
}
string xmlPrintPointer(char const *label, xmlUniqueId_t id) {
stringBuilder sb;
sb.reserve(20);
if (!id) {
// sm: previously, the code for this function just inserted 'p'
// as a 'void const *', but that is nonportable, as gcc-3 inserts
// "0" while gcc-2 emits "(nil)"
sb << label << "0";
}
else {
sb << label;
// sm: I question whether this is portable, but it may not matter
// since null pointers are the only ones that are treated
// specially (as far as I can tell)
// sb << stringBuilder::Hex(reinterpret_cast<long unsigned>(p));
// dsw: just using ints now
sb << id;
}
return sb;
}
// string toXml_bool(bool b) {
// if (b) return "true";
// else return "false";
// }
void fromXml_bool(bool &b, const char *str) {
b = streq(str, "true");
}
// string toXml_int(int i) {
// return stringc << i;
// }
void fromXml_int(int &i, const char *str) {
long i0 = strtol(str, NULL, 10);
i = i0;
}
// string toXml_long(long i) {
// return stringc << i;
// }
void fromXml_long(long &i, const char *str) {
long i0 = strtol(str, NULL, 10);
i = i0;
}
// string toXml_unsigned_int(unsigned int i) {
// return stringc << i;
// }
void fromXml_unsigned_int(unsigned int &i, const char *str) {
unsigned long i0 = strtoul(str, NULL, 10);
i = i0;
}
// string toXml_unsigned_long(unsigned long i) {
// return stringc << i;
// }
void fromXml_unsigned_long(unsigned long &i, const char *str) {
unsigned long i0 = strtoul(str, NULL, 10);
i = i0;
}
// string toXml_double(double x) {
// return stringc << x;
// }
void fromXml_double(double &x, const char *str) {
x = atof(str);
}
string toXml_SourceLoc(SourceLoc loc) {
// use "(noloc)" and "(init)" so we don't have to encode to <init>
if (loc == SL_UNKNOWN) {
return "(noloc)";
} else if (loc == SL_INIT) {
return "(init)";
} else {
// NOTE: the nohashline here is very important; never change it
return sourceLocManager->getString_nohashline(loc);
}
}
// Avoid allocating memory to construct a substring, by being sneaky. This
// isn't thread safe. When put on the stack, the optimizer should only end up
// using one word, for 'save'.
class SneakySubstring {
public:
SneakySubstring(const char *begin0, const char *end0)
: begin(begin0), end(end0), save(*end0)
{
const_cast<char*>(end) [0] = '\0';
}
~SneakySubstring() {
const_cast<char*>(end) [0] = save;
}
operator const char *() const {
return begin;
}
const char *begin;
const char *end;
char save;
};
// #define string_prefix_match(s, prefix) (0==strncmp(s, prefix, sizeof(prefix)-1))
// Note: this function is performance-critical for deserialization, so don't
// use StrtokParse.
void fromXml_SourceLoc(SourceLoc &loc, const char *str) {
// the file format is filename:line:column
if (streq(str, "(noloc)")) {
loc = SL_UNKNOWN;
return;
}
if (streq(str, "(init)")) {
loc = SL_INIT;
return;
}
char const *end = str + strlen(str);
int line;
int col;
while (true) {
if (end <= str) {
// FIX: this is a parsing error but I don't want to throw an
// exception out of this library function
loc = SL_UNKNOWN;
return;
}
end--;
if (*end == ':') {
col = atoi(end+1);
if (!col) {
loc = SL_UNKNOWN;
return;
}
break;
}
if (!isdigit(*end)) {
loc = SL_UNKNOWN;
return;
}
}
while (true) {
if (end <= str) {
loc = SL_UNKNOWN;
return;
}
end--;
if (*end == ':') {
line = atoi(end+1);
if (!line) {
loc = SL_UNKNOWN;
return;
}
break;
}
if (!isdigit(*end)) {
loc = SL_UNKNOWN;
return;
}
}
if (end <= str) {
loc = SL_UNKNOWN;
return;
}
// the substring (str, end] is the filename.
SneakySubstring file(str, end);
loc = sourceLocManager->encodeLineCol(file, line, col);
}
// named escape codes
#define lt_CODE "lt;"
#define gt_CODE "gt;"
#define amp_CODE "amp;"
#define quot_CODE "quot;"
#define apos_CODE "apos;"
// int const lt_codelen = strlen(lt_CODE);
// int const gt_codelen = strlen(gt_CODE);
// int const amp_codelen = strlen(amp_CODE);
// int const quot_codelen = strlen(quot_CODE);
// Output SRC with escaping and quotes to output stream directly. This is
// more efficient than constructing strings and then outputting that.
ostream &outputXmlAttrQuoted(ostream &o, const char *src)
{
o << '\'';
for (; *src; ++src) {
unsigned char c = *src;
// escape those special to xml attributes;
// http://www.w3.org/TR/2004/REC-xml-20040204/#NT-AttValue
switch (c) {
default: break; // try below
case '<': o << "&" lt_CODE; continue;
case '>': o << "&" gt_CODE; continue; // this one not strictly required here
case '&': o << "&" amp_CODE; continue;
// Don't need to escape '"' if surrounding quote is "'"
// case '"': o << "&" quot_CODE; continue;
case '\'': o << "&" apos_CODE; continue;
}
// try itself
if (isprint(c)) {
o << c;
continue;
}
// use the most general notation
char tmp[7];
// dsw: the sillyness of XML knows no bounds: it is actually more
// efficient to use the decimal encoding since sometimes you only
// need 4 or 5 characters, whereas with hex you are guaranteed to
// need 6, however the uniformity makes it easier to decode hex.
// Why not make the shorter encoding also the default so that it
// really is shorter in the big picture?
sprintf(tmp, "&#x%02X;", c);
o << tmp;
}
return o << '\'';
}
string xmlAttrEncode(char const *p, int len) {
stringBuilder sb;
sb.reserve(len*3/2);
for(int i=0; i<len; ++i) {
unsigned char c = p[i];
// escape those special to xml attributes;
// http://www.w3.org/TR/2004/REC-xml-20040204/#NT-AttValue
switch (c) {
default: break; // try below
case '<': sb << "&" lt_CODE; continue;
case '>': sb << "&" gt_CODE; continue; // this one not strictly required here
case '&': sb << "&" amp_CODE; continue;
case '"': sb << "&" quot_CODE; continue;
case '\'': sb << "&" apos_CODE; continue;
}
// try itself
if (isprint(c)) {
sb << c;
continue;
}
// use the most general notation
char tmp[7];
// dsw: the sillyness of XML knows no bounds: it is actually more
// efficient to use the decimal encoding since sometimes you only
// need 4 or 5 characters, whereas with hex you are guaranteed to
// need 6, however the uniformity makes it easier to decode hex.
// Why not make the shorter encoding also the default so that it
// really is shorter in the big picture?
sprintf(tmp, "&#x%02X;", c);
sb << tmp;
}
return sb;
}
string xmlAttrEncode(const char *src) {
return xmlAttrEncode(src, strlen(src));
}
string xmlAttrQuote(const char *src) {
return stringc << '\''
<< xmlAttrEncode(src)
<< '\'';
}
// XML dequoting and unescaping is now done in the lexer: see
// xml_lex_extra.cc.
// string xmlAttrDeQuote(const char *text) {
// int len = strlen(text);
// if ( text[0] == '\'' && text[len-1] == '\'' ) {
// // decode escapes
// return xmlAttrDecode(text+1, text+len-1, '\'');
// }
// if ( text[0] == '"' && text[len-1] == '"' ) {
// // decode escapes
// return xmlAttrDecode(text+1, text+len-1, '"');
// }
// xformat(stringc << "quoted string is missing quotes: " << text);
// }
// // process characters between 'src' and 'end'. The 'end' is so we don't have
// // to create a new string just to strip quotes.
// string xmlAttrDecode(char const *src, const char *end, char delim)
// {
// stringBuilder result;
// result.reserve(end-src);
// while (src != end) {
// // check for newlines
// if (*src == '\n') {
// xformat("unescaped newline (unterminated string)");
// }
// // check for the delimiter
// if (*src == delim) {
// xformat(stringc << "unescaped delimiter (" << delim << ") in "
// << substring(src,end-src));
// }
// // check for normal characters
// if (*src != '&') {
// // normal character
// result << char(*src);
// src++;
// continue;
// }
// src++; // advance past amperstand
// // checked for named escape codes
// #define DO_ESCAPE(NAME, CHAR)
// if (strncmp(NAME ##_CODE, src, (sizeof(NAME ##_CODE)-1)) == 0) {
// result << char(CHAR);
// src += (sizeof(NAME ##_CODE)-1);
// continue;
// }
// DO_ESCAPE(lt, '<');
// DO_ESCAPE(gt, '>');
// DO_ESCAPE(amp, '&');
// DO_ESCAPE(quot, '"');
// DO_ESCAPE(apos, '\'');
// #undef DO_ESCAPE
// // check for numerical escapes
// if (*src != '#') {
// xformat(stringc << "use of an unimplemented or illegal amperstand escape (" << *src << ")");
// }
// ++src;
// // process decimal and hex escapes: decimal '&#DDD;' where D is a
// // decimal digit or hexadecimal '&#xHH;' where H is a hex digit.
// if (!(*src == 'x' || isdigit(*src))) {
// xformat(stringc << "illegal charcter after '&#' (" << *src << ")");
// }
// // are we doing hex or decimal processing?
// //
// // http://www.w3.org/TR/2004/REC-xml-20040204/#NT-CharRef "If the
// // character reference begins with "&#x", the digits and letters
// // up to the terminating ; provide a hexadecimal representation of
// // the character's code point in ISO/IEC 10646. If it begins just
// // with "&#", the digits up to the terminating ; provide a decimal
// // representation of the character's code point."
// bool hex = (*src == 'x');
// if (hex) {
// src++;
// // strtoul is willing to skip leading whitespace, so I need
// // to catch it myself
// if (!isxdigit(*src)) {
// // dsw: NOTE: in the non-hex case, the leading digit has
// // already been seen
// xformat("non-hex digit following '&#x' escape");
// }
// xassert(isxdigit(*src));
// } else {
// xassert(isdigit(*src));
// }
// // parse the digit
// char const *endptr;
// unsigned long val = strtoul(src, (char**)&endptr, hex? 16 : 10);
// if (src == endptr) {
// // this can't happen with the octal escapes because
// // there is always at least one valid digit
// xformat("invalid '&#' escape");
// }
// // keep it
// result << ((char)(unsigned char)val); // possible truncation..
// src = endptr;
// }
// return result;
// }
<|endoftext|> |
<commit_before>// This file is part of playd.
// playd is licensed under the MIT licence: see LICENSE.txt.
/**
* @file
* Definition of the CommandResult class.
* @see cmd_result.hpp
*/
#include <string>
#include <vector>
#include "io/io_response.hpp"
#include "cmd_result.hpp"
/* static */ const ResponseCode CommandResult::TYPE_CODES[] = {
ResponseCode::OKAY, // Type::SUCCESS
ResponseCode::WHAT, // Type::INVALID
ResponseCode::FAIL, // Type::FAILURE
};
CommandResult CommandResult::Success()
{
return CommandResult(Type::SUCCESS, "success");
}
CommandResult CommandResult::Invalid(const std::string &msg)
{
return CommandResult(Type::INVALID, msg);
}
CommandResult CommandResult::Failure(const std::string &msg)
{
return CommandResult(Type::FAILURE, msg);
}
CommandResult::CommandResult(CommandResult::Type type, const std::string &msg)
: type(type), msg(msg)
{
}
bool CommandResult::IsSuccess() const
{
return this->type == Type::SUCCESS;
}
void CommandResult::Emit(const ResponseSink &sink,
const std::vector<std::string> &cmd) const
{
std::vector<std::string> args(cmd);
// Only display a message if the result wasn't a successful one.
// The message goes at the front, as then clients always know it's the
// first argument.
if (this->type != Type::SUCCESS) args.emplace(args.begin(), this->msg);
auto code = CommandResult::TYPE_CODES[static_cast<uint8_t>(this->type)];
sink.RespondArgs(code, args);
}
<commit_msg>Use insert, not emplace.<commit_after>// This file is part of playd.
// playd is licensed under the MIT licence: see LICENSE.txt.
/**
* @file
* Definition of the CommandResult class.
* @see cmd_result.hpp
*/
#include <string>
#include <vector>
#include "io/io_response.hpp"
#include "cmd_result.hpp"
/* static */ const ResponseCode CommandResult::TYPE_CODES[] = {
ResponseCode::OKAY, // Type::SUCCESS
ResponseCode::WHAT, // Type::INVALID
ResponseCode::FAIL, // Type::FAILURE
};
CommandResult CommandResult::Success()
{
return CommandResult(Type::SUCCESS, "success");
}
CommandResult CommandResult::Invalid(const std::string &msg)
{
return CommandResult(Type::INVALID, msg);
}
CommandResult CommandResult::Failure(const std::string &msg)
{
return CommandResult(Type::FAILURE, msg);
}
CommandResult::CommandResult(CommandResult::Type type, const std::string &msg)
: type(type), msg(msg)
{
}
bool CommandResult::IsSuccess() const
{
return this->type == Type::SUCCESS;
}
void CommandResult::Emit(const ResponseSink &sink,
const std::vector<std::string> &cmd) const
{
std::vector<std::string> args(cmd);
// Only display a message if the result wasn't a successful one.
// The message goes at the front, as then clients always know it's the
// first argument.
if (this->type != Type::SUCCESS) args.insert(args.begin(), this->msg);
auto code = CommandResult::TYPE_CODES[static_cast<uint8_t>(this->type)];
sink.RespondArgs(code, args);
}
<|endoftext|> |
<commit_before>////////////////////////////////////////////////////////////////////////////////
/// DISCLAIMER
///
/// Copyright 2016 ArangoDB GmbH, Cologne, Germany
///
/// 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.
///
/// Copyright holder is ArangoDB GmbH, Cologne, Germany
///
/// @author Dr. Frank Celler
////////////////////////////////////////////////////////////////////////////////
#include "JobQueue.h"
#include "Basics/ConditionLocker.h"
#include "GeneralServer/RestHandler.h"
#include "Logger/Logger.h"
#include "Scheduler/Scheduler.h"
#include "Scheduler/SchedulerFeature.h"
using namespace arangodb;
namespace {
class JobQueueThread final : public Thread {
public:
JobQueueThread(JobQueue* server, boost::asio::io_service* ioService)
: Thread("JobQueueThread"), _jobQueue(server), _ioService(ioService) {}
~JobQueueThread() { shutdown(); }
void beginShutdown() {
Thread::beginShutdown();
_jobQueue->wakeup();
}
public:
void run() {
int idleTries = 0;
auto jobQueue = _jobQueue;
// iterate until we are shutting down
while (!isStopping()) {
++idleTries;
for (size_t i = 0; i < JobQueue::SYSTEM_QUEUE_SIZE; ++i) {
LOG_TOPIC(TRACE, Logger::THREADS) << "size of queue #" << i << ": "
<< _jobQueue->queueSize(i);
while (_jobQueue->tryQueued()) {
Job* job = nullptr;
if (!_jobQueue->pop(i, job)) {
_jobQueue->releaseQueued();
break;
}
LOG_TOPIC(TRACE, Logger::THREADS)
<< "starting next queued job, number currently queued "
<< _jobQueue->queued();
idleTries = 0;
_ioService->post([jobQueue, job]() {
jobQueue->releaseQueued();
JobGuard guard(SchedulerFeature::SCHEDULER);
guard.work();
std::unique_ptr<Job> releaseGuard(job);
try {
job->_callback(std::move(job->_handler));
} catch(std::exception& e) {
LOG(WARN) << "Exception caught in a dangereous place! "
<< e.what();
}
jobQueue->wakeup();
});
}
}
// we need to check again if more work has arrived after we have
// aquired the lock. The lockfree queue and _nrWaiting are accessed
// using "memory_order_seq_cst", this guarantees that we do not
// miss a signal.
if (idleTries >= 2) {
LOG_TOPIC(TRACE, Logger::THREADS) << "queue manager going to sleep";
_jobQueue->waitForWork();
}
}
// clear all non-processed jobs
for (size_t i = 0; i < JobQueue::SYSTEM_QUEUE_SIZE; ++i) {
Job* job = nullptr;
while (_jobQueue->pop(i, job)) {
delete job;
}
}
}
private:
JobQueue* _jobQueue;
boost::asio::io_service* _ioService;
};
}
// -----------------------------------------------------------------------------
// --SECTION-- constructors and destructors
// -----------------------------------------------------------------------------
JobQueue::JobQueue(size_t queueSize, boost::asio::io_service* ioService)
: _queueAql(queueSize),
_queueRequeue(queueSize),
_queueStandard(queueSize),
_queueUser(queueSize),
_queues{&_queueRequeue, &_queueAql, &_queueStandard, &_queueUser},
_queued(0),
_ioService(ioService),
_queueThread(new JobQueueThread(this, _ioService)) {
for (size_t i = 0; i < SYSTEM_QUEUE_SIZE; ++i) {
_queuesSize[i].store(0);
}
}
// -----------------------------------------------------------------------------
// --SECTION-- public methods
// -----------------------------------------------------------------------------
void JobQueue::start() {
_queueThread->start();
}
void JobQueue::beginShutdown() {
_queueThread->beginShutdown();
}
bool JobQueue::tryQueued() {
size_t nrIdle = SchedulerFeature::SCHEDULER->nrIdle();
// note that incrementing the overall operation is not atomic, but this is not
// required here (_queued can be higher for a while)
if (_queued < nrIdle) {
++_queued;
return true;
}
return false;
}
void JobQueue::releaseQueued() {
TRI_ASSERT(_queued > 0);
--_queued;
}
void JobQueue::wakeup() {
CONDITION_LOCKER(guard, _queueCondition);
guard.signal();
}
void JobQueue::waitForWork() {
static uint64_t WAIT_TIME = 1000 * 1000;
CONDITION_LOCKER(guard, _queueCondition);
guard.wait(WAIT_TIME);
}
<commit_msg>Revert "fix job queue _queued variable handling"<commit_after>////////////////////////////////////////////////////////////////////////////////
/// DISCLAIMER
///
/// Copyright 2016 ArangoDB GmbH, Cologne, Germany
///
/// 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.
///
/// Copyright holder is ArangoDB GmbH, Cologne, Germany
///
/// @author Dr. Frank Celler
////////////////////////////////////////////////////////////////////////////////
#include "JobQueue.h"
#include "Basics/ConditionLocker.h"
#include "GeneralServer/RestHandler.h"
#include "Logger/Logger.h"
#include "Scheduler/Scheduler.h"
#include "Scheduler/SchedulerFeature.h"
using namespace arangodb;
namespace {
class JobQueueThread final : public Thread {
public:
JobQueueThread(JobQueue* server, boost::asio::io_service* ioService)
: Thread("JobQueueThread"), _jobQueue(server), _ioService(ioService) {}
~JobQueueThread() { shutdown(); }
void beginShutdown() {
Thread::beginShutdown();
_jobQueue->wakeup();
}
public:
void run() {
int idleTries = 0;
auto jobQueue = _jobQueue;
// iterate until we are shutting down
while (!isStopping()) {
++idleTries;
for (size_t i = 0; i < JobQueue::SYSTEM_QUEUE_SIZE; ++i) {
LOG_TOPIC(TRACE, Logger::THREADS) << "size of queue #" << i << ": "
<< _jobQueue->queueSize(i);
while (_jobQueue->tryQueued()) {
Job* job = nullptr;
if (!_jobQueue->pop(i, job)) {
_jobQueue->releaseQueued();
break;
}
LOG_TOPIC(TRACE, Logger::THREADS)
<< "starting next queued job, number currently queued "
<< _jobQueue->queued();
idleTries = 0;
_ioService->post([jobQueue, job]() {
jobQueue->releaseQueued();
JobGuard guard(SchedulerFeature::SCHEDULER);
guard.work();
std::unique_ptr<Job> releaseGuard(job);
try {
job->_callback(std::move(job->_handler));
} catch(std::exception& e) {
LOG(WARN) << "Exception caught in a dangereous place! "
<< e.what();
}
jobQueue->wakeup();
});
}
}
// we need to check again if more work has arrived after we have
// aquired the lock. The lockfree queue and _nrWaiting are accessed
// using "memory_order_seq_cst", this guarantees that we do not
// miss a signal.
if (idleTries >= 2) {
LOG_TOPIC(TRACE, Logger::THREADS) << "queue manager going to sleep";
_jobQueue->waitForWork();
}
}
// clear all non-processed jobs
for (size_t i = 0; i < JobQueue::SYSTEM_QUEUE_SIZE; ++i) {
Job* job = nullptr;
while (_jobQueue->pop(i, job)) {
delete job;
}
}
}
private:
JobQueue* _jobQueue;
boost::asio::io_service* _ioService;
};
}
// -----------------------------------------------------------------------------
// --SECTION-- constructors and destructors
// -----------------------------------------------------------------------------
JobQueue::JobQueue(size_t queueSize, boost::asio::io_service* ioService)
: _queueAql(queueSize),
_queueRequeue(queueSize),
_queueStandard(queueSize),
_queueUser(queueSize),
_queues{&_queueRequeue, &_queueAql, &_queueStandard, &_queueUser},
_queued(0),
_ioService(ioService),
_queueThread(new JobQueueThread(this, _ioService)) {
for (size_t i = 0; i < SYSTEM_QUEUE_SIZE; ++i) {
_queuesSize[i].store(0);
}
}
// -----------------------------------------------------------------------------
// --SECTION-- public methods
// -----------------------------------------------------------------------------
void JobQueue::start() {
_queueThread->start();
}
void JobQueue::beginShutdown() {
_queueThread->beginShutdown();
}
bool JobQueue::tryQueued() {
size_t nrIdle = SchedulerFeature::SCHEDULER->nrIdle();
return _queued < nrIdle;
}
void JobQueue::releaseQueued() {
--_queued;
}
void JobQueue::wakeup() {
CONDITION_LOCKER(guard, _queueCondition);
guard.signal();
}
void JobQueue::waitForWork() {
static uint64_t WAIT_TIME = 1000 * 1000;
CONDITION_LOCKER(guard, _queueCondition);
guard.wait(WAIT_TIME);
}
<|endoftext|> |
<commit_before>/*
* This file is part of Poedit (https://poedit.net)
*
* Copyright (C) 2001-2021 Vaclav Slavik
*
* 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 <wx/xrc/xmlres.h>
#include <wx/config.h>
#include <wx/textctrl.h>
#include <wx/tokenzr.h>
#include "catalog.h"
#include "commentdlg.h"
CommentDialog::CommentDialog(wxWindow *parent, const wxString& comment) : wxDialog()
{
wxXmlResource::Get()->LoadDialog(this, parent, "comment_dlg");
#ifndef __WXOSX__
CenterOnParent();
#endif
m_text = XRCCTRL(*this, "comment", wxTextCtrl);
m_text->SetValue(RemoveStartHash(comment));
if (comment.empty())
{
XRCCTRL(*this, "delete", wxWindow)->Disable();
FindWindow(wxID_OK)->SetLabel(_("Add"));
}
// else: button is labeled "Update" in XRC
wxAcceleratorEntry entries[] = {
{ wxACCEL_CMD, WXK_RETURN, wxID_OK }
};
wxAcceleratorTable accel(WXSIZEOF(entries), entries);
SetAcceleratorTable(accel);
}
wxString CommentDialog::GetComment() const
{
// Put the start hash back
return AddStartHash(m_text->GetValue());
}
BEGIN_EVENT_TABLE(CommentDialog, wxDialog)
EVT_BUTTON(XRCID("delete"), CommentDialog::OnDelete)
END_EVENT_TABLE()
void CommentDialog::OnDelete(wxCommandEvent&)
{
m_text->Clear();
EndModal(wxID_OK);
}
/*static*/ wxString CommentDialog::RemoveStartHash(const wxString& comment)
{
wxString tmpComment;
wxStringTokenizer tkn(comment, "\n\r");
while (tkn.HasMoreTokens())
tmpComment << tkn.GetNextToken().Mid(2) << "\n";
return tmpComment;
}
/*static*/ wxString CommentDialog::AddStartHash(const wxString& comment)
{
wxString tmpComment;
wxStringTokenizer tkn(comment, "\n\r");
while (tkn.HasMoreTokens())
tmpComment << "# " << tkn.GetNextToken() << "\n";
return tmpComment;
}
<commit_msg>Support numpad Return key in CommentDialog too<commit_after>/*
* This file is part of Poedit (https://poedit.net)
*
* Copyright (C) 2001-2021 Vaclav Slavik
*
* 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 <wx/xrc/xmlres.h>
#include <wx/config.h>
#include <wx/textctrl.h>
#include <wx/tokenzr.h>
#include "catalog.h"
#include "commentdlg.h"
CommentDialog::CommentDialog(wxWindow *parent, const wxString& comment) : wxDialog()
{
wxXmlResource::Get()->LoadDialog(this, parent, "comment_dlg");
#ifndef __WXOSX__
CenterOnParent();
#endif
m_text = XRCCTRL(*this, "comment", wxTextCtrl);
m_text->SetValue(RemoveStartHash(comment));
if (comment.empty())
{
XRCCTRL(*this, "delete", wxWindow)->Disable();
FindWindow(wxID_OK)->SetLabel(_("Add"));
}
// else: button is labeled "Update" in XRC
wxAcceleratorEntry entries[] = {
{ wxACCEL_CMD, WXK_RETURN, wxID_OK },
{ wxACCEL_CMD, WXK_NUMPAD_ENTER, wxID_OK }
};
wxAcceleratorTable accel(WXSIZEOF(entries), entries);
SetAcceleratorTable(accel);
}
wxString CommentDialog::GetComment() const
{
// Put the start hash back
return AddStartHash(m_text->GetValue());
}
BEGIN_EVENT_TABLE(CommentDialog, wxDialog)
EVT_BUTTON(XRCID("delete"), CommentDialog::OnDelete)
END_EVENT_TABLE()
void CommentDialog::OnDelete(wxCommandEvent&)
{
m_text->Clear();
EndModal(wxID_OK);
}
/*static*/ wxString CommentDialog::RemoveStartHash(const wxString& comment)
{
wxString tmpComment;
wxStringTokenizer tkn(comment, "\n\r");
while (tkn.HasMoreTokens())
tmpComment << tkn.GetNextToken().Mid(2) << "\n";
return tmpComment;
}
/*static*/ wxString CommentDialog::AddStartHash(const wxString& comment)
{
wxString tmpComment;
wxStringTokenizer tkn(comment, "\n\r");
while (tkn.HasMoreTokens())
tmpComment << "# " << tkn.GetNextToken() << "\n";
return tmpComment;
}
<|endoftext|> |
<commit_before>/**
* Purpose: Pixel Lapse Compositor mainline
*
* Copyright 2014, Planet Labs, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#include "compositor.h"
#include "cpl_progress.h"
/************************************************************************/
/* Usage() */
/************************************************************************/
void Usage()
{
printf( "Usage: compositor --help --help-general\n" );
printf( " -o output_file [-st source_trace_file]\n" );
printf( " [-s name value]* [-q] [-v] [-dp pixel line]\n" );
printf( " [-i input_file [-c cloudmask] [-qm name value]*]*\n" );
exit(1);
}
/************************************************************************/
/* main() */
/************************************************************************/
int main(int argc, char **argv)
{
/* -------------------------------------------------------------------- */
/* Generic GDAL startup. */
/* -------------------------------------------------------------------- */
GDALAllRegister();
argc = GDALGeneralCmdLineProcessor( argc, &argv, 0 );
if( argc < 1 )
exit( -argc );
/* -------------------------------------------------------------------- */
/* Handle command line arguments. */
/* -------------------------------------------------------------------- */
PLCContext plContext;
GDALProgressFunc pfnProgress = GDALTermProgress;
for( int i = 1; i < argc; i++ )
{
if( EQUAL(argv[i],"--help") || EQUAL(argv[i],"-h"))
Usage();
else if( EQUAL(argv[i],"-i") )
{
// Consume a whole PLCInput definition.
PLCInput *input = new PLCInput();
int argsConsumed = input->ConsumeArgs(argc-i, argv+i);
i += argsConsumed-1;
plContext.inputFiles.push_back(input);
}
else if( EQUAL(argv[i],"-s") && i < argc-2 )
{
plContext.strategyParams.AddNameValue(argv[i+1], argv[i+2]);
i += 2;
}
else if( EQUAL(argv[i],"-o") && i < argc-1
&& EQUAL(plContext.outputFilename,""))
{
plContext.outputFilename = argv[++i];
}
else if( EQUAL(argv[i],"-st") && i < argc-1
&& EQUAL(plContext.sourceTraceFilename,""))
{
plContext.sourceTraceFilename = argv[++i];
}
else if( EQUAL(argv[i],"-q") )
{
plContext.quiet = TRUE;
pfnProgress = GDALDummyProgress;
}
else if( EQUAL(argv[i],"-dp") && i < argc-2 )
{
plContext.debugPixels.push_back(atoi(argv[i+1]));
plContext.debugPixels.push_back(atoi(argv[i+2]));
i += 2;
}
else if( EQUAL(argv[i],"-v") )
{
plContext.verbose++;
}
else
{
fprintf(stderr, "Unexpected argument:%s\n", argv[i]);
Usage();
}
}
if( plContext.inputFiles.size() == 0
|| plContext.outputFilename.size() == 0)
Usage();
/* -------------------------------------------------------------------- */
/* In some contexts, it is easier to pass debug requests via */
/* environment variable. */
/* -------------------------------------------------------------------- */
if( getenv("DEBUG_PIXELS") != NULL )
{
CPLStringList values(CSLTokenizeStringComplex(
getenv("DEBUG_PIXELS"), ",",
FALSE, FALSE));
for( int i = 0; i < values.size(); i++ )
plContext.debugPixels.push_back(atoi(values[i]));
}
/* -------------------------------------------------------------------- */
/* Confirm that all inputs and outputs are the same size. We */
/* will assume they are in a consistent coordinate system. */
/* -------------------------------------------------------------------- */
plContext.outputDS = (GDALDataset *)
GDALOpen(plContext.outputFilename, GA_Update);
if( plContext.outputDS == NULL )
exit(1);
plContext.width = plContext.outputDS->GetRasterXSize();
plContext.height = plContext.outputDS->GetRasterYSize();
for( unsigned int i=0; i < plContext.inputFiles.size(); i++ )
{
plContext.inputFiles[i]->Initialize(&plContext);
GDALDataset *inputDS = plContext.inputFiles[i]->getDS();
if( inputDS->GetRasterXSize() != plContext.width
|| inputDS->GetRasterYSize() != plContext.height)
{
CPLError(CE_Fatal, CPLE_AppDefined,
"Size of %s (%dx%d) does not match target %s (%dx%d)",
plContext.inputFiles[i]->getFilename(),
inputDS->GetRasterXSize(),
inputDS->GetRasterYSize(),
plContext.outputFilename.c_str(),
plContext.outputDS->GetRasterXSize(),
plContext.outputDS->GetRasterYSize());
}
}
/* -------------------------------------------------------------------- */
/* Create source trace file if requested. */
/* -------------------------------------------------------------------- */
if( !EQUAL(plContext.sourceTraceFilename,"") )
{
GDALDriver *tiffDriver = (GDALDriver *) GDALGetDriverByName("GTiff");
GDALDataType stPixelType = GDT_Byte;
if( plContext.inputFiles.size() > 255 )
stPixelType = GDT_UInt16;
plContext.sourceTraceDS =
tiffDriver->Create(plContext.sourceTraceFilename,
plContext.width, plContext.height, 1,
stPixelType, NULL);
plContext.sourceTraceDS->SetProjection(
plContext.outputDS->GetProjectionRef());
double geotransform[6];
plContext.outputDS->GetGeoTransform(geotransform);
plContext.sourceTraceDS->SetGeoTransform(geotransform);
CPLStringList sourceMD;
CPLString key;
for( unsigned int i=0; i < plContext.inputFiles.size(); i++ )
{
key.Printf("SOURCE_%d", i+1);
sourceMD.SetNameValue(key, plContext.inputFiles[i]->getFilename());
}
plContext.sourceTraceDS->SetMetadata(sourceMD);
}
/* -------------------------------------------------------------------- */
/* Run through the image processing scanlines. */
/* -------------------------------------------------------------------- */
CPLString compositor = plContext.getStratParam("compositor", "quality");
for(int line=0; line < plContext.outputDS->GetRasterYSize(); line++ )
{
pfnProgress(line / (double) plContext.height, NULL, NULL);
plContext.line = line;
PLCLine *lineObj = plContext.getOutputLine(line);
if( EQUAL(compositor,"quality") )
QualityLineCompositor(&plContext, line, lineObj );
else if( EQUAL(compositor,"median") )
MedianLineCompositor(&plContext, line, lineObj );
else
CPLError(CE_Fatal, CPLE_AppDefined,
"Unrecognized compositor '%s'.",
compositor.c_str());
plContext.writeOutputLine(line, lineObj);
delete lineObj;
}
pfnProgress(1.0, NULL, NULL);
GDALClose(plContext.outputDS);
/* -------------------------------------------------------------------- */
/* Reporting? */
/* -------------------------------------------------------------------- */
if( plContext.verbose )
{
plContext.qualityHistogram.report(stdout, "final_quality");
}
exit(0);
}
<commit_msg>enable compression for the source trace file<commit_after>/**
* Purpose: Pixel Lapse Compositor mainline
*
* Copyright 2014, Planet Labs, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#include "compositor.h"
#include "cpl_progress.h"
/************************************************************************/
/* Usage() */
/************************************************************************/
void Usage()
{
printf( "Usage: compositor --help --help-general\n" );
printf( " -o output_file [-st source_trace_file]\n" );
printf( " [-s name value]* [-q] [-v] [-dp pixel line]\n" );
printf( " [-i input_file [-c cloudmask] [-qm name value]*]*\n" );
exit(1);
}
/************************************************************************/
/* main() */
/************************************************************************/
int main(int argc, char **argv)
{
/* -------------------------------------------------------------------- */
/* Generic GDAL startup. */
/* -------------------------------------------------------------------- */
GDALAllRegister();
argc = GDALGeneralCmdLineProcessor( argc, &argv, 0 );
if( argc < 1 )
exit( -argc );
/* -------------------------------------------------------------------- */
/* Handle command line arguments. */
/* -------------------------------------------------------------------- */
PLCContext plContext;
GDALProgressFunc pfnProgress = GDALTermProgress;
for( int i = 1; i < argc; i++ )
{
if( EQUAL(argv[i],"--help") || EQUAL(argv[i],"-h"))
Usage();
else if( EQUAL(argv[i],"-i") )
{
// Consume a whole PLCInput definition.
PLCInput *input = new PLCInput();
int argsConsumed = input->ConsumeArgs(argc-i, argv+i);
i += argsConsumed-1;
plContext.inputFiles.push_back(input);
}
else if( EQUAL(argv[i],"-s") && i < argc-2 )
{
plContext.strategyParams.AddNameValue(argv[i+1], argv[i+2]);
i += 2;
}
else if( EQUAL(argv[i],"-o") && i < argc-1
&& EQUAL(plContext.outputFilename,""))
{
plContext.outputFilename = argv[++i];
}
else if( EQUAL(argv[i],"-st") && i < argc-1
&& EQUAL(plContext.sourceTraceFilename,""))
{
plContext.sourceTraceFilename = argv[++i];
}
else if( EQUAL(argv[i],"-q") )
{
plContext.quiet = TRUE;
pfnProgress = GDALDummyProgress;
}
else if( EQUAL(argv[i],"-dp") && i < argc-2 )
{
plContext.debugPixels.push_back(atoi(argv[i+1]));
plContext.debugPixels.push_back(atoi(argv[i+2]));
i += 2;
}
else if( EQUAL(argv[i],"-v") )
{
plContext.verbose++;
}
else
{
fprintf(stderr, "Unexpected argument:%s\n", argv[i]);
Usage();
}
}
if( plContext.inputFiles.size() == 0
|| plContext.outputFilename.size() == 0)
Usage();
/* -------------------------------------------------------------------- */
/* In some contexts, it is easier to pass debug requests via */
/* environment variable. */
/* -------------------------------------------------------------------- */
if( getenv("DEBUG_PIXELS") != NULL )
{
CPLStringList values(CSLTokenizeStringComplex(
getenv("DEBUG_PIXELS"), ",",
FALSE, FALSE));
for( int i = 0; i < values.size(); i++ )
plContext.debugPixels.push_back(atoi(values[i]));
}
/* -------------------------------------------------------------------- */
/* Confirm that all inputs and outputs are the same size. We */
/* will assume they are in a consistent coordinate system. */
/* -------------------------------------------------------------------- */
plContext.outputDS = (GDALDataset *)
GDALOpen(plContext.outputFilename, GA_Update);
if( plContext.outputDS == NULL )
exit(1);
plContext.width = plContext.outputDS->GetRasterXSize();
plContext.height = plContext.outputDS->GetRasterYSize();
for( unsigned int i=0; i < plContext.inputFiles.size(); i++ )
{
plContext.inputFiles[i]->Initialize(&plContext);
GDALDataset *inputDS = plContext.inputFiles[i]->getDS();
if( inputDS->GetRasterXSize() != plContext.width
|| inputDS->GetRasterYSize() != plContext.height)
{
CPLError(CE_Fatal, CPLE_AppDefined,
"Size of %s (%dx%d) does not match target %s (%dx%d)",
plContext.inputFiles[i]->getFilename(),
inputDS->GetRasterXSize(),
inputDS->GetRasterYSize(),
plContext.outputFilename.c_str(),
plContext.outputDS->GetRasterXSize(),
plContext.outputDS->GetRasterYSize());
}
}
/* -------------------------------------------------------------------- */
/* Create source trace file if requested. */
/* -------------------------------------------------------------------- */
if( !EQUAL(plContext.sourceTraceFilename,"") )
{
GDALDriver *tiffDriver = (GDALDriver *) GDALGetDriverByName("GTiff");
CPLStringList createOptions;
GDALDataType stPixelType = GDT_Byte;
if( plContext.inputFiles.size() > 255 )
stPixelType = GDT_UInt16;
createOptions.AddString("COMPRESS=LZW");
plContext.sourceTraceDS =
tiffDriver->Create(plContext.sourceTraceFilename,
plContext.width, plContext.height, 1,
stPixelType, createOptions);
plContext.sourceTraceDS->SetProjection(
plContext.outputDS->GetProjectionRef());
double geotransform[6];
plContext.outputDS->GetGeoTransform(geotransform);
plContext.sourceTraceDS->SetGeoTransform(geotransform);
CPLStringList sourceMD;
CPLString key;
for( unsigned int i=0; i < plContext.inputFiles.size(); i++ )
{
key.Printf("SOURCE_%d", i+1);
sourceMD.SetNameValue(key, plContext.inputFiles[i]->getFilename());
}
plContext.sourceTraceDS->SetMetadata(sourceMD);
}
/* -------------------------------------------------------------------- */
/* Run through the image processing scanlines. */
/* -------------------------------------------------------------------- */
CPLString compositor = plContext.getStratParam("compositor", "quality");
for(int line=0; line < plContext.outputDS->GetRasterYSize(); line++ )
{
pfnProgress(line / (double) plContext.height, NULL, NULL);
plContext.line = line;
PLCLine *lineObj = plContext.getOutputLine(line);
if( EQUAL(compositor,"quality") )
QualityLineCompositor(&plContext, line, lineObj );
else if( EQUAL(compositor,"median") )
MedianLineCompositor(&plContext, line, lineObj );
else
CPLError(CE_Fatal, CPLE_AppDefined,
"Unrecognized compositor '%s'.",
compositor.c_str());
plContext.writeOutputLine(line, lineObj);
delete lineObj;
}
pfnProgress(1.0, NULL, NULL);
GDALClose(plContext.outputDS);
/* -------------------------------------------------------------------- */
/* Reporting? */
/* -------------------------------------------------------------------- */
if( plContext.verbose )
{
plContext.qualityHistogram.report(stdout, "final_quality");
}
exit(0);
}
<|endoftext|> |
<commit_before>/*********************************************************************************
*
* Inviwo - Interactive Visualization Workshop
*
* Copyright (c) 2014-2015 Inviwo 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.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
* ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
* WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
* DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR
* ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
* (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
* ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*
*********************************************************************************/
#include "imagelayoutgl.h"
#include <modules/opengl/glwrap/textureunit.h>
#include <inviwo/core/interaction/events/gestureevent.h>
#include <inviwo/core/interaction/events/touchevent.h>
#include <modules/opengl/glwrap/shader.h>
#include <inviwo/core/interaction/interactionhandler.h>
#include <modules/opengl/textureutils.h>
namespace inviwo {
ProcessorClassIdentifier(ImageLayoutGL, "org.inviwo.ImageLayoutGL");
ProcessorDisplayName(ImageLayoutGL, "Image Layout");
ProcessorTags(ImageLayoutGL, Tags::GL);
ProcessorCategory(ImageLayoutGL, "Image Operation");
ProcessorCodeState(ImageLayoutGL, CODE_STATE_EXPERIMENTAL);
ImageLayoutGL::ImageLayoutGL()
: Processor()
, multiinport_("multiinport")
, outport_("outport")
, layout_("layout", "Layout")
, horizontalSplitter_("horizontalSplitter", "Horizontal Splitter", 0.5f, 0.f, 1.f)
, verticalSplitter_("verticalSplitter", "Vertical Splitter", 0.5f, 0.f, 1.f)
, shader_(nullptr)
, layoutHandler_(nullptr)
, currentLayout_(ImageLayoutTypes::CrossSplit)
, currentDim_(0u, 0u) {
addPort(multiinport_);
multiinport_.onChange(this, &ImageLayoutGL::multiInportChanged);
addPort(outport_);
layout_.addOption("single", "Single Only", ImageLayoutTypes::Single);
layout_.addOption("horizontalSplit", "Horizontal Split", ImageLayoutTypes::HorizontalSplit);
layout_.addOption("verticalSplit", "Vertical Split", ImageLayoutTypes::VerticalSplit);
layout_.addOption("crossSplit", "Cross Split", ImageLayoutTypes::CrossSplit);
layout_.addOption("threeRightOneLeftSplit", "Three Left, One Right",
ImageLayoutTypes::ThreeLeftOneRight);
layout_.addOption("threeLeftOneRightSplit", "Three Right, One Left",
ImageLayoutTypes::ThreeRightOneLeft);
layout_.setSelectedValue(ImageLayoutTypes::CrossSplit);
layout_.setCurrentStateAsDefault();
addProperty(layout_);
horizontalSplitter_.setVisible(false);
addProperty(horizontalSplitter_);
verticalSplitter_.setVisible(false);
addProperty(verticalSplitter_);
layout_.onChange(this, &ImageLayoutGL::onStatusChange);
layoutHandler_ = new ImageLayoutGLInteractionHandler(this);
addInteractionHandler(layoutHandler_);
setAllPropertiesCurrentStateAsDefault();
}
ImageLayoutGL::~ImageLayoutGL() {
removeInteractionHandler(layoutHandler_);
delete layoutHandler_;
}
void ImageLayoutGL::initialize() {
Processor::initialize();
shader_ = new Shader("img_texturequad.vert", "img_copy.frag");
onStatusChange();
}
void ImageLayoutGL::deinitialize() {
delete shader_;
shader_ = nullptr;
Processor::deinitialize();
}
const std::vector<Inport*>& ImageLayoutGL::getInports(Event* e) const {
InteractionEvent* ie = dynamic_cast<InteractionEvent*>(e);
// Last clicked mouse position determines which inport is active
// This is recorded with the interactionhandler before-hand
if (ie && !viewCoords_.empty()) {
currentInteractionInport_.clear();
if (multiinport_.isConnected()) {
std::vector<Inport*> inports = multiinport_.getInports();
size_t minNum = std::min(inports.size(), viewCoords_.size());
ivec2 activePos = layoutHandler_->getActivePosition();
uvec2 dim = outport_.getConstData()->getDimensions();
activePos.y = static_cast<int>(dim.y) - activePos.y;
for (size_t i = 0; i < minNum; ++i) {
if (static_cast<int>(viewCoords_[i].x) <= activePos.x &&
(static_cast<int>(viewCoords_[i].x) + static_cast<int>(viewCoords_[i].z)) >=
activePos.x)
if (static_cast<int>(viewCoords_[i].y) <= activePos.y &&
(static_cast<int>(viewCoords_[i].y) + static_cast<int>(viewCoords_[i].w)) >=
activePos.y)
currentInteractionInport_.push_back(inports[i]);
}
}
return currentInteractionInport_;
}
return Processor::getInports();
}
const std::vector<uvec4>& ImageLayoutGL::getViewCoords(){
return viewCoords_;
}
void ImageLayoutGL::multiInportChanged() {
if (multiinport_.isConnected()) {
updateViewports(true);
std::vector<Inport*> inports = multiinport_.getInports();
size_t minNum = std::min(inports.size(), viewCoords_.size());
uvec2 outDimU = outport_.getData()->getDimensions();
vec2 outDim = vec2(outDimU.x, outDimU.y);
for (size_t i = 0; i < minNum; ++i) {
ImageInport* imageInport = dynamic_cast<ImageInport*>(inports[i]);
if (imageInport) {
imageInport->setResizeScale(vec2(viewCoords_[i].z, viewCoords_[i].w) / outDim);
}
}
}
}
void ImageLayoutGL::onStatusChange() {
updateViewports(true);
std::vector<Inport*> inports = multiinport_.getInports();
size_t minNum = std::min(inports.size(), viewCoords_.size());
uvec2 outDimU = outport_.getData()->getDimensions();
vec2 outDim = vec2(outDimU.x, outDimU.y);
for (size_t i = 0; i < minNum; ++i) {
ImageInport* imageInport = dynamic_cast<ImageInport*>(inports[i]);
if (imageInport) {
uvec2 inDimU = imageInport->getDimensions();
imageInport->setResizeScale(vec2(viewCoords_[i].z, viewCoords_[i].w) / outDim);
uvec2 inDimNewU = uvec2(viewCoords_[i].z, viewCoords_[i].w);
if (inDimNewU != inDimU){
ResizeEvent e(inDimNewU);
e.setPreviousSize(inDimU);
imageInport->changeDataDimensions(&e);
}
}
}
}
void ImageLayoutGL::process() {
TextureUnit::setZeroUnit();
std::vector<const Image*> images = multiinport_.getData();
vec2 dim = outport_.getData()->getDimensions();
// updateViewports();
TextureUnit colorUnit, depthUnit, pickingUnit;
utilgl::activateAndClearTarget(outport_, COLOR_DEPTH_PICKING);
shader_->activate();
shader_->setUniform("screenDim_", dim);
shader_->setUniform("screenDimRCP_", vec2(1.0f,1.0f)/dim);
shader_->setUniform("color_", colorUnit.getUnitNumber());
shader_->setUniform("depth_", depthUnit.getUnitNumber());
shader_->setUniform("picking_", pickingUnit.getUnitNumber());
size_t minNum = std::min(images.size(), viewCoords_.size());
for (size_t i = 0; i < minNum; ++i) {
utilgl::bindTextures(images[i], colorUnit.getEnum(), depthUnit.getEnum(), pickingUnit.getEnum());
glViewport(static_cast<int>(viewCoords_[i].x), static_cast<int>(viewCoords_[i].y),
viewCoords_[i].z, viewCoords_[i].w);
utilgl::singleDrawImagePlaneRect();
}
glViewport(0, 0, dim.x, dim.y);
shader_->deactivate();
utilgl::deactivateCurrentTarget();
TextureUnit::setZeroUnit();
}
void ImageLayoutGL::updateViewports(bool force) {
uvec2 dim(256u, 256u);
if (outport_.isConnected()) dim = outport_.getData()->getDimensions();
if (!force && (currentDim_ == dim) && (currentLayout_ == layout_.get()))
return; // no changes
viewCoords_.clear();
unsigned int smallWindowDim = dim.y / 3;
switch (layout_.getSelectedValue()) {
case ImageLayoutTypes::HorizontalSplit:
viewCoords_.push_back(uvec4(0, dim.y / 2, dim.x, dim.y / 2));
viewCoords_.push_back(uvec4(0, 0, dim.x, dim.y / 2));
break;
case ImageLayoutTypes::VerticalSplit:
viewCoords_.push_back(uvec4(0, 0, dim.x / 2, dim.y));
viewCoords_.push_back(uvec4(dim.x / 2, 0, dim.x / 2, dim.y));
break;
case ImageLayoutTypes::CrossSplit:
viewCoords_.push_back(uvec4(0, dim.y / 2, dim.x / 2, dim.y / 2));
viewCoords_.push_back(uvec4(dim.x / 2, dim.y / 2, dim.x / 2, dim.y / 2));
viewCoords_.push_back(uvec4(0, 0, dim.x / 2, dim.y / 2));
viewCoords_.push_back(uvec4(dim.x / 2, 0, dim.x / 2, dim.y / 2));
break;
case ImageLayoutTypes::ThreeLeftOneRight:
viewCoords_.push_back(uvec4(0, 2 * smallWindowDim, smallWindowDim, smallWindowDim));
viewCoords_.push_back(uvec4(0, smallWindowDim, smallWindowDim, smallWindowDim));
viewCoords_.push_back(uvec4(0, 0, smallWindowDim, smallWindowDim));
viewCoords_.push_back(uvec4(smallWindowDim, 0, dim.x - smallWindowDim, dim.y));
break;
case ImageLayoutTypes::ThreeRightOneLeft:
viewCoords_.push_back(
uvec4(dim.x - smallWindowDim, 2 * smallWindowDim, smallWindowDim, smallWindowDim));
viewCoords_.push_back(
uvec4(dim.x - smallWindowDim, smallWindowDim, smallWindowDim, smallWindowDim));
viewCoords_.push_back(uvec4(dim.x - smallWindowDim, 0, smallWindowDim, smallWindowDim));
viewCoords_.push_back(uvec4(0, 0, dim.x - smallWindowDim, dim.y));
break;
case ImageLayoutTypes::Single:
default:
viewCoords_.push_back(uvec4(0, 0, dim.x, dim.y));
}
currentDim_ = dim;
currentLayout_ = static_cast<ImageLayoutTypes::Layout>(layout_.get());
}
ImageLayoutGL::ImageLayoutGLInteractionHandler::ImageLayoutGLInteractionHandler(ImageLayoutGL* src)
: InteractionHandler()
, src_(src)
, activePositionChangeEvent_(ivec2(0), MouseEvent::MOUSE_BUTTON_LEFT,
MouseEvent::MOUSE_STATE_PRESS, InteractionEvent::MODIFIER_NONE,
uvec2(512))
, viewportActive_(false)
, activePosition_(ivec2(0)) {}
void ImageLayoutGL::ImageLayoutGLInteractionHandler::invokeEvent(Event* event) {
const std::vector<uvec4>& viewCoords = src_->getViewCoords();
MouseEvent* mouseEvent = dynamic_cast<MouseEvent*>(event);
if (mouseEvent) {
if (!viewportActive_ && mouseEvent->state() == activePositionChangeEvent_.state()) {
viewportActive_ = true;
activePosition_ = mouseEvent->pos();
} else if (viewportActive_ && mouseEvent->state() == MouseEvent::MOUSE_STATE_RELEASE) {
viewportActive_ = false;
return;
}
ivec2 mPos = mouseEvent->pos();
uvec2 cSize = mouseEvent->canvasSize();
for (size_t i = 0; i < viewCoords.size(); ++i) {
if(activePosition_.x >= viewCoords[i].x && activePosition_.x < viewCoords[i].x+viewCoords[i].z
&& activePosition_.y >= viewCoords[i].y && activePosition_.y < viewCoords[i].y+viewCoords[i].w){
ivec2 vc = ivec2(viewCoords[i].x, viewCoords[i].y);
mouseEvent->modify(mPos-vc, uvec2(viewCoords[i].z, viewCoords[i].w));
break;
}
}
return;
}
GestureEvent* gestureEvent = dynamic_cast<GestureEvent*>(event);
if (gestureEvent) {
vec2 mPosNorm = gestureEvent->screenPosNormalized();
vec2 cSize = gestureEvent->canvasSize();
vec2 mPos = mPosNorm * cSize;
for (size_t i = 0; i < viewCoords.size(); ++i) {
if(mPos.x >= viewCoords[i].x && mPos.x < viewCoords[i].x+viewCoords[i].z
&& mPos.y >= viewCoords[i].y && mPos.y < viewCoords[i].y+viewCoords[i].w){
vec2 vc = vec2(viewCoords[i].x, viewCoords[i].y);
gestureEvent->modify((mPos-vc)/mPos);
break;
}
}
return;
}
TouchEvent* touchEvent = dynamic_cast<TouchEvent*>(event);
if (touchEvent) {
if (!viewportActive_ && touchEvent->state() == TouchEvent::TOUCH_STATE_STARTED) {
viewportActive_ = true;
activePosition_ = touchEvent->pos();
} else if (viewportActive_ && touchEvent->state() == TouchEvent::TOUCH_STATE_ENDED) {
viewportActive_ = false;
}
return;
}
}
} // namespace
<commit_msg>BaseGL: ImageLayoutGL event propagation coordinate corrections and added positioning of horizontal splitter.<commit_after>/*********************************************************************************
*
* Inviwo - Interactive Visualization Workshop
*
* Copyright (c) 2014-2015 Inviwo 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.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
* ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
* WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
* DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR
* ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
* (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
* ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*
*********************************************************************************/
#include "imagelayoutgl.h"
#include <modules/opengl/glwrap/textureunit.h>
#include <inviwo/core/interaction/events/gestureevent.h>
#include <inviwo/core/interaction/events/touchevent.h>
#include <modules/opengl/glwrap/shader.h>
#include <inviwo/core/interaction/interactionhandler.h>
#include <modules/opengl/textureutils.h>
namespace inviwo {
ProcessorClassIdentifier(ImageLayoutGL, "org.inviwo.ImageLayoutGL");
ProcessorDisplayName(ImageLayoutGL, "Image Layout");
ProcessorTags(ImageLayoutGL, Tags::GL);
ProcessorCategory(ImageLayoutGL, "Image Operation");
ProcessorCodeState(ImageLayoutGL, CODE_STATE_EXPERIMENTAL);
ImageLayoutGL::ImageLayoutGL()
: Processor()
, multiinport_("multiinport")
, outport_("outport")
, layout_("layout", "Layout")
, horizontalSplitter_("horizontalSplitter", "Horizontal Splitter", 0.5f, 0.f, 1.f)
, verticalSplitter_("verticalSplitter", "Vertical Splitter", 0.5f, 0.f, 1.f)
, shader_(nullptr)
, layoutHandler_(nullptr)
, currentLayout_(ImageLayoutTypes::CrossSplit)
, currentDim_(0u, 0u) {
addPort(multiinport_);
multiinport_.onChange(this, &ImageLayoutGL::multiInportChanged);
addPort(outport_);
layout_.addOption("single", "Single Only", ImageLayoutTypes::Single);
layout_.addOption("horizontalSplit", "Horizontal Split", ImageLayoutTypes::HorizontalSplit);
layout_.addOption("verticalSplit", "Vertical Split", ImageLayoutTypes::VerticalSplit);
layout_.addOption("crossSplit", "Cross Split", ImageLayoutTypes::CrossSplit);
layout_.addOption("threeRightOneLeftSplit", "Three Left, One Right",
ImageLayoutTypes::ThreeLeftOneRight);
layout_.addOption("threeLeftOneRightSplit", "Three Right, One Left",
ImageLayoutTypes::ThreeRightOneLeft);
layout_.setSelectedValue(ImageLayoutTypes::CrossSplit);
layout_.setCurrentStateAsDefault();
addProperty(layout_);
horizontalSplitter_.setVisible(false);
horizontalSplitter_.onChange(this, &ImageLayoutGL::onStatusChange);
addProperty(horizontalSplitter_);
verticalSplitter_.setVisible(false);
addProperty(verticalSplitter_);
layout_.onChange(this, &ImageLayoutGL::onStatusChange);
layoutHandler_ = new ImageLayoutGLInteractionHandler(this);
addInteractionHandler(layoutHandler_);
setAllPropertiesCurrentStateAsDefault();
}
ImageLayoutGL::~ImageLayoutGL() {
removeInteractionHandler(layoutHandler_);
delete layoutHandler_;
}
void ImageLayoutGL::initialize() {
Processor::initialize();
shader_ = new Shader("img_texturequad.vert", "img_copy.frag");
onStatusChange();
}
void ImageLayoutGL::deinitialize() {
delete shader_;
shader_ = nullptr;
Processor::deinitialize();
}
const std::vector<Inport*>& ImageLayoutGL::getInports(Event* e) const {
InteractionEvent* ie = dynamic_cast<InteractionEvent*>(e);
// Last clicked mouse position determines which inport is active
// This is recorded with the interactionhandler before-hand
if (ie && !viewCoords_.empty()) {
currentInteractionInport_.clear();
if (multiinport_.isConnected()) {
std::vector<Inport*> inports = multiinport_.getInports();
size_t minNum = std::min(inports.size(), viewCoords_.size());
ivec2 activePos = layoutHandler_->getActivePosition();
uvec2 dim = outport_.getConstData()->getDimensions();
activePos.y = static_cast<int>(dim.y) - activePos.y;
for (size_t i = 0; i < minNum; ++i) {
if (static_cast<int>(viewCoords_[i].x) <= activePos.x &&
(static_cast<int>(viewCoords_[i].x) + static_cast<int>(viewCoords_[i].z)) >=
activePos.x)
if (static_cast<int>(viewCoords_[i].y) <= activePos.y &&
(static_cast<int>(viewCoords_[i].y) + static_cast<int>(viewCoords_[i].w)) >=
activePos.y)
currentInteractionInport_.push_back(inports[i]);
}
}
return currentInteractionInport_;
}
return Processor::getInports();
}
const std::vector<uvec4>& ImageLayoutGL::getViewCoords(){
return viewCoords_;
}
void ImageLayoutGL::multiInportChanged() {
if (multiinport_.isConnected()) {
updateViewports(true);
std::vector<Inport*> inports = multiinport_.getInports();
size_t minNum = std::min(inports.size(), viewCoords_.size());
uvec2 outDimU = outport_.getData()->getDimensions();
vec2 outDim = vec2(outDimU.x, outDimU.y);
for (size_t i = 0; i < minNum; ++i) {
ImageInport* imageInport = dynamic_cast<ImageInport*>(inports[i]);
if (imageInport) {
imageInport->setResizeScale(vec2(viewCoords_[i].z, viewCoords_[i].w) / outDim);
}
}
}
}
void ImageLayoutGL::onStatusChange() {
if (layout_.getSelectedValue() == ImageLayoutTypes::HorizontalSplit) {
horizontalSplitter_.setVisible(true);
} else {
horizontalSplitter_.setVisible(false);
}
updateViewports(true);
std::vector<Inport*> inports = multiinport_.getInports();
size_t minNum = std::min(inports.size(), viewCoords_.size());
uvec2 outDimU = outport_.getData()->getDimensions();
vec2 outDim = vec2(outDimU.x, outDimU.y);
for (size_t i = 0; i < minNum; ++i) {
ImageInport* imageInport = dynamic_cast<ImageInport*>(inports[i]);
if (imageInport) {
uvec2 inDimU = imageInport->getDimensions();
imageInport->setResizeScale(vec2(viewCoords_[i].z, viewCoords_[i].w) / outDim);
uvec2 inDimNewU = uvec2(viewCoords_[i].z, viewCoords_[i].w);
if (inDimNewU != inDimU){
ResizeEvent e(inDimNewU);
e.setPreviousSize(inDimU);
imageInport->changeDataDimensions(&e);
}
}
}
}
void ImageLayoutGL::process() {
TextureUnit::setZeroUnit();
std::vector<const Image*> images = multiinport_.getData();
vec2 dim = outport_.getData()->getDimensions();
// updateViewports();
TextureUnit colorUnit, depthUnit, pickingUnit;
utilgl::activateAndClearTarget(outport_, COLOR_DEPTH_PICKING);
shader_->activate();
shader_->setUniform("screenDim_", dim);
shader_->setUniform("screenDimRCP_", vec2(1.0f,1.0f)/dim);
shader_->setUniform("color_", colorUnit.getUnitNumber());
shader_->setUniform("depth_", depthUnit.getUnitNumber());
shader_->setUniform("picking_", pickingUnit.getUnitNumber());
size_t minNum = std::min(images.size(), viewCoords_.size());
for (size_t i = 0; i < minNum; ++i) {
utilgl::bindTextures(images[i], colorUnit.getEnum(), depthUnit.getEnum(), pickingUnit.getEnum());
glViewport(static_cast<int>(viewCoords_[i].x), static_cast<int>(viewCoords_[i].y),
viewCoords_[i].z, viewCoords_[i].w);
utilgl::singleDrawImagePlaneRect();
}
glViewport(0, 0, dim.x, dim.y);
shader_->deactivate();
utilgl::deactivateCurrentTarget();
TextureUnit::setZeroUnit();
}
void ImageLayoutGL::updateViewports(bool force) {
uvec2 dim(256u, 256u);
if (outport_.isConnected()) dim = outport_.getData()->getDimensions();
if (!force && (currentDim_ == dim) && (currentLayout_ == layout_.get()))
return; // no changes
viewCoords_.clear();
unsigned int smallWindowDim = dim.y / 3;
switch (layout_.getSelectedValue()) {
case ImageLayoutTypes::HorizontalSplit:
viewCoords_.push_back(uvec4(0, horizontalSplitter_.get() * dim.y, dim.x, (1.f - horizontalSplitter_.get()) * dim.y));
viewCoords_.push_back(uvec4(0, 0, dim.x, horizontalSplitter_.get() * dim.y));
break;
case ImageLayoutTypes::VerticalSplit:
viewCoords_.push_back(uvec4(0, 0, dim.x / 2, dim.y));
viewCoords_.push_back(uvec4(dim.x / 2, 0, dim.x / 2, dim.y));
break;
case ImageLayoutTypes::CrossSplit:
viewCoords_.push_back(uvec4(0, dim.y / 2, dim.x / 2, dim.y / 2));
viewCoords_.push_back(uvec4(dim.x / 2, dim.y / 2, dim.x / 2, dim.y / 2));
viewCoords_.push_back(uvec4(0, 0, dim.x / 2, dim.y / 2));
viewCoords_.push_back(uvec4(dim.x / 2, 0, dim.x / 2, dim.y / 2));
break;
case ImageLayoutTypes::ThreeLeftOneRight:
viewCoords_.push_back(uvec4(0, 2 * smallWindowDim, smallWindowDim, smallWindowDim));
viewCoords_.push_back(uvec4(0, smallWindowDim, smallWindowDim, smallWindowDim));
viewCoords_.push_back(uvec4(0, 0, smallWindowDim, smallWindowDim));
viewCoords_.push_back(uvec4(smallWindowDim, 0, dim.x - smallWindowDim, dim.y));
break;
case ImageLayoutTypes::ThreeRightOneLeft:
viewCoords_.push_back(
uvec4(dim.x - smallWindowDim, 2 * smallWindowDim, smallWindowDim, smallWindowDim));
viewCoords_.push_back(
uvec4(dim.x - smallWindowDim, smallWindowDim, smallWindowDim, smallWindowDim));
viewCoords_.push_back(uvec4(dim.x - smallWindowDim, 0, smallWindowDim, smallWindowDim));
viewCoords_.push_back(uvec4(0, 0, dim.x - smallWindowDim, dim.y));
break;
case ImageLayoutTypes::Single:
default:
viewCoords_.push_back(uvec4(0, 0, dim.x, dim.y));
}
currentDim_ = dim;
currentLayout_ = static_cast<ImageLayoutTypes::Layout>(layout_.get());
}
ImageLayoutGL::ImageLayoutGLInteractionHandler::ImageLayoutGLInteractionHandler(ImageLayoutGL* src)
: InteractionHandler()
, src_(src)
, activePositionChangeEvent_(ivec2(0), MouseEvent::MOUSE_BUTTON_LEFT,
MouseEvent::MOUSE_STATE_PRESS, InteractionEvent::MODIFIER_NONE,
uvec2(512))
, viewportActive_(false)
, activePosition_(ivec2(0)) {}
void ImageLayoutGL::ImageLayoutGLInteractionHandler::invokeEvent(Event* event) {
const std::vector<uvec4>& viewCoords = src_->getViewCoords();
MouseEvent* mouseEvent = dynamic_cast<MouseEvent*>(event);
if (mouseEvent) {
if (!viewportActive_ && mouseEvent->state() == activePositionChangeEvent_.state()) {
viewportActive_ = true;
activePosition_ = mouseEvent->pos();
} else if (viewportActive_ && mouseEvent->state() == MouseEvent::MOUSE_STATE_RELEASE) {
viewportActive_ = false;
}
ivec2 mPos = mouseEvent->pos();
uvec2 cSize = mouseEvent->canvasSize();
// Flip y-coordinate to bottom->up
vec2 activePosition(activePosition_.x, cSize.y - activePosition_.y);
for (size_t i = 0; i < viewCoords.size(); ++i) {
if (activePosition.x >= viewCoords[i].x && activePosition.x < viewCoords[i].x + viewCoords[i].z
&& activePosition.y >= viewCoords[i].y && activePosition.y < viewCoords[i].y + viewCoords[i].w){
ivec2 vc = ivec2(viewCoords[i].x, cSize.y - viewCoords[i].y - viewCoords[i].w);
mouseEvent->modify(mPos-vc, uvec2(viewCoords[i].z, viewCoords[i].w));
break;
}
}
return;
}
GestureEvent* gestureEvent = dynamic_cast<GestureEvent*>(event);
if (gestureEvent) {
vec2 mPosNorm = gestureEvent->screenPosNormalized();
vec2 cSize = gestureEvent->canvasSize();
vec2 mPos = mPosNorm * cSize;
vec2 activePosition(mPos.x, cSize.y - mPos.y);
for (size_t i = 0; i < viewCoords.size(); ++i) {
if (activePosition.x >= viewCoords[i].x && activePosition.x < viewCoords[i].x + viewCoords[i].z
&& activePosition.y >= viewCoords[i].y && activePosition.y < viewCoords[i].y + viewCoords[i].w){
vec2 vc = vec2(viewCoords[i].x, cSize.y - viewCoords[i].y - viewCoords[i].w);
gestureEvent->modify((mPos - vc) / vec2(viewCoords[i].zw()));
break;
}
}
return;
}
TouchEvent* touchEvent = dynamic_cast<TouchEvent*>(event);
if (touchEvent) {
if (!viewportActive_ && touchEvent->state() == TouchEvent::TOUCH_STATE_STARTED) {
viewportActive_ = true;
activePosition_ = touchEvent->pos();
} else if (viewportActive_ && touchEvent->state() == TouchEvent::TOUCH_STATE_ENDED) {
viewportActive_ = false;
}
return;
}
}
} // namespace
<|endoftext|> |
<commit_before><commit_msg>HMI: Cache onboard HMIMode and recover next time.<commit_after><|endoftext|> |
<commit_before><commit_msg>planning: always stop for crosswalk regardless of stop_deceleration (10141)<commit_after><|endoftext|> |
<commit_before>/*
* Copyright 2016 Google Inc.
*
* Use of this source code is governed by a BSD-style license that can be
* found in the LICENSE file.
*/
#include "SkShaper.h"
#include "SkStream.h"
#include "SkTo.h"
#include "SkTypeface.h"
struct SkShaper::Impl {
sk_sp<SkTypeface> fTypeface;
};
SkShaper::SkShaper(sk_sp<SkTypeface> tf) : fImpl(new Impl) {
fImpl->fTypeface = tf ? std::move(tf) : SkTypeface::MakeDefault();
}
SkShaper::~SkShaper() {}
bool SkShaper::good() const { return true; }
// This example only uses public API, so we don't use SkUTF8_NextUnichar.
unsigned utf8_lead_byte_to_count(const char* ptr) {
uint8_t c = *(const uint8_t*)ptr;
SkASSERT(c <= 0xF7);
SkASSERT((c & 0xC0) != 0x80);
return (((0xE5 << 24) >> ((unsigned)c >> 4 << 1)) & 3) + 1;
}
SkPoint SkShaper::shape(RunHandler* handler,
const SkFont& srcFont,
const char* utf8text,
size_t textBytes,
bool leftToRight,
SkPoint point,
SkScalar width) const {
sk_ignore_unused_variable(leftToRight);
sk_ignore_unused_variable(width);
SkFont font(srcFont);
font.setTypeface(fImpl->fTypeface);
int glyphCount = font.countText(utf8text, textBytes, SkTextEncoding::kUTF8);
if (glyphCount <= 0) {
return point;
}
SkFontMetrics metrics;
font.getMetrics(&metrics);
point.fY -= metrics.fAscent;
const RunHandler::RunInfo info = {
0,
{ font.measureText(utf8text, textBytes, SkTextEncoding::kUTF8), 0 },
metrics.fAscent,
metrics.fDescent,
metrics.fLeading,
};
const auto buffer = handler->newRunBuffer(info, font, glyphCount, textBytes);
SkAssertResult(font.textToGlyphs(utf8text, textBytes, SkTextEncoding::kUTF8, buffer.glyphs,
glyphCount) == glyphCount);
font.getPos(buffer.glyphs, glyphCount, buffer.positions, point);
if (buffer.utf8text) {
memcpy(buffer.utf8text, utf8text, textBytes);
}
if (buffer.clusters) {
const char* txtPtr = utf8text;
for (int i = 0; i < glyphCount; ++i) {
// Each charater maps to exactly one glyph via SkGlyphCache::unicharToGlyph().
buffer.clusters[i] = SkToU32(txtPtr - utf8text);
txtPtr += utf8_lead_byte_to_count(txtPtr);
SkASSERT(txtPtr <= utf8text + textBytes);
}
}
return point + SkVector::Make(0, metrics.fDescent + metrics.fLeading);
}
<commit_msg>iwyu<commit_after>/*
* Copyright 2016 Google Inc.
*
* Use of this source code is governed by a BSD-style license that can be
* found in the LICENSE file.
*/
#include "SkShaper.h"
#include "SkFontMetrics.h"
#include "SkStream.h"
#include "SkTo.h"
#include "SkTypeface.h"
struct SkShaper::Impl {
sk_sp<SkTypeface> fTypeface;
};
SkShaper::SkShaper(sk_sp<SkTypeface> tf) : fImpl(new Impl) {
fImpl->fTypeface = tf ? std::move(tf) : SkTypeface::MakeDefault();
}
SkShaper::~SkShaper() {}
bool SkShaper::good() const { return true; }
// This example only uses public API, so we don't use SkUTF8_NextUnichar.
unsigned utf8_lead_byte_to_count(const char* ptr) {
uint8_t c = *(const uint8_t*)ptr;
SkASSERT(c <= 0xF7);
SkASSERT((c & 0xC0) != 0x80);
return (((0xE5 << 24) >> ((unsigned)c >> 4 << 1)) & 3) + 1;
}
SkPoint SkShaper::shape(RunHandler* handler,
const SkFont& srcFont,
const char* utf8text,
size_t textBytes,
bool leftToRight,
SkPoint point,
SkScalar width) const {
sk_ignore_unused_variable(leftToRight);
sk_ignore_unused_variable(width);
SkFont font(srcFont);
font.setTypeface(fImpl->fTypeface);
int glyphCount = font.countText(utf8text, textBytes, SkTextEncoding::kUTF8);
if (glyphCount <= 0) {
return point;
}
SkFontMetrics metrics;
font.getMetrics(&metrics);
point.fY -= metrics.fAscent;
const RunHandler::RunInfo info = {
0,
{ font.measureText(utf8text, textBytes, SkTextEncoding::kUTF8), 0 },
metrics.fAscent,
metrics.fDescent,
metrics.fLeading,
};
const auto buffer = handler->newRunBuffer(info, font, glyphCount, textBytes);
SkAssertResult(font.textToGlyphs(utf8text, textBytes, SkTextEncoding::kUTF8, buffer.glyphs,
glyphCount) == glyphCount);
font.getPos(buffer.glyphs, glyphCount, buffer.positions, point);
if (buffer.utf8text) {
memcpy(buffer.utf8text, utf8text, textBytes);
}
if (buffer.clusters) {
const char* txtPtr = utf8text;
for (int i = 0; i < glyphCount; ++i) {
// Each charater maps to exactly one glyph via SkGlyphCache::unicharToGlyph().
buffer.clusters[i] = SkToU32(txtPtr - utf8text);
txtPtr += utf8_lead_byte_to_count(txtPtr);
SkASSERT(txtPtr <= utf8text + textBytes);
}
}
return point + SkVector::Make(0, metrics.fDescent + metrics.fLeading);
}
<|endoftext|> |
<commit_before>#define BOOST_SPIRIT_NO_PREDEFINED_TERMINALS
#include <chrono>
#include <mutex>
#include <vector>
#include <unordered_map>
#include <boost/format.hpp>
#include <boost/program_options.hpp>
#include <magic.h>
#include <json11.hpp>
#include <server_http.hpp>
#include <server_extra.hpp>
#include <server_extra_zip.hpp>
#include "picpac-cv.h"
#include "picpac-overview.h"
#include "bfdfs/bfdfs.h"
using namespace std;
using namespace picpac;
char const *version = PP_VERSION "-" PP_BUILD_NUMBER "," PP_BUILD_ID "," PP_BUILD_TIME;
extern char _binary_html_static_start;
static vector<pair<string, string>> const EXT_MIME{
{".html", "text/html"},
{".css", "text/css"},
{".js", "application/javascript"},
};
static unsigned constexpr EXT_MIME_GZIP = 3;
static std::string const DEFAULT_MIME("application/octet-stream");
void banner () {
cout <<
" ____ _ ____ " << endl <<
" | _ \\(_) ___| _ \\ __ _ ___ " << endl <<
" | |_) | |/ __| |_) / _` |/ __|" << endl <<
" | __/| | (__| __/ (_| | (__ " << endl <<
" |_| |_|\\___|_| \\__,_|\\___|" << endl <<
" " << endl;
cout << "PicPac Explorer" << endl;
cout << "Version: " << version << endl;
cout << "https://github.com/aaalgo/picpac" << endl;
}
using namespace json11;
static size_t max_peak_mb = 1000;
static float max_peak_relax = 0.2;
typedef SimpleWeb::Server<SimpleWeb::HTTP> HttpServer;
using SimpleWeb::Response;
using SimpleWeb::Request;
void backtrace ();
class Service: public SimpleWeb::Multiplexer {
picpac::IndexedFileReader db;
bfdfs::Loader statics;
default_random_engine rng; // needs protection!!!TODO
string overview;
string collage;
vector<vector<string>> samples;
magic_t cookie;
#define HTTP_Q "(\\?.+)?$"
string http_query (string const &path) const {
auto p = path.find('?');
if (p == path.npos) return "";
return path.substr(p+1);
}
static string const &path2mime (string const &path, bool *gzip) {
do {
auto p = path.rfind('.');
if (p == path.npos) break;
string ext = path.substr(p);
*gzip = false;
unsigned i = 0;
for (auto const &v: EXT_MIME) {
if (v.first == ext) {
if (i < EXT_MIME_GZIP) {
*gzip = true;
}
return v.second;
}
++i;
}
} while (false);
return DEFAULT_MIME;
}
public:
Service (fs::path const &db_path, HttpServer *sv)
: Multiplexer(sv),
db(db_path),
statics(&_binary_html_static_start, "") {
cookie = magic_open(MAGIC_MIME_TYPE);
CHECK(cookie);
magic_load(cookie, "/usr/share/misc/magic:/usr/local/share/misc/magic");
Overview ov(db, max_peak_mb, max_peak_relax);
ov.toJson(&overview);
{
ImageEncoder encoder(".jpg");
encoder.encode(ov.collage(), &collage);
{
vector<vector<cv::Mat>> ss;
ov.stealSamples(&ss);
samples.resize(ss.size());
for (unsigned i = 0; i < ss.size(); ++i) {
auto &from = ss[i];
auto &to = samples[i];
to.resize(from.size());
for (unsigned j = 0; j < from.size(); ++j) {
encoder.encode(from[j], &to[j]);
}
}
}
}
add("^/api/overview" HTTP_Q, "GET", [this](Response &res, Request &req) {
/*
rfc3986::Form trans;
// transfer all applicable image parameters to trans
// so we can later use that for image display
#define PICPAC_CONFIG_UPDATE(C,P) \
{ auto it = query.find(#P); if (it != query.end()) trans.insert(*it);}
PICPAC_CONFIG_UPDATE_ALL(0);
#undef PICPAC_CONFIG_UPDATE
string ext = trans.encode(true);
*/
res.content = overview;
res.mime = "application/json";
});
add("^/api/collage.jpg" HTTP_Q, "GET", [this](Response &res, Request &req) {
/*
rfc3986::Form trans;
// transfer all applicable image parameters to trans
// so we can later use that for image display
#define PICPAC_CONFIG_UPDATE(C,P) \
{ auto it = query.find(#P); if (it != query.end()) trans.insert(*it);}
PICPAC_CONFIG_UPDATE_ALL(0);
#undef PICPAC_CONFIG_UPDATE
string ext = trans.encode(true);
*/
res.content = collage;
res.mime = "image/jpeg";
});
add("^/api/thumb" HTTP_Q, "GET", [this](Response &res, Request &req) {
int cls = req.GET.get<int>("class", 0);
int off = req.GET.get<int>("offset", 0);
if (cls >= samples.size()
|| off >= samples[cls].size()) {
res.status = 404;
res.status_string = "Not Found";
}
else {
res.mime = "image/jpeg";
res.content = samples[cls][off];
}
});
add("^/api/sample" HTTP_Q, "GET", [this](Response &res, Request &req) {
int count = req.GET.get<int>("count", 20);
//string anno = query.get<string>("anno", "");
vector<int> ids(count);
for (auto &id: ids) {
id = rand() % db.size();
}
Json json = Json::object {
{"samples", Json(ids)},
};
res.mime = "application/json";
res.content = json.dump();
});
add("^/api/file" HTTP_Q, "GET",
[this](Response &res, Request &req) {
int id = req.GET.get<int>("id", 0);
Record rec;
db.read(id, &rec);
string buf = rec.field_string(0);
res.mime = magic_buffer(cookie, &buf[0], buf.size());
res.content.swap(buf);
});
add("^/api/image" HTTP_Q, "GET",
[this](Response &res, Request &req) {
PICPAC_CONFIG conf;
conf.anno_color3 = 255;
conf.anno_copy = true;
conf.anno_thickness = 2;
conf.pert_color1 = 20;
conf.pert_color2 = 20;
conf.pert_color3 = 20;
conf.pert_angle = 20;
conf.pert_min_scale = 0.8;
conf.pert_max_scale = 1.2;
#define PICPAC_CONFIG_UPDATE(C,P) C.P = req.GET.get<decltype(C.P)>(#P, C.P)
PICPAC_CONFIG_UPDATE_ALL(conf);
#undef PICPAC_CONFIG_UPDATE
float anno_factor = req.GET.get<float>("anno_factor", 0);
LOG(INFO) << "ANNO: " << anno_factor;
bool do_norm = req.GET.get<int>("norm", 0);
ImageLoader loader(conf);
ImageLoader::PerturbVector pv;
int id = req.GET.get<int>("id", rng() % db.size());
ImageLoader::Value v;
loader.sample(rng, &pv);
loader.load([this, id](Record *r){db.read(id, r);}, pv, &v);
ImageEncoder encoder;
string buf;
cv::Mat image = v.image;
if (conf.annotate.size()) {
image = v.annotation;
if (anno_factor) {
image *= anno_factor;
}
}
if (do_norm) {
cv::Mat tmp;
cv::normalize(image, tmp, 0, 255, cv::NORM_MINMAX, CV_8U);
image = tmp;
}
encoder.encode(image, &buf);
res.mime = "image/jpeg";
res.content.swap(buf);
});
add_default("GET",
[this](Response &res, Request &req) {
string path = req.path;
bfdfs::Page page;
bool loaded = statics.load(path, &page);
if (!loaded) {
loaded = statics.load("/index.html", &page);
}
if (loaded) {
auto it = req.header.find("If-None-Match");
do {
if (it != req.header.end()) {
string const &tag = it->second;
if (tag == page.checksum || (true
&& (tag.size() == (page.checksum.size() + 2))
&& (tag.find(page.checksum) == 1)
&& (tag.front() == '"')
&& (tag.back() == '"'))) {
res.status = 304;
res.status_string = "Not Modified";
res.content.clear();
break;
}
}
res.content = string(page.begin, page.end);
bool gz = false;
res.mime = path2mime(path, &gz);
res.header.insert(make_pair(string("ETag"), '"' + page.checksum +'"'));
if (gz) {
SimpleWeb::plugins::deflate(res, req);
}
} while (false);
}
else {
res.status = 404;
res.content.clear();
}
});
}
~Service () {
magic_close(cookie);
}
};
int main(int argc, char const* argv[]) {
banner();
//string address;
unsigned short port;
int threads;
fs::path db_path;
namespace po = boost::program_options;
po::options_description desc("Allowed options");
desc.add_options()
("help,h", "produce help message.")
//("address", po::value(&address)->default_value("0.0.0.0"), "")
("port", po::value(&port)->default_value(18888), "")
("db", po::value(&db_path), "")
("threads,t", po::value(&threads)->default_value(1), "")
("no-browser", "do not start browser")
("max-peek", po::value(&max_peak_mb)->default_value(1000), "read this number MB of data")
;
po::options_description desc_hidden("Expert options");
desc_hidden.add_options()
//("html_root", po::value(&html_root), "")
;
desc.add(desc_hidden);
po::positional_options_description p;
p.add("db", 1);
po::variables_map vm;
po::store(po::command_line_parser(argc, argv).
options(desc).positional(p).run(), vm);
po::notify(vm);
if (vm.count("help") || db_path.empty()) {
cout << "Usage:" << endl;
cout << "\tserver ... <db>" << endl;
cout << desc;
cout << endl;
return 0;
}
HttpServer server(port, threads);
Service service(db_path, &server);
thread th([&]() {
LOG(INFO) << "listening at port: " << port;
LOG(INFO) << "running server with " << threads << " threads.";
server.start();
});
do { // test and start web browser
if (vm.count("no-browser")) break;
char *display = getenv("DISPLAY");
if ((!display) || (strlen(display) == 0)) {
LOG(WARNING) << "No DISPLAY found, not starting browser.";
break;
}
boost::format cmd("xdg-open http://localhost:%1%");
system((cmd % port).str().c_str());
} while (false);
// GET /hello
th.join();
return 0;
}
<commit_msg>updat<commit_after>#define BOOST_SPIRIT_NO_PREDEFINED_TERMINALS
#include <chrono>
#include <mutex>
#include <vector>
#include <unordered_map>
#include <boost/format.hpp>
#include <boost/program_options.hpp>
#include <magic.h>
#include <json11.hpp>
#include <server_http.hpp>
#include <server_extra.hpp>
#include <server_extra_zip.hpp>
#include "picpac-cv.h"
#include "picpac-overview.h"
#include "bfdfs/bfdfs.h"
using namespace std;
using namespace picpac;
char const *version = PP_VERSION "-" PP_BUILD_NUMBER "," PP_BUILD_ID "," PP_BUILD_TIME;
extern char _binary_html_static_start;
static vector<pair<string, string>> const EXT_MIME{
{".html", "text/html"},
{".css", "text/css"},
{".js", "application/javascript"},
};
static unsigned constexpr EXT_MIME_GZIP = 3;
static std::string const DEFAULT_MIME("application/octet-stream");
void banner () {
cout <<
" ____ _ ____ " << endl <<
" | _ \\(_) ___| _ \\ __ _ ___ " << endl <<
" | |_) | |/ __| |_) / _` |/ __|" << endl <<
" | __/| | (__| __/ (_| | (__ " << endl <<
" |_| |_|\\___|_| \\__,_|\\___|" << endl <<
" " << endl;
cout << "PicPac Explorer" << endl;
cout << "Version: " << version << endl;
cout << "https://github.com/aaalgo/picpac" << endl;
}
using namespace json11;
static size_t max_peak_mb = 1000;
static float max_peak_relax = 0.2;
typedef SimpleWeb::Server<SimpleWeb::HTTP> HttpServer;
using SimpleWeb::Response;
using SimpleWeb::Request;
void backtrace ();
class Service: public SimpleWeb::Multiplexer {
picpac::IndexedFileReader db;
bfdfs::Loader statics;
default_random_engine rng; // needs protection!!!TODO
string overview;
string collage;
vector<vector<string>> samples;
magic_t cookie;
#define HTTP_Q "(\\?.+)?$"
string http_query (string const &path) const {
auto p = path.find('?');
if (p == path.npos) return "";
return path.substr(p+1);
}
static string const &path2mime (string const &path, bool *gzip) {
do {
auto p = path.rfind('.');
if (p == path.npos) break;
string ext = path.substr(p);
*gzip = false;
unsigned i = 0;
for (auto const &v: EXT_MIME) {
if (v.first == ext) {
if (i < EXT_MIME_GZIP) {
*gzip = true;
}
return v.second;
}
++i;
}
} while (false);
return DEFAULT_MIME;
}
public:
Service (fs::path const &db_path, HttpServer *sv)
: Multiplexer(sv),
db(db_path),
statics(&_binary_html_static_start, "") {
cookie = magic_open(MAGIC_MIME_TYPE);
CHECK(cookie);
magic_load(cookie, "/usr/share/misc/magic:/usr/local/share/misc/magic");
Overview ov(db, max_peak_mb, max_peak_relax);
ov.toJson(&overview);
{
ImageEncoder encoder(".jpg");
encoder.encode(ov.collage(), &collage);
{
vector<vector<cv::Mat>> ss;
ov.stealSamples(&ss);
samples.resize(ss.size());
for (unsigned i = 0; i < ss.size(); ++i) {
auto &from = ss[i];
auto &to = samples[i];
to.resize(from.size());
for (unsigned j = 0; j < from.size(); ++j) {
encoder.encode(from[j], &to[j]);
}
}
}
}
add("^/api/overview" HTTP_Q, "GET", [this](Response &res, Request &req) {
/*
rfc3986::Form trans;
// transfer all applicable image parameters to trans
// so we can later use that for image display
#define PICPAC_CONFIG_UPDATE(C,P) \
{ auto it = query.find(#P); if (it != query.end()) trans.insert(*it);}
PICPAC_CONFIG_UPDATE_ALL(0);
#undef PICPAC_CONFIG_UPDATE
string ext = trans.encode(true);
*/
res.content = overview;
res.mime = "application/json";
});
add("^/api/collage.jpg" HTTP_Q, "GET", [this](Response &res, Request &req) {
/*
rfc3986::Form trans;
// transfer all applicable image parameters to trans
// so we can later use that for image display
#define PICPAC_CONFIG_UPDATE(C,P) \
{ auto it = query.find(#P); if (it != query.end()) trans.insert(*it);}
PICPAC_CONFIG_UPDATE_ALL(0);
#undef PICPAC_CONFIG_UPDATE
string ext = trans.encode(true);
*/
res.content = collage;
res.mime = "image/jpeg";
});
add("^/api/thumb" HTTP_Q, "GET", [this](Response &res, Request &req) {
int cls = req.GET.get<int>("class", 0);
int off = req.GET.get<int>("offset", 0);
if (cls >= samples.size()
|| off >= samples[cls].size()) {
res.status = 404;
res.status_string = "Not Found";
}
else {
res.mime = "image/jpeg";
res.content = samples[cls][off];
}
});
add("^/api/sample" HTTP_Q, "GET", [this](Response &res, Request &req) {
int count = req.GET.get<int>("count", 20);
//string anno = query.get<string>("anno", "");
vector<int> ids(count);
for (auto &id: ids) {
id = rand() % db.size();
}
Json json = Json::object {
{"samples", Json(ids)},
};
res.mime = "application/json";
res.content = json.dump();
});
add("^/api/file" HTTP_Q, "GET",
[this](Response &res, Request &req) {
int id = req.GET.get<int>("id", 0);
Record rec;
db.read(id, &rec);
string buf = rec.field_string(0);
res.mime = magic_buffer(cookie, &buf[0], buf.size());
res.content.swap(buf);
});
add("^/api/image" HTTP_Q, "GET",
[this](Response &res, Request &req) {
PICPAC_CONFIG conf;
conf.anno_color3 = 255;
conf.anno_copy = true;
conf.anno_thickness = 2;
conf.pert_color1 = 20;
conf.pert_color2 = 20;
conf.pert_color3 = 20;
conf.pert_angle = 20;
conf.pert_min_scale = 0.8;
conf.pert_max_scale = 1.2;
#define PICPAC_CONFIG_UPDATE(C,P) C.P = req.GET.get<decltype(C.P)>(#P, C.P)
PICPAC_CONFIG_UPDATE_ALL(conf);
#undef PICPAC_CONFIG_UPDATE
float anno_factor = req.GET.get<float>("anno_factor", 0);
LOG(INFO) << "ANNO: " << anno_factor;
bool do_norm = req.GET.get<int>("norm", 0);
ImageLoader loader(conf);
ImageLoader::PerturbVector pv;
int id = req.GET.get<int>("id", rng() % db.size());
ImageLoader::Value v;
loader.sample(rng, &pv);
loader.load([this, id](Record *r){db.read(id, r);}, pv, &v);
ImageEncoder encoder;
string buf;
cv::Mat image = v.image;
if (conf.annotate.size()) {
image = v.annotation;
if (anno_factor) {
image *= anno_factor;
}
}
if (do_norm) {
cv::Mat tmp;
cv::normalize(image, tmp, 0, 255, cv::NORM_MINMAX, CV_8U);
image = tmp;
}
encoder.encode(image, &buf);
res.mime = "image/jpeg";
res.content.swap(buf);
});
add_default("GET",
[this](Response &res, Request &req) {
string path = req.path;
bfdfs::Page page;
bool loaded = statics.load(path, &page);
if (!loaded) {
path = "/index.html";
loaded = statics.load(path, &page);
}
if (loaded) {
auto it = req.header.find("If-None-Match");
do {
if (it != req.header.end()) {
string const &tag = it->second;
if (tag == page.checksum || (true
&& (tag.size() == (page.checksum.size() + 2))
&& (tag.find(page.checksum) == 1)
&& (tag.front() == '"')
&& (tag.back() == '"'))) {
res.status = 304;
res.status_string = "Not Modified";
res.content.clear();
break;
}
}
res.content = string(page.begin, page.end);
bool gz = false;
res.mime = path2mime(path, &gz);
res.header.insert(make_pair(string("ETag"), '"' + page.checksum +'"'));
if (gz) {
SimpleWeb::plugins::deflate(res, req);
}
} while (false);
}
else {
res.status = 404;
res.content.clear();
}
});
}
~Service () {
magic_close(cookie);
}
};
int main(int argc, char const* argv[]) {
banner();
//string address;
unsigned short port;
int threads;
fs::path db_path;
namespace po = boost::program_options;
po::options_description desc("Allowed options");
desc.add_options()
("help,h", "produce help message.")
//("address", po::value(&address)->default_value("0.0.0.0"), "")
("port", po::value(&port)->default_value(18888), "")
("db", po::value(&db_path), "")
("threads,t", po::value(&threads)->default_value(1), "")
("no-browser", "do not start browser")
("max-peek", po::value(&max_peak_mb)->default_value(1000), "read this number MB of data")
;
po::options_description desc_hidden("Expert options");
desc_hidden.add_options()
//("html_root", po::value(&html_root), "")
;
desc.add(desc_hidden);
po::positional_options_description p;
p.add("db", 1);
po::variables_map vm;
po::store(po::command_line_parser(argc, argv).
options(desc).positional(p).run(), vm);
po::notify(vm);
if (vm.count("help") || db_path.empty()) {
cout << "Usage:" << endl;
cout << "\tserver ... <db>" << endl;
cout << desc;
cout << endl;
return 0;
}
HttpServer server(port, threads);
Service service(db_path, &server);
thread th([&]() {
LOG(INFO) << "listening at port: " << port;
LOG(INFO) << "running server with " << threads << " threads.";
server.start();
});
do { // test and start web browser
if (vm.count("no-browser")) break;
char *display = getenv("DISPLAY");
if ((!display) || (strlen(display) == 0)) {
LOG(WARNING) << "No DISPLAY found, not starting browser.";
break;
}
boost::format cmd("xdg-open http://localhost:%1%");
system((cmd % port).str().c_str());
} while (false);
// GET /hello
th.join();
return 0;
}
<|endoftext|> |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.