text
stringlengths 54
60.6k
|
---|
<commit_before>#include "p_rect.h"
#include "algebra.h"
#include <stdexcept>
#include <typeinfo>
#include <algorithm>
#include <iterator>
using liven::scene;
using liven::view;
using liven::viewer;
using liven::node;
using liven::located;
using liven::dimension;
using liven::ascii_image;
using liven::ascii_viewer;
using liven::point;
using liven::rect;
using liven::grid_node;
bool operator==(const length &lhs, const length &rhs) {return !(lhs < rhs) && !(rhs < lhs);}
bool operator< (const length &lhs, const length &rhs) {
if (lhs.val < rhs.val) {return true;}
else if (lhs.val > rhs.val) {return false;}
else {
// lhs.val == rhs.val
return lhs.name < rhs.name;
}
}
located<rect,2> p_rect::own_bounding_rect() const {
return located<rect,2>(rect(width()+1,height()+1),get_location());
}
int p_rect::width_in_units() const {
int out = 0;
for (auto it = x_lengths.begin(); it != x_lengths.end(); ++it) {out += it->val;}
return out;
}
int p_rect::height_in_units() const {
int out = 0;
for (auto it = y_lengths.begin(); it != y_lengths.end(); ++it) {out += it->val;}
return out;
}
int p_rect::width() const {
return width_in_units() * unit_size;
}
int p_rect::height() const {
return height_in_units() * unit_size;
}
std::map<length,int> p_rect::get_length_frequency_map(dimension dim) const {
std::map<length,int> out{};
for (auto len : get_lengths(dim)) {++out[len];}
return out;
}
std::map<std::string,int> p_rect::get_var_coeff_map(dimension dim) const {
std::map<std::string,int> out{};
auto lengths = get_lengths(dim);
for (auto len : lengths) {
std::string name{};
if (len.name == "1") {name = "";}
else (name = len.name);
++out[name];
}
return out;
}
const std::vector<length> &p_rect::get_lengths(dimension dim) const {
switch (dim) {
case dimension::x:
return x_lengths;
case dimension::y:
return y_lengths;
}
}
void p_rect::swap_x_y() {
x_lengths.swap(y_lengths);
}
std::string p_rect::x_label_text() const {
return p_rect::label_text(dimension::x);
}
std::string p_rect::y_label_text() const {
return p_rect::label_text(dimension::y);
}
std::string p_rect::get_factored_string() const {
return algebra::enclose(x_label_text()) + algebra::enclose(y_label_text());
}
std::string p_rect::get_expanded_string() const {
return algebra::sum_to_string(algebra::expand(get_var_coeff_map(dimension::x),get_var_coeff_map(dimension::y)));
}
std::string p_rect::label_text(dimension dim) const {
return algebra::sum_to_string(get_var_coeff_map(dim));
}
void p_rect::set_display_style(display_style_type ds) {
display_style = ds;
switch (ds) {
case display_style_type::empty:
show_interior_lines = false;
show_sub_rect_labels = false;
show_center_factored = false;
show_center_expanded = false;
break;
case display_style_type::labels_and_lines:
show_interior_lines = true;
show_sub_rect_labels = true;
show_center_factored = false;
show_center_expanded = false;
break;
case display_style_type::center_factored:
show_interior_lines = false;
show_sub_rect_labels = false;
show_center_factored = true;
show_center_expanded = false;
break;
case display_style_type::center_expanded:
show_interior_lines = false;
show_sub_rect_labels = false;
show_center_factored = false;
show_center_expanded = true;
}
}
p_rect::display_style_type p_rect::get_display_style() {
return display_style;
}
void p_rect::set_children_display_style(std::shared_ptr<node> n, display_style_type ds) {
for (auto child : n->get_children()) {
std::dynamic_pointer_cast<p_rect>(child)->set_display_style(ds);
}
}
std::shared_ptr<node> p_rect::split(dimension dim,std::set<int> split_points) {
auto out = std::make_shared<node>();
std::vector<length> split_lengths;
std::vector<length> other_lengths;
switch(dim) {
case dimension::x:
split_lengths = x_lengths;
other_lengths = y_lengths;
break;
case dimension::y:
split_lengths = y_lengths;
other_lengths = x_lengths;
break;
}
int low = 0;
int low_units = 0;
int low_coordinates = 0;
std::vector<std::vector<length>> out_split_lengths = {};
std::vector<int> location_offsets = {};
split_points.insert(split_lengths.size());
for (auto split_point : split_points) {
if (split_point < 1) {throw std::out_of_range("split_point less than 1");}
if (split_point > split_lengths.size()) {throw std::out_of_range("split_point past the end");}
out_split_lengths.push_back(std::vector<length>(split_lengths.begin() + low,split_lengths.begin() + split_point));
location_offsets.push_back(low_coordinates);
for (int i = low; i < split_point; ++i) {
low_units += split_lengths[i].val;
}
low_coordinates = low_units * unit_size;
low = split_point;
}
std::shared_ptr<p_rect> sub_rect;
for (int i = 0; i < out_split_lengths.size(); ++i) {
auto lengths = out_split_lengths[i];
switch(dim) {
case dimension::x:
sub_rect = std::make_shared<p_rect>(lengths,other_lengths);
sub_rect->set_location(point<3>(location_offsets[i],0,0));
break;
case dimension::y:
sub_rect = std::make_shared<p_rect>(other_lengths,lengths);
sub_rect->set_location(point<3>(0,location_offsets[i],0));
break;
}
out->add_child(sub_rect);
sub_rect->set_display_style(this->display_style);
}
out->set_location(this->get_location());
auto p = get_parent().lock();
if (p == nullptr) {
auto scn_ = get_scene().lock();
if (scn_) {
// this node is the root of a scene; replace it with the new node out
scn_->set_root(out);
} // TODO: check on possible memory leak from this?
} else {
// remove this node from parent and replace it with out.
p->remove_child(shared_from_this());
p->add_child(out);
}
return out;
}
std::shared_ptr<p_rect> p_rect::merge(std::shared_ptr<node> parent, dimension dim) {
if (parent->get_children().empty()) {
throw std::runtime_error("children empty in p_rect::merge");
}
auto zero_child = std::dynamic_pointer_cast<p_rect>(parent->get_children()[0]);
const std::vector<length> &lengths = zero_child->get_lengths(dim);
std::vector<length> other_lengths{};
// sort parent->get_children() by appropriate coordinate, x or y,
// depending on the value of dim
std::vector<std::shared_ptr<node>> sorted_children = parent->get_children();
std::sort(sorted_children.begin(),sorted_children.end(),
[dim](std::shared_ptr<node> a, std::shared_ptr<node> b) {
switch (dim) {
case dimension::x:
return a->get_location().x < b->get_location().x;
case dimension::y:
return a->get_location().y < b->get_location().y;
}
}
);
dimension other_dim = dim == dimension::x ? dimension::y : dimension::x;
for (auto child : sorted_children) {
auto p_rect_child = std::dynamic_pointer_cast<p_rect>(child);
if (p_rect_child->get_lengths(dim) != lengths) {
throw std::runtime_error("merging p_rects with different lengths");
}
// append p_rect_child's other lengths to other_lengths
auto child_other_lengths = p_rect_child->get_lengths(other_dim);
std::copy(child_other_lengths.cbegin(), child_other_lengths.cend(),std::back_inserter(other_lengths));
}
std::shared_ptr<p_rect> merged_rect;
switch (dim) {
case dimension::x:
merged_rect = std::make_shared<p_rect>(lengths,other_lengths);
break;
case dimension::y:
merged_rect = std::make_shared<p_rect>(other_lengths,lengths);
break;
}
merged_rect->set_location(parent->get_location());
auto grandparent = parent->get_parent();
if (auto gp = grandparent.lock()) {
gp->remove_child(parent);
merged_rect->set_parent(gp,true);
}
merged_rect->set_display_style(zero_child->display_style);
return merged_rect;
}
std::set<int> p_rect::get_split_points(dimension dim, unsigned int sub_rect_count) const {
int partitions;
switch (dim) {
case dimension::x:
partitions = x_lengths.size(); break;
case dimension::y:
partitions = y_lengths.size(); break;
}
if (sub_rect_count > partitions) {throw std::runtime_error("p_rect has too few partitions for requested number of sub-rects");}
std::set<int> split_points{};
unsigned int sub_rect_height = partitions / sub_rect_count;
if (sub_rect_height * sub_rect_count != partitions) {throw std::runtime_error("Height of p_rect is not a multiple of sub_rect_count");}
unsigned int current_split = sub_rect_height;
while (current_split < partitions) {
split_points.insert(current_split);
current_split += sub_rect_height;
}
return split_points;
}
std::shared_ptr<node> p_rect::split(dimension dim, int sub_rect_count) {
return split(dim,get_split_points(dim,sub_rect_count));
}
grid_node p_rect::get_grid_node() const {
std::vector<std::vector<int>> partition_vectors{{0},{0}};
std::vector<std::vector<length>> length_vectors{x_lengths,y_lengths};
int position;
for (int i = 0; i < 2; ++i) {
position = 0;
for (auto l : length_vectors[i]) {
position += l.val * unit_size;
partition_vectors[i].push_back(position);
}
}
return grid_node{width(),height(),partition_vectors[0], partition_vectors[1]};
}
/******** p_rect actions ********/
/*
bool flash_display_style::own_act() {
if (current_frame > end_frame) {return false;}
if (pause_during == 0) {return false;}
if (current_frame == change_frame) {
pr->set_display_style(ds);
return true;
}
if (current_frame == revert_frame) {
pr->set_display_style(original_ds);
if (pause_after > 0) {return true;}
else {return false;}
}
return true;
}*/<commit_msg>fix sorting order<commit_after>#include "p_rect.h"
#include "algebra.h"
#include <stdexcept>
#include <typeinfo>
#include <algorithm>
#include <iterator>
using liven::scene;
using liven::view;
using liven::viewer;
using liven::node;
using liven::located;
using liven::dimension;
using liven::ascii_image;
using liven::ascii_viewer;
using liven::point;
using liven::rect;
using liven::grid_node;
bool operator==(const length &lhs, const length &rhs) {return !(lhs < rhs) && !(rhs < lhs);}
bool operator< (const length &lhs, const length &rhs) {
if (lhs.val < rhs.val) {return true;}
else if (lhs.val > rhs.val) {return false;}
else {
// lhs.val == rhs.val
return lhs.name < rhs.name;
}
}
located<rect,2> p_rect::own_bounding_rect() const {
return located<rect,2>(rect(width()+1,height()+1),get_location());
}
int p_rect::width_in_units() const {
int out = 0;
for (auto it = x_lengths.begin(); it != x_lengths.end(); ++it) {out += it->val;}
return out;
}
int p_rect::height_in_units() const {
int out = 0;
for (auto it = y_lengths.begin(); it != y_lengths.end(); ++it) {out += it->val;}
return out;
}
int p_rect::width() const {
return width_in_units() * unit_size;
}
int p_rect::height() const {
return height_in_units() * unit_size;
}
std::map<length,int> p_rect::get_length_frequency_map(dimension dim) const {
std::map<length,int> out{};
for (auto len : get_lengths(dim)) {++out[len];}
return out;
}
std::map<std::string,int> p_rect::get_var_coeff_map(dimension dim) const {
std::map<std::string,int> out{};
auto lengths = get_lengths(dim);
for (auto len : lengths) {
std::string name{};
if (len.name == "1") {name = "";}
else (name = len.name);
++out[name];
}
return out;
}
const std::vector<length> &p_rect::get_lengths(dimension dim) const {
switch (dim) {
case dimension::x:
return x_lengths;
case dimension::y:
return y_lengths;
}
}
void p_rect::swap_x_y() {
x_lengths.swap(y_lengths);
}
std::string p_rect::x_label_text() const {
return p_rect::label_text(dimension::x);
}
std::string p_rect::y_label_text() const {
return p_rect::label_text(dimension::y);
}
std::string p_rect::get_factored_string() const {
return algebra::enclose(x_label_text()) + algebra::enclose(y_label_text());
}
std::string p_rect::get_expanded_string() const {
return algebra::sum_to_string(algebra::expand(get_var_coeff_map(dimension::x),get_var_coeff_map(dimension::y)));
}
std::string p_rect::label_text(dimension dim) const {
return algebra::sum_to_string(get_var_coeff_map(dim));
}
void p_rect::set_display_style(display_style_type ds) {
display_style = ds;
switch (ds) {
case display_style_type::empty:
show_interior_lines = false;
show_sub_rect_labels = false;
show_center_factored = false;
show_center_expanded = false;
break;
case display_style_type::labels_and_lines:
show_interior_lines = true;
show_sub_rect_labels = true;
show_center_factored = false;
show_center_expanded = false;
break;
case display_style_type::center_factored:
show_interior_lines = false;
show_sub_rect_labels = false;
show_center_factored = true;
show_center_expanded = false;
break;
case display_style_type::center_expanded:
show_interior_lines = false;
show_sub_rect_labels = false;
show_center_factored = false;
show_center_expanded = true;
}
}
p_rect::display_style_type p_rect::get_display_style() {
return display_style;
}
void p_rect::set_children_display_style(std::shared_ptr<node> n, display_style_type ds) {
for (auto child : n->get_children()) {
std::dynamic_pointer_cast<p_rect>(child)->set_display_style(ds);
}
}
std::shared_ptr<node> p_rect::split(dimension dim,std::set<int> split_points) {
auto out = std::make_shared<node>();
std::vector<length> split_lengths;
std::vector<length> other_lengths;
switch(dim) {
case dimension::x:
split_lengths = x_lengths;
other_lengths = y_lengths;
break;
case dimension::y:
split_lengths = y_lengths;
other_lengths = x_lengths;
break;
}
int low = 0;
int low_units = 0;
int low_coordinates = 0;
std::vector<std::vector<length>> out_split_lengths = {};
std::vector<int> location_offsets = {};
split_points.insert(split_lengths.size());
for (auto split_point : split_points) {
if (split_point < 1) {throw std::out_of_range("split_point less than 1");}
if (split_point > split_lengths.size()) {throw std::out_of_range("split_point past the end");}
out_split_lengths.push_back(std::vector<length>(split_lengths.begin() + low,split_lengths.begin() + split_point));
location_offsets.push_back(low_coordinates);
for (int i = low; i < split_point; ++i) {
low_units += split_lengths[i].val;
}
low_coordinates = low_units * unit_size;
low = split_point;
}
std::shared_ptr<p_rect> sub_rect;
for (int i = 0; i < out_split_lengths.size(); ++i) {
auto lengths = out_split_lengths[i];
switch(dim) {
case dimension::x:
sub_rect = std::make_shared<p_rect>(lengths,other_lengths);
sub_rect->set_location(point<3>(location_offsets[i],0,0));
break;
case dimension::y:
sub_rect = std::make_shared<p_rect>(other_lengths,lengths);
sub_rect->set_location(point<3>(0,location_offsets[i],0));
break;
}
out->add_child(sub_rect);
sub_rect->set_display_style(this->display_style);
}
out->set_location(this->get_location());
auto p = get_parent().lock();
if (p == nullptr) {
auto scn_ = get_scene().lock();
if (scn_) {
// this node is the root of a scene; replace it with the new node out
scn_->set_root(out);
} // TODO: check on possible memory leak from this?
} else {
// remove this node from parent and replace it with out.
p->remove_child(shared_from_this());
p->add_child(out);
}
return out;
}
std::shared_ptr<p_rect> p_rect::merge(std::shared_ptr<node> parent, dimension dim) {
if (parent->get_children().empty()) {
throw std::runtime_error("children empty in p_rect::merge");
}
auto zero_child = std::dynamic_pointer_cast<p_rect>(parent->get_children()[0]);
const std::vector<length> &lengths = zero_child->get_lengths(dim);
std::vector<length> other_lengths{};
// sort parent->get_children() by appropriate coordinate, x or y,
// depending on the value of dim
std::vector<std::shared_ptr<node>> sorted_children = parent->get_children();
std::sort(sorted_children.begin(),sorted_children.end(),
[dim](std::shared_ptr<node> a, std::shared_ptr<node> b) {
switch (dim) {
case dimension::x:
return a->get_location().y < b->get_location().y;
case dimension::y:
return a->get_location().x < b->get_location().x;
}
}
);
dimension other_dim = dim == dimension::x ? dimension::y : dimension::x;
for (auto child : sorted_children) {
auto p_rect_child = std::dynamic_pointer_cast<p_rect>(child);
if (p_rect_child->get_lengths(dim) != lengths) {
throw std::runtime_error("merging p_rects with different lengths");
}
// append p_rect_child's other lengths to other_lengths
auto child_other_lengths = p_rect_child->get_lengths(other_dim);
std::copy(child_other_lengths.cbegin(), child_other_lengths.cend(),std::back_inserter(other_lengths));
}
std::shared_ptr<p_rect> merged_rect;
switch (dim) {
case dimension::x:
merged_rect = std::make_shared<p_rect>(lengths,other_lengths);
break;
case dimension::y:
merged_rect = std::make_shared<p_rect>(other_lengths,lengths);
break;
}
merged_rect->set_location(parent->get_location());
auto grandparent = parent->get_parent();
if (auto gp = grandparent.lock()) {
gp->remove_child(parent);
merged_rect->set_parent(gp,true);
}
merged_rect->set_display_style(zero_child->display_style);
return merged_rect;
}
std::set<int> p_rect::get_split_points(dimension dim, unsigned int sub_rect_count) const {
int partitions;
switch (dim) {
case dimension::x:
partitions = x_lengths.size(); break;
case dimension::y:
partitions = y_lengths.size(); break;
}
if (sub_rect_count > partitions) {throw std::runtime_error("p_rect has too few partitions for requested number of sub-rects");}
std::set<int> split_points{};
unsigned int sub_rect_height = partitions / sub_rect_count;
if (sub_rect_height * sub_rect_count != partitions) {throw std::runtime_error("Height of p_rect is not a multiple of sub_rect_count");}
unsigned int current_split = sub_rect_height;
while (current_split < partitions) {
split_points.insert(current_split);
current_split += sub_rect_height;
}
return split_points;
}
std::shared_ptr<node> p_rect::split(dimension dim, int sub_rect_count) {
return split(dim,get_split_points(dim,sub_rect_count));
}
grid_node p_rect::get_grid_node() const {
std::vector<std::vector<int>> partition_vectors{{0},{0}};
std::vector<std::vector<length>> length_vectors{x_lengths,y_lengths};
int position;
for (int i = 0; i < 2; ++i) {
position = 0;
for (auto l : length_vectors[i]) {
position += l.val * unit_size;
partition_vectors[i].push_back(position);
}
}
return grid_node{width(),height(),partition_vectors[0], partition_vectors[1]};
}
/******** p_rect actions ********/
/*
bool flash_display_style::own_act() {
if (current_frame > end_frame) {return false;}
if (pause_during == 0) {return false;}
if (current_frame == change_frame) {
pr->set_display_style(ds);
return true;
}
if (current_frame == revert_frame) {
pr->set_display_style(original_ds);
if (pause_after > 0) {return true;}
else {return false;}
}
return true;
}*/<|endoftext|> |
<commit_before><commit_msg>Fix: 2022-06-01<commit_after><|endoftext|> |
<commit_before><commit_msg>Added printed output, MOST OF THE THINGS WORKgit add .!<commit_after><|endoftext|> |
<commit_before><commit_msg>Correctly get Nth FILE_UIElement.<commit_after><|endoftext|> |
<commit_before>/*
* Copyright(c) Sophist Solutions, Inc. 1990-2020. All rights reserved
*/
#include "Stroika/Frameworks/StroikaPreComp.h"
#include <cstdlib>
#include <iostream>
#include "Stroika/Foundation/Characters/String_Constant.h"
#include "Stroika/Foundation/Characters/ToString.h"
#include "Stroika/Foundation/Debug/Fatal.h"
#include "Stroika/Foundation/Execution/CommandLine.h"
#include "Stroika/Foundation/Execution/Finally.h"
#include "Stroika/Foundation/Execution/SignalHandlers.h"
#include "Stroika/Foundation/Execution/Thread.h"
#if qPlatform_Windows
#include "Stroika/Foundation/Execution/Platform/Windows/Exception.h"
#include "Stroika/Foundation/Execution/Platform/Windows/StructuredException.h"
#endif
#include "Stroika/Frameworks/Service/Main.h"
#include "AppVersion.h"
#include "Service.h"
/**
* \file
*
* SAMPLE CODE
*
* Sample Simple Service Application
*
* This sample demonstrates a few Stroika features.
*
* o Creating a service application (one that can be automatically started/stopped by
* the OS, and one where you can query the status, check process ID, etc)
*
* o Simple example of command line processing
*
* o Simple example of Logging (to syslog or windows log or other)
*/
using namespace std;
using namespace Stroika::Foundation;
using namespace Stroika::Frameworks::Service;
using Characters::String_Constant;
using Containers::Sequence;
using Execution::SignalHandler;
using Execution::SignalHandlerRegistry;
using Execution::Thread;
#if qUseLogger
#include "Stroika/Foundation/Debug/BackTrace.h"
#include "Stroika/Foundation/Execution/Logger.h"
using Execution::Logger;
#endif
namespace {
void FatalErorrHandler_ (const Characters::SDKChar* msg) noexcept
{
Thread::SuppressInterruptionInContext suppressCtx;
DbgTrace (SDKSTR ("Fatal Error %s encountered"), msg);
#if qUseLogger
Logger::Get ().Log (Logger::Priority::eCriticalError, L"Fatal Error: %s; Aborting...", String::FromSDKString (msg).c_str ());
Logger::Get ().Log (Logger::Priority::eCriticalError, L"Backtrace: %s", Debug::BackTrace ().c_str ());
if (std::exception_ptr exc = std::current_exception ()) {
Logger::Get ().Log (Logger::Priority::eCriticalError, L"Uncaught exception: %s", Characters::ToString (exc).c_str ());
}
Logger::Get ().Flush ();
#endif
std::_Exit (EXIT_FAILURE); // skip
}
void FatalSignalHandler_ (Execution::SignalID signal) noexcept
{
Thread::SuppressInterruptionInContext suppressCtx;
DbgTrace (L"Fatal Signal encountered: %s", Execution::SignalToName (signal).c_str ());
#if qUseLogger
Logger::Get ().Log (Logger::Priority::eCriticalError, L"Fatal Signal: %s; Aborting...", Execution::SignalToName (signal).c_str ());
Logger::Get ().Log (Logger::Priority::eCriticalError, L"Backtrace: %s", Debug::BackTrace ().c_str ());
Logger::Get ().Flush ();
#endif
std::_Exit (EXIT_FAILURE); // skip
}
}
namespace {
void ShowUsage_ (const Main& m, const Execution::InvalidCommandLineArgument& e = Execution::InvalidCommandLineArgument ())
{
if (not e.fMessage.empty ()) {
cerr << "Error: " << e.fMessage.AsUTF8 () << endl;
cerr << endl;
}
cerr << "Usage: " << m.GetServiceDescription ().fRegistrationName.AsNarrowSDKString () << " [options] where options can be :\n ";
if (m.GetServiceIntegrationFeatures ().Contains (Main::ServiceIntegrationFeatures::eInstall)) {
cerr << "\t--" << Characters::WideStringToNarrowSDKString (Main::CommandNames::kInstall) << " /* Install service (only when debugging - should use real installer like WIX) */" << endl;
cerr << "\t--" << Characters::WideStringToNarrowSDKString (Main::CommandNames::kUnInstall) << " /* UnInstall service (only when debugging - should use real installer like WIX) */" << endl;
}
cerr << "\t--" << Characters::WideStringToNarrowSDKString (Main::CommandNames::kRunAsService) << " /* Run this process as a service (doesn't exit until the serivce is done ...) */" << endl;
cerr << "\t--" << Characters::WideStringToNarrowSDKString (Main::CommandNames::kRunDirectly) << " /* Run this process as a directly (doesn't exit until the serivce is done ...) but not using service infrastructure */" << endl;
cerr << "\t--" << Characters::WideStringToNarrowSDKString (Main::CommandNames::kStart) << " /* Service/Control Function: Start the service */" << endl;
cerr << "\t--" << Characters::WideStringToNarrowSDKString (Main::CommandNames::kStop) << " /* Service/Control Function: Stop the service */" << endl;
cerr << "\t--" << Characters::WideStringToNarrowSDKString (Main::CommandNames::kForcedStop) << " /* Service/Control Function: Forced stop the service (after trying to normally stop) */" << endl;
cerr << "\t--" << Characters::WideStringToNarrowSDKString (Main::CommandNames::kRestart) << " /* Service/Control Function: Stop and then re-start the service (ok if already stopped) */" << endl;
cerr << "\t--" << Characters::WideStringToNarrowSDKString (Main::CommandNames::kForcedRestart) << " /* Service/Control Function: Stop (force if needed) and then re-start the service (ok if already stopped) */" << endl;
cerr << "\t--" << Characters::WideStringToNarrowSDKString (Main::CommandNames::kReloadConfiguration) << " /* Reload service configuration */" << endl;
cerr << "\t--" << Characters::WideStringToNarrowSDKString (Main::CommandNames::kPause) << " /* Service/Control Function: Pause the service */" << endl;
cerr << "\t--" << Characters::WideStringToNarrowSDKString (Main::CommandNames::kContinue) << " /* Service/Control Function: Continue the paused service */" << endl;
cerr << "\t--Status /* Service/Control Function: Print status of running service */ " << endl;
cerr << "\t--Version /* print this application version */ " << endl;
cerr << "\t--run2Idle /* run2Idle (@todo TDB) */ " << endl;
cerr << "\t--help /* Print this help. */ " << endl;
cerr << endl
<< "\tExtra unrecognized parameters for start/restart, and forcedrestart operations will be passed along to the actual service process" << endl;
cerr << endl;
}
}
int main (int argc, const char* argv[])
{
Debug::TraceContextBumper ctx{Stroika_Foundation_Debug_OptionalizeTraceArgs (L"main", L"argv=%s", Characters::ToString (vector<const char*>{argv, argv + argc}).c_str ())};
#if qStroika_Foundation_Exection_Thread_SupportThreadStatistics
[[maybe_unused]] auto&& cleanupReport = Execution::Finally ([] () {
DbgTrace (L"Exiting main with thread %s running", Characters::ToString (Execution::Thread::GetStatistics ().fRunningThreads).c_str ());
});
#endif
/*
* This allows for safe signals to be managed in a threadsafe way
*/
SignalHandlerRegistry::SafeSignalsManager safeSignals;
/*
* Setup basic (optional) error handling.
*/
#if qPlatform_Windows
Execution::Platform::Windows::RegisterDefaultHandler_invalid_parameter ();
Execution::Platform::Windows::RegisterDefaultHandler_StructuredException ();
#endif
Debug::RegisterDefaultFatalErrorHandlers (FatalErorrHandler_); // override the default handler to emit message via Logger
/*
* SetStandardCrashHandlerSignals not really needed, but helpful for many applications so you get a decent log message/debugging on crash.
*/
SignalHandlerRegistry::Get ().SetStandardCrashHandlerSignals (SignalHandler{FatalSignalHandler_, SignalHandler::Type::eDirect});
/*
* Ignore SIGPIPE is common practice/helpful in POSIX, but not required by the service manager.
*/
#if qPlatform_POSIX
SignalHandlerRegistry::Get ().SetSignalHandlers (SIGPIPE, SignalHandlerRegistry::kIGNORED);
#endif
/*
* Setup Logging to the OS logging facility.
*/
#if qUseLogger
[[maybe_unused]] auto&& cleanup = Execution::Finally ([] () {
Logger::ShutdownSingleton (); // make sure Logger threads shutdown before the end of main (), and flush buffered messages
});
#if qHas_Syslog
Logger::Get ().SetAppender (make_shared<Logger::SysLogAppender> (L"Stroika-Sample-Service"));
#elif qPlatform_Windows
Logger::Get ().SetAppender (make_shared<Logger::WindowsEventLogAppender> (L"Stroika-Sample-Service"));
#endif
/*
* Optional - use buffering feature
* Optional - use suppress duplicates in a 15 second window
*/
Logger::Get ().SetBufferingEnabled (true);
Logger::Get ().SetSuppressDuplicates (15s);
#endif
/*
* Parse command line arguments, and start looking at options.
*/
Sequence<String> args = Execution::ParseCommandLine (argc, argv);
shared_ptr<Main::IServiceIntegrationRep> serviceIntegrationRep = Main::mkDefaultServiceIntegrationRep ();
if (Execution::MatchesCommandLineArgument (args, L"run2Idle")) {
cerr << "Warning: RunTilIdleService not really done correctly yet - no notion of idle" << endl;
serviceIntegrationRep = make_shared<Main::RunTilIdleService> ();
}
#if qUseLogger
serviceIntegrationRep = make_shared<Main::LoggerServiceWrapper> (serviceIntegrationRep);
#endif
/*
* Create service handler instance.
*/
Main m (make_shared<Samples::Service::SampleAppServiceRep> (), serviceIntegrationRep);
/*
* Run request.
*/
try {
if (Execution::MatchesCommandLineArgument (args, L"status")) {
cout << m.GetServiceStatusMessage ().AsUTF8<string> ();
return EXIT_SUCCESS;
}
else if (Execution::MatchesCommandLineArgument (args, L"help")) {
ShowUsage_ (m);
return EXIT_SUCCESS;
}
else if (Execution::MatchesCommandLineArgument (args, L"version")) {
cout << m.GetServiceDescription ().fPrettyName.AsNarrowSDKString () << ": " << Characters::ToString (AppVersion::kVersion).AsNarrowSDKString () << endl;
return EXIT_SUCCESS;
}
else {
/*
* Run the commands, and capture/display exceptions
*/
m.Run (args);
}
}
catch (const Execution::InvalidCommandLineArgument& e) {
ShowUsage_ (m, e);
}
catch (...) {
String exceptMsg = Characters::ToString (current_exception ());
#if qUseLogger
Logger::Get ().Log (Logger::Priority::eError, L"%s", exceptMsg.c_str ());
#endif
cerr << "FAILED: " << exceptMsg.AsNarrowSDKString () << endl;
return EXIT_FAILURE;
}
return EXIT_SUCCESS;
}
<commit_msg>react to name change: Debug::BackTrace::Capture ()<commit_after>/*
* Copyright(c) Sophist Solutions, Inc. 1990-2020. All rights reserved
*/
#include "Stroika/Frameworks/StroikaPreComp.h"
#include <cstdlib>
#include <iostream>
#include "Stroika/Foundation/Characters/String_Constant.h"
#include "Stroika/Foundation/Characters/ToString.h"
#include "Stroika/Foundation/Debug/Fatal.h"
#include "Stroika/Foundation/Execution/CommandLine.h"
#include "Stroika/Foundation/Execution/Finally.h"
#include "Stroika/Foundation/Execution/SignalHandlers.h"
#include "Stroika/Foundation/Execution/Thread.h"
#if qPlatform_Windows
#include "Stroika/Foundation/Execution/Platform/Windows/Exception.h"
#include "Stroika/Foundation/Execution/Platform/Windows/StructuredException.h"
#endif
#include "Stroika/Frameworks/Service/Main.h"
#include "AppVersion.h"
#include "Service.h"
/**
* \file
*
* SAMPLE CODE
*
* Sample Simple Service Application
*
* This sample demonstrates a few Stroika features.
*
* o Creating a service application (one that can be automatically started/stopped by
* the OS, and one where you can query the status, check process ID, etc)
*
* o Simple example of command line processing
*
* o Simple example of Logging (to syslog or windows log or other)
*/
using namespace std;
using namespace Stroika::Foundation;
using namespace Stroika::Frameworks::Service;
using Characters::String_Constant;
using Containers::Sequence;
using Execution::SignalHandler;
using Execution::SignalHandlerRegistry;
using Execution::Thread;
#if qUseLogger
#include "Stroika/Foundation/Debug/BackTrace.h"
#include "Stroika/Foundation/Execution/Logger.h"
using Execution::Logger;
#endif
namespace {
void FatalErorrHandler_ (const Characters::SDKChar* msg) noexcept
{
Thread::SuppressInterruptionInContext suppressCtx;
DbgTrace (SDKSTR ("Fatal Error %s encountered"), msg);
#if qUseLogger
Logger::Get ().Log (Logger::Priority::eCriticalError, L"Fatal Error: %s; Aborting...", String::FromSDKString (msg).c_str ());
Logger::Get ().Log (Logger::Priority::eCriticalError, L"Backtrace: %s", Debug::BackTrace::Capture ().c_str ());
if (std::exception_ptr exc = std::current_exception ()) {
Logger::Get ().Log (Logger::Priority::eCriticalError, L"Uncaught exception: %s", Characters::ToString (exc).c_str ());
}
Logger::Get ().Flush ();
#endif
std::_Exit (EXIT_FAILURE); // skip
}
void FatalSignalHandler_ (Execution::SignalID signal) noexcept
{
Thread::SuppressInterruptionInContext suppressCtx;
DbgTrace (L"Fatal Signal encountered: %s", Execution::SignalToName (signal).c_str ());
#if qUseLogger
Logger::Get ().Log (Logger::Priority::eCriticalError, L"Fatal Signal: %s; Aborting...", Execution::SignalToName (signal).c_str ());
Logger::Get ().Log (Logger::Priority::eCriticalError, L"Backtrace: %s", Debug::BackTrace ().c_str ());
Logger::Get ().Flush ();
#endif
std::_Exit (EXIT_FAILURE); // skip
}
}
namespace {
void ShowUsage_ (const Main& m, const Execution::InvalidCommandLineArgument& e = Execution::InvalidCommandLineArgument ())
{
if (not e.fMessage.empty ()) {
cerr << "Error: " << e.fMessage.AsUTF8 () << endl;
cerr << endl;
}
cerr << "Usage: " << m.GetServiceDescription ().fRegistrationName.AsNarrowSDKString () << " [options] where options can be :\n ";
if (m.GetServiceIntegrationFeatures ().Contains (Main::ServiceIntegrationFeatures::eInstall)) {
cerr << "\t--" << Characters::WideStringToNarrowSDKString (Main::CommandNames::kInstall) << " /* Install service (only when debugging - should use real installer like WIX) */" << endl;
cerr << "\t--" << Characters::WideStringToNarrowSDKString (Main::CommandNames::kUnInstall) << " /* UnInstall service (only when debugging - should use real installer like WIX) */" << endl;
}
cerr << "\t--" << Characters::WideStringToNarrowSDKString (Main::CommandNames::kRunAsService) << " /* Run this process as a service (doesn't exit until the serivce is done ...) */" << endl;
cerr << "\t--" << Characters::WideStringToNarrowSDKString (Main::CommandNames::kRunDirectly) << " /* Run this process as a directly (doesn't exit until the serivce is done ...) but not using service infrastructure */" << endl;
cerr << "\t--" << Characters::WideStringToNarrowSDKString (Main::CommandNames::kStart) << " /* Service/Control Function: Start the service */" << endl;
cerr << "\t--" << Characters::WideStringToNarrowSDKString (Main::CommandNames::kStop) << " /* Service/Control Function: Stop the service */" << endl;
cerr << "\t--" << Characters::WideStringToNarrowSDKString (Main::CommandNames::kForcedStop) << " /* Service/Control Function: Forced stop the service (after trying to normally stop) */" << endl;
cerr << "\t--" << Characters::WideStringToNarrowSDKString (Main::CommandNames::kRestart) << " /* Service/Control Function: Stop and then re-start the service (ok if already stopped) */" << endl;
cerr << "\t--" << Characters::WideStringToNarrowSDKString (Main::CommandNames::kForcedRestart) << " /* Service/Control Function: Stop (force if needed) and then re-start the service (ok if already stopped) */" << endl;
cerr << "\t--" << Characters::WideStringToNarrowSDKString (Main::CommandNames::kReloadConfiguration) << " /* Reload service configuration */" << endl;
cerr << "\t--" << Characters::WideStringToNarrowSDKString (Main::CommandNames::kPause) << " /* Service/Control Function: Pause the service */" << endl;
cerr << "\t--" << Characters::WideStringToNarrowSDKString (Main::CommandNames::kContinue) << " /* Service/Control Function: Continue the paused service */" << endl;
cerr << "\t--Status /* Service/Control Function: Print status of running service */ " << endl;
cerr << "\t--Version /* print this application version */ " << endl;
cerr << "\t--run2Idle /* run2Idle (@todo TDB) */ " << endl;
cerr << "\t--help /* Print this help. */ " << endl;
cerr << endl
<< "\tExtra unrecognized parameters for start/restart, and forcedrestart operations will be passed along to the actual service process" << endl;
cerr << endl;
}
}
int main (int argc, const char* argv[])
{
Debug::TraceContextBumper ctx{Stroika_Foundation_Debug_OptionalizeTraceArgs (L"main", L"argv=%s", Characters::ToString (vector<const char*>{argv, argv + argc}).c_str ())};
#if qStroika_Foundation_Exection_Thread_SupportThreadStatistics
[[maybe_unused]] auto&& cleanupReport = Execution::Finally ([] () {
DbgTrace (L"Exiting main with thread %s running", Characters::ToString (Execution::Thread::GetStatistics ().fRunningThreads).c_str ());
});
#endif
/*
* This allows for safe signals to be managed in a threadsafe way
*/
SignalHandlerRegistry::SafeSignalsManager safeSignals;
/*
* Setup basic (optional) error handling.
*/
#if qPlatform_Windows
Execution::Platform::Windows::RegisterDefaultHandler_invalid_parameter ();
Execution::Platform::Windows::RegisterDefaultHandler_StructuredException ();
#endif
Debug::RegisterDefaultFatalErrorHandlers (FatalErorrHandler_); // override the default handler to emit message via Logger
/*
* SetStandardCrashHandlerSignals not really needed, but helpful for many applications so you get a decent log message/debugging on crash.
*/
SignalHandlerRegistry::Get ().SetStandardCrashHandlerSignals (SignalHandler{FatalSignalHandler_, SignalHandler::Type::eDirect});
/*
* Ignore SIGPIPE is common practice/helpful in POSIX, but not required by the service manager.
*/
#if qPlatform_POSIX
SignalHandlerRegistry::Get ().SetSignalHandlers (SIGPIPE, SignalHandlerRegistry::kIGNORED);
#endif
/*
* Setup Logging to the OS logging facility.
*/
#if qUseLogger
[[maybe_unused]] auto&& cleanup = Execution::Finally ([] () {
Logger::ShutdownSingleton (); // make sure Logger threads shutdown before the end of main (), and flush buffered messages
});
#if qHas_Syslog
Logger::Get ().SetAppender (make_shared<Logger::SysLogAppender> (L"Stroika-Sample-Service"));
#elif qPlatform_Windows
Logger::Get ().SetAppender (make_shared<Logger::WindowsEventLogAppender> (L"Stroika-Sample-Service"));
#endif
/*
* Optional - use buffering feature
* Optional - use suppress duplicates in a 15 second window
*/
Logger::Get ().SetBufferingEnabled (true);
Logger::Get ().SetSuppressDuplicates (15s);
#endif
/*
* Parse command line arguments, and start looking at options.
*/
Sequence<String> args = Execution::ParseCommandLine (argc, argv);
shared_ptr<Main::IServiceIntegrationRep> serviceIntegrationRep = Main::mkDefaultServiceIntegrationRep ();
if (Execution::MatchesCommandLineArgument (args, L"run2Idle")) {
cerr << "Warning: RunTilIdleService not really done correctly yet - no notion of idle" << endl;
serviceIntegrationRep = make_shared<Main::RunTilIdleService> ();
}
#if qUseLogger
serviceIntegrationRep = make_shared<Main::LoggerServiceWrapper> (serviceIntegrationRep);
#endif
/*
* Create service handler instance.
*/
Main m (make_shared<Samples::Service::SampleAppServiceRep> (), serviceIntegrationRep);
/*
* Run request.
*/
try {
if (Execution::MatchesCommandLineArgument (args, L"status")) {
cout << m.GetServiceStatusMessage ().AsUTF8<string> ();
return EXIT_SUCCESS;
}
else if (Execution::MatchesCommandLineArgument (args, L"help")) {
ShowUsage_ (m);
return EXIT_SUCCESS;
}
else if (Execution::MatchesCommandLineArgument (args, L"version")) {
cout << m.GetServiceDescription ().fPrettyName.AsNarrowSDKString () << ": " << Characters::ToString (AppVersion::kVersion).AsNarrowSDKString () << endl;
return EXIT_SUCCESS;
}
else {
/*
* Run the commands, and capture/display exceptions
*/
m.Run (args);
}
}
catch (const Execution::InvalidCommandLineArgument& e) {
ShowUsage_ (m, e);
}
catch (...) {
String exceptMsg = Characters::ToString (current_exception ());
#if qUseLogger
Logger::Get ().Log (Logger::Priority::eError, L"%s", exceptMsg.c_str ());
#endif
cerr << "FAILED: " << exceptMsg.AsNarrowSDKString () << endl;
return EXIT_FAILURE;
}
return EXIT_SUCCESS;
}
<|endoftext|> |
<commit_before>//
// Copyright (c) 2018 Rokas Kupstys
//
// 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 <Urho3D/Core/ProcessUtils.h>
#include <Urho3D/Input/Input.h>
#include "EditorEvents.h"
#include "Editor.h"
#include "Tab.h"
namespace Urho3D
{
Tab::Tab(Context* context)
: Object(context)
, inspector_(context)
{
SetID(GenerateUUID());
SubscribeToEvent(E_EDITORPROJECTSAVING, [&](StringHash, VariantMap& args) {
using namespace EditorProjectSaving;
JSONValue& root = *(JSONValue*)args[P_ROOT].GetVoidPtr();
auto& tabs = root["tabs"];
JSONValue tab;
OnSaveProject(tab);
tabs.Push(tab);
});
}
void Tab::Initialize(const String& title, const Vector2& initSize, ui::DockSlot initPosition, const String& afterDockName)
{
initialSize_ = initSize;
placePosition_ = initPosition;
placeAfter_ = afterDockName;
title_ = title;
SetID(GenerateUUID());
}
Tab::~Tab()
{
SendEvent(E_EDITORTABCLOSED, EditorTabClosed::P_TAB, this);
}
bool Tab::RenderWindow()
{
Input* input = GetSubsystem<Input>();
if (input->IsMouseVisible())
lastMousePosition_ = input->GetMousePosition();
bool wasRendered = isRendered_;
ui::SetNextDockPos(placeAfter_.Empty() ? nullptr : placeAfter_.CString(), placePosition_, ImGuiCond_FirstUseEver);
if (ui::BeginDock(uniqueTitle_.CString(), &open_, windowFlags_, ToImGui(initialSize_)))
{
if (open_)
{
IntRect tabRect = ToIntRect(ui::GetCurrentWindow()->InnerClipRect);
if (tabRect.IsInside(lastMousePosition_) == INSIDE)
{
if (!ui::IsWindowFocused() && ui::IsWindowHovered() && input->GetMouseButtonDown(MOUSEB_RIGHT))
ui::SetWindowFocus();
}
if (!wasRendered)
ui::SetWindowFocus();
isActive_ = ui::IsWindowFocused() && ui::IsDockActive();
open_ = RenderWindowContent();
isRendered_ = true;
}
}
else
{
isActive_ = false;
isRendered_ = false;
}
if (activateTab_)
{
ui::SetDockActive();
ui::SetWindowFocus();
open_ = true;
isActive_ = true;
activateTab_ = false;
}
ui::EndDock();
return open_;
}
void Tab::SetTitle(const String& title)
{
title_ = title;
UpdateUniqueTitle();
}
void Tab::UpdateUniqueTitle()
{
uniqueTitle_ = ToString("%s###%s", title_.CString(), id_.CString());
}
IntRect Tab::UpdateViewRect()
{
IntRect tabRect = ToIntRect(ui::GetCurrentWindow()->InnerClipRect);
tabRect += IntRect(0, static_cast<int>(ui::GetCursorPosY()), 0, 0);
return tabRect;
}
void Tab::OnSaveProject(JSONValue& tab)
{
tab["type"] = GetTypeName();
tab["uuid"] = GetID();
}
void Tab::OnLoadProject(const JSONValue& tab)
{
SetID(tab["uuid"].GetString());
}
void Tab::AutoPlace()
{
String afterTabName;
auto placement = ui::Slot_None;
auto tabs = GetSubsystem<Editor>()->GetContentTabs();
// Need a separate loop because we prefer consile (as per default layout) but it may come after hierarchy in tabs list.
for (const auto& openTab : tabs)
{
if (openTab == this)
continue;
if (openTab->GetTitle() == "Console")
{
if (afterTabName.Empty())
{
// Place after hierarchy if no content tab exist
afterTabName = openTab->GetUniqueTitle();
placement = ui::Slot_Top;
}
}
}
for (const auto& openTab : tabs)
{
if (openTab == this)
continue;
if (openTab->GetTitle() == "Hierarchy")
{
if (afterTabName.Empty())
{
// Place after hierarchy if no content tab exist
afterTabName = openTab->GetUniqueTitle();
placement = ui::Slot_Right;
}
}
else if (!openTab->IsUtility())
{
// Place after content tab
afterTabName = openTab->GetUniqueTitle();
placement = ui::Slot_Tab;
}
}
initialSize_ = {-1, GetGraphics()->GetHeight() * 0.9f};
placeAfter_ = afterTabName;
placePosition_ = placement;
}
}
<commit_msg>Editor: One more tweak to tab activation logic which was a little broken.<commit_after>//
// Copyright (c) 2018 Rokas Kupstys
//
// 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 <Urho3D/Core/ProcessUtils.h>
#include <Urho3D/Input/Input.h>
#include "EditorEvents.h"
#include "Editor.h"
#include "Tab.h"
namespace Urho3D
{
Tab::Tab(Context* context)
: Object(context)
, inspector_(context)
{
SetID(GenerateUUID());
SubscribeToEvent(E_EDITORPROJECTSAVING, [&](StringHash, VariantMap& args) {
using namespace EditorProjectSaving;
JSONValue& root = *(JSONValue*)args[P_ROOT].GetVoidPtr();
auto& tabs = root["tabs"];
JSONValue tab;
OnSaveProject(tab);
tabs.Push(tab);
});
}
void Tab::Initialize(const String& title, const Vector2& initSize, ui::DockSlot initPosition, const String& afterDockName)
{
initialSize_ = initSize;
placePosition_ = initPosition;
placeAfter_ = afterDockName;
title_ = title;
SetID(GenerateUUID());
}
Tab::~Tab()
{
SendEvent(E_EDITORTABCLOSED, EditorTabClosed::P_TAB, this);
}
bool Tab::RenderWindow()
{
Input* input = GetSubsystem<Input>();
if (input->IsMouseVisible())
lastMousePosition_ = input->GetMousePosition();
bool wasRendered = isRendered_;
ui::SetNextDockPos(placeAfter_.Empty() ? nullptr : placeAfter_.CString(), placePosition_, ImGuiCond_FirstUseEver);
if (ui::BeginDock(uniqueTitle_.CString(), &open_, windowFlags_, ToImGui(initialSize_)))
{
if (open_)
{
if (!ui::IsWindowFocused(ImGuiFocusedFlags_ChildWindows))
{
IntRect tabRect = ToIntRect(ui::GetCurrentWindow()->InnerClipRect);
if (!wasRendered || // Just activated
(tabRect.IsInside(lastMousePosition_) == INSIDE && ui::IsAnyMouseDown())) // Interacting
ui::SetWindowFocus();
}
isActive_ = ui::IsWindowFocused() && ui::IsDockActive();
open_ = RenderWindowContent();
isRendered_ = true;
}
}
else
{
isActive_ = false;
isRendered_ = false;
}
if (activateTab_)
{
ui::SetDockActive();
ui::SetWindowFocus();
open_ = true;
isActive_ = true;
activateTab_ = false;
}
ui::EndDock();
return open_;
}
void Tab::SetTitle(const String& title)
{
title_ = title;
UpdateUniqueTitle();
}
void Tab::UpdateUniqueTitle()
{
uniqueTitle_ = ToString("%s###%s", title_.CString(), id_.CString());
}
IntRect Tab::UpdateViewRect()
{
IntRect tabRect = ToIntRect(ui::GetCurrentWindow()->InnerClipRect);
tabRect += IntRect(0, static_cast<int>(ui::GetCursorPosY()), 0, 0);
return tabRect;
}
void Tab::OnSaveProject(JSONValue& tab)
{
tab["type"] = GetTypeName();
tab["uuid"] = GetID();
}
void Tab::OnLoadProject(const JSONValue& tab)
{
SetID(tab["uuid"].GetString());
}
void Tab::AutoPlace()
{
String afterTabName;
auto placement = ui::Slot_None;
auto tabs = GetSubsystem<Editor>()->GetContentTabs();
// Need a separate loop because we prefer consile (as per default layout) but it may come after hierarchy in tabs list.
for (const auto& openTab : tabs)
{
if (openTab == this)
continue;
if (openTab->GetTitle() == "Console")
{
if (afterTabName.Empty())
{
// Place after hierarchy if no content tab exist
afterTabName = openTab->GetUniqueTitle();
placement = ui::Slot_Top;
}
}
}
for (const auto& openTab : tabs)
{
if (openTab == this)
continue;
if (openTab->GetTitle() == "Hierarchy")
{
if (afterTabName.Empty())
{
// Place after hierarchy if no content tab exist
afterTabName = openTab->GetUniqueTitle();
placement = ui::Slot_Right;
}
}
else if (!openTab->IsUtility())
{
// Place after content tab
afterTabName = openTab->GetUniqueTitle();
placement = ui::Slot_Tab;
}
}
initialSize_ = {-1, GetGraphics()->GetHeight() * 0.9f};
placeAfter_ = afterTabName;
placePosition_ = placement;
}
}
<|endoftext|> |
<commit_before>/*
* yosys -- Yosys Open SYnthesis Suite
*
* Copyright (C) 2012 Clifford Wolf <[email protected]>
*
* Permission to use, copy, modify, and/or distribute this software for any
* purpose with or without fee is hereby granted, provided that the above
* copyright notice and this permission notice appear in all copies.
*
* THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
* WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
* MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
* ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
* WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
* ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
* OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
*
*/
// [[CITE]] Tarjan's strongly connected components algorithm
// Tarjan, R. E. (1972), "Depth-first search and linear graph algorithms", SIAM Journal on Computing 1 (2): 146-160, doi:10.1137/0201010
// http://en.wikipedia.org/wiki/Tarjan's_strongly_connected_components_algorithm
#include "kernel/register.h"
#include "kernel/celltypes.h"
#include "kernel/sigtools.h"
#include "kernel/log.h"
#include <stdlib.h>
#include <stdio.h>
#include <set>
USING_YOSYS_NAMESPACE
PRIVATE_NAMESPACE_BEGIN
struct SccWorker
{
RTLIL::Design *design;
RTLIL::Module *module;
SigMap sigmap;
CellTypes ct;
std::set<RTLIL::Cell*> workQueue;
std::map<RTLIL::Cell*, std::set<RTLIL::Cell*>> cellToNextCell;
std::map<RTLIL::Cell*, RTLIL::SigSpec> cellToPrevSig, cellToNextSig;
std::map<RTLIL::Cell*, std::pair<int, int>> cellLabels;
std::map<RTLIL::Cell*, int> cellDepth;
std::set<RTLIL::Cell*> cellsOnStack;
std::vector<RTLIL::Cell*> cellStack;
int labelCounter;
std::map<RTLIL::Cell*, int> cell2scc;
std::vector<std::set<RTLIL::Cell*>> sccList;
void run(RTLIL::Cell *cell, int depth, int maxDepth)
{
log_assert(workQueue.count(cell) > 0);
workQueue.erase(cell);
cellLabels[cell] = std::pair<int, int>(labelCounter, labelCounter);
labelCounter++;
cellsOnStack.insert(cell);
cellStack.push_back(cell);
if (maxDepth >= 0)
cellDepth[cell] = depth;
for (auto nextCell : cellToNextCell[cell])
if (cellLabels.count(nextCell) == 0) {
run(nextCell, depth+1, maxDepth);
cellLabels[cell].second = min(cellLabels[cell].second, cellLabels[nextCell].second);
} else
if (cellsOnStack.count(nextCell) > 0 && (maxDepth < 0 || cellDepth[nextCell] + maxDepth > depth)) {
cellLabels[cell].second = min(cellLabels[cell].second, cellLabels[nextCell].second);
}
if (cellLabels[cell].first == cellLabels[cell].second)
{
if (cellStack.back() == cell)
{
cellStack.pop_back();
cellsOnStack.erase(cell);
}
else
{
log("Found an SCC:");
std::set<RTLIL::Cell*> scc;
while (cellsOnStack.count(cell) > 0) {
RTLIL::Cell *c = cellStack.back();
cellStack.pop_back();
cellsOnStack.erase(c);
log(" %s", RTLIL::id2cstr(c->name));
cell2scc[c] = sccList.size();
scc.insert(c);
}
sccList.push_back(scc);
log("\n");
}
}
}
SccWorker(RTLIL::Design *design, RTLIL::Module *module, bool nofeedbackMode, bool allCellTypes, int maxDepth) :
design(design), module(module), sigmap(module)
{
if (module->processes.size() > 0) {
log("Skipping module %s as it contains processes (run 'proc' pass first).\n", module->name.c_str());
return;
}
if (allCellTypes) {
ct.setup(design);
} else {
ct.setup_internals();
ct.setup_stdcells();
}
SigPool selectedSignals;
SigSet<RTLIL::Cell*> sigToNextCells;
for (auto &it : module->wires_)
if (design->selected(module, it.second))
selectedSignals.add(sigmap(RTLIL::SigSpec(it.second)));
for (auto &it : module->cells_)
{
RTLIL::Cell *cell = it.second;
if (!design->selected(module, cell))
continue;
if (!allCellTypes && !ct.cell_known(cell->type))
continue;
workQueue.insert(cell);
RTLIL::SigSpec inputSignals, outputSignals;
for (auto &conn : cell->connections())
{
bool isInput = true, isOutput = true;
if (ct.cell_known(cell->type)) {
isInput = ct.cell_input(cell->type, conn.first);
isOutput = ct.cell_output(cell->type, conn.first);
}
RTLIL::SigSpec sig = selectedSignals.extract(sigmap(conn.second));
sig.sort_and_unify();
if (isInput)
inputSignals.append(sig);
if (isOutput)
outputSignals.append(sig);
}
inputSignals.sort_and_unify();
outputSignals.sort_and_unify();
cellToPrevSig[cell] = inputSignals;
cellToNextSig[cell] = outputSignals;
sigToNextCells.insert(inputSignals, cell);
}
for (auto cell : workQueue)
{
cellToNextCell[cell] = sigToNextCells.find(cellToNextSig[cell]);
if (!nofeedbackMode && cellToNextCell[cell].count(cell)) {
log("Found an SCC:");
std::set<RTLIL::Cell*> scc;
log(" %s", RTLIL::id2cstr(cell->name));
cell2scc[cell] = sccList.size();
scc.insert(cell);
sccList.push_back(scc);
log("\n");
}
}
labelCounter = 0;
cellLabels.clear();
while (!workQueue.empty())
{
RTLIL::Cell *cell = *workQueue.begin();
log_assert(cellStack.size() == 0);
cellDepth.clear();
run(cell, 0, maxDepth);
}
log("Found %d SCCs in module %s.\n", int(sccList.size()), RTLIL::id2cstr(module->name));
}
void select(RTLIL::Selection &sel)
{
for (int i = 0; i < int(sccList.size()); i++)
{
std::set<RTLIL::Cell*> &cells = sccList[i];
RTLIL::SigSpec prevsig, nextsig, sig;
for (auto cell : cells) {
sel.selected_members[module->name].insert(cell->name);
prevsig.append(cellToPrevSig[cell]);
nextsig.append(cellToNextSig[cell]);
}
prevsig.sort_and_unify();
nextsig.sort_and_unify();
sig = prevsig.extract(nextsig);
for (auto &chunk : sig.chunks())
if (chunk.wire != NULL)
sel.selected_members[module->name].insert(chunk.wire->name);
}
}
};
struct SccPass : public Pass {
SccPass() : Pass("scc", "detect strongly connected components (logic loops)") { }
virtual void help()
{
// |---v---|---v---|---v---|---v---|---v---|---v---|---v---|---v---|---v---|---v---|
log("\n");
log(" scc [options] [selection]\n");
log("\n");
log("This command identifies strongly connected components (aka logic loops) in the\n");
log("design.\n");
log("\n");
log(" -expect <num>\n");
log(" expect to find exactly <num> SSCs. A different number of SSCs will\n");
log(" produce an error.\n");
log("\n");
log(" -max_depth <num>\n");
log(" limit to loops not longer than the specified number of cells. This\n");
log(" can e.g. be useful in identifying small local loops in a module that\n");
log(" implements one large SCC.\n");
log("\n");
log(" -nofeedback\n");
log(" do not count cells that have their output fed back into one of their\n");
log(" inputs as single-cell scc.\n");
log("\n");
log(" -all_cell_types\n");
log(" Usually this command only considers internal non-memory cells. With\n");
log(" this option set, all cells are considered. For unknown cells all ports\n");
log(" are assumed to be bidirectional 'inout' ports.\n");
log("\n");
log(" -set_attr <name> <value>\n");
log(" -set_cell_attr <name> <value>\n");
log(" -set_wire_attr <name> <value>\n");
log(" set the specified attribute on all cells and/or wires that are part of\n");
log(" a logic loop. the special token {} in the value is replaced with a\n");
log(" unique identifier for the logic loop.\n");
log("\n");
log(" -select\n");
log(" replace the current selection with a selection of all cells and wires\n");
log(" that are part of a found logic loop\n");
log("\n");
}
virtual void execute(std::vector<std::string> args, RTLIL::Design *design)
{
std::map<std::string, std::string> setCellAttr, setWireAttr;
bool allCellTypes = false;
bool selectMode = false;
bool nofeedbackMode = false;
int maxDepth = -1;
int expect = -1;
log_header(design, "Executing SCC pass (detecting logic loops).\n");
size_t argidx;
for (argidx = 1; argidx < args.size(); argidx++) {
if (args[argidx] == "-max_depth" && argidx+1 < args.size()) {
maxDepth = atoi(args[++argidx].c_str());
continue;
}
if (args[argidx] == "-expect" && argidx+1 < args.size()) {
expect = atoi(args[++argidx].c_str());
continue;
}
if (args[argidx] == "-nofeedback") {
nofeedbackMode = true;
continue;
}
if (args[argidx] == "-all_cell_types") {
allCellTypes = true;
continue;
}
if (args[argidx] == "-set_attr" && argidx+2 < args.size()) {
setCellAttr[args[argidx+1]] = args[argidx+2];
setWireAttr[args[argidx+1]] = args[argidx+2];
argidx += 2;
continue;
}
if (args[argidx] == "-set_cell_attr" && argidx+2 < args.size()) {
setCellAttr[args[argidx+1]] = args[argidx+2];
argidx += 2;
continue;
}
if (args[argidx] == "-set_wire_attr" && argidx+2 < args.size()) {
setWireAttr[args[argidx+1]] = args[argidx+2];
argidx += 2;
continue;
}
if (args[argidx] == "-select") {
selectMode = true;
continue;
}
break;
}
int origSelectPos = design->selection_stack.size() - 1;
extra_args(args, argidx, design);
if (setCellAttr.size() > 0 || setWireAttr.size() > 0)
log_cmd_error("The -set*_attr options are not implemented at the moment!\n");
RTLIL::Selection newSelection(false);
int scc_counter = 0;
for (auto &mod_it : design->modules_)
if (design->selected(mod_it.second))
{
SccWorker worker(design, mod_it.second, nofeedbackMode, allCellTypes, maxDepth);
scc_counter += GetSize(worker.sccList);
if (selectMode)
worker.select(newSelection);
}
if (expect >= 0) {
if (scc_counter == expect)
log("Found and expected %d SCCs.\n", scc_counter);
else
log_error("Found %d SCCs but expected %d.\n", scc_counter, expect);
} else
log("Found %d SCCs.\n", scc_counter);
if (selectMode) {
log_assert(origSelectPos >= 0);
design->selection_stack[origSelectPos] = newSelection;
design->selection_stack[origSelectPos].optimize(design);
}
}
} SccPass;
PRIVATE_NAMESPACE_END
<commit_msg>Implemented "scc -set_attr"<commit_after>/*
* yosys -- Yosys Open SYnthesis Suite
*
* Copyright (C) 2012 Clifford Wolf <[email protected]>
*
* Permission to use, copy, modify, and/or distribute this software for any
* purpose with or without fee is hereby granted, provided that the above
* copyright notice and this permission notice appear in all copies.
*
* THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
* WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
* MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
* ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
* WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
* ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
* OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
*
*/
// [[CITE]] Tarjan's strongly connected components algorithm
// Tarjan, R. E. (1972), "Depth-first search and linear graph algorithms", SIAM Journal on Computing 1 (2): 146-160, doi:10.1137/0201010
// http://en.wikipedia.org/wiki/Tarjan's_strongly_connected_components_algorithm
#include "kernel/register.h"
#include "kernel/celltypes.h"
#include "kernel/sigtools.h"
#include "kernel/log.h"
#include <stdlib.h>
#include <stdio.h>
#include <set>
USING_YOSYS_NAMESPACE
PRIVATE_NAMESPACE_BEGIN
struct SccWorker
{
RTLIL::Design *design;
RTLIL::Module *module;
SigMap sigmap;
CellTypes ct;
std::set<RTLIL::Cell*> workQueue;
std::map<RTLIL::Cell*, std::set<RTLIL::Cell*>> cellToNextCell;
std::map<RTLIL::Cell*, RTLIL::SigSpec> cellToPrevSig, cellToNextSig;
std::map<RTLIL::Cell*, std::pair<int, int>> cellLabels;
std::map<RTLIL::Cell*, int> cellDepth;
std::set<RTLIL::Cell*> cellsOnStack;
std::vector<RTLIL::Cell*> cellStack;
int labelCounter;
std::map<RTLIL::Cell*, int> cell2scc;
std::vector<std::set<RTLIL::Cell*>> sccList;
void run(RTLIL::Cell *cell, int depth, int maxDepth)
{
log_assert(workQueue.count(cell) > 0);
workQueue.erase(cell);
cellLabels[cell] = std::pair<int, int>(labelCounter, labelCounter);
labelCounter++;
cellsOnStack.insert(cell);
cellStack.push_back(cell);
if (maxDepth >= 0)
cellDepth[cell] = depth;
for (auto nextCell : cellToNextCell[cell])
if (cellLabels.count(nextCell) == 0) {
run(nextCell, depth+1, maxDepth);
cellLabels[cell].second = min(cellLabels[cell].second, cellLabels[nextCell].second);
} else
if (cellsOnStack.count(nextCell) > 0 && (maxDepth < 0 || cellDepth[nextCell] + maxDepth > depth)) {
cellLabels[cell].second = min(cellLabels[cell].second, cellLabels[nextCell].second);
}
if (cellLabels[cell].first == cellLabels[cell].second)
{
if (cellStack.back() == cell)
{
cellStack.pop_back();
cellsOnStack.erase(cell);
}
else
{
log("Found an SCC:");
std::set<RTLIL::Cell*> scc;
while (cellsOnStack.count(cell) > 0) {
RTLIL::Cell *c = cellStack.back();
cellStack.pop_back();
cellsOnStack.erase(c);
log(" %s", RTLIL::id2cstr(c->name));
cell2scc[c] = sccList.size();
scc.insert(c);
}
sccList.push_back(scc);
log("\n");
}
}
}
SccWorker(RTLIL::Design *design, RTLIL::Module *module, bool nofeedbackMode, bool allCellTypes, int maxDepth) :
design(design), module(module), sigmap(module)
{
if (module->processes.size() > 0) {
log("Skipping module %s as it contains processes (run 'proc' pass first).\n", module->name.c_str());
return;
}
if (allCellTypes) {
ct.setup(design);
} else {
ct.setup_internals();
ct.setup_stdcells();
}
SigPool selectedSignals;
SigSet<RTLIL::Cell*> sigToNextCells;
for (auto &it : module->wires_)
if (design->selected(module, it.second))
selectedSignals.add(sigmap(RTLIL::SigSpec(it.second)));
for (auto &it : module->cells_)
{
RTLIL::Cell *cell = it.second;
if (!design->selected(module, cell))
continue;
if (!allCellTypes && !ct.cell_known(cell->type))
continue;
workQueue.insert(cell);
RTLIL::SigSpec inputSignals, outputSignals;
for (auto &conn : cell->connections())
{
bool isInput = true, isOutput = true;
if (ct.cell_known(cell->type)) {
isInput = ct.cell_input(cell->type, conn.first);
isOutput = ct.cell_output(cell->type, conn.first);
}
RTLIL::SigSpec sig = selectedSignals.extract(sigmap(conn.second));
sig.sort_and_unify();
if (isInput)
inputSignals.append(sig);
if (isOutput)
outputSignals.append(sig);
}
inputSignals.sort_and_unify();
outputSignals.sort_and_unify();
cellToPrevSig[cell] = inputSignals;
cellToNextSig[cell] = outputSignals;
sigToNextCells.insert(inputSignals, cell);
}
for (auto cell : workQueue)
{
cellToNextCell[cell] = sigToNextCells.find(cellToNextSig[cell]);
if (!nofeedbackMode && cellToNextCell[cell].count(cell)) {
log("Found an SCC:");
std::set<RTLIL::Cell*> scc;
log(" %s", RTLIL::id2cstr(cell->name));
cell2scc[cell] = sccList.size();
scc.insert(cell);
sccList.push_back(scc);
log("\n");
}
}
labelCounter = 0;
cellLabels.clear();
while (!workQueue.empty())
{
RTLIL::Cell *cell = *workQueue.begin();
log_assert(cellStack.size() == 0);
cellDepth.clear();
run(cell, 0, maxDepth);
}
log("Found %d SCCs in module %s.\n", int(sccList.size()), RTLIL::id2cstr(module->name));
}
void select(RTLIL::Selection &sel)
{
for (int i = 0; i < int(sccList.size()); i++)
{
std::set<RTLIL::Cell*> &cells = sccList[i];
RTLIL::SigSpec prevsig, nextsig, sig;
for (auto cell : cells) {
sel.selected_members[module->name].insert(cell->name);
prevsig.append(cellToPrevSig[cell]);
nextsig.append(cellToNextSig[cell]);
}
prevsig.sort_and_unify();
nextsig.sort_and_unify();
sig = prevsig.extract(nextsig);
for (auto &chunk : sig.chunks())
if (chunk.wire != NULL)
sel.selected_members[module->name].insert(chunk.wire->name);
}
}
};
struct SccPass : public Pass {
SccPass() : Pass("scc", "detect strongly connected components (logic loops)") { }
virtual void help()
{
// |---v---|---v---|---v---|---v---|---v---|---v---|---v---|---v---|---v---|---v---|
log("\n");
log(" scc [options] [selection]\n");
log("\n");
log("This command identifies strongly connected components (aka logic loops) in the\n");
log("design.\n");
log("\n");
log(" -expect <num>\n");
log(" expect to find exactly <num> SSCs. A different number of SSCs will\n");
log(" produce an error.\n");
log("\n");
log(" -max_depth <num>\n");
log(" limit to loops not longer than the specified number of cells. This\n");
log(" can e.g. be useful in identifying small local loops in a module that\n");
log(" implements one large SCC.\n");
log("\n");
log(" -nofeedback\n");
log(" do not count cells that have their output fed back into one of their\n");
log(" inputs as single-cell scc.\n");
log("\n");
log(" -all_cell_types\n");
log(" Usually this command only considers internal non-memory cells. With\n");
log(" this option set, all cells are considered. For unknown cells all ports\n");
log(" are assumed to be bidirectional 'inout' ports.\n");
log("\n");
log(" -set_attr <name> <value>\n");
log(" set the specified attribute on all cells that are part of a logic\n");
log(" loop. the special token {} in the value is replaced with a unique\n");
log(" identifier for the logic loop.\n");
log("\n");
log(" -select\n");
log(" replace the current selection with a selection of all cells and wires\n");
log(" that are part of a found logic loop\n");
log("\n");
}
virtual void execute(std::vector<std::string> args, RTLIL::Design *design)
{
std::map<std::string, std::string> setAttr;
bool allCellTypes = false;
bool selectMode = false;
bool nofeedbackMode = false;
int maxDepth = -1;
int expect = -1;
log_header(design, "Executing SCC pass (detecting logic loops).\n");
size_t argidx;
for (argidx = 1; argidx < args.size(); argidx++) {
if (args[argidx] == "-max_depth" && argidx+1 < args.size()) {
maxDepth = atoi(args[++argidx].c_str());
continue;
}
if (args[argidx] == "-expect" && argidx+1 < args.size()) {
expect = atoi(args[++argidx].c_str());
continue;
}
if (args[argidx] == "-nofeedback") {
nofeedbackMode = true;
continue;
}
if (args[argidx] == "-all_cell_types") {
allCellTypes = true;
continue;
}
if (args[argidx] == "-set_attr" && argidx+2 < args.size()) {
setAttr[args[argidx+1]] = args[argidx+2];
argidx += 2;
continue;
}
if (args[argidx] == "-select") {
selectMode = true;
continue;
}
break;
}
int origSelectPos = design->selection_stack.size() - 1;
extra_args(args, argidx, design);
RTLIL::Selection newSelection(false);
int scc_counter = 0;
for (auto &mod_it : design->modules_)
if (design->selected(mod_it.second))
{
SccWorker worker(design, mod_it.second, nofeedbackMode, allCellTypes, maxDepth);
if (!setAttr.empty())
{
for (const auto &cells : worker.sccList)
{
for (auto attr : setAttr)
{
IdString attr_name(RTLIL::escape_id(attr.first));
string attr_valstr = attr.second;
string index = stringf("%d", scc_counter);
for (size_t pos = 0; (pos = attr_valstr.find("{}", pos)) != string::npos; pos += index.size())
attr_valstr.replace(pos, 2, index);
Const attr_value(attr_valstr);
for (auto cell : cells)
cell->attributes[attr_name] = attr_value;
}
scc_counter++;
}
}
else
{
scc_counter += GetSize(worker.sccList);
}
if (selectMode)
worker.select(newSelection);
}
if (expect >= 0) {
if (scc_counter == expect)
log("Found and expected %d SCCs.\n", scc_counter);
else
log_error("Found %d SCCs but expected %d.\n", scc_counter, expect);
} else
log("Found %d SCCs.\n", scc_counter);
if (selectMode) {
log_assert(origSelectPos >= 0);
design->selection_stack[origSelectPos] = newSelection;
design->selection_stack[origSelectPos].optimize(design);
}
}
} SccPass;
PRIVATE_NAMESPACE_END
<|endoftext|> |
<commit_before>/*
* yosys -- Yosys Open SYnthesis Suite
*
* Copyright (C) 2014 Clifford Wolf <[email protected]>
* Copyright (C) 2014 Johann Glaser <[email protected]>
*
* Permission to use, copy, modify, and/or distribute this software for any
* purpose with or without fee is hereby granted, provided that the above
* copyright notice and this permission notice appear in all copies.
*
* THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
* WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
* MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
* ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
* WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
* ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
* OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
*
*/
#include "kernel/register.h"
#include "kernel/rtlil.h"
#include "kernel/log.h"
USING_YOSYS_NAMESPACE
PRIVATE_NAMESPACE_BEGIN
struct TeePass : public Pass {
TeePass() : Pass("tee", "redirect command output to file") { }
void help() YS_OVERRIDE
{
// |---v---|---v---|---v---|---v---|---v---|---v---|---v---|---v---|---v---|---v---|
log("\n");
log(" tee [-q] [-o logfile|-a logfile] cmd\n");
log("\n");
log("Execute the specified command, optionally writing the commands output to the\n");
log("specified logfile(s).\n");
log("\n");
log(" -q\n");
log(" Do not print output to the normal destination (console and/or log file).\n");
log("\n");
log(" -o logfile\n");
log(" Write output to this file, truncate if exists.\n");
log("\n");
log(" -a logfile\n");
log(" Write output to this file, append if exists.\n");
log("\n");
log(" +INT, -INT\n");
log(" Add/subtract INT from the -v setting for this command.\n");
log("\n");
}
void execute(std::vector<std::string> args, RTLIL::Design *design) YS_OVERRIDE
{
std::vector<FILE*> backup_log_files, files_to_close;
int backup_log_verbose_level = log_verbose_level;
backup_log_files = log_files;
size_t argidx;
for (argidx = 1; argidx < args.size(); argidx++)
{
if (args[argidx] == "-q" && files_to_close.empty()) {
log_files.clear();
continue;
}
if ((args[argidx] == "-o" || args[argidx] == "-a") && argidx+1 < args.size()) {
const char *open_mode = args[argidx] == "-o" ? "w" : "a+";
FILE *f = fopen(args[++argidx].c_str(), open_mode);
yosys_input_files.insert(args[argidx]);
if (f == NULL) {
for (auto cf : files_to_close)
fclose(cf);
log_cmd_error("Can't create file %s.\n", args[argidx].c_str());
}
log_files.push_back(f);
files_to_close.push_back(f);
continue;
}
if (GetSize(args[argidx]) >= 2 && (args[argidx][0] == '-' || args[argidx][0] == '+') && args[argidx][1] >= '0' && args[argidx][1] <= '9') {
log_verbose_level += atoi(args[argidx].c_str());
continue;
}
break;
}
try {
std::vector<std::string> new_args(args.begin() + argidx, args.end());
Pass::call(design, new_args);
} catch (...) {
for (auto cf : files_to_close)
fclose(cf);
log_files = backup_log_files;
throw;
}
for (auto cf : files_to_close)
fclose(cf);
log_verbose_level = backup_log_verbose_level;
log_files = backup_log_files;
}
} TeePass;
PRIVATE_NAMESPACE_END
<commit_msg>Fix "tee" handling of log_streams<commit_after>/*
* yosys -- Yosys Open SYnthesis Suite
*
* Copyright (C) 2014 Clifford Wolf <[email protected]>
* Copyright (C) 2014 Johann Glaser <[email protected]>
*
* Permission to use, copy, modify, and/or distribute this software for any
* purpose with or without fee is hereby granted, provided that the above
* copyright notice and this permission notice appear in all copies.
*
* THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
* WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
* MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
* ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
* WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
* ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
* OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
*
*/
#include "kernel/register.h"
#include "kernel/rtlil.h"
#include "kernel/log.h"
USING_YOSYS_NAMESPACE
PRIVATE_NAMESPACE_BEGIN
struct TeePass : public Pass {
TeePass() : Pass("tee", "redirect command output to file") { }
void help() YS_OVERRIDE
{
// |---v---|---v---|---v---|---v---|---v---|---v---|---v---|---v---|---v---|---v---|
log("\n");
log(" tee [-q] [-o logfile|-a logfile] cmd\n");
log("\n");
log("Execute the specified command, optionally writing the commands output to the\n");
log("specified logfile(s).\n");
log("\n");
log(" -q\n");
log(" Do not print output to the normal destination (console and/or log file).\n");
log("\n");
log(" -o logfile\n");
log(" Write output to this file, truncate if exists.\n");
log("\n");
log(" -a logfile\n");
log(" Write output to this file, append if exists.\n");
log("\n");
log(" +INT, -INT\n");
log(" Add/subtract INT from the -v setting for this command.\n");
log("\n");
}
void execute(std::vector<std::string> args, RTLIL::Design *design) YS_OVERRIDE
{
std::vector<FILE*> backup_log_files, files_to_close;
std::vector<std::ostream*> backup_log_streams;
int backup_log_verbose_level = log_verbose_level;
backup_log_streams = log_streams;
backup_log_files = log_files;
size_t argidx;
for (argidx = 1; argidx < args.size(); argidx++)
{
if (args[argidx] == "-q" && files_to_close.empty()) {
log_files.clear();
log_streams.clear();
continue;
}
if ((args[argidx] == "-o" || args[argidx] == "-a") && argidx+1 < args.size()) {
const char *open_mode = args[argidx] == "-o" ? "w" : "a+";
FILE *f = fopen(args[++argidx].c_str(), open_mode);
yosys_input_files.insert(args[argidx]);
if (f == NULL) {
for (auto cf : files_to_close)
fclose(cf);
log_cmd_error("Can't create file %s.\n", args[argidx].c_str());
}
log_files.push_back(f);
files_to_close.push_back(f);
continue;
}
if (GetSize(args[argidx]) >= 2 && (args[argidx][0] == '-' || args[argidx][0] == '+') && args[argidx][1] >= '0' && args[argidx][1] <= '9') {
log_verbose_level += atoi(args[argidx].c_str());
continue;
}
break;
}
try {
std::vector<std::string> new_args(args.begin() + argidx, args.end());
Pass::call(design, new_args);
} catch (...) {
for (auto cf : files_to_close)
fclose(cf);
log_files = backup_log_files;
log_streams = backup_log_streams;
throw;
}
for (auto cf : files_to_close)
fclose(cf);
log_verbose_level = backup_log_verbose_level;
log_files = backup_log_files;
log_streams = backup_log_streams;
}
} TeePass;
PRIVATE_NAMESPACE_END
<|endoftext|> |
<commit_before>
#include "Strategy.h"
#include "ETSumoStrategy.h"
#include "StrategyManager.h"
#include "InOutManager.h"
#include "SelfPositionManager.h"
#include "ETTrainStrategy.h"
#include "HSLColor.h"
#include "ColorDecision.h"
#include "SerialData.h"
#include "PIDDataManager.h"
#define BACK_POWER 20
#define TURN_SPEED 12 // 旋回時の出力
#define FIRST_TURN_SPEED 20
#define BACK_ANGLE 1
#define ONLINE 60
#define STATION_ANGLE 90 // 駅に尻尾を向けた方向
#define SWITCH_OFF_ANGLE 30 // スイッチを切れる角度
#define FORWARD_ANGLE 180 // 正面方向
void ETTrainStrategy::Run()
{
// 使用するシングルトンクラスのインスタンスを取得
InOutManager *IOManager = InOutManager::GetInstance();
SelfPositionManager *SpManager = SelfPositionManager::GetInstance();
auto pid = PIDDataManager::GetInstance();
SpManager->ParticleFilterON = false;
ACTION :
int currentAngle = SpManager->RobotAngle;
Point currentPoint = SpManager->RobotPoint;
switch (CurrentState) {
// ゴール後、反対向きに旋回する
case TurnToBack:
if (abs(currentAngle - BACK_ANGLE) < 10) {
CurrentState = BackToStation;
goto ACTION;
}
IOManager->TurnCCW(FIRST_TURN_SPEED);
break;
// 駅の前まで移動中
case BackToStation:
// 駅の前に到達したので、駅に尻尾を向けるまで旋回中に遷移
if (currentPoint.X > (1640 + KillCount * 30)) {
CurrentState = TurnToStation;
// ライントレース終了時にはまっすぐ後ろ向き
SpManager->ResetAngle(BACK_ANGLE);
goto ACTION;
}
// 前に到達するまで後退
IOManager->LineTraceAction(pid->GetPIDData(ETTrainSlow), 120, false);
break;
// 駅に尻尾を向けるまで旋回中
case TurnToStation:
if (abs(currentAngle - STATION_ANGLE) < 5) {
CurrentState = TurnOffSwitch;
// 尻尾を下げている間、スレッドが停止するため強制的に周期書き込みを発生させる
IOManager->Stop();
IOManager->WriteOutputMotor();
// 遷移時に、尻尾を下げる
IOManager->DownTailMotor();
goto ACTION;
}
// 駅角度まで旋回
IOManager->Turn(currentAngle, STATION_ANGLE, FIRST_TURN_SPEED);
break;
// スイッチを操作して、停止側にする
case TurnOffSwitch:
if (abs(currentAngle - SWITCH_OFF_ANGLE) < 5){
// 尻尾をあげている間、スレッドが停止するため強制的に周期書き込みを発生させる
IOManager->Stop();
IOManager->WriteOutputMotor();
// 遷移時に、尻尾を上げる
IOManager->UpTailMotor();
KillCount++;
// 3回実行したら前を向く
if(KillCount == 3) CurrentState = TurnFront;
else CurrentState = TurnNextBack;
goto ACTION;
}
// スイッチオフ角度まで旋回
IOManager->Turn(currentAngle, SWITCH_OFF_ANGLE, TURN_SPEED);
break;
// もう一度
case TurnNextBack:
if (abs(currentAngle - BACK_ANGLE) < 10) {
CurrentState = BackToStation;
goto ACTION;
}
IOManager->TurnCW(FIRST_TURN_SPEED);
break;
// 進行方向を向くまで旋回する
case TurnFront:
if (IOManager->InputData.ReflectLight < ONLINE && abs(currentAngle - FORWARD_ANGLE) < 60){
CurrentState = LineTraceSlowToGrayArea;
IOManager->Stop();
IOManager->WriteOutputMotor();
IOManager->BottomTailMotor();
goto ACTION;
}
// 進行方向まで旋回
IOManager->Turn(currentAngle, FORWARD_ANGLE, FIRST_TURN_SPEED);
break;
case LineTraceSlowToGrayArea:
if(currentPoint.X < 1570) {
CurrentState = LineTraceToGrayArea;
goto ACTION;
}
IOManager->LineTraceAction(pid->GetPIDData(ETTrainSlow), 120, false);
break;
case LineTraceToGrayArea:
// 灰色エリアに到達したら、直進処理に変更
if(currentPoint.X < 1200) {
CurrentState = ForwardGrayArea;
// ライントレース終了時にはまっすぐ前向き
SpManager->ResetAngle(FORWARD_ANGLE);
goto ACTION;
}
IOManager->LineTraceAction(pid->GetPIDData(ETTrainHigh), 120, false);
break;
case ForwardGrayArea:
// 灰色エリアを抜けたら、ライントレース状態に遷移
if(currentPoint.X < 1020) {
CurrentState = LineTraceToArena;
goto ACTION;
}
IOManager->Forward(pid->GetPIDData(ETTrainHigh).BasePower);
break;
// たどり着くまで、ライントレースを実施する
case LineTraceToArena:
if(SpManager->Distance > 2750) {
Manager->SetStrategy(new ETSumoStrategy(Manager));
return;
}
IOManager->LineTraceAction(pid->GetPIDData(ETTrainHigh), 120, false);
break;
default:
break;
}
}<commit_msg>新幹線停止の移動距離を調整<commit_after>
#include "Strategy.h"
#include "ETSumoStrategy.h"
#include "StrategyManager.h"
#include "InOutManager.h"
#include "SelfPositionManager.h"
#include "ETTrainStrategy.h"
#include "HSLColor.h"
#include "ColorDecision.h"
#include "SerialData.h"
#include "PIDDataManager.h"
#define BACK_POWER 20
#define TURN_SPEED 12 // 旋回時の出力
#define FIRST_TURN_SPEED 20
#define BACK_ANGLE 1
#define ONLINE 60
#define STATION_ANGLE 90 // 駅に尻尾を向けた方向
#define SWITCH_OFF_ANGLE 30 // スイッチを切れる角度
#define FORWARD_ANGLE 180 // 正面方向
#define BASE_DISTANCE 455
void ETTrainStrategy::Run()
{
// 使用するシングルトンクラスのインスタンスを取得
InOutManager *IOManager = InOutManager::GetInstance();
SelfPositionManager *SpManager = SelfPositionManager::GetInstance();
auto pid = PIDDataManager::GetInstance();
SpManager->ParticleFilterON = false;
ACTION :
int currentAngle = SpManager->RobotAngle;
Point currentPoint = SpManager->RobotPoint;
switch (CurrentState) {
// ゴール後、反対向きに旋回する
case TurnToBack:
if (abs(currentAngle - BACK_ANGLE) < 10) {
CurrentState = BackToStation;
// 距離を初期化
SpManager->Distance = 0;
goto ACTION;
}
IOManager->TurnCCW(FIRST_TURN_SPEED);
break;
// 駅の前まで移動中
case BackToStation:
// 駅の前に到達したので、駅に尻尾を向けるまで旋回中に遷移
if (SpManager->Distance > (BASE_DISTANCE + KillCount * 27)) {
CurrentState = TurnToStation;
// ライントレース終了時にはまっすぐ後ろ向き
SpManager->ResetAngle(BACK_ANGLE);
goto ACTION;
}
// 前に到達するまで後退
IOManager->LineTraceAction(pid->GetPIDData(ETTrainSlow), 120, false);
break;
// 駅に尻尾を向けるまで旋回中
case TurnToStation:
if (abs(currentAngle - STATION_ANGLE) < 5) {
CurrentState = TurnOffSwitch;
// 尻尾を下げている間、スレッドが停止するため強制的に周期書き込みを発生させる
IOManager->Stop();
IOManager->WriteOutputMotor();
// 遷移時に、尻尾を下げる
IOManager->DownTailMotor();
goto ACTION;
}
// 駅角度まで旋回
IOManager->Turn(currentAngle, STATION_ANGLE, FIRST_TURN_SPEED);
break;
// スイッチを操作して、停止側にする
case TurnOffSwitch:
if (abs(currentAngle - SWITCH_OFF_ANGLE) < 5){
// 尻尾をあげている間、スレッドが停止するため強制的に周期書き込みを発生させる
IOManager->Stop();
IOManager->WriteOutputMotor();
// 遷移時に、尻尾を上げる
IOManager->UpTailMotor();
KillCount++;
// 3回実行したら前を向く
if(KillCount == 3) CurrentState = TurnFront;
else CurrentState = TurnNextBack;
goto ACTION;
}
// スイッチオフ角度まで旋回
IOManager->Turn(currentAngle, SWITCH_OFF_ANGLE, TURN_SPEED);
break;
// もう一度
case TurnNextBack:
if (abs(currentAngle - BACK_ANGLE) < 10) {
CurrentState = BackToStation;
goto ACTION;
}
IOManager->TurnCW(FIRST_TURN_SPEED);
break;
// 進行方向を向くまで旋回する
case TurnFront:
if (IOManager->InputData.ReflectLight < ONLINE && abs(currentAngle - FORWARD_ANGLE) < 60){
CurrentState = LineTraceSlowToGrayArea;
IOManager->Stop();
IOManager->WriteOutputMotor();
IOManager->BottomTailMotor();
goto ACTION;
}
// 進行方向まで旋回
IOManager->Turn(currentAngle, FORWARD_ANGLE, FIRST_TURN_SPEED);
break;
case LineTraceSlowToGrayArea:
if(currentPoint.X < 1570) {
CurrentState = LineTraceToGrayArea;
goto ACTION;
}
IOManager->LineTraceAction(pid->GetPIDData(ETTrainSlow), 120, false);
break;
case LineTraceToGrayArea:
// 灰色エリアに到達したら、直進処理に変更
if(currentPoint.X < 1200) {
CurrentState = ForwardGrayArea;
// ライントレース終了時にはまっすぐ前向き
SpManager->ResetAngle(FORWARD_ANGLE);
goto ACTION;
}
IOManager->LineTraceAction(pid->GetPIDData(ETTrainHigh), 120, false);
break;
case ForwardGrayArea:
// 灰色エリアを抜けたら、ライントレース状態に遷移
if(currentPoint.X < 1020) {
CurrentState = LineTraceToArena;
goto ACTION;
}
IOManager->Forward(pid->GetPIDData(ETTrainHigh).BasePower);
break;
// たどり着くまで、ライントレースを実施する
case LineTraceToArena:
if(SpManager->Distance > 2750) {
Manager->SetStrategy(new ETSumoStrategy(Manager));
return;
}
IOManager->LineTraceAction(pid->GetPIDData(ETTrainHigh), 120, false);
break;
default:
break;
}
}<|endoftext|> |
<commit_before>/* This file is part of the KDE project
Copyright (C) 2004-2007 Matthias Kretz <[email protected]>
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) version 3, or any
later version accepted by the membership of KDE e.V. (or its
successor approved by the membership of KDE e.V.), Trolltech ASA
(or its successors, if any) and the KDE Free Qt Foundation, which shall
act as a proxy defined in Section 6 of version 3 of the license.
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, see <http://www.gnu.org/licenses/>.
*/
#include "factory_p.h"
#include "backendinterface.h"
#include "medianode_p.h"
#include "mediaobject.h"
#include "audiooutput.h"
#include "globalstatic_p.h"
#include "objectdescription.h"
#include "platformplugin.h"
#include "phononnamespace_p.h"
#include <QtCore/QCoreApplication>
#include <QtCore/QDir>
#include <QtCore/QList>
#include <QtCore/QPluginLoader>
#include <QtCore/QPointer>
#ifndef QT_NO_DBUS
#include <QtDBus/QtDBus>
#endif
QT_BEGIN_NAMESPACE
namespace Phonon
{
class PlatformPlugin;
class FactoryPrivate : public Phonon::Factory::Sender
{
friend QObject *Factory::backend(bool);
Q_OBJECT
public:
FactoryPrivate();
~FactoryPrivate();
bool createBackend();
#ifndef QT_NO_PHONON_PLATFORMPLUGIN
PlatformPlugin *platformPlugin();
PlatformPlugin *m_platformPlugin;
bool m_noPlatformPlugin;
#endif //QT_NO_PHONON_PLATFORMPLUGIN
QPointer<QObject> m_backendObject;
QList<QObject *> objects;
QList<MediaNodePrivate *> mediaNodePrivateList;
private Q_SLOTS:
/**
* This is called via DBUS when the user changes the Phonon Backend.
*/
#ifndef QT_NO_DBUS
void phononBackendChanged();
#endif //QT_NO_DBUS
/**
* unregisters the backend object
*/
void objectDestroyed(QObject *);
void objectDescriptionChanged(ObjectDescriptionType);
};
PHONON_GLOBAL_STATIC(Phonon::FactoryPrivate, globalFactory)
static inline void ensureLibraryPathSet()
{
#ifdef PHONON_LIBRARY_PATH
static bool done = false;
if (!done) {
done = true;
QCoreApplication::addLibraryPath(QLatin1String(PHONON_LIBRARY_PATH));
}
#endif // PHONON_LIBRARY_PATH
}
void Factory::setBackend(QObject *b)
{
Q_ASSERT(globalFactory->m_backendObject == 0);
globalFactory->m_backendObject = b;
}
/*void Factory::createBackend(const QString &library, const QString &version)
{
Q_ASSERT(globalFactory->m_backendObject == 0);
PlatformPlugin *f = globalFactory->platformPlugin();
if (f) {
globalFactory->m_backendObject = f->createBackend(library, version);
}
}*/
bool FactoryPrivate::createBackend()
{
Q_ASSERT(m_backendObject == 0);
#ifndef QT_NO_PHONON_PLATFORMPLUGIN
PlatformPlugin *f = globalFactory->platformPlugin();
if (f) {
m_backendObject = f->createBackend();
}
#endif //QT_NO_PHONON_PLATFORMPLUGIN
if (!m_backendObject) {
ensureLibraryPathSet();
// could not load a backend through the platform plugin. Falling back to the default
// (finding the first loadable backend).
const QLatin1String suffix("/phonon_backend/");
foreach (QString libPath, QCoreApplication::libraryPaths()) {
libPath += suffix;
const QDir dir(libPath);
if (!dir.exists()) {
pDebug() << Q_FUNC_INFO << dir.absolutePath() << "does not exist";
continue;
}
foreach (const QString &pluginName, dir.entryList(QDir::Files)) {
QPluginLoader pluginLoader(libPath + pluginName);
if (!pluginLoader.load()) {
pDebug() << Q_FUNC_INFO << " load failed:"
<< pluginLoader.errorString();
continue;
}
pDebug() << pluginLoader.instance();
m_backendObject = pluginLoader.instance();
if (m_backendObject) {
break;
}
// no backend found, don't leave an unused plugin in memory
pluginLoader.unload();
}
if (m_backendObject) {
break;
}
}
if (!m_backendObject) {
pWarning() << Q_FUNC_INFO << "phonon backend plugin could not be loaded";
return false;
}
}
connect(m_backendObject, SIGNAL(objectDescriptionChanged(ObjectDescriptionType)),
SLOT(objectDescriptionChanged(ObjectDescriptionType)));
return true;
}
FactoryPrivate::FactoryPrivate()
#ifndef QT_NO_PHONON_PLATFORMPLUGIN
: m_platformPlugin(0),
m_noPlatformPlugin(false)
#endif //QT_NO_PHONON_PLATFORMPLUGIN
, m_backendObject(0)
{
// Add the post routine to make sure that all other global statics (especially the ones from Qt)
// are still available. If the FactoryPrivate dtor is called too late many bad things can happen
// as the whole backend might still be alive.
qAddPostRoutine(globalFactory.destroy);
#ifndef QT_NO_DBUS
QDBusConnection::sessionBus().connect(QString(), QString(), "org.kde.Phonon.Factory",
"phononBackendChanged", this, SLOT(phononBackendChanged()));
#endif
}
FactoryPrivate::~FactoryPrivate()
{
foreach (QObject *o, objects) {
MediaObject *m = qobject_cast<MediaObject *>(o);
if (m) {
m->stop();
}
}
foreach (MediaNodePrivate *bp, mediaNodePrivateList) {
bp->deleteBackendObject();
}
if (objects.size() > 0) {
pError() << "The backend objects are not deleted as was requested.";
qDeleteAll(objects);
}
delete m_backendObject;
#ifndef QT_NO_PHONON_PLATFORMPLUGIN
delete m_platformPlugin;
#endif //QT_NO_PHONON_PLATFORMPLUGIN
}
void FactoryPrivate::objectDescriptionChanged(ObjectDescriptionType type)
{
#ifdef PHONON_METHODTEST
Q_UNUSED(type);
#else
pDebug() << Q_FUNC_INFO << type;
switch (type) {
case AudioOutputDeviceType:
emit availableAudioOutputDevicesChanged();
break;
case AudioCaptureDeviceType:
emit availableAudioCaptureDevicesChanged();
break;
default:
break;
}
//emit capabilitiesChanged();
#endif // PHONON_METHODTEST
}
Factory::Sender *Factory::sender()
{
return globalFactory;
}
bool Factory::isMimeTypeAvailable(const QString &mimeType)
{
#ifndef QT_NO_PHONON_PLATFORMPLUGIN
PlatformPlugin *f = globalFactory->platformPlugin();
if (f) {
return f->isMimeTypeAvailable(mimeType);
}
#else
Q_UNUSED(mimeType);
#endif //QT_NO_PHONON_PLATFORMPLUGIN
return true; // the MIME type might be supported, let BackendCapabilities find out
}
void Factory::registerFrontendObject(MediaNodePrivate *bp)
{
globalFactory->mediaNodePrivateList.prepend(bp); // inserted last => deleted first
}
void Factory::deregisterFrontendObject(MediaNodePrivate *bp)
{
// The Factory can already be cleaned up while there are other frontend objects still alive.
// When those are deleted they'll call deregisterFrontendObject through ~BasePrivate
if (!globalFactory.isDestroyed()) {
globalFactory->mediaNodePrivateList.removeAll(bp);
}
}
#ifndef QT_NO_DBUS
void FactoryPrivate::phononBackendChanged()
{
if (m_backendObject) {
foreach (MediaNodePrivate *bp, mediaNodePrivateList) {
bp->deleteBackendObject();
}
if (objects.size() > 0) {
pDebug() << "WARNING: we were asked to change the backend but the application did\n"
"not free all references to objects created by the factory. Therefore we can not\n"
"change the backend without crashing. Now we have to wait for a restart to make\n"
"backendswitching possible.";
// in case there were objects deleted give 'em a chance to recreate
// them now
foreach (MediaNodePrivate *bp, mediaNodePrivateList) {
bp->createBackendObject();
}
return;
}
delete m_backendObject;
m_backendObject = 0;
}
createBackend();
foreach (MediaNodePrivate *bp, mediaNodePrivateList) {
bp->createBackendObject();
}
emit backendChanged();
}
#endif //QT_NO_DBUS
//X void Factory::freeSoundcardDevices()
//X {
//X if (globalFactory->backend) {
//X globalFactory->backend->freeSoundcardDevices();
//X }
//X }
void FactoryPrivate::objectDestroyed(QObject * obj)
{
//pDebug() << Q_FUNC_INFO << obj;
objects.removeAll(obj);
}
#define FACTORY_IMPL(classname) \
QObject *Factory::create ## classname(QObject *parent) \
{ \
if (backend()) { \
return registerQObject(qobject_cast<BackendInterface *>(backend())->createObject(BackendInterface::classname##Class, parent)); \
} \
return 0; \
}
#define FACTORY_IMPL_1ARG(classname) \
QObject *Factory::create ## classname(int arg1, QObject *parent) \
{ \
if (backend()) { \
return registerQObject(qobject_cast<BackendInterface *>(backend())->createObject(BackendInterface::classname##Class, parent, QList<QVariant>() << arg1)); \
} \
return 0; \
}
FACTORY_IMPL(MediaObject)
#ifndef QT_NO_PHONON_EFFECT
FACTORY_IMPL_1ARG(Effect)
#endif //QT_NO_PHONON_EFFECT
#ifndef QT_NO_PHONON_VOLUMEFADEREFFECT
FACTORY_IMPL(VolumeFaderEffect)
#endif //QT_NO_PHONON_VOLUMEFADEREFFECT
FACTORY_IMPL(AudioOutput)
#ifndef QT_NO_PHONON_VIDEO
FACTORY_IMPL(VideoWidget)
#endif //QT_NO_PHONON_VIDEO
#undef FACTORY_IMPL
#ifndef QT_NO_PHONON_PLATFORMPLUGIN
PlatformPlugin *FactoryPrivate::platformPlugin()
{
if (m_platformPlugin) {
return m_platformPlugin;
}
if (m_noPlatformPlugin) {
return 0;
}
#ifndef QT_NO_DBUS
if (!QCoreApplication::instance() || QCoreApplication::applicationName().isEmpty()) {
pWarning() << "Phonon needs QCoreApplication::applicationName to be set to export audio output names through the DBUS interface";
}
#endif
Q_ASSERT(QCoreApplication::instance());
if (!qgetenv("PHONON_PLATFORMPLUGIN").isEmpty()) {
QPluginLoader pluginLoader(qgetenv("PHONON_PLATFORMPLUGIN"));
if (pluginLoader.load()) {
m_platformPlugin = qobject_cast<PlatformPlugin *>(pluginLoader.instance());
if (m_platformPlugin) {
return m_platformPlugin;
}
}
}
const QString suffix(QLatin1String("/phonon_platform/"));
ensureLibraryPathSet();
QDir dir;
dir.setNameFilters(
!qgetenv("KDE_FULL_SESSION").isEmpty() ? QStringList(QLatin1String("kde.*")) :
(!qgetenv("GNOME_DESKTOP_SESSION_ID").isEmpty() ? QStringList(QLatin1String("gnome.*")) :
QStringList())
);
dir.setFilter(QDir::Files);
forever {
foreach (QString libPath, QCoreApplication::libraryPaths()) {
libPath += suffix;
dir.setPath(libPath);
if (!dir.exists()) {
continue;
}
foreach (const QString &pluginName, dir.entryList()) {
QPluginLoader pluginLoader(libPath + pluginName);
if (!pluginLoader.load()) {
pDebug() << Q_FUNC_INFO << " platform plugin load failed:"
<< pluginLoader.errorString();
continue;
}
pDebug() << pluginLoader.instance();
QObject *qobj = pluginLoader.instance();
m_platformPlugin = qobject_cast<PlatformPlugin *>(qobj);
pDebug() << m_platformPlugin;
if (m_platformPlugin) {
connect(qobj, SIGNAL(objectDescriptionChanged(ObjectDescriptionType)),
SLOT(objectDescriptionChanged(ObjectDescriptionType)));
return m_platformPlugin;
} else {
delete qobj;
pDebug() << Q_FUNC_INFO << dir.absolutePath() << "exists but the platform plugin was not loadable:" << pluginLoader.errorString();
pluginLoader.unload();
}
}
}
if (dir.nameFilters().isEmpty()) {
break;
}
dir.setNameFilters(QStringList());
}
pDebug() << Q_FUNC_INFO << "platform plugin could not be loaded";
m_noPlatformPlugin = true;
return 0;
}
PlatformPlugin *Factory::platformPlugin()
{
return globalFactory->platformPlugin();
}
#endif // QT_NO_PHONON_PLATFORMPLUGIN
QObject *Factory::backend(bool createWhenNull)
{
if (globalFactory.isDestroyed()) {
return 0;
}
if (createWhenNull && globalFactory->m_backendObject == 0) {
globalFactory->createBackend();
// XXX: might create "reentrancy" problems:
// a method calls this method and is called again because the
// backendChanged signal is emitted
emit globalFactory->backendChanged();
}
return globalFactory->m_backendObject;
}
#define GET_STRING_PROPERTY(name) \
QString Factory::name() \
{ \
if (globalFactory->m_backendObject) { \
return globalFactory->m_backendObject->property(#name).toString(); \
} \
return QString(); \
} \
GET_STRING_PROPERTY(identifier)
GET_STRING_PROPERTY(backendName)
GET_STRING_PROPERTY(backendComment)
GET_STRING_PROPERTY(backendVersion)
GET_STRING_PROPERTY(backendIcon)
GET_STRING_PROPERTY(backendWebsite)
QObject *Factory::registerQObject(QObject *o)
{
if (o) {
QObject::connect(o, SIGNAL(destroyed(QObject *)), globalFactory, SLOT(objectDestroyed(QObject *)), Qt::DirectConnection);
globalFactory->objects.append(o);
}
return o;
}
} //namespace Phonon
QT_END_NAMESPACE
#include "factory.moc"
#include "moc_factory_p.cpp"
// vim: sw=4 ts=4
<commit_msg>remove a compiler warning<commit_after>/* This file is part of the KDE project
Copyright (C) 2004-2007 Matthias Kretz <[email protected]>
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) version 3, or any
later version accepted by the membership of KDE e.V. (or its
successor approved by the membership of KDE e.V.), Trolltech ASA
(or its successors, if any) and the KDE Free Qt Foundation, which shall
act as a proxy defined in Section 6 of version 3 of the license.
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, see <http://www.gnu.org/licenses/>.
*/
#include "factory_p.h"
#include "backendinterface.h"
#include "medianode_p.h"
#include "mediaobject.h"
#include "audiooutput.h"
#include "globalstatic_p.h"
#include "objectdescription.h"
#include "platformplugin.h"
#include "phononnamespace_p.h"
#include <QtCore/QCoreApplication>
#include <QtCore/QDir>
#include <QtCore/QList>
#include <QtCore/QPluginLoader>
#include <QtCore/QPointer>
#ifndef QT_NO_DBUS
#include <QtDBus/QtDBus>
#endif
QT_BEGIN_NAMESPACE
namespace Phonon
{
class PlatformPlugin;
class FactoryPrivate : public Phonon::Factory::Sender
{
friend QObject *Factory::backend(bool);
Q_OBJECT
public:
FactoryPrivate();
~FactoryPrivate();
bool createBackend();
#ifndef QT_NO_PHONON_PLATFORMPLUGIN
PlatformPlugin *platformPlugin();
PlatformPlugin *m_platformPlugin;
bool m_noPlatformPlugin;
#endif //QT_NO_PHONON_PLATFORMPLUGIN
QPointer<QObject> m_backendObject;
QList<QObject *> objects;
QList<MediaNodePrivate *> mediaNodePrivateList;
private Q_SLOTS:
/**
* This is called via DBUS when the user changes the Phonon Backend.
*/
#ifndef QT_NO_DBUS
void phononBackendChanged();
#endif //QT_NO_DBUS
/**
* unregisters the backend object
*/
void objectDestroyed(QObject *);
void objectDescriptionChanged(ObjectDescriptionType);
};
PHONON_GLOBAL_STATIC(Phonon::FactoryPrivate, globalFactory)
static inline void ensureLibraryPathSet()
{
#ifdef PHONON_LIBRARY_PATH
static bool done = false;
if (!done) {
done = true;
QCoreApplication::addLibraryPath(QLatin1String(PHONON_LIBRARY_PATH));
}
#endif // PHONON_LIBRARY_PATH
}
void Factory::setBackend(QObject *b)
{
Q_ASSERT(globalFactory->m_backendObject == 0);
globalFactory->m_backendObject = b;
}
/*void Factory::createBackend(const QString &library, const QString &version)
{
Q_ASSERT(globalFactory->m_backendObject == 0);
PlatformPlugin *f = globalFactory->platformPlugin();
if (f) {
globalFactory->m_backendObject = f->createBackend(library, version);
}
}*/
bool FactoryPrivate::createBackend()
{
Q_ASSERT(m_backendObject == 0);
#ifndef QT_NO_PHONON_PLATFORMPLUGIN
PlatformPlugin *f = globalFactory->platformPlugin();
if (f) {
m_backendObject = f->createBackend();
}
#endif //QT_NO_PHONON_PLATFORMPLUGIN
if (!m_backendObject) {
ensureLibraryPathSet();
// could not load a backend through the platform plugin. Falling back to the default
// (finding the first loadable backend).
const QLatin1String suffix("/phonon_backend/");
foreach (QString libPath, QCoreApplication::libraryPaths()) {
libPath += suffix;
const QDir dir(libPath);
if (!dir.exists()) {
pDebug() << Q_FUNC_INFO << dir.absolutePath() << "does not exist";
continue;
}
foreach (const QString &pluginName, dir.entryList(QDir::Files)) {
QPluginLoader pluginLoader(libPath + pluginName);
if (!pluginLoader.load()) {
pDebug() << Q_FUNC_INFO << " load failed:"
<< pluginLoader.errorString();
continue;
}
pDebug() << pluginLoader.instance();
m_backendObject = pluginLoader.instance();
if (m_backendObject) {
break;
}
// no backend found, don't leave an unused plugin in memory
pluginLoader.unload();
}
if (m_backendObject) {
break;
}
}
if (!m_backendObject) {
pWarning() << Q_FUNC_INFO << "phonon backend plugin could not be loaded";
return false;
}
}
connect(m_backendObject, SIGNAL(objectDescriptionChanged(ObjectDescriptionType)),
SLOT(objectDescriptionChanged(ObjectDescriptionType)));
return true;
}
FactoryPrivate::FactoryPrivate()
#ifndef QT_NO_PHONON_PLATFORMPLUGIN
: m_platformPlugin(0),
m_noPlatformPlugin(false)
#endif //QT_NO_PHONON_PLATFORMPLUGIN
, m_backendObject(0)
{
// Add the post routine to make sure that all other global statics (especially the ones from Qt)
// are still available. If the FactoryPrivate dtor is called too late many bad things can happen
// as the whole backend might still be alive.
qAddPostRoutine(globalFactory.destroy);
#ifndef QT_NO_DBUS
QDBusConnection::sessionBus().connect(QString(), QString(), "org.kde.Phonon.Factory",
"phononBackendChanged", this, SLOT(phononBackendChanged()));
#endif
}
FactoryPrivate::~FactoryPrivate()
{
foreach (QObject *o, objects) {
MediaObject *m = qobject_cast<MediaObject *>(o);
if (m) {
m->stop();
}
}
foreach (MediaNodePrivate *bp, mediaNodePrivateList) {
bp->deleteBackendObject();
}
if (objects.size() > 0) {
pError() << "The backend objects are not deleted as was requested.";
qDeleteAll(objects);
}
delete m_backendObject;
#ifndef QT_NO_PHONON_PLATFORMPLUGIN
delete m_platformPlugin;
#endif //QT_NO_PHONON_PLATFORMPLUGIN
}
void FactoryPrivate::objectDescriptionChanged(ObjectDescriptionType type)
{
#ifdef PHONON_METHODTEST
Q_UNUSED(type);
#else
pDebug() << Q_FUNC_INFO << type;
switch (type) {
case AudioOutputDeviceType:
emit availableAudioOutputDevicesChanged();
break;
case AudioCaptureDeviceType:
emit availableAudioCaptureDevicesChanged();
break;
default:
break;
}
//emit capabilitiesChanged();
#endif // PHONON_METHODTEST
}
Factory::Sender *Factory::sender()
{
return globalFactory;
}
bool Factory::isMimeTypeAvailable(const QString &mimeType)
{
#ifndef QT_NO_PHONON_PLATFORMPLUGIN
PlatformPlugin *f = globalFactory->platformPlugin();
if (f) {
return f->isMimeTypeAvailable(mimeType);
}
#else
Q_UNUSED(mimeType);
#endif //QT_NO_PHONON_PLATFORMPLUGIN
return true; // the MIME type might be supported, let BackendCapabilities find out
}
void Factory::registerFrontendObject(MediaNodePrivate *bp)
{
globalFactory->mediaNodePrivateList.prepend(bp); // inserted last => deleted first
}
void Factory::deregisterFrontendObject(MediaNodePrivate *bp)
{
// The Factory can already be cleaned up while there are other frontend objects still alive.
// When those are deleted they'll call deregisterFrontendObject through ~BasePrivate
if (!globalFactory.isDestroyed()) {
globalFactory->mediaNodePrivateList.removeAll(bp);
}
}
#ifndef QT_NO_DBUS
void FactoryPrivate::phononBackendChanged()
{
if (m_backendObject) {
foreach (MediaNodePrivate *bp, mediaNodePrivateList) {
bp->deleteBackendObject();
}
if (objects.size() > 0) {
pDebug() << "WARNING: we were asked to change the backend but the application did\n"
"not free all references to objects created by the factory. Therefore we can not\n"
"change the backend without crashing. Now we have to wait for a restart to make\n"
"backendswitching possible.";
// in case there were objects deleted give 'em a chance to recreate
// them now
foreach (MediaNodePrivate *bp, mediaNodePrivateList) {
bp->createBackendObject();
}
return;
}
delete m_backendObject;
m_backendObject = 0;
}
createBackend();
foreach (MediaNodePrivate *bp, mediaNodePrivateList) {
bp->createBackendObject();
}
emit backendChanged();
}
#endif //QT_NO_DBUS
//X void Factory::freeSoundcardDevices()
//X {
//X if (globalFactory->backend) {
//X globalFactory->backend->freeSoundcardDevices();
//X }
//X }
void FactoryPrivate::objectDestroyed(QObject * obj)
{
//pDebug() << Q_FUNC_INFO << obj;
objects.removeAll(obj);
}
#define FACTORY_IMPL(classname) \
QObject *Factory::create ## classname(QObject *parent) \
{ \
if (backend()) { \
return registerQObject(qobject_cast<BackendInterface *>(backend())->createObject(BackendInterface::classname##Class, parent)); \
} \
return 0; \
}
#define FACTORY_IMPL_1ARG(classname) \
QObject *Factory::create ## classname(int arg1, QObject *parent) \
{ \
if (backend()) { \
return registerQObject(qobject_cast<BackendInterface *>(backend())->createObject(BackendInterface::classname##Class, parent, QList<QVariant>() << arg1)); \
} \
return 0; \
}
FACTORY_IMPL(MediaObject)
#ifndef QT_NO_PHONON_EFFECT
FACTORY_IMPL_1ARG(Effect)
#endif //QT_NO_PHONON_EFFECT
#ifndef QT_NO_PHONON_VOLUMEFADEREFFECT
FACTORY_IMPL(VolumeFaderEffect)
#endif //QT_NO_PHONON_VOLUMEFADEREFFECT
FACTORY_IMPL(AudioOutput)
#ifndef QT_NO_PHONON_VIDEO
FACTORY_IMPL(VideoWidget)
#endif //QT_NO_PHONON_VIDEO
#undef FACTORY_IMPL
#ifndef QT_NO_PHONON_PLATFORMPLUGIN
PlatformPlugin *FactoryPrivate::platformPlugin()
{
if (m_platformPlugin) {
return m_platformPlugin;
}
if (m_noPlatformPlugin) {
return 0;
}
#ifndef QT_NO_DBUS
if (!QCoreApplication::instance() || QCoreApplication::applicationName().isEmpty()) {
pWarning() << "Phonon needs QCoreApplication::applicationName to be set to export audio output names through the DBUS interface";
}
#endif
Q_ASSERT(QCoreApplication::instance());
const QByteArray platform_plugin_env = qgetenv("PHONON_PLATFORMPLUGIN");
if (!platform_plugin_env.isEmpty()) {
QPluginLoader pluginLoader(QString::fromLocal8Bit(platform_plugin_env.constData()));
if (pluginLoader.load()) {
m_platformPlugin = qobject_cast<PlatformPlugin *>(pluginLoader.instance());
if (m_platformPlugin) {
return m_platformPlugin;
}
}
}
const QString suffix(QLatin1String("/phonon_platform/"));
ensureLibraryPathSet();
QDir dir;
dir.setNameFilters(
!qgetenv("KDE_FULL_SESSION").isEmpty() ? QStringList(QLatin1String("kde.*")) :
(!qgetenv("GNOME_DESKTOP_SESSION_ID").isEmpty() ? QStringList(QLatin1String("gnome.*")) :
QStringList())
);
dir.setFilter(QDir::Files);
forever {
foreach (QString libPath, QCoreApplication::libraryPaths()) {
libPath += suffix;
dir.setPath(libPath);
if (!dir.exists()) {
continue;
}
foreach (const QString &pluginName, dir.entryList()) {
QPluginLoader pluginLoader(libPath + pluginName);
if (!pluginLoader.load()) {
pDebug() << Q_FUNC_INFO << " platform plugin load failed:"
<< pluginLoader.errorString();
continue;
}
pDebug() << pluginLoader.instance();
QObject *qobj = pluginLoader.instance();
m_platformPlugin = qobject_cast<PlatformPlugin *>(qobj);
pDebug() << m_platformPlugin;
if (m_platformPlugin) {
connect(qobj, SIGNAL(objectDescriptionChanged(ObjectDescriptionType)),
SLOT(objectDescriptionChanged(ObjectDescriptionType)));
return m_platformPlugin;
} else {
delete qobj;
pDebug() << Q_FUNC_INFO << dir.absolutePath() << "exists but the platform plugin was not loadable:" << pluginLoader.errorString();
pluginLoader.unload();
}
}
}
if (dir.nameFilters().isEmpty()) {
break;
}
dir.setNameFilters(QStringList());
}
pDebug() << Q_FUNC_INFO << "platform plugin could not be loaded";
m_noPlatformPlugin = true;
return 0;
}
PlatformPlugin *Factory::platformPlugin()
{
return globalFactory->platformPlugin();
}
#endif // QT_NO_PHONON_PLATFORMPLUGIN
QObject *Factory::backend(bool createWhenNull)
{
if (globalFactory.isDestroyed()) {
return 0;
}
if (createWhenNull && globalFactory->m_backendObject == 0) {
globalFactory->createBackend();
// XXX: might create "reentrancy" problems:
// a method calls this method and is called again because the
// backendChanged signal is emitted
emit globalFactory->backendChanged();
}
return globalFactory->m_backendObject;
}
#define GET_STRING_PROPERTY(name) \
QString Factory::name() \
{ \
if (globalFactory->m_backendObject) { \
return globalFactory->m_backendObject->property(#name).toString(); \
} \
return QString(); \
} \
GET_STRING_PROPERTY(identifier)
GET_STRING_PROPERTY(backendName)
GET_STRING_PROPERTY(backendComment)
GET_STRING_PROPERTY(backendVersion)
GET_STRING_PROPERTY(backendIcon)
GET_STRING_PROPERTY(backendWebsite)
QObject *Factory::registerQObject(QObject *o)
{
if (o) {
QObject::connect(o, SIGNAL(destroyed(QObject *)), globalFactory, SLOT(objectDestroyed(QObject *)), Qt::DirectConnection);
globalFactory->objects.append(o);
}
return o;
}
} //namespace Phonon
QT_END_NAMESPACE
#include "factory.moc"
#include "moc_factory_p.cpp"
// vim: sw=4 ts=4
<|endoftext|> |
<commit_before>#include "life.h"
#include <iostream>
#include <thread>
#include <chrono>
#include <functional>
#include <string.h>
using namespace std;
Life::Life() {
board = new map<long, map<long, bool> >;
}
void Life::set_living(long x, long y) {
(*board)[x][y] = true;
}
void Life::set_dead(long x, long y) {
(*board)[x].erase(y);
}
map<long, map<long, bool> >* Life::get_births() {
map<long, map<long, bool> >* births = new map<long, map<long, bool> >;
for (auto const &ent1 : *board) {
for (auto const &ent2 : ent1.second) {
long x = ent1.first,
y = ent2.first;
vector<Point> neighbors = get_neighbors(x, y);
for (auto &neighbor : neighbors) {
if (should_give_birth(neighbor.x, neighbor.y)) {
(*births)[neighbor.x][neighbor.y] = true;
}
}
}
}
return births;
}
map<long, map<long, bool> >* Life::get_deaths() {
map<long, map<long, bool> >* deaths = new map<long, map<long, bool> >;
for (auto const &ent1 : *board) {
for (auto const &ent2 : ent1.second) {
long x = ent1.first,
y = ent2.first;
if (should_die(x, y)) {
(*deaths)[x][y] = true;
}
}
}
return deaths;
}
string Life::map_to_json(map<long, map<long, bool> >* m) {
return map_to_json(m, "true");
}
string Life::map_to_json(map<long, map<long, bool> >* m, string existsKey) {
string json = "{";
size_t len = json.size();
for (auto &ent1 : *m) {
json += ("\"" + to_string(ent1.first) + "\":{");
int json_size = json.size();
for (auto &ent2 : ent1.second) {
json += "\"" + to_string(ent2.first) + "\":" + existsKey + ",";
}
if (json_size < json.size()) { json.pop_back(); }
json += "},";
}
if (len < json.size()) { json.pop_back(); }
json += "}";
return json;
}
bool Life::should_give_birth(long x, long y) {
if (board->count(x) == 0 ||
board->at(x).count(y) == 0) {
return get_num_live_neighbors(x, y) == 3;
}
return false;
}
bool Life::should_die(long x, long y) {
int n = get_num_live_neighbors(x, y);
return n < 2 || n > 3;
}
vector<Point> Life::get_neighbors(long x, long y) {
vector<Point> neighbors;
long left = x - 1,
top = y - 1,
right_edge = left + 3,
bottom_edge = top + 3;
if (left < 0) { left = 0; }
if (top < 0) { top = 0; }
// iterate through neighbors
for (long i = left; i < right_edge; i++) {
for (long j = top; j < bottom_edge; j++) {
if (i == x && j == y) { continue; }
Point p(i, j);
neighbors.push_back(p);
}
}
return neighbors;
}
int Life::get_num_live_neighbors(long x, long y) {
int live_neighbors = 0;
vector<Point> neighbors = get_neighbors(x, y);
for (auto &neighbor : neighbors) {
if (board->count(neighbor.x)) {
map<long, bool> m = board->at(neighbor.x);
if (m.count(neighbor.y)) {
live_neighbors++;
}
}
}
return live_neighbors;
}
void Life::add_points(string points) {
size_t i = 0,
len = points.size(),
pos = 0;
long x, y;
while (i < len && pos != string::npos) {
pos = points.find(" ", i);
x = stol(points.substr(i, pos));
i = pos + 1;
pos = points.find(" ", i);
y = stol(points.substr(i, pos));
i = pos + 1;
set_living(x, y);
}
}
void Life::step() {
auto births = get_births();
auto deaths = get_deaths();
for (auto ent1 : *births) {
long x = ent1.first;
for (auto ent2 : ent1.second) {
long y = ent2.first;
set_living(x, y);
}
}
string births_json = Life::map_to_json(births);
delete births;
for (auto ent1 : *deaths) {
long x = ent1.first;
for (auto ent2 : ent1.second) {
long y = ent2.first;
set_dead(x, y);
}
}
string deaths_json = Life::map_to_json(deaths, "null");
delete deaths;
cout << "{\"births\":";
cout << births_json;
cout << ",\"deaths\":";
cout << deaths_json;
cout << "}" << endl;
}
void timer(
function<void(Life*)> exit_fn, Life* life,
atomic<bool>* shouldClose, unsigned int interval) {
thread([exit_fn, life, shouldClose, interval]() {
while (true) {
if (*shouldClose) {
exit_fn(life);
} else {
*shouldClose = true;
this_thread::sleep_for(chrono::milliseconds(interval));
}
}
}).detach();
}
void exit_fn(Life* life) {
delete life;
exit(0);
}
int main(int argc, char* argv[]) {
atomic<bool> shouldClose(false);
Life* life = new Life();
timer(exit_fn, life, &shouldClose, 10000);
for (string s; getline(cin, s);) {
shouldClose = false;
life->add_points(s);
life->step();
}
}
<commit_msg>Added missing #include<commit_after>#include "life.h"
#include <atomic>
#include <chrono>
#include <thread>
#include <iostream>
#include <functional>
#include <string.h>
using namespace std;
Life::Life() {
board = new map<long, map<long, bool> >;
}
void Life::set_living(long x, long y) {
(*board)[x][y] = true;
}
void Life::set_dead(long x, long y) {
(*board)[x].erase(y);
}
map<long, map<long, bool> >* Life::get_births() {
map<long, map<long, bool> >* births = new map<long, map<long, bool> >;
for (auto const &ent1 : *board) {
for (auto const &ent2 : ent1.second) {
long x = ent1.first,
y = ent2.first;
vector<Point> neighbors = get_neighbors(x, y);
for (auto &neighbor : neighbors) {
if (should_give_birth(neighbor.x, neighbor.y)) {
(*births)[neighbor.x][neighbor.y] = true;
}
}
}
}
return births;
}
map<long, map<long, bool> >* Life::get_deaths() {
map<long, map<long, bool> >* deaths = new map<long, map<long, bool> >;
for (auto const &ent1 : *board) {
for (auto const &ent2 : ent1.second) {
long x = ent1.first,
y = ent2.first;
if (should_die(x, y)) {
(*deaths)[x][y] = true;
}
}
}
return deaths;
}
string Life::map_to_json(map<long, map<long, bool> >* m) {
return map_to_json(m, "true");
}
string Life::map_to_json(map<long, map<long, bool> >* m, string existsKey) {
string json = "{";
size_t len = json.size();
for (auto &ent1 : *m) {
json += ("\"" + to_string(ent1.first) + "\":{");
int json_size = json.size();
for (auto &ent2 : ent1.second) {
json += "\"" + to_string(ent2.first) + "\":" + existsKey + ",";
}
if (json_size < json.size()) { json.pop_back(); }
json += "},";
}
if (len < json.size()) { json.pop_back(); }
json += "}";
return json;
}
bool Life::should_give_birth(long x, long y) {
if (board->count(x) == 0 ||
board->at(x).count(y) == 0) {
return get_num_live_neighbors(x, y) == 3;
}
return false;
}
bool Life::should_die(long x, long y) {
int n = get_num_live_neighbors(x, y);
return n < 2 || n > 3;
}
vector<Point> Life::get_neighbors(long x, long y) {
vector<Point> neighbors;
long left = x - 1,
top = y - 1,
right_edge = left + 3,
bottom_edge = top + 3;
if (left < 0) { left = 0; }
if (top < 0) { top = 0; }
// iterate through neighbors
for (long i = left; i < right_edge; i++) {
for (long j = top; j < bottom_edge; j++) {
if (i == x && j == y) { continue; }
Point p(i, j);
neighbors.push_back(p);
}
}
return neighbors;
}
int Life::get_num_live_neighbors(long x, long y) {
int live_neighbors = 0;
vector<Point> neighbors = get_neighbors(x, y);
for (auto &neighbor : neighbors) {
if (board->count(neighbor.x)) {
map<long, bool> m = board->at(neighbor.x);
if (m.count(neighbor.y)) {
live_neighbors++;
}
}
}
return live_neighbors;
}
void Life::add_points(string points) {
size_t i = 0,
len = points.size(),
pos = 0;
long x, y;
while (i < len && pos != string::npos) {
pos = points.find(" ", i);
x = stol(points.substr(i, pos));
i = pos + 1;
pos = points.find(" ", i);
y = stol(points.substr(i, pos));
i = pos + 1;
set_living(x, y);
}
}
void Life::step() {
auto births = get_births();
auto deaths = get_deaths();
for (auto ent1 : *births) {
long x = ent1.first;
for (auto ent2 : ent1.second) {
long y = ent2.first;
set_living(x, y);
}
}
string births_json = Life::map_to_json(births);
delete births;
for (auto ent1 : *deaths) {
long x = ent1.first;
for (auto ent2 : ent1.second) {
long y = ent2.first;
set_dead(x, y);
}
}
string deaths_json = Life::map_to_json(deaths, "null");
delete deaths;
cout << "{\"births\":";
cout << births_json;
cout << ",\"deaths\":";
cout << deaths_json;
cout << "}" << endl;
}
void timer(
function<void(Life*)> exit_fn, Life* life,
atomic<bool>* shouldClose, unsigned int interval) {
thread([exit_fn, life, shouldClose, interval]() {
while (true) {
if (*shouldClose) {
exit_fn(life);
} else {
*shouldClose = true;
this_thread::sleep_for(chrono::milliseconds(interval));
}
}
}).detach();
}
void exit_fn(Life* life) {
delete life;
exit(0);
}
int main(int argc, char* argv[]) {
atomic<bool> shouldClose(false);
Life* life = new Life();
timer(exit_fn, life, &shouldClose, 10000);
for (string s; getline(cin, s);) {
shouldClose = false;
life->add_points(s);
life->step();
}
}
<|endoftext|> |
<commit_before>// Base header file. Must be first.
#include <Include/PlatformDefinitions.hpp>
#include <cassert>
#if defined(XALAN_OLD_STREAM_HEADERS)
#include <iostream.h>
#else
#include <iostream>
#endif
#include <util/PlatformUtils.hpp>
#include <util/Mutexes.hpp>
#include <PlatformSupport/DOMStringHelper.hpp>
#include <PlatformSupport/XalanFileOutputStream.hpp>
#include <PlatformSupport/XalanOutputStreamPrintWriter.hpp>
#include <XalanSourceTree/XalanSourceTreeDOMSupport.hpp>
#include <XalanSourceTree/XalanSourceTreeParserLiaison.hpp>
#include <XPath/XObjectFactoryDefault.hpp>
#include <XPath/XPathFactoryDefault.hpp>
#include <XSLT/StylesheetConstructionContextDefault.hpp>
#include <XSLT/StylesheetExecutionContextDefault.hpp>
#include <XSLT/StylesheetRoot.hpp>
#include <XSLT/XSLTEngineImpl.hpp>
#include <XSLT/XSLTInit.hpp>
#include <XSLT/XSLTInputSource.hpp>
#include <XSLT/XSLTProcessorEnvSupportDefault.hpp>
#include <XSLT/XSLTResultTarget.hpp>
#if defined(WIN32)
//This is here for the threads.
#include <process.h>
#define WIN32_LEAN_AND_MEAN
#include <windows.h>
#elif defined(XALAN_POSIX2_AVAILABLE)
#include <pthread.h>
#include <unistd.h>
#else
#error Unsupported platform!
#endif
#if !defined(XALAN_NO_NAMESPACES)
using std::cerr;
using std::cout;
using std::endl;
using std::vector;
#endif
// This is here for memory leak testing.
#if defined(_DEBUG)
#include <crtdbg.h>
#endif
// Used to hold compiled stylesheet
StylesheetRoot* glbStylesheetRoot;
class SynchronizedCounter
{
public:
SynchronizedCounter();
~SynchronizedCounter();
void
increment();
void
decrement();
unsigned long
getCounter() const;
private:
mutable XMLMutex m_mutex;
unsigned long m_counter;
};
SynchronizedCounter::SynchronizedCounter() :
m_mutex(),
m_counter(0)
{
}
SynchronizedCounter::~SynchronizedCounter()
{
}
void
SynchronizedCounter::increment()
{
XMLMutexLock theLock(&m_mutex);
if (m_counter < ULONG_MAX)
{
++m_counter;
}
}
void
SynchronizedCounter::decrement()
{
XMLMutexLock theLock(&m_mutex);
if (m_counter > 0)
{
--m_counter;
}
}
unsigned long
SynchronizedCounter::getCounter() const
{
return m_counter;
}
struct
ThreadInfo
{
ThreadInfo(
unsigned int theThreadNumber = 0,
SynchronizedCounter* theCounter = 0) :
m_threadNumber(theThreadNumber),
m_counter(theCounter)
{
}
ThreadInfo(const ThreadInfo& theSource) :
m_threadNumber(theSource.m_threadNumber),
m_counter(theSource.m_counter)
{
}
unsigned int m_threadNumber;
SynchronizedCounter* m_counter;
};
#if defined(WIN32)
extern "C" void theThreadRoutine(void* param);
void
#elif defined(XALAN_POSIX2_AVAILABLE)
extern "C" void* theThreadRoutine(void* param);
void*
#else
#error Unsupported platform!
#endif
theThreadRoutine(void* param)
{
// This routine uses compiled stylesheet (glbStylesheetRoot), which is set using the
// theProcessor.setStylesheetRoot method. The transform is done using the theProcessor's
// process() method.
#if defined(XALAN_OLD_STYLE_CASTS)
const ThreadInfo* const theInfo = (const ThreadInfo*)param;
#else
const ThreadInfo* const theInfo = reinterpret_cast<const ThreadInfo*>(param);
#endif
assert(theInfo != 0);
theInfo->m_counter->increment();
try
{
// Create the support objects that are necessary for running the processor...
XalanSourceTreeDOMSupport theDOMSupport;
XalanSourceTreeParserLiaison theParserLiaison(theDOMSupport);
theDOMSupport.setParserLiaison(&theParserLiaison);
// The default is that documents are not thread-safe. Set this to
// true so they are.
//theParserLiaison.setThreadSafe(true);
XSLTProcessorEnvSupportDefault theXSLTProcessorEnvSupport;
XObjectFactoryDefault theXObjectFactory;
XPathFactoryDefault theXPathFactory;
// Create a processor...and output start message.
XSLTEngineImpl theProcessor(
theParserLiaison,
theXSLTProcessorEnvSupport,
theDOMSupport,
theXObjectFactory,
theXPathFactory);
// Connect the processor to the support object...
theXSLTProcessorEnvSupport.setProcessor(&theProcessor);
// The execution context uses the same factory support objects as
// the processor, since those objects have the same lifetime as
// other objects created as a result of the execution.
StylesheetExecutionContextDefault ssExecutionContext(
theProcessor,
theXSLTProcessorEnvSupport,
theDOMSupport,
theXObjectFactory);
// Our input files. The assumption is that the executable will be run
// from same directory as the input files.
// Generate the input and output file names.
const XalanDOMString theXMLfile("birds.xml");
const XalanDOMString theOutputFile(
XalanDOMString("birds") +
UnsignedLongToDOMString(theInfo->m_threadNumber) +
XalanDOMString(".out"));
//Generate the XML input and output objects.
XSLTInputSource theInputSource(c_wstr(theXMLfile));
XSLTResultTarget theResultTarget(theOutputFile);
// Set the stylesheet to be the compiled stylesheet. Then do the transform.
// Report both the start of the transform and end of the thread.
theProcessor.setStylesheetRoot(glbStylesheetRoot);
theProcessor.process(theInputSource,theResultTarget,ssExecutionContext);
}
catch(...)
{
cerr << "Exception caught in thread " << theInfo->m_threadNumber;
}
// Decrement the counter because we're done...
theInfo->m_counter->decrement();
#if defined(XALAN_POSIX2_AVAILABLE)
return 0;
#endif
}
inline void
doSleep(unsigned int theMilliseconds)
{
#if defined(WIN32)
Sleep(theMilliseconds);
#elif defined(XALAN_POSIX2_AVAILABLE)
usleep(theMilliseconds * 10);
#else
#error Unsupported platform!
#endif
}
void
doThreads(long theThreadCount)
{
cout << endl << "Starting " << theThreadCount << " threads." << endl;
typedef vector<ThreadInfo> ThreadInfoVectorType;
ThreadInfoVectorType theThreadInfo;
theThreadInfo.reserve(theThreadCount);
try
{
cout << endl << "Clock before starting threads: " << clock() << endl;
SynchronizedCounter theCounter;
for (long i = 0; i < theThreadCount; i++)
{
theThreadInfo.push_back(ThreadInfoVectorType::value_type(i, &theCounter));
#if defined(WIN32)
const unsigned long theThreadID =
_beginthread(theThreadRoutine, 4096, reinterpret_cast<LPVOID>(&theThreadInfo.back()));
if (theThreadID == unsigned(-1))
{
cerr << endl << "Unable to create thread number " << i + 1 << "." << endl;
}
#elif defined(XALAN_POSIX2_AVAILABLE)
pthread_t theThread;
const int theResult = pthread_create(&theThread, 0, theThreadRoutine, (void*)&theThreadInfo.back());
if (theResult != 0)
{
cerr << endl << "Unable to create thread number " << i + 1 << "." << endl;
}
else
{
#if defined(OS390)
pthread_detach(&theThread);
#else
pthread_detach(theThread);
#endif
}
#else
#error Unsupported platform!
#endif
}
clock_t theClock = 0;
if (theThreadInfo.size() == 0)
{
cerr << endl << "No threads were created!" << endl;
}
else
{
unsigned int theCheckCount = 0;
do
{
doSleep(2000);
// Check a couple of times, just in case, since
// getCounter() is not synchronized...
if (theCounter.getCounter() == 0)
{
if (theCheckCount == 0)
{
theClock = clock();
}
++theCheckCount;
}
}
while(theCheckCount < 2);
}
cout << endl << "Clock after threads: " << theClock << endl;
}
catch(...)
{
cerr << "Exception caught!!!"
<< endl
<< endl;
}
}
int
main(
int argc,
const char* argv[])
{
#if !defined(NDEBUG) && defined(_MSC_VER)
_CrtSetDbgFlag(_CrtSetDbgFlag(_CRTDBG_REPORT_FLAG) | _CRTDBG_LEAK_CHECK_DF);
_CrtSetReportMode(_CRT_WARN, _CRTDBG_MODE_FILE);
_CrtSetReportFile(_CRT_WARN, _CRTDBG_FILE_STDERR);
#endif
if (argc > 2)
{
cerr << "Usage: ThreadTest"
<< endl
<< endl;
}
else
{
int threadCount = 60;
if (argc == 2)
{
threadCount = atoi(argv[1]);
}
try
{
// Call the static initializers...
XMLPlatformUtils::Initialize();
{
XSLTInit theInit;
// Create the necessary stuff of compile the stylesheet.
XercesDOMSupport ssDOMSupport;
XercesParserLiaison ssParserLiaison(ssDOMSupport);
XSLTProcessorEnvSupportDefault ssXSLTProcessorEnvSupport;
XObjectFactoryDefault ssXObjectFactory;
XPathFactoryDefault ssXPathFactory;
// Create a processor to compile the stylesheet...
XSLTEngineImpl ssProcessor(
ssParserLiaison,
ssXSLTProcessorEnvSupport,
ssDOMSupport,
ssXObjectFactory,
ssXPathFactory);
// Create separate factory support objects so the stylesheet's
// factory-created XObject and XPath instances are independent
// from processor's.
XPathFactoryDefault ssStylesheetXPathFactory;
// Create a stylesheet construction context, using the
// stylesheet's factory support objects.
StylesheetConstructionContextDefault ssConstructionContext(
ssProcessor,
ssXSLTProcessorEnvSupport,
ssStylesheetXPathFactory);
const XalanDOMString theXSLFileName("birds.xsl");
const XalanDOMString theXMLFileName("birds.xml");
// Our stylesheet input source...
XSLTInputSource ssStylesheetSourceXSL(c_wstr(theXSLFileName));
XSLTInputSource ssStylesheetSourceXML(c_wstr(theXMLFileName));
// Ask the processor to create a StylesheetRoot for the specified
// input XSL. This is the compiled stylesheet. We don't have to
// delete it, since it is owned by the StylesheetConstructionContext
// instance.
glbStylesheetRoot = ssProcessor.processStylesheet(ssStylesheetSourceXSL,
ssConstructionContext);
assert(glbStylesheetRoot != 0);
doThreads(threadCount);
}
XMLPlatformUtils::Terminate();
}
catch(...)
{
cerr << "Exception caught!!!"
<< endl
<< endl;
}
}
return 0;
}
<commit_msg>Updated test to use XalanTransformer.<commit_after>// Base header file. Must be first.
#include <Include/PlatformDefinitions.hpp>
#include <cassert>
#if defined(XALAN_OLD_STREAM_HEADERS)
#include <iostream.h>
#else
#include <iostream>
#endif
#include <util/PlatformUtils.hpp>
#include <util/Mutexes.hpp>
#include <XalanTransformer/XalanTransformer.hpp>
#if defined(WIN32)
//This is here for the threads.
#include <process.h>
#define WIN32_LEAN_AND_MEAN
#include <windows.h>
#elif defined(XALAN_POSIX2_AVAILABLE)
#include <pthread.h>
#include <unistd.h>
#else
#error Unsupported platform!
#endif
#if !defined(XALAN_NO_NAMESPACES)
using std::cerr;
using std::cout;
using std::endl;
using std::vector;
#endif
// This is here for memory leak testing.
#if defined(_DEBUG)
#include <crtdbg.h>
#endif
class SynchronizedCounter
{
public:
SynchronizedCounter();
~SynchronizedCounter();
void
increment();
void
decrement();
unsigned long
getCounter() const;
private:
mutable XMLMutex m_mutex;
unsigned long m_counter;
};
SynchronizedCounter::SynchronizedCounter() :
m_mutex(),
m_counter(0)
{
}
SynchronizedCounter::~SynchronizedCounter()
{
}
void
SynchronizedCounter::increment()
{
XMLMutexLock theLock(&m_mutex);
if (m_counter < ULONG_MAX)
{
++m_counter;
}
}
void
SynchronizedCounter::decrement()
{
XMLMutexLock theLock(&m_mutex);
if (m_counter > 0)
{
--m_counter;
}
}
unsigned long
SynchronizedCounter::getCounter() const
{
return m_counter;
}
struct
ThreadInfo
{
ThreadInfo(
unsigned int theThreadNumber = 0,
SynchronizedCounter* theCounter = 0) :
m_threadNumber(theThreadNumber),
m_counter(theCounter)
{
}
ThreadInfo(const ThreadInfo& theSource) :
m_threadNumber(theSource.m_threadNumber),
m_counter(theSource.m_counter)
{
}
unsigned int m_threadNumber;
SynchronizedCounter* m_counter;
};
// Used to hold compiled stylesheet and pre-parsed source...
XalanCompiledStylesheet* glbCompiledStylesheet = 0;
XalanParsedSource* glbParsedSource = 0;
#if defined(WIN32)
extern "C" void theThreadRoutine(void* param);
void
#elif defined(XALAN_POSIX2_AVAILABLE)
extern "C" void* theThreadRoutine(void* param);
void*
#else
#error Unsupported platform!
#endif
theThreadRoutine(void* param)
{
// This routine uses compiled stylesheet (glbStylesheetRoot), which is set using the
// theProcessor.setStylesheetRoot method. The transform is done using the theProcessor's
// process() method.
#if defined(XALAN_OLD_STYLE_CASTS)
const ThreadInfo* const theInfo = (const ThreadInfo*)param;
#else
const ThreadInfo* const theInfo = reinterpret_cast<const ThreadInfo*>(param);
#endif
assert(theInfo != 0);
theInfo->m_counter->increment();
try
{
// Our input file. The assumption is that the executable will be run
// from same directory as the input files.
// Generate the output file name.
const XalanDOMString theOutputFile(
XalanDOMString("birds") +
UnsignedLongToDOMString(theInfo->m_threadNumber) +
XalanDOMString(".out"));
// Create a transformer...
XalanTransformer theTransformer;
// Do the transform...
theTransformer.transform(*glbParsedSource, glbCompiledStylesheet, XSLTResultTarget(theOutputFile));
}
catch(...)
{
cerr << "Exception caught in thread " << theInfo->m_threadNumber;
}
// Decrement the counter because we're done...
theInfo->m_counter->decrement();
#if defined(XALAN_POSIX2_AVAILABLE)
return 0;
#endif
}
inline void
doSleep(unsigned int theMilliseconds)
{
#if defined(WIN32)
Sleep(theMilliseconds);
#elif defined(XALAN_POSIX2_AVAILABLE)
usleep(theMilliseconds * 10);
#else
#error Unsupported platform!
#endif
}
void
doThreads(long theThreadCount)
{
cout << endl << "Starting " << theThreadCount << " threads." << endl;
typedef vector<ThreadInfo> ThreadInfoVectorType;
ThreadInfoVectorType theThreadInfo;
theThreadInfo.reserve(theThreadCount);
try
{
cout << endl << "Clock before starting threads: " << clock() << endl;
SynchronizedCounter theCounter;
for (long i = 0; i < theThreadCount; i++)
{
theThreadInfo.push_back(ThreadInfoVectorType::value_type(i, &theCounter));
#if defined(WIN32)
const unsigned long theThreadID =
_beginthread(theThreadRoutine, 4096, reinterpret_cast<LPVOID>(&theThreadInfo.back()));
if (theThreadID == unsigned(-1))
{
cerr << endl << "Unable to create thread number " << i + 1 << "." << endl;
}
#elif defined(XALAN_POSIX2_AVAILABLE)
pthread_t theThread;
const int theResult = pthread_create(&theThread, 0, theThreadRoutine, (void*)&theThreadInfo.back());
if (theResult != 0)
{
cerr << endl << "Unable to create thread number " << i + 1 << "." << endl;
}
else
{
#if defined(OS390)
pthread_detach(&theThread);
#else
pthread_detach(theThread);
#endif
}
#else
#error Unsupported platform!
#endif
}
clock_t theClock = 0;
if (theThreadInfo.size() == 0)
{
cerr << endl << "No threads were created!" << endl;
}
else
{
unsigned int theCheckCount = 0;
do
{
doSleep(2000);
// Check a couple of times, just in case, since
// getCounter() is not synchronized...
if (theCounter.getCounter() == 0)
{
if (theCheckCount == 0)
{
theClock = clock();
}
++theCheckCount;
}
}
while(theCheckCount < 2);
}
cout << endl << "Clock after threads: " << theClock << endl;
}
catch(...)
{
cerr << "Exception caught!!!"
<< endl
<< endl;
}
}
int
main(
int argc,
const char* argv[])
{
#if !defined(NDEBUG) && defined(_MSC_VER)
_CrtSetDbgFlag(_CrtSetDbgFlag(_CRTDBG_REPORT_FLAG) | _CRTDBG_LEAK_CHECK_DF);
_CrtSetReportMode(_CRT_WARN, _CRTDBG_MODE_FILE);
_CrtSetReportFile(_CRT_WARN, _CRTDBG_FILE_STDERR);
#endif
if (argc > 2)
{
cerr << "Usage: ThreadTest"
<< endl
<< endl;
}
else
{
int threadCount = 60;
if (argc == 2)
{
threadCount = atoi(argv[1]);
}
try
{
// Initialize Xerces...
XMLPlatformUtils::Initialize();
// Initialize Xalan...
XalanTransformer::initialize();
{
// Create a XalanTransformer. We won't actually use this to transform --
// it's just acting likely a factory for the compiled stylesheet and
// pre-parsed source.
XalanTransformer theXalanTransformer;
const char* const theXSLFileName = "birds.xsl";
glbCompiledStylesheet = theXalanTransformer.compileStylesheet(theXSLFileName);
assert(glbCompiledStylesheet != 0);
// Compile the XML source document as well. All threads will use
// this binary representation of the source tree.
const char* const theXMLFileName = "birds.xml";
glbParsedSource = theXalanTransformer.parseSource(theXMLFileName);
assert(glbParsedSource != 0);
doThreads(threadCount);
}
// Terminate Xalan...
XalanTransformer::terminate();
// Terminate Xerces...
XMLPlatformUtils::Terminate();
}
catch(...)
{
cerr << "Exception caught!!!"
<< endl
<< endl;
}
}
return 0;
}
<|endoftext|> |
<commit_before>#include <boost_common.h>
#include <boilerplate.cpp>
#include <autogen_converters.cpp>
#include <to_python_converters.cc>
using std::string;
using std::vector;
bool VBoostedMaxEnt__wrap_train(VBoostedMaxEnt* inst,
pyarr<double> X_train,
pyarr<double> Y_train)
{
if (X_train.dims[0] != Y_train.dims[0]) {
printf("oh no, X train has %zu entries but Y train has %zu\n",
X_train.dims[0],
Y_train.dims[0]);
}
vector<const vector<double>*> Xvec;
vector<const vector<double>*> Yvec;
for (int i=0; i<X_train.dims[0]; i++) {
vector<double> *tmp = new vector<double>(X_train.data + i*X_train.dims[1],
X_train.data + (i+1)*X_train.dims[1]);
Xvec.push_back(const_cast<const vector<double>*>(tmp));
tmp = new vector<double>(Y_train.data + i*Y_train.dims[1],
Y_train.data + (i+1)*Y_train.dims[1]);
Yvec.push_back(const_cast<const vector<double>*>(tmp));
}
vector<double> w_fold(Xvec.size(), 1.0);
inst->train(Xvec, Yvec, w_fold, NULL, NULL);
for (int i=0; i<X_train.dims[0]; i++) {
delete Xvec[i];
delete Yvec[i];
}
return false;
}
PyObject* VBoostedMaxEnt__wrap_predict(VBoostedMaxEnt* inst,
vector<double> query)
{
vector<double> ret(inst->m_nbr_labels);
inst->predict(query, ret);
return vec_to_numpy(ret);
}
vector<VRandomForest*> VBoostedMaxEnt__get_vec_vrandomforest(VBoostedMaxEnt* inst)
{
vector<VRandomForest*> ret;
foreach (it, inst->m_vregressors) {
/* C++ is beautiful:
* - the innermost * dereferences the iterator;
* - the next * dereferences the shared ptr;
* - the & gets the address of the actual object, because boost can't deal with std
* tr1 shared ptrs
* - it's officially a vector of VRegressors, but we happen to know they're really
* VRandomForests, so cast.
*/
ret.push_back((VRandomForest*)&(*(*it)));
}
return ret;
}
/* at some point I gotta figure out how to make readonly properties of pointer
* fields without this crap
*/
VRandomForest::VTreeNode* VTreeNode__get_left(VRandomForest::VTreeNode* inst)
{
return inst->left;
}
VRandomForest::VTreeNode* VTreeNode__get_right(VRandomForest::VTreeNode* inst)
{
return inst->right;
}
void VTreeNode__refill_avg_outputs(VRandomForest::VTreeNode *inst)
{
if (inst->avg_output.size() > 0)
return;
if (inst->left->avg_output.size() == 0)
VTreeNode__refill_avg_outputs(inst->left);
if (inst->right->avg_output.size() == 0)
VTreeNode__refill_avg_outputs(inst->right);
for (int i=0; i<inst->left->avg_output.size(); i++) {
inst->avg_output.push_back((inst->left->avg_output[i] +
inst->right->avg_output[i]) / 2.0);
}
}
void VRandomForest__wrap_train(VRandomForest *inst,
pyarr<double> X,
pyarr<double> Y)
{
if (X.dims[0] != Y.dims[0]) {
printf("OH NO! X.dims[0] = %ld, Y.dims[0] = %ld\n",
X.dims[0], Y.dims[0]);
return;
}
vector<const vector<double>*> Xv, Yv;
for (int i=0; i<X.dims[0]; i++) {
vector<double>* Xtmp = new vector<double>(X.dims[1]);
vector<double>* Ytmp = new vector<double>(Y.dims[1]);
for (int j=0; j<X.dims[1]; j++) {
(*Xtmp)[j] = X[ind(i,j)];
}
for (int j=0; j<Y.dims[1]; j++) {
(*Ytmp)[j] = Y[ind(i,j)];
}
Xv.push_back(const_cast<const vector<double>*>(Xtmp));
Yv.push_back(const_cast<const vector<double>*>(Ytmp));
}
vector<double> weights(X.dims[0], 1.0), feature_costs;
vector<size_t> usable_features, required_features;
inst->train(X.dims[1], Y.dims[1],
Xv, Yv, weights, usable_features, feature_costs, required_features);
for (int i=0; i<X.dims[0]; i++) {
delete Xv[i];
delete Yv[i];
}
}
pyarr<double> VRandomForest__wrap_predict(VRandomForest *inst,
pyarr<double> X)
{
long int argh[] = {inst->getDimTarget()};
pyarr<double> ret(1, argh);
vector<double> xv(X.dims[0]), yv(ret.dims[0]);
for (int i=0; i<X.dims[0]; i++) {
xv[i] = X[ind(i)];
}
inst->predict(xv, yv);
for (int i=0; i<ret.dims[0]; i++){
ret[ind(i)] = yv[i];
}
return ret;
}
void set_logger_verbosity(string verbosity)
{
misc_util::Logger::status_t s;
if (verbosity == "debug") s = misc_util::Logger::DEBUG;
else if (verbosity == "info") s = misc_util::Logger::INFO;
else if (verbosity == "warning") s = misc_util::Logger::WARNING;
else if (verbosity == "error") s = misc_util::Logger::ERROR;
else s = misc_util::Logger::INFO;
misc_util::Logger::setVerbosity(s);
}
static bool boosted_common = false;
void boost_common()
{
import_array();
if (boosted_common) return;
boosted_common = true;
// long int dims[] = {10, 10, 10};
// pyarr<double> d(3, dims);
// pyarr<float> f(3, dims);
// pyarr<int> i(3, dims);
// pyarr<long int> l(3, dims);
// pyarr<unsigned char> uc(3, dims);
// pyarr<unsigned int> ui(3, dims);
// pyarr<char> c(3, dims);
// printf("d %d f %d i %d l %d uc %d ui %d c %d\n",
// d.ao->descr->type_num,
// f.ao->descr->type_num,
// i.ao->descr->type_num,
// l.ao->descr->type_num,
// uc.ao->descr->type_num,
// ui.ao->descr->type_num,
// c.ao->descr->type_num);
to_python_converter<MatrixMap, MatrixMap_to_numpy_str>();
MatrixMap_from_numpy_str();
to_python_converter<d2d::SegmentMap, SegmentMap_to_numpy_str>();
SegmentMap_from_numpy_str();
to_python_converter<f2d::Pixel2DData, Pixel2DData_to_numpy_str>();
Pixel2DData_from_numpy_str();
to_python_converter<LRgbImage, LRgbImage_to_numpy_str>();
LRgbImage_from_numpy_str();
to_python_converter<vector<double>, vec_to_numpy_str>();
vec_from_numpy_str();
register_autogen_converters();
register_common_converters();
class_<std::pair<unsigned int, double> >("uint_double_pair")
.def_readwrite("first", &std::pair<unsigned int, double>::first)
.def_readwrite("second", &std::pair<unsigned int, double>::second)
;
class_<vector<std::pair<unsigned int, double> > >("uint_double_pair_vec")
.def(vector_indexing_suite<vector<std::pair<unsigned int, double> > >())
;
class_<vector<vector<std::pair<unsigned int, double> > > >("uint_double_pair_vec_vec")
.def(vector_indexing_suite<vector<vector<std::pair<unsigned int, double> > > >())
;
def("set_logger_verbosity", set_logger_verbosity);
class_<vector<string> >("string_vector")
.def(vector_indexing_suite<vector<string > >() )
;
}
static bool boosted_ml = false;
void boost_ml()
{
if (0 && boosted_ml) return;
boosted_ml = true;
class_<VRandomForest::VTreeNode>("VTreeNode", init<>())
.def_readwrite("is_leaf", &VRandomForest::VTreeNode::is_leaf)
.def_readwrite("count", &VRandomForest::VTreeNode::count)
.def_readwrite("dim", &VRandomForest::VTreeNode::dim)
.def_readwrite("avg_output", &VRandomForest::VTreeNode::avg_output)
.def("get_left", VTreeNode__get_left, return_value_policy<reference_existing_object>())
.def("get_right", VTreeNode__get_right, return_value_policy<reference_existing_object>())
.def("refill_avg_outputs", VTreeNode__refill_avg_outputs)
.def_readonly("thresh", &VRandomForest::VTreeNode::thresh)
;
class_<vector<VRandomForest::VTreeNode> >("VTreeNode_vec")
.def(vector_indexing_suite<vector<VRandomForest::VTreeNode> >())
;
class_<VRandomForest>("VRandomForest", init<int, int, int, double, double>())
.def_readwrite("m_nbr_trees", &VRandomForest::m_nbr_trees)
.def_readwrite("m_max_depth", &VRandomForest::m_max_depth)
.def_readwrite("m_min_node_size", &VRandomForest::m_min_node_size)
.def_readwrite("m_rdm_dim_percent", &VRandomForest::m_rdm_dim_percent)
.def_readwrite("m_rdm_sample_percent", &VRandomForest::m_rdm_sample_percent)
.def_readwrite("m_seeds", &VRandomForest::m_seeds)
.def_readwrite("m_trees", &VRandomForest::m_trees)
.def("save", &VRandomForest::save)
.def("load", &VRandomForest::load)
.def("train", VRandomForest__wrap_train)
.def("predict", VRandomForest__wrap_predict)
;
class_<vector<VRandomForest*> >("VRandomForest_vec")
.def(vector_indexing_suite<vector<VRandomForest*> >())
;
class_<VBoostedMaxEnt>("VBoostedMaxEnt", init<double, double, double, int, VRandomForest>())
.def_readwrite("m_step_sizes", &VBoostedMaxEnt::m_step_sizes)
.def_readwrite("m_dim", &VBoostedMaxEnt::m_dim)
.def("get_vec_vrandomforest", VBoostedMaxEnt__get_vec_vrandomforest)
.def("train", VBoostedMaxEnt__wrap_train)
.def("predict", VBoostedMaxEnt__wrap_predict)
.def("save", &VBoostedMaxEnt::save)
.def("load", &VBoostedMaxEnt::load)
;
class_<vector<VBoostedMaxEnt*> >("VBoostedMaxEnt_vec")
.def(vector_indexing_suite<vector<VBoostedMaxEnt*> >())
;
}
BOOST_PYTHON_MODULE(libboost_common) {
PyEval_InitThreads();
import_array();
ilInit();
boost_common();
}
<commit_msg>(split) parse_svmlight fixes, plus an r fix<commit_after>#include <boost_common.h>
#include <boilerplate.cpp>
#include <autogen_converters.cpp>
#include <to_python_converters.cc>
using std::string;
using std::vector;
bool VBoostedMaxEnt__wrap_train(VBoostedMaxEnt* inst,
pyarr<double> X_train,
pyarr<double> Y_train)
{
if (X_train.dims[0] != Y_train.dims[0]) {
printf("oh no, X train has %zu entries but Y train has %zu\n",
X_train.dims[0],
Y_train.dims[0]);
}
vector<const vector<double>*> Xvec;
vector<const vector<double>*> Yvec;
for (int i=0; i<X_train.dims[0]; i++) {
vector<double> *tmp = new vector<double>(X_train.data + i*X_train.dims[1],
X_train.data + (i+1)*X_train.dims[1]);
Xvec.push_back(const_cast<const vector<double>*>(tmp));
tmp = new vector<double>(Y_train.data + i*Y_train.dims[1],
Y_train.data + (i+1)*Y_train.dims[1]);
Yvec.push_back(const_cast<const vector<double>*>(tmp));
}
vector<double> w_fold(Xvec.size(), 1.0);
inst->train(Xvec, Yvec, w_fold, NULL, NULL);
for (int i=0; i<X_train.dims[0]; i++) {
delete Xvec[i];
delete Yvec[i];
}
return false;
}
PyObject* VBoostedMaxEnt__wrap_predict(VBoostedMaxEnt* inst,
vector<double> query)
{
vector<double> ret(inst->m_nbr_labels);
inst->predict(query, ret);
return vec_to_numpy(ret);
}
pyarr<double> VBoostedMaxEnt__batch_predict(VBoostedMaxEnt* inst,
pyarr<double> queries)
{
long int argh[] = {queries.dims[0], inst->m_nbr_labels};
pyarr<double> ret(2, argh);
vector<double> tmp_ret(inst->m_nbr_labels);
vector<double> query(queries.dims[1]);
for (int i=0; i<queries.dims[0]; i++) {
for (int j=0; j<queries.dims[1]; j++) {
query[j] = queries[ind(i, j)];
}
inst->predict(query, tmp_ret);
for (int j=0; j<inst->m_nbr_labels; j++) {
ret[ind(i, j)] = tmp_ret[j];
}
}
return ret;
}
vector<VRandomForest*> VBoostedMaxEnt__get_vec_vrandomforest(VBoostedMaxEnt* inst)
{
vector<VRandomForest*> ret;
foreach (it, inst->m_vregressors) {
/* C++ is beautiful:
* - the innermost * dereferences the iterator;
* - the next * dereferences the shared ptr;
* - the & gets the address of the actual object, because boost can't deal with std
* tr1 shared ptrs
* - it's officially a vector of VRegressors, but we happen to know they're really
* VRandomForests, so cast.
*/
ret.push_back((VRandomForest*)&(*(*it)));
}
return ret;
}
/* at some point I gotta figure out how to make readonly properties of pointer
* fields without this crap
*/
VRandomForest::VTreeNode* VTreeNode__get_left(VRandomForest::VTreeNode* inst)
{
return inst->left;
}
VRandomForest::VTreeNode* VTreeNode__get_right(VRandomForest::VTreeNode* inst)
{
return inst->right;
}
void VTreeNode__refill_avg_outputs(VRandomForest::VTreeNode *inst)
{
if (inst->avg_output.size() > 0)
return;
if (inst->left->avg_output.size() == 0)
VTreeNode__refill_avg_outputs(inst->left);
if (inst->right->avg_output.size() == 0)
VTreeNode__refill_avg_outputs(inst->right);
for (int i=0; i<inst->left->avg_output.size(); i++) {
inst->avg_output.push_back((inst->left->avg_output[i] +
inst->right->avg_output[i]) / 2.0);
}
}
void VRandomForest__wrap_train(VRandomForest *inst,
pyarr<double> X,
pyarr<double> Y)
{
if (X.dims[0] != Y.dims[0]) {
printf("OH NO! X.dims[0] = %ld, Y.dims[0] = %ld\n",
X.dims[0], Y.dims[0]);
return;
}
vector<const vector<double>*> Xv, Yv;
for (int i=0; i<X.dims[0]; i++) {
vector<double>* Xtmp = new vector<double>(X.dims[1]);
vector<double>* Ytmp = new vector<double>(Y.dims[1]);
for (int j=0; j<X.dims[1]; j++) {
(*Xtmp)[j] = X[ind(i,j)];
}
for (int j=0; j<Y.dims[1]; j++) {
(*Ytmp)[j] = Y[ind(i,j)];
}
Xv.push_back(const_cast<const vector<double>*>(Xtmp));
Yv.push_back(const_cast<const vector<double>*>(Ytmp));
}
vector<double> weights(X.dims[0], 1.0), feature_costs;
vector<size_t> usable_features, required_features;
inst->train(X.dims[1], Y.dims[1],
Xv, Yv, weights, usable_features, feature_costs, required_features);
for (int i=0; i<X.dims[0]; i++) {
delete Xv[i];
delete Yv[i];
}
}
pyarr<double> VRandomForest__wrap_predict(VRandomForest *inst,
pyarr<double> X)
{
long int argh[] = {inst->getDimTarget()};
pyarr<double> ret(1, argh);
vector<double> xv(X.dims[0]), yv(ret.dims[0]);
for (int i=0; i<X.dims[0]; i++) {
xv[i] = X[ind(i)];
}
inst->predict(xv, yv);
for (int i=0; i<ret.dims[0]; i++){
ret[ind(i)] = yv[i];
}
return ret;
}
void set_logger_verbosity(string verbosity)
{
misc_util::Logger::status_t s;
if (verbosity == "debug") s = misc_util::Logger::DEBUG;
else if (verbosity == "info") s = misc_util::Logger::INFO;
else if (verbosity == "warning") s = misc_util::Logger::WARNING;
else if (verbosity == "error") s = misc_util::Logger::ERROR;
else s = misc_util::Logger::INFO;
misc_util::Logger::setVerbosity(s);
}
static bool boosted_common = false;
void boost_common()
{
import_array();
if (boosted_common) return;
boosted_common = true;
// long int dims[] = {10, 10, 10};
// pyarr<double> d(3, dims);
// pyarr<float> f(3, dims);
// pyarr<int> i(3, dims);
// pyarr<long int> l(3, dims);
// pyarr<unsigned char> uc(3, dims);
// pyarr<unsigned int> ui(3, dims);
// pyarr<char> c(3, dims);
// printf("d %d f %d i %d l %d uc %d ui %d c %d\n",
// d.ao->descr->type_num,
// f.ao->descr->type_num,
// i.ao->descr->type_num,
// l.ao->descr->type_num,
// uc.ao->descr->type_num,
// ui.ao->descr->type_num,
// c.ao->descr->type_num);
to_python_converter<MatrixMap, MatrixMap_to_numpy_str>();
MatrixMap_from_numpy_str();
to_python_converter<d2d::SegmentMap, SegmentMap_to_numpy_str>();
SegmentMap_from_numpy_str();
to_python_converter<f2d::Pixel2DData, Pixel2DData_to_numpy_str>();
Pixel2DData_from_numpy_str();
to_python_converter<LRgbImage, LRgbImage_to_numpy_str>();
LRgbImage_from_numpy_str();
to_python_converter<vector<double>, vec_to_numpy_str>();
vec_from_numpy_str();
register_autogen_converters();
register_common_converters();
class_<std::pair<unsigned int, double> >("uint_double_pair")
.def_readwrite("first", &std::pair<unsigned int, double>::first)
.def_readwrite("second", &std::pair<unsigned int, double>::second)
;
class_<vector<std::pair<unsigned int, double> > >("uint_double_pair_vec")
.def(vector_indexing_suite<vector<std::pair<unsigned int, double> > >())
;
class_<vector<vector<std::pair<unsigned int, double> > > >("uint_double_pair_vec_vec")
.def(vector_indexing_suite<vector<vector<std::pair<unsigned int, double> > > >())
;
def("set_logger_verbosity", set_logger_verbosity);
class_<vector<string> >("string_vector")
.def(vector_indexing_suite<vector<string > >() )
;
}
static bool boosted_ml = false;
void boost_ml()
{
if (0 && boosted_ml) return;
boosted_ml = true;
class_<VRandomForest::VTreeNode>("VTreeNode", init<>())
.def_readwrite("is_leaf", &VRandomForest::VTreeNode::is_leaf)
.def_readwrite("count", &VRandomForest::VTreeNode::count)
.def_readwrite("dim", &VRandomForest::VTreeNode::dim)
.def_readwrite("avg_output", &VRandomForest::VTreeNode::avg_output)
.def("get_left", VTreeNode__get_left, return_value_policy<reference_existing_object>())
.def("get_right", VTreeNode__get_right, return_value_policy<reference_existing_object>())
.def("refill_avg_outputs", VTreeNode__refill_avg_outputs)
.def_readonly("thresh", &VRandomForest::VTreeNode::thresh)
;
class_<vector<VRandomForest::VTreeNode> >("VTreeNode_vec")
.def(vector_indexing_suite<vector<VRandomForest::VTreeNode> >())
;
class_<VRandomForest>("VRandomForest", init<int, int, int, double, double>())
.def_readwrite("m_nbr_trees", &VRandomForest::m_nbr_trees)
.def_readwrite("m_max_depth", &VRandomForest::m_max_depth)
.def_readwrite("m_min_node_size", &VRandomForest::m_min_node_size)
.def_readwrite("m_rdm_dim_percent", &VRandomForest::m_rdm_dim_percent)
.def_readwrite("m_rdm_sample_percent", &VRandomForest::m_rdm_sample_percent)
.def_readwrite("m_seeds", &VRandomForest::m_seeds)
.def_readwrite("m_trees", &VRandomForest::m_trees)
.def("save", &VRandomForest::save)
.def("load", &VRandomForest::load)
.def("train", VRandomForest__wrap_train)
.def("predict", VRandomForest__wrap_predict)
;
class_<vector<VRandomForest*> >("VRandomForest_vec")
.def(vector_indexing_suite<vector<VRandomForest*> >())
;
class_<VBoostedMaxEnt>("VBoostedMaxEnt", init<double, double, double, int, VRandomForest>())
.def_readwrite("m_step_sizes", &VBoostedMaxEnt::m_step_sizes)
.def_readwrite("m_dim", &VBoostedMaxEnt::m_dim)
.def("get_vec_vrandomforest", VBoostedMaxEnt__get_vec_vrandomforest)
.def("train", VBoostedMaxEnt__wrap_train)
.def("predict", VBoostedMaxEnt__wrap_predict)
.def("batch_predict", VBoostedMaxEnt__batch_predict)
.def("save", &VBoostedMaxEnt::save)
.def("load", &VBoostedMaxEnt::load)
;
class_<vector<VBoostedMaxEnt*> >("VBoostedMaxEnt_vec")
.def(vector_indexing_suite<vector<VBoostedMaxEnt*> >())
;
}
BOOST_PYTHON_MODULE(libboost_common) {
PyEval_InitThreads();
import_array();
ilInit();
boost_common();
}
<|endoftext|> |
<commit_before>/*=========================================================================
*
* Copyright Insight Software Consortium
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0.txt
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
*=========================================================================*/
#include "itkNormalDistributionImageSource.h"
#include "itkImageFileWriter.h"
#include "itkTestingMacros.h"
int itkNormalDistributionImageSourceTest( int argc, char * argv[] )
{
if( argc < 2 )
{
std::cerr << "Usage: " << argv[0];
std::cerr << " outputImage";
std::cerr << std::endl;
return EXIT_FAILURE;
}
const char * outputImageFileName = argv[1];
const unsigned int Dimension = 2;
typedef float PixelType;
typedef itk::Image< PixelType, Dimension > ImageType;
typedef itk::NormalDistributionImageSource< ImageType > DistributionSourceType;
DistributionSourceType::Pointer distributionSource = DistributionSourceType::New();
EXERCISE_BASIC_OBJECT_METHODS( distributionSource, NormalDistributionImageSource , GenerateImageSource );
ImageType::SizeType size;
size.Fill( 128 );
distributionSource->SetSize( size );
std::cout << distributionSource << std::endl;
typedef itk::ImageFileWriter< ImageType > WriterType;
WriterType::Pointer writer = WriterType::New();
writer->SetFileName( outputImageFileName );
writer->SetInput( distributionSource->GetOutput() );
try
{
writer->Update();
}
catch( itk::ExceptionObject & error )
{
std::cerr << "Error: " << error << std::endl;
return EXIT_FAILURE;
}
return EXIT_SUCCESS;
}
<commit_msg>STYLE: Remove unnecessary white space before comma.<commit_after>/*=========================================================================
*
* Copyright Insight Software Consortium
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0.txt
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
*=========================================================================*/
#include "itkNormalDistributionImageSource.h"
#include "itkImageFileWriter.h"
#include "itkTestingMacros.h"
int itkNormalDistributionImageSourceTest( int argc, char * argv[] )
{
if( argc < 2 )
{
std::cerr << "Usage: " << argv[0];
std::cerr << " outputImage";
std::cerr << std::endl;
return EXIT_FAILURE;
}
const char * outputImageFileName = argv[1];
const unsigned int Dimension = 2;
typedef float PixelType;
typedef itk::Image< PixelType, Dimension > ImageType;
typedef itk::NormalDistributionImageSource< ImageType > DistributionSourceType;
DistributionSourceType::Pointer distributionSource = DistributionSourceType::New();
EXERCISE_BASIC_OBJECT_METHODS( distributionSource, NormalDistributionImageSource, GenerateImageSource );
ImageType::SizeType size;
size.Fill( 128 );
distributionSource->SetSize( size );
std::cout << distributionSource << std::endl;
typedef itk::ImageFileWriter< ImageType > WriterType;
WriterType::Pointer writer = WriterType::New();
writer->SetFileName( outputImageFileName );
writer->SetInput( distributionSource->GetOutput() );
try
{
writer->Update();
}
catch( itk::ExceptionObject & error )
{
std::cerr << "Error: " << error << std::endl;
return EXIT_FAILURE;
}
return EXIT_SUCCESS;
}
<|endoftext|> |
<commit_before>#include "Tools/DataStructures/RingBufferWithSum.h"
#include "Tools/Math/Common.h"
#include <vector>
#include <gtest/gtest.h>
using namespace std;
class RingBufferWithSumTest : public testing::Test
{
public:
RingBufferWithSum<double, 29> buffer;
float tolerance;
std::vector<double> test_vector;
virtual void SetUp() {
tolerance = 0.0001f;
for(size_t i = 0; i < 17; i++) {
double x = Math::random();
buffer.add(x);
}
for(size_t i = 0; i < 29; i++) {
double x = Math::random();
test_vector.push_back(x);
buffer.add(x);
}
}
virtual void TearDown() {
}
};
TEST_F(RingBufferWithSumTest,Size) {
ASSERT_EQ(buffer.size(),(int)test_vector.size());
ASSERT_EQ(buffer.size(),buffer.getMaxEntries());
}
TEST_F(RingBufferWithSumTest,ArrayAccess) {
ASSERT_EQ(buffer.size(),(int)test_vector.size());
for(size_t i = 0; i < test_vector.size(); i++) {
ASSERT_DOUBLE_EQ(test_vector[test_vector.size()-i-1],buffer[i]);
ASSERT_DOUBLE_EQ(buffer.getEntry(i),buffer[i]);
}
EXPECT_DEATH(buffer.getEntry(buffer.size()), "");
EXPECT_DEATH(buffer.getEntry(-1), "");
}
TEST_F(RingBufferWithSumTest,Average) {
double sum = 0.0;
for(int i = 0; i < buffer.size(); i++) {
sum += buffer[i];
}
ASSERT_DOUBLE_EQ(sum/buffer.size(), buffer.getAverage());
}
<commit_msg>fixed warning in gcc<commit_after>#include "Tools/DataStructures/RingBufferWithSum.h"
#include "Tools/Math/Common.h"
#include <vector>
#include <gtest/gtest.h>
using namespace std;
class RingBufferWithSumTest : public testing::Test
{
public:
RingBufferWithSum<double, 29> buffer;
float tolerance;
std::vector<double> test_vector;
virtual void SetUp() {
tolerance = 0.0001f;
for(size_t i = 0; i < 17; i++) {
double x = Math::random();
buffer.add(x);
}
for(size_t i = 0; i < 29; i++) {
double x = Math::random();
test_vector.push_back(x);
buffer.add(x);
}
}
virtual void TearDown() {
}
};
TEST_F(RingBufferWithSumTest,Size) {
ASSERT_EQ(buffer.size(),(int)test_vector.size());
ASSERT_EQ(buffer.size(),buffer.getMaxEntries());
}
TEST_F(RingBufferWithSumTest,ArrayAccess) {
ASSERT_EQ(buffer.size(),(int)test_vector.size());
for(size_t i = 0; i < test_vector.size(); i++) {
ASSERT_DOUBLE_EQ(test_vector[test_vector.size()-i-1],buffer[(int)i]);
ASSERT_DOUBLE_EQ(buffer.getEntry((int)i),buffer[(int)i]);
}
EXPECT_DEATH(buffer.getEntry(buffer.size()), "");
EXPECT_DEATH(buffer.getEntry(-1), "");
}
TEST_F(RingBufferWithSumTest,Average) {
double sum = 0.0;
for(int i = 0; i < buffer.size(); i++) {
sum += buffer[i];
}
ASSERT_DOUBLE_EQ(sum/buffer.size(), buffer.getAverage());
}
<|endoftext|> |
<commit_before>// Copyright (C) 2010 and 2011 Marcin Arkadiusz Skrobiranda.
// All rights reserved.
//
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions
// are met:
// 1. Redistributions of source code must retain the above copyright
// notice, this list of conditions and the following disclaimer.
// 2. Redistributions in binary form must reproduce the above copyright
// notice, this list of conditions and the following disclaimer in the
// documentation and/or other materials provided with the distribution.
// 3. Neither the name of the project 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 PROJECT 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 PROJECT OR CONTRIBUTORS BE LIABLE
// FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
// DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
// OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
// HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
// LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
// OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
// SUCH DAMAGE.
#ifndef ICONFIGURATORBUILDING_HPP
#define ICONFIGURATORBUILDING_HPP
#include <GameServer/Configuration/Configurator/Building/IBuilding.hpp>
#include <boost/noncopyable.hpp>
#include <boost/shared_ptr.hpp>
/**
* @brief The interface of ConfiguratorBuilding.
*/
class IConfiguratorBuilding
: private boost::noncopyable
{
public:
virtual ~IConfiguratorBuilding(){};
/**
* @brief Gets the configuration.
*
* @return True on success, false otherwise.
*/
virtual bool configure() = 0;
/**
* @brief Gets the building.
*
* @param a_key The key of the building.
*
* @return The building, null if not found.
*/
virtual GameServer::Configuration::IBuildingShrPtr getBuilding(
GameServer::Configuration::IKey const a_key
) const = 0;
/**
* @brief Gets the map of buildings.
*
* @return The map of buildings.
*/
virtual GameServer::Configuration::IBuildingMap const & getBuildings() const = 0;
};
/**
* @brief A useful typedef.
*/
typedef boost::shared_ptr<IConfiguratorBuilding> IConfiguratorBuildingShrPtr;
#endif // CONFIGURATORBUILDING_HPP
<commit_msg>A typo fixed.<commit_after>// Copyright (C) 2010 and 2011 Marcin Arkadiusz Skrobiranda.
// All rights reserved.
//
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions
// are met:
// 1. Redistributions of source code must retain the above copyright
// notice, this list of conditions and the following disclaimer.
// 2. Redistributions in binary form must reproduce the above copyright
// notice, this list of conditions and the following disclaimer in the
// documentation and/or other materials provided with the distribution.
// 3. Neither the name of the project 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 PROJECT 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 PROJECT OR CONTRIBUTORS BE LIABLE
// FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
// DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
// OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
// HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
// LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
// OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
// SUCH DAMAGE.
#ifndef ICONFIGURATORBUILDING_HPP
#define ICONFIGURATORBUILDING_HPP
#include <GameServer/Configuration/Configurator/Building/IBuilding.hpp>
#include <boost/noncopyable.hpp>
#include <boost/shared_ptr.hpp>
/**
* @brief The interface of ConfiguratorBuilding.
*/
class IConfiguratorBuilding
: private boost::noncopyable
{
public:
virtual ~IConfiguratorBuilding(){};
/**
* @brief Gets the configuration.
*
* @return True on success, false otherwise.
*/
virtual bool configure() = 0;
/**
* @brief Gets the building.
*
* @param a_key The key of the building.
*
* @return The building, null if not found.
*/
virtual GameServer::Configuration::IBuildingShrPtr getBuilding(
GameServer::Configuration::IKey const a_key
) const = 0;
/**
* @brief Gets the map of buildings.
*
* @return The map of buildings.
*/
virtual GameServer::Configuration::IBuildingMap const & getBuildings() const = 0;
};
/**
* @brief A useful typedef.
*/
typedef boost::shared_ptr<IConfiguratorBuilding> IConfiguratorBuildingShrPtr;
#endif // ICONFIGURATORBUILDING_HPP
<|endoftext|> |
<commit_before>/* Copyright (c) 2016 PaddlePaddle Authors. All Rights Reserve.
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 "paddle/operators/bilinear_tensor_product_op.h"
namespace paddle {
namespace operators {
using framework::Tensor;
class BilinearTensorProductOp : public framework::OperatorWithKernel {
public:
using framework::OperatorWithKernel::OperatorWithKernel;
protected:
void InferShape(framework::InferShapeContext* ctx) const override {
PADDLE_ENFORCE(ctx->HasInput("X"), "Input(X) should not be null.");
PADDLE_ENFORCE(ctx->HasInput("Y"), "Input(Y) should not be null.");
PADDLE_ENFORCE(ctx->HasInput("Weight"),
"Input(Weight) should not be null.");
PADDLE_ENFORCE(ctx->HasOutput("Out"), "Output(Out) should not be null.");
auto x_dims = ctx->GetInputDim("X");
auto y_dims = ctx->GetInputDim("Y");
auto weight_dims = ctx->GetInputDim("Weight");
PADDLE_ENFORCE_EQ(x_dims.size(), 2UL, "The input(X) must be a 2D Tensor.");
PADDLE_ENFORCE_EQ(y_dims.size(), 2UL, "The input(Y) must be a 2D Tensor.");
PADDLE_ENFORCE_EQ(weight_dims.size(), 3UL,
"The input(Weight) must be a 3D tensor.");
PADDLE_ENFORCE_EQ(x_dims[0], y_dims[0],
"The first dimension(batch_size) of input(X) must be "
"equal to the first dimension of the input(Y).");
PADDLE_ENFORCE_EQ(x_dims[1], weight_dims[1],
"The second dimension of input(X) must be equal to "
"the second dimension of the input(Weight).");
PADDLE_ENFORCE_EQ(y_dims[1], weight_dims[2],
"The second dimension of input(Y) must be equal to "
"the third dimension of the input(Weight).");
if (ctx->HasInput("Bias")) {
auto bias_dims = ctx->GetInputDim("Bias");
PADDLE_ENFORCE(bias_dims.size() == 2UL && bias_dims[0] == 1UL,
"The Input(Bias) must be a 2-D tensor with "
"the 2nd dimension fixed to 1 (a row vector).");
PADDLE_ENFORCE_EQ(bias_dims[1], weight_dims[0],
"The second dimension of input(Bias) must be equal "
"to the first dimension of the input(Weight).");
}
ctx->SetOutputDim("Out", {x_dims[0], weight_dims[0]});
ctx->ShareLoD("X", /*->*/ "Out");
}
};
class BilinearTensorProductOpMaker : public framework::OpProtoAndCheckerMaker {
public:
BilinearTensorProductOpMaker(framework::OpProto* proto,
framework::OpAttrChecker* op_checker)
: OpProtoAndCheckerMaker(proto, op_checker) {
AddInput("X", "The first input of bilinear_tensor_product operator.");
AddInput("Y", "The second input of bilinear_tensor_product operator.");
AddInput("Weight",
"The learnable parameters of bilinear_tensor_product operator.");
AddInput("Bias", "The learnable bias of bilinear_tensor_product operator.")
.AsDispensable();
AddOutput("Out", "The output of bilinear_tensor_product operator.");
AddComment(R"DOC(
Bilinear Tensor Product operator.
Given input X and Y, a 3D tensor weight, and bias. Each column of the
output is computed by one slice i = 1, . . . , k of the tensor:
M = (X W_i) \cdot Y
Out_i = \sum_i {M_i} + Bias_i
)DOC");
}
};
class BilinearTensorProductOpGrad : public framework::OperatorWithKernel {
public:
using framework::OperatorWithKernel::OperatorWithKernel;
protected:
void InferShape(framework::InferShapeContext* ctx) const override {
PADDLE_ENFORCE(ctx->HasInput("X"), "Input(X) should not be null.");
PADDLE_ENFORCE(ctx->HasInput("Y"), "Input(Y) should not be null.");
PADDLE_ENFORCE(ctx->HasInput("Weight"),
"Input(Weight) should not be null.");
PADDLE_ENFORCE(ctx->HasInput(framework::GradVarName("Out")),
"Input(Out@GRAD) should not be null.");
auto x_dims = ctx->GetInputDim("X");
auto y_dims = ctx->GetInputDim("Y");
auto weight_dims = ctx->GetInputDim("Weight");
auto out_dims = ctx->GetInputDim(framework::GradVarName("Out"));
PADDLE_ENFORCE_EQ(out_dims.size(), 2UL,
"The input(Out@GRAD) must be a 2D Tensor.");
PADDLE_ENFORCE_EQ(
x_dims[0], out_dims[0],
"The first dimension(batch_size) of input(Out@GRAD) must be "
"equal to the first dimension of the Input(X).");
PADDLE_ENFORCE_EQ(
weight_dims[0], out_dims[1],
"The second dimension of input(Out@GRAD) must be equal to "
"the third dimension of the Input(Weight).");
if (ctx->HasInput("Bias")) {
auto bias_dims = ctx->GetInputDim("Bias");
PADDLE_ENFORCE_EQ(
bias_dims[1], out_dims[1],
"The second dimension of input(Out@GRAD) must be equal to "
"the second dimension of the Input(Bias).");
auto bias_grad_name = framework::GradVarName("Bias");
if (ctx->HasOutput(bias_grad_name))
ctx->SetOutputDim(bias_grad_name, bias_dims);
}
auto x_grad_name = framework::GradVarName("X");
auto y_grad_name = framework::GradVarName("Y");
auto weight_grad_name = framework::GradVarName("Weight");
if (ctx->HasOutput(x_grad_name)) {
ctx->SetOutputDim(x_grad_name, x_dims);
}
if (ctx->HasOutput(y_grad_name)) {
ctx->SetOutputDim(y_grad_name, y_dims);
}
if (ctx->HasOutput(weight_grad_name)) {
ctx->SetOutputDim(weight_grad_name, weight_dims);
}
}
};
} // namespace operators
} // namespace paddle
namespace ops = paddle::operators;
REGISTER_OP(bilinear_tensor_product, ops::BilinearTensorProductOp,
ops::BilinearTensorProductOpMaker, bilinear_tensor_product_grad,
ops::BilinearTensorProductOpGrad);
REGISTER_OP_CPU_KERNEL(
bilinear_tensor_product,
ops::BilinearTensorProductKernel<paddle::platform::CPUPlace, float>,
ops::BilinearTensorProductKernel<paddle::platform::CPUPlace, double>);
REGISTER_OP_CPU_KERNEL(
bilinear_tensor_product_grad,
ops::BilinearTensorProductGradKernel<paddle::platform::CPUPlace, float>,
ops::BilinearTensorProductGradKernel<paddle::platform::CPUPlace, double>);
<commit_msg>refine bilinear tensor product doc<commit_after>/* Copyright (c) 2016 PaddlePaddle Authors. All Rights Reserve.
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 "paddle/operators/bilinear_tensor_product_op.h"
namespace paddle {
namespace operators {
using framework::Tensor;
class BilinearTensorProductOp : public framework::OperatorWithKernel {
public:
using framework::OperatorWithKernel::OperatorWithKernel;
protected:
void InferShape(framework::InferShapeContext* ctx) const override {
PADDLE_ENFORCE(ctx->HasInput("X"), "Input(X) should not be null.");
PADDLE_ENFORCE(ctx->HasInput("Y"), "Input(Y) should not be null.");
PADDLE_ENFORCE(ctx->HasInput("Weight"),
"Input(Weight) should not be null.");
PADDLE_ENFORCE(ctx->HasOutput("Out"), "Output(Out) should not be null.");
auto x_dims = ctx->GetInputDim("X");
auto y_dims = ctx->GetInputDim("Y");
auto weight_dims = ctx->GetInputDim("Weight");
PADDLE_ENFORCE_EQ(x_dims.size(), 2UL, "The input(X) must be a 2D Tensor.");
PADDLE_ENFORCE_EQ(y_dims.size(), 2UL, "The input(Y) must be a 2D Tensor.");
PADDLE_ENFORCE_EQ(weight_dims.size(), 3UL,
"The input(Weight) must be a 3D tensor.");
PADDLE_ENFORCE_EQ(x_dims[0], y_dims[0],
"The first dimension(batch_size) of input(X) must be "
"equal to the first dimension of the input(Y).");
PADDLE_ENFORCE_EQ(x_dims[1], weight_dims[1],
"The second dimension of input(X) must be equal to "
"the second dimension of the input(Weight).");
PADDLE_ENFORCE_EQ(y_dims[1], weight_dims[2],
"The second dimension of input(Y) must be equal to "
"the third dimension of the input(Weight).");
if (ctx->HasInput("Bias")) {
auto bias_dims = ctx->GetInputDim("Bias");
PADDLE_ENFORCE(bias_dims.size() == 2UL && bias_dims[0] == 1UL,
"The Input(Bias) must be a 2-D tensor with "
"the 2nd dimension fixed to 1 (a row vector).");
PADDLE_ENFORCE_EQ(bias_dims[1], weight_dims[0],
"The second dimension of input(Bias) must be equal "
"to the first dimension of the input(Weight).");
}
ctx->SetOutputDim("Out", {x_dims[0], weight_dims[0]});
ctx->ShareLoD("X", /*->*/ "Out");
}
};
class BilinearTensorProductOpMaker : public framework::OpProtoAndCheckerMaker {
public:
BilinearTensorProductOpMaker(framework::OpProto* proto,
framework::OpAttrChecker* op_checker)
: OpProtoAndCheckerMaker(proto, op_checker) {
AddInput("X", "The first input of bilinear_tensor_product operator.");
AddInput("Y", "The second input of bilinear_tensor_product operator.");
AddInput("Weight",
"The learnable parameters of bilinear_tensor_product operator.");
AddInput("Bias", "The learnable bias of bilinear_tensor_product operator.")
.AsDispensable();
AddOutput("Out", "The output of bilinear_tensor_product operator.");
AddComment(R"DOC(
Bilinear Tensor Product operator.
Given input X and Y, a 3D tensor Weight and a Bias. Each column of the
Output is computed by one slice i = 1, . . . , k of the tensor:
$$
M = (X W_i) * Y \\
Out_i = \sum_j {M_j} + Bias_i
$$
Where $$W_i$$ is the i-th slice of Input(Weight);
$$M_j$$ is the j-th column of $$M$$;
$$Out_i$$ is the i-th column of Output(Out);
$$Bias_i$$ is a column vector, each element of it is equal to
the i-th element of $$Bias$$;
)DOC");
}
};
class BilinearTensorProductOpGrad : public framework::OperatorWithKernel {
public:
using framework::OperatorWithKernel::OperatorWithKernel;
protected:
void InferShape(framework::InferShapeContext* ctx) const override {
PADDLE_ENFORCE(ctx->HasInput("X"), "Input(X) should not be null.");
PADDLE_ENFORCE(ctx->HasInput("Y"), "Input(Y) should not be null.");
PADDLE_ENFORCE(ctx->HasInput("Weight"),
"Input(Weight) should not be null.");
PADDLE_ENFORCE(ctx->HasInput(framework::GradVarName("Out")),
"Input(Out@GRAD) should not be null.");
auto x_dims = ctx->GetInputDim("X");
auto y_dims = ctx->GetInputDim("Y");
auto weight_dims = ctx->GetInputDim("Weight");
auto out_dims = ctx->GetInputDim(framework::GradVarName("Out"));
PADDLE_ENFORCE_EQ(out_dims.size(), 2UL,
"The input(Out@GRAD) must be a 2D Tensor.");
PADDLE_ENFORCE_EQ(
x_dims[0], out_dims[0],
"The first dimension(batch_size) of input(Out@GRAD) must be "
"equal to the first dimension of the Input(X).");
PADDLE_ENFORCE_EQ(
weight_dims[0], out_dims[1],
"The second dimension of input(Out@GRAD) must be equal to "
"the third dimension of the Input(Weight).");
if (ctx->HasInput("Bias")) {
auto bias_dims = ctx->GetInputDim("Bias");
PADDLE_ENFORCE_EQ(
bias_dims[1], out_dims[1],
"The second dimension of input(Out@GRAD) must be equal to "
"the second dimension of the Input(Bias).");
auto bias_grad_name = framework::GradVarName("Bias");
if (ctx->HasOutput(bias_grad_name))
ctx->SetOutputDim(bias_grad_name, bias_dims);
}
auto x_grad_name = framework::GradVarName("X");
auto y_grad_name = framework::GradVarName("Y");
auto weight_grad_name = framework::GradVarName("Weight");
if (ctx->HasOutput(x_grad_name)) {
ctx->SetOutputDim(x_grad_name, x_dims);
}
if (ctx->HasOutput(y_grad_name)) {
ctx->SetOutputDim(y_grad_name, y_dims);
}
if (ctx->HasOutput(weight_grad_name)) {
ctx->SetOutputDim(weight_grad_name, weight_dims);
}
}
};
} // namespace operators
} // namespace paddle
namespace ops = paddle::operators;
REGISTER_OP(bilinear_tensor_product, ops::BilinearTensorProductOp,
ops::BilinearTensorProductOpMaker, bilinear_tensor_product_grad,
ops::BilinearTensorProductOpGrad);
REGISTER_OP_CPU_KERNEL(
bilinear_tensor_product,
ops::BilinearTensorProductKernel<paddle::platform::CPUPlace, float>,
ops::BilinearTensorProductKernel<paddle::platform::CPUPlace, double>);
REGISTER_OP_CPU_KERNEL(
bilinear_tensor_product_grad,
ops::BilinearTensorProductGradKernel<paddle::platform::CPUPlace, float>,
ops::BilinearTensorProductGradKernel<paddle::platform::CPUPlace, double>);
<|endoftext|> |
<commit_before>/////////////////////////////////////////////////////////////////////////////
// Name: dialog_general_options.cpp
// Author: jean-pierre Charras
/////////////////////////////////////////////////////////////////////////////
/* functions relatives to the dialogs opened from the main menu :
* Preferences/general
* Preferences/display
*/
#include "fctsys.h"
#include "common.h"
#include "class_drawpanel.h"
#include "confirm.h"
#include "pcbnew.h"
#include "wxPcbStruct.h"
#include "class_board_design_settings.h"
#include "dialog_general_options.h"
#include "pcbnew_id.h"
Dialog_GeneralOptions::Dialog_GeneralOptions( WinEDA_PcbFrame* parent ) :
DialogGeneralOptionsBoardEditor_base( parent )
{
m_Parent = parent;
init();
GetSizer()->SetSizeHints( this );
Center();
}
void Dialog_GeneralOptions::init()
{
SetFocus();
m_Board = m_Parent->GetBoard();
/* Set display options */
m_PolarDisplay->SetSelection( DisplayOpt.DisplayPolarCood ? 1 : 0 );
m_UnitsSelection->SetSelection( g_UnitMetric ? 1 : 0 );
m_CursorShape->SetSelection( m_Parent->m_CursorShape ? 1 : 0 );
wxString timevalue;
timevalue << g_TimeOut / 60;
m_SaveTime->SetValue( timevalue );
m_MaxShowLinks->SetValue( g_MaxLinksShowed );
m_DrcOn->SetValue( Drc_On );
m_ShowModuleRatsnest->SetValue( g_Show_Module_Ratsnest );
m_ShowGlobalRatsnest->SetValue( m_Board->IsElementVisible(RATSNEST_VISIBLE) );
m_TrackAutodel->SetValue( g_AutoDeleteOldTrack );
m_Track_45_Only_Ctrl->SetValue( Track_45_Only );
m_Segments_45_Only_Ctrl->SetValue( Segments_45_Only );
m_AutoPANOpt->SetValue( m_Parent->DrawPanel->m_AutoPAN_Enable );
m_Segments_45_Only_Ctrl->SetValue( Segments_45_Only );
m_Track_DoubleSegm_Ctrl->SetValue( g_TwoSegmentTrackBuild );
m_MagneticPadOptCtrl->SetSelection( g_MagneticPadOption );
m_MagneticTrackOptCtrl->SetSelection( g_MagneticTrackOption );
}
void Dialog_GeneralOptions::OnCancelClick( wxCommandEvent& event )
{
event.Skip();
}
void Dialog_GeneralOptions::OnOkClick( wxCommandEvent& event )
{
int ii;
DisplayOpt.DisplayPolarCood =
( m_PolarDisplay->GetSelection() == 0 ) ? FALSE : true;
ii = g_UnitMetric;
g_UnitMetric = ( m_UnitsSelection->GetSelection() == 0 ) ? 0 : 1;
if( ii != g_UnitMetric )
m_Parent->ReCreateAuxiliaryToolbar();
m_Parent->m_CursorShape = m_CursorShape->GetSelection();
g_TimeOut = 60 * m_SaveTime->GetValue();
/* Updating the combobox to display the active layer. */
g_MaxLinksShowed = m_MaxShowLinks->GetValue();
Drc_On = m_DrcOn->GetValue();
if( m_Board->IsElementVisible(RATSNEST_VISIBLE) != m_ShowGlobalRatsnest->GetValue() )
{
m_Parent->SetElementVisibility(RATSNEST_VISIBLE, m_ShowGlobalRatsnest->GetValue() );
m_Parent->DrawPanel->Refresh( );
}
g_Show_Module_Ratsnest = m_ShowModuleRatsnest->GetValue();
g_AutoDeleteOldTrack = m_TrackAutodel->GetValue();
Segments_45_Only = m_Segments_45_Only_Ctrl->GetValue();
Track_45_Only = m_Track_45_Only_Ctrl->GetValue();
m_Parent->DrawPanel->m_AutoPAN_Enable = m_AutoPANOpt->GetValue();
g_TwoSegmentTrackBuild = m_Track_DoubleSegm_Ctrl->GetValue();
g_MagneticPadOption = m_MagneticPadOptCtrl->GetSelection();
g_MagneticTrackOption = m_MagneticTrackOptCtrl->GetSelection();
EndModal( 1 );
}
#include "dialog_graphic_items_options.cpp"
void WinEDA_PcbFrame::InstallPcbOptionsFrame( int id )
{
switch( id )
{
case ID_PCB_DRAWINGS_WIDTHS_SETUP:
{
WinEDA_GraphicItemsOptionsDialog dlg( this );
dlg.ShowModal();
}
break;
default:
wxMessageBox( wxT( "InstallPcbOptionsFrame() id error" ) );
break;
}
}
void WinEDA_ModuleEditFrame::InstallOptionsFrame( const wxPoint& pos )
{
WinEDA_GraphicItemsOptionsDialog dlg( this );
dlg.ShowModal();
}
/* Must be called on a click on the left toolbar (options toolbar
* Update variables according to tools states
*/
void WinEDA_PcbFrame::OnSelectOptionToolbar( wxCommandEvent& event )
{
int id = event.GetId();
bool state = m_OptionsToolBar->GetToolState( id );
switch( id )
{
case ID_TB_OPTIONS_DRC_OFF:
Drc_On = state ? FALSE : true;
break;
case ID_TB_OPTIONS_SHOW_GRID:
SetElementVisibility(GRID_VISIBLE, state);
DrawPanel->Refresh();
break;
case ID_TB_OPTIONS_SHOW_RATSNEST:
SetElementVisibility(RATSNEST_VISIBLE, state);
DrawPanel->Refresh( );
break;
case ID_TB_OPTIONS_SHOW_MODULE_RATSNEST:
g_Show_Module_Ratsnest = state; // TODO: use the visibility list
break;
case ID_TB_OPTIONS_SELECT_UNIT_MM:
g_UnitMetric = MILLIMETRE;
case ID_TB_OPTIONS_SELECT_UNIT_INCH:
if( id == ID_TB_OPTIONS_SELECT_UNIT_INCH )
g_UnitMetric = INCHES;
m_TrackAndViasSizesList_Changed = true;
UpdateStatusBar();
ReCreateAuxiliaryToolbar();
DisplayUnitsMsg();
break;
case ID_TB_OPTIONS_SHOW_POLAR_COORD:
Affiche_Message( wxEmptyString );
DisplayOpt.DisplayPolarCood = state;
UpdateStatusBar();
break;
case ID_TB_OPTIONS_SELECT_CURSOR:
m_CursorShape = state;
break;
case ID_TB_OPTIONS_AUTO_DEL_TRACK:
g_AutoDeleteOldTrack = state;
break;
case ID_TB_OPTIONS_SHOW_ZONES:
DisplayOpt.DisplayZonesMode = 0;
DrawPanel->Refresh();
break;
case ID_TB_OPTIONS_SHOW_ZONES_DISABLE:
DisplayOpt.DisplayZonesMode = 1;
DrawPanel->Refresh();
break;
case ID_TB_OPTIONS_SHOW_ZONES_OUTLINES_ONLY:
DisplayOpt.DisplayZonesMode = 2;
DrawPanel->Refresh();
break;
case ID_TB_OPTIONS_SHOW_PADS_SKETCH:
if( state )
{
m_DisplayPadFill = DisplayOpt.DisplayPadFill = false;
}
else
{
m_DisplayPadFill = DisplayOpt.DisplayPadFill = true;
}
DrawPanel->Refresh();
break;
case ID_TB_OPTIONS_SHOW_VIAS_SKETCH:
if( state )
{
m_DisplayViaFill = DisplayOpt.DisplayViaFill = false;
}
else
{
m_DisplayViaFill = DisplayOpt.DisplayViaFill = true;
}
DrawPanel->Refresh();
break;
case ID_TB_OPTIONS_SHOW_TRACKS_SKETCH:
m_DisplayPcbTrackFill = DisplayOpt.DisplayPcbTrackFill = !state;
DrawPanel->Refresh();
break;
case ID_TB_OPTIONS_SHOW_HIGH_CONTRAST_MODE:
DisplayOpt.ContrastModeDisplay = state;
DrawPanel->Refresh();
break;
case ID_TB_OPTIONS_SHOW_EXTRA_VERTICAL_TOOLBAR1:
m_show_microwave_tools = state;
m_auimgr.GetPane( wxT( "m_AuxVToolBar" ) ).Show( m_show_microwave_tools );
m_auimgr.Update();
break;
case ID_TB_OPTIONS_SHOW_LAYERS_MANAGER_VERTICAL_TOOLBAR:
// show auxiliary Vertical layers and visibility manager toolbar
m_show_layer_manager_tools = state;
m_auimgr.GetPane( wxT( "m_LayersManagerToolBar" ) ).Show( m_show_layer_manager_tools );
m_auimgr.Update();
if( m_show_layer_manager_tools )
GetMenuBar()->SetLabel(ID_MENU_PCB_SHOW_HIDE_LAYERS_MANAGER_DIALOG,
_("Hide &Layers Manager" ) );
else
GetMenuBar()->SetLabel(ID_MENU_PCB_SHOW_HIDE_LAYERS_MANAGER_DIALOG,
_("Show &Layers Manager" ) );
break;
default:
DisplayError( this,
wxT( "WinEDA_PcbFrame::OnSelectOptionToolbar error \n (event not handled!)" ) );
break;
}
SetToolbars();
}
<commit_msg>Use layer_widget in Gerbview Added sample gerber files for test (gerbview has problem with 2 files)<commit_after>/////////////////////////////////////////////////////////////////////////////
// Name: dialog_general_options.cpp
// Author: jean-pierre Charras
/////////////////////////////////////////////////////////////////////////////
/* functions relatives to the dialogs opened from the main menu :
* Preferences/general
* Preferences/display
*/
#include "fctsys.h"
#include "common.h"
#include "class_drawpanel.h"
#include "confirm.h"
#include "pcbnew.h"
#include "wxPcbStruct.h"
#include "class_board_design_settings.h"
#include "dialog_general_options.h"
#include "pcbnew_id.h"
Dialog_GeneralOptions::Dialog_GeneralOptions( WinEDA_PcbFrame* parent ) :
DialogGeneralOptionsBoardEditor_base( parent )
{
m_Parent = parent;
init();
GetSizer()->SetSizeHints( this );
Center();
}
void Dialog_GeneralOptions::init()
{
SetFocus();
m_Board = m_Parent->GetBoard();
/* Set display options */
m_PolarDisplay->SetSelection( DisplayOpt.DisplayPolarCood ? 1 : 0 );
m_UnitsSelection->SetSelection( g_UnitMetric ? 1 : 0 );
m_CursorShape->SetSelection( m_Parent->m_CursorShape ? 1 : 0 );
wxString timevalue;
timevalue << g_TimeOut / 60;
m_SaveTime->SetValue( timevalue );
m_MaxShowLinks->SetValue( g_MaxLinksShowed );
m_DrcOn->SetValue( Drc_On );
m_ShowModuleRatsnest->SetValue( g_Show_Module_Ratsnest );
m_ShowGlobalRatsnest->SetValue( m_Board->IsElementVisible(RATSNEST_VISIBLE) );
m_TrackAutodel->SetValue( g_AutoDeleteOldTrack );
m_Track_45_Only_Ctrl->SetValue( Track_45_Only );
m_Segments_45_Only_Ctrl->SetValue( Segments_45_Only );
m_AutoPANOpt->SetValue( m_Parent->DrawPanel->m_AutoPAN_Enable );
m_Segments_45_Only_Ctrl->SetValue( Segments_45_Only );
m_Track_DoubleSegm_Ctrl->SetValue( g_TwoSegmentTrackBuild );
m_MagneticPadOptCtrl->SetSelection( g_MagneticPadOption );
m_MagneticTrackOptCtrl->SetSelection( g_MagneticTrackOption );
}
void Dialog_GeneralOptions::OnCancelClick( wxCommandEvent& event )
{
event.Skip();
}
void Dialog_GeneralOptions::OnOkClick( wxCommandEvent& event )
{
int ii;
DisplayOpt.DisplayPolarCood =
( m_PolarDisplay->GetSelection() == 0 ) ? FALSE : true;
ii = g_UnitMetric;
g_UnitMetric = ( m_UnitsSelection->GetSelection() == 0 ) ? 0 : 1;
if( ii != g_UnitMetric )
m_Parent->ReCreateAuxiliaryToolbar();
m_Parent->m_CursorShape = m_CursorShape->GetSelection();
g_TimeOut = 60 * m_SaveTime->GetValue();
/* Updating the combobox to display the active layer. */
g_MaxLinksShowed = m_MaxShowLinks->GetValue();
Drc_On = m_DrcOn->GetValue();
if( m_Board->IsElementVisible(RATSNEST_VISIBLE) != m_ShowGlobalRatsnest->GetValue() )
{
m_Parent->SetElementVisibility(RATSNEST_VISIBLE, m_ShowGlobalRatsnest->GetValue() );
m_Parent->DrawPanel->Refresh( );
}
g_Show_Module_Ratsnest = m_ShowModuleRatsnest->GetValue();
g_AutoDeleteOldTrack = m_TrackAutodel->GetValue();
Segments_45_Only = m_Segments_45_Only_Ctrl->GetValue();
Track_45_Only = m_Track_45_Only_Ctrl->GetValue();
m_Parent->DrawPanel->m_AutoPAN_Enable = m_AutoPANOpt->GetValue();
g_TwoSegmentTrackBuild = m_Track_DoubleSegm_Ctrl->GetValue();
g_MagneticPadOption = m_MagneticPadOptCtrl->GetSelection();
g_MagneticTrackOption = m_MagneticTrackOptCtrl->GetSelection();
EndModal( 1 );
}
#include "dialog_graphic_items_options.cpp"
void WinEDA_PcbFrame::InstallPcbOptionsFrame( int id )
{
switch( id )
{
case ID_PCB_DRAWINGS_WIDTHS_SETUP:
{
WinEDA_GraphicItemsOptionsDialog dlg( this );
dlg.ShowModal();
}
break;
default:
wxMessageBox( wxT( "InstallPcbOptionsFrame() id error" ) );
break;
}
}
void WinEDA_ModuleEditFrame::InstallOptionsFrame( const wxPoint& pos )
{
WinEDA_GraphicItemsOptionsDialog dlg( this );
dlg.ShowModal();
}
/* Must be called on a click on the left toolbar (options toolbar
* Update variables according to tools states
*/
void WinEDA_PcbFrame::OnSelectOptionToolbar( wxCommandEvent& event )
{
int id = event.GetId();
bool state = m_OptionsToolBar->GetToolState( id );
switch( id )
{
case ID_TB_OPTIONS_DRC_OFF:
Drc_On = state ? FALSE : true;
break;
case ID_TB_OPTIONS_SHOW_GRID:
SetElementVisibility(GRID_VISIBLE, state);
DrawPanel->Refresh();
break;
case ID_TB_OPTIONS_SHOW_RATSNEST:
SetElementVisibility(RATSNEST_VISIBLE, state);
DrawPanel->Refresh( );
break;
case ID_TB_OPTIONS_SHOW_MODULE_RATSNEST:
g_Show_Module_Ratsnest = state; // TODO: use the visibility list
break;
case ID_TB_OPTIONS_SELECT_UNIT_MM:
g_UnitMetric = MILLIMETRE;
case ID_TB_OPTIONS_SELECT_UNIT_INCH:
if( id == ID_TB_OPTIONS_SELECT_UNIT_INCH )
g_UnitMetric = INCHES;
m_TrackAndViasSizesList_Changed = true;
UpdateStatusBar();
ReCreateAuxiliaryToolbar();
DisplayUnitsMsg();
break;
case ID_TB_OPTIONS_SHOW_POLAR_COORD:
Affiche_Message( wxEmptyString );
DisplayOpt.DisplayPolarCood = state;
UpdateStatusBar();
break;
case ID_TB_OPTIONS_SELECT_CURSOR:
m_CursorShape = state;
break;
case ID_TB_OPTIONS_AUTO_DEL_TRACK:
g_AutoDeleteOldTrack = state;
break;
case ID_TB_OPTIONS_SHOW_ZONES:
DisplayOpt.DisplayZonesMode = 0;
DrawPanel->Refresh();
break;
case ID_TB_OPTIONS_SHOW_ZONES_DISABLE:
DisplayOpt.DisplayZonesMode = 1;
DrawPanel->Refresh();
break;
case ID_TB_OPTIONS_SHOW_ZONES_OUTLINES_ONLY:
DisplayOpt.DisplayZonesMode = 2;
DrawPanel->Refresh();
break;
case ID_TB_OPTIONS_SHOW_PADS_SKETCH:
if( state )
{
m_DisplayPadFill = DisplayOpt.DisplayPadFill = false;
}
else
{
m_DisplayPadFill = DisplayOpt.DisplayPadFill = true;
}
DrawPanel->Refresh();
break;
case ID_TB_OPTIONS_SHOW_VIAS_SKETCH:
if( state )
{
m_DisplayViaFill = DisplayOpt.DisplayViaFill = false;
}
else
{
m_DisplayViaFill = DisplayOpt.DisplayViaFill = true;
}
DrawPanel->Refresh();
break;
case ID_TB_OPTIONS_SHOW_TRACKS_SKETCH:
m_DisplayPcbTrackFill = DisplayOpt.DisplayPcbTrackFill = !state;
DrawPanel->Refresh();
break;
case ID_TB_OPTIONS_SHOW_HIGH_CONTRAST_MODE:
DisplayOpt.ContrastModeDisplay = state;
DrawPanel->Refresh();
break;
case ID_TB_OPTIONS_SHOW_EXTRA_VERTICAL_TOOLBAR1:
m_show_microwave_tools = state;
m_auimgr.GetPane( wxT( "m_AuxVToolBar" ) ).Show( m_show_microwave_tools );
m_auimgr.Update();
break;
case ID_TB_OPTIONS_SHOW_MANAGE_LAYERS_VERTICAL_TOOLBAR:
// show auxiliary Vertical layers and visibility manager toolbar
m_show_layer_manager_tools = state;
m_auimgr.GetPane( wxT( "m_LayersManagerToolBar" ) ).Show( m_show_layer_manager_tools );
m_auimgr.Update();
if( m_show_layer_manager_tools )
GetMenuBar()->SetLabel(ID_MENU_PCB_SHOW_HIDE_LAYERS_MANAGER_DIALOG,
_("Hide &Layers Manager" ) );
else
GetMenuBar()->SetLabel(ID_MENU_PCB_SHOW_HIDE_LAYERS_MANAGER_DIALOG,
_("Show &Layers Manager" ) );
break;
default:
DisplayError( this,
wxT( "WinEDA_PcbFrame::OnSelectOptionToolbar error \n (event not handled!)" ) );
break;
}
SetToolbars();
}
<|endoftext|> |
<commit_before>//===- LazyCallGraph.cpp - Analysis of a Module's call graph --------------===//
//
// The LLVM Compiler Infrastructure
//
// This file is distributed under the University of Illinois Open Source
// License. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//
#include "llvm/Analysis/LazyCallGraph.h"
#include "llvm/ADT/STLExtras.h"
#include "llvm/IR/CallSite.h"
#include "llvm/IR/InstVisitor.h"
#include "llvm/IR/Instructions.h"
#include "llvm/IR/PassManager.h"
#include "llvm/Support/raw_ostream.h"
using namespace llvm;
static void findCallees(
SmallVectorImpl<Constant *> &Worklist, SmallPtrSetImpl<Constant *> &Visited,
SmallVectorImpl<PointerUnion<Function *, LazyCallGraph::Node *>> &Callees,
SmallPtrSetImpl<Function *> &CalleeSet) {
while (!Worklist.empty()) {
Constant *C = Worklist.pop_back_val();
if (Function *F = dyn_cast<Function>(C)) {
// Note that we consider *any* function with a definition to be a viable
// edge. Even if the function's definition is subject to replacement by
// some other module (say, a weak definition) there may still be
// optimizations which essentially speculate based on the definition and
// a way to check that the specific definition is in fact the one being
// used. For example, this could be done by moving the weak definition to
// a strong (internal) definition and making the weak definition be an
// alias. Then a test of the address of the weak function against the new
// strong definition's address would be an effective way to determine the
// safety of optimizing a direct call edge.
if (!F->isDeclaration() && CalleeSet.insert(F))
Callees.push_back(F);
continue;
}
for (Value *Op : C->operand_values())
if (Visited.insert(cast<Constant>(Op)))
Worklist.push_back(cast<Constant>(Op));
}
}
LazyCallGraph::Node::Node(LazyCallGraph &G, Function &F)
: G(&G), F(F), DFSNumber(0), LowLink(0) {
SmallVector<Constant *, 16> Worklist;
SmallPtrSet<Constant *, 16> Visited;
// Find all the potential callees in this function. First walk the
// instructions and add every operand which is a constant to the worklist.
for (BasicBlock &BB : F)
for (Instruction &I : BB)
for (Value *Op : I.operand_values())
if (Constant *C = dyn_cast<Constant>(Op))
if (Visited.insert(C))
Worklist.push_back(C);
// We've collected all the constant (and thus potentially function or
// function containing) operands to all of the instructions in the function.
// Process them (recursively) collecting every function found.
findCallees(Worklist, Visited, Callees, CalleeSet);
}
LazyCallGraph::LazyCallGraph(Module &M) {
for (Function &F : M)
if (!F.isDeclaration() && !F.hasLocalLinkage())
if (EntryNodeSet.insert(&F))
EntryNodes.push_back(&F);
// Now add entry nodes for functions reachable via initializers to globals.
SmallVector<Constant *, 16> Worklist;
SmallPtrSet<Constant *, 16> Visited;
for (GlobalVariable &GV : M.globals())
if (GV.hasInitializer())
if (Visited.insert(GV.getInitializer()))
Worklist.push_back(GV.getInitializer());
findCallees(Worklist, Visited, EntryNodes, EntryNodeSet);
for (auto &Entry : EntryNodes)
if (Function *F = Entry.dyn_cast<Function *>())
SCCEntryNodes.insert(F);
else
SCCEntryNodes.insert(&Entry.get<Node *>()->getFunction());
}
LazyCallGraph::LazyCallGraph(LazyCallGraph &&G)
: BPA(std::move(G.BPA)), EntryNodes(std::move(G.EntryNodes)),
EntryNodeSet(std::move(G.EntryNodeSet)), SCCBPA(std::move(G.SCCBPA)),
SCCMap(std::move(G.SCCMap)), LeafSCCs(std::move(G.LeafSCCs)),
DFSStack(std::move(G.DFSStack)),
SCCEntryNodes(std::move(G.SCCEntryNodes)) {
updateGraphPtrs();
}
LazyCallGraph &LazyCallGraph::operator=(LazyCallGraph &&G) {
BPA = std::move(G.BPA);
EntryNodes = std::move(G.EntryNodes);
EntryNodeSet = std::move(G.EntryNodeSet);
SCCBPA = std::move(G.SCCBPA);
SCCMap = std::move(G.SCCMap);
LeafSCCs = std::move(G.LeafSCCs);
DFSStack = std::move(G.DFSStack);
SCCEntryNodes = std::move(G.SCCEntryNodes);
updateGraphPtrs();
return *this;
}
LazyCallGraph::Node *LazyCallGraph::insertInto(Function &F, Node *&MappedN) {
return new (MappedN = BPA.Allocate()) Node(*this, F);
}
void LazyCallGraph::updateGraphPtrs() {
// Process all nodes updating the graph pointers.
SmallVector<Node *, 16> Worklist;
for (auto &Entry : EntryNodes)
if (Node *EntryN = Entry.dyn_cast<Node *>())
Worklist.push_back(EntryN);
while (!Worklist.empty()) {
Node *N = Worklist.pop_back_val();
N->G = this;
for (auto &Callee : N->Callees)
if (Node *CalleeN = Callee.dyn_cast<Node *>())
Worklist.push_back(CalleeN);
}
}
LazyCallGraph::SCC *LazyCallGraph::getNextSCCInPostOrder() {
// When the stack is empty, there are no more SCCs to walk in this graph.
if (DFSStack.empty()) {
// If we've handled all candidate entry nodes to the SCC forest, we're done.
if (SCCEntryNodes.empty())
return nullptr;
Node *N = get(*SCCEntryNodes.pop_back_val());
DFSStack.push_back(std::make_pair(N, N->begin()));
}
Node *N = DFSStack.back().first;
if (N->DFSNumber == 0) {
// This node hasn't been visited before, assign it a DFS number and remove
// it from the entry set.
N->LowLink = N->DFSNumber = NextDFSNumber++;
SCCEntryNodes.remove(&N->getFunction());
}
for (auto I = DFSStack.back().second, E = N->end(); I != E; ++I) {
Node *ChildN = *I;
if (ChildN->DFSNumber == 0) {
// Mark that we should start at this child when next this node is the
// top of the stack. We don't start at the next child to ensure this
// child's lowlink is reflected.
// FIXME: I don't actually think this is required, and we could start
// at the next child.
DFSStack.back().second = I;
// Recurse onto this node via a tail call.
DFSStack.push_back(std::make_pair(ChildN, ChildN->begin()));
return LazyCallGraph::getNextSCCInPostOrder();
}
// Track the lowest link of the childen, if any are still in the stack.
if (ChildN->LowLink < N->LowLink && !SCCMap.count(&ChildN->getFunction()))
N->LowLink = ChildN->LowLink;
}
// The tail of the stack is the new SCC. Allocate the SCC and pop the stack
// into it.
SCC *NewSCC = new (SCCBPA.Allocate()) SCC();
// Because we don't follow the strict Tarjan recursive formulation, walk
// from the top of the stack down, propagating the lowest link and stopping
// when the DFS number is the lowest link.
int LowestLink = N->LowLink;
do {
Node *SCCN = DFSStack.pop_back_val().first;
SCCMap.insert(std::make_pair(&SCCN->getFunction(), NewSCC));
NewSCC->Nodes.push_back(SCCN);
LowestLink = std::min(LowestLink, SCCN->LowLink);
bool Inserted =
NewSCC->NodeSet.insert(&SCCN->getFunction());
(void)Inserted;
assert(Inserted && "Cannot have duplicates in the DFSStack!");
} while (!DFSStack.empty() && LowestLink <= DFSStack.back().first->DFSNumber);
assert(LowestLink == NewSCC->Nodes.back()->DFSNumber &&
"Cannot stop with a DFS number greater than the lowest link!");
// A final pass over all edges in the SCC (this remains linear as we only
// do this once when we build the SCC) to connect it to the parent sets of
// its children.
bool IsLeafSCC = true;
for (Node *SCCN : NewSCC->Nodes)
for (Node *SCCChildN : *SCCN) {
if (NewSCC->NodeSet.count(&SCCChildN->getFunction()))
continue;
SCC *ChildSCC = SCCMap.lookup(&SCCChildN->getFunction());
assert(ChildSCC &&
"Must have all child SCCs processed when building a new SCC!");
ChildSCC->ParentSCCs.insert(NewSCC);
IsLeafSCC = false;
}
// For the SCCs where we fine no child SCCs, add them to the leaf list.
if (IsLeafSCC)
LeafSCCs.push_back(NewSCC);
return NewSCC;
}
char LazyCallGraphAnalysis::PassID;
LazyCallGraphPrinterPass::LazyCallGraphPrinterPass(raw_ostream &OS) : OS(OS) {}
static void printNodes(raw_ostream &OS, LazyCallGraph::Node &N,
SmallPtrSetImpl<LazyCallGraph::Node *> &Printed) {
// Recurse depth first through the nodes.
for (LazyCallGraph::Node *ChildN : N)
if (Printed.insert(ChildN))
printNodes(OS, *ChildN, Printed);
OS << " Call edges in function: " << N.getFunction().getName() << "\n";
for (LazyCallGraph::iterator I = N.begin(), E = N.end(); I != E; ++I)
OS << " -> " << I->getFunction().getName() << "\n";
OS << "\n";
}
static void printSCC(raw_ostream &OS, LazyCallGraph::SCC &SCC) {
ptrdiff_t SCCSize = std::distance(SCC.begin(), SCC.end());
OS << " SCC with " << SCCSize << " functions:\n";
for (LazyCallGraph::Node *N : SCC)
OS << " " << N->getFunction().getName() << "\n";
OS << "\n";
}
PreservedAnalyses LazyCallGraphPrinterPass::run(Module *M,
ModuleAnalysisManager *AM) {
LazyCallGraph &G = AM->getResult<LazyCallGraphAnalysis>(M);
OS << "Printing the call graph for module: " << M->getModuleIdentifier()
<< "\n\n";
SmallPtrSet<LazyCallGraph::Node *, 16> Printed;
for (LazyCallGraph::Node *N : G)
if (Printed.insert(N))
printNodes(OS, *N, Printed);
for (LazyCallGraph::SCC *SCC : G.postorder_sccs())
printSCC(OS, *SCC);
return PreservedAnalyses::all();
}
<commit_msg>[LCG] Fix the bugs that Ben pointed out in code review (and the MSan bot caught). Sad that we don't have warnings for these things, but bleh, no idea how to fix that.<commit_after>//===- LazyCallGraph.cpp - Analysis of a Module's call graph --------------===//
//
// The LLVM Compiler Infrastructure
//
// This file is distributed under the University of Illinois Open Source
// License. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//
#include "llvm/Analysis/LazyCallGraph.h"
#include "llvm/ADT/STLExtras.h"
#include "llvm/IR/CallSite.h"
#include "llvm/IR/InstVisitor.h"
#include "llvm/IR/Instructions.h"
#include "llvm/IR/PassManager.h"
#include "llvm/Support/raw_ostream.h"
using namespace llvm;
static void findCallees(
SmallVectorImpl<Constant *> &Worklist, SmallPtrSetImpl<Constant *> &Visited,
SmallVectorImpl<PointerUnion<Function *, LazyCallGraph::Node *>> &Callees,
SmallPtrSetImpl<Function *> &CalleeSet) {
while (!Worklist.empty()) {
Constant *C = Worklist.pop_back_val();
if (Function *F = dyn_cast<Function>(C)) {
// Note that we consider *any* function with a definition to be a viable
// edge. Even if the function's definition is subject to replacement by
// some other module (say, a weak definition) there may still be
// optimizations which essentially speculate based on the definition and
// a way to check that the specific definition is in fact the one being
// used. For example, this could be done by moving the weak definition to
// a strong (internal) definition and making the weak definition be an
// alias. Then a test of the address of the weak function against the new
// strong definition's address would be an effective way to determine the
// safety of optimizing a direct call edge.
if (!F->isDeclaration() && CalleeSet.insert(F))
Callees.push_back(F);
continue;
}
for (Value *Op : C->operand_values())
if (Visited.insert(cast<Constant>(Op)))
Worklist.push_back(cast<Constant>(Op));
}
}
LazyCallGraph::Node::Node(LazyCallGraph &G, Function &F)
: G(&G), F(F), DFSNumber(0), LowLink(0) {
SmallVector<Constant *, 16> Worklist;
SmallPtrSet<Constant *, 16> Visited;
// Find all the potential callees in this function. First walk the
// instructions and add every operand which is a constant to the worklist.
for (BasicBlock &BB : F)
for (Instruction &I : BB)
for (Value *Op : I.operand_values())
if (Constant *C = dyn_cast<Constant>(Op))
if (Visited.insert(C))
Worklist.push_back(C);
// We've collected all the constant (and thus potentially function or
// function containing) operands to all of the instructions in the function.
// Process them (recursively) collecting every function found.
findCallees(Worklist, Visited, Callees, CalleeSet);
}
LazyCallGraph::LazyCallGraph(Module &M) : NextDFSNumber(0) {
for (Function &F : M)
if (!F.isDeclaration() && !F.hasLocalLinkage())
if (EntryNodeSet.insert(&F))
EntryNodes.push_back(&F);
// Now add entry nodes for functions reachable via initializers to globals.
SmallVector<Constant *, 16> Worklist;
SmallPtrSet<Constant *, 16> Visited;
for (GlobalVariable &GV : M.globals())
if (GV.hasInitializer())
if (Visited.insert(GV.getInitializer()))
Worklist.push_back(GV.getInitializer());
findCallees(Worklist, Visited, EntryNodes, EntryNodeSet);
for (auto &Entry : EntryNodes)
if (Function *F = Entry.dyn_cast<Function *>())
SCCEntryNodes.insert(F);
else
SCCEntryNodes.insert(&Entry.get<Node *>()->getFunction());
}
LazyCallGraph::LazyCallGraph(LazyCallGraph &&G)
: BPA(std::move(G.BPA)), NodeMap(std::move(G.NodeMap)),
EntryNodes(std::move(G.EntryNodes)),
EntryNodeSet(std::move(G.EntryNodeSet)), SCCBPA(std::move(G.SCCBPA)),
SCCMap(std::move(G.SCCMap)), LeafSCCs(std::move(G.LeafSCCs)),
DFSStack(std::move(G.DFSStack)),
SCCEntryNodes(std::move(G.SCCEntryNodes)),
NextDFSNumber(G.NextDFSNumber) {
updateGraphPtrs();
}
LazyCallGraph &LazyCallGraph::operator=(LazyCallGraph &&G) {
BPA = std::move(G.BPA);
NodeMap = std::move(G.NodeMap);
EntryNodes = std::move(G.EntryNodes);
EntryNodeSet = std::move(G.EntryNodeSet);
SCCBPA = std::move(G.SCCBPA);
SCCMap = std::move(G.SCCMap);
LeafSCCs = std::move(G.LeafSCCs);
DFSStack = std::move(G.DFSStack);
SCCEntryNodes = std::move(G.SCCEntryNodes);
NextDFSNumber = G.NextDFSNumber;
updateGraphPtrs();
return *this;
}
LazyCallGraph::Node *LazyCallGraph::insertInto(Function &F, Node *&MappedN) {
return new (MappedN = BPA.Allocate()) Node(*this, F);
}
void LazyCallGraph::updateGraphPtrs() {
// Process all nodes updating the graph pointers.
SmallVector<Node *, 16> Worklist;
for (auto &Entry : EntryNodes)
if (Node *EntryN = Entry.dyn_cast<Node *>())
Worklist.push_back(EntryN);
while (!Worklist.empty()) {
Node *N = Worklist.pop_back_val();
N->G = this;
for (auto &Callee : N->Callees)
if (Node *CalleeN = Callee.dyn_cast<Node *>())
Worklist.push_back(CalleeN);
}
}
LazyCallGraph::SCC *LazyCallGraph::getNextSCCInPostOrder() {
// When the stack is empty, there are no more SCCs to walk in this graph.
if (DFSStack.empty()) {
// If we've handled all candidate entry nodes to the SCC forest, we're done.
if (SCCEntryNodes.empty())
return nullptr;
Node *N = get(*SCCEntryNodes.pop_back_val());
DFSStack.push_back(std::make_pair(N, N->begin()));
}
Node *N = DFSStack.back().first;
if (N->DFSNumber == 0) {
// This node hasn't been visited before, assign it a DFS number and remove
// it from the entry set.
N->LowLink = N->DFSNumber = NextDFSNumber++;
SCCEntryNodes.remove(&N->getFunction());
}
for (auto I = DFSStack.back().second, E = N->end(); I != E; ++I) {
Node *ChildN = *I;
if (ChildN->DFSNumber == 0) {
// Mark that we should start at this child when next this node is the
// top of the stack. We don't start at the next child to ensure this
// child's lowlink is reflected.
// FIXME: I don't actually think this is required, and we could start
// at the next child.
DFSStack.back().second = I;
// Recurse onto this node via a tail call.
DFSStack.push_back(std::make_pair(ChildN, ChildN->begin()));
return LazyCallGraph::getNextSCCInPostOrder();
}
// Track the lowest link of the childen, if any are still in the stack.
if (ChildN->LowLink < N->LowLink && !SCCMap.count(&ChildN->getFunction()))
N->LowLink = ChildN->LowLink;
}
// The tail of the stack is the new SCC. Allocate the SCC and pop the stack
// into it.
SCC *NewSCC = new (SCCBPA.Allocate()) SCC();
// Because we don't follow the strict Tarjan recursive formulation, walk
// from the top of the stack down, propagating the lowest link and stopping
// when the DFS number is the lowest link.
int LowestLink = N->LowLink;
do {
Node *SCCN = DFSStack.pop_back_val().first;
SCCMap.insert(std::make_pair(&SCCN->getFunction(), NewSCC));
NewSCC->Nodes.push_back(SCCN);
LowestLink = std::min(LowestLink, SCCN->LowLink);
bool Inserted =
NewSCC->NodeSet.insert(&SCCN->getFunction());
(void)Inserted;
assert(Inserted && "Cannot have duplicates in the DFSStack!");
} while (!DFSStack.empty() && LowestLink <= DFSStack.back().first->DFSNumber);
assert(LowestLink == NewSCC->Nodes.back()->DFSNumber &&
"Cannot stop with a DFS number greater than the lowest link!");
// A final pass over all edges in the SCC (this remains linear as we only
// do this once when we build the SCC) to connect it to the parent sets of
// its children.
bool IsLeafSCC = true;
for (Node *SCCN : NewSCC->Nodes)
for (Node *SCCChildN : *SCCN) {
if (NewSCC->NodeSet.count(&SCCChildN->getFunction()))
continue;
SCC *ChildSCC = SCCMap.lookup(&SCCChildN->getFunction());
assert(ChildSCC &&
"Must have all child SCCs processed when building a new SCC!");
ChildSCC->ParentSCCs.insert(NewSCC);
IsLeafSCC = false;
}
// For the SCCs where we fine no child SCCs, add them to the leaf list.
if (IsLeafSCC)
LeafSCCs.push_back(NewSCC);
return NewSCC;
}
char LazyCallGraphAnalysis::PassID;
LazyCallGraphPrinterPass::LazyCallGraphPrinterPass(raw_ostream &OS) : OS(OS) {}
static void printNodes(raw_ostream &OS, LazyCallGraph::Node &N,
SmallPtrSetImpl<LazyCallGraph::Node *> &Printed) {
// Recurse depth first through the nodes.
for (LazyCallGraph::Node *ChildN : N)
if (Printed.insert(ChildN))
printNodes(OS, *ChildN, Printed);
OS << " Call edges in function: " << N.getFunction().getName() << "\n";
for (LazyCallGraph::iterator I = N.begin(), E = N.end(); I != E; ++I)
OS << " -> " << I->getFunction().getName() << "\n";
OS << "\n";
}
static void printSCC(raw_ostream &OS, LazyCallGraph::SCC &SCC) {
ptrdiff_t SCCSize = std::distance(SCC.begin(), SCC.end());
OS << " SCC with " << SCCSize << " functions:\n";
for (LazyCallGraph::Node *N : SCC)
OS << " " << N->getFunction().getName() << "\n";
OS << "\n";
}
PreservedAnalyses LazyCallGraphPrinterPass::run(Module *M,
ModuleAnalysisManager *AM) {
LazyCallGraph &G = AM->getResult<LazyCallGraphAnalysis>(M);
OS << "Printing the call graph for module: " << M->getModuleIdentifier()
<< "\n\n";
SmallPtrSet<LazyCallGraph::Node *, 16> Printed;
for (LazyCallGraph::Node *N : G)
if (Printed.insert(N))
printNodes(OS, *N, Printed);
for (LazyCallGraph::SCC *SCC : G.postorder_sccs())
printSCC(OS, *SCC);
return PreservedAnalyses::all();
}
<|endoftext|> |
<commit_before>#include <yttrium/ion/document.h>
#include <yttrium/ion/node.h>
#include <yttrium/ion/object.h>
#include <yttrium/ion/value.h>
#include <yttrium/storage/reader.h>
#include <yttrium/translation.h>
#include <iostream>
using namespace Yttrium;
bool update_tr(Translation& translation, const IonObject& tr_object)
{
if (tr_object.size() != 1)
return false;
const auto& tr_node = *tr_object.begin();
if (tr_node.name() != "tr" || tr_node.size() != 1)
return false;
const auto& tr_value = *tr_node.first();
if (tr_value.type() != IonValue::Type::String)
return false;
translation.add(tr_value.string());
return true;
}
void update_translation(Translation& translation, const IonObject& source);
void update_translation(Translation& translation, const IonValue& source)
{
switch (source.type())
{
case IonValue::Type::List:
for (const auto& value : source.list())
update_translation(translation, value);
break;
case IonValue::Type::Object:
if (!update_tr(translation, *source.object()))
update_translation(translation, *source.object());
break;
default:
break;
}
}
void update_translation(Translation& translation, const IonObject& source)
{
for (const auto& node : source)
for (const auto& value : node)
update_translation(translation, value);
}
int main(int argc, char** argv)
{
if (argc < 3)
{
std::cerr << "Usage: ytr TRANSLATION SOURCES...\n";
return 1;
}
const auto translation = Translation::open(Reader(argv[1]));
if (!translation)
{
std::cerr << "ERROR: Unable to open translation \"" << argv[1] << "\"\n";
return 1;
}
for (int i = 2; i < argc; ++i)
{
const auto document = IonDocument::open(Reader(argv[i]));
if (!document)
{
std::cerr << "ERROR: Unable to open source \"" << argv[i] << "\"\n";
return 1;
}
update_translation(*translation, document->root());
}
translation->remove_obsolete();
translation->save(argv[1]);
}
<commit_msg>ytr switched to IonReader.<commit_after>#include <yttrium/ion/reader.h>
#include <yttrium/storage/reader.h>
#include <yttrium/translation.h>
#include <iostream>
using namespace Yttrium;
int main(int argc, char** argv)
{
if (argc < 3)
{
std::cerr << "Usage: ytr TRANSLATION SOURCES...\n";
return 1;
}
const auto translation = Translation::open(Reader{argv[1]});
if (!translation)
{
std::cerr << "ERROR: Unable to open translation \"" << argv[1] << "\"\n";
return 1;
}
for (int i = 2; i < argc; ++i)
{
const Reader reader{argv[i]};
if (!reader)
{
std::cerr << "ERROR: Unable to open source \"" << argv[i] << "\"\n";
return 1;
}
try
{
IonReader ion{reader};
enum { None, Open, Tr, Source, Close } stage = None;
StaticString source;
for (auto token = ion.read(); token.type() != IonReader::Token::Type::End; token = ion.read())
{
if (token.type() == IonReader::Token::Type::ObjectBegin)
stage = Open;
else if (stage == Open && token.type() == IonReader::Token::Type::Name && token.text() == "tr")
stage = Tr;
else if (stage == Tr && token.type() == IonReader::Token::Type::Value)
{
stage = Source;
source = token.text();
}
else if (stage == Source && token.type() == IonReader::Token::Type::ObjectEnd)
translation->add(source);
else
stage = None;
}
}
catch (const IonError& e)
{
std::cerr << "ERROR(" << argv[i] << "): " << e.what() << "\n";
return 1;
}
}
translation->remove_obsolete();
translation->save(argv[1]);
}
<|endoftext|> |
<commit_before>//===--- DeltaAlgorithm.h - A Set Minimization Algorithm -------*- C++ -*--===//
//
// The LLVM Compiler Infrastructure
//
// This file is distributed under the University of Illinois Open Source
// License. See LICENSE.TXT for details.
//===----------------------------------------------------------------------===//
#include "llvm/ADT/DeltaAlgorithm.h"
#include <algorithm>
using namespace llvm;
bool DeltaAlgorithm::GetTestResult(const changeset_ty &Changes) {
if (FailedTestsCache.count(Changes))
return false;
bool Result = ExecuteOneTest(Changes);
if (!Result)
FailedTestsCache.insert(Changes);
return Result;
}
void DeltaAlgorithm::Split(const changeset_ty &S, changesetlist_ty &Res) {
// FIXME: Allow clients to provide heuristics for improved splitting.
// FIXME: This is really slow.
changeset_ty LHS, RHS;
unsigned idx = 0;
for (changeset_ty::const_iterator it = S.begin(),
ie = S.end(); it != ie; ++it, ++idx)
((idx & 1) ? LHS : RHS).insert(*it);
if (!LHS.empty())
Res.push_back(LHS);
if (!RHS.empty())
Res.push_back(RHS);
}
DeltaAlgorithm::changeset_ty
DeltaAlgorithm::Delta(const changeset_ty &Changes,
const changesetlist_ty &Sets) {
// Invariant: union(Res) == Changes
UpdatedSearchState(Changes, Sets);
// If there is nothing left we can remove, we are done.
if (Sets.size() <= 1)
return Changes;
// Look for a passing subset.
changeset_ty Res;
if (Search(Changes, Sets, Res))
return Res;
// Otherwise, partition the sets if possible; if not we are done.
changesetlist_ty SplitSets;
for (changesetlist_ty::const_iterator it = Sets.begin(),
ie = Sets.end(); it != ie; ++it)
Split(*it, SplitSets);
if (SplitSets.size() == Sets.size())
return Changes;
return Delta(Changes, SplitSets);
}
bool DeltaAlgorithm::Search(const changeset_ty &Changes,
const changesetlist_ty &Sets,
changeset_ty &Res) {
// FIXME: Parallelize.
for (changesetlist_ty::const_iterator it = Sets.begin(),
ie = Sets.end(); it != ie; ++it) {
// If the test passes on this subset alone, recurse.
if (GetTestResult(*it)) {
changesetlist_ty Sets;
Split(*it, Sets);
Res = Delta(*it, Sets);
return true;
}
// Otherwise, if we have more than two sets, see if test passes on the
// complement.
if (Sets.size() > 2) {
// FIXME: This is really slow.
changeset_ty Complement;
std::set_difference(
Changes.begin(), Changes.end(), it->begin(), it->end(),
std::insert_iterator<changeset_ty>(Complement, Complement.begin()));
if (GetTestResult(Complement)) {
changesetlist_ty ComplementSets;
ComplementSets.insert(ComplementSets.end(), Sets.begin(), it);
ComplementSets.insert(ComplementSets.end(), it + 1, Sets.end());
Res = Delta(Complement, ComplementSets);
return true;
}
}
}
return false;
}
DeltaAlgorithm::changeset_ty DeltaAlgorithm::Run(const changeset_ty &Changes) {
// Check empty set first to quickly find poor test functions.
if (GetTestResult(changeset_ty()))
return changeset_ty();
// Otherwise run the real delta algorithm.
changesetlist_ty Sets;
Split(Changes, Sets);
return Delta(Changes, Sets);
}
<commit_msg>Fix typo and add missing include.<commit_after>//===--- DeltaAlgorithm.cpp - A Set Minimization Algorithm -----*- C++ -*--===//
//
// The LLVM Compiler Infrastructure
//
// This file is distributed under the University of Illinois Open Source
// License. See LICENSE.TXT for details.
//===----------------------------------------------------------------------===//
#include "llvm/ADT/DeltaAlgorithm.h"
#include <algorithm>
#include <iterator>
using namespace llvm;
bool DeltaAlgorithm::GetTestResult(const changeset_ty &Changes) {
if (FailedTestsCache.count(Changes))
return false;
bool Result = ExecuteOneTest(Changes);
if (!Result)
FailedTestsCache.insert(Changes);
return Result;
}
void DeltaAlgorithm::Split(const changeset_ty &S, changesetlist_ty &Res) {
// FIXME: Allow clients to provide heuristics for improved splitting.
// FIXME: This is really slow.
changeset_ty LHS, RHS;
unsigned idx = 0;
for (changeset_ty::const_iterator it = S.begin(),
ie = S.end(); it != ie; ++it, ++idx)
((idx & 1) ? LHS : RHS).insert(*it);
if (!LHS.empty())
Res.push_back(LHS);
if (!RHS.empty())
Res.push_back(RHS);
}
DeltaAlgorithm::changeset_ty
DeltaAlgorithm::Delta(const changeset_ty &Changes,
const changesetlist_ty &Sets) {
// Invariant: union(Res) == Changes
UpdatedSearchState(Changes, Sets);
// If there is nothing left we can remove, we are done.
if (Sets.size() <= 1)
return Changes;
// Look for a passing subset.
changeset_ty Res;
if (Search(Changes, Sets, Res))
return Res;
// Otherwise, partition the sets if possible; if not we are done.
changesetlist_ty SplitSets;
for (changesetlist_ty::const_iterator it = Sets.begin(),
ie = Sets.end(); it != ie; ++it)
Split(*it, SplitSets);
if (SplitSets.size() == Sets.size())
return Changes;
return Delta(Changes, SplitSets);
}
bool DeltaAlgorithm::Search(const changeset_ty &Changes,
const changesetlist_ty &Sets,
changeset_ty &Res) {
// FIXME: Parallelize.
for (changesetlist_ty::const_iterator it = Sets.begin(),
ie = Sets.end(); it != ie; ++it) {
// If the test passes on this subset alone, recurse.
if (GetTestResult(*it)) {
changesetlist_ty Sets;
Split(*it, Sets);
Res = Delta(*it, Sets);
return true;
}
// Otherwise, if we have more than two sets, see if test passes on the
// complement.
if (Sets.size() > 2) {
// FIXME: This is really slow.
changeset_ty Complement;
std::set_difference(
Changes.begin(), Changes.end(), it->begin(), it->end(),
std::insert_iterator<changeset_ty>(Complement, Complement.begin()));
if (GetTestResult(Complement)) {
changesetlist_ty ComplementSets;
ComplementSets.insert(ComplementSets.end(), Sets.begin(), it);
ComplementSets.insert(ComplementSets.end(), it + 1, Sets.end());
Res = Delta(Complement, ComplementSets);
return true;
}
}
}
return false;
}
DeltaAlgorithm::changeset_ty DeltaAlgorithm::Run(const changeset_ty &Changes) {
// Check empty set first to quickly find poor test functions.
if (GetTestResult(changeset_ty()))
return changeset_ty();
// Otherwise run the real delta algorithm.
changesetlist_ty Sets;
Split(Changes, Sets);
return Delta(Changes, Sets);
}
<|endoftext|> |
<commit_before>//===- Inliner.cpp - Code common to all inliners --------------------------===//
//
// The LLVM Compiler Infrastructure
//
// This file is distributed under the University of Illinois Open Source
// License. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//
//
// This file implements the mechanics required to implement inlining without
// missing any calls and updating the call graph. The decisions of which calls
// are profitable to inline are implemented elsewhere.
//
//===----------------------------------------------------------------------===//
#define DEBUG_TYPE "inline"
#include "llvm/Module.h"
#include "llvm/Instructions.h"
#include "llvm/IntrinsicInst.h"
#include "llvm/Analysis/CallGraph.h"
#include "llvm/Support/CallSite.h"
#include "llvm/Target/TargetData.h"
#include "llvm/Transforms/IPO/InlinerPass.h"
#include "llvm/Transforms/Utils/Cloning.h"
#include "llvm/Support/CommandLine.h"
#include "llvm/Support/Debug.h"
#include "llvm/Support/raw_ostream.h"
#include "llvm/ADT/Statistic.h"
#include <set>
using namespace llvm;
STATISTIC(NumInlined, "Number of functions inlined");
STATISTIC(NumDeleted, "Number of functions deleted because all callers found");
static cl::opt<int>
InlineLimit("inline-threshold", cl::Hidden, cl::init(200),
cl::desc("Control the amount of inlining to perform (default = 200)"));
Inliner::Inliner(void *ID)
: CallGraphSCCPass(ID), InlineThreshold(InlineLimit) {}
Inliner::Inliner(void *ID, int Threshold)
: CallGraphSCCPass(ID), InlineThreshold(Threshold) {}
/// getAnalysisUsage - For this class, we declare that we require and preserve
/// the call graph. If the derived class implements this method, it should
/// always explicitly call the implementation here.
void Inliner::getAnalysisUsage(AnalysisUsage &Info) const {
CallGraphSCCPass::getAnalysisUsage(Info);
}
// InlineCallIfPossible - If it is possible to inline the specified call site,
// do so and update the CallGraph for this operation.
bool Inliner::InlineCallIfPossible(CallSite CS, CallGraph &CG,
const SmallPtrSet<Function*, 8> &SCCFunctions,
const TargetData *TD) {
Function *Callee = CS.getCalledFunction();
Function *Caller = CS.getCaller();
if (!InlineFunction(CS, &CG, TD)) return false;
// If the inlined function had a higher stack protection level than the
// calling function, then bump up the caller's stack protection level.
if (Callee->hasFnAttr(Attribute::StackProtectReq))
Caller->addFnAttr(Attribute::StackProtectReq);
else if (Callee->hasFnAttr(Attribute::StackProtect) &&
!Caller->hasFnAttr(Attribute::StackProtectReq))
Caller->addFnAttr(Attribute::StackProtect);
// If we inlined the last possible call site to the function, delete the
// function body now.
if (Callee->use_empty() && (Callee->hasLocalLinkage() ||
Callee->hasAvailableExternallyLinkage()) &&
!SCCFunctions.count(Callee)) {
DEBUG(errs() << " -> Deleting dead function: "
<< Callee->getName() << "\n");
CallGraphNode *CalleeNode = CG[Callee];
// Remove any call graph edges from the callee to its callees.
CalleeNode->removeAllCalledFunctions();
resetCachedCostInfo(CalleeNode->getFunction());
// Removing the node for callee from the call graph and delete it.
delete CG.removeFunctionFromModule(CalleeNode);
++NumDeleted;
}
return true;
}
/// shouldInline - Return true if the inliner should attempt to inline
/// at the given CallSite.
bool Inliner::shouldInline(CallSite CS) {
InlineCost IC = getInlineCost(CS);
float FudgeFactor = getInlineFudgeFactor(CS);
if (IC.isAlways()) {
DEBUG(errs() << " Inlining: cost=always"
<< ", Call: " << *CS.getInstruction() << "\n");
return true;
}
if (IC.isNever()) {
DEBUG(errs() << " NOT Inlining: cost=never"
<< ", Call: " << *CS.getInstruction() << "\n");
return false;
}
int Cost = IC.getValue();
int CurrentThreshold = InlineThreshold;
Function *Fn = CS.getCaller();
if (Fn && !Fn->isDeclaration() &&
Fn->hasFnAttr(Attribute::OptimizeForSize) &&
InlineThreshold != 50)
CurrentThreshold = 50;
if (Cost >= (int)(CurrentThreshold * FudgeFactor)) {
DEBUG(errs() << " NOT Inlining: cost=" << Cost
<< ", Call: " << *CS.getInstruction() << "\n");
return false;
} else {
DEBUG(errs() << " Inlining: cost=" << Cost
<< ", Call: " << *CS.getInstruction() << "\n");
return true;
}
}
bool Inliner::runOnSCC(const std::vector<CallGraphNode*> &SCC) {
CallGraph &CG = getAnalysis<CallGraph>();
const TargetData *TD = getAnalysisIfAvailable<TargetData>();
SmallPtrSet<Function*, 8> SCCFunctions;
DEBUG(errs() << "Inliner visiting SCC:");
for (unsigned i = 0, e = SCC.size(); i != e; ++i) {
Function *F = SCC[i]->getFunction();
if (F) SCCFunctions.insert(F);
DEBUG(errs() << " " << (F ? F->getName() : "INDIRECTNODE"));
}
// Scan through and identify all call sites ahead of time so that we only
// inline call sites in the original functions, not call sites that result
// from inlining other functions.
std::vector<CallSite> CallSites;
for (unsigned i = 0, e = SCC.size(); i != e; ++i)
if (Function *F = SCC[i]->getFunction())
for (Function::iterator BB = F->begin(), E = F->end(); BB != E; ++BB)
for (BasicBlock::iterator I = BB->begin(); I != BB->end(); ++I) {
CallSite CS = CallSite::get(I);
if (CS.getInstruction() && !isa<DbgInfoIntrinsic>(I) &&
(!CS.getCalledFunction() ||
!CS.getCalledFunction()->isDeclaration()))
CallSites.push_back(CS);
}
DEBUG(errs() << ": " << CallSites.size() << " call sites.\n");
// Now that we have all of the call sites, move the ones to functions in the
// current SCC to the end of the list.
unsigned FirstCallInSCC = CallSites.size();
for (unsigned i = 0; i < FirstCallInSCC; ++i)
if (Function *F = CallSites[i].getCalledFunction())
if (SCCFunctions.count(F))
std::swap(CallSites[i--], CallSites[--FirstCallInSCC]);
// Now that we have all of the call sites, loop over them and inline them if
// it looks profitable to do so.
bool Changed = false;
bool LocalChange;
do {
LocalChange = false;
// Iterate over the outer loop because inlining functions can cause indirect
// calls to become direct calls.
for (unsigned CSi = 0; CSi != CallSites.size(); ++CSi)
if (Function *Callee = CallSites[CSi].getCalledFunction()) {
// Calls to external functions are never inlinable.
if (Callee->isDeclaration()) {
if (SCC.size() == 1) {
std::swap(CallSites[CSi], CallSites.back());
CallSites.pop_back();
} else {
// Keep the 'in SCC / not in SCC' boundary correct.
CallSites.erase(CallSites.begin()+CSi);
}
--CSi;
continue;
}
// If the policy determines that we should inline this function,
// try to do so.
CallSite CS = CallSites[CSi];
if (shouldInline(CS)) {
Function *Caller = CS.getCaller();
// Attempt to inline the function...
if (InlineCallIfPossible(CS, CG, SCCFunctions, TD)) {
// Remove any cached cost info for this caller, as inlining the
// callee has increased the size of the caller (which may be the
// same as the callee).
resetCachedCostInfo(Caller);
// Remove this call site from the list. If possible, use
// swap/pop_back for efficiency, but do not use it if doing so would
// move a call site to a function in this SCC before the
// 'FirstCallInSCC' barrier.
if (SCC.size() == 1) {
std::swap(CallSites[CSi], CallSites.back());
CallSites.pop_back();
} else {
CallSites.erase(CallSites.begin()+CSi);
}
--CSi;
++NumInlined;
Changed = true;
LocalChange = true;
}
}
}
} while (LocalChange);
return Changed;
}
// doFinalization - Remove now-dead linkonce functions at the end of
// processing to avoid breaking the SCC traversal.
bool Inliner::doFinalization(CallGraph &CG) {
return removeDeadFunctions(CG);
}
/// removeDeadFunctions - Remove dead functions that are not included in
/// DNR (Do Not Remove) list.
bool Inliner::removeDeadFunctions(CallGraph &CG,
SmallPtrSet<const Function *, 16> *DNR) {
std::set<CallGraphNode*> FunctionsToRemove;
// Scan for all of the functions, looking for ones that should now be removed
// from the program. Insert the dead ones in the FunctionsToRemove set.
for (CallGraph::iterator I = CG.begin(), E = CG.end(); I != E; ++I) {
CallGraphNode *CGN = I->second;
if (Function *F = CGN ? CGN->getFunction() : 0) {
// If the only remaining users of the function are dead constants, remove
// them.
F->removeDeadConstantUsers();
if (DNR && DNR->count(F))
continue;
if ((F->hasLinkOnceLinkage() || F->hasLocalLinkage()) &&
F->use_empty()) {
// Remove any call graph edges from the function to its callees.
CGN->removeAllCalledFunctions();
// Remove any edges from the external node to the function's call graph
// node. These edges might have been made irrelegant due to
// optimization of the program.
CG.getExternalCallingNode()->removeAnyCallEdgeTo(CGN);
// Removing the node for callee from the call graph and delete it.
FunctionsToRemove.insert(CGN);
}
}
}
// Now that we know which functions to delete, do so. We didn't want to do
// this inline, because that would invalidate our CallGraph::iterator
// objects. :(
bool Changed = false;
for (std::set<CallGraphNode*>::iterator I = FunctionsToRemove.begin(),
E = FunctionsToRemove.end(); I != E; ++I) {
resetCachedCostInfo((*I)->getFunction());
delete CG.removeFunctionFromModule(*I);
++NumDeleted;
Changed = true;
}
return Changed;
}
<commit_msg>Allow multiple occurrences of -inline-threshold on the command line. This gives llvm-gcc developers a way to control inlining (documented as "not intended for end users").<commit_after>//===- Inliner.cpp - Code common to all inliners --------------------------===//
//
// The LLVM Compiler Infrastructure
//
// This file is distributed under the University of Illinois Open Source
// License. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//
//
// This file implements the mechanics required to implement inlining without
// missing any calls and updating the call graph. The decisions of which calls
// are profitable to inline are implemented elsewhere.
//
//===----------------------------------------------------------------------===//
#define DEBUG_TYPE "inline"
#include "llvm/Module.h"
#include "llvm/Instructions.h"
#include "llvm/IntrinsicInst.h"
#include "llvm/Analysis/CallGraph.h"
#include "llvm/Support/CallSite.h"
#include "llvm/Target/TargetData.h"
#include "llvm/Transforms/IPO/InlinerPass.h"
#include "llvm/Transforms/Utils/Cloning.h"
#include "llvm/Support/CommandLine.h"
#include "llvm/Support/Debug.h"
#include "llvm/Support/raw_ostream.h"
#include "llvm/ADT/Statistic.h"
#include <set>
using namespace llvm;
STATISTIC(NumInlined, "Number of functions inlined");
STATISTIC(NumDeleted, "Number of functions deleted because all callers found");
static cl::opt<int>
InlineLimit("inline-threshold", cl::Hidden, cl::init(200), cl::ZeroOrMore,
cl::desc("Control the amount of inlining to perform (default = 200)"));
Inliner::Inliner(void *ID)
: CallGraphSCCPass(ID), InlineThreshold(InlineLimit) {}
Inliner::Inliner(void *ID, int Threshold)
: CallGraphSCCPass(ID), InlineThreshold(Threshold) {}
/// getAnalysisUsage - For this class, we declare that we require and preserve
/// the call graph. If the derived class implements this method, it should
/// always explicitly call the implementation here.
void Inliner::getAnalysisUsage(AnalysisUsage &Info) const {
CallGraphSCCPass::getAnalysisUsage(Info);
}
// InlineCallIfPossible - If it is possible to inline the specified call site,
// do so and update the CallGraph for this operation.
bool Inliner::InlineCallIfPossible(CallSite CS, CallGraph &CG,
const SmallPtrSet<Function*, 8> &SCCFunctions,
const TargetData *TD) {
Function *Callee = CS.getCalledFunction();
Function *Caller = CS.getCaller();
if (!InlineFunction(CS, &CG, TD)) return false;
// If the inlined function had a higher stack protection level than the
// calling function, then bump up the caller's stack protection level.
if (Callee->hasFnAttr(Attribute::StackProtectReq))
Caller->addFnAttr(Attribute::StackProtectReq);
else if (Callee->hasFnAttr(Attribute::StackProtect) &&
!Caller->hasFnAttr(Attribute::StackProtectReq))
Caller->addFnAttr(Attribute::StackProtect);
// If we inlined the last possible call site to the function, delete the
// function body now.
if (Callee->use_empty() && (Callee->hasLocalLinkage() ||
Callee->hasAvailableExternallyLinkage()) &&
!SCCFunctions.count(Callee)) {
DEBUG(errs() << " -> Deleting dead function: "
<< Callee->getName() << "\n");
CallGraphNode *CalleeNode = CG[Callee];
// Remove any call graph edges from the callee to its callees.
CalleeNode->removeAllCalledFunctions();
resetCachedCostInfo(CalleeNode->getFunction());
// Removing the node for callee from the call graph and delete it.
delete CG.removeFunctionFromModule(CalleeNode);
++NumDeleted;
}
return true;
}
/// shouldInline - Return true if the inliner should attempt to inline
/// at the given CallSite.
bool Inliner::shouldInline(CallSite CS) {
InlineCost IC = getInlineCost(CS);
float FudgeFactor = getInlineFudgeFactor(CS);
if (IC.isAlways()) {
DEBUG(errs() << " Inlining: cost=always"
<< ", Call: " << *CS.getInstruction() << "\n");
return true;
}
if (IC.isNever()) {
DEBUG(errs() << " NOT Inlining: cost=never"
<< ", Call: " << *CS.getInstruction() << "\n");
return false;
}
int Cost = IC.getValue();
int CurrentThreshold = InlineThreshold;
Function *Fn = CS.getCaller();
if (Fn && !Fn->isDeclaration() &&
Fn->hasFnAttr(Attribute::OptimizeForSize) &&
InlineThreshold != 50)
CurrentThreshold = 50;
if (Cost >= (int)(CurrentThreshold * FudgeFactor)) {
DEBUG(errs() << " NOT Inlining: cost=" << Cost
<< ", Call: " << *CS.getInstruction() << "\n");
return false;
} else {
DEBUG(errs() << " Inlining: cost=" << Cost
<< ", Call: " << *CS.getInstruction() << "\n");
return true;
}
}
bool Inliner::runOnSCC(const std::vector<CallGraphNode*> &SCC) {
CallGraph &CG = getAnalysis<CallGraph>();
const TargetData *TD = getAnalysisIfAvailable<TargetData>();
SmallPtrSet<Function*, 8> SCCFunctions;
DEBUG(errs() << "Inliner visiting SCC:");
for (unsigned i = 0, e = SCC.size(); i != e; ++i) {
Function *F = SCC[i]->getFunction();
if (F) SCCFunctions.insert(F);
DEBUG(errs() << " " << (F ? F->getName() : "INDIRECTNODE"));
}
// Scan through and identify all call sites ahead of time so that we only
// inline call sites in the original functions, not call sites that result
// from inlining other functions.
std::vector<CallSite> CallSites;
for (unsigned i = 0, e = SCC.size(); i != e; ++i)
if (Function *F = SCC[i]->getFunction())
for (Function::iterator BB = F->begin(), E = F->end(); BB != E; ++BB)
for (BasicBlock::iterator I = BB->begin(); I != BB->end(); ++I) {
CallSite CS = CallSite::get(I);
if (CS.getInstruction() && !isa<DbgInfoIntrinsic>(I) &&
(!CS.getCalledFunction() ||
!CS.getCalledFunction()->isDeclaration()))
CallSites.push_back(CS);
}
DEBUG(errs() << ": " << CallSites.size() << " call sites.\n");
// Now that we have all of the call sites, move the ones to functions in the
// current SCC to the end of the list.
unsigned FirstCallInSCC = CallSites.size();
for (unsigned i = 0; i < FirstCallInSCC; ++i)
if (Function *F = CallSites[i].getCalledFunction())
if (SCCFunctions.count(F))
std::swap(CallSites[i--], CallSites[--FirstCallInSCC]);
// Now that we have all of the call sites, loop over them and inline them if
// it looks profitable to do so.
bool Changed = false;
bool LocalChange;
do {
LocalChange = false;
// Iterate over the outer loop because inlining functions can cause indirect
// calls to become direct calls.
for (unsigned CSi = 0; CSi != CallSites.size(); ++CSi)
if (Function *Callee = CallSites[CSi].getCalledFunction()) {
// Calls to external functions are never inlinable.
if (Callee->isDeclaration()) {
if (SCC.size() == 1) {
std::swap(CallSites[CSi], CallSites.back());
CallSites.pop_back();
} else {
// Keep the 'in SCC / not in SCC' boundary correct.
CallSites.erase(CallSites.begin()+CSi);
}
--CSi;
continue;
}
// If the policy determines that we should inline this function,
// try to do so.
CallSite CS = CallSites[CSi];
if (shouldInline(CS)) {
Function *Caller = CS.getCaller();
// Attempt to inline the function...
if (InlineCallIfPossible(CS, CG, SCCFunctions, TD)) {
// Remove any cached cost info for this caller, as inlining the
// callee has increased the size of the caller (which may be the
// same as the callee).
resetCachedCostInfo(Caller);
// Remove this call site from the list. If possible, use
// swap/pop_back for efficiency, but do not use it if doing so would
// move a call site to a function in this SCC before the
// 'FirstCallInSCC' barrier.
if (SCC.size() == 1) {
std::swap(CallSites[CSi], CallSites.back());
CallSites.pop_back();
} else {
CallSites.erase(CallSites.begin()+CSi);
}
--CSi;
++NumInlined;
Changed = true;
LocalChange = true;
}
}
}
} while (LocalChange);
return Changed;
}
// doFinalization - Remove now-dead linkonce functions at the end of
// processing to avoid breaking the SCC traversal.
bool Inliner::doFinalization(CallGraph &CG) {
return removeDeadFunctions(CG);
}
/// removeDeadFunctions - Remove dead functions that are not included in
/// DNR (Do Not Remove) list.
bool Inliner::removeDeadFunctions(CallGraph &CG,
SmallPtrSet<const Function *, 16> *DNR) {
std::set<CallGraphNode*> FunctionsToRemove;
// Scan for all of the functions, looking for ones that should now be removed
// from the program. Insert the dead ones in the FunctionsToRemove set.
for (CallGraph::iterator I = CG.begin(), E = CG.end(); I != E; ++I) {
CallGraphNode *CGN = I->second;
if (Function *F = CGN ? CGN->getFunction() : 0) {
// If the only remaining users of the function are dead constants, remove
// them.
F->removeDeadConstantUsers();
if (DNR && DNR->count(F))
continue;
if ((F->hasLinkOnceLinkage() || F->hasLocalLinkage()) &&
F->use_empty()) {
// Remove any call graph edges from the function to its callees.
CGN->removeAllCalledFunctions();
// Remove any edges from the external node to the function's call graph
// node. These edges might have been made irrelegant due to
// optimization of the program.
CG.getExternalCallingNode()->removeAnyCallEdgeTo(CGN);
// Removing the node for callee from the call graph and delete it.
FunctionsToRemove.insert(CGN);
}
}
}
// Now that we know which functions to delete, do so. We didn't want to do
// this inline, because that would invalidate our CallGraph::iterator
// objects. :(
bool Changed = false;
for (std::set<CallGraphNode*>::iterator I = FunctionsToRemove.begin(),
E = FunctionsToRemove.end(); I != E; ++I) {
resetCachedCostInfo((*I)->getFunction());
delete CG.removeFunctionFromModule(*I);
++NumDeleted;
Changed = true;
}
return Changed;
}
<|endoftext|> |
<commit_before>//===- Inliner.cpp - Code common to all inliners --------------------------===//
//
// The LLVM Compiler Infrastructure
//
// This file is distributed under the University of Illinois Open Source
// License. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//
//
// This file implements the mechanics required to implement inlining without
// missing any calls and updating the call graph. The decisions of which calls
// are profitable to inline are implemented elsewhere.
//
//===----------------------------------------------------------------------===//
#define DEBUG_TYPE "inline"
#include "llvm/Module.h"
#include "llvm/Instructions.h"
#include "llvm/IntrinsicInst.h"
#include "llvm/Analysis/CallGraph.h"
#include "llvm/Support/CallSite.h"
#include "llvm/Target/TargetData.h"
#include "llvm/Transforms/IPO/InlinerPass.h"
#include "llvm/Transforms/Utils/Cloning.h"
#include "llvm/Support/CommandLine.h"
#include "llvm/Support/Debug.h"
#include "llvm/Support/raw_ostream.h"
#include "llvm/ADT/Statistic.h"
#include <set>
using namespace llvm;
STATISTIC(NumInlined, "Number of functions inlined");
STATISTIC(NumDeleted, "Number of functions deleted because all callers found");
static cl::opt<int>
InlineLimit("inline-threshold", cl::Hidden, cl::init(200),
cl::desc("Control the amount of inlining to perform (default = 200)"));
Inliner::Inliner(void *ID)
: CallGraphSCCPass(ID), InlineThreshold(InlineLimit) {}
Inliner::Inliner(void *ID, int Threshold)
: CallGraphSCCPass(ID), InlineThreshold(Threshold) {}
/// getAnalysisUsage - For this class, we declare that we require and preserve
/// the call graph. If the derived class implements this method, it should
/// always explicitly call the implementation here.
void Inliner::getAnalysisUsage(AnalysisUsage &Info) const {
CallGraphSCCPass::getAnalysisUsage(Info);
}
// InlineCallIfPossible - If it is possible to inline the specified call site,
// do so and update the CallGraph for this operation.
bool Inliner::InlineCallIfPossible(CallSite CS, CallGraph &CG,
const SmallPtrSet<Function*, 8> &SCCFunctions,
const TargetData *TD) {
Function *Callee = CS.getCalledFunction();
Function *Caller = CS.getCaller();
if (!InlineFunction(CS, &CG, TD)) return false;
// If the inlined function had a higher stack protection level than the
// calling function, then bump up the caller's stack protection level.
if (Callee->hasFnAttr(Attribute::StackProtectReq))
Caller->addFnAttr(Attribute::StackProtectReq);
else if (Callee->hasFnAttr(Attribute::StackProtect) &&
!Caller->hasFnAttr(Attribute::StackProtectReq))
Caller->addFnAttr(Attribute::StackProtect);
// If we inlined the last possible call site to the function, delete the
// function body now.
if (Callee->use_empty() && (Callee->hasLocalLinkage() ||
Callee->hasAvailableExternallyLinkage()) &&
!SCCFunctions.count(Callee)) {
DEBUG(errs() << " -> Deleting dead function: "
<< Callee->getName() << "\n");
CallGraphNode *CalleeNode = CG[Callee];
// Remove any call graph edges from the callee to its callees.
CalleeNode->removeAllCalledFunctions();
resetCachedCostInfo(CalleeNode->getFunction());
// Removing the node for callee from the call graph and delete it.
delete CG.removeFunctionFromModule(CalleeNode);
++NumDeleted;
}
return true;
}
/// shouldInline - Return true if the inliner should attempt to inline
/// at the given CallSite.
bool Inliner::shouldInline(CallSite CS) {
InlineCost IC = getInlineCost(CS);
float FudgeFactor = getInlineFudgeFactor(CS);
if (IC.isAlways()) {
DOUT << " Inlining: cost=always"
<< ", Call: " << *CS.getInstruction() << "\n";
return true;
}
if (IC.isNever()) {
DOUT << " NOT Inlining: cost=never"
<< ", Call: " << *CS.getInstruction() << "\n";
return false;
}
int Cost = IC.getValue();
int CurrentThreshold = InlineThreshold;
Function *Fn = CS.getCaller();
if (Fn && !Fn->isDeclaration()
&& Fn->hasFnAttr(Attribute::OptimizeForSize)
&& InlineThreshold != 50) {
CurrentThreshold = 50;
}
if (Cost >= (int)(CurrentThreshold * FudgeFactor)) {
DOUT << " NOT Inlining: cost=" << Cost
<< ", Call: " << *CS.getInstruction() << "\n";
return false;
} else {
DOUT << " Inlining: cost=" << Cost
<< ", Call: " << *CS.getInstruction() << "\n";
return true;
}
}
bool Inliner::runOnSCC(const std::vector<CallGraphNode*> &SCC) {
CallGraph &CG = getAnalysis<CallGraph>();
const TargetData *TD = getAnalysisIfAvailable<TargetData>();
SmallPtrSet<Function*, 8> SCCFunctions;
DOUT << "Inliner visiting SCC:";
for (unsigned i = 0, e = SCC.size(); i != e; ++i) {
Function *F = SCC[i]->getFunction();
if (F) SCCFunctions.insert(F);
DEBUG(errs() << " " << (F ? F->getName() : "INDIRECTNODE"));
}
// Scan through and identify all call sites ahead of time so that we only
// inline call sites in the original functions, not call sites that result
// from inlining other functions.
std::vector<CallSite> CallSites;
for (unsigned i = 0, e = SCC.size(); i != e; ++i)
if (Function *F = SCC[i]->getFunction())
for (Function::iterator BB = F->begin(), E = F->end(); BB != E; ++BB)
for (BasicBlock::iterator I = BB->begin(); I != BB->end(); ++I) {
CallSite CS = CallSite::get(I);
if (CS.getInstruction() && !isa<DbgInfoIntrinsic>(I) &&
(!CS.getCalledFunction() ||
!CS.getCalledFunction()->isDeclaration()))
CallSites.push_back(CS);
}
DOUT << ": " << CallSites.size() << " call sites.\n";
// Now that we have all of the call sites, move the ones to functions in the
// current SCC to the end of the list.
unsigned FirstCallInSCC = CallSites.size();
for (unsigned i = 0; i < FirstCallInSCC; ++i)
if (Function *F = CallSites[i].getCalledFunction())
if (SCCFunctions.count(F))
std::swap(CallSites[i--], CallSites[--FirstCallInSCC]);
// Now that we have all of the call sites, loop over them and inline them if
// it looks profitable to do so.
bool Changed = false;
bool LocalChange;
do {
LocalChange = false;
// Iterate over the outer loop because inlining functions can cause indirect
// calls to become direct calls.
for (unsigned CSi = 0; CSi != CallSites.size(); ++CSi)
if (Function *Callee = CallSites[CSi].getCalledFunction()) {
// Calls to external functions are never inlinable.
if (Callee->isDeclaration()) {
if (SCC.size() == 1) {
std::swap(CallSites[CSi], CallSites.back());
CallSites.pop_back();
} else {
// Keep the 'in SCC / not in SCC' boundary correct.
CallSites.erase(CallSites.begin()+CSi);
}
--CSi;
continue;
}
// If the policy determines that we should inline this function,
// try to do so.
CallSite CS = CallSites[CSi];
if (shouldInline(CS)) {
Function *Caller = CS.getCaller();
// Attempt to inline the function...
if (InlineCallIfPossible(CS, CG, SCCFunctions, TD)) {
// Remove any cached cost info for this caller, as inlining the
// callee has increased the size of the caller (which may be the
// same as the callee).
resetCachedCostInfo(Caller);
// Remove this call site from the list. If possible, use
// swap/pop_back for efficiency, but do not use it if doing so would
// move a call site to a function in this SCC before the
// 'FirstCallInSCC' barrier.
if (SCC.size() == 1) {
std::swap(CallSites[CSi], CallSites.back());
CallSites.pop_back();
} else {
CallSites.erase(CallSites.begin()+CSi);
}
--CSi;
++NumInlined;
Changed = true;
LocalChange = true;
}
}
}
} while (LocalChange);
return Changed;
}
// doFinalization - Remove now-dead linkonce functions at the end of
// processing to avoid breaking the SCC traversal.
bool Inliner::doFinalization(CallGraph &CG) {
return removeDeadFunctions(CG);
}
/// removeDeadFunctions - Remove dead functions that are not included in
/// DNR (Do Not Remove) list.
bool Inliner::removeDeadFunctions(CallGraph &CG,
SmallPtrSet<const Function *, 16> *DNR) {
std::set<CallGraphNode*> FunctionsToRemove;
// Scan for all of the functions, looking for ones that should now be removed
// from the program. Insert the dead ones in the FunctionsToRemove set.
for (CallGraph::iterator I = CG.begin(), E = CG.end(); I != E; ++I) {
CallGraphNode *CGN = I->second;
if (Function *F = CGN ? CGN->getFunction() : 0) {
// If the only remaining users of the function are dead constants, remove
// them.
F->removeDeadConstantUsers();
if (DNR && DNR->count(F))
continue;
if ((F->hasLinkOnceLinkage() || F->hasLocalLinkage()) &&
F->use_empty()) {
// Remove any call graph edges from the function to its callees.
CGN->removeAllCalledFunctions();
// Remove any edges from the external node to the function's call graph
// node. These edges might have been made irrelegant due to
// optimization of the program.
CG.getExternalCallingNode()->removeAnyCallEdgeTo(CGN);
// Removing the node for callee from the call graph and delete it.
FunctionsToRemove.insert(CGN);
}
}
}
// Now that we know which functions to delete, do so. We didn't want to do
// this inline, because that would invalidate our CallGraph::iterator
// objects. :(
bool Changed = false;
for (std::set<CallGraphNode*>::iterator I = FunctionsToRemove.begin(),
E = FunctionsToRemove.end(); I != E; ++I) {
resetCachedCostInfo((*I)->getFunction());
delete CG.removeFunctionFromModule(*I);
++NumDeleted;
Changed = true;
}
return Changed;
}
<commit_msg>- Convert the rest of the DOUTs to DEBUG+errs(). - One formatting change.<commit_after>//===- Inliner.cpp - Code common to all inliners --------------------------===//
//
// The LLVM Compiler Infrastructure
//
// This file is distributed under the University of Illinois Open Source
// License. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//
//
// This file implements the mechanics required to implement inlining without
// missing any calls and updating the call graph. The decisions of which calls
// are profitable to inline are implemented elsewhere.
//
//===----------------------------------------------------------------------===//
#define DEBUG_TYPE "inline"
#include "llvm/Module.h"
#include "llvm/Instructions.h"
#include "llvm/IntrinsicInst.h"
#include "llvm/Analysis/CallGraph.h"
#include "llvm/Support/CallSite.h"
#include "llvm/Target/TargetData.h"
#include "llvm/Transforms/IPO/InlinerPass.h"
#include "llvm/Transforms/Utils/Cloning.h"
#include "llvm/Support/CommandLine.h"
#include "llvm/Support/Debug.h"
#include "llvm/Support/raw_ostream.h"
#include "llvm/ADT/Statistic.h"
#include <set>
using namespace llvm;
STATISTIC(NumInlined, "Number of functions inlined");
STATISTIC(NumDeleted, "Number of functions deleted because all callers found");
static cl::opt<int>
InlineLimit("inline-threshold", cl::Hidden, cl::init(200),
cl::desc("Control the amount of inlining to perform (default = 200)"));
Inliner::Inliner(void *ID)
: CallGraphSCCPass(ID), InlineThreshold(InlineLimit) {}
Inliner::Inliner(void *ID, int Threshold)
: CallGraphSCCPass(ID), InlineThreshold(Threshold) {}
/// getAnalysisUsage - For this class, we declare that we require and preserve
/// the call graph. If the derived class implements this method, it should
/// always explicitly call the implementation here.
void Inliner::getAnalysisUsage(AnalysisUsage &Info) const {
CallGraphSCCPass::getAnalysisUsage(Info);
}
// InlineCallIfPossible - If it is possible to inline the specified call site,
// do so and update the CallGraph for this operation.
bool Inliner::InlineCallIfPossible(CallSite CS, CallGraph &CG,
const SmallPtrSet<Function*, 8> &SCCFunctions,
const TargetData *TD) {
Function *Callee = CS.getCalledFunction();
Function *Caller = CS.getCaller();
if (!InlineFunction(CS, &CG, TD)) return false;
// If the inlined function had a higher stack protection level than the
// calling function, then bump up the caller's stack protection level.
if (Callee->hasFnAttr(Attribute::StackProtectReq))
Caller->addFnAttr(Attribute::StackProtectReq);
else if (Callee->hasFnAttr(Attribute::StackProtect) &&
!Caller->hasFnAttr(Attribute::StackProtectReq))
Caller->addFnAttr(Attribute::StackProtect);
// If we inlined the last possible call site to the function, delete the
// function body now.
if (Callee->use_empty() && (Callee->hasLocalLinkage() ||
Callee->hasAvailableExternallyLinkage()) &&
!SCCFunctions.count(Callee)) {
DEBUG(errs() << " -> Deleting dead function: "
<< Callee->getName() << "\n");
CallGraphNode *CalleeNode = CG[Callee];
// Remove any call graph edges from the callee to its callees.
CalleeNode->removeAllCalledFunctions();
resetCachedCostInfo(CalleeNode->getFunction());
// Removing the node for callee from the call graph and delete it.
delete CG.removeFunctionFromModule(CalleeNode);
++NumDeleted;
}
return true;
}
/// shouldInline - Return true if the inliner should attempt to inline
/// at the given CallSite.
bool Inliner::shouldInline(CallSite CS) {
InlineCost IC = getInlineCost(CS);
float FudgeFactor = getInlineFudgeFactor(CS);
if (IC.isAlways()) {
DEBUG(errs() << " Inlining: cost=always"
<< ", Call: " << *CS.getInstruction() << "\n");
return true;
}
if (IC.isNever()) {
DEBUG(errs() << " NOT Inlining: cost=never"
<< ", Call: " << *CS.getInstruction() << "\n");
return false;
}
int Cost = IC.getValue();
int CurrentThreshold = InlineThreshold;
Function *Fn = CS.getCaller();
if (Fn && !Fn->isDeclaration() &&
Fn->hasFnAttr(Attribute::OptimizeForSize) &&
InlineThreshold != 50)
CurrentThreshold = 50;
if (Cost >= (int)(CurrentThreshold * FudgeFactor)) {
DEBUG(errs() << " NOT Inlining: cost=" << Cost
<< ", Call: " << *CS.getInstruction() << "\n");
return false;
} else {
DEBUG(errs() << " Inlining: cost=" << Cost
<< ", Call: " << *CS.getInstruction() << "\n");
return true;
}
}
bool Inliner::runOnSCC(const std::vector<CallGraphNode*> &SCC) {
CallGraph &CG = getAnalysis<CallGraph>();
const TargetData *TD = getAnalysisIfAvailable<TargetData>();
SmallPtrSet<Function*, 8> SCCFunctions;
DEBUG(errs() << "Inliner visiting SCC:");
for (unsigned i = 0, e = SCC.size(); i != e; ++i) {
Function *F = SCC[i]->getFunction();
if (F) SCCFunctions.insert(F);
DEBUG(errs() << " " << (F ? F->getName() : "INDIRECTNODE"));
}
// Scan through and identify all call sites ahead of time so that we only
// inline call sites in the original functions, not call sites that result
// from inlining other functions.
std::vector<CallSite> CallSites;
for (unsigned i = 0, e = SCC.size(); i != e; ++i)
if (Function *F = SCC[i]->getFunction())
for (Function::iterator BB = F->begin(), E = F->end(); BB != E; ++BB)
for (BasicBlock::iterator I = BB->begin(); I != BB->end(); ++I) {
CallSite CS = CallSite::get(I);
if (CS.getInstruction() && !isa<DbgInfoIntrinsic>(I) &&
(!CS.getCalledFunction() ||
!CS.getCalledFunction()->isDeclaration()))
CallSites.push_back(CS);
}
DEBUG(errs() << ": " << CallSites.size() << " call sites.\n");
// Now that we have all of the call sites, move the ones to functions in the
// current SCC to the end of the list.
unsigned FirstCallInSCC = CallSites.size();
for (unsigned i = 0; i < FirstCallInSCC; ++i)
if (Function *F = CallSites[i].getCalledFunction())
if (SCCFunctions.count(F))
std::swap(CallSites[i--], CallSites[--FirstCallInSCC]);
// Now that we have all of the call sites, loop over them and inline them if
// it looks profitable to do so.
bool Changed = false;
bool LocalChange;
do {
LocalChange = false;
// Iterate over the outer loop because inlining functions can cause indirect
// calls to become direct calls.
for (unsigned CSi = 0; CSi != CallSites.size(); ++CSi)
if (Function *Callee = CallSites[CSi].getCalledFunction()) {
// Calls to external functions are never inlinable.
if (Callee->isDeclaration()) {
if (SCC.size() == 1) {
std::swap(CallSites[CSi], CallSites.back());
CallSites.pop_back();
} else {
// Keep the 'in SCC / not in SCC' boundary correct.
CallSites.erase(CallSites.begin()+CSi);
}
--CSi;
continue;
}
// If the policy determines that we should inline this function,
// try to do so.
CallSite CS = CallSites[CSi];
if (shouldInline(CS)) {
Function *Caller = CS.getCaller();
// Attempt to inline the function...
if (InlineCallIfPossible(CS, CG, SCCFunctions, TD)) {
// Remove any cached cost info for this caller, as inlining the
// callee has increased the size of the caller (which may be the
// same as the callee).
resetCachedCostInfo(Caller);
// Remove this call site from the list. If possible, use
// swap/pop_back for efficiency, but do not use it if doing so would
// move a call site to a function in this SCC before the
// 'FirstCallInSCC' barrier.
if (SCC.size() == 1) {
std::swap(CallSites[CSi], CallSites.back());
CallSites.pop_back();
} else {
CallSites.erase(CallSites.begin()+CSi);
}
--CSi;
++NumInlined;
Changed = true;
LocalChange = true;
}
}
}
} while (LocalChange);
return Changed;
}
// doFinalization - Remove now-dead linkonce functions at the end of
// processing to avoid breaking the SCC traversal.
bool Inliner::doFinalization(CallGraph &CG) {
return removeDeadFunctions(CG);
}
/// removeDeadFunctions - Remove dead functions that are not included in
/// DNR (Do Not Remove) list.
bool Inliner::removeDeadFunctions(CallGraph &CG,
SmallPtrSet<const Function *, 16> *DNR) {
std::set<CallGraphNode*> FunctionsToRemove;
// Scan for all of the functions, looking for ones that should now be removed
// from the program. Insert the dead ones in the FunctionsToRemove set.
for (CallGraph::iterator I = CG.begin(), E = CG.end(); I != E; ++I) {
CallGraphNode *CGN = I->second;
if (Function *F = CGN ? CGN->getFunction() : 0) {
// If the only remaining users of the function are dead constants, remove
// them.
F->removeDeadConstantUsers();
if (DNR && DNR->count(F))
continue;
if ((F->hasLinkOnceLinkage() || F->hasLocalLinkage()) &&
F->use_empty()) {
// Remove any call graph edges from the function to its callees.
CGN->removeAllCalledFunctions();
// Remove any edges from the external node to the function's call graph
// node. These edges might have been made irrelegant due to
// optimization of the program.
CG.getExternalCallingNode()->removeAnyCallEdgeTo(CGN);
// Removing the node for callee from the call graph and delete it.
FunctionsToRemove.insert(CGN);
}
}
}
// Now that we know which functions to delete, do so. We didn't want to do
// this inline, because that would invalidate our CallGraph::iterator
// objects. :(
bool Changed = false;
for (std::set<CallGraphNode*>::iterator I = FunctionsToRemove.begin(),
E = FunctionsToRemove.end(); I != E; ++I) {
resetCachedCostInfo((*I)->getFunction());
delete CG.removeFunctionFromModule(*I);
++NumDeleted;
Changed = true;
}
return Changed;
}
<|endoftext|> |
<commit_before>//===- ADCE.cpp - Code to perform agressive dead code elimination ---------===//
//
// This file implements "agressive" dead code elimination. ADCE is DCe where
// values are assumed to be dead until proven otherwise. This is similar to
// SCCP, except applied to the liveness of values.
//
//===----------------------------------------------------------------------===//
#include "llvm/Transforms/Scalar.h"
#include "llvm/Type.h"
#include "llvm/Analysis/Dominators.h"
#include "llvm/Analysis/Writer.h"
#include "llvm/iTerminators.h"
#include "llvm/iPHINode.h"
#include "llvm/Support/CFG.h"
#include "Support/STLExtras.h"
#include "Support/DepthFirstIterator.h"
#include <algorithm>
#include <iostream>
using std::cerr;
#define DEBUG_ADCE 1
namespace {
//===----------------------------------------------------------------------===//
// ADCE Class
//
// This class does all of the work of Agressive Dead Code Elimination.
// It's public interface consists of a constructor and a doADCE() method.
//
class ADCE : public FunctionPass {
Function *Func; // The function that we are working on
std::vector<Instruction*> WorkList; // Instructions that just became live
std::set<Instruction*> LiveSet; // The set of live instructions
bool MadeChanges;
//===--------------------------------------------------------------------===//
// The public interface for this class
//
public:
const char *getPassName() const { return "Aggressive Dead Code Elimination"; }
// doADCE - Execute the Agressive Dead Code Elimination Algorithm
//
virtual bool runOnFunction(Function *F) {
Func = F; MadeChanges = false;
doADCE(getAnalysis<DominanceFrontier>(DominanceFrontier::PostDomID));
assert(WorkList.empty());
LiveSet.clear();
return MadeChanges;
}
// getAnalysisUsage - We require post dominance frontiers (aka Control
// Dependence Graph)
virtual void getAnalysisUsage(AnalysisUsage &AU) const {
AU.addRequired(DominanceFrontier::PostDomID);
}
//===--------------------------------------------------------------------===//
// The implementation of this class
//
private:
// doADCE() - Run the Agressive Dead Code Elimination algorithm, returning
// true if the function was modified.
//
void doADCE(DominanceFrontier &CDG);
inline void markInstructionLive(Instruction *I) {
if (LiveSet.count(I)) return;
#ifdef DEBUG_ADCE
cerr << "Insn Live: " << I;
#endif
LiveSet.insert(I);
WorkList.push_back(I);
}
inline void markTerminatorLive(const BasicBlock *BB) {
#ifdef DEBUG_ADCE
cerr << "Terminat Live: " << BB->getTerminator();
#endif
markInstructionLive((Instruction*)BB->getTerminator());
}
// fixupCFG - Walk the CFG in depth first order, eliminating references to
// dead blocks.
//
BasicBlock *fixupCFG(BasicBlock *Head, std::set<BasicBlock*> &VisitedBlocks,
const std::set<BasicBlock*> &AliveBlocks);
};
} // End of anonymous namespace
Pass *createAgressiveDCEPass() {
return new ADCE();
}
// doADCE() - Run the Agressive Dead Code Elimination algorithm, returning
// true if the function was modified.
//
void ADCE::doADCE(DominanceFrontier &CDG) {
#ifdef DEBUG_ADCE
cerr << "Function: " << Func;
#endif
// Iterate over all of the instructions in the function, eliminating trivially
// dead instructions, and marking instructions live that are known to be
// needed. Perform the walk in depth first order so that we avoid marking any
// instructions live in basic blocks that are unreachable. These blocks will
// be eliminated later, along with the instructions inside.
//
for (df_iterator<Function*> BBI = df_begin(Func), BBE = df_end(Func);
BBI != BBE; ++BBI) {
BasicBlock *BB = *BBI;
for (BasicBlock::iterator II = BB->begin(), EI = BB->end(); II != EI; ) {
Instruction *I = *II;
if (I->hasSideEffects() || I->getOpcode() == Instruction::Ret) {
markInstructionLive(I);
} else {
// Check to see if anything is trivially dead
if (I->use_size() == 0 && I->getType() != Type::VoidTy) {
// Remove the instruction from it's basic block...
delete BB->getInstList().remove(II);
MadeChanges = true;
continue; // Don't increment the iterator past the current slot
}
}
++II; // Increment the inst iterator if the inst wasn't deleted
}
}
#ifdef DEBUG_ADCE
cerr << "Processing work list\n";
#endif
// AliveBlocks - Set of basic blocks that we know have instructions that are
// alive in them...
//
std::set<BasicBlock*> AliveBlocks;
// Process the work list of instructions that just became live... if they
// became live, then that means that all of their operands are neccesary as
// well... make them live as well.
//
while (!WorkList.empty()) {
Instruction *I = WorkList.back(); // Get an instruction that became live...
WorkList.pop_back();
BasicBlock *BB = I->getParent();
if (AliveBlocks.count(BB) == 0) { // Basic block not alive yet...
// Mark the basic block as being newly ALIVE... and mark all branches that
// this block is control dependant on as being alive also...
//
AliveBlocks.insert(BB); // Block is now ALIVE!
DominanceFrontier::const_iterator It = CDG.find(BB);
if (It != CDG.end()) {
// Get the blocks that this node is control dependant on...
const DominanceFrontier::DomSetType &CDB = It->second;
for_each(CDB.begin(), CDB.end(), // Mark all their terminators as live
bind_obj(this, &ADCE::markTerminatorLive));
}
// If this basic block is live, then the terminator must be as well!
markTerminatorLive(BB);
}
// Loop over all of the operands of the live instruction, making sure that
// they are known to be alive as well...
//
for (unsigned op = 0, End = I->getNumOperands(); op != End; ++op) {
if (Instruction *Operand = dyn_cast<Instruction>(I->getOperand(op)))
markInstructionLive(Operand);
}
}
#ifdef DEBUG_ADCE
cerr << "Current Function: X = Live\n";
for (Function::iterator I = Func->begin(), E = Func->end(); I != E; ++I)
for (BasicBlock::iterator BI = (*I)->begin(), BE = (*I)->end();
BI != BE; ++BI) {
if (LiveSet.count(*BI)) cerr << "X ";
cerr << *BI;
}
#endif
// After the worklist is processed, recursively walk the CFG in depth first
// order, patching up references to dead blocks...
//
std::set<BasicBlock*> VisitedBlocks;
BasicBlock *EntryBlock = fixupCFG(Func->front(), VisitedBlocks, AliveBlocks);
if (EntryBlock && EntryBlock != Func->front()) {
if (isa<PHINode>(EntryBlock->front())) {
// Cannot make the first block be a block with a PHI node in it! Instead,
// strip the first basic block of the function to contain no instructions,
// then add a simple branch to the "real" entry node...
//
BasicBlock *E = Func->front();
if (!isa<TerminatorInst>(E->front()) || // Check for an actual change...
cast<TerminatorInst>(E->front())->getNumSuccessors() != 1 ||
cast<TerminatorInst>(E->front())->getSuccessor(0) != EntryBlock) {
E->getInstList().delete_all(); // Delete all instructions in block
E->getInstList().push_back(new BranchInst(EntryBlock));
MadeChanges = true;
}
AliveBlocks.insert(E);
// Next we need to change any PHI nodes in the entry block to refer to the
// new predecessor node...
} else {
// We need to move the new entry block to be the first bb of the function
Function::iterator EBI = find(Func->begin(), Func->end(), EntryBlock);
std::swap(*EBI, *Func->begin()); // Exchange old location with start of fn
MadeChanges = true;
}
}
// Now go through and tell dead blocks to drop all of their references so they
// can be safely deleted.
//
for (Function::iterator BI = Func->begin(), BE = Func->end(); BI != BE; ++BI){
BasicBlock *BB = *BI;
if (!AliveBlocks.count(BB)) {
BB->dropAllReferences();
}
}
// Now loop through all of the blocks and delete them. We can safely do this
// now because we know that there are no references to dead blocks (because
// they have dropped all of their references...
//
for (Function::iterator BI = Func->begin(); BI != Func->end();) {
if (!AliveBlocks.count(*BI)) {
delete Func->getBasicBlocks().remove(BI);
MadeChanges = true;
continue; // Don't increment iterator
}
++BI; // Increment iterator...
}
}
// fixupCFG - Walk the CFG in depth first order, eliminating references to
// dead blocks:
// If the BB is alive (in AliveBlocks):
// 1. Eliminate all dead instructions in the BB
// 2. Recursively traverse all of the successors of the BB:
// - If the returned successor is non-null, update our terminator to
// reference the returned BB
// 3. Return 0 (no update needed)
//
// If the BB is dead (not in AliveBlocks):
// 1. Add the BB to the dead set
// 2. Recursively traverse all of the successors of the block:
// - Only one shall return a nonnull value (or else this block should have
// been in the alive set).
// 3. Return the nonnull child, or 0 if no non-null children.
//
BasicBlock *ADCE::fixupCFG(BasicBlock *BB, std::set<BasicBlock*> &VisitedBlocks,
const std::set<BasicBlock*> &AliveBlocks) {
if (VisitedBlocks.count(BB)) return 0; // Revisiting a node? No update.
VisitedBlocks.insert(BB); // We have now visited this node!
#ifdef DEBUG_ADCE
cerr << "Fixing up BB: " << BB;
#endif
if (AliveBlocks.count(BB)) { // Is the block alive?
// Yes it's alive: loop through and eliminate all dead instructions in block
for (BasicBlock::iterator II = BB->begin(); II != BB->end()-1; ) {
Instruction *I = *II;
if (!LiveSet.count(I)) { // Is this instruction alive?
// Nope... remove the instruction from it's basic block...
delete BB->getInstList().remove(II);
MadeChanges = true;
continue; // Don't increment II
}
++II;
}
// Recursively traverse successors of this basic block.
for (succ_iterator SI = succ_begin(BB), SE = succ_end(BB); SI != SE; ++SI) {
BasicBlock *Succ = *SI;
BasicBlock *Repl = fixupCFG(Succ, VisitedBlocks, AliveBlocks);
if (Repl && Repl != Succ) { // We have to replace the successor
Succ->replaceAllUsesWith(Repl);
MadeChanges = true;
}
}
return BB;
} else { // Otherwise the block is dead...
BasicBlock *ReturnBB = 0; // Default to nothing live down here
// Recursively traverse successors of this basic block.
for (succ_iterator SI = succ_begin(BB), SE = succ_end(BB); SI != SE; ++SI) {
BasicBlock *RetBB = fixupCFG(*SI, VisitedBlocks, AliveBlocks);
if (RetBB) {
assert(ReturnBB == 0 && "One one live child allowed!");
ReturnBB = RetBB;
}
}
return ReturnBB; // Return the result of traversal
}
}
<commit_msg>Fix bug: test/Regression/Transforms/ADCE/2002-01-31-UseStuckAround.ll Cleanup code a lot<commit_after>//===- ADCE.cpp - Code to perform aggressive dead code elimination --------===//
//
// This file implements "aggressive" dead code elimination. ADCE is DCe where
// values are assumed to be dead until proven otherwise. This is similar to
// SCCP, except applied to the liveness of values.
//
//===----------------------------------------------------------------------===//
#include "llvm/Transforms/Scalar.h"
#include "llvm/Transforms/Utils/Local.h"
#include "llvm/Type.h"
#include "llvm/Analysis/Dominators.h"
#include "llvm/Analysis/Writer.h"
#include "llvm/iTerminators.h"
#include "llvm/iPHINode.h"
#include "llvm/Support/CFG.h"
#include "Support/STLExtras.h"
#include "Support/DepthFirstIterator.h"
#include <algorithm>
#include <iostream>
using std::cerr;
#define DEBUG_ADCE 1
namespace {
//===----------------------------------------------------------------------===//
// ADCE Class
//
// This class does all of the work of Aggressive Dead Code Elimination.
// It's public interface consists of a constructor and a doADCE() method.
//
class ADCE : public FunctionPass {
Function *Func; // The function that we are working on
std::vector<Instruction*> WorkList; // Instructions that just became live
std::set<Instruction*> LiveSet; // The set of live instructions
bool MadeChanges;
//===--------------------------------------------------------------------===//
// The public interface for this class
//
public:
const char *getPassName() const { return "Aggressive Dead Code Elimination"; }
// doADCE - Execute the Aggressive Dead Code Elimination Algorithm
//
virtual bool runOnFunction(Function *F) {
Func = F; MadeChanges = false;
doADCE(getAnalysis<DominanceFrontier>(DominanceFrontier::PostDomID));
assert(WorkList.empty());
LiveSet.clear();
return MadeChanges;
}
// getAnalysisUsage - We require post dominance frontiers (aka Control
// Dependence Graph)
virtual void getAnalysisUsage(AnalysisUsage &AU) const {
AU.addRequired(DominanceFrontier::PostDomID);
}
//===--------------------------------------------------------------------===//
// The implementation of this class
//
private:
// doADCE() - Run the Aggressive Dead Code Elimination algorithm, returning
// true if the function was modified.
//
void doADCE(DominanceFrontier &CDG);
inline void markInstructionLive(Instruction *I) {
if (LiveSet.count(I)) return;
#ifdef DEBUG_ADCE
cerr << "Insn Live: " << I;
#endif
LiveSet.insert(I);
WorkList.push_back(I);
}
inline void markTerminatorLive(const BasicBlock *BB) {
#ifdef DEBUG_ADCE
cerr << "Terminat Live: " << BB->getTerminator();
#endif
markInstructionLive((Instruction*)BB->getTerminator());
}
// fixupCFG - Walk the CFG in depth first order, eliminating references to
// dead blocks.
//
BasicBlock *fixupCFG(BasicBlock *Head, std::set<BasicBlock*> &VisitedBlocks,
const std::set<BasicBlock*> &AliveBlocks);
};
} // End of anonymous namespace
Pass *createAggressiveDCEPass() {
return new ADCE();
}
// doADCE() - Run the Aggressive Dead Code Elimination algorithm, returning
// true if the function was modified.
//
void ADCE::doADCE(DominanceFrontier &CDG) {
#ifdef DEBUG_ADCE
cerr << "Function: " << Func;
#endif
// Iterate over all of the instructions in the function, eliminating trivially
// dead instructions, and marking instructions live that are known to be
// needed. Perform the walk in depth first order so that we avoid marking any
// instructions live in basic blocks that are unreachable. These blocks will
// be eliminated later, along with the instructions inside.
//
for (df_iterator<Function*> BBI = df_begin(Func), BBE = df_end(Func);
BBI != BBE; ++BBI) {
BasicBlock *BB = *BBI;
for (BasicBlock::iterator II = BB->begin(), EI = BB->end(); II != EI; ) {
Instruction *I = *II;
if (I->hasSideEffects() || I->getOpcode() == Instruction::Ret) {
markInstructionLive(I);
++II; // Increment the inst iterator if the inst wasn't deleted
} else if (isInstructionTriviallyDead(I)) {
// Remove the instruction from it's basic block...
delete BB->getInstList().remove(II);
MadeChanges = true;
} else {
++II; // Increment the inst iterator if the inst wasn't deleted
}
}
}
#ifdef DEBUG_ADCE
cerr << "Processing work list\n";
#endif
// AliveBlocks - Set of basic blocks that we know have instructions that are
// alive in them...
//
std::set<BasicBlock*> AliveBlocks;
// Process the work list of instructions that just became live... if they
// became live, then that means that all of their operands are neccesary as
// well... make them live as well.
//
while (!WorkList.empty()) {
Instruction *I = WorkList.back(); // Get an instruction that became live...
WorkList.pop_back();
BasicBlock *BB = I->getParent();
if (AliveBlocks.count(BB) == 0) { // Basic block not alive yet...
// Mark the basic block as being newly ALIVE... and mark all branches that
// this block is control dependant on as being alive also...
//
AliveBlocks.insert(BB); // Block is now ALIVE!
DominanceFrontier::const_iterator It = CDG.find(BB);
if (It != CDG.end()) {
// Get the blocks that this node is control dependant on...
const DominanceFrontier::DomSetType &CDB = It->second;
for_each(CDB.begin(), CDB.end(), // Mark all their terminators as live
bind_obj(this, &ADCE::markTerminatorLive));
}
// If this basic block is live, then the terminator must be as well!
markTerminatorLive(BB);
}
// Loop over all of the operands of the live instruction, making sure that
// they are known to be alive as well...
//
for (unsigned op = 0, End = I->getNumOperands(); op != End; ++op)
if (Instruction *Operand = dyn_cast<Instruction>(I->getOperand(op)))
markInstructionLive(Operand);
}
#ifdef DEBUG_ADCE
cerr << "Current Function: X = Live\n";
for (Function::iterator I = Func->begin(), E = Func->end(); I != E; ++I)
for (BasicBlock::iterator BI = (*I)->begin(), BE = (*I)->end();
BI != BE; ++BI) {
if (LiveSet.count(*BI)) cerr << "X ";
cerr << *BI;
}
#endif
// After the worklist is processed, recursively walk the CFG in depth first
// order, patching up references to dead blocks...
//
std::set<BasicBlock*> VisitedBlocks;
BasicBlock *EntryBlock = fixupCFG(Func->front(), VisitedBlocks, AliveBlocks);
if (EntryBlock && EntryBlock != Func->front()) {
// We need to move the new entry block to be the first bb of the function
Function::iterator EBI = find(Func->begin(), Func->end(), EntryBlock);
std::swap(*EBI, *Func->begin()); // Exchange old location with start of fn
while (PHINode *PN = dyn_cast<PHINode>(EntryBlock->front())) {
assert(PN->getNumIncomingValues() == 1 &&
"Can only have a single incoming value at this point...");
// The incoming value must be outside of the scope of the function, a
// global variable, constant or parameter maybe...
//
PN->replaceAllUsesWith(PN->getIncomingValue(0));
// Nuke the phi node...
delete EntryBlock->getInstList().remove(EntryBlock->begin());
}
}
// Now go through and tell dead blocks to drop all of their references so they
// can be safely deleted.
//
for (Function::iterator BI = Func->begin(), BE = Func->end(); BI != BE; ++BI){
BasicBlock *BB = *BI;
if (!AliveBlocks.count(BB)) {
BB->dropAllReferences();
}
}
// Now loop through all of the blocks and delete them. We can safely do this
// now because we know that there are no references to dead blocks (because
// they have dropped all of their references...
//
for (Function::iterator BI = Func->begin(); BI != Func->end();) {
if (!AliveBlocks.count(*BI)) {
delete Func->getBasicBlocks().remove(BI);
MadeChanges = true;
continue; // Don't increment iterator
}
++BI; // Increment iterator...
}
}
// fixupCFG - Walk the CFG in depth first order, eliminating references to
// dead blocks:
// If the BB is alive (in AliveBlocks):
// 1. Eliminate all dead instructions in the BB
// 2. Recursively traverse all of the successors of the BB:
// - If the returned successor is non-null, update our terminator to
// reference the returned BB
// 3. Return 0 (no update needed)
//
// If the BB is dead (not in AliveBlocks):
// 1. Add the BB to the dead set
// 2. Recursively traverse all of the successors of the block:
// - Only one shall return a nonnull value (or else this block should have
// been in the alive set).
// 3. Return the nonnull child, or 0 if no non-null children.
//
BasicBlock *ADCE::fixupCFG(BasicBlock *BB, std::set<BasicBlock*> &VisitedBlocks,
const std::set<BasicBlock*> &AliveBlocks) {
if (VisitedBlocks.count(BB)) return 0; // Revisiting a node? No update.
VisitedBlocks.insert(BB); // We have now visited this node!
#ifdef DEBUG_ADCE
cerr << "Fixing up BB: " << BB;
#endif
if (AliveBlocks.count(BB)) { // Is the block alive?
// Yes it's alive: loop through and eliminate all dead instructions in block
for (BasicBlock::iterator II = BB->begin(); II != BB->end()-1; )
if (!LiveSet.count(*II)) { // Is this instruction alive?
// Nope... remove the instruction from it's basic block...
delete BB->getInstList().remove(II);
MadeChanges = true;
} else {
++II;
}
// Recursively traverse successors of this basic block.
for (succ_iterator SI = succ_begin(BB), SE = succ_end(BB); SI != SE; ++SI) {
BasicBlock *Succ = *SI;
BasicBlock *Repl = fixupCFG(Succ, VisitedBlocks, AliveBlocks);
if (Repl && Repl != Succ) { // We have to replace the successor
Succ->replaceAllUsesWith(Repl);
MadeChanges = true;
}
}
return BB;
} else { // Otherwise the block is dead...
BasicBlock *ReturnBB = 0; // Default to nothing live down here
// Recursively traverse successors of this basic block.
for (succ_iterator SI = succ_begin(BB), SE = succ_end(BB); SI != SE; ++SI) {
BasicBlock *RetBB = fixupCFG(*SI, VisitedBlocks, AliveBlocks);
if (RetBB) {
assert(ReturnBB == 0 && "One one live child allowed!");
ReturnBB = RetBB;
}
}
return ReturnBB; // Return the result of traversal
}
}
<|endoftext|> |
<commit_before>//===-- GCSE.cpp - SSA based Global Common Subexpr Elimination ------------===//
//
// This pass is designed to be a very quick global transformation that
// eliminates global common subexpressions from a function. It does this by
// using an existing value numbering implementation to identify the common
// subexpressions, eliminating them when possible.
//
//===----------------------------------------------------------------------===//
#include "llvm/Transforms/Scalar.h"
#include "llvm/iMemory.h"
#include "llvm/Type.h"
#include "llvm/Analysis/Dominators.h"
#include "llvm/Analysis/ValueNumbering.h"
#include "llvm/Support/InstIterator.h"
#include "Support/Statistic.h"
#include <algorithm>
namespace {
Statistic<> NumInstRemoved("gcse", "Number of instructions removed");
Statistic<> NumLoadRemoved("gcse", "Number of loads removed");
Statistic<> NumNonInsts ("gcse", "Number of instructions removed due "
"to non-instruction values");
class GCSE : public FunctionPass {
std::set<Instruction*> WorkList;
DominatorSet *DomSetInfo;
#if 0
ImmediateDominators *ImmDominator;
#endif
ValueNumbering *VN;
public:
virtual bool runOnFunction(Function &F);
private:
bool EliminateRedundancies(Instruction *I,std::vector<Value*> &EqualValues);
Instruction *EliminateCSE(Instruction *I, Instruction *Other);
void ReplaceInstWithInst(Instruction *First, BasicBlock::iterator SI);
// This transformation requires dominator and immediate dominator info
virtual void getAnalysisUsage(AnalysisUsage &AU) const {
AU.setPreservesCFG();
AU.addRequired<DominatorSet>();
AU.addRequired<ImmediateDominators>();
AU.addRequired<ValueNumbering>();
}
};
RegisterOpt<GCSE> X("gcse", "Global Common Subexpression Elimination");
}
// createGCSEPass - The public interface to this file...
Pass *createGCSEPass() { return new GCSE(); }
// GCSE::runOnFunction - This is the main transformation entry point for a
// function.
//
bool GCSE::runOnFunction(Function &F) {
bool Changed = false;
// Get pointers to the analysis results that we will be using...
DomSetInfo = &getAnalysis<DominatorSet>();
#if 0
ImmDominator = &getAnalysis<ImmediateDominators>();
#endif
VN = &getAnalysis<ValueNumbering>();
// Step #1: Add all instructions in the function to the worklist for
// processing. All of the instructions are considered to be our
// subexpressions to eliminate if possible.
//
WorkList.insert(inst_begin(F), inst_end(F));
// Step #2: WorkList processing. Iterate through all of the instructions,
// checking to see if there are any additionally defined subexpressions in the
// program. If so, eliminate them!
//
while (!WorkList.empty()) {
Instruction &I = **WorkList.begin(); // Get an instruction from the worklist
WorkList.erase(WorkList.begin());
// If this instruction computes a value, try to fold together common
// instructions that compute it.
//
if (I.getType() != Type::VoidTy) {
std::vector<Value*> EqualValues;
VN->getEqualNumberNodes(&I, EqualValues);
if (!EqualValues.empty())
Changed |= EliminateRedundancies(&I, EqualValues);
}
}
// When the worklist is empty, return whether or not we changed anything...
return Changed;
}
bool GCSE::EliminateRedundancies(Instruction *I,
std::vector<Value*> &EqualValues) {
// If the EqualValues set contains any non-instruction values, then we know
// that all of the instructions can be replaced with the non-instruction value
// because it is guaranteed to dominate all of the instructions in the
// function. We only have to do hard work if all we have are instructions.
//
for (unsigned i = 0, e = EqualValues.size(); i != e; ++i)
if (!isa<Instruction>(EqualValues[i])) {
// Found a non-instruction. Replace all instructions with the
// non-instruction.
//
Value *Replacement = EqualValues[i];
// Make sure we get I as well...
EqualValues[i] = I;
// Replace all instructions with the Replacement value.
for (i = 0; i != e; ++i)
if (Instruction *I = dyn_cast<Instruction>(EqualValues[i])) {
// Change all users of I to use Replacement.
I->replaceAllUsesWith(Replacement);
if (isa<LoadInst>(I))
++NumLoadRemoved; // Keep track of loads eliminated
++NumInstRemoved; // Keep track of number of instructions eliminated
++NumNonInsts; // Keep track of number of insts repl with values
// Erase the instruction from the program.
I->getParent()->getInstList().erase(I);
}
return true;
}
// Remove duplicate entries from EqualValues...
std::sort(EqualValues.begin(), EqualValues.end());
EqualValues.erase(std::unique(EqualValues.begin(), EqualValues.end()),
EqualValues.end());
// From this point on, EqualValues is logically a vector of instructions.
//
bool Changed = false;
EqualValues.push_back(I); // Make sure I is included...
while (EqualValues.size() > 1) {
// FIXME, this could be done better than simple iteration!
Instruction *Test = cast<Instruction>(EqualValues.back());
EqualValues.pop_back();
for (unsigned i = 0, e = EqualValues.size(); i != e; ++i)
if (Instruction *Ret = EliminateCSE(Test,
cast<Instruction>(EqualValues[i]))) {
if (Ret == Test) // Eliminated EqualValues[i]
EqualValues[i] = Test; // Make sure that we reprocess I at some point
Changed = true;
break;
}
}
return Changed;
}
// ReplaceInstWithInst - Destroy the instruction pointed to by SI, making all
// uses of the instruction use First now instead.
//
void GCSE::ReplaceInstWithInst(Instruction *First, BasicBlock::iterator SI) {
Instruction &Second = *SI;
//cerr << "DEL " << (void*)Second << Second;
// Add the first instruction back to the worklist
WorkList.insert(First);
// Add all uses of the second instruction to the worklist
for (Value::use_iterator UI = Second.use_begin(), UE = Second.use_end();
UI != UE; ++UI)
WorkList.insert(cast<Instruction>(*UI));
// Make all users of 'Second' now use 'First'
Second.replaceAllUsesWith(First);
// Erase the second instruction from the program
Second.getParent()->getInstList().erase(SI);
}
// EliminateCSE - The two instruction I & Other have been found to be common
// subexpressions. This function is responsible for eliminating one of them,
// and for fixing the worklist to be correct. The instruction that is preserved
// is returned from the function if the other is eliminated, otherwise null is
// returned.
//
Instruction *GCSE::EliminateCSE(Instruction *I, Instruction *Other) {
assert(I != Other);
WorkList.erase(I);
WorkList.erase(Other); // Other may not actually be on the worklist anymore...
// Handle the easy case, where both instructions are in the same basic block
BasicBlock *BB1 = I->getParent(), *BB2 = Other->getParent();
Instruction *Ret = 0;
if (BB1 == BB2) {
// Eliminate the second occuring instruction. Add all uses of the second
// instruction to the worklist.
//
// Scan the basic block looking for the "first" instruction
BasicBlock::iterator BI = BB1->begin();
while (&*BI != I && &*BI != Other) {
++BI;
assert(BI != BB1->end() && "Instructions not found in parent BB!");
}
// Keep track of which instructions occurred first & second
Instruction *First = BI;
Instruction *Second = I != First ? I : Other; // Get iterator to second inst
BI = Second;
// Destroy Second, using First instead.
ReplaceInstWithInst(First, BI);
Ret = First;
// Otherwise, the two instructions are in different basic blocks. If one
// dominates the other instruction, we can simply use it
//
} else if (DomSetInfo->dominates(BB1, BB2)) { // I dom Other?
ReplaceInstWithInst(I, Other);
Ret = I;
} else if (DomSetInfo->dominates(BB2, BB1)) { // Other dom I?
ReplaceInstWithInst(Other, I);
Ret = Other;
} else {
// This code is disabled because it has several problems:
// One, the actual assumption is wrong, as shown by this code:
// int "test"(int %X, int %Y) {
// %Z = add int %X, %Y
// ret int %Z
// Unreachable:
// %Q = add int %X, %Y
// ret int %Q
// }
//
// Here there are no shared dominators. Additionally, this had the habit of
// moving computations where they were not always computed. For example, in
// a cast like this:
// if (c) {
// if (d) ...
// else ... X+Y ...
// } else {
// ... X+Y ...
// }
//
// In thiscase, the expression would be hoisted to outside the 'if' stmt,
// causing the expression to be evaluated, even for the if (d) path, which
// could cause problems, if, for example, it caused a divide by zero. In
// general the problem this case is trying to solve is better addressed with
// PRE than GCSE.
//
return 0;
#if 0
// Handle the most general case now. In this case, neither I dom Other nor
// Other dom I. Because we are in SSA form, we are guaranteed that the
// operands of the two instructions both dominate the uses, so we _know_
// that there must exist a block that dominates both instructions (if the
// operands of the instructions are globals or constants, worst case we
// would get the entry node of the function). Search for this block now.
//
// Search up the immediate dominator chain of BB1 for the shared dominator
BasicBlock *SharedDom = (*ImmDominator)[BB1];
while (!DomSetInfo->dominates(SharedDom, BB2))
SharedDom = (*ImmDominator)[SharedDom];
// At this point, shared dom must dominate BOTH BB1 and BB2...
assert(SharedDom && DomSetInfo->dominates(SharedDom, BB1) &&
DomSetInfo->dominates(SharedDom, BB2) && "Dominators broken!");
// Rip 'I' out of BB1, and move it to the end of SharedDom.
BB1->getInstList().remove(I);
SharedDom->getInstList().insert(--SharedDom->end(), I);
// Eliminate 'Other' now.
ReplaceInstWithInst(I, Other);
#endif
}
if (isa<LoadInst>(Ret))
++NumLoadRemoved; // Keep track of loads eliminated
++NumInstRemoved; // Keep track of number of instructions eliminated
// Add all users of Ret to the worklist...
for (Value::use_iterator I = Ret->use_begin(), E = Ret->use_end(); I != E;++I)
if (Instruction *Inst = dyn_cast<Instruction>(*I))
WorkList.insert(Inst);
return Ret;
}
<commit_msg>Remove dead code<commit_after>//===-- GCSE.cpp - SSA based Global Common Subexpr Elimination ------------===//
//
// This pass is designed to be a very quick global transformation that
// eliminates global common subexpressions from a function. It does this by
// using an existing value numbering implementation to identify the common
// subexpressions, eliminating them when possible.
//
//===----------------------------------------------------------------------===//
#include "llvm/Transforms/Scalar.h"
#include "llvm/iMemory.h"
#include "llvm/Type.h"
#include "llvm/Analysis/Dominators.h"
#include "llvm/Analysis/ValueNumbering.h"
#include "llvm/Support/InstIterator.h"
#include "Support/Statistic.h"
#include <algorithm>
namespace {
Statistic<> NumInstRemoved("gcse", "Number of instructions removed");
Statistic<> NumLoadRemoved("gcse", "Number of loads removed");
Statistic<> NumNonInsts ("gcse", "Number of instructions removed due "
"to non-instruction values");
class GCSE : public FunctionPass {
std::set<Instruction*> WorkList;
DominatorSet *DomSetInfo;
ValueNumbering *VN;
public:
virtual bool runOnFunction(Function &F);
private:
bool EliminateRedundancies(Instruction *I,std::vector<Value*> &EqualValues);
Instruction *EliminateCSE(Instruction *I, Instruction *Other);
void ReplaceInstWithInst(Instruction *First, BasicBlock::iterator SI);
// This transformation requires dominator and immediate dominator info
virtual void getAnalysisUsage(AnalysisUsage &AU) const {
AU.setPreservesCFG();
AU.addRequired<DominatorSet>();
AU.addRequired<ImmediateDominators>();
AU.addRequired<ValueNumbering>();
}
};
RegisterOpt<GCSE> X("gcse", "Global Common Subexpression Elimination");
}
// createGCSEPass - The public interface to this file...
Pass *createGCSEPass() { return new GCSE(); }
// GCSE::runOnFunction - This is the main transformation entry point for a
// function.
//
bool GCSE::runOnFunction(Function &F) {
bool Changed = false;
// Get pointers to the analysis results that we will be using...
DomSetInfo = &getAnalysis<DominatorSet>();
VN = &getAnalysis<ValueNumbering>();
// Step #1: Add all instructions in the function to the worklist for
// processing. All of the instructions are considered to be our
// subexpressions to eliminate if possible.
//
WorkList.insert(inst_begin(F), inst_end(F));
// Step #2: WorkList processing. Iterate through all of the instructions,
// checking to see if there are any additionally defined subexpressions in the
// program. If so, eliminate them!
//
while (!WorkList.empty()) {
Instruction &I = **WorkList.begin(); // Get an instruction from the worklist
WorkList.erase(WorkList.begin());
// If this instruction computes a value, try to fold together common
// instructions that compute it.
//
if (I.getType() != Type::VoidTy) {
std::vector<Value*> EqualValues;
VN->getEqualNumberNodes(&I, EqualValues);
if (!EqualValues.empty())
Changed |= EliminateRedundancies(&I, EqualValues);
}
}
// When the worklist is empty, return whether or not we changed anything...
return Changed;
}
bool GCSE::EliminateRedundancies(Instruction *I,
std::vector<Value*> &EqualValues) {
// If the EqualValues set contains any non-instruction values, then we know
// that all of the instructions can be replaced with the non-instruction value
// because it is guaranteed to dominate all of the instructions in the
// function. We only have to do hard work if all we have are instructions.
//
for (unsigned i = 0, e = EqualValues.size(); i != e; ++i)
if (!isa<Instruction>(EqualValues[i])) {
// Found a non-instruction. Replace all instructions with the
// non-instruction.
//
Value *Replacement = EqualValues[i];
// Make sure we get I as well...
EqualValues[i] = I;
// Replace all instructions with the Replacement value.
for (i = 0; i != e; ++i)
if (Instruction *I = dyn_cast<Instruction>(EqualValues[i])) {
// Change all users of I to use Replacement.
I->replaceAllUsesWith(Replacement);
if (isa<LoadInst>(I))
++NumLoadRemoved; // Keep track of loads eliminated
++NumInstRemoved; // Keep track of number of instructions eliminated
++NumNonInsts; // Keep track of number of insts repl with values
// Erase the instruction from the program.
I->getParent()->getInstList().erase(I);
}
return true;
}
// Remove duplicate entries from EqualValues...
std::sort(EqualValues.begin(), EqualValues.end());
EqualValues.erase(std::unique(EqualValues.begin(), EqualValues.end()),
EqualValues.end());
// From this point on, EqualValues is logically a vector of instructions.
//
bool Changed = false;
EqualValues.push_back(I); // Make sure I is included...
while (EqualValues.size() > 1) {
// FIXME, this could be done better than simple iteration!
Instruction *Test = cast<Instruction>(EqualValues.back());
EqualValues.pop_back();
for (unsigned i = 0, e = EqualValues.size(); i != e; ++i)
if (Instruction *Ret = EliminateCSE(Test,
cast<Instruction>(EqualValues[i]))) {
if (Ret == Test) // Eliminated EqualValues[i]
EqualValues[i] = Test; // Make sure that we reprocess I at some point
Changed = true;
break;
}
}
return Changed;
}
// ReplaceInstWithInst - Destroy the instruction pointed to by SI, making all
// uses of the instruction use First now instead.
//
void GCSE::ReplaceInstWithInst(Instruction *First, BasicBlock::iterator SI) {
Instruction &Second = *SI;
//cerr << "DEL " << (void*)Second << Second;
// Add the first instruction back to the worklist
WorkList.insert(First);
// Add all uses of the second instruction to the worklist
for (Value::use_iterator UI = Second.use_begin(), UE = Second.use_end();
UI != UE; ++UI)
WorkList.insert(cast<Instruction>(*UI));
// Make all users of 'Second' now use 'First'
Second.replaceAllUsesWith(First);
// Erase the second instruction from the program
Second.getParent()->getInstList().erase(SI);
}
// EliminateCSE - The two instruction I & Other have been found to be common
// subexpressions. This function is responsible for eliminating one of them,
// and for fixing the worklist to be correct. The instruction that is preserved
// is returned from the function if the other is eliminated, otherwise null is
// returned.
//
Instruction *GCSE::EliminateCSE(Instruction *I, Instruction *Other) {
assert(I != Other);
WorkList.erase(I);
WorkList.erase(Other); // Other may not actually be on the worklist anymore...
// Handle the easy case, where both instructions are in the same basic block
BasicBlock *BB1 = I->getParent(), *BB2 = Other->getParent();
Instruction *Ret = 0;
if (BB1 == BB2) {
// Eliminate the second occuring instruction. Add all uses of the second
// instruction to the worklist.
//
// Scan the basic block looking for the "first" instruction
BasicBlock::iterator BI = BB1->begin();
while (&*BI != I && &*BI != Other) {
++BI;
assert(BI != BB1->end() && "Instructions not found in parent BB!");
}
// Keep track of which instructions occurred first & second
Instruction *First = BI;
Instruction *Second = I != First ? I : Other; // Get iterator to second inst
BI = Second;
// Destroy Second, using First instead.
ReplaceInstWithInst(First, BI);
Ret = First;
// Otherwise, the two instructions are in different basic blocks. If one
// dominates the other instruction, we can simply use it
//
} else if (DomSetInfo->dominates(BB1, BB2)) { // I dom Other?
ReplaceInstWithInst(I, Other);
Ret = I;
} else if (DomSetInfo->dominates(BB2, BB1)) { // Other dom I?
ReplaceInstWithInst(Other, I);
Ret = Other;
} else {
// This code is disabled because it has several problems:
// One, the actual assumption is wrong, as shown by this code:
// int "test"(int %X, int %Y) {
// %Z = add int %X, %Y
// ret int %Z
// Unreachable:
// %Q = add int %X, %Y
// ret int %Q
// }
//
// Here there are no shared dominators. Additionally, this had the habit of
// moving computations where they were not always computed. For example, in
// a cast like this:
// if (c) {
// if (d) ...
// else ... X+Y ...
// } else {
// ... X+Y ...
// }
//
// In thiscase, the expression would be hoisted to outside the 'if' stmt,
// causing the expression to be evaluated, even for the if (d) path, which
// could cause problems, if, for example, it caused a divide by zero. In
// general the problem this case is trying to solve is better addressed with
// PRE than GCSE.
//
return 0;
}
if (isa<LoadInst>(Ret))
++NumLoadRemoved; // Keep track of loads eliminated
++NumInstRemoved; // Keep track of number of instructions eliminated
// Add all users of Ret to the worklist...
for (Value::use_iterator I = Ret->use_begin(), E = Ret->use_end(); I != E;++I)
if (Instruction *Inst = dyn_cast<Instruction>(*I))
WorkList.insert(Inst);
return Ret;
}
<|endoftext|> |
<commit_before>#include "MethodResult.h"
#include "common/RhodesApp.h"
#include "common/StringConverter.h"
#include "rubyext/WebView.h"
#include "MethodResultConvertor.h"
#include "RubyResultConvertor.h"
#include "JSONResultConvertor.h"
namespace rho
{
namespace apiGenerator
{
using namespace rho::json;
using namespace rho::common;
IMPLEMENT_LOGCLASS(CMethodResult, "MethodResult");
rho::String CMethodResult::toJSON()
{
rho::String strRes = CMethodResultConvertor().toJSON(*this);
return strRes;
}
rho::String CMethodResult::toString()
{
if ( m_ResType == eString)
return m_strRes;
else if ( m_ResType == eJSON)
return m_strJSONRes;
else if ( m_ResType == eBool)
return convertToStringA(m_bRes?1:0);
else if ( m_ResType == eInt)
return convertToStringA(m_nRes);
else if ( m_ResType == eDouble)
return convertToStringA(m_dRes);
return rho::String();
}
VALUE CMethodResult::toRuby(bool bForCallback/* = false*/)
{
VALUE valRes = CMethodResultConvertor().toRuby(*this, bForCallback);
return valRes;
}
bool CMethodResult::hasCallback()
{
return m_strRubyCallback.length() != 0 || m_pRubyCallbackProc || m_strJSCallback.length() != 0;
}
bool CMethodResult::isEqualCallback(CMethodResult& oResult)
{
if (!hasCallback())
return hasCallback() == oResult.hasCallback();
if ( m_strRubyCallback.length() != 0 )
return m_strRubyCallback == oResult.m_strRubyCallback;
if ( m_pRubyCallbackProc )
return m_pRubyCallbackProc == oResult.m_pRubyCallbackProc;
return m_strJSCallback == oResult.m_strJSCallback;
}
void CMethodResult::callCallback()
{
if ( m_bCollectionMode )
return;
if ( m_ResType != eNone && m_strRubyCallback.length() != 0 )
{
rho::String strResBody = RHODESAPP().addCallbackObject( new CRubyCallbackResult<CMethodResult>(*this), "__rho_inline");
RHODESAPP().callCallbackWithData( m_strRubyCallback, strResBody, m_strCallbackParam, true);
m_ResType = eNone;
}else if ( m_ResType != eNone && m_pRubyCallbackProc)
{
VALUE oProc = m_pRubyCallbackProc->getValue();
rho::String strResBody = RHODESAPP().addCallbackObject( new CRubyCallbackResult<CMethodResult>(*this), "__rho_inline");
RHODESAPP().callCallbackProcWithData( oProc, strResBody, m_strCallbackParam, true);
m_ResType = eNone;
}else if ( m_ResType != eNone && m_strJSCallback.length() != 0 )
{
String strRes(CMethodResultConvertor().toJSON(*this));
String strCallback("Rho.callbackHandler( \"");
strCallback += m_strJSCallback;
strCallback += "\", {";
strCallback += strRes;
strCallback += "})";
rho_webview_execute_js(strCallback.c_str(), m_iTabId);
m_ResType = eNone;
}
}
CMethodResult::CMethodRubyValue::CMethodRubyValue(unsigned long val) : m_value(val)
{
rho_ruby_holdValue(m_value);
}
CMethodResult::CMethodRubyValue::~CMethodRubyValue()
{
rho_ruby_releaseValue(m_value);
}
void CMethodResult::setRubyCallbackProc(unsigned long oRubyCallbackProc)
{
LOG(TRACE) + "setRubyCallbackProc";
m_pRubyCallbackProc = new CMethodRubyValue(oRubyCallbackProc);
}
void CMethodResult::setJSCallback(const rho::String& strCallback)
{
LOG(TRACE) + "setJSCallback: " + strCallback;
m_strJSCallback = strCallback;
m_iTabId = rho_webview_active_tab();
}
}
}
<commit_msg>apigen:c++: fix issue with getProperties<commit_after>#include "MethodResult.h"
#include "common/RhodesApp.h"
#include "common/StringConverter.h"
#include "rubyext/WebView.h"
#include "MethodResultConvertor.h"
#include "RubyResultConvertor.h"
#include "JSONResultConvertor.h"
namespace rho
{
namespace apiGenerator
{
using namespace rho::json;
using namespace rho::common;
IMPLEMENT_LOGCLASS(CMethodResult, "MethodResult");
rho::String CMethodResult::toJSON()
{
rho::String strRes = CMethodResultConvertor().toJSON(*this);
return strRes;
}
rho::String CMethodResult::toString()
{
if ( m_ResType == eString)
return m_strRes;
if ( m_ResType == eStringW)
return convertToStringA(m_strResW);
else if ( m_ResType == eJSON)
return m_strJSONRes;
else if ( m_ResType == eBool)
return convertToStringA(m_bRes?1:0);
else if ( m_ResType == eInt)
return convertToStringA(m_nRes);
else if ( m_ResType == eDouble)
return convertToStringA(m_dRes);
return rho::String();
}
VALUE CMethodResult::toRuby(bool bForCallback/* = false*/)
{
VALUE valRes = CMethodResultConvertor().toRuby(*this, bForCallback);
return valRes;
}
bool CMethodResult::hasCallback()
{
return m_strRubyCallback.length() != 0 || m_pRubyCallbackProc || m_strJSCallback.length() != 0;
}
bool CMethodResult::isEqualCallback(CMethodResult& oResult)
{
if (!hasCallback())
return hasCallback() == oResult.hasCallback();
if ( m_strRubyCallback.length() != 0 )
return m_strRubyCallback == oResult.m_strRubyCallback;
if ( m_pRubyCallbackProc )
return m_pRubyCallbackProc == oResult.m_pRubyCallbackProc;
return m_strJSCallback == oResult.m_strJSCallback;
}
void CMethodResult::callCallback()
{
if ( m_bCollectionMode )
return;
if ( m_ResType != eNone && m_strRubyCallback.length() != 0 )
{
rho::String strResBody = RHODESAPP().addCallbackObject( new CRubyCallbackResult<CMethodResult>(*this), "__rho_inline");
RHODESAPP().callCallbackWithData( m_strRubyCallback, strResBody, m_strCallbackParam, true);
m_ResType = eNone;
}else if ( m_ResType != eNone && m_pRubyCallbackProc)
{
VALUE oProc = m_pRubyCallbackProc->getValue();
rho::String strResBody = RHODESAPP().addCallbackObject( new CRubyCallbackResult<CMethodResult>(*this), "__rho_inline");
RHODESAPP().callCallbackProcWithData( oProc, strResBody, m_strCallbackParam, true);
m_ResType = eNone;
}else if ( m_ResType != eNone && m_strJSCallback.length() != 0 )
{
String strRes(CMethodResultConvertor().toJSON(*this));
String strCallback("Rho.callbackHandler( \"");
strCallback += m_strJSCallback;
strCallback += "\", {";
strCallback += strRes;
strCallback += "})";
rho_webview_execute_js(strCallback.c_str(), m_iTabId);
m_ResType = eNone;
}
}
CMethodResult::CMethodRubyValue::CMethodRubyValue(unsigned long val) : m_value(val)
{
rho_ruby_holdValue(m_value);
}
CMethodResult::CMethodRubyValue::~CMethodRubyValue()
{
rho_ruby_releaseValue(m_value);
}
void CMethodResult::setRubyCallbackProc(unsigned long oRubyCallbackProc)
{
LOG(TRACE) + "setRubyCallbackProc";
m_pRubyCallbackProc = new CMethodRubyValue(oRubyCallbackProc);
}
void CMethodResult::setJSCallback(const rho::String& strCallback)
{
LOG(TRACE) + "setJSCallback: " + strCallback;
m_strJSCallback = strCallback;
m_iTabId = rho_webview_active_tab();
}
}
}
<|endoftext|> |
<commit_before>//===- FDRRecordProducer.cpp - XRay FDR Mode Record Producer --------------===//
//
// The LLVM Compiler Infrastructure
//
// This file is distributed under the University of Illinois Open Source
// License. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//
#include "llvm/XRay/FDRRecords.h"
namespace llvm {
namespace xray {
Error RecordInitializer::visit(BufferExtents &R) {
if (!E.isValidOffsetForDataOfSize(OffsetPtr, sizeof(uint64_t)))
return createStringError(std::make_error_code(std::errc::bad_address),
"Invalid offset for a buffer extent (%d).",
OffsetPtr);
auto PreReadOffset = OffsetPtr;
R.Size = E.getU64(&OffsetPtr);
if (PreReadOffset == OffsetPtr)
return createStringError(std::make_error_code(std::errc::bad_message),
"Cannot read buffer extent at offset %d.",
OffsetPtr);
OffsetPtr += MetadataRecord::kMetadataBodySize - (OffsetPtr - PreReadOffset);
return Error::success();
}
Error RecordInitializer::visit(WallclockRecord &R) {
if (!E.isValidOffsetForDataOfSize(OffsetPtr,
MetadataRecord::kMetadataBodySize))
return createStringError(std::make_error_code(std::errc::bad_address),
"Invalid offset for a wallclock record (%d).",
OffsetPtr);
auto BeginOffset = OffsetPtr;
auto PreReadOffset = OffsetPtr;
R.Seconds = E.getU64(&OffsetPtr);
if (OffsetPtr == PreReadOffset)
return createStringError(
std::make_error_code(std::errc::bad_message),
"Cannot read wall clock 'seconds' field at offset %d.", OffsetPtr);
PreReadOffset = OffsetPtr;
R.Nanos = E.getU32(&OffsetPtr);
if (OffsetPtr == PreReadOffset)
return createStringError(
std::make_error_code(std::errc::bad_message),
"Cannot read wall clock 'nanos' field at offset %d.", OffsetPtr);
// Align to metadata record size boundary.
assert(OffsetPtr - BeginOffset <= MetadataRecord::kMetadataBodySize);
OffsetPtr += MetadataRecord::kMetadataBodySize - (OffsetPtr - BeginOffset);
return Error::success();
}
Error RecordInitializer::visit(NewCPUIDRecord &R) {
if (!E.isValidOffsetForDataOfSize(OffsetPtr,
MetadataRecord::kMetadataBodySize))
return createStringError(std::make_error_code(std::errc::bad_address),
"Invalid offset for a new cpu id record (%d).",
OffsetPtr);
auto PreReadOffset = OffsetPtr;
R.CPUId = E.getU16(&OffsetPtr);
if (OffsetPtr == PreReadOffset)
return createStringError(std::make_error_code(std::errc::bad_message),
"Cannot read CPU id at offset %d.", OffsetPtr);
OffsetPtr += MetadataRecord::kMetadataBodySize - (OffsetPtr - PreReadOffset);
return Error::success();
}
Error RecordInitializer::visit(TSCWrapRecord &R) {
if (!E.isValidOffsetForDataOfSize(OffsetPtr,
MetadataRecord::kMetadataBodySize))
return createStringError(std::make_error_code(std::errc::bad_address),
"Invalid offset for a new TSC wrap record (%d).",
OffsetPtr);
auto PreReadOffset = OffsetPtr;
R.BaseTSC = E.getU64(&OffsetPtr);
if (PreReadOffset == OffsetPtr)
return createStringError(std::make_error_code(std::errc::bad_message),
"Cannot read TSC wrap record at offset %d.",
OffsetPtr);
OffsetPtr += MetadataRecord::kMetadataBodySize - (OffsetPtr - PreReadOffset);
return Error::success();
}
Error RecordInitializer::visit(CustomEventRecord &R) {
if (!E.isValidOffsetForDataOfSize(OffsetPtr,
MetadataRecord::kMetadataBodySize))
return createStringError(std::make_error_code(std::errc::bad_address),
"Invalid offset for a custom event record (%d).",
OffsetPtr);
auto BeginOffset = OffsetPtr;
auto PreReadOffset = OffsetPtr;
R.Size = E.getSigned(&OffsetPtr, sizeof(int32_t));
if (PreReadOffset == OffsetPtr)
return createStringError(
std::make_error_code(std::errc::bad_message),
"Cannot read a custom event record size field offset %d.", OffsetPtr);
PreReadOffset = OffsetPtr;
R.TSC = E.getU64(&OffsetPtr);
if (PreReadOffset == OffsetPtr)
return createStringError(
std::make_error_code(std::errc::bad_message),
"Cannot read a custom event TSC field at offset %d.", OffsetPtr);
OffsetPtr += MetadataRecord::kMetadataBodySize - (OffsetPtr - BeginOffset);
// Next we read in a fixed chunk of data from the given offset.
if (!E.isValidOffsetForDataOfSize(OffsetPtr, R.Size))
return createStringError(
std::make_error_code(std::errc::bad_address),
"Cannot read %d bytes of custom event data from offset %d.", R.Size,
OffsetPtr);
std::vector<uint8_t> Buffer;
Buffer.resize(R.Size);
if (E.getU8(&OffsetPtr, Buffer.data(), R.Size) != Buffer.data())
return createStringError(
std::make_error_code(std::errc::bad_message),
"Failed reading data into buffer of size %d at offset %d.", R.Size,
OffsetPtr);
R.Data.assign(Buffer.begin(), Buffer.end());
return Error::success();
}
Error RecordInitializer::visit(CallArgRecord &R) {
if (!E.isValidOffsetForDataOfSize(OffsetPtr,
MetadataRecord::kMetadataBodySize))
return createStringError(std::make_error_code(std::errc::bad_address),
"Invalid offset for a call argument record (%d).",
OffsetPtr);
auto PreReadOffset = OffsetPtr;
R.Arg = E.getU64(&OffsetPtr);
if (PreReadOffset == OffsetPtr)
return createStringError(std::make_error_code(std::errc::bad_message),
"Cannot read a call arg record at offset %d.",
OffsetPtr);
OffsetPtr += MetadataRecord::kMetadataBodySize - (OffsetPtr - PreReadOffset);
return Error::success();
}
Error RecordInitializer::visit(PIDRecord &R) {
if (!E.isValidOffsetForDataOfSize(OffsetPtr,
MetadataRecord::kMetadataBodySize))
return createStringError(std::make_error_code(std::errc::bad_address),
"Invalid offset for a process ID record (%d).",
OffsetPtr);
auto PreReadOffset = OffsetPtr;
R.PID = E.getU64(&OffsetPtr);
if (PreReadOffset == OffsetPtr)
return createStringError(std::make_error_code(std::errc::bad_message),
"Cannot read a process ID record at offset %d.",
OffsetPtr);
OffsetPtr += MetadataRecord::kMetadataBodySize - (OffsetPtr - PreReadOffset);
return Error::success();
}
Error RecordInitializer::visit(NewBufferRecord &R) {
if (!E.isValidOffsetForDataOfSize(OffsetPtr,
MetadataRecord::kMetadataBodySize))
return createStringError(std::make_error_code(std::errc::bad_address),
"Invalid offset for a new buffer record (%d).",
OffsetPtr);
auto PreReadOffset = OffsetPtr;
R.TID = E.getSigned(&OffsetPtr, sizeof(int32_t));
if (PreReadOffset == OffsetPtr)
return createStringError(std::make_error_code(std::errc::bad_message),
"Cannot read a new buffer record at offset %d.",
OffsetPtr);
OffsetPtr += MetadataRecord::kMetadataBodySize - (OffsetPtr - PreReadOffset);
return Error::success();
}
Error RecordInitializer::visit(EndBufferRecord &R) {
if (!E.isValidOffsetForDataOfSize(OffsetPtr,
MetadataRecord::kMetadataBodySize))
return createStringError(std::make_error_code(std::errc::bad_address),
"Invalid offset for an end-of-buffer record (%d).",
OffsetPtr);
OffsetPtr += MetadataRecord::kMetadataBodySize;
return Error::success();
}
Error RecordInitializer::visit(FunctionRecord &R) {
// For function records, we need to retreat one byte back to read a full
// unsigned 32-bit value. The first four bytes will have the following
// layout:
//
// bit 0 : function record indicator (must be 0)
// bits 1..3 : function record type
// bits 4..32 : function id
//
if (OffsetPtr == 0 || !E.isValidOffsetForDataOfSize(
--OffsetPtr, FunctionRecord::kFunctionRecordSize))
return createStringError(std::make_error_code(std::errc::bad_address),
"Invalid offset for a function record (%d).",
OffsetPtr);
auto BeginOffset = OffsetPtr;
auto PreReadOffset = BeginOffset;
uint32_t Buffer = E.getU32(&OffsetPtr);
if (PreReadOffset == OffsetPtr)
return createStringError(std::make_error_code(std::errc::bad_address),
"Cannot read function id field from offset %d.",
OffsetPtr);
unsigned FunctionType = (Buffer >> 1) & 0x07;
switch (FunctionType) {
case static_cast<unsigned>(RecordTypes::ENTER):
case static_cast<unsigned>(RecordTypes::ENTER_ARG):
case static_cast<unsigned>(RecordTypes::EXIT):
case static_cast<unsigned>(RecordTypes::TAIL_EXIT):
R.Kind = static_cast<RecordTypes>(FunctionType);
break;
default:
return createStringError(std::make_error_code(std::errc::bad_message),
"Unknown function record type '%d' at offset %d.",
FunctionType, BeginOffset);
}
R.FuncId = Buffer >> 4;
PreReadOffset = OffsetPtr;
R.Delta = E.getU32(&OffsetPtr);
if (OffsetPtr == PreReadOffset)
return createStringError(std::make_error_code(std::errc::bad_message),
"Failed reading TSC delta from offset %d.",
OffsetPtr);
assert(FunctionRecord::kFunctionRecordSize == (OffsetPtr - BeginOffset));
return Error::success();
}
} // namespace xray
} // namespace llvm
<commit_msg>[XRay] Update RecordInitializer for PIDRecord<commit_after>//===- FDRRecordProducer.cpp - XRay FDR Mode Record Producer --------------===//
//
// The LLVM Compiler Infrastructure
//
// This file is distributed under the University of Illinois Open Source
// License. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//
#include "llvm/XRay/FDRRecords.h"
namespace llvm {
namespace xray {
Error RecordInitializer::visit(BufferExtents &R) {
if (!E.isValidOffsetForDataOfSize(OffsetPtr, sizeof(uint64_t)))
return createStringError(std::make_error_code(std::errc::bad_address),
"Invalid offset for a buffer extent (%d).",
OffsetPtr);
auto PreReadOffset = OffsetPtr;
R.Size = E.getU64(&OffsetPtr);
if (PreReadOffset == OffsetPtr)
return createStringError(std::make_error_code(std::errc::bad_message),
"Cannot read buffer extent at offset %d.",
OffsetPtr);
OffsetPtr += MetadataRecord::kMetadataBodySize - (OffsetPtr - PreReadOffset);
return Error::success();
}
Error RecordInitializer::visit(WallclockRecord &R) {
if (!E.isValidOffsetForDataOfSize(OffsetPtr,
MetadataRecord::kMetadataBodySize))
return createStringError(std::make_error_code(std::errc::bad_address),
"Invalid offset for a wallclock record (%d).",
OffsetPtr);
auto BeginOffset = OffsetPtr;
auto PreReadOffset = OffsetPtr;
R.Seconds = E.getU64(&OffsetPtr);
if (OffsetPtr == PreReadOffset)
return createStringError(
std::make_error_code(std::errc::bad_message),
"Cannot read wall clock 'seconds' field at offset %d.", OffsetPtr);
PreReadOffset = OffsetPtr;
R.Nanos = E.getU32(&OffsetPtr);
if (OffsetPtr == PreReadOffset)
return createStringError(
std::make_error_code(std::errc::bad_message),
"Cannot read wall clock 'nanos' field at offset %d.", OffsetPtr);
// Align to metadata record size boundary.
assert(OffsetPtr - BeginOffset <= MetadataRecord::kMetadataBodySize);
OffsetPtr += MetadataRecord::kMetadataBodySize - (OffsetPtr - BeginOffset);
return Error::success();
}
Error RecordInitializer::visit(NewCPUIDRecord &R) {
if (!E.isValidOffsetForDataOfSize(OffsetPtr,
MetadataRecord::kMetadataBodySize))
return createStringError(std::make_error_code(std::errc::bad_address),
"Invalid offset for a new cpu id record (%d).",
OffsetPtr);
auto PreReadOffset = OffsetPtr;
R.CPUId = E.getU16(&OffsetPtr);
if (OffsetPtr == PreReadOffset)
return createStringError(std::make_error_code(std::errc::bad_message),
"Cannot read CPU id at offset %d.", OffsetPtr);
OffsetPtr += MetadataRecord::kMetadataBodySize - (OffsetPtr - PreReadOffset);
return Error::success();
}
Error RecordInitializer::visit(TSCWrapRecord &R) {
if (!E.isValidOffsetForDataOfSize(OffsetPtr,
MetadataRecord::kMetadataBodySize))
return createStringError(std::make_error_code(std::errc::bad_address),
"Invalid offset for a new TSC wrap record (%d).",
OffsetPtr);
auto PreReadOffset = OffsetPtr;
R.BaseTSC = E.getU64(&OffsetPtr);
if (PreReadOffset == OffsetPtr)
return createStringError(std::make_error_code(std::errc::bad_message),
"Cannot read TSC wrap record at offset %d.",
OffsetPtr);
OffsetPtr += MetadataRecord::kMetadataBodySize - (OffsetPtr - PreReadOffset);
return Error::success();
}
Error RecordInitializer::visit(CustomEventRecord &R) {
if (!E.isValidOffsetForDataOfSize(OffsetPtr,
MetadataRecord::kMetadataBodySize))
return createStringError(std::make_error_code(std::errc::bad_address),
"Invalid offset for a custom event record (%d).",
OffsetPtr);
auto BeginOffset = OffsetPtr;
auto PreReadOffset = OffsetPtr;
R.Size = E.getSigned(&OffsetPtr, sizeof(int32_t));
if (PreReadOffset == OffsetPtr)
return createStringError(
std::make_error_code(std::errc::bad_message),
"Cannot read a custom event record size field offset %d.", OffsetPtr);
PreReadOffset = OffsetPtr;
R.TSC = E.getU64(&OffsetPtr);
if (PreReadOffset == OffsetPtr)
return createStringError(
std::make_error_code(std::errc::bad_message),
"Cannot read a custom event TSC field at offset %d.", OffsetPtr);
OffsetPtr += MetadataRecord::kMetadataBodySize - (OffsetPtr - BeginOffset);
// Next we read in a fixed chunk of data from the given offset.
if (!E.isValidOffsetForDataOfSize(OffsetPtr, R.Size))
return createStringError(
std::make_error_code(std::errc::bad_address),
"Cannot read %d bytes of custom event data from offset %d.", R.Size,
OffsetPtr);
std::vector<uint8_t> Buffer;
Buffer.resize(R.Size);
if (E.getU8(&OffsetPtr, Buffer.data(), R.Size) != Buffer.data())
return createStringError(
std::make_error_code(std::errc::bad_message),
"Failed reading data into buffer of size %d at offset %d.", R.Size,
OffsetPtr);
R.Data.assign(Buffer.begin(), Buffer.end());
return Error::success();
}
Error RecordInitializer::visit(CallArgRecord &R) {
if (!E.isValidOffsetForDataOfSize(OffsetPtr,
MetadataRecord::kMetadataBodySize))
return createStringError(std::make_error_code(std::errc::bad_address),
"Invalid offset for a call argument record (%d).",
OffsetPtr);
auto PreReadOffset = OffsetPtr;
R.Arg = E.getU64(&OffsetPtr);
if (PreReadOffset == OffsetPtr)
return createStringError(std::make_error_code(std::errc::bad_message),
"Cannot read a call arg record at offset %d.",
OffsetPtr);
OffsetPtr += MetadataRecord::kMetadataBodySize - (OffsetPtr - PreReadOffset);
return Error::success();
}
Error RecordInitializer::visit(PIDRecord &R) {
if (!E.isValidOffsetForDataOfSize(OffsetPtr,
MetadataRecord::kMetadataBodySize))
return createStringError(std::make_error_code(std::errc::bad_address),
"Invalid offset for a process ID record (%d).",
OffsetPtr);
auto PreReadOffset = OffsetPtr;
R.PID = E.getSigned(&OffsetPtr, 4);
if (PreReadOffset == OffsetPtr)
return createStringError(std::make_error_code(std::errc::bad_message),
"Cannot read a process ID record at offset %d.",
OffsetPtr);
OffsetPtr += MetadataRecord::kMetadataBodySize - (OffsetPtr - PreReadOffset);
return Error::success();
}
Error RecordInitializer::visit(NewBufferRecord &R) {
if (!E.isValidOffsetForDataOfSize(OffsetPtr,
MetadataRecord::kMetadataBodySize))
return createStringError(std::make_error_code(std::errc::bad_address),
"Invalid offset for a new buffer record (%d).",
OffsetPtr);
auto PreReadOffset = OffsetPtr;
R.TID = E.getSigned(&OffsetPtr, sizeof(int32_t));
if (PreReadOffset == OffsetPtr)
return createStringError(std::make_error_code(std::errc::bad_message),
"Cannot read a new buffer record at offset %d.",
OffsetPtr);
OffsetPtr += MetadataRecord::kMetadataBodySize - (OffsetPtr - PreReadOffset);
return Error::success();
}
Error RecordInitializer::visit(EndBufferRecord &R) {
if (!E.isValidOffsetForDataOfSize(OffsetPtr,
MetadataRecord::kMetadataBodySize))
return createStringError(std::make_error_code(std::errc::bad_address),
"Invalid offset for an end-of-buffer record (%d).",
OffsetPtr);
OffsetPtr += MetadataRecord::kMetadataBodySize;
return Error::success();
}
Error RecordInitializer::visit(FunctionRecord &R) {
// For function records, we need to retreat one byte back to read a full
// unsigned 32-bit value. The first four bytes will have the following
// layout:
//
// bit 0 : function record indicator (must be 0)
// bits 1..3 : function record type
// bits 4..32 : function id
//
if (OffsetPtr == 0 || !E.isValidOffsetForDataOfSize(
--OffsetPtr, FunctionRecord::kFunctionRecordSize))
return createStringError(std::make_error_code(std::errc::bad_address),
"Invalid offset for a function record (%d).",
OffsetPtr);
auto BeginOffset = OffsetPtr;
auto PreReadOffset = BeginOffset;
uint32_t Buffer = E.getU32(&OffsetPtr);
if (PreReadOffset == OffsetPtr)
return createStringError(std::make_error_code(std::errc::bad_address),
"Cannot read function id field from offset %d.",
OffsetPtr);
unsigned FunctionType = (Buffer >> 1) & 0x07;
switch (FunctionType) {
case static_cast<unsigned>(RecordTypes::ENTER):
case static_cast<unsigned>(RecordTypes::ENTER_ARG):
case static_cast<unsigned>(RecordTypes::EXIT):
case static_cast<unsigned>(RecordTypes::TAIL_EXIT):
R.Kind = static_cast<RecordTypes>(FunctionType);
break;
default:
return createStringError(std::make_error_code(std::errc::bad_message),
"Unknown function record type '%d' at offset %d.",
FunctionType, BeginOffset);
}
R.FuncId = Buffer >> 4;
PreReadOffset = OffsetPtr;
R.Delta = E.getU32(&OffsetPtr);
if (OffsetPtr == PreReadOffset)
return createStringError(std::make_error_code(std::errc::bad_message),
"Failed reading TSC delta from offset %d.",
OffsetPtr);
assert(FunctionRecord::kFunctionRecordSize == (OffsetPtr - BeginOffset));
return Error::success();
}
} // namespace xray
} // namespace llvm
<|endoftext|> |
<commit_before>/*
* Copyright 2012 Coherent Theory LLC
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU Library General Public License as
* published by the Free Software Foundation; either version 2, 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 Library 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 "assetoperations.h"
#include <QDebug>
#include "assethandler.h"
#include "installjob.h"
#include "installjobsmodel.h"
#include "uninstalljob.h"
namespace Bodega
{
class AssetOperations::Private {
public:
Private(AssetOperations *operations)
: q(operations),
handler(0),
wasInstalled(false),
progress(0)
{}
~Private()
{}
void assetDownloadComplete(NetworkJob *job);
bool ready();
void checkInstalled();
void progressHasChanged(qreal progress);
AssetOperations *q;
AssetHandler *handler;
AssetInfo assetInfo;
Tags assetTags;
QString mimetype;
bool wasInstalled;
qreal progress;
};
void AssetOperations::Private::assetDownloadComplete(NetworkJob *job)
{
AssetJob *assetJob = qobject_cast<AssetJob *>(job);
Q_ASSERT(assetJob);
if (!job->failed()) {
assetInfo = assetJob->info();
assetTags = assetJob->tags();
delete handler;
handler = 0;
//FIXME: may ever have more than one mimetype?
QHash<QString, QString> tags = assetJob->tags();
QHashIterator<QString, QString> it(tags);
while (it.hasNext()) {
it.next();
if (it.key() == QLatin1String("mimetype")) {
mimetype = it.value();
handler = AssetHandler::create(mimetype, q);
break;
}
}
}
if (handler) {
QObject::connect(handler, SIGNAL(ready()), q, SIGNAL(ready()));
QObject::connect(handler, SIGNAL(ready()), q, SLOT(checkInstalled()));
if (handler->isReady()) {
emit q->ready();
}
QObject::connect(handler, SIGNAL(installedChanged()), q, SIGNAL(installedChanged()));
} else {
emit q->failed();
}
checkInstalled();
}
bool AssetOperations::Private::ready()
{
return handler && handler->isReady();
}
void AssetOperations::Private::checkInstalled()
{
if (ready() && wasInstalled != handler->isInstalled()) {
wasInstalled = handler->isInstalled();
emit q->installedChanged();
}
}
void AssetOperations::Private::progressHasChanged(qreal prog)
{
progress = prog;
emit q->progressChanged(progress);
}
AssetOperations::AssetOperations(const QString &assetId, Session *session)
: QObject(session),
d(new AssetOperations::Private(this))
{
AssetJob *aj = session->asset(assetId);
QObject::connect(aj, SIGNAL(jobFinished(Bodega::NetworkJob*)),
this, SLOT(assetDownloadComplete(Bodega::NetworkJob*)));
}
AssetOperations::~AssetOperations()
{
}
const AssetInfo &AssetOperations::assetInfo() const
{
return d->assetInfo;
}
const Bodega::Tags& AssetOperations::assetTags() const
{
return d->assetTags;
}
bool AssetOperations::isReady() const
{
return d->ready();
}
QString AssetOperations::launchText() const
{
if (d->ready()) {
return d->handler->launchText();
}
return QString();
}
bool AssetOperations::isInstalled() const
{
if (d->ready()) {
return d->handler->isInstalled();
}
return false;
}
QString AssetOperations::mimetype() const
{
return d->mimetype;
}
qreal AssetOperations::progress() const
{
return d->progress;
}
Bodega::InstallJob *AssetOperations::install(QNetworkReply *reply, Session *session)
{
if (d->ready()) {
Bodega::InstallJob *job = d->handler->install(reply, session);
if (job) {
connect(job, SIGNAL(jobFinished(Bodega::NetworkJob *)), this, SLOT(checkInstalled()));
}
session->installJobsModel()->addJob(d->assetInfo, job);
connect(job, SIGNAL(progressChanged(qreal)), this, SLOT(progressHasChanged(qreal)));
return job;
}
return new InstallJob(reply, session);
}
Bodega::UninstallJob *AssetOperations::uninstall(Session *session)
{
if (d->ready()) {
Bodega::UninstallJob *job = d->handler->uninstall(session);
if (job) {
connect(job, SIGNAL(jobFinished(Bodega::UninstallJob *)), this, SLOT(checkInstalled()));
d->checkInstalled();
}
return job;
}
return 0;
}
void AssetOperations::launch()
{
if (d->ready()) {
d->handler->launch();
}
}
}
#include "assetoperations.moc"
<commit_msg>equivalent, but faster<commit_after>/*
* Copyright 2012 Coherent Theory LLC
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU Library General Public License as
* published by the Free Software Foundation; either version 2, 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 Library 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 "assetoperations.h"
#include <QDebug>
#include "assethandler.h"
#include "installjob.h"
#include "installjobsmodel.h"
#include "uninstalljob.h"
namespace Bodega
{
class AssetOperations::Private {
public:
Private(AssetOperations *operations)
: q(operations),
handler(0),
wasInstalled(false),
progress(0)
{}
~Private()
{}
void assetDownloadComplete(NetworkJob *job);
bool ready();
void checkInstalled();
void progressHasChanged(qreal progress);
AssetOperations *q;
AssetHandler *handler;
AssetInfo assetInfo;
Tags assetTags;
QString mimetype;
bool wasInstalled;
qreal progress;
};
void AssetOperations::Private::assetDownloadComplete(NetworkJob *job)
{
AssetJob *assetJob = qobject_cast<AssetJob *>(job);
Q_ASSERT(assetJob);
if (!job->failed()) {
assetInfo = assetJob->info();
assetTags = assetJob->tags();
delete handler;
handler = 0;
//FIXME: may ever have more than one mimetype?
QHash<QString, QString> tags = assetJob->tags();
const QString mimeTag(QLatin1String("mimetype"));
mimetype = tags.value(mimeTag);
if (!mimetype.isEmpty()) {
handler = AssetHandler::create(mimetype, q);
}
}
if (handler) {
QObject::connect(handler, SIGNAL(ready()), q, SIGNAL(ready()));
QObject::connect(handler, SIGNAL(ready()), q, SLOT(checkInstalled()));
if (handler->isReady()) {
emit q->ready();
}
QObject::connect(handler, SIGNAL(installedChanged()), q, SIGNAL(installedChanged()));
} else {
emit q->failed();
}
checkInstalled();
}
bool AssetOperations::Private::ready()
{
return handler && handler->isReady();
}
void AssetOperations::Private::checkInstalled()
{
if (ready() && wasInstalled != handler->isInstalled()) {
wasInstalled = handler->isInstalled();
emit q->installedChanged();
}
}
void AssetOperations::Private::progressHasChanged(qreal prog)
{
progress = prog;
emit q->progressChanged(progress);
}
AssetOperations::AssetOperations(const QString &assetId, Session *session)
: QObject(session),
d(new AssetOperations::Private(this))
{
AssetJob *aj = session->asset(assetId);
QObject::connect(aj, SIGNAL(jobFinished(Bodega::NetworkJob*)),
this, SLOT(assetDownloadComplete(Bodega::NetworkJob*)));
}
AssetOperations::~AssetOperations()
{
}
const AssetInfo &AssetOperations::assetInfo() const
{
return d->assetInfo;
}
const Bodega::Tags& AssetOperations::assetTags() const
{
return d->assetTags;
}
bool AssetOperations::isReady() const
{
return d->ready();
}
QString AssetOperations::launchText() const
{
if (d->ready()) {
return d->handler->launchText();
}
return QString();
}
bool AssetOperations::isInstalled() const
{
if (d->ready()) {
return d->handler->isInstalled();
}
return false;
}
QString AssetOperations::mimetype() const
{
return d->mimetype;
}
qreal AssetOperations::progress() const
{
return d->progress;
}
Bodega::InstallJob *AssetOperations::install(QNetworkReply *reply, Session *session)
{
if (d->ready()) {
Bodega::InstallJob *job = d->handler->install(reply, session);
if (job) {
connect(job, SIGNAL(jobFinished(Bodega::NetworkJob *)), this, SLOT(checkInstalled()));
}
session->installJobsModel()->addJob(d->assetInfo, job);
connect(job, SIGNAL(progressChanged(qreal)), this, SLOT(progressHasChanged(qreal)));
return job;
}
return new InstallJob(reply, session);
}
Bodega::UninstallJob *AssetOperations::uninstall(Session *session)
{
if (d->ready()) {
Bodega::UninstallJob *job = d->handler->uninstall(session);
if (job) {
connect(job, SIGNAL(jobFinished(Bodega::UninstallJob *)), this, SLOT(checkInstalled()));
d->checkInstalled();
}
return job;
}
return 0;
}
void AssetOperations::launch()
{
if (d->ready()) {
d->handler->launch();
}
}
}
#include "assetoperations.moc"
<|endoftext|> |
<commit_before>#include "uwhd/config/Config.h"
#include "uwhd/canvas/CanvasViewer.h"
#ifdef UWHD_BUILD_DISPLAY
#include <graphics.h>
#include <canvas.h>
#include <led-matrix.h>
#include <threaded-canvas-manipulator.h>
namespace rgb_matrix {
class RGBMatrix;
}
using namespace rgb_matrix;
class GameDisplay : public rgb_matrix::ThreadedCanvasManipulator {
public:
GameDisplay(rgb_matrix::RGBMatrix *Mtx)
: ThreadedCanvasManipulator(Mtx)
, Mtx(Mtx)
, Mgr()
, TD(1, Mgr)
{}
void Run();
/// For the SWIG bindings, which can't tell the overloads apart:
virtual void Start0() { Start(); }
virtual void Start2(int RealtimePriority, uint32_t CPUAffinityMask) {
Start(RealtimePriority, CPUAffinityMask);
}
GameModelManager &getMgr() { return Mgr; }
/// For SWIG, which doesn't do the right thing for references
/// FIXME: replace uses of the other getter with this one.
GameModelManager *getMgr2() { return &Mgr; }
private:
rgb_matrix::RGBMatrix *Mtx;
GameModelManager Mgr;
TimeDisplay TD;
public:
static const rgb_matrix::Color WhiteTeamFG;
static const rgb_matrix::Color WhiteTeamBG;
static const rgb_matrix::Color BlackTeamFG;
static const rgb_matrix::Color BlackTeamBG;
static const rgb_matrix::Color Background;
};
void GameDisplay::Run() {
FrameCanvas *Frame = Mtx->CreateFrameCanvas();
while (running()) {
GameModel M = Mgr.getModel();
renderGameDisplay(M, Canvas);
Canvas->forEach([&](unsigned X, unsigned Y) {
UWHDPixel &V = Canvas->at(X, Y);
Frame->SetPixel(X, Y, V.r, V.g, V.b);
});
Frame = Mtx->SwapOnVSync(Frame);
}
}
#endif // UWHD_BUILD_DISPLAY
UWHDCanvasViewer *createLEDCanvasViewer() {
return nullptr;
}
<commit_msg>WIP: speculative cleanup of LEDCanvasViewer... MIGHT NOT BUILD<commit_after>#include "uwhd/config/Config.h"
#include "uwhd/canvas/CanvasViewer.h"
#ifdef UWHD_BUILD_DISPLAY
#include <graphics.h>
#include <canvas.h>
#include <led-matrix.h>
#include <memory>
using namespace rgb_matrix;
class LEDCanvasViewer {
public:
LEDCanvasViewer(std::unique_ptr<RGBMatrix> Mtx)
, Mtx(std::move(Mtx))
{}
virtual void show(UWHDCanvas *C) `{
FrameCanvas *Frame = Mtx->CreateFrameCanvas();
C->forEach([&](unsigned X, unsigned Y) {
UWHDPixel &V = C->at(X, Y);
Frame->SetPixel(X, Y, V.r, V.g, V.b);
});
Frame = Mtx->SwapOnVSync(Frame);
}
private:
std::unique_ptr<RGBMatrix> Mtx;
};
#endif // UWHD_BUILD_DISPLAY
UWHDCanvasViewer *createLEDCanvasViewer() {
#ifdef UWHD_BUILD_DISPLAY
static GPIO IO;
if (!IO.Init())
return nullptr;
auto Matrix = std::unique_ptr<RGBMatrix>(new RGBMatrix(&IO, 32, 3, 1));
Matrix->SetPWMBits(11);
return new LEDCanvasViewer(std::move(Matrix));
#else
return nullptr;
#endif
}
<|endoftext|> |
<commit_before><commit_msg>plugins: oisUserInput: ignore coordinatesystem on ray intersection<commit_after><|endoftext|> |
<commit_before>#include "UASUnitTest.h"
#include <stdio.h>
#include <QObject>
UASUnitTest::UASUnitTest()
{
}
//This function is called after every test
void UASUnitTest::init()
{
mav = new MAVLinkProtocol();
uas = new UAS(mav, UASID);
uas->deleteSettings();
}
//this function is called after every test
void UASUnitTest::cleanup()
{
delete uas;
uas = NULL;
delete mav;
mav = NULL;
}
void UASUnitTest::getUASID_test()
{
// Test a default ID of zero is assigned
UAS* uas2 = new UAS(mav);
QCOMPARE(uas2->getUASID(), 0);
delete uas2;
// Test that the chosen ID was assigned at construction
QCOMPARE(uas->getUASID(), UASID);
// Make sure that no other ID was set
QEXPECT_FAIL("", "When you set an ID it does not use the default ID of 0", Continue);
QCOMPARE(uas->getUASID(), 0);
// Make sure that ID >= 0
QCOMPARE(uas->getUASID(), 100);
}
void UASUnitTest::getUASName_test()
{
// Test that the name is build as MAV + ID
QCOMPARE(uas->getUASName(), "MAV " + QString::number(UASID));
}
void UASUnitTest::getUpTime_test()
{
UAS* uas2 = new UAS(mav);
// Test that the uptime starts at zero to a
// precision of seconds
QCOMPARE(floor(uas2->getUptime()/1000.0), 0.0);
// Sleep for three seconds
QTest::qSleep(3000);
// Test that the up time is computed correctly to a
// precision of seconds
QCOMPARE(floor(uas2->getUptime()/1000.0), 3.0);
delete uas2;
}
void UASUnitTest::getCommunicationStatus_test()
{
// Verify that upon construction the Comm status is disconnected
QCOMPARE(uas->getCommunicationStatus(), static_cast<int>(UASInterface::COMM_DISCONNECTED));
}
void UASUnitTest::filterVoltage_test()
{
float verificar=uas->filterVoltage(0.4f);
// Verify that upon construction the Comm status is disconnected
QCOMPARE(verificar, 8.52f);
}
void UASUnitTest:: getAutopilotType_test()
{
int type = uas->getAutopilotType();
// Verify that upon construction the autopilot is set to -1
QCOMPARE(type, -1);
}
void UASUnitTest::setAutopilotType_test()
{
uas->setAutopilotType(2);
// Verify that the autopilot is set
QCOMPARE(uas->getAutopilotType(), 2);
}
void UASUnitTest::getStatusForCode_test()
{
QString state, desc;
state = "";
desc = "";
uas->getStatusForCode(MAV_STATE_UNINIT, state, desc);
QVERIFY(state == "UNINIT");
uas->getStatusForCode(MAV_STATE_UNINIT, state, desc);
QVERIFY(state == "UNINIT");
uas->getStatusForCode(MAV_STATE_BOOT, state, desc);
QVERIFY(state == "BOOT");
uas->getStatusForCode(MAV_STATE_CALIBRATING, state, desc);
QVERIFY(state == "CALIBRATING");
uas->getStatusForCode(MAV_STATE_ACTIVE, state, desc);
QVERIFY(state == "ACTIVE");
uas->getStatusForCode(MAV_STATE_STANDBY, state, desc);
QVERIFY(state == "STANDBY");
uas->getStatusForCode(MAV_STATE_CRITICAL, state, desc);
QVERIFY(state == "CRITICAL");
uas->getStatusForCode(MAV_STATE_EMERGENCY, state, desc);
QVERIFY(state == "EMERGENCY");
uas->getStatusForCode(MAV_STATE_POWEROFF, state, desc);
QVERIFY(state == "SHUTDOWN");
uas->getStatusForCode(5325, state, desc);
QVERIFY(state == "UNKNOWN");
}
void UASUnitTest::getLocalX_test()
{
QCOMPARE(uas->getLocalX(), 0.0);
}
void UASUnitTest::getLocalY_test()
{
QCOMPARE(uas->getLocalY(), 0.0);
}
void UASUnitTest::getLocalZ_test()
{
QCOMPARE(uas->getLocalZ(), 0.0);
}
void UASUnitTest::getLatitude_test()
{ QCOMPARE(uas->getLatitude(), 0.0);
}
void UASUnitTest::getLongitude_test()
{
QCOMPARE(uas->getLongitude(), 0.0);
}
void UASUnitTest::getAltitude_test()
{
QCOMPARE(uas->getAltitude(), 0.0);
}
void UASUnitTest::getRoll_test()
{
QCOMPARE(uas->getRoll(), 0.0);
}
void UASUnitTest::getPitch_test()
{
QCOMPARE(uas->getPitch(), 0.0);
}
void UASUnitTest::getYaw_test()
{
QCOMPARE(uas->getYaw(), 0.0);
}
void UASUnitTest::getSelected_test()
{
QCOMPARE(uas->getSelected(), false);
}
void UASUnitTest::getSystemType_test()
{ //check that system type is set to MAV_TYPE_GENERIC when initialized
QCOMPARE(uas->getSystemType(), 0);
uas->setSystemType(13);
QCOMPARE(uas->getSystemType(), 13);
}
void UASUnitTest::getAirframe_test()
{
//when uas is constructed, airframe is set to QGC_AIRFRAME_GENERIC which is 0
QCOMPARE(uas->getAirframe(), 0);
}
void UASUnitTest::setAirframe_test()
{
//check at construction, that airframe=0 (GENERIC)
QVERIFY(uas->getAirframe() == 0);
//check that set airframe works
uas->setAirframe(11);
QVERIFY(uas->getAirframe() == 11);
//check that setAirframe will not assign a number to airframe, that is
//not defined in the enum
uas->setAirframe(12);
QVERIFY(uas->getAirframe() == 11);
}
void UASUnitTest::getWaypointList_test()
{
QVector<Waypoint*> kk = uas->getWaypointManager()->getWaypointEditableList();
QCOMPARE(kk.count(), 0);
Waypoint* wp = new Waypoint(0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,false, false, MAV_FRAME_GLOBAL, MAV_CMD_MISSION_START, "blah");
uas->getWaypointManager()->addWaypointEditable(wp, true);
kk = uas->getWaypointManager()->getWaypointEditableList();
QCOMPARE(kk.count(), 1);
wp = new Waypoint();
uas->getWaypointManager()->addWaypointEditable(wp, false);
kk = uas->getWaypointManager()->getWaypointEditableList();
QCOMPARE(kk.count(), 2);
uas->getWaypointManager()->removeWaypoint(1);
kk = uas->getWaypointManager()->getWaypointEditableList();
QCOMPARE(kk.count(), 1);
uas->getWaypointManager()->removeWaypoint(0);
kk = uas->getWaypointManager()->getWaypointEditableList();
QCOMPARE(kk.count(), 0);
qDebug()<<"disconnect SIGNAL waypointListChanged";
}
void UASUnitTest::getWaypoint_test()
{
Waypoint* wp = new Waypoint(0,5.6,2.0,3.0,0.0,0.0,0.0,0.0,false, false, MAV_FRAME_GLOBAL, MAV_CMD_MISSION_START, "blah");
uas->getWaypointManager()->addWaypointEditable(wp, true);
QVector<Waypoint*> wpList = uas->getWaypointManager()->getWaypointEditableList();
QCOMPARE(wpList.count(), 1);
QCOMPARE(static_cast<quint16>(0), static_cast<Waypoint*>(wpList.at(0))->getId());
Waypoint* wp3 = new Waypoint(1, 5.6, 2.0, 3.0);
uas->getWaypointManager()->addWaypointEditable(wp3, true);
wpList = uas->getWaypointManager()->getWaypointEditableList();
Waypoint* wp2 = static_cast<Waypoint*>(wpList.at(0));
QCOMPARE(wpList.count(), 2);
QCOMPARE(wp3->getX(), wp2->getX());
QCOMPARE(wp3->getY(), wp2->getY());
QCOMPARE(wp3->getZ(), wp2->getZ());
QCOMPARE(wpList.at(1)->getId(), static_cast<quint16>(1));
QCOMPARE(wp3->getFrame(), MAV_FRAME_GLOBAL);
QCOMPARE(wp3->getFrame(), wp2->getFrame());
delete wp3;
delete wp;
}
void UASUnitTest::signalWayPoint_test()
{
QSignalSpy spy(uas->getWaypointManager(), SIGNAL(waypointEditableListChanged()));
Waypoint* wp = new Waypoint(0,1.0,0.0,0.0,0.0,0.0,0.0,0.0,false, false, MAV_FRAME_GLOBAL, MAV_CMD_MISSION_START, "blah");
uas->getWaypointManager()->addWaypointEditable(wp, true);
QCOMPARE(spy.count(), 1); // 1 listChanged for add wayPoint
uas->getWaypointManager()->removeWaypoint(0);
QCOMPARE(spy.count(), 2); // 2 listChanged for remove wayPoint
QSignalSpy spyDestroyed(uas->getWaypointManager(), SIGNAL(destroyed()));
QVERIFY(spyDestroyed.isValid());
QCOMPARE( spyDestroyed.count(), 0 );
delete uas;// delete(destroyed) uas for validating
uas = NULL;
QCOMPARE(spyDestroyed.count(), 1);// count destroyed uas should are 1
uas = new UAS(mav,UASID);
QSignalSpy spy2(uas->getWaypointManager(), SIGNAL(waypointEditableListChanged()));
QCOMPARE(spy2.count(), 0);
Waypoint* wp2 = new Waypoint(0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,false, false, MAV_FRAME_GLOBAL, MAV_CMD_MISSION_START, "blah");
uas->getWaypointManager()->addWaypointEditable(wp2, true);
QCOMPARE(spy2.count(), 1);
uas->getWaypointManager()->clearWaypointList();
QVector<Waypoint*> wpList = uas->getWaypointManager()->getWaypointEditableList();
QCOMPARE(wpList.count(), 1);
delete uas;
uas = NULL;
delete wp2;
}
//TODO:startHil. to make sure connect and disconnect simulation in QGCFlightGear works properly
//TODO:stopHil
void UASUnitTest::signalUASLink_test()
{
QSignalSpy spy(uas, SIGNAL(modeChanged(int,QString,QString)));
uas->setMode(2);
QCOMPARE(spy.count(), 0);// not solve for UAS not receiving message from UAS
QSignalSpy spyS(LinkManager::instance(), SIGNAL(newLink(LinkInterface*)));
SerialLink* link = new SerialLink();
LinkManager::instance()->add(link);
LinkManager::instance()->addProtocol(link, mav);
QCOMPARE(spyS.count(), 1);
LinkManager::instance()->add(link);
LinkManager::instance()->addProtocol(link, mav);
QCOMPARE(spyS.count(), 1);// not add SerialLink, exist in list
SerialLink* link2 = new SerialLink();
LinkManager::instance()->add(link2);
LinkManager::instance()->addProtocol(link2, mav);
QCOMPARE(spyS.count(), 2);// add SerialLink, not exist in list
QList<LinkInterface*> links = LinkManager::instance()->getLinks();
foreach(LinkInterface* link, links)
{
qDebug()<< link->getName();
qDebug()<< QString::number(link->getId());
qDebug()<< QString::number(link->getNominalDataRate());
QVERIFY(link != NULL);
uas->addLink(link);
}
SerialLink* ff = static_cast<SerialLink*>(uas->getLinks()->at(0));
QCOMPARE(ff->isConnected(), false);
QCOMPARE(ff->isRunning(), false);
QCOMPARE(ff->isFinished(), false);
QCOMPARE(links.count(), uas->getLinks()->count());
QCOMPARE(uas->getLinks()->count(), 2);
LinkInterface* ff99 = static_cast<LinkInterface*>(links.at(1));
LinkManager::instance()->removeLink(ff99);
delete link2;
QCOMPARE(LinkManager::instance()->getLinks().count(), 1);
QCOMPARE(uas->getLinks()->count(), 2);
QCOMPARE(static_cast<LinkInterface*>(LinkManager::instance()->getLinks().at(0))->getId(),
static_cast<LinkInterface*>(uas->getLinks()->at(0))->getId());
SerialLink* link3 = new SerialLink();
LinkManager::instance()->add(link3);
LinkManager::instance()->addProtocol(link3, mav);
QCOMPARE(spyS.count(), 3);
QCOMPARE(LinkManager::instance()->getLinks().count(), 2);
LinkManager::instance()->removeLink(link3);
delete link3;
QCOMPARE(LinkManager::instance()->getLinks().count(), 1);
LinkManager::instance()->removeLink(link);
delete link;
QCOMPARE(LinkManager::instance()->getLinks().count(), 0);
}
void UASUnitTest::signalIdUASLink_test()
{
QCOMPARE(LinkManager::instance()->getLinks().count(), 0);
SerialLink* myLink = new SerialLink();
myLink->setPortName("COM 17");
LinkManager::instance()->add(myLink);
LinkManager::instance()->addProtocol(myLink, mav);
SerialLink* myLink2 = new SerialLink();
myLink2->setPortName("COM 18");
LinkManager::instance()->add(myLink2);
LinkManager::instance()->addProtocol(myLink2, mav);
SerialLink* myLink3 = new SerialLink();
myLink3->setPortName("COM 19");
LinkManager::instance()->add(myLink3);
LinkManager::instance()->addProtocol(myLink3, mav);
SerialLink* myLink4 = new SerialLink();
myLink4->setPortName("COM 20");
LinkManager::instance()->add(myLink4);
LinkManager::instance()->addProtocol(myLink4, mav);
QCOMPARE(LinkManager::instance()->getLinks().count(), 4);
QList<LinkInterface*> links = LinkManager::instance()->getLinks();
LinkInterface* a = static_cast<LinkInterface*>(links.at(0));
LinkInterface* b = static_cast<LinkInterface*>(links.at(1));
LinkInterface* c = static_cast<LinkInterface*>(links.at(2));
LinkInterface* d = static_cast<LinkInterface*>(links.at(3));
QCOMPARE(a->getName(), QString("serial port COM 17"));
QCOMPARE(b->getName(), QString("serial port COM 18"));
QCOMPARE(c->getName(), QString("serial port COM 19"));
QCOMPARE(d->getName(), QString("serial port COM 20"));
LinkManager::instance()->removeLink(myLink4);
delete myLink4;
LinkManager::instance()->removeLink(myLink3);
delete myLink3;
LinkManager::instance()->removeLink(myLink2);
delete myLink2;
LinkManager::instance()->removeLink(myLink);
delete myLink;
QCOMPARE(LinkManager::instance()->getLinks().count(), 0);
}
<commit_msg>ClModified unit test.<commit_after>#include "UASUnitTest.h"
#include <stdio.h>
#include <QObject>
UASUnitTest::UASUnitTest()
{
}
//This function is called after every test
void UASUnitTest::init()
{
mav = new MAVLinkProtocol();
uas = new UAS(mav, UASID);
uas->deleteSettings();
}
//this function is called after every test
void UASUnitTest::cleanup()
{
delete uas;
uas = NULL;
delete mav;
mav = NULL;
}
void UASUnitTest::getUASID_test()
{
// Test a default ID of zero is assigned
UAS* uas2 = new UAS(mav);
QCOMPARE(uas2->getUASID(), 0);
delete uas2;
// Test that the chosen ID was assigned at construction
QCOMPARE(uas->getUASID(), UASID);
// Make sure that no other ID was set
QEXPECT_FAIL("", "When you set an ID it does not use the default ID of 0", Continue);
QCOMPARE(uas->getUASID(), 0);
// Make sure that ID >= 0
QCOMPARE(uas->getUASID(), 100);
}
void UASUnitTest::getUASName_test()
{
// Test that the name is build as MAV + ID
QCOMPARE(uas->getUASName(), "MAV " + QString::number(UASID));
}
void UASUnitTest::getUpTime_test()
{
UAS* uas2 = new UAS(mav);
// Test that the uptime starts at zero to a
// precision of seconds
QCOMPARE(floor(uas2->getUptime()/1000.0), 0.0);
// Sleep for three seconds
QTest::qSleep(3000);
// Test that the up time is computed correctly to a
// precision of seconds
QCOMPARE(floor(uas2->getUptime()/1000.0), 3.0);
delete uas2;
}
void UASUnitTest::getCommunicationStatus_test()
{
// Verify that upon construction the Comm status is disconnected
QCOMPARE(uas->getCommunicationStatus(), static_cast<int>(UASInterface::COMM_DISCONNECTED));
}
void UASUnitTest::filterVoltage_test()
{
float verificar=uas->filterVoltage(0.4f);
// Verify that upon construction the Comm status is disconnected
QCOMPARE(verificar, 8.52f);
}
void UASUnitTest:: getAutopilotType_test()
{
int type = uas->getAutopilotType();
// Verify that upon construction the autopilot is set to -1
QCOMPARE(type, -1);
}
void UASUnitTest::setAutopilotType_test()
{
uas->setAutopilotType(2);
// Verify that the autopilot is set
QCOMPARE(uas->getAutopilotType(), 2);
}
void UASUnitTest::getStatusForCode_test()
{
QString state, desc;
state = "";
desc = "";
uas->getStatusForCode(MAV_STATE_UNINIT, state, desc);
QVERIFY(state == "UNINIT");
uas->getStatusForCode(MAV_STATE_UNINIT, state, desc);
QVERIFY(state == "UNINIT");
uas->getStatusForCode(MAV_STATE_BOOT, state, desc);
QVERIFY(state == "BOOT");
uas->getStatusForCode(MAV_STATE_CALIBRATING, state, desc);
QVERIFY(state == "CALIBRATING");
uas->getStatusForCode(MAV_STATE_ACTIVE, state, desc);
QVERIFY(state == "ACTIVE");
uas->getStatusForCode(MAV_STATE_STANDBY, state, desc);
QVERIFY(state == "STANDBY");
uas->getStatusForCode(MAV_STATE_CRITICAL, state, desc);
QVERIFY(state == "CRITICAL");
uas->getStatusForCode(MAV_STATE_EMERGENCY, state, desc);
QVERIFY(state == "EMERGENCY");
uas->getStatusForCode(MAV_STATE_POWEROFF, state, desc);
QVERIFY(state == "SHUTDOWN");
uas->getStatusForCode(5325, state, desc);
QVERIFY(state == "UNKNOWN");
}
void UASUnitTest::getLocalX_test()
{
QCOMPARE(uas->getLocalX(), 0.0);
}
void UASUnitTest::getLocalY_test()
{
QCOMPARE(uas->getLocalY(), 0.0);
}
void UASUnitTest::getLocalZ_test()
{
QCOMPARE(uas->getLocalZ(), 0.0);
}
void UASUnitTest::getLatitude_test()
{
QCOMPARE(uas->getLatitude(), 0.0);
}
void UASUnitTest::getLongitude_test()
{
QCOMPARE(uas->getLongitude(), 0.0);
}
void UASUnitTest::getAltitude_test()
{
QCOMPARE(uas->getAltitude(), 0.0);
}
void UASUnitTest::getRoll_test()
{
QCOMPARE(uas->getRoll(), 0.0);
}
void UASUnitTest::getPitch_test()
{
QCOMPARE(uas->getPitch(), 0.0);
}
void UASUnitTest::getYaw_test()
{
QCOMPARE(uas->getYaw(), 0.0);
}
void UASUnitTest::getSelected_test()
{
QCOMPARE(uas->getSelected(), false);
}
void UASUnitTest::getSystemType_test()
{ //check that system type is set to MAV_TYPE_GENERIC when initialized
QCOMPARE(uas->getSystemType(), 0);
uas->setSystemType(13);
QCOMPARE(uas->getSystemType(), 13);
}
void UASUnitTest::getAirframe_test()
{
//when uas is constructed, airframe is set to QGC_AIRFRAME_GENERIC which is 0
QCOMPARE(uas->getAirframe(), 0);
}
void UASUnitTest::setAirframe_test()
{
//check at construction, that airframe=0 (GENERIC)
QVERIFY(uas->getAirframe() == 0);
//check that set airframe works
uas->setAirframe(11);
QVERIFY(uas->getAirframe() == 11);
//check that setAirframe will not assign a number to airframe, that is
//not defined in the enum
uas->setAirframe(12);
QVERIFY(uas->getAirframe() == 11);
}
void UASUnitTest::getWaypointList_test()
{
QVector<Waypoint*> kk = uas->getWaypointManager()->getWaypointEditableList();
QCOMPARE(kk.count(), 0);
Waypoint* wp = new Waypoint(0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,false, false, MAV_FRAME_GLOBAL, MAV_CMD_MISSION_START, "blah");
uas->getWaypointManager()->addWaypointEditable(wp, true);
kk = uas->getWaypointManager()->getWaypointEditableList();
QCOMPARE(kk.count(), 1);
wp = new Waypoint();
uas->getWaypointManager()->addWaypointEditable(wp, false);
kk = uas->getWaypointManager()->getWaypointEditableList();
QCOMPARE(kk.count(), 2);
uas->getWaypointManager()->removeWaypoint(1);
kk = uas->getWaypointManager()->getWaypointEditableList();
QCOMPARE(kk.count(), 1);
uas->getWaypointManager()->removeWaypoint(0);
kk = uas->getWaypointManager()->getWaypointEditableList();
QCOMPARE(kk.count(), 0);
qDebug()<<"disconnect SIGNAL waypointListChanged";
}
void UASUnitTest::getWaypoint_test()
{
Waypoint* wp = new Waypoint(0,5.6,2.0,3.0,0.0,0.0,0.0,0.0,false, false, MAV_FRAME_GLOBAL, MAV_CMD_MISSION_START, "blah");
uas->getWaypointManager()->addWaypointEditable(wp, true);
QVector<Waypoint*> wpList = uas->getWaypointManager()->getWaypointEditableList();
QCOMPARE(wpList.count(), 1);
QCOMPARE(static_cast<quint16>(0), static_cast<Waypoint*>(wpList.at(0))->getId());
Waypoint* wp3 = new Waypoint(1, 5.6, 2.0, 3.0);
uas->getWaypointManager()->addWaypointEditable(wp3, true);
wpList = uas->getWaypointManager()->getWaypointEditableList();
Waypoint* wp2 = static_cast<Waypoint*>(wpList.at(0));
QCOMPARE(wpList.count(), 2);
QCOMPARE(wp3->getX(), wp2->getX());
QCOMPARE(wp3->getY(), wp2->getY());
QCOMPARE(wp3->getZ(), wp2->getZ());
QCOMPARE(wpList.at(1)->getId(), static_cast<quint16>(1));
QCOMPARE(wp3->getFrame(), MAV_FRAME_GLOBAL);
QCOMPARE(wp3->getFrame(), wp2->getFrame());
delete wp3;
delete wp;
}
void UASUnitTest::signalWayPoint_test()
{
QSignalSpy spy(uas->getWaypointManager(), SIGNAL(waypointEditableListChanged()));
Waypoint* wp = new Waypoint(0,1.0,0.0,0.0,0.0,0.0,0.0,0.0,false, false, MAV_FRAME_GLOBAL, MAV_CMD_MISSION_START, "blah");
uas->getWaypointManager()->addWaypointEditable(wp, true);
QCOMPARE(spy.count(), 1); // 1 listChanged for add wayPoint
uas->getWaypointManager()->removeWaypoint(0);
QCOMPARE(spy.count(), 2); // 2 listChanged for remove wayPoint
QSignalSpy spyDestroyed(uas->getWaypointManager(), SIGNAL(destroyed()));
QVERIFY(spyDestroyed.isValid());
QCOMPARE( spyDestroyed.count(), 0 );
delete uas;// delete(destroyed) uas for validating
uas = NULL;
QCOMPARE(spyDestroyed.count(), 1);// count destroyed uas should are 1
uas = new UAS(mav,UASID);
QSignalSpy spy2(uas->getWaypointManager(), SIGNAL(waypointEditableListChanged()));
QCOMPARE(spy2.count(), 0);
Waypoint* wp2 = new Waypoint(0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,false, false, MAV_FRAME_GLOBAL, MAV_CMD_MISSION_START, "blah");
uas->getWaypointManager()->addWaypointEditable(wp2, true);
QCOMPARE(spy2.count(), 1);
uas->getWaypointManager()->clearWaypointList();
QVector<Waypoint*> wpList = uas->getWaypointManager()->getWaypointEditableList();
QCOMPARE(wpList.count(), 1);
delete uas;
uas = NULL;
delete wp2;
}
//TODO:startHil. to make sure connect and disconnect simulation in QGCFlightGear works properly
//TODO:stopHil
void UASUnitTest::signalUASLink_test()
{
QSignalSpy spy(uas, SIGNAL(modeChanged(int,QString,QString)));
uas->setMode(2);
QCOMPARE(spy.count(), 0);// not solve for UAS not receiving message from UAS
QSignalSpy spyS(LinkManager::instance(), SIGNAL(newLink(LinkInterface*)));
SerialLink* link = new SerialLink();
LinkManager::instance()->add(link);
LinkManager::instance()->addProtocol(link, mav);
QCOMPARE(spyS.count(), 1);
LinkManager::instance()->add(link);
LinkManager::instance()->addProtocol(link, mav);
QCOMPARE(spyS.count(), 1);// not add SerialLink, exist in list
SerialLink* link2 = new SerialLink();
LinkManager::instance()->add(link2);
LinkManager::instance()->addProtocol(link2, mav);
QCOMPARE(spyS.count(), 2);// add SerialLink, not exist in list
QList<LinkInterface*> links = LinkManager::instance()->getLinks();
foreach(LinkInterface* link, links)
{
qDebug()<< link->getName();
qDebug()<< QString::number(link->getId());
qDebug()<< QString::number(link->getNominalDataRate());
QVERIFY(link != NULL);
uas->addLink(link);
}
SerialLink* ff = static_cast<SerialLink*>(uas->getLinks()->at(0));
QCOMPARE(ff->isConnected(), false);
QCOMPARE(ff->isRunning(), false);
QCOMPARE(ff->isFinished(), false);
QCOMPARE(links.count(), uas->getLinks()->count());
QCOMPARE(uas->getLinks()->count(), 2);
LinkInterface* ff99 = static_cast<LinkInterface*>(links.at(1));
LinkManager::instance()->removeLink(ff99);
delete link2;
QCOMPARE(LinkManager::instance()->getLinks().count(), 1);
QCOMPARE(uas->getLinks()->count(), 2);
QCOMPARE(static_cast<LinkInterface*>(LinkManager::instance()->getLinks().at(0))->getId(),
static_cast<LinkInterface*>(uas->getLinks()->at(0))->getId());
SerialLink* link3 = new SerialLink();
LinkManager::instance()->add(link3);
LinkManager::instance()->addProtocol(link3, mav);
QCOMPARE(spyS.count(), 3);
QCOMPARE(LinkManager::instance()->getLinks().count(), 2);
LinkManager::instance()->removeLink(link3);
delete link3;
QCOMPARE(LinkManager::instance()->getLinks().count(), 1);
LinkManager::instance()->removeLink(link);
delete link;
QCOMPARE(LinkManager::instance()->getLinks().count(), 0);
}
void UASUnitTest::signalIdUASLink_test()
{
QCOMPARE(LinkManager::instance()->getLinks().count(), 0);
SerialLink* myLink = new SerialLink();
myLink->setPortName("COM 17");
LinkManager::instance()->add(myLink);
LinkManager::instance()->addProtocol(myLink, mav);
SerialLink* myLink2 = new SerialLink();
myLink2->setPortName("COM 18");
LinkManager::instance()->add(myLink2);
LinkManager::instance()->addProtocol(myLink2, mav);
SerialLink* myLink3 = new SerialLink();
myLink3->setPortName("COM 19");
LinkManager::instance()->add(myLink3);
LinkManager::instance()->addProtocol(myLink3, mav);
SerialLink* myLink4 = new SerialLink();
myLink4->setPortName("COM 20");
LinkManager::instance()->add(myLink4);
LinkManager::instance()->addProtocol(myLink4, mav);
QCOMPARE(LinkManager::instance()->getLinks().count(), 4);
QList<LinkInterface*> links = LinkManager::instance()->getLinks();
LinkInterface* a = static_cast<LinkInterface*>(links.at(0));
LinkInterface* b = static_cast<LinkInterface*>(links.at(1));
LinkInterface* c = static_cast<LinkInterface*>(links.at(2));
LinkInterface* d = static_cast<LinkInterface*>(links.at(3));
QCOMPARE(a->getName(), QString("serial port COM 17"));
QCOMPARE(b->getName(), QString("serial port COM 18"));
QCOMPARE(c->getName(), QString("serial port COM 19"));
QCOMPARE(d->getName(), QString("serial port COM 20"));
LinkManager::instance()->removeLink(myLink4);
delete myLink4;
LinkManager::instance()->removeLink(myLink3);
delete myLink3;
LinkManager::instance()->removeLink(myLink2);
delete myLink2;
LinkManager::instance()->removeLink(myLink);
delete myLink;
QCOMPARE(LinkManager::instance()->getLinks().count(), 0);
}
<|endoftext|> |
<commit_before>// Copyright (c) 2015-2017 The Bitcoin Unlimited developers
// Distributed under the MIT software license, see the accompanying
// file COPYING or http://www.opensource.org/licenses/mit-license.php.
#include "receivefreezedialog.h"
#include "ui_receivefreezedialog.h"
#include "guiconstants.h"
#include "guiutil.h"
#include "main.h"
#include "optionsmodel.h"
ReceiveFreezeDialog::ReceiveFreezeDialog(QWidget *parent) : QDialog(parent), ui(new Ui::ReceiveFreezeDialog), model(0)
{
ui->setupUi(this);
ui->freezeDateTime->setMinimumDateTime(QDateTime::currentDateTime());
ui->freezeDateTime->setDisplayFormat("yyyy/MM/dd hh:mm");
ui->freezeDateTime->setDateTime(QDateTime::currentDateTime());
ui->freezeBlock->setMinimum(chainActive.Height());
on_resetButton_clicked();
connect(this, SIGNAL(accepted()), parent, SLOT(on_freezeDialog_hide()));
connect(this, SIGNAL(rejected()), parent, SLOT(on_freezeDialog_hide()));
}
ReceiveFreezeDialog::~ReceiveFreezeDialog() { delete ui; }
void ReceiveFreezeDialog::setModel(OptionsModel *model) { this->model = model; }
void ReceiveFreezeDialog::on_freezeDateTime_editingFinished()
{
if (ui->freezeDateTime->dateTime() > ui->freezeDateTime->minimumDateTime())
ui->freezeBlock->clear();
}
void ReceiveFreezeDialog::on_freezeBlock_editingFinished()
{
if (ui->freezeBlock->value() > 0)
ui->freezeDateTime->setDateTime(ui->freezeDateTime->minimumDateTime());
/* limit check */
std::string freezeText = ui->freezeBlock->text().toStdString();
int64_t nFreezeLockTime = 0;
if (freezeText != "")
nFreezeLockTime = std::strtoul(freezeText.c_str(), 0, 10);
if (nFreezeLockTime < 1 || nFreezeLockTime > LOCKTIME_THRESHOLD - 1)
ui->freezeBlock->clear();
}
void ReceiveFreezeDialog::on_resetButton_clicked()
{
ui->freezeBlock->clear();
ui->freezeDateTime->setDateTime(ui->freezeDateTime->minimumDateTime());
}
void ReceiveFreezeDialog::on_okButton_clicked() { accept(); }
void ReceiveFreezeDialog::on_ReceiveFreezeDialog_rejected()
{
// this signal is also called by the ESC key
on_resetButton_clicked();
}
void ReceiveFreezeDialog::getFreezeLockTime(CScriptNum &nFreezeLockTime)
{
nFreezeLockTime = CScriptNum(0);
// try freezeBlock
std::string freezeText = ui->freezeBlock->text().toStdString();
if (freezeText != "")
nFreezeLockTime = CScriptNum(std::strtoul(freezeText.c_str(), 0, 10));
else
{
// try freezeDateTime
if (ui->freezeDateTime->dateTime() > ui->freezeDateTime->minimumDateTime())
nFreezeLockTime = CScriptNum(ui->freezeDateTime->dateTime().toMSecsSinceEpoch() / 1000);
}
}
<commit_msg>Fix variable shadowing in qt/receivefreezedialog.cpp<commit_after>// Copyright (c) 2015-2017 The Bitcoin Unlimited developers
// Distributed under the MIT software license, see the accompanying
// file COPYING or http://www.opensource.org/licenses/mit-license.php.
#include "receivefreezedialog.h"
#include "ui_receivefreezedialog.h"
#include "guiconstants.h"
#include "guiutil.h"
#include "main.h"
#include "optionsmodel.h"
ReceiveFreezeDialog::ReceiveFreezeDialog(QWidget *parent) : QDialog(parent), ui(new Ui::ReceiveFreezeDialog), model(0)
{
ui->setupUi(this);
ui->freezeDateTime->setMinimumDateTime(QDateTime::currentDateTime());
ui->freezeDateTime->setDisplayFormat("yyyy/MM/dd hh:mm");
ui->freezeDateTime->setDateTime(QDateTime::currentDateTime());
ui->freezeBlock->setMinimum(chainActive.Height());
on_resetButton_clicked();
connect(this, SIGNAL(accepted()), parent, SLOT(on_freezeDialog_hide()));
connect(this, SIGNAL(rejected()), parent, SLOT(on_freezeDialog_hide()));
}
ReceiveFreezeDialog::~ReceiveFreezeDialog() { delete ui; }
void ReceiveFreezeDialog::setModel(OptionsModel *_model) { this->model = _model; }
void ReceiveFreezeDialog::on_freezeDateTime_editingFinished()
{
if (ui->freezeDateTime->dateTime() > ui->freezeDateTime->minimumDateTime())
ui->freezeBlock->clear();
}
void ReceiveFreezeDialog::on_freezeBlock_editingFinished()
{
if (ui->freezeBlock->value() > 0)
ui->freezeDateTime->setDateTime(ui->freezeDateTime->minimumDateTime());
/* limit check */
std::string freezeText = ui->freezeBlock->text().toStdString();
int64_t nFreezeLockTime = 0;
if (freezeText != "")
nFreezeLockTime = std::strtoul(freezeText.c_str(), 0, 10);
if (nFreezeLockTime < 1 || nFreezeLockTime > LOCKTIME_THRESHOLD - 1)
ui->freezeBlock->clear();
}
void ReceiveFreezeDialog::on_resetButton_clicked()
{
ui->freezeBlock->clear();
ui->freezeDateTime->setDateTime(ui->freezeDateTime->minimumDateTime());
}
void ReceiveFreezeDialog::on_okButton_clicked() { accept(); }
void ReceiveFreezeDialog::on_ReceiveFreezeDialog_rejected()
{
// this signal is also called by the ESC key
on_resetButton_clicked();
}
void ReceiveFreezeDialog::getFreezeLockTime(CScriptNum &nFreezeLockTime)
{
nFreezeLockTime = CScriptNum(0);
// try freezeBlock
std::string freezeText = ui->freezeBlock->text().toStdString();
if (freezeText != "")
nFreezeLockTime = CScriptNum(std::strtoul(freezeText.c_str(), 0, 10));
else
{
// try freezeDateTime
if (ui->freezeDateTime->dateTime() > ui->freezeDateTime->minimumDateTime())
nFreezeLockTime = CScriptNum(ui->freezeDateTime->dateTime().toMSecsSinceEpoch() / 1000);
}
}
<|endoftext|> |
<commit_before>// Copyright (c) 2006-2008 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "build/build_config.h"
#if defined(OS_WIN)
#include <windows.h>
#endif
#include <string>
#include "base/icu_util.h"
#include "base/file_path.h"
#include "base/file_util.h"
#include "base/logging.h"
#include "base/path_service.h"
#include "base/sys_string_conversions.h"
#include "unicode/putil.h"
#include "unicode/udata.h"
#define ICU_UTIL_DATA_FILE 0
#define ICU_UTIL_DATA_SHARED 1
#define ICU_UTIL_DATA_STATIC 2
#ifndef ICU_UTIL_DATA_IMPL
#if defined(OS_WIN)
#define ICU_UTIL_DATA_IMPL ICU_UTIL_DATA_SHARED
#elif defined(OS_MACOSX)
#define ICU_UTIL_DATA_IMPL ICU_UTIL_DATA_STATIC
#elif defined(OS_LINUX)
#define ICU_UTIL_DATA_IMPL ICU_UTIL_DATA_FILE
#endif
#endif // ICU_UTIL_DATA_IMPL
#if defined(OS_WIN)
#define ICU_UTIL_DATA_SYMBOL "icudt38_dat"
#define ICU_UTIL_DATA_SHARED_MODULE_NAME L"icudt38.dll"
#endif
namespace icu_util {
bool Initialize() {
#ifndef NDEBUG
// Assert that we are not called more than once. Even though calling this
// function isn't harmful (ICU can handle it), being called twice probably
// indicates a programming error.
static bool called_once = false;
DCHECK(!called_once);
called_once = true;
#endif
#if (ICU_UTIL_DATA_IMPL == ICU_UTIL_DATA_SHARED)
// We expect to find the ICU data module alongside the current module.
std::wstring data_path;
PathService::Get(base::DIR_MODULE, &data_path);
file_util::AppendToPath(&data_path, ICU_UTIL_DATA_SHARED_MODULE_NAME);
HMODULE module = LoadLibrary(data_path.c_str());
if (!module)
return false;
FARPROC addr = GetProcAddress(module, ICU_UTIL_DATA_SYMBOL);
if (!addr)
return false;
UErrorCode err = U_ZERO_ERROR;
udata_setCommonData(reinterpret_cast<void*>(addr), &err);
return err == U_ZERO_ERROR;
#elif (ICU_UTIL_DATA_IMPL == ICU_UTIL_DATA_STATIC)
// Mac bundles the ICU data in.
return true;
#elif (ICU_UTIL_DATA_IMPL == ICU_UTIL_DATA_FILE)
// For now, expect the data file to be alongside the executable.
// This is sufficient while we work on unit tests, but will eventually
// likely live in a data directory.
FilePath data_path;
bool path_ok = PathService::Get(base::DIR_EXE, &data_path);
DCHECK(path_ok);
u_setDataDirectory(data_path.value().c_str());
// Only look for the packaged data file;
// the default behavior is to look for individual files.
UErrorCode err = U_ZERO_ERROR;
udata_setFileAccess(UDATA_ONLY_PACKAGES, &err);
return err == U_ZERO_ERROR;
#endif
}
} // namespace icu_util
<commit_msg>Use U_ICU_VERSION_SHORT instead of hard-coding the icu data dll and module name.<commit_after>// Copyright (c) 2006-2008 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "build/build_config.h"
#if defined(OS_WIN)
#include <windows.h>
#endif
#include <string>
#include "base/icu_util.h"
#include "base/file_path.h"
#include "base/file_util.h"
#include "base/logging.h"
#include "base/path_service.h"
#include "base/string_util.h"
#include "base/sys_string_conversions.h"
#include "unicode/putil.h"
#include "unicode/udata.h"
#define ICU_UTIL_DATA_FILE 0
#define ICU_UTIL_DATA_SHARED 1
#define ICU_UTIL_DATA_STATIC 2
#ifndef ICU_UTIL_DATA_IMPL
#if defined(OS_WIN)
#define ICU_UTIL_DATA_IMPL ICU_UTIL_DATA_SHARED
#elif defined(OS_MACOSX)
#define ICU_UTIL_DATA_IMPL ICU_UTIL_DATA_STATIC
#elif defined(OS_LINUX)
#define ICU_UTIL_DATA_IMPL ICU_UTIL_DATA_FILE
#endif
#endif // ICU_UTIL_DATA_IMPL
#if defined(OS_WIN)
#define ICU_UTIL_DATA_SYMBOL "icudt" U_ICU_VERSION_SHORT "_dat"
#define ICU_UTIL_DATA_SHARED_MODULE_NAME "icudt" U_ICU_VERSION_SHORT ".dll"
#endif
namespace icu_util {
bool Initialize() {
#ifndef NDEBUG
// Assert that we are not called more than once. Even though calling this
// function isn't harmful (ICU can handle it), being called twice probably
// indicates a programming error.
static bool called_once = false;
DCHECK(!called_once);
called_once = true;
#endif
#if (ICU_UTIL_DATA_IMPL == ICU_UTIL_DATA_SHARED)
// We expect to find the ICU data module alongside the current module.
std::wstring data_path;
PathService::Get(base::DIR_MODULE, &data_path);
file_util::AppendToPath(&data_path,
ASCIIToWide(ICU_UTIL_DATA_SHARED_MODULE_NAME));
HMODULE module = LoadLibrary(data_path.c_str());
if (!module)
return false;
FARPROC addr = GetProcAddress(module, ICU_UTIL_DATA_SYMBOL);
if (!addr)
return false;
UErrorCode err = U_ZERO_ERROR;
udata_setCommonData(reinterpret_cast<void*>(addr), &err);
return err == U_ZERO_ERROR;
#elif (ICU_UTIL_DATA_IMPL == ICU_UTIL_DATA_STATIC)
// Mac bundles the ICU data in.
return true;
#elif (ICU_UTIL_DATA_IMPL == ICU_UTIL_DATA_FILE)
// For now, expect the data file to be alongside the executable.
// This is sufficient while we work on unit tests, but will eventually
// likely live in a data directory.
FilePath data_path;
bool path_ok = PathService::Get(base::DIR_EXE, &data_path);
DCHECK(path_ok);
u_setDataDirectory(data_path.value().c_str());
// Only look for the packaged data file;
// the default behavior is to look for individual files.
UErrorCode err = U_ZERO_ERROR;
udata_setFileAccess(UDATA_ONLY_PACKAGES, &err);
return err == U_ZERO_ERROR;
#endif
}
} // namespace icu_util
<|endoftext|> |
<commit_before>/****************************************************************************
**
** Copyright (C) 2011 Nokia Corporation and/or its subsidiary(-ies).
** All rights reserved.
** Contact: Nokia Corporation ([email protected])
**
** This file is part of the Qt Compositor.
**
** $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.1, included in the file LGPL_EXCEPTION.txt in this package.
**
** If you have questions regarding the use of this file, please contact
** Nokia at [email protected].
**
**
**
**
**
**
**
**
** $QT_END_LICENSE$
**
****************************************************************************/
#include "waylandwindowmanagerintegration.h"
#include "waylandobject.h"
#include "wayland_wrapper/wldisplay.h"
#include "wayland_wrapper/wlcompositor.h"
#include "wayland-server.h"
#include "wayland-windowmanager-server-protocol.h"
// the protocol files are generated with wayland-scanner, in the following manner:
// wayland-scanner client-header < windowmanager.xml > wayland-windowmanager-client-protocol.h
// wayland-scanner server-header < windowmanager.xml > wayland-windowmanager-server-protocol.h
// wayland-scanner code < windowmanager.xml > wayland-windowmanager-protocol.c
//
// wayland-scanner can be found from wayland sources.
class WindowManagerObject
{
public:
void mapClientToProcess(wl_client *client, uint32_t processId)
{
WindowManagerServerIntegration::instance()->mapClientToProcess(client, processId);
}
void authenticateWithToken(wl_client *client, const char *authenticationToken)
{
WindowManagerServerIntegration::instance()->authenticateWithToken(client, authenticationToken);
}
void changeScreenVisibility(wl_client *client, int visible)
{
WindowManagerServerIntegration::instance()->setVisibilityOnScreen(client, visible);
}
void updateWindowProperty(wl_client *client, wl_surface *surface, const char *name, struct wl_array *value)
{
WindowManagerServerIntegration::instance()->updateWindowProperty(client, surface, name, value);
}
static void bind_func(struct wl_client *client, void *data,
uint32_t version, uint32_t id);
struct wl_resource *getWindowManagerResourceForClient(struct wl_client *client) {
for (int i = 0; i < m_client_resources.size(); i++) {
if (m_client_resources.at(i)->client == client) {
return m_client_resources.at(i);
}
}
return 0;
}
private:
QList<struct wl_resource *>m_client_resources;
};
void map_client_to_process(wl_client *client, struct wl_resource *windowMgrResource, uint32_t processId)
{
WindowManagerObject *windowMgr = static_cast<WindowManagerObject *>(windowMgrResource->data);
windowMgr->mapClientToProcess(client,processId);
}
void authenticate_with_token(wl_client *client, struct wl_resource *windowMgrResource, const char *wl_authentication_token)
{
WindowManagerObject *windowMgr = static_cast<WindowManagerObject *>(windowMgrResource->data);
windowMgr->authenticateWithToken(client,wl_authentication_token);
}
void update_generic_property(wl_client *client, struct wl_resource *windowMgrResource, wl_resource *surfaceResource, const char *name, struct wl_array *value)
{
WindowManagerObject *windowMgr = static_cast<WindowManagerObject *>(windowMgrResource->data);
struct wl_surface *surface = static_cast<struct wl_surface *>(surfaceResource->data);
windowMgr->updateWindowProperty(client,surface,name,value);
}
const static struct wl_windowmanager_interface windowmanager_interface = {
map_client_to_process,
authenticate_with_token,
update_generic_property
};
void WindowManagerObject::bind_func(struct wl_client *client, void *data,
uint32_t version, uint32_t id)
{
Q_UNUSED(version);
WindowManagerObject *win_mgr_object= static_cast<WindowManagerObject *>(data);
struct wl_resource *resource =wl_client_add_object(client,&wl_windowmanager_interface,&windowmanager_interface,id,data);
for (int i = 0; i < win_mgr_object->m_client_resources.size(); i++) {
struct wl_client *existing_client = win_mgr_object->m_client_resources.at(i)->client;
Q_ASSERT(client != existing_client);
}
win_mgr_object->m_client_resources.append(resource);
}
WindowManagerServerIntegration *WindowManagerServerIntegration::m_instance = 0;
WindowManagerServerIntegration::WindowManagerServerIntegration(QObject *parent)
: QObject(parent)
{
m_instance = this;
}
void WindowManagerServerIntegration::initialize(Wayland::Display *waylandDisplay)
{
m_windowManagerObject = new WindowManagerObject();
wl_display_add_global(waylandDisplay->handle(),&wl_windowmanager_interface,m_windowManagerObject,WindowManagerObject::bind_func);
}
void WindowManagerServerIntegration::removeClient(wl_client *client)
{
WaylandManagedClient *managedClient = m_managedClients.take(client);
delete managedClient;
}
void WindowManagerServerIntegration::mapClientToProcess(wl_client *client, uint32_t processId)
{
WaylandManagedClient *managedClient = m_managedClients.value(client, new WaylandManagedClient);
managedClient->m_processId = processId;
m_managedClients.insert(client, managedClient);
}
void WindowManagerServerIntegration::authenticateWithToken(wl_client *client, const char *token)
{
Q_ASSERT(token != 0 && *token != 0);
WaylandManagedClient *managedClient = m_managedClients.value(client, new WaylandManagedClient);
managedClient->m_authenticationToken = QByteArray(token);
m_managedClients.insert(client, managedClient);
emit clientAuthenticated(client);
}
void WindowManagerServerIntegration::setVisibilityOnScreen(wl_client *client, bool visible)
{
struct wl_resource *win_mgr_resource = m_windowManagerObject->getWindowManagerResourceForClient(client);
wl_resource_post_event(win_mgr_resource,WL_WINDOWMANAGER_CLIENT_ONSCREEN_VISIBILITY,visible);
}
void WindowManagerServerIntegration::setScreenOrientation(wl_client *client, wl_object *output, Qt::ScreenOrientation orientation)
{
struct wl_resource *win_mgr_resource = m_windowManagerObject->getWindowManagerResourceForClient(client);
wl_resource_post_event(win_mgr_resource,WL_WINDOWMANAGER_SET_SCREEN_ROTATION,output, qint32(orientation));
}
// client -> server
void WindowManagerServerIntegration::updateWindowProperty(wl_client *client, wl_surface *surface, const char *name, struct wl_array *value)
{
QVariant variantValue;
QByteArray byteValue((const char*)value->data, value->size);
QDataStream ds(&byteValue, QIODevice::ReadOnly);
ds >> variantValue;
emit windowPropertyChanged(client, surface, QString(name), variantValue);
}
// server -> client
void WindowManagerServerIntegration::setWindowProperty(wl_client *client, wl_surface *surface, const QString &name, const QVariant &value)
{
QByteArray byteValue;
QDataStream ds(&byteValue, QIODevice::WriteOnly);
ds << value;
wl_array data;
data.size = byteValue.size();
data.data = (void*) byteValue.constData();
data.alloc = 0;
struct wl_resource *win_mgr_resource = m_windowManagerObject->getWindowManagerResourceForClient(client);
wl_resource_post_event(win_mgr_resource,WL_WINDOWMANAGER_SET_GENERIC_PROPERTY,surface, name.toLatin1().constData(),&data);
}
WaylandManagedClient *WindowManagerServerIntegration::managedClient(wl_client *client) const
{
return m_managedClients.value(client, 0);
}
WindowManagerServerIntegration *WindowManagerServerIntegration::instance()
{
return m_instance;
}
/// ///
/// / WaylandManagedClient
/// ///
WaylandManagedClient::WaylandManagedClient()
: m_processId(0)
{
}
qint64 WaylandManagedClient::processId() const
{
return m_processId;
}
QByteArray WaylandManagedClient::authenticationToken() const
{
return m_authenticationToken;
}
<commit_msg>Fix wm object resource destruction in qt-compositor.<commit_after>/****************************************************************************
**
** Copyright (C) 2011 Nokia Corporation and/or its subsidiary(-ies).
** All rights reserved.
** Contact: Nokia Corporation ([email protected])
**
** This file is part of the Qt Compositor.
**
** $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.1, included in the file LGPL_EXCEPTION.txt in this package.
**
** If you have questions regarding the use of this file, please contact
** Nokia at [email protected].
**
**
**
**
**
**
**
**
** $QT_END_LICENSE$
**
****************************************************************************/
#include "waylandwindowmanagerintegration.h"
#include "waylandobject.h"
#include "wayland_wrapper/wldisplay.h"
#include "wayland_wrapper/wlcompositor.h"
#include "wayland-server.h"
#include "wayland-windowmanager-server-protocol.h"
// the protocol files are generated with wayland-scanner, in the following manner:
// wayland-scanner client-header < windowmanager.xml > wayland-windowmanager-client-protocol.h
// wayland-scanner server-header < windowmanager.xml > wayland-windowmanager-server-protocol.h
// wayland-scanner code < windowmanager.xml > wayland-windowmanager-protocol.c
//
// wayland-scanner can be found from wayland sources.
class WindowManagerObject
{
public:
void mapClientToProcess(wl_client *client, uint32_t processId)
{
WindowManagerServerIntegration::instance()->mapClientToProcess(client, processId);
}
void authenticateWithToken(wl_client *client, const char *authenticationToken)
{
WindowManagerServerIntegration::instance()->authenticateWithToken(client, authenticationToken);
}
void changeScreenVisibility(wl_client *client, int visible)
{
WindowManagerServerIntegration::instance()->setVisibilityOnScreen(client, visible);
}
void updateWindowProperty(wl_client *client, wl_surface *surface, const char *name, struct wl_array *value)
{
WindowManagerServerIntegration::instance()->updateWindowProperty(client, surface, name, value);
}
static void bind_func(struct wl_client *client, void *data,
uint32_t version, uint32_t id);
static void destroy_resource(wl_resource *resource);
struct wl_resource *getWindowManagerResourceForClient(struct wl_client *client) {
for (int i = 0; i < m_client_resources.size(); i++) {
if (m_client_resources.at(i)->client == client) {
return m_client_resources.at(i);
}
}
return 0;
}
private:
QList<struct wl_resource *>m_client_resources;
};
void map_client_to_process(wl_client *client, struct wl_resource *windowMgrResource, uint32_t processId)
{
WindowManagerObject *windowMgr = static_cast<WindowManagerObject *>(windowMgrResource->data);
windowMgr->mapClientToProcess(client,processId);
}
void authenticate_with_token(wl_client *client, struct wl_resource *windowMgrResource, const char *wl_authentication_token)
{
WindowManagerObject *windowMgr = static_cast<WindowManagerObject *>(windowMgrResource->data);
windowMgr->authenticateWithToken(client,wl_authentication_token);
}
void update_generic_property(wl_client *client, struct wl_resource *windowMgrResource, wl_resource *surfaceResource, const char *name, struct wl_array *value)
{
WindowManagerObject *windowMgr = static_cast<WindowManagerObject *>(windowMgrResource->data);
struct wl_surface *surface = static_cast<struct wl_surface *>(surfaceResource->data);
windowMgr->updateWindowProperty(client,surface,name,value);
}
const static struct wl_windowmanager_interface windowmanager_interface = {
map_client_to_process,
authenticate_with_token,
update_generic_property
};
void WindowManagerObject::bind_func(struct wl_client *client, void *data,
uint32_t version, uint32_t id)
{
Q_UNUSED(version);
WindowManagerObject *win_mgr_object= static_cast<WindowManagerObject *>(data);
struct wl_resource *resource =wl_client_add_object(client,&wl_windowmanager_interface,&windowmanager_interface,id,data);
resource->destroy = destroy_resource;
win_mgr_object->m_client_resources.append(resource);
qDebug("wm bind client %p resource %p", client, resource);
}
void WindowManagerObject::destroy_resource(wl_resource *resource)
{
qDebug("wm destroy resource %p", resource);
WindowManagerObject *win_mgr_object = static_cast<WindowManagerObject *>(resource->data);
win_mgr_object->m_client_resources.removeOne(resource);
free(resource);
}
WindowManagerServerIntegration *WindowManagerServerIntegration::m_instance = 0;
WindowManagerServerIntegration::WindowManagerServerIntegration(QObject *parent)
: QObject(parent)
{
m_instance = this;
}
void WindowManagerServerIntegration::initialize(Wayland::Display *waylandDisplay)
{
m_windowManagerObject = new WindowManagerObject();
wl_display_add_global(waylandDisplay->handle(),&wl_windowmanager_interface,m_windowManagerObject,WindowManagerObject::bind_func);
}
void WindowManagerServerIntegration::removeClient(wl_client *client)
{
WaylandManagedClient *managedClient = m_managedClients.take(client);
delete managedClient;
}
void WindowManagerServerIntegration::mapClientToProcess(wl_client *client, uint32_t processId)
{
WaylandManagedClient *managedClient = m_managedClients.value(client, new WaylandManagedClient);
managedClient->m_processId = processId;
m_managedClients.insert(client, managedClient);
}
void WindowManagerServerIntegration::authenticateWithToken(wl_client *client, const char *token)
{
Q_ASSERT(token != 0 && *token != 0);
WaylandManagedClient *managedClient = m_managedClients.value(client, new WaylandManagedClient);
managedClient->m_authenticationToken = QByteArray(token);
m_managedClients.insert(client, managedClient);
emit clientAuthenticated(client);
}
void WindowManagerServerIntegration::setVisibilityOnScreen(wl_client *client, bool visible)
{
struct wl_resource *win_mgr_resource = m_windowManagerObject->getWindowManagerResourceForClient(client);
wl_resource_post_event(win_mgr_resource,WL_WINDOWMANAGER_CLIENT_ONSCREEN_VISIBILITY,visible);
}
void WindowManagerServerIntegration::setScreenOrientation(wl_client *client, wl_object *output, Qt::ScreenOrientation orientation)
{
struct wl_resource *win_mgr_resource = m_windowManagerObject->getWindowManagerResourceForClient(client);
wl_resource_post_event(win_mgr_resource,WL_WINDOWMANAGER_SET_SCREEN_ROTATION,output, qint32(orientation));
}
// client -> server
void WindowManagerServerIntegration::updateWindowProperty(wl_client *client, wl_surface *surface, const char *name, struct wl_array *value)
{
QVariant variantValue;
QByteArray byteValue((const char*)value->data, value->size);
QDataStream ds(&byteValue, QIODevice::ReadOnly);
ds >> variantValue;
emit windowPropertyChanged(client, surface, QString(name), variantValue);
}
// server -> client
void WindowManagerServerIntegration::setWindowProperty(wl_client *client, wl_surface *surface, const QString &name, const QVariant &value)
{
QByteArray byteValue;
QDataStream ds(&byteValue, QIODevice::WriteOnly);
ds << value;
wl_array data;
data.size = byteValue.size();
data.data = (void*) byteValue.constData();
data.alloc = 0;
struct wl_resource *win_mgr_resource = m_windowManagerObject->getWindowManagerResourceForClient(client);
wl_resource_post_event(win_mgr_resource,WL_WINDOWMANAGER_SET_GENERIC_PROPERTY,surface, name.toLatin1().constData(),&data);
}
WaylandManagedClient *WindowManagerServerIntegration::managedClient(wl_client *client) const
{
return m_managedClients.value(client, 0);
}
WindowManagerServerIntegration *WindowManagerServerIntegration::instance()
{
return m_instance;
}
/// ///
/// / WaylandManagedClient
/// ///
WaylandManagedClient::WaylandManagedClient()
: m_processId(0)
{
}
qint64 WaylandManagedClient::processId() const
{
return m_processId;
}
QByteArray WaylandManagedClient::authenticationToken() const
{
return m_authenticationToken;
}
<|endoftext|> |
<commit_before>/***
* Copyright (c) 2013, Dan Hasting
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
*
* 1. Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* 2. Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
* 3. Neither the name of the organization 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 HOLDER OR CONTRIBUTORS BE
* LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
* CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
* SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
* INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
* CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
* ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
* POSSIBILITY OF SUCH DAMAGE.
*
***/
#include "thegamesdbscraper.h"
#include "../global.h"
#include "../common.h"
#include <QDir>
#include <QEventLoop>
#include <QMessageBox>
#include <QTextStream>
#include <QTimer>
#include <QUrl>
#include <QtNetwork/QNetworkAccessManager>
#include <QtNetwork/QNetworkReply>
#include <QtNetwork/QNetworkRequest>
#include <QtXml/QDomDocument>
TheGamesDBScraper::TheGamesDBScraper(QWidget *parent, bool force) : QObject(parent)
{
this->parent = parent;
this->force = force;
this->keepGoing = true;
}
void TheGamesDBScraper::deleteGameInfo(QString fileName, QString identifier)
{
QString text;
text = QString(tr("<b>NOTE:</b> If you are deleting this game's information because the game doesn't "))
+ tr("exist on TheGamesDB and <AppName> pulled the information for different game, it's ")
+ tr("better to create an account on")+" <a href=\"http://thegamesdb.net/\">TheGamesDB</a> "
+ tr("and add the game so other users can benefit as well.")
+ "<br /><br />"
+ tr("This will cause <AppName> to not update the information for this game until you ")
+ tr("force it with \"Download/Update Info...\"")
+ "<br /><br />"
+ tr("Delete the current information for") + " <b>" + fileName + "</b>?";
text.replace("<AppName>",AppName);
int answer = QMessageBox::question(parent, tr("Delete Game Information"), text,
QMessageBox::Yes | QMessageBox::No);
if (answer == QMessageBox::Yes) {
QString gameCache = getDataLocation() + "/cache/" + identifier.toLower();
QString dataFile = gameCache + "/data.xml";
QFile file(dataFile);
// Remove game information
file.open(QIODevice::WriteOnly);
QTextStream stream(&file);
stream << "NULL";
file.close();
// Remove cover image
QString coverFile = gameCache + "/boxart-front.";
QFile coverJPG(coverFile + "jpg");
QFile coverPNG(coverFile + "png");
if (coverJPG.exists())
coverJPG.remove();
if (coverPNG.exists())
coverPNG.remove();
coverJPG.open(QIODevice::WriteOnly);
QTextStream streamImage(&coverJPG);
streamImage << "";
coverJPG.close();
}
}
void TheGamesDBScraper::downloadGameInfo(QString identifier, QString searchName, QString gameID)
{
if (keepGoing && identifier != "") {
if (force) parent->setEnabled(false);
bool updated = false;
QString gameCache = getDataLocation() + "/cache/" + identifier.toLower();
QDir cache(gameCache);
if (!cache.exists()) {
cache.mkpath(gameCache);
}
//Get game XML info from thegamesdb.net
QString dataFile = gameCache + "/data.xml";
QFile file(dataFile);
if (!file.exists() || file.size() == 0 || force) {
QUrl url;
//Remove [!], (U), etc. from GoodName for searching
searchName.remove(QRegExp("\\W*(\\(|\\[).+(\\)|\\])\\W*"));
//Few game specific hacks
//TODO: Contact thegamesdb.net and see if these can be fixed on their end
if (searchName == "Legend of Zelda, The - Majora's Mask")
searchName = "Majora's Mask";
else if (searchName == "Legend of Zelda, The - Ocarina of Time - Master Quest")
searchName = "Master Quest";
else if (searchName == "Legend of Zelda, The - Ocarina of Time" ||
searchName == "THE LEGEND OF ZELDA")
searchName = "Ocarina of Time";
else if (searchName.toLower() == "f-zero x")
gameID = "10836";
//If user submits gameID, use that
if (gameID != "")
url.setUrl("http://thegamesdb.net/api/GetGame.php?id="
+ gameID + "&platform=Nintendo 64");
else
url.setUrl("http://thegamesdb.net/api/GetGame.php?name="
+ searchName + "&platform=Nintendo 64");
QString dom = getUrlContents(url);
QDomDocument xml;
xml.setContent(dom);
QDomNode node = xml.elementsByTagName("Data").at(0).firstChildElement("Game");
int count = 0, found = 0;
while(!node.isNull())
{
QDomElement element = node.firstChildElement("GameTitle").toElement();
if (force) { //from user dialog
QDomElement date = node.firstChildElement("ReleaseDate").toElement();
QString check = "Game: " + element.text();
check.remove(QRegExp(QString("[^A-Za-z 0-9 \\.,\\?'""!@#\\$%\\^&\\*\\")
+ "(\\)-_=\\+;:<>\\/\\\\|\\}\\{\\[\\]`~]*"));
if (date.text() != "") check += "\n" + tr("Released on: ") + date.text();
check += "\n\n" + tr("Does this look correct?");
int answer = QMessageBox::question(parent, QObject::tr("Game Information Download"),
check, QMessageBox::Yes | QMessageBox::No);
if (answer == QMessageBox::Yes) {
found = count;
updated = true;
break;
}
} else {
//We only want one game, so search for a perfect match in the GameTitle element.
//Otherwise this will default to 0 (the first game found)
if(element.text() == searchName)
found = count;
}
node = node.nextSibling();
count++;
}
if (!force || updated) {
file.open(QIODevice::WriteOnly);
QTextStream stream(&file);
QDomNodeList gameList = xml.elementsByTagName("Game");
gameList.at(found).save(stream, QDomNode::EncodingFromDocument);
file.close();
}
if (force && !updated) {
QString message;
if (count == 0)
message = QObject::tr("No results found.");
else
message = QObject::tr("No more results found.");
QMessageBox::information(parent, QObject::tr("Game Information Download"), message);
}
}
//Get front cover
QString boxartURL = "";
QString boxartExt = "";
QString coverFile = gameCache + "/boxart-front.";
QFile coverJPG(coverFile + "jpg");
QFile coverPNG(coverFile + "png");
if ((!coverJPG.exists() && !coverPNG.exists()) || (force && updated)) {
file.open(QIODevice::ReadOnly);
QString dom = file.readAll();
file.close();
QDomDocument xml;
xml.setContent(dom);
QDomNode node = xml.elementsByTagName("Game").at(0).firstChildElement("Images").firstChild();
while(!node.isNull())
{
QDomElement element = node.toElement();
if(element.tagName() == "boxart" && element.attribute("side") == "front")
boxartURL = element.attribute("thumb");
node = node.nextSibling();
}
if (boxartURL != "") {
QUrl url("http://thegamesdb.net/banners/" + boxartURL);
//Check to save as JPG or PNG
boxartExt = QFileInfo(boxartURL).completeSuffix().toLower();
QFile cover(coverFile + boxartExt);
cover.open(QIODevice::WriteOnly);
cover.write(getUrlContents(url));
cover.close();
}
}
if (updated)
QMessageBox::information(parent, QObject::tr("Game Information Download"),
QObject::tr("Download Complete!"));
if (force) parent->setEnabled(true);
}
}
QByteArray TheGamesDBScraper::getUrlContents(QUrl url)
{
QNetworkAccessManager *manager = new QNetworkAccessManager;
QNetworkRequest request;
request.setUrl(url);
request.setRawHeader("User-Agent", AppName.toUtf8().constData());
QNetworkReply *reply = manager->get(request);
QTimer timer;
timer.setSingleShot(true);
QEventLoop loop;
connect(reply, SIGNAL(finished()), &loop, SLOT(quit()));
connect(&timer, SIGNAL(timeout()), &loop, SLOT(quit()));
int time = SETTINGS.value("Other/networktimeout", 10).toInt();
if (time == 0) time = 10;
time *= 1000;
timer.start(time);
loop.exec();
if(timer.isActive()) { //Got reply
timer.stop();
if(reply->error() > 0)
showError(reply->errorString());
else
return reply->readAll();
} else //Request timed out
showError(tr("Request timed out. Check your network settings."));
return QByteArray();
}
void TheGamesDBScraper::showError(QString error)
{
QString question = "\n\n" + tr("Continue scraping information?");
if (force)
QMessageBox::information(parent, tr("Network Error"), error);
else {
int answer = QMessageBox::question(parent, tr("Network Error"), error + question,
QMessageBox::Yes | QMessageBox::No);
if (answer == QMessageBox::No)
keepGoing = false;
}
}
<commit_msg>Delete game images before downloading new ones (closes #31)<commit_after>/***
* Copyright (c) 2013, Dan Hasting
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
*
* 1. Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* 2. Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
* 3. Neither the name of the organization 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 HOLDER OR CONTRIBUTORS BE
* LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
* CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
* SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
* INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
* CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
* ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
* POSSIBILITY OF SUCH DAMAGE.
*
***/
#include "thegamesdbscraper.h"
#include "../global.h"
#include "../common.h"
#include <QDir>
#include <QEventLoop>
#include <QMessageBox>
#include <QTextStream>
#include <QTimer>
#include <QUrl>
#include <QtNetwork/QNetworkAccessManager>
#include <QtNetwork/QNetworkReply>
#include <QtNetwork/QNetworkRequest>
#include <QtXml/QDomDocument>
TheGamesDBScraper::TheGamesDBScraper(QWidget *parent, bool force) : QObject(parent)
{
this->parent = parent;
this->force = force;
this->keepGoing = true;
}
void TheGamesDBScraper::deleteGameInfo(QString fileName, QString identifier)
{
QString text;
text = QString(tr("<b>NOTE:</b> If you are deleting this game's information because the game doesn't "))
+ tr("exist on TheGamesDB and <AppName> pulled the information for different game, it's ")
+ tr("better to create an account on")+" <a href=\"http://thegamesdb.net/\">TheGamesDB</a> "
+ tr("and add the game so other users can benefit as well.")
+ "<br /><br />"
+ tr("This will cause <AppName> to not update the information for this game until you ")
+ tr("force it with \"Download/Update Info...\"")
+ "<br /><br />"
+ tr("Delete the current information for") + " <b>" + fileName + "</b>?";
text.replace("<AppName>",AppName);
int answer = QMessageBox::question(parent, tr("Delete Game Information"), text,
QMessageBox::Yes | QMessageBox::No);
if (answer == QMessageBox::Yes) {
QString gameCache = getDataLocation() + "/cache/" + identifier.toLower();
QString dataFile = gameCache + "/data.xml";
QFile file(dataFile);
// Remove game information
file.open(QIODevice::WriteOnly);
QTextStream stream(&file);
stream << "NULL";
file.close();
// Remove cover image
QString coverFile = gameCache + "/boxart-front.";
QFile coverJPG(coverFile + "jpg");
QFile coverPNG(coverFile + "png");
if (coverJPG.exists())
coverJPG.remove();
if (coverPNG.exists())
coverPNG.remove();
coverJPG.open(QIODevice::WriteOnly);
QTextStream streamImage(&coverJPG);
streamImage << "";
coverJPG.close();
}
}
void TheGamesDBScraper::downloadGameInfo(QString identifier, QString searchName, QString gameID)
{
if (keepGoing && identifier != "") {
if (force) parent->setEnabled(false);
bool updated = false;
QString gameCache = getDataLocation() + "/cache/" + identifier.toLower();
QDir cache(gameCache);
if (!cache.exists()) {
cache.mkpath(gameCache);
}
//Get game XML info from thegamesdb.net
QString dataFile = gameCache + "/data.xml";
QFile file(dataFile);
if (!file.exists() || file.size() == 0 || force) {
QUrl url;
//Remove [!], (U), etc. from GoodName for searching
searchName.remove(QRegExp("\\W*(\\(|\\[).+(\\)|\\])\\W*"));
//Few game specific hacks
//TODO: Contact thegamesdb.net and see if these can be fixed on their end
if (searchName == "Legend of Zelda, The - Majora's Mask")
searchName = "Majora's Mask";
else if (searchName == "Legend of Zelda, The - Ocarina of Time - Master Quest")
searchName = "Master Quest";
else if (searchName == "Legend of Zelda, The - Ocarina of Time" ||
searchName == "THE LEGEND OF ZELDA")
searchName = "Ocarina of Time";
else if (searchName.toLower() == "f-zero x")
gameID = "10836";
//If user submits gameID, use that
if (gameID != "")
url.setUrl("http://thegamesdb.net/api/GetGame.php?id="
+ gameID + "&platform=Nintendo 64");
else
url.setUrl("http://thegamesdb.net/api/GetGame.php?name="
+ searchName + "&platform=Nintendo 64");
QString dom = getUrlContents(url);
QDomDocument xml;
xml.setContent(dom);
QDomNode node = xml.elementsByTagName("Data").at(0).firstChildElement("Game");
int count = 0, found = 0;
while(!node.isNull())
{
QDomElement element = node.firstChildElement("GameTitle").toElement();
if (force) { //from user dialog
QDomElement date = node.firstChildElement("ReleaseDate").toElement();
QString check = "Game: " + element.text();
check.remove(QRegExp(QString("[^A-Za-z 0-9 \\.,\\?'""!@#\\$%\\^&\\*\\")
+ "(\\)-_=\\+;:<>\\/\\\\|\\}\\{\\[\\]`~]*"));
if (date.text() != "") check += "\n" + tr("Released on: ") + date.text();
check += "\n\n" + tr("Does this look correct?");
int answer = QMessageBox::question(parent, QObject::tr("Game Information Download"),
check, QMessageBox::Yes | QMessageBox::No);
if (answer == QMessageBox::Yes) {
found = count;
updated = true;
break;
}
} else {
//We only want one game, so search for a perfect match in the GameTitle element.
//Otherwise this will default to 0 (the first game found)
if(element.text() == searchName)
found = count;
}
node = node.nextSibling();
count++;
}
if (!force || updated) {
file.open(QIODevice::WriteOnly);
QTextStream stream(&file);
QDomNodeList gameList = xml.elementsByTagName("Game");
gameList.at(found).save(stream, QDomNode::EncodingFromDocument);
file.close();
}
if (force && !updated) {
QString message;
if (count == 0)
message = QObject::tr("No results found.");
else
message = QObject::tr("No more results found.");
QMessageBox::information(parent, QObject::tr("Game Information Download"), message);
}
}
//Get front cover
QString boxartURL = "";
QString boxartExt = "";
QString coverFile = gameCache + "/boxart-front.";
QFile coverJPG(coverFile + "jpg");
QFile coverPNG(coverFile + "png");
if ((!coverJPG.exists() && !coverPNG.exists()) || (force && updated)) {
file.open(QIODevice::ReadOnly);
QString dom = file.readAll();
file.close();
QDomDocument xml;
xml.setContent(dom);
QDomNode node = xml.elementsByTagName("Game").at(0).firstChildElement("Images").firstChild();
while(!node.isNull())
{
QDomElement element = node.toElement();
if(element.tagName() == "boxart" && element.attribute("side") == "front")
boxartURL = element.attribute("thumb");
node = node.nextSibling();
}
if (boxartURL != "") {
QUrl url("http://thegamesdb.net/banners/" + boxartURL);
//Delete current box art
QFile::remove(coverFile + "jpg");
QFile::remove(coverFile + "png");
//Check to save as JPG or PNG
boxartExt = QFileInfo(boxartURL).completeSuffix().toLower();
QFile cover(coverFile + boxartExt);
cover.open(QIODevice::WriteOnly);
cover.write(getUrlContents(url));
cover.close();
}
}
if (updated)
QMessageBox::information(parent, QObject::tr("Game Information Download"),
QObject::tr("Download Complete!"));
if (force) parent->setEnabled(true);
}
}
QByteArray TheGamesDBScraper::getUrlContents(QUrl url)
{
QNetworkAccessManager *manager = new QNetworkAccessManager;
QNetworkRequest request;
request.setUrl(url);
request.setRawHeader("User-Agent", AppName.toUtf8().constData());
QNetworkReply *reply = manager->get(request);
QTimer timer;
timer.setSingleShot(true);
QEventLoop loop;
connect(reply, SIGNAL(finished()), &loop, SLOT(quit()));
connect(&timer, SIGNAL(timeout()), &loop, SLOT(quit()));
int time = SETTINGS.value("Other/networktimeout", 10).toInt();
if (time == 0) time = 10;
time *= 1000;
timer.start(time);
loop.exec();
if(timer.isActive()) { //Got reply
timer.stop();
if(reply->error() > 0)
showError(reply->errorString());
else
return reply->readAll();
} else //Request timed out
showError(tr("Request timed out. Check your network settings."));
return QByteArray();
}
void TheGamesDBScraper::showError(QString error)
{
QString question = "\n\n" + tr("Continue scraping information?");
if (force)
QMessageBox::information(parent, tr("Network Error"), error);
else {
int answer = QMessageBox::question(parent, tr("Network Error"), error + question,
QMessageBox::Yes | QMessageBox::No);
if (answer == QMessageBox::No)
keepGoing = false;
}
}
<|endoftext|> |
<commit_before>/*****************************************************************************************
* *
* OpenSpace *
* *
* Copyright (c) 2014-2022 *
* *
* 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. *
****************************************************************************************/
namespace {
/**
* Adds an asset to the current scene. The parameter passed into this function is the path
* to the file that should be loaded.
*/
[[codegen::luawrap]] void add(std::string assetName) {
openspace::global::openSpaceEngine->assetManager().add(assetName);
}
/**
* Removes the asset with the specfied name from the scene. The parameter to this function
* is the same that was originally used to load this asset, i.e. the path to the asset
* file.
*/
[[codegen::luawrap]] void remove(std::string assetName) {
openspace::global::openSpaceEngine->assetManager().remove(assetName);
}
/**
* Returns true if the referenced asset already has been loaded. Otherwise false is
* returned. The parameter to this function is the path of the asset that should be
* tested.
*/
[[codegen::luawrap]] bool isLoaded(std::string assetName) {
using namespace openspace;
std::vector<const Asset*> as = global::openSpaceEngine->assetManager().allAssets();
for (const Asset* a : as) {
if (a->path() == assetName) {
return true;
}
}
return false;
}
/**
* Returns the paths to all loaded assets, loaded directly or indirectly, as a table
* containing the paths to all loaded assets.
*/
[[codegen::luawrap]] std::vector<std::string> allAssets(std::string assetName) {
using namespace openspace;
std::vector<const Asset*> as = global::openSpaceEngine->assetManager().allAssets();
std::vector<std::string> res;
res.reserve(as.size());
for (const Asset* a : as) {
res.push_back(a->path().string());
}
return res;
}
#include "assetmanager_lua_codegen.cpp"
} // namespace
<commit_msg>Remove unused parameter when accessing all loaded assets through Lua<commit_after>/*****************************************************************************************
* *
* OpenSpace *
* *
* Copyright (c) 2014-2022 *
* *
* 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. *
****************************************************************************************/
namespace {
/**
* Adds an asset to the current scene. The parameter passed into this function is the path
* to the file that should be loaded.
*/
[[codegen::luawrap]] void add(std::string assetName) {
openspace::global::openSpaceEngine->assetManager().add(assetName);
}
/**
* Removes the asset with the specfied name from the scene. The parameter to this function
* is the same that was originally used to load this asset, i.e. the path to the asset
* file.
*/
[[codegen::luawrap]] void remove(std::string assetName) {
openspace::global::openSpaceEngine->assetManager().remove(assetName);
}
/**
* Returns true if the referenced asset already has been loaded. Otherwise false is
* returned. The parameter to this function is the path of the asset that should be
* tested.
*/
[[codegen::luawrap]] bool isLoaded(std::string assetName) {
using namespace openspace;
std::vector<const Asset*> as = global::openSpaceEngine->assetManager().allAssets();
for (const Asset* a : as) {
if (a->path() == assetName) {
return true;
}
}
return false;
}
/**
* Returns the paths to all loaded assets, loaded directly or indirectly, as a table
* containing the paths to all loaded assets.
*/
[[codegen::luawrap]] std::vector<std::string> allAssets() {
using namespace openspace;
std::vector<const Asset*> as = global::openSpaceEngine->assetManager().allAssets();
std::vector<std::string> res;
res.reserve(as.size());
for (const Asset* a : as) {
res.push_back(a->path().string());
}
return res;
}
#include "assetmanager_lua_codegen.cpp"
} // namespace
<|endoftext|> |
<commit_before>//----------------------------------------------------------
// @file : tracker_double.cpp
// @adder : Watanabe Yuuta
// @version: Ver0.0.1 (since 2014.05.02)
// @date : 2014.11.21
//----------------------------------------------------------
#include <ros/ros.h>
#include <pthread.h>
#include <std_msgs/String.h>
#include <sensor_msgs/LaserScan.h>
#include <sensor_msgs/MultiEchoLaserScan.h>
#include <tms_msg_ss/tracking_points.h>
#include <tms_msg_ss/tracking_grid.h>
pthread_mutex_t mutex_laser = PTHREAD_MUTEX_INITIALIZER;
pthread_mutex_t mutex_target = PTHREAD_MUTEX_INITIALIZER;
#include "opencv/cv.h"
#include "define.h"
#include "target.h"
#include "laser.h"
#include "particle_filter.h"
#include "multiple_particle_filter.h"
#include <boost/date_time/posix_time/posix_time.hpp>
#include <string>
#include <iostream>
#include <ctime>
#include <time.h>
#include <iostream>
#include <fstream>
#include <string>
std::vector<float> scanData;
std::vector<float> scanData1;
CLaser laser;
bool CallbackCalled = false;
ros::Publisher pub ;
ros::Subscriber sub ;
ros::Subscriber sub1;
void *Visualization( void *ptr )
{
int ID;
float X;
float Y;
ros::Rate r(10);
ros::Publisher *pub = (ros::Publisher *)ptr;
int latest_id = 0;
while (ros::ok())
{
tms_msg_ss::tracking_grid grid;
tms_msg_ss::tracking_points points;
int id = 0;
int flag = 0;
for (int i = 0; i < 3; i++)
{
id ++;
}
pthread_mutex_lock(&mutex_target);
for (int i = 0; i < MAX_TRACKING_OBJECT; i++)
{
if (laser.m_pTarget[i] != NULL)
{
if (laser.m_pTarget[i]->cnt < 200)
{
//cout << laser.m_pTarget[i]->cnt << endl;
continue;
}
//std::cout << "laser.m_pTarget " << laser.m_pTarget[i]->cnt << std::endl;
ID = (laser.m_pTarget[i]->id) % 20;
X = -(laser.m_pTarget[i]->py) + 5200;
Y = (laser.m_pTarget[i]->px) + 100;
//std::cout << "FX FY"<< FX << " "<< FY <<std::endl;
if (0.0 < X && X < 8000.0 && 0.0 < Y && Y < 4500.0)
{
grid.id = ID;
grid.x = X;
grid.y = Y;
points.tracking_grid.push_back(grid);
}
id ++;
}
}
//if (id - 3 > 0) std::cout << "Number of Markers " << id - 3 << std::endl;
pthread_mutex_unlock(&mutex_target);
latest_id = id;
pub->publish(points);
//std::cout << "pub"<<std::endl;
r.sleep();
}
return 0;
}
void *Processing( void *ptr )
{
CMultipleParticleFilter m_PF;
std::vector<double> itigou_x;
std::vector<double> itigou_y;
std::vector<double> nigou_x;
std::vector<double> nigou_y;
ros::Rate r(30);
laser.Init();
laser.m_bNodeActive[0] = true;
laser.m_bNodeActive[1] = true;
laser.m_nConnectNum = 2;
laser.GetLRFParam();
laser.m_nStep[0] = laser.m_LRFParam[0].step;
laser.m_nStep[1] = laser.m_LRFParam[1].step;
laser.m_StartAngle[0] = -laser.m_LRFParam[0].viewangle / 2.0;
laser.m_StartAngle[1] = -laser.m_LRFParam[1].viewangle / 2.0;
laser.m_DivAngle[0] = laser.m_LRFParam[0].divangle;
laser.m_DivAngle[1] = laser.m_LRFParam[1].divangle;
CvMat *m_Rotate = cvCreateMat(2, 2, CV_64F);
CvMat *m_Translate = cvCreateMat(2, 1, CV_64F);
CvMat *Temp = cvCreateMat(2, 1, CV_64F);
int count;
double theta, range;
if (laser.m_bNodeActive[0])
while (!CallbackCalled) r.sleep();
if (laser.m_bResetBackRangeData == true)
{
for (int it = 0; it < laser.m_ring; it++)
{
for (int n = 0; n < laser.m_cnMaxConnect; n++)
{
if (laser.m_bNodeActive[n])
{
pthread_mutex_lock(&mutex_laser);
laser.m_LRFData[n].clear();
if (n == 0)
{
laser.m_LRFData[n].resize(scanData.size());
for (int i = 0; i < scanData.size(); i++)
{
laser.m_LRFData[n][i] = scanData[i];
}
}
else if (n == 1)
{
laser.m_LRFData[n].resize(scanData1.size());
for (int i = 0; i < scanData1.size(); i++)
{
laser.m_LRFData[n][i] = scanData1[i];
}
}
pthread_mutex_unlock(&mutex_laser);
}
}
laser.GetBackLRFDataGaussian();
r.sleep();
}
laser.m_bResetBackRangeData = false;
std::cout << "Back range data is stored" << std::endl;
}
int iteration = 0;
while (ros::ok())
{
if (laser.m_bResetBackRangeData == false)
{
for (int n = 0; n < laser.m_cnMaxConnect; n++)
{
if (laser.m_bNodeActive[n])
{
pthread_mutex_lock(&mutex_laser);
laser.m_LRFData[n].clear();
if (n == 0)
{
laser.m_LRFData[n].resize(scanData.size());
for (int i = 0; i < scanData.size(); i++)
{
laser.m_LRFData[n][i] = scanData[i];
}
}
else if (n == 1)
{
laser.m_LRFData[n].resize(scanData1.size());
for (int i = 0; i < scanData1.size(); i++)
{
laser.m_LRFData[n][i] = scanData1[i];
}
}
pthread_mutex_unlock(&mutex_laser);
laser.GetDiffLRFCluster(n);
cvmSet(m_Rotate, 0, 0, cos(deg2rad(laser.m_LRFParam[n].rz)));
cvmSet(m_Rotate, 0, 1, -sin(deg2rad(laser.m_LRFParam[n].rz)));
cvmSet(m_Rotate, 1, 0, sin(deg2rad(laser.m_LRFParam[n].rz)));
cvmSet(m_Rotate, 1, 1, cos(deg2rad(laser.m_LRFParam[n].rz)));
cvmSet(m_Translate, 0, 0, laser.m_LRFParam[n].tx);
cvmSet(m_Translate, 1, 0, laser.m_LRFParam[n].ty);
laser.m_LRFPoints[n].clear();
laser.m_LRFPoints[n].resize(laser.m_DiffLRFData[n].size());
for ( int i = 0; i < laser.m_DiffLRFData[n].size(); i++)
{
count = laser.m_DiffLRFData[n][i].n;
range = laser.m_DiffLRFData[n][i].range;
theta = laser.m_DivAngle[0] * count + laser.m_StartAngle[0];
cvmSet(laser.m_LRFPos[n][i], 0, 0, range * cos(deg2rad(theta)));
cvmSet(laser.m_LRFPos[n][i], 1, 0, range * sin(deg2rad(theta)));
cvmMul(m_Rotate, laser.m_LRFPos[n][i], Temp);
cvmAdd(m_Translate, Temp, laser.m_LRFPos[n][i]);
laser.m_LRFPoints[n][i].x = cvmGet(laser.m_LRFPos[n][i], 0, 0) * 1000.0;
laser.m_LRFPoints[n][i].y = cvmGet(laser.m_LRFPos[n][i], 1, 0) * 1000.0;
}
laser.m_LRFClsPoints[n].clear();
laser.m_LRFClsPoints[n].resize(laser.m_LRFClsData[n].size());
for (int i = 0; i < laser.m_LRFClsData[n].size(); i++)
{
count = laser.m_LRFClsData[n][i].n;
range = laser.m_LRFClsData[n][i].range;
theta = laser.m_DivAngle[0] * count + laser.m_StartAngle[0];
theta = laser.m_DivAngle[1] * count + laser.m_StartAngle[1];
cvmSet(laser.m_LRFClsPos[n][i], 0, 0, range * cos(deg2rad(theta)));
cvmSet(laser.m_LRFClsPos[n][i], 1, 0, range * sin(deg2rad(theta)));
cvmMul(m_Rotate, laser.m_LRFClsPos[n][i], Temp);
cvmAdd(m_Translate, Temp, laser.m_LRFClsPos[n][i]);
laser.m_LRFClsPoints[n][i].x = cvmGet(laser.m_LRFClsPos[n][i], 0, 0) * 1000.0;
laser.m_LRFClsPoints[n][i].y = cvmGet(laser.m_LRFClsPos[n][i], 1, 0) * 1000.0;
if (n == 0)
{
itigou_x.push_back(laser.m_LRFClsPoints[0][i].x);
itigou_y.push_back(laser.m_LRFClsPoints[0][i].y);
}
else if (n == 1)
{
nigou_x.push_back(laser.m_LRFClsPoints[1][i].x);
nigou_y.push_back(laser.m_LRFClsPoints[1][i].y);
}
}
}
if (n == 1)
{
itigou_x.insert(itigou_x.begin(), nigou_x.begin(), nigou_x.end());
itigou_y.insert(itigou_y.begin(), nigou_y.begin(), nigou_y.end());
laser.m_LRFClsPoints[0].clear();
laser.m_LRFClsPoints[0].resize(itigou_x.size());
for (int i = 0; i < itigou_x.size(); i++)
{
laser.m_LRFClsPoints[0][i].x = itigou_x[i];
laser.m_LRFClsPoints[0][i].y = itigou_y[i];
}
itigou_x.clear();
itigou_y.clear();
nigou_x.clear();
nigou_y.clear();
}
}
}
pthread_mutex_lock(&mutex_target);
m_PF.update(&laser);
pthread_mutex_unlock(&mutex_target);
ros::Time begin = ros::Time::now();
if (m_PF.m_ParticleFilter.size() > 0)
{
std::cout << "Time " << begin << " Number of PFs " << m_PF.m_ParticleFilter.size() << std::endl;
}
if (!(iteration % 100000))
{
laser.GetBackLRFDataGaussian();
}
r.sleep();
iteration ++;
}
cvReleaseMat(&Temp);
cvReleaseMat(&m_Rotate);
cvReleaseMat(&m_Translate);
}
void LaserSensingCallback(const sensor_msgs::LaserScan::ConstPtr &scan)
{
pthread_mutex_lock(&mutex_laser);
int num = floor((scan->angle_max - scan->angle_min) / scan->angle_increment);
if ( scanData.size() == 0 )
scanData.resize(num);
scanData = scan->ranges;
pthread_mutex_unlock(&mutex_laser);
CallbackCalled = true;
}
void LaserSensingCallback1(const sensor_msgs::LaserScan::ConstPtr &scan)
{
pthread_mutex_lock(&mutex_laser);
int num = floor((scan->angle_max - scan->angle_min) / scan->angle_increment);
if ( scanData1.size() == 0 )
scanData1.resize(num);
scanData1 = scan->ranges;
pthread_mutex_unlock(&mutex_laser);
CallbackCalled = true;
}
int main( int argc, char **argv )
{
pthread_t thread_p;
pthread_t thread_v;
ros::MultiThreadedSpinner spinner(4);
ros::init(argc, argv, "moving_object_tracker");
ros::NodeHandle n;
ros::Publisher pub = n.advertise<tms_msg_ss::tracking_points>("tracking_points", 10);
ros::Subscriber sub = n.subscribe("/urg2/most_intense" , 10, LaserSensingCallback);
ros::Subscriber sub1 = n.subscribe("/urg1/most_intense" , 10, LaserSensingCallback1);
if ( pthread_create( &thread_v, NULL, Visualization, (void *)&pub) )
{
printf("error creating thread.");
abort();
}
if ( pthread_create( &thread_p, NULL, Processing, NULL) )
{
printf("error creating thread.");
abort();
}
spinner.spin();
ros::waitForShutdown();
if ( pthread_join( thread_p, NULL) )
{
printf("error joining thread.");
abort();
}
if ( pthread_join( thread_v, NULL) )
{
printf("error joining thread.");
abort();
}
scanData.clear();
return 0;
}
<commit_msg>speedup of tracker publisher<commit_after>//----------------------------------------------------------
// @file : tracker_double.cpp
// @adder : Watanabe Yuuta
// @version: Ver0.0.1 (since 2014.05.02)
// @date : 2014.11.21
//----------------------------------------------------------
#include <ros/ros.h>
#include <pthread.h>
#include <std_msgs/String.h>
#include <sensor_msgs/LaserScan.h>
#include <sensor_msgs/MultiEchoLaserScan.h>
#include <tms_msg_ss/tracking_points.h>
#include <tms_msg_ss/tracking_grid.h>
pthread_mutex_t mutex_laser = PTHREAD_MUTEX_INITIALIZER;
pthread_mutex_t mutex_target = PTHREAD_MUTEX_INITIALIZER;
#include "opencv/cv.h"
#include "define.h"
#include "target.h"
#include "laser.h"
#include "particle_filter.h"
#include "multiple_particle_filter.h"
#include <boost/date_time/posix_time/posix_time.hpp>
#include <string>
#include <iostream>
#include <ctime>
#include <time.h>
#include <iostream>
#include <fstream>
#include <string>
std::vector<float> scanData;
std::vector<float> scanData1;
CLaser laser;
bool CallbackCalled = false;
ros::Publisher pub ;
ros::Subscriber sub ;
ros::Subscriber sub1;
void *Visualization( void *ptr )
{
int ID;
float X;
float Y;
ros::Rate r(20);
ros::Publisher *pub = (ros::Publisher *)ptr;
int latest_id = 0;
while (ros::ok())
{
tms_msg_ss::tracking_grid grid;
tms_msg_ss::tracking_points points;
int id = 0;
int flag = 0;
for (int i = 0; i < 3; i++)
{
id ++;
}
pthread_mutex_lock(&mutex_target);
for (int i = 0; i < MAX_TRACKING_OBJECT; i++)
{
if (laser.m_pTarget[i] != NULL)
{
if (laser.m_pTarget[i]->cnt < 200)
{
//cout << laser.m_pTarget[i]->cnt << endl;
continue;
}
//std::cout << "laser.m_pTarget " << laser.m_pTarget[i]->cnt << std::endl;
ID = (laser.m_pTarget[i]->id) % 20;
X = -(laser.m_pTarget[i]->py) + 5200;
Y = (laser.m_pTarget[i]->px) + 100;
//std::cout << "FX FY"<< FX << " "<< FY <<std::endl;
if (0.0 < X && X < 8000.0 && 0.0 < Y && Y < 4500.0)
{
grid.id = ID;
grid.x = X;
grid.y = Y;
points.tracking_grid.push_back(grid);
}
id ++;
}
}
//if (id - 3 > 0) std::cout << "Number of Markers " << id - 3 << std::endl;
pthread_mutex_unlock(&mutex_target);
latest_id = id;
pub->publish(points);
//std::cout << "pub"<<std::endl;
r.sleep();
}
return 0;
}
void *Processing( void *ptr )
{
CMultipleParticleFilter m_PF;
std::vector<double> itigou_x;
std::vector<double> itigou_y;
std::vector<double> nigou_x;
std::vector<double> nigou_y;
ros::Rate r(30);
laser.Init();
laser.m_bNodeActive[0] = true;
laser.m_bNodeActive[1] = true;
laser.m_nConnectNum = 2;
laser.GetLRFParam();
laser.m_nStep[0] = laser.m_LRFParam[0].step;
laser.m_nStep[1] = laser.m_LRFParam[1].step;
laser.m_StartAngle[0] = -laser.m_LRFParam[0].viewangle / 2.0;
laser.m_StartAngle[1] = -laser.m_LRFParam[1].viewangle / 2.0;
laser.m_DivAngle[0] = laser.m_LRFParam[0].divangle;
laser.m_DivAngle[1] = laser.m_LRFParam[1].divangle;
CvMat *m_Rotate = cvCreateMat(2, 2, CV_64F);
CvMat *m_Translate = cvCreateMat(2, 1, CV_64F);
CvMat *Temp = cvCreateMat(2, 1, CV_64F);
int count;
double theta, range;
if (laser.m_bNodeActive[0])
while (!CallbackCalled) r.sleep();
if (laser.m_bResetBackRangeData == true)
{
for (int it = 0; it < laser.m_ring; it++)
{
for (int n = 0; n < laser.m_cnMaxConnect; n++)
{
if (laser.m_bNodeActive[n])
{
pthread_mutex_lock(&mutex_laser);
laser.m_LRFData[n].clear();
if (n == 0)
{
laser.m_LRFData[n].resize(scanData.size());
for (int i = 0; i < scanData.size(); i++)
{
laser.m_LRFData[n][i] = scanData[i];
}
}
else if (n == 1)
{
laser.m_LRFData[n].resize(scanData1.size());
for (int i = 0; i < scanData1.size(); i++)
{
laser.m_LRFData[n][i] = scanData1[i];
}
}
pthread_mutex_unlock(&mutex_laser);
}
}
laser.GetBackLRFDataGaussian();
r.sleep();
}
laser.m_bResetBackRangeData = false;
std::cout << "Back range data is stored" << std::endl;
}
int iteration = 0;
while (ros::ok())
{
if (laser.m_bResetBackRangeData == false)
{
for (int n = 0; n < laser.m_cnMaxConnect; n++)
{
if (laser.m_bNodeActive[n])
{
pthread_mutex_lock(&mutex_laser);
laser.m_LRFData[n].clear();
if (n == 0)
{
laser.m_LRFData[n].resize(scanData.size());
for (int i = 0; i < scanData.size(); i++)
{
laser.m_LRFData[n][i] = scanData[i];
}
}
else if (n == 1)
{
laser.m_LRFData[n].resize(scanData1.size());
for (int i = 0; i < scanData1.size(); i++)
{
laser.m_LRFData[n][i] = scanData1[i];
}
}
pthread_mutex_unlock(&mutex_laser);
laser.GetDiffLRFCluster(n);
cvmSet(m_Rotate, 0, 0, cos(deg2rad(laser.m_LRFParam[n].rz)));
cvmSet(m_Rotate, 0, 1, -sin(deg2rad(laser.m_LRFParam[n].rz)));
cvmSet(m_Rotate, 1, 0, sin(deg2rad(laser.m_LRFParam[n].rz)));
cvmSet(m_Rotate, 1, 1, cos(deg2rad(laser.m_LRFParam[n].rz)));
cvmSet(m_Translate, 0, 0, laser.m_LRFParam[n].tx);
cvmSet(m_Translate, 1, 0, laser.m_LRFParam[n].ty);
laser.m_LRFPoints[n].clear();
laser.m_LRFPoints[n].resize(laser.m_DiffLRFData[n].size());
for ( int i = 0; i < laser.m_DiffLRFData[n].size(); i++)
{
count = laser.m_DiffLRFData[n][i].n;
range = laser.m_DiffLRFData[n][i].range;
theta = laser.m_DivAngle[0] * count + laser.m_StartAngle[0];
cvmSet(laser.m_LRFPos[n][i], 0, 0, range * cos(deg2rad(theta)));
cvmSet(laser.m_LRFPos[n][i], 1, 0, range * sin(deg2rad(theta)));
cvmMul(m_Rotate, laser.m_LRFPos[n][i], Temp);
cvmAdd(m_Translate, Temp, laser.m_LRFPos[n][i]);
laser.m_LRFPoints[n][i].x = cvmGet(laser.m_LRFPos[n][i], 0, 0) * 1000.0;
laser.m_LRFPoints[n][i].y = cvmGet(laser.m_LRFPos[n][i], 1, 0) * 1000.0;
}
laser.m_LRFClsPoints[n].clear();
laser.m_LRFClsPoints[n].resize(laser.m_LRFClsData[n].size());
for (int i = 0; i < laser.m_LRFClsData[n].size(); i++)
{
count = laser.m_LRFClsData[n][i].n;
range = laser.m_LRFClsData[n][i].range;
theta = laser.m_DivAngle[0] * count + laser.m_StartAngle[0];
theta = laser.m_DivAngle[1] * count + laser.m_StartAngle[1];
cvmSet(laser.m_LRFClsPos[n][i], 0, 0, range * cos(deg2rad(theta)));
cvmSet(laser.m_LRFClsPos[n][i], 1, 0, range * sin(deg2rad(theta)));
cvmMul(m_Rotate, laser.m_LRFClsPos[n][i], Temp);
cvmAdd(m_Translate, Temp, laser.m_LRFClsPos[n][i]);
laser.m_LRFClsPoints[n][i].x = cvmGet(laser.m_LRFClsPos[n][i], 0, 0) * 1000.0;
laser.m_LRFClsPoints[n][i].y = cvmGet(laser.m_LRFClsPos[n][i], 1, 0) * 1000.0;
if (n == 0)
{
itigou_x.push_back(laser.m_LRFClsPoints[0][i].x);
itigou_y.push_back(laser.m_LRFClsPoints[0][i].y);
}
else if (n == 1)
{
nigou_x.push_back(laser.m_LRFClsPoints[1][i].x);
nigou_y.push_back(laser.m_LRFClsPoints[1][i].y);
}
}
}
if (n == 1)
{
itigou_x.insert(itigou_x.begin(), nigou_x.begin(), nigou_x.end());
itigou_y.insert(itigou_y.begin(), nigou_y.begin(), nigou_y.end());
laser.m_LRFClsPoints[0].clear();
laser.m_LRFClsPoints[0].resize(itigou_x.size());
for (int i = 0; i < itigou_x.size(); i++)
{
laser.m_LRFClsPoints[0][i].x = itigou_x[i];
laser.m_LRFClsPoints[0][i].y = itigou_y[i];
}
itigou_x.clear();
itigou_y.clear();
nigou_x.clear();
nigou_y.clear();
}
}
}
pthread_mutex_lock(&mutex_target);
m_PF.update(&laser);
pthread_mutex_unlock(&mutex_target);
ros::Time begin = ros::Time::now();
if (m_PF.m_ParticleFilter.size() > 0)
{
std::cout << "Time " << begin << " Number of PFs " << m_PF.m_ParticleFilter.size() << std::endl;
}
if (!(iteration % 100000))
{
laser.GetBackLRFDataGaussian();
}
r.sleep();
iteration ++;
}
cvReleaseMat(&Temp);
cvReleaseMat(&m_Rotate);
cvReleaseMat(&m_Translate);
}
void LaserSensingCallback(const sensor_msgs::LaserScan::ConstPtr &scan)
{
pthread_mutex_lock(&mutex_laser);
int num = floor((scan->angle_max - scan->angle_min) / scan->angle_increment);
if ( scanData.size() == 0 )
scanData.resize(num);
scanData = scan->ranges;
pthread_mutex_unlock(&mutex_laser);
CallbackCalled = true;
}
void LaserSensingCallback1(const sensor_msgs::LaserScan::ConstPtr &scan)
{
pthread_mutex_lock(&mutex_laser);
int num = floor((scan->angle_max - scan->angle_min) / scan->angle_increment);
if ( scanData1.size() == 0 )
scanData1.resize(num);
scanData1 = scan->ranges;
pthread_mutex_unlock(&mutex_laser);
CallbackCalled = true;
}
int main( int argc, char **argv )
{
pthread_t thread_p;
pthread_t thread_v;
ros::MultiThreadedSpinner spinner(4);
ros::init(argc, argv, "moving_object_tracker");
ros::NodeHandle n;
ros::Publisher pub = n.advertise<tms_msg_ss::tracking_points>("tracking_points", 10);
ros::Subscriber sub = n.subscribe("/urg2/most_intense" , 10, LaserSensingCallback);
ros::Subscriber sub1 = n.subscribe("/urg1/most_intense" , 10, LaserSensingCallback1);
if ( pthread_create( &thread_v, NULL, Visualization, (void *)&pub) )
{
printf("error creating thread.");
abort();
}
if ( pthread_create( &thread_p, NULL, Processing, NULL) )
{
printf("error creating thread.");
abort();
}
spinner.spin();
ros::waitForShutdown();
if ( pthread_join( thread_p, NULL) )
{
printf("error joining thread.");
abort();
}
if ( pthread_join( thread_v, NULL) )
{
printf("error joining thread.");
abort();
}
scanData.clear();
return 0;
}
<|endoftext|> |
<commit_before>/* listener.cpp
* Copyright (C) 2003 Tommi Maekitalo
*
* 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
* is provided AS IS, WITHOUT ANY WARRANTY; without even the implied
* warranty of MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE, and
* NON-INFRINGEMENT. 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 St, Fifth Floor, Boston, MA 02110-1301 USA
*
* In addition, as a special exception, the copyright holders give
* permission to link the code of portions of this program with the
* OpenSSL library under certain conditions as described in each
* individual source file, and distribute linked combinations
* including the two.
* You must obey the GNU General Public License in all respects
* for all of the code used other than OpenSSL. If you modify
* file(s) with this exception, you may extend this exception to your
* version of the file(s), but you are not obligated to do so. If you
* do not wish to do so, delete this exception statement from your
* version. If you delete this exception statement from all source
* files in the program, then also delete it here.
*/
#include "tnt/listener.h"
#include "tnt/tntnet.h"
#include <cxxtools/log.h>
#include <errno.h>
#include <unistd.h>
#ifdef USE_SSL
# include "tnt/ssl.h"
#endif
log_define("tntnet.listener")
static void doListenRetry(cxxtools::net::Server& server,
const char* ipaddr, unsigned short int port)
{
for (unsigned n = 1; true; ++n)
{
try
{
log_debug("listen " << ipaddr << ':' << port);
server.listen(ipaddr, port, tnt::Listener::getBacklog());
return;
}
catch (const cxxtools::net::Exception& e)
{
log_debug("cxxtools::net::Exception caught: errno=" << e.getErrno() << " msg=" << e.what());
if (e.getErrno() != EADDRINUSE || n > tnt::Listener::getListenRetry())
{
log_debug("rethrow exception");
throw;
}
log_warn("address " << ipaddr << ':' << port << " in use - retry; n = " << n);
::sleep(1);
}
}
}
namespace tnt
{
void ListenerBase::doStop()
{
log_warn("stop listener " << ipaddr << ':' << port);
try
{
// connect once to wake up listener, so it will check stop-flag
cxxtools::net::Stream(ipaddr, port);
}
catch (const std::exception& e)
{
log_error(e.what());
}
}
int Listener::backlog = 16;
unsigned Listener::listenRetry = 5;
Listener::Listener(const std::string& ipaddr, unsigned short int port, Jobqueue& q)
: ListenerBase(ipaddr, port),
queue(q)
{
log_info("listen ip=" << ipaddr << " port=" << port);
doListenRetry(server, ipaddr.c_str(), port);
}
void Listener::run()
{
// accept-loop
log_debug("enter accept-loop");
while (!Tntnet::shouldStop())
{
try
{
Tcpjob* j = new Tcpjob;
Jobqueue::JobPtr p(j);
j->accept(server);
log_debug("connection accepted");
if (Tntnet::shouldStop())
break;
queue.put(p);
}
catch (const std::exception& e)
{
log_error("error in accept-loop: " << e.what());
}
}
log_debug("stop listener");
}
#ifdef USE_SSL
Ssllistener::Ssllistener(const char* certificateFile,
const char* keyFile,
const std::string& ipaddr, unsigned short int port,
Jobqueue& q)
: ListenerBase(ipaddr, port),
server(certificateFile, keyFile),
queue(q)
{
log_info("listen ip=" << ipaddr << " port=" << port << " (ssl)");
doListenRetry(server, ipaddr.c_str(), port);
}
void Ssllistener::run()
{
// accept-loop
log_debug("enter accept-loop (ssl)");
while (!Tntnet::shouldStop())
{
try
{
SslTcpjob* j = new SslTcpjob;
Jobqueue::JobPtr p(j);
j->accept(server);
if (Tntnet::shouldStop())
break;
queue.put(p);
}
catch (const std::exception& e)
{
log_error("error in ssl-accept-loop: " << e.what());
}
}
log_debug("stop ssl-listener");
}
#endif // USE_SSL
}
<commit_msg>try harder to shut down listener<commit_after>/* listener.cpp
* Copyright (C) 2003 Tommi Maekitalo
*
* 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
* is provided AS IS, WITHOUT ANY WARRANTY; without even the implied
* warranty of MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE, and
* NON-INFRINGEMENT. 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 St, Fifth Floor, Boston, MA 02110-1301 USA
*
* In addition, as a special exception, the copyright holders give
* permission to link the code of portions of this program with the
* OpenSSL library under certain conditions as described in each
* individual source file, and distribute linked combinations
* including the two.
* You must obey the GNU General Public License in all respects
* for all of the code used other than OpenSSL. If you modify
* file(s) with this exception, you may extend this exception to your
* version of the file(s), but you are not obligated to do so. If you
* do not wish to do so, delete this exception statement from your
* version. If you delete this exception statement from all source
* files in the program, then also delete it here.
*/
#include "tnt/listener.h"
#include "tnt/tntnet.h"
#include <cxxtools/log.h>
#include <errno.h>
#include <unistd.h>
#ifdef USE_SSL
# include "tnt/ssl.h"
#endif
log_define("tntnet.listener")
static void doListenRetry(cxxtools::net::Server& server,
const char* ipaddr, unsigned short int port)
{
for (unsigned n = 1; true; ++n)
{
try
{
log_debug("listen " << ipaddr << ':' << port);
server.listen(ipaddr, port, tnt::Listener::getBacklog());
return;
}
catch (const cxxtools::net::Exception& e)
{
log_debug("cxxtools::net::Exception caught: errno=" << e.getErrno() << " msg=" << e.what());
if (e.getErrno() != EADDRINUSE || n > tnt::Listener::getListenRetry())
{
log_debug("rethrow exception");
throw;
}
log_warn("address " << ipaddr << ':' << port << " in use - retry; n = " << n);
::sleep(1);
}
}
}
namespace tnt
{
void ListenerBase::doStop()
{
log_warn("stop listener " << ipaddr << ':' << port);
try
{
// connect once to wake up listener, so it will check stop-flag
cxxtools::net::Stream(ipaddr, port);
}
catch (const std::exception& e)
{
log_warn("error waking up listener: " << e.what() << " try 127.0.0.1");
cxxtools::net::Stream("127.0.0.1", port);
}
}
int Listener::backlog = 16;
unsigned Listener::listenRetry = 5;
Listener::Listener(const std::string& ipaddr, unsigned short int port, Jobqueue& q)
: ListenerBase(ipaddr, port),
queue(q)
{
log_info("listen ip=" << ipaddr << " port=" << port);
doListenRetry(server, ipaddr.c_str(), port);
}
void Listener::run()
{
// accept-loop
log_debug("enter accept-loop");
while (!Tntnet::shouldStop())
{
try
{
Tcpjob* j = new Tcpjob;
Jobqueue::JobPtr p(j);
j->accept(server);
log_debug("connection accepted");
if (Tntnet::shouldStop())
break;
queue.put(p);
}
catch (const std::exception& e)
{
log_error("error in accept-loop: " << e.what());
}
}
log_debug("stop listener");
}
#ifdef USE_SSL
Ssllistener::Ssllistener(const char* certificateFile,
const char* keyFile,
const std::string& ipaddr, unsigned short int port,
Jobqueue& q)
: ListenerBase(ipaddr, port),
server(certificateFile, keyFile),
queue(q)
{
log_info("listen ip=" << ipaddr << " port=" << port << " (ssl)");
doListenRetry(server, ipaddr.c_str(), port);
}
void Ssllistener::run()
{
// accept-loop
log_debug("enter accept-loop (ssl)");
while (!Tntnet::shouldStop())
{
try
{
SslTcpjob* j = new SslTcpjob;
Jobqueue::JobPtr p(j);
j->accept(server);
if (Tntnet::shouldStop())
break;
queue.put(p);
}
catch (const std::exception& e)
{
log_error("error in ssl-accept-loop: " << e.what());
}
}
log_debug("stop ssl-listener");
}
#endif // USE_SSL
}
<|endoftext|> |
<commit_before>// vim:ts=2:sw=2:expandtab:autoindent:filetype=cpp:
/*
Copyright (c) 2008 Ash Berlin
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 "flusspferd/class.hpp"
#include "flusspferd/create.hpp"
#include "flusspferd/native_object_base.hpp"
#include "flusspferd/string.hpp"
#include "flusspferd/tracer.hpp"
#include <new>
#include "sqlite3.h"
using namespace flusspferd;
// Put everything in an anon-namespace so typeid wont clash ever.
namespace {
void raise_sqlite_error(sqlite3* db);
///////////////////////////
// Classes
///////////////////////////
class sqlite3 : public native_object_base {
public:
struct class_info : public flusspferd::class_info {
static char const *full_name() { return "SQLite3"; }
typedef boost::mpl::bool_<true> constructible;
static char const *constructor_name() { return "SQLite3"; }
static void augment_constructor(object &ctor);
static object create_prototype();
};
sqlite3(object const &obj, call_context &x);
~sqlite3();
protected:
//void trace(tracer &);
private: // JS methods
::sqlite3 *db;
void close();
void cursor(call_context &x);
};
class sqlite3_cursor : public native_object_base {
public:
struct class_info : public flusspferd::class_info {
typedef boost::mpl::bool_<false> constructible;
static char const *full_name() { return "SQLite3.Cursor"; }
static char const* constructor_name() { return "Cursor"; }
static object create_prototype();
};
sqlite3_cursor(object const &obj, sqlite3_stmt *sth);
~sqlite3_cursor();
private:
sqlite3_stmt *sth;
// Methods that help wiht binding
void bind_array(array &a, size_t num_binds);
void bind_dict(object &o, size_t num_binds);
void do_bind_param(int n, value v);
private: // JS methods
void finish();
void reset();
object next();
void bind(call_context &x);
};
///////////////////////////
// import hook
extern "C" value flusspferd_load(object container)
{
return load_class<sqlite3>(container);
}
///////////////////////////
// Set version properties on constructor object
void sqlite3::class_info::augment_constructor(object &ctor)
{
// Set static properties on the constructor
ctor.define_property("version", SQLITE_VERSION_NUMBER,
object::read_only_property | object::permanent_property);
ctor.define_property("versionStr", string(SQLITE_VERSION),
object::read_only_property | object::permanent_property);
load_class<sqlite3_cursor>(ctor);
}
///////////////////////////
object sqlite3::class_info::create_prototype()
{
object proto = create_object();
create_native_method(proto, "cursor", 1);
create_native_method(proto, "close", 0);
return proto;
}
///////////////////////////
sqlite3::sqlite3(object const &obj, call_context &x)
: native_object_base(obj),
db(NULL)
{
if (x.arg.size() == 0)
throw exception ("SQLite3 requires more than 0 arguments");
string dsn = x.arg[0];
// TODO: pull arguments from 2nd/options argument
if (sqlite3_open(dsn.c_str(), &db) != SQLITE_OK) {
if (db)
raise_sqlite_error(db);
else
throw std::bad_alloc(); // out of memory. better way to signal this?
}
register_native_method("cursor", &sqlite3::cursor);
register_native_method("close", &sqlite3::close);
}
///////////////////////////
sqlite3::~sqlite3()
{
close();
}
///////////////////////////
void sqlite3::close()
{
if (db) {
sqlite3_close(db);
db = NULL;
}
}
///////////////////////////
void sqlite3::cursor(call_context &x) {
local_root_scope scope;
if (!db)
throw exception("SQLite3.cursor called on closed dbh");
if (x.arg.size() < 1)
throw exception ("cursor requires more than 0 arguments");
string sql = x.arg[0].to_string();
size_t n_bytes = sql.length() * 2;
sqlite3_stmt *sth;
char16_t *tail; // uncompiled part of the sql (when multiple stmts)
if (sqlite3_prepare16_v2(db, sql.data(), n_bytes, &sth, (const void**)&tail) != SQLITE_OK)
{
raise_sqlite_error(db);
}
object cursor = create_native_object<sqlite3_cursor>(object(), sth);
// TODO: remove tail and set it seperately
cursor.define_property("sql", sql);
x.result = cursor;
}
///////////////////////////
object sqlite3_cursor::class_info::create_prototype() {
object proto = create_object();
create_native_method(proto, "finish", 0);
create_native_method(proto, "reset", 0);
create_native_method(proto, "next", 0);
create_native_method(proto, "bind", 0);
return proto;
}
///////////////////////////
// 'Private' constructor that is called from sqlite3::cursor
sqlite3_cursor::sqlite3_cursor(object const &obj, sqlite3_stmt *_sth)
: native_object_base(obj),
sth(_sth)
{
register_native_method("finish", &sqlite3_cursor::finish);
register_native_method("reset", &sqlite3_cursor::reset);
register_native_method("next", &sqlite3_cursor::next);
register_native_method("bind", &sqlite3_cursor::bind);
}
///////////////////////////
sqlite3_cursor::~sqlite3_cursor()
{
finish();
}
///////////////////////////
void sqlite3_cursor::finish() {
if (sth) {
sqlite3_finalize(sth);
sth = NULL;
}
}
///////////////////////////
void sqlite3_cursor::reset() {
}
///////////////////////////
object sqlite3_cursor::next() {
return object();
}
///////////////////////////
// JS method
void sqlite3_cursor::bind(call_context &x) {
local_root_scope scope;
size_t num_binds = sqlite3_bind_parameter_count(sth);
if (!num_binds)
return;
if (x.arg[0].is_object()) {
object o = x.arg[0].get_object();
if (o.is_array()) {
array a = o;
bind_array(a, num_binds);
}
else
bind_dict(o, num_binds);
} else if (num_binds == 1) {
// Dont document that we accept a single param
do_bind_param(1, x.arg[0]);
} else {
throw exception("SQLite3.Cursor.bind requires an array or an object as its only argument");
}
}
///////////////////////////
// bind numbered params
void sqlite3_cursor::bind_array(array &a, size_t num_binds) {
// Pull bind param 1 (the first) from array index 0 (also the first)
for (size_t n = 1; n <= num_binds; n++) {
value bind = a.get_element(n-1);
if (!bind.is_void())
do_bind_param(n, bind);
}
}
///////////////////////////
// bind named or numbered params
void sqlite3_cursor::bind_dict(object &o, size_t num_binds) {
for (size_t n = 1; n <= num_binds; n++) {
const char* name = sqlite3_bind_parameter_name(sth, n);
value bind;
if (!name) {
// Possibly a '?' unnnamed param
// TODO: This will break when n is > 2^31.
bind = o.get_property( value( int(n) ) );
} else {
// Named param
bind = o.get_property(name);
}
if (!bind.is_void())
do_bind_param(n, bind);
}
}
///////////////////////////
// Bind the actual para
void sqlite3_cursor::do_bind_param(int n, value v) {
int ok;
if (v.is_int()) {
ok = sqlite3_bind_int(sth, n, v.get_int());
} else if (v.is_double()) {
ok = sqlite3_bind_double(sth, n, v.get_double());
} else if (v.is_null()) {
ok = sqlite3_bind_null(sth, n);
} else {
// Default, stringify the object
string bind = v.to_string();
ok = sqlite3_bind_text16(sth, n, bind.data(), bind.length()*2, SQLITE_TRANSIENT);
}
if (ok != SQLITE_OK)
raise_sqlite_error( sqlite3_db_handle(sth) );
}
///////////////////////////
// Helper function
void raise_sqlite_error(::sqlite3* db)
{
std::string s = "SQLite3 Error: ";
s += sqlite3_errmsg(db);
throw exception(s);
}
}
<commit_msg>Plugins/sqlite3: Implement rest of cursor methods<commit_after>// vim:ts=2:sw=2:expandtab:autoindent:filetype=cpp:
/*
Copyright (c) 2008 Ash Berlin
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 "flusspferd/class.hpp"
#include "flusspferd/create.hpp"
#include "flusspferd/native_object_base.hpp"
#include "flusspferd/string.hpp"
#include "flusspferd/tracer.hpp"
#include <new>
#include <sstream>
#include "sqlite3.h"
using namespace flusspferd;
// Put everything in an anon-namespace so typeid wont clash ever.
namespace {
void raise_sqlite_error(sqlite3* db);
///////////////////////////
// Classes
///////////////////////////
class sqlite3 : public native_object_base {
public:
struct class_info : public flusspferd::class_info {
static char const *full_name() { return "SQLite3"; }
typedef boost::mpl::bool_<true> constructible;
static char const *constructor_name() { return "SQLite3"; }
static void augment_constructor(object &ctor);
static object create_prototype();
};
sqlite3(object const &obj, call_context &x);
~sqlite3();
protected:
//void trace(tracer &);
private: // JS methods
::sqlite3 *db;
void close();
void cursor(call_context &x);
};
class sqlite3_cursor : public native_object_base {
public:
struct class_info : public flusspferd::class_info {
typedef boost::mpl::bool_<false> constructible;
static char const *full_name() { return "SQLite3.Cursor"; }
static char const* constructor_name() { return "Cursor"; }
static object create_prototype();
};
sqlite3_cursor(object const &obj, sqlite3_stmt *sth);
~sqlite3_cursor();
private:
sqlite3_stmt *sth;
enum {
CursorState_Init = 0,
CursorState_InProgress = 1,
CursorState_Finished = 2,
CursorState_Errored = 3
} state;
// Methods that help wiht binding
void bind_array(array &a, size_t num_binds);
void bind_dict(object &o, size_t num_binds);
void do_bind_param(int n, value v);
private: // JS methods
void close();
void reset();
object next();
void bind(call_context &x);
};
///////////////////////////
// import hook
extern "C" value flusspferd_load(object container)
{
return load_class<sqlite3>(container);
}
///////////////////////////
// Set version properties on constructor object
void sqlite3::class_info::augment_constructor(object &ctor)
{
// Set static properties on the constructor
ctor.define_property("version", SQLITE_VERSION_NUMBER,
object::read_only_property | object::permanent_property);
ctor.define_property("versionStr", string(SQLITE_VERSION),
object::read_only_property | object::permanent_property);
load_class<sqlite3_cursor>(ctor);
}
///////////////////////////
object sqlite3::class_info::create_prototype()
{
object proto = create_object();
create_native_method(proto, "cursor", 1);
create_native_method(proto, "close", 0);
return proto;
}
///////////////////////////
sqlite3::sqlite3(object const &obj, call_context &x)
: native_object_base(obj),
db(NULL)
{
if (x.arg.size() == 0)
throw exception ("SQLite3 requires more than 0 arguments");
string dsn = x.arg[0];
// TODO: pull arguments from 2nd/options argument
if (sqlite3_open(dsn.c_str(), &db) != SQLITE_OK) {
if (db)
raise_sqlite_error(db);
else
throw std::bad_alloc(); // out of memory. better way to signal this?
}
register_native_method("cursor", &sqlite3::cursor);
register_native_method("close", &sqlite3::close);
}
///////////////////////////
sqlite3::~sqlite3()
{
close();
}
///////////////////////////
void sqlite3::close()
{
if (db) {
sqlite3_close(db);
db = NULL;
}
}
///////////////////////////
void sqlite3::cursor(call_context &x) {
local_root_scope scope;
if (!db)
throw exception("SQLite3.cursor called on closed dbh");
if (x.arg.size() < 1)
throw exception ("cursor requires more than 0 arguments");
string sql = x.arg[0].to_string();
size_t n_bytes = sql.length() * 2;
sqlite3_stmt *sth;
char16_t *tail; // uncompiled part of the sql (when multiple stmts)
if (sqlite3_prepare16_v2(db, sql.data(), n_bytes, &sth, (const void**)&tail) != SQLITE_OK)
{
raise_sqlite_error(db);
}
object cursor = create_native_object<sqlite3_cursor>(object(), sth);
// TODO: remove tail and set it seperately
cursor.define_property("sql", sql);
x.result = cursor;
}
///////////////////////////
object sqlite3_cursor::class_info::create_prototype() {
object proto = create_object();
create_native_method(proto, "close", 0);
create_native_method(proto, "reset", 0);
create_native_method(proto, "next", 0);
create_native_method(proto, "bind", 0);
return proto;
}
///////////////////////////
// 'Private' constructor that is called from sqlite3::cursor
sqlite3_cursor::sqlite3_cursor(object const &obj, sqlite3_stmt *_sth)
: native_object_base(obj),
sth(_sth),
state(CursorState_Init)
{
register_native_method("close", &sqlite3_cursor::close);
register_native_method("reset", &sqlite3_cursor::reset);
register_native_method("next", &sqlite3_cursor::next);
register_native_method("bind", &sqlite3_cursor::bind);
}
///////////////////////////
sqlite3_cursor::~sqlite3_cursor()
{
close();
}
///////////////////////////
void sqlite3_cursor::close() {
if (sth) {
sqlite3_finalize(sth);
sth = NULL;
}
}
///////////////////////////
void sqlite3_cursor::reset() {
sqlite3_reset(sth);
state = CursorState_Init;
}
///////////////////////////
object sqlite3_cursor::next() {
local_root_scope scope;
if (!sth)
throw exception("SQLite3.Cursor.next called on closed cursor");
switch (state) {
case CursorState_Finished:
// We've seen the last row, remember it and return the EOF indicator
return object();
case CursorState_Errored:
throw exception("SQLite3.Cursor: This cursor has seen an error and "
"needs to be reset");
default:
break;
}
int code = sqlite3_step(sth);
if (code == SQLITE_DONE) {
state = CursorState_Finished;
return object();
} else if (code != SQLITE_ROW) {
if (sqlite3_errcode( sqlite3_db_handle(sth) ) != SQLITE_OK) {
state = CursorState_Errored;
raise_sqlite_error( sqlite3_db_handle(sth) );
} else {
throw exception("SQLite3.Cursor: database reported misuse error. "
"Please try again");
}
}
state = CursorState_InProgress;
// Build up the row object.
array row = create_array();
int cols = sqlite3_column_count(sth);
for (int i=0; i < cols; i++)
{
int type = sqlite3_column_type(sth, i);
value col;
switch (type) {
case SQLITE_INTEGER:
col = sqlite3_column_int(sth, i);
break;
case SQLITE_FLOAT:
col = sqlite3_column_double(sth, i);
break;
case SQLITE_NULL:
col = object();
break;
//case SQLITE_BLOB:
// TODO: Support binary data!
case SQLITE_TEXT:
char16_t *bytes = (char16_t*)sqlite3_column_text16(sth, i);
if (!bytes)
throw std::bad_alloc();
// Its actualy num of *bytes* not chars
size_t nbytes = sqlite3_column_bytes16(sth, i)/2;
col = string(bytes, nbytes);
break;
default:
std::stringstream ss;
ss << "SQLite3.Cursor.next: Unknown column type " << type;
throw exception(ss.str());
}
row.set_element(i, col);
}
return row;
}
///////////////////////////
// JS method
void sqlite3_cursor::bind(call_context &x) {
local_root_scope scope;
size_t num_binds = sqlite3_bind_parameter_count(sth);
if (!num_binds)
return;
if (x.arg[0].is_object()) {
object o = x.arg[0].get_object();
if (o.is_array()) {
array a = o;
bind_array(a, num_binds);
}
else
bind_dict(o, num_binds);
} else if (num_binds == 1) {
// Dont document that we accept a single param
do_bind_param(1, x.arg[0]);
} else {
throw exception("SQLite3.Cursor.bind requires an array or an object as its only argument");
}
}
///////////////////////////
// bind numbered params
void sqlite3_cursor::bind_array(array &a, size_t num_binds) {
// Pull bind param 1 (the first) from array index 0 (also the first)
for (size_t n = 1; n <= num_binds; n++) {
value bind = a.get_element(n-1);
if (!bind.is_void())
do_bind_param(n, bind);
}
}
///////////////////////////
// bind named or numbered params
void sqlite3_cursor::bind_dict(object &o, size_t num_binds) {
for (size_t n = 1; n <= num_binds; n++) {
const char* name = sqlite3_bind_parameter_name(sth, n);
value bind;
if (!name) {
// Possibly a '?' unnnamed param
// TODO: This will break when n is > 2^31.
bind = o.get_property( value( int(n) ) );
} else {
// Named param
bind = o.get_property(name);
}
if (!bind.is_void())
do_bind_param(n, bind);
}
}
///////////////////////////
// Bind the actual para
void sqlite3_cursor::do_bind_param(int n, value v) {
int ok;
if (v.is_int()) {
ok = sqlite3_bind_int(sth, n, v.get_int());
} else if (v.is_double()) {
ok = sqlite3_bind_double(sth, n, v.get_double());
} else if (v.is_null()) {
ok = sqlite3_bind_null(sth, n);
} else {
// Default, stringify the object
string bind = v.to_string();
ok = sqlite3_bind_text16(sth, n, bind.data(), bind.length()*2, SQLITE_TRANSIENT);
}
if (ok != SQLITE_OK)
raise_sqlite_error( sqlite3_db_handle(sth) );
}
///////////////////////////
// Helper function
void raise_sqlite_error(::sqlite3* db)
{
std::string s = "SQLite3 Error: ";
s += sqlite3_errmsg(db);
throw exception(s);
}
}
<|endoftext|> |
<commit_before>// Copyright (c) 2013 GitHub, Inc. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include <string.h>
#include "content/public/app/content_main.h"
namespace node {
int Start(int argc, char *argv[]);
}
#if defined(OS_WIN)
#include <windows.h> // NOLINT
#include <shellapi.h> // NOLINT
#include "app/atom_main_delegate.h"
#include "content/public/app/startup_helper_win.h"
#include "sandbox/win/src/sandbox_types.h"
int APIENTRY wWinMain(HINSTANCE instance, HINSTANCE, wchar_t* cmd, int) {
int argc = 0;
wchar_t** wargv = ::CommandLineToArgvW(cmd, &argc);
if (argc > 1 && wcscmp(wargv[1], L"--atom-child_process-fork") == 0) {
// Convert argv to to UTF8
char** argv = new char*[argc];
for (int i = 0; i < argc; i++) {
// Compute the size of the required buffer
DWORD size = WideCharToMultiByte(CP_UTF8,
0,
wargv[i],
-1,
NULL,
0,
NULL,
NULL);
if (size == 0) {
// This should never happen.
fprintf(stderr, "Could not convert arguments to utf8.");
exit(1);
}
// Do the actual conversion
argv[i] = new char[size];
DWORD result = WideCharToMultiByte(CP_UTF8,
0,
wargv[i],
-1,
argv[i],
size,
NULL,
NULL);
if (result == 0) {
// This should never happen.
fprintf(stderr, "Could not convert arguments to utf8.");
exit(1);
}
}
// Now that conversion is done, we can finally start.
argv[1] = argv[0];
return node::Start(argc - 1, argv + 1);
}
sandbox::SandboxInterfaceInfo sandbox_info = {0};
content::InitializeSandboxInfo(&sandbox_info);
atom::AtomMainDelegate delegate;
return content::ContentMain(instance, &sandbox_info, &delegate);
}
#else // defined(OS_WIN)
#include "app/atom_library_main.h"
int main(int argc, const char* argv[]) {
if (argc > 1 && strcmp(argv[1], "--atom-child_process-fork") == 0) {
argv[1] = argv[0];
return node::Start(argc - 1, const_cast<char**>(argv + 1));
}
return AtomMain(argc, argv);
}
#endif
<commit_msg>Don't use the cmd paramter passed by WinMain.<commit_after>// Copyright (c) 2013 GitHub, Inc. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include <string.h>
#include "content/public/app/content_main.h"
namespace node {
int Start(int argc, char *argv[]);
}
#if defined(OS_WIN)
#include <windows.h> // NOLINT
#include <shellapi.h> // NOLINT
#include "app/atom_main_delegate.h"
#include "content/public/app/startup_helper_win.h"
#include "sandbox/win/src/sandbox_types.h"
int APIENTRY wWinMain(HINSTANCE instance, HINSTANCE, wchar_t* cmd, int) {
int argc = 0;
wchar_t** wargv = ::CommandLineToArgvW(::GetCommandLineW(), &argc);
if (argc > 1 && wcscmp(wargv[1], L"--atom-child_process-fork") == 0) {
// Convert argv to to UTF8
char** argv = new char*[argc];
for (int i = 0; i < argc; i++) {
// Compute the size of the required buffer
DWORD size = WideCharToMultiByte(CP_UTF8,
0,
wargv[i],
-1,
NULL,
0,
NULL,
NULL);
if (size == 0) {
// This should never happen.
fprintf(stderr, "Could not convert arguments to utf8.");
exit(1);
}
// Do the actual conversion
argv[i] = new char[size];
DWORD result = WideCharToMultiByte(CP_UTF8,
0,
wargv[i],
-1,
argv[i],
size,
NULL,
NULL);
if (result == 0) {
// This should never happen.
fprintf(stderr, "Could not convert arguments to utf8.");
exit(1);
}
}
// Now that conversion is done, we can finally start.
argv[1] = argv[0];
return node::Start(argc - 1, argv + 1);
}
sandbox::SandboxInterfaceInfo sandbox_info = {0};
content::InitializeSandboxInfo(&sandbox_info);
atom::AtomMainDelegate delegate;
return content::ContentMain(instance, &sandbox_info, &delegate);
}
#else // defined(OS_WIN)
#include "app/atom_library_main.h"
int main(int argc, const char* argv[]) {
if (argc > 1 && strcmp(argv[1], "--atom-child_process-fork") == 0) {
argv[1] = argv[0];
return node::Start(argc - 1, const_cast<char**>(argv + 1));
}
return AtomMain(argc, argv);
}
#endif
<|endoftext|> |
<commit_before>#include "MergeOperators.hpp"
#include "macros.hpp"
#include <iostream>
#include <rocksdb/env.h>
bool HOT Int64AddOperator::Merge(
const rocksdb::Slice& key,
const rocksdb::Slice* existing_value,
const rocksdb::Slice& value,
std::string* new_value,
rocksdb::Logger* logger) const {
// assuming 0 if no existing value
int64_t existing = 0;
if (existing_value != nullptr) {
if (unlikely(existing_value->size() != sizeof(int64_t))) {
// if existing_value is corrupted, treat it as 0
Log(logger, "existing value corruption");
existing = 0;
} else {
memcpy(&existing, existing_value->data(), sizeof(int64_t));
}
}
int64_t operand;
if (unlikely(value.size() != sizeof(int64_t))) {
// if existing_value is corrupted, treat it as 0
Log(logger, "operand value corruption");
operand = 0;
} else {
memcpy(&operand, value.data(), sizeof(int64_t));
}
int64_t result = existing + operand;
*new_value = std::move(std::string((char*)&result, sizeof(int64_t)));
//Errors are treated as 0.
return true;
}
const char* Int64AddOperator::Name() const {
return "Int64AddOperator";
}
bool HOT DMulOperator::Merge(
const rocksdb::Slice& key,
const rocksdb::Slice* existing_value,
const rocksdb::Slice& value,
std::string* new_value,
rocksdb::Logger* logger) const {
//Assuming 0 if no existing value
double existing = 0;
if (existing_value) {
if (unlikely(existing_value->size() != sizeof(double))) {
// if existing_value is corrupted, treat it as 0
Log(logger, "existing value corruption");
existing = 0;
} else {
memcpy(&existing, existing_value->data(), sizeof(double));
}
}
double operand;
if (unlikely(value.size() != sizeof(double))) {
// if existing_value is corrupted, treat it as 0
Log(logger, "operand value corruption");
operand = 0;
} else {
memcpy(&operand, value.data(), sizeof(double));
}
double result = existing * operand;
*new_value = std::move(std::string((char*)&result, sizeof(double)));
//Errors are treated as 0.
return true;
}
const char* DMulOperator::Name() const {
return "DMulOperator";
}
bool HOT DAddOperator::Merge(
const rocksdb::Slice& key,
const rocksdb::Slice* existing_value,
const rocksdb::Slice& value,
std::string* new_value,
rocksdb::Logger* logger) const {
//Assuming 0 if no existing value
double existing = 0;
if (existing_value) {
if (unlikely(existing_value->size() != sizeof(double))) {
// if existing_value is corrupted, treat it as 0
Log(logger, "existing value corruption");
existing = 0;
} else {
memcpy(&existing, existing_value->data(), sizeof(double));
}
}
double operand;
if (unlikely(value.size() != sizeof(double))) {
// if existing_value is corrupted, treat it as 0
Log(logger, "operand value corruption");
operand = 0;
} else {
memcpy(&operand, value.data(), sizeof(double));
}
double result = existing + operand;
*new_value = std::move(std::string((char*)&result, sizeof(double)));
//Errors are treated as 0.
return true;
}
const char* DAddOperator::Name() const {
return "DAddOperator";
}
bool HOT AppendOperator::Merge(
const rocksdb::Slice& key,
const rocksdb::Slice* existing_value,
const rocksdb::Slice& value,
std::string* new_value,
rocksdb::Logger* logger) const {
// assuming empty if no existing value
std::string existing;
if (existing_value) {
existing = existing_value->ToString();
}
*new_value = std::move(existing + value.ToString());
//Errors are treated as 0.
return true;
}
const char* AppendOperator::Name() const {
return "AppendOperator";
}
bool ReplaceOperator::Merge(
const rocksdb::Slice& key,
const rocksdb::Slice* existing_value,
const rocksdb::Slice& value,
std::string* new_value,
rocksdb::Logger* logger) const {
*new_value = value.ToString();
return true;
}
const char* ReplaceOperator::Name() const {
return "ReplaceOperator";
}
const char* ListAppendOperator::Name() const {
return "ListAppendOperator";
}
bool HOT ListAppendOperator::Merge(
const rocksdb::Slice& key,
const rocksdb::Slice* existing_value,
const rocksdb::Slice& value,
std::string* new_value,
rocksdb::Logger* logger) const {
// assuming empty if no existing value
std::string existing;
if (existing_value) {
existing = existing_value->ToString();
}
//Note that it is not inherently safe to assume the new value size is <
uint32_t newValLength = value.size();
//In between the old and the new value, we need to add the 4 bytes size
*new_value = std::move(existing + std::string((const char*)&newValLength, sizeof(uint32_t)) + value.ToString());
}
bool HOT ANDOperator::Merge(
const rocksdb::Slice& key,
const rocksdb::Slice* existing_value,
const rocksdb::Slice& value,
std::string* new_value,
rocksdb::Logger* logger) const {
//Assuming 0 if no existing value
std::string existing;
if (existing_value) {
existing = existing_value->ToString();
} else {
//Skip complex boolean logic, just copy value
*new_value = value.ToString();
return true;
}
//Extract raw binary info
const char* existingData = existing.data();
size_t existingSize = existing.size();
const char* valueData = value.data();
size_t valueSize = value.size();
/*
* Allocate the result memory (will be copied to the result string later)
* Writing to a string's data() could produce undefined behaviour
* with some C++ STL implementations
*/
size_t dstSize = std::max(existingSize, valueSize);
char* dst = new char[dstSize];
/*
* Perform bytewise boolean operation, ignoring extra bytes
* TODO: Optimize to use 128+-bit SSE / 64 bit / 32 bit operator,
* or check if the compiler is intelligent enough to do that
*/
size_t numCommonBytes = std::min(existingSize, valueSize);
for(size_t i = 0; i < numCommonBytes; i++) {
dst[i] = existingData[i] & valueData[i];
}
//Copy remaining bytes, if any
if(existingSize > numCommonBytes) {
memcpy(dst + numCommonBytes, existingData + numCommonBytes, existingSize - numCommonBytes);
} else if(valueSize > numCommonBytes) {
memcpy(dst + numCommonBytes, valueData + numCommonBytes, valueSize - numCommonBytes);
} //Else: Both have the same size, nothing to be done
//Copy dst buffer to new_value string
*new_value = std::move(std::string(dst, dstSize));
//Free allocated temporary resources
delete[] dst;
//This function does not have any logical error condition
return true;
}
const char* ANDOperator::Name() const {
return "ANDOperator";
}
bool HOT OROperator::Merge(
const rocksdb::Slice& key,
const rocksdb::Slice* existing_value,
const rocksdb::Slice& value,
std::string* new_value,
rocksdb::Logger* logger) const {
//Assuming 0 if no existing value
std::string existing;
if (existing_value) {
existing = existing_value->ToString();
} else {
//Skip complex boolean logic, just copy value
*new_value = value.ToString();
return true;
}
//Extract raw binary info
const char* existingData = existing.data();
size_t existingSize = existing.size();
const char* valueData = value.data();
size_t valueSize = value.size();
/*
* Allocate the result memory (will be copied to the result string later)
* Writing to a string's data() could produce undefined behaviour
* with some C++ STL implementations
*/
size_t dstSize = std::max(existingSize, valueSize);
char* dst = new char[dstSize];
/*
* Perform bytewise boolean operation, ignoring extra bytes
* TODO: Optimize to use 128+-bit SSE / 64 bit / 32 bit operator,
* or check if the compiler is intelligent enough to do that
*/
size_t numCommonBytes = std::min(existingSize, valueSize);
for(size_t i = 0; i < numCommonBytes; i++) {
dst[i] = existingData[i] | valueData[i];
}
//Copy remaining bytes, if any
if(existingSize > numCommonBytes) {
memcpy(dst + numCommonBytes, existingData + numCommonBytes, existingSize - numCommonBytes);
} else if(valueSize > numCommonBytes) {
memcpy(dst + numCommonBytes, valueData + numCommonBytes, valueSize - numCommonBytes);
} //Else: Both have the same size, nothing to be done
//Copy dst buffer to new_value string
*new_value = std::move(std::string(dst, dstSize));
//Free allocated temporary resources
delete[] dst;
//This function does not have any logical error condition
return true;
}
const char* OROperator::Name() const {
return "OROperator";
}
bool HOT XOROperator::Merge(
const rocksdb::Slice& key,
const rocksdb::Slice* existing_value,
const rocksdb::Slice& value,
std::string* new_value,
rocksdb::Logger* logger) const {
//Assuming 0 if no existing value
std::string existing;
if (existing_value) {
existing = existing_value->ToString();
} else {
//Skip complex boolean logic, just copy value
*new_value = value.ToString();
return true;
}
//Extract raw binary info
const char* existingData = existing.data();
size_t existingSize = existing.size();
const char* valueData = value.data();
size_t valueSize = value.size();
/*
* Allocate the result memory (will be copied to the result string later)
* Writing to a string's data() could produce undefined behaviour
* with some C++ STL implementations
*/
size_t dstSize = std::max(existingSize, valueSize);
char* dst = new char[dstSize];
/*
* Perform bytewise boolean operation, ignoring extra bytes
* TODO: Optimize to use 128+-bit SSE / 64 bit / 32 bit operator,
* or check if the compiler is intelligent enough to do that
*/
size_t numCommonBytes = std::min(existingSize, valueSize);
for(size_t i = 0; i < numCommonBytes; i++) {
dst[i] = existingData[i] ^ valueData[i];
}
//Copy remaining bytes, if any
if(existingSize > numCommonBytes) {
memcpy(dst + numCommonBytes, existingData + numCommonBytes, existingSize - numCommonBytes);
} else if(valueSize > numCommonBytes) {
memcpy(dst + numCommonBytes, valueData + numCommonBytes, valueSize - numCommonBytes);
} //Else: Both have the same size, nothing to be done
//Copy dst buffer to new_value string
*new_value = std::move(std::string(dst, dstSize));
//Free allocated temporary resources
delete[] dst;
//This function does not have any logical error condition
return true;
}
const char* XOROperator::Name() const {
return "XOROperator";
}
std::shared_ptr<rocksdb::MergeOperator> createMergeOperator(
const std::string& mergeOperatorCode) {
if(mergeOperatorCode.empty()) {
//empty --> default
return std::make_shared<ReplaceOperator>();
} else if(mergeOperatorCode == "INT64ADD") {
return std::make_shared<Int64AddOperator>();
} else if(mergeOperatorCode == "DMUL") {
return std::make_shared<DMulOperator>();
} else if(mergeOperatorCode == "DADD") {
return std::make_shared<DAddOperator>();
} else if(mergeOperatorCode == "APPEND") {
return std::make_shared<AppendOperator>();
} else if(mergeOperatorCode == "REPLACE") { //Also handles REPLACE
return std::make_shared<ReplaceOperator>();
} else if(mergeOperatorCode == "AND") {
return std::make_shared<ANDOperator>();
} else if(mergeOperatorCode == "OR") {
return std::make_shared<OROperator>();
} else if(mergeOperatorCode == "XOR") {
return std::make_shared<XOROperator>();
} else if(mergeOperatorCode == "LISTAPPEND") {
return std::make_shared<ListAppendOperator>();
} else {
std::cerr << "Warning: Invalid merge operator code: " << mergeOperatorCode << std::endl;
return std::make_shared<ReplaceOperator>();
}
}<commit_msg>Fix merge operator return value<commit_after>#include "MergeOperators.hpp"
#include "macros.hpp"
#include <iostream>
#include <rocksdb/env.h>
bool HOT Int64AddOperator::Merge(
const rocksdb::Slice& key,
const rocksdb::Slice* existing_value,
const rocksdb::Slice& value,
std::string* new_value,
rocksdb::Logger* logger) const {
// assuming 0 if no existing value
int64_t existing = 0;
if (existing_value != nullptr) {
if (unlikely(existing_value->size() != sizeof(int64_t))) {
// if existing_value is corrupted, treat it as 0
Log(logger, "existing value corruption");
existing = 0;
} else {
memcpy(&existing, existing_value->data(), sizeof(int64_t));
}
}
int64_t operand;
if (unlikely(value.size() != sizeof(int64_t))) {
// if existing_value is corrupted, treat it as 0
Log(logger, "operand value corruption");
operand = 0;
} else {
memcpy(&operand, value.data(), sizeof(int64_t));
}
int64_t result = existing + operand;
*new_value = std::move(std::string((char*)&result, sizeof(int64_t)));
//Errors are treated as 0.
return true;
}
const char* Int64AddOperator::Name() const {
return "Int64AddOperator";
}
bool HOT DMulOperator::Merge(
const rocksdb::Slice& key,
const rocksdb::Slice* existing_value,
const rocksdb::Slice& value,
std::string* new_value,
rocksdb::Logger* logger) const {
//Assuming 0 if no existing value
double existing = 0;
if (existing_value) {
if (unlikely(existing_value->size() != sizeof(double))) {
// if existing_value is corrupted, treat it as 0
Log(logger, "existing value corruption");
existing = 0;
} else {
memcpy(&existing, existing_value->data(), sizeof(double));
}
}
double operand;
if (unlikely(value.size() != sizeof(double))) {
// if existing_value is corrupted, treat it as 0
Log(logger, "operand value corruption");
operand = 0;
} else {
memcpy(&operand, value.data(), sizeof(double));
}
double result = existing * operand;
*new_value = std::move(std::string((char*)&result, sizeof(double)));
//Errors are treated as 0.
return true;
}
const char* DMulOperator::Name() const {
return "DMulOperator";
}
bool HOT DAddOperator::Merge(
const rocksdb::Slice& key,
const rocksdb::Slice* existing_value,
const rocksdb::Slice& value,
std::string* new_value,
rocksdb::Logger* logger) const {
//Assuming 0 if no existing value
double existing = 0;
if (existing_value) {
if (unlikely(existing_value->size() != sizeof(double))) {
// if existing_value is corrupted, treat it as 0
Log(logger, "existing value corruption");
existing = 0;
} else {
memcpy(&existing, existing_value->data(), sizeof(double));
}
}
double operand;
if (unlikely(value.size() != sizeof(double))) {
// if existing_value is corrupted, treat it as 0
Log(logger, "operand value corruption");
operand = 0;
} else {
memcpy(&operand, value.data(), sizeof(double));
}
double result = existing + operand;
*new_value = std::move(std::string((char*)&result, sizeof(double)));
//Errors are treated as 0.
return true;
}
const char* DAddOperator::Name() const {
return "DAddOperator";
}
bool HOT AppendOperator::Merge(
const rocksdb::Slice& key,
const rocksdb::Slice* existing_value,
const rocksdb::Slice& value,
std::string* new_value,
rocksdb::Logger* logger) const {
// assuming empty if no existing value
std::string existing;
if (existing_value) {
existing = existing_value->ToString();
}
*new_value = std::move(existing + value.ToString());
//Errors are treated as 0.
return true;
}
const char* AppendOperator::Name() const {
return "AppendOperator";
}
bool ReplaceOperator::Merge(
const rocksdb::Slice& key,
const rocksdb::Slice* existing_value,
const rocksdb::Slice& value,
std::string* new_value,
rocksdb::Logger* logger) const {
*new_value = value.ToString();
return true;
}
const char* ReplaceOperator::Name() const {
return "ReplaceOperator";
}
const char* ListAppendOperator::Name() const {
return "ListAppendOperator";
}
bool HOT ListAppendOperator::Merge(
const rocksdb::Slice& key,
const rocksdb::Slice* existing_value,
const rocksdb::Slice& value,
std::string* new_value,
rocksdb::Logger* logger) const {
// assuming empty if no existing value
std::string existing;
if (existing_value) {
existing = existing_value->ToString();
}
//Note that it is not inherently safe to assume the new value size is <
uint32_t newValLength = value.size();
//In between the old and the new value, we need to add the 4 bytes size
*new_value = std::move(existing + std::string((const char*)&newValLength, sizeof(uint32_t)) + value.ToString());
return true;
}
bool HOT ANDOperator::Merge(
const rocksdb::Slice& key,
const rocksdb::Slice* existing_value,
const rocksdb::Slice& value,
std::string* new_value,
rocksdb::Logger* logger) const {
//Assuming 0 if no existing value
std::string existing;
if (existing_value) {
existing = existing_value->ToString();
} else {
//Skip complex boolean logic, just copy value
*new_value = value.ToString();
return true;
}
//Extract raw binary info
const char* existingData = existing.data();
size_t existingSize = existing.size();
const char* valueData = value.data();
size_t valueSize = value.size();
/*
* Allocate the result memory (will be copied to the result string later)
* Writing to a string's data() could produce undefined behaviour
* with some C++ STL implementations
*/
size_t dstSize = std::max(existingSize, valueSize);
char* dst = new char[dstSize];
/*
* Perform bytewise boolean operation, ignoring extra bytes
* TODO: Optimize to use 128+-bit SSE / 64 bit / 32 bit operator,
* or check if the compiler is intelligent enough to do that
*/
size_t numCommonBytes = std::min(existingSize, valueSize);
for(size_t i = 0; i < numCommonBytes; i++) {
dst[i] = existingData[i] & valueData[i];
}
//Copy remaining bytes, if any
if(existingSize > numCommonBytes) {
memcpy(dst + numCommonBytes, existingData + numCommonBytes, existingSize - numCommonBytes);
} else if(valueSize > numCommonBytes) {
memcpy(dst + numCommonBytes, valueData + numCommonBytes, valueSize - numCommonBytes);
} //Else: Both have the same size, nothing to be done
//Copy dst buffer to new_value string
*new_value = std::move(std::string(dst, dstSize));
//Free allocated temporary resources
delete[] dst;
//This function does not have any logical error condition
return true;
}
const char* ANDOperator::Name() const {
return "ANDOperator";
}
bool HOT OROperator::Merge(
const rocksdb::Slice& key,
const rocksdb::Slice* existing_value,
const rocksdb::Slice& value,
std::string* new_value,
rocksdb::Logger* logger) const {
//Assuming 0 if no existing value
std::string existing;
if (existing_value) {
existing = existing_value->ToString();
} else {
//Skip complex boolean logic, just copy value
*new_value = value.ToString();
return true;
}
//Extract raw binary info
const char* existingData = existing.data();
size_t existingSize = existing.size();
const char* valueData = value.data();
size_t valueSize = value.size();
/*
* Allocate the result memory (will be copied to the result string later)
* Writing to a string's data() could produce undefined behaviour
* with some C++ STL implementations
*/
size_t dstSize = std::max(existingSize, valueSize);
char* dst = new char[dstSize];
/*
* Perform bytewise boolean operation, ignoring extra bytes
* TODO: Optimize to use 128+-bit SSE / 64 bit / 32 bit operator,
* or check if the compiler is intelligent enough to do that
*/
size_t numCommonBytes = std::min(existingSize, valueSize);
for(size_t i = 0; i < numCommonBytes; i++) {
dst[i] = existingData[i] | valueData[i];
}
//Copy remaining bytes, if any
if(existingSize > numCommonBytes) {
memcpy(dst + numCommonBytes, existingData + numCommonBytes, existingSize - numCommonBytes);
} else if(valueSize > numCommonBytes) {
memcpy(dst + numCommonBytes, valueData + numCommonBytes, valueSize - numCommonBytes);
} //Else: Both have the same size, nothing to be done
//Copy dst buffer to new_value string
*new_value = std::move(std::string(dst, dstSize));
//Free allocated temporary resources
delete[] dst;
//This function does not have any logical error condition
return true;
}
const char* OROperator::Name() const {
return "OROperator";
}
bool HOT XOROperator::Merge(
const rocksdb::Slice& key,
const rocksdb::Slice* existing_value,
const rocksdb::Slice& value,
std::string* new_value,
rocksdb::Logger* logger) const {
//Assuming 0 if no existing value
std::string existing;
if (existing_value) {
existing = existing_value->ToString();
} else {
//Skip complex boolean logic, just copy value
*new_value = value.ToString();
return true;
}
//Extract raw binary info
const char* existingData = existing.data();
size_t existingSize = existing.size();
const char* valueData = value.data();
size_t valueSize = value.size();
/*
* Allocate the result memory (will be copied to the result string later)
* Writing to a string's data() could produce undefined behaviour
* with some C++ STL implementations
*/
size_t dstSize = std::max(existingSize, valueSize);
char* dst = new char[dstSize];
/*
* Perform bytewise boolean operation, ignoring extra bytes
* TODO: Optimize to use 128+-bit SSE / 64 bit / 32 bit operator,
* or check if the compiler is intelligent enough to do that
*/
size_t numCommonBytes = std::min(existingSize, valueSize);
for(size_t i = 0; i < numCommonBytes; i++) {
dst[i] = existingData[i] ^ valueData[i];
}
//Copy remaining bytes, if any
if(existingSize > numCommonBytes) {
memcpy(dst + numCommonBytes, existingData + numCommonBytes, existingSize - numCommonBytes);
} else if(valueSize > numCommonBytes) {
memcpy(dst + numCommonBytes, valueData + numCommonBytes, valueSize - numCommonBytes);
} //Else: Both have the same size, nothing to be done
//Copy dst buffer to new_value string
*new_value = std::move(std::string(dst, dstSize));
//Free allocated temporary resources
delete[] dst;
//This function does not have any logical error condition
return true;
}
const char* XOROperator::Name() const {
return "XOROperator";
}
std::shared_ptr<rocksdb::MergeOperator> createMergeOperator(
const std::string& mergeOperatorCode) {
if(mergeOperatorCode.empty()) {
//empty --> default
return std::make_shared<ReplaceOperator>();
} else if(mergeOperatorCode == "INT64ADD") {
return std::make_shared<Int64AddOperator>();
} else if(mergeOperatorCode == "DMUL") {
return std::make_shared<DMulOperator>();
} else if(mergeOperatorCode == "DADD") {
return std::make_shared<DAddOperator>();
} else if(mergeOperatorCode == "APPEND") {
return std::make_shared<AppendOperator>();
} else if(mergeOperatorCode == "REPLACE") { //Also handles REPLACE
return std::make_shared<ReplaceOperator>();
} else if(mergeOperatorCode == "AND") {
return std::make_shared<ANDOperator>();
} else if(mergeOperatorCode == "OR") {
return std::make_shared<OROperator>();
} else if(mergeOperatorCode == "XOR") {
return std::make_shared<XOROperator>();
} else if(mergeOperatorCode == "LISTAPPEND") {
return std::make_shared<ListAppendOperator>();
} else {
std::cerr << "Warning: Invalid merge operator code: " << mergeOperatorCode << std::endl;
return std::make_shared<ReplaceOperator>();
}
}<|endoftext|> |
<commit_before>/*****************************************************************************
* Licensed to Qualys, Inc. (QUALYS) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* QUALYS licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
****************************************************************************/
/**
* @file
* @brief Predicate --- Dot 2 implementation.
*
* @author Christopher Alfeld <[email protected]>
*/
#include <predicate/dot2.hpp>
#include <predicate/merge_graph.hpp>
#include <boost/algorithm/string/join.hpp>
#include <boost/format.hpp>
#include <boost/lexical_cast.hpp>
using namespace std;
namespace IronBee {
namespace Predicate {
namespace {
//! List of const nodes.
typedef list<node_cp> node_clist_t;
/**
* Determine if @a node can be absorbed.
*
* An absorbable node will be included in its parents label and will not be
* rendered as a discrete node.
*
* @param[in] node Node to check.
* @param[in] G Graph; used to check if @a node is a root.
* @param[in] root_namer Root namer; used to check if one is defined.
* @return true iff @a node should be absorbed into parent rendering.
**/
bool is_absorbable(
const node_cp& node,
const MergeGraph& G,
root_namer_t root_namer
)
{
if (! node->is_literal()) {
return false;
}
try {
G.root_indices(node);
}
catch (enoent) {
// Not a root.
return node->is_literal();
}
// Root
return ! root_namer;
}
/**
* Generic HTML escaping routine.
*
* Turns various HTML special characters into their HTML escapes. This
* routine should be used for any text that comes from the rest of Predicate,
* especially user defined sexpressions that may include literals with HTML
* escapes.
*
* @param[in] src Text to escape.
* @return @a src with special characters escaped.
**/
string escape_html(
const string& src
)
{
string result;
BOOST_FOREACH(char c, src) {
switch (c) {
case '&': result += "&"; break;
case '"': result += """; break;
case '\'': result += "'"; break;
case '<': result += "<"; break;
case '>': result += ">"; break;
case '\\': result += "\\\\"; break;
default:
result += (boost::format("%c") % c).str();
}
}
return result;
}
//! Construct unicode glyph for a circled number @a n (@a n <= 20).
string circle_n(
unsigned int n
)
{
if (n == 0) {
return "%#9450;";
}
else if (n > 20) {
BOOST_THROW_EXCEPTION(
einval() << errinfo_what("Cannot circle numbers above 20.")
);
}
else {
return (boost::format("&#%d;") % (9311 + n)).str();
}
}
//! Render a node.
void render_node(
ostream& out,
const node_cp& node,
const string& attrs
)
{
out << " \"" << node << "\" [" << attrs << "];" << endl;
}
//! Render a literal.
void render_literal(
ostream& out,
const node_cp& node
)
{
render_node(out, node, "label=<" + escape_html(node->to_s()) + ">");
}
//! Render an edge.
void render_edge(
ostream& out,
const node_cp& from,
const node_cp& to,
const string& label = string()
)
{
out << " \"" << from << "\" -> \"" << to << "\"";
if (! label.empty()) {
out << " [label=<" << label << ">]";
}
out << ";" << endl;
}
//! Render roots.
void render_roots(
ostream& out,
const node_cp& node,
const MergeGraph& G,
root_namer_t root_namer
)
{
if (! root_namer) {
return;
}
try {
BOOST_FOREACH(size_t index, G.root_indices(node)) {
string name = root_namer(index);
out << " \"root-" << index << "\" ["
<< "fontname=\"Times-Roman\", shape=none, label=<"
<< escape_html(name) << ">];" << endl;
out << " \"root-" << index << "\" -> \"" << node << "\" ["
<< "style=dotted, dir=none];" << endl;
}
}
catch (enoent) {}
}
//! Render a validation report.
void render_report(
ostream& out,
const string& report,
const node_cp& node
)
{
out << " { rank = same; \"" << node
<< "\" \"report-" << node << "\" }" << endl;
out << " \"report-" << node << "\" ["
<< "fontsize=10, shape=none, "
<< "label=<<table border=\"0\" cellborder=\"0\">"
<< report << "</table>>];\n";
out << " \"" << node << "\" -> \"report-" << node << "\" ["
<< " weight=1000, dir=none, penwidth=0.5];\n";
}
//! Validation status of a node.
enum status_t {
STATUS_OK,
STATUS_WARN,
STATUS_ERROR
};
/**
* Reporter; generates Dot reports for use with render_report().
*
* @param[out] status Status of node.
* @param[out] report Report for node.
* @param[in] is_error Is an error being reported?
* @param[in] message Message.
**/
void dot_reporter(
status_t& status,
string& report,
bool is_error,
const string& message
)
{
status = is_error ? STATUS_ERROR : STATUS_WARN;
report += string("<tr><td><font color=\"") +
(is_error ? "red" : "orange") + "\">" +
escape_html(message) + "</font></td></tr>";
}
/**
* Render a Value.
*
* @param[out] out Where to write.
* @param[in] value What to write.
**/
void render_value(
ostream& out,
const Value& value
)
{
if (value.type() != Value::LIST) {
out << escape_html(value.name()) << ":" << escape_html(value.to_s());
}
else {
bool first = true;
out << "[";
BOOST_FOREACH(const Value& subvalue, value.value_as_list<Value>()) {
if (first) {
out << ", ";
first = false;
}
render_value(out, subvalue);
}
out << "]";
}
}
/**
* Render values of a node.
*
* @param[out] out Where to write.
* @param[in] node Node to write values of.
**/
void render_values(
ostream& out,
const node_cp& node
)
{
size_t i = 0;
BOOST_FOREACH(const Value& value, node->values()) {
++i;
out << " { rank = same; \"" << node
<< "\" \"value-" << node << "-" << i << "\" }" << endl;
out << " \"value-" << node << "-" << i << "\" ["
<< "fontsize=10, shape=none, label=<";
render_value(out, value);
out << ">];\n";
out << " \"" << node << "\" -> \"value-" << node << "-" << i
<< "\" [weight=1000, dir=none, penwidth=0.5];\n";
}
}
/**
* Node hook.
*
* First argument is output stream to output additional dot *before* node.
* Second argument is a string of additional node properties.
* Third argument is is the node itself.
**/
typedef boost::function<void(ostream&, string&, const node_cp&)>
node_hook_t;
/**
* Base to_dot2() routine.
*
* @param[in] out Where to write dot.
* @param[in] G MergeGraph, used to detect roots.
* @param[in] initial Initial vector for search. If empty, will default
* to all nodes in graph.
* @param[in] root_namer How to name roots.
* @param[in] node_hook Additional rendering logic.
**/
void to_dot2_base(
ostream& out,
const MergeGraph& G,
const node_clist_t& initial,
root_namer_t root_namer,
node_hook_t node_hook
)
{
typedef set<node_cp> node_cset_t;
node_clist_t queue;
node_cset_t skip;
if (! initial.empty()) {
queue = initial;
}
else {
copy(G.roots().first, G.roots().second, back_inserter(queue));
}
// Header
out << "digraph G {" << endl;
out << " ordering = out;" << endl;
out << " edge [arrowsize=0.5, fontsize=9];" << endl;
out << " node [fontname=Courier, penwidth=0.2, shape=rect, height=0.4];"
<< endl;
// Body
while (! queue.empty()) {
node_cp node = queue.front();
queue.pop_front();
if (skip.count(node)) {
continue;
}
skip.insert(node);
// If node is a literal...
if (node->is_literal()) {
render_literal(out, node);
}
else {
boost::shared_ptr<const Call> call =
boost::dynamic_pointer_cast<const Call>(node);
assert(call);
string extra;
// Let node hook run.
if (node_hook) {
node_hook(out, extra, node);
}
// Otherwise node is a call.
if (node->children().size() > 5) {
// High degree nodes, have no absorbption.
render_node(out, node,
"label=<" + escape_html(call->name()) + ">"
);
BOOST_FOREACH(const node_cp& child, node->children()) {
render_edge(out, node, child);
queue.push_back(child);
}
}
else {
// Try to absorb children.
vector<string> name;
name.push_back("<b>" + call->name() + "</b>");
unsigned int placeholder = 0;
BOOST_FOREACH(const node_cp& child, node->children()) {
if (is_absorbable(child, G, root_namer)) {
if (child->to_s()[0] == '\'') {
name.push_back(
"<i>" + escape_html(child->to_s()) + "</i>"
);
}
else {
name.push_back(
"<font>" + escape_html(child->to_s()) +
"</font>"
);
}
}
else {
++placeholder;
name.push_back(
"<font>" + circle_n(placeholder) + "</font>"
);
render_edge(out, node, child, circle_n(placeholder));
queue.push_back(child);
}
}
render_node(out, node,
"label=<" +
boost::algorithm::join(name, " ") + ">" +
extra
);
}
}
render_roots(out, node, G, root_namer);
}
// Footer
out << "}" << endl;
}
//! Node Hook: Validate
void nh_validate(
validation_e validate,
ostream& out,
string& extra,
const node_cp& node
)
{
status_t status;
string report;
switch (validate) {
case VALIDATE_NONE: return;
case VALIDATE_PRE:
node->pre_transform(NodeReporter(
boost::bind(
dot_reporter,
boost::ref(status),
boost::ref(report),
_1, _2
), node, false
));
break;
case VALIDATE_POST:
node->post_transform(NodeReporter(
boost::bind(
dot_reporter,
boost::ref(status),
boost::ref(report),
_1, _2
), node, false
));
break;
};
switch (status) {
case STATUS_OK:
break;
case STATUS_WARN:
extra = ", style=filled, fillcolor=orange";
break;
case STATUS_ERROR:
extra = ", style=filled, fillcolor=red";
break;
};
if (status != STATUS_OK) {
render_report(out, report, node);
}
}
//! Node Hook: Value
void nh_value(
ostream& out,
string& extra,
const node_cp& node
)
{
const ValueList& values = node->values();
bool finished = node->is_finished();
if (finished) {
extra += ", style=\"diagonals,filled\"";
}
if (! values.empty()) {
extra += ", fillcolor=\"#BDECB6\"";
render_values(out, node);
}
}
}
void to_dot2(
ostream& out,
const MergeGraph& G,
root_namer_t root_namer
)
{
to_dot2_base(out, G, node_clist_t(), root_namer, node_hook_t());
}
void to_dot2_validate(
ostream& out,
const MergeGraph& G,
validation_e validate,
root_namer_t root_namer
)
{
to_dot2_base(out, G, node_clist_t(), root_namer,
bind(nh_validate, validate, _1, _2, _3)
);
}
void to_dot2_value(
ostream& out,
const MergeGraph& G,
const node_clist_t& initial,
root_namer_t root_namer
)
{
to_dot2_base(out, G, initial, root_namer, nh_value);
}
} // Predicate
} // IronBee
<commit_msg>predicate/dot2: Improve value rendering in to_dot2_value().<commit_after>/*****************************************************************************
* Licensed to Qualys, Inc. (QUALYS) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* QUALYS licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
****************************************************************************/
/**
* @file
* @brief Predicate --- Dot 2 implementation.
*
* @author Christopher Alfeld <[email protected]>
*/
#include <predicate/dot2.hpp>
#include <predicate/merge_graph.hpp>
#include <boost/algorithm/string/join.hpp>
#include <boost/format.hpp>
#include <boost/lexical_cast.hpp>
using namespace std;
namespace IronBee {
namespace Predicate {
namespace {
//! List of const nodes.
typedef list<node_cp> node_clist_t;
/**
* Determine if @a node can be absorbed.
*
* An absorbable node will be included in its parents label and will not be
* rendered as a discrete node.
*
* @param[in] node Node to check.
* @param[in] G Graph; used to check if @a node is a root.
* @param[in] root_namer Root namer; used to check if one is defined.
* @return true iff @a node should be absorbed into parent rendering.
**/
bool is_absorbable(
const node_cp& node,
const MergeGraph& G,
root_namer_t root_namer
)
{
if (! node->is_literal()) {
return false;
}
try {
G.root_indices(node);
}
catch (enoent) {
// Not a root.
return node->is_literal();
}
// Root
return ! root_namer;
}
/**
* Generic HTML escaping routine.
*
* Turns various HTML special characters into their HTML escapes. This
* routine should be used for any text that comes from the rest of Predicate,
* especially user defined sexpressions that may include literals with HTML
* escapes.
*
* @param[in] src Text to escape.
* @return @a src with special characters escaped.
**/
string escape_html(
const string& src
)
{
string result;
BOOST_FOREACH(char c, src) {
switch (c) {
case '&': result += "&"; break;
case '"': result += """; break;
case '\'': result += "'"; break;
case '<': result += "<"; break;
case '>': result += ">"; break;
case '\\': result += "\\\\"; break;
default:
result += (boost::format("%c") % c).str();
}
}
return result;
}
//! Construct unicode glyph for a circled number @a n (@a n <= 20).
string circle_n(
unsigned int n
)
{
if (n == 0) {
return "%#9450;";
}
else if (n > 20) {
BOOST_THROW_EXCEPTION(
einval() << errinfo_what("Cannot circle numbers above 20.")
);
}
else {
return (boost::format("&#%d;") % (9311 + n)).str();
}
}
//! Render a node.
void render_node(
ostream& out,
const node_cp& node,
const string& attrs
)
{
out << " \"" << node << "\" [" << attrs << "];" << endl;
}
//! Render a literal.
void render_literal(
ostream& out,
const node_cp& node
)
{
render_node(out, node, "label=<" + escape_html(node->to_s()) + ">");
}
//! Render an edge.
void render_edge(
ostream& out,
const node_cp& from,
const node_cp& to,
const string& label = string()
)
{
out << " \"" << from << "\" -> \"" << to << "\"";
if (! label.empty()) {
out << " [label=<" << label << ">]";
}
out << ";" << endl;
}
//! Render roots.
void render_roots(
ostream& out,
const node_cp& node,
const MergeGraph& G,
root_namer_t root_namer
)
{
if (! root_namer) {
return;
}
try {
BOOST_FOREACH(size_t index, G.root_indices(node)) {
string name = root_namer(index);
out << " \"root-" << index << "\" ["
<< "fontname=\"Times-Roman\", shape=none, label=<"
<< escape_html(name) << ">];" << endl;
out << " \"root-" << index << "\" -> \"" << node << "\" ["
<< "style=dotted, dir=none];" << endl;
}
}
catch (enoent) {}
}
//! Render a validation report.
void render_report(
ostream& out,
const string& report,
const node_cp& node
)
{
out << " { rank = same; \"" << node
<< "\" \"report-" << node << "\" }" << endl;
out << " \"report-" << node << "\" ["
<< "fontsize=10, shape=none, "
<< "label=<<table border=\"0\" cellborder=\"0\">"
<< report << "</table>>];\n";
out << " \"" << node << "\" -> \"report-" << node << "\" ["
<< " weight=1000, dir=none, penwidth=0.5];\n";
}
//! Validation status of a node.
enum status_t {
STATUS_OK,
STATUS_WARN,
STATUS_ERROR
};
/**
* Reporter; generates Dot reports for use with render_report().
*
* @param[out] status Status of node.
* @param[out] report Report for node.
* @param[in] is_error Is an error being reported?
* @param[in] message Message.
**/
void dot_reporter(
status_t& status,
string& report,
bool is_error,
const string& message
)
{
status = is_error ? STATUS_ERROR : STATUS_WARN;
report += string("<tr><td><font color=\"") +
(is_error ? "red" : "orange") + "\">" +
escape_html(message) + "</font></td></tr>";
}
/**
* Render a Value.
*
* @param[out] out Where to write.
* @param[in] value What to write.
**/
void render_value(
ostream& out,
const Value& value
);
/**
* Render a list of values.
*
* @param[out] out Where to write.
* @param[in] values What to write.
**/
void render_valuelist(
ostream& out,
const ValueList& values
)
{
out << "<table border=\"0\">";
BOOST_FOREACH(const Value& value, values) {
out << "<tr><td align=\"right\">" << escape_html(value.name_as_s())
<< "</td><td align=\"left\">";
render_value(out, value);
out << "</td></tr>";
}
out << "</table>";
}
void render_value(
ostream& out,
const Value& value
)
{
if (value.type() != Value::LIST) {
out << escape_html(value.to_s());
}
else {
render_valuelist(out, value.value_as_list<Value>());
}
}
/**
* Render values of a node.
*
* @param[out] out Where to write.
* @param[in] node Node to write values of.
**/
void render_values(
ostream& out,
const node_cp& node
)
{
out << " { rank = same; \"" << node
<< "\" \"value-" << node << "\" }" << endl
<< " \"" << node << "\" -> \"value-" << node
<< "\" [weight=1000, dir=none, penwidth=0.5];\n"
<< " \"value-" << node << "\" ["
<< "fontsize=10, shape=none, label=<";
render_valuelist(out, node->values());
out << ">];" << endl;
}
/**
* Node hook.
*
* First argument is output stream to output additional dot *before* node.
* Second argument is a string of additional node properties.
* Third argument is is the node itself.
**/
typedef boost::function<void(ostream&, string&, const node_cp&)>
node_hook_t;
/**
* Base to_dot2() routine.
*
* @param[in] out Where to write dot.
* @param[in] G MergeGraph, used to detect roots.
* @param[in] initial Initial vector for search. If empty, will default
* to all nodes in graph.
* @param[in] root_namer How to name roots.
* @param[in] node_hook Additional rendering logic.
**/
void to_dot2_base(
ostream& out,
const MergeGraph& G,
const node_clist_t& initial,
root_namer_t root_namer,
node_hook_t node_hook
)
{
typedef set<node_cp> node_cset_t;
node_clist_t queue;
node_cset_t skip;
if (! initial.empty()) {
queue = initial;
}
else {
copy(G.roots().first, G.roots().second, back_inserter(queue));
}
// Header
out << "digraph G {" << endl;
out << " ordering = out;" << endl;
out << " edge [arrowsize=0.5, fontsize=9];" << endl;
out << " node [fontname=Courier, penwidth=0.2, shape=rect, height=0.4];"
<< endl;
// Body
while (! queue.empty()) {
node_cp node = queue.front();
queue.pop_front();
if (skip.count(node)) {
continue;
}
skip.insert(node);
// If node is a literal...
if (node->is_literal()) {
render_literal(out, node);
}
else {
boost::shared_ptr<const Call> call =
boost::dynamic_pointer_cast<const Call>(node);
assert(call);
string extra;
// Let node hook run.
if (node_hook) {
node_hook(out, extra, node);
}
// Otherwise node is a call.
if (node->children().size() > 5) {
// High degree nodes, have no absorbption.
render_node(out, node,
"label=<" + escape_html(call->name()) + ">"
);
BOOST_FOREACH(const node_cp& child, node->children()) {
render_edge(out, node, child);
queue.push_back(child);
}
}
else {
// Try to absorb children.
vector<string> name;
name.push_back("<b>" + call->name() + "</b>");
unsigned int placeholder = 0;
BOOST_FOREACH(const node_cp& child, node->children()) {
if (is_absorbable(child, G, root_namer)) {
if (child->to_s()[0] == '\'') {
name.push_back(
"<i>" + escape_html(child->to_s()) + "</i>"
);
}
else {
name.push_back(
"<font>" + escape_html(child->to_s()) +
"</font>"
);
}
}
else {
++placeholder;
name.push_back(
"<font>" + circle_n(placeholder) + "</font>"
);
render_edge(out, node, child, circle_n(placeholder));
queue.push_back(child);
}
}
render_node(out, node,
"label=<" +
boost::algorithm::join(name, " ") + ">" +
extra
);
}
}
render_roots(out, node, G, root_namer);
}
// Footer
out << "}" << endl;
}
//! Node Hook: Validate
void nh_validate(
validation_e validate,
ostream& out,
string& extra,
const node_cp& node
)
{
status_t status;
string report;
switch (validate) {
case VALIDATE_NONE: return;
case VALIDATE_PRE:
node->pre_transform(NodeReporter(
boost::bind(
dot_reporter,
boost::ref(status),
boost::ref(report),
_1, _2
), node, false
));
break;
case VALIDATE_POST:
node->post_transform(NodeReporter(
boost::bind(
dot_reporter,
boost::ref(status),
boost::ref(report),
_1, _2
), node, false
));
break;
};
switch (status) {
case STATUS_OK:
break;
case STATUS_WARN:
extra = ", style=filled, fillcolor=orange";
break;
case STATUS_ERROR:
extra = ", style=filled, fillcolor=red";
break;
};
if (status != STATUS_OK) {
render_report(out, report, node);
}
}
//! Node Hook: Value
void nh_value(
ostream& out,
string& extra,
const node_cp& node
)
{
const ValueList& values = node->values();
bool finished = node->is_finished();
if (finished) {
extra += ", style=\"diagonals,filled\"";
}
if (! values.empty()) {
extra += ", fillcolor=\"#BDECB6\"";
render_values(out, node);
}
}
}
void to_dot2(
ostream& out,
const MergeGraph& G,
root_namer_t root_namer
)
{
to_dot2_base(out, G, node_clist_t(), root_namer, node_hook_t());
}
void to_dot2_validate(
ostream& out,
const MergeGraph& G,
validation_e validate,
root_namer_t root_namer
)
{
to_dot2_base(out, G, node_clist_t(), root_namer,
bind(nh_validate, validate, _1, _2, _3)
);
}
void to_dot2_value(
ostream& out,
const MergeGraph& G,
const node_clist_t& initial,
root_namer_t root_namer
)
{
to_dot2_base(out, G, initial, root_namer, nh_value);
}
} // Predicate
} // IronBee
<|endoftext|> |
<commit_before>/***************************************************************************
* *
* Copyright 2012 Marco Martin <[email protected]> *
* *
* 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 "appbackgroundprovider_p.h"
#include "bodegastore.h"
#include "kdeclarativeview.h"
#include <QtDeclarative/qdeclarative.h>
#include <QDeclarativeContext>
#include <QDeclarativeEngine>
#include <QScriptEngine>
#include <QScriptValueIterator>
#include <KConfig>
#include <KConfigGroup>
#include <KDebug>
#include <KGlobal>
#include <kwallet.h>
//Bodega libs
#include <bodega/assetoperations.h>
#include <bodega/bodegamodel.h>
#include <bodega/channelsjob.h>
#include <bodega/historymodel.h>
#include <bodega/networkjob.h>
#include <bodega/participantinfojob.h>
#include <bodega/registerjob.h>
#include <bodega/session.h>
#include <bodega/signonjob.h>
#include <bodega/installjob.h>
#include <bodega/installjobsmodel.h>
#include <bodega/uninstalljob.h>
using namespace Bodega;
QScriptValue qScriptValueFromError(QScriptEngine *engine, const Bodega::Error &error)
{
QScriptValue obj = engine->newObject();
obj.setProperty("serverCode", error.serverCode());
obj.setProperty("type", error.type());
obj.setProperty("errorId", error.errorId());
obj.setProperty("title", error.title());
obj.setProperty("description", error.description());
return obj;
}
void errorFromQScriptValue(const QScriptValue &scriptValue, Bodega::Error &error)
{
Error::Type type = Error::Network;
QString errorId;
QString title;
QString description;
QScriptValueIterator it(scriptValue);
while (it.hasNext()) {
it.next();
//kDebug() << it.name() << "is" << it.value().toString();
if (it.name() == "serverCode") {
const Error::ServerCode code = (Error::ServerCode)it.value().toInteger();
if (code != Error::NoCode) {
error = Error(code);
return;
}
} else if (it.name() == "type") {
type = (Error::Type)it.value().toInteger();
} else if (it.name() == "errorId") {
errorId = it.value().toString();
} else if (it.name() == "title") {
title = it.value().toString();
} else if (it.name() == "description") {
description = it.value().toString();
}
}
error = Error(type, errorId, title, description);
}
QScriptValue qScriptValueFromChannelInfo(QScriptEngine *engine, const Bodega::ChannelInfo &info)
{
QScriptValue obj = engine->newObject();
obj.setProperty("id", info.id);
obj.setProperty("name", info.name);
obj.setProperty("description", info.description);
obj.setProperty("assetCount", info.assetCount);
//obj.setProperty("images", images);
return obj;
}
void channelInfoFromQScriptValue(const QScriptValue &scriptValue, Bodega::ChannelInfo &info)
{
QScriptValueIterator it(scriptValue);
while (it.hasNext()) {
it.next();
//kDebug() << it.name() << "is" << it.value().toString();
if (it.name() == "id") {
info.id = it.value().toString();
} else if (it.name() == "name") {
info.name = it.value().toString();
} else if (it.name() == "description") {
info.description = it.value().toString();
} else if (it.name() == "assetCount") {
info.assetCount = it.value().toInteger();
}
}
}
QScriptValue qScriptValueFromAssetInfo(QScriptEngine *engine, const Bodega::AssetInfo &info)
{
QScriptValue obj = engine->newObject();
obj.setProperty("id", info.id);
obj.setProperty("license", info.license);
obj.setProperty("partnerId", info.partnerId);
obj.setProperty("partnerName", info.partnerName);
obj.setProperty("name", info.name);
obj.setProperty("filename", info.filename);
obj.setProperty("version", info.version);
//obj.setProperty("images", info.images);
obj.setProperty("description", info.description);
obj.setProperty("points", info.points);
obj.setProperty("canDownload", info.canDownload);
QScriptValue imageObj = engine->newObject();
imageObj.setProperty("tiny", info.images[ImageTiny].toString());
imageObj.setProperty("small", info.images[ImageSmall].toString());
imageObj.setProperty("medium", info.images[ImageMedium].toString());
imageObj.setProperty("large", info.images[ImageLarge].toString());
imageObj.setProperty("huge", info.images[ImageHuge].toString());
imageObj.setProperty("previews", info.images[ImagePreviews].toString());
obj.setProperty("images", imageObj);
return obj;
}
void assetInfoFromQScriptValue(const QScriptValue &scriptValue, Bodega::AssetInfo &info)
{
QScriptValueIterator it(scriptValue);
while (it.hasNext()) {
it.next();
if (it.name() == "id") {
info.id = it.value().toString();
} else if (it.name() == "license") {
info.license = it.value().toString();
} else if (it.name() == "partnerId") {
info.partnerId = it.value().toString();
} else if (it.name() == "partnerName") {
info.partnerName = it.value().toString();
} else if (it.name() == "name") {
info.name = it.value().toString();
} else if (it.name() == "filename") {
info.filename = it.value().toString();
} else if (it.name() == "version") {
info.version = it.value().toString();
} else if (it.name() == "description") {
info.description = it.value().toString();
} else if (it.name() == "points") {
info.points = it.value().toInteger();
} else if (it.name() == "canDownload") {
info.canDownload = it.value().toBool();
} else if (it.name() == "images") {
QMap<ImageUrl, QUrl> images;
QScriptValueIterator imageIt(scriptValue);
while (imageIt.hasNext()) {
imageIt.next();
if (imageIt.name() == "tiny") {
images[ImageTiny] = imageIt.value().toString();
} else if (imageIt.name() == "small") {
images[ImageSmall] = imageIt.value().toString();
} else if (imageIt.name() == "medium") {
images[ImageMedium] = imageIt.value().toString();
} else if (imageIt.name() == "large") {
images[ImageLarge] = imageIt.value().toString();
} else if (imageIt.name() == "huge") {
images[ImageHuge] = imageIt.value().toString();
} else if (imageIt.name() == "previews") {
images[ImagePreviews] = imageIt.value().toString();
}
}
info.images = images;
}
}
}
QScriptValue qScriptValueFromTags(QScriptEngine *engine, const Bodega::Tags &tags)
{
QScriptValue obj = engine->newObject();
foreach (const QString &key, tags.keys()) {
QScriptValue list = engine->newArray();
int i = 0;
foreach (const QString &value, tags.values(key)) {
list.setProperty(i, value);
++i;
}
obj.setProperty(key, list);
}
return obj;
}
void tagsFromQScriptValue(const QScriptValue &scriptValue, Bodega::Tags &tags)
{
QScriptValueIterator it(scriptValue);
while (it.hasNext()) {
it.next();
QScriptValueIterator tagIterator(it.value());
while (tagIterator.hasNext()) {
tags.insert(it.name(), tagIterator.value().toString());
}
}
}
QScriptValue qScriptValueFromParticipantInfo(QScriptEngine *engine, const Bodega::ParticipantInfo &info)
{
QScriptValue obj = engine->newObject();
obj.setProperty("assetCount", info.assetCount);
obj.setProperty("channelCount", info.channelCount);
obj.setProperty("pointsOwed", info.pointsOwed);
obj.setProperty("organization", info.organization);
obj.setProperty("firstName", info.firstName);
obj.setProperty("lastName", info.lastName);
obj.setProperty("email", info.email);
return obj;
}
void participantInfoFromQScriptValue(const QScriptValue &scriptValue, Bodega::ParticipantInfo &info)
{
info.assetCount = scriptValue.property("assetCount").toInt32();
info.channelCount = scriptValue.property("channelCount").toInt32();
info.pointsOwed = scriptValue.property("pointsOwed").toInt32();
info.organization = scriptValue.property("organization").toString();
info.firstName = scriptValue.property("firstName").toString();
info.lastName = scriptValue.property("lastName").toString();
info.email = scriptValue.property("email").toString();
}
BodegaStore::BodegaStore()
: KDeclarativeMainWindow(),
m_historyModel(0)
{
// For kde-runtime 4.8 compabitility, the appbackgrounds image provider is only
// in PlasmaExtras 4.9 (master currently)
// FIXME: Remove this call and the class from commmon/ once we can depend on 4.9
if (!declarativeView()->engine()->imageProvider("appbackgrounds")) {
declarativeView()->engine()->addImageProvider(QLatin1String("appbackgrounds"), new AppBackgroundProvider);
}
declarativeView()->setPackageName("com.coherenttheory.addonsapp");
qmlRegisterType<Bodega::ParticipantInfoJob>();
qmlRegisterType<Bodega::AssetJob>();
qmlRegisterType<Bodega::AssetOperations>();
qmlRegisterType<Bodega::ChannelsJob>();
qmlRegisterType<Bodega::HistoryModel>();
qmlRegisterType<Bodega::Model>();
qmlRegisterType<Bodega::NetworkJob>();
qmlRegisterType<Bodega::RegisterJob>();
qmlRegisterType<Bodega::Session>();
qmlRegisterType<Bodega::SignOnJob>();
qmlRegisterType<Bodega::InstallJob>();
qmlRegisterType<Bodega::InstallJobsModel>();
qmlRegisterType<Bodega::UninstallJob>();
qmlRegisterUncreatableType<ErrorCode>("com.coherenttheory.addonsapp", 1, 0, "ErrorCode", QLatin1String("Do not create objects of this type."));
qScriptRegisterMetaType<Bodega::Error>(declarativeView()->scriptEngine(), qScriptValueFromError, errorFromQScriptValue, QScriptValue());
qScriptRegisterMetaType<Bodega::ChannelInfo>(declarativeView()->scriptEngine(), qScriptValueFromChannelInfo, channelInfoFromQScriptValue, QScriptValue());
qScriptRegisterMetaType<Bodega::AssetInfo>(declarativeView()->scriptEngine(), qScriptValueFromAssetInfo, assetInfoFromQScriptValue, QScriptValue());
qScriptRegisterMetaType<Bodega::Tags>(declarativeView()->scriptEngine(), qScriptValueFromTags, tagsFromQScriptValue, QScriptValue());
qScriptRegisterMetaType<Bodega::ParticipantInfo>(declarativeView()->scriptEngine(), qScriptValueFromParticipantInfo, participantInfoFromQScriptValue, QScriptValue());
m_session = new Session(this);
KConfigGroup config(KGlobal::config(), "AddOns");
m_session->setBaseUrl(config.readEntry("URL", "http://addons.makeplaylive.com:3000"));
m_session->setStoreId(config.readEntry("Store", "VIVALDI-1"));
m_channelsModel = new Bodega::Model(this);
m_channelsModel->setSession(m_session);
m_searchModel = new Bodega::Model(this);
m_searchModel->setSession(m_session);
declarativeView()->rootContext()->setContextProperty("bodegaClient", this);
}
BodegaStore::~BodegaStore()
{
}
Session* BodegaStore::session() const
{
return m_session;
}
Model* BodegaStore::channelsModel() const
{
return m_channelsModel;
}
Model* BodegaStore::searchModel() const
{
return m_searchModel;
}
HistoryModel *BodegaStore::historyModel()
{
if (!m_historyModel) {
m_historyUsers = 0;
m_historyModel = new HistoryModel(m_session);
m_historyModel->setSession(m_session);
}
return m_historyModel;
}
void BodegaStore::historyInUse(bool used)
{
if (used) {
++m_historyUsers;
} else {
--m_historyUsers;
if (m_historyUsers < 1) {
m_historyUsers = 0;
m_historyModel->deleteLater();
m_historyModel = 0;
}
}
}
void BodegaStore::forgetCredentials() const
{
m_session->setUserName(QString());
m_session->setPassword(QString());
saveCredentials();
}
void BodegaStore::saveCredentials() const
{
KWallet::Wallet *wallet = KWallet::Wallet::openWallet(KWallet::Wallet::NetworkWallet(),
winId(), KWallet::Wallet::Synchronous);
if (wallet->isOpen() &&
(wallet->hasFolder("MakePlayLive") ||
wallet->createFolder("MakePlayLive")) &&
wallet->setFolder("MakePlayLive")) {
QMap<QString, QString> map;
map["username"] = m_session->userName();
map["password"] = m_session->password();
if (wallet->writeMap("credentials", map) != 0) {
kWarning() << "Unable to write credentials to wallet";
}
} else {
kWarning() << "Unable to open wallet";
}
}
QVariantHash BodegaStore::retrieveCredentials() const
{
KWallet::Wallet *wallet = KWallet::Wallet::openWallet(KWallet::Wallet::NetworkWallet(),
winId(), KWallet::Wallet::Synchronous);
if (wallet && wallet->isOpen() && wallet->setFolder("MakePlayLive")) {
QMap<QString, QString> map;
if (wallet->readMap("credentials", map) == 0) {
QVariantHash hash;
hash["username"] = map["username"];
hash["password"] = map["password"];
return hash;
} else {
kWarning() << "Unable to write credentials to wallet";
}
} else {
kWarning() << "Unable to open wallet";
}
return QVariantHash();
}
#include "bodegastore.moc"
<commit_msg>fix comment<commit_after>/***************************************************************************
* *
* Copyright 2012 Marco Martin <[email protected]> *
* *
* 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 "appbackgroundprovider_p.h"
#include "bodegastore.h"
#include "kdeclarativeview.h"
#include <QtDeclarative/qdeclarative.h>
#include <QDeclarativeContext>
#include <QDeclarativeEngine>
#include <QScriptEngine>
#include <QScriptValueIterator>
#include <KConfig>
#include <KConfigGroup>
#include <KDebug>
#include <KGlobal>
#include <kwallet.h>
//Bodega libs
#include <bodega/assetoperations.h>
#include <bodega/bodegamodel.h>
#include <bodega/channelsjob.h>
#include <bodega/historymodel.h>
#include <bodega/networkjob.h>
#include <bodega/participantinfojob.h>
#include <bodega/registerjob.h>
#include <bodega/session.h>
#include <bodega/signonjob.h>
#include <bodega/installjob.h>
#include <bodega/installjobsmodel.h>
#include <bodega/uninstalljob.h>
using namespace Bodega;
QScriptValue qScriptValueFromError(QScriptEngine *engine, const Bodega::Error &error)
{
QScriptValue obj = engine->newObject();
obj.setProperty("serverCode", error.serverCode());
obj.setProperty("type", error.type());
obj.setProperty("errorId", error.errorId());
obj.setProperty("title", error.title());
obj.setProperty("description", error.description());
return obj;
}
void errorFromQScriptValue(const QScriptValue &scriptValue, Bodega::Error &error)
{
Error::Type type = Error::Network;
QString errorId;
QString title;
QString description;
QScriptValueIterator it(scriptValue);
while (it.hasNext()) {
it.next();
//kDebug() << it.name() << "is" << it.value().toString();
if (it.name() == "serverCode") {
const Error::ServerCode code = (Error::ServerCode)it.value().toInteger();
if (code != Error::NoCode) {
error = Error(code);
return;
}
} else if (it.name() == "type") {
type = (Error::Type)it.value().toInteger();
} else if (it.name() == "errorId") {
errorId = it.value().toString();
} else if (it.name() == "title") {
title = it.value().toString();
} else if (it.name() == "description") {
description = it.value().toString();
}
}
error = Error(type, errorId, title, description);
}
QScriptValue qScriptValueFromChannelInfo(QScriptEngine *engine, const Bodega::ChannelInfo &info)
{
QScriptValue obj = engine->newObject();
obj.setProperty("id", info.id);
obj.setProperty("name", info.name);
obj.setProperty("description", info.description);
obj.setProperty("assetCount", info.assetCount);
//obj.setProperty("images", images);
return obj;
}
void channelInfoFromQScriptValue(const QScriptValue &scriptValue, Bodega::ChannelInfo &info)
{
QScriptValueIterator it(scriptValue);
while (it.hasNext()) {
it.next();
//kDebug() << it.name() << "is" << it.value().toString();
if (it.name() == "id") {
info.id = it.value().toString();
} else if (it.name() == "name") {
info.name = it.value().toString();
} else if (it.name() == "description") {
info.description = it.value().toString();
} else if (it.name() == "assetCount") {
info.assetCount = it.value().toInteger();
}
}
}
QScriptValue qScriptValueFromAssetInfo(QScriptEngine *engine, const Bodega::AssetInfo &info)
{
QScriptValue obj = engine->newObject();
obj.setProperty("id", info.id);
obj.setProperty("license", info.license);
obj.setProperty("partnerId", info.partnerId);
obj.setProperty("partnerName", info.partnerName);
obj.setProperty("name", info.name);
obj.setProperty("filename", info.filename);
obj.setProperty("version", info.version);
//obj.setProperty("images", info.images);
obj.setProperty("description", info.description);
obj.setProperty("points", info.points);
obj.setProperty("canDownload", info.canDownload);
QScriptValue imageObj = engine->newObject();
imageObj.setProperty("tiny", info.images[ImageTiny].toString());
imageObj.setProperty("small", info.images[ImageSmall].toString());
imageObj.setProperty("medium", info.images[ImageMedium].toString());
imageObj.setProperty("large", info.images[ImageLarge].toString());
imageObj.setProperty("huge", info.images[ImageHuge].toString());
imageObj.setProperty("previews", info.images[ImagePreviews].toString());
obj.setProperty("images", imageObj);
return obj;
}
void assetInfoFromQScriptValue(const QScriptValue &scriptValue, Bodega::AssetInfo &info)
{
QScriptValueIterator it(scriptValue);
while (it.hasNext()) {
it.next();
if (it.name() == "id") {
info.id = it.value().toString();
} else if (it.name() == "license") {
info.license = it.value().toString();
} else if (it.name() == "partnerId") {
info.partnerId = it.value().toString();
} else if (it.name() == "partnerName") {
info.partnerName = it.value().toString();
} else if (it.name() == "name") {
info.name = it.value().toString();
} else if (it.name() == "filename") {
info.filename = it.value().toString();
} else if (it.name() == "version") {
info.version = it.value().toString();
} else if (it.name() == "description") {
info.description = it.value().toString();
} else if (it.name() == "points") {
info.points = it.value().toInteger();
} else if (it.name() == "canDownload") {
info.canDownload = it.value().toBool();
} else if (it.name() == "images") {
QMap<ImageUrl, QUrl> images;
QScriptValueIterator imageIt(scriptValue);
while (imageIt.hasNext()) {
imageIt.next();
if (imageIt.name() == "tiny") {
images[ImageTiny] = imageIt.value().toString();
} else if (imageIt.name() == "small") {
images[ImageSmall] = imageIt.value().toString();
} else if (imageIt.name() == "medium") {
images[ImageMedium] = imageIt.value().toString();
} else if (imageIt.name() == "large") {
images[ImageLarge] = imageIt.value().toString();
} else if (imageIt.name() == "huge") {
images[ImageHuge] = imageIt.value().toString();
} else if (imageIt.name() == "previews") {
images[ImagePreviews] = imageIt.value().toString();
}
}
info.images = images;
}
}
}
QScriptValue qScriptValueFromTags(QScriptEngine *engine, const Bodega::Tags &tags)
{
QScriptValue obj = engine->newObject();
foreach (const QString &key, tags.keys()) {
QScriptValue list = engine->newArray();
int i = 0;
foreach (const QString &value, tags.values(key)) {
list.setProperty(i, value);
++i;
}
obj.setProperty(key, list);
}
return obj;
}
void tagsFromQScriptValue(const QScriptValue &scriptValue, Bodega::Tags &tags)
{
QScriptValueIterator it(scriptValue);
while (it.hasNext()) {
it.next();
QScriptValueIterator tagIterator(it.value());
while (tagIterator.hasNext()) {
tags.insert(it.name(), tagIterator.value().toString());
}
}
}
QScriptValue qScriptValueFromParticipantInfo(QScriptEngine *engine, const Bodega::ParticipantInfo &info)
{
QScriptValue obj = engine->newObject();
obj.setProperty("assetCount", info.assetCount);
obj.setProperty("channelCount", info.channelCount);
obj.setProperty("pointsOwed", info.pointsOwed);
obj.setProperty("organization", info.organization);
obj.setProperty("firstName", info.firstName);
obj.setProperty("lastName", info.lastName);
obj.setProperty("email", info.email);
return obj;
}
void participantInfoFromQScriptValue(const QScriptValue &scriptValue, Bodega::ParticipantInfo &info)
{
info.assetCount = scriptValue.property("assetCount").toInt32();
info.channelCount = scriptValue.property("channelCount").toInt32();
info.pointsOwed = scriptValue.property("pointsOwed").toInt32();
info.organization = scriptValue.property("organization").toString();
info.firstName = scriptValue.property("firstName").toString();
info.lastName = scriptValue.property("lastName").toString();
info.email = scriptValue.property("email").toString();
}
BodegaStore::BodegaStore()
: KDeclarativeMainWindow(),
m_historyModel(0)
{
// For kde-runtime 4.8 compabitility, the appbackgrounds image provider is only
// in PlasmaExtras 4.9 (master currently)
// FIXME: Remove this call and the class from commmon/ once we can depend on 4.9
if (!declarativeView()->engine()->imageProvider("appbackgrounds")) {
declarativeView()->engine()->addImageProvider(QLatin1String("appbackgrounds"), new AppBackgroundProvider);
}
declarativeView()->setPackageName("com.coherenttheory.addonsapp");
qmlRegisterType<Bodega::ParticipantInfoJob>();
qmlRegisterType<Bodega::AssetJob>();
qmlRegisterType<Bodega::AssetOperations>();
qmlRegisterType<Bodega::ChannelsJob>();
qmlRegisterType<Bodega::HistoryModel>();
qmlRegisterType<Bodega::Model>();
qmlRegisterType<Bodega::NetworkJob>();
qmlRegisterType<Bodega::RegisterJob>();
qmlRegisterType<Bodega::Session>();
qmlRegisterType<Bodega::SignOnJob>();
qmlRegisterType<Bodega::InstallJob>();
qmlRegisterType<Bodega::InstallJobsModel>();
qmlRegisterType<Bodega::UninstallJob>();
qmlRegisterUncreatableType<ErrorCode>("com.coherenttheory.addonsapp", 1, 0, "ErrorCode", QLatin1String("Do not create objects of this type."));
qScriptRegisterMetaType<Bodega::Error>(declarativeView()->scriptEngine(), qScriptValueFromError, errorFromQScriptValue, QScriptValue());
qScriptRegisterMetaType<Bodega::ChannelInfo>(declarativeView()->scriptEngine(), qScriptValueFromChannelInfo, channelInfoFromQScriptValue, QScriptValue());
qScriptRegisterMetaType<Bodega::AssetInfo>(declarativeView()->scriptEngine(), qScriptValueFromAssetInfo, assetInfoFromQScriptValue, QScriptValue());
qScriptRegisterMetaType<Bodega::Tags>(declarativeView()->scriptEngine(), qScriptValueFromTags, tagsFromQScriptValue, QScriptValue());
qScriptRegisterMetaType<Bodega::ParticipantInfo>(declarativeView()->scriptEngine(), qScriptValueFromParticipantInfo, participantInfoFromQScriptValue, QScriptValue());
m_session = new Session(this);
KConfigGroup config(KGlobal::config(), "AddOns");
m_session->setBaseUrl(config.readEntry("URL", "http://addons.makeplaylive.com:3000"));
m_session->setStoreId(config.readEntry("Store", "VIVALDI-1"));
m_channelsModel = new Bodega::Model(this);
m_channelsModel->setSession(m_session);
m_searchModel = new Bodega::Model(this);
m_searchModel->setSession(m_session);
declarativeView()->rootContext()->setContextProperty("bodegaClient", this);
}
BodegaStore::~BodegaStore()
{
}
Session* BodegaStore::session() const
{
return m_session;
}
Model* BodegaStore::channelsModel() const
{
return m_channelsModel;
}
Model* BodegaStore::searchModel() const
{
return m_searchModel;
}
HistoryModel *BodegaStore::historyModel()
{
if (!m_historyModel) {
m_historyUsers = 0;
m_historyModel = new HistoryModel(m_session);
m_historyModel->setSession(m_session);
}
return m_historyModel;
}
void BodegaStore::historyInUse(bool used)
{
if (used) {
++m_historyUsers;
} else {
--m_historyUsers;
if (m_historyUsers < 1) {
m_historyUsers = 0;
m_historyModel->deleteLater();
m_historyModel = 0;
}
}
}
void BodegaStore::forgetCredentials() const
{
m_session->setUserName(QString());
m_session->setPassword(QString());
saveCredentials();
}
void BodegaStore::saveCredentials() const
{
KWallet::Wallet *wallet = KWallet::Wallet::openWallet(KWallet::Wallet::NetworkWallet(),
winId(), KWallet::Wallet::Synchronous);
if (wallet->isOpen() &&
(wallet->hasFolder("MakePlayLive") ||
wallet->createFolder("MakePlayLive")) &&
wallet->setFolder("MakePlayLive")) {
QMap<QString, QString> map;
map["username"] = m_session->userName();
map["password"] = m_session->password();
if (wallet->writeMap("credentials", map) != 0) {
kWarning() << "Unable to write credentials to wallet";
}
} else {
kWarning() << "Unable to open wallet";
}
}
QVariantHash BodegaStore::retrieveCredentials() const
{
KWallet::Wallet *wallet = KWallet::Wallet::openWallet(KWallet::Wallet::NetworkWallet(),
winId(), KWallet::Wallet::Synchronous);
if (wallet && wallet->isOpen() && wallet->setFolder("MakePlayLive")) {
QMap<QString, QString> map;
if (wallet->readMap("credentials", map) == 0) {
QVariantHash hash;
hash["username"] = map["username"];
hash["password"] = map["password"];
return hash;
} else {
kWarning() << "Unable to read credentials from wallet";
}
} else {
kWarning() << "Unable to open wallet";
}
return QVariantHash();
}
#include "bodegastore.moc"
<|endoftext|> |
<commit_before>/*
* Copyright (C) 2013 - 2015 Hong Jen Yee (PCMan) <[email protected]>
*
* 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 "pathedit.h"
#include "pathedit_p.h"
#include <QCompleter>
#include <QStringListModel>
#include <QStringBuilder>
#include <QThread>
#include <QDebug>
#include <QKeyEvent>
#include <QDir>
namespace Fm {
void PathEditJob::runJob() {
GError* err = nullptr;
GFileEnumerator* enu = g_file_enumerate_children(dirName,
// G_FILE_ATTRIBUTE_STANDARD_NAME","
G_FILE_ATTRIBUTE_STANDARD_DISPLAY_NAME","
G_FILE_ATTRIBUTE_STANDARD_TYPE,
G_FILE_QUERY_INFO_NONE, cancellable,
&err);
if(enu) {
while(!g_cancellable_is_cancelled(cancellable)) {
GFileInfo* inf = g_file_enumerator_next_file(enu, cancellable, &err);
if(inf) {
GFileType type = g_file_info_get_file_type(inf);
if(type == G_FILE_TYPE_DIRECTORY) {
const char* name = g_file_info_get_display_name(inf);
// FIXME: encoding conversion here?
subDirs.append(QString::fromUtf8(name));
}
g_object_unref(inf);
}
else {
if(err) {
g_error_free(err);
err = nullptr;
}
else { /* EOF */
break;
}
}
}
g_file_enumerator_close(enu, cancellable, nullptr);
g_object_unref(enu);
}
// finished! let's update the UI in the main thread
Q_EMIT finished();
QThread::currentThread()->quit();
}
PathEdit::PathEdit(QWidget* parent):
QLineEdit(parent),
completer_(new QCompleter()),
model_(new QStringListModel()),
cancellable_(nullptr) {
setCompleter(completer_);
completer_->setModel(model_);
connect(this, &PathEdit::textChanged, this, &PathEdit::onTextChanged);
connect(this, &PathEdit::textEdited, this, &PathEdit::onTextEdited);
}
PathEdit::~PathEdit() {
delete completer_;
if(model_) {
delete model_;
}
if(cancellable_) {
g_cancellable_cancel(cancellable_);
g_object_unref(cancellable_);
}
}
void PathEdit::focusInEvent(QFocusEvent* e) {
QLineEdit::focusInEvent(e);
// build the completion list only when we have the keyboard focus
reloadCompleter(true);
}
void PathEdit::focusOutEvent(QFocusEvent* e) {
QLineEdit::focusOutEvent(e);
// free the completion list since we don't need it anymore
freeCompleter();
}
bool PathEdit::event(QEvent* e) {
// Stop Qt from moving the keyboard focus to the next widget when "Tab" is pressed.
// Instead, we need to do auto-completion in this case.
if(e->type() == QEvent::KeyPress) {
QKeyEvent* keyEvent = static_cast<QKeyEvent*>(e);
if(keyEvent->key() == Qt::Key_Tab && keyEvent->modifiers() == Qt::NoModifier) { // Tab key is pressed
e->accept();
// do auto-completion when the user press the Tab key.
// This fixes #201: https://github.com/lxqt/pcmanfm-qt/issues/201
autoComplete();
return true;
}
}
return QLineEdit::event(e);
}
void PathEdit::onTextEdited(const QString& text) {
// just replace start tilde with home path if text is changed by user
if(text == QLatin1String("~") || text.startsWith(QLatin1String("~/"))) {
QString txt(text);
txt.replace(0, 1, QDir::homePath());
setText(txt); // emits textChanged()
return;
}
}
void PathEdit::onTextChanged(const QString& text) {
if(text == QLatin1String("~") || text.startsWith(QLatin1String("~/"))) {
// do nothing with a start tilde because neither Fm::FilePath nor autocompletion
// understands it; instead, wait until textChanged() is emitted again without it
// WARNING: replacing tilde may not be safe here
return;
}
int pos = text.lastIndexOf('/');
if(pos >= 0) {
++pos;
}
else {
pos = text.length();
}
QString newPrefix = text.left(pos);
if(currentPrefix_ != newPrefix) {
currentPrefix_ = newPrefix;
// only build the completion list if we have the keyboard focus
// if we don't have the focus now, then we'll rebuild the completion list
// when focusInEvent happens. this avoid unnecessary dir loading.
if(hasFocus()) {
reloadCompleter(false);
}
}
}
void PathEdit::autoComplete() {
// find longest common prefix of the strings currently shown in the candidate list
QAbstractItemModel* model = completer_->completionModel();
if(model->rowCount() > 0) {
int minLen = text().length();
QString commonPrefix = model->data(model->index(0, 0)).toString();
for(int row = 1; row < model->rowCount() && commonPrefix.length() > minLen; ++row) {
QModelIndex index = model->index(row, 0);
QString rowText = model->data(index).toString();
int prefixLen = 0;
while(prefixLen < rowText.length() && prefixLen < commonPrefix.length() && rowText[prefixLen] == commonPrefix[prefixLen]) {
++prefixLen;
}
commonPrefix.truncate(prefixLen);
}
if(commonPrefix.length() > minLen) {
setText(commonPrefix);
}
}
}
void PathEdit::reloadCompleter(bool triggeredByFocusInEvent) {
// parent dir has been changed, reload dir list
// if(currentPrefix_[0] == "~") { // special case for home dir
// cancel running dir-listing jobs, if there's any
if(cancellable_) {
g_cancellable_cancel(cancellable_);
g_object_unref(cancellable_);
}
// create a new job to do dir listing
PathEditJob* job = new PathEditJob();
job->edit = this;
job->triggeredByFocusInEvent = triggeredByFocusInEvent;
// need to use fm_file_new_for_commandline_arg() rather than g_file_new_for_commandline_arg().
// otherwise, our own vfs, such as menu://, won't be loaded.
job->dirName = g_file_new_for_commandline_arg(currentPrefix_.toLocal8Bit().constData());
// qDebug("load: %s", g_file_get_uri(data->dirName));
cancellable_ = g_cancellable_new();
job->cancellable = (GCancellable*)g_object_ref(cancellable_);
// launch a new worker thread to handle the job
QThread* thread = new QThread();
job->moveToThread(thread);
connect(job, &PathEditJob::finished, this, &PathEdit::onJobFinished, Qt::BlockingQueuedConnection);
// connect(job, &PathEditJob::finished, thread, &QThread::quit);
connect(thread, &QThread::started, job, &PathEditJob::runJob);
connect(thread, &QThread::finished, thread, &QObject::deleteLater);
connect(thread, &QThread::finished, job, &QObject::deleteLater);
thread->start(QThread::LowPriority);
}
void PathEdit::freeCompleter() {
if(cancellable_) {
g_cancellable_cancel(cancellable_);
g_object_unref(cancellable_);
cancellable_ = nullptr;
}
model_->setStringList(QStringList());
}
// This slot is called from main thread so it's safe to access the GUI
void PathEdit::onJobFinished() {
PathEditJob* data = static_cast<PathEditJob*>(sender());
if(!g_cancellable_is_cancelled(data->cancellable)) {
// update the completer only if the job is not cancelled
QStringList::iterator it;
for(it = data->subDirs.begin(); it != data->subDirs.end(); ++it) {
// qDebug("%s", it->toUtf8().constData());
*it = (currentPrefix_ % *it);
}
model_->setStringList(data->subDirs);
// trigger completion manually
if(hasFocus() && !data->triggeredByFocusInEvent) {
completer_->complete();
}
}
else {
model_->setStringList(QStringList());
}
if(cancellable_) {
g_object_unref(cancellable_);
cancellable_ = nullptr;
}
}
} // namespace Fm
<commit_msg>Just made path-edit completer insensitive to case (#288)<commit_after>/*
* Copyright (C) 2013 - 2015 Hong Jen Yee (PCMan) <[email protected]>
*
* 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 "pathedit.h"
#include "pathedit_p.h"
#include <QCompleter>
#include <QStringListModel>
#include <QStringBuilder>
#include <QThread>
#include <QDebug>
#include <QKeyEvent>
#include <QDir>
namespace Fm {
void PathEditJob::runJob() {
GError* err = nullptr;
GFileEnumerator* enu = g_file_enumerate_children(dirName,
// G_FILE_ATTRIBUTE_STANDARD_NAME","
G_FILE_ATTRIBUTE_STANDARD_DISPLAY_NAME","
G_FILE_ATTRIBUTE_STANDARD_TYPE,
G_FILE_QUERY_INFO_NONE, cancellable,
&err);
if(enu) {
while(!g_cancellable_is_cancelled(cancellable)) {
GFileInfo* inf = g_file_enumerator_next_file(enu, cancellable, &err);
if(inf) {
GFileType type = g_file_info_get_file_type(inf);
if(type == G_FILE_TYPE_DIRECTORY) {
const char* name = g_file_info_get_display_name(inf);
// FIXME: encoding conversion here?
subDirs.append(QString::fromUtf8(name));
}
g_object_unref(inf);
}
else {
if(err) {
g_error_free(err);
err = nullptr;
}
else { /* EOF */
break;
}
}
}
g_file_enumerator_close(enu, cancellable, nullptr);
g_object_unref(enu);
}
// finished! let's update the UI in the main thread
Q_EMIT finished();
QThread::currentThread()->quit();
}
PathEdit::PathEdit(QWidget* parent):
QLineEdit(parent),
completer_(new QCompleter()),
model_(new QStringListModel()),
cancellable_(nullptr) {
completer_->setCaseSensitivity(Qt::CaseInsensitive);
setCompleter(completer_);
completer_->setModel(model_);
connect(this, &PathEdit::textChanged, this, &PathEdit::onTextChanged);
connect(this, &PathEdit::textEdited, this, &PathEdit::onTextEdited);
}
PathEdit::~PathEdit() {
delete completer_;
if(model_) {
delete model_;
}
if(cancellable_) {
g_cancellable_cancel(cancellable_);
g_object_unref(cancellable_);
}
}
void PathEdit::focusInEvent(QFocusEvent* e) {
QLineEdit::focusInEvent(e);
// build the completion list only when we have the keyboard focus
reloadCompleter(true);
}
void PathEdit::focusOutEvent(QFocusEvent* e) {
QLineEdit::focusOutEvent(e);
// free the completion list since we don't need it anymore
freeCompleter();
}
bool PathEdit::event(QEvent* e) {
// Stop Qt from moving the keyboard focus to the next widget when "Tab" is pressed.
// Instead, we need to do auto-completion in this case.
if(e->type() == QEvent::KeyPress) {
QKeyEvent* keyEvent = static_cast<QKeyEvent*>(e);
if(keyEvent->key() == Qt::Key_Tab && keyEvent->modifiers() == Qt::NoModifier) { // Tab key is pressed
e->accept();
// do auto-completion when the user press the Tab key.
// This fixes #201: https://github.com/lxqt/pcmanfm-qt/issues/201
autoComplete();
return true;
}
}
return QLineEdit::event(e);
}
void PathEdit::onTextEdited(const QString& text) {
// just replace start tilde with home path if text is changed by user
if(text == QLatin1String("~") || text.startsWith(QLatin1String("~/"))) {
QString txt(text);
txt.replace(0, 1, QDir::homePath());
setText(txt); // emits textChanged()
return;
}
}
void PathEdit::onTextChanged(const QString& text) {
if(text == QLatin1String("~") || text.startsWith(QLatin1String("~/"))) {
// do nothing with a start tilde because neither Fm::FilePath nor autocompletion
// understands it; instead, wait until textChanged() is emitted again without it
// WARNING: replacing tilde may not be safe here
return;
}
int pos = text.lastIndexOf('/');
if(pos >= 0) {
++pos;
}
else {
pos = text.length();
}
QString newPrefix = text.left(pos);
if(currentPrefix_ != newPrefix) {
currentPrefix_ = newPrefix;
// only build the completion list if we have the keyboard focus
// if we don't have the focus now, then we'll rebuild the completion list
// when focusInEvent happens. this avoid unnecessary dir loading.
if(hasFocus()) {
reloadCompleter(false);
}
}
}
void PathEdit::autoComplete() {
// find longest common prefix of the strings currently shown in the candidate list
QAbstractItemModel* model = completer_->completionModel();
if(model->rowCount() > 0) {
int minLen = text().length();
QString commonPrefix = model->data(model->index(0, 0)).toString();
for(int row = 1; row < model->rowCount() && commonPrefix.length() > minLen; ++row) {
QModelIndex index = model->index(row, 0);
QString rowText = model->data(index).toString();
int prefixLen = 0;
while(prefixLen < rowText.length() && prefixLen < commonPrefix.length() && rowText[prefixLen] == commonPrefix[prefixLen]) {
++prefixLen;
}
commonPrefix.truncate(prefixLen);
}
if(commonPrefix.length() > minLen) {
setText(commonPrefix);
}
}
}
void PathEdit::reloadCompleter(bool triggeredByFocusInEvent) {
// parent dir has been changed, reload dir list
// if(currentPrefix_[0] == "~") { // special case for home dir
// cancel running dir-listing jobs, if there's any
if(cancellable_) {
g_cancellable_cancel(cancellable_);
g_object_unref(cancellable_);
}
// create a new job to do dir listing
PathEditJob* job = new PathEditJob();
job->edit = this;
job->triggeredByFocusInEvent = triggeredByFocusInEvent;
// need to use fm_file_new_for_commandline_arg() rather than g_file_new_for_commandline_arg().
// otherwise, our own vfs, such as menu://, won't be loaded.
job->dirName = g_file_new_for_commandline_arg(currentPrefix_.toLocal8Bit().constData());
// qDebug("load: %s", g_file_get_uri(data->dirName));
cancellable_ = g_cancellable_new();
job->cancellable = (GCancellable*)g_object_ref(cancellable_);
// launch a new worker thread to handle the job
QThread* thread = new QThread();
job->moveToThread(thread);
connect(job, &PathEditJob::finished, this, &PathEdit::onJobFinished, Qt::BlockingQueuedConnection);
// connect(job, &PathEditJob::finished, thread, &QThread::quit);
connect(thread, &QThread::started, job, &PathEditJob::runJob);
connect(thread, &QThread::finished, thread, &QObject::deleteLater);
connect(thread, &QThread::finished, job, &QObject::deleteLater);
thread->start(QThread::LowPriority);
}
void PathEdit::freeCompleter() {
if(cancellable_) {
g_cancellable_cancel(cancellable_);
g_object_unref(cancellable_);
cancellable_ = nullptr;
}
model_->setStringList(QStringList());
}
// This slot is called from main thread so it's safe to access the GUI
void PathEdit::onJobFinished() {
PathEditJob* data = static_cast<PathEditJob*>(sender());
if(!g_cancellable_is_cancelled(data->cancellable)) {
// update the completer only if the job is not cancelled
QStringList::iterator it;
for(it = data->subDirs.begin(); it != data->subDirs.end(); ++it) {
// qDebug("%s", it->toUtf8().constData());
*it = (currentPrefix_ % *it);
}
model_->setStringList(data->subDirs);
// trigger completion manually
if(hasFocus() && !data->triggeredByFocusInEvent) {
completer_->complete();
}
}
else {
model_->setStringList(QStringList());
}
if(cancellable_) {
g_object_unref(cancellable_);
cancellable_ = nullptr;
}
}
} // namespace Fm
<|endoftext|> |
<commit_before>#ifndef INCLUDE_AL_FILE_HPP
#define INCLUDE_AL_FILE_HPP
/* Allocore --
Multimedia / virtual environment application class library
Copyright (C) 2009. AlloSphere Research Group, Media Arts & Technology, UCSB.
Copyright (C) 2012. The Regents of the University of California.
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 University of California 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 HOLDER OR CONTRIBUTORS BE
LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
POSSIBILITY OF SUCH DAMAGE.
File description:
Utilities for file management
File author(s):
Graham Wakefield, 2010, [email protected]
Lance Putnam, 2010, [email protected]
*/
#include <limits.h>
#include <stdlib.h>
#include <unistd.h>
#include <stdio.h>
#include <string>
#include <list>
#include "allocore/system/al_Config.h"
#ifdef AL_WINDOWS
#define AL_FILE_DELIMITER '\\'
#define AL_FILE_DELIMITER_STR "\\"
#else
#define AL_FILE_DELIMITER '/'
#define AL_FILE_DELIMITER_STR "/"
#endif
#define AL_PATH_MAX (4096)
namespace al{
class FilePath;
/// File
/// Used to retrieve data from and store data to disk.
/// The term 'path' means a file or directory.
class File{
public:
/// @param[in] path path of file
/// @param[in] mode i/o mode w, r, wb, rb
/// @param[in] open whether to open the file
File(const std::string& path, const std::string& mode="r", bool open=false);
File(const FilePath& path, const std::string& mode="r", bool open=false);
~File();
void close(); ///< Close file
bool open(); ///< Open file with specified i/o mode
File& mode(const std::string& v){ mMode=v; return *this; }
File& path(const std::string& v){ mPath=v; return *this; }
/// Write string to file
int write(const std::string& v){ return write(v.data(), 1, v.length()); }
/// Write memory elements to file
int write(const void * v, int itemSizeInBytes, int items=1){
int itemsWritten = fwrite(v, itemSizeInBytes, items, mFP);
mSizeBytes += itemsWritten * itemSizeInBytes;
return itemsWritten;
}
/// Read memory elements from file
int read(void * v, int size, int items=1){ return fread(v, size, items, mFP); }
/// Quick and dirty write memory to file
static int write(const std::string& path, const void * v, int size, int items=1);
/// Returns character string of file contents (read mode only)
const char * readAll();
/// Returns whether file is open
bool opened() const { return 0 != mFP; }
/// Returns file i/o mode string
const std::string& mode() const { return mMode; }
/// Returns path string
const std::string& path() const { return mPath; }
/// Returns size, in bytes, of file contents
int size() const { return mSizeBytes; }
/// Return modification time of file (or 0 on failure) as number of seconds since 00:00:00 January 1, 1970 UTC
al_sec modified() const;
/// Return last access time of file (or 0 on failure) as number of seconds since 00:00:00 January 1, 1970 UTC
al_sec accessed() const;
/// Return creation time of file (or 0 on failure) as number of seconds since 00:00:00 January 1, 1970 UTC
al_sec created() const;
/// Return size file (or 0 on failure)
size_t sizeFile() const;
/// Return space used on disk of file (or 0 on failure)
size_t storage() const;
FILE * filePointer() { return mFP; }
/// Returns string ensured to having an ending delimiter
/// The directory string argument is not checked to actually exist in
/// the file system.
static std::string conformDirectory(const std::string& dir);
/// Conforms path
/// This function takes a path as an argument and returns a new path with
/// correct platform-specific directory delimiters, '/' or '\' and
/// an extra delimiter at the end if the argument is a valid directory.
static std::string conformPathToOS(const std::string& src);
/// Convert relative paths to absolute paths
static std::string absolutePath(const std::string& src);
/// Extracts the directory-part of file name.
/// The directory-part of the file name is everything up through (and
/// including) the last slash in it. If the file name contains no slash,
/// the directory part is the string ‘./’. E.g., /usr/bin/man -> /usr/bin/.
static std::string directory(const std::string& src);
/// Returns whether a file or directory exists
static bool exists(const std::string& path);
/// Returns whether a file in a directory exists
static bool exists(const std::string& name, const std::string& path){
return exists(path+name);
}
/// Returns true if path is a directory
static bool isDirectory(const std::string& src);
/// Search for file or directory back from current directory
/// @param[out] prefixPath If the file is found, this contains a series of
/// "../" that can be prefixed to 'matchPath' to get
/// its actual location.
/// @param[in] matchPath File or directory to search for
/// @param[in] maxDepth Maximum number of directories to search back
/// \returns whether the file or directory was found
static bool searchBack(std::string& prefixPath, const std::string& matchPath, int maxDepth=6);
/// Search for file or directory back from current directory
/// @param[in,out] path Input is a file or directory to search for.
/// If the file is found, the output contains a series of
/// "../" prefixed to the input. Otherwise, the input
/// path is not modified.
/// @param[in] maxDepth Maximum number of directories to search back
/// \returns whether the file or directory was found
static bool searchBack(std::string& path, int maxDepth=6);
/* static al_sec modified(const std::string& path){ return File(path).modified(); }
static al_sec accessed(const std::string& path){ return File(path).accessed(); }
static al_sec created (const std::string& path){ return File(path).created(); }
static size_t sizeFile(const std::string& path){ return File(path).sizeFile(); }
static size_t storage (const std::string& path){ return File(path).storage(); }
*/
protected:
class Impl; Impl * mImpl;
std::string mPath;
std::string mMode;
char * mContent;
int mSizeBytes;
FILE * mFP;
void dtor();
void freeContent();
void allocContent(int n);
void getSize();
};
/// A pair of path (folder/directory) and file name
class FilePath {
public:
FilePath(){}
/// @param[in] file File name without directory
/// @param[in] path Directory of file
FilePath(const std::string& file, const std::string& path)
: mPath(path), mFile(file) {}
/// @param[in] fullpath Full path to file (directory + file name)
explicit FilePath(const std::string& fullpath);
/// Get file name without directory
const std::string& file() const { return mFile; }
/// Get path (directory) of file
const std::string& path() const { return mPath; }
/// Get file with directory
std::string filepath() const { return path()+file(); }
/// Returns whether file part is valid
bool valid() const { return file()!=""; }
/// Set file name without directory
FilePath& file(const std::string& v) { mFile=v; return *this; }
/// Set path (directory) of file
FilePath& path(const std::string& v) { mPath=v; return *this; }
protected:
std::string mPath;
std::string mFile;
};
/// A handy way to manage several possible search paths
class SearchPaths {
public:
typedef std::pair<std::string, bool> searchpath;
typedef std::list<searchpath> searchpathlist;
typedef std::list<searchpath>::iterator iterator;
SearchPaths(){}
SearchPaths(const std::string& file);
SearchPaths(int argc, char * const argv[], bool recursive=true);
SearchPaths(const SearchPaths& cpy);
/// find a file in the searchpaths
FilePath find(const std::string& filename);
/// add a path to search in; recursive searching is optional
void addSearchPath(const std::string& path, bool recursive = true);
void addRelativePath(std::string rel, bool recursive=true) {
addSearchPath(appPath() + rel, recursive);
}
/// adds best estimate of application launch paths (cwd etc.)
/// can pass in argv from the main() function if desired.
void addAppPaths(int argc, char * const argv[], bool recursive = true);
void addAppPaths(int argc, const char ** argv, bool recursive = true);
void addAppPaths(std::string path, bool recursive = true);
void addAppPaths(bool recursive = true);
const std::string& appPath() const { return mAppPath; }
void print() const;
iterator begin() { return mSearchPaths.begin(); }
iterator end() { return mSearchPaths.end(); }
protected:
std::list<searchpath> mSearchPaths;
std::string mAppPath;
};
} // al::
#endif
<commit_msg>uncomment accidentally commented out functions<commit_after>#ifndef INCLUDE_AL_FILE_HPP
#define INCLUDE_AL_FILE_HPP
/* Allocore --
Multimedia / virtual environment application class library
Copyright (C) 2009. AlloSphere Research Group, Media Arts & Technology, UCSB.
Copyright (C) 2012. The Regents of the University of California.
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 University of California 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 HOLDER OR CONTRIBUTORS BE
LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
POSSIBILITY OF SUCH DAMAGE.
File description:
Utilities for file management
File author(s):
Graham Wakefield, 2010, [email protected]
Lance Putnam, 2010, [email protected]
*/
#include <limits.h>
#include <stdlib.h>
#include <unistd.h>
#include <stdio.h>
#include <string>
#include <list>
#include "allocore/system/al_Config.h"
#ifdef AL_WINDOWS
#define AL_FILE_DELIMITER '\\'
#define AL_FILE_DELIMITER_STR "\\"
#else
#define AL_FILE_DELIMITER '/'
#define AL_FILE_DELIMITER_STR "/"
#endif
#define AL_PATH_MAX (4096)
namespace al{
class FilePath;
/// File
/// Used to retrieve data from and store data to disk.
/// The term 'path' means a file or directory.
class File{
public:
/// @param[in] path path of file
/// @param[in] mode i/o mode w, r, wb, rb
/// @param[in] open whether to open the file
File(const std::string& path, const std::string& mode="r", bool open=false);
File(const FilePath& path, const std::string& mode="r", bool open=false);
~File();
void close(); ///< Close file
bool open(); ///< Open file with specified i/o mode
File& mode(const std::string& v){ mMode=v; return *this; }
File& path(const std::string& v){ mPath=v; return *this; }
/// Write string to file
int write(const std::string& v){ return write(v.data(), 1, v.length()); }
/// Write memory elements to file
int write(const void * v, int itemSizeInBytes, int items=1){
int itemsWritten = fwrite(v, itemSizeInBytes, items, mFP);
mSizeBytes += itemsWritten * itemSizeInBytes;
return itemsWritten;
}
/// Read memory elements from file
int read(void * v, int size, int items=1){ return fread(v, size, items, mFP); }
/// Quick and dirty write memory to file
static int write(const std::string& path, const void * v, int size, int items=1);
/// Returns character string of file contents (read mode only)
const char * readAll();
/// Returns whether file is open
bool opened() const { return 0 != mFP; }
/// Returns file i/o mode string
const std::string& mode() const { return mMode; }
/// Returns path string
const std::string& path() const { return mPath; }
/// Returns size, in bytes, of file contents
int size() const { return mSizeBytes; }
/// Return modification time of file (or 0 on failure) as number of seconds since 00:00:00 January 1, 1970 UTC
al_sec modified() const;
/// Return last access time of file (or 0 on failure) as number of seconds since 00:00:00 January 1, 1970 UTC
al_sec accessed() const;
/// Return creation time of file (or 0 on failure) as number of seconds since 00:00:00 January 1, 1970 UTC
al_sec created() const;
/// Return size file (or 0 on failure)
size_t sizeFile() const;
/// Return space used on disk of file (or 0 on failure)
size_t storage() const;
FILE * filePointer() { return mFP; }
/// Returns string ensured to having an ending delimiter
/// The directory string argument is not checked to actually exist in
/// the file system.
static std::string conformDirectory(const std::string& dir);
/// Conforms path
/// This function takes a path as an argument and returns a new path with
/// correct platform-specific directory delimiters, '/' or '\' and
/// an extra delimiter at the end if the argument is a valid directory.
static std::string conformPathToOS(const std::string& src);
/// Convert relative paths to absolute paths
static std::string absolutePath(const std::string& src);
/// Extracts the directory-part of file name.
/// The directory-part of the file name is everything up through (and
/// including) the last slash in it. If the file name contains no slash,
/// the directory part is the string ‘./’. E.g., /usr/bin/man -> /usr/bin/.
static std::string directory(const std::string& src);
/// Returns whether a file or directory exists
static bool exists(const std::string& path);
/// Returns whether a file in a directory exists
static bool exists(const std::string& name, const std::string& path){
return exists(path+name);
}
/// Returns true if path is a directory
static bool isDirectory(const std::string& src);
/// Search for file or directory back from current directory
/// @param[out] prefixPath If the file is found, this contains a series of
/// "../" that can be prefixed to 'matchPath' to get
/// its actual location.
/// @param[in] matchPath File or directory to search for
/// @param[in] maxDepth Maximum number of directories to search back
/// \returns whether the file or directory was found
static bool searchBack(std::string& prefixPath, const std::string& matchPath, int maxDepth=6);
/// Search for file or directory back from current directory
/// @param[in,out] path Input is a file or directory to search for.
/// If the file is found, the output contains a series of
/// "../" prefixed to the input. Otherwise, the input
/// path is not modified.
/// @param[in] maxDepth Maximum number of directories to search back
/// \returns whether the file or directory was found
static bool searchBack(std::string& path, int maxDepth=6);
// TODO: why have these?
static al_sec modified(const std::string& path){ return File(path).modified(); }
static al_sec accessed(const std::string& path){ return File(path).accessed(); }
static al_sec created (const std::string& path){ return File(path).created(); }
static size_t sizeFile(const std::string& path){ return File(path).sizeFile(); }
static size_t storage (const std::string& path){ return File(path).storage(); }
protected:
class Impl; Impl * mImpl;
std::string mPath;
std::string mMode;
char * mContent;
int mSizeBytes;
FILE * mFP;
void dtor();
void freeContent();
void allocContent(int n);
void getSize();
};
/// A pair of path (folder/directory) and file name
class FilePath {
public:
FilePath(){}
/// @param[in] file File name without directory
/// @param[in] path Directory of file
FilePath(const std::string& file, const std::string& path)
: mPath(path), mFile(file) {}
/// @param[in] fullpath Full path to file (directory + file name)
explicit FilePath(const std::string& fullpath);
/// Get file name without directory
const std::string& file() const { return mFile; }
/// Get path (directory) of file
const std::string& path() const { return mPath; }
/// Get file with directory
std::string filepath() const { return path()+file(); }
/// Returns whether file part is valid
bool valid() const { return file()!=""; }
/// Set file name without directory
FilePath& file(const std::string& v) { mFile=v; return *this; }
/// Set path (directory) of file
FilePath& path(const std::string& v) { mPath=v; return *this; }
protected:
std::string mPath;
std::string mFile;
};
/// A handy way to manage several possible search paths
class SearchPaths {
public:
typedef std::pair<std::string, bool> searchpath;
typedef std::list<searchpath> searchpathlist;
typedef std::list<searchpath>::iterator iterator;
SearchPaths(){}
SearchPaths(const std::string& file);
SearchPaths(int argc, char * const argv[], bool recursive=true);
SearchPaths(const SearchPaths& cpy);
/// find a file in the searchpaths
FilePath find(const std::string& filename);
/// add a path to search in; recursive searching is optional
void addSearchPath(const std::string& path, bool recursive = true);
void addRelativePath(std::string rel, bool recursive=true) {
addSearchPath(appPath() + rel, recursive);
}
/// adds best estimate of application launch paths (cwd etc.)
/// can pass in argv from the main() function if desired.
void addAppPaths(int argc, char * const argv[], bool recursive = true);
void addAppPaths(int argc, const char ** argv, bool recursive = true);
void addAppPaths(std::string path, bool recursive = true);
void addAppPaths(bool recursive = true);
const std::string& appPath() const { return mAppPath; }
void print() const;
iterator begin() { return mSearchPaths.begin(); }
iterator end() { return mSearchPaths.end(); }
protected:
std::list<searchpath> mSearchPaths;
std::string mAppPath;
};
} // al::
#endif
<|endoftext|> |
<commit_before>/**
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#include <errno.h>
#include <signal.h>
#include <stdio.h> // For perror.
#include <string.h>
#include <map>
#include <set>
#include <process/clock.hpp>
#include <process/defer.hpp>
#include <process/dispatch.hpp>
#include <process/id.hpp>
#include <stout/check.hpp>
#include <stout/exit.hpp>
#include <stout/foreach.hpp>
#include <stout/lambda.hpp>
#include <stout/nothing.hpp>
#include <stout/option.hpp>
#include <stout/os.hpp>
#include <stout/uuid.hpp>
#include "common/type_utils.hpp"
#include "slave/flags.hpp"
#include "slave/process_isolator.hpp"
#include "slave/state.hpp"
using namespace process;
using std::map;
using std::set;
using std::string;
using process::defer;
using process::wait; // Necessary on some OS's to disambiguate.
namespace mesos {
namespace internal {
namespace slave {
using launcher::ExecutorLauncher;
using state::SlaveState;
using state::FrameworkState;
using state::ExecutorState;
using state::RunState;
ProcessIsolator::ProcessIsolator()
: ProcessBase(ID::generate("process-isolator")),
initialized(false) {}
void ProcessIsolator::initialize(
const Flags& _flags,
const Resources& _,
bool _local,
const PID<Slave>& _slave)
{
flags = _flags;
local = _local;
slave = _slave;
initialized = true;
}
void ProcessIsolator::launchExecutor(
const SlaveID& slaveId,
const FrameworkID& frameworkId,
const FrameworkInfo& frameworkInfo,
const ExecutorInfo& executorInfo,
const UUID& uuid,
const string& directory,
const Resources& resources)
{
CHECK(initialized) << "Cannot launch executors before initialization!";
const ExecutorID& executorId = executorInfo.executor_id();
LOG(INFO) << "Launching " << executorId
<< " (" << executorInfo.command().value() << ")"
<< " in " << directory
<< " with resources " << resources
<< "' for framework " << frameworkId;
ProcessInfo* info = new ProcessInfo(frameworkId, executorId);
infos[frameworkId][executorId] = info;
// Use pipes to determine which child has successfully changed session.
int pipes[2];
if (pipe(pipes) < 0) {
PLOG(FATAL) << "Failed to create a pipe";
}
// Set the FD_CLOEXEC flags on these pipes
Try<Nothing> cloexec = os::cloexec(pipes[0]);
CHECK_SOME(cloexec) << "Error setting FD_CLOEXEC on pipe[0]";
cloexec = os::cloexec(pipes[1]);
CHECK_SOME(cloexec) << "Error setting FD_CLOEXEC on pipe[1]";
// Create the ExecutorLauncher instance before the fork for the
// child process to use.
ExecutorLauncher launcher(
slaveId,
frameworkId,
executorInfo.executor_id(),
uuid,
executorInfo.command(),
frameworkInfo.user(),
directory,
flags.work_dir,
slave,
flags.frameworks_home,
flags.hadoop_home,
!local,
flags.switch_user,
frameworkInfo.checkpoint());
// We get the environment map for launching mesos-launcher before
// the fork, because we have seen deadlock issues with ostringstream
// in the forked process before it calls exec.
map<string, string> env = launcher.getLauncherEnvironment();
pid_t pid;
if ((pid = fork()) == -1) {
PLOG(FATAL) << "Failed to fork to launch new executor";
}
if (pid > 0) {
os::close(pipes[1]);
// Get the child's pid via the pipe.
if (read(pipes[0], &pid, sizeof(pid)) == -1) {
PLOG(FATAL) << "Failed to get child PID from pipe";
}
os::close(pipes[0]);
// In parent process.
LOG(INFO) << "Forked executor at " << pid;
// Record the pid (should also be the pgid since we setsid below).
infos[frameworkId][executorId]->pid = pid;
reaper.monitor(pid)
.onAny(defer(PID<ProcessIsolator>(this),
&ProcessIsolator::reaped,
pid,
lambda::_1));
// Tell the slave this executor has started.
dispatch(slave, &Slave::executorStarted, frameworkId, executorId, pid);
} else {
// In child process, we make cleanup easier by putting process
// into it's own session. DO NOT USE GLOG!
os::close(pipes[0]);
// NOTE: We setsid() in a loop because setsid() might fail if another
// process has the same process group id as the calling process.
while ((pid = setsid()) == -1) {
perror("Could not put executor in its own session");
std::cout << "Forking another process and retrying ..." << std::endl;
if ((pid = fork()) == -1) {
perror("Failed to fork to launch executor");
abort();
}
if (pid > 0) {
// In parent process.
// It is ok to suicide here, though process reaper signals the exit,
// because the process isolator ignores unknown processes.
exit(0);
}
}
if (write(pipes[1], &pid, sizeof(pid)) != sizeof(pid)) {
perror("Failed to write PID on pipe");
abort();
}
os::close(pipes[1]);
// Setup the environment for launcher.
foreachpair (const string& key, const string& value, env) {
os::setenv(key, value);
}
const char** args = (const char**) new char*[2];
// Determine path for mesos-launcher.
Try<string> realpath = os::realpath(
path::join(flags.launcher_dir, "mesos-launcher"));
if (realpath.isError()) {
EXIT(1) << "Failed to determine the canonical path "
<< "for the mesos-launcher: " << realpath.error();
}
// Grab a copy of the path so that we can reliably use 'c_str()'.
const string& path = realpath.get();
args[0] = path.c_str();
args[1] = NULL;
// Execute the mesos-launcher!
execvp(args[0], (char* const*) args);
// If we get here, the execvp call failed.
perror("Failed to execvp the mesos-launcher");
abort();
}
}
// NOTE: This function can be called by the isolator itself or by the
// slave if it doesn't hear about an executor exit after it sends a
// shutdown message.
void ProcessIsolator::killExecutor(
const FrameworkID& frameworkId,
const ExecutorID& executorId)
{
CHECK(initialized) << "Cannot kill executors before initialization!";
if (!infos.contains(frameworkId) ||
!infos[frameworkId].contains(executorId) ||
infos[frameworkId][executorId]->killed) {
LOG(ERROR) << "Asked to kill an unknown/killed executor! " << executorId;
return;
}
const Option<pid_t>& pid = infos[frameworkId][executorId]->pid;
if (pid.isSome()) {
// TODO(vinod): Call killtree on the pid of the actual executor process
// that is running the tasks (stored in the local storage by the
// executor module).
os::killtree(pid.get(), SIGKILL, true, true, &LOG(INFO));
// Also kill all processes that belong to the process group of the executor.
// This is valuable in situations where the top level executor process
// exited and hence killtree is unable to kill any spawned orphans.
// NOTE: This assumes that the process group id of the executor process is
// same as its pid (which is expected to be the case with setsid()).
// TODO(vinod): Also (recursively) kill processes belonging to the
// same session, but have a different process group id.
if (killpg(pid.get(), SIGKILL) == -1 && errno != ESRCH) {
PLOG(WARNING) << "Failed to kill process group " << pid.get();
}
infos[frameworkId][executorId]->killed = true;
}
}
void ProcessIsolator::resourcesChanged(
const FrameworkID& frameworkId,
const ExecutorID& executorId,
const Resources& resources)
{
CHECK(initialized) << "Cannot do resourcesChanged before initialization!";
if (!infos.contains(frameworkId) ||
!infos[frameworkId].contains(executorId) ||
infos[frameworkId][executorId]->killed) {
LOG(INFO) << "Asked to update resources for an unknown/killed executor '"
<< executorId << "' of framework " << frameworkId;
return;
}
ProcessInfo* info = CHECK_NOTNULL(infos[frameworkId][executorId]);
info->resources = resources;
// Do nothing; subclasses may override this.
}
Future<Nothing> ProcessIsolator::recover(
const Option<SlaveState>& state)
{
LOG(INFO) << "Recovering isolator";
if (state.isNone()) {
return Nothing();
}
foreachvalue (const FrameworkState& framework, state.get().frameworks) {
foreachvalue (const ExecutorState& executor, framework.executors) {
LOG(INFO) << "Recovering executor '" << executor.id
<< "' of framework " << framework.id;
if (executor.info.isNone()) {
LOG(WARNING) << "Skipping recovery of executor '" << executor.id
<< "' of framework " << framework.id
<< " because its info cannot be recovered";
continue;
}
if (executor.latest.isNone()) {
LOG(WARNING) << "Skipping recovery of executor '" << executor.id
<< "' of framework " << framework.id
<< " because its latest run cannot be recovered";
continue;
}
// We are only interested in the latest run of the executor!
const UUID& uuid = executor.latest.get();
CHECK(executor.runs.contains(uuid));
const RunState& run = executor.runs.get(uuid).get();
ProcessInfo* info =
new ProcessInfo(framework.id, executor.id, run.forkedPid);
infos[framework.id][executor.id] = info;
// Add the pid to the reaper to monitor exit status.
if (run.forkedPid.isSome()) {
reaper.monitor(run.forkedPid.get())
.onAny(defer(PID<ProcessIsolator>(this),
&ProcessIsolator::reaped,
run.forkedPid.get(),
lambda::_1));
}
}
}
return Nothing();
}
Future<ResourceStatistics> ProcessIsolator::usage(
const FrameworkID& frameworkId,
const ExecutorID& executorId)
{
if (!infos.contains(frameworkId) ||
!infos[frameworkId].contains(executorId) ||
infos[frameworkId][executorId]->killed) {
return Future<ResourceStatistics>::failed("Unknown/killed executor");
}
ProcessInfo* info = infos[frameworkId][executorId];
CHECK_NOTNULL(info);
ResourceStatistics result;
result.set_timestamp(Clock::now().secs());
// Set the resource allocations.
const Option<Bytes>& mem = info->resources.mem();
if (mem.isSome()) {
result.set_mem_limit_bytes(mem.get().bytes());
}
const Option<double>& cpus = info->resources.cpus();
if (cpus.isSome()) {
result.set_cpus_limit(cpus.get());
}
CHECK_SOME(info->pid);
Result<os::Process> process = os::process(info->pid.get());
if (!process.isSome()) {
return Future<ResourceStatistics>::failed(
process.isError() ? process.error() : "Process does not exist");
}
result.set_timestamp(Clock::now().secs());
result.set_mem_rss_bytes(process.get().rss.bytes());
result.set_cpus_user_time_secs(process.get().utime.secs());
result.set_cpus_system_time_secs(process.get().stime.secs());
// Now aggregate all descendant process usage statistics.
const Try<set<pid_t> >& children = os::children(info->pid.get(), true);
if (children.isError()) {
return Future<ResourceStatistics>::failed(
"Failed to get children of " + stringify(info->pid.get()) + ": " +
children.error());
}
// Aggregate the usage of all child processes.
foreach (pid_t child, children.get()) {
process = os::process(child);
// Skip processes that disappear.
if (process.isNone()) {
continue;
}
if (process.isError()) {
LOG(WARNING) << "Failed to get status of descendant process " << child
<< " of parent " << info->pid.get() << ": "
<< process.error();
continue;
}
result.set_mem_rss_bytes(
result.mem_rss_bytes() + process.get().rss.bytes());
result.set_cpus_user_time_secs(
result.cpus_user_time_secs() + process.get().utime.secs());
result.set_cpus_system_time_secs(
result.cpus_system_time_secs() + process.get().stime.secs());
}
return result;
}
void ProcessIsolator::reaped(pid_t pid, const Future<Option<int> >& status)
{
foreachkey (const FrameworkID& frameworkId, infos) {
foreachkey (const ExecutorID& executorId, infos[frameworkId]) {
ProcessInfo* info = infos[frameworkId][executorId];
if (info->pid.isSome() && info->pid.get() == pid) {
if (!status.isReady()) {
LOG(ERROR) << "Failed to get the status for executor '" << executorId
<< "' of framework " << frameworkId << ": "
<< (status.isFailed() ? status.failure() : "discarded");
return;
}
LOG(INFO) << "Telling slave of terminated executor '" << executorId
<< "' of framework " << frameworkId;
dispatch(slave,
&Slave::executorTerminated,
frameworkId,
executorId,
status.get(),
false,
"Executor terminated");
if (!info->killed) {
// Try and cleanup after the executor.
killExecutor(frameworkId, executorId);
}
if (infos[frameworkId].size() == 1) {
infos.erase(frameworkId);
} else {
infos[frameworkId].erase(executorId);
}
delete info;
return;
}
}
}
}
} // namespace slave {
} // namespace internal {
} // namespace mesos {
<commit_msg>Fixed a crash due to invalid utime / stime values coming from /proc/pid/stat.<commit_after>/**
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#include <errno.h>
#include <signal.h>
#include <stdio.h> // For perror.
#include <string.h>
#include <map>
#include <set>
#include <process/clock.hpp>
#include <process/defer.hpp>
#include <process/dispatch.hpp>
#include <process/id.hpp>
#include <stout/check.hpp>
#include <stout/exit.hpp>
#include <stout/foreach.hpp>
#include <stout/lambda.hpp>
#include <stout/nothing.hpp>
#include <stout/option.hpp>
#include <stout/os.hpp>
#include <stout/uuid.hpp>
#include "common/type_utils.hpp"
#include "slave/flags.hpp"
#include "slave/process_isolator.hpp"
#include "slave/state.hpp"
using namespace process;
using std::map;
using std::set;
using std::string;
using process::defer;
using process::wait; // Necessary on some OS's to disambiguate.
namespace mesos {
namespace internal {
namespace slave {
using launcher::ExecutorLauncher;
using state::SlaveState;
using state::FrameworkState;
using state::ExecutorState;
using state::RunState;
ProcessIsolator::ProcessIsolator()
: ProcessBase(ID::generate("process-isolator")),
initialized(false) {}
void ProcessIsolator::initialize(
const Flags& _flags,
const Resources& _,
bool _local,
const PID<Slave>& _slave)
{
flags = _flags;
local = _local;
slave = _slave;
initialized = true;
}
void ProcessIsolator::launchExecutor(
const SlaveID& slaveId,
const FrameworkID& frameworkId,
const FrameworkInfo& frameworkInfo,
const ExecutorInfo& executorInfo,
const UUID& uuid,
const string& directory,
const Resources& resources)
{
CHECK(initialized) << "Cannot launch executors before initialization!";
const ExecutorID& executorId = executorInfo.executor_id();
LOG(INFO) << "Launching " << executorId
<< " (" << executorInfo.command().value() << ")"
<< " in " << directory
<< " with resources " << resources
<< "' for framework " << frameworkId;
ProcessInfo* info = new ProcessInfo(frameworkId, executorId);
infos[frameworkId][executorId] = info;
// Use pipes to determine which child has successfully changed session.
int pipes[2];
if (pipe(pipes) < 0) {
PLOG(FATAL) << "Failed to create a pipe";
}
// Set the FD_CLOEXEC flags on these pipes
Try<Nothing> cloexec = os::cloexec(pipes[0]);
CHECK_SOME(cloexec) << "Error setting FD_CLOEXEC on pipe[0]";
cloexec = os::cloexec(pipes[1]);
CHECK_SOME(cloexec) << "Error setting FD_CLOEXEC on pipe[1]";
// Create the ExecutorLauncher instance before the fork for the
// child process to use.
ExecutorLauncher launcher(
slaveId,
frameworkId,
executorInfo.executor_id(),
uuid,
executorInfo.command(),
frameworkInfo.user(),
directory,
flags.work_dir,
slave,
flags.frameworks_home,
flags.hadoop_home,
!local,
flags.switch_user,
frameworkInfo.checkpoint());
// We get the environment map for launching mesos-launcher before
// the fork, because we have seen deadlock issues with ostringstream
// in the forked process before it calls exec.
map<string, string> env = launcher.getLauncherEnvironment();
pid_t pid;
if ((pid = fork()) == -1) {
PLOG(FATAL) << "Failed to fork to launch new executor";
}
if (pid > 0) {
os::close(pipes[1]);
// Get the child's pid via the pipe.
if (read(pipes[0], &pid, sizeof(pid)) == -1) {
PLOG(FATAL) << "Failed to get child PID from pipe";
}
os::close(pipes[0]);
// In parent process.
LOG(INFO) << "Forked executor at " << pid;
// Record the pid (should also be the pgid since we setsid below).
infos[frameworkId][executorId]->pid = pid;
reaper.monitor(pid)
.onAny(defer(PID<ProcessIsolator>(this),
&ProcessIsolator::reaped,
pid,
lambda::_1));
// Tell the slave this executor has started.
dispatch(slave, &Slave::executorStarted, frameworkId, executorId, pid);
} else {
// In child process, we make cleanup easier by putting process
// into it's own session. DO NOT USE GLOG!
os::close(pipes[0]);
// NOTE: We setsid() in a loop because setsid() might fail if another
// process has the same process group id as the calling process.
while ((pid = setsid()) == -1) {
perror("Could not put executor in its own session");
std::cout << "Forking another process and retrying ..." << std::endl;
if ((pid = fork()) == -1) {
perror("Failed to fork to launch executor");
abort();
}
if (pid > 0) {
// In parent process.
// It is ok to suicide here, though process reaper signals the exit,
// because the process isolator ignores unknown processes.
exit(0);
}
}
if (write(pipes[1], &pid, sizeof(pid)) != sizeof(pid)) {
perror("Failed to write PID on pipe");
abort();
}
os::close(pipes[1]);
// Setup the environment for launcher.
foreachpair (const string& key, const string& value, env) {
os::setenv(key, value);
}
const char** args = (const char**) new char*[2];
// Determine path for mesos-launcher.
Try<string> realpath = os::realpath(
path::join(flags.launcher_dir, "mesos-launcher"));
if (realpath.isError()) {
EXIT(1) << "Failed to determine the canonical path "
<< "for the mesos-launcher: " << realpath.error();
}
// Grab a copy of the path so that we can reliably use 'c_str()'.
const string& path = realpath.get();
args[0] = path.c_str();
args[1] = NULL;
// Execute the mesos-launcher!
execvp(args[0], (char* const*) args);
// If we get here, the execvp call failed.
perror("Failed to execvp the mesos-launcher");
abort();
}
}
// NOTE: This function can be called by the isolator itself or by the
// slave if it doesn't hear about an executor exit after it sends a
// shutdown message.
void ProcessIsolator::killExecutor(
const FrameworkID& frameworkId,
const ExecutorID& executorId)
{
CHECK(initialized) << "Cannot kill executors before initialization!";
if (!infos.contains(frameworkId) ||
!infos[frameworkId].contains(executorId) ||
infos[frameworkId][executorId]->killed) {
LOG(ERROR) << "Asked to kill an unknown/killed executor! " << executorId;
return;
}
const Option<pid_t>& pid = infos[frameworkId][executorId]->pid;
if (pid.isSome()) {
// TODO(vinod): Call killtree on the pid of the actual executor process
// that is running the tasks (stored in the local storage by the
// executor module).
os::killtree(pid.get(), SIGKILL, true, true, &LOG(INFO));
// Also kill all processes that belong to the process group of the executor.
// This is valuable in situations where the top level executor process
// exited and hence killtree is unable to kill any spawned orphans.
// NOTE: This assumes that the process group id of the executor process is
// same as its pid (which is expected to be the case with setsid()).
// TODO(vinod): Also (recursively) kill processes belonging to the
// same session, but have a different process group id.
if (killpg(pid.get(), SIGKILL) == -1 && errno != ESRCH) {
PLOG(WARNING) << "Failed to kill process group " << pid.get();
}
infos[frameworkId][executorId]->killed = true;
}
}
void ProcessIsolator::resourcesChanged(
const FrameworkID& frameworkId,
const ExecutorID& executorId,
const Resources& resources)
{
CHECK(initialized) << "Cannot do resourcesChanged before initialization!";
if (!infos.contains(frameworkId) ||
!infos[frameworkId].contains(executorId) ||
infos[frameworkId][executorId]->killed) {
LOG(INFO) << "Asked to update resources for an unknown/killed executor '"
<< executorId << "' of framework " << frameworkId;
return;
}
ProcessInfo* info = CHECK_NOTNULL(infos[frameworkId][executorId]);
info->resources = resources;
// Do nothing; subclasses may override this.
}
Future<Nothing> ProcessIsolator::recover(
const Option<SlaveState>& state)
{
LOG(INFO) << "Recovering isolator";
if (state.isNone()) {
return Nothing();
}
foreachvalue (const FrameworkState& framework, state.get().frameworks) {
foreachvalue (const ExecutorState& executor, framework.executors) {
LOG(INFO) << "Recovering executor '" << executor.id
<< "' of framework " << framework.id;
if (executor.info.isNone()) {
LOG(WARNING) << "Skipping recovery of executor '" << executor.id
<< "' of framework " << framework.id
<< " because its info cannot be recovered";
continue;
}
if (executor.latest.isNone()) {
LOG(WARNING) << "Skipping recovery of executor '" << executor.id
<< "' of framework " << framework.id
<< " because its latest run cannot be recovered";
continue;
}
// We are only interested in the latest run of the executor!
const UUID& uuid = executor.latest.get();
CHECK(executor.runs.contains(uuid));
const RunState& run = executor.runs.get(uuid).get();
ProcessInfo* info =
new ProcessInfo(framework.id, executor.id, run.forkedPid);
infos[framework.id][executor.id] = info;
// Add the pid to the reaper to monitor exit status.
if (run.forkedPid.isSome()) {
reaper.monitor(run.forkedPid.get())
.onAny(defer(PID<ProcessIsolator>(this),
&ProcessIsolator::reaped,
run.forkedPid.get(),
lambda::_1));
}
}
}
return Nothing();
}
Future<ResourceStatistics> ProcessIsolator::usage(
const FrameworkID& frameworkId,
const ExecutorID& executorId)
{
if (!infos.contains(frameworkId) ||
!infos[frameworkId].contains(executorId) ||
infos[frameworkId][executorId]->killed) {
return Future<ResourceStatistics>::failed("Unknown/killed executor");
}
ProcessInfo* info = infos[frameworkId][executorId];
CHECK_NOTNULL(info);
ResourceStatistics result;
result.set_timestamp(Clock::now().secs());
// Set the resource allocations.
const Option<Bytes>& mem = info->resources.mem();
if (mem.isSome()) {
result.set_mem_limit_bytes(mem.get().bytes());
}
const Option<double>& cpus = info->resources.cpus();
if (cpus.isSome()) {
result.set_cpus_limit(cpus.get());
}
CHECK_SOME(info->pid);
Result<os::Process> process = os::process(info->pid.get());
if (!process.isSome()) {
return Future<ResourceStatistics>::failed(
process.isError() ? process.error() : "Process does not exist");
}
result.set_timestamp(Clock::now().secs());
if (process.get().rss.isSome()) {
result.set_mem_rss_bytes(process.get().rss.get().bytes());
}
// We only show utime and stime when both are available, otherwise
// we're exposing a partial view of the CPU times.
if (process.get().utime.isSome() && process.get().stime.isSome()) {
result.set_cpus_user_time_secs(process.get().utime.get().secs());
result.set_cpus_system_time_secs(process.get().stime.get().secs());
}
// Now aggregate all descendant process usage statistics.
const Try<set<pid_t> >& children = os::children(info->pid.get(), true);
if (children.isError()) {
return Future<ResourceStatistics>::failed(
"Failed to get children of " + stringify(info->pid.get()) + ": " +
children.error());
}
// Aggregate the usage of all child processes.
foreach (pid_t child, children.get()) {
process = os::process(child);
// Skip processes that disappear.
if (process.isNone()) {
continue;
}
if (process.isError()) {
LOG(WARNING) << "Failed to get status of descendant process " << child
<< " of parent " << info->pid.get() << ": "
<< process.error();
continue;
}
if (process.get().rss.isSome()) {
result.set_mem_rss_bytes(
result.mem_rss_bytes() + process.get().rss.get().bytes());
}
// We only show utime and stime when both are available, otherwise
// we're exposing a partial view of the CPU times.
if (process.get().utime.isSome() && process.get().stime.isSome()) {
result.set_cpus_user_time_secs(
result.cpus_user_time_secs() + process.get().utime.get().secs());
result.set_cpus_system_time_secs(
result.cpus_system_time_secs() + process.get().stime.get().secs());
}
}
return result;
}
void ProcessIsolator::reaped(pid_t pid, const Future<Option<int> >& status)
{
foreachkey (const FrameworkID& frameworkId, infos) {
foreachkey (const ExecutorID& executorId, infos[frameworkId]) {
ProcessInfo* info = infos[frameworkId][executorId];
if (info->pid.isSome() && info->pid.get() == pid) {
if (!status.isReady()) {
LOG(ERROR) << "Failed to get the status for executor '" << executorId
<< "' of framework " << frameworkId << ": "
<< (status.isFailed() ? status.failure() : "discarded");
return;
}
LOG(INFO) << "Telling slave of terminated executor '" << executorId
<< "' of framework " << frameworkId;
dispatch(slave,
&Slave::executorTerminated,
frameworkId,
executorId,
status.get(),
false,
"Executor terminated");
if (!info->killed) {
// Try and cleanup after the executor.
killExecutor(frameworkId, executorId);
}
if (infos[frameworkId].size() == 1) {
infos.erase(frameworkId);
} else {
infos[frameworkId].erase(executorId);
}
delete info;
return;
}
}
}
}
} // namespace slave {
} // namespace internal {
} // namespace mesos {
<|endoftext|> |
<commit_before>//
// Copyright (c) 2012 Kim Walisch, <[email protected]>.
// All rights reserved.
//
// This file is part of primesieve.
// Homepage: http://primesieve.googlecode.com
//
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions
// are met:
//
// * Redistributions of source code must retain the above copyright
// notice, this list of conditions and the following disclaimer.
// * Redistributions in binary form must reproduce the above
// copyright notice, this list of conditions and the following
// disclaimer in the documentation and/or other materials provided
// with the distribution.
// * 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.
/// @brief ParallelPrimeSieve sieves primes in parallel using
/// OpenMP 2.0 (2002) or later.
#include "ParallelPrimeSieve.h"
#include "PrimeSieve.h"
#include "imath.h"
#include "config.h"
#include <stdint.h>
#include <cstdlib>
#include <cassert>
#include <algorithm>
#ifdef _OPENMP
#include <omp.h>
#include "openmp_RAII.h"
#endif
using namespace soe;
ParallelPrimeSieve::ParallelPrimeSieve() :
shm_(NULL),
numThreads_(DEFAULT_NUM_THREADS)
{ }
void ParallelPrimeSieve::init(SharedMemory& shm)
{
setStart(shm.start);
setStop(shm.stop);
setSieveSize(shm.sieveSize);
setFlags(shm.flags);
setNumThreads(shm.threads);
shm_ = &shm;
}
int ParallelPrimeSieve::getNumThreads() const
{
if (numThreads_ == DEFAULT_NUM_THREADS) {
// Use 1 thread to generate primes in arithmetic order
return isGenerate() ? 1 : idealNumThreads();
}
return numThreads_;
}
void ParallelPrimeSieve::setNumThreads(int threads)
{
numThreads_ = getInBetween(1, threads, getMaxThreads());
}
/// Get an ideal number of threads for the current
/// set start_ and stop_ numbers.
///
int ParallelPrimeSieve::idealNumThreads() const
{
uint64_t threshold = std::max(config::MIN_THREAD_INTERVAL, isqrt(stop_) / 5);
uint64_t threads = getInterval() / threshold;
threads = getInBetween<uint64_t>(1, threads, getMaxThreads());
return static_cast<int>(threads);
}
/// Get an interval size that ensures a good load balance
/// when multiple threads are used.
///
uint64_t ParallelPrimeSieve::getThreadInterval(int threads) const
{
assert(threads > 0);
uint64_t unbalanced = getInterval() / threads;
uint64_t balanced = isqrt(stop_) * 1000;
uint64_t fastest = std::min(balanced, unbalanced);
uint64_t threadInterval = getInBetween(config::MIN_THREAD_INTERVAL, fastest, config::MAX_THREAD_INTERVAL);
uint64_t chunks = getInterval() / threadInterval;
if (chunks < threads * 5u)
threadInterval = std::max(config::MIN_THREAD_INTERVAL, unbalanced);
threadInterval += 30 - threadInterval % 30;
return threadInterval;
}
/// Align n to modulo 30 + 2 to prevent prime k-tuplet
/// (twin primes, prime triplets, ...) gaps.
///
uint64_t ParallelPrimeSieve::align(uint64_t n) const
{
if (n != start_)
n = std::min(n + 32 - n % 30, stop_);
return n;
}
bool ParallelPrimeSieve::tooMany(int threads) const
{
return (threads > 1 && getInterval() / threads < config::MIN_THREAD_INTERVAL);
}
#ifdef _OPENMP
int ParallelPrimeSieve::getMaxThreads()
{
return omp_get_max_threads();
}
/// Sieve the primes and prime k-tuplets within [start_, stop_]
/// in parallel using OpenMP multi-threading.
///
void ParallelPrimeSieve::sieve()
{
if (start_ > stop_)
throw primesieve_error("start must be <= stop");
OmpInitLock ompInit(&lock_);
int threads = getNumThreads();
if (tooMany(threads))
threads = idealNumThreads();
if (threads == 1)
PrimeSieve::sieve();
else {
reset();
uint64_t threadInterval = getThreadInterval(threads);
uint64_t count0 = 0, count1 = 0, count2 = 0, count3 = 0, count4 = 0, count5 = 0, count6 = 0;
double time = omp_get_wtime();
#if _OPENMP >= 200800 /* OpenMP >= 3.0 (2008) */
#pragma omp parallel for schedule(dynamic) num_threads(threads) \
reduction(+: count0, count1, count2, count3, count4, count5, count6)
for (uint64_t n = start_; n < stop_; n += threadInterval) {
PrimeSieve ps(*this, omp_get_thread_num());
uint64_t threadStart = align(n);
uint64_t threadStop = align(n + threadInterval);
ps.sieve(threadStart, threadStop);
count0 += ps.getCount(0);
count1 += ps.getCount(1);
count2 += ps.getCount(2);
count3 += ps.getCount(3);
count4 += ps.getCount(4);
count5 += ps.getCount(5);
count6 += ps.getCount(6);
}
#else /* OpenMP 2.x */
int64_t iters = 1 + (getInterval() - 1) / threadInterval;
#pragma omp parallel for schedule(dynamic) num_threads(threads) \
reduction(+: count0, count1, count2, count3, count4, count5, count6)
for (int64_t i = 0; i < iters; i++) {
PrimeSieve ps(*this, omp_get_thread_num());
uint64_t n = start_ + i * threadInterval;
uint64_t threadStart = align(n);
uint64_t threadStop = align(n + threadInterval);
ps.sieve(threadStart, threadStop);
count0 += ps.getCount(0);
count1 += ps.getCount(1);
count2 += ps.getCount(2);
count3 += ps.getCount(3);
count4 += ps.getCount(4);
count5 += ps.getCount(5);
count6 += ps.getCount(6);
}
#endif
seconds_ = omp_get_wtime() - time;
counts_[0] = count0;
counts_[1] = count1;
counts_[2] = count2;
counts_[3] = count3;
counts_[4] = count4;
counts_[5] = count5;
counts_[6] = count6;
}
// communicate the sieving results to the
// primesieve GUI application
if (shm_ != NULL) {
std::copy(counts_.begin(), counts_.end(), shm_->counts);
shm_->seconds = seconds_;
}
}
/// Calculate the sieving status (in percent).
/// @param processed Sum of recently processed segments.
///
bool ParallelPrimeSieve::updateStatus(uint64_t processed, bool waitForLock)
{
OmpLockGuard lock(getLock<omp_lock_t*>(), waitForLock);
if (lock.isSet()) {
PrimeSieve::updateStatus(processed, false);
if (shm_ != NULL)
shm_->status = getStatus();
}
return lock.isSet();
}
/// Used to synchronize threads for prime number generation
void ParallelPrimeSieve::setLock()
{
omp_lock_t* lock = getLock<omp_lock_t*>();
omp_set_lock(lock);
}
void ParallelPrimeSieve::unsetLock()
{
omp_lock_t* lock = getLock<omp_lock_t*>();
omp_unset_lock(lock);
}
#endif /* _OPENMP */
/// If OpenMP is disabled then ParallelPrimeSieve behaves like
/// the single threaded PrimeSieve.
///
#if !defined(_OPENMP)
int ParallelPrimeSieve::getMaxThreads()
{
return 1;
}
void ParallelPrimeSieve::sieve()
{
PrimeSieve::sieve();
}
bool ParallelPrimeSieve::updateStatus(uint64_t processed, bool waitForLock)
{
return PrimeSieve::updateStatus(processed, waitForLock);
}
void ParallelPrimeSieve::setLock() { }
void ParallelPrimeSieve::unsetLock() { }
#endif
<commit_msg>silenced a warning<commit_after>//
// Copyright (c) 2012 Kim Walisch, <[email protected]>.
// All rights reserved.
//
// This file is part of primesieve.
// Homepage: http://primesieve.googlecode.com
//
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions
// are met:
//
// * Redistributions of source code must retain the above copyright
// notice, this list of conditions and the following disclaimer.
// * Redistributions in binary form must reproduce the above
// copyright notice, this list of conditions and the following
// disclaimer in the documentation and/or other materials provided
// with the distribution.
// * 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.
/// @brief ParallelPrimeSieve sieves primes in parallel using
/// OpenMP 2.0 (2002) or later.
#include "ParallelPrimeSieve.h"
#include "PrimeSieve.h"
#include "imath.h"
#include "config.h"
#include <stdint.h>
#include <cstdlib>
#include <cassert>
#include <algorithm>
#ifdef _OPENMP
#include <omp.h>
#include "openmp_RAII.h"
#endif
using namespace soe;
ParallelPrimeSieve::ParallelPrimeSieve() :
numThreads_(DEFAULT_NUM_THREADS),
shm_(NULL)
{ }
void ParallelPrimeSieve::init(SharedMemory& shm)
{
setStart(shm.start);
setStop(shm.stop);
setSieveSize(shm.sieveSize);
setFlags(shm.flags);
setNumThreads(shm.threads);
shm_ = &shm;
}
int ParallelPrimeSieve::getNumThreads() const
{
if (numThreads_ == DEFAULT_NUM_THREADS) {
// Use 1 thread to generate primes in arithmetic order
return isGenerate() ? 1 : idealNumThreads();
}
return numThreads_;
}
void ParallelPrimeSieve::setNumThreads(int threads)
{
numThreads_ = getInBetween(1, threads, getMaxThreads());
}
/// Get an ideal number of threads for the current
/// set start_ and stop_ numbers.
///
int ParallelPrimeSieve::idealNumThreads() const
{
uint64_t threshold = std::max(config::MIN_THREAD_INTERVAL, isqrt(stop_) / 5);
uint64_t threads = getInterval() / threshold;
threads = getInBetween<uint64_t>(1, threads, getMaxThreads());
return static_cast<int>(threads);
}
/// Get an interval size that ensures a good load balance
/// when multiple threads are used.
///
uint64_t ParallelPrimeSieve::getThreadInterval(int threads) const
{
assert(threads > 0);
uint64_t unbalanced = getInterval() / threads;
uint64_t balanced = isqrt(stop_) * 1000;
uint64_t fastest = std::min(balanced, unbalanced);
uint64_t threadInterval = getInBetween(config::MIN_THREAD_INTERVAL, fastest, config::MAX_THREAD_INTERVAL);
uint64_t chunks = getInterval() / threadInterval;
if (chunks < threads * 5u)
threadInterval = std::max(config::MIN_THREAD_INTERVAL, unbalanced);
threadInterval += 30 - threadInterval % 30;
return threadInterval;
}
/// Align n to modulo 30 + 2 to prevent prime k-tuplet
/// (twin primes, prime triplets, ...) gaps.
///
uint64_t ParallelPrimeSieve::align(uint64_t n) const
{
if (n != start_)
n = std::min(n + 32 - n % 30, stop_);
return n;
}
bool ParallelPrimeSieve::tooMany(int threads) const
{
return (threads > 1 && getInterval() / threads < config::MIN_THREAD_INTERVAL);
}
#ifdef _OPENMP
int ParallelPrimeSieve::getMaxThreads()
{
return omp_get_max_threads();
}
/// Sieve the primes and prime k-tuplets within [start_, stop_]
/// in parallel using OpenMP multi-threading.
///
void ParallelPrimeSieve::sieve()
{
if (start_ > stop_)
throw primesieve_error("start must be <= stop");
OmpInitLock ompInit(&lock_);
int threads = getNumThreads();
if (tooMany(threads))
threads = idealNumThreads();
if (threads == 1)
PrimeSieve::sieve();
else {
reset();
uint64_t threadInterval = getThreadInterval(threads);
uint64_t count0 = 0, count1 = 0, count2 = 0, count3 = 0, count4 = 0, count5 = 0, count6 = 0;
double time = omp_get_wtime();
#if _OPENMP >= 200800 /* OpenMP >= 3.0 (2008) */
#pragma omp parallel for schedule(dynamic) num_threads(threads) \
reduction(+: count0, count1, count2, count3, count4, count5, count6)
for (uint64_t n = start_; n < stop_; n += threadInterval) {
PrimeSieve ps(*this, omp_get_thread_num());
uint64_t threadStart = align(n);
uint64_t threadStop = align(n + threadInterval);
ps.sieve(threadStart, threadStop);
count0 += ps.getCount(0);
count1 += ps.getCount(1);
count2 += ps.getCount(2);
count3 += ps.getCount(3);
count4 += ps.getCount(4);
count5 += ps.getCount(5);
count6 += ps.getCount(6);
}
#else /* OpenMP 2.x */
int64_t iters = 1 + (getInterval() - 1) / threadInterval;
#pragma omp parallel for schedule(dynamic) num_threads(threads) \
reduction(+: count0, count1, count2, count3, count4, count5, count6)
for (int64_t i = 0; i < iters; i++) {
PrimeSieve ps(*this, omp_get_thread_num());
uint64_t n = start_ + i * threadInterval;
uint64_t threadStart = align(n);
uint64_t threadStop = align(n + threadInterval);
ps.sieve(threadStart, threadStop);
count0 += ps.getCount(0);
count1 += ps.getCount(1);
count2 += ps.getCount(2);
count3 += ps.getCount(3);
count4 += ps.getCount(4);
count5 += ps.getCount(5);
count6 += ps.getCount(6);
}
#endif
seconds_ = omp_get_wtime() - time;
counts_[0] = count0;
counts_[1] = count1;
counts_[2] = count2;
counts_[3] = count3;
counts_[4] = count4;
counts_[5] = count5;
counts_[6] = count6;
}
// communicate the sieving results to the
// primesieve GUI application
if (shm_ != NULL) {
std::copy(counts_.begin(), counts_.end(), shm_->counts);
shm_->seconds = seconds_;
}
}
/// Calculate the sieving status (in percent).
/// @param processed Sum of recently processed segments.
///
bool ParallelPrimeSieve::updateStatus(uint64_t processed, bool waitForLock)
{
OmpLockGuard lock(getLock<omp_lock_t*>(), waitForLock);
if (lock.isSet()) {
PrimeSieve::updateStatus(processed, false);
if (shm_ != NULL)
shm_->status = getStatus();
}
return lock.isSet();
}
/// Used to synchronize threads for prime number generation
void ParallelPrimeSieve::setLock()
{
omp_lock_t* lock = getLock<omp_lock_t*>();
omp_set_lock(lock);
}
void ParallelPrimeSieve::unsetLock()
{
omp_lock_t* lock = getLock<omp_lock_t*>();
omp_unset_lock(lock);
}
#endif /* _OPENMP */
/// If OpenMP is disabled then ParallelPrimeSieve behaves like
/// the single threaded PrimeSieve.
///
#if !defined(_OPENMP)
int ParallelPrimeSieve::getMaxThreads()
{
return 1;
}
void ParallelPrimeSieve::sieve()
{
PrimeSieve::sieve();
}
bool ParallelPrimeSieve::updateStatus(uint64_t processed, bool waitForLock)
{
return PrimeSieve::updateStatus(processed, waitForLock);
}
void ParallelPrimeSieve::setLock() { }
void ParallelPrimeSieve::unsetLock() { }
#endif
<|endoftext|> |
<commit_before>#include <string>
#include <curl/curl.h>
#include <boost/filesystem.hpp>
#include <boost/program_options.hpp>
#include "json/json.h"
#include "accumulator.h"
#include "authenticate.h"
#include "check.h"
#include "garage_common.h"
#include "garage_tools_version.h"
#include "logging/logging.h"
#include "ostree_http_repo.h"
#include "ostree_object.h"
#include "request_pool.h"
#include "treehub_server.h"
#include "utilities/types.h"
#include "utilities/utils.h"
namespace po = boost::program_options;
int main(int argc, char **argv) {
logger_init();
int verbosity;
std::string ref;
boost::filesystem::path credentials_path;
std::string cacerts;
int max_curl_requests;
RunMode mode = RunMode::kDefault;
po::options_description desc("garage-check command line options");
// clang-format off
desc.add_options()
("help", "print usage")
("version", "Current garage-check version")
("verbose,v", accumulator<int>(&verbosity), "Verbose logging (use twice for more information)")
("quiet,q", "Quiet mode")
("ref,r", po::value<std::string>(&ref)->required(), "refhash to check")
("credentials,j", po::value<boost::filesystem::path>(&credentials_path)->required(), "credentials (json or zip containing json)")
("cacert", po::value<std::string>(&cacerts), "override path to CA root certificates, in the same format as curl --cacert")
("jobs", po::value<int>(&max_curl_requests)->default_value(30), "maximum number of parallel requests (only relevant with --walk-tree)")
("walk-tree,w", "walk entire tree and check presence of all objects");
// clang-format on
po::variables_map vm;
try {
po::store(po::parse_command_line(argc, reinterpret_cast<const char *const *>(argv), desc), vm);
if (vm.count("help") != 0u) {
LOG_INFO << desc;
return EXIT_SUCCESS;
}
if (vm.count("version") != 0) {
LOG_INFO << "Current garage-check version is: " << garage_tools_version();
exit(EXIT_SUCCESS);
}
po::notify(vm);
} catch (const po::error &o) {
LOG_ERROR << o.what();
LOG_ERROR << desc;
return EXIT_FAILURE;
}
try {
// Configure logging
if (verbosity == 0) {
// 'verbose' trumps 'quiet'
if (static_cast<int>(vm.count("quiet")) != 0) {
logger_set_threshold(boost::log::trivial::warning);
} else {
logger_set_threshold(boost::log::trivial::info);
}
} else if (verbosity == 1) {
logger_set_threshold(boost::log::trivial::debug);
LOG_DEBUG << "Debug level debugging enabled";
} else if (verbosity > 1) {
logger_set_threshold(boost::log::trivial::trace);
LOG_TRACE << "Trace level debugging enabled";
} else {
assert(0);
}
Utils::setUserAgent(std::string("garage-check/") + garage_tools_version());
if (vm.count("walk-tree") != 0u) {
mode = RunMode::kWalkTree;
}
TreehubServer treehub;
if (cacerts != "") {
if (boost::filesystem::exists(cacerts)) {
treehub.ca_certs(cacerts);
} else {
LOG_FATAL << "--cacert path " << cacerts << " does not exist";
return EXIT_FAILURE;
}
}
if (max_curl_requests < 1) {
LOG_FATAL << "--jobs must be greater than 0";
return EXIT_FAILURE;
}
if (authenticate(cacerts, ServerCredentials(credentials_path), treehub) != EXIT_SUCCESS) {
LOG_FATAL << "Authentication failed";
return EXIT_FAILURE;
}
if (CheckRefValid(treehub, ref, mode, max_curl_requests) != EXIT_SUCCESS) {
LOG_FATAL << "Check if the ref is present on the server or in targets.json failed";
return EXIT_FAILURE;
}
} catch (std::exception &ex) {
LOG_ERROR << "Exception: " << ex.what();
return EXIT_FAILURE;
} catch (...) {
LOG_ERROR << "Unknown exception";
return EXIT_FAILURE;
}
}
<commit_msg>Remove redundant call to set CA cert.<commit_after>#include <string>
#include <curl/curl.h>
#include <boost/filesystem.hpp>
#include <boost/program_options.hpp>
#include "json/json.h"
#include "accumulator.h"
#include "authenticate.h"
#include "check.h"
#include "garage_common.h"
#include "garage_tools_version.h"
#include "logging/logging.h"
#include "ostree_http_repo.h"
#include "ostree_object.h"
#include "request_pool.h"
#include "treehub_server.h"
#include "utilities/types.h"
#include "utilities/utils.h"
namespace po = boost::program_options;
int main(int argc, char **argv) {
logger_init();
int verbosity;
std::string ref;
boost::filesystem::path credentials_path;
std::string cacerts;
int max_curl_requests;
RunMode mode = RunMode::kDefault;
po::options_description desc("garage-check command line options");
// clang-format off
desc.add_options()
("help", "print usage")
("version", "Current garage-check version")
("verbose,v", accumulator<int>(&verbosity), "Verbose logging (use twice for more information)")
("quiet,q", "Quiet mode")
("ref,r", po::value<std::string>(&ref)->required(), "refhash to check")
("credentials,j", po::value<boost::filesystem::path>(&credentials_path)->required(), "credentials (json or zip containing json)")
("cacert", po::value<std::string>(&cacerts), "override path to CA root certificates, in the same format as curl --cacert")
("jobs", po::value<int>(&max_curl_requests)->default_value(30), "maximum number of parallel requests (only relevant with --walk-tree)")
("walk-tree,w", "walk entire tree and check presence of all objects");
// clang-format on
po::variables_map vm;
try {
po::store(po::parse_command_line(argc, reinterpret_cast<const char *const *>(argv), desc), vm);
if (vm.count("help") != 0u) {
LOG_INFO << desc;
return EXIT_SUCCESS;
}
if (vm.count("version") != 0) {
LOG_INFO << "Current garage-check version is: " << garage_tools_version();
exit(EXIT_SUCCESS);
}
po::notify(vm);
} catch (const po::error &o) {
LOG_ERROR << o.what();
LOG_ERROR << desc;
return EXIT_FAILURE;
}
try {
// Configure logging
if (verbosity == 0) {
// 'verbose' trumps 'quiet'
if (static_cast<int>(vm.count("quiet")) != 0) {
logger_set_threshold(boost::log::trivial::warning);
} else {
logger_set_threshold(boost::log::trivial::info);
}
} else if (verbosity == 1) {
logger_set_threshold(boost::log::trivial::debug);
LOG_DEBUG << "Debug level debugging enabled";
} else if (verbosity > 1) {
logger_set_threshold(boost::log::trivial::trace);
LOG_TRACE << "Trace level debugging enabled";
} else {
assert(0);
}
Utils::setUserAgent(std::string("garage-check/") + garage_tools_version());
if (vm.count("walk-tree") != 0u) {
mode = RunMode::kWalkTree;
}
if (max_curl_requests < 1) {
LOG_FATAL << "--jobs must be greater than 0";
return EXIT_FAILURE;
}
TreehubServer treehub;
if (authenticate(cacerts, ServerCredentials(credentials_path), treehub) != EXIT_SUCCESS) {
LOG_FATAL << "Authentication failed";
return EXIT_FAILURE;
}
if (CheckRefValid(treehub, ref, mode, max_curl_requests) != EXIT_SUCCESS) {
LOG_FATAL << "Check if the ref is present on the server or in targets.json failed";
return EXIT_FAILURE;
}
} catch (std::exception &ex) {
LOG_ERROR << "Exception: " << ex.what();
return EXIT_FAILURE;
} catch (...) {
LOG_ERROR << "Unknown exception";
return EXIT_FAILURE;
}
}
<|endoftext|> |
<commit_before>// SA:MP Profiler plugin
//
// Copyright (c) 2011 Zeex
//
// 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 <algorithm>
#include <cstdio>
#include <cstdlib>
#include <fstream>
#include <iomanip>
#include <iostream>
#include <list>
#include <numeric>
#include <string>
#include <vector>
#include "amxnamefinder.h"
#include "jump.h"
#include "plugincommon.h"
#include "profiler.h"
std::map<AMX*, AmxProfiler*> AmxProfiler::instances_;
AmxProfiler::AmxProfiler() {}
static void GetNatives(AMX *amx, std::vector<std::string> &names) {
AMX_HEADER *hdr = reinterpret_cast<AMX_HEADER*>(amx->base);
AMX_FUNCSTUBNT *natives = reinterpret_cast<AMX_FUNCSTUBNT*>(amx->base + hdr->natives);
int numNatives = (hdr->libraries - hdr->natives) / hdr->defsize;
for (int i = 0; i < numNatives; i++) {
names.push_back(reinterpret_cast<char*>(amx->base + natives[i].nameofs));
}
}
AmxProfiler::AmxProfiler(AMX *amx, AMX_DBG amxdbg)
: amx_(amx),
amxdbg_(amxdbg),
debug_(amx->debug),
callback_(amx->callback),
active_(false),
frame_(amx->stp)
{
// Since PrintStats is done in AmxUnload nad amx->base is already freed before
// AmxUnload gets called, the native table is not accessible there thus natives'
// names must be stored in some global place.
GetNatives(amx, nativeNames_);
}
void AmxProfiler::Attach(AMX *amx, AMX_DBG amxdbg) {
AmxProfiler *prof = new AmxProfiler(amx, amxdbg);
instances_[amx] = prof;
prof->Activate();
}
void AmxProfiler::Detach(AMX *amx) {
AmxProfiler *prof = AmxProfiler::Get(amx);
if (prof != 0) {
prof->Deactivate();
delete prof;
}
instances_.erase(amx);
}
AmxProfiler *AmxProfiler::Get(AMX *amx) {
std::map<AMX*, AmxProfiler*>::iterator it = instances_.find(amx);
if (it != instances_.end()) {
return it->second;
}
return 0;
}
static int AMXAPI Debug(AMX *amx) {
return AmxProfiler::Get(amx)->Debug();
}
static int AMXAPI Callback(AMX *amx, cell index, cell *result, cell *params) {
return AmxProfiler::Get(amx)->Callback(index, result, params);
}
void AmxProfiler::Activate() {
if (!active_) {
active_ = true;
amx_SetDebugHook(amx_, ::Debug);
amx_SetCallback(amx_, ::Callback);
}
}
bool AmxProfiler::IsActive() const {
return active_;
}
void AmxProfiler::Deactivate() {
if (active_) {
active_ = false;
amx_SetDebugHook(amx_, debug_);
amx_SetCallback(amx_, callback_);
}
}
void AmxProfiler::ResetStats() {
counters_.clear();
}
static bool ByCalls(const std::pair<cell, AmxPerformanceCounter> &op1,
const std::pair<cell, AmxPerformanceCounter> &op2) {
return op1.second.GetCalls() > op2.second.GetCalls();
}
static bool ByTime(const std::pair<cell, AmxPerformanceCounter> &op1,
const std::pair<cell, AmxPerformanceCounter> &op2) {
return op1.second.GetTime() > op2.second.GetTime();
}
static bool ByTimePerCall(const std::pair<cell, AmxPerformanceCounter> &op1,
const std::pair<cell, AmxPerformanceCounter> &op2) {
return static_cast<double>(op1.second.GetTime()) / static_cast<double>(op1.second.GetCalls())
> static_cast<double>(op2.second.GetTime()) / static_cast<double>(op2.second.GetCalls());
}
bool AmxProfiler::PrintStats(const std::string &filename, StatsPrintOrder order) {
std::ofstream stream(filename.c_str());
if (stream.is_open()) {
std::vector<std::pair<cell, AmxPerformanceCounter> > stats(counters_.begin(),
counters_.end());
switch (order) {
case ORDER_BY_CALLS:
std::sort(stats.begin(), stats.end(), ByCalls);
break;
case ORDER_BY_TIME:
std::sort(stats.begin(), stats.end(), ByTime);
break;
case ORDER_BY_TIME_PER_CALL:
std::sort(stats.begin(), stats.end(), ByTimePerCall);
break;
default:
// leave as is
break;
}
stream << "<table>\n"
<< "\t<tr>\n"
<< "\t\t<td>Function</td>\n"
<< "\t\t<td>Calls</td>\n"
<< "\t\t<td>Time per call, µs</td>\n"
<< "\t\t<td>Overall time, µs</td>\n"
<< "\t\t<td>Overall time, %</td>\n"
<< "\t</tr>\n";
platformstl::int64_t totalTime = 0;
for (std::vector<std::pair<cell, AmxPerformanceCounter> >::iterator it = stats.begin();
it != stats.end(); ++it)
{
totalTime += it->second.GetTime();
}
for (std::vector<std::pair<cell, AmxPerformanceCounter> >::iterator it = stats.begin();
it != stats.end(); ++it)
{
stream << "\t<tr>\n";
if (it->first <= 0) {
stream << "\t\t<td>" << nativeNames_[-it->first] << "</td>\n";
} else {
const char *name;
if (dbg_LookupFunction(&amxdbg_, it->first, &name) == AMX_ERR_NONE) {
//stream << "\t\t<td>" << name << "@" << std::hex << it->first << std::dec << "</td>\n";
stream << "\t\t<td>" << name << "</td>\n";
} else {
stream << "\t\t<td>" << std::hex << it->first << std::dec << "</td>\n";
}
}
stream << "\t\t<td>" << it->second.GetCalls() << "</td>\n"
<< "\t\t<td>" << std::fixed << std::setprecision(0)
<< static_cast<double>(it->second.GetTime()) /
static_cast<double>(it->second.GetCalls()) << "</td>\n"
<< "\t\t<td>" << it->second.GetTime() << "</td>\n"
<< "\t\t<td>" << std::setprecision(2)
<< static_cast<double>(it->second.GetTime() * 100) /
static_cast<double>(totalTime) << "</td>\n";
stream << "\t</tr>\n";
}
stream << "</table>\n";
return true;
}
return false;
}
int AmxProfiler::Debug() {
if (amx_->frm != frame_) {
if (amx_->frm < frame_) {
// Probably entered a function body (first BREAK after PROC)
cell address = amx_->cip - 2*sizeof(cell);
// Check if we have a PROC opcode behind us
AMX_HEADER *hdr = reinterpret_cast<AMX_HEADER*>(amx_->base);
cell op = *reinterpret_cast<cell*>(hdr->cod + amx_->base + address);
if (op == 46) {
callStack_.push(address);
if (active_) {
counters_[address].Start();
}
}
} else {
// Left a function
cell address = callStack_.top();
if (active_) {
counters_[address].Stop();
}
callStack_.pop();
if (callStack_.empty()) {
frame_ = amx_->stp;
}
}
frame_ = amx_->frm;
}
if (debug_ != 0) {
// Others could set their own debug hooks
return debug_(amx_);
}
return AMX_ERR_NONE;
}
int AmxProfiler::Callback(cell index, cell *result, cell *params) {
// The default AMX callback (amx_Callback) can replace SYSREQ.C opcodes
// with SYSREQ.D for better performance.
amx_->sysreq_d = 0;
if (active_) {
counters_[-index].Start();; // Notice negative index
}
// Call any previously set AMX callback (must not be null so we don't check)
int error = callback_(amx_, index, result, params);
if (active_) {
counters_[-index].Stop();
}
return error;
}
static uint32_t amx_Exec_addr;
static unsigned char amx_Exec_code[5];
static int AMXAPI Exec(AMX *amx, cell *retval, int index) {
memcpy(reinterpret_cast<void*>(::amx_Exec_addr), ::amx_Exec_code, 5);
int error;
// Check if this script has a profiler attached to it
AmxProfiler *prof = AmxProfiler::Get(amx);
if (prof != 0 && prof->IsActive()) {
error = prof->Exec(retval, index);
} else {
error = amx_Exec(amx, retval, index);
}
SetJump(reinterpret_cast<void*>(::amx_Exec_addr), (void*)::Exec, ::amx_Exec_code);
return error;
}
int AmxProfiler::Exec(cell *retval, int index) {
AMX_HEADER *hdr = reinterpret_cast<AMX_HEADER*>(amx_->base);
AMX_FUNCSTUBNT *publics = reinterpret_cast<AMX_FUNCSTUBNT*>(amx_->base + hdr->publics);
cell address = publics[index].address;
callStack_.push(address);
counters_[address].Start();
int error = amx_Exec(amx_, retval, index);
counters_[address].Stop();
if (!callStack_.empty()) {
callStack_.pop();
}
if (callStack_.empty()) {
frame_ = amx_->stp;
}
return error;
}
PLUGIN_EXPORT unsigned int PLUGIN_CALL Supports() {
return SUPPORTS_VERSION | SUPPORTS_AMX_NATIVES;
}
extern void *pAMXFunctions;
// Both x86 and x86-64 are Little Endian
static void *AMXAPI DummyAmxAlign(void *v) { return v; }
static std::list<std::string> profiledScripts;
PLUGIN_EXPORT bool PLUGIN_CALL Load(void **pluginData) {
pAMXFunctions = pluginData[PLUGIN_DATA_AMX_EXPORTS];
// The server does not export amx_Align16 and amx_Align32 for some reason
((void**)pAMXFunctions)[PLUGIN_AMX_EXPORT_Align16] = (void*)DummyAmxAlign;
((void**)pAMXFunctions)[PLUGIN_AMX_EXPORT_Align32] = (void*)DummyAmxAlign;
::amx_Exec_addr = reinterpret_cast<uint32_t>((static_cast<void**>(pAMXFunctions))[PLUGIN_AMX_EXPORT_Exec]);
SetJump(reinterpret_cast<void*>(::amx_Exec_addr), (void*)::Exec, ::amx_Exec_code);
// Get list of scripts to be profiled
std::copy(std::istream_iterator<std::string>(std::ifstream("plugins/profiler.cfg")),
std::istream_iterator<std::string>(),
std::back_inserter(::profiledScripts));
//std::copy(::profiledScripts.begin(), ::profiledScripts.end(), std::ostream_iterator<std::string>(std::cout));
// Initialize the name finder
AmxNameFinder::GetInstance()->AddSearchDir("gamemodes");
AmxNameFinder::GetInstance()->AddSearchDir("filterscripts");
return true;
}
PLUGIN_EXPORT void PLUGIN_CALL Unload() {
return;
}
PLUGIN_EXPORT int PLUGIN_CALL AmxLoad(AMX *amx) {
AmxNameFinder::GetInstance()->UpdateCache();
std::string filename = AmxNameFinder::GetInstance()->GetAmxName(amx);
// Looking up the base name only, i.e. file name + '.' + extenstion
if (std::find(::profiledScripts.begin(),
::profiledScripts.end(), filename) != ::profiledScripts.end())
{
FILE *fp = fopen(filename.c_str(), "rb");
if (fp != 0) {
AMX_DBG amxdbg;
int error = dbg_LoadInfo(&amxdbg, fp);
if (error == AMX_ERR_NONE) {
AmxProfiler::Attach(amx, amxdbg);
} else {
return error;
}
fclose(fp);
}
}
return AMX_ERR_NONE;
}
PLUGIN_EXPORT int PLUGIN_CALL AmxUnload(AMX *amx) {
AmxProfiler *prof = AmxProfiler::Get(amx);
std::string name = AmxNameFinder::GetInstance()->GetAmxName(amx);
if (prof != 0 && !name.empty()) {
prof->PrintStats(name + std::string(".prof"));
AmxProfiler::Detach(amx);
}
return AMX_ERR_NONE;
}
<commit_msg>Fix a typo in comment<commit_after>// SA:MP Profiler plugin
//
// Copyright (c) 2011 Zeex
//
// 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 <algorithm>
#include <cstdio>
#include <cstdlib>
#include <fstream>
#include <iomanip>
#include <iostream>
#include <list>
#include <numeric>
#include <string>
#include <vector>
#include "amxnamefinder.h"
#include "jump.h"
#include "plugincommon.h"
#include "profiler.h"
std::map<AMX*, AmxProfiler*> AmxProfiler::instances_;
AmxProfiler::AmxProfiler() {}
static void GetNatives(AMX *amx, std::vector<std::string> &names) {
AMX_HEADER *hdr = reinterpret_cast<AMX_HEADER*>(amx->base);
AMX_FUNCSTUBNT *natives = reinterpret_cast<AMX_FUNCSTUBNT*>(amx->base + hdr->natives);
int numNatives = (hdr->libraries - hdr->natives) / hdr->defsize;
for (int i = 0; i < numNatives; i++) {
names.push_back(reinterpret_cast<char*>(amx->base + natives[i].nameofs));
}
}
AmxProfiler::AmxProfiler(AMX *amx, AMX_DBG amxdbg)
: amx_(amx),
amxdbg_(amxdbg),
debug_(amx->debug),
callback_(amx->callback),
active_(false),
frame_(amx->stp)
{
// Since PrintStats is done in AmxUnload and amx->base is already freed before
// AmxUnload gets called, the native table is not accessible there thus natives'
// names must be stored in some global place.
GetNatives(amx, nativeNames_);
}
void AmxProfiler::Attach(AMX *amx, AMX_DBG amxdbg) {
AmxProfiler *prof = new AmxProfiler(amx, amxdbg);
instances_[amx] = prof;
prof->Activate();
}
void AmxProfiler::Detach(AMX *amx) {
AmxProfiler *prof = AmxProfiler::Get(amx);
if (prof != 0) {
prof->Deactivate();
delete prof;
}
instances_.erase(amx);
}
AmxProfiler *AmxProfiler::Get(AMX *amx) {
std::map<AMX*, AmxProfiler*>::iterator it = instances_.find(amx);
if (it != instances_.end()) {
return it->second;
}
return 0;
}
static int AMXAPI Debug(AMX *amx) {
return AmxProfiler::Get(amx)->Debug();
}
static int AMXAPI Callback(AMX *amx, cell index, cell *result, cell *params) {
return AmxProfiler::Get(amx)->Callback(index, result, params);
}
void AmxProfiler::Activate() {
if (!active_) {
active_ = true;
amx_SetDebugHook(amx_, ::Debug);
amx_SetCallback(amx_, ::Callback);
}
}
bool AmxProfiler::IsActive() const {
return active_;
}
void AmxProfiler::Deactivate() {
if (active_) {
active_ = false;
amx_SetDebugHook(amx_, debug_);
amx_SetCallback(amx_, callback_);
}
}
void AmxProfiler::ResetStats() {
counters_.clear();
}
static bool ByCalls(const std::pair<cell, AmxPerformanceCounter> &op1,
const std::pair<cell, AmxPerformanceCounter> &op2) {
return op1.second.GetCalls() > op2.second.GetCalls();
}
static bool ByTime(const std::pair<cell, AmxPerformanceCounter> &op1,
const std::pair<cell, AmxPerformanceCounter> &op2) {
return op1.second.GetTime() > op2.second.GetTime();
}
static bool ByTimePerCall(const std::pair<cell, AmxPerformanceCounter> &op1,
const std::pair<cell, AmxPerformanceCounter> &op2) {
return static_cast<double>(op1.second.GetTime()) / static_cast<double>(op1.second.GetCalls())
> static_cast<double>(op2.second.GetTime()) / static_cast<double>(op2.second.GetCalls());
}
bool AmxProfiler::PrintStats(const std::string &filename, StatsPrintOrder order) {
std::ofstream stream(filename.c_str());
if (stream.is_open()) {
std::vector<std::pair<cell, AmxPerformanceCounter> > stats(counters_.begin(),
counters_.end());
switch (order) {
case ORDER_BY_CALLS:
std::sort(stats.begin(), stats.end(), ByCalls);
break;
case ORDER_BY_TIME:
std::sort(stats.begin(), stats.end(), ByTime);
break;
case ORDER_BY_TIME_PER_CALL:
std::sort(stats.begin(), stats.end(), ByTimePerCall);
break;
default:
// leave as is
break;
}
stream << "<table>\n"
<< "\t<tr>\n"
<< "\t\t<td>Function</td>\n"
<< "\t\t<td>Calls</td>\n"
<< "\t\t<td>Time per call, µs</td>\n"
<< "\t\t<td>Overall time, µs</td>\n"
<< "\t\t<td>Overall time, %</td>\n"
<< "\t</tr>\n";
platformstl::int64_t totalTime = 0;
for (std::vector<std::pair<cell, AmxPerformanceCounter> >::iterator it = stats.begin();
it != stats.end(); ++it)
{
totalTime += it->second.GetTime();
}
for (std::vector<std::pair<cell, AmxPerformanceCounter> >::iterator it = stats.begin();
it != stats.end(); ++it)
{
stream << "\t<tr>\n";
if (it->first <= 0) {
stream << "\t\t<td>" << nativeNames_[-it->first] << "</td>\n";
} else {
const char *name;
if (dbg_LookupFunction(&amxdbg_, it->first, &name) == AMX_ERR_NONE) {
//stream << "\t\t<td>" << name << "@" << std::hex << it->first << std::dec << "</td>\n";
stream << "\t\t<td>" << name << "</td>\n";
} else {
stream << "\t\t<td>" << std::hex << it->first << std::dec << "</td>\n";
}
}
stream << "\t\t<td>" << it->second.GetCalls() << "</td>\n"
<< "\t\t<td>" << std::fixed << std::setprecision(0)
<< static_cast<double>(it->second.GetTime()) /
static_cast<double>(it->second.GetCalls()) << "</td>\n"
<< "\t\t<td>" << it->second.GetTime() << "</td>\n"
<< "\t\t<td>" << std::setprecision(2)
<< static_cast<double>(it->second.GetTime() * 100) /
static_cast<double>(totalTime) << "</td>\n";
stream << "\t</tr>\n";
}
stream << "</table>\n";
return true;
}
return false;
}
int AmxProfiler::Debug() {
if (amx_->frm != frame_) {
if (amx_->frm < frame_) {
// Probably entered a function body (first BREAK after PROC)
cell address = amx_->cip - 2*sizeof(cell);
// Check if we have a PROC opcode behind us
AMX_HEADER *hdr = reinterpret_cast<AMX_HEADER*>(amx_->base);
cell op = *reinterpret_cast<cell*>(hdr->cod + amx_->base + address);
if (op == 46) {
callStack_.push(address);
if (active_) {
counters_[address].Start();
}
}
} else {
// Left a function
cell address = callStack_.top();
if (active_) {
counters_[address].Stop();
}
callStack_.pop();
if (callStack_.empty()) {
frame_ = amx_->stp;
}
}
frame_ = amx_->frm;
}
if (debug_ != 0) {
// Others could set their own debug hooks
return debug_(amx_);
}
return AMX_ERR_NONE;
}
int AmxProfiler::Callback(cell index, cell *result, cell *params) {
// The default AMX callback (amx_Callback) can replace SYSREQ.C opcodes
// with SYSREQ.D for better performance.
amx_->sysreq_d = 0;
if (active_) {
counters_[-index].Start();; // Notice negative index
}
// Call any previously set AMX callback (must not be null so we don't check)
int error = callback_(amx_, index, result, params);
if (active_) {
counters_[-index].Stop();
}
return error;
}
static uint32_t amx_Exec_addr;
static unsigned char amx_Exec_code[5];
static int AMXAPI Exec(AMX *amx, cell *retval, int index) {
memcpy(reinterpret_cast<void*>(::amx_Exec_addr), ::amx_Exec_code, 5);
int error;
// Check if this script has a profiler attached to it
AmxProfiler *prof = AmxProfiler::Get(amx);
if (prof != 0 && prof->IsActive()) {
error = prof->Exec(retval, index);
} else {
error = amx_Exec(amx, retval, index);
}
SetJump(reinterpret_cast<void*>(::amx_Exec_addr), (void*)::Exec, ::amx_Exec_code);
return error;
}
int AmxProfiler::Exec(cell *retval, int index) {
AMX_HEADER *hdr = reinterpret_cast<AMX_HEADER*>(amx_->base);
AMX_FUNCSTUBNT *publics = reinterpret_cast<AMX_FUNCSTUBNT*>(amx_->base + hdr->publics);
cell address = publics[index].address;
callStack_.push(address);
counters_[address].Start();
int error = amx_Exec(amx_, retval, index);
counters_[address].Stop();
if (!callStack_.empty()) {
callStack_.pop();
}
if (callStack_.empty()) {
frame_ = amx_->stp;
}
return error;
}
PLUGIN_EXPORT unsigned int PLUGIN_CALL Supports() {
return SUPPORTS_VERSION | SUPPORTS_AMX_NATIVES;
}
extern void *pAMXFunctions;
// Both x86 and x86-64 are Little Endian
static void *AMXAPI DummyAmxAlign(void *v) { return v; }
static std::list<std::string> profiledScripts;
PLUGIN_EXPORT bool PLUGIN_CALL Load(void **pluginData) {
pAMXFunctions = pluginData[PLUGIN_DATA_AMX_EXPORTS];
// The server does not export amx_Align16 and amx_Align32 for some reason
((void**)pAMXFunctions)[PLUGIN_AMX_EXPORT_Align16] = (void*)DummyAmxAlign;
((void**)pAMXFunctions)[PLUGIN_AMX_EXPORT_Align32] = (void*)DummyAmxAlign;
::amx_Exec_addr = reinterpret_cast<uint32_t>((static_cast<void**>(pAMXFunctions))[PLUGIN_AMX_EXPORT_Exec]);
SetJump(reinterpret_cast<void*>(::amx_Exec_addr), (void*)::Exec, ::amx_Exec_code);
// Get list of scripts to be profiled
std::copy(std::istream_iterator<std::string>(std::ifstream("plugins/profiler.cfg")),
std::istream_iterator<std::string>(),
std::back_inserter(::profiledScripts));
//std::copy(::profiledScripts.begin(), ::profiledScripts.end(), std::ostream_iterator<std::string>(std::cout));
// Initialize the name finder
AmxNameFinder::GetInstance()->AddSearchDir("gamemodes");
AmxNameFinder::GetInstance()->AddSearchDir("filterscripts");
return true;
}
PLUGIN_EXPORT void PLUGIN_CALL Unload() {
return;
}
PLUGIN_EXPORT int PLUGIN_CALL AmxLoad(AMX *amx) {
AmxNameFinder::GetInstance()->UpdateCache();
std::string filename = AmxNameFinder::GetInstance()->GetAmxName(amx);
// Looking up the base name only, i.e. file name + '.' + extenstion
if (std::find(::profiledScripts.begin(),
::profiledScripts.end(), filename) != ::profiledScripts.end())
{
FILE *fp = fopen(filename.c_str(), "rb");
if (fp != 0) {
AMX_DBG amxdbg;
int error = dbg_LoadInfo(&amxdbg, fp);
if (error == AMX_ERR_NONE) {
AmxProfiler::Attach(amx, amxdbg);
} else {
return error;
}
fclose(fp);
}
}
return AMX_ERR_NONE;
}
PLUGIN_EXPORT int PLUGIN_CALL AmxUnload(AMX *amx) {
AmxProfiler *prof = AmxProfiler::Get(amx);
std::string name = AmxNameFinder::GetInstance()->GetAmxName(amx);
if (prof != 0 && !name.empty()) {
prof->PrintStats(name + std::string(".prof"));
AmxProfiler::Detach(amx);
}
return AMX_ERR_NONE;
}
<|endoftext|> |
<commit_before>#include <gtest/gtest.h>
#include "mixable_stat.hpp"
#include <cmath>
using namespace std;
using namespace pfi::lang;
namespace jubatus {
TEST(mixable_stat_test, mixed_entropy) {
stat::mixable_stat p(1024);
p.push("test", 1.0);
p.push("test", 2.0);
p.push("test", 3.0);
double e_d = 3 * log(3);
double e_e = - e_d / 3 + log(3);
std::pair<double,size_t> d = p.get_diff();
ASSERT_DOUBLE_EQ(e_d, d.first);
ASSERT_EQ(3, d.second);
p.put_diff(d);
ASSERT_DOUBLE_EQ(e_e, p.mixed_entropy());
ASSERT_DOUBLE_EQ(p.entropy(), p.mixed_entropy());
}
}
<commit_msg>change signed constant to unsigned one to suppress warning<commit_after>#include <gtest/gtest.h>
#include "mixable_stat.hpp"
#include <cmath>
using namespace std;
using namespace pfi::lang;
namespace jubatus {
TEST(mixable_stat_test, mixed_entropy) {
stat::mixable_stat p(1024);
p.push("test", 1.0);
p.push("test", 2.0);
p.push("test", 3.0);
double e_d = 3 * log(3);
double e_e = - e_d / 3 + log(3);
std::pair<double,size_t> d = p.get_diff();
ASSERT_DOUBLE_EQ(e_d, d.first);
ASSERT_EQ(3u, d.second);
p.put_diff(d);
ASSERT_DOUBLE_EQ(e_e, p.mixed_entropy());
ASSERT_DOUBLE_EQ(p.entropy(), p.mixed_entropy());
}
}
<|endoftext|> |
<commit_before>//-----------------------------------------------------------------------------
// HIMG, by Marcus Geelnard, 2015
//
// This is free and unencumbered software released into the public domain.
//
// See LICENSE for details.
//-----------------------------------------------------------------------------
#include "quantize.h"
#include <algorithm>
namespace himg {
namespace {
const uint8_t kQuantTable[64] = {
8, 7, 7, 8, 9, 9, 10, 10,
8, 8, 8, 8, 9, 10, 10, 10,
8, 8, 8, 8, 9, 10, 10, 10,
8, 8, 8, 9, 10, 11, 10, 10,
8, 8, 9, 10, 10, 11, 11, 10,
9, 9, 10, 10, 10, 11, 11, 11,
9, 10, 10, 10, 11, 11, 11, 11,
10, 10, 10, 11, 11, 11, 11, 11
};
// TODO(m): Base this on histogram studies.
const int16_t kDelinearizeTable[128] = {
1, 2, 3, 4, 5, 6, 7, 8,
9, 10, 11, 12, 13, 14, 15, 16,
17, 18, 19, 20, 21, 22, 23, 24,
25, 26, 27, 28, 29, 30, 31, 32,
33, 35, 37, 39, 41, 43, 45, 47,
49, 51, 53, 55, 57, 59, 61, 63,
65, 69, 73, 77, 81, 85, 89, 93,
97, 101, 105, 109, 113, 117, 121, 125,
129, 137, 145, 153, 161, 169, 177, 185,
193, 201, 209, 217, 225, 233, 241, 249,
257, 265, 273, 281, 289, 297, 305, 313,
321, 329, 337, 345, 353, 361, 369, 377,
385, 401, 417, 433, 449, 465, 481, 497,
513, 529, 545, 561, 577, 593, 609, 625,
641, 657, 673, 689, 705, 721, 737, 753,
769, 785, 800, 820, 850, 900, 1000, 1500
};
uint8_t ToSignedMagnitude(int16_t abs_x, bool negative) {
// Special case: zero (it's quite common).
if (!abs_x) {
return 0;
}
// Look up the code.
// TODO(m): Do binary search, and proper rounding.
uint8_t code;
for (code = 0; code < 127; ++code) {
if (abs_x < kDelinearizeTable[code + 1])
break;
}
code++; // 1 <= code <= 128
// Combine code and sign bit.
if (negative)
return ((code - 1) << 1) + 1;
else
return code <= 127 ? (code << 1) : 254;
}
int16_t FromSignedMagnitude(uint8_t x) {
// Special case: zero (it's quite common).
if (!x) {
return 0;
}
if (x & 1)
return -kDelinearizeTable[x >> 1];
else
return kDelinearizeTable[(x >> 1) - 1];
}
} // namespace
void Quantize::MakeTable(uint8_t *table, uint8_t quality) {
if (quality > 9)
quality = 9;
for (int i = 0; i < 64; ++i) {
int16_t shift = static_cast<int16_t>(kQuantTable[i]) - quality;
table[i] =
shift >= 0 ? (shift <= 16 ? static_cast<uint8_t>(shift) : 16) : 0;
}
}
void Quantize::Pack(uint8_t *out, const int16_t *in, const uint8_t *table) {
for (int i = 0; i < 64; ++i) {
uint8_t shift = *table++;
int16_t x = *in++;
bool negative = x < 0;
// NOTE: We can not just shift negative numbers, since that will never
// produce zero (e.g. -5 >> 7 == -1), so we shift the absolute value and
// keep track of the sign.
*out++ = ToSignedMagnitude((negative ? -x : x) >> shift, negative);
}
}
void Quantize::Unpack(int16_t *out, const uint8_t *in, const uint8_t *table) {
for (int i = 0; i < 64; ++i) {
uint8_t shift = *table++;
*out++ = FromSignedMagnitude(*in++) << shift;
}
}
} // namespace himg
<commit_msg>Slightly improved delinearization LUT<commit_after>//-----------------------------------------------------------------------------
// HIMG, by Marcus Geelnard, 2015
//
// This is free and unencumbered software released into the public domain.
//
// See LICENSE for details.
//-----------------------------------------------------------------------------
#include "quantize.h"
#include <algorithm>
namespace himg {
namespace {
const uint8_t kQuantTable[64] = {
8, 7, 7, 8, 9, 9, 10, 10,
8, 8, 8, 8, 9, 10, 10, 10,
8, 8, 8, 8, 9, 10, 10, 10,
8, 8, 8, 9, 10, 11, 10, 10,
8, 8, 9, 10, 10, 11, 11, 10,
9, 9, 10, 10, 10, 11, 11, 11,
9, 10, 10, 10, 11, 11, 11, 11,
10, 10, 10, 11, 11, 11, 11, 11
};
// This LUT is based on histogram studies.
const int16_t kDelinearizeTable[128] = {
1, 2, 3, 4, 5, 6, 7,
8, 9, 10, 11, 12, 13, 14, 15,
16, 17, 18, 19, 20, 21, 22, 23,
24, 25, 26, 27, 28, 29, 30, 31,
32, 33, 34, 35, 36, 37, 38, 39,
40, 41, 42, 43, 44, 45, 46, 47,
48, 49, 50, 51, 52, 53, 54, 55,
56, 57, 58, 59, 60, 61, 62, 63,
64, 65, 66, 67, 68, 69, 70, 71,
73, 74, 76, 78, 79, 81, 83, 85,
87, 89, 92, 94, 97, 100, 103, 106,
109, 112, 116, 120, 125, 130, 135, 140,
146, 152, 159, 166, 173, 181, 190, 200,
210, 221, 233, 246, 260, 276, 293, 312,
333, 357, 383, 413, 448, 488, 535, 590,
656, 737, 838, 968, 1141, 1386, 1767, 2471,
5000
};
uint8_t ToSignedMagnitude(int16_t abs_x, bool negative) {
// Special case: zero (it's quite common).
if (!abs_x) {
return 0;
}
// Look up the code.
// TODO(m): Do binary search.
uint8_t code;
for (code = 0; code <= 127; ++code) {
if (abs_x <= kDelinearizeTable[code])
break;
}
if (code > 0 && code < 128) {
if (abs_x - kDelinearizeTable[code - 1] < kDelinearizeTable[code] - abs_x)
code--;
}
// Combine code and sign bit.
if (negative)
return (code << 1) + 1;
else
return code <= 126 ? ((code + 1) << 1) : 254;
}
int16_t FromSignedMagnitude(uint8_t x) {
// Special case: zero (it's quite common).
if (!x) {
return 0;
}
if (x & 1)
return -kDelinearizeTable[x >> 1];
else
return kDelinearizeTable[(x >> 1) - 1];
}
} // namespace
void Quantize::MakeTable(uint8_t *table, uint8_t quality) {
if (quality > 9)
quality = 9;
for (int i = 0; i < 64; ++i) {
int16_t shift = static_cast<int16_t>(kQuantTable[i]) - quality;
table[i] =
shift >= 0 ? (shift <= 16 ? static_cast<uint8_t>(shift) : 16) : 0;
}
}
void Quantize::Pack(uint8_t *out, const int16_t *in, const uint8_t *table) {
for (int i = 0; i < 64; ++i) {
uint8_t shift = *table++;
int16_t x = *in++;
bool negative = x < 0;
// NOTE: We can not just shift negative numbers, since that will never
// produce zero (e.g. -5 >> 7 == -1), so we shift the absolute value and
// keep track of the sign.
*out++ = ToSignedMagnitude((negative ? -x : x) >> shift, negative);
}
}
void Quantize::Unpack(int16_t *out, const uint8_t *in, const uint8_t *table) {
for (int i = 0; i < 64; ++i) {
uint8_t shift = *table++;
*out++ = FromSignedMagnitude(*in++) << shift;
}
}
} // namespace himg
<|endoftext|> |
<commit_before>#include <assert.h>
#include <algorithm>
#include <kstring.h>
#include <vcf.h>
#include "BCFSerialize.h"
#include "residuals.h"
using namespace std;
namespace GLnexus {
static string concat(const std::vector<std::string>& samples) {
return std::accumulate(samples.begin(), samples.end(), std::string(),
[](const std::string& a, const std::string& b) -> std::string {
return a + (a.length() > 0 ? "\t" : "") + b;
} );
}
Status residuals_gen_record(const unified_site& site,
const bcf_hdr_t *gl_hdr,
const bcf1_t *gl_call,
const std::vector<DatasetSiteInfo> &sites,
const MetadataCache& cache,
const std::vector<std::string>& samples,
std::string &ynode) {
Status s;
YAML::Emitter out;
out << YAML::BeginMap;
out << YAML::Key << "input";
out << YAML::BeginMap;
out << YAML::Key << "body";
out << YAML::BeginSeq;
// for each pertinent dataset
for (const auto& ds_info : sites) {
if (ds_info.records.size() == 0)
continue;
ostringstream records_text;
records_text << ds_info.name;
for (const auto& rec : ds_info.records) {
records_text << "\n" << *(bcf1_to_string(ds_info.header.get(), rec.get()));
}
out << YAML::BeginMap;
out << YAML::Key << ds_info.name;
out << YAML::Value << YAML::Literal << records_text.str();
out << YAML::EndMap;
}
out << YAML::EndSeq;
out << YAML::EndMap;
// write the unified site
out << YAML::Key << "unified_site";
const auto& contigs = cache.contigs();
S(site.yaml(contigs, out));
// write the output bcf, the calls that GLnexus made. Also, add the samples matching the calls.
out << YAML::Key << "output_vcf";
out << YAML::Literal << concat(samples) + "\n" + *(bcf1_to_string(gl_hdr, gl_call));
out << YAML::EndMap;
// Emit YAML format
ynode = string(out.c_str());
return Status::OK();
}
// destructor
ResidualsFile::~ResidualsFile() {
// write EOF marker
ofs_ << "..." << endl;
ofs_.close();
}
Status ResidualsFile::Open(std::string filename,
std::unique_ptr<ResidualsFile> &ans) {
ans = make_unique<ResidualsFile>(filename);
// Note: we open in truncate mode, to erase the existing file, if any.
// This avoids confusing results of old runs, with the current run, in case of failure.
ans->ofs_.open(filename, std::ofstream::out | std::ofstream::trunc);
if (ans->ofs_.fail())
return Status::Invalid("Error opening file for truncate ", filename);
return Status::OK();
}
Status ResidualsFile::write_record(std::string &rec) {
if (!ofs_.good())
return Status::Invalid("File cannot be written to ", filename_);
ofs_ << "---" << endl;
ofs_ << rec << endl;
ofs_ << endl;
return Status::OK();
}
}
<commit_msg>residuals: adjust sample name output<commit_after>#include <assert.h>
#include <algorithm>
#include <kstring.h>
#include <vcf.h>
#include "BCFSerialize.h"
#include "residuals.h"
using namespace std;
namespace GLnexus {
static string concat(const std::vector<std::string>& samples) {
return std::accumulate(samples.begin(), samples.end(), std::string(),
[](const std::string& a, const std::string& b) -> std::string {
return a + (a.length() > 0 ? "\t" : "") + b;
} );
}
Status residuals_gen_record(const unified_site& site,
const bcf_hdr_t *gl_hdr,
const bcf1_t *gl_call,
const std::vector<DatasetSiteInfo> &sites,
const MetadataCache& cache,
const std::vector<std::string>& samples,
std::string &ynode) {
Status s;
YAML::Emitter out;
out << YAML::BeginMap;
out << YAML::Key << "input";
out << YAML::BeginMap;
out << YAML::Key << "body";
out << YAML::BeginSeq;
// for each dataset
for (const auto& ds_info : sites) {
if (ds_info.records.size() == 0)
continue;
ostringstream records_text;
// line with sample name(s)
for (int i = 0; i < bcf_hdr_nsamples(gl_hdr); i++) {
if (i > 0) {
records_text << '\t';
}
records_text << bcf_hdr_int2id(gl_hdr, BCF_DT_SAMPLE, i);
}
// gVCF records, one per line
for (const auto& rec : ds_info.records) {
records_text << "\n" << *(bcf1_to_string(ds_info.header.get(), rec.get()));
}
out << YAML::BeginMap;
out << YAML::Key << ds_info.name;
out << YAML::Value << YAML::Literal << records_text.str();
out << YAML::EndMap;
}
out << YAML::EndSeq;
out << YAML::EndMap;
// write the unified site
out << YAML::Key << "unified_site";
const auto& contigs = cache.contigs();
S(site.yaml(contigs, out));
// write the output bcf, the calls that GLnexus made. Also, add the samples matching the calls.
out << YAML::Key << "output_vcf";
out << YAML::Literal << concat(samples) + "\n" + *(bcf1_to_string(gl_hdr, gl_call));
out << YAML::EndMap;
// Emit YAML format
ynode = string(out.c_str());
return Status::OK();
}
// destructor
ResidualsFile::~ResidualsFile() {
// write EOF marker
ofs_ << "..." << endl;
ofs_.close();
}
Status ResidualsFile::Open(std::string filename,
std::unique_ptr<ResidualsFile> &ans) {
ans = make_unique<ResidualsFile>(filename);
// Note: we open in truncate mode, to erase the existing file, if any.
// This avoids confusing results of old runs, with the current run, in case of failure.
ans->ofs_.open(filename, std::ofstream::out | std::ofstream::trunc);
if (ans->ofs_.fail())
return Status::Invalid("Error opening file for truncate ", filename);
return Status::OK();
}
Status ResidualsFile::write_record(std::string &rec) {
if (!ofs_.good())
return Status::Invalid("File cannot be written to ", filename_);
ofs_ << "---" << endl;
ofs_ << rec << endl;
ofs_ << endl;
return Status::OK();
}
}
<|endoftext|> |
<commit_before>/*
* Copyright 2016-2017 Nikolay Aleksiev. All rights reserved.
* License: https://github.com/naleksiev/mtlpp/blob/master/LICENSE
*/
#pragma once
#include "defines.hpp"
#include "ns.hpp"
namespace mtlpp
{
class Heap;
static const uint32_t ResourceCpuCacheModeShift = 0;
static const uint32_t ResourceStorageModeShift = 4;
static const uint32_t ResourceHazardTrackingModeShift = 8;
enum class PurgeableState
{
KeepCurrent = 1,
NonVolatile = 2,
Volatile = 3,
Empty = 4,
}
MTLPP_AVAILABLE(10_11, 8_0);
enum class CpuCacheMode
{
DefaultCache = 0,
WriteCombined = 1,
}
MTLPP_AVAILABLE(10_11, 8_0);
enum class StorageMode
{
Shared = 0,
Managed MTLPP_AVAILABLE(10_11, NA) = 1,
Private = 2,
Memoryless MTLPP_AVAILABLE(NA, 10_0) = 3,
}
MTLPP_AVAILABLE(10_11, 9_0);
enum class ResourceOptions
{
CpuCacheModeDefaultCache = uint32_t(CpuCacheMode::DefaultCache) << ResourceCpuCacheModeShift,
CpuCacheModeWriteCombined = uint32_t(CpuCacheMode::WriteCombined) << ResourceCpuCacheModeShift,
StorageModeShared MTLPP_AVAILABLE(10_11, 9_0) = uint32_t(StorageMode::Shared) << ResourceStorageModeShift,
StorageModeManaged MTLPP_AVAILABLE(10_11, NA) = uint32_t(StorageMode::Managed) << ResourceStorageModeShift,
StorageModePrivate MTLPP_AVAILABLE(10_11, 9_0) = uint32_t(StorageMode::Private) << ResourceStorageModeShift,
StorageModeMemoryless MTLPP_AVAILABLE(NA, 10_0) = uint32_t(StorageMode::Memoryless) << ResourceStorageModeShift,
HazardTrackingModeUntracked MTLPP_AVAILABLE(NA, 10_0) = 0x1 << ResourceHazardTrackingModeShift,
OptionCPUCacheModeDefault = CpuCacheModeDefaultCache,
OptionCPUCacheModeWriteCombined = CpuCacheModeWriteCombined,
}
MTLPP_AVAILABLE(10_11, 8_0);
class Resource : public ns::Object
{
public:
Resource() { }
Resource(const ns::Handle& handle) : ns::Object(handle) { }
ns::String GetLabel() const;
CpuCacheMode GetCpuCacheMode() const;
StorageMode GetStorageMode() const MTLPP_AVAILABLE(10_11, 9_0);
Heap GetHeap() const MTLPP_AVAILABLE(NA, 10_0);
bool IsAliasable() const MTLPP_AVAILABLE(NA, 10_0);
void SetLabel(const ns::String& label);
PurgeableState SetPurgeableState(PurgeableState state);
void MakeAliasable() const MTLPP_AVAILABLE(NA, 10_0);
}
MTLPP_AVAILABLE(10_11, 8_0);
}
<commit_msg>Fixing capitalization<commit_after>/*
* Copyright 2016-2017 Nikolay Aleksiev. All rights reserved.
* License: https://github.com/naleksiev/mtlpp/blob/master/LICENSE
*/
#pragma once
#include "defines.hpp"
#include "ns.hpp"
namespace mtlpp
{
class Heap;
static const uint32_t ResourceCpuCacheModeShift = 0;
static const uint32_t ResourceStorageModeShift = 4;
static const uint32_t ResourceHazardTrackingModeShift = 8;
enum class PurgeableState
{
KeepCurrent = 1,
NonVolatile = 2,
Volatile = 3,
Empty = 4,
}
MTLPP_AVAILABLE(10_11, 8_0);
enum class CpuCacheMode
{
DefaultCache = 0,
WriteCombined = 1,
}
MTLPP_AVAILABLE(10_11, 8_0);
enum class StorageMode
{
Shared = 0,
Managed MTLPP_AVAILABLE(10_11, NA) = 1,
Private = 2,
Memoryless MTLPP_AVAILABLE(NA, 10_0) = 3,
}
MTLPP_AVAILABLE(10_11, 9_0);
enum class ResourceOptions
{
CpuCacheModeDefaultCache = uint32_t(CpuCacheMode::DefaultCache) << ResourceCpuCacheModeShift,
CpuCacheModeWriteCombined = uint32_t(CpuCacheMode::WriteCombined) << ResourceCpuCacheModeShift,
StorageModeShared MTLPP_AVAILABLE(10_11, 9_0) = uint32_t(StorageMode::Shared) << ResourceStorageModeShift,
StorageModeManaged MTLPP_AVAILABLE(10_11, NA) = uint32_t(StorageMode::Managed) << ResourceStorageModeShift,
StorageModePrivate MTLPP_AVAILABLE(10_11, 9_0) = uint32_t(StorageMode::Private) << ResourceStorageModeShift,
StorageModeMemoryless MTLPP_AVAILABLE(NA, 10_0) = uint32_t(StorageMode::Memoryless) << ResourceStorageModeShift,
HazardTrackingModeUntracked MTLPP_AVAILABLE(NA, 10_0) = 0x1 << ResourceHazardTrackingModeShift,
OptionCpuCacheModeDefault = CpuCacheModeDefaultCache,
OptionCpuCacheModeWriteCombined = CpuCacheModeWriteCombined,
}
MTLPP_AVAILABLE(10_11, 8_0);
class Resource : public ns::Object
{
public:
Resource() { }
Resource(const ns::Handle& handle) : ns::Object(handle) { }
ns::String GetLabel() const;
CpuCacheMode GetCpuCacheMode() const;
StorageMode GetStorageMode() const MTLPP_AVAILABLE(10_11, 9_0);
Heap GetHeap() const MTLPP_AVAILABLE(NA, 10_0);
bool IsAliasable() const MTLPP_AVAILABLE(NA, 10_0);
void SetLabel(const ns::String& label);
PurgeableState SetPurgeableState(PurgeableState state);
void MakeAliasable() const MTLPP_AVAILABLE(NA, 10_0);
}
MTLPP_AVAILABLE(10_11, 8_0);
}
<|endoftext|> |
<commit_before>#include "responce.h"
std::string test(std::string data){
std::string message;
message = data;
return message;
}
<commit_msg>add newline delimiter at end of responce<commit_after>#include "responce.h"
std::string test(std::string data){
std::stringstream ss;
ss << data << std::endl;
std::string message = ss.str();
return message;
}
<|endoftext|> |
<commit_before>// This file is part of xsonrpc, an XML/JSON RPC library.
// Copyright (C) 2015 Erik Johansson <[email protected]>
//
// 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 "response.h"
#include "fault.h"
#include "writer.h"
namespace xsonrpc {
Response::Response(Value value)
: myResult(std::move(value)),
myIsFault(false)
{
}
Response::Response(int32_t faultCode, std::string faultString)
: myIsFault(true),
myFaultCode(faultCode),
myFaultString(std::move(faultString))
{
}
void Response::Write(Writer& writer) const
{
writer.StartDocument();
if (myIsFault) {
writer.StartFaultResponse();
writer.WriteFault(myFaultCode, myFaultString);
writer.EndFaultResponse();
}
else {
writer.StartResponse();
myResult.Write(writer);
writer.EndResponse();
}
writer.EndDocument();
}
void Response::ThrowIfFault() const
{
if (!IsFault()) {
return;
}
switch (static_cast<Fault::ReservedCodes>(myFaultCode)) {
case Fault::RESERVED_CODE_MIN:
case Fault::RESERVED_CODE_MAX:
case Fault::SERVER_ERROR_CODE_MIN:
break;
case Fault::PARSE_ERROR:
throw ParseErrorFault(myFaultString);
case Fault::INVALID_REQUEST:
throw InvalidRequestFault(myFaultString);
case Fault::METHOD_NOT_FOUND:
throw MethodNotFoundFault(myFaultString);
case Fault::INVALID_PARAMETERS:
throw InvalidParametersFault(myFaultString);
case Fault::INTERNAL_ERROR:
throw InternalErrorFault(myFaultString);
}
if (myFaultCode >= Fault::SERVER_ERROR_CODE_MIN
&& myFaultCode <= Fault::SERVER_ERROR_CODE_MAX) {
throw ServerErrorFault(myFaultCode, myFaultString);
}
if (myFaultCode >= Fault::RESERVED_CODE_MIN
&& myFaultCode <= Fault::RESERVED_CODE_MAX) {
throw PreDefinedFault(myFaultCode, myFaultString);
}
throw Fault(myFaultString, myFaultCode);
}
} // namespace xsonrpc
<commit_msg>Initialize field to please coverity<commit_after>// This file is part of xsonrpc, an XML/JSON RPC library.
// Copyright (C) 2015 Erik Johansson <[email protected]>
//
// 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 "response.h"
#include "fault.h"
#include "writer.h"
namespace xsonrpc {
Response::Response(Value value)
: myResult(std::move(value)),
myIsFault(false),
myFaultCode(0)
{
}
Response::Response(int32_t faultCode, std::string faultString)
: myIsFault(true),
myFaultCode(faultCode),
myFaultString(std::move(faultString))
{
}
void Response::Write(Writer& writer) const
{
writer.StartDocument();
if (myIsFault) {
writer.StartFaultResponse();
writer.WriteFault(myFaultCode, myFaultString);
writer.EndFaultResponse();
}
else {
writer.StartResponse();
myResult.Write(writer);
writer.EndResponse();
}
writer.EndDocument();
}
void Response::ThrowIfFault() const
{
if (!IsFault()) {
return;
}
switch (static_cast<Fault::ReservedCodes>(myFaultCode)) {
case Fault::RESERVED_CODE_MIN:
case Fault::RESERVED_CODE_MAX:
case Fault::SERVER_ERROR_CODE_MIN:
break;
case Fault::PARSE_ERROR:
throw ParseErrorFault(myFaultString);
case Fault::INVALID_REQUEST:
throw InvalidRequestFault(myFaultString);
case Fault::METHOD_NOT_FOUND:
throw MethodNotFoundFault(myFaultString);
case Fault::INVALID_PARAMETERS:
throw InvalidParametersFault(myFaultString);
case Fault::INTERNAL_ERROR:
throw InternalErrorFault(myFaultString);
}
if (myFaultCode >= Fault::SERVER_ERROR_CODE_MIN
&& myFaultCode <= Fault::SERVER_ERROR_CODE_MAX) {
throw ServerErrorFault(myFaultCode, myFaultString);
}
if (myFaultCode >= Fault::RESERVED_CODE_MIN
&& myFaultCode <= Fault::RESERVED_CODE_MAX) {
throw PreDefinedFault(myFaultCode, myFaultString);
}
throw Fault(myFaultString, myFaultCode);
}
} // namespace xsonrpc
<|endoftext|> |
<commit_before>/*****************************************************************************
* Media Library
*****************************************************************************
* Copyright (C) 2015-2019 Hugo Beauzée-Luyssen, Videolabs, VideoLAN
*
* Authors: Hugo Beauzée-Luyssen <[email protected]>
*
* This program is free software; you can redistribute it and/or modify it
* under the terms of the GNU Lesser General Public License as published by
* the Free Software Foundation; either version 2.1 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with this program; if not, write to the Free Software Foundation,
* Inc., 51 Franklin Street, Fifth Floor, Boston MA 02110-1301, USA.
*****************************************************************************/
#if HAVE_CONFIG_H
# include "config.h"
#endif
#include "FsDiscoverer.h"
#include <algorithm>
#include <queue>
#include <utility>
#include "factory/FileSystemFactory.h"
#include "medialibrary/filesystem/IDevice.h"
#include "Media.h"
#include "File.h"
#include "Device.h"
#include "Folder.h"
#include "logging/Logger.h"
#include "MediaLibrary.h"
#include "probe/CrawlerProbe.h"
#include "utils/Filename.h"
namespace medialibrary
{
FsDiscoverer::FsDiscoverer( std::shared_ptr<fs::IFileSystemFactory> fsFactory, MediaLibrary* ml, IMediaLibraryCb* cb, std::unique_ptr<prober::IProbe> probe )
: m_ml( ml )
, m_fsFactory( std::move( fsFactory ))
, m_cb( cb )
, m_probe( std::move( probe ) )
{
}
bool FsDiscoverer::discover( const std::string& entryPoint,
const IInterruptProbe& interruptProbe )
{
if ( m_fsFactory->isMrlSupported( entryPoint ) == false )
return false;
std::shared_ptr<fs::IDirectory> fsDir;
try
{
fsDir = m_fsFactory->createDirectory( entryPoint );
}
catch ( std::system_error& ex )
{
LOG_WARN( entryPoint, " discovery aborted because of a filesystem error: ", ex.what() );
return true;
}
auto fsDirMrl = fsDir->mrl(); // Saving MRL now since we might need it after fsDir is moved
auto f = Folder::fromMrl( m_ml, fsDirMrl );
// If the folder exists, we assume it will be handled by reload()
if ( f != nullptr )
return true;
try
{
if ( m_probe->proceedOnDirectory( *fsDir ) == false || m_probe->isHidden( *fsDir ) == true )
return true;
// Fetch files explicitly
fsDir->files();
auto res = addFolder( std::move( fsDir ), m_probe->getFolderParent().get(),
interruptProbe );
m_ml->getCb()->onEntryPointAdded( entryPoint, res );
return res;
}
catch ( sqlite::errors::ConstraintViolation& ex )
{
LOG_DEBUG( fsDirMrl, " discovery aborted (assuming banned folder): ", ex.what() );
}
catch ( fs::DeviceRemovedException& )
{
// Simply ignore, the device has already been marked as removed and the DB updated accordingly
LOG_DEBUG( "Discovery of ", fsDirMrl, " was stopped after the device was removed" );
}
return true;
}
bool FsDiscoverer::reloadFolder( std::shared_ptr<Folder> f,
const IInterruptProbe& probe )
{
assert( f->isPresent() );
auto mrl = f->mrl();
std::shared_ptr<fs::IDirectory> directory;
try
{
directory = m_fsFactory->createDirectory( mrl );
assert( directory->device() != nullptr );
if ( directory->device() == nullptr )
return false;
}
catch ( const std::system_error& ex )
{
LOG_INFO( "Failed to instanciate a directory for ", mrl, ": ", ex.what(),
". Can't reload the folder." );
}
if ( directory == nullptr )
{
auto device = m_fsFactory->createDeviceFromMrl( mrl );
if ( device == nullptr || device->isRemovable() == false )
{
LOG_DEBUG( "Failed to find folder matching entrypoint ", mrl, ". "
"Removing that folder" );
m_ml->deleteFolder( *f );
return false;
}
}
try
{
checkFolder( std::move( directory ), std::move( f ), false, probe );
}
catch ( fs::DeviceRemovedException& )
{
LOG_INFO( "Reloading of ", mrl, " was stopped after the device was removed" );
return false;
}
return true;
}
bool FsDiscoverer::reload( const IInterruptProbe& interruptProbe )
{
LOG_INFO( "Reloading all folders" );
auto rootFolders = Folder::fetchRootFolders( m_ml );
for ( const auto& f : rootFolders )
{
if ( interruptProbe.isInterrupted() == true )
break;
// fetchRootFolders only returns present folders
assert( f->isPresent() == true );
auto mrl = f->mrl();
if ( m_fsFactory->isMrlSupported( mrl ) == false )
continue;
m_cb->onReloadStarted( mrl );
auto res = reloadFolder( f, interruptProbe );
m_cb->onReloadCompleted( mrl, res );
}
return true;
}
bool FsDiscoverer::reload( const std::string& entryPoint,
const IInterruptProbe& interruptProbe )
{
if ( m_fsFactory->isMrlSupported( entryPoint ) == false )
return false;
auto folder = Folder::fromMrl( m_ml, entryPoint );
if ( folder == nullptr )
{
LOG_ERROR( "Can't reload ", entryPoint, ": folder wasn't found in database" );
return false;
}
if ( folder->isPresent() == false )
{
LOG_INFO( "Folder ", entryPoint, " isn't present, and therefore won't "
"be reloaded" );
return false;
}
reloadFolder( std::move( folder ), interruptProbe );
return true;
}
void FsDiscoverer::checkFolder( std::shared_ptr<fs::IDirectory> currentFolderFs,
std::shared_ptr<Folder> currentFolder,
bool newFolder,
const IInterruptProbe& interruptProbe ) const
{
try
{
// We already know of this folder, though it may now contain a .nomedia file.
// In this case, simply delete the folder.
if ( m_probe->isHidden( *currentFolderFs ) == true )
{
if ( newFolder == false )
m_ml->deleteFolder( *currentFolder );
return;
}
// Ensuring that the file fetching is done in this scope, to catch errors
currentFolderFs->files();
}
// Only check once for a system_error. They are bound to happen when we list the files/folders
// within, and IProbe::isHidden is the first place when this is done
catch ( std::system_error& ex )
{
LOG_WARN( "Failed to browse ", currentFolderFs->mrl(), ": ", ex.what() );
// Even when we're discovering a new folder, we want to rule out device removal as the cause of
// an IO error. If this is the cause, simply abort the discovery. All the folder we have
// discovered so far will be marked as non-present through sqlite hooks, and we'll resume the
// discovery when the device gets plugged back in
auto device = currentFolderFs->device();
// The device might not be present at all, and therefor we might miss a
// representation for it.
if ( device == nullptr || device->isRemovable() )
{
// If the device is removable/missing, check if it was indeed removed.
LOG_INFO( "The device containing ", currentFolderFs->mrl(), " is ",
device != nullptr ? "removable" : "not found",
". Refreshing device cache..." );
m_ml->refreshDevices( *m_fsFactory );
// If the device was missing, refresh our list of devices in case
// the device was plugged back and/or we missed a notification for it
if ( device == nullptr )
device = currentFolderFs->device();
// The device presence flag will be changed in place, so simply retest it
if ( device == nullptr || device->isPresent() == false )
throw fs::DeviceRemovedException();
LOG_INFO( "Device was not removed" );
}
// However if the device isn't removable, we want to:
// - ignore it when we're discovering a new folder.
// - delete it when it was discovered in the past. This is likely to be due to a permission change
// as we would not check the folder if it wasn't present during the parent folder browsing
// but it might also be that we're checking an entry point.
// The error won't arise earlier, as we only perform IO when reading the folder from this function.
if ( newFolder == false )
{
// If we ever came across this folder, its content is now unaccessible: let's remove it.
m_ml->deleteFolder( *currentFolder );
}
return;
}
if ( m_cb != nullptr )
m_cb->onDiscoveryProgress( currentFolderFs->mrl() );
// Load the folders we already know of:
LOG_DEBUG( "Checking for modifications in ", currentFolderFs->mrl() );
// Don't try to fetch any potential sub folders if the folder was freshly added
std::vector<std::shared_ptr<Folder>> subFoldersInDB;
if ( newFolder == false )
subFoldersInDB = currentFolder->folders();
for ( const auto& subFolder : currentFolderFs->dirs() )
{
if ( interruptProbe.isInterrupted() == true )
break;
if ( subFolder->device() == nullptr )
continue;
if ( m_probe->stopFileDiscovery() == true )
break;
if ( m_probe->proceedOnDirectory( *subFolder ) == false )
continue;
auto it = std::find_if( begin( subFoldersInDB ), end( subFoldersInDB ), [&subFolder](const std::shared_ptr<Folder>& f) {
return f->mrl() == subFolder->mrl();
});
// We don't know this folder, it's a new one
if ( it == end( subFoldersInDB ) )
{
if ( m_probe->isHidden( *subFolder ) )
continue;
LOG_DEBUG( "New folder detected: ", subFolder->mrl() );
try
{
addFolder( subFolder, currentFolder.get(), interruptProbe );
continue;
}
catch ( sqlite::errors::ConstraintViolation& ex )
{
// Best attempt to detect a foreign key violation, indicating the
// parent folders have been deleted due to being banned
if ( strstr( ex.what(), "foreign key" ) != nullptr )
{
LOG_WARN( "Creation of a folder failed because the parent is non existing: ", ex.what(),
". Assuming it was deleted due to being banned" );
return;
}
LOG_WARN( "Creation of a duplicated folder failed: ", ex.what(), ". Assuming it was banned" );
continue;
}
}
auto folderInDb = *it;
// In any case, check for modifications, as a change related to a mountpoint might
// not update the folder modification date.
// Also, relying on the modification date probably isn't portable
checkFolder( subFolder, folderInDb, false, interruptProbe );
subFoldersInDB.erase( it );
}
if ( m_probe->deleteUnseenFolders() == true )
{
// Now all folders we had in DB but haven't seen from the FS must have been deleted.
for ( const auto& f : subFoldersInDB )
{
LOG_DEBUG( "Folder ", f->mrl(), " not found in FS, deleting it" );
m_ml->deleteFolder( *f );
}
}
checkFiles( currentFolderFs, currentFolder, interruptProbe );
LOG_DEBUG( "Done checking subfolders in ", currentFolderFs->mrl() );
}
void FsDiscoverer::checkFiles( std::shared_ptr<fs::IDirectory> parentFolderFs,
std::shared_ptr<Folder> parentFolder,
const IInterruptProbe& interruptProbe) const
{
LOG_DEBUG( "Checking file in ", parentFolderFs->mrl() );
auto files = File::fromParentFolder( m_ml, parentFolder->id() );
std::vector<std::shared_ptr<fs::IFile>> filesToAdd;
std::vector<std::pair<std::shared_ptr<File>, std::shared_ptr<fs::IFile>>> filesToRefresh;
for ( const auto& fileFs: parentFolderFs->files() )
{
if ( interruptProbe.isInterrupted() == true )
return;
if ( m_probe->stopFileDiscovery() == true )
break;
if ( m_probe->proceedOnFile( *fileFs ) == false )
continue;
auto it = std::find_if( begin( files ), end( files ), [fileFs](const std::shared_ptr<File>& f) {
return f->mrl() == fileFs->mrl();
});
if ( it == end( files ) || m_probe->forceFileRefresh() == true )
{
if ( MediaLibrary::isExtensionSupported( fileFs->extension().c_str() ) == true )
filesToAdd.push_back( fileFs );
continue;
}
if ( fileFs->lastModificationDate() != (*it)->lastModificationDate() )
{
LOG_DEBUG( "Forcing file refresh ", fileFs->mrl() );
filesToRefresh.emplace_back( std::move( *it ), fileFs );
}
files.erase( it );
}
if ( m_probe->deleteUnseenFiles() == false )
files.clear();
auto t = m_ml->getConn()->newTransaction();
for ( const auto& file : files )
{
if ( interruptProbe.isInterrupted() == true )
break;
LOG_DEBUG( "File ", file->mrl(), " not found on filesystem, deleting it" );
auto media = file->media();
if ( media != nullptr )
media->removeFile( *file );
else
{
// This is unexpected, as the file should have been deleted when the media was
// removed.
LOG_WARN( "Deleting a file without an associated media." );
file->destroy();
}
}
for ( auto& p: filesToRefresh )
{
if ( interruptProbe.isInterrupted() == true )
break;
m_ml->onUpdatedFile( std::move( p.first ), std::move( p.second ) );
}
// Insert all files at once to avoid SQL write contention
for ( auto& p : filesToAdd )
{
if ( interruptProbe.isInterrupted() == true )
break;
m_ml->onDiscoveredFile( p, parentFolder, parentFolderFs,
IFile::Type::Main, m_probe->getPlaylistParent() );
}
t->commit();
LOG_DEBUG( "Done checking files in ", parentFolderFs->mrl() );
}
bool FsDiscoverer::addFolder( std::shared_ptr<fs::IDirectory> folder,
Folder* parentFolder,
const IInterruptProbe& interruptProbe ) const
{
auto deviceFs = folder->device();
// We are creating a folder, there has to be a device containing it.
assert( deviceFs != nullptr );
// But gracefully handle failure in release mode
if( deviceFs == nullptr )
return false;
auto device = Device::fromUuid( m_ml, deviceFs->uuid() );
if ( device == nullptr )
{
LOG_INFO( "Creating new device in DB ", deviceFs->uuid() );
device = Device::create( m_ml, deviceFs->uuid(),
utils::file::scheme( folder->mrl() ),
deviceFs->isRemovable() );
if ( device == nullptr )
return false;
}
auto f = Folder::create( m_ml, folder->mrl(),
parentFolder != nullptr ? parentFolder->id() : 0,
*device, *deviceFs );
if ( f == nullptr )
return false;
checkFolder( std::move( folder ), std::move( f ), true, interruptProbe );
return true;
}
}
<commit_msg>FsDiscoverer: Reindent after last change<commit_after>/*****************************************************************************
* Media Library
*****************************************************************************
* Copyright (C) 2015-2019 Hugo Beauzée-Luyssen, Videolabs, VideoLAN
*
* Authors: Hugo Beauzée-Luyssen <[email protected]>
*
* This program is free software; you can redistribute it and/or modify it
* under the terms of the GNU Lesser General Public License as published by
* the Free Software Foundation; either version 2.1 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with this program; if not, write to the Free Software Foundation,
* Inc., 51 Franklin Street, Fifth Floor, Boston MA 02110-1301, USA.
*****************************************************************************/
#if HAVE_CONFIG_H
# include "config.h"
#endif
#include "FsDiscoverer.h"
#include <algorithm>
#include <queue>
#include <utility>
#include "factory/FileSystemFactory.h"
#include "medialibrary/filesystem/IDevice.h"
#include "Media.h"
#include "File.h"
#include "Device.h"
#include "Folder.h"
#include "logging/Logger.h"
#include "MediaLibrary.h"
#include "probe/CrawlerProbe.h"
#include "utils/Filename.h"
namespace medialibrary
{
FsDiscoverer::FsDiscoverer( std::shared_ptr<fs::IFileSystemFactory> fsFactory, MediaLibrary* ml, IMediaLibraryCb* cb, std::unique_ptr<prober::IProbe> probe )
: m_ml( ml )
, m_fsFactory( std::move( fsFactory ))
, m_cb( cb )
, m_probe( std::move( probe ) )
{
}
bool FsDiscoverer::discover( const std::string& entryPoint,
const IInterruptProbe& interruptProbe )
{
if ( m_fsFactory->isMrlSupported( entryPoint ) == false )
return false;
std::shared_ptr<fs::IDirectory> fsDir;
try
{
fsDir = m_fsFactory->createDirectory( entryPoint );
}
catch ( std::system_error& ex )
{
LOG_WARN( entryPoint, " discovery aborted because of a filesystem error: ", ex.what() );
return true;
}
auto fsDirMrl = fsDir->mrl(); // Saving MRL now since we might need it after fsDir is moved
auto f = Folder::fromMrl( m_ml, fsDirMrl );
// If the folder exists, we assume it will be handled by reload()
if ( f != nullptr )
return true;
try
{
if ( m_probe->proceedOnDirectory( *fsDir ) == false || m_probe->isHidden( *fsDir ) == true )
return true;
// Fetch files explicitly
fsDir->files();
auto res = addFolder( std::move( fsDir ), m_probe->getFolderParent().get(),
interruptProbe );
m_ml->getCb()->onEntryPointAdded( entryPoint, res );
return res;
}
catch ( sqlite::errors::ConstraintViolation& ex )
{
LOG_DEBUG( fsDirMrl, " discovery aborted (assuming banned folder): ", ex.what() );
}
catch ( fs::DeviceRemovedException& )
{
// Simply ignore, the device has already been marked as removed and the DB updated accordingly
LOG_DEBUG( "Discovery of ", fsDirMrl, " was stopped after the device was removed" );
}
return true;
}
bool FsDiscoverer::reloadFolder( std::shared_ptr<Folder> f,
const IInterruptProbe& probe )
{
assert( f->isPresent() );
auto mrl = f->mrl();
std::shared_ptr<fs::IDirectory> directory;
try
{
directory = m_fsFactory->createDirectory( mrl );
assert( directory->device() != nullptr );
if ( directory->device() == nullptr )
return false;
}
catch ( const std::system_error& ex )
{
LOG_INFO( "Failed to instanciate a directory for ", mrl, ": ", ex.what(),
". Can't reload the folder." );
}
if ( directory == nullptr )
{
auto device = m_fsFactory->createDeviceFromMrl( mrl );
if ( device == nullptr || device->isRemovable() == false )
{
LOG_DEBUG( "Failed to find folder matching entrypoint ", mrl, ". "
"Removing that folder" );
m_ml->deleteFolder( *f );
return false;
}
}
try
{
checkFolder( std::move( directory ), std::move( f ), false, probe );
}
catch ( fs::DeviceRemovedException& )
{
LOG_INFO( "Reloading of ", mrl, " was stopped after the device was removed" );
return false;
}
return true;
}
bool FsDiscoverer::reload( const IInterruptProbe& interruptProbe )
{
LOG_INFO( "Reloading all folders" );
auto rootFolders = Folder::fetchRootFolders( m_ml );
for ( const auto& f : rootFolders )
{
if ( interruptProbe.isInterrupted() == true )
break;
// fetchRootFolders only returns present folders
assert( f->isPresent() == true );
auto mrl = f->mrl();
if ( m_fsFactory->isMrlSupported( mrl ) == false )
continue;
m_cb->onReloadStarted( mrl );
auto res = reloadFolder( f, interruptProbe );
m_cb->onReloadCompleted( mrl, res );
}
return true;
}
bool FsDiscoverer::reload( const std::string& entryPoint,
const IInterruptProbe& interruptProbe )
{
if ( m_fsFactory->isMrlSupported( entryPoint ) == false )
return false;
auto folder = Folder::fromMrl( m_ml, entryPoint );
if ( folder == nullptr )
{
LOG_ERROR( "Can't reload ", entryPoint, ": folder wasn't found in database" );
return false;
}
if ( folder->isPresent() == false )
{
LOG_INFO( "Folder ", entryPoint, " isn't present, and therefore won't "
"be reloaded" );
return false;
}
reloadFolder( std::move( folder ), interruptProbe );
return true;
}
void FsDiscoverer::checkFolder( std::shared_ptr<fs::IDirectory> currentFolderFs,
std::shared_ptr<Folder> currentFolder,
bool newFolder,
const IInterruptProbe& interruptProbe ) const
{
try
{
// We already know of this folder, though it may now contain a .nomedia file.
// In this case, simply delete the folder.
if ( m_probe->isHidden( *currentFolderFs ) == true )
{
if ( newFolder == false )
m_ml->deleteFolder( *currentFolder );
return;
}
// Ensuring that the file fetching is done in this scope, to catch errors
currentFolderFs->files();
}
// Only check once for a system_error. They are bound to happen when we list the files/folders
// within, and IProbe::isHidden is the first place when this is done
catch ( std::system_error& ex )
{
LOG_WARN( "Failed to browse ", currentFolderFs->mrl(), ": ", ex.what() );
// Even when we're discovering a new folder, we want to rule out device removal as the cause of
// an IO error. If this is the cause, simply abort the discovery. All the folder we have
// discovered so far will be marked as non-present through sqlite hooks, and we'll resume the
// discovery when the device gets plugged back in
auto device = currentFolderFs->device();
// The device might not be present at all, and therefor we might miss a
// representation for it.
if ( device == nullptr || device->isRemovable() )
{
// If the device is removable/missing, check if it was indeed removed.
LOG_INFO( "The device containing ", currentFolderFs->mrl(), " is ",
device != nullptr ? "removable" : "not found",
". Refreshing device cache..." );
m_ml->refreshDevices( *m_fsFactory );
// If the device was missing, refresh our list of devices in case
// the device was plugged back and/or we missed a notification for it
if ( device == nullptr )
device = currentFolderFs->device();
// The device presence flag will be changed in place, so simply retest it
if ( device == nullptr || device->isPresent() == false )
throw fs::DeviceRemovedException();
LOG_INFO( "Device was not removed" );
}
// However if the device isn't removable, we want to:
// - ignore it when we're discovering a new folder.
// - delete it when it was discovered in the past. This is likely to be due to a permission change
// as we would not check the folder if it wasn't present during the parent folder browsing
// but it might also be that we're checking an entry point.
// The error won't arise earlier, as we only perform IO when reading the folder from this function.
if ( newFolder == false )
{
// If we ever came across this folder, its content is now unaccessible: let's remove it.
m_ml->deleteFolder( *currentFolder );
}
return;
}
if ( m_cb != nullptr )
m_cb->onDiscoveryProgress( currentFolderFs->mrl() );
// Load the folders we already know of:
LOG_DEBUG( "Checking for modifications in ", currentFolderFs->mrl() );
// Don't try to fetch any potential sub folders if the folder was freshly added
std::vector<std::shared_ptr<Folder>> subFoldersInDB;
if ( newFolder == false )
subFoldersInDB = currentFolder->folders();
for ( const auto& subFolder : currentFolderFs->dirs() )
{
if ( interruptProbe.isInterrupted() == true )
break;
if ( subFolder->device() == nullptr )
continue;
if ( m_probe->stopFileDiscovery() == true )
break;
if ( m_probe->proceedOnDirectory( *subFolder ) == false )
continue;
auto it = std::find_if( begin( subFoldersInDB ), end( subFoldersInDB ), [&subFolder](const std::shared_ptr<Folder>& f) {
return f->mrl() == subFolder->mrl();
});
// We don't know this folder, it's a new one
if ( it == end( subFoldersInDB ) )
{
if ( m_probe->isHidden( *subFolder ) )
continue;
LOG_DEBUG( "New folder detected: ", subFolder->mrl() );
try
{
addFolder( subFolder, currentFolder.get(), interruptProbe );
continue;
}
catch ( sqlite::errors::ConstraintViolation& ex )
{
// Best attempt to detect a foreign key violation, indicating the
// parent folders have been deleted due to being banned
if ( strstr( ex.what(), "foreign key" ) != nullptr )
{
LOG_WARN( "Creation of a folder failed because the parent is non existing: ", ex.what(),
". Assuming it was deleted due to being banned" );
return;
}
LOG_WARN( "Creation of a duplicated folder failed: ", ex.what(), ". Assuming it was banned" );
continue;
}
}
auto folderInDb = *it;
// In any case, check for modifications, as a change related to a mountpoint might
// not update the folder modification date.
// Also, relying on the modification date probably isn't portable
checkFolder( subFolder, folderInDb, false, interruptProbe );
subFoldersInDB.erase( it );
}
if ( m_probe->deleteUnseenFolders() == true )
{
// Now all folders we had in DB but haven't seen from the FS must have been deleted.
for ( const auto& f : subFoldersInDB )
{
LOG_DEBUG( "Folder ", f->mrl(), " not found in FS, deleting it" );
m_ml->deleteFolder( *f );
}
}
checkFiles( currentFolderFs, currentFolder, interruptProbe );
LOG_DEBUG( "Done checking subfolders in ", currentFolderFs->mrl() );
}
void FsDiscoverer::checkFiles( std::shared_ptr<fs::IDirectory> parentFolderFs,
std::shared_ptr<Folder> parentFolder,
const IInterruptProbe& interruptProbe) const
{
LOG_DEBUG( "Checking file in ", parentFolderFs->mrl() );
auto files = File::fromParentFolder( m_ml, parentFolder->id() );
std::vector<std::shared_ptr<fs::IFile>> filesToAdd;
std::vector<std::pair<std::shared_ptr<File>, std::shared_ptr<fs::IFile>>> filesToRefresh;
for ( const auto& fileFs: parentFolderFs->files() )
{
if ( interruptProbe.isInterrupted() == true )
return;
if ( m_probe->stopFileDiscovery() == true )
break;
if ( m_probe->proceedOnFile( *fileFs ) == false )
continue;
auto it = std::find_if( begin( files ), end( files ), [fileFs](const std::shared_ptr<File>& f) {
return f->mrl() == fileFs->mrl();
});
if ( it == end( files ) || m_probe->forceFileRefresh() == true )
{
if ( MediaLibrary::isExtensionSupported( fileFs->extension().c_str() ) == true )
filesToAdd.push_back( fileFs );
continue;
}
if ( fileFs->lastModificationDate() != (*it)->lastModificationDate() )
{
LOG_DEBUG( "Forcing file refresh ", fileFs->mrl() );
filesToRefresh.emplace_back( std::move( *it ), fileFs );
}
files.erase( it );
}
if ( m_probe->deleteUnseenFiles() == false )
files.clear();
auto t = m_ml->getConn()->newTransaction();
for ( const auto& file : files )
{
if ( interruptProbe.isInterrupted() == true )
break;
LOG_DEBUG( "File ", file->mrl(), " not found on filesystem, deleting it" );
auto media = file->media();
if ( media != nullptr )
media->removeFile( *file );
else
{
// This is unexpected, as the file should have been deleted when the media was
// removed.
LOG_WARN( "Deleting a file without an associated media." );
file->destroy();
}
}
for ( auto& p: filesToRefresh )
{
if ( interruptProbe.isInterrupted() == true )
break;
m_ml->onUpdatedFile( std::move( p.first ), std::move( p.second ) );
}
// Insert all files at once to avoid SQL write contention
for ( auto& p : filesToAdd )
{
if ( interruptProbe.isInterrupted() == true )
break;
m_ml->onDiscoveredFile( p, parentFolder, parentFolderFs,
IFile::Type::Main, m_probe->getPlaylistParent() );
}
t->commit();
LOG_DEBUG( "Done checking files in ", parentFolderFs->mrl() );
}
bool FsDiscoverer::addFolder( std::shared_ptr<fs::IDirectory> folder,
Folder* parentFolder,
const IInterruptProbe& interruptProbe ) const
{
auto deviceFs = folder->device();
// We are creating a folder, there has to be a device containing it.
assert( deviceFs != nullptr );
// But gracefully handle failure in release mode
if( deviceFs == nullptr )
return false;
auto device = Device::fromUuid( m_ml, deviceFs->uuid() );
if ( device == nullptr )
{
LOG_INFO( "Creating new device in DB ", deviceFs->uuid() );
device = Device::create( m_ml, deviceFs->uuid(),
utils::file::scheme( folder->mrl() ),
deviceFs->isRemovable() );
if ( device == nullptr )
return false;
}
auto f = Folder::create( m_ml, folder->mrl(),
parentFolder != nullptr ? parentFolder->id() : 0,
*device, *deviceFs );
if ( f == nullptr )
return false;
checkFolder( std::move( folder ), std::move( f ), true, interruptProbe );
return true;
}
}
<|endoftext|> |
<commit_before>// sdl_main.cpp
#ifdef _WIN32
# define WINDOWS_LEAN_AND_MEAN
# define NOMINMAX
# include <windows.h>
#endif
#include <fstream>
#include <vector>
#include <GL/glew.h>
#include <SDL.h>
#include <SDL_syswm.h>
#undef main
#include "ShaderFunctions.h"
#include "Timer.h"
#include "g_textures.h"
Timer g_timer;
int winw = 800;
int winh = 600;
struct renderpass {
GLuint prog;
GLint uloc_iResolution;
GLint uloc_iGlobalTime;
GLint uloc_iChannelResolution;
//iChannelTime not implemented
GLint uloc_iChannel[4];
GLint uloc_iMouse;
GLint uloc_iDate;
GLint uloc_iBlockOffset;
GLint uloc_iSampleRate;
GLuint texs[4];
};
struct Shadertoy {
renderpass image;
renderpass sound;
};
Shadertoy g_toy;
void keyboard(const SDL_Event& event, int key, int codes, int action, int mods)
{
(void)codes;
(void)mods;
if (action == SDL_KEYDOWN)
{
switch (key)
{
default:
break;
case SDLK_ESCAPE:
SDL_Quit();
exit(0);
break;
}
}
}
void PollEvents()
{
SDL_Event event;
while (SDL_PollEvent(&event))
{
switch(event.type)
{
case SDL_KEYDOWN:
case SDL_KEYUP:
keyboard(event, event.key.keysym.sym, 0, event.key.type, 0);
break;
case SDL_MOUSEBUTTONDOWN:
case SDL_MOUSEBUTTONUP:
break;
case SDL_MOUSEMOTION:
break;
case SDL_MOUSEWHEEL:
break;
case SDL_WINDOWEVENT:
break;
case SDL_QUIT:
exit(0);
break;
default:
break;
}
}
}
void display()
{
const renderpass& r = g_toy.image;
glUseProgram(r.prog);
if (r.uloc_iResolution > -1) glUniform3f(r.uloc_iResolution, (float)winw, (float)winh, 1.f);
if (r.uloc_iGlobalTime > -1) glUniform1f(r.uloc_iGlobalTime, g_timer.seconds());
if (r.uloc_iMouse > -1) glUniform4f(r.uloc_iMouse, 0.f, 0.f, 0.f, 0.f);
if (r.uloc_iDate > -1) glUniform4f(r.uloc_iDate, 2015.f, 3.f, 6.f, 6.f);
for (int i=0; i<4; ++i)
{
glActiveTexture(GL_TEXTURE0+i);
glBindTexture(GL_TEXTURE_2D, r.texs[i]);
if (r.uloc_iChannel[i] > -1) glUniform1i(r.uloc_iChannel[i], i);
}
glRecti(-1,-1,1,1);
}
//
// Audio
//
struct
{
SDL_AudioSpec spec;
Uint8 *sound; /* Pointer to wave data */
Uint32 soundlen; /* Length of wave data */
int soundpos; /* Current play position */
} wave;
void SDLCALL fillerup(void *unused, Uint8 * stream, int len)
{
Uint8 *waveptr;
int waveleft;
waveptr = wave.sound + wave.soundpos;
waveleft = wave.soundlen - wave.soundpos;
while (waveleft <= len) { // wrap condition
SDL_memcpy(stream, waveptr, waveleft);
stream += waveleft;
len -= waveleft;
waveptr = wave.sound;
waveleft = wave.soundlen;
wave.soundpos = 0;
}
SDL_memcpy(stream, waveptr, len);
wave.soundpos += len;
}
void play_audio()
{
wave.spec.freq = 44100;
wave.spec.format = AUDIO_U8; //AUDIO_S16LSB;
wave.spec.channels = 2;
wave.spec.callback = fillerup;
const int mPlayTime = 60; // Shadertoy gives 60 seconds of audio
wave.soundlen = mPlayTime * wave.spec.freq;
wave.sound = new Uint8[2*wave.soundlen];
glViewport(0,0,512,512);
const renderpass& r = g_toy.sound;
glUseProgram(r.prog);
unsigned char* mData = new unsigned char[512*512*4];
int mTmpBufferSamples = 262144;
int mPlaySamples = wave.soundlen;
int numBlocks = mPlaySamples / mTmpBufferSamples;
for (int j=0; j<numBlocks; ++j)
{
int off = j * mTmpBufferSamples;
if (r.uloc_iBlockOffset > -1) glUniform1f(r.uloc_iBlockOffset, (float)off / (float)wave.spec.freq);
glRecti(-1,-1,1,1);
// mData: Uint8Array[1048576]
glReadPixels(0,0,512,512, GL_RGBA, GL_UNSIGNED_BYTE, mData);
for (int i = 0; i<mTmpBufferSamples; ++i)
{
const float aL = -1.0f + 2.0f*((float)mData[4 * i + 0] + 256.0f*(float)mData[4 * i + 1]) / 65535.0f;
const float aR = -1.0f + 2.0f*((float)mData[4 * i + 2] + 256.0f*(float)mData[4 * i + 3]) / 65535.0f;
wave.sound[2*(off + i) ] = (unsigned char)(.5f*(1.f+aL) * 255.f);
wave.sound[2*(off + i)+1] = (unsigned char)(.5f*(1.f+aR) * 255.f);
}
}
delete [] mData;
if (SDL_OpenAudio(&wave.spec, NULL) < 0)
{
SDL_FreeWAV(wave.sound);
SDL_Quit();
exit(2);
}
SDL_PauseAudio(0); // Start playing
}
int main(void)
{
///@todo cmd line aargs
if (SDL_Init(SDL_INIT_EVERYTHING) < 0)
{
return false;
}
SDL_GL_SetAttribute(SDL_GL_CONTEXT_PROFILE_MASK, SDL_GL_CONTEXT_PROFILE_COMPATIBILITY);
SDL_GL_SetAttribute(SDL_GL_CONTEXT_MAJOR_VERSION, 3);
SDL_GL_SetAttribute(SDL_GL_CONTEXT_MINOR_VERSION, 2);
int winw = 800;
int winh = 600;
SDL_Window* pWindow = SDL_CreateWindow(
"kinderegg",
100,100,
winw, winh,
SDL_WINDOW_SHOWN | SDL_WINDOW_OPENGL);
// thank you http://www.brandonfoltz.com/2013/12/example-using-opengl-3-0-with-sdl2-and-glew/
SDL_GLContext glContext = SDL_GL_CreateContext(pWindow);
if (glContext == NULL)
{
printf("There was an error creating the OpenGL context!\n");
return 0;
}
const unsigned char *version = glGetString(GL_VERSION);
if (version == NULL)
{
printf("There was an error creating the OpenGL context!\n");
return 1;
}
SDL_GL_MakeCurrent(pWindow, glContext);
// Don't forget to initialize Glew, turn glewExperimental on to
// avoid problems fetching function pointers...
glewExperimental = GL_TRUE;
const GLenum l_Result = glewInit();
if (l_Result != GLEW_OK)
{
exit(EXIT_FAILURE);
}
renderpass& r = g_toy.image;
r.prog = makeShaderFromSource("passthru.vert", "image.frag");
r.uloc_iResolution = glGetUniformLocation(r.prog, "iResolution");
r.uloc_iGlobalTime = glGetUniformLocation(r.prog, "iGlobalTime");
r.uloc_iChannelResolution = glGetUniformLocation(r.prog, "iChannelResolution");
r.uloc_iChannel[0] = glGetUniformLocation(r.prog, "iChannel0");
r.uloc_iChannel[1] = glGetUniformLocation(r.prog, "iChannel1");
r.uloc_iChannel[2] = glGetUniformLocation(r.prog, "iChannel2");
r.uloc_iChannel[3] = glGetUniformLocation(r.prog, "iChannel3");
r.uloc_iMouse = glGetUniformLocation(r.prog, "iMouse");
r.uloc_iDate = glGetUniformLocation(r.prog, "iDate");
for (int i=0; i<4; ++i)
{
const int w = texdims[3*i];
const int h = texdims[3*i+1];
const int d = texdims[3*i+2];
if (w == 0)
continue;
GLuint t = 0;
glActiveTexture(GL_TEXTURE0+i);
glGenTextures(1, &t);
glBindTexture(GL_TEXTURE_2D, t);
GLuint mode = 0;
switch (d)
{
default:break;
case 1: mode = GL_LUMINANCE; break;
case 3: mode = GL_RGB; break;
case 4: mode = GL_RGBA; break;
}
char texname[6] = "tex00";
texname[4] += i;
std::ifstream file(texname, std::ios::binary);
if (!file.is_open())
continue;
file.seekg(0, std::ios::end);
std::streamsize size = file.tellg();
file.seekg(0, std::ios::beg);
std::vector<char> buffer(size);
if (file.read(buffer.data(), size))
{
glTexParameteri( GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_NEAREST );
glTexParameteri( GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_NEAREST );
glTexImage2D(GL_TEXTURE_2D,
0, mode,
w, h,
0, mode,
GL_UNSIGNED_BYTE,
&buffer[0]);
r.texs[i] = t;
}
}
renderpass& s = g_toy.sound;
s.prog = makeShaderFromSource("passthru.vert", "sound.frag");
s.uloc_iBlockOffset = glGetUniformLocation(s.prog, "iBlockOffset");
s.uloc_iSampleRate = glGetUniformLocation(s.prog, "iSampleRate");
play_audio();
glViewport(0,0, winw, winh);
int quit = 0;
while (quit == 0)
{
PollEvents();
display();
SDL_GL_SwapWindow(pWindow);
}
SDL_GL_DeleteContext(glContext);
SDL_DestroyWindow(pWindow);
SDL_CloseAudio();
SDL_FreeWAV(wave.sound);
SDL_Quit();
}
<commit_msg>Set system time uniform.<commit_after>// sdl_main.cpp
#ifdef _WIN32
# define WINDOWS_LEAN_AND_MEAN
# define NOMINMAX
# include <windows.h>
#endif
#include <fstream>
#include <vector>
#include <GL/glew.h>
#include <SDL.h>
#include <SDL_syswm.h>
#undef main
#include "ShaderFunctions.h"
#include "Timer.h"
#include "g_textures.h"
Timer g_timer;
int winw = 800;
int winh = 600;
struct renderpass {
GLuint prog;
GLint uloc_iResolution;
GLint uloc_iGlobalTime;
GLint uloc_iChannelResolution;
//iChannelTime not implemented
GLint uloc_iChannel[4];
GLint uloc_iMouse;
GLint uloc_iDate;
GLint uloc_iBlockOffset;
GLint uloc_iSampleRate;
GLuint texs[4];
};
struct Shadertoy {
renderpass image;
renderpass sound;
};
Shadertoy g_toy;
void keyboard(const SDL_Event& event, int key, int codes, int action, int mods)
{
(void)codes;
(void)mods;
if (action == SDL_KEYDOWN)
{
switch (key)
{
default:
break;
case SDLK_ESCAPE:
SDL_Quit();
exit(0);
break;
}
}
}
void PollEvents()
{
SDL_Event event;
while (SDL_PollEvent(&event))
{
switch(event.type)
{
case SDL_KEYDOWN:
case SDL_KEYUP:
keyboard(event, event.key.keysym.sym, 0, event.key.type, 0);
break;
case SDL_MOUSEBUTTONDOWN:
case SDL_MOUSEBUTTONUP:
break;
case SDL_MOUSEMOTION:
break;
case SDL_MOUSEWHEEL:
break;
case SDL_WINDOWEVENT:
break;
case SDL_QUIT:
exit(0);
break;
default:
break;
}
}
}
void display()
{
const renderpass& r = g_toy.image;
glUseProgram(r.prog);
if (r.uloc_iResolution > -1) glUniform3f(r.uloc_iResolution, (float)winw, (float)winh, 1.f);
if (r.uloc_iGlobalTime > -1) glUniform1f(r.uloc_iGlobalTime, g_timer.seconds());
if (r.uloc_iMouse > -1) glUniform4f(r.uloc_iMouse, 0.f, 0.f, 0.f, 0.f);
SYSTEMTIME stNow;
GetSystemTime(&stNow);
if (r.uloc_iDate > -1) glUniform4f(r.uloc_iDate,
(float)stNow.wYear,
(float)stNow.wMonth - 1.f,
(float)stNow.wDay,
(float)stNow.wHour*60.f*60.f +
(float)stNow.wMinute*60.f +
(float)stNow.wSecond
);
for (int i=0; i<4; ++i)
{
glActiveTexture(GL_TEXTURE0+i);
glBindTexture(GL_TEXTURE_2D, r.texs[i]);
if (r.uloc_iChannel[i] > -1) glUniform1i(r.uloc_iChannel[i], i);
}
glRecti(-1,-1,1,1);
}
//
// Audio
//
struct
{
SDL_AudioSpec spec;
Uint8 *sound; /* Pointer to wave data */
Uint32 soundlen; /* Length of wave data */
int soundpos; /* Current play position */
} wave;
void SDLCALL fillerup(void *unused, Uint8 * stream, int len)
{
Uint8 *waveptr;
int waveleft;
waveptr = wave.sound + wave.soundpos;
waveleft = wave.soundlen - wave.soundpos;
while (waveleft <= len) { // wrap condition
SDL_memcpy(stream, waveptr, waveleft);
stream += waveleft;
len -= waveleft;
waveptr = wave.sound;
waveleft = wave.soundlen;
wave.soundpos = 0;
}
SDL_memcpy(stream, waveptr, len);
wave.soundpos += len;
}
void play_audio()
{
wave.spec.freq = 44100;
wave.spec.format = AUDIO_U8; //AUDIO_S16LSB;
wave.spec.channels = 2;
wave.spec.callback = fillerup;
const int mPlayTime = 60; // Shadertoy gives 60 seconds of audio
wave.soundlen = mPlayTime * wave.spec.freq;
wave.sound = new Uint8[2*wave.soundlen];
glViewport(0,0,512,512);
const renderpass& r = g_toy.sound;
glUseProgram(r.prog);
unsigned char* mData = new unsigned char[512*512*4];
int mTmpBufferSamples = 262144;
int mPlaySamples = wave.soundlen;
int numBlocks = mPlaySamples / mTmpBufferSamples;
for (int j=0; j<numBlocks; ++j)
{
int off = j * mTmpBufferSamples;
if (r.uloc_iBlockOffset > -1) glUniform1f(r.uloc_iBlockOffset, (float)off / (float)wave.spec.freq);
glRecti(-1,-1,1,1);
// mData: Uint8Array[1048576]
glReadPixels(0,0,512,512, GL_RGBA, GL_UNSIGNED_BYTE, mData);
for (int i = 0; i<mTmpBufferSamples; ++i)
{
const float aL = -1.0f + 2.0f*((float)mData[4 * i + 0] + 256.0f*(float)mData[4 * i + 1]) / 65535.0f;
const float aR = -1.0f + 2.0f*((float)mData[4 * i + 2] + 256.0f*(float)mData[4 * i + 3]) / 65535.0f;
wave.sound[2*(off + i) ] = (unsigned char)(.5f*(1.f+aL) * 255.f);
wave.sound[2*(off + i)+1] = (unsigned char)(.5f*(1.f+aR) * 255.f);
}
}
delete [] mData;
if (SDL_OpenAudio(&wave.spec, NULL) < 0)
{
SDL_FreeWAV(wave.sound);
SDL_Quit();
exit(2);
}
SDL_PauseAudio(0); // Start playing
}
int main(void)
{
///@todo cmd line aargs
if (SDL_Init(SDL_INIT_EVERYTHING) < 0)
{
return false;
}
SDL_GL_SetAttribute(SDL_GL_CONTEXT_PROFILE_MASK, SDL_GL_CONTEXT_PROFILE_COMPATIBILITY);
SDL_GL_SetAttribute(SDL_GL_CONTEXT_MAJOR_VERSION, 3);
SDL_GL_SetAttribute(SDL_GL_CONTEXT_MINOR_VERSION, 2);
int winw = 800;
int winh = 600;
SDL_Window* pWindow = SDL_CreateWindow(
"kinderegg",
100,100,
winw, winh,
SDL_WINDOW_SHOWN | SDL_WINDOW_OPENGL);
// thank you http://www.brandonfoltz.com/2013/12/example-using-opengl-3-0-with-sdl2-and-glew/
SDL_GLContext glContext = SDL_GL_CreateContext(pWindow);
if (glContext == NULL)
{
printf("There was an error creating the OpenGL context!\n");
return 0;
}
const unsigned char *version = glGetString(GL_VERSION);
if (version == NULL)
{
printf("There was an error creating the OpenGL context!\n");
return 1;
}
SDL_GL_MakeCurrent(pWindow, glContext);
// Don't forget to initialize Glew, turn glewExperimental on to
// avoid problems fetching function pointers...
glewExperimental = GL_TRUE;
const GLenum l_Result = glewInit();
if (l_Result != GLEW_OK)
{
exit(EXIT_FAILURE);
}
renderpass& r = g_toy.image;
r.prog = makeShaderFromSource("passthru.vert", "image.frag");
r.uloc_iResolution = glGetUniformLocation(r.prog, "iResolution");
r.uloc_iGlobalTime = glGetUniformLocation(r.prog, "iGlobalTime");
r.uloc_iChannelResolution = glGetUniformLocation(r.prog, "iChannelResolution");
r.uloc_iChannel[0] = glGetUniformLocation(r.prog, "iChannel0");
r.uloc_iChannel[1] = glGetUniformLocation(r.prog, "iChannel1");
r.uloc_iChannel[2] = glGetUniformLocation(r.prog, "iChannel2");
r.uloc_iChannel[3] = glGetUniformLocation(r.prog, "iChannel3");
r.uloc_iMouse = glGetUniformLocation(r.prog, "iMouse");
r.uloc_iDate = glGetUniformLocation(r.prog, "iDate");
for (int i=0; i<4; ++i)
{
const int w = texdims[3*i];
const int h = texdims[3*i+1];
const int d = texdims[3*i+2];
if (w == 0)
continue;
GLuint t = 0;
glActiveTexture(GL_TEXTURE0+i);
glGenTextures(1, &t);
glBindTexture(GL_TEXTURE_2D, t);
GLuint mode = 0;
switch (d)
{
default:break;
case 1: mode = GL_LUMINANCE; break;
case 3: mode = GL_RGB; break;
case 4: mode = GL_RGBA; break;
}
char texname[6] = "tex00";
texname[4] += i;
std::ifstream file(texname, std::ios::binary);
if (!file.is_open())
continue;
file.seekg(0, std::ios::end);
std::streamsize size = file.tellg();
file.seekg(0, std::ios::beg);
std::vector<char> buffer(size);
if (file.read(buffer.data(), size))
{
glTexParameteri( GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_NEAREST );
glTexParameteri( GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_NEAREST );
glTexImage2D(GL_TEXTURE_2D,
0, mode,
w, h,
0, mode,
GL_UNSIGNED_BYTE,
&buffer[0]);
r.texs[i] = t;
}
}
renderpass& s = g_toy.sound;
s.prog = makeShaderFromSource("passthru.vert", "sound.frag");
s.uloc_iBlockOffset = glGetUniformLocation(s.prog, "iBlockOffset");
s.uloc_iSampleRate = glGetUniformLocation(s.prog, "iSampleRate");
play_audio();
glViewport(0,0, winw, winh);
int quit = 0;
while (quit == 0)
{
PollEvents();
display();
SDL_GL_SwapWindow(pWindow);
}
SDL_GL_DeleteContext(glContext);
SDL_DestroyWindow(pWindow);
SDL_CloseAudio();
SDL_FreeWAV(wave.sound);
SDL_Quit();
}
<|endoftext|> |
<commit_before>/*
* Copyright 2010-2012 Esrille 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 "HTMLBodyElementImp.h"
#include <org/w3c/dom/html/Window.h>
namespace org { namespace w3c { namespace dom { namespace bootstrap {
void HTMLBodyElementImp::eval()
{
HTMLElementImp::eval();
HTMLElementImp::evalBackground(this);
HTMLElementImp::evalBgcolor(this);
}
// Node
Node HTMLBodyElementImp::cloneNode(bool deep)
{
return new(std::nothrow) HTMLBodyElementImp(this, deep);
}
// HTMLBodyElement
html::Function HTMLBodyElementImp::getOnafterprint()
{
// TODO: implement me!
return static_cast<Object*>(0);
}
void HTMLBodyElementImp::setOnafterprint(html::Function onafterprint)
{
// TODO: implement me!
}
html::Function HTMLBodyElementImp::getOnbeforeprint()
{
// TODO: implement me!
return static_cast<Object*>(0);
}
void HTMLBodyElementImp::setOnbeforeprint(html::Function onbeforeprint)
{
// TODO: implement me!
}
html::Function HTMLBodyElementImp::getOnbeforeunload()
{
// TODO: implement me!
return static_cast<Object*>(0);
}
void HTMLBodyElementImp::setOnbeforeunload(html::Function onbeforeunload)
{
// TODO: implement me!
}
html::Function HTMLBodyElementImp::getOnblur()
{
// TODO: implement me!
return static_cast<Object*>(0);
}
void HTMLBodyElementImp::setOnblur(html::Function onblur)
{
// TODO: implement me!
}
html::Function HTMLBodyElementImp::getOnerror()
{
// TODO: implement me!
return static_cast<Object*>(0);
}
void HTMLBodyElementImp::setOnerror(html::Function onerror)
{
// TODO: implement me!
}
html::Function HTMLBodyElementImp::getOnfocus()
{
// TODO: implement me!
return static_cast<Object*>(0);
}
void HTMLBodyElementImp::setOnfocus(html::Function onfocus)
{
// TODO: implement me!
}
html::Function HTMLBodyElementImp::getOnhashchange()
{
// TODO: implement me!
return static_cast<Object*>(0);
}
void HTMLBodyElementImp::setOnhashchange(html::Function onhashchange)
{
// TODO: implement me!
}
html::Function HTMLBodyElementImp::getOnload()
{
// TODO: implement me!
return static_cast<Object*>(0);
}
void HTMLBodyElementImp::setOnload(html::Function onload)
{
getOwnerDocument().getDefaultView().setOnload(onload);
}
html::Function HTMLBodyElementImp::getOnmessage()
{
// TODO: implement me!
return static_cast<Object*>(0);
}
void HTMLBodyElementImp::setOnmessage(html::Function onmessage)
{
// TODO: implement me!
}
html::Function HTMLBodyElementImp::getOnoffline()
{
// TODO: implement me!
return static_cast<Object*>(0);
}
void HTMLBodyElementImp::setOnoffline(html::Function onoffline)
{
// TODO: implement me!
}
html::Function HTMLBodyElementImp::getOnonline()
{
// TODO: implement me!
return static_cast<Object*>(0);
}
void HTMLBodyElementImp::setOnonline(html::Function ononline)
{
// TODO: implement me!
}
html::Function HTMLBodyElementImp::getOnpopstate()
{
// TODO: implement me!
return static_cast<Object*>(0);
}
void HTMLBodyElementImp::setOnpopstate(html::Function onpopstate)
{
// TODO: implement me!
}
html::Function HTMLBodyElementImp::getOnpagehide()
{
// TODO: implement me!
return static_cast<Object*>(0);
}
void HTMLBodyElementImp::setOnpagehide(html::Function onpagehide)
{
// TODO: implement me!
}
html::Function HTMLBodyElementImp::getOnpageshow()
{
// TODO: implement me!
return static_cast<Object*>(0);
}
void HTMLBodyElementImp::setOnpageshow(html::Function onpageshow)
{
// TODO: implement me!
}
html::Function HTMLBodyElementImp::getOnredo()
{
// TODO: implement me!
return static_cast<Object*>(0);
}
void HTMLBodyElementImp::setOnredo(html::Function onredo)
{
// TODO: implement me!
}
html::Function HTMLBodyElementImp::getOnresize()
{
// TODO: implement me!
return static_cast<Object*>(0);
}
void HTMLBodyElementImp::setOnresize(html::Function onresize)
{
// TODO: implement me!
}
html::Function HTMLBodyElementImp::getOnstorage()
{
// TODO: implement me!
return static_cast<Object*>(0);
}
void HTMLBodyElementImp::setOnstorage(html::Function onstorage)
{
// TODO: implement me!
}
html::Function HTMLBodyElementImp::getOnundo()
{
// TODO: implement me!
return static_cast<Object*>(0);
}
void HTMLBodyElementImp::setOnundo(html::Function onundo)
{
// TODO: implement me!
}
html::Function HTMLBodyElementImp::getOnunload()
{
// TODO: implement me!
return static_cast<Object*>(0);
}
void HTMLBodyElementImp::setOnunload(html::Function onunload)
{
// TODO: implement me!
}
std::u16string HTMLBodyElementImp::getText()
{
// TODO: implement me!
return u"";
}
void HTMLBodyElementImp::setText(std::u16string text)
{
// TODO: implement me!
}
std::u16string HTMLBodyElementImp::getBgColor()
{
// TODO: implement me!
return u"";
}
void HTMLBodyElementImp::setBgColor(std::u16string bgColor)
{
// TODO: implement me!
}
std::u16string HTMLBodyElementImp::getBackground()
{
// TODO: implement me!
return u"";
}
void HTMLBodyElementImp::setBackground(std::u16string background)
{
// TODO: implement me!
}
std::u16string HTMLBodyElementImp::getLink()
{
// TODO: implement me!
return u"";
}
void HTMLBodyElementImp::setLink(std::u16string link)
{
// TODO: implement me!
}
std::u16string HTMLBodyElementImp::getVLink()
{
// TODO: implement me!
return u"";
}
void HTMLBodyElementImp::setVLink(std::u16string vLink)
{
// TODO: implement me!
}
std::u16string HTMLBodyElementImp::getALink()
{
// TODO: implement me!
return u"";
}
void HTMLBodyElementImp::setALink(std::u16string aLink)
{
// TODO: implement me!
}
}}}} // org::w3c::dom::bootstrap
<commit_msg>(HTMLBodyElementImp::eval) : Evaluate text attribute.<commit_after>/*
* Copyright 2010-2012 Esrille 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 "HTMLBodyElementImp.h"
#include <org/w3c/dom/html/Window.h>
namespace org { namespace w3c { namespace dom { namespace bootstrap {
void HTMLBodyElementImp::eval()
{
HTMLElementImp::eval();
HTMLElementImp::evalBackground(this);
HTMLElementImp::evalBgcolor(this);
HTMLElementImp::evalColor(this, u"text", u"color");
}
// Node
Node HTMLBodyElementImp::cloneNode(bool deep)
{
return new(std::nothrow) HTMLBodyElementImp(this, deep);
}
// HTMLBodyElement
html::Function HTMLBodyElementImp::getOnafterprint()
{
// TODO: implement me!
return static_cast<Object*>(0);
}
void HTMLBodyElementImp::setOnafterprint(html::Function onafterprint)
{
// TODO: implement me!
}
html::Function HTMLBodyElementImp::getOnbeforeprint()
{
// TODO: implement me!
return static_cast<Object*>(0);
}
void HTMLBodyElementImp::setOnbeforeprint(html::Function onbeforeprint)
{
// TODO: implement me!
}
html::Function HTMLBodyElementImp::getOnbeforeunload()
{
// TODO: implement me!
return static_cast<Object*>(0);
}
void HTMLBodyElementImp::setOnbeforeunload(html::Function onbeforeunload)
{
// TODO: implement me!
}
html::Function HTMLBodyElementImp::getOnblur()
{
// TODO: implement me!
return static_cast<Object*>(0);
}
void HTMLBodyElementImp::setOnblur(html::Function onblur)
{
// TODO: implement me!
}
html::Function HTMLBodyElementImp::getOnerror()
{
// TODO: implement me!
return static_cast<Object*>(0);
}
void HTMLBodyElementImp::setOnerror(html::Function onerror)
{
// TODO: implement me!
}
html::Function HTMLBodyElementImp::getOnfocus()
{
// TODO: implement me!
return static_cast<Object*>(0);
}
void HTMLBodyElementImp::setOnfocus(html::Function onfocus)
{
// TODO: implement me!
}
html::Function HTMLBodyElementImp::getOnhashchange()
{
// TODO: implement me!
return static_cast<Object*>(0);
}
void HTMLBodyElementImp::setOnhashchange(html::Function onhashchange)
{
// TODO: implement me!
}
html::Function HTMLBodyElementImp::getOnload()
{
// TODO: implement me!
return static_cast<Object*>(0);
}
void HTMLBodyElementImp::setOnload(html::Function onload)
{
getOwnerDocument().getDefaultView().setOnload(onload);
}
html::Function HTMLBodyElementImp::getOnmessage()
{
// TODO: implement me!
return static_cast<Object*>(0);
}
void HTMLBodyElementImp::setOnmessage(html::Function onmessage)
{
// TODO: implement me!
}
html::Function HTMLBodyElementImp::getOnoffline()
{
// TODO: implement me!
return static_cast<Object*>(0);
}
void HTMLBodyElementImp::setOnoffline(html::Function onoffline)
{
// TODO: implement me!
}
html::Function HTMLBodyElementImp::getOnonline()
{
// TODO: implement me!
return static_cast<Object*>(0);
}
void HTMLBodyElementImp::setOnonline(html::Function ononline)
{
// TODO: implement me!
}
html::Function HTMLBodyElementImp::getOnpopstate()
{
// TODO: implement me!
return static_cast<Object*>(0);
}
void HTMLBodyElementImp::setOnpopstate(html::Function onpopstate)
{
// TODO: implement me!
}
html::Function HTMLBodyElementImp::getOnpagehide()
{
// TODO: implement me!
return static_cast<Object*>(0);
}
void HTMLBodyElementImp::setOnpagehide(html::Function onpagehide)
{
// TODO: implement me!
}
html::Function HTMLBodyElementImp::getOnpageshow()
{
// TODO: implement me!
return static_cast<Object*>(0);
}
void HTMLBodyElementImp::setOnpageshow(html::Function onpageshow)
{
// TODO: implement me!
}
html::Function HTMLBodyElementImp::getOnredo()
{
// TODO: implement me!
return static_cast<Object*>(0);
}
void HTMLBodyElementImp::setOnredo(html::Function onredo)
{
// TODO: implement me!
}
html::Function HTMLBodyElementImp::getOnresize()
{
// TODO: implement me!
return static_cast<Object*>(0);
}
void HTMLBodyElementImp::setOnresize(html::Function onresize)
{
// TODO: implement me!
}
html::Function HTMLBodyElementImp::getOnstorage()
{
// TODO: implement me!
return static_cast<Object*>(0);
}
void HTMLBodyElementImp::setOnstorage(html::Function onstorage)
{
// TODO: implement me!
}
html::Function HTMLBodyElementImp::getOnundo()
{
// TODO: implement me!
return static_cast<Object*>(0);
}
void HTMLBodyElementImp::setOnundo(html::Function onundo)
{
// TODO: implement me!
}
html::Function HTMLBodyElementImp::getOnunload()
{
// TODO: implement me!
return static_cast<Object*>(0);
}
void HTMLBodyElementImp::setOnunload(html::Function onunload)
{
// TODO: implement me!
}
std::u16string HTMLBodyElementImp::getText()
{
// TODO: implement me!
return u"";
}
void HTMLBodyElementImp::setText(std::u16string text)
{
// TODO: implement me!
}
std::u16string HTMLBodyElementImp::getBgColor()
{
// TODO: implement me!
return u"";
}
void HTMLBodyElementImp::setBgColor(std::u16string bgColor)
{
// TODO: implement me!
}
std::u16string HTMLBodyElementImp::getBackground()
{
// TODO: implement me!
return u"";
}
void HTMLBodyElementImp::setBackground(std::u16string background)
{
// TODO: implement me!
}
std::u16string HTMLBodyElementImp::getLink()
{
// TODO: implement me!
return u"";
}
void HTMLBodyElementImp::setLink(std::u16string link)
{
// TODO: implement me!
}
std::u16string HTMLBodyElementImp::getVLink()
{
// TODO: implement me!
return u"";
}
void HTMLBodyElementImp::setVLink(std::u16string vLink)
{
// TODO: implement me!
}
std::u16string HTMLBodyElementImp::getALink()
{
// TODO: implement me!
return u"";
}
void HTMLBodyElementImp::setALink(std::u16string aLink)
{
// TODO: implement me!
}
}}}} // org::w3c::dom::bootstrap
<|endoftext|> |
<commit_before>// Copyright (c) 2014-2017 The Helium Core developers
// Distributed under the MIT software license, see the accompanying
// file COPYING or http://www.opensource.org/licenses/mit-license.php.
#include "dsnotificationinterface.h"
#include "darksend.h"
#include "instantx.h"
#include "governance.h"
#include "masternodeman.h"
#include "masternode-payments.h"
#include "masternode-sync.h"
CDSNotificationInterface::CDSNotificationInterface()
{
}
CDSNotificationInterface::~CDSNotificationInterface()
{
}
void CDSNotificationInterface::UpdatedBlockTip(const CBlockIndex *pindex)
{
mnodeman.UpdatedBlockTip(pindex);
darkSendPool.UpdatedBlockTip(pindex);
instantsend.UpdatedBlockTip(pindex);
mnpayments.UpdatedBlockTip(pindex);
governance.UpdatedBlockTip(pindex);
masternodeSync.UpdatedBlockTip(pindex);
}
void CDSNotificationInterface::SyncTransaction(const CTransaction &tx, const CBlock *pblock)
{
instantsend.SyncTransaction(tx, pblock);
}<commit_msg>Update dsnotificationinterface.cpp<commit_after>// Copyright (c) 2014-2017 The Helium Core developers
// Copyright (c) 2014-2017 The DASH Core developers
// Distributed under the MIT software license, see the accompanying
// file COPYING or http://www.opensource.org/licenses/mit-license.php.
#include "dsnotificationinterface.h"
#include "darksend.h"
#include "instantx.h"
#include "governance.h"
#include "masternodeman.h"
#include "masternode-payments.h"
#include "masternode-sync.h"
CDSNotificationInterface::CDSNotificationInterface()
{
}
CDSNotificationInterface::~CDSNotificationInterface()
{
}
void CDSNotificationInterface::UpdatedBlockTip(const CBlockIndex *pindex)
{
mnodeman.UpdatedBlockTip(pindex);
darkSendPool.UpdatedBlockTip(pindex);
instantsend.UpdatedBlockTip(pindex);
mnpayments.UpdatedBlockTip(pindex);
governance.UpdatedBlockTip(pindex);
masternodeSync.UpdatedBlockTip(pindex);
}
void CDSNotificationInterface::SyncTransaction(const CTransaction &tx, const CBlock *pblock)
{
instantsend.SyncTransaction(tx, pblock);
}
<|endoftext|> |
<commit_before>/* This file is part of the Kate project.
*
* Copyright (C) 2010 Dominik Haumann <dhaumann kde org>
* Copyright (C) 2010 Diana-Victoria Tiriplica <[email protected]>
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Library General Public
* License as published by the Free Software Foundation; either
* version 2 of the License, or (at your option) any later version.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Library General Public License for more details.
*
* You should have received a copy of the GNU Library General Public License
* along with this library; see the file COPYING.LIB. If not, write to
* the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
* Boston, MA 02110-1301, USA.
*/
#include "kateswapfile.h"
#include "kateview.h"
#include <kde_file.h>
#include <QFileInfo>
#include <QDir>
namespace Kate {
const static qint8 EA_StartEditing = 'S';
const static qint8 EA_FinishEditing = 'E';
const static qint8 EA_WrapLine = 'W';
const static qint8 EA_UnwrapLine = 'U';
const static qint8 EA_InsertText = 'I';
const static qint8 EA_RemoveText = 'R';
SwapFile::SwapFile(KateDocument *document)
: QObject(document)
, m_document(document)
, m_trackingEnabled(false)
{
// fixed version of serialisation
m_stream.setVersion (QDataStream::Qt_4_6);
// connecting the signals
connect(&m_document->buffer(), SIGNAL(saved(const QString &)), this, SLOT(fileSaved(const QString&)));
connect(&m_document->buffer(), SIGNAL(loaded(const QString &, bool)), this, SLOT(fileLoaded(const QString&)));
setTrackingEnabled(true);
}
SwapFile::~SwapFile()
{
removeSwapFile();
}
void SwapFile::setTrackingEnabled(bool enable)
{
if (m_trackingEnabled == enable) {
return;
}
m_trackingEnabled = enable;
TextBuffer &buffer = m_document->buffer();
if (m_trackingEnabled) {
connect(&buffer, SIGNAL(editingStarted()), this, SLOT(startEditing()));
connect(&buffer, SIGNAL(editingFinished()), this, SLOT(finishEditing()));
connect(&buffer, SIGNAL(lineWrapped(const KTextEditor::Cursor&)), this, SLOT(wrapLine(const KTextEditor::Cursor&)));
connect(&buffer, SIGNAL(lineUnwrapped(int)), this, SLOT(unwrapLine(int)));
connect(&buffer, SIGNAL(textInserted(const KTextEditor::Cursor &, const QString &)), this, SLOT(insertText(const KTextEditor::Cursor &, const QString &)));
connect(&buffer, SIGNAL(textRemoved(const KTextEditor::Range &, const QString &)), this, SLOT(removeText(const KTextEditor::Range &)));
} else {
disconnect(&buffer, SIGNAL(editingStarted()), this, SLOT(startEditing()));
disconnect(&buffer, SIGNAL(editingFinished()), this, SLOT(finishEditing()));
disconnect(&buffer, SIGNAL(lineWrapped(const KTextEditor::Cursor&)), this, SLOT(wrapLine(const KTextEditor::Cursor&)));
disconnect(&buffer, SIGNAL(lineUnwrapped(int)), this, SLOT(unwrapLine(int)));
disconnect(&buffer, SIGNAL(textInserted(const KTextEditor::Cursor &, const QString &)), this, SLOT(insertText(const KTextEditor::Cursor &, const QString &)));
disconnect(&buffer, SIGNAL(textRemoved(const KTextEditor::Range &, const QString &)), this, SLOT(removeText(const KTextEditor::Range &)));
}
}
void SwapFile::fileLoaded(const QString&)
{
// look for swap file
if (!updateFileName())
return;
if (!m_swapfile.exists())
{
kDebug (13020) << "No swap file";
return;
}
if (!QFileInfo(m_swapfile).isReadable())
{
kWarning( 13020 ) << "Can't open swap file (missing permissions)";
return;
}
// emit signal in case the document has more views
emit swapFileFound();
// TODO set file as read-only
}
void SwapFile::recover()
{
// disconnect current signals
setTrackingEnabled(false);
// replay the swap file
if (!m_swapfile.open(QIODevice::ReadOnly))
{
kWarning( 13020 ) << "Can't open swap file";
return;
}
// open data stream
m_stream.setDevice(&m_swapfile);
// read and check header
QString header;
m_stream >> header;
if (header != QString ("Kate Swap File Version 1.0"))
{
m_stream.setDevice (0);
m_swapfile.close ();
kWarning( 13020 ) << "Can't open swap file, wrong version";
return;
}
// replay swapfile
bool editStarted = false;
while (!m_stream.atEnd()) {
qint8 type;
m_stream >> type;
switch (type) {
case EA_StartEditing: {
m_document->editStart();
editStarted = true;
break;
}
case EA_FinishEditing: {
m_document->editEnd();
editStarted = false;
break;
}
case EA_WrapLine: {
int line = 0, column = 0;
m_stream >> line >> column;
// emulate buffer unwrapLine with document
m_document->editWrapLine(line, column, true);
break;
}
case EA_UnwrapLine: {
int line = 0;
m_stream >> line;
// assert valid line
Q_ASSERT (line > 0);
// emulate buffer unwrapLine with document
m_document->editUnWrapLine(line - 1, true, 0);
break;
}
case EA_InsertText: {
int line, column;
QString text;
m_stream >> line >> column >> text;
m_document->insertText(KTextEditor::Cursor(line, column), text);
break;
}
case EA_RemoveText: {
int line, startColumn, endColumn;
m_stream >> line >> startColumn >> endColumn;
m_document->removeText (KTextEditor::Range(KTextEditor::Cursor(line, startColumn), KTextEditor::Cursor(line, endColumn)));
}
default: {
kWarning( 13020 ) << "Unknown type:" << type;
}
}
}
// balance editStart and editEnd
if (editStarted) {
kWarning ( 13020 ) << "Some data might be lost";
m_document->editEnd();
}
// close swap file
m_stream.setDevice(0);
m_swapfile.close();
// reconnect the signals
setTrackingEnabled(true);
// emit signal in case the document has more views
emit swapFileHandled();
}
void SwapFile::fileSaved(const QString&)
{
// remove old swap file (e.g. if a file A was "saved as" B)
removeSwapFile();
// set the name for the new swap file
if (!updateFileName())
return;
}
void SwapFile::startEditing ()
{
// if swap file doesn't exists, open it in WriteOnly mode
// if it does, append the data to the existing swap file,
// in case you recover and start edititng again
if (!m_swapfile.exists()) {
m_swapfile.open(QIODevice::WriteOnly);
m_stream.setDevice(&m_swapfile);
// write file header
m_stream << QString ("Kate Swap File Version 1.0");
} else if (m_stream.device() == 0) {
m_swapfile.open(QIODevice::Append);
m_stream.setDevice(&m_swapfile);
}
// format: qint8
m_stream << EA_StartEditing;
}
void SwapFile::finishEditing ()
{
// format: qint8
m_stream << EA_FinishEditing;
m_swapfile.flush();
#ifndef Q_OS_WIN
// ensure that the file is written to disk
fdatasync (m_swapfile.handle());
#endif
}
void SwapFile::wrapLine (const KTextEditor::Cursor &position)
{
// format: qint8, int, int
m_stream << EA_WrapLine << position.line() << position.column();
}
void SwapFile::unwrapLine (int line)
{
// format: qint8, int
m_stream << EA_UnwrapLine << line;
}
void SwapFile::insertText (const KTextEditor::Cursor &position, const QString &text)
{
// format: qint8, int, int, string
m_stream << EA_InsertText << position.line() << position.column() << text;
}
void SwapFile::removeText (const KTextEditor::Range &range)
{
// format: qint8, int, int, int
Q_ASSERT (range.start().line() == range.end().line());
m_stream << EA_RemoveText
<< range.start().line() << range.start().column()
<< range.end().column();
}
bool SwapFile::shouldRecover() const
{
return m_swapfile.exists() && m_stream.device() == 0;
}
void SwapFile::discard()
{
removeSwapFile();
emit swapFileHandled();
}
void SwapFile::removeSwapFile()
{
if (m_swapfile.exists()) {
m_stream.setDevice(0);
m_swapfile.close();
m_swapfile.remove();
}
}
bool SwapFile::updateFileName()
{
KUrl url = m_document->url();
if (!url.isLocalFile())
return false;
QString path = url.toLocalFile();
int poz = path.lastIndexOf(QDir::separator());
path.insert(poz+1, ".swp.");
m_swapfile.setFileName(path);
return true;
}
}
// kate: space-indent on; indent-width 2; replace-tabs on;
<commit_msg>plain text swap file header + utf8 encoded text<commit_after>/* This file is part of the Kate project.
*
* Copyright (C) 2010 Dominik Haumann <dhaumann kde org>
* Copyright (C) 2010 Diana-Victoria Tiriplica <[email protected]>
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Library General Public
* License as published by the Free Software Foundation; either
* version 2 of the License, or (at your option) any later version.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Library General Public License for more details.
*
* You should have received a copy of the GNU Library General Public License
* along with this library; see the file COPYING.LIB. If not, write to
* the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
* Boston, MA 02110-1301, USA.
*/
#include "kateswapfile.h"
#include "kateview.h"
#include <kde_file.h>
#include <QFileInfo>
#include <QDir>
// swap file version header
const static char * const swapFileVersionString = "Kate Swap File - Version 1.0";
// tokens for swap files
const static qint8 EA_StartEditing = 'S';
const static qint8 EA_FinishEditing = 'E';
const static qint8 EA_WrapLine = 'W';
const static qint8 EA_UnwrapLine = 'U';
const static qint8 EA_InsertText = 'I';
const static qint8 EA_RemoveText = 'R';
namespace Kate {
SwapFile::SwapFile(KateDocument *document)
: QObject(document)
, m_document(document)
, m_trackingEnabled(false)
{
// fixed version of serialisation
m_stream.setVersion (QDataStream::Qt_4_6);
// connecting the signals
connect(&m_document->buffer(), SIGNAL(saved(const QString &)), this, SLOT(fileSaved(const QString&)));
connect(&m_document->buffer(), SIGNAL(loaded(const QString &, bool)), this, SLOT(fileLoaded(const QString&)));
setTrackingEnabled(true);
}
SwapFile::~SwapFile()
{
removeSwapFile();
}
void SwapFile::setTrackingEnabled(bool enable)
{
if (m_trackingEnabled == enable) {
return;
}
m_trackingEnabled = enable;
TextBuffer &buffer = m_document->buffer();
if (m_trackingEnabled) {
connect(&buffer, SIGNAL(editingStarted()), this, SLOT(startEditing()));
connect(&buffer, SIGNAL(editingFinished()), this, SLOT(finishEditing()));
connect(&buffer, SIGNAL(lineWrapped(const KTextEditor::Cursor&)), this, SLOT(wrapLine(const KTextEditor::Cursor&)));
connect(&buffer, SIGNAL(lineUnwrapped(int)), this, SLOT(unwrapLine(int)));
connect(&buffer, SIGNAL(textInserted(const KTextEditor::Cursor &, const QString &)), this, SLOT(insertText(const KTextEditor::Cursor &, const QString &)));
connect(&buffer, SIGNAL(textRemoved(const KTextEditor::Range &, const QString &)), this, SLOT(removeText(const KTextEditor::Range &)));
} else {
disconnect(&buffer, SIGNAL(editingStarted()), this, SLOT(startEditing()));
disconnect(&buffer, SIGNAL(editingFinished()), this, SLOT(finishEditing()));
disconnect(&buffer, SIGNAL(lineWrapped(const KTextEditor::Cursor&)), this, SLOT(wrapLine(const KTextEditor::Cursor&)));
disconnect(&buffer, SIGNAL(lineUnwrapped(int)), this, SLOT(unwrapLine(int)));
disconnect(&buffer, SIGNAL(textInserted(const KTextEditor::Cursor &, const QString &)), this, SLOT(insertText(const KTextEditor::Cursor &, const QString &)));
disconnect(&buffer, SIGNAL(textRemoved(const KTextEditor::Range &, const QString &)), this, SLOT(removeText(const KTextEditor::Range &)));
}
}
void SwapFile::fileLoaded(const QString&)
{
// look for swap file
if (!updateFileName())
return;
if (!m_swapfile.exists())
{
kDebug (13020) << "No swap file";
return;
}
if (!QFileInfo(m_swapfile).isReadable())
{
kWarning( 13020 ) << "Can't open swap file (missing permissions)";
return;
}
// emit signal in case the document has more views
emit swapFileFound();
// TODO set file as read-only
}
void SwapFile::recover()
{
// disconnect current signals
setTrackingEnabled(false);
// replay the swap file
if (!m_swapfile.open(QIODevice::ReadOnly))
{
kWarning( 13020 ) << "Can't open swap file";
return;
}
// open data stream
m_stream.setDevice(&m_swapfile);
// read and check header
QByteArray header;
m_stream >> header;
if (header != swapFileVersionString)
{
m_stream.setDevice (0);
m_swapfile.close ();
kWarning( 13020 ) << "Can't open swap file, wrong version";
return;
}
// replay swapfile
bool editStarted = false;
while (!m_stream.atEnd()) {
qint8 type;
m_stream >> type;
switch (type) {
case EA_StartEditing: {
m_document->editStart();
editStarted = true;
break;
}
case EA_FinishEditing: {
m_document->editEnd();
editStarted = false;
break;
}
case EA_WrapLine: {
int line = 0, column = 0;
m_stream >> line >> column;
// emulate buffer unwrapLine with document
m_document->editWrapLine(line, column, true);
break;
}
case EA_UnwrapLine: {
int line = 0;
m_stream >> line;
// assert valid line
Q_ASSERT (line > 0);
// emulate buffer unwrapLine with document
m_document->editUnWrapLine(line - 1, true, 0);
break;
}
case EA_InsertText: {
int line, column;
QByteArray text;
m_stream >> line >> column >> text;
m_document->insertText(KTextEditor::Cursor(line, column), QString::fromUtf8 (text.data (), text.size()));
break;
}
case EA_RemoveText: {
int line, startColumn, endColumn;
m_stream >> line >> startColumn >> endColumn;
m_document->removeText (KTextEditor::Range(KTextEditor::Cursor(line, startColumn), KTextEditor::Cursor(line, endColumn)));
}
default: {
kWarning( 13020 ) << "Unknown type:" << type;
}
}
}
// balance editStart and editEnd
if (editStarted) {
kWarning ( 13020 ) << "Some data might be lost";
m_document->editEnd();
}
// close swap file
m_stream.setDevice(0);
m_swapfile.close();
// reconnect the signals
setTrackingEnabled(true);
// emit signal in case the document has more views
emit swapFileHandled();
}
void SwapFile::fileSaved(const QString&)
{
// remove old swap file (e.g. if a file A was "saved as" B)
removeSwapFile();
// set the name for the new swap file
if (!updateFileName())
return;
}
void SwapFile::startEditing ()
{
// if swap file doesn't exists, open it in WriteOnly mode
// if it does, append the data to the existing swap file,
// in case you recover and start edititng again
if (!m_swapfile.exists()) {
m_swapfile.open(QIODevice::WriteOnly);
m_stream.setDevice(&m_swapfile);
// write file header
m_stream << QByteArray (swapFileVersionString);
} else if (m_stream.device() == 0) {
m_swapfile.open(QIODevice::Append);
m_stream.setDevice(&m_swapfile);
}
// format: qint8
m_stream << EA_StartEditing;
}
void SwapFile::finishEditing ()
{
// format: qint8
m_stream << EA_FinishEditing;
m_swapfile.flush();
#ifndef Q_OS_WIN
// ensure that the file is written to disk
fdatasync (m_swapfile.handle());
#endif
}
void SwapFile::wrapLine (const KTextEditor::Cursor &position)
{
// format: qint8, int, int
m_stream << EA_WrapLine << position.line() << position.column();
}
void SwapFile::unwrapLine (int line)
{
// format: qint8, int
m_stream << EA_UnwrapLine << line;
}
void SwapFile::insertText (const KTextEditor::Cursor &position, const QString &text)
{
// format: qint8, int, int, bytearray
m_stream << EA_InsertText << position.line() << position.column() << text.toUtf8 ();
}
void SwapFile::removeText (const KTextEditor::Range &range)
{
// format: qint8, int, int, int
Q_ASSERT (range.start().line() == range.end().line());
m_stream << EA_RemoveText
<< range.start().line() << range.start().column()
<< range.end().column();
}
bool SwapFile::shouldRecover() const
{
return m_swapfile.exists() && m_stream.device() == 0;
}
void SwapFile::discard()
{
removeSwapFile();
emit swapFileHandled();
}
void SwapFile::removeSwapFile()
{
if (m_swapfile.exists()) {
m_stream.setDevice(0);
m_swapfile.close();
m_swapfile.remove();
}
}
bool SwapFile::updateFileName()
{
KUrl url = m_document->url();
if (!url.isLocalFile())
return false;
QString path = url.toLocalFile();
int poz = path.lastIndexOf(QDir::separator());
path.insert(poz+1, ".swp.");
m_swapfile.setFileName(path);
return true;
}
}
// kate: space-indent on; indent-width 2; replace-tabs on;
<|endoftext|> |
<commit_before>#include "dom.hpp"
#include <vector>
#include <ting/debug.hpp>
#include <ting/Array.hpp>
#include "parser.hpp"
using namespace stob;
namespace{
ting::MemoryPool<sizeof(Node), 4096 / sizeof(Node)> memoryPool;
}
void* Node::operator new(size_t size){
ASSERT(size == sizeof(Node))
return memoryPool.Alloc_ts();
}
void Node::operator delete(void* p)throw(){
memoryPool.Free_ts(p);
}
std::pair<Node*, Node*> Node::Next(const std::string& value)throw(){
Node* prev = this;
for(Node* n = this->Next(); n; prev = n, n = n->Next()){
if(n->Value() == value){
return std::pair<Node*, Node*>(prev, n);
}
}
return std::pair<Node*, Node*>(prev, 0);
}
std::pair<Node*, Node*> Node::Child(const std::string& value)throw(){
if(this->children.IsNotValid()){
return std::pair<Node*, Node*>(0, 0);
}
if(this->children->Value() == value){
return std::pair<Node*, Node*>(0, this->children.operator->());
}
return this->children->Next(value);
}
Node* Node::AddProperty(const std::string& propName){
ting::Ptr<Node> p = Node::New();
p->SetValue(propName);
p->SetNext(this->RemoveChildren());
this->SetChildren(p);
this->Child()->SetChildren(Node::New());
return this->Child()->Child();
}
namespace{
bool CanStringBeUnquoted(const std::string& s, unsigned& numEscapes){
// TRACE(<< "CanStringBeUnquoted(): enter" << std::endl)
numEscapes = 0;
if(s.size() == 0){//empty string is always quoted
return false;
}
bool ret = true;
for(const char* c = s.c_str(); *c != 0; ++c){
// TRACE(<< "CanStringBeUnquoted(): c = " << (*c) << std::endl)
switch(*c){
case '\t':
case '\n':
case '\r':
case '"':
++numEscapes;
case '{':
case '}':
case ' ':
ret = false;
break;
default:
break;
}
}
return ret;
}
void MakeEscapedString(const std::string& str, ting::Buffer<ting::u8>& out){
ting::u8 *p = out.Begin();
for(const char* c = str.c_str(); *c != 0; ++c){
ASSERT(p != out.End())
switch(*c){
case '\t':
*p = '\\';
++p;
ASSERT(p != out.End())
*p = 't';
break;
case '\n':
*p = '\\';
++p;
ASSERT(p != out.End())
*p = 'n';
break;
case '\r':
*p = '\\';
++p;
ASSERT(p != out.End())
*p = 'r';
break;
case '"':
*p = '\\';
++p;
ASSERT(p != out.End())
*p = '"';
break;
default:
*p = *c;
break;
}
++p;
}
}
void WriteNode(const stob::Node* node, ting::fs::File& fi, bool formatted, unsigned indentation){
ASSERT(node)
ting::StaticBuffer<ting::u8, 1> quote;
quote[0] = '"';
ting::StaticBuffer<ting::u8, 1> lcurly;
lcurly[0] = '{';
ting::StaticBuffer<ting::u8, 1> rcurly;
rcurly[0] = '}';
ting::StaticBuffer<ting::u8, 1> space;
space[0] = ' ';
ting::StaticBuffer<ting::u8, 1> tab;
tab[0] = '\t';
ting::StaticBuffer<ting::u8, 1> newLine;
newLine[0] = '\n';
//used to detect case of two adjacent unquoted strings without children, need to insert space between them
bool prevWasUnquotedWithoutChildren = false;
for(const Node* n = node->Child(); n; n = n->Next()){
//indent
if(formatted){
for(unsigned i = 0; i != indentation; ++i){
fi.Write(tab);
}
}
//write node value
unsigned numEscapes;
bool unqouted = CanStringBeUnquoted(n->Value(), numEscapes);
if(!unqouted){
fi.Write(quote);
if(numEscapes == 0){
fi.Write(ting::Buffer<ting::u8>(
const_cast<ting::u8*>(reinterpret_cast<const ting::u8*>(n->Value().c_str())),
n->Value().size()
));
}else{
ting::Array<ting::u8> buf(n->Value().size() + numEscapes);
MakeEscapedString(n->Value(), buf);
fi.Write(buf);
}
fi.Write(quote);
}else{
//unquoted string
if(!formatted && prevWasUnquotedWithoutChildren){
fi.Write(space);
}
ASSERT(numEscapes == 0)
fi.Write(ting::Buffer<ting::u8>(
const_cast<ting::u8*>(reinterpret_cast<const ting::u8*>(n->Value().c_str())),
n->Value().size()
));
}
if(n->Child() == 0){
if(formatted){
fi.Write(newLine);
}
prevWasUnquotedWithoutChildren = unqouted;
continue;
}else{
prevWasUnquotedWithoutChildren = false;
}
if(!formatted){
fi.Write(lcurly);
WriteNode(n, fi, false, 0);
fi.Write(rcurly);
}else{
if(n->Child()->Next() == 0 && n->Child()->Child() == 0){
//if only one child and that child has no children
fi.Write(space);
fi.Write(lcurly);
WriteNode(n, fi, false, 0);
fi.Write(rcurly);
fi.Write(newLine);
}else{
fi.Write(lcurly);
fi.Write(newLine);
WriteNode(n, fi, true, indentation + 1);
//indent
for(unsigned i = 0; i != indentation; ++i){
fi.Write(tab);
}
fi.Write(rcurly);
fi.Write(newLine);
}
}
}//~for()
}
}//~namespace
void Node::Write(ting::fs::File& fi, bool formatted){
ting::fs::File::Guard fileGuard(fi, ting::fs::File::CREATE);
WriteNode(this, fi, formatted, 0);
}
ting::Ptr<stob::Node> stob::Load(ting::fs::File& fi){
class Listener : public stob::ParseListener{
typedef std::pair<ting::Ptr<Node>, Node*> T_Pair;
std::vector<T_Pair> stack;
public:
//override
void OnChildrenParseFinished(){
this->stack.back().second->SetChildren(this->chain);
this->chain = this->stack.back().first;
this->lastInChain = this->stack.back().second;
this->stack.pop_back();
}
//override
void OnChildrenParseStarted(){
this->stack.push_back(
T_Pair(this->chain, this->lastInChain)
);
}
//override
void OnStringParsed(const char* s, ting::u32 size){
ting::Ptr<Node> node = Node::New();
node->SetValue(std::string(s, size));
if(this->chain.IsNotValid()){
this->chain = node;
this->lastInChain = this->chain.operator->();
}else{
this->lastInChain->InsertNext(node);
this->lastInChain = this->lastInChain->Next();
}
}
ting::Ptr<Node> chain;
Node* lastInChain;
Listener() :
chain(Node::New()),//create root node
lastInChain(this->chain.operator->())
{}
~Listener()throw(){}
} listener;
listener.OnChildrenParseStarted();
stob::Parse(fi, listener);
listener.OnChildrenParseFinished();
return listener.chain;
}
<commit_msg>100 elements per chunk<commit_after>#include "dom.hpp"
#include <vector>
#include <ting/debug.hpp>
#include <ting/Array.hpp>
#include "parser.hpp"
using namespace stob;
namespace{
ting::MemoryPool<sizeof(Node), 100> memoryPool;
}
void* Node::operator new(size_t size){
ASSERT(size == sizeof(Node))
return memoryPool.Alloc_ts();
}
void Node::operator delete(void* p)throw(){
memoryPool.Free_ts(p);
}
std::pair<Node*, Node*> Node::Next(const std::string& value)throw(){
Node* prev = this;
for(Node* n = this->Next(); n; prev = n, n = n->Next()){
if(n->Value() == value){
return std::pair<Node*, Node*>(prev, n);
}
}
return std::pair<Node*, Node*>(prev, 0);
}
std::pair<Node*, Node*> Node::Child(const std::string& value)throw(){
if(this->children.IsNotValid()){
return std::pair<Node*, Node*>(0, 0);
}
if(this->children->Value() == value){
return std::pair<Node*, Node*>(0, this->children.operator->());
}
return this->children->Next(value);
}
Node* Node::AddProperty(const std::string& propName){
ting::Ptr<Node> p = Node::New();
p->SetValue(propName);
p->SetNext(this->RemoveChildren());
this->SetChildren(p);
this->Child()->SetChildren(Node::New());
return this->Child()->Child();
}
namespace{
bool CanStringBeUnquoted(const std::string& s, unsigned& numEscapes){
// TRACE(<< "CanStringBeUnquoted(): enter" << std::endl)
numEscapes = 0;
if(s.size() == 0){//empty string is always quoted
return false;
}
bool ret = true;
for(const char* c = s.c_str(); *c != 0; ++c){
// TRACE(<< "CanStringBeUnquoted(): c = " << (*c) << std::endl)
switch(*c){
case '\t':
case '\n':
case '\r':
case '"':
++numEscapes;
case '{':
case '}':
case ' ':
ret = false;
break;
default:
break;
}
}
return ret;
}
void MakeEscapedString(const std::string& str, ting::Buffer<ting::u8>& out){
ting::u8 *p = out.Begin();
for(const char* c = str.c_str(); *c != 0; ++c){
ASSERT(p != out.End())
switch(*c){
case '\t':
*p = '\\';
++p;
ASSERT(p != out.End())
*p = 't';
break;
case '\n':
*p = '\\';
++p;
ASSERT(p != out.End())
*p = 'n';
break;
case '\r':
*p = '\\';
++p;
ASSERT(p != out.End())
*p = 'r';
break;
case '"':
*p = '\\';
++p;
ASSERT(p != out.End())
*p = '"';
break;
default:
*p = *c;
break;
}
++p;
}
}
void WriteNode(const stob::Node* node, ting::fs::File& fi, bool formatted, unsigned indentation){
ASSERT(node)
ting::StaticBuffer<ting::u8, 1> quote;
quote[0] = '"';
ting::StaticBuffer<ting::u8, 1> lcurly;
lcurly[0] = '{';
ting::StaticBuffer<ting::u8, 1> rcurly;
rcurly[0] = '}';
ting::StaticBuffer<ting::u8, 1> space;
space[0] = ' ';
ting::StaticBuffer<ting::u8, 1> tab;
tab[0] = '\t';
ting::StaticBuffer<ting::u8, 1> newLine;
newLine[0] = '\n';
//used to detect case of two adjacent unquoted strings without children, need to insert space between them
bool prevWasUnquotedWithoutChildren = false;
for(const Node* n = node->Child(); n; n = n->Next()){
//indent
if(formatted){
for(unsigned i = 0; i != indentation; ++i){
fi.Write(tab);
}
}
//write node value
unsigned numEscapes;
bool unqouted = CanStringBeUnquoted(n->Value(), numEscapes);
if(!unqouted){
fi.Write(quote);
if(numEscapes == 0){
fi.Write(ting::Buffer<ting::u8>(
const_cast<ting::u8*>(reinterpret_cast<const ting::u8*>(n->Value().c_str())),
n->Value().size()
));
}else{
ting::Array<ting::u8> buf(n->Value().size() + numEscapes);
MakeEscapedString(n->Value(), buf);
fi.Write(buf);
}
fi.Write(quote);
}else{
//unquoted string
if(!formatted && prevWasUnquotedWithoutChildren){
fi.Write(space);
}
ASSERT(numEscapes == 0)
fi.Write(ting::Buffer<ting::u8>(
const_cast<ting::u8*>(reinterpret_cast<const ting::u8*>(n->Value().c_str())),
n->Value().size()
));
}
if(n->Child() == 0){
if(formatted){
fi.Write(newLine);
}
prevWasUnquotedWithoutChildren = unqouted;
continue;
}else{
prevWasUnquotedWithoutChildren = false;
}
if(!formatted){
fi.Write(lcurly);
WriteNode(n, fi, false, 0);
fi.Write(rcurly);
}else{
if(n->Child()->Next() == 0 && n->Child()->Child() == 0){
//if only one child and that child has no children
fi.Write(space);
fi.Write(lcurly);
WriteNode(n, fi, false, 0);
fi.Write(rcurly);
fi.Write(newLine);
}else{
fi.Write(lcurly);
fi.Write(newLine);
WriteNode(n, fi, true, indentation + 1);
//indent
for(unsigned i = 0; i != indentation; ++i){
fi.Write(tab);
}
fi.Write(rcurly);
fi.Write(newLine);
}
}
}//~for()
}
}//~namespace
void Node::Write(ting::fs::File& fi, bool formatted){
ting::fs::File::Guard fileGuard(fi, ting::fs::File::CREATE);
WriteNode(this, fi, formatted, 0);
}
ting::Ptr<stob::Node> stob::Load(ting::fs::File& fi){
class Listener : public stob::ParseListener{
typedef std::pair<ting::Ptr<Node>, Node*> T_Pair;
std::vector<T_Pair> stack;
public:
//override
void OnChildrenParseFinished(){
this->stack.back().second->SetChildren(this->chain);
this->chain = this->stack.back().first;
this->lastInChain = this->stack.back().second;
this->stack.pop_back();
}
//override
void OnChildrenParseStarted(){
this->stack.push_back(
T_Pair(this->chain, this->lastInChain)
);
}
//override
void OnStringParsed(const char* s, ting::u32 size){
ting::Ptr<Node> node = Node::New();
node->SetValue(std::string(s, size));
if(this->chain.IsNotValid()){
this->chain = node;
this->lastInChain = this->chain.operator->();
}else{
this->lastInChain->InsertNext(node);
this->lastInChain = this->lastInChain->Next();
}
}
ting::Ptr<Node> chain;
Node* lastInChain;
Listener() :
chain(Node::New()),//create root node
lastInChain(this->chain.operator->())
{}
~Listener()throw(){}
} listener;
listener.OnChildrenParseStarted();
stob::Parse(fi, listener);
listener.OnChildrenParseFinished();
return listener.chain;
}
<|endoftext|> |
<commit_before>/**
* Copyright (c) 2014 - 2016 Tolga Cakir <[email protected]>
*
* This source file is part of Sidewinder daemon and is distributed under the
* MIT License. For more information, see LICENSE file.
*/
#include <chrono>
#include <iostream>
#include <queue>
#include <thread>
#include <fcntl.h>
#include <netdb.h>
#include <unistd.h>
#include <sys/socket.h>
#include <sys/stat.h>
#include <streamer.hpp>
int Streamer::enableDisk(std::string diskPath) {
diskStream_.open(diskPath, std::ofstream::binary);
if (diskStream_.fail()) {
std::cerr << "Can't open " << diskPath << std::endl;
return 1;
}
std::cerr << "Saving to disk: " << diskPath << std::endl;
return 0;
}
void Streamer::disableDisk() {
if (diskStream_.is_open()) {
diskStream_.close();
}
}
int Streamer::enableSocket(std::string ip, std::string port) {
struct addrinfo hints = {};
struct addrinfo *result, *entry;
hints.ai_family = AF_UNSPEC;
hints.ai_socktype = SOCK_DGRAM;
hints.ai_flags = AI_PASSIVE;
// if <ip> is unconfigured, set it to nullptr, effectively IP 0.0.0.0
const char *ipAddress;
if (ip.empty()) {
ipAddress = nullptr;
} else {
ipAddress = ip.c_str();
}
auto ret = getaddrinfo(ipAddress, port.c_str(), &hints, &result);
if (ret) {
std::cerr << "Socket error: " << gai_strerror(ret) << std::endl;
return 1;
}
for (entry = result; entry != nullptr; entry = entry->ai_next) {
socketFd_ = socket(entry->ai_family, entry->ai_socktype, entry->ai_protocol);
if (socketFd_ < 0) {
// error, try next iteration
continue;
}
if (connect(socketFd_, entry->ai_addr, entry->ai_addrlen) != -1) {
// success
break;
}
close(socketFd_);
socketFd_ = -1;
return 1;
}
freeaddrinfo(result);
auto flags = fcntl(socketFd_, F_GETFL);
if (flags == -1) {
std::cerr << "Socket error: fcntl get flags." << std::endl;
return 1;
}
flags |= O_NONBLOCK;
if (fcntl(socketFd_, F_SETFL, flags) == -1) {
std::cerr << "Socket error: fcntl set flags." << std::endl;
return 1;
}
return 0;
}
void Streamer::disableSocket() {
if (socketFd_ != -1) {
close(socketFd_);
socketFd_ = -1;
}
}
void Streamer::loop() {
std::array<unsigned char, DATA_BUF> buffer;
std::queue<std::array<unsigned char, DATA_BUF>> fifoQueue;
std::cerr << "Streamer has been started." << std::endl;
while (process_->isActive()) {
gchd_->stream(&buffer);
if (diskStream_.is_open()) {
diskStream_.write(reinterpret_cast<char *>(buffer.data()), buffer.size());
}
fifo.output(&buffer);
if (socketFd_ != -1) {
write(socketFd_, buffer.data(), buffer.size());
}
}
}
Streamer::Streamer(GCHD *gchd, Process *process) {
socketFd_ = -1;
gchd_ = gchd;
process_ = process;
}
Streamer::~Streamer() {
disableDisk();
disableSocket();
}
<commit_msg>remove unneeded include files<commit_after>/**
* Copyright (c) 2014 - 2016 Tolga Cakir <[email protected]>
*
* This source file is part of Sidewinder daemon and is distributed under the
* MIT License. For more information, see LICENSE file.
*/
#include <iostream>
#include <fcntl.h>
#include <netdb.h>
#include <unistd.h>
#include <sys/socket.h>
#include <streamer.hpp>
int Streamer::enableDisk(std::string diskPath) {
diskStream_.open(diskPath, std::ofstream::binary);
if (diskStream_.fail()) {
std::cerr << "Can't open " << diskPath << std::endl;
return 1;
}
std::cerr << "Saving to disk: " << diskPath << std::endl;
return 0;
}
void Streamer::disableDisk() {
if (diskStream_.is_open()) {
diskStream_.close();
}
}
int Streamer::enableSocket(std::string ip, std::string port) {
struct addrinfo hints = {};
struct addrinfo *result, *entry;
hints.ai_family = AF_UNSPEC;
hints.ai_socktype = SOCK_DGRAM;
hints.ai_flags = AI_PASSIVE;
// if <ip> is unconfigured, set it to nullptr, effectively IP 0.0.0.0
const char *ipAddress;
if (ip.empty()) {
ipAddress = nullptr;
} else {
ipAddress = ip.c_str();
}
auto ret = getaddrinfo(ipAddress, port.c_str(), &hints, &result);
if (ret) {
std::cerr << "Socket error: " << gai_strerror(ret) << std::endl;
return 1;
}
for (entry = result; entry != nullptr; entry = entry->ai_next) {
socketFd_ = socket(entry->ai_family, entry->ai_socktype, entry->ai_protocol);
if (socketFd_ < 0) {
// error, try next iteration
continue;
}
if (connect(socketFd_, entry->ai_addr, entry->ai_addrlen) != -1) {
// success
break;
}
close(socketFd_);
socketFd_ = -1;
return 1;
}
freeaddrinfo(result);
auto flags = fcntl(socketFd_, F_GETFL);
if (flags == -1) {
std::cerr << "Socket error: fcntl get flags." << std::endl;
return 1;
}
flags |= O_NONBLOCK;
if (fcntl(socketFd_, F_SETFL, flags) == -1) {
std::cerr << "Socket error: fcntl set flags." << std::endl;
return 1;
}
return 0;
}
void Streamer::disableSocket() {
if (socketFd_ != -1) {
close(socketFd_);
socketFd_ = -1;
}
}
void Streamer::loop() {
std::array<unsigned char, DATA_BUF> buffer;
std::cerr << "Streamer has been started." << std::endl;
while (process_->isActive()) {
gchd_->stream(&buffer);
if (diskStream_.is_open()) {
diskStream_.write(reinterpret_cast<char *>(buffer.data()), buffer.size());
}
fifo.output(&buffer);
if (socketFd_ != -1) {
write(socketFd_, buffer.data(), buffer.size());
}
}
}
Streamer::Streamer(GCHD *gchd, Process *process) {
socketFd_ = -1;
gchd_ = gchd;
process_ = process;
}
Streamer::~Streamer() {
disableDisk();
disableSocket();
}
<|endoftext|> |
<commit_before>#include<string>
#include<iostream>
#include<algorithm>
#include<cstring>
#include<map>
#include<vector>
class Vector3D
{
public:
double data[3];
double& x;
double& y;
double& z;
Vector3D(const double tx=0.0,const double ty=0.0,const double tz=0.0):
data({tx,ty,tz}),
x(data[0]),y(data[1]),z(data[2])
{}
double magnitude() const
{
return sqrt(dot(*this));
}
void normalize()
{
operator*=(1.0/magnitude());
}
Vector3D& operator*=(const double scale)
{
x*=scale;y*=scale;z*=scale;
return *this;
}
double dot(const Vector3D& o) const
{
return data[0]*o.data[0]+data[1]*o.data[1]+data[2]*o.data[2];
}
};
class Point2D
{
public:
double x, y;
Point2D(const double tx,const double ty):x(tx),y(ty)
{}
};
struct projection_size
{
int width;
int height;
int latitude_frequency;
projection_size():width(-1),height(-1),latitude_frequency(-1)
{}
};
class Projection
{
public:
virtual Vector3D uv_to_sphere(double u, double v) const = 0;
virtual Point2D sphere_to_uv(const Vector3D& direction) const = 0;
virtual bool is_valid_pixel(double u, double v) const = 0;
virtual projection_size get_projection_size(const projection_size& options=projection_size()) const = 0;
virtual ~Projection()
{}
virtual void setOptions(const std::map<std::string,std::string>& options)
{}
};
vector<std::string> split(const std::string& s,const std::string& delimiters)
{
std::vector<std::string> result;
size_t current;
size_t next = -1;
do
{
current = next + 1;
next = s.find_first_of( delimiters, current );
result.push_back( s.substr( current, next - current ) );
}
while (next != std::string::npos);
return result;
}
class ProjectionRegistry
{
public:
map<std::string,Projection*> projections;
private:
template<class T>
void register_projection(const std::string& name)
{
projections[name]=new T;
}
public:
ProjectionRegistry()
{
register_projection<MirrorBallProjection>("mirrorball");
register_projection<AngularProjection>("angular");
register_projection<PolarProjection>("polar");
register_projection<PolarProjection>("latlong");
register_projection<CubeProjection>("cube");
register_projection<CylindricalProjection>("cylindrical");
}
~ProjectionRegistry()
{
for(std::map<std::string>::iterator i=projections_in.begin(),i!=projections_in.end();++i)
{
delete i->second;
}
}
Projection* parse_projstring(const std::string& projstring)
{
std::vector<std::string> slashiesplit=split(projstring,"/");
string name=slashiesplit[0]
std::transform(name.begin(),name.end(),name.begin(),std::tolower);
std::map<std::string,Projection*>::iterator found=projections.find(name);
if(found == projections.end())
{
throw std::runtime_error(std::string("No projection with the name \"")+name+"\" found.");
}
std::map<std::string,std::string> options;
for(size_t i=1;i<slashiesplit.size();i++)
{
std::vector<std::string> nvpairs=split(projstring,"=");
if(nvpairs.size()==1)
{
options[nvpairs[0]]="";
}
else
{
options[nvpairs[0]]=nvpairs[1];
}
}
found->second->setOptions(options);
return found->second;
}
};
int panoramic()
{
ProjectionRegistry inprojections,outprojections;
std::vector<std::string> inoutpstring=split(pstring,"+");
}
<commit_msg>more code towards pfspanoramic<commit_after>#include<string>
#include<iostream>
#include<algorithm>
#include<cstring>
#include<map>
#include<vector>
class Vector3D
{
public:
double data[3];
double& x;
double& y;
double& z;
Vector3D(const double tx=0.0,const double ty=0.0,const double tz=0.0):
data({tx,ty,tz}),
x(data[0]),y(data[1]),z(data[2])
{}
double magnitude() const
{
return sqrt(dot(*this));
}
void normalize()
{
operator*=(1.0/magnitude());
}
Vector3D& operator*=(const double scale)
{
x*=scale;y*=scale;z*=scale;
return *this;
}
double dot(const Vector3D& o) const
{
return data[0]*o.data[0]+data[1]*o.data[1]+data[2]*o.data[2];
}
};
class Point2D
{
public:
double x, y;
Point2D(const double tx,const double ty):x(tx),y(ty)
{}
};
struct projection_size
{
int width;
int height;
int latitude_frequency;
projection_size(int w=-1,int h=-1,int l=-1):width(w),height(h),latitude_frequency(l)
{}
};
class Projection
{
public:
virtual Vector3D uv_to_sphere(double u, double v) const = 0;
virtual Point2D sphere_to_uv(const Vector3D& direction) const = 0;
virtual bool is_valid_pixel(double u, double v) const = 0;
virtual projection_size get_projection_size(const projection_size& options=projection_size()) const = 0;
virtual std::string guess_valid_string(int w,int h) const = 0;
virtual ~Projection()
{}
virtual void setOptions(const std::map<std::string,std::string>& options)
{}
};
vector<std::string> split(const std::string& s,const std::string& delimiters)
{
std::vector<std::string> result;
size_t current;
size_t next = -1;
do
{
current = next + 1;
next = s.find_first_of( delimiters, current );
result.push_back( s.substr( current, next - current ) );
}
while (next != std::string::npos);
return result;
}
class ProjectionRegistry
{
public:
map<std::string,Projection*> projections;
private:
template<class T>
void register_projection(const std::string& name)
{
projections[name]=new T;
}
public:
ProjectionRegistry()
{
register_projection<MirrorBallProjection>("mirrorball");
register_projection<AngularProjection>("angular");
register_projection<PolarProjection>("polar");
register_projection<PolarProjection>("latlong");
register_projection<CubeProjection>("cube");
register_projection<CylindricalProjection>("cylindrical");
}
~ProjectionRegistry()
{
for(std::map<std::string>::iterator i=projections_in.begin(),i!=projections_in.end();++i)
{
delete i->second;
}
}
Projection* parse_projstring(const std::string& projstring)
{
std::vector<std::string> slashiesplit=split(projstring,"/");
string name=slashiesplit[0]
std::transform(name.begin(),name.end(),name.begin(),std::tolower);
std::map<std::string,Projection*>::iterator found=projections.find(name);
if(found == projections.end())
{
throw std::runtime_error(std::string("No projection with the name \"")+name+"\" found.");
}
std::map<std::string,std::string> options;
for(size_t i=1;i<slashiesplit.size();i++)
{
std::vector<std::string> nvpairs=split(projstring,"=");
if(nvpairs.size()==1)
{
options[nvpairs[0]]="";
}
else
{
options[nvpairs[0]]=nvpairs[1];
}
}
found->second->setOptions(options);
return found->second;
}
std::string guess_projstring(int x,int y)
{
if(x <= 0 || y <= 0)
{
throw std::runtime_error("No projection can be determined automatically from the given size parameters. Please specify a projection or size parameters");
}
std::string guess="";
for(map<std::string,Projection*>::iterator it=projections.begin();it!=projections.end();++it)
{
std::string cguess=it->second->guess_projstring(x,y);
if(cguess != "")
{
if(guess=="")
{
guess=cguess;
}
else
{
throw std::runtime_error(std::string("Cannot determine projection automatically from size parameters..given parameters could be ")+cguess+" or "+guess);
}
}
}
if(guess=="")
{
throw std::runtime_error("No projection could be determined automatically from the given size parameters. Please specify a projection.");
}
}
};
static const std::string PROG_NAME="pfspanoramic";
void printHelp(const std::string& arg0)
{
cerr << arg0 << " <source projection>+<target projection> [--width <val>] [--height <val>] [--oversample <val>] [--interpolate] [--xrotate <angle>] [--yrotate <angle>] [--zrotate <angle>] [--verbose] [--help]\n"
<< "See man page for more information.\n";
}
struct cmdargs
{
std::string pstring="";
projection_size size;
bool verbose=false;
Vector3D rotation;
bool interpolate=false;
int oversample=1;
cmdargs(const std::vector<std::string>& args):
pstring(""),
verbose(false),
interpolate(false),
oversample(false)
{
for(int i=1;i<args.size();i++)
{
if(args[i][0]!='-')
{
pstring=args[i];
}
else if(args[i]=='--help')
{
printHelp(args[0]);
return 0;
}
else
{
char ch=args[i][1]=='-' ? args[i][2] : args[i][1];
switch(ch)
{
case 'w':
{
std::istringstream(args[++i]) >> size.width;
break;
}
case 'h':
{
std::istringstream(args[++i]) >> size.height;
break;
}
case 'x':
{
std::istringstream(args[++i]) >> rotation.x;
break;
}
case 'y':
{
std::istringstream(args[++i]) >> rotation.y;
break;
}
case 'z':
{
std::istringstream(args[++i]) >> rotation.z;
break;
}
case 'i':
{
interpolate=true;
break;
}
case 'o':
{
std::istringstream(args[++i]) >> oversample;
break;
}
default:
{
printHelp(args[0]);
throw std::runtime_error("Invalid arguments");
}
};
}
}
if(pstring == "")
{
throw std::runtime_error("No projection string detected!");
}
if(oversample < 1)
{
throw std::runtime_error("Oversampling must be an integer greater than 10");
}
}
};
Projection* replace_guess(Projection* proj,const std::string pstr,ProjectionRegistry& reg,int width,int height)
{
if(proj!=NULL)
return proj;
if(pstr=="")
{
pstr=reg.guess_projstring(width,height);
}
return inprojections.parse_projstring(pstr);
}
int panoramic(const std::vector<std::string>& args)
{
cmdargs argsin(args);
ProjectionRegistry inprojections,outprojections;
pfs::DOMIO pfsio;
std::vector<std::string> inoutpstring=split(pstring,"+");
Projection* inproj=NULL;
Projection* outproj=NULL;
pfs::Frame *inframe;
while(inframe=pfsio.readFrame( stdin ))
{
inproj=replace_guess(inproj,inoutpstring[0],inprojections,inframe->getWidth(),inframe->getHeight());
projection_size ips=inproj->get_projection_size(projection_size(inframe->getWidth(),inframe->getHeight()));
outproj=replace_guess(outproj,inoutpstring[1],outprojections,argsin.size.x,argin.size.y);
projection_size ops;
if(argin.size.x <=0 || argin.size.y <=0)
{
ops=outproj->get_projection_size(ips);
}
else
{
ops=argin.size;
}
}
}
<|endoftext|> |
<commit_before>/*
The MIT License
Copyright (c) 2012 by Jorrit Tyberghein
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 "cssysdef.h"
#include "csutil/csinput.h"
#include "cstool/cspixmap.h"
#include "csgeom/math3d.h"
#include "iutil/objreg.h"
#include "iutil/virtclk.h"
#include "ivideo/graph3d.h"
#include "ivideo/graph2d.h"
#include "ivideo/fontserv.h"
#include "ivideo/txtmgr.h"
#include "iengine/engine.h"
#include "iengine/texture.h"
#include "iengine/camera.h"
#include "iengine/movable.h"
#include "gamecontrol.h"
#include "physicallayer/pl.h"
#include "physicallayer/entity.h"
#include "propclass/camera.h"
#include "propclass/dynworld.h"
#include "propclass/dynmove.h"
#include "propclass/prop.h"
#include "ivaria/dynamics.h"
//---------------------------------------------------------------------------
CEL_IMPLEMENT_FACTORY (GameController, "ares.gamecontrol")
//---------------------------------------------------------------------------
csStringID celPcGameController::id_message = csInvalidStringID;
csStringID celPcGameController::id_timeout = csInvalidStringID;
PropertyHolder celPcGameController::propinfo;
celPcGameController::celPcGameController (iObjectRegistry* object_reg)
: scfImplementationType (this, object_reg)
{
// For SendMessage parameters.
if (id_message == csInvalidStringID)
{
id_message = pl->FetchStringID ("message");
id_timeout = pl->FetchStringID ("timeout");
}
propholder = &propinfo;
// For actions.
if (!propinfo.actions_done)
{
SetActionMask ("ares.controller.");
AddAction (action_message, "Message");
AddAction (action_startdrag, "StartDrag");
AddAction (action_stopdrag, "StopDrag");
AddAction (action_examine, "Examine");
}
// For properties.
propinfo.SetCount (0);
//AddProperty (propid_counter, "counter",
//CEL_DATA_LONG, false, "Print counter.", &counter);
//AddProperty (propid_max, "max",
//CEL_DATA_LONG, false, "Max length.", 0);
dragobj = 0;
mouse = csQueryRegistry<iMouseDriver> (object_reg);
g3d = csQueryRegistry<iGraphics3D> (object_reg);
vc = csQueryRegistry<iVirtualClock> (object_reg);
g2d = g3d->GetDriver2D ();
engine = csQueryRegistry<iEngine> (object_reg);
pl->CallbackEveryFrame ((iCelTimerListener*)this, CEL_EVENT_POST);
messageColor = g3d->GetDriver2D ()->FindRGB (255, 255, 255);
iFontServer* fontsrv = g3d->GetDriver2D ()->GetFontServer ();
//font = fontsrv->LoadFont (CSFONT_COURIER);
font = fontsrv->LoadFont ("DejaVuSansBold", 10);
font->GetMaxSize (fontW, fontH);
classNoteID = pl->FetchStringID ("ares.note");
classInfoID = pl->FetchStringID ("ares.info");
attrDragType = pl->FetchStringID ("ares.dragtype");
LoadIcons ();
}
celPcGameController::~celPcGameController ()
{
pl->RemoveCallbackEveryFrame ((iCelTimerListener*)this, CEL_EVENT_POST);
delete iconCursor;
delete iconEye;
delete iconBook;
delete iconDot;
}
void celPcGameController::LoadIcons ()
{
iTextureWrapper* txt;
txt = engine->CreateTexture ("icon_cursor",
"/icons/iconic_cursor_32x32.png", 0, CS_TEXTURE_2D | CS_TEXTURE_NOMIPMAPS);
txt->Register (g3d->GetTextureManager ());
iconCursor = new csSimplePixmap (txt->GetTextureHandle ());
txt = engine->CreateTexture ("icon_dot",
"/icons/icon_dot.png", 0, CS_TEXTURE_2D | CS_TEXTURE_NOMIPMAPS);
txt->Register (g3d->GetTextureManager ());
iconDot = new csSimplePixmap (txt->GetTextureHandle ());
txt = engine->CreateTexture ("icon_eye",
"/icons/iconic_eye_32x24.png", 0, CS_TEXTURE_2D | CS_TEXTURE_NOMIPMAPS);
txt->Register (g3d->GetTextureManager ());
iconEye = new csSimplePixmap (txt->GetTextureHandle ());
txt = engine->CreateTexture ("icon_book",
"/icons/iconic_book_alt2_32x28.png", 0, CS_TEXTURE_2D | CS_TEXTURE_NOMIPMAPS);
txt->Register (g3d->GetTextureManager ());
iconBook = new csSimplePixmap (txt->GetTextureHandle ());
}
void celPcGameController::TryGetDynworld ()
{
if (dynworld) return;
dynworld = celQueryPropertyClassEntity<iPcDynamicWorld> (entity);
if (dynworld) return;
// Not very clean. We should only depend on the dynworld plugin
// to be in this entity but for the editor we actually have the
// dynworld plugin in the 'Zone' entity. Need to find a way for this
// that is cleaner.
csRef<iCelEntity> zone = pl->FindEntity ("Zone");
if (!zone)
{
printf ("Can't find entity 'Zone' and current entity has no dynworld PC!\n");
return;
}
dynworld = celQueryPropertyClassEntity<iPcDynamicWorld> (zone);
iDynamicSystem* dynSys = dynworld->GetCurrentCell ()->GetDynamicSystem ();
bullet_dynSys = scfQueryInterface<CS::Physics::Bullet::iDynamicSystem> (dynSys);
}
void celPcGameController::TryGetCamera ()
{
if (pccamera && pcdynmove) return;
csRef<iCelEntity> player = pl->FindEntity ("Player");
if (!player)
{
printf ("Can't find entity 'Player'!\n");
return;
}
pccamera = celQueryPropertyClassEntity<iPcCamera> (player);
pcdynmove = celQueryPropertyClassEntity<iPcDynamicMove> (player);
}
bool celPcGameController::PerformActionIndexed (int idx,
iCelParameterBlock* params,
celData& ret)
{
switch (idx)
{
case action_message:
{
CEL_FETCH_STRING_PAR (msg,params,id_message);
if (!p_msg) return false;
CEL_FETCH_FLOAT_PAR (timeout,params,id_timeout);
if (!p_timeout) timeout = 2.0f;
Message (msg, timeout);
return true;
}
case action_startdrag:
return StartDrag ();
case action_stopdrag:
StopDrag ();
return true;
case action_examine:
Examine ();
return true;
default:
return false;
}
return false;
}
void celPcGameController::Examine ()
{
iRigidBody* hitBody;
csVector3 start, isect;
iDynamicObject* obj = FindCenterObject (hitBody, start, isect);
if (obj)
{
iCelEntity* ent = obj->GetEntity ();
if (ent && ent->HasClass (classInfoID))
{
csRef<iPcProperties> prop = celQueryPropertyClassEntity<iPcProperties> (ent);
if (!prop)
{
Message ("ERROR: Entity has no properties!");
return;
}
size_t idx = prop->GetPropertyIndex ("ares.info");
if (idx == csArrayItemNotFound)
{
Message ("ERROR: Entity has no 'ares.info' property!");
return;
}
Message (prop->GetPropertyString (idx));
}
else
{
Message ("I see nothing special!");
}
}
else
{
Message ("Nothing to examine!");
}
}
void celPcGameController::Message (const char* message, float timeout)
{
TimedMessage m;
m.message = message;
m.timeleft = timeout;
messages.Push (m);
printf ("MSG: %s\n", message);
fflush (stdout);
}
iDynamicObject* celPcGameController::FindCenterObject (iRigidBody*& hitBody,
csVector3& start, csVector3& isect)
{
TryGetCamera ();
TryGetDynworld ();
iCamera* cam = pccamera->GetCamera ();
if (!cam) return 0;
int x = mouse->GetLastX ();
int y = mouse->GetLastY ();
csVector2 v2d (x, g2d->GetHeight () - y);
csVector3 v3d = cam->InvPerspective (v2d, 3.0f);
start = cam->GetTransform ().GetOrigin ();
csVector3 end = cam->GetTransform ().This2Other (v3d);
// Trace the physical beam
CS::Physics::Bullet::HitBeamResult result = bullet_dynSys->HitBeam (start, end);
if (!result.body) return 0;
hitBody = result.body->QueryRigidBody ();
isect = result.isect;
return dynworld->FindObject (hitBody);
}
bool celPcGameController::StartDrag ()
{
iRigidBody* hitBody;
csVector3 start, isect;
iDynamicObject* obj = FindCenterObject (hitBody, start, isect);
if (obj)
{
dragobj = obj;
csString dt = obj->GetFactory ()->GetAttribute (attrDragType);
if (dt == "roty")
{
printf ("Start roty drag!\n"); fflush (stdout);
dragType = DRAGTYPE_ROTY;
pcdynmove->EnableMouselook (false);
dragOrigin = obj->GetMesh ()->GetMovable ()->GetTransform ().GetOrigin ();
//dragOrigin.y = isect.y;
isect.y = dragOrigin.y;
dragAnchor = isect;
dragDistance = (isect - dragOrigin).Norm ();
}
else
{
printf ("Start normal drag!\n"); fflush (stdout);
dragType = DRAGTYPE_NORMAL;
dragDistance = (isect - start).Norm ();
}
dragJoint = bullet_dynSys->CreatePivotJoint ();
dragJoint->Attach (hitBody, isect);
// Set some dampening on the rigid body to have a more stable dragging
csRef<CS::Physics::Bullet::iRigidBody> csBody =
scfQueryInterface<CS::Physics::Bullet::iRigidBody> (hitBody);
oldLinearDampening = csBody->GetLinearDampener ();
oldAngularDampening = csBody->GetRollingDampener ();
csBody->SetLinearDampener (0.9f);
csBody->SetRollingDampener (0.9f);
return true;
}
return false;
}
void celPcGameController::StopDrag ()
{
if (!dragobj) return;
printf ("Stop drag!\n"); fflush (stdout);
csRef<CS::Physics::Bullet::iRigidBody> csBody =
scfQueryInterface<CS::Physics::Bullet::iRigidBody> (dragJoint->GetAttachedBody ());
csBody->SetLinearDampener (oldLinearDampening);
csBody->SetRollingDampener (oldAngularDampening);
bullet_dynSys->RemovePivotJoint (dragJoint);
dragJoint = 0;
dragobj = 0;
if (dragType == DRAGTYPE_ROTY)
pcdynmove->EnableMouselook (true);
}
void celPcGameController::TickEveryFrame ()
{
csSimplePixmap* icon = iconDot;
int sw = g2d->GetWidth ();
int sh = g2d->GetHeight ();
if (dragobj)
{
iCamera* cam = pccamera->GetCamera ();
if (!cam) return;
int x = mouse->GetLastX ();
int y = mouse->GetLastY ();
csVector3 newPosition;
if (dragType == DRAGTYPE_ROTY)
{
int sx = x - sw / 2;
int sy = y - sh / 2;
g2d->SetMousePosition (sw / 2, sh / 2);
csVector3 v (float (sx) / 200.0f, 0, - float (sy) / 200.0f);
float len = v.Norm ();
v = cam->GetTransform ().This2OtherRelative (v);
v.y = 0;
if (v.Norm () > .0001f)
{
v.Normalize ();
v *= len;
dragAnchor += v;
newPosition = dragAnchor - dragOrigin;
newPosition.Normalize ();
newPosition = dragOrigin + newPosition * dragDistance;
dragJoint->SetPosition (newPosition);
}
icon = iconDot;
}
else
{
csVector2 v2d (x, sh - y);
csVector3 v3d = cam->InvPerspective (v2d, 3.0f);
csVector3 start = cam->GetTransform ().GetOrigin ();
csVector3 end = cam->GetTransform ().This2Other (v3d);
newPosition = end - start;
newPosition.Normalize ();
newPosition = cam->GetTransform ().GetOrigin () + newPosition * dragDistance;
dragJoint->SetPosition (newPosition);
icon = iconCursor;
}
}
else
{
iRigidBody* hitBody;
csVector3 start, isect;
iDynamicObject* obj = FindCenterObject (hitBody, start, isect);
if (obj)
{
iCelEntity* ent = obj->GetEntity ();
if (ent && ent->HasClass (classNoteID))
{
icon = iconBook;
}
else if (ent && ent->HasClass (classInfoID))
{
icon = iconEye;
}
else if (!obj->IsStatic ())
{
icon = iconCursor;
}
}
}
g3d->BeginDraw (CSDRAW_2DGRAPHICS);
if (messages.GetSize () > 0)
{
float elapsed = vc->GetElapsedSeconds ();
int y = 20;
size_t i = 0;
while (i < messages.GetSize ())
{
TimedMessage& m = messages[i];
m.timeleft -= elapsed;
if (m.timeleft <= 0)
messages.DeleteIndex (i);
else
{
int alpha = 255;
if (m.timeleft < 1.0f) alpha = int (255.0f * (m.timeleft));
messageColor = g3d->GetDriver2D ()->FindRGB (255, 255, 255, alpha);
g2d->Write (font, 20, y, messageColor, -1, m.message.GetData ());
y += fontH + 2;
i++;
}
}
}
icon->Draw (g3d, sw / 2, sh / 2);
}
//---------------------------------------------------------------------------
<commit_msg>Slightly better dragging parameters.<commit_after>/*
The MIT License
Copyright (c) 2012 by Jorrit Tyberghein
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 "cssysdef.h"
#include "csutil/csinput.h"
#include "cstool/cspixmap.h"
#include "csgeom/math3d.h"
#include "iutil/objreg.h"
#include "iutil/virtclk.h"
#include "ivideo/graph3d.h"
#include "ivideo/graph2d.h"
#include "ivideo/fontserv.h"
#include "ivideo/txtmgr.h"
#include "iengine/engine.h"
#include "iengine/texture.h"
#include "iengine/camera.h"
#include "iengine/movable.h"
#include "gamecontrol.h"
#include "physicallayer/pl.h"
#include "physicallayer/entity.h"
#include "propclass/camera.h"
#include "propclass/dynworld.h"
#include "propclass/dynmove.h"
#include "propclass/prop.h"
#include "ivaria/dynamics.h"
//---------------------------------------------------------------------------
CEL_IMPLEMENT_FACTORY (GameController, "ares.gamecontrol")
//---------------------------------------------------------------------------
csStringID celPcGameController::id_message = csInvalidStringID;
csStringID celPcGameController::id_timeout = csInvalidStringID;
PropertyHolder celPcGameController::propinfo;
celPcGameController::celPcGameController (iObjectRegistry* object_reg)
: scfImplementationType (this, object_reg)
{
// For SendMessage parameters.
if (id_message == csInvalidStringID)
{
id_message = pl->FetchStringID ("message");
id_timeout = pl->FetchStringID ("timeout");
}
propholder = &propinfo;
// For actions.
if (!propinfo.actions_done)
{
SetActionMask ("ares.controller.");
AddAction (action_message, "Message");
AddAction (action_startdrag, "StartDrag");
AddAction (action_stopdrag, "StopDrag");
AddAction (action_examine, "Examine");
}
// For properties.
propinfo.SetCount (0);
//AddProperty (propid_counter, "counter",
//CEL_DATA_LONG, false, "Print counter.", &counter);
//AddProperty (propid_max, "max",
//CEL_DATA_LONG, false, "Max length.", 0);
dragobj = 0;
mouse = csQueryRegistry<iMouseDriver> (object_reg);
g3d = csQueryRegistry<iGraphics3D> (object_reg);
vc = csQueryRegistry<iVirtualClock> (object_reg);
g2d = g3d->GetDriver2D ();
engine = csQueryRegistry<iEngine> (object_reg);
pl->CallbackEveryFrame ((iCelTimerListener*)this, CEL_EVENT_POST);
messageColor = g3d->GetDriver2D ()->FindRGB (255, 255, 255);
iFontServer* fontsrv = g3d->GetDriver2D ()->GetFontServer ();
//font = fontsrv->LoadFont (CSFONT_COURIER);
font = fontsrv->LoadFont ("DejaVuSansBold", 10);
font->GetMaxSize (fontW, fontH);
classNoteID = pl->FetchStringID ("ares.note");
classInfoID = pl->FetchStringID ("ares.info");
attrDragType = pl->FetchStringID ("ares.dragtype");
LoadIcons ();
}
celPcGameController::~celPcGameController ()
{
pl->RemoveCallbackEveryFrame ((iCelTimerListener*)this, CEL_EVENT_POST);
delete iconCursor;
delete iconEye;
delete iconBook;
delete iconDot;
}
void celPcGameController::LoadIcons ()
{
iTextureWrapper* txt;
txt = engine->CreateTexture ("icon_cursor",
"/icons/iconic_cursor_32x32.png", 0, CS_TEXTURE_2D | CS_TEXTURE_NOMIPMAPS);
txt->Register (g3d->GetTextureManager ());
iconCursor = new csSimplePixmap (txt->GetTextureHandle ());
txt = engine->CreateTexture ("icon_dot",
"/icons/icon_dot.png", 0, CS_TEXTURE_2D | CS_TEXTURE_NOMIPMAPS);
txt->Register (g3d->GetTextureManager ());
iconDot = new csSimplePixmap (txt->GetTextureHandle ());
txt = engine->CreateTexture ("icon_eye",
"/icons/iconic_eye_32x24.png", 0, CS_TEXTURE_2D | CS_TEXTURE_NOMIPMAPS);
txt->Register (g3d->GetTextureManager ());
iconEye = new csSimplePixmap (txt->GetTextureHandle ());
txt = engine->CreateTexture ("icon_book",
"/icons/iconic_book_alt2_32x28.png", 0, CS_TEXTURE_2D | CS_TEXTURE_NOMIPMAPS);
txt->Register (g3d->GetTextureManager ());
iconBook = new csSimplePixmap (txt->GetTextureHandle ());
}
void celPcGameController::TryGetDynworld ()
{
if (dynworld) return;
dynworld = celQueryPropertyClassEntity<iPcDynamicWorld> (entity);
if (dynworld) return;
// Not very clean. We should only depend on the dynworld plugin
// to be in this entity but for the editor we actually have the
// dynworld plugin in the 'Zone' entity. Need to find a way for this
// that is cleaner.
csRef<iCelEntity> zone = pl->FindEntity ("Zone");
if (!zone)
{
printf ("Can't find entity 'Zone' and current entity has no dynworld PC!\n");
return;
}
dynworld = celQueryPropertyClassEntity<iPcDynamicWorld> (zone);
iDynamicSystem* dynSys = dynworld->GetCurrentCell ()->GetDynamicSystem ();
bullet_dynSys = scfQueryInterface<CS::Physics::Bullet::iDynamicSystem> (dynSys);
}
void celPcGameController::TryGetCamera ()
{
if (pccamera && pcdynmove) return;
csRef<iCelEntity> player = pl->FindEntity ("Player");
if (!player)
{
printf ("Can't find entity 'Player'!\n");
return;
}
pccamera = celQueryPropertyClassEntity<iPcCamera> (player);
pcdynmove = celQueryPropertyClassEntity<iPcDynamicMove> (player);
}
bool celPcGameController::PerformActionIndexed (int idx,
iCelParameterBlock* params,
celData& ret)
{
switch (idx)
{
case action_message:
{
CEL_FETCH_STRING_PAR (msg,params,id_message);
if (!p_msg) return false;
CEL_FETCH_FLOAT_PAR (timeout,params,id_timeout);
if (!p_timeout) timeout = 2.0f;
Message (msg, timeout);
return true;
}
case action_startdrag:
return StartDrag ();
case action_stopdrag:
StopDrag ();
return true;
case action_examine:
Examine ();
return true;
default:
return false;
}
return false;
}
void celPcGameController::Examine ()
{
iRigidBody* hitBody;
csVector3 start, isect;
iDynamicObject* obj = FindCenterObject (hitBody, start, isect);
if (obj)
{
iCelEntity* ent = obj->GetEntity ();
if (ent && ent->HasClass (classInfoID))
{
csRef<iPcProperties> prop = celQueryPropertyClassEntity<iPcProperties> (ent);
if (!prop)
{
Message ("ERROR: Entity has no properties!");
return;
}
size_t idx = prop->GetPropertyIndex ("ares.info");
if (idx == csArrayItemNotFound)
{
Message ("ERROR: Entity has no 'ares.info' property!");
return;
}
Message (prop->GetPropertyString (idx));
}
else
{
Message ("I see nothing special!");
}
}
else
{
Message ("Nothing to examine!");
}
}
void celPcGameController::Message (const char* message, float timeout)
{
TimedMessage m;
m.message = message;
m.timeleft = timeout;
messages.Push (m);
printf ("MSG: %s\n", message);
fflush (stdout);
}
iDynamicObject* celPcGameController::FindCenterObject (iRigidBody*& hitBody,
csVector3& start, csVector3& isect)
{
TryGetCamera ();
TryGetDynworld ();
iCamera* cam = pccamera->GetCamera ();
if (!cam) return 0;
int x = mouse->GetLastX ();
int y = mouse->GetLastY ();
csVector2 v2d (x, g2d->GetHeight () - y);
csVector3 v3d = cam->InvPerspective (v2d, 3.0f);
start = cam->GetTransform ().GetOrigin ();
csVector3 end = cam->GetTransform ().This2Other (v3d);
// Trace the physical beam
CS::Physics::Bullet::HitBeamResult result = bullet_dynSys->HitBeam (start, end);
if (!result.body) return 0;
hitBody = result.body->QueryRigidBody ();
isect = result.isect;
return dynworld->FindObject (hitBody);
}
bool celPcGameController::StartDrag ()
{
iRigidBody* hitBody;
csVector3 start, isect;
iDynamicObject* obj = FindCenterObject (hitBody, start, isect);
if (obj)
{
dragobj = obj;
csString dt = obj->GetFactory ()->GetAttribute (attrDragType);
if (dt == "roty")
{
printf ("Start roty drag!\n"); fflush (stdout);
dragType = DRAGTYPE_ROTY;
pcdynmove->EnableMouselook (false);
dragOrigin = obj->GetMesh ()->GetMovable ()->GetTransform ().GetOrigin ();
//dragOrigin.y = isect.y;
isect.y = dragOrigin.y;
dragAnchor = isect;
dragDistance = (isect - dragOrigin).Norm ();
}
else
{
printf ("Start normal drag!\n"); fflush (stdout);
dragType = DRAGTYPE_NORMAL;
dragDistance = (isect - start).Norm ();
}
dragJoint = bullet_dynSys->CreatePivotJoint ();
dragJoint->SetParameters (1.0f, 0.001f, 1.0f);
dragJoint->Attach (hitBody, isect);
// Set some dampening on the rigid body to have a more stable dragging
csRef<CS::Physics::Bullet::iRigidBody> csBody =
scfQueryInterface<CS::Physics::Bullet::iRigidBody> (hitBody);
oldLinearDampening = csBody->GetLinearDampener ();
oldAngularDampening = csBody->GetRollingDampener ();
csBody->SetLinearDampener (0.9f);
csBody->SetRollingDampener (0.9f);
return true;
}
return false;
}
void celPcGameController::StopDrag ()
{
if (!dragobj) return;
printf ("Stop drag!\n"); fflush (stdout);
csRef<CS::Physics::Bullet::iRigidBody> csBody =
scfQueryInterface<CS::Physics::Bullet::iRigidBody> (dragJoint->GetAttachedBody ());
csBody->SetLinearDampener (oldLinearDampening);
csBody->SetRollingDampener (oldAngularDampening);
bullet_dynSys->RemovePivotJoint (dragJoint);
dragJoint = 0;
dragobj = 0;
if (dragType == DRAGTYPE_ROTY)
pcdynmove->EnableMouselook (true);
}
void celPcGameController::TickEveryFrame ()
{
csSimplePixmap* icon = iconDot;
int sw = g2d->GetWidth ();
int sh = g2d->GetHeight ();
if (dragobj)
{
iCamera* cam = pccamera->GetCamera ();
if (!cam) return;
int x = mouse->GetLastX ();
int y = mouse->GetLastY ();
csVector3 newPosition;
if (dragType == DRAGTYPE_ROTY)
{
int sx = x - sw / 2;
int sy = y - sh / 2;
g2d->SetMousePosition (sw / 2, sh / 2);
csVector3 v (float (sx) / 200.0f, 0, - float (sy) / 200.0f);
float len = v.Norm ();
v = cam->GetTransform ().This2OtherRelative (v);
v.y = 0;
if (v.Norm () > .0001f)
{
v.Normalize ();
v *= len;
dragAnchor += v;
newPosition = dragAnchor - dragOrigin;
newPosition.Normalize ();
newPosition = dragOrigin + newPosition * dragDistance;
dragJoint->SetPosition (newPosition);
}
icon = iconDot;
}
else
{
csVector2 v2d (x, sh - y);
csVector3 v3d = cam->InvPerspective (v2d, 3.0f);
csVector3 start = cam->GetTransform ().GetOrigin ();
csVector3 end = cam->GetTransform ().This2Other (v3d);
newPosition = end - start;
newPosition.Normalize ();
newPosition = cam->GetTransform ().GetOrigin () + newPosition * dragDistance;
dragJoint->SetPosition (newPosition);
icon = iconCursor;
}
}
else
{
iRigidBody* hitBody;
csVector3 start, isect;
iDynamicObject* obj = FindCenterObject (hitBody, start, isect);
if (obj)
{
iCelEntity* ent = obj->GetEntity ();
if (ent && ent->HasClass (classNoteID))
{
icon = iconBook;
}
else if (ent && ent->HasClass (classInfoID))
{
icon = iconEye;
}
else if (!obj->IsStatic ())
{
icon = iconCursor;
}
}
}
g3d->BeginDraw (CSDRAW_2DGRAPHICS);
if (messages.GetSize () > 0)
{
float elapsed = vc->GetElapsedSeconds ();
int y = 20;
size_t i = 0;
while (i < messages.GetSize ())
{
TimedMessage& m = messages[i];
m.timeleft -= elapsed;
if (m.timeleft <= 0)
messages.DeleteIndex (i);
else
{
int alpha = 255;
if (m.timeleft < 1.0f) alpha = int (255.0f * (m.timeleft));
messageColor = g3d->GetDriver2D ()->FindRGB (255, 255, 255, alpha);
g2d->Write (font, 20, y, messageColor, -1, m.message.GetData ());
y += fontH + 2;
i++;
}
}
}
icon->Draw (g3d, sw / 2, sh / 2);
}
//---------------------------------------------------------------------------
<|endoftext|> |
<commit_before>#include "generator/CompGenerator.h"
// from STL
#include <iostream>
// from ROOT
#include "TRandom.h"
// from project - generator
#include "generator/generator.h"
#include "generator/Observables.h"
// from project - configuration
#include "configuration/CompConfig.h"
namespace cptoymc {
namespace generator {
CompGenerator::CompGenerator() { }
CompGenerator::~CompGenerator() { }
BSig_CPV_P2VP_Generator::BSig_CPV_P2VP_Generator() :
CompGenerator(),
params_mass_{5279.15, 0.},
params_massresol_{0.,8.},
params_timeandcp_{1.5,0.,0.5,0.7,0.,0.7,0.},
params_timeresol_{0.,0.05},
params_taggingeffs_{0.30,0.06,0.04},
params_taggingOS_{1.0,0.25,0.25,0.0,0.0},
params_taggingSS_{1.0,0.25,0.25,0.0,0.0},
comp_cat_(-1000),
tag_calib_func_omegaOS_(
[&](double eta) -> double { std::cout << "p1 " << params_taggingOS_.p1 << std::endl;return params_taggingOS_.p1*(eta-params_taggingOS_.etabar)+params_taggingOS_.p0; }
),
tag_calib_func_domegaOS_(
[&](double eta) -> double { return params_taggingOS_.dp1*(eta-params_taggingOS_.etabar)+params_taggingOS_.dp0; } ),
tag_calib_func_omegaSS_(
[&](double eta) -> double { return params_taggingSS_.p1*(eta-params_taggingSS_.etabar)+params_taggingSS_.p0; } ),
tag_calib_func_domegaSS_(
[&](double eta) -> double { return params_taggingSS_.dp1*(eta-params_taggingSS_.etabar)+params_taggingSS_.dp0; } )
{
}
BSig_CPV_P2VP_Generator::~BSig_CPV_P2VP_Generator() {
}
void BSig_CPV_P2VP_Generator::Configure(const configuration::CompConfig& comp_config) {
auto config_ptree = comp_config.model_ptree();
// Mass
auto sub_config_ptree = config_ptree.get_child("Mass");
params_mass_.mean = sub_config_ptree.get("mean", params_mass_.mean);
params_mass_.width = sub_config_ptree.get("width",params_mass_.width);
sub_config_ptree = config_ptree.get_child("MassResol");
params_massresol_.bias = sub_config_ptree.get("bias",params_massresol_.bias);
params_massresol_.sigma = sub_config_ptree.get("sigma",params_massresol_.sigma);
// TimeAndCP
sub_config_ptree = config_ptree.get_child("TimeAndCP");
params_timeandcp_.tau = sub_config_ptree.get("tau", params_timeandcp_.tau);
params_timeandcp_.dGamma = sub_config_ptree.get("dGamma", params_timeandcp_.dGamma);
params_timeandcp_.dm = sub_config_ptree.get("dm", params_timeandcp_.dm);
params_timeandcp_.Sf = sub_config_ptree.get("Sf", params_timeandcp_.Sf);
params_timeandcp_.Cf = sub_config_ptree.get("Cf", params_timeandcp_.Cf);
params_timeandcp_.Df = sub_config_ptree.get("Df", params_timeandcp_.Df);
params_timeandcp_.prod_asym = sub_config_ptree.get("prod_asym", params_timeandcp_.prod_asym);
sub_config_ptree = config_ptree.get_child("TimeResol");
params_timeresol_.bias = sub_config_ptree.get("bias" , params_timeresol_.bias );
params_timeresol_.sigma = sub_config_ptree.get("sigma", params_timeresol_.sigma );
// Tagging
sub_config_ptree = config_ptree.get_child("Tagging");
params_taggingeffs_.eff_OS = sub_config_ptree.get("eff_OS" ,params_taggingeffs_.eff_OS );
params_taggingeffs_.eff_SS = sub_config_ptree.get("eff_SS" ,params_taggingeffs_.eff_SS );
params_taggingeffs_.eff_SSOS = sub_config_ptree.get("eff_SSOS" ,params_taggingeffs_.eff_SSOS );
params_taggingOS_.p1 = sub_config_ptree.get("p1_OS" , params_taggingOS_.p1 );
params_taggingOS_.p0 = sub_config_ptree.get("p0_OS" , params_taggingOS_.p0 );
params_taggingOS_.etabar = sub_config_ptree.get("etabar_OS", params_taggingOS_.etabar);
params_taggingOS_.dp1 = sub_config_ptree.get("dp1_OS" , params_taggingOS_.dp1 );
params_taggingOS_.dp0 = sub_config_ptree.get("dp0_OS" , params_taggingOS_.dp0 );
params_taggingSS_.p1 = sub_config_ptree.get("p1_SS" , params_taggingSS_.p1 );
params_taggingSS_.p0 = sub_config_ptree.get("p0_SS" , params_taggingSS_.p0 );
params_taggingSS_.etabar = sub_config_ptree.get("etabar_SS", params_taggingSS_.etabar);
params_taggingSS_.dp1 = sub_config_ptree.get("dp1_SS" , params_taggingSS_.dp1 );
params_taggingSS_.dp0 = sub_config_ptree.get("dp0_SS" , params_taggingSS_.dp0 );
}
void BSig_CPV_P2VP_Generator::GenerateEvent(TRandom& rndm, Observables& observables) {
observables.comp_cat = comp_cat_;
GenerateMassBreitWigner(rndm, params_mass_.mean, params_mass_.width, observables.mass_true);
GenerateResolSingleGauss(rndm, params_massresol_.bias, params_massresol_.sigma, observables.mass_true, observables.mass_meas);
GenerateCPV_P2PV(rndm, params_timeandcp_.prod_asym, params_timeandcp_.tau,
params_timeandcp_.dGamma, params_timeandcp_.dm,
params_timeandcp_.Sf, params_timeandcp_.Cf, params_timeandcp_.Df,
observables.time_true, observables.tag_true);
GenerateResolSingleGauss(rndm, params_timeresol_.bias, params_timeresol_.sigma,
observables.time_true, observables.time_meas);
double random_val = rndm.Uniform();
if (random_val < params_taggingeffs_.eff_OS) {
GenerateEtaFlat(rndm, observables.eta_OS);
GenerateTag(rndm,tag_calib_func_omegaOS_,tag_calib_func_domegaOS_,
observables.tag_true, observables.eta_OS, observables.tag_OS);
observables.tag_SS = 1;
observables.eta_SS = 0.5;
observables.tag_class = 1;
}
else if (random_val < (params_taggingeffs_.eff_OS + params_taggingeffs_.eff_SS)) {
GenerateEtaFlat(rndm, observables.eta_SS);
GenerateTag(rndm,tag_calib_func_omegaSS_,tag_calib_func_domegaSS_,
observables.tag_true, observables.eta_SS, observables.tag_SS);
observables.tag_OS = 1;
observables.eta_OS = 0.5;
observables.tag_class = -1;
}
else if (random_val < ( params_taggingeffs_.eff_OS
+ params_taggingeffs_.eff_SS
+ params_taggingeffs_.eff_SSOS) ) {
GenerateEtaFlat(rndm, observables.eta_OS);
GenerateTag(rndm,tag_calib_func_omegaOS_,tag_calib_func_domegaOS_,
observables.tag_true, observables.eta_OS, observables.tag_OS);
GenerateEtaFlat(rndm, observables.eta_SS);
GenerateTag(rndm,tag_calib_func_omegaSS_,tag_calib_func_domegaSS_,
observables.tag_true, observables.eta_SS, observables.tag_SS);
observables.tag_class = 10;
}
else {
observables.tag_SS = 1;
observables.eta_SS = 0.5;
observables.tag_OS = 1;
observables.eta_OS = 0.5;
observables.tag_class = 0;
}
}
} // namespace generator
} // namespace cptoymc
<commit_msg>Fixed another round of small issues.<commit_after>#include "generator/CompGenerator.h"
// from STL
#include <iostream>
// from ROOT
#include "TRandom.h"
// from project - generator
#include "generator/generator.h"
#include "generator/Observables.h"
// from project - configuration
#include "configuration/CompConfig.h"
namespace cptoymc {
namespace generator {
CompGenerator::CompGenerator() { }
CompGenerator::~CompGenerator() { }
BSig_CPV_P2VP_Generator::BSig_CPV_P2VP_Generator() :
CompGenerator(),
params_mass_{5279.15, 0.},
params_massresol_{0.,8.},
params_timeandcp_{1.5,0.,0.5,0.7,0.,0.7,0.},
params_timeresol_{0.,0.05},
params_taggingeffs_{0.30,0.06,0.04},
params_taggingOS_{1.0,0.25,0.25,0.0,0.0},
params_taggingSS_{1.0,0.25,0.25,0.0,0.0},
comp_cat_(-1000),
tag_calib_func_omegaOS_(
[&](double eta) -> double { return params_taggingOS_.p1*(eta-params_taggingOS_.etabar)+params_taggingOS_.p0; }
),
tag_calib_func_domegaOS_(
[&](double eta) -> double { return params_taggingOS_.dp1*(eta-params_taggingOS_.etabar)+params_taggingOS_.dp0; } ),
tag_calib_func_omegaSS_(
[&](double eta) -> double { return params_taggingSS_.p1*(eta-params_taggingSS_.etabar)+params_taggingSS_.p0; } ),
tag_calib_func_domegaSS_(
[&](double eta) -> double { return params_taggingSS_.dp1*(eta-params_taggingSS_.etabar)+params_taggingSS_.dp0; } )
{
}
BSig_CPV_P2VP_Generator::~BSig_CPV_P2VP_Generator() {
}
void BSig_CPV_P2VP_Generator::Configure(const configuration::CompConfig& comp_config) {
auto config_ptree = comp_config.model_ptree();
// Mass
auto sub_config_ptree = config_ptree.get_child("Mass");
params_mass_.mean = sub_config_ptree.get("mean", params_mass_.mean);
params_mass_.width = sub_config_ptree.get("width",params_mass_.width);
sub_config_ptree = config_ptree.get_child("MassResol");
params_massresol_.bias = sub_config_ptree.get("bias",params_massresol_.bias);
params_massresol_.sigma = sub_config_ptree.get("sigma",params_massresol_.sigma);
// TimeAndCP
sub_config_ptree = config_ptree.get_child("TimeAndCP");
params_timeandcp_.tau = sub_config_ptree.get("tau", params_timeandcp_.tau);
params_timeandcp_.dGamma = sub_config_ptree.get("dGamma", params_timeandcp_.dGamma);
params_timeandcp_.dm = sub_config_ptree.get("dm", params_timeandcp_.dm);
params_timeandcp_.Sf = sub_config_ptree.get("Sf", params_timeandcp_.Sf);
params_timeandcp_.Cf = sub_config_ptree.get("Cf", params_timeandcp_.Cf);
params_timeandcp_.Df = sub_config_ptree.get("Df", params_timeandcp_.Df);
params_timeandcp_.prod_asym = sub_config_ptree.get("prod_asym", params_timeandcp_.prod_asym);
sub_config_ptree = config_ptree.get_child("TimeResol");
params_timeresol_.bias = sub_config_ptree.get("bias" , params_timeresol_.bias );
params_timeresol_.sigma = sub_config_ptree.get("sigma", params_timeresol_.sigma );
// Tagging
sub_config_ptree = config_ptree.get_child("Tagging");
params_taggingeffs_.eff_OS = sub_config_ptree.get("eff_OS" ,params_taggingeffs_.eff_OS );
params_taggingeffs_.eff_SS = sub_config_ptree.get("eff_SS" ,params_taggingeffs_.eff_SS );
params_taggingeffs_.eff_SSOS = sub_config_ptree.get("eff_SSOS" ,params_taggingeffs_.eff_SSOS );
params_taggingOS_.p1 = sub_config_ptree.get("p1_OS" , params_taggingOS_.p1 );
params_taggingOS_.p0 = sub_config_ptree.get("p0_OS" , params_taggingOS_.p0 );
params_taggingOS_.etabar = sub_config_ptree.get("etabar_OS", params_taggingOS_.etabar);
params_taggingOS_.dp1 = sub_config_ptree.get("dp1_OS" , params_taggingOS_.dp1 );
params_taggingOS_.dp0 = sub_config_ptree.get("dp0_OS" , params_taggingOS_.dp0 );
params_taggingSS_.p1 = sub_config_ptree.get("p1_SS" , params_taggingSS_.p1 );
params_taggingSS_.p0 = sub_config_ptree.get("p0_SS" , params_taggingSS_.p0 );
params_taggingSS_.etabar = sub_config_ptree.get("etabar_SS", params_taggingSS_.etabar);
params_taggingSS_.dp1 = sub_config_ptree.get("dp1_SS" , params_taggingSS_.dp1 );
params_taggingSS_.dp0 = sub_config_ptree.get("dp0_SS" , params_taggingSS_.dp0 );
}
void BSig_CPV_P2VP_Generator::GenerateEvent(TRandom& rndm, Observables& observables) {
observables.comp_cat = comp_cat_;
GenerateMassBreitWigner(rndm, params_mass_.mean, params_mass_.width, observables.mass_true);
GenerateResolSingleGauss(rndm, params_massresol_.bias, params_massresol_.sigma, observables.mass_true, observables.mass_meas);
GenerateCPV_P2PV(rndm, params_timeandcp_.prod_asym, params_timeandcp_.tau,
params_timeandcp_.dGamma, params_timeandcp_.dm,
params_timeandcp_.Sf, params_timeandcp_.Cf, params_timeandcp_.Df,
observables.time_true, observables.tag_true);
GenerateResolSingleGauss(rndm, params_timeresol_.bias, params_timeresol_.sigma,
observables.time_true, observables.time_meas);
double random_val = rndm.Uniform();
if (random_val < params_taggingeffs_.eff_OS) {
GenerateEtaFlat(rndm, observables.eta_OS);
GenerateTag(rndm,tag_calib_func_omegaOS_,tag_calib_func_domegaOS_,
observables.tag_true, observables.eta_OS, observables.tag_OS);
observables.tag_SS = 1;
observables.eta_SS = 0.5;
observables.tag_class = 1;
}
else if (random_val < (params_taggingeffs_.eff_OS + params_taggingeffs_.eff_SS)) {
GenerateEtaFlat(rndm, observables.eta_SS);
GenerateTag(rndm,tag_calib_func_omegaSS_,tag_calib_func_domegaSS_,
observables.tag_true, observables.eta_SS, observables.tag_SS);
observables.tag_OS = 1;
observables.eta_OS = 0.5;
observables.tag_class = -1;
}
else if (random_val < ( params_taggingeffs_.eff_OS
+ params_taggingeffs_.eff_SS
+ params_taggingeffs_.eff_SSOS) ) {
GenerateEtaFlat(rndm, observables.eta_OS);
GenerateTag(rndm,tag_calib_func_omegaOS_,tag_calib_func_domegaOS_,
observables.tag_true, observables.eta_OS, observables.tag_OS);
GenerateEtaFlat(rndm, observables.eta_SS);
GenerateTag(rndm,tag_calib_func_omegaSS_,tag_calib_func_domegaSS_,
observables.tag_true, observables.eta_SS, observables.tag_SS);
observables.tag_class = 10;
}
else {
observables.tag_SS = 1;
observables.eta_SS = 0.5;
observables.tag_OS = 1;
observables.eta_OS = 0.5;
observables.tag_class = 0;
}
}
} // namespace generator
} // namespace cptoymc
<|endoftext|> |
<commit_before>#include <bits/stdc++.h>
/* -------------------------------- Template -------------------------------- */
#define REP(i,n) for(int i=0;i<(int)(n);i++)
#define ALL(x) (x).begin(),(x).end()
using namespace std;
using ll = long long;
using ld = long double;
template <typename T> T &chmin(T &a, const T &b) { return a = min(a, b); }
template <typename T> T &chmax(T &a, const T &b) { return a = max(a, b); }
template<typename T> T inf = [](){ assert(false); };
template<> constexpr int inf<int> = 1e9;
template<> constexpr ll inf<ll> = 1e18;
template<> constexpr ld inf<ld> = 1e30;
/* -------------------------------- Library -------------------------------- */
/* ---------------------------------- Main ---------------------------------- */
int main() {
return 0;
}
<commit_msg>boolalpha<commit_after>#include <bits/stdc++.h>
/* -------------------------------- Template -------------------------------- */
#define REP(i,n) for(int i=0;i<(int)(n);i++)
#define ALL(x) (x).begin(),(x).end()
using namespace std;
using ll = long long;
using ld = long double;
template <typename T> T &chmin(T &a, const T &b) { return a = min(a, b); }
template <typename T> T &chmax(T &a, const T &b) { return a = max(a, b); }
template<typename T> T inf = [](){ assert(false); };
template<> constexpr int inf<int> = 1e9;
template<> constexpr ll inf<ll> = 1e18;
template<> constexpr ld inf<ld> = 1e30;
struct yes_no : numpunct<char> {
string_type do_truename() const { return "Yes"; }
string_type do_falsename() const { return "No"; }
};
/* -------------------------------- Library -------------------------------- */
/* ---------------------------------- Main ---------------------------------- */
int main() {
locale loc(locale(), new yes_no);
cout << boolalpha;
cout.imbue(loc);
return 0;
}
<|endoftext|> |
<commit_before>#include "HTTP.hpp"
#include <iostream>
using namespace boost;
using namespace boost::asio::ip; // to get 'tcp::'
void testHTTPGet(asio::io_service& io_service, tcp::resolver& resolver, asio::yield_context yield) {
RESTClient::HTTP server("httpbin.org", io_service, resolver, yield, false);
RESTClient::HTTPResponse response = server.get("/get");
using namespace std;
cout << "Got the body: " << response.body << endl;
}
int main(int argc, char *argv[]) {
asio::io_service io_service;
tcp::resolver resolver(io_service);
using namespace std::placeholders;
asio::spawn(io_service, std::bind(testHTTPGet, std::ref(io_service),
std::ref(resolver), _1));
io_service.run();
return 0;
}
<commit_msg>Just making the GET test a bit simpler for issue #7 a bit nicer<commit_after>#include "HTTP.hpp"
#include <iostream>
using namespace boost;
using namespace boost::asio::ip; // to get 'tcp::'
void testHTTPGet(asio::io_service& io_service, tcp::resolver& resolver, asio::yield_context yield) {
RESTClient::HTTP server("httpbin.org", io_service, resolver, yield, false);
RESTClient::HTTPResponse response = server.get("/get");
assert(response.body.empty());
}
int main(int argc, char *argv[]) {
asio::io_service io_service;
tcp::resolver resolver(io_service);
using namespace std::placeholders;
asio::spawn(io_service, std::bind(testHTTPGet, std::ref(io_service),
std::ref(resolver), _1));
io_service.run();
return 0;
}
<|endoftext|> |
<commit_before>//LUDUM DARE 30
#include <map>
#include <string>
#include <sstream>
#include <iostream>
#include <SFML/Window.hpp>
#include <SFML/Graphics.hpp>
namespace sf{
bool operator< (const sf::Color& c1, const sf::Color& c2){
if(c1.r < c2.r) return true; else if(c1.r > c2.r) return false;
else if(c1.g < c2.g) return true; else if(c1.g > c2.g) return false;
else if(c1.b < c2.b) return true; else if(c1.b > c2.b) return false;
else if(c1.a < c2.a) return true; else if(c1.a > c2.a) return false;
else return false;
}
}
sf::Color getColisionColor(float posx, float posy, sf::Image& img, sf::Sprite& bSprite){
return img.getPixel( posx/bSprite.getScale().x, posy/bSprite.getScale().y);
}
int main(int argc, const char* argv[]){
sf::Vector2f v = sf::Vector2f(0,0);
sf::RenderWindow window(sf::VideoMode::getDesktopMode(), "Gravity");
const float g = (int)window.getSize().y*2 ;
sf::RectangleShape r(sf::Vector2f(window.getSize().x/10, window.getSize().y/10));
r.setPosition(0,0); r.setFillColor(sf::Color::White);
sf::Clock timer;
float deltatime = 0;
float ground = window.getSize().y-4; // float ground = window.getSize().y*6/7;
sf::Text text; sf::Font font;
if(! font.loadFromFile("font.ttf")) std::cout << "penguin" << std::endl;
text.setFont(font); text.setPosition(0,0); text.setString("penguin <3");
text.setColor(sf::Color(255,255,255));
sf::Image bimg;
sf::Texture bTex;
sf::Sprite bSprite;
std::map<sf::Color, sf::Time> colorsColiding;
int pantalla = 0;
if(argc > 1) pantalla = atoi(argv[1]);
bool reboot = false;
bool needshiet = true;
//GAME LOOP
while(window.isOpen()){
if(needshiet){
v = sf::Vector2f(0,0);
colorsColiding.clear();
r.setPosition(0,0);
std::stringstream s;
s << "board" << pantalla;
std::string board = s.str();
if(!bimg.loadFromFile(board+".png")) std::cout << "I CAN'T LOAD BOARD IMAGE" << std::endl;
if(!bTex.loadFromFile(board+".png")) std::cout << "I CAN'T LOAD BOARD texture" << std::endl;
bSprite.setTexture(bTex, true);
bSprite.scale(window.getSize().x/bSprite.getGlobalBounds().width ,
window.getSize().y/bSprite.getGlobalBounds().height);
needshiet = false;
deltatime = 0;
}
deltatime = timer.restart().asSeconds();
sf::Event event;
while(window.pollEvent(event)) if (event.type == sf::Event::Closed) window.close();
if(r.getPosition().y > 0){
if(sf::Keyboard::isKeyPressed(sf::Keyboard::Up )) v.y = (int)window.getSize().y/2 * -1;
if(sf::Keyboard::isKeyPressed(sf::Keyboard::W )) v.y = (int)window.getSize().y/2 * -1;
if(sf::Keyboard::isKeyPressed(sf::Keyboard::Space)) v.y = (int)window.getSize().y * -1;
}
if(sf::Keyboard::isKeyPressed(sf::Keyboard::Left )) v.x = (int)window.getSize().x/20 * -1;
if(sf::Keyboard::isKeyPressed(sf::Keyboard::A )) v.x = (int)window.getSize().x/20 * -1;
if(sf::Keyboard::isKeyPressed(sf::Keyboard::Right)) v.x = window.getSize().x/20;
if(sf::Keyboard::isKeyPressed(sf::Keyboard::D)) v.x = window.getSize().x/20;
if(sf::Keyboard::isKeyPressed(sf::Keyboard::R)) { reboot = true; v.x = 0; }
if(sf::Keyboard::isKeyPressed(sf::Keyboard::Escape)) window.close();
r.move(v * deltatime);
if(r.getPosition().y < 0) {v.y += g*deltatime;}
if( (r.getPosition().y + r.getSize().y) < ground || v.y < 0) v.y += g *deltatime;
else {
r.setPosition(r.getPosition().x, ground - r.getSize().y);
v.y = 0;
}
r.setOutlineColor(sf::Color::White);
r.setOutlineThickness(1);
if(r.getPosition().x < 1) r.setPosition(1, r.getPosition().y);
if(r.getPosition().x + r.getSize().x+3 > window.getSize().x) r.setPosition(window.getSize().x-r.getSize().x-3, r.getPosition().y);
sf::VertexArray pj(sf::Quads, 4);
sf::FloatRect fr = r.getGlobalBounds();
pj[0].position = sf::Vector2<float>(r.getPosition().x, r.getPosition().y);
pj[1].position = sf::Vector2<float>(r.getPosition().x + fr.width-2, r.getPosition().y);
pj[3].position = sf::Vector2<float>(r.getPosition().x, r.getPosition().y + fr.height-2);
pj[2].position = sf::Vector2<float>(r.getPosition().x + fr.width-2, r.getPosition().y + fr.height-2);
for(int i = 0; i < 4; ++i) pj[i].color = sf::Color::Black;
if(r.getPosition().y >= 0 && r.getPosition().x+r.getSize().x < window.getSize().x-1 && r.getPosition().x > 1 && r.getPosition().y+r.getSize().y < window.getSize().y) {
sf::Color color = getColisionColor(r.getPosition().x, r.getPosition().y, bimg, bSprite);
if(color != sf::Color::Black) colorsColiding[color] += sf::seconds(deltatime);
sf::Color color2 = getColisionColor(r.getPosition().x + fr.width, r.getPosition().y, bimg, bSprite);
if(color2 != sf::Color::Black) colorsColiding[color2] += sf::seconds(deltatime);
pj[0].color = color; pj[1].color = color2;
sf::Color color3 = getColisionColor(r.getPosition().x, r.getPosition().y + fr.height , bimg, bSprite);
if(color3 != sf::Color::Black) colorsColiding[color3] += sf::seconds(deltatime);
sf::Color color4 = getColisionColor(r.getPosition().x + fr.width, r.getPosition().y + fr.height, bimg, bSprite);
if(color4 != sf::Color::Black) colorsColiding[color4] += sf::seconds(deltatime);
pj[3].color = color3; pj[2].color = color4;
}
else if(r.getPosition().y+fr.height >= 0){
sf::Color color3 = getColisionColor(r.getPosition().x, r.getPosition().y + fr.height , bimg, bSprite);
if(color3 != sf::Color::Black) colorsColiding[color3] += sf::seconds(deltatime);
sf::Color color4 = getColisionColor(r.getPosition().x + fr.width, r.getPosition().y + fr.height, bimg, bSprite);
if(color4 != sf::Color::Black) colorsColiding[color4] += sf::seconds(deltatime);
pj[3].color = color3; pj[2].color = color4;
}
std::map<std::string, int> colorTimers;
colorTimers["Red:"] = colorTimers["Yellow:"] = colorTimers["Green:"] = colorTimers["Blue:"] = 0;
for (std::map<sf::Color, sf::Time>::iterator it=colorsColiding.begin(); it!=colorsColiding.end(); ++it){
std::string col = "wat:";
sf::Color aux = (it->first);
if(aux.r >= aux.g and aux.r >= aux.b) {
if(aux.g < 100) col = "Red:";
else col = "Yellow:";
}
else if(aux.g >= aux.r and aux.g >= aux.b) col = "Green:";
else if(aux.b >= aux.g and aux.b >= aux.r) col = "Blue:";
if((int)(it->second).asSeconds() > 0)
colorTimers[col] += (int)(it->second).asSeconds();
}
std::stringstream ss;
for (std::map<std::string, int>::iterator it=colorTimers.begin(); it!=colorTimers.end(); ++it){
if(it->second > 0)
ss << " " << it->first << "" << it->second;
}
std::string str = ss.str();
text.setString(str);
sf::Text textBg = text;
textBg.setScale(1.1,1.1);
textBg.setColor(sf::Color(100,100,100));
int max = 0;
int qtty = 0;
int min = 99999999;
if(colorsColiding[sf::Color::White] != sf::seconds(0.0) || reboot){
for (std::map<std::string, int>::iterator it=colorTimers.begin(); it!=colorTimers.end(); ++it){
int num = (int)(it->second);
if(num > 0) {
if(num > max) max = num; if(num < min) min = num;
++qtty;
}
}
if((max - min <= 3 && qtty >= 4) || reboot || pantalla < 2) {
std::ostringstream oss;
oss << max;
std::string strn = oss.str();
if(!reboot) str = "YouWonTheGame! punctuation = " + strn; //text.setString("YouWonTheGame! punctuation = " + strn);
else str = " Nice try! "; //text.setString(" Nice try!");
window.clear();
window.draw(bSprite);
for(int i = 0; i < str.size(); ++i) {
text.setString(str[i]);
textBg.setString(str[i]);
text.setPosition(text.getCharacterSize()*i, 0);
textBg.setPosition(text.getCharacterSize()*i, 0);
window.draw(textBg, sf::BlendAlpha);
window.draw(text, sf::BlendAlpha);
}
window.draw(r);
window.display();
sf::Clock c; float t = 0;
while(t < 3){
t += c.restart().asSeconds();
timer.restart();
}
if(!reboot) ++pantalla;
needshiet = true;
reboot = false;
}
else reboot = true;
}
window.clear();
window.draw(bSprite);
for(int i = 0; i < str.size(); ++i) {
text.setString(str[i]);
textBg.setString(str[i]);
text.setPosition(text.getCharacterSize()/1.5*i, 0);
textBg.setPosition(text.getCharacterSize()/1.5*i, 0);
window.draw(textBg, sf::BlendAlpha);
window.draw(text, sf::BlendAlpha);
}
window.draw(r);
window.draw(pj, sf::BlendAlpha);
window.display();
}
}
<commit_msg>fast on introduction<commit_after>//LUDUM DARE 30
#include <map>
#include <string>
#include <sstream>
#include <iostream>
#include <SFML/Window.hpp>
#include <SFML/Graphics.hpp>
namespace sf{
bool operator< (const sf::Color& c1, const sf::Color& c2){
if(c1.r < c2.r) return true; else if(c1.r > c2.r) return false;
else if(c1.g < c2.g) return true; else if(c1.g > c2.g) return false;
else if(c1.b < c2.b) return true; else if(c1.b > c2.b) return false;
else if(c1.a < c2.a) return true; else if(c1.a > c2.a) return false;
else return false;
}
}
sf::Color getColisionColor(float posx, float posy, sf::Image& img, sf::Sprite& bSprite){
return img.getPixel( posx/bSprite.getScale().x, posy/bSprite.getScale().y);
}
int main(int argc, const char* argv[]){
sf::Vector2f v = sf::Vector2f(0,0);
sf::RenderWindow window(sf::VideoMode::getDesktopMode(), "Gravity");
const float g = (int)window.getSize().y*2 ;
sf::RectangleShape r(sf::Vector2f(window.getSize().x/10, window.getSize().y/10));
r.setPosition(0,0); r.setFillColor(sf::Color::White);
sf::Clock timer;
float deltatime = 0;
float ground = window.getSize().y-4; // float ground = window.getSize().y*6/7;
sf::Text text; sf::Font font;
if(! font.loadFromFile("font.ttf")) std::cout << "penguin" << std::endl;
text.setFont(font); text.setPosition(0,0); text.setString("penguin <3");
text.setColor(sf::Color(255,255,255));
sf::Image bimg;
sf::Texture bTex;
sf::Sprite bSprite;
std::map<sf::Color, sf::Time> colorsColiding;
int pantalla = 0;
if(argc > 1) pantalla = atoi(argv[1]);
bool reboot = false;
bool needshiet = true;
//GAME LOOP
while(window.isOpen()){
if(needshiet){
v = sf::Vector2f(0,0);
colorsColiding.clear();
r.setPosition(0,0);
std::stringstream s;
s << "board" << pantalla;
std::string board = s.str();
if(!bimg.loadFromFile(board+".png")) std::cout << "I CAN'T LOAD BOARD IMAGE" << std::endl;
if(!bTex.loadFromFile(board+".png")) std::cout << "I CAN'T LOAD BOARD texture" << std::endl;
bSprite.setTexture(bTex, true);
bSprite.scale(window.getSize().x/bSprite.getGlobalBounds().width ,
window.getSize().y/bSprite.getGlobalBounds().height);
needshiet = false;
deltatime = 0;
}
deltatime = timer.restart().asSeconds();
sf::Event event;
while(window.pollEvent(event)) if (event.type == sf::Event::Closed) window.close();
if(r.getPosition().y > 0){
if(sf::Keyboard::isKeyPressed(sf::Keyboard::Up )) v.y = (int)window.getSize().y/2 * -1;
if(sf::Keyboard::isKeyPressed(sf::Keyboard::W )) v.y = (int)window.getSize().y/2 * -1;
if(sf::Keyboard::isKeyPressed(sf::Keyboard::Space)) v.y = (int)window.getSize().y * -1;
}
if(sf::Keyboard::isKeyPressed(sf::Keyboard::Left )) v.x = (int)window.getSize().x/20 * -1;
if(sf::Keyboard::isKeyPressed(sf::Keyboard::A )) v.x = (int)window.getSize().x/20 * -1;
if(sf::Keyboard::isKeyPressed(sf::Keyboard::Right)) v.x = window.getSize().x/20;
if(sf::Keyboard::isKeyPressed(sf::Keyboard::D)) v.x = window.getSize().x/20;
if(sf::Keyboard::isKeyPressed(sf::Keyboard::R)) { reboot = true; v.x = 0; }
if(sf::Keyboard::isKeyPressed(sf::Keyboard::Escape)) window.close();
if(pantalla < 2) r.move(v*3.0f * deltatime);
else r.move(v * deltatime);
if(r.getPosition().y < 0) {v.y += g*deltatime;}
if( (r.getPosition().y + r.getSize().y) < ground || v.y < 0) v.y += g *deltatime;
else {
r.setPosition(r.getPosition().x, ground - r.getSize().y);
v.y = 0;
}
r.setOutlineColor(sf::Color::White);
r.setOutlineThickness(1);
if(r.getPosition().x < 1) r.setPosition(1, r.getPosition().y);
if(r.getPosition().x + r.getSize().x+3 > window.getSize().x) r.setPosition(window.getSize().x-r.getSize().x-3, r.getPosition().y);
sf::VertexArray pj(sf::Quads, 4);
sf::FloatRect fr = r.getGlobalBounds();
pj[0].position = sf::Vector2<float>(r.getPosition().x, r.getPosition().y);
pj[1].position = sf::Vector2<float>(r.getPosition().x + fr.width-2, r.getPosition().y);
pj[3].position = sf::Vector2<float>(r.getPosition().x, r.getPosition().y + fr.height-2);
pj[2].position = sf::Vector2<float>(r.getPosition().x + fr.width-2, r.getPosition().y + fr.height-2);
for(int i = 0; i < 4; ++i) pj[i].color = sf::Color::Black;
if(r.getPosition().y >= 0 && r.getPosition().x+r.getSize().x < window.getSize().x-1 && r.getPosition().x > 1 && r.getPosition().y+r.getSize().y < window.getSize().y) {
sf::Color color = getColisionColor(r.getPosition().x, r.getPosition().y, bimg, bSprite);
if(color != sf::Color::Black) colorsColiding[color] += sf::seconds(deltatime);
sf::Color color2 = getColisionColor(r.getPosition().x + fr.width, r.getPosition().y, bimg, bSprite);
if(color2 != sf::Color::Black) colorsColiding[color2] += sf::seconds(deltatime);
pj[0].color = color; pj[1].color = color2;
sf::Color color3 = getColisionColor(r.getPosition().x, r.getPosition().y + fr.height , bimg, bSprite);
if(color3 != sf::Color::Black) colorsColiding[color3] += sf::seconds(deltatime);
sf::Color color4 = getColisionColor(r.getPosition().x + fr.width, r.getPosition().y + fr.height, bimg, bSprite);
if(color4 != sf::Color::Black) colorsColiding[color4] += sf::seconds(deltatime);
pj[3].color = color3; pj[2].color = color4;
}
else if(r.getPosition().y+fr.height >= 0){
sf::Color color3 = getColisionColor(r.getPosition().x, r.getPosition().y + fr.height , bimg, bSprite);
if(color3 != sf::Color::Black) colorsColiding[color3] += sf::seconds(deltatime);
sf::Color color4 = getColisionColor(r.getPosition().x + fr.width, r.getPosition().y + fr.height, bimg, bSprite);
if(color4 != sf::Color::Black) colorsColiding[color4] += sf::seconds(deltatime);
pj[3].color = color3; pj[2].color = color4;
}
std::map<std::string, int> colorTimers;
colorTimers["Red:"] = colorTimers["Yellow:"] = colorTimers["Green:"] = colorTimers["Blue:"] = 0;
for (std::map<sf::Color, sf::Time>::iterator it=colorsColiding.begin(); it!=colorsColiding.end(); ++it){
std::string col = "wat:";
sf::Color aux = (it->first);
if(aux.r >= aux.g and aux.r >= aux.b) {
if(aux.g < 100) col = "Red:";
else col = "Yellow:";
}
else if(aux.g >= aux.r and aux.g >= aux.b) col = "Green:";
else if(aux.b >= aux.g and aux.b >= aux.r) col = "Blue:";
if((int)(it->second).asSeconds() > 0)
colorTimers[col] += (int)(it->second).asSeconds();
}
std::stringstream ss;
for (std::map<std::string, int>::iterator it=colorTimers.begin(); it!=colorTimers.end(); ++it){
if(it->second > 0)
ss << " " << it->first << "" << it->second;
}
std::string str = ss.str();
text.setString(str);
sf::Text textBg = text;
textBg.setScale(1.1,1.1);
textBg.setColor(sf::Color(100,100,100));
int max = 0;
int qtty = 0;
int min = 99999999;
if(colorsColiding[sf::Color::White] != sf::seconds(0.0) || reboot){
for (std::map<std::string, int>::iterator it=colorTimers.begin(); it!=colorTimers.end(); ++it){
int num = (int)(it->second);
if(num > 0) {
if(num > max) max = num; if(num < min) min = num;
++qtty;
}
}
if((max - min <= 3 && qtty >= 4) || reboot || pantalla < 2) {
std::ostringstream oss;
oss << max;
std::string strn = oss.str();
if(!reboot) str = "YouWonTheGame! punctuation = " + strn; //text.setString("YouWonTheGame! punctuation = " + strn);
else str = " Nice try! "; //text.setString(" Nice try!");
window.clear();
window.draw(bSprite);
for(int i = 0; i < str.size(); ++i) {
text.setString(str[i]);
textBg.setString(str[i]);
text.setPosition(text.getCharacterSize()*i, 0);
textBg.setPosition(text.getCharacterSize()*i, 0);
window.draw(textBg, sf::BlendAlpha);
window.draw(text, sf::BlendAlpha);
}
window.draw(r);
window.display();
sf::Clock c; float t = 0;
while(t < 3){
t += c.restart().asSeconds();
timer.restart();
}
if(!reboot) ++pantalla;
needshiet = true;
reboot = false;
}
else reboot = true;
}
window.clear();
window.draw(bSprite);
window.draw(r);
window.draw(pj, sf::BlendAlpha);
for(int i = 0; i < str.size(); ++i) {
text.setString(str[i]);
textBg.setString(str[i]);
text.setPosition(text.getCharacterSize()/1.5*i, 0);
textBg.setPosition(text.getCharacterSize()/1.5*i, 0);
window.draw(textBg, sf::BlendAlpha);
window.draw(text, sf::BlendAlpha);
}
window.display();
}
}
<|endoftext|> |
<commit_before>// Copyright (c) 2014 The Bitcoin developers
// Distributed under the MIT/X11 software license, see the accompanying
// file COPYING or http://www.opensource.org/licenses/mit-license.php.
#include "timedata.h"
#include "netbase.h"
#include "sync.h"
#include "ui_interface.h"
#include "util.h"
#include <boost/foreach.hpp>
using namespace std;
static CCriticalSection cs_nTimeOffset;
static int64_t nTimeOffset = 0;
//
// "Never go to sea with two chronometers; take one or three."
// Our three time sources are:
// - System clock
// - Median of other nodes clocks
// - The user (asking the user to fix the system clock if the first two disagree)
//
//
int64_t GetTimeOffset()
{
LOCK(cs_nTimeOffset);
return nTimeOffset;
}
int64_t GetAdjustedTime()
{
return GetTime() + GetTimeOffset();
}
void AddTimeData(const CNetAddr& ip, int64_t nOffsetSample)
{
LOCK(cs_nTimeOffset);
// Ignore duplicates
static set<CNetAddr> setKnown;
if (!setKnown.insert(ip).second)
return;
// Add data
static CMedianFilter<int64_t> vTimeOffsets(200,0);
vTimeOffsets.input(nOffsetSample);
LogPrintf("Added time data, samples %d, offset %+d (%+d minutes)\n", vTimeOffsets.size(), nOffsetSample, nOffsetSample/60);
// There is a known issue here (see issue #4521):
//
// - The structure vTimeOffsets contains up to 200 elements, after which
// any new element added to it will not increase its size, replacing the
// oldest element.
//
// - The condition to update nTimeOffset includes checking whether the
// number of elements in vTimeOffsets is odd, which will never happen after
// there are 200 elements.
//
// But in this case the 'bug' is protective against some attacks, and may
// actually explain why we've never seen attacks which manipulate the
// clock offset.
//
// So we should hold off on fixing this and clean it up as part of
// a timing cleanup that strengthens it in a number of other ways.
//
if (vTimeOffsets.size() >= 5 && vTimeOffsets.size() % 2 == 1)
{
int64_t nMedian = vTimeOffsets.median();
std::vector<int64_t> vSorted = vTimeOffsets.sorted();
// Only let other nodes change our time by so much
if (abs64(nMedian) < 70 * 60)
{
nTimeOffset = nMedian;
}
else
{
nTimeOffset = 0;
static bool fDone;
if (!fDone)
{
// If nobody has a time different than ours but within 5 minutes of ours, give a warning
bool fMatch = false;
BOOST_FOREACH(int64_t nOffset, vSorted)
if (nOffset != 0 && abs64(nOffset) < 5 * 60)
fMatch = true;
if (!fMatch)
{
fDone = true;
string strMessage = _("Warning: Please check that your computer's date and time are correct! If your clock is wrong BlackCoin will not work properly.");
strMiscWarning = strMessage;
LogPrintf("*** %s\n", strMessage);
uiInterface.ThreadSafeMessageBox(strMessage, "", CClientUIInterface::MSG_WARNING);
}
}
}
if (fDebug) {
BOOST_FOREACH(int64_t n, vSorted)
LogPrintf("%+d ", n);
LogPrintf("| ");
}
LogPrintf("nTimeOffset = %+d (%+d minutes)\n", nTimeOffset, nTimeOffset/60);
}
}
<commit_msg>Do not store more than 200 timedata samples.<commit_after>// Copyright (c) 2014 The Bitcoin developers
// Distributed under the MIT/X11 software license, see the accompanying
// file COPYING or http://www.opensource.org/licenses/mit-license.php.
#include "timedata.h"
#include "netbase.h"
#include "sync.h"
#include "ui_interface.h"
#include "util.h"
#include <boost/foreach.hpp>
using namespace std;
static CCriticalSection cs_nTimeOffset;
static int64_t nTimeOffset = 0;
//
// "Never go to sea with two chronometers; take one or three."
// Our three time sources are:
// - System clock
// - Median of other nodes clocks
// - The user (asking the user to fix the system clock if the first two disagree)
//
//
int64_t GetTimeOffset()
{
LOCK(cs_nTimeOffset);
return nTimeOffset;
}
int64_t GetAdjustedTime()
{
return GetTime() + GetTimeOffset();
}
#define BITCOIN_TIMEDATA_MAX_SAMPLES 200
void AddTimeData(const CNetAddr& ip, int64_t nOffsetSample)
{
LOCK(cs_nTimeOffset);
// Ignore duplicates
static set<CNetAddr> setKnown;
if (setKnown.size() == BITCOIN_TIMEDATA_MAX_SAMPLES)
return;
if (!setKnown.insert(ip).second)
return;
// Add data
static CMedianFilter<int64_t> vTimeOffsets(BITCOIN_TIMEDATA_MAX_SAMPLES, 0);
vTimeOffsets.input(nOffsetSample);
LogPrintf("Added time data, samples %d, offset %+d (%+d minutes)\n", vTimeOffsets.size(), nOffsetSample, nOffsetSample/60);
// There is a known issue here (see issue #4521):
//
// - The structure vTimeOffsets contains up to 200 elements, after which
// any new element added to it will not increase its size, replacing the
// oldest element.
//
// - The condition to update nTimeOffset includes checking whether the
// number of elements in vTimeOffsets is odd, which will never happen after
// there are 200 elements.
//
// But in this case the 'bug' is protective against some attacks, and may
// actually explain why we've never seen attacks which manipulate the
// clock offset.
//
// So we should hold off on fixing this and clean it up as part of
// a timing cleanup that strengthens it in a number of other ways.
//
if (vTimeOffsets.size() >= 5 && vTimeOffsets.size() % 2 == 1)
{
int64_t nMedian = vTimeOffsets.median();
std::vector<int64_t> vSorted = vTimeOffsets.sorted();
// Only let other nodes change our time by so much
if (abs64(nMedian) < 70 * 60)
{
nTimeOffset = nMedian;
}
else
{
nTimeOffset = 0;
static bool fDone;
if (!fDone)
{
// If nobody has a time different than ours but within 5 minutes of ours, give a warning
bool fMatch = false;
BOOST_FOREACH(int64_t nOffset, vSorted)
if (nOffset != 0 && abs64(nOffset) < 5 * 60)
fMatch = true;
if (!fMatch)
{
fDone = true;
string strMessage = _("Warning: Please check that your computer's date and time are correct! If your clock is wrong BlackCoin will not work properly.");
strMiscWarning = strMessage;
LogPrintf("*** %s\n", strMessage);
uiInterface.ThreadSafeMessageBox(strMessage, "", CClientUIInterface::MSG_WARNING);
}
}
}
if (fDebug) {
BOOST_FOREACH(int64_t n, vSorted)
LogPrintf("%+d ", n);
LogPrintf("| ");
}
LogPrintf("nTimeOffset = %+d (%+d minutes)\n", nTimeOffset, nTimeOffset/60);
}
}
<|endoftext|> |
<commit_before>///////////////////////////////////////////////////////////////////////////////
// BSD 3-Clause License
//
// Copyright (c) 2019, OpenROAD
// All rights reserved.
//
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions are met:
//
// * Redistributions of source code must retain the above copyright notice, this
// list of conditions and the following disclaimer.
//
// * Redistributions in binary form must reproduce the above copyright notice,
// this list of conditions and the following disclaimer in the documentation
// and/or other materials provided with the distribution.
//
// * Neither the name of the copyright holder 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 HOLDER OR CONTRIBUTORS BE
// LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
// CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
// SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
// INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
// CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
// ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
// POSSIBILITY OF SUCH DAMAGE.
#include "displayControls.h"
#include <QHeaderView>
#include <QKeyEvent>
#include <QLineEdit>
#include <QPainter>
#include <QSettings>
#include <vector>
#include "db.h"
#include "openroad/InitOpenRoad.hh"
Q_DECLARE_METATYPE(odb::dbTechLayer*);
namespace gui {
using namespace odb;
PatternButton::PatternButton(Qt::BrushStyle pattern, QWidget* parent)
: QRadioButton(parent), pattern_(pattern)
{
setFixedWidth(100);
}
void PatternButton::paintEvent(QPaintEvent* event)
{
QRadioButton::paintEvent(event);
auto qp = QPainter(this);
auto brush = QBrush(QColor("black"), pattern_);
qp.setBrush(brush);
auto btnRect = rect();
btnRect.adjust(18, 2, -1, -1);
qp.drawRect(btnRect);
qp.end();
}
DisplayColorDialog::DisplayColorDialog(QColor color,
Qt::BrushStyle pattern,
QWidget* parent)
: QDialog(parent), color_(color), pattern_(pattern)
{
buildUI();
}
void DisplayColorDialog::buildUI()
{
colorDialog_ = new QColorDialog(this);
colorDialog_->setOptions(QColorDialog::DontUseNativeDialog);
colorDialog_->setWindowFlags(Qt::Widget);
colorDialog_->setCurrentColor(color_);
patternGroupBox_ = new QGroupBox("Layer Pattern");
gridLayout_ = new QGridLayout();
gridLayout_->setColumnStretch(2, 4);
int rowIndex = 0;
for (auto& patGrp : DisplayColorDialog::brushPatterns) {
int colIndex = 0;
for (auto pat : patGrp) {
PatternButton* pBtn = new PatternButton(pat);
patternButtons_.push_back(pBtn);
if (pat == pattern_)
pBtn->setChecked(true);
else
pBtn->setChecked(false);
gridLayout_->addWidget(pBtn, rowIndex, colIndex);
++colIndex;
}
++rowIndex;
}
patternGroupBox_->setLayout(gridLayout_);
connect(colorDialog_, SIGNAL(accepted()), this, SLOT(acceptDialog()));
connect(colorDialog_, SIGNAL(rejected()), this, SLOT(rejectDialog()));
mainLayout_ = new QVBoxLayout();
mainLayout_->addWidget(patternGroupBox_);
mainLayout_->addWidget(colorDialog_);
setLayout(mainLayout_);
setWindowTitle("Layer Config");
setFixedSize(600, width() - 20);
}
DisplayColorDialog::~DisplayColorDialog()
{
}
Qt::BrushStyle DisplayColorDialog::getSelectedPattern() const
{
for (auto patBtn : patternButtons_) {
if (patBtn->isChecked())
return patBtn->pattern();
}
return Qt::SolidPattern;
}
void DisplayColorDialog::acceptDialog()
{
color_ = colorDialog_->selectedColor();
accept();
}
void DisplayColorDialog::rejectDialog()
{
reject();
}
DisplayControls::DisplayControls(QWidget* parent)
: QDockWidget("Display Control", parent),
view_(new QTreeView(parent)),
model_(new QStandardItemModel(0, 4, parent)),
tech_inited_(false),
fills_visible_(false),
tracks_visible_pref_(false),
tracks_visible_non_pref_(false),
rows_visible_(false),
nets_signal_visible_(true),
nets_special_visible_(true),
nets_power_visible_(true),
nets_ground_visible_(true),
nets_clock_visible_(true)
{
setObjectName("layers"); // for settings
model_->setHorizontalHeaderLabels({"", "", "V", "S"});
view_->setModel(model_);
QHeaderView* header = view_->header();
header->setSectionResizeMode(Name, QHeaderView::Stretch);
header->setSectionResizeMode(Swatch, QHeaderView::ResizeToContents);
header->setSectionResizeMode(Visible, QHeaderView::ResizeToContents);
header->setSectionResizeMode(Selectable, QHeaderView::ResizeToContents);
layers_ = makeItem(
"Layers",
model_,
Qt::Checked,
[this](bool visible) { toggleAllChildren(visible, layers_, Visible); },
[this](bool selectable) {
toggleAllChildren(selectable, layers_, Selectable);
});
view_->expand(layers_->index());
// nets patterns
nets_ = makeItem("Nets", model_, Qt::Checked, [this](bool visible) {
toggleAllChildren(visible, nets_, Visible);
});
nets_signal_ = makeItem("Signal", nets_, Qt::Checked, [this](bool visible) {
nets_signal_visible_ = visible;
});
nets_special_ = makeItem("Special", nets_, Qt::Checked, [this](bool visible) {
nets_special_visible_ = visible;
});
nets_power_ = makeItem("Power", nets_, Qt::Checked, [this](bool visible) {
nets_power_visible_ = visible;
});
nets_ground_ = makeItem("Ground", nets_, Qt::Checked, [this](bool visible) {
nets_ground_visible_ = visible;
});
nets_clock_ = makeItem("Clock", nets_, Qt::Checked, [this](bool visible) {
nets_clock_visible_ = visible;
});
// Rows
rows_ = makeItem("Rows", model_, Qt::Unchecked, [this](bool visible) {
rows_visible_ = visible;
});
// Track patterns
tracks_ = makeItem("Tracks", model_, Qt::Unchecked, [this](bool visible) {
toggleAllChildren(visible, tracks_, Visible);
});
tracks_pref_ = makeItem("Pref", tracks_, Qt::Unchecked, [this](bool visible) {
tracks_visible_pref_ = visible;
});
tracks_non_pref_
= makeItem("Non Pref", tracks_, Qt::Unchecked, [this](bool visible) {
tracks_visible_non_pref_ = visible;
});
// Track patterns
misc_ = makeItem("Misc", model_, Qt::Unchecked, [this](bool visible) {
toggleAllChildren(visible, misc_, Visible);
});
fills_ = makeItem("Fills", misc_, Qt::Unchecked, [this](bool visible) {
fills_visible_ = visible;
});
setWidget(view_);
connect(model_,
SIGNAL(itemChanged(QStandardItem*)),
this,
SLOT(itemChanged(QStandardItem*)));
connect(view_,
SIGNAL(doubleClicked(const QModelIndex&)),
this,
SLOT(displayItemDblClicked(const QModelIndex&)));
}
void DisplayControls::toggleAllChildren(bool checked,
QStandardItem* parent,
Column column)
{
Qt::CheckState state = checked ? Qt::Checked : Qt::Unchecked;
for (int row = 0; row < parent->rowCount(); ++row) {
auto child = parent->child(row, column);
child->setCheckState(state);
}
emit changed();
}
void DisplayControls::itemChanged(QStandardItem* item)
{
if (item->isCheckable() == false) {
emit changed();
return;
}
bool checked = item->checkState() == Qt::Checked;
Callback callback = item->data().value<Callback>();
callback.action(checked);
emit changed();
}
void DisplayControls::displayItemDblClicked(const QModelIndex& index)
{
if (index.column() == 1) {
auto colorItem = model_->itemFromIndex(index);
QVariant techLayerData = colorItem->data(Qt::UserRole);
if (!techLayerData.isValid())
return;
auto techLayer
= static_cast<odb::dbTechLayer*>(techLayerData.value<void*>());
if (techLayer == nullptr)
return;
QColor colorVal = color(techLayer);
Qt::BrushStyle patternVal = pattern(techLayer);
DisplayColorDialog dispDlg(colorVal, patternVal);
dispDlg.exec();
QColor chosenColor = dispDlg.getSelectedColor();
if (chosenColor.isValid()) {
QPixmap swatch(20, 20);
swatch.fill(chosenColor);
colorItem->setIcon(QIcon(swatch));
auto cutLayer = index.siblingAtRow(index.row() + 1);
if (cutLayer.isValid()) {
auto cutColorItem = model_->itemFromIndex(cutLayer);
cutColorItem->setIcon(QIcon(swatch));
}
if (chosenColor != colorVal
|| layer_pattern_[techLayer] != dispDlg.getSelectedPattern()) {
layer_color_[techLayer] = chosenColor;
layer_pattern_[techLayer] = dispDlg.getSelectedPattern();
view_->repaint();
emit changed();
}
}
}
}
void DisplayControls::setDb(odb::dbDatabase* db)
{
db_ = db;
if (!db) {
return;
}
dbTech* tech = db->getTech();
if (!tech) {
return;
}
techInit();
for (dbTechLayer* layer : tech->getLayers()) {
dbTechLayerType type = layer->getType();
if (type == dbTechLayerType::ROUTING || type == dbTechLayerType::CUT) {
makeItem(
QString::fromStdString(layer->getName()),
layers_,
Qt::Checked,
[this, layer](bool visible) { layer_visible_[layer] = visible; },
[this, layer](bool select) { layer_selectable_[layer] = select; },
color(layer),
type == dbTechLayerType::CUT ? NULL : layer);
}
}
emit changed();
}
template <typename T>
QStandardItem* DisplayControls::makeItem(
const QString& text,
T* parent,
Qt::CheckState checked,
const std::function<void(bool)>& visibility_action,
const std::function<void(bool)>& select_action,
const QColor& color,
odb::dbTechLayer* techLayer)
{
QStandardItem* nameItem = new QStandardItem(text);
nameItem->setEditable(false);
QPixmap swatch(20, 20);
swatch.fill(color);
QStandardItem* colorItem = new QStandardItem(QIcon(swatch), "");
QString colorName = color.name(QColor::HexArgb);
colorItem->setEditable(false);
colorItem->setCheckable(false);
if (techLayer != nullptr) {
QVariant techLayerData(QVariant::fromValue(static_cast<void*>(techLayer)));
colorItem->setData(techLayerData, Qt::UserRole);
}
QStandardItem* visibilityItem = new QStandardItem("");
visibilityItem->setCheckable(true);
visibilityItem->setEditable(false);
visibilityItem->setCheckState(checked);
visibilityItem->setData(QVariant::fromValue(Callback({visibility_action})));
QStandardItem* selectItem = nullptr;
if (select_action) {
selectItem = new QStandardItem("");
selectItem->setCheckable(true);
selectItem->setCheckState(checked);
selectItem->setEditable(false);
selectItem->setData(QVariant::fromValue(Callback({select_action})));
}
parent->appendRow({nameItem, colorItem, visibilityItem, selectItem});
return nameItem;
}
QColor DisplayControls::color(const odb::dbTechLayer* layer)
{
return layer_color_.at(layer);
}
Qt::BrushStyle DisplayControls::pattern(const odb::dbTechLayer* layer)
{
return layer_pattern_.at(layer);
}
bool DisplayControls::isVisible(const odb::dbTechLayer* layer)
{
auto it = layer_visible_.find(layer);
if (it != layer_visible_.end()) {
return it->second;
}
return false;
}
bool DisplayControls::isNetVisible(odb::dbNet* net)
{
switch (net->getSigType()) {
case dbSigType::SIGNAL:
return nets_signal_visible_;
case dbSigType::POWER:
return nets_power_visible_;
case dbSigType::GROUND:
return nets_ground_visible_;
case dbSigType::CLOCK:
return nets_clock_visible_;
default:
return true;
}
}
bool DisplayControls::isSelectable(const odb::dbTechLayer* layer)
{
auto it = layer_selectable_.find(layer);
if (it != layer_selectable_.end()) {
return it->second;
}
return false;
}
bool DisplayControls::areFillsVisible()
{
return fills_visible_;
}
bool DisplayControls::areRowsVisible()
{
return rows_visible_;
}
bool DisplayControls::arePrefTracksVisible()
{
return tracks_visible_pref_;
}
bool DisplayControls::areNonPrefTracksVisible()
{
return tracks_visible_non_pref_;
}
void DisplayControls::techInit()
{
if (tech_inited_ || !db_) {
return;
}
dbTech* tech = db_->getTech();
if (!tech) {
return;
}
// Default colors
// From http://vrl.cs.brown.edu/color seeded with #00F, #F00, #0D0
const QColor colors[] = {QColor(0, 0, 254),
QColor(254, 0, 0),
QColor(9, 221, 0),
QColor(190, 244, 81),
QColor(159, 24, 69),
QColor(32, 216, 253),
QColor(253, 108, 160),
QColor(117, 63, 194),
QColor(128, 155, 49),
QColor(234, 63, 252),
QColor(9, 96, 19),
QColor(214, 120, 239),
QColor(192, 222, 164),
QColor(110, 68, 107)};
const int numColors = sizeof(colors) / sizeof(QColor);
int metal = 0;
int via = 0;
// Iterate through the layers and set default colors
for (dbTechLayer* layer : tech->getLayers()) {
dbTechLayerType type = layer->getType();
QColor color;
if (type == dbTechLayerType::ROUTING) {
if (metal < numColors) {
color = colors[metal++];
} else {
// pick a random color as we exceeded the built-in palette size
color = QColor(50 + rand() % 200, 50 + rand() % 200, 50 + rand() % 200);
}
} else if (type == dbTechLayerType::CUT) {
if (via < numColors) {
color = colors[via++];
} else {
// pick a random color as we exceeded the built-in palette size
color = QColor(50 + rand() % 200, 50 + rand() % 200, 50 + rand() % 200);
}
} else {
continue;
}
color.setAlpha(180);
layer_color_[layer] = color;
layer_pattern_[layer] = Qt::SolidPattern; // Default pattern is fill solid
layer_visible_[layer] = true;
layer_selectable_[layer] = true;
}
tech_inited_ = true;
}
void DisplayControls::designLoaded(odb::dbBlock* block)
{
setDb(block->getDb());
}
} // namespace gui
<commit_msg>Changed sibling function to suport Qt5.9<commit_after>///////////////////////////////////////////////////////////////////////////////
// BSD 3-Clause License
//
// Copyright (c) 2019, OpenROAD
// All rights reserved.
//
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions are met:
//
// * Redistributions of source code must retain the above copyright notice, this
// list of conditions and the following disclaimer.
//
// * Redistributions in binary form must reproduce the above copyright notice,
// this list of conditions and the following disclaimer in the documentation
// and/or other materials provided with the distribution.
//
// * Neither the name of the copyright holder 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 HOLDER OR CONTRIBUTORS BE
// LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
// CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
// SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
// INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
// CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
// ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
// POSSIBILITY OF SUCH DAMAGE.
#include "displayControls.h"
#include <QHeaderView>
#include <QKeyEvent>
#include <QLineEdit>
#include <QPainter>
#include <QSettings>
#include <vector>
#include "db.h"
#include "openroad/InitOpenRoad.hh"
Q_DECLARE_METATYPE(odb::dbTechLayer*);
namespace gui {
using namespace odb;
PatternButton::PatternButton(Qt::BrushStyle pattern, QWidget* parent)
: QRadioButton(parent), pattern_(pattern)
{
setFixedWidth(100);
}
void PatternButton::paintEvent(QPaintEvent* event)
{
QRadioButton::paintEvent(event);
auto qp = QPainter(this);
auto brush = QBrush(QColor("black"), pattern_);
qp.setBrush(brush);
auto btnRect = rect();
btnRect.adjust(18, 2, -1, -1);
qp.drawRect(btnRect);
qp.end();
}
DisplayColorDialog::DisplayColorDialog(QColor color,
Qt::BrushStyle pattern,
QWidget* parent)
: QDialog(parent), color_(color), pattern_(pattern)
{
buildUI();
}
void DisplayColorDialog::buildUI()
{
colorDialog_ = new QColorDialog(this);
colorDialog_->setOptions(QColorDialog::DontUseNativeDialog);
colorDialog_->setWindowFlags(Qt::Widget);
colorDialog_->setCurrentColor(color_);
patternGroupBox_ = new QGroupBox("Layer Pattern");
gridLayout_ = new QGridLayout();
gridLayout_->setColumnStretch(2, 4);
int rowIndex = 0;
for (auto& patGrp : DisplayColorDialog::brushPatterns) {
int colIndex = 0;
for (auto pat : patGrp) {
PatternButton* pBtn = new PatternButton(pat);
patternButtons_.push_back(pBtn);
if (pat == pattern_)
pBtn->setChecked(true);
else
pBtn->setChecked(false);
gridLayout_->addWidget(pBtn, rowIndex, colIndex);
++colIndex;
}
++rowIndex;
}
patternGroupBox_->setLayout(gridLayout_);
connect(colorDialog_, SIGNAL(accepted()), this, SLOT(acceptDialog()));
connect(colorDialog_, SIGNAL(rejected()), this, SLOT(rejectDialog()));
mainLayout_ = new QVBoxLayout();
mainLayout_->addWidget(patternGroupBox_);
mainLayout_->addWidget(colorDialog_);
setLayout(mainLayout_);
setWindowTitle("Layer Config");
setFixedSize(600, width() - 20);
}
DisplayColorDialog::~DisplayColorDialog()
{
}
Qt::BrushStyle DisplayColorDialog::getSelectedPattern() const
{
for (auto patBtn : patternButtons_) {
if (patBtn->isChecked())
return patBtn->pattern();
}
return Qt::SolidPattern;
}
void DisplayColorDialog::acceptDialog()
{
color_ = colorDialog_->selectedColor();
accept();
}
void DisplayColorDialog::rejectDialog()
{
reject();
}
DisplayControls::DisplayControls(QWidget* parent)
: QDockWidget("Display Control", parent),
view_(new QTreeView(parent)),
model_(new QStandardItemModel(0, 4, parent)),
tech_inited_(false),
fills_visible_(false),
tracks_visible_pref_(false),
tracks_visible_non_pref_(false),
rows_visible_(false),
nets_signal_visible_(true),
nets_special_visible_(true),
nets_power_visible_(true),
nets_ground_visible_(true),
nets_clock_visible_(true)
{
setObjectName("layers"); // for settings
model_->setHorizontalHeaderLabels({"", "", "V", "S"});
view_->setModel(model_);
QHeaderView* header = view_->header();
header->setSectionResizeMode(Name, QHeaderView::Stretch);
header->setSectionResizeMode(Swatch, QHeaderView::ResizeToContents);
header->setSectionResizeMode(Visible, QHeaderView::ResizeToContents);
header->setSectionResizeMode(Selectable, QHeaderView::ResizeToContents);
layers_ = makeItem(
"Layers",
model_,
Qt::Checked,
[this](bool visible) { toggleAllChildren(visible, layers_, Visible); },
[this](bool selectable) {
toggleAllChildren(selectable, layers_, Selectable);
});
view_->expand(layers_->index());
// nets patterns
nets_ = makeItem("Nets", model_, Qt::Checked, [this](bool visible) {
toggleAllChildren(visible, nets_, Visible);
});
nets_signal_ = makeItem("Signal", nets_, Qt::Checked, [this](bool visible) {
nets_signal_visible_ = visible;
});
nets_special_ = makeItem("Special", nets_, Qt::Checked, [this](bool visible) {
nets_special_visible_ = visible;
});
nets_power_ = makeItem("Power", nets_, Qt::Checked, [this](bool visible) {
nets_power_visible_ = visible;
});
nets_ground_ = makeItem("Ground", nets_, Qt::Checked, [this](bool visible) {
nets_ground_visible_ = visible;
});
nets_clock_ = makeItem("Clock", nets_, Qt::Checked, [this](bool visible) {
nets_clock_visible_ = visible;
});
// Rows
rows_ = makeItem("Rows", model_, Qt::Unchecked, [this](bool visible) {
rows_visible_ = visible;
});
// Track patterns
tracks_ = makeItem("Tracks", model_, Qt::Unchecked, [this](bool visible) {
toggleAllChildren(visible, tracks_, Visible);
});
tracks_pref_ = makeItem("Pref", tracks_, Qt::Unchecked, [this](bool visible) {
tracks_visible_pref_ = visible;
});
tracks_non_pref_
= makeItem("Non Pref", tracks_, Qt::Unchecked, [this](bool visible) {
tracks_visible_non_pref_ = visible;
});
// Track patterns
misc_ = makeItem("Misc", model_, Qt::Unchecked, [this](bool visible) {
toggleAllChildren(visible, misc_, Visible);
});
fills_ = makeItem("Fills", misc_, Qt::Unchecked, [this](bool visible) {
fills_visible_ = visible;
});
setWidget(view_);
connect(model_,
SIGNAL(itemChanged(QStandardItem*)),
this,
SLOT(itemChanged(QStandardItem*)));
connect(view_,
SIGNAL(doubleClicked(const QModelIndex&)),
this,
SLOT(displayItemDblClicked(const QModelIndex&)));
}
void DisplayControls::toggleAllChildren(bool checked,
QStandardItem* parent,
Column column)
{
Qt::CheckState state = checked ? Qt::Checked : Qt::Unchecked;
for (int row = 0; row < parent->rowCount(); ++row) {
auto child = parent->child(row, column);
child->setCheckState(state);
}
emit changed();
}
void DisplayControls::itemChanged(QStandardItem* item)
{
if (item->isCheckable() == false) {
emit changed();
return;
}
bool checked = item->checkState() == Qt::Checked;
Callback callback = item->data().value<Callback>();
callback.action(checked);
emit changed();
}
void DisplayControls::displayItemDblClicked(const QModelIndex& index)
{
if (index.column() == 1) {
auto colorItem = model_->itemFromIndex(index);
QVariant techLayerData = colorItem->data(Qt::UserRole);
if (!techLayerData.isValid())
return;
auto techLayer
= static_cast<odb::dbTechLayer*>(techLayerData.value<void*>());
if (techLayer == nullptr)
return;
QColor colorVal = color(techLayer);
Qt::BrushStyle patternVal = pattern(techLayer);
DisplayColorDialog dispDlg(colorVal, patternVal);
dispDlg.exec();
QColor chosenColor = dispDlg.getSelectedColor();
if (chosenColor.isValid()) {
QPixmap swatch(20, 20);
swatch.fill(chosenColor);
colorItem->setIcon(QIcon(swatch));
auto cutLayerIndex
= model_->sibling(index.row() + 1, index.column(), index);
if (cutLayerIndex.isValid()) {
auto cutColorItem = model_->itemFromIndex(cutLayerIndex);
cutColorItem->setIcon(QIcon(swatch));
}
if (chosenColor != colorVal
|| layer_pattern_[techLayer] != dispDlg.getSelectedPattern()) {
layer_color_[techLayer] = chosenColor;
layer_pattern_[techLayer] = dispDlg.getSelectedPattern();
view_->repaint();
emit changed();
}
}
}
}
void DisplayControls::setDb(odb::dbDatabase* db)
{
db_ = db;
if (!db) {
return;
}
dbTech* tech = db->getTech();
if (!tech) {
return;
}
techInit();
for (dbTechLayer* layer : tech->getLayers()) {
dbTechLayerType type = layer->getType();
if (type == dbTechLayerType::ROUTING || type == dbTechLayerType::CUT) {
makeItem(
QString::fromStdString(layer->getName()),
layers_,
Qt::Checked,
[this, layer](bool visible) { layer_visible_[layer] = visible; },
[this, layer](bool select) { layer_selectable_[layer] = select; },
color(layer),
type == dbTechLayerType::CUT ? NULL : layer);
}
}
emit changed();
}
template <typename T>
QStandardItem* DisplayControls::makeItem(
const QString& text,
T* parent,
Qt::CheckState checked,
const std::function<void(bool)>& visibility_action,
const std::function<void(bool)>& select_action,
const QColor& color,
odb::dbTechLayer* techLayer)
{
QStandardItem* nameItem = new QStandardItem(text);
nameItem->setEditable(false);
QPixmap swatch(20, 20);
swatch.fill(color);
QStandardItem* colorItem = new QStandardItem(QIcon(swatch), "");
QString colorName = color.name(QColor::HexArgb);
colorItem->setEditable(false);
colorItem->setCheckable(false);
if (techLayer != nullptr) {
QVariant techLayerData(QVariant::fromValue(static_cast<void*>(techLayer)));
colorItem->setData(techLayerData, Qt::UserRole);
}
QStandardItem* visibilityItem = new QStandardItem("");
visibilityItem->setCheckable(true);
visibilityItem->setEditable(false);
visibilityItem->setCheckState(checked);
visibilityItem->setData(QVariant::fromValue(Callback({visibility_action})));
QStandardItem* selectItem = nullptr;
if (select_action) {
selectItem = new QStandardItem("");
selectItem->setCheckable(true);
selectItem->setCheckState(checked);
selectItem->setEditable(false);
selectItem->setData(QVariant::fromValue(Callback({select_action})));
}
parent->appendRow({nameItem, colorItem, visibilityItem, selectItem});
return nameItem;
}
QColor DisplayControls::color(const odb::dbTechLayer* layer)
{
return layer_color_.at(layer);
}
Qt::BrushStyle DisplayControls::pattern(const odb::dbTechLayer* layer)
{
return layer_pattern_.at(layer);
}
bool DisplayControls::isVisible(const odb::dbTechLayer* layer)
{
auto it = layer_visible_.find(layer);
if (it != layer_visible_.end()) {
return it->second;
}
return false;
}
bool DisplayControls::isNetVisible(odb::dbNet* net)
{
switch (net->getSigType()) {
case dbSigType::SIGNAL:
return nets_signal_visible_;
case dbSigType::POWER:
return nets_power_visible_;
case dbSigType::GROUND:
return nets_ground_visible_;
case dbSigType::CLOCK:
return nets_clock_visible_;
default:
return true;
}
}
bool DisplayControls::isSelectable(const odb::dbTechLayer* layer)
{
auto it = layer_selectable_.find(layer);
if (it != layer_selectable_.end()) {
return it->second;
}
return false;
}
bool DisplayControls::areFillsVisible()
{
return fills_visible_;
}
bool DisplayControls::areRowsVisible()
{
return rows_visible_;
}
bool DisplayControls::arePrefTracksVisible()
{
return tracks_visible_pref_;
}
bool DisplayControls::areNonPrefTracksVisible()
{
return tracks_visible_non_pref_;
}
void DisplayControls::techInit()
{
if (tech_inited_ || !db_) {
return;
}
dbTech* tech = db_->getTech();
if (!tech) {
return;
}
// Default colors
// From http://vrl.cs.brown.edu/color seeded with #00F, #F00, #0D0
const QColor colors[] = {QColor(0, 0, 254),
QColor(254, 0, 0),
QColor(9, 221, 0),
QColor(190, 244, 81),
QColor(159, 24, 69),
QColor(32, 216, 253),
QColor(253, 108, 160),
QColor(117, 63, 194),
QColor(128, 155, 49),
QColor(234, 63, 252),
QColor(9, 96, 19),
QColor(214, 120, 239),
QColor(192, 222, 164),
QColor(110, 68, 107)};
const int numColors = sizeof(colors) / sizeof(QColor);
int metal = 0;
int via = 0;
// Iterate through the layers and set default colors
for (dbTechLayer* layer : tech->getLayers()) {
dbTechLayerType type = layer->getType();
QColor color;
if (type == dbTechLayerType::ROUTING) {
if (metal < numColors) {
color = colors[metal++];
} else {
// pick a random color as we exceeded the built-in palette size
color = QColor(50 + rand() % 200, 50 + rand() % 200, 50 + rand() % 200);
}
} else if (type == dbTechLayerType::CUT) {
if (via < numColors) {
color = colors[via++];
} else {
// pick a random color as we exceeded the built-in palette size
color = QColor(50 + rand() % 200, 50 + rand() % 200, 50 + rand() % 200);
}
} else {
continue;
}
color.setAlpha(180);
layer_color_[layer] = color;
layer_pattern_[layer] = Qt::SolidPattern; // Default pattern is fill solid
layer_visible_[layer] = true;
layer_selectable_[layer] = true;
}
tech_inited_ = true;
}
void DisplayControls::designLoaded(odb::dbBlock* block)
{
setDb(block->getDb());
}
} // namespace gui
<|endoftext|> |
<commit_before>#include <stdio.h>
#include <sys/ioctl.h>
#include <unistd.h>
#include <iostream>
#include <tiobj.hpp>
#include <tiarg.hpp>
#include "tisys.hpp"
using namespace std;
// ANSI-Cores
#define C_VERMELHO "{FONTE}33[41m{FONTE}33[37m"
#define C_VERDE "{FONTE}33[42m{FONTE}33[30m"
#define C_LARANJA "{FONTE}33[43m{FONTE}33[30m"
#define C_AZUL "{FONTE}33[44m{FONTE}33[37m"
#define C_ROSA "{FONTE}33[45m{FONTE}33[37m"
#define C_CIANO "{FONTE}33[46m{FONTE}33[30m"
#define C_BRANCO "{FONTE}33[47m{FONTE}33[30m"
#define C_PRETO "{FONTE}33[40m{FONTE}33[37m"
#define C_RESTAURA "{FONTE}33[00m"
/*struct winsize w;
ioctl(0, TIOCGWINSZ, &w);
printf ("lines %d\n", w.ws_row);
printf ("columns %d\n", w.ws_col);*/
int main(int argc, char** argv){
TiObj args, folder;
getArgs(args, argc, argv);
Filesystem fs;
string classe = args.atStr("_Akk");
string url = args.atStr("from", "");
/*TiObj aaa;
tiurl_explode(aaa, url);
return 0;*/
if ( classe != "" ){
if ( classe == "User" ){
/*TiObj aux;
TiSys::listUsers(aux);
cout << aux;*/
} else {
TiBox aux;
fs.listdir(folder, url);
folder.sort();
folder.select(aux, classe);
cout << aux;
}
} else {
TiObj folder;
fs.listdir(folder, url);
folder.sort();
cout << folder.box;
}
}
<commit_msg>alterado o tisys.ls para mostrar um objeto para cada linha<commit_after>#include <stdio.h>
#include <sys/ioctl.h>
#include <unistd.h>
#include <iostream>
#include <tiobj.hpp>
#include <tiarg.hpp>
#include "tisys.hpp"
using namespace std;
// ANSI-Cores
#define C_VERMELHO "{FONTE}33[41m{FONTE}33[37m"
#define C_VERDE "{FONTE}33[42m{FONTE}33[30m"
#define C_LARANJA "{FONTE}33[43m{FONTE}33[30m"
#define C_AZUL "{FONTE}33[44m{FONTE}33[37m"
#define C_ROSA "{FONTE}33[45m{FONTE}33[37m"
#define C_CIANO "{FONTE}33[46m{FONTE}33[30m"
#define C_BRANCO "{FONTE}33[47m{FONTE}33[30m"
#define C_PRETO "{FONTE}33[40m{FONTE}33[37m"
#define C_RESTAURA "{FONTE}33[00m"
/*struct winsize w;
ioctl(0, TIOCGWINSZ, &w);
printf ("lines %d\n", w.ws_row);
printf ("columns %d\n", w.ws_col);*/
void printBox(TiBox& box){
for (uint i=0; i<box.size(); i++){
cout << printObj(box[i]) << endl;
cout << box[i].toString() << endl;
}
}
int main(int argc, char** argv){
TiObj args, folder;
getArgs(args, argc, argv);
Filesystem fs;
string classe = args.atStr("_Akk");
string url = args.atStr("from", "");
/*TiObj aaa;
tiurl_explode(aaa, url);
return 0;*/
if ( classe != "" ){
if ( classe == "User" ){
/*TiObj aux;
TiSys::listUsers(aux);
cout << aux;*/
} else {
TiBox aux;
fs.listdir(folder, url);
folder.sort();
folder.select(aux, classe);
printBox(aux);
}
} else {
TiObj folder;
fs.listdir(folder, url);
folder.sort();
printBox(folder.box);
}
}
<|endoftext|> |
<commit_before>#ifndef GROUPER_HPP_
#define GROUPER_HPP_
#include "iterbase.hpp"
#include <vector>
#include <algorithm>
#include <type_traits>
#include <functional>
#include <utility>
#include <iterator>
#include <initializer_list>
namespace iter {
template <typename Container>
class Grouper;
template <typename Container>
Grouper<Container> grouper(Container&&, std::size_t);
template <typename T>
Grouper<std::initializer_list<T>> grouper(
std::initializer_list<T>, std::size_t);
template <typename Container>
class Grouper {
private:
Container container;
std::size_t group_size;
Grouper(Container c, std::size_t sz)
: container(std::forward<Container>(c)),
group_size{sz}
{ }
friend Grouper grouper<Container>(Container&&, std::size_t);
template <typename T>
friend Grouper<std::initializer_list<T>> grouper(
std::initializer_list<T>, std::size_t);
public:
class Iterator {
private:
Container& container;
std::vector<iterator_type<Container>> group;
std::size_t group_size = 0;
bool not_done = true;
using Deref_type =
std::vector<
std::reference_wrapper<
typename std::remove_reference<
iterator_deref<Container>>::type>>;
public:
Iterator(Container& c, std::size_t s)
: container(c),
group_size(s)
{
// if the group size is 0 or the container is empty produce
// nothing
if (this->group_size == 0
|| (!(std::begin(this->container)
!= std::end(this->container)))) {
this->not_done = false;
return;
}
std::size_t i = 0;
for (auto iter = std::begin(container);
i < group_size;
++i, ++iter) {
group.push_back(iter);
}
}
//seems like conclassor is same as sliding_window_iter
Iterator(Container& c)
: container(c)
{
//creates the end iterator
group.push_back(std::end(container));
}
//plan to conditionally check for existence of +=
Iterator & operator++() {
for (auto & iter : this->group) {
std::advance(iter,this->group_size);
}
return *this;
}
bool operator!=(const Iterator &) const {
return this->not_done;
}
Deref_type operator*() {
Deref_type vec;
for (auto i : this->group) {
if(!(i != std::end(this->container))) {
this->not_done = false;
break;
}
//if the group is at the end the vector will be smaller
else {
vec.push_back(*i);
}
}
return vec;
}
};
Iterator begin() {
return {this->container, group_size};
}
Iterator end() {
return {this->container};
}
};
template <typename Container>
Grouper<Container> grouper(Container&& container, std::size_t group_size) {
return {std::forward<Container>(container), group_size};
}
template <typename T>
Grouper<std::initializer_list<T>> grouper(
std::initializer_list<T> il, std::size_t group_size) {
return {il, group_size};
}
}
#endif // #ifndef GROUPER_HPP_
<commit_msg>eliminates extra moves<commit_after>#ifndef ITER_GROUPER_HPP_
#define ITER_GROUPER_HPP_
#include "iterbase.hpp"
#include <vector>
#include <algorithm>
#include <type_traits>
#include <functional>
#include <utility>
#include <iterator>
#include <initializer_list>
namespace iter {
template <typename Container>
class Grouper;
template <typename Container>
Grouper<Container> grouper(Container&&, std::size_t);
template <typename T>
Grouper<std::initializer_list<T>> grouper(
std::initializer_list<T>, std::size_t);
template <typename Container>
class Grouper {
private:
Container container;
std::size_t group_size;
Grouper(Container&& c, std::size_t sz)
: container(std::forward<Container>(c)),
group_size{sz}
{ }
friend Grouper grouper<Container>(Container&&, std::size_t);
template <typename T>
friend Grouper<std::initializer_list<T>> grouper(
std::initializer_list<T>, std::size_t);
public:
class Iterator {
private:
Container& container;
std::vector<iterator_type<Container>> group;
std::size_t group_size = 0;
bool not_done = true;
using Deref_type =
std::vector<
std::reference_wrapper<
typename std::remove_reference<
iterator_deref<Container>>::type>>;
public:
Iterator(Container& c, std::size_t s)
: container(c),
group_size(s)
{
// if the group size is 0 or the container is empty produce
// nothing
if (this->group_size == 0
|| (!(std::begin(this->container)
!= std::end(this->container)))) {
this->not_done = false;
return;
}
std::size_t i = 0;
for (auto iter = std::begin(container);
i < group_size;
++i, ++iter) {
group.push_back(iter);
}
}
//seems like conclassor is same as sliding_window_iter
Iterator(Container& c)
: container(c)
{
//creates the end iterator
group.push_back(std::end(container));
}
//plan to conditionally check for existence of +=
Iterator & operator++() {
for (auto & iter : this->group) {
std::advance(iter,this->group_size);
}
return *this;
}
bool operator!=(const Iterator &) const {
return this->not_done;
}
Deref_type operator*() {
Deref_type vec;
for (auto i : this->group) {
if(!(i != std::end(this->container))) {
this->not_done = false;
break;
}
//if the group is at the end the vector will be smaller
else {
vec.push_back(*i);
}
}
return vec;
}
};
Iterator begin() {
return {this->container, group_size};
}
Iterator end() {
return {this->container};
}
};
template <typename Container>
Grouper<Container> grouper(Container&& container, std::size_t group_size) {
return {std::forward<Container>(container), group_size};
}
template <typename T>
Grouper<std::initializer_list<T>> grouper(
std::initializer_list<T> il, std::size_t group_size) {
return {std::move(il), group_size};
}
}
#endif
<|endoftext|> |
<commit_before><commit_msg>gui: fix isCore check<commit_after><|endoftext|> |
<commit_before>#ifndef GROUPER_HPP
#define GROUPER_HPP
#include "iterator_range.hpp"
#include <vector>
#include <algorithm>
#include <functional>
#include <type_traits>
namespace iter {
template <typename Container>
struct grouper_iter;
template <typename Container>
iterator_range<grouper_iter<Container>>
grouper(Container & container, size_t s) {
auto begin = grouper_iter<Container>(container,s);
auto end = grouper_iter<Container>(container);
return iterator_range<grouper_iter<Container>>(begin,end);
}
template <typename Container>
struct grouper_iter {
Container & container;
using Iterator = decltype(container.begin());
std::vector<Iterator> group;
size_t group_size = 0;
bool not_done = true;
grouper_iter(Container & c, size_t s) :
container(c),group_size(s)
{
//if the group size is 0 or the container is empty produce nothing
if (group_size == 0 || !(container.begin() != container.end())) {
not_done = false;
return;
}
for (size_t i = 0; i < group_size; ++i)
group.push_back(container.begin()+i);
}
//seems like constructor is same as moving_section_iter
grouper_iter(Container & c) : container(c)
//creates the end iterator
{
group.push_back(container.end());
}
grouper_iter & operator++() {
for (auto & iter : group) {
iter += group_size;
}
return *this;
}
bool operator!=(const grouper_iter &) {
return not_done;
}
using Deref_type = std::vector<std::reference_wrapper<typename std::remove_reference<decltype(*std::declval<Iterator>())>::type>>;
Deref_type operator*()
{
Deref_type vec;
for (auto i : group) {
if(i == container.end()) {
not_done = false;
break;
}
//if the group is at the end the vector will be smaller
else {
vec.push_back(*i);
}
}
return vec;
}
};
}
#endif //MOVING_SECTION_HPP
<commit_msg>Formatting on grouper<commit_after>#ifndef GROUPER_HPP
#define GROUPER_HPP
#include "iterator_range.hpp"
#include <vector>
#include <algorithm>
#include <functional>
#include <type_traits>
namespace iter {
template <typename Container>
class grouper_iter;
template <typename Container>
iterator_range<grouper_iter<Container>> grouper(
Container & container, size_t s) {
auto begin = grouper_iter<Container>(container, s);
auto end = grouper_iter<Container>(container);
return iterator_range<grouper_iter<Container>>(begin, end);
}
template <typename Container>
class grouper_iter {
private:
Container & container;
using Iterator = decltype(container.begin());
using Deref_type =
std::vector<
std::reference_wrapper<
typename std::remove_reference<
decltype(*std::declval<Iterator>())>::type>>;
std::vector<Iterator> group;
size_t group_size = 0;
bool not_done = true;
public:
grouper_iter(Container & c, size_t s) :
container(c),group_size(s)
{
// if the group size is 0 or the container is empty produce
// nothing
if (this->group_size == 0 ||
!(this->container.begin() != this->container.end())) {
this->not_done = false;
return;
}
for (size_t i = 0; i < this->group_size; ++i)
this->group.push_back(this->container.begin() + i);
}
//seems like conclassor is same as moving_section_iter
grouper_iter(Container & c) :
container(c)
{
//creates the end iterator
group.push_back(container.end());
}
grouper_iter & operator++() {
for (auto & iter : this->group) {
iter += this->group_size;
}
return *this;
}
bool operator!=(const grouper_iter &) const {
return this->not_done;
}
Deref_type operator*() {
Deref_type vec;
for (auto i : this->group) {
if(i == this->container.end()) {
this->not_done = false;
break;
}
//if the group is at the end the vector will be smaller
else {
vec.push_back(*i);
}
}
return vec;
}
};
}
#endif // ifndef GROUPER_HPP
<|endoftext|> |
<commit_before><commit_msg>Add one more test to TreeNodeModelTest.<commit_after><|endoftext|> |
<commit_before><commit_msg>code_editor.cpp: remove unwanted empty line at EOF<commit_after><|endoftext|> |
<commit_before><commit_msg>imguial_log: remove imgui demo<commit_after><|endoftext|> |
<commit_before>///
/// \file integrated_snarl_finder.cpp
///
///
#include "integrated_snarl_finder.hpp"
#include <bdsg/overlays/overlay_helper.hpp>
#include <structures/union_find.hpp>
namespace vg {
using namespace std;
class IntegratedSnarlFinder::MergedAdjacencyGraph {
protected:
/// Hold onto the backing HandleGraph
const HandleGraph* graph;
/// Keep a vectorizable overlay over it to let us map between handles
/// and union-find indices via handle ranking. The handles are all at index
/// (rank - 1) * 2 + is_reverse.
///
/// We rely on handles in the vectorizable overlay and handles in the
/// backing graph being identical.
VectorizableOverlayHelper overlay_helper;
/// Keep a union-find over the ranks of the merged oriented handles that
/// make up each component. Runs with include_children=true so we can find
/// all the members of each group.
structures::UnionFind union_find;
/// If not null, we represent a set of further merges on top of this
/// backing MergedAdjacencyGraph. The backing graph MAY NOT CHANGE as long
/// as we are alive, and we DO NOT OWN IT.
///
/// Our union-find will be over the ranked heads of components in the base
/// MergedAdjacencyGraph, and our overlay helper will be unused.
const MergedAdjacencyGraph* base;
/// If we are an overlay ourselves, we define a dense rank space over the
/// heads of the base's components.
/// TODO: When we get a good sparse union-find, get rid of this.
vector<handle_t> base_components;
/// And we map from handle to index in base_components.
unordered_map<handle_t, size_t> base_ranks;
// TODO: is keeping all this really better than just copying the union-find?
/// Get the rank corresponding to the given handle, in the union-find.
/// Our ranks are 0-based.
size_t uf_rank(handle_t into) const;
/// Get the handle with the given rank in union-find space.
/// Our ranks are 0-based.
handle_t uf_handle(size_t rank) const;
public:
/// Make a MergedAdjacencyGraph representing the graph of adjacency components of the given HandleGraph.
MergedAdjacencyGraph(const HandleGraph* graph);
/// Make a MergedAdjacencyGraph representing further merges of the
/// components of the given immutable MergedAdjacencyGraph.
MergedAdjacencyGraph(const MergedAdjacencyGraph* base);
/// Given handles reading into two components, a and b, merge them into a single component.
void merge(handle_t into_a, handle_t into_b);
/// Find the handle heading the component that the given handle is in.
handle_t find(handle_t into) const;
/// Count the number of components in the MergedAdjacencyGraph
size_t size() const;
};
size_t IntegratedSnarlFinder::MergedAdjacencyGraph::uf_rank(handle_t into) const {
if (base == nullptr) {
// We have a vectorizable overlay
return (overlay_helper.get()->id_to_rank(graph->get_id(into)) - 1) * 2 + (size_t) graph->get_is_reverse(into);
} else {
// We're really an overlay ourselves
}
}
handle_t IntegratedSnarlFinder::MergedAdjacencyGraph::uf_handle(size_t rank) const {
if (base == nullptr) {
return graph->get_handle(overlay_helper.get()->rank_to_id(rank / 2 + 1), rank % 2);
} else {
}
}
IntegratedSnarlFinder::MergedAdjacencyGraph::MergedAdjacencyGraph(const HandleGraph* graph) : graph(graph),
overlay_helper(), union_find(overlay_helper.apply(graph)->get_node_count() * 2, true), base(nullptr), base_components(), base_ranks() {
// TODO: we want the adjacency components that are just single edges
// between two handles (i.e. trivial snarls) to be implicit, so we don't
// have to do O(n) work for so much of the graph. But to do that we need a
// union-find that lets us declare it over a potentially large space
// without filling it all in.
// So we do this the easy way and compute all the merges for all adjacency
// components, including tiny/numerous ones, right now.
graph->for_each_edge([&](const handlegraph::edge_t& e) {
// Get the inward-facing version of the second handle
auto into_b = graph->flip(e.second);
// Merge to create initial adjacency components
merge(e.first, into_b)
});
}
IntegratedSnarlFinder::MergedAdjacencyGraph::MergedAdjacencyGraph(const MergedAdjacencyGraph* base) : graph(base->graph),
overlay_helper(), union_find(base->size(), true), base(base) {
// Nothing to do!
}
IntegratedSnarlFinder::MergedAdjacencyGraph::merge(
IntegratedSnarlFinder::IntegratedSnarlFinder(const PathHandleGraph& graph) : graph(&graph) {
// Nothing to do!
}
void IntegratedSnarlFinder::for_each_snarl_including_trivial(const function<void(handle_t, handle_t)>& iteratee) const {
// Do the actual snarl finding work and then feed the iteratee our snarls.
// We need our base graph to be vectorizable, so we can have ranks for all the handles, so we can do a union-find over them.
PathVectorizableOverlayHelper overlay_helper;
// Get or create a vectorizability facet of the base graph, which we can use to go between ranks and handles.
VectorizableHandleGraph vectorized_graph = overlay_helper.apply(graph);
// We need a union-find over the whole graph.
}
SnarlManager IntegratedSnarlFinder::find_snarls() {
// Start with an empty SnarlManager
SnarlManager snarl_manager;
for_each_snarl_including_trivial([&](handle_t start_inward, handle_t end_outward) {
// For every snarl, including the trivial ones
// Make a Protobuf version of it
vg::Snarl proto_snarl;
// Convert boundary handles to Visits
proto_snarl.mutable_start()->set_node_id(graph->get_id(start_inward));
proto_snarl.mutable_start()->set_backward(graph->get_is_reverse(start_inward));
proto_snarl.mutable_end()->set_node_id(graph->get_id(end_outward));
proto_snarl.mutable_end()->set_backward(graph->get_is_reverse(end_outward));
// TODO: Determine snarl metadata somehow. Do a postorder traversal? Or make the manager somehow do it?
// Add the Protobuf version of the snarl to the SNarl Manager
snarl_manager.add_snarl(proto_snarl);
});
// Let the snarl manager compute all its indexes
snarl_manager.finish();
// Give it back
return snarl_manager;
}
}
<commit_msg>Make the mergeable component graph copyable instead<commit_after>///
/// \file integrated_snarl_finder.cpp
///
///
#include "integrated_snarl_finder.hpp"
#include <bdsg/overlays/overlay_helper.hpp>
#include <structures/union_find.hpp>
namespace vg {
using namespace std;
class IntegratedSnarlFinder::MergedAdjacencyGraph {
protected:
/// Hold onto the backing HandleGraph
const HandleGraph* graph;
/// Keep a vectorizable overlay over it to let us map between handles
/// and union-find indices via handle ranking. The handles are all at index
/// (rank - 1) * 2 + is_reverse.
///
/// We rely on handles in the vectorizable overlay and handles in the
/// backing graph being identical.
VectorizableOverlayHelper overlay_helper;
/// Keep a union-find over the ranks of the merged oriented handles that
/// make up each component. Runs with include_children=true so we can find
/// all the members of each group.
/// Needs to be mutable because union-find find operations do internal tree
/// massaging and aren't const.
/// TODO: this makes read operations not thread safe!
mutable structures::UnionFind union_find;
/// Get the rank corresponding to the given handle, in the union-find.
/// Our ranks are 0-based.
size_t uf_rank(handle_t into) const;
/// Get the handle with the given rank in union-find space.
/// Our ranks are 0-based.
handle_t uf_handle(size_t rank) const;
public:
/// Make a MergedAdjacencyGraph representing the graph of adjacency components of the given HandleGraph.
MergedAdjacencyGraph(const HandleGraph* graph);
/// Copy a MergedAdjacencyGraph by re-doing all the merges. Uses its own internal vectorization.
MergedAdjacencyGraph(const MergedAdjacencyGraph& other);
/// Given handles reading into two components, a and b, merge them into a single component.
void merge(handle_t into_a, handle_t into_b);
/// Find the handle heading the component that the given handle is in.
handle_t find(handle_t into) const;
/// For each item other than the head in each component, calls the iteratee
/// with the head and the other item. Does not call the iteratee for
/// single-item components.
void for_each_membership(const function<void(handle_t, handle_t)>& iteratee) const;
};
size_t IntegratedSnarlFinder::MergedAdjacencyGraph::uf_rank(handle_t into) const {
// We need to 0-base the backing rank, space it out, and make the low bit orientation
return (overlay_helper.get()->id_to_rank(graph->get_id(into)) - 1) * 2 + (size_t) graph->get_is_reverse(into);
}
handle_t IntegratedSnarlFinder::MergedAdjacencyGraph::uf_handle(size_t rank) const {
// We need to take the high bits and than make it 1-based, and get the orientation from the low bit
return graph->get_handle(overlay_helper.get()->rank_to_id(rank / 2 + 1), rank % 2);
}
IntegratedSnarlFinder::MergedAdjacencyGraph::MergedAdjacencyGraph(const HandleGraph* graph) : graph(graph),
overlay_helper(), union_find(overlay_helper.apply(graph)->get_node_count() * 2, true) {
// TODO: we want the adjacency components that are just single edges
// between two handles (i.e. trivial snarls) to be implicit, so we don't
// have to do O(n) work for so much of the graph. But to do that we need a
// union-find that lets us declare it over a potentially large space
// without filling it all in.
// So we do this the easy way and compute all the merges for all adjacency
// components, including tiny/numerous ones, right now.
// If we ever change this, we should also make MergedAdjacencyGraph
// stackable, to save a copy when we want to do further merges but keep the
// old state.
graph->for_each_edge([&](const handlegraph::edge_t& e) {
// Get the inward-facing version of the second handle
auto into_b = graph->flip(e.second);
// Merge to create initial adjacency components
merge(e.first, into_b)
});
}
IntegratedSnarlFinder::MergedAdjacencyGraph::MergedAdjacencyGraph(const MergedAdjacencyGraph& other) : MergedAdjacencyGraph(other.graph) {
other.for_each_membership([&](handle_t head, handle_t member) {
// For anything in a component, other than its head, do the merge with the head.
merge(head, member);
});
}
IntegratedSnarlFinder::MergedAdjacencyGraph::merge(handle_t into_a, handle_t into_b) {
// Get ranks and merge
union_find.union_groups(uf_rank(into_a), uf_rank(into_b));
}
handle_t IntegratedSnarlFinder::MergedAdjacencyGraph::find(handle_t into) const {
// Get rank, find head, and get handle
return uf_handle(union_find.find_group(uf_rank(into)));
}
void IntegratedSnarlFinder::MergedAdjacencyGraph::for_each_membership(const function<void(handle_t, handle_t)>& iteratee) const {
// We do this weird iteration because it's vaguely efficient in the union-find we use.
vector<vector<size_t>> uf_components = union_find.all_groups();
for (auto& component : uf_components) {
// For each component
for (size_t i = 1; i < component.size(); i++) {
// For everything other than the head, announce with the head.
iteratee(uf_handle(component[0]), uf_handle(component[i]));
}
}
}
////////////////////////////////////////////////////////////////////////////////////////////
IntegratedSnarlFinder::IntegratedSnarlFinder(const PathHandleGraph& graph) : graph(&graph) {
// Nothing to do!
}
void IntegratedSnarlFinder::for_each_snarl_including_trivial(const function<void(handle_t, handle_t)>& iteratee) const {
// Do the actual snarl finding work and then feed the iteratee our snarls.
// We need our base graph to be vectorizable, so we can have ranks for all the handles, so we can do a union-find over them.
PathVectorizableOverlayHelper overlay_helper;
// Get or create a vectorizability facet of the base graph, which we can use to go between ranks and handles.
VectorizableHandleGraph vectorized_graph = overlay_helper.apply(graph);
// We need a union-find over the whole graph.
}
SnarlManager IntegratedSnarlFinder::find_snarls() {
// Start with an empty SnarlManager
SnarlManager snarl_manager;
for_each_snarl_including_trivial([&](handle_t start_inward, handle_t end_outward) {
// For every snarl, including the trivial ones
// Make a Protobuf version of it
vg::Snarl proto_snarl;
// Convert boundary handles to Visits
proto_snarl.mutable_start()->set_node_id(graph->get_id(start_inward));
proto_snarl.mutable_start()->set_backward(graph->get_is_reverse(start_inward));
proto_snarl.mutable_end()->set_node_id(graph->get_id(end_outward));
proto_snarl.mutable_end()->set_backward(graph->get_is_reverse(end_outward));
// TODO: Determine snarl metadata somehow. Do a postorder traversal? Or make the manager somehow do it?
// Add the Protobuf version of the snarl to the SNarl Manager
snarl_manager.add_snarl(proto_snarl);
});
// Let the snarl manager compute all its indexes
snarl_manager.finish();
// Give it back
return snarl_manager;
}
}
<|endoftext|> |
<commit_before>// Copyright (c) 2015, Baidu.com, Inc. All Rights Reserved
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
//
// 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.
#include "db/skiplist.h"
#include <set>
#include "leveldb/env.h"
#include "util/arena.h"
#include "util/hash.h"
#include "util/random.h"
#include "util/testharness.h"
namespace leveldb {
typedef uint64_t Key;
struct Comparator {
int operator()(const Key& a, const Key& b) const {
if (a < b) {
return -1;
} else if (a > b) {
return +1;
} else {
return 0;
}
}
};
class SkipTest { };
TEST(SkipTest, Empty) {
Arena arena;
Comparator cmp;
SkipList<Key, Comparator> list(cmp, &arena);
ASSERT_TRUE(!list.Contains(10));
SkipList<Key, Comparator>::Iterator iter(&list);
ASSERT_TRUE(!iter.Valid());
iter.SeekToFirst();
ASSERT_TRUE(!iter.Valid());
iter.Seek(100);
ASSERT_TRUE(!iter.Valid());
iter.SeekToLast();
ASSERT_TRUE(!iter.Valid());
}
TEST(SkipTest, InsertAndLookup) {
const int N = 2000;
const int R = 5000;
Random rnd(1000);
std::set<Key> keys;
Arena arena;
Comparator cmp;
SkipList<Key, Comparator> list(cmp, &arena);
for (int i = 0; i < N; i++) {
Key key = rnd.Next() % R;
if (keys.insert(key).second) {
list.Insert(key);
}
}
for (int i = 0; i < R; i++) {
if (list.Contains(i)) {
ASSERT_EQ(keys.count(i), 1u);
} else {
ASSERT_EQ(keys.count(i), 0u);
}
}
// Simple iterator tests
{
SkipList<Key, Comparator>::Iterator iter(&list);
ASSERT_TRUE(!iter.Valid());
iter.Seek(0);
ASSERT_TRUE(iter.Valid());
ASSERT_EQ(*(keys.begin()), iter.key());
iter.SeekToFirst();
ASSERT_TRUE(iter.Valid());
ASSERT_EQ(*(keys.begin()), iter.key());
iter.SeekToLast();
ASSERT_TRUE(iter.Valid());
ASSERT_EQ(*(keys.rbegin()), iter.key());
}
// Forward iteration test
for (int i = 0; i < R; i++) {
SkipList<Key, Comparator>::Iterator iter(&list);
iter.Seek(i);
// Compare against model iterator
std::set<Key>::iterator model_iter = keys.lower_bound(i);
for (int j = 0; j < 3; j++) {
if (model_iter == keys.end()) {
ASSERT_TRUE(!iter.Valid());
break;
} else {
ASSERT_TRUE(iter.Valid());
ASSERT_EQ(*model_iter, iter.key());
++model_iter;
iter.Next();
}
}
}
// Backward iteration test
{
SkipList<Key, Comparator>::Iterator iter(&list);
iter.SeekToLast();
// Compare against model iterator
for (std::set<Key>::reverse_iterator model_iter = keys.rbegin();
model_iter != keys.rend();
++model_iter) {
ASSERT_TRUE(iter.Valid());
ASSERT_EQ(*model_iter, iter.key());
iter.Prev();
}
ASSERT_TRUE(!iter.Valid());
}
}
// We want to make sure that with a single writer and multiple
// concurrent readers (with no synchronization other than when a
// reader's iterator is created), the reader always observes all the
// data that was present in the skip list when the iterator was
// constructor. Because insertions are happening concurrently, we may
// also observe new values that were inserted since the iterator was
// constructed, but we should never miss any values that were present
// at iterator construction time.
//
// We generate multi-part keys:
// <key,gen,hash>
// where:
// key is in range [0..K-1]
// gen is a generation number for key
// hash is hash(key,gen)
//
// The insertion code picks a random key, sets gen to be 1 + the last
// generation number inserted for that key, and sets hash to Hash(key,gen).
//
// At the beginning of a read, we snapshot the last inserted
// generation number for each key. We then iterate, including random
// calls to Next() and Seek(). For every key we encounter, we
// check that it is either expected given the initial snapshot or has
// been concurrently added since the iterator started.
class ConcurrentTest {
private:
static const uint32_t K = 4;
static uint64_t key(Key key) { return (key >> 40); }
static uint64_t gen(Key key) { return (key >> 8) & 0xffffffffu; }
static uint64_t hash(Key key) { return key & 0xff; }
static uint64_t HashNumbers(uint64_t k, uint64_t g) {
uint64_t data[2] = { k, g };
return Hash(reinterpret_cast<char*>(data), sizeof(data), 0);
}
static Key MakeKey(uint64_t k, uint64_t g) {
assert(sizeof(Key) == sizeof(uint64_t));
assert(k <= K); // We sometimes pass K to seek to the end of the skiplist
assert(g <= 0xffffffffu);
return ((k << 40) | (g << 8) | (HashNumbers(k, g) & 0xff));
}
static bool IsValidKey(Key k) {
return hash(k) == (HashNumbers(key(k), gen(k)) & 0xff);
}
static Key RandomTarget(Random* rnd) {
switch (rnd->Next() % 10) {
case 0:
// Seek to beginning
return MakeKey(0, 0);
case 1:
// Seek to end
return MakeKey(K, 0);
default:
// Seek to middle
return MakeKey(rnd->Next() % K, 0);
}
}
// Per-key generation
struct State {
port::AtomicPointer generation[K];
void Set(int k, intptr_t v) {
generation[k].Release_Store(reinterpret_cast<void*>(v));
}
intptr_t Get(int k) {
return reinterpret_cast<intptr_t>(generation[k].Acquire_Load());
}
State() {
for (uint32_t k = 0; k < K; k++) {
Set(k, 0);
}
}
};
// Current state of the test
State current_;
Arena arena_;
// SkipList is not protected by mu_. We just use a single writer
// thread to modify it.
SkipList<Key, Comparator> list_;
public:
ConcurrentTest() : list_(Comparator(), &arena_) { }
// REQUIRES: External synchronization
void WriteStep(Random* rnd) {
const uint32_t k = rnd->Next() % K;
const intptr_t g = current_.Get(k) + 1;
const Key key = MakeKey(k, g);
list_.Insert(key);
current_.Set(k, g);
}
void ReadStep(Random* rnd) {
// Remember the initial committed state of the skiplist.
State initial_state;
for (uint32_t k = 0; k < K; k++) {
initial_state.Set(k, current_.Get(k));
}
Key pos = RandomTarget(rnd);
SkipList<Key, Comparator>::Iterator iter(&list_);
iter.Seek(pos);
while (true) {
Key current;
if (!iter.Valid()) {
current = MakeKey(K, 0);
} else {
current = iter.key();
ASSERT_TRUE(IsValidKey(current)) << current;
}
ASSERT_LE(pos, current) << "should not go backwards";
// Verify that everything in [pos,current) was not present in
// initial_state.
while (pos < current) {
ASSERT_LT(key(pos), K) << pos;
// Note that generation 0 is never inserted, so it is ok if
// <*,0,*> is missing.
ASSERT_TRUE((gen(pos) == 0u) ||
(static_cast<int>(gen(pos)) > initial_state.Get(key(pos)))
) << "key: " << key(pos)
<< "; gen: " << gen(pos)
<< "; initgen: "
<< initial_state.Get(key(pos));
// Advance to next key in the valid key space
if (key(pos) < key(current)) {
pos = MakeKey(key(pos) + 1, 0);
} else {
pos = MakeKey(key(pos), gen(pos) + 1);
}
}
if (!iter.Valid()) {
break;
}
if (rnd->Next() % 2) {
iter.Next();
pos = MakeKey(key(pos), gen(pos) + 1);
} else {
Key new_target = RandomTarget(rnd);
if (new_target > pos) {
pos = new_target;
iter.Seek(new_target);
}
}
}
}
};
const uint32_t ConcurrentTest::K;
// Simple test that does single-threaded testing of the ConcurrentTest
// scaffolding.
TEST(SkipTest, ConcurrentWithoutThreads) {
ConcurrentTest test;
Random rnd(test::RandomSeed());
for (int i = 0; i < 10000; i++) {
test.ReadStep(&rnd);
test.WriteStep(&rnd);
}
}
class TestState {
public:
ConcurrentTest t_;
int seed_;
port::AtomicPointer quit_flag_;
enum ReaderState {
STARTING,
RUNNING,
DONE
};
explicit TestState(int s)
: seed_(s),
quit_flag_(NULL),
state_(STARTING),
state_cv_(&mu_) {}
void Wait(ReaderState s) {
mu_.Lock();
while (state_ != s) {
state_cv_.Wait();
}
mu_.Unlock();
}
void Change(ReaderState s) {
mu_.Lock();
state_ = s;
state_cv_.Signal();
mu_.Unlock();
}
private:
port::Mutex mu_;
ReaderState state_;
port::CondVar state_cv_;
};
#if 0 // disable by taocipian for anqin disable caller, so callee is unused
static void ConcurrentReader(void* arg) {
TestState* state = reinterpret_cast<TestState*>(arg);
Random rnd(state->seed_);
int64_t reads = 0;
state->Change(TestState::RUNNING);
while (!state->quit_flag_.Acquire_Load()) {
state->t_.ReadStep(&rnd);
++reads;
}
state->Change(TestState::DONE);
}
static void RunConcurrent(int run) {
const int seed = test::RandomSeed() + (run * 100);
Random rnd(seed);
const int N = 1000;
const int kSize = 1000;
for (int i = 0; i < N; i++) {
if ((i % 100) == 0) {
fprintf(stderr, "Run %d of %d\n", i, N);
}
TestState state(seed + 1);
Env::Default()->Schedule(ConcurrentReader, &state);
state.Wait(TestState::RUNNING);
for (int i = 0; i < kSize; i++) {
state.t_.WriteStep(&rnd);
}
state.quit_flag_.Release_Store(&state); // Any non-NULL arg will do
state.Wait(TestState::DONE);
}
}
#endif
#if 0 // disabled by anqin for thread blocking, need check!
TEST(SkipTest, Concurrent1) { RunConcurrent(1); }
TEST(SkipTest, Concurrent2) { RunConcurrent(2); }
TEST(SkipTest, Concurrent3) { RunConcurrent(3); }
TEST(SkipTest, Concurrent4) { RunConcurrent(4); }
TEST(SkipTest, Concurrent5) { RunConcurrent(5); }
#endif
} // namespace leveldb
int main(int argc, char** argv) {
return leveldb::test::RunAllTests();
}
<commit_msg>fix conflicts<commit_after>// Copyright (c) 2015, Baidu.com, Inc. All Rights Reserved
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
//
// 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.
#include "db/skiplist.h"
#include <set>
#include "leveldb/env.h"
#include "util/arena.h"
#include "util/hash.h"
#include "util/random.h"
#include "util/testharness.h"
namespace leveldb {
typedef uint64_t Key;
struct Comparator {
int operator()(const Key& a, const Key& b) const {
if (a < b) {
return -1;
} else if (a > b) {
return +1;
} else {
return 0;
}
}
};
class SkipTest { };
TEST(SkipTest, Empty) {
Arena arena;
Comparator cmp;
SkipList<Key, Comparator> list(cmp, &arena);
ASSERT_TRUE(!list.Contains(10));
SkipList<Key, Comparator>::Iterator iter(&list);
ASSERT_TRUE(!iter.Valid());
iter.SeekToFirst();
ASSERT_TRUE(!iter.Valid());
iter.Seek(100);
ASSERT_TRUE(!iter.Valid());
iter.SeekToLast();
ASSERT_TRUE(!iter.Valid());
}
TEST(SkipTest, InsertAndLookup) {
const int N = 2000;
const int R = 5000;
Random rnd(1000);
std::set<Key> keys;
Arena arena;
Comparator cmp;
SkipList<Key, Comparator> list(cmp, &arena);
for (int i = 0; i < N; i++) {
Key key = rnd.Next() % R;
if (keys.insert(key).second) {
list.Insert(key);
}
}
for (int i = 0; i < R; i++) {
if (list.Contains(i)) {
ASSERT_EQ(keys.count(i), 1u);
} else {
ASSERT_EQ(keys.count(i), 0u);
}
}
// Simple iterator tests
{
SkipList<Key, Comparator>::Iterator iter(&list);
ASSERT_TRUE(!iter.Valid());
iter.Seek(0);
ASSERT_TRUE(iter.Valid());
ASSERT_EQ(*(keys.begin()), iter.key());
iter.SeekToFirst();
ASSERT_TRUE(iter.Valid());
ASSERT_EQ(*(keys.begin()), iter.key());
iter.SeekToLast();
ASSERT_TRUE(iter.Valid());
ASSERT_EQ(*(keys.rbegin()), iter.key());
}
// Forward iteration test
for (int i = 0; i < R; i++) {
SkipList<Key, Comparator>::Iterator iter(&list);
iter.Seek(i);
// Compare against model iterator
std::set<Key>::iterator model_iter = keys.lower_bound(i);
for (int j = 0; j < 3; j++) {
if (model_iter == keys.end()) {
ASSERT_TRUE(!iter.Valid());
break;
} else {
ASSERT_TRUE(iter.Valid());
ASSERT_EQ(*model_iter, iter.key());
++model_iter;
iter.Next();
}
}
}
// Backward iteration test
{
SkipList<Key, Comparator>::Iterator iter(&list);
iter.SeekToLast();
// Compare against model iterator
for (std::set<Key>::reverse_iterator model_iter = keys.rbegin();
model_iter != keys.rend();
++model_iter) {
ASSERT_TRUE(iter.Valid());
ASSERT_EQ(*model_iter, iter.key());
iter.Prev();
}
ASSERT_TRUE(!iter.Valid());
}
}
// We want to make sure that with a single writer and multiple
// concurrent readers (with no synchronization other than when a
// reader's iterator is created), the reader always observes all the
// data that was present in the skip list when the iterator was
// constructor. Because insertions are happening concurrently, we may
// also observe new values that were inserted since the iterator was
// constructed, but we should never miss any values that were present
// at iterator construction time.
//
// We generate multi-part keys:
// <key,gen,hash>
// where:
// key is in range [0..K-1]
// gen is a generation number for key
// hash is hash(key,gen)
//
// The insertion code picks a random key, sets gen to be 1 + the last
// generation number inserted for that key, and sets hash to Hash(key,gen).
//
// At the beginning of a read, we snapshot the last inserted
// generation number for each key. We then iterate, including random
// calls to Next() and Seek(). For every key we encounter, we
// check that it is either expected given the initial snapshot or has
// been concurrently added since the iterator started.
class ConcurrentTest {
private:
static const uint32_t K = 4;
static uint64_t key(Key key) { return (key >> 40); }
static uint64_t gen(Key key) { return (key >> 8) & 0xffffffffu; }
static uint64_t hash(Key key) { return key & 0xff; }
static uint64_t HashNumbers(uint64_t k, uint64_t g) {
uint64_t data[2] = { k, g };
return Hash(reinterpret_cast<char*>(data), sizeof(data), 0);
}
static Key MakeKey(uint64_t k, uint64_t g) {
assert(sizeof(Key) == sizeof(uint64_t));
assert(k <= K); // We sometimes pass K to seek to the end of the skiplist
assert(g <= 0xffffffffu);
return ((k << 40) | (g << 8) | (HashNumbers(k, g) & 0xff));
}
static bool IsValidKey(Key k) {
return hash(k) == (HashNumbers(key(k), gen(k)) & 0xff);
}
static Key RandomTarget(Random* rnd) {
switch (rnd->Next() % 10) {
case 0:
// Seek to beginning
return MakeKey(0, 0);
case 1:
// Seek to end
return MakeKey(K, 0);
default:
// Seek to middle
return MakeKey(rnd->Next() % K, 0);
}
}
// Per-key generation
struct State {
port::AtomicPointer generation[K];
void Set(int k, intptr_t v) {
generation[k].Release_Store(reinterpret_cast<void*>(v));
}
intptr_t Get(int k) {
return reinterpret_cast<intptr_t>(generation[k].Acquire_Load());
}
State() {
for (uint32_t k = 0; k < K; k++) {
Set(k, 0);
}
}
};
// Current state of the test
State current_;
Arena arena_;
// SkipList is not protected by mu_. We just use a single writer
// thread to modify it.
SkipList<Key, Comparator> list_;
public:
ConcurrentTest() : list_(Comparator(), &arena_) { }
// REQUIRES: External synchronization
void WriteStep(Random* rnd) {
const uint32_t k = rnd->Next() % K;
const intptr_t g = current_.Get(k) + 1;
const Key key = MakeKey(k, g);
list_.Insert(key);
current_.Set(k, g);
}
void ReadStep(Random* rnd) {
// Remember the initial committed state of the skiplist.
State initial_state;
for (uint32_t k = 0; k < K; k++) {
initial_state.Set(k, current_.Get(k));
}
Key pos = RandomTarget(rnd);
SkipList<Key, Comparator>::Iterator iter(&list_);
iter.Seek(pos);
while (true) {
Key current;
if (!iter.Valid()) {
current = MakeKey(K, 0);
} else {
current = iter.key();
ASSERT_TRUE(IsValidKey(current)) << current;
}
ASSERT_LE(pos, current) << "should not go backwards";
// Verify that everything in [pos,current) was not present in
// initial_state.
while (pos < current) {
ASSERT_LT(key(pos), K) << pos;
// Note that generation 0 is never inserted, so it is ok if
// <*,0,*> is missing.
ASSERT_TRUE((gen(pos) == 0u) ||
(static_cast<int>(gen(pos)) > initial_state.Get(key(pos)))
) << "key: " << key(pos)
<< "; gen: " << gen(pos)
<< "; initgen: "
<< initial_state.Get(key(pos));
// Advance to next key in the valid key space
if (key(pos) < key(current)) {
pos = MakeKey(key(pos) + 1, 0);
} else {
pos = MakeKey(key(pos), gen(pos) + 1);
}
}
if (!iter.Valid()) {
break;
}
if (rnd->Next() % 2) {
iter.Next();
pos = MakeKey(key(pos), gen(pos) + 1);
} else {
Key new_target = RandomTarget(rnd);
if (new_target > pos) {
pos = new_target;
iter.Seek(new_target);
}
}
}
}
};
const uint32_t ConcurrentTest::K;
// Simple test that does single-threaded testing of the ConcurrentTest
// scaffolding.
TEST(SkipTest, ConcurrentWithoutThreads) {
ConcurrentTest test;
Random rnd(test::RandomSeed());
for (int i = 0; i < 10000; i++) {
test.ReadStep(&rnd);
test.WriteStep(&rnd);
}
}
class TestState {
public:
ConcurrentTest t_;
int seed_;
port::AtomicPointer quit_flag_;
enum ReaderState {
STARTING,
RUNNING,
DONE
};
explicit TestState(int s)
: seed_(s),
quit_flag_(NULL),
state_(STARTING),
state_cv_(&mu_) {}
void Wait(ReaderState s) {
mu_.Lock();
while (state_ != s) {
state_cv_.Wait();
}
mu_.Unlock();
}
void Change(ReaderState s) {
mu_.Lock();
state_ = s;
state_cv_.Signal();
mu_.Unlock();
}
private:
port::Mutex mu_;
ReaderState state_;
port::CondVar state_cv_;
};
static void ConcurrentReader(void* arg) {
TestState* state = reinterpret_cast<TestState*>(arg);
Random rnd(state->seed_);
int64_t reads = 0;
state->Change(TestState::RUNNING);
while (!state->quit_flag_.Acquire_Load()) {
state->t_.ReadStep(&rnd);
++reads;
}
state->Change(TestState::DONE);
}
static void RunConcurrent(int run) {
const int seed = test::RandomSeed() + (run * 100);
Random rnd(seed);
const int N = 1000;
const int kSize = 1000;
for (int i = 0; i < N; i++) {
if ((i % 100) == 0) {
fprintf(stderr, "Run %d of %d\n", i, N);
}
TestState state(seed + 1);
Env::Default()->Schedule(ConcurrentReader, &state);
state.Wait(TestState::RUNNING);
for (int i = 0; i < kSize; i++) {
state.t_.WriteStep(&rnd);
}
state.quit_flag_.Release_Store(&state); // Any non-NULL arg will do
state.Wait(TestState::DONE);
}
}
TEST(SkipTest, Concurrent1) { RunConcurrent(1); }
TEST(SkipTest, Concurrent2) { RunConcurrent(2); }
TEST(SkipTest, Concurrent3) { RunConcurrent(3); }
TEST(SkipTest, Concurrent4) { RunConcurrent(4); }
TEST(SkipTest, Concurrent5) { RunConcurrent(5); }
} // namespace leveldb
int main(int argc, char** argv) {
return leveldb::test::RunAllTests();
}
<|endoftext|> |
<commit_before>#ifndef __Z2H_PARSER__
#define __Z2H_PARSER__ = 1
#include <cmath>
#include <string>
#include <vector>
#include <fstream>
#include <sstream>
#include <iostream>
#include <stddef.h>
#include <sys/stat.h>
#include <functional>
#include "token.hpp"
#include "symbol.hpp"
#include "binder.hpp"
using namespace std::placeholders;
namespace z2h {
template <typename TAst>
class Token;
template <typename TAst>
class Symbol;
template <typename TAst>
class Grammar;
class ParserException : public std::exception {
const char *_filename;
size_t _line;
const std::string _message;
std::string _what;
public:
ParserException(const char *filename, size_t line, const std::string &message)
: _filename(filename)
, _line(line)
, _message(message) {
std::ostringstream out;
out << "filename=" << _filename
<< " line=" << _line
<< " msg=" << _message
<< std::endl;
_what = out.str();
}
virtual const char * what() const throw() {
return _what.c_str();
}
};
template <typename TAst, typename TParser>
struct Parser : public Binder<TAst, TParser> {
std::string source;
size_t position;
std::vector<Token<TAst> *> tokens;
size_t index;
~Parser() {
while (!tokens.empty())
delete tokens.back(), tokens.pop_back();
}
Parser()
: source("")
, position(0)
, tokens({})
, index(0) {
}
// Symbols must be defined by the inheriting parser
virtual std::vector<Symbol<TAst> *> Symbols() = 0;
Token<TAst> * Scan() {
auto eof = Symbols()[0];
Symbol<TAst> *match = nullptr;
if (position < source.length()) {
size_t end = position;
bool skip = false;
for (auto symbol : Symbols()) {
long length = symbol->Scan(symbol, source.substr(position, source.length() - position), position);
if (position + abs(length) > end || (match != nullptr && symbol->lbp > match->lbp && position + abs(length) == end)) {
match = symbol;
end = position + abs(length);
skip = length < 0;
}
}
if (position == end) {
throw ParserException(__FILE__, __LINE__, "Parser::Scan: invalid symbol");
}
return new Token<TAst>(match, source, position, end - position, skip);
}
return new Token<TAst>(eof, source, position, 0, false); //eof
}
Token<TAst> * LookAhead(size_t distance, bool skips = false) {
Token<TAst> *token = nullptr;
auto i = index;
while (distance) {
if (i < tokens.size()) {
token = tokens[i];
}
else {
token = Scan();
position += token->length;
tokens.push_back(token);
}
if (skips || !token->skip)
--distance;
++i;
}
return token;
}
Token<TAst> * Consume(Symbol<TAst> *expected = nullptr, const std::string &message = "") {
auto token = LookAhead(1);
while (token->position != tokens[index++]->position);
if (nullptr != expected && *expected != *token->symbol)
throw ParserException(__FILE__, __LINE__, message);
return token;
}
std::vector<Token<TAst> *> Tokenize() {
auto eof = Symbols()[0];
auto token = Consume();
while (*eof != *token->symbol) {
token = Consume();
}
return tokens;
}
std::string Load(const std::string &filename) {
struct stat buffer;
if (stat (filename.c_str(), &buffer) != 0)
ParserException(__FILE__, __LINE__, filename + " doesn't exist or is unreadable");
std::ifstream file(filename);
std::string text((std::istreambuf_iterator<char>(file)), std::istreambuf_iterator<char>());
return text;
}
TAst ParseFile(const std::string &filename) {
auto source = Load(filename);
return Parse(source);
}
TAst Parse(std::string source) {
this->source = source;
return Expression();
}
TAst Expression(size_t rbp = 0) {
auto *curr = Consume();
if (nullptr == curr->symbol->Nud) {
std::ostringstream out;
out << "unexpected: nullptr==Nud curr=" << *curr;
throw ParserException(__FILE__, __LINE__, out.str());
}
TAst left = curr->symbol->Nud(curr);
auto *next = LookAhead(1);
while (rbp < next->symbol->lbp) {
next = Consume();
left = next->symbol->Led(left, next);
}
return left;
}
TAst Statement() {
auto *la1 = LookAhead(1);
if (la1->symbol->Std) {
Consume();
return la1->symbol->Std();
}
auto ast = Expression();
Consume(1, "EndOfStatement expected!");
return ast;
}
size_t Line() {
return 0;
}
size_t Column() {
return 0;
}
};
}
#endif /*__Z2H_PARSER__*/
<commit_msg>refactored exception class... -sai<commit_after>#ifndef __Z2H_PARSER__
#define __Z2H_PARSER__ = 1
#include <cmath>
#include <string>
#include <vector>
#include <fstream>
#include <sstream>
#include <iostream>
#include <stddef.h>
#include <sys/stat.h>
#include <functional>
#include "token.hpp"
#include "symbol.hpp"
#include "binder.hpp"
using namespace std::placeholders;
namespace z2h {
template <typename TAst>
class Token;
template <typename TAst>
class Symbol;
template <typename TAst>
class Grammar;
class ParserException : public std::exception {
const char *_file;
size_t _line;
const std::string _message;
std::string _what;
public:
ParserException(const char *file, size_t line, const std::string &message)
: _file(file)
, _line(line)
, _message(message) {
std::ostringstream out;
out << _filename << ":" << _line << " " << _message << std::endl;
_what = out.str();
}
virtual const char * what() const throw() {
return _what.c_str();
}
};
template <typename TAst, typename TParser>
struct Parser : public Binder<TAst, TParser> {
std::string source;
size_t position;
std::vector<Token<TAst> *> tokens;
size_t index;
~Parser() {
while (!tokens.empty())
delete tokens.back(), tokens.pop_back();
}
Parser()
: source("")
, position(0)
, tokens({})
, index(0) {
}
// Symbols must be defined by the inheriting parser
virtual std::vector<Symbol<TAst> *> Symbols() = 0;
Token<TAst> * Scan() {
auto eof = Symbols()[0];
Symbol<TAst> *match = nullptr;
if (position < source.length()) {
size_t end = position;
bool skip = false;
for (auto symbol : Symbols()) {
long length = symbol->Scan(symbol, source.substr(position, source.length() - position), position);
if (position + abs(length) > end || (match != nullptr && symbol->lbp > match->lbp && position + abs(length) == end)) {
match = symbol;
end = position + abs(length);
skip = length < 0;
}
}
if (position == end) {
throw ParserException(__FILE__, __LINE__, "Parser::Scan: invalid symbol");
}
return new Token<TAst>(match, source, position, end - position, skip);
}
return new Token<TAst>(eof, source, position, 0, false); //eof
}
Token<TAst> * LookAhead(size_t distance, bool skips = false) {
Token<TAst> *token = nullptr;
auto i = index;
while (distance) {
if (i < tokens.size()) {
token = tokens[i];
}
else {
token = Scan();
position += token->length;
tokens.push_back(token);
}
if (skips || !token->skip)
--distance;
++i;
}
return token;
}
Token<TAst> * Consume(Symbol<TAst> *expected = nullptr, const std::string &message = "") {
auto token = LookAhead(1);
while (token->position != tokens[index++]->position);
if (nullptr != expected && *expected != *token->symbol)
throw ParserException(__FILE__, __LINE__, message);
return token;
}
std::vector<Token<TAst> *> Tokenize() {
auto eof = Symbols()[0];
auto token = Consume();
while (*eof != *token->symbol) {
token = Consume();
}
return tokens;
}
std::string Load(const std::string &filename) {
struct stat buffer;
if (stat (filename.c_str(), &buffer) != 0)
ParserException(__FILE__, __LINE__, filename + " doesn't exist or is unreadable");
std::ifstream file(filename);
std::string text((std::istreambuf_iterator<char>(file)), std::istreambuf_iterator<char>());
return text;
}
TAst ParseFile(const std::string &filename) {
auto source = Load(filename);
return Parse(source);
}
TAst Parse(std::string source) {
this->source = source;
return Expression();
}
TAst Expression(size_t rbp = 0) {
auto *curr = Consume();
if (nullptr == curr->symbol->Nud) {
std::ostringstream out;
out << "unexpected: nullptr==Nud curr=" << *curr;
throw ParserException(__FILE__, __LINE__, out.str());
}
TAst left = curr->symbol->Nud(curr);
auto *next = LookAhead(1);
while (rbp < next->symbol->lbp) {
next = Consume();
left = next->symbol->Led(left, next);
}
return left;
}
TAst Statement() {
auto *la1 = LookAhead(1);
if (la1->symbol->Std) {
Consume();
return la1->symbol->Std();
}
auto ast = Expression();
Consume(1, "EndOfStatement expected!");
return ast;
}
size_t Line() {
return 0;
}
size_t Column() {
return 0;
}
};
}
#endif /*__Z2H_PARSER__*/
<|endoftext|> |
<commit_before>#ifndef BFC_PARSER_HPP
#define BFC_PARSER_HPP
#include "lexer.hpp"
#include "ast.hpp"
namespace bfc {
template <class Lexer>
class Parser {
using result = typename Lexer::result;
public:
Parser(Lexer lexer) : this.lexer(lexer) {}
std:vector<AstNode> parse() {
/* create result to hold lexer result */
result res = OK;
/* create token to pass into lexer */
token tok;
for(;;) {
res = lexer.next(tok);
switch (res) {
case OK:
updateAst(tok);
break;
case DONE:
return ast;
case FAIL:
default:
}
}
}
private:
Lexer lexer;
/* vector of instructions to return */
std::vector<std::unique_ptr<AstNode>> ast;
/* stack to manage nested instructions in loop nodes */
std::stack<std::vector<std::unique_ptr<AstNode>>> stack;
void updateAst(token &tok) {
token::type kind = tok.kind;
position pos = tok.pos;
std::unique_ptr<AstNode> node;
switch (kind) {
case token::INC:
node = std::make_unique<AddNode>(pos, 1);
ast.push_back(node);
break;
case token::DEC:
node = std::make_unique<AddNode>(pos, -1);
ast.push_back(node);
break;
case token::MOVE_R:
node = std::make_unique<MoveNode>(pos, 1);
ast.push_back(node);
break;
case token::MOVE_L:
node = std::make_unique<MoveNode>(pos, -1);
ast.push_back(node);
break;
case token::LOOP_BEGIN:
stack.push(ast);
ast = std::vector<std::unique_ptr<AstNode>>();
break;
case token::LOOP_END:
if (!stack.empty()) {
node = std::make_unique<LoopNode>(pos, ast);
ast = stack.top();
stack.pop();
ast.push_back(node);
} else {
// throw exception
}
break;
case token::PUT_CHAR:
node = std::make_unique<WriteNode>(pos);
ast.push_back(node);
break;
case token::GET_CHAR:
node = std::make_unique<ReadNode>(pos);
ast.push_back(node);
break;
default:
}
}
};
}
#endif /* !BFC_PARSER_HPP */
<commit_msg>Update result type in parser<commit_after>#ifndef BFC_PARSER_HPP
#define BFC_PARSER_HPP
#include "lexer.hpp"
#include "result.hpp"
#include "ast.hpp"
namespace bfc {
template <class Lexer>
class Parser {
public:
Parser(Lexer lexer) : this.lexer(lexer) {}
std:vector<AstNode> parse() {
/* create result to hold lexer result */
result_type res = result_type::OK;
/* create token to pass into lexer */
token tok;
for(;;) {
res = lexer.next(tok);
switch (res) {
case OK:
updateAst(tok);
break;
case DONE:
return ast;
case FAIL:
default:
}
}
}
private:
Lexer lexer;
/* vector of instructions to return */
std::vector<std::unique_ptr<AstNode>> ast;
/* stack to manage nested instructions in loop nodes */
std::stack<std::vector<std::unique_ptr<AstNode>>> stack;
void updateAst(token &tok) {
token::type kind = tok.kind;
position pos = tok.pos;
std::unique_ptr<AstNode> node;
switch (kind) {
case token::INC:
node = std::make_unique<AddNode>(pos, 1);
ast.push_back(node);
break;
case token::DEC:
node = std::make_unique<AddNode>(pos, -1);
ast.push_back(node);
break;
case token::MOVE_R:
node = std::make_unique<MoveNode>(pos, 1);
ast.push_back(node);
break;
case token::MOVE_L:
node = std::make_unique<MoveNode>(pos, -1);
ast.push_back(node);
break;
case token::LOOP_BEGIN:
stack.push(ast);
ast = std::vector<std::unique_ptr<AstNode>>();
break;
case token::LOOP_END:
if (!stack.empty()) {
node = std::make_unique<LoopNode>(pos, ast);
ast = stack.top();
stack.pop();
ast.push_back(node);
} else {
// throw exception
}
break;
case token::PUT_CHAR:
node = std::make_unique<WriteNode>(pos);
ast.push_back(node);
break;
case token::GET_CHAR:
node = std::make_unique<ReadNode>(pos);
ast.push_back(node);
break;
default:
}
}
};
}
#endif /* !BFC_PARSER_HPP */
<|endoftext|> |
<commit_before>#include <assert.h>
#include <iostream>
#include <map>
#include <memory>
#include <vector>
#include "common/simhubdeviceplugin.h"
#include "main.h"
// -- public C FFI
extern "C" {
int simplug_init(SPHANDLE *plugin_instance, LoggingFunctionCB logger)
{
*plugin_instance = new PokeyDevicePluginStateManager(logger);
return 0;
}
int simplug_config_passthrough(SPHANDLE plugin_instance, void *libconfig_instance)
{
return static_cast<PluginStateManager *>(plugin_instance)->configPassthrough(static_cast<libconfig::Config *>(libconfig_instance));
}
int simplug_preflight_complete(SPHANDLE plugin_instance)
{
return static_cast<PluginStateManager *>(plugin_instance)->preflightComplete();
}
void simplug_commence_eventing(SPHANDLE plugin_instance, EnqueueEventHandler enqueue_callback, void *arg)
{
static_cast<PluginStateManager *>(plugin_instance)->commenceEventing(enqueue_callback, arg);
}
int simplug_deliver_value(SPHANDLE plugin_instance, GenericTLV *value)
{
return static_cast<PluginStateManager *>(plugin_instance)->deliverValue(value);
}
void simplug_cease_eventing(SPHANDLE plugin_instance)
{
static_cast<PluginStateManager *>(plugin_instance)->ceaseEventing();
}
void simplug_release(SPHANDLE plugin_instance)
{
assert(plugin_instance);
delete static_cast<PluginStateManager *>(plugin_instance);
}
}
PokeyDevicePluginStateManager *PokeyDevicePluginStateManager::_StateManagerInstance = NULL;
// -- private C++ pokey plugin implementation
PokeyDevicePluginStateManager::PokeyDevicePluginStateManager(LoggingFunctionCB logger)
: PluginStateManager(logger)
{
_numberOfDevices = 0; ///< 0 devices discovered
_devices = (sPoKeysNetworkDeviceSummary *)calloc(sizeof(sPoKeysNetworkDeviceSummary),
16); ///< 0 initialise the network device summary
}
//! static getter for singleton instance of our class
PokeyDevicePluginStateManager *PokeyDevicePluginStateManager::StateManagerInstance(void)
{
return _StateManagerInstance;
}
PokeyDevicePluginStateManager::~PokeyDevicePluginStateManager(void)
{
// TODO: enable once shtudown implemented
if (_pluginThread != NULL) {
if (_pluginThread->joinable()) {
ceaseEventing();
_pluginThread->join();
}
_deviceList.clear();
delete _pluginThread;
delete _devices;
}
}
int PokeyDevicePluginStateManager::deliverValue(GenericTLV *data)
{
assert(data);
PokeyDevice *device = NULL;
bool ret = targetFromDeviceTargetList(data->name, device);
if (ret) {
if (data->type == ConfigType::CONFIG_BOOL) {
device->targetValue(data->name, (int)data->value);
}
}
return 0;
}
void PokeyDevicePluginStateManager::enumerateDevices(void)
{
_numberOfDevices = PK_EnumerateNetworkDevices(_devices, 800);
assert(_numberOfDevices > 0);
for (int i = 0; i < _numberOfDevices; i++) {
PokeyDevice *device = new PokeyDevice(_devices[i], i);
_logger(LOG_INFO, " - #%s %s %s (v%d.%d.%d) - %u.%u.%u.%u ", device->serialNumber().c_str(), device->hardwareTypeString().c_str(), device->deviceData().DeviceName,
device->firmwareMajorMajorVersion(), device->firmwareMajorVersion(), device->firmwareMinorVersion(), device->ipAddress()[0], device->ipAddress()[1],
device->ipAddress()[2], device->ipAddress()[3]);
_deviceList.emplace(device->serialNumber(), device);
}
}
bool PokeyDevicePluginStateManager::addTargetToDeviceTargetList(std::string target, PokeyDevice *device)
{
_deviceTargetList.emplace(target, device);
return true;
}
bool PokeyDevicePluginStateManager::targetFromDeviceTargetList(std::string key, PokeyDevice *&ret)
{
std::map<std::string, PokeyDevice *>::iterator it = _deviceTargetList.find(key);
if (it != _deviceTargetList.end()) {
ret = it->second;
return true;
}
return false;
}
PokeyDevice *PokeyDevicePluginStateManager::device(std::string serialNumber)
{
if (_deviceList.count(serialNumber)) {
return _deviceList.find(serialNumber)->second;
}
else {
return NULL;
}
}
bool PokeyDevicePluginStateManager::validateConfig(libconfig::SettingIterator iter)
{
bool retValue = true;
try {
iter->lookup("pins");
}
catch (const libconfig::SettingNotFoundException &nfex) {
_logger(LOG_ERROR, "Config file parse error at %s. Skipping....", nfex.getPath());
retValue = false;
}
return retValue;
}
bool PokeyDevicePluginStateManager::getDeviceConfiguration(libconfig::SettingIterator iter, PokeyDevice *pokeyDevice)
{
bool retVal = true;
std::string configSerialNumber = "";
std::string configName = "";
try {
iter->lookupValue("serialNumber", configSerialNumber);
pokeyDevice = device(configSerialNumber);
if (pokeyDevice == NULL) {
_logger(LOG_ERROR, " - #%s. No physical device. Skipping....", configSerialNumber.c_str());
retVal = false;
}
else {
iter->lookupValue("name", configName);
if (configName != pokeyDevice->name().c_str()) {
_logger(LOG_INFO, " - Name mismatch. %s <-> %s", configName.c_str(), pokeyDevice->name().c_str());
}
}
}
catch (const libconfig::SettingNotFoundException &nfex) {
_logger(LOG_ERROR, "Config file parse error at %s. Skipping....", nfex.getPath());
retVal = false;
}
return retVal;
}
bool PokeyDevicePluginStateManager::getDevicePinsConfiguration(libconfig::Setting *pins, PokeyDevice *pokeyDevice)
{
/** pin = 4,
name = "S_OH_GROUND_CALL",
type = "DIGITAL_INPUT",
default = 0
**/
_logger(LOG_INFO, "------- %s", pokeyDevice->name().c_str());
bool retVal = true;
int pinCount = pins->getLength();
if (pinCount > 0) {
_logger(LOG_INFO, " - Found %d pins", pinCount);
int pinIndex = 0;
for (libconfig::SettingIterator iter = pins->begin(); iter != pins->end(); iter++) {
int pinNumber = 0;
std::string pinName = "";
std::string pinType = "";
bool pinDefault = false;
try {
iter->lookupValue("pin", pinNumber);
iter->lookupValue("name", pinName);
iter->lookupValue("type", pinType);
}
catch (const libconfig::SettingNotFoundException &nfex) {
_logger(LOG_ERROR, "Config file parse error at %s. Skipping....", nfex.getPath());
}
if (pokeyDevice->validatePinCapability(pinNumber, pinType)) {
if (pinType == "DIGITAL_OUTPUT") {
bool poo = addTargetToDeviceTargetList(pinName, pokeyDevice);
if (!poo) {
_logger(LOG_INFO, " - [%d] Failed to add target. Duplicate %s", pinIndex, pinName.c_str());
}
else {
_logger(LOG_INFO, " - [%d] Added target %s on pin %d", pinIndex, pinName.c_str(), pinNumber);
pinIndex++;
}
}
}
else {
continue;
}
}
}
else {
retVal = false;
}
return retVal;
}
int PokeyDevicePluginStateManager::preflightComplete(void)
{
int retVal = PREFLIGHT_OK;
libconfig::Setting *devicesConfiguraiton = NULL;
enumerateDevices();
try {
devicesConfiguraiton = &_config->lookup("configuration");
}
catch (const libconfig::SettingNotFoundException &nfex) {
_logger(LOG_ERROR, "Config file parse error at %s. Skipping....", nfex.getPath());
}
for (libconfig::SettingIterator iter = devicesConfiguraiton->begin(); iter != devicesConfiguraiton->end(); iter++) {
std::string serialNumber = "";
iter->lookupValue("serialNumber", serialNumber);
PokeyDevice *pokeyDevice = device(serialNumber);
// check that the configuration has the required config sections
if (!validateConfig(iter)) {
continue;
}
if (getDeviceConfiguration(iter, pokeyDevice) == 0) {
continue;
}
getDevicePinsConfiguration(&iter->lookup("pins"), pokeyDevice);
}
if (_numberOfDevices > 0) {
_logger(LOG_INFO, " - Discovered %d pokey devices", _numberOfDevices);
retVal = PREFLIGHT_OK;
}
else {
_logger(LOG_INFO, " - No Pokey devices discovered");
}
return retVal;
}
<commit_msg>rename<commit_after>#include <assert.h>
#include <iostream>
#include <map>
#include <memory>
#include <vector>
#include "common/simhubdeviceplugin.h"
#include "main.h"
// -- public C FFI
extern "C" {
int simplug_init(SPHANDLE *plugin_instance, LoggingFunctionCB logger)
{
*plugin_instance = new PokeyDevicePluginStateManager(logger);
return 0;
}
int simplug_config_passthrough(SPHANDLE plugin_instance, void *libconfig_instance)
{
return static_cast<PluginStateManager *>(plugin_instance)->configPassthrough(static_cast<libconfig::Config *>(libconfig_instance));
}
int simplug_preflight_complete(SPHANDLE plugin_instance)
{
return static_cast<PluginStateManager *>(plugin_instance)->preflightComplete();
}
void simplug_commence_eventing(SPHANDLE plugin_instance, EnqueueEventHandler enqueue_callback, void *arg)
{
static_cast<PluginStateManager *>(plugin_instance)->commenceEventing(enqueue_callback, arg);
}
int simplug_deliver_value(SPHANDLE plugin_instance, GenericTLV *value)
{
return static_cast<PluginStateManager *>(plugin_instance)->deliverValue(value);
}
void simplug_cease_eventing(SPHANDLE plugin_instance)
{
static_cast<PluginStateManager *>(plugin_instance)->ceaseEventing();
}
void simplug_release(SPHANDLE plugin_instance)
{
assert(plugin_instance);
delete static_cast<PluginStateManager *>(plugin_instance);
}
}
PokeyDevicePluginStateManager *PokeyDevicePluginStateManager::_StateManagerInstance = NULL;
// -- private C++ pokey plugin implementation
PokeyDevicePluginStateManager::PokeyDevicePluginStateManager(LoggingFunctionCB logger)
: PluginStateManager(logger)
{
_numberOfDevices = 0; ///< 0 devices discovered
_devices = (sPoKeysNetworkDeviceSummary *)calloc(sizeof(sPoKeysNetworkDeviceSummary),
16); ///< 0 initialise the network device summary
}
//! static getter for singleton instance of our class
PokeyDevicePluginStateManager *PokeyDevicePluginStateManager::StateManagerInstance(void)
{
return _StateManagerInstance;
}
PokeyDevicePluginStateManager::~PokeyDevicePluginStateManager(void)
{
// TODO: enable once shtudown implemented
if (_pluginThread != NULL) {
if (_pluginThread->joinable()) {
ceaseEventing();
_pluginThread->join();
}
_deviceList.clear();
delete _pluginThread;
delete _devices;
}
}
int PokeyDevicePluginStateManager::deliverValue(GenericTLV *data)
{
assert(data);
PokeyDevice *device = NULL;
bool ret = targetFromDeviceTargetList(data->name, device);
if (ret) {
if (data->type == ConfigType::CONFIG_BOOL) {
device->targetValue(data->name, (int)data->value);
}
}
return 0;
}
void PokeyDevicePluginStateManager::enumerateDevices(void)
{
_numberOfDevices = PK_EnumerateNetworkDevices(_devices, 800);
assert(_numberOfDevices > 0);
for (int i = 0; i < _numberOfDevices; i++) {
PokeyDevice *device = new PokeyDevice(_devices[i], i);
_logger(LOG_INFO, " - #%s %s %s (v%d.%d.%d) - %u.%u.%u.%u ", device->serialNumber().c_str(), device->hardwareTypeString().c_str(), device->deviceData().DeviceName,
device->firmwareMajorMajorVersion(), device->firmwareMajorVersion(), device->firmwareMinorVersion(), device->ipAddress()[0], device->ipAddress()[1],
device->ipAddress()[2], device->ipAddress()[3]);
_deviceList.emplace(device->serialNumber(), device);
}
}
bool PokeyDevicePluginStateManager::addTargetToDeviceTargetList(std::string target, PokeyDevice *device)
{
_deviceTargetList.emplace(target, device);
return true;
}
bool PokeyDevicePluginStateManager::targetFromDeviceTargetList(std::string key, PokeyDevice *&ret)
{
std::map<std::string, PokeyDevice *>::iterator it = _deviceTargetList.find(key);
if (it != _deviceTargetList.end()) {
ret = it->second;
return true;
}
return false;
}
PokeyDevice *PokeyDevicePluginStateManager::device(std::string serialNumber)
{
if (_deviceList.count(serialNumber)) {
return _deviceList.find(serialNumber)->second;
}
else {
return NULL;
}
}
bool PokeyDevicePluginStateManager::validateConfig(libconfig::SettingIterator iter)
{
bool retValue = true;
try {
iter->lookup("pins");
}
catch (const libconfig::SettingNotFoundException &nfex) {
_logger(LOG_ERROR, "Config file parse error at %s. Skipping....", nfex.getPath());
retValue = false;
}
return retValue;
}
bool PokeyDevicePluginStateManager::deviceConfiguration(libconfig::SettingIterator iter, PokeyDevice *pokeyDevice)
{
bool retVal = true;
std::string configSerialNumber = "";
std::string configName = "";
try {
iter->lookupValue("serialNumber", configSerialNumber);
pokeyDevice = device(configSerialNumber);
if (pokeyDevice == NULL) {
_logger(LOG_ERROR, " - #%s. No physical device. Skipping....", configSerialNumber.c_str());
retVal = false;
}
else {
iter->lookupValue("name", configName);
if (configName != pokeyDevice->name().c_str()) {
_logger(LOG_INFO, " - Name mismatch. %s <-> %s", configName.c_str(), pokeyDevice->name().c_str());
}
}
}
catch (const libconfig::SettingNotFoundException &nfex) {
_logger(LOG_ERROR, "Config file parse error at %s. Skipping....", nfex.getPath());
retVal = false;
}
return retVal;
}
bool PokeyDevicePluginStateManager::getDevicePinsConfiguration(libconfig::Setting *pins, PokeyDevice *pokeyDevice)
{
/** pin = 4,
name = "S_OH_GROUND_CALL",
type = "DIGITAL_INPUT",
default = 0
**/
_logger(LOG_INFO, "------- %s", pokeyDevice->name().c_str());
bool retVal = true;
int pinCount = pins->getLength();
if (pinCount > 0) {
_logger(LOG_INFO, " - Found %d pins", pinCount);
int pinIndex = 0;
for (libconfig::SettingIterator iter = pins->begin(); iter != pins->end(); iter++) {
int pinNumber = 0;
std::string pinName = "";
std::string pinType = "";
bool pinDefault = false;
try {
iter->lookupValue("pin", pinNumber);
iter->lookupValue("name", pinName);
iter->lookupValue("type", pinType);
}
catch (const libconfig::SettingNotFoundException &nfex) {
_logger(LOG_ERROR, "Config file parse error at %s. Skipping....", nfex.getPath());
}
if (pokeyDevice->validatePinCapability(pinNumber, pinType)) {
if (pinType == "DIGITAL_OUTPUT") {
bool poo = addTargetToDeviceTargetList(pinName, pokeyDevice);
if (!poo) {
_logger(LOG_INFO, " - [%d] Failed to add target. Duplicate %s", pinIndex, pinName.c_str());
}
else {
_logger(LOG_INFO, " - [%d] Added target %s on pin %d", pinIndex, pinName.c_str(), pinNumber);
pinIndex++;
}
}
}
else {
continue;
}
}
}
else {
retVal = false;
}
return retVal;
}
int PokeyDevicePluginStateManager::preflightComplete(void)
{
int retVal = PREFLIGHT_OK;
libconfig::Setting *devicesConfiguraiton = NULL;
enumerateDevices();
try {
devicesConfiguraiton = &_config->lookup("configuration");
}
catch (const libconfig::SettingNotFoundException &nfex) {
_logger(LOG_ERROR, "Config file parse error at %s. Skipping....", nfex.getPath());
}
for (libconfig::SettingIterator iter = devicesConfiguraiton->begin(); iter != devicesConfiguraiton->end(); iter++) {
std::string serialNumber = "";
iter->lookupValue("serialNumber", serialNumber);
PokeyDevice *pokeyDevice = device(serialNumber);
// check that the configuration has the required config sections
if (!validateConfig(iter)) {
continue;
}
if (getDeviceConfiguration(iter, pokeyDevice) == 0) {
continue;
}
getDevicePinsConfiguration(&iter->lookup("pins"), pokeyDevice);
}
if (_numberOfDevices > 0) {
_logger(LOG_INFO, " - Discovered %d pokey devices", _numberOfDevices);
retVal = PREFLIGHT_OK;
}
else {
_logger(LOG_INFO, " - No Pokey devices discovered");
}
return retVal;
}
<|endoftext|> |
<commit_before>/*
* Copyright (c) 2009, Piotr Korzuszek
* 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 <organization> 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 HOLDER OR
* CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
* EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
* PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS;
* OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,
* WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR
* OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE,
* EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
#include "MessageBoard.h"
#include <limits>
#include <assert.h>
#include "common.h"
namespace Race {
/** What is the most number of messages that can be kept */
const unsigned UPPER_LIMIT = 100;
/** To what count value message board will be cleaned */
const unsigned LOWER_LIMIT = 30;
struct Comparator {
bool operator() (unsigned s1, unsigned s2) const
{
return s1 > s2; // reverse result will sort in reverse order
}
};
MessageBoard::MessageBoard() :
m_id(0)
{
}
MessageBoard::~MessageBoard()
{
}
const CL_String &MessageBoard::getMessageString(int p_id)
{
assert(m_messageMap.find(p_id) != m_messageMap.end());
return m_messageMap[p_id].m_msg;
}
unsigned MessageBoard::getMessageCreationTime(int p_id)
{
assert(m_messageMap.find(p_id) != m_messageMap.end());
return m_messageMap[p_id].m_creationTime;
}
std::vector<int> MessageBoard::getMessageIdsYoungerThat(unsigned p_ageMs, unsigned p_limit)
{
std::vector<int> result;
const unsigned now = CL_System::get_time();
TMessageMapPair pair;
foreach (pair, m_messageMap) {
if (now - pair.second.m_creationTime < p_ageMs) {
result.push_back(pair.first);
}
}
return result;
}
int MessageBoard::addMessage(const CL_String &p_message)
{
const int id = nextId();
Message msg = { p_message, CL_System::get_time() };
m_messageMap[id] = msg;
checkLimits();
return id;
}
int MessageBoard::nextId()
{
bool overflow = false;
do {
if (m_id != std::numeric_limits<int>::max()) {
++m_id;
if (!overflow) {
overflow = true;
} else {
assert(0 && "Lack of id's");
}
} else {
m_id = 1;
}
} while (m_messageMap.find(m_id) == m_messageMap.end());
return m_id;
}
void MessageBoard::checkLimits()
{
if (m_messageMap.size() > UPPER_LIMIT) {
// remove oldest messages to reach the LOWER_LIMIT
// create a creation time => id map to find oldest ones
typedef std::multimap<unsigned, int, Comparator> TTimeIdMap;
typedef std::pair<unsigned, int> TTimeIdPair;
typedef TTimeIdMap::iterator TTimeIdMapItor;
TTimeIdMap timeIdMap;
TMessageMapPair pair;
foreach (pair, m_messageMap) {
timeIdMap.insert(std::pair<unsigned, int>(pair.second.m_creationTime, pair.first));
}
// kepp only the youngest
unsigned i = 1;
for (TTimeIdMapItor it = timeIdMap.begin(); it != timeIdMap.end(); ++it, ++i) {
if (i > LOWER_LIMIT) {
m_messageMap.erase(it->second);
}
}
}
}
}
<commit_msg>Forget about p_limit parameter<commit_after>/*
* Copyright (c) 2009, Piotr Korzuszek
* 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 <organization> 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 HOLDER OR
* CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
* EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
* PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS;
* OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,
* WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR
* OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE,
* EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
#include "MessageBoard.h"
#include <limits>
#include <assert.h>
#include "common.h"
namespace Race {
/** What is the most number of messages that can be kept */
const unsigned UPPER_LIMIT = 100;
/** To what count value message board will be cleaned */
const unsigned LOWER_LIMIT = 30;
struct Comparator {
bool operator() (unsigned s1, unsigned s2) const
{
return s1 > s2; // reverse result will sort in reverse order
}
};
MessageBoard::MessageBoard() :
m_id(0)
{
}
MessageBoard::~MessageBoard()
{
}
const CL_String &MessageBoard::getMessageString(int p_id)
{
assert(m_messageMap.find(p_id) != m_messageMap.end());
return m_messageMap[p_id].m_msg;
}
unsigned MessageBoard::getMessageCreationTime(int p_id)
{
assert(m_messageMap.find(p_id) != m_messageMap.end());
return m_messageMap[p_id].m_creationTime;
}
std::vector<int> MessageBoard::getMessageIdsYoungerThat(unsigned p_ageMs, unsigned p_limit)
{
std::vector<int> result;
if (p_limit != 0) {
const unsigned now = CL_System::get_time();
TMessageMapPair pair;
foreach (pair, m_messageMap) {
if (now - pair.second.m_creationTime < p_ageMs) {
result.push_back(pair.first);
if (result.size() == p_limit) {
break;
}
}
}
}
return result;
}
int MessageBoard::addMessage(const CL_String &p_message)
{
const int id = nextId();
Message msg = { p_message, CL_System::get_time() };
m_messageMap[id] = msg;
checkLimits();
return id;
}
int MessageBoard::nextId()
{
bool overflow = false;
do {
if (m_id != std::numeric_limits<int>::max()) {
++m_id;
if (!overflow) {
overflow = true;
} else {
assert(0 && "Lack of id's");
}
} else {
m_id = 1;
}
} while (m_messageMap.find(m_id) == m_messageMap.end());
return m_id;
}
void MessageBoard::checkLimits()
{
if (m_messageMap.size() > UPPER_LIMIT) {
// remove oldest messages to reach the LOWER_LIMIT
// create a creation time => id map to find oldest ones
typedef std::multimap<unsigned, int, Comparator> TTimeIdMap;
typedef std::pair<unsigned, int> TTimeIdPair;
typedef TTimeIdMap::iterator TTimeIdMapItor;
TTimeIdMap timeIdMap;
TMessageMapPair pair;
foreach (pair, m_messageMap) {
timeIdMap.insert(std::pair<unsigned, int>(pair.second.m_creationTime, pair.first));
}
// kepp only the youngest
unsigned i = 1;
for (TTimeIdMapItor it = timeIdMap.begin(); it != timeIdMap.end(); ++it, ++i) {
if (i > LOWER_LIMIT) {
m_messageMap.erase(it->second);
}
}
}
}
}
<|endoftext|> |
<commit_before>// This file is a shim for zig1. The real implementations of these are in
// src-self-hosted/stage1.zig
#include "userland.h"
#include "util.hpp"
#include "zig_llvm.h"
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
Error stage2_translate_c(struct Stage2Ast **out_ast,
struct Stage2ErrorMsg **out_errors_ptr, size_t *out_errors_len,
const char **args_begin, const char **args_end, const char *resources_path)
{
const char *msg = "stage0 called stage2_translate_c";
stage2_panic(msg, strlen(msg));
}
void stage2_free_clang_errors(struct Stage2ErrorMsg *ptr, size_t len) {
const char *msg = "stage0 called stage2_free_clang_errors";
stage2_panic(msg, strlen(msg));
}
void stage2_zen(const char **ptr, size_t *len) {
const char *msg = "stage0 called stage2_zen";
stage2_panic(msg, strlen(msg));
}
void stage2_attach_segfault_handler(void) { }
void stage2_panic(const char *ptr, size_t len) {
fwrite(ptr, 1, len, stderr);
fprintf(stderr, "\n");
fflush(stderr);
abort();
}
void stage2_render_ast(struct Stage2Ast *ast, FILE *output_file) {
const char *msg = "stage0 called stage2_render_ast";
stage2_panic(msg, strlen(msg));
}
int stage2_fmt(int argc, char **argv) {
const char *msg = "stage0 called stage2_fmt";
stage2_panic(msg, strlen(msg));
}
stage2_DepTokenizer stage2_DepTokenizer_init(const char *input, size_t len) {
const char *msg = "stage0 called stage2_DepTokenizer_init";
stage2_panic(msg, strlen(msg));
}
void stage2_DepTokenizer_deinit(stage2_DepTokenizer *self) {
const char *msg = "stage0 called stage2_DepTokenizer_deinit";
stage2_panic(msg, strlen(msg));
}
stage2_DepNextResult stage2_DepTokenizer_next(stage2_DepTokenizer *self) {
const char *msg = "stage0 called stage2_DepTokenizer_next";
stage2_panic(msg, strlen(msg));
}
struct Stage2Progress {
int trash;
};
struct Stage2ProgressNode {
int trash;
};
Stage2Progress *stage2_progress_create(void) {
return nullptr;
}
void stage2_progress_destroy(Stage2Progress *progress) {}
Stage2ProgressNode *stage2_progress_start_root(Stage2Progress *progress,
const char *name_ptr, size_t name_len, size_t estimated_total_items)
{
return nullptr;
}
Stage2ProgressNode *stage2_progress_start(Stage2ProgressNode *node,
const char *name_ptr, size_t name_len, size_t estimated_total_items)
{
return nullptr;
}
void stage2_progress_end(Stage2ProgressNode *node) {}
void stage2_progress_complete_one(Stage2ProgressNode *node) {}
void stage2_progress_disable_tty(Stage2Progress *progress) {}
void stage2_progress_update_node(Stage2ProgressNode *node, size_t completed_count, size_t estimated_total_items){}
struct Stage2CpuFeatures {
const char *llvm_cpu_name;
const char *llvm_cpu_features;
const char *builtin_str;
const char *cache_hash;
};
Error stage2_cpu_features_parse(struct Stage2CpuFeatures **out, const char *zig_triple,
const char *cpu_name, const char *cpu_features)
{
if (zig_triple == nullptr) {
Stage2CpuFeatures *result = heap::c_allocator.create<Stage2CpuFeatures>();
result->llvm_cpu_name = ZigLLVMGetHostCPUName();
result->llvm_cpu_features = ZigLLVMGetNativeFeatures();
result->builtin_str = "arch.getBaselineCpuFeatures();\n";
result->cache_hash = "native\n\n";
*out = result;
return ErrorNone;
}
if (cpu_name == nullptr && cpu_features == nullptr) {
Stage2CpuFeatures *result = heap::c_allocator.create<Stage2CpuFeatures>();
result->builtin_str = "arch.getBaselineCpuFeatures();\n";
result->cache_hash = "\n\n";
*out = result;
return ErrorNone;
}
const char *msg = "stage0 called stage2_cpu_features_parse with non-null cpu name or features";
stage2_panic(msg, strlen(msg));
}
void stage2_cpu_features_get_cache_hash(const Stage2CpuFeatures *cpu_features,
const char **ptr, size_t *len)
{
*ptr = cpu_features->cache_hash;
*len = strlen(cpu_features->cache_hash);
}
const char *stage2_cpu_features_get_llvm_cpu(const Stage2CpuFeatures *cpu_features) {
return cpu_features->llvm_cpu_name;
}
const char *stage2_cpu_features_get_llvm_features(const Stage2CpuFeatures *cpu_features) {
return cpu_features->llvm_cpu_features;
}
void stage2_cpu_features_get_builtin_str(const Stage2CpuFeatures *cpu_features,
const char **ptr, size_t *len)
{
*ptr = cpu_features->builtin_str;
*len = strlen(cpu_features->builtin_str);
}
int stage2_cmd_targets(const char *zig_triple) {
const char *msg = "stage0 called stage2_cmd_targets";
stage2_panic(msg, strlen(msg));
}
enum Error stage2_libc_parse(struct Stage2LibCInstallation *libc, const char *libc_file) {
const char *msg = "stage0 called stage2_libc_parse";
stage2_panic(msg, strlen(msg));
}
enum Error stage2_libc_render(struct Stage2LibCInstallation *self, FILE *file) {
const char *msg = "stage0 called stage2_libc_render";
stage2_panic(msg, strlen(msg));
}
enum Error stage2_libc_find_native(struct Stage2LibCInstallation *libc) {
const char *msg = "stage0 called stage2_libc_find_native";
stage2_panic(msg, strlen(msg));
}
enum Error stage2_libc_cc_print_file_name(char **out_ptr, size_t *out_len,
const char *o_file, bool want_dirname)
{
const char *msg = "stage0 called stage2_libc_cc_print_file_name";
stage2_panic(msg, strlen(msg));
}
<commit_msg>fix building zig0 -> zig on macos<commit_after>// This file is a shim for zig1. The real implementations of these are in
// src-self-hosted/stage1.zig
#include "userland.h"
#include "util.hpp"
#include "zig_llvm.h"
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
Error stage2_translate_c(struct Stage2Ast **out_ast,
struct Stage2ErrorMsg **out_errors_ptr, size_t *out_errors_len,
const char **args_begin, const char **args_end, const char *resources_path)
{
const char *msg = "stage0 called stage2_translate_c";
stage2_panic(msg, strlen(msg));
}
void stage2_free_clang_errors(struct Stage2ErrorMsg *ptr, size_t len) {
const char *msg = "stage0 called stage2_free_clang_errors";
stage2_panic(msg, strlen(msg));
}
void stage2_zen(const char **ptr, size_t *len) {
const char *msg = "stage0 called stage2_zen";
stage2_panic(msg, strlen(msg));
}
void stage2_attach_segfault_handler(void) { }
void stage2_panic(const char *ptr, size_t len) {
fwrite(ptr, 1, len, stderr);
fprintf(stderr, "\n");
fflush(stderr);
abort();
}
void stage2_render_ast(struct Stage2Ast *ast, FILE *output_file) {
const char *msg = "stage0 called stage2_render_ast";
stage2_panic(msg, strlen(msg));
}
int stage2_fmt(int argc, char **argv) {
const char *msg = "stage0 called stage2_fmt";
stage2_panic(msg, strlen(msg));
}
stage2_DepTokenizer stage2_DepTokenizer_init(const char *input, size_t len) {
const char *msg = "stage0 called stage2_DepTokenizer_init";
stage2_panic(msg, strlen(msg));
}
void stage2_DepTokenizer_deinit(stage2_DepTokenizer *self) {
const char *msg = "stage0 called stage2_DepTokenizer_deinit";
stage2_panic(msg, strlen(msg));
}
stage2_DepNextResult stage2_DepTokenizer_next(stage2_DepTokenizer *self) {
const char *msg = "stage0 called stage2_DepTokenizer_next";
stage2_panic(msg, strlen(msg));
}
struct Stage2Progress {
int trash;
};
struct Stage2ProgressNode {
int trash;
};
Stage2Progress *stage2_progress_create(void) {
return nullptr;
}
void stage2_progress_destroy(Stage2Progress *progress) {}
Stage2ProgressNode *stage2_progress_start_root(Stage2Progress *progress,
const char *name_ptr, size_t name_len, size_t estimated_total_items)
{
return nullptr;
}
Stage2ProgressNode *stage2_progress_start(Stage2ProgressNode *node,
const char *name_ptr, size_t name_len, size_t estimated_total_items)
{
return nullptr;
}
void stage2_progress_end(Stage2ProgressNode *node) {}
void stage2_progress_complete_one(Stage2ProgressNode *node) {}
void stage2_progress_disable_tty(Stage2Progress *progress) {}
void stage2_progress_update_node(Stage2ProgressNode *node, size_t completed_count, size_t estimated_total_items){}
struct Stage2CpuFeatures {
const char *llvm_cpu_name;
const char *llvm_cpu_features;
const char *builtin_str;
const char *cache_hash;
};
Error stage2_cpu_features_parse(struct Stage2CpuFeatures **out, const char *zig_triple,
const char *cpu_name, const char *cpu_features)
{
if (zig_triple == nullptr) {
Stage2CpuFeatures *result = heap::c_allocator.create<Stage2CpuFeatures>();
result->llvm_cpu_name = ZigLLVMGetHostCPUName();
result->llvm_cpu_features = ZigLLVMGetNativeFeatures();
result->builtin_str = "arch.getBaselineCpuFeatures();\n";
result->cache_hash = "native\n\n";
*out = result;
return ErrorNone;
}
if (cpu_name == nullptr && cpu_features == nullptr) {
Stage2CpuFeatures *result = heap::c_allocator.create<Stage2CpuFeatures>();
result->builtin_str = "arch.getBaselineCpuFeatures();\n";
result->cache_hash = "\n\n";
*out = result;
return ErrorNone;
}
const char *msg = "stage0 called stage2_cpu_features_parse with non-null cpu name or features";
stage2_panic(msg, strlen(msg));
}
void stage2_cpu_features_get_cache_hash(const Stage2CpuFeatures *cpu_features,
const char **ptr, size_t *len)
{
*ptr = cpu_features->cache_hash;
*len = strlen(cpu_features->cache_hash);
}
const char *stage2_cpu_features_get_llvm_cpu(const Stage2CpuFeatures *cpu_features) {
return cpu_features->llvm_cpu_name;
}
const char *stage2_cpu_features_get_llvm_features(const Stage2CpuFeatures *cpu_features) {
return cpu_features->llvm_cpu_features;
}
void stage2_cpu_features_get_builtin_str(const Stage2CpuFeatures *cpu_features,
const char **ptr, size_t *len)
{
*ptr = cpu_features->builtin_str;
*len = strlen(cpu_features->builtin_str);
}
int stage2_cmd_targets(const char *zig_triple) {
const char *msg = "stage0 called stage2_cmd_targets";
stage2_panic(msg, strlen(msg));
}
enum Error stage2_libc_parse(struct Stage2LibCInstallation *libc, const char *libc_file) {
libc->include_dir = "/dummy/include";
libc->include_dir_len = strlen(libc->include_dir);
libc->sys_include_dir = "/dummy/sys/include";
libc->sys_include_dir_len = strlen(libc->sys_include_dir);
libc->crt_dir = "";
libc->crt_dir_len = strlen(libc->crt_dir);
libc->static_crt_dir = "";
libc->static_crt_dir_len = strlen(libc->static_crt_dir);
libc->msvc_lib_dir = "";
libc->msvc_lib_dir_len = strlen(libc->msvc_lib_dir);
libc->kernel32_lib_dir = "";
libc->kernel32_lib_dir_len = strlen(libc->kernel32_lib_dir);
return ErrorNone;
}
enum Error stage2_libc_render(struct Stage2LibCInstallation *self, FILE *file) {
const char *msg = "stage0 called stage2_libc_render";
stage2_panic(msg, strlen(msg));
}
enum Error stage2_libc_find_native(struct Stage2LibCInstallation *libc) {
const char *msg = "stage0 called stage2_libc_find_native";
stage2_panic(msg, strlen(msg));
}
enum Error stage2_libc_cc_print_file_name(char **out_ptr, size_t *out_len,
const char *o_file, bool want_dirname)
{
const char *msg = "stage0 called stage2_libc_cc_print_file_name";
stage2_panic(msg, strlen(msg));
}
<|endoftext|> |
<commit_before>// Copyright (C) 2016 xaizek <[email protected]>
//
// This file is part of uncov.
//
// uncov 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.
//
// uncov 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 uncov. If not, see <http://www.gnu.org/licenses/>.
#ifndef UNCOV__UTILS__FS_HPP__
#define UNCOV__UTILS__FS_HPP__
#include <boost/filesystem/path.hpp>
#include <string>
/**
* @file fs.hpp
*
* @brief File-system utilities.
*/
/**
* @brief Checks that @p path is somewhere under @p root.
*
* @param root Root to check against.
* @param path Path to check.
*
* @returns @c true if so, otherwise @c false.
*
* @note Path are assumed to be canonicalized.
*/
bool pathIsInSubtree(const boost::filesystem::path &root,
const boost::filesystem::path &path);
/**
* @brief Excludes `..` and `.` entries from a path.
*
* @param path Path to process.
*
* @returns Normalized path.
*/
boost::filesystem::path normalizePath(const boost::filesystem::path &path);
/**
* @brief Makes path relative to specified base directory.
*
* @param base Base path.
* @param path Path to make relative.
*
* @returns Relative path.
*/
boost::filesystem::path makeRelativePath(boost::filesystem::path base,
boost::filesystem::path path);
/**
* @brief Reads file into a string.
*
* @param path Path to the file.
*
* @returns File contents.
*
* @throws std::runtime_error if @p path specifies a directory or file
* reading has failed.
*/
std::string readFile(const std::string &path);
#endif // UNCOV__UTILS__FS_HPP__
<commit_msg>Introduce TempDir class<commit_after>// Copyright (C) 2016 xaizek <[email protected]>
//
// This file is part of uncov.
//
// uncov 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.
//
// uncov 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 uncov. If not, see <http://www.gnu.org/licenses/>.
#ifndef UNCOV__UTILS__FS_HPP__
#define UNCOV__UTILS__FS_HPP__
#include <boost/filesystem/operations.hpp>
#include <boost/filesystem/path.hpp>
#include <string>
/**
* @file fs.hpp
*
* @brief File-system utilities.
*/
/**
* @brief Temporary directory in RAII-style.
*/
class TempDir
{
public:
/**
* @brief Makes temporary directory, which is removed in destructor.
*
* @param prefix Directory name prefix.
*/
explicit TempDir(const std::string &prefix)
{
namespace fs = boost::filesystem;
path = fs::temp_directory_path()
/ fs::unique_path("uncov-" + prefix + "-%%%%-%%%%");
fs::create_directories(path);
}
// Make sure temporary directory is deleted only once.
TempDir(const TempDir &rhs) = delete;
TempDir & operator=(const TempDir &rhs) = delete;
/**
* @brief Removes temporary directory and all its content, if it still
* exists.
*/
~TempDir()
{
boost::filesystem::remove_all(path);
}
public:
/**
* @brief Provides implicit conversion to a directory path string.
*
* @returns The path.
*/
operator std::string() const
{
return path.string();
}
private:
/**
* @brief Path to the temporary directory.
*/
boost::filesystem::path path;
};
/**
* @brief Checks that @p path is somewhere under @p root.
*
* @param root Root to check against.
* @param path Path to check.
*
* @returns @c true if so, otherwise @c false.
*
* @note Path are assumed to be canonicalized.
*/
bool pathIsInSubtree(const boost::filesystem::path &root,
const boost::filesystem::path &path);
/**
* @brief Excludes `..` and `.` entries from a path.
*
* @param path Path to process.
*
* @returns Normalized path.
*/
boost::filesystem::path normalizePath(const boost::filesystem::path &path);
/**
* @brief Makes path relative to specified base directory.
*
* @param base Base path.
* @param path Path to make relative.
*
* @returns Relative path.
*/
boost::filesystem::path makeRelativePath(boost::filesystem::path base,
boost::filesystem::path path);
/**
* @brief Reads file into a string.
*
* @param path Path to the file.
*
* @returns File contents.
*
* @throws std::runtime_error if @p path specifies a directory or file
* reading has failed.
*/
std::string readFile(const std::string &path);
#endif // UNCOV__UTILS__FS_HPP__
<|endoftext|> |
<commit_before>// Copyright (c) 2009-2010 Satoshi Nakamoto
// Copyright (c) 2009-2017 The Machinecoin Core developers
// Distributed under the MIT software license, see the accompanying
// file COPYING or http://www.opensource.org/licenses/mit-license.php.
#if defined(HAVE_CONFIG_H)
#include "config/machinecoin-config.h"
#endif
#include "utiltime.h"
#include <boost/date_time/posix_time/posix_time.hpp>
#include <boost/thread.hpp>
using namespace std;
static int64_t nMockTime = 0; //!< For unit testing
int64_t GetTime()
{
if (nMockTime) return nMockTime;
time_t now = time(NULL);
assert(now > 0);
return now;
}
void SetMockTime(int64_t nMockTimeIn)
{
nMockTime = nMockTimeIn;
}
int64_t GetTimeMillis()
{
int64_t now = (boost::posix_time::microsec_clock::universal_time() -
boost::posix_time::ptime(boost::gregorian::date(1970,1,1))).total_milliseconds();
assert(now > 0);
return now;
}
int64_t GetTimeMicros()
{
int64_t now = (boost::posix_time::microsec_clock::universal_time() -
boost::posix_time::ptime(boost::gregorian::date(1970,1,1))).total_microseconds();
assert(now > 0);
return now;
}
int64_t GetSystemTimeInSeconds()
{
return GetTimeMicros()/1000000;
}
/** Return a time useful for the debug log */
int64_t GetLogTimeMicros()
{
if (nMockTime) return nMockTime*1000000;
return GetTimeMicros();
}
void MilliSleep(int64_t n)
{
/**
* Boost's sleep_for was uninterruptible when backed by nanosleep from 1.50
* until fixed in 1.52. Use the deprecated sleep method for the broken case.
* See: https://svn.boost.org/trac/boost/ticket/7238
*/
#if defined(HAVE_WORKING_BOOST_SLEEP_FOR)
boost::this_thread::sleep_for(boost::chrono::milliseconds(n));
#elif defined(HAVE_WORKING_BOOST_SLEEP)
boost::this_thread::sleep(boost::posix_time::milliseconds(n));
#else
//should never get here
#error missing boost sleep implementation
#endif
}
std::string DateTimeStrFormat(const char* pszFormat, int64_t nTime)
{
static std::locale classic(std::locale::classic());
// std::locale takes ownership of the pointer
std::locale loc(classic, new boost::posix_time::time_facet(pszFormat));
std::stringstream ss;
ss.imbue(loc);
ss << boost::posix_time::from_time_t(nTime);
return ss.str();
}
std::string DurationToDHMS(int64_t nDurationTime)
{
int seconds = nDurationTime % 60;
nDurationTime /= 60;
int minutes = nDurationTime % 60;
nDurationTime /= 60;
int hours = nDurationTime % 24;
int days = nDurationTime / 24;
if(days)
return strprintf("%dd %02dh:%02dm:%02ds", days, hours, minutes, seconds);
if(hours)
return strprintf("%02dh:%02dm:%02ds", hours, minutes, seconds);
return strprintf("%02dm:%02ds", minutes, seconds);
}
<commit_msg>Added missing include<commit_after>// Copyright (c) 2009-2010 Satoshi Nakamoto
// Copyright (c) 2009-2017 The Machinecoin Core developers
// Distributed under the MIT software license, see the accompanying
// file COPYING or http://www.opensource.org/licenses/mit-license.php.
#if defined(HAVE_CONFIG_H)
#include "config/machinecoin-config.h"
#endif
#include "tinyformat.h"
#include "utiltime.h"
#include <boost/date_time/posix_time/posix_time.hpp>
#include <boost/thread.hpp>
using namespace std;
static int64_t nMockTime = 0; //!< For unit testing
int64_t GetTime()
{
if (nMockTime) return nMockTime;
time_t now = time(NULL);
assert(now > 0);
return now;
}
void SetMockTime(int64_t nMockTimeIn)
{
nMockTime = nMockTimeIn;
}
int64_t GetTimeMillis()
{
int64_t now = (boost::posix_time::microsec_clock::universal_time() -
boost::posix_time::ptime(boost::gregorian::date(1970,1,1))).total_milliseconds();
assert(now > 0);
return now;
}
int64_t GetTimeMicros()
{
int64_t now = (boost::posix_time::microsec_clock::universal_time() -
boost::posix_time::ptime(boost::gregorian::date(1970,1,1))).total_microseconds();
assert(now > 0);
return now;
}
int64_t GetSystemTimeInSeconds()
{
return GetTimeMicros()/1000000;
}
/** Return a time useful for the debug log */
int64_t GetLogTimeMicros()
{
if (nMockTime) return nMockTime*1000000;
return GetTimeMicros();
}
void MilliSleep(int64_t n)
{
/**
* Boost's sleep_for was uninterruptible when backed by nanosleep from 1.50
* until fixed in 1.52. Use the deprecated sleep method for the broken case.
* See: https://svn.boost.org/trac/boost/ticket/7238
*/
#if defined(HAVE_WORKING_BOOST_SLEEP_FOR)
boost::this_thread::sleep_for(boost::chrono::milliseconds(n));
#elif defined(HAVE_WORKING_BOOST_SLEEP)
boost::this_thread::sleep(boost::posix_time::milliseconds(n));
#else
//should never get here
#error missing boost sleep implementation
#endif
}
std::string DateTimeStrFormat(const char* pszFormat, int64_t nTime)
{
static std::locale classic(std::locale::classic());
// std::locale takes ownership of the pointer
std::locale loc(classic, new boost::posix_time::time_facet(pszFormat));
std::stringstream ss;
ss.imbue(loc);
ss << boost::posix_time::from_time_t(nTime);
return ss.str();
}
std::string DurationToDHMS(int64_t nDurationTime)
{
int seconds = nDurationTime % 60;
nDurationTime /= 60;
int minutes = nDurationTime % 60;
nDurationTime /= 60;
int hours = nDurationTime % 24;
int days = nDurationTime / 24;
if(days)
return strprintf("%dd %02dh:%02dm:%02ds", days, hours, minutes, seconds);
if(hours)
return strprintf("%02dh:%02dm:%02ds", hours, minutes, seconds);
return strprintf("%02dm:%02ds", minutes, seconds);
}
<|endoftext|> |
<commit_before>#include "player.h"
#include <list>
#include <vector>
#include <iostream>
const char* Player::VERSION = "Default C++ folding player";
class Hand;
using namespace std;
class Card
{
public:
enum Suit { hearts, spades, clubs, diamonds};
Suit suit;
int rank; // 2-2 .. 10-10 11-V 12-D 13-K 14-A
Card():suit(hearts),rank(0){}
Card(Suit s, int r):suit(s),rank(r){}
Card(const string & s,const string &r);
iostream operator<<(const iostream &b);
};
class Table
{
public :
Hand * self;
std::list<int> bet;
std::list<Card> common;
Table();//:self(new Hand()){}
};
class Hand
{
public:
std::list<Card> cards;
int cost();
};
Table::Table():self(new Hand()){}
#define BadJsonBet 150
int Player::betRequest(json::Value game_state)
{
if (game_state.GetType()!=json::ObjectVal) {
return BadJsonBet;
}
json::Object gsObj = game_state.ToObject();
json::Value players = gsObj["players"];
if (players.GetType() != json::ArrayVal) {
return BadJsonBet;
}
Table table;
json::Array aplayers = players.ToArray();
int cur_bet = 0;
int SelfStack = 0;
int playerCount = aplayers.size();
for (int i=aplayers.size()-1; i>=0; --i) {
if (aplayers[i].GetType() != json::ObjectVal) continue;
json::Object player = aplayers[i].ToObject();
if (player["name"].ToString() == "DmitracoffAndCompany") {
json::Array cards = player["hole_cards"].ToArray();
if (cards.size()<2) return 0;
table.self->cards.push_back(Card(cards[0]["suit"].ToString(),cards[0]["rank"].ToString()));
table.self->cards.push_back(Card(cards[1]["suit"].ToString(),cards[1]["rank"].ToString()));
SelfStack = player["stack"].ToInt();
} else {
int bet=player["bet"].ToInt();
if (cur_bet<bet) cur_bet = bet;
}
}
json::Array jsComm = gsObj["community_cards"].ToArray();
vector<Card> comm(jsComm.size());
for(int i=jsComm.size()-1; i>=0; --i) {
comm[i]=Card(jsComm[i]["suit"].ToString(),jsComm[i]["rank"].ToString());
}
cerr<<"ok"<<endl;
Card c1 = table.self->cards.front();
Card c2 = table.self->cards.back();
if (comm.size()>1) {
//proverka na set i kare
cerr << "stack =" << SelfStack << endl;
if (c1.rank == c2.rank) {
int count = 2;
for (int i=0; i < comm.size(); i++)
if (comm[i].rank == c1.rank)
count++;
if (count > 2)
return SelfStack;
} else {
int count1 = 1;
for (int i=0; i < comm.size(); i++)
if (comm[i].rank == c1.rank)
count1++;
int count2 = 1;
for (int i=0; i < comm.size(); i++)
if (comm[i].rank == c2.rank)
count2++;
if (count1 + count2 > 3)
return SelfStack;
if (count1 + count2 == 3)
return SelfStack / 5;
}
}
if (abs(c1.rank - c2.rank) > 3 && (c1.suit!=c2.suit) && playerCount>3)
return 0;
if ((c1.rank == c2.rank +1 || c1.rank == c2.rank-1) && c1.suit == c2.suit)
return 500;
if (c1.rank == c2.rank)
return 300;
if (c1.suit == c2.suit)
return 200;
if (c1.rank == c2.rank +1 || c1.rank == c2.rank-1)
return 200;
int bet = 150;
return bet;
}
void Player::showdown(json::Value game_state)
{
}
Card::Card(const string &s, const string &r)
:suit(hearts),rank(0)
{ //hearts, spades, clubs, diamonds
if (s=="spades") suit=spades;
if (s=="clubs") suit=clubs;
if (s=="diamonds") suit=diamonds;
if (r=="A") rank = 14;
if (r=="K") rank = 13;
if (r=="Q") rank = 12;
if (r=="J") rank = 11;
if (r=="10") rank = 10;
if (rank==0 && r.size()>0) rank=r[0] - '0';
}
iostream Card::operator<<(const iostream &b)
{
//return (b<<"["<<rank<<suit<<"]");
}
<commit_msg>cur_bet<commit_after>#include "player.h"
#include <list>
#include <vector>
#include <iostream>
const char* Player::VERSION = "Default C++ folding player";
class Hand;
using namespace std;
class Card
{
public:
enum Suit { hearts, spades, clubs, diamonds};
Suit suit;
int rank; // 2-2 .. 10-10 11-V 12-D 13-K 14-A
Card():suit(hearts),rank(0){}
Card(Suit s, int r):suit(s),rank(r){}
Card(const string & s,const string &r);
iostream operator<<(const iostream &b);
};
class Table
{
public :
Hand * self;
std::list<int> bet;
std::list<Card> common;
Table();//:self(new Hand()){}
};
class Hand
{
public:
std::list<Card> cards;
int cost();
};
Table::Table():self(new Hand()){}
#define BadJsonBet 150
int Player::betRequest(json::Value game_state)
{
if (game_state.GetType()!=json::ObjectVal) {
return BadJsonBet;
}
json::Object gsObj = game_state.ToObject();
json::Value players = gsObj["players"];
if (players.GetType() != json::ArrayVal) {
return BadJsonBet;
}
Table table;
json::Array aplayers = players.ToArray();
int cur_bet = 0;
int SelfStack = 0;
int playerCount = aplayers.size();
for (int i=aplayers.size()-1; i>=0; --i) {
if (aplayers[i].GetType() != json::ObjectVal) continue;
json::Object player = aplayers[i].ToObject();
if (player["name"].ToString() == "DmitracoffAndCompany") {
json::Array cards = player["hole_cards"].ToArray();
if (cards.size()<2) return 0;
table.self->cards.push_back(Card(cards[0]["suit"].ToString(),cards[0]["rank"].ToString()));
table.self->cards.push_back(Card(cards[1]["suit"].ToString(),cards[1]["rank"].ToString()));
SelfStack = player["stack"].ToInt();
} else {
int bet=player["bet"].ToInt();
if (cur_bet<bet) cur_bet = bet;
}
}
json::Array jsComm = gsObj["community_cards"].ToArray();
vector<Card> comm(jsComm.size());
for(int i=jsComm.size()-1; i>=0; --i) {
comm[i]=Card(jsComm[i]["suit"].ToString(),jsComm[i]["rank"].ToString());
}
cerr<<"ok"<<endl;
Card c1 = table.self->cards.front();
Card c2 = table.self->cards.back();
if (comm.size()>1) {
//proverka na set i kare
cerr << "stack =" << SelfStack << endl;
if (c1.rank == c2.rank) {
int count = 2;
for (int i=0; i < comm.size(); i++)
if (comm[i].rank == c1.rank)
count++;
if (count > 2)
return SelfStack;
} else {
int count1 = 1;
for (int i=0; i < comm.size(); i++)
if (comm[i].rank == c1.rank)
count1++;
int count2 = 1;
for (int i=0; i < comm.size(); i++)
if (comm[i].rank == c2.rank)
count2++;
if (count1 + count2 > 3)
return SelfStack;
if (count1 + count2 == 3)
return SelfStack / 5;
}
}
if (abs(c1.rank - c2.rank) > 3 && (c1.suit!=c2.suit) && playerCount>3)
return 0;
if ((c1.rank == c2.rank +1 || c1.rank == c2.rank-1) && c1.suit == c2.suit)
return 500;
if (c1.rank == c2.rank)
return 300;
if (c1.suit == c2.suit)
return 200;
if (c1.rank == c2.rank +1 || c1.rank == c2.rank-1)
return 200;
return (cur_bet>200)?0:cur_bet;
}
void Player::showdown(json::Value game_state)
{
}
Card::Card(const string &s, const string &r)
:suit(hearts),rank(0)
{ //hearts, spades, clubs, diamonds
if (s=="spades") suit=spades;
if (s=="clubs") suit=clubs;
if (s=="diamonds") suit=diamonds;
if (r=="A") rank = 14;
if (r=="K") rank = 13;
if (r=="Q") rank = 12;
if (r=="J") rank = 11;
if (r=="10") rank = 10;
if (rank==0 && r.size()>0) rank=r[0] - '0';
}
iostream Card::operator<<(const iostream &b)
{
//return (b<<"["<<rank<<suit<<"]");
}
<|endoftext|> |
<commit_before>/*
* Software License Agreement (BSD License)
*
* Point Cloud Library (PCL) - www.pointclouds.org
* Copyright (c) 2009-2011, Willow Garage, Inc.
*
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
*
* * Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* * Redistributions in binary form must reproduce the above
* copyright notice, this list of conditions and the following
* disclaimer in the documentation and/or other materials provided
* with the distribution.
* * Neither the name of Willow Garage, 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 <pcl/apps/openni_passthrough.h>
// QT4
#include <QApplication>
#include <QGtkStyle>
#include <QMutexLocker>
#include <QEvent>
#include <QObject>
// PCL
#include <pcl/console/parse.h>
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
OpenNIPassthrough::OpenNIPassthrough (pcl::OpenNIGrabber& grabber) : grabber_(grabber), cloud_pass_()
{
// Create a timer and fire it up every 5ms
vis_timer_ = new QTimer (this);
vis_timer_->start (5);
connect (vis_timer_, SIGNAL (timeout ()), this, SLOT (timeoutSlot ()));
ui_ = new Ui::MainWindow;
ui_->setupUi (this);
this->setWindowTitle ("PCL OpenNI PassThrough Viewer");
vis_.reset (new pcl::visualization::PCLVisualizer ("", false));
ui_->qvtk_widget->SetRenderWindow (vis_->getRenderWindow ());
vis_->setupInteractor (ui_->qvtk_widget->GetInteractor (), ui_->qvtk_widget->GetRenderWindow ());
vis_->getInteractorStyle ()->setKeyboardModifier (pcl::visualization::INTERACTOR_KB_MOD_SHIFT);
ui_->qvtk_widget->update ();
// Start the OpenNI data acquision
boost::function<void (const CloudConstPtr&)> f = boost::bind (&OpenNIPassthrough::cloud_cb, this, _1);
boost::signals2::connection c = grabber_.registerCallback (f);
grabber_.start ();
// Set defaults
pass_.setFilterFieldName ("z");
pass_.setFilterLimits (0.5, 5.0);
ui_->fieldValueSlider->setRange (5, 50);
ui_->fieldValueSlider->setValue (50);
connect (ui_->fieldValueSlider, SIGNAL (valueChanged (int)), this, SLOT (adjustPassThroughValues (int)));
}
/////////////////////////////////////////////////////////////////////////////////////////////////////////
void
OpenNIPassthrough::cloud_cb (const CloudConstPtr& cloud)
{
QMutexLocker locker (&mtx_);
FPS_CALC ("computation");
// Computation goes here
cloud_pass_.reset (new Cloud);
pass_.setInputCloud (cloud);
pass_.filter (*cloud_pass_);
}
/////////////////////////////////////////////////////////////////////////////////////////////////////////
void
OpenNIPassthrough::timeoutSlot ()
{
if (!cloud_pass_)
{
boost::this_thread::sleep (boost::posix_time::milliseconds (1));
return;
}
CloudPtr temp_cloud;
{
QMutexLocker locker (&mtx_);
temp_cloud.swap (cloud_pass_);
}
// Add to the 3D viewer
if (!vis_->updatePointCloud (temp_cloud, "cloud_pass"))
{
vis_->addPointCloud (temp_cloud, "cloud_pass");
vis_->resetCameraViewpoint ("cloud_pass");
}
FPS_CALC ("visualization");
ui_->qvtk_widget->update ();
}
int
main (int argc, char ** argv)
{
// Initialize QT
QApplication app (argc, argv);
QApplication::setStyle (new QGtkStyle);
// Open the first available camera
pcl::OpenNIGrabber grabber ("#1");
// Check if an RGB stream is provided
if (!grabber.providesCallback<pcl::OpenNIGrabber::sig_cb_openni_point_cloud_rgb> ())
{
PCL_ERROR ("Device #1 does not provide an RGB stream!\n");
return (-1);
}
OpenNIPassthrough v (grabber);
v.show ();
return (app.exec ());
}
<commit_msg>no qgtkstyle<commit_after>/*
* Software License Agreement (BSD License)
*
* Point Cloud Library (PCL) - www.pointclouds.org
* Copyright (c) 2009-2011, Willow Garage, Inc.
*
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
*
* * Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* * Redistributions in binary form must reproduce the above
* copyright notice, this list of conditions and the following
* disclaimer in the documentation and/or other materials provided
* with the distribution.
* * Neither the name of Willow Garage, 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 <pcl/apps/openni_passthrough.h>
// QT4
#include <QApplication>
#include <QGtkStyle>
#include <QMutexLocker>
#include <QEvent>
#include <QObject>
// PCL
#include <pcl/console/parse.h>
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
OpenNIPassthrough::OpenNIPassthrough (pcl::OpenNIGrabber& grabber) : grabber_(grabber), cloud_pass_()
{
// Create a timer and fire it up every 5ms
vis_timer_ = new QTimer (this);
vis_timer_->start (5);
connect (vis_timer_, SIGNAL (timeout ()), this, SLOT (timeoutSlot ()));
ui_ = new Ui::MainWindow;
ui_->setupUi (this);
this->setWindowTitle ("PCL OpenNI PassThrough Viewer");
vis_.reset (new pcl::visualization::PCLVisualizer ("", false));
ui_->qvtk_widget->SetRenderWindow (vis_->getRenderWindow ());
vis_->setupInteractor (ui_->qvtk_widget->GetInteractor (), ui_->qvtk_widget->GetRenderWindow ());
vis_->getInteractorStyle ()->setKeyboardModifier (pcl::visualization::INTERACTOR_KB_MOD_SHIFT);
ui_->qvtk_widget->update ();
// Start the OpenNI data acquision
boost::function<void (const CloudConstPtr&)> f = boost::bind (&OpenNIPassthrough::cloud_cb, this, _1);
boost::signals2::connection c = grabber_.registerCallback (f);
grabber_.start ();
// Set defaults
pass_.setFilterFieldName ("z");
pass_.setFilterLimits (0.5, 5.0);
ui_->fieldValueSlider->setRange (5, 50);
ui_->fieldValueSlider->setValue (50);
connect (ui_->fieldValueSlider, SIGNAL (valueChanged (int)), this, SLOT (adjustPassThroughValues (int)));
}
/////////////////////////////////////////////////////////////////////////////////////////////////////////
void
OpenNIPassthrough::cloud_cb (const CloudConstPtr& cloud)
{
QMutexLocker locker (&mtx_);
FPS_CALC ("computation");
// Computation goes here
cloud_pass_.reset (new Cloud);
pass_.setInputCloud (cloud);
pass_.filter (*cloud_pass_);
}
/////////////////////////////////////////////////////////////////////////////////////////////////////////
void
OpenNIPassthrough::timeoutSlot ()
{
if (!cloud_pass_)
{
boost::this_thread::sleep (boost::posix_time::milliseconds (1));
return;
}
CloudPtr temp_cloud;
{
QMutexLocker locker (&mtx_);
temp_cloud.swap (cloud_pass_);
}
// Add to the 3D viewer
if (!vis_->updatePointCloud (temp_cloud, "cloud_pass"))
{
vis_->addPointCloud (temp_cloud, "cloud_pass");
vis_->resetCameraViewpoint ("cloud_pass");
}
FPS_CALC ("visualization");
ui_->qvtk_widget->update ();
}
int
main (int argc, char ** argv)
{
// Initialize QT
QApplication app (argc, argv);
// Open the first available camera
pcl::OpenNIGrabber grabber ("#1");
// Check if an RGB stream is provided
if (!grabber.providesCallback<pcl::OpenNIGrabber::sig_cb_openni_point_cloud_rgb> ())
{
PCL_ERROR ("Device #1 does not provide an RGB stream!\n");
return (-1);
}
OpenNIPassthrough v (grabber);
v.show ();
return (app.exec ());
}
<|endoftext|> |
<commit_before><commit_msg>fix truncate operation in synchronous replication (#10492)<commit_after><|endoftext|> |
<commit_before>// Conventions:
// O is the stack pointer (post-decrement)
// B is the (so far only) return register
// C is the (so far only) argument register
// N is the relative-jump temp register
#include "common.th"
_start:
bare_metal_init() // TODO this shouldn't be necessary
prologue
c <- 1 // argument
call(init_display)
call(disable_cursor)
j <- 0 // multiplier (0 -> 0x26)
k <- 0 // multiplicand (0 -> 0x12)
c <- 0b0100 // decimal point between J and K
c -> [0x101]
// write the top row first
loop_top:
f <- 4 // field width
e <- k * f + 3 // column is multiplicand * field width + header width
d <- 0 // row is 0
c <- k // number to print is multiplicand
call(putnum)
k <- k + 1
c <- k < 0x13
jnzrel(c,loop_top)
// outer loop is j (multiplier, corresponds to row)
loop_j:
k <- 0
// print row header
f <- 2 // field width 2
e <- 0 // column is 0
d <- j + 1 // row (J + 1)
c <- j
call(putnum)
loop_k:
f <- 4 // field width 3
e <- k * f + 3 // E is column (0 - 79)
d <- j + 1
c <- j * k
call(putnum)
c <- 0x100 // write {J,K} to LEDs
[c] <- j << 8 + k
k <- k + 1
c <- k < 0x13
jnzrel(c,loop_k)
j <- j + 1 // increment N
c <- j < 0x27
jnzrel(c,loop_j)
illegal
<commit_msg>Spin when done until we have hardware halt<commit_after>// Conventions:
// O is the stack pointer (post-decrement)
// B is the (so far only) return register
// C is the (so far only) argument register
// N is the relative-jump temp register
#include "common.th"
_start:
bare_metal_init() // TODO this shouldn't be necessary
prologue
c <- 1 // argument
call(init_display)
call(disable_cursor)
j <- 0 // multiplier (0 -> 0x26)
k <- 0 // multiplicand (0 -> 0x12)
c <- 0b0100 // decimal point between J and K
c -> [0x101]
// write the top row first
loop_top:
f <- 4 // field width
e <- k * f + 3 // column is multiplicand * field width + header width
d <- 0 // row is 0
c <- k // number to print is multiplicand
call(putnum)
k <- k + 1
c <- k < 0x13
jnzrel(c,loop_top)
// outer loop is j (multiplier, corresponds to row)
loop_j:
k <- 0
// print row header
f <- 2 // field width 2
e <- 0 // column is 0
d <- j + 1 // row (J + 1)
c <- j
call(putnum)
loop_k:
f <- 4 // field width 3
e <- k * f + 3 // E is column (0 - 79)
d <- j + 1
c <- j * k
call(putnum)
c <- 0x100 // write {J,K} to LEDs
[c] <- j << 8 + k
k <- k + 1
c <- k < 0x13
jnzrel(c,loop_k)
j <- j + 1 // increment N
c <- j < 0x27
jnzrel(c,loop_j)
halt:
goto(halt)
illegal
<|endoftext|> |
<commit_before>#include <memory>
#include <miniMAT/checker/Checker.hpp>
#include <iostream>
namespace miniMAT {
namespace checker {
Checker::Checker(std::shared_ptr<std::map<std::string, Matrix>> vars,
std::shared_ptr<reporter::ErrorReporter> reporter) {
this->vars = vars;
this->reporter = reporter;
}
std::shared_ptr<ast::AST> Checker::check(std::shared_ptr<ast::AST> ast) {
try {
ast->VisitCheck(this->vars, this->reporter);
return ast;
} catch (std::string error) {
reporter->AddCheckError(error);
return nullptr;
}
}
}
}
<commit_msg>Change catch statement to catch by reference<commit_after>#include <memory>
#include <miniMAT/checker/Checker.hpp>
#include <iostream>
namespace miniMAT {
namespace checker {
Checker::Checker(std::shared_ptr<std::map<std::string, Matrix>> vars,
std::shared_ptr<reporter::ErrorReporter> reporter) {
this->vars = vars;
this->reporter = reporter;
}
std::shared_ptr<ast::AST> Checker::check(std::shared_ptr<ast::AST> ast) {
try {
ast->VisitCheck(this->vars, this->reporter);
return ast;
} catch (std::string& error) {
reporter->AddCheckError(error);
return nullptr;
}
}
}
}
<|endoftext|> |
<commit_before>//
// Copyright(c) 2015 Gabi Melman.
// Distributed under the MIT License (http://opensource.org/licenses/MIT)
// spdlog usage example
#include <cstdio>
void stdout_logger_example();
void basic_example();
void rotating_example();
void daily_example();
void async_example();
void binary_example();
void trace_example();
void multi_sink_example();
void user_defined_example();
void err_handler_example();
void syslog_example();
void clone_example();
#include "spdlog/spdlog.h"
int main(int, char *[])
{
spdlog::info("Welcome to spdlog version {}.{}.{} !", SPDLOG_VER_MAJOR, SPDLOG_VER_MINOR, SPDLOG_VER_PATCH);
spdlog::warn("Easy padding in numbers like {:08d}", 12);
spdlog::critical("Support for int: {0:d}; hex: {0:x}; oct: {0:o}; bin: {0:b}", 42);
spdlog::info("Support for floats {:03.2f}", 1.23456);
spdlog::info("Positional args are {1} {0}..", "too", "supported");
spdlog::info("{:>8} aligned, {:<8} aligned", "right", "left");
// Runtime log levels
spdlog::set_level(spdlog::level::info); // Set global log level to info
spdlog::debug("This message should not be displayed!");
spdlog::set_level(spdlog::level::trace); // Set specific logger's log level
spdlog::debug("This message should be displayed..");
// Customize msg format for all loggers
spdlog::set_pattern("[%H:%M:%S %z] [%^%L%$] [thread %t] %v");
spdlog::info("This an info message with custom format");
spdlog::set_pattern("%+"); // back to default format
// Backtrace support.
// Auto trigger backtrace of latest debug/trace messages upon when error/critical messages happen..
spdlog::enable_backtrace(16);
spdlog::trace("Backtrace message 1");
spdlog::debug("Backtrace message 2");
spdlog::debug("Backtrace message 3");
spdlog::error("This should trigger backtrace!");
try
{
stdout_logger_example();
basic_example();
rotating_example();
daily_example();
clone_example();
async_example();
binary_example();
multi_sink_example();
user_defined_example();
err_handler_example();
trace_example();
// Flush all *registered* loggers using a worker thread every 3 seconds.
// note: registered loggers *must* be thread safe for this to work correctly!
spdlog::flush_every(std::chrono::seconds(3));
// Apply some function on all registered loggers
spdlog::apply_all([&](std::shared_ptr<spdlog::logger> l) { l->info("End of example."); });
// Release all spdlog resources, and drop all loggers in the registry.
// This is optional (only mandatory if using windows + async log).
spdlog::shutdown();
}
// Exceptions will only be thrown upon failed logger or sink construction (not during logging).
catch (const spdlog::spdlog_ex &ex)
{
std::printf("Log initialization failed: %s\n", ex.what());
return 1;
}
}
#include "spdlog/sinks/stdout_color_sinks.h"
// or #include "spdlog/sinks/stdout_sinks.h" if no colors needed.
void stdout_logger_example()
{
// Create color multi threaded logger.
auto console = spdlog::stdout_color_mt("console");
// or for stderr:
// auto console = spdlog::stderr_color_mt("error-logger");
}
#include "spdlog/sinks/basic_file_sink.h"
void basic_example()
{
// Create basic file logger (not rotated).
auto my_logger = spdlog::basic_logger_mt("file_logger", "logs/basic-log.txt");
}
#include "spdlog/sinks/rotating_file_sink.h"
void rotating_example()
{
// Create a file rotating logger with 5mb size max and 3 rotated files.
auto rotating_logger = spdlog::rotating_logger_mt("some_logger_name", "logs/rotating.txt", 1048576 * 5, 3);
}
#include "spdlog/sinks/daily_file_sink.h"
void daily_example()
{
// Create a daily logger - a new file is created every day on 2:30am.
auto daily_logger = spdlog::daily_logger_mt("daily_logger", "logs/daily.txt", 2, 30);
}
// Clone a logger and give it new name.
// Useful for creating component/subsystem loggers from some "root" logger.
void clone_example()
{
auto network_logger = spdlog::default_logger()->clone("network");
network_logger->info("Logging network stuff..");
}
#include "spdlog/async.h"
void async_example()
{
// Default thread pool settings can be modified *before* creating the async logger:
// spdlog::init_thread_pool(32768, 1); // queue with max 32k items 1 backing thread.
auto async_file = spdlog::basic_logger_mt<spdlog::async_factory>("async_file_logger", "logs/async_log.txt");
// alternatively:
// auto async_file = spdlog::create_async<spdlog::sinks::basic_file_sink_mt>("async_file_logger", "logs/async_log.txt");
for (int i = 1; i < 101; ++i)
{
async_file->info("Async message #{}", i);
}
}
// Log binary data as hex.
// Many types of std::container<char> types can be used.
// Iterator ranges are supported too.
// Format flags:
// {:X} - print in uppercase.
// {:s} - don't separate each byte with space.
// {:p} - don't print the position on each line start.
// {:n} - don't split the output to lines.
#include "spdlog/fmt/bin_to_hex.h"
void binary_example()
{
std::vector<char> buf;
for (int i = 0; i < 80; i++)
{
buf.push_back(static_cast<char>(i & 0xff));
}
spdlog::info("Binary example: {}", spdlog::to_hex(buf));
spdlog::info("Another binary example:{:n}", spdlog::to_hex(std::begin(buf), std::begin(buf) + 10));
// more examples:
// logger->info("uppercase: {:X}", spdlog::to_hex(buf));
// logger->info("uppercase, no delimiters: {:Xs}", spdlog::to_hex(buf));
// logger->info("uppercase, no delimiters, no position info: {:Xsp}", spdlog::to_hex(buf));
}
// Compile time log levels.
// define SPDLOG_ACTIVE_LEVEL to required level (e.g. SPDLOG_LEVEL_TRACE)
void trace_example()
{
// trace from default logger
SPDLOG_TRACE("Some trace message.. {} ,{}", 1, 3.23);
// debug from default logger
SPDLOG_DEBUG("Some debug message.. {} ,{}", 1, 3.23);
// trace from logger object
auto logger = spdlog::get("file_logger");
SPDLOG_LOGGER_TRACE(logger, "another trace message");
}
// A logger with multiple sinks (stdout and file) - each with a different format and log level.
void multi_sink_example()
{
auto console_sink = std::make_shared<spdlog::sinks::stdout_color_sink_mt>();
console_sink->set_level(spdlog::level::warn);
console_sink->set_pattern("[multi_sink_example] [%^%l%$] %v");
auto file_sink = std::make_shared<spdlog::sinks::basic_file_sink_mt>("logs/multisink.txt", true);
file_sink->set_level(spdlog::level::trace);
spdlog::logger logger("multi_sink", {console_sink, file_sink});
logger.set_level(spdlog::level::debug);
logger.warn("this should appear in both console and file");
logger.info("this message should not appear in the console, only in the file");
}
// User defined types logging by implementing operator<<
#include "spdlog/fmt/ostr.h" // must be included
struct my_type
{
int i;
template<typename OStream>
friend OStream &operator<<(OStream &os, const my_type &c)
{
return os << "[my_type i=" << c.i << "]";
}
};
void user_defined_example()
{
spdlog::info("user defined type: {}", my_type{14});
}
// Custom error handler. Will be triggered on log failure.
void err_handler_example()
{
// can be set globally or per logger(logger->set_error_handler(..))
spdlog::set_error_handler([](const std::string &msg) { printf("*** Custom log error handler: %s ***\n", msg.c_str()); });
}
// syslog example (linux/osx/freebsd)
#ifndef _WIN32
#include "spdlog/sinks/syslog_sink.h"
void syslog_example()
{
std::string ident = "spdlog-example";
auto syslog_logger = spdlog::syslog_logger_mt("syslog", ident, LOG_PID);
syslog_logger->warn("This is warning that will end up in syslog.");
}
#endif
// Android example.
#if defined(__ANDROID__)
#include "spdlog/sinks/android_sink.h"
void android_example()
{
std::string tag = "spdlog-android";
auto android_logger = spdlog::android_logger_mt("android", tag);
android_logger->critical("Use \"adb shell logcat\" to view this message.");
}
#endif
<commit_msg>Fixed example<commit_after>//
// Copyright(c) 2015 Gabi Melman.
// Distributed under the MIT License (http://opensource.org/licenses/MIT)
// spdlog usage example
#include <cstdio>
void stdout_logger_example();
void basic_example();
void rotating_example();
void daily_example();
void async_example();
void binary_example();
void trace_example();
void multi_sink_example();
void user_defined_example();
void err_handler_example();
void syslog_example();
void clone_example();
#include "spdlog/spdlog.h"
int main(int, char *[])
{
spdlog::info("Welcome to spdlog version {}.{}.{} !", SPDLOG_VER_MAJOR, SPDLOG_VER_MINOR, SPDLOG_VER_PATCH);
spdlog::warn("Easy padding in numbers like {:08d}", 12);
spdlog::critical("Support for int: {0:d}; hex: {0:x}; oct: {0:o}; bin: {0:b}", 42);
spdlog::info("Support for floats {:03.2f}", 1.23456);
spdlog::info("Positional args are {1} {0}..", "too", "supported");
spdlog::info("{:>8} aligned, {:<8} aligned", "right", "left");
// Runtime log levels
spdlog::set_level(spdlog::level::info); // Set global log level to info
spdlog::debug("This message should not be displayed!");
spdlog::set_level(spdlog::level::trace); // Set specific logger's log level
spdlog::debug("This message should be displayed..");
spdlog::set_level(spdlog::level::info); // Set specific logger's log level
// Customize msg format for all loggers
spdlog::set_pattern("[%H:%M:%S %z] [%^%L%$] [thread %t] %v");
spdlog::info("This an info message with custom format");
spdlog::set_pattern("%+"); // back to default format
// Backtrace support.
// Auto trigger backtrace of latest debug/trace messages upon when error/critical messages happen..
spdlog::enable_backtrace(16);
spdlog::trace("Backtrace message 1");
spdlog::debug("Backtrace message 2");
spdlog::dump_backtrace();
try
{
stdout_logger_example();
basic_example();
rotating_example();
daily_example();
clone_example();
async_example();
binary_example();
multi_sink_example();
user_defined_example();
err_handler_example();
trace_example();
// Flush all *registered* loggers using a worker thread every 3 seconds.
// note: registered loggers *must* be thread safe for this to work correctly!
spdlog::flush_every(std::chrono::seconds(3));
// Apply some function on all registered loggers
spdlog::apply_all([&](std::shared_ptr<spdlog::logger> l) { l->info("End of example."); });
// Release all spdlog resources, and drop all loggers in the registry.
// This is optional (only mandatory if using windows + async log).
spdlog::shutdown();
}
// Exceptions will only be thrown upon failed logger or sink construction (not during logging).
catch (const spdlog::spdlog_ex &ex)
{
std::printf("Log initialization failed: %s\n", ex.what());
return 1;
}
}
#include "spdlog/sinks/stdout_color_sinks.h"
// or #include "spdlog/sinks/stdout_sinks.h" if no colors needed.
void stdout_logger_example()
{
// Create color multi threaded logger.
auto console = spdlog::stdout_color_mt("console");
// or for stderr:
// auto console = spdlog::stderr_color_mt("error-logger");
}
#include "spdlog/sinks/basic_file_sink.h"
void basic_example()
{
// Create basic file logger (not rotated).
auto my_logger = spdlog::basic_logger_mt("file_logger", "logs/basic-log.txt");
}
#include "spdlog/sinks/rotating_file_sink.h"
void rotating_example()
{
// Create a file rotating logger with 5mb size max and 3 rotated files.
auto rotating_logger = spdlog::rotating_logger_mt("some_logger_name", "logs/rotating.txt", 1048576 * 5, 3);
}
#include "spdlog/sinks/daily_file_sink.h"
void daily_example()
{
// Create a daily logger - a new file is created every day on 2:30am.
auto daily_logger = spdlog::daily_logger_mt("daily_logger", "logs/daily.txt", 2, 30);
}
// Clone a logger and give it new name.
// Useful for creating component/subsystem loggers from some "root" logger.
void clone_example()
{
auto network_logger = spdlog::default_logger()->clone("network");
network_logger->info("Logging network stuff..");
}
#include "spdlog/async.h"
void async_example()
{
// Default thread pool settings can be modified *before* creating the async logger:
// spdlog::init_thread_pool(32768, 1); // queue with max 32k items 1 backing thread.
auto async_file = spdlog::basic_logger_mt<spdlog::async_factory>("async_file_logger", "logs/async_log.txt");
// alternatively:
// auto async_file = spdlog::create_async<spdlog::sinks::basic_file_sink_mt>("async_file_logger", "logs/async_log.txt");
for (int i = 1; i < 101; ++i)
{
async_file->info("Async message #{}", i);
}
}
// Log binary data as hex.
// Many types of std::container<char> types can be used.
// Iterator ranges are supported too.
// Format flags:
// {:X} - print in uppercase.
// {:s} - don't separate each byte with space.
// {:p} - don't print the position on each line start.
// {:n} - don't split the output to lines.
#include "spdlog/fmt/bin_to_hex.h"
void binary_example()
{
std::vector<char> buf;
for (int i = 0; i < 80; i++)
{
buf.push_back(static_cast<char>(i & 0xff));
}
spdlog::info("Binary example: {}", spdlog::to_hex(buf));
spdlog::info("Another binary example:{:n}", spdlog::to_hex(std::begin(buf), std::begin(buf) + 10));
// more examples:
// logger->info("uppercase: {:X}", spdlog::to_hex(buf));
// logger->info("uppercase, no delimiters: {:Xs}", spdlog::to_hex(buf));
// logger->info("uppercase, no delimiters, no position info: {:Xsp}", spdlog::to_hex(buf));
}
// Compile time log levels.
// define SPDLOG_ACTIVE_LEVEL to required level (e.g. SPDLOG_LEVEL_TRACE)
void trace_example()
{
// trace from default logger
SPDLOG_TRACE("Some trace message.. {} ,{}", 1, 3.23);
// debug from default logger
SPDLOG_DEBUG("Some debug message.. {} ,{}", 1, 3.23);
// trace from logger object
auto logger = spdlog::get("file_logger");
SPDLOG_LOGGER_TRACE(logger, "another trace message");
}
// A logger with multiple sinks (stdout and file) - each with a different format and log level.
void multi_sink_example()
{
auto console_sink = std::make_shared<spdlog::sinks::stdout_color_sink_mt>();
console_sink->set_level(spdlog::level::warn);
console_sink->set_pattern("[multi_sink_example] [%^%l%$] %v");
auto file_sink = std::make_shared<spdlog::sinks::basic_file_sink_mt>("logs/multisink.txt", true);
file_sink->set_level(spdlog::level::trace);
spdlog::logger logger("multi_sink", {console_sink, file_sink});
logger.set_level(spdlog::level::debug);
logger.warn("this should appear in both console and file");
logger.info("this message should not appear in the console, only in the file");
}
// User defined types logging by implementing operator<<
#include "spdlog/fmt/ostr.h" // must be included
struct my_type
{
int i;
template<typename OStream>
friend OStream &operator<<(OStream &os, const my_type &c)
{
return os << "[my_type i=" << c.i << "]";
}
};
void user_defined_example()
{
spdlog::info("user defined type: {}", my_type{14});
}
// Custom error handler. Will be triggered on log failure.
void err_handler_example()
{
// can be set globally or per logger(logger->set_error_handler(..))
spdlog::set_error_handler([](const std::string &msg) { printf("*** Custom log error handler: %s ***\n", msg.c_str()); });
}
// syslog example (linux/osx/freebsd)
#ifndef _WIN32
#include "spdlog/sinks/syslog_sink.h"
void syslog_example()
{
std::string ident = "spdlog-example";
auto syslog_logger = spdlog::syslog_logger_mt("syslog", ident, LOG_PID);
syslog_logger->warn("This is warning that will end up in syslog.");
}
#endif
// Android example.
#if defined(__ANDROID__)
#include "spdlog/sinks/android_sink.h"
void android_example()
{
std::string tag = "spdlog-android";
auto android_logger = spdlog::android_logger_mt("android", tag);
android_logger->critical("Use \"adb shell logcat\" to view this message.");
}
#endif
<|endoftext|> |
<commit_before>/* -*-c++-*- OpenSceneGraph - Copyright (C) 1998-2006 Robert Osfield
*
* This library is open source and may be redistributed and/or modified under
* the terms of the OpenSceneGraph Public License (OSGPL) version 0.0 or
* (at your option) any later version. The full license is in LICENSE file
* included with this distribution, and on the openscenegraph.org website.
*
* 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
* OpenSceneGraph Public License for more details.
*/
#include <osgPresentation/Timeout>
#include <osgUtil/CullVisitor>
#include <osgGA/EventVisitor>
using namespace osgPresentation;
HUDSettings::HUDSettings(double slideDistance, float eyeOffset, unsigned int leftMask, unsigned int rightMask):
_slideDistance(slideDistance),
_eyeOffset(eyeOffset),
_leftMask(leftMask),
_rightMask(rightMask)
{
}
HUDSettings::~HUDSettings()
{
}
bool HUDSettings::getModelViewMatrix(osg::Matrix& matrix, osg::NodeVisitor* nv) const
{
matrix.makeLookAt(osg::Vec3d(0.0,0.0,0.0),osg::Vec3d(0.0,_slideDistance,0.0),osg::Vec3d(0.0,0.0,1.0));
if (nv)
{
if (nv->getTraversalMask()==_leftMask)
{
matrix.postMultTranslate(osg::Vec3(_eyeOffset,0.0,0.0));
}
else if (nv->getTraversalMask()==_rightMask)
{
matrix.postMultTranslate(osg::Vec3(-_eyeOffset,0.0,0.0));
}
}
return true;
}
bool HUDSettings::getInverseModelViewMatrix(osg::Matrix& matrix, osg::NodeVisitor* nv) const
{
osg::Matrix modelView;
getModelViewMatrix(modelView,nv);
matrix.invert(modelView);
return true;
}
Timeout::Timeout(HUDSettings* hudSettings):
_previousFrameNumber(-1),
_timeOfLastEvent(0.0),
_displayTimeout(false),
_idleDurationBeforeTimeoutDisplay(DBL_MAX),
_idleDurationBeforeTimeoutAction(DBL_MAX),
_keyStartsTimoutDisplay(0),
_keyDismissTimoutDisplay(0),
_keyRunTimeoutAction(0)
{
_hudSettings = hudSettings;
setCullingActive(false);
setNumChildrenRequiringEventTraversal(1);
}
/** Copy constructor using CopyOp to manage deep vs shallow copy.*/
Timeout::Timeout(const Timeout& timeout,const osg::CopyOp& copyop):
osg::Transform(timeout, copyop),
_hudSettings(timeout._hudSettings)
{
setDataVariance(osg::Object::DYNAMIC);
setReferenceFrame(osg::Transform::ABSOLUTE_RF);
}
Timeout::~Timeout()
{
}
bool Timeout::computeLocalToWorldMatrix(osg::Matrix& matrix,osg::NodeVisitor* nv) const
{
if (_hudSettings.valid()) return _hudSettings->getModelViewMatrix(matrix,nv);
else return false;
}
bool Timeout::computeWorldToLocalMatrix(osg::Matrix& matrix,osg::NodeVisitor* nv) const
{
if (_hudSettings.valid()) return _hudSettings->getInverseModelViewMatrix(matrix,nv);
else return false;
}
void Timeout::broadcastEvent(osgViewer::Viewer* viewer, const osgPresentation::KeyPosition& keyPos)
{
osg::ref_ptr<osgGA::GUIEventAdapter> event = new osgGA::GUIEventAdapter;
if (keyPos._key!=0) event->setEventType(osgGA::GUIEventAdapter::KEYDOWN);
else event->setEventType(osgGA::GUIEventAdapter::MOVE);
if (keyPos._key!=0) event->setKey(keyPos._key);
if (keyPos._x!=FLT_MAX) event->setX(keyPos._x);
if (keyPos._y!=FLT_MAX) event->setY(keyPos._y);
event->setMouseYOrientation(osgGA::GUIEventAdapter::Y_INCREASING_UPWARDS);
// dispatch cloned event to devices
osgViewer::View::Devices& devices = viewer->getDevices();
for(osgViewer::View::Devices::iterator i = devices.begin(); i != devices.end(); ++i)
{
if((*i)->getCapabilities() & osgGA::Device::SEND_EVENTS)
{
(*i)->sendEvent(*event);
}
}
}
void Timeout::traverse(osg::NodeVisitor& nv)
{
if (nv.getVisitorType()==osg::NodeVisitor::CULL_VISITOR)
{
osgUtil::CullVisitor* cv = dynamic_cast<osgUtil::CullVisitor*>(&nv);
if (_displayTimeout && cv)
{
osgUtil::RenderStage* previous_stage = cv->getCurrentRenderBin()->getStage();
osg::ref_ptr<osgUtil::RenderStage> rs = new osgUtil::RenderStage;
osg::ColorMask* colorMask = previous_stage->getColorMask();
rs->setColorMask(colorMask);
// set up the viewport.
osg::Viewport* viewport = previous_stage->getViewport();
rs->setViewport( viewport );
rs->setClearMask(GL_DEPTH_BUFFER_BIT);
// record the render bin, to be restored after creation
// of the render to text
osgUtil::RenderBin* previousRenderBin = cv->getCurrentRenderBin();
// set the current renderbin to be the newly created stage.
cv->setCurrentRenderBin(rs.get());
// traverse the subgraph
{
Transform::traverse(nv);
}
// restore the previous renderbin.
cv->setCurrentRenderBin(previousRenderBin);
// and the render to texture stage to the current stages
// dependancy list.
cv->getCurrentRenderBin()->getStage()->addPostRenderStage(rs.get(),0);
}
}
else if (nv.getVisitorType()==osg::NodeVisitor::EVENT_VISITOR)
{
int deltaFrameNumber = (nv.getFrameStamp()->getFrameNumber()-_previousFrameNumber);
_previousFrameNumber = nv.getFrameStamp()->getFrameNumber();
bool needToRecordEventTime = false;
bool needToAction = false;
if (deltaFrameNumber>1)
{
needToRecordEventTime = true;
}
bool previous_displayTimeout = _displayTimeout;
bool needToDismiss = false;
osgGA::EventVisitor* ev = dynamic_cast<osgGA::EventVisitor*>(&nv);
osgViewer::Viewer* viewer = ev ? dynamic_cast<osgViewer::Viewer*>(ev->getActionAdapter()) : 0;
if (ev)
{
osgGA::EventQueue::Events& events = ev->getEvents();
for(osgGA::EventQueue::Events::iterator itr = events.begin();
itr != events.end();
++itr)
{
osgGA::GUIEventAdapter* event = itr->get();
bool keyEvent = event->getEventType()==osgGA::GUIEventAdapter::KEYDOWN || event->getEventType()==osgGA::GUIEventAdapter::KEYUP;
if (keyEvent && event->getKey()==_keyStartsTimoutDisplay)
{
OSG_NOTICE<<"_keyStartsTimoutDisplay pressed"<<std::endl;
_displayTimeout = true;
}
else if (keyEvent && event->getKey()==_keyDismissTimoutDisplay)
{
OSG_NOTICE<<"_keyDismissTimoutDisplay pressed"<<std::endl;
needToRecordEventTime = true;
needToDismiss = _displayTimeout;
_displayTimeout = false;
}
else if (keyEvent && event->getKey()==_keyRunTimeoutAction)
{
OSG_NOTICE<<"_keyRunTimeoutAction pressed"<<std::endl;
_displayTimeout = false;
needToRecordEventTime = true;
needToAction = true;
}
else if (event->getEventType()!=osgGA::GUIEventAdapter::FRAME)
{
needToRecordEventTime = true;
needToDismiss = _displayTimeout;
_displayTimeout = false;
}
}
}
if (needToRecordEventTime)
{
_timeOfLastEvent = nv.getFrameStamp()->getReferenceTime();
}
double timeSinceLastEvent = nv.getFrameStamp() ? nv.getFrameStamp()->getReferenceTime()-_timeOfLastEvent : 0.0;
if (timeSinceLastEvent>_idleDurationBeforeTimeoutDisplay)
{
_displayTimeout = true;
}
if (timeSinceLastEvent>_idleDurationBeforeTimeoutAction)
{
_displayTimeout = false;
needToAction = true;
needToDismiss = false;
}
if (!previous_displayTimeout && _displayTimeout)
{
if (viewer && (_displayBroadcastKeyPos._key!=0 || _displayBroadcastKeyPos._x!=FLT_MAX || _displayBroadcastKeyPos._y!=FLT_MAX))
{
OSG_NOTICE<<"Doing display broadcast key event"<<_displayBroadcastKeyPos._key<<std::endl;
broadcastEvent(viewer, _displayBroadcastKeyPos);
}
}
if (needToDismiss)
{
if (viewer && (_dismissBroadcastKeyPos._key!=0 || _dismissBroadcastKeyPos._x!=FLT_MAX || _dismissBroadcastKeyPos._y!=FLT_MAX))
{
OSG_NOTICE<<"Doing dismiss broadcast key event"<<_dismissBroadcastKeyPos._key<<std::endl;
broadcastEvent(viewer, _dismissBroadcastKeyPos);
}
}
Transform::traverse(nv);
if (needToAction)
{
OSG_NOTICE<<"Do timeout action"<<std::endl;
_previousFrameNumber = -1;
_timeOfLastEvent = nv.getFrameStamp()->getReferenceTime();
if (_actionJumpData.requiresJump())
{
OSG_NOTICE<<"Doing timeout jump"<<std::endl;
_actionJumpData.jump(SlideEventHandler::instance());
}
if (_actionKeyPos._key!=0 || _actionKeyPos._x!=FLT_MAX || _actionKeyPos._y!=FLT_MAX)
{
OSG_NOTICE<<"Doing timeout key event"<<_actionKeyPos._key<<std::endl;
if (SlideEventHandler::instance()) SlideEventHandler::instance()->dispatchEvent(_actionKeyPos);
}
if (viewer && (_actionBroadcastKeyPos._key!=0 || _actionBroadcastKeyPos._x!=FLT_MAX || _actionBroadcastKeyPos._y!=FLT_MAX))
{
OSG_NOTICE<<"Doing timeout broadcast key event"<<_actionBroadcastKeyPos._key<<std::endl;
broadcastEvent(viewer, _actionBroadcastKeyPos);
}
}
}
else
{
OSG_NOTICE<<"Timout::traverse() "<<nv.className()<<std::endl;
Transform::traverse(nv);
}
}
<commit_msg>Added disabling of the traversal of the Timeout in update when the timout is not displayed and disabled traversal by the SlideEventHandler.<commit_after>/* -*-c++-*- OpenSceneGraph - Copyright (C) 1998-2006 Robert Osfield
*
* This library is open source and may be redistributed and/or modified under
* the terms of the OpenSceneGraph Public License (OSGPL) version 0.0 or
* (at your option) any later version. The full license is in LICENSE file
* included with this distribution, and on the openscenegraph.org website.
*
* 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
* OpenSceneGraph Public License for more details.
*/
#include <osgPresentation/Timeout>
#include <osgUtil/CullVisitor>
#include <osgGA/EventVisitor>
using namespace osgPresentation;
HUDSettings::HUDSettings(double slideDistance, float eyeOffset, unsigned int leftMask, unsigned int rightMask):
_slideDistance(slideDistance),
_eyeOffset(eyeOffset),
_leftMask(leftMask),
_rightMask(rightMask)
{
}
HUDSettings::~HUDSettings()
{
}
bool HUDSettings::getModelViewMatrix(osg::Matrix& matrix, osg::NodeVisitor* nv) const
{
matrix.makeLookAt(osg::Vec3d(0.0,0.0,0.0),osg::Vec3d(0.0,_slideDistance,0.0),osg::Vec3d(0.0,0.0,1.0));
if (nv)
{
if (nv->getTraversalMask()==_leftMask)
{
matrix.postMultTranslate(osg::Vec3(_eyeOffset,0.0,0.0));
}
else if (nv->getTraversalMask()==_rightMask)
{
matrix.postMultTranslate(osg::Vec3(-_eyeOffset,0.0,0.0));
}
}
return true;
}
bool HUDSettings::getInverseModelViewMatrix(osg::Matrix& matrix, osg::NodeVisitor* nv) const
{
osg::Matrix modelView;
getModelViewMatrix(modelView,nv);
matrix.invert(modelView);
return true;
}
Timeout::Timeout(HUDSettings* hudSettings):
_previousFrameNumber(-1),
_timeOfLastEvent(0.0),
_displayTimeout(false),
_idleDurationBeforeTimeoutDisplay(DBL_MAX),
_idleDurationBeforeTimeoutAction(DBL_MAX),
_keyStartsTimoutDisplay(0),
_keyDismissTimoutDisplay(0),
_keyRunTimeoutAction(0)
{
_hudSettings = hudSettings;
setCullingActive(false);
setNumChildrenRequiringEventTraversal(1);
}
/** Copy constructor using CopyOp to manage deep vs shallow copy.*/
Timeout::Timeout(const Timeout& timeout,const osg::CopyOp& copyop):
osg::Transform(timeout, copyop),
_hudSettings(timeout._hudSettings)
{
setDataVariance(osg::Object::DYNAMIC);
setReferenceFrame(osg::Transform::ABSOLUTE_RF);
}
Timeout::~Timeout()
{
}
bool Timeout::computeLocalToWorldMatrix(osg::Matrix& matrix,osg::NodeVisitor* nv) const
{
if (_hudSettings.valid()) return _hudSettings->getModelViewMatrix(matrix,nv);
else return false;
}
bool Timeout::computeWorldToLocalMatrix(osg::Matrix& matrix,osg::NodeVisitor* nv) const
{
if (_hudSettings.valid()) return _hudSettings->getInverseModelViewMatrix(matrix,nv);
else return false;
}
void Timeout::broadcastEvent(osgViewer::Viewer* viewer, const osgPresentation::KeyPosition& keyPos)
{
osg::ref_ptr<osgGA::GUIEventAdapter> event = new osgGA::GUIEventAdapter;
if (keyPos._key!=0) event->setEventType(osgGA::GUIEventAdapter::KEYDOWN);
else event->setEventType(osgGA::GUIEventAdapter::MOVE);
if (keyPos._key!=0) event->setKey(keyPos._key);
if (keyPos._x!=FLT_MAX) event->setX(keyPos._x);
if (keyPos._y!=FLT_MAX) event->setY(keyPos._y);
event->setMouseYOrientation(osgGA::GUIEventAdapter::Y_INCREASING_UPWARDS);
// dispatch cloned event to devices
osgViewer::View::Devices& devices = viewer->getDevices();
for(osgViewer::View::Devices::iterator i = devices.begin(); i != devices.end(); ++i)
{
if((*i)->getCapabilities() & osgGA::Device::SEND_EVENTS)
{
(*i)->sendEvent(*event);
}
}
}
void Timeout::traverse(osg::NodeVisitor& nv)
{
if (nv.getVisitorType()==osg::NodeVisitor::CULL_VISITOR)
{
osgUtil::CullVisitor* cv = dynamic_cast<osgUtil::CullVisitor*>(&nv);
if (_displayTimeout && cv)
{
osgUtil::RenderStage* previous_stage = cv->getCurrentRenderBin()->getStage();
osg::ref_ptr<osgUtil::RenderStage> rs = new osgUtil::RenderStage;
osg::ColorMask* colorMask = previous_stage->getColorMask();
rs->setColorMask(colorMask);
// set up the viewport.
osg::Viewport* viewport = previous_stage->getViewport();
rs->setViewport( viewport );
rs->setClearMask(GL_DEPTH_BUFFER_BIT);
// record the render bin, to be restored after creation
// of the render to text
osgUtil::RenderBin* previousRenderBin = cv->getCurrentRenderBin();
// set the current renderbin to be the newly created stage.
cv->setCurrentRenderBin(rs.get());
// traverse the subgraph
{
Transform::traverse(nv);
}
// restore the previous renderbin.
cv->setCurrentRenderBin(previousRenderBin);
// and the render to texture stage to the current stages
// dependancy list.
cv->getCurrentRenderBin()->getStage()->addPostRenderStage(rs.get(),0);
}
}
else if (nv.getVisitorType()==osg::NodeVisitor::EVENT_VISITOR)
{
int deltaFrameNumber = (nv.getFrameStamp()->getFrameNumber()-_previousFrameNumber);
_previousFrameNumber = nv.getFrameStamp()->getFrameNumber();
bool needToRecordEventTime = false;
bool needToAction = false;
if (deltaFrameNumber>1)
{
needToRecordEventTime = true;
}
bool previous_displayTimeout = _displayTimeout;
bool needToDismiss = false;
osgGA::EventVisitor* ev = dynamic_cast<osgGA::EventVisitor*>(&nv);
osgViewer::Viewer* viewer = ev ? dynamic_cast<osgViewer::Viewer*>(ev->getActionAdapter()) : 0;
if (ev)
{
osgGA::EventQueue::Events& events = ev->getEvents();
for(osgGA::EventQueue::Events::iterator itr = events.begin();
itr != events.end();
++itr)
{
osgGA::GUIEventAdapter* event = itr->get();
bool keyEvent = event->getEventType()==osgGA::GUIEventAdapter::KEYDOWN || event->getEventType()==osgGA::GUIEventAdapter::KEYUP;
if (keyEvent && event->getKey()==_keyStartsTimoutDisplay)
{
OSG_NOTICE<<"_keyStartsTimoutDisplay pressed"<<std::endl;
_displayTimeout = true;
}
else if (keyEvent && event->getKey()==_keyDismissTimoutDisplay)
{
OSG_NOTICE<<"_keyDismissTimoutDisplay pressed"<<std::endl;
needToRecordEventTime = true;
needToDismiss = _displayTimeout;
_displayTimeout = false;
}
else if (keyEvent && event->getKey()==_keyRunTimeoutAction)
{
OSG_NOTICE<<"_keyRunTimeoutAction pressed"<<std::endl;
_displayTimeout = false;
needToRecordEventTime = true;
needToAction = true;
}
else if (event->getEventType()!=osgGA::GUIEventAdapter::FRAME)
{
needToRecordEventTime = true;
needToDismiss = _displayTimeout;
_displayTimeout = false;
}
}
}
if (needToRecordEventTime)
{
_timeOfLastEvent = nv.getFrameStamp()->getReferenceTime();
}
double timeSinceLastEvent = nv.getFrameStamp() ? nv.getFrameStamp()->getReferenceTime()-_timeOfLastEvent : 0.0;
if (timeSinceLastEvent>_idleDurationBeforeTimeoutDisplay)
{
_displayTimeout = true;
}
if (timeSinceLastEvent>_idleDurationBeforeTimeoutAction)
{
_displayTimeout = false;
needToAction = true;
needToDismiss = false;
}
if (!previous_displayTimeout && _displayTimeout)
{
if (viewer && (_displayBroadcastKeyPos._key!=0 || _displayBroadcastKeyPos._x!=FLT_MAX || _displayBroadcastKeyPos._y!=FLT_MAX))
{
OSG_NOTICE<<"Doing display broadcast key event"<<_displayBroadcastKeyPos._key<<std::endl;
broadcastEvent(viewer, _displayBroadcastKeyPos);
}
}
if (needToDismiss)
{
if (viewer && (_dismissBroadcastKeyPos._key!=0 || _dismissBroadcastKeyPos._x!=FLT_MAX || _dismissBroadcastKeyPos._y!=FLT_MAX))
{
OSG_NOTICE<<"Doing dismiss broadcast key event"<<_dismissBroadcastKeyPos._key<<std::endl;
broadcastEvent(viewer, _dismissBroadcastKeyPos);
}
}
Transform::traverse(nv);
if (needToAction)
{
OSG_NOTICE<<"Do timeout action"<<std::endl;
_previousFrameNumber = -1;
_timeOfLastEvent = nv.getFrameStamp()->getReferenceTime();
if (_actionJumpData.requiresJump())
{
OSG_NOTICE<<"Doing timeout jump"<<std::endl;
_actionJumpData.jump(SlideEventHandler::instance());
}
if (_actionKeyPos._key!=0 || _actionKeyPos._x!=FLT_MAX || _actionKeyPos._y!=FLT_MAX)
{
OSG_NOTICE<<"Doing timeout key event"<<_actionKeyPos._key<<std::endl;
if (SlideEventHandler::instance()) SlideEventHandler::instance()->dispatchEvent(_actionKeyPos);
}
if (viewer && (_actionBroadcastKeyPos._key!=0 || _actionBroadcastKeyPos._x!=FLT_MAX || _actionBroadcastKeyPos._y!=FLT_MAX))
{
OSG_NOTICE<<"Doing timeout broadcast key event"<<_actionBroadcastKeyPos._key<<std::endl;
broadcastEvent(viewer, _actionBroadcastKeyPos);
}
}
}
else if (nv.getVisitorType()==osg::NodeVisitor::UPDATE_VISITOR)
{
if (_displayTimeout) Transform::traverse(nv);
}
else
{
if (strcmp(nv.className(),"FindOperatorsVisitor")==0)
{
OSG_NOTICE<<"Timout::traverse() "<<nv.className()<<", ignoring traversal"<<std::endl;
}
else
{
Transform::traverse(nv);
}
}
}
<|endoftext|> |
<commit_before>#include "bitstreamparser.h"
#include "exceptions/decodernotfoundexception.h"
#include "exceptions/bitstreamnotfoundexception.h"
#include "gitlupdateuievt.h"
#include <QProcess>
#include <QDir>
#include <QFileInfo>
#include <QDebug>
#include <QApplication>
BitstreamParser::BitstreamParser(QObject *parent):
m_cDecoderProcess(this)
{
connect(&m_cDecoderProcess, SIGNAL(readyReadStandardOutput()), this, SLOT(displayDecoderOutput()));
connect(qApp, SIGNAL(aboutToQuit()), &m_cDecoderProcess, SLOT(kill()));
//connect
}
BitstreamParser::~BitstreamParser()
{
m_cDecoderProcess.kill();
//m_cDecoderProcess.waitForFinished();
}
bool BitstreamParser::parseFile(QString strDecoderFolder,
int iEncoderVersion,
QString strBitstreamFilePath,
QString strOutputPath,
ComSequence* pcSequence)
{
QDir cCurDir = QDir::current();
/// check if decoder exist
QString strDecoderPath;
QStringList cCandidateDecoderList;
cCandidateDecoderList << QString("HM_%1").arg(iEncoderVersion)
<< QString("HM_%1.exe").arg(iEncoderVersion)
<< QString("HM_%1.out").arg(iEncoderVersion);
QDir cDecoderFolder(strDecoderFolder);
foreach(const QString& strDecoderExe, cCandidateDecoderList)
{
if( cDecoderFolder.exists(strDecoderExe) )
{
strDecoderPath = cDecoderFolder.absoluteFilePath(strDecoderExe);
break;
}
}
/// not found
if(strDecoderPath.isEmpty())
{
qCritical() << QString("Decoder Not found in folder %1").arg(strDecoderFolder);
throw DecoderNotFoundException();
}
/// check if bitstream file exist
if( (!cCurDir.exists(strBitstreamFilePath)) ||
(!cCurDir.isAbsolutePath(strBitstreamFilePath)) )
{
throw BitstreamNotFoundException();
}
/// check if output folder exist
if( !cCurDir.exists(strOutputPath) )
{
cCurDir.mkpath(strOutputPath);
}
m_cDecoderProcess.setWorkingDirectory(strOutputPath);
QString strStandardOutputFile = strOutputPath+"/decoder_general.txt";
m_cStdOutputFile.setFileName(strStandardOutputFile);
m_cStdOutputFile.open(QIODevice::WriteOnly);
QString strDecoderCmd = QString("\"%1\" -b \"%2\" -o decoder_yuv.yuv").arg(strDecoderPath).arg(strBitstreamFilePath);
qDebug() << strDecoderCmd;
m_cDecoderProcess.start(strDecoderCmd);
/// wait for end/cancel
m_cDecoderProcess.waitForFinished(-1);
m_cStdOutputFile.close();
pcSequence->setDecodingFolder(strOutputPath);
return (m_cDecoderProcess.exitCode() == 0);
}
void BitstreamParser::displayDecoderOutput()
{
while( m_cDecoderProcess.canReadLine() )
{
// write to file
QString strLine = m_cDecoderProcess.readLine();
m_cStdOutputFile.write(strLine.toStdString().c_str());
// display progress text as event
QRegExp cMatchTarget;
cMatchTarget.setPattern("POC *(-?[0-9]+)");
if( cMatchTarget.indexIn(strLine) != -1 )
{
GitlUpdateUIEvt evt;
int iPoc = cMatchTarget.cap(1).toInt();
QString strText = QString("POC %1 Decoded").arg(iPoc);
evt.setParameter("decoding_progress", strText);
dispatchEvt(evt);
}
}
}
<commit_msg>change encoder and bitstream path into native format<commit_after>#include "bitstreamparser.h"
#include "exceptions/decodernotfoundexception.h"
#include "exceptions/bitstreamnotfoundexception.h"
#include "gitlupdateuievt.h"
#include <QProcess>
#include <QDir>
#include <QFileInfo>
#include <QDebug>
#include <QApplication>
BitstreamParser::BitstreamParser(QObject *parent):
m_cDecoderProcess(this)
{
connect(&m_cDecoderProcess, SIGNAL(readyReadStandardOutput()), this, SLOT(displayDecoderOutput()));
connect(qApp, SIGNAL(aboutToQuit()), &m_cDecoderProcess, SLOT(kill()));
//connect
}
BitstreamParser::~BitstreamParser()
{
m_cDecoderProcess.kill();
//m_cDecoderProcess.waitForFinished();
}
bool BitstreamParser::parseFile(QString strDecoderFolder,
int iEncoderVersion,
QString strBitstreamFilePath,
QString strOutputPath,
ComSequence* pcSequence)
{
QDir cCurDir = QDir::current();
/// check if decoder exist
QString strDecoderPath;
QStringList cCandidateDecoderList;
cCandidateDecoderList << QString("HM_%1").arg(iEncoderVersion)
<< QString("HM_%1.exe").arg(iEncoderVersion)
<< QString("HM_%1.out").arg(iEncoderVersion);
QDir cDecoderFolder(strDecoderFolder);
foreach(const QString& strDecoderExe, cCandidateDecoderList)
{
if( cDecoderFolder.exists(strDecoderExe) )
{
strDecoderPath = cDecoderFolder.absoluteFilePath(strDecoderExe);
break;
}
}
/// not found
if(strDecoderPath.isEmpty())
{
qCritical() << QString("Decoder Not found in folder %1").arg(strDecoderFolder);
throw DecoderNotFoundException();
}
/// check if bitstream file exist
if( (!cCurDir.exists(strBitstreamFilePath)) ||
(!cCurDir.isAbsolutePath(strBitstreamFilePath)) )
{
throw BitstreamNotFoundException();
}
/// check if output folder exist
if( !cCurDir.exists(strOutputPath) )
{
cCurDir.mkpath(strOutputPath);
}
m_cDecoderProcess.setWorkingDirectory(strOutputPath);
QString strStandardOutputFile = strOutputPath+"/decoder_general.txt";
m_cStdOutputFile.setFileName(strStandardOutputFile);
m_cStdOutputFile.open(QIODevice::WriteOnly);
strDecoderPath = QDir::toNativeSeparators(strDecoderPath); /// convert to native path
strBitstreamFilePath = QDir::toNativeSeparators(strBitstreamFilePath); /// convert to native path
QString strDecoderCmd = QString("\"%1\" -b \"%2\" -o decoder_yuv.yuv").arg(strDecoderPath).arg(strBitstreamFilePath);
qDebug() << strDecoderCmd;
m_cDecoderProcess.start(strDecoderCmd);
/// wait for end/cancel
m_cDecoderProcess.waitForFinished(-1);
m_cStdOutputFile.close();
pcSequence->setDecodingFolder(strOutputPath);
return (m_cDecoderProcess.exitCode() == 0);
}
void BitstreamParser::displayDecoderOutput()
{
while( m_cDecoderProcess.canReadLine() )
{
// write to file
QString strLine = m_cDecoderProcess.readLine();
m_cStdOutputFile.write(strLine.toStdString().c_str());
// display progress text as event
QRegExp cMatchTarget;
cMatchTarget.setPattern("POC *(-?[0-9]+)");
if( cMatchTarget.indexIn(strLine) != -1 )
{
GitlUpdateUIEvt evt;
int iPoc = cMatchTarget.cap(1).toInt();
QString strText = QString("POC %1 Decoded").arg(iPoc);
evt.setParameter("decoding_progress", strText);
dispatchEvt(evt);
}
}
}
<|endoftext|> |
<commit_before>//
// libavg - Media Playback Engine.
// Copyright (C) 2003-2008 Ulrich von Zadow
//
// 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 of the License, or (at your option) any later version.
//
// This library is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
// Lesser General Public License for more details.
//
// You should have received a copy of the GNU Lesser General Public
// License along with this library; if not, write to the Free Software
// Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
//
// Current versions can be found at www.libavg.de
//
#include "FilledVectorNode.h"
#include "NodeDefinition.h"
#include "Image.h"
#include "DivNode.h"
#include "../player/SDLDisplayEngine.h"
#include "../base/ScopeTimer.h"
#include "../base/Logger.h"
using namespace std;
using namespace boost;
namespace avg {
NodeDefinition FilledVectorNode::createDefinition()
{
return NodeDefinition("filledvector")
.extendDefinition(VectorNode::createDefinition())
.addArg(Arg<string>("filltexhref", "", false,
offsetof(FilledVectorNode, m_FillTexHRef)))
.addArg(Arg<double>("fillopacity", 0, false,
offsetof(FilledVectorNode, m_FillOpacity)))
.addArg(Arg<string>("fillcolor", "FFFFFF", false,
offsetof(FilledVectorNode, m_sFillColorName)))
;
}
FilledVectorNode::FilledVectorNode(const ArgList& Args)
: VectorNode(Args),
m_FillTexCoord1(0,0),
m_FillTexCoord2(1,1),
m_pFillShape(new Shape("", GL_REPEAT, GL_REPEAT))
{
m_FillTexHRef = Args.getArgVal<string>("filltexhref");
setFillTexHRef(m_FillTexHRef);
m_sFillColorName = Args.getArgVal<string>("fillcolor");
m_FillColor = colorStringToColor(m_sFillColorName);
}
FilledVectorNode::~FilledVectorNode()
{
}
void FilledVectorNode::setRenderingEngines(DisplayEngine * pDisplayEngine,
AudioEngine * pAudioEngine)
{
VectorNode::setRenderingEngines(pDisplayEngine, pAudioEngine);
m_FillColor = colorStringToColor(m_sFillColorName);
m_pFillShape->moveToGPU(getDisplayEngine());
m_OldOpacity = -1;
}
void FilledVectorNode::disconnect()
{
m_pFillShape->moveToCPU();
VectorNode::disconnect();
}
void FilledVectorNode::checkReload()
{
ImagePtr pImage = boost::dynamic_pointer_cast<Image>(m_pFillShape);
Node::checkReload(m_FillTexHRef, pImage);
VectorNode::checkReload();
}
const std::string& FilledVectorNode::getFillTexHRef() const
{
return m_FillTexHRef;
}
void FilledVectorNode::setFillTexHRef(const string& href)
{
m_FillTexHRef = href;
checkReload();
setDrawNeeded(true);
}
void FilledVectorNode::setFillBitmap(const Bitmap * pBmp)
{
m_FillTexHRef = "";
m_pFillShape->setBitmap(pBmp);
setDrawNeeded(true);
}
const DPoint& FilledVectorNode::getFillTexCoord1() const
{
return m_FillTexCoord1;
}
void FilledVectorNode::setFillTexCoord1(const DPoint& pt)
{
m_FillTexCoord1 = pt;
setDrawNeeded(false);
}
const DPoint& FilledVectorNode::getFillTexCoord2() const
{
return m_FillTexCoord2;
}
void FilledVectorNode::setFillTexCoord2(const DPoint& pt)
{
m_FillTexCoord2 = pt;
setDrawNeeded(false);
}
double FilledVectorNode::getFillOpacity() const
{
return m_FillOpacity;
}
void FilledVectorNode::setFillOpacity(double opacity)
{
m_FillOpacity = opacity;
setDrawNeeded(false);
}
void FilledVectorNode::preRender()
{
Node::preRender();
double curOpacity = getParent()->getEffectiveOpacity()*m_FillOpacity;
VertexArrayPtr pFillVA;
pFillVA = m_pFillShape->getVertexArray();
if (hasVASizeChanged()) {
pFillVA->changeSize(getNumFillVertexes(), getNumFillIndexes());
}
if (isDrawNeeded() || curOpacity != m_OldOpacity) {
pFillVA->reset();
Pixel32 color = getFillColorVal();
color.setA((unsigned char)(curOpacity*255));
calcFillVertexes(pFillVA, color);
pFillVA->update();
m_OldOpacity = curOpacity;
}
VectorNode::preRender();
}
void FilledVectorNode::maybeRender(const DRect& Rect)
{
assert(getState() == NS_CANRENDER);
if (getEffectiveOpacity() > 0.01 ||
getParent()->getEffectiveOpacity()*m_FillOpacity > 0.01)
{
if (getID() != "") {
AVG_TRACE(Logger::BLTS, "Rendering " << getTypeStr() <<
" with ID " << getID());
} else {
AVG_TRACE(Logger::BLTS, "Rendering " << getTypeStr());
}
getDisplayEngine()->setBlendMode(getBlendMode());
render(Rect);
}
}
static ProfilingZone RenderProfilingZone("FilledVectorNode::render");
void FilledVectorNode::render(const DRect& rect)
{
ScopeTimer Timer(RenderProfilingZone);
double curOpacity = getParent()->getEffectiveOpacity()*m_FillOpacity;
glColor4d(1.0, 1.0, 1.0, curOpacity);
m_pFillShape->draw();
VectorNode::render(rect);
}
void FilledVectorNode::setFillColor(const string& sColor)
{
if (m_sFillColorName != sColor) {
m_sFillColorName = sColor;
m_FillColor = colorStringToColor(m_sFillColorName);
setDrawNeeded(false);
}
}
const string& FilledVectorNode::getFillColor() const
{
return m_sFillColorName;
}
Pixel32 FilledVectorNode::getFillColorVal() const
{
return m_FillColor;
}
DPoint FilledVectorNode::calcFillTexCoord(const DPoint& pt, const DPoint& minPt,
const DPoint& maxPt)
{
DPoint texPt;
texPt.x = (m_FillTexCoord2.x-m_FillTexCoord1.x)*(pt.x-minPt.x)/(maxPt.x-minPt.x)
+m_FillTexCoord1.x;
texPt.y = (m_FillTexCoord2.y-m_FillTexCoord1.y)*(pt.y-minPt.y)/(maxPt.y-minPt.y)
+m_FillTexCoord1.y;
return texPt;
}
}
<commit_msg>Added ability to set vector node fill bitmap to empty after using a real texture.<commit_after>//
// libavg - Media Playback Engine.
// Copyright (C) 2003-2008 Ulrich von Zadow
//
// 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 of the License, or (at your option) any later version.
//
// This library is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
// Lesser General Public License for more details.
//
// You should have received a copy of the GNU Lesser General Public
// License along with this library; if not, write to the Free Software
// Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
//
// Current versions can be found at www.libavg.de
//
#include "FilledVectorNode.h"
#include "NodeDefinition.h"
#include "Image.h"
#include "DivNode.h"
#include "../player/SDLDisplayEngine.h"
#include "../base/ScopeTimer.h"
#include "../base/Logger.h"
using namespace std;
using namespace boost;
namespace avg {
NodeDefinition FilledVectorNode::createDefinition()
{
return NodeDefinition("filledvector")
.extendDefinition(VectorNode::createDefinition())
.addArg(Arg<string>("filltexhref", "", false,
offsetof(FilledVectorNode, m_FillTexHRef)))
.addArg(Arg<double>("fillopacity", 0, false,
offsetof(FilledVectorNode, m_FillOpacity)))
.addArg(Arg<string>("fillcolor", "FFFFFF", false,
offsetof(FilledVectorNode, m_sFillColorName)))
;
}
FilledVectorNode::FilledVectorNode(const ArgList& Args)
: VectorNode(Args),
m_FillTexCoord1(0,0),
m_FillTexCoord2(1,1),
m_pFillShape(new Shape("", GL_REPEAT, GL_REPEAT))
{
m_FillTexHRef = Args.getArgVal<string>("filltexhref");
setFillTexHRef(m_FillTexHRef);
m_sFillColorName = Args.getArgVal<string>("fillcolor");
m_FillColor = colorStringToColor(m_sFillColorName);
}
FilledVectorNode::~FilledVectorNode()
{
}
void FilledVectorNode::setRenderingEngines(DisplayEngine * pDisplayEngine,
AudioEngine * pAudioEngine)
{
VectorNode::setRenderingEngines(pDisplayEngine, pAudioEngine);
m_FillColor = colorStringToColor(m_sFillColorName);
m_pFillShape->moveToGPU(getDisplayEngine());
m_OldOpacity = -1;
}
void FilledVectorNode::disconnect()
{
m_pFillShape->moveToCPU();
VectorNode::disconnect();
}
void FilledVectorNode::checkReload()
{
ImagePtr pImage = boost::dynamic_pointer_cast<Image>(m_pFillShape);
Node::checkReload(m_FillTexHRef, pImage);
VectorNode::checkReload();
}
const std::string& FilledVectorNode::getFillTexHRef() const
{
return m_FillTexHRef;
}
void FilledVectorNode::setFillTexHRef(const string& href)
{
m_FillTexHRef = href;
checkReload();
setDrawNeeded(true);
}
void FilledVectorNode::setFillBitmap(const Bitmap * pBmp)
{
m_FillTexHRef = "";
if (pBmp) {
m_pFillShape->setBitmap(pBmp);
} else {
m_pFillShape->setFilename("");
}
setDrawNeeded(true);
}
const DPoint& FilledVectorNode::getFillTexCoord1() const
{
return m_FillTexCoord1;
}
void FilledVectorNode::setFillTexCoord1(const DPoint& pt)
{
m_FillTexCoord1 = pt;
setDrawNeeded(false);
}
const DPoint& FilledVectorNode::getFillTexCoord2() const
{
return m_FillTexCoord2;
}
void FilledVectorNode::setFillTexCoord2(const DPoint& pt)
{
m_FillTexCoord2 = pt;
setDrawNeeded(false);
}
double FilledVectorNode::getFillOpacity() const
{
return m_FillOpacity;
}
void FilledVectorNode::setFillOpacity(double opacity)
{
m_FillOpacity = opacity;
setDrawNeeded(false);
}
void FilledVectorNode::preRender()
{
Node::preRender();
double curOpacity = getParent()->getEffectiveOpacity()*m_FillOpacity;
VertexArrayPtr pFillVA;
pFillVA = m_pFillShape->getVertexArray();
if (hasVASizeChanged()) {
pFillVA->changeSize(getNumFillVertexes(), getNumFillIndexes());
}
if (isDrawNeeded() || curOpacity != m_OldOpacity) {
pFillVA->reset();
Pixel32 color = getFillColorVal();
color.setA((unsigned char)(curOpacity*255));
calcFillVertexes(pFillVA, color);
pFillVA->update();
m_OldOpacity = curOpacity;
}
VectorNode::preRender();
}
void FilledVectorNode::maybeRender(const DRect& Rect)
{
assert(getState() == NS_CANRENDER);
if (getEffectiveOpacity() > 0.01 ||
getParent()->getEffectiveOpacity()*m_FillOpacity > 0.01)
{
if (getID() != "") {
AVG_TRACE(Logger::BLTS, "Rendering " << getTypeStr() <<
" with ID " << getID());
} else {
AVG_TRACE(Logger::BLTS, "Rendering " << getTypeStr());
}
getDisplayEngine()->setBlendMode(getBlendMode());
render(Rect);
}
}
static ProfilingZone RenderProfilingZone("FilledVectorNode::render");
void FilledVectorNode::render(const DRect& rect)
{
ScopeTimer Timer(RenderProfilingZone);
double curOpacity = getParent()->getEffectiveOpacity()*m_FillOpacity;
glColor4d(1.0, 1.0, 1.0, curOpacity);
m_pFillShape->draw();
VectorNode::render(rect);
}
void FilledVectorNode::setFillColor(const string& sColor)
{
if (m_sFillColorName != sColor) {
m_sFillColorName = sColor;
m_FillColor = colorStringToColor(m_sFillColorName);
setDrawNeeded(false);
}
}
const string& FilledVectorNode::getFillColor() const
{
return m_sFillColorName;
}
Pixel32 FilledVectorNode::getFillColorVal() const
{
return m_FillColor;
}
DPoint FilledVectorNode::calcFillTexCoord(const DPoint& pt, const DPoint& minPt,
const DPoint& maxPt)
{
DPoint texPt;
texPt.x = (m_FillTexCoord2.x-m_FillTexCoord1.x)*(pt.x-minPt.x)/(maxPt.x-minPt.x)
+m_FillTexCoord1.x;
texPt.y = (m_FillTexCoord2.y-m_FillTexCoord1.y)*(pt.y-minPt.y)/(maxPt.y-minPt.y)
+m_FillTexCoord1.y;
return texPt;
}
}
<|endoftext|> |
<commit_before>#include "postgres.h"
#include <string.h>
#include "fmgr.h"
#include "utils/geo_decls.h"
#ifdef __cplusplus
extern "C" {
#endif
#ifdef PG_MODULE_MAGIC
PG_MODULE_MAGIC;
#endif
/* by value */
PG_FUNCTION_INFO_V1(add_one);
Datum
add_one(PG_FUNCTION_ARGS) {
int32 arg = PG_GETARG_INT32(0);
PG_RETURN_INT32(arg + 1);
}
/* by reference, fixed length */
PG_FUNCTION_INFO_V1(add_one_float8);
Datum
add_one_float8(PG_FUNCTION_ARGS) {
/* The macros for FLOAT8 hide its pass-by-reference nature. */
float8 arg = PG_GETARG_FLOAT8(0);
PG_RETURN_FLOAT8(arg + 1.0);
}
PG_FUNCTION_INFO_V1(makepoint);
Datum
makepoint(PG_FUNCTION_ARGS) {
/* Here, the pass-by-reference nature of Point is not hidden. */
Point *pointx = PG_GETARG_POINT_P(0);
Point *pointy = PG_GETARG_POINT_P(1);
Point *new_point = (Point *) palloc(sizeof(Point));
new_point->x = pointx->x;
new_point->y = pointy->y;
PG_RETURN_POINT_P(new_point);
}
/* by reference, variable length */
PG_FUNCTION_INFO_V1(copytext);
Datum
copytext(PG_FUNCTION_ARGS) {
text *t = PG_GETARG_TEXT_P(0);
/*
* VARSIZE is the total size of the struct in bytes.
*/
text *new_t = (text *) palloc(VARSIZE(t));
SET_VARSIZE(new_t, VARSIZE(t));
/*
* VARDATA is a pointer to the data region of the struct.
*/
memcpy((void *) VARDATA(new_t), /* destination */
(void *) VARDATA(t), /* source */
VARSIZE(t) - VARHDRSZ); /* how many bytes */
PG_RETURN_TEXT_P(new_t);
}
PG_FUNCTION_INFO_V1(concat_text);
Datum
concat_text(PG_FUNCTION_ARGS) {
text *arg1 = PG_GETARG_TEXT_P(0);
text *arg2 = PG_GETARG_TEXT_P(1);
int32 new_text_size = VARSIZE(arg1) + VARSIZE(arg2) - VARHDRSZ;
text *new_text = (text *) palloc(new_text_size);
SET_VARSIZE(new_text, new_text_size);
memcpy(VARDATA(new_text), VARDATA(arg1), VARSIZE(arg1) - VARHDRSZ);
memcpy(VARDATA(new_text) + (VARSIZE(arg1) - VARHDRSZ),
VARDATA(arg2), VARSIZE(arg2) - VARHDRSZ);
PG_RETURN_TEXT_P(new_text);
}
#ifdef __cplusplus
};
#endif
<commit_msg>Add udf tests<commit_after>#include "postgres.h"
#include <string.h>
#include "fmgr.h"
#include "utils/geo_decls.h"
#ifdef __cplusplus
extern "C" {
#endif
#ifdef PG_MODULE_MAGIC
PG_MODULE_MAGIC;
#endif
/* by value */
PG_FUNCTION_INFO_V1(add_one);
Datum
add_one(PG_FUNCTION_ARGS) {
int32 arg = PG_GETARG_INT32(0);
PG_RETURN_INT32(arg + 1);
}
/* by value */
PG_FUNCTION_INFO_V1(add);
Datum
add(PG_FUNCTION_ARGS) {
int32 arg0 = PG_GETARG_INT32(0);
int32 arg1 = PG_GETARG_INT32(1);
PG_RETURN_INT32(arg0 + arg1);
}
/* by value */
PG_FUNCTION_INFO_V1(minus);
Datum
minus(PG_FUNCTION_ARGS) {
int32 arg0 = PG_GETARG_INT32(0);
int32 arg1 = PG_GETARG_INT32(1);
PG_RETURN_INT32(arg0 - arg1);
}
/* by value */
PG_FUNCTION_INFO_V1(multiply);
Datum
multiply(PG_FUNCTION_ARGS) {
int32 arg0 = PG_GETARG_INT32(0);
int32 arg1 = PG_GETARG_INT32(1);
PG_RETURN_INT32(arg0 * arg1);
}
/* by value */
PG_FUNCTION_INFO_V1(divide);
Datum
divide(PG_FUNCTION_ARGS) {
int32 arg0 = PG_GETARG_INT32(0);
int32 arg1 = PG_GETARG_INT32(1);
PG_RETURN_INT32(arg0 / arg1);
}
/* by reference, fixed length */
PG_FUNCTION_INFO_V1(add_one_float8);
Datum
add_one_float8(PG_FUNCTION_ARGS) {
/* The macros for FLOAT8 hide its pass-by-reference nature. */
float8 arg = PG_GETARG_FLOAT8(0);
PG_RETURN_FLOAT8(arg + 1.0);
}
PG_FUNCTION_INFO_V1(makepoint);
Datum
makepoint(PG_FUNCTION_ARGS) {
/* Here, the pass-by-reference nature of Point is not hidden. */
Point *pointx = PG_GETARG_POINT_P(0);
Point *pointy = PG_GETARG_POINT_P(1);
Point *new_point = (Point *) palloc(sizeof(Point));
new_point->x = pointx->x;
new_point->y = pointy->y;
PG_RETURN_POINT_P(new_point);
}
/* by reference, variable length */
PG_FUNCTION_INFO_V1(copytext);
Datum
copytext(PG_FUNCTION_ARGS) {
text *t = PG_GETARG_TEXT_P(0);
/*
* VARSIZE is the total size of the struct in bytes.
*/
text *new_t = (text *) palloc(VARSIZE(t));
SET_VARSIZE(new_t, VARSIZE(t));
/*
* VARDATA is a pointer to the data region of the struct.
*/
memcpy((void *) VARDATA(new_t), /* destination */
(void *) VARDATA(t), /* source */
VARSIZE(t) - VARHDRSZ); /* how many bytes */
PG_RETURN_TEXT_P(new_t);
}
PG_FUNCTION_INFO_V1(concat_text);
Datum
concat_text(PG_FUNCTION_ARGS) {
text *arg1 = PG_GETARG_TEXT_P(0);
text *arg2 = PG_GETARG_TEXT_P(1);
int32 new_text_size = VARSIZE(arg1) + VARSIZE(arg2) - VARHDRSZ;
text *new_text = (text *) palloc(new_text_size);
SET_VARSIZE(new_text, new_text_size);
memcpy(VARDATA(new_text), VARDATA(arg1), VARSIZE(arg1) - VARHDRSZ);
memcpy(VARDATA(new_text) + (VARSIZE(arg1) - VARHDRSZ),
VARDATA(arg2), VARSIZE(arg2) - VARHDRSZ);
PG_RETURN_TEXT_P(new_text);
}
#ifdef __cplusplus
};
#endif
<|endoftext|> |
<commit_before>#include "ossimS3StreamBuffer.h"
#include <aws/s3/model/PutObjectRequest.h>
#include <aws/s3/model/GetObjectRequest.h>
#include <aws/s3/model/GetObjectResult.h>
#include <aws/s3/model/HeadObjectRequest.h>
#include <aws/core/Aws.h>
#include <aws/core/utils/memory/stl/AWSStringStream.h>
#include <iostream>
#include <ossim/base/ossimUrl.h>
//static const char* KEY = "test-file.txt";
//static const char* BUCKET = "ossimlabs";
#include <cstdio> /* for EOF */
#include <streambuf>
#include <sstream>
#include <iosfwd>
#include <ios>
#include <vector>
#include <cstring> /* for memcpy */
using namespace Aws::S3;
using namespace Aws::S3::Model;
ossim::S3StreamBuffer::S3StreamBuffer()
:
m_bucket(""),
m_key(""),
m_buffer(1024*1024),
m_bufferActualDataSize(0),
m_currentPosition(-1),
m_bufferPtr(0),
m_currentPtr(0),
m_fileSize(0),
m_opened(false),
m_mode(0)
{
// std::cout << "CONSTRUCTED!!!!!" << std::endl;
// setp(0);
setg(m_currentPtr, m_currentPtr, m_currentPtr);
}
ossim_int64 ossim::S3StreamBuffer::getBlockIndex(ossim_int64 byteOffset)const
{
ossim_int64 blockNumber = -1;
if(byteOffset < m_fileSize)
{
if(m_buffer.size()>0)
{
blockNumber = byteOffset/m_buffer.size();
}
}
return blockNumber;
}
ossim_int64 ossim::S3StreamBuffer::getBlockOffset(ossim_int64 byteOffset)const
{
ossim_int64 blockOffset = -1;
if(m_buffer.size()>0)
{
blockOffset = byteOffset%m_buffer.size();
}
return blockOffset;
}
bool ossim::S3StreamBuffer::getBlockRangeInBytes(ossim_int64 blockIndex,
ossim_int64& startRange,
ossim_int64& endRange)const
{
bool result = false;
if(blockIndex >= 0)
{
startRange = blockIndex*m_buffer.size();
endRange = startRange + m_buffer.size()-1;
result = true;
}
return result;
}
bool ossim::S3StreamBuffer::loadBlock(ossim_int64 blockIndex)
{
bool result = false;
m_bufferPtr = 0;
m_currentPtr = 0;
GetObjectRequest getObjectRequest;
std::stringstream stringStream;
ossim_int64 startRange, endRange;
if(getBlockRangeInBytes(blockIndex, startRange, endRange))
{
stringStream << "bytes=" << startRange << "-" << endRange;
getObjectRequest.WithBucket(m_bucket.c_str())
.WithKey(m_key.c_str()).WithRange(stringStream.str().c_str());
auto getObjectOutcome = m_client.GetObject(getObjectRequest);
if(getObjectOutcome.IsSuccess())
{
// std::cout << "GOOD CALL!!!!!!!!!!!!\n";
Aws::IOStream& bodyStream = getObjectOutcome.GetResult().GetBody();
ossim_uint64 bufSize = getObjectOutcome.GetResult().GetContentLength();
// std::cout << "SIZE OF RESULT ======== " << bufSize << std::endl;
m_bufferActualDataSize = bufSize;
bodyStream.read(&m_buffer.front(), bufSize);
m_bufferPtr = &m_buffer.front();
m_currentPtr = m_bufferPtr;
if(m_currentPosition>=0)
{
ossim_int64 delta = m_currentPosition-startRange;
setg(m_bufferPtr, m_bufferPtr + delta, m_bufferPtr+m_bufferActualDataSize);
}
else
{
setg(m_bufferPtr, m_bufferPtr, m_bufferPtr + m_bufferActualDataSize);
m_currentPosition = startRange;
}
result = true;
//std::cout << "Successfully retrieved object from s3 with value: " << std::endl;
//std::cout << getObjectOutcome.GetResult().GetBody().rdbuf() << std::endl << std::endl;;
}
}
return result;
}
ossim::S3StreamBuffer* ossim::S3StreamBuffer::open (const char* connectionString,
std::ios_base::openmode m)
{
std::string temp(connectionString);
return open(temp, m);
}
ossim::S3StreamBuffer* ossim::S3StreamBuffer::open (const std::string& connectionString,
std::ios_base::openmode mode)
{
bool result = false;
ossimUrl url(connectionString);
clearAll();
m_mode = mode;
if(url.getProtocol() == "s3")
{
m_bucket = url.getIp().c_str();
m_key = url.getPath().c_str();
if(!m_bucket.empty() && !m_key.empty())
{
HeadObjectRequest headObjectRequest;
headObjectRequest.WithBucket(m_bucket.c_str())
.WithKey(m_key.c_str());
auto headObject = m_client.HeadObject(headObjectRequest);
if(headObject.IsSuccess())
{
m_fileSize = headObject.GetResult().GetContentLength();
m_opened = true;
}
}
}
if(m_opened) return this;
return 0;
}
void ossim::S3StreamBuffer::clearAll()
{
m_bucket = "";
m_key = "";
m_currentPtr = 0;
m_fileSize = 0;
m_opened = false;
}
int ossim::S3StreamBuffer::underflow()
{
if((!gptr())&&is_open())
{
if(m_currentPosition >= 0)
{
loadBlock(getBlockIndex(m_currentPosition));
}
else
{
loadBlock(0);
}
if(!gptr())
{
return EOF;
}
}
else if(!is_open())
{
return EOF;
}
else if(egptr() == gptr())
{
m_currentPosition += m_buffer.size();
if(m_currentPosition < m_fileSize)
{
if(!loadBlock(getBlockIndex(m_currentPosition)))
{
return EOF;
}
}
else
{
// std::cout << "SHOULD BE EOF RETURNED\n";
return EOF;
}
}
// std::cout << "GPTR CHARACTER ========== " << (int)(*gptr()) << std::endl;
return (int)(*gptr());
}
#if 0
int ossim::S3StreamBuffer::uflow()
{
// std::cout << "ossim::S3StreamBuffer::uflow()\n";
int result = underflow();
if(result != EOF)
{
result = (int) (*gptr());
++m_currentPosition;
pbump(1);
}
return result;
}
#endif
ossim::S3StreamBuffer::pos_type ossim::S3StreamBuffer::seekoff(off_type offset,
std::ios_base::seekdir dir,
std::ios_base::openmode mode)
{
// std::cout << "ossim::S3StreamBuffer::seekoff\n";
pos_type result = pos_type(off_type(-1));
bool withinBlock = true;
if((mode & std::ios_base::in)&&
(mode & std::ios_base::out))
{
return result;
}
switch(dir)
{
case std::ios_base::beg:
{
// if we are determing an absolute position from the beginning then
// just make sure the offset is within range of the current buffer size
//
if((offset < m_fileSize)&&
(offset >=0))
{
result = pos_type(offset);
}
break;
}
case std::ios_base::cur:
{
ossim_int64 testOffset = m_currentPosition + offset;
if((testOffset >= 0)||(testOffset<m_fileSize))
{
result = testOffset;
}
break;
}
case std::ios_base::end:
{
ossim_int64 testOffset = m_fileSize - offset;
if((testOffset >= 0)||(testOffset<m_fileSize))
{
result = testOffset;
}
break;
}
default:
{
break;
}
}
if(m_currentPosition != result)
{
adjustForSeekgPosition(result);
}
return result;
}
ossim::S3StreamBuffer::pos_type ossim::S3StreamBuffer::seekpos(pos_type pos, std::ios_base::openmode mode)
{
// std::cout << "ossim::S3StreamBuffer::seekpos\n";
pos_type result = pos_type(off_type(-1));
if(mode & std::ios_base::in)
{
if(pos >= 0)
{
if(pos < m_fileSize)
{
result = pos;
}
}
adjustForSeekgPosition(result);
}
return result;
}
void ossim::S3StreamBuffer::adjustForSeekgPosition(ossim_int64 seekPosition)
{
if(seekPosition >= 0)
{
ossim_int64 testPosition = static_cast<ossim_int64> (seekPosition);
if(m_currentPosition >= 0 )
{
ossim_int64 blockIndex1 = getBlockIndex(testPosition);
ossim_int64 blockIndex2 = getBlockIndex(m_currentPosition);
if(blockIndex1 != blockIndex2)
{
m_bufferPtr = m_currentPtr = 0;
// clear out the pointers and force a load on next read
setg(m_bufferPtr, m_bufferPtr, m_bufferPtr);
m_currentPosition = seekPosition;
}
else
{
ossim_int64 startOffset, endOffset;
ossim_int64 delta;
getBlockRangeInBytes(blockIndex1, startOffset, endOffset);
delta = testPosition-startOffset;
m_currentPosition = testPosition;
setg(m_bufferPtr, m_bufferPtr+delta, m_bufferPtr+m_buffer.size());
}
}
else
{
m_bufferPtr = m_currentPtr = 0;
m_currentPosition = seekPosition;
setg(m_bufferPtr, m_bufferPtr, m_bufferPtr);
}
}
else
{
if(m_currentPosition < 0)
{
m_bufferPtr = m_currentPtr = 0;
setg(m_bufferPtr, m_bufferPtr, m_bufferPtr);
}
}
}
std::streamsize ossim::S3StreamBuffer::xsgetn(char_type* s, std::streamsize n)
{
// std::cout << "ossim::S3StreamBuffer::xsgetn" << std::endl;
// unsigned long int bytesLeftToRead = egptr()-gptr();
// initialize if we need to to load the block at current position
if((!gptr())&&is_open())
{
if(m_currentPosition >= 0)
{
loadBlock(getBlockIndex(m_currentPosition));
}
else
{
loadBlock(0);
}
}
else if(!is_open())
{
return EOF;
}
bool needMore = true;
ossim_int64 bytesNeedToRead = n;
ossim_int64 bytesToRead = 0;
ossim_int64 bytesRead = 0;
ossim_int64 startOffset, endOffset;
if(m_currentPosition >= m_fileSize)
{
return EOF;
}
else if((m_currentPosition + bytesNeedToRead)>(m_fileSize))
{
bytesNeedToRead = (m_fileSize - m_currentPosition);
}
while(bytesNeedToRead > 0)
{
if(egptr()==gptr())
{
// load next block
if(m_currentPosition < m_fileSize)
{
if(!loadBlock(getBlockIndex(m_currentPosition)))
{
return bytesRead;
}
}
else
{
return bytesRead;
}
}
// get each bloc
if(m_currentPosition>=0)
{
getBlockRangeInBytes(getBlockIndex(m_currentPosition), startOffset, endOffset);
ossim_int64 delta = (endOffset - m_currentPosition)+1;
if(delta <= bytesNeedToRead)
{
std::memcpy(s+bytesRead, gptr(), delta);
m_currentPosition += delta;
setg(eback(), gptr()+delta, egptr());
bytesRead+=delta;
bytesNeedToRead-=delta;
}
else
{
std::memcpy(s+bytesRead, gptr(), delta);
m_currentPosition += bytesNeedToRead;
setg(eback(), gptr()+bytesNeedToRead, egptr());
bytesRead+=bytesNeedToRead;
bytesNeedToRead=0;
}
}
else
{
break;
}
}
return std::streamsize(bytesRead);
}
<commit_msg>Fixed a core dump in the xsgetn<commit_after>#include "ossimS3StreamBuffer.h"
#include <aws/s3/model/PutObjectRequest.h>
#include <aws/s3/model/GetObjectRequest.h>
#include <aws/s3/model/GetObjectResult.h>
#include <aws/s3/model/HeadObjectRequest.h>
#include <aws/core/Aws.h>
#include <aws/core/utils/memory/stl/AWSStringStream.h>
#include <iostream>
#include <ossim/base/ossimUrl.h>
//static const char* KEY = "test-file.txt";
//static const char* BUCKET = "ossimlabs";
#include <cstdio> /* for EOF */
#include <streambuf>
#include <sstream>
#include <iosfwd>
#include <ios>
#include <vector>
#include <cstring> /* for memcpy */
using namespace Aws::S3;
using namespace Aws::S3::Model;
ossim::S3StreamBuffer::S3StreamBuffer()
:
m_bucket(""),
m_key(""),
m_buffer(1024*1024),
m_bufferActualDataSize(0),
m_currentPosition(-1),
m_bufferPtr(0),
m_currentPtr(0),
m_fileSize(0),
m_opened(false),
m_mode(0)
{
// std::cout << "CONSTRUCTED!!!!!" << std::endl;
// setp(0);
setg(m_currentPtr, m_currentPtr, m_currentPtr);
}
ossim_int64 ossim::S3StreamBuffer::getBlockIndex(ossim_int64 byteOffset)const
{
ossim_int64 blockNumber = -1;
if(byteOffset < m_fileSize)
{
if(m_buffer.size()>0)
{
blockNumber = byteOffset/m_buffer.size();
}
}
return blockNumber;
}
ossim_int64 ossim::S3StreamBuffer::getBlockOffset(ossim_int64 byteOffset)const
{
ossim_int64 blockOffset = -1;
if(m_buffer.size()>0)
{
blockOffset = byteOffset%m_buffer.size();
}
return blockOffset;
}
bool ossim::S3StreamBuffer::getBlockRangeInBytes(ossim_int64 blockIndex,
ossim_int64& startRange,
ossim_int64& endRange)const
{
bool result = false;
if(blockIndex >= 0)
{
startRange = blockIndex*m_buffer.size();
endRange = startRange + m_buffer.size()-1;
result = true;
}
return result;
}
bool ossim::S3StreamBuffer::loadBlock(ossim_int64 blockIndex)
{
bool result = false;
m_bufferPtr = 0;
m_currentPtr = 0;
GetObjectRequest getObjectRequest;
std::stringstream stringStream;
ossim_int64 startRange, endRange;
if(getBlockRangeInBytes(blockIndex, startRange, endRange))
{
stringStream << "bytes=" << startRange << "-" << endRange;
getObjectRequest.WithBucket(m_bucket.c_str())
.WithKey(m_key.c_str()).WithRange(stringStream.str().c_str());
auto getObjectOutcome = m_client.GetObject(getObjectRequest);
if(getObjectOutcome.IsSuccess())
{
// std::cout << "GOOD CALL!!!!!!!!!!!!\n";
Aws::IOStream& bodyStream = getObjectOutcome.GetResult().GetBody();
ossim_uint64 bufSize = getObjectOutcome.GetResult().GetContentLength();
// std::cout << "SIZE OF RESULT ======== " << bufSize << std::endl;
m_bufferActualDataSize = bufSize;
bodyStream.read(&m_buffer.front(), bufSize);
m_bufferPtr = &m_buffer.front();
m_currentPtr = m_bufferPtr;
if(m_currentPosition>=0)
{
ossim_int64 delta = m_currentPosition-startRange;
setg(m_bufferPtr, m_bufferPtr + delta, m_bufferPtr+m_bufferActualDataSize);
}
else
{
setg(m_bufferPtr, m_bufferPtr, m_bufferPtr + m_bufferActualDataSize);
m_currentPosition = startRange;
}
result = true;
//std::cout << "Successfully retrieved object from s3 with value: " << std::endl;
//std::cout << getObjectOutcome.GetResult().GetBody().rdbuf() << std::endl << std::endl;;
}
}
return result;
}
ossim::S3StreamBuffer* ossim::S3StreamBuffer::open (const char* connectionString,
std::ios_base::openmode m)
{
std::string temp(connectionString);
return open(temp, m);
}
ossim::S3StreamBuffer* ossim::S3StreamBuffer::open (const std::string& connectionString,
std::ios_base::openmode mode)
{
bool result = false;
ossimUrl url(connectionString);
clearAll();
m_mode = mode;
if(url.getProtocol() == "s3")
{
m_bucket = url.getIp().c_str();
m_key = url.getPath().c_str();
if(!m_bucket.empty() && !m_key.empty())
{
HeadObjectRequest headObjectRequest;
headObjectRequest.WithBucket(m_bucket.c_str())
.WithKey(m_key.c_str());
auto headObject = m_client.HeadObject(headObjectRequest);
if(headObject.IsSuccess())
{
m_fileSize = headObject.GetResult().GetContentLength();
m_opened = true;
}
}
}
if(m_opened) return this;
return 0;
}
void ossim::S3StreamBuffer::clearAll()
{
m_bucket = "";
m_key = "";
m_currentPtr = 0;
m_fileSize = 0;
m_opened = false;
}
int ossim::S3StreamBuffer::underflow()
{
if((!gptr())&&is_open())
{
if(m_currentPosition >= 0)
{
loadBlock(getBlockIndex(m_currentPosition));
}
else
{
loadBlock(0);
}
if(!gptr())
{
return EOF;
}
}
else if(!is_open())
{
return EOF;
}
else if(egptr() == gptr())
{
m_currentPosition += m_buffer.size();
if(m_currentPosition < m_fileSize)
{
if(!loadBlock(getBlockIndex(m_currentPosition)))
{
return EOF;
}
}
else
{
// std::cout << "SHOULD BE EOF RETURNED\n";
return EOF;
}
}
// std::cout << "GPTR CHARACTER ========== " << (int)(*gptr()) << std::endl;
return (int)(*gptr());
}
#if 0
int ossim::S3StreamBuffer::uflow()
{
// std::cout << "ossim::S3StreamBuffer::uflow()\n";
int result = underflow();
if(result != EOF)
{
result = (int) (*gptr());
++m_currentPosition;
pbump(1);
}
return result;
}
#endif
ossim::S3StreamBuffer::pos_type ossim::S3StreamBuffer::seekoff(off_type offset,
std::ios_base::seekdir dir,
std::ios_base::openmode mode)
{
// std::cout << "ossim::S3StreamBuffer::seekoff\n";
pos_type result = pos_type(off_type(-1));
bool withinBlock = true;
if((mode & std::ios_base::in)&&
(mode & std::ios_base::out))
{
return result;
}
switch(dir)
{
case std::ios_base::beg:
{
// if we are determing an absolute position from the beginning then
// just make sure the offset is within range of the current buffer size
//
if((offset < m_fileSize)&&
(offset >=0))
{
result = pos_type(offset);
}
break;
}
case std::ios_base::cur:
{
ossim_int64 testOffset = m_currentPosition + offset;
if((testOffset >= 0)||(testOffset<m_fileSize))
{
result = testOffset;
}
break;
}
case std::ios_base::end:
{
ossim_int64 testOffset = m_fileSize - offset;
if((testOffset >= 0)||(testOffset<m_fileSize))
{
result = testOffset;
}
break;
}
default:
{
break;
}
}
if(m_currentPosition != result)
{
adjustForSeekgPosition(result);
}
return result;
}
ossim::S3StreamBuffer::pos_type ossim::S3StreamBuffer::seekpos(pos_type pos, std::ios_base::openmode mode)
{
// std::cout << "ossim::S3StreamBuffer::seekpos\n";
pos_type result = pos_type(off_type(-1));
if(mode & std::ios_base::in)
{
if(pos >= 0)
{
if(pos < m_fileSize)
{
result = pos;
}
}
adjustForSeekgPosition(result);
}
return result;
}
void ossim::S3StreamBuffer::adjustForSeekgPosition(ossim_int64 seekPosition)
{
if(seekPosition >= 0)
{
ossim_int64 testPosition = static_cast<ossim_int64> (seekPosition);
if(m_currentPosition >= 0 )
{
ossim_int64 blockIndex1 = getBlockIndex(testPosition);
ossim_int64 blockIndex2 = getBlockIndex(m_currentPosition);
if(blockIndex1 != blockIndex2)
{
m_bufferPtr = m_currentPtr = 0;
// clear out the pointers and force a load on next read
setg(m_bufferPtr, m_bufferPtr, m_bufferPtr);
m_currentPosition = seekPosition;
}
else
{
ossim_int64 startOffset, endOffset;
ossim_int64 delta;
getBlockRangeInBytes(blockIndex1, startOffset, endOffset);
delta = testPosition-startOffset;
m_currentPosition = testPosition;
setg(m_bufferPtr, m_bufferPtr+delta, m_bufferPtr+m_buffer.size());
}
}
else
{
m_bufferPtr = m_currentPtr = 0;
m_currentPosition = seekPosition;
setg(m_bufferPtr, m_bufferPtr, m_bufferPtr);
}
}
else
{
if(m_currentPosition < 0)
{
m_bufferPtr = m_currentPtr = 0;
setg(m_bufferPtr, m_bufferPtr, m_bufferPtr);
}
}
}
std::streamsize ossim::S3StreamBuffer::xsgetn(char_type* s, std::streamsize n)
{
// std::cout << "ossim::S3StreamBuffer::xsgetn" << std::endl;
if(!is_open()) return EOF;
// unsigned long int bytesLeftToRead = egptr()-gptr();
// initialize if we need to to load the block at current position
if((egptr()==gptr())&&is_open())
{
if(m_currentPosition >= 0)
{
loadBlock(getBlockIndex(m_currentPosition));
}
else
{
loadBlock(0);
}
}
ossim_int64 bytesNeedToRead = n;
ossim_int64 bytesToRead = 0;
ossim_int64 bytesRead = 0;
ossim_int64 startOffset, endOffset;
if(m_currentPosition >= m_fileSize)
{
return EOF;
}
else if((m_currentPosition + bytesNeedToRead)>(m_fileSize))
{
bytesNeedToRead = (m_fileSize - m_currentPosition);
}
while(bytesNeedToRead > 0)
{
if(egptr()==gptr())
{
// load next block
if(m_currentPosition < m_fileSize)
{
if(!loadBlock(getBlockIndex(m_currentPosition)))
{
return bytesRead;
}
}
else
{
return bytesRead;
}
}
// get each bloc
if(m_currentPosition>=0)
{
//getBlockRangeInBytes(getBlockIndex(m_currentPosition), startOffset, endOffset);
ossim_int64 delta = (egptr()-gptr());//(endOffset - m_currentPosition)+1;
if(delta <= bytesNeedToRead)
{
std::memcpy(s+bytesRead, gptr(), delta);
m_currentPosition += delta;
setg(eback(), egptr(), egptr());
bytesRead+=delta;
bytesNeedToRead-=delta;
}
else
{
std::memcpy(s+bytesRead, gptr(), bytesNeedToRead);
m_currentPosition += bytesNeedToRead;
setg(eback(), gptr()+bytesNeedToRead, egptr());
bytesRead+=bytesNeedToRead;
bytesNeedToRead=0;
}
}
else
{
break;
}
}
return std::streamsize(bytesRead);
}
<|endoftext|> |
<commit_before>#ifndef RDB_PROTOCOL_CHANGEFEED_HPP_
#define RDB_PROTOCOL_CHANGEFEED_HPP_
#include <deque>
#include <exception>
#include <map>
#include "errors.hpp"
#include <boost/variant.hpp>
#include "concurrency/rwlock.hpp"
#include "containers/counted.hpp"
#include "containers/scoped.hpp"
#include "protocol_api.hpp"
#include "repli_timestamp.hpp"
#include "rpc/connectivity/connectivity.hpp"
#include "rpc/mailbox/typed.hpp"
#include "rpc/serialize_macros.hpp"
class auto_drainer_t;
class base_namespace_repo_t;
class mailbox_manager_t;
struct rdb_modification_report_t;
namespace ql {
class base_exc_t;
class batcher_t;
class changefeed_t;
class datum_stream_t;
class datum_t;
class env_t;
class table_t;
namespace changefeed {
struct msg_t {
struct change_t {
change_t();
explicit change_t(counted_t<const datum_t> _old_val,
counted_t<const datum_t> _new_val);
~change_t();
counted_t<const datum_t> old_val, new_val;
RDB_DECLARE_ME_SERIALIZABLE;
};
struct stop_t { RDB_DECLARE_ME_SERIALIZABLE; };
msg_t() { }
msg_t(msg_t &&msg);
msg_t(const msg_t &msg) = default;
explicit msg_t(stop_t &&op);
explicit msg_t(change_t &&op);
// Starts with STOP to avoid doing work for default initialization.
boost::variant<stop_t, change_t> op;
RDB_DECLARE_ME_SERIALIZABLE;
};
class feed_t;
struct stamped_msg_t;
// The `client_t` exists on the machine handling the changefeed query, in the
// `rdb_context_t`. When a query subscribes to the changes on a table, it
// should call `new_feed`. The `client_t` will give it back a stream of rows.
// The `client_t` does this by maintaining an internal map from table UUIDs to
// `feed_t`s. (It does this so that there is at most one `feed_t` per <table,
// client> pair, to prevent redundant cluster messages.) The actual logic for
// subscribing to a changefeed server and distributing writes to streams can be
// found in the `feed_t` class.
class client_t : public home_thread_mixin_t {
public:
typedef mailbox_addr_t<void(stamped_msg_t)> addr_t;
client_t(mailbox_manager_t *_manager);
~client_t();
// Throws QL exceptions.
counted_t<datum_stream_t> new_feed(const counted_t<table_t> &tbl, env_t *env);
void maybe_remove_feed(const uuid_u &uuid);
scoped_ptr_t<feed_t> detach_feed(const uuid_u &uuid);
private:
friend class sub_t;
mailbox_manager_t *manager;
std::map<uuid_u, scoped_ptr_t<feed_t> > feeds;
// This lock manages access to the `feeds` map. The `feeds` map needs to be
// read whenever `new_feed` is called, and needs to be written to whenever
// `new_feed` is called with a table not already in the `feeds` map, or
// whenever `maybe_remove_feed` or `detach_feed` is called.
rwlock_t feeds_lock;
auto_drainer_t drainer;
};
// There is one `server_t` per `store_t`, and it is used to send changes that
// occur on that `store_t` to any subscribed `feed_t`s contained in a
// `client_t`.
class server_t {
public:
typedef mailbox_addr_t<void(client_t::addr_t)> addr_t;
server_t(mailbox_manager_t *_manager);
void add_client(const client_t::addr_t &addr);
void send_all(msg_t msg);
addr_t get_stop_addr();
uint64_t get_stamp(const client_t::addr_t &addr);
uuid_u get_uuid();
private:
void stop_mailbox_cb(client_t::addr_t addr);
void add_client_cb(signal_t *stopped, client_t::addr_t addr);
// The UUID of the server, used so that `feed_t`s can order changefeed
// messages on a per-server basis (and drop changefeed messages from before
// their own creation timestamp on a per-server basis).
uuid_u uuid;
mailbox_manager_t *manager;
struct client_info_t {
scoped_ptr_t<cond_t> cond;
uint64_t stamp;
};
std::map<client_t::addr_t, client_info_t> clients;
rwlock_t clients_lock;
mailbox_t<void(client_t::addr_t)> stop_mailbox;
auto_drainer_t drainer;
};
} // namespace changefeed
} // namespace ql
#endif // RDB_PROTOCOL_CHANGEFEED_HPP_
<commit_msg>Made some member variables const.<commit_after>#ifndef RDB_PROTOCOL_CHANGEFEED_HPP_
#define RDB_PROTOCOL_CHANGEFEED_HPP_
#include <deque>
#include <exception>
#include <map>
#include "errors.hpp"
#include <boost/variant.hpp>
#include "concurrency/rwlock.hpp"
#include "containers/counted.hpp"
#include "containers/scoped.hpp"
#include "protocol_api.hpp"
#include "repli_timestamp.hpp"
#include "rpc/connectivity/connectivity.hpp"
#include "rpc/mailbox/typed.hpp"
#include "rpc/serialize_macros.hpp"
class auto_drainer_t;
class base_namespace_repo_t;
class mailbox_manager_t;
struct rdb_modification_report_t;
namespace ql {
class base_exc_t;
class batcher_t;
class changefeed_t;
class datum_stream_t;
class datum_t;
class env_t;
class table_t;
namespace changefeed {
struct msg_t {
struct change_t {
change_t();
explicit change_t(counted_t<const datum_t> _old_val,
counted_t<const datum_t> _new_val);
~change_t();
counted_t<const datum_t> old_val, new_val;
RDB_DECLARE_ME_SERIALIZABLE;
};
struct stop_t { RDB_DECLARE_ME_SERIALIZABLE; };
msg_t() { }
msg_t(msg_t &&msg);
msg_t(const msg_t &msg) = default;
explicit msg_t(stop_t &&op);
explicit msg_t(change_t &&op);
// Starts with STOP to avoid doing work for default initialization.
boost::variant<stop_t, change_t> op;
RDB_DECLARE_ME_SERIALIZABLE;
};
class feed_t;
struct stamped_msg_t;
// The `client_t` exists on the machine handling the changefeed query, in the
// `rdb_context_t`. When a query subscribes to the changes on a table, it
// should call `new_feed`. The `client_t` will give it back a stream of rows.
// The `client_t` does this by maintaining an internal map from table UUIDs to
// `feed_t`s. (It does this so that there is at most one `feed_t` per <table,
// client> pair, to prevent redundant cluster messages.) The actual logic for
// subscribing to a changefeed server and distributing writes to streams can be
// found in the `feed_t` class.
class client_t : public home_thread_mixin_t {
public:
typedef mailbox_addr_t<void(stamped_msg_t)> addr_t;
client_t(mailbox_manager_t *_manager);
~client_t();
// Throws QL exceptions.
counted_t<datum_stream_t> new_feed(const counted_t<table_t> &tbl, env_t *env);
void maybe_remove_feed(const uuid_u &uuid);
scoped_ptr_t<feed_t> detach_feed(const uuid_u &uuid);
private:
friend class sub_t;
mailbox_manager_t *const manager;
std::map<uuid_u, scoped_ptr_t<feed_t> > feeds;
// This lock manages access to the `feeds` map. The `feeds` map needs to be
// read whenever `new_feed` is called, and needs to be written to whenever
// `new_feed` is called with a table not already in the `feeds` map, or
// whenever `maybe_remove_feed` or `detach_feed` is called.
rwlock_t feeds_lock;
auto_drainer_t drainer;
};
// There is one `server_t` per `store_t`, and it is used to send changes that
// occur on that `store_t` to any subscribed `feed_t`s contained in a
// `client_t`.
class server_t {
public:
typedef mailbox_addr_t<void(client_t::addr_t)> addr_t;
server_t(mailbox_manager_t *_manager);
void add_client(const client_t::addr_t &addr);
void send_all(msg_t msg);
addr_t get_stop_addr();
uint64_t get_stamp(const client_t::addr_t &addr);
uuid_u get_uuid();
private:
void stop_mailbox_cb(client_t::addr_t addr);
void add_client_cb(signal_t *stopped, client_t::addr_t addr);
// The UUID of the server, used so that `feed_t`s can order changefeed
// messages on a per-server basis (and drop changefeed messages from before
// their own creation timestamp on a per-server basis).
const uuid_u uuid;
mailbox_manager_t *const manager;
struct client_info_t {
scoped_ptr_t<cond_t> cond;
uint64_t stamp;
};
std::map<client_t::addr_t, client_info_t> clients;
rwlock_t clients_lock;
mailbox_t<void(client_t::addr_t)> stop_mailbox;
auto_drainer_t drainer;
};
} // namespace changefeed
} // namespace ql
#endif // RDB_PROTOCOL_CHANGEFEED_HPP_
<|endoftext|> |
<commit_before>/**************************************************************************
* Copyright(c) 1998-1999, ALICE Experiment at CERN, All rights reserved. *
* *
* Author: The ALICE Off-line Project. *
* Contributors are mentioned in the code where appropriate. *
* *
* Permission to use, copy, modify and distribute this software and its *
* documentation strictly for non-commercial purposes is hereby granted *
* without fee, provided that the above copyright notice appears in all *
* copies and that both the copyright notice and this permission notice *
* appear in the supporting documentation. The authors make no claims *
* about the suitability of this software for any purpose. It is *
* provided "as is" without express or implied warranty. *
**************************************************************************/
/*
$Log$
Revision 1.12 2002/10/14 14:55:33 hristov
Merging the VirtualMC branch to the main development branch (HEAD)
Revision 1.10.6.1 2002/08/28 15:06:49 alibrary
Updating to v3-09-01
Revision 1.11 2002/08/18 20:20:48 hristov
InitGui removed (J.Chudoba)
Revision 1.10 2002/02/18 14:26:14 hristov
#include <AliConfig.h> removed
Revision 1.9 2002/01/09 17:05:03 morsch
Increase memory allocated for ZEBRA.
Revision 1.8 2001/10/04 15:32:36 hristov
Instantiation of AliConfig removed
Revision 1.7 2001/05/22 11:39:48 buncic
Restored proper name for top level AliRoot folder.
Revision 1.6 2001/05/21 17:22:50 buncic
Fixed problem with missing AliConfig while reading galice.root
Revision 1.5 2001/05/16 14:57:07 alibrary
New files for folders and Stack
Revision 1.4 2000/12/20 08:39:37 fca
Support for Cerenkov and process list in Virtual MC
Revision 1.3 1999/09/29 09:24:07 fca
Introduction of the Copyright and cvs Log
*/
//////////////////////////////////////////////////////////////////////////
// //
// aliroot //
// //
// Main program used to create aliroot application. //
// //
// //
// To be able to communicate between the FORTRAN code of GEANT and the //
// ROOT data structure, a number of interface routines have been //
// developed. //
//Begin_Html
/*
<img src="picts/newg.gif">
*/
//End_Html
//////////////////////////////////////////////////////////////////////////
//Standard Root includes
#include <TROOT.h>
#include <TRint.h>
#include <TFile.h>
#include <AliRun.h>
#if defined __linux
//On linux Fortran wants this, so we give to it!
int xargv=0;
int xargc=0;
#endif
#if defined WIN32
extern "C" int __fastflag=0;
extern "C" int _pctype=0;
extern "C" int __mb_cur_max=0;
#endif
//int gcbank_[4000000];
//_____________________________________________________________________________
int main(int argc, char **argv)
{
//
// gAlice main program.
// It creates the main Geant3 and AliRun objects.
//
// The Hits are written out after each track in a ROOT Tree structure TreeH,
// of the file galice.root. There is one such tree per event. The kinematics
// of all the particles that produce hits, together with their genealogy up
// to the primary tracks is stared in the galice.root file in an other tree
// TreeK of which exists one per event. Finally the information of the events
// in the run is stored in the same file in the tree TreeE, containing the
// run and event number, the number of vertices, tracks and primary tracks
// in the event.
// Create new configuration
new AliRun("gAlice","The ALICE Off-line Simulation Framework");
// Start interactive geant
TRint *theApp = new TRint("aliroot", &argc, argv, 0, 0);
// --- Start the event loop ---
theApp->Run();
return(0);
}
<commit_msg>Small correction to enable std input<commit_after>/**************************************************************************
* Copyright(c) 1998-1999, ALICE Experiment at CERN, All rights reserved. *
* *
* Author: The ALICE Off-line Project. *
* Contributors are mentioned in the code where appropriate. *
* *
* Permission to use, copy, modify and distribute this software and its *
* documentation strictly for non-commercial purposes is hereby granted *
* without fee, provided that the above copyright notice appears in all *
* copies and that both the copyright notice and this permission notice *
* appear in the supporting documentation. The authors make no claims *
* about the suitability of this software for any purpose. It is *
* provided "as is" without express or implied warranty. *
**************************************************************************/
/*
$Log$
Revision 1.13 2002/12/03 09:03:06 hristov
Changes needed on Itanium (F.Carminati)
Revision 1.12 2002/10/14 14:55:33 hristov
Merging the VirtualMC branch to the main development branch (HEAD)
Revision 1.10.6.1 2002/08/28 15:06:49 alibrary
Updating to v3-09-01
Revision 1.11 2002/08/18 20:20:48 hristov
InitGui removed (J.Chudoba)
Revision 1.10 2002/02/18 14:26:14 hristov
#include <AliConfig.h> removed
Revision 1.9 2002/01/09 17:05:03 morsch
Increase memory allocated for ZEBRA.
Revision 1.8 2001/10/04 15:32:36 hristov
Instantiation of AliConfig removed
Revision 1.7 2001/05/22 11:39:48 buncic
Restored proper name for top level AliRoot folder.
Revision 1.6 2001/05/21 17:22:50 buncic
Fixed problem with missing AliConfig while reading galice.root
Revision 1.5 2001/05/16 14:57:07 alibrary
New files for folders and Stack
Revision 1.4 2000/12/20 08:39:37 fca
Support for Cerenkov and process list in Virtual MC
Revision 1.3 1999/09/29 09:24:07 fca
Introduction of the Copyright and cvs Log
*/
//////////////////////////////////////////////////////////////////////////
// //
// aliroot //
// //
// Main program used to create aliroot application. //
// //
// //
// To be able to communicate between the FORTRAN code of GEANT and the //
// ROOT data structure, a number of interface routines have been //
// developed. //
//Begin_Html
/*
<img src="picts/newg.gif">
*/
//End_Html
//////////////////////////////////////////////////////////////////////////
//Standard Root includes
#include <TROOT.h>
#include <TRint.h>
#include <TFile.h>
#include <AliRun.h>
#if defined __linux
//On linux Fortran wants this, so we give to it!
int xargv=0;
int xargc=0;
#endif
#if defined WIN32
extern "C" int __fastflag=0;
extern "C" int _pctype=0;
extern "C" int __mb_cur_max=0;
#endif
//_____________________________________________________________________________
int main(int argc, char **argv)
{
//
// gAlice main program.
// It creates the main Geant3 and AliRun objects.
//
// The Hits are written out after each track in a ROOT Tree structure TreeH,
// of the file galice.root. There is one such tree per event. The kinematics
// of all the particles that produce hits, together with their genealogy up
// to the primary tracks is stared in the galice.root file in an other tree
// TreeK of which exists one per event. Finally the information of the events
// in the run is stored in the same file in the tree TreeE, containing the
// run and event number, the number of vertices, tracks and primary tracks
// in the event.
// Create new configuration
new AliRun("gAlice","The ALICE Off-line Simulation Framework");
// Start interactive geant
TRint *theApp = new TRint("aliroot", &argc, argv);
// --- Start the event loop ---
theApp->Run();
return(0);
}
<|endoftext|> |
<commit_before>#include "RTC.h"
#include <sys/time.h>
#include <ctime>
#include <csignal>
#include <cerrno>
#include <cstring>
using namespace std;
namespace Simulator
{
/* the following implements a very crude semaphore.
We want that several RTC clocks can update their time
when a tick event is received. They could update more
often but we want to limit syscall usage.
To do this we maintain a count of the RTC clocks
that have acknowledged the tickevent in "timerTicked".
The count is reset to the number of RTC clocks
every time SIGALRM ticks; each RTC clock's event
handler then decreases it.
*/
static volatile unsigned clockSemaphore = 0;
static unsigned clockListeners = 0;
static clock_delay_t clockResolution = 0;
static volatile precise_time_t currentTime = 0;
static void set_time(void)
{
struct timeval tv;
int gtod_status = gettimeofday(&tv, NULL);
assert(gtod_status == 0);
precise_time_t newTime = tv.tv_usec + tv.tv_sec * 1000000;
currentTime = newTime;
}
static void alarm_handler(int)
{
clockSemaphore = clockListeners;
set_time();
}
static void setup_clocks(Config& config)
{
static bool initialized = false;
if (!initialized)
{
set_time(); // need to have a non-zero value before the RTC starts
// update delay in microseconds
clockResolution = config.getValue<clock_delay_t>("RTCMeatSpaceUpdateInterval");
if (SIG_ERR == signal(SIGALRM, alarm_handler))
{
throw exceptf<>("Cannot set alarm: %s", strerror(errno));
};
struct itimerval it;
it.it_interval.tv_sec = clockResolution / 1000000;
it.it_interval.tv_usec = clockResolution % 1000000;
it.it_value = it.it_interval;
if (-1 == setitimer(ITIMER_REAL, &it, NULL))
{
throw exceptf<>("Cannot set timer: %s", strerror(errno));
};
initialized = true;
}
}
const std::string& RTC::RTCInterface::GetIODeviceName() const
{
return GetName();
}
RTC::RTCInterface::RTCInterface(const std::string& name, RTC& parent, IIOBus& iobus, IODeviceID devid)
: Object(name, parent),
m_devid(devid),
m_iobus(iobus),
m_doNotify("f_interruptTriggered", *this, iobus.GetClock(), false),
m_interruptNumber(0),
InitProcess(p_notifyTime, DoNotifyTime)
{
iobus.RegisterClient(devid, *this);
m_doNotify.Sensitive(p_notifyTime);
}
void RTC::RTCInterface::Initialize()
{
p_notifyTime.SetStorageTraces(m_iobus.GetInterruptRequestTraces());
}
RTC::RTC(const string& name, Object& parent, Clock& rtcclock, IIOBus& iobus, IODeviceID devid, Config& config)
: Object(name, parent),
m_timerTicked(false),
m_timeOfLastInterrupt(0),
m_triggerDelay(0),
m_deliverAllEvents(true),
m_enableCheck("f_checkTime", *this, rtcclock, false),
m_businterface("if", *this, iobus, devid),
InitProcess(p_checkTime, DoCheckTime)
{
setup_clocks(config);
m_timeOfLastInterrupt = currentTime;
++clockListeners;
m_enableCheck.Sensitive(p_checkTime);
p_checkTime.SetStorageTraces(opt(m_businterface.m_doNotify));
}
Result RTC::RTCInterface::DoNotifyTime()
{
if (!m_iobus.SendInterruptRequest(m_devid, m_interruptNumber))
{
DeadlockWrite("Cannot send timer interrupt to I/O bus");
return FAILED;
}
m_doNotify.Clear();
return SUCCESS;
}
Result RTC::DoCheckTime()
{
if (!m_timerTicked && (clockSemaphore != 0))
{
m_timerTicked = true;
--clockSemaphore;
}
if (m_timerTicked)
{
// The clock is configured to deliver interrupts. Check
// for this.
if (m_timeOfLastInterrupt + m_triggerDelay <= currentTime)
{
// Time for an interrupt.
m_businterface.m_doNotify.Set();
COMMIT {
if (m_deliverAllEvents)
{
m_timeOfLastInterrupt += m_triggerDelay;
}
else
{
m_timeOfLastInterrupt = currentTime;
}
}
}
COMMIT {
m_timerTicked = false;
}
}
return SUCCESS;
}
void RTC::RTCInterface::GetDeviceIdentity(IODeviceIdentification& id) const
{
if (!DeviceDatabase::GetDatabase().FindDeviceByName("MGSim", "RTC", id))
{
throw InvalidArgumentException(*this, "Device identity not registered");
}
}
static uint32_t pack_time(const struct tm* tm, bool otherbits)
{
if (!otherbits)
{
// bits 0-5: seconds (0-59)
// bits 6-11: minutes (0-59)
// bits 12-16: hours (0-23)
// bits 17-21: day in month (0-30)
// bits 22-25: month in year (0-11)
// bits 26-31: year from 1970
return (uint32_t)tm->tm_sec
| ((uint32_t)tm->tm_min << 6)
| ((uint32_t)tm->tm_hour << 12)
| ((uint32_t)tm->tm_mday << 17)
| ((uint32_t)tm->tm_mon << 22)
| ((uint32_t)(tm->tm_year + 70) << 26);
}
else
{
// bits 0-3: day of week (sunday = 0)
// bits 4-12: day of year (0-365)
// bit 13: summer time in effect
// bits 14-31: offset from UTC in seconds
return (uint32_t)tm->tm_wday
| ((uint32_t)tm->tm_yday << 4)
| ((uint32_t)!!tm->tm_isdst << 13)
#ifdef HAVE_STRUCT_TM_TM_GMTOFF
| ((uint32_t)tm->tm_gmtoff << 14)
#endif
;
}
}
bool RTC::RTCInterface::OnWriteRequestReceived(IODeviceID /*from*/, MemAddr address, const IOData& data)
{
unsigned word = address / 4;
if (address % 4 != 0 || data.size != 4)
{
throw exceptf<>(*this, "Invalid unaligned RTC write: %#016llx (%u)", (unsigned long long)address, (unsigned)data.size);
}
if (word == 0 || word > 3)
{
throw exceptf<>(*this, "Invalid write to RTC word: %u", word);
}
Integer value = UnserializeRegister(RT_INTEGER, data.data, data.size);
RTC& rtc = GetRTC();
COMMIT{
switch(word)
{
case 1:
{
if (value != 0)
{
rtc.m_timeOfLastInterrupt = currentTime;
rtc.m_enableCheck.Set();
}
else
{
m_doNotify.Clear(); // cancel sending the current interrupt if currently ongoing.
rtc.m_enableCheck.Clear();
}
rtc.m_triggerDelay = value;
break;
}
case 2: m_interruptNumber = value; break;
case 3: rtc.m_deliverAllEvents = value; break;
}
}
return true;
}
bool RTC::RTCInterface::OnReadRequestReceived(IODeviceID from, MemAddr address, MemSize size)
{
// the clock uses 32-bit control words
// word 0: resolution (microseconds)
// word 1: interrupt delay (in microseconds, set to 0 to disable interrupts)
// word 2: interrupt number to generate
// word 3: whether to deliver all events
// word 4: microseconds part of current time since jan 1, 1970
// word 5: seconds part of current time since jan 1, 1970
// word 6: packed UTC time:
// word 7: packed UTC time (more):
// word 8,9: packed local time (same format as UTC)
unsigned word = address / 4;
uint32_t value = 0;
if (address % 4 != 0 || size != 4)
{
throw exceptf<>(*this, "Invalid unaligned RTC read: %#016llx (%u)", (unsigned long long)address, (unsigned)size);
}
if (word > 9)
{
throw exceptf<>(*this, "Read from invalid RTC word: %u", word);
}
RTC& rtc = GetRTC();
COMMIT{
switch(word)
{
case 0: value = clockResolution; break;
case 1: value = rtc.m_triggerDelay; break;
case 2: value = m_interruptNumber; break;
case 3: value = (int)rtc.m_deliverAllEvents; break;
case 4: value = currentTime % 1000000; break;
case 5: value = currentTime / 1000000; break;
case 6: case 7:
{
time_t c = time(0);
struct tm * tm = gmtime(&c);
value = pack_time(tm, word - 6);
break;
}
case 8: case 9:
{
time_t c = time(0);
struct tm * tm = localtime(&c);
value = pack_time(tm, word - 8);
break;
}
}
}
IOData iodata;
SerializeRegister(RT_INTEGER, value, iodata.data, 4);
iodata.size = 4;
if (!m_iobus.SendReadResponse(m_devid, from, address, iodata))
{
DeadlockWrite("Cannot send RTC read response to I/O bus");
return false;
}
return true;
}
}
<commit_msg>Prefix global variables in RTC.cpp with g_ for clarity.<commit_after>#include "RTC.h"
#include <sys/time.h>
#include <ctime>
#include <csignal>
#include <cerrno>
#include <cstring>
using namespace std;
namespace Simulator
{
/* the following implements a very crude semaphore.
We want that several RTC clocks can update their time
when a tick event is received. They could update more
often but we want to limit syscall usage.
To do this we maintain a count of the RTC clocks
that have acknowledged the tickevent in "timerTicked".
The count is reset to the number of RTC clocks
every time SIGALRM ticks; each RTC clock's event
handler then decreases it.
*/
static volatile unsigned g_clockSemaphore = 0;
static unsigned g_clockListeners = 0;
static clock_delay_t g_clockResolution = 0;
static volatile precise_time_t g_currentTime = 0;
static void set_time(void)
{
struct timeval tv;
int gtod_status = gettimeofday(&tv, NULL);
assert(gtod_status == 0);
precise_time_t newTime = tv.tv_usec + tv.tv_sec * 1000000;
g_currentTime = newTime;
}
static void alarm_handler(int)
{
g_clockSemaphore = g_clockListeners;
set_time();
}
static void setup_clocks(Config& config)
{
static bool initialized = false;
if (!initialized)
{
set_time(); // need to have a non-zero value before the RTC starts
g_clockResolution = config.getValue<clock_delay_t>("RTCMeatSpaceUpdateInterval");
if (SIG_ERR == signal(SIGALRM, alarm_handler))
{
throw exceptf<>("Cannot set alarm: %s", strerror(errno));
};
struct itimerval it;
it.it_interval.tv_sec = g_clockResolution / 1000000;
it.it_interval.tv_usec = g_clockResolution % 1000000;
it.it_value = it.it_interval;
if (-1 == setitimer(ITIMER_REAL, &it, NULL))
{
throw exceptf<>("Cannot set timer: %s", strerror(errno));
};
initialized = true;
}
}
const std::string& RTC::RTCInterface::GetIODeviceName() const
{
return GetName();
}
RTC::RTCInterface::RTCInterface(const std::string& name, RTC& parent, IIOBus& iobus, IODeviceID devid)
: Object(name, parent),
m_devid(devid),
m_iobus(iobus),
m_doNotify("f_interruptTriggered", *this, iobus.GetClock(), false),
m_interruptNumber(0),
InitProcess(p_notifyTime, DoNotifyTime)
{
iobus.RegisterClient(devid, *this);
m_doNotify.Sensitive(p_notifyTime);
}
void RTC::RTCInterface::Initialize()
{
p_notifyTime.SetStorageTraces(m_iobus.GetInterruptRequestTraces());
}
RTC::RTC(const string& name, Object& parent, Clock& rtcclock, IIOBus& iobus, IODeviceID devid, Config& config)
: Object(name, parent),
m_timerTicked(false),
m_timeOfLastInterrupt(0),
m_triggerDelay(0),
m_deliverAllEvents(true),
m_enableCheck("f_checkTime", *this, rtcclock, false),
m_businterface("if", *this, iobus, devid),
InitProcess(p_checkTime, DoCheckTime)
{
setup_clocks(config);
m_timeOfLastInterrupt = g_currentTime;
++g_clockListeners;
m_enableCheck.Sensitive(p_checkTime);
p_checkTime.SetStorageTraces(opt(m_businterface.m_doNotify));
}
Result RTC::RTCInterface::DoNotifyTime()
{
if (!m_iobus.SendInterruptRequest(m_devid, m_interruptNumber))
{
DeadlockWrite("Cannot send timer interrupt to I/O bus");
return FAILED;
}
m_doNotify.Clear();
return SUCCESS;
}
Result RTC::DoCheckTime()
{
if (!m_timerTicked && (g_clockSemaphore != 0))
{
m_timerTicked = true;
--g_clockSemaphore;
}
if (m_timerTicked)
{
// The clock is configured to deliver interrupts. Check
// for this.
if (m_timeOfLastInterrupt + m_triggerDelay <= g_currentTime)
{
// Time for an interrupt.
m_businterface.m_doNotify.Set();
COMMIT {
if (m_deliverAllEvents)
{
m_timeOfLastInterrupt += m_triggerDelay;
}
else
{
m_timeOfLastInterrupt = g_currentTime;
}
}
}
COMMIT {
m_timerTicked = false;
}
}
return SUCCESS;
}
void RTC::RTCInterface::GetDeviceIdentity(IODeviceIdentification& id) const
{
if (!DeviceDatabase::GetDatabase().FindDeviceByName("MGSim", "RTC", id))
{
throw InvalidArgumentException(*this, "Device identity not registered");
}
}
static uint32_t pack_time(const struct tm* tm, bool otherbits)
{
if (!otherbits)
{
// bits 0-5: seconds (0-59)
// bits 6-11: minutes (0-59)
// bits 12-16: hours (0-23)
// bits 17-21: day in month (0-30)
// bits 22-25: month in year (0-11)
// bits 26-31: year from 1970
return (uint32_t)tm->tm_sec
| ((uint32_t)tm->tm_min << 6)
| ((uint32_t)tm->tm_hour << 12)
| ((uint32_t)tm->tm_mday << 17)
| ((uint32_t)tm->tm_mon << 22)
| ((uint32_t)(tm->tm_year + 70) << 26);
}
else
{
// bits 0-3: day of week (sunday = 0)
// bits 4-12: day of year (0-365)
// bit 13: summer time in effect
// bits 14-31: offset from UTC in seconds
return (uint32_t)tm->tm_wday
| ((uint32_t)tm->tm_yday << 4)
| ((uint32_t)!!tm->tm_isdst << 13)
#ifdef HAVE_STRUCT_TM_TM_GMTOFF
| ((uint32_t)tm->tm_gmtoff << 14)
#endif
;
}
}
bool RTC::RTCInterface::OnWriteRequestReceived(IODeviceID /*from*/, MemAddr address, const IOData& data)
{
unsigned word = address / 4;
if (address % 4 != 0 || data.size != 4)
{
throw exceptf<>(*this, "Invalid unaligned RTC write: %#016llx (%u)", (unsigned long long)address, (unsigned)data.size);
}
if (word == 0 || word > 3)
{
throw exceptf<>(*this, "Invalid write to RTC word: %u", word);
}
Integer value = UnserializeRegister(RT_INTEGER, data.data, data.size);
RTC& rtc = GetRTC();
COMMIT{
switch(word)
{
case 1:
{
if (value != 0)
{
rtc.m_timeOfLastInterrupt = g_currentTime;
rtc.m_enableCheck.Set();
}
else
{
m_doNotify.Clear(); // cancel sending the current interrupt if currently ongoing.
rtc.m_enableCheck.Clear();
}
rtc.m_triggerDelay = value;
break;
}
case 2: m_interruptNumber = value; break;
case 3: rtc.m_deliverAllEvents = value; break;
}
}
return true;
}
bool RTC::RTCInterface::OnReadRequestReceived(IODeviceID from, MemAddr address, MemSize size)
{
// the clock uses 32-bit control words
// word 0: resolution (microseconds)
// word 1: interrupt delay (in microseconds, set to 0 to disable interrupts)
// word 2: interrupt number to generate
// word 3: whether to deliver all events
// word 4: microseconds part of current time since jan 1, 1970
// word 5: seconds part of current time since jan 1, 1970
// word 6: packed UTC time:
// word 7: packed UTC time (more):
// word 8,9: packed local time (same format as UTC)
unsigned word = address / 4;
uint32_t value = 0;
if (address % 4 != 0 || size != 4)
{
throw exceptf<>(*this, "Invalid unaligned RTC read: %#016llx (%u)", (unsigned long long)address, (unsigned)size);
}
if (word > 9)
{
throw exceptf<>(*this, "Read from invalid RTC word: %u", word);
}
RTC& rtc = GetRTC();
COMMIT{
switch(word)
{
case 0: value = g_clockResolution; break;
case 1: value = rtc.m_triggerDelay; break;
case 2: value = m_interruptNumber; break;
case 3: value = (int)rtc.m_deliverAllEvents; break;
case 4: value = g_currentTime % 1000000; break;
case 5: value = g_currentTime / 1000000; break;
case 6: case 7:
{
time_t c = time(0);
struct tm * tm = gmtime(&c);
value = pack_time(tm, word - 6);
break;
}
case 8: case 9:
{
time_t c = time(0);
struct tm * tm = localtime(&c);
value = pack_time(tm, word - 8);
break;
}
}
}
IOData iodata;
SerializeRegister(RT_INTEGER, value, iodata.data, 4);
iodata.size = 4;
if (!m_iobus.SendReadResponse(m_devid, from, address, iodata))
{
DeadlockWrite("Cannot send RTC read response to I/O bus");
return false;
}
return true;
}
}
<|endoftext|> |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.