text stringlengths 54 60.6k |
|---|
<commit_before>#include "board.hpp"
#include "enemy.hpp"
#include "level.hpp"
#include "random.hpp"
namespace roadagain
{
Enemy::Enemy(Level level) : level_(level)
{
}
Enemy::~Enemy()
{
}
Point Enemy::select(const Board* board, const CellColor& stone) const
{
switch (level_){
case EASY:
return (randomized_select(board, stone));
case MEDIUM:
return (maximized_select(board, stone));
default:
return (evaluated_select(board, stone));
}
}
const int Enemy::SCORE_TABLE[Board::ROW][Board::COL] = {
{ 50, -20, 20, 15, 15, 20, -20, 50 },
{ -20, -20, 20, -10, -10, 20, -20, -20 },
{ 20, 20, 20, 10, 10, 20, 20, 20 },
{ 15, -10, 10, 15, 15, 10, -10, 15 },
{ 15, -10, 10, 15, 15, 10, -10, 15 },
{ 20, 20, 20, 10, 10, 20, 20, 20 },
{ -20, -20, 20, -10, -10, 20, -20, -20 },
{ 50, -20, 20, 15, 15, 20, -20, 50 },
};
Point Enemy::randomized_select(const Board* board, const CellColor& stone) const
{
int n = random();
Cell c(stone);
do {
c.point.y++;
if (c.point.y >= Board::ROW){
c.point.y = 0;
c.point.x = (c.point.x + 1) % Board::COL;
}
while (not board->can_put(c)){
c.point.y++;
if (c.point.y >= Board::ROW){
c.point.y = 0;
c.point.x = (c.point.x + 1) % Board::COL;
}
}
n--;
} while (n > 0);
return (c.point);
}
Point Enemy::maximized_select(const Board* board, const CellColor& stone) const
{
Point p;
int maximum = 0;
for (int i = 0; i < Board::ROW; i++){
for (int j = 0; j < Board::COL; j++){
Cell c(i, j, stone);
if (board->can_put(c)){
int tmp = board->reverse_num(c);
if (maximum < tmp){
maximum = tmp;
p = c.point;
}
else if (maximum == tmp && random() % 2 == 0){
p = c.point;
}
}
}
}
return (p);
}
Point Enemy::evaluated_select(const Board* board, const CellColor& stone, int depth) const
{
if (depth >= MAX_DEPTH){
return Point(-1, -1);
}
Point p;
int maximum = MIN_EVALUTE_VALUE;
for (int i = 0; i < Board::ROW; i++){
for (int j = 0; j < Board::COL; j++){
Cell c(i, j, stone);
if (board->can_put(c)){
Board t_board(*board);
int tmp = reverse_score(&t_board, c, depth);
if (maximum < tmp){
maximum = tmp;
p = c.point;
}
else if (maximum == tmp && random() % 2 == 0){
p = c.point;
}
}
}
}
return (p);
}
int Enemy::reverse_score(Board* board, const Cell& cell, int depth) const
{
int score = SCORE_TABLE[cell.point.y][cell.point.x] + board->count_neighbor(cell.point, cell.color.reversed()) * 3;
board->put(cell, false);
for (const Point& d : Board::D){
score += reverse_score(board, cell, d);
bool player_put = false;
for (int i = 0; i < Board::ROW; i++){
for (int j = 0; j < Board::COL; j++){
if (board->can_put(Cell(i, j, cell.color.reversed()))){
score -= 3;
player_put = true;
}
}
}
if (not player_put){
score += 50;
Point player_point = evaluated_select(board, cell.color, depth + 1);
if (player_point.y != -1 && player_point.x != -1){
score += reverse_score(board, Cell(player_point, cell.color), depth + 1);
}
}
else {
Point player_point = evaluated_select(board, cell.color.reversed(), depth + 1);
if (player_point.y != -1 && player_point.x != -1){
score -= reverse_score(board, Cell(player_point, cell.color.reversed()), depth + 1);
}
}
}
return (score);
}
int Enemy::reverse_score(const Board* board, const Cell& cell, const Point& d) const
{
int score = 0;
int num = board->reverse_num(cell, d);
for (int i = 1; i < num; i++){
score += SCORE_TABLE[cell.point.y + d.y * i][cell.point.x + d.x * i];
}
return (score - num * 3);
}
} // namespace roadagain
<commit_msg>Get out non-differenitated check outside of loop<commit_after>#include "board.hpp"
#include "enemy.hpp"
#include "level.hpp"
#include "random.hpp"
namespace roadagain
{
Enemy::Enemy(Level level) : level_(level)
{
}
Enemy::~Enemy()
{
}
Point Enemy::select(const Board* board, const CellColor& stone) const
{
switch (level_){
case EASY:
return (randomized_select(board, stone));
case MEDIUM:
return (maximized_select(board, stone));
default:
return (evaluated_select(board, stone));
}
}
const int Enemy::SCORE_TABLE[Board::ROW][Board::COL] = {
{ 50, -20, 20, 15, 15, 20, -20, 50 },
{ -20, -20, 20, -10, -10, 20, -20, -20 },
{ 20, 20, 20, 10, 10, 20, 20, 20 },
{ 15, -10, 10, 15, 15, 10, -10, 15 },
{ 15, -10, 10, 15, 15, 10, -10, 15 },
{ 20, 20, 20, 10, 10, 20, 20, 20 },
{ -20, -20, 20, -10, -10, 20, -20, -20 },
{ 50, -20, 20, 15, 15, 20, -20, 50 },
};
Point Enemy::randomized_select(const Board* board, const CellColor& stone) const
{
int n = random();
Cell c(stone);
do {
c.point.y++;
if (c.point.y >= Board::ROW){
c.point.y = 0;
c.point.x = (c.point.x + 1) % Board::COL;
}
while (not board->can_put(c)){
c.point.y++;
if (c.point.y >= Board::ROW){
c.point.y = 0;
c.point.x = (c.point.x + 1) % Board::COL;
}
}
n--;
} while (n > 0);
return (c.point);
}
Point Enemy::maximized_select(const Board* board, const CellColor& stone) const
{
Point p;
int maximum = 0;
for (int i = 0; i < Board::ROW; i++){
for (int j = 0; j < Board::COL; j++){
Cell c(i, j, stone);
if (board->can_put(c)){
int tmp = board->reverse_num(c);
if (maximum < tmp){
maximum = tmp;
p = c.point;
}
else if (maximum == tmp && random() % 2 == 0){
p = c.point;
}
}
}
}
return (p);
}
Point Enemy::evaluated_select(const Board* board, const CellColor& stone, int depth) const
{
if (depth >= MAX_DEPTH){
return Point(-1, -1);
}
Point p;
int maximum = MIN_EVALUTE_VALUE;
for (int i = 0; i < Board::ROW; i++){
for (int j = 0; j < Board::COL; j++){
Cell c(i, j, stone);
if (board->can_put(c)){
Board t_board(*board);
int tmp = reverse_score(&t_board, c, depth);
if (maximum < tmp){
maximum = tmp;
p = c.point;
}
else if (maximum == tmp && random() % 2 == 0){
p = c.point;
}
}
}
}
return (p);
}
int Enemy::reverse_score(Board* board, const Cell& cell, int depth) const
{
int score = SCORE_TABLE[cell.point.y][cell.point.x] + board->count_neighbor(cell.point, cell.color.reversed()) * 3;
board->put(cell, false);
for (const Point& d : Board::D){
score += reverse_score(board, cell, d);
}
bool player_put = false;
for (int i = 0; i < Board::ROW; i++){
for (int j = 0; j < Board::COL; j++){
if (board->can_put(Cell(i, j, cell.color.reversed()))){
score -= 3;
player_put = true;
}
}
}
if (not player_put){
score += 50;
Point player_point = evaluated_select(board, cell.color, depth + 1);
if (player_point.y != -1 && player_point.x != -1){
score += reverse_score(board, Cell(player_point, cell.color), depth + 1);
}
}
else {
Point player_point = evaluated_select(board, cell.color.reversed(), depth + 1);
if (player_point.y != -1 && player_point.x != -1){
score -= reverse_score(board, Cell(player_point, cell.color.reversed()), depth + 1);
}
}
return (score);
}
int Enemy::reverse_score(const Board* board, const Cell& cell, const Point& d) const
{
int score = 0;
int num = board->reverse_num(cell, d);
for (int i = 1; i < num; i++){
score += SCORE_TABLE[cell.point.y + d.y * i][cell.point.x + d.x * i];
}
return (score - num * 3);
}
} // namespace roadagain
<|endoftext|> |
<commit_before>#include <iostream>
#include <string>
#include "LookAndSay.hpp"
void run_part_one() {
std::string value = "1113222113";
for (unsigned int i = 0; i< 40; i++) {
value = look_and_say(value);
}
std::cout << value.length() << std::endl;
}
void run_part_two() {
}
int main(int argc, char* argv[]) {
if (argc > 1) {
if (std::string(argv[1]) == "--part_two") {
run_part_two();
} else {
std::cout << "Usage: day10 [--part_two]" << std::endl;
return -1;
}
} else {
run_part_one();
}
}
<commit_msg>added runtime code for day 10 part two<commit_after>#include <iostream>
#include <string>
#include "LookAndSay.hpp"
void run_part_one() {
std::string value = "1113222113";
for (unsigned int i = 0; i< 40; i++) {
value = look_and_say(value);
}
std::cout << value.length() << std::endl;
}
void run_part_two() {
std::string value = "1113222113";
for (unsigned int i = 0; i< 50; i++) {
value = look_and_say(value);
}
std::cout << value.length() << std::endl;
}
int main(int argc, char* argv[]) {
if (argc > 1) {
if (std::string(argv[1]) == "--part_two") {
run_part_two();
} else {
std::cout << "Usage: day10 [--part_two]" << std::endl;
return -1;
}
} else {
run_part_one();
}
}
<|endoftext|> |
<commit_before>// -----------------------------------------------------------------------------------------
// <copyright file="cloud_client.cpp" company="Microsoft">
// Copyright 2013 Microsoft Corporation
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
// </copyright>
// -----------------------------------------------------------------------------------------
#include "stdafx.h"
#include "was/service_client.h"
#include "wascore/protocol.h"
#include "wascore/protocol_xml.h"
namespace azure { namespace storage {
pplx::task<service_properties> cloud_client::download_service_properties_base_async(const request_options& modified_options, operation_context context) const
{
auto command = std::make_shared<core::storage_command<service_properties>>(base_uri());
command->set_build_request(std::bind(protocol::get_service_properties, std::placeholders::_1, std::placeholders::_2, std::placeholders::_3));
command->set_authentication_handler(authentication_handler());
command->set_location_mode(core::command_location_mode::primary_or_secondary);
command->set_preprocess_response(std::bind(protocol::preprocess_response<service_properties>, service_properties(), std::placeholders::_1, std::placeholders::_2, std::placeholders::_3));
command->set_postprocess_response([] (const web::http::http_response& response, const request_result&, const core::ostream_descriptor&, operation_context context) -> pplx::task<service_properties>
{
protocol::service_properties_reader reader(response.body());
return pplx::task_from_result<service_properties>(reader.move_properties());
});
return core::executor<service_properties>::execute_async(command, modified_options, context);
}
pplx::task<void> cloud_client::upload_service_properties_base_async(const service_properties& properties, const service_properties_includes& includes, const request_options& modified_options, operation_context context) const
{
protocol::service_properties_writer writer;
concurrency::streams::istream stream(concurrency::streams::bytestream::open_istream(writer.write(properties, includes)));
auto command = std::make_shared<core::storage_command<void>>(base_uri());
command->set_build_request(std::bind(protocol::set_service_properties, std::placeholders::_1, std::placeholders::_2, std::placeholders::_3));
command->set_authentication_handler(authentication_handler());
command->set_preprocess_response(std::bind(protocol::preprocess_response_void, std::placeholders::_1, std::placeholders::_2, std::placeholders::_3));
return core::istream_descriptor::create(stream).then([command, context, modified_options] (core::istream_descriptor request_body) -> pplx::task<void>
{
command->set_request_body(request_body);
return core::executor<void>::execute_async(command, modified_options, context);
});
}
pplx::task<service_stats> cloud_client::download_service_stats_base_async(const request_options& modified_options, operation_context context) const
{
auto command = std::make_shared<core::storage_command<service_stats>>(base_uri());
command->set_build_request(std::bind(protocol::get_service_stats, std::placeholders::_1, std::placeholders::_2, std::placeholders::_3));
command->set_authentication_handler(authentication_handler());
command->set_location_mode(core::command_location_mode::primary_or_secondary);
command->set_preprocess_response(std::bind(protocol::preprocess_response<service_stats>, service_stats(), std::placeholders::_1, std::placeholders::_2, std::placeholders::_3));
command->set_postprocess_response([] (const web::http::http_response& response, const request_result&, const core::ostream_descriptor&, operation_context context) -> pplx::task<service_stats>
{
protocol::service_stats_reader reader(response.body());
return pplx::task_from_result<service_stats>(reader.move_stats());
});
return core::executor<service_stats>::execute_async(command, modified_options, context);
}
}
} // namespace azure::storage
<commit_msg>Throw exception to warn on the conflict between primary_only and download_services_stats<commit_after>// -----------------------------------------------------------------------------------------
// <copyright file="cloud_client.cpp" company="Microsoft">
// Copyright 2013 Microsoft Corporation
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
// </copyright>
// -----------------------------------------------------------------------------------------
#include "stdafx.h"
#include "was/service_client.h"
#include "wascore/protocol.h"
#include "wascore/protocol_xml.h"
namespace azure { namespace storage {
pplx::task<service_properties> cloud_client::download_service_properties_base_async(const request_options& modified_options, operation_context context) const
{
auto command = std::make_shared<core::storage_command<service_properties>>(base_uri());
command->set_build_request(std::bind(protocol::get_service_properties, std::placeholders::_1, std::placeholders::_2, std::placeholders::_3));
command->set_authentication_handler(authentication_handler());
command->set_location_mode(core::command_location_mode::primary_or_secondary);
command->set_preprocess_response(std::bind(protocol::preprocess_response<service_properties>, service_properties(), std::placeholders::_1, std::placeholders::_2, std::placeholders::_3));
command->set_postprocess_response([] (const web::http::http_response& response, const request_result&, const core::ostream_descriptor&, operation_context context) -> pplx::task<service_properties>
{
protocol::service_properties_reader reader(response.body());
return pplx::task_from_result<service_properties>(reader.move_properties());
});
return core::executor<service_properties>::execute_async(command, modified_options, context);
}
pplx::task<void> cloud_client::upload_service_properties_base_async(const service_properties& properties, const service_properties_includes& includes, const request_options& modified_options, operation_context context) const
{
protocol::service_properties_writer writer;
concurrency::streams::istream stream(concurrency::streams::bytestream::open_istream(writer.write(properties, includes)));
auto command = std::make_shared<core::storage_command<void>>(base_uri());
command->set_build_request(std::bind(protocol::set_service_properties, std::placeholders::_1, std::placeholders::_2, std::placeholders::_3));
command->set_authentication_handler(authentication_handler());
command->set_preprocess_response(std::bind(protocol::preprocess_response_void, std::placeholders::_1, std::placeholders::_2, std::placeholders::_3));
return core::istream_descriptor::create(stream).then([command, context, modified_options] (core::istream_descriptor request_body) -> pplx::task<void>
{
command->set_request_body(request_body);
return core::executor<void>::execute_async(command, modified_options, context);
});
}
pplx::task<service_stats> cloud_client::download_service_stats_base_async(const request_options& modified_options, operation_context context) const
{
if (modified_options.location_mode() == location_mode::primary_only)
{
throw storage_exception("download_service_stats cannot be run with a 'primary_only' location mode.");
}
auto command = std::make_shared<core::storage_command<service_stats>>(base_uri());
command->set_build_request(std::bind(protocol::get_service_stats, std::placeholders::_1, std::placeholders::_2, std::placeholders::_3));
command->set_authentication_handler(authentication_handler());
command->set_location_mode(core::command_location_mode::primary_or_secondary);
command->set_preprocess_response(std::bind(protocol::preprocess_response<service_stats>, service_stats(), std::placeholders::_1, std::placeholders::_2, std::placeholders::_3));
command->set_postprocess_response([] (const web::http::http_response& response, const request_result&, const core::ostream_descriptor&, operation_context context) -> pplx::task<service_stats>
{
protocol::service_stats_reader reader(response.body());
return pplx::task_from_result<service_stats>(reader.move_stats());
});
return core::executor<service_stats>::execute_async(command, modified_options, context);
}
}
} // namespace azure::storage
<|endoftext|> |
<commit_before>// Copyright (c) 2011 The LevelDB Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file. See the AUTHORS file for names of contributors.
#define __STDC_LIMIT_MACROS
#include "db/db_iter.h"
#include "db/filename.h"
#include "db/db_impl.h"
#include "db/dbformat.h"
#include "hyperleveldb/env.h"
#include "hyperleveldb/iterator.h"
#include "port/port.h"
#include "util/logging.h"
#include "util/mutexlock.h"
#include "util/random.h"
namespace leveldb {
#if 0
static void DumpInternalIter(Iterator* iter) {
for (iter->SeekToFirst(); iter->Valid(); iter->Next()) {
ParsedInternalKey k;
if (!ParseInternalKey(iter->key(), &k)) {
fprintf(stderr, "Corrupt '%s'\n", EscapeString(iter->key()).c_str());
} else {
fprintf(stderr, "@ '%s'\n", k.DebugString().c_str());
}
}
}
#endif
namespace {
// Memtables and sstables that make the DB representation contain
// (userkey,seq,type) => uservalue entries. DBIter
// combines multiple entries for the same userkey found in the DB
// representation into a single entry while accounting for sequence
// numbers, deletion markers, overwrites, etc.
class DBIter: public Iterator {
public:
// Which direction is the iterator currently moving?
// (1) When moving forward, the internal iterator is positioned at
// the exact entry that yields this->key(), this->value()
// (2) When moving backwards, the internal iterator is positioned
// just before all entries whose user key == this->key().
enum Direction {
kForward,
kReverse
};
DBIter(DBImpl* db, const Comparator* cmp, Iterator* iter, SequenceNumber s,
uint32_t seed)
: db_(db),
user_comparator_(cmp),
iter_(iter),
sequence_(s),
status_(),
saved_key_(),
saved_value_(),
direction_(kForward),
valid_(false),
rnd_(seed),
bytes_counter_(RandomPeriod()) {
}
virtual ~DBIter() {
delete iter_;
}
virtual bool Valid() const { return valid_; }
virtual Slice key() const {
assert(valid_);
return (direction_ == kForward) ? ExtractUserKey(iter_->key()) : saved_key_;
}
virtual Slice value() const {
assert(valid_);
return (direction_ == kForward) ? iter_->value() : saved_value_;
}
virtual const Status& status() const {
if (status_.ok()) {
return iter_->status();
} else {
return status_;
}
}
virtual void Next();
virtual void Prev();
virtual void Seek(const Slice& target);
virtual void SeekToFirst();
virtual void SeekToLast();
private:
void FindNextUserEntry(bool skipping, std::string* skip);
void FindPrevUserEntry();
bool ParseKey(ParsedInternalKey* key);
inline void SaveKey(const Slice& k, std::string* dst) {
dst->assign(k.data(), k.size());
}
inline void ClearSavedValue() {
if (saved_value_.capacity() > 1048576) {
std::string empty;
swap(empty, saved_value_);
} else {
saved_value_.clear();
}
}
// Pick next gap with average value of config::kReadBytesPeriod.
ssize_t RandomPeriod() {
return rnd_.Uniform(2*config::kReadBytesPeriod);
}
DBImpl* db_;
const Comparator* const user_comparator_;
Iterator* const iter_;
SequenceNumber const sequence_;
Status status_;
std::string saved_key_; // == current key when direction_==kReverse
std::string saved_value_; // == current raw value when direction_==kReverse
Direction direction_;
bool valid_;
Random rnd_;
ssize_t bytes_counter_;
// No copying allowed
DBIter(const DBIter&);
void operator=(const DBIter&);
};
inline bool DBIter::ParseKey(ParsedInternalKey* ikey) {
Slice k = iter_->key();
ssize_t n = k.size() + iter_->value().size();
bytes_counter_ -= n;
while (bytes_counter_ < 0) {
bytes_counter_ += RandomPeriod();
db_->RecordReadSample(k);
}
if (!ParseInternalKey(k, ikey)) {
status_ = Status::Corruption("corrupted internal key in DBIter");
return false;
} else {
return true;
}
}
void DBIter::Next() {
assert(valid_);
if (direction_ == kReverse) { // Switch directions?
direction_ = kForward;
// iter_ is pointing just before the entries for this->key(),
// so advance into the range of entries for this->key() and then
// use the normal skipping code below.
if (!iter_->Valid()) {
iter_->SeekToFirst();
} else {
iter_->Next();
}
if (!iter_->Valid()) {
valid_ = false;
saved_key_.clear();
return;
}
// saved_key_ already contains the key to skip past.
} else {
// Store in saved_key_ the current key so we skip it below.
SaveKey(ExtractUserKey(iter_->key()), &saved_key_);
}
FindNextUserEntry(true, &saved_key_);
}
void DBIter::FindNextUserEntry(bool skipping, std::string* skip) {
// Loop until we hit an acceptable entry to yield
assert(iter_->Valid());
assert(direction_ == kForward);
do {
ParsedInternalKey ikey;
if (ParseKey(&ikey) && ikey.sequence <= sequence_) {
switch (ikey.type) {
case kTypeDeletion:
// Arrange to skip all upcoming entries for this key since
// they are hidden by this deletion.
SaveKey(ikey.user_key, skip);
skipping = true;
break;
case kTypeValue:
if (skipping &&
user_comparator_->Compare(ikey.user_key, *skip) <= 0) {
// Entry hidden
} else {
valid_ = true;
saved_key_.clear();
return;
}
break;
default:
break;
}
}
iter_->Next();
} while (iter_->Valid());
saved_key_.clear();
valid_ = false;
}
void DBIter::Prev() {
assert(valid_);
if (direction_ == kForward) { // Switch directions?
// iter_ is pointing at the current entry. Scan backwards until
// the key changes so we can use the normal reverse scanning code.
assert(iter_->Valid()); // Otherwise valid_ would have been false
SaveKey(ExtractUserKey(iter_->key()), &saved_key_);
while (true) {
iter_->Prev();
if (!iter_->Valid()) {
valid_ = false;
saved_key_.clear();
ClearSavedValue();
return;
}
if (user_comparator_->Compare(ExtractUserKey(iter_->key()),
saved_key_) < 0) {
break;
}
}
direction_ = kReverse;
}
FindPrevUserEntry();
}
void DBIter::FindPrevUserEntry() {
assert(direction_ == kReverse);
ValueType value_type = kTypeDeletion;
if (iter_->Valid()) {
do {
ParsedInternalKey ikey;
if (ParseKey(&ikey) && ikey.sequence <= sequence_) {
if ((value_type != kTypeDeletion) &&
user_comparator_->Compare(ikey.user_key, saved_key_) < 0) {
// We encountered a non-deleted value in entries for previous keys,
break;
}
value_type = ikey.type;
if (value_type == kTypeDeletion) {
saved_key_.clear();
ClearSavedValue();
} else {
Slice raw_value = iter_->value();
if (saved_value_.capacity() > raw_value.size() + 1048576) {
std::string empty;
swap(empty, saved_value_);
}
SaveKey(ExtractUserKey(iter_->key()), &saved_key_);
saved_value_.assign(raw_value.data(), raw_value.size());
}
}
iter_->Prev();
} while (iter_->Valid());
}
if (value_type == kTypeDeletion) {
// End
valid_ = false;
saved_key_.clear();
ClearSavedValue();
direction_ = kForward;
} else {
valid_ = true;
}
}
void DBIter::Seek(const Slice& target) {
direction_ = kForward;
ClearSavedValue();
saved_key_.clear();
AppendInternalKey(
&saved_key_, ParsedInternalKey(target, sequence_, kValueTypeForSeek));
iter_->Seek(saved_key_);
if (iter_->Valid()) {
FindNextUserEntry(false, &saved_key_ /* temporary storage */);
} else {
valid_ = false;
}
}
void DBIter::SeekToFirst() {
direction_ = kForward;
ClearSavedValue();
iter_->SeekToFirst();
if (iter_->Valid()) {
FindNextUserEntry(false, &saved_key_ /* temporary storage */);
} else {
valid_ = false;
}
}
void DBIter::SeekToLast() {
direction_ = kReverse;
ClearSavedValue();
iter_->SeekToLast();
FindPrevUserEntry();
}
} // anonymous namespace
Iterator* NewDBIterator(
DBImpl* db,
const Comparator* user_key_comparator,
Iterator* internal_iter,
SequenceNumber sequence,
uint32_t seed) {
return new DBIter(db, user_key_comparator, internal_iter, sequence, seed);
}
} // namespace leveldb
<commit_msg>Record seeks through many tombstones<commit_after>// Copyright (c) 2011 The LevelDB Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file. See the AUTHORS file for names of contributors.
#define __STDC_LIMIT_MACROS
#include "db/db_iter.h"
#include "db/filename.h"
#include "db/db_impl.h"
#include "db/dbformat.h"
#include "hyperleveldb/env.h"
#include "hyperleveldb/iterator.h"
#include "port/port.h"
#include "util/logging.h"
#include "util/mutexlock.h"
#include "util/random.h"
namespace leveldb {
#if 0
static void DumpInternalIter(Iterator* iter) {
for (iter->SeekToFirst(); iter->Valid(); iter->Next()) {
ParsedInternalKey k;
if (!ParseInternalKey(iter->key(), &k)) {
fprintf(stderr, "Corrupt '%s'\n", EscapeString(iter->key()).c_str());
} else {
fprintf(stderr, "@ '%s'\n", k.DebugString().c_str());
}
}
}
#endif
namespace {
// Memtables and sstables that make the DB representation contain
// (userkey,seq,type) => uservalue entries. DBIter
// combines multiple entries for the same userkey found in the DB
// representation into a single entry while accounting for sequence
// numbers, deletion markers, overwrites, etc.
class DBIter: public Iterator {
public:
// Which direction is the iterator currently moving?
// (1) When moving forward, the internal iterator is positioned at
// the exact entry that yields this->key(), this->value()
// (2) When moving backwards, the internal iterator is positioned
// just before all entries whose user key == this->key().
enum Direction {
kForward,
kReverse
};
DBIter(DBImpl* db, const Comparator* cmp, Iterator* iter, SequenceNumber s,
uint32_t seed)
: db_(db),
user_comparator_(cmp),
iter_(iter),
sequence_(s),
status_(),
saved_key_(),
saved_value_(),
direction_(kForward),
valid_(false),
rnd_(seed),
bytes_counter_(RandomPeriod()),
tombstones_counter_(0) {
}
virtual ~DBIter() {
delete iter_;
}
virtual bool Valid() const { return valid_; }
virtual Slice key() const {
assert(valid_);
return (direction_ == kForward) ? ExtractUserKey(iter_->key()) : saved_key_;
}
virtual Slice value() const {
assert(valid_);
return (direction_ == kForward) ? iter_->value() : saved_value_;
}
virtual const Status& status() const {
if (status_.ok()) {
return iter_->status();
} else {
return status_;
}
}
virtual void Next();
virtual void Prev();
virtual void Seek(const Slice& target);
virtual void SeekToFirst();
virtual void SeekToLast();
private:
void FindNextUserEntry(bool skipping, std::string* skip);
void FindPrevUserEntry();
bool ParseKey(ParsedInternalKey* key);
inline void SaveKey(const Slice& k, std::string* dst) {
dst->assign(k.data(), k.size());
}
inline void ClearSavedValue() {
if (saved_value_.capacity() > 1048576) {
std::string empty;
swap(empty, saved_value_);
} else {
saved_value_.clear();
}
}
// Pick next gap with average value of config::kReadBytesPeriod.
ssize_t RandomPeriod() {
return rnd_.Uniform(2*config::kReadBytesPeriod);
}
DBImpl* db_;
const Comparator* const user_comparator_;
Iterator* const iter_;
SequenceNumber const sequence_;
Status status_;
std::string saved_key_; // == current key when direction_==kReverse
std::string saved_value_; // == current raw value when direction_==kReverse
Direction direction_;
bool valid_;
Random rnd_;
ssize_t bytes_counter_;
ssize_t tombstones_counter_;
// No copying allowed
DBIter(const DBIter&);
void operator=(const DBIter&);
};
inline bool DBIter::ParseKey(ParsedInternalKey* ikey) {
Slice k = iter_->key();
ssize_t n = k.size() + iter_->value().size();
bytes_counter_ -= n;
while (bytes_counter_ < 0) {
bytes_counter_ += RandomPeriod();
db_->RecordReadSample(k);
}
if (!ParseInternalKey(k, ikey)) {
status_ = Status::Corruption("corrupted internal key in DBIter");
return false;
} else {
if (ikey->type == kTypeDeletion) {
++tombstones_counter_;
if (tombstones_counter_ > 64) {
db_->RecordReadSample(k);
tombstones_counter_ = 0;
}
}
return true;
}
}
void DBIter::Next() {
assert(valid_);
if (direction_ == kReverse) { // Switch directions?
direction_ = kForward;
// iter_ is pointing just before the entries for this->key(),
// so advance into the range of entries for this->key() and then
// use the normal skipping code below.
if (!iter_->Valid()) {
iter_->SeekToFirst();
} else {
iter_->Next();
}
if (!iter_->Valid()) {
valid_ = false;
saved_key_.clear();
return;
}
// saved_key_ already contains the key to skip past.
} else {
// Store in saved_key_ the current key so we skip it below.
SaveKey(ExtractUserKey(iter_->key()), &saved_key_);
}
FindNextUserEntry(true, &saved_key_);
}
void DBIter::FindNextUserEntry(bool skipping, std::string* skip) {
// Loop until we hit an acceptable entry to yield
assert(iter_->Valid());
assert(direction_ == kForward);
do {
ParsedInternalKey ikey;
if (ParseKey(&ikey) && ikey.sequence <= sequence_) {
switch (ikey.type) {
case kTypeDeletion:
// Arrange to skip all upcoming entries for this key since
// they are hidden by this deletion.
SaveKey(ikey.user_key, skip);
skipping = true;
break;
case kTypeValue:
if (skipping &&
user_comparator_->Compare(ikey.user_key, *skip) <= 0) {
// Entry hidden
} else {
valid_ = true;
saved_key_.clear();
return;
}
break;
default:
break;
}
}
iter_->Next();
} while (iter_->Valid());
saved_key_.clear();
valid_ = false;
}
void DBIter::Prev() {
assert(valid_);
if (direction_ == kForward) { // Switch directions?
// iter_ is pointing at the current entry. Scan backwards until
// the key changes so we can use the normal reverse scanning code.
assert(iter_->Valid()); // Otherwise valid_ would have been false
SaveKey(ExtractUserKey(iter_->key()), &saved_key_);
while (true) {
iter_->Prev();
if (!iter_->Valid()) {
valid_ = false;
saved_key_.clear();
ClearSavedValue();
return;
}
if (user_comparator_->Compare(ExtractUserKey(iter_->key()),
saved_key_) < 0) {
break;
}
}
direction_ = kReverse;
}
FindPrevUserEntry();
}
void DBIter::FindPrevUserEntry() {
assert(direction_ == kReverse);
ValueType value_type = kTypeDeletion;
if (iter_->Valid()) {
do {
ParsedInternalKey ikey;
if (ParseKey(&ikey) && ikey.sequence <= sequence_) {
if ((value_type != kTypeDeletion) &&
user_comparator_->Compare(ikey.user_key, saved_key_) < 0) {
// We encountered a non-deleted value in entries for previous keys,
break;
}
value_type = ikey.type;
if (value_type == kTypeDeletion) {
saved_key_.clear();
ClearSavedValue();
} else {
Slice raw_value = iter_->value();
if (saved_value_.capacity() > raw_value.size() + 1048576) {
std::string empty;
swap(empty, saved_value_);
}
SaveKey(ExtractUserKey(iter_->key()), &saved_key_);
saved_value_.assign(raw_value.data(), raw_value.size());
}
}
iter_->Prev();
} while (iter_->Valid());
}
if (value_type == kTypeDeletion) {
// End
valid_ = false;
saved_key_.clear();
ClearSavedValue();
direction_ = kForward;
} else {
valid_ = true;
}
}
void DBIter::Seek(const Slice& target) {
direction_ = kForward;
ClearSavedValue();
saved_key_.clear();
AppendInternalKey(
&saved_key_, ParsedInternalKey(target, sequence_, kValueTypeForSeek));
iter_->Seek(saved_key_);
if (iter_->Valid()) {
FindNextUserEntry(false, &saved_key_ /* temporary storage */);
} else {
valid_ = false;
}
}
void DBIter::SeekToFirst() {
direction_ = kForward;
ClearSavedValue();
iter_->SeekToFirst();
if (iter_->Valid()) {
FindNextUserEntry(false, &saved_key_ /* temporary storage */);
} else {
valid_ = false;
}
}
void DBIter::SeekToLast() {
direction_ = kReverse;
ClearSavedValue();
iter_->SeekToLast();
FindPrevUserEntry();
}
} // anonymous namespace
Iterator* NewDBIterator(
DBImpl* db,
const Comparator* user_key_comparator,
Iterator* internal_iter,
SequenceNumber sequence,
uint32_t seed) {
return new DBIter(db, user_key_comparator, internal_iter, sequence, seed);
}
} // namespace leveldb
<|endoftext|> |
<commit_before>/**
* @file
*/
#include "bi/io/cpp/CppResumeGenerator.hpp"
#include "bi/visitor/Gatherer.hpp"
#include "bi/primitive/encode.hpp"
bi::CppResumeGenerator::CppResumeGenerator(const Class* currentClass,
const Fiber* currentFiber, std::ostream& base, const int level,
const bool header) :
CppBaseGenerator(base, level, header),
currentClass(currentClass),
currentFiber(currentFiber),
paramIndex(0),
localIndex(currentClass ? 1 : 0) {
// ^ first local variable is self, for member fiber
}
void bi::CppResumeGenerator::visit(const Function* o) {
auto fiberType = dynamic_cast<const FiberType*>(o->returnType);
assert(fiberType);
auto generic = o->typeParams->width() + o->params->width() > 0;
auto params = requiresParam(o);
auto locals = requiresLocal(o);
bool first = true;
if (currentClass && !header) {
genTemplateParams(currentClass);
}
genSourceLine(o->loc);
if (generic || params || locals) {
start("template<");
}
for (auto typeParam : *o->typeParams) {
if (!first) {
middle(", ");
}
first = false;
middle("class " << typeParam);
}
if (params) {
if (!first) {
middle(", ");
}
first = false;
middle("class Param_");
}
if (locals) {
if (!first) {
middle(", ");
}
first = false;
middle("class Local_");
}
if (generic || params || locals) {
finish('>');
}
if (header) {
genSourceLine(o->loc);
start("struct ");
genUniqueName(o);
middle(" final : public libbirch::FiberState<");
finish(fiberType->returnType << ',' << fiberType->yieldType << "> {");
in();
if (params) {
genSourceLine(o->loc);
line("Param_ param_;\n");
}
if (locals) {
genSourceLine(o->loc);
line("Local_ local_;\n");
}
genSourceLine(o->loc);
start("");
genUniqueName(o);
middle('(');
if (params) {
middle("Param_ param_");
}
if (locals) {
if (params) {
middle(", ");
}
middle("Local_ local_");
}
middle(") ");
if (params || locals) {
middle(":");
}
if (params) {
middle(" param_(param_)");
}
if (locals) {
if (params) {
middle(',');
}
middle(" local_(local_)");
}
finish(" {");
in();
line("//");
out();
line("}\n");
genSourceLine(o->loc);
line("virtual " << fiberType << " query();");
/* boilerplace */
line("");
genSourceLine(o->loc);
if (currentClass) {
start("LIBBIRCH_MEMBER_FIBER(");
} else {
start("LIBBIRCH_FIBER(");
}
genUniqueName(o);
middle(", libbirch::FiberState<" << fiberType->returnType << ',');
finish(fiberType->yieldType << ">)");
genSourceLine(o->loc);
start("LIBBIRCH_MEMBERS(");
if (params) {
middle("param_");
}
if (locals) {
if (params) {
middle(", ");
}
middle("local_");
}
finish(')');
out();
line("};\n");
genYieldMacro(o);
} else {
genSourceLine(o->loc);
start(fiberType << " bi::");
if (currentClass) {
middle("type::" << currentClass->name);
genTemplateArgs(currentClass);
middle("::");
}
genUniqueName(o);
if (generic || params || locals) {
start('<');
}
first = true;
for (auto typeParam : *o->typeParams) {
if (!first) {
middle(", ");
}
first = false;
middle(typeParam);
}
if (params) {
if (!first) {
middle(", ");
}
first = false;
middle("Param_");
}
if (locals) {
if (!first) {
middle(", ");
}
first = false;
middle("Local_");
}
if (generic || params || locals) {
middle('>');
}
finish("::query() {");
in();
genTraceFunction(o->name->str(), o->loc);
genUnpackParam(o);
*this << o->braces->strip();
out();
line("}");
}
}
void bi::CppResumeGenerator::visit(const MemberFunction* o) {
visit(dynamic_cast<const Function*>(o));
}
void bi::CppResumeGenerator::visit(const Yield* o) {
genTraceLine(o->loc);
start("yield_");
genUniqueName(o);
finish('(' << o->single << ");");
}
void bi::CppResumeGenerator::visit(const Return* o) {
if (inLambda) {
CppBaseGenerator::visit(o);
} else {
auto fiberType = dynamic_cast<const FiberType*>(currentFiber->returnType);
assert(fiberType);
genTraceLine(o->loc);
start("return " << currentFiber->returnType << '(');
if (!o->single->isEmpty()) {
middle(fiberType->returnType << '(' << o->single << ')');
}
finish(");");
}
}
void bi::CppResumeGenerator::visit(const LocalVariable* o) {
auto name = getName(o->name->str(), o->number);
if (o->has(RESUME)) {
start("[[maybe_unused]] auto& " << name);
finish(" = local_.template get<" << localIndex++ << ">();");
} else {
genTraceLine(o->loc);
if (o->has(AUTO)) {
start("auto " << name);
} else {
start(o->type << ' ' << name);
}
genInit(o);
finish(';');
}
}
void bi::CppResumeGenerator::visit(const NamedExpression* o) {
if (o->isLocal()) {
middle(getName(o->name->str(), o->number));
if (!o->typeArgs->isEmpty()) {
middle('<' << o->typeArgs << '>');
}
} else {
CppBaseGenerator::visit(o);
}
}
void bi::CppResumeGenerator::genUniqueName(const Numbered* o) {
if (currentClass) {
middle(currentClass->name << '_');
}
middle(currentFiber->name << '_' << currentFiber->number << '_');
middle(o->number << '_');
}
void bi::CppResumeGenerator::genPackType(const Function* o) {
if (!currentFiber->typeParams->isEmpty() || requiresParam(o) ||
requiresLocal(o)) {
bool first = true;
middle('<');
if (!currentFiber->typeParams->isEmpty()) {
middle(currentFiber->typeParams);
first = false;
}
if (requiresParam(o)) {
if (!first) {
middle(',');
}
middle("decltype(");
genPackParam(o, false);
middle(')');
first = false;
}
if (requiresLocal(o)) {
if (!first) {
middle(',');
}
middle("decltype(");
genPackLocal(o, false);
middle(')');
first = false;
}
middle('>');
}
}
void bi::CppResumeGenerator::genPackParam(const Function* o, const bool move) {
Gatherer<Parameter> params;
o->params->accept(¶ms);
middle("libbirch::make_tuple(");
bool first = true;
for (auto param : params) {
if (!first) {
middle(", ");
}
first = false;
if (move) {
middle("std::move(");
}
middle(getName(param->name->str(), param->number));
if (move) {
middle(')');
}
}
middle(')');
}
void bi::CppResumeGenerator::genPackLocal(const Function* o, const bool move) {
Gatherer<LocalVariable> locals([](auto o) { return o->has(RESUME); });
o->accept(&locals);
middle("libbirch::make_tuple(");
bool first = true;
if (currentClass) {
first = false;
middle("shared_from_this_()");
}
for (auto local : locals) {
if (!first) {
middle(", ");
}
first = false;
if (move) {
middle("std::move(");
}
middle(getName(local->name->str(), local->number));
if (move) {
middle(')');
}
}
middle(')');
}
void bi::CppResumeGenerator::genUnpackParam(const Function* o) {
Gatherer<Parameter> params;
o->params->accept(¶ms);
for (auto param : params) {
genSourceLine(param->loc);
start("const auto& " << getName(param->name->str(), param->number));
finish(" = param_.template get<" << paramIndex++ << ">();");
}
}
void bi::CppResumeGenerator::genYieldMacro(const Function* o) {
auto params = requiresParam(o);
auto locals = requiresLocal(o);
start("#define yield_");
genUniqueName(o);
middle('(');
if (!o->has(START)) {
middle("...");
}
middle(") return " << currentFiber->returnType << '(');
if (!o->has(START)) {
auto fiberType = dynamic_cast<const FiberType*>(currentFiber->returnType);
assert(fiberType);
middle(fiberType->yieldType << "(__VA_ARGS__)");
}
if (!o->has(START)) {
middle(", ");
}
middle("libbirch::Lazy<libbirch::Shared<");
genUniqueName(o);
genPackType(o);
middle(">>(");
if (params) {
genPackParam(o, o->number != 0); // don't move for start function
}
if (locals) {
if (params) {
middle(", ");
}
genPackLocal(o, o->number != 0); // don't move for start function
}
middle(')');
finish(")\n");
}
bool bi::CppResumeGenerator::requiresParam(const Function* o) {
Gatherer<Parameter> params;
o->accept(¶ms);
return params.size() > 0;
}
bool bi::CppResumeGenerator::requiresLocal(const Function* o) {
Gatherer<LocalVariable> locals([](auto o) { return o->has(RESUME); });
o->accept(&locals);
return currentClass || locals.size() > 0;
}
std::string bi::CppResumeGenerator::getName(const std::string& name,
const int number) {
std::stringstream buf;
std::string result;
auto iter = names.find(number);
if (iter == names.end()) {
auto count = counts.find(name);
if (count == counts.end()) {
buf << internalise(name);
result = buf.str();
counts.insert(std::make_pair(name, 1));
} else {
buf << internalise(name) << '_' << count->second << '_';
result = buf.str();
++count->second;
}
names.insert(std::make_pair(number, result));
} else {
result = iter->second;
}
return result;
}
std::string bi::CppResumeGenerator::getIndex(const Statement* o) {
auto index = dynamic_cast<const LocalVariable*>(o);
assert(index);
return getName(index->name->str(), index->number);
}
<commit_msg>Removed use of std::move for passing state through resume functions; causing problems with gcc.<commit_after>/**
* @file
*/
#include "bi/io/cpp/CppResumeGenerator.hpp"
#include "bi/visitor/Gatherer.hpp"
#include "bi/primitive/encode.hpp"
bi::CppResumeGenerator::CppResumeGenerator(const Class* currentClass,
const Fiber* currentFiber, std::ostream& base, const int level,
const bool header) :
CppBaseGenerator(base, level, header),
currentClass(currentClass),
currentFiber(currentFiber),
paramIndex(0),
localIndex(currentClass ? 1 : 0) {
// ^ first local variable is self, for member fiber
}
void bi::CppResumeGenerator::visit(const Function* o) {
auto fiberType = dynamic_cast<const FiberType*>(o->returnType);
assert(fiberType);
auto generic = o->typeParams->width() + o->params->width() > 0;
auto params = requiresParam(o);
auto locals = requiresLocal(o);
bool first = true;
if (currentClass && !header) {
genTemplateParams(currentClass);
}
genSourceLine(o->loc);
if (generic || params || locals) {
start("template<");
}
for (auto typeParam : *o->typeParams) {
if (!first) {
middle(", ");
}
first = false;
middle("class " << typeParam);
}
if (params) {
if (!first) {
middle(", ");
}
first = false;
middle("class Param_");
}
if (locals) {
if (!first) {
middle(", ");
}
first = false;
middle("class Local_");
}
if (generic || params || locals) {
finish('>');
}
if (header) {
genSourceLine(o->loc);
start("struct ");
genUniqueName(o);
middle(" final : public libbirch::FiberState<");
finish(fiberType->returnType << ',' << fiberType->yieldType << "> {");
in();
if (params) {
genSourceLine(o->loc);
line("Param_ param_;\n");
}
if (locals) {
genSourceLine(o->loc);
line("Local_ local_;\n");
}
genSourceLine(o->loc);
start("");
genUniqueName(o);
middle('(');
if (params) {
middle("Param_ param_");
}
if (locals) {
if (params) {
middle(", ");
}
middle("Local_ local_");
}
middle(") ");
if (params || locals) {
middle(":");
}
if (params) {
middle(" param_(param_)");
}
if (locals) {
if (params) {
middle(',');
}
middle(" local_(local_)");
}
finish(" {");
in();
line("//");
out();
line("}\n");
genSourceLine(o->loc);
line("virtual " << fiberType << " query();");
/* boilerplace */
line("");
genSourceLine(o->loc);
if (currentClass) {
start("LIBBIRCH_MEMBER_FIBER(");
} else {
start("LIBBIRCH_FIBER(");
}
genUniqueName(o);
middle(", libbirch::FiberState<" << fiberType->returnType << ',');
finish(fiberType->yieldType << ">)");
genSourceLine(o->loc);
start("LIBBIRCH_MEMBERS(");
if (params) {
middle("param_");
}
if (locals) {
if (params) {
middle(", ");
}
middle("local_");
}
finish(')');
out();
line("};\n");
genYieldMacro(o);
} else {
genSourceLine(o->loc);
start(fiberType << " bi::");
if (currentClass) {
middle("type::" << currentClass->name);
genTemplateArgs(currentClass);
middle("::");
}
genUniqueName(o);
if (generic || params || locals) {
start('<');
}
first = true;
for (auto typeParam : *o->typeParams) {
if (!first) {
middle(", ");
}
first = false;
middle(typeParam);
}
if (params) {
if (!first) {
middle(", ");
}
first = false;
middle("Param_");
}
if (locals) {
if (!first) {
middle(", ");
}
first = false;
middle("Local_");
}
if (generic || params || locals) {
middle('>');
}
finish("::query() {");
in();
genTraceFunction(o->name->str(), o->loc);
genUnpackParam(o);
*this << o->braces->strip();
out();
line("}");
}
}
void bi::CppResumeGenerator::visit(const MemberFunction* o) {
visit(dynamic_cast<const Function*>(o));
}
void bi::CppResumeGenerator::visit(const Yield* o) {
genTraceLine(o->loc);
start("yield_");
genUniqueName(o);
finish('(' << o->single << ");");
}
void bi::CppResumeGenerator::visit(const Return* o) {
if (inLambda) {
CppBaseGenerator::visit(o);
} else {
genTraceLine(o->loc);
start("return " << currentFiber->returnType << '(');
if (!o->single->isEmpty()) {
middle(o->single);
}
finish(");");
}
}
void bi::CppResumeGenerator::visit(const LocalVariable* o) {
auto name = getName(o->name->str(), o->number);
if (o->has(RESUME)) {
start("[[maybe_unused]] auto& " << name);
finish(" = local_.template get<" << localIndex++ << ">();");
} else {
genTraceLine(o->loc);
if (o->has(AUTO)) {
start("auto " << name);
} else {
start(o->type << ' ' << name);
}
genInit(o);
finish(';');
}
}
void bi::CppResumeGenerator::visit(const NamedExpression* o) {
if (o->isLocal()) {
middle(getName(o->name->str(), o->number));
if (!o->typeArgs->isEmpty()) {
middle('<' << o->typeArgs << '>');
}
} else {
CppBaseGenerator::visit(o);
}
}
void bi::CppResumeGenerator::genUniqueName(const Numbered* o) {
if (currentClass) {
middle(currentClass->name << '_');
}
middle(currentFiber->name << '_' << currentFiber->number << '_');
middle(o->number << '_');
}
void bi::CppResumeGenerator::genPackType(const Function* o) {
if (!currentFiber->typeParams->isEmpty() || requiresParam(o) ||
requiresLocal(o)) {
bool first = true;
middle('<');
if (!currentFiber->typeParams->isEmpty()) {
middle(currentFiber->typeParams);
first = false;
}
if (requiresParam(o)) {
if (!first) {
middle(',');
}
middle("decltype(");
genPackParam(o, false);
middle(')');
first = false;
}
if (requiresLocal(o)) {
if (!first) {
middle(',');
}
middle("decltype(");
genPackLocal(o, false);
middle(')');
first = false;
}
middle('>');
}
}
void bi::CppResumeGenerator::genPackParam(const Function* o, const bool move) {
Gatherer<Parameter> params;
o->params->accept(¶ms);
middle("libbirch::make_tuple(");
bool first = true;
for (auto param : params) {
if (!first) {
middle(", ");
}
first = false;
if (move) {
middle("std::move(");
}
middle(getName(param->name->str(), param->number));
if (move) {
middle(')');
}
}
middle(')');
}
void bi::CppResumeGenerator::genPackLocal(const Function* o, const bool move) {
Gatherer<LocalVariable> locals([](auto o) { return o->has(RESUME); });
o->accept(&locals);
middle("libbirch::make_tuple(");
bool first = true;
if (currentClass) {
first = false;
middle("shared_from_this_()");
}
for (auto local : locals) {
if (!first) {
middle(", ");
}
first = false;
if (move) {
middle("std::move(");
}
middle(getName(local->name->str(), local->number));
if (move) {
middle(')');
}
}
middle(')');
}
void bi::CppResumeGenerator::genUnpackParam(const Function* o) {
Gatherer<Parameter> params;
o->params->accept(¶ms);
for (auto param : params) {
genSourceLine(param->loc);
start("const auto& " << getName(param->name->str(), param->number));
finish(" = param_.template get<" << paramIndex++ << ">();");
}
}
void bi::CppResumeGenerator::genYieldMacro(const Function* o) {
auto params = requiresParam(o);
auto locals = requiresLocal(o);
start("#define yield_");
genUniqueName(o);
middle('(');
if (!o->has(START)) {
middle("...");
}
middle(") return " << currentFiber->returnType << '(');
if (!o->has(START)) {
middle("__VA_ARGS__,");
}
middle("libbirch::Lazy<libbirch::Shared<");
genUniqueName(o);
genPackType(o);
middle(">>(");
if (params) {
genPackParam(o, false);
}
if (locals) {
if (params) {
middle(", ");
}
genPackLocal(o, false);
}
middle(')');
finish(")\n");
}
bool bi::CppResumeGenerator::requiresParam(const Function* o) {
Gatherer<Parameter> params;
o->accept(¶ms);
return params.size() > 0;
}
bool bi::CppResumeGenerator::requiresLocal(const Function* o) {
Gatherer<LocalVariable> locals([](auto o) { return o->has(RESUME); });
o->accept(&locals);
return currentClass || locals.size() > 0;
}
std::string bi::CppResumeGenerator::getName(const std::string& name,
const int number) {
std::stringstream buf;
std::string result;
auto iter = names.find(number);
if (iter == names.end()) {
auto count = counts.find(name);
if (count == counts.end()) {
buf << internalise(name);
result = buf.str();
counts.insert(std::make_pair(name, 1));
} else {
buf << internalise(name) << '_' << count->second << '_';
result = buf.str();
++count->second;
}
names.insert(std::make_pair(number, result));
} else {
result = iter->second;
}
return result;
}
std::string bi::CppResumeGenerator::getIndex(const Statement* o) {
auto index = dynamic_cast<const LocalVariable*>(o);
assert(index);
return getName(index->name->str(), index->number);
}
<|endoftext|> |
<commit_before><commit_msg><commit_after><|endoftext|> |
<commit_before>/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
/*
* File: main.cpp
* Author: phytress
*
* Created on July 18, 2017, 1:24 PM
*/
#include <cstdlib>
using namespace std;
/*
*
*/
int main(int argc, char** argv) {
return 0;
}
<commit_msg>Delete main.cpp<commit_after><|endoftext|> |
<commit_before>//
// @file http_protocol_module_base.cpp
// @brief shared object http protocol module absctract class
//
// Distributed under the Boost Software License, Version 1.0.(See accompanying
// file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt
//
#include <boost/xpressive/xpressive.hpp>
#include "http_protocol_module_base.h"
using namespace boost::xpressive;
l7vs::http_protocol_module_base::CHECK_RESULT_TAG l7vs::http_protocol_module_base::check_http_method( const char* buffer,
const size_t buffer_len ) const {
l7vs::http_protocol_module_base::CHECK_RESULT_TAG check_result = CHECK_OK;
char* check_string = NULL;
size_t line_length = 0;
cregex method_regex
= ( as_xpr("GET") | as_xpr("HEAD") | as_xpr("POST") |
as_xpr("PUT") | as_xpr("PROPFIND") | as_xpr("PROPPATCH") |
as_xpr("OPTIONS") | as_xpr("CONNECT") | as_xpr("COPY") |
as_xpr("TRACE") | as_xpr("DELETE") | as_xpr("LOCK") |
as_xpr("UNLOCK") | as_xpr("MOVE") | as_xpr("MKCOL")) >> _s >>
+~_s >> _s >>
"HTTP/" >> _d >> "." >> _d;
if( buffer != NULL ){
for( line_length = 0; line_length < buffer_len; line_length++ ){
if( buffer[line_length] == '\r' || buffer[line_length] == '\n' ){
break;
}
}
if( line_length < buffer_len ){
check_string = (char*)malloc( line_length + 1 );
if( check_string != NULL ){
memcpy( check_string, buffer, line_length );
check_string[line_length] = '\0';
if( !regex_match( check_string, method_regex )){
check_result = CHECK_NG;
}
free( check_string );
}
else{
check_result = CHECK_NG;
}
}
else{
check_result = CHECK_INPOSSIBLE;
}
}
else{
check_result = CHECK_NG;
}
return check_result;
}
l7vs::http_protocol_module_base::CHECK_RESULT_TAG l7vs::http_protocol_module_base::check_http_version( const char* buffer,
const size_t buffer_len ) const {
l7vs::http_protocol_module_base::CHECK_RESULT_TAG check_result = CHECK_OK;
char* check_string = NULL;
size_t line_length = 0;
cregex version_regex_request
= +alpha >> _s >>
+~_s >> _s >>
"HTTP/" >> (as_xpr("1.0")|as_xpr("1.1"));
cregex version_regex_response
= "HTTP/" >> (as_xpr("1.0")|as_xpr("1.1")) >> _s >>
repeat<3>(_d) >> _s >>
*_;
if( buffer != NULL ){
for( line_length = 0; line_length < buffer_len; line_length++ ){
if( buffer[line_length] == '\r' || buffer[line_length] == '\n' ){
break;
}
}
if( line_length < buffer_len ){
check_string = (char*)malloc( line_length + 1 );
if( check_string != NULL ){
memcpy( check_string, buffer, line_length );
check_string[line_length] = '\0';
if( !regex_match( check_string, version_regex_request ) &&
!regex_match( check_string, version_regex_response ) ){
check_result = CHECK_NG;
}
free( check_string );
}
else{
check_result = CHECK_NG;
}
}
else{
check_result = CHECK_INPOSSIBLE;
}
}
else{
check_result = CHECK_NG;
}
return check_result;
}
l7vs::http_protocol_module_base::CHECK_RESULT_TAG l7vs::http_protocol_module_base::check_status_code( const char* buffer,
const size_t buffer_len ) const {
l7vs::http_protocol_module_base::CHECK_RESULT_TAG check_result = CHECK_OK;
char* check_string = NULL;
size_t line_length = 0;
cregex status_code_regex
= "HTTP/" >> _d >> "." >> _d >> _s >>
range('1', '3') >> repeat<2>(_d) >> _s >>
*_;
if( buffer != NULL ){
for( line_length = 0; line_length < buffer_len; line_length++ ){
if( buffer[line_length] == '\r' || buffer[line_length] == '\n' ){
break;
}
}
if( line_length < buffer_len ){
check_string = (char*)malloc( line_length + 1 );
if( check_string != NULL ){
memcpy( check_string, buffer, line_length );
check_string[line_length] = '\0';
if( !regex_match( check_string, status_code_regex )){
check_result = CHECK_NG;
}
free( check_string );
}
else{
check_result = CHECK_NG;
}
}
else{
check_result = CHECK_INPOSSIBLE;
}
}
else{
check_result = CHECK_NG;
}
return check_result;
}
bool l7vs::http_protocol_module_base::find_uri( const char* buffer,
const size_t buffer_len,
size_t& uri_offset,
size_t& uri_len){
bool find_result = true;
char* find_string = NULL;
size_t line_length = 0;
match_results< const char* > result;
cregex uri_regex
= +alpha >> _s >>
(s1 = +~_s) >> _s >>
"HTTP/" >> _d >> "." >> _d;
if( buffer != NULL ){
for( line_length = 0; line_length < buffer_len; line_length++ ){
if( buffer[line_length] == '\r' || buffer[line_length] == '\n' ){
break;
}
}
if( line_length < buffer_len ){
find_string = (char*)malloc( line_length + 1 );
if( find_string != NULL ){
memcpy( find_string, buffer, line_length );
find_string[line_length] = '\0';
find_result = regex_search( find_string, result, uri_regex );
if( find_result == true ){
uri_offset = result.position(1);
uri_len = result.length(1);
}
free( find_string );
}
else{
find_result = false;
}
}
else{
find_result = false;
}
}
else{
find_result = false;
}
return find_result;
}
bool l7vs::http_protocol_module_base::find_status_code( const char* buffer,
const size_t buffer_len,
size_t& status_code_offset,
size_t& status_code_len){
bool find_result = true;
char* find_string = NULL;
size_t line_length = 0;
match_results< const char* > result;
cregex status_code_regex
= "HTTP/" >> _d >> "." >> _d >> _s >>
(s1 = repeat<3>(_d)) >> _s >>
*_;
if( buffer != NULL ){
for( line_length = 0; line_length < buffer_len; line_length++ ){
if( buffer[line_length] == '\r' || buffer[line_length] == '\n' ){
break;
}
}
if( line_length < buffer_len ){
find_string = (char*)malloc( line_length + 1 );
if( find_string != NULL ){
memcpy( find_string, buffer, line_length );
find_string[line_length] = '\0';
find_result = regex_search( find_string, result, status_code_regex );
if( find_result == true ){
status_code_offset = result.position(1);
status_code_len = result.length(1);
}
free( find_string );
}
else{
find_result = false;
}
}
else{
find_result = false;
}
}
else{
find_result = false;
}
return find_result;
}
bool l7vs::http_protocol_module_base::find_http_header( const char* buffer,
const size_t buffer_len,
const std::string& http_header_name,
size_t& http_header_offset,
size_t& http_header_len ){
bool find_result = true;
char* find_string = NULL;
size_t count = 0;
size_t header_begin = 0;
size_t header_end = 0;
size_t header_length = 0;
int header_begin_flag = 0;
int header_end_flag = 0;
match_results< const char* > result;
cregex http_header_regex;
if( buffer != NULL ){
for( count = 0; count < buffer_len; count++ ){
if( buffer[count] == '\r' || buffer[count] == '\n' ){
if( header_begin_flag == 0 ){
header_begin = count;
header_begin_flag = 1;
}
if( count > 0 ){
if( ( buffer[count-1] == '\r' && buffer[count] == '\r' ) ||
( buffer[count-1] == '\n' && buffer[count] == '\n' ) ){
header_end = count;
header_end_flag = 1;
break;
}
}
if( count > 2 ){
if( buffer[count-3] == '\r' && buffer[count-2] == '\n' &&
buffer[count-1] == '\r' && buffer[count] == '\n' ){
header_end = count;
header_end_flag = 1;
break;
}
}
}
}
if( header_begin_flag == 1 && header_end_flag == 1 ){
header_length = header_end - header_begin + 1;
find_string = (char*)malloc( header_length + 1 );
if( find_string != NULL ){
memcpy( find_string, buffer + header_begin, header_length );
find_string[header_length] = '\0';
if( http_header_name.length() > 0 ){
http_header_regex = _ln >> (s1 = icase(http_header_name) >> ":" >> *~_ln);
find_result = regex_search( find_string, result, http_header_regex );
if( find_result == true ){
http_header_offset = result.position(1) + header_begin;
http_header_len = result.length(1);
}
}
else{
http_header_regex = _ln >> (s1 = *_ >> ~_ln) >> repeat<2>(_ln);
find_result = regex_search( find_string, result, http_header_regex );
if( find_result == true ){
http_header_offset = result.position(1) + header_begin;
http_header_len = result.length(1);
}
else{
http_header_regex = _ln >> (s1 = _ln);
find_result = regex_search( find_string, result, http_header_regex );
if( find_result == true ){
http_header_offset = result.position(1) + header_begin;
http_header_len = 0;
}
}
}
free( find_string );
}
else{
find_result = false;
}
}
else{
find_result = false;
}
}
else{
find_result = false;
}
return find_result;
}
<commit_msg>find_uri regex 更新<commit_after>//
// @file http_protocol_module_base.cpp
// @brief shared object http protocol module absctract class
//
// Distributed under the Boost Software License, Version 1.0.(See accompanying
// file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt
//
#include <boost/xpressive/xpressive.hpp>
#include "http_protocol_module_base.h"
using namespace boost::xpressive;
l7vs::http_protocol_module_base::CHECK_RESULT_TAG l7vs::http_protocol_module_base::check_http_method( const char* buffer,
const size_t buffer_len ) const {
l7vs::http_protocol_module_base::CHECK_RESULT_TAG check_result = CHECK_OK;
char* check_string = NULL;
size_t line_length = 0;
cregex method_regex
= ( as_xpr("GET") | as_xpr("HEAD") | as_xpr("POST") |
as_xpr("PUT") | as_xpr("PROPFIND") | as_xpr("PROPPATCH") |
as_xpr("OPTIONS") | as_xpr("CONNECT") | as_xpr("COPY") |
as_xpr("TRACE") | as_xpr("DELETE") | as_xpr("LOCK") |
as_xpr("UNLOCK") | as_xpr("MOVE") | as_xpr("MKCOL")) >> _s >>
+~_s >> _s >>
"HTTP/" >> _d >> "." >> _d;
if( buffer != NULL ){
for( line_length = 0; line_length < buffer_len; line_length++ ){
if( buffer[line_length] == '\r' || buffer[line_length] == '\n' ){
break;
}
}
if( line_length < buffer_len ){
check_string = (char*)malloc( line_length + 1 );
if( check_string != NULL ){
memcpy( check_string, buffer, line_length );
check_string[line_length] = '\0';
if( !regex_match( check_string, method_regex )){
check_result = CHECK_NG;
}
free( check_string );
}
else{
check_result = CHECK_NG;
}
}
else{
check_result = CHECK_INPOSSIBLE;
}
}
else{
check_result = CHECK_NG;
}
return check_result;
}
l7vs::http_protocol_module_base::CHECK_RESULT_TAG l7vs::http_protocol_module_base::check_http_version( const char* buffer,
const size_t buffer_len ) const {
l7vs::http_protocol_module_base::CHECK_RESULT_TAG check_result = CHECK_OK;
char* check_string = NULL;
size_t line_length = 0;
cregex version_regex_request
= +alpha >> _s >>
+~_s >> _s >>
"HTTP/" >> (as_xpr("1.0")|as_xpr("1.1"));
cregex version_regex_response
= "HTTP/" >> (as_xpr("1.0")|as_xpr("1.1")) >> _s >>
repeat<3>(_d) >> _s >>
*_;
if( buffer != NULL ){
for( line_length = 0; line_length < buffer_len; line_length++ ){
if( buffer[line_length] == '\r' || buffer[line_length] == '\n' ){
break;
}
}
if( line_length < buffer_len ){
check_string = (char*)malloc( line_length + 1 );
if( check_string != NULL ){
memcpy( check_string, buffer, line_length );
check_string[line_length] = '\0';
if( !regex_match( check_string, version_regex_request ) &&
!regex_match( check_string, version_regex_response ) ){
check_result = CHECK_NG;
}
free( check_string );
}
else{
check_result = CHECK_NG;
}
}
else{
check_result = CHECK_INPOSSIBLE;
}
}
else{
check_result = CHECK_NG;
}
return check_result;
}
l7vs::http_protocol_module_base::CHECK_RESULT_TAG l7vs::http_protocol_module_base::check_status_code( const char* buffer,
const size_t buffer_len ) const {
l7vs::http_protocol_module_base::CHECK_RESULT_TAG check_result = CHECK_OK;
char* check_string = NULL;
size_t line_length = 0;
cregex status_code_regex
= "HTTP/" >> _d >> "." >> _d >> _s >>
range('1', '3') >> repeat<2>(_d) >> _s >>
*_;
if( buffer != NULL ){
for( line_length = 0; line_length < buffer_len; line_length++ ){
if( buffer[line_length] == '\r' || buffer[line_length] == '\n' ){
break;
}
}
if( line_length < buffer_len ){
check_string = (char*)malloc( line_length + 1 );
if( check_string != NULL ){
memcpy( check_string, buffer, line_length );
check_string[line_length] = '\0';
if( !regex_match( check_string, status_code_regex )){
check_result = CHECK_NG;
}
free( check_string );
}
else{
check_result = CHECK_NG;
}
}
else{
check_result = CHECK_INPOSSIBLE;
}
}
else{
check_result = CHECK_NG;
}
return check_result;
}
bool l7vs::http_protocol_module_base::find_uri( const char* buffer,
const size_t buffer_len,
size_t& uri_offset,
size_t& uri_len){
bool find_result = true;
char* find_string = NULL;
size_t line_length = 0;
match_results< const char* > result;
cregex uri_regex
= +alpha >> _s >>
(s1 = *~_s) >> _s >>
"HTTP/" >> _d >> "." >> _d;
if( buffer != NULL ){
for( line_length = 0; line_length < buffer_len; line_length++ ){
if( buffer[line_length] == '\r' || buffer[line_length] == '\n' ){
break;
}
}
if( line_length < buffer_len ){
find_string = (char*)malloc( line_length + 1 );
if( find_string != NULL ){
memcpy( find_string, buffer, line_length );
find_string[line_length] = '\0';
find_result = regex_search( find_string, result, uri_regex );
if( find_result == true ){
uri_offset = result.position(1);
uri_len = result.length(1);
}
free( find_string );
}
else{
find_result = false;
}
}
else{
find_result = false;
}
}
else{
find_result = false;
}
return find_result;
}
bool l7vs::http_protocol_module_base::find_status_code( const char* buffer,
const size_t buffer_len,
size_t& status_code_offset,
size_t& status_code_len){
bool find_result = true;
char* find_string = NULL;
size_t line_length = 0;
match_results< const char* > result;
cregex status_code_regex
= "HTTP/" >> _d >> "." >> _d >> _s >>
(s1 = repeat<3>(_d)) >> _s >>
*_;
if( buffer != NULL ){
for( line_length = 0; line_length < buffer_len; line_length++ ){
if( buffer[line_length] == '\r' || buffer[line_length] == '\n' ){
break;
}
}
if( line_length < buffer_len ){
find_string = (char*)malloc( line_length + 1 );
if( find_string != NULL ){
memcpy( find_string, buffer, line_length );
find_string[line_length] = '\0';
find_result = regex_search( find_string, result, status_code_regex );
if( find_result == true ){
status_code_offset = result.position(1);
status_code_len = result.length(1);
}
free( find_string );
}
else{
find_result = false;
}
}
else{
find_result = false;
}
}
else{
find_result = false;
}
return find_result;
}
bool l7vs::http_protocol_module_base::find_http_header( const char* buffer,
const size_t buffer_len,
const std::string& http_header_name,
size_t& http_header_offset,
size_t& http_header_len ){
bool find_result = true;
char* find_string = NULL;
size_t count = 0;
size_t header_begin = 0;
size_t header_end = 0;
size_t header_length = 0;
int header_begin_flag = 0;
int header_end_flag = 0;
match_results< const char* > result;
cregex http_header_regex;
if( buffer != NULL ){
for( count = 0; count < buffer_len; count++ ){
if( buffer[count] == '\r' || buffer[count] == '\n' ){
if( header_begin_flag == 0 ){
header_begin = count;
header_begin_flag = 1;
}
if( count > 0 ){
if( ( buffer[count-1] == '\r' && buffer[count] == '\r' ) ||
( buffer[count-1] == '\n' && buffer[count] == '\n' ) ){
header_end = count;
header_end_flag = 1;
break;
}
}
if( count > 2 ){
if( buffer[count-3] == '\r' && buffer[count-2] == '\n' &&
buffer[count-1] == '\r' && buffer[count] == '\n' ){
header_end = count;
header_end_flag = 1;
break;
}
}
}
}
if( header_begin_flag == 1 && header_end_flag == 1 ){
header_length = header_end - header_begin + 1;
find_string = (char*)malloc( header_length + 1 );
if( find_string != NULL ){
memcpy( find_string, buffer + header_begin, header_length );
find_string[header_length] = '\0';
if( http_header_name.length() > 0 ){
http_header_regex = _ln >> (s1 = icase(http_header_name) >> ":" >> *~_ln);
find_result = regex_search( find_string, result, http_header_regex );
if( find_result == true ){
http_header_offset = result.position(1) + header_begin;
http_header_len = result.length(1);
}
}
else{
http_header_regex = _ln >> (s1 = *_ >> ~_ln) >> repeat<2>(_ln);
find_result = regex_search( find_string, result, http_header_regex );
if( find_result == true ){
http_header_offset = result.position(1) + header_begin;
http_header_len = result.length(1);
}
else{
http_header_regex = _ln >> (s1 = _ln);
find_result = regex_search( find_string, result, http_header_regex );
if( find_result == true ){
http_header_offset = result.position(1) + header_begin;
http_header_len = 0;
}
}
}
free( find_string );
}
else{
find_result = false;
}
}
else{
find_result = false;
}
}
else{
find_result = false;
}
return find_result;
}
<|endoftext|> |
<commit_before>/*=========================================================================
Program: Medical Imaging & Interaction Toolkit
Language: C++
Date: $Date$
Version: $Revision: 1.12 $
Copyright (c) German Cancer Research Center, Division of Medical and
Biological Informatics. All rights reserved.
See MITKCopyright.txt or http://www.mitk.org/copyright.html for details.
This software is distributed WITHOUT ANY WARRANTY; without even
the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR
PURPOSE. See the above copyright notices for more information.
=========================================================================*/
#include "mitkPaintbrushTool.h"
#include "mitkToolManager.h"
#include "mitkOverwriteSliceImageFilter.h"
#include "mitkBaseRenderer.h"
#include "ipSegmentation.h"
#define ROUND(a) ((a)>0 ? (int)((a)+0.5) : -(int)(0.5-(a)))
int mitk::PaintbrushTool::m_Size = 1;
mitk::PaintbrushTool::PaintbrushTool(int paintingPixelValue)
:FeedbackContourTool("PressMoveReleaseWithCTRLInversionAllMouseMoves"),
m_PaintingPixelValue(paintingPixelValue),
m_LastContourSize(0) // other than initial mitk::PaintbrushTool::m_Size (around l. 28)
{
m_MasterContour = Contour::New();
m_MasterContour->Initialize();
}
mitk::PaintbrushTool::~PaintbrushTool()
{
}
void mitk::PaintbrushTool::Activated()
{
Superclass::Activated();
FeedbackContourTool::SetFeedbackContourVisible(true);
SizeChanged.Send(m_Size);
}
void mitk::PaintbrushTool::Deactivated()
{
FeedbackContourTool::SetFeedbackContourVisible(false);
Superclass::Deactivated();
}
void mitk::PaintbrushTool::SetSize(int value)
{
m_Size = value;
}
void mitk::PaintbrushTool::UpdateContour(const StateEvent* stateEvent)
{
// examine stateEvent and create a contour that matches the pixel mask that we are going to draw
const PositionEvent* positionEvent = dynamic_cast<const PositionEvent*>(stateEvent->GetEvent());
if (!positionEvent) return;
Image::Pointer m_WorkingSlice = FeedbackContourTool::GetAffectedWorkingSlice( positionEvent );
if (m_WorkingSlice.IsNull()) return;
// create a copy of this slice (at least match the pixel sizes/spacings),
// then draw the desired mask on it and create a contour from it
// Convert to ipMITKSegmentationTYPE (because getting pixels relys on that data type)
itk::Image< ipMITKSegmentationTYPE, 2 >::Pointer correctPixelTypeImage;
CastToItkImage( m_WorkingSlice, correctPixelTypeImage );
assert (correctPixelTypeImage.IsNotNull() );
itk::Image< ipMITKSegmentationTYPE, 2 >::DirectionType imageDirection;
imageDirection.SetIdentity();
correctPixelTypeImage->SetDirection(imageDirection);
Image::Pointer temporarySlice = Image::New();
CastToMitkImage( correctPixelTypeImage, temporarySlice );
mitkIpPicDescriptor* stupidClone = mitkIpPicClone( temporarySlice->GetSliceData()->GetPicDescriptor() );
unsigned int pixelWidth = m_Size + 1;
unsigned int pixelHeight = m_Size + 1;
if ( stupidClone->n[0] <= pixelWidth || stupidClone->n[1] <= pixelHeight )
{
MITK_INFO << "Brush size is bigger than your working image. Reconsider this...\n"
"(Or tell your progammer until (s)he fixes this message.)" << std::endl;
mitkIpPicFree( stupidClone );
return;
}
unsigned int lineLength( stupidClone->n[0] );
unsigned int oneContourOffset(0);
float circleCenterX = (float)m_Size / 2.0;
float circleCenterY = (float)m_Size / 2.0;
for (unsigned int x = 0; x <= pixelWidth; ++x)
{
for (unsigned int y = 0; y <= pixelHeight; ++y)
{
unsigned int offset = lineLength * y + x;
ipMITKSegmentationTYPE* current = (ipMITKSegmentationTYPE*)stupidClone->data + offset;
float pixelCenterX = x + 0.5;
float pixelCenterY = y + 0.5;
float xoff = pixelCenterX - circleCenterX;
float yoff = pixelCenterY - circleCenterY;
bool inside = xoff * xoff + yoff * yoff < (m_Size * m_Size) / 4.0; // no idea, if this would work for ellipses
if (inside)
{
*current = 1;
oneContourOffset = offset;
}
else
{
*current = 0;
}
}
}
int numberOfContourPoints( 0 );
int newBufferSize( 0 );
float* contourPoints = ipMITKSegmentationGetContour8N( stupidClone, oneContourOffset, numberOfContourPoints, newBufferSize ); // memory allocated with malloc
if (!contourPoints)
{
mitkIpPicFree( stupidClone );
return;
}
// copy point from float* to mitk::Contour
Contour::Pointer contourInImageIndexCoordinates = Contour::New();
contourInImageIndexCoordinates->Initialize();
Point3D newPoint;
//ipMITKSegmentationGetContour8N returns all points, which causes vtk warnings, since the first and the last points are coincident.
//leaving the last point out, the contour is still drawn correctly
for (int index = 0; index < numberOfContourPoints-1; ++index)
{
newPoint[0] = contourPoints[ 2 * index + 0 ] - circleCenterX; // master contour should be centered around (0,0)
newPoint[1] = contourPoints[ 2 * index + 1] - circleCenterY;
newPoint[2] = 0.0;
MITK_DEBUG << "Point [" << index << "] (" << newPoint[0] << ", " << newPoint[1] << ")" << std::endl;
contourInImageIndexCoordinates->AddVertex( newPoint );
}
free(contourPoints);
m_MasterContour = contourInImageIndexCoordinates;
mitkIpPicFree( stupidClone );
}
/**
Just show the contour, get one point as the central point and add surrounding points to the contour.
*/
bool mitk::PaintbrushTool::OnMousePressed (Action* action, const StateEvent* stateEvent)
{
if (FeedbackContourTool::OnMousePressed( action, stateEvent ))
{
const PositionEvent* positionEvent = dynamic_cast<const PositionEvent*>(stateEvent->GetEvent());
if (positionEvent)
{
UpdateContour( stateEvent );
}
}
return this->OnMouseMoved(action, stateEvent);
/*
return true;
*/
}
/**
Insert the point to the feedback contour,finish to build the contour and at the same time the painting function
*/
bool mitk::PaintbrushTool::OnMouseMoved (Action* itkNotUsed(action), const StateEvent* stateEvent)
{
bool leftMouseButtonPressed(
stateEvent->GetId() == 530
|| stateEvent->GetId() == 1
|| stateEvent->GetId() == 5
);
const PositionEvent* positionEvent = dynamic_cast<const PositionEvent*>(stateEvent->GetEvent());
if (!positionEvent) return false;
if ( m_LastContourSize != m_Size )
{
UpdateContour( stateEvent );
m_LastContourSize = m_Size;
}
DataNode* workingNode( m_ToolManager->GetWorkingData(0) );
if (!workingNode) return false;
Image* image = dynamic_cast<Image*>(workingNode->GetData());
const PlaneGeometry* planeGeometry( dynamic_cast<const PlaneGeometry*> (positionEvent->GetSender()->GetCurrentWorldGeometry2D() ) );
if ( !image || !planeGeometry ) return false;
int affectedDimension( -1 );
int affectedSlice( -1 );
if ( !SegTool2D::DetermineAffectedImageSlice( image, planeGeometry, affectedDimension, affectedSlice ) ) return false;
Point3D worldCoordinates = positionEvent->GetWorldPosition();
Point3D indexCoordinates;
image->GetGeometry()->WorldToIndex( worldCoordinates, indexCoordinates );
MITK_DEBUG << "Mouse at W " << worldCoordinates << std::endl;
MITK_DEBUG << "Mouse at I " << indexCoordinates << std::endl;
unsigned int firstDimension(0);
unsigned int secondDimension(1);
switch( affectedDimension )
{
case 2: // transversal
default:
firstDimension = 0;
secondDimension = 1;
break;
case 1: // frontal
firstDimension = 0;
secondDimension = 2;
break;
case 0: // sagittal
firstDimension = 1;
secondDimension = 2;
break;
}
// round to nearest voxel center (abort if this hasn't changed)
if ( m_Size % 2 == 0 ) // even
{
indexCoordinates[firstDimension] = ROUND( indexCoordinates[firstDimension] + 0.5);
indexCoordinates[secondDimension] = ROUND( indexCoordinates[secondDimension] + 0.5 );
}
else // odd
{
indexCoordinates[firstDimension] = ROUND( indexCoordinates[firstDimension] ) ;
indexCoordinates[secondDimension] = ROUND( indexCoordinates[secondDimension] ) ;
}
static Point3D lastPos; // uninitialized: if somebody finds out how this can be initialized in a one-liner, tell me
static bool lastLeftMouseButtonPressed(false);
if ( fabs(indexCoordinates[0] - lastPos[0]) > mitk::eps ||
fabs(indexCoordinates[1] - lastPos[1]) > mitk::eps ||
fabs(indexCoordinates[2] - lastPos[2]) > mitk::eps ||
leftMouseButtonPressed != lastLeftMouseButtonPressed
)
{
lastPos = indexCoordinates;
lastLeftMouseButtonPressed = leftMouseButtonPressed;
}
else
{
MITK_DEBUG << "." << std::flush;
return false;
}
MITK_DEBUG << "Mouse at C " << indexCoordinates;
Contour::Pointer contour = Contour::New();
contour->Initialize();
for (unsigned int index = 0; index < m_MasterContour->GetNumberOfPoints(); ++index)
{
Point3D point = m_MasterContour->GetPoints()->ElementAt(index);
point[0] += indexCoordinates[ firstDimension ];
point[1] += indexCoordinates[ secondDimension ];
MITK_DEBUG << "Contour point [" << index << "] :" << point;
contour->AddVertex( point );
}
if (leftMouseButtonPressed)
{
Image::Pointer slice = SegTool2D::GetAffectedImageSliceAs2DImage( positionEvent, image );
if ( slice.IsNull() ) return false;
FeedbackContourTool::FillContourInSlice( contour, slice, m_PaintingPixelValue );
OverwriteSliceImageFilter::Pointer slicewriter = OverwriteSliceImageFilter::New();
slicewriter->SetInput( image );
slicewriter->SetCreateUndoInformation( true );
slicewriter->SetSliceImage( slice );
slicewriter->SetSliceDimension( affectedDimension );
slicewriter->SetSliceIndex( affectedSlice );
slicewriter->SetTimeStep( positionEvent->GetSender()->GetTimeStep( image ) );
slicewriter->Update();
}
// visualize contour
Contour::Pointer displayContour = Contour::New();
displayContour->Initialize();
for (unsigned int index = 0; index < contour->GetNumberOfPoints(); ++index)
{
Point3D point = contour->GetPoints()->ElementAt(index);
/*if ( m_Size % 2 != 0 ) // even
{
point[0] += 0.5;
point[1] += 0.5;
}*/
displayContour->AddVertex( point );
}
displayContour = FeedbackContourTool::BackProjectContourFrom2DSlice( planeGeometry, displayContour );
SetFeedbackContour( *displayContour );
assert( positionEvent->GetSender()->GetRenderWindow() );
RenderingManager::GetInstance()->RequestUpdate( positionEvent->GetSender()->GetRenderWindow() );
return true;
}
bool mitk::PaintbrushTool::OnMouseReleased(Action* /*action*/, const StateEvent* /*stateEvent*/)
{
//FeedbackContourTool::SetFeedbackContourVisible(false);
return true;
}
/**
Called when the CTRL key is pressed. Will change the painting pixel value from 0 to 1 or from 1 to 0.
*/
bool mitk::PaintbrushTool::OnInvertLogic(Action* action, const StateEvent* stateEvent)
{
if (!FeedbackContourTool::OnInvertLogic(action, stateEvent)) return false;
// Inversion only for 0 and 1 as painting values
if (m_PaintingPixelValue == 1)
{
m_PaintingPixelValue = 0;
FeedbackContourTool::SetFeedbackContourColor( 1.0, 0.0, 0.0 );
}
else if (m_PaintingPixelValue == 0)
{
m_PaintingPixelValue = 1;
FeedbackContourTool::SetFeedbackContourColorDefault();
}
return true;
}
<commit_msg>FIX (#6552): Reverted some of the changes to make it work properly again.<commit_after>/*=========================================================================
Program: Medical Imaging & Interaction Toolkit
Language: C++
Date: $Date$
Version: $Revision: 1.12 $
Copyright (c) German Cancer Research Center, Division of Medical and
Biological Informatics. All rights reserved.
See MITKCopyright.txt or http://www.mitk.org/copyright.html for details.
This software is distributed WITHOUT ANY WARRANTY; without even
the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR
PURPOSE. See the above copyright notices for more information.
=========================================================================*/
#include "mitkPaintbrushTool.h"
#include "mitkToolManager.h"
#include "mitkOverwriteSliceImageFilter.h"
#include "mitkBaseRenderer.h"
#include "ipSegmentation.h"
#define ROUND(a) ((a)>0 ? (int)((a)+0.5) : -(int)(0.5-(a)))
int mitk::PaintbrushTool::m_Size = 1;
mitk::PaintbrushTool::PaintbrushTool(int paintingPixelValue)
:FeedbackContourTool("PressMoveReleaseWithCTRLInversionAllMouseMoves"),
m_PaintingPixelValue(paintingPixelValue),
m_LastContourSize(0) // other than initial mitk::PaintbrushTool::m_Size (around l. 28)
{
m_MasterContour = Contour::New();
m_MasterContour->Initialize();
}
mitk::PaintbrushTool::~PaintbrushTool()
{
}
void mitk::PaintbrushTool::Activated()
{
Superclass::Activated();
FeedbackContourTool::SetFeedbackContourVisible(true);
SizeChanged.Send(m_Size);
}
void mitk::PaintbrushTool::Deactivated()
{
FeedbackContourTool::SetFeedbackContourVisible(false);
Superclass::Deactivated();
}
void mitk::PaintbrushTool::SetSize(int value)
{
m_Size = value;
}
void mitk::PaintbrushTool::UpdateContour(const StateEvent* stateEvent)
{
// examine stateEvent and create a contour that matches the pixel mask that we are going to draw
const PositionEvent* positionEvent = dynamic_cast<const PositionEvent*>(stateEvent->GetEvent());
if (!positionEvent) return;
Image::Pointer m_WorkingSlice = FeedbackContourTool::GetAffectedWorkingSlice( positionEvent );
if (m_WorkingSlice.IsNull()) return;
// create a copy of this slice (at least match the pixel sizes/spacings),
// then draw the desired mask on it and create a contour from it
// Convert to ipMITKSegmentationTYPE (because getting pixels relys on that data type)
itk::Image< ipMITKSegmentationTYPE, 2 >::Pointer correctPixelTypeImage;
CastToItkImage( m_WorkingSlice, correctPixelTypeImage );
assert (correctPixelTypeImage.IsNotNull() );
itk::Image< ipMITKSegmentationTYPE, 2 >::DirectionType imageDirection;
imageDirection.SetIdentity();
correctPixelTypeImage->SetDirection(imageDirection);
Image::Pointer temporarySlice = Image::New();
CastToMitkImage( correctPixelTypeImage, temporarySlice );
mitkIpPicDescriptor* stupidClone = mitkIpPicClone( temporarySlice->GetSliceData()->GetPicDescriptor() );
unsigned int pixelWidth = m_Size + 1;
unsigned int pixelHeight = m_Size + 1;
if ( stupidClone->n[0] <= pixelWidth || stupidClone->n[1] <= pixelHeight )
{
MITK_INFO << "Brush size is bigger than your working image. Reconsider this...\n"
"(Or tell your progammer until (s)he fixes this message.)" << std::endl;
mitkIpPicFree( stupidClone );
return;
}
unsigned int lineLength( stupidClone->n[0] );
unsigned int oneContourOffset(0);
float circleCenterX = (float)m_Size / 2.0;
float circleCenterY = (float)m_Size / 2.0;
for (unsigned int x = 0; x <= pixelWidth; ++x)
{
for (unsigned int y = 0; y <= pixelHeight; ++y)
{
unsigned int offset = lineLength * y + x;
ipMITKSegmentationTYPE* current = (ipMITKSegmentationTYPE*)stupidClone->data + offset;
float pixelCenterX = x + 0.5;
float pixelCenterY = y + 0.5;
float xoff = pixelCenterX - circleCenterX;
float yoff = pixelCenterY - circleCenterY;
bool inside = xoff * xoff + yoff * yoff < (m_Size * m_Size) / 4.0; // no idea, if this would work for ellipses
if (inside)
{
*current = 1;
oneContourOffset = offset;
}
else
{
*current = 0;
}
}
}
int numberOfContourPoints( 0 );
int newBufferSize( 0 );
float* contourPoints = ipMITKSegmentationGetContour8N( stupidClone, oneContourOffset, numberOfContourPoints, newBufferSize ); // memory allocated with malloc
if (!contourPoints)
{
mitkIpPicFree( stupidClone );
return;
}
// copy point from float* to mitk::Contour
Contour::Pointer contourInImageIndexCoordinates = Contour::New();
contourInImageIndexCoordinates->Initialize();
Point3D newPoint;
//ipMITKSegmentationGetContour8N returns all points, which causes vtk warnings, since the first and the last points are coincident.
//leaving the last point out, the contour is still drawn correctly
for (int index = 0; index < numberOfContourPoints-1; ++index)
{
newPoint[0] = contourPoints[ 2 * index + 0 ] - circleCenterX; // master contour should be centered around (0,0)
newPoint[1] = contourPoints[ 2 * index + 1] - circleCenterY;
newPoint[2] = 0.0;
MITK_DEBUG << "Point [" << index << "] (" << newPoint[0] << ", " << newPoint[1] << ")" << std::endl;
contourInImageIndexCoordinates->AddVertex( newPoint );
}
free(contourPoints);
m_MasterContour = contourInImageIndexCoordinates;
mitkIpPicFree( stupidClone );
}
/**
Just show the contour, get one point as the central point and add surrounding points to the contour.
*/
bool mitk::PaintbrushTool::OnMousePressed (Action* action, const StateEvent* stateEvent)
{
if (FeedbackContourTool::OnMousePressed( action, stateEvent ))
{
const PositionEvent* positionEvent = dynamic_cast<const PositionEvent*>(stateEvent->GetEvent());
if (positionEvent)
{
UpdateContour( stateEvent );
}
}
return this->OnMouseMoved(action, stateEvent);
/*
return true;
*/
}
/**
Insert the point to the feedback contour,finish to build the contour and at the same time the painting function
*/
bool mitk::PaintbrushTool::OnMouseMoved (Action* itkNotUsed(action), const StateEvent* stateEvent)
{
bool leftMouseButtonPressed(
stateEvent->GetId() == 530
|| stateEvent->GetId() == 1
|| stateEvent->GetId() == 5
);
const PositionEvent* positionEvent = dynamic_cast<const PositionEvent*>(stateEvent->GetEvent());
if (!positionEvent) return false;
if ( m_LastContourSize != m_Size )
{
UpdateContour( stateEvent );
m_LastContourSize = m_Size;
}
DataNode* workingNode( m_ToolManager->GetWorkingData(0) );
if (!workingNode) return false;
Image* image = dynamic_cast<Image*>(workingNode->GetData());
const PlaneGeometry* planeGeometry( dynamic_cast<const PlaneGeometry*> (positionEvent->GetSender()->GetCurrentWorldGeometry2D() ) );
if ( !image || !planeGeometry )
return false;
int affectedDimension( -1 );
int affectedSlice( -1 );
if ( !SegTool2D::DetermineAffectedImageSlice( image, planeGeometry, affectedDimension, affectedSlice ) )
return false;
Point3D worldCoordinates = positionEvent->GetWorldPosition();
Point3D indexCoordinates;
image->GetGeometry()->WorldToIndex( worldCoordinates, indexCoordinates );
MITK_DEBUG << "Mouse at W " << worldCoordinates << std::endl;
MITK_DEBUG << "Mouse at I " << indexCoordinates << std::endl;
unsigned int firstDimension(0);
unsigned int secondDimension(1);
switch( affectedDimension )
{
case 2: // transversal
default:
firstDimension = 0;
secondDimension = 1;
break;
case 1: // frontal
firstDimension = 0;
secondDimension = 2;
break;
case 0: // sagittal
firstDimension = 1;
secondDimension = 2;
break;
}
// round to nearest voxel center (abort if this hasn't changed)
if ( m_Size % 2 == 0 ) // even
{
indexCoordinates[firstDimension] = ROUND( indexCoordinates[firstDimension] + 0.5);
indexCoordinates[secondDimension] = ROUND( indexCoordinates[secondDimension] + 0.5 );
}
else // odd
{
indexCoordinates[firstDimension] = ROUND( indexCoordinates[firstDimension] ) ;
indexCoordinates[secondDimension] = ROUND( indexCoordinates[secondDimension] ) ;
}
static Point3D lastPos; // uninitialized: if somebody finds out how this can be initialized in a one-liner, tell me
static bool lastLeftMouseButtonPressed(false);
if ( fabs(indexCoordinates[0] - lastPos[0]) > mitk::eps ||
fabs(indexCoordinates[1] - lastPos[1]) > mitk::eps ||
fabs(indexCoordinates[2] - lastPos[2]) > mitk::eps ||
leftMouseButtonPressed != lastLeftMouseButtonPressed
)
{
lastPos = indexCoordinates;
lastLeftMouseButtonPressed = leftMouseButtonPressed;
}
else
{
MITK_DEBUG << "." << std::flush;
return false;
}
MITK_DEBUG << "Mouse at C " << indexCoordinates;
Contour::Pointer contour = Contour::New();
contour->Initialize();
for (unsigned int index = 0; index < m_MasterContour->GetNumberOfPoints(); ++index)
{
Point3D point = m_MasterContour->GetPoints()->ElementAt(index);
point[0] += indexCoordinates[ firstDimension ];
point[1] += indexCoordinates[ secondDimension ];
MITK_DEBUG << "Contour point [" << index << "] :" << point;
contour->AddVertex( point );
}
Image::Pointer slice = SegTool2D::GetAffectedImageSliceAs2DImage( positionEvent, image );
if ( slice.IsNull() )
return false;
if (leftMouseButtonPressed)
{
FeedbackContourTool::FillContourInSlice( contour, slice, m_PaintingPixelValue );
OverwriteSliceImageFilter::Pointer slicewriter = OverwriteSliceImageFilter::New();
slicewriter->SetInput( image );
slicewriter->SetCreateUndoInformation( true );
slicewriter->SetSliceImage( slice );
slicewriter->SetSliceDimension( affectedDimension );
slicewriter->SetSliceIndex( affectedSlice );
slicewriter->SetTimeStep( positionEvent->GetSender()->GetTimeStep( image ) );
slicewriter->Update();
}
// visualize contour
Contour::Pointer displayContour = Contour::New();
displayContour->Initialize();
for (unsigned int index = 0; index < contour->GetNumberOfPoints(); ++index)
{
Point3D point = contour->GetPoints()->ElementAt(index);
/*if ( m_Size % 2 != 0 ) // even
{
point[0] += 0.5;
point[1] += 0.5;
}*/
displayContour->AddVertex( point );
}
displayContour = FeedbackContourTool::BackProjectContourFrom2DSlice( slice->GetGeometry(), displayContour );
SetFeedbackContour( *displayContour );
assert( positionEvent->GetSender()->GetRenderWindow() );
RenderingManager::GetInstance()->RequestUpdate( positionEvent->GetSender()->GetRenderWindow() );
return true;
}
bool mitk::PaintbrushTool::OnMouseReleased(Action* /*action*/, const StateEvent* /*stateEvent*/)
{
//FeedbackContourTool::SetFeedbackContourVisible(false);
return true;
}
/**
Called when the CTRL key is pressed. Will change the painting pixel value from 0 to 1 or from 1 to 0.
*/
bool mitk::PaintbrushTool::OnInvertLogic(Action* action, const StateEvent* stateEvent)
{
if (!FeedbackContourTool::OnInvertLogic(action, stateEvent)) return false;
// Inversion only for 0 and 1 as painting values
if (m_PaintingPixelValue == 1)
{
m_PaintingPixelValue = 0;
FeedbackContourTool::SetFeedbackContourColor( 1.0, 0.0, 0.0 );
}
else if (m_PaintingPixelValue == 0)
{
m_PaintingPixelValue = 1;
FeedbackContourTool::SetFeedbackContourColorDefault();
}
return 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/.
*
* 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 .
*/
#include "TableCopyHelper.hxx"
#include "dbustrings.hrc"
#include "sqlmessage.hxx"
#include <vcl/msgbox.hxx>
#include "WCopyTable.hxx"
#include <dbaccess/genericcontroller.hxx>
#include "WCPage.hxx"
#include <com/sun/star/task/XInteractionHandler.hpp>
#include <com/sun/star/sdb/XSingleSelectQueryComposer.hpp>
#include <com/sun/star/sdb/application/CopyTableOperation.hpp>
#include <com/sun/star/sdb/application/CopyTableWizard.hpp>
#include <com/sun/star/sdb/DataAccessDescriptorFactory.hpp>
#include "RtfReader.hxx"
#include "HtmlReader.hxx"
#include "TokenWriter.hxx"
#include "UITools.hxx"
#include <dbaccess/dataview.hxx>
#include "dbu_resource.hrc"
#include <unotools/ucbhelper.hxx>
#include <tools/urlobj.hxx>
#include <tools/diagnose_ex.h>
#include <comphelper/processfactory.hxx>
#include <com/sun/star/sdbcx/XTablesSupplier.hpp>
#include <com/sun/star/sdbcx/XViewsSupplier.hpp>
#include <com/sun/star/sdb/XQueryDefinitionsSupplier.hpp>
#include <com/sun/star/sdb/SQLContext.hpp>
#include <com/sun/star/sdbc/XParameters.hpp>
#include <com/sun/star/sdbc/XResultSetMetaDataSupplier.hpp>
#include <com/sun/star/sdb/XQueriesSupplier.hpp>
#include <com/sun/star/sdbc/XColumnLocate.hpp>
#include <com/sun/star/sdbcx/XRowLocate.hpp>
#include <vcl/waitobj.hxx>
#include <com/sun/star/sdb/XSQLQueryComposerFactory.hpp>
#include <unotools/tempfile.hxx>
#include <cppuhelper/exc_hlp.hxx>
#include "dbexchange.hxx"
namespace dbaui
{
using namespace ::dbtools;
using namespace ::svx;
using namespace ::com::sun::star::uno;
using namespace ::com::sun::star::task;
using namespace ::com::sun::star::beans;
using namespace ::com::sun::star::lang;
using namespace ::com::sun::star::container;
using namespace ::com::sun::star::sdb;
using namespace ::com::sun::star::sdb::application;
using namespace ::com::sun::star::sdbc;
using namespace ::com::sun::star::sdbcx;
using namespace ::com::sun::star::frame;
using namespace ::com::sun::star::ucb;
OTableCopyHelper::OTableCopyHelper(OGenericUnoController* _pControler)
:m_pController(_pControler)
{
}
void OTableCopyHelper::insertTable( const OUString& i_rSourceDataSource, const Reference<XConnection>& i_rSourceConnection,
const OUString& i_rCommand, const sal_Int32 i_nCommandType,
const Reference< XResultSet >& i_rSourceRows, const Sequence< Any >& i_rSelection, const bool i_bBookmarkSelection,
const OUString& i_rDestDataSource, const Reference<XConnection>& i_rDestConnection)
{
if ( CommandType::QUERY != i_nCommandType && CommandType::TABLE != i_nCommandType )
{
SAL_WARN("dbaccess.ui", "OTableCopyHelper::insertTable: invalid call (no supported format found)!" );
return;
}
try
{
Reference<XConnection> xSrcConnection( i_rSourceConnection );
if ( i_rSourceDataSource == i_rDestDataSource )
xSrcConnection = i_rDestConnection;
if ( !xSrcConnection.is() || !i_rDestConnection.is() )
{
SAL_WARN("dbaccess.ui", "OTableCopyHelper::insertTable: no connection/s!" );
return;
}
Reference<XComponentContext> aContext( m_pController->getORB() );
Reference< XDataAccessDescriptorFactory > xFactory( DataAccessDescriptorFactory::get( aContext ) );
Reference< XPropertySet > xSource( xFactory->createDataAccessDescriptor(), UNO_SET_THROW );
xSource->setPropertyValue( PROPERTY_COMMAND_TYPE, makeAny( i_nCommandType ) );
xSource->setPropertyValue( PROPERTY_COMMAND, makeAny( i_rCommand ) );
xSource->setPropertyValue( PROPERTY_ACTIVE_CONNECTION, makeAny( xSrcConnection ) );
xSource->setPropertyValue( PROPERTY_RESULT_SET, makeAny( i_rSourceRows ) );
xSource->setPropertyValue( PROPERTY_SELECTION, makeAny( i_rSelection ) );
xSource->setPropertyValue( PROPERTY_BOOKMARK_SELECTION, makeAny( i_bBookmarkSelection ) );
Reference< XPropertySet > xDest( xFactory->createDataAccessDescriptor(), UNO_SET_THROW );
xDest->setPropertyValue( PROPERTY_ACTIVE_CONNECTION, makeAny( i_rDestConnection ) );
Reference< XCopyTableWizard > xWizard( CopyTableWizard::create( aContext, xSource, xDest ), UNO_SET_THROW );
OUString sTableNameForAppend( GetTableNameForAppend() );
xWizard->setDestinationTableName( GetTableNameForAppend() );
bool bAppendToExisting = !sTableNameForAppend.isEmpty();
xWizard->setOperation( bAppendToExisting ? CopyTableOperation::AppendData : CopyTableOperation::CopyDefinitionAndData );
xWizard->execute();
}
catch( const SQLException& )
{
m_pController->showError( SQLExceptionInfo( ::cppu::getCaughtException() ) );
}
catch( const Exception& )
{
DBG_UNHANDLED_EXCEPTION();
}
}
void OTableCopyHelper::pasteTable( const ::svx::ODataAccessDescriptor& _rPasteData, const OUString& i_rDestDataSourceName,
const SharedConnection& i_rDestConnection )
{
OUString sSrcDataSourceName = _rPasteData.getDataSource();
OUString sCommand;
_rPasteData[ daCommand ] >>= sCommand;
Reference<XConnection> xSrcConnection;
if ( _rPasteData.has(daConnection) )
{
OSL_VERIFY( _rPasteData[daConnection] >>= xSrcConnection );
}
Reference< XResultSet > xResultSet;
if ( _rPasteData.has(daCursor) )
{
OSL_VERIFY( _rPasteData[ daCursor ] >>= xResultSet );
}
Sequence< Any > aSelection;
if ( _rPasteData.has( daSelection ) )
{
OSL_VERIFY( _rPasteData[ daSelection ] >>= aSelection );
OSL_ENSURE( _rPasteData.has( daBookmarkSelection ), "OTableCopyHelper::pasteTable: you should specify BookmarkSelection, too, to be on the safe side!" );
}
bool bBookmarkSelection( true );
if ( _rPasteData.has( daBookmarkSelection ) )
{
OSL_VERIFY( _rPasteData[ daBookmarkSelection ] >>= bBookmarkSelection );
}
OSL_ENSURE( bBookmarkSelection, "OTableCopyHelper::pasteTable: working with selection-indicies (instead of bookmarks) is error-prone, and thus deprecated!" );
sal_Int32 nCommandType = CommandType::COMMAND;
if ( _rPasteData.has(daCommandType) )
_rPasteData[daCommandType] >>= nCommandType;
insertTable( sSrcDataSourceName, xSrcConnection, sCommand, nCommandType,
xResultSet, aSelection, bBookmarkSelection,
i_rDestDataSourceName, i_rDestConnection );
}
void OTableCopyHelper::pasteTable( SotFormatStringId _nFormatId
,const TransferableDataHelper& _rTransData
,const OUString& i_rDestDataSource
,const SharedConnection& _xConnection)
{
if ( _nFormatId == SOT_FORMATSTR_ID_DBACCESS_TABLE || _nFormatId == SOT_FORMATSTR_ID_DBACCESS_QUERY )
{
if ( ODataAccessObjectTransferable::canExtractObjectDescriptor(_rTransData.GetDataFlavorExVector()) )
{
::svx::ODataAccessDescriptor aPasteData = ODataAccessObjectTransferable::extractObjectDescriptor(_rTransData);
pasteTable( aPasteData,i_rDestDataSource,_xConnection);
}
}
else if ( _rTransData.HasFormat(_nFormatId) )
{
try
{
DropDescriptor aTrans;
if ( _nFormatId != SOT_FORMAT_RTF )
const_cast<TransferableDataHelper&>(_rTransData).GetSotStorageStream(SOT_FORMATSTR_ID_HTML ,aTrans.aHtmlRtfStorage);
else
const_cast<TransferableDataHelper&>(_rTransData).GetSotStorageStream(SOT_FORMAT_RTF,aTrans.aHtmlRtfStorage);
aTrans.nType = E_TABLE;
aTrans.bHtml = SOT_FORMATSTR_ID_HTML == _nFormatId;
aTrans.sDefaultTableName = GetTableNameForAppend();
if ( !copyTagTable(aTrans,false,_xConnection) )
m_pController->showError(SQLException(ModuleRes(STR_NO_TABLE_FORMAT_INSIDE), *m_pController, OUString("S1000"), 0, Any()));
}
catch(const SQLException&)
{
m_pController->showError( SQLExceptionInfo( ::cppu::getCaughtException() ) );
}
catch( const Exception& )
{
DBG_UNHANDLED_EXCEPTION();
}
}
else
m_pController->showError(SQLException(ModuleRes(STR_NO_TABLE_FORMAT_INSIDE), *m_pController, OUString("S1000"), 0, Any()));
}
void OTableCopyHelper::pasteTable( const TransferableDataHelper& _rTransData
,const OUString& i_rDestDataSource
,const SharedConnection& _xConnection)
{
if ( _rTransData.HasFormat(SOT_FORMATSTR_ID_DBACCESS_TABLE) || _rTransData.HasFormat(SOT_FORMATSTR_ID_DBACCESS_QUERY) )
pasteTable( SOT_FORMATSTR_ID_DBACCESS_TABLE,_rTransData,i_rDestDataSource,_xConnection);
else if ( _rTransData.HasFormat(SOT_FORMATSTR_ID_HTML) )
pasteTable( SOT_FORMATSTR_ID_HTML,_rTransData,i_rDestDataSource,_xConnection);
else if ( _rTransData.HasFormat(SOT_FORMAT_RTF) )
pasteTable( SOT_FORMAT_RTF,_rTransData,i_rDestDataSource,_xConnection);
}
bool OTableCopyHelper::copyTagTable(OTableCopyHelper::DropDescriptor& _rDesc, bool _bCheck, const SharedConnection& _xConnection)
{
Reference<XEventListener> xEvt;
ODatabaseImportExport* pImport = NULL;
if ( _rDesc.bHtml )
pImport = new OHTMLImportExport(_xConnection,getNumberFormatter(_xConnection, m_pController->getORB()),m_pController->getORB());
else
pImport = new ORTFImportExport(_xConnection,getNumberFormatter(_xConnection, m_pController->getORB()),m_pController->getORB());
xEvt = pImport;
SvStream* pStream = (SvStream*)(SotStorageStream*)_rDesc.aHtmlRtfStorage;
if ( _bCheck )
pImport->enableCheckOnly();
//set the selected tablename
pImport->setSTableName(_rDesc.sDefaultTableName);
pImport->setStream(pStream);
return pImport->Read();
}
bool OTableCopyHelper::isTableFormat(const TransferableDataHelper& _rClipboard) const
{
bool bTableFormat = _rClipboard.HasFormat(SOT_FORMATSTR_ID_DBACCESS_TABLE)
|| _rClipboard.HasFormat(SOT_FORMATSTR_ID_DBACCESS_QUERY)
|| _rClipboard.HasFormat(SOT_FORMAT_RTF)
|| _rClipboard.HasFormat(SOT_FORMATSTR_ID_HTML);
return bTableFormat;
}
bool OTableCopyHelper::copyTagTable(const TransferableDataHelper& _aDroppedData
,DropDescriptor& _rAsyncDrop
,const SharedConnection& _xConnection)
{
bool bRet = false;
bool bHtml = _aDroppedData.HasFormat(SOT_FORMATSTR_ID_HTML);
if ( bHtml || _aDroppedData.HasFormat(SOT_FORMAT_RTF) )
{
if ( bHtml )
const_cast<TransferableDataHelper&>(_aDroppedData).GetSotStorageStream(SOT_FORMATSTR_ID_HTML ,_rAsyncDrop.aHtmlRtfStorage);
else
const_cast<TransferableDataHelper&>(_aDroppedData).GetSotStorageStream(SOT_FORMAT_RTF,_rAsyncDrop.aHtmlRtfStorage);
_rAsyncDrop.bHtml = bHtml;
_rAsyncDrop.bError = !copyTagTable(_rAsyncDrop,true,_xConnection);
bRet = ( !_rAsyncDrop.bError && _rAsyncDrop.aHtmlRtfStorage.Is() );
if ( bRet )
{
// now we need to copy the stream
::utl::TempFile aTmp;
aTmp.EnableKillingFile(false);
_rAsyncDrop.aUrl = aTmp.GetURL();
SotStorageStreamRef aNew = new SotStorageStream( aTmp.GetFileName() );
_rAsyncDrop.aHtmlRtfStorage->Seek(STREAM_SEEK_TO_BEGIN);
_rAsyncDrop.aHtmlRtfStorage->CopyTo( aNew );
aNew->Commit();
_rAsyncDrop.aHtmlRtfStorage = aNew;
}
else
_rAsyncDrop.aHtmlRtfStorage = NULL;
}
return bRet;
}
void OTableCopyHelper::asyncCopyTagTable( DropDescriptor& _rDesc
,const OUString& i_rDestDataSource
,const SharedConnection& _xConnection)
{
if ( _rDesc.aHtmlRtfStorage.Is() )
{
copyTagTable(_rDesc,false,_xConnection);
_rDesc.aHtmlRtfStorage = NULL;
// we now have to delete the temp file created in executeDrop
INetURLObject aURL;
aURL.SetURL(_rDesc.aUrl);
::utl::UCBContentHelper::Kill(aURL.GetMainURL(INetURLObject::NO_DECODE));
}
else if ( !_rDesc.bError )
pasteTable(_rDesc.aDroppedData,i_rDestDataSource,_xConnection);
else
m_pController->showError(SQLException(ModuleRes(STR_NO_TABLE_FORMAT_INSIDE), *m_pController, OUString("S1000"), 0, Any()));
}
} // namespace dbaui
/* vim:set shiftwidth=4 softtabstop=4 expandtab: */
<commit_msg>coverity#703939 Unchecked return value<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 .
*/
#include "TableCopyHelper.hxx"
#include "dbustrings.hrc"
#include "sqlmessage.hxx"
#include <vcl/msgbox.hxx>
#include "WCopyTable.hxx"
#include <dbaccess/genericcontroller.hxx>
#include "WCPage.hxx"
#include <com/sun/star/task/XInteractionHandler.hpp>
#include <com/sun/star/sdb/XSingleSelectQueryComposer.hpp>
#include <com/sun/star/sdb/application/CopyTableOperation.hpp>
#include <com/sun/star/sdb/application/CopyTableWizard.hpp>
#include <com/sun/star/sdb/DataAccessDescriptorFactory.hpp>
#include "RtfReader.hxx"
#include "HtmlReader.hxx"
#include "TokenWriter.hxx"
#include "UITools.hxx"
#include <dbaccess/dataview.hxx>
#include "dbu_resource.hrc"
#include <unotools/ucbhelper.hxx>
#include <tools/urlobj.hxx>
#include <tools/diagnose_ex.h>
#include <comphelper/processfactory.hxx>
#include <com/sun/star/sdbcx/XTablesSupplier.hpp>
#include <com/sun/star/sdbcx/XViewsSupplier.hpp>
#include <com/sun/star/sdb/XQueryDefinitionsSupplier.hpp>
#include <com/sun/star/sdb/SQLContext.hpp>
#include <com/sun/star/sdbc/XParameters.hpp>
#include <com/sun/star/sdbc/XResultSetMetaDataSupplier.hpp>
#include <com/sun/star/sdb/XQueriesSupplier.hpp>
#include <com/sun/star/sdbc/XColumnLocate.hpp>
#include <com/sun/star/sdbcx/XRowLocate.hpp>
#include <vcl/waitobj.hxx>
#include <com/sun/star/sdb/XSQLQueryComposerFactory.hpp>
#include <unotools/tempfile.hxx>
#include <cppuhelper/exc_hlp.hxx>
#include "dbexchange.hxx"
namespace dbaui
{
using namespace ::dbtools;
using namespace ::svx;
using namespace ::com::sun::star::uno;
using namespace ::com::sun::star::task;
using namespace ::com::sun::star::beans;
using namespace ::com::sun::star::lang;
using namespace ::com::sun::star::container;
using namespace ::com::sun::star::sdb;
using namespace ::com::sun::star::sdb::application;
using namespace ::com::sun::star::sdbc;
using namespace ::com::sun::star::sdbcx;
using namespace ::com::sun::star::frame;
using namespace ::com::sun::star::ucb;
OTableCopyHelper::OTableCopyHelper(OGenericUnoController* _pControler)
:m_pController(_pControler)
{
}
void OTableCopyHelper::insertTable( const OUString& i_rSourceDataSource, const Reference<XConnection>& i_rSourceConnection,
const OUString& i_rCommand, const sal_Int32 i_nCommandType,
const Reference< XResultSet >& i_rSourceRows, const Sequence< Any >& i_rSelection, const bool i_bBookmarkSelection,
const OUString& i_rDestDataSource, const Reference<XConnection>& i_rDestConnection)
{
if ( CommandType::QUERY != i_nCommandType && CommandType::TABLE != i_nCommandType )
{
SAL_WARN("dbaccess.ui", "OTableCopyHelper::insertTable: invalid call (no supported format found)!" );
return;
}
try
{
Reference<XConnection> xSrcConnection( i_rSourceConnection );
if ( i_rSourceDataSource == i_rDestDataSource )
xSrcConnection = i_rDestConnection;
if ( !xSrcConnection.is() || !i_rDestConnection.is() )
{
SAL_WARN("dbaccess.ui", "OTableCopyHelper::insertTable: no connection/s!" );
return;
}
Reference<XComponentContext> aContext( m_pController->getORB() );
Reference< XDataAccessDescriptorFactory > xFactory( DataAccessDescriptorFactory::get( aContext ) );
Reference< XPropertySet > xSource( xFactory->createDataAccessDescriptor(), UNO_SET_THROW );
xSource->setPropertyValue( PROPERTY_COMMAND_TYPE, makeAny( i_nCommandType ) );
xSource->setPropertyValue( PROPERTY_COMMAND, makeAny( i_rCommand ) );
xSource->setPropertyValue( PROPERTY_ACTIVE_CONNECTION, makeAny( xSrcConnection ) );
xSource->setPropertyValue( PROPERTY_RESULT_SET, makeAny( i_rSourceRows ) );
xSource->setPropertyValue( PROPERTY_SELECTION, makeAny( i_rSelection ) );
xSource->setPropertyValue( PROPERTY_BOOKMARK_SELECTION, makeAny( i_bBookmarkSelection ) );
Reference< XPropertySet > xDest( xFactory->createDataAccessDescriptor(), UNO_SET_THROW );
xDest->setPropertyValue( PROPERTY_ACTIVE_CONNECTION, makeAny( i_rDestConnection ) );
Reference< XCopyTableWizard > xWizard( CopyTableWizard::create( aContext, xSource, xDest ), UNO_SET_THROW );
OUString sTableNameForAppend( GetTableNameForAppend() );
xWizard->setDestinationTableName( GetTableNameForAppend() );
bool bAppendToExisting = !sTableNameForAppend.isEmpty();
xWizard->setOperation( bAppendToExisting ? CopyTableOperation::AppendData : CopyTableOperation::CopyDefinitionAndData );
xWizard->execute();
}
catch( const SQLException& )
{
m_pController->showError( SQLExceptionInfo( ::cppu::getCaughtException() ) );
}
catch( const Exception& )
{
DBG_UNHANDLED_EXCEPTION();
}
}
void OTableCopyHelper::pasteTable( const ::svx::ODataAccessDescriptor& _rPasteData, const OUString& i_rDestDataSourceName,
const SharedConnection& i_rDestConnection )
{
OUString sSrcDataSourceName = _rPasteData.getDataSource();
OUString sCommand;
_rPasteData[ daCommand ] >>= sCommand;
Reference<XConnection> xSrcConnection;
if ( _rPasteData.has(daConnection) )
{
OSL_VERIFY( _rPasteData[daConnection] >>= xSrcConnection );
}
Reference< XResultSet > xResultSet;
if ( _rPasteData.has(daCursor) )
{
OSL_VERIFY( _rPasteData[ daCursor ] >>= xResultSet );
}
Sequence< Any > aSelection;
if ( _rPasteData.has( daSelection ) )
{
OSL_VERIFY( _rPasteData[ daSelection ] >>= aSelection );
OSL_ENSURE( _rPasteData.has( daBookmarkSelection ), "OTableCopyHelper::pasteTable: you should specify BookmarkSelection, too, to be on the safe side!" );
}
bool bBookmarkSelection( true );
if ( _rPasteData.has( daBookmarkSelection ) )
{
OSL_VERIFY( _rPasteData[ daBookmarkSelection ] >>= bBookmarkSelection );
}
OSL_ENSURE( bBookmarkSelection, "OTableCopyHelper::pasteTable: working with selection-indicies (instead of bookmarks) is error-prone, and thus deprecated!" );
sal_Int32 nCommandType = CommandType::COMMAND;
if ( _rPasteData.has(daCommandType) )
_rPasteData[daCommandType] >>= nCommandType;
insertTable( sSrcDataSourceName, xSrcConnection, sCommand, nCommandType,
xResultSet, aSelection, bBookmarkSelection,
i_rDestDataSourceName, i_rDestConnection );
}
void OTableCopyHelper::pasteTable( SotFormatStringId _nFormatId
,const TransferableDataHelper& _rTransData
,const OUString& i_rDestDataSource
,const SharedConnection& _xConnection)
{
if ( _nFormatId == SOT_FORMATSTR_ID_DBACCESS_TABLE || _nFormatId == SOT_FORMATSTR_ID_DBACCESS_QUERY )
{
if ( ODataAccessObjectTransferable::canExtractObjectDescriptor(_rTransData.GetDataFlavorExVector()) )
{
::svx::ODataAccessDescriptor aPasteData = ODataAccessObjectTransferable::extractObjectDescriptor(_rTransData);
pasteTable( aPasteData,i_rDestDataSource,_xConnection);
}
}
else if ( _rTransData.HasFormat(_nFormatId) )
{
try
{
DropDescriptor aTrans;
if ( _nFormatId != SOT_FORMAT_RTF )
const_cast<TransferableDataHelper&>(_rTransData).GetSotStorageStream(SOT_FORMATSTR_ID_HTML ,aTrans.aHtmlRtfStorage);
else
const_cast<TransferableDataHelper&>(_rTransData).GetSotStorageStream(SOT_FORMAT_RTF,aTrans.aHtmlRtfStorage);
aTrans.nType = E_TABLE;
aTrans.bHtml = SOT_FORMATSTR_ID_HTML == _nFormatId;
aTrans.sDefaultTableName = GetTableNameForAppend();
if ( !copyTagTable(aTrans,false,_xConnection) )
m_pController->showError(SQLException(ModuleRes(STR_NO_TABLE_FORMAT_INSIDE), *m_pController, OUString("S1000"), 0, Any()));
}
catch(const SQLException&)
{
m_pController->showError( SQLExceptionInfo( ::cppu::getCaughtException() ) );
}
catch( const Exception& )
{
DBG_UNHANDLED_EXCEPTION();
}
}
else
m_pController->showError(SQLException(ModuleRes(STR_NO_TABLE_FORMAT_INSIDE), *m_pController, OUString("S1000"), 0, Any()));
}
void OTableCopyHelper::pasteTable( const TransferableDataHelper& _rTransData
,const OUString& i_rDestDataSource
,const SharedConnection& _xConnection)
{
if ( _rTransData.HasFormat(SOT_FORMATSTR_ID_DBACCESS_TABLE) || _rTransData.HasFormat(SOT_FORMATSTR_ID_DBACCESS_QUERY) )
pasteTable( SOT_FORMATSTR_ID_DBACCESS_TABLE,_rTransData,i_rDestDataSource,_xConnection);
else if ( _rTransData.HasFormat(SOT_FORMATSTR_ID_HTML) )
pasteTable( SOT_FORMATSTR_ID_HTML,_rTransData,i_rDestDataSource,_xConnection);
else if ( _rTransData.HasFormat(SOT_FORMAT_RTF) )
pasteTable( SOT_FORMAT_RTF,_rTransData,i_rDestDataSource,_xConnection);
}
bool OTableCopyHelper::copyTagTable(OTableCopyHelper::DropDescriptor& _rDesc, bool _bCheck, const SharedConnection& _xConnection)
{
Reference<XEventListener> xEvt;
ODatabaseImportExport* pImport = NULL;
if ( _rDesc.bHtml )
pImport = new OHTMLImportExport(_xConnection,getNumberFormatter(_xConnection, m_pController->getORB()),m_pController->getORB());
else
pImport = new ORTFImportExport(_xConnection,getNumberFormatter(_xConnection, m_pController->getORB()),m_pController->getORB());
xEvt = pImport;
SvStream* pStream = (SvStream*)(SotStorageStream*)_rDesc.aHtmlRtfStorage;
if ( _bCheck )
pImport->enableCheckOnly();
//set the selected tablename
pImport->setSTableName(_rDesc.sDefaultTableName);
pImport->setStream(pStream);
return pImport->Read();
}
bool OTableCopyHelper::isTableFormat(const TransferableDataHelper& _rClipboard) const
{
bool bTableFormat = _rClipboard.HasFormat(SOT_FORMATSTR_ID_DBACCESS_TABLE)
|| _rClipboard.HasFormat(SOT_FORMATSTR_ID_DBACCESS_QUERY)
|| _rClipboard.HasFormat(SOT_FORMAT_RTF)
|| _rClipboard.HasFormat(SOT_FORMATSTR_ID_HTML);
return bTableFormat;
}
bool OTableCopyHelper::copyTagTable(const TransferableDataHelper& _aDroppedData
,DropDescriptor& _rAsyncDrop
,const SharedConnection& _xConnection)
{
bool bRet = false;
bool bHtml = _aDroppedData.HasFormat(SOT_FORMATSTR_ID_HTML);
if ( bHtml || _aDroppedData.HasFormat(SOT_FORMAT_RTF) )
{
bool bOk;
if ( bHtml )
bOk = const_cast<TransferableDataHelper&>(_aDroppedData).GetSotStorageStream(SOT_FORMATSTR_ID_HTML ,_rAsyncDrop.aHtmlRtfStorage);
else
bOk = const_cast<TransferableDataHelper&>(_aDroppedData).GetSotStorageStream(SOT_FORMAT_RTF,_rAsyncDrop.aHtmlRtfStorage);
_rAsyncDrop.bHtml = bHtml;
_rAsyncDrop.bError = !copyTagTable(_rAsyncDrop,true,_xConnection);
bRet = ( !_rAsyncDrop.bError && bOk && _rAsyncDrop.aHtmlRtfStorage.Is() );
if ( bRet )
{
// now we need to copy the stream
::utl::TempFile aTmp;
aTmp.EnableKillingFile(false);
_rAsyncDrop.aUrl = aTmp.GetURL();
SotStorageStreamRef aNew = new SotStorageStream( aTmp.GetFileName() );
_rAsyncDrop.aHtmlRtfStorage->Seek(STREAM_SEEK_TO_BEGIN);
_rAsyncDrop.aHtmlRtfStorage->CopyTo( aNew );
aNew->Commit();
_rAsyncDrop.aHtmlRtfStorage = aNew;
}
else
_rAsyncDrop.aHtmlRtfStorage = NULL;
}
return bRet;
}
void OTableCopyHelper::asyncCopyTagTable( DropDescriptor& _rDesc
,const OUString& i_rDestDataSource
,const SharedConnection& _xConnection)
{
if ( _rDesc.aHtmlRtfStorage.Is() )
{
copyTagTable(_rDesc,false,_xConnection);
_rDesc.aHtmlRtfStorage = NULL;
// we now have to delete the temp file created in executeDrop
INetURLObject aURL;
aURL.SetURL(_rDesc.aUrl);
::utl::UCBContentHelper::Kill(aURL.GetMainURL(INetURLObject::NO_DECODE));
}
else if ( !_rDesc.bError )
pasteTable(_rDesc.aDroppedData,i_rDestDataSource,_xConnection);
else
m_pController->showError(SQLException(ModuleRes(STR_NO_TABLE_FORMAT_INSIDE), *m_pController, OUString("S1000"), 0, Any()));
}
} // namespace dbaui
/* vim:set shiftwidth=4 softtabstop=4 expandtab: */
<|endoftext|> |
<commit_before>#include <microscopes/lda/model.hpp>
#include <microscopes/lda/data.hpp>
#include <microscopes/lda/random_docs.hpp>
#include <microscopes/common/macros.hpp>
#include <microscopes/common/recarray/dataview.hpp>
#include <microscopes/models/distributions.hpp>
#include <microscopes/common/random_fwd.hpp>
#include <random>
#include <iostream>
#include <time.h>
using namespace std;
using namespace distributions;
using namespace microscopes;
using namespace microscopes::common;
using namespace microscopes::common::recarray;
static void
test_small()
{
rng_t r(time(NULL)); //
std::cout << "creating model definition...";
lda::model_definition def(3, 4);
std::vector<std::vector<size_t>> docs = {{0, 1, 2}, {1, 2, 3}, {3, 3}};
lda::state state(def, .1, .5, .1, docs, r);
std::cout << " complete" << std::endl;
for(unsigned i = 0; i < 100; ++i){
std::cout << "inference step: " << i << std::endl;
state.inference();
std::cout << " K=" << state.usedDishes() << std::endl;
std::cout << " p=" << state.perplexity() << std::endl;
std::map<size_t, int> count;
for(auto k_j: state.k_jt){
for(auto k: k_j){
count[k]++;
}
}
std::cout << "k_jt count " << count << std::endl;
}
std::cout << "FINI!" << std::endl;
}
int main(void){
test_small();
}<commit_msg>Auto count words in docs<commit_after>#include <microscopes/lda/model.hpp>
#include <microscopes/lda/data.hpp>
#include <microscopes/lda/random_docs.hpp>
#include <microscopes/common/macros.hpp>
#include <microscopes/common/recarray/dataview.hpp>
#include <microscopes/models/distributions.hpp>
#include <microscopes/common/random_fwd.hpp>
#include <random>
#include <iostream>
#include <time.h>
using namespace std;
using namespace distributions;
using namespace microscopes;
using namespace microscopes::common;
using namespace microscopes::common::recarray;
size_t
num_unique_words_in_docs(const std::vector< std::vector<size_t> > &docs){
std::set<size_t> words;
for(auto doc: docs)
for(auto word: doc)
words.insert(word);
return words.size();
}
static void
test_small()
{
rng_t r(time(NULL)); //
std::cout << "creating model definition...";
std::vector<std::vector<size_t>> docs = {{0, 1}, {2, 3}};
lda::model_definition def(docs.size(), num_unique_words_in_docs(docs));
lda::state state(def, .5, .01, .5, docs, r);
std::cout << " complete" << std::endl;
for(unsigned i = 0; i < 100; ++i){
std::cout << "inference step: " << i << std::endl;
state.inference();
std::cout << " K=" << state.usedDishes() << std::endl;
std::cout << " p=" << state.perplexity() << std::endl;
std::map<size_t, int> count;
for(auto k_j: state.k_jt){
for(auto k: k_j){
count[k]++;
}
}
std::cout << "k_jt count " << count << std::endl;
}
std::cout << "FINI!" << std::endl;
}
int main(void){
test_small();
}<|endoftext|> |
<commit_before>//Author: wysaid
//blog: http://blog.wysaid.org
#include "cgeMat.h"
#include "cgeVec.h"
#include "graphics.h"
#include <vector>
#include "teapot.h"
using namespace CGE;
#define USE_DEPTH_TEST 0 //Must be 0
//Change them as you like
#define USE_PERSPECTIVE_PROJ 1
#define RENDER_TRIANGLE_HALF_1 1
#define RENDER_TRIANGLE_HALF_2 0
#define USE_CULL_FACE_BACK 1
#define USE_CULL_FACE_FRONT 0
color_t g_color;
#define SCREEN_WIDTH 800
#define SCREEN_HEIGHT 600
#if USE_DEPTH_TEST
//depth 还存在一点问题, 没有效果
unsigned char g_depthMask[SCREEN_WIDTH][SCREEN_HEIGHT];
const int g_maskSize = sizeof(g_depthMask);
#endif
template<class Type>
class Triangle
{
public:
static inline void fillTriangle(const Type& v0, const Type& v1, const Type& v2)
{
if(v0[1] == v2[1])
{
_fillSimpleTriangle(v0, v1, v2);
}
else if(v1[1] == v2[1])
{
_fillSimpleTriangle(v1, v0, v2);
}
else if(v0[1] == v1[1])
{
_fillSimpleTriangle(v0, v2, v1);
}
else
{
_fillNormalTriangle(v0, v1, v2);
}
}
private:
#if USE_DEPTH_TEST
static inline void drawPixel(int x, int y, int depth, color_t color)
{
if(x < 0 || x >= SCREEN_WIDTH || y < 0 || y >= SCREEN_HEIGHT)
return;
if(depth >=0 && depth < 256 && g_depthMask[x][y] <= depth)
{
putpixel_f(x, y, color);
g_depthMask[x][y] = depth;
}
}
static inline void drawLineL2R(int x0, int depth0, int x1, int depth1, int y, color_t color)
{
if(x0 == x1)
{
drawPixel(x0, y, depth0, color);
return;
}
int left, right;
int depthL, depthR;
if(x0 < x1)
{
left = x0;
right = x1;
depthL = depth0;
depthR = depth1;
}
else
{
left = x1;
right = x0;
depthL = depth1;
depthR = depth0;
}
float delta = float(depthR - depthL) / (right - left);
for(int i = left; i <= right; ++i)
{
drawPixel(i, y, depthL, color);
depthL += delta;
}
}
#endif
// 平顶/平底三角形, v0[1] == v2[1], v1[1] 最大
static inline void _fillSimpleTriangle(const Type& v0, const Type& v1, const Type& v2)
{
assert(v0[1] == v2[1]);
float h = v1[1] - v0[1];
float dL = (v1[0] - v0[0]) / h;
float dR = (v1[0] - v2[0]) / h;
float xL = v0[0], xR = v2[0];
#if USE_DEPTH_TEST
static_assert(Type::VEC_DIM >= 3, "Depth-Test is not available now!");
float dDepthL = (v1[2] - v0[2]) / h;
float dDepthR = (v1[2] - v2[2]) / h;
float depthL = v0[2], depthR = v2[2];
#endif
if(v0[1] < v1[1])
{
#if RENDER_TRIANGLE_HALF_1
for(int i = v0[1]; i <= v1[1]; ++i)
{
#if USE_DEPTH_TEST
drawLineL2R(xL, depthL, xR, depthR, i, RED);
depthL += dDepthL;
depthR += dDepthR;
#else
line(xL, i, xR, i); //A Simple Function That Just Draw A Line
#endif //USE_DEPTH_TEST
xL += dL;
xR += dR;
}
#endif //RENDER_TRIANGLE_HALF_1
}
else
{
#if RENDER_TRIANGLE_HALF_2
for(int i = v0[1]; i >= v1[1]; --i)
{
#if USE_DEPTH_TEST
drawLineL2R(xL, depthL, xR, depthR, i, YELLOW);
depthL -= dDepthL;
depthR -= dDepthR;
#else
line(xL, i, xR, i); //A Simple Function That Just Draw A Line
#endif //USE_DEPTH_TEST
xL -= dL;
xR -= dR;
}
#endif
}
}
static inline void _fillNormalTriangle(const Type& v0, const Type& v1, const Type& v2)
{
const Type *pnts[] = {&v0, &v1, &v2};
if((*pnts[0])[1] > (*pnts[1])[1])
std::swap(pnts[0], pnts[1]);
if((*pnts[0])[1] > (*pnts[2])[1])
std::swap(pnts[0], pnts[2]);
if((*pnts[1])[1] > (*pnts[2])[1])
std::swap(pnts[1], pnts[2]);
const Type &vv0 = *pnts[0], &vv1 = *pnts[1], &vv2 = *pnts[2];
Type newPoint(vv1);
newPoint[0] = vv0[0] + (vv2[0] - vv0[0]) * (vv1[1] - vv0[1]) / (vv2[1] - vv0[1]);
_fillSimpleTriangle(newPoint, vv0, vv1);
_fillSimpleTriangle(newPoint, vv2, vv1);
}
};
class Object
{
public:
Object()
{
//把下面的0(1)换成1(0)可以切换两种视图
#if USE_PERSPECTIVE_PROJ
m_matProj = Mat4::makePerspective(M_PI / 4.0f, 4.0f / 3.0f, 1.0f, 1000.0f);
m_matModelView = Mat4::makeLookAt(0.0f, 0.0f, 800.0f, 0.0f, 0.0f, -1000.0f, 0.0f, 1.0f, 0.0f);
#else
m_matProj = Mat4::makeOrtho(-400.0f, 400.0f, -300.0f, 300.0f, -300.0f, 300.0f);
m_matModelView.loadIdentity();
#endif
}
~Object() {}
void render(float x, float y)
{
std::vector<Vec2f> vec;
const Mat4 mvp = m_matProj * m_matModelView;
const Vec4f viewPort(0.0f, 0.0f, SCREEN_WIDTH, SCREEN_HEIGHT);
for(auto t = m_vec.begin(); t != m_vec.end(); ++t)
{
Vec2f coord;
Mat4::projectM4f(*t, mvp, viewPort, coord);
//Mat4::projectM4fPerspective(*t, m_matModelView, m_matProj, viewPort, coord);
vec.push_back(coord);
}
vec.reserve(g_teapotIndicesNum);
for(int i = 0; i < g_teapotIndicesNum; i += 3)
{
const int index1 = g_teapotIndices[i];
const int index2 = g_teapotIndices[i + 1];
const int index3 = g_teapotIndices[i + 2];
const Vec2i posPoints[] = {
Vec2i(x + vec[index1][0], y + vec[index1][1]),// vec[index1][2] * 255.0f),
Vec2i(x + vec[index2][0], y + vec[index2][1]),// vec[index2][2] * 255.0f),
Vec2i(x + vec[index3][0], y + vec[index3][1]) // vec[index3][2] * 255.0f)
};
//设置是否进行面剔除
#if USE_CULL_FACE_BACK || USE_CULL_FACE_FRONT
float ax = posPoints[1][0] - posPoints[0][0];
float ay = posPoints[1][1] - posPoints[0][1];
float bx = posPoints[2][0] - posPoints[1][0];
float by = posPoints[2][1] - posPoints[1][1];
float zNorm = ax * by - ay * bx;
#if USE_CULL_FACE_BACK
if(zNorm <= 0.0f)
{
goto Render_Wire_Frame;
//continue;
}
#endif
#if USE_CULL_FACE_FRONT
if(zNorm > 0.0f)
{
goto Render_Wire_Frame;
//continue;
}
#endif
#endif
//设置是否显示模拟填充
#if RENDER_TRIANGLE_HALF_1 || RENDER_TRIANGLE_HALF_2
setcolor(g_color ^ 0xffffff);
#if USE_DEPTH_TEST
memset(g_depthMask, 0, g_maskSize);
#endif //USE_DEPTH_TEST
Triangle<Vec2i>::fillTriangle(posPoints[0], posPoints[1], posPoints[2]);
#endif //RENDER_TRIANGLE_HALF_1 || RENDER_TRIANGLE_HALF_2
Render_Wire_Frame:
setcolor(g_color);
line(posPoints[0][0], posPoints[0][1], posPoints[1][0], posPoints[1][1]);
line(posPoints[1][0], posPoints[1][1], posPoints[2][0], posPoints[2][1]);
line(posPoints[2][0], posPoints[2][1], posPoints[0][0], posPoints[0][1]);
}
}
void pushPoint(Vec3f pnt)
{
m_vec.push_back(pnt);
}
void pushPoints(Vec3f* pnt, int n)
{
for(int i = 0; i != n; ++i)
{
m_vec.push_back(pnt[i]);
}
}
void pushPoint(float x, float y, float z)
{
m_vec.push_back(Vec3f(x, y, z));
}
void rotate(float rad, float x, float y, float z)
{
m_matModelView.rotate(rad, x, y, z);
}
void rotateX(float rad)
{
m_matModelView.rotateX(rad);
}
void rotateY(float rad)
{
m_matModelView.rotateY(rad);
}
void rotateZ(float rad)
{
m_matModelView.rotateZ(rad);
}
void translateZ(float z)
{
m_matModelView.translateZ(z);
}
void clear() { m_vec.clear(); }
private:
std::vector<Vec3f> m_vec;
Mat4 m_matProj, m_matModelView;
};
bool mouseFunc(Object& obj)
{
if(!mousemsg()) return false;
do
{
static int s_lastX, s_lastY;
static int s_bIsDown = false;
mouse_msg msg = getmouse();
switch (msg.msg)
{
case mouse_msg_down:
s_lastX = msg.x;
s_lastY = msg.y;
s_bIsDown = true;
break;
case mouse_msg_up:
s_bIsDown = false;
break;
case mouse_msg_wheel:
obj.translateZ(msg.wheel / 12.0f);
break;
default:
break;
}
if(s_bIsDown && msg.is_move())
{
obj.rotateX((msg.y - s_lastY) / 100.0f);
obj.rotateY((msg.x - s_lastX) / 100.0f);
s_lastX = msg.x;
s_lastY = msg.y;
}
}while(mousemsg());
return true;
}
void getObj(Object& obj, float scale)
{
const int num = g_positionNum / 3;
for(int i = 0; i < g_positionNum; i += 3)
{
obj.pushPoint(g_teapotPositions[i] * 10.0f, g_teapotPositions[i + 1] * 10.0f, g_teapotPositions[i + 2] * 10.0f);
}
}
int main()
{
initgraph(SCREEN_WIDTH, SCREEN_HEIGHT);
setrendermode(RENDER_MANUAL);
Object obj;
randomize();
getObj(obj, 100);
int i = 0;
static bool s_useBlur = false;
float x = 0.0f, y = 0.0f;
float dx = randomf()* 5.0f + 1.0f, dy = randomf()* 5.0f + 1.0f;
float radX = randomf()*10.0f + 0.001f, radY = randomf() * 10.0f, radZ = randomf() * 10.0f;
setbkmode(TRANSPARENT);
setfillcolor(DARKGRAY);
for(; is_run(); delay_fps(60))
{
if(s_useBlur) imagefilter_blurring(0, 0x80, 0x100);
else cleardevice();
mouseFunc(obj);
obj.render(0, 0);
g_color = HSVtoRGB(i*2, 1.0f, 1.0f);
outtextxy(20, 10, "点击空格键启用模糊滤镜, 滚轮移动模型Z值");
x += dx;
y += dy;
if(x < 0.0f || x > 800.0f)
{
dx = -dx;
x += dx;
}
if(y < 0.0f || y > 600.0f)
{
dy = -dy;
y += dy;
}
if(++i > 360)
{
i = 0;
}
if(kbhit())
{
switch (getch())
{
case ' ':
s_useBlur = !s_useBlur;
break;
default:
break;
}
}
}
closegraph();
return 0;
}<commit_msg>update<commit_after>//Author: wysaid
//blog: http://blog.wysaid.org
#include "cgeMat.h"
#include "cgeVec.h"
#include "graphics.h"
#include <vector>
#include "teapot.h"
using namespace CGE;
#define USE_DEPTH_TEST 0 //Must be 0
//Change them as you like
#define USE_PERSPECTIVE_PROJ 1
#define RENDER_TRIANGLE_HALF_1 1
#define RENDER_TRIANGLE_HALF_2 0
#define USE_CULL_FACE_BACK 1
#define USE_CULL_FACE_FRONT 0
#define SCREEN_WIDTH 800
#define SCREEN_HEIGHT 600
#if USE_DEPTH_TEST
//depth 还存在一点问题, 没有效果
unsigned char g_depthMask[SCREEN_WIDTH][SCREEN_HEIGHT];
const int g_maskSize = sizeof(g_depthMask);
#endif
color_t g_color;
template<class Type>
class Triangle
{
public:
static inline void fillTriangle(const Type& v0, const Type& v1, const Type& v2)
{
if(v0[1] == v2[1])
{
_fillSimpleTriangle(v0, v1, v2);
}
else if(v1[1] == v2[1])
{
_fillSimpleTriangle(v1, v0, v2);
}
else if(v0[1] == v1[1])
{
_fillSimpleTriangle(v0, v2, v1);
}
else
{
_fillNormalTriangle(v0, v1, v2);
}
}
private:
#if USE_DEPTH_TEST
static inline void drawPixel(int x, int y, int depth, color_t color)
{
if(x < 0 || x >= SCREEN_WIDTH || y < 0 || y >= SCREEN_HEIGHT)
return;
if(depth >=0 && depth < 256 && g_depthMask[x][y] <= depth)
{
putpixel_f(x, y, color);
g_depthMask[x][y] = depth;
}
}
static inline void drawLineL2R(int x0, int depth0, int x1, int depth1, int y, color_t color)
{
if(x0 == x1)
{
drawPixel(x0, y, depth0, color);
return;
}
int left, right;
int depthL, depthR;
if(x0 < x1)
{
left = x0;
right = x1;
depthL = depth0;
depthR = depth1;
}
else
{
left = x1;
right = x0;
depthL = depth1;
depthR = depth0;
}
float delta = float(depthR - depthL) / (right - left);
for(int i = left; i <= right; ++i)
{
drawPixel(i, y, depthL, color);
depthL += delta;
}
}
#endif
// 平顶/平底三角形, v0[1] == v2[1], v1[1] 最大
static inline void _fillSimpleTriangle(const Type& v0, const Type& v1, const Type& v2)
{
assert(v0[1] == v2[1]);
float h = v1[1] - v0[1];
float dL = (v1[0] - v0[0]) / h;
float dR = (v1[0] - v2[0]) / h;
float xL = v0[0], xR = v2[0];
#if USE_DEPTH_TEST
static_assert(Type::VEC_DIM >= 3, "Depth-Test is not available now!");
float dDepthL = (v1[2] - v0[2]) / h;
float dDepthR = (v1[2] - v2[2]) / h;
float depthL = v0[2], depthR = v2[2];
#endif
if(v0[1] < v1[1])
{
#if RENDER_TRIANGLE_HALF_1
for(int i = v0[1]; i <= v1[1]; ++i)
{
#if USE_DEPTH_TEST
drawLineL2R(xL, depthL, xR, depthR, i, RED);
depthL += dDepthL;
depthR += dDepthR;
#else
line(xL, i, xR, i); //A Simple Function That Just Draw A Line
#endif //USE_DEPTH_TEST
xL += dL;
xR += dR;
}
#endif //RENDER_TRIANGLE_HALF_1
}
else
{
#if RENDER_TRIANGLE_HALF_2
for(int i = v0[1]; i >= v1[1]; --i)
{
#if USE_DEPTH_TEST
drawLineL2R(xL, depthL, xR, depthR, i, YELLOW);
depthL -= dDepthL;
depthR -= dDepthR;
#else
line(xL, i, xR, i); //A Simple Function That Just Draw A Line
#endif //USE_DEPTH_TEST
xL -= dL;
xR -= dR;
}
#endif
}
}
static inline void _fillNormalTriangle(const Type& v0, const Type& v1, const Type& v2)
{
const Type *pnts[] = {&v0, &v1, &v2};
if((*pnts[0])[1] > (*pnts[1])[1])
std::swap(pnts[0], pnts[1]);
if((*pnts[0])[1] > (*pnts[2])[1])
std::swap(pnts[0], pnts[2]);
if((*pnts[1])[1] > (*pnts[2])[1])
std::swap(pnts[1], pnts[2]);
const Type &vv0 = *pnts[0], &vv1 = *pnts[1], &vv2 = *pnts[2];
Type newPoint(vv1);
newPoint[0] = vv0[0] + (vv2[0] - vv0[0]) * (vv1[1] - vv0[1]) / (vv2[1] - vv0[1]);
_fillSimpleTriangle(newPoint, vv0, vv1);
_fillSimpleTriangle(newPoint, vv2, vv1);
}
};
class Object
{
public:
Object()
{
//把下面的0(1)换成1(0)可以切换两种视图
#if USE_PERSPECTIVE_PROJ
m_matProj = Mat4::makePerspective(M_PI / 4.0f, 4.0f / 3.0f, 1.0f, 1000.0f);
m_matModelView = Mat4::makeLookAt(0.0f, 0.0f, 800.0f, 0.0f, 0.0f, -1000.0f, 0.0f, 1.0f, 0.0f);
#else
m_matProj = Mat4::makeOrtho(-400.0f, 400.0f, -300.0f, 300.0f, -300.0f, 300.0f);
m_matModelView.loadIdentity();
#endif
}
~Object() {}
void render(float x, float y)
{
std::vector<Vec2f> vec;
const Mat4 mvp = m_matProj * m_matModelView;
const Vec4f viewPort(0.0f, 0.0f, SCREEN_WIDTH, SCREEN_HEIGHT);
for(auto t = m_vec.begin(); t != m_vec.end(); ++t)
{
Vec2f coord;
Mat4::projectM4f(*t, mvp, viewPort, coord);
//Mat4::projectM4fPerspective(*t, m_matModelView, m_matProj, viewPort, coord);
vec.push_back(coord);
}
vec.reserve(g_teapotIndicesNum);
for(int i = 0; i < g_teapotIndicesNum; i += 3)
{
const int index1 = g_teapotIndices[i];
const int index2 = g_teapotIndices[i + 1];
const int index3 = g_teapotIndices[i + 2];
const Vec2i posPoints[] = {
Vec2i(x + vec[index1][0], y + vec[index1][1]),// vec[index1][2] * 255.0f),
Vec2i(x + vec[index2][0], y + vec[index2][1]),// vec[index2][2] * 255.0f),
Vec2i(x + vec[index3][0], y + vec[index3][1]) // vec[index3][2] * 255.0f)
};
//设置是否进行面剔除
#if USE_CULL_FACE_BACK || USE_CULL_FACE_FRONT
float ax = posPoints[1][0] - posPoints[0][0];
float ay = posPoints[1][1] - posPoints[0][1];
float bx = posPoints[2][0] - posPoints[1][0];
float by = posPoints[2][1] - posPoints[1][1];
float zNorm = ax * by - ay * bx;
#if USE_CULL_FACE_BACK
if(zNorm <= 0.0f)
{
goto Render_Wire_Frame;
//continue;
}
#endif
#if USE_CULL_FACE_FRONT
if(zNorm > 0.0f)
{
goto Render_Wire_Frame;
//continue;
}
#endif
#endif
//设置是否显示模拟填充
#if RENDER_TRIANGLE_HALF_1 || RENDER_TRIANGLE_HALF_2
setcolor(g_color ^ 0xffffff);
#if USE_DEPTH_TEST
memset(g_depthMask, 0, g_maskSize);
#endif //USE_DEPTH_TEST
Triangle<Vec2i>::fillTriangle(posPoints[0], posPoints[1], posPoints[2]);
#endif //RENDER_TRIANGLE_HALF_1 || RENDER_TRIANGLE_HALF_2
Render_Wire_Frame:
setcolor(g_color);
line(posPoints[0][0], posPoints[0][1], posPoints[1][0], posPoints[1][1]);
line(posPoints[1][0], posPoints[1][1], posPoints[2][0], posPoints[2][1]);
line(posPoints[2][0], posPoints[2][1], posPoints[0][0], posPoints[0][1]);
}
}
void pushPoint(Vec3f pnt)
{
m_vec.push_back(pnt);
}
void pushPoints(Vec3f* pnt, int n)
{
for(int i = 0; i != n; ++i)
{
m_vec.push_back(pnt[i]);
}
}
void pushPoint(float x, float y, float z)
{
m_vec.push_back(Vec3f(x, y, z));
}
void rotate(float rad, float x, float y, float z)
{
m_matModelView.rotate(rad, x, y, z);
}
void rotateX(float rad)
{
m_matModelView.rotateX(rad);
}
void rotateY(float rad)
{
m_matModelView.rotateY(rad);
}
void rotateZ(float rad)
{
m_matModelView.rotateZ(rad);
}
void translateZ(float z)
{
m_matModelView.translateZ(z);
}
void clear() { m_vec.clear(); }
private:
std::vector<Vec3f> m_vec;
Mat4 m_matProj, m_matModelView;
};
bool mouseFunc(Object& obj)
{
if(!mousemsg()) return false;
do
{
static int s_lastX, s_lastY;
static int s_bIsDown = false;
mouse_msg msg = getmouse();
switch (msg.msg)
{
case mouse_msg_down:
s_lastX = msg.x;
s_lastY = msg.y;
s_bIsDown = true;
break;
case mouse_msg_up:
s_bIsDown = false;
break;
case mouse_msg_wheel:
obj.translateZ(msg.wheel / 12.0f);
break;
default:
break;
}
if(s_bIsDown && msg.is_move())
{
obj.rotateX((msg.y - s_lastY) / 100.0f);
obj.rotateY((msg.x - s_lastX) / 100.0f);
s_lastX = msg.x;
s_lastY = msg.y;
}
}while(mousemsg());
return true;
}
void getObj(Object& obj, float scale)
{
const int num = g_positionNum / 3;
for(int i = 0; i < g_positionNum; i += 3)
{
obj.pushPoint(g_teapotPositions[i] * 10.0f, g_teapotPositions[i + 1] * 10.0f, g_teapotPositions[i + 2] * 10.0f);
}
}
int main()
{
initgraph(SCREEN_WIDTH, SCREEN_HEIGHT);
setrendermode(RENDER_MANUAL);
Object obj;
randomize();
getObj(obj, 100);
int i = 0;
static bool s_useBlur = false;
float x = 0.0f, y = 0.0f;
float dx = randomf()* 5.0f + 1.0f, dy = randomf()* 5.0f + 1.0f;
float radX = randomf()*10.0f + 0.001f, radY = randomf() * 10.0f, radZ = randomf() * 10.0f;
setbkmode(TRANSPARENT);
setfillcolor(DARKGRAY);
for(; is_run(); delay_fps(60))
{
if(s_useBlur) imagefilter_blurring(0, 0x80, 0x100);
else cleardevice();
mouseFunc(obj);
obj.render(0, 0);
g_color = HSVtoRGB(i*2, 1.0f, 1.0f);
outtextxy(20, 10, "点击空格键启用模糊滤镜, 滚轮移动模型Z值");
x += dx;
y += dy;
if(x < 0.0f || x > 800.0f)
{
dx = -dx;
x += dx;
}
if(y < 0.0f || y > 600.0f)
{
dy = -dy;
y += dy;
}
if(++i > 360)
{
i = 0;
}
if(kbhit())
{
switch (getch())
{
case ' ':
s_useBlur = !s_useBlur;
break;
default:
break;
}
}
}
closegraph();
return 0;
}<|endoftext|> |
<commit_before>#include "stdafx.h"
#include "datastore.h"
namespace You {
namespace DataStore {
const std::wstring DataStore::FILE_PATH = std::wstring(L"data.xml");
bool DataStore::post(TaskId rawId, const STask& sTask) {
// Consider changing parameter to std::wstring altogether
std::wstring taskId = boost::lexical_cast<std::wstring>(rawId);
if (document.find_child_by_attribute(L"id", taskId.c_str())) {
return false;
}
pugi::xml_node newTask = document.append_child(L"task");
pugi::xml_attribute id = newTask.append_attribute(L"id");
id.set_value(taskId.c_str());
serialize(sTask, newTask);
return true;
}
bool DataStore::put(TaskId rawId, const STask& sTask) {
std::wstring taskId = boost::lexical_cast<std::wstring>(rawId);
pugi::xml_node toEdit =
document.find_child_by_attribute(L"id", taskId.c_str());
if (!toEdit) {
return false;
}
document.remove_child(toEdit);
return post(rawId, sTask);
}
boost::variant<bool, DataStore::STask> DataStore::get(TaskId rawId) {
std::wstring taskId = boost::lexical_cast<std::wstring>(rawId);
pugi::xml_node toGet =
document.find_child_by_attribute(L"id", taskId.c_str());
if (!toGet) {
return false;
}
DataStore::STask stask = deserialize(toGet);
return stask;
}
bool DataStore::erase(TaskId rawId) {
std::wstring taskId = boost::lexical_cast<std::wstring>(rawId);
pugi::xml_node toErase =
document.find_child_by_attribute(L"id", taskId.c_str());
return document.remove_child(toErase);
}
bool DataStore::saveData() {
bool status = document.save_file(FILE_PATH.c_str());
return status;
}
void DataStore::loadData() {
pugi::xml_parse_result status = document.load_file(FILE_PATH.c_str());
// Not sure if the if block below is necessary
if (status == pugi::xml_parse_status::status_file_not_found) {
document.reset();
}
}
void DataStore::serialize(const STask& stask, pugi::xml_node& const node) {
for each (KeyValuePair kvp in stask) {
pugi::xml_node keyNode =
node.append_child(kvp.first.c_str());
pugi::xml_node keyValue =
keyNode.append_child(pugi::xml_node_type::node_pcdata);
keyValue.set_value(kvp.second.c_str());
}
}
DataStore::STask DataStore::deserialize(const pugi::xml_node& taskNode) {
STask stask;
for (auto iter = taskNode.begin(); iter != taskNode.end(); ++iter) {
stask.insert(KeyValuePair(Key(iter->name()),
Value(iter->child_value())));
}
return stask;
}
} // namespace DataStore
} // namespace You
<commit_msg>Modify the other for each to iterator-based for loop<commit_after>#include "stdafx.h"
#include "datastore.h"
namespace You {
namespace DataStore {
const std::wstring DataStore::FILE_PATH = std::wstring(L"data.xml");
bool DataStore::post(TaskId rawId, const STask& sTask) {
// Consider changing parameter to std::wstring altogether
std::wstring taskId = boost::lexical_cast<std::wstring>(rawId);
if (document.find_child_by_attribute(L"id", taskId.c_str())) {
return false;
}
pugi::xml_node newTask = document.append_child(L"task");
pugi::xml_attribute id = newTask.append_attribute(L"id");
id.set_value(taskId.c_str());
serialize(sTask, newTask);
return true;
}
bool DataStore::put(TaskId rawId, const STask& sTask) {
std::wstring taskId = boost::lexical_cast<std::wstring>(rawId);
pugi::xml_node toEdit =
document.find_child_by_attribute(L"id", taskId.c_str());
if (!toEdit) {
return false;
}
document.remove_child(toEdit);
return post(rawId, sTask);
}
boost::variant<bool, DataStore::STask> DataStore::get(TaskId rawId) {
std::wstring taskId = boost::lexical_cast<std::wstring>(rawId);
pugi::xml_node toGet =
document.find_child_by_attribute(L"id", taskId.c_str());
if (!toGet) {
return false;
}
DataStore::STask stask = deserialize(toGet);
return stask;
}
bool DataStore::erase(TaskId rawId) {
std::wstring taskId = boost::lexical_cast<std::wstring>(rawId);
pugi::xml_node toErase =
document.find_child_by_attribute(L"id", taskId.c_str());
return document.remove_child(toErase);
}
bool DataStore::saveData() {
bool status = document.save_file(FILE_PATH.c_str());
return status;
}
void DataStore::loadData() {
pugi::xml_parse_result status = document.load_file(FILE_PATH.c_str());
// Not sure if the if block below is necessary
if (status == pugi::xml_parse_status::status_file_not_found) {
document.reset();
}
}
void DataStore::serialize(const STask& stask, pugi::xml_node& const node) {
for (auto iter = stask.begin(); iter != stask.end(); ++iter) {
pugi::xml_node keyNode =
node.append_child(iter->first.c_str());
pugi::xml_node keyValue =
keyNode.append_child(pugi::xml_node_type::node_pcdata);
keyValue.set_value(iter->second.c_str());
}
}
DataStore::STask DataStore::deserialize(const pugi::xml_node& taskNode) {
STask stask;
for (auto iter = taskNode.begin(); iter != taskNode.end(); ++iter) {
stask.insert(KeyValuePair(Key(iter->name()),
Value(iter->child_value())));
}
return stask;
}
} // namespace DataStore
} // namespace You
<|endoftext|> |
<commit_before>/*M///////////////////////////////////////////////////////////////////////////////////////
//
// IMPORTANT: READ BEFORE DOWNLOADING, COPYING, INSTALLING OR USING.
//
// By downloading, copying, installing or using the software you agree to this license.
// If you do not agree to this license, do not download, install,
// copy or use the software.
//
//
// License Agreement
// For Open Source Computer Vision Library
//
// Copyright (C) 2000-2008, Intel Corporation, all rights reserved.
// Copyright (C) 2009, Willow Garage Inc., all rights reserved.
// Third party copyrights are property of their respective owners.
//
// Redistribution and use in source and binary forms, with or without modification,
// are permitted provided that the following conditions are met:
//
// * Redistribution's of source code must retain the above copyright notice,
// this list of conditions and the following disclaimer.
//
// * Redistribution's 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.
//
// * The name of the copyright holders may not 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 Intel Corporation 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.
//
//M*/
#ifndef _OPENCV_FLANN_HPP_
#define _OPENCV_FLANN_HPP_
#ifdef __cplusplus
#include "opencv2/flann/flann_base.hpp"
namespace cv
{
namespace flann
{
template <typename T> struct CvType {};
template <> struct CvType<unsigned char> { static int type() { return CV_8U; } };
template <> struct CvType<char> { static int type() { return CV_8S; } };
template <> struct CvType<unsigned short> { static int type() { return CV_16U; } };
template <> struct CvType<short> { static int type() { return CV_16S; } };
template <> struct CvType<int> { static int type() { return CV_32S; } };
template <> struct CvType<float> { static int type() { return CV_32F; } };
template <> struct CvType<double> { static int type() { return CV_64F; } };
using ::cvflann::IndexParams;
using ::cvflann::LinearIndexParams;
using ::cvflann::KDTreeIndexParams;
using ::cvflann::KMeansIndexParams;
using ::cvflann::CompositeIndexParams;
using ::cvflann::AutotunedIndexParams;
using ::cvflann::SavedIndexParams;
using ::cvflann::SearchParams;
template <typename T>
class CV_EXPORTS Index_ {
::cvflann::Index<T>* nnIndex;
public:
Index_(const Mat& features, const IndexParams& params);
~Index_();
void knnSearch(const vector<T>& query, vector<int>& indices, vector<float>& dists, int knn, const SearchParams& params);
void knnSearch(const Mat& queries, Mat& indices, Mat& dists, int knn, const SearchParams& params);
int radiusSearch(const vector<T>& query, vector<int>& indices, vector<float>& dists, float radius, const SearchParams& params);
int radiusSearch(const Mat& query, Mat& indices, Mat& dists, float radius, const SearchParams& params);
void save(std::string filename) { nnIndex->save(filename); }
int veclen() const { return nnIndex->veclen(); }
int size() const { return nnIndex->size(); }
const IndexParams* getIndexParameters() { return nnIndex->getParameters(); }
};
template <typename T>
Index_<T>::Index_(const Mat& dataset, const IndexParams& params)
{
CV_Assert(dataset.type() == CvType<T>::type());
CV_Assert(dataset.isContinuous());
::cvflann::Matrix<T> m_dataset((T*)dataset.ptr<T>(0), dataset.rows, dataset.cols);
nnIndex = new ::cvflann::Index<T>(m_dataset, params);
nnIndex->buildIndex();
}
template <typename T>
Index_<T>::~Index_()
{
delete nnIndex;
}
template <typename T>
void Index_<T>::knnSearch(const vector<T>& query, vector<int>& indices, vector<float>& dists, int knn, const SearchParams& searchParams)
{
::cvflann::Matrix<T> m_query((T*)&query[0], 1, (int)query.size());
::cvflann::Matrix<int> m_indices(&indices[0], 1, (int)indices.size());
::cvflann::Matrix<float> m_dists(&dists[0], 1, (int)dists.size());
nnIndex->knnSearch(m_query,m_indices,m_dists,knn,searchParams);
}
template <typename T>
void Index_<T>::knnSearch(const Mat& queries, Mat& indices, Mat& dists, int knn, const SearchParams& searchParams)
{
CV_Assert(queries.type() == CvType<T>::type());
CV_Assert(queries.isContinuous());
::cvflann::Matrix<T> m_queries((T*)queries.ptr<T>(0), queries.rows, queries.cols);
CV_Assert(indices.type() == CV_32S);
CV_Assert(indices.isContinuous());
::cvflann::Matrix<int> m_indices((int*)indices.ptr<int>(0), indices.rows, indices.cols);
CV_Assert(dists.type() == CV_32F);
CV_Assert(dists.isContinuous());
::cvflann::Matrix<float> m_dists((float*)dists.ptr<float>(0), dists.rows, dists.cols);
nnIndex->knnSearch(m_queries,m_indices,m_dists,knn, searchParams);
}
template <typename T>
int Index_<T>::radiusSearch(const vector<T>& query, vector<int>& indices, vector<float>& dists, float radius, const SearchParams& searchParams)
{
::cvflann::Matrix<T> m_query((T*)&query[0], 1, (int)query.size());
::cvflann::Matrix<int> m_indices(&indices[0], 1, (int)indices.size());
::cvflann::Matrix<float> m_dists(&dists[0], 1, (int)dists.size());
return nnIndex->radiusSearch(m_query,m_indices,m_dists,radius,searchParams);
}
template <typename T>
int Index_<T>::radiusSearch(const Mat& query, Mat& indices, Mat& dists, float radius, const SearchParams& searchParams)
{
CV_Assert(query.type() == CvType<T>::type());
CV_Assert(query.isContinuous());
::cvflann::Matrix<T> m_query((T*)query.ptr<T>(0), query.rows, query.cols);
CV_Assert(indices.type() == CV_32S);
CV_Assert(indices.isContinuous());
::cvflann::Matrix<int> m_indices((int*)indices.ptr<int>(0), indices.rows, indices.cols);
CV_Assert(dists.type() == CV_32F);
CV_Assert(dists.isContinuous());
::cvflann::Matrix<float> m_dists((float*)dists.ptr<float>(0), dists.rows, dists.cols);
return nnIndex->radiusSearch(m_query,m_indices,m_dists,radius,searchParams);
}
typedef Index_<float> Index;
template <typename ELEM_TYPE, typename DIST_TYPE>
int hierarchicalClustering(const Mat& features, Mat& centers, const KMeansIndexParams& params)
{
CV_Assert(features.type() == CvType<ELEM_TYPE>::type());
CV_Assert(features.isContinuous());
::cvflann::Matrix<ELEM_TYPE> m_features((ELEM_TYPE*)features.ptr<ELEM_TYPE>(0), features.rows, features.cols);
CV_Assert(centers.type() == CvType<DIST_TYPE>::type());
CV_Assert(centers.isContinuous());
::cvflann::Matrix<DIST_TYPE> m_centers((DIST_TYPE*)centers.ptr<DIST_TYPE>(0), centers.rows, centers.cols);
return ::cvflann::hierarchicalClustering<ELEM_TYPE,DIST_TYPE>(m_features, m_centers, params);
}
} } // namespace cv::flann
#endif // __cplusplus
#endif
<commit_msg>fixed #841<commit_after>/*M///////////////////////////////////////////////////////////////////////////////////////
//
// IMPORTANT: READ BEFORE DOWNLOADING, COPYING, INSTALLING OR USING.
//
// By downloading, copying, installing or using the software you agree to this license.
// If you do not agree to this license, do not download, install,
// copy or use the software.
//
//
// License Agreement
// For Open Source Computer Vision Library
//
// Copyright (C) 2000-2008, Intel Corporation, all rights reserved.
// Copyright (C) 2009, Willow Garage Inc., all rights reserved.
// Third party copyrights are property of their respective owners.
//
// Redistribution and use in source and binary forms, with or without modification,
// are permitted provided that the following conditions are met:
//
// * Redistribution's of source code must retain the above copyright notice,
// this list of conditions and the following disclaimer.
//
// * Redistribution's 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.
//
// * The name of the copyright holders may not 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 Intel Corporation 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.
//
//M*/
#ifndef _OPENCV_FLANN_HPP_
#define _OPENCV_FLANN_HPP_
#ifdef __cplusplus
#include "opencv2/flann/flann_base.hpp"
namespace cv
{
namespace flann
{
template <typename T> struct CvType {};
template <> struct CvType<unsigned char> { static int type() { return CV_8U; } };
template <> struct CvType<char> { static int type() { return CV_8S; } };
template <> struct CvType<unsigned short> { static int type() { return CV_16U; } };
template <> struct CvType<short> { static int type() { return CV_16S; } };
template <> struct CvType<int> { static int type() { return CV_32S; } };
template <> struct CvType<float> { static int type() { return CV_32F; } };
template <> struct CvType<double> { static int type() { return CV_64F; } };
using ::cvflann::IndexParams;
using ::cvflann::LinearIndexParams;
using ::cvflann::KDTreeIndexParams;
using ::cvflann::KMeansIndexParams;
using ::cvflann::CompositeIndexParams;
using ::cvflann::AutotunedIndexParams;
using ::cvflann::SavedIndexParams;
using ::cvflann::SearchParams;
template <typename T>
class CV_EXPORTS Index_ {
::cvflann::Index<T>* nnIndex;
public:
Index_(const Mat& features, const IndexParams& params);
~Index_();
void knnSearch(const vector<T>& query, vector<int>& indices, vector<float>& dists, int knn, const SearchParams& params);
void knnSearch(const Mat& queries, Mat& indices, Mat& dists, int knn, const SearchParams& params);
int radiusSearch(const vector<T>& query, vector<int>& indices, vector<float>& dists, float radius, const SearchParams& params);
int radiusSearch(const Mat& query, Mat& indices, Mat& dists, float radius, const SearchParams& params);
void save(std::string filename) { nnIndex->save(filename); }
int veclen() const { return nnIndex->veclen(); }
int size() const { return nnIndex->size(); }
const IndexParams* getIndexParameters() { return nnIndex->getIndexParameters(); }
};
template <typename T>
Index_<T>::Index_(const Mat& dataset, const IndexParams& params)
{
CV_Assert(dataset.type() == CvType<T>::type());
CV_Assert(dataset.isContinuous());
::cvflann::Matrix<T> m_dataset((T*)dataset.ptr<T>(0), dataset.rows, dataset.cols);
nnIndex = new ::cvflann::Index<T>(m_dataset, params);
nnIndex->buildIndex();
}
template <typename T>
Index_<T>::~Index_()
{
delete nnIndex;
}
template <typename T>
void Index_<T>::knnSearch(const vector<T>& query, vector<int>& indices, vector<float>& dists, int knn, const SearchParams& searchParams)
{
::cvflann::Matrix<T> m_query((T*)&query[0], 1, (int)query.size());
::cvflann::Matrix<int> m_indices(&indices[0], 1, (int)indices.size());
::cvflann::Matrix<float> m_dists(&dists[0], 1, (int)dists.size());
nnIndex->knnSearch(m_query,m_indices,m_dists,knn,searchParams);
}
template <typename T>
void Index_<T>::knnSearch(const Mat& queries, Mat& indices, Mat& dists, int knn, const SearchParams& searchParams)
{
CV_Assert(queries.type() == CvType<T>::type());
CV_Assert(queries.isContinuous());
::cvflann::Matrix<T> m_queries((T*)queries.ptr<T>(0), queries.rows, queries.cols);
CV_Assert(indices.type() == CV_32S);
CV_Assert(indices.isContinuous());
::cvflann::Matrix<int> m_indices((int*)indices.ptr<int>(0), indices.rows, indices.cols);
CV_Assert(dists.type() == CV_32F);
CV_Assert(dists.isContinuous());
::cvflann::Matrix<float> m_dists((float*)dists.ptr<float>(0), dists.rows, dists.cols);
nnIndex->knnSearch(m_queries,m_indices,m_dists,knn, searchParams);
}
template <typename T>
int Index_<T>::radiusSearch(const vector<T>& query, vector<int>& indices, vector<float>& dists, float radius, const SearchParams& searchParams)
{
::cvflann::Matrix<T> m_query((T*)&query[0], 1, (int)query.size());
::cvflann::Matrix<int> m_indices(&indices[0], 1, (int)indices.size());
::cvflann::Matrix<float> m_dists(&dists[0], 1, (int)dists.size());
return nnIndex->radiusSearch(m_query,m_indices,m_dists,radius,searchParams);
}
template <typename T>
int Index_<T>::radiusSearch(const Mat& query, Mat& indices, Mat& dists, float radius, const SearchParams& searchParams)
{
CV_Assert(query.type() == CvType<T>::type());
CV_Assert(query.isContinuous());
::cvflann::Matrix<T> m_query((T*)query.ptr<T>(0), query.rows, query.cols);
CV_Assert(indices.type() == CV_32S);
CV_Assert(indices.isContinuous());
::cvflann::Matrix<int> m_indices((int*)indices.ptr<int>(0), indices.rows, indices.cols);
CV_Assert(dists.type() == CV_32F);
CV_Assert(dists.isContinuous());
::cvflann::Matrix<float> m_dists((float*)dists.ptr<float>(0), dists.rows, dists.cols);
return nnIndex->radiusSearch(m_query,m_indices,m_dists,radius,searchParams);
}
typedef Index_<float> Index;
template <typename ELEM_TYPE, typename DIST_TYPE>
int hierarchicalClustering(const Mat& features, Mat& centers, const KMeansIndexParams& params)
{
CV_Assert(features.type() == CvType<ELEM_TYPE>::type());
CV_Assert(features.isContinuous());
::cvflann::Matrix<ELEM_TYPE> m_features((ELEM_TYPE*)features.ptr<ELEM_TYPE>(0), features.rows, features.cols);
CV_Assert(centers.type() == CvType<DIST_TYPE>::type());
CV_Assert(centers.isContinuous());
::cvflann::Matrix<DIST_TYPE> m_centers((DIST_TYPE*)centers.ptr<DIST_TYPE>(0), centers.rows, centers.cols);
return ::cvflann::hierarchicalClustering<ELEM_TYPE,DIST_TYPE>(m_features, m_centers, params);
}
} } // namespace cv::flann
#endif // __cplusplus
#endif
<|endoftext|> |
<commit_before>/*M///////////////////////////////////////////////////////////////////////////////////////
//
// IMPORTANT: READ BEFORE DOWNLOADING, COPYING, INSTALLING OR USING.
//
// By downloading, copying, installing or using the software you agree to this license.
// If you do not agree to this license, do not download, install,
// copy or use the software.
//
//
// License Agreement
// For Open Source Computer Vision Library
//
// Copyright (C) 2010-2012, Institute Of Software Chinese Academy Of Science, all rights reserved.
// Copyright (C) 2010-2012, Advanced Micro Devices, Inc., all rights reserved.
// Copyright (C) 2010-2012, Multicoreware, Inc., all rights reserved.
// Third party copyrights are property of their respective owners.
//
// Redistribution and use in source and binary forms, with or without modification,
// are permitted provided that the following conditions are met:
//
// * Redistribution's of source code must retain the above copyright notice,
// this list of conditions and the following disclaimer.
//
// * Redistribution's 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.
//
// * The name of the copyright holders may not 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 Intel Corporation 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.
//
//M*/
#include "test_precomp.hpp"
#include "opencv2/ts/ocl_test.hpp"
#ifdef HAVE_OPENCL
namespace cvtest {
namespace ocl {
/////////////////////////////////////////////////////////////////////////////////////////////////
// sepFilter2D
PARAM_TEST_CASE(SepFilter2D, MatDepth, Channels, BorderType, bool, bool)
{
static const int kernelMinSize = 2;
static const int kernelMaxSize = 10;
int type;
Point anchor;
int borderType;
bool useRoi;
Mat kernelX, kernelY;
TEST_DECLARE_INPUT_PARAMETER(src)
TEST_DECLARE_OUTPUT_PARAMETER(dst)
virtual void SetUp()
{
type = CV_MAKE_TYPE(GET_PARAM(0), GET_PARAM(1));
borderType = GET_PARAM(2) | (GET_PARAM(3) ? BORDER_ISOLATED : 0);
useRoi = GET_PARAM(4);
}
void random_roi()
{
Size ksize = randomSize(kernelMinSize, kernelMaxSize);
if (1 != (ksize.width % 2))
ksize.width++;
if (1 != (ksize.height % 2))
ksize.height++;
Mat temp = randomMat(Size(ksize.width, 1), CV_MAKE_TYPE(CV_32F, 1), -MAX_VALUE, MAX_VALUE);
cv::normalize(temp, kernelX, 1.0, 0.0, NORM_L1);
temp = randomMat(Size(1, ksize.height), CV_MAKE_TYPE(CV_32F, 1), -MAX_VALUE, MAX_VALUE);
cv::normalize(temp, kernelY, 1.0, 0.0, NORM_L1);
Size roiSize = randomSize(ksize.width, MAX_VALUE, ksize.height, MAX_VALUE);
int rest = roiSize.width % 4;
if (0 != rest)
roiSize.width += (4 - rest);
Border srcBorder = randomBorder(0, useRoi ? MAX_VALUE : 0);
rest = srcBorder.lef % 4;
if (0 != rest)
srcBorder.lef += (4 - rest);
rest = srcBorder.rig % 4;
if (0 != rest)
srcBorder.rig += (4 - rest);
randomSubMat(src, src_roi, roiSize, srcBorder, type, -MAX_VALUE, MAX_VALUE);
Border dstBorder = randomBorder(0, useRoi ? MAX_VALUE : 0);
randomSubMat(dst, dst_roi, roiSize, dstBorder, type, -MAX_VALUE, MAX_VALUE);
anchor.x = -1;
anchor.y = -1;
UMAT_UPLOAD_INPUT_PARAMETER(src)
UMAT_UPLOAD_OUTPUT_PARAMETER(dst)
}
void Near(double threshold = 0.0)
{
OCL_EXPECT_MATS_NEAR(dst, threshold);
}
};
OCL_TEST_P(SepFilter2D, Mat)
{
for (int j = 0; j < test_loop_times; j++)
{
random_roi();
OCL_OFF(cv::sepFilter2D(src_roi, dst_roi, -1, kernelX, kernelY, anchor, 0.0, borderType));
OCL_ON(cv::sepFilter2D(usrc_roi, udst_roi, -1, kernelX, kernelY, anchor, 0.0, borderType));
Near(2.0);
}
}
OCL_INSTANTIATE_TEST_CASE_P(ImageProc, SepFilter2D,
Combine(
Values(CV_8U, CV_32F),
Values(1, 4),
Values(
(BorderType)BORDER_CONSTANT,
(BorderType)BORDER_REPLICATE,
(BorderType)BORDER_REFLECT,
(BorderType)BORDER_REFLECT_101),
Bool(), // BORDER_ISOLATED
Bool() // ROI
)
);
} } // namespace cvtest::ocl
#endif // HAVE_OPENCL
<commit_msg>Change threshold from 2.0 to 1.0 in the test<commit_after>/*M///////////////////////////////////////////////////////////////////////////////////////
//
// IMPORTANT: READ BEFORE DOWNLOADING, COPYING, INSTALLING OR USING.
//
// By downloading, copying, installing or using the software you agree to this license.
// If you do not agree to this license, do not download, install,
// copy or use the software.
//
//
// License Agreement
// For Open Source Computer Vision Library
//
// Copyright (C) 2010-2012, Institute Of Software Chinese Academy Of Science, all rights reserved.
// Copyright (C) 2010-2012, Advanced Micro Devices, Inc., all rights reserved.
// Copyright (C) 2010-2012, Multicoreware, Inc., all rights reserved.
// Third party copyrights are property of their respective owners.
//
// Redistribution and use in source and binary forms, with or without modification,
// are permitted provided that the following conditions are met:
//
// * Redistribution's of source code must retain the above copyright notice,
// this list of conditions and the following disclaimer.
//
// * Redistribution's 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.
//
// * The name of the copyright holders may not 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 Intel Corporation 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.
//
//M*/
#include "test_precomp.hpp"
#include "opencv2/ts/ocl_test.hpp"
#ifdef HAVE_OPENCL
namespace cvtest {
namespace ocl {
/////////////////////////////////////////////////////////////////////////////////////////////////
// sepFilter2D
PARAM_TEST_CASE(SepFilter2D, MatDepth, Channels, BorderType, bool, bool)
{
static const int kernelMinSize = 2;
static const int kernelMaxSize = 10;
int type;
Point anchor;
int borderType;
bool useRoi;
Mat kernelX, kernelY;
TEST_DECLARE_INPUT_PARAMETER(src)
TEST_DECLARE_OUTPUT_PARAMETER(dst)
virtual void SetUp()
{
type = CV_MAKE_TYPE(GET_PARAM(0), GET_PARAM(1));
borderType = GET_PARAM(2) | (GET_PARAM(3) ? BORDER_ISOLATED : 0);
useRoi = GET_PARAM(4);
}
void random_roi()
{
Size ksize = randomSize(kernelMinSize, kernelMaxSize);
if (1 != (ksize.width % 2))
ksize.width++;
if (1 != (ksize.height % 2))
ksize.height++;
Mat temp = randomMat(Size(ksize.width, 1), CV_MAKE_TYPE(CV_32F, 1), -MAX_VALUE, MAX_VALUE);
cv::normalize(temp, kernelX, 1.0, 0.0, NORM_L1);
temp = randomMat(Size(1, ksize.height), CV_MAKE_TYPE(CV_32F, 1), -MAX_VALUE, MAX_VALUE);
cv::normalize(temp, kernelY, 1.0, 0.0, NORM_L1);
Size roiSize = randomSize(ksize.width, MAX_VALUE, ksize.height, MAX_VALUE);
int rest = roiSize.width % 4;
if (0 != rest)
roiSize.width += (4 - rest);
Border srcBorder = randomBorder(0, useRoi ? MAX_VALUE : 0);
rest = srcBorder.lef % 4;
if (0 != rest)
srcBorder.lef += (4 - rest);
rest = srcBorder.rig % 4;
if (0 != rest)
srcBorder.rig += (4 - rest);
randomSubMat(src, src_roi, roiSize, srcBorder, type, -MAX_VALUE, MAX_VALUE);
Border dstBorder = randomBorder(0, useRoi ? MAX_VALUE : 0);
randomSubMat(dst, dst_roi, roiSize, dstBorder, type, -MAX_VALUE, MAX_VALUE);
anchor.x = -1;
anchor.y = -1;
UMAT_UPLOAD_INPUT_PARAMETER(src)
UMAT_UPLOAD_OUTPUT_PARAMETER(dst)
}
void Near(double threshold = 0.0)
{
OCL_EXPECT_MATS_NEAR(dst, threshold);
}
};
OCL_TEST_P(SepFilter2D, Mat)
{
for (int j = 0; j < test_loop_times; j++)
{
random_roi();
OCL_OFF(cv::sepFilter2D(src_roi, dst_roi, -1, kernelX, kernelY, anchor, 0.0, borderType));
OCL_ON(cv::sepFilter2D(usrc_roi, udst_roi, -1, kernelX, kernelY, anchor, 0.0, borderType));
Near(1.0);
}
}
OCL_INSTANTIATE_TEST_CASE_P(ImageProc, SepFilter2D,
Combine(
Values(CV_8U, CV_32F),
Values(1, 4),
Values(
(BorderType)BORDER_CONSTANT,
(BorderType)BORDER_REPLICATE,
(BorderType)BORDER_REFLECT,
(BorderType)BORDER_REFLECT_101),
Bool(), // BORDER_ISOLATED
Bool() // ROI
)
);
} } // namespace cvtest::ocl
#endif // HAVE_OPENCL
<|endoftext|> |
<commit_before>#include "stdafx.h"
#include "Problem2.h"
/*
https://projecteuler.net/problem=2
Even Fibonacci numbers
Problem 2
Each new term in the Fibonacci sequence is generated by adding the previous two terms. By starting with 1 and 2, the first 10 terms will be:
1, 2, 3, 5, 8, 13, 21, 34, 55, 89, ...
By considering the terms in the Fibonacci sequence whose values do not exceed four million, find the sum of the even-valued terms.
*/
int Problem2::FibonacciSumEven(int range)
{
auto sum = 0;
if (range >= 2)
{
sum += 2;
}
if (range == 8)
{
sum += 8;
}
return sum;
}
int Problem2::Fibonacci(int range)
{
if (range == 2)
{
return 2;
}
return 1;
}<commit_msg>green-commit - Fibonacci_Input3_Returns3<commit_after>#include "stdafx.h"
#include "Problem2.h"
/*
https://projecteuler.net/problem=2
Even Fibonacci numbers
Problem 2
Each new term in the Fibonacci sequence is generated by adding the previous two terms. By starting with 1 and 2, the first 10 terms will be:
1, 2, 3, 5, 8, 13, 21, 34, 55, 89, ...
By considering the terms in the Fibonacci sequence whose values do not exceed four million, find the sum of the even-valued terms.
*/
int Problem2::FibonacciSumEven(int range)
{
auto sum = 0;
if (range >= 2)
{
sum += 2;
}
if (range == 8)
{
sum += 8;
}
return sum;
}
int Problem2::Fibonacci(int range)
{
if (range == 2)
{
return 2;
}
else if (range == 3)
{
return 3;
}
return 1;
}<|endoftext|> |
<commit_before>// This file may be redistributed and modified only under the terms of
// the GNU Lesser General Public License (See COPYING for details).
// Copyright (C) 2005 - 2008 Simon Goodall
#include <sys/types.h>
#include <sys/stat.h>
#include <dirent.h>
#include <errno.h>
#include <stdio.h>
#include "libwfut/IO.h"
#include "libwfut/Encoder.h"
#include "libwfut/platform.h"
#ifdef HAVE_CONFIG_H
#include "config.h"
#endif
namespace WFUT {
static const bool debug = false;
// Create the parent dir of the file.
// TODO Does this work if the parent parent dir does not exist?
static int createParentDirs(const std::string &filename) {
int err = 1;
// TODO This function may not work correctly or be portable.
// Perhaps should only search for '\\' on win32, '/' otherwise
size_t pos = filename.find_last_of("\\/");
// Return if no separator is found, or if it is the first
// character, e.g. /home
if (pos == std::string::npos || pos == 0) return 0;
const std::string &path = filename.substr(0, pos);
if ((err = createParentDirs(path))) {
// There was an error creating the parent path.
return err;
}
// See if the directory already exists
DIR *d = opendir(path.c_str());
if (!d) {
// Make dir as it doesn't exist
err = os_mkdir(path);
} else{
closedir(d);
err = 0;
}
return err;
}
static int copy_file(FILE *fp, const std::string &target_filename) {
if (createParentDirs(target_filename)) {
// Error making dir structure
fprintf(stderr, "There was an error creating the required directory tree for %s.\n", target_filename.c_str());
return 1;
}
FILE *tp = fopen(target_filename.c_str(), "wb");
if (!tp) {
// Error opening file to write
return 1;
}
if (fp) {
rewind(fp);
char buf[1024];
size_t num;
while ((num = fread(buf, sizeof(char), 1024, fp)) != 0) {
fwrite(buf, sizeof(char), num, tp);
}
} else {
// No fp? we should only get here if the file was empty
// so all this function will do is create an empty file.
}
fclose(tp);
return 0;
}
// Callback function to write downloaded data to a file.
static size_t write_data(void *buffer, size_t size, size_t nmemb,void *userp) {
assert(userp != NULL);
DataStruct *ds = reinterpret_cast<DataStruct*>(userp);
// Need to create a file in fp is NULL
if (ds->fp == NULL) {
// Open File handle
ds->fp = os_create_tmpfile();
// TODO Check that filehandle is valid
if (ds->fp == NULL) {
fprintf(stderr, "Error opening file for writing\n");
return 0;
}
// Initialise CRC32 value
ds->actual_crc32 = crc32(0L, Z_NULL, 0);
}
assert(ds->fp != NULL);
// Update crc32 value
ds->actual_crc32 = crc32(ds->actual_crc32, reinterpret_cast<Bytef*>(buffer), size * nmemb);
// Write data to file
return fwrite(buffer, size, nmemb, ds->fp);
}
/**
* Set some options that each handle needs
*/
static int setDefaultOpts(CURL *handle) {
curl_easy_setopt(handle, CURLOPT_FOLLOWLOCATION, 1);
curl_easy_setopt(handle, CURLOPT_WRITEFUNCTION, write_data);
curl_easy_setopt(handle, CURLOPT_FAILONERROR, 1);
return 0;
}
int IO::init() {
assert (m_initialised == false);
curl_global_init(CURL_GLOBAL_ALL);
m_mhandle = curl_multi_init();
#ifdef HAVE_CURL_MULTI_PIPELINING
curl_multi_setopt(m_mhandle, CURLMOPT_PIPELINING, 1);
#endif
m_initialised = true;
return 0;
}
int IO::shutdown(){
assert (m_initialised == true);
curl_multi_cleanup(m_mhandle);
m_mhandle = NULL;
while (!m_files.empty()) {
DataStruct *ds = m_files.begin()->second;
if (ds->handle) {
curl_easy_cleanup(ds->handle);
ds->handle = NULL;
}
if (ds->fp) {
fclose(ds->fp);
ds->fp = NULL;
}
delete ds;
m_files.erase(m_files.begin());
}
curl_global_cleanup();
m_initialised = false;
return 0;
}
int IO::downloadFile(const std::string &filename, const std::string &url, uLong expected_crc32) {
DataStruct ds;
ds.fp = NULL;
ds.url = Encoder::encodeURL(url);
ds.filename = filename;
ds.executable = false;
ds.actual_crc32 = crc32(0L, Z_NULL, 0);
ds.expected_crc32 = expected_crc32;
ds.handle = curl_easy_init();
setDefaultOpts(ds.handle);
curl_easy_setopt(ds.handle, CURLOPT_URL, ds.url.c_str());
curl_easy_setopt(ds.handle, CURLOPT_WRITEDATA, &ds);
CURLcode err = curl_easy_perform(ds.handle);
// TODO: Report back the error message
// Either convert code to message
// Or set CURLOPT_ERRORBUFFER using curl_easy_setopt
// to record the message.
int error = 1;
if (err == 0) {
if (copy_file(ds.fp, ds.filename) == 0) {
error = 0;
}
}
if (ds.fp) fclose(ds.fp);
curl_easy_cleanup(ds.handle);
// Zero on success
return error;
}
int IO::downloadFile(FILE *fp, const std::string &url, uLong expected_crc32) {
DataStruct ds;
ds.fp = fp;
ds.url = Encoder::encodeURL(url);
ds.executable = false;
ds.filename = "";
ds.actual_crc32 = crc32(0L, Z_NULL, 0);
ds.expected_crc32 = expected_crc32;
ds.handle = curl_easy_init();
setDefaultOpts(ds.handle);
curl_easy_setopt(ds.handle, CURLOPT_URL, ds.url.c_str());
curl_easy_setopt(ds.handle, CURLOPT_WRITEDATA, &ds);
CURLcode err = curl_easy_perform(ds.handle);
curl_easy_cleanup(ds.handle);
// TODO: Report back the error message
// Either convert code to message
// Or set CURLOPT_ERRORBUFFER using curl_easy_setopt
// to record the message.
// Zero on success
return (err != 0);
}
int IO::queueFile(const std::string &path, const std::string &filename, const std::string &url, uLong expected_crc32, bool executable) {
if (m_files.find(url) != m_files.end()) {
fprintf(stderr, "Error file is already in queue\n");
// Url already in queue
return 1;
}
DataStruct *ds = new DataStruct();
ds->fp = NULL;
ds->url = Encoder::encodeURL(url);
ds->filename = filename;
ds->path = path;
ds->executable = executable;
ds->actual_crc32 = crc32(0L, Z_NULL, 0);
ds->expected_crc32 = expected_crc32;
ds->handle = curl_easy_init();
m_files[ds->url] = ds;
setDefaultOpts(ds->handle);
curl_easy_setopt(ds->handle, CURLOPT_URL, ds->url.c_str());
curl_easy_setopt(ds->handle, CURLOPT_WRITEDATA, ds);
curl_easy_setopt(ds->handle, CURLOPT_PRIVATE, ds);
// Add handle to our queue instead of to curl directly so that
// we can limit the number of connections we make to the server.
m_handles.push_back(ds->handle);
return 0;
}
int IO::poll() {
// Do some work and get number of handles in progress
int num_handles;
curl_multi_perform(m_mhandle, &num_handles);
struct CURLMsg *msg = NULL;
int msgs;
// Get messages back out of CURL
while ((msg = curl_multi_info_read(m_mhandle, &msgs)) != NULL) {
DataStruct *ds = NULL;
int err = curl_easy_getinfo(msg->easy_handle, CURLINFO_PRIVATE, &ds);
if (err != CURLE_OK) {
// Do something on error
fprintf(stderr, "Got some error on curl_easy_getinfo (%d)\n", err);
continue;
}
bool failed = true;
std::string errormsg = "Unknown failure";
switch (msg->msg) {
case CURLMSG_DONE: {
if (msg->data.result == CURLE_OK) {
assert(ds != NULL);
if (ds->expected_crc32 == 0L ||
ds->expected_crc32 == ds->actual_crc32) {
// Download success!
failed = false;
// Copy file to proper location
if (copy_file(ds->fp, ds->path + "/" + ds->filename)) {
errormsg = "Error copying file to target location.\n";
failed = true;
}
// Set executable if required
if (ds->executable) {
os_set_executable(ds->path + "/" + ds->filename);
}
} else {
// CRC32 check failed
failed = true;
errormsg = "CRC32 mismatch";
}
} else {
// Error downloading file
failed = true;
errormsg = "There was an error downloading the requested file: "
+ std::string(curl_easy_strerror(msg->data.result));
}
break;
}
default:
// Something not too good with curl...
failed = true;
errormsg = "There was an unknown error downloading the requested file";
}
if (debug) printf("Removing Handle\n");
// Close handle
curl_multi_remove_handle(m_mhandle, msg->easy_handle);
// Clean up
if (ds) {
if (ds->fp) os_free_tmpfile(ds->fp);
ds->fp = NULL;
if (failed) {
if (debug) printf("Download Failed\n");
DownloadFailed.emit(ds->url, ds->filename, errormsg);
} else {
if (debug) printf("Download Complete\n");
DownloadComplete.emit(ds->url, ds->filename);
}
m_files.erase(m_files.find(ds->url));
curl_easy_cleanup(ds->handle);
delete ds;
}
}
// Spare capacity? Lets queue some more items.
int diff = m_num_to_process - num_handles;
if (diff > 0) {
while (diff--) {
if (!m_handles.empty()) {
// This is where we tell curl about our downloads.
curl_multi_add_handle(m_mhandle, m_handles.front());
m_handles.pop_front();
++num_handles;
}
}
}
return num_handles;
}
/**
* Abort all current and pending downloads.
*/
void IO::abortAll() {
while (!m_files.empty()) {
DataStruct *ds = (m_files.begin())->second;
abortDownload(ds);
delete ds;
m_files.erase(m_files.begin());
}
}
/**
* Abort all current and pending downloads.
*/
void IO::abortDownload(const std::string &filename) {
std::map<std::string, DataStruct*>::iterator I = m_files.find(filename);
if (I != m_files.end()) {
DataStruct *ds = I->second;
abortDownload(ds);
delete ds;
m_files.erase(I);
}
}
void IO::abortDownload(DataStruct *ds) {
if (ds->handle) {
// Find handle in pending list
std::deque<CURL*>::iterator I = std::find(m_handles.begin(), m_handles.end(), ds->handle);
// Not found? Must be currently downloading.
if (I != m_handles.end()) {
m_handles.erase(I);
} else {
curl_multi_remove_handle(m_mhandle, ds->handle);
}
// Clean up curl handle
curl_easy_cleanup(ds->handle);
ds->handle = NULL;
}
// Clean up file pointer
if (ds->fp) {
os_free_tmpfile(ds->fp);
ds->fp = NULL;
}
// Trigger user feedback
DownloadFailed.emit(ds->url, ds->filename, "Aborted");
}
} /* namespace WFUT */
<commit_msg>Fixing build on GCC 4.3.<commit_after>// This file may be redistributed and modified only under the terms of
// the GNU Lesser General Public License (See COPYING for details).
// Copyright (C) 2005 - 2008 Simon Goodall
#include <sys/types.h>
#include <sys/stat.h>
#include <dirent.h>
#include <errno.h>
#include <stdio.h>
#include <algorithm>
#include "libwfut/IO.h"
#include "libwfut/Encoder.h"
#include "libwfut/platform.h"
#ifdef HAVE_CONFIG_H
#include "config.h"
#endif
namespace WFUT {
static const bool debug = false;
// Create the parent dir of the file.
// TODO Does this work if the parent parent dir does not exist?
static int createParentDirs(const std::string &filename) {
int err = 1;
// TODO This function may not work correctly or be portable.
// Perhaps should only search for '\\' on win32, '/' otherwise
size_t pos = filename.find_last_of("\\/");
// Return if no separator is found, or if it is the first
// character, e.g. /home
if (pos == std::string::npos || pos == 0) return 0;
const std::string &path = filename.substr(0, pos);
if ((err = createParentDirs(path))) {
// There was an error creating the parent path.
return err;
}
// See if the directory already exists
DIR *d = opendir(path.c_str());
if (!d) {
// Make dir as it doesn't exist
err = os_mkdir(path);
} else{
closedir(d);
err = 0;
}
return err;
}
static int copy_file(FILE *fp, const std::string &target_filename) {
if (createParentDirs(target_filename)) {
// Error making dir structure
fprintf(stderr, "There was an error creating the required directory tree for %s.\n", target_filename.c_str());
return 1;
}
FILE *tp = fopen(target_filename.c_str(), "wb");
if (!tp) {
// Error opening file to write
return 1;
}
if (fp) {
rewind(fp);
char buf[1024];
size_t num;
while ((num = fread(buf, sizeof(char), 1024, fp)) != 0) {
fwrite(buf, sizeof(char), num, tp);
}
} else {
// No fp? we should only get here if the file was empty
// so all this function will do is create an empty file.
}
fclose(tp);
return 0;
}
// Callback function to write downloaded data to a file.
static size_t write_data(void *buffer, size_t size, size_t nmemb,void *userp) {
assert(userp != NULL);
DataStruct *ds = reinterpret_cast<DataStruct*>(userp);
// Need to create a file in fp is NULL
if (ds->fp == NULL) {
// Open File handle
ds->fp = os_create_tmpfile();
// TODO Check that filehandle is valid
if (ds->fp == NULL) {
fprintf(stderr, "Error opening file for writing\n");
return 0;
}
// Initialise CRC32 value
ds->actual_crc32 = crc32(0L, Z_NULL, 0);
}
assert(ds->fp != NULL);
// Update crc32 value
ds->actual_crc32 = crc32(ds->actual_crc32, reinterpret_cast<Bytef*>(buffer), size * nmemb);
// Write data to file
return fwrite(buffer, size, nmemb, ds->fp);
}
/**
* Set some options that each handle needs
*/
static int setDefaultOpts(CURL *handle) {
curl_easy_setopt(handle, CURLOPT_FOLLOWLOCATION, 1);
curl_easy_setopt(handle, CURLOPT_WRITEFUNCTION, write_data);
curl_easy_setopt(handle, CURLOPT_FAILONERROR, 1);
return 0;
}
int IO::init() {
assert (m_initialised == false);
curl_global_init(CURL_GLOBAL_ALL);
m_mhandle = curl_multi_init();
#ifdef HAVE_CURL_MULTI_PIPELINING
curl_multi_setopt(m_mhandle, CURLMOPT_PIPELINING, 1);
#endif
m_initialised = true;
return 0;
}
int IO::shutdown(){
assert (m_initialised == true);
curl_multi_cleanup(m_mhandle);
m_mhandle = NULL;
while (!m_files.empty()) {
DataStruct *ds = m_files.begin()->second;
if (ds->handle) {
curl_easy_cleanup(ds->handle);
ds->handle = NULL;
}
if (ds->fp) {
fclose(ds->fp);
ds->fp = NULL;
}
delete ds;
m_files.erase(m_files.begin());
}
curl_global_cleanup();
m_initialised = false;
return 0;
}
int IO::downloadFile(const std::string &filename, const std::string &url, uLong expected_crc32) {
DataStruct ds;
ds.fp = NULL;
ds.url = Encoder::encodeURL(url);
ds.filename = filename;
ds.executable = false;
ds.actual_crc32 = crc32(0L, Z_NULL, 0);
ds.expected_crc32 = expected_crc32;
ds.handle = curl_easy_init();
setDefaultOpts(ds.handle);
curl_easy_setopt(ds.handle, CURLOPT_URL, ds.url.c_str());
curl_easy_setopt(ds.handle, CURLOPT_WRITEDATA, &ds);
CURLcode err = curl_easy_perform(ds.handle);
// TODO: Report back the error message
// Either convert code to message
// Or set CURLOPT_ERRORBUFFER using curl_easy_setopt
// to record the message.
int error = 1;
if (err == 0) {
if (copy_file(ds.fp, ds.filename) == 0) {
error = 0;
}
}
if (ds.fp) fclose(ds.fp);
curl_easy_cleanup(ds.handle);
// Zero on success
return error;
}
int IO::downloadFile(FILE *fp, const std::string &url, uLong expected_crc32) {
DataStruct ds;
ds.fp = fp;
ds.url = Encoder::encodeURL(url);
ds.executable = false;
ds.filename = "";
ds.actual_crc32 = crc32(0L, Z_NULL, 0);
ds.expected_crc32 = expected_crc32;
ds.handle = curl_easy_init();
setDefaultOpts(ds.handle);
curl_easy_setopt(ds.handle, CURLOPT_URL, ds.url.c_str());
curl_easy_setopt(ds.handle, CURLOPT_WRITEDATA, &ds);
CURLcode err = curl_easy_perform(ds.handle);
curl_easy_cleanup(ds.handle);
// TODO: Report back the error message
// Either convert code to message
// Or set CURLOPT_ERRORBUFFER using curl_easy_setopt
// to record the message.
// Zero on success
return (err != 0);
}
int IO::queueFile(const std::string &path, const std::string &filename, const std::string &url, uLong expected_crc32, bool executable) {
if (m_files.find(url) != m_files.end()) {
fprintf(stderr, "Error file is already in queue\n");
// Url already in queue
return 1;
}
DataStruct *ds = new DataStruct();
ds->fp = NULL;
ds->url = Encoder::encodeURL(url);
ds->filename = filename;
ds->path = path;
ds->executable = executable;
ds->actual_crc32 = crc32(0L, Z_NULL, 0);
ds->expected_crc32 = expected_crc32;
ds->handle = curl_easy_init();
m_files[ds->url] = ds;
setDefaultOpts(ds->handle);
curl_easy_setopt(ds->handle, CURLOPT_URL, ds->url.c_str());
curl_easy_setopt(ds->handle, CURLOPT_WRITEDATA, ds);
curl_easy_setopt(ds->handle, CURLOPT_PRIVATE, ds);
// Add handle to our queue instead of to curl directly so that
// we can limit the number of connections we make to the server.
m_handles.push_back(ds->handle);
return 0;
}
int IO::poll() {
// Do some work and get number of handles in progress
int num_handles;
curl_multi_perform(m_mhandle, &num_handles);
struct CURLMsg *msg = NULL;
int msgs;
// Get messages back out of CURL
while ((msg = curl_multi_info_read(m_mhandle, &msgs)) != NULL) {
DataStruct *ds = NULL;
int err = curl_easy_getinfo(msg->easy_handle, CURLINFO_PRIVATE, &ds);
if (err != CURLE_OK) {
// Do something on error
fprintf(stderr, "Got some error on curl_easy_getinfo (%d)\n", err);
continue;
}
bool failed = true;
std::string errormsg = "Unknown failure";
switch (msg->msg) {
case CURLMSG_DONE: {
if (msg->data.result == CURLE_OK) {
assert(ds != NULL);
if (ds->expected_crc32 == 0L ||
ds->expected_crc32 == ds->actual_crc32) {
// Download success!
failed = false;
// Copy file to proper location
if (copy_file(ds->fp, ds->path + "/" + ds->filename)) {
errormsg = "Error copying file to target location.\n";
failed = true;
}
// Set executable if required
if (ds->executable) {
os_set_executable(ds->path + "/" + ds->filename);
}
} else {
// CRC32 check failed
failed = true;
errormsg = "CRC32 mismatch";
}
} else {
// Error downloading file
failed = true;
errormsg = "There was an error downloading the requested file: "
+ std::string(curl_easy_strerror(msg->data.result));
}
break;
}
default:
// Something not too good with curl...
failed = true;
errormsg = "There was an unknown error downloading the requested file";
}
if (debug) printf("Removing Handle\n");
// Close handle
curl_multi_remove_handle(m_mhandle, msg->easy_handle);
// Clean up
if (ds) {
if (ds->fp) os_free_tmpfile(ds->fp);
ds->fp = NULL;
if (failed) {
if (debug) printf("Download Failed\n");
DownloadFailed.emit(ds->url, ds->filename, errormsg);
} else {
if (debug) printf("Download Complete\n");
DownloadComplete.emit(ds->url, ds->filename);
}
m_files.erase(m_files.find(ds->url));
curl_easy_cleanup(ds->handle);
delete ds;
}
}
// Spare capacity? Lets queue some more items.
int diff = m_num_to_process - num_handles;
if (diff > 0) {
while (diff--) {
if (!m_handles.empty()) {
// This is where we tell curl about our downloads.
curl_multi_add_handle(m_mhandle, m_handles.front());
m_handles.pop_front();
++num_handles;
}
}
}
return num_handles;
}
/**
* Abort all current and pending downloads.
*/
void IO::abortAll() {
while (!m_files.empty()) {
DataStruct *ds = (m_files.begin())->second;
abortDownload(ds);
delete ds;
m_files.erase(m_files.begin());
}
}
/**
* Abort all current and pending downloads.
*/
void IO::abortDownload(const std::string &filename) {
std::map<std::string, DataStruct*>::iterator I = m_files.find(filename);
if (I != m_files.end()) {
DataStruct *ds = I->second;
abortDownload(ds);
delete ds;
m_files.erase(I);
}
}
void IO::abortDownload(DataStruct *ds) {
if (ds->handle) {
// Find handle in pending list
std::deque<CURL*>::iterator I = std::find(m_handles.begin(), m_handles.end(), ds->handle);
// Not found? Must be currently downloading.
if (I != m_handles.end()) {
m_handles.erase(I);
} else {
curl_multi_remove_handle(m_mhandle, ds->handle);
}
// Clean up curl handle
curl_easy_cleanup(ds->handle);
ds->handle = NULL;
}
// Clean up file pointer
if (ds->fp) {
os_free_tmpfile(ds->fp);
ds->fp = NULL;
}
// Trigger user feedback
DownloadFailed.emit(ds->url, ds->filename, "Aborted");
}
} /* namespace WFUT */
<|endoftext|> |
<commit_before>#include <Dusk/Dusk.hpp>
#include <Dusk/Log.hpp>
#include <Dusk/Module.hpp>
#include <Python/PyDusk.hpp>
#include <Python.h>
#include <frameobject.h>
#if defined(_WIN32)
#include <Windows.h>
#include <conio.h>
#else
#include <termios.h>
#include <unistd.h>
#endif // defined(_WIN32)
#include <string>
#include <vector>
#include <cstdio>
namespace Dusk {
DUSK_CORE_API
void Initialize(int argc, char ** argv) {
PyImport_AppendInittab("Dusk", PyInit_Dusk);
wchar_t *program = Py_DecodeLocale(argv[0], NULL);
if (program) {
Py_SetProgramName(program);
}
PyMem_RawFree(program);
Py_Initialize();
PyImport_ImportModule("Dusk");
DuskLogVerbose("Dusk Version: %s", GetVersion().GetString());
DuskLogVerbose("Application Name: %s", GetApplicationName());
DuskLogVerbose("Application Version: %s", GetApplicationVersion().GetString());
}
DUSK_CORE_API
void Terminate() {
Py_Finalize();
FreeModules();
}
static bool _Running = false;
DUSK_CORE_API
void SetRunning(bool running) {
_Running = running;
}
DUSK_CORE_API
bool IsRunning() {
return _Running;
}
DUSK_CORE_API
void RunScriptFile(const std::string& filename) {
FILE * file = fopen(filename.c_str(), "rt");
if (!file) {
exit(1);
}
PyObject * pyMain = PyImport_AddModule("__main__");
PyObject * pyMainDict = PyModule_GetDict(pyMain);
PyObject * pyLocalDict = PyDict_New();
PyRun_File(file, filename.c_str(), Py_file_input, pyMainDict, pyLocalDict);
PyCheckError();
fclose(file);
}
DUSK_CORE_API
void RunScriptString(const std::string& code)
{
PyObject * pyMain = PyImport_AddModule("__main__");
PyObject * pyMainDict = PyModule_GetDict(pyMain);
PyObject * pyLocalDict = PyDict_New();
PyRun_String(code.c_str(), Py_single_input, pyMainDict, pyLocalDict);
PyCheckError();
}
static PyObject * _PyScriptConsoleLocals = NULL;
static std::vector<std::string> _ScriptConsoleHistory;
static int _ScriptConsoleCursor = 0;
static int _ScriptConsoleHistoryIndex = 0;
bool _ScriptConsoleRunCommand(const std::string&);
void _ScriptConsoleMoveCursorLeft(int);
void _ScriptConsoleMoveCursorRight(int);
void _ScriptConsoleNextCharacter();
#if !defined(_WIN32)
static struct termios _Termios;
#endif
DUSK_CORE_API
void InitScriptConsole()
{
#if defined(_WIN32)
#else
struct termios tmp;
tcgetattr(STDIN_FILENO, &_Termios);
tmp = _Termios;
tmp.c_lflag &= ~(ECHO | ICANON | ISIG | IEXTEN);
tmp.c_cc[VMIN] = 0;
tcsetattr(STDIN_FILENO, TCSANOW, &tmp);
#endif
PyObject * pyMain = PyImport_AddModule("__main__");
PyObject * pyMainDict = PyModule_GetDict(pyMain);
_PyScriptConsoleLocals = PyDict_New();
PyRun_String("import Dusk", Py_single_input, pyMainDict, _PyScriptConsoleLocals);
_ScriptConsoleHistory.push_back(std::string());
_ScriptConsoleHistoryIndex = _ScriptConsoleHistory.size() - 1;
printf(">>> ");
fflush(stdout);
}
DUSK_CORE_API
void TermScriptConsole()
{
Py_XDECREF(_PyScriptConsoleLocals);
#if defined(_WIN32)
#else
tcsetattr(STDIN_FILENO, TCSANOW, &_Termios);
#endif
}
bool _ScriptConsoleRunCommand(const std::string& command)
{
if (command[0] == '#') {
return true;
}
bool whitespace = true;
for (const auto& c : command) {
if (!isspace(c)) {
whitespace = false;
}
}
if (whitespace) {
return false;
}
PyObject * pyMain = PyImport_AddModule("__main__");
PyObject * pyMainDict = PyModule_GetDict(pyMain);
PyObject * result = PyRun_String(command.c_str(), Py_single_input, pyMainDict, _PyScriptConsoleLocals);
if (PyCheckError()) {
return false;
}
else if (result && result != Py_None) {
PyObject * resultRepr = PyObject_Repr(result);
if (resultRepr) {
PyObject * resultStr = PyUnicode_AsEncodedString(resultRepr, "utf-8", "~E~");
printf("%s\n", PyBytes_AS_STRING(resultStr));
Py_XDECREF(resultStr);
Py_XDECREF(resultRepr);
}
Py_XDECREF(result);
}
return true;
}
void _ScriptConsoleMoveCursorLeft(int amount)
{
printf("\033[%dD", amount);
fflush(stdout);
}
void _ScriptConsoleMoveCursorRight(int amount)
{
printf("\033[%dC", amount);
fflush(stdout);
}
void _ScriptConsoleNextCharacter()
{
static bool inEscape = false;
unsigned char c;
if (read(STDIN_FILENO, &c, sizeof(c)) < 0) {
return;
}
if (inEscape) {
if (c == '[' || c == '~') {
return;
}
switch (c) {
case 'A': // up
if (_ScriptConsoleHistoryIndex > 0) {
--_ScriptConsoleHistoryIndex;
if (_ScriptConsoleCursor > 0) {
_ScriptConsoleMoveCursorLeft(_ScriptConsoleCursor);
}
_ScriptConsoleCursor = 0;
printf("\033[K");
fflush(stdout);
const auto& str = _ScriptConsoleHistory[_ScriptConsoleHistoryIndex];
printf("%s", str.c_str());
fflush(stdout);
_ScriptConsoleCursor = str.size();
}
break;
case 'B': // down
if (_ScriptConsoleHistoryIndex < _ScriptConsoleHistory.size() - 1) {
++_ScriptConsoleHistoryIndex;
if (_ScriptConsoleCursor > 0) {
_ScriptConsoleMoveCursorLeft(_ScriptConsoleCursor);
}
_ScriptConsoleCursor = 0;
printf("\033[K");
fflush(stdout);
const auto& str = _ScriptConsoleHistory[_ScriptConsoleHistoryIndex];
printf("%s", str.c_str());
fflush(stdout);
_ScriptConsoleCursor = str.size();
}
break;
case 'C': // right
if (_ScriptConsoleCursor < _ScriptConsoleHistory.back().size()) {
_ScriptConsoleMoveCursorRight(1);
++_ScriptConsoleCursor;
}
break;
case 'D': // left
if (_ScriptConsoleCursor > 0) {
_ScriptConsoleMoveCursorLeft(1);
--_ScriptConsoleCursor;
}
break;
case 'H': // home
if (_ScriptConsoleCursor > 0) {
_ScriptConsoleMoveCursorLeft(_ScriptConsoleCursor);
_ScriptConsoleCursor = 0;
}
break;
case 'F': // end
if (_ScriptConsoleCursor < _ScriptConsoleHistory.back().size()) {
_ScriptConsoleMoveCursorRight(_ScriptConsoleHistory.back().size() - _ScriptConsoleCursor);
_ScriptConsoleCursor = _ScriptConsoleHistory.back().size();
}
break;
}
inEscape = false;
}
else if (c != 9 && iscntrl(c)) {
switch (c) {
case 3: // Ctrl+C
case 4: // Ctrl+D
SetRunning(false);
break;
case 10: // Enter
printf("\n");
fflush(stdout);
if (_ScriptConsoleHistoryIndex < _ScriptConsoleHistory.size() - 1) {
_ScriptConsoleHistory.back() = _ScriptConsoleHistory[_ScriptConsoleHistoryIndex];
}
if (_ScriptConsoleRunCommand(_ScriptConsoleHistory.back())) {
_ScriptConsoleHistory.push_back(std::string());
_ScriptConsoleHistoryIndex = _ScriptConsoleHistory.size() - 1;
}
else {
_ScriptConsoleHistory.back().clear();
}
_ScriptConsoleCursor = 0;
printf(">>> ");
fflush(stdout);
break;
case 27: // Escape
inEscape = true;
break;
case 127: // Backspace
if (_ScriptConsoleCursor > 0) {
printf("\010\033[K");
fflush(stdout);
--_ScriptConsoleCursor;
_ScriptConsoleHistory.back().erase(_ScriptConsoleCursor, 1);
printf("%s", _ScriptConsoleHistory.back().c_str() + _ScriptConsoleCursor);
fflush(stdout);
if (_ScriptConsoleCursor < _ScriptConsoleHistory.back().size()) {
_ScriptConsoleMoveCursorLeft(_ScriptConsoleHistory.back().size() - _ScriptConsoleCursor);
}
}
break;
}
}
else {
putchar(c);
fflush(stdout);
_ScriptConsoleHistory.back().insert(_ScriptConsoleCursor, 1, c);
++_ScriptConsoleCursor;
printf("%s", _ScriptConsoleHistory.back().c_str() + _ScriptConsoleCursor);
fflush(stdout);
if (_ScriptConsoleCursor < _ScriptConsoleHistory.back().size()) {
_ScriptConsoleMoveCursorLeft(_ScriptConsoleHistory.back().size() - _ScriptConsoleCursor);
}
}
}
DUSK_CORE_API
void UpdateScriptConsole()
{
struct timeval tv = { 0L, 0L };
fd_set fds;
FD_ZERO(&fds);
FD_SET(STDIN_FILENO, &fds);
while (select(1, &fds, NULL, NULL, &tv)) {
_ScriptConsoleNextCharacter();
}
}
static std::string _ApplicationName;
DUSK_CORE_API
void SetApplicationName(const std::string& name)
{
_ApplicationName = name;
}
DUSK_CORE_API
std::string GetApplicationName()
{
return _ApplicationName;
}
static Version _ApplicationVersion;
DUSK_CORE_API
void SetApplicationVersion(unsigned major, unsigned minor, unsigned patch)
{
_ApplicationVersion = Version(major, minor, patch);
}
DUSK_CORE_API
void SetApplicationVersion(const Version& version)
{
_ApplicationVersion = version;
}
DUSK_CORE_API
Version GetApplicationVersion()
{
return _ApplicationVersion;
}
}
<commit_msg>Fix: Allow editing history commands<commit_after>#include <Dusk/Dusk.hpp>
#include <Dusk/Log.hpp>
#include <Dusk/Module.hpp>
#include <Python/PyDusk.hpp>
#include <Python.h>
#include <frameobject.h>
#if defined(_WIN32)
#include <Windows.h>
#include <conio.h>
#else
#include <termios.h>
#include <unistd.h>
#endif // defined(_WIN32)
#include <string>
#include <vector>
#include <cstdio>
namespace Dusk {
DUSK_CORE_API
void Initialize(int argc, char ** argv) {
PyImport_AppendInittab("Dusk", PyInit_Dusk);
wchar_t *program = Py_DecodeLocale(argv[0], NULL);
if (program) {
Py_SetProgramName(program);
}
PyMem_RawFree(program);
Py_Initialize();
PyImport_ImportModule("Dusk");
DuskLogVerbose("Dusk Version: %s", GetVersion().GetString());
DuskLogVerbose("Application Name: %s", GetApplicationName());
DuskLogVerbose("Application Version: %s", GetApplicationVersion().GetString());
}
DUSK_CORE_API
void Terminate() {
Py_Finalize();
FreeModules();
}
static bool _Running = false;
DUSK_CORE_API
void SetRunning(bool running) {
_Running = running;
}
DUSK_CORE_API
bool IsRunning() {
return _Running;
}
DUSK_CORE_API
void RunScriptFile(const std::string& filename) {
FILE * file = fopen(filename.c_str(), "rt");
if (!file) {
exit(1);
}
PyObject * pyMain = PyImport_AddModule("__main__");
PyObject * pyMainDict = PyModule_GetDict(pyMain);
PyObject * pyLocalDict = PyDict_New();
PyRun_File(file, filename.c_str(), Py_file_input, pyMainDict, pyLocalDict);
PyCheckError();
fclose(file);
}
DUSK_CORE_API
void RunScriptString(const std::string& code)
{
PyObject * pyMain = PyImport_AddModule("__main__");
PyObject * pyMainDict = PyModule_GetDict(pyMain);
PyObject * pyLocalDict = PyDict_New();
PyRun_String(code.c_str(), Py_single_input, pyMainDict, pyLocalDict);
PyCheckError();
}
static PyObject * _PyScriptConsoleLocals = NULL;
static std::vector<std::string> _ScriptConsoleHistory;
static int _ScriptConsoleCursor = 0;
static int _ScriptConsoleHistoryIndex = 0;
bool _ScriptConsoleRunCommand(const std::string&);
void _ScriptConsoleMoveCursorLeft(int);
void _ScriptConsoleMoveCursorRight(int);
void _ScriptConsoleNextCharacter();
#if !defined(_WIN32)
static struct termios _Termios;
#endif
DUSK_CORE_API
void InitScriptConsole()
{
#if defined(_WIN32)
#else
struct termios tmp;
tcgetattr(STDIN_FILENO, &_Termios);
tmp = _Termios;
tmp.c_lflag &= ~(ECHO | ICANON | ISIG | IEXTEN);
tmp.c_cc[VMIN] = 0;
tcsetattr(STDIN_FILENO, TCSANOW, &tmp);
#endif
PyObject * pyMain = PyImport_AddModule("__main__");
PyObject * pyMainDict = PyModule_GetDict(pyMain);
_PyScriptConsoleLocals = PyDict_New();
PyRun_String("import Dusk", Py_single_input, pyMainDict, _PyScriptConsoleLocals);
_ScriptConsoleHistory.push_back(std::string());
_ScriptConsoleHistoryIndex = _ScriptConsoleHistory.size() - 1;
printf(">>> ");
fflush(stdout);
}
DUSK_CORE_API
void TermScriptConsole()
{
Py_XDECREF(_PyScriptConsoleLocals);
#if defined(_WIN32)
#else
tcsetattr(STDIN_FILENO, TCSANOW, &_Termios);
#endif
}
bool _ScriptConsoleRunCommand(const std::string& command)
{
if (command[0] == '#') {
return true;
}
bool whitespace = true;
for (const auto& c : command) {
if (!isspace(c)) {
whitespace = false;
}
}
if (whitespace) {
return false;
}
PyObject * pyMain = PyImport_AddModule("__main__");
PyObject * pyMainDict = PyModule_GetDict(pyMain);
PyObject * result = PyRun_String(command.c_str(), Py_single_input, pyMainDict, _PyScriptConsoleLocals);
if (PyCheckError()) {
return false;
}
else if (result && result != Py_None) {
PyObject * resultRepr = PyObject_Repr(result);
if (resultRepr) {
PyObject * resultStr = PyUnicode_AsEncodedString(resultRepr, "utf-8", "~E~");
printf("%s\n", PyBytes_AS_STRING(resultStr));
Py_XDECREF(resultStr);
Py_XDECREF(resultRepr);
}
Py_XDECREF(result);
}
return true;
}
void _ScriptConsoleMoveCursorLeft(int amount)
{
printf("\033[%dD", amount);
fflush(stdout);
}
void _ScriptConsoleMoveCursorRight(int amount)
{
printf("\033[%dC", amount);
fflush(stdout);
}
void _ScriptConsoleNextCharacter()
{
static bool inEscape = false;
unsigned char c;
if (read(STDIN_FILENO, &c, sizeof(c)) < 0) {
return;
}
if (inEscape) {
if (c == '[' || c == '~') {
return;
}
switch (c) {
case 'A': // up
if (_ScriptConsoleHistoryIndex > 0) {
--_ScriptConsoleHistoryIndex;
if (_ScriptConsoleCursor > 0) {
_ScriptConsoleMoveCursorLeft(_ScriptConsoleCursor);
}
_ScriptConsoleCursor = 0;
printf("\033[K");
fflush(stdout);
const auto& str = _ScriptConsoleHistory[_ScriptConsoleHistoryIndex];
printf("%s", str.c_str());
fflush(stdout);
_ScriptConsoleCursor = str.size();
}
break;
case 'B': // down
if (_ScriptConsoleHistoryIndex < _ScriptConsoleHistory.size() - 1) {
++_ScriptConsoleHistoryIndex;
if (_ScriptConsoleCursor > 0) {
_ScriptConsoleMoveCursorLeft(_ScriptConsoleCursor);
}
_ScriptConsoleCursor = 0;
printf("\033[K");
fflush(stdout);
const auto& str = _ScriptConsoleHistory[_ScriptConsoleHistoryIndex];
printf("%s", str.c_str());
fflush(stdout);
_ScriptConsoleCursor = str.size();
}
break;
case 'C': // right
if (_ScriptConsoleCursor < _ScriptConsoleHistory.back().size()) {
_ScriptConsoleMoveCursorRight(1);
++_ScriptConsoleCursor;
}
break;
case 'D': // left
if (_ScriptConsoleCursor > 0) {
_ScriptConsoleMoveCursorLeft(1);
--_ScriptConsoleCursor;
}
break;
case 'H': // home
if (_ScriptConsoleCursor > 0) {
_ScriptConsoleMoveCursorLeft(_ScriptConsoleCursor);
_ScriptConsoleCursor = 0;
}
break;
case 'F': // end
if (_ScriptConsoleCursor < _ScriptConsoleHistory.back().size()) {
_ScriptConsoleMoveCursorRight(_ScriptConsoleHistory.back().size() - _ScriptConsoleCursor);
_ScriptConsoleCursor = _ScriptConsoleHistory.back().size();
}
break;
}
inEscape = false;
}
else if (c != 9 && iscntrl(c)) {
switch (c) {
case 3: // Ctrl+C
case 4: // Ctrl+D
SetRunning(false);
break;
case 10: // Enter
printf("\n");
fflush(stdout);
if (_ScriptConsoleHistoryIndex < _ScriptConsoleHistory.size() - 1) {
_ScriptConsoleHistory.back() = _ScriptConsoleHistory[_ScriptConsoleHistoryIndex];
}
if (_ScriptConsoleRunCommand(_ScriptConsoleHistory.back())) {
_ScriptConsoleHistory.push_back(std::string());
_ScriptConsoleHistoryIndex = _ScriptConsoleHistory.size() - 1;
}
else {
_ScriptConsoleHistory.back().clear();
}
_ScriptConsoleCursor = 0;
printf(">>> ");
fflush(stdout);
break;
case 27: // Escape
inEscape = true;
break;
case 127: // Backspace
if (_ScriptConsoleCursor > 0) {
printf("\010\033[K");
fflush(stdout);
if (_ScriptConsoleHistoryIndex < _ScriptConsoleHistory.size() - 1) {
_ScriptConsoleHistory.back() = _ScriptConsoleHistory[_ScriptConsoleHistoryIndex];
_ScriptConsoleHistoryIndex = _ScriptConsoleHistory.size() - 1;
}
--_ScriptConsoleCursor;
_ScriptConsoleHistory.back().erase(_ScriptConsoleCursor, 1);
printf("%s", _ScriptConsoleHistory.back().c_str() + _ScriptConsoleCursor);
fflush(stdout);
if (_ScriptConsoleCursor < _ScriptConsoleHistory.back().size()) {
_ScriptConsoleMoveCursorLeft(_ScriptConsoleHistory.back().size() - _ScriptConsoleCursor);
}
}
break;
}
}
else {
putchar(c);
fflush(stdout);
if (_ScriptConsoleHistoryIndex < _ScriptConsoleHistory.size() - 1) {
_ScriptConsoleHistory.back() = _ScriptConsoleHistory[_ScriptConsoleHistoryIndex];
_ScriptConsoleHistoryIndex = _ScriptConsoleHistory.size() - 1;
}
_ScriptConsoleHistory.back().insert(_ScriptConsoleCursor, 1, c);
++_ScriptConsoleCursor;
printf("%s", _ScriptConsoleHistory.back().c_str() + _ScriptConsoleCursor);
fflush(stdout);
if (_ScriptConsoleCursor < _ScriptConsoleHistory.back().size()) {
_ScriptConsoleMoveCursorLeft(_ScriptConsoleHistory.back().size() - _ScriptConsoleCursor);
}
}
}
DUSK_CORE_API
void UpdateScriptConsole()
{
struct timeval tv = { 0L, 0L };
fd_set fds;
FD_ZERO(&fds);
FD_SET(STDIN_FILENO, &fds);
while (select(1, &fds, NULL, NULL, &tv)) {
_ScriptConsoleNextCharacter();
}
}
static std::string _ApplicationName;
DUSK_CORE_API
void SetApplicationName(const std::string& name)
{
_ApplicationName = name;
}
DUSK_CORE_API
std::string GetApplicationName()
{
return _ApplicationName;
}
static Version _ApplicationVersion;
DUSK_CORE_API
void SetApplicationVersion(unsigned major, unsigned minor, unsigned patch)
{
_ApplicationVersion = Version(major, minor, patch);
}
DUSK_CORE_API
void SetApplicationVersion(const Version& version)
{
_ApplicationVersion = version;
}
DUSK_CORE_API
Version GetApplicationVersion()
{
return _ApplicationVersion;
}
}
<|endoftext|> |
<commit_before>/*
* Distributed under the OSI-approved Apache License, Version 2.0. See
* accompanying file Copyright.txt for details.
*
* gluePyBind11.cpp
*
* Created on: Mar 16, 2017
* Author: William F Godoy godoywf@ornl.gov
*/
#include <stdexcept>
#include <adios2.h>
#include <pybind11/pybind11.h>
#ifdef ADIOS2_HAVE_MPI
#include <mpi4py/mpi4py.h>
#endif
#include "ADIOSPy.h"
#include "EnginePy.h"
#include "IOPy.h"
#include "VariablePy.h"
#include "adiosPyFunctions.h"
#include "adiosPyTypes.h"
#ifdef ADIOS2_HAVE_MPI
adios2::ADIOSPy ADIOSPyInitConfig(const std::string configFile,
adios2::pyObject &object,
const bool debugMode)
{
MPI_Comm *mpiCommPtr = PyMPIComm_Get(object.ptr());
if (import_mpi4py() < 0)
{
throw std::runtime_error("ERROR: could not import mpi4py "
"communicator, in call to ADIOS "
"constructor\n");
}
if (mpiCommPtr == nullptr)
{
throw std::runtime_error("ERROR: mpi4py communicator is null, in call "
"to ADIOS constructor\n");
}
return adios2::ADIOSPy(configFile, *mpiCommPtr, debugMode);
}
adios2::ADIOSPy ADIOSPyInit(adios2::pyObject &object, const bool debugMode)
{
MPI_Comm *mpiCommPtr = PyMPIComm_Get(object.ptr());
if (import_mpi4py() < 0)
{
throw std::runtime_error("ERROR: could not import mpi4py "
"communicator, in call to ADIOS "
"constructor\n");
}
if (mpiCommPtr == nullptr)
{
throw std::runtime_error("ERROR: mpi4py communicator is null, in call "
"to ADIOS constructor\n");
}
return adios2::ADIOSPy(*mpiCommPtr, debugMode);
}
#else
adios2::ADIOSPy ADIOSPyInitConfig(const std::string configFile,
const bool debugMode)
{
return adios2::ADIOSPy(debugMode);
}
adios::ADIOSPy ADIOSPyInit(const bool debugMode)
{
return adios2::ADIOSPy(debugMode);
}
#endif
PYBIND11_PLUGIN(adios2)
{
#ifdef ADIOS2_HAVE_MPI
if (import_mpi4py() < 0)
{
throw std::runtime_error(
"ERROR: mpi4py not loaded correctly\n"); /* Python 2.X */
}
#endif
pybind11::module m("adios2", "ADIOS2 Python bindings using pybind11");
m.attr("DebugON") = true;
m.attr("DebugOFF") = false;
m.attr("ConstantDims") = true;
m.attr("OpenModeWrite") = static_cast<int>(adios2::OpenMode::Write);
m.attr("OpenModeRead") = static_cast<int>(adios2::OpenMode::Read);
m.attr("OpenModeAppend") = static_cast<int>(adios2::OpenMode::Append);
m.attr("OpenModeReadWrite") = static_cast<int>(adios2::OpenMode::ReadWrite);
m.def("ADIOS", &ADIOSPyInit, "Function that creates an ADIOS class object");
m.def("ADIOS", &ADIOSPyInitConfig,
"Function that creates an ADIOS class object using a config file");
pybind11::class_<adios2::ADIOSPy>(m, "ADIOSPy")
.def("DeclareIO", &adios2::ADIOSPy::DeclareIO);
pybind11::class_<adios2::IOPy>(m, "IOPy")
.def("SetEngine", &adios2::IOPy::SetEngine)
.def("SetParameters", &adios2::IOPy::SetParameters)
.def("AddTransport", &adios2::IOPy::AddTransport)
.def("DefineVariable", &adios2::IOPy::DefineVariable,
pybind11::return_value_policy::reference_internal,
pybind11::arg("name"), pybind11::arg("shape") = adios2::pyList(),
pybind11::arg("start") = adios2::pyList(),
pybind11::arg("count") = adios2::pyList(),
pybind11::arg("isConstantDims") = false)
.def("GetVariable", &adios2::IOPy::GetVariable,
pybind11::return_value_policy::reference_internal)
.def("Open", (adios2::EnginePy (adios2::IOPy::*)(const std::string &,
const int)) &
adios2::IOPy::Open);
pybind11::class_<adios2::VariablePy>(m, "VariablePy")
.def("SetDimensions", &adios2::VariablePy::SetDimensions);
pybind11::class_<adios2::EnginePy>(m, "EnginePy")
.def("Write", &adios2::EnginePy::Write)
.def("Advance", &adios2::EnginePy::Advance,
pybind11::arg("timeoutSeconds") = 0.)
.def("Close", &adios2::EnginePy::Close,
pybind11::arg("transportIndex") = -1);
return m.ptr();
}
<commit_msg>Fix leftover adios:: -> adios2:: conversion in python bindings<commit_after>/*
* Distributed under the OSI-approved Apache License, Version 2.0. See
* accompanying file Copyright.txt for details.
*
* gluePyBind11.cpp
*
* Created on: Mar 16, 2017
* Author: William F Godoy godoywf@ornl.gov
*/
#include <stdexcept>
#include <adios2.h>
#include <pybind11/pybind11.h>
#ifdef ADIOS2_HAVE_MPI
#include <mpi4py/mpi4py.h>
#endif
#include "ADIOSPy.h"
#include "EnginePy.h"
#include "IOPy.h"
#include "VariablePy.h"
#include "adiosPyFunctions.h"
#include "adiosPyTypes.h"
#ifdef ADIOS2_HAVE_MPI
adios2::ADIOSPy ADIOSPyInitConfig(const std::string configFile,
adios2::pyObject &object,
const bool debugMode)
{
MPI_Comm *mpiCommPtr = PyMPIComm_Get(object.ptr());
if (import_mpi4py() < 0)
{
throw std::runtime_error("ERROR: could not import mpi4py "
"communicator, in call to ADIOS "
"constructor\n");
}
if (mpiCommPtr == nullptr)
{
throw std::runtime_error("ERROR: mpi4py communicator is null, in call "
"to ADIOS constructor\n");
}
return adios2::ADIOSPy(configFile, *mpiCommPtr, debugMode);
}
adios2::ADIOSPy ADIOSPyInit(adios2::pyObject &object, const bool debugMode)
{
MPI_Comm *mpiCommPtr = PyMPIComm_Get(object.ptr());
if (import_mpi4py() < 0)
{
throw std::runtime_error("ERROR: could not import mpi4py "
"communicator, in call to ADIOS "
"constructor\n");
}
if (mpiCommPtr == nullptr)
{
throw std::runtime_error("ERROR: mpi4py communicator is null, in call "
"to ADIOS constructor\n");
}
return adios2::ADIOSPy(*mpiCommPtr, debugMode);
}
#else
adios2::ADIOSPy ADIOSPyInitConfig(const std::string configFile,
const bool debugMode)
{
return adios2::ADIOSPy(debugMode);
}
adios2::ADIOSPy ADIOSPyInit(const bool debugMode)
{
return adios2::ADIOSPy(debugMode);
}
#endif
PYBIND11_PLUGIN(adios2)
{
#ifdef ADIOS2_HAVE_MPI
if (import_mpi4py() < 0)
{
throw std::runtime_error(
"ERROR: mpi4py not loaded correctly\n"); /* Python 2.X */
}
#endif
pybind11::module m("adios2", "ADIOS2 Python bindings using pybind11");
m.attr("DebugON") = true;
m.attr("DebugOFF") = false;
m.attr("ConstantDims") = true;
m.attr("OpenModeWrite") = static_cast<int>(adios2::OpenMode::Write);
m.attr("OpenModeRead") = static_cast<int>(adios2::OpenMode::Read);
m.attr("OpenModeAppend") = static_cast<int>(adios2::OpenMode::Append);
m.attr("OpenModeReadWrite") = static_cast<int>(adios2::OpenMode::ReadWrite);
m.def("ADIOS", &ADIOSPyInit, "Function that creates an ADIOS class object");
m.def("ADIOS", &ADIOSPyInitConfig,
"Function that creates an ADIOS class object using a config file");
pybind11::class_<adios2::ADIOSPy>(m, "ADIOSPy")
.def("DeclareIO", &adios2::ADIOSPy::DeclareIO);
pybind11::class_<adios2::IOPy>(m, "IOPy")
.def("SetEngine", &adios2::IOPy::SetEngine)
.def("SetParameters", &adios2::IOPy::SetParameters)
.def("AddTransport", &adios2::IOPy::AddTransport)
.def("DefineVariable", &adios2::IOPy::DefineVariable,
pybind11::return_value_policy::reference_internal,
pybind11::arg("name"), pybind11::arg("shape") = adios2::pyList(),
pybind11::arg("start") = adios2::pyList(),
pybind11::arg("count") = adios2::pyList(),
pybind11::arg("isConstantDims") = false)
.def("GetVariable", &adios2::IOPy::GetVariable,
pybind11::return_value_policy::reference_internal)
.def("Open", (adios2::EnginePy (adios2::IOPy::*)(const std::string &,
const int)) &
adios2::IOPy::Open);
pybind11::class_<adios2::VariablePy>(m, "VariablePy")
.def("SetDimensions", &adios2::VariablePy::SetDimensions);
pybind11::class_<adios2::EnginePy>(m, "EnginePy")
.def("Write", &adios2::EnginePy::Write)
.def("Advance", &adios2::EnginePy::Advance,
pybind11::arg("timeoutSeconds") = 0.)
.def("Close", &adios2::EnginePy::Close,
pybind11::arg("transportIndex") = -1);
return m.ptr();
}
<|endoftext|> |
<commit_before>#pragma once
#include <agency/execution_categories.hpp>
#include <agency/detail/tuple.hpp>
#include <utility>
namespace agency
{
namespace detail
{
// execution is nested, just return x
template<class ExecutionCategory1, class ExecutionCategory2, class T>
__AGENCY_ANNOTATION
auto make_tuple_if_not_nested(nested_execution_tag<ExecutionCategory1,ExecutionCategory2>, T&& x)
-> decltype(std::forward<T>(x))
{
return std::forward<T>(x);
}
// execution is not nested, wrap up x in a tuple
template<class ExecutionCategory, class T>
__AGENCY_ANNOTATION
auto make_tuple_if_not_nested(ExecutionCategory, T&& x)
-> decltype(agency::detail::make_tuple(std::forward<T>(x)))
{
return agency::detail::make_tuple(std::forward<T>(x));
}
template<class ExecutionCategory, class T>
__AGENCY_ANNOTATION
auto make_tuple_if_not_nested(T&& x)
-> decltype(make_tuple_if_not_nested(ExecutionCategory(), std::forward<T>(x)))
{
return make_tuple_if_not_nested(ExecutionCategory(), std::forward<T>(x));
}
template<class ExecutionCategory1, class ExecutionCategory2, class T>
__AGENCY_ANNOTATION
auto tie_if_not_nested(nested_execution_tag<ExecutionCategory1,ExecutionCategory2>, T&& x)
-> decltype(std::forward<T>(x))
{
return std::forward<T>(x);
}
template<class ExecutionCategory, class T>
__AGENCY_ANNOTATION
auto tie_if_not_nested(ExecutionCategory, T&& x)
-> decltype(agency::detail::tie(std::forward<T>(x)))
{
return agency::detail::tie(std::forward<T>(x));
}
template<class ExecutionCategory, class T>
__AGENCY_ANNOTATION
auto tie_if_not_nested(T&& x)
-> decltype(tie_if_not_nested(ExecutionCategory(), std::forward<T>(x)))
{
return tie_if_not_nested(ExecutionCategory(), std::forward<T>(x));
}
} // end detail
} // end agency
<commit_msg>Avoid unnecessary perfect forwarding in make_tuple_if_not_nested to avoid a cudafe performance issue.<commit_after>#pragma once
#include <agency/execution_categories.hpp>
#include <agency/detail/tuple.hpp>
#include <utility>
namespace agency
{
namespace detail
{
// execution is nested, just return x
template<class ExecutionCategory1, class ExecutionCategory2, class T>
__AGENCY_ANNOTATION
T make_tuple_if_not_nested(agency::nested_execution_tag<ExecutionCategory1,ExecutionCategory2>, const T& x)
{
return x;
}
// execution is not nested, wrap up x in a tuple
template<class ExecutionCategory, class T>
__AGENCY_ANNOTATION
agency::detail::tuple<T> make_tuple_if_not_nested(ExecutionCategory, const T& x)
{
return agency::detail::make_tuple(x);
}
template<class ExecutionCategory, class T>
__AGENCY_ANNOTATION
auto make_tuple_if_not_nested(const T& x)
-> decltype(agency::detail::make_tuple_if_not_nested(ExecutionCategory(), x))
{
return agency::detail::make_tuple_if_not_nested(ExecutionCategory(), x);
}
template<class ExecutionCategory1, class ExecutionCategory2, class T>
__AGENCY_ANNOTATION
auto tie_if_not_nested(nested_execution_tag<ExecutionCategory1,ExecutionCategory2>, T&& x)
-> decltype(std::forward<T>(x))
{
return std::forward<T>(x);
}
template<class ExecutionCategory, class T>
__AGENCY_ANNOTATION
auto tie_if_not_nested(ExecutionCategory, T&& x)
-> decltype(agency::detail::tie(std::forward<T>(x)))
{
return agency::detail::tie(std::forward<T>(x));
}
template<class ExecutionCategory, class T>
__AGENCY_ANNOTATION
auto tie_if_not_nested(T&& x)
-> decltype(tie_if_not_nested(ExecutionCategory(), std::forward<T>(x)))
{
return tie_if_not_nested(ExecutionCategory(), std::forward<T>(x));
}
} // end detail
} // end agency
<|endoftext|> |
<commit_before>#include <opencv2/core/core.hpp>
#include <opencv2/imgproc/imgproc.hpp>
#include <opencv2/highgui/highgui.hpp>
#include <opencv2/calib3d/calib3d.hpp>
#include <iostream>
using namespace std;
using namespace cv;
void drawQuad(Mat image, Mat points, Scalar color) {
cout << points.at<Point2f>(0,0) << " " << points.at<Point2f>(0,1) << " " << points.at<Point2f>(0,2) << " " << points.at<Point2f>(0,3) << endl;
line(image, points.at<Point2f>(0,0), points.at<Point2f>(0,1), color);
line(image, points.at<Point2f>(0,1), points.at<Point2f>(0,2), color);
line(image, points.at<Point2f>(0,2), points.at<Point2f>(0,3), color);
line(image, points.at<Point2f>(0,3), points.at<Point2f>(0,0), color);
}
int main(int argc, char** argv) {
FileStorage fs("../calibrate/out_camera_data.xml", FileStorage::READ);
Mat intrinsics, distortion;
fs["Camera_Matrix"] >> intrinsics;
fs["Distortion_Coefficients"] >> distortion;
if (intrinsics.rows != 3 || intrinsics.cols != 3 || distortion.rows != 5 || distortion.cols != 1) {
cout << "Run calibration (in ../calibrate/) first!" << endl;
return 1;
}
VideoCapture cap(0);
if(!cap.isOpened()) // check if we succeeded
return -1;
Mat image;
for (;;) {
cap >> image;
Mat grayImage;
cvtColor(image, grayImage, CV_RGB2GRAY);
Mat blurredImage;
blur(grayImage, blurredImage, Size(5, 5));
Mat threshImage;
threshold(blurredImage, threshImage, 128.0, 255.0, THRESH_OTSU);
vector<vector<Point> > contours;
findContours(threshImage, contours, CV_RETR_LIST, CV_CHAIN_APPROX_NONE);
Scalar color(0, 255, 0);
// drawContours(image, contours, -1, color);
vector<Mat> squares;
for (auto contour : contours) {
vector<Point> approx;
approxPolyDP(contour, approx, arcLength(Mat(contour), true)*0.02, true);
if( approx.size() == 4 &&
fabs(contourArea(Mat(approx))) > 1000 &&
isContourConvex(Mat(approx)) )
{
Mat squareMat;
Mat(approx).convertTo(squareMat, CV_32FC3);
squares.push_back(squareMat);
}
}
if (squares.size() > 0) {
vector<Point3f> objectPoints = {Point3f(-1, -1, 0), Point3f(-1, 1, 0), Point3f(1, 1, 0), Point3f(1, -1, 0)};
Mat objectPointsMat(objectPoints);
cout << "objectPointsMat: " << objectPointsMat.rows << ", " << objectPointsMat.cols << endl;
cout << "squares[0]: " << squares[0] << endl;
Mat rvec;
Mat tvec;
solvePnP(objectPointsMat, squares[0], intrinsics, distortion, rvec, tvec);
cout << "rvec = " << rvec << endl;
cout << "tvec = " << tvec << endl;
drawQuad(image, squares[0], color);
}
cv::imshow("image", image);
cv::waitKey(1);
}
return 0;
}
<commit_msg>Draw a red 3D line oriented to marker.<commit_after>#include <opencv2/core/core.hpp>
#include <opencv2/imgproc/imgproc.hpp>
#include <opencv2/highgui/highgui.hpp>
#include <opencv2/calib3d/calib3d.hpp>
#include <iostream>
using namespace std;
using namespace cv;
void drawQuad(Mat image, Mat points, Scalar color) {
// cout << points.at<Point2f>(0,0) << " " << points.at<Point2f>(0,1) << " " << points.at<Point2f>(0,2) << " " << points.at<Point2f>(0,3) << endl;
line(image, points.at<Point2f>(0,0), points.at<Point2f>(0,1), color);
line(image, points.at<Point2f>(0,1), points.at<Point2f>(0,2), color);
line(image, points.at<Point2f>(0,2), points.at<Point2f>(0,3), color);
line(image, points.at<Point2f>(0,3), points.at<Point2f>(0,0), color);
}
int main(int argc, char** argv) {
Scalar red(255, 0, 0);
Scalar green(0, 255, 0);
Scalar blue(0, 0, 255);
FileStorage fs("../calibrate/out_camera_data.xml", FileStorage::READ);
Mat intrinsics, distortion;
fs["Camera_Matrix"] >> intrinsics;
fs["Distortion_Coefficients"] >> distortion;
if (intrinsics.rows != 3 || intrinsics.cols != 3 || distortion.rows != 5 || distortion.cols != 1) {
cout << "Run calibration (in ../calibrate/) first!" << endl;
return 1;
}
VideoCapture cap(0);
if(!cap.isOpened()) // check if we succeeded
return -1;
Mat image;
for (;;) {
cap >> image;
Mat grayImage;
cvtColor(image, grayImage, CV_RGB2GRAY);
Mat blurredImage;
blur(grayImage, blurredImage, Size(5, 5));
Mat threshImage;
threshold(blurredImage, threshImage, 128.0, 255.0, THRESH_OTSU);
vector<vector<Point> > contours;
findContours(threshImage, contours, CV_RETR_LIST, CV_CHAIN_APPROX_NONE);
// drawContours(image, contours, -1, color);
vector<Mat> squares;
for (auto contour : contours) {
vector<Point> approx;
approxPolyDP(contour, approx, arcLength(Mat(contour), true)*0.02, true);
if( approx.size() == 4 &&
fabs(contourArea(Mat(approx))) > 1000 &&
isContourConvex(Mat(approx)) )
{
Mat squareMat;
Mat(approx).convertTo(squareMat, CV_32FC3);
squares.push_back(squareMat);
}
}
if (squares.size() > 0) {
vector<Point3f> objectPoints = {Point3f(-1, -1, 0), Point3f(-1, 1, 0), Point3f(1, 1, 0), Point3f(1, -1, 0)};
Mat objectPointsMat(objectPoints);
cout << "objectPointsMat: " << objectPointsMat.rows << ", " << objectPointsMat.cols << endl;
cout << "squares[0]: " << squares[0] << endl;
Mat rvec;
Mat tvec;
solvePnP(objectPointsMat, squares[0], intrinsics, distortion, rvec, tvec);
cout << "rvec = " << rvec << endl;
cout << "tvec = " << tvec << endl;
drawQuad(image, squares[0], green);
vector<Point3f> line3d = {{0, 0, 0}, {0, 0, 1}};
vector<Point2f> line2d;
projectPoints(line3d, rvec, tvec, intrinsics, distortion, line2d);
cout << "line2d = " << line2d << endl;
line(image, line2d[0], line2d[1], red);
}
cv::imshow("image", image);
cv::waitKey(1);
}
return 0;
}
<|endoftext|> |
<commit_before>/*
Copyright 2013 SINTEF ICT, Applied Mathematics.
*/
#include "PrintCPUBackendASTVisitor.hpp"
#include "ASTNodes.hpp"
#include "SymbolTable.hpp"
#include <iostream>
#include <cctype>
#include <sstream>
namespace
{
const char* cppStartString();
const char* cppEndString();
}
PrintCPUBackendASTVisitor::PrintCPUBackendASTVisitor()
: suppressed_(false),
indent_(1),
sequence_depth_(0)
{
}
PrintCPUBackendASTVisitor::~PrintCPUBackendASTVisitor()
{
}
void PrintCPUBackendASTVisitor::visit(SequenceNode&)
{
if (sequence_depth_ == 0) {
// This is the root node of the program.
std::cout << cppStartString();
endl();
}
++sequence_depth_;
}
void PrintCPUBackendASTVisitor::midVisit(SequenceNode&)
{
}
void PrintCPUBackendASTVisitor::postVisit(SequenceNode&)
{
--sequence_depth_;
if (sequence_depth_ == 0) {
// We are back at the root node. Finish main() function.
std::cout << cppEndString();
// Emit ensureRequirements() function.
std::cout <<
"\n"
"void ensureRequirements(const EquelleRuntimeCPU& er)\n"
"{\n";
for (const std::string& req : requirement_strings_) {
std::cout << " " << req;
}
std::cout <<
"}\n";
}
}
void PrintCPUBackendASTVisitor::visit(NumberNode& node)
{
std::cout.precision(16);
std::cout << "double(" << node.number() << ")";
}
void PrintCPUBackendASTVisitor::visit(StringNode& node)
{
std::cout << node.content();
}
void PrintCPUBackendASTVisitor::visit(TypeNode&)
{
// std::cout << SymbolTable::equelleString(node.type());
}
void PrintCPUBackendASTVisitor::visit(FuncTypeNode&)
{
// std::cout << node.funcType().equelleString();
}
void PrintCPUBackendASTVisitor::visit(BinaryOpNode&)
{
std::cout << '(';
}
void PrintCPUBackendASTVisitor::midVisit(BinaryOpNode& node)
{
char op = ' ';
switch (node.op()) {
case Add:
op = '+';
break;
case Subtract:
op = '-';
break;
case Multiply:
op = '*';
break;
case Divide:
op = '/';
break;
default:
break;
}
std::cout << ' ' << op << ' ';
}
void PrintCPUBackendASTVisitor::postVisit(BinaryOpNode&)
{
std::cout << ')';
}
void PrintCPUBackendASTVisitor::visit(ComparisonOpNode&)
{
std::cout << '(';
}
void PrintCPUBackendASTVisitor::midVisit(ComparisonOpNode& node)
{
std::string op(" ");
switch (node.op()) {
case Less:
op = "<";
break;
case Greater:
op = ">";
break;
case LessEqual:
op = "<=";
break;
case GreaterEqual:
op = ">=";
break;
case Equal:
op = "==";
break;
case NotEqual:
op = "!=";
break;
default:
break;
}
std::cout << ' ' << op << ' ';
}
void PrintCPUBackendASTVisitor::postVisit(ComparisonOpNode&)
{
std::cout << ')';
}
void PrintCPUBackendASTVisitor::visit(NormNode&)
{
std::cout << "er.norm(";
}
void PrintCPUBackendASTVisitor::postVisit(NormNode&)
{
std::cout << ')';
}
void PrintCPUBackendASTVisitor::visit(UnaryNegationNode&)
{
std::cout << '-';
}
void PrintCPUBackendASTVisitor::postVisit(UnaryNegationNode&)
{
}
void PrintCPUBackendASTVisitor::visit(OnNode& node)
{
if (node.isExtend()) {
std::cout << "er.operatorExtend(";
} else {
std::cout << "er.operatorOn(";
}
}
void PrintCPUBackendASTVisitor::midVisit(OnNode& node)
{
// Backend's operatorOn/operatorExtend has three arguments when the left argument
// is a collection, not two. The middle argument (that we will
// write in this method) should be the set that the first argument
// is On. Example:
// a : Collection Of Scalar On InteriorFaces()
// a On AllFaces() ===> er.operatorOn(a, InteriorFaces(), AllFaces()).
std::cout << ", ";
if (node.lefttype().isCollection()) {
const std::string esname = SymbolTable::entitySetName(node.lefttype().gridMapping());
// Now esname can be either a user-created named set or an Equelle built-in
// function call such as AllCells(). If the second, we must transform to
// proper call syntax for the C++ backend.
const char first = esname[0];
const std::string cppterm = std::isupper(first) ?
std::string("er.") + char(std::tolower(first)) + esname.substr(1)
: esname;
std::cout << cppterm;
std::cout << ", ";
}
}
void PrintCPUBackendASTVisitor::postVisit(OnNode&)
{
std::cout << ')';
}
void PrintCPUBackendASTVisitor::visit(TrinaryIfNode&)
{
std::cout << "er.trinaryIf(";
}
void PrintCPUBackendASTVisitor::questionMarkVisit(TrinaryIfNode&)
{
std::cout << ", ";
}
void PrintCPUBackendASTVisitor::colonVisit(TrinaryIfNode&)
{
std::cout << ", ";
}
void PrintCPUBackendASTVisitor::postVisit(TrinaryIfNode&)
{
std::cout << ')';
}
void PrintCPUBackendASTVisitor::visit(VarDeclNode& node)
{
if (node.type().isMutable()) {
std::cout << indent() << cppTypeString(node.type()) << " " << node.name() << ';';
endl();
}
// suppress();
}
void PrintCPUBackendASTVisitor::postVisit(VarDeclNode&)
{
// unsuppress();
}
void PrintCPUBackendASTVisitor::visit(VarAssignNode& node)
{
std::cout << indent();
if (!SymbolTable::variableType(node.name()).isMutable()) {
std::cout << "const " << cppTypeString(node.type()) << " ";
}
std::cout << node.name() << " = ";
}
void PrintCPUBackendASTVisitor::postVisit(VarAssignNode&)
{
std::cout << ';';
endl();
}
void PrintCPUBackendASTVisitor::visit(VarNode& node)
{
if (!suppressed_) {
std::cout << node.name();
}
}
void PrintCPUBackendASTVisitor::visit(FuncRefNode& node)
{
std::cout << node.name();
}
void PrintCPUBackendASTVisitor::visit(JustAnIdentifierNode&)
{
}
void PrintCPUBackendASTVisitor::visit(FuncArgsDeclNode&)
{
std::cout << "{FuncArgsDeclNode::visit()}";
}
void PrintCPUBackendASTVisitor::midVisit(FuncArgsDeclNode&)
{
std::cout << "{FuncArgsDeclNode::midVisit()}";
}
void PrintCPUBackendASTVisitor::postVisit(FuncArgsDeclNode&)
{
std::cout << "{FuncArgsDeclNode::postVisit()}";
}
void PrintCPUBackendASTVisitor::visit(FuncDeclNode&)
{
// std::cout << node.name() << " : ";
}
void PrintCPUBackendASTVisitor::postVisit(FuncDeclNode&)
{
// endl();
}
void PrintCPUBackendASTVisitor::visit(FuncStartNode& node)
{
std::cout << indent() << "auto " << node.name() << " = [&](";
const FunctionType& ft = SymbolTable::getFunction(node.name()).functionType();
const size_t n = ft.arguments().size();
for (int i = 0; i < n; ++i) {
std::cout << "const "
<< cppTypeString(ft.arguments()[i].type())
<< "& " << ft.arguments()[i].name();
if (i < n - 1) {
std::cout << ", ";
}
}
suppress();
++indent_;
}
void PrintCPUBackendASTVisitor::postVisit(FuncStartNode& node)
{
unsuppress();
const FunctionType& ft = SymbolTable::getFunction(node.name()).functionType();
std::cout << ") -> " << cppTypeString(ft.returnType()) << " {";
endl();
}
void PrintCPUBackendASTVisitor::visit(FuncAssignNode&)
{
}
void PrintCPUBackendASTVisitor::postVisit(FuncAssignNode&)
{
--indent_;
std::cout << indent() << "};";
endl();
}
void PrintCPUBackendASTVisitor::visit(FuncArgsNode&)
{
}
void PrintCPUBackendASTVisitor::midVisit(FuncArgsNode&)
{
if (!suppressed_) {
std::cout << ", ";
}
}
void PrintCPUBackendASTVisitor::postVisit(FuncArgsNode&)
{
}
void PrintCPUBackendASTVisitor::visit(ReturnStatementNode&)
{
std::cout << indent() << "return ";
}
void PrintCPUBackendASTVisitor::postVisit(ReturnStatementNode&)
{
std::cout << ';';
endl();
}
void PrintCPUBackendASTVisitor::visit(FuncCallNode& node)
{
const std::string fname = node.name();
const char first = fname[0];
std::string cppname;
if (std::isupper(first)) {
cppname += std::string("er.") + char(std::tolower(first)) + fname.substr(1);
} else {
cppname += fname;
}
std::cout << cppname << '(';
}
void PrintCPUBackendASTVisitor::postVisit(FuncCallNode&)
{
std::cout << ')';
}
void PrintCPUBackendASTVisitor::visit(FuncCallStatementNode&)
{
std::cout << indent();
}
void PrintCPUBackendASTVisitor::postVisit(FuncCallStatementNode&)
{
std::cout << ';';
endl();
}
void PrintCPUBackendASTVisitor::visit(LoopNode& node)
{
BasicType loopvartype = SymbolTable::variableType(node.loopSet()).basicType();
std::cout << indent() << "for (const " << cppTypeString(loopvartype) << "& "
<< node.loopVariable() << " : " << node.loopSet() << ") {";
++indent_;
endl();
}
void PrintCPUBackendASTVisitor::postVisit(LoopNode&)
{
--indent_;
std::cout << indent() << "}";
endl();
}
void PrintCPUBackendASTVisitor::visit(ArrayNode& node)
{
std::cout << cppTypeString(node.type()) << "({{";
}
void PrintCPUBackendASTVisitor::postVisit(ArrayNode&)
{
std::cout << "}})";
}
void PrintCPUBackendASTVisitor::visit(RandomAccessNode& node)
{
if (!node.arrayAccess()) {
// This is Vector access.
std::cout << "CollOfScalar(";
}
}
void PrintCPUBackendASTVisitor::postVisit(RandomAccessNode& node)
{
if (node.arrayAccess()) {
// This is Array access.
std::cout << "[" << node.index() << "]";
} else {
// This is Vector access.
// Add a grid dimension requirement.
std::ostringstream os;
os << "er.ensureGridDimensionMin(" << node.index() + 1 << ");\n";
addRequirementString(os.str());
// Random access op is taking the column of the underlying Eigen array.
std::cout << ".col(" << node.index() << "))";
}
}
void PrintCPUBackendASTVisitor::endl() const
{
std::cout << '\n';
}
std::string PrintCPUBackendASTVisitor::indent() const
{
return std::string(indent_*4, ' ');
}
void PrintCPUBackendASTVisitor::suppress()
{
suppressed_ = true;
}
void PrintCPUBackendASTVisitor::unsuppress()
{
suppressed_ = false;
}
std::string PrintCPUBackendASTVisitor::cppTypeString(const EquelleType& et) const
{
std::string cppstring;
if (et.isArray()) {
cppstring += "std::array<";
}
if (et.isCollection()) {
cppstring += "CollOf";
} else if (et.isSequence()) {
cppstring += "SeqOf";
}
cppstring += basicTypeString(et.basicType());
if (et.isArray()) {
cppstring += ", " + std::to_string(et.arraySize()) + ">";
}
return cppstring;
}
void PrintCPUBackendASTVisitor::addRequirementString(const std::string& req)
{
requirement_strings_.insert(req);
}
namespace
{
const char* cppStartString()
{
return
"\n"
"// This program was created by the Equelle compiler from SINTEF.\n"
"\n"
"#include <opm/core/utility/parameters/ParameterGroup.hpp>\n"
"#include <opm/core/linalg/LinearSolverFactory.hpp>\n"
"#include <opm/core/utility/ErrorMacros.hpp>\n"
"#include <opm/autodiff/AutoDiffBlock.hpp>\n"
"#include <opm/autodiff/AutoDiffHelpers.hpp>\n"
"#include <opm/core/grid.h>\n"
"#include <opm/core/grid/GridManager.hpp>\n"
"#include <algorithm>\n"
"#include <iterator>\n"
"#include <iostream>\n"
"#include <cmath>\n"
"#include <array>\n"
"\n"
"#include \"EquelleRuntimeCPU.hpp\"\n"
"\n"
"void ensureRequirements(const EquelleRuntimeCPU& er);\n"
"\n"
"int main(int argc, char** argv)\n"
"{\n"
" // Get user parameters.\n"
" Opm::parameter::ParameterGroup param(argc, argv, false);\n"
"\n"
" // Create the Equelle runtime.\n"
" EquelleRuntimeCPU er(param);\n"
"\n"
" ensureRequirements(er);\n"
"\n"
" // ============= Generated code starts here ================\n";
}
const char* cppEndString()
{
return "\n"
" // ============= Generated code ends here ================\n"
"\n"
" return 0;\n"
"}\n";
}
}
<commit_msg>Compiler: modify cpp codegen for array and functions.<commit_after>/*
Copyright 2013 SINTEF ICT, Applied Mathematics.
*/
#include "PrintCPUBackendASTVisitor.hpp"
#include "ASTNodes.hpp"
#include "SymbolTable.hpp"
#include <iostream>
#include <cctype>
#include <sstream>
namespace
{
const char* cppStartString();
const char* cppEndString();
}
PrintCPUBackendASTVisitor::PrintCPUBackendASTVisitor()
: suppressed_(false),
indent_(1),
sequence_depth_(0)
{
}
PrintCPUBackendASTVisitor::~PrintCPUBackendASTVisitor()
{
}
void PrintCPUBackendASTVisitor::visit(SequenceNode&)
{
if (sequence_depth_ == 0) {
// This is the root node of the program.
std::cout << cppStartString();
endl();
}
++sequence_depth_;
}
void PrintCPUBackendASTVisitor::midVisit(SequenceNode&)
{
}
void PrintCPUBackendASTVisitor::postVisit(SequenceNode&)
{
--sequence_depth_;
if (sequence_depth_ == 0) {
// We are back at the root node. Finish main() function.
std::cout << cppEndString();
// Emit ensureRequirements() function.
std::cout <<
"\n"
"void ensureRequirements(const EquelleRuntimeCPU& er)\n"
"{\n";
for (const std::string& req : requirement_strings_) {
std::cout << " " << req;
}
std::cout <<
"}\n";
}
}
void PrintCPUBackendASTVisitor::visit(NumberNode& node)
{
std::cout.precision(16);
std::cout << "double(" << node.number() << ")";
}
void PrintCPUBackendASTVisitor::visit(StringNode& node)
{
std::cout << node.content();
}
void PrintCPUBackendASTVisitor::visit(TypeNode&)
{
// std::cout << SymbolTable::equelleString(node.type());
}
void PrintCPUBackendASTVisitor::visit(FuncTypeNode&)
{
// std::cout << node.funcType().equelleString();
}
void PrintCPUBackendASTVisitor::visit(BinaryOpNode&)
{
std::cout << '(';
}
void PrintCPUBackendASTVisitor::midVisit(BinaryOpNode& node)
{
char op = ' ';
switch (node.op()) {
case Add:
op = '+';
break;
case Subtract:
op = '-';
break;
case Multiply:
op = '*';
break;
case Divide:
op = '/';
break;
default:
break;
}
std::cout << ' ' << op << ' ';
}
void PrintCPUBackendASTVisitor::postVisit(BinaryOpNode&)
{
std::cout << ')';
}
void PrintCPUBackendASTVisitor::visit(ComparisonOpNode&)
{
std::cout << '(';
}
void PrintCPUBackendASTVisitor::midVisit(ComparisonOpNode& node)
{
std::string op(" ");
switch (node.op()) {
case Less:
op = "<";
break;
case Greater:
op = ">";
break;
case LessEqual:
op = "<=";
break;
case GreaterEqual:
op = ">=";
break;
case Equal:
op = "==";
break;
case NotEqual:
op = "!=";
break;
default:
break;
}
std::cout << ' ' << op << ' ';
}
void PrintCPUBackendASTVisitor::postVisit(ComparisonOpNode&)
{
std::cout << ')';
}
void PrintCPUBackendASTVisitor::visit(NormNode&)
{
std::cout << "er.norm(";
}
void PrintCPUBackendASTVisitor::postVisit(NormNode&)
{
std::cout << ')';
}
void PrintCPUBackendASTVisitor::visit(UnaryNegationNode&)
{
std::cout << '-';
}
void PrintCPUBackendASTVisitor::postVisit(UnaryNegationNode&)
{
}
void PrintCPUBackendASTVisitor::visit(OnNode& node)
{
if (node.isExtend()) {
std::cout << "er.operatorExtend(";
} else {
std::cout << "er.operatorOn(";
}
}
void PrintCPUBackendASTVisitor::midVisit(OnNode& node)
{
// Backend's operatorOn/operatorExtend has three arguments when the left argument
// is a collection, not two. The middle argument (that we will
// write in this method) should be the set that the first argument
// is On. Example:
// a : Collection Of Scalar On InteriorFaces()
// a On AllFaces() ===> er.operatorOn(a, InteriorFaces(), AllFaces()).
std::cout << ", ";
if (node.lefttype().isCollection()) {
const std::string esname = SymbolTable::entitySetName(node.lefttype().gridMapping());
// Now esname can be either a user-created named set or an Equelle built-in
// function call such as AllCells(). If the second, we must transform to
// proper call syntax for the C++ backend.
const char first = esname[0];
const std::string cppterm = std::isupper(first) ?
std::string("er.") + char(std::tolower(first)) + esname.substr(1)
: esname;
std::cout << cppterm;
std::cout << ", ";
}
}
void PrintCPUBackendASTVisitor::postVisit(OnNode&)
{
std::cout << ')';
}
void PrintCPUBackendASTVisitor::visit(TrinaryIfNode&)
{
std::cout << "er.trinaryIf(";
}
void PrintCPUBackendASTVisitor::questionMarkVisit(TrinaryIfNode&)
{
std::cout << ", ";
}
void PrintCPUBackendASTVisitor::colonVisit(TrinaryIfNode&)
{
std::cout << ", ";
}
void PrintCPUBackendASTVisitor::postVisit(TrinaryIfNode&)
{
std::cout << ')';
}
void PrintCPUBackendASTVisitor::visit(VarDeclNode& node)
{
if (node.type().isMutable()) {
std::cout << indent() << cppTypeString(node.type()) << " " << node.name() << ';';
endl();
}
// suppress();
}
void PrintCPUBackendASTVisitor::postVisit(VarDeclNode&)
{
// unsuppress();
}
void PrintCPUBackendASTVisitor::visit(VarAssignNode& node)
{
std::cout << indent();
if (!SymbolTable::variableType(node.name()).isMutable()) {
std::cout << "const " << cppTypeString(node.type()) << " ";
}
std::cout << node.name() << " = ";
}
void PrintCPUBackendASTVisitor::postVisit(VarAssignNode&)
{
std::cout << ';';
endl();
}
void PrintCPUBackendASTVisitor::visit(VarNode& node)
{
if (!suppressed_) {
std::cout << node.name();
}
}
void PrintCPUBackendASTVisitor::visit(FuncRefNode& node)
{
std::cout << node.name();
}
void PrintCPUBackendASTVisitor::visit(JustAnIdentifierNode&)
{
}
void PrintCPUBackendASTVisitor::visit(FuncArgsDeclNode&)
{
std::cout << "{FuncArgsDeclNode::visit()}";
}
void PrintCPUBackendASTVisitor::midVisit(FuncArgsDeclNode&)
{
std::cout << "{FuncArgsDeclNode::midVisit()}";
}
void PrintCPUBackendASTVisitor::postVisit(FuncArgsDeclNode&)
{
std::cout << "{FuncArgsDeclNode::postVisit()}";
}
void PrintCPUBackendASTVisitor::visit(FuncDeclNode&)
{
// std::cout << node.name() << " : ";
}
void PrintCPUBackendASTVisitor::postVisit(FuncDeclNode&)
{
// endl();
}
void PrintCPUBackendASTVisitor::visit(FuncStartNode& node)
{
// std::cout << indent() << "auto " << node.name() << " = [&](";
const FunctionType& ft = SymbolTable::getFunction(node.name()).functionType();
const size_t n = ft.arguments().size();
std::cout << indent() << "std::function<" << cppTypeString(ft.returnType()) << '(';
for (int i = 0; i < n; ++i) {
std::cout << "const "
<< cppTypeString(ft.arguments()[i].type())
<< "&";
if (i < n - 1) {
std::cout << ", ";
}
}
std::cout << ")> " << node.name() << " = [&](";
for (int i = 0; i < n; ++i) {
std::cout << "const "
<< cppTypeString(ft.arguments()[i].type())
<< "& " << ft.arguments()[i].name();
if (i < n - 1) {
std::cout << ", ";
}
}
suppress();
++indent_;
}
void PrintCPUBackendASTVisitor::postVisit(FuncStartNode& node)
{
unsuppress();
const FunctionType& ft = SymbolTable::getFunction(node.name()).functionType();
std::cout << ") -> " << cppTypeString(ft.returnType()) << " {";
endl();
}
void PrintCPUBackendASTVisitor::visit(FuncAssignNode&)
{
}
void PrintCPUBackendASTVisitor::postVisit(FuncAssignNode&)
{
--indent_;
std::cout << indent() << "};";
endl();
}
void PrintCPUBackendASTVisitor::visit(FuncArgsNode&)
{
}
void PrintCPUBackendASTVisitor::midVisit(FuncArgsNode&)
{
if (!suppressed_) {
std::cout << ", ";
}
}
void PrintCPUBackendASTVisitor::postVisit(FuncArgsNode&)
{
}
void PrintCPUBackendASTVisitor::visit(ReturnStatementNode&)
{
std::cout << indent() << "return ";
}
void PrintCPUBackendASTVisitor::postVisit(ReturnStatementNode&)
{
std::cout << ';';
endl();
}
void PrintCPUBackendASTVisitor::visit(FuncCallNode& node)
{
const std::string fname = node.name();
const char first = fname[0];
std::string cppname;
if (std::isupper(first)) {
cppname += std::string("er.") + char(std::tolower(first)) + fname.substr(1);
} else {
cppname += fname;
}
// Special treatment for the NewtonSolveSystem() function, since it is unable to
// deduce its template parameter <int Num>.
if (fname == "NewtonSolveSystem") {
std::ostringstream extra;
extra << "<" << node.type().arraySize() << ">";
cppname += extra.str();
}
std::cout << cppname << '(';
}
void PrintCPUBackendASTVisitor::postVisit(FuncCallNode&)
{
std::cout << ')';
}
void PrintCPUBackendASTVisitor::visit(FuncCallStatementNode&)
{
std::cout << indent();
}
void PrintCPUBackendASTVisitor::postVisit(FuncCallStatementNode&)
{
std::cout << ';';
endl();
}
void PrintCPUBackendASTVisitor::visit(LoopNode& node)
{
BasicType loopvartype = SymbolTable::variableType(node.loopSet()).basicType();
std::cout << indent() << "for (const " << cppTypeString(loopvartype) << "& "
<< node.loopVariable() << " : " << node.loopSet() << ") {";
++indent_;
endl();
}
void PrintCPUBackendASTVisitor::postVisit(LoopNode&)
{
--indent_;
std::cout << indent() << "}";
endl();
}
void PrintCPUBackendASTVisitor::visit(ArrayNode&)
{
// std::cout << cppTypeString(node.type()) << "({{";
std::cout << "makeArray(";
}
void PrintCPUBackendASTVisitor::postVisit(ArrayNode&)
{
// std::cout << "}})";
std::cout << ")";
}
void PrintCPUBackendASTVisitor::visit(RandomAccessNode& node)
{
if (!node.arrayAccess()) {
// This is Vector access.
std::cout << "CollOfScalar(";
}
}
void PrintCPUBackendASTVisitor::postVisit(RandomAccessNode& node)
{
if (node.arrayAccess()) {
// This is Array access.
std::cout << "[" << node.index() << "]";
} else {
// This is Vector access.
// Add a grid dimension requirement.
std::ostringstream os;
os << "er.ensureGridDimensionMin(" << node.index() + 1 << ");\n";
addRequirementString(os.str());
// Random access op is taking the column of the underlying Eigen array.
std::cout << ".col(" << node.index() << "))";
}
}
void PrintCPUBackendASTVisitor::endl() const
{
std::cout << '\n';
}
std::string PrintCPUBackendASTVisitor::indent() const
{
return std::string(indent_*4, ' ');
}
void PrintCPUBackendASTVisitor::suppress()
{
suppressed_ = true;
}
void PrintCPUBackendASTVisitor::unsuppress()
{
suppressed_ = false;
}
std::string PrintCPUBackendASTVisitor::cppTypeString(const EquelleType& et) const
{
std::string cppstring;
if (et.isArray()) {
cppstring += "std::array<";
}
if (et.isCollection()) {
cppstring += "CollOf";
} else if (et.isSequence()) {
cppstring += "SeqOf";
}
cppstring += basicTypeString(et.basicType());
if (et.isArray()) {
cppstring += ", " + std::to_string(et.arraySize()) + ">";
}
return cppstring;
}
void PrintCPUBackendASTVisitor::addRequirementString(const std::string& req)
{
requirement_strings_.insert(req);
}
namespace
{
const char* cppStartString()
{
return
"\n"
"// This program was created by the Equelle compiler from SINTEF.\n"
"\n"
"#include <opm/core/utility/parameters/ParameterGroup.hpp>\n"
"#include <opm/core/linalg/LinearSolverFactory.hpp>\n"
"#include <opm/core/utility/ErrorMacros.hpp>\n"
"#include <opm/autodiff/AutoDiffBlock.hpp>\n"
"#include <opm/autodiff/AutoDiffHelpers.hpp>\n"
"#include <opm/core/grid.h>\n"
"#include <opm/core/grid/GridManager.hpp>\n"
"#include <algorithm>\n"
"#include <iterator>\n"
"#include <iostream>\n"
"#include <cmath>\n"
"#include <array>\n"
"\n"
"#include \"EquelleRuntimeCPU.hpp\"\n"
"\n"
"void ensureRequirements(const EquelleRuntimeCPU& er);\n"
"\n"
"int main(int argc, char** argv)\n"
"{\n"
" // Get user parameters.\n"
" Opm::parameter::ParameterGroup param(argc, argv, false);\n"
"\n"
" // Create the Equelle runtime.\n"
" EquelleRuntimeCPU er(param);\n"
"\n"
" ensureRequirements(er);\n"
"\n"
" // ============= Generated code starts here ================\n";
}
const char* cppEndString()
{
return "\n"
" // ============= Generated code ends here ================\n"
"\n"
" return 0;\n"
"}\n";
}
}
<|endoftext|> |
<commit_before>/* <Cidr.cpp>
*
* This file is part of the x0 web server project and is released under AGPL-3.
* http://www.xzero.io/
*
* (c) 2009-2014 Christian Parpart <trapni@gmail.com>
*/
#include <x0/Cidr.h>
#include <x0/IPAddress.h>
namespace x0 {
std::string Cidr::str() const
{
char result[INET6_ADDRSTRLEN + 32];
inet_ntop(ipaddr_.family(), ipaddr_.data(), result, sizeof(result));
size_t n = strlen(result);
snprintf(result + n, sizeof(result) - n, "/%zu", prefix_);
return result;
}
bool Cidr::contains(const IPAddress& ipaddr) const
{
if (ipaddr.family() != address().family())
return false;
// IPv4
if (ipaddr.family() == IPAddress::V4) {
uint32_t ip = *(uint32_t*) ipaddr.data();
uint32_t subnet = *(uint32_t*) address().data();
uint32_t match = ip & (0xFFFFFFFF >> (32 - prefix()));
return match == subnet;
}
// IPv6 TODO
return false;
}
bool operator==(const Cidr& a, const Cidr& b)
{
if (&a == &b)
return true;
if (a.address().family() != b.address().family())
return false;
switch (a.address().family()) {
case AF_INET:
case AF_INET6:
return memcmp(a.address().data(), b.address().data(), a.address().size()) == 0 && a.prefix_ == b.prefix_;
default:
return false;
}
return false;
}
bool operator!=(const Cidr& a, const Cidr& b)
{
return !(a == b);
}
} // namespace x0
<commit_msg>[base] Cidr: basic implementation of IPv6 match support<commit_after>/* <Cidr.cpp>
*
* This file is part of the x0 web server project and is released under AGPL-3.
* http://www.xzero.io/
*
* (c) 2009-2014 Christian Parpart <trapni@gmail.com>
*/
#include <x0/Cidr.h>
#include <x0/IPAddress.h>
namespace x0 {
std::string Cidr::str() const
{
char result[INET6_ADDRSTRLEN + 32];
inet_ntop(ipaddr_.family(), ipaddr_.data(), result, sizeof(result));
size_t n = strlen(result);
snprintf(result + n, sizeof(result) - n, "/%zu", prefix_);
return result;
}
bool Cidr::contains(const IPAddress& ipaddr) const
{
if (ipaddr.family() != address().family())
return false;
// IPv4
if (ipaddr.family() == IPAddress::V4) {
uint32_t ip = *(uint32_t*) ipaddr.data();
uint32_t subnet = *(uint32_t*) address().data();
uint32_t match = ip & (0xFFFFFFFF >> (32 - prefix()));
return match == subnet;
}
// IPv6
int bits = prefix();
const uint32_t* words = (const uint32_t*) address().data();
const uint32_t* input = (const uint32_t*) ipaddr.data();
while (bits >= 32) {
uint32_t match = *words & 0xFFFFFFFF;
if (match != *input)
return false;
words++;
input++;
bits -= 32;
}
uint32_t match = *words & 0xFFFFFFFF >> (32 - bits);
if (match != *input)
return false;
return true;
}
bool operator==(const Cidr& a, const Cidr& b)
{
if (&a == &b)
return true;
if (a.address().family() != b.address().family())
return false;
switch (a.address().family()) {
case AF_INET:
case AF_INET6:
return memcmp(a.address().data(), b.address().data(), a.address().size()) == 0 && a.prefix_ == b.prefix_;
default:
return false;
}
return false;
}
bool operator!=(const Cidr& a, const Cidr& b)
{
return !(a == b);
}
} // namespace x0
<|endoftext|> |
<commit_before>/*
* Copyright (c) 2021, Jan de Visser <jan@finiandarcy.com>
*
* SPDX-License-Identifier: GPL-3.0-or-later
*/
#include <algorithm>
#include <cstring>
#include <memory>
#include <jv80/cpu/memory.h>
namespace Obelix::JV80::CPU {
class Block {
public:
explicit Block(size_t size)
: m_size(size)
, m_bytes((size) ? new byte[size] : nullptr)
{
}
~Block()
{
delete[] m_bytes;
}
[[nodiscard]] byte* operator*() const { return m_bytes; }
byte& operator[](size_t ix)
{
assert(m_bytes && ix < m_size);
return m_bytes[ix];
}
byte const& operator[](size_t ix) const
{
assert(m_bytes && ix < m_size);
return m_bytes[ix];
}
void copy(byte const* bytes, size_t size)
{
memcpy(m_bytes, bytes, std::min(m_size, size));
}
void erase()
{
memset(m_bytes, 0, m_size);
}
private:
size_t m_size { 0 };
byte* m_bytes { nullptr };
};
/* ----------------------------------------------------------------------- */
MemoryBank::MemoryBank(word start, word size, bool writable, const byte* image) noexcept
: m_start(start)
, m_size(size)
, m_writable(writable)
{
if ((int(start) + int(size)) > 0xFFFF) {
m_start = m_size = 0x00;
return;
}
m_image = std::make_shared<Block>(size);
if (image) {
m_image->copy(image, size);
} else {
erase();
}
}
SystemError MemoryBank::poke(std::size_t addr, byte value)
{
if (mapped(addr) && writable()) {
(*m_image)[offset(addr)] = value;
return {};
} else {
return SystemErrorCode::ProtectedMemory;
}
}
ErrorOr<byte, SystemErrorCode> MemoryBank::peek(std::size_t addr) const
{
if (mapped(addr)) {
return (*m_image)[offset(addr)];
} else {
return SystemErrorCode::ProtectedMemory;
}
}
bool MemoryBank::operator<(const MemoryBank& other) const
{
return start() < other.start();
}
bool MemoryBank::operator<=(const MemoryBank& other) const
{
return start() < other.start();
}
bool MemoryBank::operator>(const MemoryBank& other) const
{
return start() > other.start();
}
bool MemoryBank::operator>=(const MemoryBank& other) const
{
return start() > other.start();
}
bool MemoryBank::operator==(const MemoryBank& other) const
{
return (start() == other.start()) && (start() || (size() == other.size()));
}
bool MemoryBank::operator!=(const MemoryBank& other) const
{
return (start() != other.start()) || (!start() && (size() != other.size()));
}
std::string MemoryBank::name() const
{
return format("{} {04x}-{04x}", ((writable()) ? "RAM" : "ROM"), start(), end());
}
void MemoryBank::erase()
{
m_image->erase();
}
void MemoryBank::copy(size_t addr, size_t size, const byte* contents)
{
if (fits(addr, size)) {
m_image->copy(contents, size);
}
}
bool MemoryBank::mapped(size_t addr) const
{
return (start() <= addr) && (addr < end());
}
bool MemoryBank::fits(size_t addr, size_t size) const
{
return mapped(addr) && mapped(addr + size);
}
bool MemoryBank::disjointFrom(size_t addr, size_t size) const
{
return ((addr < start()) && ((addr + size) < start())) || (addr >= end());
}
/* ----------------------------------------------------------------------- */
Memory::Memory()
: AddressRegister(ADDR_ID, "M")
, m_banks()
{
}
Memory::Memory(word ramStart, word ramSize, word romStart, word romSize)
: Memory()
{
add(ramStart, ramSize, true);
add(romStart, romSize, false);
}
std::optional<size_t> Memory::findBankForAddress(size_t addr) const
{
for (auto ix = 0; ix < m_banks.size(); ++ix) {
auto& bank = m_banks[ix];
if (bank.mapped(addr))
return ix;
}
return {};
}
std::optional<size_t> Memory::findBankForBlock(size_t addr, size_t size) const
{
for (size_t ix = 0; ix < m_banks.size(); ++ix) {
auto& bank = m_banks[ix];
if (bank.fits(addr, size))
return ix;
}
return {};
}
MemoryBank const& Memory::bank(size_t addr) const
{
auto ix = findBankForAddress(addr);
assert(ix.has_value());
return m_banks[ix.value()];
}
word Memory::start() const
{
return (!m_banks.empty()) ? (*m_banks.begin()).start() : 0xFFFF;
}
bool Memory::disjointFromAll(size_t addr, size_t size) const
{
return std::all_of(m_banks.begin(), m_banks.end(),
[addr, size](auto& bank) { return bank.disjointFrom(addr, size); });
}
void Memory::erase()
{
for (auto& bank : m_banks) {
bank.erase();
}
}
bool Memory::add(word address, word size, bool writable, const byte* contents)
{
auto b = findBankForBlock(address, size);
if (b.has_value()) {
m_banks[b.value()].copy(address, size, contents);
} else if (disjointFromAll(address, size)) {
m_banks.emplace_back(address, size, writable, contents);
sendEvent(EV_CONFIGCHANGED);
} else {
return false;
}
if (contents) {
sendEvent(EV_IMAGELOADED);
}
return true;
}
bool Memory::remove(word addr, word size)
{
auto ret = std::remove_if(m_banks.begin(), m_banks.end(), [addr, size](auto& bank) {
return (bank.start() == addr) && (bank.size() == size);
});
return ret != m_banks.end();
}
bool Memory::initialize(word address, word size, const byte* contents, bool writable)
{
return add(address, size, writable, contents);
}
bool Memory::inRAM(word addr) const
{
auto bank_ix = findBankForAddress(addr);
return bank_ix.has_value() && m_banks[bank_ix.value()].writable();
}
bool Memory::inROM(word addr) const
{
auto bank_ix = findBankForAddress(addr);
return bank_ix.has_value() && !m_banks[bank_ix.value()].writable();
}
bool Memory::isMapped(word addr) const
{
return std::any_of(m_banks.begin(), m_banks.end(), [addr](auto& bank) {
return bank.mapped(addr);
});
}
SystemError Memory::poke(std::size_t addr, byte value)
{
auto bank = findBankForAddress(addr);
if (bank.has_value() && m_banks[bank.value()].writable()) {
return m_banks[bank.value()].poke(addr, value);
} else {
return SystemErrorCode::ProtectedMemory;
}
}
ErrorOr<byte, SystemErrorCode> Memory::peek(std::size_t addr) const
{
auto bank = findBankForAddress(addr);
if (bank.has_value()) {
return m_banks[bank.value()].peek(addr);
} else {
return SystemErrorCode::ProtectedMemory;
}
}
std::string Memory::to_string() const
{
return format("{01x}. M {04x} CONTENTS {01x}. [{02x}]", address(), getValue(),
MEM_ID, (isMapped(getValue()) ? peek(getValue()).value() : 0xFF));
}
SystemError Memory::onRisingClockEdge()
{
if ((!bus()->xdata() || !bus()->xaddr() || (!bus()->io() && (bus()->opflags() & SystemBus::IOOut))) && (bus()->getAddress() == MEM_ID)) {
if (!isMapped(getValue())) {
return SystemErrorCode::ProtectedMemory;
}
bus()->putOnAddrBus(0x00);
bus()->putOnDataBus(peek(getValue()).value());
}
return {};
}
SystemError Memory::onHighClock()
{
if (((!bus()->xdata() || !bus()->xaddr()) && (bus()->putAddress() == MEM_ID)) || (!bus()->io() && (bus()->opflags() & SystemBus::IOIn) && (bus()->getAddress() == MEM_ID))) {
TRY_RETURN(poke(getValue(), bus()->readDataBus()));
sendEvent(EV_CONTENTSCHANGED);
} else if (bus()->putAddress() == ADDR_ID) {
if (!(bus()->xaddr())) {
setValue(((word)bus()->readAddrBus() << 8) | ((word)bus()->readDataBus()));
} else if (!(bus()->xdata())) {
if (!(bus()->opflags() & SystemBus::MSB)) {
setValue((getValue() & 0xFF00) | bus()->readDataBus());
} else {
setValue((getValue() & 0x00FF) | (((word)bus()->readDataBus()) << 8));
}
}
}
return {};
}
}
<commit_msg>Improved error messaging and implemented INC and DEC on MEM register<commit_after>/*
* Copyright (c) 2021, Jan de Visser <jan@finiandarcy.com>
*
* SPDX-License-Identifier: GPL-3.0-or-later
*/
#include <algorithm>
#include <cstring>
#include <memory>
#include <jv80/cpu/memory.h>
namespace Obelix::JV80::CPU {
class Block {
public:
explicit Block(size_t size)
: m_size(size)
, m_bytes((size) ? new byte[size] : nullptr)
{
}
~Block()
{
delete[] m_bytes;
}
[[nodiscard]] byte* operator*() const { return m_bytes; }
byte& operator[](size_t ix)
{
assert(m_bytes && ix < m_size);
return m_bytes[ix];
}
byte const& operator[](size_t ix) const
{
assert(m_bytes && ix < m_size);
return m_bytes[ix];
}
void copy(byte const* bytes, size_t size)
{
memcpy(m_bytes, bytes, std::min(m_size, size));
}
void erase()
{
memset(m_bytes, 0, m_size);
}
private:
size_t m_size { 0 };
byte* m_bytes { nullptr };
};
/* ----------------------------------------------------------------------- */
MemoryBank::MemoryBank(word start, word size, bool writable, const byte* image) noexcept
: m_start(start)
, m_size(size)
, m_writable(writable)
{
if ((int(start) + int(size)) > 0xFFFF) {
m_start = m_size = 0x00;
return;
}
m_image = std::make_shared<Block>(size);
if (image) {
m_image->copy(image, size);
} else {
erase();
}
}
SystemError MemoryBank::poke(std::size_t addr, byte value)
{
if (mapped(addr) && writable()) {
(*m_image)[offset(addr)] = value;
return {};
} else {
return SystemErrorCode::ProtectedMemory;
}
}
ErrorOr<byte, SystemErrorCode> MemoryBank::peek(std::size_t addr) const
{
if (mapped(addr)) {
return (*m_image)[offset(addr)];
} else {
return SystemErrorCode::ProtectedMemory;
}
}
bool MemoryBank::operator<(const MemoryBank& other) const
{
return start() < other.start();
}
bool MemoryBank::operator<=(const MemoryBank& other) const
{
return start() < other.start();
}
bool MemoryBank::operator>(const MemoryBank& other) const
{
return start() > other.start();
}
bool MemoryBank::operator>=(const MemoryBank& other) const
{
return start() > other.start();
}
bool MemoryBank::operator==(const MemoryBank& other) const
{
return (start() == other.start()) && (start() || (size() == other.size()));
}
bool MemoryBank::operator!=(const MemoryBank& other) const
{
return (start() != other.start()) || (!start() && (size() != other.size()));
}
std::string MemoryBank::name() const
{
return format("{} {04x}-{04x}", ((writable()) ? "RAM" : "ROM"), start(), end());
}
void MemoryBank::erase()
{
m_image->erase();
}
void MemoryBank::copy(size_t addr, size_t size, const byte* contents)
{
if (fits(addr, size)) {
m_image->copy(contents, size);
}
}
bool MemoryBank::mapped(size_t addr) const
{
return (start() <= addr) && (addr < end());
}
bool MemoryBank::fits(size_t addr, size_t size) const
{
return mapped(addr) && mapped(addr + size);
}
bool MemoryBank::disjointFrom(size_t addr, size_t size) const
{
return ((addr < start()) && ((addr + size) < start())) || (addr >= end());
}
/* ----------------------------------------------------------------------- */
Memory::Memory()
: AddressRegister(ADDR_ID, "M")
, m_banks()
{
}
Memory::Memory(word ramStart, word ramSize, word romStart, word romSize)
: Memory()
{
add(ramStart, ramSize, true);
add(romStart, romSize, false);
}
std::optional<size_t> Memory::findBankForAddress(size_t addr) const
{
for (auto ix = 0; ix < m_banks.size(); ++ix) {
auto& bank = m_banks[ix];
if (bank.mapped(addr))
return ix;
}
return {};
}
std::optional<size_t> Memory::findBankForBlock(size_t addr, size_t size) const
{
for (size_t ix = 0; ix < m_banks.size(); ++ix) {
auto& bank = m_banks[ix];
if (bank.fits(addr, size))
return ix;
}
return {};
}
MemoryBank const& Memory::bank(size_t addr) const
{
auto ix = findBankForAddress(addr);
assert(ix.has_value());
return m_banks[ix.value()];
}
word Memory::start() const
{
return (!m_banks.empty()) ? (*m_banks.begin()).start() : 0xFFFF;
}
bool Memory::disjointFromAll(size_t addr, size_t size) const
{
return std::all_of(m_banks.begin(), m_banks.end(),
[addr, size](auto& bank) { return bank.disjointFrom(addr, size); });
}
void Memory::erase()
{
for (auto& bank : m_banks) {
bank.erase();
}
}
bool Memory::add(word address, word size, bool writable, const byte* contents)
{
auto b = findBankForBlock(address, size);
if (b.has_value()) {
m_banks[b.value()].copy(address, size, contents);
} else if (disjointFromAll(address, size)) {
m_banks.emplace_back(address, size, writable, contents);
sendEvent(EV_CONFIGCHANGED);
} else {
return false;
}
if (contents) {
sendEvent(EV_IMAGELOADED);
}
return true;
}
bool Memory::remove(word addr, word size)
{
auto ret = std::remove_if(m_banks.begin(), m_banks.end(), [addr, size](auto& bank) {
return (bank.start() == addr) && (bank.size() == size);
});
return ret != m_banks.end();
}
bool Memory::initialize(word address, word size, const byte* contents, bool writable)
{
return add(address, size, writable, contents);
}
bool Memory::inRAM(word addr) const
{
auto bank_ix = findBankForAddress(addr);
return bank_ix.has_value() && m_banks[bank_ix.value()].writable();
}
bool Memory::inROM(word addr) const
{
auto bank_ix = findBankForAddress(addr);
return bank_ix.has_value() && !m_banks[bank_ix.value()].writable();
}
bool Memory::isMapped(word addr) const
{
return std::any_of(m_banks.begin(), m_banks.end(), [addr](auto& bank) {
return bank.mapped(addr);
});
}
SystemError Memory::poke(std::size_t addr, byte value)
{
auto bank_ix = findBankForAddress(addr);
if (!bank_ix.has_value()) {
std::cout << format("poke({04x}, {02x}): Unmapped address.\n", addr, value);
return SystemErrorCode::ProtectedMemory;
}
auto bank = m_banks[bank_ix.value()];
if (!m_banks[bank_ix.value()].writable()) {
std::cout << format("poke({04x}, {02x}): Read-only bank {04x}-{04x}.\n", addr, value, bank.start(), bank.end());
return SystemErrorCode::ProtectedMemory;
}
return bank.poke(addr, value);
}
ErrorOr<byte, SystemErrorCode> Memory::peek(std::size_t addr) const
{
auto bank_ix = findBankForAddress(addr);
if (!bank_ix.has_value()) {
std::cout << format("peek({04x}): Unmapped address.\n", addr);
return SystemErrorCode::ProtectedMemory;
}
return m_banks[bank_ix.value()].peek(addr);
}
std::string Memory::to_string() const
{
return format("{01x}. M {04x} CONTENTS {01x}. [{02x}]", address(), getValue(),
MEM_ID, (isMapped(getValue()) ? peek(getValue()).value() : 0xFF));
}
SystemError Memory::onRisingClockEdge()
{
if ((!bus()->xdata() || !bus()->xaddr() || (!bus()->io() && (bus()->opflags() & SystemBus::IOOut))) && (bus()->getAddress() == MEM_ID)) {
if (!isMapped(getValue())) {
std::cout << format("onRisingClockEdge(): Unmapped address {04x}.\n", getValue());
return SystemErrorCode::ProtectedMemory;
}
bus()->putOnAddrBus(0x00);
bus()->putOnDataBus(peek(getValue()).value());
if (bus()->opflags() & SystemBus::INC) {
setValue(AddressRegister::getValue() + 1);
}
if (bus()->opflags() & SystemBus::DEC) {
setValue(AddressRegister::getValue() - 1);
}
}
return {};
}
SystemError Memory::onHighClock()
{
if (((!bus()->xdata() || !bus()->xaddr()) && (bus()->putAddress() == MEM_ID)) || (!bus()->io() && (bus()->opflags() & SystemBus::IOIn) && (bus()->getAddress() == MEM_ID))) {
TRY_RETURN(poke(getValue(), bus()->readDataBus()));
if (bus()->opflags() & SystemBus::INC) {
setValue(AddressRegister::getValue() + 1);
}
if (bus()->opflags() & SystemBus::DEC) {
setValue(AddressRegister::getValue() - 1);
}
sendEvent(EV_CONTENTSCHANGED);
} else if (bus()->putAddress() == ADDR_ID) {
if (!(bus()->xaddr())) {
setValue(((word)bus()->readAddrBus() << 8) | ((word)bus()->readDataBus()));
} else if (!(bus()->xdata())) {
if (!(bus()->opflags() & SystemBus::MSB)) {
setValue((getValue() & 0xFF00) | bus()->readDataBus());
} else {
setValue((getValue() & 0x00FF) | (((word)bus()->readDataBus()) << 8));
}
}
}
return {};
}
}
<|endoftext|> |
<commit_before>// SimtkAnimationCallback.cpp
//+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
/*
* Copyright (c) 2005, Stanford University. 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 Stanford University 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.
*/
/*
* Author:
*/
//=============================================================================
// INCLUDES
//=============================================================================
#include <OpenSim/Tools/Mtx.h>
#include <OpenSim/Simulation/Model/IntegCallbackSet.h>
#include <OpenSim/Simulation/SIMM/SimmBody.h>
#include <OpenSim/Simulation/SIMM/SimmKinematicsEngine.h>
#include <OpenSim/Simulation/SIMM/SimmModel.h>
#include "SimtkAnimationCallback.h"
//=============================================================================
// STATICS
//=============================================================================
using namespace OpenSim;
bool SimtkAnimationCallback::_busy = false;
//=============================================================================
// CONSTRUCTOR(S) AND DESTRUCTOR
//=============================================================================
//_____________________________________________________________________________
/**
* Destructor.
*/
SimtkAnimationCallback::~SimtkAnimationCallback()
{
delete[] _transforms;
}
//_____________________________________________________________________________
/**
* Default constructor.
*
* Note that this constructor adds the callback to the model. Derived
* classes should not also add themselves to the model.
*
* @param aModel Model to which the callback mthods apply.
*/
SimtkAnimationCallback::SimtkAnimationCallback(Model *aModel) :
IntegCallback(aModel)
{
// NULL
setNull();
// We keep pointer to body's xform. Don't delete them on exit
_transforms = new Transform[_model->getNB()];
static double Orig[3] = { 0.0, 0.0, 0.0 }; // Zero
std::string modelName = _model->getName();
SimmModel *simmModel = dynamic_cast<SimmModel*>(aModel);
if (simmModel)
getTransformsFromKinematicsEngine(simmModel);
_currentTime=0.0;
}
//=============================================================================
// CONSTRUCTION
//=============================================================================
//_____________________________________________________________________________
/**
* Set NULL values for member variables.
*/
void SimtkAnimationCallback::
setNull()
{
setType("SimtkAnimationCallback");
setName("UNKNOWN");
//_transforms.setSize(0);
_currentTime=0.0;
}
//=============================================================================
// GET AND SET
//=============================================================================
//_____________________________________________________________________________
/**
* This method is called from ui code to give user feedback about how far along
* is the simulation
*/
const double SimtkAnimationCallback::
getCurrentTime() const
{
return _currentTime;
}
//=============================================================================
// CALLBACKS
//=============================================================================
//_____________________________________________________________________________
/**
* This method is called after each successful integration time step and is
* intended to be used for conducting analyses, driving animations, etc.
*
* Override this method in derived classes.
*
* @param aXPrev Control values at the previous time step.
* @param aYPrev State values at the previous time step.
* @param aStep Number of integrations steps that have been completed.
* @param aDT Size of the time step that WAS just completed.
* @param aT Current time in the integration.
* @param aX Current control values.
* @param aY Current states.
* @param aClientData General use pointer for sending in client data.
*/
int SimtkAnimationCallback::
step(double *aXPrev,double *aYPrev,int aStep,double aDT,double aT,
double *aX,double *aY,void *aClientData)
{
if(_busy)
return 0;
getMutex(); // Intention is to make sure xforms that are cached are consistent from the same time
_currentTime = aT;
// CHECK STEP INTERVAL
if((aStep% getStepInterval())!=0) {
std::cout << "************WE ARE HERE AFTER ALL!!!!!!!" << std::endl << std::flush;
std::cout << "************" << aStep << " " << getStepInterval() << std::endl << std::flush;
releaseMutex();
return 0;
}
// OpenSim display time
double realTime = aT * _model->getTimeNormConstant();
printf("Callback time = %lf\n",realTime);
// LOOP OVER BODIES
double t[3]; // Translation from sdfast
double dirCos[3][3]; // Direction cosines
SimmModel *simmModel = dynamic_cast<SimmModel*>(_model);
if (simmModel){
getTransformsFromKinematicsEngine(simmModel);
}
else { // SDFast?
//double com[3]; // Center of mass
double Orig[3] = { 0.0, 0.0, 0.0 };
for(int i=0;i<_model->getNB();i++) {
// get position from sdfast
// adjust by com
for(int k=0; k < 3; k++)
Orig[k] = -_offsets[3*i+k];
_model->getPosition(i, Orig, t);
_model->getDirectionCosines(i,dirCos);
for(int j=0; j<3; j++)
for(int k=0; k<j; k++){
double swap=dirCos[j][k];
dirCos[j][k]=dirCos[k][j];
dirCos[k][j]=swap;
}
// Initialize xform to identity
_transforms[i].setPosition(t);
_transforms[i].setRotationSubmatrix(dirCos);
}
}
releaseMutex();
// Create a transform change event and notify observers
/*TransformChangeEvent *xformChangeEvnt = new TransformChangeEvent(*body);
body->notifyObservers(*xformChangeEvnt);
delete xformChangeEvnt;*/
return (0);
}
void SimtkAnimationCallback::getMutex()
{
while(_busy)
;
_busy = true;
return;
}
void SimtkAnimationCallback::releaseMutex()
{
_busy = false;
}
const Transform* SimtkAnimationCallback::getBodyTransform(int index) const
{
return &_transforms[index];
}
/**
* Cache Coms for bodies so that we can get the xform for the bodies from SDFast in one go with
* minimal computation on our side. If displaying a SimmModel for example in IK then offsets are set to 0
*/
void SimtkAnimationCallback::extractOffsets(SimmModel& displayModel)
{
_offsets = new double[displayModel.getNB()*3];
int i;
SimmModel *simmModel = dynamic_cast<SimmModel*>(_model);
if (simmModel){ // Just set offsets to zero we're displaying a SimmModel and Running SimmModel too
for(i=0;i<_model->getNB();i++){
_offsets[i*3]=_offsets[i*3+1]=_offsets[i*3+2]=0.0;
}
return;
}
double bodyCom[3];
for(i=0;i<_model->getNB();i++) {
// TRANSLATION AND ROTATION
Body *body = _model->getBody(i);
std::string bodyName = body->getName();
SimmBody* sBody = displayModel.getBodies().get(bodyName);
if (sBody != 0){
sBody->getMassCenter(bodyCom);
for(int j=0; j<3; j++){
_offsets[3*i+j] = bodyCom[j];
}
std::cout << "Com for body " << bodyName << " at"
<< bodyCom[0] << bodyCom[1] << bodyCom[2] << std::endl;
}
}
static double Orig[3] = { 0.0, 0.0, 0.0 }; // Zero
double t[3]; // Translation from sdfast
double dirCos[3][3]; // Direction cosines
for(int i=0;i<_model->getNB();i++) {
// get position from sdfast
// adjust by com
for(int k=0; k < 3; k++)
Orig[k] = -_offsets[3*i+k];
_model->getPosition(i, Orig, t);
_model->getDirectionCosines(i,dirCos);
// Initialize xform to identity
_transforms[i].setPosition(t);
for(int j=0; j<3; j++)
for(int k=0; k<j; k++){
double swap=dirCos[j][k];
dirCos[j][k]=dirCos[k][j];
dirCos[k][j]=swap;
}
_transforms[i].setRotationSubmatrix(dirCos);
std::cout << "Body at position " << i << "is " <<
_model->getBody(i)->getName() << displayModel.getBodies().get(i)->getName() << std::endl;
}
}
/*------------------------------------------------------------------
* getTransformsFromKinematicsEngine is a utility used to filll the
* _transforms array from a SimmKinematicsEngine
* @param simmModel: The model to use with associated kinematicsEngine
*/
void SimtkAnimationCallback::
getTransformsFromKinematicsEngine(SimmModel* simmModel)
{
SimmBody* gnd = simmModel->getSimmKinematicsEngine().getGroundBodyPtr();
SimmBodySet& bodySet = simmModel->getSimmKinematicsEngine().getBodies();
double dirCos[3][3]; // Direction cosines
for(int i=0;i<_model->getNB();i++) {
// Initialize inside the loop since convert* methods operate in-place.
double stdFrame[3][3] = {{ 1.0, 0.0, 0.0 },
{0., 1., 0.},
{0., 0., 1.}};
double Orig[3] = { 0.0, 0.0, 0.0 };
SimmBody *body = bodySet.get(i);
simmModel->getSimmKinematicsEngine().convertVector(stdFrame[0], body, gnd);
simmModel->getSimmKinematicsEngine().convertVector(stdFrame[1], body, gnd);
simmModel->getSimmKinematicsEngine().convertVector(stdFrame[2], body, gnd);
simmModel->getSimmKinematicsEngine().convertPoint(Orig, body, gnd);
// Assign dirCos
for(int j=0; j <3; j++)
for(int k=0; k <3; k++)
dirCos[j][k]=stdFrame[j][k];
_transforms[i].setRotationSubmatrix(dirCos);
_transforms[i].setPosition(Orig);
}
}
<commit_msg>Trying to replace the dynamic casts... close, but so far unsuccessful.<commit_after>// SimtkAnimationCallback.cpp
//+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
/*
* Copyright (c) 2005, Stanford University. 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 Stanford University 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.
*/
/*
* Author:
*/
//=============================================================================
// INCLUDES
//=============================================================================
#include <OpenSim/Tools/Mtx.h>
#include <OpenSim/Simulation/Model/IntegCallbackSet.h>
#include <OpenSim/Simulation/SIMM/SimmBody.h>
#include <OpenSim/Simulation/SIMM/SimmKinematicsEngine.h>
#include <OpenSim/Simulation/SIMM/SimmModel.h>
#include "SimtkAnimationCallback.h"
using namespace std;
using namespace OpenSim;
//=============================================================================
// STATICS
//=============================================================================
bool SimtkAnimationCallback::_busy = false;
//=============================================================================
// CONSTRUCTOR(S) AND DESTRUCTOR
//=============================================================================
//_____________________________________________________________________________
/**
* Destructor.
*/
SimtkAnimationCallback::~SimtkAnimationCallback()
{
delete[] _transforms;
}
//_____________________________________________________________________________
/**
* Default constructor.
*
* Note that this constructor adds the callback to the model. Derived
* classes should not also add themselves to the model.
*
* @param aModel Model to which the callback mthods apply.
*/
SimtkAnimationCallback::SimtkAnimationCallback(Model *aModel) :
IntegCallback(aModel)
{
cout<<"\n\nCreating new SimtkAnimationCallback...\n";
// NULL
setNull();
cout<<"finished setNull()\n";
// We keep pointer to body's xform. Don't delete them on exit
_transforms = new Transform[_model->getNB()];
cout<<"alocated transforms.\n";
static double Orig[3] = { 0.0, 0.0, 0.0 }; // Zero
std::string modelName = _model->getName();
cout<<"modelName = "<<modelName<<endl;
//SimmModel *simmModel = dynamic_cast<SimmModel*>(aModel);
string type = aModel->getType();
cout<<"finished dynamic cast.\n";
if (type=="SimmModel") {
getTransformsFromKinematicsEngine((SimmModel*)aModel);
cout<<"got transforms from simmModel\n";
}
_currentTime=0.0;
cout<<"set current time to 0.0\n";
cout<<endl<<endl;
}
//=============================================================================
// CONSTRUCTION
//=============================================================================
//_____________________________________________________________________________
/**
* Set NULL values for member variables.
*/
void SimtkAnimationCallback::
setNull()
{
setType("SimtkAnimationCallback");
setName("UNKNOWN");
//_transforms.setSize(0);
_currentTime=0.0;
}
//=============================================================================
// GET AND SET
//=============================================================================
//_____________________________________________________________________________
/**
* This method is called from ui code to give user feedback about how far along
* is the simulation
*/
const double SimtkAnimationCallback::
getCurrentTime() const
{
return _currentTime;
}
//=============================================================================
// CALLBACKS
//=============================================================================
//_____________________________________________________________________________
/**
* This method is called after each successful integration time step and is
* intended to be used for conducting analyses, driving animations, etc.
*
* Override this method in derived classes.
*
* @param aXPrev Control values at the previous time step.
* @param aYPrev State values at the previous time step.
* @param aStep Number of integrations steps that have been completed.
* @param aDT Size of the time step that WAS just completed.
* @param aT Current time in the integration.
* @param aX Current control values.
* @param aY Current states.
* @param aClientData General use pointer for sending in client data.
*/
int SimtkAnimationCallback::
step(double *aXPrev,double *aYPrev,int aStep,double aDT,double aT,
double *aX,double *aY,void *aClientData)
{
if(_busy)
return 0;
getMutex(); // Intention is to make sure xforms that are cached are consistent from the same time
_currentTime = aT;
// CHECK STEP INTERVAL
if((aStep% getStepInterval())!=0) {
std::cout << "************WE ARE HERE AFTER ALL!!!!!!!" << std::endl << std::flush;
std::cout << "************" << aStep << " " << getStepInterval() << std::endl << std::flush;
releaseMutex();
return 0;
}
// OpenSim display time
double realTime = aT * _model->getTimeNormConstant();
printf("Callback time = %lf\n",realTime);
// LOOP OVER BODIES
double t[3]; // Translation from sdfast
double dirCos[3][3]; // Direction cosines
//SimmModel *simmModel = dynamic_cast<SimmModel*>(_model); CLAY- avoiding dynamic cast.
string type = _model->getType();
cout<<"type = "<<type<<endl;
// SimmModel
if(type=="SimmModel"){
getTransformsFromKinematicsEngine((SimmModel*)_model);
// SDFast Model
} else { // SDFast?
//double com[3]; // Center of mass
double Orig[3] = { 0.0, 0.0, 0.0 };
for(int i=0;i<_model->getNB();i++) {
// get position from sdfast
// adjust by com
for(int k=0; k < 3; k++)
Orig[k] = -_offsets[3*i+k];
_model->getPosition(i, Orig, t);
_model->getDirectionCosines(i,dirCos);
for(int j=0; j<3; j++)
for(int k=0; k<j; k++){
double swap=dirCos[j][k];
dirCos[j][k]=dirCos[k][j];
dirCos[k][j]=swap;
}
// Initialize xform to identity
_transforms[i].setPosition(t);
_transforms[i].setRotationSubmatrix(dirCos);
}
}
releaseMutex();
// Create a transform change event and notify observers
/*TransformChangeEvent *xformChangeEvnt = new TransformChangeEvent(*body);
body->notifyObservers(*xformChangeEvnt);
delete xformChangeEvnt;*/
return (0);
}
void SimtkAnimationCallback::getMutex()
{
while(_busy)
;
_busy = true;
return;
}
void SimtkAnimationCallback::releaseMutex()
{
_busy = false;
}
const Transform* SimtkAnimationCallback::getBodyTransform(int index) const
{
return &_transforms[index];
}
/**
* Cache Coms for bodies so that we can get the xform for the bodies from SDFast in one go with
* minimal computation on our side. If displaying a SimmModel for example in IK then offsets are set to 0
*/
void SimtkAnimationCallback::extractOffsets(SimmModel& displayModel)
{
_offsets = new double[displayModel.getNB()*3];
int i;
SimmModel *simmModel = dynamic_cast<SimmModel*>(_model);
if (simmModel){ // Just set offsets to zero we're displaying a SimmModel and Running SimmModel too
for(i=0;i<_model->getNB();i++){
_offsets[i*3]=_offsets[i*3+1]=_offsets[i*3+2]=0.0;
}
return;
}
double bodyCom[3];
for(i=0;i<_model->getNB();i++) {
// TRANSLATION AND ROTATION
Body *body = _model->getBody(i);
std::string bodyName = body->getName();
SimmBody* sBody = displayModel.getBodies().get(bodyName);
if (sBody != 0){
sBody->getMassCenter(bodyCom);
for(int j=0; j<3; j++){
_offsets[3*i+j] = bodyCom[j];
}
std::cout << "Com for body " << bodyName << " at"
<< bodyCom[0] << bodyCom[1] << bodyCom[2] << std::endl;
}
}
static double Orig[3] = { 0.0, 0.0, 0.0 }; // Zero
double t[3]; // Translation from sdfast
double dirCos[3][3]; // Direction cosines
for(int i=0;i<_model->getNB();i++) {
// get position from sdfast
// adjust by com
for(int k=0; k < 3; k++)
Orig[k] = -_offsets[3*i+k];
_model->getPosition(i, Orig, t);
_model->getDirectionCosines(i,dirCos);
// Initialize xform to identity
_transforms[i].setPosition(t);
for(int j=0; j<3; j++)
for(int k=0; k<j; k++){
double swap=dirCos[j][k];
dirCos[j][k]=dirCos[k][j];
dirCos[k][j]=swap;
}
_transforms[i].setRotationSubmatrix(dirCos);
std::cout << "Body at position " << i << "is " <<
_model->getBody(i)->getName() << displayModel.getBodies().get(i)->getName() << std::endl;
}
}
/*------------------------------------------------------------------
* getTransformsFromKinematicsEngine is a utility used to filll the
* _transforms array from a SimmKinematicsEngine
* @param simmModel: The model to use with associated kinematicsEngine
*/
void SimtkAnimationCallback::
getTransformsFromKinematicsEngine(SimmModel* simmModel)
{
SimmBody* gnd = simmModel->getSimmKinematicsEngine().getGroundBodyPtr();
SimmBodySet& bodySet = simmModel->getSimmKinematicsEngine().getBodies();
double dirCos[3][3]; // Direction cosines
for(int i=0;i<_model->getNB();i++) {
// Initialize inside the loop since convert* methods operate in-place.
double stdFrame[3][3] = {{ 1.0, 0.0, 0.0 },
{0., 1., 0.},
{0., 0., 1.}};
double Orig[3] = { 0.0, 0.0, 0.0 };
SimmBody *body = bodySet.get(i);
simmModel->getSimmKinematicsEngine().convertVector(stdFrame[0], body, gnd);
simmModel->getSimmKinematicsEngine().convertVector(stdFrame[1], body, gnd);
simmModel->getSimmKinematicsEngine().convertVector(stdFrame[2], body, gnd);
simmModel->getSimmKinematicsEngine().convertPoint(Orig, body, gnd);
// Assign dirCos
for(int j=0; j <3; j++)
for(int k=0; k <3; k++)
dirCos[j][k]=stdFrame[j][k];
_transforms[i].setRotationSubmatrix(dirCos);
_transforms[i].setPosition(Orig);
}
}
<|endoftext|> |
<commit_before>#include "confignode.hpp"
#include "treeviewmodel.hpp"
using namespace kdb;
ConfigNode::ConfigNode(const QString& name, const QString& path, const Key &key, TreeViewModel *parentModel)
: m_name(name)
, m_path(path)
, m_key(key)
, m_children(new TreeViewModel)
, m_metaData(NULL)
, m_parentModel(parentModel)
, m_isExpanded(false)
, m_isDirty(false)
{
if (m_key && m_key.isString())
m_value = QVariant::fromValue(QString::fromStdString(m_key.getString()));
else if (m_key && m_key.isBinary())
m_value = QVariant::fromValue(QString::fromStdString(m_key.getBinary()));
if(m_key)
{
m_metaData = new TreeViewModel;
populateMetaModel();
}
connect(m_children, SIGNAL(expandNode(bool)), this, SLOT(setIsExpanded(bool)));
connect(this, SIGNAL(showMessage(QString,QString,QString)), parentModel, SLOT(showConfigNodeMessage(QString,QString,QString)));
}
ConfigNode::ConfigNode(const ConfigNode& other)
: QObject()
, m_name(other.m_name)
, m_path(other.m_path)
, m_value(other.m_value)
, m_key(other.m_key.dup())
, m_children(new TreeViewModel)
, m_metaData(NULL)
, m_parentModel(NULL)
, m_isExpanded(other.m_isExpanded)
, m_isDirty(false)
{
if(other.m_children)
{
foreach(ConfigNodePtr node, other.m_children->model())
{
m_children->append(ConfigNodePtr(new ConfigNode(*node)));
}
}
if(other.m_metaData)
{
m_metaData = new TreeViewModel;
foreach(ConfigNodePtr node, other.m_metaData->model())
{
m_metaData->append(ConfigNodePtr(new ConfigNode(*node)));
}
}
connect(m_children, SIGNAL(expandNode(bool)), this, SLOT(setIsExpanded(bool)));
}
ConfigNode::ConfigNode()
: m_children(NULL)
, m_metaData(NULL)
, m_parentModel(NULL)
, m_isExpanded(false)
, m_isDirty(false)
{
//this constructor is used to create metanodes
}
ConfigNode::~ConfigNode()
{
delete m_children;
delete m_metaData;
}
int ConfigNode::getChildCount() const
{
if(m_children)
return m_children->rowCount();
return 0;
}
QString ConfigNode::getName() const
{
return m_name;
}
QString ConfigNode::getPath() const
{
return m_path;
}
QVariant ConfigNode::getValue() const
{
return m_value;
}
void ConfigNode::setName(const QString& name)
{
int index = m_path.lastIndexOf("/");
if(index != -1)
{
m_path.replace(index, m_path.length() - index, "/" + name);
}
if(!m_key)
m_key = Key(m_path.toStdString(), KEY_END);
else
m_key = m_key.dup();
try{
if(m_key.getBaseName().compare(name.toStdString()) != 0)
m_key.setBaseName(name.toStdString());
}
catch(KeyInvalidName const& ex){
emit showMessage(tr("Error"), tr("Could not set name because Keyname \"%1\" is invalid.").arg(name), ex.what());
return;
}
m_name = name;
}
void ConfigNode::setValue(const QVariant& value)
{
if(!m_key)
m_key = Key(m_path.toStdString(), KEY_END);
else
m_key = m_key.dup();
if(m_key.getString().compare(value.toString().toStdString()) != 0){
m_key.setString(value.toString().toStdString());
m_value = value;
}
}
void ConfigNode::setMeta(const QString &name, const QVariant &value)
{
if(!m_key)
m_key = Key(m_path.toStdString(), KEY_END);
else
m_key = m_key.dup();
m_key.setMeta(name.toStdString(), value.toString().toStdString());
m_name = name;
m_value = value;
}
void ConfigNode::setMeta(const QVariantMap &metaData)
{
if(m_metaData)
{
//delete old metadata in key
for(int i = 0; i < m_metaData->model().size(); i++)
{
m_metaData->model().at(i)->deleteMeta(m_metaData->model().at(i)->getName());
}
//delete old metadata in model
m_metaData->clearMetaModel();
}
else
m_metaData = new TreeViewModel;
//create new metadata nodes in model
for(int i = 0; i < metaData.size(); i++)
{
m_metaData->insertMetaRow(i, m_key, m_name);
}
int counter = 0;
//set new metadata
for(QVariantMap::const_iterator iter = metaData.begin(); iter != metaData.end(); iter++)
{
QVariantList tmp;
tmp << iter.key() << iter.value();
m_metaData->setData(m_metaData->index(counter), tmp, TreeViewModel::MetaValueRole);
counter++;
}
}
void ConfigNode::deleteMeta(const QString &name)
{
if(m_key)
m_key.delMeta(name.toStdString());
}
void ConfigNode::accept(Visitor &visitor)
{
visitor.visit(*this);
if(m_children)
{
foreach (ConfigNodePtr node, m_children->model())
node->accept(visitor);
}
}
Key ConfigNode::getKey() const
{
return m_key;
}
int ConfigNode::getChildIndexByName(const QString &name)
{
if(m_children)
{
for(int i = 0; i < m_children->rowCount(); i++)
{
if(m_children->model().at(i)->getName() == name)
return i;
}
}
return -1;
}
TreeViewModel *ConfigNode::getParentModel()
{
return m_parentModel;
}
void ConfigNode::setParentModel(TreeViewModel *parentModel)
{
m_parentModel = parentModel;
}
bool ConfigNode::isExpanded() const
{
return m_isExpanded;
}
bool ConfigNode::isDirty() const
{
return m_isDirty;
}
void ConfigNode::setIsDirty(bool dirty)
{
m_isDirty = dirty;
}
void ConfigNode::setIsExpanded(bool value)
{
m_isExpanded = value;
}
void ConfigNode::populateMetaModel()
{
if (m_key)
{
m_key.rewindMeta();
m_metaData->model().clear();
while (m_key.nextMeta())
{
ConfigNodePtr node(new ConfigNode());
node->setName(QString::fromStdString(m_key.getName()));
node->setKey(m_key);
node->setMeta(QString::fromStdString(m_key.currentMeta().getName()), QVariant::fromValue(QString::fromStdString(m_key.currentMeta().getString())));
m_metaData->model().append(node);
}
}
}
void ConfigNode::setKey(Key key)
{
m_key = key;
}
void ConfigNode::setKeyName(const QString &name)
{
if(m_key)
{
try
{
m_key.setName(name.toStdString());
}
catch(KeyInvalidName ex)
{
emit showMessage(tr("Error"), tr("Could not set name because Keyname \"%1\" is invalid.").arg(name), ex.what());
return;
}
}
}
void ConfigNode::appendChild(ConfigNodePtr node)
{
m_children->append(node);
}
bool ConfigNode::hasChild(const QString& name) const
{
if(m_children)
{
foreach (ConfigNodePtr node, m_children->model())
{
if (node->getName() == name)
{
return true;
}
}
}
return false;
}
TreeViewModel* ConfigNode::getChildren() const
{
return m_children;
}
TreeViewModel* ConfigNode::getMetaKeys() const
{
return m_metaData;
}
ConfigNodePtr ConfigNode::getChildByName(QString& name) const
{
if(m_children)
{
foreach (ConfigNodePtr node, m_children->model())
{
if (node->getName() == name)
{
return node;
}
}
}
return ConfigNodePtr();
}
ConfigNodePtr ConfigNode::getChildByIndex(int index) const
{
if(m_children)
{
if (index >= 0 && index < m_children->model().length())
return m_children->model().at(index);
}
return ConfigNodePtr();
}
void ConfigNode::setPath(const QString &path)
{
m_path = path;
setKeyName(path);
if(m_children)
{
foreach(ConfigNodePtr node, m_children->model()){
node->setPath(m_path + "/" + node->getName());
}
}
}
bool ConfigNode::childrenHaveNoChildren() const
{
int childcount = 0;
if(m_children)
{
foreach (ConfigNodePtr node, m_children->model())
{
childcount += node->getChildCount();
}
}
return childcount == 0;
}
<commit_msg>Move bracket to next line<commit_after>#include "confignode.hpp"
#include "treeviewmodel.hpp"
using namespace kdb;
ConfigNode::ConfigNode(const QString& name, const QString& path, const Key &key, TreeViewModel *parentModel)
: m_name(name)
, m_path(path)
, m_key(key)
, m_children(new TreeViewModel)
, m_metaData(NULL)
, m_parentModel(parentModel)
, m_isExpanded(false)
, m_isDirty(false)
{
if (m_key && m_key.isString())
m_value = QVariant::fromValue(QString::fromStdString(m_key.getString()));
else if (m_key && m_key.isBinary())
m_value = QVariant::fromValue(QString::fromStdString(m_key.getBinary()));
if(m_key)
{
m_metaData = new TreeViewModel;
populateMetaModel();
}
connect(m_children, SIGNAL(expandNode(bool)), this, SLOT(setIsExpanded(bool)));
connect(this, SIGNAL(showMessage(QString,QString,QString)), parentModel, SLOT(showConfigNodeMessage(QString,QString,QString)));
}
ConfigNode::ConfigNode(const ConfigNode& other)
: QObject()
, m_name(other.m_name)
, m_path(other.m_path)
, m_value(other.m_value)
, m_key(other.m_key.dup())
, m_children(new TreeViewModel)
, m_metaData(NULL)
, m_parentModel(NULL)
, m_isExpanded(other.m_isExpanded)
, m_isDirty(false)
{
if(other.m_children)
{
foreach(ConfigNodePtr node, other.m_children->model())
{
m_children->append(ConfigNodePtr(new ConfigNode(*node)));
}
}
if(other.m_metaData)
{
m_metaData = new TreeViewModel;
foreach(ConfigNodePtr node, other.m_metaData->model())
{
m_metaData->append(ConfigNodePtr(new ConfigNode(*node)));
}
}
connect(m_children, SIGNAL(expandNode(bool)), this, SLOT(setIsExpanded(bool)));
}
ConfigNode::ConfigNode()
: m_children(NULL)
, m_metaData(NULL)
, m_parentModel(NULL)
, m_isExpanded(false)
, m_isDirty(false)
{
//this constructor is used to create metanodes
}
ConfigNode::~ConfigNode()
{
delete m_children;
delete m_metaData;
}
int ConfigNode::getChildCount() const
{
if(m_children)
return m_children->rowCount();
return 0;
}
QString ConfigNode::getName() const
{
return m_name;
}
QString ConfigNode::getPath() const
{
return m_path;
}
QVariant ConfigNode::getValue() const
{
return m_value;
}
void ConfigNode::setName(const QString& name)
{
int index = m_path.lastIndexOf("/");
if(index != -1)
{
m_path.replace(index, m_path.length() - index, "/" + name);
}
if(!m_key)
m_key = Key(m_path.toStdString(), KEY_END);
else
m_key = m_key.dup();
try{
if(m_key.getBaseName().compare(name.toStdString()) != 0)
m_key.setBaseName(name.toStdString());
}
catch(KeyInvalidName const& ex){
emit showMessage(tr("Error"), tr("Could not set name because Keyname \"%1\" is invalid.").arg(name), ex.what());
return;
}
m_name = name;
}
void ConfigNode::setValue(const QVariant& value)
{
if(!m_key)
m_key = Key(m_path.toStdString(), KEY_END);
else
m_key = m_key.dup();
if(m_key.getString().compare(value.toString().toStdString()) != 0)
{
m_key.setString(value.toString().toStdString());
m_value = value;
}
}
void ConfigNode::setMeta(const QString &name, const QVariant &value)
{
if(!m_key)
m_key = Key(m_path.toStdString(), KEY_END);
else
m_key = m_key.dup();
m_key.setMeta(name.toStdString(), value.toString().toStdString());
m_name = name;
m_value = value;
}
void ConfigNode::setMeta(const QVariantMap &metaData)
{
if(m_metaData)
{
//delete old metadata in key
for(int i = 0; i < m_metaData->model().size(); i++)
{
m_metaData->model().at(i)->deleteMeta(m_metaData->model().at(i)->getName());
}
//delete old metadata in model
m_metaData->clearMetaModel();
}
else
m_metaData = new TreeViewModel;
//create new metadata nodes in model
for(int i = 0; i < metaData.size(); i++)
{
m_metaData->insertMetaRow(i, m_key, m_name);
}
int counter = 0;
//set new metadata
for(QVariantMap::const_iterator iter = metaData.begin(); iter != metaData.end(); iter++)
{
QVariantList tmp;
tmp << iter.key() << iter.value();
m_metaData->setData(m_metaData->index(counter), tmp, TreeViewModel::MetaValueRole);
counter++;
}
}
void ConfigNode::deleteMeta(const QString &name)
{
if(m_key)
m_key.delMeta(name.toStdString());
}
void ConfigNode::accept(Visitor &visitor)
{
visitor.visit(*this);
if(m_children)
{
foreach (ConfigNodePtr node, m_children->model())
node->accept(visitor);
}
}
Key ConfigNode::getKey() const
{
return m_key;
}
int ConfigNode::getChildIndexByName(const QString &name)
{
if(m_children)
{
for(int i = 0; i < m_children->rowCount(); i++)
{
if(m_children->model().at(i)->getName() == name)
return i;
}
}
return -1;
}
TreeViewModel *ConfigNode::getParentModel()
{
return m_parentModel;
}
void ConfigNode::setParentModel(TreeViewModel *parentModel)
{
m_parentModel = parentModel;
}
bool ConfigNode::isExpanded() const
{
return m_isExpanded;
}
bool ConfigNode::isDirty() const
{
return m_isDirty;
}
void ConfigNode::setIsDirty(bool dirty)
{
m_isDirty = dirty;
}
void ConfigNode::setIsExpanded(bool value)
{
m_isExpanded = value;
}
void ConfigNode::populateMetaModel()
{
if (m_key)
{
m_key.rewindMeta();
m_metaData->model().clear();
while (m_key.nextMeta())
{
ConfigNodePtr node(new ConfigNode());
node->setName(QString::fromStdString(m_key.getName()));
node->setKey(m_key);
node->setMeta(QString::fromStdString(m_key.currentMeta().getName()), QVariant::fromValue(QString::fromStdString(m_key.currentMeta().getString())));
m_metaData->model().append(node);
}
}
}
void ConfigNode::setKey(Key key)
{
m_key = key;
}
void ConfigNode::setKeyName(const QString &name)
{
if(m_key)
{
try
{
m_key.setName(name.toStdString());
}
catch(KeyInvalidName ex)
{
emit showMessage(tr("Error"), tr("Could not set name because Keyname \"%1\" is invalid.").arg(name), ex.what());
return;
}
}
}
void ConfigNode::appendChild(ConfigNodePtr node)
{
m_children->append(node);
}
bool ConfigNode::hasChild(const QString& name) const
{
if(m_children)
{
foreach (ConfigNodePtr node, m_children->model())
{
if (node->getName() == name)
{
return true;
}
}
}
return false;
}
TreeViewModel* ConfigNode::getChildren() const
{
return m_children;
}
TreeViewModel* ConfigNode::getMetaKeys() const
{
return m_metaData;
}
ConfigNodePtr ConfigNode::getChildByName(QString& name) const
{
if(m_children)
{
foreach (ConfigNodePtr node, m_children->model())
{
if (node->getName() == name)
{
return node;
}
}
}
return ConfigNodePtr();
}
ConfigNodePtr ConfigNode::getChildByIndex(int index) const
{
if(m_children)
{
if (index >= 0 && index < m_children->model().length())
return m_children->model().at(index);
}
return ConfigNodePtr();
}
void ConfigNode::setPath(const QString &path)
{
m_path = path;
setKeyName(path);
if(m_children)
{
foreach(ConfigNodePtr node, m_children->model()){
node->setPath(m_path + "/" + node->getName());
}
}
}
bool ConfigNode::childrenHaveNoChildren() const
{
int childcount = 0;
if(m_children)
{
foreach (ConfigNodePtr node, m_children->model())
{
childcount += node->getChildCount();
}
}
return childcount == 0;
}
<|endoftext|> |
<commit_before>/*
Based on Allocore Example: Audio To Graphics by Lance Putnam
*/
#include <iostream>
#include "allocore/io/al_App.hpp"
#include "alloaudio/al_OutputMaster.hpp"
using namespace std;
using namespace al;
class MyApp : public App{
public:
double phase;
OutputMaster outMaster;
MyApp(int num_chnls, double sampleRate,
const char * address = "", int inport = 19375,
const char * sendAddress = "localhost", int sendPort = -1)
: outMaster(num_chnls, sampleRate, address, inport, sendAddress, sendPort)
{
nav().pos(0,0,4);
initWindow();
initAudio(sampleRate, 512, num_chnls, num_chnls);
}
// Audio callback
void onSound(AudioIOData& io){
// Set the base frequency to 55 Hz
double freq = 55/io.framesPerSecond();
while(io()){
// Update the oscillators' phase
phase += freq;
if(phase > 1) phase -= 1;
// Generate two sine waves at the 5th and 4th harmonics
float out1 = cos(5*phase * 2*M_PI);
float out2 = sin(4*phase * 2*M_PI);
// Send scaled waveforms to output...
io.out(0) = out1*0.2;
io.out(1) = out2*0.2;
io.out(2) = out1*0.4;
io.out(3) = out2*0.4;
}
outMaster.onAudioCB(io);
}
void onAnimate(double dt){
}
void onDraw(Graphics& g, const Viewpoint& v){
}
};
int main(){
int num_chnls = 4;
double sampleRate = 44100;
const char * address = "localhost";
int inport = 3002;
const char * sendAddress = "localhost";
int sendPort = 3003;
cout << "Listening to \"" << address << "\" on port " << inport << endl;
cout << "Sending to \"" << sendAddress << "\" on port " << sendPort << endl;
MyApp(num_chnls, sampleRate, address, inport, sendAddress, sendPort).start();
}
<commit_msg>Minor fixes for multichannel control example<commit_after>/*
Based on Allocore Example: Audio To Graphics by Lance Putnam
*/
#include <iostream>
#include "allocore/io/al_App.hpp"
#include "alloaudio/al_OutputMaster.hpp"
using namespace std;
using namespace al;
class MyApp : public App{
public:
double phase;
OutputMaster outMaster;
MyApp(int num_chnls, double sampleRate,
const char * address = "", int inport = 19375,
const char * sendAddress = "localhost", int sendPort = -1)
: outMaster(num_chnls, sampleRate, address, inport, sendAddress, sendPort)
{
nav().pos(0,0,4);
initWindow();
initAudio(sampleRate, 512, num_chnls, num_chnls);
}
// Audio callback
void onSound(AudioIOData& io){
// Set the base frequency to 55 Hz
double freq = 55/io.framesPerSecond();
while(io()){
// Update the oscillators' phase
phase += freq;
if(phase > 1) phase -= 1;
// Generate two sine waves at the 5th and 4th harmonics
float out1 = cos(5*phase * 2*M_PI);
float out2 = sin(4*phase * 2*M_PI);
// Send scaled waveforms to output...
io.out(0) = out1*0.2;
io.out(1) = out2*0.2;
io.out(2) = out1*0.4;
io.out(3) = out2*0.4;
}
outMaster.onAudioCB(io);
}
void onAnimate(double dt){
}
void onDraw(Graphics& g, const Viewpoint& v){
}
};
int main(){
int num_chnls = 4;
double sampleRate = 44100;
const char * address = "localhost";
int inport = 3002;
const char * sendAddress = "localhost";
int sendPort = 3003;
cout << "Listening to \"" << address << "\" on port " << inport << endl;
cout << "Sending to \"" << sendAddress << "\" on port " << sendPort << endl;
MyApp(num_chnls, sampleRate, address, inport, sendAddress, sendPort).start();
return 0;
}
<|endoftext|> |
<commit_before>// RhoLaunch.cpp : Defines the entry point for the application.
//
#include "windows.h"
#include "RhoLaunch.h"
#define MAX_LOADSTRING 100
// Global Variables:
//HINSTANCE g_hInst; // current instance
//#ifdef SHELL_AYGSHELL
//HWND g_hWndMenuBar; // menu bar handle
//#else // SHELL_AYGSHELL
//HWND g_hWndCommandBar; // command bar handle
//#endif // SHELL_AYGSHELL
int WINAPI WinMain(HINSTANCE hInstance,
HINSTANCE hPrevInstance,
LPTSTR lpCmdLine,
int nCmdShow)
{
//validate the command line
int iLen = wcslen(lpCmdLine);
if(iLen < 3){
return 1;
}
LPWSTR pAppName = new WCHAR[iLen + 3];//allow space for the index
LPWSTR pTemp = pAppName;
LPWSTR pTabID;
int iLoop,iTabID;
bool bRead = false;
for(iLoop = 0;iLoop < iLen ;iLoop++)
{
if(lpCmdLine[iLoop] == L' '){
if(bRead){
*pTemp= NULL;
for(;iLoop < iLen && lpCmdLine[iLoop] == L' ';iLoop++);
pTabID = &lpCmdLine[iLoop+1];
iTabID = _wtoi(pTabID);
break;
}
continue;
}
*pTemp = lpCmdLine[iLoop];
pTemp++;
bRead = true;
}
HWND hwndRunningRE = FindWindow(NULL, pAppName);
if (hwndRunningRE){
// Found the running instance
//send a message to inform Rho of the requested index
/*****TODO***********/
//SendMessage(hwndRunningRE, WM_WINDOW_RESTORE, (WPARAM)iTabID, TRUE);
// switch to it
ShowWindow(hwndRunningRE, SW_RESTORE);
SetForegroundWindow(hwndRunningRE);
}
delete[]pAppName;
return 0;
}
//
// FUNCTION: MyRegisterClass()
//
// PURPOSE: Registers the window class.
//
// COMMENTS:
//
//ATOM MyRegisterClass(HINSTANCE hInstance, LPTSTR szWindowClass)
//{
// WNDCLASS wc;
//
// wc.style = CS_HREDRAW | CS_VREDRAW;
// wc.lpfnWndProc = WndProc;
// wc.cbClsExtra = 0;
// wc.cbWndExtra = 0;
// wc.hInstance = hInstance;
// wc.hIcon = LoadIcon(hInstance, MAKEINTRESOURCE(IDI_RHOLAUNCH));
// wc.hCursor = 0;
// wc.hbrBackground = (HBRUSH) GetStockObject(WHITE_BRUSH);
// wc.lpszMenuName = 0;
// wc.lpszClassName = szWindowClass;
//
// return RegisterClass(&wc);
//}
//
// FUNCTION: InitInstance(HINSTANCE, int)
//
// PURPOSE: Saves instance handle and creates main window
//
// COMMENTS:
//
// In this function, we save the instance handle in a global variable and
// create and display the main program window.
//
//BOOL InitInstance(HINSTANCE hInstance, int nCmdShow)
//{
// HWND hWnd;
// TCHAR szTitle[MAX_LOADSTRING]; // title bar text
// TCHAR szWindowClass[MAX_LOADSTRING]; // main window class name
//
// g_hInst = hInstance; // Store instance handle in our global variable
//
//#if defined(WIN32_PLATFORM_PSPC) || defined(WIN32_PLATFORM_WFSP)
// // SHInitExtraControls should be called once during your application's initialization to initialize any
// // of the device specific controls such as CAPEDIT and SIPPREF.
// SHInitExtraControls();
//#endif // WIN32_PLATFORM_PSPC || WIN32_PLATFORM_WFSP
//
// LoadString(hInstance, IDS_APP_TITLE, szTitle, MAX_LOADSTRING);
// LoadString(hInstance, IDC_RHOLAUNCH, szWindowClass, MAX_LOADSTRING);
//
//#if defined(WIN32_PLATFORM_PSPC) || defined(WIN32_PLATFORM_WFSP)
// //If it is already running, then focus on the window, and exit
// hWnd = FindWindow(szWindowClass, szTitle);
// if (hWnd)
// {
// // set focus to foremost child window
// // The "| 0x00000001" is used to bring any owned windows to the foreground and
// // activate them.
// SetForegroundWindow((HWND)((ULONG) hWnd | 0x00000001));
// return 0;
// }
//#endif // WIN32_PLATFORM_PSPC || WIN32_PLATFORM_WFSP
//
// if (!MyRegisterClass(hInstance, szWindowClass))
// {
// return FALSE;
// }
//
// hWnd = CreateWindow(szWindowClass, szTitle, WS_VISIBLE,
// CW_USEDEFAULT, CW_USEDEFAULT, CW_USEDEFAULT, CW_USEDEFAULT, NULL, NULL, hInstance, NULL);
//
// if (!hWnd)
// {
// return FALSE;
// }
//
//#ifdef WIN32_PLATFORM_PSPC
// // When the main window is created using CW_USEDEFAULT the height of the menubar (if one
// // is created is not taken into account). So we resize the window after creating it
// // if a menubar is present
// if (g_hWndMenuBar)
// {
// RECT rc;
// RECT rcMenuBar;
//
// GetWindowRect(hWnd, &rc);
// GetWindowRect(g_hWndMenuBar, &rcMenuBar);
// rc.bottom -= (rcMenuBar.bottom - rcMenuBar.top);
//
// MoveWindow(hWnd, rc.left, rc.top, rc.right-rc.left, rc.bottom-rc.top, FALSE);
// }
//#endif // WIN32_PLATFORM_PSPC
//
// ShowWindow(hWnd, nCmdShow);
// UpdateWindow(hWnd);
//
//#ifndef SHELL_AYGSHELL
// if (g_hWndCommandBar)
// {
// CommandBar_Show(g_hWndCommandBar, TRUE);
// }
//#endif // !SHELL_AYGSHELL
//
// return TRUE;
//}
//
// FUNCTION: WndProc(HWND, UINT, WPARAM, LPARAM)
//
// PURPOSE: Processes messages for the main window.
//
// WM_COMMAND - process the application menu
// WM_PAINT - Paint the main window
// WM_DESTROY - post a quit message and return
//
//
//LRESULT CALLBACK WndProc(HWND hWnd, UINT message, WPARAM wParam, LPARAM lParam)
//{
// int wmId, wmEvent;
// PAINTSTRUCT ps;
// HDC hdc;
//
//#if defined(SHELL_AYGSHELL) && !defined(WIN32_PLATFORM_WFSP)
// static SHACTIVATEINFO s_sai;
//#endif // SHELL_AYGSHELL && !WIN32_PLATFORM_WFSP
//
// switch (message)
// {
// case WM_COMMAND:
// wmId = LOWORD(wParam);
// wmEvent = HIWORD(wParam);
// // Parse the menu selections:
// switch (wmId)
// {
// case IDM_HELP_ABOUT:
// MessageBox(hWnd,g_Msg,L"Testing...",MB_OK);
// //DialogBox(g_hInst, (LPCTSTR)IDD_ABOUTBOX, hWnd, About);
// break;
//#ifndef SHELL_AYGSHELL
// case IDM_FILE_EXIT:
// DestroyWindow(hWnd);
// break;
//#endif // !SHELL_AYGSHELL
//#ifdef WIN32_PLATFORM_PSPC
// case IDM_OK:
// SendMessage (hWnd, WM_CLOSE, 0, 0);
// break;
//#endif // WIN32_PLATFORM_PSPC
// default:
// return DefWindowProc(hWnd, message, wParam, lParam);
// }
// break;
// case WM_CREATE:
//#ifndef SHELL_AYGSHELL
// g_hWndCommandBar = CommandBar_Create(g_hInst, hWnd, 1);
// CommandBar_InsertMenubar(g_hWndCommandBar, g_hInst, IDR_MENU, 0);
// CommandBar_AddAdornments(g_hWndCommandBar, 0, 0);
//#endif // !SHELL_AYGSHELL
//#ifdef SHELL_AYGSHELL
// SHMENUBARINFO mbi;
//
// memset(&mbi, 0, sizeof(SHMENUBARINFO));
// mbi.cbSize = sizeof(SHMENUBARINFO);
// mbi.hwndParent = hWnd;
// mbi.nToolBarId = IDR_MENU;
// mbi.hInstRes = g_hInst;
//
// if (!SHCreateMenuBar(&mbi))
// {
// g_hWndMenuBar = NULL;
// }
// else
// {
// g_hWndMenuBar = mbi.hwndMB;
// }
//
// // Initialize the shell activate info structure
// memset(&s_sai, 0, sizeof (s_sai));
// s_sai.cbSize = sizeof (s_sai);
//#endif // SHELL_AYGSHELL
// break;
// case WM_PAINT:
// hdc = BeginPaint(hWnd, &ps);
//
// // TODO: Add any drawing code here...
//
// EndPaint(hWnd, &ps);
// break;
// case WM_DESTROY:
//#ifndef SHELL_AYGSHELL
// CommandBar_Destroy(g_hWndCommandBar);
//#endif // !SHELL_AYGSHELL
//#ifdef SHELL_AYGSHELL
// CommandBar_Destroy(g_hWndMenuBar);
//#endif // SHELL_AYGSHELL
// PostQuitMessage(0);
// break;
//
//#if defined(SHELL_AYGSHELL) && !defined(WIN32_PLATFORM_WFSP)
// case WM_ACTIVATE:
// // Notify shell of our activate message
// SHHandleWMActivate(hWnd, wParam, lParam, &s_sai, FALSE);
// break;
// case WM_SETTINGCHANGE:
// SHHandleWMSettingChange(hWnd, wParam, lParam, &s_sai);
// break;
//#endif // SHELL_AYGSHELL && !WIN32_PLATFORM_WFSP
//
// default:
// return DefWindowProc(hWnd, message, wParam, lParam);
// }
// return 0;
//}
// Message handler for about box.
//INT_PTR CALLBACK About(HWND hDlg, UINT message, WPARAM wParam, LPARAM lParam)
//{
// switch (message)
// {
// case WM_INITDIALOG:
//#ifndef SHELL_AYGSHELL
// RECT rectChild, rectParent;
// int DlgWidth, DlgHeight; // dialog width and height in pixel units
// int NewPosX, NewPosY;
//
// // trying to center the About dialog
// if (GetWindowRect(hDlg, &rectChild))
// {
// GetClientRect(GetParent(hDlg), &rectParent);
// DlgWidth = rectChild.right - rectChild.left;
// DlgHeight = rectChild.bottom - rectChild.top ;
// NewPosX = (rectParent.right - rectParent.left - DlgWidth) / 2;
// NewPosY = (rectParent.bottom - rectParent.top - DlgHeight) / 2;
//
// // if the About box is larger than the physical screen
// if (NewPosX < 0) NewPosX = 0;
// if (NewPosY < 0) NewPosY = 0;
// SetWindowPos(hDlg, 0, NewPosX, NewPosY,
// 0, 0, SWP_NOZORDER | SWP_NOSIZE);
// }
//#endif // !SHELL_AYGSHELL
//#ifdef SHELL_AYGSHELL
// {
// // Create a Done button and size it.
// SHINITDLGINFO shidi;
// shidi.dwMask = SHIDIM_FLAGS;
// shidi.dwFlags = SHIDIF_DONEBUTTON | SHIDIF_SIPDOWN | SHIDIF_SIZEDLGFULLSCREEN | SHIDIF_EMPTYMENU;
// shidi.hDlg = hDlg;
// SHInitDialog(&shidi);
// }
//#endif // SHELL_AYGSHELL
//
// return (INT_PTR)TRUE;
//
// case WM_COMMAND:
//#ifndef SHELL_AYGSHELL
// if ((LOWORD(wParam) == IDOK) || (LOWORD(wParam) == IDCANCEL))
//#endif // !SHELL_AYGSHELL
//#ifdef SHELL_AYGSHELL
// if (LOWORD(wParam) == IDOK)
//#endif
// {
// EndDialog(hDlg, LOWORD(wParam));
// return (INT_PTR)TRUE;
// }
// break;
//
// case WM_CLOSE:
// EndDialog(hDlg, message);
// return (INT_PTR)TRUE;
//
// }
// return (INT_PTR)FALSE;
//}
<commit_msg>Sends a WM_COPYDATA message to Rhodes to request a tab selection.<commit_after>// RhoLaunch.cpp : Defines the entry point for the application.
//
#include "windows.h"
#include "RhoLaunch.h"
#define MAX_LOADSTRING 100
// Global Functions:
int LaunchProcess( LPTSTR pFilePath, LPTSTR pCmdLine);
int WINAPI WinMain(HINSTANCE hInstance,
HINSTANCE hPrevInstance,
LPTSTR lpCmdLine,
int nCmdShow)
{
COPYDATASTRUCT launchData;
//validate the command line
int iLen = wcslen(lpCmdLine);
if(iLen < 3){
return 1;
}
//LPWSTR pAppName = new WCHAR[iLen + 3];//allow space for the index
LPWSTR pAppName,pTabName,pTemp;
pAppName = pTemp= lpCmdLine;
int iLoop;
bool bStart,bTabStart,bAppName;
bStart = bTabStart = bAppName= false;
for(iLoop = 0;iLoop < iLen ;iLoop++)
{
if(lpCmdLine[iLoop] == L' '){
if(bStart){
if(!bAppName){
*pTemp = NULL;//terminate the app name
pTemp++;
bAppName = true;
pTabName = pTemp;
}
else if(bTabStart){
*pTemp = NULL;//terminate the tab name
break;//finished so exit loop
}
}
continue;//ignore spaces
}
if(lpCmdLine[iLoop] == L'/'){
if(!bStart){
bStart = !bStart;
continue;
}
if(!bAppName){
*pTemp= NULL;
bAppName = !bAppName;
bTabStart = true;
}
if(!bTabStart){
bTabStart = true;
continue;
}
}
*pTemp= lpCmdLine[iLoop];
pTemp++;
}
*pTemp = NULL;
HWND hwndRunningRE = FindWindow(NULL, pAppName);
if (hwndRunningRE){
// Found the running instance
//rhode expects a MultiByte string so convert
int ilen = wcslen(pTabName);
char *pTabNameMB = new char[ilen+1];
wcstombs(pTabNameMB, pTabName,ilen);
launchData.lpData = pTabNameMB;
launchData.cbData = (ilen+1);
//send a message to inform Rho of the requested index
SendMessage(hwndRunningRE,WM_COPYDATA,(WPARAM)NULL,(LPARAM) (LPVOID) &launchData );
delete [] pTabNameMB;
// switch to it
ShowWindow(hwndRunningRE, SW_RESTORE);
SetForegroundWindow(hwndRunningRE);
}
else{
//no window handle, so try to start the app
//will only work if RhoLaunch is in the same directory as the app
//build the Rho app name
WCHAR pApp[MAX_PATH + 1];
int iIndex,iLen;
if(!(iLen = GetModuleFileName(NULL,pApp,MAX_PATH))){
return 1;//error could not find the path
}
//remove 'RhoLaunch' from the path
for(iIndex = iLen - 1;pApp[iIndex]!=L'\\';iIndex--);
pApp[iIndex+ 1] = NULL;
//LPWSTR pApp = new WCHAR[wcslen(pAppName)+10];
wcscat(pApp,pAppName);
wcscat(pApp,L".exe");
LPWSTR pTabCommand = new WCHAR[wcslen(pTabName)+20];
wsprintf(pTabCommand,L"/tabname=\"%s\"",pTabName);
LaunchProcess(pApp,pTabCommand);
delete [] pTabCommand;
}
return 0;
}
int LaunchProcess( LPTSTR pFilePath, LPTSTR pCmdLine)
{
STARTUPINFO StartInfo;
PROCESS_INFORMATION ProcessInfo;
BOOL bOk;
// Reset the contents of the 'Process Information' and 'Start Up' structures.
memset( &ProcessInfo, 0, sizeof( PROCESS_INFORMATION));
memset( &StartInfo, 0, sizeof( STARTUPINFO));
StartInfo.cb = sizeof( STARTUPINFO);
// Create the 'browser' in a seperate process.
bOk = CreateProcess( pFilePath, // LPCTSTR lpApplicationName,//L"\\program files\\Neon\\BIN\\SVC_Controls.exe",
pCmdLine, // LPTSTR lpCommandLine,
NULL, // LPSECURITY_ATTRIBUTES lpProcessAttributes,
NULL, // LPSECURITY_ATTRIBUTES lpThreadAttributes,
FALSE, // BOOL bInheritHandles,
0, // DWORD dwCreationFlags,
NULL, // LPVOID lpEnvironment,
NULL, // LPCTSTR lpCurrentDirectory,
&StartInfo, // LPSTARTUPINFO lpStartupInfo,
&ProcessInfo); // LPPROCESS_INFORMATION lpProcessInformation
//m_dwProcessID = ProcessInfo.dwProcessId;
// If all is Ok, then return '0' else return the last error code.
return bOk ? 0 : GetLastError();
}<|endoftext|> |
<commit_before>#include "WorldTeleporter.hpp"
namespace DataSpec::DNAMP1 {
template <class Op>
void WorldTeleporter::Enumerate(typename Op::StreamT& s) {
IScriptObject::Enumerate<Op>(s);
Do<Op>({"name"}, name, s);
Do<Op>({"active"}, active, s);
Do<Op>({"mlvl"}, mlvl, s);
Do<Op>({"mrea"}, mrea, s);
Do<Op>({"animationParameters"}, animationParameters, s);
Do<Op>({"playerScale"}, playerScale, s);
Do<Op>({"platformModel"}, platformModel, s);
Do<Op>({"platformScale"}, platformScale, s);
Do<Op>({"blackgroundModel"}, backgroundModel, s);
Do<Op>({"backgroundScale"}, backgroundScale, s);
Do<Op>({"upElevator"}, upElevator, s);
Do<Op>({"elevatorSound"}, elevatorSound, s);
Do<Op>({"volume"}, volume, s);
Do<Op>({"panning"}, panning, s);
Do<Op>({"showText"}, showText, s);
Do<Op>({"font"}, font, s);
Do<Op>({"strg"}, strg, s);
Do<Op>({"fadeWhite"}, fadeWhite, s);
Do<Op>({"charFadeInTime"}, charFadeInTime, s);
Do<Op>({"charsPerSecond"}, charFadeInTime, s);
Do<Op>({"showDelay"}, showDelay, s);
if (propertyCount == 26) {
Do<Op>({"audioStream"}, audioStream, s);
Do<Op>({"unknown13"}, unknown13, s);
Do<Op>({"unknown14"}, unknown14, s);
Do<Op>({"unknown15"}, unknown15, s);
Do<Op>({"unknown16"}, unknown16, s);
} else {
unknown13 = false;
unknown14 = 0.0;
unknown15 = 0.0;
unknown16 = 0.0;
}
}
const char* WorldTeleporter::DNAType() { return "urde::DNAMP1::WorldTeleporter"; }
AT_SPECIALIZE_DNA_YAML(WorldTeleporter)
} // namespace DataSpec::DNAMP1
<commit_msg>Fix WorldTeleporter derp<commit_after>#include "WorldTeleporter.hpp"
namespace DataSpec::DNAMP1 {
template <class Op>
void WorldTeleporter::Enumerate(typename Op::StreamT& s) {
IScriptObject::Enumerate<Op>(s);
Do<Op>({"name"}, name, s);
Do<Op>({"active"}, active, s);
Do<Op>({"mlvl"}, mlvl, s);
Do<Op>({"mrea"}, mrea, s);
Do<Op>({"animationParameters"}, animationParameters, s);
Do<Op>({"playerScale"}, playerScale, s);
Do<Op>({"platformModel"}, platformModel, s);
Do<Op>({"platformScale"}, platformScale, s);
Do<Op>({"blackgroundModel"}, backgroundModel, s);
Do<Op>({"backgroundScale"}, backgroundScale, s);
Do<Op>({"upElevator"}, upElevator, s);
Do<Op>({"elevatorSound"}, elevatorSound, s);
Do<Op>({"volume"}, volume, s);
Do<Op>({"panning"}, panning, s);
Do<Op>({"showText"}, showText, s);
Do<Op>({"font"}, font, s);
Do<Op>({"strg"}, strg, s);
Do<Op>({"fadeWhite"}, fadeWhite, s);
Do<Op>({"charFadeInTime"}, charFadeInTime, s);
Do<Op>({"charsPerSecond"}, charsPerSecond, s);
Do<Op>({"showDelay"}, showDelay, s);
if (propertyCount == 26) {
Do<Op>({"audioStream"}, audioStream, s);
Do<Op>({"unknown13"}, unknown13, s);
Do<Op>({"unknown14"}, unknown14, s);
Do<Op>({"unknown15"}, unknown15, s);
Do<Op>({"unknown16"}, unknown16, s);
} else {
unknown13 = false;
unknown14 = 0.0;
unknown15 = 0.0;
unknown16 = 0.0;
}
}
const char* WorldTeleporter::DNAType() { return "urde::DNAMP1::WorldTeleporter"; }
AT_SPECIALIZE_DNA_YAML(WorldTeleporter)
} // namespace DataSpec::DNAMP1
<|endoftext|> |
<commit_before>#include "linearizer.hpp"
#include <vector>
#include "tgmath.h"
#include "utils.hpp"
void linearizeCurrent(elementaryFunctionLib elementaryFunctionType, double lb,
double ub, int meshPts, std::vector<double> &aCurrent,
std::vector<double> &bCurrent) {
double Z = ub - lb;
double delta = Z / meshPts;
std::vector<double> F_j(meshPts);
std::vector<double> F_j_hat(meshPts);
// You can set up X_j=linspace(lb,ub,meshPts+1) to avoid Xinit, Xend
std::vector<double> X_j(meshPts + 1);
for (int j = 0; j < meshPts + 1; j++) {
X_j[j] = lb + j * delta;
}
double Xinit;
double Xend;
int n = 0;
switch (elementaryFunctionType) {
case CONST:
n = 0;
for (int j = 0; j < meshPts; j++) {
Xinit = X_j[j];
Xend = X_j[j + 1];
F_j[j] = (Xend - Xinit) / (n + 1) / delta;
F_j_hat[j] = (Xend * Xend - Xinit * Xinit) / (n + 2) / delta;
}
break;
case POLY1:
n = 1;
for (int j = 0; j < meshPts; j++) {
Xinit = X_j[j];
Xend = X_j[j + 1];
F_j[j] = (Xend * Xend - Xinit * Xinit) / (n + 1) / delta;
F_j_hat[j] = (Xend * Xend * Xend - Xinit * Xinit * Xinit) /
(n + 2) / delta;
}
break;
case POLY2:
n = 2;
for (int j = 0; j < meshPts; j++) {
Xinit = X_j[j];
Xend = X_j[j + 1];
F_j[j] = (Xend * Xend * Xend - Xinit * Xinit * Xinit) /
(n + 1) / delta;
F_j_hat[j] = (Xend * Xend * Xend * Xend -
Xinit * Xinit * Xinit * Xinit) /
(n + 2) / delta;
}
break;
case POLY3:
n = 3;
for (int j = 0; j < meshPts; j++) {
Xinit = X_j[j];
Xend = X_j[j + 1];
F_j[j] = (Xend * Xend * Xend * Xend -
Xinit * Xinit * Xinit * Xinit) /
(n + 1) / delta;
F_j_hat[j] = (Xend * Xend * Xend * Xend * Xend -
Xinit * Xinit * Xinit * Xinit * Xinit) /
(n + 2) / delta;
}
break;
case POLY4:
n = 4;
for (int j = 0; j < meshPts; j++) {
Xinit = X_j[j];
Xend = X_j[j + 1];
F_j[j] = (Xend * Xend * Xend * Xend * Xend -
Xinit * Xinit * Xinit * Xinit * Xinit) /
(n + 1) / delta;
F_j_hat[j] = (Xend * Xend * Xend * Xend * Xend * Xend -
Xinit * Xinit * Xinit * Xinit * Xinit * Xinit) /
(n + 2) / delta;
}
break;
case SINE:
for (int j = 0; j < meshPts; j++) {
Xinit = X_j[j];
Xend = X_j[j + 1];
F_j[j] = (cos(Xinit) - cos(Xend)) / delta;
F_j_hat[j] = (sin(Xend) - sin(Xinit) + (Xinit)*cos(Xinit) -
(Xend)*cos(Xend)) /
delta;
}
break;
case COSINE:
for (int j = 0; j < meshPts; j++) {
Xinit = X_j[j];
Xend = X_j[j + 1];
F_j[j] = (sin(Xend) - sin(Xinit)) / delta;
F_j_hat[j] = (cos(Xend) - cos(Xinit) + (Xend)*sin(Xend) -
(Xinit)*sin(Xinit)) /
delta;
}
break;
case TANGENT:
for (int j = 0; j < meshPts; j++) {
Xinit = X_j[j];
Xend = X_j[j + 1];
}
break;
case LN:
for (int j = 0; j < meshPts; j++) {
Xinit = X_j[j];
Xend = X_j[j + 1];
F_j[j] =
(Xinit - Xinit * log(Xinit) - Xend + Xend * log(Xend)) /
delta;
F_j_hat[j] =
(0.25 * (Xinit * Xinit - 2 * Xinit * Xinit * log(Xinit) -
Xend * Xend + 2 * Xend * Xend * log(Xend))) /
delta;
}
break;
case LOG: // log10
for (int j = 0; j < meshPts; j++) {
Xinit = X_j[j];
Xend = X_j[j + 1];
F_j[j] =
(Xinit - Xinit * log10(Xinit) - Xend + Xend * log10(Xend)) /
delta;
F_j_hat[j] =
(0.25 * (Xinit * Xinit - 2 * Xinit * Xinit * log10(Xinit) -
Xend * Xend + 2 * Xend * Xend * log10(Xend))) /
delta;
}
break;
case EXP:
for (int j = 0; j < meshPts; j++) {
Xinit = X_j[j];
Xend = X_j[j + 1];
F_j[j] = (exp(Xend) - exp(Xinit)) / delta;
F_j_hat[j] =
((Xend - 1) * exp(Xend) - (Xinit - 1) * exp(Xinit)) / delta;
}
break;
};
bCurrent = F_j;
for (int j = 0; j < meshPts; j++) {
aCurrent[j] = (F_j_hat[j] - bCurrent[j] * (j + j + 1) * delta / 2) *
12 / delta / delta;
}
return;
};
<commit_msg>fixed bugs when lower bound is not zero<commit_after>#include "linearizer.hpp"
#include <vector>
#include "tgmath.h"
#include "utils.hpp"
void linearizeCurrent(elementaryFunctionLib elementaryFunctionType, double lb,
double ub, int meshPts, std::vector<double> &aCurrent,
std::vector<double> &bCurrent) {
double Z = ub - lb;
double delta = Z / meshPts;
std::vector<double> F_j(meshPts);
std::vector<double> F_j_hat(meshPts);
// You can set up X_j=linspace(lb,ub,meshPts+1) to avoid Xinit, Xend
std::vector<double> X_j(meshPts + 1);
for (int j = 0; j < meshPts + 1; j++) {
X_j[j] = lb + j * delta;
}
double Xinit;
double Xend;
int n = 0;
switch (elementaryFunctionType) {
case CONST:
n = 0;
for (int j = 0; j < meshPts; j++) {
Xinit = X_j[j];
Xend = X_j[j + 1];
F_j[j] = (Xend - Xinit) / (n + 1) / delta;
F_j_hat[j] = (Xend * Xend - Xinit * Xinit) / (n + 2) / delta;
}
break;
case POLY1:
n = 1;
for (int j = 0; j < meshPts; j++) {
Xinit = X_j[j];
Xend = X_j[j + 1];
F_j[j] = (Xend * Xend - Xinit * Xinit) / (n + 1) / delta;
F_j_hat[j] = (Xend * Xend * Xend - Xinit * Xinit * Xinit) /
(n + 2) / delta;
}
break;
case POLY2:
n = 2;
for (int j = 0; j < meshPts; j++) {
Xinit = X_j[j];
Xend = X_j[j + 1];
F_j[j] = (Xend * Xend * Xend - Xinit * Xinit * Xinit) /
(n + 1) / delta;
F_j_hat[j] = (Xend * Xend * Xend * Xend -
Xinit * Xinit * Xinit * Xinit) /
(n + 2) / delta;
}
break;
case POLY3:
n = 3;
for (int j = 0; j < meshPts; j++) {
Xinit = X_j[j];
Xend = X_j[j + 1];
F_j[j] = (Xend * Xend * Xend * Xend -
Xinit * Xinit * Xinit * Xinit) /
(n + 1) / delta;
F_j_hat[j] = (Xend * Xend * Xend * Xend * Xend -
Xinit * Xinit * Xinit * Xinit * Xinit) /
(n + 2) / delta;
}
break;
case POLY4:
n = 4;
for (int j = 0; j < meshPts; j++) {
Xinit = X_j[j];
Xend = X_j[j + 1];
F_j[j] = (Xend * Xend * Xend * Xend * Xend -
Xinit * Xinit * Xinit * Xinit * Xinit) /
(n + 1) / delta;
F_j_hat[j] = (Xend * Xend * Xend * Xend * Xend * Xend -
Xinit * Xinit * Xinit * Xinit * Xinit * Xinit) /
(n + 2) / delta;
}
break;
case SINE:
for (int j = 0; j < meshPts; j++) {
Xinit = X_j[j];
Xend = X_j[j + 1];
F_j[j] = (cos(Xinit) - cos(Xend)) / delta;
F_j_hat[j] = (sin(Xend) - sin(Xinit) + (Xinit)*cos(Xinit) -
(Xend)*cos(Xend)) /
delta;
}
break;
case COSINE:
for (int j = 0; j < meshPts; j++) {
Xinit = X_j[j];
Xend = X_j[j + 1];
F_j[j] = (sin(Xend) - sin(Xinit)) / delta;
F_j_hat[j] = (cos(Xend) - cos(Xinit) + (Xend)*sin(Xend) -
(Xinit)*sin(Xinit)) /
delta;
}
break;
case TANGENT:
for (int j = 0; j < meshPts; j++) {
Xinit = X_j[j];
Xend = X_j[j + 1];
}
break;
case LN:
for (int j = 0; j < meshPts; j++) {
Xinit = X_j[j];
Xend = X_j[j + 1];
F_j[j] =
(Xinit - Xinit * log(Xinit) - Xend + Xend * log(Xend)) /
delta;
F_j_hat[j] =
(0.25 * (Xinit * Xinit - 2 * Xinit * Xinit * log(Xinit) -
Xend * Xend + 2 * Xend * Xend * log(Xend))) /
delta;
}
break;
case LOG: // log10
for (int j = 0; j < meshPts; j++) {
Xinit = X_j[j];
Xend = X_j[j + 1];
F_j[j] =
(Xinit - Xinit * log10(Xinit) - Xend + Xend * log10(Xend)) /
delta;
F_j_hat[j] =
(0.25 * (Xinit * Xinit - 2 * Xinit * Xinit * log10(Xinit) -
Xend * Xend + 2 * Xend * Xend * log10(Xend))) /
delta;
}
break;
case EXP:
for (int j = 0; j < meshPts; j++) {
Xinit = X_j[j];
Xend = X_j[j + 1];
F_j[j] = (exp(Xend) - exp(Xinit)) / delta;
F_j_hat[j] =
((Xend - 1) * exp(Xend) - (Xinit - 1) * exp(Xinit)) / delta;
}
break;
};
bCurrent = F_j;
for (int j = 0; j < meshPts; j++) {
aCurrent[j] = (F_j_hat[j] - bCurrent[j] * (X_j[j] + X_j[j + 1]) / 2) *
12 / delta / delta;
}
return;
};
<|endoftext|> |
<commit_before>/**
Copyright(c) 2015 - 2017 Denis Blank <denis.blank at outlook dot 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.
**/
#include <string>
#include <functional>
struct continuable_base {
template <typename T> continuable_base& then(T&&) { return *this; }
template <typename T> continuable_base& dropped(T&&) { return *this; }
template <typename T> continuable_base& thrown(T&&) { return *this; }
template <typename T> continuable_base& failed(T&&) { return *this; }
};
template<typename... Result>
struct accumulator {
auto accumulate() { return [] {}; }
};
template <typename Accumulator, typename... Initial>
auto make_accumulator(Accumulator&& /*ac*/, Initial&&... /*initial*/) {
return std::make_tuple(continuable_base{}, accumulator<int>{});
}
continuable_base http_request(std::string) { return {}; }
int main(int, char**) {
auto accumulator = make_accumulator(std::plus<int>{}, 0);
http_request("github.com")
.then([](std::string response) {
// ...
(void)response;
})
.then(std::get<1>(accumulator).accumulate())
.thrown([](std::exception_ptr exception) {
// ...
(void)exception;
})
.failed([](std::error_code code) {
// ...
(void)code;
});
return 0;
}
<commit_msg>Fix the CI build<commit_after>/**
Copyright(c) 2015 - 2017 Denis Blank <denis.blank at outlook dot 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.
**/
#include <string>
#include <functional>
#include <system_error>
struct continuable_base {
template <typename T> continuable_base& then(T&&) { return *this; }
template <typename T> continuable_base& dropped(T&&) { return *this; }
template <typename T> continuable_base& thrown(T&&) { return *this; }
template <typename T> continuable_base& failed(T&&) { return *this; }
};
template<typename... Result>
struct accumulator {
auto accumulate() { return [] {}; }
};
template <typename Accumulator, typename... Initial>
auto make_accumulator(Accumulator&& /*ac*/, Initial&&... /*initial*/) {
return std::make_tuple(continuable_base{}, accumulator<int>{});
}
continuable_base http_request(std::string) { return {}; }
int main(int, char**) {
auto accumulator = make_accumulator(std::plus<int>{}, 0);
http_request("github.com")
.then([](std::string response) {
// ...
(void)response;
})
.then(std::get<1>(accumulator).accumulate())
.thrown([](std::exception_ptr exception) {
// ...
(void)exception;
})
.failed([](std::error_code code) {
// ...
(void)code;
});
return 0;
}
<|endoftext|> |
<commit_before>/******************************************************************************
* This file is part of the Gluon Development Platform
* Copyright (C) 2010 Shantanu Tushar <jhahoneyk@gmail.com>
* Copyright (C) 2010 Laszlo Papp <djszapi@archlinux.us>
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 2.1 of the License, or (at your option) any later version.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
*/
#include "commentsmodel.h"
#include "player/lib/atticamanager.h"
#include "core/gluonobject.h"
#include "core/gdlhandler.h"
#include "core/gluon_global.h"
#include "engine/gameproject.h"
#include <attica/comment.h>
#include <attica/listjob.h>
#include <KDE/KLocalizedString>
#include <QtCore/QDebug>
#include <QtCore/QFile>
#include <QtCore/QDir>
using namespace GluonCore;
using namespace GluonPlayer;
static const char serviceURI[] = "gamingfreedom.org";
CommentsModel::CommentsModel( QString gameId, QObject* parent )
: QAbstractItemModel( parent )
, m_rootNode( new GluonObject( "Comment" ) )
, m_isOnline( false )
, m_gameId( gameId )
{
m_columnNames << "Author" << "Title" << "Body" << "DateTime" << "Rating";
loadData(); // Load comments stored locally
updateData(); // Fetch latest comments from the web service
}
void CommentsModel::updateData()
{
if( AtticaManager::instance()->isProviderValid() )
{
providersUpdated();
}
else
{
connect( AtticaManager::instance(), SIGNAL( gotProvider() ), SLOT( providersUpdated() ) );
}
}
void CommentsModel::providersUpdated()
{
if( AtticaManager::instance()->isProviderValid() )
{
Attica::ListJob<Attica::Comment> *job =
AtticaManager::instance()->provider().requestComments( Attica::Comment::ContentComment,
m_gameId, "0", 0, 100 );
connect( job, SIGNAL( finished( Attica::BaseJob* ) ), SLOT( processFetchedComments( Attica::BaseJob* ) ) );
job->start();
}
else
{
qDebug() << "No providers found.";
}
}
void CommentsModel::processFetchedComments( Attica::BaseJob* job )
{
qDebug() << "Comments Successfully Fetched from the server!";
Attica::ListJob<Attica::Comment> *commentsJob = static_cast<Attica::ListJob<Attica::Comment> *>( job );
if( commentsJob->metadata().error() == Attica::Metadata::NoError )
{
//No error, try to remove exising comments (if any)
//and add new comments
if( m_rootNode )
{
qDeleteAll( m_rootNode->children() );
}
for( int i = 0; i < commentsJob->itemList().count(); ++i )
{
Attica::Comment p( commentsJob->itemList().at( i ) );
addComment( p, m_rootNode );
}
m_isOnline = true;
reset(); //Reset the model to notify views to reload comments
}
else
{
qDebug() << "Could not fetch information";
}
}
void CommentsModel::addCommentFinished( Attica::BaseJob* job )
{
Attica::ListJob<Attica::Comment> *commentsJob = static_cast<Attica::ListJob<Attica::Comment>*>( job );
if( commentsJob->metadata().error() == Attica::Metadata::NoError )
{
updateData();
}
else
{
emit addCommentFailed();
}
}
GluonObject* CommentsModel::addComment( Attica::Comment comment, GluonObject* parent )
{
GluonObject* newComment = new GluonObject( comment.id(), parent );
newComment->setProperty( "Author", comment.user() );
newComment->setProperty( "Title", comment.subject() );
newComment->setProperty( "Body", comment.text() );
newComment->setProperty( "DateTime", comment.date().toString() );
newComment->setProperty( "Rating", comment.score() );
foreach( const Attica::Comment& child, comment.children() )
{
addComment( child, newComment );
}
return newComment;
}
void CommentsModel::loadData()
{
QDir gluonDir = QDir::home();
gluonDir.mkpath( GluonEngine::projectSuffix + "/" + QString( serviceURI ) );
gluonDir.cd( GluonEngine::projectSuffix + "/" + QString( serviceURI ) );
m_rootNode = GluonCore::GDLHandler::instance()->parseGDL( gluonDir.absoluteFilePath( "comments.gdl" ) ).at(0);
}
void CommentsModel::saveData()
{
qDebug() << "Saving data!";
QDir gluonDir = QDir::home();
gluonDir.mkpath( GluonEngine::projectSuffix + "/" + QString( serviceURI ) );
gluonDir.cd( GluonEngine::projectSuffix + "/" + QString( serviceURI ) );
QString filename = gluonDir.absoluteFilePath( "comments.gdl" );
QFile dataFile( filename );
if( !dataFile.open( QIODevice::WriteOnly ) )
qDebug() << "Cannot open the comments file!";
QList<const GluonObject*> comments;
comments.append( m_rootNode );
QTextStream dataWriter( &dataFile );
dataWriter << GluonCore::GDLHandler::instance()->serializeGDL( comments );
dataFile.close();
qDebug() << "Saved";
}
CommentsModel::~CommentsModel()
{
saveData(); //Save data before exiting
delete m_rootNode;
}
QVariant CommentsModel::data( const QModelIndex& index, int role ) const
{
if( role == Qt::DisplayRole || role == Qt::EditRole )
{
GluonObject* node;
node = static_cast<GluonObject*>( index.internalPointer() );
return node->property( m_columnNames.at(index.column()).toUtf8() );
}
return QVariant();
}
int CommentsModel::columnCount( const QModelIndex& parent ) const
{
Q_UNUSED( parent )
return 5;
}
int CommentsModel::rowCount( const QModelIndex& parent ) const
{
GluonObject* parentItem;
if( parent.column() > 0 )
return 0;
if( !parent.isValid() )
parentItem = m_rootNode;
else
parentItem = static_cast<GluonObject*>( parent.internalPointer() );
return parentItem->children().count();
}
QModelIndex CommentsModel::parent( const QModelIndex& child ) const
{
if( !child.isValid() )
return QModelIndex();
GluonObject* childItem = static_cast<GluonObject*>( child.internalPointer() );
GluonObject* parentItem = qobject_cast<GluonObject*> ( childItem->parent() );
if( parentItem == m_rootNode )
return QModelIndex();
GluonObject* grandParentItem = qobject_cast<GluonObject*>( parentItem->parent() );
if( !grandParentItem )
return QModelIndex();
return createIndex( grandParentItem->children().indexOf( parentItem ), 0, parentItem );
}
QModelIndex CommentsModel::index( int row, int column, const QModelIndex& parent ) const
{
if( !hasIndex( row, column, parent ) )
return QModelIndex();
GluonObject* parentItem;
if( !parent.isValid() )
parentItem = m_rootNode;
else
parentItem = static_cast<GluonObject*>( parent.internalPointer() );
GluonObject* childItem = parentItem->child( row );
if( childItem )
return createIndex( row, column, childItem );
else
return QModelIndex();
}
QVariant CommentsModel::headerData( int section, Qt::Orientation orientation, int role ) const
{
if( orientation == Qt::Horizontal && role == Qt::DisplayRole )
return m_columnNames.at( section );
return QVariant();
}
Qt::ItemFlags CommentsModel::flags( const QModelIndex& index ) const
{
if( !index.isValid() )
return Qt::ItemIsEnabled;
return QAbstractItemModel::flags( index );
}
bool CommentsModel::setData( const QModelIndex& index, const QVariant& value, int role )
{
if( index.isValid() && role == Qt::EditRole )
{
GluonObject* node;
node = static_cast<GluonObject*>( index.internalPointer() );
node->setProperty( m_columnNames.at(index.column()).toUtf8(), value );
emit dataChanged( index, index );
return true;
}
return false;
}
bool CommentsModel::insertRows( int row, int count, const QModelIndex& parent )
{
if( count != 1 ) // Do not support more than one row at a time
{
qDebug() << "Can insert only one comment at a time";
return false;
}
if( row != rowCount( parent ) )
{
qDebug() << "Can only add a comment to the end of existing comments";
return false;
}
beginInsertRows( parent, row, row );
GluonObject* parentNode;
parentNode = static_cast<GluonObject*>( parent.internalPointer() );
GluonObject* newNode = new GluonObject( "Comment", parentNode );
parentNode->addChild( newNode );
endInsertRows();
return true;
}
bool CommentsModel::isOnline()
{
return m_isOnline;
}
void CommentsModel::uploadComment( const QModelIndex& parentIndex, const QString& subject, const QString& message )
{
GluonObject* parentNode = static_cast<GluonObject*>( parentIndex.internalPointer() );
Attica::PostJob* job =
AtticaManager::instance()->provider().addNewComment( Attica::Comment::ContentComment,
"128637", "0", parentNode->name(), subject,
message );
connect( job, SIGNAL( finished( Attica::BaseJob* ) ), SLOT( addCommentFinished( Attica::BaseJob* ) ) );
job->start();
}
#include "commentsmodel.moc"
<commit_msg>Player: Add tr() method to the Colum string (commentsmodel).<commit_after>/******************************************************************************
* This file is part of the Gluon Development Platform
* Copyright (C) 2010 Shantanu Tushar <jhahoneyk@gmail.com>
* Copyright (C) 2010 Laszlo Papp <djszapi@archlinux.us>
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 2.1 of the License, or (at your option) any later version.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
*/
#include "commentsmodel.h"
#include "player/lib/atticamanager.h"
#include "core/gluonobject.h"
#include "core/gdlhandler.h"
#include "core/gluon_global.h"
#include "engine/gameproject.h"
#include <attica/comment.h>
#include <attica/listjob.h>
#include <QtCore/QDebug>
#include <QtCore/QFile>
#include <QtCore/QDir>
using namespace GluonCore;
using namespace GluonPlayer;
static const char serviceURI[] = "gamingfreedom.org";
CommentsModel::CommentsModel( QString gameId, QObject* parent )
: QAbstractItemModel( parent )
, m_rootNode( new GluonObject( "Comment" ) )
, m_isOnline( false )
, m_gameId( gameId )
{
m_columnNames << tr("Author") << tr("Title") << tr("Body") << tr("DateTime") << tr("Rating");
loadData(); // Load comments stored locally
updateData(); // Fetch latest comments from the web service
}
void CommentsModel::updateData()
{
if( AtticaManager::instance()->isProviderValid() )
{
providersUpdated();
}
else
{
connect( AtticaManager::instance(), SIGNAL( gotProvider() ), SLOT( providersUpdated() ) );
}
}
void CommentsModel::providersUpdated()
{
if( AtticaManager::instance()->isProviderValid() )
{
Attica::ListJob<Attica::Comment> *job =
AtticaManager::instance()->provider().requestComments( Attica::Comment::ContentComment,
m_gameId, "0", 0, 100 );
connect( job, SIGNAL( finished( Attica::BaseJob* ) ), SLOT( processFetchedComments( Attica::BaseJob* ) ) );
job->start();
}
else
{
qDebug() << "No providers found.";
}
}
void CommentsModel::processFetchedComments( Attica::BaseJob* job )
{
qDebug() << "Comments Successfully Fetched from the server!";
Attica::ListJob<Attica::Comment> *commentsJob = static_cast<Attica::ListJob<Attica::Comment> *>( job );
if( commentsJob->metadata().error() == Attica::Metadata::NoError )
{
//No error, try to remove exising comments (if any)
//and add new comments
if( m_rootNode )
{
qDeleteAll( m_rootNode->children() );
}
for( int i = 0; i < commentsJob->itemList().count(); ++i )
{
Attica::Comment p( commentsJob->itemList().at( i ) );
addComment( p, m_rootNode );
}
m_isOnline = true;
reset(); //Reset the model to notify views to reload comments
}
else
{
qDebug() << "Could not fetch information";
}
}
void CommentsModel::addCommentFinished( Attica::BaseJob* job )
{
Attica::ListJob<Attica::Comment> *commentsJob = static_cast<Attica::ListJob<Attica::Comment>*>( job );
if( commentsJob->metadata().error() == Attica::Metadata::NoError )
{
updateData();
}
else
{
emit addCommentFailed();
}
}
GluonObject* CommentsModel::addComment( Attica::Comment comment, GluonObject* parent )
{
GluonObject* newComment = new GluonObject( comment.id(), parent );
newComment->setProperty( "Author", comment.user() );
newComment->setProperty( "Title", comment.subject() );
newComment->setProperty( "Body", comment.text() );
newComment->setProperty( "DateTime", comment.date().toString() );
newComment->setProperty( "Rating", comment.score() );
foreach( const Attica::Comment& child, comment.children() )
{
addComment( child, newComment );
}
return newComment;
}
void CommentsModel::loadData()
{
QDir gluonDir = QDir::home();
gluonDir.mkpath( GluonEngine::projectSuffix + "/" + QString( serviceURI ) );
gluonDir.cd( GluonEngine::projectSuffix + "/" + QString( serviceURI ) );
m_rootNode = GluonCore::GDLHandler::instance()->parseGDL( gluonDir.absoluteFilePath( "comments.gdl" ) ).at(0);
}
void CommentsModel::saveData()
{
qDebug() << "Saving data!";
QDir gluonDir = QDir::home();
gluonDir.mkpath( GluonEngine::projectSuffix + "/" + QString( serviceURI ) );
gluonDir.cd( GluonEngine::projectSuffix + "/" + QString( serviceURI ) );
QString filename = gluonDir.absoluteFilePath( "comments.gdl" );
QFile dataFile( filename );
if( !dataFile.open( QIODevice::WriteOnly ) )
qDebug() << "Cannot open the comments file!";
QList<const GluonObject*> comments;
comments.append( m_rootNode );
QTextStream dataWriter( &dataFile );
dataWriter << GluonCore::GDLHandler::instance()->serializeGDL( comments );
dataFile.close();
qDebug() << "Saved";
}
CommentsModel::~CommentsModel()
{
saveData(); //Save data before exiting
delete m_rootNode;
}
QVariant CommentsModel::data( const QModelIndex& index, int role ) const
{
if( role == Qt::DisplayRole || role == Qt::EditRole )
{
GluonObject* node;
node = static_cast<GluonObject*>( index.internalPointer() );
return node->property( m_columnNames.at(index.column()).toUtf8() );
}
return QVariant();
}
int CommentsModel::columnCount( const QModelIndex& parent ) const
{
Q_UNUSED( parent )
return 5;
}
int CommentsModel::rowCount( const QModelIndex& parent ) const
{
GluonObject* parentItem;
if( parent.column() > 0 )
return 0;
if( !parent.isValid() )
parentItem = m_rootNode;
else
parentItem = static_cast<GluonObject*>( parent.internalPointer() );
return parentItem->children().count();
}
QModelIndex CommentsModel::parent( const QModelIndex& child ) const
{
if( !child.isValid() )
return QModelIndex();
GluonObject* childItem = static_cast<GluonObject*>( child.internalPointer() );
GluonObject* parentItem = qobject_cast<GluonObject*> ( childItem->parent() );
if( parentItem == m_rootNode )
return QModelIndex();
GluonObject* grandParentItem = qobject_cast<GluonObject*>( parentItem->parent() );
if( !grandParentItem )
return QModelIndex();
return createIndex( grandParentItem->children().indexOf( parentItem ), 0, parentItem );
}
QModelIndex CommentsModel::index( int row, int column, const QModelIndex& parent ) const
{
if( !hasIndex( row, column, parent ) )
return QModelIndex();
GluonObject* parentItem;
if( !parent.isValid() )
parentItem = m_rootNode;
else
parentItem = static_cast<GluonObject*>( parent.internalPointer() );
GluonObject* childItem = parentItem->child( row );
if( childItem )
return createIndex( row, column, childItem );
else
return QModelIndex();
}
QVariant CommentsModel::headerData( int section, Qt::Orientation orientation, int role ) const
{
if( orientation == Qt::Horizontal && role == Qt::DisplayRole )
return m_columnNames.at( section );
return QVariant();
}
Qt::ItemFlags CommentsModel::flags( const QModelIndex& index ) const
{
if( !index.isValid() )
return Qt::ItemIsEnabled;
return QAbstractItemModel::flags( index );
}
bool CommentsModel::setData( const QModelIndex& index, const QVariant& value, int role )
{
if( index.isValid() && role == Qt::EditRole )
{
GluonObject* node;
node = static_cast<GluonObject*>( index.internalPointer() );
node->setProperty( m_columnNames.at(index.column()).toUtf8(), value );
emit dataChanged( index, index );
return true;
}
return false;
}
bool CommentsModel::insertRows( int row, int count, const QModelIndex& parent )
{
if( count != 1 ) // Do not support more than one row at a time
{
qDebug() << "Can insert only one comment at a time";
return false;
}
if( row != rowCount( parent ) )
{
qDebug() << "Can only add a comment to the end of existing comments";
return false;
}
beginInsertRows( parent, row, row );
GluonObject* parentNode;
parentNode = static_cast<GluonObject*>( parent.internalPointer() );
GluonObject* newNode = new GluonObject( "Comment", parentNode );
parentNode->addChild( newNode );
endInsertRows();
return true;
}
bool CommentsModel::isOnline()
{
return m_isOnline;
}
void CommentsModel::uploadComment( const QModelIndex& parentIndex, const QString& subject, const QString& message )
{
GluonObject* parentNode = static_cast<GluonObject*>( parentIndex.internalPointer() );
Attica::PostJob* job =
AtticaManager::instance()->provider().addNewComment( Attica::Comment::ContentComment,
"128637", "0", parentNode->name(), subject,
message );
connect( job, SIGNAL( finished( Attica::BaseJob* ) ), SLOT( addCommentFinished( Attica::BaseJob* ) ) );
job->start();
}
#include "commentsmodel.moc"
<|endoftext|> |
<commit_before>void AliAnalysisTaskSEVertexingHFTest()
{
//
// Test macro for the AliAnalysisTaskSE for heavy-flavour vertexing
// A.Dainese, andrea.dainese@lnl.infn.it
//
Bool_t inputAOD=kFALSE; // otherwise, ESD
Bool_t createAOD=kTRUE; // kTRUE: create AOD and use it as input to vertexing
// kFALSE: use ESD as input to vertexing
Bool_t writeKineToAOD = kFALSE;
TString mode="local"; // otherwise, "grid"
Bool_t useParFiles=kFALSE;
gROOT->LoadMacro("$ALICE_ROOT/PWG3/vertexingHF/macros/LoadLibraries.C");
LoadLibraries(useParFiles);
TChain *chain = 0;
if(mode=="local") {
// Local files
TString treeName,fileName;
if(inputAOD) {
treeName="aodTree";
fileName="AliAOD.root";
} else {
treeName="esdTree";
fileName="AliESDs.root";
}
chain = new TChain(treeName.Data());
chain->Add(fileName.Data());
} else if (mode=="grid") {
//Fetch files with AliEn :
const char *collectionfile = "Collection.xml";
TGrid::Connect("alien://") ;
TAlienCollection *coll = TAlienCollection::Open(collectionfile);
if(inputAOD) { // input AOD
chain = new TChain("aodTree");
while(coll->Next()) chain->Add(coll->GetTURL(""));
} else { // input ESD
//Create an AliRunTagCuts and an AliEventTagCuts Object and impose some selection criteria
AliRunTagCuts *runCuts = new AliRunTagCuts();
AliEventTagCuts *eventCuts = new AliEventTagCuts();
AliLHCTagCuts *lhcCuts = new AliLHCTagCuts();
AliDetectorTagCuts *detCuts = new AliDetectorTagCuts();
eventCuts->SetMultiplicityRange(0,20000);
//Create an AliTagAnalysis Object and chain the tags
AliTagAnalysis *tagAna = new AliTagAnalysis();
tagAna->SetType("ESD");
TGridResult *tagResult = coll->GetGridResult("",0,0);
tagResult->Print();
tagAna->ChainGridTags(tagResult);
//Create a new esd chain and assign the chain that is returned by querying the tags
chain = tagAna->QueryTags(runCuts,lhcCuts,detCuts,eventCuts);
}
} else {
printf("ERROR: mode has to be \"local\" or \"grid\" \n");
return;
}
// Create the analysis manager
AliAnalysisManager *mgr = new AliAnalysisManager("My Manager","My Manager");
mgr->SetDebugLevel(10);
// Input Handler
AliInputEventHandler *inputHandler = 0;
if(inputAOD) {
inputHandler = new AliAODInputHandler();
} else {
inputHandler = new AliESDInputHandler();
}
mgr->SetInputEventHandler(inputHandler);
// Output
AliAODHandler *aodHandler = new AliAODHandler();
const char* deltaAODfname="AliAOD.VertexingHF.root";
if(createAOD) {
aodHandler->SetOutputFileName("AliAOD.root");
} else {
aodHandler->SetFillAOD(kFALSE);
aodHandler->SetOutputFileName(deltaAODfname);
aodHandler->SetCreateNonStandardAOD();
}
mgr->SetOutputEventHandler(aodHandler);
mgr->RegisterExtraFile(deltaAODfname);
if(!inputAOD && createAOD) {
// MC Truth
AliMCEventHandler* mcHandler = new AliMCEventHandler();
if(writeKineToAOD) mgr->SetMCtruthEventHandler(mcHandler);
AliAnalysisTaskMCParticleFilter *kinefilter = new AliAnalysisTaskMCParticleFilter("Particle Filter");
if(writeKineToAOD) mgr->AddTask(kinefilter);
// Barrel Tracks
AliAnalysisTaskESDfilter *filter = new AliAnalysisTaskESDfilter("Filter");
mgr->AddTask(filter);
AliESDtrackCuts* esdTrackCutsHF = new AliESDtrackCuts("AliESDtrackCuts", "Heavy flavour");
esdTrackCutsHF->SetClusterRequirementITS(AliESDtrackCuts::kSPD,AliESDtrackCuts::kAny);
AliAnalysisFilter* trackFilter = new AliAnalysisFilter("trackFilter");
trackFilter->AddCuts(esdTrackCutsHF);
filter->SetTrackFilter(trackFilter);
// Pipelining
mgr->ConnectInput(filter,0,mgr->GetCommonInputContainer());
mgr->ConnectOutput(filter,0,mgr->GetCommonOutputContainer());
if(writeKineToAOD) {
mgr->ConnectInput(kinefilter,0,mgr->GetCommonInputContainer());
mgr->ConnectOutput(kinefilter,0,mgr->GetCommonOutputContainer());
}
}
// Vertexing analysis task
gROOT->LoadMacro("$ALICE_ROOT/PWG3/vertexingHF/macros/AddTaskVertexingHF.C");
AliAnalysisTaskSEVertexingHF *hfTask = AddTaskVertexingHF(deltaAODfname);
//
// Run the analysis
//
printf("CHAIN HAS %d ENTRIES\n",(Int_t)chain->GetEntries());
if(!mgr->InitAnalysis()) return;
mgr->PrintStatus();
TStopwatch watch;
watch.Start();
mgr->StartAnalysis(mode.Data(),chain);
watch.Stop();
watch.Print();
return;
}
<commit_msg>Fix for AOD->AOD+delta case (Andrei)<commit_after>void AliAnalysisTaskSEVertexingHFTest()
{
//
// Test macro for the AliAnalysisTaskSE for heavy-flavour vertexing
// A.Dainese, andrea.dainese@lnl.infn.it
//
Bool_t inputAOD=kFALSE; // otherwise, ESD
Bool_t createAOD=kTRUE; // kTRUE: create AOD and use it as input to vertexing
// kFALSE: use ESD as input to vertexing
Bool_t writeKineToAOD = kFALSE;
TString mode="local"; // otherwise, "grid"
Bool_t useParFiles=kFALSE;
gROOT->LoadMacro("$ALICE_ROOT/PWG3/vertexingHF/macros/LoadLibraries.C");
LoadLibraries(useParFiles);
TChain *chain = 0;
if(mode=="local") {
// Local files
TString treeName,fileName;
if(inputAOD) {
treeName="aodTree";
fileName="AliAOD.root";
} else {
treeName="esdTree";
fileName="AliESDs.root";
}
chain = new TChain(treeName.Data());
chain->Add(fileName.Data());
} else if (mode=="grid") {
//Fetch files with AliEn :
const char *collectionfile = "Collection.xml";
TGrid::Connect("alien://") ;
TAlienCollection *coll = TAlienCollection::Open(collectionfile);
if(inputAOD) { // input AOD
chain = new TChain("aodTree");
while(coll->Next()) chain->Add(coll->GetTURL(""));
} else { // input ESD
//Create an AliRunTagCuts and an AliEventTagCuts Object and impose some selection criteria
AliRunTagCuts *runCuts = new AliRunTagCuts();
AliEventTagCuts *eventCuts = new AliEventTagCuts();
AliLHCTagCuts *lhcCuts = new AliLHCTagCuts();
AliDetectorTagCuts *detCuts = new AliDetectorTagCuts();
eventCuts->SetMultiplicityRange(0,20000);
//Create an AliTagAnalysis Object and chain the tags
AliTagAnalysis *tagAna = new AliTagAnalysis();
tagAna->SetType("ESD");
TGridResult *tagResult = coll->GetGridResult("",0,0);
tagResult->Print();
tagAna->ChainGridTags(tagResult);
//Create a new esd chain and assign the chain that is returned by querying the tags
chain = tagAna->QueryTags(runCuts,lhcCuts,detCuts,eventCuts);
}
} else {
printf("ERROR: mode has to be \"local\" or \"grid\" \n");
return;
}
// Create the analysis manager
AliAnalysisManager *mgr = new AliAnalysisManager("My Manager","My Manager");
mgr->SetDebugLevel(10);
// Input Handler
AliInputEventHandler *inputHandler = 0;
if(inputAOD) {
inputHandler = new AliAODInputHandler();
} else {
inputHandler = new AliESDInputHandler();
}
mgr->SetInputEventHandler(inputHandler);
// Output
AliAODHandler *aodHandler = new AliAODHandler();
const char* deltaAODfname="AliAOD.VertexingHF.root";
if(createAOD) {
aodHandler->SetOutputFileName("AliAOD.root");
} else {
aodHandler->SetOutputFileName(deltaAODfname);
aodHandler->SetAODExtensionMode();
}
mgr->SetOutputEventHandler(aodHandler);
mgr->RegisterExtraFile(deltaAODfname);
if(!inputAOD && createAOD) {
// MC Truth
AliMCEventHandler* mcHandler = new AliMCEventHandler();
if(writeKineToAOD) mgr->SetMCtruthEventHandler(mcHandler);
AliAnalysisTaskMCParticleFilter *kinefilter = new AliAnalysisTaskMCParticleFilter("Particle Filter");
if(writeKineToAOD) mgr->AddTask(kinefilter);
// Barrel Tracks
AliAnalysisTaskESDfilter *filter = new AliAnalysisTaskESDfilter("Filter");
mgr->AddTask(filter);
AliESDtrackCuts* esdTrackCutsHF = new AliESDtrackCuts("AliESDtrackCuts", "Heavy flavour");
esdTrackCutsHF->SetClusterRequirementITS(AliESDtrackCuts::kSPD,AliESDtrackCuts::kAny);
AliAnalysisFilter* trackFilter = new AliAnalysisFilter("trackFilter");
trackFilter->AddCuts(esdTrackCutsHF);
filter->SetTrackFilter(trackFilter);
// Pipelining
mgr->ConnectInput(filter,0,mgr->GetCommonInputContainer());
mgr->ConnectOutput(filter,0,mgr->GetCommonOutputContainer());
if(writeKineToAOD) {
mgr->ConnectInput(kinefilter,0,mgr->GetCommonInputContainer());
mgr->ConnectOutput(kinefilter,0,mgr->GetCommonOutputContainer());
}
}
// Vertexing analysis task
gROOT->LoadMacro("$ALICE_ROOT/PWG3/vertexingHF/macros/AddTaskVertexingHF.C");
AliAnalysisTaskSEVertexingHF *hfTask = AddTaskVertexingHF(deltaAODfname);
//
// Run the analysis
//
printf("CHAIN HAS %d ENTRIES\n",(Int_t)chain->GetEntries());
if(!mgr->InitAnalysis()) return;
mgr->PrintStatus();
TStopwatch watch;
watch.Start();
mgr->StartAnalysis(mode.Data(),chain);
watch.Stop();
watch.Print();
return;
}
<|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/command_line.h"
#include "chrome/browser/browser.h"
#include "chrome/browser/debugger/devtools_client_host.h"
#include "chrome/browser/debugger/devtools_manager.h"
#include "chrome/browser/debugger/devtools_window.h"
#include "chrome/browser/renderer_host/render_view_host.h"
#include "chrome/browser/tab_contents/tab_contents.h"
#include "chrome/common/chrome_switches.h"
#include "chrome/common/notification_registrar.h"
#include "chrome/common/notification_service.h"
#include "chrome/test/in_process_browser_test.h"
#include "chrome/test/ui_test_utils.h"
namespace {
// Used to block until a dev tools client window's browser is closed.
class BrowserClosedObserver : public NotificationObserver {
public:
BrowserClosedObserver(Browser* browser) {
registrar_.Add(this, NotificationType::BROWSER_CLOSED,
Source<Browser>(browser));
ui_test_utils::RunMessageLoop();
}
virtual void Observe(NotificationType type,
const NotificationSource& source,
const NotificationDetails& details) {
MessageLoopForUI::current()->Quit();
}
private:
NotificationRegistrar registrar_;
DISALLOW_COPY_AND_ASSIGN(BrowserClosedObserver);
};
// The delay waited in some cases where we don't have a notifications for an
// action we take.
const int kActionDelayMs = 500;
const wchar_t kConsoleTestPage[] = L"files/devtools/console_test_page.html";
const wchar_t kDebuggerTestPage[] = L"files/devtools/debugger_test_page.html";
const wchar_t kEvalTestPage[] = L"files/devtools/eval_test_page.html";
const wchar_t kJsPage[] = L"files/devtools/js_page.html";
const wchar_t kResourceTestPage[] = L"files/devtools/resource_test_page.html";
const wchar_t kSimplePage[] = L"files/devtools/simple_page.html";
class DevToolsSanityTest : public InProcessBrowserTest {
public:
DevToolsSanityTest() {
set_show_window(true);
EnableDOMAutomation();
}
protected:
void RunTest(const std::string& test_name, const std::wstring& test_page) {
OpenDevToolsWindow(test_page);
std::string result;
// At first check that JavaScript part of the front-end is loaded by
// checking that global variable uiTests exists(it's created after all js
// files have been loaded) and has runTest method.
ASSERT_TRUE(
ui_test_utils::ExecuteJavaScriptAndExtractString(
client_contents_->render_view_host(),
L"",
L"window.domAutomationController.send("
L"'' + (window.uiTests && (typeof uiTests.runTest)));",
&result));
if (result == "function") {
ASSERT_TRUE(
ui_test_utils::ExecuteJavaScriptAndExtractString(
client_contents_->render_view_host(),
L"",
UTF8ToWide(StringPrintf("uiTests.runTest('%s')",
test_name.c_str())),
&result));
EXPECT_EQ("[OK]", result);
} else {
FAIL() << "DevTools front-end is broken.";
}
CloseDevToolsWindow();
}
void OpenDevToolsWindow(const std::wstring& test_page) {
HTTPTestServer* server = StartHTTPServer();
GURL url = server->TestServerPageW(test_page);
ui_test_utils::NavigateToURL(browser(), url);
TabContents* tab = browser()->GetTabContentsAt(0);
inspected_rvh_ = tab->render_view_host();
DevToolsManager* devtools_manager = DevToolsManager::GetInstance();
devtools_manager->OpenDevToolsWindow(inspected_rvh_);
DevToolsClientHost* client_host =
devtools_manager->GetDevToolsClientHostFor(inspected_rvh_);
window_ = client_host->AsDevToolsWindow();
RenderViewHost* client_rvh = window_->GetRenderViewHost();
client_contents_ = client_rvh->delegate()->GetAsTabContents();
ui_test_utils::WaitForNavigation(&client_contents_->controller());
}
void CloseDevToolsWindow() {
DevToolsManager* devtools_manager = DevToolsManager::GetInstance();
// UnregisterDevToolsClientHostFor may destroy window_ so store the browser
// first.
Browser* browser = window_->browser();
devtools_manager->UnregisterDevToolsClientHostFor(inspected_rvh_);
BrowserClosedObserver close_observer(browser);
}
TabContents* client_contents_;
DevToolsWindow* window_;
RenderViewHost* inspected_rvh_;
};
// WebInspector opens.
IN_PROC_BROWSER_TEST_F(DevToolsSanityTest, TestHostIsPresent) {
RunTest("testHostIsPresent", kSimplePage);
}
// Tests elements panel basics.
IN_PROC_BROWSER_TEST_F(DevToolsSanityTest, TestElementsTreeRoot) {
RunTest("testElementsTreeRoot", kSimplePage);
}
// Tests main resource load.
IN_PROC_BROWSER_TEST_F(DevToolsSanityTest, TestMainResource) {
RunTest("testMainResource", kSimplePage);
}
// Tests resources panel enabling.
IN_PROC_BROWSER_TEST_F(DevToolsSanityTest, TestEnableResourcesTab) {
RunTest("testEnableResourcesTab", kSimplePage);
}
// Tests resource headers.
IN_PROC_BROWSER_TEST_F(DevToolsSanityTest, TestResourceHeaders) {
RunTest("testResourceHeaders", kResourceTestPage);
}
// Tests profiler panel.
IN_PROC_BROWSER_TEST_F(DevToolsSanityTest, TestProfilerTab) {
RunTest("testProfilerTab", kJsPage);
}
// Tests scripts panel showing.
// http://crbug.com/16767
IN_PROC_BROWSER_TEST_F(DevToolsSanityTest, TestShowScriptsTab) {
RunTest("testShowScriptsTab", kDebuggerTestPage);
}
// Tests set breakpoint.
// http://crbug.com/16767
IN_PROC_BROWSER_TEST_F(DevToolsSanityTest, TestSetBreakpoint) {
RunTest("testSetBreakpoint", kDebuggerTestPage);
}
// Tests that 'Pause' button works for eval.
IN_PROC_BROWSER_TEST_F(DevToolsSanityTest, DISABLED_TestPauseInEval) {
RunTest("testPauseInEval", kDebuggerTestPage);
}
// Tests console eval.
IN_PROC_BROWSER_TEST_F(DevToolsSanityTest, TestConsoleEval) {
RunTest("testConsoleEval", kConsoleTestPage);
}
// Tests console log.
IN_PROC_BROWSER_TEST_F(DevToolsSanityTest, TestConsoleLog) {
RunTest("testConsoleLog", kConsoleTestPage);
}
// Tests eval global values.
IN_PROC_BROWSER_TEST_F(DevToolsSanityTest, TestEvalGlobal) {
RunTest("testEvalGlobal", kEvalTestPage);
}
// Tests eval on call frame.
IN_PROC_BROWSER_TEST_F(DevToolsSanityTest, TestEvalCallFrame) {
RunTest("testEvalCallFrame", kEvalTestPage);
}
} // namespace
<commit_msg>Disable interactive_ui_tests failing as of WebKit merge 48098:48155 due to upstream breakage.<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/command_line.h"
#include "chrome/browser/browser.h"
#include "chrome/browser/debugger/devtools_client_host.h"
#include "chrome/browser/debugger/devtools_manager.h"
#include "chrome/browser/debugger/devtools_window.h"
#include "chrome/browser/renderer_host/render_view_host.h"
#include "chrome/browser/tab_contents/tab_contents.h"
#include "chrome/common/chrome_switches.h"
#include "chrome/common/notification_registrar.h"
#include "chrome/common/notification_service.h"
#include "chrome/test/in_process_browser_test.h"
#include "chrome/test/ui_test_utils.h"
namespace {
// Used to block until a dev tools client window's browser is closed.
class BrowserClosedObserver : public NotificationObserver {
public:
BrowserClosedObserver(Browser* browser) {
registrar_.Add(this, NotificationType::BROWSER_CLOSED,
Source<Browser>(browser));
ui_test_utils::RunMessageLoop();
}
virtual void Observe(NotificationType type,
const NotificationSource& source,
const NotificationDetails& details) {
MessageLoopForUI::current()->Quit();
}
private:
NotificationRegistrar registrar_;
DISALLOW_COPY_AND_ASSIGN(BrowserClosedObserver);
};
// The delay waited in some cases where we don't have a notifications for an
// action we take.
const int kActionDelayMs = 500;
const wchar_t kConsoleTestPage[] = L"files/devtools/console_test_page.html";
const wchar_t kDebuggerTestPage[] = L"files/devtools/debugger_test_page.html";
const wchar_t kEvalTestPage[] = L"files/devtools/eval_test_page.html";
const wchar_t kJsPage[] = L"files/devtools/js_page.html";
const wchar_t kResourceTestPage[] = L"files/devtools/resource_test_page.html";
const wchar_t kSimplePage[] = L"files/devtools/simple_page.html";
class DevToolsSanityTest : public InProcessBrowserTest {
public:
DevToolsSanityTest() {
set_show_window(true);
EnableDOMAutomation();
}
protected:
void RunTest(const std::string& test_name, const std::wstring& test_page) {
OpenDevToolsWindow(test_page);
std::string result;
// At first check that JavaScript part of the front-end is loaded by
// checking that global variable uiTests exists(it's created after all js
// files have been loaded) and has runTest method.
ASSERT_TRUE(
ui_test_utils::ExecuteJavaScriptAndExtractString(
client_contents_->render_view_host(),
L"",
L"window.domAutomationController.send("
L"'' + (window.uiTests && (typeof uiTests.runTest)));",
&result));
if (result == "function") {
ASSERT_TRUE(
ui_test_utils::ExecuteJavaScriptAndExtractString(
client_contents_->render_view_host(),
L"",
UTF8ToWide(StringPrintf("uiTests.runTest('%s')",
test_name.c_str())),
&result));
EXPECT_EQ("[OK]", result);
} else {
FAIL() << "DevTools front-end is broken.";
}
CloseDevToolsWindow();
}
void OpenDevToolsWindow(const std::wstring& test_page) {
HTTPTestServer* server = StartHTTPServer();
GURL url = server->TestServerPageW(test_page);
ui_test_utils::NavigateToURL(browser(), url);
TabContents* tab = browser()->GetTabContentsAt(0);
inspected_rvh_ = tab->render_view_host();
DevToolsManager* devtools_manager = DevToolsManager::GetInstance();
devtools_manager->OpenDevToolsWindow(inspected_rvh_);
DevToolsClientHost* client_host =
devtools_manager->GetDevToolsClientHostFor(inspected_rvh_);
window_ = client_host->AsDevToolsWindow();
RenderViewHost* client_rvh = window_->GetRenderViewHost();
client_contents_ = client_rvh->delegate()->GetAsTabContents();
ui_test_utils::WaitForNavigation(&client_contents_->controller());
}
void CloseDevToolsWindow() {
DevToolsManager* devtools_manager = DevToolsManager::GetInstance();
// UnregisterDevToolsClientHostFor may destroy window_ so store the browser
// first.
Browser* browser = window_->browser();
devtools_manager->UnregisterDevToolsClientHostFor(inspected_rvh_);
BrowserClosedObserver close_observer(browser);
}
TabContents* client_contents_;
DevToolsWindow* window_;
RenderViewHost* inspected_rvh_;
};
// WebInspector opens.
IN_PROC_BROWSER_TEST_F(DevToolsSanityTest, TestHostIsPresent) {
RunTest("testHostIsPresent", kSimplePage);
}
// Tests elements panel basics.
IN_PROC_BROWSER_TEST_F(DevToolsSanityTest, DISABLED_TestElementsTreeRoot) {
RunTest("testElementsTreeRoot", kSimplePage);
}
// Tests main resource load.
IN_PROC_BROWSER_TEST_F(DevToolsSanityTest, DISABLED_TestMainResource) {
RunTest("testMainResource", kSimplePage);
}
// Tests resources panel enabling.
IN_PROC_BROWSER_TEST_F(DevToolsSanityTest, DISABLED_TestEnableResourcesTab) {
RunTest("testEnableResourcesTab", kSimplePage);
}
// Tests resource headers.
IN_PROC_BROWSER_TEST_F(DevToolsSanityTest, DISABLED_TestResourceHeaders) {
RunTest("testResourceHeaders", kResourceTestPage);
}
// Tests profiler panel.
IN_PROC_BROWSER_TEST_F(DevToolsSanityTest, DISABLED_TestProfilerTab) {
RunTest("testProfilerTab", kJsPage);
}
// Tests scripts panel showing.
// http://crbug.com/16767
IN_PROC_BROWSER_TEST_F(DevToolsSanityTest, DISABLED_TestShowScriptsTab) {
RunTest("testShowScriptsTab", kDebuggerTestPage);
}
// Tests set breakpoint.
// http://crbug.com/16767
IN_PROC_BROWSER_TEST_F(DevToolsSanityTest, DISABLED_TestSetBreakpoint) {
RunTest("testSetBreakpoint", kDebuggerTestPage);
}
// Tests that 'Pause' button works for eval.
IN_PROC_BROWSER_TEST_F(DevToolsSanityTest, DISABLED_TestPauseInEval) {
RunTest("testPauseInEval", kDebuggerTestPage);
}
// Tests console eval.
IN_PROC_BROWSER_TEST_F(DevToolsSanityTest, DISABLED_TestConsoleEval) {
RunTest("testConsoleEval", kConsoleTestPage);
}
// Tests console log.
IN_PROC_BROWSER_TEST_F(DevToolsSanityTest, DISABLED_TestConsoleLog) {
RunTest("testConsoleLog", kConsoleTestPage);
}
// Tests eval global values.
IN_PROC_BROWSER_TEST_F(DevToolsSanityTest, DISABLED_TestEvalGlobal) {
RunTest("testEvalGlobal", kEvalTestPage);
}
// Tests eval on call frame.
IN_PROC_BROWSER_TEST_F(DevToolsSanityTest, TestEvalCallFrame) {
RunTest("testEvalCallFrame", kEvalTestPage);
}
} // namespace
<|endoftext|> |
<commit_before>/***************************************************************************
Anders Knospe - last modified on 26 March 2016
//Lauches phi analysis with rsn mini package
//Allows basic configuration of pile-up check and event cuts
****************************************************************************/
enum pairYCutSet { kPairDefault=0,
kCentral //=1
};
enum eventCutSet { kEvtDefault=0,
kNoPileUpCut, //=1
kDefaultVtx12,//=2
kDefaultVtx8, //=3
kDefaultVtx5, //=4
kMCEvtDefault, //=5
kSpecial1, //=6
kSpecial2, //=7
kNoEvtSel, //=8
kSpecial3, //=9
kSpecial4, //=10
kSpecial5 //=11
};
enum eventMixConfig { kDisabled = -1,
kMixDefault,//=0 //10 events, Dvz = 1cm, DC = 10
k5Evts, //=1 //5 events, Dvz = 1cm, DC = 10
k5Cent, //=2 //10 events, Dvz = 1cm, DC = 5
k5Evts5Cent
};
AliRsnMiniAnalysisTask * AddTaskPhiPP5TeV_PID
(
Bool_t isMC=kFALSE,
Bool_t isPP=kTRUE,
TString outNameSuffix="tpc2stof3sveto",
Int_t evtCutSetID=0,
Int_t pairCutSetID=0,
Int_t mixingConfigID=0,
Int_t aodFilterBit=5,
Int_t customQualityCutsID=1,
AliRsnCutSetDaughterParticle::ERsnDaughterCutSet cutKaCandidate=AliRsnCutSetDaughterParticle::kTPCpidTOFveto3s,
Float_t nsigmaKa=2.,
Bool_t enableMonitor=kTRUE,
Bool_t IsMcTrueOnly=kFALSE,
TString monitorOpt="NoSIGN",
Bool_t useMixLS=0,
Bool_t checkReflex=0,
AliRsnMiniValue::EType yaxisvar=AliRsnMiniValue::kPt,
TString polarizationOpt="" /* J - Jackson,T - Transversity */
)
{
//-------------------------------------------
// event cuts
//-------------------------------------------
UInt_t triggerMask=AliVEvent::kINT7;
Bool_t rejectPileUp=kTRUE;
Double_t vtxZcut=10.0;//cm, default cut on vtx z
Int_t MultBins=aodFilterBit/100;
if(evtCutSetID==eventCutSet::kDefaultVtx12) vtxZcut=12.0; //cm
if(evtCutSetID==eventCutSet::kDefaultVtx8) vtxZcut=8.0; //cm
if(evtCutSetID==eventCutSet::kDefaultVtx5) vtxZcut=5.0; //cm
if(evtCutSetID==eventCutSet::kNoPileUpCut) rejectPileUp=kFALSE;
if(evtCutSetID==eventCutSet::kSpecial2) vtxZcut=1.e6;//off
if(!isPP || isMC || MultBins) rejectPileUp=kFALSE;
//-------------------------------------------
//pair cuts
//-------------------------------------------
Double_t minYlab=-0.5;
Double_t maxYlab= 0.5;
if(pairCutSetID==pairYCutSet::kCentral){//|y_cm|<0.3
minYlab=-0.3; maxYlab=0.3;
}
//-------------------------------------------
//mixing settings
//-------------------------------------------
Int_t nmix=0;
Float_t maxDiffVzMix=1.;
Float_t maxDiffMultMix=10.;
if(mixingConfigID==eventMixConfig::kMixDefault) nmix=10;
if(mixingConfigID==eventMixConfig::k5Evts) nmix=5;
if(mixingConfigID==eventMixConfig::k5Cent) maxDiffMultMix=5;
if(mixingConfigID==eventMixConfig::k5Evts5Cent){nmix=5; maxDiffMultMix=5;}
// -- INITIALIZATION ----------------------------------------------------------------------------
// retrieve analysis manager
AliAnalysisManager* mgr=AliAnalysisManager::GetAnalysisManager();
if(!mgr){
::Error("AddTaskPhiPP5TeV_PID", "No analysis manager to connect to.");
return NULL;
}
// create the task and configure
TString taskName=Form("phi%s%s_%i%i",(isPP? "pp" : "PbPb"),(isMC ? "MC" : "Data"),(Int_t)cutKaCandidate);
AliRsnMiniAnalysisTask* task=new AliRsnMiniAnalysisTask(taskName.Data(),isMC);
if(evtCutSetID==eventCutSet::kSpecial4 || evtCutSetID==eventCutSet::kSpecial5) task->UseESDTriggerMask(triggerMask); //ESD ****** check this *****
if(evtCutSetID!=eventCutSet::kNoEvtSel && evtCutSetID!=eventCutSet::kSpecial3 && evtCutSetID!=eventCutSet::kSpecial4) task->SelectCollisionCandidates(triggerMask); //AOD
if(isPP){
if(MultBins==1) task->UseMultiplicity("AliMultSelection_V0M");
else if(MultBins==2) task->UseMultiplicity("AliMultSelection_RefMult08");
else task->UseMultiplicity("QUALITY");
}else task->UseCentrality("V0M");
// set event mixing options
task->UseContinuousMix();
//task->UseBinnedMix();
task->SetNMix(nmix);
task->SetMaxDiffVz(maxDiffVzMix);
task->SetMaxDiffMult(maxDiffMultMix);
::Info("AddTaskPhiPP5TeV_PID", Form("Event mixing configuration: \n events to mix = %i \n max diff. vtxZ = cm %5.3f \n max diff multi = %5.3f", nmix, maxDiffVzMix, maxDiffMultMix));
mgr->AddTask(task);
// cut on primary vertex:
// - 2nd argument --> |Vz| range
// - 3rd argument --> minimum required number of contributors to vtx
// - 4th argument --> tells if TPC stand-alone vertexes must be accepted
AliRsnCutPrimaryVertex* cutVertex=0;
if(evtCutSetID!=eventCutSet::kSpecial1 && evtCutSetID!=eventCutSet::kNoEvtSel && (!MultBins || fabs(vtxZcut-10.)>1.e-10)){
cutVertex=new AliRsnCutPrimaryVertex("cutVertex",vtxZcut,0,kFALSE);
if(!MultBins && evtCutSetID!=eventCutSet::kSpecial3){
cutVertex->SetCheckZResolutionSPD();
cutVertex->SetCheckDispersionSPD();
cutVertex->SetCheckZDifferenceSPDTrack();
}
if (evtCutSetID==eventCutSet::kSpecial3) cutVertex->SetCheckGeneratedVertexZ();
}
AliRsnCutEventUtils* cutEventUtils=0;
if(evtCutSetID!=eventCutSet::kNoEvtSel && evtCutSetID!=eventCutSet::kSpecial3){
cutEventUtils=new AliRsnCutEventUtils("cutEventUtils",kTRUE,rejectPileUp);
if(!MultBins){
cutEventUtils->SetCheckIncompleteDAQ();
cutEventUtils->SetCheckSPDClusterVsTrackletBG();
}else{
//cutEventUtils->SetCheckInelGt0SPDtracklets();
cutEventUtils->SetRemovePileUppA2013(kFALSE);
cutEventUtils->SetCheckAcceptedMultSelection();
}
}
if(isPP && (!isMC) && cutVertex){
cutVertex->SetCheckPileUp(rejectPileUp);// set the check for pileup
::Info("AddTaskPhiPP5TeV_PID", Form(":::::::::::::::::: Pile-up rejection mode: %s", (rejectPileUp)?"ON":"OFF"));
}
// define and fill cut set for event cut
AliRsnCutSet* eventCuts=0;
if(cutEventUtils || cutVertex){
eventCuts=new AliRsnCutSet("eventCuts",AliRsnTarget::kEvent);
if(cutEventUtils && cutVertex){
eventCuts->AddCut(cutEventUtils);
eventCuts->AddCut(cutVertex);
eventCuts->SetCutScheme(Form("%s&%s",cutEventUtils->GetName(),cutVertex->GetName()));
}else if(cutEventUtils && !cutVertex){
eventCuts->AddCut(cutEventUtils);
eventCuts->SetCutScheme(Form("%s",cutEventUtils->GetName()));
}else if(!cutEventUtils && cutVertex){
eventCuts->AddCut(cutVertex);
eventCuts->SetCutScheme(Form("%s",cutVertex->GetName()));
}
task->SetEventCuts(eventCuts);
}
//-- EVENT-ONLY COMPUTATIONS -------------------------------------------------------------------
//vertex
Int_t vtxID=task->CreateValue(AliRsnMiniValue::kVz,kFALSE);
AliRsnMiniOutput* outVtx=task->CreateOutput("eventVtx","HIST","EVENT");
outVtx->AddAxis(vtxID,240,-12.0,12.0);
//multiplicity or centrality
Int_t multID=task->CreateValue(AliRsnMiniValue::kMult,kFALSE);
AliRsnMiniOutput* outMult=task->CreateOutput("eventMult","HIST","EVENT");
if(isPP && !MultBins) outMult->AddAxis(multID,400,0.5,400.5);
else outMult->AddAxis(multID,110,0.,110.);
TH2F* hvz=new TH2F("hVzVsCent","",110,0.,110., 240,-12.0,12.0);
task->SetEventQAHist("vz",hvz);//plugs this histogram into the fHAEventVz data member
TH2F* hmc=new TH2F("MultiVsCent","", 110,0.,110., 400,0.5,400.5);
hmc->GetYaxis()->SetTitle("QUALITY");
task->SetEventQAHist("multicent",hmc);//plugs this histogram into the fHAEventMultiCent data member
// -- PAIR CUTS (common to all resonances) ------------------------------------------------------
AliRsnCutMiniPair* cutY=new AliRsnCutMiniPair("cutRapidity",AliRsnCutMiniPair::kRapidityRange);
cutY->SetRangeD(minYlab,maxYlab);
AliRsnCutSet* cutsPair=new AliRsnCutSet("pairCuts",AliRsnTarget::kMother);
cutsPair->AddCut(cutY);
cutsPair->SetCutScheme(cutY->GetName());
// -- CONFIG ANALYSIS --------------------------------------------------------------------------
gROOT->LoadMacro("$ALICE_PHYSICS/PWGLF/RESONANCES/macros/mini/ConfigPhiPP5TeV_PID.C");
if(!ConfigPhiPP5TeV_PID(task,isMC,isPP,"",cutsPair,aodFilterBit,customQualityCutsID,cutKaCandidate,nsigmaKa,enableMonitor,isMC&IsMcTrueOnly,monitorOpt.Data(),useMixLS,isMC&checkReflex,yaxisvar,polarizationOpt)) return 0x0;
// -- CONTAINERS --------------------------------------------------------------------------------
TString outputFileName = AliAnalysisManager::GetCommonFileName();
// outputFileName += ":Rsn";
Printf("AddAnalysisTaskPhiPP5TeV_PID - Set OutputFileName : \n %s\n",outputFileName.Data());
AliAnalysisDataContainer* output=mgr->CreateContainer(Form("RsnOut_%s",outNameSuffix.Data()),
TList::Class(),
AliAnalysisManager::kOutputContainer,
outputFileName);
mgr->ConnectInput(task, 0, mgr->GetCommonInputContainer());
mgr->ConnectOutput(task, 1, output);
return task;
}
<commit_msg>Modification on macro to select true INEL>0 events for calculations of the signal-loss and event-loss corrections for multiplicity-dependent analyses<commit_after>/***************************************************************************
Anders Knospe - last modified on 26 March 2016
Sushanta Tripathy - last modified on 14 April 2018
//Lauches phi analysis with rsn mini package
//Allows basic configuration of pile-up check and event cuts
****************************************************************************/
enum pairYCutSet { kPairDefault=0,
kCentral //=1
};
enum eventCutSet { kEvtDefault=0,
kNoPileUpCut, //=1
kDefaultVtx12,//=2
kDefaultVtx8, //=3
kDefaultVtx5, //=4
kMCEvtDefault, //=5
kSpecial1, //=6
kSpecial2, //=7
kNoEvtSel, //=8
kSpecial3, //=9
kSpecial4, //=10
kSpecial5, //=11
kSpecial6 //=12 (only for multiplicity analyses)
};
enum eventMixConfig { kDisabled = -1,
kMixDefault,//=0 //10 events, Dvz = 1cm, DC = 10
k5Evts, //=1 //5 events, Dvz = 1cm, DC = 10
k5Cent, //=2 //10 events, Dvz = 1cm, DC = 5
k5Evts5Cent
};
AliRsnMiniAnalysisTask * AddTaskPhiPP5TeV_PID
(
Bool_t isMC=kFALSE,
Bool_t isPP=kTRUE,
TString outNameSuffix="tpc2stof3sveto",
Int_t evtCutSetID=0,
Int_t pairCutSetID=0,
Int_t mixingConfigID=0,
Int_t aodFilterBit=5,
Int_t customQualityCutsID=1,
AliRsnCutSetDaughterParticle::ERsnDaughterCutSet cutKaCandidate=AliRsnCutSetDaughterParticle::kTPCpidTOFveto3s,
Float_t nsigmaKa=2.,
Bool_t enableMonitor=kTRUE,
Bool_t IsMcTrueOnly=kFALSE,
TString monitorOpt="NoSIGN",
Bool_t useMixLS=0,
Bool_t checkReflex=0,
AliRsnMiniValue::EType yaxisvar=AliRsnMiniValue::kPt,
TString polarizationOpt="" /* J - Jackson,T - Transversity */
)
{
//-------------------------------------------
// event cuts
//-------------------------------------------
UInt_t triggerMask=AliVEvent::kINT7;
Bool_t rejectPileUp=kTRUE;
Double_t vtxZcut=10.0;//cm, default cut on vtx z
Int_t MultBins=aodFilterBit/100;
if(evtCutSetID==eventCutSet::kDefaultVtx12) vtxZcut=12.0; //cm
if(evtCutSetID==eventCutSet::kDefaultVtx8) vtxZcut=8.0; //cm
if(evtCutSetID==eventCutSet::kDefaultVtx5) vtxZcut=5.0; //cm
if(evtCutSetID==eventCutSet::kNoPileUpCut) rejectPileUp=kFALSE;
if(evtCutSetID==eventCutSet::kSpecial2) vtxZcut=1.e6;//off
if(!isPP || isMC || MultBins) rejectPileUp=kFALSE;
//-------------------------------------------
//pair cuts
//-------------------------------------------
Double_t minYlab=-0.5;
Double_t maxYlab= 0.5;
if(pairCutSetID==pairYCutSet::kCentral){//|y_cm|<0.3
minYlab=-0.3; maxYlab=0.3;
}
//-------------------------------------------
//mixing settings
//-------------------------------------------
Int_t nmix=0;
Float_t maxDiffVzMix=1.;
Float_t maxDiffMultMix=10.;
if(mixingConfigID==eventMixConfig::kMixDefault) nmix=10;
if(mixingConfigID==eventMixConfig::k5Evts) nmix=5;
if(mixingConfigID==eventMixConfig::k5Cent) maxDiffMultMix=5;
if(mixingConfigID==eventMixConfig::k5Evts5Cent){nmix=5; maxDiffMultMix=5;}
// -- INITIALIZATION ----------------------------------------------------------------------------
// retrieve analysis manager
AliAnalysisManager* mgr=AliAnalysisManager::GetAnalysisManager();
if(!mgr){
::Error("AddTaskPhiPP5TeV_PID", "No analysis manager to connect to.");
return NULL;
}
// create the task and configure
TString taskName=Form("phi%s%s_%i%i",(isPP? "pp" : "PbPb"),(isMC ? "MC" : "Data"),(Int_t)cutKaCandidate);
AliRsnMiniAnalysisTask* task=new AliRsnMiniAnalysisTask(taskName.Data(),isMC);
if(evtCutSetID==eventCutSet::kSpecial4 || evtCutSetID==eventCutSet::kSpecial5) task->UseESDTriggerMask(triggerMask); //ESD ****** check this *****
if(evtCutSetID!=eventCutSet::kNoEvtSel && evtCutSetID!=eventCutSet::kSpecial3 && evtCutSetID!=eventCutSet::kSpecial4 && evtCutSetID!=eventCutSet::kSpecial6) task->SelectCollisionCandidates(triggerMask); //AOD
if(isPP){
if(MultBins==1) task->UseMultiplicity("AliMultSelection_V0M");
else if(MultBins==2) task->UseMultiplicity("AliMultSelection_RefMult08");
else task->UseMultiplicity("QUALITY");
}else task->UseCentrality("V0M");
// set event mixing options
task->UseContinuousMix();
//task->UseBinnedMix();
task->SetNMix(nmix);
task->SetMaxDiffVz(maxDiffVzMix);
task->SetMaxDiffMult(maxDiffMultMix);
::Info("AddTaskPhiPP5TeV_PID", Form("Event mixing configuration: \n events to mix = %i \n max diff. vtxZ = cm %5.3f \n max diff multi = %5.3f", nmix, maxDiffVzMix, maxDiffMultMix));
mgr->AddTask(task);
// cut on primary vertex:
// - 2nd argument --> |Vz| range
// - 3rd argument --> minimum required number of contributors to vtx
// - 4th argument --> tells if TPC stand-alone vertexes must be accepted
AliRsnCutPrimaryVertex* cutVertex=0;
if(evtCutSetID!=eventCutSet::kSpecial1 && evtCutSetID!=eventCutSet::kNoEvtSel && (!MultBins || fabs(vtxZcut-10.)>1.e-10)){
cutVertex=new AliRsnCutPrimaryVertex("cutVertex",vtxZcut,0,kFALSE);
if(!MultBins && evtCutSetID!=eventCutSet::kSpecial3){
cutVertex->SetCheckZResolutionSPD();
cutVertex->SetCheckDispersionSPD();
cutVertex->SetCheckZDifferenceSPDTrack();
}
if (evtCutSetID==eventCutSet::kSpecial3 && kSpecial6) cutVertex->SetCheckGeneratedVertexZ();
}
AliRsnCutEventUtils* cutEventUtils=0;
if(evtCutSetID!=eventCutSet::kNoEvtSel && evtCutSetID!=eventCutSet::kSpecial3){
cutEventUtils=new AliRsnCutEventUtils("cutEventUtils",kTRUE,rejectPileUp);
if(!MultBins){
cutEventUtils->SetCheckIncompleteDAQ();
cutEventUtils->SetCheckSPDClusterVsTrackletBG();
}else{
//cutEventUtils->SetCheckInelGt0SPDtracklets();
cutEventUtils->SetRemovePileUppA2013(kFALSE);
cutEventUtils->SetCheckAcceptedMultSelection();
if (isMC && kSpecial6) cutEventUtils->SetCheckInelGt0MC();
}
}
if(isPP && (!isMC) && cutVertex){
cutVertex->SetCheckPileUp(rejectPileUp);// set the check for pileup
::Info("AddTaskPhiPP5TeV_PID", Form(":::::::::::::::::: Pile-up rejection mode: %s", (rejectPileUp)?"ON":"OFF"));
}
// define and fill cut set for event cut
AliRsnCutSet* eventCuts=0;
if(cutEventUtils || cutVertex){
eventCuts=new AliRsnCutSet("eventCuts",AliRsnTarget::kEvent);
if(cutEventUtils && cutVertex){
eventCuts->AddCut(cutEventUtils);
eventCuts->AddCut(cutVertex);
eventCuts->SetCutScheme(Form("%s&%s",cutEventUtils->GetName(),cutVertex->GetName()));
}else if(cutEventUtils && !cutVertex){
eventCuts->AddCut(cutEventUtils);
eventCuts->SetCutScheme(Form("%s",cutEventUtils->GetName()));
}else if(!cutEventUtils && cutVertex){
eventCuts->AddCut(cutVertex);
eventCuts->SetCutScheme(Form("%s",cutVertex->GetName()));
}
task->SetEventCuts(eventCuts);
}
//-- EVENT-ONLY COMPUTATIONS -------------------------------------------------------------------
//vertex
Int_t vtxID=task->CreateValue(AliRsnMiniValue::kVz,kFALSE);
AliRsnMiniOutput* outVtx=task->CreateOutput("eventVtx","HIST","EVENT");
outVtx->AddAxis(vtxID,240,-12.0,12.0);
//multiplicity or centrality
Int_t multID=task->CreateValue(AliRsnMiniValue::kMult,kFALSE);
AliRsnMiniOutput* outMult=task->CreateOutput("eventMult","HIST","EVENT");
if(isPP && !MultBins) outMult->AddAxis(multID,400,0.5,400.5);
else outMult->AddAxis(multID,110,0.,110.);
TH2F* hvz=new TH2F("hVzVsCent","",110,0.,110., 240,-12.0,12.0);
task->SetEventQAHist("vz",hvz);//plugs this histogram into the fHAEventVz data member
TH2F* hmc=new TH2F("MultiVsCent","", 110,0.,110., 400,0.5,400.5);
hmc->GetYaxis()->SetTitle("QUALITY");
task->SetEventQAHist("multicent",hmc);//plugs this histogram into the fHAEventMultiCent data member
// -- PAIR CUTS (common to all resonances) ------------------------------------------------------
AliRsnCutMiniPair* cutY=new AliRsnCutMiniPair("cutRapidity",AliRsnCutMiniPair::kRapidityRange);
cutY->SetRangeD(minYlab,maxYlab);
AliRsnCutSet* cutsPair=new AliRsnCutSet("pairCuts",AliRsnTarget::kMother);
cutsPair->AddCut(cutY);
cutsPair->SetCutScheme(cutY->GetName());
// -- CONFIG ANALYSIS --------------------------------------------------------------------------
gROOT->LoadMacro("$ALICE_PHYSICS/PWGLF/RESONANCES/macros/mini/ConfigPhiPP5TeV_PID.C");
if(!ConfigPhiPP5TeV_PID(task,isMC,isPP,"",cutsPair,aodFilterBit,customQualityCutsID,cutKaCandidate,nsigmaKa,enableMonitor,isMC&IsMcTrueOnly,monitorOpt.Data(),useMixLS,isMC&checkReflex,yaxisvar,polarizationOpt)) return 0x0;
// -- CONTAINERS --------------------------------------------------------------------------------
TString outputFileName = AliAnalysisManager::GetCommonFileName();
// outputFileName += ":Rsn";
Printf("AddAnalysisTaskPhiPP5TeV_PID - Set OutputFileName : \n %s\n",outputFileName.Data());
AliAnalysisDataContainer* output=mgr->CreateContainer(Form("RsnOut_%s",outNameSuffix.Data()),
TList::Class(),
AliAnalysisManager::kOutputContainer,
outputFileName);
mgr->ConnectInput(task, 0, mgr->GetCommonInputContainer());
mgr->ConnectOutput(task, 1, output);
return task;
}
<|endoftext|> |
<commit_before>/** @file
Plugin to perform background fetches of certain content that would
otherwise not be cached. For example, Range: requests / responses.
@section license License
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 "configs.h"
// Read a config file, populare the linked list (chain the BgFetchRule's)
bool
BgFetchConfig::readConfig(const char *config_file)
{
char file_path[4096];
TSFile file;
if (nullptr == config_file) {
TSError("[%s] invalid config file", PLUGIN_NAME);
return false;
}
TSDebug(PLUGIN_NAME, "trying to open config file in this path: %s", config_file);
file = TSfopen(config_file, "r");
if (nullptr == file) {
TSDebug(PLUGIN_NAME, "Failed to open config file %s, trying rel path", config_file);
snprintf(file_path, sizeof(file_path), "%s/%s", TSInstallDirGet(), config_file);
file = TSfopen(file_path, "r");
if (nullptr == file) {
TSError("[%s] invalid config file", PLUGIN_NAME);
return false;
}
}
BgFetchRule *cur = nullptr;
char buffer[8192];
memset(buffer, 0, sizeof(buffer));
while (TSfgets(file, buffer, sizeof(buffer) - 1) != nullptr) {
char *eol = nullptr;
// make sure line was not bigger than buffer
if (nullptr == (eol = strchr(buffer, '\n')) && nullptr == (eol = strstr(buffer, "\r\n"))) {
TSError("[%s] exclusion line too long, did not get a good line in cfg, skipping, line: %s", PLUGIN_NAME, buffer);
memset(buffer, 0, sizeof(buffer));
continue;
}
// make sure line has something useful on it
if (eol - buffer < 2 || buffer[0] == '#') {
memset(buffer, 0, sizeof(buffer));
continue;
}
char *savePtr = nullptr;
char *cfg = strtok_r(buffer, "\n\r\n", &savePtr);
if (nullptr != cfg) {
TSDebug(PLUGIN_NAME, "setting background_fetch exclusion criterion based on string: %s", cfg);
char *cfg_type = strtok_r(buffer, " ", &savePtr);
char *cfg_name = nullptr;
char *cfg_value = nullptr;
bool exclude = false;
if (cfg_type) {
if (!strcmp(cfg_type, "exclude")) {
exclude = true;
} else if (strcmp(cfg_type, "include")) {
TSError("[%s] invalid specifier %s, skipping config line", PLUGIN_NAME, cfg_type);
memset(buffer, 0, sizeof(buffer));
continue;
}
cfg_name = strtok_r(nullptr, " ", &savePtr);
if (cfg_name) {
cfg_value = strtok_r(nullptr, " ", &savePtr);
if (cfg_value) {
if (!strcmp(cfg_name, "Content-Length")) {
if ((cfg_value[0] != '<') && (cfg_value[0] != '>')) {
TSError("[%s] invalid content-len condition %s, skipping config value", PLUGIN_NAME, cfg_value);
memset(buffer, 0, sizeof(buffer));
continue;
}
}
BgFetchRule *r = new BgFetchRule(exclude, cfg_name, cfg_value);
if (nullptr == cur) {
_rules = r;
} else {
cur->chain(r);
}
cur = r;
TSDebug(PLUGIN_NAME, "adding background_fetch exclusion rule %d for %s: %s", exclude, cfg_name, cfg_value);
} else {
TSError("[%s] invalid value %s, skipping config line", PLUGIN_NAME, cfg_name);
}
}
}
memset(buffer, 0, sizeof(buffer));
}
}
TSfclose(file);
TSDebug(PLUGIN_NAME, "Done parsing config");
return true;
}
<commit_msg>TS-5050: The background_fetch plugin fails to check for config files relative to the config dir etc/trafficserver.<commit_after>/** @file
Plugin to perform background fetches of certain content that would
otherwise not be cached. For example, Range: requests / responses.
@section license License
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 "configs.h"
// Read a config file, populare the linked list (chain the BgFetchRule's)
bool
BgFetchConfig::readConfig(const char *config_file)
{
char file_path[4096];
TSFile file;
if (nullptr == config_file) {
TSError("[%s] invalid config file", PLUGIN_NAME);
return false;
}
TSDebug(PLUGIN_NAME, "trying to open config file in this path: %s", config_file);
if (*config_file == '/') {
snprintf(file_path, sizeof(file_path), "%s", config_file);
} else {
snprintf(file_path, sizeof(file_path), "%s/%s", TSConfigDirGet(), config_file);
}
TSDebug(PLUGIN_NAME, "Chosen config file is at: %s", file_path);
file = TSfopen(file_path, "r");
if (nullptr == file) {
TSError("[%s] invalid config file: %s", PLUGIN_NAME, file_path);
return false;
}
BgFetchRule *cur = nullptr;
char buffer[8192];
memset(buffer, 0, sizeof(buffer));
while (TSfgets(file, buffer, sizeof(buffer) - 1) != nullptr) {
char *eol = nullptr;
// make sure line was not bigger than buffer
if (nullptr == (eol = strchr(buffer, '\n')) && nullptr == (eol = strstr(buffer, "\r\n"))) {
TSError("[%s] exclusion line too long, did not get a good line in cfg, skipping, line: %s", PLUGIN_NAME, buffer);
memset(buffer, 0, sizeof(buffer));
continue;
}
// make sure line has something useful on it
if (eol - buffer < 2 || buffer[0] == '#') {
memset(buffer, 0, sizeof(buffer));
continue;
}
char *savePtr = nullptr;
char *cfg = strtok_r(buffer, "\n\r\n", &savePtr);
if (nullptr != cfg) {
TSDebug(PLUGIN_NAME, "setting background_fetch exclusion criterion based on string: %s", cfg);
char *cfg_type = strtok_r(buffer, " ", &savePtr);
char *cfg_name = nullptr;
char *cfg_value = nullptr;
bool exclude = false;
if (cfg_type) {
if (!strcmp(cfg_type, "exclude")) {
exclude = true;
} else if (strcmp(cfg_type, "include")) {
TSError("[%s] invalid specifier %s, skipping config line", PLUGIN_NAME, cfg_type);
memset(buffer, 0, sizeof(buffer));
continue;
}
cfg_name = strtok_r(nullptr, " ", &savePtr);
if (cfg_name) {
cfg_value = strtok_r(nullptr, " ", &savePtr);
if (cfg_value) {
if (!strcmp(cfg_name, "Content-Length")) {
if ((cfg_value[0] != '<') && (cfg_value[0] != '>')) {
TSError("[%s] invalid content-len condition %s, skipping config value", PLUGIN_NAME, cfg_value);
memset(buffer, 0, sizeof(buffer));
continue;
}
}
BgFetchRule *r = new BgFetchRule(exclude, cfg_name, cfg_value);
if (nullptr == cur) {
_rules = r;
} else {
cur->chain(r);
}
cur = r;
TSDebug(PLUGIN_NAME, "adding background_fetch exclusion rule %d for %s: %s", exclude, cfg_name, cfg_value);
} else {
TSError("[%s] invalid value %s, skipping config line", PLUGIN_NAME, cfg_name);
}
}
}
memset(buffer, 0, sizeof(buffer));
}
}
TSfclose(file);
TSDebug(PLUGIN_NAME, "Done parsing config");
return true;
}
<|endoftext|> |
<commit_before>#include "stdafx.h"
#include "ed.h"
#include "mainframe.h"
#include <algorithm>
ApplicationFrame::ApplicationFrame ()
: mouse (kbdq), frame_index (1)
{
auto_save_count = 0;
ime_composition = 0;
ime_open_mode = kbd_queue::IME_MODE_OFF;
sleep_timer_exhausted = 0;
last_vkeycode = -1;
kbd_repeat_count = 0;
wait_cursor_depth = 0;
f_in_drop = 0;
drop_window = 0;
drag_window = 0;
drag_buffer = 0;
f_protect_quit = 0;
hwnd_clipboard = 0;
last_cmd_tick = GetTickCount ();
f_auto_save_pending = 0;
default_caret_blink_time = 0;
last_blink_caret = 0;
lquit_char = make_char ('G' - '@');
quit_vkey = 'G';
quit_mod = MOD_CONTROL;
minibuffer_prompt_column = -1;
mframe = new main_frame();
lminibuffer_prompt = Qnil;
lminibuffer_message = Qnil;
memset((void*)&active_frame, 0, sizeof(active_frame));
a_next = 0;
}
ApplicationFrame::~ApplicationFrame ()
{
mframe->cleanup();
delete mframe;
Buffer::remove_application_frame_cache (this);
}
ApplicationFrame *root = NULL;
static void inline ensure_root()
{
if(root == NULL)
{
root = new ApplicationFrame();
}
}
ApplicationFrame& active_app_frame()
{
ensure_root();
return *root;
}
main_frame& active_main_frame()
{
ensure_root();
return *root->mframe;
}
ApplicationFrame *first_app_frame() { ensure_root(); return root; }
ApplicationFrame* retrieve_app_frame(HWND hwnd)
{
return (ApplicationFrame *)GetWindowLong (hwnd, 0);
}
#include <vector>
static std::vector<ApplicationFrame*> g_floating_frames;
static std::vector<ApplicationFrame*> g_startup_second_pending_frames;
void app_frame_gc_mark(void (*f)(lisp))
{
for(ApplicationFrame *app1 = root; app1; app1 = app1->a_next)
{
Window *wp;
for (wp = app1->active_frame.windows; wp; wp = wp->w_next)
(*f) (wp->lwp);
for (wp = app1->active_frame.reserved; wp; wp = wp->w_next)
(*f) (wp->lwp);
for (wp = app1->active_frame.deleted; wp; wp = wp->w_next)
(*f) (wp->lwp);
app1->mframe->gc_mark(f);
(*f)(app1->lminibuffer_message);
(*f)(app1->lminibuffer_prompt);
(*f)(app1->lquit_char);
(*f)(app1->lfp);
app1->user_timer.gc_mark (f);
}
}
// this needs all appframe, so implement in this file.
void
Window::modify_all_mode_line ()
{
for(ApplicationFrame *app1 = root; app1; app1 = app1->a_next)
{
for (Window *wp = app1->active_frame.windows; wp; wp = wp->w_next)
wp->w_disp_flags |= WDF_MODELINE;
}
}
void insert_app_frame(HWND hwnd, ApplicationFrame *app1)
{
SetWindowLong (hwnd, 0, LONG (app1));
}
bool is_last_app_frame()
{
if(root == NULL || root->a_next == NULL)
return true;
return false;
}
static void change_root_frame(ApplicationFrame *app1)
{
if (root == app1) // do nothing.
return;
ApplicationFrame *cur = root;
ApplicationFrame *prev = cur;
while(cur != app1)
{
prev = cur;
cur = cur->a_next;
}
assert(prev->a_next == app1);
prev->a_next = app1->a_next;
app1->a_next = root;
root = app1;
}
void notify_focus(ApplicationFrame *app1)
{
if (root == app1) // do nothing.
return;
/*
most of the case, hs_focus turn off at KILL_FOCUS.
But when inside read_minibuffer, defer_focus should update caret and other information even if they are inside eval call.
So I apply re_focus in defer_focus_change, and that make has_focus non-zero in some case.
*/
root->active_frame.has_focus = 0;
change_root_frame(app1);
kbd_queue::change_application_window = true;
for(Window* wp = root->active_frame.windows; wp; wp = wp->w_next)
wp->update_window();
}
static void unchain_app_frame(ApplicationFrame* app1)
{
if(root == app1){
root = app1->a_next;
app1->a_next = 0;
return;
}
ApplicationFrame *app = root;
while(app->a_next != app1)
{
app = app->a_next;
}
app->a_next = app1->a_next;
app1->a_next = 0;
}
void delete_app_frame(ApplicationFrame *app1)
{
unchain_app_frame(app1);
// delete app1;
g_floating_frames.push_back(app1);
kbd_queue::change_application_window = true;
// notify_focus(root);
}
extern void remove_menus(ApplicationFrame* app);
void delete_floating_app_frame()
{
for(std::vector<ApplicationFrame*>::iterator it = g_floating_frames.begin(); it != g_floating_frames.end(); it++)
{
ApplicationFrame *app1 = *it;
remove_menus(app1);
delete app1;
}
g_floating_frames.clear();
}
void call_all_startup_frame_second()
{
for(std::vector<ApplicationFrame*>::iterator itr = g_startup_second_pending_frames.begin(); itr != g_startup_second_pending_frames.end(); itr++)
{
ApplicationFrame *app1 = *itr;
change_root_frame(app1);
if (xsymbol_function (Vstartup_frame_second) == Qunbound
|| xsymbol_function (Vstartup_frame_second) == Qnil)
return;
suppress_gc sgc;
try
{
funcall_1 (Vstartup_frame_second, app1->lfp);
}
catch (nonlocal_jump &)
{
print_condition (nonlocal_jump::data());
}
}
g_startup_second_pending_frames.clear();
}
extern int init_app(HINSTANCE hinst, ApplicationFrame* app1, ApplicationFrame* parent);
ApplicationFrame *
ApplicationFrame::coerce_to_frame (lisp object)
{
if (!object || object == Qnil)
return &active_app_frame ();
check_appframe (object);
if (!xappframe_fp (object))
FEprogram_error (Edeleted_window);
return xappframe_fp (object);
}
// --- below here is lisp functions.
lisp
Fmake_frame (lisp opt)
{
ApplicationFrame *parent = root;
HINSTANCE hinst = root->hinst;
if (Qnil == selected_buffer(root)->run_hook_while_success (Vbefore_make_frame_hook))
return Qnil;
Window* window = selected_window (root);
if (window)
{
window->save_buffer_params ();
}
u_long new_app_index = 1;
{
std::vector<u_long> v;
for (ApplicationFrame *app1 = root; app1; app1 = app1->a_next)
v.push_back (app1->frame_index);
if (!v.empty ())
{
std::sort( v.begin (), v.end () );
for (std::vector<u_long>::const_iterator it = v.begin (); it != v.end (); ++it, ++new_app_index)
if (*it != new_app_index) break;
}
}
ApplicationFrame* new_app = new ApplicationFrame();
ApplicationFrame* next = root->a_next;
root->a_next = new_app;
new_app->a_next = next;
g_startup_second_pending_frames.push_back(new_app);
new_app->frame_index = new_app_index;
init_app(hinst, new_app, parent);
defer_change_focus::request_change_focus(new_app);
return new_app->lfp;
}
lisp
Fselected_frame ()
{
assert (xappframe_fp (active_app_frame ().lfp));
assert (xappframe_fp (active_app_frame ().lfp) == &active_app_frame ());
return active_app_frame ().lfp;
}
// ignore minibufp now.
lisp
Fnext_frame (lisp frame, lisp minibufp)
{
ApplicationFrame *app = ApplicationFrame::coerce_to_frame(frame);
ApplicationFrame *next = app->a_next;
if (!next)
next = first_app_frame();
return next->lfp;
}
lisp
Fframe_list ()
{
ApplicationFrame *app1 = first_app_frame();
lisp result = xcons (app1->lfp, Qnil);
lisp p = result;
for(app1 = app1->a_next; app1; app1 = app1->a_next)
{
xcdr (p) = xcons (app1->lfp, Qnil);
p = xcdr (p);
}
return result;
}
lisp
Fother_frame ()
{
ApplicationFrame *app1 = first_app_frame();
if(app1->a_next)
{
SetFocus(app1->a_next->toplev);
return Qt;
}
return Qnil;
}
lisp
Fdelete_frame (lisp frame, lisp force)
{
ApplicationFrame *app = ApplicationFrame::coerce_to_frame(frame);
try
{
selected_buffer(app)->run_hook (Vdelete_frame_functions, app->lfp);
}
catch (nonlocal_jump &)
{
print_condition (nonlocal_jump::data ());
}
if(!is_last_app_frame())
{
DestroyWindow (app->toplev);
return Qnil;
}
if(force != Qt)
return Qnil;
Fkill_xyzzy();
return Qnil;
}
lisp
Fselect_frame (lisp frame)
{
ApplicationFrame *app = ApplicationFrame::coerce_to_frame (frame);
if (app)
{
SetFocus (app->toplev);
return Qt;
}
else
{
return Qnil;
}
}
lisp
Fget_frame_window_handle (lisp frame)
{
ApplicationFrame *app = ApplicationFrame::coerce_to_frame (frame);
if (app)
{
return make_integer (long_to_large_int ((u_long) (app->toplev)));
}
else
{
return Qnil;
}
}
lisp
Fget_frame_index (lisp frame)
{
ApplicationFrame *app = ApplicationFrame::coerce_to_frame (frame);
if (app)
{
return make_integer (long_to_large_int (app->frame_index));
}
else
{
return Qnil;
}
}
<commit_msg>Refactroing: Extract find_open_appframe_id().<commit_after>#include "stdafx.h"
#include "ed.h"
#include "mainframe.h"
#include <algorithm>
ApplicationFrame::ApplicationFrame ()
: mouse (kbdq), frame_index (1)
{
auto_save_count = 0;
ime_composition = 0;
ime_open_mode = kbd_queue::IME_MODE_OFF;
sleep_timer_exhausted = 0;
last_vkeycode = -1;
kbd_repeat_count = 0;
wait_cursor_depth = 0;
f_in_drop = 0;
drop_window = 0;
drag_window = 0;
drag_buffer = 0;
f_protect_quit = 0;
hwnd_clipboard = 0;
last_cmd_tick = GetTickCount ();
f_auto_save_pending = 0;
default_caret_blink_time = 0;
last_blink_caret = 0;
lquit_char = make_char ('G' - '@');
quit_vkey = 'G';
quit_mod = MOD_CONTROL;
minibuffer_prompt_column = -1;
mframe = new main_frame();
lminibuffer_prompt = Qnil;
lminibuffer_message = Qnil;
memset((void*)&active_frame, 0, sizeof(active_frame));
a_next = 0;
}
ApplicationFrame::~ApplicationFrame ()
{
mframe->cleanup();
delete mframe;
Buffer::remove_application_frame_cache (this);
}
ApplicationFrame *root = NULL;
static void inline ensure_root()
{
if(root == NULL)
{
root = new ApplicationFrame();
}
}
ApplicationFrame& active_app_frame()
{
ensure_root();
return *root;
}
main_frame& active_main_frame()
{
ensure_root();
return *root->mframe;
}
ApplicationFrame *first_app_frame() { ensure_root(); return root; }
ApplicationFrame* retrieve_app_frame(HWND hwnd)
{
return (ApplicationFrame *)GetWindowLong (hwnd, 0);
}
#include <vector>
static std::vector<ApplicationFrame*> g_floating_frames;
static std::vector<ApplicationFrame*> g_startup_second_pending_frames;
void app_frame_gc_mark(void (*f)(lisp))
{
for(ApplicationFrame *app1 = root; app1; app1 = app1->a_next)
{
Window *wp;
for (wp = app1->active_frame.windows; wp; wp = wp->w_next)
(*f) (wp->lwp);
for (wp = app1->active_frame.reserved; wp; wp = wp->w_next)
(*f) (wp->lwp);
for (wp = app1->active_frame.deleted; wp; wp = wp->w_next)
(*f) (wp->lwp);
app1->mframe->gc_mark(f);
(*f)(app1->lminibuffer_message);
(*f)(app1->lminibuffer_prompt);
(*f)(app1->lquit_char);
(*f)(app1->lfp);
app1->user_timer.gc_mark (f);
}
}
// this needs all appframe, so implement in this file.
void
Window::modify_all_mode_line ()
{
for(ApplicationFrame *app1 = root; app1; app1 = app1->a_next)
{
for (Window *wp = app1->active_frame.windows; wp; wp = wp->w_next)
wp->w_disp_flags |= WDF_MODELINE;
}
}
void insert_app_frame(HWND hwnd, ApplicationFrame *app1)
{
SetWindowLong (hwnd, 0, LONG (app1));
}
bool is_last_app_frame()
{
if(root == NULL || root->a_next == NULL)
return true;
return false;
}
static void change_root_frame(ApplicationFrame *app1)
{
if (root == app1) // do nothing.
return;
ApplicationFrame *cur = root;
ApplicationFrame *prev = cur;
while(cur != app1)
{
prev = cur;
cur = cur->a_next;
}
assert(prev->a_next == app1);
prev->a_next = app1->a_next;
app1->a_next = root;
root = app1;
}
void notify_focus(ApplicationFrame *app1)
{
if (root == app1) // do nothing.
return;
/*
most of the case, hs_focus turn off at KILL_FOCUS.
But when inside read_minibuffer, defer_focus should update caret and other information even if they are inside eval call.
So I apply re_focus in defer_focus_change, and that make has_focus non-zero in some case.
*/
root->active_frame.has_focus = 0;
change_root_frame(app1);
kbd_queue::change_application_window = true;
for(Window* wp = root->active_frame.windows; wp; wp = wp->w_next)
wp->update_window();
}
static void unchain_app_frame(ApplicationFrame* app1)
{
if(root == app1){
root = app1->a_next;
app1->a_next = 0;
return;
}
ApplicationFrame *app = root;
while(app->a_next != app1)
{
app = app->a_next;
}
app->a_next = app1->a_next;
app1->a_next = 0;
}
void delete_app_frame(ApplicationFrame *app1)
{
unchain_app_frame(app1);
// delete app1;
g_floating_frames.push_back(app1);
kbd_queue::change_application_window = true;
// notify_focus(root);
}
extern void remove_menus(ApplicationFrame* app);
void delete_floating_app_frame()
{
for(std::vector<ApplicationFrame*>::iterator it = g_floating_frames.begin(); it != g_floating_frames.end(); it++)
{
ApplicationFrame *app1 = *it;
remove_menus(app1);
delete app1;
}
g_floating_frames.clear();
}
void call_all_startup_frame_second()
{
for(std::vector<ApplicationFrame*>::iterator itr = g_startup_second_pending_frames.begin(); itr != g_startup_second_pending_frames.end(); itr++)
{
ApplicationFrame *app1 = *itr;
change_root_frame(app1);
if (xsymbol_function (Vstartup_frame_second) == Qunbound
|| xsymbol_function (Vstartup_frame_second) == Qnil)
return;
suppress_gc sgc;
try
{
funcall_1 (Vstartup_frame_second, app1->lfp);
}
catch (nonlocal_jump &)
{
print_condition (nonlocal_jump::data());
}
}
g_startup_second_pending_frames.clear();
}
extern int init_app(HINSTANCE hinst, ApplicationFrame* app1, ApplicationFrame* parent);
ApplicationFrame *
ApplicationFrame::coerce_to_frame (lisp object)
{
if (!object || object == Qnil)
return &active_app_frame ();
check_appframe (object);
if (!xappframe_fp (object))
FEprogram_error (Edeleted_window);
return xappframe_fp (object);
}
static u_long
find_open_appframe_id()
{
u_long new_app_index = 1;
{
std::vector<u_long> v;
for (ApplicationFrame *app1 = root; app1; app1 = app1->a_next)
v.push_back (app1->frame_index);
if (!v.empty ())
{
std::sort( v.begin (), v.end () );
for (std::vector<u_long>::const_iterator it = v.begin (); it != v.end (); ++it, ++new_app_index)
if (*it != new_app_index) break;
}
}
return new_app_index;
}
// --- below here is lisp functions.
lisp
Fmake_frame (lisp opt)
{
ApplicationFrame *parent = root;
HINSTANCE hinst = root->hinst;
if (Qnil == selected_buffer(root)->run_hook_while_success (Vbefore_make_frame_hook))
return Qnil;
Window* window = selected_window (root);
if (window)
{
window->save_buffer_params ();
}
u_long new_app_index = find_open_appframe_id();
ApplicationFrame* new_app = new ApplicationFrame();
ApplicationFrame* next = root->a_next;
root->a_next = new_app;
new_app->a_next = next;
g_startup_second_pending_frames.push_back(new_app);
new_app->frame_index = new_app_index;
init_app(hinst, new_app, parent);
defer_change_focus::request_change_focus(new_app);
return new_app->lfp;
}
lisp
Fselected_frame ()
{
assert (xappframe_fp (active_app_frame ().lfp));
assert (xappframe_fp (active_app_frame ().lfp) == &active_app_frame ());
return active_app_frame ().lfp;
}
// ignore minibufp now.
lisp
Fnext_frame (lisp frame, lisp minibufp)
{
ApplicationFrame *app = ApplicationFrame::coerce_to_frame(frame);
ApplicationFrame *next = app->a_next;
if (!next)
next = first_app_frame();
return next->lfp;
}
lisp
Fframe_list ()
{
ApplicationFrame *app1 = first_app_frame();
lisp result = xcons (app1->lfp, Qnil);
lisp p = result;
for(app1 = app1->a_next; app1; app1 = app1->a_next)
{
xcdr (p) = xcons (app1->lfp, Qnil);
p = xcdr (p);
}
return result;
}
lisp
Fother_frame ()
{
ApplicationFrame *app1 = first_app_frame();
if(app1->a_next)
{
SetFocus(app1->a_next->toplev);
return Qt;
}
return Qnil;
}
lisp
Fdelete_frame (lisp frame, lisp force)
{
ApplicationFrame *app = ApplicationFrame::coerce_to_frame(frame);
try
{
selected_buffer(app)->run_hook (Vdelete_frame_functions, app->lfp);
}
catch (nonlocal_jump &)
{
print_condition (nonlocal_jump::data ());
}
if(!is_last_app_frame())
{
DestroyWindow (app->toplev);
return Qnil;
}
if(force != Qt)
return Qnil;
Fkill_xyzzy();
return Qnil;
}
lisp
Fselect_frame (lisp frame)
{
ApplicationFrame *app = ApplicationFrame::coerce_to_frame (frame);
if (app)
{
SetFocus (app->toplev);
return Qt;
}
else
{
return Qnil;
}
}
lisp
Fget_frame_window_handle (lisp frame)
{
ApplicationFrame *app = ApplicationFrame::coerce_to_frame (frame);
if (app)
{
return make_integer (long_to_large_int ((u_long) (app->toplev)));
}
else
{
return Qnil;
}
}
lisp
Fget_frame_index (lisp frame)
{
ApplicationFrame *app = ApplicationFrame::coerce_to_frame (frame);
if (app)
{
return make_integer (long_to_large_int (app->frame_index));
}
else
{
return Qnil;
}
}
<|endoftext|> |
<commit_before>// Copyright 2015 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 "game.h"
#include <math.h>
#include "assets_generated.h"
#include "audio_config_generated.h"
#include "entity/entity.h"
#include "events/play_sound.h"
#include "fplbase/input.h"
#include "fplbase/utilities.h"
#include "input_config_generated.h"
#include "mathfu/glsl_mappings.h"
#include "mathfu/vector.h"
#include "motive/init.h"
#include "motive/io/flatbuffers.h"
#include "motive/math/angle.h"
#include "pindrop/pindrop.h"
#include "world.h"
#ifdef __ANDROID__
#include "fplbase/renderer_android.h"
#endif
#ifdef ANDROID_CARDBOARD
#include "fplbase/renderer_hmd.h"
#endif
using mathfu::vec2i;
using mathfu::vec2;
using mathfu::vec3;
using mathfu::vec4;
using mathfu::mat3;
using mathfu::mat4;
using mathfu::quat;
namespace fpl {
namespace fpl_project {
static const int kQuadNumVertices = 4;
static const int kQuadNumIndices = 6;
static const unsigned short kQuadIndices[] = {0, 1, 2, 2, 1, 3};
static const Attribute kQuadMeshFormat[] = {kPosition3f, kTexCoord2f, kNormal3f,
kTangent4f, kEND};
static const char kAssetsDir[] = "assets";
static const char kConfigFileName[] = "config.bin";
#ifdef __ANDROID__
static const int kAndroidMaxScreenWidth = 1920;
static const int kAndroidMaxScreenHeight = 1080;
#endif
static const vec3 kCameraPos = vec3(4, 5, -10);
static const vec3 kCameraOrientation = vec3(0, 0, 0);
static const vec3 kLightPos = vec3(0, 20, 20);
static const vec3 kCardboardAmbient = vec3(0.75f);
static const vec3 kCardboardDiffuse = vec3(0.85f);
static const vec3 kCardboardSpecular = vec3(0.3f);
static const float kCardboardShininess = 32.0f;
static const float kCardboardNormalMapScale = 0.3f;
static const int kMinUpdateTime = 1000 / 60;
static const int kMaxUpdateTime = 1000 / 30;
static const char* kOpenTypeFontFile = "fonts/NotoSansCJKjp-Bold.otf";
/// kVersion is used by Google developers to identify which
/// applications uploaded to Google Play are derived from this application.
/// This allows the development team at Google to determine the popularity of
/// this application.
/// How it works: Applications that are uploaded to the Google Play Store are
/// scanned for this version string. We track which applications are using it
/// to measure popularity. You are free to remove it (of course) but we would
/// appreciate if you left it in.
static const char kVersion[] = "FPL Project 0.0.1";
Game::Game()
: asset_manager_(renderer_),
event_manager_(EventSinkUnion_Size),
shader_lit_textured_normal_(nullptr),
shader_textured_(nullptr),
prev_world_time_(0),
audio_config_(nullptr),
world_(),
version_(kVersion) {}
// Initialize the 'renderer_' member. No other members have been initialized at
// this point.
bool Game::InitializeRenderer() {
#ifdef __ANDROID__
const vec2i window_size(kAndroidMaxScreenWidth, kAndroidMaxScreenHeight);
#else
const vec2i window_size(1200, 800);
#endif
if (!renderer_.Initialize(window_size, "Window Title!")) {
LogError("Renderer initialization error: %s\n",
renderer_.last_error().c_str());
return false;
}
renderer_.color() = mathfu::kOnes4f;
// Initialize the first frame as black.
renderer_.ClearFrameBuffer(mathfu::kZeros4f);
#ifdef ANDROID_CARDBOARD
vec2i size = AndroidGetScalerResolution();
const vec2i viewport_size =
size.x() && size.y() ? size : renderer_.window_size();
InitializeUndistortFramebuffer(viewport_size.x(), viewport_size.y());
#endif
return true;
}
// Initializes 'vertices' at the specified position, aligned up-and-down.
// 'vertices' must be an array of length kQuadNumVertices.
static void CreateVerticalQuad(const vec3& offset, const vec2& geo_size,
const vec2& texture_coord_size,
NormalMappedVertex* vertices) {
const float half_width = geo_size[0] * 0.5f;
const vec3 bottom_left = offset + vec3(-half_width, 0.0f, 0.0f);
const vec3 top_right = offset + vec3(half_width, 0.0f, geo_size[1]);
vertices[0].pos = bottom_left;
vertices[1].pos = vec3(top_right[0], offset[1], bottom_left[2]);
vertices[2].pos = vec3(bottom_left[0], offset[1], top_right[2]);
vertices[3].pos = top_right;
const float coord_half_width = texture_coord_size[0] * 0.5f;
const vec2 coord_bottom_left(0.5f - coord_half_width, 1.0f);
const vec2 coord_top_right(0.5f + coord_half_width,
1.0f - texture_coord_size[1]);
vertices[0].tc = coord_bottom_left;
vertices[1].tc = vec2(coord_top_right[0], coord_bottom_left[1]);
vertices[2].tc = vec2(coord_bottom_left[0], coord_top_right[1]);
vertices[3].tc = coord_top_right;
Mesh::ComputeNormalsTangents(vertices, &kQuadIndices[0], kQuadNumVertices,
kQuadNumIndices);
}
// Creates a mesh of a single quad (two triangles) vertically upright.
// The quad's has x and y size determined by the size of the texture.
// The quad is offset in (x,y,z) space by the 'offset' variable.
// Returns a mesh with the quad and texture, or nullptr if anything went wrong.
Mesh* Game::CreateVerticalQuadMesh(const char* material_name,
const vec3& offset, const vec2& pixel_bounds,
float pixel_to_world_scale) {
// Don't try to load obviously invalid materials. Suppresses error logs from
// the material manager.
if (material_name == nullptr || material_name[0] == '\0') return nullptr;
// Load the material from file, and check validity.
Material* material = asset_manager_.LoadMaterial(material_name);
bool material_valid = material != nullptr && material->textures().size() > 0;
if (!material_valid) return nullptr;
// Create vertex geometry in proportion to the texture size.
// This is nice for the artist since everything is at the scale of the
// original artwork.
assert(pixel_bounds.x() && pixel_bounds.y());
const vec2 texture_size = vec2(mathfu::RoundUpToPowerOf2(pixel_bounds.x()),
mathfu::RoundUpToPowerOf2(pixel_bounds.y()));
const vec2 texture_coord_size = pixel_bounds / texture_size;
const vec2 geo_size = pixel_bounds * vec2(pixel_to_world_scale);
// Initialize a vertex array in the requested position.
NormalMappedVertex vertices[kQuadNumVertices];
CreateVerticalQuad(offset, geo_size, texture_coord_size, vertices);
// Create mesh and add in quad indices.
Mesh* mesh = new Mesh(vertices, kQuadNumVertices, sizeof(NormalMappedVertex),
kQuadMeshFormat);
mesh->AddIndices(kQuadIndices, kQuadNumIndices, material);
return mesh;
}
// Load textures for cardboard into 'materials_'. The 'renderer_' and
// 'asset_manager_' members have been initialized at this point.
bool Game::InitializeAssets() {
// Load up all of our assets, as defined in the manifest.
// TODO - put this into an asynchronous loding function, like we
// had in pie noon.
const AssetManifest& asset_manifest = GetAssetManifest();
for (size_t i = 0; i < asset_manifest.mesh_list()->size(); i++) {
asset_manager_.LoadMesh(asset_manifest.mesh_list()->Get(i)->c_str());
}
for (size_t i = 0; i < asset_manifest.shader_list()->size(); i++) {
asset_manager_.LoadShader(asset_manifest.shader_list()->Get(i)->c_str());
}
for (size_t i = 0; i < asset_manifest.material_list()->size(); i++) {
asset_manager_.LoadMaterial(
asset_manifest.material_list()->Get(i)->c_str());
}
asset_manager_.StartLoadingTextures();
shader_lit_textured_normal_ =
asset_manager_.LoadShader("shaders/lit_textured_normal");
shader_textured_ = asset_manager_.LoadShader("shaders/textured");
// Load animation table:
anim_table_.InitFromFlatBuffers(*asset_manifest.anims());
// Load all animations referenced by the animation table:
const char* anim_not_found = LoadAnimTableAnimations(&anim_table_, LoadFile);
if (anim_not_found != nullptr) {
LogError("Failed to load animation file %s.\n", anim_not_found);
return false;
}
return true;
}
const Config& Game::GetConfig() const {
return *fpl::fpl_project::GetConfig(config_source_.c_str());
}
const InputConfig& Game::GetInputConfig() const {
return *fpl::fpl_project::GetInputConfig(input_config_source_.c_str());
}
const AssetManifest& Game::GetAssetManifest() const {
return *fpl::fpl_project::GetAssetManifest(asset_manifest_source_.c_str());
}
// Initialize each member in turn. This is logically just one function, since
// the order of initialization cannot be changed. However, it's nice for
// debugging and readability to have each section lexographically separate.
bool Game::Initialize(const char* const binary_directory) {
LogInfo("Zooshi Initializing...");
if (!ChangeToUpstreamDir(binary_directory, kAssetsDir)) return false;
if (!LoadFile(kConfigFileName, &config_source_)) return false;
if (!InitializeRenderer()) return false;
if (!LoadFile(GetConfig().input_config()->c_str(), &input_config_source_))
return false;
if (!LoadFile(GetConfig().assets_filename()->c_str(),
&asset_manifest_source_)) {
return false;
}
if (!InitializeAssets()) return false;
// Some people are having trouble loading the audio engine, and it's not
// strictly necessary for gameplay, so don't die if the audio engine fails to
// initialize.
if (!audio_engine_.Initialize(GetConfig().audio_config()->c_str())) {
LogError("Failed to initialize audio engine.\n");
}
if (!audio_engine_.LoadSoundBank("sound_banks/sound_assets.bin")) {
LogError("Failed to load sound bank.\n");
}
// Wait for everything to finish loading...
while (!asset_manager_.TryFinalize()) {
}
event_manager_.RegisterListener(EventSinkUnion_PlaySound, this);
font_manager_.Open(kOpenTypeFontFile);
font_manager_.SetRenderer(renderer_);
SetRelativeMouseMode(true);
input_controller_.set_input_system(&input_);
input_controller_.set_input_config(&GetInputConfig());
world_.Initialize(GetConfig(), &input_, &asset_manager_,
&world_renderer_, &font_manager_, &audio_engine_,
&event_manager_, &renderer_, &anim_table_);
world_renderer_.Initialize(&world_);
world_editor_.reset(new editor::WorldEditor());
world_editor_->Initialize(GetConfig().world_editor_config(),
&world_.entity_manager, &font_manager_);
world_editor_->AddComponentToUpdate(
component_library::TransformComponent::GetComponentId());
world_editor_->AddComponentToUpdate(
ShadowControllerComponent::GetComponentId());
world_editor_->AddComponentToUpdate(
component_library::RenderMeshComponent::GetComponentId());
pause_state_.Initialize(&input_, &world_, &asset_manager_, &font_manager_);
gameplay_state_.Initialize(&input_, &world_, &GetInputConfig(),
world_editor_.get());
game_menu_state_.Initialize(&input_, &world_, &input_controller_,
&GetConfig(), &asset_manager_,
&font_manager_);
world_editor_state_.Initialize(&renderer_, &input_, world_editor_.get(),
&world_);
state_machine_.AssignState(kGameStateGameplay, &gameplay_state_);
state_machine_.AssignState(kGameStatePause, &pause_state_);
state_machine_.AssignState(kGameStateGameMenu, &game_menu_state_);
state_machine_.AssignState(kGameStateWorldEditor, &world_editor_state_);
state_machine_.SetCurrentStateId(kGameStateGameMenu);
LogInfo("Initialization complete\n");
return true;
}
void Game::SetRelativeMouseMode(bool relative_mouse_mode) {
relative_mouse_mode_ = relative_mouse_mode;
input_.SetRelativeMouseMode(relative_mouse_mode);
}
void Game::ToggleRelativeMouseMode() {
relative_mouse_mode_ = !relative_mouse_mode_;
input_.SetRelativeMouseMode(relative_mouse_mode_);
}
static inline WorldTime CurrentWorldTime() { return GetTicks(); }
void Game::Run() {
// Initialize so that we don't sleep the first time through the loop.
prev_world_time_ = CurrentWorldTime() - kMinUpdateTime;
while (!input_.exit_requested() && !state_machine_.done()) {
// Milliseconds elapsed since last update. To avoid burning through the
// CPU, enforce a minimum time between updates. For example, if
// min_update_time is 1, we will not exceed 1000Hz update time.
const WorldTime world_time = CurrentWorldTime();
const WorldTime delta_time =
std::min(world_time - prev_world_time_, kMaxUpdateTime);
prev_world_time_ = world_time;
if (delta_time < kMinUpdateTime) {
Delay(kMinUpdateTime - delta_time);
}
input_.AdvanceFrame(&renderer_.window_size());
state_machine_.AdvanceFrame(delta_time);
state_machine_.Render(&renderer_);
renderer_.AdvanceFrame(input_.minimized(), input_.Time());
audio_engine_.AdvanceFrame(delta_time / 1000.0f);
// Process input device messages since the last game loop.
// Update render window size.
if (input_.GetButton(fpl::FPLK_BACKQUOTE).went_down()) {
ToggleRelativeMouseMode();
}
}
}
void Game::OnEvent(const event::EventPayload& event_payload) {
switch (event_payload.id()) {
case EventSinkUnion_PlaySound: {
auto* payload = event_payload.ToData<PlaySoundPayload>();
audio_engine_.PlaySound(payload->sound_name, payload->location);
break;
}
default: { assert(false); }
}
}
} // fpl_project
} // fpl
<commit_msg>Removing unused constants about Cardboard shader<commit_after>// Copyright 2015 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 "game.h"
#include <math.h>
#include "assets_generated.h"
#include "audio_config_generated.h"
#include "entity/entity.h"
#include "events/play_sound.h"
#include "fplbase/input.h"
#include "fplbase/utilities.h"
#include "input_config_generated.h"
#include "mathfu/glsl_mappings.h"
#include "mathfu/vector.h"
#include "motive/init.h"
#include "motive/io/flatbuffers.h"
#include "motive/math/angle.h"
#include "pindrop/pindrop.h"
#include "world.h"
#ifdef __ANDROID__
#include "fplbase/renderer_android.h"
#endif
#ifdef ANDROID_CARDBOARD
#include "fplbase/renderer_hmd.h"
#endif
using mathfu::vec2i;
using mathfu::vec2;
using mathfu::vec3;
using mathfu::vec4;
using mathfu::mat3;
using mathfu::mat4;
using mathfu::quat;
namespace fpl {
namespace fpl_project {
static const int kQuadNumVertices = 4;
static const int kQuadNumIndices = 6;
static const unsigned short kQuadIndices[] = {0, 1, 2, 2, 1, 3};
static const Attribute kQuadMeshFormat[] = {kPosition3f, kTexCoord2f, kNormal3f,
kTangent4f, kEND};
static const char kAssetsDir[] = "assets";
static const char kConfigFileName[] = "config.bin";
#ifdef __ANDROID__
static const int kAndroidMaxScreenWidth = 1920;
static const int kAndroidMaxScreenHeight = 1080;
#endif
static const vec3 kCameraPos = vec3(4, 5, -10);
static const vec3 kCameraOrientation = vec3(0, 0, 0);
static const vec3 kLightPos = vec3(0, 20, 20);
static const int kMinUpdateTime = 1000 / 60;
static const int kMaxUpdateTime = 1000 / 30;
static const char* kOpenTypeFontFile = "fonts/NotoSansCJKjp-Bold.otf";
/// kVersion is used by Google developers to identify which
/// applications uploaded to Google Play are derived from this application.
/// This allows the development team at Google to determine the popularity of
/// this application.
/// How it works: Applications that are uploaded to the Google Play Store are
/// scanned for this version string. We track which applications are using it
/// to measure popularity. You are free to remove it (of course) but we would
/// appreciate if you left it in.
static const char kVersion[] = "FPL Project 0.0.1";
Game::Game()
: asset_manager_(renderer_),
event_manager_(EventSinkUnion_Size),
shader_lit_textured_normal_(nullptr),
shader_textured_(nullptr),
prev_world_time_(0),
audio_config_(nullptr),
world_(),
version_(kVersion) {}
// Initialize the 'renderer_' member. No other members have been initialized at
// this point.
bool Game::InitializeRenderer() {
#ifdef __ANDROID__
const vec2i window_size(kAndroidMaxScreenWidth, kAndroidMaxScreenHeight);
#else
const vec2i window_size(1200, 800);
#endif
if (!renderer_.Initialize(window_size, "Window Title!")) {
LogError("Renderer initialization error: %s\n",
renderer_.last_error().c_str());
return false;
}
renderer_.color() = mathfu::kOnes4f;
// Initialize the first frame as black.
renderer_.ClearFrameBuffer(mathfu::kZeros4f);
#ifdef ANDROID_CARDBOARD
vec2i size = AndroidGetScalerResolution();
const vec2i viewport_size =
size.x() && size.y() ? size : renderer_.window_size();
InitializeUndistortFramebuffer(viewport_size.x(), viewport_size.y());
#endif
return true;
}
// Initializes 'vertices' at the specified position, aligned up-and-down.
// 'vertices' must be an array of length kQuadNumVertices.
static void CreateVerticalQuad(const vec3& offset, const vec2& geo_size,
const vec2& texture_coord_size,
NormalMappedVertex* vertices) {
const float half_width = geo_size[0] * 0.5f;
const vec3 bottom_left = offset + vec3(-half_width, 0.0f, 0.0f);
const vec3 top_right = offset + vec3(half_width, 0.0f, geo_size[1]);
vertices[0].pos = bottom_left;
vertices[1].pos = vec3(top_right[0], offset[1], bottom_left[2]);
vertices[2].pos = vec3(bottom_left[0], offset[1], top_right[2]);
vertices[3].pos = top_right;
const float coord_half_width = texture_coord_size[0] * 0.5f;
const vec2 coord_bottom_left(0.5f - coord_half_width, 1.0f);
const vec2 coord_top_right(0.5f + coord_half_width,
1.0f - texture_coord_size[1]);
vertices[0].tc = coord_bottom_left;
vertices[1].tc = vec2(coord_top_right[0], coord_bottom_left[1]);
vertices[2].tc = vec2(coord_bottom_left[0], coord_top_right[1]);
vertices[3].tc = coord_top_right;
Mesh::ComputeNormalsTangents(vertices, &kQuadIndices[0], kQuadNumVertices,
kQuadNumIndices);
}
// Creates a mesh of a single quad (two triangles) vertically upright.
// The quad's has x and y size determined by the size of the texture.
// The quad is offset in (x,y,z) space by the 'offset' variable.
// Returns a mesh with the quad and texture, or nullptr if anything went wrong.
Mesh* Game::CreateVerticalQuadMesh(const char* material_name,
const vec3& offset, const vec2& pixel_bounds,
float pixel_to_world_scale) {
// Don't try to load obviously invalid materials. Suppresses error logs from
// the material manager.
if (material_name == nullptr || material_name[0] == '\0') return nullptr;
// Load the material from file, and check validity.
Material* material = asset_manager_.LoadMaterial(material_name);
bool material_valid = material != nullptr && material->textures().size() > 0;
if (!material_valid) return nullptr;
// Create vertex geometry in proportion to the texture size.
// This is nice for the artist since everything is at the scale of the
// original artwork.
assert(pixel_bounds.x() && pixel_bounds.y());
const vec2 texture_size = vec2(mathfu::RoundUpToPowerOf2(pixel_bounds.x()),
mathfu::RoundUpToPowerOf2(pixel_bounds.y()));
const vec2 texture_coord_size = pixel_bounds / texture_size;
const vec2 geo_size = pixel_bounds * vec2(pixel_to_world_scale);
// Initialize a vertex array in the requested position.
NormalMappedVertex vertices[kQuadNumVertices];
CreateVerticalQuad(offset, geo_size, texture_coord_size, vertices);
// Create mesh and add in quad indices.
Mesh* mesh = new Mesh(vertices, kQuadNumVertices, sizeof(NormalMappedVertex),
kQuadMeshFormat);
mesh->AddIndices(kQuadIndices, kQuadNumIndices, material);
return mesh;
}
// Load textures for cardboard into 'materials_'. The 'renderer_' and
// 'asset_manager_' members have been initialized at this point.
bool Game::InitializeAssets() {
// Load up all of our assets, as defined in the manifest.
// TODO - put this into an asynchronous loding function, like we
// had in pie noon.
const AssetManifest& asset_manifest = GetAssetManifest();
for (size_t i = 0; i < asset_manifest.mesh_list()->size(); i++) {
asset_manager_.LoadMesh(asset_manifest.mesh_list()->Get(i)->c_str());
}
for (size_t i = 0; i < asset_manifest.shader_list()->size(); i++) {
asset_manager_.LoadShader(asset_manifest.shader_list()->Get(i)->c_str());
}
for (size_t i = 0; i < asset_manifest.material_list()->size(); i++) {
asset_manager_.LoadMaterial(
asset_manifest.material_list()->Get(i)->c_str());
}
asset_manager_.StartLoadingTextures();
shader_lit_textured_normal_ =
asset_manager_.LoadShader("shaders/lit_textured_normal");
shader_textured_ = asset_manager_.LoadShader("shaders/textured");
// Load animation table:
anim_table_.InitFromFlatBuffers(*asset_manifest.anims());
// Load all animations referenced by the animation table:
const char* anim_not_found = LoadAnimTableAnimations(&anim_table_, LoadFile);
if (anim_not_found != nullptr) {
LogError("Failed to load animation file %s.\n", anim_not_found);
return false;
}
return true;
}
const Config& Game::GetConfig() const {
return *fpl::fpl_project::GetConfig(config_source_.c_str());
}
const InputConfig& Game::GetInputConfig() const {
return *fpl::fpl_project::GetInputConfig(input_config_source_.c_str());
}
const AssetManifest& Game::GetAssetManifest() const {
return *fpl::fpl_project::GetAssetManifest(asset_manifest_source_.c_str());
}
// Initialize each member in turn. This is logically just one function, since
// the order of initialization cannot be changed. However, it's nice for
// debugging and readability to have each section lexographically separate.
bool Game::Initialize(const char* const binary_directory) {
LogInfo("Zooshi Initializing...");
if (!ChangeToUpstreamDir(binary_directory, kAssetsDir)) return false;
if (!LoadFile(kConfigFileName, &config_source_)) return false;
if (!InitializeRenderer()) return false;
if (!LoadFile(GetConfig().input_config()->c_str(), &input_config_source_))
return false;
if (!LoadFile(GetConfig().assets_filename()->c_str(),
&asset_manifest_source_)) {
return false;
}
if (!InitializeAssets()) return false;
// Some people are having trouble loading the audio engine, and it's not
// strictly necessary for gameplay, so don't die if the audio engine fails to
// initialize.
if (!audio_engine_.Initialize(GetConfig().audio_config()->c_str())) {
LogError("Failed to initialize audio engine.\n");
}
if (!audio_engine_.LoadSoundBank("sound_banks/sound_assets.bin")) {
LogError("Failed to load sound bank.\n");
}
// Wait for everything to finish loading...
while (!asset_manager_.TryFinalize()) {
}
event_manager_.RegisterListener(EventSinkUnion_PlaySound, this);
font_manager_.Open(kOpenTypeFontFile);
font_manager_.SetRenderer(renderer_);
SetRelativeMouseMode(true);
input_controller_.set_input_system(&input_);
input_controller_.set_input_config(&GetInputConfig());
world_.Initialize(GetConfig(), &input_, &asset_manager_,
&world_renderer_, &font_manager_, &audio_engine_,
&event_manager_, &renderer_, &anim_table_);
world_renderer_.Initialize(&world_);
world_editor_.reset(new editor::WorldEditor());
world_editor_->Initialize(GetConfig().world_editor_config(),
&world_.entity_manager, &font_manager_);
world_editor_->AddComponentToUpdate(
component_library::TransformComponent::GetComponentId());
world_editor_->AddComponentToUpdate(
ShadowControllerComponent::GetComponentId());
world_editor_->AddComponentToUpdate(
component_library::RenderMeshComponent::GetComponentId());
pause_state_.Initialize(&input_, &world_, &asset_manager_, &font_manager_);
gameplay_state_.Initialize(&input_, &world_, &GetInputConfig(),
world_editor_.get());
game_menu_state_.Initialize(&input_, &world_, &input_controller_,
&GetConfig(), &asset_manager_,
&font_manager_);
world_editor_state_.Initialize(&renderer_, &input_, world_editor_.get(),
&world_);
state_machine_.AssignState(kGameStateGameplay, &gameplay_state_);
state_machine_.AssignState(kGameStatePause, &pause_state_);
state_machine_.AssignState(kGameStateGameMenu, &game_menu_state_);
state_machine_.AssignState(kGameStateWorldEditor, &world_editor_state_);
state_machine_.SetCurrentStateId(kGameStateGameMenu);
LogInfo("Initialization complete\n");
return true;
}
void Game::SetRelativeMouseMode(bool relative_mouse_mode) {
relative_mouse_mode_ = relative_mouse_mode;
input_.SetRelativeMouseMode(relative_mouse_mode);
}
void Game::ToggleRelativeMouseMode() {
relative_mouse_mode_ = !relative_mouse_mode_;
input_.SetRelativeMouseMode(relative_mouse_mode_);
}
static inline WorldTime CurrentWorldTime() { return GetTicks(); }
void Game::Run() {
// Initialize so that we don't sleep the first time through the loop.
prev_world_time_ = CurrentWorldTime() - kMinUpdateTime;
while (!input_.exit_requested() && !state_machine_.done()) {
// Milliseconds elapsed since last update. To avoid burning through the
// CPU, enforce a minimum time between updates. For example, if
// min_update_time is 1, we will not exceed 1000Hz update time.
const WorldTime world_time = CurrentWorldTime();
const WorldTime delta_time =
std::min(world_time - prev_world_time_, kMaxUpdateTime);
prev_world_time_ = world_time;
if (delta_time < kMinUpdateTime) {
Delay(kMinUpdateTime - delta_time);
}
input_.AdvanceFrame(&renderer_.window_size());
state_machine_.AdvanceFrame(delta_time);
state_machine_.Render(&renderer_);
renderer_.AdvanceFrame(input_.minimized(), input_.Time());
audio_engine_.AdvanceFrame(delta_time / 1000.0f);
// Process input device messages since the last game loop.
// Update render window size.
if (input_.GetButton(fpl::FPLK_BACKQUOTE).went_down()) {
ToggleRelativeMouseMode();
}
}
}
void Game::OnEvent(const event::EventPayload& event_payload) {
switch (event_payload.id()) {
case EventSinkUnion_PlaySound: {
auto* payload = event_payload.ToData<PlaySoundPayload>();
audio_engine_.PlaySound(payload->sound_name, payload->location);
break;
}
default: { assert(false); }
}
}
} // fpl_project
} // fpl
<|endoftext|> |
<commit_before>#include <iostream>
#include <QtGui>
#include<QMessageBox>
#include "zjsonobject.h"
#include "zjsonparser.h"
#include "zstring.h"
#include "flyembodyinfodialog.h"
#include "ui_flyembodyinfodialog.h"
#include "zdialogfactory.h"
/*
* this dialog displays a list of bodies and their properties; data is
* loaded from a static json bookmarks file
*
* djo, 7/15
*
*/
FlyEmBodyInfoDialog::FlyEmBodyInfoDialog(QWidget *parent) :
QDialog(parent),
ui(new Ui::FlyEmBodyInfoDialog)
{
ui->setupUi(this);
connect(ui->openButton, SIGNAL(clicked()), this, SLOT(onOpenButton()));
connect(ui->closeButton, SIGNAL(clicked()), this, SLOT(onCloseButton()));
m_model = createModel(ui->tableView);
ui->tableView->setModel(m_model);
connect(ui->tableView, SIGNAL(doubleClicked(QModelIndex)),
this, SLOT(activateBody(QModelIndex)));
}
void FlyEmBodyInfoDialog::activateBody(QModelIndex modelIndex)
{
if (modelIndex.column() == 0) {
QStandardItem *item = m_model->itemFromIndex(modelIndex);
uint64_t bodyId = item->data(Qt::DisplayRole).toULongLong();
#ifdef _DEBUG_
std::cout << bodyId << " activated." << std::endl;
#endif
emit bodyActivated(bodyId);
}
}
QStandardItemModel* FlyEmBodyInfoDialog::createModel(QObject* parent) {
QStandardItemModel* model = new QStandardItemModel(0, 3, parent);
setHeaders(model);
return model;
}
void FlyEmBodyInfoDialog::setHeaders(QStandardItemModel * model) {
model->setHorizontalHeaderItem(0, new QStandardItem(QString("Body ID")));
model->setHorizontalHeaderItem(1, new QStandardItem(QString("# synapses")));
model->setHorizontalHeaderItem(2, new QStandardItem(QString("status")));
}
void FlyEmBodyInfoDialog::importBookmarksFile(const QString &filename) {
ZJsonObject jsonObject;
if (!jsonObject.load(filename.toStdString())) {
QMessageBox errorBox;
errorBox.setText("Problem parsing json file");
errorBox.setInformativeText("Are you sure this is a Fly EM JSON file?");
errorBox.setStandardButtons(QMessageBox::Ok);
errorBox.setIcon(QMessageBox::Warning);
errorBox.exec();
return;
}
if (!isValidBookmarkFile(jsonObject)) {
return;
}
// update model from the object, or the data piece of it
ZJsonValue dataObject = jsonObject.value("data");
updateModel(dataObject);
}
bool FlyEmBodyInfoDialog::isValidBookmarkFile(ZJsonObject jsonObject) {
// validation is admittedly limited for now; ultimately, I
// expect we'll be getting the info from DVID rather than
// a file anyway, so I'm not going to spend much time on it
// likewise, I'm copy/pasting the error dialog code rather than
// neatly factoring it out
QMessageBox errorBox;
if (!jsonObject.hasKey("data") || !jsonObject.hasKey("metadata")) {
errorBox.setText("Problem with json file");
errorBox.setInformativeText("This file is missing 'data' or 'metadata'. Are you sure this is a Fly EM JSON file?");
errorBox.setStandardButtons(QMessageBox::Ok);
errorBox.setIcon(QMessageBox::Warning);
errorBox.exec();
return false;
}
ZJsonObject metadata = (ZJsonObject) jsonObject.value("metadata");
if (!metadata.hasKey("description")) {
errorBox.setText("Problem with json file");
errorBox.setInformativeText("This file is missing 'metadata/description'. Are you sure this is a Fly EM JSON file?");
errorBox.setStandardButtons(QMessageBox::Ok);
errorBox.setIcon(QMessageBox::Warning);
errorBox.exec();
return false;
}
ZString description = ZJsonParser::stringValue(metadata["description"]);
if (description != "bookmarks") {
errorBox.setText("Problem with json file");
errorBox.setInformativeText("This json file does not have description 'bookmarks'!");
errorBox.setStandardButtons(QMessageBox::Ok);
errorBox.setIcon(QMessageBox::Warning);
errorBox.exec();
return false;
}
ZJsonValue data = jsonObject.value("data");
if (!data.isArray()) {
errorBox.setText("Problem with json file");
errorBox.setInformativeText("The data section in this json file is not an array!");
errorBox.setStandardButtons(QMessageBox::Ok);
errorBox.setIcon(QMessageBox::Warning);
errorBox.exec();
return false;
}
// we could/should test all the elements of the array to see if they
// are bookmarks, but enough is enough...
return true;
}
void FlyEmBodyInfoDialog::onCloseButton() {
close();
}
void FlyEmBodyInfoDialog::onOpenButton() {
QString filename =
ZDialogFactory::GetOpenFileName("Open bookmarks file", "", this);
// QString filename = QFileDialog::getOpenFileName(this, "Open bookmarks file");
if (!filename.isEmpty()) {
importBookmarksFile(filename);
}
}
/*
* update the data model from json; input should be the
* "data" part of our standard bookmarks json file
*/
void FlyEmBodyInfoDialog::updateModel(ZJsonValue data) {
m_model->clear();
setHeaders(m_model);
ZJsonArray bookmarks(data);
m_model->setRowCount(bookmarks.size());
for (size_t i = 0; i < bookmarks.size(); ++i) {
ZJsonObject bkmk(bookmarks.at(i), false);
// carefully set data for items so they will sort numerically;
// contrast the "body status" entry, which we keep as a string
qulonglong bodyID = ZJsonParser::integerValue(bkmk["body ID"]);
QStandardItem * bodyIDItem = new QStandardItem();
bodyIDItem->setData(QVariant(bodyID), Qt::DisplayRole);
m_model->setItem(i, 0, bodyIDItem);
int nSynapses = ZJsonParser::integerValue(bkmk["body synapses"]);
QStandardItem * synapsesItem = new QStandardItem();
synapsesItem->setData(QVariant(nSynapses), Qt::DisplayRole);
m_model->setItem(i, 1, synapsesItem);
const char* status = ZJsonParser::stringValue(bkmk["body status"]);
m_model->setItem(i, 2, new QStandardItem(QString(status)));
}
ui->tableView->resizeColumnsToContents();
// initial sort order is by synapses, descending
ui->tableView->sortByColumn(1, Qt::DescendingOrder);
}
FlyEmBodyInfoDialog::~FlyEmBodyInfoDialog()
{
delete ui;
}
<commit_msg>body info dialog: nsynapses -> npre and npost columns<commit_after>#include <iostream>
#include <QtGui>
#include<QMessageBox>
#include "zjsonobject.h"
#include "zjsonparser.h"
#include "zstring.h"
#include "flyembodyinfodialog.h"
#include "ui_flyembodyinfodialog.h"
#include "zdialogfactory.h"
/*
* this dialog displays a list of bodies and their properties; data is
* loaded from a static json bookmarks file
*
* to add/remove columns in table:
* -- in createModel(), change ncol
* -- in setHeaders(), adjust headers
* -- in updateModel(), adjust data load and initial sort order
*
* I really should be creating model and headers from a constant headers list
*
* djo, 7/15
*
*/
FlyEmBodyInfoDialog::FlyEmBodyInfoDialog(QWidget *parent) :
QDialog(parent),
ui(new Ui::FlyEmBodyInfoDialog)
{
ui->setupUi(this);
connect(ui->openButton, SIGNAL(clicked()), this, SLOT(onOpenButton()));
connect(ui->closeButton, SIGNAL(clicked()), this, SLOT(onCloseButton()));
m_model = createModel(ui->tableView);
ui->tableView->setModel(m_model);
connect(ui->tableView, SIGNAL(doubleClicked(QModelIndex)),
this, SLOT(activateBody(QModelIndex)));
}
void FlyEmBodyInfoDialog::activateBody(QModelIndex modelIndex)
{
if (modelIndex.column() == 0) {
QStandardItem *item = m_model->itemFromIndex(modelIndex);
uint64_t bodyId = item->data(Qt::DisplayRole).toULongLong();
#ifdef _DEBUG_
std::cout << bodyId << " activated." << std::endl;
#endif
emit bodyActivated(bodyId);
}
}
QStandardItemModel* FlyEmBodyInfoDialog::createModel(QObject* parent) {
QStandardItemModel* model = new QStandardItemModel(0, 4, parent);
setHeaders(model);
return model;
}
void FlyEmBodyInfoDialog::setHeaders(QStandardItemModel * model) {
model->setHorizontalHeaderItem(0, new QStandardItem(QString("Body ID")));
model->setHorizontalHeaderItem(1, new QStandardItem(QString("# pre")));
model->setHorizontalHeaderItem(2, new QStandardItem(QString("# post")));
model->setHorizontalHeaderItem(3, new QStandardItem(QString("status")));
}
void FlyEmBodyInfoDialog::importBookmarksFile(const QString &filename) {
ZJsonObject jsonObject;
if (!jsonObject.load(filename.toStdString())) {
QMessageBox errorBox;
errorBox.setText("Problem parsing json file");
errorBox.setInformativeText("Are you sure this is a Fly EM JSON file?");
errorBox.setStandardButtons(QMessageBox::Ok);
errorBox.setIcon(QMessageBox::Warning);
errorBox.exec();
return;
}
if (!isValidBookmarkFile(jsonObject)) {
return;
}
// update model from the object, or the data piece of it
ZJsonValue dataObject = jsonObject.value("data");
updateModel(dataObject);
}
bool FlyEmBodyInfoDialog::isValidBookmarkFile(ZJsonObject jsonObject) {
// validation is admittedly limited for now; ultimately, I
// expect we'll be getting the info from DVID rather than
// a file anyway, so I'm not going to spend much time on it
// likewise, I'm copy/pasting the error dialog code rather than
// neatly factoring it out
QMessageBox errorBox;
if (!jsonObject.hasKey("data") || !jsonObject.hasKey("metadata")) {
errorBox.setText("Problem with json file");
errorBox.setInformativeText("This file is missing 'data' or 'metadata'. Are you sure this is a Fly EM JSON file?");
errorBox.setStandardButtons(QMessageBox::Ok);
errorBox.setIcon(QMessageBox::Warning);
errorBox.exec();
return false;
}
ZJsonObject metadata = (ZJsonObject) jsonObject.value("metadata");
if (!metadata.hasKey("description")) {
errorBox.setText("Problem with json file");
errorBox.setInformativeText("This file is missing 'metadata/description'. Are you sure this is a Fly EM JSON file?");
errorBox.setStandardButtons(QMessageBox::Ok);
errorBox.setIcon(QMessageBox::Warning);
errorBox.exec();
return false;
}
ZString description = ZJsonParser::stringValue(metadata["description"]);
if (description != "bookmarks") {
errorBox.setText("Problem with json file");
errorBox.setInformativeText("This json file does not have description 'bookmarks'!");
errorBox.setStandardButtons(QMessageBox::Ok);
errorBox.setIcon(QMessageBox::Warning);
errorBox.exec();
return false;
}
ZJsonValue data = jsonObject.value("data");
if (!data.isArray()) {
errorBox.setText("Problem with json file");
errorBox.setInformativeText("The data section in this json file is not an array!");
errorBox.setStandardButtons(QMessageBox::Ok);
errorBox.setIcon(QMessageBox::Warning);
errorBox.exec();
return false;
}
// we could/should test all the elements of the array to see if they
// are bookmarks, but enough is enough...
return true;
}
void FlyEmBodyInfoDialog::onCloseButton() {
close();
}
void FlyEmBodyInfoDialog::onOpenButton() {
QString filename =
ZDialogFactory::GetOpenFileName("Open bookmarks file", "", this);
// QString filename = QFileDialog::getOpenFileName(this, "Open bookmarks file");
if (!filename.isEmpty()) {
importBookmarksFile(filename);
}
}
/*
* update the data model from json; input should be the
* "data" part of our standard bookmarks json file
*/
void FlyEmBodyInfoDialog::updateModel(ZJsonValue data) {
m_model->clear();
setHeaders(m_model);
ZJsonArray bookmarks(data);
m_model->setRowCount(bookmarks.size());
for (size_t i = 0; i < bookmarks.size(); ++i) {
ZJsonObject bkmk(bookmarks.at(i), false);
// carefully set data for items so they will sort numerically;
// contrast the "body status" entry, which we keep as a string
qulonglong bodyID = ZJsonParser::integerValue(bkmk["body ID"]);
QStandardItem * bodyIDItem = new QStandardItem();
bodyIDItem->setData(QVariant(bodyID), Qt::DisplayRole);
m_model->setItem(i, 0, bodyIDItem);
int nPre = ZJsonParser::integerValue(bkmk["body T-bars"]);
QStandardItem * preSynapseItem = new QStandardItem();
preSynapseItem->setData(QVariant(nPre), Qt::DisplayRole);
m_model->setItem(i, 1, preSynapseItem);
int nPost = ZJsonParser::integerValue(bkmk["body PSDs"]);
QStandardItem * postSynapseItem = new QStandardItem();
postSynapseItem->setData(QVariant(nPost), Qt::DisplayRole);
m_model->setItem(i, 2, postSynapseItem);
const char* status = ZJsonParser::stringValue(bkmk["body status"]);
m_model->setItem(i, 3, new QStandardItem(QString(status)));
}
ui->tableView->resizeColumnsToContents();
// initial sort order is by #pre, descending
ui->tableView->sortByColumn(1, Qt::DescendingOrder);
}
FlyEmBodyInfoDialog::~FlyEmBodyInfoDialog()
{
delete ui;
}
<|endoftext|> |
<commit_before>/*
* Copyright (C) 2008-2014 The QXmpp developers
*
* Author:
* Jeremy Lainé
*
* Source:
* https://github.com/qxmpp-project/qxmpp
*
* This file is a part of QXmpp library.
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 2.1 of the License, or (at your option) any later version.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
*/
#include <QObject>
#include <QtTest>
#include "QXmppRtcpPacket.h"
class tst_QXmppRtcpPacket : public QObject
{
Q_OBJECT
private slots:
void testBad();
void testSenderReport();
void testSourceDescription();
};
void tst_QXmppRtcpPacket::testBad()
{
QXmppRtcpPacket packet;
// too short
QCOMPARE(packet.decode(QByteArray()), false);
}
void tst_QXmppRtcpPacket::testSenderReport()
{
QByteArray data("\x80\xc8\x00\x06\x27\xa6\xe4\xc1\xd9\x7f\xec\x7d\x92\xac\xd9\xe8\xdd\x9e\x32\x57\x00\x00\x00\x74\x00\x00\x48\x80", 28);
QXmppRtcpPacket packet;
QVERIFY(packet.decode(data));
QCOMPARE(packet.type(), quint8(QXmppRtcpPacket::SenderReport));
QCOMPARE(packet.receiverReports().size(), 0);
QCOMPARE(packet.senderReport().ntpStamp(), quint64(15672505252348484072));
QCOMPARE(packet.senderReport().octetCount(), quint32(18560));
QCOMPARE(packet.senderReport().packetCount(), quint32(116));
QCOMPARE(packet.senderReport().rtpStamp(), quint32(3718132311));
QCOMPARE(packet.senderReport().ssrc(), quint32(665248961));
QCOMPARE(packet.sourceDescriptions().size(), 0);
QCOMPARE(packet.encode(), data);
}
void tst_QXmppRtcpPacket::testSourceDescription()
{
QByteArray data("\x81\xca\x00\x0c\x27\xa6\xe4\xc1\x01\x26\x7b\x64\x30\x33\x61\x37\x63\x34\x38\x2d\x64\x39\x30\x36\x2d\x34\x62\x39\x61\x2d\x39\x38\x32\x30\x2d\x31\x31\x31\x38\x30\x32\x64\x63\x64\x35\x37\x38\x7d\x00\x00\x00\x00", 52);
QXmppRtcpPacket packet;
QVERIFY(packet.decode(data));
QCOMPARE(packet.type(), quint8(QXmppRtcpPacket::SourceDescription));
QCOMPARE(packet.receiverReports().size(), 0);
QCOMPARE(packet.senderReport().ntpStamp(), quint64(0));
QCOMPARE(packet.senderReport().octetCount(), quint32(0));
QCOMPARE(packet.senderReport().packetCount(), quint32(0));
QCOMPARE(packet.senderReport().rtpStamp(), quint32(0));
QCOMPARE(packet.senderReport().ssrc(), quint32(0));
QCOMPARE(packet.sourceDescriptions().size(), 1);
QCOMPARE(packet.sourceDescriptions()[0].cname(), QLatin1String("{d03a7c48-d906-4b9a-9820-111802dcd578}"));
QCOMPARE(packet.sourceDescriptions()[0].name(), QString());
QCOMPARE(packet.sourceDescriptions()[0].ssrc(), quint32(665248961));
QCOMPARE(packet.encode(), data);
}
QTEST_MAIN(tst_QXmppRtcpPacket)
#include "tst_qxmpprtcppacket.moc"
<commit_msg>fix compiler warning<commit_after>/*
* Copyright (C) 2008-2014 The QXmpp developers
*
* Author:
* Jeremy Lainé
*
* Source:
* https://github.com/qxmpp-project/qxmpp
*
* This file is a part of QXmpp library.
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 2.1 of the License, or (at your option) any later version.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
*/
#include <QObject>
#include <QtTest>
#include "QXmppRtcpPacket.h"
class tst_QXmppRtcpPacket : public QObject
{
Q_OBJECT
private slots:
void testBad();
void testSenderReport();
void testSourceDescription();
};
void tst_QXmppRtcpPacket::testBad()
{
QXmppRtcpPacket packet;
// too short
QCOMPARE(packet.decode(QByteArray()), false);
}
void tst_QXmppRtcpPacket::testSenderReport()
{
QByteArray data("\x80\xc8\x00\x06\x27\xa6\xe4\xc1\xd9\x7f\xec\x7d\x92\xac\xd9\xe8\xdd\x9e\x32\x57\x00\x00\x00\x74\x00\x00\x48\x80", 28);
QXmppRtcpPacket packet;
QVERIFY(packet.decode(data));
QCOMPARE(packet.type(), quint8(QXmppRtcpPacket::SenderReport));
QCOMPARE(packet.receiverReports().size(), 0);
QCOMPARE(packet.senderReport().ntpStamp(), quint64(15672505252348484072ULL));
QCOMPARE(packet.senderReport().octetCount(), quint32(18560));
QCOMPARE(packet.senderReport().packetCount(), quint32(116));
QCOMPARE(packet.senderReport().rtpStamp(), quint32(3718132311));
QCOMPARE(packet.senderReport().ssrc(), quint32(665248961));
QCOMPARE(packet.sourceDescriptions().size(), 0);
QCOMPARE(packet.encode(), data);
}
void tst_QXmppRtcpPacket::testSourceDescription()
{
QByteArray data("\x81\xca\x00\x0c\x27\xa6\xe4\xc1\x01\x26\x7b\x64\x30\x33\x61\x37\x63\x34\x38\x2d\x64\x39\x30\x36\x2d\x34\x62\x39\x61\x2d\x39\x38\x32\x30\x2d\x31\x31\x31\x38\x30\x32\x64\x63\x64\x35\x37\x38\x7d\x00\x00\x00\x00", 52);
QXmppRtcpPacket packet;
QVERIFY(packet.decode(data));
QCOMPARE(packet.type(), quint8(QXmppRtcpPacket::SourceDescription));
QCOMPARE(packet.receiverReports().size(), 0);
QCOMPARE(packet.senderReport().ntpStamp(), quint64(0));
QCOMPARE(packet.senderReport().octetCount(), quint32(0));
QCOMPARE(packet.senderReport().packetCount(), quint32(0));
QCOMPARE(packet.senderReport().rtpStamp(), quint32(0));
QCOMPARE(packet.senderReport().ssrc(), quint32(0));
QCOMPARE(packet.sourceDescriptions().size(), 1);
QCOMPARE(packet.sourceDescriptions()[0].cname(), QLatin1String("{d03a7c48-d906-4b9a-9820-111802dcd578}"));
QCOMPARE(packet.sourceDescriptions()[0].name(), QString());
QCOMPARE(packet.sourceDescriptions()[0].ssrc(), quint32(665248961));
QCOMPARE(packet.encode(), data);
}
QTEST_MAIN(tst_QXmppRtcpPacket)
#include "tst_qxmpprtcppacket.moc"
<|endoftext|> |
<commit_before>#include "realm.h"
#include <cstdio>
#include <cstdlib>
#include <cassert>
#include <cstring>
#include <csignal>
#include <cmath>
#include <time.h>
#include "osdep.h"
using namespace Realm;
Logger log_app("app");
// Task IDs, some IDs are reserved so start at first available number
enum {
TOP_LEVEL_TASK = Processor::TASK_ID_FIRST_AVAILABLE+0,
MEMSPEED_TASK,
COPYPROF_TASK,
};
template <int N>
struct LayoutPermutation {
int dim_order[N];
char name[N+1];
};
template <int N>
struct TransposeExperiment {
const struct LayoutPermutation<N> *src_perm;
const struct LayoutPermutation<N> *dst_perm;
long long nanoseconds;
};
template <int N>
void create_permutations(std::vector<LayoutPermutation<N> >& perms,
LayoutPermutation<N>& scratch,
int pos)
{
static const char *dim_names = "XYZW";
for(int i = 0; i < N; i++) {
bool found = false;
for(int j = 0; j < pos; j++)
if(scratch.dim_order[j] == i) found = true;
if(found) continue;
scratch.dim_order[pos] = i;
scratch.name[pos] = dim_names[i];
if(pos == (N - 1))
perms.push_back(scratch);
else
create_permutations<N>(perms, scratch, pos+1);
}
}
struct CopyProfResult {
long long *nanoseconds;
UserEvent done;
};
void copy_profiling_task(const void *args, size_t arglen,
const void *userdata, size_t userlen, Processor p)
{
ProfilingResponse resp(args, arglen);
assert(resp.user_data_size() == sizeof(CopyProfResult));
const CopyProfResult *result = static_cast<const CopyProfResult *>(resp.user_data());
ProfilingMeasurements::OperationTimeline timeline;
if(resp.get_measurement(timeline)) {
*(result->nanoseconds) = timeline.complete_time - timeline.start_time;
result->done.trigger();
} else {
log_app.fatal() << "no operation timeline in profiling response!";
assert(0);
}
}
static size_t log2_buffer_size = 20; // should be bigger than any cache in system
template <int N, typename FT>
void do_single_dim(Memory src_mem, Memory dst_mem, int log2_size,
Processor prof_proc, int pad = 0)
{
std::vector<LayoutPermutation<N> > perms;
LayoutPermutation<N> scratch;
memset(&scratch, 0, sizeof(scratch));
create_permutations<N>(perms, scratch, 0);
Rect<N> bounds;
for(int i = 0; i < N; i++) {
bounds.lo[i] = 0;
bounds.hi[i] = (1 << (log2_size / N)) - 1;
}
IndexSpace<N> is(bounds);
Rect<N> bounds_pad;
for(int i = 0; i < N; i++) {
bounds_pad.lo[i] = 0;
bounds_pad.hi[i] = (1 << (log2_size / N)) - 1 + 32;
}
IndexSpace<N> is_pad(bounds_pad);
std::vector<RegionInstance> src_insts, dst_insts;
std::map<FieldID, size_t> field_sizes;
field_sizes[0] = sizeof(FT);
InstanceLayoutConstraints ilc(field_sizes, 1);
for(typename std::vector<LayoutPermutation<N> >::const_iterator it = perms.begin();
it != perms.end();
++it) {
// src mem
{
InstanceLayoutGeneric *ilg = InstanceLayoutGeneric::choose_instance_layout<N,FT>(is_pad, ilc, it->dim_order);
RegionInstance s_inst;
Event e = RegionInstance::create_instance(s_inst, src_mem, ilg,
ProfilingRequestSet());
std::vector<CopySrcDstField> tgt(1);
tgt[0].inst = s_inst;
tgt[0].field_id = 0;
tgt[0].size = field_sizes[0];
FT fill_value = 77;
e = is.fill(tgt, ProfilingRequestSet(), &fill_value, sizeof(fill_value), e);
e.wait();
src_insts.push_back(s_inst);
}
// dst mem
{
InstanceLayoutGeneric *ilg = InstanceLayoutGeneric::choose_instance_layout<N,FT>(is, ilc, it->dim_order);
RegionInstance d_inst;
Event e = RegionInstance::create_instance(d_inst, dst_mem, ilg,
ProfilingRequestSet());
std::vector<CopySrcDstField> tgt(1);
tgt[0].inst = d_inst;
tgt[0].field_id = 0;
tgt[0].size = field_sizes[0];
FT fill_value = 88;
e = is.fill(tgt, ProfilingRequestSet(), &fill_value, sizeof(fill_value), e);
e.wait();
dst_insts.push_back(d_inst);
}
}
std::vector<TransposeExperiment<N> *> experiments;
std::set<Event> done_events;
Event prev_copy = Event::NO_EVENT;
for(unsigned i = 0; i < perms.size(); i++)
for(unsigned j = 0; j < perms.size(); j++) {
TransposeExperiment<N> *exp = new TransposeExperiment<N>;
exp->src_perm = &perms[i];
exp->dst_perm = &perms[j];
exp->nanoseconds = 0;
experiments.push_back(exp);
UserEvent done = UserEvent::create_user_event();
done_events.insert(done);
CopyProfResult cpr;
cpr.nanoseconds = &(exp->nanoseconds);
cpr.done = done;
ProfilingRequestSet prs;
prs.add_request(prof_proc, COPYPROF_TASK, &cpr, sizeof(CopyProfResult))
.add_measurement<ProfilingMeasurements::OperationTimeline>();
std::vector<CopySrcDstField> srcs(1), dsts(1);
srcs[0].inst = src_insts[i];
srcs[0].field_id = 0;
srcs[0].size = field_sizes[0];
dsts[0].inst = dst_insts[j];
dsts[0].field_id = 0;
dsts[0].size = field_sizes[0];
prev_copy = is.copy(srcs, dsts, prs, prev_copy);
}
// wait for copies to finish
done_events.insert(prev_copy);
Event::merge_events(done_events).wait();
for(typename std::vector<TransposeExperiment<N> *>::const_iterator it = experiments.begin();
it != experiments.end();
++it) {
double bw = 1.0 * is.volume() * field_sizes[0] / (*it)->nanoseconds;
log_app.print() << "src=" << (*it)->src_perm->name
<< " dst=" << (*it)->dst_perm->name
<< " time=" << (1e-9 * (*it)->nanoseconds)
<< " bw=" << bw;
delete *it;
}
// cleanup
for(typename std::vector<RegionInstance>::const_iterator it = src_insts.begin();
it != src_insts.end();
++it)
it->destroy();
for(typename std::vector<RegionInstance>::const_iterator it = dst_insts.begin();
it != dst_insts.end();
++it)
it->destroy();
}
std::set<Processor::Kind> supported_proc_kinds;
void top_level_task(const void *args, size_t arglen,
const void *userdata, size_t userlen, Processor p)
{
log_app.print() << "Copy/transpose test";
// just sysmem for now
Machine machine = Machine::get_machine();
Memory m = Machine::MemoryQuery(machine).only_kind(Memory::SYSTEM_MEM).first();
assert(m.exists());
typedef int FT;
do_single_dim<1, FT>(m, m, log2_buffer_size, p);
do_single_dim<2, FT>(m, m, log2_buffer_size, p);
do_single_dim<3, FT>(m, m, log2_buffer_size, p);
}
int main(int argc, char **argv)
{
Runtime rt;
rt.init(&argc, &argv);
for(int i = 1; i < argc; i++) {
if(!strcmp(argv[i], "-b")) {
log2_buffer_size = strtoll(argv[++i], 0, 10);
continue;
}
}
rt.register_task(TOP_LEVEL_TASK, top_level_task);
Processor::register_task_by_kind(Processor::LOC_PROC, false /*!global*/,
COPYPROF_TASK,
CodeDescriptor(copy_profiling_task),
ProfilingRequestSet(),
0, 0).wait();
// select a processor to run the top level task on
Processor p = Machine::ProcessorQuery(Machine::get_machine())
.only_kind(Processor::LOC_PROC)
.first();
assert(p.exists());
// collective launch of a single task - everybody gets the same finish event
Event e = rt.collective_spawn(p, TOP_LEVEL_TASK, 0, 0);
// request shutdown once that task is complete
rt.shutdown(e);
// now sleep this thread until that shutdown actually happens
rt.wait_for_shutdown();
return 0;
}
<commit_msg>test: augment realm transpose test to do more memories, narrow layouts<commit_after>#include "realm.h"
#include "realm/cmdline.h"
#include <cstdio>
#include <cstdlib>
#include <cassert>
#include <cstring>
#include <csignal>
#include <cmath>
#include <time.h>
#include "osdep.h"
using namespace Realm;
Logger log_app("app");
// Task IDs, some IDs are reserved so start at first available number
enum {
TOP_LEVEL_TASK = Processor::TASK_ID_FIRST_AVAILABLE+0,
MEMSPEED_TASK,
COPYPROF_TASK,
};
template <int N>
struct LayoutPermutation {
int dim_order[N];
char name[N+1];
};
template <int N>
struct TransposeExperiment {
const struct LayoutPermutation<N> *src_perm;
const struct LayoutPermutation<N> *dst_perm;
long long nanoseconds;
};
template <int N>
void create_permutations(std::vector<LayoutPermutation<N> >& perms,
LayoutPermutation<N>& scratch,
int pos, size_t narrow_size)
{
static const char *dim_names = "XYZW";
for(int i = 0; i < N; i++) {
bool found = false;
for(int j = 0; j < pos; j++)
if(scratch.dim_order[j] == i) found = true;
if(found) continue;
scratch.dim_order[pos] = i;
scratch.name[pos] = (((i == 0) && (narrow_size > 0)) ?
tolower(dim_names[i]):
dim_names[i]);
if(pos == (N - 1))
perms.push_back(scratch);
else
create_permutations<N>(perms, scratch, pos+1, narrow_size);
}
}
struct CopyProfResult {
long long *nanoseconds;
UserEvent done;
};
void copy_profiling_task(const void *args, size_t arglen,
const void *userdata, size_t userlen, Processor p)
{
ProfilingResponse resp(args, arglen);
assert(resp.user_data_size() == sizeof(CopyProfResult));
const CopyProfResult *result = static_cast<const CopyProfResult *>(resp.user_data());
ProfilingMeasurements::OperationTimeline timeline;
if(resp.get_measurement(timeline)) {
*(result->nanoseconds) = timeline.complete_time - timeline.start_time;
result->done.trigger();
} else {
log_app.fatal() << "no operation timeline in profiling response!";
assert(0);
}
}
namespace TestConfig {
size_t buffer_size = 64 << 20; // should be bigger than any cache in system
size_t narrow_dim = 0; // should one dimension be a fixed (narrow) size?
unsigned dim_mask = 7; // i.e. 1-D, 2-D, 3-D
bool all_mems = false;
};
template <int N, typename FT>
void do_single_dim(Memory src_mem, Memory dst_mem, int log2_size,
size_t narrow_size,
Processor prof_proc, int pad = 0)
{
std::vector<LayoutPermutation<N> > perms;
LayoutPermutation<N> scratch;
memset(&scratch, 0, sizeof(scratch));
create_permutations<N>(perms, scratch, 0, narrow_size);
Rect<N> bounds;
for(int i = 0; i < N; i++) {
bounds.lo[i] = 0;
if((N > 1) && (narrow_size > 0)) {
if(i == 0)
bounds.hi[i] = narrow_size - 1;
else {
// max is for compilers that don't see this code is unreachable for N==1
bounds.hi[i] = (1 << (log2_size / std::max(1, N - 1))) - 1;
}
} else
bounds.hi[i] = (1 << (log2_size / N)) - 1;
}
IndexSpace<N> is(bounds);
Rect<N> bounds_pad;
for(int i = 0; i < N; i++) {
bounds_pad.lo[i] = 0;
bounds_pad.hi[i] = bounds.hi[i] + (((narrow_size > 0) && (narrow_size < 32)) ? narrow_size : 32);
}
IndexSpace<N> is_pad(bounds_pad);
std::map<FieldID, size_t> field_sizes;
field_sizes[0] = sizeof(FT);
InstanceLayoutConstraints ilc(field_sizes, 1);
std::vector<TransposeExperiment<N> *> experiments;
Event wait_for = Event::NO_EVENT;
std::vector<Event> done_events;
for(unsigned i = 0; i < perms.size(); i++) {
RegionInstance src_inst;
{
InstanceLayoutGeneric *ilg = InstanceLayoutGeneric::choose_instance_layout<N,FT>(is_pad, ilc, perms[i].dim_order);
wait_for = RegionInstance::create_instance(src_inst, src_mem, ilg,
ProfilingRequestSet(),
wait_for);
std::vector<CopySrcDstField> tgt(1);
tgt[0].inst = src_inst;
tgt[0].field_id = 0;
tgt[0].size = field_sizes[0];
FT fill_value = 77;
wait_for = is.fill(tgt, ProfilingRequestSet(),
&fill_value, sizeof(fill_value), wait_for);
}
for(unsigned j = 0; j < perms.size(); j++) {
RegionInstance dst_inst;
{
InstanceLayoutGeneric *ilg = InstanceLayoutGeneric::choose_instance_layout<N,FT>(is_pad, ilc, perms[j].dim_order);
wait_for = RegionInstance::create_instance(dst_inst, dst_mem, ilg,
ProfilingRequestSet(),
wait_for);
std::vector<CopySrcDstField> tgt(1);
tgt[0].inst = dst_inst;
tgt[0].field_id = 0;
tgt[0].size = field_sizes[0];
FT fill_value = 88;
wait_for = is.fill(tgt, ProfilingRequestSet(),
&fill_value, sizeof(fill_value), wait_for);
}
TransposeExperiment<N> *exp = new TransposeExperiment<N>;
exp->src_perm = &perms[i];
exp->dst_perm = &perms[j];
exp->nanoseconds = 0;
experiments.push_back(exp);
UserEvent done = UserEvent::create_user_event();
done_events.push_back(done);
CopyProfResult cpr;
cpr.nanoseconds = &(exp->nanoseconds);
cpr.done = done;
ProfilingRequestSet prs;
prs.add_request(prof_proc, COPYPROF_TASK, &cpr, sizeof(CopyProfResult))
.add_measurement<ProfilingMeasurements::OperationTimeline>();
std::vector<CopySrcDstField> srcs(1), dsts(1);
srcs[0].inst = src_inst;
srcs[0].field_id = 0;
srcs[0].size = field_sizes[0];
dsts[0].inst = dst_inst;
dsts[0].field_id = 0;
dsts[0].size = field_sizes[0];
wait_for = is.copy(srcs, dsts, prs, wait_for);
dst_inst.destroy(wait_for);
}
src_inst.destroy(wait_for);
}
// wait for copies to finish
done_events.push_back(wait_for);
Event::merge_events(done_events).wait();
for(typename std::vector<TransposeExperiment<N> *>::const_iterator it = experiments.begin();
it != experiments.end();
++it) {
double bw = 1.0 * is.volume() * field_sizes[0] / (*it)->nanoseconds;
log_app.print() << "src=" << (*it)->src_perm->name
<< " dst=" << (*it)->dst_perm->name
<< " time=" << (1e-9 * (*it)->nanoseconds)
<< " bw=" << bw;
delete *it;
}
}
std::set<Processor::Kind> supported_proc_kinds;
void top_level_task(const void *args, size_t arglen,
const void *userdata, size_t userlen, Processor p)
{
log_app.print() << "Copy/transpose test";
size_t log2_buffer_size = 0;
{
size_t v = TestConfig::buffer_size / sizeof(int);
if(TestConfig::narrow_dim > 0)
v /= TestConfig::narrow_dim;
while(v > 1) {
v >>= 1;
log2_buffer_size++;
}
}
std::vector<Memory> src_mems, dst_mems;
Machine::MemoryQuery mq(Machine::get_machine());
for(Machine::MemoryQuery::iterator it = mq.begin(); it != mq.end(); ++it) {
// skip small memories
if((*it).capacity() < (3 * TestConfig::buffer_size)) continue;
// only sysmem if were not doing all combinations
if(((*it).kind() != Memory::SYSTEM_MEM) && !TestConfig::all_mems)
continue;
src_mems.push_back(*it);
}
assert(!src_mems.empty());
if(TestConfig::all_mems) {
dst_mems = src_mems;
} else {
// just use first as source and last as dest (gives you inter-node
// copies when multiple nodes are present)
dst_mems.push_back(src_mems[src_mems.size() - 1]);
src_mems.resize(1);
}
for(std::vector<Memory>::const_iterator src_it = src_mems.begin();
src_it != src_mems.end();
++src_it)
for(std::vector<Memory>::const_iterator dst_it = dst_mems.begin();
dst_it != dst_mems.end();
++dst_it) {
log_app.print() << "srcmem=" << *src_it << " dstmem=" << *dst_it;
typedef int FT;
if((TestConfig::dim_mask & 1) != 0)
do_single_dim<1, FT>(*src_it, *dst_it, log2_buffer_size, 0, p);
if((TestConfig::dim_mask & 2) != 0)
do_single_dim<2, FT>(*src_it, *dst_it, log2_buffer_size,
TestConfig::narrow_dim, p);
if((TestConfig::dim_mask & 4) != 0)
do_single_dim<3, FT>(*src_it, *dst_it, log2_buffer_size,
TestConfig::narrow_dim, p);
}
}
int main(int argc, char **argv)
{
Runtime rt;
rt.init(&argc, &argv);
CommandLineParser cp;
cp.add_option_int_units("-b", TestConfig::buffer_size, 'M')
.add_option_int("-narrow", TestConfig::narrow_dim)
.add_option_int("-dims", TestConfig::dim_mask)
.add_option_int("-all", TestConfig::all_mems);
bool ok = cp.parse_command_line(argc, const_cast<const char **>(argv));
assert(ok);
rt.register_task(TOP_LEVEL_TASK, top_level_task);
Processor::register_task_by_kind(Processor::LOC_PROC, false /*!global*/,
COPYPROF_TASK,
CodeDescriptor(copy_profiling_task),
ProfilingRequestSet(),
0, 0).wait();
// select a processor to run the top level task on
Processor p = Machine::ProcessorQuery(Machine::get_machine())
.only_kind(Processor::LOC_PROC)
.first();
assert(p.exists());
// collective launch of a single task - everybody gets the same finish event
Event e = rt.collective_spawn(p, TOP_LEVEL_TASK, 0, 0);
// request shutdown once that task is complete
rt.shutdown(e);
// now sleep this thread until that shutdown actually happens
rt.wait_for_shutdown();
return 0;
}
<|endoftext|> |
<commit_before>/**
* @file
* @copyright defined in eos/LICENSE.txt
*/
#include <eosio/wallet_plugin/se_wallet.hpp>
#include <eosio/wallet_plugin/macos_user_auth.h>
#include <eosio/chain/exceptions.hpp>
#include <fc/crypto/openssl.hpp>
#include <boost/range/adaptor/map.hpp>
#include <boost/range/algorithm/copy.hpp>
#include <Security/Security.h>
#include <future>
namespace eosio { namespace wallet {
using namespace fc::crypto::r1;
namespace detail {
static void auth_callback(int success, void* data) {
promise<bool>* prom = (promise<bool>*)data;
prom->set_value(success);
}
struct se_wallet_impl {
static public_key_data get_public_key_data(SecKeyRef key) {
SecKeyRef pubkey = SecKeyCopyPublicKey(key);
CFErrorRef error = nullptr;
CFDataRef keyrep = nullptr;
keyrep = SecKeyCopyExternalRepresentation(pubkey, &error);
public_key_data pub_key_data;
if(!error) {
const UInt8* cfdata = CFDataGetBytePtr(keyrep);
memcpy(pub_key_data.data+1, cfdata+1, 32);
pub_key_data.data[0] = 0x02 + (cfdata[64]&1);
}
CFRelease(keyrep);
CFRelease(pubkey);
if(error) {
string error_string = string_for_cferror(error);
CFRelease(error);
FC_THROW_EXCEPTION(chain::wallet_exception, "Failed to get public key from Secure Enclave: ${m}", ("m", error_string));
}
return pub_key_data;
}
static public_key_type get_public_key(SecKeyRef key) {
char serialized_pub_key[sizeof(public_key_data) + 1];
serialized_pub_key[0] = 0x01;
public_key_data pub_key_data = get_public_key_data(key);
memcpy(serialized_pub_key+1, pub_key_data.data, sizeof(pub_key_data));
public_key_type pub_key;
fc::datastream<const char *> ds(serialized_pub_key, sizeof(serialized_pub_key));
fc::raw::unpack(ds, pub_key);
return pub_key;
}
static string string_for_cferror(CFErrorRef error) {
CFStringRef errorString = CFCopyDescription(error);
char buff[CFStringGetLength(errorString) + 1];
string ret;
if(CFStringGetCString(errorString, buff, sizeof(buff), kCFStringEncodingUTF8))
ret = buff;
else
ret = "Unknown";
CFRelease(errorString);
return ret;
}
#define XSTR(A) STR(A)
#define STR(A) #A
void populate_existing_keys() {
const void* keyAttrKeys[] = {
kSecClass,
kSecAttrKeyClass,
kSecMatchLimit,
kSecReturnRef,
kSecAttrTokenID,
kSecAttrAccessGroup
};
const void* keyAttrValues[] = {
kSecClassKey,
kSecAttrKeyClassPrivate,
kSecMatchLimitAll,
kCFBooleanTrue,
kSecAttrTokenIDSecureEnclave,
#ifdef MAS_KEYCHAIN_GROUP
CFSTR(XSTR(MAS_KEYCHAIN_GROUP))
#endif
};
CFDictionaryRef keyAttrDic = CFDictionaryCreate(nullptr, keyAttrKeys, keyAttrValues, sizeof(keyAttrValues)/sizeof(keyAttrValues[0]), &kCFTypeDictionaryKeyCallBacks, &kCFTypeDictionaryValueCallBacks);
CFArrayRef keyRefs = nullptr;
if(SecItemCopyMatching(keyAttrDic, (CFTypeRef*)&keyRefs) || !keyRefs) {
CFRelease(keyAttrDic);
return;
}
CFIndex count = CFArrayGetCount(keyRefs);
for(long i = 0; i < count; ++i) {
public_key_type pub;
try {
SecKeyRef key = (SecKeyRef)CFRetain(CFArrayGetValueAtIndex(keyRefs, i));
_keys[get_public_key(key)] = key;
}
catch(chain::wallet_exception&) {}
}
CFRelease(keyRefs);
CFRelease(keyAttrDic);
}
public_key_type create() {
SecAccessControlRef accessControlRef = SecAccessControlCreateWithFlags(nullptr, kSecAttrAccessibleWhenUnlockedThisDeviceOnly, kSecAccessControlPrivateKeyUsage, nullptr);
int keySizeValue = 256;
CFNumberRef keySizeNumber = CFNumberCreate(NULL, kCFNumberIntType, &keySizeValue);
const void* keyAttrKeys[] = {
kSecAttrIsPermanent,
kSecAttrAccessControl,
kSecAttrAccessGroup
};
const void* keyAttrValues[] = {
kCFBooleanTrue,
accessControlRef,
#ifdef MAS_KEYCHAIN_GROUP
CFSTR(XSTR(MAS_KEYCHAIN_GROUP))
#endif
};
CFDictionaryRef keyAttrDic = CFDictionaryCreate(NULL, keyAttrKeys, keyAttrValues, sizeof(keyAttrValues)/sizeof(keyAttrValues[0]), &kCFTypeDictionaryKeyCallBacks, &kCFTypeDictionaryValueCallBacks);
const void* attrKeys[] = {
kSecAttrKeyType,
kSecAttrKeySizeInBits,
kSecAttrTokenID,
kSecPrivateKeyAttrs
};
const void* atrrValues[] = {
kSecAttrKeyTypeECSECPrimeRandom,
keySizeNumber,
kSecAttrTokenIDSecureEnclave,
keyAttrDic
};
CFDictionaryRef attributesDic = CFDictionaryCreate(NULL, attrKeys, atrrValues, sizeof(attrKeys)/sizeof(attrKeys[0]), &kCFTypeDictionaryKeyCallBacks, &kCFTypeDictionaryValueCallBacks);
CFErrorRef error = NULL;
SecKeyRef privateKey = SecKeyCreateRandomKey(attributesDic, &error);
string error_string;
if(error) {
error_string = string_for_cferror(error);
CFRelease(error);
}
CFRelease(attributesDic);
CFRelease(keyAttrDic);
CFRelease(keySizeNumber);
CFRelease(accessControlRef);
if(error_string.size())
FC_THROW_EXCEPTION(chain::wallet_exception, "Failed to create key in Secure Enclave: ${m}", ("m", error_string));
public_key_type pub;
try {
pub = get_public_key(privateKey);
}
catch(chain::wallet_exception&) {
//possibly we should delete the key here?
CFRelease(privateKey);
throw;
}
_keys[pub] = privateKey;
return pub;
}
optional<signature_type> try_sign_digest(const digest_type d, const public_key_type public_key) {
auto it = _keys.find(public_key);
if(it == _keys.end())
return optional<signature_type>{};
fc::ecdsa_sig sig = ECDSA_SIG_new();
CFErrorRef error = nullptr;
CFDataRef digestData = CFDataCreateWithBytesNoCopy(nullptr, (UInt8*)d.data(), d.data_size(), kCFAllocatorNull);
CFDataRef signature = SecKeyCreateSignature(it->second, kSecKeyAlgorithmECDSASignatureDigestX962SHA256, digestData, &error);
if(error) {
string error_string = string_for_cferror(error);
CFRelease(error);
CFRelease(digestData);
FC_THROW_EXCEPTION(chain::wallet_exception, "Failed to sign digest in Secure Enclave: ${m}", ("m", error_string));
}
const UInt8* der_bytes = CFDataGetBytePtr(signature);
long derSize = CFDataGetLength(signature);
d2i_ECDSA_SIG(&sig.obj, &der_bytes, derSize);
public_key_data kd;
compact_signature compact_sig;
try {
kd = get_public_key_data(it->second);
compact_sig = signature_from_ecdsa(key, kd, sig, d);
} catch(chain::wallet_exception&) {
CFRelease(signature);
CFRelease(digestData);
throw;
}
CFRelease(signature);
CFRelease(digestData);
char serialized_signature[sizeof(compact_sig) + 1];
serialized_signature[0] = 0x01;
memcpy(serialized_signature+1, compact_sig.data, sizeof(compact_sig));
signature_type final_signature;
fc::datastream<const char *> ds(serialized_signature, sizeof(serialized_signature));
fc::raw::unpack(ds, final_signature);
return final_signature;
}
bool remove_key(string public_key) {
auto it = _keys.find(public_key_type{public_key});
if(it == _keys.end())
FC_THROW_EXCEPTION(chain::wallet_exception, "Given key to delete not found in Secure Enclave wallet");
promise<bool> prom;
future<bool> fut = prom.get_future();
macos_user_auth(auth_callback, &prom, CFSTR("remove a key from your EOSIO wallet"));
if(!fut.get())
FC_THROW_EXCEPTION(chain::wallet_invalid_password_exception, "Local user authentication failed");
CFDictionaryRef deleteDic = CFDictionaryCreate(nullptr, (const void**)&kSecValueRef, (const void**)&it->second, 1, &kCFTypeDictionaryKeyCallBacks, &kCFTypeDictionaryValueCallBacks);
OSStatus ret = SecItemDelete(deleteDic);
CFRelease(deleteDic);
if(ret)
FC_THROW_EXCEPTION(chain::wallet_exception, "Failed to getremove key from Secure Enclave");
CFRelease(it->second);
_keys.erase(it);
return true;
}
~se_wallet_impl() {
for(auto& k : _keys)
CFRelease(k.second);
}
map<public_key_type,SecKeyRef> _keys;
fc::ec_key key = EC_KEY_new_by_curve_name(NID_X9_62_prime256v1);
bool locked = true;
};
static void check_signed() {
OSStatus is_valid{0};
pid_t pid = getpid();
SecCodeRef code = nullptr;
CFNumberRef pidnumber = CFNumberCreate(kCFAllocatorDefault, kCFNumberSInt32Type, &pid);
CFDictionaryRef piddict = CFDictionaryCreate(kCFAllocatorDefault, (const void**)&kSecGuestAttributePid, (const void**)&pidnumber, 1, nullptr, nullptr);
if(!SecCodeCopyGuestWithAttributes(nullptr, piddict, kSecCSDefaultFlags, &code)) {
is_valid = SecCodeCheckValidity(code, kSecCSDefaultFlags, 0);
CFRelease(code);
}
CFRelease(piddict);
CFRelease(pidnumber);
if(is_valid != errSecSuccess) {
wlog("Application does not have a valid signature; Secure Enclave support disabled");
EOS_THROW(secure_enclave_exception, "");
}
}
}
se_wallet::se_wallet() : my(new detail::se_wallet_impl()) {
detail::check_signed();
//How to figure out of SE is available?!
char model[256];
size_t model_size = sizeof(model);
if(sysctlbyname("hw.model", model, &model_size, nullptr, 0) == 0) {
if(strncmp(model, "iMacPro", strlen("iMacPro")) == 0) {
my->populate_existing_keys();
return;
}
unsigned int major, minor;
if(sscanf(model, "MacBookPro%u,%u", &major, &minor) == 2) {
if(major >= 13 && minor >= 2) {
my->populate_existing_keys();
return;
}
}
}
EOS_THROW(secure_enclave_exception, "Secure Enclave not supported on this hardware");
}
se_wallet::~se_wallet() {
}
private_key_type se_wallet::get_private_key(public_key_type pubkey) const {
FC_THROW_EXCEPTION(chain::wallet_exception, "Obtaining private key for a key stored in Secure Enclave is impossible");
}
bool se_wallet::is_locked() const {
return my->locked;
}
void se_wallet::lock() {
EOS_ASSERT(!is_locked(), wallet_locked_exception, "You can not lock an already locked wallet");
my->locked = true;
}
void se_wallet::unlock(string password) {
promise<bool> prom;
future<bool> fut = prom.get_future();
macos_user_auth(detail::auth_callback, &prom, CFSTR("unlock your EOSIO wallet"));
if(!fut.get())
FC_THROW_EXCEPTION(chain::wallet_invalid_password_exception, "Local user authentication failed");
my->locked = false;
}
void se_wallet::check_password(string password) {
//just leave this as a noop for now; remove_key from wallet_mgr calls through here
}
void se_wallet::set_password(string password) {
FC_THROW_EXCEPTION(chain::wallet_exception, "Secure Enclave wallet cannot have a password set");
}
map<public_key_type, private_key_type> se_wallet::list_keys() {
FC_THROW_EXCEPTION(chain::wallet_exception, "Getting the private keys from the Secure Enclave wallet is impossible");
}
flat_set<public_key_type> se_wallet::list_public_keys() {
flat_set<public_key_type> keys;
boost::copy(my->_keys | boost::adaptors::map_keys, std::inserter(keys, keys.end()));
return keys;
}
bool se_wallet::import_key(string wif_key) {
FC_THROW_EXCEPTION(chain::wallet_exception, "It is not possible to import a key in to the Secure Enclave wallet");
}
string se_wallet::create_key(string key_type) {
return (string)my->create();
}
bool se_wallet::remove_key(string key) {
EOS_ASSERT(!is_locked(), wallet_locked_exception, "You can not remove a key from a locked wallet");
return my->remove_key(key);
}
optional<signature_type> se_wallet::try_sign_digest(const digest_type digest, const public_key_type public_key) {
return my->try_sign_digest(digest, public_key);
}
}}<commit_msg>Enable Secure Enclave wallet for 2018 MBP models<commit_after>/**
* @file
* @copyright defined in eos/LICENSE.txt
*/
#include <eosio/wallet_plugin/se_wallet.hpp>
#include <eosio/wallet_plugin/macos_user_auth.h>
#include <eosio/chain/exceptions.hpp>
#include <fc/crypto/openssl.hpp>
#include <boost/range/adaptor/map.hpp>
#include <boost/range/algorithm/copy.hpp>
#include <Security/Security.h>
#include <future>
namespace eosio { namespace wallet {
using namespace fc::crypto::r1;
namespace detail {
static void auth_callback(int success, void* data) {
promise<bool>* prom = (promise<bool>*)data;
prom->set_value(success);
}
struct se_wallet_impl {
static public_key_data get_public_key_data(SecKeyRef key) {
SecKeyRef pubkey = SecKeyCopyPublicKey(key);
CFErrorRef error = nullptr;
CFDataRef keyrep = nullptr;
keyrep = SecKeyCopyExternalRepresentation(pubkey, &error);
public_key_data pub_key_data;
if(!error) {
const UInt8* cfdata = CFDataGetBytePtr(keyrep);
memcpy(pub_key_data.data+1, cfdata+1, 32);
pub_key_data.data[0] = 0x02 + (cfdata[64]&1);
}
CFRelease(keyrep);
CFRelease(pubkey);
if(error) {
string error_string = string_for_cferror(error);
CFRelease(error);
FC_THROW_EXCEPTION(chain::wallet_exception, "Failed to get public key from Secure Enclave: ${m}", ("m", error_string));
}
return pub_key_data;
}
static public_key_type get_public_key(SecKeyRef key) {
char serialized_pub_key[sizeof(public_key_data) + 1];
serialized_pub_key[0] = 0x01;
public_key_data pub_key_data = get_public_key_data(key);
memcpy(serialized_pub_key+1, pub_key_data.data, sizeof(pub_key_data));
public_key_type pub_key;
fc::datastream<const char *> ds(serialized_pub_key, sizeof(serialized_pub_key));
fc::raw::unpack(ds, pub_key);
return pub_key;
}
static string string_for_cferror(CFErrorRef error) {
CFStringRef errorString = CFCopyDescription(error);
char buff[CFStringGetLength(errorString) + 1];
string ret;
if(CFStringGetCString(errorString, buff, sizeof(buff), kCFStringEncodingUTF8))
ret = buff;
else
ret = "Unknown";
CFRelease(errorString);
return ret;
}
#define XSTR(A) STR(A)
#define STR(A) #A
void populate_existing_keys() {
const void* keyAttrKeys[] = {
kSecClass,
kSecAttrKeyClass,
kSecMatchLimit,
kSecReturnRef,
kSecAttrTokenID,
kSecAttrAccessGroup
};
const void* keyAttrValues[] = {
kSecClassKey,
kSecAttrKeyClassPrivate,
kSecMatchLimitAll,
kCFBooleanTrue,
kSecAttrTokenIDSecureEnclave,
#ifdef MAS_KEYCHAIN_GROUP
CFSTR(XSTR(MAS_KEYCHAIN_GROUP))
#endif
};
CFDictionaryRef keyAttrDic = CFDictionaryCreate(nullptr, keyAttrKeys, keyAttrValues, sizeof(keyAttrValues)/sizeof(keyAttrValues[0]), &kCFTypeDictionaryKeyCallBacks, &kCFTypeDictionaryValueCallBacks);
CFArrayRef keyRefs = nullptr;
if(SecItemCopyMatching(keyAttrDic, (CFTypeRef*)&keyRefs) || !keyRefs) {
CFRelease(keyAttrDic);
return;
}
CFIndex count = CFArrayGetCount(keyRefs);
for(long i = 0; i < count; ++i) {
public_key_type pub;
try {
SecKeyRef key = (SecKeyRef)CFRetain(CFArrayGetValueAtIndex(keyRefs, i));
_keys[get_public_key(key)] = key;
}
catch(chain::wallet_exception&) {}
}
CFRelease(keyRefs);
CFRelease(keyAttrDic);
}
public_key_type create() {
SecAccessControlRef accessControlRef = SecAccessControlCreateWithFlags(nullptr, kSecAttrAccessibleWhenUnlockedThisDeviceOnly, kSecAccessControlPrivateKeyUsage, nullptr);
int keySizeValue = 256;
CFNumberRef keySizeNumber = CFNumberCreate(NULL, kCFNumberIntType, &keySizeValue);
const void* keyAttrKeys[] = {
kSecAttrIsPermanent,
kSecAttrAccessControl,
kSecAttrAccessGroup
};
const void* keyAttrValues[] = {
kCFBooleanTrue,
accessControlRef,
#ifdef MAS_KEYCHAIN_GROUP
CFSTR(XSTR(MAS_KEYCHAIN_GROUP))
#endif
};
CFDictionaryRef keyAttrDic = CFDictionaryCreate(NULL, keyAttrKeys, keyAttrValues, sizeof(keyAttrValues)/sizeof(keyAttrValues[0]), &kCFTypeDictionaryKeyCallBacks, &kCFTypeDictionaryValueCallBacks);
const void* attrKeys[] = {
kSecAttrKeyType,
kSecAttrKeySizeInBits,
kSecAttrTokenID,
kSecPrivateKeyAttrs
};
const void* atrrValues[] = {
kSecAttrKeyTypeECSECPrimeRandom,
keySizeNumber,
kSecAttrTokenIDSecureEnclave,
keyAttrDic
};
CFDictionaryRef attributesDic = CFDictionaryCreate(NULL, attrKeys, atrrValues, sizeof(attrKeys)/sizeof(attrKeys[0]), &kCFTypeDictionaryKeyCallBacks, &kCFTypeDictionaryValueCallBacks);
CFErrorRef error = NULL;
SecKeyRef privateKey = SecKeyCreateRandomKey(attributesDic, &error);
string error_string;
if(error) {
error_string = string_for_cferror(error);
CFRelease(error);
}
CFRelease(attributesDic);
CFRelease(keyAttrDic);
CFRelease(keySizeNumber);
CFRelease(accessControlRef);
if(error_string.size())
FC_THROW_EXCEPTION(chain::wallet_exception, "Failed to create key in Secure Enclave: ${m}", ("m", error_string));
public_key_type pub;
try {
pub = get_public_key(privateKey);
}
catch(chain::wallet_exception&) {
//possibly we should delete the key here?
CFRelease(privateKey);
throw;
}
_keys[pub] = privateKey;
return pub;
}
optional<signature_type> try_sign_digest(const digest_type d, const public_key_type public_key) {
auto it = _keys.find(public_key);
if(it == _keys.end())
return optional<signature_type>{};
fc::ecdsa_sig sig = ECDSA_SIG_new();
CFErrorRef error = nullptr;
CFDataRef digestData = CFDataCreateWithBytesNoCopy(nullptr, (UInt8*)d.data(), d.data_size(), kCFAllocatorNull);
CFDataRef signature = SecKeyCreateSignature(it->second, kSecKeyAlgorithmECDSASignatureDigestX962SHA256, digestData, &error);
if(error) {
string error_string = string_for_cferror(error);
CFRelease(error);
CFRelease(digestData);
FC_THROW_EXCEPTION(chain::wallet_exception, "Failed to sign digest in Secure Enclave: ${m}", ("m", error_string));
}
const UInt8* der_bytes = CFDataGetBytePtr(signature);
long derSize = CFDataGetLength(signature);
d2i_ECDSA_SIG(&sig.obj, &der_bytes, derSize);
public_key_data kd;
compact_signature compact_sig;
try {
kd = get_public_key_data(it->second);
compact_sig = signature_from_ecdsa(key, kd, sig, d);
} catch(chain::wallet_exception&) {
CFRelease(signature);
CFRelease(digestData);
throw;
}
CFRelease(signature);
CFRelease(digestData);
char serialized_signature[sizeof(compact_sig) + 1];
serialized_signature[0] = 0x01;
memcpy(serialized_signature+1, compact_sig.data, sizeof(compact_sig));
signature_type final_signature;
fc::datastream<const char *> ds(serialized_signature, sizeof(serialized_signature));
fc::raw::unpack(ds, final_signature);
return final_signature;
}
bool remove_key(string public_key) {
auto it = _keys.find(public_key_type{public_key});
if(it == _keys.end())
FC_THROW_EXCEPTION(chain::wallet_exception, "Given key to delete not found in Secure Enclave wallet");
promise<bool> prom;
future<bool> fut = prom.get_future();
macos_user_auth(auth_callback, &prom, CFSTR("remove a key from your EOSIO wallet"));
if(!fut.get())
FC_THROW_EXCEPTION(chain::wallet_invalid_password_exception, "Local user authentication failed");
CFDictionaryRef deleteDic = CFDictionaryCreate(nullptr, (const void**)&kSecValueRef, (const void**)&it->second, 1, &kCFTypeDictionaryKeyCallBacks, &kCFTypeDictionaryValueCallBacks);
OSStatus ret = SecItemDelete(deleteDic);
CFRelease(deleteDic);
if(ret)
FC_THROW_EXCEPTION(chain::wallet_exception, "Failed to getremove key from Secure Enclave");
CFRelease(it->second);
_keys.erase(it);
return true;
}
~se_wallet_impl() {
for(auto& k : _keys)
CFRelease(k.second);
}
map<public_key_type,SecKeyRef> _keys;
fc::ec_key key = EC_KEY_new_by_curve_name(NID_X9_62_prime256v1);
bool locked = true;
};
static void check_signed() {
OSStatus is_valid{0};
pid_t pid = getpid();
SecCodeRef code = nullptr;
CFNumberRef pidnumber = CFNumberCreate(kCFAllocatorDefault, kCFNumberSInt32Type, &pid);
CFDictionaryRef piddict = CFDictionaryCreate(kCFAllocatorDefault, (const void**)&kSecGuestAttributePid, (const void**)&pidnumber, 1, nullptr, nullptr);
if(!SecCodeCopyGuestWithAttributes(nullptr, piddict, kSecCSDefaultFlags, &code)) {
is_valid = SecCodeCheckValidity(code, kSecCSDefaultFlags, 0);
CFRelease(code);
}
CFRelease(piddict);
CFRelease(pidnumber);
if(is_valid != errSecSuccess) {
wlog("Application does not have a valid signature; Secure Enclave support disabled");
EOS_THROW(secure_enclave_exception, "");
}
}
}
se_wallet::se_wallet() : my(new detail::se_wallet_impl()) {
detail::check_signed();
//How to figure out of SE is available?!
char model[256];
size_t model_size = sizeof(model);
if(sysctlbyname("hw.model", model, &model_size, nullptr, 0) == 0) {
if(strncmp(model, "iMacPro", strlen("iMacPro")) == 0) {
my->populate_existing_keys();
return;
}
unsigned int major, minor;
if(sscanf(model, "MacBookPro%u,%u", &major, &minor) == 2) {
if((major >= 15) || (major >= 13 && minor >= 2)) {
my->populate_existing_keys();
return;
}
}
}
EOS_THROW(secure_enclave_exception, "Secure Enclave not supported on this hardware");
}
se_wallet::~se_wallet() {
}
private_key_type se_wallet::get_private_key(public_key_type pubkey) const {
FC_THROW_EXCEPTION(chain::wallet_exception, "Obtaining private key for a key stored in Secure Enclave is impossible");
}
bool se_wallet::is_locked() const {
return my->locked;
}
void se_wallet::lock() {
EOS_ASSERT(!is_locked(), wallet_locked_exception, "You can not lock an already locked wallet");
my->locked = true;
}
void se_wallet::unlock(string password) {
promise<bool> prom;
future<bool> fut = prom.get_future();
macos_user_auth(detail::auth_callback, &prom, CFSTR("unlock your EOSIO wallet"));
if(!fut.get())
FC_THROW_EXCEPTION(chain::wallet_invalid_password_exception, "Local user authentication failed");
my->locked = false;
}
void se_wallet::check_password(string password) {
//just leave this as a noop for now; remove_key from wallet_mgr calls through here
}
void se_wallet::set_password(string password) {
FC_THROW_EXCEPTION(chain::wallet_exception, "Secure Enclave wallet cannot have a password set");
}
map<public_key_type, private_key_type> se_wallet::list_keys() {
FC_THROW_EXCEPTION(chain::wallet_exception, "Getting the private keys from the Secure Enclave wallet is impossible");
}
flat_set<public_key_type> se_wallet::list_public_keys() {
flat_set<public_key_type> keys;
boost::copy(my->_keys | boost::adaptors::map_keys, std::inserter(keys, keys.end()));
return keys;
}
bool se_wallet::import_key(string wif_key) {
FC_THROW_EXCEPTION(chain::wallet_exception, "It is not possible to import a key in to the Secure Enclave wallet");
}
string se_wallet::create_key(string key_type) {
return (string)my->create();
}
bool se_wallet::remove_key(string key) {
EOS_ASSERT(!is_locked(), wallet_locked_exception, "You can not remove a key from a locked wallet");
return my->remove_key(key);
}
optional<signature_type> se_wallet::try_sign_digest(const digest_type digest, const public_key_type public_key) {
return my->try_sign_digest(digest, public_key);
}
}}<|endoftext|> |
<commit_before>/****************************************************************************
**
** Copyright (c) 2008-2009 Nokia Corporation and/or its subsidiary(-ies).
**
** Contact: Nokia Corporation (qt-info@nokia.com)
**
** This file is part of the Qt Mobility Components.
**
** $QT_BEGIN_LICENSE:LGPL$
** No Commercial Usage
** This file contains pre-release code and may not be distributed.
** You may use this file in accordance with the terms and conditions
** contained in the Technology Preview License Agreement accompanying
** this package.
**
** GNU Lesser General Public License Usage
** Alternatively, this file may be used under the terms of the GNU Lesser
** General Public License version 2.1 as published by the Free Software
** Foundation and appearing in the file LICENSE.LGPL included in the
** packaging of this file. Please review the following information to
** ensure the GNU Lesser General Public License version 2.1 requirements
** will be met: http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
**
** In addition, as a special exception, Nokia gives you certain
** additional rights. These rights are described in the Nokia Qt LGPL
** Exception version 1.0, included in the file LGPL_EXCEPTION.txt in this
** package.
**
** If you have questions regarding the use of this file, please contact
** Nokia at http://qt.nokia.com/contact.
** $QT_END_LICENSE$
**
****************************************************************************/
#include "qwmpserviceprovider.h"
#include "qwmpplayerservice.h"
QStringList QWmpServiceProviderPlugin::keys() const
{
return QStringList()
<< QLatin1String("mediaplayer")
<< QLatin1String("windowsmediaplayer");
}
QMediaService *QWmpServiceProviderPlugin::create(const QString &key)
{
if (qstrcmp(type.constData(), "mediaplayer") == 0)
return new QWmpPlayerService(QWmpPlayerService::LocalEmbed);
/*
else if (qstrcmp(iid, QRemoteMediaPlayerService_iid) == 0)
return new QWmpPlayerService(QWmpPlayerService::RemoteEmbed);
*/
return 0;
}
Q_EXPORT_PLUGIN2(qwmp, QWmpServiceProviderPlugin);
<commit_msg>WMP plugin; fix service provider.<commit_after>/****************************************************************************
**
** Copyright (c) 2008-2009 Nokia Corporation and/or its subsidiary(-ies).
**
** Contact: Nokia Corporation (qt-info@nokia.com)
**
** This file is part of the Qt Mobility Components.
**
** $QT_BEGIN_LICENSE:LGPL$
** No Commercial Usage
** This file contains pre-release code and may not be distributed.
** You may use this file in accordance with the terms and conditions
** contained in the Technology Preview License Agreement accompanying
** this package.
**
** GNU Lesser General Public License Usage
** Alternatively, this file may be used under the terms of the GNU Lesser
** General Public License version 2.1 as published by the Free Software
** Foundation and appearing in the file LICENSE.LGPL included in the
** packaging of this file. Please review the following information to
** ensure the GNU Lesser General Public License version 2.1 requirements
** will be met: http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
**
** In addition, as a special exception, Nokia gives you certain
** additional rights. These rights are described in the Nokia Qt LGPL
** Exception version 1.0, included in the file LGPL_EXCEPTION.txt in this
** package.
**
** If you have questions regarding the use of this file, please contact
** Nokia at http://qt.nokia.com/contact.
** $QT_END_LICENSE$
**
****************************************************************************/
#include "qwmpserviceprovider.h"
#include "qwmpplayerservice.h"
QStringList QWmpServiceProviderPlugin::keys() const
{
return QStringList()
<< QLatin1String("mediaplayer")
<< QLatin1String("windowsmediaplayer");
}
QMediaService *QWmpServiceProviderPlugin::create(const QString &key)
{
if (QLatin1String("mediaplayer") == key) {
QByteArray providerKey = qgetenv("QT_MEDIAPLAYER_PROVIDER");
if (!providerKey.isNull() && qstrcmp(providerKey.constData(), "windowsmediaplayer") == 0)
return new QWmpPlayerService(QWmpPlayerService::RemoteEmbed);
return new QWmpPlayerService(QWmpPlayerService::LocalEmbed);
}
else if (QLatin1String("windowsmediaplayer") == key)
return new QWmpPlayerService(QWmpPlayerService::RemoteEmbed);
return 0;
}
Q_EXPORT_PLUGIN2(qwmp, QWmpServiceProviderPlugin);
<|endoftext|> |
<commit_before>/*=========================================================================
Program: Insight Segmentation & Registration Toolkit
Module: DeformableRegistration4.cxx
Language: C++
Date: $Date$
Version: $Revision$
Copyright (c) Insight Software Consortium. All rights reserved.
See ITKCopyright.txt or http://www.itk.org/HTML/Copyright.htm for details.
This software is distributed WITHOUT ANY WARRANTY; without even
the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR
PURPOSE. See the above copyright notices for more information.
=========================================================================*/
// Software Guide : BeginLatex
//
// This example illustrates the use of the \doxygen{BSplineDeformableTransform}
// class for performing registration of two $2D$ images. The example code is
// for the most part identical to the code presented in
// Section~\ref{sec:RigidRegistrationIn2D}. The major difference is that this
// example we replace the Transform for a more generic one endowed with a large
// number of degrees of freedom.
//
//
// \index{itk::BSplineDeformableTransform}
// \index{itk::BSplineDeformableTransform!DeformableRegistration}
//
//
// Software Guide : EndLatex
#include "itkImageRegistrationMethod.h"
#include "itkMeanSquaresImageToImageMetric.h"
#include "itkLinearInterpolateImageFunction.h"
#include "itkImage.h"
// Software Guide : BeginLatex
//
// The following are the most relevant headers to this example.
//
// \index{itk::BSplineDeformableTransform!header}
//
// Software Guide : EndLatex
// Software Guide : BeginCodeSnippet
#include "itkBSplineDeformableTransform.h"
// Software Guide : EndCodeSnippet
// Software Guide : BeginLatex
//
// The parameter space of the \code{BSplineDeformableTransform} is composed by
// the set of all the deformations associated with the nodes of the BSpline
// grid. This large number of parameters makes possible to represent a wide
// variety of deformations, but it also has the price of requiring a
// significant amount of computation time.
//
// \index{itk::BSplineDeformableTransform!header}
//
// Software Guide : EndLatex
// Software Guide : BeginCodeSnippet
#include "itkRegularStepGradientDescentOptimizer.h"
// Software Guide : EndCodeSnippet
#include "itkImageFileReader.h"
#include "itkImageFileWriter.h"
#include "itkResampleImageFilter.h"
#include "itkCastImageFilter.h"
#include "itkSquaredDifferenceImageFilter.h"
// The following section of code implements a Command observer
// that will monitor the evolution of the registration process.
//
#include "itkCommand.h"
class CommandIterationUpdate : public itk::Command
{
public:
typedef CommandIterationUpdate Self;
typedef itk::Command Superclass;
typedef itk::SmartPointer<Self> Pointer;
itkNewMacro( Self );
protected:
CommandIterationUpdate() {};
public:
typedef itk::RegularStepGradientDescentOptimizer OptimizerType;
typedef const OptimizerType * OptimizerPointer;
void Execute(itk::Object *caller, const itk::EventObject & event)
{
Execute( (const itk::Object *)caller, event);
}
void Execute(const itk::Object * object, const itk::EventObject & event)
{
OptimizerPointer optimizer =
dynamic_cast< OptimizerPointer >( object );
if( typeid( event ) != typeid( itk::IterationEvent ) )
{
return;
}
std::cout << optimizer->GetCurrentIteration() << " ";
std::cout << optimizer->GetValue() << " ";
std::cout << optimizer->GetCurrentPosition() << std::endl;
}
};
int main( int argc, char *argv[] )
{
if( argc < 4 )
{
std::cerr << "Missing Parameters " << std::endl;
std::cerr << "Usage: " << argv[0];
std::cerr << " fixedImageFile movingImageFile ";
std::cerr << " outputImagefile [differenceOutputfile] ";
std::cerr << " [differenceBeforeRegistration] "<< std::endl;
return 1;
}
const unsigned int ImageDimension = 2;
typedef float PixelType;
typedef itk::Image< PixelType, ImageDimension > FixedImageType;
typedef itk::Image< PixelType, ImageDimension > MovingImageType;
// Software Guide : BeginLatex
//
// We instantiate now the type of the \code{BSplineDeformableTransform} using
// as template parameters the type for coordinates representation, the
// dimension of the space, and the order of the BSpline.
//
// \index{BSplineDeformableTransform|New}
// \index{BSplineDeformableTransform|Instantiation}
//
// Software Guide : EndLatex
// Software Guide : BeginCodeSnippet
const unsigned int SpaceDimension = ImageDimension;
const unsigned int SplineOrder = 3;
typedef double CoordinateRepType;
typedef itk::BSplineDeformableTransform<
CoordinateRepType,
SpaceDimension,
SplineOrder > TransformType;
// Software Guide : EndCodeSnippet
typedef itk::RegularStepGradientDescentOptimizer OptimizerType;
typedef itk::MeanSquaresImageToImageMetric<
FixedImageType,
MovingImageType > MetricType;
typedef itk:: LinearInterpolateImageFunction<
MovingImageType,
double > InterpolatorType;
typedef itk::ImageRegistrationMethod<
FixedImageType,
MovingImageType > RegistrationType;
MetricType::Pointer metric = MetricType::New();
OptimizerType::Pointer optimizer = OptimizerType::New();
InterpolatorType::Pointer interpolator = InterpolatorType::New();
RegistrationType::Pointer registration = RegistrationType::New();
registration->SetMetric( metric );
registration->SetOptimizer( optimizer );
registration->SetInterpolator( interpolator );
// Software Guide : BeginLatex
//
// The transform object is constructed below and passed to the registration
// method.
//
// \index{itk::VersorRigid3DTransform!New()}
// \index{itk::VersorRigid3DTransform!Pointer}
// \index{itk::RegistrationMethod!SetTransform()}
//
// Software Guide : EndLatex
// Software Guide : BeginCodeSnippet
TransformType::Pointer transform = TransformType::New();
registration->SetTransform( transform );
// Software Guide : EndCodeSnippet
typedef itk::ImageFileReader< FixedImageType > FixedImageReaderType;
typedef itk::ImageFileReader< MovingImageType > MovingImageReaderType;
FixedImageReaderType::Pointer fixedImageReader = FixedImageReaderType::New();
MovingImageReaderType::Pointer movingImageReader = MovingImageReaderType::New();
fixedImageReader->SetFileName( argv[1] );
movingImageReader->SetFileName( argv[2] );
FixedImageType::ConstPointer fixedImage = fixedImageReader->GetOutput();
registration->SetFixedImage( fixedImage );
registration->SetMovingImage( movingImageReader->GetOutput() );
fixedImageReader->Update();
FixedImageType::RegionType fixedRegion = fixedImage->GetBufferedRegion();
registration->SetFixedImageRegion( fixedRegion );
// Software Guide : BeginLatex
//
// Here we define the parameters of the BSplineDeformableTransform grid. We
// arbitrarily decide to use a grid with $10 \times 10$ nodes. We compute
// its spacing from the image spacing and the resolution ratio. We also
// assign its origin from the origin of the fixed image.
//
// \index{BSplineDeformableTransform}
//
// Software Guide : EndLatex
// Software Guide : BeginCodeSnippet
typedef TransformType::RegionType RegionType;
RegionType bsplineRegion;
RegionType::SizeType size;
size.Fill( 10 );
bsplineRegion.SetSize( size );
typedef TransformType::SpacingType SpacingType;
SpacingType spacing = fixedImage->GetSpacing();
typedef TransformType::OriginType OriginType;
OriginType origin = fixedImage->GetOrigin();;
FixedImageType::SizeType fixedImageSize = fixedRegion.GetSize();
for(unsigned int r=0; r<ImageDimension; r++)
{
spacing[r] *= fixedImageSize[r] / size[r];
}
transform->SetGridSpacing( spacing );
transform->SetGridOrigin( origin );
transform->SetGridRegion( bsplineRegion );
typedef TransformType::ParametersType ParametersType;
const unsigned int numberOfParameters =
transform->GetNumberOfParameters();
ParametersType parameters( numberOfParameters );
parameters.Fill( 0.0 );
// Software Guide : EndCodeSnippet
// Software Guide : BeginLatex
//
// We now pass the parameters of the current transform as the initial
// parameters to be used when the registration process starts.
//
// Software Guide : EndLatex
// Software Guide : BeginCodeSnippet
registration->SetInitialTransformParameters( transform->GetParameters() );
// Software Guide : EndCodeSnippet
std::cout << "Intial Parameters = " << std::endl;
std::cout << transform->GetParameters() << std::endl;
typedef OptimizerType::ScalesType OptimizerScalesType;
OptimizerScalesType optimizerScales( transform->GetNumberOfParameters() );
optimizerScales.Fill( 1.0 ); // All parameters have the same dynamic range.
optimizer->SetScales( optimizerScales );
optimizer->SetMaximumStepLength( 1.000 );
optimizer->SetMinimumStepLength( 0.001 );
optimizer->SetNumberOfIterations( 200 );
// Create the Command observer and register it with the optimizer.
//
CommandIterationUpdate::Pointer observer = CommandIterationUpdate::New();
optimizer->AddObserver( itk::IterationEvent(), observer );
std::cout << std::endl << "Starting Registration" << std::endl;
try
{
registration->StartRegistration();
}
catch( itk::ExceptionObject & err )
{
std::cerr << "ExceptionObject caught !" << std::endl;
std::cerr << err << std::endl;
return -1;
}
OptimizerType::ParametersType finalParameters =
registration->GetLastTransformParameters();
const unsigned int numberOfIterations = optimizer->GetCurrentIteration();
const double bestValue = optimizer->GetValue();
// Print out results
//
std::cout << "Result = " << std::endl;
std::cout << " Iterations = " << numberOfIterations << std::endl;
std::cout << " Metric value = " << bestValue << std::endl;
// Software Guide : BeginLatex
//
// Let's execute this example over some of the images available in
// the ftp site, for example:
//
// \begin{itemize}
// \item \code{brainweb165a10f17.mha}
// \item \code{brainweb165a10f17Rot10Tx15.mha}
// \end{itemize}
//
//
// Software Guide : EndLatex
// Software Guide : BeginCodeSnippet
transform->SetParameters( finalParameters );
// Software Guide : EndCodeSnippet
typedef itk::ResampleImageFilter<
MovingImageType,
FixedImageType > ResampleFilterType;
TransformType::Pointer finalTransform = TransformType::New();
finalTransform->SetParameters( finalParameters );
ResampleFilterType::Pointer resample = ResampleFilterType::New();
resample->SetTransform( finalTransform );
resample->SetInput( movingImageReader->GetOutput() );
resample->SetSize( fixedImage->GetLargestPossibleRegion().GetSize() );
resample->SetOutputOrigin( fixedImage->GetOrigin() );
resample->SetOutputSpacing( fixedImage->GetSpacing() );
resample->SetDefaultPixelValue( 100 );
typedef unsigned char OutputPixelType;
typedef itk::Image< OutputPixelType, ImageDimension > OutputImageType;
typedef itk::CastImageFilter<
FixedImageType,
OutputImageType > CastFilterType;
typedef itk::ImageFileWriter< OutputImageType > WriterType;
WriterType::Pointer writer = WriterType::New();
CastFilterType::Pointer caster = CastFilterType::New();
writer->SetFileName( argv[3] );
caster->SetInput( resample->GetOutput() );
writer->SetInput( caster->GetOutput() );
writer->Update();
typedef itk::SquaredDifferenceImageFilter<
FixedImageType,
FixedImageType,
OutputImageType > DifferenceFilterType;
DifferenceFilterType::Pointer difference = DifferenceFilterType::New();
WriterType::Pointer writer2 = WriterType::New();
writer2->SetInput( difference->GetOutput() );
// Compute the difference image between the
// fixed and resampled moving image.
if( argc >= 5 )
{
difference->SetInput1( fixedImageReader->GetOutput() );
difference->SetInput2( resample->GetOutput() );
writer2->SetFileName( argv[4] );
writer2->Update();
}
// Compute the difference image between the
// fixed and moving image before registration.
if( argc >= 6 )
{
writer2->SetFileName( argv[5] );
difference->SetInput1( fixedImageReader->GetOutput() );
difference->SetInput2( movingImageReader->GetOutput() );
writer2->Update();
}
return 0;
}
<commit_msg>ENH: try/catch blocks added around every Update(). FIX: finaltransform is now created by setting the parameters into the transform object used during the registration process.<commit_after>/*=========================================================================
Program: Insight Segmentation & Registration Toolkit
Module: DeformableRegistration4.cxx
Language: C++
Date: $Date$
Version: $Revision$
Copyright (c) Insight Software Consortium. All rights reserved.
See ITKCopyright.txt or http://www.itk.org/HTML/Copyright.htm for details.
This software is distributed WITHOUT ANY WARRANTY; without even
the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR
PURPOSE. See the above copyright notices for more information.
=========================================================================*/
// Software Guide : BeginLatex
//
// This example illustrates the use of the \doxygen{BSplineDeformableTransform}
// class for performing registration of two $2D$ images. The example code is
// for the most part identical to the code presented in
// Section~\ref{sec:RigidRegistrationIn2D}. The major difference is that this
// example we replace the Transform for a more generic one endowed with a large
// number of degrees of freedom.
//
//
// \index{itk::BSplineDeformableTransform}
// \index{itk::BSplineDeformableTransform!DeformableRegistration}
//
//
// Software Guide : EndLatex
#include "itkImageRegistrationMethod.h"
#include "itkMeanSquaresImageToImageMetric.h"
#include "itkLinearInterpolateImageFunction.h"
#include "itkImage.h"
// Software Guide : BeginLatex
//
// The following are the most relevant headers to this example.
//
// \index{itk::BSplineDeformableTransform!header}
//
// Software Guide : EndLatex
// Software Guide : BeginCodeSnippet
#include "itkBSplineDeformableTransform.h"
// Software Guide : EndCodeSnippet
// Software Guide : BeginLatex
//
// The parameter space of the \code{BSplineDeformableTransform} is composed by
// the set of all the deformations associated with the nodes of the BSpline
// grid. This large number of parameters makes possible to represent a wide
// variety of deformations, but it also has the price of requiring a
// significant amount of computation time.
//
// \index{itk::BSplineDeformableTransform!header}
//
// Software Guide : EndLatex
// Software Guide : BeginCodeSnippet
#include "itkRegularStepGradientDescentOptimizer.h"
// Software Guide : EndCodeSnippet
#include "itkImageFileReader.h"
#include "itkImageFileWriter.h"
#include "itkResampleImageFilter.h"
#include "itkCastImageFilter.h"
#include "itkSquaredDifferenceImageFilter.h"
// The following section of code implements a Command observer
// that will monitor the evolution of the registration process.
//
#include "itkCommand.h"
class CommandIterationUpdate : public itk::Command
{
public:
typedef CommandIterationUpdate Self;
typedef itk::Command Superclass;
typedef itk::SmartPointer<Self> Pointer;
itkNewMacro( Self );
protected:
CommandIterationUpdate() {};
public:
typedef itk::RegularStepGradientDescentOptimizer OptimizerType;
typedef const OptimizerType * OptimizerPointer;
void Execute(itk::Object *caller, const itk::EventObject & event)
{
Execute( (const itk::Object *)caller, event);
}
void Execute(const itk::Object * object, const itk::EventObject & event)
{
OptimizerPointer optimizer =
dynamic_cast< OptimizerPointer >( object );
if( typeid( event ) != typeid( itk::IterationEvent ) )
{
return;
}
std::cout << optimizer->GetCurrentIteration() << " ";
std::cout << optimizer->GetValue() << std::endl;
}
};
int main( int argc, char *argv[] )
{
if( argc < 4 )
{
std::cerr << "Missing Parameters " << std::endl;
std::cerr << "Usage: " << argv[0];
std::cerr << " fixedImageFile movingImageFile ";
std::cerr << " outputImagefile [differenceOutputfile] ";
std::cerr << " [differenceBeforeRegistration] "<< std::endl;
return 1;
}
const unsigned int ImageDimension = 2;
typedef float PixelType;
typedef itk::Image< PixelType, ImageDimension > FixedImageType;
typedef itk::Image< PixelType, ImageDimension > MovingImageType;
// Software Guide : BeginLatex
//
// We instantiate now the type of the \code{BSplineDeformableTransform} using
// as template parameters the type for coordinates representation, the
// dimension of the space, and the order of the BSpline.
//
// \index{BSplineDeformableTransform|New}
// \index{BSplineDeformableTransform|Instantiation}
//
// Software Guide : EndLatex
// Software Guide : BeginCodeSnippet
const unsigned int SpaceDimension = ImageDimension;
const unsigned int SplineOrder = 3;
typedef double CoordinateRepType;
typedef itk::BSplineDeformableTransform<
CoordinateRepType,
SpaceDimension,
SplineOrder > TransformType;
// Software Guide : EndCodeSnippet
typedef itk::RegularStepGradientDescentOptimizer OptimizerType;
typedef itk::MeanSquaresImageToImageMetric<
FixedImageType,
MovingImageType > MetricType;
typedef itk:: LinearInterpolateImageFunction<
MovingImageType,
double > InterpolatorType;
typedef itk::ImageRegistrationMethod<
FixedImageType,
MovingImageType > RegistrationType;
MetricType::Pointer metric = MetricType::New();
OptimizerType::Pointer optimizer = OptimizerType::New();
InterpolatorType::Pointer interpolator = InterpolatorType::New();
RegistrationType::Pointer registration = RegistrationType::New();
registration->SetMetric( metric );
registration->SetOptimizer( optimizer );
registration->SetInterpolator( interpolator );
// Software Guide : BeginLatex
//
// The transform object is constructed below and passed to the registration
// method.
//
// \index{itk::VersorRigid3DTransform!New()}
// \index{itk::VersorRigid3DTransform!Pointer}
// \index{itk::RegistrationMethod!SetTransform()}
//
// Software Guide : EndLatex
// Software Guide : BeginCodeSnippet
TransformType::Pointer transform = TransformType::New();
registration->SetTransform( transform );
// Software Guide : EndCodeSnippet
typedef itk::ImageFileReader< FixedImageType > FixedImageReaderType;
typedef itk::ImageFileReader< MovingImageType > MovingImageReaderType;
FixedImageReaderType::Pointer fixedImageReader = FixedImageReaderType::New();
MovingImageReaderType::Pointer movingImageReader = MovingImageReaderType::New();
fixedImageReader->SetFileName( argv[1] );
movingImageReader->SetFileName( argv[2] );
FixedImageType::ConstPointer fixedImage = fixedImageReader->GetOutput();
registration->SetFixedImage( fixedImage );
registration->SetMovingImage( movingImageReader->GetOutput() );
fixedImageReader->Update();
FixedImageType::RegionType fixedRegion = fixedImage->GetBufferedRegion();
registration->SetFixedImageRegion( fixedRegion );
// Software Guide : BeginLatex
//
// Here we define the parameters of the BSplineDeformableTransform grid. We
// arbitrarily decide to use a grid with $10 \times 10$ nodes. We compute
// its spacing from the image spacing and the resolution ratio. We also
// assign its origin from the origin of the fixed image.
//
// \index{BSplineDeformableTransform}
//
// Software Guide : EndLatex
// Software Guide : BeginCodeSnippet
typedef TransformType::RegionType RegionType;
RegionType bsplineRegion;
RegionType::SizeType size;
size.Fill( 10 );
bsplineRegion.SetSize( size );
typedef TransformType::SpacingType SpacingType;
SpacingType spacing = fixedImage->GetSpacing();
typedef TransformType::OriginType OriginType;
OriginType origin = fixedImage->GetOrigin();;
FixedImageType::SizeType fixedImageSize = fixedRegion.GetSize();
for(unsigned int r=0; r<ImageDimension; r++)
{
spacing[r] *= fixedImageSize[r] / size[r];
}
transform->SetGridSpacing( spacing );
transform->SetGridOrigin( origin );
transform->SetGridRegion( bsplineRegion );
typedef TransformType::ParametersType ParametersType;
const unsigned int numberOfParameters =
transform->GetNumberOfParameters();
ParametersType parameters( numberOfParameters );
parameters.Fill( 0.0 );
transform->SetParameters( parameters );
// Software Guide : EndCodeSnippet
// Software Guide : BeginLatex
//
// We now pass the parameters of the current transform as the initial
// parameters to be used when the registration process starts.
//
// Software Guide : EndLatex
// Software Guide : BeginCodeSnippet
registration->SetInitialTransformParameters( transform->GetParameters() );
// Software Guide : EndCodeSnippet
std::cout << "Intial Parameters = " << std::endl;
std::cout << transform->GetParameters() << std::endl;
transform->Print( std::cout );
typedef OptimizerType::ScalesType OptimizerScalesType;
OptimizerScalesType optimizerScales( numberOfParameters );
optimizerScales.Fill( 1.0 ); // All parameters have the same dynamic range.
optimizer->SetScales( optimizerScales );
optimizer->SetMaximumStepLength( 10.00 );
optimizer->SetMinimumStepLength( 0.01 );
optimizer->SetNumberOfIterations( 200 );
// Create the Command observer and register it with the optimizer.
//
CommandIterationUpdate::Pointer observer = CommandIterationUpdate::New();
optimizer->AddObserver( itk::IterationEvent(), observer );
std::cout << std::endl << "Starting Registration" << std::endl;
try
{
registration->StartRegistration();
}
catch( itk::ExceptionObject & err )
{
std::cerr << "ExceptionObject caught !" << std::endl;
std::cerr << err << std::endl;
return -1;
}
OptimizerType::ParametersType finalParameters =
registration->GetLastTransformParameters();
std::cout << "Last Transform Parameters" << std::endl;
std::cout << finalParameters << std::endl;
const unsigned int numberOfIterations = optimizer->GetCurrentIteration();
const double bestValue = optimizer->GetValue();
// Print out results
//
std::cout << "Result = " << std::endl;
std::cout << " Iterations = " << numberOfIterations << std::endl;
std::cout << " Metric value = " << bestValue << std::endl;
// Software Guide : BeginLatex
//
// Let's execute this example over some of the images available in
// the ftp site, for example:
//
// \begin{itemize}
// \item \code{brainweb165a10f17.mha}
// \item \code{brainweb165a10f17Rot10Tx15.mha}
// \end{itemize}
//
//
// Software Guide : EndLatex
// Software Guide : BeginCodeSnippet
transform->SetParameters( finalParameters );
// Software Guide : EndCodeSnippet
typedef itk::ResampleImageFilter<
MovingImageType,
FixedImageType > ResampleFilterType;
ResampleFilterType::Pointer resample = ResampleFilterType::New();
resample->SetTransform( transform );
resample->SetInput( movingImageReader->GetOutput() );
resample->SetSize( fixedImage->GetLargestPossibleRegion().GetSize() );
resample->SetOutputOrigin( fixedImage->GetOrigin() );
resample->SetOutputSpacing( fixedImage->GetSpacing() );
resample->SetDefaultPixelValue( 100 );
typedef unsigned char OutputPixelType;
typedef itk::Image< OutputPixelType, ImageDimension > OutputImageType;
typedef itk::CastImageFilter<
FixedImageType,
OutputImageType > CastFilterType;
typedef itk::ImageFileWriter< OutputImageType > WriterType;
WriterType::Pointer writer = WriterType::New();
CastFilterType::Pointer caster = CastFilterType::New();
writer->SetFileName( argv[3] );
caster->SetInput( resample->GetOutput() );
writer->SetInput( caster->GetOutput() );
try
{
writer->Update();
}
catch( itk::ExceptionObject & err )
{
std::cerr << "ExceptionObject caught !" << std::endl;
std::cerr << err << std::endl;
return -1;
}
typedef itk::SquaredDifferenceImageFilter<
FixedImageType,
FixedImageType,
OutputImageType > DifferenceFilterType;
DifferenceFilterType::Pointer difference = DifferenceFilterType::New();
WriterType::Pointer writer2 = WriterType::New();
writer2->SetInput( difference->GetOutput() );
// Compute the difference image between the
// fixed and resampled moving image.
if( argc >= 5 )
{
difference->SetInput1( fixedImageReader->GetOutput() );
difference->SetInput2( resample->GetOutput() );
writer2->SetFileName( argv[4] );
try
{
writer2->Update();
}
catch( itk::ExceptionObject & err )
{
std::cerr << "ExceptionObject caught !" << std::endl;
std::cerr << err << std::endl;
return -1;
}
}
// Compute the difference image between the
// fixed and moving image before registration.
if( argc >= 6 )
{
writer2->SetFileName( argv[5] );
difference->SetInput1( fixedImageReader->GetOutput() );
difference->SetInput2( movingImageReader->GetOutput() );
try
{
writer2->Update();
}
catch( itk::ExceptionObject & err )
{
std::cerr << "ExceptionObject caught !" << std::endl;
std::cerr << err << std::endl;
return -1;
}
}
return 0;
}
<|endoftext|> |
<commit_before>/*=========================================================================
Program: Insight Segmentation & Registration Toolkit
Module: MeanSquaresImageMetric1.cxx
Language: C++
Date: $Date$
Version: $Revision$
Copyright (c) Insight Software Consortium. All rights reserved.
See ITKCopyright.txt or http://www.itk.org/HTML/Copyright.htm for details.
This software is distributed WITHOUT ANY WARRANTY; without even
the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR
PURPOSE. See the above copyright notices for more information.
=========================================================================*/
#if defined(_MSC_VER)
#pragma warning ( disable : 4786 )
#endif
// Software Guide : BeginLatex
//
// This example illustrates how to explore the domain of an image metric. This
// is a useful exercise to do before starting a registration process, since
// getting familiar with the characteristics of the metric is fundamental for
// the apropriate selection of the optimizer to be use for driving the
// registration process, as well as for selecting the optimizer parameters.
// This process makes possible to identify how noisy a metric may be in a given
// range of parameters, and it will also give an idea of the number of local
// minima or maxima in which an optimizer may get trapped while exploring the
// parametric space.
//
// Software Guide : EndLatex
#include "itkImage.h"
#include "itkImageFileReader.h"
#include "itkImageFileWriter.h"
// Software Guide : BeginLatex
//
// We start by including the headers of the basic components: Metric, Transform
// and Interpolator.
//
// Software Guide : EndLatex
// Software Guide : BeginCodeSnippet
#include "itkMeanSquaresImageToImageMetric.h"
#include "itkTranslationTransform.h"
#include "itkNearestNeighborInterpolateImageFunction.h"
// Software Guide : EndCodeSnippet
int main( int argc, char * argv[] )
{
if( argc < 3 )
{
std::cerr << "Usage: " << std::endl;
std::cerr << argv[0] << " fixedImage movingImage" << std::endl;
return 1;
}
// Software Guide : BeginLatex
//
// We define the dimension and pixel type of the images to be used in the
// evaluation of the Metric.
//
// Software Guide : EndLatex
// Software Guide : BeginCodeSnippet
const unsigned int Dimension = 2;
typedef unsigned char PixelType;
typedef itk::Image< PixelType, Dimension > ImageType;
// Software Guide : EndCodeSnippet
typedef itk::ImageFileReader< ImageType > ReaderType;
ReaderType::Pointer fixedReader = ReaderType::New();
ReaderType::Pointer movingReader = ReaderType::New();
fixedReader->SetFileName( argv[ 1 ] );
movingReader->SetFileName( argv[ 2 ] );
try
{
fixedReader->Update();
movingReader->Update();
}
catch( itk::ExceptionObject & excep )
{
std::cerr << "Exception catched !" << std::endl;
std::cerr << excep << std::endl;
}
// Software Guide : BeginLatex
//
// The type of the Metric is instantiated and one is constructed. In this case
// we decided to use the same image type for both the fixed and the moving
// images.
//
// Software Guide : EndLatex
// Software Guide : BeginCodeSnippet
typedef itk::MeanSquaresImageToImageMetric<
ImageType, ImageType > MetricType;
MetricType::Pointer metric = MetricType::New();
// Software Guide : EndCodeSnippet
// Software Guide : BeginLatex
//
// We also instantiate the transform and interpolator types, and create objects
// of each class.
//
// Software Guide : EndLatex
// Software Guide : BeginCodeSnippet
typedef itk::TranslationTransform< double, Dimension > TransformType;
TransformType::Pointer transform = TransformType::New();
typedef itk::NearestNeighborInterpolateImageFunction<
ImageType, double > InterpolatorType;
InterpolatorType::Pointer interpolator = InterpolatorType::New();
// Software Guide : EndCodeSnippet
transform->SetIdentity();
ImageType::ConstPointer fixedImage = fixedReader->GetOutput();
ImageType::ConstPointer movingImage = movingReader->GetOutput();
// Software Guide : BeginLatex
//
// The classes required by the metric are connected to it. This includes the
// fixed and moving images, the interpolator and the transform.
//
// Software Guide : EndLatex
// Software Guide : BeginCodeSnippet
metric->SetTransform( transform );
metric->SetInterpolator( interpolator );
metric->SetFixedImage( fixedImage );
metric->SetMovingImage( movingImage );
// Software Guide : EndCodeSnippet
metric->SetFixedImageRegion( fixedImage->GetBufferedRegion() );
try
{
metric->Initialize();
}
catch( itk::ExceptionObject & excep )
{
std::cerr << "Exception catched !" << std::endl;
std::cerr << excep << std::endl;
return -1;
}
// Software Guide : BeginLatex
//
// Finally we select a region of the parametric to explore. In this case we are
// using a translation transform in 2D, so we simply select translations from a
// negative position to a positive position, in both $x$ and $y$. For each one
// of those positions we invoke the GetValue() method of the Metric.
//
// Software Guide : EndLatex
// Software Guide : BeginCodeSnippet
MetricType::TransformParametersType displacement( Dimension );
const int rangex = 50;
const int rangey = 50;
for( int dx = -rangex; dx <= rangex; dx++ )
{
for( int dy = -rangey; dy <= rangey; dy++ )
{
displacement[0] = dx;
displacement[1] = dy;
const double value = metric->GetValue( displacement );
std::cout << dx << " " << dy << " " << value << std::endl;
}
}
// Software Guide : EndCodeSnippet
// Software Guide : BeginLatex
//
// Running this code using the image BrainProtonDensitySlice.png as both the
// fixed and the moving images results in the plot shown in
// Figure~\ref{fig:MeanSquaresMetricPlot}. From this Figure, it can be seen
// that a gradient based optimizer will be appropriate for finding the extrema
// of the Metric. It is also possible to estimate a good value for the step
// length of a gradient-descent optimizer.
//
// This exercise of plotting the Metric is probably the best thing to do when a
// registration process is not converging and when it is unclear how to fine
// tune the different parameters involved in the registration. This includes
// the optimizer parameters, the metric parameters and even options such as
// preprocessing the image data with smoothing filters.
//
// Of course, this plotting exercise becomes more challenging when the
// transform has more than three parameters, and when those parameters have
// very different range of values.
//
//
// Software Guide : EndLatex
return 0;
}
<commit_msg>STYLE: Adding the two Metric plots generated with a shell and gnuplot scripts.<commit_after>/*=========================================================================
Program: Insight Segmentation & Registration Toolkit
Module: MeanSquaresImageMetric1.cxx
Language: C++
Date: $Date$
Version: $Revision$
Copyright (c) Insight Software Consortium. All rights reserved.
See ITKCopyright.txt or http://www.itk.org/HTML/Copyright.htm for details.
This software is distributed WITHOUT ANY WARRANTY; without even
the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR
PURPOSE. See the above copyright notices for more information.
=========================================================================*/
#if defined(_MSC_VER)
#pragma warning ( disable : 4786 )
#endif
// Software Guide : BeginLatex
//
// This example illustrates how to explore the domain of an image metric. This
// is a useful exercise to do before starting a registration process, since
// getting familiar with the characteristics of the metric is fundamental for
// the apropriate selection of the optimizer to be use for driving the
// registration process, as well as for selecting the optimizer parameters.
// This process makes possible to identify how noisy a metric may be in a given
// range of parameters, and it will also give an idea of the number of local
// minima or maxima in which an optimizer may get trapped while exploring the
// parametric space.
//
// Software Guide : EndLatex
#include "itkImage.h"
#include "itkImageFileReader.h"
#include "itkImageFileWriter.h"
// Software Guide : BeginLatex
//
// We start by including the headers of the basic components: Metric, Transform
// and Interpolator.
//
// Software Guide : EndLatex
// Software Guide : BeginCodeSnippet
#include "itkMeanSquaresImageToImageMetric.h"
#include "itkTranslationTransform.h"
#include "itkNearestNeighborInterpolateImageFunction.h"
// Software Guide : EndCodeSnippet
int main( int argc, char * argv[] )
{
if( argc < 3 )
{
std::cerr << "Usage: " << std::endl;
std::cerr << argv[0] << " fixedImage movingImage" << std::endl;
return 1;
}
// Software Guide : BeginLatex
//
// We define the dimension and pixel type of the images to be used in the
// evaluation of the Metric.
//
// Software Guide : EndLatex
// Software Guide : BeginCodeSnippet
const unsigned int Dimension = 2;
typedef unsigned char PixelType;
typedef itk::Image< PixelType, Dimension > ImageType;
// Software Guide : EndCodeSnippet
typedef itk::ImageFileReader< ImageType > ReaderType;
ReaderType::Pointer fixedReader = ReaderType::New();
ReaderType::Pointer movingReader = ReaderType::New();
fixedReader->SetFileName( argv[ 1 ] );
movingReader->SetFileName( argv[ 2 ] );
try
{
fixedReader->Update();
movingReader->Update();
}
catch( itk::ExceptionObject & excep )
{
std::cerr << "Exception catched !" << std::endl;
std::cerr << excep << std::endl;
}
// Software Guide : BeginLatex
//
// The type of the Metric is instantiated and one is constructed. In this case
// we decided to use the same image type for both the fixed and the moving
// images.
//
// Software Guide : EndLatex
// Software Guide : BeginCodeSnippet
typedef itk::MeanSquaresImageToImageMetric<
ImageType, ImageType > MetricType;
MetricType::Pointer metric = MetricType::New();
// Software Guide : EndCodeSnippet
// Software Guide : BeginLatex
//
// We also instantiate the transform and interpolator types, and create objects
// of each class.
//
// Software Guide : EndLatex
// Software Guide : BeginCodeSnippet
typedef itk::TranslationTransform< double, Dimension > TransformType;
TransformType::Pointer transform = TransformType::New();
typedef itk::NearestNeighborInterpolateImageFunction<
ImageType, double > InterpolatorType;
InterpolatorType::Pointer interpolator = InterpolatorType::New();
// Software Guide : EndCodeSnippet
transform->SetIdentity();
ImageType::ConstPointer fixedImage = fixedReader->GetOutput();
ImageType::ConstPointer movingImage = movingReader->GetOutput();
// Software Guide : BeginLatex
//
// The classes required by the metric are connected to it. This includes the
// fixed and moving images, the interpolator and the transform.
//
// Software Guide : EndLatex
// Software Guide : BeginCodeSnippet
metric->SetTransform( transform );
metric->SetInterpolator( interpolator );
metric->SetFixedImage( fixedImage );
metric->SetMovingImage( movingImage );
// Software Guide : EndCodeSnippet
metric->SetFixedImageRegion( fixedImage->GetBufferedRegion() );
try
{
metric->Initialize();
}
catch( itk::ExceptionObject & excep )
{
std::cerr << "Exception catched !" << std::endl;
std::cerr << excep << std::endl;
return -1;
}
// Software Guide : BeginLatex
//
// Finally we select a region of the parametric to explore. In this case we are
// using a translation transform in 2D, so we simply select translations from a
// negative position to a positive position, in both $x$ and $y$. For each one
// of those positions we invoke the GetValue() method of the Metric.
//
// Software Guide : EndLatex
// Software Guide : BeginCodeSnippet
MetricType::TransformParametersType displacement( Dimension );
const int rangex = 50;
const int rangey = 50;
for( int dx = -rangex; dx <= rangex; dx++ )
{
for( int dy = -rangey; dy <= rangey; dy++ )
{
displacement[0] = dx;
displacement[1] = dy;
const double value = metric->GetValue( displacement );
std::cout << dx << " " << dy << " " << value << std::endl;
}
}
// Software Guide : EndCodeSnippet
// Software Guide : BeginLatex
//
// \begin{figure}
// \center
// \includegraphics[width=0.44\textwidth]{MeanSquaresMetricPlot1.eps}
// \includegraphics[width=0.44\textwidth]{MeanSquaresMetricPlot2.eps}
// \itkcaption[Mean Squares Metric Plots]{Plots of the Mean Squares Metric for
// an image compared to itself under multiple translations.}
// \label{fig:MeanSquaresMetricPlot}
// \end{figure}
//
// Running this code using the image BrainProtonDensitySlice.png as both the
// fixed and the moving images results in the plot shown in
// Figure~\ref{fig:MeanSquaresMetricPlot}. From this Figure, it can be seen
// that a gradient based optimizer will be appropriate for finding the extrema
// of the Metric. It is also possible to estimate a good value for the step
// length of a gradient-descent optimizer.
//
// This exercise of plotting the Metric is probably the best thing to do when a
// registration process is not converging and when it is unclear how to fine
// tune the different parameters involved in the registration. This includes
// the optimizer parameters, the metric parameters and even options such as
// preprocessing the image data with smoothing filters.
//
// The shell and Gnuplot\footnote{http://www.gnuplot.info} scripts used for
// generating the graphics in Figure~\ref{fig:MeanSquaresMetricPlot} are
// available in the directory
//
// \code{InsightDocuments/SoftwareGuide/Art}
//
// Of course, this plotting exercise becomes more challenging when the
// transform has more than three parameters, and when those parameters have
// very different range of values. In those cases is necessary to select only a
// key subset of parameters from the transform and to study the behavior of the
// metric when those parameters are varied.
//
//
// Software Guide : EndLatex
return 0;
}
<|endoftext|> |
<commit_before>//
// Copyright (c) 2008-2014 the Urho3D project.
//
// 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 "Camera.h"
#include "CoreEvents.h"
#include "Engine.h"
#include "Font.h"
#include "Graphics.h"
#include "Input.h"
#include "LightAnimation.h"
#include "Material.h"
#include "Model.h"
#include "Octree.h"
#include "Renderer.h"
#include "ResourceCache.h"
#include "Scene.h"
#include "StaticModel.h"
#include "Text.h"
#include "UI.h"
#include "ValueAnimation.h"
#include "DebugNew.h"
#include "Animatable.h"
DEFINE_APPLICATION_MAIN(LightAnimation)
LightAnimation::LightAnimation(Context* context) :
Sample(context)
{
}
void LightAnimation::Start()
{
// Execute base class startup
Sample::Start();
// Create the scene content
CreateScene();
// Create the UI content
CreateInstructions();
// Setup the viewport for displaying the scene
SetupViewport();
// Hook up to the frame update events
SubscribeToEvents();
}
void LightAnimation::CreateScene()
{
ResourceCache* cache = GetSubsystem<ResourceCache>();
scene_ = new Scene(context_);
// Create the Octree component to the scene. This is required before adding any drawable components, or else nothing will
// show up. The default octree volume will be from (-1000, -1000, -1000) to (1000, 1000, 1000) in world coordinates; it
// is also legal to place objects outside the volume but their visibility can then not be checked in a hierarchically
// optimizing manner
scene_->CreateComponent<Octree>();
// Create a child scene node (at world origin) and a StaticModel component into it. Set the StaticModel to show a simple
// plane mesh with a "stone" material. Note that naming the scene nodes is optional. Scale the scene node larger
// (100 x 100 world units)
Node* planeNode = scene_->CreateChild("Plane");
planeNode->SetScale(Vector3(100.0f, 1.0f, 100.0f));
StaticModel* planeObject = planeNode->CreateComponent<StaticModel>();
planeObject->SetModel(cache->GetResource<Model>("Models/Plane.mdl"));
planeObject->SetMaterial(cache->GetResource<Material>("Materials/StoneTiled.xml"));
// Create a point light to the world so that we can see something.
Node* lightNode = scene_->CreateChild("PointLight");
Light* light = lightNode->CreateComponent<Light>();
light->SetLightType(LIGHT_POINT);
light->SetRange(10.0f);
// Create light color animation
SharedPtr<ValueAnimation> colorAnimation(new ValueAnimation(context_));
colorAnimation->SetKeyFrame(0.0f, Color::WHITE);
colorAnimation->SetKeyFrame(1.0f, Color::RED);
colorAnimation->SetKeyFrame(2.0f, Color::YELLOW);
colorAnimation->SetKeyFrame(3.0f, Color::GREEN);
colorAnimation->SetKeyFrame(4.0f, Color::WHITE);
light->SetAttributeAnimation("Color", colorAnimation);
// Create light position animation
SharedPtr<ValueAnimation> positionAnimation(new ValueAnimation(context_));
// Use spline interpolation method
positionAnimation->SetInterpolationMethod(IM_SPLINE);
// Set spline tension
positionAnimation->SetSplineTension(0.7f);
positionAnimation->SetKeyFrame(0.0f, Vector3(-30.0f, 5.0f, -30.0f));
positionAnimation->SetKeyFrame(1.0f, Vector3( 30.0f, 5.0f, -30.0f));
positionAnimation->SetKeyFrame(2.0f, Vector3( 30.0f, 5.0f, 30.0f));
positionAnimation->SetKeyFrame(3.0f, Vector3(-30.0f, 5.0f, 30.0f));
positionAnimation->SetKeyFrame(4.0f, Vector3(-30.0f, 5.0f, -30.0f));
lightNode->SetAttributeAnimation("Position", positionAnimation);
// Create more StaticModel objects to the scene, randomly positioned, rotated and scaled. For rotation, we construct a
// quaternion from Euler angles where the Y angle (rotation about the Y axis) is randomized. The mushroom model contains
// LOD levels, so the StaticModel component will automatically select the LOD level according to the view distance (you'll
// see the model get simpler as it moves further away). Finally, rendering a large number of the same object with the
// same material allows instancing to be used, if the GPU supports it. This reduces the amount of CPU work in rendering the
// scene.
const unsigned NUM_OBJECTS = 200;
for (unsigned i = 0; i < NUM_OBJECTS; ++i)
{
Node* mushroomNode = scene_->CreateChild("Mushroom");
mushroomNode->SetPosition(Vector3(Random(90.0f) - 45.0f, 0.0f, Random(90.0f) - 45.0f));
mushroomNode->SetRotation(Quaternion(0.0f, Random(360.0f), 0.0f));
mushroomNode->SetScale(0.5f + Random(2.0f));
StaticModel* mushroomObject = mushroomNode->CreateComponent<StaticModel>();
mushroomObject->SetModel(cache->GetResource<Model>("Models/Mushroom.mdl"));
mushroomObject->SetMaterial(cache->GetResource<Material>("Materials/Mushroom.xml"));
}
// Create a scene node for the camera, which we will move around
// The camera will use default settings (1000 far clip distance, 45 degrees FOV, set aspect ratio automatically)
cameraNode_ = scene_->CreateChild("Camera");
cameraNode_->CreateComponent<Camera>();
// Set an initial position for the camera scene node above the plane
cameraNode_->SetPosition(Vector3(0.0f, 5.0f, 0.0f));
}
void LightAnimation::CreateInstructions()
{
ResourceCache* cache = GetSubsystem<ResourceCache>();
UI* ui = GetSubsystem<UI>();
// Construct new Text object, set string to display and font to use
Text* instructionText = ui->GetRoot()->CreateChild<Text>();
instructionText->SetText("Use WASD keys and mouse/touch to move");
instructionText->SetFont(cache->GetResource<Font>("Fonts/Anonymous Pro.ttf"), 15);
// Position the text relative to the screen center
instructionText->SetHorizontalAlignment(HA_CENTER);
instructionText->SetVerticalAlignment(VA_CENTER);
instructionText->SetPosition(0, ui->GetRoot()->GetHeight() / 4);
}
void LightAnimation::SetupViewport()
{
Renderer* renderer = GetSubsystem<Renderer>();
// Set up a viewport to the Renderer subsystem so that the 3D scene can be seen. We need to define the scene and the camera
// at minimum. Additionally we could configure the viewport screen size and the rendering path (eg. forward / deferred) to
// use, but now we just use full screen and default render path configured in the engine command line options
SharedPtr<Viewport> viewport(new Viewport(context_, scene_, cameraNode_->GetComponent<Camera>()));
renderer->SetViewport(0, viewport);
}
void LightAnimation::MoveCamera(float timeStep)
{
// Do not move if the UI has a focused element (the console)
if (GetSubsystem<UI>()->GetFocusElement())
return;
Input* input = GetSubsystem<Input>();
// Movement speed as world units per second
const float MOVE_SPEED = 20.0f;
// Mouse sensitivity as degrees per pixel
const float MOUSE_SENSITIVITY = 0.1f;
// Use this frame's mouse motion to adjust camera node yaw and pitch. Clamp the pitch between -90 and 90 degrees
IntVector2 mouseMove = input->GetMouseMove();
yaw_ += MOUSE_SENSITIVITY * mouseMove.x_;
pitch_ += MOUSE_SENSITIVITY * mouseMove.y_;
pitch_ = Clamp(pitch_, -90.0f, 90.0f);
// Construct new orientation for the camera scene node from yaw and pitch. Roll is fixed to zero
cameraNode_->SetRotation(Quaternion(pitch_, yaw_, 0.0f));
// Read WASD keys and move the camera scene node to the corresponding direction if they are pressed
// Use the Translate() function (default local space) to move relative to the node's orientation.
if (input->GetKeyDown('W'))
cameraNode_->Translate(Vector3::FORWARD * MOVE_SPEED * timeStep);
if (input->GetKeyDown('S'))
cameraNode_->Translate(Vector3::BACK * MOVE_SPEED * timeStep);
if (input->GetKeyDown('A'))
cameraNode_->Translate(Vector3::LEFT * MOVE_SPEED * timeStep);
if (input->GetKeyDown('D'))
cameraNode_->Translate(Vector3::RIGHT * MOVE_SPEED * timeStep);
}
void LightAnimation::SubscribeToEvents()
{
// Subscribe HandleUpdate() function for processing update events
SubscribeToEvent(E_UPDATE, HANDLER(LightAnimation, HandleUpdate));
}
void LightAnimation::HandleUpdate(StringHash eventType, VariantMap& eventData)
{
using namespace Update;
// Take the frame time step, which is stored as a float
float timeStep = eventData[P_TIMESTEP].GetFloat();
// Move the camera, scale movement with time step
MoveCamera(timeStep);
}
<commit_msg>LightAnimation sample now use ObjectAnimation in C++.<commit_after>//
// Copyright (c) 2008-2014 the Urho3D project.
//
// 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 "Camera.h"
#include "CoreEvents.h"
#include "Engine.h"
#include "Font.h"
#include "Graphics.h"
#include "Input.h"
#include "LightAnimation.h"
#include "Material.h"
#include "Model.h"
#include "Octree.h"
#include "ObjectAnimation.h"
#include "Renderer.h"
#include "ResourceCache.h"
#include "Scene.h"
#include "StaticModel.h"
#include "Text.h"
#include "UI.h"
#include "ValueAnimation.h"
#include "DebugNew.h"
#include "Animatable.h"
DEFINE_APPLICATION_MAIN(LightAnimation)
LightAnimation::LightAnimation(Context* context) :
Sample(context)
{
}
void LightAnimation::Start()
{
// Execute base class startup
Sample::Start();
// Create the scene content
CreateScene();
// Create the UI content
CreateInstructions();
// Setup the viewport for displaying the scene
SetupViewport();
// Hook up to the frame update events
SubscribeToEvents();
}
void LightAnimation::CreateScene()
{
ResourceCache* cache = GetSubsystem<ResourceCache>();
scene_ = new Scene(context_);
// Create the Octree component to the scene. This is required before adding any drawable components, or else nothing will
// show up. The default octree volume will be from (-1000, -1000, -1000) to (1000, 1000, 1000) in world coordinates; it
// is also legal to place objects outside the volume but their visibility can then not be checked in a hierarchically
// optimizing manner
scene_->CreateComponent<Octree>();
// Create a child scene node (at world origin) and a StaticModel component into it. Set the StaticModel to show a simple
// plane mesh with a "stone" material. Note that naming the scene nodes is optional. Scale the scene node larger
// (100 x 100 world units)
Node* planeNode = scene_->CreateChild("Plane");
planeNode->SetScale(Vector3(100.0f, 1.0f, 100.0f));
StaticModel* planeObject = planeNode->CreateComponent<StaticModel>();
planeObject->SetModel(cache->GetResource<Model>("Models/Plane.mdl"));
planeObject->SetMaterial(cache->GetResource<Material>("Materials/StoneTiled.xml"));
// Create a point light to the world so that we can see something.
Node* lightNode = scene_->CreateChild("PointLight");
Light* light = lightNode->CreateComponent<Light>();
light->SetLightType(LIGHT_POINT);
light->SetRange(10.0f);
// Create light animation
SharedPtr<ObjectAnimation> lightAnimation(new ObjectAnimation(context_));
// Create light position animation
SharedPtr<ValueAnimation> positionAnimation(new ValueAnimation(context_));
// Use spline interpolation method
positionAnimation->SetInterpolationMethod(IM_SPLINE);
// Set spline tension
positionAnimation->SetSplineTension(0.7f);
positionAnimation->SetKeyFrame(0.0f, Vector3(-30.0f, 5.0f, -30.0f));
positionAnimation->SetKeyFrame(1.0f, Vector3( 30.0f, 5.0f, -30.0f));
positionAnimation->SetKeyFrame(2.0f, Vector3( 30.0f, 5.0f, 30.0f));
positionAnimation->SetKeyFrame(3.0f, Vector3(-30.0f, 5.0f, 30.0f));
positionAnimation->SetKeyFrame(4.0f, Vector3(-30.0f, 5.0f, -30.0f));
// Set position animation
lightAnimation->AddAttributeAnimation("Position", positionAnimation);
// Create light color animation
SharedPtr<ValueAnimation> colorAnimation(new ValueAnimation(context_));
colorAnimation->SetKeyFrame(0.0f, Color::WHITE);
colorAnimation->SetKeyFrame(1.0f, Color::RED);
colorAnimation->SetKeyFrame(2.0f, Color::YELLOW);
colorAnimation->SetKeyFrame(3.0f, Color::GREEN);
colorAnimation->SetKeyFrame(4.0f, Color::WHITE);
// Set Light component's color animation
lightAnimation->AddAttributeAnimation("@Light/Color", colorAnimation);
// Apply light animation to light node
lightNode->SetObjectAnimation(lightAnimation);
// Create more StaticModel objects to the scene, randomly positioned, rotated and scaled. For rotation, we construct a
// quaternion from Euler angles where the Y angle (rotation about the Y axis) is randomized. The mushroom model contains
// LOD levels, so the StaticModel component will automatically select the LOD level according to the view distance (you'll
// see the model get simpler as it moves further away). Finally, rendering a large number of the same object with the
// same material allows instancing to be used, if the GPU supports it. This reduces the amount of CPU work in rendering the
// scene.
const unsigned NUM_OBJECTS = 200;
for (unsigned i = 0; i < NUM_OBJECTS; ++i)
{
Node* mushroomNode = scene_->CreateChild("Mushroom");
mushroomNode->SetPosition(Vector3(Random(90.0f) - 45.0f, 0.0f, Random(90.0f) - 45.0f));
mushroomNode->SetRotation(Quaternion(0.0f, Random(360.0f), 0.0f));
mushroomNode->SetScale(0.5f + Random(2.0f));
StaticModel* mushroomObject = mushroomNode->CreateComponent<StaticModel>();
mushroomObject->SetModel(cache->GetResource<Model>("Models/Mushroom.mdl"));
mushroomObject->SetMaterial(cache->GetResource<Material>("Materials/Mushroom.xml"));
}
// Create a scene node for the camera, which we will move around
// The camera will use default settings (1000 far clip distance, 45 degrees FOV, set aspect ratio automatically)
cameraNode_ = scene_->CreateChild("Camera");
cameraNode_->CreateComponent<Camera>();
// Set an initial position for the camera scene node above the plane
cameraNode_->SetPosition(Vector3(0.0f, 5.0f, 0.0f));
}
void LightAnimation::CreateInstructions()
{
ResourceCache* cache = GetSubsystem<ResourceCache>();
UI* ui = GetSubsystem<UI>();
// Construct new Text object, set string to display and font to use
Text* instructionText = ui->GetRoot()->CreateChild<Text>();
instructionText->SetText("Use WASD keys and mouse/touch to move");
instructionText->SetFont(cache->GetResource<Font>("Fonts/Anonymous Pro.ttf"), 15);
// Position the text relative to the screen center
instructionText->SetHorizontalAlignment(HA_CENTER);
instructionText->SetVerticalAlignment(VA_CENTER);
instructionText->SetPosition(0, ui->GetRoot()->GetHeight() / 4);
}
void LightAnimation::SetupViewport()
{
Renderer* renderer = GetSubsystem<Renderer>();
// Set up a viewport to the Renderer subsystem so that the 3D scene can be seen. We need to define the scene and the camera
// at minimum. Additionally we could configure the viewport screen size and the rendering path (eg. forward / deferred) to
// use, but now we just use full screen and default render path configured in the engine command line options
SharedPtr<Viewport> viewport(new Viewport(context_, scene_, cameraNode_->GetComponent<Camera>()));
renderer->SetViewport(0, viewport);
}
void LightAnimation::MoveCamera(float timeStep)
{
// Do not move if the UI has a focused element (the console)
if (GetSubsystem<UI>()->GetFocusElement())
return;
Input* input = GetSubsystem<Input>();
// Movement speed as world units per second
const float MOVE_SPEED = 20.0f;
// Mouse sensitivity as degrees per pixel
const float MOUSE_SENSITIVITY = 0.1f;
// Use this frame's mouse motion to adjust camera node yaw and pitch. Clamp the pitch between -90 and 90 degrees
IntVector2 mouseMove = input->GetMouseMove();
yaw_ += MOUSE_SENSITIVITY * mouseMove.x_;
pitch_ += MOUSE_SENSITIVITY * mouseMove.y_;
pitch_ = Clamp(pitch_, -90.0f, 90.0f);
// Construct new orientation for the camera scene node from yaw and pitch. Roll is fixed to zero
cameraNode_->SetRotation(Quaternion(pitch_, yaw_, 0.0f));
// Read WASD keys and move the camera scene node to the corresponding direction if they are pressed
// Use the Translate() function (default local space) to move relative to the node's orientation.
if (input->GetKeyDown('W'))
cameraNode_->Translate(Vector3::FORWARD * MOVE_SPEED * timeStep);
if (input->GetKeyDown('S'))
cameraNode_->Translate(Vector3::BACK * MOVE_SPEED * timeStep);
if (input->GetKeyDown('A'))
cameraNode_->Translate(Vector3::LEFT * MOVE_SPEED * timeStep);
if (input->GetKeyDown('D'))
cameraNode_->Translate(Vector3::RIGHT * MOVE_SPEED * timeStep);
}
void LightAnimation::SubscribeToEvents()
{
// Subscribe HandleUpdate() function for processing update events
SubscribeToEvent(E_UPDATE, HANDLER(LightAnimation, HandleUpdate));
}
void LightAnimation::HandleUpdate(StringHash eventType, VariantMap& eventData)
{
using namespace Update;
// Take the frame time step, which is stored as a float
float timeStep = eventData[P_TIMESTEP].GetFloat();
// Move the camera, scale movement with time step
MoveCamera(timeStep);
}
<|endoftext|> |
<commit_before>/*=============================================================================
NiftyLink: A software library to facilitate communication over OpenIGTLink.
Copyright (c) University College London (UCL). All rights reserved.
This software is distributed WITHOUT ANY WARRANTY; without even
the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR
PURPOSE.
See LICENSE.txt in the top level directory for details.
=============================================================================*/
#include "NiftyLinkDescriptorTests.h"
#include <NiftyLinkUtils.h>
#include <NiftyLinkXMLBuilder.h>
namespace niftk
{
//-----------------------------------------------------------------------------
void NiftyLinkDescriptorTests::ClientDescriptorTest()
{
NiftyLinkClientDescriptor clientDescriptor;
QVERIFY(clientDescriptor.GetClientIP().size() == 0);
QVERIFY(clientDescriptor.GetClientPort().size() == 0);
QVERIFY(clientDescriptor.GetCommunicationType().size() == 0);
QVERIFY(clientDescriptor.GetDeviceName().size() == 0);
QVERIFY(clientDescriptor.GetDeviceType().size() == 0);
QVERIFY(clientDescriptor.GetPortName().size() == 0);
clientDescriptor.SetClientIP("123.456.789.012");
clientDescriptor.SetClientPort("1234");
clientDescriptor.SetCommunicationType("TCP");
clientDescriptor.SetDeviceName("TestImager");
clientDescriptor.SetDeviceType("Imager");
clientDescriptor.SetPortName("TestPort");
QString xml = clientDescriptor.GetXMLAsString();
QVERIFY(xml.size() > 0);
std::cerr << "xml=\n" << xml.toStdString() << std::endl;
QVERIFY(clientDescriptor.SetXMLString(xml));
QVERIFY(clientDescriptor.GetClientIP() == "123.456.789.012");
QVERIFY(clientDescriptor.GetClientPort() == "1234");
QVERIFY(clientDescriptor.GetCommunicationType() == "TCP");
QVERIFY(clientDescriptor.GetDeviceName() == "TestImager");
QVERIFY(clientDescriptor.GetDeviceType() == "Imager");
QVERIFY(clientDescriptor.GetPortName() == "TestPort");
}
//-----------------------------------------------------------------------------
void NiftyLinkDescriptorTests::TrackerClientDescriptorTest()
{
NiftyLinkTrackerClientDescriptor clientDescriptor;
QVERIFY(clientDescriptor.GetClientIP().size() == 0);
QVERIFY(clientDescriptor.GetClientPort().size() == 0);
QVERIFY(clientDescriptor.GetCommunicationType().size() == 0);
QVERIFY(clientDescriptor.GetDeviceName().size() == 0);
QVERIFY(clientDescriptor.GetDeviceType().size() == 0);
QVERIFY(clientDescriptor.GetPortName().size() == 0);
clientDescriptor.SetClientIP("123.456.789.012");
clientDescriptor.SetClientPort("1234");
clientDescriptor.SetCommunicationType("TCP");
clientDescriptor.SetDeviceName("TestImager");
clientDescriptor.SetDeviceType("Imager");
clientDescriptor.SetPortName("TestPort");
QString xml = clientDescriptor.GetXMLAsString();
QVERIFY(xml.size() > 0);
std::cerr << "xml=\n" << xml.toStdString() << std::endl;
QVERIFY(clientDescriptor.SetXMLString(xml));
QVERIFY(clientDescriptor.GetClientIP() == "123.456.789.012");
QVERIFY(clientDescriptor.GetClientPort() == "1234");
QVERIFY(clientDescriptor.GetCommunicationType() == "TCP");
QVERIFY(clientDescriptor.GetDeviceName() == "TestImager");
QVERIFY(clientDescriptor.GetDeviceType() == "Imager");
QVERIFY(clientDescriptor.GetPortName() == "TestPort");
QVERIFY(clientDescriptor.GetTrackerTools().size() == 0);
clientDescriptor.AddTrackerTool("PointerTool");
QString xml2 = clientDescriptor.GetXMLAsString();
std::cerr << "xml2=\n" << xml2.toStdString() << std::endl;
QVERIFY(xml != xml2);
QVERIFY(clientDescriptor.GetTrackerTools().size() == 1);
QStringList tools;
tools << "PointerTool";
QVERIFY(clientDescriptor.GetTrackerTools() == tools);
}
//-----------------------------------------------------------------------------
void NiftyLinkDescriptorTests::CommandDescriptorTest()
{
NiftyLinkCommandDescriptor descriptor;
QVERIFY(descriptor.GetCommandName().size() == 0);
QVERIFY(descriptor.GetNumOfParameters() == 0);
descriptor.SetCommandName("JustDoIt");
descriptor.AddParameter("P1", "String", "Nike");
descriptor.AddParameter("P2", "int", "10");
QString xml = descriptor.GetXMLAsString();
QVERIFY(xml.size() > 0);
std::cerr << "xml=\n" << xml.toStdString() << std::endl;
descriptor.SetXMLString(xml);
QVERIFY(descriptor.GetCommandName() == "JustDoIt");
QVERIFY(descriptor.GetNumOfParameters() == 2);
QVERIFY(descriptor.GetParameterName(0) == "P1");
QVERIFY(descriptor.GetParameterName(1) == "P2");
QVERIFY(descriptor.GetParameterType(0) == "String");
QVERIFY(descriptor.GetParameterType(1) == "int");
QVERIFY(descriptor.GetParameterValue(0) == "Nike");
QVERIFY(descriptor.GetParameterValue(1) == "10");
}
} // end namespace niftk
NIFTYLINK_QTEST_MAIN( niftk::NiftyLinkDescriptorTests )
<commit_msg>Bug #3609: Update XML builder tests, more coverage<commit_after>/*=============================================================================
NiftyLink: A software library to facilitate communication over OpenIGTLink.
Copyright (c) University College London (UCL). All rights reserved.
This software is distributed WITHOUT ANY WARRANTY; without even
the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR
PURPOSE.
See LICENSE.txt in the top level directory for details.
=============================================================================*/
#include "NiftyLinkDescriptorTests.h"
#include <NiftyLinkUtils.h>
#include <NiftyLinkXMLBuilder.h>
namespace niftk
{
//-----------------------------------------------------------------------------
void NiftyLinkDescriptorTests::ClientDescriptorTest()
{
NiftyLinkClientDescriptor clientDescriptor;
QVERIFY(clientDescriptor.GetClientIP().size() == 0);
QVERIFY(clientDescriptor.GetClientPort().size() == 0);
QVERIFY(clientDescriptor.GetCommunicationType().size() == 0);
QVERIFY(clientDescriptor.GetDeviceName().size() == 0);
QVERIFY(clientDescriptor.GetDeviceType().size() == 0);
QVERIFY(clientDescriptor.GetPortName().size() == 0);
clientDescriptor.SetClientIP("123.456.789.012");
clientDescriptor.SetClientPort("1234");
clientDescriptor.SetCommunicationType("TCP");
clientDescriptor.SetDeviceName("TestImager");
clientDescriptor.SetDeviceType("Imager");
clientDescriptor.SetPortName("TestPort");
QString xml = clientDescriptor.GetXMLAsString();
QVERIFY(xml.size() > 0);
std::cerr << "xml=\n" << xml.toStdString() << std::endl;
QVERIFY(clientDescriptor.SetXMLString(xml));
QVERIFY(clientDescriptor.GetClientIP() == "123.456.789.012");
QVERIFY(clientDescriptor.GetClientPort() == "1234");
QVERIFY(clientDescriptor.GetCommunicationType() == "TCP");
QVERIFY(clientDescriptor.GetDeviceName() == "TestImager");
QVERIFY(clientDescriptor.GetDeviceType() == "Imager");
QVERIFY(clientDescriptor.GetPortName() == "TestPort");
NiftyLinkClientDescriptor c2(clientDescriptor);
QVERIFY(c2.GetClientIP() == "123.456.789.012");
QVERIFY(c2.GetClientPort() == "1234");
QVERIFY(c2.GetCommunicationType() == "TCP");
QVERIFY(c2.GetDeviceName() == "TestImager");
QVERIFY(c2.GetDeviceType() == "Imager");
QVERIFY(c2.GetPortName() == "TestPort");
}
//-----------------------------------------------------------------------------
void NiftyLinkDescriptorTests::TrackerClientDescriptorTest()
{
NiftyLinkTrackerClientDescriptor clientDescriptor;
QVERIFY(clientDescriptor.GetClientIP().size() == 0);
QVERIFY(clientDescriptor.GetClientPort().size() == 0);
QVERIFY(clientDescriptor.GetCommunicationType().size() == 0);
QVERIFY(clientDescriptor.GetDeviceName().size() == 0);
QVERIFY(clientDescriptor.GetDeviceType().size() == 0);
QVERIFY(clientDescriptor.GetPortName().size() == 0);
clientDescriptor.SetClientIP("123.456.789.012");
clientDescriptor.SetClientPort("1234");
clientDescriptor.SetCommunicationType("TCP");
clientDescriptor.SetDeviceName("TestImager");
clientDescriptor.SetDeviceType("Imager");
clientDescriptor.SetPortName("TestPort");
QString xml = clientDescriptor.GetXMLAsString();
QVERIFY(xml.size() > 0);
std::cerr << "xml=\n" << xml.toStdString() << std::endl;
QVERIFY(clientDescriptor.SetXMLString(xml));
QVERIFY(clientDescriptor.GetClientIP() == "123.456.789.012");
QVERIFY(clientDescriptor.GetClientPort() == "1234");
QVERIFY(clientDescriptor.GetCommunicationType() == "TCP");
QVERIFY(clientDescriptor.GetDeviceName() == "TestImager");
QVERIFY(clientDescriptor.GetDeviceType() == "Imager");
QVERIFY(clientDescriptor.GetPortName() == "TestPort");
QVERIFY(clientDescriptor.GetTrackerTools().size() == 0);
clientDescriptor.AddTrackerTool("PointerTool");
QString xml2 = clientDescriptor.GetXMLAsString();
std::cerr << "xml2=\n" << xml2.toStdString() << std::endl;
QVERIFY(xml != xml2);
QVERIFY(clientDescriptor.GetTrackerTools().size() == 1);
QStringList tools;
tools << "PointerTool";
QVERIFY(clientDescriptor.GetTrackerTools() == tools);
NiftyLinkTrackerClientDescriptor c2(clientDescriptor);
QVERIFY(c2.GetClientIP() == "123.456.789.012");
QVERIFY(c2.GetClientPort() == "1234");
QVERIFY(c2.GetCommunicationType() == "TCP");
QVERIFY(c2.GetDeviceName() == "TestImager");
QVERIFY(c2.GetDeviceType() == "Imager");
QVERIFY(c2.GetPortName() == "TestPort");
QVERIFY(c2.GetTrackerTools() == tools);
}
//-----------------------------------------------------------------------------
void NiftyLinkDescriptorTests::CommandDescriptorTest()
{
NiftyLinkCommandDescriptor descriptor;
QVERIFY(descriptor.GetCommandName().size() == 0);
QVERIFY(descriptor.GetNumOfParameters() == 0);
descriptor.SetCommandName("JustDoIt");
descriptor.AddParameter("P1", "String", "Nike");
descriptor.AddParameter("P2", "int", "10");
QString xml = descriptor.GetXMLAsString();
QVERIFY(xml.size() > 0);
std::cerr << "xml=\n" << xml.toStdString() << std::endl;
descriptor.SetXMLString(xml);
QVERIFY(descriptor.GetCommandName() == "JustDoIt");
QVERIFY(descriptor.GetNumOfParameters() == 2);
QVERIFY(descriptor.GetParameterName(0) == "P1");
QVERIFY(descriptor.GetParameterName(1) == "P2");
QVERIFY(descriptor.GetParameterType(0) == "String");
QVERIFY(descriptor.GetParameterType(1) == "int");
QVERIFY(descriptor.GetParameterValue(0) == "Nike");
QVERIFY(descriptor.GetParameterValue(1) == "10");
NiftyLinkCommandDescriptor c2(descriptor);
QVERIFY(c2.GetCommandName() == "JustDoIt");
QVERIFY(c2.GetNumOfParameters() == 2);
QVERIFY(c2.GetParameterName(0) == "P1");
QVERIFY(c2.GetParameterName(1) == "P2");
QVERIFY(c2.GetParameterType(0) == "String");
QVERIFY(c2.GetParameterType(1) == "int");
QVERIFY(c2.GetParameterValue(0) == "Nike");
QVERIFY(c2.GetParameterValue(1) == "10");
}
} // end namespace niftk
NIFTYLINK_QTEST_MAIN( niftk::NiftyLinkDescriptorTests )
<|endoftext|> |
<commit_before>#ifndef RECOMBINATION_DEF_HPP_
#define RECOMBINATION_DEF_HPP_
#include <cassert>
#include "clotho/powerset/variable_subset.hpp"
namespace clotho {
namespace recombine {
template < class Sequence >
class recombination {
public:
typedef Sequence sequence_type;
typedef Method method_type;
void operator()( sequence_type base, sequence_type alt );
};
template < class Element, class Block, class BlockMap, class ElementKeyer >
class recombination< variable_subset< Element, Block, BlockMap, ElementKeyer > > {
public:
typedef variable_subset< Element, Block, BlockMap, ElementKeyer > subset_type;
typedef typename subset_type::pointer sequence_type;
typedef typename subset_type::bitset_type bit_sequence_type;
typedef Block block_type;
void operator()( sequence_type base, sequence_type alt ) {
assert( base->isSameFamily( alt ) );
m_match_base = m_match_alt = m_empty = true;
if( base == alt ) {
return;
}
m_res_seq.reset();
m_res_seq.resize( base->max_size(), false );
subset_type::cblock_iterator base_it = base->begin(), base_end = base->end();
subset_type::cblock_iterator alt_it = base->begin(), alt_end = base->end();
subset_type::block_iterator res_it = m_res_seq.m_bits.begin();
while( true ) {
if( alt_it == alt_end ) {
while( base_it != base_end ) {
block_type _base = (*base_it++);
recombine( (*res_it), _base, 0 );
++res_it;
}
break;
}
if( base_it == base_end ) {
while( alt_it != alt_end ) {
block_type _alt = (*alt_it++);
recombine( (*res_it), 0, _alt );
++res_it;
}
break;
}
block_type _base = (*base_it++), _alt = (*alt_it++);
recombine( (*res_it), _base, _alt );
++res_it;
}
}
bit_sequence_type * getResultSequence() { return &m_res_seq; }
bool isMatchBase() const { return m_match_base; }
bool isMatchAlt() const { return m_match_alt; }
bool isEmpty() const { return m_empty; }
void recombine( block_type & res, const block_type base, const block_type alt ) {
block_type hom = base & alt;
block_type hets = base ^ alt;
block_type bmask = base_mask_from_hets( hets );
block_type amask = ((~bmask & hets) & alt);
res =(hom | (amask | (bmask & base)));
m_match_base = (m_match_base && (base == res) );
m_match_alt = (m_match_alt && (alt == res) );
m_empty = (m_empty && (res == 0) );
}
block_type base_mask_from_hets( block_type _bits ) {
if( !_bits ) return (block_type)0;
typename lowest_bit_map::block_type sub_block = (typename lowest_bit_map::block_type)(_bits);
block_type res = 0;
if( sub_block ) { // block 0
bit_walk( res, sub_block, 0 );
}
_bits /= lowest_bit_map::max_values;
if( !_bits ) return res;
sub_block = (typename lowest_bit_map::block_type)(_bits);
if( sub_block ) { // block 1
bit_walk( res, sub_block, lowest_bit_map::block_width );
}
_bits /= lowest_bit_map::max_values;
if( !_bits ) return res;
sub_block = (typename lowest_bit_map::block_type)(_bits);
if( sub_block ) { // block 2
bit_walk( res, sub_block, 2 * lowest_bit_map::block_width );
}
_bits /= lowest_bit_map::max_values;
sub_block = (typename lowest_bit_map::block_type)(_bits);
if( sub_block ) { // block 3
bit_walk( res, sub_block, 3 * lowest_bit_map::block_width );
}
return res;
}
inline void bit_walk( Block & res, typename lowest_bit_map::block_type sub_block, const Block & base, const Block & alt, set_iterator alpha_it, unsigned int _offset ) {
const lowest_bit_map::value_type * v = low_bit_map.begin() + sub_block;
do {
unsigned int idx = _offset + v->bit_index;
typename Alphabet::locus_t loc = accessor::get< set_iterator, typename Alphabet::locus_t >(alpha_it + idx);
recombination_iterator rit = std::upper_bound( rec_points->begin(), rec_points->end(), loc);
res |= ((((rit - rec_points->begin()) % 2) ? base : alt) & SortedAlleleAlphabet2::bit_position_masks[idx]);
_offset += v->bit_shift_next;
v = v->next_ptr;
} while( v != NULL );
}
virtual ~recombination() {}
protected:
bit_sequence_type m_res_seq;
bool m_match_base, m_match_alt, m_empty;
};
} // namespace recombine
} // namespace clotho
#endif // RECOMBINATION_DEF_HPP_
<commit_msg>Working partial specialization of recombination definition for variable_subsets<commit_after>#ifndef RECOMBINATION_DEF_HPP_
#define RECOMBINATION_DEF_HPP_
#include <cassert>
#include "clotho/powerset/variable_subset.hpp"
#include "clotho/utility/bit_walker.hpp"
namespace clotho {
namespace recombine {
template < class Sequence, class Classifier >
class recombination;
template < class Element, class Block, class BlockMap, class ElementKeyer, class Classifier >
class recombination< clotho::powersets::variable_subset< Element, Block, BlockMap, ElementKeyer >, Classifier > {
public:
typedef clotho::powersets::variable_subset< Element, Block, BlockMap, ElementKeyer > subset_type;
typedef typename subset_type::pointer sequence_type;
typedef Classifier classifier_type;
typedef typename subset_type::bitset_type bit_sequence_type;
typedef Block block_type;
typedef clotho::utility::block_walker< block_type, unsigned short > block_walker_type;
void operator()( sequence_type base, sequence_type alt, classifier_type & elem_classifier) {
assert( base->isSameFamily( alt ) );
m_match_base = m_match_alt = m_empty = true;
if( base == alt ) {
return;
}
m_res_seq.reset();
m_res_seq.resize( base->max_size(), false );
typename subset_type::cblock_iterator base_it = base->begin(), base_end = base->end();
typename subset_type::cblock_iterator alt_it = base->begin(), alt_end = base->end();
typename subset_type::block_iterator res_it = m_res_seq.m_bits.begin();
while( true ) {
if( alt_it == alt_end ) {
while( base_it != base_end ) {
block_type _base = (*base_it++);
recombine( (*res_it), _base, 0, elem_classifier );
++res_it;
}
break;
}
if( base_it == base_end ) {
while( alt_it != alt_end ) {
block_type _alt = (*alt_it++);
recombine( (*res_it), 0, _alt, elem_classifier );
++res_it;
}
break;
}
block_type _base = (*base_it++), _alt = (*alt_it++);
recombine( (*res_it), _base, _alt, elem_classifier );
++res_it;
}
}
bit_sequence_type * getResultSequence() { return &m_res_seq; }
bool isMatchBase() const { return m_match_base; }
bool isMatchAlt() const { return m_match_alt; }
bool isEmpty() const { return m_empty; }
void recombine( block_type & res, const block_type base, const block_type alt, classifier_type & elem_classifier ) {
block_type hom = base & alt;
block_type hets = base ^ alt;
elem_classifier.resetResult();
block_walker_type::apply( hets, elem_classifier );
block_type base_mask = elem_classifier.getResult();
block_type alt_mask = ((~base_mask & hets) & alt);
res =(hom | (alt_mask | (base_mask & base)));
m_match_base = (m_match_base && (base == res) );
m_match_alt = (m_match_alt && (alt == res) );
m_empty = (m_empty && (res == 0) );
}
virtual ~recombination() {}
protected:
bit_sequence_type m_res_seq;
bool m_match_base, m_match_alt, m_empty;
};
} // namespace recombine
} // namespace clotho
#endif // RECOMBINATION_DEF_HPP_
<|endoftext|> |
<commit_before>/**
* \file
* \brief ThreadControlBlock class header
*
* \author Copyright (C) 2014-2015 Kamil Szczygiel http://www.distortec.com http://www.freddiechopin.info
*
* \par License
* 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/.
*
* \date 2015-02-12
*/
#ifndef INCLUDE_DISTORTOS_SCHEDULER_THREADCONTROLBLOCK_HPP_
#define INCLUDE_DISTORTOS_SCHEDULER_THREADCONTROLBLOCK_HPP_
#include "distortos/scheduler/RoundRobinQuantum.hpp"
#include "distortos/scheduler/ThreadControlBlockList-types.hpp"
#include "distortos/scheduler/MutexControlBlockList.hpp"
#include "distortos/architecture/Stack.hpp"
#include "distortos/SchedulingPolicy.hpp"
#include "distortos/estd/TypeErasedFunctor.hpp"
namespace distortos
{
namespace scheduler
{
class ThreadControlBlockList;
/// ThreadControlBlock class is a simple description of a Thread
class ThreadControlBlock
{
public:
/// state of the thread
enum class State : uint8_t
{
/// state in which thread is created, before being added to Scheduler
New,
/// thread is runnable
Runnable,
/// thread is sleeping
Sleeping,
/// thread is blocked on Semaphore
BlockedOnSemaphore,
/// thread is suspended
Suspended,
/// thread is terminated
Terminated,
/// thread is blocked on Mutex
BlockedOnMutex,
/// thread is blocked on ConditionVariable
BlockedOnConditionVariable,
};
/// reason of thread unblocking
enum class UnblockReason : uint8_t
{
/// explicit request to unblock the thread - normal unblock
UnblockRequest,
/// timeout - unblock via software timer
Timeout,
};
/// type of object used as storage for ThreadControlBlockList elements - 3 pointers
using Link = std::array<std::aligned_storage<sizeof(void*), alignof(void*)>::type, 3>;
/// UnblockFunctor is a functor executed when unblocking the thread, it receives one parameter - a reference to
/// ThreadControlBlock that is being unblocked
using UnblockFunctor = estd::TypeErasedFunctor<void(ThreadControlBlock&)>;
/**
* \brief ThreadControlBlock constructor.
*
* \param [in] buffer is a pointer to stack's buffer
* \param [in] size is the size of stack's buffer, bytes
* \param [in] priority is the thread's priority, 0 - lowest, UINT8_MAX - highest
* \param [in] schedulingPolicy is the scheduling policy of the thread
*/
ThreadControlBlock(void* buffer, size_t size, uint8_t priority, SchedulingPolicy schedulingPolicy);
/**
* \brief ThreadControlBlock constructor.
*
* \param [in] stack is an rvalue reference to architecture::Stack object which will be adopted for this thread
* \param [in] priority is the thread's priority, 0 - lowest, UINT8_MAX - highest
* \param [in] schedulingPolicy is the scheduling policy of the thread
*/
ThreadControlBlock(architecture::Stack&& stack, uint8_t priority, SchedulingPolicy schedulingPolicy);
/**
* \brief Block hook function of thread
*
* Saves pointer to UnblockFunctor.
*
* \attention This function should be called only by Scheduler::blockInternal().
*
* \param [in] unblockFunctor is a pointer to UnblockFunctor which will be executed in unblockHook()
*/
void blockHook(const UnblockFunctor* const unblockFunctor)
{
unblockFunctor_ = unblockFunctor;
}
/**
* \return effective priority of ThreadControlBlock
*/
uint8_t getEffectivePriority() const
{
return std::max(priority_, boostedPriority_);
}
/**
* \return iterator to the element on the list, valid only when list_ != nullptr
*/
ThreadControlBlockListIterator getIterator() const
{
return iterator_;
}
/**
* \return reference to internal storage for list link
*/
Link& getLink()
{
return link_;
}
/**
* \return pointer to list that has this object
*/
ThreadControlBlockList* getList() const
{
return list_;
}
/**
* \return reference to list of mutex control blocks with enabled priority protocol owned by this thread
*/
MutexControlBlockList& getOwnedProtocolMutexControlBlocksList()
{
return ownedProtocolMutexControlBlocksList_;
}
/**
* \return priority of ThreadControlBlock
*/
uint8_t getPriority() const
{
return priority_;
}
/**
* \return reference to internal RoundRobinQuantum object
*/
RoundRobinQuantum& getRoundRobinQuantum()
{
return roundRobinQuantum_;
}
/**
* \return scheduling policy of the thread
*/
SchedulingPolicy getSchedulingPolicy() const
{
return schedulingPolicy_;
}
/**
* \return reference to internal Stack object
*/
architecture::Stack& getStack()
{
return stack_;
}
/**
* \return current state of object
*/
State getState() const
{
return state_;
}
/**
* \return reason of previous unblocking of the thread
*/
UnblockReason getUnblockReason() const
{
return unblockReason_;
}
/**
* \brief Sets the iterator to the element on the list.
*
* \param [in] iterator is an iterator to the element on the list
*/
void setIterator(const ThreadControlBlockListIterator iterator)
{
iterator_ = iterator;
}
/**
* \brief Sets the list that has this object.
*
* \param [in] list is a pointer to list that has this object
*/
void setList(ThreadControlBlockList* const list)
{
list_ = list;
}
/**
* \brief Changes priority of thread.
*
* If the priority really changes, the position in the thread list is adjusted and context switch may be requested.
*
* \param [in] priority is the new priority of thread
* \param [in] alwaysBehind selects the method of ordering when lowering the priority
* - false - the thread is moved to the head of the group of threads with the new priority (default),
* - true - the thread is moved to the tail of the group of threads with the new priority.
*/
void setPriority(uint8_t priority, bool alwaysBehind = {});
/**
* \param [in] priorityInheritanceMutexControlBlock is a pointer to MutexControlBlock (with PriorityInheritance
* protocol) that blocks this thread
*/
void setPriorityInheritanceMutexControlBlock(const synchronization::MutexControlBlock* const
priorityInheritanceMutexControlBlock)
{
priorityInheritanceMutexControlBlock_ = priorityInheritanceMutexControlBlock;
}
/**
* param [in] schedulingPolicy is the new scheduling policy of the thread
*/
void setSchedulingPolicy(SchedulingPolicy schedulingPolicy);
/**
* \param [in] state is the new state of object
*/
void setState(const State state)
{
state_ = state;
}
/**
* \brief Hook function called when context is switched to this thread.
*
* Sets global _impure_ptr (from newlib) to thread's \a reent_ member variable.
*
* \attention This function should be called only by Scheduler::switchContext().
*/
void switchedToHook()
{
_impure_ptr = &reent_;
}
/**
* \brief Termination hook function of thread
*
* \attention This function should be called only by Scheduler::remove().
*/
void terminationHook()
{
terminationHook_();
}
/**
* \brief Unblock hook function of thread
*
* Resets round-robin's quantum, sets unblock reason and executes unblock functor saved in blockHook().
*
* \attention This function should be called only by Scheduler::unblockInternal().
*
* \param [in] unblockReason is the new reason of unblocking of the thread
*/
void unblockHook(UnblockReason unblockReason);
/**
* \brief Updates boosted priority of the thread.
*
* This function should be called after all operations involving this thread and a mutex with enabled priority
* protocol.
*
* \param [in] boostedPriority is the initial boosted priority, this should be effective priority of the thread that
* is about to be blocked on a mutex owned by this thread, default - 0
*/
void updateBoostedPriority(uint8_t boostedPriority = {});
protected:
/**
* \brief ThreadControlBlock's destructor
*
* \note Polymorphic objects of ThreadControlBlock type must not be deleted via pointer/reference
*/
~ThreadControlBlock();
private:
/**
* \brief Thread runner function - entry point of threads.
*
* After return from actual thread function, thread is terminated, so this function never returns.
*
* \param [in] threadControlBlock is a reference to ThreadControlBlock object that is being run
*/
static void threadRunner(ThreadControlBlock& threadControlBlock) __attribute__ ((noreturn));
/**
* \brief Repositions the thread on the list it's currently on.
*
* This function should be called when thread's effective priority changes.
*
* \attention list_ must not be nullptr
*
* \param [in] loweringBefore selects the method of ordering when lowering the priority (it must be false when the
* priority is raised!):
* - true - the thread is moved to the head of the group of threads with the new priority, this is accomplished by
* temporarily boosting effective priority by 1,
* - false - the thread is moved to the tail of the group of threads with the new priority.
*/
void reposition(bool loweringBefore);
/**
* \brief "Run" function of thread
*
* This should be overridden by derived classes.
*/
virtual void run() = 0;
/**
* \brief Termination hook function of thread
*
* This function is called after run() completes.
*
* This should be overridden by derived classes.
*/
virtual void terminationHook_() = 0;
/// internal stack object
architecture::Stack stack_;
/// storage for list link
Link link_;
/// list of mutex control blocks with enabled priority protocol owned by this thread
MutexControlBlockList ownedProtocolMutexControlBlocksList_;
/// pointer to MutexControlBlock (with PriorityInheritance protocol) that blocks this thread
const synchronization::MutexControlBlock* priorityInheritanceMutexControlBlock_;
/// pointer to list that has this object
ThreadControlBlockList* list_;
/// iterator to the element on the list, valid only when list_ != nullptr
ThreadControlBlockListIterator iterator_;
/// information related to unblocking
union
{
/// functor executed in unblockHook() - valid only when thread is blocked
const UnblockFunctor* unblockFunctor_;
/// reason of previous unblocking of the thread - valid only when thread is not blocked
UnblockReason unblockReason_;
};
/// newlib's _reent structure with thread-specific data
_reent reent_;
/// thread's priority, 0 - lowest, UINT8_MAX - highest
uint8_t priority_;
/// thread's boosted priority, 0 - no boosting
uint8_t boostedPriority_;
/// round-robin quantum
RoundRobinQuantum roundRobinQuantum_;
/// scheduling policy of the thread
SchedulingPolicy schedulingPolicy_;
/// current state of object
State state_;
};
} // namespace scheduler
} // namespace distortos
#endif // INCLUDE_DISTORTOS_SCHEDULER_THREADCONTROLBLOCK_HPP_
<commit_msg>ThreadControlBlock: delete copy constructor, copy assignment and move assignment, force generation of move constructor<commit_after>/**
* \file
* \brief ThreadControlBlock class header
*
* \author Copyright (C) 2014-2015 Kamil Szczygiel http://www.distortec.com http://www.freddiechopin.info
*
* \par License
* 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/.
*
* \date 2015-02-14
*/
#ifndef INCLUDE_DISTORTOS_SCHEDULER_THREADCONTROLBLOCK_HPP_
#define INCLUDE_DISTORTOS_SCHEDULER_THREADCONTROLBLOCK_HPP_
#include "distortos/scheduler/RoundRobinQuantum.hpp"
#include "distortos/scheduler/ThreadControlBlockList-types.hpp"
#include "distortos/scheduler/MutexControlBlockList.hpp"
#include "distortos/architecture/Stack.hpp"
#include "distortos/SchedulingPolicy.hpp"
#include "distortos/estd/TypeErasedFunctor.hpp"
namespace distortos
{
namespace scheduler
{
class ThreadControlBlockList;
/// ThreadControlBlock class is a simple description of a Thread
class ThreadControlBlock
{
public:
/// state of the thread
enum class State : uint8_t
{
/// state in which thread is created, before being added to Scheduler
New,
/// thread is runnable
Runnable,
/// thread is sleeping
Sleeping,
/// thread is blocked on Semaphore
BlockedOnSemaphore,
/// thread is suspended
Suspended,
/// thread is terminated
Terminated,
/// thread is blocked on Mutex
BlockedOnMutex,
/// thread is blocked on ConditionVariable
BlockedOnConditionVariable,
};
/// reason of thread unblocking
enum class UnblockReason : uint8_t
{
/// explicit request to unblock the thread - normal unblock
UnblockRequest,
/// timeout - unblock via software timer
Timeout,
};
/// type of object used as storage for ThreadControlBlockList elements - 3 pointers
using Link = std::array<std::aligned_storage<sizeof(void*), alignof(void*)>::type, 3>;
/// UnblockFunctor is a functor executed when unblocking the thread, it receives one parameter - a reference to
/// ThreadControlBlock that is being unblocked
using UnblockFunctor = estd::TypeErasedFunctor<void(ThreadControlBlock&)>;
/**
* \brief ThreadControlBlock constructor.
*
* \param [in] buffer is a pointer to stack's buffer
* \param [in] size is the size of stack's buffer, bytes
* \param [in] priority is the thread's priority, 0 - lowest, UINT8_MAX - highest
* \param [in] schedulingPolicy is the scheduling policy of the thread
*/
ThreadControlBlock(void* buffer, size_t size, uint8_t priority, SchedulingPolicy schedulingPolicy);
/**
* \brief ThreadControlBlock constructor.
*
* \param [in] stack is an rvalue reference to architecture::Stack object which will be adopted for this thread
* \param [in] priority is the thread's priority, 0 - lowest, UINT8_MAX - highest
* \param [in] schedulingPolicy is the scheduling policy of the thread
*/
ThreadControlBlock(architecture::Stack&& stack, uint8_t priority, SchedulingPolicy schedulingPolicy);
/**
* \brief Block hook function of thread
*
* Saves pointer to UnblockFunctor.
*
* \attention This function should be called only by Scheduler::blockInternal().
*
* \param [in] unblockFunctor is a pointer to UnblockFunctor which will be executed in unblockHook()
*/
void blockHook(const UnblockFunctor* const unblockFunctor)
{
unblockFunctor_ = unblockFunctor;
}
/**
* \return effective priority of ThreadControlBlock
*/
uint8_t getEffectivePriority() const
{
return std::max(priority_, boostedPriority_);
}
/**
* \return iterator to the element on the list, valid only when list_ != nullptr
*/
ThreadControlBlockListIterator getIterator() const
{
return iterator_;
}
/**
* \return reference to internal storage for list link
*/
Link& getLink()
{
return link_;
}
/**
* \return pointer to list that has this object
*/
ThreadControlBlockList* getList() const
{
return list_;
}
/**
* \return reference to list of mutex control blocks with enabled priority protocol owned by this thread
*/
MutexControlBlockList& getOwnedProtocolMutexControlBlocksList()
{
return ownedProtocolMutexControlBlocksList_;
}
/**
* \return priority of ThreadControlBlock
*/
uint8_t getPriority() const
{
return priority_;
}
/**
* \return reference to internal RoundRobinQuantum object
*/
RoundRobinQuantum& getRoundRobinQuantum()
{
return roundRobinQuantum_;
}
/**
* \return scheduling policy of the thread
*/
SchedulingPolicy getSchedulingPolicy() const
{
return schedulingPolicy_;
}
/**
* \return reference to internal Stack object
*/
architecture::Stack& getStack()
{
return stack_;
}
/**
* \return current state of object
*/
State getState() const
{
return state_;
}
/**
* \return reason of previous unblocking of the thread
*/
UnblockReason getUnblockReason() const
{
return unblockReason_;
}
/**
* \brief Sets the iterator to the element on the list.
*
* \param [in] iterator is an iterator to the element on the list
*/
void setIterator(const ThreadControlBlockListIterator iterator)
{
iterator_ = iterator;
}
/**
* \brief Sets the list that has this object.
*
* \param [in] list is a pointer to list that has this object
*/
void setList(ThreadControlBlockList* const list)
{
list_ = list;
}
/**
* \brief Changes priority of thread.
*
* If the priority really changes, the position in the thread list is adjusted and context switch may be requested.
*
* \param [in] priority is the new priority of thread
* \param [in] alwaysBehind selects the method of ordering when lowering the priority
* - false - the thread is moved to the head of the group of threads with the new priority (default),
* - true - the thread is moved to the tail of the group of threads with the new priority.
*/
void setPriority(uint8_t priority, bool alwaysBehind = {});
/**
* \param [in] priorityInheritanceMutexControlBlock is a pointer to MutexControlBlock (with PriorityInheritance
* protocol) that blocks this thread
*/
void setPriorityInheritanceMutexControlBlock(const synchronization::MutexControlBlock* const
priorityInheritanceMutexControlBlock)
{
priorityInheritanceMutexControlBlock_ = priorityInheritanceMutexControlBlock;
}
/**
* param [in] schedulingPolicy is the new scheduling policy of the thread
*/
void setSchedulingPolicy(SchedulingPolicy schedulingPolicy);
/**
* \param [in] state is the new state of object
*/
void setState(const State state)
{
state_ = state;
}
/**
* \brief Hook function called when context is switched to this thread.
*
* Sets global _impure_ptr (from newlib) to thread's \a reent_ member variable.
*
* \attention This function should be called only by Scheduler::switchContext().
*/
void switchedToHook()
{
_impure_ptr = &reent_;
}
/**
* \brief Termination hook function of thread
*
* \attention This function should be called only by Scheduler::remove().
*/
void terminationHook()
{
terminationHook_();
}
/**
* \brief Unblock hook function of thread
*
* Resets round-robin's quantum, sets unblock reason and executes unblock functor saved in blockHook().
*
* \attention This function should be called only by Scheduler::unblockInternal().
*
* \param [in] unblockReason is the new reason of unblocking of the thread
*/
void unblockHook(UnblockReason unblockReason);
/**
* \brief Updates boosted priority of the thread.
*
* This function should be called after all operations involving this thread and a mutex with enabled priority
* protocol.
*
* \param [in] boostedPriority is the initial boosted priority, this should be effective priority of the thread that
* is about to be blocked on a mutex owned by this thread, default - 0
*/
void updateBoostedPriority(uint8_t boostedPriority = {});
ThreadControlBlock(const ThreadControlBlock&) = delete;
ThreadControlBlock(ThreadControlBlock&&) = default;
const ThreadControlBlock& operator=(const ThreadControlBlock&) = delete;
ThreadControlBlock& operator=(ThreadControlBlock&&) = delete;
protected:
/**
* \brief ThreadControlBlock's destructor
*
* \note Polymorphic objects of ThreadControlBlock type must not be deleted via pointer/reference
*/
~ThreadControlBlock();
private:
/**
* \brief Thread runner function - entry point of threads.
*
* After return from actual thread function, thread is terminated, so this function never returns.
*
* \param [in] threadControlBlock is a reference to ThreadControlBlock object that is being run
*/
static void threadRunner(ThreadControlBlock& threadControlBlock) __attribute__ ((noreturn));
/**
* \brief Repositions the thread on the list it's currently on.
*
* This function should be called when thread's effective priority changes.
*
* \attention list_ must not be nullptr
*
* \param [in] loweringBefore selects the method of ordering when lowering the priority (it must be false when the
* priority is raised!):
* - true - the thread is moved to the head of the group of threads with the new priority, this is accomplished by
* temporarily boosting effective priority by 1,
* - false - the thread is moved to the tail of the group of threads with the new priority.
*/
void reposition(bool loweringBefore);
/**
* \brief "Run" function of thread
*
* This should be overridden by derived classes.
*/
virtual void run() = 0;
/**
* \brief Termination hook function of thread
*
* This function is called after run() completes.
*
* This should be overridden by derived classes.
*/
virtual void terminationHook_() = 0;
/// internal stack object
architecture::Stack stack_;
/// storage for list link
Link link_;
/// list of mutex control blocks with enabled priority protocol owned by this thread
MutexControlBlockList ownedProtocolMutexControlBlocksList_;
/// pointer to MutexControlBlock (with PriorityInheritance protocol) that blocks this thread
const synchronization::MutexControlBlock* priorityInheritanceMutexControlBlock_;
/// pointer to list that has this object
ThreadControlBlockList* list_;
/// iterator to the element on the list, valid only when list_ != nullptr
ThreadControlBlockListIterator iterator_;
/// information related to unblocking
union
{
/// functor executed in unblockHook() - valid only when thread is blocked
const UnblockFunctor* unblockFunctor_;
/// reason of previous unblocking of the thread - valid only when thread is not blocked
UnblockReason unblockReason_;
};
/// newlib's _reent structure with thread-specific data
_reent reent_;
/// thread's priority, 0 - lowest, UINT8_MAX - highest
uint8_t priority_;
/// thread's boosted priority, 0 - no boosting
uint8_t boostedPriority_;
/// round-robin quantum
RoundRobinQuantum roundRobinQuantum_;
/// scheduling policy of the thread
SchedulingPolicy schedulingPolicy_;
/// current state of object
State state_;
};
} // namespace scheduler
} // namespace distortos
#endif // INCLUDE_DISTORTOS_SCHEDULER_THREADCONTROLBLOCK_HPP_
<|endoftext|> |
<commit_before>/* mockturtle: C++ logic network library
* Copyright (C) 2018-2019 EPFL
*
* 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 xag_constant_fanin_optimization.hpp
\brief Finds constant transitive linear fanin to AND gates
\author Mathias Soeken
*/
#pragma once
#include <cstdint>
#include <string>
#include "cleanup.hpp"
#include "dont_cares.hpp"
#include "../networks/xag.hpp"
#include "../utils/node_map.hpp"
#include "../views/topo_view.hpp"
namespace mockturtle
{
namespace detail
{
class xag_constant_fanin_optimization_impl
{
public:
xag_constant_fanin_optimization_impl( xag_network const& xag )
: xag( xag ),
old2new( xag ),
lfi( xag )
{
}
xag_network run()
{
xag_network dest;
old2new[xag.get_node( xag.get_constant( false ) )] = dest.get_constant( false );
if ( xag.get_node( xag.get_constant( true ) ) != xag.get_node( xag.get_constant( true ) ) )
{
old2new[xag.get_node( xag.get_constant( true ) )] = dest.get_constant( true );
}
xag.foreach_pi( [&]( auto const& n ) {
old2new[n] = dest.create_pi();
} );
topo_view{xag}.foreach_node( [&]( auto const& n ) {
if ( xag.is_constant( n ) || xag.is_pi( n ) )
return;
if ( xag.is_xor( n ) )
{
std::vector<xag_network::signal> children;
xag.foreach_fanin( n, [&]( auto const& f ) {
children.push_back( old2new[xag.get_node( f )] );
} );
old2new[n] = dest.create_xor( children[0], children[1] );
}
else /* is AND */
{
// 1st bool is true, if LFI is empty
// 2nd bool is complement flag of child
// 3rd is corresponding dest child
std::array<std::tuple<bool, bool, xag_network::signal>, 2> lfi_info;
xag.foreach_fanin( n, [&]( auto const& f, auto i ) {
lfi_info[i] = {compute_lfi( xag.get_node( f ) ).empty(), xag.is_complemented( f ), old2new[xag.get_node( f )] ^ xag.is_complemented(f)};
} );
if ( std::get<0>( lfi_info[0] ) )
{
old2new[n] = std::get<1>( lfi_info[0] ) ? std::get<2>( lfi_info[1] ) : dest.get_constant( false );
}
else if ( std::get<0>( lfi_info[1] ) )
{
old2new[n] = std::get<1>( lfi_info[1] ) ? std::get<2>( lfi_info[0] ) : dest.get_constant( false );
}
else
{
old2new[n] = dest.create_and( std::get<2>( lfi_info[0] ), std::get<2>( lfi_info[1] ) );
}
}
} );
xag.foreach_po( [&]( auto const& f ) {
dest.create_po( old2new[xag.get_node( f )] ^ xag.is_complemented( f ) );
} );
return cleanup_dangling( dest );
}
private:
std::vector<xag_network::node> const& compute_lfi( xag_network::node const& n )
{
if ( lfi.has( n ) )
{
return lfi[n];
}
assert( !xag.is_constant( n ) );
if ( xag.is_pi( n ) || xag.is_and( n ) )
{
return lfi[n] = {n};
}
// TODO generalize for n-ary XOR
assert( xag.is_xor( n ) && xag.fanin_size( n ) == 2u );
std::array<std::vector<xag_network::node>, 2> child_lfi;
xag.foreach_fanin( n, [&]( auto const& f, auto i ) {
child_lfi[i] = compute_lfi( xag.get_node( f ) );
} );
// merge LFIs
std::vector<xag_network::node> node_lfi;
auto it1 = child_lfi[0].begin();
auto it2 = child_lfi[1].begin();
while ( it1 != child_lfi[0].end() && it2 != child_lfi[1].end() )
{
if ( *it1 < *it2 )
{
node_lfi.push_back( *it1++ );
}
else if ( *it2 < *it1 )
{
node_lfi.push_back( *it2++ );
}
else
{
++it1;
++it2;
}
}
std::copy( it1, child_lfi[0].end(), std::back_inserter( node_lfi ) );
std::copy( it2, child_lfi[1].end(), std::back_inserter( node_lfi ) );
return lfi[n] = node_lfi;
}
private:
xag_network const& xag;
node_map<xag_network::signal, xag_network> old2new;
unordered_node_map<std::vector<xag_network::node>, xag_network> lfi;
};
}
/*! \brief Optimizes some AND gates by computing transitive linear fanin
*
* This function reevaluates the transitive linear fanin for each AND gate.
* This is a subnetwork composed of all immediate XOR gates in the transitive
* fanin cone until primary inputs or AND gates are reached. This linear
* transitive fanin might be constant for some fanin due to the cancellation
* property of the XOR operation. In such cases the AND gate can be replaced
* by a constant or a fanin.
*/
xag_network xag_constant_fanin_optimization( xag_network const& xag )
{
return detail::xag_constant_fanin_optimization_impl( xag ).run();
}
/*! \brief Optimizes some AND gates using satisfiability don't cares
*
* If an AND gate is satisfiability don't care for assignment 00, it can be
* replaced by an XNOR gate, therefore reducing the multiplicative complexity.
*/
xag_network xag_dont_cares_optimization( xag_network const& xag )
{
node_map<xag_network::signal, xag_network> old_to_new( xag );
xag_network dest;
old_to_new[xag.get_constant( false )] = dest.get_constant( false );
xag.foreach_pi( [&]( auto const& n ) {
old_to_new[n] = dest.create_pi();
} );
satisfiability_dont_cares_checker<xag_network> checker( xag );
topo_view<xag_network>{xag}.foreach_node( [&]( auto const& n ) {
if ( xag.is_constant( n ) || xag.is_pi( n ) ) return;
std::array<xag_network::signal, 2> fanin;
xag.foreach_fanin( n, [&]( auto const& f, auto i ) {
fanin[i] = old_to_new[f] ^ xag.is_complemented( f );
} );
if ( xag.is_and( n ) )
{
if ( checker.is_dont_care( n, {false, false} ) )
{
old_to_new[n] = dest.create_xnor( fanin[0], fanin[1] );
}
else
{
old_to_new[n] = dest.create_and( fanin[0], fanin[1] );
}
}
else /* is XOR */
{
old_to_new[n] = dest.create_xor( fanin[0], fanin[1] );
}
} );
xag.foreach_po( [&]( auto const& f ) {
dest.create_po( old_to_new[f] ^ xag.is_complemented( f ) );
});
return dest;
}
} /* namespace mockturtle */
<commit_msg>Better algorithm for XAG optimization (idea from Bruno). (#248)<commit_after>/* mockturtle: C++ logic network library
* Copyright (C) 2018-2019 EPFL
*
* 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 xag_optimization.hpp
\brief Various XAG optimization algorithms
\author Mathias Soeken
*/
#pragma once
#include <cstdint>
#include <string>
#include "../networks/xag.hpp"
#include "../utils/node_map.hpp"
#include "../views/topo_view.hpp"
#include "cleanup.hpp"
#include "dont_cares.hpp"
namespace mockturtle
{
namespace detail
{
class xag_constant_fanin_optimization_impl
{
public:
xag_constant_fanin_optimization_impl( xag_network const& xag )
: xag( xag )
{
}
xag_network run()
{
xag_network dest;
node_map<xag_network::signal, xag_network> old2new( xag );
node_map<std::vector<xag_network::node>, xag_network> lfi( xag );
old2new[xag.get_node( xag.get_constant( false ) )] = dest.get_constant( false );
if ( xag.get_node( xag.get_constant( true ) ) != xag.get_node( xag.get_constant( false ) ) )
{
old2new[xag.get_node( xag.get_constant( true ) )] = dest.get_constant( true );
}
xag.foreach_pi( [&]( auto const& n ) {
old2new[n] = dest.create_pi();
lfi[n].emplace_back( n );
} );
topo_view{xag}.foreach_node( [&]( auto const& n ) {
if ( xag.is_constant( n ) || xag.is_pi( n ) )
return;
if ( xag.is_xor( n ) )
{
std::array<xag_network::signal*, 2> children;
std::array<std::vector<xag_network::node>*, 2> clfi;
xag.foreach_fanin( n, [&]( auto const& f, auto i ) {
children[i] = &old2new[f];
clfi[i] = &lfi[f];
} );
lfi[n] = merge( *clfi[0], *clfi[1] );
if ( lfi[n].size() == 0 )
{
old2new[n] = dest.get_constant( false );
}
else if ( lfi[n].size() == 1 )
{
old2new[n] = dest.make_signal( lfi[n].front() );
}
else
{
old2new[n] = dest.create_xor( *children[0], *children[1] );
}
}
else /* is AND */
{
lfi[n].emplace_back( n );
std::vector<xag_network::signal> children;
xag.foreach_fanin( n, [&]( auto const& f ) {
children.push_back( old2new[f] ^ xag.is_complemented( f ) );
} );
old2new[n] = dest.create_and( children[0], children[1] );
}
} );
xag.foreach_po( [&]( auto const& f ) {
dest.create_po( old2new[f] ^ xag.is_complemented( f ) );
} );
return cleanup_dangling( dest );
}
private:
std::vector<xag_network::node> merge( std::vector<xag_network::node> const& s1, std::vector<xag_network::node> const& s2 ) const
{
std::vector<xag_network::node> s;
auto it1 = s1.begin();
auto it2 = s2.begin();
while ( it1 != s1.end() && it2 != s2.end() )
{
if ( *it1 < *it2 )
{
s.push_back( *it1++ );
}
else if ( *it2 < *it1 )
{
s.push_back( *it2++ );
}
else
{
++it1;
++it2;
}
}
std::copy( it1, s1.end(), std::back_inserter( s ) );
std::copy( it2, s2.end(), std::back_inserter( s ) );
return s;
}
private:
xag_network const& xag;
};
} // namespace detail
/*! \brief Optimizes some AND gates by computing transitive linear fanin
*
* This function reevaluates the transitive linear fanin for each AND gate.
* This is a subnetwork composed of all immediate XOR gates in the transitive
* fanin cone until primary inputs or AND gates are reached. This linear
* transitive fanin might be constant for some fanin due to the cancellation
* property of the XOR operation. In such cases the AND gate can be replaced
* by a constant or a fanin.
*/
xag_network xag_constant_fanin_optimization( xag_network const& xag )
{
return cleanup_dangling( detail::xag_constant_fanin_optimization_impl( xag ).run() );
}
/*! \brief Optimizes some AND gates using satisfiability don't cares
*
* If an AND gate is satisfiability don't care for assignment 00, it can be
* replaced by an XNOR gate, therefore reducing the multiplicative complexity.
*/
xag_network xag_dont_cares_optimization( xag_network const& xag )
{
node_map<xag_network::signal, xag_network> old_to_new( xag );
xag_network dest;
old_to_new[xag.get_constant( false )] = dest.get_constant( false );
xag.foreach_pi( [&]( auto const& n ) {
old_to_new[n] = dest.create_pi();
} );
satisfiability_dont_cares_checker<xag_network> checker( xag );
topo_view<xag_network>{xag}.foreach_node( [&]( auto const& n ) {
if ( xag.is_constant( n ) || xag.is_pi( n ) )
return;
std::array<xag_network::signal, 2> fanin;
xag.foreach_fanin( n, [&]( auto const& f, auto i ) {
fanin[i] = old_to_new[f] ^ xag.is_complemented( f );
} );
if ( xag.is_and( n ) )
{
if ( checker.is_dont_care( n, {false, false} ) )
{
old_to_new[n] = dest.create_xnor( fanin[0], fanin[1] );
}
else
{
old_to_new[n] = dest.create_and( fanin[0], fanin[1] );
}
}
else /* is XOR */
{
old_to_new[n] = dest.create_xor( fanin[0], fanin[1] );
}
} );
xag.foreach_po( [&]( auto const& f ) {
dest.create_po( old_to_new[f] ^ xag.is_complemented( f ) );
} );
return dest;
}
} /* namespace mockturtle */
<|endoftext|> |
<commit_before>/***************************************************************************
**
** Copyright (C) 2010 Nokia Corporation and/or its subsidiary(-ies).
** All rights reserved.
** Contact: Nokia Corporation (directui@nokia.com)
**
** This file is part of libmeegotouch.
**
** If you have questions regarding the use of this file, please contact
** Nokia at directui@nokia.com.
**
** 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
** and appearing in the file LICENSE.LGPL included in the packaging
** of this file.
**
****************************************************************************/
#include "ut_mextensionarea.h"
#include "mextensionarea.h"
#include "mextensionareaview.h"
#include "mextensionarea_p.h"
#include "mappletid_stub.h"
#include "mapplication.h"
#include "mappletinstancemanager_stub.h"
#include "mockdatastore.h"
#include "mobjectmenu_stub.h"
#include <QtTest/QtTest>
#include <mwidgetcreator.h>
M_REGISTER_WIDGET(TestExtensionArea);
// TestExtensionArea
class TestExtensionArea : public MExtensionArea
{
public:
TestExtensionArea() : MExtensionArea() { }
void addWidget(MWidget *widget, MDataStore &store) {
MExtensionArea::addWidget(widget, store);
}
void removeWidget(MWidget *widget) {
MExtensionArea::removeWidget(widget);
}
};
// The test class
void Ut_MExtensionArea::init()
{
area = new TestExtensionArea();
gMAppletInstanceManagerStub->stubReset();
}
void Ut_MExtensionArea::cleanup()
{
// Destroy the extension area.
delete area;
}
void Ut_MExtensionArea::initTestCase()
{
// MApplications must be created manually due to theme system changes
static int argc = 1;
static char *app_name = (char *)"./ut_mextensionarea";
app = new MApplication(argc, &app_name);
}
void Ut_MExtensionArea::cleanupTestCase()
{
// this is commented out for now, to prevent crash at exit:
// delete app;
}
void Ut_MExtensionArea::testAddition()
{
QSignalSpy spy(area->model(), SIGNAL(modified(QList<const char *>)));
MWidget *widget1 = new MWidget;
MockDataStore store1;
MWidget *widget2 = new MWidget;
MockDataStore store2;
// Add one widget and ensure that the model was modified.
area->addWidget(widget1, store1);
QCOMPARE(spy.count(), 1);
QCOMPARE(area->model()->dataStores()->keys().count(), 1);
QVERIFY(area->model()->dataStores()->contains(widget1));
spy.clear();
// Add another widget. Ensure that both widgets are in the model.
area->addWidget(widget2, store2);
QCOMPARE(spy.count(), 1);
QCOMPARE(area->model()->dataStores()->keys().count(), 2);
QVERIFY(area->model()->dataStores()->contains(widget1));
QVERIFY(area->model()->dataStores()->contains(widget2));
spy.clear();
// Add the first widget again. The model should not be modified.
area->addWidget(widget1, store1);
QCOMPARE(spy.count(), 0);
QCOMPARE(area->model()->dataStores()->keys().count(), 2);
}
void Ut_MExtensionArea::testRemoval()
{
QSignalSpy spy(area->model(), SIGNAL(modified(QList<const char *>)));
MWidget *widget1 = new MWidget;
MockDataStore store1;
MWidget *widget2 = new MWidget;
MockDataStore store2;
MWidget *widget3 = new MWidget;
MockDataStore store3;
// Add three widgets and ensure that they're in the model.
area->addWidget(widget1, store1);
area->addWidget(widget2, store2);
area->addWidget(widget3, store3);
QCOMPARE(spy.count(), 3);
QCOMPARE(area->model()->dataStores()->keys().count(), 3);
QVERIFY(area->model()->dataStores()->contains(widget1));
QVERIFY(area->model()->dataStores()->contains(widget2));
QVERIFY(area->model()->dataStores()->contains(widget3));
spy.clear();
// Remove widget2 and verify that the rest are in the model.
area->removeWidget(widget2);
QCOMPARE(spy.count(), 1);
QCOMPARE(area->model()->dataStores()->keys().count(), 2);
QVERIFY(area->model()->dataStores()->contains(widget1));
QVERIFY(!area->model()->dataStores()->contains(widget2));
QVERIFY(area->model()->dataStores()->contains(widget3));
spy.clear();
// Remove widget2 again and verify that the model was not changed.
area->removeWidget(widget2);
QCOMPARE(spy.count(), 0);
QCOMPARE(area->model()->dataStores()->keys().count(), 2);
QVERIFY(area->model()->dataStores()->contains(widget1));
QVERIFY(!area->model()->dataStores()->contains(widget2));
QVERIFY(area->model()->dataStores()->contains(widget3));
spy.clear();
}
QTEST_APPLESS_MAIN(Ut_MExtensionArea)
<commit_msg>Fixes: NB#235174 - ut_mextensionarea aborts (SIGBUS)<commit_after>/***************************************************************************
**
** Copyright (C) 2010 Nokia Corporation and/or its subsidiary(-ies).
** All rights reserved.
** Contact: Nokia Corporation (directui@nokia.com)
**
** This file is part of libmeegotouch.
**
** If you have questions regarding the use of this file, please contact
** Nokia at directui@nokia.com.
**
** 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
** and appearing in the file LICENSE.LGPL included in the packaging
** of this file.
**
****************************************************************************/
#include "ut_mextensionarea.h"
#include "mextensionarea.h"
#include "mextensionareaview.h"
#include "mextensionarea_p.h"
#include "mappletid_stub.h"
#include "mapplication.h"
#include "mappletinstancemanager_stub.h"
#include "mockdatastore.h"
#include "mobjectmenu_stub.h"
#include <QtTest/QtTest>
#include <mwidgetcreator.h>
M_REGISTER_WIDGET(TestExtensionArea);
// TestExtensionArea
class TestExtensionArea : public MExtensionArea
{
public:
TestExtensionArea() : MExtensionArea() { }
void addWidget(MWidget *widget, MDataStore &store) {
MExtensionArea::addWidget(widget, store);
}
void removeWidget(MWidget *widget) {
MExtensionArea::removeWidget(widget);
}
};
// The test class
void Ut_MExtensionArea::init()
{
area = new TestExtensionArea();
gMAppletInstanceManagerStub->stubReset();
}
void Ut_MExtensionArea::cleanup()
{
// Destroy the extension area.
delete area;
}
void Ut_MExtensionArea::initTestCase()
{
// MApplications must be created manually due to theme system changes
static int argc = 1;
static char *app_name = (char *)"./ut_mextensionarea";
app = new MApplication(argc, &app_name);
}
void Ut_MExtensionArea::cleanupTestCase()
{
delete app;
}
void Ut_MExtensionArea::testAddition()
{
QSignalSpy spy(area->model(), SIGNAL(modified(QList<const char *>)));
MWidget *widget1 = new MWidget;
MockDataStore store1;
MWidget *widget2 = new MWidget;
MockDataStore store2;
// Add one widget and ensure that the model was modified.
area->addWidget(widget1, store1);
QCOMPARE(spy.count(), 1);
QCOMPARE(area->model()->dataStores()->keys().count(), 1);
QVERIFY(area->model()->dataStores()->contains(widget1));
spy.clear();
// Add another widget. Ensure that both widgets are in the model.
area->addWidget(widget2, store2);
QCOMPARE(spy.count(), 1);
QCOMPARE(area->model()->dataStores()->keys().count(), 2);
QVERIFY(area->model()->dataStores()->contains(widget1));
QVERIFY(area->model()->dataStores()->contains(widget2));
spy.clear();
// Add the first widget again. The model should not be modified.
area->addWidget(widget1, store1);
QCOMPARE(spy.count(), 0);
QCOMPARE(area->model()->dataStores()->keys().count(), 2);
}
void Ut_MExtensionArea::testRemoval()
{
QSignalSpy spy(area->model(), SIGNAL(modified(QList<const char *>)));
MWidget *widget1 = new MWidget;
MockDataStore store1;
MWidget *widget2 = new MWidget;
MockDataStore store2;
MWidget *widget3 = new MWidget;
MockDataStore store3;
// Add three widgets and ensure that they're in the model.
area->addWidget(widget1, store1);
area->addWidget(widget2, store2);
area->addWidget(widget3, store3);
QCOMPARE(spy.count(), 3);
QCOMPARE(area->model()->dataStores()->keys().count(), 3);
QVERIFY(area->model()->dataStores()->contains(widget1));
QVERIFY(area->model()->dataStores()->contains(widget2));
QVERIFY(area->model()->dataStores()->contains(widget3));
spy.clear();
// Remove widget2 and verify that the rest are in the model.
area->removeWidget(widget2);
QCOMPARE(spy.count(), 1);
QCOMPARE(area->model()->dataStores()->keys().count(), 2);
QVERIFY(area->model()->dataStores()->contains(widget1));
QVERIFY(!area->model()->dataStores()->contains(widget2));
QVERIFY(area->model()->dataStores()->contains(widget3));
spy.clear();
// Remove widget2 again and verify that the model was not changed.
area->removeWidget(widget2);
QCOMPARE(spy.count(), 0);
QCOMPARE(area->model()->dataStores()->keys().count(), 2);
QVERIFY(area->model()->dataStores()->contains(widget1));
QVERIFY(!area->model()->dataStores()->contains(widget2));
QVERIFY(area->model()->dataStores()->contains(widget3));
spy.clear();
}
QTEST_APPLESS_MAIN(Ut_MExtensionArea)
<|endoftext|> |
<commit_before>#ifndef SIMHASH_HASH_H
#define SIMHASH_HASH_H
/* Simply holds references to all of our hash functions */
#include "hashes/jenkins.h"
#include "hashes/murmur.h"
#include "hashes/fnv.h"
/* Include a reference to the tokenizer to use */
#include "tokenizers/strspn.h"
/* For hash_t */
#include "common.h"
#include "cyclic.hpp"
namespace Simhash {
/**
* Compute a similarity hash for the provided string using a rolling hash
* function and a provided hash window
*
* @param tokens - An NULL-terminated array of character pointers to the
* nul-terminated tokens comprising the text.
*
* @return hash representative of the content of the text */
template <typename Hash=jenkins>
class Simhash {
public:
typedef Hash hash_type;
/* Alias of operator()
*
* Some languages have difficulty making use of operator(), and so this
* it made available for those languages */
inline hash_t hash(char **tokens) {
return operator()(tokens);
}
/* Return a simhash value using a moving window */
hash_t operator()(char **tokens) {
/* Simhash works by calculating the hashes of overlaping windows
* of the input, and then for each bit of that hash, increments a
* corresponding count. At the end, each of the counts is
* transformed back into a bit by whether or not the count is
* positive or negative */
// Counts
int64_t v[64] = {
0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0
};
hash_t hash(0); // The hash we're trying to produce
size_t j(0); // Counter
size_t window(3); // How many tokens in rolling hash?
char **tp; // For stepping through tokens
/* Create a tokenizer, hash function, and cyclic */
Hash hasher;
Cyclic<hash_t> cyclic(window);
for (tp = tokens; *tp != NULL; tp++) {
/* puts(*tp); /* debug */
hash_t r = cyclic.push(hasher(*tp, strlen(*tp), 0));
for (j = 63; j > 0; --j) {
v[j] += (r & 1) ? 1 : -1;
r = r >> 1;
}
v[j] += (r & 1) ? 1 : -1;
}
/* With counts appropriately tallied, create a 1 bit for each of
* the counts that's positive. That result is the hash. */
for (j = 0; j < 64; ++j) {
if (v[j] > 0) {
hash = hash | (static_cast<hash_t>(1) << j);
}
}
return hash;
}
/* As above, but operate on a vector of unsigned 64-bit numbers,
not strings. */
hash_t hash_fp(uint64_t *vec, int len)
{
// Counts
int64_t v[64] = {
0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0
};
hash_t hash(0); // The hash we're trying to produce
size_t j(0); // Counter
size_t window(3); // How many tokens in rolling hash?
int i; // For stepping through tokens
/* Create a tokenizer, hash function, and cyclic */
Hash hasher;
Cyclic<hash_t> cyclic(window);
for (i = 0; i < len; i++) {
hash_t r = cyclic.push(hasher(reinterpret_cast<char*>(vec+i), sizeof(uint64_t), 0));
for (j = 63; j > 0; --j) {
v[j] += (r & 1) ? 1 : -1;
r = r >> 1;
}
v[j] += (r & 1) ? 1 : -1;
}
/* With counts appropriately tallied, create a 1 bit for each of
* the counts that's positive. That result is the hash. */
for (j = 0; j < 64; ++j) {
if (v[j] > 0) {
hash = hash | (static_cast<hash_t>(1) << j);
}
}
return hash;
}
private:
/* Internal stuffs */
hash_type hasher;
};
}
#endif
<commit_msg>Added a signed version of hash_fp<commit_after>#ifndef SIMHASH_HASH_H
#define SIMHASH_HASH_H
/* Simply holds references to all of our hash functions */
#include "hashes/jenkins.h"
#include "hashes/murmur.h"
#include "hashes/fnv.h"
/* Include a reference to the tokenizer to use */
#include "tokenizers/strspn.h"
/* For hash_t */
#include "common.h"
#include "cyclic.hpp"
namespace Simhash {
/**
* Compute a similarity hash for the provided string using a rolling hash
* function and a provided hash window
*
* @param tokens - An NULL-terminated array of character pointers to the
* nul-terminated tokens comprising the text.
*
* @return hash representative of the content of the text */
template <typename Hash=jenkins>
class Simhash {
public:
typedef Hash hash_type;
/* Alias of operator()
*
* Some languages have difficulty making use of operator(), and so this
* it made available for those languages */
inline hash_t hash(char **tokens) {
return operator()(tokens);
}
/* Return a simhash value using a moving window */
hash_t operator()(char **tokens) {
/* Simhash works by calculating the hashes of overlaping windows
* of the input, and then for each bit of that hash, increments a
* corresponding count. At the end, each of the counts is
* transformed back into a bit by whether or not the count is
* positive or negative */
// Counts
int64_t v[64] = {
0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0
};
hash_t hash(0); // The hash we're trying to produce
size_t j(0); // Counter
size_t window(3); // How many tokens in rolling hash?
char **tp; // For stepping through tokens
/* Create a tokenizer, hash function, and cyclic */
Hash hasher;
Cyclic<hash_t> cyclic(window);
for (tp = tokens; *tp != NULL; tp++) {
/* puts(*tp); /* debug */
hash_t r = cyclic.push(hasher(*tp, strlen(*tp), 0));
for (j = 63; j > 0; --j) {
v[j] += (r & 1) ? 1 : -1;
r = r >> 1;
}
v[j] += (r & 1) ? 1 : -1;
}
/* With counts appropriately tallied, create a 1 bit for each of
* the counts that's positive. That result is the hash. */
for (j = 0; j < 64; ++j) {
if (v[j] > 0) {
hash = hash | (static_cast<hash_t>(1) << j);
}
}
return hash;
}
/* As above, but operate on a vector of unsigned 64-bit numbers,
not strings. */
hash_t hash_fp(uint64_t *vec, int len)
{
// Counts
int64_t v[64] = {
0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0
};
hash_t hash(0); // The hash we're trying to produce
size_t j(0); // Counter
size_t window(3); // How many tokens in rolling hash?
int i; // For stepping through tokens
/* Create a tokenizer, hash function, and cyclic */
Hash hasher;
Cyclic<hash_t> cyclic(window);
for (i = 0; i < len; i++) {
hash_t r = cyclic.push(hasher(reinterpret_cast<char*>(vec+i), sizeof(uint64_t), 0));
for (j = 63; j > 0; --j) {
v[j] += (r & 1) ? 1 : -1;
r = r >> 1;
}
v[j] += (r & 1) ? 1 : -1;
}
/* With counts appropriately tallied, create a 1 bit for each of
* the counts that's positive. That result is the hash. */
for (j = 0; j < 64; ++j) {
if (v[j] > 0) {
hash = hash | (static_cast<hash_t>(1) << j);
}
}
return hash;
}
/* As above, but operate on a vector of signed 64-bit integers. For
* some language bindings, casting and function overloading can be
* difficult to use, which is why it's given a new name */
hash_t hash_fps(int64_t *vec, int len) {
return hash_fp(reinterpret_cast<uint64_t*>(vec), len);
}
private:
/* Internal stuffs */
hash_type hasher;
};
}
#endif
<|endoftext|> |
<commit_before>#include "TCoroutine.h"
#include "Interface.h"
#include "helper/TConst.h"
#include "helper/TLogger.h"
void TestCoroutine::SetUp()
{
m_cv_counter = 0;
m_wait_counter = 0;
coro::Init(std::make_shared<CLogFake>());
}
void TestCoroutine::TearDown()
{
coro::Stop();
}
void TestCoroutine::IncNotify()
{
++m_cv_counter;
m_cv.notify_all();
}
void TestCoroutine::Wait(uint32_t val, const std::chrono::milliseconds& duration)
{
std::unique_lock<std::mutex> lck(m_mutex);
m_cv.wait_for(lck, duration, [&] {return (m_cv_counter == val);});
}
void TestCoroutine::IncWait(const std::chrono::milliseconds& duration)
{
++m_wait_counter;
Wait(m_wait_counter, duration);
}
TEST_F(TestCoroutine, DisallowToUseServiceSchedulerId)
{
ASSERT_THROW(coro::AddScheduler(coro::ERROR_SCHEDULER_ID, "main"), std::runtime_error);
ASSERT_THROW(coro::AddScheduler(coro::TIMEOUT_SCHEDULER_ID, "main"), std::runtime_error);
}
TEST_F(TestCoroutine, DisallowToUseDuplicateSchedulerId)
{
ASSERT_NO_THROW(coro::AddScheduler(E_SH_1, "main"));
ASSERT_THROW(coro::AddScheduler(E_SH_1, "dop"), std::runtime_error);
}
TEST_F(TestCoroutine, TaskWithoutYield)
{
coro::AddScheduler(E_SH_1, "main");
uint32_t process(0);
coro::Run([this, &process]
{
process = 1;
IncNotify();
}, E_SH_1);
IncWait();
ASSERT_EQ(1, process);
}
TEST_F(TestCoroutine, TaskWithOneYield)
{
coro::AddScheduler(E_SH_1, "main");
uint32_t process(0);
coro::tResumeHandle h_resume;
coro::Run([this, &process, &h_resume]
{
process = 1;
h_resume = coro::CurrentResumeId();
IncNotify();
coro::yield();
process = 2;
IncNotify();
}, E_SH_1);
IncWait();
ASSERT_EQ(1, process);
coro::Resume(h_resume, E_SH_1);
IncWait();
ASSERT_EQ(2, process);
}
TEST_F(TestCoroutine, TaskWithTwoYield)
{
coro::AddScheduler(E_SH_1, "main");
uint32_t process(0);
coro::tResumeHandle h_resume;
coro::Run([this, &process, &h_resume]
{
process = 1;
h_resume = coro::CurrentResumeId();
IncNotify();
coro::yield();
process = 2;
h_resume = coro::CurrentResumeId();
IncNotify();
coro::yield();
process = 3;
IncNotify();
}, E_SH_1);
IncWait();
ASSERT_EQ(1, process);
coro::Resume(h_resume, E_SH_1);
IncWait();
ASSERT_EQ(2, process);
coro::Resume(h_resume, E_SH_1);
IncWait();
ASSERT_EQ(3, process);
}
TEST_F(TestCoroutine, ResumeInOtherScheduler)
{
coro::AddScheduler(E_SH_1, "main");
coro::AddScheduler(E_SH_2, "dop");
coro::tResumeHandle h_resume;
coro::Run([this, &h_resume]
{
ASSERT_EQ(E_SH_1, coro::CurrentSchedulerId());
h_resume = coro::CurrentResumeId();
IncNotify();
coro::yield();
ASSERT_EQ(E_SH_2, coro::CurrentSchedulerId());
IncNotify();
}, E_SH_1);
IncWait();
coro::Resume(h_resume, E_SH_2);
IncWait();
}
TEST_F(TestCoroutine, RaiseTimeOutExceptionForLongCall)
{
coro::AddScheduler(E_SH_1, "main");
coro::Run([this]
{
try
{
auto short_timeout = std::chrono::milliseconds(100);
coro::CTimeout t(short_timeout);
coro::yield();
FAIL();
}
catch (const coro::TimeoutError&)
{
ASSERT_EQ(E_SH_1, coro::CurrentSchedulerId());
}
catch (...)
{
FAIL();
}
IncNotify();
}, E_SH_1);
IncWait();
}
TEST_F(TestCoroutine, NoExceptionIfOperationCompletedBeforeTimeOut)
{
coro::AddScheduler(E_SH_1, "main");
coro::tResumeHandle h_resume;
coro::Run([this, &h_resume]
{
try
{
auto long_timeout = std::chrono::seconds(10);
coro::CTimeout t(long_timeout);
h_resume = coro::CurrentResumeId();
IncNotify();
coro::yield();
ASSERT_EQ(E_SH_1, coro::CurrentSchedulerId());
IncNotify();
}
catch (const coro::TimeoutError&)
{
FAIL();
}
catch (...)
{
FAIL();
}
}, E_SH_1);
IncWait();
coro::Resume(h_resume, E_SH_1);
IncWait();
}
TEST_F(TestCoroutine, StopInfiniteLoopCoroutine)
{
coro::AddScheduler(E_SH_1, "main");
coro::Run([]
{
while(true) {};
FAIL();
}, E_SH_1);
coro::Stop(std::chrono::milliseconds(10));
}
<commit_msg>test for timeout scope error<commit_after>#include "TCoroutine.h"
#include <thread>
#include "Interface.h"
#include "helper/TConst.h"
#include "helper/TLogger.h"
void TestCoroutine::SetUp()
{
m_cv_counter = 0;
m_wait_counter = 0;
coro::Init(std::make_shared<CLogFake>());
}
void TestCoroutine::TearDown()
{
coro::Stop();
}
void TestCoroutine::IncNotify()
{
++m_cv_counter;
m_cv.notify_all();
}
void TestCoroutine::Wait(uint32_t val, const std::chrono::milliseconds& duration)
{
std::unique_lock<std::mutex> lck(m_mutex);
m_cv.wait_for(lck, duration, [&] {return (m_cv_counter == val);});
}
void TestCoroutine::IncWait(const std::chrono::milliseconds& duration)
{
++m_wait_counter;
Wait(m_wait_counter, duration);
}
TEST_F(TestCoroutine, DisallowToUseServiceSchedulerId)
{
ASSERT_THROW(coro::AddScheduler(coro::ERROR_SCHEDULER_ID, "main"), std::runtime_error);
ASSERT_THROW(coro::AddScheduler(coro::TIMEOUT_SCHEDULER_ID, "main"), std::runtime_error);
}
TEST_F(TestCoroutine, DisallowToUseDuplicateSchedulerId)
{
ASSERT_NO_THROW(coro::AddScheduler(E_SH_1, "main"));
ASSERT_THROW(coro::AddScheduler(E_SH_1, "dop"), std::runtime_error);
}
TEST_F(TestCoroutine, TaskWithoutYield)
{
coro::AddScheduler(E_SH_1, "main");
uint32_t process(0);
coro::Run([this, &process]
{
process = 1;
IncNotify();
}, E_SH_1);
IncWait();
ASSERT_EQ(1, process);
}
TEST_F(TestCoroutine, TaskWithOneYield)
{
coro::AddScheduler(E_SH_1, "main");
uint32_t process(0);
coro::tResumeHandle h_resume;
coro::Run([this, &process, &h_resume]
{
process = 1;
h_resume = coro::CurrentResumeId();
IncNotify();
coro::yield();
process = 2;
IncNotify();
}, E_SH_1);
IncWait();
ASSERT_EQ(1, process);
coro::Resume(h_resume, E_SH_1);
IncWait();
ASSERT_EQ(2, process);
}
TEST_F(TestCoroutine, TaskWithTwoYield)
{
coro::AddScheduler(E_SH_1, "main");
uint32_t process(0);
coro::tResumeHandle h_resume;
coro::Run([this, &process, &h_resume]
{
process = 1;
h_resume = coro::CurrentResumeId();
IncNotify();
coro::yield();
process = 2;
h_resume = coro::CurrentResumeId();
IncNotify();
coro::yield();
process = 3;
IncNotify();
}, E_SH_1);
IncWait();
ASSERT_EQ(1, process);
coro::Resume(h_resume, E_SH_1);
IncWait();
ASSERT_EQ(2, process);
coro::Resume(h_resume, E_SH_1);
IncWait();
ASSERT_EQ(3, process);
}
TEST_F(TestCoroutine, ResumeInOtherScheduler)
{
coro::AddScheduler(E_SH_1, "main");
coro::AddScheduler(E_SH_2, "dop");
coro::tResumeHandle h_resume;
coro::Run([this, &h_resume]
{
ASSERT_EQ(E_SH_1, coro::CurrentSchedulerId());
h_resume = coro::CurrentResumeId();
IncNotify();
coro::yield();
ASSERT_EQ(E_SH_2, coro::CurrentSchedulerId());
IncNotify();
}, E_SH_1);
IncWait();
coro::Resume(h_resume, E_SH_2);
IncWait();
}
TEST_F(TestCoroutine, RaiseTimeOutExceptionForLongCall)
{
coro::AddScheduler(E_SH_1, "main");
coro::Run([this]
{
try
{
auto short_timeout = std::chrono::milliseconds(100);
coro::CTimeout t(short_timeout);
coro::yield();
FAIL();
}
catch (const coro::TimeoutError&)
{
ASSERT_EQ(E_SH_1, coro::CurrentSchedulerId());
}
catch (...)
{
FAIL();
}
IncNotify();
}, E_SH_1);
IncWait();
}
TEST_F(TestCoroutine, NoExceptionIfTimeoutExitFromScope)
{
coro::AddScheduler(E_SH_1, "main");
coro::tResumeHandle h_resume;
coro::Run([this, &h_resume]
{
try
{
{
auto canceled_timeout = std::chrono::milliseconds(0);
coro::CTimeout t(canceled_timeout);
}
auto not_expired_timeout = std::chrono::seconds(10);
coro::CTimeout t(not_expired_timeout);
auto wait_expired_canceled_timeout = std::chrono::milliseconds(100);
std::this_thread::sleep_for(wait_expired_canceled_timeout);
h_resume = coro::CurrentResumeId();
IncNotify();
coro::yield();
SUCCEED();
IncNotify();
}
catch (const coro::TimeoutError&)
{
FAIL();
}
catch (...)
{
FAIL();
}
IncNotify();
}, E_SH_1);
IncWait();
}
TEST_F(TestCoroutine, NoExceptionIfOperationCompletedBeforeTimeOut)
{
coro::AddScheduler(E_SH_1, "main");
coro::tResumeHandle h_resume;
coro::Run([this, &h_resume]
{
try
{
auto long_timeout = std::chrono::seconds(10);
coro::CTimeout t(long_timeout);
h_resume = coro::CurrentResumeId();
IncNotify();
coro::yield();
ASSERT_EQ(E_SH_1, coro::CurrentSchedulerId());
IncNotify();
}
catch (const coro::TimeoutError&)
{
FAIL();
}
catch (...)
{
FAIL();
}
}, E_SH_1);
IncWait();
coro::Resume(h_resume, E_SH_1);
IncWait();
}
TEST_F(TestCoroutine, StopInfiniteLoopCoroutine)
{
coro::AddScheduler(E_SH_1, "main");
coro::Run([]
{
while(true) {};
FAIL();
}, E_SH_1);
coro::Stop(std::chrono::milliseconds(10));
}
<|endoftext|> |
<commit_before>/*************************************************************************
* Copyright (C) 2011-2012 by Paul-Louis Ageneau *
* paul-louis (at) ageneau (dot) org *
* *
* This file is part of TeapotNet. *
* *
* TeapotNet is free software: you can redistribute it and/or modify *
* it under the terms of the GNU Affero General Public License as *
* published by the Free Software Foundation, either version 3 of *
* the License, or (at your option) any later version. *
* *
* TeapotNet is distributed in the hope that it will be useful, but *
* WITHOUT ANY WARRANTY; without even the implied warranty of *
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the *
* GNU Affero General Public License for more details. *
* *
* You should have received a copy of the GNU Affero General Public *
* License along with TeapotNet. *
* If not, see <http://www.gnu.org/licenses/>. *
*************************************************************************/
#include "http.h"
#include "exception.h"
#include "html.h"
namespace tpot
{
Http::Request::Request(void)
{
clear();
}
Http::Request::Request(const String &url, const String &method)
{
clear();
int p = url.find("://");
if(p == String::NotFound) this->url = url;
else {
String protocol(url.substr(0,p));
if(protocol != "http") throw Exception(String("Unknown protocol in URL: ")+protocol);
String host(url.substr(p+3));
this->url = String('/') + host.cut('/');
headers["Host"] = host;
}
if(!method.empty()) this->method = method;
this->headers["User-Agent"] = String(APPNAME) + '/' + APPVERSION;
}
void Http::Request::send(Socket &sock)
{
this->sock = &sock;
if(version == "1.1" && !headers.contains("Connexion"))
headers["Connection"] = "close";
if(!headers.contains("Accept-Encoding"))
headers["Accept-Encoding"] = "identity";
String completeUrl(url);
if(!get.empty())
{
if(completeUrl.find('?') == String::NotFound)
completeUrl+= '?';
for( StringMap::iterator it = get.begin();
it != get.end();
++it)
{
completeUrl<<'&'<<it->first.urlEncode()<<'='<<it->second.urlEncode();
}
}
String postData;
if(!post.empty())
{
for( StringMap::iterator it = post.begin();
it != post.end();
++it)
{
if(!postData.empty()) postData<<'&';
postData<<it->first.urlEncode()<<'='<<it->second.urlEncode();
}
headers["Content-Length"] = "";
headers["Content-Length"] << postData.size();
headers["Content-Type"] = "application/x-www-form-urlencoded";
}
String buf;
buf<<method<<" "<<completeUrl<<" HTTP/"<<version<<"\r\n";
for( StringMap::iterator it = headers.begin();
it != headers.end();
++it)
{
List<String> lines;
it->second.remove('\r');
it->second.explode(lines,'\n');
for( List<String>::iterator l = lines.begin();
l != lines.end();
++l)
{
buf<<it->first<<": "<<*l<<"\r\n";
}
}
for( StringMap::iterator it = cookies.begin();
it != cookies.end();
++it)
{
buf<<"Set-Cookie: "<< it->first<<'='<<it->second<<"\r\n";
}
buf<<"\r\n";
sock<<buf;
if(!postData.empty())
sock<<postData;
}
void Http::Request::recv(Socket &sock)
{
this->sock = &sock;
clear();
// Read first line
String line;
if(!sock.readLine(line)) throw IOException("Connection closed");
method.clear();
url.clear();
line.readString(method);
line.readString(url);
String protocol;
line.readString(protocol);
version = protocol.cut('/');
if(url.empty() || version.empty() || protocol != "HTTP")
throw 400;
if(method != "GET" && method != "POST" /*&& method != "HEAD"*/)
throw 405;
// Read headers
while(true)
{
String line;
AssertIO(sock.readLine(line));
if(line.empty()) break;
String value = line.cut(':');
line.trim();
value.trim();
headers.insert(line,value);
}
// Read cookies
String cookie;
if(headers.get("Cookie",cookie))
{
while(!cookie.empty())
{
String next = cookie.cut(';');
String value = cookie.cut('=');
cookie.trim();
value.trim();
cookies.insert(cookie,value);
cookie = next;
}
}
// Read URL variables
String getData = url.cut('?');
if(!getData.empty())
{
List<String> exploded;
getData.explode(exploded,'&');
for( List<String>::iterator it = exploded.begin();
it != exploded.end();
++it)
{
String value = it->cut('=').urlDecode();
get.insert(it->urlDecode(), value);
}
}
// Read post variables
if(method == "POST")
{
if(!headers.contains("Content-Length"))
throw Exception("Missing Content-Length header in POST request");
size_t size = 0;
String contentLength(headers["Content-Length"]);
contentLength >> size;
String data;
if(sock.read(data, size) != size)
throw IOException("Connection unexpectedly closed");
if(headers.contains("Content-Type"))
{
String type = headers["Content-Type"];
String parameters = type.cut(';');
type.trim();
if(type == "application/x-www-form-urlencoded")
{
List<String> exploded;
data.explode(exploded,'&');
for( List<String>::iterator it = exploded.begin();
it != exploded.end();
++it)
{
String value = it->cut('=').urlDecode();
post.insert(it->urlDecode(), value);
}
}
}
}
}
void Http::Request::clear(void)
{
method = "GET";
version = "1.1";
url.clear();
headers.clear();
cookies.clear();
get.clear();
post.clear();
}
Http::Response::Response(void)
{
clear();
}
Http::Response::Response(const Request &request, int code)
{
clear();
this->code = code;
this->version = request.version;
this->sock = request.sock;
this->headers["Content-Type"] = "text/html; charset=UTF-8";
}
void Http::Response::send(void)
{
send(*sock);
}
void Http::Response::send(Socket &sock)
{
this->sock = &sock;
if(version == "1.1" && code >= 200 && !headers.contains("Connexion"))
headers["Connection"] = "close";
if(!headers.contains("Date"))
{
// TODO
time_t rawtime;
time(&rawtime);
struct tm *timeinfo = localtime(&rawtime);
char buffer[256];
strftime(buffer, 256, "%a, %d %b %Y %H:%M:%S %Z", timeinfo);
headers["Date"] = buffer;
}
if(message.empty())
{
switch(code)
{
case 100: message = "Continue"; break;
case 200: message = "OK"; break;
case 204: message = "No content"; break;
case 206: message = "Partial Content"; break;
case 301: message = "Moved Permanently"; break;
case 302: message = "Found"; break;
case 303: message = "See Other"; break;
case 304: message = "Not Modified"; break;
case 305: message = "Use Proxy"; break;
case 307: message = "Temporary Redirect"; break;
case 400: message = "Bad Request"; break;
case 401: message = "Unauthorized"; break;
case 403: message = "Forbidden"; break;
case 404: message = "Not Found"; break;
case 405: message = "Method Not Allowed"; break;
case 406: message = "Not Acceptable"; break;
case 408: message = "Request Timeout"; break;
case 410: message = "Gone"; break;
case 413: message = "Request Entity Too Large"; break;
case 414: message = "Request-URI Too Long"; break;
case 416: message = "Requested Range Not Satisfiable"; break;
case 500: message = "Internal Server Error"; break;
case 501: message = "Not Implemented"; break;
case 502: message = "Bad Gateway"; break;
case 503: message = "Service Unavailable"; break;
case 504: message = "Gateway Timeout"; break;
case 505: message = "HTTP Version Not Supported"; break;
default:
if(code < 300) message = "OK";
else message = "Error";
break;
}
}
sock<<"HTTP/"<<version<<" "<<code<<" "<<message<<"\r\n";
for( StringMap::iterator it = headers.begin();
it != headers.end();
++it)
{
List<String> lines;
it->second.remove('\r');
it->second.explode(lines,'\n');
for( List<String>::iterator l = lines.begin();
l != lines.end();
++l)
{
sock<<it->first<<": "<<*l<<"\r\n";
}
}
sock<<"\r\n";
}
void Http::Response::recv(Socket &sock)
{
this->sock = &sock;
clear();
// Read first line
String line;
if(!sock.readLine(line)) throw IOException("Connection closed");
String protocol;
line.readString(protocol);
version = protocol.cut('/');
line.read(code);
message = line;
if(version.empty() || protocol != "HTTP")
throw Exception("Invalid HTTP response");
// Read headers
while(true)
{
String line;
AssertIO(sock.readLine(line));
if(line.empty()) break;
String value = line.cut(':');
line.trim();
value.trim();
headers.insert(line,value);
}
}
void Http::Response::clear(void)
{
code = 200;
version = "1.1";
message.clear();
version.clear();
}
Http::Server::Server(int port) :
mSock(port)
{
}
Http::Server::~Server(void)
{
mSock.close(); // useless
}
void Http::Server::run(void)
{
try {
while(true)
{
Socket *sock = new Socket;
mSock.accept(*sock);
Handler *client = new Handler(this, sock);
client->start(true); // client will destroy itself
}
}
catch(const NetException &e)
{
return;
}
}
Http::Server::Handler::Handler(Server *server, Socket *sock) :
mServer(server),
mSock(sock)
{
}
Http::Server::Handler::~Handler(void)
{
delete mSock; // deletion closes the socket
}
void Http::Server::Handler::run(void)
{
Request request;
try {
try {
request.recv(*mSock);
String expect;
if(request.headers.get("Expect",expect)
&& expect.toLower() == "100-continue")
{
mSock->write("HTTP/1.1 100 Continue\r\n\r\n");
}
mServer->process(request);
}
catch(const NetException &e)
{
Log("Http::Server::Handler", e.what());
}
catch(const Exception &e)
{
Log("Http::Server::Handler", String("Error: ") + e.what());
throw 500;
}
}
catch(int code)
{
Response response(request, code);
response.headers["Content-Type"] = "text/html; charset=UTF-8";
response.send();
if(request.method != "HEAD")
{
Html page(response.sock);
page.header(response.message);
page.open("h1");
page.text(String::number(response.code) + " - " + response.message);
page.close("h1");
page.footer();
}
}
}
int Http::Get(const String &url, Stream *output)
{
Request request(url,"GET");
String host;
if(!request.headers.get("Host",host))
throw Exception("Invalid URL");
String service(host.cut(':'));
if(service.empty()) service = "80";
Socket sock(Address(host, service));
request.send(sock);
Response response;
response.recv(sock);
if(response.code/100 == 3 && response.headers.contains("Location"))
{
sock.discard();
sock.close();
// TODO: relative location (even if not RFC-compliant)
return Get(response.headers["Location"], output);
}
if(output) sock.read(*output);
else sock.discard();
return response.code;
}
int Http::Post(const String &url, const StringMap &post, Stream *output)
{
Request request(url,"POST");
request.post = post;
String host;
if(!request.headers.get("Host",host))
throw Exception("Invalid URL");
String service(host.cut(':'));
if(service.empty()) service = "80";
Socket sock(Address(host, service));
request.send(sock);
Response response;
response.recv(sock);
if(response.code/100 == 3 && response.headers.contains("Location"))
{
sock.discard();
sock.close();
// Location MAY NOT be a relative URL
return Get(response.headers["Location"], output);
}
if(output) sock.read(*output);
else sock.discard();
return response.code;
}
}
<commit_msg>Requests now done in HTTP 1.0<commit_after>/*************************************************************************
* Copyright (C) 2011-2012 by Paul-Louis Ageneau *
* paul-louis (at) ageneau (dot) org *
* *
* This file is part of TeapotNet. *
* *
* TeapotNet is free software: you can redistribute it and/or modify *
* it under the terms of the GNU Affero General Public License as *
* published by the Free Software Foundation, either version 3 of *
* the License, or (at your option) any later version. *
* *
* TeapotNet is distributed in the hope that it will be useful, but *
* WITHOUT ANY WARRANTY; without even the implied warranty of *
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the *
* GNU Affero General Public License for more details. *
* *
* You should have received a copy of the GNU Affero General Public *
* License along with TeapotNet. *
* If not, see <http://www.gnu.org/licenses/>. *
*************************************************************************/
#include "http.h"
#include "exception.h"
#include "html.h"
namespace tpot
{
Http::Request::Request(void)
{
clear();
}
Http::Request::Request(const String &url, const String &method)
{
clear();
int p = url.find("://");
if(p == String::NotFound) this->url = url;
else {
String protocol(url.substr(0,p));
if(protocol != "http") throw Exception(String("Unknown protocol in URL: ")+protocol);
String host(url.substr(p+3));
this->url = String('/') + host.cut('/');
headers["Host"] = host;
}
if(!method.empty()) this->method = method;
this->headers["User-Agent"] = String(APPNAME) + '/' + APPVERSION;
}
void Http::Request::send(Socket &sock)
{
this->sock = &sock;
if(version == "1.1" && !headers.contains("Connexion"))
headers["Connection"] = "close";
//if(!headers.contains("Accept-Encoding"))
// headers["Accept-Encoding"] = "identity";
String completeUrl(url);
if(!get.empty())
{
if(completeUrl.find('?') == String::NotFound)
completeUrl+= '?';
for( StringMap::iterator it = get.begin();
it != get.end();
++it)
{
completeUrl<<'&'<<it->first.urlEncode()<<'='<<it->second.urlEncode();
}
}
String postData;
if(!post.empty())
{
for( StringMap::iterator it = post.begin();
it != post.end();
++it)
{
if(!postData.empty()) postData<<'&';
postData<<it->first.urlEncode()<<'='<<it->second.urlEncode();
}
headers["Content-Length"] = "";
headers["Content-Length"] << postData.size();
headers["Content-Type"] = "application/x-www-form-urlencoded";
}
String buf;
buf<<method<<" "<<completeUrl<<" HTTP/"<<version<<"\r\n";
for( StringMap::iterator it = headers.begin();
it != headers.end();
++it)
{
List<String> lines;
it->second.remove('\r');
it->second.explode(lines,'\n');
for( List<String>::iterator l = lines.begin();
l != lines.end();
++l)
{
buf<<it->first<<": "<<*l<<"\r\n";
}
}
for( StringMap::iterator it = cookies.begin();
it != cookies.end();
++it)
{
buf<<"Set-Cookie: "<< it->first<<'='<<it->second<<"\r\n";
}
buf<<"\r\n";
sock<<buf;
if(!postData.empty())
sock<<postData;
}
void Http::Request::recv(Socket &sock)
{
this->sock = &sock;
clear();
// Read first line
String line;
if(!sock.readLine(line)) throw IOException("Connection closed");
method.clear();
url.clear();
line.readString(method);
line.readString(url);
String protocol;
line.readString(protocol);
version = protocol.cut('/');
if(url.empty() || version.empty() || protocol != "HTTP")
throw 400;
if(method != "GET" && method != "POST" /*&& method != "HEAD"*/)
throw 405;
// Read headers
while(true)
{
String line;
AssertIO(sock.readLine(line));
if(line.empty()) break;
String value = line.cut(':');
line.trim();
value.trim();
headers.insert(line,value);
}
// Read cookies
String cookie;
if(headers.get("Cookie",cookie))
{
while(!cookie.empty())
{
String next = cookie.cut(';');
String value = cookie.cut('=');
cookie.trim();
value.trim();
cookies.insert(cookie,value);
cookie = next;
}
}
// Read URL variables
String getData = url.cut('?');
if(!getData.empty())
{
List<String> exploded;
getData.explode(exploded,'&');
for( List<String>::iterator it = exploded.begin();
it != exploded.end();
++it)
{
String value = it->cut('=').urlDecode();
get.insert(it->urlDecode(), value);
}
}
// Read post variables
if(method == "POST")
{
if(!headers.contains("Content-Length"))
throw Exception("Missing Content-Length header in POST request");
size_t size = 0;
String contentLength(headers["Content-Length"]);
contentLength >> size;
String data;
if(sock.read(data, size) != size)
throw IOException("Connection unexpectedly closed");
if(headers.contains("Content-Type"))
{
String type = headers["Content-Type"];
String parameters = type.cut(';');
type.trim();
if(type == "application/x-www-form-urlencoded")
{
List<String> exploded;
data.explode(exploded,'&');
for( List<String>::iterator it = exploded.begin();
it != exploded.end();
++it)
{
String value = it->cut('=').urlDecode();
post.insert(it->urlDecode(), value);
}
}
}
}
}
void Http::Request::clear(void)
{
method = "GET";
version = "1.0";
url.clear();
headers.clear();
cookies.clear();
get.clear();
post.clear();
}
Http::Response::Response(void)
{
clear();
}
Http::Response::Response(const Request &request, int code)
{
clear();
this->code = code;
this->version = request.version;
this->sock = request.sock;
this->headers["Content-Type"] = "text/html; charset=UTF-8";
}
void Http::Response::send(void)
{
send(*sock);
}
void Http::Response::send(Socket &sock)
{
this->sock = &sock;
if(version == "1.1" && code >= 200 && !headers.contains("Connexion"))
headers["Connection"] = "close";
if(!headers.contains("Date"))
{
// TODO
time_t rawtime;
time(&rawtime);
struct tm *timeinfo = localtime(&rawtime);
char buffer[256];
strftime(buffer, 256, "%a, %d %b %Y %H:%M:%S %Z", timeinfo);
headers["Date"] = buffer;
}
if(message.empty())
{
switch(code)
{
case 100: message = "Continue"; break;
case 200: message = "OK"; break;
case 204: message = "No content"; break;
case 206: message = "Partial Content"; break;
case 301: message = "Moved Permanently"; break;
case 302: message = "Found"; break;
case 303: message = "See Other"; break;
case 304: message = "Not Modified"; break;
case 305: message = "Use Proxy"; break;
case 307: message = "Temporary Redirect"; break;
case 400: message = "Bad Request"; break;
case 401: message = "Unauthorized"; break;
case 403: message = "Forbidden"; break;
case 404: message = "Not Found"; break;
case 405: message = "Method Not Allowed"; break;
case 406: message = "Not Acceptable"; break;
case 408: message = "Request Timeout"; break;
case 410: message = "Gone"; break;
case 413: message = "Request Entity Too Large"; break;
case 414: message = "Request-URI Too Long"; break;
case 416: message = "Requested Range Not Satisfiable"; break;
case 500: message = "Internal Server Error"; break;
case 501: message = "Not Implemented"; break;
case 502: message = "Bad Gateway"; break;
case 503: message = "Service Unavailable"; break;
case 504: message = "Gateway Timeout"; break;
case 505: message = "HTTP Version Not Supported"; break;
default:
if(code < 300) message = "OK";
else message = "Error";
break;
}
}
sock<<"HTTP/"<<version<<" "<<code<<" "<<message<<"\r\n";
for( StringMap::iterator it = headers.begin();
it != headers.end();
++it)
{
List<String> lines;
it->second.remove('\r');
it->second.explode(lines,'\n');
for( List<String>::iterator l = lines.begin();
l != lines.end();
++l)
{
sock<<it->first<<": "<<*l<<"\r\n";
}
}
sock<<"\r\n";
}
void Http::Response::recv(Socket &sock)
{
this->sock = &sock;
clear();
// Read first line
String line;
if(!sock.readLine(line)) throw IOException("Connection closed");
String protocol;
line.readString(protocol);
version = protocol.cut('/');
line.read(code);
message = line;
if(version.empty() || protocol != "HTTP")
throw Exception("Invalid HTTP response");
// Read headers
while(true)
{
String line;
AssertIO(sock.readLine(line));
if(line.empty()) break;
String value = line.cut(':');
line.trim();
value.trim();
headers.insert(line,value);
}
}
void Http::Response::clear(void)
{
code = 200;
version = "1.0";
message.clear();
version.clear();
}
Http::Server::Server(int port) :
mSock(port)
{
}
Http::Server::~Server(void)
{
mSock.close(); // useless
}
void Http::Server::run(void)
{
try {
while(true)
{
Socket *sock = new Socket;
mSock.accept(*sock);
Handler *client = new Handler(this, sock);
client->start(true); // client will destroy itself
}
}
catch(const NetException &e)
{
return;
}
}
Http::Server::Handler::Handler(Server *server, Socket *sock) :
mServer(server),
mSock(sock)
{
}
Http::Server::Handler::~Handler(void)
{
delete mSock; // deletion closes the socket
}
void Http::Server::Handler::run(void)
{
Request request;
try {
try {
request.recv(*mSock);
String expect;
if(request.headers.get("Expect",expect)
&& expect.toLower() == "100-continue")
{
mSock->write("HTTP/1.1 100 Continue\r\n\r\n");
}
mServer->process(request);
}
catch(const NetException &e)
{
Log("Http::Server::Handler", e.what());
}
catch(const Exception &e)
{
Log("Http::Server::Handler", String("Error: ") + e.what());
throw 500;
}
}
catch(int code)
{
Response response(request, code);
response.headers["Content-Type"] = "text/html; charset=UTF-8";
response.send();
if(request.method != "HEAD")
{
Html page(response.sock);
page.header(response.message);
page.open("h1");
page.text(String::number(response.code) + " - " + response.message);
page.close("h1");
page.footer();
}
}
}
int Http::Get(const String &url, Stream *output)
{
Request request(url,"GET");
String host;
if(!request.headers.get("Host",host))
throw Exception("Invalid URL");
String service(host.cut(':'));
if(service.empty()) service = "80";
Socket sock(Address(host, service));
request.send(sock);
Response response;
response.recv(sock);
if(response.code/100 == 3 && response.headers.contains("Location"))
{
sock.discard();
sock.close();
// TODO: relative location (even if not RFC-compliant)
return Get(response.headers["Location"], output);
}
if(output) sock.read(*output);
else sock.discard();
return response.code;
}
int Http::Post(const String &url, const StringMap &post, Stream *output)
{
Request request(url,"POST");
request.post = post;
String host;
if(!request.headers.get("Host",host))
throw Exception("Invalid URL");
String service(host.cut(':'));
if(service.empty()) service = "80";
Socket sock(Address(host, service));
request.send(sock);
Response response;
response.recv(sock);
if(response.code/100 == 3 && response.headers.contains("Location"))
{
sock.discard();
sock.close();
// Location MAY NOT be a relative URL
return Get(response.headers["Location"], output);
}
if(output) sock.read(*output);
else sock.discard();
return response.code;
}
}
<|endoftext|> |
<commit_before>/*
*
* Copyright 2015, 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 <memory>
#include "server.h"
#include <node.h>
#include <nan.h>
#include <vector>
#include "grpc/grpc.h"
#include "grpc/grpc_security.h"
#include "grpc/support/log.h"
#include "call.h"
#include "completion_queue_async_worker.h"
#include "server_credentials.h"
#include "timeval.h"
namespace grpc {
namespace node {
using std::unique_ptr;
using v8::Array;
using v8::Boolean;
using v8::Date;
using v8::Exception;
using v8::Function;
using v8::FunctionTemplate;
using v8::Handle;
using v8::HandleScope;
using v8::Local;
using v8::Number;
using v8::Object;
using v8::Persistent;
using v8::String;
using v8::Value;
NanCallback *Server::constructor;
Persistent<FunctionTemplate> Server::fun_tpl;
class NewCallOp : public Op {
public:
NewCallOp() {
call = NULL;
grpc_call_details_init(&details);
grpc_metadata_array_init(&request_metadata);
}
~NewCallOp() {
grpc_call_details_destroy(&details);
grpc_metadata_array_destroy(&request_metadata);
}
Handle<Value> GetNodeValue() const {
NanEscapableScope();
if (call == NULL) {
return NanEscapeScope(NanNull());
}
Handle<Object> obj = NanNew<Object>();
obj->Set(NanNew("call"), Call::WrapStruct(call));
obj->Set(NanNew("method"), NanNew(details.method));
obj->Set(NanNew("host"), NanNew(details.host));
obj->Set(NanNew("deadline"),
NanNew<Date>(TimespecToMilliseconds(details.deadline)));
obj->Set(NanNew("metadata"), ParseMetadata(&request_metadata));
return NanEscapeScope(obj);
}
bool ParseOp(Handle<Value> value, grpc_op *out,
shared_ptr<Resources> resources) {
return true;
}
grpc_call *call;
grpc_call_details details;
grpc_metadata_array request_metadata;
protected:
std::string GetTypeString() const {
return "new_call";
}
};
Server::Server(grpc_server *server) : wrapped_server(server) {
shutdown_queue = grpc_completion_queue_create();
grpc_server_register_completion_queue(server, shutdown_queue);
}
Server::~Server() {
this->ShutdownServer();
grpc_completion_queue_shutdown(this->shutdown_queue);
grpc_server_destroy(wrapped_server);
grpc_completion_queue_destroy(this->shutdown_queue);
}
void Server::Init(Handle<Object> exports) {
NanScope();
Local<FunctionTemplate> tpl = NanNew<FunctionTemplate>(New);
tpl->SetClassName(NanNew("Server"));
tpl->InstanceTemplate()->SetInternalFieldCount(1);
NanSetPrototypeTemplate(tpl, "requestCall",
NanNew<FunctionTemplate>(RequestCall)->GetFunction());
NanSetPrototypeTemplate(
tpl, "addHttp2Port",
NanNew<FunctionTemplate>(AddHttp2Port)->GetFunction());
NanSetPrototypeTemplate(tpl, "start",
NanNew<FunctionTemplate>(Start)->GetFunction());
NanSetPrototypeTemplate(tpl, "shutdown",
NanNew<FunctionTemplate>(Shutdown)->GetFunction());
NanAssignPersistent(fun_tpl, tpl);
Handle<Function> ctr = tpl->GetFunction();
constructor = new NanCallback(ctr);
exports->Set(NanNew("Server"), ctr);
}
bool Server::HasInstance(Handle<Value> val) {
return NanHasInstance(fun_tpl, val);
}
void Server::ShutdownServer() {
if (this->wrapped_server != NULL) {
grpc_server_shutdown_and_notify(this->wrapped_server,
this->shutdown_queue,
NULL);
grpc_completion_queue_pluck(this->shutdown_queue, NULL,
gpr_inf_future(GPR_CLOCK_REALTIME));
this->wrapped_server = NULL;
}
}
NAN_METHOD(Server::New) {
NanScope();
/* If this is not a constructor call, make a constructor call and return
the result */
if (!args.IsConstructCall()) {
const int argc = 1;
Local<Value> argv[argc] = {args[0]};
NanReturnValue(constructor->GetFunction()->NewInstance(argc, argv));
}
grpc_server *wrapped_server;
grpc_completion_queue *queue = CompletionQueueAsyncWorker::GetQueue();
if (args[0]->IsUndefined()) {
wrapped_server = grpc_server_create(NULL);
} else if (args[0]->IsObject()) {
Handle<Object> args_hash(args[0]->ToObject());
Handle<Array> keys(args_hash->GetOwnPropertyNames());
grpc_channel_args channel_args;
channel_args.num_args = keys->Length();
channel_args.args = reinterpret_cast<grpc_arg *>(
calloc(channel_args.num_args, sizeof(grpc_arg)));
/* These are used to keep all strings until then end of the block, then
destroy them */
std::vector<NanUtf8String *> key_strings(keys->Length());
std::vector<NanUtf8String *> value_strings(keys->Length());
for (unsigned int i = 0; i < channel_args.num_args; i++) {
Handle<String> current_key(keys->Get(i)->ToString());
Handle<Value> current_value(args_hash->Get(current_key));
key_strings[i] = new NanUtf8String(current_key);
channel_args.args[i].key = **key_strings[i];
if (current_value->IsInt32()) {
channel_args.args[i].type = GRPC_ARG_INTEGER;
channel_args.args[i].value.integer = current_value->Int32Value();
} else if (current_value->IsString()) {
channel_args.args[i].type = GRPC_ARG_STRING;
value_strings[i] = new NanUtf8String(current_value);
channel_args.args[i].value.string = **value_strings[i];
} else {
free(channel_args.args);
return NanThrowTypeError("Arg values must be strings");
}
}
wrapped_server = grpc_server_create(&channel_args);
free(channel_args.args);
} else {
return NanThrowTypeError("Server expects an object");
}
grpc_server_register_completion_queue(wrapped_server, queue);
Server *server = new Server(wrapped_server);
server->Wrap(args.This());
NanReturnValue(args.This());
}
NAN_METHOD(Server::RequestCall) {
NanScope();
if (!HasInstance(args.This())) {
return NanThrowTypeError("requestCall can only be called on a Server");
}
Server *server = ObjectWrap::Unwrap<Server>(args.This());
if (server->wrapped_server == NULL) {
return NanThrowError("requestCall cannot be called on a shut down Server");
}
NewCallOp *op = new NewCallOp();
unique_ptr<OpVec> ops(new OpVec());
ops->push_back(unique_ptr<Op>(op));
grpc_call_error error = grpc_server_request_call(
server->wrapped_server, &op->call, &op->details, &op->request_metadata,
CompletionQueueAsyncWorker::GetQueue(),
CompletionQueueAsyncWorker::GetQueue(),
new struct tag(new NanCallback(args[0].As<Function>()), ops.release(),
shared_ptr<Resources>(nullptr)));
if (error != GRPC_CALL_OK) {
return NanThrowError("requestCall failed", error);
}
CompletionQueueAsyncWorker::Next();
NanReturnUndefined();
}
NAN_METHOD(Server::AddHttp2Port) {
NanScope();
if (!HasInstance(args.This())) {
return NanThrowTypeError(
"addHttp2Port can only be called on a Server");
}
if (!args[0]->IsString()) {
return NanThrowTypeError(
"addHttp2Port's first argument must be a String");
}
if (!ServerCredentials::HasInstance(args[1])) {
return NanThrowTypeError(
"addHttp2Port's second argument must be ServerCredentials");
}
Server *server = ObjectWrap::Unwrap<Server>(args.This());
if (server->wrapped_server == NULL) {
return NanThrowError(
"addHttp2Port cannot be called on a shut down Server");
}
ServerCredentials *creds_object = ObjectWrap::Unwrap<ServerCredentials>(
args[1]->ToObject());
grpc_server_credentials *creds = creds_object->GetWrappedServerCredentials();
int port;
if (creds == NULL) {
port = grpc_server_add_http2_port(server->wrapped_server,
*NanUtf8String(args[0]));
} else {
port = grpc_server_add_secure_http2_port(server->wrapped_server,
*NanUtf8String(args[0]),
creds);
}
NanReturnValue(NanNew<Number>(port));
}
NAN_METHOD(Server::Start) {
NanScope();
if (!HasInstance(args.This())) {
return NanThrowTypeError("start can only be called on a Server");
}
Server *server = ObjectWrap::Unwrap<Server>(args.This());
if (server->wrapped_server == NULL) {
return NanThrowError("start cannot be called on a shut down Server");
}
grpc_server_start(server->wrapped_server);
NanReturnUndefined();
}
NAN_METHOD(ShutdownCallback) {
NanReturnUndefined();
}
NAN_METHOD(Server::Shutdown) {
NanScope();
if (!HasInstance(args.This())) {
return NanThrowTypeError("shutdown can only be called on a Server");
}
Server *server = ObjectWrap::Unwrap<Server>(args.This());
server->ShutdownServer();
NanReturnUndefined();
}
} // namespace node
} // namespace grpc
<commit_msg>Rename grpc_server_add_http2_port to grpc_server_add_insecure_http2_port<commit_after>/*
*
* Copyright 2015, 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 <memory>
#include "server.h"
#include <node.h>
#include <nan.h>
#include <vector>
#include "grpc/grpc.h"
#include "grpc/grpc_security.h"
#include "grpc/support/log.h"
#include "call.h"
#include "completion_queue_async_worker.h"
#include "server_credentials.h"
#include "timeval.h"
namespace grpc {
namespace node {
using std::unique_ptr;
using v8::Array;
using v8::Boolean;
using v8::Date;
using v8::Exception;
using v8::Function;
using v8::FunctionTemplate;
using v8::Handle;
using v8::HandleScope;
using v8::Local;
using v8::Number;
using v8::Object;
using v8::Persistent;
using v8::String;
using v8::Value;
NanCallback *Server::constructor;
Persistent<FunctionTemplate> Server::fun_tpl;
class NewCallOp : public Op {
public:
NewCallOp() {
call = NULL;
grpc_call_details_init(&details);
grpc_metadata_array_init(&request_metadata);
}
~NewCallOp() {
grpc_call_details_destroy(&details);
grpc_metadata_array_destroy(&request_metadata);
}
Handle<Value> GetNodeValue() const {
NanEscapableScope();
if (call == NULL) {
return NanEscapeScope(NanNull());
}
Handle<Object> obj = NanNew<Object>();
obj->Set(NanNew("call"), Call::WrapStruct(call));
obj->Set(NanNew("method"), NanNew(details.method));
obj->Set(NanNew("host"), NanNew(details.host));
obj->Set(NanNew("deadline"),
NanNew<Date>(TimespecToMilliseconds(details.deadline)));
obj->Set(NanNew("metadata"), ParseMetadata(&request_metadata));
return NanEscapeScope(obj);
}
bool ParseOp(Handle<Value> value, grpc_op *out,
shared_ptr<Resources> resources) {
return true;
}
grpc_call *call;
grpc_call_details details;
grpc_metadata_array request_metadata;
protected:
std::string GetTypeString() const {
return "new_call";
}
};
Server::Server(grpc_server *server) : wrapped_server(server) {
shutdown_queue = grpc_completion_queue_create();
grpc_server_register_completion_queue(server, shutdown_queue);
}
Server::~Server() {
this->ShutdownServer();
grpc_completion_queue_shutdown(this->shutdown_queue);
grpc_server_destroy(wrapped_server);
grpc_completion_queue_destroy(this->shutdown_queue);
}
void Server::Init(Handle<Object> exports) {
NanScope();
Local<FunctionTemplate> tpl = NanNew<FunctionTemplate>(New);
tpl->SetClassName(NanNew("Server"));
tpl->InstanceTemplate()->SetInternalFieldCount(1);
NanSetPrototypeTemplate(tpl, "requestCall",
NanNew<FunctionTemplate>(RequestCall)->GetFunction());
NanSetPrototypeTemplate(
tpl, "addHttp2Port",
NanNew<FunctionTemplate>(AddHttp2Port)->GetFunction());
NanSetPrototypeTemplate(tpl, "start",
NanNew<FunctionTemplate>(Start)->GetFunction());
NanSetPrototypeTemplate(tpl, "shutdown",
NanNew<FunctionTemplate>(Shutdown)->GetFunction());
NanAssignPersistent(fun_tpl, tpl);
Handle<Function> ctr = tpl->GetFunction();
constructor = new NanCallback(ctr);
exports->Set(NanNew("Server"), ctr);
}
bool Server::HasInstance(Handle<Value> val) {
return NanHasInstance(fun_tpl, val);
}
void Server::ShutdownServer() {
if (this->wrapped_server != NULL) {
grpc_server_shutdown_and_notify(this->wrapped_server,
this->shutdown_queue,
NULL);
grpc_completion_queue_pluck(this->shutdown_queue, NULL,
gpr_inf_future(GPR_CLOCK_REALTIME));
this->wrapped_server = NULL;
}
}
NAN_METHOD(Server::New) {
NanScope();
/* If this is not a constructor call, make a constructor call and return
the result */
if (!args.IsConstructCall()) {
const int argc = 1;
Local<Value> argv[argc] = {args[0]};
NanReturnValue(constructor->GetFunction()->NewInstance(argc, argv));
}
grpc_server *wrapped_server;
grpc_completion_queue *queue = CompletionQueueAsyncWorker::GetQueue();
if (args[0]->IsUndefined()) {
wrapped_server = grpc_server_create(NULL);
} else if (args[0]->IsObject()) {
Handle<Object> args_hash(args[0]->ToObject());
Handle<Array> keys(args_hash->GetOwnPropertyNames());
grpc_channel_args channel_args;
channel_args.num_args = keys->Length();
channel_args.args = reinterpret_cast<grpc_arg *>(
calloc(channel_args.num_args, sizeof(grpc_arg)));
/* These are used to keep all strings until then end of the block, then
destroy them */
std::vector<NanUtf8String *> key_strings(keys->Length());
std::vector<NanUtf8String *> value_strings(keys->Length());
for (unsigned int i = 0; i < channel_args.num_args; i++) {
Handle<String> current_key(keys->Get(i)->ToString());
Handle<Value> current_value(args_hash->Get(current_key));
key_strings[i] = new NanUtf8String(current_key);
channel_args.args[i].key = **key_strings[i];
if (current_value->IsInt32()) {
channel_args.args[i].type = GRPC_ARG_INTEGER;
channel_args.args[i].value.integer = current_value->Int32Value();
} else if (current_value->IsString()) {
channel_args.args[i].type = GRPC_ARG_STRING;
value_strings[i] = new NanUtf8String(current_value);
channel_args.args[i].value.string = **value_strings[i];
} else {
free(channel_args.args);
return NanThrowTypeError("Arg values must be strings");
}
}
wrapped_server = grpc_server_create(&channel_args);
free(channel_args.args);
} else {
return NanThrowTypeError("Server expects an object");
}
grpc_server_register_completion_queue(wrapped_server, queue);
Server *server = new Server(wrapped_server);
server->Wrap(args.This());
NanReturnValue(args.This());
}
NAN_METHOD(Server::RequestCall) {
NanScope();
if (!HasInstance(args.This())) {
return NanThrowTypeError("requestCall can only be called on a Server");
}
Server *server = ObjectWrap::Unwrap<Server>(args.This());
if (server->wrapped_server == NULL) {
return NanThrowError("requestCall cannot be called on a shut down Server");
}
NewCallOp *op = new NewCallOp();
unique_ptr<OpVec> ops(new OpVec());
ops->push_back(unique_ptr<Op>(op));
grpc_call_error error = grpc_server_request_call(
server->wrapped_server, &op->call, &op->details, &op->request_metadata,
CompletionQueueAsyncWorker::GetQueue(),
CompletionQueueAsyncWorker::GetQueue(),
new struct tag(new NanCallback(args[0].As<Function>()), ops.release(),
shared_ptr<Resources>(nullptr)));
if (error != GRPC_CALL_OK) {
return NanThrowError("requestCall failed", error);
}
CompletionQueueAsyncWorker::Next();
NanReturnUndefined();
}
NAN_METHOD(Server::AddHttp2Port) {
NanScope();
if (!HasInstance(args.This())) {
return NanThrowTypeError(
"addHttp2Port can only be called on a Server");
}
if (!args[0]->IsString()) {
return NanThrowTypeError(
"addHttp2Port's first argument must be a String");
}
if (!ServerCredentials::HasInstance(args[1])) {
return NanThrowTypeError(
"addHttp2Port's second argument must be ServerCredentials");
}
Server *server = ObjectWrap::Unwrap<Server>(args.This());
if (server->wrapped_server == NULL) {
return NanThrowError(
"addHttp2Port cannot be called on a shut down Server");
}
ServerCredentials *creds_object = ObjectWrap::Unwrap<ServerCredentials>(
args[1]->ToObject());
grpc_server_credentials *creds = creds_object->GetWrappedServerCredentials();
int port;
if (creds == NULL) {
port = grpc_server_add_insecure_http2_port(server->wrapped_server,
*NanUtf8String(args[0]));
} else {
port = grpc_server_add_secure_http2_port(server->wrapped_server,
*NanUtf8String(args[0]),
creds);
}
NanReturnValue(NanNew<Number>(port));
}
NAN_METHOD(Server::Start) {
NanScope();
if (!HasInstance(args.This())) {
return NanThrowTypeError("start can only be called on a Server");
}
Server *server = ObjectWrap::Unwrap<Server>(args.This());
if (server->wrapped_server == NULL) {
return NanThrowError("start cannot be called on a shut down Server");
}
grpc_server_start(server->wrapped_server);
NanReturnUndefined();
}
NAN_METHOD(ShutdownCallback) {
NanReturnUndefined();
}
NAN_METHOD(Server::Shutdown) {
NanScope();
if (!HasInstance(args.This())) {
return NanThrowTypeError("shutdown can only be called on a Server");
}
Server *server = ObjectWrap::Unwrap<Server>(args.This());
server->ShutdownServer();
NanReturnUndefined();
}
} // namespace node
} // namespace grpc
<|endoftext|> |
<commit_before>/*************************************************************************
*
* $RCSfile: doclinkdialog.cxx,v $
*
* $Revision: 1.2 $
*
* last change: $Author: hr $ $Date: 2004-08-02 16:38:40 $
*
* 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 EXPRESS OR IMPLIED, INCLUDING,
* WITHOUT LIMITATION, WARRANTIES THAT THE SOFTWARE IS FREE OF DEFECTS,
* MERCHANTABLE, FIT FOR A PARTICULAR PURPOSE, OR NON-INFRINGING.
* See the License for the specific provisions governing your rights and
* obligations concerning the Software.
*
* The Initial Developer of the Original Code is: Sun Microsystems, Inc..
*
* Copyright: 2000 by Sun Microsystems, Inc.
*
* All Rights Reserved.
*
* Contributor(s): _______________________________________
*
*
************************************************************************/
#ifndef _SVX_DOCLINKDIALOG_HXX_
#include "doclinkdialog.hxx"
#endif
#ifndef _SVX_DOCLINKDIALOG_HRC_
#include "doclinkdialog.hrc"
#endif
#include "dialogs.hrc"
#include "svxids.hrc"
#ifndef _TOOLS_DEBUG_HXX
#include <tools/debug.hxx>
#endif
#ifndef SVTOOLS_FILENOTATION_HXX_
#include <svtools/filenotation.hxx>
#endif
#ifndef _SV_MSGBOX_HXX
#include <vcl/msgbox.hxx>
#endif
#ifndef _UCBHELPER_CONTENT_HXX
#include <ucbhelper/content.hxx>
#endif
#include "dialmgr.hxx"
#ifndef _URLOBJ_HXX
#include <tools/urlobj.hxx>
#endif
#ifndef _FILEDLGHELPER_HXX
#include <sfx2/filedlghelper.hxx>
#endif
#ifndef _SFX_DOCFILT_HACK_HXX
#include <sfx2/docfilt.hxx>
#endif
//......................................................................
namespace svx
{
//......................................................................
using namespace ::com::sun::star::uno;
using namespace ::com::sun::star::ucb;
using namespace ::svt;
//==================================================================
//= ODocumentLinkDialog
//==================================================================
//------------------------------------------------------------------
ODocumentLinkDialog::ODocumentLinkDialog( Window* _pParent, sal_Bool _bCreateNew )
:ModalDialog( _pParent, SVX_RES(DLG_DOCUMENTLINK) )
,m_aNameLabel (this, ResId(FT_NAME))
,m_aName (this, ResId(ET_NAME))
,m_aURLLabel (this, ResId(FT_URL))
,m_aURL (this, ResId(CMB_URL))
,m_aBrowseFile (this, ResId(PB_BROWSEFILE))
,m_aBottomLine (this, ResId(FL_BOTTOM))
,m_aOK (this, ResId(BTN_OK))
,m_aCancel (this, ResId(BTN_CANCEL))
,m_aHelp (this, ResId(BTN_HELP))
,m_bCreatingNew(_bCreateNew)
{
String sText = String( ResId( m_bCreatingNew ? STR_NEW_LINK : STR_EDIT_LINK ) );
SetText(sText);
FreeResource();
String sTemp = String::CreateFromAscii("*.odb");
m_aURL.SetFilter(sTemp);
m_aName.SetModifyHdl( LINK(this, ODocumentLinkDialog, OnTextModified) );
m_aURL.SetModifyHdl( LINK(this, ODocumentLinkDialog, OnTextModified) );
m_aBrowseFile.SetClickHdl( LINK(this, ODocumentLinkDialog, OnBrowseFile) );
m_aOK.SetClickHdl( LINK(this, ODocumentLinkDialog, OnOk) );
m_aURL.SetDropDownLineCount(10);
validate();
// m_aURL.SetHelpId( HID_DOCLINKEDIT_URL );
m_aURL.SetDropDownLineCount( 5 );
}
//------------------------------------------------------------------
void ODocumentLinkDialog::set( const String& _rName, const String& _rURL )
{
m_aName.SetText(_rName);
m_aURL.SetText(_rURL);
validate();
}
//------------------------------------------------------------------
void ODocumentLinkDialog::get( String& _rName, String& _rURL ) const
{
_rName = m_aName.GetText();
_rURL = m_aURL.GetText();
}
//------------------------------------------------------------------
void ODocumentLinkDialog::validate( )
{
m_aOK.Enable( (0 != m_aName.GetText().Len()) && ( 0 != m_aURL.GetText().Len() ) );
}
//------------------------------------------------------------------
IMPL_LINK( ODocumentLinkDialog, OnOk, void*, NOINTERESTEDIN )
{
// get the current URL
::rtl::OUString sURL = m_aURL.GetText();
OFileNotation aTransformer(sURL, OFileNotation::N_DETECT);
sURL = aTransformer.get(OFileNotation::N_URL);
// check for the existence of the selected file
sal_Bool bFileExists = sal_False;
try
{
::ucb::Content aFile(sURL, Reference< XCommandEnvironment >());
if (aFile.isDocument())
bFileExists = sal_True;
}
catch(Exception&)
{
}
if (!bFileExists)
{
String sMsg = String(SVX_RES(STR_LINKEDDOC_DOESNOTEXIST));
sMsg.SearchAndReplaceAscii("$file$", m_aURL.GetText());
ErrorBox aError(this, WB_OK , sMsg);
aError.Execute();
return 0L;
} // if (!bFileExists)
String sCurrentText = m_aName.GetText();
if ( m_aNameValidator.IsSet() )
{
if ( !m_aNameValidator.Call( &sCurrentText ) )
{
String sMsg = String(SVX_RES(STR_NAME_CONFLICT));
sMsg.SearchAndReplaceAscii("$file$", sCurrentText);
InfoBox aError(this, sMsg);
aError.Execute();
m_aName.SetSelection(Selection(0,sCurrentText.Len()));
m_aName.GrabFocus();
return 0L;
}
}
EndDialog(RET_OK);
return 0L;
}
//------------------------------------------------------------------
IMPL_LINK( ODocumentLinkDialog, OnBrowseFile, void*, NOINTERESTEDIN )
{
::sfx2::FileDialogHelper aFileDlg(WB_3DLOOK | WB_STDMODAL | WB_OPEN);
static const String s_sDatabaseType = String::CreateFromAscii("StarOffice XML (Base)");
const SfxFilter* pFilter = SfxFilter::GetFilterByName( s_sDatabaseType);
if ( pFilter )
{
aFileDlg.AddFilter(pFilter->GetFilterName(),pFilter->GetDefaultExtension());
aFileDlg.SetCurrentFilter(pFilter->GetFilterName());
}
String sPath = m_aURL.GetText();
if (sPath.Len())
{
OFileNotation aTransformer( sPath, OFileNotation::N_SYSTEM );
aFileDlg.SetDisplayDirectory( aTransformer.get( OFileNotation::N_URL ) );
}
if (0 != aFileDlg.Execute())
return 0L;
if (0 == m_aName.GetText().Len())
{ // default the name to the base of the chosen URL
INetURLObject aParser;
aParser.SetSmartProtocol(INET_PROT_FILE);
aParser.SetSmartURL(aFileDlg.GetPath());
m_aName.SetText(aParser.getBase(INetURLObject::LAST_SEGMENT, true, INetURLObject::DECODE_WITH_CHARSET));
m_aName.SetSelection(Selection(0,m_aName.GetText().Len()));
m_aName.GrabFocus();
}
else
m_aURL.GrabFocus();
// get the path in system notation
OFileNotation aTransformer(aFileDlg.GetPath(), OFileNotation::N_URL);
m_aURL.SetText(aTransformer.get(OFileNotation::N_SYSTEM));
validate();
return 0L;
}
//------------------------------------------------------------------
IMPL_LINK( ODocumentLinkDialog, OnTextModified, Control*, _pWhich )
{
validate( );
return 0L;
}
//......................................................................
} // namespace svx
//......................................................................
<commit_msg>#i10000#: wrong ctor of OFileNotation used<commit_after>/*************************************************************************
*
* $RCSfile: doclinkdialog.cxx,v $
*
* $Revision: 1.3 $
*
* last change: $Author: hr $ $Date: 2004-08-04 12:04:14 $
*
* 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 EXPRESS OR IMPLIED, INCLUDING,
* WITHOUT LIMITATION, WARRANTIES THAT THE SOFTWARE IS FREE OF DEFECTS,
* MERCHANTABLE, FIT FOR A PARTICULAR PURPOSE, OR NON-INFRINGING.
* See the License for the specific provisions governing your rights and
* obligations concerning the Software.
*
* The Initial Developer of the Original Code is: Sun Microsystems, Inc..
*
* Copyright: 2000 by Sun Microsystems, Inc.
*
* All Rights Reserved.
*
* Contributor(s): _______________________________________
*
*
************************************************************************/
#ifndef _SVX_DOCLINKDIALOG_HXX_
#include "doclinkdialog.hxx"
#endif
#ifndef _SVX_DOCLINKDIALOG_HRC_
#include "doclinkdialog.hrc"
#endif
#include "dialogs.hrc"
#include "svxids.hrc"
#ifndef _TOOLS_DEBUG_HXX
#include <tools/debug.hxx>
#endif
#ifndef SVTOOLS_FILENOTATION_HXX_
#include <svtools/filenotation.hxx>
#endif
#ifndef _SV_MSGBOX_HXX
#include <vcl/msgbox.hxx>
#endif
#ifndef _UCBHELPER_CONTENT_HXX
#include <ucbhelper/content.hxx>
#endif
#include "dialmgr.hxx"
#ifndef _URLOBJ_HXX
#include <tools/urlobj.hxx>
#endif
#ifndef _FILEDLGHELPER_HXX
#include <sfx2/filedlghelper.hxx>
#endif
#ifndef _SFX_DOCFILT_HACK_HXX
#include <sfx2/docfilt.hxx>
#endif
//......................................................................
namespace svx
{
//......................................................................
using namespace ::com::sun::star::uno;
using namespace ::com::sun::star::ucb;
using namespace ::svt;
//==================================================================
//= ODocumentLinkDialog
//==================================================================
//------------------------------------------------------------------
ODocumentLinkDialog::ODocumentLinkDialog( Window* _pParent, sal_Bool _bCreateNew )
:ModalDialog( _pParent, SVX_RES(DLG_DOCUMENTLINK) )
,m_aNameLabel (this, ResId(FT_NAME))
,m_aName (this, ResId(ET_NAME))
,m_aURLLabel (this, ResId(FT_URL))
,m_aURL (this, ResId(CMB_URL))
,m_aBrowseFile (this, ResId(PB_BROWSEFILE))
,m_aBottomLine (this, ResId(FL_BOTTOM))
,m_aOK (this, ResId(BTN_OK))
,m_aCancel (this, ResId(BTN_CANCEL))
,m_aHelp (this, ResId(BTN_HELP))
,m_bCreatingNew(_bCreateNew)
{
String sText = String( ResId( m_bCreatingNew ? STR_NEW_LINK : STR_EDIT_LINK ) );
SetText(sText);
FreeResource();
String sTemp = String::CreateFromAscii("*.odb");
m_aURL.SetFilter(sTemp);
m_aName.SetModifyHdl( LINK(this, ODocumentLinkDialog, OnTextModified) );
m_aURL.SetModifyHdl( LINK(this, ODocumentLinkDialog, OnTextModified) );
m_aBrowseFile.SetClickHdl( LINK(this, ODocumentLinkDialog, OnBrowseFile) );
m_aOK.SetClickHdl( LINK(this, ODocumentLinkDialog, OnOk) );
m_aURL.SetDropDownLineCount(10);
validate();
// m_aURL.SetHelpId( HID_DOCLINKEDIT_URL );
m_aURL.SetDropDownLineCount( 5 );
}
//------------------------------------------------------------------
void ODocumentLinkDialog::set( const String& _rName, const String& _rURL )
{
m_aName.SetText(_rName);
m_aURL.SetText(_rURL);
validate();
}
//------------------------------------------------------------------
void ODocumentLinkDialog::get( String& _rName, String& _rURL ) const
{
_rName = m_aName.GetText();
_rURL = m_aURL.GetText();
}
//------------------------------------------------------------------
void ODocumentLinkDialog::validate( )
{
m_aOK.Enable( (0 != m_aName.GetText().Len()) && ( 0 != m_aURL.GetText().Len() ) );
}
//------------------------------------------------------------------
IMPL_LINK( ODocumentLinkDialog, OnOk, void*, NOINTERESTEDIN )
{
// get the current URL
::rtl::OUString sURL = m_aURL.GetText();
OFileNotation aTransformer(sURL);
sURL = aTransformer.get(OFileNotation::N_URL);
// check for the existence of the selected file
sal_Bool bFileExists = sal_False;
try
{
::ucb::Content aFile(sURL, Reference< XCommandEnvironment >());
if (aFile.isDocument())
bFileExists = sal_True;
}
catch(Exception&)
{
}
if (!bFileExists)
{
String sMsg = String(SVX_RES(STR_LINKEDDOC_DOESNOTEXIST));
sMsg.SearchAndReplaceAscii("$file$", m_aURL.GetText());
ErrorBox aError(this, WB_OK , sMsg);
aError.Execute();
return 0L;
} // if (!bFileExists)
String sCurrentText = m_aName.GetText();
if ( m_aNameValidator.IsSet() )
{
if ( !m_aNameValidator.Call( &sCurrentText ) )
{
String sMsg = String(SVX_RES(STR_NAME_CONFLICT));
sMsg.SearchAndReplaceAscii("$file$", sCurrentText);
InfoBox aError(this, sMsg);
aError.Execute();
m_aName.SetSelection(Selection(0,sCurrentText.Len()));
m_aName.GrabFocus();
return 0L;
}
}
EndDialog(RET_OK);
return 0L;
}
//------------------------------------------------------------------
IMPL_LINK( ODocumentLinkDialog, OnBrowseFile, void*, NOINTERESTEDIN )
{
::sfx2::FileDialogHelper aFileDlg(WB_3DLOOK | WB_STDMODAL | WB_OPEN);
static const String s_sDatabaseType = String::CreateFromAscii("StarOffice XML (Base)");
const SfxFilter* pFilter = SfxFilter::GetFilterByName( s_sDatabaseType);
if ( pFilter )
{
aFileDlg.AddFilter(pFilter->GetFilterName(),pFilter->GetDefaultExtension());
aFileDlg.SetCurrentFilter(pFilter->GetFilterName());
}
String sPath = m_aURL.GetText();
if (sPath.Len())
{
OFileNotation aTransformer( sPath, OFileNotation::N_SYSTEM );
aFileDlg.SetDisplayDirectory( aTransformer.get( OFileNotation::N_URL ) );
}
if (0 != aFileDlg.Execute())
return 0L;
if (0 == m_aName.GetText().Len())
{ // default the name to the base of the chosen URL
INetURLObject aParser;
aParser.SetSmartProtocol(INET_PROT_FILE);
aParser.SetSmartURL(aFileDlg.GetPath());
m_aName.SetText(aParser.getBase(INetURLObject::LAST_SEGMENT, true, INetURLObject::DECODE_WITH_CHARSET));
m_aName.SetSelection(Selection(0,m_aName.GetText().Len()));
m_aName.GrabFocus();
}
else
m_aURL.GrabFocus();
// get the path in system notation
OFileNotation aTransformer(aFileDlg.GetPath(), OFileNotation::N_URL);
m_aURL.SetText(aTransformer.get(OFileNotation::N_SYSTEM));
validate();
return 0L;
}
//------------------------------------------------------------------
IMPL_LINK( ODocumentLinkDialog, OnTextModified, Control*, _pWhich )
{
validate( );
return 0L;
}
//......................................................................
} // namespace svx
//......................................................................
<|endoftext|> |
<commit_before>/*************************************************************************
*
* OpenOffice.org - a multi-platform office productivity suite
*
* $RCSfile: charhiddenitem.cxx,v $
*
* $Revision: 1.3 $
*
* last change: $Author: rt $ $Date: 2005-09-08 23:32:57 $
*
* 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
*
************************************************************************/
#pragma hdrstop
#define ITEMID_CHARHIDDEN 0
#ifndef _SVX_CHARHIDDENITEM_HXX
#include <charhiddenitem.hxx>
#endif
#include "svxitems.hrc"
#include "dialmgr.hxx"
TYPEINIT1_AUTOFACTORY(SvxCharHiddenItem, SfxBoolItem);
/*-- 16.12.2003 15:24:25---------------------------------------------------
-----------------------------------------------------------------------*/
SvxCharHiddenItem::SvxCharHiddenItem( const sal_Bool bHidden, const USHORT nId ) :
SfxBoolItem( nId, bHidden )
{
}
/*-- 16.12.2003 15:24:25---------------------------------------------------
-----------------------------------------------------------------------*/
SfxPoolItem* SvxCharHiddenItem::Clone( SfxItemPool * ) const
{
return new SvxCharHiddenItem( *this );
}
/*-- 16.12.2003 15:24:25---------------------------------------------------
-----------------------------------------------------------------------*/
SfxItemPresentation SvxCharHiddenItem::GetPresentation
(
SfxItemPresentation ePres,
SfxMapUnit eCoreUnit,
SfxMapUnit ePresUnit,
XubString& rText, const IntlWrapper *pIntl
) const
{
switch ( ePres )
{
case SFX_ITEM_PRESENTATION_NONE:
rText.Erase();
return ePres;
case SFX_ITEM_PRESENTATION_NAMELESS:
case SFX_ITEM_PRESENTATION_COMPLETE:
{
USHORT nId = RID_SVXITEMS_CHARHIDDEN_FALSE;
if ( GetValue() )
nId = RID_SVXITEMS_CHARHIDDEN_TRUE;
rText = SVX_RESSTR(nId);
return ePres;
}
}
return SFX_ITEM_PRESENTATION_NONE;
}
<commit_msg>INTEGRATION: CWS warnings01 (1.3.220); FILE MERGED 2006/04/24 09:54:25 os 1.3.220.2: warnings removed 2006/04/20 14:49:53 cl 1.3.220.1: warning free code changes<commit_after>/*************************************************************************
*
* OpenOffice.org - a multi-platform office productivity suite
*
* $RCSfile: charhiddenitem.cxx,v $
*
* $Revision: 1.4 $
*
* last change: $Author: hr $ $Date: 2006-06-19 16:10:04 $
*
* The Contents of this file are made available subject to
* the terms of GNU Lesser General Public License Version 2.1.
*
*
* GNU Lesser General Public License Version 2.1
* =============================================
* Copyright 2005 by Sun Microsystems, Inc.
* 901 San Antonio Road, Palo Alto, CA 94303, USA
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License version 2.1, as published by the Free Software Foundation.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston,
* MA 02111-1307 USA
*
************************************************************************/
#define ITEMID_CHARHIDDEN 0
#ifndef _SVX_CHARHIDDENITEM_HXX
#include <charhiddenitem.hxx>
#endif
#include "svxitems.hrc"
#include "dialmgr.hxx"
TYPEINIT1_AUTOFACTORY(SvxCharHiddenItem, SfxBoolItem);
/*-- 16.12.2003 15:24:25---------------------------------------------------
-----------------------------------------------------------------------*/
SvxCharHiddenItem::SvxCharHiddenItem( const sal_Bool bHidden, const USHORT nId ) :
SfxBoolItem( nId, bHidden )
{
}
/*-- 16.12.2003 15:24:25---------------------------------------------------
-----------------------------------------------------------------------*/
SfxPoolItem* SvxCharHiddenItem::Clone( SfxItemPool * ) const
{
return new SvxCharHiddenItem( *this );
}
/*-- 16.12.2003 15:24:25---------------------------------------------------
-----------------------------------------------------------------------*/
SfxItemPresentation SvxCharHiddenItem::GetPresentation
(
SfxItemPresentation ePres,
SfxMapUnit /*eCoreUnit*/,
SfxMapUnit /*ePresUnit*/,
XubString& rText, const IntlWrapper */*pIntl*/
) const
{
switch ( ePres )
{
case SFX_ITEM_PRESENTATION_NONE:
rText.Erase();
return ePres;
case SFX_ITEM_PRESENTATION_NAMELESS:
case SFX_ITEM_PRESENTATION_COMPLETE:
{
USHORT nId = RID_SVXITEMS_CHARHIDDEN_FALSE;
if ( GetValue() )
nId = RID_SVXITEMS_CHARHIDDEN_TRUE;
rText = SVX_RESSTR(nId);
return ePres;
}
default: ; //prevent warning
}
return SFX_ITEM_PRESENTATION_NONE;
}
<|endoftext|> |
<commit_before>/*
* Copyright 2017-2018 Baidu 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 "openrasp_hook.h"
#include "openrasp_ini.h"
#include "openrasp_inject.h"
#include <new>
#include <vector>
#include <map>
extern "C" {
#include "ext/standard/php_fopen_wrappers.h"
}
static std::vector<hook_handler_t> global_hook_handlers;
void register_hook_handler(hook_handler_t hook_handler)
{
global_hook_handlers.push_back(hook_handler);
}
typedef struct _track_vars_pair_t
{
int id;
const char *name;
} track_vars_pair;
ZEND_DECLARE_MODULE_GLOBALS(openrasp_hook)
bool openrasp_zval_in_request(zval *item)
{
static const track_vars_pair pairs[] = {{TRACK_VARS_POST, "_POST"},
{TRACK_VARS_GET, "_GET"},
{TRACK_VARS_COOKIE, "_COOKIE"}};
int size = sizeof(pairs) / sizeof(pairs[0]);
for (int index = 0; index < size; ++index)
{
zval *global = &PG(http_globals)[pairs[index].id];
if (Z_TYPE_P(global) != IS_ARRAY &&
!zend_is_auto_global_str(const_cast<char *>(pairs[index].name), strlen(pairs[index].name)))
{
return false;
}
zval *val;
ZEND_HASH_FOREACH_VAL(Z_ARRVAL_P(global), val)
{
if (Z_COUNTED_P(item) == Z_COUNTED_P(val))
{
return true;
}
}
ZEND_HASH_FOREACH_END();
}
return false;
}
void openrasp_buildin_php_risk_handle(zend_bool is_block, const char *type, int confidence, zval *params, zval *message)
{
zval params_result;
array_init(¶ms_result);
add_assoc_long(¶ms_result, "plugin_confidence", confidence);
add_assoc_zval(¶ms_result, "attack_params", params);
add_assoc_string(¶ms_result, "attack_type", const_cast<char *>(type));
add_assoc_zval(¶ms_result, "plugin_message", message);
add_assoc_string(¶ms_result, "intercept_state", const_cast<char *>(is_block ? "block" : "log"));
add_assoc_string(¶ms_result, "plugin_name", const_cast<char *>("php_builtin_plugin"));
alarm_info(¶ms_result);
zval_ptr_dtor(¶ms_result);
if (is_block)
{
handle_block();
}
}
bool openrasp_check_type_ignored(const char *item_name, uint item_name_length)
{
return openrasp_ini.hooks_ignore.find(item_name) != openrasp_ini.hooks_ignore.end();
}
bool openrasp_check_callable_black(const char *item_name, uint item_name_length)
{
return openrasp_ini.callable_blacklists.find(item_name) != openrasp_ini.callable_blacklists.end();
}
struct scheme_cmp {
bool operator() (const std::string& lhs, const std::string& rhs) const {
return strcasecmp(lhs.c_str(), rhs.c_str()) < 0;
}
};
zend_string *openrasp_real_path(char *filename, int length, bool use_include_path, wrapper_operation w_op)
{
static const std::map<std::string, int, scheme_cmp> opMap =
{
{"http", READING},
{"https", READING},
{"ftp", READING | WRITING | APPENDING},
{"ftps", READING | WRITING | APPENDING},
{"php", READING | WRITING | APPENDING | SIMULTANEOUSRW},
{"zlib", READING | WRITING | APPENDING},
{"bzip2", READING | WRITING | APPENDING},
{"zlib", READING},
{"data", READING},
{"phar", READING | WRITING | SIMULTANEOUSRW},
{"ssh2", READING | WRITING | SIMULTANEOUSRW},
{"rar", READING},
{"ogg", READING | WRITING | APPENDING},
{"expect", READING | WRITING | APPENDING}
};
zend_string *resolved_path = nullptr;
resolved_path = php_resolve_path(filename, length, use_include_path ? PG(include_path) : nullptr);
if (nullptr == resolved_path)
{
const char *p = fetch_url_scheme(filename);
if (nullptr !=p)
{
std::string scheme(filename, p - filename);
php_stream_wrapper *wrapper;
wrapper = php_stream_locate_url_wrapper(filename, nullptr, STREAM_LOCATE_WRAPPERS_ONLY TSRMLS_CC);
if (wrapper && wrapper->wops)
{
if (w_op & RENAMESRC || w_op & RENAMEDEST)
{
if (wrapper->wops->rename)
{
resolved_path = zend_string_init(filename, length, 0);
}
}
else if ((w_op & OPENDIR))
{
if (wrapper->wops->dir_opener)
{
resolved_path = zend_string_init(filename, length, 0);
}
}
else
{
auto it = opMap.find(scheme);
if (it != opMap.end() && w_op & it->second)
{
resolved_path = zend_string_init(filename, length, 0);
}
}
}
}
else
{
char expand_path[MAXPATHLEN];
char real_path[MAXPATHLEN];
expand_filepath(filename, expand_path);
if (VCWD_REALPATH(expand_path, real_path))
{
if (w_op & OPENDIR || w_op & RENAMESRC)
{
//skip
}
else
{
resolved_path = zend_string_init(expand_path, strlen(expand_path), 0);
}
}
else
{
if (w_op & WRITING || w_op & RENAMEDEST)
{
resolved_path = zend_string_init(expand_path, strlen(expand_path), 0);
}
}
}
}
return resolved_path;
}
void handle_block()
{
int status = php_output_get_status();
if (status & PHP_OUTPUT_WRITTEN)
{
php_output_discard_all();
}
char *block_url = openrasp_ini.block_url;
char *request_id = OPENRASP_INJECT_G(request_id);
if (!SG(headers_sent))
{
char *redirect_header = nullptr;
int redirect_header_len = 0;
redirect_header_len = spprintf(&redirect_header, 0, "Location: %s?request_id=%s", block_url, request_id);
if (redirect_header)
{
sapi_header_line header;
header.line = redirect_header;
header.line_len = redirect_header_len;
header.response_code = openrasp_ini.block_status_code;
sapi_header_op(SAPI_HEADER_REPLACE, &header);
}
efree(redirect_header);
}
/* body 中插入 script 进行重定向 */
{
char *redirect_script = nullptr;
int redirect_script_len = 0;
redirect_script_len = spprintf(&redirect_script, 0, "</script><script>location.href=\"%s?request_id=%s\"</script>", block_url, request_id);
if (redirect_script)
{
php_output_write(redirect_script, redirect_script_len);
php_output_flush();
}
efree(redirect_script);
}
zend_bailout();
}
/**
* 调用 openrasp_check 提供的方法进行检测
* 若需要拦截,直接返回重定向信息,并终止请求
*/
void check(const char *type, zval *params)
{
char result = openrasp_check(type, params);
zval_ptr_dtor(params);
if (result)
{
handle_block();
}
}
extern int include_or_eval_handler(zend_execute_data *execute_data);
PHP_GINIT_FUNCTION(openrasp_hook)
{
#ifdef ZTS
new (openrasp_hook_globals) _zend_openrasp_hook_globals;
#endif
}
PHP_GSHUTDOWN_FUNCTION(openrasp_hook)
{
#ifdef ZTS
openrasp_hook_globals->~_zend_openrasp_hook_globals();
#endif
}
PHP_MINIT_FUNCTION(openrasp_hook)
{
ZEND_INIT_MODULE_GLOBALS(openrasp_hook, PHP_GINIT(openrasp_hook), PHP_GSHUTDOWN(openrasp_hook));
for (auto &single_handler : global_hook_handlers)
{
single_handler();
}
zend_set_user_opcode_handler(ZEND_INCLUDE_OR_EVAL, include_or_eval_handler);
return SUCCESS;
}
PHP_MSHUTDOWN_FUNCTION(openrasp_hook)
{
ZEND_SHUTDOWN_MODULE_GLOBALS(openrasp_hook, PHP_GSHUTDOWN(openrasp_hook));
return SUCCESS;
}
PHP_RINIT_FUNCTION(openrasp_hook);
PHP_RSHUTDOWN_FUNCTION(openrasp_hook);
<commit_msg>fix(php7) fix can not add hook handler to std::vector before main function<commit_after>/*
* Copyright 2017-2018 Baidu 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 "openrasp_hook.h"
#include "openrasp_ini.h"
#include "openrasp_inject.h"
#include <new>
#include <vector>
#include <map>
extern "C" {
#include "ext/standard/php_fopen_wrappers.h"
}
static hook_handler_t global_hook_handlers[512];
static size_t global_hook_handlers_len = 0;
void register_hook_handler(hook_handler_t hook_handler)
{
global_hook_handlers[global_hook_handlers_len++] = hook_handler;
}
typedef struct _track_vars_pair_t
{
int id;
const char *name;
} track_vars_pair;
ZEND_DECLARE_MODULE_GLOBALS(openrasp_hook)
bool openrasp_zval_in_request(zval *item)
{
static const track_vars_pair pairs[] = {{TRACK_VARS_POST, "_POST"},
{TRACK_VARS_GET, "_GET"},
{TRACK_VARS_COOKIE, "_COOKIE"}};
int size = sizeof(pairs) / sizeof(pairs[0]);
for (int index = 0; index < size; ++index)
{
zval *global = &PG(http_globals)[pairs[index].id];
if (Z_TYPE_P(global) != IS_ARRAY &&
!zend_is_auto_global_str(const_cast<char *>(pairs[index].name), strlen(pairs[index].name)))
{
return false;
}
zval *val;
ZEND_HASH_FOREACH_VAL(Z_ARRVAL_P(global), val)
{
if (Z_COUNTED_P(item) == Z_COUNTED_P(val))
{
return true;
}
}
ZEND_HASH_FOREACH_END();
}
return false;
}
void openrasp_buildin_php_risk_handle(zend_bool is_block, const char *type, int confidence, zval *params, zval *message)
{
zval params_result;
array_init(¶ms_result);
add_assoc_long(¶ms_result, "plugin_confidence", confidence);
add_assoc_zval(¶ms_result, "attack_params", params);
add_assoc_string(¶ms_result, "attack_type", const_cast<char *>(type));
add_assoc_zval(¶ms_result, "plugin_message", message);
add_assoc_string(¶ms_result, "intercept_state", const_cast<char *>(is_block ? "block" : "log"));
add_assoc_string(¶ms_result, "plugin_name", const_cast<char *>("php_builtin_plugin"));
alarm_info(¶ms_result);
zval_ptr_dtor(¶ms_result);
if (is_block)
{
handle_block();
}
}
bool openrasp_check_type_ignored(const char *item_name, uint item_name_length)
{
return openrasp_ini.hooks_ignore.find(item_name) != openrasp_ini.hooks_ignore.end();
}
bool openrasp_check_callable_black(const char *item_name, uint item_name_length)
{
return openrasp_ini.callable_blacklists.find(item_name) != openrasp_ini.callable_blacklists.end();
}
struct scheme_cmp {
bool operator() (const std::string& lhs, const std::string& rhs) const {
return strcasecmp(lhs.c_str(), rhs.c_str()) < 0;
}
};
zend_string *openrasp_real_path(char *filename, int length, bool use_include_path, wrapper_operation w_op)
{
static const std::map<std::string, int, scheme_cmp> opMap =
{
{"http", READING},
{"https", READING},
{"ftp", READING | WRITING | APPENDING},
{"ftps", READING | WRITING | APPENDING},
{"php", READING | WRITING | APPENDING | SIMULTANEOUSRW},
{"zlib", READING | WRITING | APPENDING},
{"bzip2", READING | WRITING | APPENDING},
{"zlib", READING},
{"data", READING},
{"phar", READING | WRITING | SIMULTANEOUSRW},
{"ssh2", READING | WRITING | SIMULTANEOUSRW},
{"rar", READING},
{"ogg", READING | WRITING | APPENDING},
{"expect", READING | WRITING | APPENDING}
};
zend_string *resolved_path = nullptr;
resolved_path = php_resolve_path(filename, length, use_include_path ? PG(include_path) : nullptr);
if (nullptr == resolved_path)
{
const char *p = fetch_url_scheme(filename);
if (nullptr !=p)
{
std::string scheme(filename, p - filename);
php_stream_wrapper *wrapper;
wrapper = php_stream_locate_url_wrapper(filename, nullptr, STREAM_LOCATE_WRAPPERS_ONLY TSRMLS_CC);
if (wrapper && wrapper->wops)
{
if (w_op & RENAMESRC || w_op & RENAMEDEST)
{
if (wrapper->wops->rename)
{
resolved_path = zend_string_init(filename, length, 0);
}
}
else if ((w_op & OPENDIR))
{
if (wrapper->wops->dir_opener)
{
resolved_path = zend_string_init(filename, length, 0);
}
}
else
{
auto it = opMap.find(scheme);
if (it != opMap.end() && w_op & it->second)
{
resolved_path = zend_string_init(filename, length, 0);
}
}
}
}
else
{
char expand_path[MAXPATHLEN];
char real_path[MAXPATHLEN];
expand_filepath(filename, expand_path);
if (VCWD_REALPATH(expand_path, real_path))
{
if (w_op & OPENDIR || w_op & RENAMESRC)
{
//skip
}
else
{
resolved_path = zend_string_init(expand_path, strlen(expand_path), 0);
}
}
else
{
if (w_op & WRITING || w_op & RENAMEDEST)
{
resolved_path = zend_string_init(expand_path, strlen(expand_path), 0);
}
}
}
}
return resolved_path;
}
void handle_block()
{
int status = php_output_get_status();
if (status & PHP_OUTPUT_WRITTEN)
{
php_output_discard_all();
}
char *block_url = openrasp_ini.block_url;
char *request_id = OPENRASP_INJECT_G(request_id);
if (!SG(headers_sent))
{
char *redirect_header = nullptr;
int redirect_header_len = 0;
redirect_header_len = spprintf(&redirect_header, 0, "Location: %s?request_id=%s", block_url, request_id);
if (redirect_header)
{
sapi_header_line header;
header.line = redirect_header;
header.line_len = redirect_header_len;
header.response_code = openrasp_ini.block_status_code;
sapi_header_op(SAPI_HEADER_REPLACE, &header);
}
efree(redirect_header);
}
/* body 中插入 script 进行重定向 */
{
char *redirect_script = nullptr;
int redirect_script_len = 0;
redirect_script_len = spprintf(&redirect_script, 0, "</script><script>location.href=\"%s?request_id=%s\"</script>", block_url, request_id);
if (redirect_script)
{
php_output_write(redirect_script, redirect_script_len);
php_output_flush();
}
efree(redirect_script);
}
zend_bailout();
}
/**
* 调用 openrasp_check 提供的方法进行检测
* 若需要拦截,直接返回重定向信息,并终止请求
*/
void check(const char *type, zval *params)
{
char result = openrasp_check(type, params);
zval_ptr_dtor(params);
if (result)
{
handle_block();
}
}
extern int include_or_eval_handler(zend_execute_data *execute_data);
PHP_GINIT_FUNCTION(openrasp_hook)
{
#ifdef ZTS
new (openrasp_hook_globals) _zend_openrasp_hook_globals;
#endif
}
PHP_GSHUTDOWN_FUNCTION(openrasp_hook)
{
#ifdef ZTS
openrasp_hook_globals->~_zend_openrasp_hook_globals();
#endif
}
PHP_MINIT_FUNCTION(openrasp_hook)
{
ZEND_INIT_MODULE_GLOBALS(openrasp_hook, PHP_GINIT(openrasp_hook), PHP_GSHUTDOWN(openrasp_hook));
for (size_t i = 0; i < global_hook_handlers_len; i++)
{
global_hook_handlers[i](TSRMLS_C);
}
zend_set_user_opcode_handler(ZEND_INCLUDE_OR_EVAL, include_or_eval_handler);
return SUCCESS;
}
PHP_MSHUTDOWN_FUNCTION(openrasp_hook)
{
ZEND_SHUTDOWN_MODULE_GLOBALS(openrasp_hook, PHP_GSHUTDOWN(openrasp_hook));
return SUCCESS;
}
PHP_RINIT_FUNCTION(openrasp_hook);
PHP_RSHUTDOWN_FUNCTION(openrasp_hook);
<|endoftext|> |
<commit_before>#include "mainwindow.h"
#include "ui_mainwindow.h"
#include <QProcess>
#include <QClipboard>
#include "qqrencode.h"
#include <dmtx.h>
MainWindow::MainWindow(QWidget *parent) :
QMainWindow(parent),
ui(new Ui::MainWindow)
{
ui->setupUi(this);
this->setWindowFlags(Qt::WindowStaysOnTopHint/*|Qt::X11BypassWindowManagerHint|Qt::FramelessWindowHint*/);
/*this->setWindowState(Qt::WindowFullScreen);*/
// the text that I want encoded
QString inputText;
if (QApplication::arguments().length() > 1) {
inputText = QApplication::arguments().last();
} else {
QClipboard *clipboard = QGuiApplication::clipboard();
if(clipboard->supportsSelection()) {
// win, darwin etc?
inputText = QApplication::clipboard()->text();
} else {
// linux?
const QMimeData *mime = clipboard->mimeData (QClipboard::Selection);
inputText = mime->text ();
}
}
// DATAMATRIX STUFF START
DmtxEncode *enc;
int err = 0;
int len = inputText.length();
// segfault for text longer than this. so dont bother
if (len > 1595) {
// err = 1596;
} else {
enc = dmtxEncodeCreate();
/* Read input data into buffer */
err = dmtxEncodeDataMatrix(enc, len, (unsigned char*)inputText.toLocal8Bit().data());
QImage dmatrix(enc->image->pxl, enc->image->width, enc->image->height, QImage::Format_RGB888);
ui->label->setPixmap(QPixmap::fromImage(dmatrix).scaled(240,240));
dmtxEncodeDestroy(&enc);
}
// DATAMATRIX STUFF END
// QRCODE STUFF START
QQREncode encoder;
encoder.encode(inputText);
QImage qrcode = encoder.toQImage().scaled(240,240);
ui->label_2->setPixmap(QPixmap::fromImage(qrcode));
// QRCODE STUFF END
// COMPENSATE FOR DMATRIX FAILURE USING INVERTED QRCODE START
if (err == 0) {
qrcode.invertPixels();
ui->label->setPixmap(QPixmap::fromImage(qrcode));
}
// COMPENSATE FOR DMATRIX FAILURE USING INVERTED QRCODE END
this->updateGeometry();
}
void MainWindow::mousePressEvent ( QMouseEvent * event )
{
QApplication::quit();
}
MainWindow::~MainWindow()
{
delete ui;
}
<commit_msg>suppress unused warning<commit_after>#include "mainwindow.h"
#include "ui_mainwindow.h"
#include <QProcess>
#include <QClipboard>
#include "qqrencode.h"
#include <dmtx.h>
MainWindow::MainWindow(QWidget *parent) :
QMainWindow(parent),
ui(new Ui::MainWindow)
{
ui->setupUi(this);
this->setWindowFlags(Qt::WindowStaysOnTopHint/*|Qt::X11BypassWindowManagerHint|Qt::FramelessWindowHint*/);
/*this->setWindowState(Qt::WindowFullScreen);*/
// the text that I want encoded
QString inputText;
if (QApplication::arguments().length() > 1) {
inputText = QApplication::arguments().last();
} else {
QClipboard *clipboard = QGuiApplication::clipboard();
if(clipboard->supportsSelection()) {
// win, darwin etc?
inputText = QApplication::clipboard()->text();
} else {
// linux?
const QMimeData *mime = clipboard->mimeData (QClipboard::Selection);
inputText = mime->text ();
}
}
// DATAMATRIX STUFF START
DmtxEncode *enc;
int err = 0;
int len = inputText.length();
// segfault for text longer than this. so dont bother
if (len > 1595) {
// err = 1596;
} else {
enc = dmtxEncodeCreate();
/* Read input data into buffer */
err = dmtxEncodeDataMatrix(enc, len, (unsigned char*)inputText.toLocal8Bit().data());
QImage dmatrix(enc->image->pxl, enc->image->width, enc->image->height, QImage::Format_RGB888);
ui->label->setPixmap(QPixmap::fromImage(dmatrix).scaled(240,240));
dmtxEncodeDestroy(&enc);
}
// DATAMATRIX STUFF END
// QRCODE STUFF START
QQREncode encoder;
encoder.encode(inputText);
QImage qrcode = encoder.toQImage().scaled(240,240);
ui->label_2->setPixmap(QPixmap::fromImage(qrcode));
// QRCODE STUFF END
// COMPENSATE FOR DMATRIX FAILURE USING INVERTED QRCODE START
if (err == 0) {
qrcode.invertPixels();
ui->label->setPixmap(QPixmap::fromImage(qrcode));
}
// COMPENSATE FOR DMATRIX FAILURE USING INVERTED QRCODE END
this->updateGeometry();
}
void MainWindow::mousePressEvent ( QMouseEvent * event )
{
Q_UNUSED(event);
QApplication::quit();
}
MainWindow::~MainWindow()
{
delete ui;
}
<|endoftext|> |
<commit_before>/*
* File: mandelbrot.hpp
* Author: manu343726
*
* Created on 29 de septiembre de 2013, 23:59
*/
#ifndef MANDELBROT_HPP
#define MANDELBROT_HPP
#include "iterator.hpp"
#include "for_loops.hpp"
#include "complex.hpp"
#include "color.hpp"
#include <iostream>
#include <fstream>
#include <iterator>
namespace mandelbrot
{
const int begin_point = -1;
const int end_point = 1;
using begin = mpl::make_decimal_forward_iterator<begin_point>;
using end = mpl::make_decimal_forward_iterator<end_point>;
using size = mpl::uinteger<1>; //Size in tiles
using step = decltype( (mpl::decimal<end_point>() - mpl::decimal<begin_point>()) / size() );
using convergence_value = mpl::decimal<1>;
using iteration_begin = mpl::make_uinteger_forward_iterator<0>;
using iteration_end = mpl::make_uinteger_forward_iterator<10>;
template<typename Y>
struct outer_loop
{
template<typename X>
struct inner_loop
{
using number = math::complex<X,Y>;
template<typename INDEX , typename PREVIOUS>
struct iterate_number
{
using result = decltype( PREVIOUS() * PREVIOUS() + mpl::one<PREVIOUS>() );
static const bool abort = decltype( math::square_length<result>() > convergence_value )::value;
};
//using result_number = mpl::for_loop<iteration_begin , iteration_end , number , iterate_number , step>; COMPILER SEGFAULT HERE
using result_number = number;
using result = mpl::conditional<mpl::true_type , gfx::from_rgb<0,0,0> , gfx::from_rgb<255,255,255>>;
//using result = gfx::from_rgb<255,255,255>;
};
using result = mpl::for_each<begin,end,inner_loop,mpl::true_predicate,step>;
};
using execute = mpl::for_each<begin,end,outer_loop,mpl::true_predicate,step>;
template<typename LIST>
struct stract_to_array;
template<typename... Ts>
struct stract_to_array<mpl::list<Ts...>>
{
template<typename list>
struct stract_sub_array;
template<typename... Us>
struct stract_sub_array<mpl::list<Us...>>
{
static constexpr unsigned int result[size::value] = { Us::value... };
};
static constexpr unsigned int result[size::value][size::value] = { {stract_sub_array<Ts>::result...} };
};
template<typename LIST>
void dump_to_file()
{
auto begin = std::begin( stract_to_array<LIST>::result );
auto end = std::end( stract_to_array<LIST>::result );
std::ofstream os("mandelbrot_output.ppm");
if(os)
{
os << "P6 " << size::value << " " << size::value << "255 ";
std::copy(begin,end,std::ostream_iterator<unsigned int>(os));
}
}
}
#endif /* MANDELBROT_HPP */
<commit_msg>Little refactoring. Also there is more segfaults, segfaults, everywhere...<commit_after>/*
* File: mandelbrot.hpp
* Author: manu343726
*
* Created on 29 de septiembre de 2013, 23:59
*/
#ifndef MANDELBROT_HPP
#define MANDELBROT_HPP
#include "iterator.hpp"
#include "for_loops.hpp"
#include "complex.hpp"
#include "color.hpp"
#include <iostream>
#include <fstream>
#include <iterator>
namespace mandelbrot
{
const int begin_point = -1;
const int end_point = 1;
using begin = mpl::make_decimal_forward_iterator<begin_point>;
using end = mpl::make_decimal_forward_iterator<end_point>;
using size = mpl::uinteger<1>; //Size in tiles
using step = decltype( (mpl::decimal<end_point>() - mpl::decimal<begin_point>()) / size() );
using convergence_value = mpl::decimal<1>;
using iteration_begin = mpl::make_uinteger_forward_iterator<0>;
using iteration_end = mpl::make_uinteger_forward_iterator<10>;
template<typename Y>
struct outer_loop
{
template<typename X>
struct inner_loop
{
using number = math::complex<X,Y>;
template<typename INDEX , typename PREVIOUS>
struct iterate_number
{
using result = decltype( PREVIOUS() * PREVIOUS() + mpl::one<PREVIOUS>() );
static const bool abort = decltype( math::square_length<result>() > convergence_value )::value;
};
//using result_number = mpl::for_loop<iteration_begin , iteration_end , number , iterate_number , step>; COMPILER SEGFAULT HERE
using result_number = number;
using result = mpl::conditional<mpl::true_type , gfx::from_rgb<0,0,0> , gfx::from_rgb<255,255,255>>;
//using result = gfx::from_rgb<255,255,255>;
};
using result = mpl::for_each<begin,end,inner_loop,mpl::true_predicate,step>;
};
using execute = mpl::for_each<begin,end,outer_loop,mpl::true_predicate,step>;
template<typename LIST>
struct to_array;
template<typename... Ts>
struct to_array<mpl::list<Ts...>>
{
template<typename list>
struct dump_sub_array;
template<typename... Us>
struct dump_sub_array<mpl::list<Us...>>
{
static constexpr unsigned int result[size::value] = { Us::value... };
};
static constexpr unsigned int result[size::value][size::value] = { {dump_sub_array<Ts>::result...} };
};
template<typename LIST>
void dump_to_file()
{
auto begin = std::begin( to_array<LIST>::result );
auto end = std::end( to_array<LIST>::result );
std::ofstream os("mandelbrot_output.ppm");
if(os)
{
os << "P6 " << size::value << " " << size::value << "255 ";
std::copy(begin,end,std::ostream_iterator<unsigned int>(os));
}
}
}
#endif /* MANDELBROT_HPP */
<|endoftext|> |
<commit_before>#include <algorithm>
#include "grammar_loader.h"
#include "grammar.h"
#include "json_object.h"
#include "json_loader.h"
#include "shl_exception.h"
namespace shl {
Grammar GrammarLoader::load(const string& buffer) {
JsonLoader loader;
JsonObject object = loader.load(buffer);
Grammar grammar;
process(object, grammar);
return grammar;
}
void GrammarLoader::process(const JsonObject& object, Grammar& grammar) {
grammar.desc = object.name;
grammar.file_types = object.file_types;
compile_grammar(object, grammar, object, grammar, nullptr);
swap(grammar.desc, grammar.name);
}
void GrammarLoader::compile_grammar(const JsonObject& root, Grammar& grammar, const JsonObject& object, Pattern& pattern, Pattern* parent) {
pattern.name = object.name;
pattern.patterns = vector<Pattern>(object.patterns.size());
for (unsigned int idx = 0; idx < pattern.patterns.size(); idx++) {
compile_grammar(root, grammar, object.patterns[idx], pattern.patterns[idx], &pattern);
}
if (!object.include.empty()) {
Pattern* included = find_include(root, grammar, pattern, object.include, parent);
pattern.include = included;
} else if (!object.match.empty()) {
pattern.is_match_rule = true;
pattern.begin = Regex(object.match);
pattern.captures = get_captures(object.captures);
} else if (!object.begin.empty()) {
pattern.is_match_rule = false;
pattern.begin = Regex(object.begin);
pattern.begin_captures = get_captures(object.begin_captures);
if(object.end.empty()) throw InvalidGrammarException("should have end for a begin/end pattern");
pattern.end = Regex(object.end);
pattern.end_captures = get_captures(object.end_captures);
pattern.content_name = object.content_name;
} else {
if (object.patterns.empty()) throw InvalidGrammarException("Empty rule is not alowed");
}
}
int to_int(const string& str) {
for (unsigned int idx = 0; idx < str.size(); idx++) {
if (!isdigit(str[idx])) throw InvalidGrammarException("only numeric capture keys are supported");
}
return atoi(str.c_str());
}
string to_capture_name(const map<string, string> m) {
auto it = m.find("name");
if (it == m.end()) throw InvalidGrammarException("capture should have the name property");
return it->second;
}
map<int, string> GrammarLoader::get_captures(const map<string, map<string, string> > raw_capture) {
map<int, string> captures;
for(auto raw_it = raw_capture.begin(); raw_it != raw_capture.end(); raw_it++) {
int id = to_int(raw_it->first);
string name = to_capture_name(raw_it->second);
}
return captures;
}
Pattern* GrammarLoader::find_include(const JsonObject& root, Grammar& grammar, Pattern& pattern, const string& include_name, Pattern* parent) {
// self reference
if (include_name == "$self") {
return &grammar;
// base reference
} else if (include_name == "$base") {
if ( parent != nullptr) {
return parent;
} else {
throw InvalidGrammarException("a toplevel grammar or toplevel repository item can't included $base");
}
// repository reference
} else if (include_name[0] == '#'){
string repo_name = include_name.substr(1);
// if the stocked resource is already added, then return the address directly
auto stock_res = grammar.repository.find(repo_name);
if (stock_res != grammar.repository.end()) return &stock_res->second;
auto it = root.repository.find(repo_name);
if (it == root.repository.end()) throw InvalidGrammarException(string("can't find the name in repository: ") + repo_name);
grammar.repository[repo_name] = Pattern();
compile_grammar(root, grammar, it->second, grammar.repository[repo_name], nullptr);
return &grammar.repository[repo_name];
// external grammar reference
} else {
throw InvalidGrammarException("include another grammar is not supported yet");
}
}
}
<commit_msg>check to ensure no containing rule is direct parent/child<commit_after>#include <algorithm>
#include "grammar_loader.h"
#include "grammar.h"
#include "json_object.h"
#include "json_loader.h"
#include "shl_exception.h"
namespace shl {
Grammar GrammarLoader::load(const string& buffer) {
JsonLoader loader;
JsonObject object = loader.load(buffer);
Grammar grammar;
process(object, grammar);
return grammar;
}
void GrammarLoader::process(const JsonObject& object, Grammar& grammar) {
grammar.desc = object.name;
grammar.file_types = object.file_types;
compile_grammar(object, grammar, object, grammar, nullptr);
swap(grammar.desc, grammar.name);
}
void GrammarLoader::compile_grammar(const JsonObject& root, Grammar& grammar, const JsonObject& object, Pattern& pattern, Pattern* parent) {
pattern.name = object.name;
if (!object.include.empty()) {
Pattern* included = find_include(root, grammar, pattern, object.include, parent);
pattern.include = included;
} else if (!object.match.empty()) {
pattern.is_match_rule = true;
pattern.begin = Regex(object.match);
pattern.captures = get_captures(object.captures);
} else if (!object.begin.empty()) {
pattern.is_match_rule = false;
pattern.begin = Regex(object.begin);
pattern.begin_captures = get_captures(object.begin_captures);
if(object.end.empty()) throw InvalidGrammarException("should have end for a begin/end pattern");
pattern.end = Regex(object.end);
pattern.end_captures = get_captures(object.end_captures);
pattern.content_name = object.content_name;
} else {
if (object.patterns.empty()) {
throw InvalidGrammarException("empty rule is not alowed");
} else {
if (parent != nullptr && parent->begin.empty()) {
throw InvalidGrammarException("a containing rule can't be direct child of abother containing rule");
}
}
}
pattern.patterns = vector<Pattern>(object.patterns.size());
for (unsigned int idx = 0; idx < pattern.patterns.size(); idx++) {
compile_grammar(root, grammar, object.patterns[idx], pattern.patterns[idx], &pattern);
}
}
int to_int(const string& str) {
for (unsigned int idx = 0; idx < str.size(); idx++) {
if (!isdigit(str[idx])) throw InvalidGrammarException("only numeric capture keys are supported");
}
return atoi(str.c_str());
}
string to_capture_name(const map<string, string> m) {
auto it = m.find("name");
if (it == m.end()) throw InvalidGrammarException("capture should have the name property");
return it->second;
}
map<int, string> GrammarLoader::get_captures(const map<string, map<string, string> > raw_capture) {
map<int, string> captures;
for(auto raw_it = raw_capture.begin(); raw_it != raw_capture.end(); raw_it++) {
int id = to_int(raw_it->first);
string name = to_capture_name(raw_it->second);
}
return captures;
}
Pattern* GrammarLoader::find_include(const JsonObject& root, Grammar& grammar, Pattern& pattern, const string& include_name, Pattern* parent) {
// self reference
if (include_name == "$self") {
return &grammar;
// base reference
} else if (include_name == "$base") {
if ( parent != nullptr) {
return parent;
} else {
throw InvalidGrammarException("a toplevel grammar or toplevel repository item can't included $base");
}
// repository reference
} else if (include_name[0] == '#'){
string repo_name = include_name.substr(1);
// if the stocked resource is already added, then return the address directly
auto stock_res = grammar.repository.find(repo_name);
if (stock_res != grammar.repository.end()) return &stock_res->second;
auto it = root.repository.find(repo_name);
if (it == root.repository.end()) throw InvalidGrammarException(string("can't find the name in repository: ") + repo_name);
grammar.repository[repo_name] = Pattern();
compile_grammar(root, grammar, it->second, grammar.repository[repo_name], nullptr);
return &grammar.repository[repo_name];
// external grammar reference
} else {
throw InvalidGrammarException("include another grammar is not supported yet");
}
}
}
<|endoftext|> |
<commit_before>/* Copyright 2017 Istio Authors. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may 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 "src/grpc_transport.h"
#include <mutex>
#include <thread>
namespace istio {
namespace mixer_client {
namespace {
// A gRPC stream
template <class RequestType, class ResponseType>
class GrpcStream final : public WriteInterface<RequestType> {
public:
typedef std::unique_ptr<
::grpc::ClientReaderWriterInterface<RequestType, ResponseType>>
StreamPtr;
typedef std::function<StreamPtr(::grpc::ClientContext&)> StreamNewFunc;
GrpcStream(ReadInterface<ResponseType>* reader, StreamNewFunc create_func)
: reader_(reader), write_closed_(false) {
stream_ = create_func(context_);
}
static void Start(
std::shared_ptr<GrpcStream<RequestType, ResponseType>> grpc_stream) {
std::thread t([grpc_stream]() { grpc_stream->ReadMainLoop(); });
t.detach();
}
void Write(const RequestType& request) override {
std::lock_guard<std::mutex> lock(write_mutex_);
if (!stream_->Write(request)) {
stream_->WritesDone();
write_closed_ = true;
}
}
void WritesDone() override {
std::lock_guard<std::mutex> lock(write_mutex_);
stream_->WritesDone();
write_closed_ = true;
}
bool is_write_closed() const override { return write_closed_; }
private:
// The worker loop to read response messages.
void ReadMainLoop() {
ResponseType response;
while (stream_->Read(&response)) {
reader_->OnRead(response);
}
::grpc::Status status = stream_->Finish();
// Convert grpc status to protobuf status.
::google::protobuf::util::Status pb_status(
::google::protobuf::util::error::Code(status.error_code()),
::google::protobuf::StringPiece(status.error_message()));
reader_->OnClose(pb_status);
}
// The client context.
::grpc::ClientContext context_;
// Mutex to make sure not calling stream_->Write() parallelly.
std::mutex write_mutex_;
// The reader writer stream.
StreamPtr stream_;
// The reader interface from caller.
ReadInterface<ResponseType>* reader_;
// Indicates if write is closed.
bool write_closed_;
};
typedef GrpcStream<::istio::mixer::v1::CheckRequest,
::istio::mixer::v1::CheckResponse>
CheckGrpcStream;
typedef GrpcStream<::istio::mixer::v1::ReportRequest,
::istio::mixer::v1::ReportResponse>
ReportGrpcStream;
typedef GrpcStream<::istio::mixer::v1::QuotaRequest,
::istio::mixer::v1::QuotaResponse>
QuotaGrpcStream;
} // namespace
GrpcTransport::GrpcTransport(const std::string& mixer_server) {
channel_ = CreateChannel(mixer_server, ::grpc::InsecureChannelCredentials());
stub_ = ::istio::mixer::v1::Mixer::NewStub(channel_);
}
CheckWriterPtr GrpcTransport::NewStream(CheckReaderRawPtr reader) {
auto writer = std::make_shared<CheckGrpcStream>(
reader,
[this](::grpc::ClientContext& context) -> CheckGrpcStream::StreamPtr {
return stub_->Check(&context);
});
CheckGrpcStream::Start(writer);
return writer;
}
ReportWriterPtr GrpcTransport::NewStream(ReportReaderRawPtr reader) {
auto writer = std::make_shared<ReportGrpcStream>(
reader,
[this](::grpc::ClientContext& context) -> ReportGrpcStream::StreamPtr {
return stub_->Report(&context);
});
ReportGrpcStream::Start(writer);
return writer;
}
QuotaWriterPtr GrpcTransport::NewStream(QuotaReaderRawPtr reader) {
auto writer = std::make_shared<QuotaGrpcStream>(
reader,
[this](::grpc::ClientContext& context) -> QuotaGrpcStream::StreamPtr {
return stub_->Quota(&context);
});
QuotaGrpcStream::Start(writer);
return writer;
}
} // namespace mixer_client
} // namespace istio
<commit_msg>Add fast_fail for gRPC (#36)<commit_after>/* Copyright 2017 Istio Authors. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may 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 "src/grpc_transport.h"
#include <mutex>
#include <thread>
namespace istio {
namespace mixer_client {
namespace {
// A gRPC stream
template <class RequestType, class ResponseType>
class GrpcStream final : public WriteInterface<RequestType> {
public:
typedef std::unique_ptr<
::grpc::ClientReaderWriterInterface<RequestType, ResponseType>>
StreamPtr;
typedef std::function<StreamPtr(::grpc::ClientContext&)> StreamNewFunc;
GrpcStream(ReadInterface<ResponseType>* reader, StreamNewFunc create_func)
: reader_(reader), write_closed_(false) {
context_.set_fail_fast(true);
stream_ = create_func(context_);
}
static void Start(
std::shared_ptr<GrpcStream<RequestType, ResponseType>> grpc_stream) {
std::thread t([grpc_stream]() { grpc_stream->ReadMainLoop(); });
t.detach();
}
void Write(const RequestType& request) override {
std::lock_guard<std::mutex> lock(write_mutex_);
if (!stream_->Write(request)) {
stream_->Finish();
}
}
void WritesDone() override {
std::lock_guard<std::mutex> lock(write_mutex_);
stream_->WritesDone();
write_closed_ = true;
}
bool is_write_closed() const override { return write_closed_; }
private:
// The worker loop to read response messages.
void ReadMainLoop() {
ResponseType response;
while (stream_->Read(&response)) {
reader_->OnRead(response);
}
::grpc::Status status = stream_->Finish();
// Convert grpc status to protobuf status.
::google::protobuf::util::Status pb_status(
::google::protobuf::util::error::Code(status.error_code()),
::google::protobuf::StringPiece(status.error_message()));
reader_->OnClose(pb_status);
}
// The client context.
::grpc::ClientContext context_;
// Mutex to make sure not calling stream_->Write() parallelly.
std::mutex write_mutex_;
// The reader writer stream.
StreamPtr stream_;
// The reader interface from caller.
ReadInterface<ResponseType>* reader_;
// Indicates if write is closed.
bool write_closed_;
};
typedef GrpcStream<::istio::mixer::v1::CheckRequest,
::istio::mixer::v1::CheckResponse>
CheckGrpcStream;
typedef GrpcStream<::istio::mixer::v1::ReportRequest,
::istio::mixer::v1::ReportResponse>
ReportGrpcStream;
typedef GrpcStream<::istio::mixer::v1::QuotaRequest,
::istio::mixer::v1::QuotaResponse>
QuotaGrpcStream;
} // namespace
GrpcTransport::GrpcTransport(const std::string& mixer_server) {
channel_ = CreateChannel(mixer_server, ::grpc::InsecureChannelCredentials());
stub_ = ::istio::mixer::v1::Mixer::NewStub(channel_);
}
CheckWriterPtr GrpcTransport::NewStream(CheckReaderRawPtr reader) {
auto writer = std::make_shared<CheckGrpcStream>(
reader,
[this](::grpc::ClientContext& context) -> CheckGrpcStream::StreamPtr {
return stub_->Check(&context);
});
CheckGrpcStream::Start(writer);
return writer;
}
ReportWriterPtr GrpcTransport::NewStream(ReportReaderRawPtr reader) {
auto writer = std::make_shared<ReportGrpcStream>(
reader,
[this](::grpc::ClientContext& context) -> ReportGrpcStream::StreamPtr {
return stub_->Report(&context);
});
ReportGrpcStream::Start(writer);
return writer;
}
QuotaWriterPtr GrpcTransport::NewStream(QuotaReaderRawPtr reader) {
auto writer = std::make_shared<QuotaGrpcStream>(
reader,
[this](::grpc::ClientContext& context) -> QuotaGrpcStream::StreamPtr {
return stub_->Quota(&context);
});
QuotaGrpcStream::Start(writer);
return writer;
}
} // namespace mixer_client
} // namespace istio
<|endoftext|> |
<commit_before>// Copyright 2007, 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.
//
// Author: wan@google.com (Zhanyong Wan)
// Google Test - The Google C++ Testing Framework
//
// This file implements a universal value printer that can print a
// value of any type T:
//
// void ::testing::internal::UniversalPrinter<T>::Print(value, ostream_ptr);
//
// It uses the << operator when possible, and prints the bytes in the
// object otherwise. A user can override its behavior for a class
// type Foo by defining either operator<<(::std::ostream&, const Foo&)
// or void PrintTo(const Foo&, ::std::ostream*) in the namespace that
// defines Foo.
#include "gtest/gtest-printers.h"
#include <ctype.h>
#include <stdio.h>
#include <ostream> // NOLINT
#include <string>
#include "gtest/internal/gtest-port.h"
namespace testing {
namespace {
using ::std::ostream;
#if GTEST_OS_WINDOWS_MOBILE // Windows CE does not define _snprintf_s.
# define snprintf _snprintf
#elif _MSC_VER >= 1400 // VC 8.0 and later deprecate snprintf and _snprintf.
# define snprintf _snprintf_s
#elif _MSC_VER
# define snprintf _snprintf
#endif // GTEST_OS_WINDOWS_MOBILE
// Prints a segment of bytes in the given object.
void PrintByteSegmentInObjectTo(const unsigned char* obj_bytes, size_t start,
size_t count, ostream* os) {
char text[5] = "";
for (size_t i = 0; i != count; i++) {
const size_t j = start + i;
if (i != 0) {
// Organizes the bytes into groups of 2 for easy parsing by
// human.
if ((j % 2) == 0)
*os << ' ';
else
*os << '-';
}
snprintf(text, sizeof(text), "%02X", obj_bytes[j]);
*os << text;
}
}
// Prints the bytes in the given value to the given ostream.
void PrintBytesInObjectToImpl(const unsigned char* obj_bytes, size_t count,
ostream* os) {
// Tells the user how big the object is.
*os << count << "-byte object <";
const size_t kThreshold = 132;
const size_t kChunkSize = 64;
// If the object size is bigger than kThreshold, we'll have to omit
// some details by printing only the first and the last kChunkSize
// bytes.
// TODO(wan): let the user control the threshold using a flag.
if (count < kThreshold) {
PrintByteSegmentInObjectTo(obj_bytes, 0, count, os);
} else {
PrintByteSegmentInObjectTo(obj_bytes, 0, kChunkSize, os);
*os << " ... ";
// Rounds up to 2-byte boundary.
const size_t resume_pos = (count - kChunkSize + 1)/2*2;
PrintByteSegmentInObjectTo(obj_bytes, resume_pos, count - resume_pos, os);
}
*os << ">";
}
} // namespace
namespace internal2 {
// Delegates to PrintBytesInObjectToImpl() to print the bytes in the
// given object. The delegation simplifies the implementation, which
// uses the << operator and thus is easier done outside of the
// ::testing::internal namespace, which contains a << operator that
// sometimes conflicts with the one in STL.
void PrintBytesInObjectTo(const unsigned char* obj_bytes, size_t count,
ostream* os) {
PrintBytesInObjectToImpl(obj_bytes, count, os);
}
} // namespace internal2
namespace internal {
// Depending on the value of a char (or wchar_t), we print it in one
// of three formats:
// - as is if it's a printable ASCII (e.g. 'a', '2', ' '),
// - as a hexidecimal escape sequence (e.g. '\x7F'), or
// - as a special escape sequence (e.g. '\r', '\n').
enum CharFormat {
kAsIs,
kHexEscape,
kSpecialEscape
};
// Returns true if c is a printable ASCII character. We test the
// value of c directly instead of calling isprint(), which is buggy on
// Windows Mobile.
inline bool IsPrintableAscii(wchar_t c) {
return 0x20 <= c && c <= 0x7E;
}
// Prints a wide or narrow char c as a character literal without the
// quotes, escaping it when necessary; returns how c was formatted.
// The template argument UnsignedChar is the unsigned version of Char,
// which is the type of c.
template <typename UnsignedChar, typename Char>
static CharFormat PrintAsCharLiteralTo(Char c, ostream* os) {
switch (static_cast<wchar_t>(c)) {
case L'\0':
*os << "\\0";
break;
case L'\'':
*os << "\\'";
break;
case L'\\':
*os << "\\\\";
break;
case L'\a':
*os << "\\a";
break;
case L'\b':
*os << "\\b";
break;
case L'\f':
*os << "\\f";
break;
case L'\n':
*os << "\\n";
break;
case L'\r':
*os << "\\r";
break;
case L'\t':
*os << "\\t";
break;
case L'\v':
*os << "\\v";
break;
default:
if (IsPrintableAscii(c)) {
*os << static_cast<char>(c);
return kAsIs;
} else {
*os << String::Format("\\x%X", static_cast<UnsignedChar>(c));
return kHexEscape;
}
}
return kSpecialEscape;
}
// Prints a char c as if it's part of a string literal, escaping it when
// necessary; returns how c was formatted.
static CharFormat PrintAsWideStringLiteralTo(wchar_t c, ostream* os) {
switch (c) {
case L'\'':
*os << "'";
return kAsIs;
case L'"':
*os << "\\\"";
return kSpecialEscape;
default:
return PrintAsCharLiteralTo<wchar_t>(c, os);
}
}
// Prints a char c as if it's part of a string literal, escaping it when
// necessary; returns how c was formatted.
static CharFormat PrintAsNarrowStringLiteralTo(char c, ostream* os) {
return PrintAsWideStringLiteralTo(static_cast<unsigned char>(c), os);
}
// Prints a wide or narrow character c and its code. '\0' is printed
// as "'\\0'", other unprintable characters are also properly escaped
// using the standard C++ escape sequence. The template argument
// UnsignedChar is the unsigned version of Char, which is the type of c.
template <typename UnsignedChar, typename Char>
void PrintCharAndCodeTo(Char c, ostream* os) {
// First, print c as a literal in the most readable form we can find.
*os << ((sizeof(c) > 1) ? "L'" : "'");
const CharFormat format = PrintAsCharLiteralTo<UnsignedChar>(c, os);
*os << "'";
// To aid user debugging, we also print c's code in decimal, unless
// it's 0 (in which case c was printed as '\\0', making the code
// obvious).
if (c == 0)
return;
*os << " (" << String::Format("%d", c).c_str();
// For more convenience, we print c's code again in hexidecimal,
// unless c was already printed in the form '\x##' or the code is in
// [1, 9].
if (format == kHexEscape || (1 <= c && c <= 9)) {
// Do nothing.
} else {
*os << String::Format(", 0x%X",
static_cast<UnsignedChar>(c)).c_str();
}
*os << ")";
}
void PrintTo(unsigned char c, ::std::ostream* os) {
PrintCharAndCodeTo<unsigned char>(c, os);
}
void PrintTo(signed char c, ::std::ostream* os) {
PrintCharAndCodeTo<unsigned char>(c, os);
}
// Prints a wchar_t as a symbol if it is printable or as its internal
// code otherwise and also as its code. L'\0' is printed as "L'\\0'".
void PrintTo(wchar_t wc, ostream* os) {
PrintCharAndCodeTo<wchar_t>(wc, os);
}
// Prints the given array of characters to the ostream.
// The array starts at *begin, the length is len, it may include '\0' characters
// and may not be null-terminated.
static void PrintCharsAsStringTo(const char* begin, size_t len, ostream* os) {
*os << "\"";
bool is_previous_hex = false;
for (size_t index = 0; index < len; ++index) {
const char cur = begin[index];
if (is_previous_hex && IsXDigit(cur)) {
// Previous character is of '\x..' form and this character can be
// interpreted as another hexadecimal digit in its number. Break string to
// disambiguate.
*os << "\" \"";
}
is_previous_hex = PrintAsNarrowStringLiteralTo(cur, os) == kHexEscape;
}
*os << "\"";
}
// Prints a (const) char array of 'len' elements, starting at address 'begin'.
void UniversalPrintArray(const char* begin, size_t len, ostream* os) {
PrintCharsAsStringTo(begin, len, os);
}
// Prints the given array of wide characters to the ostream.
// The array starts at *begin, the length is len, it may include L'\0'
// characters and may not be null-terminated.
static void PrintWideCharsAsStringTo(const wchar_t* begin, size_t len,
ostream* os) {
*os << "L\"";
bool is_previous_hex = false;
for (size_t index = 0; index < len; ++index) {
const wchar_t cur = begin[index];
if (is_previous_hex && 0 <= cur && cur < 128 &&
IsXDigit(static_cast<char>(cur))) {
// Previous character is of '\x..' form and this character can be
// interpreted as another hexadecimal digit in its number. Break string to
// disambiguate.
*os << "\" L\"";
}
is_previous_hex = PrintAsWideStringLiteralTo(cur, os) == kHexEscape;
}
*os << "\"";
}
// Prints the given C string to the ostream.
void PrintTo(const char* s, ostream* os) {
if (s == NULL) {
*os << "NULL";
} else {
*os << ImplicitCast_<const void*>(s) << " pointing to ";
PrintCharsAsStringTo(s, strlen(s), os);
}
}
// MSVC compiler can be configured to define whar_t as a typedef
// of unsigned short. Defining an overload for const wchar_t* in that case
// would cause pointers to unsigned shorts be printed as wide strings,
// possibly accessing more memory than intended and causing invalid
// memory accesses. MSVC defines _NATIVE_WCHAR_T_DEFINED symbol when
// wchar_t is implemented as a native type.
#if !defined(_MSC_VER) || defined(_NATIVE_WCHAR_T_DEFINED)
// Prints the given wide C string to the ostream.
void PrintTo(const wchar_t* s, ostream* os) {
if (s == NULL) {
*os << "NULL";
} else {
*os << ImplicitCast_<const void*>(s) << " pointing to ";
PrintWideCharsAsStringTo(s, wcslen(s), os);
}
}
#endif // wchar_t is native
// Prints a ::string object.
#if GTEST_HAS_GLOBAL_STRING
void PrintStringTo(const ::string& s, ostream* os) {
PrintCharsAsStringTo(s.data(), s.size(), os);
}
#endif // GTEST_HAS_GLOBAL_STRING
void PrintStringTo(const ::std::string& s, ostream* os) {
PrintCharsAsStringTo(s.data(), s.size(), os);
}
// Prints a ::wstring object.
#if GTEST_HAS_GLOBAL_WSTRING
void PrintWideStringTo(const ::wstring& s, ostream* os) {
PrintWideCharsAsStringTo(s.data(), s.size(), os);
}
#endif // GTEST_HAS_GLOBAL_WSTRING
#if GTEST_HAS_STD_WSTRING
void PrintWideStringTo(const ::std::wstring& s, ostream* os) {
PrintWideCharsAsStringTo(s.data(), s.size(), os);
}
#endif // GTEST_HAS_STD_WSTRING
} // namespace internal
} // namespace testing
<commit_msg>Simplifies ASCII character detection in gtest-printers.h. This also makes it possible to build Google Test on MinGW.<commit_after>// Copyright 2007, 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.
//
// Author: wan@google.com (Zhanyong Wan)
// Google Test - The Google C++ Testing Framework
//
// This file implements a universal value printer that can print a
// value of any type T:
//
// void ::testing::internal::UniversalPrinter<T>::Print(value, ostream_ptr);
//
// It uses the << operator when possible, and prints the bytes in the
// object otherwise. A user can override its behavior for a class
// type Foo by defining either operator<<(::std::ostream&, const Foo&)
// or void PrintTo(const Foo&, ::std::ostream*) in the namespace that
// defines Foo.
#include "gtest/gtest-printers.h"
#include <ctype.h>
#include <stdio.h>
#include <ostream> // NOLINT
#include <string>
#include "gtest/internal/gtest-port.h"
namespace testing {
namespace {
using ::std::ostream;
#if GTEST_OS_WINDOWS_MOBILE // Windows CE does not define _snprintf_s.
# define snprintf _snprintf
#elif _MSC_VER >= 1400 // VC 8.0 and later deprecate snprintf and _snprintf.
# define snprintf _snprintf_s
#elif _MSC_VER
# define snprintf _snprintf
#endif // GTEST_OS_WINDOWS_MOBILE
// Prints a segment of bytes in the given object.
void PrintByteSegmentInObjectTo(const unsigned char* obj_bytes, size_t start,
size_t count, ostream* os) {
char text[5] = "";
for (size_t i = 0; i != count; i++) {
const size_t j = start + i;
if (i != 0) {
// Organizes the bytes into groups of 2 for easy parsing by
// human.
if ((j % 2) == 0)
*os << ' ';
else
*os << '-';
}
snprintf(text, sizeof(text), "%02X", obj_bytes[j]);
*os << text;
}
}
// Prints the bytes in the given value to the given ostream.
void PrintBytesInObjectToImpl(const unsigned char* obj_bytes, size_t count,
ostream* os) {
// Tells the user how big the object is.
*os << count << "-byte object <";
const size_t kThreshold = 132;
const size_t kChunkSize = 64;
// If the object size is bigger than kThreshold, we'll have to omit
// some details by printing only the first and the last kChunkSize
// bytes.
// TODO(wan): let the user control the threshold using a flag.
if (count < kThreshold) {
PrintByteSegmentInObjectTo(obj_bytes, 0, count, os);
} else {
PrintByteSegmentInObjectTo(obj_bytes, 0, kChunkSize, os);
*os << " ... ";
// Rounds up to 2-byte boundary.
const size_t resume_pos = (count - kChunkSize + 1)/2*2;
PrintByteSegmentInObjectTo(obj_bytes, resume_pos, count - resume_pos, os);
}
*os << ">";
}
} // namespace
namespace internal2 {
// Delegates to PrintBytesInObjectToImpl() to print the bytes in the
// given object. The delegation simplifies the implementation, which
// uses the << operator and thus is easier done outside of the
// ::testing::internal namespace, which contains a << operator that
// sometimes conflicts with the one in STL.
void PrintBytesInObjectTo(const unsigned char* obj_bytes, size_t count,
ostream* os) {
PrintBytesInObjectToImpl(obj_bytes, count, os);
}
} // namespace internal2
namespace internal {
// Depending on the value of a char (or wchar_t), we print it in one
// of three formats:
// - as is if it's a printable ASCII (e.g. 'a', '2', ' '),
// - as a hexidecimal escape sequence (e.g. '\x7F'), or
// - as a special escape sequence (e.g. '\r', '\n').
enum CharFormat {
kAsIs,
kHexEscape,
kSpecialEscape
};
// Returns true if c is a printable ASCII character. We test the
// value of c directly instead of calling isprint(), which is buggy on
// Windows Mobile.
inline bool IsPrintableAscii(wchar_t c) {
return 0x20 <= c && c <= 0x7E;
}
// Prints a wide or narrow char c as a character literal without the
// quotes, escaping it when necessary; returns how c was formatted.
// The template argument UnsignedChar is the unsigned version of Char,
// which is the type of c.
template <typename UnsignedChar, typename Char>
static CharFormat PrintAsCharLiteralTo(Char c, ostream* os) {
switch (static_cast<wchar_t>(c)) {
case L'\0':
*os << "\\0";
break;
case L'\'':
*os << "\\'";
break;
case L'\\':
*os << "\\\\";
break;
case L'\a':
*os << "\\a";
break;
case L'\b':
*os << "\\b";
break;
case L'\f':
*os << "\\f";
break;
case L'\n':
*os << "\\n";
break;
case L'\r':
*os << "\\r";
break;
case L'\t':
*os << "\\t";
break;
case L'\v':
*os << "\\v";
break;
default:
if (IsPrintableAscii(c)) {
*os << static_cast<char>(c);
return kAsIs;
} else {
*os << String::Format("\\x%X", static_cast<UnsignedChar>(c));
return kHexEscape;
}
}
return kSpecialEscape;
}
// Prints a char c as if it's part of a string literal, escaping it when
// necessary; returns how c was formatted.
static CharFormat PrintAsWideStringLiteralTo(wchar_t c, ostream* os) {
switch (c) {
case L'\'':
*os << "'";
return kAsIs;
case L'"':
*os << "\\\"";
return kSpecialEscape;
default:
return PrintAsCharLiteralTo<wchar_t>(c, os);
}
}
// Prints a char c as if it's part of a string literal, escaping it when
// necessary; returns how c was formatted.
static CharFormat PrintAsNarrowStringLiteralTo(char c, ostream* os) {
return PrintAsWideStringLiteralTo(static_cast<unsigned char>(c), os);
}
// Prints a wide or narrow character c and its code. '\0' is printed
// as "'\\0'", other unprintable characters are also properly escaped
// using the standard C++ escape sequence. The template argument
// UnsignedChar is the unsigned version of Char, which is the type of c.
template <typename UnsignedChar, typename Char>
void PrintCharAndCodeTo(Char c, ostream* os) {
// First, print c as a literal in the most readable form we can find.
*os << ((sizeof(c) > 1) ? "L'" : "'");
const CharFormat format = PrintAsCharLiteralTo<UnsignedChar>(c, os);
*os << "'";
// To aid user debugging, we also print c's code in decimal, unless
// it's 0 (in which case c was printed as '\\0', making the code
// obvious).
if (c == 0)
return;
*os << " (" << String::Format("%d", c).c_str();
// For more convenience, we print c's code again in hexidecimal,
// unless c was already printed in the form '\x##' or the code is in
// [1, 9].
if (format == kHexEscape || (1 <= c && c <= 9)) {
// Do nothing.
} else {
*os << String::Format(", 0x%X",
static_cast<UnsignedChar>(c)).c_str();
}
*os << ")";
}
void PrintTo(unsigned char c, ::std::ostream* os) {
PrintCharAndCodeTo<unsigned char>(c, os);
}
void PrintTo(signed char c, ::std::ostream* os) {
PrintCharAndCodeTo<unsigned char>(c, os);
}
// Prints a wchar_t as a symbol if it is printable or as its internal
// code otherwise and also as its code. L'\0' is printed as "L'\\0'".
void PrintTo(wchar_t wc, ostream* os) {
PrintCharAndCodeTo<wchar_t>(wc, os);
}
// Prints the given array of characters to the ostream.
// The array starts at *begin, the length is len, it may include '\0' characters
// and may not be null-terminated.
static void PrintCharsAsStringTo(const char* begin, size_t len, ostream* os) {
*os << "\"";
bool is_previous_hex = false;
for (size_t index = 0; index < len; ++index) {
const char cur = begin[index];
if (is_previous_hex && IsXDigit(cur)) {
// Previous character is of '\x..' form and this character can be
// interpreted as another hexadecimal digit in its number. Break string to
// disambiguate.
*os << "\" \"";
}
is_previous_hex = PrintAsNarrowStringLiteralTo(cur, os) == kHexEscape;
}
*os << "\"";
}
// Prints a (const) char array of 'len' elements, starting at address 'begin'.
void UniversalPrintArray(const char* begin, size_t len, ostream* os) {
PrintCharsAsStringTo(begin, len, os);
}
// Prints the given array of wide characters to the ostream.
// The array starts at *begin, the length is len, it may include L'\0'
// characters and may not be null-terminated.
static void PrintWideCharsAsStringTo(const wchar_t* begin, size_t len,
ostream* os) {
*os << "L\"";
bool is_previous_hex = false;
for (size_t index = 0; index < len; ++index) {
const wchar_t cur = begin[index];
if (is_previous_hex && isascii(cur) && IsXDigit(static_cast<char>(cur))) {
// Previous character is of '\x..' form and this character can be
// interpreted as another hexadecimal digit in its number. Break string to
// disambiguate.
*os << "\" L\"";
}
is_previous_hex = PrintAsWideStringLiteralTo(cur, os) == kHexEscape;
}
*os << "\"";
}
// Prints the given C string to the ostream.
void PrintTo(const char* s, ostream* os) {
if (s == NULL) {
*os << "NULL";
} else {
*os << ImplicitCast_<const void*>(s) << " pointing to ";
PrintCharsAsStringTo(s, strlen(s), os);
}
}
// MSVC compiler can be configured to define whar_t as a typedef
// of unsigned short. Defining an overload for const wchar_t* in that case
// would cause pointers to unsigned shorts be printed as wide strings,
// possibly accessing more memory than intended and causing invalid
// memory accesses. MSVC defines _NATIVE_WCHAR_T_DEFINED symbol when
// wchar_t is implemented as a native type.
#if !defined(_MSC_VER) || defined(_NATIVE_WCHAR_T_DEFINED)
// Prints the given wide C string to the ostream.
void PrintTo(const wchar_t* s, ostream* os) {
if (s == NULL) {
*os << "NULL";
} else {
*os << ImplicitCast_<const void*>(s) << " pointing to ";
PrintWideCharsAsStringTo(s, wcslen(s), os);
}
}
#endif // wchar_t is native
// Prints a ::string object.
#if GTEST_HAS_GLOBAL_STRING
void PrintStringTo(const ::string& s, ostream* os) {
PrintCharsAsStringTo(s.data(), s.size(), os);
}
#endif // GTEST_HAS_GLOBAL_STRING
void PrintStringTo(const ::std::string& s, ostream* os) {
PrintCharsAsStringTo(s.data(), s.size(), os);
}
// Prints a ::wstring object.
#if GTEST_HAS_GLOBAL_WSTRING
void PrintWideStringTo(const ::wstring& s, ostream* os) {
PrintWideCharsAsStringTo(s.data(), s.size(), os);
}
#endif // GTEST_HAS_GLOBAL_WSTRING
#if GTEST_HAS_STD_WSTRING
void PrintWideStringTo(const ::std::wstring& s, ostream* os) {
PrintWideCharsAsStringTo(s.data(), s.size(), os);
}
#endif // GTEST_HAS_STD_WSTRING
} // namespace internal
} // namespace testing
<|endoftext|> |
<commit_before>/*=========================================================================
Program: Visomics
Copyright (c) Kitware, Inc.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
=========================================================================*/
// Qt includes
#include <QAction>
#include <QDebug>
#include <QDesktopServices>
#include <QFileDialog>
#include <QLayout>
#include <QResizeEvent>
// Visomics includes
#include "voDataObject.h"
#include "voTreeHeatmapView.h"
#include "voUtils.h"
#include "vtkExtendedTable.h"
// VTK includes
#include <QVTKWidget.h>
#include <vtkContextMouseEvent.h>
#include <vtkContextScene.h>
#include <vtkContextTransform.h>
#include <vtkContextView.h>
#include <vtkDataSetAttributes.h>
#include <vtkDendrogramItem.h>
#include <vtkGL2PSExporter.h>
#include <vtkRenderer.h>
#include <vtkRenderWindow.h>
#include <vtkSmartPointer.h>
#include <vtkTransform2D.h>
#include <vtkTree.h>
#include <vtkTreeHeatmapItem.h>
// --------------------------------------------------------------------------
class voTreeHeatmapViewPrivate
{
public:
voTreeHeatmapViewPrivate();
vtkSmartPointer<vtkContextView> ContextView;
vtkSmartPointer<vtkTreeHeatmapItem> TreeItem;
vtkSmartPointer<vtkContextTransform> TransformItem;
QVTKWidget* Widget;
bool DataAlreadyCentered;
};
// --------------------------------------------------------------------------
// voTreeHeatmapViewPrivate methods
// --------------------------------------------------------------------------
voTreeHeatmapViewPrivate::voTreeHeatmapViewPrivate()
{
this->Widget = 0;
this->DataAlreadyCentered = false;
}
// --------------------------------------------------------------------------
// voTreeHeatmapView methods
// --------------------------------------------------------------------------
voTreeHeatmapView::voTreeHeatmapView(QWidget * newParent):
Superclass(newParent), d_ptr(new voTreeHeatmapViewPrivate)
{
}
// --------------------------------------------------------------------------
voTreeHeatmapView::~voTreeHeatmapView()
{
}
// --------------------------------------------------------------------------
vtkTreeHeatmapItem * voTreeHeatmapView::getTreeHeatmapItem() const
{
Q_D(const voTreeHeatmapView);
return d->TreeItem;
}
// --------------------------------------------------------------------------
void voTreeHeatmapView::setupUi(QLayout *layout)
{
Q_D(voTreeHeatmapView);
d->ContextView = vtkSmartPointer<vtkContextView>::New();
d->Widget = new QVTKWidget();
d->ContextView->SetInteractor(d->Widget->GetInteractor());
d->Widget->SetRenderWindow(d->ContextView->GetRenderWindow());
d->ContextView->GetRenderer()->SetBackground(1.0, 1.0, 1.0);
d->TreeItem = vtkSmartPointer<vtkTreeHeatmapItem>::New();
d->TransformItem = vtkSmartPointer<vtkContextTransform>::New();
d->TransformItem->AddItem(d->TreeItem);
d->TransformItem->SetInteractive(true);
d->ContextView->GetScene()->AddItem(d->TransformItem);
layout->addWidget(d->Widget);
}
// --------------------------------------------------------------------------
void voTreeHeatmapView::setDataObjectListInternal(const QList<voDataObject*> dataObjects)
{
Q_D(voTreeHeatmapView);
if (dataObjects.size() == 2)
{
vtkTree * Tree = vtkTree::SafeDownCast(dataObjects[0]->dataAsVTKDataObject());
if (!Tree)
{
qCritical() << "voTreeHeatmapView - Failed to setDataObject - vtkTree data is expected !";
return;
}
vtkExtendedTable * Table = vtkExtendedTable::SafeDownCast(dataObjects[1]->dataAsVTKDataObject());
if (!Table)
{
qCritical() << "voTreeHeatmapView - Failed to setDataObject - vtkExtendedTable data is expected !";
return;
}
//If there is a real change in the tree (# of vertices), update the tree, otherwise, just leave it there,
//so that expanding/collapsing interactions results could be kept on the view.
if (d->TreeItem->GetTree()->GetNumberOfVertices() != Tree->GetNumberOfVertices())
{
// making a copy of the Tree so that the TreeHeatmap & Dendrogram no longer
// share a single input data source
vtkSmartPointer<vtkTree> treeCopy = vtkSmartPointer<vtkTree>::New();
treeCopy->DeepCopy(Tree);
d->TreeItem->SetTree(treeCopy);
}
if (d->TreeItem->GetTable() != Table->GetInputData())
{
d->TreeItem->SetTable(Table->GetInputData());
}
}
else
{
// one of our dataObjects must have been deleted...
// first check if we have ANY data left
if (dataObjects.size() == 0)
{
return;
}
vtkTree * Tree = vtkTree::SafeDownCast(dataObjects[0]->dataAsVTKDataObject());
if (Tree)
{
// do we have a tree?
if (d->TreeItem->GetTree() != Tree)
{
// is it different from the one we're already drawing?
d->TreeItem->SetTree(Tree);
}
d->TreeItem->SetTable(NULL);
}
else
{
// or do we have a table?
vtkExtendedTable * Table = vtkExtendedTable::SafeDownCast(dataObjects[0]->dataAsVTKDataObject());
if (!Table)
{
qCritical() << "voTreeHeatmapView - Failed to setDataObjectListInternal - Neither tree or table were found !";
return;
}
if (d->TreeItem->GetTable() != Table->GetInputData())
{
// and is it different from the one we're already drawing?
d->TreeItem->SetTable(Table->GetInputData());
}
d->TreeItem->SetTree(NULL);
}
}
this->colorTreeForDifference();
d->ContextView->GetRenderWindow()->SetMultiSamples(0);
}
// --------------------------------------------------------------------------
void voTreeHeatmapView::setDataObjectInternal(const voDataObject& dataObject)
{//only render the tree
Q_D(voTreeHeatmapView);
vtkTree * tree = vtkTree::SafeDownCast(dataObject.dataAsVTKDataObject());
if (!tree)
{
qCritical() << "voTreeHeatmapView - Failed to setDataObject - vtkTree data is expected !";
return;
}
if (d->TreeItem->GetTree() != tree)
{
d->TreeItem->SetTree(tree);
}
this->colorTreeForDifference();
d->ContextView->GetRenderWindow()->SetMultiSamples(0);
}
// --------------------------------------------------------------------------
void voTreeHeatmapView::colorTreeForDifference()
{
Q_D(voTreeHeatmapView);
vtkDataArray *differenceArray =
d->TreeItem->GetTree()->GetVertexData()->GetArray("differences");
if (differenceArray)
{
d->TreeItem->GetDendrogram()->SetColorArray("differences");
d->TreeItem->GetDendrogram()->SetLineWidth(2.0);
}
}
// --------------------------------------------------------------------------
void voTreeHeatmapView::centerData()
{
Q_D(voTreeHeatmapView);
// this function gets called every time the view is selected, but we
// only want to perform this data centering on the initial render.
if (d->DataAlreadyCentered)
{
return;
}
d->DataAlreadyCentered = true;
// make sure the underlying data has been rendered before we start querying
// it about its bounds & center.
d->ContextView->Render();
// get the size of our data. because this is measured in scene coordinates,
// we convert it to pixel coordinates. in practice this should be a no-op,
// as the transform involved should be an identity as this point.
double itemSize[3];
d->TreeItem->GetSize(itemSize);
d->TransformItem->GetTransform()->MultiplyPoint(itemSize, itemSize);
// get the size of the scene (measured in pixels).
double sceneWidth = d->ContextView->GetScene()->GetSceneWidth();
double sceneHeight = d->ContextView->GetScene()->GetSceneHeight();
// scale the data so that the full extent of the item fills 90% of the scene.
this->scaleItem(itemSize[0], itemSize[1],
sceneWidth * 0.9, sceneHeight * 0.9);
// get the center of the item and convert it to pixel coordinates.
// because of the previous scale operation, this probably isn't a no-op.
double itemCenter[2];
d->TreeItem->GetCenter(itemCenter);
d->TransformItem->GetTransform()->MultiplyPoint(itemCenter, itemCenter);
// get the center of the scene
double sceneCenter[2];
sceneCenter[0] = sceneWidth / 2.0;
sceneCenter[1] = sceneHeight / 2.0;
// construct a mouse event dragging from the center of the item to the
// center of the scene. this centers the data.
vtkContextMouseEvent mouseEvent;
mouseEvent.SetButton(vtkContextMouseEvent::LEFT_BUTTON);
mouseEvent.SetInteractor(d->Widget->GetInteractor());
vtkVector2i lastPos;
lastPos.Set(itemCenter[0], itemCenter[1]);
mouseEvent.SetLastScreenPos(lastPos);
vtkVector2i pos;
pos.Set(sceneCenter[0], sceneCenter[1]);
mouseEvent.SetScreenPos(pos);
d->TransformItem->MouseMoveEvent(mouseEvent);
}
// --------------------------------------------------------------------------
void voTreeHeatmapView::scaleItem(double oldWidth, double oldHeight,
double newWidth, double newHeight)
{
Q_D(voTreeHeatmapView);
double sx = newWidth / oldWidth;
double sy = newHeight / oldHeight;
// regardless if zooming out or zooming in, we should always use
// the scale factor closest to 1.0, as this will not resize the
// scene in such a way as to push objects of interest out of view.
double dx = abs(sx - 1.0);
double dy = abs(sy - 1.0);
if (dy > dx)
{
d->TransformItem->Scale(sx, sx);
}
else
{
d->TransformItem->Scale(sy, sy);
}
}
// --------------------------------------------------------------------------
void voTreeHeatmapView::resizeEvent(QResizeEvent *event)
{
// if this resize is occurring as part of the initial render, then
// we do nothing here. centerData() will be called slightly later
// from voViewStackedWidget.
if (event->oldSize().width() == -1)
{
return;
}
// otherwise, zoom in or out to compensate for the change in size of the
// render window.
else
{
this->scaleItem(static_cast<double>(event->oldSize().width()),
static_cast<double>(event->oldSize().height()),
static_cast<double>(event->size().width()),
static_cast<double>(event->size().height()));
}
}
// --------------------------------------------------------------------------
QList<QAction*> voTreeHeatmapView::actions()
{
QList<QAction*> actionList;
QAction * saveScreenshotAction =
new QAction(QIcon(":/Icons/saveScreenshot.png"), "Save screenshot", this);
saveScreenshotAction->setToolTip("Save the current view to disk.");
connect(saveScreenshotAction, SIGNAL(triggered()),
this, SLOT(onSaveScreenshotActionTriggered()));
actionList << saveScreenshotAction;
return actionList;
}
// --------------------------------------------------------------------------
void voTreeHeatmapView::onSaveScreenshotActionTriggered()
{
QString defaultFileName =
QDesktopServices::storageLocation(QDesktopServices::DesktopLocation)
+ "/" + voUtils::cleanString(this->objectName()) + ".svg";
QString fileName = QFileDialog::getSaveFileName(
0, tr("Save screenshot..."), defaultFileName, "Image (*.svg *.png)");
if(fileName.isEmpty())
{
return;
}
this->saveScreenshot(fileName);
}
// --------------------------------------------------------------------------
void voTreeHeatmapView::saveScreenshot(const QString& fileName)
{
Q_D(voTreeHeatmapView);
if (fileName.endsWith(".png"))
{
this->Superclass::saveScreenshot(fileName);
return;
}
vtkNew<vtkGL2PSExporter> exporter;
exporter->SetRenderWindow(d->ContextView->GetRenderWindow());
exporter->SetFileFormatToSVG();
exporter->UsePainterSettings();
exporter->CompressOff();
exporter->SetTitle(this->objectName().toStdString().c_str());
exporter->DrawBackgroundOn();
QFileInfo fileInfo(fileName);
QString fileNameWithoutExt = fileInfo.dir().absolutePath() +
QString("/") + fileInfo.baseName();
exporter->SetFilePrefix(fileNameWithoutExt.toStdString().c_str());
exporter->Write();
}
<commit_msg>fix "load sample data" button on windows<commit_after>/*=========================================================================
Program: Visomics
Copyright (c) Kitware, Inc.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
=========================================================================*/
// Qt includes
#include <QAction>
#include <QDebug>
#include <QDesktopServices>
#include <QFileDialog>
#include <QLayout>
#include <QResizeEvent>
// Visomics includes
#include "voDataObject.h"
#include "voTreeHeatmapView.h"
#include "voUtils.h"
#include "vtkExtendedTable.h"
// VTK includes
#include <QVTKWidget.h>
#include <vtkContextMouseEvent.h>
#include <vtkContextScene.h>
#include <vtkContextTransform.h>
#include <vtkContextView.h>
#include <vtkDataSetAttributes.h>
#include <vtkDendrogramItem.h>
#include <vtkGL2PSExporter.h>
#include <vtkRenderer.h>
#include <vtkRenderWindow.h>
#include <vtkSmartPointer.h>
#include <vtkTransform2D.h>
#include <vtkTree.h>
#include <vtkTreeHeatmapItem.h>
// --------------------------------------------------------------------------
class voTreeHeatmapViewPrivate
{
public:
voTreeHeatmapViewPrivate();
vtkSmartPointer<vtkContextView> ContextView;
vtkSmartPointer<vtkTreeHeatmapItem> TreeItem;
vtkSmartPointer<vtkContextTransform> TransformItem;
QVTKWidget* Widget;
bool DataAlreadyCentered;
};
// --------------------------------------------------------------------------
// voTreeHeatmapViewPrivate methods
// --------------------------------------------------------------------------
voTreeHeatmapViewPrivate::voTreeHeatmapViewPrivate()
{
this->Widget = 0;
this->DataAlreadyCentered = false;
}
// --------------------------------------------------------------------------
// voTreeHeatmapView methods
// --------------------------------------------------------------------------
voTreeHeatmapView::voTreeHeatmapView(QWidget * newParent):
Superclass(newParent), d_ptr(new voTreeHeatmapViewPrivate)
{
}
// --------------------------------------------------------------------------
voTreeHeatmapView::~voTreeHeatmapView()
{
}
// --------------------------------------------------------------------------
vtkTreeHeatmapItem * voTreeHeatmapView::getTreeHeatmapItem() const
{
Q_D(const voTreeHeatmapView);
return d->TreeItem;
}
// --------------------------------------------------------------------------
void voTreeHeatmapView::setupUi(QLayout *layout)
{
Q_D(voTreeHeatmapView);
d->ContextView = vtkSmartPointer<vtkContextView>::New();
d->Widget = new QVTKWidget();
d->ContextView->SetInteractor(d->Widget->GetInteractor());
d->Widget->SetRenderWindow(d->ContextView->GetRenderWindow());
d->ContextView->GetRenderer()->SetBackground(1.0, 1.0, 1.0);
d->TreeItem = vtkSmartPointer<vtkTreeHeatmapItem>::New();
d->TransformItem = vtkSmartPointer<vtkContextTransform>::New();
d->TransformItem->AddItem(d->TreeItem);
d->TransformItem->SetInteractive(true);
d->ContextView->GetScene()->AddItem(d->TransformItem);
layout->addWidget(d->Widget);
}
// --------------------------------------------------------------------------
void voTreeHeatmapView::setDataObjectListInternal(const QList<voDataObject*> dataObjects)
{
Q_D(voTreeHeatmapView);
if (dataObjects.size() == 2)
{
vtkTree * Tree = vtkTree::SafeDownCast(dataObjects[0]->dataAsVTKDataObject());
if (!Tree)
{
qCritical() << "voTreeHeatmapView - Failed to setDataObject - vtkTree data is expected !";
return;
}
vtkExtendedTable * Table = vtkExtendedTable::SafeDownCast(dataObjects[1]->dataAsVTKDataObject());
if (!Table)
{
qCritical() << "voTreeHeatmapView - Failed to setDataObject - vtkExtendedTable data is expected !";
return;
}
//If there is a real change in the tree (# of vertices), update the tree, otherwise, just leave it there,
//so that expanding/collapsing interactions results could be kept on the view.
if (d->TreeItem->GetTree()->GetNumberOfVertices() != Tree->GetNumberOfVertices())
{
// making a copy of the Tree so that the TreeHeatmap & Dendrogram no longer
// share a single input data source
vtkSmartPointer<vtkTree> treeCopy = vtkSmartPointer<vtkTree>::New();
treeCopy->DeepCopy(Tree);
d->TreeItem->SetTree(treeCopy);
}
if (d->TreeItem->GetTable() != Table->GetInputData())
{
d->TreeItem->SetTable(Table->GetInputData());
}
}
else
{
// one of our dataObjects must have been deleted...
// first check if we have ANY data left
if (dataObjects.size() == 0)
{
return;
}
vtkTree * Tree = vtkTree::SafeDownCast(dataObjects[0]->dataAsVTKDataObject());
if (Tree)
{
// do we have a tree?
if (d->TreeItem->GetTree() != Tree)
{
// is it different from the one we're already drawing?
d->TreeItem->SetTree(Tree);
}
d->TreeItem->SetTable(NULL);
}
else
{
// or do we have a table?
vtkExtendedTable * Table = vtkExtendedTable::SafeDownCast(dataObjects[0]->dataAsVTKDataObject());
if (!Table)
{
qCritical() << "voTreeHeatmapView - Failed to setDataObjectListInternal - Neither tree or table were found !";
return;
}
if (d->TreeItem->GetTable() != Table->GetInputData())
{
// and is it different from the one we're already drawing?
d->TreeItem->SetTable(Table->GetInputData());
}
d->TreeItem->SetTree(NULL);
}
}
this->colorTreeForDifference();
d->ContextView->GetRenderWindow()->SetMultiSamples(0);
}
// --------------------------------------------------------------------------
void voTreeHeatmapView::setDataObjectInternal(const voDataObject& dataObject)
{//only render the tree
Q_D(voTreeHeatmapView);
vtkTree * tree = vtkTree::SafeDownCast(dataObject.dataAsVTKDataObject());
if (!tree)
{
qCritical() << "voTreeHeatmapView - Failed to setDataObject - vtkTree data is expected !";
return;
}
if (d->TreeItem->GetTree() != tree)
{
d->TreeItem->SetTree(tree);
}
this->colorTreeForDifference();
d->ContextView->GetRenderWindow()->SetMultiSamples(0);
}
// --------------------------------------------------------------------------
void voTreeHeatmapView::colorTreeForDifference()
{
Q_D(voTreeHeatmapView);
vtkDataArray *differenceArray =
d->TreeItem->GetTree()->GetVertexData()->GetArray("differences");
if (differenceArray)
{
d->TreeItem->GetDendrogram()->SetColorArray("differences");
d->TreeItem->GetDendrogram()->SetLineWidth(2.0);
}
}
// --------------------------------------------------------------------------
void voTreeHeatmapView::centerData()
{
Q_D(voTreeHeatmapView);
// this function gets called every time the view is selected, but we
// only want to perform this data centering on the initial render.
if (d->DataAlreadyCentered)
{
return;
}
d->DataAlreadyCentered = true;
// make sure the underlying data has been rendered before we start querying
// it about its bounds & center.
d->ContextView->Render();
// get the size of our data. because this is measured in scene coordinates,
// we convert it to pixel coordinates. in practice this should be a no-op,
// as the transform involved should be an identity as this point.
double itemSize[3];
d->TreeItem->GetSize(itemSize);
itemSize[2] = 0.0;
d->TransformItem->GetTransform()->MultiplyPoint(itemSize, itemSize);
// get the size of the scene (measured in pixels).
double sceneWidth = d->ContextView->GetScene()->GetSceneWidth();
double sceneHeight = d->ContextView->GetScene()->GetSceneHeight();
// scale the data so that the full extent of the item fills 90% of the scene.
this->scaleItem(itemSize[0], itemSize[1],
sceneWidth * 0.9, sceneHeight * 0.9);
// get the center of the item and convert it to pixel coordinates.
// because of the previous scale operation, this probably isn't a no-op.
double itemCenter[2];
d->TreeItem->GetCenter(itemCenter);
d->TransformItem->GetTransform()->MultiplyPoint(itemCenter, itemCenter);
// get the center of the scene
double sceneCenter[2];
sceneCenter[0] = sceneWidth / 2.0;
sceneCenter[1] = sceneHeight / 2.0;
// construct a mouse event dragging from the center of the item to the
// center of the scene. this centers the data.
vtkContextMouseEvent mouseEvent;
mouseEvent.SetButton(vtkContextMouseEvent::LEFT_BUTTON);
mouseEvent.SetInteractor(d->Widget->GetInteractor());
vtkVector2i lastPos;
lastPos.Set(itemCenter[0], itemCenter[1]);
mouseEvent.SetLastScreenPos(lastPos);
vtkVector2i pos;
pos.Set(sceneCenter[0], sceneCenter[1]);
mouseEvent.SetScreenPos(pos);
d->TransformItem->MouseMoveEvent(mouseEvent);
}
// --------------------------------------------------------------------------
void voTreeHeatmapView::scaleItem(double oldWidth, double oldHeight,
double newWidth, double newHeight)
{
Q_D(voTreeHeatmapView);
double sx = newWidth / oldWidth;
double sy = newHeight / oldHeight;
// regardless if zooming out or zooming in, we should always use
// the scale factor closest to 1.0, as this will not resize the
// scene in such a way as to push objects of interest out of view.
double dx = abs(sx - 1.0);
double dy = abs(sy - 1.0);
if (dy > dx)
{
d->TransformItem->Scale(sx, sx);
}
else
{
d->TransformItem->Scale(sy, sy);
}
}
// --------------------------------------------------------------------------
void voTreeHeatmapView::resizeEvent(QResizeEvent *event)
{
// if this resize is occurring as part of the initial render, then
// we do nothing here. centerData() will be called slightly later
// from voViewStackedWidget.
if (event->oldSize().width() == -1)
{
return;
}
// otherwise, zoom in or out to compensate for the change in size of the
// render window.
else
{
this->scaleItem(static_cast<double>(event->oldSize().width()),
static_cast<double>(event->oldSize().height()),
static_cast<double>(event->size().width()),
static_cast<double>(event->size().height()));
}
}
// --------------------------------------------------------------------------
QList<QAction*> voTreeHeatmapView::actions()
{
QList<QAction*> actionList;
QAction * saveScreenshotAction =
new QAction(QIcon(":/Icons/saveScreenshot.png"), "Save screenshot", this);
saveScreenshotAction->setToolTip("Save the current view to disk.");
connect(saveScreenshotAction, SIGNAL(triggered()),
this, SLOT(onSaveScreenshotActionTriggered()));
actionList << saveScreenshotAction;
return actionList;
}
// --------------------------------------------------------------------------
void voTreeHeatmapView::onSaveScreenshotActionTriggered()
{
QString defaultFileName =
QDesktopServices::storageLocation(QDesktopServices::DesktopLocation)
+ "/" + voUtils::cleanString(this->objectName()) + ".svg";
QString fileName = QFileDialog::getSaveFileName(
0, tr("Save screenshot..."), defaultFileName, "Image (*.svg *.png)");
if(fileName.isEmpty())
{
return;
}
this->saveScreenshot(fileName);
}
// --------------------------------------------------------------------------
void voTreeHeatmapView::saveScreenshot(const QString& fileName)
{
Q_D(voTreeHeatmapView);
if (fileName.endsWith(".png"))
{
this->Superclass::saveScreenshot(fileName);
return;
}
vtkNew<vtkGL2PSExporter> exporter;
exporter->SetRenderWindow(d->ContextView->GetRenderWindow());
exporter->SetFileFormatToSVG();
exporter->UsePainterSettings();
exporter->CompressOff();
exporter->SetTitle(this->objectName().toStdString().c_str());
exporter->DrawBackgroundOn();
QFileInfo fileInfo(fileName);
QString fileNameWithoutExt = fileInfo.dir().absolutePath() +
QString("/") + fileInfo.baseName();
exporter->SetFilePrefix(fileNameWithoutExt.toStdString().c_str());
exporter->Write();
}
<|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 (!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>Attempted fix for refcount in sideloaded font path<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(), adoptRef(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 <v8.h>
#include <node.h>
#include <cstdio>
//#ifdef __POSIX__
#include <unistd.h>
/*#else
#include <process.h>
#endif*/
using namespace node;
using namespace v8;
static int clear_cloexec (int desc)
{
int flags = fcntl (desc, F_GETFD, 0);
if (flags < 0)
return flags; //return if reading failed
flags &= ~FD_CLOEXEC; //clear FD_CLOEXEC bit
return fcntl (desc, F_SETFD, flags);
}
static Handle<Value> kexec(const Arguments& args) {
HandleScope scope;
String::Utf8Value v8str(args[0]);
char* argv[] = { const_cast<char *>(""), const_cast<char *>("-c"), *v8str, NULL};
clear_cloexec(0); //stdin
clear_cloexec(1); //stdout
clear_cloexec(2); //stderr
int err = execvp("/bin/sh", argv);
Local<Number> num = Number::New(err);
return scope.Close(num/*Undefined()*/);
}
extern "C" {
static void init (Handle<Object> target) {
NODE_SET_METHOD(target, "kexec", kexec);
}
NODE_MODULE(kexec, init);
}
<commit_msg>Fix execvp argv[0] convention.<commit_after>
#include <v8.h>
#include <node.h>
#include <cstdio>
//#ifdef __POSIX__
#include <unistd.h>
/*#else
#include <process.h>
#endif*/
using namespace node;
using namespace v8;
static int clear_cloexec (int desc)
{
int flags = fcntl (desc, F_GETFD, 0);
if (flags < 0)
return flags; //return if reading failed
flags &= ~FD_CLOEXEC; //clear FD_CLOEXEC bit
return fcntl (desc, F_SETFD, flags);
}
static Handle<Value> kexec(const Arguments& args) {
HandleScope scope;
String::Utf8Value v8str(args[0]);
char* argv[] = { const_cast<char *>("sh"), const_cast<char *>("-c"), *v8str, NULL};
clear_cloexec(0); //stdin
clear_cloexec(1); //stdout
clear_cloexec(2); //stderr
int err = execvp("/bin/sh", argv);
Local<Number> num = Number::New(err);
return scope.Close(num/*Undefined()*/);
}
extern "C" {
static void init (Handle<Object> target) {
NODE_SET_METHOD(target, "kexec", kexec);
}
NODE_MODULE(kexec, init);
}
<|endoftext|> |
<commit_before>/*
This file is part of Akregator.
Copyright (C) 2004 Sashmit Bhaduri <smt@vfemail.net>
This program is free software; you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation; either version 2 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program; if not, write to the Free Software
Foundation, Inc., 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 "tabwidget.h"
#include <QStyle>
#include <QApplication>
#include <QIcon>
#include <QClipboard>
#include <QHash>
#include <QString>
#include <QPushButton>
#include <QMenu>
#include <QStyleOption>
#include <kapplication.h>
#include <kdebug.h>
#include <ktabwidget.h>
#include <ktabbar.h>
#include <kmenu.h>
#include <krun.h>
#include <klocale.h>
#include <khtmlview.h>
#include <khtml_part.h>
#include <kiconloader.h>
#include <ktoolinvocation.h>
#include <kurl.h>
#include <kmimetype.h>
#include <kio/global.h>
#include "actionmanager.h"
#include "akregatorconfig.h"
#include "frame.h"
#include "framemanager.h"
#include "kernel.h"
#include "openurlrequest.h"
#include <cassert>
namespace Akregator {
class TabWidget::Private
{
private:
TabWidget* const q;
public:
explicit Private( TabWidget * qq ) : q( qq ) {}
TabWidget* parent;
QHash<QWidget*, Frame*> frames;
QHash<int, Frame*> framesById;
int currentMaxLength;
QWidget* currentItem;
QPushButton* tabsClose;
uint tabBarWidthForMaxChars(int maxLength);
void setTitle(const QString &title , QWidget* sender);
void updateTabBarVisibility();
Frame* currentFrame();
};
void TabWidget::Private::updateTabBarVisibility()
{
q->setTabBarHidden( q->count() <= 1 );
}
TabWidget::TabWidget(QWidget * parent)
:KTabWidget(parent), d(new Private( this ) )
{
d->parent = this;
d->currentMaxLength = 30;
setMinimumSize(250,150);
setTabReorderingEnabled(false);
connect( this, SIGNAL( currentChanged(QWidget *) ),
this, SLOT( slotTabChanged(QWidget *) ) );
connect(this, SIGNAL(closeRequest(QWidget*)),
this, SLOT(slotCloseRequest(QWidget*)));
setHoverCloseButton(Settings::closeButtonOnTabs());
d->tabsClose = new QPushButton(this);
d->tabsClose->setShortcut(QKeySequence("Ctrl+W"));
connect( d->tabsClose, SIGNAL( clicked() ), this,
SLOT( slotRemoveCurrentFrame() ) );
d->tabsClose->setIcon( KIcon( "tab-close" ) );
d->tabsClose->setEnabled( false );
d->tabsClose->adjustSize();
d->tabsClose->setToolTip( i18n("Close the current tab"));
setCornerWidget( d->tabsClose, Qt::TopRightCorner );
setTabBarHidden( true );
}
TabWidget::~TabWidget()
{
delete d;
}
void TabWidget::slotSettingsChanged()
{
if (hoverCloseButton() != Settings::closeButtonOnTabs())
setHoverCloseButton(Settings::closeButtonOnTabs());
}
void TabWidget::slotNextTab()
{
setCurrentIndex((currentIndex()+1) % count());
}
void TabWidget::slotPreviousTab()
{
if (currentIndex() == 0)
setCurrentIndex(count()-1);
else
setCurrentIndex(currentIndex()-1);
}
void TabWidget::slotSelectFrame(int frameId)
{
Frame* frame = d->framesById[frameId];
if (frame && frame != d->currentFrame())
{
setCurrentWidget(frame);
if (frame->part() && frame->part()->widget())
{
frame->part()->widget()->setFocus();
}
else
{
frame->setFocus();
}
}
}
void TabWidget::slotAddFrame(Frame* frame)
{
if (!frame)
return;
d->frames.insert(frame, frame);
d->framesById[frame->id()] = frame;
addTab(frame, frame->title());
connect(frame, SIGNAL(signalTitleChanged(Akregator::Frame*, const QString& )),
this, SLOT(slotSetTitle(Akregator::Frame*, const QString& )));
connect(frame, SIGNAL(signalPartDestroyed(int)), this, SLOT(slotRemoveFrame(int)));
slotSetTitle(frame, frame->title());
}
Frame * TabWidget::Private::currentFrame()
{
QWidget* w = q->currentWidget();
assert( frames[w] );
return w ? frames[w] : 0;
}
void TabWidget::slotTabChanged(QWidget *w)
{
Frame* frame = d->frames[w];
d->tabsClose->setEnabled(frame && frame->isRemovable());
emit signalCurrentFrameChanged(frame ? frame->id() : -1);
}
void TabWidget::tabInserted( int )
{
d->updateTabBarVisibility();
}
void TabWidget::tabRemoved( int )
{
d->updateTabBarVisibility();
}
void TabWidget::slotRemoveCurrentFrame()
{
Frame* const frame = d->currentFrame();
if (frame)
emit signalRemoveFrameRequest(frame->id());
}
void TabWidget::slotRemoveFrame(int frameId)
{
if (!d->framesById.contains(frameId))
return;
Frame* f = d->framesById[frameId];
d->frames.remove(f);
d->framesById.remove(frameId);
removeTab(indexOf(f));
if (d->currentFrame())
d->setTitle( d->currentFrame()->title(), currentWidget() );
}
// copied wholesale from KonqFrameTabs
uint TabWidget::Private::tabBarWidthForMaxChars( int maxLength )
{
int hframe, overlap;
QStyleOption o;
hframe = parent->tabBar()->style()->pixelMetric( QStyle::PM_TabBarTabHSpace, &o, parent );
overlap = parent->tabBar()->style()->pixelMetric( QStyle::PM_TabBarTabOverlap, &o, parent );
QFontMetrics fm = parent->tabBar()->fontMetrics();
int x = 0;
for (int i = 0; i < parent->count(); ++i)
{
Frame* f = frames[parent->widget(i)];
QString newTitle = f->title();
if ( newTitle.length() > maxLength )
newTitle = newTitle.left( maxLength-3 ) + "...";
int lw = fm.width( newTitle );
int iw = parent->tabBar()->tabIcon( i ).pixmap( parent->tabBar()->style()->pixelMetric(
QStyle::PM_SmallIconSize ), QIcon::Normal
).width() + 4;
x += ( parent->tabBar()->style()->sizeFromContents( QStyle::CT_TabBarTab, &o,
QSize( qMax( lw + hframe + iw, QApplication::globalStrut().width() ), 0 ), parent ) ).width();
}
return x;
}
void TabWidget::slotSetTitle(Frame* frame, const QString& title)
{
d->setTitle(title, frame);
}
void TabWidget::Private::setTitle( const QString &title, QWidget* sender)
{
int senderIndex = parent->indexOf(sender);
parent->setTabToolTip( senderIndex, QString() );
uint lcw=0, rcw=0;
int tabBarHeight = parent->tabBar()->sizeHint().height();
QWidget* leftCorner = parent->cornerWidget( Qt::TopLeftCorner );
if ( leftCorner && leftCorner->isVisible() )
lcw = qMax( leftCorner->width(), tabBarHeight );
QWidget* rightCorner = parent->cornerWidget( Qt::TopRightCorner );
if ( rightCorner && rightCorner->isVisible() )
rcw = qMax( rightCorner->width(), tabBarHeight );
uint maxTabBarWidth = parent->width() - lcw - rcw;
int newMaxLength = 30;
for ( ; newMaxLength > 3; newMaxLength-- )
{
if ( tabBarWidthForMaxChars( newMaxLength ) < maxTabBarWidth )
break;
}
QString newTitle = title;
if ( newTitle.length() > newMaxLength )
{
parent->setTabToolTip( senderIndex, newTitle );
newTitle = newTitle.left( newMaxLength-3 ) + "...";
}
newTitle.replace( '&', "&&" );
if ( parent->tabText(senderIndex) != newTitle )
parent->setTabText( senderIndex, newTitle );
if( newMaxLength != currentMaxLength )
{
for( int i = 0; i < parent->count(); ++i)
{
Frame* f = frames[parent->widget(i)];
newTitle = f->title();
int index = parent->indexOf(parent->widget( i ));
parent->setTabToolTip( index, QString() );
if ( newTitle.length() > newMaxLength )
{
parent->setTabToolTip( index, newTitle );
newTitle = newTitle.left( newMaxLength-3 ) + "...";
}
newTitle.replace( '&', "&&" );
if ( newTitle != parent->tabText( index ) )
parent->setTabText( index, newTitle );
}
currentMaxLength = newMaxLength;
}
}
void TabWidget::contextMenu(int i, const QPoint &p)
{
QWidget* w = ActionManager::getInstance()->container("tab_popup");
d->currentItem = widget(i);
//kDebug() << indexOf(d->currentItem);
// FIXME: do not hardcode index of maintab
if (w && indexOf(d->currentItem) != 0)
static_cast<QMenu *>(w)->exec(p);
d->currentItem = 0;
}
void TabWidget::slotDetachTab()
{
if (!d->currentItem || indexOf(d->currentItem) == -1)
d->currentItem = currentWidget();
Frame* frame = d->frames[d->currentItem];
if (frame && frame->url().isValid() && frame->isRemovable())
{
OpenUrlRequest request;
request.setUrl(frame->url());
request.setOptions(OpenUrlRequest::ExternalBrowser);
emit signalOpenUrlRequest(request);
slotCloseTab();
}
}
void TabWidget::slotCopyLinkAddress()
{
if(!d->currentItem || indexOf(d->currentItem) == -1)
d->currentItem = currentWidget();
Frame* frame = d->frames[d->currentItem];
if (frame && frame->url().isValid())
{
KUrl url = frame->url();
// don't set url to selection as it's a no-no according to a fd.o spec
//kapp->clipboard()->setText(url.prettyUrl(), QClipboard::Selection);
kapp->clipboard()->setText(url.prettyUrl(), QClipboard::Clipboard);
}
}
void TabWidget::slotCloseTab()
{
if (!d->currentItem || indexOf(d->currentItem) == -1)
d->currentItem = currentWidget();
if (d->frames[d->currentItem] == 0 || !d->frames[d->currentItem]->isRemovable() )
return;
emit signalRemoveFrameRequest(d->frames[d->currentItem]->id());
}
void TabWidget::initiateDrag(int tab)
{
Frame* frame = d->frames[widget(tab)];
if (frame && frame->url().isValid())
{
KUrl::List lst;
lst.append( frame->url() );
QDrag* drag = new QDrag( this );
QMimeData *md = new QMimeData;
drag->setMimeData( md );
lst.populateMimeData( md );
drag->setPixmap( KIO::pixmapForUrl( lst.first(), 0, KIconLoader::Small ) );
drag->start();
}
}
void TabWidget::slotCloseRequest(QWidget* widget)
{
if (d->frames[widget])
emit signalRemoveFrameRequest(d->frames[widget]->id());
}
} // namespace Akregator
#include "tabwidget.moc"
<commit_msg>backport from trunk:<commit_after>/*
This file is part of Akregator.
Copyright (C) 2004 Sashmit Bhaduri <smt@vfemail.net>
This program is free software; you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation; either version 2 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program; if not, write to the Free Software
Foundation, Inc., 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 "tabwidget.h"
#include <QStyle>
#include <QApplication>
#include <QIcon>
#include <QClipboard>
#include <QHash>
#include <QString>
#include <QPushButton>
#include <QMenu>
#include <QStyleOption>
#include <kapplication.h>
#include <kdebug.h>
#include <ktabwidget.h>
#include <ktabbar.h>
#include <kmenu.h>
#include <krun.h>
#include <klocale.h>
#include <khtmlview.h>
#include <khtml_part.h>
#include <kiconloader.h>
#include <ktoolinvocation.h>
#include <kurl.h>
#include <kmimetype.h>
#include <kio/global.h>
#include "actionmanager.h"
#include "akregatorconfig.h"
#include "frame.h"
#include "framemanager.h"
#include "kernel.h"
#include "openurlrequest.h"
#include <cassert>
namespace Akregator {
class TabWidget::Private
{
private:
TabWidget* const q;
public:
explicit Private( TabWidget * qq ) : q( qq ) {}
TabWidget* parent;
QHash<QWidget*, Frame*> frames;
QHash<int, Frame*> framesById;
int currentMaxLength;
QWidget* currentItem;
QPushButton* tabsClose;
uint tabBarWidthForMaxChars(int maxLength);
void setTitle(const QString &title , QWidget* sender);
void updateTabBarVisibility();
Frame* currentFrame();
};
void TabWidget::Private::updateTabBarVisibility()
{
q->setTabBarHidden( q->count() <= 1 );
}
TabWidget::TabWidget(QWidget * parent)
:KTabWidget(parent), d(new Private( this ) )
{
d->parent = this;
d->currentMaxLength = 30;
setMinimumSize(250,150);
setTabReorderingEnabled(false);
connect( this, SIGNAL( currentChanged(QWidget *) ),
this, SLOT( slotTabChanged(QWidget *) ) );
connect(this, SIGNAL(closeRequest(QWidget*)),
this, SLOT(slotCloseRequest(QWidget*)));
setHoverCloseButton(Settings::closeButtonOnTabs());
d->tabsClose = new QPushButton(this);
d->tabsClose->setShortcut(QKeySequence("Ctrl+W"));
connect( d->tabsClose, SIGNAL( clicked() ), this,
SLOT( slotRemoveCurrentFrame() ) );
d->tabsClose->setIcon( KIcon( "tab-close" ) );
d->tabsClose->setEnabled( false );
d->tabsClose->adjustSize();
d->tabsClose->setToolTip( i18n("Close the current tab"));
setCornerWidget( d->tabsClose, Qt::TopRightCorner );
setTabBarHidden( true );
}
TabWidget::~TabWidget()
{
delete d;
}
void TabWidget::slotSettingsChanged()
{
if (hoverCloseButton() != Settings::closeButtonOnTabs())
setHoverCloseButton(Settings::closeButtonOnTabs());
}
void TabWidget::slotNextTab()
{
setCurrentIndex((currentIndex()+1) % count());
}
void TabWidget::slotPreviousTab()
{
if (currentIndex() == 0)
setCurrentIndex(count()-1);
else
setCurrentIndex(currentIndex()-1);
}
void TabWidget::slotSelectFrame(int frameId)
{
Frame* frame = d->framesById[frameId];
if (frame && frame != d->currentFrame())
{
setCurrentWidget(frame);
if (frame->part() && frame->part()->widget())
{
frame->part()->widget()->setFocus();
}
else
{
frame->setFocus();
}
}
}
void TabWidget::slotAddFrame(Frame* frame)
{
if (!frame)
return;
d->frames.insert(frame, frame);
d->framesById[frame->id()] = frame;
addTab(frame, frame->title());
connect(frame, SIGNAL(signalTitleChanged(Akregator::Frame*, const QString& )),
this, SLOT(slotSetTitle(Akregator::Frame*, const QString& )));
if(frame->id() > 0) // MainFrame doesn't emit signalPartDestroyed signals, neither should it
connect(frame, SIGNAL(signalPartDestroyed(int)), this, SLOT(slotRemoveFrame(int)));
slotSetTitle(frame, frame->title());
}
Frame * TabWidget::Private::currentFrame()
{
QWidget* w = q->currentWidget();
assert( frames[w] );
return w ? frames[w] : 0;
}
void TabWidget::slotTabChanged(QWidget *w)
{
Frame* frame = d->frames[w];
d->tabsClose->setEnabled(frame && frame->isRemovable());
emit signalCurrentFrameChanged(frame ? frame->id() : -1);
}
void TabWidget::tabInserted( int )
{
d->updateTabBarVisibility();
}
void TabWidget::tabRemoved( int )
{
d->updateTabBarVisibility();
}
void TabWidget::slotRemoveCurrentFrame()
{
Frame* const frame = d->currentFrame();
if (frame)
emit signalRemoveFrameRequest(frame->id());
}
void TabWidget::slotRemoveFrame(int frameId)
{
if (!d->framesById.contains(frameId))
return;
Frame* f = d->framesById[frameId];
d->frames.remove(f);
d->framesById.remove(frameId);
removeTab(indexOf(f));
f->deleteLater(); // removeTab doesn't remove the widget, so let's do it ourselves
if (d->currentFrame())
d->setTitle( d->currentFrame()->title(), currentWidget() );
}
// copied wholesale from KonqFrameTabs
uint TabWidget::Private::tabBarWidthForMaxChars( int maxLength )
{
int hframe, overlap;
QStyleOption o;
hframe = parent->tabBar()->style()->pixelMetric( QStyle::PM_TabBarTabHSpace, &o, parent );
overlap = parent->tabBar()->style()->pixelMetric( QStyle::PM_TabBarTabOverlap, &o, parent );
QFontMetrics fm = parent->tabBar()->fontMetrics();
int x = 0;
for (int i = 0; i < parent->count(); ++i)
{
Frame* f = frames[parent->widget(i)];
QString newTitle = f->title();
if ( newTitle.length() > maxLength )
newTitle = newTitle.left( maxLength-3 ) + "...";
int lw = fm.width( newTitle );
int iw = parent->tabBar()->tabIcon( i ).pixmap( parent->tabBar()->style()->pixelMetric(
QStyle::PM_SmallIconSize ), QIcon::Normal
).width() + 4;
x += ( parent->tabBar()->style()->sizeFromContents( QStyle::CT_TabBarTab, &o,
QSize( qMax( lw + hframe + iw, QApplication::globalStrut().width() ), 0 ), parent ) ).width();
}
return x;
}
void TabWidget::slotSetTitle(Frame* frame, const QString& title)
{
d->setTitle(title, frame);
}
void TabWidget::Private::setTitle( const QString &title, QWidget* sender)
{
int senderIndex = parent->indexOf(sender);
parent->setTabToolTip( senderIndex, QString() );
uint lcw=0, rcw=0;
int tabBarHeight = parent->tabBar()->sizeHint().height();
QWidget* leftCorner = parent->cornerWidget( Qt::TopLeftCorner );
if ( leftCorner && leftCorner->isVisible() )
lcw = qMax( leftCorner->width(), tabBarHeight );
QWidget* rightCorner = parent->cornerWidget( Qt::TopRightCorner );
if ( rightCorner && rightCorner->isVisible() )
rcw = qMax( rightCorner->width(), tabBarHeight );
uint maxTabBarWidth = parent->width() - lcw - rcw;
int newMaxLength = 30;
for ( ; newMaxLength > 3; newMaxLength-- )
{
if ( tabBarWidthForMaxChars( newMaxLength ) < maxTabBarWidth )
break;
}
QString newTitle = title;
if ( newTitle.length() > newMaxLength )
{
parent->setTabToolTip( senderIndex, newTitle );
newTitle = newTitle.left( newMaxLength-3 ) + "...";
}
newTitle.replace( '&', "&&" );
if ( parent->tabText(senderIndex) != newTitle )
parent->setTabText( senderIndex, newTitle );
if( newMaxLength != currentMaxLength )
{
for( int i = 0; i < parent->count(); ++i)
{
Frame* f = frames[parent->widget(i)];
newTitle = f->title();
int index = parent->indexOf(parent->widget( i ));
parent->setTabToolTip( index, QString() );
if ( newTitle.length() > newMaxLength )
{
parent->setTabToolTip( index, newTitle );
newTitle = newTitle.left( newMaxLength-3 ) + "...";
}
newTitle.replace( '&', "&&" );
if ( newTitle != parent->tabText( index ) )
parent->setTabText( index, newTitle );
}
currentMaxLength = newMaxLength;
}
}
void TabWidget::contextMenu(int i, const QPoint &p)
{
QWidget* w = ActionManager::getInstance()->container("tab_popup");
d->currentItem = widget(i);
//kDebug() << indexOf(d->currentItem);
// FIXME: do not hardcode index of maintab
if (w && indexOf(d->currentItem) != 0)
static_cast<QMenu *>(w)->exec(p);
d->currentItem = 0;
}
void TabWidget::slotDetachTab()
{
if (!d->currentItem || indexOf(d->currentItem) == -1)
d->currentItem = currentWidget();
Frame* frame = d->frames[d->currentItem];
if (frame && frame->url().isValid() && frame->isRemovable())
{
OpenUrlRequest request;
request.setUrl(frame->url());
request.setOptions(OpenUrlRequest::ExternalBrowser);
emit signalOpenUrlRequest(request);
slotCloseTab();
}
}
void TabWidget::slotCopyLinkAddress()
{
if(!d->currentItem || indexOf(d->currentItem) == -1)
d->currentItem = currentWidget();
Frame* frame = d->frames[d->currentItem];
if (frame && frame->url().isValid())
{
KUrl url = frame->url();
// don't set url to selection as it's a no-no according to a fd.o spec
//kapp->clipboard()->setText(url.prettyUrl(), QClipboard::Selection);
kapp->clipboard()->setText(url.prettyUrl(), QClipboard::Clipboard);
}
}
void TabWidget::slotCloseTab()
{
if (!d->currentItem || indexOf(d->currentItem) == -1)
d->currentItem = currentWidget();
if (d->frames[d->currentItem] == 0 || !d->frames[d->currentItem]->isRemovable() )
return;
emit signalRemoveFrameRequest(d->frames[d->currentItem]->id());
}
void TabWidget::initiateDrag(int tab)
{
Frame* frame = d->frames[widget(tab)];
if (frame && frame->url().isValid())
{
KUrl::List lst;
lst.append( frame->url() );
QDrag* drag = new QDrag( this );
QMimeData *md = new QMimeData;
drag->setMimeData( md );
lst.populateMimeData( md );
drag->setPixmap( KIO::pixmapForUrl( lst.first(), 0, KIconLoader::Small ) );
drag->start();
}
}
void TabWidget::slotCloseRequest(QWidget* widget)
{
if (d->frames[widget])
emit signalRemoveFrameRequest(d->frames[widget]->id());
}
} // namespace Akregator
#include "tabwidget.moc"
<|endoftext|> |
<commit_before>#include <sys/types.h>
#include <dirent.h>
#include <fstream>
#include <iomanip>
#include <iostream>
#include <sstream>
#include <regex>
#include <vector>
#include <string>
#include "list.h"
#include "bpftrace.h"
namespace bpftrace {
const std::string kprobe_path = "/sys/kernel/debug/tracing/available_filter_functions";
const std::string tp_path = "/sys/kernel/debug/tracing/events";
std::string replace_all(const std::string &str, const std::string &from,
const std::string &to)
{
std::string result(str);
std::string::size_type
index = 0,
from_len = from.size(),
to_len = to.size();
while ((index = result.find(from, index)) != std::string::npos) {
result.replace(index, from_len, to);
index += to_len;
}
return result;
}
bool search_probe(const std::string &probe, const std::string& search)
{
try {
std::string glob = "*";
std::string regex = ".*";
std::string s = replace_all(search,glob,regex);
glob = "?";
regex = ".";
s = replace_all(s,glob,regex);
s = "^" + s + "$";
std::regex re(s, std::regex::icase | std::regex::grep | std::regex::nosubs);
if (std::regex_search(probe, re))
return false;
else
return true;
} catch(std::regex_error& e) {
return true;
}
}
void list_dir(const std::string path, std::vector<std::string> &files)
{
// yes, I know about std::filesystem::directory_iterator, but no, it wasn't available
DIR *dp;
struct dirent *dep;
if ((dp = opendir(path.c_str())) == NULL)
return;
while ((dep = readdir(dp)) != NULL)
files.push_back(std::string(dep->d_name));
closedir(dp);
}
void list_probes_from_list(const std::vector<ProbeListItem> &probes_list,
const std::string &probetype, const std::string &search)
{
for (auto &probeListItem : probes_list)
{
if (!search.empty())
{
if (search_probe(probeListItem.path, search) && search_probe(probeListItem.alias, search))
continue;
}
std::cout << probetype << ":" << probeListItem.path << ":" << std::endl;
}
}
void list_probes(const std::string &search)
{
unsigned int i, j;
std::string line, probe;
// software
list_probes_from_list(SW_PROBE_LIST, "software", search);
// hardware
std::cout << std::endl;
list_probes_from_list(HW_PROBE_LIST, "hardware", search);
// tracepoints
std::cout << std::endl;
std::vector<std::string> cats = std::vector<std::string>();
list_dir(tp_path, cats);
for (i = 0; i < cats.size(); i++)
{
if (cats[i] == "." || cats[i] == ".." || cats[i] == "enable" || cats[i] == "filter")
continue;
std::vector<std::string> events = std::vector<std::string>();
list_dir(tp_path + "/" + cats[i], events);
for (j = 0; j < events.size(); j++)
{
if (events[j] == "." || events[j] == ".." || events[j] == "enable" || events[j] == "filter")
continue;
probe = "tracepoint:" + cats[i] + ":" + events[j];
if (!search.empty())
{
if (search_probe(probe, search))
continue;
}
std::cout << probe << std::endl;
}
}
// kprobes
std::cout << std::endl;
std::ifstream file(kprobe_path);
if (file.fail())
{
std::cerr << strerror(errno) << ": " << kprobe_path << std::endl;
return;
}
size_t loc;
while (std::getline(file, line))
{
loc = line.find_first_of(" ");
if (loc == std::string::npos)
probe = "kprobe:" + line;
else
probe = "kprobe:" + line.substr(0, loc);
if (!search.empty())
{
if (search_probe(probe, search))
continue;
}
std::cout << probe << std::endl;
}
}
void list_probes()
{
const std::string search = "";
list_probes(search);
}
} // namespace bpftrace
<commit_msg>remove unnecessary newlines in -l<commit_after>#include <sys/types.h>
#include <dirent.h>
#include <fstream>
#include <iomanip>
#include <iostream>
#include <sstream>
#include <regex>
#include <vector>
#include <string>
#include "list.h"
#include "bpftrace.h"
namespace bpftrace {
const std::string kprobe_path = "/sys/kernel/debug/tracing/available_filter_functions";
const std::string tp_path = "/sys/kernel/debug/tracing/events";
std::string replace_all(const std::string &str, const std::string &from,
const std::string &to)
{
std::string result(str);
std::string::size_type
index = 0,
from_len = from.size(),
to_len = to.size();
while ((index = result.find(from, index)) != std::string::npos) {
result.replace(index, from_len, to);
index += to_len;
}
return result;
}
bool search_probe(const std::string &probe, const std::string& search)
{
try {
std::string glob = "*";
std::string regex = ".*";
std::string s = replace_all(search,glob,regex);
glob = "?";
regex = ".";
s = replace_all(s,glob,regex);
s = "^" + s + "$";
std::regex re(s, std::regex::icase | std::regex::grep | std::regex::nosubs);
if (std::regex_search(probe, re))
return false;
else
return true;
} catch(std::regex_error& e) {
return true;
}
}
void list_dir(const std::string path, std::vector<std::string> &files)
{
// yes, I know about std::filesystem::directory_iterator, but no, it wasn't available
DIR *dp;
struct dirent *dep;
if ((dp = opendir(path.c_str())) == NULL)
return;
while ((dep = readdir(dp)) != NULL)
files.push_back(std::string(dep->d_name));
closedir(dp);
}
void list_probes_from_list(const std::vector<ProbeListItem> &probes_list,
const std::string &probetype, const std::string &search)
{
for (auto &probeListItem : probes_list)
{
if (!search.empty())
{
if (search_probe(probeListItem.path, search) && search_probe(probeListItem.alias, search))
continue;
}
std::cout << probetype << ":" << probeListItem.path << ":" << std::endl;
}
}
void list_probes(const std::string &search)
{
unsigned int i, j;
std::string line, probe;
// software
list_probes_from_list(SW_PROBE_LIST, "software", search);
// hardware
list_probes_from_list(HW_PROBE_LIST, "hardware", search);
// tracepoints
std::vector<std::string> cats = std::vector<std::string>();
list_dir(tp_path, cats);
for (i = 0; i < cats.size(); i++)
{
if (cats[i] == "." || cats[i] == ".." || cats[i] == "enable" || cats[i] == "filter")
continue;
std::vector<std::string> events = std::vector<std::string>();
list_dir(tp_path + "/" + cats[i], events);
for (j = 0; j < events.size(); j++)
{
if (events[j] == "." || events[j] == ".." || events[j] == "enable" || events[j] == "filter")
continue;
probe = "tracepoint:" + cats[i] + ":" + events[j];
if (!search.empty())
{
if (search_probe(probe, search))
continue;
}
std::cout << probe << std::endl;
}
}
// kprobes
std::ifstream file(kprobe_path);
if (file.fail())
{
std::cerr << strerror(errno) << ": " << kprobe_path << std::endl;
return;
}
size_t loc;
while (std::getline(file, line))
{
loc = line.find_first_of(" ");
if (loc == std::string::npos)
probe = "kprobe:" + line;
else
probe = "kprobe:" + line.substr(0, loc);
if (!search.empty())
{
if (search_probe(probe, search))
continue;
}
std::cout << probe << std::endl;
}
}
void list_probes()
{
const std::string search = "";
list_probes(search);
}
} // namespace bpftrace
<|endoftext|> |
<commit_before><commit_msg>modified feature_2<commit_after>#include <stdio.h><|endoftext|> |
<commit_before>
#include <togo/assert.hpp>
#include <togo/log.hpp>
#include <togo/fixed_array.hpp>
#include <togo/string.hpp>
#include <togo/system.hpp>
using namespace togo;
signed main() {
TOGO_LOGF("num_cores = %u\n", system::num_cores());
StringRef exec_dir = system::exec_dir();
TOGO_LOGF("exec_dir: '%.*s'\n", exec_dir.size, exec_dir.data);
TOGO_ASSERTE(system::secs_since_epoch() > 1407135980u);
StringRef const env_path = system::environment_variable("PATH");
TOGO_LOGF("PATH = '%.*s'\n", env_path.size, env_path.data);
StringRef const env_test_name = "__TOGO_TEST";
// Base state of unassigned variable
StringRef env_test_value = system::environment_variable(env_test_name);
TOGO_ASSERTE(!env_test_value.valid());
// Assignment
TOGO_ASSERTE(system::set_environment_variable(env_test_name, "test"));
env_test_value = system::environment_variable(env_test_name);
TOGO_ASSERTE(string::compare_equal(env_test_value, "test"));
// Removal (return to unassigned state)
TOGO_ASSERTE(system::remove_environment_variable(env_test_name));
env_test_value = system::environment_variable(env_test_name);
TOGO_ASSERTE(!env_test_value.valid());
FixedArray<char, 256> wd_init{};
unsigned const wd_init_size = system::working_dir(wd_init);
TOGO_LOGF("wd_init: '%.*s'\n", string::size(wd_init), fixed_array::begin(wd_init));
TOGO_ASSERTE(wd_init_size > 0 && wd_init_size == fixed_array::size(wd_init));
TOGO_ASSERTE(system::set_working_dir("/"));
FixedArray<char, 256> wd_root{};
unsigned const wd_root_size = system::working_dir(wd_root);
TOGO_LOGF("wd_root: '%.*s'\n", string::size(wd_root), fixed_array::begin(wd_root));
TOGO_ASSERTE(wd_root_size > 0 && wd_root_size == fixed_array::size(wd_root));
TOGO_ASSERTE(string::compare_equal(wd_root, "/"));
TOGO_ASSERTE(system::set_working_dir(exec_dir));
TOGO_ASSERTE(!system::is_file("/non/existent/file"));
TOGO_ASSERTE(!system::is_file("."));
#if defined(TOGO_PLATFORM_LINUX)
TOGO_ASSERTE(system::is_file("general.elf"));
#elif defined(TOGO_PLATFORM_WINDOWS)
TOGO_ASSERTE(system::is_file("general.exe"));
#endif
TOGO_ASSERTE(!system::is_directory("/non/existent/directory"));
TOGO_ASSERTE( system::is_directory("."));
TOGO_ASSERTE( system::is_directory(".."));
TOGO_LOG("\n");
float const start = system::time_monotonic();
system::sleep_ms(1000u);
float const d_1000ms = system::time_monotonic() - start;
system::sleep_ms(100u);
float const d_100ms = system::time_monotonic() - start;
system::sleep_ms(10u);
float const d_10ms = system::time_monotonic() - start;
system::sleep_ms(1u);
float const d_1ms = system::time_monotonic() - start;
TOGO_LOGF("start : time_monotonic() = %.6f\n", start);
TOGO_LOGF("1000ms delay: time_monotonic() = %.6f\n", d_1000ms);
TOGO_LOGF("100ms delay : time_monotonic() = %.6f\n", d_100ms);
TOGO_LOGF("10ms delay : time_monotonic() = %.6f\n", d_10ms);
TOGO_LOGF("1ms delay : time_monotonic() = %.6f\n", d_1ms);
return 0;
}
<commit_msg>test/system/general: added file & directory creation & removal tests.<commit_after>
#include <togo/assert.hpp>
#include <togo/log.hpp>
#include <togo/fixed_array.hpp>
#include <togo/string.hpp>
#include <togo/system.hpp>
using namespace togo;
signed main() {
TOGO_LOGF("num_cores = %u\n", system::num_cores());
StringRef exec_dir = system::exec_dir();
TOGO_LOGF("exec_dir: '%.*s'\n", exec_dir.size, exec_dir.data);
TOGO_ASSERTE(system::secs_since_epoch() > 1407135980u);
StringRef const env_path = system::environment_variable("PATH");
TOGO_LOGF("PATH = '%.*s'\n", env_path.size, env_path.data);
StringRef const env_test_name = "__TOGO_TEST";
// Base state of unassigned variable
StringRef env_test_value = system::environment_variable(env_test_name);
TOGO_ASSERTE(!env_test_value.valid());
// Assignment
TOGO_ASSERTE(system::set_environment_variable(env_test_name, "test"));
env_test_value = system::environment_variable(env_test_name);
TOGO_ASSERTE(string::compare_equal(env_test_value, "test"));
// Removal (return to unassigned state)
TOGO_ASSERTE(system::remove_environment_variable(env_test_name));
env_test_value = system::environment_variable(env_test_name);
TOGO_ASSERTE(!env_test_value.valid());
FixedArray<char, 256> wd_init{};
unsigned const wd_init_size = system::working_dir(wd_init);
TOGO_LOGF("wd_init: '%.*s'\n", string::size(wd_init), fixed_array::begin(wd_init));
TOGO_ASSERTE(wd_init_size > 0 && wd_init_size == fixed_array::size(wd_init));
TOGO_ASSERTE(system::set_working_dir("/"));
FixedArray<char, 256> wd_root{};
unsigned const wd_root_size = system::working_dir(wd_root);
TOGO_LOGF("wd_root: '%.*s'\n", string::size(wd_root), fixed_array::begin(wd_root));
TOGO_ASSERTE(wd_root_size > 0 && wd_root_size == fixed_array::size(wd_root));
TOGO_ASSERTE(string::compare_equal(wd_root, "/"));
TOGO_ASSERTE(system::set_working_dir(exec_dir));
TOGO_ASSERTE(!system::is_file("/non/existent/file"));
TOGO_ASSERTE(!system::is_file("."));
#if defined(TOGO_PLATFORM_LINUX)
TOGO_ASSERTE(system::is_file("general.elf"));
#elif defined(TOGO_PLATFORM_WINDOWS)
TOGO_ASSERTE(system::is_file("general.exe"));
#endif
TOGO_ASSERTE(!system::is_directory("/non/existent/directory"));
TOGO_ASSERTE( system::is_directory("."));
TOGO_ASSERTE( system::is_directory(".."));
#define TEST_DIR "test_dir"
#define TEST_FILE TEST_DIR "/test_file"
// Directory creation
TOGO_ASSERTE(!system::is_directory(TEST_DIR));
TOGO_ASSERTE(system::create_directory(TEST_DIR));
TOGO_ASSERTE(system::is_directory(TEST_DIR));
TOGO_ASSERTE(!system::create_directory(TEST_DIR));
// File creation
TOGO_ASSERTE(!system::is_file(TEST_FILE));
TOGO_ASSERTE(system::create_file(TEST_FILE));
TOGO_ASSERTE(system::is_file(TEST_FILE));
TOGO_ASSERTE(!system::create_file(TEST_FILE));
// File removal
TOGO_ASSERTE(system::remove_file(TEST_FILE));
TOGO_ASSERTE(!system::is_file(TEST_FILE));
TOGO_ASSERTE(!system::remove_file(TEST_FILE));
// Directory removal
TOGO_ASSERTE(system::remove_directory(TEST_DIR));
TOGO_ASSERTE(!system::is_directory(TEST_DIR));
TOGO_ASSERTE(!system::remove_directory(TEST_DIR));
TOGO_LOG("\n");
float const start = system::time_monotonic();
system::sleep_ms(1000u);
float const d_1000ms = system::time_monotonic() - start;
system::sleep_ms(100u);
float const d_100ms = system::time_monotonic() - start;
system::sleep_ms(10u);
float const d_10ms = system::time_monotonic() - start;
system::sleep_ms(1u);
float const d_1ms = system::time_monotonic() - start;
TOGO_LOGF("start : time_monotonic() = %.6f\n", start);
TOGO_LOGF("1000ms delay: time_monotonic() = %.6f\n", d_1000ms);
TOGO_LOGF("100ms delay : time_monotonic() = %.6f\n", d_100ms);
TOGO_LOGF("10ms delay : time_monotonic() = %.6f\n", d_10ms);
TOGO_LOGF("1ms delay : time_monotonic() = %.6f\n", d_1ms);
return 0;
}
<|endoftext|> |
<commit_before>// Copyright (c) 2013, Zeex
// 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 <ctime>
#include <iomanip>
#include <iostream>
#include "time_utils.h"
namespace amx_profiler {
std::time_t TimeStamp::Now() {
return std::time(0);
}
TimeStamp::TimeStamp()
: value_(Now())
{
}
TimeStamp::TimeStamp(std::time_t value)
: value_(value)
{
}
const char *CTime(TimeStamp ts) {
std::time_t now = TimeStamp::Now();
char *string = const_cast<char*>(std::ctime(&now));
string[kCTimeResultLength] = '\0';
return string;
}
TimeSpan::TimeSpan(Seconds d) {
hours_ = static_cast<int>(Hours(d).count());
d -= Hours(hours_);
minutes_ = static_cast<int>(Minutes(d).count());
d -= Minutes(minutes_);
seconds_ = static_cast<int>(Seconds(d).count());
d -= Seconds(seconds_);
}
std::ostream &operator<<(std::ostream &os, const TimeSpan &time) {
os << std::setw(2) << std::setfill('0') << time.hours() << ':'
<< std::setw(2) << std::setfill('0') << time.minutes() << ':'
<< std::setw(2) << std::setfill('0') << time.seconds();
return os;
}
} // namespace amx_profiler
<commit_msg>Fix TimeSpan permanently setting stream fill character<commit_after>// Copyright (c) 2013, Zeex
// 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 <ctime>
#include <iomanip>
#include <iostream>
#include "time_utils.h"
namespace amx_profiler {
std::time_t TimeStamp::Now() {
return std::time(0);
}
TimeStamp::TimeStamp()
: value_(Now())
{
}
TimeStamp::TimeStamp(std::time_t value)
: value_(value)
{
}
const char *CTime(TimeStamp ts) {
std::time_t now = TimeStamp::Now();
char *string = const_cast<char*>(std::ctime(&now));
string[kCTimeResultLength] = '\0';
return string;
}
TimeSpan::TimeSpan(Seconds d) {
hours_ = static_cast<int>(Hours(d).count());
d -= Hours(hours_);
minutes_ = static_cast<int>(Minutes(d).count());
d -= Minutes(minutes_);
seconds_ = static_cast<int>(Seconds(d).count());
d -= Seconds(seconds_);
}
std::ostream &operator<<(std::ostream &os, const TimeSpan &time) {
char fill = os.fill('0');
os << std::setw(2) << time.hours() << ':'
<< std::setw(2) << time.minutes() << ':'
<< std::setw(2) << time.seconds();
os.fill(fill);
return os;
}
} // namespace amx_profiler
<|endoftext|> |
<commit_before>#include <test/unit/math/test_ad.hpp>
TEST(mathMixMatFun, Phi) {
auto f = [](const auto& x1) { return stan::math::Phi(x1); };
stan::test::expect_common_unary_vectorized(f);
stan::test::expect_unary_vectorized(f, -27.5, 27.5);
for (double x = -37.5; x <= 10; x += 0.5)
stan::test::expect_unary_vectorized(x);
}
TEST(mathMixMatFun, Phi_varmat) {
using stan::math::vec_concat;
using stan::test::expect_ad_vector_matvar;
using stan::test::internal::common_nonzero_args;
auto f = [](const auto& x1) {
using stan::math::Phi;
return Phi(x1);
};
std::vector<double> com_args = common_nonzero_args();
std::vector<double> args{-27.5, -0.5, 0.0, 1.1 27.5};
auto all_args = vec_concat(com_args, args);
Eigen::VectorXd A(all_args.size());
for (int i = 0; i < all_args.size(); ++i) {
A(i) = all_args[i];
}
expect_ad_vector_matvar(f, A);
}
<commit_msg>Added missing comma (Issue #1805)<commit_after>#include <test/unit/math/test_ad.hpp>
TEST(mathMixMatFun, Phi) {
auto f = [](const auto& x1) { return stan::math::Phi(x1); };
stan::test::expect_common_unary_vectorized(f);
stan::test::expect_unary_vectorized(f, -27.5, 27.5);
for (double x = -37.5; x <= 10; x += 0.5)
stan::test::expect_unary_vectorized(x);
}
TEST(mathMixMatFun, Phi_varmat) {
using stan::math::vec_concat;
using stan::test::expect_ad_vector_matvar;
using stan::test::internal::common_nonzero_args;
auto f = [](const auto& x1) {
using stan::math::Phi;
return Phi(x1);
};
std::vector<double> com_args = common_nonzero_args();
std::vector<double> args{-27.5, -0.5, 0.0, 1.1, 27.5};
auto all_args = vec_concat(com_args, args);
Eigen::VectorXd A(all_args.size());
for (int i = 0; i < all_args.size(); ++i) {
A(i) = all_args[i];
}
expect_ad_vector_matvar(f, A);
}
<|endoftext|> |
<commit_before>//
// leaf-node-collada.cpp
// gepetto-viewer
//
// Created by Anthony Couret, Mathieu Geisert in November 2014.
// Copyright (c) 2014 LAAS-CNRS. All rights reserved.
//
#include <sys/stat.h>
#include <fstream>
#include <ios>
#include <gepetto/viewer/leaf-node-collada.h>
namespace graphics {
inline bool fileExists (const char* fn)
{ struct stat buffer; return (stat (fn, &buffer) == 0); }
std::string getCachedFileName (const std::string& meshfile)
{
static const std::string exts[3] = { ".osg", ".osg2", ".osgb" };
for (int i = 0; i < 3; ++i) {
std::string cached = meshfile + exts[i];
if (fileExists(cached.c_str())) return cached;
}
return std::string();
}
/* Declaration of private function members */
void LeafNodeCollada::init()
{
if (!fileExists(collada_file_path_.c_str()))
throw std::invalid_argument(std::string("File ") + collada_file_path_ + std::string(" not found."));
std::string osgname = getCachedFileName(collada_file_path_);
if (!osgname.empty()) {
std::cout << "Using " << osgname << std::endl;
collada_ptr_ = osgDB::readNodeFile(osgname);
} else {
// get the extension of the meshs file
std::string ext = collada_file_path_.substr(collada_file_path_.find_last_of(".")+1,collada_file_path_.size());
if(ext == "obj"){
const osgDB::Options* options = new osgDB::Options("noRotation");
collada_ptr_ = osgDB::readNodeFile(collada_file_path_,options);
}
else
collada_ptr_ = osgDB::readNodeFile(collada_file_path_);
}
if (!collada_ptr_)
throw std::invalid_argument(std::string("File ") + collada_file_path_ + std::string(" found but could not be opened. Check that a plugin exist."));
/* Create PositionAttitudeTransform */
this->asQueue()->addChild(collada_ptr_);
/* Allow transparency */
if (collada_ptr_->getOrCreateStateSet())
{
collada_ptr_->getOrCreateStateSet()->setMode(GL_BLEND, ::osg::StateAttribute::ON);
}
addProperty(StringProperty::create("Meshfile path",
StringProperty::getterFromMemberFunction(this, &LeafNodeCollada::meshFilePath),
StringProperty::Setter_t()));
}
LeafNodeCollada::LeafNodeCollada(const std::string& name, const std::string& collada_file_path) :
Node(name), collada_file_path_(collada_file_path)
{
init();
}
LeafNodeCollada::LeafNodeCollada(const std::string& name, const std::string& collada_file_path, const osgVector4& color) :
Node(name), collada_file_path_(collada_file_path)
{
init();
setColor(color);
}
LeafNodeCollada::LeafNodeCollada(const LeafNodeCollada& other) :
Node(other.getID()), collada_file_path_(other.collada_file_path_)
{
init();
}
void LeafNodeCollada::initWeakPtr(LeafNodeColladaWeakPtr other_weak_ptr)
{
weak_ptr_ = other_weak_ptr;
}
/* End of declaration of private function members */
/* Declaration of protected function members */
LeafNodeColladaPtr_t LeafNodeCollada::create(const std::string& name, const std::string& collada_file_path)
{
std::ifstream infile(collada_file_path.c_str ());
if (!infile.good()) {
throw std::ios_base::failure (collada_file_path +
std::string (" does not exist."));
}
LeafNodeColladaPtr_t shared_ptr(new LeafNodeCollada
(name, collada_file_path));
// Add reference to itself
shared_ptr->initWeakPtr(shared_ptr);
return shared_ptr;
}
LeafNodeColladaPtr_t LeafNodeCollada::create(const std::string& name, const std::string& collada_file_path, const osgVector4& color)
{
std::ifstream infile(collada_file_path.c_str ());
if (!infile.good()) {
throw std::ios_base::failure (collada_file_path +
std::string (" does not exist."));
}
LeafNodeColladaPtr_t shared_ptr(new LeafNodeCollada
(name, collada_file_path, color));
// Add reference to itself
shared_ptr->initWeakPtr(shared_ptr);
return shared_ptr;
}
LeafNodeColladaPtr_t LeafNodeCollada::createCopy(LeafNodeColladaPtr_t other)
{
LeafNodeColladaPtr_t shared_ptr(new LeafNodeCollada(*other));
// Add reference to itself
shared_ptr->initWeakPtr(shared_ptr);
return shared_ptr;
}
::osg::NodeRefPtr LeafNodeCollada::getColladaPtr()
{
return collada_ptr_.get();
}
/* End of declaration of protected function members */
/* Declaration of public function members */
LeafNodeColladaPtr_t LeafNodeCollada::clone(void) const
{
return LeafNodeCollada::createCopy(weak_ptr_.lock());
}
LeafNodeColladaPtr_t LeafNodeCollada::self(void) const
{
return weak_ptr_.lock();
}
void LeafNodeCollada::setColor(const osgVector4& color)
{
osg::ref_ptr<osg::Material> mat_ptr (new osg::Material);
osgVector4 ambient (color.r() * 0.5f, color.g() * 0.5f, color.b() * 0.5f, color.a());
mat_ptr->setDiffuse (osg::Material::FRONT_AND_BACK,color);
mat_ptr->setAmbient (osg::Material::FRONT_AND_BACK,ambient);
collada_ptr_->getOrCreateStateSet()->setAttribute(mat_ptr.get());
}
void LeafNodeCollada::setAlpha(const float& alpha)
{
osg::StateSet* ss = getColladaPtr().get()->getStateSet();
if (ss)
{
alpha_ = alpha;
osg::Material *mat;
if (ss->getAttribute(osg::StateAttribute::MATERIAL))
mat = dynamic_cast<osg::Material*>(ss->getAttribute(osg::StateAttribute::MATERIAL));
else
{
mat = new osg::Material;
ss->setAttribute(mat, osg::StateAttribute::OFF | osg::StateAttribute::OVERRIDE);
}
mat->setTransparency(osg::Material::FRONT_AND_BACK, alpha);
if (alpha == 0)
ss->setRenderingHint(osg::StateSet::DEFAULT_BIN);
else
ss->setRenderingHint(osg::StateSet::TRANSPARENT_BIN);
}
}
void LeafNodeCollada::setTexture(const std::string& image_path)
{
texture_file_path_ = image_path;
osg::ref_ptr<osg::Texture2D> texture = new osg::Texture2D;
texture->setDataVariance(osg::Object::DYNAMIC);
osg::ref_ptr<osg::Image> image = osgDB::readImageFile(image_path);
if (!image)
{
std::cout << " couldn't find texture, quiting." << std::endl;
return;
}
texture->setImage(image);
collada_ptr_->getStateSet()->setTextureAttributeAndModes(0,texture,osg::StateAttribute::ON);
}
const std::string& LeafNodeCollada::meshFilePath () const
{
return collada_file_path_;
}
const std::string& LeafNodeCollada::textureFilePath () const
{
return texture_file_path_;
}
/*void LeafNodeCollada::setColor(osg::NodeRefPtr osgNode_ptr,const osgVector4& color)
{
osg::Vec4ArrayRefPtr colorArray = new osg::Vec4Array();
colorArray->push_back(color);
osg::GeodeRefPtr geode_ptr = osgNode_ptr->asGeode();
if (geode_ptr) {
for (unsigned int i = 0 ; i < geode_ptr->getNumDrawables() ; i++) {
osg::GeometryRefPtr geom_ptr = geode_ptr->getDrawable(i)->asGeometry();
if (geom_ptr) {
geom_ptr->setColorArray(colorArray.get());
geom_ptr->setColorBinding(osg::Geometry::BIND_OVERALL);
}
}
}
else {
osg::GroupRefPtr group_ptr = osgNode_ptr->asGroup();
if (group_ptr) {
for (unsigned int i = 0 ; i < group_ptr->getNumChildren() ; i++) {
setColor(group_ptr->getChild(i),color);
}
}
}
}*/
osg::ref_ptr<osg::Node> LeafNodeCollada::getOsgNode() const
{
return collada_ptr_;
}
LeafNodeCollada::~LeafNodeCollada()
{
/* Proper deletion of all tree scene */
this->asQueue()->removeChild(collada_ptr_);
collada_ptr_ = NULL;
weak_ptr_.reset();
}
/* End of declaration of public function members */
} /* namespace graphics */
<commit_msg>Add warning when parsing DAE file with wrong locale.<commit_after>//
// leaf-node-collada.cpp
// gepetto-viewer
//
// Created by Anthony Couret, Mathieu Geisert in November 2014.
// Copyright (c) 2014 LAAS-CNRS. All rights reserved.
//
#include <sys/stat.h>
#include <fstream>
#include <clocale>
#include <ios>
#include <osgDB/FileNameUtils>
#include <gepetto/viewer/leaf-node-collada.h>
namespace graphics {
inline bool fileExists (const char* fn)
{ struct stat buffer; return (stat (fn, &buffer) == 0); }
std::string getCachedFileName (const std::string& meshfile)
{
static const std::string exts[3] = { ".osg", ".osg2", ".osgb" };
for (int i = 0; i < 3; ++i) {
std::string cached = meshfile + exts[i];
if (fileExists(cached.c_str())) return cached;
}
return std::string();
}
/* Declaration of private function members */
void LeafNodeCollada::init()
{
if (!fileExists(collada_file_path_.c_str()))
throw std::invalid_argument(std::string("File ") + collada_file_path_ + std::string(" not found."));
std::string osgname = getCachedFileName(collada_file_path_);
if (!osgname.empty()) {
std::cout << "Using " << osgname << std::endl;
collada_ptr_ = osgDB::readNodeFile(osgname);
} else {
// get the extension of the meshs file
std::string ext = osgDB::getLowerCaseFileExtension(collada_file_path_);
if (ext == "dae" && *localeconv()->decimal_point != '.') {
std::cerr << "Warning: your locale convention uses '"
<< localeconv()->decimal_point << "' as decimal separator while DAE "
"expects '.'.\nSet LC_NUMERIC to a locale convetion using '.' as "
"decimal separator (e.g. export LC_NUMERIC=\"en_US.utf-8\")."
<< std::endl;
}
if(ext == "obj"){
const osgDB::Options* options = new osgDB::Options("noRotation");
collada_ptr_ = osgDB::readNodeFile(collada_file_path_,options);
}
else
collada_ptr_ = osgDB::readNodeFile(collada_file_path_);
if (ext == "dae") {
bool error = false;
if (!collada_ptr_) {
std::cout << "File: " << collada_file_path_ << " could not be loaded\n";
error = true;
} else if (strncasecmp(collada_ptr_->getName().c_str(), "empty", 5) == 0) {
std::cout << "File: " << collada_file_path_ << " could not be loaded:\n"
<< collada_ptr_->getName() << '\n';
error = true;
}
if (error) {
std::cout << "You may try to convert the file with the following command:\n"
"osgconv " << collada_file_path_ << ' ' << collada_file_path_ << ".osgb" << std::endl;
}
}
}
if (!collada_ptr_)
throw std::invalid_argument(std::string("File ") + collada_file_path_ + std::string(" found but could not be opened. Check that a plugin exist."));
/* Create PositionAttitudeTransform */
this->asQueue()->addChild(collada_ptr_);
/* Allow transparency */
if (collada_ptr_->getOrCreateStateSet())
{
collada_ptr_->getOrCreateStateSet()->setMode(GL_BLEND, ::osg::StateAttribute::ON);
}
addProperty(StringProperty::create("Meshfile path",
StringProperty::getterFromMemberFunction(this, &LeafNodeCollada::meshFilePath),
StringProperty::Setter_t()));
}
LeafNodeCollada::LeafNodeCollada(const std::string& name, const std::string& collada_file_path) :
Node(name), collada_file_path_(collada_file_path)
{
init();
}
LeafNodeCollada::LeafNodeCollada(const std::string& name, const std::string& collada_file_path, const osgVector4& color) :
Node(name), collada_file_path_(collada_file_path)
{
init();
setColor(color);
}
LeafNodeCollada::LeafNodeCollada(const LeafNodeCollada& other) :
Node(other.getID()), collada_file_path_(other.collada_file_path_)
{
init();
}
void LeafNodeCollada::initWeakPtr(LeafNodeColladaWeakPtr other_weak_ptr)
{
weak_ptr_ = other_weak_ptr;
}
/* End of declaration of private function members */
/* Declaration of protected function members */
LeafNodeColladaPtr_t LeafNodeCollada::create(const std::string& name, const std::string& collada_file_path)
{
std::ifstream infile(collada_file_path.c_str ());
if (!infile.good()) {
throw std::ios_base::failure (collada_file_path +
std::string (" does not exist."));
}
LeafNodeColladaPtr_t shared_ptr(new LeafNodeCollada
(name, collada_file_path));
// Add reference to itself
shared_ptr->initWeakPtr(shared_ptr);
return shared_ptr;
}
LeafNodeColladaPtr_t LeafNodeCollada::create(const std::string& name, const std::string& collada_file_path, const osgVector4& color)
{
std::ifstream infile(collada_file_path.c_str ());
if (!infile.good()) {
throw std::ios_base::failure (collada_file_path +
std::string (" does not exist."));
}
LeafNodeColladaPtr_t shared_ptr(new LeafNodeCollada
(name, collada_file_path, color));
// Add reference to itself
shared_ptr->initWeakPtr(shared_ptr);
return shared_ptr;
}
LeafNodeColladaPtr_t LeafNodeCollada::createCopy(LeafNodeColladaPtr_t other)
{
LeafNodeColladaPtr_t shared_ptr(new LeafNodeCollada(*other));
// Add reference to itself
shared_ptr->initWeakPtr(shared_ptr);
return shared_ptr;
}
::osg::NodeRefPtr LeafNodeCollada::getColladaPtr()
{
return collada_ptr_.get();
}
/* End of declaration of protected function members */
/* Declaration of public function members */
LeafNodeColladaPtr_t LeafNodeCollada::clone(void) const
{
return LeafNodeCollada::createCopy(weak_ptr_.lock());
}
LeafNodeColladaPtr_t LeafNodeCollada::self(void) const
{
return weak_ptr_.lock();
}
void LeafNodeCollada::setColor(const osgVector4& color)
{
osg::ref_ptr<osg::Material> mat_ptr (new osg::Material);
osgVector4 ambient (color.r() * 0.5f, color.g() * 0.5f, color.b() * 0.5f, color.a());
mat_ptr->setDiffuse (osg::Material::FRONT_AND_BACK,color);
mat_ptr->setAmbient (osg::Material::FRONT_AND_BACK,ambient);
collada_ptr_->getOrCreateStateSet()->setAttribute(mat_ptr.get());
}
void LeafNodeCollada::setAlpha(const float& alpha)
{
osg::StateSet* ss = getColladaPtr().get()->getStateSet();
if (ss)
{
alpha_ = alpha;
osg::Material *mat;
if (ss->getAttribute(osg::StateAttribute::MATERIAL))
mat = dynamic_cast<osg::Material*>(ss->getAttribute(osg::StateAttribute::MATERIAL));
else
{
mat = new osg::Material;
ss->setAttribute(mat, osg::StateAttribute::OFF | osg::StateAttribute::OVERRIDE);
}
mat->setTransparency(osg::Material::FRONT_AND_BACK, alpha);
if (alpha == 0)
ss->setRenderingHint(osg::StateSet::DEFAULT_BIN);
else
ss->setRenderingHint(osg::StateSet::TRANSPARENT_BIN);
}
}
void LeafNodeCollada::setTexture(const std::string& image_path)
{
texture_file_path_ = image_path;
osg::ref_ptr<osg::Texture2D> texture = new osg::Texture2D;
texture->setDataVariance(osg::Object::DYNAMIC);
osg::ref_ptr<osg::Image> image = osgDB::readImageFile(image_path);
if (!image)
{
std::cout << " couldn't find texture, quiting." << std::endl;
return;
}
texture->setImage(image);
collada_ptr_->getStateSet()->setTextureAttributeAndModes(0,texture,osg::StateAttribute::ON);
}
const std::string& LeafNodeCollada::meshFilePath () const
{
return collada_file_path_;
}
const std::string& LeafNodeCollada::textureFilePath () const
{
return texture_file_path_;
}
/*void LeafNodeCollada::setColor(osg::NodeRefPtr osgNode_ptr,const osgVector4& color)
{
osg::Vec4ArrayRefPtr colorArray = new osg::Vec4Array();
colorArray->push_back(color);
osg::GeodeRefPtr geode_ptr = osgNode_ptr->asGeode();
if (geode_ptr) {
for (unsigned int i = 0 ; i < geode_ptr->getNumDrawables() ; i++) {
osg::GeometryRefPtr geom_ptr = geode_ptr->getDrawable(i)->asGeometry();
if (geom_ptr) {
geom_ptr->setColorArray(colorArray.get());
geom_ptr->setColorBinding(osg::Geometry::BIND_OVERALL);
}
}
}
else {
osg::GroupRefPtr group_ptr = osgNode_ptr->asGroup();
if (group_ptr) {
for (unsigned int i = 0 ; i < group_ptr->getNumChildren() ; i++) {
setColor(group_ptr->getChild(i),color);
}
}
}
}*/
osg::ref_ptr<osg::Node> LeafNodeCollada::getOsgNode() const
{
return collada_ptr_;
}
LeafNodeCollada::~LeafNodeCollada()
{
/* Proper deletion of all tree scene */
this->asQueue()->removeChild(collada_ptr_);
collada_ptr_ = NULL;
weak_ptr_.reset();
}
/* End of declaration of public function members */
} /* namespace graphics */
<|endoftext|> |
<commit_before> /*
kopetechatwindowstylemanager.cpp - Manager all chat window styles
Copyright (c) 2005 by Michaël Larouche <michael.larouche@kdemail.net>
Kopete (c) 2002-2005 by the Kopete developers <kopete-devel@kde.org>
*************************************************************************
* *
* 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. *
* *
*************************************************************************
*/
#include "kopetechatwindowstylemanager.h"
// Qt includes
#include <qvaluestack.h>
// KDE includes
#include <kstandarddirs.h>
#include <kdirlister.h>
#include <kdebug.h>
#include <kurl.h>
#include <kglobal.h>
#include <karchive.h>
#include <kzip.h>
#include <ktar.h>
#include <kmimetype.h>
#include <kio/netaccess.h>
#include <kstaticdeleter.h>
#include <kconfig.h>
#include <kglobal.h>
#include "kopetechatwindowstyle.h"
class ChatWindowStyleManager::Private
{
public:
Private()
: styleDirLister(0)
{}
~Private()
{
if(styleDirLister)
{
styleDirLister->deleteLater();
}
QMap<QString, ChatWindowStyle*>::Iterator styleIt, styleItEnd = stylePool.end();
for(styleIt = stylePool.begin(); styleIt != styleItEnd; ++styleIt)
{
delete styleIt.data();
}
}
KDirLister *styleDirLister;
StyleList availableStyles;
// key = style path, value = ChatWindowStyle instance
QMap<QString, ChatWindowStyle*> stylePool;
QValueStack<KURL> styleDirs;
};
static KStaticDeleter<ChatWindowStyleManager> ChatWindowStyleManagerstaticDeleter;
ChatWindowStyleManager *ChatWindowStyleManager::s_self = 0;
ChatWindowStyleManager *ChatWindowStyleManager::self()
{
if( !s_self )
{
ChatWindowStyleManagerstaticDeleter.setObject( s_self, new ChatWindowStyleManager() );
}
return s_self;
}
ChatWindowStyleManager::ChatWindowStyleManager(QObject *parent, const char *name)
: QObject(parent, name), d(new Private())
{
kdDebug(14000) << k_funcinfo << endl;
loadStyles();
}
ChatWindowStyleManager::~ChatWindowStyleManager()
{
kdDebug(14000) << k_funcinfo << endl;
delete d;
}
void ChatWindowStyleManager::loadStyles()
{
QStringList chatStyles = KGlobal::dirs()->findDirs( "appdata", QString::fromUtf8( "styles" ) );
QStringList::const_iterator it;
for(it = chatStyles.constBegin(); it != chatStyles.constEnd(); ++it)
{
kdDebug(14000) << k_funcinfo << *it << endl;
d->styleDirs.push( KURL(*it) );
}
d->styleDirLister = new KDirLister;
d->styleDirLister->setDirOnlyMode(true);
connect(d->styleDirLister, SIGNAL(newItems(const KFileItemList &)), this, SLOT(slotNewStyles(const KFileItemList &)));
connect(d->styleDirLister, SIGNAL(completed()), this, SLOT(slotDirectoryFinished()));
if( !d->styleDirs.isEmpty() )
d->styleDirLister->openURL(d->styleDirs.pop(), true);
}
ChatWindowStyleManager::StyleList ChatWindowStyleManager::getAvailableStyles()
{
return d->availableStyles;
}
int ChatWindowStyleManager::installStyle(const QString &styleBundlePath)
{
QString localStyleDir( locateLocal( "appdata", QString::fromUtf8("styles/") ) );
KArchiveEntry *currentEntry = 0L;
KArchiveDirectory* currentDir = 0L;
KArchive *archive = 0L;
if( localStyleDir.isEmpty() )
{
return StyleNoDirectoryValid;
}
// Find mimetype for current bundle. ZIP and KTar need separate constructor
QString currentBundleMimeType = KMimeType::findByPath(styleBundlePath, 0, false)->name();
if(currentBundleMimeType == "application/x-zip")
{
archive = new KZip(styleBundlePath);
}
else if( currentBundleMimeType == "application/x-tgz" || currentBundleMimeType == "application/x-tbz" || currentBundleMimeType == "application/x-gzip" || currentBundleMimeType == "application/x-bzip2" )
{
archive = new KTar(styleBundlePath);
}
else
{
return StyleCannotOpen;
}
if ( !archive->open(IO_ReadOnly) )
{
delete archive;
return StyleCannotOpen;
}
const KArchiveDirectory* rootDir = archive->directory();
// Ok where we go to check if the archive is valid.
// Each time we found a correspondance to a theme bundle, we add a point to validResult.
// A valid style bundle must have:
// -a Contents, Contents/Resources, Co/Res/Incoming, Co/Res/Outgoing dirs
// main.css, Footer.html, Header.html, Status.html files in Contents/Ressources.
// So for a style bundle to be valid, it must have a result greather than 8, because we test for 8 required entry.
int validResult = 0;
QStringList entries = rootDir->entries();
// Will be reused later.
QStringList::Iterator entriesIt, entriesItEnd = entries.end();
for(entriesIt = entries.begin(); entriesIt != entries.end(); ++entriesIt)
{
currentEntry = const_cast<KArchiveEntry*>(rootDir->entry(*entriesIt));
// kdDebug() << k_funcinfo << "Current entry name: " << currentEntry->name() << endl;
if (currentEntry->isDirectory())
{
currentDir = dynamic_cast<KArchiveDirectory*>( currentEntry );
if (currentDir)
{
if( currentDir->entry(QString::fromUtf8("Contents")) )
{
// kdDebug() << k_funcinfo << "Contents found" << endl;
validResult += 1;
}
if( currentDir->entry(QString::fromUtf8("Contents/Resources")) )
{
// kdDebug() << k_funcinfo << "Contents/Resources found" << endl;
validResult += 1;
}
if( currentDir->entry(QString::fromUtf8("Contents/Resources/Incoming")) )
{
// kdDebug() << k_funcinfo << "Contents/Resources/Incoming found" << endl;
validResult += 1;
}
if( currentDir->entry(QString::fromUtf8("Contents/Resources/Outgoing")) )
{
// kdDebug() << k_funcinfo << "Contents/Resources/Outgoing found" << endl;
validResult += 1;
}
if( currentDir->entry(QString::fromUtf8("Contents/Resources/main.css")) )
{
// kdDebug() << k_funcinfo << "Contents/Resources/main.css found" << endl;
validResult += 1;
}
if( currentDir->entry(QString::fromUtf8("Contents/Resources/Footer.html")) )
{
// kdDebug() << k_funcinfo << "Contents/Resources/Footer.html found" << endl;
validResult += 1;
}
if( currentDir->entry(QString::fromUtf8("Contents/Resources/Status.html")) )
{
// kdDebug() << k_funcinfo << "Contents/Resources/Status.html found" << endl;
validResult += 1;
}
if( currentDir->entry(QString::fromUtf8("Contents/Resources/Header.html")) )
{
// kdDebug() << k_funcinfo << "Contents/Resources/Header.html found" << endl;
validResult += 1;
}
if( currentDir->entry(QString::fromUtf8("Contents/Resources/Incoming/Content.html")) )
{
// kdDebug() << k_funcinfo << "Contents/Resources/Incoming/Content.html found" << endl;
validResult += 1;
}
if( currentDir->entry(QString::fromUtf8("Contents/Resources/Outgoing/Content.html")) )
{
// kdDebug() << k_funcinfo << "Contents/Resources/Outgoing/Content.html found" << endl;
validResult += 1;
}
}
}
}
// kdDebug() << k_funcinfo << "Valid result: " << QString::number(validResult) << endl;
// The archive is a valid style bundle.
if(validResult >= 8)
{
bool installOk = false;
for(entriesIt = entries.begin(); entriesIt != entries.end(); ++entriesIt)
{
currentEntry = const_cast<KArchiveEntry*>(rootDir->entry(*entriesIt));
if(currentEntry && currentEntry->isDirectory())
{
// Ignore this MacOS X "garbage" directory in zip.
if(currentEntry->name() == QString::fromUtf8("__MACOSX"))
{
continue;
}
else
{
currentDir = dynamic_cast<KArchiveDirectory*>(currentEntry);
if(currentDir)
{
currentDir->copyTo(localStyleDir + currentDir->name());
installOk = true;
}
}
}
}
archive->close();
delete archive;
if(installOk)
return StyleInstallOk;
else
return StyleUnknow;
}
else
{
archive->close();
delete archive;
return StyleNotValid;
}
if(archive)
{
archive->close();
delete archive;
}
return StyleUnknow;
}
bool ChatWindowStyleManager::removeStyle(const QString &stylePath)
{
// Find for the current style in avaiableStyles map.
StyleList::Iterator foundStyle = d->availableStyles.find(stylePath);
// QMap iterator return end() if it found no item.
if(foundStyle != d->availableStyles.end())
{
d->availableStyles.remove(foundStyle);
// Remove and delete style from pool if needed.
if( d->stylePool.contains(stylePath) )
{
ChatWindowStyle *deletedStyle = d->stylePool[stylePath];
d->stylePool.remove(stylePath);
delete deletedStyle;
}
// Do the actual deletion of the directory style.
return KIO::NetAccess::del( KURL(stylePath), 0 );
}
else
{
return false;
}
}
ChatWindowStyle *ChatWindowStyleManager::getStyleFromPool(const QString &stylePath)
{
if( d->stylePool.contains(stylePath) )
{
// NOTE: This is a hidden config switch for style developers
// Check in the config if the cache is disabled.
// if the cache is disabled, reload the style everytime it's getted.
KConfig *config = KGlobal::config();
config->setGroup("KopeteStyleDebug");
bool disableCache = config->readBoolEntry("disableStyleCache", false);
if(disableCache)
{
d->stylePool[stylePath]->reload();
}
return d->stylePool[stylePath];
}
else
{
// Build a chat window style and list its variants, then add it to the pool.
ChatWindowStyle *style = new ChatWindowStyle(stylePath, ChatWindowStyle::StyleBuildNormal);
d->stylePool.insert(stylePath, style);
return style;
}
return 0;
}
void ChatWindowStyleManager::slotNewStyles(const KFileItemList &dirList)
{
KFileItem *item;
QPtrListIterator<KFileItem> it( dirList );
while( (item = it.current()) != 0 )
{
// Ignore data dir(from deprecated XSLT themes)
if( !item->url().fileName().contains(QString::fromUtf8("data")) )
{
kdDebug(14000) << k_funcinfo << "Listing: " << item->url().fileName() << endl;
// If the style path is already in the pool, that's mean the style was updated on disk
// Reload the style
if( d->stylePool.contains(item->url().path()) )
{
kdDebug(14000) << k_funcinfo << "Updating style: " << item->url().path() << endl;
d->stylePool[item->url().path()]->reload();
// Add to avaialble if required.
if( !d->availableStyles.contains(item->url().fileName()) )
d->availableStyles.insert(item->url().fileName(), item->url().path());
}
else
{
// TODO: Use name from Info.plist
d->availableStyles.insert(item->url().fileName(), item->url().path());
}
}
++it;
}
}
void ChatWindowStyleManager::slotDirectoryFinished()
{
// Start another scanning if the directories stack is not empty
if( !d->styleDirs.isEmpty() )
{
kdDebug(14000) << k_funcinfo << "Starting another directory." << endl;
d->styleDirLister->openURL(d->styleDirs.pop(), true);
}
else
{
emit loadStylesFinished();
}
}
#include "kopetechatwindowstylemanager.moc"
<commit_msg>fix mem leak (shown by valgrind) <commit_after> /*
kopetechatwindowstylemanager.cpp - Manager all chat window styles
Copyright (c) 2005 by Michaël Larouche <michael.larouche@kdemail.net>
Kopete (c) 2002-2005 by the Kopete developers <kopete-devel@kde.org>
*************************************************************************
* *
* 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. *
* *
*************************************************************************
*/
#include "kopetechatwindowstylemanager.h"
// Qt includes
#include <qvaluestack.h>
// KDE includes
#include <kstandarddirs.h>
#include <kdirlister.h>
#include <kdebug.h>
#include <kurl.h>
#include <kglobal.h>
#include <karchive.h>
#include <kzip.h>
#include <ktar.h>
#include <kmimetype.h>
#include <kio/netaccess.h>
#include <kstaticdeleter.h>
#include <kconfig.h>
#include <kglobal.h>
#include "kopetechatwindowstyle.h"
class ChatWindowStyleManager::Private
{
public:
Private()
: styleDirLister(0)
{}
~Private()
{
if(styleDirLister)
{
styleDirLister->deleteLater();
}
QMap<QString, ChatWindowStyle*>::Iterator styleIt, styleItEnd = stylePool.end();
for(styleIt = stylePool.begin(); styleIt != styleItEnd; ++styleIt)
{
delete styleIt.data();
}
}
KDirLister *styleDirLister;
StyleList availableStyles;
// key = style path, value = ChatWindowStyle instance
QMap<QString, ChatWindowStyle*> stylePool;
QValueStack<KURL> styleDirs;
};
static KStaticDeleter<ChatWindowStyleManager> ChatWindowStyleManagerstaticDeleter;
ChatWindowStyleManager *ChatWindowStyleManager::s_self = 0;
ChatWindowStyleManager *ChatWindowStyleManager::self()
{
if( !s_self )
{
ChatWindowStyleManagerstaticDeleter.setObject( s_self, new ChatWindowStyleManager() );
}
return s_self;
}
ChatWindowStyleManager::ChatWindowStyleManager(QObject *parent, const char *name)
: QObject(parent, name), d(new Private())
{
kdDebug(14000) << k_funcinfo << endl;
loadStyles();
}
ChatWindowStyleManager::~ChatWindowStyleManager()
{
kdDebug(14000) << k_funcinfo << endl;
delete d;
}
void ChatWindowStyleManager::loadStyles()
{
QStringList chatStyles = KGlobal::dirs()->findDirs( "appdata", QString::fromUtf8( "styles" ) );
QStringList::const_iterator it;
for(it = chatStyles.constBegin(); it != chatStyles.constEnd(); ++it)
{
kdDebug(14000) << k_funcinfo << *it << endl;
d->styleDirs.push( KURL(*it) );
}
d->styleDirLister = new KDirLister(this);
d->styleDirLister->setDirOnlyMode(true);
connect(d->styleDirLister, SIGNAL(newItems(const KFileItemList &)), this, SLOT(slotNewStyles(const KFileItemList &)));
connect(d->styleDirLister, SIGNAL(completed()), this, SLOT(slotDirectoryFinished()));
if( !d->styleDirs.isEmpty() )
d->styleDirLister->openURL(d->styleDirs.pop(), true);
}
ChatWindowStyleManager::StyleList ChatWindowStyleManager::getAvailableStyles()
{
return d->availableStyles;
}
int ChatWindowStyleManager::installStyle(const QString &styleBundlePath)
{
QString localStyleDir( locateLocal( "appdata", QString::fromUtf8("styles/") ) );
KArchiveEntry *currentEntry = 0L;
KArchiveDirectory* currentDir = 0L;
KArchive *archive = 0L;
if( localStyleDir.isEmpty() )
{
return StyleNoDirectoryValid;
}
// Find mimetype for current bundle. ZIP and KTar need separate constructor
QString currentBundleMimeType = KMimeType::findByPath(styleBundlePath, 0, false)->name();
if(currentBundleMimeType == "application/x-zip")
{
archive = new KZip(styleBundlePath);
}
else if( currentBundleMimeType == "application/x-tgz" || currentBundleMimeType == "application/x-tbz" || currentBundleMimeType == "application/x-gzip" || currentBundleMimeType == "application/x-bzip2" )
{
archive = new KTar(styleBundlePath);
}
else
{
return StyleCannotOpen;
}
if ( !archive->open(IO_ReadOnly) )
{
delete archive;
return StyleCannotOpen;
}
const KArchiveDirectory* rootDir = archive->directory();
// Ok where we go to check if the archive is valid.
// Each time we found a correspondance to a theme bundle, we add a point to validResult.
// A valid style bundle must have:
// -a Contents, Contents/Resources, Co/Res/Incoming, Co/Res/Outgoing dirs
// main.css, Footer.html, Header.html, Status.html files in Contents/Ressources.
// So for a style bundle to be valid, it must have a result greather than 8, because we test for 8 required entry.
int validResult = 0;
QStringList entries = rootDir->entries();
// Will be reused later.
QStringList::Iterator entriesIt, entriesItEnd = entries.end();
for(entriesIt = entries.begin(); entriesIt != entries.end(); ++entriesIt)
{
currentEntry = const_cast<KArchiveEntry*>(rootDir->entry(*entriesIt));
// kdDebug() << k_funcinfo << "Current entry name: " << currentEntry->name() << endl;
if (currentEntry->isDirectory())
{
currentDir = dynamic_cast<KArchiveDirectory*>( currentEntry );
if (currentDir)
{
if( currentDir->entry(QString::fromUtf8("Contents")) )
{
// kdDebug() << k_funcinfo << "Contents found" << endl;
validResult += 1;
}
if( currentDir->entry(QString::fromUtf8("Contents/Resources")) )
{
// kdDebug() << k_funcinfo << "Contents/Resources found" << endl;
validResult += 1;
}
if( currentDir->entry(QString::fromUtf8("Contents/Resources/Incoming")) )
{
// kdDebug() << k_funcinfo << "Contents/Resources/Incoming found" << endl;
validResult += 1;
}
if( currentDir->entry(QString::fromUtf8("Contents/Resources/Outgoing")) )
{
// kdDebug() << k_funcinfo << "Contents/Resources/Outgoing found" << endl;
validResult += 1;
}
if( currentDir->entry(QString::fromUtf8("Contents/Resources/main.css")) )
{
// kdDebug() << k_funcinfo << "Contents/Resources/main.css found" << endl;
validResult += 1;
}
if( currentDir->entry(QString::fromUtf8("Contents/Resources/Footer.html")) )
{
// kdDebug() << k_funcinfo << "Contents/Resources/Footer.html found" << endl;
validResult += 1;
}
if( currentDir->entry(QString::fromUtf8("Contents/Resources/Status.html")) )
{
// kdDebug() << k_funcinfo << "Contents/Resources/Status.html found" << endl;
validResult += 1;
}
if( currentDir->entry(QString::fromUtf8("Contents/Resources/Header.html")) )
{
// kdDebug() << k_funcinfo << "Contents/Resources/Header.html found" << endl;
validResult += 1;
}
if( currentDir->entry(QString::fromUtf8("Contents/Resources/Incoming/Content.html")) )
{
// kdDebug() << k_funcinfo << "Contents/Resources/Incoming/Content.html found" << endl;
validResult += 1;
}
if( currentDir->entry(QString::fromUtf8("Contents/Resources/Outgoing/Content.html")) )
{
// kdDebug() << k_funcinfo << "Contents/Resources/Outgoing/Content.html found" << endl;
validResult += 1;
}
}
}
}
// kdDebug() << k_funcinfo << "Valid result: " << QString::number(validResult) << endl;
// The archive is a valid style bundle.
if(validResult >= 8)
{
bool installOk = false;
for(entriesIt = entries.begin(); entriesIt != entries.end(); ++entriesIt)
{
currentEntry = const_cast<KArchiveEntry*>(rootDir->entry(*entriesIt));
if(currentEntry && currentEntry->isDirectory())
{
// Ignore this MacOS X "garbage" directory in zip.
if(currentEntry->name() == QString::fromUtf8("__MACOSX"))
{
continue;
}
else
{
currentDir = dynamic_cast<KArchiveDirectory*>(currentEntry);
if(currentDir)
{
currentDir->copyTo(localStyleDir + currentDir->name());
installOk = true;
}
}
}
}
archive->close();
delete archive;
if(installOk)
return StyleInstallOk;
else
return StyleUnknow;
}
else
{
archive->close();
delete archive;
return StyleNotValid;
}
if(archive)
{
archive->close();
delete archive;
}
return StyleUnknow;
}
bool ChatWindowStyleManager::removeStyle(const QString &stylePath)
{
// Find for the current style in avaiableStyles map.
StyleList::Iterator foundStyle = d->availableStyles.find(stylePath);
// QMap iterator return end() if it found no item.
if(foundStyle != d->availableStyles.end())
{
d->availableStyles.remove(foundStyle);
// Remove and delete style from pool if needed.
if( d->stylePool.contains(stylePath) )
{
ChatWindowStyle *deletedStyle = d->stylePool[stylePath];
d->stylePool.remove(stylePath);
delete deletedStyle;
}
// Do the actual deletion of the directory style.
return KIO::NetAccess::del( KURL(stylePath), 0 );
}
else
{
return false;
}
}
ChatWindowStyle *ChatWindowStyleManager::getStyleFromPool(const QString &stylePath)
{
if( d->stylePool.contains(stylePath) )
{
// NOTE: This is a hidden config switch for style developers
// Check in the config if the cache is disabled.
// if the cache is disabled, reload the style everytime it's getted.
KConfig *config = KGlobal::config();
config->setGroup("KopeteStyleDebug");
bool disableCache = config->readBoolEntry("disableStyleCache", false);
if(disableCache)
{
d->stylePool[stylePath]->reload();
}
return d->stylePool[stylePath];
}
else
{
// Build a chat window style and list its variants, then add it to the pool.
ChatWindowStyle *style = new ChatWindowStyle(stylePath, ChatWindowStyle::StyleBuildNormal);
d->stylePool.insert(stylePath, style);
return style;
}
return 0;
}
void ChatWindowStyleManager::slotNewStyles(const KFileItemList &dirList)
{
KFileItem *item;
QPtrListIterator<KFileItem> it( dirList );
while( (item = it.current()) != 0 )
{
// Ignore data dir(from deprecated XSLT themes)
if( !item->url().fileName().contains(QString::fromUtf8("data")) )
{
kdDebug(14000) << k_funcinfo << "Listing: " << item->url().fileName() << endl;
// If the style path is already in the pool, that's mean the style was updated on disk
// Reload the style
if( d->stylePool.contains(item->url().path()) )
{
kdDebug(14000) << k_funcinfo << "Updating style: " << item->url().path() << endl;
d->stylePool[item->url().path()]->reload();
// Add to avaialble if required.
if( !d->availableStyles.contains(item->url().fileName()) )
d->availableStyles.insert(item->url().fileName(), item->url().path());
}
else
{
// TODO: Use name from Info.plist
d->availableStyles.insert(item->url().fileName(), item->url().path());
}
}
++it;
}
}
void ChatWindowStyleManager::slotDirectoryFinished()
{
// Start another scanning if the directories stack is not empty
if( !d->styleDirs.isEmpty() )
{
kdDebug(14000) << k_funcinfo << "Starting another directory." << endl;
d->styleDirLister->openURL(d->styleDirs.pop(), true);
}
else
{
emit loadStylesFinished();
}
}
#include "kopetechatwindowstylemanager.moc"
<|endoftext|> |
<commit_before>#include <iostream>
#include <gtest/gtest.h>
#include <thread>
#include <chrono>
#include <msgrpc/thrift_struct/thrift_codec.h>
#include <type_traits>
using namespace std;
using namespace std::chrono;
#include "demo/demo_api_declare.h"
////////////////////////////////////////////////////////////////////////////////
namespace msgrpc {
template <typename T> struct Ret {};
typedef unsigned short msg_id_t;
typedef unsigned short service_id_t; //TODO: how to deal with different service id types
struct MsgChannel {
virtual uint32_t send_msg(const service_id_t& remote_service_id, msg_id_t msg_id, const char* buf, size_t len) const = 0;
};
struct Config {
void initWith(MsgChannel* msg_channel, msgrpc::msg_id_t request_msg_id, msgrpc::msg_id_t response_msg_id) {
instance().msg_channel_ = msg_channel;
request_msg_id_ = request_msg_id;
response_msg_id_ = response_msg_id;
}
static inline Config& instance() {
static thread_local Config instance;
return instance;
}
MsgChannel* msg_channel_;
msg_id_t request_msg_id_;
msg_id_t response_msg_id_;
};
}
namespace msgrpc {
typedef uint8_t method_index_t;
typedef uint16_t iface_index_t;
struct MsgHeader {
uint8_t msgrpc_version_ = {0};
method_index_t method_index_in_interface_ = {0};
iface_index_t iface_index_in_service_ = {0};
//TODO: unsigned char feature_id_in_service_ = {0};
//TODO: TLV encoded varient length options
//unsigned long sequence_no_;
//optional 1
/*TODO: call sequence number*/
};
/*TODO: consider make msgHeader encoded through thrift*/
struct ReqMsgHeader : MsgHeader {
};
enum class RpcResult : unsigned short {
succeeded = 0
, failed = 1
, method_not_found = 2
, iface_not_found = 3
};
struct RspMsgHeader : MsgHeader {
RpcResult rpc_result_ = { RpcResult::succeeded };
};
}
////////////////////////////////////////////////////////////////////////////////
#include "test_util/UdpChannel.h"
namespace demo {
const msgrpc::msg_id_t k_msgrpc_request_msg_id = 101;
const msgrpc::msg_id_t k_msgrpc_response_msg_id = 102;
struct UdpMsgChannel : msgrpc::MsgChannel {
virtual uint32_t send_msg(const msgrpc::service_id_t& remote_service_id, msgrpc::msg_id_t msg_id, const char* buf, size_t len) const {
size_t msg_len_with_msgid = sizeof(msgrpc::msg_id_t) + len;
char* mem = (char*)malloc(msg_len_with_msgid);
if (mem) {
*(msgrpc::msg_id_t*)(mem) = msg_id;
memcpy(mem + sizeof(msgrpc::msg_id_t), buf, len);
cout << "send msg len: " << msg_len_with_msgid << endl;
g_msg_channel->send_msg_to_remote(string(mem, msg_len_with_msgid), udp::endpoint(udp::v4(), remote_service_id));
free(mem);
} else {
cout << "send msg failed: allocation failure." << endl;
}
return 0;
}
};
}
////////////////////////////////////////////////////////////////////////////////
using namespace demo;
const msgrpc::service_id_t k_remote_service_id = 2222;
const msgrpc::service_id_t k_local_service_id = 3333;
//TODO: unify interface of stub and implement.
struct IBuzzMath {
virtual msgrpc::Ret<ResponseBar> negative_fields(const RequestFoo&) = 0;
virtual msgrpc::Ret<ResponseBar> plus1_to_fields(const RequestFoo&) = 0;
};
////////////////////////////////////////////////////////////////////////////////
namespace msgrpc {
struct IfaceImplBase {
virtual bool onRpcInvoke(const msgrpc::ReqMsgHeader& msg_header, const char* msg, size_t len, msgrpc::RspMsgHeader& rsp_header, uint8_t*& pout_buf, uint32_t& out_buf_len) = 0;
};
struct IfaceRepository : msgrpc::Singleton<IfaceRepository> {
void add_iface_impl(iface_index_t ii, IfaceImplBase* iface) {
assert(iface != nullptr && "interface implementation can not be null");
assert(___m.find(ii) == ___m.end() && "interface can only register once");
___m[ii] = iface;
}
IfaceImplBase* get_iface_impl_by(iface_index_t ii) {
auto iter = ___m.find(ii);
return iter == ___m.end() ? nullptr : iter->second;
}
private:
std::map<iface_index_t, IfaceImplBase*> ___m;
};
template<typename T, iface_index_t iface_index>
struct InterfaceImplBaseT : IfaceImplBase {
InterfaceImplBaseT() {
IfaceRepository::instance().add_iface_impl(iface_index, this);
}
template<typename REQ, typename RSP>
bool invoke_templated_method( bool (T::*method_impl)(const REQ&, RSP&)
, const char *msg, size_t len
, uint8_t *&pout_buf, uint32_t &out_buf_len) {
REQ req;
if (! ThriftDecoder::decode(req, (uint8_t *) msg, len)) {
cout << "decode failed on remote side." << endl;
return false;
}
RSP rsp;
if (! ((T*)this->*method_impl)(req, rsp)) {
//TODO: log
return false;
}
if (! ThriftEncoder::encode(rsp, &pout_buf, &out_buf_len)) {
cout << "encode failed on remtoe side." << endl;
return false;
}
return true;
}
};
}
////////////////////////////////////////////////////////////////////////////////
namespace msgrpc {
struct RpcReqMsgHandler {
static void on_rpc_req_msg(msgrpc::msg_id_t msg_id, const char *msg, size_t len) {
cout << "remote received msg with length: " << len << endl;
assert(msg_id == k_msgrpc_request_msg_id && "invalid msg id for rpc");
if (len < sizeof(msgrpc::ReqMsgHeader)) {
cout << "invalid msg: without sufficient msg header info." << endl;
return;
}
auto *req_header = (msgrpc::ReqMsgHeader *) msg;
msg += sizeof(msgrpc::ReqMsgHeader);
msgrpc::RspMsgHeader rsp_header;
rsp_header.msgrpc_version_ = req_header->msgrpc_version_;
rsp_header.iface_index_in_service_ = req_header->iface_index_in_service_;
rsp_header.method_index_in_interface_ = req_header->method_index_in_interface_;
uint8_t *pout_buf;
uint32_t out_buf_len;
IfaceImplBase *iface = IfaceRepository::instance().get_iface_impl_by(req_header->iface_index_in_service_);
if (iface == nullptr) {
rsp_header.rpc_result_ = RpcResult::iface_not_found;
msgrpc::Config::instance().msg_channel_->send_msg(k_local_service_id, k_msgrpc_response_msg_id, (const char *) &rsp_header, sizeof(rsp_header));
return;
}
bool ret = iface->onRpcInvoke(*req_header, msg, len - sizeof(msgrpc::ReqMsgHeader), rsp_header, pout_buf, out_buf_len);
if (ret) {
return send_msg_with_header(rsp_header, pout_buf, out_buf_len);
} else {
msgrpc::Config::instance().msg_channel_->send_msg(k_local_service_id, k_msgrpc_response_msg_id, (const char *) &rsp_header, sizeof(rsp_header));
}
//TODO: using pipelined processor to handling input/output msgheader and rpc statistics.
}
static void send_msg_with_header(RspMsgHeader &rsp_header, const uint8_t *pout_buf, uint32_t out_buf_len) {
size_t rsp_len_with_header = sizeof(rsp_header) + out_buf_len;
char *mem = (char *) malloc(rsp_len_with_header);
if (mem != nullptr) {
memcpy(mem, &rsp_header, sizeof(rsp_header));
memcpy(mem + sizeof(rsp_header), pout_buf, out_buf_len);
/*TODO: replace k_local_service_id to sender id*/
Config::instance().msg_channel_->send_msg(k_local_service_id, k_msgrpc_response_msg_id, mem, rsp_len_with_header);
free(mem);
}
}
};
}
////////////////////////////////////////////////////////////////////////////////
//---------------- generate this part by macros set:
struct IBuzzMathImpl : msgrpc::InterfaceImplBaseT<IBuzzMathImpl, 1> {
bool negative_fields(const RequestFoo& req, ResponseBar& rsp);
bool plus1_to_fields(const RequestFoo& req, ResponseBar& rsp);
virtual bool onRpcInvoke(const msgrpc::ReqMsgHeader& req_header, const char* msg, size_t len, msgrpc::RspMsgHeader& rsp_header, uint8_t*& pout_buf, uint32_t& out_buf_len) override;
};
////////////////////////////////////////////////////////////////////////////////
//---------------- generate this part by macros set: interface_implement_define.h
IBuzzMathImpl buzzMath;
bool IBuzzMathImpl::onRpcInvoke(const msgrpc::ReqMsgHeader& req_header, const char* msg, size_t len, msgrpc::RspMsgHeader& rsp_header, uint8_t*& pout_buf, uint32_t& out_buf_len) {
bool ret = false;
if (req_header.method_index_in_interface_ == 1) {
ret = this->invoke_templated_method(&IBuzzMathImpl::negative_fields, msg, len, pout_buf, out_buf_len);
} else
if (req_header.method_index_in_interface_ == 2) {
ret = this->invoke_templated_method(&IBuzzMathImpl::plus1_to_fields, msg, len, pout_buf, out_buf_len);
} else
{
rsp_header.rpc_result_ = msgrpc::RpcResult::method_not_found;
return false;
}
if (! ret) {
rsp_header.rpc_result_ = msgrpc::RpcResult::failed;
}
return ret;
}
////////////////////////////////////////////////////////////////////////////////
//---------------- implement interface in here:
bool IBuzzMathImpl::negative_fields(const RequestFoo& req, ResponseBar& rsp) {
rsp.__set_bara(req.get_foob());
if (req.__isset.foob) {
rsp.__set_barb(req.fooa);
}
return true;
}
bool IBuzzMathImpl::plus1_to_fields(const RequestFoo& req, ResponseBar& rsp) {
rsp.__set_bara(1 + req.fooa);
if (req.__isset.foob) {
rsp.__set_barb(1 + req.get_foob());
}
return true;
}
////////////////////////////////////////////////////////////////////////////////
void remote_service() {
msgrpc::Config::instance().initWith(new UdpMsgChannel(), k_msgrpc_request_msg_id, k_msgrpc_response_msg_id);
UdpChannel channel(k_remote_service_id,
[&channel](msgrpc::msg_id_t msg_id, const char* msg, size_t len) {
if (0 == strcmp(msg, "init")) {
return;
}
msgrpc::RpcReqMsgHandler::on_rpc_req_msg(msg_id, msg, len);
channel.close();
}
);
}
////////////////////////////////////////////////////////////////////////////////
#if 0
#define ___methods_of_interface___IBuzzMath(_, ...) \
_(1, ResponseBar, negative_fields, RequestFoo, __VA_ARGS__)\
_(2, ResponseBar, plus1_to_fields, RequestFoo, __VA_ARGS__)
___as_interface(IBuzzMath, __with_interface_id(1))
#endif
////////////////////////////////////////////////////////////////////////////////
namespace msgrpc {
struct RpcStubBase {
//TODO: split into .h and .cpp
void send_rpc_request_buf(msgrpc::iface_index_t iface_index, msgrpc::method_index_t method_index, const uint8_t *pbuf, uint32_t len) const {
size_t msg_len_with_header = sizeof(msgrpc::ReqMsgHeader) + len;
char *mem = (char *) malloc(msg_len_with_header);
if (!mem) {
cout << "alloc mem failed, during sending rpc request." << endl;
return;
}
auto header = (msgrpc::ReqMsgHeader *) mem;
header->msgrpc_version_ = 0;
header->iface_index_in_service_ = iface_index;
header->method_index_in_interface_ = method_index;
memcpy(header + 1, (const char *) pbuf, len);
cout << "stub sending msg with length: " << msg_len_with_header << endl;
//TODO: find k_remote_service_id by interface name "IBuzzMath"
msgrpc::Config::instance().msg_channel_->send_msg(k_remote_service_id, k_msgrpc_request_msg_id, mem, msg_len_with_header);
free(mem);
}
template<typename REQ>
void encode_request_and_send(msgrpc::iface_index_t iface_index, msgrpc::method_index_t method_index, const REQ &req) const {
uint8_t* pbuf;
uint32_t len;
/*TODO: extract interface for encode/decode for other protocol adoption such as protobuf*/
if (!ThriftEncoder::encode(req, &pbuf, &len)) {
/*TODO: how to do with log, maybe should extract logging interface*/
cout << "encode failed." << endl;
return;
}
send_rpc_request_buf(iface_index, method_index, pbuf, len);
};
};
}
////////////////////////////////////////////////////////////////////////////////
//-----------generate by: declare and define stub macros
struct IBuzzMathStub : msgrpc::RpcStubBase {
virtual void negative_fields(const RequestFoo&);
virtual void plus1_to_fields(const RequestFoo&);
};
//TODO: extract command codes into base class, only left data from macros
void IBuzzMathStub::negative_fields(const RequestFoo& req) {
encode_request_and_send(1, 1, req);
}
void IBuzzMathStub::plus1_to_fields(const RequestFoo& req) {
encode_request_and_send(1, 2, req);
}
////////////////////////////////////////////////////////////////////////////////
void local_service() {
std::this_thread::sleep_for(std::chrono::seconds(1));
msgrpc::Config::instance().initWith(new UdpMsgChannel(), k_msgrpc_request_msg_id, k_msgrpc_response_msg_id);
UdpChannel channel(k_local_service_id,
[&channel](msgrpc::msg_id_t msg_id, const char* msg, size_t len) {
if (0 == strcmp(msg, "init")) {
IBuzzMathStub buzzMath;
RequestFoo foo; foo.fooa = 97; foo.__set_foob(98);
buzzMath.negative_fields(foo);
} else {
cout << "local received msg: " << string(msg, len) << endl;
channel.close();
}
}
);
}
////////////////////////////////////////////////////////////////////////////////
TEST(async_rpc, should_able_to__auto__register_rpc_interface__after__application_startup) {
demo::RequestFoo req;
req.fooa = 1;
req.__set_foob(2);
std::thread local_thread(local_service);
std::thread remote_thread(remote_service);
local_thread.join();
remote_thread.join();
}
<commit_msg>refactor<commit_after>#include <iostream>
#include <gtest/gtest.h>
#include <thread>
#include <chrono>
#include <msgrpc/thrift_struct/thrift_codec.h>
#include <type_traits>
using namespace std;
using namespace std::chrono;
#include "demo/demo_api_declare.h"
////////////////////////////////////////////////////////////////////////////////
namespace msgrpc {
template <typename T> struct Ret {};
typedef unsigned short msg_id_t;
typedef unsigned short service_id_t; //TODO: how to deal with different service id types
struct MsgChannel {
virtual uint32_t send_msg(const service_id_t& remote_service_id, msg_id_t msg_id, const char* buf, size_t len) const = 0;
};
struct Config {
void initWith(MsgChannel* msg_channel, msgrpc::msg_id_t request_msg_id, msgrpc::msg_id_t response_msg_id) {
instance().msg_channel_ = msg_channel;
request_msg_id_ = request_msg_id;
response_msg_id_ = response_msg_id;
}
static inline Config& instance() {
static thread_local Config instance;
return instance;
}
MsgChannel* msg_channel_;
msg_id_t request_msg_id_;
msg_id_t response_msg_id_;
};
}
namespace msgrpc {
typedef uint8_t method_index_t;
typedef uint16_t iface_index_t;
struct MsgHeader {
uint8_t msgrpc_version_ = {0};
method_index_t method_index_in_interface_ = {0};
iface_index_t iface_index_in_service_ = {0};
//TODO: unsigned char feature_id_in_service_ = {0};
//TODO: TLV encoded varient length options
//unsigned long sequence_no_;
//optional 1
/*TODO: call sequence number*/
};
/*TODO: consider make msgHeader encoded through thrift*/
struct ReqMsgHeader : MsgHeader {
};
enum class RpcResult : unsigned short {
succeeded = 0
, failed = 1
, method_not_found = 2
, iface_not_found = 3
};
struct RspMsgHeader : MsgHeader {
RpcResult rpc_result_ = { RpcResult::succeeded };
};
}
////////////////////////////////////////////////////////////////////////////////
#include "test_util/UdpChannel.h"
namespace demo {
const msgrpc::msg_id_t k_msgrpc_request_msg_id = 101;
const msgrpc::msg_id_t k_msgrpc_response_msg_id = 102;
struct UdpMsgChannel : msgrpc::MsgChannel {
virtual uint32_t send_msg(const msgrpc::service_id_t& remote_service_id, msgrpc::msg_id_t msg_id, const char* buf, size_t len) const {
size_t msg_len_with_msgid = sizeof(msgrpc::msg_id_t) + len;
char* mem = (char*)malloc(msg_len_with_msgid);
if (mem) {
*(msgrpc::msg_id_t*)(mem) = msg_id;
memcpy(mem + sizeof(msgrpc::msg_id_t), buf, len);
cout << "send msg len: " << msg_len_with_msgid << endl;
g_msg_channel->send_msg_to_remote(string(mem, msg_len_with_msgid), udp::endpoint(udp::v4(), remote_service_id));
free(mem);
} else {
cout << "send msg failed: allocation failure." << endl;
}
return 0;
}
};
}
////////////////////////////////////////////////////////////////////////////////
using namespace demo;
const msgrpc::service_id_t k_remote_service_id = 2222;
const msgrpc::service_id_t k_local_service_id = 3333;
//TODO: unify interface of stub and implement.
struct IBuzzMath {
virtual msgrpc::Ret<ResponseBar> negative_fields(const RequestFoo&) = 0;
virtual msgrpc::Ret<ResponseBar> plus1_to_fields(const RequestFoo&) = 0;
};
////////////////////////////////////////////////////////////////////////////////
namespace msgrpc {
struct IfaceImplBase {
virtual bool onRpcInvoke(const msgrpc::ReqMsgHeader& msg_header, const char* msg, size_t len, msgrpc::RspMsgHeader& rsp_header, uint8_t*& pout_buf, uint32_t& out_buf_len) = 0;
};
struct IfaceRepository : msgrpc::Singleton<IfaceRepository> {
void add_iface_impl(iface_index_t ii, IfaceImplBase* iface) {
assert(iface != nullptr && "interface implementation can not be null");
assert(___m.find(ii) == ___m.end() && "interface can only register once");
___m[ii] = iface;
}
IfaceImplBase* get_iface_impl_by(iface_index_t ii) {
auto iter = ___m.find(ii);
return iter == ___m.end() ? nullptr : iter->second;
}
private:
std::map<iface_index_t, IfaceImplBase*> ___m;
};
template<typename T, iface_index_t iface_index>
struct InterfaceImplBaseT : IfaceImplBase {
InterfaceImplBaseT() {
IfaceRepository::instance().add_iface_impl(iface_index, this);
}
template<typename REQ, typename RSP>
bool invoke_templated_method( bool (T::*method_impl)(const REQ&, RSP&)
, const char *msg, size_t len
, uint8_t *&pout_buf, uint32_t &out_buf_len) {
REQ req;
if (! ThriftDecoder::decode(req, (uint8_t *) msg, len)) {
cout << "decode failed on remote side." << endl;
return false;
}
RSP rsp;
if (! ((T*)this->*method_impl)(req, rsp)) {
//TODO: log
return false;
}
if (! ThriftEncoder::encode(rsp, &pout_buf, &out_buf_len)) {
cout << "encode failed on remtoe side." << endl;
return false;
}
return true;
}
};
}
////////////////////////////////////////////////////////////////////////////////
namespace msgrpc {
struct RpcReqMsgHandler {
static void on_rpc_req_msg(msgrpc::msg_id_t msg_id, const char *msg, size_t len) {
cout << "remote received msg with length: " << len << endl;
assert(msg_id == k_msgrpc_request_msg_id && "invalid msg id for rpc");
if (len < sizeof(msgrpc::ReqMsgHeader)) {
cout << "invalid msg: without sufficient msg header info." << endl;
return;
}
auto *req_header = (msgrpc::ReqMsgHeader *) msg;
msg += sizeof(msgrpc::ReqMsgHeader);
msgrpc::RspMsgHeader rsp_header;
rsp_header.msgrpc_version_ = req_header->msgrpc_version_;
rsp_header.iface_index_in_service_ = req_header->iface_index_in_service_;
rsp_header.method_index_in_interface_ = req_header->method_index_in_interface_;
uint8_t *pout_buf;
uint32_t out_buf_len;
IfaceImplBase *iface = IfaceRepository::instance().get_iface_impl_by(req_header->iface_index_in_service_);
if (iface == nullptr) {
rsp_header.rpc_result_ = RpcResult::iface_not_found;
msgrpc::Config::instance().msg_channel_->send_msg(k_local_service_id, k_msgrpc_response_msg_id, (const char *) &rsp_header, sizeof(rsp_header));
return;
}
bool ret = iface->onRpcInvoke(*req_header, msg, len - sizeof(msgrpc::ReqMsgHeader), rsp_header, pout_buf, out_buf_len);
if (ret) {
return send_msg_with_header(rsp_header, pout_buf, out_buf_len);
} else {
msgrpc::Config::instance().msg_channel_->send_msg(k_local_service_id, k_msgrpc_response_msg_id, (const char *) &rsp_header, sizeof(rsp_header));
}
//TODO: using pipelined processor to handling input/output msgheader and rpc statistics.
}
static void send_msg_with_header(RspMsgHeader &rsp_header, const uint8_t *pout_buf, uint32_t out_buf_len) {
size_t rsp_len_with_header = sizeof(rsp_header) + out_buf_len;
char *mem = (char *) malloc(rsp_len_with_header);
if (mem != nullptr) {
memcpy(mem, &rsp_header, sizeof(rsp_header));
memcpy(mem + sizeof(rsp_header), pout_buf, out_buf_len);
/*TODO: replace k_local_service_id to sender id*/
Config::instance().msg_channel_->send_msg(k_local_service_id, k_msgrpc_response_msg_id, mem, rsp_len_with_header);
free(mem);
}
}
};
}
////////////////////////////////////////////////////////////////////////////////
//---------------- generate this part by macros set:
struct IBuzzMathImpl : msgrpc::InterfaceImplBaseT<IBuzzMathImpl, 1> {
bool negative_fields(const RequestFoo& req, ResponseBar& rsp);
bool plus1_to_fields(const RequestFoo& req, ResponseBar& rsp);
virtual bool onRpcInvoke(const msgrpc::ReqMsgHeader& req_header, const char* msg, size_t len, msgrpc::RspMsgHeader& rsp_header, uint8_t*& pout_buf, uint32_t& out_buf_len) override;
};
////////////////////////////////////////////////////////////////////////////////
//---------------- generate this part by macros set: interface_implement_define.h
IBuzzMathImpl buzzMath;
bool IBuzzMathImpl::onRpcInvoke(const msgrpc::ReqMsgHeader& req_header, const char* msg, size_t len, msgrpc::RspMsgHeader& rsp_header, uint8_t*& pout_buf, uint32_t& out_buf_len) {
bool ret = false;
if (req_header.method_index_in_interface_ == 1) {
ret = this->invoke_templated_method(&IBuzzMathImpl::negative_fields, msg, len, pout_buf, out_buf_len);
} else
if (req_header.method_index_in_interface_ == 2) {
ret = this->invoke_templated_method(&IBuzzMathImpl::plus1_to_fields, msg, len, pout_buf, out_buf_len);
} else
{
rsp_header.rpc_result_ = msgrpc::RpcResult::method_not_found;
return false;
}
if (! ret) {
rsp_header.rpc_result_ = msgrpc::RpcResult::failed;
}
return ret;
}
////////////////////////////////////////////////////////////////////////////////
//---------------- implement interface in here:
bool IBuzzMathImpl::negative_fields(const RequestFoo& req, ResponseBar& rsp) {
rsp.__set_bara(req.get_foob());
if (req.__isset.foob) {
rsp.__set_barb(req.fooa);
}
return true;
}
bool IBuzzMathImpl::plus1_to_fields(const RequestFoo& req, ResponseBar& rsp) {
rsp.__set_bara(1 + req.fooa);
if (req.__isset.foob) {
rsp.__set_barb(1 + req.get_foob());
}
return true;
}
////////////////////////////////////////////////////////////////////////////////
#if 0
#define ___methods_of_interface___IBuzzMath(_, ...) \
_(1, ResponseBar, negative_fields, RequestFoo, __VA_ARGS__)\
_(2, ResponseBar, plus1_to_fields, RequestFoo, __VA_ARGS__)
___as_interface(IBuzzMath, __with_interface_id(1))
#endif
////////////////////////////////////////////////////////////////////////////////
namespace msgrpc {
struct RpcStubBase {
//TODO: split into .h and .cpp
void send_rpc_request_buf(msgrpc::iface_index_t iface_index, msgrpc::method_index_t method_index, const uint8_t *pbuf, uint32_t len) const {
size_t msg_len_with_header = sizeof(msgrpc::ReqMsgHeader) + len;
char *mem = (char *) malloc(msg_len_with_header);
if (!mem) {
cout << "alloc mem failed, during sending rpc request." << endl;
return;
}
auto header = (msgrpc::ReqMsgHeader *) mem;
header->msgrpc_version_ = 0;
header->iface_index_in_service_ = iface_index;
header->method_index_in_interface_ = method_index;
memcpy(header + 1, (const char *) pbuf, len);
cout << "stub sending msg with length: " << msg_len_with_header << endl;
//TODO: find k_remote_service_id by interface name "IBuzzMath"
msgrpc::Config::instance().msg_channel_->send_msg(k_remote_service_id, k_msgrpc_request_msg_id, mem, msg_len_with_header);
free(mem);
}
template<typename REQ>
void encode_request_and_send(msgrpc::iface_index_t iface_index, msgrpc::method_index_t method_index, const REQ &req) const {
uint8_t* pbuf;
uint32_t len;
/*TODO: extract interface for encode/decode for other protocol adoption such as protobuf*/
if (!ThriftEncoder::encode(req, &pbuf, &len)) {
/*TODO: how to do with log, maybe should extract logging interface*/
cout << "encode failed." << endl;
return;
}
send_rpc_request_buf(iface_index, method_index, pbuf, len);
};
};
}
////////////////////////////////////////////////////////////////////////////////
//-----------generate by: declare and define stub macros
struct IBuzzMathStub : msgrpc::RpcStubBase {
virtual void negative_fields(const RequestFoo&);
virtual void plus1_to_fields(const RequestFoo&);
};
void IBuzzMathStub::negative_fields(const RequestFoo& req) {
encode_request_and_send(1, 1, req);
}
void IBuzzMathStub::plus1_to_fields(const RequestFoo& req) {
encode_request_and_send(1, 2, req);
}
////////////////////////////////////////////////////////////////////////////////
void local_service() {
std::this_thread::sleep_for(std::chrono::seconds(1));
msgrpc::Config::instance().initWith(new UdpMsgChannel(), k_msgrpc_request_msg_id, k_msgrpc_response_msg_id);
UdpChannel channel(k_local_service_id,
[&channel](msgrpc::msg_id_t msg_id, const char* msg, size_t len) {
if (0 == strcmp(msg, "init")) {
IBuzzMathStub buzzMath;
RequestFoo foo; foo.fooa = 97; foo.__set_foob(98);
buzzMath.negative_fields(foo);
} else {
cout << "local received msg: " << string(msg, len) << endl;
channel.close();
}
}
);
}
////////////////////////////////////////////////////////////////////////////////
void remote_service() {
msgrpc::Config::instance().initWith(new UdpMsgChannel(), k_msgrpc_request_msg_id, k_msgrpc_response_msg_id);
UdpChannel channel(k_remote_service_id,
[&channel](msgrpc::msg_id_t msg_id, const char* msg, size_t len) {
if (0 == strcmp(msg, "init")) {
return;
}
msgrpc::RpcReqMsgHandler::on_rpc_req_msg(msg_id, msg, len);
channel.close();
}
);
}
////////////////////////////////////////////////////////////////////////////////
TEST(async_rpc, should_able_to__auto__register_rpc_interface__after__application_startup) {
demo::RequestFoo req;
req.fooa = 1;
req.__set_foob(2);
std::thread local_thread(local_service);
std::thread remote_thread(remote_service);
local_thread.join();
remote_thread.join();
}
<|endoftext|> |
<commit_before>//===-- ARMELFObjectWriter.cpp - ARM ELF Writer ---------------------------===//
//
// The LLVM Compiler Infrastructure
//
// This file is distributed under the University of Illinois Open Source
// License. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//
#include "MCTargetDesc/ARMMCTargetDesc.h"
#include "MCTargetDesc/ARMFixupKinds.h"
#include "llvm/ADT/Statistic.h"
#include "llvm/ADT/StringSwitch.h"
#include "llvm/MC/MCELFObjectWriter.h"
#include "llvm/MC/MCExpr.h"
#include "llvm/MC/MCSectionELF.h"
#include "llvm/MC/MCValue.h"
#include "llvm/Support/Debug.h"
#include "llvm/Support/ErrorHandling.h"
#include "llvm/Support/raw_ostream.h"
using namespace llvm;
namespace {
class ARMELFObjectWriter : public MCELFObjectTargetWriter {
enum { DefaultEABIVersion = 0x05000000U };
unsigned GetRelocTypeInner(const MCValue &Target,
const MCFixup &Fixup,
bool IsPCRel) const;
public:
ARMELFObjectWriter(uint8_t OSABI);
virtual ~ARMELFObjectWriter();
unsigned GetRelocType(const MCValue &Target, const MCFixup &Fixup,
bool IsPCRel) const override;
bool needsRelocateWithSymbol(const MCSymbolData &SD,
unsigned Type) const override;
};
}
ARMELFObjectWriter::ARMELFObjectWriter(uint8_t OSABI)
: MCELFObjectTargetWriter(/*Is64Bit*/ false, OSABI,
ELF::EM_ARM,
/*HasRelocationAddend*/ false) {}
ARMELFObjectWriter::~ARMELFObjectWriter() {}
bool ARMELFObjectWriter::needsRelocateWithSymbol(const MCSymbolData &SD,
unsigned Type) const {
// FIXME: This is extremelly conservative. This really needs to use a
// whitelist with a clear explanation for why each realocation needs to
// point to the symbol, not to the section.
switch (Type) {
default:
return true;
case ELF::R_ARM_PREL31:
case ELF::R_ARM_ABS32:
return false;
}
}
// Need to examine the Fixup when determining whether to
// emit the relocation as an explicit symbol or as a section relative
// offset
unsigned ARMELFObjectWriter::GetRelocType(const MCValue &Target,
const MCFixup &Fixup,
bool IsPCRel) const {
return GetRelocTypeInner(Target, Fixup, IsPCRel);
}
unsigned ARMELFObjectWriter::GetRelocTypeInner(const MCValue &Target,
const MCFixup &Fixup,
bool IsPCRel) const {
MCSymbolRefExpr::VariantKind Modifier = Target.getAccessVariant();
unsigned Type = 0;
if (IsPCRel) {
switch ((unsigned)Fixup.getKind()) {
default: llvm_unreachable("Unimplemented");
case FK_Data_4:
switch (Modifier) {
default: llvm_unreachable("Unsupported Modifier");
case MCSymbolRefExpr::VK_None:
Type = ELF::R_ARM_REL32;
break;
case MCSymbolRefExpr::VK_TLSGD:
llvm_unreachable("unimplemented");
case MCSymbolRefExpr::VK_GOTTPOFF:
Type = ELF::R_ARM_TLS_IE32;
break;
case MCSymbolRefExpr::VK_GOTPCREL:
Type = ELF::R_ARM_GOT_PREL;
break;
}
break;
case ARM::fixup_arm_blx:
case ARM::fixup_arm_uncondbl:
switch (Modifier) {
case MCSymbolRefExpr::VK_PLT:
Type = ELF::R_ARM_CALL;
break;
case MCSymbolRefExpr::VK_ARM_TLSCALL:
Type = ELF::R_ARM_TLS_CALL;
break;
default:
Type = ELF::R_ARM_CALL;
break;
}
break;
case ARM::fixup_arm_condbl:
case ARM::fixup_arm_condbranch:
case ARM::fixup_arm_uncondbranch:
Type = ELF::R_ARM_JUMP24;
break;
case ARM::fixup_t2_condbranch:
case ARM::fixup_t2_uncondbranch:
Type = ELF::R_ARM_THM_JUMP24;
break;
case ARM::fixup_arm_movt_hi16:
Type = ELF::R_ARM_MOVT_PREL;
break;
case ARM::fixup_arm_movw_lo16:
Type = ELF::R_ARM_MOVW_PREL_NC;
break;
case ARM::fixup_t2_movt_hi16:
Type = ELF::R_ARM_THM_MOVT_PREL;
break;
case ARM::fixup_t2_movw_lo16:
Type = ELF::R_ARM_THM_MOVW_PREL_NC;
break;
case ARM::fixup_arm_thumb_bl:
case ARM::fixup_arm_thumb_blx:
switch (Modifier) {
case MCSymbolRefExpr::VK_ARM_TLSCALL:
Type = ELF::R_ARM_THM_TLS_CALL;
break;
default:
Type = ELF::R_ARM_THM_CALL;
break;
}
break;
}
} else {
switch ((unsigned)Fixup.getKind()) {
default: llvm_unreachable("invalid fixup kind!");
case FK_Data_4:
switch (Modifier) {
default: llvm_unreachable("Unsupported Modifier");
case MCSymbolRefExpr::VK_ARM_NONE:
Type = ELF::R_ARM_NONE;
break;
case MCSymbolRefExpr::VK_GOT:
Type = ELF::R_ARM_GOT_BREL;
break;
case MCSymbolRefExpr::VK_TLSGD:
Type = ELF::R_ARM_TLS_GD32;
break;
case MCSymbolRefExpr::VK_TPOFF:
Type = ELF::R_ARM_TLS_LE32;
break;
case MCSymbolRefExpr::VK_GOTTPOFF:
Type = ELF::R_ARM_TLS_IE32;
break;
case MCSymbolRefExpr::VK_None:
Type = ELF::R_ARM_ABS32;
break;
case MCSymbolRefExpr::VK_GOTOFF:
Type = ELF::R_ARM_GOTOFF32;
break;
case MCSymbolRefExpr::VK_GOTPCREL:
Type = ELF::R_ARM_GOT_PREL;
break;
case MCSymbolRefExpr::VK_ARM_TARGET1:
Type = ELF::R_ARM_TARGET1;
break;
case MCSymbolRefExpr::VK_ARM_TARGET2:
Type = ELF::R_ARM_TARGET2;
break;
case MCSymbolRefExpr::VK_ARM_PREL31:
Type = ELF::R_ARM_PREL31;
break;
case MCSymbolRefExpr::VK_ARM_TLSLDO:
Type = ELF::R_ARM_TLS_LDO32;
break;
case MCSymbolRefExpr::VK_ARM_TLSCALL:
Type = ELF::R_ARM_TLS_CALL;
break;
case MCSymbolRefExpr::VK_ARM_TLSDESC:
Type = ELF::R_ARM_TLS_GOTDESC;
break;
case MCSymbolRefExpr::VK_ARM_TLSDESCSEQ:
Type = ELF::R_ARM_TLS_DESCSEQ;
break;
}
break;
case ARM::fixup_arm_ldst_pcrel_12:
case ARM::fixup_arm_pcrel_10:
case ARM::fixup_arm_adr_pcrel_12:
case ARM::fixup_arm_thumb_bl:
case ARM::fixup_arm_thumb_cb:
case ARM::fixup_arm_thumb_cp:
case ARM::fixup_arm_thumb_br:
llvm_unreachable("Unimplemented");
case ARM::fixup_arm_condbranch:
case ARM::fixup_arm_uncondbranch:
Type = ELF::R_ARM_JUMP24;
break;
case ARM::fixup_arm_movt_hi16:
Type = ELF::R_ARM_MOVT_ABS;
break;
case ARM::fixup_arm_movw_lo16:
Type = ELF::R_ARM_MOVW_ABS_NC;
break;
case ARM::fixup_t2_movt_hi16:
Type = ELF::R_ARM_THM_MOVT_ABS;
break;
case ARM::fixup_t2_movw_lo16:
Type = ELF::R_ARM_THM_MOVW_ABS_NC;
break;
}
}
return Type;
}
MCObjectWriter *llvm::createARMELFObjectWriter(raw_ostream &OS,
uint8_t OSABI,
bool IsLittleEndian) {
MCELFObjectTargetWriter *MOTW = new ARMELFObjectWriter(OSABI);
return createELFObjectWriter(MOTW, OS, IsLittleEndian);
}
<commit_msg>test commit (spelling correction)<commit_after>//===-- ARMELFObjectWriter.cpp - ARM ELF Writer ---------------------------===//
//
// The LLVM Compiler Infrastructure
//
// This file is distributed under the University of Illinois Open Source
// License. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//
#include "MCTargetDesc/ARMMCTargetDesc.h"
#include "MCTargetDesc/ARMFixupKinds.h"
#include "llvm/ADT/Statistic.h"
#include "llvm/ADT/StringSwitch.h"
#include "llvm/MC/MCELFObjectWriter.h"
#include "llvm/MC/MCExpr.h"
#include "llvm/MC/MCSectionELF.h"
#include "llvm/MC/MCValue.h"
#include "llvm/Support/Debug.h"
#include "llvm/Support/ErrorHandling.h"
#include "llvm/Support/raw_ostream.h"
using namespace llvm;
namespace {
class ARMELFObjectWriter : public MCELFObjectTargetWriter {
enum { DefaultEABIVersion = 0x05000000U };
unsigned GetRelocTypeInner(const MCValue &Target,
const MCFixup &Fixup,
bool IsPCRel) const;
public:
ARMELFObjectWriter(uint8_t OSABI);
virtual ~ARMELFObjectWriter();
unsigned GetRelocType(const MCValue &Target, const MCFixup &Fixup,
bool IsPCRel) const override;
bool needsRelocateWithSymbol(const MCSymbolData &SD,
unsigned Type) const override;
};
}
ARMELFObjectWriter::ARMELFObjectWriter(uint8_t OSABI)
: MCELFObjectTargetWriter(/*Is64Bit*/ false, OSABI,
ELF::EM_ARM,
/*HasRelocationAddend*/ false) {}
ARMELFObjectWriter::~ARMELFObjectWriter() {}
bool ARMELFObjectWriter::needsRelocateWithSymbol(const MCSymbolData &SD,
unsigned Type) const {
// FIXME: This is extremely conservative. This really needs to use a
// whitelist with a clear explanation for why each realocation needs to
// point to the symbol, not to the section.
switch (Type) {
default:
return true;
case ELF::R_ARM_PREL31:
case ELF::R_ARM_ABS32:
return false;
}
}
// Need to examine the Fixup when determining whether to
// emit the relocation as an explicit symbol or as a section relative
// offset
unsigned ARMELFObjectWriter::GetRelocType(const MCValue &Target,
const MCFixup &Fixup,
bool IsPCRel) const {
return GetRelocTypeInner(Target, Fixup, IsPCRel);
}
unsigned ARMELFObjectWriter::GetRelocTypeInner(const MCValue &Target,
const MCFixup &Fixup,
bool IsPCRel) const {
MCSymbolRefExpr::VariantKind Modifier = Target.getAccessVariant();
unsigned Type = 0;
if (IsPCRel) {
switch ((unsigned)Fixup.getKind()) {
default: llvm_unreachable("Unimplemented");
case FK_Data_4:
switch (Modifier) {
default: llvm_unreachable("Unsupported Modifier");
case MCSymbolRefExpr::VK_None:
Type = ELF::R_ARM_REL32;
break;
case MCSymbolRefExpr::VK_TLSGD:
llvm_unreachable("unimplemented");
case MCSymbolRefExpr::VK_GOTTPOFF:
Type = ELF::R_ARM_TLS_IE32;
break;
case MCSymbolRefExpr::VK_GOTPCREL:
Type = ELF::R_ARM_GOT_PREL;
break;
}
break;
case ARM::fixup_arm_blx:
case ARM::fixup_arm_uncondbl:
switch (Modifier) {
case MCSymbolRefExpr::VK_PLT:
Type = ELF::R_ARM_CALL;
break;
case MCSymbolRefExpr::VK_ARM_TLSCALL:
Type = ELF::R_ARM_TLS_CALL;
break;
default:
Type = ELF::R_ARM_CALL;
break;
}
break;
case ARM::fixup_arm_condbl:
case ARM::fixup_arm_condbranch:
case ARM::fixup_arm_uncondbranch:
Type = ELF::R_ARM_JUMP24;
break;
case ARM::fixup_t2_condbranch:
case ARM::fixup_t2_uncondbranch:
Type = ELF::R_ARM_THM_JUMP24;
break;
case ARM::fixup_arm_movt_hi16:
Type = ELF::R_ARM_MOVT_PREL;
break;
case ARM::fixup_arm_movw_lo16:
Type = ELF::R_ARM_MOVW_PREL_NC;
break;
case ARM::fixup_t2_movt_hi16:
Type = ELF::R_ARM_THM_MOVT_PREL;
break;
case ARM::fixup_t2_movw_lo16:
Type = ELF::R_ARM_THM_MOVW_PREL_NC;
break;
case ARM::fixup_arm_thumb_bl:
case ARM::fixup_arm_thumb_blx:
switch (Modifier) {
case MCSymbolRefExpr::VK_ARM_TLSCALL:
Type = ELF::R_ARM_THM_TLS_CALL;
break;
default:
Type = ELF::R_ARM_THM_CALL;
break;
}
break;
}
} else {
switch ((unsigned)Fixup.getKind()) {
default: llvm_unreachable("invalid fixup kind!");
case FK_Data_4:
switch (Modifier) {
default: llvm_unreachable("Unsupported Modifier");
case MCSymbolRefExpr::VK_ARM_NONE:
Type = ELF::R_ARM_NONE;
break;
case MCSymbolRefExpr::VK_GOT:
Type = ELF::R_ARM_GOT_BREL;
break;
case MCSymbolRefExpr::VK_TLSGD:
Type = ELF::R_ARM_TLS_GD32;
break;
case MCSymbolRefExpr::VK_TPOFF:
Type = ELF::R_ARM_TLS_LE32;
break;
case MCSymbolRefExpr::VK_GOTTPOFF:
Type = ELF::R_ARM_TLS_IE32;
break;
case MCSymbolRefExpr::VK_None:
Type = ELF::R_ARM_ABS32;
break;
case MCSymbolRefExpr::VK_GOTOFF:
Type = ELF::R_ARM_GOTOFF32;
break;
case MCSymbolRefExpr::VK_GOTPCREL:
Type = ELF::R_ARM_GOT_PREL;
break;
case MCSymbolRefExpr::VK_ARM_TARGET1:
Type = ELF::R_ARM_TARGET1;
break;
case MCSymbolRefExpr::VK_ARM_TARGET2:
Type = ELF::R_ARM_TARGET2;
break;
case MCSymbolRefExpr::VK_ARM_PREL31:
Type = ELF::R_ARM_PREL31;
break;
case MCSymbolRefExpr::VK_ARM_TLSLDO:
Type = ELF::R_ARM_TLS_LDO32;
break;
case MCSymbolRefExpr::VK_ARM_TLSCALL:
Type = ELF::R_ARM_TLS_CALL;
break;
case MCSymbolRefExpr::VK_ARM_TLSDESC:
Type = ELF::R_ARM_TLS_GOTDESC;
break;
case MCSymbolRefExpr::VK_ARM_TLSDESCSEQ:
Type = ELF::R_ARM_TLS_DESCSEQ;
break;
}
break;
case ARM::fixup_arm_ldst_pcrel_12:
case ARM::fixup_arm_pcrel_10:
case ARM::fixup_arm_adr_pcrel_12:
case ARM::fixup_arm_thumb_bl:
case ARM::fixup_arm_thumb_cb:
case ARM::fixup_arm_thumb_cp:
case ARM::fixup_arm_thumb_br:
llvm_unreachable("Unimplemented");
case ARM::fixup_arm_condbranch:
case ARM::fixup_arm_uncondbranch:
Type = ELF::R_ARM_JUMP24;
break;
case ARM::fixup_arm_movt_hi16:
Type = ELF::R_ARM_MOVT_ABS;
break;
case ARM::fixup_arm_movw_lo16:
Type = ELF::R_ARM_MOVW_ABS_NC;
break;
case ARM::fixup_t2_movt_hi16:
Type = ELF::R_ARM_THM_MOVT_ABS;
break;
case ARM::fixup_t2_movw_lo16:
Type = ELF::R_ARM_THM_MOVW_ABS_NC;
break;
}
}
return Type;
}
MCObjectWriter *llvm::createARMELFObjectWriter(raw_ostream &OS,
uint8_t OSABI,
bool IsLittleEndian) {
MCELFObjectTargetWriter *MOTW = new ARMELFObjectWriter(OSABI);
return createELFObjectWriter(MOTW, OS, IsLittleEndian);
}
<|endoftext|> |
<commit_before>// Copyright (c) 2019 Chris Ohk, Youngjoong Kim, SeungHyun Jeon
// We are making my contributions/submissions to this project solely in our
// personal capacity and are not conveying any rights to any intellectual
// property of any third parties.
#include <Utils/CardSetUtils.hpp>
#include <Rosetta/Actions/Draw.hpp>
#include <Rosetta/Cards/Cards.hpp>
using namespace RosettaStone;
using namespace PlayerTasks;
using namespace SimpleTasks;
TEST(CoreCardsGen, EX1_066)
{
GameConfig config;
config.player1Class = CardClass::WARRIOR;
config.player2Class = CardClass::ROGUE;
config.startPlayer = PlayerType::PLAYER1;
Game game(config);
game.StartGame();
Player& curPlayer = game.GetCurrentPlayer();
Player& opPlayer = game.GetCurrentPlayer().GetOpponent();
curPlayer.maximumMana = 10;
curPlayer.currentMana = 10;
opPlayer.maximumMana = 10;
opPlayer.currentMana = 10;
const auto card1 = Generic::DrawCard(
curPlayer, Cards::GetInstance().FindCardByName("Fiery War Axe"));
const auto card2 = Generic::DrawCard(
opPlayer, Cards::GetInstance().FindCardByName("Acidic Swamp Ooze"));
Task::Run(curPlayer, PlayCardTask::Weapon(curPlayer, card1));
EXPECT_EQ(curPlayer.GetHero()->HasWeapon(), true);
Task::Run(opPlayer, PlayCardTask::Minion(opPlayer, card2));
EXPECT_EQ(curPlayer.GetHero()->HasWeapon(), false);
}
TEST(CoreCardsGen, EX1_306)
{
GameConfig config;
config.player1Class = CardClass::WARLOCK;
config.player2Class = CardClass::WARRIOR;
config.startPlayer = PlayerType::PLAYER1;
Game game(config);
game.StartGame();
Player& curPlayer = game.GetCurrentPlayer();
Player& opPlayer = game.GetCurrentPlayer().GetOpponent();
curPlayer.maximumMana = 10;
curPlayer.currentMana = 10;
opPlayer.maximumMana = 10;
opPlayer.currentMana = 10;
const auto card1 = Generic::DrawCard(
curPlayer, Cards::GetInstance().FindCardByName("Succubus"));
Generic::DrawCard(curPlayer,
Cards::GetInstance().FindCardByName("Stonetusk Boar"));
const auto card2 = Generic::DrawCard(
opPlayer, Cards::GetInstance().FindCardByName("Acidic Swamp Ooze"));
Generic::DrawCard(opPlayer,
Cards::GetInstance().FindCardByName("Fiery War Axe"));
Task::Run(curPlayer, PlayCardTask::Minion(curPlayer, card1));
EXPECT_EQ(curPlayer.GetHand().GetNumOfCards(), 0u);
Task::Run(opPlayer, PlayCardTask::Minion(opPlayer, card2));
EXPECT_EQ(opPlayer.GetHand().GetNumOfCards(), 2u);
}
TEST(CoreCardsGen, CS2_041)
{
GameConfig config;
config.player1Class = CardClass::SHAMAN;
config.player2Class = CardClass::ROGUE;
config.startPlayer = PlayerType::PLAYER1;
Game game(config);
game.StartGame();
Player& curPlayer = game.GetCurrentPlayer();
Player& opPlayer = game.GetCurrentPlayer().GetOpponent();
curPlayer.maximumMana = 10;
curPlayer.currentMana = 10;
opPlayer.maximumMana = 10;
opPlayer.currentMana = 10;
auto& curField = curPlayer.GetField();
const auto& opField = opPlayer.GetField();
const auto card1 = Generic::DrawCard(
curPlayer, Cards::GetInstance().FindCardByName("Acidic Swamp Ooze"));
const auto card2 = Generic::DrawCard(
curPlayer, Cards::GetInstance().FindCardByName("Ancestral Healing"));
const auto card3 = Generic::DrawCard(
opPlayer, Cards::GetInstance().FindCardByName("Stonetusk Boar"));
Task::Run(curPlayer, PlayCardTask::Minion(curPlayer, card1));
Task::Run(opPlayer, PlayCardTask::Minion(opPlayer, card3));
Task::Run(opPlayer, AttackTask(card3, card1));
EXPECT_EQ(curField.GetMinion(0)->health, 1);
EXPECT_EQ(opField.GetNumOfMinions(), 0u);
Task::Run(curPlayer, PlayCardTask::SpellTarget(curPlayer, card2, card1));
EXPECT_EQ(curField.GetMinion(0)->health, 2);
EXPECT_EQ(curField.GetMinion(0)->GetGameTag(GameTag::TAUNT), 1);
}
TEST(CoreCardsGen, CS2_088)
{
GameConfig config;
config.player1Class = CardClass::DRUID;
config.player2Class = CardClass::PALADIN;
config.startPlayer = PlayerType::PLAYER1;
Game game(config);
game.StartGame();
Player& curPlayer = game.GetCurrentPlayer();
Player& opPlayer = game.GetCurrentPlayer().GetOpponent();
curPlayer.maximumMana = 10;
curPlayer.currentMana = 10;
opPlayer.maximumMana = 10;
opPlayer.currentMana = 10;
opPlayer.GetHero()->health = 24;
const auto card1 = Generic::DrawCard(
opPlayer, Cards::GetInstance().FindCardByName("Guardian of Kings"));
Task::Run(opPlayer, PlayCardTask::Minion(opPlayer, card1));
EXPECT_EQ(opPlayer.GetHero()->maxHealth, opPlayer.GetHero()->health);
}
TEST(CoreCardsGen, CS1_112)
{
GameConfig config;
config.player1Class = CardClass::PRIEST;
config.player2Class = CardClass::PALADIN;
config.startPlayer = PlayerType::PLAYER1;
config.doFillDecks = true;
Game game(config);
game.StartGame();
Player& curPlayer = game.GetCurrentPlayer();
Player& opPlayer = game.GetCurrentPlayer().GetOpponent();
curPlayer.maximumMana = 10;
curPlayer.currentMana = 10;
opPlayer.maximumMana = 10;
opPlayer.currentMana = 10;
curPlayer.GetHero()->health = 26;
auto& curField = curPlayer.GetField();
auto& opField = opPlayer.GetField();
const auto card1 = Generic::DrawCard(
curPlayer, Cards::GetInstance().FindCardByName("Windfury Harpy"));
const auto card2 = Generic::DrawCard(
curPlayer, Cards::GetInstance().FindCardByName("Boulderfist Ogre"));
const auto card3 = Generic::DrawCard(
curPlayer, Cards::GetInstance().FindCardByName("Holy Nova"));
const auto card4 = Generic::DrawCard(
opPlayer, Cards::GetInstance().FindCardByName("Argent Squire"));
const auto card5 = Generic::DrawCard(
opPlayer, Cards::GetInstance().FindCardByName("Worgen Infiltrator"));
Task::Run(curPlayer, PlayCardTask::Minion(curPlayer, card1));
curPlayer.currentMana = 10;
Task::Run(curPlayer, PlayCardTask::Minion(curPlayer, card2));
curPlayer.currentMana = 10;
Task::Run(opPlayer, PlayCardTask::Minion(opPlayer, card4));
Task::Run(opPlayer, PlayCardTask::Minion(opPlayer, card5));
Task::Run(curPlayer, EndTurnTask());
Task::Run(opPlayer, EndTurnTask());
Task::Run(curPlayer, AttackTask(card1, card4));
EXPECT_EQ(curField.GetMinion(0)->health, 4);
EXPECT_EQ(opField.GetMinion(0)->GetGameTag(GameTag::DIVINE_SHIELD), 0);
Task::Run(curPlayer, PlayCardTask::Spell(curPlayer, card3));
EXPECT_EQ(curPlayer.GetHero()->health, 28);
EXPECT_EQ(opPlayer.GetHero()->health, 28);
EXPECT_EQ(curField.GetMinion(0)->health, 5);
EXPECT_EQ(curField.GetMinion(1)->health, 7);
EXPECT_EQ(opField.GetNumOfMinions(), 0u);
}
TEST(CoreCardsGen, CS1_113)
{
GameConfig config;
config.player1Class = CardClass::PRIEST;
config.player2Class = CardClass::PALADIN;
config.startPlayer = PlayerType::PLAYER1;
Game game(config);
game.StartGame();
Player& curPlayer = game.GetCurrentPlayer();
Player& opPlayer = game.GetCurrentPlayer().GetOpponent();
curPlayer.maximumMana = 10;
curPlayer.currentMana = 10;
opPlayer.maximumMana = 10;
opPlayer.currentMana = 10;
const auto& curField = curPlayer.GetField();
const auto& opField = opPlayer.GetField();
const auto card1 = Generic::DrawCard(
curPlayer, Cards::GetInstance().FindCardByName("Windfury Harpy"));
const auto card2 = Generic::DrawCard(
opPlayer, Cards::GetInstance().FindCardByName("Boulderfist Ogre"));
const auto card3 = Generic::DrawCard(
curPlayer, Cards::GetInstance().FindCardByName("Mind Control"));
const auto card4 = Generic::DrawCard(
opPlayer, Cards::GetInstance().FindCardByName("Mind Control"));
Task::Run(curPlayer, PlayCardTask::Minion(curPlayer, card1));
curPlayer.currentMana = 10;
Task::Run(opPlayer, PlayCardTask::Minion(opPlayer, card2));
EXPECT_EQ(curField.GetNumOfMinions(), 1u);
EXPECT_EQ(opField.GetNumOfMinions(), 1u);
Task::Run(curPlayer, PlayCardTask::SpellTarget(curPlayer, card3, card2));
EXPECT_EQ(curField.GetNumOfMinions(), 2u);
EXPECT_EQ(opField.GetNumOfMinions(), 0u);
opPlayer.currentMana = 10;
auto curHero = curPlayer.GetHero();
Task::Run(opPlayer, PlayCardTask::SpellTarget(curPlayer, card4, curHero));
EXPECT_EQ(opPlayer.GetHand().GetNumOfCards(), 2u);
}
TEST(CoreCardsGen, EX1_129)
{
GameConfig config;
config.player1Class = CardClass::ROGUE;
config.player2Class = CardClass::PALADIN;
config.startPlayer = PlayerType::PLAYER1;
config.doFillDecks = true;
Game game(config);
game.StartGame();
Player& curPlayer = game.GetCurrentPlayer();
Player& opPlayer = game.GetCurrentPlayer().GetOpponent();
curPlayer.maximumMana = 10;
curPlayer.currentMana = 10;
opPlayer.maximumMana = 10;
opPlayer.currentMana = 10;
opPlayer.GetHero()->health = 30;
const auto& curField = curPlayer.GetField();
const auto& opField = opPlayer.GetField();
const auto card1 = Generic::DrawCard(
curPlayer, Cards::GetInstance().FindCardByName("Fan of Knives"));
const auto card2 = Generic::DrawCard(
curPlayer, Cards::GetInstance().FindCardByName("Fan of Knives"));
const auto card3 = Generic::DrawCard(
opPlayer, Cards::GetInstance().FindCardByName("Acidic Swamp Ooze"));
const auto card4 = Generic::DrawCard(
opPlayer, Cards::GetInstance().FindCardByName("Acidic Swamp Ooze"));
const auto card5 = Generic::DrawCard(
opPlayer, Cards::GetInstance().FindCardByName("Wolfrider"));
Task::Run(opPlayer, PlayCardTask::Minion(opPlayer, card3));
Task::Run(opPlayer, PlayCardTask::Minion(opPlayer, card4));
Task::Run(opPlayer, PlayCardTask::Minion(opPlayer, card5));
EXPECT_EQ(curField.GetNumOfMinions(), 0u);
EXPECT_EQ(opField.GetNumOfMinions(), 3u);
EXPECT_EQ(curPlayer.GetHand().GetNumOfCards(), 6u);
Task::Run(curPlayer, PlayCardTask::Spell(curPlayer, card1));
EXPECT_EQ(curPlayer.GetHand().GetNumOfCards(), 6u);
EXPECT_EQ(opField.GetNumOfMinions(), 2u);
Task::Run(curPlayer, PlayCardTask::Spell(curPlayer, card2));
EXPECT_EQ(curPlayer.GetHand().GetNumOfCards(), 6u);
EXPECT_EQ(opField.GetNumOfMinions(), 0u);
EXPECT_EQ(opPlayer.GetHero()->health, 30);
}
TEST(CoreCardsGen, DS1_233)
{
GameConfig config;
config.player1Class = CardClass::PRIEST;
config.player2Class = CardClass::PALADIN;
config.startPlayer = PlayerType::PLAYER1;
config.doFillDecks = true;
Game game(config);
game.StartGame();
Player& curPlayer = game.GetCurrentPlayer();
Player& opPlayer = game.GetCurrentPlayer().GetOpponent();
curPlayer.maximumMana = 10;
curPlayer.currentMana = 10;
opPlayer.maximumMana = 10;
opPlayer.currentMana = 10;
opPlayer.GetHero()->health = 30;
const auto card1 = Generic::DrawCard(
curPlayer, Cards::GetInstance().FindCardByName("Mind Blast"));
auto opHero = opPlayer.GetHero();
Task::Run(curPlayer, PlayCardTask::SpellTarget(curPlayer, card1, opHero));
EXPECT_EQ(opPlayer.GetHero()->health, 25);
}<commit_msg>fix: delete useless code<commit_after>// Copyright (c) 2019 Chris Ohk, Youngjoong Kim, SeungHyun Jeon
// We are making my contributions/submissions to this project solely in our
// personal capacity and are not conveying any rights to any intellectual
// property of any third parties.
#include <Utils/CardSetUtils.hpp>
#include <Rosetta/Actions/Draw.hpp>
#include <Rosetta/Cards/Cards.hpp>
using namespace RosettaStone;
using namespace PlayerTasks;
using namespace SimpleTasks;
TEST(CoreCardsGen, EX1_066)
{
GameConfig config;
config.player1Class = CardClass::WARRIOR;
config.player2Class = CardClass::ROGUE;
config.startPlayer = PlayerType::PLAYER1;
Game game(config);
game.StartGame();
Player& curPlayer = game.GetCurrentPlayer();
Player& opPlayer = game.GetCurrentPlayer().GetOpponent();
curPlayer.maximumMana = 10;
curPlayer.currentMana = 10;
opPlayer.maximumMana = 10;
opPlayer.currentMana = 10;
const auto card1 = Generic::DrawCard(
curPlayer, Cards::GetInstance().FindCardByName("Fiery War Axe"));
const auto card2 = Generic::DrawCard(
opPlayer, Cards::GetInstance().FindCardByName("Acidic Swamp Ooze"));
Task::Run(curPlayer, PlayCardTask::Weapon(curPlayer, card1));
EXPECT_EQ(curPlayer.GetHero()->HasWeapon(), true);
Task::Run(opPlayer, PlayCardTask::Minion(opPlayer, card2));
EXPECT_EQ(curPlayer.GetHero()->HasWeapon(), false);
}
TEST(CoreCardsGen, EX1_306)
{
GameConfig config;
config.player1Class = CardClass::WARLOCK;
config.player2Class = CardClass::WARRIOR;
config.startPlayer = PlayerType::PLAYER1;
Game game(config);
game.StartGame();
Player& curPlayer = game.GetCurrentPlayer();
Player& opPlayer = game.GetCurrentPlayer().GetOpponent();
curPlayer.maximumMana = 10;
curPlayer.currentMana = 10;
opPlayer.maximumMana = 10;
opPlayer.currentMana = 10;
const auto card1 = Generic::DrawCard(
curPlayer, Cards::GetInstance().FindCardByName("Succubus"));
Generic::DrawCard(curPlayer,
Cards::GetInstance().FindCardByName("Stonetusk Boar"));
const auto card2 = Generic::DrawCard(
opPlayer, Cards::GetInstance().FindCardByName("Acidic Swamp Ooze"));
Generic::DrawCard(opPlayer,
Cards::GetInstance().FindCardByName("Fiery War Axe"));
Task::Run(curPlayer, PlayCardTask::Minion(curPlayer, card1));
EXPECT_EQ(curPlayer.GetHand().GetNumOfCards(), 0u);
Task::Run(opPlayer, PlayCardTask::Minion(opPlayer, card2));
EXPECT_EQ(opPlayer.GetHand().GetNumOfCards(), 2u);
}
TEST(CoreCardsGen, CS2_041)
{
GameConfig config;
config.player1Class = CardClass::SHAMAN;
config.player2Class = CardClass::ROGUE;
config.startPlayer = PlayerType::PLAYER1;
Game game(config);
game.StartGame();
Player& curPlayer = game.GetCurrentPlayer();
Player& opPlayer = game.GetCurrentPlayer().GetOpponent();
curPlayer.maximumMana = 10;
curPlayer.currentMana = 10;
opPlayer.maximumMana = 10;
opPlayer.currentMana = 10;
auto& curField = curPlayer.GetField();
const auto& opField = opPlayer.GetField();
const auto card1 = Generic::DrawCard(
curPlayer, Cards::GetInstance().FindCardByName("Acidic Swamp Ooze"));
const auto card2 = Generic::DrawCard(
curPlayer, Cards::GetInstance().FindCardByName("Ancestral Healing"));
const auto card3 = Generic::DrawCard(
opPlayer, Cards::GetInstance().FindCardByName("Stonetusk Boar"));
Task::Run(curPlayer, PlayCardTask::Minion(curPlayer, card1));
Task::Run(opPlayer, PlayCardTask::Minion(opPlayer, card3));
Task::Run(opPlayer, AttackTask(card3, card1));
EXPECT_EQ(curField.GetMinion(0)->health, 1);
EXPECT_EQ(opField.GetNumOfMinions(), 0u);
Task::Run(curPlayer, PlayCardTask::SpellTarget(curPlayer, card2, card1));
EXPECT_EQ(curField.GetMinion(0)->health, 2);
EXPECT_EQ(curField.GetMinion(0)->GetGameTag(GameTag::TAUNT), 1);
}
TEST(CoreCardsGen, CS2_088)
{
GameConfig config;
config.player1Class = CardClass::DRUID;
config.player2Class = CardClass::PALADIN;
config.startPlayer = PlayerType::PLAYER1;
Game game(config);
game.StartGame();
Player& curPlayer = game.GetCurrentPlayer();
Player& opPlayer = game.GetCurrentPlayer().GetOpponent();
curPlayer.maximumMana = 10;
curPlayer.currentMana = 10;
opPlayer.maximumMana = 10;
opPlayer.currentMana = 10;
opPlayer.GetHero()->health = 24;
const auto card1 = Generic::DrawCard(
opPlayer, Cards::GetInstance().FindCardByName("Guardian of Kings"));
Task::Run(opPlayer, PlayCardTask::Minion(opPlayer, card1));
EXPECT_EQ(opPlayer.GetHero()->maxHealth, opPlayer.GetHero()->health);
}
TEST(CoreCardsGen, CS1_112)
{
GameConfig config;
config.player1Class = CardClass::PRIEST;
config.player2Class = CardClass::PALADIN;
config.startPlayer = PlayerType::PLAYER1;
config.doFillDecks = true;
Game game(config);
game.StartGame();
Player& curPlayer = game.GetCurrentPlayer();
Player& opPlayer = game.GetCurrentPlayer().GetOpponent();
curPlayer.maximumMana = 10;
curPlayer.currentMana = 10;
opPlayer.maximumMana = 10;
opPlayer.currentMana = 10;
curPlayer.GetHero()->health = 26;
auto& curField = curPlayer.GetField();
auto& opField = opPlayer.GetField();
const auto card1 = Generic::DrawCard(
curPlayer, Cards::GetInstance().FindCardByName("Windfury Harpy"));
const auto card2 = Generic::DrawCard(
curPlayer, Cards::GetInstance().FindCardByName("Boulderfist Ogre"));
const auto card3 = Generic::DrawCard(
curPlayer, Cards::GetInstance().FindCardByName("Holy Nova"));
const auto card4 = Generic::DrawCard(
opPlayer, Cards::GetInstance().FindCardByName("Argent Squire"));
const auto card5 = Generic::DrawCard(
opPlayer, Cards::GetInstance().FindCardByName("Worgen Infiltrator"));
Task::Run(curPlayer, PlayCardTask::Minion(curPlayer, card1));
curPlayer.currentMana = 10;
Task::Run(curPlayer, PlayCardTask::Minion(curPlayer, card2));
curPlayer.currentMana = 10;
Task::Run(opPlayer, PlayCardTask::Minion(opPlayer, card4));
Task::Run(opPlayer, PlayCardTask::Minion(opPlayer, card5));
Task::Run(curPlayer, EndTurnTask());
Task::Run(opPlayer, EndTurnTask());
Task::Run(curPlayer, AttackTask(card1, card4));
EXPECT_EQ(curField.GetMinion(0)->health, 4);
EXPECT_EQ(opField.GetMinion(0)->GetGameTag(GameTag::DIVINE_SHIELD), 0);
Task::Run(curPlayer, PlayCardTask::Spell(curPlayer, card3));
EXPECT_EQ(curPlayer.GetHero()->health, 28);
EXPECT_EQ(opPlayer.GetHero()->health, 28);
EXPECT_EQ(curField.GetMinion(0)->health, 5);
EXPECT_EQ(curField.GetMinion(1)->health, 7);
EXPECT_EQ(opField.GetNumOfMinions(), 0u);
}
TEST(CoreCardsGen, CS1_113)
{
GameConfig config;
config.player1Class = CardClass::PRIEST;
config.player2Class = CardClass::PALADIN;
config.startPlayer = PlayerType::PLAYER1;
Game game(config);
game.StartGame();
Player& curPlayer = game.GetCurrentPlayer();
Player& opPlayer = game.GetCurrentPlayer().GetOpponent();
curPlayer.maximumMana = 10;
curPlayer.currentMana = 10;
opPlayer.maximumMana = 10;
opPlayer.currentMana = 10;
const auto& curField = curPlayer.GetField();
const auto& opField = opPlayer.GetField();
const auto card1 = Generic::DrawCard(
curPlayer, Cards::GetInstance().FindCardByName("Windfury Harpy"));
const auto card2 = Generic::DrawCard(
opPlayer, Cards::GetInstance().FindCardByName("Boulderfist Ogre"));
const auto card3 = Generic::DrawCard(
curPlayer, Cards::GetInstance().FindCardByName("Mind Control"));
const auto card4 = Generic::DrawCard(
opPlayer, Cards::GetInstance().FindCardByName("Mind Control"));
Task::Run(curPlayer, PlayCardTask::Minion(curPlayer, card1));
curPlayer.currentMana = 10;
Task::Run(opPlayer, PlayCardTask::Minion(opPlayer, card2));
EXPECT_EQ(curField.GetNumOfMinions(), 1u);
EXPECT_EQ(opField.GetNumOfMinions(), 1u);
Task::Run(curPlayer, PlayCardTask::SpellTarget(curPlayer, card3, card2));
EXPECT_EQ(curField.GetNumOfMinions(), 2u);
EXPECT_EQ(opField.GetNumOfMinions(), 0u);
opPlayer.currentMana = 10;
auto curHero = curPlayer.GetHero();
Task::Run(opPlayer, PlayCardTask::SpellTarget(curPlayer, card4, curHero));
EXPECT_EQ(opPlayer.GetHand().GetNumOfCards(), 2u);
}
TEST(CoreCardsGen, EX1_129)
{
GameConfig config;
config.player1Class = CardClass::ROGUE;
config.player2Class = CardClass::PALADIN;
config.startPlayer = PlayerType::PLAYER1;
config.doFillDecks = true;
Game game(config);
game.StartGame();
Player& curPlayer = game.GetCurrentPlayer();
Player& opPlayer = game.GetCurrentPlayer().GetOpponent();
curPlayer.maximumMana = 10;
curPlayer.currentMana = 10;
opPlayer.maximumMana = 10;
opPlayer.currentMana = 10;
opPlayer.GetHero()->health = 30;
const auto& curField = curPlayer.GetField();
const auto& opField = opPlayer.GetField();
const auto card1 = Generic::DrawCard(
curPlayer, Cards::GetInstance().FindCardByName("Fan of Knives"));
const auto card2 = Generic::DrawCard(
curPlayer, Cards::GetInstance().FindCardByName("Fan of Knives"));
const auto card3 = Generic::DrawCard(
opPlayer, Cards::GetInstance().FindCardByName("Acidic Swamp Ooze"));
const auto card4 = Generic::DrawCard(
opPlayer, Cards::GetInstance().FindCardByName("Acidic Swamp Ooze"));
const auto card5 = Generic::DrawCard(
opPlayer, Cards::GetInstance().FindCardByName("Wolfrider"));
Task::Run(opPlayer, PlayCardTask::Minion(opPlayer, card3));
Task::Run(opPlayer, PlayCardTask::Minion(opPlayer, card4));
Task::Run(opPlayer, PlayCardTask::Minion(opPlayer, card5));
EXPECT_EQ(curField.GetNumOfMinions(), 0u);
EXPECT_EQ(opField.GetNumOfMinions(), 3u);
EXPECT_EQ(curPlayer.GetHand().GetNumOfCards(), 6u);
Task::Run(curPlayer, PlayCardTask::Spell(curPlayer, card1));
EXPECT_EQ(curPlayer.GetHand().GetNumOfCards(), 6u);
EXPECT_EQ(opField.GetNumOfMinions(), 2u);
Task::Run(curPlayer, PlayCardTask::Spell(curPlayer, card2));
EXPECT_EQ(curPlayer.GetHand().GetNumOfCards(), 6u);
EXPECT_EQ(opField.GetNumOfMinions(), 0u);
EXPECT_EQ(opPlayer.GetHero()->health, 30);
}
TEST(CoreCardsGen, DS1_233)
{
GameConfig config;
config.player1Class = CardClass::PRIEST;
config.player2Class = CardClass::PALADIN;
config.startPlayer = PlayerType::PLAYER1;
config.doFillDecks = true;
Game game(config);
game.StartGame();
Player& curPlayer = game.GetCurrentPlayer();
Player& opPlayer = game.GetCurrentPlayer().GetOpponent();
curPlayer.maximumMana = 10;
curPlayer.currentMana = 10;
opPlayer.maximumMana = 10;
opPlayer.currentMana = 10;
const auto card1 = Generic::DrawCard(
curPlayer, Cards::GetInstance().FindCardByName("Mind Blast"));
auto opHero = opPlayer.GetHero();
Task::Run(curPlayer, PlayCardTask::SpellTarget(curPlayer, card1, opHero));
EXPECT_EQ(opPlayer.GetHero()->health, 25);
}<|endoftext|> |
<commit_before>// Copyright (c) 2019 Chris Ohk, Youngjoong Kim, SeungHyun Jeon
// We are making my contributions/submissions to this project solely in our
// personal capacity and are not conveying any rights to any intellectual
// property of any third parties.
#include "gtest/gtest.h"
#include <Rosetta/Cards/Cards.hpp>
#include <Rosetta/Commons/Utils.hpp>
#include <Rosetta/Games/Game.hpp>
#include <Rosetta/Games/GameConfig.hpp>
#include <Rosetta/Policies/RandomPolicy.hpp>
#include <Rosetta/Tasks/PlayerTasks/AttackTask.hpp>
#include <Rosetta/Tasks/PlayerTasks/ChooseTask.hpp>
#include <Rosetta/Tasks/PlayerTasks/EndTurnTask.hpp>
#include <Rosetta/Tasks/PlayerTasks/PlayCardTask.hpp>
using namespace RosettaStone;
TEST(RandomPolicy, AutoRun)
{
GameConfig config;
config.player1Class = CardClass::ROGUE;
config.player2Class = CardClass::PALADIN;
config.startPlayer = PlayerType::RANDOM;
config.doShuffle = false;
config.doFillDecks = false;
config.skipMulligan = true;
config.autoRun = true;
std::array<std::string, START_DECK_SIZE> deck = {
"CS2_106", "CS2_105", "CS1_112", "CS1_112", // 1
"CS1_113", "CS1_113", "CS1_130", "CS1_130", // 2
"CS2_007", "CS2_007", "CS2_022", "CS2_022", // 3
"CS2_023", "CS2_023", "CS2_024", "CS2_024", // 4
"CS2_025", "CS2_025", "CS2_026", "CS2_026", // 5
"CS2_027", "CS2_027", "CS2_029", "CS2_029", // 6
"CS2_032", "CS2_032", "CS2_033", "CS2_033", // 7
"CS2_037", "CS2_037"
};
for (size_t i = 0; i < START_DECK_SIZE; ++i)
{
config.player1Deck[i] = Cards::GetInstance().FindCardByID(deck[i]);
config.player2Deck[i] = Cards::GetInstance().FindCardByID(deck[i]);
}
Game game(config);
RandomPolicy policy;
game.GetPlayer1().policy = &policy;
game.GetPlayer2().policy = &policy;
game.StartGame();
}
TEST(RandomPolicy, Mulligan)
{
for (int i = 0; i < 10; ++i)
{
GameConfig config;
config.player1Class = CardClass::ROGUE;
config.player2Class = CardClass::PALADIN;
config.startPlayer = PlayerType::RANDOM;
config.doShuffle = false;
config.doFillDecks = false;
config.skipMulligan = false;
config.autoRun = true;
std::array<std::string, START_DECK_SIZE> deck = {
"CS2_106", "CS2_105", "CS1_112", "CS1_112", // 1
"CS1_113", "CS1_113", "CS1_130", "CS1_130", // 2
"CS2_007", "CS2_007", "CS2_022", "CS2_022", // 3
"CS2_023", "CS2_023", "CS2_024", "CS2_024", // 4
"CS2_025", "CS2_025", "CS2_026", "CS2_026", // 5
"CS2_027", "CS2_027", "CS2_029", "CS2_029", // 6
"CS2_032", "CS2_032", "CS2_033", "CS2_033", // 7
"CS2_037", "CS2_037"
};
for (size_t j = 0; j < START_DECK_SIZE; ++j)
{
config.player1Deck[j] = Cards::GetInstance().FindCardByID(deck[j]);
config.player2Deck[j] = Cards::GetInstance().FindCardByID(deck[j]);
}
Game game(config);
RandomPolicy policy;
game.GetPlayer1().policy = &policy;
game.GetPlayer2().policy = &policy;
game.StartGame();
Player& player1 = game.GetPlayer1();
// Request mulligan choices to policy.
TaskMeta p1Choice = player1.policy->Require(player1, TaskID::MULLIGAN);
// Get mulligan choices from policy.
game.Process(
player1,
PlayerTasks::ChooseTask::Mulligan(
player1, p1Choice.GetObject<std::vector<std::size_t>>()));
Player& player2 = game.GetPlayer2();
// Request mulligan choices to policy.
TaskMeta p2Choice = player2.policy->Require(player2, TaskID::MULLIGAN);
// Get mulligan choices from policy.
game.Process(
player2,
PlayerTasks::ChooseTask::Mulligan(
player2, p2Choice.GetObject<std::vector<std::size_t>>()));
game.MainReady();
while (game.state != State::COMPLETE)
{
auto& player = game.GetCurrentPlayer();
ITask* nextAction = player.GetNextAction();
game.Process(player, nextAction);
}
EXPECT_EQ(game.state, State::COMPLETE);
}
}<commit_msg>refactor: Apply changes of PlayPolicy() method<commit_after>// Copyright (c) 2019 Chris Ohk, Youngjoong Kim, SeungHyun Jeon
// We are making my contributions/submissions to this project solely in our
// personal capacity and are not conveying any rights to any intellectual
// property of any third parties.
#include "gtest/gtest.h"
#include <Rosetta/Cards/Cards.hpp>
#include <Rosetta/Games/Game.hpp>
#include <Rosetta/Games/GameConfig.hpp>
#include <Rosetta/Policies/RandomPolicy.hpp>
#include <Rosetta/Tasks/PlayerTasks/ChooseTask.hpp>
using namespace RosettaStone;
TEST(RandomPolicy, AutoRun)
{
GameConfig config;
config.player1Class = CardClass::ROGUE;
config.player2Class = CardClass::PALADIN;
config.startPlayer = PlayerType::RANDOM;
config.doShuffle = false;
config.doFillDecks = false;
config.skipMulligan = true;
config.autoRun = true;
std::array<std::string, START_DECK_SIZE> deck = {
"CS2_106", "CS2_105", "CS1_112", "CS1_112", // 1
"CS1_113", "CS1_113", "CS1_130", "CS1_130", // 2
"CS2_007", "CS2_007", "CS2_022", "CS2_022", // 3
"CS2_023", "CS2_023", "CS2_024", "CS2_024", // 4
"CS2_025", "CS2_025", "CS2_026", "CS2_026", // 5
"CS2_027", "CS2_027", "CS2_029", "CS2_029", // 6
"CS2_032", "CS2_032", "CS2_033", "CS2_033", // 7
"CS2_037", "CS2_037"
};
for (size_t i = 0; i < START_DECK_SIZE; ++i)
{
config.player1Deck[i] = Cards::GetInstance().FindCardByID(deck[i]);
config.player2Deck[i] = Cards::GetInstance().FindCardByID(deck[i]);
}
Game game(config);
RandomPolicy policy;
game.GetPlayer1().policy = &policy;
game.GetPlayer2().policy = &policy;
game.StartGame();
}
TEST(RandomPolicy, Mulligan)
{
for (int i = 0; i < 10; ++i)
{
GameConfig config;
config.player1Class = CardClass::ROGUE;
config.player2Class = CardClass::PALADIN;
config.startPlayer = PlayerType::RANDOM;
config.doShuffle = false;
config.doFillDecks = false;
config.skipMulligan = false;
config.autoRun = true;
std::array<std::string, START_DECK_SIZE> deck = {
"CS2_106", "CS2_105", "CS1_112", "CS1_112", // 1
"CS1_113", "CS1_113", "CS1_130", "CS1_130", // 2
"CS2_007", "CS2_007", "CS2_022", "CS2_022", // 3
"CS2_023", "CS2_023", "CS2_024", "CS2_024", // 4
"CS2_025", "CS2_025", "CS2_026", "CS2_026", // 5
"CS2_027", "CS2_027", "CS2_029", "CS2_029", // 6
"CS2_032", "CS2_032", "CS2_033", "CS2_033", // 7
"CS2_037", "CS2_037"
};
for (size_t j = 0; j < START_DECK_SIZE; ++j)
{
config.player1Deck[j] = Cards::GetInstance().FindCardByID(deck[j]);
config.player2Deck[j] = Cards::GetInstance().FindCardByID(deck[j]);
}
Game game(config);
RandomPolicy policy;
game.GetPlayer1().policy = &policy;
game.GetPlayer2().policy = &policy;
game.PlayPolicy();
EXPECT_EQ(game.state, State::COMPLETE);
}
}<|endoftext|> |
<commit_before>#ifndef CUFFT_HPP_
#define CUFFT_HPP_
#include "application.hpp"
#include "timer.hpp"
#include "fft.hpp"
#include "benchmark_suite.hpp"
#include "cufft_helper.hpp"
#include "traits.hpp"
#include <array>
#include <cufft.h>
#include <vector_types.h>
namespace gearshifft {
namespace CuFFT {
namespace traits{
template<typename T_Precision=float>
struct Types
{
using ComplexType = cufftComplex;
using RealType = cufftReal;
static constexpr cufftType FFTForward = CUFFT_R2C;
static constexpr cufftType FFTComplex = CUFFT_C2C;
static constexpr cufftType FFTBackward = CUFFT_C2R;
struct FFTExecuteForward{
void operator()(cufftHandle plan, RealType* in, ComplexType* out){
CHECK_CUDA(cufftExecR2C(plan, in, out));
}
void operator()(cufftHandle plan, ComplexType* in, ComplexType* out){
CHECK_CUDA(cufftExecC2C(plan, in, out, CUFFT_FORWARD));
}
};
struct FFTExecuteBackward{
void operator()(cufftHandle plan, ComplexType* in, RealType* out){
CHECK_CUDA(cufftExecC2R(plan, in, out));
}
void operator()(cufftHandle plan, ComplexType* in, ComplexType* out){
CHECK_CUDA(cufftExecC2C(plan, in, out, CUFFT_INVERSE));
}
};
};
template<>
struct Types<double>
{
using ComplexType = cufftDoubleComplex;
using RealType = cufftDoubleReal;
static constexpr cufftType FFTForward = CUFFT_D2Z;
static constexpr cufftType FFTComplex = CUFFT_Z2Z;
static constexpr cufftType FFTBackward = CUFFT_Z2D;
struct FFTExecuteForward{
void operator()(cufftHandle plan, RealType* in, ComplexType* out){
CHECK_CUDA(cufftExecD2Z(plan, in, out));
}
void operator()(cufftHandle plan, ComplexType* in, ComplexType* out){
CHECK_CUDA(cufftExecZ2Z(plan, in, out, CUFFT_FORWARD));
}
};
struct FFTExecuteBackward{
void operator()(cufftHandle plan, ComplexType* in, RealType* out){
CHECK_CUDA(cufftExecZ2D(plan, in, out));
}
void operator()(cufftHandle plan, ComplexType* in, ComplexType* out){
CHECK_CUDA(cufftExecZ2Z(plan, in, out, CUFFT_INVERSE));
}
};
};
} // namespace traits
/**
* CUDA implicit context init and reset wrapper. Time is benchmarked.
*/
struct Context {
static const std::string title() {
return "CuFFT";
}
std::string getDeviceInfos() {
auto ss = getCUDADeviceInformations(0);
return ss.str();
}
void create() {
CHECK_CUDA(cudaSetDevice(0));
}
void destroy() {
CHECK_CUDA(cudaDeviceReset());
}
};
/**
* Estimates memory reserved by cufft plan depending on FFT transform type
* (CUFFT_R2C, ...) and depending on number of dimensions {1,2,3}.
*/
template<cufftType FFTType, size_t NDim>
size_t estimateAllocSize(cufftHandle& plan, const std::array<size_t,NDim>& e)
{
size_t s=0;
CHECK_CUDA( cufftCreate(&plan) );
if(NDim==1){
CHECK_CUDA( cufftGetSize1d(plan, e[0], FFTType, 1, &s) );
}
if(NDim==2){
CHECK_CUDA( cufftGetSize2d(plan, e[0], e[1], FFTType, &s) );
}
if(NDim==3){
CHECK_CUDA( cufftGetSize3d(plan, e[0], e[1], e[2], FFTType, &s) );
}
return s;
}
template<cufftType FFTType, size_t NDim>
size_t estimateAllocSize64(cufftHandle& plan, const std::array<size_t,NDim>& e) {
size_t worksize=0;
std::array<long long int, 3> lengths = {{0}};
std::copy(e.begin(), e.end(), lengths.begin());
CHECK_CUDA( cufftCreate(&plan) );
CHECK_CUDA( cufftGetSizeMany64(plan, NDim, lengths.data(), NULL, 0, 0, NULL, 0, 0,
FFTType,
1, //batches
&worksize));
return worksize;
}
/**
* Plan Creator depending on FFT transform type (CUFFT_R2C, ...).
*/
template<cufftType FFTType>
void makePlan(cufftHandle& plan, const std::array<size_t,3>& e){
CHECK_CUDA(cufftPlan3d(&plan, e[0], e[1], e[2], FFTType));
}
template<cufftType FFTType>
void makePlan(cufftHandle& plan, const std::array<size_t,1>& e){
CHECK_CUDA(cufftPlan1d(&plan, e[0], FFTType, 1));
}
template<cufftType FFTType>
void makePlan(cufftHandle& plan, const std::array<size_t,2>& e){
CHECK_CUDA(cufftPlan2d(&plan, e[0], e[1], FFTType));
}
template<cufftType FFTType, size_t NDim>
void makePlan64(cufftHandle& plan, const std::array<size_t,NDim>& e) {
size_t worksize=0;
std::array<long long int, 3> lengths = {{0}};
std::copy(e.begin(), e.end(), lengths.begin());
CHECK_CUDA( cufftCreate(&plan) );
CHECK_CUDA( cufftMakePlanMany64(plan,
NDim,
lengths.data(),
NULL, 0, 0, NULL, 0, 0, //ignored
FFTType,
1, //batches
&worksize));
}
/**
* CuFFT plan and execution class.
*
* This class handles:
* - {1D, 2D, 3D} x {R2C, C2R, C2C} x {inplace, outplace} x {float, double}.
*/
template<typename TFFT, // see fft_abstract.hpp (FFT_Inplace_Real, ...)
typename TPrecision, // double, float
size_t NDim // 1..3
>
struct CuFFTImpl {
using Extent = std::array<size_t,NDim>;
using Types = typename traits::Types<TPrecision>;
using ComplexType = typename Types::ComplexType;
using RealType = typename Types::RealType;
using FFTExecuteForward = typename Types::FFTExecuteForward;
using FFTExecuteBackward = typename Types::FFTExecuteBackward;
static constexpr
bool IsInplace = TFFT::IsInplace;
static constexpr
bool IsComplex = TFFT::IsComplex;
static constexpr
bool Padding = IsInplace && IsComplex==false && NDim>1;
static constexpr
cufftType FFTForward = IsComplex ? Types::FFTComplex : Types::FFTForward;
static constexpr
cufftType FFTBackward = IsComplex ? Types::FFTComplex : Types::FFTBackward;
using RealOrComplexType = typename std::conditional<IsComplex,ComplexType,RealType>::type;
size_t n_; // =[1]*..*[dim]
size_t n_padded_; // =[1]*..*[dim-1]*([dim]/2+1)
Extent extents_;
cufftHandle plan_ = 0;
RealOrComplexType* data_ = nullptr;
ComplexType* data_transform_ = nullptr; // intermediate buffer
size_t data_size_;
size_t data_transform_size_;
bool use64bit_ = false;
CuFFTImpl(const Extent& cextents) {
extents_ = interpret_as::column_major(cextents);
n_ = std::accumulate(extents_.begin(),
extents_.end(),
static_cast<size_t>(1),
std::multiplies<size_t>());
if(Padding)
n_padded_ = n_ / extents_[NDim-1] * (extents_[NDim-1]/2 + 1);
data_size_ = ( Padding ? 2*n_padded_ : n_ ) * sizeof(RealOrComplexType);
data_transform_size_ = IsInplace ? 0 : n_ * sizeof(ComplexType);
// There are some additional restrictions when using 64-bit API of cufft
// see http://docs.nvidia.com/cuda/cufft/#unique_1972991535
if(data_size_ >= (1ull<<32) || data_transform_size_ >= (1ull<<32))
use64bit_ = true;
}
~CuFFTImpl() {
destroy();
}
/**
* Returns allocated memory on device for FFT
*/
size_t getAllocSize() {
return data_size_ + data_transform_size_;
}
/**
* Returns estimated allocated memory on device for FFT plan
*/
size_t getPlanSize() {
size_t size1 = 0;
size_t size2 = 0;
if(use64bit_)
size1 = estimateAllocSize64<FFTForward>(plan_,extents_);
else{
size1 = estimateAllocSize<FFTForward>(plan_,extents_);
}
CHECK_CUDA(cufftDestroy(plan_));
plan_=0;
if(use64bit_)
size2 = estimateAllocSize64<FFTBackward>(plan_,extents_);
else{
size2 = estimateAllocSize<FFTBackward>(plan_,extents_);
}
CHECK_CUDA(cufftDestroy(plan_));
plan_=0;
// check available GPU memory
size_t mem_free=0, mem_tot=0;
CHECK_CUDA( cudaMemGetInfo(&mem_free, &mem_tot) );
size_t wanted = std::max(size1,size2) + data_size_ + data_transform_size_;
if(mem_free<wanted) {
std::stringstream ss;
ss << mem_free << "<" << wanted << " (bytes)";
throw std::runtime_error("Not enough GPU memory available. "+ss.str());
}
return std::max(size1,size2);
}
// --- next methods are benchmarked ---
void malloc() {
CHECK_CUDA(cudaMalloc(&data_, data_size_));
if(!data_) throw std::runtime_error("Could not allocate GPU input buffer.");
if(IsInplace) {
data_transform_ = reinterpret_cast<ComplexType*>(data_);
}else{
CHECK_CUDA(cudaMalloc(&data_transform_, data_transform_size_));
if(!data_transform_) throw std::runtime_error("Could not allocate GPU buffer for outplace transform.");
}
}
// create FFT plan handle
void init_forward() {
if(use64bit_)
makePlan64<FFTForward>(plan_, extents_);
else
makePlan<FFTForward>(plan_, extents_);
}
// recreates plan if needed
void init_backward() {
if(IsComplex==false){
CHECK_CUDA(cufftDestroy(plan_));
plan_=0;
if(use64bit_)
makePlan64<FFTBackward>(plan_, extents_);
else
makePlan<FFTBackward>(plan_, extents_);
}
}
void execute_forward() {
FFTExecuteForward()(plan_, data_, data_transform_);
}
void execute_backward() {
FFTExecuteBackward()(plan_, data_transform_, data_);
}
template<typename THostData>
void upload(THostData* input) {
if(Padding) { // real + inplace + ndim>1
size_t w = extents_[NDim-1] * sizeof(THostData);
size_t h = n_ * sizeof(THostData) / w;
size_t pitch = (extents_[NDim-1]/2+1) * sizeof(ComplexType);
CHECK_CUDA(cudaMemcpy2D(data_, pitch, input, w, w, h, cudaMemcpyHostToDevice));
}else{
CHECK_CUDA(cudaMemcpy(data_, input, data_size_, cudaMemcpyHostToDevice));
}
}
template<typename THostData>
void download(THostData* output) {
if(Padding) { // real + inplace + ndim>1
size_t w = extents_[NDim-1] * sizeof(THostData);
size_t h = n_ * sizeof(THostData) / w;
size_t pitch = (extents_[NDim-1]/2+1) * sizeof(ComplexType);
CHECK_CUDA(cudaMemcpy2D(output, w, data_, pitch, w, h, cudaMemcpyDeviceToHost));
}else{
CHECK_CUDA(cudaMemcpy(output, data_, data_size_, cudaMemcpyDeviceToHost));
}
}
void destroy() {
CHECK_CUDA( cudaFree(data_) );
data_=nullptr;
if(IsInplace==false && data_transform_) {
CHECK_CUDA( cudaFree(data_transform_) );
data_transform_ = nullptr;
}
if(plan_) {
CHECK_CUDA( cufftDestroy(plan_) );
plan_=0;
}
}
};
typedef gearshifft::FFT<gearshifft::FFT_Inplace_Real, CuFFTImpl, TimerGPU> Inplace_Real;
typedef gearshifft::FFT<gearshifft::FFT_Outplace_Real, CuFFTImpl, TimerGPU> Outplace_Real;
typedef gearshifft::FFT<gearshifft::FFT_Inplace_Complex, CuFFTImpl, TimerGPU> Inplace_Complex;
typedef gearshifft::FFT<gearshifft::FFT_Outplace_Complex, CuFFTImpl, TimerGPU> Outplace_Complex;
} // namespace CuFFT
} // namespace gearshifft
#endif /* CUFFT_HPP_ */
<commit_msg>removed unneeded check for cudaMalloc failure.<commit_after>#ifndef CUFFT_HPP_
#define CUFFT_HPP_
#include "application.hpp"
#include "timer.hpp"
#include "fft.hpp"
#include "benchmark_suite.hpp"
#include "cufft_helper.hpp"
#include "traits.hpp"
#include <array>
#include <cufft.h>
#include <vector_types.h>
namespace gearshifft {
namespace CuFFT {
namespace traits{
template<typename T_Precision=float>
struct Types
{
using ComplexType = cufftComplex;
using RealType = cufftReal;
static constexpr cufftType FFTForward = CUFFT_R2C;
static constexpr cufftType FFTComplex = CUFFT_C2C;
static constexpr cufftType FFTBackward = CUFFT_C2R;
struct FFTExecuteForward{
void operator()(cufftHandle plan, RealType* in, ComplexType* out){
CHECK_CUDA(cufftExecR2C(plan, in, out));
}
void operator()(cufftHandle plan, ComplexType* in, ComplexType* out){
CHECK_CUDA(cufftExecC2C(plan, in, out, CUFFT_FORWARD));
}
};
struct FFTExecuteBackward{
void operator()(cufftHandle plan, ComplexType* in, RealType* out){
CHECK_CUDA(cufftExecC2R(plan, in, out));
}
void operator()(cufftHandle plan, ComplexType* in, ComplexType* out){
CHECK_CUDA(cufftExecC2C(plan, in, out, CUFFT_INVERSE));
}
};
};
template<>
struct Types<double>
{
using ComplexType = cufftDoubleComplex;
using RealType = cufftDoubleReal;
static constexpr cufftType FFTForward = CUFFT_D2Z;
static constexpr cufftType FFTComplex = CUFFT_Z2Z;
static constexpr cufftType FFTBackward = CUFFT_Z2D;
struct FFTExecuteForward{
void operator()(cufftHandle plan, RealType* in, ComplexType* out){
CHECK_CUDA(cufftExecD2Z(plan, in, out));
}
void operator()(cufftHandle plan, ComplexType* in, ComplexType* out){
CHECK_CUDA(cufftExecZ2Z(plan, in, out, CUFFT_FORWARD));
}
};
struct FFTExecuteBackward{
void operator()(cufftHandle plan, ComplexType* in, RealType* out){
CHECK_CUDA(cufftExecZ2D(plan, in, out));
}
void operator()(cufftHandle plan, ComplexType* in, ComplexType* out){
CHECK_CUDA(cufftExecZ2Z(plan, in, out, CUFFT_INVERSE));
}
};
};
} // namespace traits
/**
* CUDA implicit context init and reset wrapper. Time is benchmarked.
*/
struct Context {
static const std::string title() {
return "CuFFT";
}
std::string getDeviceInfos() {
auto ss = getCUDADeviceInformations(0);
return ss.str();
}
void create() {
CHECK_CUDA(cudaSetDevice(0));
}
void destroy() {
CHECK_CUDA(cudaDeviceReset());
}
};
/**
* Estimates memory reserved by cufft plan depending on FFT transform type
* (CUFFT_R2C, ...) and depending on number of dimensions {1,2,3}.
*/
template<cufftType FFTType, size_t NDim>
size_t estimateAllocSize(cufftHandle& plan, const std::array<size_t,NDim>& e)
{
size_t s=0;
CHECK_CUDA( cufftCreate(&plan) );
if(NDim==1){
CHECK_CUDA( cufftGetSize1d(plan, e[0], FFTType, 1, &s) );
}
if(NDim==2){
CHECK_CUDA( cufftGetSize2d(plan, e[0], e[1], FFTType, &s) );
}
if(NDim==3){
CHECK_CUDA( cufftGetSize3d(plan, e[0], e[1], e[2], FFTType, &s) );
}
return s;
}
template<cufftType FFTType, size_t NDim>
size_t estimateAllocSize64(cufftHandle& plan, const std::array<size_t,NDim>& e) {
size_t worksize=0;
std::array<long long int, 3> lengths = {{0}};
std::copy(e.begin(), e.end(), lengths.begin());
CHECK_CUDA( cufftCreate(&plan) );
CHECK_CUDA( cufftGetSizeMany64(plan, NDim, lengths.data(), NULL, 0, 0, NULL, 0, 0,
FFTType,
1, //batches
&worksize));
return worksize;
}
/**
* Plan Creator depending on FFT transform type (CUFFT_R2C, ...).
*/
template<cufftType FFTType>
void makePlan(cufftHandle& plan, const std::array<size_t,3>& e){
CHECK_CUDA(cufftPlan3d(&plan, e[0], e[1], e[2], FFTType));
}
template<cufftType FFTType>
void makePlan(cufftHandle& plan, const std::array<size_t,1>& e){
CHECK_CUDA(cufftPlan1d(&plan, e[0], FFTType, 1));
}
template<cufftType FFTType>
void makePlan(cufftHandle& plan, const std::array<size_t,2>& e){
CHECK_CUDA(cufftPlan2d(&plan, e[0], e[1], FFTType));
}
template<cufftType FFTType, size_t NDim>
void makePlan64(cufftHandle& plan, const std::array<size_t,NDim>& e) {
size_t worksize=0;
std::array<long long int, 3> lengths = {{0}};
std::copy(e.begin(), e.end(), lengths.begin());
CHECK_CUDA( cufftCreate(&plan) );
CHECK_CUDA( cufftMakePlanMany64(plan,
NDim,
lengths.data(),
NULL, 0, 0, NULL, 0, 0, //ignored
FFTType,
1, //batches
&worksize));
}
/**
* CuFFT plan and execution class.
*
* This class handles:
* - {1D, 2D, 3D} x {R2C, C2R, C2C} x {inplace, outplace} x {float, double}.
*/
template<typename TFFT, // see fft_abstract.hpp (FFT_Inplace_Real, ...)
typename TPrecision, // double, float
size_t NDim // 1..3
>
struct CuFFTImpl {
using Extent = std::array<size_t,NDim>;
using Types = typename traits::Types<TPrecision>;
using ComplexType = typename Types::ComplexType;
using RealType = typename Types::RealType;
using FFTExecuteForward = typename Types::FFTExecuteForward;
using FFTExecuteBackward = typename Types::FFTExecuteBackward;
static constexpr
bool IsInplace = TFFT::IsInplace;
static constexpr
bool IsComplex = TFFT::IsComplex;
static constexpr
bool Padding = IsInplace && IsComplex==false && NDim>1;
static constexpr
cufftType FFTForward = IsComplex ? Types::FFTComplex : Types::FFTForward;
static constexpr
cufftType FFTBackward = IsComplex ? Types::FFTComplex : Types::FFTBackward;
using RealOrComplexType = typename std::conditional<IsComplex,ComplexType,RealType>::type;
size_t n_; // =[1]*..*[dim]
size_t n_padded_; // =[1]*..*[dim-1]*([dim]/2+1)
Extent extents_;
cufftHandle plan_ = 0;
RealOrComplexType* data_ = nullptr;
ComplexType* data_transform_ = nullptr; // intermediate buffer
size_t data_size_;
size_t data_transform_size_;
bool use64bit_ = false;
CuFFTImpl(const Extent& cextents) {
extents_ = interpret_as::column_major(cextents);
n_ = std::accumulate(extents_.begin(),
extents_.end(),
static_cast<size_t>(1),
std::multiplies<size_t>());
if(Padding)
n_padded_ = n_ / extents_[NDim-1] * (extents_[NDim-1]/2 + 1);
data_size_ = ( Padding ? 2*n_padded_ : n_ ) * sizeof(RealOrComplexType);
data_transform_size_ = IsInplace ? 0 : n_ * sizeof(ComplexType);
// There are some additional restrictions when using 64-bit API of cufft
// see http://docs.nvidia.com/cuda/cufft/#unique_1972991535
if(data_size_ >= (1ull<<32) || data_transform_size_ >= (1ull<<32))
use64bit_ = true;
}
~CuFFTImpl() {
destroy();
}
/**
* Returns allocated memory on device for FFT
*/
size_t getAllocSize() {
return data_size_ + data_transform_size_;
}
/**
* Returns estimated allocated memory on device for FFT plan
*/
size_t getPlanSize() {
size_t size1 = 0;
size_t size2 = 0;
if(use64bit_)
size1 = estimateAllocSize64<FFTForward>(plan_,extents_);
else{
size1 = estimateAllocSize<FFTForward>(plan_,extents_);
}
CHECK_CUDA(cufftDestroy(plan_));
plan_=0;
if(use64bit_)
size2 = estimateAllocSize64<FFTBackward>(plan_,extents_);
else{
size2 = estimateAllocSize<FFTBackward>(plan_,extents_);
}
CHECK_CUDA(cufftDestroy(plan_));
plan_=0;
// check available GPU memory
size_t mem_free=0, mem_tot=0;
CHECK_CUDA( cudaMemGetInfo(&mem_free, &mem_tot) );
size_t wanted = std::max(size1,size2) + data_size_ + data_transform_size_;
if(mem_free<wanted) {
std::stringstream ss;
ss << mem_free << "<" << wanted << " (bytes)";
throw std::runtime_error("Not enough GPU memory available. "+ss.str());
}
return std::max(size1,size2);
}
// --- next methods are benchmarked ---
void malloc() {
CHECK_CUDA(cudaMalloc(&data_, data_size_));
if(IsInplace) {
data_transform_ = reinterpret_cast<ComplexType*>(data_);
}else{
CHECK_CUDA(cudaMalloc(&data_transform_, data_transform_size_));
}
}
// create FFT plan handle
void init_forward() {
if(use64bit_)
makePlan64<FFTForward>(plan_, extents_);
else
makePlan<FFTForward>(plan_, extents_);
}
// recreates plan if needed
void init_backward() {
if(IsComplex==false){
CHECK_CUDA(cufftDestroy(plan_));
plan_=0;
if(use64bit_)
makePlan64<FFTBackward>(plan_, extents_);
else
makePlan<FFTBackward>(plan_, extents_);
}
}
void execute_forward() {
FFTExecuteForward()(plan_, data_, data_transform_);
}
void execute_backward() {
FFTExecuteBackward()(plan_, data_transform_, data_);
}
template<typename THostData>
void upload(THostData* input) {
if(Padding) { // real + inplace + ndim>1
size_t w = extents_[NDim-1] * sizeof(THostData);
size_t h = n_ * sizeof(THostData) / w;
size_t pitch = (extents_[NDim-1]/2+1) * sizeof(ComplexType);
CHECK_CUDA(cudaMemcpy2D(data_, pitch, input, w, w, h, cudaMemcpyHostToDevice));
}else{
CHECK_CUDA(cudaMemcpy(data_, input, data_size_, cudaMemcpyHostToDevice));
}
}
template<typename THostData>
void download(THostData* output) {
if(Padding) { // real + inplace + ndim>1
size_t w = extents_[NDim-1] * sizeof(THostData);
size_t h = n_ * sizeof(THostData) / w;
size_t pitch = (extents_[NDim-1]/2+1) * sizeof(ComplexType);
CHECK_CUDA(cudaMemcpy2D(output, w, data_, pitch, w, h, cudaMemcpyDeviceToHost));
}else{
CHECK_CUDA(cudaMemcpy(output, data_, data_size_, cudaMemcpyDeviceToHost));
}
}
void destroy() {
CHECK_CUDA( cudaFree(data_) );
data_=nullptr;
if(IsInplace==false && data_transform_) {
CHECK_CUDA( cudaFree(data_transform_) );
data_transform_ = nullptr;
}
if(plan_) {
CHECK_CUDA( cufftDestroy(plan_) );
plan_=0;
}
}
};
typedef gearshifft::FFT<gearshifft::FFT_Inplace_Real, CuFFTImpl, TimerGPU> Inplace_Real;
typedef gearshifft::FFT<gearshifft::FFT_Outplace_Real, CuFFTImpl, TimerGPU> Outplace_Real;
typedef gearshifft::FFT<gearshifft::FFT_Inplace_Complex, CuFFTImpl, TimerGPU> Inplace_Complex;
typedef gearshifft::FFT<gearshifft::FFT_Outplace_Complex, CuFFTImpl, TimerGPU> Outplace_Complex;
} // namespace CuFFT
} // namespace gearshifft
#endif /* CUFFT_HPP_ */
<|endoftext|> |
<commit_before>#if defined(LINUX)
#include <sys/syscall.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <unistd.h>
#include <stdio.h>
#include <string.h>
#include <stdint.h>
#include <stddef.h>
#include <errno.h>
typedef uint64_t u64;
#include "include/wq.hh"
#include "user/dirit.hh"
#define ST_SIZE(st) (st).st_size
#define ST_ISDIR(st) S_ISDIR((st).st_mode)
#define BSIZ 256
#else // assume xv6
#include "types.h"
#include "stat.h"
#include "user.h"
#include "lib.h"
#include "fs.h"
#include "uspinlock.h"
#include "wq.hh"
#include "dirit.hh"
#define ST_SIZE(st) (st).size
#define ST_ISDIR(st) ((st).type == T_DIR)
#define stderr 2
#define BSIZ (DIRSIZ+1)
#endif
static size_t
du(int fd)
{
struct stat st;
if (fstat(fd, &st) < 0) {
fprintf(stderr, "du: cannot stat\n");
close(fd);
return 0;
}
// XXX(sbw) size should use an add reducer
size_t size = ST_SIZE(st);
if (ST_ISDIR(st)) {
dirit di(fd);
wq_for<dirit>(di,
[](dirit &i)->bool { return !i.end(); },
[&](const char *name)->void
{
if (!strcmp(name, ".") || !strcmp(name, "..")) {
free((void*)name);
return;
}
int nfd = openat(fd, name, 0);
if (nfd >= 0)
size += du(nfd); // should go into work queue
free((void*)name);
});
} else {
close(fd);
}
return size;
}
int
main(int ac, char **av)
{
initwq();
printf("%ld\n", du(open(".", 0)));
return 0;
}
<commit_msg>A hacked up add reducer<commit_after>#if defined(LINUX)
#include <sys/syscall.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <unistd.h>
#include <stdio.h>
#include <string.h>
#include <stdint.h>
#include <stddef.h>
#include <errno.h>
typedef uint64_t u64;
#include "include/wq.hh"
#include "user/dirit.hh"
#include "include/percpu.hh"
#define ST_SIZE(st) (st).st_size
#define ST_ISDIR(st) S_ISDIR((st).st_mode)
#define BSIZ 256
#else // assume xv6
#include "types.h"
#include "stat.h"
#include "user.h"
#include "lib.h"
#include "fs.h"
#include "uspinlock.h"
#include "wq.hh"
#include "dirit.hh"
#include "percpu.hh"
#define ST_SIZE(st) (st).size
#define ST_ISDIR(st) ((st).type == T_DIR)
#define stderr 2
#define BSIZ (DIRSIZ+1)
#endif
template <typename T>
struct reducer_opadd
{
reducer_opadd(T v) {
for (int i = 0; i < NCPU; i++)
v_[i] = 0;
*v_ = v;
}
T operator+=(T i) {
(*v_) += i;
return *v_;
}
T get_value() {
T t = 0;
for (int i = 0; i < NCPU; i++)
t += v_[i];
return t;
}
percpu<T> v_;
};
static size_t
du(int fd)
{
struct stat st;
if (fstat(fd, &st) < 0) {
fprintf(stderr, "du: cannot stat\n");
close(fd);
return 0;
}
// XXX(sbw) size should use an add reducer
reducer_opadd<size_t> size(ST_SIZE(st));
if (ST_ISDIR(st)) {
dirit di(fd);
wq_for<dirit>(di,
[](dirit &i)->bool { return !i.end(); },
[&](const char *name)->void
{
if (!strcmp(name, ".") || !strcmp(name, "..")) {
free((void*)name);
return;
}
int nfd = openat(fd, name, 0);
if (nfd >= 0)
size += du(nfd); // should go into work queue
free((void*)name);
});
} else {
close(fd);
}
return size.get_value();
}
int
main(int ac, char **av)
{
initwq();
printf("%ld\n", du(open(".", 0)));
return 0;
}
<|endoftext|> |
<commit_before>/*
* Label.cpp
* iPhoneEmptyExample
*
* Created by hansi on 29.01.11.
* Copyright 2011 __MyCompanyName__. All rights reserved.
*
* ------------------------------
* PLEASE READ BEFORE YOU CODE:
*
* This is a simple container thingie.
* You can use it exactly like an OF main app, there are only small differences in how touch events work.
* 1. If you don't want an event to propagate to other containers just do a "return true;" at then end.
* 2. A container will only be notified of events that happen within it's bounds
* 3. If you do a "return true" at the end of touchDown() your container will be remembered and will then
* receive all moved(), doubleTap() and touchUp() events, even if they happen outside the container.
* 4. The coordinates touch.x and touch.y are modified to match the drawing coordinate system, so 0/0 is at the
* left top corner of your container, not top left corner of your application.
*/
#include "MUI.h"
//--------------------------------------------------------------
void mui::Label::update(){
}
//--------------------------------------------------------------
void mui::Label::draw(){
// // magic trick #1:
// int w, h;
// if( Helpers::retinaMode ) w = 2*width, h = 2*height;
// else w = width, h=height;
//
// ofRectangle size = Helpers::alignBox( this, fbo.getWidth(), fbo.getHeight(), horizontalAlign, verticalAlign );
ofRectangle size = Helpers::alignBox( this, boundingBox.width, boundingBox.height, horizontalAlign, verticalAlign );
ofSetColor( 255, 255, 255 );
glBlendFunc( GL_ONE, GL_ONE_MINUS_SRC_ALPHA );
// fbo.draw( (int)size.x, (int)size.y, size.width, size.height );
ofSetColor( fg.r, fg.g, fg.b );
if( Helpers::retinaMode ){
MUI_FONT_TYPE * font = Helpers::getFont( 2*fontSize );
ofPushMatrix();
ofTranslate( (int)(size.x-boundingBox.x), (int)(size.y-(int)boundingBox.y) );
ofScale( 0.5, 0.5 );
font->drawString( displayText, 0, 0 );
ofPopMatrix();
}
else{
MUI_FONT_TYPE * font = Helpers::getFont( Helpers::retinaMode?(fontSize*2):fontSize );
font->drawString( displayText, (int)(size.x-boundingBox.x), (int)(size.y-(int)boundingBox.y) );
}
ofEnableAlphaBlending();
}
//--------------------------------------------------------------
void mui::Label::render(){
// old, maybe new again one day.
//Helpers::drawStringWithShadow( text, renderX, renderY, fontSize, fg.r, fg.g, fg.b );
if( horizontalAlign == Left ) renderX = -boundingBox.x;
if( verticalAlign == Top ) renderY = - boundingBox.y;
}
//--------------------------------------------------------------
void mui::Label::drawBackground(){
Container::drawBackground();
}
ofRectangle mui::Label::box( float t, float r, float b, float l ){
ofRectangle size = Helpers::alignBox( this, boundingBox.width, boundingBox.height, horizontalAlign, verticalAlign );
return ofRectangle( size.x - boundingBox.x - l, size.y - boundingBox.y - t, boundingBox.width + l + r, boundingBox.height + t + b );
}
//--------------------------------------------------------------
void mui::Label::commit(){
// magic trick #2
// MUI_FONT_TYPE * font = Helpers::getFont( Helpers::retinaMode?(fontSize*2):fontSize );
// magic trick #2.2: fuck retina, we compute the bounding box at normal size!
MUI_FONT_TYPE * font = Helpers::getFont( fontSize );
boundingBox = font->getStringBoundingBox( text, 0, 0 );
// NASTY HACK#158
boundingBox.x = 0;
if( ellipsisMode ){
if( boundingBox.width > width && text.length() > 3 ){
int len = text.length() - 3;
while( boundingBox.width > width && len >= 0 ){
displayText = text.substr(0, len ) + "...";
boundingBox = font->getStringBoundingBox( displayText, 0, 0 );
len --;
}
}
else{
displayText = text;
}
}
else{
displayText = text;
}
int w = floorf(boundingBox.width) + 1;
int h = floorf(boundingBox.height);
/*
// magic trick #1:
if( Helpers::retinaMode ) w *= 2, h *= 2;
ofPushMatrix();
if( fbo.getWidth() != w || fbo.getHeight() != h ) fbo.allocate( w, h, GL_RGBA );
fbo.clear( 0, 0, 0, 0 );
//////////////////////
// RENDER!
//////////////////////
fbo.begin();
#ifdef TARGET_OPENGLES
glBlendFuncSeparateOES(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA,GL_ONE,GL_ONE_MINUS_SRC_ALPHA); //oriol added to get rid of halos
#else
glBlendFuncSeparate(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA,GL_ONE,GL_ONE_MINUS_SRC_ALPHA); //oriol added to get rid of halos
#endif
if( Helpers::retinaMode ){
ofPushMatrix();
ofScale( 0.5, 0.5, 1 );
}
ofSetColor( fg.r, fg.g, fg.b );
font->drawString( text, -(int)boundingBox.x, -(int)boundingBox.y );
if( Helpers::retinaMode ){
ofPopMatrix();
}
fbo.end();
ofPopMatrix(); */
}<commit_msg>don't auto set width/height on labels<commit_after>/*
* Label.cpp
* iPhoneEmptyExample
*
* Created by hansi on 29.01.11.
* Copyright 2011 __MyCompanyName__. All rights reserved.
*
* ------------------------------
* PLEASE READ BEFORE YOU CODE:
*
* This is a simple container thingie.
* You can use it exactly like an OF main app, there are only small differences in how touch events work.
* 1. If you don't want an event to propagate to other containers just do a "return true;" at then end.
* 2. A container will only be notified of events that happen within it's bounds
* 3. If you do a "return true" at the end of touchDown() your container will be remembered and will then
* receive all moved(), doubleTap() and touchUp() events, even if they happen outside the container.
* 4. The coordinates touch.x and touch.y are modified to match the drawing coordinate system, so 0/0 is at the
* left top corner of your container, not top left corner of your application.
*/
#include "MUI.h"
//--------------------------------------------------------------
void mui::Label::update(){
}
//--------------------------------------------------------------
void mui::Label::draw(){
// // magic trick #1:
// int w, h;
// if( Helpers::retinaMode ) w = 2*width, h = 2*height;
// else w = width, h=height;
//
// ofRectangle size = Helpers::alignBox( this, fbo.getWidth(), fbo.getHeight(), horizontalAlign, verticalAlign );
ofRectangle size = Helpers::alignBox( this, boundingBox.width, boundingBox.height, horizontalAlign, verticalAlign );
ofSetColor( 255, 255, 255 );
glBlendFunc( GL_ONE, GL_ONE_MINUS_SRC_ALPHA );
// fbo.draw( (int)size.x, (int)size.y, size.width, size.height );
ofSetColor( fg.r, fg.g, fg.b );
if( Helpers::retinaMode ){
MUI_FONT_TYPE * font = Helpers::getFont( 2*fontSize );
ofPushMatrix();
ofTranslate( (int)(size.x-boundingBox.x), (int)(size.y-(int)boundingBox.y) );
ofScale( 0.5, 0.5 );
font->drawString( displayText, 0, 0 );
ofPopMatrix();
}
else{
MUI_FONT_TYPE * font = Helpers::getFont( Helpers::retinaMode?(fontSize*2):fontSize );
font->drawString( displayText, (int)(size.x-boundingBox.x), (int)(size.y-(int)boundingBox.y) );
}
ofEnableAlphaBlending();
}
//--------------------------------------------------------------
void mui::Label::render(){
// old, maybe new again one day.
//Helpers::drawStringWithShadow( text, renderX, renderY, fontSize, fg.r, fg.g, fg.b );
if( horizontalAlign == Left ) renderX = -boundingBox.x;
if( verticalAlign == Top ) renderY = - boundingBox.y;
}
//--------------------------------------------------------------
void mui::Label::drawBackground(){
Container::drawBackground();
}
ofRectangle mui::Label::box( float t, float r, float b, float l ){
ofRectangle size = Helpers::alignBox( this, boundingBox.width, boundingBox.height, horizontalAlign, verticalAlign );
return ofRectangle( size.x - boundingBox.x - l, size.y - boundingBox.y - t, boundingBox.width + l + r, boundingBox.height + t + b );
}
//--------------------------------------------------------------
void mui::Label::commit(){
// magic trick #2
// MUI_FONT_TYPE * font = Helpers::getFont( Helpers::retinaMode?(fontSize*2):fontSize );
// magic trick #2.2: fuck retina, we compute the bounding box at normal size!
MUI_FONT_TYPE * font = Helpers::getFont( fontSize );
boundingBox = font->getStringBoundingBox( text, 0, 0 );
// NASTY HACK#158
boundingBox.x = 0;
if( ellipsisMode ){
if( boundingBox.width > width && text.length() > 3 ){
int len = text.length() - 3;
while( boundingBox.width > width && len >= 0 ){
displayText = text.substr(0, len ) + "...";
boundingBox = font->getStringBoundingBox( displayText, 0, 0 );
len --;
}
}
else{
displayText = text;
}
}
else{
displayText = text;
}
/*
int w = floorf(boundingBox.width) + 1;
int h = floorf(boundingBox.height);
// magic trick #1:
if( Helpers::retinaMode ) w *= 2, h *= 2;
ofPushMatrix();
if( fbo.getWidth() != w || fbo.getHeight() != h ) fbo.allocate( w, h, GL_RGBA );
fbo.clear( 0, 0, 0, 0 );
//////////////////////
// RENDER!
//////////////////////
fbo.begin();
#ifdef TARGET_OPENGLES
glBlendFuncSeparateOES(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA,GL_ONE,GL_ONE_MINUS_SRC_ALPHA); //oriol added to get rid of halos
#else
glBlendFuncSeparate(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA,GL_ONE,GL_ONE_MINUS_SRC_ALPHA); //oriol added to get rid of halos
#endif
if( Helpers::retinaMode ){
ofPushMatrix();
ofScale( 0.5, 0.5, 1 );
}
ofSetColor( fg.r, fg.g, fg.b );
font->drawString( text, -(int)boundingBox.x, -(int)boundingBox.y );
if( Helpers::retinaMode ){
ofPopMatrix();
}
fbo.end();
ofPopMatrix(); */
}<|endoftext|> |
<commit_before>#include <stan/math/prim/core/init_threadpool_tbb.hpp>
#include <stan/math.hpp>
#include <gtest/gtest.h>
#include <algorithm>
#include <sstream>
#include <tuple>
#include <vector>
// reduce functor which is the BinaryFunction
// here we use iterators which represent integer indices
template <typename T>
struct count_lpdf {
count_lpdf() {}
// does the reduction in the sub-slice start to end
inline T operator()(std::size_t start, std::size_t end,
const std::vector<int>& sub_slice,
const std::vector<T>& lambda,
const std::vector<int>& idata) const {
return stan::math::poisson_lpmf(sub_slice, lambda[0]);
}
};
TEST(v3_reduce_sum, value) {
stan::math::init_threadpool_tbb();
double lambda_d = 10.0;
const std::size_t elems = 10000;
const std::size_t num_iter = 1000;
std::vector<int> data(elems);
for (std::size_t i = 0; i != elems; ++i)
data[i] = i;
std::vector<int> idata;
std::vector<double> vlambda_d(1, lambda_d);
typedef boost::counting_iterator<std::size_t> count_iter;
double poisson_lpdf = stan::math::reduce_sum<count_lpdf<double>>(data, 5, vlambda_d, idata);
double poisson_lpdf_ref = stan::math::poisson_lpmf(data, lambda_d);
EXPECT_FLOAT_EQ(poisson_lpdf, poisson_lpdf_ref);
std::cout << "ref value of poisson lpdf : " << poisson_lpdf_ref << std::endl;
std::cout << "value of poisson lpdf : " << poisson_lpdf << std::endl;
}
// ********************************
// test if nested parallelism works
// ********************************
template <typename T>
struct nesting_count_lpdf {
nesting_count_lpdf() {}
// does the reduction in the sub-slice start to end
inline T operator()(std::size_t start, std::size_t end,
const std::vector<int>& sub_slice,
const std::vector<T>& lambda,
const std::vector<int>& idata) const {
return stan::math::reduce_sum<count_lpdf<T>>(sub_slice, 5, lambda,
idata);
}
};
TEST(v3_reduce_sum, nesting_value) {
stan::math::init_threadpool_tbb();
double lambda_d = 10.0;
const std::size_t elems = 10000;
const std::size_t num_iter = 1000;
std::vector<int> data(elems);
for (std::size_t i = 0; i != elems; ++i)
data[i] = i;
std::vector<int> idata;
std::vector<double> vlambda_d(1, lambda_d);
typedef boost::counting_iterator<std::size_t> count_iter;
double poisson_lpdf = stan::math::reduce_sum<count_lpdf<double>>(
data, 5, vlambda_d, idata);
double poisson_lpdf_ref = stan::math::poisson_lpmf(data, lambda_d);
EXPECT_FLOAT_EQ(poisson_lpdf, poisson_lpdf_ref);
std::cout << "ref value of poisson lpdf : " << poisson_lpdf_ref << std::endl;
std::cout << "value of poisson lpdf : " << poisson_lpdf << std::endl;
}
<commit_msg>[Jenkins] auto-formatting by clang-format version 6.0.0 (tags/google/stable/2017-11-14)<commit_after>#include <stan/math/prim/core/init_threadpool_tbb.hpp>
#include <stan/math.hpp>
#include <gtest/gtest.h>
#include <algorithm>
#include <sstream>
#include <tuple>
#include <vector>
// reduce functor which is the BinaryFunction
// here we use iterators which represent integer indices
template <typename T>
struct count_lpdf {
count_lpdf() {}
// does the reduction in the sub-slice start to end
inline T operator()(std::size_t start, std::size_t end,
const std::vector<int>& sub_slice,
const std::vector<T>& lambda,
const std::vector<int>& idata) const {
return stan::math::poisson_lpmf(sub_slice, lambda[0]);
}
};
TEST(v3_reduce_sum, value) {
stan::math::init_threadpool_tbb();
double lambda_d = 10.0;
const std::size_t elems = 10000;
const std::size_t num_iter = 1000;
std::vector<int> data(elems);
for (std::size_t i = 0; i != elems; ++i)
data[i] = i;
std::vector<int> idata;
std::vector<double> vlambda_d(1, lambda_d);
typedef boost::counting_iterator<std::size_t> count_iter;
double poisson_lpdf
= stan::math::reduce_sum<count_lpdf<double>>(data, 5, vlambda_d, idata);
double poisson_lpdf_ref = stan::math::poisson_lpmf(data, lambda_d);
EXPECT_FLOAT_EQ(poisson_lpdf, poisson_lpdf_ref);
std::cout << "ref value of poisson lpdf : " << poisson_lpdf_ref << std::endl;
std::cout << "value of poisson lpdf : " << poisson_lpdf << std::endl;
}
// ********************************
// test if nested parallelism works
// ********************************
template <typename T>
struct nesting_count_lpdf {
nesting_count_lpdf() {}
// does the reduction in the sub-slice start to end
inline T operator()(std::size_t start, std::size_t end,
const std::vector<int>& sub_slice,
const std::vector<T>& lambda,
const std::vector<int>& idata) const {
return stan::math::reduce_sum<count_lpdf<T>>(sub_slice, 5, lambda, idata);
}
};
TEST(v3_reduce_sum, nesting_value) {
stan::math::init_threadpool_tbb();
double lambda_d = 10.0;
const std::size_t elems = 10000;
const std::size_t num_iter = 1000;
std::vector<int> data(elems);
for (std::size_t i = 0; i != elems; ++i)
data[i] = i;
std::vector<int> idata;
std::vector<double> vlambda_d(1, lambda_d);
typedef boost::counting_iterator<std::size_t> count_iter;
double poisson_lpdf
= stan::math::reduce_sum<count_lpdf<double>>(data, 5, vlambda_d, idata);
double poisson_lpdf_ref = stan::math::poisson_lpmf(data, lambda_d);
EXPECT_FLOAT_EQ(poisson_lpdf, poisson_lpdf_ref);
std::cout << "ref value of poisson lpdf : " << poisson_lpdf_ref << std::endl;
std::cout << "value of poisson lpdf : " << poisson_lpdf << std::endl;
}
<|endoftext|> |
<commit_before>
// =================================================================================================
// This file is part of the CLBlast project. The project is licensed under Apache Version 2.0. This
// project loosely follows the Google C++ styleguide and uses a tab-size of two spaces and a max-
// width of 100 characters per line.
//
// Author(s):
// Cedric Nugteren <www.cedricnugteren.nl>
//
// This file provides declarations for the common test utility functions (performance clients and
// correctness testers).
//
// =================================================================================================
#ifndef CLBLAST_TEST_UTILITIES_H_
#define CLBLAST_TEST_UTILITIES_H_
#include <cstdlib>
#include <string>
#include <fstream>
#include <sstream>
#include "utilities/utilities.hpp"
namespace clblast {
// =================================================================================================
// The client-specific arguments in string form
constexpr auto kArgCompareclblas = "clblas";
constexpr auto kArgComparecblas = "cblas";
constexpr auto kArgComparecublas = "cublas";
constexpr auto kArgStepSize = "step";
constexpr auto kArgNumSteps = "num_steps";
constexpr auto kArgWarmUp = "warm_up";
constexpr auto kArgTunerFiles = "tuner_files";
// The test-specific arguments in string form
constexpr auto kArgFullTest = "full_test";
constexpr auto kArgVerbose = "verbose";
// =================================================================================================
// Returns whether a scalar is close to zero
template <typename T> bool IsCloseToZero(const T value);
// =================================================================================================
// Structure containing all possible buffers for test clients
template <typename T>
struct Buffers {
Buffer<T> x_vec;
Buffer<T> y_vec;
Buffer<T> a_mat;
Buffer<T> b_mat;
Buffer<T> c_mat;
Buffer<T> ap_mat;
Buffer<T> scalar;
};
template <typename T>
struct BuffersHost {
std::vector<T> x_vec;
std::vector<T> y_vec;
std::vector<T> a_mat;
std::vector<T> b_mat;
std::vector<T> c_mat;
std::vector<T> ap_mat;
std::vector<T> scalar;
};
// =================================================================================================
// Converts a value (e.g. an integer) to a string. This also covers special cases for CLBlast
// data-types such as the Layout and Transpose data-types.
template <typename T>
std::string ToString(T value);
// =================================================================================================
// Copies buffers from the OpenCL device to the host
template <typename T, typename U>
void DeviceToHost(const Arguments<U> &args, Buffers<T> &buffers, BuffersHost<T> &buffers_host,
Queue &queue, const std::vector<std::string> &names);
// Copies buffers from the host to the OpenCL device
template <typename T, typename U>
void HostToDevice(const Arguments<U> &args, Buffers<T> &buffers, BuffersHost<T> &buffers_host,
Queue &queue, const std::vector<std::string> &names);
// =================================================================================================
// Conversion between half and single-precision
std::vector<float> HalfToFloatBuffer(const std::vector<half>& source);
void FloatToHalfBuffer(std::vector<half>& result, const std::vector<float>& source);
// As above, but now for OpenCL data-types instead of std::vectors
#ifdef OPENCL_API
Buffer<float> HalfToFloatBuffer(const Buffer<half>& source, RawCommandQueue queue_raw);
void FloatToHalfBuffer(Buffer<half>& result, const Buffer<float>& source, RawCommandQueue queue_raw);
#endif
// =================================================================================================
// Creates a buffer but don't test for validity. That's the reason this is not using the clpp11.h or
// cupp11.h interface.
template <typename T>
Buffer<T> CreateInvalidBuffer(const Context& context, const size_t size) {
#ifdef OPENCL_API
auto raw_buffer = clCreateBuffer(context(), CL_MEM_READ_WRITE, size * sizeof(T), nullptr, nullptr);
#elif CUDA_API
CUdeviceptr raw_buffer;
cuMemAlloc(&raw_buffer, size * sizeof(T));
#endif
return Buffer<T>(raw_buffer);
}
// =================================================================================================
template<typename Out>
void split(const std::string &s, char delimiter, Out result) {
std::stringstream ss(s);
std::string item;
while (std::getline(ss, item, delimiter)) {
*(result++) = item;
}
}
inline std::vector<std::string> split(const std::string &s, char delimiter) {
std::vector<std::string> elements;
split(s, delimiter, std::back_inserter(elements));
return elements;
}
// =================================================================================================
using BestParameters = std::unordered_map<std::string,size_t>;
using BestParametersCollection = std::unordered_map<std::string, BestParameters>;
void OverrideParametersFromJSONFiles(const std::vector<std::string>& file_names,
const cl_device_id device, const Precision precision);
void GetBestParametersFromJSONFile(const std::string& file_name,
BestParametersCollection& all_parameters,
const Precision precision);
// =================================================================================================
} // namespace clblast
// CLBLAST_TEST_UTILITIES_H_
#endif
<commit_msg>Added missing include file<commit_after>
// =================================================================================================
// This file is part of the CLBlast project. The project is licensed under Apache Version 2.0. This
// project loosely follows the Google C++ styleguide and uses a tab-size of two spaces and a max-
// width of 100 characters per line.
//
// Author(s):
// Cedric Nugteren <www.cedricnugteren.nl>
//
// This file provides declarations for the common test utility functions (performance clients and
// correctness testers).
//
// =================================================================================================
#ifndef CLBLAST_TEST_UTILITIES_H_
#define CLBLAST_TEST_UTILITIES_H_
#include <cstdlib>
#include <string>
#include <fstream>
#include <sstream>
#include <iterator>
#include "utilities/utilities.hpp"
namespace clblast {
// =================================================================================================
// The client-specific arguments in string form
constexpr auto kArgCompareclblas = "clblas";
constexpr auto kArgComparecblas = "cblas";
constexpr auto kArgComparecublas = "cublas";
constexpr auto kArgStepSize = "step";
constexpr auto kArgNumSteps = "num_steps";
constexpr auto kArgWarmUp = "warm_up";
constexpr auto kArgTunerFiles = "tuner_files";
// The test-specific arguments in string form
constexpr auto kArgFullTest = "full_test";
constexpr auto kArgVerbose = "verbose";
// =================================================================================================
// Returns whether a scalar is close to zero
template <typename T> bool IsCloseToZero(const T value);
// =================================================================================================
// Structure containing all possible buffers for test clients
template <typename T>
struct Buffers {
Buffer<T> x_vec;
Buffer<T> y_vec;
Buffer<T> a_mat;
Buffer<T> b_mat;
Buffer<T> c_mat;
Buffer<T> ap_mat;
Buffer<T> scalar;
};
template <typename T>
struct BuffersHost {
std::vector<T> x_vec;
std::vector<T> y_vec;
std::vector<T> a_mat;
std::vector<T> b_mat;
std::vector<T> c_mat;
std::vector<T> ap_mat;
std::vector<T> scalar;
};
// =================================================================================================
// Converts a value (e.g. an integer) to a string. This also covers special cases for CLBlast
// data-types such as the Layout and Transpose data-types.
template <typename T>
std::string ToString(T value);
// =================================================================================================
// Copies buffers from the OpenCL device to the host
template <typename T, typename U>
void DeviceToHost(const Arguments<U> &args, Buffers<T> &buffers, BuffersHost<T> &buffers_host,
Queue &queue, const std::vector<std::string> &names);
// Copies buffers from the host to the OpenCL device
template <typename T, typename U>
void HostToDevice(const Arguments<U> &args, Buffers<T> &buffers, BuffersHost<T> &buffers_host,
Queue &queue, const std::vector<std::string> &names);
// =================================================================================================
// Conversion between half and single-precision
std::vector<float> HalfToFloatBuffer(const std::vector<half>& source);
void FloatToHalfBuffer(std::vector<half>& result, const std::vector<float>& source);
// As above, but now for OpenCL data-types instead of std::vectors
#ifdef OPENCL_API
Buffer<float> HalfToFloatBuffer(const Buffer<half>& source, RawCommandQueue queue_raw);
void FloatToHalfBuffer(Buffer<half>& result, const Buffer<float>& source, RawCommandQueue queue_raw);
#endif
// =================================================================================================
// Creates a buffer but don't test for validity. That's the reason this is not using the clpp11.h or
// cupp11.h interface.
template <typename T>
Buffer<T> CreateInvalidBuffer(const Context& context, const size_t size) {
#ifdef OPENCL_API
auto raw_buffer = clCreateBuffer(context(), CL_MEM_READ_WRITE, size * sizeof(T), nullptr, nullptr);
#elif CUDA_API
CUdeviceptr raw_buffer;
cuMemAlloc(&raw_buffer, size * sizeof(T));
#endif
return Buffer<T>(raw_buffer);
}
// =================================================================================================
template<typename Out>
void split(const std::string &s, char delimiter, Out result) {
std::stringstream ss(s);
std::string item;
while (std::getline(ss, item, delimiter)) {
*(result++) = item;
}
}
inline std::vector<std::string> split(const std::string &s, char delimiter) {
std::vector<std::string> elements;
split(s, delimiter, std::back_inserter(elements));
return elements;
}
// =================================================================================================
using BestParameters = std::unordered_map<std::string,size_t>;
using BestParametersCollection = std::unordered_map<std::string, BestParameters>;
void OverrideParametersFromJSONFiles(const std::vector<std::string>& file_names,
const cl_device_id device, const Precision precision);
void GetBestParametersFromJSONFile(const std::string& file_name,
BestParametersCollection& all_parameters,
const Precision precision);
// =================================================================================================
} // namespace clblast
// CLBLAST_TEST_UTILITIES_H_
#endif
<|endoftext|> |
<commit_before>#ifndef TYPES_H
#define TYPES_H
#include<stack>
#include<set>
#include"heaps.hpp"
#include"hashes.hpp"
class Semispace;
void* operator new(size_t, Semispace&);
void operator delete(void*, Semispace&);
class ToPointerLock;
class Generic {
private:
Generic* to_pointer;
protected:
Generic(void) : to_pointer(NULL) {};
Generic(Generic const&) : to_pointer(NULL) {};
public:
friend class Semispace;
friend class ToPointerLock;
virtual size_t hash(void) const =0;
virtual Generic* clone(Semispace&) const =0;
/* clone should always have the following code:
virtual Type* clone(Semispace& sp) const{
return new(sp) Type(*this);
}
*/
/*gets addresses of references to other objects*/
virtual void get_refs(std::stack<Generic**>&){};
/*comparisons*/
virtual bool is(Generic const* gp) const{return gp == this;}
virtual bool iso(Generic const* gp) const{return is(gp);}
virtual size_t get_size(void) const =0;
/*get_size should always have the following code:
virtual size_t get_size(void) const {
return sizeof(Type);
}
*/
virtual ~Generic(){};
size_t total_size(void);
};
inline bool is(Generic const* a, Generic const* b){ return a->is(b);}
inline bool iso(Generic const* a, Generic const* b){ return a->iso(b);}
class ToPointerLock{
private:
std::set<Generic*> enset;
public:
void pointto(Generic* from, Generic* to){
enset.insert(from);
from->to_pointer = to;
}
Generic* to(Generic* from){
return from->to_pointer;
}
/*used to ignore the to-pointers in a successful
copy-and-sweep GC cycle
*/
void good(void){
enset.clear();
}
~ToPointerLock(){
std::set<Generic*>::iterator i;
for(i = enset.begin(); i != enset.end(); ++i){
(*i)->to_pointer = NULL;
}
}
};
class Cons : public Generic{
private:
Generic* a;
Generic* d;
protected:
Cons(Cons const&){};
public:
/*standard stuff*/
virtual size_t hash(void) const {
return a->hash() ^ d->hash();
}
virtual Cons* clone(Semispace& sp) const{
return new(sp) Cons(*this);
}
virtual size_t get_size(void) const {
return sizeof(Cons);
}
/*comparisons*/
virtual bool iso(Generic*gp) const{
if(is(gp)) {
return 1;
} else {
Cons* cp = dynamic_cast<Cons*>(gp);
if(cp != NULL){
return a->iso(cp->a) && d->iso(cp->d);
} else return 0;
}
}
/*references*/
virtual void get_refs(std::stack<Generic**>&s){
s.push(&a);
s.push(&d);
}
Cons(Generic* na, Generic* nd) : a(na), d(nd) {};
virtual ~Cons(){};
/*new stuff*/
Generic* car(void) const {return a;}
Generic* cdr(void) const {return d;}
Generic* scar(Generic* na) {return a = na;}
Generic* scdr(Generic* nd) {return d = nd;}
};
class MetadataCons : public Cons {
private:
Generic* line;
Generic* file;
protected:
MetadataCons(MetadataCons const&):Cons(*this){};
public:
virtual MetadataCons* clone(Semispace& sp) const{
return new(sp) MetadataCons(*this);
}
virtual size_t get_size(void) const {
return sizeof(MetadataCons);
}
MetadataCons(Generic* na, Generic* nd, Generic* nline, Generic* nfile)
: Cons(na, nd), line(nline), file(nfile){};
virtual ~MetadataCons(){};
/*can't be changed*/
Generic* getline(void) const {return line;}
Generic* getfile(void) const {return file;}
};
class Atom;
class Sym : public Generic{
private:
boost::shared_ptr<Atom> a;
Sym(void){}; //disallowed!
protected:
Sym(Sym const&){};
public:
/*standard stuff*/
virtual size_t hash(void) const{
return distribute_bits((size_t) &(*a));
}
virtual Sym* clone(Semispace& sp) const{
return new(sp) Sym(*this);
}
virtual size_t get_size(void) const{
return sizeof(Sym);
};
virtual bool is(Generic* gp) const{
if(gp == this) return 1;
Sym* sp = dynamic_cast<Sym*>(gp);
if(sp != NULL){
return sp->a == a;
} else return 0;
};
Sym(boost::shared_ptr<Atom> const& na) : a(na){};
virtual ~Sym(){};
/*new stuff*/
Atom& atom(void){return *a;};
};
#endif //TYPES_H
<commit_msg>Added comment about ToPointerLock<commit_after>#ifndef TYPES_H
#define TYPES_H
#include<stack>
#include<set>
#include"heaps.hpp"
#include"hashes.hpp"
class Semispace;
void* operator new(size_t, Semispace&);
void operator delete(void*, Semispace&);
class ToPointerLock;
class Generic {
private:
Generic* to_pointer;
protected:
Generic(void) : to_pointer(NULL) {};
Generic(Generic const&) : to_pointer(NULL) {};
public:
friend class Semispace;
friend class ToPointerLock;
virtual size_t hash(void) const =0;
virtual Generic* clone(Semispace&) const =0;
/* clone should always have the following code:
virtual Type* clone(Semispace& sp) const{
return new(sp) Type(*this);
}
*/
/*gets addresses of references to other objects*/
virtual void get_refs(std::stack<Generic**>&){};
/*comparisons*/
virtual bool is(Generic const* gp) const{return gp == this;}
virtual bool iso(Generic const* gp) const{return is(gp);}
virtual size_t get_size(void) const =0;
/*get_size should always have the following code:
virtual size_t get_size(void) const {
return sizeof(Type);
}
*/
virtual ~Generic(){};
size_t total_size(void);
};
inline bool is(Generic const* a, Generic const* b){ return a->is(b);}
inline bool iso(Generic const* a, Generic const* b){ return a->iso(b);}
/*RAII class to handle the to-pointers
This is used to protect the to-pointers in case of
an exception. The invariant is, to-pointers are
NULL during normal operation. If to-pointers must
be used, access to them should be via
ToPointerLock's, so that the to-pointers are reset
to NULL once the non-normal operation (GC,
tracing) are complete. When the operation
determines that the to-pointers can be left used
(i.e. after a GC run) then it can call the clear()
member function so that it won't bother resetting
the to-pointers.
*/
class ToPointerLock{
private:
std::set<Generic*> enset;
public:
void pointto(Generic* from, Generic* to){
enset.insert(from);
from->to_pointer = to;
}
Generic* to(Generic* from){
return from->to_pointer;
}
/*used to ignore the to-pointers in a successful
copy-and-sweep GC cycle
*/
void good(void){
enset.clear();
}
~ToPointerLock(){
std::set<Generic*>::iterator i;
for(i = enset.begin(); i != enset.end(); ++i){
(*i)->to_pointer = NULL;
}
}
};
class Cons : public Generic{
private:
Generic* a;
Generic* d;
protected:
Cons(Cons const&){};
public:
/*standard stuff*/
virtual size_t hash(void) const {
return a->hash() ^ d->hash();
}
virtual Cons* clone(Semispace& sp) const{
return new(sp) Cons(*this);
}
virtual size_t get_size(void) const {
return sizeof(Cons);
}
/*comparisons*/
virtual bool iso(Generic*gp) const{
if(is(gp)) {
return 1;
} else {
Cons* cp = dynamic_cast<Cons*>(gp);
if(cp != NULL){
return a->iso(cp->a) && d->iso(cp->d);
} else return 0;
}
}
/*references*/
virtual void get_refs(std::stack<Generic**>&s){
s.push(&a);
s.push(&d);
}
Cons(Generic* na, Generic* nd) : a(na), d(nd) {};
virtual ~Cons(){};
/*new stuff*/
Generic* car(void) const {return a;}
Generic* cdr(void) const {return d;}
Generic* scar(Generic* na) {return a = na;}
Generic* scdr(Generic* nd) {return d = nd;}
};
class MetadataCons : public Cons {
private:
Generic* line;
Generic* file;
protected:
MetadataCons(MetadataCons const&):Cons(*this){};
public:
virtual MetadataCons* clone(Semispace& sp) const{
return new(sp) MetadataCons(*this);
}
virtual size_t get_size(void) const {
return sizeof(MetadataCons);
}
MetadataCons(Generic* na, Generic* nd, Generic* nline, Generic* nfile)
: Cons(na, nd), line(nline), file(nfile){};
virtual ~MetadataCons(){};
/*can't be changed*/
Generic* getline(void) const {return line;}
Generic* getfile(void) const {return file;}
};
class Atom;
class Sym : public Generic{
private:
boost::shared_ptr<Atom> a;
Sym(void){}; //disallowed!
protected:
Sym(Sym const&){};
public:
/*standard stuff*/
virtual size_t hash(void) const{
return distribute_bits((size_t) &(*a));
}
virtual Sym* clone(Semispace& sp) const{
return new(sp) Sym(*this);
}
virtual size_t get_size(void) const{
return sizeof(Sym);
};
virtual bool is(Generic* gp) const{
if(gp == this) return 1;
Sym* sp = dynamic_cast<Sym*>(gp);
if(sp != NULL){
return sp->a == a;
} else return 0;
};
Sym(boost::shared_ptr<Atom> const& na) : a(na){};
virtual ~Sym(){};
/*new stuff*/
Atom& atom(void){return *a;};
};
#endif //TYPES_H
<|endoftext|> |
<commit_before>#include <string>
#include "dg/analysis/PointsTo/PointsToSet.h"
#include "dg/analysis/PointsTo/PointerSubgraphValidator.h"
namespace dg {
namespace analysis {
namespace pta {
namespace debug {
static void dumpNode(const PSNode *nd, std::string& errors) {
errors += std::string(PSNodeTypeToCString(nd->getType())) + " with ID " +
std::to_string(nd->getID()) + "\n - operands: [";
for (unsigned i = 0, e = nd->getOperandsNum(); i < e; ++i) {
const PSNode *op = nd->getOperand(i);
errors += std::to_string(op->getID()) += " ";
errors += std::string(PSNodeTypeToCString(op->getType()));
if (i != e - 1)
errors += ", ";
}
errors += "]\n";
}
bool PointerSubgraphValidator::warn(const PSNode *nd, const std::string& warning) {
warnings += "Warning: " + warning + "\n";
dumpNode(nd, warnings);
return true;
}
bool PointerSubgraphValidator::reportInvalOperands(const PSNode *nd, const std::string& user_err) {
errors += "Invalid operands:\n";
dumpNode(nd, errors);
if (!user_err.empty())
errors += "(" + user_err + ")\n";
return true;
}
bool PointerSubgraphValidator::reportInvalEdges(const PSNode *nd, const std::string& user_err) {
errors += "Invalid number of edges:\n";
dumpNode(nd, errors);
if (!user_err.empty())
errors += "(" + user_err + ")\n";
return true;
}
bool PointerSubgraphValidator::reportInvalNode(const PSNode *nd, const std::string& user_err) {
errors += "Invalid node:\n";
dumpNode(nd, errors);
if (!user_err.empty())
errors += "(" + user_err + ")\n";
return true;
}
bool PointerSubgraphValidator::reportUnreachableNode(const PSNode *nd) {
errors += "Unreachable node:\n";
dumpNode(nd, errors);
return true;
}
static bool hasDuplicateOperand(const PSNode *nd)
{
std::set<const PSNode *> ops;
for (const PSNode *op : nd->getOperands()) {
if (!ops.insert(op).second)
return true;
}
return false;
}
static bool hasNonpointerOperand(const PSNode *nd)
{
for (const PSNode *op : nd->getOperands()) {
if (op->getType() == PSNodeType::NOOP ||
op->getType() == PSNodeType::FREE ||
op->getType() == PSNodeType::ENTRY ||
op->getType() == PSNodeType::INVALIDATE_LOCALS ||
op->getType() == PSNodeType::INVALIDATE_OBJECT ||
op->getType() == PSNodeType::MEMCPY ||
op->getType() == PSNodeType::STORE)
return true;
}
return false;
}
bool PointerSubgraphValidator::checkOperands() {
bool invalid = false;
std::set<const PSNode *> known_nodes;
const auto& nodes = PS->getNodes();
for (const auto& nd : nodes) {
if (!nd)
continue;
if (!known_nodes.insert(nd.get()).second)
invalid |= reportInvalNode(nd.get(), "Node multiple times in the graph");
}
for (const auto& ndptr : nodes) {
if (!ndptr)
continue;
PSNode *nd = ndptr.get();
for (const PSNode *op : nd->getOperands()) {
if (op != NULLPTR && op != UNKNOWN_MEMORY && op != INVALIDATED &&
known_nodes.count(op) == 0) {
invalid |= reportInvalOperands(nd, "Node has unknown (maybe dangling) operand");
}
}
switch (nd->getType()) {
case PSNodeType::PHI:
if (nd->getOperandsNum() == 0) {
// this may not be always an error
// (say this is a phi of an uninitialized pointer
// for which we do not have any points to)
warn(nd, "Empty PHI");
} else if (hasDuplicateOperand(nd)) {
// this is not an error, but warn the user
// as this is redundant
warn(nd, "PHI Node contains duplicated operand");
} else if (hasNonpointerOperand(nd)) {
invalid |= reportInvalOperands(nd, "PHI Node contains non-pointer operand");
}
break;
case PSNodeType::NULL_ADDR:
case PSNodeType::UNKNOWN_MEM:
case PSNodeType::NOOP:
case PSNodeType::FUNCTION:
if (nd->getOperandsNum() != 0) {
invalid |= reportInvalOperands(nd, "Should not have an operand");
}
break;
case PSNodeType::GEP:
case PSNodeType::LOAD:
case PSNodeType::CAST:
case PSNodeType::INVALIDATE_OBJECT:
case PSNodeType::CONSTANT:
case PSNodeType::FREE:
if (hasNonpointerOperand(nd)) {
invalid |= reportInvalOperands(nd, "Node has non-pointer operand");
}
if (nd->getOperandsNum() != 1) {
invalid |= reportInvalOperands(nd, "Should have exactly one operand");
}
break;
case PSNodeType::STORE:
case PSNodeType::MEMCPY:
if (hasNonpointerOperand(nd)) {
invalid |= reportInvalOperands(nd, "Node has non-pointer operand");
}
if (nd->getOperandsNum() != 2) {
invalid |= reportInvalOperands(nd, "Should have exactly two operands");
}
break;
}
}
return invalid;
}
static inline bool isInPredecessors(const PSNode *nd, const PSNode *of) {
for (const PSNode *pred: of->getPredecessors()) {
if (pred == nd)
return true;
}
return false;
}
static inline bool canBeOutsideGraph(const PSNode *nd) {
return (nd->getType() == PSNodeType::FUNCTION ||
nd->getType() == PSNodeType::CONSTANT ||
nd->getType() == PSNodeType::UNKNOWN_MEM ||
nd->getType() == PSNodeType::NULL_ADDR);
}
std::set<const PSNode *> reachableNodes(const PSNode *nd) {
std::set<const PSNode *> reachable;
reachable.insert(nd);
std::vector<const PSNode *> to_process;
to_process.reserve(4);
to_process.push_back(nd);
while (!to_process.empty()) {
std::vector<const PSNode *> new_to_process;
new_to_process.reserve(to_process.size());
for (const PSNode *cur : to_process) {
for (const PSNode *succ : cur->getSuccessors()) {
if (reachable.insert(succ).second)
new_to_process.push_back(succ);
}
}
new_to_process.swap(to_process);
}
return reachable;
}
bool PointerSubgraphValidator::checkEdges() {
bool invalid = false;
// check incoming/outcoming edges of all nodes
const auto& nodes = PS->getNodes();
for (const auto& nd : nodes) {
if (!nd)
continue;
if (nd->predecessorsNum() == 0 && nd.get() != PS->getRoot()
&& !canBeOutsideGraph(nd.get())) {
invalid |= reportInvalEdges(nd.get(), "Non-root node has no predecessors");
}
for (const PSNode *succ : nd->getSuccessors()) {
if (!isInPredecessors(nd.get(), succ))
invalid |= reportInvalEdges(nd.get(), "Node not set as a predecessor of some of its successors");
}
}
// check that the edges form valid CFG (all nodes are reachable)
auto reachable = reachableNodes(PS->getRoot());
for (const auto &nd : nodes) {
if (!nd)
continue;
if (reachable.count(nd.get()) < 1 && !canBeOutsideGraph(nd.get())) {
invalid |= reportUnreachableNode(nd.get());
}
}
return invalid;
}
bool PointerSubgraphValidator::validate() {
bool invalid = false;
invalid |= checkOperands();
invalid |= checkEdges();
return invalid;
}
} // namespace debug
} // namespace pta
} // namespace analysis
} // namespace dg
<commit_msg>PTA validator: use getReachableNodes<commit_after>#include <string>
#include "dg/analysis/PointsTo/PointsToSet.h"
#include "dg/analysis/PointsTo/PointerSubgraphValidator.h"
namespace dg {
namespace analysis {
namespace pta {
namespace debug {
static void dumpNode(const PSNode *nd, std::string& errors) {
errors += std::string(PSNodeTypeToCString(nd->getType())) + " with ID " +
std::to_string(nd->getID()) + "\n - operands: [";
for (unsigned i = 0, e = nd->getOperandsNum(); i < e; ++i) {
const PSNode *op = nd->getOperand(i);
errors += std::to_string(op->getID()) += " ";
errors += std::string(PSNodeTypeToCString(op->getType()));
if (i != e - 1)
errors += ", ";
}
errors += "]\n";
}
bool PointerSubgraphValidator::warn(const PSNode *nd, const std::string& warning) {
warnings += "Warning: " + warning + "\n";
dumpNode(nd, warnings);
return true;
}
bool PointerSubgraphValidator::reportInvalOperands(const PSNode *nd, const std::string& user_err) {
errors += "Invalid operands:\n";
dumpNode(nd, errors);
if (!user_err.empty())
errors += "(" + user_err + ")\n";
return true;
}
bool PointerSubgraphValidator::reportInvalEdges(const PSNode *nd, const std::string& user_err) {
errors += "Invalid number of edges:\n";
dumpNode(nd, errors);
if (!user_err.empty())
errors += "(" + user_err + ")\n";
return true;
}
bool PointerSubgraphValidator::reportInvalNode(const PSNode *nd, const std::string& user_err) {
errors += "Invalid node:\n";
dumpNode(nd, errors);
if (!user_err.empty())
errors += "(" + user_err + ")\n";
return true;
}
bool PointerSubgraphValidator::reportUnreachableNode(const PSNode *nd) {
errors += "Unreachable node:\n";
dumpNode(nd, errors);
return true;
}
static bool hasDuplicateOperand(const PSNode *nd)
{
std::set<const PSNode *> ops;
for (const PSNode *op : nd->getOperands()) {
if (!ops.insert(op).second)
return true;
}
return false;
}
static bool hasNonpointerOperand(const PSNode *nd)
{
for (const PSNode *op : nd->getOperands()) {
if (op->getType() == PSNodeType::NOOP ||
op->getType() == PSNodeType::FREE ||
op->getType() == PSNodeType::ENTRY ||
op->getType() == PSNodeType::INVALIDATE_LOCALS ||
op->getType() == PSNodeType::INVALIDATE_OBJECT ||
op->getType() == PSNodeType::MEMCPY ||
op->getType() == PSNodeType::STORE)
return true;
}
return false;
}
bool PointerSubgraphValidator::checkOperands() {
bool invalid = false;
std::set<const PSNode *> known_nodes;
const auto& nodes = PS->getNodes();
for (const auto& nd : nodes) {
if (!nd)
continue;
if (!known_nodes.insert(nd.get()).second)
invalid |= reportInvalNode(nd.get(), "Node multiple times in the graph");
}
for (const auto& ndptr : nodes) {
if (!ndptr)
continue;
PSNode *nd = ndptr.get();
for (const PSNode *op : nd->getOperands()) {
if (op != NULLPTR && op != UNKNOWN_MEMORY && op != INVALIDATED &&
known_nodes.count(op) == 0) {
invalid |= reportInvalOperands(nd, "Node has unknown (maybe dangling) operand");
}
}
switch (nd->getType()) {
case PSNodeType::PHI:
if (nd->getOperandsNum() == 0) {
// this may not be always an error
// (say this is a phi of an uninitialized pointer
// for which we do not have any points to)
warn(nd, "Empty PHI");
} else if (hasDuplicateOperand(nd)) {
// this is not an error, but warn the user
// as this is redundant
warn(nd, "PHI Node contains duplicated operand");
} else if (hasNonpointerOperand(nd)) {
invalid |= reportInvalOperands(nd, "PHI Node contains non-pointer operand");
}
break;
case PSNodeType::NULL_ADDR:
case PSNodeType::UNKNOWN_MEM:
case PSNodeType::NOOP:
case PSNodeType::FUNCTION:
if (nd->getOperandsNum() != 0) {
invalid |= reportInvalOperands(nd, "Should not have an operand");
}
break;
case PSNodeType::GEP:
case PSNodeType::LOAD:
case PSNodeType::CAST:
case PSNodeType::INVALIDATE_OBJECT:
case PSNodeType::CONSTANT:
case PSNodeType::FREE:
if (hasNonpointerOperand(nd)) {
invalid |= reportInvalOperands(nd, "Node has non-pointer operand");
}
if (nd->getOperandsNum() != 1) {
invalid |= reportInvalOperands(nd, "Should have exactly one operand");
}
break;
case PSNodeType::STORE:
case PSNodeType::MEMCPY:
if (hasNonpointerOperand(nd)) {
invalid |= reportInvalOperands(nd, "Node has non-pointer operand");
}
if (nd->getOperandsNum() != 2) {
invalid |= reportInvalOperands(nd, "Should have exactly two operands");
}
break;
}
}
return invalid;
}
static inline bool isInPredecessors(const PSNode *nd, const PSNode *of) {
for (const PSNode *pred: of->getPredecessors()) {
if (pred == nd)
return true;
}
return false;
}
static inline bool canBeOutsideGraph(const PSNode *nd) {
return (nd->getType() == PSNodeType::FUNCTION ||
nd->getType() == PSNodeType::CONSTANT ||
nd->getType() == PSNodeType::UNKNOWN_MEM ||
nd->getType() == PSNodeType::NULL_ADDR);
}
std::set<const PSNode *> reachableNodes(const PSNode *nd) {
std::set<const PSNode *> reachable;
reachable.insert(nd);
std::vector<const PSNode *> to_process;
to_process.reserve(4);
to_process.push_back(nd);
while (!to_process.empty()) {
std::vector<const PSNode *> new_to_process;
new_to_process.reserve(to_process.size());
for (const PSNode *cur : to_process) {
for (const PSNode *succ : cur->getSuccessors()) {
if (reachable.insert(succ).second)
new_to_process.push_back(succ);
}
}
new_to_process.swap(to_process);
}
return reachable;
}
bool PointerSubgraphValidator::checkEdges() {
bool invalid = false;
// check incoming/outcoming edges of all nodes
const auto& nodes = PS->getNodes();
for (const auto& nd : nodes) {
if (!nd)
continue;
if (nd->predecessorsNum() == 0 && nd.get() != PS->getRoot()
&& !canBeOutsideGraph(nd.get())) {
invalid |= reportInvalEdges(nd.get(), "Non-root node has no predecessors");
}
for (const PSNode *succ : nd->getSuccessors()) {
if (!isInPredecessors(nd.get(), succ))
invalid |= reportInvalEdges(nd.get(), "Node not set as a predecessor of some of its successors");
}
}
// check that all nodes are reachable from the root
const auto reachable = getReachableNodes(PS->getRoot());
for (const auto &nd : nodes) {
if (!nd)
continue;
if (reachable.count(nd.get()) < 1 && !canBeOutsideGraph(nd.get())) {
invalid |= reportUnreachableNode(nd.get());
}
}
return invalid;
}
bool PointerSubgraphValidator::validate() {
bool invalid = false;
invalid |= checkOperands();
invalid |= checkEdges();
return invalid;
}
} // namespace debug
} // namespace pta
} // namespace analysis
} // namespace dg
<|endoftext|> |
<commit_before>#include <iostream>
#include <gtest/gtest.h>
using namespace std;
#include <zookeeper/zookeeper.h>
static int connected = 0;
static int expired = 0;
void main_watcher(zhandle_t *zkh, int type, int state, const char *path, void *context) {
if (type == ZOO_SESSION_EVENT) {
if (state == ZOO_CONNECTED_STATE) {
connected = 1;
} else if (state == ZOO_CONNECTING_STATE) {
connected = 0;
} else if (state == ZOO_EXPIRED_SESSION_STATE) {
expired = 1;
connected = 0;
zookeeper_close(zkh);
}
}
}
zhandle_t* init(const char *hostPort) {
srand(time(NULL));
zoo_set_debug_level(ZOO_LOG_LEVEL_INFO);
return zookeeper_init(hostPort, main_watcher, 15000, 0, 0, 0);
}
TEST(async_rpc, DISABLED_should_able_to_connect_to_zookeeper) {
zhandle_t* zk = init("localhost:2181");
EXPECT_TRUE(zk != nullptr);
sleep(1);
zookeeper_close(zk);
};
////////////////////////////////////////////////////////////////////////////////
#if 0
{
return InterfaceYStub(ctxt)._____async_y(req);
}
{
auto ___1 = InterfaceYStub(ctxt).______sync_y(req);
___bind_action(save_rsp_from_other_services_to_db, ___1);
___bind_action(save_rsp_to_log, ___1);
return ___1;
}
{///////////////////////////////////////////////////////////////////////////////TODO:
auto ___1 = InterfaceYStub(ctxt).______sync_y(req);
___1 --> save_rsp_from_other_services_to_db;
___1 --> save_rsp_to_log;
return ___1;
}
{
auto ___1 = InterfaceYStub(ctxt)._____async_y(req);
auto ___2 = InterfaceYStub(ctxt)._____async_y(req);
return ___bind_cell(merge_logic, ___1, ___2);
}
{///////////////////////////////////////////////////////////////////////////////TODO:
auto ___1 = InterfaceYStub(ctxt)._____async_y(req);
auto ___2 = InterfaceYStub(ctxt)._____async_y(req);
auto ___3 = (___1, ___2) --> merge_logic;
}
{
auto ___1 = InterfaceYStub(ctxt).______sync_y(req);
{
auto ___2 = ___bind_rpc(call__sync_y_again, ___1);
{
return ___bind_rpc(call__sync_y_again, ___2);
}
}
}
{///////////////////////////////////////////////////////////////////////////////TODO:
auto ___1 = InterfaceYStub(ctxt).______sync_y(req);
auto ___2 = ___1 --> call__sync_y_again;
auto ___3 = ___2 --> call__sync_y_again;
}
{
auto ___3 = InterfaceYStub(ctxt)._____async_y(req);
auto ___1 = InterfaceYStub(ctxt)._____async_y(req); ___bind_action(action1, ___1);
{
auto ___2 = ___bind_cell(gen2, ___1);
{
return ___bind_cell(merge_logic, ___2, ___3);
}
}
}
{///////////////////////////////////////////////////////////////////////////////TODO:
auto ___3 = InterfaceYStub(ctxt)._____async_y(req);
auto ___1 = InterfaceYStub(ctxt)._____async_y(req);
___1 --> action1;
auto ___2 = ___1 --> gen2;
auto ___4 = (___2, ___3) --> merge_logic;
}
{///////////////////////////////////////////////////////////////////////////////TODO:
auto ___1 = InterfaceYStub(ctxt).______sync_y(req) --> timeout(___ms(2000), rollback_transaction);
return ___1;
}
{///////////////////////////////////////////////////////////////////////////////TODO:
auto ___1 = InterfaceYStub(ctxt).______sync_y(req) --> timeout(___ms(2000), rollback_transaction);
auto ___2 = InterfaceYStub(ctxt).______sync_y(req) --> timeout(___ms(6000), rollback_transaction);
auto ___3 = (___1, ___2) --> merge_logic;
return ___3;
}
{///////////////////////////////////////////////////////////////////////////////TODO:
auto ___1 = InterfaceYStub(ctxt).______sync_y(req) --> timeout(___ms(2000), rollback_transaction);
auto ___2 = InterfaceYStub(ctxt).______sync_y(req) --> timeout(___ms(6000), rollback_transaction);
auto ___3 = (___1, ___2) --> merge_logic;
return ___3;
}
//TODO: multiple rpc, send rpc request to multiple interface provider.
//TODO: add filter and map keywords, such as map, filter, all, any, success, failure
//TODO: will not implement loop construct in SI, but we can call SI in loop in outside of SI.
// but we need an loop style example
// void sending_following_ids(id_batch_index) {
// if (id_batch_index == last_batch) { return loop_finish_cell(); };
//
// auto rsp_cell = SyncIdService.send_one_batch(get_ids_in_batch(id_batch_index));
// rsp_cell --> sending_following_ids();
// }
// void on_sync_id_msg() {
// sending_following_ids(start_batch_id);
// }
#endif
<commit_msg>add timeout logic<commit_after>#include <iostream>
#include <gtest/gtest.h>
using namespace std;
#include <zookeeper/zookeeper.h>
static int connected = 0;
static int expired = 0;
void main_watcher(zhandle_t *zkh, int type, int state, const char *path, void *context) {
if (type == ZOO_SESSION_EVENT) {
if (state == ZOO_CONNECTED_STATE) {
connected = 1;
} else if (state == ZOO_CONNECTING_STATE) {
connected = 0;
} else if (state == ZOO_EXPIRED_SESSION_STATE) {
expired = 1;
connected = 0;
zookeeper_close(zkh);
}
}
}
zhandle_t* init(const char *hostPort) {
srand(time(NULL));
zoo_set_debug_level(ZOO_LOG_LEVEL_INFO);
return zookeeper_init(hostPort, main_watcher, 15000, 0, 0, 0);
}
TEST(async_rpc, DISABLED_should_able_to_connect_to_zookeeper) {
zhandle_t* zk = init("localhost:2181");
EXPECT_TRUE(zk != nullptr);
sleep(1);
zookeeper_close(zk);
};
////////////////////////////////////////////////////////////////////////////////
#if 0
{
return InterfaceYStub(ctxt)._____async_y(req);
}
{
auto ___1 = InterfaceYStub(ctxt).______sync_y(req);
___bind_action(save_rsp_from_other_services_to_db, ___1);
___bind_action(save_rsp_to_log, ___1);
return ___1;
}
{///////////////////////////////////////////////////////////////////////////////TODO:
auto ___1 = InterfaceYStub(ctxt).______sync_y(req);
___1 --> save_rsp_from_other_services_to_db;
___1 --> save_rsp_to_log;
return ___1;
}
{
auto ___1 = InterfaceYStub(ctxt)._____async_y(req);
auto ___2 = InterfaceYStub(ctxt)._____async_y(req);
return ___bind_cell(merge_logic, ___1, ___2);
}
{///////////////////////////////////////////////////////////////////////////////TODO:
auto ___1 = InterfaceYStub(ctxt)._____async_y(req);
auto ___2 = InterfaceYStub(ctxt)._____async_y(req);
auto ___3 = (___1, ___2) --> merge_logic;
}
{
auto ___1 = InterfaceYStub(ctxt).______sync_y(req);
{
auto ___2 = ___bind_rpc(call__sync_y_again, ___1);
{
return ___bind_rpc(call__sync_y_again, ___2);
}
}
}
{///////////////////////////////////////////////////////////////////////////////TODO:
auto ___1 = InterfaceYStub(ctxt).______sync_y(req);
auto ___2 = ___1 --> call__sync_y_again;
auto ___3 = ___2 --> call__sync_y_again;
}
{
auto ___3 = InterfaceYStub(ctxt)._____async_y(req);
auto ___1 = InterfaceYStub(ctxt)._____async_y(req); ___bind_action(action1, ___1);
{
auto ___2 = ___bind_cell(gen2, ___1);
{
return ___bind_cell(merge_logic, ___2, ___3);
}
}
}
{///////////////////////////////////////////////////////////////////////////////TODO:
auto ___3 = InterfaceYStub(ctxt)._____async_y(req);
auto ___1 = InterfaceYStub(ctxt)._____async_y(req);
___1 --> action1;
auto ___2 = ___1 --> gen2;
auto ___4 = (___2, ___3) --> merge_logic;
}
{///////////////////////////////////////////////////////////////////////////////TODO:
auto ___1 = InterfaceYStub(ctxt).______sync_y(req) --> timeout(___ms(2000), rollback_transaction);
return ___1;
}
{///////////////////////////////////////////////////////////////////////////////TODO:
auto ___1 = InterfaceYStub(ctxt).______sync_y(req) --> timeout(___ms(2000), rollback_transaction);
auto ___2 = InterfaceYStub(ctxt).______sync_y(req) --> timeout(___ms(6000), rollback_transaction);
auto ___3 = (___1, ___2) --> merge_logic;
return ___3;
}
{///////////////////////////////////////////////////////////////////////////////TODO:
auto ___1 = InterfaceYStub(ctxt).______sync_y(req) --> timeout(___ms(2000), rollback_transaction);
auto ___2 = InterfaceYStub(ctxt).______sync_y(req) --> timeout(___ms(3000), rollback_transaction);
auto ___3 = (___1, ___2) --> merge_logic;
return ___3;
}
Cell<ResponseBar>& init_another_rpc_request(RpcContext &ctxt, Cell<ResponseBar> *___r) {
RequestFoo req; req.reqa = ___r->value().rspa;
return *(InterfaceYStub(ctxt).______sync_y_failed(req));
}
{///////////////////////////////////////////////////////////////////////////////TODO:
auto ___1 = InterfaceYStub(ctxt).______sync_y(req) --> timeout(___ms(2000), rollback_transaction);
auto ___2 = InterfaceYStub(ctxt).______sync_y(req) --> timeout(___ms(3000), rollback_transaction);
auto ___3 = (___1, ___2) --> init_another_rpc_request --> timeout(___ms(1000), rollback_transaction);
return ___3;
}
{///////////////////////////////////////////////////////////////////////////////TODO:
auto ___1 = InterfaceYStub(ctxt).______sync_y(req);
___1 --> action1;
auto ___2 = InterfaceYStub(ctxt).______sync_y(req);
___2 --> action1;
___2 --> action2;
auto ___3 = (___1, ___2) --> merge_logic --> timeout(___ms(5000), rollback_transaction);
return ___3;
}
//TODO: multiple rpc, send rpc request to multiple interface provider.
//TODO: add filter and map keywords, such as map, filter, all, any, success, failure
//TODO: will not implement loop construct in SI, but we can call SI in loop in outside of SI.
// but we need an loop style example
// void sending_following_ids(id_batch_index) {
// if (id_batch_index == last_batch) { return loop_finish_cell(); };
//
// auto rsp_cell = SyncIdService.send_one_batch(get_ids_in_batch(id_batch_index));
// rsp_cell --> sending_following_ids();
// }
// void on_sync_id_msg() {
// sending_following_ids(start_batch_id);
// }
#endif
<|endoftext|> |
<commit_before>#include <dlfcn.h>
#include "loader.h"
using BVS::Loader;
using BVS::ModuleDataMap;
using BVS::ModuleVector;
using BVS::LibHandle;
ModuleDataMap Loader::modules;
ModuleVector* Loader::hotSwapGraveYard = nullptr;
Loader::Loader(const Info& info, std::function<void()> errorHandler)
: logger{"Loader"},
info(info),
errorHandler(errorHandler)
{ }
void Loader::registerModule(const std::string& id, Module* module, bool hotSwap)
{
if (hotSwap)
{
#ifdef BVS_MODULE_HOTSWAP
// NOTE: hotSwapGraveYard will only be initialized when the HotSwap
// functionality is used. It is intended as a store for unneeded
// shared_ptr until the process execution ends, but since it is a
// static pointer it will never be explicitly deleted.
if (hotSwapGraveYard==nullptr) hotSwapGraveYard = new ModuleVector();
hotSwapGraveYard->push_back(std::shared_ptr<Module>(module));
modules[id]->module.swap(hotSwapGraveYard->back());
#endif //BVS_MODULE_HOTSWAP
}
else
{
modules[id] = std::shared_ptr<ModuleData>{new ModuleData{id, {}, {}, {},
module, nullptr, {}, ControlFlag::WAIT, Status::OK, {}}};
}
}
Loader& Loader::load(const std::string& id, const std::string& library, const std::string& configuration, const std::string& options, const std::string& poolName)
{
if (modules.find(id)!=modules.end())
{
LOG(0, "Duplicate id for module: " << id << std::endl << "If you try to load a module more than once, use unique ids and the id(library).options syntax!");
errorHandler();
}
LibHandle dlib = loadLibrary(id, library);
// execute bvsRegisterModule in loaded lib
typedef void (*bvsRegisterModule_t)(ModuleInfo moduleInfo, const Info& info);
bvsRegisterModule_t bvsRegisterModule;
#ifndef BVS_STATIC_MODULES
*reinterpret_cast<void**>(&bvsRegisterModule)=dlsym(dlib, "bvsRegisterModule");
#else
*reinterpret_cast<void**>(&bvsRegisterModule)=dlsym(dlib, std::string("bvsRegisterModule_" + library).c_str());
#endif //BVS_STATIC_MODULES
const char* dlerr = dlerror();
if (dlerr && bvsRegisterModule==nullptr)
{
LOG(0, "Loading function bvsRegisterModule() in '" << library << "' resulted in: " << dlerr);
errorHandler();
}
ModuleInfo moduleInfo{id, configuration};
bvsRegisterModule(moduleInfo, info);
modules[id]->configuration = configuration;
modules[id]->dlib = dlib;
modules[id]->library = library;
modules[id]->options = options;
// get connectors
modules[id]->connectors = std::move(ConnectorDataCollector::connectors);
modules[id]->poolName = poolName;
LOG(2, "Loading '" << id << "' successfull!");
return *this;
}
Loader& Loader::unload(const std::string& id)
{
disconnectModule(id);
modules[id]->connectors.clear();
modules[id]->module.reset();
unloadLibrary(id);
modules.erase(id);
LOG(2, "Unloading '" << id << "' successfull!");
return *this;
}
Loader& Loader::connectAllModules(const bool connectorTypeMatching)
{
for (auto& it: modules) connectModule(it.second->id, connectorTypeMatching);
return *this;
}
Loader& Loader::connectModule(const std::string& id, const bool connectorTypeMatching)
{
ModuleData* module = modules[id].get();
std::string options = module->options;
std::string selection;
std::string input;
std::string targetModule;
std::string targetOutput;
size_t separator;
size_t separator2;
while (!options.empty())
{
separator = options.find_first_of('(');
separator2 = options.find_first_of(')');
selection = options.substr(0, separator2+1);
if (separator!=std::string::npos)
{
input = options.substr(0, separator);
targetModule = options.substr(separator+1, separator2-separator-1);
}
else
{
LOG(0, "No input selection found: " << selection);
errorHandler();
}
options.erase(0, separator2+1);
if (options[0] == '.') options.erase(options.begin());
separator = targetModule.find_first_of('.');
if (separator!=std::string::npos)
{
targetOutput = targetModule.substr(separator+1, std::string::npos);
targetModule = targetModule.substr(0, separator);
}
else
{
LOG(0, "No module output selected: " << module->id << "." << selection);
errorHandler();
}
checkModuleInput(module, input);
checkModuleOutput(module, targetModule, targetOutput);
if (connectorTypeMatching && module->connectors[input]->typeIDHash != modules[targetModule]->connectors[targetOutput]->typeIDHash)
{
LOG(0, "Selected input and output connector template instantiations are of different type: " << module->id << "." << selection << " -> " << module->connectors[input]->typeIDName << " != " << modules[targetModule]->connectors[targetOutput]->typeIDName);
errorHandler();
}
module->connectors[input]->pointer = modules[targetModule]->connectors[targetOutput]->pointer;
module->connectors[input]->lock = std::unique_lock<std::mutex>{modules[targetModule]->connectors[targetOutput]->mutex, std::defer_lock};
LOG(3, "Connected: " << module->id << "." << module->connectors[input]->id << " <- " << modules[targetModule]->id << "." << modules[targetModule]->connectors[targetOutput]->id);
}
return *this;
}
Loader& Loader::disconnectModule(const std::string& id)
{
for (auto& connector: modules[id]->connectors)
{
if (connector.second->type==ConnectorType::INPUT) continue;
for (auto& module: modules)
{
for (auto& targetConnector: module.second->connectors)
{
if (connector.second->pointer==targetConnector.second->pointer)
{
targetConnector.second->active = false;
targetConnector.second->pointer = nullptr;
}
}
}
}
return *this;
}
#ifdef BVS_MODULE_HOTSWAP
Loader& Loader::hotSwapModule(const std::string& id)
{
unloadLibrary(id);
LibHandle dlib = loadLibrary(id, modules[id]->library);
typedef void (*bvsHotSwapModule_t)(const std::string& id, Module* module);
bvsHotSwapModule_t bvsHotSwapModule;
*reinterpret_cast<void**>(&bvsHotSwapModule)=dlsym(dlib, "bvsHotSwapModule");
char* dlerr = dlerror();
if (dlerr)
{
LOG(0, "Loading function bvsHotSwapModule() in '" << modules[id]->library << "' resulted in: " << dlerr);
errorHandler();
}
bvsHotSwapModule(id, modules[id]->module.get());
modules[id]->dlib = dlib;
LOG(2, "Hotswapping '" << id << "' successfull!");
return *this;
}
#endif //BVS_MODULE_HOTSWAP
LibHandle Loader::loadLibrary(const std::string& id, const std::string& library)
{
std::string modulePath = "lib" + library + ".so";
#ifndef BVS_STATIC_MODULES
LibHandle dlib = dlopen(modulePath.c_str(), RTLD_NOW);
#else
LibHandle dlib = dlopen(NULL, RTLD_NOW);
#endif //BVS_STATIC_MODULES
if (dlib!=NULL)
{
LOG(3, "Loading '" << id << "' from '" << modulePath << "'!");
}
else
{
#ifdef BVS_OSX_ANOMALIES
// additional check for 'dylib' (when compiled under OSX as SHARED instead of MODULE)
modulePath.resize(modulePath.size()-2);
modulePath += "dylib";
dlib = dlopen(modulePath.c_str(), RTLD_NOW);
if (dlib!=NULL) LOG(3, "Loading " << id << " from " << modulePath << "!");
#endif //BVS_OSX_ANOMALIES
}
if (dlib==NULL)
{
LOG(0, "Loading '" << modulePath << "' resulted in: " << dlerror());
errorHandler();
}
return dlib;
}
Loader& Loader::unloadLibrary(const std::string& id)
{
#ifndef BVS_OSX_ANOMALIES
std::string modulePath = "./lib" + modules[id]->library + ".so";
#else
std::string modulePath = "./lib" + modules[id]->library + ".(so|dylib)";
#endif //BVS_OSX_ANOMALIES
LOG(3, "Module '" << id << "' unloading from '" << modulePath << "'!");
void* dlib = modules[id]->dlib;
if (dlib==nullptr) LOG(0, "Requested module '" << id << "' not found!");
dlclose(dlib);
const char* dlerr = dlerror();
if (dlerr)
{
LOG(0, "While closing '" << modulePath << "' following error occured: " << dlerror());
errorHandler();
}
LOG(3, "Library '" << modulePath << "' unloaded!");
return *this;
}
Loader& Loader::checkModuleInput(const ModuleData* module, const std::string& inputName)
{
auto input = module->connectors.find(inputName);
if (input == module->connectors.end() || input->second->type != ConnectorType::INPUT)
{
LOG(0, "Input not found: " << module->id << "." << inputName);
printModuleConnectors(module);
errorHandler();
}
if (input->second->active)
{
LOG(0, "Input already connected: " << module->id << "." << inputName);
errorHandler();
}
return *this;
}
Loader& Loader::checkModuleOutput(const ModuleData* module, const std::string& targetModule, const std::string& targetOutput)
{
auto target = modules.find(targetModule);
if (target == modules.end())
{
LOG(0, "Module not found: " << targetModule << " in " << module->id << "." << module->options);
errorHandler();
}
auto output = target->second->connectors.find(targetOutput);
if (output == target->second->connectors.end() || output->second->type != ConnectorType::OUTPUT)
{
LOG(0, "Output not found: " << targetOutput << " in " << module->id << "." << module->options);
printModuleConnectors(target->second.get());
errorHandler();
}
return *this;
}
Loader& Loader::printModuleConnectors(const ModuleData* module)
{
if (module->connectors.size()==0)
{
LOG(0, "Module " << module->id << " does not define any connector!");
}
else
{
LOG(0, "Module " << module->id << " defines the following connectors: ");
for (auto& it: module->connectors) LOG(0, it.second->type << ": " << it.second->id);
}
return *this;
}
<commit_msg>lib: build modules into extra library on android<commit_after>#include <dlfcn.h>
#include "loader.h"
using BVS::Loader;
using BVS::ModuleDataMap;
using BVS::ModuleVector;
using BVS::LibHandle;
ModuleDataMap Loader::modules;
ModuleVector* Loader::hotSwapGraveYard = nullptr;
Loader::Loader(const Info& info, std::function<void()> errorHandler)
: logger{"Loader"},
info(info),
errorHandler(errorHandler)
{ }
void Loader::registerModule(const std::string& id, Module* module, bool hotSwap)
{
if (hotSwap)
{
#ifdef BVS_MODULE_HOTSWAP
// NOTE: hotSwapGraveYard will only be initialized when the HotSwap
// functionality is used. It is intended as a store for unneeded
// shared_ptr until the process execution ends, but since it is a
// static pointer it will never be explicitly deleted.
if (hotSwapGraveYard==nullptr) hotSwapGraveYard = new ModuleVector();
hotSwapGraveYard->push_back(std::shared_ptr<Module>(module));
modules[id]->module.swap(hotSwapGraveYard->back());
#endif //BVS_MODULE_HOTSWAP
}
else
{
modules[id] = std::shared_ptr<ModuleData>{new ModuleData{id, {}, {}, {},
module, nullptr, {}, ControlFlag::WAIT, Status::OK, {}}};
}
}
Loader& Loader::load(const std::string& id, const std::string& library, const std::string& configuration, const std::string& options, const std::string& poolName)
{
if (modules.find(id)!=modules.end())
{
LOG(0, "Duplicate id for module: " << id << std::endl << "If you try to load a module more than once, use unique ids and the id(library).options syntax!");
errorHandler();
}
std::string function = "bvsRegisterModule";
std::string tmpLibrary = library;
#ifdef BVS_STATIC_MODULES
function += "_" + library;
#ifdef __ANDROID_API__
tmpLibrary = "bvs_modules";
#else //__ANDROID_API__
tmpLibrary = "bvs";
#endif //__ANDROID_API__
#endif //BVS_STATIC_MODULES
LibHandle dlib = loadLibrary(id, tmpLibrary);
// execute bvsRegisterModule in loaded lib
typedef void (*bvsRegisterModule_t)(ModuleInfo moduleInfo, const Info& info);
bvsRegisterModule_t bvsRegisterModule;
*reinterpret_cast<void**>(&bvsRegisterModule)=dlsym(dlib, function.c_str());
const char* dlerr = dlerror();
if (dlerr && bvsRegisterModule==nullptr)
{
LOG(0, "Loading function " << function << " from '" << tmpLibrary << "' resulted in: " << dlerr);
errorHandler();
}
ModuleInfo moduleInfo{id, configuration};
bvsRegisterModule(moduleInfo, info);
modules[id]->configuration = configuration;
modules[id]->dlib = dlib;
modules[id]->library = tmpLibrary;
modules[id]->options = options;
// get connectors
modules[id]->connectors = std::move(ConnectorDataCollector::connectors);
modules[id]->poolName = poolName;
LOG(2, "Loading '" << id << "' successfull!");
return *this;
}
Loader& Loader::unload(const std::string& id)
{
disconnectModule(id);
modules[id]->connectors.clear();
modules[id]->module.reset();
unloadLibrary(id);
modules.erase(id);
LOG(2, "Unloading '" << id << "' successfull!");
return *this;
}
Loader& Loader::connectAllModules(const bool connectorTypeMatching)
{
for (auto& it: modules) connectModule(it.second->id, connectorTypeMatching);
return *this;
}
Loader& Loader::connectModule(const std::string& id, const bool connectorTypeMatching)
{
ModuleData* module = modules[id].get();
std::string options = module->options;
std::string selection;
std::string input;
std::string targetModule;
std::string targetOutput;
size_t separator;
size_t separator2;
while (!options.empty())
{
separator = options.find_first_of('(');
separator2 = options.find_first_of(')');
selection = options.substr(0, separator2+1);
if (separator!=std::string::npos)
{
input = options.substr(0, separator);
targetModule = options.substr(separator+1, separator2-separator-1);
}
else
{
LOG(0, "No input selection found: " << selection);
errorHandler();
}
options.erase(0, separator2+1);
if (options[0] == '.') options.erase(options.begin());
separator = targetModule.find_first_of('.');
if (separator!=std::string::npos)
{
targetOutput = targetModule.substr(separator+1, std::string::npos);
targetModule = targetModule.substr(0, separator);
}
else
{
LOG(0, "No module output selected: " << module->id << "." << selection);
errorHandler();
}
checkModuleInput(module, input);
checkModuleOutput(module, targetModule, targetOutput);
if (connectorTypeMatching && module->connectors[input]->typeIDHash != modules[targetModule]->connectors[targetOutput]->typeIDHash)
{
LOG(0, "Selected input and output connector template instantiations are of different type: " << module->id << "." << selection << " -> " << module->connectors[input]->typeIDName << " != " << modules[targetModule]->connectors[targetOutput]->typeIDName);
errorHandler();
}
module->connectors[input]->pointer = modules[targetModule]->connectors[targetOutput]->pointer;
module->connectors[input]->lock = std::unique_lock<std::mutex>{modules[targetModule]->connectors[targetOutput]->mutex, std::defer_lock};
LOG(3, "Connected: " << module->id << "." << module->connectors[input]->id << " <- " << modules[targetModule]->id << "." << modules[targetModule]->connectors[targetOutput]->id);
}
return *this;
}
Loader& Loader::disconnectModule(const std::string& id)
{
for (auto& connector: modules[id]->connectors)
{
if (connector.second->type==ConnectorType::INPUT) continue;
for (auto& module: modules)
{
for (auto& targetConnector: module.second->connectors)
{
if (connector.second->pointer==targetConnector.second->pointer)
{
targetConnector.second->active = false;
targetConnector.second->pointer = nullptr;
}
}
}
}
return *this;
}
#ifdef BVS_MODULE_HOTSWAP
Loader& Loader::hotSwapModule(const std::string& id)
{
unloadLibrary(id);
LibHandle dlib = loadLibrary(id, modules[id]->library);
typedef void (*bvsHotSwapModule_t)(const std::string& id, Module* module);
bvsHotSwapModule_t bvsHotSwapModule;
*reinterpret_cast<void**>(&bvsHotSwapModule)=dlsym(dlib, "bvsHotSwapModule");
char* dlerr = dlerror();
if (dlerr)
{
LOG(0, "Loading function bvsHotSwapModule() in '" << modules[id]->library << "' resulted in: " << dlerr);
errorHandler();
}
bvsHotSwapModule(id, modules[id]->module.get());
modules[id]->dlib = dlib;
LOG(2, "Hotswapping '" << id << "' successfull!");
return *this;
}
#endif //BVS_MODULE_HOTSWAP
LibHandle Loader::loadLibrary(const std::string& id, const std::string& library)
{
std::string modulePath;
if (library == "bvs") modulePath = "libbvs.so";
else modulePath = "lib" + library + ".so";
LibHandle dlib;
if (modulePath == "bvs") dlib = dlopen(NULL, RTLD_NOW);
else dlib = dlopen(modulePath.c_str(), RTLD_NOW);
if (dlib!=NULL)
{
LOG(3, "Loading '" << id << "' from '" << modulePath << "'!");
}
else
{
#ifdef BVS_OSX_ANOMALIES
// additional check for 'dylib' (when compiled under OSX as SHARED instead of MODULE)
modulePath.resize(modulePath.size()-2);
modulePath += "dylib";
dlib = dlopen(modulePath.c_str(), RTLD_NOW);
if (dlib!=NULL) LOG(3, "Loading " << id << " from " << modulePath << "!");
#endif //BVS_OSX_ANOMALIES
}
if (dlib==NULL)
{
LOG(0, "Loading '" << modulePath << "' resulted in: " << dlerror());
errorHandler();
}
return dlib;
}
Loader& Loader::unloadLibrary(const std::string& id)
{
#ifndef BVS_OSX_ANOMALIES
std::string modulePath = "./lib" + modules[id]->library + ".so";
#else
std::string modulePath = "./lib" + modules[id]->library + ".(so|dylib)";
#endif //BVS_OSX_ANOMALIES
LOG(3, "Module '" << id << "' unloading from '" << modulePath << "'!");
void* dlib = modules[id]->dlib;
if (dlib==nullptr) LOG(0, "Requested module '" << id << "' not found!");
dlclose(dlib);
const char* dlerr = dlerror();
if (dlerr)
{
LOG(0, "While closing '" << modulePath << "' following error occured: " << dlerror());
errorHandler();
}
LOG(3, "Library '" << modulePath << "' unloaded!");
return *this;
}
Loader& Loader::checkModuleInput(const ModuleData* module, const std::string& inputName)
{
auto input = module->connectors.find(inputName);
if (input == module->connectors.end() || input->second->type != ConnectorType::INPUT)
{
LOG(0, "Input not found: " << module->id << "." << inputName);
printModuleConnectors(module);
errorHandler();
}
if (input->second->active)
{
LOG(0, "Input already connected: " << module->id << "." << inputName);
errorHandler();
}
return *this;
}
Loader& Loader::checkModuleOutput(const ModuleData* module, const std::string& targetModule, const std::string& targetOutput)
{
auto target = modules.find(targetModule);
if (target == modules.end())
{
LOG(0, "Module not found: " << targetModule << " in " << module->id << "." << module->options);
errorHandler();
}
auto output = target->second->connectors.find(targetOutput);
if (output == target->second->connectors.end() || output->second->type != ConnectorType::OUTPUT)
{
LOG(0, "Output not found: " << targetOutput << " in " << module->id << "." << module->options);
printModuleConnectors(target->second.get());
errorHandler();
}
return *this;
}
Loader& Loader::printModuleConnectors(const ModuleData* module)
{
if (module->connectors.size()==0)
{
LOG(0, "Module " << module->id << " does not define any connector!");
}
else
{
LOG(0, "Module " << module->id << " defines the following connectors: ");
for (auto& it: module->connectors) LOG(0, it.second->type << ": " << it.second->id);
}
return *this;
}
<|endoftext|> |
<commit_before>// This file is a part of the IncludeOS unikernel - www.includeos.org
//
// Copyright 2016-2017 Oslo and Akershus University College of Applied Sciences
// and Alfred Bratterud
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
#pragma once
#ifndef HTTP_CONNECTION_HPP
#define HTTP_CONNECTION_HPP
// http
#include "request.hpp"
#include "response.hpp"
#include <net/tcp/connection.hpp>
namespace http {
class Connection {
public:
using TCP_conn = net::tcp::Connection_ptr;
using Peer = net::tcp::Socket;
using buffer_t = net::tcp::buffer_t;
public:
inline explicit Connection(TCP_conn tcpconn, bool keep_alive = true);
template <typename TCP>
explicit Connection(TCP&, Peer);
inline constexpr explicit Connection() noexcept;
net::tcp::port_t local_port() const noexcept
{ return (tcpconn_) ? tcpconn_->local_port() : 0; }
Peer peer() const noexcept
{ return (tcpconn_) ? tcpconn_->remote() : Peer(); }
void timeout()
{ tcpconn_->is_closing() ? tcpconn_->abort() : tcpconn_->close(); }
auto&& tcp() const
{ return tcpconn_; }
/**
* @brief Shutdown the underlying TCP connection
*/
inline void shutdown();
/**
* @brief Release the underlying TCP connection,
* making this connection useless.
*
* @return The underlying TCP connection
*/
inline TCP_conn release();
/**
* @brief Wether the underlying TCP connection has been released or not
*
* @return true if the underlying TCP connection is released
*/
bool released() const
{ return tcpconn_ == nullptr; }
static Connection& empty() noexcept
{
static Connection c;
return c;
}
/* Delete copy constructor */
Connection(const Connection&) = delete;
Connection(Connection&&) = default;
/* Delete copy assignment */
Connection& operator=(const Connection&) = delete;
Connection& operator=(Connection&&) = default;
virtual ~Connection() {}
protected:
TCP_conn tcpconn_;
bool keep_alive_;
}; // < class Connection
inline Connection::Connection(TCP_conn tcpconn, bool keep_alive)
: tcpconn_{std::move(tcpconn)},
keep_alive_{keep_alive}
{
Ensures(tcpconn_ != nullptr);
debug("<http::Connection> Created %u -> %s %p\n", local_port(), peer().to_string().c_str(), this);
}
template <typename TCP>
Connection::Connection(TCP& tcp, Peer addr)
: Connection(tcp.connect(addr))
{
}
inline constexpr Connection::Connection() noexcept
: tcpconn_(nullptr),
keep_alive_(false)
{
}
inline void Connection::shutdown()
{
if(tcpconn_->is_closing())
tcpconn_->close();
}
inline Connection::TCP_conn Connection::release()
{
auto copy = tcpconn_;
// this is expensive and may be unecessary,
// but just to be safe for now
copy->setup_default_callbacks();
tcpconn_ = nullptr;
return copy;
}
} // < namespace http
#endif // < HTTP_CONNECTION_HPP
<commit_msg>http: Connection now keeps track of its peer even when TCP conn is released<commit_after>// This file is a part of the IncludeOS unikernel - www.includeos.org
//
// Copyright 2016-2017 Oslo and Akershus University College of Applied Sciences
// and Alfred Bratterud
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
#pragma once
#ifndef HTTP_CONNECTION_HPP
#define HTTP_CONNECTION_HPP
// http
#include "request.hpp"
#include "response.hpp"
#include <net/tcp/connection.hpp>
namespace http {
class Connection {
public:
using TCP_conn = net::tcp::Connection_ptr;
using Peer = net::tcp::Socket;
using buffer_t = net::tcp::buffer_t;
public:
inline explicit Connection(TCP_conn tcpconn, bool keep_alive = true);
template <typename TCP>
explicit Connection(TCP&, Peer);
inline explicit Connection() noexcept;
net::tcp::port_t local_port() const noexcept
{ return (tcpconn_) ? tcpconn_->local_port() : 0; }
Peer peer() const noexcept
{ return peer_; }
void timeout()
{ tcpconn_->is_closing() ? tcpconn_->abort() : tcpconn_->close(); }
auto&& tcp() const
{ return tcpconn_; }
/**
* @brief Shutdown the underlying TCP connection
*/
inline void shutdown();
/**
* @brief Release the underlying TCP connection,
* making this connection useless.
*
* @return The underlying TCP connection
*/
inline TCP_conn release();
/**
* @brief Wether the underlying TCP connection has been released or not
*
* @return true if the underlying TCP connection is released
*/
bool released() const
{ return tcpconn_ == nullptr; }
static Connection& empty() noexcept
{
static Connection c;
return c;
}
/* Delete copy constructor */
Connection(const Connection&) = delete;
Connection(Connection&&) = default;
/* Delete copy assignment */
Connection& operator=(const Connection&) = delete;
Connection& operator=(Connection&&) = default;
virtual ~Connection() {}
protected:
TCP_conn tcpconn_;
bool keep_alive_;
Peer peer_;
}; // < class Connection
inline Connection::Connection(TCP_conn tcpconn, bool keep_alive)
: tcpconn_{std::move(tcpconn)},
keep_alive_{keep_alive},
peer_{tcpconn_->remote()}
{
Ensures(tcpconn_ != nullptr);
debug("<http::Connection> Created %u -> %s %p\n", local_port(), peer().to_string().c_str(), this);
}
template <typename TCP>
Connection::Connection(TCP& tcp, Peer addr)
: Connection(tcp.connect(addr))
{
}
inline Connection::Connection() noexcept
: tcpconn_(nullptr),
keep_alive_(false),
peer_{}
{
}
inline void Connection::shutdown()
{
if(tcpconn_->is_closing())
tcpconn_->close();
}
inline Connection::TCP_conn Connection::release()
{
auto copy = tcpconn_;
// this is expensive and may be unecessary,
// but just to be safe for now
copy->setup_default_callbacks();
tcpconn_ = nullptr;
return copy;
}
} // < namespace http
#endif // < HTTP_CONNECTION_HPP
<|endoftext|> |
<commit_before>#include <archie/utils/number.h>
namespace archie {
namespace utils {
template <typename... Ts>
struct type_list {
using size = Number<sizeof...(Ts)>;
template <template <typename...> class Func>
using apply = typename Func<Ts...>::type;
template <template <typename> class Func>
using transform = type_list<typename Func<Ts>::type...>;
};
}
}
#include <gtest/gtest.h>
#include <tuple>
#include <type_traits>
#include <memory>
namespace {
template <unsigned I>
struct utype {};
template <typename... Ts>
struct tuple_ {
using type = std::tuple<Ts...>;
};
template <typename Tp>
struct uptr_ {
using type = std::unique_ptr<Tp>;
};
namespace au = archie::utils;
struct type_list_test : testing::Test {};
TEST_F(type_list_test, canGetTypeListSize) {
static_assert(au::type_list<>::size::value == 0, "");
static_assert(au::type_list<utype<0>>::size::value == 1, "");
static_assert(au::type_list<utype<0>, utype<0>>::size::value == 2, "");
static_assert(au::type_list<utype<0>, utype<1>>::size::value == 2, "");
}
TEST_F(type_list_test, canApply) {
using type = au::type_list<utype<0>, utype<1>>::apply<tuple_>;
static_assert(std::is_same<std::tuple<utype<0>, utype<1>>, type>::value, "");
}
TEST_F(type_list_test, canTransform) {
using type = au::type_list<utype<0>, utype<1>>::transform<uptr_>;
static_assert(
std::is_same<
au::type_list<std::unique_ptr<utype<0>>, std::unique_ptr<utype<1>>>,
type>::value,
"");
}
}
<commit_msg>transform and apply<commit_after>#include <archie/utils/number.h>
namespace archie {
namespace utils {
template <typename... Ts>
struct type_list {
using size = Number<sizeof...(Ts)>;
template <template <typename...> class Func>
using apply = typename Func<Ts...>::type;
template <template <typename> class Func>
using transform = type_list<typename Func<Ts>::type...>;
};
}
}
#include <gtest/gtest.h>
#include <tuple>
#include <type_traits>
#include <memory>
namespace {
template <unsigned I>
struct utype {};
using _0 = utype<0>;
using _1 = utype<1>;
template <typename... Ts>
struct tuple_ {
using type = std::tuple<Ts...>;
};
template <typename Tp>
struct uptr_ {
using type = std::unique_ptr<Tp>;
};
namespace au = archie::utils;
struct type_list_test : testing::Test {};
TEST_F(type_list_test, canGetTypeListSize) {
static_assert(au::type_list<>::size::value == 0, "");
static_assert(au::type_list<_0>::size::value == 1, "");
static_assert(au::type_list<_0, _0>::size::value == 2, "");
static_assert(au::type_list<_0, _1>::size::value == 2, "");
}
using list_ = au::type_list<_0, _1>;
TEST_F(type_list_test, canApply) {
using type = list_::apply<tuple_>;
static_assert(std::is_same<std::tuple<_0, _1>, type>::value, "");
}
TEST_F(type_list_test, canTransform) {
using type = list_::transform<uptr_>;
static_assert(
std::is_same<au::type_list<std::unique_ptr<_0>, std::unique_ptr<_1>>,
type>::value,
"");
}
TEST_F(type_list_test, canTransformAndApply) {
using type = list_::transform<uptr_>::apply<tuple_>;
static_assert(
std::is_same<std::tuple<std::unique_ptr<_0>, std::unique_ptr<_1>>,
type>::value,
"");
}
}
<|endoftext|> |
<commit_before>#include <sstream>
#include <iostream>
#include <iomanip>
#include <map>
#include <cstdlib>
#include <time.h>
#include <sys/time.h>
#include "zlog/db.h"
#include "zlog/backend/lmdb.h"
#include "kvstore/kvstore.pb.h"
#include "rapidjson/writer.h"
#include "rapidjson/stringbuffer.h"
using namespace rapidjson;
int main(int argc, char **argv)
{
auto be = new LMDBBackend();
be->Init("/tmp/zlog-db");
zlog::Log *log;
int ret = zlog::Log::OpenOrCreate(be, "log", NULL, &log);
assert(ret == 0);
uint64_t tail;
ret = log->CheckTail(&tail);
assert(ret == 0);
std::cerr << "tail: " << tail << std::endl;
uint64_t pos = tail;
do {
std::string data;
ret = log->Read(pos, &data);
if (ret == 0) {
kvstore_proto::Intention i;
assert(i.ParseFromString(data));
assert(i.IsInitialized());
StringBuffer s;
Writer<StringBuffer> writer(s);
writer.StartObject();
writer.Key("pos");
writer.Uint(pos);
writer.Key("bytes");
writer.Uint(data.size());
writer.Key("snapshot");
writer.Uint(i.snapshot());
writer.Key("tree");
writer.StartArray();
for (int j = 0; j < i.tree_size(); j++) {
const auto& node = i.tree(j);
writer.StartObject();
writer.Key("red");
writer.Bool(node.red());
writer.Key("key");
writer.String(node.key().c_str());
writer.Key("val");
writer.String(node.val().c_str());
writer.Key("left");
writer.StartObject();
writer.Key("nil");
writer.Bool(node.left().nil());
writer.Key("self");
writer.Bool(node.left().self());
writer.Key("csn");
writer.Uint(node.left().csn());
writer.Key("off");
writer.Uint(node.left().off());
writer.EndObject();
writer.Key("right");
writer.StartObject();
writer.Key("nil");
writer.Bool(node.right().nil());
writer.Key("self");
writer.Bool(node.right().self());
writer.Key("csn");
writer.Uint(node.right().csn());
writer.Key("off");
writer.Uint(node.right().off());
writer.EndObject();
writer.EndObject();
}
writer.EndArray();
writer.EndObject();
std::cout << s.GetString() << std::endl;
} else {
std::cerr << "pos " << pos << " err " << ret << std::endl;
}
} while (pos--);
return 0;
}
<commit_msg>kvs: export in back to front order<commit_after>#include <sstream>
#include <iostream>
#include <iomanip>
#include <map>
#include <cstdlib>
#include <time.h>
#include <sys/time.h>
#include "zlog/db.h"
#include "zlog/backend/lmdb.h"
#include "kvstore/kvstore.pb.h"
#include "rapidjson/writer.h"
#include "rapidjson/stringbuffer.h"
using namespace rapidjson;
int main(int argc, char **argv)
{
auto be = new LMDBBackend();
be->Init("/tmp/zlog-db");
zlog::Log *log;
int ret = zlog::Log::OpenOrCreate(be, "log", NULL, &log);
assert(ret == 0);
uint64_t tail;
ret = log->CheckTail(&tail);
assert(ret == 0);
std::cerr << "tail: " << tail << std::endl;
uint64_t pos = 0;
do {
std::string data;
ret = log->Read(pos, &data);
if (ret == 0) {
kvstore_proto::Intention i;
assert(i.ParseFromString(data));
assert(i.IsInitialized());
StringBuffer s;
Writer<StringBuffer> writer(s);
writer.StartObject();
writer.Key("pos");
writer.Uint(pos);
writer.Key("bytes");
writer.Uint(data.size());
writer.Key("snapshot");
writer.Uint(i.snapshot());
writer.Key("tree");
writer.StartArray();
for (int j = 0; j < i.tree_size(); j++) {
const auto& node = i.tree(j);
writer.StartObject();
writer.Key("red");
writer.Bool(node.red());
writer.Key("key");
writer.String(node.key().c_str());
writer.Key("val");
writer.String(node.val().c_str());
writer.Key("left");
writer.StartObject();
writer.Key("nil");
writer.Bool(node.left().nil());
writer.Key("self");
writer.Bool(node.left().self());
writer.Key("csn");
writer.Uint(node.left().csn());
writer.Key("off");
writer.Uint(node.left().off());
writer.EndObject();
writer.Key("right");
writer.StartObject();
writer.Key("nil");
writer.Bool(node.right().nil());
writer.Key("self");
writer.Bool(node.right().self());
writer.Key("csn");
writer.Uint(node.right().csn());
writer.Key("off");
writer.Uint(node.right().off());
writer.EndObject();
writer.EndObject();
}
writer.EndArray();
writer.EndObject();
std::cout << s.GetString() << std::endl;
} else {
std::cerr << "pos " << pos << " err " << ret << std::endl;
}
} while (++pos <= tail);
return 0;
}
<|endoftext|> |
<commit_before>#ifndef DATA_ADAPTER_ARRAY_HPP_INCLUDED
#define DATA_ADAPTER_ARRAY_HPP_INCLUDED
#include "data_adapter.hpp"
#ifndef NDEBUG
#include <iostream>
using std::cout;
using std::endl;
#endif // NDEBUG
template <typename T, size_t N>
class DataAdapter<T[N]> : public DataAdapterBase<T[N], T, DataAdapter<T[N]> > {
public:
typedef DataAdapterBase<T[N], T, DataAdapter<T[N]> > _Base;
typedef typename _Base::value_type value_type;
typedef typename _Base::element_type element_type;
typedef typename _Base::pointer_type pointer_type;
typedef typename _Base::size_type size_type;
typedef typename _Base::iterator iterator;
typedef typename _Base::const_iterator const_iterator;
typedef typename _Base::reverse_iterator reverse_iterator;
typedef typename _Base::const_reverse_iterator const_reverse_iterator;
private:
value_type data;
static size_type data_size;
size_type used_length;
public:
DataAdapter() {
this->clear();
}
explicit DataAdapter( const value_type & val ) {
this->assign( val, val + N );
}
inline size_type capacity() const {
return DataAdapter::data_size;
}
inline size_type length() const {
return this->used_length;
}
void push_back( const element_type & n ) {
//uses the previous length returned by resize to dictate the position of the last element
this->at( this->resize( this->length() + 1 ) ) = n;
}
void push_front( const element_type & val ) {
if( !this->full() ) {
iterator first = this->begin();
iterator last = this->end();
this->resize( this->length() + 1 );
std::copy_backward( first, last, this->end() );
*first = val;
} else {
throw std::out_of_range( "DataAdapter::push_front: Out of Range" );
}
}
element_type pop_back() {
if( !this->empty() ) {
return this->data[--this->used_length];
} else {
return element_type();
}
}
element_type pop_front() {
element_type ret = this->front();
std::copy( this->begin() + 1, this->end() - 1, this->begin() );
this->resize( this->length() - 1 );
return ret;
}
inline element_type & at( size_type n ) {
return this->data[n];
}
inline const element_type at( size_type n ) const {
return this->data[n];
}
inline element_type & at( iterator it ) {
return this->at( it.off );
}
inline const element_type at( const_iterator it ) const {
return this->at( it.off );
}
inline element_type front() const {
return this->at( 0 );
}
inline element_type & front() {
return this->at( 0 );
}
element_type back() const {
if( !this->empty() ) {
return this->at( this->end() - 1 );
} else {
return this->front();
}
}
element_type & back() {
if( !this->empty() ) {
return this->data[this->used_length - 1];
} else {
return this->front();
}
}
iterator sorted_insert( const element_type & n ) {
//First, add it to the end
this->push_back( n );
//Then insert it into the proper place
for( size_type i = this->length() - 1; i > 0; --i ) {
if( this->at( i ) < this->at( i - 1 ) ) {
std::swap( this->at( i ), this->at( i - 1 ) );
} else {
return this->begin() + i;
}
}
return this->begin();
}
//single element
inline iterator insert( iterator pos, const element_type & val ) {
return this->insert( pos, 1, val );
}
//fill
iterator insert( iterator pos, size_type n, const element_type & val ) {
if( n != 0 ) {
if( pos < this->end() + 1 && this->length() + n <= this->capacity() ) {
iterator first = this->begin() + pos;
iterator last = this->end() - n;
this->resize( this->length() + n );
std::copy_backward( first, last, this->end() );
std::fill( first, first + n, val );
return first;
} else {
throw std::out_of_range( "DataAdapter::insert(fill): Out of Range" );
}
} else {
return this->end();
}
//Otherwise there is nothing to insert
}
//range
iterator insert( iterator pos, const_iterator first, const_iterator last ) {
if( first != last && first < last ) {
if( this->length() + ( last - first ) <= this->capacity() ) {
size_type diff = last - first;
iterator f = this->begin() + pos;
iterator l = this->end() - diff;
this->resize( this->length() + diff );
std::copy_backward( f, l, this->end() );
std::copy( first, last, f );
return f;
} else {
throw std::out_of_range( "DataAdapter::insert(range): Out of Range" );
}
} else {
return this->end();
}
}
//Clear is unique in that is zeros the memory just in case
void clear() {
std::fill( this->data, this->data + this->capacity(), element_type( 0x0 ) );
this->used_length = 0;
}
inline size_type resize( size_type n ) {
return this->resize( n, element_type( 0x0 ) );
}
size_type resize( size_type n, const element_type & v ) {
if( n <= this->capacity() ) {
size_type ret = this->length();
if( n < this->length() ) {
this->used_length = n;
} else {
size_type ol = this->used_length;
this->used_length = n;
std::fill( this->begin() + n, this->end(), v );
}
return ret;
} else {
throw std::out_of_range( "DataAdapter::resize: Out of Range" );
}
}
inline iterator erase( iterator pos ) {
return this->erase( pos, pos + 1 );
}
iterator erase( iterator first, iterator last ) {
size_type diff = ( last - first );
if( last <= this->end() && diff <= this->length() ) {
iterator f = this->begin() + first;
iterator l = this->begin() + last;
std::copy( l, this->end(), f );
this->resize( this->length() - diff );
return f;
} else {
throw std::out_of_range( "DataAdapter::erase(range): Out of Range" );
}
}
};
template <typename T, size_t N>
typename DataAdapter<T[N]>::size_type DataAdapter<T[N]>::data_size =
sizeof( DataAdapter<T[N]>::value_type ) / sizeof( DataAdapter<T[N]>::element_type );
template <typename T, size_t N>
class DataApapterIterator<T[N]>
: public std::iterator<std::random_access_iterator_tag, T, size_t> {
public:
typedef std::iterator<std::random_access_iterator_tag, T> iterator_traits;
typedef typename iterator_traits::iterator_category iterator_category;
typedef typename iterator_traits::value_type value_type;
typedef typename iterator_traits::difference_type difference_type;
typedef typename iterator_traits::pointer pointer;
typedef typename iterator_traits::reference reference;
typedef DataAdapter<T[N]> parent_type;
friend class DataAdapter<T[N]>;
private:
//Keep a pointer to the parent
parent_type * parent;
difference_type off;
public:
DataApapterIterator() : parent( NULL ), off( 0 ) {}
DataApapterIterator( parent_type * x, difference_type ioff = 0 ) : parent( x ), off( ioff ) {}
DataApapterIterator( parent_type & x, difference_type ioff = 0 ) : parent( &x ), off( ioff ) {}
DataApapterIterator( const DataApapterIterator & it ) : parent( it.parent ), off( it.off ) {}
inline DataApapterIterator & operator=( const DataApapterIterator & it ) {
this->parent = it.parent;
this->off = it.off;
return *this;
}
inline bool operator==( const DataApapterIterator & it ) const {
return this->parent == it.parent && this->off == it.off;
}
inline bool operator!=( const DataApapterIterator & it ) const {
return this->parent != it.parent || this->off != it.off;
}
inline reference operator*() {
return this->parent->at( this->off );
}
inline reference operator[]( difference_type n ) {
return *( *this + n );
}
inline pointer operator->() {
return &( this->parent->at( this->off ) );
}
//VERY IMPORTANT for converting and comparing to const_iterators
inline operator typename parent_type::const_iterator() const {
return typename parent_type::const_iterator( this->parent ) + this->off;
}
#define DATA_ADAPTER_ITERATOR_UNARY_OP(op) \
inline DataApapterIterator& operator op() { \
this->off op; \
return *this; \
} \
inline DataApapterIterator operator op( int ) { \
DataApapterIterator tmp( *this ); \
this->off op; \
return tmp; \
}
DATA_ADAPTER_ITERATOR_UNARY_OP( ++ )
DATA_ADAPTER_ITERATOR_UNARY_OP( -- )
inline DataApapterIterator operator+( const DataApapterIterator & it ) const {
DataApapterIterator tmp( *this );
tmp.off += it.off;
return tmp;
}
inline DataApapterIterator operator+( difference_type n ) const {
DataApapterIterator tmp( *this );
tmp.off += n;
return tmp;
}
inline DataApapterIterator & operator +=( const DataApapterIterator & it ) {
this->off += it.off;
return *this;
}
inline DataApapterIterator & operator +=( difference_type n ) {
this->off += n;
return *this;
}
inline difference_type operator-( const DataApapterIterator & it ) const {
return this->off - it.off;
}
inline DataApapterIterator operator-( difference_type n ) const {
DataApapterIterator tmp( *this );
tmp.off -= n;
return tmp;
}
inline DataApapterIterator & operator -=( const DataApapterIterator & it ) {
this->off -= it.off;
return *this;
}
inline DataApapterIterator & operator -=( difference_type n ) {
this->off -= n;
return *this;
}
#define DATA_ADAPTER_ITERATOR_COMP_OP(op) \
inline bool operator op( const DataApapterIterator& it ) const { \
return this->off op it.off; \
}
DATA_ADAPTER_ITERATOR_COMP_OP( < )
DATA_ADAPTER_ITERATOR_COMP_OP( > )
DATA_ADAPTER_ITERATOR_COMP_OP( <= )
DATA_ADAPTER_ITERATOR_COMP_OP( >= )
};
template <typename T, size_t N>
class DataApapterIterator<const T[N]> : public std::iterator<std::random_access_iterator_tag, T, size_t> {
public:
typedef std::iterator<std::random_access_iterator_tag, T> iterator_traits;
typedef typename iterator_traits::iterator_category iterator_category;
typedef typename iterator_traits::value_type value_type;
typedef typename iterator_traits::difference_type difference_type;
typedef typename iterator_traits::pointer pointer;
typedef typename iterator_traits::reference reference;
typedef DataAdapter<T[N]> parent_type;
friend class DataAdapter<T[N]>;
private:
//Keep a pointer to the parent
const parent_type * parent;
difference_type off;
public:
DataApapterIterator() : parent( NULL ), off( 0 ) {}
DataApapterIterator( const parent_type * x, difference_type ioff = 0 ) : parent( x ), off( ioff ) {}
DataApapterIterator( const parent_type & x, difference_type ioff = 0 ) : parent( &x ), off( ioff ) {}
DataApapterIterator( const DataApapterIterator & it ) : parent( it.parent ), off( it.off ) {}
inline DataApapterIterator & operator=( const DataApapterIterator & it ) {
this->parent = it.parent;
this->off = it.off;
return *this;
}
inline bool operator==( const DataApapterIterator & it ) const {
return this->parent == it.parent && this->off == it.off;
}
inline bool operator!=( const DataApapterIterator & it ) const {
return this->parent != it.parent || this->off != it.off;
}
inline value_type operator*() {
return this->parent->at( this->off );
}
inline value_type operator[]( difference_type n ) {
return *( *this + n );
}
DATA_ADAPTER_ITERATOR_UNARY_OP( ++ )
DATA_ADAPTER_ITERATOR_UNARY_OP( -- )
inline DataApapterIterator operator+( const DataApapterIterator & it ) const {
DataApapterIterator tmp( *this );
tmp.off += it.off;
return tmp;
}
inline DataApapterIterator operator+( difference_type n ) const {
DataApapterIterator tmp( *this );
tmp.off += n;
return tmp;
}
inline DataApapterIterator & operator +=( const DataApapterIterator & it ) {
this->off += it.off;
return *this;
}
inline DataApapterIterator & operator +=( difference_type n ) {
this->off += n;
return *this;
}
inline difference_type operator-( const DataApapterIterator & it ) const {
return this->off - it.off;
}
inline DataApapterIterator operator-( difference_type n ) const {
DataApapterIterator tmp( *this );
tmp.off -= n;
return tmp;
}
inline DataApapterIterator & operator -=( const DataApapterIterator & it ) {
this->off -= it.off;
return *this;
}
inline DataApapterIterator & operator -=( difference_type n ) {
this->off -= n;
return *this;
}
DATA_ADAPTER_ITERATOR_COMP_OP( < )
DATA_ADAPTER_ITERATOR_COMP_OP( > )
DATA_ADAPTER_ITERATOR_COMP_OP( <= )
DATA_ADAPTER_ITERATOR_COMP_OP( >= )
};
#undef DATA_ADAPTER_ITERATOR_UNARY_OP
#undef DATA_ADAPTER_ITERATOR_BINARY_OP
#undef DATA_ADAPTER_ITERATOR_COMP_OP
#endif // DATA_ADAPTER_ARRAY_HPP_INCLUDED
<commit_msg>Fixed relative file location<commit_after>#ifndef DATA_ADAPTER_ARRAY_HPP_INCLUDED
#define DATA_ADAPTER_ARRAY_HPP_INCLUDED
#include "../data_adapter.hpp"
#ifndef NDEBUG
#include <iostream>
using std::cout;
using std::endl;
#endif // NDEBUG
template <typename T, size_t N>
class DataAdapter<T[N]> : public DataAdapterBase<T[N], T, DataAdapter<T[N]> > {
public:
typedef DataAdapterBase<T[N], T, DataAdapter<T[N]> > _Base;
typedef typename _Base::value_type value_type;
typedef typename _Base::element_type element_type;
typedef typename _Base::pointer_type pointer_type;
typedef typename _Base::size_type size_type;
typedef typename _Base::iterator iterator;
typedef typename _Base::const_iterator const_iterator;
typedef typename _Base::reverse_iterator reverse_iterator;
typedef typename _Base::const_reverse_iterator const_reverse_iterator;
private:
value_type data;
static size_type data_size;
size_type used_length;
public:
DataAdapter() {
this->clear();
}
explicit DataAdapter( const value_type & val ) {
this->assign( val, val + N );
}
inline size_type capacity() const {
return DataAdapter::data_size;
}
inline size_type length() const {
return this->used_length;
}
void push_back( const element_type & n ) {
//uses the previous length returned by resize to dictate the position of the last element
this->at( this->resize( this->length() + 1 ) ) = n;
}
void push_front( const element_type & val ) {
if( !this->full() ) {
iterator first = this->begin();
iterator last = this->end();
this->resize( this->length() + 1 );
std::copy_backward( first, last, this->end() );
*first = val;
} else {
throw std::out_of_range( "DataAdapter::push_front: Out of Range" );
}
}
element_type pop_back() {
if( !this->empty() ) {
return this->data[--this->used_length];
} else {
return element_type();
}
}
element_type pop_front() {
element_type ret = this->front();
std::copy( this->begin() + 1, this->end() - 1, this->begin() );
this->resize( this->length() - 1 );
return ret;
}
inline element_type & at( size_type n ) {
return this->data[n];
}
inline const element_type at( size_type n ) const {
return this->data[n];
}
inline element_type & at( iterator it ) {
return this->at( it.off );
}
inline const element_type at( const_iterator it ) const {
return this->at( it.off );
}
inline element_type front() const {
return this->at( 0 );
}
inline element_type & front() {
return this->at( 0 );
}
element_type back() const {
if( !this->empty() ) {
return this->at( this->end() - 1 );
} else {
return this->front();
}
}
element_type & back() {
if( !this->empty() ) {
return this->data[this->used_length - 1];
} else {
return this->front();
}
}
iterator sorted_insert( const element_type & n ) {
//First, add it to the end
this->push_back( n );
//Then insert it into the proper place
for( size_type i = this->length() - 1; i > 0; --i ) {
if( this->at( i ) < this->at( i - 1 ) ) {
std::swap( this->at( i ), this->at( i - 1 ) );
} else {
return this->begin() + i;
}
}
return this->begin();
}
//single element
inline iterator insert( iterator pos, const element_type & val ) {
return this->insert( pos, 1, val );
}
//fill
iterator insert( iterator pos, size_type n, const element_type & val ) {
if( n != 0 ) {
if( pos < this->end() + 1 && this->length() + n <= this->capacity() ) {
iterator first = this->begin() + pos;
iterator last = this->end() - n;
this->resize( this->length() + n );
std::copy_backward( first, last, this->end() );
std::fill( first, first + n, val );
return first;
} else {
throw std::out_of_range( "DataAdapter::insert(fill): Out of Range" );
}
} else {
return this->end();
}
//Otherwise there is nothing to insert
}
//range
iterator insert( iterator pos, const_iterator first, const_iterator last ) {
if( first != last && first < last ) {
if( this->length() + ( last - first ) <= this->capacity() ) {
size_type diff = last - first;
iterator f = this->begin() + pos;
iterator l = this->end() - diff;
this->resize( this->length() + diff );
std::copy_backward( f, l, this->end() );
std::copy( first, last, f );
return f;
} else {
throw std::out_of_range( "DataAdapter::insert(range): Out of Range" );
}
} else {
return this->end();
}
}
//Clear is unique in that is zeros the memory just in case
void clear() {
std::fill( this->data, this->data + this->capacity(), element_type( 0x0 ) );
this->used_length = 0;
}
inline size_type resize( size_type n ) {
return this->resize( n, element_type( 0x0 ) );
}
size_type resize( size_type n, const element_type & v ) {
if( n <= this->capacity() ) {
size_type ret = this->length();
if( n < this->length() ) {
this->used_length = n;
} else {
size_type ol = this->used_length;
this->used_length = n;
std::fill( this->begin() + n, this->end(), v );
}
return ret;
} else {
throw std::out_of_range( "DataAdapter::resize: Out of Range" );
}
}
inline iterator erase( iterator pos ) {
return this->erase( pos, pos + 1 );
}
iterator erase( iterator first, iterator last ) {
size_type diff = ( last - first );
if( last <= this->end() && diff <= this->length() ) {
iterator f = this->begin() + first;
iterator l = this->begin() + last;
std::copy( l, this->end(), f );
this->resize( this->length() - diff );
return f;
} else {
throw std::out_of_range( "DataAdapter::erase(range): Out of Range" );
}
}
};
template <typename T, size_t N>
typename DataAdapter<T[N]>::size_type DataAdapter<T[N]>::data_size =
sizeof( DataAdapter<T[N]>::value_type ) / sizeof( DataAdapter<T[N]>::element_type );
template <typename T, size_t N>
class DataApapterIterator<T[N]>
: public std::iterator<std::random_access_iterator_tag, T, size_t> {
public:
typedef std::iterator<std::random_access_iterator_tag, T> iterator_traits;
typedef typename iterator_traits::iterator_category iterator_category;
typedef typename iterator_traits::value_type value_type;
typedef typename iterator_traits::difference_type difference_type;
typedef typename iterator_traits::pointer pointer;
typedef typename iterator_traits::reference reference;
typedef DataAdapter<T[N]> parent_type;
friend class DataAdapter<T[N]>;
private:
//Keep a pointer to the parent
parent_type * parent;
difference_type off;
public:
DataApapterIterator() : parent( NULL ), off( 0 ) {}
DataApapterIterator( parent_type * x, difference_type ioff = 0 ) : parent( x ), off( ioff ) {}
DataApapterIterator( parent_type & x, difference_type ioff = 0 ) : parent( &x ), off( ioff ) {}
DataApapterIterator( const DataApapterIterator & it ) : parent( it.parent ), off( it.off ) {}
inline DataApapterIterator & operator=( const DataApapterIterator & it ) {
this->parent = it.parent;
this->off = it.off;
return *this;
}
inline bool operator==( const DataApapterIterator & it ) const {
return this->parent == it.parent && this->off == it.off;
}
inline bool operator!=( const DataApapterIterator & it ) const {
return this->parent != it.parent || this->off != it.off;
}
inline reference operator*() {
return this->parent->at( this->off );
}
inline reference operator[]( difference_type n ) {
return *( *this + n );
}
inline pointer operator->() {
return &( this->parent->at( this->off ) );
}
//VERY IMPORTANT for converting and comparing to const_iterators
inline operator typename parent_type::const_iterator() const {
return typename parent_type::const_iterator( this->parent ) + this->off;
}
#define DATA_ADAPTER_ITERATOR_UNARY_OP(op) \
inline DataApapterIterator& operator op() { \
this->off op; \
return *this; \
} \
inline DataApapterIterator operator op( int ) { \
DataApapterIterator tmp( *this ); \
this->off op; \
return tmp; \
}
DATA_ADAPTER_ITERATOR_UNARY_OP( ++ )
DATA_ADAPTER_ITERATOR_UNARY_OP( -- )
inline DataApapterIterator operator+( const DataApapterIterator & it ) const {
DataApapterIterator tmp( *this );
tmp.off += it.off;
return tmp;
}
inline DataApapterIterator operator+( difference_type n ) const {
DataApapterIterator tmp( *this );
tmp.off += n;
return tmp;
}
inline DataApapterIterator & operator +=( const DataApapterIterator & it ) {
this->off += it.off;
return *this;
}
inline DataApapterIterator & operator +=( difference_type n ) {
this->off += n;
return *this;
}
inline difference_type operator-( const DataApapterIterator & it ) const {
return this->off - it.off;
}
inline DataApapterIterator operator-( difference_type n ) const {
DataApapterIterator tmp( *this );
tmp.off -= n;
return tmp;
}
inline DataApapterIterator & operator -=( const DataApapterIterator & it ) {
this->off -= it.off;
return *this;
}
inline DataApapterIterator & operator -=( difference_type n ) {
this->off -= n;
return *this;
}
#define DATA_ADAPTER_ITERATOR_COMP_OP(op) \
inline bool operator op( const DataApapterIterator& it ) const { \
return this->off op it.off; \
}
DATA_ADAPTER_ITERATOR_COMP_OP( < )
DATA_ADAPTER_ITERATOR_COMP_OP( > )
DATA_ADAPTER_ITERATOR_COMP_OP( <= )
DATA_ADAPTER_ITERATOR_COMP_OP( >= )
};
template <typename T, size_t N>
class DataApapterIterator<const T[N]> : public std::iterator<std::random_access_iterator_tag, T, size_t> {
public:
typedef std::iterator<std::random_access_iterator_tag, T> iterator_traits;
typedef typename iterator_traits::iterator_category iterator_category;
typedef typename iterator_traits::value_type value_type;
typedef typename iterator_traits::difference_type difference_type;
typedef typename iterator_traits::pointer pointer;
typedef typename iterator_traits::reference reference;
typedef DataAdapter<T[N]> parent_type;
friend class DataAdapter<T[N]>;
private:
//Keep a pointer to the parent
const parent_type * parent;
difference_type off;
public:
DataApapterIterator() : parent( NULL ), off( 0 ) {}
DataApapterIterator( const parent_type * x, difference_type ioff = 0 ) : parent( x ), off( ioff ) {}
DataApapterIterator( const parent_type & x, difference_type ioff = 0 ) : parent( &x ), off( ioff ) {}
DataApapterIterator( const DataApapterIterator & it ) : parent( it.parent ), off( it.off ) {}
inline DataApapterIterator & operator=( const DataApapterIterator & it ) {
this->parent = it.parent;
this->off = it.off;
return *this;
}
inline bool operator==( const DataApapterIterator & it ) const {
return this->parent == it.parent && this->off == it.off;
}
inline bool operator!=( const DataApapterIterator & it ) const {
return this->parent != it.parent || this->off != it.off;
}
inline value_type operator*() {
return this->parent->at( this->off );
}
inline value_type operator[]( difference_type n ) {
return *( *this + n );
}
DATA_ADAPTER_ITERATOR_UNARY_OP( ++ )
DATA_ADAPTER_ITERATOR_UNARY_OP( -- )
inline DataApapterIterator operator+( const DataApapterIterator & it ) const {
DataApapterIterator tmp( *this );
tmp.off += it.off;
return tmp;
}
inline DataApapterIterator operator+( difference_type n ) const {
DataApapterIterator tmp( *this );
tmp.off += n;
return tmp;
}
inline DataApapterIterator & operator +=( const DataApapterIterator & it ) {
this->off += it.off;
return *this;
}
inline DataApapterIterator & operator +=( difference_type n ) {
this->off += n;
return *this;
}
inline difference_type operator-( const DataApapterIterator & it ) const {
return this->off - it.off;
}
inline DataApapterIterator operator-( difference_type n ) const {
DataApapterIterator tmp( *this );
tmp.off -= n;
return tmp;
}
inline DataApapterIterator & operator -=( const DataApapterIterator & it ) {
this->off -= it.off;
return *this;
}
inline DataApapterIterator & operator -=( difference_type n ) {
this->off -= n;
return *this;
}
DATA_ADAPTER_ITERATOR_COMP_OP( < )
DATA_ADAPTER_ITERATOR_COMP_OP( > )
DATA_ADAPTER_ITERATOR_COMP_OP( <= )
DATA_ADAPTER_ITERATOR_COMP_OP( >= )
};
#undef DATA_ADAPTER_ITERATOR_UNARY_OP
#undef DATA_ADAPTER_ITERATOR_BINARY_OP
#undef DATA_ADAPTER_ITERATOR_COMP_OP
#endif // DATA_ADAPTER_ARRAY_HPP_INCLUDED
<|endoftext|> |
<commit_before>/**************************************************************************
** This file is part of LiteIDE
**
** Copyright (c) 2011-2015 LiteIDE Team. All rights reserved.
**
** 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.
**
** In addition, as a special exception, that plugins developed for LiteIDE,
** are allowed to remain closed sourced and can be distributed under any license .
** These rights are included in the file LGPL_EXCEPTION.txt in this package.
**
**************************************************************************/
// Module: liteeditorfile.cpp
// Creator: visualfc <visualfc@gmail.com>
#include "liteeditorfile.h"
#include "liteeditor_global.h"
#include <QFile>
#include <QTextDocument>
#include <QTextCodec>
#include <QTextStream>
#include <QMessageBox>
#include <QDir>
#include <QDebug>
//lite_memory_check_begin
#if defined(WIN32) && defined(_MSC_VER) && defined(_DEBUG)
#define _CRTDBG_MAP_ALLOC
#include <stdlib.h>
#include <crtdbg.h>
#define DEBUG_NEW new( _NORMAL_BLOCK, __FILE__, __LINE__ )
#define new DEBUG_NEW
#endif
//lite_memory_check_end
LiteEditorFile::LiteEditorFile(LiteApi::IApplication *app, QObject *parent)
: LiteApi::IFile(parent),
m_liteApp(app)
{
//m_codec = QTextCodec::codecForLocale();
m_codec = QTextCodec::codecForName("utf-8");
m_hasDecodingError = false;
m_bReadOnly = false;
}
QString LiteEditorFile::filePath() const
{
return m_fileName;
}
bool LiteEditorFile::isReadOnly() const
{
if (m_hasDecodingError) {
return true;
}
return m_bReadOnly;
}
bool LiteEditorFile::save(const QString &fileName)
{
QFile file(fileName);
if (!file.open(QFile::WriteOnly | QIODevice::Truncate)) {
return false;
}
m_fileName = fileName;
QString text = m_document->toPlainText();
if (m_lineTerminatorMode == CRLFLineTerminator)
text.replace(QLatin1Char('\n'), QLatin1String("\r\n"));
if (m_codec) {
file.write(m_codec->fromUnicode(text));
} else {
file.write(text.toLocal8Bit());
}
m_document->setModified(false);
return true;
}
bool LiteEditorFile::reloadByCodec(const QString &codecName)
{
setTextCodec(codecName);
return open(m_fileName,m_mimeType,false);
}
bool LiteEditorFile::reload()
{
return open(m_fileName,m_mimeType);
}
QString LiteEditorFile::mimeType() const
{
return m_mimeType;
}
void LiteEditorFile::setDocument(QTextDocument *document)
{
m_document = document;
}
void LiteEditorFile::setTextCodec(const QString &name)
{
QTextCodec *codec = QTextCodec::codecForName(name.toLatin1());
if (codec) {
m_codec = codec;
}
}
QString LiteEditorFile::textCodec() const
{
return m_codec->name();
}
QTextDocument *LiteEditorFile::document()
{
return m_document;
}
bool LiteEditorFile::open(const QString &fileName, const QString &mimeType, bool bCheckCodec)
{
QFile file(fileName);
if (!file.open(QFile::ReadOnly)) {
return false;
}
const QFileInfo fi(fileName);
m_bReadOnly = !fi.isWritable();
m_mimeType = mimeType;
m_fileName = fileName;
QByteArray buf = file.readAll();
m_hasDecodingError = false;
if (bCheckCodec) {
if (mimeType == "text/html" || mimeType == "text/xml") {
m_codec = QTextCodec::codecForHtml(buf,QTextCodec::codecForName("utf-8"));
} else {
LiteApi::IMimeType *im = m_liteApp->mimeTypeManager()->findMimeType(mimeType);
if (im) {
QString codecName = im->codec();
if (!codecName.isEmpty()) {
m_codec = QTextCodec::codecForName(codecName.toLatin1());
}
}
int bytesRead = buf.size();
QTextCodec *codec = m_codec;
// code taken from qtextstream
if (bytesRead >= 4 && ((uchar(buf[0]) == 0xff && uchar(buf[1]) == 0xfe && uchar(buf[2]) == 0 && uchar(buf[3]) == 0)
|| (uchar(buf[0]) == 0 && uchar(buf[1]) == 0 && uchar(buf[2]) == 0xfe && uchar(buf[3]) == 0xff))) {
codec = QTextCodec::codecForName("UTF-32");
} else if (bytesRead >= 2 && ((uchar(buf[0]) == 0xff && uchar(buf[1]) == 0xfe)
|| (uchar(buf[0]) == 0xfe && uchar(buf[1]) == 0xff))) {
codec = QTextCodec::codecForName("UTF-16");
} else if (bytesRead >= 3 && uchar(buf[0]) == 0xef && uchar(buf[1]) == 0xbb && uchar(buf[2])== 0xbf) {
codec = QTextCodec::codecForName("UTF-8");
} else if (!codec) {
codec = QTextCodec::codecForLocale();
}
// end code taken from qtextstream
m_codec = codec;
}
}
QTextCodec::ConverterState state;
QString text = m_codec->toUnicode(buf,buf.size(),&state);
if (state.invalidChars > 0 || state.remainingChars > 0) {
m_hasDecodingError = true;
}
//qDebug() << state.invalidChars << state.remainingChars;
/*
QByteArray verifyBuf = m_codec->fromUnicode(text); // slow
// the minSize trick lets us ignore unicode headers
int minSize = qMin(verifyBuf.size(), buf.size());
m_hasDecodingError = (minSize < buf.size()- 4
|| memcmp(verifyBuf.constData() + verifyBuf.size() - minSize,
buf.constData() + buf.size() - minSize, minSize));
*/
/*
if (text.length()*2+4 < buf.length()) {
m_hasDecodingError = true;
}
*/
int lf = text.indexOf('\n');
if (lf < 0) {
m_lineTerminatorMode = NativeLineTerminator;
} else if (lf == 0) {
m_lineTerminatorMode = LFLineTerminator;
} else {
lf = text.indexOf(QRegExp("[^\r]\n"),lf-1);
if (lf >= 0) {
m_lineTerminatorMode = LFLineTerminator;
} else {
m_lineTerminatorMode = CRLFLineTerminator;
}
}
bool noprintCheck = m_liteApp->settings()->value(EDITOR_NOPRINTCHECK,true).toBool();
if (noprintCheck) {
for (int i = 0; i < text.length(); i++) {
if (!text[i].isPrint() && !text[i].isSpace() && text[i] != '\r' && text[i] != '\n') {
text[i] = '.';
m_hasDecodingError = true;
}
}
}
m_document->setPlainText(text);
return true;
}
bool LiteEditorFile::setLineEndUnix(bool b)
{
if (this->isLineEndUnix() == b) {
return false;
}
QString text = m_document->toPlainText();
if (b) {
m_lineTerminatorMode = LFLineTerminator;
text.replace("\r\n","\n");
} else {
m_lineTerminatorMode = CRLFLineTerminator;
text.replace("\n","\r\n");
}
m_document->setPlainText(text);
return true;
}
bool LiteEditorFile::isLineEndUnix() const
{
return m_lineTerminatorMode == LFLineTerminator;
}
bool LiteEditorFile::isLineEndWindow() const
{
return m_lineTerminatorMode == CRLFLineTerminator;
}
bool LiteEditorFile::create(const QString &contents, const QString &mimeType)
{
m_mimeType = mimeType;
m_lineTerminatorMode = LFLineTerminator;
m_document->setPlainText(contents);
return true;
}
bool LiteEditorFile::open(const QString &fileName, const QString &mimeType)
{
return open(fileName,mimeType,true);
}
<commit_msg>text mimetype not use printcheck<commit_after>/**************************************************************************
** This file is part of LiteIDE
**
** Copyright (c) 2011-2015 LiteIDE Team. All rights reserved.
**
** 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.
**
** In addition, as a special exception, that plugins developed for LiteIDE,
** are allowed to remain closed sourced and can be distributed under any license .
** These rights are included in the file LGPL_EXCEPTION.txt in this package.
**
**************************************************************************/
// Module: liteeditorfile.cpp
// Creator: visualfc <visualfc@gmail.com>
#include "liteeditorfile.h"
#include "liteeditor_global.h"
#include <QFile>
#include <QTextDocument>
#include <QTextCodec>
#include <QTextStream>
#include <QMessageBox>
#include <QDir>
#include <QDebug>
//lite_memory_check_begin
#if defined(WIN32) && defined(_MSC_VER) && defined(_DEBUG)
#define _CRTDBG_MAP_ALLOC
#include <stdlib.h>
#include <crtdbg.h>
#define DEBUG_NEW new( _NORMAL_BLOCK, __FILE__, __LINE__ )
#define new DEBUG_NEW
#endif
//lite_memory_check_end
LiteEditorFile::LiteEditorFile(LiteApi::IApplication *app, QObject *parent)
: LiteApi::IFile(parent),
m_liteApp(app)
{
//m_codec = QTextCodec::codecForLocale();
m_codec = QTextCodec::codecForName("utf-8");
m_hasDecodingError = false;
m_bReadOnly = false;
}
QString LiteEditorFile::filePath() const
{
return m_fileName;
}
bool LiteEditorFile::isReadOnly() const
{
if (m_hasDecodingError) {
return true;
}
return m_bReadOnly;
}
bool LiteEditorFile::save(const QString &fileName)
{
QFile file(fileName);
if (!file.open(QFile::WriteOnly | QIODevice::Truncate)) {
return false;
}
m_fileName = fileName;
QString text = m_document->toPlainText();
if (m_lineTerminatorMode == CRLFLineTerminator)
text.replace(QLatin1Char('\n'), QLatin1String("\r\n"));
if (m_codec) {
file.write(m_codec->fromUnicode(text));
} else {
file.write(text.toLocal8Bit());
}
m_document->setModified(false);
return true;
}
bool LiteEditorFile::reloadByCodec(const QString &codecName)
{
setTextCodec(codecName);
return open(m_fileName,m_mimeType,false);
}
bool LiteEditorFile::reload()
{
return open(m_fileName,m_mimeType);
}
QString LiteEditorFile::mimeType() const
{
return m_mimeType;
}
void LiteEditorFile::setDocument(QTextDocument *document)
{
m_document = document;
}
void LiteEditorFile::setTextCodec(const QString &name)
{
QTextCodec *codec = QTextCodec::codecForName(name.toLatin1());
if (codec) {
m_codec = codec;
}
}
QString LiteEditorFile::textCodec() const
{
return m_codec->name();
}
QTextDocument *LiteEditorFile::document()
{
return m_document;
}
bool LiteEditorFile::open(const QString &fileName, const QString &mimeType, bool bCheckCodec)
{
QFile file(fileName);
if (!file.open(QFile::ReadOnly)) {
return false;
}
const QFileInfo fi(fileName);
m_bReadOnly = !fi.isWritable();
m_mimeType = mimeType;
m_fileName = fileName;
QByteArray buf = file.readAll();
m_hasDecodingError = false;
if (bCheckCodec) {
if (mimeType == "text/html" || mimeType == "text/xml") {
m_codec = QTextCodec::codecForHtml(buf,QTextCodec::codecForName("utf-8"));
} else {
LiteApi::IMimeType *im = m_liteApp->mimeTypeManager()->findMimeType(mimeType);
if (im) {
QString codecName = im->codec();
if (!codecName.isEmpty()) {
m_codec = QTextCodec::codecForName(codecName.toLatin1());
}
}
int bytesRead = buf.size();
QTextCodec *codec = m_codec;
// code taken from qtextstream
if (bytesRead >= 4 && ((uchar(buf[0]) == 0xff && uchar(buf[1]) == 0xfe && uchar(buf[2]) == 0 && uchar(buf[3]) == 0)
|| (uchar(buf[0]) == 0 && uchar(buf[1]) == 0 && uchar(buf[2]) == 0xfe && uchar(buf[3]) == 0xff))) {
codec = QTextCodec::codecForName("UTF-32");
} else if (bytesRead >= 2 && ((uchar(buf[0]) == 0xff && uchar(buf[1]) == 0xfe)
|| (uchar(buf[0]) == 0xfe && uchar(buf[1]) == 0xff))) {
codec = QTextCodec::codecForName("UTF-16");
} else if (bytesRead >= 3 && uchar(buf[0]) == 0xef && uchar(buf[1]) == 0xbb && uchar(buf[2])== 0xbf) {
codec = QTextCodec::codecForName("UTF-8");
} else if (!codec) {
codec = QTextCodec::codecForLocale();
}
// end code taken from qtextstream
m_codec = codec;
}
}
QTextCodec::ConverterState state;
QString text = m_codec->toUnicode(buf,buf.size(),&state);
if (state.invalidChars > 0 || state.remainingChars > 0) {
m_hasDecodingError = true;
}
//qDebug() << state.invalidChars << state.remainingChars;
/*
QByteArray verifyBuf = m_codec->fromUnicode(text); // slow
// the minSize trick lets us ignore unicode headers
int minSize = qMin(verifyBuf.size(), buf.size());
m_hasDecodingError = (minSize < buf.size()- 4
|| memcmp(verifyBuf.constData() + verifyBuf.size() - minSize,
buf.constData() + buf.size() - minSize, minSize));
*/
/*
if (text.length()*2+4 < buf.length()) {
m_hasDecodingError = true;
}
*/
int lf = text.indexOf('\n');
if (lf < 0) {
m_lineTerminatorMode = NativeLineTerminator;
} else if (lf == 0) {
m_lineTerminatorMode = LFLineTerminator;
} else {
lf = text.indexOf(QRegExp("[^\r]\n"),lf-1);
if (lf >= 0) {
m_lineTerminatorMode = LFLineTerminator;
} else {
m_lineTerminatorMode = CRLFLineTerminator;
}
}
bool noprintCheck = m_liteApp->settings()->value(EDITOR_NOPRINTCHECK,true).toBool();
if (noprintCheck && !LiteApi::mimeIsText(mimeType)) {
for (int i = 0; i < text.length(); i++) {
if (!text[i].isPrint() && !text[i].isSpace() && text[i] != '\r' && text[i] != '\n') {
text[i] = '.';
m_hasDecodingError = true;
}
}
}
m_document->setPlainText(text);
return true;
}
bool LiteEditorFile::setLineEndUnix(bool b)
{
if (this->isLineEndUnix() == b) {
return false;
}
QString text = m_document->toPlainText();
if (b) {
m_lineTerminatorMode = LFLineTerminator;
text.replace("\r\n","\n");
} else {
m_lineTerminatorMode = CRLFLineTerminator;
text.replace("\n","\r\n");
}
m_document->setPlainText(text);
return true;
}
bool LiteEditorFile::isLineEndUnix() const
{
return m_lineTerminatorMode == LFLineTerminator;
}
bool LiteEditorFile::isLineEndWindow() const
{
return m_lineTerminatorMode == CRLFLineTerminator;
}
bool LiteEditorFile::create(const QString &contents, const QString &mimeType)
{
m_mimeType = mimeType;
m_lineTerminatorMode = LFLineTerminator;
m_document->setPlainText(contents);
return true;
}
bool LiteEditorFile::open(const QString &fileName, const QString &mimeType)
{
return open(fileName,mimeType,true);
}
<|endoftext|> |
<commit_before>/*
Copyright (c) 2003-2012, Arvid Norberg
All rights reserved.
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions
are met:
* Redistributions of source code must retain the above copyright
notice, this list of conditions and the following disclaimer.
* Redistributions in binary form must reproduce the above copyright
notice, this list of conditions and the following disclaimer in
the documentation and/or other materials provided with the distribution.
* Neither the name of the author nor the names of its
contributors may be used to endorse or promote products derived
from this software without specific prior written permission.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE
LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
POSSIBILITY OF SUCH DAMAGE.
*/
#include "libtorrent/pch.hpp"
#include <vector>
#include <cctype>
#include <boost/bind.hpp>
#include "libtorrent/tracker_manager.hpp"
#include "libtorrent/http_tracker_connection.hpp"
#include "libtorrent/udp_tracker_connection.hpp"
#include "libtorrent/aux_/session_impl.hpp"
using boost::tuples::make_tuple;
using boost::tuples::tuple;
namespace
{
enum
{
minimum_tracker_response_length = 3,
http_buffer_size = 2048
};
}
namespace libtorrent
{
timeout_handler::timeout_handler(io_service& ios)
: m_start_time(time_now_hires())
, m_read_time(m_start_time)
, m_timeout(ios)
, m_completion_timeout(0)
, m_read_timeout(0)
, m_abort(false)
{}
void timeout_handler::set_timeout(int completion_timeout, int read_timeout)
{
m_completion_timeout = completion_timeout;
m_read_timeout = read_timeout;
m_start_time = m_read_time = time_now_hires();
TORRENT_ASSERT(completion_timeout > 0 || read_timeout > 0);
if (m_abort) return;
int timeout = 0;
if (m_read_timeout > 0) timeout = m_read_timeout;
if (m_completion_timeout > 0)
{
timeout = timeout == 0
? m_completion_timeout
: (std::min)(m_completion_timeout, timeout);
}
#if defined TORRENT_ASIO_DEBUGGING
add_outstanding_async("timeout_handler::timeout_callback");
#endif
error_code ec;
m_timeout.expires_at(m_read_time + seconds(timeout), ec);
m_timeout.async_wait(boost::bind(
&timeout_handler::timeout_callback, self(), _1));
}
void timeout_handler::restart_read_timeout()
{
m_read_time = time_now_hires();
}
void timeout_handler::cancel()
{
m_abort = true;
m_completion_timeout = 0;
error_code ec;
m_timeout.cancel(ec);
}
void timeout_handler::timeout_callback(error_code const& error)
{
#if defined TORRENT_ASIO_DEBUGGING
complete_async("timeout_handler::timeout_callback");
#endif
if (m_abort) return;
ptime now = time_now_hires();
time_duration receive_timeout = now - m_read_time;
time_duration completion_timeout = now - m_start_time;
if ((m_read_timeout
&& m_read_timeout <= total_seconds(receive_timeout))
|| (m_completion_timeout
&& m_completion_timeout <= total_seconds(completion_timeout))
|| error)
{
on_timeout(error);
return;
}
int timeout = 0;
if (m_read_timeout > 0) timeout = m_read_timeout;
if (m_completion_timeout > 0)
{
timeout = timeout == 0
? m_completion_timeout - total_seconds(m_read_time - m_start_time)
: (std::min)(m_completion_timeout - total_seconds(m_read_time - m_start_time), timeout);
}
#if defined TORRENT_ASIO_DEBUGGING
add_outstanding_async("timeout_handler::timeout_callback");
#endif
error_code ec;
m_timeout.expires_at(m_read_time + seconds(timeout), ec);
m_timeout.async_wait(
boost::bind(&timeout_handler::timeout_callback, self(), _1));
}
tracker_connection::tracker_connection(
tracker_manager& man
, tracker_request const& req
, io_service& ios
, boost::weak_ptr<request_callback> r)
: timeout_handler(ios)
, m_requester(r)
, m_man(man)
, m_req(req)
{}
boost::shared_ptr<request_callback> tracker_connection::requester() const
{
return m_requester.lock();
}
void tracker_connection::fail(error_code const& ec, int code
, char const* msg, int interval, int min_interval)
{
boost::shared_ptr<request_callback> cb = requester();
if (cb) cb->tracker_request_error(m_req, code, ec, msg
, interval == 0 ? min_interval : interval);
close();
}
void tracker_connection::sent_bytes(int bytes)
{
m_man.sent_bytes(bytes);
}
void tracker_connection::received_bytes(int bytes)
{
m_man.received_bytes(bytes);
}
void tracker_connection::close()
{
cancel();
m_man.remove_request(this);
}
tracker_manager::~tracker_manager()
{
TORRENT_ASSERT(m_abort);
abort_all_requests(true);
}
void tracker_manager::sent_bytes(int bytes)
{
TORRENT_ASSERT(m_ses.is_network_thread());
m_ses.m_stat.sent_tracker_bytes(bytes);
}
void tracker_manager::received_bytes(int bytes)
{
TORRENT_ASSERT(m_ses.is_network_thread());
m_ses.m_stat.received_tracker_bytes(bytes);
}
void tracker_manager::remove_request(tracker_connection const* c)
{
mutex_t::scoped_lock l(m_mutex);
tracker_connections_t::iterator i = std::find(m_connections.begin()
, m_connections.end(), boost::intrusive_ptr<const tracker_connection>(c));
if (i == m_connections.end()) return;
m_connections.erase(i);
}
void tracker_manager::queue_request(
io_service& ios
, connection_queue& cc
, tracker_request req
, std::string const& auth
, boost::weak_ptr<request_callback> c)
{
mutex_t::scoped_lock l(m_mutex);
TORRENT_ASSERT(req.num_want >= 0);
TORRENT_ASSERT(!m_abort || req.event == tracker_request::stopped);
if (m_abort && req.event != tracker_request::stopped) return;
if (req.event == tracker_request::stopped)
req.num_want = 0;
TORRENT_ASSERT(!m_abort || req.event == tracker_request::stopped);
if (m_abort && req.event != tracker_request::stopped)
return;
std::string protocol = req.url.substr(0, req.url.find(':'));
boost::intrusive_ptr<tracker_connection> con;
#ifdef TORRENT_USE_OPENSSL
if (protocol == "http" || protocol == "https")
#else
if (protocol == "http")
#endif
{
con = new http_tracker_connection(
ios, cc, *this, req, c
, m_ses, m_proxy, auth
#if TORRENT_USE_I2P
, &m_ses.m_i2p_conn
#endif
);
}
else if (protocol == "udp")
{
con = new udp_tracker_connection(
ios, cc, *this, req , c, m_ses
, m_proxy);
}
else
{
// we need to post the error to avoid deadlock
if (boost::shared_ptr<request_callback> r = c.lock())
ios.post(boost::bind(&request_callback::tracker_request_error, r, req
, -1, error_code(errors::unsupported_url_protocol)
, "", 0));
return;
}
m_connections.push_back(con);
boost::shared_ptr<request_callback> cb = con->requester();
if (cb) cb->m_manager = this;
con->start();
}
bool tracker_manager::incoming_packet(error_code const& e
, udp::endpoint const& ep, char const* buf, int size)
{
// m_ses.m_stat.received_tracker_bytes(len + 28);
for (tracker_connections_t::iterator i = m_connections.begin();
i != m_connections.end();)
{
boost::intrusive_ptr<tracker_connection> p = *i;
++i;
// on_receive() may remove the tracker connection from the list
if (p->on_receive(e, ep, buf, size)) return true;
}
return false;
}
bool tracker_manager::incoming_packet(error_code const& e
, char const* hostname, char const* buf, int size)
{
// m_ses.m_stat.received_tracker_bytes(len + 28);
for (tracker_connections_t::iterator i = m_connections.begin();
i != m_connections.end();)
{
boost::intrusive_ptr<tracker_connection> p = *i;
++i;
// on_receive() may remove the tracker connection from the list
if (p->on_receive_hostname(e, hostname, buf, size)) return true;
}
return false;
}
void tracker_manager::abort_all_requests(bool all)
{
// removes all connections from m_connections
// except 'event=stopped'-requests
mutex_t::scoped_lock l(m_mutex);
m_abort = true;
tracker_connections_t close_connections;
for (tracker_connections_t::iterator i = m_connections.begin()
, end(m_connections.end()); i != end; ++i)
{
intrusive_ptr<tracker_connection> c = *i;
tracker_request const& req = c->tracker_req();
if (req.event == tracker_request::stopped && !all)
continue;
close_connections.push_back(c);
#if defined TORRENT_VERBOSE_LOGGING || defined TORRENT_LOGGING || defined TORRENT_ERROR_LOGGING
boost::shared_ptr<request_callback> rc = c->requester();
if (rc) rc->debug_log("aborting: %s", req.url.c_str());
#endif
}
l.unlock();
for (tracker_connections_t::iterator i = close_connections.begin()
, end(close_connections.end()); i != end; ++i)
{
(*i)->close();
}
}
bool tracker_manager::empty() const
{
mutex_t::scoped_lock l(m_mutex);
return m_connections.empty();
}
int tracker_manager::num_requests() const
{
mutex_t::scoped_lock l(m_mutex);
return m_connections.size();
}
}
<commit_msg>fix ambiguity invoking min<commit_after>/*
Copyright (c) 2003-2012, Arvid Norberg
All rights reserved.
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions
are met:
* Redistributions of source code must retain the above copyright
notice, this list of conditions and the following disclaimer.
* Redistributions in binary form must reproduce the above copyright
notice, this list of conditions and the following disclaimer in
the documentation and/or other materials provided with the distribution.
* Neither the name of the author nor the names of its
contributors may be used to endorse or promote products derived
from this software without specific prior written permission.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE
LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
POSSIBILITY OF SUCH DAMAGE.
*/
#include "libtorrent/pch.hpp"
#include <vector>
#include <cctype>
#include <boost/bind.hpp>
#include "libtorrent/tracker_manager.hpp"
#include "libtorrent/http_tracker_connection.hpp"
#include "libtorrent/udp_tracker_connection.hpp"
#include "libtorrent/aux_/session_impl.hpp"
using boost::tuples::make_tuple;
using boost::tuples::tuple;
namespace
{
enum
{
minimum_tracker_response_length = 3,
http_buffer_size = 2048
};
}
namespace libtorrent
{
timeout_handler::timeout_handler(io_service& ios)
: m_start_time(time_now_hires())
, m_read_time(m_start_time)
, m_timeout(ios)
, m_completion_timeout(0)
, m_read_timeout(0)
, m_abort(false)
{}
void timeout_handler::set_timeout(int completion_timeout, int read_timeout)
{
m_completion_timeout = completion_timeout;
m_read_timeout = read_timeout;
m_start_time = m_read_time = time_now_hires();
TORRENT_ASSERT(completion_timeout > 0 || read_timeout > 0);
if (m_abort) return;
int timeout = 0;
if (m_read_timeout > 0) timeout = m_read_timeout;
if (m_completion_timeout > 0)
{
timeout = timeout == 0
? m_completion_timeout
: (std::min)(m_completion_timeout, timeout);
}
#if defined TORRENT_ASIO_DEBUGGING
add_outstanding_async("timeout_handler::timeout_callback");
#endif
error_code ec;
m_timeout.expires_at(m_read_time + seconds(timeout), ec);
m_timeout.async_wait(boost::bind(
&timeout_handler::timeout_callback, self(), _1));
}
void timeout_handler::restart_read_timeout()
{
m_read_time = time_now_hires();
}
void timeout_handler::cancel()
{
m_abort = true;
m_completion_timeout = 0;
error_code ec;
m_timeout.cancel(ec);
}
void timeout_handler::timeout_callback(error_code const& error)
{
#if defined TORRENT_ASIO_DEBUGGING
complete_async("timeout_handler::timeout_callback");
#endif
if (m_abort) return;
ptime now = time_now_hires();
time_duration receive_timeout = now - m_read_time;
time_duration completion_timeout = now - m_start_time;
if ((m_read_timeout
&& m_read_timeout <= total_seconds(receive_timeout))
|| (m_completion_timeout
&& m_completion_timeout <= total_seconds(completion_timeout))
|| error)
{
on_timeout(error);
return;
}
int timeout = 0;
if (m_read_timeout > 0) timeout = m_read_timeout;
if (m_completion_timeout > 0)
{
timeout = timeout == 0
? m_completion_timeout - total_seconds(m_read_time - m_start_time)
: (std::min)(int(m_completion_timeout - total_seconds(m_read_time - m_start_time)), timeout);
}
#if defined TORRENT_ASIO_DEBUGGING
add_outstanding_async("timeout_handler::timeout_callback");
#endif
error_code ec;
m_timeout.expires_at(m_read_time + seconds(timeout), ec);
m_timeout.async_wait(
boost::bind(&timeout_handler::timeout_callback, self(), _1));
}
tracker_connection::tracker_connection(
tracker_manager& man
, tracker_request const& req
, io_service& ios
, boost::weak_ptr<request_callback> r)
: timeout_handler(ios)
, m_requester(r)
, m_man(man)
, m_req(req)
{}
boost::shared_ptr<request_callback> tracker_connection::requester() const
{
return m_requester.lock();
}
void tracker_connection::fail(error_code const& ec, int code
, char const* msg, int interval, int min_interval)
{
boost::shared_ptr<request_callback> cb = requester();
if (cb) cb->tracker_request_error(m_req, code, ec, msg
, interval == 0 ? min_interval : interval);
close();
}
void tracker_connection::sent_bytes(int bytes)
{
m_man.sent_bytes(bytes);
}
void tracker_connection::received_bytes(int bytes)
{
m_man.received_bytes(bytes);
}
void tracker_connection::close()
{
cancel();
m_man.remove_request(this);
}
tracker_manager::~tracker_manager()
{
TORRENT_ASSERT(m_abort);
abort_all_requests(true);
}
void tracker_manager::sent_bytes(int bytes)
{
TORRENT_ASSERT(m_ses.is_network_thread());
m_ses.m_stat.sent_tracker_bytes(bytes);
}
void tracker_manager::received_bytes(int bytes)
{
TORRENT_ASSERT(m_ses.is_network_thread());
m_ses.m_stat.received_tracker_bytes(bytes);
}
void tracker_manager::remove_request(tracker_connection const* c)
{
mutex_t::scoped_lock l(m_mutex);
tracker_connections_t::iterator i = std::find(m_connections.begin()
, m_connections.end(), boost::intrusive_ptr<const tracker_connection>(c));
if (i == m_connections.end()) return;
m_connections.erase(i);
}
void tracker_manager::queue_request(
io_service& ios
, connection_queue& cc
, tracker_request req
, std::string const& auth
, boost::weak_ptr<request_callback> c)
{
mutex_t::scoped_lock l(m_mutex);
TORRENT_ASSERT(req.num_want >= 0);
TORRENT_ASSERT(!m_abort || req.event == tracker_request::stopped);
if (m_abort && req.event != tracker_request::stopped) return;
if (req.event == tracker_request::stopped)
req.num_want = 0;
TORRENT_ASSERT(!m_abort || req.event == tracker_request::stopped);
if (m_abort && req.event != tracker_request::stopped)
return;
std::string protocol = req.url.substr(0, req.url.find(':'));
boost::intrusive_ptr<tracker_connection> con;
#ifdef TORRENT_USE_OPENSSL
if (protocol == "http" || protocol == "https")
#else
if (protocol == "http")
#endif
{
con = new http_tracker_connection(
ios, cc, *this, req, c
, m_ses, m_proxy, auth
#if TORRENT_USE_I2P
, &m_ses.m_i2p_conn
#endif
);
}
else if (protocol == "udp")
{
con = new udp_tracker_connection(
ios, cc, *this, req , c, m_ses
, m_proxy);
}
else
{
// we need to post the error to avoid deadlock
if (boost::shared_ptr<request_callback> r = c.lock())
ios.post(boost::bind(&request_callback::tracker_request_error, r, req
, -1, error_code(errors::unsupported_url_protocol)
, "", 0));
return;
}
m_connections.push_back(con);
boost::shared_ptr<request_callback> cb = con->requester();
if (cb) cb->m_manager = this;
con->start();
}
bool tracker_manager::incoming_packet(error_code const& e
, udp::endpoint const& ep, char const* buf, int size)
{
// m_ses.m_stat.received_tracker_bytes(len + 28);
for (tracker_connections_t::iterator i = m_connections.begin();
i != m_connections.end();)
{
boost::intrusive_ptr<tracker_connection> p = *i;
++i;
// on_receive() may remove the tracker connection from the list
if (p->on_receive(e, ep, buf, size)) return true;
}
return false;
}
bool tracker_manager::incoming_packet(error_code const& e
, char const* hostname, char const* buf, int size)
{
// m_ses.m_stat.received_tracker_bytes(len + 28);
for (tracker_connections_t::iterator i = m_connections.begin();
i != m_connections.end();)
{
boost::intrusive_ptr<tracker_connection> p = *i;
++i;
// on_receive() may remove the tracker connection from the list
if (p->on_receive_hostname(e, hostname, buf, size)) return true;
}
return false;
}
void tracker_manager::abort_all_requests(bool all)
{
// removes all connections from m_connections
// except 'event=stopped'-requests
mutex_t::scoped_lock l(m_mutex);
m_abort = true;
tracker_connections_t close_connections;
for (tracker_connections_t::iterator i = m_connections.begin()
, end(m_connections.end()); i != end; ++i)
{
intrusive_ptr<tracker_connection> c = *i;
tracker_request const& req = c->tracker_req();
if (req.event == tracker_request::stopped && !all)
continue;
close_connections.push_back(c);
#if defined TORRENT_VERBOSE_LOGGING || defined TORRENT_LOGGING || defined TORRENT_ERROR_LOGGING
boost::shared_ptr<request_callback> rc = c->requester();
if (rc) rc->debug_log("aborting: %s", req.url.c_str());
#endif
}
l.unlock();
for (tracker_connections_t::iterator i = close_connections.begin()
, end(close_connections.end()); i != end; ++i)
{
(*i)->close();
}
}
bool tracker_manager::empty() const
{
mutex_t::scoped_lock l(m_mutex);
return m_connections.empty();
}
int tracker_manager::num_requests() const
{
mutex_t::scoped_lock l(m_mutex);
return m_connections.size();
}
}
<|endoftext|> |
<commit_before>#include "NWUnitTest.h"
#ifdef __linux
#include "NanoWinMFCAfxStr.h"
#else
#include <windows.h>
#endif
NW_BEGIN_TEST_GROUP_SIMPLE(NanoWinMFCAfxStrTestGroup)
NW_TEST(NanoWinMFCAfxStrTestGroup, CStringReplaceSimpleTCHARTest)
{
CString cString("abc abc abc");
int n = cString.Replace('a', 'q');
NW_CHECK_EQUAL(3, n);
NW_CHECK_EQUAL_STRCMP(cString, "qbc qbc qbc");
n = cString.Replace('w', 'q');
NW_CHECK_EQUAL(0, n);
NW_CHECK_EQUAL_STRCMP(cString, "qbc qbc qbc");
}
NW_TEST(NanoWinMFCAfxStrTestGroup, CStringReplaceSimpleLPCTSTRTest)
{
CString cString("abc abc abc");
LPCTSTR strOld = "a";
LPCTSTR strNew = "q";
int n = cString.Replace(strOld, strNew);
NW_CHECK_EQUAL(3, n);
NW_CHECK_EQUAL_STRCMP(cString, "qbc qbc qbc");
}
NW_TEST(NanoWinMFCAfxStrTestGroup, CStringReplaceNullLPCTSTRTest)
{
CString cString("abc abc abc");
LPCTSTR strOld = "ab";
LPCTSTR strNew = NULL;
int n = cString.Replace(strOld, strNew);
NW_CHECK_EQUAL(3, n);
NW_CHECK_EQUAL_STRCMP(cString, "c c c");
}
NW_TEST(NanoWinMFCAfxStrTestGroup, CStringReplaceDifferentLengthLPCTSTRTest)
{
CString cString("abc abc abc qwe");
LPCTSTR strOld = "abc";
LPCTSTR strNew = "de";
int n = cString.Replace(strOld, strNew);
NW_CHECK_EQUAL(3, n);
NW_CHECK_EQUAL_STRCMP(cString, "de de de qwe");
}
NW_TEST(NanoWinMFCAfxStrTestGroup, CStringFindSimpleTCHARTest)
{
CString cString("abcdef");
int n = cString.Find('b');
NW_CHECK_EQUAL(1, n);
n = cString.Find('q');
NW_CHECK_EQUAL(-1, n);
}
NW_TEST(NanoWinMFCAfxStrTestGroup, CStringFindWithStartPosTCHARTest)
{
CString cString("abcdef abcdef");
int n = cString.Find('b', 4);
NW_CHECK_EQUAL(8, n);
n = cString.Find('q', 5);
NW_CHECK_EQUAL(-1, n);
}
NW_TEST(NanoWinMFCAfxStrTestGroup, CStringFindSimpleLPCTSTRTest)
{
CString cString("abcdef");
LPCTSTR sub = "b";
int n = cString.Find(sub);
NW_CHECK_EQUAL(1, n);
sub = "def";
n = cString.Find(sub);
NW_CHECK_EQUAL(3, n);
sub = "qqq";
n = cString.Find(sub);
NW_CHECK_EQUAL(-1, n);
}
NW_TEST(NanoWinMFCAfxStrTestGroup, CStringFindWithStartPosLPCTSTRTest)
{
CString cString("abcdef abcdef");
LPCTSTR sub = "b";
int n = cString.Find(sub, 4);
NW_CHECK_EQUAL(8, n);
sub = "def";
n = cString.Find(sub, 5);
NW_CHECK_EQUAL(10, n);
}
NW_TEST(NanoWinMFCAfxStrTestGroup, CStringReverseFindSimpleTCHARTest)
{
CString cString("abc abc abc");
int n = cString.ReverseFind('a');
NW_CHECK_EQUAL(8, n);
n = cString.ReverseFind('q');
NW_CHECK_EQUAL(-1, n);
}
NW_TEST(NanoWinMFCAfxStrTestGroup, CStringMakeLowerTest)
{
CString cString("aBcDeFZzZ");
cString.MakeLower();
NW_CHECK_EQUAL_STRCMP(cString, "abcdefzzz");
}
NW_TEST(NanoWinMFCAfxStrTestGroup, CStringMakeUpperTest)
{
CString cString("aBcDeFZzZ");
cString.MakeUpper();
NW_CHECK_EQUAL_STRCMP(cString, "ABCDEFZZZ");
}
NW_TEST(NanoWinMFCAfxStrTestGroup, CStringMakeReverseTest)
{
CString cString("abcdef");
cString.MakeReverse();
NW_CHECK_EQUAL_STRCMP(cString, "fedcba");
}
NW_TEST(NanoWinMFCAfxStrTestGroup, CStringRightTest)
{
CString cString("abcdef");
CString resStr = cString.Right(3);
NW_CHECK_EQUAL_STRCMP(resStr, "def");
}
NW_TEST(NanoWinMFCAfxStrTestGroup, CStringMidTest)
{
CString cString("abcdef");
CString resStr = cString.Mid(2);
NW_CHECK_EQUAL_STRCMP(resStr, "cdef");
}
/*
NW_TEST(NanoWinMFCAfxStrTestGroup, CStringMidWithCounterTest)
{
CString cString("abcdefabcdef");
CString resStr = cString.Mid(2, 5);
NW_CHECK_EQUAL_STRCMP("cdefa", resStr);
}
*/
/*
NW_TEST(NanoWinMFCAfxStrTestGroup, CStringLeftTest)
{
CString cString("abcdef");
CString resStr = cString.Left(3);
NW_CHECK_EQUAL_STRCMP("abc", resStr);
}
*/
NW_TEST(NanoWinMFCAfxStrTestGroup, CStringInsertTest)
{
CString cString("abcdef");
CString resStr = cString.Mid(2);
NW_CHECK_EQUAL_STRCMP(resStr, "cdef");
}
NW_END_TEST_GROUP()
// format<commit_msg>added set of tests for CString<commit_after>#include "NWUnitTest.h"
#ifdef __linux
#include "NanoWinMFCAfxStr.h"
#else
#include <windows.h>
#endif
NW_BEGIN_TEST_GROUP_SIMPLE(NanoWinMFCAfxStrTestGroup)
NW_TEST(NanoWinMFCAfxStrTestGroup, CStringReplaceSimpleTCHARTest)
{
CString cString("abc abc abc");
int n = cString.Replace('a', 'q');
NW_CHECK_EQUAL(3, n);
NW_CHECK_EQUAL_STRCMP(cString, "qbc qbc qbc");
n = cString.Replace('w', 'q');
NW_CHECK_EQUAL(0, n);
NW_CHECK_EQUAL_STRCMP(cString, "qbc qbc qbc");
}
NW_TEST(NanoWinMFCAfxStrTestGroup, CStringReplaceSimpleLPCTSTRTest)
{
CString cString("abc abc abc");
LPCTSTR strOld = "a";
LPCTSTR strNew = "q";
int n = cString.Replace(strOld, strNew);
NW_CHECK_EQUAL(3, n);
NW_CHECK_EQUAL_STRCMP(cString, "qbc qbc qbc");
}
NW_TEST(NanoWinMFCAfxStrTestGroup, CStringReplaceNullLPCTSTRTest)
{
CString cString("abc abc abc");
LPCTSTR strOld = "ab";
LPCTSTR strNew = NULL;
int n = cString.Replace(strOld, strNew);
NW_CHECK_EQUAL(3, n);
NW_CHECK_EQUAL_STRCMP(cString, "c c c");
}
NW_TEST(NanoWinMFCAfxStrTestGroup, CStringReplaceDifferentLengthLPCTSTRTest)
{
CString cString("abc abc abc qwe");
LPCTSTR strOld = "abc";
LPCTSTR strNew = "de";
int n = cString.Replace(strOld, strNew);
NW_CHECK_EQUAL(3, n);
NW_CHECK_EQUAL_STRCMP(cString, "de de de qwe");
}
NW_TEST(NanoWinMFCAfxStrTestGroup, CStringFindSimpleTCHARTest)
{
CString cString("abcdef");
int n = cString.Find('b');
NW_CHECK_EQUAL(1, n);
n = cString.Find('q');
NW_CHECK_EQUAL(-1, n);
}
NW_TEST(NanoWinMFCAfxStrTestGroup, CStringFindWithStartPosTCHARTest)
{
CString cString("abcdef abcdef");
int n = cString.Find('b', 4);
NW_CHECK_EQUAL(8, n);
n = cString.Find('q', 5);
NW_CHECK_EQUAL(-1, n);
}
NW_TEST(NanoWinMFCAfxStrTestGroup, CStringFindSimpleLPCTSTRTest)
{
CString cString("abcdef");
LPCTSTR sub = "b";
int n = cString.Find(sub);
NW_CHECK_EQUAL(1, n);
sub = "def";
n = cString.Find(sub);
NW_CHECK_EQUAL(3, n);
sub = "qqq";
n = cString.Find(sub);
NW_CHECK_EQUAL(-1, n);
}
NW_TEST(NanoWinMFCAfxStrTestGroup, CStringFindWithStartPosLPCTSTRTest)
{
CString cString("abcdef abcdef");
LPCTSTR sub = "b";
int n = cString.Find(sub, 4);
NW_CHECK_EQUAL(8, n);
sub = "def";
n = cString.Find(sub, 5);
NW_CHECK_EQUAL(10, n);
}
NW_TEST(NanoWinMFCAfxStrTestGroup, CStringReverseFindSimpleTCHARTest)
{
CString cString("abc abc abc");
int n = cString.ReverseFind('a');
NW_CHECK_EQUAL(8, n);
n = cString.ReverseFind('q');
NW_CHECK_EQUAL(-1, n);
}
NW_TEST(NanoWinMFCAfxStrTestGroup, CStringMakeLowerTest)
{
CString cString("aBcDeFZzZ");
cString.MakeLower();
NW_CHECK_EQUAL_STRCMP(cString, "abcdefzzz");
}
NW_TEST(NanoWinMFCAfxStrTestGroup, CStringMakeUpperTest)
{
CString cString("aBcDeFZzZ");
cString.MakeUpper();
NW_CHECK_EQUAL_STRCMP(cString, "ABCDEFZZZ");
}
NW_TEST(NanoWinMFCAfxStrTestGroup, CStringMakeReverseTest)
{
CString cString("abcdef");
cString.MakeReverse();
NW_CHECK_EQUAL_STRCMP(cString, "fedcba");
}
NW_TEST(NanoWinMFCAfxStrTestGroup, CStringRightTest)
{
CString cString("abcdef");
CString resStr = cString.Right(3);
NW_CHECK_EQUAL_STRCMP(resStr, "def");
}
NW_TEST(NanoWinMFCAfxStrTestGroup, CStringMidTest)
{
CString cString("abcdef");
CString resStr = cString.Mid(2);
NW_CHECK_EQUAL_STRCMP(resStr, "cdef");
}
/*
NW_TEST(NanoWinMFCAfxStrTestGroup, CStringMidWithCounterTest)
{
CString cString("abcdefabcdef");
CString resStr = cString.Mid(2, 5);
NW_CHECK_EQUAL_STRCMP("cdefa", resStr);
}
*/
/*
NW_TEST(NanoWinMFCAfxStrTestGroup, CStringLeftTest)
{
CString cString("abcdef");
CString resStr = cString.Left(3);
NW_CHECK_EQUAL_STRCMP("abc", resStr);
}
*/
NW_TEST(NanoWinMFCAfxStrTestGroup, CStringInsertTCHARTest)
{
CString cString("abcdef");
int n = cString.Insert(3, 'z');
NW_CHECK_EQUAL(7, n);
NW_CHECK_EQUAL_STRCMP("abczdef", cString);
}
NW_TEST(NanoWinMFCAfxStrTestGroup, CStringInsertIndexHigherThanLengthTCHARTest)
{
CString cString("abcdef");
int n = cString.Insert(100, 'z');
NW_CHECK_EQUAL(7, n);
NW_CHECK_EQUAL_STRCMP("abcdefz", cString);
}
NW_TEST(NanoWinMFCAfxStrTestGroup, CStringInsertLPCTSTRTest)
{
CString cString("abcdef");
int n = cString.Insert(0, "zzz");
NW_CHECK_EQUAL(9, n);
NW_CHECK_EQUAL_STRCMP("zzzabcdef", cString);
}
NW_TEST(NanoWinMFCAfxStrTestGroup, CStringDeleteTest)
{
CString cString("abcdefabc");
int n = cString.Delete(3, 3);
NW_CHECK_EQUAL(6, n);
NW_CHECK_EQUAL_STRCMP("abcabc", cString);
n = cString.Delete(3, 100);
NW_CHECK_EQUAL(3, n);
NW_CHECK_EQUAL_STRCMP("abc", cString);
}
NW_TEST(NanoWinMFCAfxStrTestGroup, CStringRemoveTest)
{
CString cString("abcdefabc");
int n = cString.Remove('a');
NW_CHECK_EQUAL(2, n);
NW_CHECK_EQUAL_STRCMP("bcdefbc", cString);
n = cString.Remove('q');
NW_CHECK_EQUAL(0, n);
NW_CHECK_EQUAL_STRCMP("bcdefbc", cString);
}
NW_TEST(NanoWinMFCAfxStrTestGroup, CStringTrimLeftTest)
{
CString cString(" abcdefabc ");
CString resStr = cString.TrimLeft();
NW_CHECK_EQUAL_STRCMP("abcdefabc ", resStr);
}
NW_TEST(NanoWinMFCAfxStrTestGroup, CStringTrimRightTest)
{
CString cString(" abcdefabc ");
CString resStr = cString.TrimRight();
NW_CHECK_EQUAL_STRCMP(" abcdefabc", resStr);
}
NW_TEST(NanoWinMFCAfxStrTestGroup, CStringTrimTest)
{
CString cString(" abcdefabc ");
CString resStr = cString.Trim();
NW_CHECK_EQUAL_STRCMP("abcdefabc", resStr);
}
NW_TEST(NanoWinMFCAfxStrTestGroup, CStringCompareTest)
{
CString cString("abcdef");
int res = cString.Compare("abcdef");
NW_CHECK_EQUAL(0, res);
res = cString.Compare("A");
NW_CHECK(res > 0);
res = cString.Compare("abcdefabc");
NW_CHECK(res < 0);
}
NW_TEST(NanoWinMFCAfxStrTestGroup, CStringCompareNoCaseTest)
{
CString cString("abcdef");
int res = cString.CompareNoCase("ABcdEF");
NW_CHECK_EQUAL(0, res);
res = cString.CompareNoCase("ABcdE");
NW_CHECK(res > 0);
}
/*
NW_TEST(NanoWinMFCAfxStrTestGroup, CStringFormatTest)
{
CString str;
str.Format("%d%s%d%s%d", 2, " * ", 2, " equal ", 4);
NW_CHECK_EQUAL_STRCMP("2 * 2 equal 4", str);
}
*/
NW_TEST(NanoWinMFCAfxStrTestGroup, CStringOperatorAssignTest)
{
CString cString("zzz");
cString = "a";
NW_CHECK_EQUAL_STRCMP("a", cString);
}
NW_TEST(NanoWinMFCAfxStrTestGroup, CStringOperatorPlusAssignTest)
{
CString cString("zzz");
cString += "www";
NW_CHECK_EQUAL_STRCMP("zzzwww", cString);
CString strAdd = "aaa";
cString += strAdd;
NW_CHECK_EQUAL_STRCMP("zzzwwwaaa", cString);
cString += 'b';
NW_CHECK_EQUAL_STRCMP("zzzwwwaaab", cString);
}
NW_TEST(NanoWinMFCAfxStrTestGroup, CStringOperatorPlusTest)
{
CString str1("zzz");
CString str2("aaa");
CString resStr = str1 + str2;
NW_CHECK_EQUAL_STRCMP("zzzaaa", resStr);
}
NW_TEST(NanoWinMFCAfxStrTestGroup, CStringCompareOperatorsTest)
{
NW_CHECK_TRUE(CString("abc") == CString("abc"));
NW_CHECK_TRUE(CString("abc") == "abc");
NW_CHECK_FALSE(CString("abc") == CString("abcde"));
NW_CHECK_FALSE("abcde" == CString("abc"));
NW_CHECK_TRUE(CString("abc") != CString("abcde"));
NW_CHECK_TRUE(CString("abc") != "abcde");
NW_CHECK_FALSE(CString("abc") != CString("abc"));
NW_CHECK_FALSE("abc" != CString("abc"));
NW_CHECK_TRUE(CString("abc") > CString("ab"));
NW_CHECK_TRUE(CString("abc") > "aaa");
NW_CHECK_FALSE("aaa" > CString("abc"));
NW_CHECK_TRUE(CString("ab") < CString("abc"));
NW_CHECK_TRUE(CString("aaa") < "abc");
NW_CHECK_FALSE("abc" < CString("aaa"));
NW_CHECK_TRUE(CString("abc") >= CString("abc"));
NW_CHECK_TRUE(CString("abc") >= "aaa");
NW_CHECK_FALSE("abc" >= CString("abcd"));
NW_CHECK_TRUE(CString("abc") <= CString("abc"));
NW_CHECK_TRUE(CString("aaa") <= "abc");
NW_CHECK_FALSE("abcd" <= CString("abc"));
}
NW_END_TEST_GROUP()<|endoftext|> |
<commit_before>#include "latexImprover.h"
#include <iostream>
#include "stringFinder.h"
latexImprover::latexImprover(std::stringstream& file, std::stringstream& output){
std::vector<std::string> stringsToFind;
stringsToFind.push_back("\\begin{align}");
stringsToFind.push_back("\\end{align}");
stringsToFind.push_back("\\begin{align}*");
stringsToFind.push_back("\\begin{equation}");
stringsToFind.push_back("\\end{equation}");
stringsToFind.push_back("\\begin{equation}*");
stringsToFind.push_back("\\left(");
stringsToFind.push_back("\\right)");
stringsToFind.push_back("\\left[");
stringsToFind.push_back("\\right]");
stringsToFind.push_back("\\label{");
stringFinder* stringFinderObj = new stringFinder(stringsToFind);
char prev_c = '\0';
char c;
while(file.get(c)){
int foundPos = stringFinderObj->read(c);
if(foundPos >= 0){
switch(foundPos){
case 0: latexImprover::inEnviromentAlign = true;
break;
case 1: latexImprover::inEnviromentAlign = false;
break;
case 2: latexImprover::inEnviromentAlign = true;
break;
case 3: latexImprover::inEnviromentEquation = true;
break;
case 4: latexImprover::inEnviromentEquation = false;
break;
case 5: latexImprover::inEnviromentEquation = true;
break;
case 10: latexImprover::inLabel = true;
break;
}
}
if(prev_c == '\\' && (c == '(' || c == '[')){
latexImprover::inSimpeEquation = true;
}
else if(prev_c == '\\' && (c == ')' || c == ']')){
latexImprover::inSimpeEquation = false;
}
else if(c == '}' && latexImprover::inLabel){
latexImprover::inLabel = false;
}
if((latexImprover::inEnviromentAlign || latexImprover::inEnviromentEquation || latexImprover::inSimpeEquation) && !latexImprover::inLabel){
if(foundPos == 6 || foundPos == 7 || foundPos == 8 || foundPos == 9){
output << c;
}
else if(c == '(' && prev_c != '\\'){
output << "\\left(";
}
else if(c == ')' && prev_c != '\\'){
output << "\\right)";
}
else if(c == '[' && prev_c != '\\'){
output << "\\left[";
}
else if(c == ']' && prev_c != '\\'){
output << "\\right]";
}
else{
output << c;
}
}
else{
output << c;
}
prev_c = c;
}
std::cout << std::endl;
}
<commit_msg>Clean up<commit_after>#include "latexImprover.h"
#include <iostream>
#include "stringFinder.h"
latexImprover::latexImprover(std::stringstream& file, std::stringstream& output){
std::vector<std::string> stringsToFind;
stringsToFind.push_back("\\begin{align}");
stringsToFind.push_back("\\end{align}");
stringsToFind.push_back("\\begin{align}*");
stringsToFind.push_back("\\begin{equation}");
stringsToFind.push_back("\\end{equation}");
stringsToFind.push_back("\\begin{equation}*");
stringsToFind.push_back("\\left(");
stringsToFind.push_back("\\right)");
stringsToFind.push_back("\\left[");
stringsToFind.push_back("\\right]");
stringsToFind.push_back("\\label{");
stringFinder* stringFinderObj = new stringFinder(stringsToFind);
char prev_c = '\0';
char c;
while(file.get(c)){
int foundPos = stringFinderObj->read(c);
if(foundPos >= 0){
switch(foundPos){
case 0: latexImprover::inEnviromentAlign = true;
break;
case 1: latexImprover::inEnviromentAlign = false;
break;
case 2: latexImprover::inEnviromentAlign = true;
break;
case 3: latexImprover::inEnviromentEquation = true;
break;
case 4: latexImprover::inEnviromentEquation = false;
break;
case 5: latexImprover::inEnviromentEquation = true;
break;
case 10: latexImprover::inLabel = true;
break;
}
}
if(prev_c == '\\' && (c == '(' || c == '[')){
latexImprover::inSimpeEquation = true;
}
else if(prev_c == '\\' && (c == ')' || c == ']')){
latexImprover::inSimpeEquation = false;
}
else if(c == '}' && latexImprover::inLabel){
latexImprover::inLabel = false;
}
if((latexImprover::inEnviromentAlign || latexImprover::inEnviromentEquation || latexImprover::inSimpeEquation) && !latexImprover::inLabel){
if(foundPos == 6 || foundPos == 7 || foundPos == 8 || foundPos == 9){
output << c;
}
else if(c == '(' && prev_c != '\\'){
output << "\\left(";
}
else if(c == ')' && prev_c != '\\'){
output << "\\right)";
}
else if(c == '[' && prev_c != '\\'){
output << "\\left[";
}
else if(c == ']' && prev_c != '\\'){
output << "\\right]";
}
else{
output << c;
}
}
else{
output << c;
}
prev_c = c;
}
}
<|endoftext|> |
<commit_before>/*
Copyright (C) 2019 Alexandr Akulich <akulichalexander@gmail.com>
This file is a part of TelegramQt library.
This library is free software; you can redistribute it and/or
modify it under the terms of the GNU Lesser General Public
License as published by the Free Software Foundation; either
version 2.1 of the License, or (at your option) any later version.
This library is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
Lesser General Public License for more details.
*/
// Client
#include "AccountStorage.hpp"
#include "CAppInformation.hpp"
#include "BaseTransport.hpp"
#include "Client.hpp"
#include "ClientSettings.hpp"
#include "ConnectionApi.hpp"
#include "ContactList.hpp"
#include "ContactsApi.hpp"
#include "DataStorage.hpp"
#include "DcConfiguration.hpp"
#include "DialogList.hpp"
#include "FilesApi.hpp"
#include "MessagingApi.hpp"
#include "RandomGenerator.hpp"
#include "TelegramNamespace.hpp"
#include "Operations/ClientAuthOperation.hpp"
#include "Operations/FileOperation.hpp"
#include "Operations/PendingContactsOperation.hpp"
// Server
#include "LocalCluster.hpp"
#include "MediaService.hpp"
#include "MessageService.hpp"
#include "RemoteClientConnection.hpp"
#include "ServerApi.hpp"
#include "ServerUtils.hpp"
#include "Session.hpp"
#include "TelegramServerUser.hpp"
// Test
#include "TestAuthProvider.hpp"
#include "TestClientUtils.hpp"
#include "TestServerUtils.hpp"
#include "TestUserData.hpp"
#include "TestUtils.hpp"
#include "keys_data.hpp"
#include <QCryptographicHash>
#include <QDebug>
#include <QRegularExpression>
#include <QSignalSpy>
#include <QTest>
using namespace Telegram;
static const UserData c_user1 = mkUserData(1000, 1);
static const UserData c_user2 = mkUserData(2000, 1);
class tst_FilesApi : public QObject
{
Q_OBJECT
public:
explicit tst_FilesApi(QObject *parent = nullptr);
private slots:
void initTestCase();
void cleanupTestCase();
void getSelfAvatar();
void getDialogListPictures();
void downloadMultipartFile();
protected:
Server::UploadDescriptor uploadFile(Server::AbstractServerApi *server);
};
tst_FilesApi::tst_FilesApi(QObject *parent) :
QObject(parent)
{
}
Server::UploadDescriptor tst_FilesApi::uploadFile(Server::AbstractServerApi *server)
{
quint64 fileId;
Telegram::RandomGenerator::instance()->generate(&fileId);
const QByteArray fileData = Telegram::RandomGenerator::instance()->generate(512);
quint32 filePartId = 0;
Server::IMediaService *mediaService = server->mediaService();
mediaService->uploadFilePart(fileId, filePartId, fileData);
return mediaService->getUploadedData(fileId);
}
void tst_FilesApi::initTestCase()
{
qRegisterMetaType<UserData>();
Telegram::initialize();
QVERIFY(TestKeyData::initKeyFiles());
}
void tst_FilesApi::cleanupTestCase()
{
QVERIFY(TestKeyData::cleanupKeyFiles());
}
void tst_FilesApi::getSelfAvatar()
{
// Generic test data
const UserData user1Data = c_user1;
const DcOption clientDcOption = c_localDcOptions.first();
const RsaKey publicKey = RsaKey::fromFile(TestKeyData::publicKeyFileName());
const RsaKey privateKey = RsaKey::fromFile(TestKeyData::privateKeyFileName());
// Prepare the server
Test::AuthProvider authProvider;
Telegram::Server::LocalCluster cluster;
cluster.setAuthorizationProvider(&authProvider);
cluster.setServerPrivateRsaKey(privateKey);
cluster.setServerConfiguration(c_localDcConfiguration);
QVERIFY(cluster.start());
Server::LocalUser *user1 = tryAddUser(&cluster, user1Data);
QVERIFY(user1);
// Upload an image
{
Server::AbstractServerApi *server = cluster.getServerApiInstance(user1->dcId());
QVERIFY(server);
const Server::ImageDescriptor image = uploadUserImage(server);
QVERIFY(image.isValid());
user1->updateImage(image);
}
// Prepare clients
Client::Client client1;
{
Test::setupClientHelper(&client1, user1Data, publicKey, clientDcOption);
Client::AuthOperation *signInOperation1 = nullptr;
Test::signInHelper(&client1, user1Data, &authProvider, &signInOperation1);
TRY_VERIFY2(signInOperation1->isSucceeded(), "Unexpected sign in fail");
QCOMPARE(client1.accountStorage()->phoneNumber(), user1Data.phoneNumber);
}
TRY_VERIFY(client1.isSignedIn());
UserInfo selfUserInfo;
client1.dataStorage()->getUserInfo(&selfUserInfo, client1.dataStorage()->selfUserId());
FileInfo pictureFile;
selfUserInfo.getPeerPicture(&pictureFile, PeerPictureSize::Small);
QVERIFY(!pictureFile.getFileId().isEmpty());
// Download by FileInfo
{
QBuffer buffer;
buffer.open(QIODevice::WriteOnly);
Client::FilesApi *filesApi = client1.filesApi();
Client::FileOperation *fileOp = filesApi->downloadFile(&pictureFile, &buffer);
QVERIFY(fileOp);
TRY_VERIFY(fileOp->isFinished());
QVERIFY(fileOp->isSucceeded());
QByteArray downloadedData = buffer.data();
QVERIFY(!downloadedData.isEmpty());
}
// Download by QString FileId
{
QBuffer buffer;
buffer.open(QIODevice::WriteOnly);
Client::FilesApi *filesApi = client1.filesApi();
Client::FileOperation *fileOp = filesApi->downloadFile(pictureFile.getFileId(), &buffer);
QVERIFY(fileOp);
TRY_VERIFY(fileOp->isFinished());
QVERIFY(fileOp->isSucceeded());
QByteArray downloadedData = buffer.data();
QVERIFY(!downloadedData.isEmpty());
}
}
void tst_FilesApi::getDialogListPictures()
{
const quint32 baseDate = 1500000000ul;
const UserData userData = c_user1;
const DcOption clientDcOption = c_localDcOptions.first();
const RsaKey publicKey = RsaKey::fromFile(TestKeyData::publicKeyFileName());
const RsaKey privateKey = RsaKey::fromFile(TestKeyData::privateKeyFileName());
const int dialogsCount = 30;
// Prepare server
Test::AuthProvider authProvider;
Telegram::Server::LocalCluster cluster;
cluster.setAuthorizationProvider(&authProvider);
cluster.setServerPrivateRsaKey(privateKey);
cluster.setServerConfiguration(c_localDcConfiguration);
QVERIFY(cluster.start());
Server::LocalUser *user = tryAddUser(&cluster, userData);
Server::AbstractServerApi *serverApi = cluster.getServerApiInstance(c_user1.dcId);
QVERIFY(serverApi);
// Prepare dialogs with avatars
{
Server::AbstractServerApi *server = cluster.getServerApiInstance(user->dcId());
QVERIFY(server);
const int dcCount = cluster.serverConfiguration().dcCount();
QVERIFY(dcCount > 1);
for (int i = 0; i < dialogsCount; ++i) {
Server::LocalUser *dialogN = tryAddUser(&cluster,
// Add users to different DCs
mkUserData(i, static_cast<quint32>((i % dcCount) + 1)));
QVERIFY(dialogN);
Server::AbstractServerApi *contactServer = cluster.getServerApiInstance(dialogN->dcId());
Server::MessageData *data = serverApi->messageService()
->addMessage(dialogN->userId(), user->toPeer(), QStringLiteral("mgs%1").arg(i + 1));
data->setDate(baseDate - dialogsCount + i);
cluster.sendMessage(data);
// Upload an image
const Server::ImageDescriptor image = uploadUserImage(contactServer);
QVERIFY(image.isValid());
dialogN->updateImage(image);
}
}
// Prepare the client
Client::Client client;
{
Test::setupClientHelper(&client, userData, publicKey, clientDcOption);
Client::AuthOperation *signInOperation = nullptr;
Test::signInHelper(&client, userData, &authProvider, &signInOperation);
TRY_VERIFY2(signInOperation->isSucceeded(), "Unexpected sign in fail");
QCOMPARE(client.accountStorage()->phoneNumber(), userData.phoneNumber);
}
TRY_VERIFY(client.isSignedIn());
Telegram::Client::DialogList *dialogList = client.messagingApi()->getDialogList();
PendingOperation *dialogsReady = dialogList->becomeReady();
TRY_VERIFY(dialogsReady->isFinished());
QVERIFY(dialogsReady->isSucceeded());
QCOMPARE(dialogList->peers().count(), dialogsCount);
Client::FilesApi *filesApi = client.filesApi();
QSet<Telegram::Client::FileOperation *> fetchOperations;
qWarning() << "START DOWNLOAD";
for (const Telegram::Peer &dialog : dialogList->peers()) {
FileInfo pictureFile;
if (dialog.type() == Telegram::Peer::User) {
UserInfo userInfo;
client.dataStorage()->getUserInfo(&userInfo, dialog.id());
userInfo.getPeerPicture(&pictureFile, PeerPictureSize::Small);
QVERIFY(!pictureFile.getFileId().isEmpty());
}
// Download by QString FileId
Client::FileOperation *fileOp = filesApi->downloadFile(pictureFile.getFileId());
QVERIFY(fileOp);
fetchOperations.insert(fileOp);
connect(fileOp, &Client::FileOperation::finished, this, [&fetchOperations, fileOp]() {
QVERIFY(fileOp->isFinished());
if (!fileOp->isSucceeded()) {
qWarning() << fileOp->errorDetails();
}
QVERIFY(fileOp->isSucceeded());
QVERIFY(fileOp->fileInfo()->isValid());
QVERIFY(fileOp->device());
const QByteArray data = fileOp->device()->readAll();
QVERIFY(!data.isEmpty());
fetchOperations.remove(fileOp);
});
}
int count = fetchOperations.count();
while (count) {
TRY_VERIFY(fetchOperations.count() != count);
count = fetchOperations.count();
}
}
void tst_FilesApi::downloadMultipartFile()
{
// Generic test data
const UserData user1Data = c_user1;
const DcOption clientDcOption = c_localDcOptions.first();
const RsaKey publicKey = RsaKey::fromFile(TestKeyData::publicKeyFileName());
const RsaKey privateKey = RsaKey::fromFile(TestKeyData::privateKeyFileName());
const int partsCount = 8;
const int partSize = 1024 * 32;
const int totalSize = partsCount * partSize;
// Prepare the server
Test::AuthProvider authProvider;
Telegram::Server::LocalCluster cluster;
cluster.setAuthorizationProvider(&authProvider);
cluster.setServerPrivateRsaKey(privateKey);
cluster.setServerConfiguration(c_localDcConfiguration);
QVERIFY(cluster.start());
Server::LocalUser *user = tryAddUser(&cluster, user1Data);
QVERIFY(user);
QByteArray fileHash;
QString clientFileId;
// Upload a multipart file
{
QCryptographicHash fileMd5Hash(QCryptographicHash::Md5);
Server::AbstractServerApi *server = cluster.getServerApiInstance(user->dcId());
QVERIFY(server);
quint64 fileId;
Telegram::RandomGenerator::instance()->generate(&fileId);
Telegram::Server::IMediaService *mediaService = server->mediaService();
for (int filePartId = 0; filePartId < partsCount; ++filePartId) {
QByteArray filePartData(partSize, 'a');
fileMd5Hash.addData(filePartData);
mediaService->uploadFilePart(fileId, filePartId, filePartData);
}
fileHash = fileMd5Hash.result();
const Telegram::Server::UploadDescriptor upload = mediaService->getUploadedData(fileId);
// QCOMPARE(desc.md5Checksum, fileMd5Hash);
const Telegram::Server::FileDescriptor fileDescriptor = mediaService->saveDocumentFile(upload, QLatin1String("a-parts.bin"), QLatin1String("bin"));
FileInfo clientFileInfo;
{
TLFileLocation location;
Telegram::Server::Utils::setupTLFileLocation(&location, fileDescriptor);
FileInfo::Private *p = FileInfo::Private::get(&clientFileInfo);
p->setFileLocation(&location);
p->m_size = fileDescriptor.size;
p->m_name = fileDescriptor.name;
}
clientFileId = clientFileInfo.getFileId();
}
// Prepare clients
Client::Client client1;
{
Test::setupClientHelper(&client1, user1Data, publicKey, clientDcOption);
Client::AuthOperation *signInOperation1 = nullptr;
Test::signInHelper(&client1, user1Data, &authProvider, &signInOperation1);
TRY_VERIFY2(signInOperation1->isSucceeded(), "Unexpected sign in fail");
QCOMPARE(client1.accountStorage()->phoneNumber(), user1Data.phoneNumber);
}
TRY_VERIFY(client1.isSignedIn());
{
Client::FileOperation *fileOp = client1.filesApi()->downloadFile(clientFileId);
quint32 totalDownloaded = 0;
forever {
TRY_VERIFY(totalDownloaded != fileOp->bytesTransferred());
totalDownloaded = fileOp->bytesTransferred();
if (fileOp->isFinished()) {
break;
}
}
QVERIFY(fileOp->isFinished());
if (!fileOp->isSucceeded()) {
qWarning() << fileOp->errorDetails();
}
QVERIFY(fileOp->isSucceeded());
QVERIFY(fileOp->device());
const QByteArray data = fileOp->device()->readAll();
QCOMPARE(data.size(), totalSize);
}
QCOMPARE(user->activeSessions().count(), 2);
Server::Session *activeMediaSession = user->activeSessions().last();
QVERIFY(activeMediaSession);
Telegram::BaseTransport *serverSideTransport = activeMediaSession->getConnection()->transport();
QVERIFY(serverSideTransport);
QVERIFY(serverSideTransport->state() == QAbstractSocket::ConnectedState);
// Brutal disconnect from server side
serverSideTransport->disconnectFromHost();
{
Client::FileOperation *fileOp = client1.filesApi()->downloadFile(clientFileId);
quint32 totalDownloaded = 0;
forever {
TRY_VERIFY(totalDownloaded != fileOp->bytesTransferred());
totalDownloaded = fileOp->bytesTransferred();
if (fileOp->isFinished()) {
break;
}
}
QVERIFY(fileOp->isFinished());
if (!fileOp->isSucceeded()) {
qWarning() << fileOp->errorDetails();
}
QVERIFY(fileOp->isSucceeded());
QVERIFY(fileOp->device());
const QByteArray data = fileOp->device()->readAll();
QCOMPARE(data.size(), totalSize);
}
}
QTEST_GUILESS_MAIN(tst_FilesApi)
#include "tst_FilesApi.moc"
<commit_msg>Tests/FilesApi: Remove a warning (there is nothing to warn about)<commit_after>/*
Copyright (C) 2019 Alexandr Akulich <akulichalexander@gmail.com>
This file is a part of TelegramQt library.
This library is free software; you can redistribute it and/or
modify it under the terms of the GNU Lesser General Public
License as published by the Free Software Foundation; either
version 2.1 of the License, or (at your option) any later version.
This library is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
Lesser General Public License for more details.
*/
// Client
#include "AccountStorage.hpp"
#include "CAppInformation.hpp"
#include "BaseTransport.hpp"
#include "Client.hpp"
#include "ClientSettings.hpp"
#include "ConnectionApi.hpp"
#include "ContactList.hpp"
#include "ContactsApi.hpp"
#include "DataStorage.hpp"
#include "DcConfiguration.hpp"
#include "DialogList.hpp"
#include "FilesApi.hpp"
#include "MessagingApi.hpp"
#include "RandomGenerator.hpp"
#include "TelegramNamespace.hpp"
#include "Operations/ClientAuthOperation.hpp"
#include "Operations/FileOperation.hpp"
#include "Operations/PendingContactsOperation.hpp"
// Server
#include "LocalCluster.hpp"
#include "MediaService.hpp"
#include "MessageService.hpp"
#include "RemoteClientConnection.hpp"
#include "ServerApi.hpp"
#include "ServerUtils.hpp"
#include "Session.hpp"
#include "TelegramServerUser.hpp"
// Test
#include "TestAuthProvider.hpp"
#include "TestClientUtils.hpp"
#include "TestServerUtils.hpp"
#include "TestUserData.hpp"
#include "TestUtils.hpp"
#include "keys_data.hpp"
#include <QCryptographicHash>
#include <QDebug>
#include <QRegularExpression>
#include <QSignalSpy>
#include <QTest>
using namespace Telegram;
static const UserData c_user1 = mkUserData(1000, 1);
static const UserData c_user2 = mkUserData(2000, 1);
class tst_FilesApi : public QObject
{
Q_OBJECT
public:
explicit tst_FilesApi(QObject *parent = nullptr);
private slots:
void initTestCase();
void cleanupTestCase();
void getSelfAvatar();
void getDialogListPictures();
void downloadMultipartFile();
protected:
Server::UploadDescriptor uploadFile(Server::AbstractServerApi *server);
};
tst_FilesApi::tst_FilesApi(QObject *parent) :
QObject(parent)
{
}
Server::UploadDescriptor tst_FilesApi::uploadFile(Server::AbstractServerApi *server)
{
quint64 fileId;
Telegram::RandomGenerator::instance()->generate(&fileId);
const QByteArray fileData = Telegram::RandomGenerator::instance()->generate(512);
quint32 filePartId = 0;
Server::IMediaService *mediaService = server->mediaService();
mediaService->uploadFilePart(fileId, filePartId, fileData);
return mediaService->getUploadedData(fileId);
}
void tst_FilesApi::initTestCase()
{
qRegisterMetaType<UserData>();
Telegram::initialize();
QVERIFY(TestKeyData::initKeyFiles());
}
void tst_FilesApi::cleanupTestCase()
{
QVERIFY(TestKeyData::cleanupKeyFiles());
}
void tst_FilesApi::getSelfAvatar()
{
// Generic test data
const UserData user1Data = c_user1;
const DcOption clientDcOption = c_localDcOptions.first();
const RsaKey publicKey = RsaKey::fromFile(TestKeyData::publicKeyFileName());
const RsaKey privateKey = RsaKey::fromFile(TestKeyData::privateKeyFileName());
// Prepare the server
Test::AuthProvider authProvider;
Telegram::Server::LocalCluster cluster;
cluster.setAuthorizationProvider(&authProvider);
cluster.setServerPrivateRsaKey(privateKey);
cluster.setServerConfiguration(c_localDcConfiguration);
QVERIFY(cluster.start());
Server::LocalUser *user1 = tryAddUser(&cluster, user1Data);
QVERIFY(user1);
// Upload an image
{
Server::AbstractServerApi *server = cluster.getServerApiInstance(user1->dcId());
QVERIFY(server);
const Server::ImageDescriptor image = uploadUserImage(server);
QVERIFY(image.isValid());
user1->updateImage(image);
}
// Prepare clients
Client::Client client1;
{
Test::setupClientHelper(&client1, user1Data, publicKey, clientDcOption);
Client::AuthOperation *signInOperation1 = nullptr;
Test::signInHelper(&client1, user1Data, &authProvider, &signInOperation1);
TRY_VERIFY2(signInOperation1->isSucceeded(), "Unexpected sign in fail");
QCOMPARE(client1.accountStorage()->phoneNumber(), user1Data.phoneNumber);
}
TRY_VERIFY(client1.isSignedIn());
UserInfo selfUserInfo;
client1.dataStorage()->getUserInfo(&selfUserInfo, client1.dataStorage()->selfUserId());
FileInfo pictureFile;
selfUserInfo.getPeerPicture(&pictureFile, PeerPictureSize::Small);
QVERIFY(!pictureFile.getFileId().isEmpty());
// Download by FileInfo
{
QBuffer buffer;
buffer.open(QIODevice::WriteOnly);
Client::FilesApi *filesApi = client1.filesApi();
Client::FileOperation *fileOp = filesApi->downloadFile(&pictureFile, &buffer);
QVERIFY(fileOp);
TRY_VERIFY(fileOp->isFinished());
QVERIFY(fileOp->isSucceeded());
QByteArray downloadedData = buffer.data();
QVERIFY(!downloadedData.isEmpty());
}
// Download by QString FileId
{
QBuffer buffer;
buffer.open(QIODevice::WriteOnly);
Client::FilesApi *filesApi = client1.filesApi();
Client::FileOperation *fileOp = filesApi->downloadFile(pictureFile.getFileId(), &buffer);
QVERIFY(fileOp);
TRY_VERIFY(fileOp->isFinished());
QVERIFY(fileOp->isSucceeded());
QByteArray downloadedData = buffer.data();
QVERIFY(!downloadedData.isEmpty());
}
}
void tst_FilesApi::getDialogListPictures()
{
const quint32 baseDate = 1500000000ul;
const UserData userData = c_user1;
const DcOption clientDcOption = c_localDcOptions.first();
const RsaKey publicKey = RsaKey::fromFile(TestKeyData::publicKeyFileName());
const RsaKey privateKey = RsaKey::fromFile(TestKeyData::privateKeyFileName());
const int dialogsCount = 30;
// Prepare server
Test::AuthProvider authProvider;
Telegram::Server::LocalCluster cluster;
cluster.setAuthorizationProvider(&authProvider);
cluster.setServerPrivateRsaKey(privateKey);
cluster.setServerConfiguration(c_localDcConfiguration);
QVERIFY(cluster.start());
Server::LocalUser *user = tryAddUser(&cluster, userData);
Server::AbstractServerApi *serverApi = cluster.getServerApiInstance(c_user1.dcId);
QVERIFY(serverApi);
// Prepare dialogs with avatars
{
Server::AbstractServerApi *server = cluster.getServerApiInstance(user->dcId());
QVERIFY(server);
const int dcCount = cluster.serverConfiguration().dcCount();
QVERIFY(dcCount > 1);
for (int i = 0; i < dialogsCount; ++i) {
Server::LocalUser *dialogN = tryAddUser(&cluster,
// Add users to different DCs
mkUserData(i, static_cast<quint32>((i % dcCount) + 1)));
QVERIFY(dialogN);
Server::AbstractServerApi *contactServer = cluster.getServerApiInstance(dialogN->dcId());
Server::MessageData *data = serverApi->messageService()
->addMessage(dialogN->userId(), user->toPeer(), QStringLiteral("mgs%1").arg(i + 1));
data->setDate(baseDate - dialogsCount + i);
cluster.sendMessage(data);
// Upload an image
const Server::ImageDescriptor image = uploadUserImage(contactServer);
QVERIFY(image.isValid());
dialogN->updateImage(image);
}
}
// Prepare the client
Client::Client client;
{
Test::setupClientHelper(&client, userData, publicKey, clientDcOption);
Client::AuthOperation *signInOperation = nullptr;
Test::signInHelper(&client, userData, &authProvider, &signInOperation);
TRY_VERIFY2(signInOperation->isSucceeded(), "Unexpected sign in fail");
QCOMPARE(client.accountStorage()->phoneNumber(), userData.phoneNumber);
}
TRY_VERIFY(client.isSignedIn());
Telegram::Client::DialogList *dialogList = client.messagingApi()->getDialogList();
PendingOperation *dialogsReady = dialogList->becomeReady();
TRY_VERIFY(dialogsReady->isFinished());
QVERIFY(dialogsReady->isSucceeded());
QCOMPARE(dialogList->peers().count(), dialogsCount);
Client::FilesApi *filesApi = client.filesApi();
QSet<Telegram::Client::FileOperation *> fetchOperations;
for (const Telegram::Peer &dialog : dialogList->peers()) {
FileInfo pictureFile;
if (dialog.type() == Telegram::Peer::User) {
UserInfo userInfo;
client.dataStorage()->getUserInfo(&userInfo, dialog.id());
userInfo.getPeerPicture(&pictureFile, PeerPictureSize::Small);
QVERIFY(!pictureFile.getFileId().isEmpty());
}
// Download by QString FileId
Client::FileOperation *fileOp = filesApi->downloadFile(pictureFile.getFileId());
QVERIFY(fileOp);
fetchOperations.insert(fileOp);
connect(fileOp, &Client::FileOperation::finished, this, [&fetchOperations, fileOp]() {
QVERIFY(fileOp->isFinished());
if (!fileOp->isSucceeded()) {
qWarning() << fileOp->errorDetails();
}
QVERIFY(fileOp->isSucceeded());
QVERIFY(fileOp->fileInfo()->isValid());
QVERIFY(fileOp->device());
const QByteArray data = fileOp->device()->readAll();
QVERIFY(!data.isEmpty());
fetchOperations.remove(fileOp);
});
}
int count = fetchOperations.count();
while (count) {
TRY_VERIFY(fetchOperations.count() != count);
count = fetchOperations.count();
}
}
void tst_FilesApi::downloadMultipartFile()
{
// Generic test data
const UserData user1Data = c_user1;
const DcOption clientDcOption = c_localDcOptions.first();
const RsaKey publicKey = RsaKey::fromFile(TestKeyData::publicKeyFileName());
const RsaKey privateKey = RsaKey::fromFile(TestKeyData::privateKeyFileName());
const int partsCount = 8;
const int partSize = 1024 * 32;
const int totalSize = partsCount * partSize;
// Prepare the server
Test::AuthProvider authProvider;
Telegram::Server::LocalCluster cluster;
cluster.setAuthorizationProvider(&authProvider);
cluster.setServerPrivateRsaKey(privateKey);
cluster.setServerConfiguration(c_localDcConfiguration);
QVERIFY(cluster.start());
Server::LocalUser *user = tryAddUser(&cluster, user1Data);
QVERIFY(user);
QByteArray fileHash;
QString clientFileId;
// Upload a multipart file
{
QCryptographicHash fileMd5Hash(QCryptographicHash::Md5);
Server::AbstractServerApi *server = cluster.getServerApiInstance(user->dcId());
QVERIFY(server);
quint64 fileId;
Telegram::RandomGenerator::instance()->generate(&fileId);
Telegram::Server::IMediaService *mediaService = server->mediaService();
for (int filePartId = 0; filePartId < partsCount; ++filePartId) {
QByteArray filePartData(partSize, 'a');
fileMd5Hash.addData(filePartData);
mediaService->uploadFilePart(fileId, filePartId, filePartData);
}
fileHash = fileMd5Hash.result();
const Telegram::Server::UploadDescriptor upload = mediaService->getUploadedData(fileId);
// QCOMPARE(desc.md5Checksum, fileMd5Hash);
const Telegram::Server::FileDescriptor fileDescriptor = mediaService->saveDocumentFile(upload, QLatin1String("a-parts.bin"), QLatin1String("bin"));
FileInfo clientFileInfo;
{
TLFileLocation location;
Telegram::Server::Utils::setupTLFileLocation(&location, fileDescriptor);
FileInfo::Private *p = FileInfo::Private::get(&clientFileInfo);
p->setFileLocation(&location);
p->m_size = fileDescriptor.size;
p->m_name = fileDescriptor.name;
}
clientFileId = clientFileInfo.getFileId();
}
// Prepare clients
Client::Client client1;
{
Test::setupClientHelper(&client1, user1Data, publicKey, clientDcOption);
Client::AuthOperation *signInOperation1 = nullptr;
Test::signInHelper(&client1, user1Data, &authProvider, &signInOperation1);
TRY_VERIFY2(signInOperation1->isSucceeded(), "Unexpected sign in fail");
QCOMPARE(client1.accountStorage()->phoneNumber(), user1Data.phoneNumber);
}
TRY_VERIFY(client1.isSignedIn());
{
Client::FileOperation *fileOp = client1.filesApi()->downloadFile(clientFileId);
quint32 totalDownloaded = 0;
forever {
TRY_VERIFY(totalDownloaded != fileOp->bytesTransferred());
totalDownloaded = fileOp->bytesTransferred();
if (fileOp->isFinished()) {
break;
}
}
QVERIFY(fileOp->isFinished());
if (!fileOp->isSucceeded()) {
qWarning() << fileOp->errorDetails();
}
QVERIFY(fileOp->isSucceeded());
QVERIFY(fileOp->device());
const QByteArray data = fileOp->device()->readAll();
QCOMPARE(data.size(), totalSize);
}
QCOMPARE(user->activeSessions().count(), 2);
Server::Session *activeMediaSession = user->activeSessions().last();
QVERIFY(activeMediaSession);
Telegram::BaseTransport *serverSideTransport = activeMediaSession->getConnection()->transport();
QVERIFY(serverSideTransport);
QVERIFY(serverSideTransport->state() == QAbstractSocket::ConnectedState);
// Brutal disconnect from server side
serverSideTransport->disconnectFromHost();
{
Client::FileOperation *fileOp = client1.filesApi()->downloadFile(clientFileId);
quint32 totalDownloaded = 0;
forever {
TRY_VERIFY(totalDownloaded != fileOp->bytesTransferred());
totalDownloaded = fileOp->bytesTransferred();
if (fileOp->isFinished()) {
break;
}
}
QVERIFY(fileOp->isFinished());
if (!fileOp->isSucceeded()) {
qWarning() << fileOp->errorDetails();
}
QVERIFY(fileOp->isSucceeded());
QVERIFY(fileOp->device());
const QByteArray data = fileOp->device()->readAll();
QCOMPARE(data.size(), totalSize);
}
}
QTEST_GUILESS_MAIN(tst_FilesApi)
#include "tst_FilesApi.moc"
<|endoftext|> |
<commit_before>/*M///////////////////////////////////////////////////////////////////////////////////////
//
// IMPORTANT: READ BEFORE DOWNLOADING, COPYING, INSTALLING OR USING.
//
// By downloading, copying, installing or using the software you agree to this license.
// If you do not agree to this license, do not download, install,
// copy or use the software.
//
//
// License Agreement
// For Open Source Computer Vision Library
//
// Copyright (C) 2000-2008, Intel Corporation, all rights reserved.
// Copyright (C) 2009, Willow Garage Inc., all rights reserved.
// Third party copyrights are property of their respective owners.
//
// Redistribution and use in source and binary forms, with or without modification,
// are permitted provided that the following conditions are met:
//
// * Redistribution's of source code must retain the above copyright notice,
// this list of conditions and the following disclaimer.
//
// * Redistribution's 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.
//
// * The name of the copyright holders may not 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 Intel Corporation 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.
//
//M*/
#ifndef OPENCV_CUDA_FILTERS_HPP
#define OPENCV_CUDA_FILTERS_HPP
#include "saturate_cast.hpp"
#include "vec_traits.hpp"
#include "vec_math.hpp"
#include "type_traits.hpp"
/** @file
* @deprecated Use @ref cudev instead.
*/
//! @cond IGNORED
namespace cv { namespace cuda { namespace device
{
template <typename Ptr2D> struct PointFilter
{
typedef typename Ptr2D::elem_type elem_type;
typedef float index_type;
explicit __host__ __device__ __forceinline__ PointFilter(const Ptr2D& src_, float fx = 0.f, float fy = 0.f)
: src(src_)
{
CV_UNUSED(fx);
CV_UNUSED(fy);
}
__device__ __forceinline__ elem_type operator ()(float y, float x) const
{
return src(__float2int_rz(y), __float2int_rz(x));
}
Ptr2D src;
};
template <typename Ptr2D> struct LinearFilter
{
typedef typename Ptr2D::elem_type elem_type;
typedef float index_type;
explicit __host__ __device__ __forceinline__ LinearFilter(const Ptr2D& src_, float fx = 0.f, float fy = 0.f)
: src(src_)
{
CV_UNUSED(fx);
CV_UNUSED(fy);
}
__device__ __forceinline__ elem_type operator ()(float y, float x) const
{
typedef typename TypeVec<float, VecTraits<elem_type>::cn>::vec_type work_type;
work_type out = VecTraits<work_type>::all(0);
const int x1 = __float2int_rd(x);
const int y1 = __float2int_rd(y);
const int x2 = x1 + 1;
const int y2 = y1 + 1;
elem_type src_reg = src(y1, x1);
out = out + src_reg * ((x2 - x) * (y2 - y));
src_reg = src(y1, x2);
out = out + src_reg * ((x - x1) * (y2 - y));
src_reg = src(y2, x1);
out = out + src_reg * ((x2 - x) * (y - y1));
src_reg = src(y2, x2);
out = out + src_reg * ((x - x1) * (y - y1));
return saturate_cast<elem_type>(out);
}
Ptr2D src;
};
template <typename Ptr2D> struct CubicFilter
{
typedef typename Ptr2D::elem_type elem_type;
typedef float index_type;
typedef typename TypeVec<float, VecTraits<elem_type>::cn>::vec_type work_type;
explicit __host__ __device__ __forceinline__ CubicFilter(const Ptr2D& src_, float fx = 0.f, float fy = 0.f)
: src(src_)
{
CV_UNUSED(fx);
CV_UNUSED(fy);
}
static __device__ __forceinline__ float bicubicCoeff(float x_)
{
float x = fabsf(x_);
if (x <= 1.0f)
{
return x * x * (1.5f * x - 2.5f) + 1.0f;
}
else if (x < 2.0f)
{
return x * (x * (-0.5f * x + 2.5f) - 4.0f) + 2.0f;
}
else
{
return 0.0f;
}
}
__device__ elem_type operator ()(float y, float x) const
{
const float xmin = ::ceilf(x - 2.0f);
const float xmax = ::floorf(x + 2.0f);
const float ymin = ::ceilf(y - 2.0f);
const float ymax = ::floorf(y + 2.0f);
work_type sum = VecTraits<work_type>::all(0);
float wsum = 0.0f;
for (float cy = ymin; cy <= ymax; cy += 1.0f)
{
for (float cx = xmin; cx <= xmax; cx += 1.0f)
{
const float w = bicubicCoeff(x - cx) * bicubicCoeff(y - cy);
sum = sum + w * src(__float2int_rd(cy), __float2int_rd(cx));
wsum += w;
}
}
work_type res = (!wsum)? VecTraits<work_type>::all(0) : sum / wsum;
return saturate_cast<elem_type>(res);
}
Ptr2D src;
};
// for integer scaling
template <typename Ptr2D> struct IntegerAreaFilter
{
typedef typename Ptr2D::elem_type elem_type;
typedef float index_type;
explicit __host__ __device__ __forceinline__ IntegerAreaFilter(const Ptr2D& src_, float scale_x_, float scale_y_)
: src(src_), scale_x(scale_x_), scale_y(scale_y_), scale(1.f / (scale_x * scale_y)) {}
__device__ __forceinline__ elem_type operator ()(float y, float x) const
{
float fsx1 = x * scale_x;
float fsx2 = fsx1 + scale_x;
int sx1 = __float2int_ru(fsx1);
int sx2 = __float2int_rd(fsx2);
float fsy1 = y * scale_y;
float fsy2 = fsy1 + scale_y;
int sy1 = __float2int_ru(fsy1);
int sy2 = __float2int_rd(fsy2);
typedef typename TypeVec<float, VecTraits<elem_type>::cn>::vec_type work_type;
work_type out = VecTraits<work_type>::all(0.f);
for(int dy = sy1; dy < sy2; ++dy)
for(int dx = sx1; dx < sx2; ++dx)
{
out = out + src(dy, dx) * scale;
}
return saturate_cast<elem_type>(out);
}
Ptr2D src;
float scale_x, scale_y ,scale;
};
template <typename Ptr2D> struct AreaFilter
{
typedef typename Ptr2D::elem_type elem_type;
typedef float index_type;
explicit __host__ __device__ __forceinline__ AreaFilter(const Ptr2D& src_, float scale_x_, float scale_y_)
: src(src_), scale_x(scale_x_), scale_y(scale_y_){}
__device__ __forceinline__ elem_type operator ()(float y, float x) const
{
float fsx1 = x * scale_x;
float fsx2 = fsx1 + scale_x;
int sx1 = __float2int_ru(fsx1);
int sx2 = __float2int_rd(fsx2);
float fsy1 = y * scale_y;
float fsy2 = fsy1 + scale_y;
int sy1 = __float2int_ru(fsy1);
int sy2 = __float2int_rd(fsy2);
float scale = 1.f / (fminf(scale_x, src.width - fsx1) * fminf(scale_y, src.height - fsy1));
typedef typename TypeVec<float, VecTraits<elem_type>::cn>::vec_type work_type;
work_type out = VecTraits<work_type>::all(0.f);
for (int dy = sy1; dy < sy2; ++dy)
{
for (int dx = sx1; dx < sx2; ++dx)
out = out + src(dy, dx) * scale;
if (sx1 > fsx1)
out = out + src(dy, (sx1 -1) ) * ((sx1 - fsx1) * scale);
if (sx2 < fsx2)
out = out + src(dy, sx2) * ((fsx2 -sx2) * scale);
}
if (sy1 > fsy1)
for (int dx = sx1; dx < sx2; ++dx)
out = out + src( (sy1 - 1) , dx) * ((sy1 -fsy1) * scale);
if (sy2 < fsy2)
for (int dx = sx1; dx < sx2; ++dx)
out = out + src(sy2, dx) * ((fsy2 -sy2) * scale);
if ((sy1 > fsy1) && (sx1 > fsx1))
out = out + src( (sy1 - 1) , (sx1 - 1)) * ((sy1 -fsy1) * (sx1 -fsx1) * scale);
if ((sy1 > fsy1) && (sx2 < fsx2))
out = out + src( (sy1 - 1) , sx2) * ((sy1 -fsy1) * (fsx2 -sx2) * scale);
if ((sy2 < fsy2) && (sx2 < fsx2))
out = out + src(sy2, sx2) * ((fsy2 -sy2) * (fsx2 -sx2) * scale);
if ((sy2 < fsy2) && (sx1 > fsx1))
out = out + src(sy2, (sx1 - 1)) * ((fsy2 -sy2) * (sx1 -fsx1) * scale);
return saturate_cast<elem_type>(out);
}
Ptr2D src;
float scale_x, scale_y;
int width, haight;
};
}}} // namespace cv { namespace cuda { namespace cudev
//! @endcond
#endif // OPENCV_CUDA_FILTERS_HPP
<commit_msg>Added overflow handling during conversion from float to int for LinearFilter<commit_after>/*M///////////////////////////////////////////////////////////////////////////////////////
//
// IMPORTANT: READ BEFORE DOWNLOADING, COPYING, INSTALLING OR USING.
//
// By downloading, copying, installing or using the software you agree to this license.
// If you do not agree to this license, do not download, install,
// copy or use the software.
//
//
// License Agreement
// For Open Source Computer Vision Library
//
// Copyright (C) 2000-2008, Intel Corporation, all rights reserved.
// Copyright (C) 2009, Willow Garage Inc., all rights reserved.
// Third party copyrights are property of their respective owners.
//
// Redistribution and use in source and binary forms, with or without modification,
// are permitted provided that the following conditions are met:
//
// * Redistribution's of source code must retain the above copyright notice,
// this list of conditions and the following disclaimer.
//
// * Redistribution's 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.
//
// * The name of the copyright holders may not 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 Intel Corporation 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.
//
//M*/
#ifndef OPENCV_CUDA_FILTERS_HPP
#define OPENCV_CUDA_FILTERS_HPP
#include "saturate_cast.hpp"
#include "vec_traits.hpp"
#include "vec_math.hpp"
#include "type_traits.hpp"
#include "nppdefs.h"
/** @file
* @deprecated Use @ref cudev instead.
*/
//! @cond IGNORED
namespace cv { namespace cuda { namespace device
{
template <typename Ptr2D> struct PointFilter
{
typedef typename Ptr2D::elem_type elem_type;
typedef float index_type;
explicit __host__ __device__ __forceinline__ PointFilter(const Ptr2D& src_, float fx = 0.f, float fy = 0.f)
: src(src_)
{
CV_UNUSED(fx);
CV_UNUSED(fy);
}
__device__ __forceinline__ elem_type operator ()(float y, float x) const
{
return src(__float2int_rz(y), __float2int_rz(x));
}
Ptr2D src;
};
template <typename Ptr2D> struct LinearFilter
{
typedef typename Ptr2D::elem_type elem_type;
typedef float index_type;
explicit __host__ __device__ __forceinline__ LinearFilter(const Ptr2D& src_, float fx = 0.f, float fy = 0.f)
: src(src_)
{
CV_UNUSED(fx);
CV_UNUSED(fy);
}
__device__ __forceinline__ elem_type operator ()(float y, float x) const
{
typedef typename TypeVec<float, VecTraits<elem_type>::cn>::vec_type work_type;
work_type out = VecTraits<work_type>::all(0);
const int x1 = __float2int_rd(x);
const int y1 = __float2int_rd(y);
if (x1 <= NPP_MIN_32S || x1 >= NPP_MAX_32S || y1 <= NPP_MIN_32S || y1 >= NPP_MAX_32S)
{
elem_type src_reg = src(y1, x1);
out = out + src_reg * 1.0f;
return saturate_cast<elem_type>(out);
}
const int x2 = x1 + 1;
const int y2 = y1 + 1;
elem_type src_reg = src(y1, x1);
out = out + src_reg * ((x2 - x) * (y2 - y));
src_reg = src(y1, x2);
out = out + src_reg * ((x - x1) * (y2 - y));
src_reg = src(y2, x1);
out = out + src_reg * ((x2 - x) * (y - y1));
src_reg = src(y2, x2);
out = out + src_reg * ((x - x1) * (y - y1));
return saturate_cast<elem_type>(out);
}
Ptr2D src;
};
template <typename Ptr2D> struct CubicFilter
{
typedef typename Ptr2D::elem_type elem_type;
typedef float index_type;
typedef typename TypeVec<float, VecTraits<elem_type>::cn>::vec_type work_type;
explicit __host__ __device__ __forceinline__ CubicFilter(const Ptr2D& src_, float fx = 0.f, float fy = 0.f)
: src(src_)
{
CV_UNUSED(fx);
CV_UNUSED(fy);
}
static __device__ __forceinline__ float bicubicCoeff(float x_)
{
float x = fabsf(x_);
if (x <= 1.0f)
{
return x * x * (1.5f * x - 2.5f) + 1.0f;
}
else if (x < 2.0f)
{
return x * (x * (-0.5f * x + 2.5f) - 4.0f) + 2.0f;
}
else
{
return 0.0f;
}
}
__device__ elem_type operator ()(float y, float x) const
{
const float xmin = ::ceilf(x - 2.0f);
const float xmax = ::floorf(x + 2.0f);
const float ymin = ::ceilf(y - 2.0f);
const float ymax = ::floorf(y + 2.0f);
work_type sum = VecTraits<work_type>::all(0);
float wsum = 0.0f;
for (float cy = ymin; cy <= ymax; cy += 1.0f)
{
for (float cx = xmin; cx <= xmax; cx += 1.0f)
{
const float w = bicubicCoeff(x - cx) * bicubicCoeff(y - cy);
sum = sum + w * src(__float2int_rd(cy), __float2int_rd(cx));
wsum += w;
}
}
work_type res = (!wsum)? VecTraits<work_type>::all(0) : sum / wsum;
return saturate_cast<elem_type>(res);
}
Ptr2D src;
};
// for integer scaling
template <typename Ptr2D> struct IntegerAreaFilter
{
typedef typename Ptr2D::elem_type elem_type;
typedef float index_type;
explicit __host__ __device__ __forceinline__ IntegerAreaFilter(const Ptr2D& src_, float scale_x_, float scale_y_)
: src(src_), scale_x(scale_x_), scale_y(scale_y_), scale(1.f / (scale_x * scale_y)) {}
__device__ __forceinline__ elem_type operator ()(float y, float x) const
{
float fsx1 = x * scale_x;
float fsx2 = fsx1 + scale_x;
int sx1 = __float2int_ru(fsx1);
int sx2 = __float2int_rd(fsx2);
float fsy1 = y * scale_y;
float fsy2 = fsy1 + scale_y;
int sy1 = __float2int_ru(fsy1);
int sy2 = __float2int_rd(fsy2);
typedef typename TypeVec<float, VecTraits<elem_type>::cn>::vec_type work_type;
work_type out = VecTraits<work_type>::all(0.f);
for(int dy = sy1; dy < sy2; ++dy)
for(int dx = sx1; dx < sx2; ++dx)
{
out = out + src(dy, dx) * scale;
}
return saturate_cast<elem_type>(out);
}
Ptr2D src;
float scale_x, scale_y ,scale;
};
template <typename Ptr2D> struct AreaFilter
{
typedef typename Ptr2D::elem_type elem_type;
typedef float index_type;
explicit __host__ __device__ __forceinline__ AreaFilter(const Ptr2D& src_, float scale_x_, float scale_y_)
: src(src_), scale_x(scale_x_), scale_y(scale_y_){}
__device__ __forceinline__ elem_type operator ()(float y, float x) const
{
float fsx1 = x * scale_x;
float fsx2 = fsx1 + scale_x;
int sx1 = __float2int_ru(fsx1);
int sx2 = __float2int_rd(fsx2);
float fsy1 = y * scale_y;
float fsy2 = fsy1 + scale_y;
int sy1 = __float2int_ru(fsy1);
int sy2 = __float2int_rd(fsy2);
float scale = 1.f / (fminf(scale_x, src.width - fsx1) * fminf(scale_y, src.height - fsy1));
typedef typename TypeVec<float, VecTraits<elem_type>::cn>::vec_type work_type;
work_type out = VecTraits<work_type>::all(0.f);
for (int dy = sy1; dy < sy2; ++dy)
{
for (int dx = sx1; dx < sx2; ++dx)
out = out + src(dy, dx) * scale;
if (sx1 > fsx1)
out = out + src(dy, (sx1 -1) ) * ((sx1 - fsx1) * scale);
if (sx2 < fsx2)
out = out + src(dy, sx2) * ((fsx2 -sx2) * scale);
}
if (sy1 > fsy1)
for (int dx = sx1; dx < sx2; ++dx)
out = out + src( (sy1 - 1) , dx) * ((sy1 -fsy1) * scale);
if (sy2 < fsy2)
for (int dx = sx1; dx < sx2; ++dx)
out = out + src(sy2, dx) * ((fsy2 -sy2) * scale);
if ((sy1 > fsy1) && (sx1 > fsx1))
out = out + src( (sy1 - 1) , (sx1 - 1)) * ((sy1 -fsy1) * (sx1 -fsx1) * scale);
if ((sy1 > fsy1) && (sx2 < fsx2))
out = out + src( (sy1 - 1) , sx2) * ((sy1 -fsy1) * (fsx2 -sx2) * scale);
if ((sy2 < fsy2) && (sx2 < fsx2))
out = out + src(sy2, sx2) * ((fsy2 -sy2) * (fsx2 -sx2) * scale);
if ((sy2 < fsy2) && (sx1 > fsx1))
out = out + src(sy2, (sx1 - 1)) * ((fsy2 -sy2) * (sx1 -fsx1) * scale);
return saturate_cast<elem_type>(out);
}
Ptr2D src;
float scale_x, scale_y;
int width, haight;
};
}}} // namespace cv { namespace cuda { namespace cudev
//! @endcond
#endif // OPENCV_CUDA_FILTERS_HPP
<|endoftext|> |
<commit_before><commit_msg>QtWidgets: Trims color string to avoid crash when trailing spaces is present<commit_after><|endoftext|> |
<commit_before>/*
* A Remote Debugger Client for SpiderMonkey Java Script Engine.
* Copyright (C) 2014-2015 Slawomir Wojtasiak
*
* 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.
*/
using namespace std;
#include <stdlib.h>
#include <iostream>
#include <errno.h>
#include <string.h>
#ifdef HAVE_TERMIOS_H
#include <termios.h>
#endif
#include <unistd.h>
#include "getopt_config.hpp"
#include "tcp_client.hpp"
#include "fsevents.hpp"
#include "readline.hpp"
#include "dbg_client.hpp"
#include "js_debugger.hpp"
using namespace std;
class ApplicationCtxImpl : public ApplicationCtx {
public:
ApplicationCtxImpl()
: _mainLoop(NULL),
_readLine(NULL),
_debugger(NULL) {
};
~ApplicationCtxImpl() {
};
public:
// ApplicationCtx
void closeApplication() {
_mainLoop->abort();
}
ReadLineEditor &getReadLineEditor() {
return *_readLine;
}
DebuggerEngine &getDebuggerEngine() {
return *_debugger;
}
public:
void setMainLoop( IEventLoop *mainLoop ) {
_mainLoop = mainLoop;
}
void setReadLineEditor( ReadLineEditor *rl ) {
_readLine = rl;
}
void setDebuggerEngine( DebuggerEngine *debuggerEngine) {
_debugger = debuggerEngine;
}
private:
IEventLoop *_mainLoop;
ReadLineEditor *_readLine;
DebuggerEngine *_debugger;
};
class DebuggerCtxImpl : public DebuggerCtx {
public:
DebuggerCtxImpl( ReadLineEditor &readLine, TCPClient &client )
: _readLine(readLine),
_client(client),
_consoleDriver(NULL) {
}
~DebuggerCtxImpl() {
}
void sendCommand( const DebuggerCommand &command ) {
_client.sendCommand(command);
}
ReadLineEditor& getEditor() {
return _readLine;
}
void print( std::string str, ... ) {
va_list args;
va_start( args, str );
if( _consoleDriver ) {
_consoleDriver->prepareConsole();
_consoleDriver->print(str, args);
} else {
_readLine.print(str, args);
}
va_end( args );
}
void registerConsoleDriver(IConsoleDriver *driver) {
// Just in case.
deleteConsoleDriver();
// Register new driver and connect it to a readline editor.
_consoleDriver = driver;
_consoleDriver->setEditor(_readLine);
}
void deleteConsoleDriver() {
if( _consoleDriver ) {
_consoleDriver->restoreConsole();
delete _consoleDriver;
_consoleDriver = NULL;
}
}
private:
ReadLineEditor &_readLine;
TCPClient &_client;
IConsoleDriver *_consoleDriver;
};
int main(int argc, char **argv) {
#ifdef HAVE_TERMIOS_H
termios termAttrs;
// Store terminal attributes.
tcgetattr( STDIN_FILENO, &termAttrs );
#endif
/* Sets the environemtn's default locale. */
setlocale(LC_ALL, "");
// Parse configuration.
Configuration configuration;
GetoptConfigParser parser( argc, argv );
if( !parser.parse( configuration ) ) {
exit(1);
}
// Register read line implementation.
ReadLine &rlConsumer = ReadLine::getInstance();
// Connect to a debugger instance.
TCPClient *client;
int error = TCPClient::Connect( configuration.getHost(), configuration.getPort(), &client );
if( error ) {
cout << strerror( errno ) << endl;
exit(1);
}
// Initialize JS engine.
DebuggerCtxImpl dbgCtx(rlConsumer, *client);
JSDebugger dbg(dbgCtx);
error = dbg.init();
if( error ) {
dbg.destroy();
cout << "Cannot initialize JS engine: " << error << endl;
exit(1);
}
// Information for the client.
cout << "JavaScript Remote Debugger Client connected to a remote debugger.\nWaiting for a list of JavaScript contexts being debugged.\nType \"help context\" for more information." << endl;
ApplicationCtxImpl ctx;
MainEventHandler mainEventHandler( ctx );
client->setEventHandler( &mainEventHandler );
// Prepare FS Events loop.
std::vector<IFSEventProducer*> producers;
producers.push_back( client );
std::vector<IFSEventConsumer*> consumers;
consumers.push_back(client);
rlConsumer.registerReadline( &mainEventHandler );
consumers.push_back( &rlConsumer );
// The main debugger's loop.
FSEventLoop eventsLoop(producers, consumers);
// Initialize the main context.
ctx.setMainLoop( &eventsLoop );
ctx.setReadLineEditor( &rlConsumer );
ctx.setDebuggerEngine( &dbg );
error = eventsLoop.loop();
if( error ) {
cout << "Debugger interrupted with error: " << error << endl;
}
client->setEventHandler(NULL);
client->disconnect(JDB_ERROR_NO_ERROR);
delete client;
dbg.destroy();
#ifdef HAVE_TERMIOS_H
// Restore terminal attributes.
tcsetattr( STDIN_FILENO, TCSANOW, &termAttrs );
#endif
exit(0);
}
<commit_msg>jrdb: add poor man's signal handling<commit_after>/*
* A Remote Debugger Client for SpiderMonkey Java Script Engine.
* Copyright (C) 2014-2015 Slawomir Wojtasiak
*
* 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.
*/
#include <stdlib.h>
#include <iostream>
#include <errno.h>
#include <string.h>
#ifdef HAVE_TERMIOS_H
#include <termios.h>
#endif
#include <unistd.h>
#include <signal.h>
#include "getopt_config.hpp"
#include "tcp_client.hpp"
#include "fsevents.hpp"
#include "readline.hpp"
#include "dbg_client.hpp"
#include "js_debugger.hpp"
using namespace std;
static void signal_handler(int signo) {
ReadLine &rl = ReadLine::getInstance();
EditorState state("quit", 5);
rl.restoreEditor(state);
}
#ifdef HAVE_TERMIOS_H
class SaveTerminalAttributes {
public:
SaveTerminalAttributes() {
tcgetattr( STDIN_FILENO, &_attrs );
}
~SaveTerminalAttributes() {
restore();
}
void restore() {
tcsetattr( STDIN_FILENO, TCSANOW, &_attrs );
}
private:
termios _attrs;
};
#endif
class ApplicationCtxImpl : public ApplicationCtx {
public:
ApplicationCtxImpl()
: _mainLoop(NULL),
_readLine(NULL),
_debugger(NULL) {
};
~ApplicationCtxImpl() {
};
public:
// ApplicationCtx
void closeApplication() {
_mainLoop->abort();
}
ReadLineEditor &getReadLineEditor() {
return *_readLine;
}
DebuggerEngine &getDebuggerEngine() {
return *_debugger;
}
public:
void setMainLoop( IEventLoop *mainLoop ) {
_mainLoop = mainLoop;
}
void setReadLineEditor( ReadLineEditor *rl ) {
_readLine = rl;
}
void setDebuggerEngine( DebuggerEngine *debuggerEngine) {
_debugger = debuggerEngine;
}
private:
IEventLoop *_mainLoop;
ReadLineEditor *_readLine;
DebuggerEngine *_debugger;
};
class DebuggerCtxImpl : public DebuggerCtx {
public:
DebuggerCtxImpl( ReadLineEditor &readLine, TCPClient &client )
: _readLine(readLine),
_client(client),
_consoleDriver(NULL) {
}
~DebuggerCtxImpl() {
}
void sendCommand( const DebuggerCommand &command ) {
_client.sendCommand(command);
}
ReadLineEditor& getEditor() {
return _readLine;
}
void print( std::string str, ... ) {
va_list args;
va_start( args, str );
if( _consoleDriver ) {
_consoleDriver->prepareConsole();
_consoleDriver->print(str, args);
} else {
_readLine.print(str, args);
}
va_end( args );
}
void registerConsoleDriver(IConsoleDriver *driver) {
// Just in case.
deleteConsoleDriver();
// Register new driver and connect it to a readline editor.
_consoleDriver = driver;
_consoleDriver->setEditor(_readLine);
}
void deleteConsoleDriver() {
if( _consoleDriver ) {
_consoleDriver->restoreConsole();
delete _consoleDriver;
_consoleDriver = NULL;
}
}
private:
ReadLineEditor &_readLine;
TCPClient &_client;
IConsoleDriver *_consoleDriver;
};
int main(int argc, char **argv) {
#ifdef HAVE_TERMIOS_H
// Store terminal attributes.
SaveTerminalAttributes termAttrs;
#endif
// Sets the environment's default locale.
setlocale(LC_ALL, "");
// Register signal handler.
struct sigaction sa;
sigemptyset(&sa.sa_mask);
sa.sa_flags = 0;
sa.sa_handler = signal_handler;
if (sigaction(SIGINT, &sa, NULL)) {
cout << "Could not register signal handler" << endl;
exit(1);
}
// Parse configuration.
Configuration configuration;
GetoptConfigParser parser( argc, argv );
if( !parser.parse( configuration ) ) {
exit(1);
}
// Register read line implementation.
ReadLine &rlConsumer = ReadLine::getInstance();
// Connect to a debugger instance.
TCPClient *client;
int error = TCPClient::Connect( configuration.getHost(), configuration.getPort(), &client );
if( error ) {
cout << strerror( errno ) << endl;
exit(1);
}
// Initialize JS engine.
DebuggerCtxImpl dbgCtx(rlConsumer, *client);
JSDebugger dbg(dbgCtx);
error = dbg.init();
if( error ) {
dbg.destroy();
cout << "Cannot initialize JS engine: " << error << endl;
exit(1);
}
// Information for the client.
cout << "JavaScript Remote Debugger Client connected to a remote debugger.\nWaiting for a list of JavaScript contexts being debugged.\nType \"help context\" for more information." << endl;
ApplicationCtxImpl ctx;
MainEventHandler mainEventHandler( ctx );
client->setEventHandler( &mainEventHandler );
// Prepare FS Events loop.
std::vector<IFSEventProducer*> producers;
producers.push_back( client );
std::vector<IFSEventConsumer*> consumers;
consumers.push_back(client);
rlConsumer.registerReadline( &mainEventHandler );
consumers.push_back( &rlConsumer );
// The main debugger's loop.
FSEventLoop eventsLoop(producers, consumers);
// Initialize the main context.
ctx.setMainLoop( &eventsLoop );
ctx.setReadLineEditor( &rlConsumer );
ctx.setDebuggerEngine( &dbg );
error = eventsLoop.loop();
if( error ) {
cout << "Debugger interrupted with error: " << error << endl;
}
client->setEventHandler(NULL);
client->disconnect(JDB_ERROR_NO_ERROR);
delete client;
dbg.destroy();
exit(0);
}
<|endoftext|> |
<commit_before>#include "phase_analyze.hpp"
using std::string;
using std::pair;
using std::shared_ptr;
using std::make_shared;
using std::move;
using std::vector;
using std::static_pointer_cast;
using std::make_pair;
using backend::utility::make_vector;
using backend::utility::make_set;
using std::set;
namespace backend {
namespace detail {
//Finds all identifiers which are returned in a procedure
class return_finder
: public rewriter<return_finder> {
private:
set<string> m_returns;
public:
using rewriter<return_finder>::operator();
result_type operator()(const ret& r) {
if (detail::isinstance<name>(r.val())) {
const name& return_name = boost::get<const name&>(r.val());
m_returns.insert(return_name.id());
}
return r.ptr();
}
const set<string>& returns() const {
return m_returns;
}
};
}
phase_analyze::phase_analyze(const string& entry_point,
const registry& reg)
: m_entry_point(entry_point), m_in_entry(false) {
for(auto i = reg.fns().cbegin();
i != reg.fns().cend();
i++) {
auto id = i->first;
string fn_name = std::get<0>(id);
auto info = i->second;
m_fns.insert(make_pair(fn_name, info.phase().ptr()));
}
}
phase_analyze::result_type phase_analyze::operator()(const procedure& n) {
if (n.id().id() == m_entry_point) {
detail::return_finder rf;
boost::apply_visitor(rf, n);
m_returns = rf.returns();
m_in_entry = true;
m_completions.begin_scope();
//All inputs to the entry point must be totally or invariantly formed
for(auto i = n.args().begin();
i != n.args().end();
i++) {
//Arguments to procedures must be names
assert(detail::isinstance<name>(*i));
const name& arg_name = detail::up_get<name>(*i);
const std::string& arg_id = arg_name.id();
//If the input is typed as a sequence, it's totally formed
//Otherwise it's invariantly formed (scalars)
if (detail::isinstance<sequence_t>(arg_name.type())) {
m_completions.insert(make_pair(arg_id, completion::total));
} else {
m_completions.insert(make_pair(arg_id, completion::invariant));
}
}
shared_ptr<const suite> stmts =
static_pointer_cast<const suite>(
boost::apply_visitor(*this, n.stmts()));
result_type result =
make_shared<const procedure>(
n.id().ptr(),
n.args().ptr(),
stmts,
n.type().ptr(),
n.ctype().ptr(),
n.place());
m_in_entry = false;
m_completions.end_scope();
return result;
} else {
return n.ptr();
}
}
bool phase_analyze::add_phase_boundary_tuple(const name& n, bool post) {
assert(m_tuples.exists(n.id()));
bool need_boundary = false;
const vector<shared_ptr<const literal> >& sources =
m_tuples.find(n.id())->second;
for(auto i = sources.begin();
i != sources.end();
i++) {
if (detail::isinstance<name>(**i)) {
const name& i_name = boost::get<const name&>(**i);
need_boundary |= add_phase_boundary(i_name);
}
}
if (!need_boundary) {
return false;
}
shared_ptr<const name> p_result =
make_shared<const name>(
detail::complete(n.id()),
n.type().ptr());
vector<shared_ptr<const expression> > expr_sources;
for(auto i = sources.begin();
i != sources.end();
i++) {
if (detail::isinstance<name>(**i)) {
const name& i_name = boost::get<const name&>(**i);
if (m_substitutions.exists(i_name.id())) {
expr_sources.push_back(
m_substitutions.find(i_name.id())->second->ptr());
} else {
expr_sources.push_back(*i);
}
} else {
expr_sources.push_back(*i);
}
}
shared_ptr<const tuple> pb_args =
make_shared<const tuple>(
move(expr_sources));
shared_ptr<const apply> pb_apply =
make_shared<const apply>(
make_shared<const name>(
detail::snippet_make_tuple()),
pb_args);
shared_ptr<const bind> result =
make_shared<const bind>(p_result, pb_apply);
if (post) {
m_post_boundary = result;
} else {
m_pre_boundaries.push_back(result);
}
//Register completion
m_completions.insert(
make_pair(p_result->id(), completion::total));
//Register substitution
m_substitutions.insert(
make_pair(n.id(), p_result));
return true;
}
bool phase_analyze::add_phase_boundary(const name& n, bool post) {
if (m_tuples.exists(n.id())) {
return add_phase_boundary_tuple(n, post);
}
if (!post) {
//Post completions can happen multiple times due to iteration
//Pre completions may happen only once
if (m_completions.exists(n.id())) {
completion c = m_completions.find(n.id())->second;
if ((c == completion::invariant) ||
(c == completion::total))
return false;
}
}
shared_ptr<const name> p_result =
make_shared<const name>(
detail::complete(n.id()),
n.type().ptr());
shared_ptr<const tuple> pb_args =
make_shared<const tuple>(
make_vector<shared_ptr<const expression> >(n.ptr()));
shared_ptr<const name> pb_name =
make_shared<const name>(detail::phase_boundary());
shared_ptr<const apply> pb_apply =
make_shared<const apply>(pb_name, pb_args);
shared_ptr<const bind> result =
make_shared<const bind>(p_result, pb_apply);
if (post) {
m_post_boundary = result;
} else {
m_pre_boundaries.push_back(result);
}
//Register completion
m_completions.insert(
make_pair(p_result->id(), completion::total));
//Register substitution
m_substitutions.insert(
make_pair(n.id(), p_result));
return true;
}
phase_analyze::result_type phase_analyze::operator()(const apply& n) {
if (!m_in_entry) {
return n.ptr();
}
const name& fn_name = n.fn();
//If function not declared, assume it can't trigger a phase boundary
if (m_fns.find(fn_name.id()) == m_fns.end()) {
return n.ptr();
}
shared_ptr<const phase_t> fn_phase = m_fns.find(fn_name.id())->second;
phase_t::iterator j = fn_phase->begin();
//The phase type for the function must match the args given to it
assert(fn_phase->size() == n.args().arity());
vector<shared_ptr<const expression> > new_args;
for(auto i = n.args().begin();
i != n.args().end();
i++, j++) {
shared_ptr<const expression> new_arg = i->ptr();
//If we have something other than a name, assume it's invariant
if (detail::isinstance<name>(*i)) {
const name& id = detail::up_get<name>(*i);
if (m_substitutions.exists(id.id())) {
//Phase boundary already took place, use the complete version
//HEURISTIC HAZARD:
//This might not always be the right choice
new_arg = m_substitutions.find(id.id())->second;
} else {
//If completion hasn't been recorded, assume it's invariant
if (m_completions.exists(id.id())) {
completion arg_completion =
m_completions.find(id.id())->second;
//Do we need a phase boundary for this argument?
if (arg_completion < (*j)) {
add_phase_boundary(id);
new_arg = m_substitutions.find(id.id())->second;
}
}
}
}
new_args.push_back(new_arg);
}
m_result_completion = fn_phase->result();
return n.ptr();
}
phase_analyze::result_type phase_analyze::make_tuple_analyze(const bind& n) {
assert(detail::isinstance<name>(n.lhs()));
const name& lhs = boost::get<const name&>(n.lhs());
assert(detail::isinstance<apply>(n.rhs()));
const apply& rhs = boost::get<const apply&>(n.rhs());
const name& fn_name = rhs.fn();
assert(fn_name.id() == detail::snippet_make_tuple());
vector<shared_ptr<const literal> > sources;
for(auto i = rhs.args().begin(); i != rhs.args().end(); i++) {
assert(detail::isinstance<literal>(*i));
const literal& i_name = detail::up_get<const literal&>(*i);
sources.push_back(i_name.ptr());
}
completion glb = completion::invariant;
for(auto i = sources.begin(); i != sources.end(); i++) {
if (m_completions.exists((*i)->id())) {
completion other = m_completions.find((*i)->id())->second;
if (other < glb) {
glb = other;
}
}
}
m_completions.insert(make_pair(lhs.id(), glb));
m_tuples.insert(make_pair(lhs.id(),
move(sources)));
return n.ptr();
}
phase_analyze::result_type phase_analyze::form_suite(
const shared_ptr<const statement>& stmt) {
if (m_pre_boundaries.empty() &&
m_post_boundary == shared_ptr<const statement>()) {
return stmt;
}
vector<shared_ptr<const statement> > stmts(m_pre_boundaries.begin(),
m_pre_boundaries.end());
m_pre_boundaries.clear();
stmts.push_back(stmt);
if (m_post_boundary != shared_ptr<const statement>()) {
stmts.push_back(m_post_boundary);
m_post_boundary = shared_ptr<const statement>();
}
return make_shared<const suite>(move(stmts));
}
phase_analyze::result_type phase_analyze::operator()(const bind& n) {
if (!m_in_entry) {
return n.ptr();
}
//XXX
//If function is make_tuple, handle it separately
//Reason: make_tuple's phase type is not representable
//at present. When we redo phase inference, we'll want to
//fix this.
//The problem is that it needs to be a GLB type
//And we don't have a way to represent GLB types in the phase
//type system
if (detail::isinstance<apply>(n.rhs())) {
const apply& rhs_apply = boost::get<const apply&>(n.rhs());
const name& fn_name = rhs_apply.fn();
if (fn_name.id() == detail::snippet_make_tuple()) {
return make_tuple_analyze(n);
}
}
//If we're rebinding, ensure the source is as complete as the dest
//This happens, for example, in the body of a while loop
//The source can be incomplete, while the destination needs to be
//Complete. In that case, trigger a phase boundary
if (detail::isinstance<name>(n.rhs())) {
const name& source_name = boost::get<const name&>(n.rhs());
shared_ptr<const name> rhs = source_name.ptr();
//Check to see if we have a completed version of the RHS
//If so, return a binding which grabs from the completed version
auto subst = m_substitutions.find(source_name.id());
if (subst != m_substitutions.end()) {
return make_shared<bind>(n.lhs().ptr(), subst->second);
}
//We don't have a completed version, so we'll need to use it
assert(detail::isinstance<name>(n.lhs()));
const name& dest_name = boost::get<const name&>(n.lhs());
if (m_completions.exists(source_name.id()) &&
m_completions.exists(dest_name.id())) {
completion source_completion =
m_completions.find(source_name.id())->second;
completion dest_completion =
m_completions.find(dest_name.id())->second;
if (source_completion < dest_completion) {
add_phase_boundary(source_name);
rhs = m_substitutions.find(source_name.id())->second;
}
}
if (rhs == n.rhs().ptr()) {
return n.ptr();
} else {
return form_suite(make_shared<const bind>(
n.lhs().ptr(),
rhs));
}
}
m_result_completion = completion::invariant;
result_type rewritten = this->rewriter<phase_analyze>::operator()(n);
//If the result is going to be returned at some point, it must be
//completed
if (detail::isinstance<name>(n.lhs())) {
const name& lhs_name = boost::get<const name&>(n.lhs());
if (m_returns.find(lhs_name.id()) != m_returns.end()) {
//Add a phase boundary, POST call
add_phase_boundary(lhs_name, true);
m_result_completion = completion::total;
}
}
//Update completion declarations
if (detail::isinstance<name>(n.lhs())) {
const name& lhs_name = detail::up_get<name>(n.lhs());
m_completions.insert(make_pair(lhs_name.id(),
m_result_completion));
}
return form_suite(static_pointer_cast<const statement>(rewritten));
}
phase_analyze::result_type phase_analyze::operator()(const ret& n) {
if (detail::isinstance<name>(n.val())) {
const name& ret_val = boost::get<const name&>(n.val());
auto subst = m_substitutions.find(ret_val.id());
if (subst != m_substitutions.end()) {
return make_shared<const ret>(subst->second);
}
}
return n.ptr();
}
}
<commit_msg>Don't complete things upon return if not necessary.<commit_after>#include "phase_analyze.hpp"
using std::string;
using std::pair;
using std::shared_ptr;
using std::make_shared;
using std::move;
using std::vector;
using std::static_pointer_cast;
using std::make_pair;
using backend::utility::make_vector;
using backend::utility::make_set;
using std::set;
namespace backend {
namespace detail {
//Finds all identifiers which are returned in a procedure
class return_finder
: public rewriter<return_finder> {
private:
set<string> m_returns;
public:
using rewriter<return_finder>::operator();
result_type operator()(const ret& r) {
if (detail::isinstance<name>(r.val())) {
const name& return_name = boost::get<const name&>(r.val());
m_returns.insert(return_name.id());
}
return r.ptr();
}
const set<string>& returns() const {
return m_returns;
}
};
}
phase_analyze::phase_analyze(const string& entry_point,
const registry& reg)
: m_entry_point(entry_point), m_in_entry(false) {
for(auto i = reg.fns().cbegin();
i != reg.fns().cend();
i++) {
auto id = i->first;
string fn_name = std::get<0>(id);
auto info = i->second;
m_fns.insert(make_pair(fn_name, info.phase().ptr()));
}
}
phase_analyze::result_type phase_analyze::operator()(const procedure& n) {
if (n.id().id() == m_entry_point) {
detail::return_finder rf;
boost::apply_visitor(rf, n);
m_returns = rf.returns();
m_in_entry = true;
m_completions.begin_scope();
//All inputs to the entry point must be totally or invariantly formed
for(auto i = n.args().begin();
i != n.args().end();
i++) {
//Arguments to procedures must be names
assert(detail::isinstance<name>(*i));
const name& arg_name = detail::up_get<name>(*i);
const std::string& arg_id = arg_name.id();
//If the input is typed as a sequence, it's totally formed
//Otherwise it's invariantly formed (scalars)
if (detail::isinstance<sequence_t>(arg_name.type())) {
m_completions.insert(make_pair(arg_id, completion::total));
} else {
m_completions.insert(make_pair(arg_id, completion::invariant));
}
}
shared_ptr<const suite> stmts =
static_pointer_cast<const suite>(
boost::apply_visitor(*this, n.stmts()));
result_type result =
make_shared<const procedure>(
n.id().ptr(),
n.args().ptr(),
stmts,
n.type().ptr(),
n.ctype().ptr(),
n.place());
m_in_entry = false;
m_completions.end_scope();
return result;
} else {
return n.ptr();
}
}
bool phase_analyze::add_phase_boundary_tuple(const name& n, bool post) {
assert(m_tuples.exists(n.id()));
bool need_boundary = false;
const vector<shared_ptr<const literal> >& sources =
m_tuples.find(n.id())->second;
for(auto i = sources.begin();
i != sources.end();
i++) {
if (detail::isinstance<name>(**i)) {
const name& i_name = boost::get<const name&>(**i);
need_boundary |= add_phase_boundary(i_name);
}
}
if (!need_boundary) {
return false;
}
shared_ptr<const name> p_result =
make_shared<const name>(
detail::complete(n.id()),
n.type().ptr());
vector<shared_ptr<const expression> > expr_sources;
for(auto i = sources.begin();
i != sources.end();
i++) {
if (detail::isinstance<name>(**i)) {
const name& i_name = boost::get<const name&>(**i);
if (m_substitutions.exists(i_name.id())) {
expr_sources.push_back(
m_substitutions.find(i_name.id())->second->ptr());
} else {
expr_sources.push_back(*i);
}
} else {
expr_sources.push_back(*i);
}
}
shared_ptr<const tuple> pb_args =
make_shared<const tuple>(
move(expr_sources));
shared_ptr<const apply> pb_apply =
make_shared<const apply>(
make_shared<const name>(
detail::snippet_make_tuple()),
pb_args);
shared_ptr<const bind> result =
make_shared<const bind>(p_result, pb_apply);
if (post) {
m_post_boundary = result;
} else {
m_pre_boundaries.push_back(result);
}
//Register completion
m_completions.insert(
make_pair(p_result->id(), completion::total));
//Register substitution
m_substitutions.insert(
make_pair(n.id(), p_result));
return true;
}
bool phase_analyze::add_phase_boundary(const name& n, bool post) {
if (m_tuples.exists(n.id())) {
return add_phase_boundary_tuple(n, post);
}
if (!post) {
//Post completions can happen multiple times due to iteration
//Pre completions may happen only once
if (m_completions.exists(n.id())) {
completion c = m_completions.find(n.id())->second;
if ((c == completion::invariant) ||
(c == completion::total))
return false;
}
}
shared_ptr<const name> p_result =
make_shared<const name>(
detail::complete(n.id()),
n.type().ptr());
shared_ptr<const tuple> pb_args =
make_shared<const tuple>(
make_vector<shared_ptr<const expression> >(n.ptr()));
shared_ptr<const name> pb_name =
make_shared<const name>(detail::phase_boundary());
shared_ptr<const apply> pb_apply =
make_shared<const apply>(pb_name, pb_args);
shared_ptr<const bind> result =
make_shared<const bind>(p_result, pb_apply);
if (post) {
m_post_boundary = result;
} else {
m_pre_boundaries.push_back(result);
}
//Register completion
m_completions.insert(
make_pair(p_result->id(), completion::total));
//Register substitution
m_substitutions.insert(
make_pair(n.id(), p_result));
return true;
}
phase_analyze::result_type phase_analyze::operator()(const apply& n) {
if (!m_in_entry) {
return n.ptr();
}
const name& fn_name = n.fn();
//If function not declared, assume it can't trigger a phase boundary
if (m_fns.find(fn_name.id()) == m_fns.end()) {
return n.ptr();
}
shared_ptr<const phase_t> fn_phase = m_fns.find(fn_name.id())->second;
phase_t::iterator j = fn_phase->begin();
//The phase type for the function must match the args given to it
assert(fn_phase->size() == n.args().arity());
vector<shared_ptr<const expression> > new_args;
for(auto i = n.args().begin();
i != n.args().end();
i++, j++) {
shared_ptr<const expression> new_arg = i->ptr();
//If we have something other than a name, assume it's invariant
if (detail::isinstance<name>(*i)) {
const name& id = detail::up_get<name>(*i);
if (m_substitutions.exists(id.id())) {
//Phase boundary already took place, use the complete version
//HEURISTIC HAZARD:
//This might not always be the right choice
new_arg = m_substitutions.find(id.id())->second;
} else {
//If completion hasn't been recorded, assume it's invariant
if (m_completions.exists(id.id())) {
completion arg_completion =
m_completions.find(id.id())->second;
//Do we need a phase boundary for this argument?
if (arg_completion < (*j)) {
add_phase_boundary(id);
new_arg = m_substitutions.find(id.id())->second;
}
}
}
}
new_args.push_back(new_arg);
}
m_result_completion = fn_phase->result();
return n.ptr();
}
phase_analyze::result_type phase_analyze::make_tuple_analyze(const bind& n) {
assert(detail::isinstance<name>(n.lhs()));
const name& lhs = boost::get<const name&>(n.lhs());
assert(detail::isinstance<apply>(n.rhs()));
const apply& rhs = boost::get<const apply&>(n.rhs());
const name& fn_name = rhs.fn();
assert(fn_name.id() == detail::snippet_make_tuple());
vector<shared_ptr<const literal> > sources;
for(auto i = rhs.args().begin(); i != rhs.args().end(); i++) {
assert(detail::isinstance<literal>(*i));
const literal& i_name = detail::up_get<const literal&>(*i);
sources.push_back(i_name.ptr());
}
completion glb = completion::invariant;
for(auto i = sources.begin(); i != sources.end(); i++) {
if (m_completions.exists((*i)->id())) {
completion other = m_completions.find((*i)->id())->second;
if (other < glb) {
glb = other;
}
}
}
m_completions.insert(make_pair(lhs.id(), glb));
m_tuples.insert(make_pair(lhs.id(),
move(sources)));
return n.ptr();
}
phase_analyze::result_type phase_analyze::form_suite(
const shared_ptr<const statement>& stmt) {
if (m_pre_boundaries.empty() &&
m_post_boundary == shared_ptr<const statement>()) {
return stmt;
}
vector<shared_ptr<const statement> > stmts(m_pre_boundaries.begin(),
m_pre_boundaries.end());
m_pre_boundaries.clear();
stmts.push_back(stmt);
if (m_post_boundary != shared_ptr<const statement>()) {
stmts.push_back(m_post_boundary);
m_post_boundary = shared_ptr<const statement>();
}
return make_shared<const suite>(move(stmts));
}
phase_analyze::result_type phase_analyze::operator()(const bind& n) {
if (!m_in_entry) {
return n.ptr();
}
//XXX
//If function is make_tuple, handle it separately
//Reason: make_tuple's phase type is not representable
//at present. When we redo phase inference, we'll want to
//fix this.
//The problem is that it needs to be a GLB type
//And we don't have a way to represent GLB types in the phase
//type system
if (detail::isinstance<apply>(n.rhs())) {
const apply& rhs_apply = boost::get<const apply&>(n.rhs());
const name& fn_name = rhs_apply.fn();
if (fn_name.id() == detail::snippet_make_tuple()) {
return make_tuple_analyze(n);
}
}
//If we're rebinding, ensure the source is as complete as the dest
//This happens, for example, in the body of a while loop
//The source can be incomplete, while the destination needs to be
//Complete. In that case, trigger a phase boundary
if (detail::isinstance<name>(n.rhs())) {
const name& source_name = boost::get<const name&>(n.rhs());
shared_ptr<const name> rhs = source_name.ptr();
//Check to see if we have a completed version of the RHS
//If so, return a binding which grabs from the completed version
auto subst = m_substitutions.find(source_name.id());
if (subst != m_substitutions.end()) {
return make_shared<bind>(n.lhs().ptr(), subst->second);
}
//We don't have a completed version, so we'll need to use it
assert(detail::isinstance<name>(n.lhs()));
const name& dest_name = boost::get<const name&>(n.lhs());
if (m_completions.exists(source_name.id()) &&
m_completions.exists(dest_name.id())) {
completion source_completion =
m_completions.find(source_name.id())->second;
completion dest_completion =
m_completions.find(dest_name.id())->second;
if (source_completion < dest_completion) {
add_phase_boundary(source_name);
rhs = m_substitutions.find(source_name.id())->second;
}
}
if (rhs == n.rhs().ptr()) {
return n.ptr();
} else {
return form_suite(make_shared<const bind>(
n.lhs().ptr(),
rhs));
}
}
m_result_completion = completion::invariant;
result_type rewritten = this->rewriter<phase_analyze>::operator()(n);
//If the result is going to be returned at some point, it must be
//completed
if (detail::isinstance<name>(n.lhs())) {
const name& lhs_name = boost::get<const name&>(n.lhs());
if ((m_returns.find(lhs_name.id()) != m_returns.end()) &&
m_result_completion < completion::total) {
//Add a phase boundary, POST call
add_phase_boundary(lhs_name, true);
m_result_completion = completion::total;
}
}
//Update completion declarations
if (detail::isinstance<name>(n.lhs())) {
const name& lhs_name = detail::up_get<name>(n.lhs());
m_completions.insert(make_pair(lhs_name.id(),
m_result_completion));
}
return form_suite(static_pointer_cast<const statement>(rewritten));
}
phase_analyze::result_type phase_analyze::operator()(const ret& n) {
if (detail::isinstance<name>(n.val())) {
const name& ret_val = boost::get<const name&>(n.val());
auto subst = m_substitutions.find(ret_val.id());
if (subst != m_substitutions.end()) {
return make_shared<const ret>(subst->second);
}
}
return n.ptr();
}
}
<|endoftext|> |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.