text
stringlengths 54
60.6k
|
|---|
<commit_before>/* -*- mode: C++; c-basic-offset: 4; indent-tabs-mode: nil -*- */
#include <algorithm>
#include <cassert>
#include <cstdlib>
#include <memory>
#include "buffer.hpp"
#include "malloc_utils.hpp"
namespace ftcxx {
const size_t Buffer::INITIAL_CAPACITY = 1<<10;
const size_t Buffer::MAXIMUM_CAPACITY = 1<<18;
const double Buffer::FULLNESS_RATIO = 0.9;
void Buffer::init() {
_buf.reset(std::malloc(_capacity));
}
/**
* Implements our growth strategy. Currently we double until we get
* up to 4kB so that we can quickly reach the point where jemalloc can
* help us resize in-place, but after that point we grow by a factor
* of 1.5x.
*
* FBVector doubles once it is bigger than 128kB, but I don't think we
* actually want to because that's about when we want to stop growing.
*/
size_t Buffer::next_alloc_size(size_t sz) {
if (sz < malloc_utils::jemallocMinInPlaceExpandable) {
return sz * 2;
}
#if 0
else if (sz > (128<<10)) {
return sz * 2;
}
#endif
else {
return (sz * 3 + 1) / 2;
}
}
void Buffer::grow(size_t sz) {
size_t new_capacity = _capacity;
while (new_capacity < _end + sz) {
new_capacity = next_alloc_size(new_capacity);
}
new_capacity = malloc_utils::goodMallocSize(new_capacity);
assert(new_capacity >= _capacity); // overflow?
if (new_capacity > _capacity) {
// This section isn't exception-safe, but smartRealloc already
// isn't. The only thing we can throw in here is
// std::bad_alloc, in which case we're kind of screwed anyway.
_buf.reset(malloc_utils::smartRealloc(_buf.release(), new_capacity, 0, 0, _capacity));
}
}
} // namespace ftcxx
<commit_msg>moved minor calculation<commit_after>/* -*- mode: C++; c-basic-offset: 4; indent-tabs-mode: nil -*- */
#include <algorithm>
#include <cassert>
#include <cstdlib>
#include <memory>
#include "buffer.hpp"
#include "malloc_utils.hpp"
namespace ftcxx {
const size_t Buffer::INITIAL_CAPACITY = 1<<10;
const size_t Buffer::MAXIMUM_CAPACITY = 1<<18;
const double Buffer::FULLNESS_RATIO = 0.9;
void Buffer::init() {
_buf.reset(std::malloc(_capacity));
}
/**
* Implements our growth strategy. Currently we double until we get
* up to 4kB so that we can quickly reach the point where jemalloc can
* help us resize in-place, but after that point we grow by a factor
* of 1.5x.
*
* FBVector doubles once it is bigger than 128kB, but I don't think we
* actually want to because that's about when we want to stop growing.
*/
size_t Buffer::next_alloc_size(size_t sz) {
if (sz < malloc_utils::jemallocMinInPlaceExpandable) {
return sz * 2;
}
#if 0
else if (sz > (128<<10)) {
return sz * 2;
}
#endif
else {
return (sz * 3 + 1) / 2;
}
}
void Buffer::grow(size_t sz) {
size_t new_capacity = _capacity;
while (new_capacity < _end + sz) {
new_capacity = next_alloc_size(new_capacity);
}
assert(new_capacity >= _capacity); // overflow?
if (new_capacity > _capacity) {
// This section isn't exception-safe, but smartRealloc already
// isn't. The only thing we can throw in here is
// std::bad_alloc, in which case we're kind of screwed anyway.
new_capacity = malloc_utils::goodMallocSize(new_capacity);
_buf.reset(malloc_utils::smartRealloc(_buf.release(), new_capacity, 0, 0, _capacity));
}
}
} // namespace ftcxx
<|endoftext|>
|
<commit_before>#include <iostream>
#include <string>
#include <stack>
#include <map>
#include <assert.h>
#include <fstream>
// From git file
#include "include/yaml.h"
#include "yaml-cpp/yaml.h"
// ---------------------------------------------------------------------------------
// ------------------------------- libyaml test code -------------------------------
// ---------------------------------------------------------------------------------
bool positionAnalysis(std::string& add_to_me, char reference_character, bool map_mode)
{
if (reference_character == 'M')
{
if (map_mode)
{
add_to_me += "K: ";
}
else
{
add_to_me += "V: ";
}
return !map_mode;
}
else if (reference_character == 'S')
{
add_to_me += "L: ";
}
else
{
add_to_me += "U: ";
}
return map_mode;
}
void addToMap(std::map<std::string, std::string> & anchor_map,
std::string& anchor, std::string& anchor_data)
{
if (&anchor != nullptr)
{
if (anchor_map.count(anchor))
{
anchor_map[anchor] = anchor_data;
}
else
{
anchor_map.insert({anchor, anchor_data});
}
}
}
void addInfoToDataStack(std::stack<std::string>& anchor_data,
std::string info)
{
if (!anchor_data.empty())
{
std::string& temp = anchor_data.top();
temp += info;
}
else
{
anchor_data.push(info);
}
}
std::string parseLibyaml(std::string name_of_file)
{
FILE *input;
yaml_parser_t parser;
yaml_event_t event;
std::string libyaml_final_output = "";
std::string relevant_saving_info = "";
bool interest_in_saving = false;
int subtract_count = 2;
std::map<std::string, std::string> anchor_map;
std::stack<std::string> anchor_save_stack;
std::stack<std::string> anchor_data_save_stack;
std::stack<char> mode_stack;
mode_stack.push(' ');
std::stack<bool> map_mode_stack;
bool map_mode = true;
input = fopen(name_of_file.c_str(), "rb");
assert(input);
if (!yaml_parser_initialize(&parser))
{
return "ERROR: Could not initialize the parser object\n";
}
yaml_parser_set_input_file(&parser, input);
while (true)
{
std::string local_event_output = "";
yaml_event_type_t type;
if (!yaml_parser_parse(&parser, &event))
{
if ( parser.problem_mark.line || parser.problem_mark.column )
{
fprintf(stderr, "Parse error: %s\nLine: %lu Column: %lu\n",
parser.problem,
(unsigned long)parser.problem_mark.line + 1,
(unsigned long)parser.problem_mark.column + 1);
}
else {
fprintf(stderr, "Parse error: %s\n", parser.problem);
}
return "ERROR: Bad parsing";
}
type = event.type;
switch (type)
{
case YAML_STREAM_END_EVENT:
if (!anchor_save_stack.empty() && interest_in_saving)
{
addToMap(anchor_map, anchor_save_stack.top(), anchor_data_save_stack.top());
anchor_save_stack.pop();
anchor_data_save_stack.pop();
interest_in_saving = false;
subtract_count = 2;
}
break;
case YAML_DOCUMENT_END_EVENT:
if (!anchor_save_stack.empty() && interest_in_saving)
{
addToMap(anchor_map, anchor_save_stack.top(), anchor_data_save_stack.top());
anchor_save_stack.pop();
anchor_data_save_stack.pop();
interest_in_saving = false;
subtract_count = 2;
}
break;
case YAML_MAPPING_START_EVENT:
if (!mode_stack.empty())
{
positionAnalysis(local_event_output, mode_stack.top(), map_mode);
}
if (mode_stack.top()=='M')
{
map_mode_stack.push(!map_mode);
}
mode_stack.push('M');
map_mode = true;
if (event.data.mapping_start.anchor)
{
anchor_save_stack.push(((char*)event.data.mapping_start.anchor));
interest_in_saving = true;
subtract_count = 2;
}
else
{
local_event_output += std::string((char*)event.data.scalar.value, event.data.scalar.length);
}
if (event.data.mapping_start.tag)
{
std::string temp_translator = ((char*)event.data.mapping_start.tag);
local_event_output += temp_translator + " \n";
}
else
{
local_event_output += "\n";
}
break;
case YAML_MAPPING_END_EVENT:
mode_stack.pop();
if(mode_stack.top()=='M')
{
map_mode = map_mode_stack.top();
map_mode_stack.pop();
}
if (!anchor_save_stack.empty() && interest_in_saving)
{
addToMap(anchor_map, anchor_save_stack.top(), anchor_data_save_stack.top());
anchor_save_stack.pop();
anchor_data_save_stack.pop();
interest_in_saving = false;
subtract_count = 2;
}
break;
case YAML_SEQUENCE_START_EVENT:
if (!mode_stack.empty())
{
map_mode = positionAnalysis(local_event_output, mode_stack.top(), map_mode);
}
mode_stack.push('S');
if (event.data.sequence_start.anchor)
if (event.data.scalar.anchor)
{
anchor_save_stack.push((char*)event.data.sequence_start.anchor);
interest_in_saving = true;
subtract_count = 2;
}
else
{
local_event_output += std::string((char*)event.data.scalar.value, event.data.scalar.length);
}
if (event.data.sequence_start.tag)
{
std::string temp_translator = ((char*)event.data.sequence_start.tag);
local_event_output += (temp_translator + " \n");
}
else
{
local_event_output += "\n";
}
break;
case YAML_SEQUENCE_END_EVENT:
mode_stack.pop();
if (!anchor_save_stack.empty() && interest_in_saving)
{
addToMap(anchor_map, anchor_save_stack.top(), anchor_data_save_stack.top());
anchor_save_stack.pop();
anchor_data_save_stack.pop();
interest_in_saving = false;
subtract_count = 2;
}
break;
case YAML_SCALAR_EVENT:
map_mode = positionAnalysis(local_event_output, mode_stack.top(), map_mode);
if (event.data.scalar.tag)
{
std::string temp_translator = ((char*)event.data.scalar.tag);
local_event_output += temp_translator + " - ";
}
else
{
local_event_output += "- ";
}
if (event.data.scalar.anchor)
{
anchor_save_stack.push((char*)event.data.scalar.anchor);
interest_in_saving = true;
subtract_count = 2;
}
else
{
local_event_output += std::string((char*)event.data.scalar.value, event.data.scalar.length);
local_event_output += ("\n");
}
break;
case YAML_ALIAS_EVENT:
{
std::string temp_translator = ((char*) event.data.alias.anchor);
std::string& temp_holder = anchor_map[temp_translator];
if (!temp_holder.empty())
{
map_mode = positionAnalysis(local_event_output, mode_stack.top(), map_mode);
local_event_output += "\n" + temp_holder;
}
else
{
yaml_event_delete(&event);
assert(!fclose(input));
yaml_parser_delete(&parser);
return "the referenced anchor is not defined";
}
break;
}
default:
break;
}
yaml_event_delete(&event);
if (type == YAML_STREAM_END_EVENT)
break;
if(subtract_count <= 1 && interest_in_saving)
{
addInfoToDataStack(anchor_data_save_stack, local_event_output);
}
if(interest_in_saving)
{
subtract_count--;
}
libyaml_final_output += local_event_output;
}
assert(!fclose(input));
yaml_parser_delete(&parser);
fflush(stdout);
return libyaml_final_output;
}
// ---------------------------------------------------------------------------------
// ------------------------------ yaml-cpp test code -------------------------------
// ---------------------------------------------------------------------------------
std::string parseYamlCppNode(YAML::Node& head)
{
std::stack <YAML::Node> iteration_list_stack;
std::stack <std::string> additional_info_stack;
iteration_list_stack.push(head);
additional_info_stack.push("U");
std::string yamlcpp_final_output = "";
while (!iteration_list_stack.empty())
{
YAML::Node base_iterator = iteration_list_stack.top();
iteration_list_stack.pop();
yamlcpp_final_output += additional_info_stack.top() + ": ";
additional_info_stack.pop();
const std::string& tag_holder = base_iterator.Tag();
if(tag_holder != "?" && tag_holder != "!")
{
yamlcpp_final_output += tag_holder + " ";
}
switch (base_iterator.Type())
{
case YAML::NodeType::Null:
{
yamlcpp_final_output = "";
break;
}
case YAML::NodeType::Scalar:
{
yamlcpp_final_output += "- " + base_iterator.as<std::string>() + "\n";
break;
}
case YAML::NodeType::Sequence:
{
yamlcpp_final_output += "\n";
for (int i = base_iterator.size() - 1; i >= 0; i--)
{
iteration_list_stack.push(base_iterator[i]);
additional_info_stack.push("L");
}
break;
}
case YAML::NodeType::Map:
{
yamlcpp_final_output += "\n";
std::stack <YAML::const_iterator> loca_iterators_temp_stack;
for (YAML::const_iterator it = base_iterator.begin(); it != base_iterator.end(); ++it)
{
loca_iterators_temp_stack.push(it);
}
while (!loca_iterators_temp_stack.empty())
{
YAML::const_iterator it = loca_iterators_temp_stack.top();
loca_iterators_temp_stack.pop();
iteration_list_stack.push(it->second);
additional_info_stack.push("V");
iteration_list_stack.push(it->first);
additional_info_stack.push("K");
}
break;
}
case YAML::NodeType::Undefined:
{
yamlcpp_final_output += "- Undef \n";
break;
}
default:
{
yamlcpp_final_output += "- ERROR: Unknown Input Type \n";
}
}
}
return yamlcpp_final_output;
}
// ---------------------------------------------------------------------------------
// ---------------------------------- testcode -------------------------------------
// ---------------------------------------------------------------------------------
bool compareStringsCustom(std::string compareMeOne, std::string compareMeTwo)
{
std::string::iterator ptrOne = compareMeOne.begin();
std::string::iterator ptrTwo = compareMeTwo.begin();
while (*ptrOne == *ptrTwo && ((ptrOne != compareMeOne.end()) || (ptrTwo != compareMeTwo.end())))
{
if(*ptrOne == *ptrTwo)
{
std::cout << *ptrTwo;
}
ptrOne++;
ptrTwo++;
}
if(!((ptrOne == compareMeOne.end()) && (ptrTwo == compareMeTwo.end())))
{
std::cout << "(X)";
return false;
}
else
{
return true;
}
}
// ---------------------------------------------------------------------------------
// -------------------------------------- main -------------------------------------
// ---------------------------------------------------------------------------------
int main(int argc, char* args[])
{
std::cout << "----------- libyaml tests -----------" << std::endl;
// parseLibyaml(args[1]);
std::string libyaml_final_output = parseLibyaml(args[1]);
std::cout << libyaml_final_output << "(END)" << std::endl;
std::cout << "----------- yaml-cpp tests -----------" << std::endl;
std::string yamlcpp_final_output;
try
{
YAML::Node node = YAML::LoadFile(args[1]);
// YAML::Node node = YAML::Load("[1, 2, 3]");
std::cout << "Node type: " << node.Type() << std::endl;
yamlcpp_final_output = parseYamlCppNode(node);
}
catch (const std::exception& err)
{
yamlcpp_final_output = err.what();
}
std::cout << "--------yaml-cpp Output:" << std::endl;
std::cout << yamlcpp_final_output << "(END)" << std::endl;
std::cout << "--------" << std::endl;
std::cout << "- Conclusion: " << std::endl;
if (compareStringsCustom(libyaml_final_output, yamlcpp_final_output))
{
std::cout << "(END)" << std::endl;
std::cout << "Cases equal!" << std::endl;
}
else
{
std::cout << "(END)" << std::endl;
std::cout << "Cases different!" << std::endl;
}
return 0;
}
// \0 in the middle<commit_msg>Small libyaml refactoring on adding to maps<commit_after>#include <iostream>
#include <string>
#include <stack>
#include <map>
#include <assert.h>
#include <fstream>
// From git file
#include "include/yaml.h"
#include "yaml-cpp/yaml.h"
// ---------------------------------------------------------------------------------
// ------------------------------- libyaml test code -------------------------------
// ---------------------------------------------------------------------------------
bool positionAnalysis(std::string& add_to_me, char reference_character, bool map_mode)
{
if (reference_character == 'M')
{
if (map_mode)
{
add_to_me += "K: ";
}
else
{
add_to_me += "V: ";
}
return !map_mode;
}
else if (reference_character == 'S')
{
add_to_me += "L: ";
}
else
{
add_to_me += "U: ";
}
return map_mode;
}
void addToMap(std::map<std::string, std::string>& anchor_map,
std::string& anchor, std::string& anchor_data)
{
if (&anchor != nullptr)
{
if (anchor_map.count(anchor))
{
anchor_map[anchor] = anchor_data;
}
else
{
anchor_map.insert({anchor, anchor_data});
}
}
}
bool addToMapDirective(std::map<std::string, std::string>& anchor_map,
std::stack<std::string>& anchor_save_stack, std::stack<std::string>& anchor_data_save_stack,
int& subtract_count, bool interest_in_saving)
{
if (!anchor_save_stack.empty() && interest_in_saving)
{
addToMap(anchor_map, anchor_save_stack.top(), anchor_data_save_stack.top());
anchor_save_stack.pop();
anchor_data_save_stack.pop();
subtract_count = 2;
return false;
}
return interest_in_saving;
}
void addInfoToDataStack(std::stack<std::string>& anchor_data,
std::string info)
{
if (!anchor_data.empty())
{
std::string& temp = anchor_data.top();
temp += info;
}
else
{
anchor_data.push(info);
}
}
std::string parseLibyaml(std::string name_of_file)
{
FILE *input;
yaml_parser_t parser;
yaml_event_t event;
std::string libyaml_final_output = "";
std::string relevant_saving_info = "";
bool interest_in_saving = false;
int subtract_count = 2;
std::map<std::string, std::string> anchor_map;
std::stack<std::string> anchor_save_stack;
std::stack<std::string> anchor_data_save_stack;
std::stack<char> mode_stack;
mode_stack.push(' ');
std::stack<bool> map_mode_stack;
bool map_mode = true;
input = fopen(name_of_file.c_str(), "rb");
assert(input);
if (!yaml_parser_initialize(&parser))
{
return "ERROR: Could not initialize the parser object\n";
}
yaml_parser_set_input_file(&parser, input);
while (true)
{
std::string local_event_output = "";
yaml_event_type_t type;
if (!yaml_parser_parse(&parser, &event))
{
if ( parser.problem_mark.line || parser.problem_mark.column )
{
fprintf(stderr, "Parse error: %s\nLine: %lu Column: %lu\n",
parser.problem,
(unsigned long)parser.problem_mark.line + 1,
(unsigned long)parser.problem_mark.column + 1);
}
else {
fprintf(stderr, "Parse error: %s\n", parser.problem);
}
return "ERROR: Bad parsing";
}
type = event.type;
switch (type)
{
case YAML_STREAM_END_EVENT:
interest_in_saving = addToMapDirective(anchor_map, anchor_save_stack,
anchor_data_save_stack, subtract_count, interest_in_saving);
break;
case YAML_DOCUMENT_END_EVENT:
interest_in_saving = addToMapDirective(anchor_map, anchor_save_stack,
anchor_data_save_stack, subtract_count, interest_in_saving);
break;
case YAML_MAPPING_START_EVENT:
if (!mode_stack.empty())
{
positionAnalysis(local_event_output, mode_stack.top(), map_mode);
}
if (mode_stack.top()=='M')
{
map_mode_stack.push(!map_mode);
}
mode_stack.push('M');
map_mode = true;
if (event.data.mapping_start.anchor)
{
anchor_save_stack.push(((char*)event.data.mapping_start.anchor));
interest_in_saving = true;
subtract_count = 2;
}
else
{
local_event_output +=
std::string((char*)event.data.scalar.value, event.data.scalar.length);
}
if (event.data.mapping_start.tag)
{
std::string temp_translator = ((char*)event.data.mapping_start.tag);
local_event_output += temp_translator + " \n";
}
else
{
local_event_output += "\n";
}
break;
case YAML_MAPPING_END_EVENT:
mode_stack.pop();
if(mode_stack.top()=='M')
{
map_mode = map_mode_stack.top();
map_mode_stack.pop();
}
interest_in_saving = addToMapDirective(anchor_map, anchor_save_stack,
anchor_data_save_stack, subtract_count, interest_in_saving);
break;
case YAML_SEQUENCE_START_EVENT:
if (!mode_stack.empty())
{
map_mode = positionAnalysis(local_event_output, mode_stack.top(), map_mode);
}
mode_stack.push('S');
if (event.data.sequence_start.anchor)
if (event.data.scalar.anchor)
{
anchor_save_stack.push((char*)event.data.sequence_start.anchor);
interest_in_saving = true;
subtract_count = 2;
}
else
{
local_event_output += std::string((char*)event.data.scalar.value, event.data.scalar.length);
}
if (event.data.sequence_start.tag)
{
std::string temp_translator = ((char*)event.data.sequence_start.tag);
local_event_output += (temp_translator + " \n");
}
else
{
local_event_output += "\n";
}
break;
case YAML_SEQUENCE_END_EVENT:
mode_stack.pop();
interest_in_saving = addToMapDirective(anchor_map, anchor_save_stack,
anchor_data_save_stack, subtract_count, interest_in_saving);
break;
case YAML_SCALAR_EVENT:
map_mode = positionAnalysis(local_event_output, mode_stack.top(), map_mode);
if (event.data.scalar.tag)
{
std::string temp_translator = ((char*)event.data.scalar.tag);
local_event_output += temp_translator + " - ";
}
else
{
local_event_output += "- ";
}
if (event.data.scalar.anchor)
{
anchor_save_stack.push((char*)event.data.scalar.anchor);
interest_in_saving = true;
subtract_count = 2;
}
else
{
local_event_output += std::string((char*)event.data.scalar.value, event.data.scalar.length);
local_event_output += ("\n");
}
break;
case YAML_ALIAS_EVENT:
{
std::string temp_translator = ((char*) event.data.alias.anchor);
std::string& temp_holder = anchor_map[temp_translator];
if (!temp_holder.empty())
{
map_mode = positionAnalysis(local_event_output, mode_stack.top(), map_mode);
local_event_output += "\n" + temp_holder;
}
else
{
yaml_event_delete(&event);
assert(!fclose(input));
yaml_parser_delete(&parser);
return "the referenced anchor is not defined";
}
break;
}
default:
break;
}
yaml_event_delete(&event);
if (type == YAML_STREAM_END_EVENT)
break;
if(subtract_count <= 1 && interest_in_saving)
{
addInfoToDataStack(anchor_data_save_stack, local_event_output);
}
if(interest_in_saving)
{
subtract_count--;
}
libyaml_final_output += local_event_output;
}
assert(!fclose(input));
yaml_parser_delete(&parser);
fflush(stdout);
return libyaml_final_output;
}
// ---------------------------------------------------------------------------------
// ------------------------------ yaml-cpp test code -------------------------------
// ---------------------------------------------------------------------------------
std::string parseYamlCppNode(YAML::Node& head)
{
std::stack <YAML::Node> iteration_list_stack;
std::stack <std::string> additional_info_stack;
iteration_list_stack.push(head);
additional_info_stack.push("U");
std::string yamlcpp_final_output = "";
while (!iteration_list_stack.empty())
{
YAML::Node base_iterator = iteration_list_stack.top();
iteration_list_stack.pop();
yamlcpp_final_output += additional_info_stack.top() + ": ";
additional_info_stack.pop();
const std::string& tag_holder = base_iterator.Tag();
if(tag_holder != "?" && tag_holder != "!")
{
yamlcpp_final_output += tag_holder + " ";
}
switch (base_iterator.Type())
{
case YAML::NodeType::Null:
{
yamlcpp_final_output = "";
break;
}
case YAML::NodeType::Scalar:
{
yamlcpp_final_output += "- " + base_iterator.as<std::string>() + "\n";
break;
}
case YAML::NodeType::Sequence:
{
yamlcpp_final_output += "\n";
for (int i = base_iterator.size() - 1; i >= 0; i--)
{
iteration_list_stack.push(base_iterator[i]);
additional_info_stack.push("L");
}
break;
}
case YAML::NodeType::Map:
{
yamlcpp_final_output += "\n";
std::stack <YAML::const_iterator> loca_iterators_temp_stack;
for (YAML::const_iterator it = base_iterator.begin(); it != base_iterator.end(); ++it)
{
loca_iterators_temp_stack.push(it);
}
while (!loca_iterators_temp_stack.empty())
{
YAML::const_iterator it = loca_iterators_temp_stack.top();
loca_iterators_temp_stack.pop();
iteration_list_stack.push(it->second);
additional_info_stack.push("V");
iteration_list_stack.push(it->first);
additional_info_stack.push("K");
}
break;
}
case YAML::NodeType::Undefined:
{
yamlcpp_final_output += "- Undef \n";
break;
}
default:
{
yamlcpp_final_output += "- ERROR: Unknown Input Type \n";
}
}
}
return yamlcpp_final_output;
}
// ---------------------------------------------------------------------------------
// ---------------------------------- testcode -------------------------------------
// ---------------------------------------------------------------------------------
bool compareStringsCustom(std::string compareMeOne, std::string compareMeTwo)
{
std::string::iterator ptrOne = compareMeOne.begin();
std::string::iterator ptrTwo = compareMeTwo.begin();
while (*ptrOne == *ptrTwo && ((ptrOne != compareMeOne.end()) || (ptrTwo != compareMeTwo.end())))
{
if(*ptrOne == *ptrTwo)
{
std::cout << *ptrTwo;
}
ptrOne++;
ptrTwo++;
}
if(!((ptrOne == compareMeOne.end()) && (ptrTwo == compareMeTwo.end())))
{
std::cout << "(X)";
return false;
}
else
{
return true;
}
}
// ---------------------------------------------------------------------------------
// -------------------------------------- main -------------------------------------
// ---------------------------------------------------------------------------------
int main(int argc, char* args[])
{
std::cout << "----------- libyaml tests -----------" << std::endl;
// parseLibyaml(args[1]);
std::string libyaml_final_output = parseLibyaml(args[1]);
std::cout << libyaml_final_output << "(END)" << std::endl;
std::cout << "----------- yaml-cpp tests -----------" << std::endl;
std::string yamlcpp_final_output;
try
{
YAML::Node node = YAML::LoadFile(args[1]);
// YAML::Node node = YAML::Load("[1, 2, 3]");
std::cout << "Node type: " << node.Type() << std::endl;
yamlcpp_final_output = parseYamlCppNode(node);
}
catch (const std::exception& err)
{
yamlcpp_final_output = err.what();
}
std::cout << "Four" << std::endl;
std::cout << "--------yaml-cpp Output:" << std::endl;
std::cout << yamlcpp_final_output << "(END)" << std::endl;
std::cout << "--------" << std::endl;
std::cout << "- Conclusion: " << std::endl;
if (compareStringsCustom(libyaml_final_output, yamlcpp_final_output))
{
std::cout << "(END)" << std::endl;
std::cout << "Cases equal!" << std::endl;
}
else
{
std::cout << "(END)" << std::endl;
std::cout << "Cases different!" << std::endl;
}
return 0;
}
// \0 in the middle<|endoftext|>
|
<commit_before>/*
* GStreamer
* Copyright (C) 2016 Freescale Semiconductor, Inc. All rights reserved.
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Library General Public
* License as published by the Free Software Foundation; either
* version 2 of the License, or (at your option) any later version.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Library General Public License for more details.
*
* You should have received a copy of the GNU Library General Public
* License along with this library; if not, write to the
* Free Software Foundation, Inc., 51 Franklin St, Fifth Floor,
* Boston, MA 02110-1301, USA.
*/
#ifdef HAVE_CONFIG_H
#include "config.h"
#endif
#include "gstqtglutility.h"
#include <QtGui/QGuiApplication>
#if GST_GL_HAVE_WINDOW_X11 && defined (HAVE_QT_X11)
#include <QX11Info>
#include <gst/gl/x11/gstgldisplay_x11.h>
#if GST_GL_HAVE_PLATFORM_GLX
#include <gst/gl/x11/gstglcontext_glx.h>
#elif GST_GL_HAVE_PLATFORM_EGL
#include <gst/gl/egl/gstglcontext_egl.h>
#endif
#endif
#if GST_GL_HAVE_WINDOW_WAYLAND && GST_GL_HAVE_PLATFORM_EGL && defined (HAVE_QT_WAYLAND)
#include <qpa/qplatformnativeinterface.h>
#include <gst/gl/wayland/gstgldisplay_wayland.h>
#endif
#if GST_GL_HAVE_PLATFORM_EGL && defined (HAVE_QT_EGLFS)
#if GST_GL_HAVE_WINDOW_VIV_FB
#include <qpa/qplatformnativeinterface.h>
#include <gst/gl/viv-fb/gstgldisplay_viv_fb.h>
#else
#include <gst/gl/egl/gstgldisplay_egl.h>
#endif
#include <gst/gl/egl/gstglcontext_egl.h>
#endif
#if GST_GL_HAVE_WINDOW_COCOA && GST_GL_HAVE_PLATFORM_COCOA && defined (HAVE_QT_MAC)
#include <gst/gl/coaoa/gstgldisplay_cocoa.h>
#endif
#define GST_CAT_DEFAULT qt_gl_utils_debug
GST_DEBUG_CATEGORY_STATIC (GST_CAT_DEFAULT);
GstGLDisplay *
gst_qt_get_gl_display ()
{
GstGLDisplay *display = NULL;
QGuiApplication *app = static_cast<QGuiApplication *> (QCoreApplication::instance ());
static volatile gsize _debug;
g_assert (app != NULL);
if (g_once_init_enter (&_debug)) {
GST_DEBUG_CATEGORY_INIT (GST_CAT_DEFAULT, "qtglutility", 0,
"Qt gl utility functions");
g_once_init_leave (&_debug, 1);
}
GST_INFO ("QGuiApplication::instance()->platformName() %s", app->platformName().toUtf8().data());
#if GST_GL_HAVE_WINDOW_X11 && defined (HAVE_QT_X11)
if (QString::fromUtf8 ("xcb") == app->platformName())
display = (GstGLDisplay *)
gst_gl_display_x11_new_with_display (QX11Info::display ());
#endif
#if GST_GL_HAVE_WINDOW_WAYLAND && GST_GL_HAVE_PLATFORM_EGL && defined (HAVE_QT_WAYLAND)
if (QString::fromUtf8 ("wayland") == app->platformName()
|| QString::fromUtf8 ("wayland-egl") == app->platformName()){
struct wl_display * wayland_display;
QPlatformNativeInterface *native =
QGuiApplication::platformNativeInterface();
wayland_display = (struct wl_display *)
native->nativeResourceForWindow("display", NULL);
display = (GstGLDisplay *)
gst_gl_display_wayland_new_with_display (wayland_display);
}
#endif
#if GST_GL_HAVE_PLATFORM_EGL && GST_GL_HAVE_WINDOW_ANDROID
if (QString::fromUtf8 ("android") == app->platformName())
display = (GstGLDisplay *) gst_gl_display_egl_new_with_egl_display (eglGetDisplay(EGL_DEFAULT_DISPLAY));
#elif GST_GL_HAVE_PLATFORM_EGL && defined (HAVE_QT_EGLFS)
if (QString::fromUtf8("eglfs") == app->platformName()) {
#if GST_GL_HAVE_WINDOW_VIV_FB
/* FIXME: Could get the display directly from Qt like this
QPlatformNativeInterface *native =
QGuiApplication::platformNativeInterface();
EGLDisplay egl_display = (EGLDisplay)
native->nativeResourceForWindow("egldisplay", NULL);
However we seem to have no way for getting the EGLNativeDisplayType, aka
native_display, via public API. As such we have to assume that display 0
is always used. Only way around that is parsing the index the same way as
Qt does in QEGLDeviceIntegration::fbDeviceName(), so let's do that.
*/
const gchar *fb_dev;
gint disp_idx = 0;
fb_dev = g_getenv ("QT_QPA_EGLFS_FB");
if (fb_dev) {
if (sscanf (fb_dev, "/dev/fb%d", &disp_idx) != 1)
disp_idx = 0;
}
display = (GstGLDisplay *) gst_gl_display_viv_fb_new (disp_idx);
#else
display = (GstGLDisplay *) gst_gl_display_egl_new_with_egl_display (eglGetDisplay(EGL_DEFAULT_DISPLAY));
#endif
}
#endif
#if GST_GL_HAVE_WINDOW_COCOA && GST_GL_HAVE_PLATFORM_COCOA && defined (HAVE_QT_MAC)
if (QString::fromUtf8 ("cocoa") == app->platformName())
display = (GstGLDisplay *) gst_gl_display_cocoa_new ();
#endif
#if GST_GL_HAVE_WINDOW_EAGL && GST_GL_HAVE_PLATFORM_EAGL && defined (HAVE_QT_IOS)
if (QString::fromUtf8 ("ios") == app->platformName())
display = gst_gl_display_new ();
#endif
#if GST_GL_HAVE_WINDOW_WIN32 && GST_GL_HAVE_PLATFORM_WGL && defined (HAVE_QT_WIN32)
if (QString::fromUtf8 ("windows") == app->platformName())
display = gst_gl_display_new ();
#endif
if (!display)
display = gst_gl_display_new ();
return display;
}
gboolean
gst_qt_get_gl_wrapcontext (GstGLDisplay * display,
GstGLContext **wrap_glcontext, GstGLContext **context)
{
GstGLPlatform platform = (GstGLPlatform) 0;
GstGLAPI gl_api;
guintptr gl_handle;
GError *error = NULL;
g_return_val_if_fail (display != NULL && wrap_glcontext != NULL, FALSE);
#if GST_GL_HAVE_WINDOW_X11 && defined (HAVE_QT_X11)
if (GST_IS_GL_DISPLAY_X11 (display)) {
#if GST_GL_HAVE_PLATFORM_GLX
platform = GST_GL_PLATFORM_GLX;
#elif GST_GL_HAVE_PLATFORM_EGL
platform = GST_GL_PLATFORM_EGL;
#endif
}
#endif
#if GST_GL_HAVE_WINDOW_WAYLAND && defined (HAVE_QT_WAYLAND)
if (GST_IS_GL_DISPLAY_WAYLAND (display)) {
platform = GST_GL_PLATFORM_EGL;
}
#endif
#if GST_GL_HAVE_PLATFORM_EGL && defined (HAVE_QT_EGLFS)
#if GST_GL_HAVE_WINDOW_VIV_FB
if (GST_IS_GL_DISPLAY_VIV_FB (display)) {
#else
if (GST_IS_GL_DISPLAY_EGL (display)) {
#endif
platform = GST_GL_PLATFORM_EGL;
}
#endif
if (platform == 0) {
#if GST_GL_HAVE_WINDOW_COCOA && GST_GL_HAVE_PLATFORM_COCOA && defined (HAVE_QT_MAC)
platform = GST_GL_PLATFORM_CGL;
#elif GST_GL_HAVE_WINDOW_EAGL && GST_GL_HAVE_PLATFORM_EAGL && defined (HAVE_QT_IOS)
platform = GST_GL_PLATFORM_EAGL;
#elif GST_GL_HAVE_WINDOW_WIN32 && GST_GL_HAVE_PLATFORM_WGL && defined (HAVE_QT_WIN32)
platform = GST_GL_PLATFORM_WGL;
#else
GST_ERROR ("Unknown platform");
return FALSE;
#endif
}
gl_api = gst_gl_context_get_current_gl_api (platform, NULL, NULL);
gl_handle = gst_gl_context_get_current_gl_context (platform);
if (gl_handle)
*wrap_glcontext =
gst_gl_context_new_wrapped (display, gl_handle,
platform, gl_api);
if (!*wrap_glcontext) {
GST_ERROR ("cannot wrap qt OpenGL context");
return FALSE;
}
(void) platform;
(void) gl_api;
(void) gl_handle;
gst_gl_context_activate (*wrap_glcontext, TRUE);
if (!gst_gl_context_fill_info (*wrap_glcontext, &error)) {
GST_ERROR ("failed to retrieve qt context info: %s", error->message);
g_object_unref (*wrap_glcontext);
*wrap_glcontext = NULL;
return FALSE;
} else {
gst_gl_display_filter_gl_api (display, gst_gl_context_get_gl_api (*wrap_glcontext));
#if GST_GL_HAVE_WINDOW_WIN32 && GST_GL_HAVE_PLATFORM_WGL && defined (HAVE_QT_WIN32)
g_return_val_if_fail (context != NULL, FALSE);
G_STMT_START {
GstGLWindow *window;
HDC device;
/* If there's no wglCreateContextAttribsARB() support, then we would fallback to
* wglShareLists() which will fail with ERROR_BUSY (0xaa) if either of the GL
* contexts are current in any other thread.
*
* The workaround here is to temporarily disable Qt's GL context while we
* set up our own.
*
* Sometimes wglCreateContextAttribsARB()
* exists, but isn't functional (some Intel drivers), so it's easiest to do this
* unconditionally.
*/
*context = gst_gl_context_new (display);
window = gst_gl_context_get_window (*context);
device = (HDC) gst_gl_window_get_display (window);
wglMakeCurrent (device, 0);
gst_object_unref (window);
if (!gst_gl_context_create (*context, *wrap_glcontext, &error)) {
GST_ERROR ("%p failed to create shared GL context: %s", this, error->message);
g_object_unref (*context);
*context = NULL;
g_object_unref (*wrap_glcontext);
*wrap_glcontext = NULL;
wglMakeCurrent (device, (HGLRC) gl_handle);
return FALSE;
}
wglMakeCurrent (device, (HGLRC) gl_handle);
}
#endif
gst_gl_context_activate (*wrap_glcontext, FALSE);
} G_STMT_END;
return TRUE;
}
<commit_msg>qt: Use GST_GL_HAVE_PLATFORM_CGL instead of GST_GL_HAVE_PLATFORM_COCOA<commit_after>/*
* GStreamer
* Copyright (C) 2016 Freescale Semiconductor, Inc. All rights reserved.
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Library General Public
* License as published by the Free Software Foundation; either
* version 2 of the License, or (at your option) any later version.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Library General Public License for more details.
*
* You should have received a copy of the GNU Library General Public
* License along with this library; if not, write to the
* Free Software Foundation, Inc., 51 Franklin St, Fifth Floor,
* Boston, MA 02110-1301, USA.
*/
#ifdef HAVE_CONFIG_H
#include "config.h"
#endif
#include "gstqtglutility.h"
#include <QtGui/QGuiApplication>
#if GST_GL_HAVE_WINDOW_X11 && defined (HAVE_QT_X11)
#include <QX11Info>
#include <gst/gl/x11/gstgldisplay_x11.h>
#if GST_GL_HAVE_PLATFORM_GLX
#include <gst/gl/x11/gstglcontext_glx.h>
#elif GST_GL_HAVE_PLATFORM_EGL
#include <gst/gl/egl/gstglcontext_egl.h>
#endif
#endif
#if GST_GL_HAVE_WINDOW_WAYLAND && GST_GL_HAVE_PLATFORM_EGL && defined (HAVE_QT_WAYLAND)
#include <qpa/qplatformnativeinterface.h>
#include <gst/gl/wayland/gstgldisplay_wayland.h>
#endif
#if GST_GL_HAVE_PLATFORM_EGL && defined (HAVE_QT_EGLFS)
#if GST_GL_HAVE_WINDOW_VIV_FB
#include <qpa/qplatformnativeinterface.h>
#include <gst/gl/viv-fb/gstgldisplay_viv_fb.h>
#else
#include <gst/gl/egl/gstgldisplay_egl.h>
#endif
#include <gst/gl/egl/gstglcontext_egl.h>
#endif
#if GST_GL_HAVE_WINDOW_COCOA && GST_GL_HAVE_PLATFORM_CGL && defined (HAVE_QT_MAC)
#include <gst/gl/cocoa/gstgldisplay_cocoa.h>
#endif
#define GST_CAT_DEFAULT qt_gl_utils_debug
GST_DEBUG_CATEGORY_STATIC (GST_CAT_DEFAULT);
GstGLDisplay *
gst_qt_get_gl_display ()
{
GstGLDisplay *display = NULL;
QGuiApplication *app = static_cast<QGuiApplication *> (QCoreApplication::instance ());
static volatile gsize _debug;
g_assert (app != NULL);
if (g_once_init_enter (&_debug)) {
GST_DEBUG_CATEGORY_INIT (GST_CAT_DEFAULT, "qtglutility", 0,
"Qt gl utility functions");
g_once_init_leave (&_debug, 1);
}
GST_INFO ("QGuiApplication::instance()->platformName() %s", app->platformName().toUtf8().data());
#if GST_GL_HAVE_WINDOW_X11 && defined (HAVE_QT_X11)
if (QString::fromUtf8 ("xcb") == app->platformName())
display = (GstGLDisplay *)
gst_gl_display_x11_new_with_display (QX11Info::display ());
#endif
#if GST_GL_HAVE_WINDOW_WAYLAND && GST_GL_HAVE_PLATFORM_EGL && defined (HAVE_QT_WAYLAND)
if (QString::fromUtf8 ("wayland") == app->platformName()
|| QString::fromUtf8 ("wayland-egl") == app->platformName()){
struct wl_display * wayland_display;
QPlatformNativeInterface *native =
QGuiApplication::platformNativeInterface();
wayland_display = (struct wl_display *)
native->nativeResourceForWindow("display", NULL);
display = (GstGLDisplay *)
gst_gl_display_wayland_new_with_display (wayland_display);
}
#endif
#if GST_GL_HAVE_PLATFORM_EGL && GST_GL_HAVE_WINDOW_ANDROID
if (QString::fromUtf8 ("android") == app->platformName())
display = (GstGLDisplay *) gst_gl_display_egl_new_with_egl_display (eglGetDisplay(EGL_DEFAULT_DISPLAY));
#elif GST_GL_HAVE_PLATFORM_EGL && defined (HAVE_QT_EGLFS)
if (QString::fromUtf8("eglfs") == app->platformName()) {
#if GST_GL_HAVE_WINDOW_VIV_FB
/* FIXME: Could get the display directly from Qt like this
QPlatformNativeInterface *native =
QGuiApplication::platformNativeInterface();
EGLDisplay egl_display = (EGLDisplay)
native->nativeResourceForWindow("egldisplay", NULL);
However we seem to have no way for getting the EGLNativeDisplayType, aka
native_display, via public API. As such we have to assume that display 0
is always used. Only way around that is parsing the index the same way as
Qt does in QEGLDeviceIntegration::fbDeviceName(), so let's do that.
*/
const gchar *fb_dev;
gint disp_idx = 0;
fb_dev = g_getenv ("QT_QPA_EGLFS_FB");
if (fb_dev) {
if (sscanf (fb_dev, "/dev/fb%d", &disp_idx) != 1)
disp_idx = 0;
}
display = (GstGLDisplay *) gst_gl_display_viv_fb_new (disp_idx);
#else
display = (GstGLDisplay *) gst_gl_display_egl_new_with_egl_display (eglGetDisplay(EGL_DEFAULT_DISPLAY));
#endif
}
#endif
#if GST_GL_HAVE_WINDOW_COCOA && GST_GL_HAVE_PLATFORM_CGL && defined (HAVE_QT_MAC)
if (QString::fromUtf8 ("cocoa") == app->platformName())
display = (GstGLDisplay *) gst_gl_display_cocoa_new ();
#endif
#if GST_GL_HAVE_WINDOW_EAGL && GST_GL_HAVE_PLATFORM_EAGL && defined (HAVE_QT_IOS)
if (QString::fromUtf8 ("ios") == app->platformName())
display = gst_gl_display_new ();
#endif
#if GST_GL_HAVE_WINDOW_WIN32 && GST_GL_HAVE_PLATFORM_WGL && defined (HAVE_QT_WIN32)
if (QString::fromUtf8 ("windows") == app->platformName())
display = gst_gl_display_new ();
#endif
if (!display)
display = gst_gl_display_new ();
return display;
}
gboolean
gst_qt_get_gl_wrapcontext (GstGLDisplay * display,
GstGLContext **wrap_glcontext, GstGLContext **context)
{
GstGLPlatform platform = (GstGLPlatform) 0;
GstGLAPI gl_api;
guintptr gl_handle;
GError *error = NULL;
g_return_val_if_fail (display != NULL && wrap_glcontext != NULL, FALSE);
#if GST_GL_HAVE_WINDOW_X11 && defined (HAVE_QT_X11)
if (GST_IS_GL_DISPLAY_X11 (display)) {
#if GST_GL_HAVE_PLATFORM_GLX
platform = GST_GL_PLATFORM_GLX;
#elif GST_GL_HAVE_PLATFORM_EGL
platform = GST_GL_PLATFORM_EGL;
#endif
}
#endif
#if GST_GL_HAVE_WINDOW_WAYLAND && defined (HAVE_QT_WAYLAND)
if (GST_IS_GL_DISPLAY_WAYLAND (display)) {
platform = GST_GL_PLATFORM_EGL;
}
#endif
#if GST_GL_HAVE_PLATFORM_EGL && defined (HAVE_QT_EGLFS)
#if GST_GL_HAVE_WINDOW_VIV_FB
if (GST_IS_GL_DISPLAY_VIV_FB (display)) {
#else
if (GST_IS_GL_DISPLAY_EGL (display)) {
#endif
platform = GST_GL_PLATFORM_EGL;
}
#endif
if (platform == 0) {
#if GST_GL_HAVE_WINDOW_COCOA && GST_GL_HAVE_PLATFORM_CGL && defined (HAVE_QT_MAC)
platform = GST_GL_PLATFORM_CGL;
#elif GST_GL_HAVE_WINDOW_EAGL && GST_GL_HAVE_PLATFORM_EAGL && defined (HAVE_QT_IOS)
platform = GST_GL_PLATFORM_EAGL;
#elif GST_GL_HAVE_WINDOW_WIN32 && GST_GL_HAVE_PLATFORM_WGL && defined (HAVE_QT_WIN32)
platform = GST_GL_PLATFORM_WGL;
#else
GST_ERROR ("Unknown platform");
return FALSE;
#endif
}
gl_api = gst_gl_context_get_current_gl_api (platform, NULL, NULL);
gl_handle = gst_gl_context_get_current_gl_context (platform);
if (gl_handle)
*wrap_glcontext =
gst_gl_context_new_wrapped (display, gl_handle,
platform, gl_api);
if (!*wrap_glcontext) {
GST_ERROR ("cannot wrap qt OpenGL context");
return FALSE;
}
(void) platform;
(void) gl_api;
(void) gl_handle;
gst_gl_context_activate (*wrap_glcontext, TRUE);
if (!gst_gl_context_fill_info (*wrap_glcontext, &error)) {
GST_ERROR ("failed to retrieve qt context info: %s", error->message);
g_object_unref (*wrap_glcontext);
*wrap_glcontext = NULL;
return FALSE;
} else {
gst_gl_display_filter_gl_api (display, gst_gl_context_get_gl_api (*wrap_glcontext));
#if GST_GL_HAVE_WINDOW_WIN32 && GST_GL_HAVE_PLATFORM_WGL && defined (HAVE_QT_WIN32)
g_return_val_if_fail (context != NULL, FALSE);
G_STMT_START {
GstGLWindow *window;
HDC device;
/* If there's no wglCreateContextAttribsARB() support, then we would fallback to
* wglShareLists() which will fail with ERROR_BUSY (0xaa) if either of the GL
* contexts are current in any other thread.
*
* The workaround here is to temporarily disable Qt's GL context while we
* set up our own.
*
* Sometimes wglCreateContextAttribsARB()
* exists, but isn't functional (some Intel drivers), so it's easiest to do this
* unconditionally.
*/
*context = gst_gl_context_new (display);
window = gst_gl_context_get_window (*context);
device = (HDC) gst_gl_window_get_display (window);
wglMakeCurrent (device, 0);
gst_object_unref (window);
if (!gst_gl_context_create (*context, *wrap_glcontext, &error)) {
GST_ERROR ("%p failed to create shared GL context: %s", this, error->message);
g_object_unref (*context);
*context = NULL;
g_object_unref (*wrap_glcontext);
*wrap_glcontext = NULL;
wglMakeCurrent (device, (HGLRC) gl_handle);
return FALSE;
}
wglMakeCurrent (device, (HGLRC) gl_handle);
}
#endif
gst_gl_context_activate (*wrap_glcontext, FALSE);
} G_STMT_END;
return TRUE;
}
<|endoftext|>
|
<commit_before>// phan_client.C - simplest example: generates a flat horizontal plane
#include <stdio.h> // for printf, NULL
#include <time.h> // for nanosleep
#include <algorithm> // for std::min_element
#include <iostream> // for std::cout
#include <string>
#include <vector>
#include <fstream>
#include <sstream>
#include <chrono>
#include <boost/math/common_factor.hpp>
#include <boost/interprocess/ipc/message_queue.hpp>
#include <boost/archive/text_iarchive.hpp>
#include <boost/archive/text_oarchive.hpp>
#include "liblager_connect.h"
#include "liblager_convert.h"
#include "spherical_coordinates.h"
#include "coordinates_letter.h"
#include "string_tokenizer.h"
#define RECOGNIZER_ERROR -1
#define RECOGNIZER_NO_ERROR 0
#define MAIN_SLEEP_INTERVAL_MICROSECONDS 1000 // 1ms
#define MAIN_SLEEP_INTERVAL_MILLISECONDS MAIN_SLEEP_INTERVAL_MICROSECONDS/1000
#define GESTURE_PAUSE_TIME_MILLISECONDS 500
#define GESTURE_GROUPING_TIME_MILLISECONDS 200
#define SINGLE_SENSOR_GESTURE_DISTANCE_THRESHOLD_PCT 20
#define DUAL_SENSOR_GESTURE_DISTANCE_THRESHOLD_PCT 30
using std::cout;
using std::endl;
using std::ifstream;
using std::string;
using std::stringstream;
using std::vector;
using std::chrono::duration;
using std::chrono::system_clock;
using std::chrono::time_point;
using namespace boost::interprocess;
/* Globals */
struct SubscribedGesture {
string name;
string lager;
string expanded_lager;
pid_t pid;
int dl_distance;
float dl_distance_pct;
};
string g_gesture_string;
vector<SubscribedGesture> g_subscribed_gestures;
#define d(i,j) dd[(i) * (m+2) + (j) ]
#define min(x,y) ((x) < (y) ? (x) : (y))
#define min3(a,b,c) ((a)< (b) ? min((a),(c)) : min((b),(c)))
#define min4(a,b,c,d) ((a)< (b) ? min3((a),(c),(d)) : min3((b),(c),(d)))
int DPrint(int* dd, int n, int m) {
int i, j;
for (i = 0; i < n + 2; i++) {
for (j = 0; j < m + 2; j++) {
printf("%02d ", d(i, j));
}
printf("\n");
}
printf("\n");
return 0;
}
int DlDist2(const char *s, const char* t, int n, int m) {
int *dd, *DA;
int i, j, cost, k, i1, j1, DB;
int infinity = n + m;
DA = (int*) malloc(256 * sizeof(int));
dd = (int*) malloc((n + 2) * (m + 2) * sizeof(int));
d(0,0)= infinity;
for (i = 0; i < n + 1; i++) {
d(i+1,1)= i;
d(i+1,0) = infinity;
}
for (j = 0; j < m + 1; j++) {
d(1,j+1)= j;
d(0,j+1) = infinity;
}
//DPrint(dd,n,m);
for (k = 0; k < 256; k++)
DA[k] = 0;
for (i = 1; i < n + 1; i++) {
DB = 0;
for (j = 1; j < m + 1; j++) {
i1 = DA[t[j - 1]];
j1 = DB;
cost = ((s[i - 1] == t[j - 1]) ? 0 : 1);
if (cost == 0)
DB = j;
d(i+1,j+1)=
min4(d(i,j)+cost,
d(i+1,j) + 1,
d(i,j+1)+1,
d(i1,j1) + (i-i1-1) + 1 + (j-j1-1));
}
DA[s[i - 1]] = i;
//dprint(dd,n,m);
}
cost = d(n + 1, m + 1);
free(dd);
return cost;
}
/* New size must be a multiple of the original string size */
string ExpandString(const string& input_string, int new_size) {
stringstream output_string;
int length_multiplier = new_size / input_string.length();
vector<string> movement_pairs;
TokenizeString(input_string, movement_pairs, ".");
for (vector<string>::iterator it = movement_pairs.begin();
it < movement_pairs.end(); ++it) {
for (int i = 0; i < length_multiplier; i++) {
output_string << *it << ".";
}
}
return output_string.str();
}
bool GestureEntryLessThan(SubscribedGesture i, SubscribedGesture j) {
return (i.dl_distance_pct < j.dl_distance_pct);
}
void UpdateSubscribedGestureDistance(
struct SubscribedGesture& subscribed_gesture) {
const string input_gesture = g_gesture_string;
int gesture_length_least_common_multiple = boost::math::lcm(
input_gesture.length(), subscribed_gesture.lager.length());
string expanded_input_string = ExpandString(
input_gesture, gesture_length_least_common_multiple);
subscribed_gesture.expanded_lager = ExpandString(
subscribed_gesture.lager, gesture_length_least_common_multiple);
subscribed_gesture.dl_distance = DlDist2(
expanded_input_string.c_str(), subscribed_gesture.expanded_lager.c_str(),
expanded_input_string.length(),
subscribed_gesture.expanded_lager.length());
subscribed_gesture.dl_distance_pct = (subscribed_gesture.dl_distance * 100.0f)
/ subscribed_gesture.expanded_lager.length();
cout << subscribed_gesture.name << endl << "\t" << subscribed_gesture.lager
<< endl;
cout << "Distance: " << subscribed_gesture.dl_distance_pct << "% ("
<< subscribed_gesture.dl_distance << " D-L ops)" << endl;
cout << endl;
}
void UpdateSubscribedGestureDistances() {
for (vector<SubscribedGesture>::iterator it = g_subscribed_gestures.begin();
it < g_subscribed_gestures.end(); ++it) {
UpdateSubscribedGestureDistance(*it);
}
}
void DrawMatchingGestures(const SubscribedGesture& closest_gesture) {
stringstream viewer_command;
string viewer_command_prefix =
"cd ~/lager/viewer/src/ && ../build/lager_viewer --gesture ";
string hide_output_suffix = " > /dev/null";
cout << "Drawing input gesture..." << endl;
viewer_command << viewer_command_prefix << g_gesture_string
<< hide_output_suffix;
system(viewer_command.str().c_str());
cout << "Drawing gesture match..." << endl;
viewer_command.str("");
viewer_command << viewer_command_prefix << closest_gesture.lager
<< hide_output_suffix;
system(viewer_command.str().c_str());
}
bool IsSingleSensorGesture() {
vector<string> movement_pairs;
TokenizeString(g_gesture_string, movement_pairs, ".");
bool sensor_0_moved = false;
bool sensor_1_moved = false;
for (vector<string>::iterator it = movement_pairs.begin();
it < movement_pairs.end(); ++it) {
// Check if sensor 0 movement is present
if ((*it).c_str()[0] != '_') {
sensor_0_moved = true;
}
// Check if sensor 0 movement is present
if ((*it).c_str()[0] != '_') {
sensor_1_moved = true;
}
// If we already found movement on both sensors, there is no need to keep checking
if (sensor_0_moved && sensor_1_moved) {
break;
}
}
return (!sensor_0_moved || !sensor_1_moved);
}
int GetMillisecondsUntilNow(const time_point<system_clock> &last_time) {
time_point<system_clock> now = system_clock::now();
return duration<double, std::milli>(now - last_time).count();
}
void RecognizeGesture(bool use_gestures_file, bool draw_gestures) {
if (g_subscribed_gestures.size() == 0) {
cout << "No gesture subscriptions." << endl;
return;
}
int lowestDistance;
bool match_found = false;
unsigned int num_milliseconds_since_recognition_start = 0;
time_point<system_clock> recognition_start_time = system_clock::now();
int gesture_distance_threshold_pct =
IsSingleSensorGesture() ?
SINGLE_SENSOR_GESTURE_DISTANCE_THRESHOLD_PCT :
DUAL_SENSOR_GESTURE_DISTANCE_THRESHOLD_PCT;
cout << " ________________________________ " << endl;
cout << "| |" << endl;
cout << "| RECOGNIZING... |" << endl;
cout << "|________________________________|" << endl;
cout << " " << endl;
UpdateSubscribedGestureDistances();
SubscribedGesture closest_gesture = *min_element(
g_subscribed_gestures.begin(), g_subscribed_gestures.end(),
GestureEntryLessThan);
match_found = closest_gesture.dl_distance_pct
<= gesture_distance_threshold_pct;
num_milliseconds_since_recognition_start = GetMillisecondsUntilNow(
recognition_start_time);
if (match_found) {
cout << " ________________________________ " << endl;
cout << "| |" << endl;
cout << "| MATCH FOUND! |" << endl;
cout << "|________________________________|" << endl;
cout << " " << endl;
} else {
cout << endl;
cout << "NO MATCH." << endl;
}
cout << endl;
cout << "Closest gesture:\t" << closest_gesture.name << endl;
cout << endl;
cout << "Distance:\t\t" << closest_gesture.dl_distance_pct << "% ("
<< closest_gesture.dl_distance << " D-L ops)" << endl;
cout << "Threshold:\t\t" << gesture_distance_threshold_pct << "%" << endl;
cout << endl;
cout << "Recognition time: \t" << num_milliseconds_since_recognition_start
<< "ms" << endl;
cout << endl;
if (match_found) {
if (draw_gestures) {
DrawMatchingGestures(closest_gesture);
}
if (!use_gestures_file && closest_gesture.pid != 0) {
SendDetectedGestureMessage(closest_gesture.name, closest_gesture.pid);
}
}
cout << endl << endl;
;
}
/*****************************************************************************
*
Callback handler
*
*****************************************************************************/
bool DetermineButtonUse(const int argc, const char** argv) {
bool use_buttons;
if ((argc > 1)
&& (std::string(argv[1]).find("--use_buttons") != std::string::npos)) {
cout << "Gesture detection will be active while pressing a button." << endl;
use_buttons = true;
} else {
cout << "Gesture detection will be active at all times." << endl;
use_buttons = false;
}
return use_buttons;
}
bool DetermineGesturesFileUse(const int argc, const char** argv) {
bool use_gestures_file;
if ((argc > 1)
&& (std::string(argv[1]).find("--use_gestures_file") != std::string::npos)) {
cout << "Comparing input to gestures in a file." << endl;
use_gestures_file = true;
} else {
cout << "Comparing input to subscribed gestures." << endl;
use_gestures_file = false;
}
return use_gestures_file;
}
bool DetermineGestureDrawing(const int argc, const char** argv) {
bool draw_gestures;
if ((argc > 1)
&& (std::string(argv[1]).find("--draw_gestures") != std::string::npos)) {
cout << "Using lager_viewer to draw input and subscribed gestures." << endl;
draw_gestures = true;
} else {
cout << "Will not draw gestures." << endl;
draw_gestures = false;
}
return draw_gestures;
}
void AddSubscribedGestures() {
while (true) {
GestureSubscriptionMessage message = GetGestureSubscriptionMessage();
cout << "Adding subscription..." << endl;
cout << endl;
cout << "Name: \"" << message.gesture_name() << "\"" << endl;
cout << "Lager: \"" << message.gesture_lager() << endl;
cout << endl;
SubscribedGesture subscription;
subscription.name = message.gesture_name();
subscription.lager = message.gesture_lager();
subscription.pid = message.pid();
g_subscribed_gestures.push_back(subscription);
}
}
int GetSubscribedGesturesFromFile() {
ifstream gestures_file;
string current_line;
cout << "Current gesture" << endl << "\t" << g_gesture_string << endl
<< endl;
gestures_file.open("gestures.dat");
if (!gestures_file.is_open()) {
return RECOGNIZER_ERROR;
}
while (getline(gestures_file, current_line)) {
string name, lager;
stringstream ss(current_line);
ss >> name >> lager;
SubscribedGesture new_gesture;
ss >> new_gesture.name >> new_gesture.lager;
new_gesture.pid = 0;
g_subscribed_gestures.push_back(new_gesture);
}
return RECOGNIZER_NO_ERROR;
}
int main(int argc, const char *argv[]) {
//printf("Generates strings for movement of tracker %s\n\n", TRACKER_SERVER);
struct timespec sleep_interval = { 0, MAIN_SLEEP_INTERVAL_MICROSECONDS };
bool use_buttons = DetermineButtonUse(argc, argv);
bool use_gestures_file = DetermineGesturesFileUse(argc, argv);
bool draw_gestures = DetermineGestureDrawing(argc, argv);
LagerConverter* lager_converter = LagerConverter::Instance();
if (use_gestures_file) {
GetSubscribedGesturesFromFile();
} else {
CreateGestureSubscriptionQueue();
boost::thread subscription_updater(AddSubscribedGestures);
}
cout << " ________________________________ " << endl;
cout << "| |" << endl;
cout << "| COLLECTING DATA... |" << endl;
cout << "|________________________________|" << endl;
cout << " " << endl;
lager_converter->SetUseButtons(use_buttons);
lager_converter->Start();
while(true) {
g_gesture_string = lager_converter->BlockingGetLagerString();
RecognizeGesture(use_gestures_file, draw_gestures);
}
} /* main */
<commit_msg>Recognizer: Use non-absolute path to lager_viewer<commit_after>// phan_client.C - simplest example: generates a flat horizontal plane
#include <stdio.h> // for printf, NULL
#include <time.h> // for nanosleep
#include <algorithm> // for std::min_element
#include <iostream> // for std::cout
#include <string>
#include <vector>
#include <fstream>
#include <sstream>
#include <chrono>
#include <boost/math/common_factor.hpp>
#include <boost/interprocess/ipc/message_queue.hpp>
#include <boost/archive/text_iarchive.hpp>
#include <boost/archive/text_oarchive.hpp>
#include "liblager_connect.h"
#include "liblager_convert.h"
#include "spherical_coordinates.h"
#include "coordinates_letter.h"
#include "string_tokenizer.h"
#define RECOGNIZER_ERROR -1
#define RECOGNIZER_NO_ERROR 0
#define MAIN_SLEEP_INTERVAL_MICROSECONDS 1000 // 1ms
#define MAIN_SLEEP_INTERVAL_MILLISECONDS MAIN_SLEEP_INTERVAL_MICROSECONDS/1000
#define GESTURE_PAUSE_TIME_MILLISECONDS 500
#define GESTURE_GROUPING_TIME_MILLISECONDS 200
#define SINGLE_SENSOR_GESTURE_DISTANCE_THRESHOLD_PCT 20
#define DUAL_SENSOR_GESTURE_DISTANCE_THRESHOLD_PCT 30
using std::cout;
using std::endl;
using std::ifstream;
using std::string;
using std::stringstream;
using std::vector;
using std::chrono::duration;
using std::chrono::system_clock;
using std::chrono::time_point;
using namespace boost::interprocess;
/* Globals */
struct SubscribedGesture {
string name;
string lager;
string expanded_lager;
pid_t pid;
int dl_distance;
float dl_distance_pct;
};
string g_gesture_string;
vector<SubscribedGesture> g_subscribed_gestures;
#define d(i,j) dd[(i) * (m+2) + (j) ]
#define min(x,y) ((x) < (y) ? (x) : (y))
#define min3(a,b,c) ((a)< (b) ? min((a),(c)) : min((b),(c)))
#define min4(a,b,c,d) ((a)< (b) ? min3((a),(c),(d)) : min3((b),(c),(d)))
int DPrint(int* dd, int n, int m) {
int i, j;
for (i = 0; i < n + 2; i++) {
for (j = 0; j < m + 2; j++) {
printf("%02d ", d(i, j));
}
printf("\n");
}
printf("\n");
return 0;
}
int DlDist2(const char *s, const char* t, int n, int m) {
int *dd, *DA;
int i, j, cost, k, i1, j1, DB;
int infinity = n + m;
DA = (int*) malloc(256 * sizeof(int));
dd = (int*) malloc((n + 2) * (m + 2) * sizeof(int));
d(0,0)= infinity;
for (i = 0; i < n + 1; i++) {
d(i+1,1)= i;
d(i+1,0) = infinity;
}
for (j = 0; j < m + 1; j++) {
d(1,j+1)= j;
d(0,j+1) = infinity;
}
//DPrint(dd,n,m);
for (k = 0; k < 256; k++)
DA[k] = 0;
for (i = 1; i < n + 1; i++) {
DB = 0;
for (j = 1; j < m + 1; j++) {
i1 = DA[t[j - 1]];
j1 = DB;
cost = ((s[i - 1] == t[j - 1]) ? 0 : 1);
if (cost == 0)
DB = j;
d(i+1,j+1)=
min4(d(i,j)+cost,
d(i+1,j) + 1,
d(i,j+1)+1,
d(i1,j1) + (i-i1-1) + 1 + (j-j1-1));
}
DA[s[i - 1]] = i;
//dprint(dd,n,m);
}
cost = d(n + 1, m + 1);
free(dd);
return cost;
}
/* New size must be a multiple of the original string size */
string ExpandString(const string& input_string, int new_size) {
stringstream output_string;
int length_multiplier = new_size / input_string.length();
vector<string> movement_pairs;
TokenizeString(input_string, movement_pairs, ".");
for (vector<string>::iterator it = movement_pairs.begin();
it < movement_pairs.end(); ++it) {
for (int i = 0; i < length_multiplier; i++) {
output_string << *it << ".";
}
}
return output_string.str();
}
bool GestureEntryLessThan(SubscribedGesture i, SubscribedGesture j) {
return (i.dl_distance_pct < j.dl_distance_pct);
}
void UpdateSubscribedGestureDistance(
struct SubscribedGesture& subscribed_gesture) {
const string input_gesture = g_gesture_string;
int gesture_length_least_common_multiple = boost::math::lcm(
input_gesture.length(), subscribed_gesture.lager.length());
string expanded_input_string = ExpandString(
input_gesture, gesture_length_least_common_multiple);
subscribed_gesture.expanded_lager = ExpandString(
subscribed_gesture.lager, gesture_length_least_common_multiple);
subscribed_gesture.dl_distance = DlDist2(
expanded_input_string.c_str(), subscribed_gesture.expanded_lager.c_str(),
expanded_input_string.length(),
subscribed_gesture.expanded_lager.length());
subscribed_gesture.dl_distance_pct = (subscribed_gesture.dl_distance * 100.0f)
/ subscribed_gesture.expanded_lager.length();
cout << subscribed_gesture.name << endl << "\t" << subscribed_gesture.lager
<< endl;
cout << "Distance: " << subscribed_gesture.dl_distance_pct << "% ("
<< subscribed_gesture.dl_distance << " D-L ops)" << endl;
cout << endl;
}
void UpdateSubscribedGestureDistances() {
for (vector<SubscribedGesture>::iterator it = g_subscribed_gestures.begin();
it < g_subscribed_gestures.end(); ++it) {
UpdateSubscribedGestureDistance(*it);
}
}
void DrawMatchingGestures(const SubscribedGesture& closest_gesture) {
stringstream viewer_command;
string viewer_command_prefix =
"lager_viewer --gesture ";
string hide_output_suffix = " > /dev/null";
cout << "Drawing input gesture..." << endl;
viewer_command << viewer_command_prefix << g_gesture_string
<< hide_output_suffix;
system(viewer_command.str().c_str());
cout << "Drawing gesture match..." << endl;
viewer_command.str("");
viewer_command << viewer_command_prefix << closest_gesture.lager
<< hide_output_suffix;
system(viewer_command.str().c_str());
}
bool IsSingleSensorGesture() {
vector<string> movement_pairs;
TokenizeString(g_gesture_string, movement_pairs, ".");
bool sensor_0_moved = false;
bool sensor_1_moved = false;
for (vector<string>::iterator it = movement_pairs.begin();
it < movement_pairs.end(); ++it) {
// Check if sensor 0 movement is present
if ((*it).c_str()[0] != '_') {
sensor_0_moved = true;
}
// Check if sensor 0 movement is present
if ((*it).c_str()[0] != '_') {
sensor_1_moved = true;
}
// If we already found movement on both sensors, there is no need to keep checking
if (sensor_0_moved && sensor_1_moved) {
break;
}
}
return (!sensor_0_moved || !sensor_1_moved);
}
int GetMillisecondsUntilNow(const time_point<system_clock> &last_time) {
time_point<system_clock> now = system_clock::now();
return duration<double, std::milli>(now - last_time).count();
}
void RecognizeGesture(bool use_gestures_file, bool draw_gestures) {
if (g_subscribed_gestures.size() == 0) {
cout << "No gesture subscriptions." << endl;
return;
}
int lowestDistance;
bool match_found = false;
unsigned int num_milliseconds_since_recognition_start = 0;
time_point<system_clock> recognition_start_time = system_clock::now();
int gesture_distance_threshold_pct =
IsSingleSensorGesture() ?
SINGLE_SENSOR_GESTURE_DISTANCE_THRESHOLD_PCT :
DUAL_SENSOR_GESTURE_DISTANCE_THRESHOLD_PCT;
cout << " ________________________________ " << endl;
cout << "| |" << endl;
cout << "| RECOGNIZING... |" << endl;
cout << "|________________________________|" << endl;
cout << " " << endl;
UpdateSubscribedGestureDistances();
SubscribedGesture closest_gesture = *min_element(
g_subscribed_gestures.begin(), g_subscribed_gestures.end(),
GestureEntryLessThan);
match_found = closest_gesture.dl_distance_pct
<= gesture_distance_threshold_pct;
num_milliseconds_since_recognition_start = GetMillisecondsUntilNow(
recognition_start_time);
if (match_found) {
cout << " ________________________________ " << endl;
cout << "| |" << endl;
cout << "| MATCH FOUND! |" << endl;
cout << "|________________________________|" << endl;
cout << " " << endl;
} else {
cout << endl;
cout << "NO MATCH." << endl;
}
cout << endl;
cout << "Closest gesture:\t" << closest_gesture.name << endl;
cout << endl;
cout << "Distance:\t\t" << closest_gesture.dl_distance_pct << "% ("
<< closest_gesture.dl_distance << " D-L ops)" << endl;
cout << "Threshold:\t\t" << gesture_distance_threshold_pct << "%" << endl;
cout << endl;
cout << "Recognition time: \t" << num_milliseconds_since_recognition_start
<< "ms" << endl;
cout << endl;
if (match_found) {
if (draw_gestures) {
DrawMatchingGestures(closest_gesture);
}
if (!use_gestures_file && closest_gesture.pid != 0) {
SendDetectedGestureMessage(closest_gesture.name, closest_gesture.pid);
}
}
cout << endl << endl;
;
}
/*****************************************************************************
*
Callback handler
*
*****************************************************************************/
bool DetermineButtonUse(const int argc, const char** argv) {
bool use_buttons;
if ((argc > 1)
&& (std::string(argv[1]).find("--use_buttons") != std::string::npos)) {
cout << "Gesture detection will be active while pressing a button." << endl;
use_buttons = true;
} else {
cout << "Gesture detection will be active at all times." << endl;
use_buttons = false;
}
return use_buttons;
}
bool DetermineGesturesFileUse(const int argc, const char** argv) {
bool use_gestures_file;
if ((argc > 1)
&& (std::string(argv[1]).find("--use_gestures_file") != std::string::npos)) {
cout << "Comparing input to gestures in a file." << endl;
use_gestures_file = true;
} else {
cout << "Comparing input to subscribed gestures." << endl;
use_gestures_file = false;
}
return use_gestures_file;
}
bool DetermineGestureDrawing(const int argc, const char** argv) {
bool draw_gestures;
if ((argc > 1)
&& (std::string(argv[1]).find("--draw_gestures") != std::string::npos)) {
cout << "Using lager_viewer to draw input and subscribed gestures." << endl;
draw_gestures = true;
} else {
cout << "Will not draw gestures." << endl;
draw_gestures = false;
}
return draw_gestures;
}
void AddSubscribedGestures() {
while (true) {
GestureSubscriptionMessage message = GetGestureSubscriptionMessage();
cout << "Adding subscription..." << endl;
cout << endl;
cout << "Name: \"" << message.gesture_name() << "\"" << endl;
cout << "Lager: \"" << message.gesture_lager() << endl;
cout << endl;
SubscribedGesture subscription;
subscription.name = message.gesture_name();
subscription.lager = message.gesture_lager();
subscription.pid = message.pid();
g_subscribed_gestures.push_back(subscription);
}
}
int GetSubscribedGesturesFromFile() {
ifstream gestures_file;
string current_line;
cout << "Current gesture" << endl << "\t" << g_gesture_string << endl
<< endl;
gestures_file.open("gestures.dat");
if (!gestures_file.is_open()) {
return RECOGNIZER_ERROR;
}
while (getline(gestures_file, current_line)) {
string name, lager;
stringstream ss(current_line);
ss >> name >> lager;
SubscribedGesture new_gesture;
ss >> new_gesture.name >> new_gesture.lager;
new_gesture.pid = 0;
g_subscribed_gestures.push_back(new_gesture);
}
return RECOGNIZER_NO_ERROR;
}
int main(int argc, const char *argv[]) {
//printf("Generates strings for movement of tracker %s\n\n", TRACKER_SERVER);
struct timespec sleep_interval = { 0, MAIN_SLEEP_INTERVAL_MICROSECONDS };
bool use_buttons = DetermineButtonUse(argc, argv);
bool use_gestures_file = DetermineGesturesFileUse(argc, argv);
bool draw_gestures = DetermineGestureDrawing(argc, argv);
LagerConverter* lager_converter = LagerConverter::Instance();
if (use_gestures_file) {
GetSubscribedGesturesFromFile();
} else {
CreateGestureSubscriptionQueue();
boost::thread subscription_updater(AddSubscribedGestures);
}
cout << " ________________________________ " << endl;
cout << "| |" << endl;
cout << "| COLLECTING DATA... |" << endl;
cout << "|________________________________|" << endl;
cout << " " << endl;
lager_converter->SetUseButtons(use_buttons);
lager_converter->Start();
while(true) {
g_gesture_string = lager_converter->BlockingGetLagerString();
RecognizeGesture(use_gestures_file, draw_gestures);
}
} /* main */
<|endoftext|>
|
<commit_before>// this file defines the itkBasicFiltersTest for the test driver
// and all it expects is that you have a function called RegisterTests
#include "itkTestMain.h"
void RegisterTests()
{
REGISTER_TEST(itkAntiAliasBinaryImageFilterTest );
REGISTER_TEST(itkBinaryMinMaxCurvatureFlowImageFilterTest );
REGISTER_TEST(itkBinaryMask3DMeshSourceTest );
REGISTER_TEST(itkBallonForce3DFilterTest );
REGISTER_TEST(itkCannySegmentationLevelSetImageFilterTest );
REGISTER_TEST(itkCurvatureFlowTest );
REGISTER_TEST(itkDemonsRegistrationFilterTest );
REGISTER_TEST(itkExtractMeshConnectedRegionsTest );
REGISTER_TEST(itkFastMarchingTest );
REGISTER_TEST(itkFastMarchingExtensionImageFilterTest );
//REGISTER_TEST(itkFEMRegistrationFilterTest );
REGISTER_TEST(itkGeodesicActiveContoursTest );
REGISTER_TEST(itkGradientVectorFlowImageFilterTest );
REGISTER_TEST(itkSimpleFuzzyConnectednessScalarImageFilterTest );
REGISTER_TEST(itkHistogramMatchingImageFilterTest );
REGISTER_TEST(itkImageMomentsTest );
REGISTER_TEST(itkImageRegistrationMethodTest );
REGISTER_TEST(itkImageRegistrationMethodTest_1 );
REGISTER_TEST(itkImageRegistrationMethodTest_2 );
REGISTER_TEST(itkImageRegistrationMethodTest_3 );
REGISTER_TEST(itkImageRegistrationMethodTest_4 );
REGISTER_TEST(itkImageRegistrationMethodTest_5 );
REGISTER_TEST(itkImageRegistrationMethodTest_6 );
REGISTER_TEST(itkImageRegistrationMethodTest_7 );
REGISTER_TEST(itkImageRegistrationMethodTest_8 );
REGISTER_TEST(itkImageRegistrationMethodTest_9 );
REGISTER_TEST(itkImageRegistrationMethodTest_10);
REGISTER_TEST(itkImageRegistrationMethodTest_11);
REGISTER_TEST(itkImageRegistrationMethodTest_12);
REGISTER_TEST(itkImageRegistrationMethodTest_13);
REGISTER_TEST(itkImageRegistrationMethodTest_14);
REGISTER_TEST(itkImageRegistrationMethodTest_15);
REGISTER_TEST(itkInterpolateTest );
REGISTER_TEST(itkKalmanLinearEstimatorTest );
REGISTER_TEST(itkKmeansModelEstimatorTest );
REGISTER_TEST(itkLaplacianSegmentationLevelSetImageFilterTest );
REGISTER_TEST(itkLevelSetShapeDetectionTest );
REGISTER_TEST(itkMattesMutualInformationImageToImageMetricTest );
REGISTER_TEST(itkMeanSquaresImageMetricTest );
REGISTER_TEST(itkMinimumMaximumImageCalculatorTest );
REGISTER_TEST(itkMinMaxCurvatureFlowImageFilterTest );
REGISTER_TEST(itkMRFImageFilterTest );
REGISTER_TEST(itkMultiResolutionPyramidImageFilterTest );
REGISTER_TEST(itkRecursiveMultiResolutionPyramidImageFilterTest );
REGISTER_TEST(itkMultiResolutionPDEDeformableRegistrationTest );
REGISTER_TEST(itkMultiResolutionImageRegistrationMethodTest);
REGISTER_TEST(itkMultiResolutionImageRegistrationMethodTest_1 );
REGISTER_TEST(itkMultiResolutionImageRegistrationMethodTest_2 );
REGISTER_TEST(itkMutualInformationMetricTest );
REGISTER_TEST(itkNewTest );
REGISTER_TEST(itkNormalizedCorrelationImageMetricTest );
REGISTER_TEST(itkOtsuThresholdImageCalculatorTest );
REGISTER_TEST(itkPatternIntensityImageMetricTest );
REGISTER_TEST(itkRegionGrow2DTest );
REGISTER_TEST(itkSupervisedImageClassifierTest);
REGISTER_TEST(itkGibbsTest );
REGISTER_TEST(itkDeformableTest );
REGISTER_TEST(itk2DDeformableTest );
REGISTER_TEST(itkSphereMeshSourceTest );
REGISTER_TEST(itkThresholdSegmentationLevelSetImageFilterTest );
REGISTER_TEST(itkVectorFuzzyConnectednessImageFilterTest );
REGISTER_TEST(itkVoronoiDiagram2DTest );
REGISTER_TEST(itkVoronoiSegmentationImageFilterTest );
REGISTER_TEST(itkWatershedImageFilterTest );
}
<commit_msg>ERR: removed BallonForce3DFilterTest.<commit_after>// this file defines the itkBasicFiltersTest for the test driver
// and all it expects is that you have a function called RegisterTests
#include "itkTestMain.h"
void RegisterTests()
{
REGISTER_TEST(itkAntiAliasBinaryImageFilterTest );
REGISTER_TEST(itkBinaryMinMaxCurvatureFlowImageFilterTest );
REGISTER_TEST(itkBinaryMask3DMeshSourceTest );
REGISTER_TEST(itkCannySegmentationLevelSetImageFilterTest );
REGISTER_TEST(itkCurvatureFlowTest );
REGISTER_TEST(itkDemonsRegistrationFilterTest );
REGISTER_TEST(itkExtractMeshConnectedRegionsTest );
REGISTER_TEST(itkFastMarchingTest );
REGISTER_TEST(itkFastMarchingExtensionImageFilterTest );
//REGISTER_TEST(itkFEMRegistrationFilterTest );
REGISTER_TEST(itkGeodesicActiveContoursTest );
REGISTER_TEST(itkGradientVectorFlowImageFilterTest );
REGISTER_TEST(itkSimpleFuzzyConnectednessScalarImageFilterTest );
REGISTER_TEST(itkHistogramMatchingImageFilterTest );
REGISTER_TEST(itkImageMomentsTest );
REGISTER_TEST(itkImageRegistrationMethodTest );
REGISTER_TEST(itkImageRegistrationMethodTest_1 );
REGISTER_TEST(itkImageRegistrationMethodTest_2 );
REGISTER_TEST(itkImageRegistrationMethodTest_3 );
REGISTER_TEST(itkImageRegistrationMethodTest_4 );
REGISTER_TEST(itkImageRegistrationMethodTest_5 );
REGISTER_TEST(itkImageRegistrationMethodTest_6 );
REGISTER_TEST(itkImageRegistrationMethodTest_7 );
REGISTER_TEST(itkImageRegistrationMethodTest_8 );
REGISTER_TEST(itkImageRegistrationMethodTest_9 );
REGISTER_TEST(itkImageRegistrationMethodTest_10);
REGISTER_TEST(itkImageRegistrationMethodTest_11);
REGISTER_TEST(itkImageRegistrationMethodTest_12);
REGISTER_TEST(itkImageRegistrationMethodTest_13);
REGISTER_TEST(itkImageRegistrationMethodTest_14);
REGISTER_TEST(itkImageRegistrationMethodTest_15);
REGISTER_TEST(itkInterpolateTest );
REGISTER_TEST(itkKalmanLinearEstimatorTest );
REGISTER_TEST(itkKmeansModelEstimatorTest );
REGISTER_TEST(itkLaplacianSegmentationLevelSetImageFilterTest );
REGISTER_TEST(itkLevelSetShapeDetectionTest );
REGISTER_TEST(itkMattesMutualInformationImageToImageMetricTest );
REGISTER_TEST(itkMeanSquaresImageMetricTest );
REGISTER_TEST(itkMinimumMaximumImageCalculatorTest );
REGISTER_TEST(itkMinMaxCurvatureFlowImageFilterTest );
REGISTER_TEST(itkMRFImageFilterTest );
REGISTER_TEST(itkMultiResolutionPyramidImageFilterTest );
REGISTER_TEST(itkRecursiveMultiResolutionPyramidImageFilterTest );
REGISTER_TEST(itkMultiResolutionPDEDeformableRegistrationTest );
REGISTER_TEST(itkMultiResolutionImageRegistrationMethodTest);
REGISTER_TEST(itkMultiResolutionImageRegistrationMethodTest_1 );
REGISTER_TEST(itkMultiResolutionImageRegistrationMethodTest_2 );
REGISTER_TEST(itkMutualInformationMetricTest );
REGISTER_TEST(itkNewTest );
REGISTER_TEST(itkNormalizedCorrelationImageMetricTest );
REGISTER_TEST(itkOtsuThresholdImageCalculatorTest );
REGISTER_TEST(itkPatternIntensityImageMetricTest );
REGISTER_TEST(itkRegionGrow2DTest );
REGISTER_TEST(itkSupervisedImageClassifierTest);
REGISTER_TEST(itkGibbsTest );
REGISTER_TEST(itkDeformableTest );
REGISTER_TEST(itk2DDeformableTest );
REGISTER_TEST(itkSphereMeshSourceTest );
REGISTER_TEST(itkThresholdSegmentationLevelSetImageFilterTest );
REGISTER_TEST(itkVectorFuzzyConnectednessImageFilterTest );
REGISTER_TEST(itkVoronoiDiagram2DTest );
REGISTER_TEST(itkVoronoiSegmentationImageFilterTest );
REGISTER_TEST(itkWatershedImageFilterTest );
}
<|endoftext|>
|
<commit_before>/*=========================================================================
Program: Insight Segmentation & Registration Toolkit
Module: itkLargeImageWriteReadTest.cxx
Language: C++
Date: $Date$xgoto-l
Version: $Revision$
Copyright (c) 2002 Insight Consortium. All rights reserved.
See ITKCopyright.txt or http://www.itk.org/HTML/Copyright.htm for details.
This software is distributed WITHOUT ANY WARRANTY; without even
the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR
PURPOSE. See the above copyright notices for more information.
=========================================================================*/
#if defined(_MSC_VER)
#pragma warning ( disable : 4786 )
#endif
#include "itkImage.h"
#include "itkImageFileWriter.h"
#include "itkImageFileReader.h"
#include "itkImageRegionIterator.h"
#include "itkTimeProbesCollectorBase.h"
int itkLargeImageWriteReadTest(int ac, char* av[])
{
if (ac < 3)
{
std::cout << "usage: itkIOTests itkLargeImageWriteReadTest outputFileName numberOfPixelsInOneDimension" << std::endl;
return EXIT_FAILURE;
}
typedef unsigned short PixelType;
typedef itk::Image<PixelType,2> ImageType;
typedef itk::ImageFileWriter< ImageType > WriterType;
typedef itk::ImageFileReader< ImageType > ReaderType;
ImageType::Pointer image = ImageType::New();
ImageType::RegionType region;
ImageType::IndexType index;
ImageType::SizeType size;
itk::TimeProbesCollectorBase chronometer;
const unsigned long numberOfPixelsInOneDimension = atol( av[2] );
size.Fill( numberOfPixelsInOneDimension );
index.Fill(0);
region.SetSize(size);
region.SetIndex(index);
image->SetRegions(region);
const unsigned long sizeInMegaBytes =
static_cast< unsigned long >(
( sizeof(PixelType) * numberOfPixelsInOneDimension * numberOfPixelsInOneDimension ) /
( 1024.0 * 1024.0 ) );
std::cout << "Trying to allocate an image of size " << sizeInMegaBytes << " Mb " << std::endl;
chronometer.Start("Allocate");
image->Allocate();
chronometer.Stop("Allocate");
std::cout << "Initializing pixel values " << std::endl;
typedef itk::ImageRegionIterator< ImageType > IteratorType;
typedef itk::ImageRegionConstIterator< ImageType > ConstIteratorType;
IteratorType itr( image, region );
itr.GoToBegin();
PixelType pixelValue = itk::NumericTraits< PixelType >::Zero;
chronometer.Start("Initializing");
while( !itr.IsAtEnd() )
{
itr.Set( pixelValue );
++pixelValue;
++itr;
}
chronometer.Stop("Initializing");
std::cout << "Trying to write the image to disk" << std::endl;
try
{
WriterType::Pointer writer = WriterType::New();
writer->SetInput(image);
writer->SetFileName(av[1]);
chronometer.Start("Write");
writer->Update();
chronometer.Stop("Write");
}
catch (itk::ExceptionObject &ex)
{
std::cout << ex << std::endl;
return EXIT_FAILURE;
}
std::cout << "Trying to read the image back from disk" << std::endl;
ReaderType::Pointer reader = ReaderType::New();
reader->SetFileName(av[1]);
try
{
chronometer.Start("Read");
reader->Update();
chronometer.Stop("Read");
}
catch (itk::ExceptionObject &ex)
{
std::cout << ex << std::endl;
return EXIT_FAILURE;
}
ImageType::ConstPointer readImage = reader->GetOutput();
ConstIteratorType ritr( readImage, region );
IteratorType oitr( image, region );
ritr.GoToBegin();
oitr.GoToBegin();
std::cout << "Comparing the pixel values.. :" << std::endl;
chronometer.Start("Compare");
while( !ritr.IsAtEnd() )
{
if( oitr.Get() != ritr.Get() )
{
std::cerr << "Pixel comparison failed at index = " << oitr.GetIndex() << std::endl;
return EXIT_FAILURE;
}
++oitr;
++ritr;
}
chronometer.Stop("Compare");
chronometer.Report( std::cout );
std::cout << std::endl;
std::cout << "Test PASSED !" << std::endl;
return EXIT_SUCCESS;
}
<commit_msg>ENH: Now testing the values of the pixels in both the created image and the read image. Before we were assuming that the values assigned to pixels were correct. Now we check for them.<commit_after>/*=========================================================================
Program: Insight Segmentation & Registration Toolkit
Module: itkLargeImageWriteReadTest.cxx
Language: C++
Date: $Date$xgoto-l
Version: $Revision$
Copyright (c) 2002 Insight Consortium. All rights reserved.
See ITKCopyright.txt or http://www.itk.org/HTML/Copyright.htm for details.
This software is distributed WITHOUT ANY WARRANTY; without even
the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR
PURPOSE. See the above copyright notices for more information.
=========================================================================*/
#if defined(_MSC_VER)
#pragma warning ( disable : 4786 )
#endif
#include "itkImage.h"
#include "itkImageFileWriter.h"
#include "itkImageFileReader.h"
#include "itkImageRegionIterator.h"
#include "itkTimeProbesCollectorBase.h"
int itkLargeImageWriteReadTest(int ac, char* av[])
{
if (ac < 3)
{
std::cout << "usage: itkIOTests itkLargeImageWriteReadTest outputFileName numberOfPixelsInOneDimension" << std::endl;
return EXIT_FAILURE;
}
typedef unsigned short PixelType;
typedef itk::Image<PixelType,2> ImageType;
typedef itk::ImageFileWriter< ImageType > WriterType;
typedef itk::ImageFileReader< ImageType > ReaderType;
ImageType::Pointer image = ImageType::New();
ImageType::RegionType region;
ImageType::IndexType index;
ImageType::SizeType size;
itk::TimeProbesCollectorBase chronometer;
const unsigned long numberOfPixelsInOneDimension = atol( av[2] );
size.Fill( numberOfPixelsInOneDimension );
index.Fill(0);
region.SetSize(size);
region.SetIndex(index);
image->SetRegions(region);
const unsigned long sizeInMegaBytes =
static_cast< unsigned long >(
( sizeof(PixelType) * numberOfPixelsInOneDimension * numberOfPixelsInOneDimension ) /
( 1024.0 * 1024.0 ) );
std::cout << "Trying to allocate an image of size " << sizeInMegaBytes << " Mb " << std::endl;
chronometer.Start("Allocate");
image->Allocate();
chronometer.Stop("Allocate");
std::cout << "Initializing pixel values " << std::endl;
typedef itk::ImageRegionIterator< ImageType > IteratorType;
typedef itk::ImageRegionConstIterator< ImageType > ConstIteratorType;
IteratorType itr( image, region );
itr.GoToBegin();
PixelType pixelValue = itk::NumericTraits< PixelType >::Zero;
chronometer.Start("Initializing");
while( !itr.IsAtEnd() )
{
itr.Set( pixelValue );
++pixelValue;
++itr;
}
chronometer.Stop("Initializing");
std::cout << "Trying to write the image to disk" << std::endl;
try
{
WriterType::Pointer writer = WriterType::New();
writer->SetInput(image);
writer->SetFileName(av[1]);
chronometer.Start("Write");
writer->Update();
chronometer.Stop("Write");
}
catch (itk::ExceptionObject &ex)
{
std::cout << ex << std::endl;
return EXIT_FAILURE;
}
std::cout << "Trying to read the image back from disk" << std::endl;
ReaderType::Pointer reader = ReaderType::New();
reader->SetFileName(av[1]);
try
{
chronometer.Start("Read");
reader->Update();
chronometer.Stop("Read");
}
catch (itk::ExceptionObject &ex)
{
std::cout << ex << std::endl;
return EXIT_FAILURE;
}
ImageType::ConstPointer readImage = reader->GetOutput();
ConstIteratorType ritr( readImage, region );
IteratorType oitr( image, region );
ritr.GoToBegin();
oitr.GoToBegin();
std::cout << "Comparing the pixel values.. :" << std::endl;
pixelValue = itk::NumericTraits< PixelType >::Zero;
chronometer.Start("Compare");
while( !ritr.IsAtEnd() )
{
if( ( oitr.Get() != ritr.Get() ) || ( oitr.Get() != pixelValue ) )
{
std::cerr << "Pixel comparison failed at index = " << oitr.GetIndex() << std::endl;
std::cerr << "Expected pixel value " << pixelValue << std::endl;
std::cerr << "Original Image pixel value " << oitr.Get() << std::endl;
std::cerr << "Read Image pixel value " << ritr.Get() << std::endl;
return EXIT_FAILURE;
}
++pixelValue;
++oitr;
++ritr;
}
chronometer.Stop("Compare");
chronometer.Report( std::cout );
std::cout << std::endl;
std::cout << "Test PASSED !" << std::endl;
return EXIT_SUCCESS;
}
<|endoftext|>
|
<commit_before>/*************************************************************************
*
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* Copyright 2008 by Sun Microsystems, Inc.
*
* OpenOffice.org - a multi-platform office productivity suite
*
* $RCSfile: RptObject.hxx,v $
* $Revision: 1.7 $
*
* This file is part of OpenOffice.org.
*
* OpenOffice.org is free software: you can redistribute it and/or modify
* it under the terms of the GNU Lesser General Public License version 3
* only, as published by the Free Software Foundation.
*
* OpenOffice.org is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Lesser General Public License version 3 for more details
* (a copy is included in the LICENSE file that accompanied this code).
*
* You should have received a copy of the GNU Lesser General Public License
* version 3 along with OpenOffice.org. If not, see
* <http://www.openoffice.org/license.html>
* for a copy of the LGPLv3 License.
*
************************************************************************/
#ifndef _REPORT_RPTUIOBJ_HXX
#define _REPORT_RPTUIOBJ_HXX
#include <svx/svdoole2.hxx>
#include <svx/svdouno.hxx>
#include <comphelper/processfactory.hxx>
#include <com/sun/star/beans/XPropertyChangeListener.hpp>
#include <com/sun/star/container/XContainerListener.hpp>
#include <com/sun/star/report/XReportComponent.hpp>
#include <com/sun/star/report/XSection.hpp>
#include <svx/svdocirc.hxx>
#include <svx/svdogrp.hxx>
#include <svx/svdoashp.hxx>
#include <comphelper/stl_types.hxx>
#include <comphelper/implementationreference.hxx>
#include "dllapi.h"
namespace rptui
{
typedef ::std::multimap< sal_Int16, ::rtl::OUString, ::std::less< sal_Int16 > > IndexToNameMap;
enum DlgEdHintKind
{
RPTUI_HINT_UNKNOWN,
RPTUI_HINT_WINDOWSCROLLED,
RPTUI_HINT_LAYERCHANGED,
RPTUI_HINT_OBJORDERCHANGED,
RPTUI_HINT_SELECTIONCHANGED
};
class OUnoObject;
class REPORTDESIGN_DLLPUBLIC DlgEdHint: public SfxHint
{
private:
DlgEdHintKind eHintKind;
OUnoObject* pDlgEdObj;
DlgEdHint(DlgEdHint&);
void operator =(DlgEdHint&);
public:
TYPEINFO();
DlgEdHint( DlgEdHintKind eHint );
virtual ~DlgEdHint();
inline DlgEdHintKind GetKind() const { return eHintKind; }
inline OUnoObject* GetObject() const { return pDlgEdObj; }
};
class OReportPage;
class OPropertyMediator;
class REPORTDESIGN_DLLPUBLIC OObjectBase
{
public:
typedef ::comphelper::ImplementationReference<OPropertyMediator,::com::sun::star::beans::XPropertyChangeListener> TMediator;
protected:
mutable TMediator m_xMediator;
mutable ::com::sun::star::uno::Reference< ::com::sun::star::beans::XPropertyChangeListener> m_xPropertyChangeListener;
//mutable ::com::sun::star::uno::Reference< ::com::sun::star::beans::XPropertyChangeListener>
mutable ::com::sun::star::uno::Reference< ::com::sun::star::report::XReportComponent> m_xReportComponent;
::com::sun::star::uno::Reference< ::com::sun::star::container::XContainerListener> m_xContainerListener;
::com::sun::star::uno::Reference< ::com::sun::star::report::XSection> m_xSection;
::com::sun::star::uno::Reference< ::com::sun::star::uno::XInterface > m_xKeepShapeAlive;
::rtl::OUString m_sComponentName;
sal_Bool m_bIsListening;
OObjectBase(const ::com::sun::star::uno::Reference< ::com::sun::star::report::XReportComponent>& _xComponent);
OObjectBase(const ::rtl::OUString& _sComponentName);
virtual ~OObjectBase();
inline sal_Bool isListening() const { return m_bIsListening; }
void SetPropsFromRect(const Rectangle& _rRect);
virtual void SetSnapRectImpl(const Rectangle& _rRect) = 0;
virtual SdrPage* GetImplPage() const = 0;
virtual void SetObjectItemHelper(const SfxPoolItem& rItem);
sal_Bool IsInside(const Rectangle& _rRect,const Point& rPnt,USHORT nTol) const;
/** called by instances of derived classes to implement their overloading of getUnoShape
*/
::com::sun::star::uno::Reference< ::com::sun::star::uno::XInterface >
getUnoShapeOf( SdrObject& _rSdrObject );
private:
static void ensureSdrObjectOwnership(
const ::com::sun::star::uno::Reference< ::com::sun::star::uno::XInterface >& _rxShape );
public:
void StartListening();
void EndListening(sal_Bool bRemoveListener = sal_True);
// PropertyChangeListener
virtual void _propertyChange( const ::com::sun::star::beans::PropertyChangeEvent& evt ) throw(::com::sun::star::uno::RuntimeException);
sal_Bool supportsService( const ::rtl::OUString& _sServiceName ) const;
::com::sun::star::uno::Reference< ::com::sun::star::report::XReportComponent> getReportComponent() const;
virtual ::com::sun::star::uno::Reference< ::com::sun::star::beans::XPropertySet> getAwtComponent();
inline void setOldParent(const ::com::sun::star::uno::Reference< ::com::sun::star::report::XSection>& _xSection) { m_xSection = _xSection; }
inline ::com::sun::star::uno::Reference< ::com::sun::star::report::XSection> getOldParent() const { return m_xSection;}
::com::sun::star::uno::Reference< ::com::sun::star::report::XSection> getSection() const;
inline const ::rtl::OUString getServiceName() const { return m_sComponentName; }
/** releases the reference to our UNO shape (m_xKeepShapeAlive)
*/
void releaseUnoShape() { m_xKeepShapeAlive.clear(); }
static SdrObject* createObject(const ::com::sun::star::uno::Reference< ::com::sun::star::report::XReportComponent>& _xComponent);
static sal_uInt16 getObjectType(const ::com::sun::star::uno::Reference< ::com::sun::star::report::XReportComponent>& _xComponent);
};
//============================================================================
// OCustomShape
//============================================================================
class REPORTDESIGN_DLLPUBLIC OCustomShape: public SdrObjCustomShape , public OObjectBase
{
friend class OReportPage;
friend class DlgEdFactory;
public:
static OCustomShape* Create( const ::com::sun::star::uno::Reference< ::com::sun::star::report::XReportComponent>& _xComponent )
{
return new OCustomShape( _xComponent );
}
protected:
OCustomShape(const ::com::sun::star::uno::Reference< ::com::sun::star::report::XReportComponent>& _xComponent);
OCustomShape(const ::rtl::OUString& _sComponentName);
virtual void NbcMove( const Size& rSize );
virtual void NbcResize(const Point& rRef, const Fraction& xFact, const Fraction& yFact);
virtual void NbcSetLogicRect(const Rectangle& rRect);
virtual FASTBOOL EndCreate(SdrDragStat& rStat, SdrCreateCmd eCmd);
virtual void SetSnapRectImpl(const Rectangle& _rRect);
virtual SdrPage* GetImplPage() const;
void SetObjectItemHelper(const SfxPoolItem& rItem);
public:
TYPEINFO();
virtual ~OCustomShape();
virtual sal_Int32 GetStep() const;
virtual SdrObject* CheckHit(const Point& rPnt,USHORT nTol,const SetOfByte*) const;
virtual ::com::sun::star::uno::Reference< ::com::sun::star::beans::XPropertySet> getAwtComponent();
virtual ::com::sun::star::uno::Reference< ::com::sun::star::uno::XInterface > getUnoShape();
virtual UINT16 GetObjIdentifier() const;
virtual UINT32 GetObjInventor() const;
};
//============================================================================
// OOle2Obj
//============================================================================
class REPORTDESIGN_DLLPUBLIC OOle2Obj: public SdrOle2Obj , public OObjectBase
{
friend class OReportPage;
friend class DlgEdFactory;
UINT16 m_nType;
void impl_createDataProvider_nothrow( const ::com::sun::star::uno::Reference< ::com::sun::star::frame::XModel>& _xModel);
public:
static OOle2Obj* Create( const ::com::sun::star::uno::Reference< ::com::sun::star::report::XReportComponent>& _xComponent,UINT16 _nType )
{
return new OOle2Obj( _xComponent,_nType );
}
OOle2Obj(const ::rtl::OUString& _sComponentName,const svt::EmbeddedObjectRef& rNewObjRef, const String& rNewObjName, const Rectangle& rNewRect,UINT16 _nType, FASTBOOL bFrame_=FALSE);
protected:
OOle2Obj(const ::com::sun::star::uno::Reference< ::com::sun::star::report::XReportComponent>& _xComponent,UINT16 _nType);
OOle2Obj(const ::rtl::OUString& _sComponentName,UINT16 _nType);
virtual void NbcMove( const Size& rSize );
virtual void NbcResize(const Point& rRef, const Fraction& xFact, const Fraction& yFact);
virtual void NbcSetLogicRect(const Rectangle& rRect);
virtual FASTBOOL EndCreate(SdrDragStat& rStat, SdrCreateCmd eCmd);
virtual void SetSnapRectImpl(const Rectangle& _rRect);
virtual SdrPage* GetImplPage() const;
public:
TYPEINFO();
virtual ~OOle2Obj();
virtual sal_Int32 GetStep() const;
virtual SdrObject* CheckHit(const Point& rPnt,USHORT nTol,const SetOfByte*) const;
virtual ::com::sun::star::uno::Reference< ::com::sun::star::beans::XPropertySet> getAwtComponent();
virtual ::com::sun::star::uno::Reference< ::com::sun::star::uno::XInterface > getUnoShape();
virtual UINT16 GetObjIdentifier() const;
virtual UINT32 GetObjInventor() const;
// Clone() soll eine komplette Kopie des Objektes erzeugen.
virtual SdrObject* Clone() const;
void initializeChart( const ::com::sun::star::uno::Reference< ::com::sun::star::frame::XModel>& _xModel);
};
//============================================================================
// OUnoObject
//============================================================================
class REPORTDESIGN_DLLPUBLIC OUnoObject: public SdrUnoObj , public OObjectBase
{
friend class OReportPage;
friend class OObjectBase;
friend class DlgEdFactory;
sal_uInt16 m_nObjectType;
protected:
OUnoObject(const ::rtl::OUString& _sComponentName
,const ::rtl::OUString& rModelName
,sal_uInt16 _nObjectType);
OUnoObject( const ::com::sun::star::uno::Reference< ::com::sun::star::report::XReportComponent>& _xComponent
,const ::rtl::OUString& rModelName
,sal_uInt16 _nObjectType);
virtual ~OUnoObject();
virtual void NbcMove( const Size& rSize );
virtual void NbcResize(const Point& rRef, const Fraction& xFact, const Fraction& yFact);
virtual void NbcSetLogicRect(const Rectangle& rRect);
virtual FASTBOOL EndCreate(SdrDragStat& rStat, SdrCreateCmd eCmd);
virtual void SetSnapRectImpl(const Rectangle& _rRect);
virtual SdrPage* GetImplPage() const;
public:
TYPEINFO();
virtual sal_Int32 GetStep() const;
virtual SdrObject* CheckHit(const Point& rPnt,USHORT nTol,const SetOfByte*) const;
virtual void _propertyChange( const ::com::sun::star::beans::PropertyChangeEvent& evt ) throw(::com::sun::star::uno::RuntimeException);
/** creates the m_xMediator when it doesn't already exist.
@param _bReverse when set to <TRUE/> then the properties from the uno control will be copied into report control
*/
void CreateMediator(sal_Bool _bReverse = sal_False);
virtual ::com::sun::star::uno::Reference< ::com::sun::star::beans::XPropertySet> getAwtComponent();
static ::rtl::OUString GetDefaultName(const OUnoObject* _pObj);
virtual ::com::sun::star::uno::Reference< ::com::sun::star::uno::XInterface > getUnoShape();
virtual UINT16 GetObjIdentifier() const;
virtual UINT32 GetObjInventor() const;
virtual SdrObject* Clone() const;
};
//============================================================================
} // rptui
//============================================================================
#endif // _REPORT_RPTUIOBJ_HXX
<commit_msg>INTEGRATION: CWS dba31a (1.7.12); FILE MERGED 2008/07/15 08:38:54 fs 1.7.12.1: remove unused code Issue number: #i91592# Submitted by: cmc@openoffice.org Reviewed by: frank.schoenheit@sun.com<commit_after>/*************************************************************************
*
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* Copyright 2008 by Sun Microsystems, Inc.
*
* OpenOffice.org - a multi-platform office productivity suite
*
* $RCSfile: RptObject.hxx,v $
* $Revision: 1.8 $
*
* This file is part of OpenOffice.org.
*
* OpenOffice.org is free software: you can redistribute it and/or modify
* it under the terms of the GNU Lesser General Public License version 3
* only, as published by the Free Software Foundation.
*
* OpenOffice.org is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Lesser General Public License version 3 for more details
* (a copy is included in the LICENSE file that accompanied this code).
*
* You should have received a copy of the GNU Lesser General Public License
* version 3 along with OpenOffice.org. If not, see
* <http://www.openoffice.org/license.html>
* for a copy of the LGPLv3 License.
*
************************************************************************/
#ifndef _REPORT_RPTUIOBJ_HXX
#define _REPORT_RPTUIOBJ_HXX
#include <svx/svdoole2.hxx>
#include <svx/svdouno.hxx>
#include <comphelper/processfactory.hxx>
#include <com/sun/star/beans/XPropertyChangeListener.hpp>
#include <com/sun/star/container/XContainerListener.hpp>
#include <com/sun/star/report/XReportComponent.hpp>
#include <com/sun/star/report/XSection.hpp>
#include <svx/svdocirc.hxx>
#include <svx/svdogrp.hxx>
#include <svx/svdoashp.hxx>
#include <comphelper/stl_types.hxx>
#include <comphelper/implementationreference.hxx>
#include "dllapi.h"
namespace rptui
{
typedef ::std::multimap< sal_Int16, ::rtl::OUString, ::std::less< sal_Int16 > > IndexToNameMap;
enum DlgEdHintKind
{
RPTUI_HINT_UNKNOWN,
RPTUI_HINT_WINDOWSCROLLED,
RPTUI_HINT_LAYERCHANGED,
RPTUI_HINT_OBJORDERCHANGED,
RPTUI_HINT_SELECTIONCHANGED
};
class OUnoObject;
class REPORTDESIGN_DLLPUBLIC DlgEdHint: public SfxHint
{
private:
DlgEdHintKind eHintKind;
OUnoObject* pDlgEdObj;
DlgEdHint(DlgEdHint&);
void operator =(DlgEdHint&);
public:
TYPEINFO();
DlgEdHint( DlgEdHintKind eHint );
virtual ~DlgEdHint();
inline DlgEdHintKind GetKind() const { return eHintKind; }
inline OUnoObject* GetObject() const { return pDlgEdObj; }
};
class OReportPage;
class OPropertyMediator;
class REPORTDESIGN_DLLPUBLIC OObjectBase
{
public:
typedef ::comphelper::ImplementationReference<OPropertyMediator,::com::sun::star::beans::XPropertyChangeListener> TMediator;
protected:
mutable TMediator m_xMediator;
mutable ::com::sun::star::uno::Reference< ::com::sun::star::beans::XPropertyChangeListener> m_xPropertyChangeListener;
//mutable ::com::sun::star::uno::Reference< ::com::sun::star::beans::XPropertyChangeListener>
mutable ::com::sun::star::uno::Reference< ::com::sun::star::report::XReportComponent> m_xReportComponent;
::com::sun::star::uno::Reference< ::com::sun::star::container::XContainerListener> m_xContainerListener;
::com::sun::star::uno::Reference< ::com::sun::star::report::XSection> m_xSection;
::com::sun::star::uno::Reference< ::com::sun::star::uno::XInterface > m_xKeepShapeAlive;
::rtl::OUString m_sComponentName;
sal_Bool m_bIsListening;
OObjectBase(const ::com::sun::star::uno::Reference< ::com::sun::star::report::XReportComponent>& _xComponent);
OObjectBase(const ::rtl::OUString& _sComponentName);
virtual ~OObjectBase();
inline sal_Bool isListening() const { return m_bIsListening; }
void SetPropsFromRect(const Rectangle& _rRect);
virtual void SetSnapRectImpl(const Rectangle& _rRect) = 0;
virtual SdrPage* GetImplPage() const = 0;
virtual void SetObjectItemHelper(const SfxPoolItem& rItem);
sal_Bool IsInside(const Rectangle& _rRect,const Point& rPnt,USHORT nTol) const;
/** called by instances of derived classes to implement their overloading of getUnoShape
*/
::com::sun::star::uno::Reference< ::com::sun::star::uno::XInterface >
getUnoShapeOf( SdrObject& _rSdrObject );
private:
static void ensureSdrObjectOwnership(
const ::com::sun::star::uno::Reference< ::com::sun::star::uno::XInterface >& _rxShape );
public:
void StartListening();
void EndListening(sal_Bool bRemoveListener = sal_True);
// PropertyChangeListener
virtual void _propertyChange( const ::com::sun::star::beans::PropertyChangeEvent& evt ) throw(::com::sun::star::uno::RuntimeException);
sal_Bool supportsService( const ::rtl::OUString& _sServiceName ) const;
::com::sun::star::uno::Reference< ::com::sun::star::report::XReportComponent> getReportComponent() const;
virtual ::com::sun::star::uno::Reference< ::com::sun::star::beans::XPropertySet> getAwtComponent();
inline void setOldParent(const ::com::sun::star::uno::Reference< ::com::sun::star::report::XSection>& _xSection) { m_xSection = _xSection; }
inline ::com::sun::star::uno::Reference< ::com::sun::star::report::XSection> getOldParent() const { return m_xSection;}
::com::sun::star::uno::Reference< ::com::sun::star::report::XSection> getSection() const;
inline const ::rtl::OUString getServiceName() const { return m_sComponentName; }
/** releases the reference to our UNO shape (m_xKeepShapeAlive)
*/
void releaseUnoShape() { m_xKeepShapeAlive.clear(); }
static SdrObject* createObject(const ::com::sun::star::uno::Reference< ::com::sun::star::report::XReportComponent>& _xComponent);
static sal_uInt16 getObjectType(const ::com::sun::star::uno::Reference< ::com::sun::star::report::XReportComponent>& _xComponent);
};
//============================================================================
// OCustomShape
//============================================================================
class REPORTDESIGN_DLLPUBLIC OCustomShape: public SdrObjCustomShape , public OObjectBase
{
friend class OReportPage;
friend class DlgEdFactory;
public:
static OCustomShape* Create( const ::com::sun::star::uno::Reference< ::com::sun::star::report::XReportComponent>& _xComponent )
{
return new OCustomShape( _xComponent );
}
protected:
OCustomShape(const ::com::sun::star::uno::Reference< ::com::sun::star::report::XReportComponent>& _xComponent);
OCustomShape(const ::rtl::OUString& _sComponentName);
virtual void NbcMove( const Size& rSize );
virtual void NbcResize(const Point& rRef, const Fraction& xFact, const Fraction& yFact);
virtual void NbcSetLogicRect(const Rectangle& rRect);
virtual FASTBOOL EndCreate(SdrDragStat& rStat, SdrCreateCmd eCmd);
virtual void SetSnapRectImpl(const Rectangle& _rRect);
virtual SdrPage* GetImplPage() const;
void SetObjectItemHelper(const SfxPoolItem& rItem);
public:
TYPEINFO();
virtual ~OCustomShape();
virtual sal_Int32 GetStep() const;
virtual SdrObject* CheckHit(const Point& rPnt,USHORT nTol,const SetOfByte*) const;
virtual ::com::sun::star::uno::Reference< ::com::sun::star::beans::XPropertySet> getAwtComponent();
virtual ::com::sun::star::uno::Reference< ::com::sun::star::uno::XInterface > getUnoShape();
virtual UINT16 GetObjIdentifier() const;
virtual UINT32 GetObjInventor() const;
};
//============================================================================
// OOle2Obj
//============================================================================
class REPORTDESIGN_DLLPUBLIC OOle2Obj: public SdrOle2Obj , public OObjectBase
{
friend class OReportPage;
friend class DlgEdFactory;
UINT16 m_nType;
void impl_createDataProvider_nothrow( const ::com::sun::star::uno::Reference< ::com::sun::star::frame::XModel>& _xModel);
public:
static OOle2Obj* Create( const ::com::sun::star::uno::Reference< ::com::sun::star::report::XReportComponent>& _xComponent,UINT16 _nType )
{
return new OOle2Obj( _xComponent,_nType );
}
protected:
OOle2Obj(const ::com::sun::star::uno::Reference< ::com::sun::star::report::XReportComponent>& _xComponent,UINT16 _nType);
OOle2Obj(const ::rtl::OUString& _sComponentName,UINT16 _nType);
virtual void NbcMove( const Size& rSize );
virtual void NbcResize(const Point& rRef, const Fraction& xFact, const Fraction& yFact);
virtual void NbcSetLogicRect(const Rectangle& rRect);
virtual FASTBOOL EndCreate(SdrDragStat& rStat, SdrCreateCmd eCmd);
virtual void SetSnapRectImpl(const Rectangle& _rRect);
virtual SdrPage* GetImplPage() const;
public:
TYPEINFO();
virtual ~OOle2Obj();
virtual sal_Int32 GetStep() const;
virtual SdrObject* CheckHit(const Point& rPnt,USHORT nTol,const SetOfByte*) const;
virtual ::com::sun::star::uno::Reference< ::com::sun::star::beans::XPropertySet> getAwtComponent();
virtual ::com::sun::star::uno::Reference< ::com::sun::star::uno::XInterface > getUnoShape();
virtual UINT16 GetObjIdentifier() const;
virtual UINT32 GetObjInventor() const;
// Clone() soll eine komplette Kopie des Objektes erzeugen.
virtual SdrObject* Clone() const;
void initializeChart( const ::com::sun::star::uno::Reference< ::com::sun::star::frame::XModel>& _xModel);
};
//============================================================================
// OUnoObject
//============================================================================
class REPORTDESIGN_DLLPUBLIC OUnoObject: public SdrUnoObj , public OObjectBase
{
friend class OReportPage;
friend class OObjectBase;
friend class DlgEdFactory;
sal_uInt16 m_nObjectType;
protected:
OUnoObject(const ::rtl::OUString& _sComponentName
,const ::rtl::OUString& rModelName
,sal_uInt16 _nObjectType);
OUnoObject( const ::com::sun::star::uno::Reference< ::com::sun::star::report::XReportComponent>& _xComponent
,const ::rtl::OUString& rModelName
,sal_uInt16 _nObjectType);
virtual ~OUnoObject();
virtual void NbcMove( const Size& rSize );
virtual void NbcResize(const Point& rRef, const Fraction& xFact, const Fraction& yFact);
virtual void NbcSetLogicRect(const Rectangle& rRect);
virtual FASTBOOL EndCreate(SdrDragStat& rStat, SdrCreateCmd eCmd);
virtual void SetSnapRectImpl(const Rectangle& _rRect);
virtual SdrPage* GetImplPage() const;
public:
TYPEINFO();
virtual sal_Int32 GetStep() const;
virtual SdrObject* CheckHit(const Point& rPnt,USHORT nTol,const SetOfByte*) const;
virtual void _propertyChange( const ::com::sun::star::beans::PropertyChangeEvent& evt ) throw(::com::sun::star::uno::RuntimeException);
/** creates the m_xMediator when it doesn't already exist.
@param _bReverse when set to <TRUE/> then the properties from the uno control will be copied into report control
*/
void CreateMediator(sal_Bool _bReverse = sal_False);
virtual ::com::sun::star::uno::Reference< ::com::sun::star::beans::XPropertySet> getAwtComponent();
static ::rtl::OUString GetDefaultName(const OUnoObject* _pObj);
virtual ::com::sun::star::uno::Reference< ::com::sun::star::uno::XInterface > getUnoShape();
virtual UINT16 GetObjIdentifier() const;
virtual UINT32 GetObjInventor() const;
virtual SdrObject* Clone() const;
};
//============================================================================
} // rptui
//============================================================================
#endif // _REPORT_RPTUIOBJ_HXX
<|endoftext|>
|
<commit_before>#include "text/table.h"
#include "text/cmdline.h"
#include "cortex/tensor.h"
#include "math/random.hpp"
#include "tensor/random.hpp"
#include "tensor/conv2d_cpp.hpp"
#include "tensor/conv2d_dyn.hpp"
#include "tensor/conv2d_eig.hpp"
#include "tensor/corr2d_cpp.hpp"
#include "tensor/corr2d_dyn.hpp"
#include "tensor/corr2d_egb.hpp"
#include "tensor/corr2d_egr.hpp"
#include "text/table_row_mark.h"
#include "cortex/util/measure.hpp"
#include <iostream>
namespace
{
using namespace cortex;
std::string make_header(const int isize, const int ksize)
{
const int osize = isize - ksize + 1;
return "(" +
text::to_string(isize) + "x" +
text::to_string(isize) + " @ " +
text::to_string(ksize) + "x" +
text::to_string(ksize) + " -> " +
text::to_string(osize) + "x" +
text::to_string(osize) +
")";
}
template
<
typename tmatrix
>
void make_matrices(const int isize, const int ksize,
tmatrix& idata, tmatrix& kdata, tmatrix& odata)
{
const int osize = isize - ksize + 1;
math::random_t<typename tmatrix::Scalar> rng(-1.0 / isize, 1.0 / isize);
idata.resize(isize, isize);
kdata.resize(ksize, ksize);
odata.resize(osize, osize);
tensor::set_random(idata, rng);
tensor::set_random(kdata, rng);
tensor::set_random(odata, rng);
}
template
<
typename top,
typename tmatrixi,
typename tmatrixk,
typename tmatrixo
>
auto measure_op(const top& op,
const tmatrixi& idata, const tmatrixk& kdata, tmatrixo&& odata, const size_t trials = 16)
{
return cortex::measure_robustly_nsec([&] ()
{
op(idata, kdata, odata);
}, trials);
}
template
<
typename tmatrix
>
void test_config_conv(const int isize, const int ksize, text::table_row_t& row, const size_t trials = 16)
{
tmatrix idata, kdata, odata;
make_matrices(isize, ksize, idata, kdata, odata);
tmatrix odata_ret = odata;
row << measure_op(tensor::conv2d_eig_t(), idata, kdata, odata_ret, trials).count();
row << measure_op(tensor::conv2d_cpp_t(), idata, kdata, odata_ret, trials).count();
row << measure_op(tensor::conv2d_dot_t(), idata, kdata, odata_ret, trials).count();
row << measure_op(tensor::conv2d_dot_dyn_t(), idata, kdata, odata_ret, trials).count();
row << measure_op(tensor::conv2d_mad_t(), idata, kdata, odata_ret, trials).count();
row << measure_op(tensor::conv2d_mad_dyn_t(), idata, kdata, odata_ret, trials).count();
row << measure_op(tensor::conv2d_dyn_t(), idata, kdata, odata_ret, trials).count();
}
template
<
typename tmatrix
>
void test_config_corr(const int isize, const int ksize, text::table_row_t& row, const size_t trials = 16)
{
tmatrix idata, kdata, odata;
make_matrices(isize, ksize, idata, kdata, odata);
tmatrix idata_ret = idata;
row << measure_op(tensor::corr2d_egb_t(), odata, kdata, idata_ret, trials).count();
row << measure_op(tensor::corr2d_egr_t(), odata, kdata, idata_ret, trials).count();
row << measure_op(tensor::corr2d_cpp_t(), odata, kdata, idata_ret, trials).count();
row << measure_op(tensor::corr2d_mdk_t(), odata, kdata, idata_ret, trials).count();
row << measure_op(tensor::corr2d_mdk_dyn_t(), odata, kdata, idata_ret, trials).count();
row << measure_op(tensor::corr2d_mdo_t(), odata, kdata, idata_ret, trials).count();
row << measure_op(tensor::corr2d_mdo_dyn_t(), odata, kdata, idata_ret, trials).count();
row << measure_op(tensor::corr2d_dyn_t(), odata, kdata, idata_ret, trials).count();
}
}
int main(int argc, char* argv[])
{
using namespace cortex;
const int min_isize = 4;
const int max_isize = 48;
const int min_ksize = 3;
const int max_ksize = 15;
// parse the command line
text::cmdline_t cmdline("benchmark 2D convolutions & correlations");
cmdline.add("", "conv", "benchmark convolutions");
cmdline.add("", "corr", "benchmark correlations");
cmdline.process(argc, argv);
// check arguments and options
const auto has_conv = cmdline.has("conv");
const auto has_corr = cmdline.has("corr");
if (!has_conv && !has_corr)
{
cmdline.usage();
}
// convolutions
if (has_conv)
{
text::table_t table("size\\convolution [ns]");
table.header()
<< "eig"
<< "cpp"
<< "dot"
<< "dot-dyn"
<< "mad"
<< "mad-dyn"
<< "dyn";
for (int isize = min_isize; isize <= max_isize; ++ isize)
{
for (int ksize = min_ksize; ksize <= isize; ++ ksize)
{
const auto header = make_header(isize, ksize);
test_config_conv<matrix_t>(isize, ksize, table.append(header));
}
}
table.mark(text::make_table_mark_minimum_col<size_t>());
table.print(std::cout);
}
// correlations
if (has_corr)
{
text::table_t table("size\\correlation [ns]");
table.header()
<< "egb"
<< "egr"
<< "cpp"
<< "mdk"
<< "mdk-dyn"
<< "mdo"
<< "mdo-dyn"
<< "dyn";
for (int isize = min_isize; isize <= max_isize; ++ isize)
{
for (int ksize = min_ksize; ksize <= std::min(isize, max_ksize); ksize += 2)
{
const auto header = make_header(isize, ksize);
test_config_corr<matrix_t>(isize, ksize, table.append(header));
}
}
table.mark(text::make_table_mark_minimum_col<size_t>());
table.print(std::cout);
}
return EXIT_SUCCESS;
}
<commit_msg>benchmark convolutions similarly to the ones used in convnets<commit_after>#include "text/table.h"
#include "text/cmdline.h"
#include "cortex/tensor.h"
#include "math/random.hpp"
#include "tensor/random.hpp"
#include "tensor/conv2d_cpp.hpp"
#include "tensor/conv2d_dyn.hpp"
#include "tensor/conv2d_eig.hpp"
#include "tensor/corr2d_cpp.hpp"
#include "tensor/corr2d_dyn.hpp"
#include "tensor/corr2d_egb.hpp"
#include "tensor/corr2d_egr.hpp"
#include "text/table_row_mark.h"
#include "cortex/util/measure.hpp"
#include <set>
#include <iostream>
namespace
{
using namespace cortex;
std::string make_header(const int isize, const int ksize)
{
const int osize = isize - ksize + 1;
return "(" +
text::to_string(isize) + "x" +
text::to_string(isize) + " @ " +
text::to_string(ksize) + "x" +
text::to_string(ksize) + " -> " +
text::to_string(osize) + "x" +
text::to_string(osize) +
")";
}
template
<
typename tmatrix
>
void make_matrices(const int isize, const int ksize,
tmatrix& idata, tmatrix& kdata, tmatrix& odata)
{
const int osize = isize - ksize + 1;
math::random_t<typename tmatrix::Scalar> rng(-1.0 / isize, 1.0 / isize);
idata.resize(isize, isize);
kdata.resize(ksize, ksize);
odata.resize(osize, osize);
tensor::set_random(idata, rng);
tensor::set_random(kdata, rng);
tensor::set_random(odata, rng);
}
template
<
typename top,
typename tmatrixi,
typename tmatrixk,
typename tmatrixo
>
auto measure_op(const top& op,
const tmatrixi& idata, const tmatrixk& kdata, tmatrixo&& odata, const size_t trials = 16)
{
return cortex::measure_robustly_nsec([&] ()
{
op(idata, kdata, odata);
}, trials);
}
template
<
typename tmatrix
>
void test_config_conv(const int isize, const int ksize, text::table_row_t& row, const size_t trials = 16)
{
tmatrix idata, kdata, odata;
make_matrices(isize, ksize, idata, kdata, odata);
tmatrix odata_ret = odata;
row << measure_op(tensor::conv2d_eig_t(), idata, kdata, odata_ret, trials).count();
row << measure_op(tensor::conv2d_cpp_t(), idata, kdata, odata_ret, trials).count();
row << measure_op(tensor::conv2d_dot_t(), idata, kdata, odata_ret, trials).count();
row << measure_op(tensor::conv2d_dot_dyn_t(), idata, kdata, odata_ret, trials).count();
row << measure_op(tensor::conv2d_mad_t(), idata, kdata, odata_ret, trials).count();
row << measure_op(tensor::conv2d_mad_dyn_t(), idata, kdata, odata_ret, trials).count();
row << measure_op(tensor::conv2d_dyn_t(), idata, kdata, odata_ret, trials).count();
}
template
<
typename tmatrix
>
void test_config_corr(const int isize, const int ksize, text::table_row_t& row, const size_t trials = 16)
{
tmatrix idata, kdata, odata;
make_matrices(isize, ksize, idata, kdata, odata);
tmatrix idata_ret = idata;
row << measure_op(tensor::corr2d_egb_t(), odata, kdata, idata_ret, trials).count();
row << measure_op(tensor::corr2d_egr_t(), odata, kdata, idata_ret, trials).count();
row << measure_op(tensor::corr2d_cpp_t(), odata, kdata, idata_ret, trials).count();
row << measure_op(tensor::corr2d_mdk_t(), odata, kdata, idata_ret, trials).count();
row << measure_op(tensor::corr2d_mdk_dyn_t(), odata, kdata, idata_ret, trials).count();
row << measure_op(tensor::corr2d_mdo_t(), odata, kdata, idata_ret, trials).count();
row << measure_op(tensor::corr2d_mdo_dyn_t(), odata, kdata, idata_ret, trials).count();
row << measure_op(tensor::corr2d_dyn_t(), odata, kdata, idata_ret, trials).count();
}
}
int main(int argc, char* argv[])
{
using namespace cortex;
const int min_isize = 4;
const int max_isize = 48;
const int min_ksize = 3;
const int max_ksize = 15;
// parse the command line
text::cmdline_t cmdline("benchmark 2D convolutions & correlations");
cmdline.add("", "conv", "benchmark convolutions");
cmdline.add("", "corr", "benchmark correlations");
cmdline.process(argc, argv);
// check arguments and options
const auto has_conv = cmdline.has("conv");
const auto has_corr = cmdline.has("corr");
if (!has_conv && !has_corr)
{
cmdline.usage();
}
// convolutions
if (has_conv)
{
text::table_t table("size\\convolution [ns]");
table.header()
<< "eig"
<< "cpp"
<< "dot"
<< "dot-dyn"
<< "mad"
<< "mad-dyn"
<< "dyn";
for (int isize = min_isize; isize <= max_isize; ++ isize)
{
std::set<int> ksizes;
for (int ksize = min_ksize; ksize <= std::min(isize, max_ksize); ksize += 2)
{
ksizes.insert(ksize);
ksizes.insert(isize - ksize + 1);
}
for (auto ksize : ksizes)
{
const auto header = make_header(isize, ksize);
test_config_conv<matrix_t>(isize, ksize, table.append(header));
}
}
table.mark(text::make_table_mark_minimum_col<size_t>());
table.print(std::cout);
}
// correlations
if (has_corr)
{
text::table_t table("size\\correlation [ns]");
table.header()
<< "egb"
<< "egr"
<< "cpp"
<< "mdk"
<< "mdk-dyn"
<< "mdo"
<< "mdo-dyn"
<< "dyn";
for (int isize = min_isize; isize <= max_isize; ++ isize)
{
for (int ksize = min_ksize; ksize <= std::min(isize, max_ksize); ksize += 2)
{
const auto header = make_header(isize, ksize);
test_config_corr<matrix_t>(isize, ksize, table.append(header));
}
}
table.mark(text::make_table_mark_minimum_col<size_t>());
table.print(std::cout);
}
return EXIT_SUCCESS;
}
<|endoftext|>
|
<commit_before>/*
* Copyright (C) 20011 Francesco Nwokeka <francesco.nwokeka@gmail.com>
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU Library General Public License version 2 as
* published by the Free Software Foundation
*
* 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 Library 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 "../common/global-presence.h"
#include "globalpresenceservice.h"
#include "globalpresencesource.h"
GlobalPresenceSource::GlobalPresenceSource(QObject* parent)
: DataContainer(parent)
, m_globalPresence(new GlobalPresence(parent))
{
// name of the source
setObjectName("GlobalPresence");
// global presence source data
setData("currentPresence", "");
setData("requestedPresence", "");
setData("presenceMessage", "");
}
GlobalPresenceSource::~GlobalPresenceSource()
{
}
Plasma::Service* GlobalPresenceSource::createService()
{
return new GlobalPresenceService(this);
}
GlobalPresence *GlobalPresenceSource::globalPresence() const
{
return m_globalPresence;
}
void GlobalPresenceSource::onCurrentPresenceChanged(Tp::Presence newPresence)
{
switch (newPresence.type()) {
case Tp::ConnectionPresenceTypeAvailable:
setData("currentPresence", "online");
break;
case Tp::ConnectionPresenceTypeAway:
setData("currentPresence", "away");
break;
case Tp::ConnectionPresenceTypeExtendedAway:
setData("currentPresence", "away-extended");
break;
case Tp::ConnectionPresenceTypeBusy:
setData("currentPresence", "busy");
break;
case Tp::ConnectionPresenceTypeHidden:
setData("currentPresence", "invisible");
break;
case Tp::ConnectionPresenceTypeOffline:
setData("currentPresence", "offline");
break;
default:
setData("currentPresence", "offline");
break;
}
setData("presenceMessage", newPresence.statusMessage());
}
void GlobalPresenceSource::setGlobalPresenceAccountManager(const Tp::AccountManagerPtr& accountMgr)
{
if (!accountMgr || !accountMgr->isValid()) {
kWarning() << "GlobalPresenceSource::setGlobalPresenceAccountManager Invalid account manager pointer";
return;
}
m_globalPresence->setAccountManager(accountMgr);
// setup connections and initialise with current data.
connect(m_globalPresence, SIGNAL(currentPresenceChanged(Tp::Presence)), this, SLOT(onCurrentPresenceChanged(Tp::Presence)));
onCurrentPresenceChanged(m_globalPresence->currentPresence());
}<commit_msg>Call checkForUpdate() when global presence changes.<commit_after>/*
* Copyright (C) 20011 Francesco Nwokeka <francesco.nwokeka@gmail.com>
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU Library General Public License version 2 as
* published by the Free Software Foundation
*
* 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 Library 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 "../common/global-presence.h"
#include "globalpresenceservice.h"
#include "globalpresencesource.h"
GlobalPresenceSource::GlobalPresenceSource(QObject* parent)
: DataContainer(parent)
, m_globalPresence(new GlobalPresence(parent))
{
// name of the source
setObjectName("GlobalPresence");
// global presence source data
setData("currentPresence", "");
setData("requestedPresence", "");
setData("presenceMessage", "");
}
GlobalPresenceSource::~GlobalPresenceSource()
{
}
Plasma::Service* GlobalPresenceSource::createService()
{
return new GlobalPresenceService(this);
}
GlobalPresence *GlobalPresenceSource::globalPresence() const
{
return m_globalPresence;
}
void GlobalPresenceSource::onCurrentPresenceChanged(Tp::Presence newPresence)
{
switch (newPresence.type()) {
case Tp::ConnectionPresenceTypeAvailable:
setData("currentPresence", "online");
break;
case Tp::ConnectionPresenceTypeAway:
setData("currentPresence", "away");
break;
case Tp::ConnectionPresenceTypeExtendedAway:
setData("currentPresence", "away-extended");
break;
case Tp::ConnectionPresenceTypeBusy:
setData("currentPresence", "busy");
break;
case Tp::ConnectionPresenceTypeHidden:
setData("currentPresence", "invisible");
break;
case Tp::ConnectionPresenceTypeOffline:
setData("currentPresence", "offline");
break;
default:
setData("currentPresence", "offline");
break;
}
setData("presenceMessage", newPresence.statusMessage());
checkForUpdate();
}
void GlobalPresenceSource::setGlobalPresenceAccountManager(const Tp::AccountManagerPtr& accountMgr)
{
if (!accountMgr || !accountMgr->isValid()) {
kWarning() << "GlobalPresenceSource::setGlobalPresenceAccountManager Invalid account manager pointer";
return;
}
m_globalPresence->setAccountManager(accountMgr);
// setup connections and initialise with current data.
connect(m_globalPresence, SIGNAL(currentPresenceChanged(Tp::Presence)), this, SLOT(onCurrentPresenceChanged(Tp::Presence)));
onCurrentPresenceChanged(m_globalPresence->currentPresence());
}<|endoftext|>
|
<commit_before>// Copyright (C) 2014 David Helkowski
// License GNU AGPLv3
#include<stdio.h>
#include<stdlib.h>
#include<string.h>
#include<unistd.h>
#include<libgen.h>
// Text to print before every hexidecimal byte representation
#define HEX_PREFIX "~"
// Characters to show normally instead of in hex
#define OK_CHARACTERS " {}\"'=-()<>,./_![]:&;?"
// Comment this out to disable acceptance of alpha-numeric characters
#define ALPHA_NUM
// Minimum number of sequential acceptable character needed to show text instead of hex
#define MIN_SEQUENCE 3
void phex( unsigned char let );
unsigned char let_okay( unsigned char let );
unsigned char accept[ 256 ];
int main( int argc, char *argv[] ) {
FILE *data_handle = 0;
bool showhelp = 0;
if( argc < 2 ) {
if( isatty( STDIN_FILENO ) ) {
showhelp = 1;
}
}
if( argc > 1 ) {
if( !strncmp( argv[1], "--help", 6 ) ) showhelp = 1;
data_handle = fopen( argv[1], "r" );
}
if( showhelp ) {
char *base = basename( argv[0] );
printf("=== Text Hack ===\nTakes input data and outputs specific characters as regular text and hex for other characters.\n\n");
printf("Characters configured to be output normally:\n");
#ifdef ALPHA_NUM
printf(" Alphanumerics\n" );
#endif
printf(" %s\n\n", OK_CHARACTERS );
printf("Usage:\n %s [filename]\n %s < filename\n", base, base );
return 0;
}
if( !data_handle ) {
return 1;
}
long pos = 0;
unsigned char stack[20];
for( int i=0;i<20;i++ ) {
stack[i] = 0;
}
for( int i=0;i<256;i++ ) {
accept[i] = 0;
}
unsigned char accept_these[] = OK_CHARACTERS;
for( int i=0;i<256;i++ ) {
unsigned char let = accept_these[ i ];
if( !let ) break;
accept[ let ] = 1;
}
unsigned char ok_cnt = 0;
while( 1 ) {
unsigned char let = fgetc( data_handle );
//printf(".");
//unsigned char ok = let_okay( let );
//if( ok ) printf("%c", let );
//else phex( let );
pos++;
// shift out the lowest char
unsigned char n_ago = stack[ 0 ];
for( int i=0;i<(MIN_SEQUENCE-1);i++ ) {
stack[ i ] = stack[ i + 1 ];
}
// push the new character onto the stack and pop the last one
stack[ MIN_SEQUENCE - 1 ] = let;
unsigned char num_ok = 0;
if( let_okay( n_ago ) ) {
num_ok++;
for( int i=0;i<=(MIN_SEQUENCE-1);i++ ) {
if( let_okay( stack[ i ] ) ) num_ok++;
else i=100;
}
}
else {
ok_cnt = 0;
}
if( ( num_ok + ok_cnt ) >= MIN_SEQUENCE ) {
printf( "%c", n_ago );
ok_cnt++;
}
else {
phex( n_ago );
ok_cnt = 0;
}
if( feof( data_handle ) ) break;
if( pos > 40000 ) break;
}
fclose( data_handle );
}
unsigned char let_okay( unsigned char let ) {
unsigned char ok = 0;
if( accept[ let ] ) ok = 1;
#ifdef ALPHA_NUM
if( let >= 'a' && let <= 'z' ) ok = 1;
if( let >= 'A' && let <= 'Z' ) ok = 1;
if( let >= '0' && let <= '9' ) ok = 1;
#endif
return ok;
}
void phex( unsigned char let ) {
unsigned char low = let % 16;
let -= low;
let /= 16;
// let is now just high portion
unsigned char hexmap[] = "0123456789ABCDEF";
//if( !let ) printf("~%c",hexmap[low]);
//else
printf( HEX_PREFIX "%c%c",hexmap[let],hexmap[low]);
//printf("(%hu,%hu[%c,%c]) ",let,low,hexmap[let],hexmap[low]);
}<commit_msg>Fix redirected input. Add error output when specified file does not exist. Correct potential bug with prefix character being interpreted as input to printf. Simplify phex function.<commit_after>// Copyright (C) 2014 David Helkowski
// License GNU AGPLv3
#include<stdio.h>
#include<stdlib.h>
#include<string.h>
#include<unistd.h>
#include<libgen.h>
// Text to print before every hexidecimal byte representation
#define HEX_PREFIX '~'
// Characters to show normally instead of in hex
#define OK_CHARACTERS " {}\"'=-()<>,./_![]:&;?"
// Comment this out to disable acceptance of alpha-numeric characters
#define ALPHA_NUM
// Minimum number of sequential acceptable character needed to show text instead of hex
#define MIN_SEQUENCE 3
void phex( unsigned char let );
unsigned char let_okay( unsigned char let );
unsigned char accept[ 256 ];
int main( int argc, char *argv[] ) {
FILE *data_handle = 0;
bool showhelp = 0;
if( argc < 2 ) {
if( isatty( STDIN_FILENO ) ) {
showhelp = 1;
}
else {
fprintf(stderr, "Reading input from redirection\n" );
data_handle = stdin;
}
}
if( argc > 1 ) {
if( !strncmp( argv[1], "--help", 6 ) ) showhelp = 1;
fprintf(stderr, "Using file '%s' for input\n", argv[1] );
data_handle = fopen( argv[1], "r" );
if( !data_handle ) {
fprintf(stderr, "File does not exist\n" );
return 1;
}
}
if( showhelp ) {
char *base = basename( argv[0] );
printf("=== Text Hack ===\nTakes input data and outputs specific characters as regular text and hex for other characters.\n\n");
printf("Characters configured to be output normally:\n");
#ifdef ALPHA_NUM
printf(" Alphanumerics\n" );
#endif
printf(" %s\n\n", OK_CHARACTERS );
printf("Usage:\n %s [filename]\n %s < filename\n", base, base );
return 0;
}
if( !data_handle ) {
return 1;
}
long pos = 0;
unsigned char stack[20];
memset( stack, 0, 20 );
// accept is a global
memset( accept, 0, 256 );
unsigned char accept_these[] = OK_CHARACTERS;
for( int i=0; i < sizeof( accept_these); i++ ) {
unsigned char let = accept_these[ i ];
accept[ let ] = 1;
}
unsigned char ok_cnt = 0;
while( 1 ) {
unsigned char let = fgetc( data_handle );
//printf(".");
//unsigned char ok = let_okay( let );
//if( ok ) printf("%c", let );
//else phex( let );
pos++;
// shift out the lowest char
unsigned char n_ago = stack[ 0 ];
for( int i=0;i<(MIN_SEQUENCE-1);i++ ) {
stack[ i ] = stack[ i + 1 ];
}
// push the new character onto the stack and pop the last one
stack[ MIN_SEQUENCE - 1 ] = let;
unsigned char num_ok = 0;
if( let_okay( n_ago ) ) {
num_ok++;
for( int i=0;i<=(MIN_SEQUENCE-1);i++ ) {
if( let_okay( stack[ i ] ) ) num_ok++;
else i=100;
}
}
else {
ok_cnt = 0;
}
if( ( num_ok + ok_cnt ) >= MIN_SEQUENCE ) {
printf( "%c", n_ago );
ok_cnt++;
}
else {
phex( n_ago );
ok_cnt = 0;
}
if( feof( data_handle ) ) break;
if( pos > 40000 ) break;
}
fclose( data_handle );
}
unsigned char let_okay( unsigned char let ) {
unsigned char ok = 0;
if( accept[ let ] ) ok = 1;
#ifdef ALPHA_NUM
if( let >= 'a' && let <= 'z' ) ok = 1;
if( let >= 'A' && let <= 'Z' ) ok = 1;
if( let >= '0' && let <= '9' ) ok = 1;
#endif
return ok;
}
void phex( unsigned char let ) {
printf( "%c%02X", HEX_PREFIX, let );
}<|endoftext|>
|
<commit_before>/*---------------------------------------------------------------------------------------------
* Copyright (c) Wilsen Hernandez. All rights reserved.
* Licensed under the MIT License. See License.txt in the project root for license information.
*--------------------------------------------------------------------------------------------*/
#ifndef _BILIST_HPP_
#define _BILIST_HPP_
#include <iostream>
#include "Binode.hpp"
template<class T>
class Bilist
{
private:
Binode<T> *_first, *_last;
int _length;
public:
Bilist() : _first(NULL), _last(NULL), _length(0) {};
Bilist(const Bilist&);
~Bilist() { clear(); };
bool empty() const { return _length == 0; };
int size() const { return _length; };
bool sorted() const;
T front() const;
T back() const;
void push_front(T);
void push_back(T);
void pop_front();
void pop_back();
void erase(int);
void change(T, int);
void clear();
void reverse();
void sort();
void operator=(const Bilist&);
bool operator>(const Bilist&);
bool operator<(const Bilist&);
bool operator==(const Bilist&);
bool operator>=(const Bilist&);
bool operator<=(const Bilist&);
};
template<class T>
Bilist<T>::Bilist(const Bilist& arg)
{
Binode<T> *argpivot = arg._first;
Binode<T> *iprev = NULL;
Binode<T> *add = NULL;
_first = NULL;
_length = arg._length;
while(argpivot)
{
add = new Binode<T>(argpivot->key());
if (_first)
{
add->set_prev(iprev);
iprev->set_next(add);
}
else
_first = add;
iprev = add;
argpivot = argpivot->next();
}
_last = add;
}
template<class T>
T Bilist<T>::front() const
{
if (_first)
return _first->key();
throw "Empty list";
}
template<class T>
T Bilist<T>::back() const
{
if(_last)
return _last->key();
throw "Empty list";
}
template<class T>
void Bilist<T>::push_front(T e)
{
Binode<T> *add = new Binode<T>(e);
if(_length == 0)
_last = add;
else
{
add->set_next(_first);
_first->set_prev(add);
}
_first = add;
_length++;
}
template<class T>
void Bilist<T>::push_back(T e)
{
Binode<T> *add = new Binode<T>(e);
if(_length == 0)
_first = add;
else
{
add->set_prev(_last);
_last->set_next(add);
}
_last = add;
_length++;
}
template<class T>
void Bilist<T>::pop_front()
{
if (!empty())
{
Binode<T> *aux = _first;
_first = aux->next();
_first->set_prev(NULL);
_length--;
delete aux;
}
else
throw "Empty list";
}
template<class T>
void Bilist<T>::pop_back()
{
if (!empty())
{
Binode<T> *aux = _last;
_last = aux->prev();
_last->set_next(NULL);
_length--;
delete aux;
}
else
throw "Empty list";
}
template<class T>
void Bilist<T>::erase(int index)
{
if (empty())
throw "Empty list";
else if (index < 1 || index > _length + 1)
throw "Index out of bounds";
else
{
Binode<T> *aux;
if (index == 1)
{
aux = _first;
_first = aux->next();
_first->set_prev(NULL);
}
else if (index == _length)
{
aux = _last;
_last = aux->prev();
_last->set_next(NULL);
}
else
{
Binode<T> *pivot = _first;
for (int i = 1; i < index; i++)
pivot = pivot->next();
aux = pivot;
aux->next()->set_prev(aux->prev());
aux->prev()->set_next(aux->next());
}
delete aux;
_length--;
}
}
template<class T>
void Bilist<T>::clear()
{
Binode<T> *pivot = _first;
Binode<T> *aux;
while (pivot)
{
aux = pivot;
pivot = pivot->next();
delete aux;
}
_first = NULL;
_last = NULL;
_length = 0;
}
#endif
<commit_msg>Reverse done<commit_after>/*---------------------------------------------------------------------------------------------
* Copyright (c) Wilsen Hernandez. All rights reserved.
* Licensed under the MIT License. See License.txt in the project root for license information.
*--------------------------------------------------------------------------------------------*/
#ifndef _BILIST_HPP_
#define _BILIST_HPP_
#include <iostream>
#include "Binode.hpp"
template<class T>
class Bilist
{
private:
Binode<T> *_first, *_last;
int _length;
public:
Bilist() : _first(NULL), _last(NULL), _length(0) {};
Bilist(const Bilist&);
~Bilist() { clear(); };
bool empty() const { return _length == 0; };
int size() const { return _length; };
bool sorted() const;
T front() const;
T back() const;
void push_front(T);
void push_back(T);
void pop_front();
void pop_back();
void erase(int);
void change(T, int);
void clear();
void reverse();
void sort();
void operator=(const Bilist&);
bool operator>(const Bilist&);
bool operator<(const Bilist&);
bool operator==(const Bilist&);
bool operator>=(const Bilist&);
bool operator<=(const Bilist&);
};
template<class T>
Bilist<T>::Bilist(const Bilist& arg)
{
Binode<T> *argpivot = arg._first;
Binode<T> *iprev = NULL;
Binode<T> *add = NULL;
_first = NULL;
_length = arg._length;
while(argpivot)
{
add = new Binode<T>(argpivot->key());
if (_first)
{
add->set_prev(iprev);
iprev->set_next(add);
}
else
_first = add;
iprev = add;
argpivot = argpivot->next();
}
_last = add;
}
template<class T>
T Bilist<T>::front() const
{
if (_first)
return _first->key();
throw "Empty list";
}
template<class T>
T Bilist<T>::back() const
{
if(_last)
return _last->key();
throw "Empty list";
}
template<class T>
void Bilist<T>::push_front(T e)
{
Binode<T> *add = new Binode<T>(e);
if(_length == 0)
_last = add;
else
{
add->set_next(_first);
_first->set_prev(add);
}
_first = add;
_length++;
}
template<class T>
void Bilist<T>::push_back(T e)
{
Binode<T> *add = new Binode<T>(e);
if(_length == 0)
_first = add;
else
{
add->set_prev(_last);
_last->set_next(add);
}
_last = add;
_length++;
}
template<class T>
void Bilist<T>::pop_front()
{
if (!empty())
{
Binode<T> *aux = _first;
_first = aux->next();
_first->set_prev(NULL);
_length--;
delete aux;
}
else
throw "Empty list";
}
template<class T>
void Bilist<T>::pop_back()
{
if (!empty())
{
Binode<T> *aux = _last;
_last = aux->prev();
_last->set_next(NULL);
_length--;
delete aux;
}
else
throw "Empty list";
}
template<class T>
void Bilist<T>::erase(int index)
{
if (empty())
throw "Empty list";
else if (index < 1 || index > _length + 1)
throw "Index out of bounds";
else
{
Binode<T> *aux;
if (index == 1)
{
aux = _first;
_first = aux->next();
_first->set_prev(NULL);
}
else if (index == _length)
{
aux = _last;
_last = aux->prev();
_last->set_next(NULL);
}
else
{
Binode<T> *pivot = _first;
for (int i = 1; i < index; i++)
pivot = pivot->next();
aux = pivot;
aux->next()->set_prev(aux->prev());
aux->prev()->set_next(aux->next());
}
delete aux;
_length--;
}
}
template<class T>
void Bilist<T>::clear()
{
Binode<T> *pivot = _first;
Binode<T> *aux;
while (pivot)
{
aux = pivot;
pivot = pivot->next();
delete aux;
}
_first = NULL;
_last = NULL;
_length = 0;
}
template<class T>
void Bilist<T>::reverse()
{
Binode<T> *current = _first;
Binode<T> *temp = NULL;
if (current)
_last = _first;
while (current)
{
temp = current->prev();
current->set_prev(current->next());
current->set_next(temp);
current = current->prev();
}
if (temp)
_first = temp->prev();
}
#endif
<|endoftext|>
|
<commit_before>//
// WebRequestExample.cpp
// ExampleApp
//
// Created by eeGeo on 30/04/2013.
// Copyright (c) 2013 eeGeo. All rights reserved.
//
#include "WebRequestExample.h"
#include <map>
#include <string>
using namespace Eegeo::Web;
namespace {
class ExternalHandlerType_NotPartOfPublicAPI : public IWebLoadRequestCompletionCallback
{
void operator()(IWebLoadRequest& webLoadRequest)
{
int* userData = (int*)webLoadRequest.GetUserData();
const std::string& url = webLoadRequest.GetUrl();
size_t responseBodySize = webLoadRequest.GetResourceData().size();
Eegeo_TTY("\nFinished Https POST of %s in a non member function of calling type, with user data %d - resource size of %ld\n",
url.c_str(), *userData, responseBodySize);
delete userData;
Eegeo_TTY("\nIs our fake token a valid key? Response was: %s\n", &webLoadRequest.GetResourceData()[0]);
}
};
ExternalHandlerType_NotPartOfPublicAPI externalHandler;
}
namespace Examples
{
WebRequestExample::WebRequestExample(IWebLoadRequestFactory& webRequestFactory)
:TWebLoadRequestCompletionCallback<WebRequestExample>(this, &WebRequestExample::RequestComplete)
,webRequestFactory(webRequestFactory)
{
}
void WebRequestExample::Start()
{
Eegeo_TTY("Making 3 Http GETs with integer labels as user data using a member as the handler...\n");
webRequestFactory.CreateGet("http://appstore.eegeo.com", *this, new int(1))->Load();
webRequestFactory.CreateGet("http://non-existent-example-host-1234.com", *this, new int(2))->Load();
webRequestFactory.CreateGet("http://wikipedia.org", *this, new int(3))->Load();
webRequestFactory.CreateGet("http://d2xvsc8j92rfya.cloudfront.net/non_existent_resource.hcff", *this, new int(4))->Load();
std::map<std::string, std::string> postData;
postData["token"] = "123456789";
Eegeo_TTY("Making Https POST to Eegeo appstore with invalid key (123456789), with integer labels as user data using a non-member as the handler...\n");
webRequestFactory.CreatePost("https://appstore.eegeo.com/validate", externalHandler, new int(5678), postData)->Load();
}
void WebRequestExample::RequestComplete(IWebLoadRequest& webLoadRequest)
{
int* userData = (int*)webLoadRequest.GetUserData();
const std::string& url = webLoadRequest.GetUrl();
size_t responseBodySize = webLoadRequest.GetResourceData().size();
int result = webLoadRequest.HttpStatusCode();
Eegeo_TTY("\nFinished Http GET of %s in a member function of calling type, result was %d, with user data %d - resource size of %ld\n",
url.c_str(), result, *userData, responseBodySize);
delete userData;
}
}
<commit_msg>Add http header example<commit_after>//
// WebRequestExample.cpp
// ExampleApp
//
// Created by eeGeo on 30/04/2013.
// Copyright (c) 2013 eeGeo. All rights reserved.
//
#include "WebRequestExample.h"
#include <map>
#include <string>
using namespace Eegeo::Web;
namespace {
class ExternalHandlerType_NotPartOfPublicAPI : public IWebLoadRequestCompletionCallback
{
void operator()(IWebLoadRequest& webLoadRequest)
{
int* userData = (int*)webLoadRequest.GetUserData();
const std::string& url = webLoadRequest.GetUrl();
size_t responseBodySize = webLoadRequest.GetResourceData().size();
Eegeo_TTY("\nFinished Https POST of %s in a non member function of calling type, with user data %d - resource size of %ld\n",
url.c_str(), *userData, responseBodySize);
delete userData;
Eegeo_TTY("\nIs our fake token a valid key? Response was: %s\n", &webLoadRequest.GetResourceData()[0]);
}
};
ExternalHandlerType_NotPartOfPublicAPI externalHandler;
}
namespace Examples
{
WebRequestExample::WebRequestExample(IWebLoadRequestFactory& webRequestFactory)
:TWebLoadRequestCompletionCallback<WebRequestExample>(this, &WebRequestExample::RequestComplete)
,webRequestFactory(webRequestFactory)
{
}
void WebRequestExample::Start()
{
Eegeo_TTY("Making 3 Http GETs with integer labels as user data using a member as the handler...\n");
webRequestFactory.CreateGet("http://appstore.eegeo.com", *this, new int(1))->Load();
webRequestFactory.CreateGet("http://non-existent-example-host-1234.com", *this, new int(2))->Load();
webRequestFactory.CreateGet("http://wikipedia.org", *this, new int(3))->Load();
webRequestFactory.CreateGet("http://d2xvsc8j92rfya.cloudfront.net/non_existent_resource.hcff", *this, new int(4))->Load();
std::map<std::string, std::string> postData;
postData["token"] = "123456789";
Eegeo_TTY("Making Https POST to Eegeo appstore with invalid key (123456789), with integer labels as user data using a non-member as the handler...\n");
webRequestFactory.CreatePost("https://appstore.eegeo.com/validate", externalHandler, new int(5678), postData)->Load();
std::map<std::string, std::string> httpHeaders;
httpHeaders["X-MyCustom-Header"] = "Hello World";
webRequestFactory.CreateGet("http://wikipedia.org", *this, new int(4), httpHeaders)->Load();
}
void WebRequestExample::RequestComplete(IWebLoadRequest& webLoadRequest)
{
int* userData = (int*)webLoadRequest.GetUserData();
const std::string& url = webLoadRequest.GetUrl();
size_t responseBodySize = webLoadRequest.GetResourceData().size();
int result = webLoadRequest.HttpStatusCode();
Eegeo_TTY("\nFinished Http GET of %s in a member function of calling type, result was %d, with user data %d - resource size of %ld\n",
url.c_str(), result, *userData, responseBodySize);
delete userData;
}
}
<|endoftext|>
|
<commit_before>// The libMesh Finite Element Library.
// Copyright (C) 2002-2012 Benjamin S. Kirk, John W. Peterson, Roy H. Stogner
// This library is free software; you can redistribute it and/or
// modify it under the terms of the GNU Lesser General Public
// License as published by the Free Software Foundation; either
// version 2.1 of the License, or (at your option) any later version.
// This library is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
// Lesser General Public License for more details.
// You should have received a copy of the GNU Lesser General Public
// License along with this library; if not, write to the Free Software
// Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
#include "libmesh/libmesh_config.h"
#ifdef LIBMESH_HAVE_TRIANGLE
// Local includes
#include "libmesh/mesh_triangle_holes.h"
namespace libMesh
{
//
// PolygonHole member functions
//
TriangleInterface::PolygonHole::PolygonHole(Point center, Real radius, unsigned int n_points)
: _center(center),
_radius(radius),
_n_points(n_points)
{}
unsigned int TriangleInterface::PolygonHole::n_points() const
{
return _n_points;
}
Point TriangleInterface::PolygonHole::point(const unsigned int n) const
{
// The nth point lies at the angle theta = 2 * pi * n / _n_points
const Real theta = static_cast<Real>(n) * 2.0 * libMesh::pi / static_cast<Real>(_n_points);
return Point(_center(0) + _radius*std::cos(theta), // x=r*cos(theta)
_center(1) + _radius*std::sin(theta), // y=r*sin(theta)
0.);
}
Point TriangleInterface::PolygonHole::inside() const
{
// The center of the hole is definitely inside.
return _center;
}
//
// ArbitraryHole member functions
//
TriangleInterface::ArbitraryHole::ArbitraryHole(const Point center,
const std::vector<Point>& points)
: _center(center),
_points(points)
{}
unsigned int TriangleInterface::ArbitraryHole::n_points() const
{
return _points.size();
}
Point TriangleInterface::ArbitraryHole::point(const unsigned int n) const
{
libmesh_assert_less (n, _points.size());
return _points[n];
}
Point TriangleInterface::ArbitraryHole::inside() const
{
return _center;
}
} // namespace libMesh
#endif // LIBMESH_HAVE_TRIANGLE
<commit_msg>Changes in mesh_triangle_holes.C for -Wshadow.<commit_after>// The libMesh Finite Element Library.
// Copyright (C) 2002-2012 Benjamin S. Kirk, John W. Peterson, Roy H. Stogner
// This library is free software; you can redistribute it and/or
// modify it under the terms of the GNU Lesser General Public
// License as published by the Free Software Foundation; either
// version 2.1 of the License, or (at your option) any later version.
// This library is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
// Lesser General Public License for more details.
// You should have received a copy of the GNU Lesser General Public
// License along with this library; if not, write to the Free Software
// Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
#include "libmesh/libmesh_config.h"
#ifdef LIBMESH_HAVE_TRIANGLE
// Local includes
#include "libmesh/mesh_triangle_holes.h"
namespace libMesh
{
//
// PolygonHole member functions
//
TriangleInterface::PolygonHole::PolygonHole(Point center, Real radius, unsigned int n_points_in)
: _center(center),
_radius(radius),
_n_points(n_points_in)
{}
unsigned int TriangleInterface::PolygonHole::n_points() const
{
return _n_points;
}
Point TriangleInterface::PolygonHole::point(const unsigned int n) const
{
// The nth point lies at the angle theta = 2 * pi * n / _n_points
const Real theta = static_cast<Real>(n) * 2.0 * libMesh::pi / static_cast<Real>(_n_points);
return Point(_center(0) + _radius*std::cos(theta), // x=r*cos(theta)
_center(1) + _radius*std::sin(theta), // y=r*sin(theta)
0.);
}
Point TriangleInterface::PolygonHole::inside() const
{
// The center of the hole is definitely inside.
return _center;
}
//
// ArbitraryHole member functions
//
TriangleInterface::ArbitraryHole::ArbitraryHole(const Point center,
const std::vector<Point>& points)
: _center(center),
_points(points)
{}
unsigned int TriangleInterface::ArbitraryHole::n_points() const
{
return _points.size();
}
Point TriangleInterface::ArbitraryHole::point(const unsigned int n) const
{
libmesh_assert_less (n, _points.size());
return _points[n];
}
Point TriangleInterface::ArbitraryHole::inside() const
{
return _center;
}
} // namespace libMesh
#endif // LIBMESH_HAVE_TRIANGLE
<|endoftext|>
|
<commit_before>/* This file is part of the KDE project
Copyright (C) 2006 Matthias Kretz <kretz@kde.org>
This library is free software; you can redistribute it and/or
modify it under the terms of the GNU Library General Public
License version 2 as published by the Free Software Foundation.
This library is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
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 "globalconfig.h"
#include <QSet>
#include <QList>
#include "factory.h"
#include "objectdescription.h"
#include "phonondefs_p.h"
namespace Phonon
{
GlobalConfig::GlobalConfig( QObject *parent )
: QObject( parent )
, m_config( KSharedConfig::openConfig( "phononrc", false, false ) )
{
}
GlobalConfig::~GlobalConfig()
{
}
QList<int> GlobalConfig::audioOutputDeviceListFor( Phonon::Category category ) const
{
const KConfigGroup configGroup( const_cast<KSharedConfig*>( m_config.data() ), "AudioOutputDevice" );
QSet<int> deviceIndexes;
QObject *backendObject = Factory::self()->backend();
pBACKEND_GET1( QSet<int>, deviceIndexes, "objectDescriptionIndexes", ObjectDescriptionType, Phonon::AudioOutputDeviceType );
QList<int> defaultList = deviceIndexes.toList();
qSort( defaultList );
QList<int> deviceList = configGroup.readEntry<QList<int> >( QLatin1String( "Category" ) +
QString::number( static_cast<int>( category ) ), defaultList );
return deviceList;
}
int GlobalConfig::audioOutputDeviceFor( Phonon::Category category ) const
{
return audioOutputDeviceListFor( category ).first();
}
} // namespace Phonon
#include "globalconfig.moc"
// vim: sw=4 ts=4 noet
<commit_msg>- separate device lists per backend - merge the device lists returned by the backend and KConfig<commit_after>/* This file is part of the KDE project
Copyright (C) 2006 Matthias Kretz <kretz@kde.org>
This library is free software; you can redistribute it and/or
modify it under the terms of the GNU Library General Public
License version 2 as published by the Free Software Foundation.
This library is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
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 "globalconfig.h"
#include <QSet>
#include <QList>
#include "factory.h"
#include "objectdescription.h"
#include "phonondefs_p.h"
namespace Phonon
{
GlobalConfig::GlobalConfig( QObject *parent )
: QObject( parent )
, m_config( KSharedConfig::openConfig( "phononrc", false, false ) )
{
}
GlobalConfig::~GlobalConfig()
{
}
QList<int> GlobalConfig::audioOutputDeviceListFor( Phonon::Category category ) const
{
//The devices need to be stored independently for every backend
//FIXME: backendName() is a translated string
const KConfigGroup configGroup( const_cast<KSharedConfig*>( m_config.data() ),
QLatin1String( "AudioOutputDevice" ) + Factory::self()->backendName() );
//First we lookup the available devices directly from the backend
QSet<int> deviceIndexes;
QObject *backendObject = Factory::self()->backend();
pBACKEND_GET1( QSet<int>, deviceIndexes, "objectDescriptionIndexes", ObjectDescriptionType, Phonon::AudioOutputDeviceType );
QList<int> defaultList = deviceIndexes.toList();
qSort( defaultList );
//Now the list from the phononrc file
QList<int> deviceList = configGroup.readEntry<QList<int> >( QLatin1String( "Category" ) +
QString::number( static_cast<int>( category ) ), defaultList );
QMutableListIterator<int> i( deviceList );
while( i.hasNext() )
if( 0 == defaultList.removeAll( i.next() ) )
//if there are devices in phononrc that the backend doesn't report, remove them from the list
i.remove();
//if the backend reports more devices that are not in phononrc append them to the list
deviceList += defaultList;
return deviceList;
}
int GlobalConfig::audioOutputDeviceFor( Phonon::Category category ) const
{
return audioOutputDeviceListFor( category ).first();
}
} // namespace Phonon
#include "globalconfig.moc"
// vim: sw=4 ts=4 noet
<|endoftext|>
|
<commit_before>/*
Copyright (c) 2016, oasi-adamay
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 glsCV 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 "stdafx.h"
/*-----------------------------------------------------------------------------
include
*/
#include "glsMacro.h"
#include "GlsMat.h"
#include "glsShader.h"
#include "glsFft.h"
#include "glsCopy.h" //tiled / untiled
#include "glsMerge.h"
#define _USE_MATH_DEFINES
#include <math.h>
#ifdef _DEBUG
//#if 1
#include "Timer.h"
#define _TMR_(...) Timer tmr(__VA_ARGS__)
#else
#define _TMR_(...)
#endif
namespace gls
{
// glsFft shader
class glsShaderFft : public glsShaderBase
{
protected:
string FragmentShaderCode(void);
list<string> UniformNameList(void);
public:
glsShaderFft(void) :glsShaderBase(__FUNCTION__){}
};
//-----------------------------------------------------------------------------
//global
glsShaderFft ShaderFft;
//-----------------------------------------------------------------------------
//glsShaderFft
string glsShaderFft::FragmentShaderCode(void){
const char fragmentShaderCode[] = TO_STR(
#version 330 core\n
precision highp float;\n
uniform sampler2D texSrc0;\n
uniform sampler2D texSrc1;\n
uniform sampler2D texW;\n
uniform int i_flag; //bit0:(0:holizontal 1:vertical)\n
uniform int i_N;\n
uniform int i_p;\n
uniform int i_q;\n
uniform float f_xscl;\n
uniform float f_yscl;\n
uniform float f_xconj;\n
uniform float f_yconj;\n
\n
layout (location = 0) out vec2 dst0;\n
layout (location = 1) out vec2 dst1;\n
\n
#define FLAG_DIR (1<<0)\n
\n
\n
int insertZeroBits(\n
const int src,\n
const int idx,\n
const int num\n
)\n
{\n
int ret = src << num;\n
ret &= ~((1 << (idx + num)) - 1);\n
ret |= src & ((1 << idx) - 1);\n
return ret;\n
}\n
\n
void main(void)\n
{\n
int p = i_p;\n
int q = i_q;\n
int N = i_N;\n
int dir = ((i_flag & FLAG_DIR)==0) ?0:1;\n
float xscl = f_xscl;\n
float yscl = f_yscl;\n
float xconj = f_xconj;\n
float yconj = f_yconj;\n
\n
int n;\n
vec2 x0;\n
vec2 x1;\n
vec2 w;\n
\n
n= int(gl_FragCoord[dir]);\n
int iw = (n >> q) << q;\n
int ix0 = insertZeroBits(n, q, 1);\n
int ix1 = ix0 + (1 << q);\n
w = texelFetch(texW,ivec2(iw,0),0).rg;\n
\n
\n
if(dir ==0){\n
if(ix0 < N/2) x0 = texelFetch(texSrc0,ivec2(ix0,gl_FragCoord.y),0).rg;\n
else x0 = texelFetch(texSrc1,ivec2(ix0-N/2,gl_FragCoord.y),0).rg;\n
\n
if(ix1 < N/2) x1 = texelFetch(texSrc0,ivec2(ix1,gl_FragCoord.y),0).rg;\n
else x1 = texelFetch(texSrc1,ivec2(ix1-N/2,gl_FragCoord.y),0).rg;\n
}\n
else{\n
if(ix0 < N/2) x0 = texelFetch(texSrc0,ivec2(gl_FragCoord.x,ix0),0).rg;\n
else x0 = texelFetch(texSrc1,ivec2(gl_FragCoord.x,ix0-N/2),0).rg;\n
\n
if(ix1 < N/2) x1 = texelFetch(texSrc0,ivec2(gl_FragCoord.x,ix1),0).rg;\n
else x1 = texelFetch(texSrc1,ivec2(gl_FragCoord.x,ix1-N/2),0).rg;\n
}\n
\n
// x0 = x0*xscl;\n
// x1 = x1*xscl;\n
x0.g = x0.g*xconj;\n
x1.g = x1.g*xconj;\n
\n
vec2 tmp;\n
tmp.r = x1.r * w.r - x1.g * w.g;\n
tmp.g = x1.r * w.g + x1.g * w.r;\n
\n
vec2 y0;\n
vec2 y1;\n
\n
y0 = x0 + tmp;\n
y1 = x0 - tmp;\n
\n
y0 = y0*yscl;\n
y1 = y1*yscl;\n
y0.g = y0.g*yconj;\n
y1.g = y1.g*yconj;\n
\n
dst0 = y0;\n
dst1 = y1;\n
\n
}\n
);
return fragmentShaderCode;
}
list<string> glsShaderFft::UniformNameList(void){
list<string> lst;
lst.push_back("texSrc0");
lst.push_back("texSrc1");
lst.push_back("texW");
lst.push_back("i_flag");
lst.push_back("i_N");
lst.push_back("i_p");
lst.push_back("i_q");
lst.push_back("f_xscl");
lst.push_back("f_yscl");
lst.push_back("f_xconj");
lst.push_back("f_yconj");
return lst;
}
//---------------------------------------------------------------------------
//value is power of 2
static bool IsPow2(unsigned int x){
return (((x)&(x - 1)) == 0);
}
//-----------------------------------------------------------------------------
void fft(const GlsMat& _src, GlsMat& dst, int flag){
GLS_Assert(_src.channels() == 2 || _src.channels() == 1);
GLS_Assert(_src.depth() == CV_32F);
int N = _src.cols;
GLS_Assert(IsPow2(N));
Size blkNum(2,2);
vector<vector<GlsMat>> _dst0 = vector<vector<GlsMat>>(blkNum.height, vector<GlsMat>(blkNum.width));
vector<vector<GlsMat>> _dst1 = vector<vector<GlsMat>>(blkNum.height, vector<GlsMat>(blkNum.width));
GlsMat src;
if (_src.channels() == 1){
// to complex mat
vector<GlsMat> tmp(2);
tmp[0] = _src;
gls::merge(tmp, src);
}
else{
src = _src;
}
gls::tiled(src, _dst0, blkNum);
for (int by = 0; by < blkNum.height; by++){
for (int bx = 0; bx < blkNum.width; bx++){
_dst1[by][bx] = GlsMat(Size(src.cols / blkNum.width, src.rows / blkNum.height), src.type());
}
}
GlsMat texW(Size(N / 2, 1), src.type());
//---------------------------------
// upload twidle texture
{
_TMR_("-twidle: \t");
Mat w(Size(N / 2, 1), CV_32FC2);
#ifdef _OPENMP
#pragma omp parallel for
#endif
for (int n = 0; n < N / 2; n++){
float jw = (float)(-2 * M_PI * n / N);
Vec2f val(cos(jw), sin(jw));
w.at<Vec2f>(0, n) = val;
}
texW.upload(w);
//vector<vec2> w(N / 2);
// --- twidle ----
//#ifdef _OPENMP
//#pragma omp parallel for
//#endif
//for (int n = 0; n < N / 2; n++){
// float jw = (float)(-2 * M_PI * n / N);
// w[n][0] = cos(jw);
// w[n][1] = sin(jw);
//}
//void* data = &w[0];
//glBindTexture(GL_TEXTURE_2D, texW);
//glTexSubImage2D(GL_TEXTURE_2D, 0, 0, 0, (GLsizei)w.size(), 1, texture.glFormat(), texture.glType(), data);
//glBindTexture(GL_TEXTURE_2D, 0);
}
vector<vector<GlsMat>>* texbuf[2] = { &_dst0, &_dst1 };
//Execute
int bank = 0;
{
_TMR_("-execute:\t");
int Q = 0;
while ((1 << Q) < N){ Q++; }
vector<GlsMat> texSrc(2);
vector<GlsMat> texDst(2);
// --- FFT rows ----
for (int p = 0, q = Q - 1; q >= 0; p++, q--, bank = bank ^ 1) {
for (int i = 0; i < 2; i++){
for (int j = 0; j < 2; j++){
texSrc[j] = (*texbuf[bank])[i][j];
texDst[j] = (*texbuf[bank ^ 1])[i][j];
}
float yscl = ((flag & GLS_FFT_SCALE) && (q == 0)) ? 1.0f / (float)N : 1.0f;
float xscl = 1.0f;
float xconj = ((flag & GLS_FFT_INVERSE) && (p == 0)) ? -1.0f : 1.0f;
float yconj = 1.0f;
ShaderFft.Execute(texSrc[0], texSrc[1], texW, 0, N, p, q, xscl, yscl, xconj, yconj, texDst[0], texDst[1]);
}
}
// --- FFT cols ----
for (int p = 0, q = Q - 1; q >= 0; p++, q--, bank = bank ^ 1) {
for (int j = 0; j < 2; j++){
for (int i = 0; i < 2; i++){
texSrc[i] = (*texbuf[bank])[i][j];
texDst[i] = (*texbuf[bank ^ 1])[i][j];
}
float yscl = ((flag & GLS_FFT_SCALE) && (q == 0)) ? 1.0f / (float)N : 1.0f;
float xscl = 1.0f;
float xconj = 1.0f;
float yconj = ((flag & GLS_FFT_INVERSE) && (q == 0)) ? -1.0f : 1.0f;
ShaderFft.Execute(texSrc[0], texSrc[1], texW, 1, N, p, q, xscl, yscl, xconj, yconj, texDst[0], texDst[1]);
}
}
}
if (flag & GLS_FFT_SHIFT){
(*texbuf[bank ^ 1])[0][0] = (*texbuf[bank])[1][1];
(*texbuf[bank ^ 1])[0][1] = (*texbuf[bank])[1][0];
(*texbuf[bank ^ 1])[1][0] = (*texbuf[bank])[0][1];
(*texbuf[bank ^ 1])[1][1] = (*texbuf[bank])[0][0];
bank = bank ^ 1;
}
gls::untiled(*texbuf[bank], dst);
}
void fft(const Mat& src, Mat& dst, int flag){
CV_Assert(src.type() == CV_32FC2);
CV_Assert(src.cols == src.rows);
int N = src.cols;
CV_Assert(IsPow2(N));
GlsMat _src(src.size(), src.type());
GlsMat _dst;
//---------------------------------
//upload
_src.upload(src);
//---------------------------------
//fft
gls::fft(_src, _dst,flag);
//---------------------------------
//download
_dst.download(dst);
}
}//namespace gls
<commit_msg>fft radix4対応前 リファクタリング<commit_after>/*
Copyright (c) 2016, oasi-adamay
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 glsCV 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 "stdafx.h"
/*-----------------------------------------------------------------------------
include
*/
#include "glsMacro.h"
#include "GlsMat.h"
#include "glsShader.h"
#include "glsFft.h"
#include "glsCopy.h" //tiled / untiled
#include "glsMerge.h"
#define _USE_MATH_DEFINES
#include <math.h>
#ifdef _DEBUG
//#if 1
#include "Timer.h"
#define _TMR_(...) Timer tmr(__VA_ARGS__)
#else
#define _TMR_(...)
#endif
namespace gls
{
// glsFft shader
class glsShaderFftRadix2 : public glsShaderBase
{
protected:
string FragmentShaderCode(void);
list<string> UniformNameList(void);
public:
glsShaderFftRadix2(void) :glsShaderBase(__FUNCTION__){}
};
//-----------------------------------------------------------------------------
//global
glsShaderFftRadix2 ShaderFftRadix2;
//-----------------------------------------------------------------------------
//glsShaderFftRadix2
// Stockham,DIT radix2
string glsShaderFftRadix2::FragmentShaderCode(void){
const char fragmentShaderCode[] = TO_STR(
#version 330 core\n
precision highp float;\n
uniform sampler2D texSrc0;\n
uniform sampler2D texSrc1;\n
uniform sampler2D texW;\n
uniform int i_flag; //bit0:(0:holizontal 1:vertical)\n
uniform int i_N;\n
uniform int i_p;\n
uniform int i_q;\n
uniform float f_xscl;\n
uniform float f_yscl;\n
uniform float f_xconj;\n
uniform float f_yconj;\n
\n
layout (location = 0) out vec2 dst0;\n
layout (location = 1) out vec2 dst1;\n
\n
#define FLAG_DIR (1<<0)\n
\n
\n
int insertZeroBits(\n
const int src,\n
const int idx,\n
const int num\n
)\n
{\n
int ret = src << num;\n
ret &= ~((1 << (idx + num)) - 1);\n
ret |= src & ((1 << idx) - 1);\n
return ret;\n
}\n
\n
void main(void)\n
{\n
int p = i_p;\n
int q = i_q;\n
int N = i_N;\n
int dir = ((i_flag & FLAG_DIR)==0) ?0:1;\n
float xscl = f_xscl;\n
float yscl = f_yscl;\n
float xconj = f_xconj;\n
float yconj = f_yconj;\n
\n
int n;\n
vec2 x0;\n
vec2 x1;\n
vec2 w;\n
\n
n= int(gl_FragCoord[dir]);\n
int iw = (n >> q) << q;\n
int ix0 = insertZeroBits(n, q, 1);\n
int ix1 = ix0 + (1 << q);\n
w = texelFetch(texW,ivec2(iw,0),0).rg;\n
\n
\n
if(dir ==0){\n
if(ix0 < N/2) x0 = texelFetch(texSrc0,ivec2(ix0,gl_FragCoord.y),0).rg;\n
else x0 = texelFetch(texSrc1,ivec2(ix0-N/2,gl_FragCoord.y),0).rg;\n
\n
if(ix1 < N/2) x1 = texelFetch(texSrc0,ivec2(ix1,gl_FragCoord.y),0).rg;\n
else x1 = texelFetch(texSrc1,ivec2(ix1-N/2,gl_FragCoord.y),0).rg;\n
}\n
else{\n
if(ix0 < N/2) x0 = texelFetch(texSrc0,ivec2(gl_FragCoord.x,ix0),0).rg;\n
else x0 = texelFetch(texSrc1,ivec2(gl_FragCoord.x,ix0-N/2),0).rg;\n
\n
if(ix1 < N/2) x1 = texelFetch(texSrc0,ivec2(gl_FragCoord.x,ix1),0).rg;\n
else x1 = texelFetch(texSrc1,ivec2(gl_FragCoord.x,ix1-N/2),0).rg;\n
}\n
\n
// x0 = x0*xscl;\n
// x1 = x1*xscl;\n
x0.g = x0.g*xconj;\n
x1.g = x1.g*xconj;\n
\n
vec2 tmp;\n
tmp.r = x1.r * w.r - x1.g * w.g;\n
tmp.g = x1.r * w.g + x1.g * w.r;\n
\n
vec2 y0;\n
vec2 y1;\n
\n
y0 = x0 + tmp;\n
y1 = x0 - tmp;\n
\n
y0 = y0*yscl;\n
y1 = y1*yscl;\n
y0.g = y0.g*yconj;\n
y1.g = y1.g*yconj;\n
\n
dst0 = y0;\n
dst1 = y1;\n
\n
}\n
);
return fragmentShaderCode;
}
list<string> glsShaderFftRadix2::UniformNameList(void){
list<string> lst;
lst.push_back("texSrc0");
lst.push_back("texSrc1");
lst.push_back("texW");
lst.push_back("i_flag");
lst.push_back("i_N");
lst.push_back("i_p");
lst.push_back("i_q");
lst.push_back("f_xscl");
lst.push_back("f_yscl");
lst.push_back("f_xconj");
lst.push_back("f_yconj");
return lst;
}
//---------------------------------------------------------------------------
//value is power of 2
static bool IsPow2(unsigned int x){
return (((x)&(x - 1)) == 0);
}
//-----------------------------------------------------------------------------
void fft(const GlsMat& _src, GlsMat& dst, int flag){
GLS_Assert(_src.channels() == 2 || _src.channels() == 1);
GLS_Assert(_src.depth() == CV_32F);
int N = _src.cols;
GLS_Assert(IsPow2(N));
GlsMat src;
if (_src.channels() == 1){
// to complex mat
vector<GlsMat> tmp(2);
tmp[0] = _src;
gls::merge(tmp, src);
}
else{
src = _src;
}
Size blkNum(2,2);
vector<vector<GlsMat>> _dst0 = vector<vector<GlsMat>>(blkNum.height, vector<GlsMat>(blkNum.width));
vector<vector<GlsMat>> _dst1 = vector<vector<GlsMat>>(blkNum.height, vector<GlsMat>(blkNum.width));
gls::tiled(src, _dst0, blkNum);
for (int by = 0; by < blkNum.height; by++){
for (int bx = 0; bx < blkNum.width; bx++){
_dst1[by][bx] = GlsMat(Size(src.cols / blkNum.width, src.rows / blkNum.height), src.type());
}
}
GlsMat texW(Size(N / 2, 1), src.type());
//---------------------------------
// upload twidle texture
{
_TMR_("-twidle: \t");
Mat w(Size(N / 2, 1), CV_32FC2);
#ifdef _OPENMP
//#pragma omp parallel for
#pragma omp parallel for if(N>=256)
#endif
for (int n = 0; n < N / 2; n++){
float jw = (float)(-2 * M_PI * n / N);
Vec2f val(cos(jw), sin(jw));
w.at<Vec2f>(0, n) = val;
}
texW.upload(w);
//vector<vec2> w(N / 2);
// --- twidle ----
//#ifdef _OPENMP
//#pragma omp parallel for
//#endif
//for (int n = 0; n < N / 2; n++){
// float jw = (float)(-2 * M_PI * n / N);
// w[n][0] = cos(jw);
// w[n][1] = sin(jw);
//}
//void* data = &w[0];
//glBindTexture(GL_TEXTURE_2D, texW);
//glTexSubImage2D(GL_TEXTURE_2D, 0, 0, 0, (GLsizei)w.size(), 1, texture.glFormat(), texture.glType(), data);
//glBindTexture(GL_TEXTURE_2D, 0);
}
vector<vector<GlsMat>>* texbuf[2] = { &_dst0, &_dst1 };
//Execute
int bank = 0;
{
_TMR_("-execute:\t");
int Q = 0;
while ((1 << Q) < N){ Q++; }
vector<GlsMat> texSrc(2);
vector<GlsMat> texDst(2);
// --- FFT rows ----
for (int p = 0, q = Q - 1; q >= 0; p++, q--, bank = bank ^ 1) {
for (int i = 0; i < 2; i++){
for (int j = 0; j < 2; j++){
texSrc[j] = (*texbuf[bank])[i][j];
texDst[j] = (*texbuf[bank ^ 1])[i][j];
}
float yscl = ((flag & GLS_FFT_SCALE) && (q == 0)) ? 1.0f / (float)N : 1.0f;
float xscl = 1.0f;
float xconj = ((flag & GLS_FFT_INVERSE) && (p == 0)) ? -1.0f : 1.0f;
float yconj = 1.0f;
ShaderFftRadix2.Execute(texSrc[0], texSrc[1], texW, 0, N, p, q, xscl, yscl, xconj, yconj, texDst[0], texDst[1]);
}
}
// --- FFT cols ----
for (int p = 0, q = Q - 1; q >= 0; p++, q--, bank = bank ^ 1) {
for (int j = 0; j < 2; j++){
for (int i = 0; i < 2; i++){
texSrc[i] = (*texbuf[bank])[i][j];
texDst[i] = (*texbuf[bank ^ 1])[i][j];
}
float yscl = ((flag & GLS_FFT_SCALE) && (q == 0)) ? 1.0f / (float)N : 1.0f;
float xscl = 1.0f;
float xconj = 1.0f;
float yconj = ((flag & GLS_FFT_INVERSE) && (q == 0)) ? -1.0f : 1.0f;
ShaderFftRadix2.Execute(texSrc[0], texSrc[1], texW, 1, N, p, q, xscl, yscl, xconj, yconj, texDst[0], texDst[1]);
}
}
}
if (flag & GLS_FFT_SHIFT){
(*texbuf[bank ^ 1])[0][0] = (*texbuf[bank])[1][1];
(*texbuf[bank ^ 1])[0][1] = (*texbuf[bank])[1][0];
(*texbuf[bank ^ 1])[1][0] = (*texbuf[bank])[0][1];
(*texbuf[bank ^ 1])[1][1] = (*texbuf[bank])[0][0];
bank = bank ^ 1;
}
gls::untiled(*texbuf[bank], dst);
}
void fft(const Mat& src, Mat& dst, int flag){
CV_Assert(src.type() == CV_32FC2);
CV_Assert(src.cols == src.rows);
int N = src.cols;
CV_Assert(IsPow2(N));
GlsMat _src(src.size(), src.type());
GlsMat _dst;
//---------------------------------
//upload
_src.upload(src);
//---------------------------------
//fft
gls::fft(_src, _dst,flag);
//---------------------------------
//download
_dst.download(dst);
}
}//namespace gls
<|endoftext|>
|
<commit_before>/**
* @file emst_test.cpp
*
* Test file for EMST methods.
*/
#include <mlpack/core.hpp>
#include <mlpack/methods/emst/dtb.hpp>
#include <boost/test/unit_test.hpp>
using namespace mlpack;
using namespace mlpack::emst;
BOOST_AUTO_TEST_SUITE(EMSTTest);
/**
* Simple emst test with small, synthetic dataset. This is an
* exhaustive test, which checks that each method for performing the calculation
* (dual-tree, single-tree, naive) produces the correct results. The dataset is
* in one dimension for simplicity -- the correct functionality of distance
* functions is not tested here.
*/
BOOST_AUTO_TEST_CASE(exhaustive_synthetic_test)
{
// Set up our data.
arma::mat data(1, 11);
data[0] = 0.05; // Row addressing is unnecessary (they are all 0).
data[1] = 0.37;
data[2] = 0.15;
data[3] = 1.25;
data[4] = 5.05;
data[5] = -0.22;
data[6] = -2.00;
data[7] = -1.30;
data[8] = 0.45;
data[9] = 0.91;
data[10] = 1.00;
// Now perform the actual calculation.
arma::mat results;
DualTreeBoruvka<> dtb(data);
dtb.ComputeMST(results);
// Now the exhaustive check for correctness.
BOOST_REQUIRE(results(0, 0) == 1);
BOOST_REQUIRE(results(0, 1) == 8);
BOOST_REQUIRE_CLOSE(results(0, 2), 0.08, 1e-5);
BOOST_REQUIRE(results(1, 0) == 9);
BOOST_REQUIRE(results(1, 1) == 10);
BOOST_REQUIRE_CLOSE(results(1, 2), 0.09, 1e-5);
BOOST_REQUIRE(results(2, 0) == 0);
BOOST_REQUIRE(results(2, 1) == 2);
BOOST_REQUIRE_CLOSE(results(2, 2), 0.1, 1e-5);
BOOST_REQUIRE(results(3, 0) == 1);
BOOST_REQUIRE(results(3, 1) == 2);
BOOST_REQUIRE_CLOSE(results(3, 2), 0.22, 1e-5);
BOOST_REQUIRE(results(4, 0) == 3);
BOOST_REQUIRE(results(4, 1) == 10);
BOOST_REQUIRE_CLOSE(results(4, 2), 0.25, 1e-5);
BOOST_REQUIRE(results(5, 0) == 0);
BOOST_REQUIRE(results(5, 1) == 5);
BOOST_REQUIRE_CLOSE(results(5, 2), 0.27, 1e-5);
BOOST_REQUIRE(results(6, 0) == 8);
BOOST_REQUIRE(results(6, 1) == 9);
BOOST_REQUIRE_CLOSE(results(6, 2), 0.46, 1e-5);
BOOST_REQUIRE(results(7, 0) == 6);
BOOST_REQUIRE(results(7, 1) == 7);
BOOST_REQUIRE_CLOSE(results(7, 2), 0.7, 1e-5);
BOOST_REQUIRE(results(8, 0) == 5);
BOOST_REQUIRE(results(8, 1) == 7);
BOOST_REQUIRE_CLOSE(results(8, 2), 1.08, 1e-5);
BOOST_REQUIRE(results(9, 0) == 3);
BOOST_REQUIRE(results(9, 1) == 4);
BOOST_REQUIRE_CLOSE(results(9, 2), 3.8, 1e-5);
}
/**
* Test the dual tree method against the naive computation.
*
* Errors are produced if the results are not identical.
*/
BOOST_AUTO_TEST_CASE(dual_tree_vs_naive)
{
arma::mat input_data;
// Hard-coded filename: bad!
// Code duplication: also bad!
if (!data::Load("test_data_3_1000.csv", input_data))
BOOST_FAIL("Cannot load test dataset test_data_3_1000.csv!");
// Set up matrices to work with (may not be necessary with no ALIAS_MATRIX?).
arma::mat dual_data = arma::trans(input_data);
arma::mat naive_data = arma::trans(input_data);
// Reset parameters from last test.
DualTreeBoruvka<> dtb(dual_data);
arma::mat dual_results;
dtb.ComputeMST(dual_results);
// Set naive mode.
DualTreeBoruvka<> dtb_naive(naive_data, true);
arma::mat naive_results;
dtb_naive.ComputeMST(naive_results);
BOOST_REQUIRE(dual_results.n_cols == naive_results.n_cols);
BOOST_REQUIRE(dual_results.n_rows == naive_results.n_rows);
for (size_t i = 0; i < dual_results.n_rows; i++)
{
BOOST_REQUIRE(dual_results(i, 0) == naive_results(i, 0));
BOOST_REQUIRE(dual_results(i, 1) == naive_results(i, 1));
BOOST_REQUIRE_CLOSE(dual_results(i, 2), naive_results(i, 2), 1e-5);
}
}
BOOST_AUTO_TEST_SUITE_END();
<commit_msg>Update for transposition of output.<commit_after>/**
* @file emst_test.cpp
*
* Test file for EMST methods.
*/
#include <mlpack/core.hpp>
#include <mlpack/methods/emst/dtb.hpp>
#include <boost/test/unit_test.hpp>
using namespace mlpack;
using namespace mlpack::emst;
BOOST_AUTO_TEST_SUITE(EMSTTest);
/**
* Simple emst test with small, synthetic dataset. This is an
* exhaustive test, which checks that each method for performing the calculation
* (dual-tree, single-tree, naive) produces the correct results. The dataset is
* in one dimension for simplicity -- the correct functionality of distance
* functions is not tested here.
*/
BOOST_AUTO_TEST_CASE(exhaustive_synthetic_test)
{
// Set up our data.
arma::mat data(1, 11);
data[0] = 0.05; // Row addressing is unnecessary (they are all 0).
data[1] = 0.37;
data[2] = 0.15;
data[3] = 1.25;
data[4] = 5.05;
data[5] = -0.22;
data[6] = -2.00;
data[7] = -1.30;
data[8] = 0.45;
data[9] = 0.91;
data[10] = 1.00;
// Now perform the actual calculation.
arma::mat results;
DualTreeBoruvka<> dtb(data);
dtb.ComputeMST(results);
// Now the exhaustive check for correctness.
BOOST_REQUIRE(results(0, 0) == 1);
BOOST_REQUIRE(results(1, 0) == 8);
BOOST_REQUIRE_CLOSE(results(2, 0), 0.08, 1e-5);
BOOST_REQUIRE(results(0, 1) == 9);
BOOST_REQUIRE(results(1, 1) == 10);
BOOST_REQUIRE_CLOSE(results(2, 1), 0.09, 1e-5);
BOOST_REQUIRE(results(0, 2) == 0);
BOOST_REQUIRE(results(1, 2) == 2);
BOOST_REQUIRE_CLOSE(results(2, 2), 0.1, 1e-5);
BOOST_REQUIRE(results(0, 3) == 1);
BOOST_REQUIRE(results(1, 3) == 2);
BOOST_REQUIRE_CLOSE(results(2, 3), 0.22, 1e-5);
BOOST_REQUIRE(results(0, 4) == 3);
BOOST_REQUIRE(results(1, 4) == 10);
BOOST_REQUIRE_CLOSE(results(2, 4), 0.25, 1e-5);
BOOST_REQUIRE(results(0, 5) == 0);
BOOST_REQUIRE(results(1, 5) == 5);
BOOST_REQUIRE_CLOSE(results(2, 5), 0.27, 1e-5);
BOOST_REQUIRE(results(0, 6) == 8);
BOOST_REQUIRE(results(1, 6) == 9);
BOOST_REQUIRE_CLOSE(results(2, 6), 0.46, 1e-5);
BOOST_REQUIRE(results(0, 7) == 6);
BOOST_REQUIRE(results(1, 7) == 7);
BOOST_REQUIRE_CLOSE(results(2, 7), 0.7, 1e-5);
BOOST_REQUIRE(results(0, 8) == 5);
BOOST_REQUIRE(results(1, 8) == 7);
BOOST_REQUIRE_CLOSE(results(2, 8), 1.08, 1e-5);
BOOST_REQUIRE(results(0, 9) == 3);
BOOST_REQUIRE(results(1, 9) == 4);
BOOST_REQUIRE_CLOSE(results(2, 9), 3.8, 1e-5);
}
/**
* Test the dual tree method against the naive computation.
*
* Errors are produced if the results are not identical.
*/
BOOST_AUTO_TEST_CASE(dual_tree_vs_naive)
{
arma::mat input_data;
// Hard-coded filename: bad!
// Code duplication: also bad!
if (!data::Load("test_data_3_1000.csv", input_data))
BOOST_FAIL("Cannot load test dataset test_data_3_1000.csv!");
// Set up matrices to work with (may not be necessary with no ALIAS_MATRIX?).
arma::mat dual_data = arma::trans(input_data);
arma::mat naive_data = arma::trans(input_data);
// Reset parameters from last test.
DualTreeBoruvka<> dtb(dual_data);
arma::mat dual_results;
dtb.ComputeMST(dual_results);
// Set naive mode.
DualTreeBoruvka<> dtb_naive(naive_data, true);
arma::mat naive_results;
dtb_naive.ComputeMST(naive_results);
BOOST_REQUIRE(dual_results.n_cols == naive_results.n_cols);
BOOST_REQUIRE(dual_results.n_rows == naive_results.n_rows);
for (size_t i = 0; i < dual_results.n_cols; i++)
{
BOOST_REQUIRE(dual_results(0, i) == naive_results(0, i));
BOOST_REQUIRE(dual_results(1, i) == naive_results(1, i));
BOOST_REQUIRE_CLOSE(dual_results(2, i), naive_results(2, i), 1e-5);
}
}
BOOST_AUTO_TEST_SUITE_END();
<|endoftext|>
|
<commit_before>/*
* Copyright 2013 Google Inc.
*
* Use of this source code is governed by a BSD-style license that can be
* found in the LICENSE file.
*/
#include "gm/gm.h"
#include "include/core/SkCanvas.h"
#include "include/core/SkColor.h"
#include "include/core/SkPaint.h"
#include "include/core/SkPath.h"
#include "include/core/SkPoint.h"
#include "include/core/SkRect.h"
#include "include/core/SkScalar.h"
#include "include/core/SkSize.h"
#include "include/core/SkString.h"
#include "include/core/SkTypes.h"
#include "include/private/SkTArray.h"
namespace skiagm {
class HairlinesGM : public GM {
protected:
SkString onShortName() override {
return SkString("hairlines");
}
SkISize onISize() override { return SkISize::Make(1250, 1250); }
void onOnceBeforeDraw() override {
{
SkPath* lineAnglesPath = &fPaths.push_back();
enum {
kNumAngles = 15,
kRadius = 40,
};
for (int i = 0; i < kNumAngles; ++i) {
SkScalar angle = SK_ScalarPI * SkIntToScalar(i) / kNumAngles;
SkScalar x = kRadius * SkScalarCos(angle);
SkScalar y = kRadius * SkScalarSin(angle);
lineAnglesPath->moveTo(x, y);
lineAnglesPath->lineTo(-x, -y);
}
}
{
SkPath* kindaTightQuad = &fPaths.push_back();
kindaTightQuad->moveTo(0, -10 * SK_Scalar1);
kindaTightQuad->quadTo(SkIntToScalar(100), SkIntToScalar(100), -10 * SK_Scalar1, 0);
}
{
SkPath* tightQuad = &fPaths.push_back();
tightQuad->moveTo(0, -5 * SK_Scalar1);
tightQuad->quadTo(SkIntToScalar(100), SkIntToScalar(100), -5 * SK_Scalar1, 0);
}
{
SkPath* tighterQuad = &fPaths.push_back();
tighterQuad->moveTo(0, -2 * SK_Scalar1);
tighterQuad->quadTo(SkIntToScalar(100), SkIntToScalar(100), -2 * SK_Scalar1, 0);
}
{
SkPath* unevenTighterQuad = &fPaths.push_back();
unevenTighterQuad->moveTo(0, -1 * SK_Scalar1);
SkPoint p;
p.set(-2 * SK_Scalar1 + 3 * SkIntToScalar(102) / 4, SkIntToScalar(75));
unevenTighterQuad->quadTo(SkIntToScalar(100), SkIntToScalar(100), p.fX, p.fY);
}
{
SkPath* reallyTightQuad = &fPaths.push_back();
reallyTightQuad->moveTo(0, -1 * SK_Scalar1);
reallyTightQuad->quadTo(SkIntToScalar(100), SkIntToScalar(100), -1 * SK_Scalar1, 0);
}
{
SkPath* closedQuad = &fPaths.push_back();
closedQuad->moveTo(0, -0);
closedQuad->quadTo(SkIntToScalar(100), SkIntToScalar(100), 0, 0);
}
{
SkPath* unevenClosedQuad = &fPaths.push_back();
unevenClosedQuad->moveTo(0, -0);
unevenClosedQuad->quadTo(SkIntToScalar(100), SkIntToScalar(100),
SkIntToScalar(75), SkIntToScalar(75));
}
// Two problem cases for gpu hairline renderer found by shapeops testing. These used
// to assert that the computed bounding box didn't contain all the vertices.
{
SkPath* problem1 = &fPaths.push_back();
problem1->moveTo(SkIntToScalar(4), SkIntToScalar(6));
problem1->cubicTo(SkIntToScalar(5), SkIntToScalar(6),
SkIntToScalar(5), SkIntToScalar(4),
SkIntToScalar(4), SkIntToScalar(0));
problem1->close();
}
{
SkPath* problem2 = &fPaths.push_back();
problem2->moveTo(SkIntToScalar(5), SkIntToScalar(1));
problem2->lineTo(4.32787323f, 1.67212653f);
problem2->cubicTo(2.75223875f, 3.24776125f,
3.00581908f, 4.51236057f,
3.7580452f, 4.37367964f);
problem2->cubicTo(4.66472578f, 3.888381f,
5.f, 2.875f,
5.f, 1.f);
problem2->close();
}
// Three paths that show the same bug (missing end caps)
{
// A caret (crbug.com/131770)
SkPath* bug0 = &fPaths.push_back();
bug0->moveTo(6.5f,5.5f);
bug0->lineTo(3.5f,0.5f);
bug0->moveTo(0.5f,5.5f);
bug0->lineTo(3.5f,0.5f);
}
{
// An X (crbug.com/137317)
SkPath* bug1 = &fPaths.push_back();
bug1->moveTo(1, 1);
bug1->lineTo(6, 6);
bug1->moveTo(1, 6);
bug1->lineTo(6, 1);
}
{
// A right angle (crbug.com/137465 and crbug.com/256776)
SkPath* bug2 = &fPaths.push_back();
bug2->moveTo(5.5f, 5.5f);
bug2->lineTo(5.5f, 0.5f);
bug2->lineTo(0.5f, 0.5f);
}
{
// Arc example to test imperfect truncation bug (crbug.com/295626)
constexpr SkScalar kRad = SkIntToScalar(2000);
constexpr SkScalar kStartAngle = 262.59717f;
constexpr SkScalar kSweepAngle = SkScalarHalf(17.188717f);
SkPath* bug = &fPaths.push_back();
// Add a circular arc
SkRect circle = SkRect::MakeLTRB(-kRad, -kRad, kRad, kRad);
bug->addArc(circle, kStartAngle, kSweepAngle);
// Now add the chord that should cap the circular arc
SkPoint p0 = { kRad * SkScalarCos(SkDegreesToRadians(kStartAngle)),
kRad * SkScalarSin(SkDegreesToRadians(kStartAngle)) };
SkPoint p1 = { kRad * SkScalarCos(SkDegreesToRadians(kStartAngle + kSweepAngle)),
kRad * SkScalarSin(SkDegreesToRadians(kStartAngle + kSweepAngle)) };
bug->moveTo(p0);
bug->lineTo(p1);
}
}
void onDraw(SkCanvas* canvas) override {
constexpr SkAlpha kAlphaValue[] = { 0xFF, 0x40 };
constexpr SkScalar kWidths[] = { 0, 0.5f, 1.5f };
enum {
kMargin = 5,
};
int wrapX = 1250 - kMargin;
SkScalar maxH = 0;
canvas->translate(SkIntToScalar(kMargin), SkIntToScalar(kMargin));
canvas->save();
SkScalar x = SkIntToScalar(kMargin);
for (int p = 0; p < fPaths.count(); ++p) {
for (size_t a = 0; a < SK_ARRAY_COUNT(kAlphaValue); ++a) {
for (int aa = 0; aa < 2; ++aa) {
for (size_t w = 0; w < SK_ARRAY_COUNT(kWidths); w++) {
const SkRect& bounds = fPaths[p].getBounds();
if (x + bounds.width() > wrapX) {
canvas->restore();
canvas->translate(0, maxH + SkIntToScalar(kMargin));
canvas->save();
maxH = 0;
x = SkIntToScalar(kMargin);
}
SkPaint paint;
paint.setARGB(kAlphaValue[a], 0, 0, 0);
paint.setAntiAlias(SkToBool(aa));
paint.setStyle(SkPaint::kStroke_Style);
paint.setStrokeWidth(kWidths[w]);
canvas->save();
canvas->translate(-bounds.fLeft, -bounds.fTop);
canvas->drawPath(fPaths[p], paint);
canvas->restore();
maxH = std::max(maxH, bounds.height());
SkScalar dx = bounds.width() + SkIntToScalar(kMargin);
x += dx;
canvas->translate(dx, 0);
}
}
}
}
canvas->restore();
}
private:
SkTArray<SkPath> fPaths;
typedef GM INHERITED;
};
static void draw_squarehair_tests(SkCanvas* canvas, SkScalar width, SkPaint::Cap cap, bool aa) {
SkPaint paint;
paint.setStrokeCap(cap);
paint.setStrokeWidth(width);
paint.setAntiAlias(aa);
paint.setStyle(SkPaint::kStroke_Style);
canvas->drawLine(10, 10, 20, 10, paint);
canvas->drawLine(30, 10, 30, 20, paint);
canvas->drawLine(40, 10, 50, 20, paint);
SkPath path;
path.moveTo(60, 10);
path.quadTo(60, 20, 70, 20);
path.conicTo(70, 10, 80, 10, 0.707f);
canvas->drawPath(path, paint);
path.reset();
path.moveTo(90, 10);
path.cubicTo(90, 20, 100, 20, 100, 10);
path.lineTo(110, 10);
canvas->drawPath(path, paint);
canvas->translate(0, 30);
}
DEF_SIMPLE_GM(squarehair, canvas, 240, 360) {
const bool aliases[] = { false, true };
const SkScalar widths[] = { 0, 0.999f, 1, 1.001f };
const SkPaint::Cap caps[] = { SkPaint::kButt_Cap, SkPaint::kSquare_Cap, SkPaint::kRound_Cap };
for (auto alias : aliases) {
canvas->save();
for (auto width : widths) {
for (auto cap : caps) {
draw_squarehair_tests(canvas, width, cap, alias);
}
}
canvas->restore();
canvas->translate(120, 0);
}
}
//////////////////////////////////////////////////////////////////////////////
DEF_GM( return new HairlinesGM; )
}
<commit_msg>Add new GM to test hairline subdivision.<commit_after>/*
* Copyright 2013 Google Inc.
*
* Use of this source code is governed by a BSD-style license that can be
* found in the LICENSE file.
*/
#include "gm/gm.h"
#include "include/core/SkCanvas.h"
#include "include/core/SkColor.h"
#include "include/core/SkPaint.h"
#include "include/core/SkPath.h"
#include "include/core/SkPoint.h"
#include "include/core/SkRect.h"
#include "include/core/SkScalar.h"
#include "include/core/SkSize.h"
#include "include/core/SkString.h"
#include "include/core/SkTypes.h"
#include "include/private/SkTArray.h"
namespace skiagm {
class HairlinesGM : public GM {
protected:
SkString onShortName() override {
return SkString("hairlines");
}
SkISize onISize() override { return SkISize::Make(1250, 1250); }
void onOnceBeforeDraw() override {
{
SkPath* lineAnglesPath = &fPaths.push_back();
enum {
kNumAngles = 15,
kRadius = 40,
};
for (int i = 0; i < kNumAngles; ++i) {
SkScalar angle = SK_ScalarPI * SkIntToScalar(i) / kNumAngles;
SkScalar x = kRadius * SkScalarCos(angle);
SkScalar y = kRadius * SkScalarSin(angle);
lineAnglesPath->moveTo(x, y);
lineAnglesPath->lineTo(-x, -y);
}
}
{
SkPath* kindaTightQuad = &fPaths.push_back();
kindaTightQuad->moveTo(0, -10 * SK_Scalar1);
kindaTightQuad->quadTo(SkIntToScalar(100), SkIntToScalar(100), -10 * SK_Scalar1, 0);
}
{
SkPath* tightQuad = &fPaths.push_back();
tightQuad->moveTo(0, -5 * SK_Scalar1);
tightQuad->quadTo(SkIntToScalar(100), SkIntToScalar(100), -5 * SK_Scalar1, 0);
}
{
SkPath* tighterQuad = &fPaths.push_back();
tighterQuad->moveTo(0, -2 * SK_Scalar1);
tighterQuad->quadTo(SkIntToScalar(100), SkIntToScalar(100), -2 * SK_Scalar1, 0);
}
{
SkPath* unevenTighterQuad = &fPaths.push_back();
unevenTighterQuad->moveTo(0, -1 * SK_Scalar1);
SkPoint p;
p.set(-2 * SK_Scalar1 + 3 * SkIntToScalar(102) / 4, SkIntToScalar(75));
unevenTighterQuad->quadTo(SkIntToScalar(100), SkIntToScalar(100), p.fX, p.fY);
}
{
SkPath* reallyTightQuad = &fPaths.push_back();
reallyTightQuad->moveTo(0, -1 * SK_Scalar1);
reallyTightQuad->quadTo(SkIntToScalar(100), SkIntToScalar(100), -1 * SK_Scalar1, 0);
}
{
SkPath* closedQuad = &fPaths.push_back();
closedQuad->moveTo(0, -0);
closedQuad->quadTo(SkIntToScalar(100), SkIntToScalar(100), 0, 0);
}
{
SkPath* unevenClosedQuad = &fPaths.push_back();
unevenClosedQuad->moveTo(0, -0);
unevenClosedQuad->quadTo(SkIntToScalar(100), SkIntToScalar(100),
SkIntToScalar(75), SkIntToScalar(75));
}
// Two problem cases for gpu hairline renderer found by shapeops testing. These used
// to assert that the computed bounding box didn't contain all the vertices.
{
SkPath* problem1 = &fPaths.push_back();
problem1->moveTo(SkIntToScalar(4), SkIntToScalar(6));
problem1->cubicTo(SkIntToScalar(5), SkIntToScalar(6),
SkIntToScalar(5), SkIntToScalar(4),
SkIntToScalar(4), SkIntToScalar(0));
problem1->close();
}
{
SkPath* problem2 = &fPaths.push_back();
problem2->moveTo(SkIntToScalar(5), SkIntToScalar(1));
problem2->lineTo(4.32787323f, 1.67212653f);
problem2->cubicTo(2.75223875f, 3.24776125f,
3.00581908f, 4.51236057f,
3.7580452f, 4.37367964f);
problem2->cubicTo(4.66472578f, 3.888381f,
5.f, 2.875f,
5.f, 1.f);
problem2->close();
}
// Three paths that show the same bug (missing end caps)
{
// A caret (crbug.com/131770)
SkPath* bug0 = &fPaths.push_back();
bug0->moveTo(6.5f,5.5f);
bug0->lineTo(3.5f,0.5f);
bug0->moveTo(0.5f,5.5f);
bug0->lineTo(3.5f,0.5f);
}
{
// An X (crbug.com/137317)
SkPath* bug1 = &fPaths.push_back();
bug1->moveTo(1, 1);
bug1->lineTo(6, 6);
bug1->moveTo(1, 6);
bug1->lineTo(6, 1);
}
{
// A right angle (crbug.com/137465 and crbug.com/256776)
SkPath* bug2 = &fPaths.push_back();
bug2->moveTo(5.5f, 5.5f);
bug2->lineTo(5.5f, 0.5f);
bug2->lineTo(0.5f, 0.5f);
}
{
// Arc example to test imperfect truncation bug (crbug.com/295626)
constexpr SkScalar kRad = SkIntToScalar(2000);
constexpr SkScalar kStartAngle = 262.59717f;
constexpr SkScalar kSweepAngle = SkScalarHalf(17.188717f);
SkPath* bug = &fPaths.push_back();
// Add a circular arc
SkRect circle = SkRect::MakeLTRB(-kRad, -kRad, kRad, kRad);
bug->addArc(circle, kStartAngle, kSweepAngle);
// Now add the chord that should cap the circular arc
SkPoint p0 = { kRad * SkScalarCos(SkDegreesToRadians(kStartAngle)),
kRad * SkScalarSin(SkDegreesToRadians(kStartAngle)) };
SkPoint p1 = { kRad * SkScalarCos(SkDegreesToRadians(kStartAngle + kSweepAngle)),
kRad * SkScalarSin(SkDegreesToRadians(kStartAngle + kSweepAngle)) };
bug->moveTo(p0);
bug->lineTo(p1);
}
}
void onDraw(SkCanvas* canvas) override {
constexpr SkAlpha kAlphaValue[] = { 0xFF, 0x40 };
constexpr SkScalar kWidths[] = { 0, 0.5f, 1.5f };
enum {
kMargin = 5,
};
int wrapX = 1250 - kMargin;
SkScalar maxH = 0;
canvas->translate(SkIntToScalar(kMargin), SkIntToScalar(kMargin));
canvas->save();
SkScalar x = SkIntToScalar(kMargin);
for (int p = 0; p < fPaths.count(); ++p) {
for (size_t a = 0; a < SK_ARRAY_COUNT(kAlphaValue); ++a) {
for (int aa = 0; aa < 2; ++aa) {
for (size_t w = 0; w < SK_ARRAY_COUNT(kWidths); w++) {
const SkRect& bounds = fPaths[p].getBounds();
if (x + bounds.width() > wrapX) {
canvas->restore();
canvas->translate(0, maxH + SkIntToScalar(kMargin));
canvas->save();
maxH = 0;
x = SkIntToScalar(kMargin);
}
SkPaint paint;
paint.setARGB(kAlphaValue[a], 0, 0, 0);
paint.setAntiAlias(SkToBool(aa));
paint.setStyle(SkPaint::kStroke_Style);
paint.setStrokeWidth(kWidths[w]);
canvas->save();
canvas->translate(-bounds.fLeft, -bounds.fTop);
canvas->drawPath(fPaths[p], paint);
canvas->restore();
maxH = std::max(maxH, bounds.height());
SkScalar dx = bounds.width() + SkIntToScalar(kMargin);
x += dx;
canvas->translate(dx, 0);
}
}
}
}
canvas->restore();
}
private:
SkTArray<SkPath> fPaths;
typedef GM INHERITED;
};
static void draw_squarehair_tests(SkCanvas* canvas, SkScalar width, SkPaint::Cap cap, bool aa) {
SkPaint paint;
paint.setStrokeCap(cap);
paint.setStrokeWidth(width);
paint.setAntiAlias(aa);
paint.setStyle(SkPaint::kStroke_Style);
canvas->drawLine(10, 10, 20, 10, paint);
canvas->drawLine(30, 10, 30, 20, paint);
canvas->drawLine(40, 10, 50, 20, paint);
SkPath path;
path.moveTo(60, 10);
path.quadTo(60, 20, 70, 20);
path.conicTo(70, 10, 80, 10, 0.707f);
canvas->drawPath(path, paint);
path.reset();
path.moveTo(90, 10);
path.cubicTo(90, 20, 100, 20, 100, 10);
path.lineTo(110, 10);
canvas->drawPath(path, paint);
canvas->translate(0, 30);
}
DEF_SIMPLE_GM(squarehair, canvas, 240, 360) {
const bool aliases[] = { false, true };
const SkScalar widths[] = { 0, 0.999f, 1, 1.001f };
const SkPaint::Cap caps[] = { SkPaint::kButt_Cap, SkPaint::kSquare_Cap, SkPaint::kRound_Cap };
for (auto alias : aliases) {
canvas->save();
for (auto width : widths) {
for (auto cap : caps) {
draw_squarehair_tests(canvas, width, cap, alias);
}
}
canvas->restore();
canvas->translate(120, 0);
}
}
// GM to test subdivision of hairlines
static void draw_subdivided_quad(SkCanvas* canvas, int x0, int y0, int x1, int y1, SkColor color) {
SkPaint paint;
paint.setStrokeWidth(1);
paint.setAntiAlias(true);
paint.setStyle(SkPaint::kStroke_Style);
paint.setColor(color);
SkPath quad;
quad.moveTo(0, 0);
quad.quadTo(SkIntToScalar(x0), SkIntToScalar(y0),
SkIntToScalar(x1), SkIntToScalar(y1));
canvas->drawPath(quad, paint);
}
DEF_SIMPLE_GM(hairline_subdiv, canvas, 512, 256) {
// no subdivisions
canvas->translate(45, -25);
draw_subdivided_quad(canvas, 334, 334, 467, 267, SK_ColorBLACK);
// one subdivision
canvas->translate(-185, -150);
draw_subdivided_quad(canvas, 472, 472, 660, 378, SK_ColorRED);
// two subdivisions
canvas->translate(-275, -200);
draw_subdivided_quad(canvas, 668, 668, 934, 535, SK_ColorGREEN);
// three subdivisions
canvas->translate(-385, -260);
draw_subdivided_quad(canvas, 944, 944, 1320, 756, SK_ColorBLUE);
}
//////////////////////////////////////////////////////////////////////////////
DEF_GM( return new HairlinesGM; )
}
<|endoftext|>
|
<commit_before>/** \copyright
* Copyright (c) 2018, Balazs Racz
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
*
* - Redistributions of source code must retain the above copyright notice,
* this list of conditions and the following disclaimer.
*
* - Redistributions in binary form must reproduce the above copyright notice,
* this list of conditions and the following disclaimer in the documentation
* and/or other materials provided with the distribution.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
* AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
* ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE
* LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
* CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
* SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
* INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
* CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
* ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
* POSSIBILITY OF SUCH DAMAGE.
*
* \file OpenMRN.cpp
*
* Implementation that needs to be compiled for the Arduino.
*
* @author Balazs Racz
* @date 24 July 2018
*/
#include <OpenMRNLite.h>
#ifdef HAVE_FILESYSTEM
#include "utils/FileUtils.hxx"
#endif
extern const char DEFAULT_WIFI_NAME[] __attribute__((weak)) = "defaultap";
extern const char DEFAULT_WIFI_PASSWORD[] __attribute__((weak)) = "defaultpw";
namespace openmrn_arduino {
OpenMRN::OpenMRN(openlcb::NodeID node_id)
{
init(node_id);
}
} // namespace openmrn_arduino
<commit_msg>remove reference to include as it is not necessary now.<commit_after>/** \copyright
* Copyright (c) 2018, Balazs Racz
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
*
* - Redistributions of source code must retain the above copyright notice,
* this list of conditions and the following disclaimer.
*
* - Redistributions in binary form must reproduce the above copyright notice,
* this list of conditions and the following disclaimer in the documentation
* and/or other materials provided with the distribution.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
* AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
* ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE
* LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
* CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
* SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
* INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
* CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
* ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
* POSSIBILITY OF SUCH DAMAGE.
*
* \file OpenMRN.cpp
*
* Implementation that needs to be compiled for the Arduino.
*
* @author Balazs Racz
* @date 24 July 2018
*/
#include <OpenMRNLite.h>
extern const char DEFAULT_WIFI_NAME[] __attribute__((weak)) = "defaultap";
extern const char DEFAULT_WIFI_PASSWORD[] __attribute__((weak)) = "defaultpw";
namespace openmrn_arduino {
OpenMRN::OpenMRN(openlcb::NodeID node_id)
{
init(node_id);
}
} // namespace openmrn_arduino
<|endoftext|>
|
<commit_before>#include <unistd.h>
#include "txn_btree.h"
#include "thread.h"
#include "util.h"
#define VERBOSE(expr) ((void)0)
using namespace std;
using namespace util;
bool
txn_btree::search(transaction &t, key_type k, value_type &v)
{
assert(!t.btree || t.btree == this);
t.btree = this;
// priority is
// 1) write set
// 2) local read set
// 3) range set
// 4) query underlying tree
//
// note (1)-(3) are served by transaction::local_search()
if (t.local_search(k, v))
return (bool) v;
btree::value_type underlying_v;
if (!underlying_btree.search(k, underlying_v)) {
// all records exist in the system at MIN_TID with no value
transaction::read_record_t *read_rec = &t.read_set[k];
read_rec->t = transaction::MIN_TID;
read_rec->r = NULL;
read_rec->ln = NULL;
return false;
} else {
transaction::logical_node *ln = (transaction::logical_node *) underlying_v;
assert(ln);
transaction::tid_t start_t;
transaction::record_t r;
if (unlikely(!ln->stable_read(t.snapshot_tid, start_t, r))) {
t.abort();
throw transaction_abort_exception();
}
transaction::read_record_t *read_rec = &t.read_set[k];
read_rec->t = start_t;
read_rec->r = r;
read_rec->ln = ln;
v = read_rec->r;
return read_rec->r;
}
}
bool
txn_btree::txn_search_range_callback::invoke(key_type k, value_type v)
{
VERBOSE(cerr << "search range k: " << k << endl);
transaction::key_range_t r(invoked ? prev_key : lower, k);
if (!r.is_empty_range())
t->add_absent_range(r);
prev_key = k;
invoked = true;
value_type local_v = 0;
bool local_read = t->local_search(k, local_v);
bool ret = true;
if (local_read && local_v)
ret = caller_callback->invoke(k, local_v);
map<key_type, transaction::read_record_t>::const_iterator it =
t->read_set.find(k);
if (it == t->read_set.end()) {
transaction::logical_node *ln = (transaction::logical_node *) v;
assert(ln);
transaction::tid_t start_t;
transaction::record_t r;
if (unlikely(!ln->stable_read(t->snapshot_tid, start_t, r))) {
t->abort();
throw transaction_abort_exception();
}
transaction::read_record_t *read_rec = &t->read_set[k];
read_rec->t = start_t;
read_rec->r = r;
read_rec->ln = ln;
VERBOSE(cerr << "read <t=" << start_t << ", r=" << size_t(r) << "> (local_read=" << local_read << ")" << endl);
if (!local_read && r)
ret = caller_callback->invoke(k, r);
}
if (ret)
caller_stopped = true;
return ret;
}
bool
txn_btree::absent_range_validation_callback::invoke(key_type k, value_type v)
{
transaction::logical_node *ln = (transaction::logical_node *) v;
assert(ln);
//cout << "absent_range_validation_callback: key " << k << " found ln " << intptr_t(ln) << endl;
bool did_write = t->write_set.find(k) != t->write_set.end();
failed_flag = did_write ? !ln->is_latest_version(0) : !ln->stable_is_latest_version(0);
return !failed_flag;
}
void
txn_btree::search_range_call(transaction &t,
key_type lower,
const key_type *upper,
search_range_callback &callback)
{
assert(!t.btree || t.btree == this);
t.btree = this;
// many cases to consider:
// 1) for each logical_node returned from the scan, we need to
// record it in our local read set. there are several cases:
// A) if the logical_node corresponds to a key we have written, then
// we emit the version from the local write set
// B) if the logical_node corresponds to a key we have previous read,
// then we emit the previous version
// 2) for each logical_node node *not* returned from the scan, we need
// to record its absense. we optimize this by recording the absense
// of contiguous ranges
if (upper && *upper <= lower)
return;
txn_search_range_callback c(&t, lower, upper, &callback);
underlying_btree.search_range_call(lower, upper, c);
if (c.caller_stopped)
return;
if (c.invoked && c.prev_key == (key_type)-1)
return;
if (upper)
t.add_absent_range(transaction::key_range_t(c.invoked ? (c.prev_key + 1): lower, *upper));
else
t.add_absent_range(transaction::key_range_t(c.invoked ? c.prev_key : lower));
}
void
txn_btree::insert_impl(transaction &t, key_type k, value_type v)
{
assert(!t.btree || t.btree == this);
t.btree = this;
t.write_set[k] = v;
}
struct test_callback_ctr {
test_callback_ctr(size_t *ctr) : ctr(ctr) {}
inline bool
operator()(txn_btree::key_type k, txn_btree::value_type v) const
{
(*ctr)++;
return true;
}
size_t *ctr;
};
static void
test1()
{
txn_btree btr;
struct rec { uint64_t v; };
rec recs[10];
for (size_t i = 0; i < ARRAY_NELEMS(recs); i++)
recs[i].v = 0;
{
transaction t;
txn_btree::value_type v;
ALWAYS_ASSERT(!btr.search(t, 0, v));
btr.insert(t, 0, (txn_btree::value_type) &recs[0]);
ALWAYS_ASSERT(btr.search(t, 0, v));
ALWAYS_ASSERT(v == (txn_btree::value_type) &recs[0]);
t.commit();
VERBOSE(cout << "------" << endl);
}
{
transaction t0, t1;
txn_btree::value_type v0, v1;
ALWAYS_ASSERT(btr.search(t0, 0, v0));
ALWAYS_ASSERT(v0 == (txn_btree::value_type) &recs[0]);
btr.insert(t0, 0, (txn_btree::value_type) &recs[1]);
ALWAYS_ASSERT(btr.search(t1, 0, v1));
ALWAYS_ASSERT(v1 == (txn_btree::value_type) &recs[0]);
t0.commit();
t1.commit();
VERBOSE(cout << "------" << endl);
}
{
// racy insert
transaction t0, t1;
txn_btree::value_type v0, v1;
ALWAYS_ASSERT(btr.search(t0, 0, v0));
ALWAYS_ASSERT(v0 == (txn_btree::value_type) &recs[1]);
btr.insert(t0, 0, (txn_btree::value_type) &recs[2]);
ALWAYS_ASSERT(btr.search(t1, 0, v1));
ALWAYS_ASSERT(v1 == (txn_btree::value_type) &recs[1]);
btr.insert(t1, 0, (txn_btree::value_type) &recs[3]);
t0.commit(); // succeeds
try {
t1.commit(); // fails
ALWAYS_ASSERT(false);
} catch (transaction_abort_exception &e) {
}
VERBOSE(cout << "------" << endl);
}
{
// racy scan
transaction t0, t1;
txn_btree::key_type vend = 5;
size_t ctr = 0;
btr.search_range(t0, 1, &vend, test_callback_ctr(&ctr));
ALWAYS_ASSERT(ctr == 0);
btr.insert(t1, 2, (txn_btree::value_type) &recs[4]);
t1.commit();
btr.insert(t0, 0, (txn_btree::value_type) &recs[0]);
try {
t0.commit(); // fails
ALWAYS_ASSERT(false);
} catch (transaction_abort_exception &e) {
}
VERBOSE(cout << "------" << endl);
}
{
transaction t;
txn_btree::key_type vend = 20;
size_t ctr = 0;
btr.search_range(t, 10, &vend, test_callback_ctr(&ctr));
ALWAYS_ASSERT(ctr == 0);
btr.insert(t, 15, (txn_btree::value_type) &recs[5]);
t.commit();
VERBOSE(cout << "------" << endl);
}
}
static void
test2()
{
txn_btree btr;
for (size_t i = 0; i < 100; i++) {
transaction t;
btr.insert(t, 0, (txn_btree::value_type) 123);
t.commit();
}
}
class txn_btree_worker : public ndb_thread {
public:
txn_btree_worker(txn_btree &btr) : btr(&btr) {}
protected:
txn_btree *btr;
};
namespace mp_test1_ns {
// read-modify-write test (counters)
struct record {
record() : v(0) {}
uint64_t v;
};
const size_t niters = 1000;
class worker : public txn_btree_worker {
public:
worker(txn_btree &btr) : txn_btree_worker(btr) {}
~worker()
{
for (vector<record *>::iterator it = recs.begin();
it != recs.end(); ++it)
delete *it;
}
virtual void run()
{
for (size_t i = 0; i < niters; i++) {
retry:
transaction t;
record *rec = new record;
recs.push_back(rec);
try {
txn_btree::value_type v = 0;
if (!btr->search(t, 0, v)) {
rec->v = 1;
} else {
*rec = *((record *)v);
rec->v++;
}
btr->insert(t, 0, (txn_btree::value_type) rec);
t.commit();
} catch (transaction_abort_exception &e) {
goto retry;
}
}
}
private:
vector<record *> recs;
};
}
static void
mp_test1()
{
using namespace mp_test1_ns;
txn_btree btr;
worker w0(btr);
worker w1(btr);
w0.start(); w1.start();
w0.join(); w1.join();
transaction t;
txn_btree::value_type v = 0;
ALWAYS_ASSERT(btr.search(t, 0, v));
ALWAYS_ASSERT( ((record *) v)->v == (niters * 2) );
t.commit();
}
namespace mp_test2_ns {
static const size_t ctr_key = 0;
static const txn_btree::key_type range_begin = 100;
static const txn_btree::key_type range_end = 200;
static volatile bool running = true;
class mutate_worker : public txn_btree_worker {
public:
mutate_worker(txn_btree &btr) : txn_btree_worker(btr) {}
virtual void run()
{
while (running) {
for (size_t i = range_begin; running && i < range_end; i++) {
retry:
transaction t;
try {
txn_btree::value_type v = 0, v_ctr = 0;
ALWAYS_ASSERT(btr->search(t, ctr_key, v_ctr));
ALWAYS_ASSERT(size_t(v_ctr) > 1);
if (btr->search(t, i, v)) {
ALWAYS_ASSERT(v = (txn_btree::value_type) i);
btr->remove(t, i);
v_ctr = (txn_btree::value_type)(size_t(v_ctr) - 1);
} else {
btr->insert(t, i, (txn_btree::value_type) i);
v_ctr = (txn_btree::value_type)(size_t(v_ctr) + 1);
}
btr->insert(t, ctr_key, v_ctr);
t.commit();
} catch (transaction_abort_exception &e) {
goto retry;
}
}
}
}
};
class reader_worker : public txn_btree_worker, public txn_btree::search_range_callback {
public:
reader_worker(txn_btree &btr) : txn_btree_worker(btr), validations(0), ctr(0) {}
virtual bool invoke(txn_btree::key_type k, txn_btree::value_type v)
{
ctr++;
return true;
}
virtual void run()
{
while (running) {
try {
transaction t;
txn_btree::value_type v_ctr = 0;
ALWAYS_ASSERT(btr->search(t, ctr_key, v_ctr));
ctr = 0;
btr->search_range_call(t, range_begin, &range_end, *this);
t.commit();
ALWAYS_ASSERT(ctr == size_t(v_ctr));
validations++;
} catch (transaction_abort_exception &e) {
}
}
}
size_t validations;
private:
size_t ctr;
};
}
static void
mp_test2()
{
using namespace mp_test2_ns;
txn_btree btr;
{
transaction t;
size_t n = 0;
for (size_t i = range_begin; i < range_end; i++)
if ((i % 2) == 0) {
btr.insert(t, i, (txn_btree::value_type) i);
n++;
}
btr.insert(t, ctr_key, (txn_btree::value_type) n);
t.commit();
}
mutate_worker w0(btr);
reader_worker w1(btr);
running = true;
w0.start(); w1.start();
sleep(10);
running = false;
w0.join(); w1.join();
cerr << "validations: " << w1.validations << endl;
}
void
txn_btree::Test()
{
test1();
test2();
mp_test1();
mp_test2();
}
<commit_msg>abort stats<commit_after>#include <unistd.h>
#include "txn_btree.h"
#include "thread.h"
#include "util.h"
#define VERBOSE(expr) ((void)0)
using namespace std;
using namespace util;
bool
txn_btree::search(transaction &t, key_type k, value_type &v)
{
assert(!t.btree || t.btree == this);
t.btree = this;
// priority is
// 1) write set
// 2) local read set
// 3) range set
// 4) query underlying tree
//
// note (1)-(3) are served by transaction::local_search()
if (t.local_search(k, v))
return (bool) v;
btree::value_type underlying_v;
if (!underlying_btree.search(k, underlying_v)) {
// all records exist in the system at MIN_TID with no value
transaction::read_record_t *read_rec = &t.read_set[k];
read_rec->t = transaction::MIN_TID;
read_rec->r = NULL;
read_rec->ln = NULL;
return false;
} else {
transaction::logical_node *ln = (transaction::logical_node *) underlying_v;
assert(ln);
transaction::tid_t start_t;
transaction::record_t r;
if (unlikely(!ln->stable_read(t.snapshot_tid, start_t, r))) {
t.abort();
throw transaction_abort_exception();
}
transaction::read_record_t *read_rec = &t.read_set[k];
read_rec->t = start_t;
read_rec->r = r;
read_rec->ln = ln;
v = read_rec->r;
return read_rec->r;
}
}
bool
txn_btree::txn_search_range_callback::invoke(key_type k, value_type v)
{
VERBOSE(cerr << "search range k: " << k << endl);
transaction::key_range_t r(invoked ? prev_key : lower, k);
if (!r.is_empty_range())
t->add_absent_range(r);
prev_key = k;
invoked = true;
value_type local_v = 0;
bool local_read = t->local_search(k, local_v);
bool ret = true;
if (local_read && local_v)
ret = caller_callback->invoke(k, local_v);
map<key_type, transaction::read_record_t>::const_iterator it =
t->read_set.find(k);
if (it == t->read_set.end()) {
transaction::logical_node *ln = (transaction::logical_node *) v;
assert(ln);
transaction::tid_t start_t;
transaction::record_t r;
if (unlikely(!ln->stable_read(t->snapshot_tid, start_t, r))) {
t->abort();
throw transaction_abort_exception();
}
transaction::read_record_t *read_rec = &t->read_set[k];
read_rec->t = start_t;
read_rec->r = r;
read_rec->ln = ln;
VERBOSE(cerr << "read <t=" << start_t << ", r=" << size_t(r) << "> (local_read=" << local_read << ")" << endl);
if (!local_read && r)
ret = caller_callback->invoke(k, r);
}
if (ret)
caller_stopped = true;
return ret;
}
bool
txn_btree::absent_range_validation_callback::invoke(key_type k, value_type v)
{
transaction::logical_node *ln = (transaction::logical_node *) v;
assert(ln);
//cout << "absent_range_validation_callback: key " << k << " found ln " << intptr_t(ln) << endl;
bool did_write = t->write_set.find(k) != t->write_set.end();
failed_flag = did_write ? !ln->is_latest_version(0) : !ln->stable_is_latest_version(0);
return !failed_flag;
}
void
txn_btree::search_range_call(transaction &t,
key_type lower,
const key_type *upper,
search_range_callback &callback)
{
assert(!t.btree || t.btree == this);
t.btree = this;
// many cases to consider:
// 1) for each logical_node returned from the scan, we need to
// record it in our local read set. there are several cases:
// A) if the logical_node corresponds to a key we have written, then
// we emit the version from the local write set
// B) if the logical_node corresponds to a key we have previous read,
// then we emit the previous version
// 2) for each logical_node node *not* returned from the scan, we need
// to record its absense. we optimize this by recording the absense
// of contiguous ranges
if (upper && *upper <= lower)
return;
txn_search_range_callback c(&t, lower, upper, &callback);
underlying_btree.search_range_call(lower, upper, c);
if (c.caller_stopped)
return;
if (c.invoked && c.prev_key == (key_type)-1)
return;
if (upper)
t.add_absent_range(transaction::key_range_t(c.invoked ? (c.prev_key + 1): lower, *upper));
else
t.add_absent_range(transaction::key_range_t(c.invoked ? c.prev_key : lower));
}
void
txn_btree::insert_impl(transaction &t, key_type k, value_type v)
{
assert(!t.btree || t.btree == this);
t.btree = this;
t.write_set[k] = v;
}
struct test_callback_ctr {
test_callback_ctr(size_t *ctr) : ctr(ctr) {}
inline bool
operator()(txn_btree::key_type k, txn_btree::value_type v) const
{
(*ctr)++;
return true;
}
size_t *ctr;
};
static void
test1()
{
txn_btree btr;
struct rec { uint64_t v; };
rec recs[10];
for (size_t i = 0; i < ARRAY_NELEMS(recs); i++)
recs[i].v = 0;
{
transaction t;
txn_btree::value_type v;
ALWAYS_ASSERT(!btr.search(t, 0, v));
btr.insert(t, 0, (txn_btree::value_type) &recs[0]);
ALWAYS_ASSERT(btr.search(t, 0, v));
ALWAYS_ASSERT(v == (txn_btree::value_type) &recs[0]);
t.commit();
VERBOSE(cout << "------" << endl);
}
{
transaction t0, t1;
txn_btree::value_type v0, v1;
ALWAYS_ASSERT(btr.search(t0, 0, v0));
ALWAYS_ASSERT(v0 == (txn_btree::value_type) &recs[0]);
btr.insert(t0, 0, (txn_btree::value_type) &recs[1]);
ALWAYS_ASSERT(btr.search(t1, 0, v1));
ALWAYS_ASSERT(v1 == (txn_btree::value_type) &recs[0]);
t0.commit();
t1.commit();
VERBOSE(cout << "------" << endl);
}
{
// racy insert
transaction t0, t1;
txn_btree::value_type v0, v1;
ALWAYS_ASSERT(btr.search(t0, 0, v0));
ALWAYS_ASSERT(v0 == (txn_btree::value_type) &recs[1]);
btr.insert(t0, 0, (txn_btree::value_type) &recs[2]);
ALWAYS_ASSERT(btr.search(t1, 0, v1));
ALWAYS_ASSERT(v1 == (txn_btree::value_type) &recs[1]);
btr.insert(t1, 0, (txn_btree::value_type) &recs[3]);
t0.commit(); // succeeds
try {
t1.commit(); // fails
ALWAYS_ASSERT(false);
} catch (transaction_abort_exception &e) {
}
VERBOSE(cout << "------" << endl);
}
{
// racy scan
transaction t0, t1;
txn_btree::key_type vend = 5;
size_t ctr = 0;
btr.search_range(t0, 1, &vend, test_callback_ctr(&ctr));
ALWAYS_ASSERT(ctr == 0);
btr.insert(t1, 2, (txn_btree::value_type) &recs[4]);
t1.commit();
btr.insert(t0, 0, (txn_btree::value_type) &recs[0]);
try {
t0.commit(); // fails
ALWAYS_ASSERT(false);
} catch (transaction_abort_exception &e) {
}
VERBOSE(cout << "------" << endl);
}
{
transaction t;
txn_btree::key_type vend = 20;
size_t ctr = 0;
btr.search_range(t, 10, &vend, test_callback_ctr(&ctr));
ALWAYS_ASSERT(ctr == 0);
btr.insert(t, 15, (txn_btree::value_type) &recs[5]);
t.commit();
VERBOSE(cout << "------" << endl);
}
}
static void
test2()
{
txn_btree btr;
for (size_t i = 0; i < 100; i++) {
transaction t;
btr.insert(t, 0, (txn_btree::value_type) 123);
t.commit();
}
}
class txn_btree_worker : public ndb_thread {
public:
txn_btree_worker(txn_btree &btr) : btr(&btr) {}
protected:
txn_btree *btr;
};
namespace mp_test1_ns {
// read-modify-write test (counters)
struct record {
record() : v(0) {}
uint64_t v;
};
const size_t niters = 1000;
class worker : public txn_btree_worker {
public:
worker(txn_btree &btr) : txn_btree_worker(btr) {}
~worker()
{
for (vector<record *>::iterator it = recs.begin();
it != recs.end(); ++it)
delete *it;
}
virtual void run()
{
for (size_t i = 0; i < niters; i++) {
retry:
transaction t;
record *rec = new record;
recs.push_back(rec);
try {
txn_btree::value_type v = 0;
if (!btr->search(t, 0, v)) {
rec->v = 1;
} else {
*rec = *((record *)v);
rec->v++;
}
btr->insert(t, 0, (txn_btree::value_type) rec);
t.commit();
} catch (transaction_abort_exception &e) {
goto retry;
}
}
}
private:
vector<record *> recs;
};
}
static void
mp_test1()
{
using namespace mp_test1_ns;
txn_btree btr;
worker w0(btr);
worker w1(btr);
w0.start(); w1.start();
w0.join(); w1.join();
transaction t;
txn_btree::value_type v = 0;
ALWAYS_ASSERT(btr.search(t, 0, v));
ALWAYS_ASSERT( ((record *) v)->v == (niters * 2) );
t.commit();
}
namespace mp_test2_ns {
static const txn_btree::key_type ctr_key = 0;
static const txn_btree::key_type range_begin = 100;
static const txn_btree::key_type range_end = 200;
static volatile bool running = true;
class mutate_worker : public txn_btree_worker {
public:
mutate_worker(txn_btree &btr) : txn_btree_worker(btr), naborts(0) {}
virtual void run()
{
while (running) {
for (size_t i = range_begin; running && i < range_end; i++) {
retry:
transaction t;
try {
txn_btree::value_type v = 0, v_ctr = 0;
ALWAYS_ASSERT(btr->search(t, ctr_key, v_ctr));
ALWAYS_ASSERT(size_t(v_ctr) > 1);
if (btr->search(t, i, v)) {
ALWAYS_ASSERT(v = (txn_btree::value_type) i);
btr->remove(t, i);
v_ctr = (txn_btree::value_type)(size_t(v_ctr) - 1);
} else {
btr->insert(t, i, (txn_btree::value_type) i);
v_ctr = (txn_btree::value_type)(size_t(v_ctr) + 1);
}
btr->insert(t, ctr_key, v_ctr);
t.commit();
} catch (transaction_abort_exception &e) {
naborts++;
goto retry;
}
}
}
}
size_t naborts;
};
class reader_worker : public txn_btree_worker, public txn_btree::search_range_callback {
public:
reader_worker(txn_btree &btr) : txn_btree_worker(btr), validations(0), naborts(0), ctr(0) {}
virtual bool invoke(txn_btree::key_type k, txn_btree::value_type v)
{
ctr++;
return true;
}
virtual void run()
{
while (running) {
try {
transaction t;
txn_btree::value_type v_ctr = 0;
ALWAYS_ASSERT(btr->search(t, ctr_key, v_ctr));
ctr = 0;
btr->search_range_call(t, range_begin, &range_end, *this);
t.commit();
ALWAYS_ASSERT(ctr == size_t(v_ctr));
validations++;
} catch (transaction_abort_exception &e) {
naborts++;
}
}
}
size_t validations;
size_t naborts;
private:
size_t ctr;
};
}
static void
mp_test2()
{
using namespace mp_test2_ns;
txn_btree btr;
{
transaction t;
size_t n = 0;
for (size_t i = range_begin; i < range_end; i++)
if ((i % 2) == 0) {
btr.insert(t, i, (txn_btree::value_type) i);
n++;
}
btr.insert(t, ctr_key, (txn_btree::value_type) n);
t.commit();
}
mutate_worker w0(btr);
reader_worker w1(btr);
running = true;
w0.start(); w1.start();
sleep(10);
running = false;
w0.join(); w1.join();
cerr << "mutate naborts: " << w0.naborts << endl;
cerr << "reader naborts: " << w1.naborts << endl;
cerr << "validations: " << w1.validations << endl;
}
void
txn_btree::Test()
{
test1();
test2();
mp_test1();
mp_test2();
}
<|endoftext|>
|
<commit_before>#include <ros/ros.h>
#include <tf2_ros/transform_broadcaster.h>
#include <geometry_msgs/PointStamped.h>
#include <geometry_msgs/TransformStamped.h>
class TomatoBroadcaster {
tf2_ros::TransformBroadcaster broadcaster_;
geometry_msgs::TransformStamped transform_;
ros::Subscriber sub_;
public:
TomatoBroadcaster(ros::NodeHandle node_handle)
: transform_ {},
sub_ {node_handle.subscribe<geometry_msgs::PointStamped>("tomato_point", 1, &TomatoBroadcaster::callback, this)}
{
}
private:
void callback(const geometry_msgs::PointStamped::ConstPtr& msg)
{
transform_.header = msg->header;
transform_.header.frame_id = "kinect";
transform_.child_frame_id = "tomato";
transform_.transform.translation.x = msg->point.x;
transform_.transform.translation.y = msg->point.y;
transform_.transform.translation.z = msg->point.z;
transform_.transform.rotation.w = 1.0;
broadcaster_.sendTransform(transform_);
}
};
int main(int argc, char** argv){
ros::init(argc, argv, "kinect_tomato_broadcaster_node");
ros::NodeHandle node_handle;
TomatoBroadcaster broadcaster {node_handle};
ros::spin();
return 0;
}
<commit_msg>Update message type for PoseStamped<commit_after>#include <ros/ros.h>
#include <tf2_ros/transform_broadcaster.h>
#include <geometry_msgs/PoseStamped.h>
#include <geometry_msgs/TransformStamped.h>
class TomatoBroadcaster {
tf2_ros::TransformBroadcaster broadcaster_;
geometry_msgs::TransformStamped transform_;
ros::Subscriber sub_;
public:
TomatoBroadcaster(ros::NodeHandle& node_handle)
: broadcaster_ {},
transform_ {},
sub_ {node_handle.subscribe<geometry_msgs::PoseStamped>("tomato_point", 1, &TomatoBroadcaster::callback, this)}
{
}
private:
void callback(const geometry_msgs::PoseStamped::ConstPtr& msg)
{
transform_.header = msg->header;
transform_.header.frame_id = "kinect";
transform_.child_frame_id = "tomato";
transform_.transform.translation.x = msg->pose.position.x;
transform_.transform.translation.y = msg->pose.position.y;
transform_.transform.translation.z = msg->pose.position.z;
transform_.transform.rotation = msg->pose.orientation;
broadcaster_.sendTransform(transform_);
}
};
int main(int argc, char** argv){
ros::init(argc, argv, "kinect_tomato_broadcaster_node");
ros::NodeHandle node_handle;
TomatoBroadcaster broadcaster {node_handle};
ros::spin();
return 0;
}
<|endoftext|>
|
<commit_before>#include <algorithm>
#include <fstream>
#include <iostream>
#include <map>
#include <sstream>
#include <string>
#include <vector>
#include <getopt.h>
#include "persistenceDiagrams/IO.hh"
#include "persistenceDiagrams/PersistenceDiagram.hh"
#include "persistenceDiagrams/PersistenceIndicatorFunction.hh"
using DataType = double;
using PersistenceDiagram = aleph::PersistenceDiagram<DataType>;
using StepFunction = aleph::math::StepFunction<double>;
/*
Prints a vector in a simple matrix-like format. Given a row index, all
of the entries are considered to be the columns of the matrix:
Input: {4,5,6}, row = 23
Output: 23 0 4
23 1 5
23 2 6
<empty line>
This output format is flexible and permits direct usage in other tools
such as TikZ or pgfplots.
*/
template <class Map> void print( std::ostream& o, const Map& m, unsigned row )
{
unsigned column = 0;
for( auto it = m.begin(); it != m.end(); ++it )
o << column++ << "\t" << row << "\t" << *it << "\n";
o << "\n";
}
int main( int argc, char** argv )
{
static option commandLineOptions[] =
{
{ "min-k", required_argument, nullptr, 'k' },
{ "max-k", required_argument, nullptr, 'K' },
{ nullptr, 0 , nullptr, 0 }
};
int option = 0;
unsigned minK = 0;
unsigned maxK = 0;
while( ( option = getopt_long( argc, argv, "k:K:", commandLineOptions, nullptr ) ) != -1 )
{
switch( option )
{
case 'k':
minK = unsigned( std::stoul( optarg ) );
break;
case 'K':
maxK = unsigned( std::stoul( optarg ) );
break;
default:
break;
}
}
if( argc - optind < 2 )
{
// TODO: Show usage
return -1;
}
unsigned n = static_cast<unsigned>( std::stoul( argv[optind++] ) );
std::vector<std::string> filenames;
std::vector<PersistenceDiagram> persistenceDiagrams;
std::vector<StepFunction> persistenceIndicatorFunctions;
std::set<DataType> domain;
for( int i = optind; i < argc; i++ )
{
filenames.push_back( argv[i] );
std::cerr << "* Processing '" << argv[i] << "'...";
PersistenceDiagram persistenceDiagram
= aleph::load<DataType>( filenames.back() );
persistenceDiagram.removeDiagonal();
persistenceDiagram.removeUnpaired();
persistenceDiagrams.push_back( persistenceDiagram );
persistenceIndicatorFunctions.push_back( aleph::persistenceIndicatorFunction( persistenceDiagram ) );
persistenceIndicatorFunctions.back().domain(
std::inserter( domain, domain.begin() ) );
std::cerr << "finished\n";
}
if( domain.empty() )
return -1;
auto min = *domain.begin();
auto max = *domain.rbegin();
std::cerr << "* Domain: [" << min << "," << max << "]\n";
// Prepare bins ------------------------------------------------------
std::vector<DataType> linbins;
std::vector<DataType> logbins;
linbins.reserve( n );
logbins.reserve( n );
for( unsigned i = 0; i < n; i++ )
{
auto offset = ( max - min ) / (n-1);
auto value = min + i * offset;
linbins.push_back( value );
}
std::cerr << "* Linear-spaced bins: ";
for( auto&& linbin : linbins )
std::cerr << linbin << " ";
std::cerr << "\n";
for( unsigned i = 0; i < n; i++ )
{
auto offset = ( std::log10( max ) - std::log10( min ) ) / (n-1);
auto value = std::log10( min ) + i * offset;
logbins.push_back( value );
}
std::transform( logbins.begin(), logbins.end(),
logbins.begin(),
[] ( const DataType x )
{
return std::pow( DataType(10), x );
} );
std::cerr << "* Log-spaced bins: ";
for( auto&& logbin : logbins )
std::cerr << logbin << " ";
std::cerr << "\n";
for( auto it = linbins.begin(); it != linbins.end(); ++it )
{
if( it != linbins.begin() )
{
auto prev = std::prev( it );
domain.insert( ( *prev + *it ) / 2.0 );
}
}
for( auto it = logbins.begin(); it != logbins.end(); ++it )
{
if( it != logbins.begin() && std::isfinite( *it ) )
{
auto prev = std::prev( it );
domain.insert( ( *prev + *it ) / 2.0 );
}
}
// Prepare histogram calculation -------------------------------------
auto valueToLinIndex = [&min, &max, &linbins, &n] ( DataType value )
{
auto offset = ( max - min ) / (n-1);
return static_cast<std::size_t>( ( value - min ) / offset );
};
auto valueToLogIndex = [&min, &max, &logbins, &n] ( DataType value )
{
auto offset = ( std::log10( max ) - std::log10( min ) ) / (n-1);
return static_cast<std::size_t>( ( std::log10( value ) - std::log10( min ) ) / offset );
};
std::ofstream linout( "/tmp/DNA_" + std::to_string( n ) + "_lin.txt" );
std::ofstream logout( "/tmp/DNA_" + std::to_string( n ) + "_log.txt" );
unsigned index = 0;
for( auto&& pif : persistenceIndicatorFunctions )
{
std::vector<DataType> linhist(n);
std::vector<DataType> loghist(n);
for( auto&& x : domain )
{
auto value = pif(x);
auto linbin = valueToLinIndex(x);
auto logbin = valueToLogIndex(x);
linhist.at(linbin) = std::max( linhist.at(linbin), value );
if( logbin < loghist.size() )
loghist.at(logbin) = std::max( loghist.at(logbin), value );
}
print( linout, linhist, index );
print( logout, loghist, index );
++index;
}
// Extend the output with sufficiently many empty histograms. This
// ensures that the output has the same dimensions.
for( unsigned i = unsigned( persistenceIndicatorFunctions.size() ); i < maxK; i++ )
{
std::vector<DataType> hist(n);
print( linout, hist, i );
print( logout, hist, i );
}
}
<commit_msg>Fixed bin creation for histograms<commit_after>#include <algorithm>
#include <fstream>
#include <iostream>
#include <map>
#include <sstream>
#include <string>
#include <vector>
#include <cmath>
#include <getopt.h>
#include "persistenceDiagrams/IO.hh"
#include "persistenceDiagrams/PersistenceDiagram.hh"
#include "persistenceDiagrams/PersistenceIndicatorFunction.hh"
using DataType = double;
using PersistenceDiagram = aleph::PersistenceDiagram<DataType>;
using StepFunction = aleph::math::StepFunction<double>;
/*
Prints a vector in a simple matrix-like format. Given a row index, all
of the entries are considered to be the columns of the matrix:
Input: {4,5,6}, row = 23
Output: 23 0 4
23 1 5
23 2 6
<empty line>
This output format is flexible and permits direct usage in other tools
such as TikZ or pgfplots.
*/
template <class Map> void print( std::ostream& o, const Map& m, unsigned row )
{
unsigned column = 0;
for( auto it = m.begin(); it != m.end(); ++it )
o << column++ << "\t" << row << "\t" << *it << "\n";
o << "\n";
}
int main( int argc, char** argv )
{
static option commandLineOptions[] =
{
{ "min-k", required_argument, nullptr, 'k' },
{ "max-k", required_argument, nullptr, 'K' },
{ nullptr, 0 , nullptr, 0 }
};
int option = 0;
unsigned minK = 0;
unsigned maxK = 0;
while( ( option = getopt_long( argc, argv, "k:K:", commandLineOptions, nullptr ) ) != -1 )
{
switch( option )
{
case 'k':
minK = unsigned( std::stoul( optarg ) );
break;
case 'K':
maxK = unsigned( std::stoul( optarg ) );
break;
default:
break;
}
}
if( argc - optind < 2 )
{
// TODO: Show usage
return -1;
}
unsigned n = static_cast<unsigned>( std::stoul( argv[optind++] ) );
std::vector<std::string> filenames;
std::vector<PersistenceDiagram> persistenceDiagrams;
std::vector<StepFunction> persistenceIndicatorFunctions;
std::set<DataType> domain;
for( int i = optind; i < argc; i++ )
{
filenames.push_back( argv[i] );
std::cerr << "* Processing '" << argv[i] << "'...";
PersistenceDiagram persistenceDiagram
= aleph::load<DataType>( filenames.back() );
persistenceDiagram.removeDiagonal();
persistenceDiagram.removeUnpaired();
persistenceDiagrams.push_back( persistenceDiagram );
persistenceIndicatorFunctions.push_back( aleph::persistenceIndicatorFunction( persistenceDiagram ) );
persistenceIndicatorFunctions.back().domain(
std::inserter( domain, domain.begin() ) );
std::cerr << "finished\n";
}
if( domain.empty() )
return -1;
auto min = *domain.begin();
auto max = std::nextafter( *domain.rbegin(), std::numeric_limits<DataType>::max() );
std::cerr << "* Domain: [" << min << "," << max << "]\n";
// Prepare bins ------------------------------------------------------
std::vector<DataType> linbins;
std::vector<DataType> logbins;
linbins.reserve( n );
logbins.reserve( n );
for( unsigned i = 0; i < n; i++ )
{
auto offset = ( max - min ) / n;
auto value = min + i * offset;
linbins.push_back( value );
}
std::cerr << "* Linear-spaced bins: ";
for( auto&& linbin : linbins )
std::cerr << linbin << " ";
std::cerr << "\n";
for( unsigned i = 0; i < n; i++ )
{
auto offset = ( std::log10( max ) - std::log10( min ) ) / (n-1);
auto value = std::log10( min ) + i * offset;
logbins.push_back( value );
}
std::transform( logbins.begin(), logbins.end(),
logbins.begin(),
[] ( const DataType x )
{
return std::pow( DataType(10), x );
} );
std::cerr << "* Log-spaced bins: ";
for( auto&& logbin : logbins )
std::cerr << logbin << " ";
std::cerr << "\n";
for( auto it = linbins.begin(); it != linbins.end(); ++it )
{
if( it != linbins.begin() )
{
auto prev = std::prev( it );
domain.insert( ( *prev + *it ) / 2.0 );
}
}
for( auto it = logbins.begin(); it != logbins.end(); ++it )
{
if( it != logbins.begin() && std::isfinite( *it ) )
{
auto prev = std::prev( it );
domain.insert( ( *prev + *it ) / 2.0 );
}
}
// Prepare histogram calculation -------------------------------------
auto valueToLinIndex = [&min, &max, &linbins, &n] ( DataType value )
{
auto offset = ( max - min ) / n;
return static_cast<std::size_t>( ( value - min ) / offset );
};
auto valueToLogIndex = [&min, &max, &logbins, &n] ( DataType value )
{
auto offset = ( std::log10( max ) - std::log10( min ) ) / n;
return static_cast<std::size_t>( ( std::log10( value ) - std::log10( min ) ) / offset );
};
std::ofstream linout( "/tmp/DNA_" + std::to_string( n ) + "_lin.txt" );
std::ofstream logout( "/tmp/DNA_" + std::to_string( n ) + "_log.txt" );
unsigned index = 0;
for( auto&& pif : persistenceIndicatorFunctions )
{
std::vector<DataType> linhist(n);
std::vector<DataType> loghist(n);
for( auto&& x : domain )
{
auto value = pif(x);
auto linbin = valueToLinIndex(x);
auto logbin = valueToLogIndex(x);
linhist.at(linbin) = std::max( linhist.at(linbin), value );
if( logbin < loghist.size() )
loghist.at(logbin) = std::max( loghist.at(logbin), value );
}
print( linout, linhist, index );
print( logout, loghist, index );
++index;
}
// Extend the output with sufficiently many empty histograms. This
// ensures that the output has the same dimensions.
for( unsigned i = unsigned( persistenceIndicatorFunctions.size() ); i < maxK; i++ )
{
std::vector<DataType> hist(n);
print( linout, hist, i );
print( logout, hist, i );
}
}
<|endoftext|>
|
<commit_before>// Copyright 2014 MongoDB 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 "catch.hpp"
#include "helpers.hpp"
#include <mongocxx/private/libmongoc.hpp>
#include <mongocxx/client.hpp>
#include <mongocxx/database.hpp>
using namespace mongocxx;
TEST_CASE("A database", "[database]") {
const std::string database_name("database");
MOCK_CLIENT
MOCK_DATABASE
client mongo_client;
SECTION("is created by a client") {
bool called = false;
get_database->interpose([&](mongoc_client_t* client, const char* c_name) {
called = true;
REQUIRE(database_name == c_name);
return nullptr;
});
database obtained_database = mongo_client[database_name];
REQUIRE(called);
REQUIRE(obtained_database.name() == database_name);
}
SECTION("cleans up its underlying mongoc database on destruction") {
bool destroy_called = false;
database_destroy->interpose([&](mongoc_database_t* client) { destroy_called = true; });
{
database database = mongo_client["database"];
REQUIRE(!destroy_called);
}
REQUIRE(destroy_called);
}
SECTION("supports move operations") {
bool destroy_called = false;
database_destroy->interpose([&](mongoc_database_t* client) { destroy_called = true; });
{
client mongo_client;
database a = mongo_client[database_name];
database b{std::move(a)};
REQUIRE(!destroy_called);
database c = std::move(b);
REQUIRE(!destroy_called);
}
REQUIRE(destroy_called);
}
SECTION("has a read preferences which may be set and obtained") {
bool destroy_called = false;
database_destroy->interpose([&](mongoc_database_t* client) { destroy_called = true; });
database mongo_database(mongo_client["database"]);
read_preference preference{read_preference::read_mode::k_secondary_preferred};
auto deleter = [](mongoc_read_prefs_t* var) { mongoc_read_prefs_destroy(var); };
std::unique_ptr<mongoc_read_prefs_t, decltype(deleter)> saved_preference(nullptr, deleter);
bool called = false;
database_set_preference->interpose([&](mongoc_database_t* db,
const mongoc_read_prefs_t* read_prefs) {
called = true;
saved_preference.reset(mongoc_read_prefs_copy(read_prefs));
REQUIRE(
mongoc_read_prefs_get_mode(read_prefs) ==
static_cast<mongoc_read_mode_t>(read_preference::read_mode::k_secondary_preferred));
});
database_get_preference->interpose([&](const mongoc_database_t* client) {
return saved_preference.get();
}).forever();
mongo_database.read_preference(std::move(preference));
REQUIRE(called);
REQUIRE(read_preference::read_mode::k_secondary_preferred ==
mongo_database.read_preference().mode());
}
SECTION("has a write concern which may be set and obtained") {
bool destroy_called = false;
database_destroy->interpose([&](mongoc_database_t* client) { destroy_called = true; });
database mongo_database(mongo_client[database_name]);
write_concern concern;
concern.majority(std::chrono::milliseconds(100));
mongoc_write_concern_t* underlying_wc;
bool set_called = false;
database_set_concern->interpose(
[&](mongoc_database_t* client, const mongoc_write_concern_t* concern) {
set_called = true;
underlying_wc = mongoc_write_concern_copy(concern);
});
bool get_called = false;
database_get_concern->interpose([&](const mongoc_database_t* client) {
get_called = true;
return underlying_wc;
});
mongo_database.write_concern(concern);
REQUIRE(set_called);
MOCK_CONCERN
bool copy_called = false;
concern_copy->interpose([&](const mongoc_write_concern_t* concern) {
copy_called = true;
return mongoc_write_concern_copy(underlying_wc);
});
REQUIRE(concern.majority() == mongo_database.write_concern().majority());
REQUIRE(get_called);
REQUIRE(copy_called);
}
SECTION("may create a collection") {
MOCK_COLLECTION
const std::string collection_name("collection");
database database = mongo_client[database_name];
collection obtained_collection = database[collection_name];
REQUIRE(obtained_collection.name() == collection_name);
}
}
<commit_msg>Fix some names and whitespace<commit_after>// Copyright 2014 MongoDB 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 "catch.hpp"
#include "helpers.hpp"
#include <mongocxx/private/libmongoc.hpp>
#include <mongocxx/client.hpp>
#include <mongocxx/database.hpp>
using namespace mongocxx;
TEST_CASE("A database", "[database]") {
const std::string database_name("database");
MOCK_CLIENT
MOCK_DATABASE
client mongo_client;
SECTION("is created by a client") {
bool called = false;
get_database->interpose([&](mongoc_client_t* client, const char* d_name) {
called = true;
REQUIRE(database_name == d_name);
return nullptr;
});
database obtained_database = mongo_client[database_name];
REQUIRE(called);
REQUIRE(obtained_database.name() == database_name);
}
SECTION("cleans up its underlying mongoc database on destruction") {
bool destroy_called = false;
database_destroy->interpose([&](mongoc_database_t* client) { destroy_called = true; });
{
database database = mongo_client["database"];
REQUIRE(!destroy_called);
}
REQUIRE(destroy_called);
}
SECTION("supports move operations") {
bool destroy_called = false;
database_destroy->interpose([&](mongoc_database_t* client) { destroy_called = true; });
{
client mongo_client;
database a = mongo_client[database_name];
database b{std::move(a)};
REQUIRE(!destroy_called);
database c = std::move(b);
REQUIRE(!destroy_called);
}
REQUIRE(destroy_called);
}
SECTION("has a read preferences which may be set and obtained") {
bool destroy_called = false;
database_destroy->interpose([&](mongoc_database_t* client) { destroy_called = true; });
database mongo_database(mongo_client["database"]);
read_preference preference{read_preference::read_mode::k_secondary_preferred};
auto deleter = [](mongoc_read_prefs_t* var) { mongoc_read_prefs_destroy(var); };
std::unique_ptr<mongoc_read_prefs_t, decltype(deleter)> saved_preference(nullptr, deleter);
bool called = false;
database_set_preference->interpose([&](mongoc_database_t* db,
const mongoc_read_prefs_t* read_prefs) {
called = true;
saved_preference.reset(mongoc_read_prefs_copy(read_prefs));
REQUIRE(
mongoc_read_prefs_get_mode(read_prefs) ==
static_cast<mongoc_read_mode_t>(read_preference::read_mode::k_secondary_preferred));
});
database_get_preference->interpose([&](const mongoc_database_t* client) {
return saved_preference.get();
}).forever();
mongo_database.read_preference(std::move(preference));
REQUIRE(called);
REQUIRE(read_preference::read_mode::k_secondary_preferred ==
mongo_database.read_preference().mode());
}
SECTION("has a write concern which may be set and obtained") {
bool destroy_called = false;
database_destroy->interpose([&](mongoc_database_t* client) { destroy_called = true; });
database mongo_database(mongo_client[database_name]);
write_concern concern;
concern.majority(std::chrono::milliseconds(100));
mongoc_write_concern_t* underlying_wc;
bool set_called = false;
database_set_concern->interpose(
[&](mongoc_database_t* client, const mongoc_write_concern_t* concern) {
set_called = true;
underlying_wc = mongoc_write_concern_copy(concern);
});
bool get_called = false;
database_get_concern->interpose([&](const mongoc_database_t* client) {
get_called = true;
return underlying_wc;
});
mongo_database.write_concern(concern);
REQUIRE(set_called);
MOCK_CONCERN
bool copy_called = false;
concern_copy->interpose([&](const mongoc_write_concern_t* concern) {
copy_called = true;
return mongoc_write_concern_copy(underlying_wc);
});
REQUIRE(concern.majority() == mongo_database.write_concern().majority());
REQUIRE(get_called);
REQUIRE(copy_called);
}
SECTION("may create a collection") {
MOCK_COLLECTION
const std::string collection_name("collection");
database database = mongo_client[database_name];
collection obtained_collection = database[collection_name];
REQUIRE(obtained_collection.name() == collection_name);
}
}
<|endoftext|>
|
<commit_before>/*
* Copyright 2002-2013 Jose Fonseca
*
* 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.
*
* 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 <map>
#include <assert.h>
#include <stdlib.h>
#include <windows.h>
#include <tchar.h>
#include <ntstatus.h>
#include "debugger.h"
#include "log.h"
#include "outdbg.h"
#include "symbols.h"
typedef struct {
HANDLE hThread;
}
THREAD_INFO, * PTHREAD_INFO;
typedef std::map< DWORD, THREAD_INFO > THREAD_INFO_LIST;
typedef struct {
HANDLE hProcess;
THREAD_INFO_LIST Threads;
}
PROCESS_INFO, * PPROCESS_INFO;
typedef std::map< DWORD, PROCESS_INFO> PROCESS_INFO_LIST;
static PROCESS_INFO_LIST g_Processes;
BOOL ObtainSeDebugPrivilege(void)
{
HANDLE hToken;
PTOKEN_PRIVILEGES NewPrivileges;
BYTE OldPriv[1024];
PBYTE pbOldPriv;
ULONG cbNeeded;
BOOLEAN fRc;
LUID LuidPrivilege;
// Make sure we have access to adjust and to get the old token privileges
if (!OpenProcessToken(GetCurrentProcess(), TOKEN_ADJUST_PRIVILEGES | TOKEN_QUERY, &hToken))
{
OutputDebug("OpenProcessToken failed with 0x%08lx\n", GetLastError());
return FALSE;
}
cbNeeded = 0;
// Initialize the privilege adjustment structure
LookupPrivilegeValue( NULL, SE_DEBUG_NAME, &LuidPrivilege );
NewPrivileges = (PTOKEN_PRIVILEGES) LocalAlloc(
LMEM_ZEROINIT,
sizeof(TOKEN_PRIVILEGES) + (1 - ANYSIZE_ARRAY)*sizeof(LUID_AND_ATTRIBUTES)
);
if(NewPrivileges == NULL) {
return FALSE;
}
NewPrivileges->PrivilegeCount = 1;
NewPrivileges->Privileges[0].Luid = LuidPrivilege;
NewPrivileges->Privileges[0].Attributes = SE_PRIVILEGE_ENABLED;
// Enable the privilege
pbOldPriv = OldPriv;
fRc = AdjustTokenPrivileges(
hToken,
FALSE,
NewPrivileges,
1024,
(PTOKEN_PRIVILEGES)pbOldPriv,
&cbNeeded
);
if (!fRc) {
// If the stack was too small to hold the privileges
// then allocate off the heap
if (GetLastError() == ERROR_INSUFFICIENT_BUFFER) {
pbOldPriv = (PBYTE)LocalAlloc(LMEM_FIXED, cbNeeded);
if (pbOldPriv == NULL) {
return FALSE;
}
fRc = AdjustTokenPrivileges(
hToken,
FALSE,
NewPrivileges,
cbNeeded,
(PTOKEN_PRIVILEGES)pbOldPriv,
&cbNeeded
);
}
}
return fRc;
}
static BOOL CALLBACK
symCallback(HANDLE hProcess,
ULONG ActionCode,
ULONG64 CallbackData,
ULONG64 UserContext)
{
if (ActionCode == CBA_DEBUG_INFO) {
lprintf("%s", (LPCSTR)(UINT_PTR)CallbackData);
return TRUE;
}
return FALSE;
}
static char *
readProcessString(HANDLE hProcess, LPCVOID lpBaseAddress, SIZE_T nSize)
{
LPSTR lpszBuffer = (LPSTR)malloc(nSize + 1);
SIZE_T NumberOfBytesRead = 0;
if (!ReadProcessMemory(hProcess, lpBaseAddress, lpszBuffer, nSize, &NumberOfBytesRead)) {
lpszBuffer[0] = '\0';
}
assert(NumberOfBytesRead <= nSize);
lpszBuffer[NumberOfBytesRead] = '\0';
return lpszBuffer;
}
BOOL DebugMainLoop(const DebugOptions *pOptions)
{
BOOL fFinished = FALSE;
BOOL fBreakpointSignalled = FALSE;
BOOL fWowBreakpointSignalled = FALSE;
while(!fFinished)
{
DEBUG_EVENT DebugEvent; // debugging event information
DWORD dwContinueStatus = DBG_CONTINUE; // exception continuation
PPROCESS_INFO pProcessInfo;
PTHREAD_INFO pThreadInfo;
// Wait for a debugging event to occur. The second parameter indicates
// that the function does not return until a debugging event occurs.
if(!WaitForDebugEvent(&DebugEvent, INFINITE))
{
OutputDebug("WaitForDebugEvent: 0x%08lx", GetLastError());
return FALSE;
}
// Process the debugging event code.
switch (DebugEvent.dwDebugEventCode) {
case EXCEPTION_DEBUG_EVENT: {
PEXCEPTION_RECORD pExceptionRecord = &DebugEvent.u.Exception.ExceptionRecord;
NTSTATUS ExceptionCode = pExceptionRecord->ExceptionCode;
// Process the exception code. When handling
// exceptions, remember to set the continuation
// status parameter (dwContinueStatus). This value
// is used by the ContinueDebugEvent function.
if (pOptions->debug_flag) {
lprintf("EXCEPTION PID=%lu TID=%lu ExceptionCode=0x%lx dwFirstChance=%lu\r\n",
DebugEvent.dwProcessId,
DebugEvent.dwThreadId,
pExceptionRecord->ExceptionCode,
DebugEvent.u.Exception.dwFirstChance
);
}
dwContinueStatus = DBG_EXCEPTION_NOT_HANDLED;
if (DebugEvent.u.Exception.dwFirstChance) {
if (pExceptionRecord->ExceptionCode == (DWORD)STATUS_BREAKPOINT) {
// Signal the aedebug event
if (!fBreakpointSignalled) {
fBreakpointSignalled = TRUE;
if (pOptions->hEvent) {
SetEvent(pOptions->hEvent);
CloseHandle(pOptions->hEvent);
}
/*
* We ignore first-chance breakpoints by default.
*
* We get one of these whenever we attach to a process.
* But in some cases, we never get a second-chance, e.g.,
* when we're attached through MSVCRT's abort().
*/
if (!pOptions->breakpoint_flag) {
dwContinueStatus = DBG_CONTINUE;
break;
}
}
}
if (ExceptionCode == STATUS_WX86_BREAKPOINT) {
if (!fWowBreakpointSignalled) {
fWowBreakpointSignalled = TRUE;
dwContinueStatus = DBG_CONTINUE;
}
}
if (!pOptions->first_chance) {
break;
}
}
// Find the process in the process list
pProcessInfo = &g_Processes[DebugEvent.dwProcessId];
SymRefreshModuleList(pProcessInfo->hProcess);
dumpException(pProcessInfo->hProcess,
&DebugEvent.u.Exception.ExceptionRecord);
// Find the thread in the thread list
THREAD_INFO_LIST::const_iterator it;
for (it = pProcessInfo->Threads.begin(); it != pProcessInfo->Threads.end(); ++it) {
DWORD dwThreadId = it->first;
if (dwThreadId != DebugEvent.dwThreadId &&
ExceptionCode != STATUS_BREAKPOINT &&
!pOptions->verbose_flag) {
continue;
}
dumpStack(pProcessInfo->hProcess,
pThreadInfo->hThread, NULL);
}
if (!DebugEvent.u.Exception.dwFirstChance) {
/*
* Terminate the process. As continuing would cause the JIT debugger
* to be invoked again.
*/
TerminateProcess(pProcessInfo->hProcess, (UINT)ExceptionCode);
}
break;
}
case CREATE_THREAD_DEBUG_EVENT:
if (pOptions->debug_flag) {
lprintf("CREATE_THREAD PID=%lu TID=%lu\r\n",
DebugEvent.dwProcessId,
DebugEvent.dwThreadId
);
}
// Add the thread to the thread list
pProcessInfo = &g_Processes[DebugEvent.dwProcessId];
pThreadInfo = &pProcessInfo->Threads[DebugEvent.dwThreadId];
pThreadInfo->hThread = DebugEvent.u.CreateThread.hThread;
break;
case CREATE_PROCESS_DEBUG_EVENT: {
if (pOptions->debug_flag) {
lprintf("CREATE_PROCESS PID=%lu TID=%lu\r\n",
DebugEvent.dwProcessId,
DebugEvent.dwThreadId
);
}
HANDLE hProcess = DebugEvent.u.CreateProcessInfo.hProcess;
pProcessInfo = &g_Processes[DebugEvent.dwProcessId];
pProcessInfo->hProcess = hProcess;
pThreadInfo = &pProcessInfo->Threads[DebugEvent.dwThreadId];
pThreadInfo->hThread = DebugEvent.u.CreateProcessInfo.hThread;
DWORD dwSymOptions = SymGetOptions();
dwSymOptions |=
SYMOPT_LOAD_LINES |
SYMOPT_DEFERRED_LOADS;
if (pOptions->debug_flag) {
//dwSymOptions |= SYMOPT_DEBUG;
}
#ifdef _WIN64
BOOL bWow64 = FALSE;
IsWow64Process(hProcess, &bWow64);
if (bWow64) {
dwSymOptions |= SYMOPT_INCLUDE_32BIT_MODULES;
}
#endif
SymSetOptions(dwSymOptions);
if (!InitializeSym(hProcess, FALSE)) {
OutputDebug("error: SymInitialize failed: 0x%08lx\n", GetLastError());
exit(EXIT_FAILURE);
}
SymRegisterCallback64(hProcess, &symCallback, 0);
break;
}
case EXIT_THREAD_DEBUG_EVENT:
if (pOptions->debug_flag) {
lprintf("EXIT_THREAD PID=%lu TID=%lu dwExitCode=0x%lx\r\n",
DebugEvent.dwProcessId,
DebugEvent.dwThreadId,
DebugEvent.u.ExitThread.dwExitCode
);
}
// Remove the thread from the thread list
pProcessInfo = &g_Processes[DebugEvent.dwProcessId];
pProcessInfo->Threads.erase(DebugEvent.dwThreadId);
break;
case EXIT_PROCESS_DEBUG_EVENT: {
if (pOptions->debug_flag) {
lprintf("EXIT_PROCESS PID=%lu TID=%lu dwExitCode=0x%lx\r\n",
DebugEvent.dwProcessId,
DebugEvent.dwThreadId,
DebugEvent.u.ExitProcess.dwExitCode
);
}
// Remove the process from the process list
HANDLE hProcess = g_Processes[DebugEvent.dwProcessId].hProcess;
g_Processes.erase(DebugEvent.dwProcessId);
if (!SymCleanup(hProcess)) {
OutputDebug("SymCleanup failed with 0x%08lx\n", GetLastError());
}
if (g_Processes.empty()) {
fFinished = TRUE;
}
break;
}
case LOAD_DLL_DEBUG_EVENT:
if (pOptions->debug_flag) {
lprintf("LOAD_DLL PID=%lu TID=%lu lpBaseOfDll=%p\r\n",
DebugEvent.dwProcessId,
DebugEvent.dwThreadId,
DebugEvent.u.LoadDll.lpBaseOfDll
);
}
break;
case UNLOAD_DLL_DEBUG_EVENT:
if (pOptions->debug_flag) {
lprintf("UNLOAD_DLL PID=%lu TID=%lu lpBaseOfDll=%p\r\n",
DebugEvent.dwProcessId,
DebugEvent.dwThreadId,
DebugEvent.u.UnloadDll.lpBaseOfDll
);
}
break;
case OUTPUT_DEBUG_STRING_EVENT: {
if (pOptions->debug_flag) {
lprintf("OUTPUT_DEBUG_STRING PID=%lu TID=%lu\r\n",
DebugEvent.dwProcessId,
DebugEvent.dwThreadId
);
}
pProcessInfo = &g_Processes[DebugEvent.dwProcessId];
assert(!DebugEvent.u.DebugString.fUnicode);
LPSTR lpDebugStringData = readProcessString(pProcessInfo->hProcess,
DebugEvent.u.DebugString.lpDebugStringData,
DebugEvent.u.DebugString.nDebugStringLength);
fputs(lpDebugStringData, stderr);
free(lpDebugStringData);
break;
}
case RIP_EVENT:
if (pOptions->debug_flag) {
lprintf("RIP PID=%lu TID=%lu\r\n",
DebugEvent.dwProcessId,
DebugEvent.dwThreadId
);
}
break;
default:
if (pOptions->debug_flag) {
lprintf("EVENT%lu PID=%lu TID=%lu\r\n",
DebugEvent.dwDebugEventCode,
DebugEvent.dwProcessId,
DebugEvent.dwThreadId
);
}
break;
}
// Resume executing the thread that reported the debugging event.
ContinueDebugEvent(
DebugEvent.dwProcessId,
DebugEvent.dwThreadId,
dwContinueStatus
);
}
return TRUE;
}
<commit_msg>debugger: Dump stack on abort.<commit_after>/*
* Copyright 2002-2013 Jose Fonseca
*
* 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.
*
* 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 <map>
#include <assert.h>
#include <stdlib.h>
#include <windows.h>
#include <tchar.h>
#include <ntstatus.h>
#include "debugger.h"
#include "log.h"
#include "outdbg.h"
#include "symbols.h"
typedef struct {
HANDLE hThread;
}
THREAD_INFO, * PTHREAD_INFO;
typedef std::map< DWORD, THREAD_INFO > THREAD_INFO_LIST;
typedef struct {
HANDLE hProcess;
THREAD_INFO_LIST Threads;
}
PROCESS_INFO, * PPROCESS_INFO;
typedef std::map< DWORD, PROCESS_INFO> PROCESS_INFO_LIST;
static PROCESS_INFO_LIST g_Processes;
BOOL ObtainSeDebugPrivilege(void)
{
HANDLE hToken;
PTOKEN_PRIVILEGES NewPrivileges;
BYTE OldPriv[1024];
PBYTE pbOldPriv;
ULONG cbNeeded;
BOOLEAN fRc;
LUID LuidPrivilege;
// Make sure we have access to adjust and to get the old token privileges
if (!OpenProcessToken(GetCurrentProcess(), TOKEN_ADJUST_PRIVILEGES | TOKEN_QUERY, &hToken))
{
OutputDebug("OpenProcessToken failed with 0x%08lx\n", GetLastError());
return FALSE;
}
cbNeeded = 0;
// Initialize the privilege adjustment structure
LookupPrivilegeValue( NULL, SE_DEBUG_NAME, &LuidPrivilege );
NewPrivileges = (PTOKEN_PRIVILEGES) LocalAlloc(
LMEM_ZEROINIT,
sizeof(TOKEN_PRIVILEGES) + (1 - ANYSIZE_ARRAY)*sizeof(LUID_AND_ATTRIBUTES)
);
if(NewPrivileges == NULL) {
return FALSE;
}
NewPrivileges->PrivilegeCount = 1;
NewPrivileges->Privileges[0].Luid = LuidPrivilege;
NewPrivileges->Privileges[0].Attributes = SE_PRIVILEGE_ENABLED;
// Enable the privilege
pbOldPriv = OldPriv;
fRc = AdjustTokenPrivileges(
hToken,
FALSE,
NewPrivileges,
1024,
(PTOKEN_PRIVILEGES)pbOldPriv,
&cbNeeded
);
if (!fRc) {
// If the stack was too small to hold the privileges
// then allocate off the heap
if (GetLastError() == ERROR_INSUFFICIENT_BUFFER) {
pbOldPriv = (PBYTE)LocalAlloc(LMEM_FIXED, cbNeeded);
if (pbOldPriv == NULL) {
return FALSE;
}
fRc = AdjustTokenPrivileges(
hToken,
FALSE,
NewPrivileges,
cbNeeded,
(PTOKEN_PRIVILEGES)pbOldPriv,
&cbNeeded
);
}
}
return fRc;
}
static BOOL CALLBACK
symCallback(HANDLE hProcess,
ULONG ActionCode,
ULONG64 CallbackData,
ULONG64 UserContext)
{
if (ActionCode == CBA_DEBUG_INFO) {
lprintf("%s", (LPCSTR)(UINT_PTR)CallbackData);
return TRUE;
}
return FALSE;
}
static char *
readProcessString(HANDLE hProcess, LPCVOID lpBaseAddress, SIZE_T nSize)
{
LPSTR lpszBuffer = (LPSTR)malloc(nSize + 1);
SIZE_T NumberOfBytesRead = 0;
if (!ReadProcessMemory(hProcess, lpBaseAddress, lpszBuffer, nSize, &NumberOfBytesRead)) {
lpszBuffer[0] = '\0';
}
assert(NumberOfBytesRead <= nSize);
lpszBuffer[NumberOfBytesRead] = '\0';
return lpszBuffer;
}
BOOL DebugMainLoop(const DebugOptions *pOptions)
{
BOOL fFinished = FALSE;
BOOL fBreakpointSignalled = FALSE;
BOOL fWowBreakpointSignalled = FALSE;
while(!fFinished)
{
DEBUG_EVENT DebugEvent; // debugging event information
DWORD dwContinueStatus = DBG_CONTINUE; // exception continuation
PPROCESS_INFO pProcessInfo;
PTHREAD_INFO pThreadInfo;
HANDLE hProcess;
// Wait for a debugging event to occur. The second parameter indicates
// that the function does not return until a debugging event occurs.
if(!WaitForDebugEvent(&DebugEvent, INFINITE))
{
OutputDebug("WaitForDebugEvent: 0x%08lx", GetLastError());
return FALSE;
}
// Process the debugging event code.
switch (DebugEvent.dwDebugEventCode) {
case EXCEPTION_DEBUG_EVENT: {
PEXCEPTION_RECORD pExceptionRecord = &DebugEvent.u.Exception.ExceptionRecord;
NTSTATUS ExceptionCode = pExceptionRecord->ExceptionCode;
// Process the exception code. When handling
// exceptions, remember to set the continuation
// status parameter (dwContinueStatus). This value
// is used by the ContinueDebugEvent function.
if (pOptions->debug_flag) {
lprintf("EXCEPTION PID=%lu TID=%lu ExceptionCode=0x%lx dwFirstChance=%lu\r\n",
DebugEvent.dwProcessId,
DebugEvent.dwThreadId,
pExceptionRecord->ExceptionCode,
DebugEvent.u.Exception.dwFirstChance
);
}
dwContinueStatus = DBG_EXCEPTION_NOT_HANDLED;
if (DebugEvent.u.Exception.dwFirstChance) {
if (pExceptionRecord->ExceptionCode == (DWORD)STATUS_BREAKPOINT) {
// Signal the aedebug event
if (!fBreakpointSignalled) {
fBreakpointSignalled = TRUE;
if (pOptions->hEvent) {
SetEvent(pOptions->hEvent);
CloseHandle(pOptions->hEvent);
}
/*
* We ignore first-chance breakpoints by default.
*
* We get one of these whenever we attach to a process.
* But in some cases, we never get a second-chance, e.g.,
* when we're attached through MSVCRT's abort().
*/
if (!pOptions->breakpoint_flag) {
dwContinueStatus = DBG_CONTINUE;
break;
}
}
}
if (ExceptionCode == STATUS_WX86_BREAKPOINT) {
if (!fWowBreakpointSignalled) {
fWowBreakpointSignalled = TRUE;
dwContinueStatus = DBG_CONTINUE;
}
}
if (!pOptions->first_chance) {
break;
}
}
// Find the process in the process list
pProcessInfo = &g_Processes[DebugEvent.dwProcessId];
SymRefreshModuleList(pProcessInfo->hProcess);
dumpException(pProcessInfo->hProcess,
&DebugEvent.u.Exception.ExceptionRecord);
// Find the thread in the thread list
THREAD_INFO_LIST::const_iterator it;
for (it = pProcessInfo->Threads.begin(); it != pProcessInfo->Threads.end(); ++it) {
DWORD dwThreadId = it->first;
if (dwThreadId != DebugEvent.dwThreadId &&
ExceptionCode != STATUS_BREAKPOINT &&
!pOptions->verbose_flag) {
continue;
}
dumpStack(pProcessInfo->hProcess,
pThreadInfo->hThread, NULL);
}
if (!DebugEvent.u.Exception.dwFirstChance) {
/*
* Terminate the process. As continuing would cause the JIT debugger
* to be invoked again.
*/
TerminateProcess(pProcessInfo->hProcess, (UINT)ExceptionCode);
}
break;
}
case CREATE_THREAD_DEBUG_EVENT:
if (pOptions->debug_flag) {
lprintf("CREATE_THREAD PID=%lu TID=%lu\r\n",
DebugEvent.dwProcessId,
DebugEvent.dwThreadId
);
}
// Add the thread to the thread list
pProcessInfo = &g_Processes[DebugEvent.dwProcessId];
pThreadInfo = &pProcessInfo->Threads[DebugEvent.dwThreadId];
pThreadInfo->hThread = DebugEvent.u.CreateThread.hThread;
break;
case CREATE_PROCESS_DEBUG_EVENT: {
if (pOptions->debug_flag) {
lprintf("CREATE_PROCESS PID=%lu TID=%lu\r\n",
DebugEvent.dwProcessId,
DebugEvent.dwThreadId
);
}
hProcess = DebugEvent.u.CreateProcessInfo.hProcess;
pProcessInfo = &g_Processes[DebugEvent.dwProcessId];
pProcessInfo->hProcess = hProcess;
pThreadInfo = &pProcessInfo->Threads[DebugEvent.dwThreadId];
pThreadInfo->hThread = DebugEvent.u.CreateProcessInfo.hThread;
DWORD dwSymOptions = SymGetOptions();
dwSymOptions |=
SYMOPT_LOAD_LINES |
SYMOPT_DEFERRED_LOADS;
if (pOptions->debug_flag) {
//dwSymOptions |= SYMOPT_DEBUG;
}
#ifdef _WIN64
BOOL bWow64 = FALSE;
IsWow64Process(hProcess, &bWow64);
if (bWow64) {
dwSymOptions |= SYMOPT_INCLUDE_32BIT_MODULES;
}
#endif
SymSetOptions(dwSymOptions);
if (!InitializeSym(hProcess, FALSE)) {
OutputDebug("error: SymInitialize failed: 0x%08lx\n", GetLastError());
exit(EXIT_FAILURE);
}
SymRegisterCallback64(hProcess, &symCallback, 0);
break;
}
case EXIT_THREAD_DEBUG_EVENT:
if (pOptions->debug_flag) {
lprintf("EXIT_THREAD PID=%lu TID=%lu dwExitCode=0x%lx\r\n",
DebugEvent.dwProcessId,
DebugEvent.dwThreadId,
DebugEvent.u.ExitThread.dwExitCode
);
}
// Remove the thread from the thread list
pProcessInfo = &g_Processes[DebugEvent.dwProcessId];
pProcessInfo->Threads.erase(DebugEvent.dwThreadId);
break;
case EXIT_PROCESS_DEBUG_EVENT: {
if (pOptions->debug_flag) {
lprintf("EXIT_PROCESS PID=%lu TID=%lu dwExitCode=0x%lx\r\n",
DebugEvent.dwProcessId,
DebugEvent.dwThreadId,
DebugEvent.u.ExitProcess.dwExitCode
);
}
pProcessInfo = &g_Processes[DebugEvent.dwProcessId];
hProcess = pProcessInfo->hProcess;
// Dump the stack on abort()
if (DebugEvent.u.ExitProcess.dwExitCode == 3) {
pThreadInfo = &pProcessInfo->Threads[DebugEvent.dwThreadId];
dumpStack(hProcess, pThreadInfo->hThread, NULL);
}
// Remove the process from the process list
g_Processes.erase(DebugEvent.dwProcessId);
if (!SymCleanup(hProcess)) {
OutputDebug("SymCleanup failed with 0x%08lx\n", GetLastError());
}
if (g_Processes.empty()) {
fFinished = TRUE;
}
break;
}
case LOAD_DLL_DEBUG_EVENT:
if (pOptions->debug_flag) {
lprintf("LOAD_DLL PID=%lu TID=%lu lpBaseOfDll=%p\r\n",
DebugEvent.dwProcessId,
DebugEvent.dwThreadId,
DebugEvent.u.LoadDll.lpBaseOfDll
);
}
break;
case UNLOAD_DLL_DEBUG_EVENT:
if (pOptions->debug_flag) {
lprintf("UNLOAD_DLL PID=%lu TID=%lu lpBaseOfDll=%p\r\n",
DebugEvent.dwProcessId,
DebugEvent.dwThreadId,
DebugEvent.u.UnloadDll.lpBaseOfDll
);
}
break;
case OUTPUT_DEBUG_STRING_EVENT: {
if (pOptions->debug_flag) {
lprintf("OUTPUT_DEBUG_STRING PID=%lu TID=%lu\r\n",
DebugEvent.dwProcessId,
DebugEvent.dwThreadId
);
}
pProcessInfo = &g_Processes[DebugEvent.dwProcessId];
assert(!DebugEvent.u.DebugString.fUnicode);
LPSTR lpDebugStringData = readProcessString(pProcessInfo->hProcess,
DebugEvent.u.DebugString.lpDebugStringData,
DebugEvent.u.DebugString.nDebugStringLength);
fputs(lpDebugStringData, stderr);
free(lpDebugStringData);
break;
}
case RIP_EVENT:
if (pOptions->debug_flag) {
lprintf("RIP PID=%lu TID=%lu\r\n",
DebugEvent.dwProcessId,
DebugEvent.dwThreadId
);
}
break;
default:
if (pOptions->debug_flag) {
lprintf("EVENT%lu PID=%lu TID=%lu\r\n",
DebugEvent.dwDebugEventCode,
DebugEvent.dwProcessId,
DebugEvent.dwThreadId
);
}
break;
}
// Resume executing the thread that reported the debugging event.
ContinueDebugEvent(
DebugEvent.dwProcessId,
DebugEvent.dwThreadId,
dwContinueStatus
);
}
return TRUE;
}
<|endoftext|>
|
<commit_before>// (C) 2014 Arek Olek
#pragma once
#include <random>
#include <vector>
#include <boost/graph/adjacency_list.hpp>
#include <boost/graph/random_spanning_tree.hpp>
#include <boost/graph/named_function_params.hpp>
#include "range.hpp"
template <class Vertex, class Graph>
Vertex random_neighbor(Vertex const & v, Graph const & G) {
unsigned target = random<unsigned>(0, out_degree(v, G)-1);
for(auto w : range(adjacent_vertices(v, G)))
if(target-- == 0) return w;
throw "Ouch.";
}
template <class Graph, class Tree>
Tree random_tree(Graph& G) {
unsigned n = num_vertices(G);
std::vector<bool> visited(n, false);
Tree T(n);
unsigned v = random<unsigned>(0, n-1);
while(num_edges(T) < n-1) {
visited[v] = true;
auto w = random_neighbor(v, G);
if(!visited[w]) add_edge(v, w, T);
v = w;
}
return T;
}
template <class Graph, class Tree>
Tree wilson_tree(Graph& G) {
unsigned n = num_vertices(G);
std::vector<int> pred(n);
std::default_random_engine gen;
random_spanning_tree(G, gen, boost::predecessor_map(&pred[0]));
Tree T(n);
for(int i = 0; i < n; ++i)
if(pred[i] != boost::graph_traits<Graph>::null_vertex())
add_edge(i, pred[i], T);
return T;
}
<commit_msg>don't reset random engine in subsequent wilson invocations<commit_after>// (C) 2014 Arek Olek
#pragma once
#include <random>
#include <vector>
#include <boost/graph/adjacency_list.hpp>
#include <boost/graph/random_spanning_tree.hpp>
#include <boost/graph/named_function_params.hpp>
#include "range.hpp"
template <class Vertex, class Graph>
Vertex random_neighbor(Vertex const & v, Graph const & G) {
unsigned target = random<unsigned>(0, out_degree(v, G)-1);
for(auto w : range(adjacent_vertices(v, G)))
if(target-- == 0) return w;
throw "Ouch.";
}
template <class Graph, class Tree>
Tree random_tree(Graph& G) {
unsigned n = num_vertices(G);
std::vector<bool> visited(n, false);
Tree T(n);
unsigned v = random<unsigned>(0, n-1);
while(num_edges(T) < n-1) {
visited[v] = true;
auto w = random_neighbor(v, G);
if(!visited[w]) add_edge(v, w, T);
v = w;
}
return T;
}
template <class Graph, class Tree>
Tree wilson_tree(Graph& G) {
unsigned n = num_vertices(G);
std::vector<int> pred(n);
static std::default_random_engine gen;
random_spanning_tree(G, gen, boost::predecessor_map(&pred[0]));
Tree T(n);
for(int i = 0; i < n; ++i)
if(pred[i] != boost::graph_traits<Graph>::null_vertex())
add_edge(i, pred[i], T);
return T;
}
<|endoftext|>
|
<commit_before>/* __ __ _
* / // /_____ ____ (_)
* / // // ___// __ \ / /
* / // // /__ / /_/ // /
* /_//_/ \___/ \____//_/
* https://bitbucket.org/galaktor/llcoi
* copyright (c) 2011, llcoi Team
* MIT license applies - see file "LICENSE" for details.
*/
#include "root_bind.h"
#include <OgreRoot.h>
#include <OgreRenderWindow.h>
#include <OgreWindowEventUtilities.h>
#include <OgreConfigFile.h>
RootHandle root_singleton()
{
return reinterpret_cast<RootHandle>(Ogre::Root::getSingletonPtr());
}
RootHandle create_root(const char* pluginFileName, const char* configFileName, const char* logFileName)
{
Ogre::Root* root = new Ogre::Root(Ogre::String(pluginFileName), Ogre::String(configFileName), Ogre::String(logFileName));
return reinterpret_cast<RootHandle>(root);
}
void delete_root(RootHandle root_handle)
{
Ogre::Root* root = reinterpret_cast<Ogre::Root*>(root_handle);
delete root;
}
RenderWindowHandle root_initialise(RootHandle root_handle, int auto_create_window, const char* render_window_title)
{
Ogre::Root* root = reinterpret_cast<Ogre::Root*>(root_handle);
Ogre::RenderWindow* window = root->initialise(auto_create_window, render_window_title);
return reinterpret_cast<RenderWindowHandle>(window);
}
RenderWindowHandle create_render_window(RootHandle root_handle, const char* name, const int width, const int height, const int full_screen, NameValuePairListHandle params)
{
Ogre::Root* root = reinterpret_cast<Ogre::Root*>(root_handle);
Ogre::RenderWindow* window = root->createRenderWindow(name, width, height, full_screen, reinterpret_cast<Ogre::NameValuePairList>(¶ms));
return reinterpret_cast<RenderWindowHandle>(window);
}
RenderWindowHandle create_render_window_hwnd(RootHandle root_handle, const char* name, const int width, const int height, const int full_screen, unsigned long hwnd)
{
Ogre::Root* root = reinterpret_cast<Ogre::Root*>(root_handle);
Ogre::NameValuePairList misc;
misc["parentWindowHandle"] = Ogre::StringConverter::toString(hwnd);
Ogre::RenderWindow* window = root->createRenderWindow(name, width, height, full_screen, &misc);
window->setActive(true);
return reinterpret_cast<RenderWindowHandle>(window);
}
// Tell Ogre to use the current GL context. This works on Linux/GLX but
// you *will* need something different on Windows or Mac.
RenderWindowHandle create_render_window_gl_context(RootHandle root_handle, const char* name, const int width, const int height, const int full_screen)
{
Ogre::Root* root = reinterpret_cast<Ogre::Root*>(root_handle);
Ogre::NameValuePairList misc;
misc["currentGLContext"] = Ogre::String("True");
Ogre::RenderWindow* window = root->createRenderWindow(name, width, height, full_screen, &misc);
return reinterpret_cast<RenderWindowHandle>(window);
}
int root_is_initialised(RootHandle root_handle)
{
Ogre::Root* root = reinterpret_cast<Ogre::Root*>(root_handle);
if(root->isInitialised())
return 1;
return 0;
}
void save_config(RootHandle root_handle)
{
Ogre::Root* root = reinterpret_cast<Ogre::Root*>(root_handle);
root->saveConfig();
}
int restore_config(RootHandle root_handle)
{
Ogre::Root* root = reinterpret_cast<Ogre::Root*>(root_handle);
if(root->restoreConfig())
return 1;
return 0;
}
int show_config_dialog(RootHandle root_handle)
{
Ogre::Root* root = reinterpret_cast<Ogre::Root*>(root_handle);
if(root->showConfigDialog())
return 1;
return 0;
}
void add_render_system(RootHandle root_handle, RenderSystemHandle render_system)
{
Ogre::Root* root = reinterpret_cast<Ogre::Root*>(root_handle);
Ogre::RenderSystem* rs = reinterpret_cast<Ogre::RenderSystem*>(render_system);
root->addRenderSystem(rs);
}
void set_render_system(RootHandle root_handle, RenderSystemHandle render_system)
{
Ogre::Root* root = reinterpret_cast<Ogre::Root*>(root_handle);
Ogre::RenderSystem* rs = reinterpret_cast<Ogre::RenderSystem*>(render_system);
root->setRenderSystem(rs);
}
RenderSystemHandle get_render_system(RootHandle root_handle)
{
Ogre::Root* root = reinterpret_cast<Ogre::Root*>(root_handle);
return reinterpret_cast<RenderSystemHandle>(root->getRenderSystem());
}
RenderSystemHandle get_render_system_by_name(RootHandle root_handle, const char* render_system_name)
{
Ogre::Root* root = reinterpret_cast<Ogre::Root*>(root_handle);
Ogre::RenderSystem* rs = root->getRenderSystemByName(render_system_name);
return reinterpret_cast<RenderSystemHandle>(rs);
}
void load_ogre_plugin(RootHandle root_handle, const char* plugin)
{
Ogre::Root* root = reinterpret_cast<Ogre::Root*>(root_handle);
#if defined( WIN32 ) || defined( _WINDOWS )
Ogre::String pluginString(plugin);
#ifdef _DEBUG
root->loadPlugin(pluginString + Ogre::String("_d"));
#else
root->loadPlugin(plugin);
#endif
#else
root->loadPlugin( Ogre::String(plugin));
#endif
}
int render_one_frame(RootHandle root_handle)
{
Ogre::Root* root = reinterpret_cast<Ogre::Root*>(root_handle);
if(root->renderOneFrame())
return 1;
return 0;
}
int render_one_frame_ex(RootHandle root_handle, float time_since_last_frame)
{
Ogre::Root* root = reinterpret_cast<Ogre::Root*>(root_handle);
if(root->renderOneFrame(time_since_last_frame))
return 1;
return 0;
}
SceneManagerHandle create_scene_manager(RootHandle root_handle, const char* type_name, const char* instance_name)
{
Ogre::Root* root = reinterpret_cast<Ogre::Root*>(root_handle);
Ogre::SceneManager* sm = root->createSceneManager(Ogre::String(type_name), Ogre::String(instance_name));
return reinterpret_cast<SceneManagerHandle>(sm);
}
SceneManagerHandle get_scene_manager_by_name(RootHandle root_handle, const char* scene_manager_instance_name)
{
Ogre::Root* root = reinterpret_cast<Ogre::Root*>(root_handle);
Ogre::SceneManager* sm = root->getSceneManager(scene_manager_instance_name);
return reinterpret_cast<SceneManagerHandle>(sm);
}
// Ogre::Root::getAvailableRenderers
RenderSystemListHandle root_get_available_renderers(RootHandle root_handle)
{
Ogre::Root* root = reinterpret_cast<Ogre::Root*>(root_handle);
const Ogre::RenderSystemList& rslist = root->getAvailableRenderers();
Ogre::RenderSystemList *l = new Ogre::RenderSystemList(rslist);
return reinterpret_cast<RenderSystemListHandle>(l);
}
SceneManagerHandle root_create_scene_manager_by_mask(RootHandle root_handle, SceneTypeMask type_mask, const char* instance_name)
{
Ogre::Root* root = reinterpret_cast<Ogre::Root*>(root_handle);
Ogre::SceneManager* sm = root->createSceneManager(type_mask, Ogre::String(instance_name));
return reinterpret_cast<SceneManagerHandle>(sm);
}
TimerHandle root_get_timer(RootHandle root_handle)
{
Ogre::Root* root = reinterpret_cast<Ogre::Root*>(root_handle);
Ogre::Timer* timer = root->getTimer();
return reinterpret_cast<TimerHandle>(timer);
}
/*
Ogre::Root::~Root()
Ogre::Root::saveConfig()
Ogre::Root::addRenderSystem(Ogre::RenderSystem*)
Ogre::Root::getRenderSystemByName(std::string const&)
Ogre::Root::setRenderSystem(Ogre::RenderSystem*)
Ogre::Root::getRenderSystem()
Ogre::Root::useCustomRenderSystemCapabilities(Ogre::RenderSystemCapabilities*)
Ogre::Root::getRemoveRenderQueueStructuresOnClear() const
Ogre::Root::setRemoveRenderQueueStructuresOnClear(bool)
Ogre::Root::addSceneManagerFactory(Ogre::SceneManagerFactory*)
Ogre::Root::removeSceneManagerFactory(Ogre::SceneManagerFactory*)
Ogre::Root::getSceneManagerMetaData(std::string const&) const
Ogre::Root::getSceneManagerMetaDataIterator() const
Ogre::Root::createSceneManager(std::string const&, std::string const&)
Ogre::Root::createSceneManager(unsigned short, std::string const&)
Ogre::Root::destroySceneManager(Ogre::SceneManager*)
Ogre::Root::getSceneManager(std::string const&) const
Ogre::Root::hasSceneManager(std::string const&) const
Ogre::Root::getSceneManagerIterator()
Ogre::Root::getTextureManager()
Ogre::Root::getMeshManager()
Ogre::Root::getErrorDescription(long)
Ogre::Root::addFrameListener(Ogre::FrameListener*)
Ogre::Root::removeFrameListener(Ogre::FrameListener*)
Ogre::Root::queueEndRendering()
Ogre::Root::startRendering()
Ogre::Root::shutdown()
Ogre::Root::addResourceLocation(std::string const&, std::string const&, std::string const&, bool)
Ogre::Root::removeResourceLocation(std::string const&, std::string const&)
Ogre::Root::createFileStream(std::string const&, std::string const&, bool, std::string const&)
Ogre::Root::openFileStream(std::string const&, std::string const&, std::string const&)
Ogre::Root::convertColourValue(Ogre::ColourValue const&, unsigned int*)
Ogre::Root::getAutoCreatedWindow()
Ogre::Root::createRenderWindow(std::string const&, unsigned int, unsigned int, bool, std::map<std::string, std::string, std::less<std::string>, Ogre::STLAllocator<std::pair<std::string const, std::string>, Ogre::CategorisedAllocPolicy<(Ogre::MemoryCategory)0> > > const*)
Ogre::Root::createRenderWindows(std::vector<Ogre::RenderWindowDescription, Ogre::STLAllocator<Ogre::RenderWindowDescription, Ogre::CategorisedAllocPolicy<(Ogre::MemoryCategory)0> > > const&, std::vector<Ogre::RenderWindow*, Ogre::STLAllocator<Ogre::RenderWindow*, Ogre::CategorisedAllocPolicy<(Ogre::MemoryCategory)0> > >&)
Ogre::Root::detachRenderTarget(Ogre::RenderTarget*)
Ogre::Root::detachRenderTarget(std::string const&)
Ogre::Root::getRenderTarget(std::string const&)
Ogre::Root::unloadPlugin(std::string const&)
Ogre::Root::installPlugin(Ogre::Plugin*)
Ogre::Root::uninstallPlugin(Ogre::Plugin*)
Ogre::Root::getInstalledPlugins() const
Ogre::Root::getTimer()
Ogre::Root::_fireFrameStarted(Ogre::FrameEvent&)
Ogre::Root::_fireFrameRenderingQueued(Ogre::FrameEvent&)
Ogre::Root::_fireFrameEnded(Ogre::FrameEvent&)
Ogre::Root::_fireFrameStarted()
Ogre::Root::_fireFrameRenderingQueued()
Ogre::Root::_fireFrameEnded()
Ogre::Root::getNextFrameNumber() const
Ogre::Root::_getCurrentSceneManager() const
Ogre::Root::_pushCurrentSceneManager(Ogre::SceneManager*)
Ogre::Root::_popCurrentSceneManager(Ogre::SceneManager*)
Ogre::Root::_updateAllRenderTargets()
Ogre::Root::_updateAllRenderTargets(Ogre::FrameEvent&)
Ogre::Root::createRenderQueueInvocationSequence(std::string const&)
Ogre::Root::getRenderQueueInvocationSequence(std::string const&)
Ogre::Root::destroyRenderQueueInvocationSequence(std::string const&)
Ogre::Root::destroyAllRenderQueueInvocationSequences()
Ogre::Root::getSingleton()
Ogre::Root::getSingletonPtr()
Ogre::Root::clearEventTimes()
Ogre::Root::setFrameSmoothingPeriod(float)
Ogre::Root::getFrameSmoothingPeriod() const
Ogre::Root::addMovableObjectFactory(Ogre::MovableObjectFactory*, bool)
Ogre::Root::removeMovableObjectFactory(Ogre::MovableObjectFactory*)
Ogre::Root::hasMovableObjectFactory(std::string const&) const
Ogre::Root::getMovableObjectFactory(std::string const&)
Ogre::Root::_allocateNextMovableObjectTypeFlag()
Ogre::Root::getMovableObjectFactoryIterator() const
Ogre::Root::getDisplayMonitorCount() const
Ogre::Root::getWorkQueue() const
Ogre::Root::setWorkQueue(Ogre::WorkQueue*)
Ogre::Root::setBlendIndicesGpuRedundant(bool)
Ogre::Root::isBlendIndicesGpuRedundant() const
Ogre::Root::setBlendWeightsGpuRedundant(bool)
Ogre::Root::isBlendWeightsGpuRedundant() const
*/
<commit_msg>Correct pointer location.<commit_after>/* __ __ _
* / // /_____ ____ (_)
* / // // ___// __ \ / /
* / // // /__ / /_/ // /
* /_//_/ \___/ \____//_/
* https://bitbucket.org/galaktor/llcoi
* copyright (c) 2011, llcoi Team
* MIT license applies - see file "LICENSE" for details.
*/
#include "root_bind.h"
#include <OgreRoot.h>
#include <OgreRenderWindow.h>
#include <OgreWindowEventUtilities.h>
#include <OgreConfigFile.h>
RootHandle root_singleton()
{
return reinterpret_cast<RootHandle>(Ogre::Root::getSingletonPtr());
}
RootHandle create_root(const char* pluginFileName, const char* configFileName, const char* logFileName)
{
Ogre::Root* root = new Ogre::Root(Ogre::String(pluginFileName), Ogre::String(configFileName), Ogre::String(logFileName));
return reinterpret_cast<RootHandle>(root);
}
void delete_root(RootHandle root_handle)
{
Ogre::Root* root = reinterpret_cast<Ogre::Root*>(root_handle);
delete root;
}
RenderWindowHandle root_initialise(RootHandle root_handle, int auto_create_window, const char* render_window_title)
{
Ogre::Root* root = reinterpret_cast<Ogre::Root*>(root_handle);
Ogre::RenderWindow* window = root->initialise(auto_create_window, render_window_title);
return reinterpret_cast<RenderWindowHandle>(window);
}
RenderWindowHandle create_render_window(RootHandle root_handle, const char* name, const int width, const int height, const int full_screen, NameValuePairListHandle params)
{
Ogre::Root* root = reinterpret_cast<Ogre::Root*>(root_handle);
Ogre::RenderWindow* window = root->createRenderWindow(name, width, height, full_screen, reinterpret_cast<Ogre::NameValuePairList*>(params));
return reinterpret_cast<RenderWindowHandle>(window);
}
RenderWindowHandle create_render_window_hwnd(RootHandle root_handle, const char* name, const int width, const int height, const int full_screen, unsigned long hwnd)
{
Ogre::Root* root = reinterpret_cast<Ogre::Root*>(root_handle);
Ogre::NameValuePairList misc;
misc["parentWindowHandle"] = Ogre::StringConverter::toString(hwnd);
Ogre::RenderWindow* window = root->createRenderWindow(name, width, height, full_screen, &misc);
window->setActive(true);
return reinterpret_cast<RenderWindowHandle>(window);
}
// Tell Ogre to use the current GL context. This works on Linux/GLX but
// you *will* need something different on Windows or Mac.
RenderWindowHandle create_render_window_gl_context(RootHandle root_handle, const char* name, const int width, const int height, const int full_screen)
{
Ogre::Root* root = reinterpret_cast<Ogre::Root*>(root_handle);
Ogre::NameValuePairList misc;
misc["currentGLContext"] = Ogre::String("True");
Ogre::RenderWindow* window = root->createRenderWindow(name, width, height, full_screen, &misc);
return reinterpret_cast<RenderWindowHandle>(window);
}
int root_is_initialised(RootHandle root_handle)
{
Ogre::Root* root = reinterpret_cast<Ogre::Root*>(root_handle);
if(root->isInitialised())
return 1;
return 0;
}
void save_config(RootHandle root_handle)
{
Ogre::Root* root = reinterpret_cast<Ogre::Root*>(root_handle);
root->saveConfig();
}
int restore_config(RootHandle root_handle)
{
Ogre::Root* root = reinterpret_cast<Ogre::Root*>(root_handle);
if(root->restoreConfig())
return 1;
return 0;
}
int show_config_dialog(RootHandle root_handle)
{
Ogre::Root* root = reinterpret_cast<Ogre::Root*>(root_handle);
if(root->showConfigDialog())
return 1;
return 0;
}
void add_render_system(RootHandle root_handle, RenderSystemHandle render_system)
{
Ogre::Root* root = reinterpret_cast<Ogre::Root*>(root_handle);
Ogre::RenderSystem* rs = reinterpret_cast<Ogre::RenderSystem*>(render_system);
root->addRenderSystem(rs);
}
void set_render_system(RootHandle root_handle, RenderSystemHandle render_system)
{
Ogre::Root* root = reinterpret_cast<Ogre::Root*>(root_handle);
Ogre::RenderSystem* rs = reinterpret_cast<Ogre::RenderSystem*>(render_system);
root->setRenderSystem(rs);
}
RenderSystemHandle get_render_system(RootHandle root_handle)
{
Ogre::Root* root = reinterpret_cast<Ogre::Root*>(root_handle);
return reinterpret_cast<RenderSystemHandle>(root->getRenderSystem());
}
RenderSystemHandle get_render_system_by_name(RootHandle root_handle, const char* render_system_name)
{
Ogre::Root* root = reinterpret_cast<Ogre::Root*>(root_handle);
Ogre::RenderSystem* rs = root->getRenderSystemByName(render_system_name);
return reinterpret_cast<RenderSystemHandle>(rs);
}
void load_ogre_plugin(RootHandle root_handle, const char* plugin)
{
Ogre::Root* root = reinterpret_cast<Ogre::Root*>(root_handle);
#if defined( WIN32 ) || defined( _WINDOWS )
Ogre::String pluginString(plugin);
#ifdef _DEBUG
root->loadPlugin(pluginString + Ogre::String("_d"));
#else
root->loadPlugin(plugin);
#endif
#else
root->loadPlugin( Ogre::String(plugin));
#endif
}
int render_one_frame(RootHandle root_handle)
{
Ogre::Root* root = reinterpret_cast<Ogre::Root*>(root_handle);
if(root->renderOneFrame())
return 1;
return 0;
}
int render_one_frame_ex(RootHandle root_handle, float time_since_last_frame)
{
Ogre::Root* root = reinterpret_cast<Ogre::Root*>(root_handle);
if(root->renderOneFrame(time_since_last_frame))
return 1;
return 0;
}
SceneManagerHandle create_scene_manager(RootHandle root_handle, const char* type_name, const char* instance_name)
{
Ogre::Root* root = reinterpret_cast<Ogre::Root*>(root_handle);
Ogre::SceneManager* sm = root->createSceneManager(Ogre::String(type_name), Ogre::String(instance_name));
return reinterpret_cast<SceneManagerHandle>(sm);
}
SceneManagerHandle get_scene_manager_by_name(RootHandle root_handle, const char* scene_manager_instance_name)
{
Ogre::Root* root = reinterpret_cast<Ogre::Root*>(root_handle);
Ogre::SceneManager* sm = root->getSceneManager(scene_manager_instance_name);
return reinterpret_cast<SceneManagerHandle>(sm);
}
// Ogre::Root::getAvailableRenderers
RenderSystemListHandle root_get_available_renderers(RootHandle root_handle)
{
Ogre::Root* root = reinterpret_cast<Ogre::Root*>(root_handle);
const Ogre::RenderSystemList& rslist = root->getAvailableRenderers();
Ogre::RenderSystemList *l = new Ogre::RenderSystemList(rslist);
return reinterpret_cast<RenderSystemListHandle>(l);
}
SceneManagerHandle root_create_scene_manager_by_mask(RootHandle root_handle, SceneTypeMask type_mask, const char* instance_name)
{
Ogre::Root* root = reinterpret_cast<Ogre::Root*>(root_handle);
Ogre::SceneManager* sm = root->createSceneManager(type_mask, Ogre::String(instance_name));
return reinterpret_cast<SceneManagerHandle>(sm);
}
TimerHandle root_get_timer(RootHandle root_handle)
{
Ogre::Root* root = reinterpret_cast<Ogre::Root*>(root_handle);
Ogre::Timer* timer = root->getTimer();
return reinterpret_cast<TimerHandle>(timer);
}
/*
Ogre::Root::~Root()
Ogre::Root::saveConfig()
Ogre::Root::addRenderSystem(Ogre::RenderSystem*)
Ogre::Root::getRenderSystemByName(std::string const&)
Ogre::Root::setRenderSystem(Ogre::RenderSystem*)
Ogre::Root::getRenderSystem()
Ogre::Root::useCustomRenderSystemCapabilities(Ogre::RenderSystemCapabilities*)
Ogre::Root::getRemoveRenderQueueStructuresOnClear() const
Ogre::Root::setRemoveRenderQueueStructuresOnClear(bool)
Ogre::Root::addSceneManagerFactory(Ogre::SceneManagerFactory*)
Ogre::Root::removeSceneManagerFactory(Ogre::SceneManagerFactory*)
Ogre::Root::getSceneManagerMetaData(std::string const&) const
Ogre::Root::getSceneManagerMetaDataIterator() const
Ogre::Root::createSceneManager(std::string const&, std::string const&)
Ogre::Root::createSceneManager(unsigned short, std::string const&)
Ogre::Root::destroySceneManager(Ogre::SceneManager*)
Ogre::Root::getSceneManager(std::string const&) const
Ogre::Root::hasSceneManager(std::string const&) const
Ogre::Root::getSceneManagerIterator()
Ogre::Root::getTextureManager()
Ogre::Root::getMeshManager()
Ogre::Root::getErrorDescription(long)
Ogre::Root::addFrameListener(Ogre::FrameListener*)
Ogre::Root::removeFrameListener(Ogre::FrameListener*)
Ogre::Root::queueEndRendering()
Ogre::Root::startRendering()
Ogre::Root::shutdown()
Ogre::Root::addResourceLocation(std::string const&, std::string const&, std::string const&, bool)
Ogre::Root::removeResourceLocation(std::string const&, std::string const&)
Ogre::Root::createFileStream(std::string const&, std::string const&, bool, std::string const&)
Ogre::Root::openFileStream(std::string const&, std::string const&, std::string const&)
Ogre::Root::convertColourValue(Ogre::ColourValue const&, unsigned int*)
Ogre::Root::getAutoCreatedWindow()
Ogre::Root::createRenderWindow(std::string const&, unsigned int, unsigned int, bool, std::map<std::string, std::string, std::less<std::string>, Ogre::STLAllocator<std::pair<std::string const, std::string>, Ogre::CategorisedAllocPolicy<(Ogre::MemoryCategory)0> > > const*)
Ogre::Root::createRenderWindows(std::vector<Ogre::RenderWindowDescription, Ogre::STLAllocator<Ogre::RenderWindowDescription, Ogre::CategorisedAllocPolicy<(Ogre::MemoryCategory)0> > > const&, std::vector<Ogre::RenderWindow*, Ogre::STLAllocator<Ogre::RenderWindow*, Ogre::CategorisedAllocPolicy<(Ogre::MemoryCategory)0> > >&)
Ogre::Root::detachRenderTarget(Ogre::RenderTarget*)
Ogre::Root::detachRenderTarget(std::string const&)
Ogre::Root::getRenderTarget(std::string const&)
Ogre::Root::unloadPlugin(std::string const&)
Ogre::Root::installPlugin(Ogre::Plugin*)
Ogre::Root::uninstallPlugin(Ogre::Plugin*)
Ogre::Root::getInstalledPlugins() const
Ogre::Root::getTimer()
Ogre::Root::_fireFrameStarted(Ogre::FrameEvent&)
Ogre::Root::_fireFrameRenderingQueued(Ogre::FrameEvent&)
Ogre::Root::_fireFrameEnded(Ogre::FrameEvent&)
Ogre::Root::_fireFrameStarted()
Ogre::Root::_fireFrameRenderingQueued()
Ogre::Root::_fireFrameEnded()
Ogre::Root::getNextFrameNumber() const
Ogre::Root::_getCurrentSceneManager() const
Ogre::Root::_pushCurrentSceneManager(Ogre::SceneManager*)
Ogre::Root::_popCurrentSceneManager(Ogre::SceneManager*)
Ogre::Root::_updateAllRenderTargets()
Ogre::Root::_updateAllRenderTargets(Ogre::FrameEvent&)
Ogre::Root::createRenderQueueInvocationSequence(std::string const&)
Ogre::Root::getRenderQueueInvocationSequence(std::string const&)
Ogre::Root::destroyRenderQueueInvocationSequence(std::string const&)
Ogre::Root::destroyAllRenderQueueInvocationSequences()
Ogre::Root::getSingleton()
Ogre::Root::getSingletonPtr()
Ogre::Root::clearEventTimes()
Ogre::Root::setFrameSmoothingPeriod(float)
Ogre::Root::getFrameSmoothingPeriod() const
Ogre::Root::addMovableObjectFactory(Ogre::MovableObjectFactory*, bool)
Ogre::Root::removeMovableObjectFactory(Ogre::MovableObjectFactory*)
Ogre::Root::hasMovableObjectFactory(std::string const&) const
Ogre::Root::getMovableObjectFactory(std::string const&)
Ogre::Root::_allocateNextMovableObjectTypeFlag()
Ogre::Root::getMovableObjectFactoryIterator() const
Ogre::Root::getDisplayMonitorCount() const
Ogre::Root::getWorkQueue() const
Ogre::Root::setWorkQueue(Ogre::WorkQueue*)
Ogre::Root::setBlendIndicesGpuRedundant(bool)
Ogre::Root::isBlendIndicesGpuRedundant() const
Ogre::Root::setBlendWeightsGpuRedundant(bool)
Ogre::Root::isBlendWeightsGpuRedundant() const
*/
<|endoftext|>
|
<commit_before>/*
LED bar library V2.0
2010 Copyright (c) Seeed Technology Inc. All right reserved.
Original Author: LG
Modify: Loovee, 2014-2-26
User can choose which Io to be used.
This library is free software; you can redistribute it and/or
modify it under the terms of the GNU Lesser General Public
License as published by the Free Software Foundation; either
version 2.1 of the License, or (at your option) any later version.
This library is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
Lesser General Public License for more details.
You should have received a copy of the GNU Lesser General Public
License along with this library; if not, write to the Free Software
Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
*/
#include <Arduino.h>
#include "Grove_LED_Bar.h"
Grove_LED_Bar::Grove_LED_Bar(unsigned char pinClock, unsigned char pinData, bool greenToRed)
{
__pinClock = pinClock;
__pinData = pinData;
__greenToRed = greenToRed; // ascending or decending
__state = 0x00; // persist state so individual leds can be toggled
pinMode(__pinClock, OUTPUT);
pinMode(__pinData, OUTPUT);
}
// Send the latch command
void Grove_LED_Bar::latchData()
{
digitalWrite(__pinData, LOW);
delayMicroseconds(10);
for (unsigned char i = 0; i < 4; i++)
{
digitalWrite(__pinData, HIGH);
digitalWrite(__pinData, LOW);
}
}
// Send 16 bits of data
void Grove_LED_Bar::sendData(unsigned int data)
{
for (unsigned char i = 0; i < 16; i++)
{
unsigned int state = (data & 0x8000) ? HIGH : LOW;
digitalWrite(__pinData, state);
state = digitalRead(__pinClock) ? LOW : HIGH;
digitalWrite(__pinClock, state);
data <<= 1;
}
}
// Change the orientation
// Green to red, or red to green
void Grove_LED_Bar::setGreenToRed(bool greenToRed)
{
__greenToRed = greenToRed;
setBits(__state);
}
// Set level (0-10)
// Level 0 means all leds off
// Level 10 means all leds on
void Grove_LED_Bar::setLevel(unsigned char level)
{
level = max(0, min(10, level));
// Set level number of bits from the left to 1
__state = ~(~0 << level);
setBits(__state);
}
// Set a single led
// led (1-10)
// state (0=off, 1=on)
void Grove_LED_Bar::setLed(unsigned char led, bool state)
{
led = max(1, min(10, led));
// Zero based index 0-9 for bitwise operations
led--;
// Bitwise OR or bitwise AND
__state = state ? (__state | (0x01<<led)) : (__state & ~(0x01<<led));
setBits(__state);
}
// Toggle a single led
// led (1-10)
void Grove_LED_Bar::toggleLed(unsigned char led)
{
led = max(1, min(10, led));
// Zero based index 0-9 for bitwise operations
led--;
// Bitwise XOR the leds current value
__state ^= (0x01<<led);
setBits(__state);
}
// Set the current state, one bit for each led
// 0 = 0x0 = 0b000000000000000 = all leds off
// 5 = 0x05 = 0b000000000000101 = leds 1 and 3 on, all others off
// 341 = 0x155 = 0b000000101010101 = leds 1,3,5,7,9 on, 2,4,6,8,10 off
// 1023 = 0x3ff = 0b000001111111111 = all leds on
// | |
// 10 1
void Grove_LED_Bar::setBits(unsigned int bits)
{
sendData(CMDMODE);
for (unsigned char i = 0; i < 10; i++)
{
if (__greenToRed)
{
// Bitwise AND the 10th bit (0x200) and left shift to cycle through all bits
sendData((bits << i) & 0x200 ? ON : OFF);
}
else
{
// Bitwise AND the 1st bit (0x01) and right shift to cycle through all bits
sendData((bits >> i) & 0x01 ? ON : OFF);
}
}
// Two extra empty bits for padding the command to the correct length
sendData(0x00);
sendData(0x00);
latchData();
}
// Return the current state
unsigned int Grove_LED_Bar::getBits()
{
return __state;
}
<commit_msg>Update Grove_LED_Bar.cpp<commit_after>/*
LED bar library V2.0
2010 Copyright (c) Seeed Technology Inc. All right reserved.
Original Author: LG
Modify: Loovee, 2014-2-26
User can choose which Io to be used.
This library is free software; you can redistribute it and/or
modify it under the terms of the GNU Lesser General Public
License as published by the Free Software Foundation; either
version 2.1 of the License, or (at your option) any later version.
This library is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
Lesser General Public License for more details.
You should have received a copy of the GNU Lesser General Public
License along with this library; if not, write to the Free Software
Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
*/
//#include <Arduino.h>
#include "Grove_LED_Bar.h"
Grove_LED_Bar::Grove_LED_Bar(unsigned char pinClock, unsigned char pinData, bool greenToRed)
{
__pinClock = pinClock;
__pinData = pinData;
__greenToRed = greenToRed; // ascending or decending
__state = 0x00; // persist state so individual leds can be toggled
pinMode(__pinClock, OUTPUT);
pinMode(__pinData, OUTPUT);
}
// Send the latch command
void Grove_LED_Bar::latchData()
{
digitalWrite(__pinData, LOW);
delayMicroseconds(10);
for (unsigned char i = 0; i < 4; i++)
{
digitalWrite(__pinData, HIGH);
digitalWrite(__pinData, LOW);
}
}
// Send 16 bits of data
void Grove_LED_Bar::sendData(unsigned int data)
{
for (unsigned char i = 0; i < 16; i++)
{
unsigned int state = (data & 0x8000) ? HIGH : LOW;
digitalWrite(__pinData, state);
state = digitalRead(__pinClock) ? LOW : HIGH;
digitalWrite(__pinClock, state);
data <<= 1;
}
}
// Change the orientation
// Green to red, or red to green
void Grove_LED_Bar::setGreenToRed(bool greenToRed)
{
__greenToRed = greenToRed;
setBits(__state);
}
// Set level (0-10)
// Level 0 means all leds off
// Level 10 means all leds on
void Grove_LED_Bar::setLevel(unsigned char level)
{
level = max(0, min(10, level));
// Set level number of bits from the left to 1
__state = ~(~0 << level);
setBits(__state);
}
// Set a single led
// led (1-10)
// state (0=off, 1=on)
void Grove_LED_Bar::setLed(unsigned char led, bool state)
{
led = max(1, min(10, led));
// Zero based index 0-9 for bitwise operations
led--;
// Bitwise OR or bitwise AND
__state = state ? (__state | (0x01<<led)) : (__state & ~(0x01<<led));
setBits(__state);
}
// Toggle a single led
// led (1-10)
void Grove_LED_Bar::toggleLed(unsigned char led)
{
led = max(1, min(10, led));
// Zero based index 0-9 for bitwise operations
led--;
// Bitwise XOR the leds current value
__state ^= (0x01<<led);
setBits(__state);
}
// Set the current state, one bit for each led
// 0 = 0x0 = 0b000000000000000 = all leds off
// 5 = 0x05 = 0b000000000000101 = leds 1 and 3 on, all others off
// 341 = 0x155 = 0b000000101010101 = leds 1,3,5,7,9 on, 2,4,6,8,10 off
// 1023 = 0x3ff = 0b000001111111111 = all leds on
// | |
// 10 1
void Grove_LED_Bar::setBits(unsigned int bits)
{
sendData(CMDMODE);
for (unsigned char i = 0; i < 10; i++)
{
if (__greenToRed)
{
// Bitwise AND the 10th bit (0x200) and left shift to cycle through all bits
sendData((bits << i) & 0x200 ? ON : OFF);
}
else
{
// Bitwise AND the 1st bit (0x01) and right shift to cycle through all bits
sendData((bits >> i) & 0x01 ? ON : OFF);
}
}
// Two extra empty bits for padding the command to the correct length
sendData(0x00);
sendData(0x00);
latchData();
}
// Return the current state
unsigned int Grove_LED_Bar::getBits()
{
return __state;
}
<|endoftext|>
|
<commit_before>/* ---------------------------------------------------------------------
* Numenta Platform for Intelligent Computing (NuPIC)
* Copyright (C) 2013, Numenta, Inc. Unless you have an agreement
* with Numenta, Inc., for a separate license for this software code, the
* following terms and conditions apply:
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero Public License version 3 as
* published by the Free Software Foundation.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
* See the GNU Affero Public License for more details.
*
* You should have received a copy of the GNU Affero Public License
* along with this program. If not, see http://www.gnu.org/licenses.
*
* http://numenta.org/licenses/
* ---------------------------------------------------------------------
*/
#ifndef NTA_YAML_HPP
#define NTA_YAML_HPP
#include <nupic/types/Types.hpp>
#include <nupic/ntypes/Value.hpp>
#include <nupic/ntypes/Collection.hpp>
#include <nupic/engine/Spec.hpp>
namespace nupic
{
namespace YAMLUtils
{
/*
* For converting param specs for Regions and LinkPolicies
*/
ValueMap toValueMap(
const char* yamlstring,
Collection<ParameterSpec>& parameters,
const std::string & nodeType = "",
const std::string & regionName = ""
);
} // namespace YAMLUtils
} // namespace nupic
#endif // NTA_YAML_HPP
<commit_msg>Revert "YAML Utils: remove toValue() from public API"<commit_after>/* ---------------------------------------------------------------------
* Numenta Platform for Intelligent Computing (NuPIC)
* Copyright (C) 2013, Numenta, Inc. Unless you have an agreement
* with Numenta, Inc., for a separate license for this software code, the
* following terms and conditions apply:
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero Public License version 3 as
* published by the Free Software Foundation.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
* See the GNU Affero Public License for more details.
*
* You should have received a copy of the GNU Affero Public License
* along with this program. If not, see http://www.gnu.org/licenses.
*
* http://numenta.org/licenses/
* ---------------------------------------------------------------------
*/
#ifndef NTA_YAML_HPP
#define NTA_YAML_HPP
#include <nupic/types/Types.hpp>
#include <nupic/ntypes/Value.hpp>
#include <nupic/ntypes/Collection.hpp>
#include <nupic/engine/Spec.hpp>
namespace nupic
{
namespace YAMLUtils
{
/*
* For converting default values
*/
Value toValue(const std::string& yamlstring, NTA_BasicType dataType);
/*
* For converting param specs for Regions and LinkPolicies
*/
ValueMap toValueMap(
const char* yamlstring,
Collection<ParameterSpec>& parameters,
const std::string & nodeType = "",
const std::string & regionName = ""
);
} // namespace YAMLUtils
} // namespace nupic
#endif // NTA_YAML_HPP
<|endoftext|>
|
<commit_before>/* ---------------------------------------------------------------------
* Numenta Platform for Intelligent Computing (NuPIC)
* Copyright (C) 2013, Numenta, Inc. Unless you have an agreement
* with Numenta, Inc., for a separate license for this software code, the
* following terms and conditions apply:
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero Public License version 3 as
* published by the Free Software Foundation.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
* See the GNU Affero Public License for more details.
*
* You should have received a copy of the GNU Affero Public License
* along with this program. If not, see http://www.gnu.org/licenses.
*
* http://numenta.org/licenses/
* ---------------------------------------------------------------------
*/
#ifndef NTA_YAML_HPP
#define NTA_YAML_HPP
#include <nupic/types/Types.hpp>
#include <nupic/ntypes/Value.hpp>
#include <nupic/ntypes/Collection.hpp>
#include <nupic/engine/Spec.hpp>
namespace nupic
{
namespace YAMLUtils
{
/*
* For converting default values
*/
Value toValue(const std::string& yamlstring, NTA_BasicType dataType);
/*
* For converting param specs for Regions and LinkPolicies
*/
ValueMap toValueMap(
const char* yamlstring,
Collection<ParameterSpec>& parameters,
const std::string & nodeType = "",
const std::string & regionName = ""
);
} // namespace YAMLUtils
} // namespace nupic
#endif // NTA_YAML_HPP
<commit_msg>YAML Utils: remove toValue() from public API<commit_after>/* ---------------------------------------------------------------------
* Numenta Platform for Intelligent Computing (NuPIC)
* Copyright (C) 2013, Numenta, Inc. Unless you have an agreement
* with Numenta, Inc., for a separate license for this software code, the
* following terms and conditions apply:
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero Public License version 3 as
* published by the Free Software Foundation.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
* See the GNU Affero Public License for more details.
*
* You should have received a copy of the GNU Affero Public License
* along with this program. If not, see http://www.gnu.org/licenses.
*
* http://numenta.org/licenses/
* ---------------------------------------------------------------------
*/
#ifndef NTA_YAML_HPP
#define NTA_YAML_HPP
#include <nupic/types/Types.hpp>
#include <nupic/ntypes/Value.hpp>
#include <nupic/ntypes/Collection.hpp>
#include <nupic/engine/Spec.hpp>
namespace nupic
{
namespace YAMLUtils
{
/*
* For converting param specs for Regions and LinkPolicies
*/
ValueMap toValueMap(
const char* yamlstring,
Collection<ParameterSpec>& parameters,
const std::string & nodeType = "",
const std::string & regionName = ""
);
} // namespace YAMLUtils
} // namespace nupic
#endif // NTA_YAML_HPP
<|endoftext|>
|
<commit_before>/*************************************************************************
*
* OpenOffice.org - a multi-platform office productivity suite
*
* $RCSfile: formatclipboard.cxx,v $
*
* $Revision: 1.5 $
*
* last change: $Author: rt $ $Date: 2005-09-09 04:30:53 $
*
* The Contents of this file are made available subject to
* the terms of GNU Lesser General Public License Version 2.1.
*
*
* GNU Lesser General Public License Version 2.1
* =============================================
* Copyright 2005 by Sun Microsystems, Inc.
* 901 San Antonio Road, Palo Alto, CA 94303, USA
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License version 2.1, as published by the Free Software Foundation.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston,
* MA 02111-1307 USA
*
************************************************************************/
#include "formatclipboard.hxx"
#ifndef _E3D_GLOBL3D_HXX
#include <svx/globl3d.hxx>
#endif
// header for class SfxItemIter
#ifndef _SFXITEMITER_HXX
#include <svtools/itemiter.hxx>
#endif
// header for class SfxStyleSheet
#ifndef _SFXSTYLE_HXX
#include <svtools/style.hxx>
#endif
/*--------------------------------------------------------------------
--------------------------------------------------------------------*/
SdFormatClipboard::SdFormatClipboard()
: m_pItemSet(0)
, m_bPersistentCopy(false)
, m_nType_Inventor(0)
, m_nType_Identifier(0)
{
}
SdFormatClipboard::~SdFormatClipboard()
{
if(m_pItemSet)
delete m_pItemSet;
}
bool SdFormatClipboard::HasContent() const
{
return m_pItemSet!=0;
}
bool SdFormatClipboard::CanCopyThisType( UINT32 nObjectInventor, UINT16 nObjectIdentifier ) const
{
if( nObjectInventor != SdrInventor && nObjectInventor != E3dInventor )
return false;
switch(nObjectIdentifier)
{
case OBJ_NONE:
case OBJ_GRUP:
return false;
break;
case OBJ_LINE:
case OBJ_RECT:
case OBJ_CIRC:
case OBJ_SECT:
case OBJ_CARC:
case OBJ_CCUT:
case OBJ_POLY:
case OBJ_PLIN:
case OBJ_PATHLINE:
case OBJ_PATHFILL:
case OBJ_FREELINE:
case OBJ_FREEFILL:
case OBJ_SPLNLINE:
case OBJ_SPLNFILL:
case OBJ_TEXT:
case OBJ_TEXTEXT:
case OBJ_TITLETEXT:
return true;
break;
case OBJ_OUTLINETEXT:
case OBJ_GRAF:
case OBJ_OLE2:
case OBJ_EDGE:
case OBJ_CAPTION:
return false;
break;
case OBJ_PATHPOLY:
case OBJ_PATHPLIN:
return true;
break;
case OBJ_PAGE:
case OBJ_MEASURE:
case OBJ_DUMMY:
case OBJ_FRAME:
case OBJ_UNO:
return false;
break;
case OBJ_CUSTOMSHAPE:
return true;
break;
default:
return false;
break;
}
return true;
}
bool SdFormatClipboard::HasContentForThisType( UINT32 nObjectInventor, UINT16 nObjectIdentifier ) const
{
if( !HasContent() )
return false;
if( !CanCopyThisType( nObjectInventor, nObjectIdentifier ) )
return false;
return true;
}
void SdFormatClipboard::Copy( ::sd::View& rDrawView, bool bPersistentCopy )
{
this->Erase();
m_bPersistentCopy = bPersistentCopy;
const SdrMarkList& rMarkList = rDrawView.GetMarkedObjectList();
if( rMarkList.GetMarkCount() >= 1 )
{
BOOL bOnlyHardAttr = FALSE;
m_pItemSet = new SfxItemSet( rDrawView.GetAttrFromMarked(bOnlyHardAttr) );
SdrObject* pObj = rMarkList.GetMark(0)->GetObj();
m_nType_Inventor = pObj->GetObjInventor();
m_nType_Identifier = pObj->GetObjIdentifier();
}
}
void SdFormatClipboard::Paste( ::sd::View& rDrawView
, bool bNoCharacterFormats, bool bNoParagraphFormats )
{
if( !rDrawView.AreObjectsMarked() )
{
if(!m_bPersistentCopy)
this->Erase();
return;
}
SdrObject* pObj = 0;
bool bWrongTargetType = false;
{
const SdrMarkList& rMarkList = rDrawView.GetMarkedObjectList();
if( rMarkList.GetMarkCount() != 1 )
bWrongTargetType = true;
else
{
pObj = rMarkList.GetMark(0)->GetObj();
if( pObj && pObj->GetStyleSheet() )
bWrongTargetType = !this->HasContentForThisType( pObj->GetObjInventor(), pObj->GetObjIdentifier() );
}
}
if( bWrongTargetType )
{
if(!m_bPersistentCopy)
this->Erase();
return;
}
if(m_pItemSet)
{
//modify source itemset
{
BOOL bOnlyHardAttr = FALSE;
SfxItemSet aTargetSet( pObj->GetStyleSheet()->GetItemSet() );
USHORT nWhich=0;
SfxItemState nSourceState;
SfxItemState nTargetState;
const SfxPoolItem* pSourceItem=0;
const SfxPoolItem* pTargetItem=0;
SfxItemIter aSourceIter(*m_pItemSet);
pSourceItem = aSourceIter.FirstItem();
while( pSourceItem!=NULL )
{
if (!IsInvalidItem(pSourceItem))
{
nWhich = pSourceItem->Which();
if(nWhich)
{
nSourceState = m_pItemSet->GetItemState( nWhich );
nTargetState = aTargetSet.GetItemState( nWhich );
pTargetItem = aTargetSet.GetItem( nWhich );
::com::sun::star::uno::Any aSourceValue, aTargetValue;
if(!pTargetItem)
m_pItemSet->ClearItem(nWhich);
else if( (*pSourceItem) == (*pTargetItem) )
{
//do not set items which have the same content in source and target
m_pItemSet->ClearItem(nWhich);
}
}
}
pSourceItem = aSourceIter.NextItem();
}//end while
}
BOOL bReplaceAll = TRUE;
rDrawView.SetAttrToMarked(*m_pItemSet, bReplaceAll);
}
if(!m_bPersistentCopy)
this->Erase();
}
void SdFormatClipboard::Erase()
{
if(m_pItemSet)
{
delete m_pItemSet;
m_pItemSet = 0;
}
m_nType_Inventor=0;
m_nType_Identifier=0;
m_bPersistentCopy = false;
}
<commit_msg>INTEGRATION: CWS aw035 (1.5.252); FILE MERGED 2006/07/13 16:05:12 aw 1.5.252.1: #126320# SdrMark::GetObj() -> SdrMark::GetMarkedSdrObj() for isolating selection handling<commit_after>/*************************************************************************
*
* OpenOffice.org - a multi-platform office productivity suite
*
* $RCSfile: formatclipboard.cxx,v $
*
* $Revision: 1.6 $
*
* last change: $Author: rt $ $Date: 2006-07-25 11:31:28 $
*
* The Contents of this file are made available subject to
* the terms of GNU Lesser General Public License Version 2.1.
*
*
* GNU Lesser General Public License Version 2.1
* =============================================
* Copyright 2005 by Sun Microsystems, Inc.
* 901 San Antonio Road, Palo Alto, CA 94303, USA
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License version 2.1, as published by the Free Software Foundation.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston,
* MA 02111-1307 USA
*
************************************************************************/
#include "formatclipboard.hxx"
#ifndef _E3D_GLOBL3D_HXX
#include <svx/globl3d.hxx>
#endif
// header for class SfxItemIter
#ifndef _SFXITEMITER_HXX
#include <svtools/itemiter.hxx>
#endif
// header for class SfxStyleSheet
#ifndef _SFXSTYLE_HXX
#include <svtools/style.hxx>
#endif
/*--------------------------------------------------------------------
--------------------------------------------------------------------*/
SdFormatClipboard::SdFormatClipboard()
: m_pItemSet(0)
, m_bPersistentCopy(false)
, m_nType_Inventor(0)
, m_nType_Identifier(0)
{
}
SdFormatClipboard::~SdFormatClipboard()
{
if(m_pItemSet)
delete m_pItemSet;
}
bool SdFormatClipboard::HasContent() const
{
return m_pItemSet!=0;
}
bool SdFormatClipboard::CanCopyThisType( UINT32 nObjectInventor, UINT16 nObjectIdentifier ) const
{
if( nObjectInventor != SdrInventor && nObjectInventor != E3dInventor )
return false;
switch(nObjectIdentifier)
{
case OBJ_NONE:
case OBJ_GRUP:
return false;
break;
case OBJ_LINE:
case OBJ_RECT:
case OBJ_CIRC:
case OBJ_SECT:
case OBJ_CARC:
case OBJ_CCUT:
case OBJ_POLY:
case OBJ_PLIN:
case OBJ_PATHLINE:
case OBJ_PATHFILL:
case OBJ_FREELINE:
case OBJ_FREEFILL:
case OBJ_SPLNLINE:
case OBJ_SPLNFILL:
case OBJ_TEXT:
case OBJ_TEXTEXT:
case OBJ_TITLETEXT:
return true;
break;
case OBJ_OUTLINETEXT:
case OBJ_GRAF:
case OBJ_OLE2:
case OBJ_EDGE:
case OBJ_CAPTION:
return false;
break;
case OBJ_PATHPOLY:
case OBJ_PATHPLIN:
return true;
break;
case OBJ_PAGE:
case OBJ_MEASURE:
case OBJ_DUMMY:
case OBJ_FRAME:
case OBJ_UNO:
return false;
break;
case OBJ_CUSTOMSHAPE:
return true;
break;
default:
return false;
break;
}
return true;
}
bool SdFormatClipboard::HasContentForThisType( UINT32 nObjectInventor, UINT16 nObjectIdentifier ) const
{
if( !HasContent() )
return false;
if( !CanCopyThisType( nObjectInventor, nObjectIdentifier ) )
return false;
return true;
}
void SdFormatClipboard::Copy( ::sd::View& rDrawView, bool bPersistentCopy )
{
this->Erase();
m_bPersistentCopy = bPersistentCopy;
const SdrMarkList& rMarkList = rDrawView.GetMarkedObjectList();
if( rMarkList.GetMarkCount() >= 1 )
{
BOOL bOnlyHardAttr = FALSE;
m_pItemSet = new SfxItemSet( rDrawView.GetAttrFromMarked(bOnlyHardAttr) );
SdrObject* pObj = rMarkList.GetMark(0)->GetMarkedSdrObj();
m_nType_Inventor = pObj->GetObjInventor();
m_nType_Identifier = pObj->GetObjIdentifier();
}
}
void SdFormatClipboard::Paste( ::sd::View& rDrawView
, bool bNoCharacterFormats, bool bNoParagraphFormats )
{
if( !rDrawView.AreObjectsMarked() )
{
if(!m_bPersistentCopy)
this->Erase();
return;
}
SdrObject* pObj = 0;
bool bWrongTargetType = false;
{
const SdrMarkList& rMarkList = rDrawView.GetMarkedObjectList();
if( rMarkList.GetMarkCount() != 1 )
bWrongTargetType = true;
else
{
pObj = rMarkList.GetMark(0)->GetMarkedSdrObj();
if( pObj && pObj->GetStyleSheet() )
bWrongTargetType = !this->HasContentForThisType( pObj->GetObjInventor(), pObj->GetObjIdentifier() );
}
}
if( bWrongTargetType )
{
if(!m_bPersistentCopy)
this->Erase();
return;
}
if(m_pItemSet)
{
//modify source itemset
{
BOOL bOnlyHardAttr = FALSE;
SfxItemSet aTargetSet( pObj->GetStyleSheet()->GetItemSet() );
USHORT nWhich=0;
SfxItemState nSourceState;
SfxItemState nTargetState;
const SfxPoolItem* pSourceItem=0;
const SfxPoolItem* pTargetItem=0;
SfxItemIter aSourceIter(*m_pItemSet);
pSourceItem = aSourceIter.FirstItem();
while( pSourceItem!=NULL )
{
if (!IsInvalidItem(pSourceItem))
{
nWhich = pSourceItem->Which();
if(nWhich)
{
nSourceState = m_pItemSet->GetItemState( nWhich );
nTargetState = aTargetSet.GetItemState( nWhich );
pTargetItem = aTargetSet.GetItem( nWhich );
::com::sun::star::uno::Any aSourceValue, aTargetValue;
if(!pTargetItem)
m_pItemSet->ClearItem(nWhich);
else if( (*pSourceItem) == (*pTargetItem) )
{
//do not set items which have the same content in source and target
m_pItemSet->ClearItem(nWhich);
}
}
}
pSourceItem = aSourceIter.NextItem();
}//end while
}
BOOL bReplaceAll = TRUE;
rDrawView.SetAttrToMarked(*m_pItemSet, bReplaceAll);
}
if(!m_bPersistentCopy)
this->Erase();
}
void SdFormatClipboard::Erase()
{
if(m_pItemSet)
{
delete m_pItemSet;
m_pItemSet = 0;
}
m_nType_Inventor=0;
m_nType_Identifier=0;
m_bPersistentCopy = false;
}
<|endoftext|>
|
<commit_before>//=======================================================================
// Copyright Baptiste Wicht 2011.
// Distributed under the Boost Software License, Version 1.0.
// (See accompanying file LICENSE_1_0.txt or copy at
// http://www.boost.org/LICENSE_1_0.txt)
//=======================================================================
#include <iostream>
#include <cassert>
#include "Litteral.hpp"
#include "StringPool.hpp"
#include "AssemblyFileWriter.hpp"
#include "Variable.hpp"
#include "il/IntermediateProgram.hpp"
#include "il/Operands.hpp"
using namespace eddic;
void Litteral::checkStrings(StringPool& pool) {
m_label = pool.label(m_litteral);
}
void Litteral::write(AssemblyFileWriter& writer) {
writer.stream() << "pushl $" << getStringLabel() << std::endl;
writer.stream() << "pushl $" << getStringSize() << std::endl;
}
bool Litteral::isConstant() {
return true;
}
std::string Litteral::getStringValue() {
return m_litteral;
}
std::string Litteral::getStringLabel(){
return m_label;
}
int Litteral::getStringSize(){
return m_litteral.size() - 2;
}
void Litteral::assignTo(std::shared_ptr<Variable> variable, IntermediateProgram& program){
std::pair<std::shared_ptr<Operand>, std::shared_ptr<Operand>> operands = variable->toStringOperand();
program.addInstruction(
program.factory().createMove(
createGlobalOperand(getStringLabel()),
operands.first
)
);
program.addInstruction(
program.factory().createMove(
createImmediateOperand(getStringSize()),
operands.second
)
);
}
void Litteral::assignTo(std::shared_ptr<Operand>, IntermediateProgram&){
assert(false); //Cannot assign a string to a single operand
}
void Litteral::push(IntermediateProgram& program){
//TODO Verify that it is corresponding to pushl $label
program.addInstruction(
program.factory().createPush(
createGlobalOperand(getStringLabel())
)
);
program.addInstruction(
program.factory().createPush(
createImmediateOperand(getStringSize())
)
);
}
<commit_msg>Use immediate operands for strings<commit_after>//=======================================================================
// Copyright Baptiste Wicht 2011.
// Distributed under the Boost Software License, Version 1.0.
// (See accompanying file LICENSE_1_0.txt or copy at
// http://www.boost.org/LICENSE_1_0.txt)
//=======================================================================
#include <iostream>
#include <cassert>
#include "Litteral.hpp"
#include "StringPool.hpp"
#include "AssemblyFileWriter.hpp"
#include "Variable.hpp"
#include "il/IntermediateProgram.hpp"
#include "il/Operands.hpp"
using namespace eddic;
void Litteral::checkStrings(StringPool& pool) {
m_label = pool.label(m_litteral);
}
void Litteral::write(AssemblyFileWriter& writer) {
writer.stream() << "pushl $" << getStringLabel() << std::endl;
writer.stream() << "pushl $" << getStringSize() << std::endl;
}
bool Litteral::isConstant() {
return true;
}
std::string Litteral::getStringValue() {
return m_litteral;
}
std::string Litteral::getStringLabel(){
return m_label;
}
int Litteral::getStringSize(){
return m_litteral.size() - 2;
}
void Litteral::assignTo(std::shared_ptr<Variable> variable, IntermediateProgram& program){
std::pair<std::shared_ptr<Operand>, std::shared_ptr<Operand>> operands = variable->toStringOperand();
program.addInstruction(
program.factory().createMove(
createImmediateOperand(getStringLabel()),
operands.first
)
);
program.addInstruction(
program.factory().createMove(
createImmediateOperand(getStringSize()),
operands.second
)
);
}
void Litteral::assignTo(std::shared_ptr<Operand>, IntermediateProgram&){
assert(false); //Cannot assign a string to a single operand
}
void Litteral::push(IntermediateProgram& program){
//TODO Verify that it is corresponding to pushl $label
program.addInstruction(
program.factory().createPush(
createImmediateOperand(getStringLabel())
)
);
program.addInstruction(
program.factory().createPush(
createImmediateOperand(getStringSize())
)
);
}
<|endoftext|>
|
<commit_before>/*
FILNAMN: NetClient.cc
PROGRAMMERARE: hanel742, eriek984, jened502, tobgr602, niker917, davha227
SKAPAD DATUM: 2013-11-19
BESKRIVNING:
*/
#include "NetClient.h"
#include "../gui/gui.h"
using namespace std;
NetClient::NetClient(QString username, QString inAddress, Gui* myGui, QObject *parent) : QObject(parent){
guiPointer = myGui;
name=username;
address=inAddress;
compare += 0x1F;
breaker +=0x1E;
}
// ---------------------------------------------
void NetClient::start(){
TcpSocket = new QTcpSocket(this);
connect(TcpSocket,SIGNAL(connected()),this,SLOT(connected()));
connect(TcpSocket,SIGNAL(disconnected()),this,SLOT(disconnected()));
connect(TcpSocket,SIGNAL(readyRead()),this,SLOT(readyRead()));
QHostInfo info = QHostInfo::fromName(address);
if (info.addresses().size() == 0){
guiPointer->noConnection();
}
else{
TcpSocket->connectToHost(info.addresses().at(0),quint16(40001));
if(!TcpSocket->waitForConnected(1000)){
guiPointer->noConnection();
}
}
}
//------Slots---------
void NetClient::connected(){
QByteArray array = "/initiate";
array += 0x1F; //unit separator
array += name;
array += breaker;
TcpSocket->write(array);
TcpSocket->waitForBytesWritten(1000);
}
void NetClient::disconnected(){
guiPointer->disconnectedFromServer();
}
// --------readyRead------------------
void NetClient::readyRead(){
QByteArray Data = TcpSocket->readAll();
QString commandName;
QString inData = Data;
QString rest;
int n = inData.indexOf(breaker);
int i;
do {
rest = inData.mid(n+1);
inData = inData.left(n);
i = inData.indexOf(compare);
commandName = inData.left(i);
inData = inData.mid(i+1);
QString temp = inData;
string stdInData = temp.toStdString();
// Check which command that's supposed to run
if (commandName == "/reinitiate") {
guiPointer->userNameTaken();
break;
}
else if ( commandName == "/userAccepted") {
guiPointer->connected();
}
else if (commandName == "/history") {
handleHistory(inData);
}
else if (commandName == "/oldHistory") {
handleOldHistory(inData);
}
else if (commandName == "/message") {
handleMessage(inData);
}
else if ( commandName == "/requestStruct") {
handleRequestStruct();
}
else if ( commandName == "/structure" ) {
handleStructure(inData);
}
else {
throw logic_error("Unknown command: " + commandName.toStdString());
}
inData = rest;
n = inData.indexOf(breaker);
}while (n != -1 );
}
// ---------------------------------------------
void NetClient::sendMessage(QString from, QString to, QString message){
QByteArray array = "/message";
array += 0x1F; //unit separator
array += from;
array += 0x1F;
array += to;
array += 0x1F;
array += message;
array += breaker;
TcpSocket->write(array);
TcpSocket->waitForBytesWritten(1000);
}
void NetClient::setName(QString inName) {
name=inName;
}
void NetClient::getStruct(){
QByteArray array = "/structure";
array += 0x1E;
TcpSocket->write(array);
TcpSocket->waitForBytesWritten(1000);
}
//--------------------------------------------
//Helpfunctions
void NetClient::handleRequestStruct(){
QByteArray array = "/structure";
array += compare;
array += breaker;
TcpSocket->write(array);
TcpSocket->waitForBytesWritten(1000);
}
// ---------------------------------------------
void NetClient::handleMessage(QString inData){
int i;
// Get from
i = inData.indexOf(compare);
QString from = inData.left(i);
inData = inData.mid(i+1);
// Get to
i = inData.indexOf(compare);
QString to = inData.left(i);
inData = inData.mid(i+1);
// Get message
i = inData.indexOf(compare);
QString contents = inData.left(i);
inData = inData.mid(i+1);
// Get time
QString dateTime = inData;
//Send message to Gui
guiPointer->receiveMessage(from, to, contents, dateTime);
}
// ---------------------------------------------
void NetClient::handleHistory(QString inData){
QVector<QString> history;
int i = inData.indexOf(compare);
while(i != -1 ){
// Get from
i = inData.indexOf(compare);
QString from = inData.left(i);
inData = inData.mid(i+1);
history.push_back(from);
// Get to
i = inData.indexOf(compare);
QString to = inData.left(i);
inData = inData.mid(i+1);
history.push_back(to);
// Get message
i = inData.indexOf(compare);
QString contents = inData.left(i);
inData = inData.mid(i+1);
history.push_back(contents);
//Get time
i = inData.indexOf(compare);
QString time = inData.left(i);
inData = inData.mid(i+1);
history.push_back(time);
}
guiPointer->receiveHistory(history);
}
// ---------------------------------------------
void NetClient::handleOldHistory(QString inData){
QVector<QString> history;
int i = inData.indexOf(compare);
while(i != -1 ){
// Get from
i = inData.indexOf(compare);
QString from = inData.left(i);
inData = inData.mid(i+1);
history.push_back(from);
// Get to
i = inData.indexOf(compare);
QString to = inData.left(i);
inData = inData.mid(i+1);
history.push_back(to);
// Get message
i = inData.indexOf(compare);
QString contents = inData.left(i);
inData = inData.mid(i+1);
history.push_back(contents);
//Get time
i = inData.indexOf(compare);
QString time = inData.left(i);
inData = inData.mid(i+1);
history.push_back(time);
}
guiPointer->receiveOldHistory(history);
}
// ---------------------------------------------
void NetClient::handleStructure(QString inData){
QVector<QString> output;
int i = inData.indexOf(compare);
while(i != -1){
//Create vector output, containing room content structure
QString data = inData.left(i);
inData = inData.mid(i+1);
output.push_back(data);
i = inData.indexOf(compare);
}
output.push_back(inData);
guiPointer->updateStruct(output);
}
// ---------------------------------------------
void NetClient::getHistory(unsigned int daysBack) {
QString temp;
string daysBackString = to_string(daysBack);
temp = QString::fromStdString(daysBackString);
QByteArray array = "/oldHistory";
array += compare; //unit separator
array += temp;
array += breaker;
TcpSocket->write(array);
TcpSocket->waitForBytesWritten(1000);
}
<commit_msg>Lacking default initiation on commandName strings. In event of crash command could be left in the string<commit_after>/*
FILNAMN: NetClient.cc
PROGRAMMERARE: hanel742, eriek984, jened502, tobgr602, niker917, davha227
SKAPAD DATUM: 2013-11-19
BESKRIVNING:
*/
#include "NetClient.h"
#include "../gui/gui.h"
using namespace std;
NetClient::NetClient(QString username, QString inAddress, Gui* myGui, QObject *parent) : QObject(parent){
guiPointer = myGui;
name=username;
address=inAddress;
compare += 0x1F;
breaker +=0x1E;
}
// ---------------------------------------------
void NetClient::start(){
TcpSocket = new QTcpSocket(this);
connect(TcpSocket,SIGNAL(connected()),this,SLOT(connected()));
connect(TcpSocket,SIGNAL(disconnected()),this,SLOT(disconnected()));
connect(TcpSocket,SIGNAL(readyRead()),this,SLOT(readyRead()));
QHostInfo info = QHostInfo::fromName(address);
if (info.addresses().size() == 0){
guiPointer->noConnection();
}
else{
TcpSocket->connectToHost(info.addresses().at(0),quint16(40001));
if(!TcpSocket->waitForConnected(1000)){
guiPointer->noConnection();
}
}
}
//------Slots---------
void NetClient::connected(){
QByteArray array = "/initiate";
array += 0x1F; //unit separator
array += name;
array += breaker;
TcpSocket->write(array);
TcpSocket->waitForBytesWritten(1000);
}
void NetClient::disconnected(){
guiPointer->disconnectedFromServer();
}
// --------readyRead------------------
void NetClient::readyRead(){
QByteArray Data = TcpSocket->readAll();
QString commandName = "";
QString inData = Data;
QString rest = "";
int n = inData.indexOf(breaker);
int i;
do {
rest = inData.mid(n+1);
inData = inData.left(n);
i = inData.indexOf(compare);
commandName = inData.left(i);
inData = inData.mid(i+1);
QString temp = inData;
string stdInData = temp.toStdString();
// Check which command that's supposed to run
if (commandName == "/reinitiate") {
guiPointer->userNameTaken();
break;
}
else if ( commandName == "/userAccepted") {
guiPointer->connected();
}
else if (commandName == "/history") {
handleHistory(inData);
}
else if (commandName == "/oldHistory") {
handleOldHistory(inData);
}
else if (commandName == "/message") {
handleMessage(inData);
}
else if ( commandName == "/requestStruct") {
handleRequestStruct();
}
else if ( commandName == "/structure" ) {
handleStructure(inData);
}
else {
throw logic_error("Unknown command: " + commandName.toStdString());
}
inData = rest;
n = inData.indexOf(breaker);
}while (n != -1 );
}
// ---------------------------------------------
void NetClient::sendMessage(QString from, QString to, QString message){
QByteArray array = "/message";
array += 0x1F; //unit separator
array += from;
array += 0x1F;
array += to;
array += 0x1F;
array += message;
array += breaker;
TcpSocket->write(array);
TcpSocket->waitForBytesWritten(1000);
}
void NetClient::setName(QString inName) {
name=inName;
}
void NetClient::getStruct(){
QByteArray array = "/structure";
array += 0x1E;
TcpSocket->write(array);
TcpSocket->waitForBytesWritten(1000);
}
//--------------------------------------------
//Helpfunctions
void NetClient::handleRequestStruct(){
QByteArray array = "/structure";
array += compare;
array += breaker;
TcpSocket->write(array);
TcpSocket->waitForBytesWritten(1000);
}
// ---------------------------------------------
void NetClient::handleMessage(QString inData){
int i;
// Get from
i = inData.indexOf(compare);
QString from = inData.left(i);
inData = inData.mid(i+1);
// Get to
i = inData.indexOf(compare);
QString to = inData.left(i);
inData = inData.mid(i+1);
// Get message
i = inData.indexOf(compare);
QString contents = inData.left(i);
inData = inData.mid(i+1);
// Get time
QString dateTime = inData;
//Send message to Gui
guiPointer->receiveMessage(from, to, contents, dateTime);
}
// ---------------------------------------------
void NetClient::handleHistory(QString inData){
QVector<QString> history;
int i = inData.indexOf(compare);
while(i != -1 ){
// Get from
i = inData.indexOf(compare);
QString from = inData.left(i);
inData = inData.mid(i+1);
history.push_back(from);
// Get to
i = inData.indexOf(compare);
QString to = inData.left(i);
inData = inData.mid(i+1);
history.push_back(to);
// Get message
i = inData.indexOf(compare);
QString contents = inData.left(i);
inData = inData.mid(i+1);
history.push_back(contents);
//Get time
i = inData.indexOf(compare);
QString time = inData.left(i);
inData = inData.mid(i+1);
history.push_back(time);
}
guiPointer->receiveHistory(history);
}
// ---------------------------------------------
void NetClient::handleOldHistory(QString inData){
QVector<QString> history;
int i = inData.indexOf(compare);
while(i != -1 ){
// Get from
i = inData.indexOf(compare);
QString from = inData.left(i);
inData = inData.mid(i+1);
history.push_back(from);
// Get to
i = inData.indexOf(compare);
QString to = inData.left(i);
inData = inData.mid(i+1);
history.push_back(to);
// Get message
i = inData.indexOf(compare);
QString contents = inData.left(i);
inData = inData.mid(i+1);
history.push_back(contents);
//Get time
i = inData.indexOf(compare);
QString time = inData.left(i);
inData = inData.mid(i+1);
history.push_back(time);
}
guiPointer->receiveOldHistory(history);
}
// ---------------------------------------------
void NetClient::handleStructure(QString inData){
QVector<QString> output;
int i = inData.indexOf(compare);
while(i != -1){
//Create vector output, containing room content structure
QString data = inData.left(i);
inData = inData.mid(i+1);
output.push_back(data);
i = inData.indexOf(compare);
}
output.push_back(inData);
guiPointer->updateStruct(output);
}
// ---------------------------------------------
void NetClient::getHistory(unsigned int daysBack) {
QString temp;
string daysBackString = to_string(daysBack);
temp = QString::fromStdString(daysBackString);
QByteArray array = "/oldHistory";
array += compare; //unit separator
array += temp;
array += breaker;
TcpSocket->write(array);
TcpSocket->waitForBytesWritten(1000);
}
<|endoftext|>
|
<commit_before>/*
* nextpnr -- Next Generation Place and Route
*
* Copyright (C) 2018 Miodrag Milanovic <miodrag@symbioticeda.com>
*
* 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 "treemodel.h"
NEXTPNR_NAMESPACE_BEGIN
static bool contextTreeItemLessThan(const ContextTreeItem *v1, const ContextTreeItem *v2)
{
return v1->name() < v2->name();
}
ContextTreeItem::ContextTreeItem() { parentNode = nullptr; }
ContextTreeItem::ContextTreeItem(QString name)
: parentNode(nullptr), itemId(IdString()), itemType(ElementType::NONE), itemName(name)
{
}
ContextTreeItem::ContextTreeItem(IdString id, ElementType type, QString name)
: parentNode(nullptr), itemId(id), itemType(type), itemName(name)
{
}
ContextTreeItem::~ContextTreeItem()
{
if (parentNode)
parentNode->children.removeOne(this);
qDeleteAll(children);
}
void ContextTreeItem::addChild(ContextTreeItem *item)
{
item->parentNode = this;
children.append(item);
}
void ContextTreeItem::sort()
{
for (auto item : children)
if (item->count()>1) item->sort();
qSort(children.begin(), children.end(), contextTreeItemLessThan);
}
ContextTreeModel::ContextTreeModel(QObject *parent) : QAbstractItemModel(parent) { root = new ContextTreeItem(); }
ContextTreeModel::~ContextTreeModel() { delete root; }
void ContextTreeModel::loadData(Context *ctx)
{
if (!ctx)
return;
beginResetModel();
delete root;
root = new ContextTreeItem();
for (int i = 0; i < 6; i++)
nameToItem[i].clear();
IdString none;
ContextTreeItem *bels_root = new ContextTreeItem("Bels");
root->addChild(bels_root);
QMap<QString, ContextTreeItem *> bel_items;
// Add bels to tree
for (auto bel : ctx->getBels()) {
IdString id = ctx->getBelName(bel);
QStringList items = QString(id.c_str(ctx)).split("/");
QString name;
ContextTreeItem *parent = bels_root;
for (int i = 0; i < items.size(); i++) {
if (!name.isEmpty())
name += "/";
name += items.at(i);
if (!bel_items.contains(name)) {
if (i == items.size() - 1) {
ContextTreeItem *item = new ContextTreeItem(id, ElementType::BEL, items.at(i));
parent->addChild(item);
nameToItem[0].insert(name, item);
} else {
ContextTreeItem *item = new ContextTreeItem(none, ElementType::NONE, items.at(i));
parent->addChild(item);
bel_items.insert(name, item);
}
}
parent = bel_items[name];
}
}
bels_root->sort();
ContextTreeItem *wire_root = new ContextTreeItem("Wires");
root->addChild(wire_root);
QMap<QString, ContextTreeItem *> wire_items;
// Add wires to tree
for (auto wire : ctx->getWires()) {
auto id = ctx->getWireName(wire);
QStringList items = QString(id.c_str(ctx)).split("/");
QString name;
ContextTreeItem *parent = wire_root;
for (int i = 0; i < items.size(); i++) {
if (!name.isEmpty())
name += "/";
name += items.at(i);
if (!wire_items.contains(name)) {
if (i == items.size() - 1) {
ContextTreeItem *item = new ContextTreeItem(id, ElementType::WIRE, items.at(i));
parent->addChild(item);
nameToItem[1].insert(name, item);
} else {
ContextTreeItem *item = new ContextTreeItem(none, ElementType::NONE, items.at(i));
parent->addChild(item);
wire_items.insert(name, item);
}
}
parent = wire_items[name];
}
}
wire_root->sort();
ContextTreeItem *pip_root = new ContextTreeItem("Pips");
root->addChild(pip_root);
QMap<QString, ContextTreeItem *> pip_items;
// Add pips to tree
for (auto pip : ctx->getPips()) {
auto id = ctx->getPipName(pip);
QStringList items = QString(id.c_str(ctx)).split("/");
QString name;
ContextTreeItem *parent = pip_root;
for (int i = 0; i < items.size(); i++) {
if (!name.isEmpty())
name += "/";
name += items.at(i);
if (!pip_items.contains(name)) {
if (i == items.size() - 1) {
ContextTreeItem *item = new ContextTreeItem(id, ElementType::PIP, items.at(i));
parent->addChild(item);
nameToItem[2].insert(name, item);
} else {
ContextTreeItem *item = new ContextTreeItem(none, ElementType::NONE, items.at(i));
parent->addChild(item);
pip_items.insert(name, item);
}
}
parent = pip_items[name];
}
}
pip_root->sort();
nets_root = new ContextTreeItem("Nets");
root->addChild(nets_root);
cells_root = new ContextTreeItem("Cells");
root->addChild(cells_root);
endResetModel();
}
void ContextTreeModel::updateData(Context *ctx)
{
if (!ctx)
return;
beginResetModel();
//QModelIndex nets_index = indexFromNode(nets_root);
// Remove nets not existing any more
QMap<QString, ContextTreeItem *>::iterator i = nameToItem[3].begin();
while (i != nameToItem[3].end()) {
QMap<QString, ContextTreeItem *>::iterator prev = i;
++i;
if (ctx->nets.find(ctx->id(prev.key().toStdString())) == ctx->nets.end()) {
//int pos = prev.value()->parent()->indexOf(prev.value());
//beginRemoveRows(nets_index, pos, pos);
delete prev.value();
nameToItem[3].erase(prev);
//endRemoveRows();
}
}
// Add nets to tree
for (auto &item : ctx->nets) {
auto id = item.first;
QString name = QString(id.c_str(ctx));
if (!nameToItem[3].contains(name)) {
//beginInsertRows(nets_index, nets_root->count() + 1, nets_root->count() + 1);
ContextTreeItem *newItem = new ContextTreeItem(id, ElementType::NET, name);
nets_root->addChild(newItem);
nameToItem[3].insert(name, newItem);
//endInsertRows();
}
}
nets_root->sort();
//QModelIndex cell_index = indexFromNode(cells_root);
// Remove cells not existing any more
i = nameToItem[4].begin();
while (i != nameToItem[4].end()) {
QMap<QString, ContextTreeItem *>::iterator prev = i;
++i;
if (ctx->cells.find(ctx->id(prev.key().toStdString())) == ctx->cells.end()) {
//int pos = prev.value()->parent()->indexOf(prev.value());
//beginRemoveRows(cell_index, pos, pos);
delete prev.value();
nameToItem[4].erase(prev);
//endRemoveRows();
}
}
// Add cells to tree
for (auto &item : ctx->cells) {
auto id = item.first;
QString name = QString(id.c_str(ctx));
if (!nameToItem[4].contains(name)) {
//beginInsertRows(cell_index, cells_root->count() + 1, cells_root->count() + 1);
ContextTreeItem *newItem = new ContextTreeItem(id, ElementType::CELL, name);
cells_root->addChild(newItem);
nameToItem[4].insert(name, newItem);
//endInsertRows();
}
}
cells_root->sort();
endResetModel();
}
int ContextTreeModel::rowCount(const QModelIndex &parent) const { return nodeFromIndex(parent)->count(); }
int ContextTreeModel::columnCount(const QModelIndex &parent) const { return 1; }
QModelIndex ContextTreeModel::index(int row, int column, const QModelIndex &parent) const
{
ContextTreeItem *node = nodeFromIndex(parent);
if (row >= node->count())
return QModelIndex();
return createIndex(row, column, node->at(row));
}
QModelIndex ContextTreeModel::parent(const QModelIndex &child) const
{
ContextTreeItem *parent = nodeFromIndex(child)->parent();
if (parent == root)
return QModelIndex();
ContextTreeItem *node = parent->parent();
return createIndex(node->indexOf(parent), 0, parent);
}
QVariant ContextTreeModel::data(const QModelIndex &index, int role) const
{
if (index.column() != 0)
return QVariant();
if (role != Qt::DisplayRole)
return QVariant();
ContextTreeItem *node = nodeFromIndex(index);
return node->name();
}
QVariant ContextTreeModel::headerData(int section, Qt::Orientation orientation, int role) const
{
Q_UNUSED(section);
if (orientation == Qt::Horizontal && role == Qt::DisplayRole)
return QString("Items");
return QVariant();
}
ContextTreeItem *ContextTreeModel::nodeFromIndex(const QModelIndex &idx) const
{
if (idx.isValid())
return (ContextTreeItem *)idx.internalPointer();
return root;
}
static int getElementIndex(ElementType type)
{
if (type == ElementType::BEL)
return 0;
if (type == ElementType::WIRE)
return 1;
if (type == ElementType::PIP)
return 2;
if (type == ElementType::NET)
return 3;
if (type == ElementType::CELL)
return 4;
return -1;
}
ContextTreeItem *ContextTreeModel::nodeForIdType(const ElementType type, const QString name) const
{
int index = getElementIndex(type);
if (type != ElementType::NONE && nameToItem[index].contains(name))
return nameToItem[index].value(name);
return nullptr;
}
QModelIndex ContextTreeModel::indexFromNode(ContextTreeItem *node)
{
ContextTreeItem *parent = node->parent();
if (parent == root)
return QModelIndex();
return createIndex(parent->indexOf(node), 0, node);
}
Qt::ItemFlags ContextTreeModel::flags(const QModelIndex &index) const
{
ContextTreeItem *node = nodeFromIndex(index);
return Qt::ItemIsEnabled | (node->type() != ElementType::NONE ? Qt::ItemIsSelectable : Qt::NoItemFlags);
}
NEXTPNR_NAMESPACE_END<commit_msg>gui: sort tree elements somewhat smarter<commit_after>/*
* nextpnr -- Next Generation Place and Route
*
* Copyright (C) 2018 Miodrag Milanovic <miodrag@symbioticeda.com>
*
* 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 "treemodel.h"
NEXTPNR_NAMESPACE_BEGIN
ContextTreeItem::ContextTreeItem() { parentNode = nullptr; }
ContextTreeItem::ContextTreeItem(QString name)
: parentNode(nullptr), itemId(IdString()), itemType(ElementType::NONE), itemName(name)
{
}
ContextTreeItem::ContextTreeItem(IdString id, ElementType type, QString name)
: parentNode(nullptr), itemId(id), itemType(type), itemName(name)
{
}
ContextTreeItem::~ContextTreeItem()
{
if (parentNode)
parentNode->children.removeOne(this);
qDeleteAll(children);
}
void ContextTreeItem::addChild(ContextTreeItem *item)
{
item->parentNode = this;
children.append(item);
}
void ContextTreeItem::sort()
{
for (auto item : children)
if (item->count()>1) item->sort();
qSort(children.begin(), children.end(), [&](const ContextTreeItem *a, const ContextTreeItem *b){
QString name_a = a->name();
QString name_b = b->name();
// Try to extract a common prefix from both strings.
QString common;
for (int i = 0; i < std::min(name_a.size(), name_b.size()); i++) {
const QChar c_a = name_a[i];
const QChar c_b = name_b[i];
if (c_a == c_b) {
common.push_back(c_a);
} else {
break;
}
}
// No common part? lexical sort.
if (common.size() == 0) {
return a->name() < b->name();
}
// Get the non-common parts.
name_a.remove(0, common.size());
name_b.remove(0, common.size());
// And see if they're strings.
bool ok = true;
int num_a = name_a.toInt(&ok);
if (!ok) {
return a->name() < b->name();
}
int num_b = name_b.toInt(&ok);
if (!ok) {
return a->name() < b->name();
}
return num_a < num_b;
});
}
ContextTreeModel::ContextTreeModel(QObject *parent) : QAbstractItemModel(parent) { root = new ContextTreeItem(); }
ContextTreeModel::~ContextTreeModel() { delete root; }
void ContextTreeModel::loadData(Context *ctx)
{
if (!ctx)
return;
beginResetModel();
delete root;
root = new ContextTreeItem();
for (int i = 0; i < 6; i++)
nameToItem[i].clear();
IdString none;
ContextTreeItem *bels_root = new ContextTreeItem("Bels");
root->addChild(bels_root);
QMap<QString, ContextTreeItem *> bel_items;
// Add bels to tree
for (auto bel : ctx->getBels()) {
IdString id = ctx->getBelName(bel);
QStringList items = QString(id.c_str(ctx)).split("/");
QString name;
ContextTreeItem *parent = bels_root;
for (int i = 0; i < items.size(); i++) {
if (!name.isEmpty())
name += "/";
name += items.at(i);
if (!bel_items.contains(name)) {
if (i == items.size() - 1) {
ContextTreeItem *item = new ContextTreeItem(id, ElementType::BEL, items.at(i));
parent->addChild(item);
nameToItem[0].insert(name, item);
} else {
ContextTreeItem *item = new ContextTreeItem(none, ElementType::NONE, items.at(i));
parent->addChild(item);
bel_items.insert(name, item);
}
}
parent = bel_items[name];
}
}
bels_root->sort();
ContextTreeItem *wire_root = new ContextTreeItem("Wires");
root->addChild(wire_root);
QMap<QString, ContextTreeItem *> wire_items;
// Add wires to tree
for (auto wire : ctx->getWires()) {
auto id = ctx->getWireName(wire);
QStringList items = QString(id.c_str(ctx)).split("/");
QString name;
ContextTreeItem *parent = wire_root;
for (int i = 0; i < items.size(); i++) {
if (!name.isEmpty())
name += "/";
name += items.at(i);
if (!wire_items.contains(name)) {
if (i == items.size() - 1) {
ContextTreeItem *item = new ContextTreeItem(id, ElementType::WIRE, items.at(i));
parent->addChild(item);
nameToItem[1].insert(name, item);
} else {
ContextTreeItem *item = new ContextTreeItem(none, ElementType::NONE, items.at(i));
parent->addChild(item);
wire_items.insert(name, item);
}
}
parent = wire_items[name];
}
}
wire_root->sort();
ContextTreeItem *pip_root = new ContextTreeItem("Pips");
root->addChild(pip_root);
QMap<QString, ContextTreeItem *> pip_items;
// Add pips to tree
for (auto pip : ctx->getPips()) {
auto id = ctx->getPipName(pip);
QStringList items = QString(id.c_str(ctx)).split("/");
QString name;
ContextTreeItem *parent = pip_root;
for (int i = 0; i < items.size(); i++) {
if (!name.isEmpty())
name += "/";
name += items.at(i);
if (!pip_items.contains(name)) {
if (i == items.size() - 1) {
ContextTreeItem *item = new ContextTreeItem(id, ElementType::PIP, items.at(i));
parent->addChild(item);
nameToItem[2].insert(name, item);
} else {
ContextTreeItem *item = new ContextTreeItem(none, ElementType::NONE, items.at(i));
parent->addChild(item);
pip_items.insert(name, item);
}
}
parent = pip_items[name];
}
}
pip_root->sort();
nets_root = new ContextTreeItem("Nets");
root->addChild(nets_root);
cells_root = new ContextTreeItem("Cells");
root->addChild(cells_root);
endResetModel();
}
void ContextTreeModel::updateData(Context *ctx)
{
if (!ctx)
return;
beginResetModel();
//QModelIndex nets_index = indexFromNode(nets_root);
// Remove nets not existing any more
QMap<QString, ContextTreeItem *>::iterator i = nameToItem[3].begin();
while (i != nameToItem[3].end()) {
QMap<QString, ContextTreeItem *>::iterator prev = i;
++i;
if (ctx->nets.find(ctx->id(prev.key().toStdString())) == ctx->nets.end()) {
//int pos = prev.value()->parent()->indexOf(prev.value());
//beginRemoveRows(nets_index, pos, pos);
delete prev.value();
nameToItem[3].erase(prev);
//endRemoveRows();
}
}
// Add nets to tree
for (auto &item : ctx->nets) {
auto id = item.first;
QString name = QString(id.c_str(ctx));
if (!nameToItem[3].contains(name)) {
//beginInsertRows(nets_index, nets_root->count() + 1, nets_root->count() + 1);
ContextTreeItem *newItem = new ContextTreeItem(id, ElementType::NET, name);
nets_root->addChild(newItem);
nameToItem[3].insert(name, newItem);
//endInsertRows();
}
}
nets_root->sort();
//QModelIndex cell_index = indexFromNode(cells_root);
// Remove cells not existing any more
i = nameToItem[4].begin();
while (i != nameToItem[4].end()) {
QMap<QString, ContextTreeItem *>::iterator prev = i;
++i;
if (ctx->cells.find(ctx->id(prev.key().toStdString())) == ctx->cells.end()) {
//int pos = prev.value()->parent()->indexOf(prev.value());
//beginRemoveRows(cell_index, pos, pos);
delete prev.value();
nameToItem[4].erase(prev);
//endRemoveRows();
}
}
// Add cells to tree
for (auto &item : ctx->cells) {
auto id = item.first;
QString name = QString(id.c_str(ctx));
if (!nameToItem[4].contains(name)) {
//beginInsertRows(cell_index, cells_root->count() + 1, cells_root->count() + 1);
ContextTreeItem *newItem = new ContextTreeItem(id, ElementType::CELL, name);
cells_root->addChild(newItem);
nameToItem[4].insert(name, newItem);
//endInsertRows();
}
}
cells_root->sort();
endResetModel();
}
int ContextTreeModel::rowCount(const QModelIndex &parent) const { return nodeFromIndex(parent)->count(); }
int ContextTreeModel::columnCount(const QModelIndex &parent) const { return 1; }
QModelIndex ContextTreeModel::index(int row, int column, const QModelIndex &parent) const
{
ContextTreeItem *node = nodeFromIndex(parent);
if (row >= node->count())
return QModelIndex();
return createIndex(row, column, node->at(row));
}
QModelIndex ContextTreeModel::parent(const QModelIndex &child) const
{
ContextTreeItem *parent = nodeFromIndex(child)->parent();
if (parent == root)
return QModelIndex();
ContextTreeItem *node = parent->parent();
return createIndex(node->indexOf(parent), 0, parent);
}
QVariant ContextTreeModel::data(const QModelIndex &index, int role) const
{
if (index.column() != 0)
return QVariant();
if (role != Qt::DisplayRole)
return QVariant();
ContextTreeItem *node = nodeFromIndex(index);
return node->name();
}
QVariant ContextTreeModel::headerData(int section, Qt::Orientation orientation, int role) const
{
Q_UNUSED(section);
if (orientation == Qt::Horizontal && role == Qt::DisplayRole)
return QString("Items");
return QVariant();
}
ContextTreeItem *ContextTreeModel::nodeFromIndex(const QModelIndex &idx) const
{
if (idx.isValid())
return (ContextTreeItem *)idx.internalPointer();
return root;
}
static int getElementIndex(ElementType type)
{
if (type == ElementType::BEL)
return 0;
if (type == ElementType::WIRE)
return 1;
if (type == ElementType::PIP)
return 2;
if (type == ElementType::NET)
return 3;
if (type == ElementType::CELL)
return 4;
return -1;
}
ContextTreeItem *ContextTreeModel::nodeForIdType(const ElementType type, const QString name) const
{
int index = getElementIndex(type);
if (type != ElementType::NONE && nameToItem[index].contains(name))
return nameToItem[index].value(name);
return nullptr;
}
QModelIndex ContextTreeModel::indexFromNode(ContextTreeItem *node)
{
ContextTreeItem *parent = node->parent();
if (parent == root)
return QModelIndex();
return createIndex(parent->indexOf(node), 0, node);
}
Qt::ItemFlags ContextTreeModel::flags(const QModelIndex &index) const
{
ContextTreeItem *node = nodeFromIndex(index);
return Qt::ItemIsEnabled | (node->type() != ElementType::NONE ? Qt::ItemIsSelectable : Qt::NoItemFlags);
}
NEXTPNR_NAMESPACE_END
<|endoftext|>
|
<commit_before>#include "quimby/MMapFile.h"
/*
#include <errno.h>
#include <math.h>
#include <string.h>
*/
#include <unistd.h>
#include <fcntl.h>
#include <stdlib.h>
#include <sys/mman.h>
#include <stdio.h>
#include <stdexcept>
namespace quimby {
MMapFile::MMapFile() :
_fd(-1), _size(0), _data((char *)MAP_FAILED) {
}
MMapFile::MMapFile(const std::string& filename, MappingType mtype) :
_fd(-1), _size(0), _data((char *)MAP_FAILED) {
open(filename, mtype);
}
MMapFile::~MMapFile() {
close();
}
void MMapFile::open(const std::string& filename, MappingType mtype ) {
close();
_fd = ::open(filename.c_str(), O_RDONLY);
if (_fd == -1) {
perror("MMapFile");
throw std::runtime_error("[MMapFile] error opening file!");
}
_size = ::lseek(_fd, 0, SEEK_END);
int flags = MAP_PRIVATE;
if (mtype == ReadAhead)
flags |= MAP_POPULATE;
else if (mtype == Auto) {
size_t mem = sysconf(_SC_PHYS_PAGES) * sysconf(_SC_PAGESIZE);
if (_size < mem - 200) {
#ifdef DEBUG
std::cout << "[MMapFile] Automatic mapping: ReadAhead, " << mem / 1000 / 1000 << " MB physical, " << _size / 1000 / 1000 << " MB required" << std::endl;
#endif
flags |= MAP_POPULATE;
} else {
#ifdef DEBUG
std::cout << "[MMapFile] Automatic mapping: OnDemand, " << mem / 1000 / 1000 << " MB physical, " << _size / 1000 / 1000 << " MB required" << std::endl;
#endif
}
}
_data = mmap(NULL, _size, PROT_READ, flags, _fd, 0);
if (_data == MAP_FAILED) {
perror("MMapFile");
close();
throw std::runtime_error("[HCubeFile] error mapping file: " + filename);
}
}
void MMapFile::close() {
if (_data != MAP_FAILED) {
int result = munmap(_data, _size);
// if (result < 0) {
// printf("Error unmapping 0x0%lx of size %ld\n",
// (unsigned long) _data, _size);
// }
_data = MAP_FAILED;
}
_size = 0;
if (_fd >= 0) {
::close(_fd);
_fd = -1;
}
}
MMapFileWrite::MMapFileWrite(const std::string filename, size_t size, bool resume) :
_file(-1), _data(MAP_FAILED), _data_size(size) {
if (resume)
_file = ::open(filename.c_str(), O_RDWR, 0666);
else
_file = ::open(filename.c_str(), O_RDWR | O_CREAT | O_TRUNC, 0666);
if (_file == -1)
throw std::runtime_error("[MappedFile] error opening file!");
truncate(_data_size);
_data = ::mmap(NULL, _data_size, PROT_READ | PROT_WRITE, MAP_PRIVATE,
_file, 0);
if (_data == MAP_FAILED) {
perror("MappedFile");
throw std::runtime_error("[MappedFileWrite] error mapping file: " + filename);
}
}
void MMapFileWrite::truncate(size_t size) {
if (_file == -1)
return;
if (ftruncate(_file, size) == -1)
throw std::runtime_error("[MappedFile Write] error truncating file!");
}
MMapFileWrite::~MMapFileWrite() {
unmap();
close();
}
void MMapFileWrite::unmap() {
if (_data != MAP_FAILED) {
::msync(_data, _data_size, MS_SYNC);
::munmap(_data, _data_size);
_data = MAP_FAILED;
}
}
void MMapFileWrite::close() {
if (_file != -1) {
::close(_file);
_file = -1;
}
}
void* MMapFileWrite::data() {
return _data;
}
} // namespace quimby
<commit_msg>fix mmap<commit_after>#include "quimby/MMapFile.h"
/*
#include <errno.h>
#include <math.h>
#include <string.h>
*/
#include <unistd.h>
#include <fcntl.h>
#include <stdlib.h>
#include <sys/mman.h>
#include <stdio.h>
#include <stdexcept>
#include <iostream>
namespace quimby {
MMapFile::MMapFile() :
_fd(-1), _size(0), _data((char *)MAP_FAILED) {
}
MMapFile::MMapFile(const std::string& filename, MappingType mtype) :
_fd(-1), _size(0), _data((char *)MAP_FAILED) {
open(filename, mtype);
}
MMapFile::~MMapFile() {
close();
}
void MMapFile::open(const std::string& filename, MappingType mtype ) {
close();
_fd = ::open(filename.c_str(), O_RDONLY);
if (_fd == -1) {
perror("MMapFile");
throw std::runtime_error("[MMapFile] error opening file!");
}
_size = ::lseek(_fd, 0, SEEK_END);
int flags = MAP_SHARED;
if (mtype == ReadAhead)
flags |= MAP_POPULATE;
else if (mtype == Auto) {
size_t mem = sysconf(_SC_PHYS_PAGES) * sysconf(_SC_PAGESIZE);
if (_size < mem - 200) {
#ifdef DEBUG
std::cout << "[MMapFile] Automatic mapping: ReadAhead, " << mem / 1000 / 1000 << " MB physical, " << _size / 1000 / 1000 << " MB required" << std::endl;
#endif
flags |= MAP_POPULATE;
} else {
#ifdef DEBUG
std::cout << "[MMapFile] Automatic mapping: OnDemand, " << mem / 1000 / 1000 << " MB physical, " << _size / 1000 / 1000 << " MB required" << std::endl;
#endif
}
}
_data = mmap(NULL, _size, PROT_READ, flags, _fd, 0);
if (_data == MAP_FAILED) {
perror("MMapFile");
close();
throw std::runtime_error("[HCubeFile] error mapping file: " + filename);
}
}
void MMapFile::close() {
if (_data != MAP_FAILED) {
int result = munmap(_data, _size);
// if (result < 0) {
// printf("Error unmapping 0x0%lx of size %ld\n",
// (unsigned long) _data, _size);
// }
_data = MAP_FAILED;
}
_size = 0;
if (_fd >= 0) {
::close(_fd);
_fd = -1;
}
}
MMapFileWrite::MMapFileWrite(const std::string filename, size_t size, bool resume) :
_file(-1), _data(MAP_FAILED), _data_size(size) {
if (resume)
_file = ::open(filename.c_str(), O_RDWR, 0666);
else
_file = ::open(filename.c_str(), O_RDWR | O_CREAT | O_TRUNC, 0666);
if (_file == -1)
throw std::runtime_error("[MappedFile] error opening file!");
truncate(_data_size);
_data = ::mmap(NULL, _data_size, PROT_READ | PROT_WRITE, MAP_SHARED,
_file, 0);
if (_data == MAP_FAILED) {
std::cout << "[MappedFileWrite] " << _data_size << std::endl;
perror("[MappedFileWrite]");
throw std::runtime_error("[MappedFileWrite] error mapping file: " + filename);
}
}
void MMapFileWrite::truncate(size_t size) {
if (_file == -1)
return;
if (ftruncate(_file, size) == -1)
throw std::runtime_error("[MappedFile Write] error truncating file!");
}
MMapFileWrite::~MMapFileWrite() {
unmap();
close();
}
void MMapFileWrite::unmap() {
if (_data != MAP_FAILED) {
::msync(_data, _data_size, MS_SYNC);
::munmap(_data, _data_size);
_data = MAP_FAILED;
}
}
void MMapFileWrite::close() {
if (_file != -1) {
::close(_file);
_file = -1;
}
}
void* MMapFileWrite::data() {
return _data;
}
} // namespace quimby
<|endoftext|>
|
<commit_before>#include "Moose.h"
#include "Factory.h"
#include "NonlinearSystem.h"
#include "PetscSupport.h"
#include "ActionWarehouse.h"
#include "ActionFactory.h"
// objects that can be created by MOOSE
#include "TimeDerivative.h"
#include "Diffusion.h"
#include "CoupledForce.h"
#include "UserForcingFunction.h"
#include "BodyForce.h"
#include "ImplicitEuler.h"
#include "Reaction.h"
#include "RealPropertyOutput.h"
// bcs
#include "DirichletBC.h"
#include "NeumannBC.h"
#include "FunctionDirichletBC.h"
#include "FunctionNeumannBC.h"
#include "MatchedValueBC.h"
#include "VacuumBC.h"
// auxkernels
#include "CoupledAux.h"
#include "ConstantAux.h"
#include "FunctionAux.h"
#include "NearestNodeDistanceAux.h"
#include "NearestNodeValueAux.h"
#include "PenetrationAux.h"
#include "ProcessorIDAux.h"
#include "GapValueAux.h"
// dirac kernels
#include "ConstantPointSource.h"
// ics
#include "ConstantIC.h"
#include "BoundingBoxIC.h"
#include "FunctionIC.h"
#include "RandomIC.h"
// mesh modifiers
#include "ElementDeleter.h"
// executioners
#include "Steady.h"
#include "Transient.h"
#include "LooseCoupling.h"
#include "SolutionTimeAdaptive.h"
// functions
#include "ParsedFunction.h"
#include "ParsedGradFunction.h"
#include "PiecewiseLinear.h"
#include "SolutionFunction.h"
#include "SphereFunction.h"
// materials
#include "GenericConstantMaterial.h"
// PPS
#include "AverageElementSize.h"
#include "AverageNodalVariableValue.h"
#include "ElementAverageValue.h"
#include "ElementH1Error.h"
#include "ElementH1SemiError.h"
#include "ElementIntegral.h"
#include "ElementL2Error.h"
#include "EmptyPostprocessor.h"
#include "NodalVariableValue.h"
#include "PrintDOFs.h"
#include "PrintDT.h"
#include "PrintNumElems.h"
#include "PrintNumNodes.h"
#include "Reporter.h"
#include "SideAverageValue.h"
#include "SideFluxIntegral.h"
#include "SideIntegral.h"
// stabilizers
#include "ConvectionDiffusionSUPG.h"
// dampers
#include "ConstantDamper.h"
#include "MaxIncrement.h"
// Actions
#include "AddMeshModifierAction.h"
#include "AddBCAction.h"
#include "AddDiracKernelAction.h"
#include "AddICAction.h"
#include "AddKernelAction.h"
#include "AddPeriodicBCAction.h"
#include "AddVariableAction.h"
#include "AddPostprocessorAction.h"
#include "AddDamperAction.h"
#include "AddStabilizerAction.h"
#include "AddFunctionAction.h"
#include "CreateExecutionerAction.h"
#include "CreateMeshAction.h"
#include "EmptyAction.h"
#include "InitProblemAction.h"
#include "CopyNodalVarsAction.h"
#include "SetupMeshAction.h"
#include "SetupOutputAction.h"
#include "AddMaterialAction.h"
#include "GlobalParamsAction.h"
#include "SetupPBPAction.h"
#include "AdaptivityAction.h"
#include "SetupDampersAction.h"
#include "CheckIntegrityAction.h"
namespace Moose {
static bool registered = false;
void
registerObjects()
{
if (registered)
return;
registerObject(TimeDerivative);
// kernels
registerObject(Diffusion);
registerObject(CoupledForce);
registerObject(UserForcingFunction);
registerObject(BodyForce);
registerObject(ImplicitEuler);
registerObject(Reaction);
registerObject(RealPropertyOutput);
// bcs
registerObject(DirichletBC);
registerObject(NeumannBC);
registerObject(FunctionDirichletBC);
registerObject(FunctionNeumannBC);
registerObject(MatchedValueBC);
registerObject(VacuumBC);
// dirac kernels
registerObject(ConstantPointSource);
// aux kernels
registerObject(CoupledAux);
registerObject(ConstantAux);
registerObject(FunctionAux);
registerObject(NearestNodeDistanceAux);
registerObject(NearestNodeValueAux);
registerObject(PenetrationAux);
registerObject(ProcessorIDAux);
registerObject(GapValueAux);
// Initial Conditions
registerObject(ConstantIC);
registerObject(BoundingBoxIC);
registerObject(FunctionIC);
registerObject(RandomIC);
// Mesh Modifiers
registerObject(ElementDeleter);
// executioners
registerObject(Steady);
registerObject(Transient);
registerObject(LooseCoupling);
registerObject(SolutionTimeAdaptive);
// functions
registerObject(ParsedFunction);
registerObject(ParsedGradFunction);
registerObject(PiecewiseLinear);
registerObject(SolutionFunction);
registerObject(SphereFunction);
// materials
registerObject(GenericConstantMaterial);
// PPS
registerObject(AverageElementSize);
registerObject(AverageNodalVariableValue);
registerObject(ElementAverageValue);
registerObject(ElementH1Error);
registerObject(ElementH1SemiError);
registerObject(ElementIntegral);
registerObject(ElementL2Error);
registerObject(EmptyPostprocessor);
registerObject(NodalVariableValue);
registerObject(PrintDOFs);
registerObject(PrintDT);
registerObject(PrintNumElems);
registerObject(PrintNumNodes);
registerObject(Reporter);
registerObject(SideAverageValue);
registerObject(SideFluxIntegral);
registerObject(SideIntegral);
// stabilizers
registerObject(ConvectionDiffusionSUPG);
// dampers
registerObject(ConstantDamper);
registerObject(MaxIncrement);
addActionTypes();
registerActions();
registered = true;
}
void
addActionTypes()
{
/**************************/
/**** Register Actions ****/
/**************************/
/// Minimal Problem
registerActionName("setup_mesh", true);
registerActionName("add_variable", true);
registerActionName("add_kernel", true);
registerActionName("setup_executioner", true);
registerActionName("setup_output", true);
registerActionName("init_problem", true);
registerActionName("copy_nodal_vars", true);
registerActionName("add_bc", false); // Does this need to be true? Not if you have periodic boundaries...
registerActionName("setup_dampers", true);
registerActionName("check_integrity", true);
/// Additional Actions
registerActionName("no_action", false); // Used for Empty Action placeholders
registerActionName("set_global_params", false);
registerActionName("create_mesh", false);
registerActionName("add_mesh_modifier", false);
registerActionName("add_material", false);
registerActionName("add_function", false);
registerActionName("add_aux_variable", false);
registerActionName("add_aux_kernel", false);
registerActionName("add_aux_bc", false);
registerActionName("add_dirac_kernel", false);
registerActionName("add_ic", false);
registerActionName("add_postprocessor", false);
registerActionName("add_damper", false);
registerActionName("add_stabilizer", false);
registerActionName("add_periodic_bc", false);
registerActionName("add_preconditioning", false);
registerActionName("setup_adaptivity", false);
// Dummy Actions (useful for sync points in the dependencies)
registerActionName("setup_mesh_complete", false);
registerActionName("setup_function_complete", false);
registerActionName("setup_variable_complete", false);
registerActionName("ready_to_init", false);
registerActionName("setup_pps_complete", false);
/**************************/
/****** Dependencies ******/
/**************************/
/*
/// Mesh Actions
action_warehouse.addDependency("setup_mesh", "create_mesh");
action_warehouse.addDependency("add_mesh_modifier", "setup_mesh");
action_warehouse.addDependency("setup_mesh_complete", "setup_mesh");
/// Executioner
action_warehouse.addDependency("setup_executioner", "setup_mesh_complete");
action_warehouse.addDependency("setup_adaptivity", "setup_executioner");
/// Functions
action_warehouse.addDependency("add_function", "setup_adaptivity");
action_warehouse.addDependency("setup_function_complete", "add_function");
/// Variable Actions
action_warehouse.addDependency("add_variable", "setup_function_complete");
/// AuxVariable Actions
action_warehouse.addDependency("add_aux_variable", "setup_function_complete");
action_warehouse.addDependency("setup_variable_complete", "add_aux_variable");
/// ICs
action_warehouse.addDependency("add_ic", "setup_variable_complete");
/// PeriodicBCs
action_warehouse.addDependency("add_periodic_bc", "setup_variable_complete");
/// Preconditioning
action_warehouse.addDependency("add_preconditioning", "add_periodic_bc");
action_warehouse.addDependency("ready_to_init", "add_preconditioning");
/// InitProblem
action_warehouse.addDependency("setup_dampers", "ready_to_init");
action_warehouse.addDependency("init_problem", "setup_dampers");
action_warehouse.addDependency("copy_nodal_vars", "init_problem");
/// Materials
action_warehouse.addDependency("add_material", "copy_nodal_vars");
/// Postprocessors
action_warehouse.addDependency("add_postprocessor", "add_material");
action_warehouse.addDependency("setup_pps_complete", "add_postprocessor");
/// Dampers
action_warehouse.addDependency("add_damper", "setup_pps_complete");
/// Stabilizers
action_warehouse.addDependency("add_stabilizer", "setup_pps_complete");
/// Kernels
action_warehouse.addDependency("add_kernel", "setup_pps_complete");
/// AuxKernels
action_warehouse.addDependency("add_aux_kernel", "setup_pps_complete");
/// BCs
action_warehouse.addDependency("add_bc", "setup_pps_complete");
/// AuxBCs
action_warehouse.addDependency("add_aux_bc", "setup_pps_complete");
/// Dirac Kernels
action_warehouse.addDependency("add_dirac_kernel", "setup_pps_complete");
/// Ouput
action_warehouse.addDependency("setup_output", "setup_pps_complete");
/// Check Integrity
action_warehouse.addDependency("check_integrity", "setup_output");
*/
/**
* The following is the default set of action dependencies for a basic MOOSE problem. The formatting
* of this string is important. Each line represents a set of dependencies that depend on the previous
* line. Items on the same line have equal weight and can be executed in any order. */
action_warehouse.addDependencySets(
"(create_mesh, set_global_params)"
"(setup_mesh)"
"(add_mesh_modifier, setup_mesh_complete)"
"(setup_executioner)"
"(add_function)"
"(setup_function_complete)"
"(add_aux_variable, add_variable)"
"(setup_variable_complete)"
"(setup_adaptivity)"
"(add_ic, add_periodic_bc)"
"(add_preconditioning)"
"(ready_to_init)"
"(setup_dampers)"
"(init_problem)"
"(copy_nodal_vars)"
"(add_material)"
"(add_postprocessor)"
"(setup_pps_complete)"
"(add_aux_bc, add_aux_kernel, add_bc, add_damper, add_dirac_kernel, add_kernel, add_stabilizer, setup_output)"
"(check_integrity)"
);
}
void
registerActions()
{
registerAction(CreateMeshAction, "Mesh/Generation", "create_mesh");
registerAction(SetupMeshAction, "Mesh", "setup_mesh");
registerAction(AddFunctionAction, "Functions/*", "add_function");
registerAction(CreateExecutionerAction, "Executioner", "setup_executioner");
registerAction(SetupOutputAction, "Output", "setup_output");
registerAction(GlobalParamsAction, "GlobalParams", "set_global_params");
/// MooseObjectActions
registerAction(AddMeshModifierAction, "Mesh/*", "add_mesh_modifier");
registerAction(AddVariableAction, "Variables/*", "add_variable");
registerAction(AddVariableAction, "AuxVariables/*", "add_aux_variable");
registerAction(AddICAction, "Variables/*/InitialCondition", "add_ic");
registerAction(AddICAction, "AuxVariables/*/InitialCondition", "add_ic");
registerAction(AddKernelAction, "Kernels/*", "add_kernel");
registerAction(AddKernelAction, "AuxKernels/*", "add_aux_kernel");
registerAction(AddBCAction, "BCs/*", "add_bc");
registerAction(EmptyAction, "BCs/Periodic", "no_action"); // placeholder
registerAction(AddPeriodicBCAction, "BCs/Periodic/*", "add_periodic_bc");
registerAction(AddBCAction, "AuxBCs/*", "add_aux_bc");
registerAction(AddMaterialAction, "Materials/*", "add_material");
registerAction(AddPostprocessorAction, "Postprocessors/*", "add_postprocessor");
registerAction(EmptyAction, "Postprocessors/Residual", "no_action"); // placeholder
registerAction(EmptyAction, "Postprocessors/Jacobian", "no_action"); // placeholder
registerAction(EmptyAction, "Postprocessors/NewtonIter", "no_action"); // placeholder
registerAction(AddPostprocessorAction, "Postprocessors/Residual/*", "add_postprocessor");
registerAction(AddPostprocessorAction, "Postprocessors/Jacobian/*", "add_postprocessor");
registerAction(AddPostprocessorAction, "Postprocessors/NewtonIter/*", "add_postprocessor");
registerAction(AddDamperAction, "Dampers/*", "add_damper");
registerAction(AddStabilizerAction, "Stabilizers/*", "add_stabilizer");
registerAction(SetupPBPAction, "Preconditioning/PBP", "add_preconditioning");
registerAction(AdaptivityAction, "Executioner/Adaptivity", "setup_adaptivity");
registerAction(AddDiracKernelAction, "DiracKernels/*", "add_dirac_kernel");
// NonParsedActions
registerNonParsedAction(SetupDampersAction, "setup_dampers");
registerNonParsedAction(InitProblemAction, "init_problem");
registerNonParsedAction(CopyNodalVarsAction, "copy_nodal_vars");
registerNonParsedAction(CheckIntegrityAction, "check_integrity");
}
void
setSolverDefaults(MProblem & problem)
{
#ifdef LIBMESH_HAVE_PETSC
Moose::PetscSupport::petscSetDefaults(problem);
#endif //LIBMESH_HAVE_PETSC
}
ActionWarehouse action_warehouse;
} // namespace Moose
<commit_msg>Some objects were not registered<commit_after>#include "Moose.h"
#include "Factory.h"
#include "NonlinearSystem.h"
#include "PetscSupport.h"
#include "ActionWarehouse.h"
#include "ActionFactory.h"
// objects that can be created by MOOSE
#include "TimeDerivative.h"
#include "Diffusion.h"
#include "CoupledForce.h"
#include "UserForcingFunction.h"
#include "BodyForce.h"
#include "ImplicitEuler.h"
#include "Reaction.h"
#include "RealPropertyOutput.h"
// bcs
#include "ConvectiveFluxBC.h"
#include "DirichletBC.h"
#include "NeumannBC.h"
#include "FunctionDirichletBC.h"
#include "FunctionNeumannBC.h"
#include "MatchedValueBC.h"
#include "VacuumBC.h"
// auxkernels
#include "CoupledAux.h"
#include "ConstantAux.h"
#include "FunctionAux.h"
#include "NearestNodeDistanceAux.h"
#include "NearestNodeValueAux.h"
#include "PenetrationAux.h"
#include "ProcessorIDAux.h"
#include "GapValueAux.h"
// dirac kernels
#include "ConstantPointSource.h"
// ics
#include "ConstantIC.h"
#include "BoundingBoxIC.h"
#include "FunctionIC.h"
#include "RandomIC.h"
// mesh modifiers
#include "ElementDeleter.h"
// executioners
#include "Steady.h"
#include "Transient.h"
#include "LooseCoupling.h"
#include "SolutionTimeAdaptive.h"
// functions
#include "ParsedFunction.h"
#include "ParsedGradFunction.h"
#include "PiecewiseLinear.h"
#include "SolutionFunction.h"
#include "SphereFunction.h"
// materials
#include "GenericConstantMaterial.h"
// PPS
#include "AverageElementSize.h"
#include "AverageNodalVariableValue.h"
#include "ElementAverageValue.h"
#include "ElementH1Error.h"
#include "ElementH1SemiError.h"
#include "ElementIntegral.h"
#include "ElementL2Error.h"
#include "EmptyPostprocessor.h"
#include "NodalVariableValue.h"
#include "PrintDOFs.h"
#include "PrintDT.h"
#include "PrintNumElems.h"
#include "PrintNumNodes.h"
#include "Reporter.h"
#include "SideAverageValue.h"
#include "SideFluxIntegral.h"
#include "SideIntegral.h"
// stabilizers
#include "ConvectionDiffusionSUPG.h"
// dampers
#include "ConstantDamper.h"
#include "MaxIncrement.h"
// Actions
#include "AddMeshModifierAction.h"
#include "AddBCAction.h"
#include "AddDiracKernelAction.h"
#include "AddICAction.h"
#include "AddKernelAction.h"
#include "AddPeriodicBCAction.h"
#include "AddVariableAction.h"
#include "AddPostprocessorAction.h"
#include "AddDamperAction.h"
#include "AddStabilizerAction.h"
#include "AddFunctionAction.h"
#include "CreateExecutionerAction.h"
#include "CreateMeshAction.h"
#include "EmptyAction.h"
#include "InitProblemAction.h"
#include "CopyNodalVarsAction.h"
#include "SetupMeshAction.h"
#include "SetupOutputAction.h"
#include "AddMaterialAction.h"
#include "GlobalParamsAction.h"
#include "SetupPBPAction.h"
#include "AdaptivityAction.h"
#include "SetupDampersAction.h"
#include "CheckIntegrityAction.h"
namespace Moose {
static bool registered = false;
void
registerObjects()
{
if (registered)
return;
registerObject(TimeDerivative);
// kernels
registerObject(Diffusion);
registerObject(CoupledForce);
registerObject(UserForcingFunction);
registerObject(BodyForce);
registerObject(ImplicitEuler);
registerObject(Reaction);
registerObject(RealPropertyOutput);
// bcs
registerObject(ConvectiveFluxBC);
registerObject(DirichletBC);
registerObject(NeumannBC);
registerObject(FunctionDirichletBC);
registerObject(FunctionNeumannBC);
registerObject(MatchedValueBC);
registerObject(VacuumBC);
// dirac kernels
registerObject(ConstantPointSource);
// aux kernels
registerObject(CoupledAux);
registerObject(ConstantAux);
registerObject(FunctionAux);
registerObject(NearestNodeDistanceAux);
registerObject(NearestNodeValueAux);
registerObject(PenetrationAux);
registerObject(ProcessorIDAux);
registerObject(GapValueAux);
// Initial Conditions
registerObject(ConstantIC);
registerObject(BoundingBoxIC);
registerObject(FunctionIC);
registerObject(RandomIC);
// Mesh Modifiers
registerObject(ElementDeleter);
// executioners
registerObject(Steady);
registerObject(Transient);
registerObject(LooseCoupling);
registerObject(SolutionTimeAdaptive);
// functions
registerObject(ParsedFunction);
registerObject(ParsedGradFunction);
registerObject(PiecewiseLinear);
registerObject(SolutionFunction);
registerObject(SphereFunction);
// materials
registerObject(GenericConstantMaterial);
// PPS
registerObject(AverageElementSize);
registerObject(AverageNodalVariableValue);
registerObject(ElementAverageValue);
registerObject(ElementH1Error);
registerObject(ElementH1SemiError);
registerObject(ElementIntegral);
registerObject(ElementL2Error);
registerObject(EmptyPostprocessor);
registerObject(NodalVariableValue);
registerObject(PrintDOFs);
registerObject(PrintDT);
registerObject(PrintNumElems);
registerObject(PrintNumNodes);
registerObject(Reporter);
registerObject(SideAverageValue);
registerObject(SideFluxIntegral);
registerObject(SideIntegral);
// stabilizers
registerObject(ConvectionDiffusionSUPG);
// dampers
registerObject(ConstantDamper);
registerObject(MaxIncrement);
addActionTypes();
registerActions();
registered = true;
}
void
addActionTypes()
{
/**************************/
/**** Register Actions ****/
/**************************/
/// Minimal Problem
registerActionName("setup_mesh", true);
registerActionName("add_variable", true);
registerActionName("add_kernel", true);
registerActionName("setup_executioner", true);
registerActionName("setup_output", true);
registerActionName("init_problem", true);
registerActionName("copy_nodal_vars", true);
registerActionName("add_bc", false); // Does this need to be true? Not if you have periodic boundaries...
registerActionName("setup_dampers", true);
registerActionName("check_integrity", true);
/// Additional Actions
registerActionName("no_action", false); // Used for Empty Action placeholders
registerActionName("set_global_params", false);
registerActionName("create_mesh", false);
registerActionName("add_mesh_modifier", false);
registerActionName("add_material", false);
registerActionName("add_function", false);
registerActionName("add_aux_variable", false);
registerActionName("add_aux_kernel", false);
registerActionName("add_aux_bc", false);
registerActionName("add_dirac_kernel", false);
registerActionName("add_ic", false);
registerActionName("add_postprocessor", false);
registerActionName("add_damper", false);
registerActionName("add_stabilizer", false);
registerActionName("add_periodic_bc", false);
registerActionName("add_preconditioning", false);
registerActionName("setup_adaptivity", false);
// Dummy Actions (useful for sync points in the dependencies)
registerActionName("setup_mesh_complete", false);
registerActionName("setup_function_complete", false);
registerActionName("setup_variable_complete", false);
registerActionName("ready_to_init", false);
registerActionName("setup_pps_complete", false);
/**************************/
/****** Dependencies ******/
/**************************/
/*
/// Mesh Actions
action_warehouse.addDependency("setup_mesh", "create_mesh");
action_warehouse.addDependency("add_mesh_modifier", "setup_mesh");
action_warehouse.addDependency("setup_mesh_complete", "setup_mesh");
/// Executioner
action_warehouse.addDependency("setup_executioner", "setup_mesh_complete");
action_warehouse.addDependency("setup_adaptivity", "setup_executioner");
/// Functions
action_warehouse.addDependency("add_function", "setup_adaptivity");
action_warehouse.addDependency("setup_function_complete", "add_function");
/// Variable Actions
action_warehouse.addDependency("add_variable", "setup_function_complete");
/// AuxVariable Actions
action_warehouse.addDependency("add_aux_variable", "setup_function_complete");
action_warehouse.addDependency("setup_variable_complete", "add_aux_variable");
/// ICs
action_warehouse.addDependency("add_ic", "setup_variable_complete");
/// PeriodicBCs
action_warehouse.addDependency("add_periodic_bc", "setup_variable_complete");
/// Preconditioning
action_warehouse.addDependency("add_preconditioning", "add_periodic_bc");
action_warehouse.addDependency("ready_to_init", "add_preconditioning");
/// InitProblem
action_warehouse.addDependency("setup_dampers", "ready_to_init");
action_warehouse.addDependency("init_problem", "setup_dampers");
action_warehouse.addDependency("copy_nodal_vars", "init_problem");
/// Materials
action_warehouse.addDependency("add_material", "copy_nodal_vars");
/// Postprocessors
action_warehouse.addDependency("add_postprocessor", "add_material");
action_warehouse.addDependency("setup_pps_complete", "add_postprocessor");
/// Dampers
action_warehouse.addDependency("add_damper", "setup_pps_complete");
/// Stabilizers
action_warehouse.addDependency("add_stabilizer", "setup_pps_complete");
/// Kernels
action_warehouse.addDependency("add_kernel", "setup_pps_complete");
/// AuxKernels
action_warehouse.addDependency("add_aux_kernel", "setup_pps_complete");
/// BCs
action_warehouse.addDependency("add_bc", "setup_pps_complete");
/// AuxBCs
action_warehouse.addDependency("add_aux_bc", "setup_pps_complete");
/// Dirac Kernels
action_warehouse.addDependency("add_dirac_kernel", "setup_pps_complete");
/// Ouput
action_warehouse.addDependency("setup_output", "setup_pps_complete");
/// Check Integrity
action_warehouse.addDependency("check_integrity", "setup_output");
*/
/**
* The following is the default set of action dependencies for a basic MOOSE problem. The formatting
* of this string is important. Each line represents a set of dependencies that depend on the previous
* line. Items on the same line have equal weight and can be executed in any order. */
action_warehouse.addDependencySets(
"(create_mesh, set_global_params)"
"(setup_mesh)"
"(add_mesh_modifier, setup_mesh_complete)"
"(setup_executioner)"
"(add_function)"
"(setup_function_complete)"
"(add_aux_variable, add_variable)"
"(setup_variable_complete)"
"(setup_adaptivity)"
"(add_ic, add_periodic_bc)"
"(add_preconditioning)"
"(ready_to_init)"
"(setup_dampers)"
"(init_problem)"
"(copy_nodal_vars)"
"(add_material)"
"(add_postprocessor)"
"(setup_pps_complete)"
"(add_aux_bc, add_aux_kernel, add_bc, add_damper, add_dirac_kernel, add_kernel, add_stabilizer, setup_output)"
"(check_integrity)"
);
}
void
registerActions()
{
registerAction(CreateMeshAction, "Mesh/Generation", "create_mesh");
registerAction(SetupMeshAction, "Mesh", "setup_mesh");
registerAction(AddFunctionAction, "Functions/*", "add_function");
registerAction(CreateExecutionerAction, "Executioner", "setup_executioner");
registerAction(SetupOutputAction, "Output", "setup_output");
registerAction(GlobalParamsAction, "GlobalParams", "set_global_params");
/// MooseObjectActions
registerAction(AddMeshModifierAction, "Mesh/*", "add_mesh_modifier");
registerAction(AddVariableAction, "Variables/*", "add_variable");
registerAction(AddVariableAction, "AuxVariables/*", "add_aux_variable");
registerAction(AddICAction, "Variables/*/InitialCondition", "add_ic");
registerAction(AddICAction, "AuxVariables/*/InitialCondition", "add_ic");
registerAction(AddKernelAction, "Kernels/*", "add_kernel");
registerAction(AddKernelAction, "AuxKernels/*", "add_aux_kernel");
registerAction(AddBCAction, "BCs/*", "add_bc");
registerAction(EmptyAction, "BCs/Periodic", "no_action"); // placeholder
registerAction(AddPeriodicBCAction, "BCs/Periodic/*", "add_periodic_bc");
registerAction(AddBCAction, "AuxBCs/*", "add_aux_bc");
registerAction(AddMaterialAction, "Materials/*", "add_material");
registerAction(AddPostprocessorAction, "Postprocessors/*", "add_postprocessor");
registerAction(EmptyAction, "Postprocessors/Residual", "no_action"); // placeholder
registerAction(EmptyAction, "Postprocessors/Jacobian", "no_action"); // placeholder
registerAction(EmptyAction, "Postprocessors/NewtonIter", "no_action"); // placeholder
registerAction(AddPostprocessorAction, "Postprocessors/Residual/*", "add_postprocessor");
registerAction(AddPostprocessorAction, "Postprocessors/Jacobian/*", "add_postprocessor");
registerAction(AddPostprocessorAction, "Postprocessors/NewtonIter/*", "add_postprocessor");
registerAction(AddDamperAction, "Dampers/*", "add_damper");
registerAction(AddStabilizerAction, "Stabilizers/*", "add_stabilizer");
registerAction(SetupPBPAction, "Preconditioning/PBP", "add_preconditioning");
registerAction(AdaptivityAction, "Executioner/Adaptivity", "setup_adaptivity");
registerAction(AddDiracKernelAction, "DiracKernels/*", "add_dirac_kernel");
// NonParsedActions
registerNonParsedAction(SetupDampersAction, "setup_dampers");
registerNonParsedAction(InitProblemAction, "init_problem");
registerNonParsedAction(CopyNodalVarsAction, "copy_nodal_vars");
registerNonParsedAction(CheckIntegrityAction, "check_integrity");
}
void
setSolverDefaults(MProblem & problem)
{
#ifdef LIBMESH_HAVE_PETSC
Moose::PetscSupport::petscSetDefaults(problem);
#endif //LIBMESH_HAVE_PETSC
}
ActionWarehouse action_warehouse;
} // namespace Moose
<|endoftext|>
|
<commit_before>#include "Platform.hpp"
#include <cmath>
#include "util/Log.hpp"
using Diggler::Util::Log;
using namespace Diggler::Util::Logging::LogLevels;
static const char *TAG = "Platform";
const char *Diggler::UserdataDirsName = "Diggler";
static struct PathCache {
std::string
executableBin,
executableDir,
configDir,
cacheDir;
} pathCache;
#if defined(BUILDINFO_PLATFORM_WINDOWS) // Windows
#include <cmath>
#include <cstring>
#include <shlobj.h>
#include <windows.h>
#include "platform/Fixes.hpp"
std::string Diggler::proc::getExecutablePath() {
if (pathCache.executableBin.length() == 0) {
HMODULE hModule = GetModuleHandleW(NULL);
WCHAR path[MAX_PATH];
GetModuleFileNameW(hModule, path, MAX_PATH);
char utf8Path[MAX_PATH];
WideCharToMultiByte(CP_UTF8, 0, path, -1, utf8Path, MAX_PATH, nullptr, nullptr);
pathCache.executableBin = utf8Path;
}
return pathCache.executableBin;
}
std::string Diggler::proc::getExecutableDirectory() {
if (pathCache.executableDir.length() == 0) {
std::string filename(getExecutablePath());
const size_t last_sep_idx = std::max(filename.rfind('/'), filename.rfind('\\'));
if (last_sep_idx != std::string::npos) {
pathCache.executableDir = filename.substr(0, last_sep_idx);
} else {
Log(Warning, TAG) << "Ill-formed executable path: " << filename;
pathCache.executableDir = filename;
}
}
return pathCache.executableDir;
}
std::string Diggler::getCacheDirectory() {
if (pathCache.cacheDir.length() == 0) {
WCHAR ucs2Path[MAX_PATH];
SHGetFolderPath(nullptr, CSIDL_APPDATA, nullptr, 0, ucs2Path);
char utf8Path[MAX_PATH];
WideCharToMultiByte(CP_UTF8, 0, ucs2Path, -1, utf8Path, MAX_PATH, nullptr, nullptr);
pathCache.cacheDir = std::string(utf8Path) + "/" + UserdataDirsName + "/cache/";
}
return pathCache.cacheDir;
}
std::string Diggler::getConfigDirectory() {
if (pathCache.cacheDir.length() == 0) {
WCHAR ucs2Path[MAX_PATH];
SHGetFolderPath(nullptr, CSIDL_APPDATA, nullptr, 0, ucs2Path);
char utf8Path[MAX_PATH];
WideCharToMultiByte(CP_UTF8, 0, ucs2Path, -1, utf8Path, MAX_PATH, nullptr, nullptr);
pathCache.configDir = std::string(utf8Path) + "/" + UserdataDirsName + "/config/";
}
return pathCache.configDir;
}
#elif defined(BUILDINFO_PLATFORM_UNIXLIKE) // Linux and UNIX alike
#include <sstream>
#include <unistd.h>
#include <dirent.h>
#include <cstdio>
std::string do_readlink(const char *path);
std::string do_readlink(const std::string &path);
#if defined(BUILDINFO_PLATFORM_LINUX)
std::string Diggler::proc::getExecutablePath() {
if (pathCache.executableBin.length() == 0) {
pid_t pid = getpid();
// Assuming 32-bit pid -> max of 10 digits, we need only "/proc/xxxxxxxxxx/exe" space
char path[21];
std::snprintf(path, 21, "/proc/%d/exe", pid);
pathCache.executableBin = do_readlink(path);
}
return pathCache.executableBin;
}
#else
// TODO: getExecutablePath for those without procfs
#endif
std::string Diggler::proc::getExecutableDirectory() {
if (pathCache.executableDir.length() == 0) {
std::string filename(getExecutablePath());
const size_t last_slash_idx = filename.rfind('/');
if (last_slash_idx != std::string::npos) {
pathCache.executableDir = filename.substr(0, last_slash_idx);
} else {
Log(Warning, TAG) << "Ill-formed executable path: " << filename;
pathCache.executableDir = filename;
}
}
return pathCache.executableDir;
}
std::string Diggler::getCacheDirectory() {
if (pathCache.cacheDir.length() == 0) {
const char *xdgCache = std::getenv("XDG_CACHE_HOME");
if (xdgCache) {
pathCache.cacheDir = std::string(xdgCache) + "/" + UserdataDirsName;
} else {
pathCache.cacheDir = std::string(std::getenv("HOME")) + "/.cache/" + UserdataDirsName;
}
}
return pathCache.cacheDir;
}
std::string Diggler::getConfigDirectory() {
if (pathCache.configDir.length() == 0) {
const char *xdgCache = std::getenv("XDG_CONFIG_HOME");
if (xdgCache) {
pathCache.configDir = std::string(xdgCache) + "/" + UserdataDirsName;
} else {
pathCache.configDir = std::string(std::getenv("HOME")) + "/.config/" + UserdataDirsName;
}
}
return pathCache.configDir;
}
#elif defined(BUILDINFO_PLATFORM_MAC) // Mac
// Put Mac code here
#else // Any other
// Stub?
#endif
namespace Diggler {
std::string getAssetsDirectory() {
return proc::getExecutableDirectory() + "/assets";
}
std::string getAssetsDirectory(const std::string &type) {
return proc::getExecutableDirectory() + "/assets/" + type + '/';
}
std::string getAssetPath(const std::string &name) {
return proc::getExecutableDirectory() + "/assets/" + name;
}
std::string getAssetPath(const std::string &type, const std::string &name) {
return proc::getExecutableDirectory() + "/assets/" + type + '/' + name;
}
float rmod(float x, float y) {
float ret = fmod(x, y);
if (ret < 0)
return y+ret;
return ret;
}
double rmod(double x, double y) {
double ret = fmod(x, y);
if (ret < 0)
return y+ret;
return ret;
}
}
<commit_msg>Windows: fix Diggler::proc::getExecutableDirectory failing<commit_after>#include "Platform.hpp"
#include <cmath>
#include "util/Log.hpp"
using Diggler::Util::Log;
using namespace Diggler::Util::Logging::LogLevels;
static const char *TAG = "Platform";
const char *Diggler::UserdataDirsName = "Diggler";
static struct PathCache {
std::string
executableBin,
executableDir,
configDir,
cacheDir;
} pathCache;
#if defined(BUILDINFO_PLATFORM_WINDOWS) // Windows
#include <cmath>
#include <cstring>
#include <shlobj.h>
#include <windows.h>
#include "platform/Fixes.hpp"
std::string Diggler::proc::getExecutablePath() {
if (pathCache.executableBin.length() == 0) {
HMODULE hModule = GetModuleHandleW(NULL);
WCHAR path[MAX_PATH];
GetModuleFileNameW(hModule, path, MAX_PATH);
char utf8Path[MAX_PATH];
WideCharToMultiByte(CP_UTF8, 0, path, -1, utf8Path, MAX_PATH, nullptr, nullptr);
pathCache.executableBin = utf8Path;
}
return pathCache.executableBin;
}
std::string Diggler::proc::getExecutableDirectory() {
if (pathCache.executableDir.length() == 0) {
std::string filename(getExecutablePath());
const size_t last_sep_idx = filename.rfind('\\');
if (last_sep_idx != std::string::npos) {
pathCache.executableDir = filename.substr(0, last_sep_idx);
} else {
Log(Warning, TAG) << "Ill-formed executable path: " << filename;
pathCache.executableDir = filename;
}
}
return pathCache.executableDir;
}
std::string Diggler::getCacheDirectory() {
if (pathCache.cacheDir.length() == 0) {
WCHAR ucs2Path[MAX_PATH];
SHGetFolderPath(nullptr, CSIDL_APPDATA, nullptr, 0, ucs2Path);
char utf8Path[MAX_PATH];
WideCharToMultiByte(CP_UTF8, 0, ucs2Path, -1, utf8Path, MAX_PATH, nullptr, nullptr);
pathCache.cacheDir = std::string(utf8Path) + "/" + UserdataDirsName + "/cache/";
}
return pathCache.cacheDir;
}
std::string Diggler::getConfigDirectory() {
if (pathCache.cacheDir.length() == 0) {
WCHAR ucs2Path[MAX_PATH];
SHGetFolderPath(nullptr, CSIDL_APPDATA, nullptr, 0, ucs2Path);
char utf8Path[MAX_PATH];
WideCharToMultiByte(CP_UTF8, 0, ucs2Path, -1, utf8Path, MAX_PATH, nullptr, nullptr);
pathCache.configDir = std::string(utf8Path) + "/" + UserdataDirsName + "/config/";
}
return pathCache.configDir;
}
#elif defined(BUILDINFO_PLATFORM_UNIXLIKE) // Linux and UNIX alike
#include <sstream>
#include <unistd.h>
#include <dirent.h>
#include <cstdio>
std::string do_readlink(const char *path);
std::string do_readlink(const std::string &path);
#if defined(BUILDINFO_PLATFORM_LINUX)
std::string Diggler::proc::getExecutablePath() {
if (pathCache.executableBin.length() == 0) {
pid_t pid = getpid();
// Assuming 32-bit pid -> max of 10 digits, we need only "/proc/xxxxxxxxxx/exe" space
char path[21];
std::snprintf(path, 21, "/proc/%d/exe", pid);
pathCache.executableBin = do_readlink(path);
}
return pathCache.executableBin;
}
#else
// TODO: getExecutablePath for those without procfs
#endif
std::string Diggler::proc::getExecutableDirectory() {
if (pathCache.executableDir.length() == 0) {
std::string filename(getExecutablePath());
const size_t last_slash_idx = filename.rfind('/');
if (last_slash_idx != std::string::npos) {
pathCache.executableDir = filename.substr(0, last_slash_idx);
} else {
Log(Warning, TAG) << "Ill-formed executable path: " << filename;
pathCache.executableDir = filename;
}
}
return pathCache.executableDir;
}
std::string Diggler::getCacheDirectory() {
if (pathCache.cacheDir.length() == 0) {
const char *xdgCache = std::getenv("XDG_CACHE_HOME");
if (xdgCache) {
pathCache.cacheDir = std::string(xdgCache) + "/" + UserdataDirsName;
} else {
pathCache.cacheDir = std::string(std::getenv("HOME")) + "/.cache/" + UserdataDirsName;
}
}
return pathCache.cacheDir;
}
std::string Diggler::getConfigDirectory() {
if (pathCache.configDir.length() == 0) {
const char *xdgCache = std::getenv("XDG_CONFIG_HOME");
if (xdgCache) {
pathCache.configDir = std::string(xdgCache) + "/" + UserdataDirsName;
} else {
pathCache.configDir = std::string(std::getenv("HOME")) + "/.config/" + UserdataDirsName;
}
}
return pathCache.configDir;
}
#elif defined(BUILDINFO_PLATFORM_MAC) // Mac
// Put Mac code here
#else // Any other
// Stub?
#endif
namespace Diggler {
std::string getAssetsDirectory() {
return proc::getExecutableDirectory() + "/assets";
}
std::string getAssetsDirectory(const std::string &type) {
return proc::getExecutableDirectory() + "/assets/" + type + '/';
}
std::string getAssetPath(const std::string &name) {
return proc::getExecutableDirectory() + "/assets/" + name;
}
std::string getAssetPath(const std::string &type, const std::string &name) {
return proc::getExecutableDirectory() + "/assets/" + type + '/' + name;
}
float rmod(float x, float y) {
float ret = fmod(x, y);
if (ret < 0)
return y+ret;
return ret;
}
double rmod(double x, double y) {
double ret = fmod(x, y);
if (ret < 0)
return y+ret;
return ret;
}
}
<|endoftext|>
|
<commit_before>/**************************************************************************************/
/* */
/* Visualization Library */
/* http://www.visualizationlibrary.com */
/* */
/* Copyright (c) 2005-2010, Michele Bosi */
/* All rights reserved. */
/* */
/* Redistribution and use in source and binary forms, with or without modification, */
/* are permitted provided that the following conditions are met: */
/* */
/* - Redistributions of source code must retain the above copyright notice, this */
/* list of conditions and the following disclaimer. */
/* */
/* - Redistributions in binary form must reproduce the above copyright notice, this */
/* list of conditions and the following disclaimer in the documentation and/or */
/* other materials provided with the distribution. */
/* */
/* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND */
/* ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED */
/* WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE */
/* DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR */
/* ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES */
/* (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; */
/* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON */
/* ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT */
/* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS */
/* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */
/* */
/**************************************************************************************/
#ifndef Transform_INCLUDE_ONCE
#define Transform_INCLUDE_ONCE
#include <vl/vlnamespace.hpp>
#include <vl/Object.hpp>
#include <vl/Matrix4.hpp>
#include <vector>
namespace vl
{
class Camera;
//------------------------------------------------------------------------------
// Transform
//------------------------------------------------------------------------------
/** Implements a 4x4 matrix transform used to define the position and orientation of an Actor.
*
* Transforms can be linked together to create a tree-like hierarchy.
*
* \par Optimizing Your Transforms
*
* - Don't use them unless strictly necessary: if an Actor uses an I (identity) transform you do not need one, just call \p vl::Actor::setTransform(NULL).
*
* - Don't create Transform hierarchies if not needed. Just call setLocalAndWorldMatrix() per-Transform if you have a set of parent-less Transforms.
*
* - If the root of a hierarchy is an I (identity) transform, let VL know it by calling \p setAssumeIdentityWorldMatrix(true). This will save
* unnecessary matrix multiplications since multiplying by an identity matrix has no effect.
*
* - Call computeWorldMatrix() / computeWorldMatrixRecursive() not at each frame but only if the local matrix has actually changed.
*
* - Do not add a Transform hierarchy to vl::Rendering::transform() if such Transforms are not animated every frame,
* this will cause VL unnecessarily update the Transforms at each frame.
*
* - Remember: VL does not require your Actors to have a Transform or such Transforms to be part of any hierarchy, it just expect that the
* worldMatrix() of an Actor's Transform (if it has any) is up to date at rendering time. How and when they are updated can be fine
* tuned by the user according to the specific application needs.
*
* \sa setLocalAndWorldMatrix(), setAssumeIdentityWorldMatrix(), Rendering::transform()
* \sa Actor, Rendering, Effect, Renderable, Geometry */
class Transform: public Object
{
public:
virtual const char* className() { return "Transform"; }
/** Constructor. */
Transform(): mParent(NULL), mWorldMatrixUpdateTick(0), mAssumeIdentityWorldMatrix(false)
{
#ifndef NDEBUG
mObjectName = className();
#endif
}
/** Constructor. The \p matrix parameter is used to set both the local and world matrix. */
Transform(const mat4& matrix): mParent(NULL), mAssumeIdentityWorldMatrix(false)
{
setLocalMatrix(matrix);
setWorldMatrix(matrix);
#ifndef NDEBUG
mObjectName = className();
#endif
}
/** Returns the children Transforms. */
const std::vector< ref<Transform> >& children() const { return mChildren; }
/** Adds a child transform. */
void addChild(Transform* child);
/** Adds \p count children transforms. */
void addChildren(Transform* const *, size_t count);
/** Adds \p count children transforms. */
void addChildren(const ref<Transform>*, size_t count);
/** Adds the specified \p children transforms. */
void addChildren(const std::vector< Transform* >& children);
/** Adds the specified \p children transforms. */
void addChildren(const std::vector< ref<Transform> >& children);
/** Minimizes the amount of memory used to store the children Transforms. */
void shrink();
/** Minimizes recursively the amount of memory used to store the children Transforms. */
void shrinkRecursive();
/** Sets the \p index-th child. */
void setChild(int index, Transform* child);
/** Returns the number of children a Transform has. */
int childCount() const;
/** Returns the i-th child Transform. */
Transform* child(int i);
/** Returns the last child. */
Transform* lastChild();
/** Removes the given \p child Transform. */
void eraseChild(Transform* child);
/** Removes \p count children Transforms starting at position \p index. */
void eraseChildren(int index, int count);
/** Removes all the children of a Transform. */
void eraseAllChildren();
/** Removes all the children of a Transform recursively descending the hierachy. */
void eraseAllChildrenRecursive();
/** Returns the parent of a Transform. */
const Transform* parent() const { return mParent; }
/** Returns the parent of a Transform. */
Transform* parent() { return mParent; }
/** Returns the matrix computed concatenating this Transform's local matrix with its parents' local matrices. */
mat4 getComputedWorldMatrix();
/** Returns the local matrix. */
const mat4& localMatrix() const;
/** Sets the local matrix.
* After calling this you might want to call computeWorldMatrix() or computeWorldMatrixRecursive(). */
void setLocalMatrix(const mat4& matrix);
/** Utility function equivalent to \p setLocalMatrix( mat4::translation(x,y,z)*localMatrix() ).
* After calling this you might want to call computeWorldMatrix() or computeWorldMatrixRecursive(). */
void translate(Real x, Real y, Real z);
/** Utility function equivalent to \p setLocalMatrix( mat4::translation(t)*localMatrix() ).
* After calling this you might want to call computeWorldMatrix() or computeWorldMatrixRecursive(). */
void translate(const vec3& t);
/** Utility function equivalent to \p setLocalMatrix( mat4::scaling(x,y,z)*localMatrix() ).
* After calling this you might want to call computeWorldMatrix() or computeWorldMatrixRecursive(). */
void scale(Real x, Real y, Real z);
/** Utility function equivalent to \p setLocalMatrix( mat4::rotation(degrees,x,y,z)*localMatrix() ).
* After calling this you might want to call computeWorldMatrix() or computeWorldMatrixRecursive(). */
void rotate(Real degrees, Real x, Real y, Real z);
/** Utility function equivalent to \p setLocalMatrix( mat4::rotation(from,to)*localMatrix() ).
* After calling this you might want to call computeWorldMatrix() or computeWorldMatrixRecursive(). */
void rotate(const vec3& from, const vec3& to);
/** Sets both the local and the world matrices.
* This function is useful to quickly set those Transforms that do not have a parent, for which
* is equivalent to: \p setLocalMatrix(matrix); \p computeWorldMatrix(NULL); */
void setLocalAndWorldMatrix(const mat4& matrix)
{
mLocalMatrix = matrix;
setWorldMatrix(matrix);
}
/** Computes the world matrix by concatenating the parent's world matrix with this' local matrix. */
virtual void computeWorldMatrix(Camera* camera=NULL);
/** Computes the world matrix by concatenating the parent's world matrix with this' local matrix, recursively descending to the children. */
void computeWorldMatrixRecursive(Camera* camera=NULL);
/** Returns the world matrix used for rendering. */
const mat4& worldMatrix() const;
/** Returns the internal update tick used to avoid unnecessary computations. The world matrix thick
* gets incremented every time the setWorldMatrix() or setLocalAndWorldMatrix() functions are called. */
long long worldMatrixUpdateTick() const { return mWorldMatrixUpdateTick; }
/** If set to true the world matrix of this transform will always be considered and identity.
* Is usually used to save calculations for top Transforms with many sub-Transforms. */
void setAssumeIdentityWorldMatrix(bool assume_I) { mAssumeIdentityWorldMatrix = assume_I; }
/** If set to true the world matrix of this transform will always be considered and identity.
* Is usually used to save calculations for top Transforms with many sub-Transforms. */
bool assumeIdentityWorldMatrix() { return mAssumeIdentityWorldMatrix; }
/** Checks whether there are duplicated entries in the Transform's children list. */
bool hasDuplicatedChildren() const;
/** Normally you should not use directly this function, call it only if you are sure you cannot do otherwise.
* Calling this function will also increment the worldMatrixUpdateTick(). */
void setWorldMatrix(const mat4& matrix);
protected:
mat4 mWorldMatrix;
mat4 mLocalMatrix;
std::vector< ref<Transform> > mChildren;
Transform* mParent;
long long mWorldMatrixUpdateTick;
bool mAssumeIdentityWorldMatrix;
};
}
#endif
<commit_msg>added Transform::reserveChildren() function.<commit_after>/**************************************************************************************/
/* */
/* Visualization Library */
/* http://www.visualizationlibrary.com */
/* */
/* Copyright (c) 2005-2010, Michele Bosi */
/* All rights reserved. */
/* */
/* Redistribution and use in source and binary forms, with or without modification, */
/* are permitted provided that the following conditions are met: */
/* */
/* - Redistributions of source code must retain the above copyright notice, this */
/* list of conditions and the following disclaimer. */
/* */
/* - Redistributions in binary form must reproduce the above copyright notice, this */
/* list of conditions and the following disclaimer in the documentation and/or */
/* other materials provided with the distribution. */
/* */
/* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND */
/* ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED */
/* WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE */
/* DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR */
/* ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES */
/* (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; */
/* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON */
/* ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT */
/* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS */
/* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */
/* */
/**************************************************************************************/
#ifndef Transform_INCLUDE_ONCE
#define Transform_INCLUDE_ONCE
#include <vl/vlnamespace.hpp>
#include <vl/Object.hpp>
#include <vl/Matrix4.hpp>
#include <vector>
namespace vl
{
class Camera;
//------------------------------------------------------------------------------
// Transform
//------------------------------------------------------------------------------
/** Implements a 4x4 matrix transform used to define the position and orientation of an Actor.
*
* Transforms can be linked together to create a tree-like hierarchy.
*
* \par Optimizing Your Transforms
*
* - Don't use them unless strictly necessary: if an Actor uses an I (identity) transform you do not need one, just call \p vl::Actor::setTransform(NULL).
*
* - Don't create Transform hierarchies if not needed. Just call setLocalAndWorldMatrix() per-Transform if you have a set of parent-less Transforms.
*
* - If the root of a hierarchy is an I (identity) transform, let VL know it by calling \p setAssumeIdentityWorldMatrix(true). This will save
* unnecessary matrix multiplications since multiplying by an identity matrix has no effect.
*
* - Call computeWorldMatrix() / computeWorldMatrixRecursive() not at each frame but only if the local matrix has actually changed.
*
* - Do not add a Transform hierarchy to vl::Rendering::transform() if such Transforms are not animated every frame,
* this will cause VL unnecessarily update the Transforms at each frame.
*
* - Remember: VL does not require your Actors to have a Transform or such Transforms to be part of any hierarchy, it just expect that the
* worldMatrix() of an Actor's Transform (if it has any) is up to date at rendering time. How and when they are updated can be fine
* tuned by the user according to the specific application needs.
*
* \sa setLocalAndWorldMatrix(), setAssumeIdentityWorldMatrix(), Rendering::transform()
* \sa Actor, Rendering, Effect, Renderable, Geometry */
class Transform: public Object
{
public:
virtual const char* className() { return "Transform"; }
/** Constructor. */
Transform(): mParent(NULL), mWorldMatrixUpdateTick(0), mAssumeIdentityWorldMatrix(false)
{
#ifndef NDEBUG
mObjectName = className();
#endif
}
/** Constructor. The \p matrix parameter is used to set both the local and world matrix. */
Transform(const mat4& matrix): mParent(NULL), mAssumeIdentityWorldMatrix(false)
{
setLocalMatrix(matrix);
setWorldMatrix(matrix);
#ifndef NDEBUG
mObjectName = className();
#endif
}
/** Returns the children Transforms. */
const std::vector< ref<Transform> >& children() const { return mChildren; }
/** Adds a child transform. */
void addChild(Transform* child);
/** Adds \p count children transforms. */
void addChildren(Transform* const *, size_t count);
/** Adds \p count children transforms. */
void addChildren(const ref<Transform>*, size_t count);
/** Adds the specified \p children transforms. */
void addChildren(const std::vector< Transform* >& children);
/** Adds the specified \p children transforms. */
void addChildren(const std::vector< ref<Transform> >& children);
/** Minimizes the amount of memory used to store the children Transforms. */
void shrink();
/** Minimizes recursively the amount of memory used to store the children Transforms. */
void shrinkRecursive();
/** Reserves space for \p count children. This function is very useful when you need to add one by one a large number of children transforms.
* \note This function does not affect the number of children, it only reallocates the buffer used to store them
* so that it's large enough to \p eventually contain \p count of them. This will make subsequent calls to addChild() quicker
* as fewer or no reallocations of the buffer will be needed. */
void reserveChildren(size_t count) { mChildren.reserve(count); }
/** Sets the \p index-th child. */
void setChild(int index, Transform* child);
/** Returns the number of children a Transform has. */
int childCount() const;
/** Returns the i-th child Transform. */
Transform* child(int i);
/** Returns the last child. */
Transform* lastChild();
/** Removes the given \p child Transform. */
void eraseChild(Transform* child);
/** Removes \p count children Transforms starting at position \p index. */
void eraseChildren(int index, int count);
/** Removes all the children of a Transform. */
void eraseAllChildren();
/** Removes all the children of a Transform recursively descending the hierachy. */
void eraseAllChildrenRecursive();
/** Returns the parent of a Transform. */
const Transform* parent() const { return mParent; }
/** Returns the parent of a Transform. */
Transform* parent() { return mParent; }
/** Returns the matrix computed concatenating this Transform's local matrix with its parents' local matrices. */
mat4 getComputedWorldMatrix();
/** Returns the local matrix. */
const mat4& localMatrix() const;
/** Sets the local matrix.
* After calling this you might want to call computeWorldMatrix() or computeWorldMatrixRecursive(). */
void setLocalMatrix(const mat4& matrix);
/** Utility function equivalent to \p setLocalMatrix( mat4::translation(x,y,z)*localMatrix() ).
* After calling this you might want to call computeWorldMatrix() or computeWorldMatrixRecursive(). */
void translate(Real x, Real y, Real z);
/** Utility function equivalent to \p setLocalMatrix( mat4::translation(t)*localMatrix() ).
* After calling this you might want to call computeWorldMatrix() or computeWorldMatrixRecursive(). */
void translate(const vec3& t);
/** Utility function equivalent to \p setLocalMatrix( mat4::scaling(x,y,z)*localMatrix() ).
* After calling this you might want to call computeWorldMatrix() or computeWorldMatrixRecursive(). */
void scale(Real x, Real y, Real z);
/** Utility function equivalent to \p setLocalMatrix( mat4::rotation(degrees,x,y,z)*localMatrix() ).
* After calling this you might want to call computeWorldMatrix() or computeWorldMatrixRecursive(). */
void rotate(Real degrees, Real x, Real y, Real z);
/** Utility function equivalent to \p setLocalMatrix( mat4::rotation(from,to)*localMatrix() ).
* After calling this you might want to call computeWorldMatrix() or computeWorldMatrixRecursive(). */
void rotate(const vec3& from, const vec3& to);
/** Sets both the local and the world matrices.
* This function is useful to quickly set those Transforms that do not have a parent, for which
* is equivalent to: \p setLocalMatrix(matrix); \p computeWorldMatrix(NULL); */
void setLocalAndWorldMatrix(const mat4& matrix)
{
mLocalMatrix = matrix;
setWorldMatrix(matrix);
}
/** Computes the world matrix by concatenating the parent's world matrix with this' local matrix. */
virtual void computeWorldMatrix(Camera* camera=NULL);
/** Computes the world matrix by concatenating the parent's world matrix with this' local matrix, recursively descending to the children. */
void computeWorldMatrixRecursive(Camera* camera=NULL);
/** Returns the world matrix used for rendering. */
const mat4& worldMatrix() const;
/** Returns the internal update tick used to avoid unnecessary computations. The world matrix thick
* gets incremented every time the setWorldMatrix() or setLocalAndWorldMatrix() functions are called. */
long long worldMatrixUpdateTick() const { return mWorldMatrixUpdateTick; }
/** If set to true the world matrix of this transform will always be considered and identity.
* Is usually used to save calculations for top Transforms with many sub-Transforms. */
void setAssumeIdentityWorldMatrix(bool assume_I) { mAssumeIdentityWorldMatrix = assume_I; }
/** If set to true the world matrix of this transform will always be considered and identity.
* Is usually used to save calculations for top Transforms with many sub-Transforms. */
bool assumeIdentityWorldMatrix() { return mAssumeIdentityWorldMatrix; }
/** Checks whether there are duplicated entries in the Transform's children list. */
bool hasDuplicatedChildren() const;
/** Normally you should not use directly this function, call it only if you are sure you cannot do otherwise.
* Calling this function will also increment the worldMatrixUpdateTick(). */
void setWorldMatrix(const mat4& matrix);
protected:
mat4 mWorldMatrix;
mat4 mLocalMatrix;
std::vector< ref<Transform> > mChildren;
Transform* mParent;
long long mWorldMatrixUpdateTick;
bool mAssumeIdentityWorldMatrix;
};
}
#endif
<|endoftext|>
|
<commit_before>/**
* @brief This file is the execution node of the Human Tracking
* @copyright Copyright (2011) Willow Garage
* @authors Koen Buys, Anatoly Baksheev
**/
#include <pcl/pcl_base.h>
#include <pcl/point_types.h>
#include <pcl/point_cloud.h>
#include <pcl/common/time.h>
#include <pcl/console/parse.h>
#include <pcl/io/pcd_io.h>
#include <pcl/gpu/people/people_detector.h>
#include <pcl/visualization/image_viewer.h>
#include <boost/lexical_cast.hpp>
#include <pcl/io/png_io.h>
#include <iostream>
using namespace pcl::visualization;
using namespace pcl::console;
using namespace std;
///////////////////////////////////////////////////////////////////////////////////////////////////////////////////
class PeoplePCDApp
{
public:
typedef pcl::gpu::people::PeopleDetector PeopleDetector;
enum { COLS = 640, ROWS = 480 };
PeoplePCDApp () : counter_(0), cmap_device_(ROWS, COLS), final_view_("Final labeling")//, image_view_("Input image")
{
final_view_.setSize (COLS, ROWS);
//image_view_.setSize (COLS, ROWS);
final_view_.setPosition (0, 0);
//image_view_.setPosition (650, 0);
}
void cloud_cb (const pcl::PointCloud<pcl::PointXYZRGB>::ConstPtr &cloud)
{
people_detector_.process(cloud);
++counter_;
//visualizeAndWrite(cloud);
}
void
visualizeAndWrite(const pcl::PointCloud<pcl::PointXYZRGB>::ConstPtr &cloud)
{
const pcl::gpu::people::RDFBodyPartsDetector::Labels& labels = people_detector_.rdf_detector_->getLabels();
people_detector_.rdf_detector_->colorizeLabels(labels, cmap_device_);
int c;
pcl::PointCloud<pcl::RGB> cmap(cmap_device_.cols(), cmap_device_.rows());
cmap_device_.download(cmap.points, c);
final_view_.showRGBImage<pcl::RGB>(cmap);
final_view_.spinOnce(1, true);
//image_view_.showRGBImage<pcl::PointXYZRGB>(cloud);
//image_view_.spinOnce(1, true);
savePNGFile("ii_" + boost::lexical_cast<string>(counter_) + ".png", *cloud);
savePNGFile("c2_" + boost::lexical_cast<string>(counter_) + ".png", cmap);
savePNGFile("s2_" + boost::lexical_cast<string>(counter_) + ".png", labels);
savePNGFile("d_" + boost::lexical_cast<string>(counter_) + ".png", people_detector_.depth_device1_);
savePNGFile("d2_" + boost::lexical_cast<string>(counter_) + ".png", people_detector_.depth_device2_);
}
template<typename T>
void savePNGFile(const std::string& filename, const pcl::gpu::DeviceArray2D<T>& arr)
{
int c;
pcl::PointCloud<T> cloud(arr.cols(), arr.rows());
arr.download(cloud.points, c);
pcl::io::savePNGFile(filename, cloud);
}
template <typename T> void
savePNGFile (const std::string& filename, const pcl::PointCloud<T>& cloud)
{
pcl::io::savePNGFile(filename, cloud);
}
int counter_;
PeopleDetector people_detector_;
PeopleDetector::Image cmap_device_;
ImageViewer final_view_;
//ImageViewer image_view_;
};
void print_help()
{
cout << "\nPeople tracking app options:" << endl;
cout << "\t -numTrees \t<int> \tnumber of trees to load" << endl;
cout << "\t -tree0 \t<path_to_tree_file>" << endl;
cout << "\t -tree1 \t<path_to_tree_file>" << endl;
cout << "\t -tree2 \t<path_to_tree_file>" << endl;
cout << "\t -tree3 \t<path_to_tree_file>" << endl;
cout << "\t -pcd \t<path_to_pcd_file>" << endl;
}
int main(int argc, char** argv)
{
if(find_switch (argc, argv, "--help") || find_switch (argc, argv, "-h"))
return print_help(), 0;
std::string treeFilenames[4] =
{
"d:/TreeData/results/forest1/tree_20.txt",
"d:/TreeData/results/forest3/tree_20.txt",
"d:/TreeData/results/forest3/tree_20.txt",
"d:/TreeData/results/forest3/tree_20.txt"
};
int numTrees = 4;
parse_argument (argc, argv, "-numTrees", numTrees);
parse_argument (argc, argv, "-tree0", treeFilenames[0]);
parse_argument (argc, argv, "-tree1", treeFilenames[1]);
parse_argument (argc, argv, "-tree2", treeFilenames[2]);
parse_argument (argc, argv, "-tree3", treeFilenames[3]);
if (numTrees == 0 || numTrees > 4)
return cout << "Invalid number of trees" << endl, -1;
string pcdname = "d:/git/pcl/gpu/people/tools/test.pcd";
parse_argument (argc, argv, "-pcd", pcdname);
// loading cloud file
pcl::PointCloud<pcl::PointXYZRGB>::Ptr cloud (new pcl::PointCloud<pcl::PointXYZRGB>);
int res = pcl::io::loadPCDFile<pcl::PointXYZRGB> (pcdname, *cloud);
if (res == -1) //* load the file
return cout << "Couldn't read tree file" << endl, -1;
cout << "Loaded " << cloud->width * cloud->height << " data points from " << pcdname << endl;
// loading trees
using pcl::gpu::people::RDFBodyPartsDetector;
vector<string> names_vector(treeFilenames, treeFilenames + numTrees);
RDFBodyPartsDetector::Ptr rdf(new RDFBodyPartsDetector(names_vector));
// Create the app
PeoplePCDApp app;
app.people_detector_.rdf_detector_ = rdf;
/// Run the app
{
pcl::ScopeTime frame_time("frame_time");
app.cloud_cb(cloud);
}
app.visualizeAndWrite(cloud);
app.final_view_.spin();
return 0;
}
<commit_msg>compilation<commit_after>/**
* @brief This file is the execution node of the Human Tracking
* @copyright Copyright (2011) Willow Garage
* @authors Koen Buys, Anatoly Baksheev
**/
#include <pcl/pcl_base.h>
#include <pcl/point_types.h>
#include <pcl/point_cloud.h>
#include <pcl/common/time.h>
#include <pcl/console/parse.h>
#include <pcl/io/pcd_io.h>
#include <pcl/gpu/people/people_detector.h>
#include <pcl/visualization/image_viewer.h>
#include <boost/lexical_cast.hpp>
#include <pcl/io/png_io.h>
#include <iostream>
using namespace pcl::visualization;
using namespace pcl::console;
using namespace std;
///////////////////////////////////////////////////////////////////////////////////////////////////////////////////
class PeoplePCDApp
{
public:
typedef pcl::gpu::people::PeopleDetector PeopleDetector;
enum { COLS = 640, ROWS = 480 };
PeoplePCDApp () : counter_(0), cmap_device_(ROWS, COLS), final_view_("Final labeling")//, image_view_("Input image")
{
final_view_.setSize (COLS, ROWS);
//image_view_.setSize (COLS, ROWS);
final_view_.setPosition (0, 0);
//image_view_.setPosition (650, 0);
}
void cloud_cb (const pcl::PointCloud<pcl::PointXYZRGB>::ConstPtr &cloud)
{
people_detector_.process(cloud);
++counter_;
//visualizeAndWrite(cloud);
}
void
visualizeAndWrite(const pcl::PointCloud<pcl::PointXYZRGB>::ConstPtr &cloud)
{
const pcl::gpu::people::RDFBodyPartsDetector::Labels& labels = people_detector_.rdf_detector_->getLabels();
people_detector_.rdf_detector_->colorizeLabels(labels, cmap_device_);
int c;
pcl::PointCloud<pcl::RGB> cmap(cmap_device_.cols(), cmap_device_.rows());
cmap_device_.download(cmap.points, c);
final_view_.showRGBImage<pcl::RGB>(cmap);
final_view_.spinOnce(1, true);
//image_view_.showRGBImage<pcl::PointXYZRGB>(cloud);
//image_view_.spinOnce(1, true);
savePNGFile("ii_" + boost::lexical_cast<string>(counter_) + ".png", *cloud);
savePNGFile("c2_" + boost::lexical_cast<string>(counter_) + ".png", cmap);
savePNGFile("s2_" + boost::lexical_cast<string>(counter_) + ".png", labels);
savePNGFile("d_" + boost::lexical_cast<string>(counter_) + ".png", people_detector_.depth_device_);
savePNGFile("d2_" + boost::lexical_cast<string>(counter_) + ".png", people_detector_.depth_device2_);
}
template<typename T>
void savePNGFile(const std::string& filename, const pcl::gpu::DeviceArray2D<T>& arr)
{
int c;
pcl::PointCloud<T> cloud(arr.cols(), arr.rows());
arr.download(cloud.points, c);
pcl::io::savePNGFile(filename, cloud);
}
template <typename T> void
savePNGFile (const std::string& filename, const pcl::PointCloud<T>& cloud)
{
pcl::io::savePNGFile(filename, cloud);
}
int counter_;
PeopleDetector people_detector_;
PeopleDetector::Image cmap_device_;
ImageViewer final_view_;
//ImageViewer image_view_;
};
void print_help()
{
cout << "\nPeople tracking app options:" << endl;
cout << "\t -numTrees \t<int> \tnumber of trees to load" << endl;
cout << "\t -tree0 \t<path_to_tree_file>" << endl;
cout << "\t -tree1 \t<path_to_tree_file>" << endl;
cout << "\t -tree2 \t<path_to_tree_file>" << endl;
cout << "\t -tree3 \t<path_to_tree_file>" << endl;
cout << "\t -pcd \t<path_to_pcd_file>" << endl;
}
int main(int argc, char** argv)
{
if(find_switch (argc, argv, "--help") || find_switch (argc, argv, "-h"))
return print_help(), 0;
std::string treeFilenames[4] =
{
"d:/TreeData/results/forest1/tree_20.txt",
"d:/TreeData/results/forest3/tree_20.txt",
"d:/TreeData/results/forest3/tree_20.txt",
"d:/TreeData/results/forest3/tree_20.txt"
};
int numTrees = 4;
parse_argument (argc, argv, "-numTrees", numTrees);
parse_argument (argc, argv, "-tree0", treeFilenames[0]);
parse_argument (argc, argv, "-tree1", treeFilenames[1]);
parse_argument (argc, argv, "-tree2", treeFilenames[2]);
parse_argument (argc, argv, "-tree3", treeFilenames[3]);
if (numTrees == 0 || numTrees > 4)
return cout << "Invalid number of trees" << endl, -1;
string pcdname = "d:/git/pcl/gpu/people/tools/test.pcd";
parse_argument (argc, argv, "-pcd", pcdname);
// loading cloud file
pcl::PointCloud<pcl::PointXYZRGB>::Ptr cloud (new pcl::PointCloud<pcl::PointXYZRGB>);
int res = pcl::io::loadPCDFile<pcl::PointXYZRGB> (pcdname, *cloud);
if (res == -1) //* load the file
return cout << "Couldn't read tree file" << endl, -1;
cout << "Loaded " << cloud->width * cloud->height << " data points from " << pcdname << endl;
// loading trees
using pcl::gpu::people::RDFBodyPartsDetector;
vector<string> names_vector(treeFilenames, treeFilenames + numTrees);
RDFBodyPartsDetector::Ptr rdf(new RDFBodyPartsDetector(names_vector));
// Create the app
PeoplePCDApp app;
app.people_detector_.rdf_detector_ = rdf;
/// Run the app
{
pcl::ScopeTime frame_time("frame_time");
app.cloud_cb(cloud);
}
app.visualizeAndWrite(cloud);
app.final_view_.spin();
return 0;
}
<|endoftext|>
|
<commit_before>// Copyright (c) 2014 Robert Kooima
//
// 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 "OVR_SDL2_obj.hpp"
//------------------------------------------------------------------------------
const char *vert_src = R"(
#version 150
uniform mat4 ProjectionMatrix;
uniform mat4 ModelViewMatrix;
uniform mat3 NormalMatrix;
uniform vec4 LightPosition;
in vec4 vPosition;
in vec3 vNormal;
in vec2 vTexCoord;
out vec3 fView;
out vec3 fLight;
out vec3 fNormal;
out vec2 fTexCoord;
void main()
{
vec4 vLight = LightPosition - vPosition;
fView = vec3(ModelViewMatrix * vPosition);
fLight = vec3(ModelViewMatrix * vLight);
fNormal = vec3(NormalMatrix * vNormal);
fTexCoord = vTexCoord;
gl_Position = ProjectionMatrix * ModelViewMatrix * vPosition;
}
)";
const char *frag_src = R"(
#version 150
uniform vec4 AmbientLight;
uniform vec4 DiffuseColor;
uniform vec4 SpecularColor;
uniform sampler2D DiffuseTexture;
uniform sampler2D SpecularTexture;
in vec3 fView;
in vec3 fLight;
in vec3 fNormal;
in vec2 fTexCoord;
out vec4 fOutput;
void main()
{
// Sample the materials.
vec3 cD = texture(DiffuseTexture, fTexCoord).rgb + DiffuseColor.rgb;
vec3 cS = texture(SpecularTexture, fTexCoord).rgb + SpecularColor.rgb;
// Determine the per-fragment lighting vectors.
vec3 N = normalize(fNormal);
vec3 L = normalize(fLight);
vec3 V = normalize(fView);
float d = length(fView);
vec3 R = reflect(L, N);
// Compute the diffuse shading.
float kd = max(dot(L, N), 0.0);
float ks = pow(max(dot(V, R), 0.0), 8.0);
// Calculate the fragment color.
float f = clamp(4.0 / d, 0.0, 1.0);
fOutput = vec4((AmbientLight.rgb * cD + kd * cD + ks * cS) * f, 1.0);
}
)";
//------------------------------------------------------------------------------
OVR_SDL2_obj::OVR_SDL2_obj(int argc, char **argv) : program(0)
{
// Compile and link the shaders.
if ((program = init_program(init_shader(GL_VERTEX_SHADER, vert_src),
init_shader(GL_FRAGMENT_SHADER, frag_src))))
{
glUseProgram(program);
// Query the program uniform locations.
ProjectionMatrixLoc = glGetUniformLocation(program, "ProjectionMatrix");
ModelViewMatrixLoc = glGetUniformLocation(program, "ModelViewMatrix");
NormalMatrixLoc = glGetUniformLocation(program, "NormalMatrix");
LightPositionLoc = glGetUniformLocation(program, "LightPosition");
AmbientLightLoc = glGetUniformLocation(program, "AmbientLight");
DiffuseColorLoc = glGetUniformLocation(program, "DiffuseColor");
SpecularColorLoc = glGetUniformLocation(program, "SpecularColor");
DiffuseTextureLoc = glGetUniformLocation(program, "DiffuseTexture");
SpecularTextureLoc = glGetUniformLocation(program, "SpecularTexture");
// Query the vertex attribute locations.
vNormalLoc = glGetAttribLocation(program, "vNormal");
vTexCoordLoc = glGetAttribLocation(program, "vTexCoord");
vPositionLoc = glGetAttribLocation(program, "vPosition");
// Configure the scene.
init_objects(argc, argv);
init_background();
glUniform4f(AmbientLightLoc, 0.2, 0.2, 0.2, 1.0);
glUniform4f(LightPositionLoc, 0.0, 3.0, 3.0, 1.0);
glUseProgram(0);
}
// Set the necessary OpenGL state.
glEnable(GL_DEPTH_TEST);
}
OVR_SDL2_obj::~OVR_SDL2_obj()
{
for (auto i : objects)
obj_delete(i.first);
}
void OVR_SDL2_obj::draw()
{
glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
glUseProgram(program);
glUniformMatrix4fv(ProjectionMatrixLoc, 1, GL_TRUE, projection());
// Render all objects.
for (auto i : objects)
{
mat4 M = view() * translation(offset) * translation(i.second);
glUniformMatrix4fv(ModelViewMatrixLoc, 1, GL_TRUE, M);
glUniformMatrix3fv(NormalMatrixLoc, 1, GL_TRUE, normal(M));
obj_render(i.first);
}
// Unbind our state.
glBindVertexArray(0);
glUseProgram(0);
}
//------------------------------------------------------------------------------
/// Load a series of OBJ files named on the command line. Configure them for
/// rendering with the current program. Arrange theo bjects along the X axis,
/// center the scene on the origin, and move the camera to a reasonable
/// starting position.
void OVR_SDL2_obj::init_objects(int argc, char **argv)
{
float w = 0;
float x = 0;
float y = 0;
float z = 0;
// Loop over the command line argument array.
for (int i = 1; i < argc; i++)
{
// Load the named OBJ.
if (obj *o = obj_create(argv[i]))
{
// Configure the object's vertex attributes.
obj_set_vert_loc(o, -1, vNormalLoc,
vTexCoordLoc,
vPositionLoc);
obj_set_prop_loc(o, OBJ_KD, DiffuseColorLoc, DiffuseTextureLoc, -1);
obj_set_prop_loc(o, OBJ_KS, SpecularColorLoc, SpecularTextureLoc, -1);
// Position the object along the X axis.
float b[6];
obj_bound(o, b);
objects[o] = vec3(x - b[0], -b[1], -0.5 * (b[5] + b[2]));
w = x + (b[3] - b[0]);
x = x + (b[3] - b[0]) * 1.25;
y = std::max(y, b[4] - b[1]);
z = std::max(z, b[5] - b[2]);
}
}
// Position the scene and camera.
offset = vec3(-0.5 * w, 0.0, 0.0);
position = vec3(0.0, y, z);
}
/// Generate a checkerboard background. For simplicity, the OBJ module.
void OVR_SDL2_obj::init_background()
{
if (obj *o = obj_create(0))
{
float v[3] = { 0, 0, 0 };
float n[3] = { 0, 1, 0 };
int m = 48;
// Generate a grid of vertices.
for (int i = 0; i <= m; i++)
for (int j = 0; j <= m; j++)
{
int k = obj_add_vert(o);
v[0] = j - 0.5 * m;
v[2] = i - 0.5 * m;
obj_set_vert_v(o, k, v);
obj_set_vert_n(o, k, n);
}
// Generate a pair of materials, one for each tile color.
int ma = obj_add_mtrl(o);
int mb = obj_add_mtrl(o);
float ca[4] = { 0.2f, 0.2f, 0.2f, 1.0f };
float cb[4] = { 0.3f, 0.3f, 0.3f, 1.0f };
obj_set_mtrl_c(o, ma, OBJ_KD, ca);
obj_set_mtrl_c(o, mb, OBJ_KD, cb);
// Generate a pair of surfaces, one for each material.
int a = obj_add_surf(o);
int b = obj_add_surf(o);
obj_set_surf(o, a, ma);
obj_set_surf(o, b, mb);
// Generate a mesh of triangles connecting the vertices.
for (int i = 0; i < m; ++i)
for (int j = 0; j < m; ++j)
{
int k[3], c = (i % 2 == j % 2) ? a : b;
k[0] = (i ) * (m + 1) + (j );
k[1] = (i ) * (m + 1) + (j + 1);
k[2] = (i + 1) * (m + 1) + (j + 1);
obj_set_poly(o, c, obj_add_poly(o, c), k);
k[0] = (i + 1) * (m + 1) + (j + 1);
k[1] = (i + 1) * (m + 1) + (j );
k[2] = (i ) * (m + 1) + (j );
obj_set_poly(o, c, obj_add_poly(o, c), k);
}
// Configure the object's vertex attributes.
obj_set_vert_loc(o, -1, vNormalLoc,
vTexCoordLoc,
vPositionLoc);
obj_set_prop_loc(o, OBJ_KD, DiffuseColorLoc, DiffuseTextureLoc, -1);
obj_set_prop_loc(o, OBJ_KS, SpecularColorLoc, SpecularTextureLoc, -1);
objects[o] = vec3(0.0, 0.0, 0.0);
}
}
//------------------------------------------------------------------------------
int main(int argc, char **argv)
{
OVR_SDL2_obj app(argc, argv);
app.run();
return 0;
}
<commit_msg>Tune fog<commit_after>// Copyright (c) 2014 Robert Kooima
//
// 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 "OVR_SDL2_obj.hpp"
//------------------------------------------------------------------------------
const char *vert_src = R"(
#version 150
uniform mat4 ProjectionMatrix;
uniform mat4 ModelViewMatrix;
uniform mat3 NormalMatrix;
uniform vec4 LightPosition;
in vec4 vPosition;
in vec3 vNormal;
in vec2 vTexCoord;
out vec3 fView;
out vec3 fLight;
out vec3 fNormal;
out vec2 fTexCoord;
void main()
{
vec4 vLight = LightPosition - vPosition;
fView = vec3(ModelViewMatrix * vPosition);
fLight = vec3(ModelViewMatrix * vLight);
fNormal = vec3(NormalMatrix * vNormal);
fTexCoord = vTexCoord;
gl_Position = ProjectionMatrix * ModelViewMatrix * vPosition;
}
)";
const char *frag_src = R"(
#version 150
uniform vec4 AmbientLight;
uniform vec4 DiffuseColor;
uniform vec4 SpecularColor;
uniform sampler2D DiffuseTexture;
uniform sampler2D SpecularTexture;
in vec3 fView;
in vec3 fLight;
in vec3 fNormal;
in vec2 fTexCoord;
out vec4 fOutput;
void main()
{
// Sample the materials.
vec3 cD = texture(DiffuseTexture, fTexCoord).rgb + DiffuseColor.rgb;
vec3 cS = texture(SpecularTexture, fTexCoord).rgb + SpecularColor.rgb;
// Determine the per-fragment lighting vectors.
vec3 N = normalize(fNormal);
vec3 L = normalize(fLight);
vec3 V = normalize(fView);
float d = length(fView);
vec3 R = reflect(L, N);
// Compute the diffuse shading.
float kd = max(dot(L, N), 0.0);
float ks = pow(max(dot(V, R), 0.0), 8.0);
// Calculate the fragment color.
vec3 f = AmbientLight.rgb * cD + kd * cD + ks * cS;
float fog = clamp(2.0 - 0.1 * d, 0.0, 1.0);
fOutput = vec4(mix(AmbientLight.rgb, f, fog), 1.0);
}
)";
//------------------------------------------------------------------------------
OVR_SDL2_obj::OVR_SDL2_obj(int argc, char **argv) : program(0)
{
// Compile and link the shaders.
if ((program = init_program(init_shader(GL_VERTEX_SHADER, vert_src),
init_shader(GL_FRAGMENT_SHADER, frag_src))))
{
glUseProgram(program);
// Query the program uniform locations.
ProjectionMatrixLoc = glGetUniformLocation(program, "ProjectionMatrix");
ModelViewMatrixLoc = glGetUniformLocation(program, "ModelViewMatrix");
NormalMatrixLoc = glGetUniformLocation(program, "NormalMatrix");
LightPositionLoc = glGetUniformLocation(program, "LightPosition");
AmbientLightLoc = glGetUniformLocation(program, "AmbientLight");
DiffuseColorLoc = glGetUniformLocation(program, "DiffuseColor");
SpecularColorLoc = glGetUniformLocation(program, "SpecularColor");
DiffuseTextureLoc = glGetUniformLocation(program, "DiffuseTexture");
SpecularTextureLoc = glGetUniformLocation(program, "SpecularTexture");
// Query the vertex attribute locations.
vNormalLoc = glGetAttribLocation(program, "vNormal");
vTexCoordLoc = glGetAttribLocation(program, "vTexCoord");
vPositionLoc = glGetAttribLocation(program, "vPosition");
// Configure the scene.
init_objects(argc, argv);
init_background();
glUniform4f(AmbientLightLoc, 0.1f, 0.1f, 0.1f, 1.0f);
glUniform4f(LightPositionLoc, 0.0f, 3.0f, 3.0f, 1.0f);
glUseProgram(0);
}
// Set the necessary OpenGL state.
glEnable(GL_DEPTH_TEST);
glClearColor(0.1f, 0.1f, 0.1f, 0.0f);
}
OVR_SDL2_obj::~OVR_SDL2_obj()
{
for (auto i : objects)
obj_delete(i.first);
}
void OVR_SDL2_obj::draw()
{
glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
glUseProgram(program);
glUniformMatrix4fv(ProjectionMatrixLoc, 1, GL_TRUE, projection());
// Render all objects.
for (auto i : objects)
{
mat4 M = view() * translation(offset) * translation(i.second);
glUniformMatrix4fv(ModelViewMatrixLoc, 1, GL_TRUE, M);
glUniformMatrix3fv(NormalMatrixLoc, 1, GL_TRUE, normal(M));
obj_render(i.first);
}
// Unbind our state.
glBindVertexArray(0);
glUseProgram(0);
}
//------------------------------------------------------------------------------
/// Load a series of OBJ files named on the command line. Configure them for
/// rendering with the current program. Arrange theo bjects along the X axis,
/// center the scene on the origin, and move the camera to a reasonable
/// starting position.
void OVR_SDL2_obj::init_objects(int argc, char **argv)
{
float w = 0;
float x = 0;
float y = 0;
float z = 0;
// Loop over the command line argument array.
for (int i = 1; i < argc; i++)
{
// Load the named OBJ.
if (obj *o = obj_create(argv[i]))
{
// Configure the object's vertex attributes.
obj_set_vert_loc(o, -1, vNormalLoc,
vTexCoordLoc,
vPositionLoc);
obj_set_prop_loc(o, OBJ_KD, DiffuseColorLoc, DiffuseTextureLoc, -1);
obj_set_prop_loc(o, OBJ_KS, SpecularColorLoc, SpecularTextureLoc, -1);
// Position the object along the X axis.
float b[6];
obj_bound(o, b);
objects[o] = vec3(x - b[0], -b[1], -0.5 * (b[5] + b[2]));
w = x + (b[3] - b[0]);
x = x + (b[3] - b[0]) * 1.25;
y = std::max(y, b[4] - b[1]);
z = std::max(z, b[5] - b[2]);
}
}
// Position the scene and camera.
offset = vec3(-0.5 * w, 0.0, 0.0);
position = vec3(0.0, y, z);
}
/// Generate a checkerboard background. For simplicity, the OBJ module.
void OVR_SDL2_obj::init_background()
{
if (obj *o = obj_create(0))
{
float v[3] = { 0, 0, 0 };
float n[3] = { 0, 1, 0 };
int m = 48;
// Generate a grid of vertices.
for (int i = 0; i <= m; i++)
for (int j = 0; j <= m; j++)
{
int k = obj_add_vert(o);
v[0] = j - 0.5 * m;
v[2] = i - 0.5 * m;
obj_set_vert_v(o, k, v);
obj_set_vert_n(o, k, n);
}
// Generate a pair of materials, one for each tile color.
int ma = obj_add_mtrl(o);
int mb = obj_add_mtrl(o);
float ca[4] = { 0.2f, 0.2f, 0.2f, 1.0f };
float cb[4] = { 0.3f, 0.3f, 0.3f, 1.0f };
obj_set_mtrl_c(o, ma, OBJ_KD, ca);
obj_set_mtrl_c(o, mb, OBJ_KD, cb);
// Generate a pair of surfaces, one for each material.
int a = obj_add_surf(o);
int b = obj_add_surf(o);
obj_set_surf(o, a, ma);
obj_set_surf(o, b, mb);
// Generate a mesh of triangles connecting the vertices.
for (int i = 0; i < m; ++i)
for (int j = 0; j < m; ++j)
{
int k[3], c = (i % 2 == j % 2) ? a : b;
k[0] = (i ) * (m + 1) + (j );
k[1] = (i ) * (m + 1) + (j + 1);
k[2] = (i + 1) * (m + 1) + (j + 1);
obj_set_poly(o, c, obj_add_poly(o, c), k);
k[0] = (i + 1) * (m + 1) + (j + 1);
k[1] = (i + 1) * (m + 1) + (j );
k[2] = (i ) * (m + 1) + (j );
obj_set_poly(o, c, obj_add_poly(o, c), k);
}
// Configure the object's vertex attributes.
obj_set_vert_loc(o, -1, vNormalLoc,
vTexCoordLoc,
vPositionLoc);
obj_set_prop_loc(o, OBJ_KD, DiffuseColorLoc, DiffuseTextureLoc, -1);
obj_set_prop_loc(o, OBJ_KS, SpecularColorLoc, SpecularTextureLoc, -1);
objects[o] = vec3(0.0, 0.0, 0.0);
}
}
//------------------------------------------------------------------------------
int main(int argc, char **argv)
{
OVR_SDL2_obj app(argc, argv);
app.run();
return 0;
}
<|endoftext|>
|
<commit_before>#ifndef __AXIS_HPP
#define __AXIS_HPP
#ifndef __ODRIVE_MAIN_HPP
#error "This file should not be included directly. Include odrive_main.hpp instead."
#endif
// Warning: Do not reorder these enum values.
// The state machine uses ">" comparision on them.
enum AxisState_t {
AXIS_STATE_UNDEFINED = 0, //<! will fall through to idle
AXIS_STATE_IDLE = 1, //<! disable PWM and do nothing
AXIS_STATE_STARTUP_SEQUENCE = 2, //<! the actual sequence is defined by the config.startup_... flags
AXIS_STATE_FULL_CALIBRATION_SEQUENCE = 3, //<! run all calibration procedures, then idle
AXIS_STATE_MOTOR_CALIBRATION = 4, //<! run motor calibration
AXIS_STATE_SENSORLESS_CONTROL = 5, //<! run sensorless calibration
AXIS_STATE_ENCODER_INDEX_SEARCH = 6, //<! run encoder index search
AXIS_STATE_ENCODER_OFFSET_CALIBRATION = 7, //<! run encoder offset calibration
AXIS_STATE_CLOSED_LOOP_CONTROL = 8 //<! run closed loop control
};
struct AxisConfig_t {
bool startup_motor_calibration = false; //<! run motor calibration at startup, skip otherwise
bool startup_encoder_index_search = false; //<! run encoder index search after startup, skip otherwise
// this only has an effect if encoder.config.use_index is also true
bool startup_encoder_offset_calibration = false; //<! run encoder offset calibration after startup, skip otherwise
bool startup_closed_loop_control = false; //<! enable closed loop control after calibration/startup
bool startup_sensorless_control = false; //<! enable sensorless control after calibration/startup
bool enable_step_dir = true; //<! enable step/dir input after calibration
// For M0 this has no effect if enable_uart is true
float counts_per_step = 2.0f;
float dc_bus_brownout_trip_level = 8.0f; //<! [V] voltage at which the motor stops operating
// Spinup settings
float ramp_up_time = 0.4f; // [s]
float ramp_up_distance = 4 * M_PI; // [rad]
float spin_up_current = 10.0f; // [A]
float spin_up_acceleration = 400.0f; // [rad/s^2]
float spin_up_target_vel = 400.0f; // [rad/s]
};
class Axis {
public:
enum Error_t {
ERROR_NO_ERROR = 0x00,
ERROR_INVALID_STATE = 0x01, //<! an invalid state was requested
ERROR_DC_BUS_UNDER_VOLTAGE = 0x02,
ERROR_DC_BUS_OVER_VOLTAGE = 0x04,
ERROR_CURRENT_MEASUREMENT_TIMEOUT = 0x08,
ERROR_MOTOR_DISARMED = 0x10, //<! the motor was unexpectedly disarmed
ERROR_MOTOR_FAILED = 0x20,
ERROR_SENSORLESS_ESTIMATOR_FAILED = 0x40,
ERROR_ENCODER_FAILED = 0x80,
ERROR_CONTROLLER_FAILED = 0x100,
ERROR_POS_CTRL_DURING_SENSORLESS = 0x200,
};
enum thread_signals {
M_SIGNAL_PH_CURRENT_MEAS = 1u << 0
};
Axis(const AxisHardwareConfig_t& hw_config,
AxisConfig_t& config,
Encoder& encoder,
SensorlessEstimator& sensorless_estimator,
Controller& controller,
Motor& motor);
void setup();
void start_thread();
void signal_current_meas();
bool wait_for_current_meas();
void step_cb();
void set_step_dir_enabled(bool enable);
bool check_DRV_fault();
bool check_PSU_brownout();
bool do_checks();
// @brief Runs the specified update handler at the frequency of the current measurements.
//
// The loop runs until one of the following conditions:
// - update_handler returns false
// - the current measurement times out
// - the health checks fail (brownout, driver fault line)
// - update_handler doesn't update the modulation timings in time
// This criterion is ignored if current_state is AXIS_STATE_IDLE
//
// If update_handler is going to update the motor timings, you must call motor.arm()
// shortly before this function.
//
// If the function returns, it is guaranteed that error is non-zero, except if the cause
// for the exit was a negative return value of update_handler or an external
// state change request (requested_state != AXIS_STATE_DONT_CARE).
// Under all exit conditions the motor is disarmed and the brake current set to zero.
// Furthermore, if the update_handler does not set the phase voltages in time, they will
// go to zero.
//
// @tparam T Must be a callable type that takes no arguments and returns a bool
template<typename T>
void run_control_loop(const T& update_handler) {
while (requested_state_ == AXIS_STATE_UNDEFINED) {
if ((current_state_ != AXIS_STATE_IDLE) && (motor_.armed_state_ == Motor::ARMED_STATE_DISARMED)) {
// motor got disarmed in something other than the idle loop
error_ |= ERROR_MOTOR_DISARMED;
break;
}
if (motor_.error_ != Motor::ERROR_NO_ERROR) {
error_ |= ERROR_MOTOR_FAILED;
break;
}
if (!do_checks()) // error set during function call
break;
if (!update_handler()) // error set during function call
break;
// Check we meet deadlines after queueing
++loop_counter_;
// Wait until the current measurement interrupt fires
if (!wait_for_current_meas()) {
// maybe the interrupt handler is dead, let's be
// safe and float the phases
safety_critical_disarm_motor_pwm(motor_);
update_brake_current();
error_ |= ERROR_CURRENT_MEASUREMENT_TIMEOUT;
break;
}
}
}
bool run_sensorless_spin_up();
bool run_sensorless_control_loop();
bool run_closed_loop_control_loop();
bool run_idle_loop();
void run_state_machine_loop();
const AxisHardwareConfig_t& hw_config_;
AxisConfig_t& config_;
Encoder& encoder_;
SensorlessEstimator& sensorless_estimator_;
Controller& controller_;
Motor& motor_;
osThreadId thread_id_;
volatile bool thread_id_valid_ = false;
// variables exposed on protocol
Error_t error_ = ERROR_NO_ERROR;
bool enable_step_dir_ = false; // auto enabled after calibration, based on config.enable_step_dir
AxisState_t requested_state_ = AXIS_STATE_STARTUP_SEQUENCE;
AxisState_t task_chain_[10] = { AXIS_STATE_UNDEFINED };
AxisState_t& current_state_ = task_chain_[0];
uint32_t loop_counter_ = 0;
// Communication protocol definitions
auto make_protocol_definitions() {
return make_protocol_member_list(
make_protocol_property("error", &error_),
make_protocol_property("enable_step_dir", &enable_step_dir_),
make_protocol_ro_property("current_state", ¤t_state_),
make_protocol_property("requested_state", &requested_state_),
make_protocol_ro_property("loop_counter", &loop_counter_),
make_protocol_object("config",
make_protocol_property("startup_motor_calibration", &config_.startup_motor_calibration),
make_protocol_property("startup_encoder_index_search", &config_.startup_encoder_index_search),
make_protocol_property("startup_encoder_offset_calibration", &config_.startup_encoder_offset_calibration),
make_protocol_property("startup_closed_loop_control", &config_.startup_closed_loop_control),
make_protocol_property("startup_sensorless_control", &config_.startup_sensorless_control),
make_protocol_property("enable_step_dir", &config_.enable_step_dir),
make_protocol_property("counts_per_step", &config_.counts_per_step),
make_protocol_property("dc_bus_brownout_trip_level", &config_.dc_bus_brownout_trip_level),
make_protocol_property("ramp_up_time", &config_.ramp_up_time),
make_protocol_property("ramp_up_distance", &config_.ramp_up_distance),
make_protocol_property("spin_up_current", &config_.spin_up_current),
make_protocol_property("spin_up_acceleration", &config_.spin_up_acceleration),
make_protocol_property("spin_up_target_vel", &config_.spin_up_target_vel)
),
make_protocol_object("motor", motor_.make_protocol_definitions()),
make_protocol_object("controller", controller_.make_protocol_definitions()),
make_protocol_object("encoder", encoder_.make_protocol_definitions()),
make_protocol_object("sensorless_estimator", sensorless_estimator_.make_protocol_definitions())
);
}
};
DEFINE_ENUM_FLAG_OPERATORS(Axis::Error_t)
#endif /* __AXIS_HPP */
<commit_msg>add Axis::ERROR_BRAKE_RESISTOR_DISARMED<commit_after>#ifndef __AXIS_HPP
#define __AXIS_HPP
#ifndef __ODRIVE_MAIN_HPP
#error "This file should not be included directly. Include odrive_main.hpp instead."
#endif
// Warning: Do not reorder these enum values.
// The state machine uses ">" comparision on them.
enum AxisState_t {
AXIS_STATE_UNDEFINED = 0, //<! will fall through to idle
AXIS_STATE_IDLE = 1, //<! disable PWM and do nothing
AXIS_STATE_STARTUP_SEQUENCE = 2, //<! the actual sequence is defined by the config.startup_... flags
AXIS_STATE_FULL_CALIBRATION_SEQUENCE = 3, //<! run all calibration procedures, then idle
AXIS_STATE_MOTOR_CALIBRATION = 4, //<! run motor calibration
AXIS_STATE_SENSORLESS_CONTROL = 5, //<! run sensorless calibration
AXIS_STATE_ENCODER_INDEX_SEARCH = 6, //<! run encoder index search
AXIS_STATE_ENCODER_OFFSET_CALIBRATION = 7, //<! run encoder offset calibration
AXIS_STATE_CLOSED_LOOP_CONTROL = 8 //<! run closed loop control
};
struct AxisConfig_t {
bool startup_motor_calibration = false; //<! run motor calibration at startup, skip otherwise
bool startup_encoder_index_search = false; //<! run encoder index search after startup, skip otherwise
// this only has an effect if encoder.config.use_index is also true
bool startup_encoder_offset_calibration = false; //<! run encoder offset calibration after startup, skip otherwise
bool startup_closed_loop_control = false; //<! enable closed loop control after calibration/startup
bool startup_sensorless_control = false; //<! enable sensorless control after calibration/startup
bool enable_step_dir = true; //<! enable step/dir input after calibration
// For M0 this has no effect if enable_uart is true
float counts_per_step = 2.0f;
float dc_bus_brownout_trip_level = 8.0f; //<! [V] voltage at which the motor stops operating
// Spinup settings
float ramp_up_time = 0.4f; // [s]
float ramp_up_distance = 4 * M_PI; // [rad]
float spin_up_current = 10.0f; // [A]
float spin_up_acceleration = 400.0f; // [rad/s^2]
float spin_up_target_vel = 400.0f; // [rad/s]
};
class Axis {
public:
enum Error_t {
ERROR_NO_ERROR = 0x00,
ERROR_INVALID_STATE = 0x01, //<! an invalid state was requested
ERROR_DC_BUS_UNDER_VOLTAGE = 0x02,
ERROR_DC_BUS_OVER_VOLTAGE = 0x04,
ERROR_CURRENT_MEASUREMENT_TIMEOUT = 0x08,
ERROR_BRAKE_RESISTOR_DISARMED = 0x10, //<! the brake resistor was unexpectedly disarmed
ERROR_MOTOR_DISARMED = 0x20, //<! the motor was unexpectedly disarmed
ERROR_MOTOR_FAILED = 0x40,
ERROR_SENSORLESS_ESTIMATOR_FAILED = 0x80,
ERROR_ENCODER_FAILED = 0x100,
ERROR_CONTROLLER_FAILED = 0x200,
ERROR_POS_CTRL_DURING_SENSORLESS = 0x400,
};
enum thread_signals {
M_SIGNAL_PH_CURRENT_MEAS = 1u << 0
};
Axis(const AxisHardwareConfig_t& hw_config,
AxisConfig_t& config,
Encoder& encoder,
SensorlessEstimator& sensorless_estimator,
Controller& controller,
Motor& motor);
void setup();
void start_thread();
void signal_current_meas();
bool wait_for_current_meas();
void step_cb();
void set_step_dir_enabled(bool enable);
bool check_DRV_fault();
bool check_PSU_brownout();
bool do_checks();
// @brief Runs the specified update handler at the frequency of the current measurements.
//
// The loop runs until one of the following conditions:
// - update_handler returns false
// - the current measurement times out
// - the health checks fail (brownout, driver fault line)
// - update_handler doesn't update the modulation timings in time
// This criterion is ignored if current_state is AXIS_STATE_IDLE
//
// If update_handler is going to update the motor timings, you must call motor.arm()
// shortly before this function.
//
// If the function returns, it is guaranteed that error is non-zero, except if the cause
// for the exit was a negative return value of update_handler or an external
// state change request (requested_state != AXIS_STATE_DONT_CARE).
// Under all exit conditions the motor is disarmed and the brake current set to zero.
// Furthermore, if the update_handler does not set the phase voltages in time, they will
// go to zero.
//
// @tparam T Must be a callable type that takes no arguments and returns a bool
template<typename T>
void run_control_loop(const T& update_handler) {
while (requested_state_ == AXIS_STATE_UNDEFINED) {
if (!brake_resistor_armed_) {
error_ |= ERROR_BRAKE_RESISTOR_DISARMED;
break;
}
if ((current_state_ != AXIS_STATE_IDLE) && (motor_.armed_state_ == Motor::ARMED_STATE_DISARMED)) {
// motor got disarmed in something other than the idle loop
error_ |= ERROR_MOTOR_DISARMED;
break;
}
if (motor_.error_ != Motor::ERROR_NO_ERROR) {
error_ |= ERROR_MOTOR_FAILED;
break;
}
if (!do_checks()) // error set during function call
break;
if (!update_handler()) // error set during function call
break;
// Check we meet deadlines after queueing
++loop_counter_;
// Wait until the current measurement interrupt fires
if (!wait_for_current_meas()) {
// maybe the interrupt handler is dead, let's be
// safe and float the phases
safety_critical_disarm_motor_pwm(motor_);
update_brake_current();
error_ |= ERROR_CURRENT_MEASUREMENT_TIMEOUT;
break;
}
}
}
bool run_sensorless_spin_up();
bool run_sensorless_control_loop();
bool run_closed_loop_control_loop();
bool run_idle_loop();
void run_state_machine_loop();
const AxisHardwareConfig_t& hw_config_;
AxisConfig_t& config_;
Encoder& encoder_;
SensorlessEstimator& sensorless_estimator_;
Controller& controller_;
Motor& motor_;
osThreadId thread_id_;
volatile bool thread_id_valid_ = false;
// variables exposed on protocol
Error_t error_ = ERROR_NO_ERROR;
bool enable_step_dir_ = false; // auto enabled after calibration, based on config.enable_step_dir
AxisState_t requested_state_ = AXIS_STATE_STARTUP_SEQUENCE;
AxisState_t task_chain_[10] = { AXIS_STATE_UNDEFINED };
AxisState_t& current_state_ = task_chain_[0];
uint32_t loop_counter_ = 0;
// Communication protocol definitions
auto make_protocol_definitions() {
return make_protocol_member_list(
make_protocol_property("error", &error_),
make_protocol_property("enable_step_dir", &enable_step_dir_),
make_protocol_ro_property("current_state", ¤t_state_),
make_protocol_property("requested_state", &requested_state_),
make_protocol_ro_property("loop_counter", &loop_counter_),
make_protocol_object("config",
make_protocol_property("startup_motor_calibration", &config_.startup_motor_calibration),
make_protocol_property("startup_encoder_index_search", &config_.startup_encoder_index_search),
make_protocol_property("startup_encoder_offset_calibration", &config_.startup_encoder_offset_calibration),
make_protocol_property("startup_closed_loop_control", &config_.startup_closed_loop_control),
make_protocol_property("startup_sensorless_control", &config_.startup_sensorless_control),
make_protocol_property("enable_step_dir", &config_.enable_step_dir),
make_protocol_property("counts_per_step", &config_.counts_per_step),
make_protocol_property("dc_bus_brownout_trip_level", &config_.dc_bus_brownout_trip_level),
make_protocol_property("ramp_up_time", &config_.ramp_up_time),
make_protocol_property("ramp_up_distance", &config_.ramp_up_distance),
make_protocol_property("spin_up_current", &config_.spin_up_current),
make_protocol_property("spin_up_acceleration", &config_.spin_up_acceleration),
make_protocol_property("spin_up_target_vel", &config_.spin_up_target_vel)
),
make_protocol_object("motor", motor_.make_protocol_definitions()),
make_protocol_object("controller", controller_.make_protocol_definitions()),
make_protocol_object("encoder", encoder_.make_protocol_definitions()),
make_protocol_object("sensorless_estimator", sensorless_estimator_.make_protocol_definitions())
);
}
};
DEFINE_ENUM_FLAG_OPERATORS(Axis::Error_t)
#endif /* __AXIS_HPP */
<|endoftext|>
|
<commit_before>/*
DAcase2.c
This program connects to the DAQ data source passed as argument
and populates local "./result.txt" file with the ids of events received
during the run.
The program exits when being asked to shut down (daqDA_checkshutdown)
or End of Run event.
Messages on stdout are exported to DAQ log system.
contact: alice-datesupport@cern.ch
*/
#include "event.h"
#include "monitor.h"
extern "C" {
#include "daqDA.h"
}
#include <stdio.h>
#include <stdlib.h>
#include <TSystem.h>
#include "AliRawReader.h"
#include "AliRawReaderDate.h"
#include "AliPHOSCalibHistoProducer.h"
#include "AliPHOSRawDecoderv1.h"
#include "AliCaloAltroMapping.h"
/* Main routine
Arguments:
1- monitoring data source
*/
int main(int argc, char **argv) {
int status;
if (argc!=2) {
printf("Wrong number of arguments\n");
return -1;
}
/* open result file */
FILE *fp=NULL;
fp=fopen("./result.txt","a");
if (fp==NULL) {
printf("Failed to open file\n");
return -1;
}
/* Open mapping files */
AliAltroMapping *mapping[4];
TString path = gSystem->Getenv("ALICE_ROOT");
path += "/PHOS/mapping/RCU";
TString path2;
for(Int_t i = 0; i < 4; i++) {
path2 = path;
path2 += i;
path2 += ".data";
mapping[i] = new AliCaloAltroMapping(path2.Data());
}
/* define data source : this is argument 1 */
status=monitorSetDataSource( argv[1] );
if (status!=0) {
printf("monitorSetDataSource() failed : %s\n",monitorDecodeError(status));
return -1;
}
/* declare monitoring program */
status=monitorDeclareMp( __FILE__ );
if (status!=0) {
printf("monitorDeclareMp() failed : %s\n",monitorDecodeError(status));
return -1;
}
/* define wait event timeout - 1s max */
monitorSetNowait();
monitorSetNoWaitNetworkTimeout(1000);
/* log start of process */
printf("DA example case2 monitoring program started\n");
/* init some counters */
int nevents_physics=0;
int nevents_total=0;
AliRawReader *rawReader = NULL;
AliPHOSDA1 da1(2); // DA1 (Calibration DA) for module2
Float_t e[64][56][2];
Float_t t[64][56][2];
Int_t gain = -1;
Int_t X = -1;
Int_t Z = -1;
/* main loop (infinite) */
for(;;) {
struct eventHeaderStruct *event;
eventTypeType eventT;
/* check shutdown condition */
if (daqDA_checkShutdown()) {break;}
/* get next event (blocking call until timeout) */
status=monitorGetEventDynamic((void **)&event);
if (status==MON_ERR_EOF) {
printf ("End of File detected\n");
break; /* end of monitoring file has been reached */
}
if (status!=0) {
printf("monitorGetEventDynamic() failed : %s\n",monitorDecodeError(status));
break;
}
/* retry if got no event */
if (event==NULL) {
continue;
}
/* use event - here, just write event id to result file */
eventT=event->eventType;
if (eventT==PHYSICS_EVENT) {
fprintf(fp,"Run #%lu, event size: %lu, BC:%u, Orbit:%u, Period:%u\n",
(unsigned long)event->eventRunNb,
(unsigned long)event->eventSize,
EVENT_ID_GET_BUNCH_CROSSING(event->eventId),
EVENT_ID_GET_ORBIT(event->eventId),
EVENT_ID_GET_PERIOD(event->eventId)
);
for(Int_t iX=0; iX<64; iX++) {
for(Int_t iZ=0; iZ<56; iZ++) {
for(Int_t iGain=0; iGain<2; iGain++) {
e[iX][iZ][iGain] = 0.;
t[iX][iZ][iGain] = 0.;
}
}
}
rawReader = new AliRawReaderDate((void*)event);
AliPHOSRawDecoderv1 dc(rawReader,mapping);
dc.SubtractPedestals(kTRUE);
dc.SetOldRCUFormat(kTRUE);
while(dc.NextDigit()) {
X = dc.GetRow() - 1;
Z = dc.GetColumn() - 1;
if(dc.IsLowGain()) gain = 0;
else
gain = 1;
e[X][Z][gain] = dc.GetEnergy();
t[X][Z][gain] = dc.GetTime();
}
da1.FillHistograms(e,t);
//da1.UpdateHistoFile();
delete rawReader;
nevents_physics++;
}
nevents_total++;
/* free resources */
free(event);
/* exit when last event received, no need to wait for TERM signal */
if (eventT==END_OF_RUN) {
printf("EOR event detected\n");
break;
}
}
for(Int_t i = 0; i < 4; i++) delete mapping[i];
/* write report */
fprintf(fp,"Run #%s, received %d physics events out of %d\n",getenv("DATE_RUN_NUMBER"),nevents_physics,nevents_total);
/* close result file */
fclose(fp);
return status;
}
<commit_msg>.h file name corrected.<commit_after>/*
DAcase2.c
This program connects to the DAQ data source passed as argument
and populates local "./result.txt" file with the ids of events received
during the run.
The program exits when being asked to shut down (daqDA_checkshutdown)
or End of Run event.
Messages on stdout are exported to DAQ log system.
contact: alice-datesupport@cern.ch
*/
#include "event.h"
#include "monitor.h"
extern "C" {
#include "daqDA.h"
}
#include <stdio.h>
#include <stdlib.h>
#include <TSystem.h>
#include "AliRawReader.h"
#include "AliRawReaderDate.h"
#include "AliPHOSDA1.h"
#include "AliPHOSRawDecoderv1.h"
#include "AliCaloAltroMapping.h"
/* Main routine
Arguments:
1- monitoring data source
*/
int main(int argc, char **argv) {
int status;
if (argc!=2) {
printf("Wrong number of arguments\n");
return -1;
}
/* open result file */
FILE *fp=NULL;
fp=fopen("./result.txt","a");
if (fp==NULL) {
printf("Failed to open file\n");
return -1;
}
/* Open mapping files */
AliAltroMapping *mapping[4];
TString path = gSystem->Getenv("ALICE_ROOT");
path += "/PHOS/mapping/RCU";
TString path2;
for(Int_t i = 0; i < 4; i++) {
path2 = path;
path2 += i;
path2 += ".data";
mapping[i] = new AliCaloAltroMapping(path2.Data());
}
/* define data source : this is argument 1 */
status=monitorSetDataSource( argv[1] );
if (status!=0) {
printf("monitorSetDataSource() failed : %s\n",monitorDecodeError(status));
return -1;
}
/* declare monitoring program */
status=monitorDeclareMp( __FILE__ );
if (status!=0) {
printf("monitorDeclareMp() failed : %s\n",monitorDecodeError(status));
return -1;
}
/* define wait event timeout - 1s max */
monitorSetNowait();
monitorSetNoWaitNetworkTimeout(1000);
/* log start of process */
printf("DA example case2 monitoring program started\n");
/* init some counters */
int nevents_physics=0;
int nevents_total=0;
AliRawReader *rawReader = NULL;
AliPHOSDA1 da1(2); // DA1 (Calibration DA) for module2
Float_t e[64][56][2];
Float_t t[64][56][2];
Int_t gain = -1;
Int_t X = -1;
Int_t Z = -1;
/* main loop (infinite) */
for(;;) {
struct eventHeaderStruct *event;
eventTypeType eventT;
/* check shutdown condition */
if (daqDA_checkShutdown()) {break;}
/* get next event (blocking call until timeout) */
status=monitorGetEventDynamic((void **)&event);
if (status==MON_ERR_EOF) {
printf ("End of File detected\n");
break; /* end of monitoring file has been reached */
}
if (status!=0) {
printf("monitorGetEventDynamic() failed : %s\n",monitorDecodeError(status));
break;
}
/* retry if got no event */
if (event==NULL) {
continue;
}
/* use event - here, just write event id to result file */
eventT=event->eventType;
if (eventT==PHYSICS_EVENT) {
fprintf(fp,"Run #%lu, event size: %lu, BC:%u, Orbit:%u, Period:%u\n",
(unsigned long)event->eventRunNb,
(unsigned long)event->eventSize,
EVENT_ID_GET_BUNCH_CROSSING(event->eventId),
EVENT_ID_GET_ORBIT(event->eventId),
EVENT_ID_GET_PERIOD(event->eventId)
);
for(Int_t iX=0; iX<64; iX++) {
for(Int_t iZ=0; iZ<56; iZ++) {
for(Int_t iGain=0; iGain<2; iGain++) {
e[iX][iZ][iGain] = 0.;
t[iX][iZ][iGain] = 0.;
}
}
}
rawReader = new AliRawReaderDate((void*)event);
AliPHOSRawDecoderv1 dc(rawReader,mapping);
dc.SubtractPedestals(kTRUE);
dc.SetOldRCUFormat(kTRUE);
while(dc.NextDigit()) {
X = dc.GetRow() - 1;
Z = dc.GetColumn() - 1;
if(dc.IsLowGain()) gain = 0;
else
gain = 1;
e[X][Z][gain] = dc.GetEnergy();
t[X][Z][gain] = dc.GetTime();
}
da1.FillHistograms(e,t);
//da1.UpdateHistoFile();
delete rawReader;
nevents_physics++;
}
nevents_total++;
/* free resources */
free(event);
/* exit when last event received, no need to wait for TERM signal */
if (eventT==END_OF_RUN) {
printf("EOR event detected\n");
break;
}
}
for(Int_t i = 0; i < 4; i++) delete mapping[i];
/* write report */
fprintf(fp,"Run #%s, received %d physics events out of %d\n",getenv("DATE_RUN_NUMBER"),nevents_physics,nevents_total);
/* close result file */
fclose(fp);
return status;
}
<|endoftext|>
|
<commit_before>/*=========================================================================
Program: Visualization Toolkit
Module: vtkRotationFilter.cxx
Copyright (c) Ken Martin, Will Schroeder, Bill Lorensen
All rights reserved.
See Copyright.txt or http://www.kitware.com/Copyright.htm for details.
This software is distributed WITHOUT ANY WARRANTY; without even
the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR
PURPOSE. See the above copyright notice for more information.
=========================================================================*/
#include "vtkRotationFilter.h"
#include "vtkCellData.h"
#include "vtkGenericCell.h"
#include "vtkIdList.h"
#include "vtkInformation.h"
#include "vtkInformationVector.h"
#include "vtkObjectFactory.h"
#include "vtkPointData.h"
#include "vtkUnstructuredGrid.h"
#include "vtkMath.h"
vtkCxxRevisionMacro(vtkRotationFilter, "1.7");
vtkStandardNewMacro(vtkRotationFilter);
//---------------------------------------------------------------------------
vtkRotationFilter::vtkRotationFilter()
{
this->Axis = 2;
this->CopyInput = 0;
this->Center[0] = this->Center[1] = this->Center[2] = 0;
this->NumberOfCopies = 0;
this->Angle = 0;
}
//---------------------------------------------------------------------------
vtkRotationFilter::~vtkRotationFilter()
{
}
//---------------------------------------------------------------------------
void vtkRotationFilter::PrintSelf(ostream &os, vtkIndent indent)
{
this->Superclass::PrintSelf(os, indent);
os << indent << "Axis: " << this->Axis << endl;
os << indent << "CopyInput: " << this->CopyInput << endl;
os << indent << "Center: (" << this->Center[0] << "," << this->Center[1]
<< "," << this->Center[2] << ")" << endl;
os << indent << "NumberOfCopies: " << this->NumberOfCopies << endl;
os << indent << "Angle: " << this->Angle << endl;
}
//---------------------------------------------------------------------------
int vtkRotationFilter::RequestData(
vtkInformation *vtkNotUsed(request),
vtkInformationVector **inputVector,
vtkInformationVector *outputVector)
{
// get the info objects
vtkInformation *inInfo = inputVector[0]->GetInformationObject(0);
vtkInformation *outInfo = outputVector->GetInformationObject(0);
// get the input and ouptut
vtkDataSet *input = vtkDataSet::SafeDownCast(
inInfo->Get(vtkDataObject::DATA_OBJECT()));
vtkUnstructuredGrid *output = vtkUnstructuredGrid::SafeDownCast(
outInfo->Get(vtkDataObject::DATA_OBJECT()));
vtkIdType i;
vtkPointData *inPD = input->GetPointData();
vtkPointData *outPD = output->GetPointData();
vtkCellData *inCD = input->GetCellData();
vtkCellData *outCD = output->GetCellData();
if (!this->GetNumberOfCopies())
{
vtkErrorMacro("No number of copy set!");
return 1;
}
double tuple[3];
vtkPoints *outPoints;
double point[3], center[3];
int ptId, cellId, j, k;
vtkGenericCell *cell = vtkGenericCell::New();
vtkIdList *ptIds = vtkIdList::New();
outPoints = vtkPoints::New();
vtkIdType numPts = input->GetNumberOfPoints();
vtkIdType numCells = input->GetNumberOfCells();
if (this->CopyInput)
{
outPoints->Allocate((this->CopyInput + this->GetNumberOfCopies()) * numPts);
output->Allocate((this->CopyInput + this->GetNumberOfCopies()) * numPts);
}
else
{
outPoints->Allocate( this->GetNumberOfCopies() * numPts);
output->Allocate( this->GetNumberOfCopies() * numPts);
}
outPD->CopyAllocate(inPD);
outCD->CopyAllocate(inCD);
vtkDataArray *inPtVectors, *outPtVectors, *inPtNormals, *outPtNormals;
vtkDataArray *inCellVectors, *outCellVectors, *inCellNormals;
vtkDataArray *outCellNormals;
inPtVectors = inPD->GetVectors();
outPtVectors = outPD->GetVectors();
inPtNormals = inPD->GetNormals();
outPtNormals = outPD->GetNormals();
inCellVectors = inCD->GetVectors();
outCellVectors = outCD->GetVectors();
inCellNormals = inCD->GetNormals();
outCellNormals = outCD->GetNormals();
// Copy first points.
if (this->CopyInput)
{
for (i = 0; i < numPts; i++)
{
input->GetPoint(i, point);
ptId = outPoints->InsertNextPoint(point);
outPD->CopyData(inPD, i, ptId);
}
}
// Rotate points.
double angle = this->GetAngle()*vtkMath::DegreesToRadians();
this->GetCenter(center);
switch (this->Axis)
{
case USE_X:
for (k = 0; k < this->GetNumberOfCopies(); k++)
{
for (i = 0; i < numPts; i++)
{
input->GetPoint(i, point);
ptId =
outPoints->InsertNextPoint((point[0]-center[0]),
(point[1]-center[1])*cos(angle*(1+k)) - (point[2]-center[2])*sin(angle*(1+k)),
(point[1]-center[1])*sin(angle*(1+k)) + (point[2]-center[2])*cos(angle*(1+k)));
outPD->CopyData(inPD, i, ptId);
if (inPtVectors)
{
inPtVectors->GetTuple(i, tuple);
outPtVectors->SetTuple(ptId, tuple);
}
if (inPtNormals)
{
inPtNormals->GetTuple(i, tuple);
outPtNormals->SetTuple(ptId, tuple);
}
}
}
break;
case USE_Y:
for (k = 0; k < this->GetNumberOfCopies(); k++)
{
for (i = 0; i < numPts; i++)
{
input->GetPoint(i, point);
ptId =
outPoints->InsertNextPoint((point[0]-center[0])*cos(angle*(1+k)) + (point[2]-center[2])*sin(angle*(1+k)),
(point[1]-center[1]),
-(point[0]-center[0])*sin(angle*(1+k)) + (point[2]-center[2])*cos(angle*(1+k)));
outPD->CopyData(inPD, i, ptId);
if (inPtVectors)
{
inPtVectors->GetTuple(i, tuple);
outPtVectors->SetTuple(ptId, tuple);
}
if (inPtNormals)
{
inPtNormals->GetTuple(i, tuple);
outPtNormals->SetTuple(ptId, tuple);
}
}
}
break;
case USE_Z:
for (k = 0; k < this->GetNumberOfCopies(); k++)
{
for (i = 0; i < numPts; i++)
{
input->GetPoint(i, point);
ptId =
outPoints->InsertNextPoint( (point[0]-center[0])*cos(angle*(1+k)) - (point[1]-center[1])*sin(angle*(1+k)),
(point[0]-center[0])*sin(angle*(1+k)) + (point[1]-center[1])*cos(angle*(1+k)),
(point[2]-center[2]));
outPD->CopyData(inPD, i, ptId);
if (inPtVectors)
{
inPtVectors->GetTuple(i, tuple);
outPtVectors->SetTuple(ptId, tuple);
}
if (inPtNormals)
{
inPtNormals->GetTuple(i, tuple);
outPtNormals->SetTuple(ptId, tuple);
}
}
}
break;
}
int numCellPts, cellType;
vtkIdType *newCellPts;
vtkIdList *cellPts;
// Copy original cells.
if (this->CopyInput)
{
for (i = 0; i < numCells; i++)
{
input->GetCellPoints(i, ptIds);
output->InsertNextCell(input->GetCellType(i), ptIds);
outCD->CopyData(inCD, i, i);
}
}
// Generate rotated cells.
for (k = 0; k < this->GetNumberOfCopies(); k++)
{
for (i = 0; i < numCells; i++)
{
input->GetCellPoints(i, ptIds);
input->GetCell(i, cell);
numCellPts = cell->GetNumberOfPoints();
cellType = cell->GetCellType();
cellPts = cell->GetPointIds();
// Triangle strips with even number of triangles have
// to be handled specially. A degenerate triangle is
// introduce to flip all the triangles properly.
if (cellType == VTK_TRIANGLE_STRIP && numCellPts % 2 == 0)
{
numCellPts++;
newCellPts = new vtkIdType[numCellPts];
newCellPts[0] = cellPts->GetId(0) + numPts;
newCellPts[1] = cellPts->GetId(2) + numPts;
newCellPts[2] = cellPts->GetId(1) + numPts;
newCellPts[3] = cellPts->GetId(2) + numPts;
for (j = 4; j < numCellPts; j++)
{
newCellPts[j] = cellPts->GetId(j-1) + numPts*k;
if (this->CopyInput)
{
newCellPts[j] += numPts;
}
}
}
else
{
newCellPts = new vtkIdType[numCellPts];
for (j = numCellPts-1; j >= 0; j--)
{
newCellPts[numCellPts-1-j] = cellPts->GetId(j) + numPts*k;
if (this->CopyInput)
{
newCellPts[numCellPts-1-j] += numPts;
}
}
}
cellId = output->InsertNextCell(cellType, numCellPts, newCellPts);
delete [] newCellPts;
outCD->CopyData(inCD, i, cellId);
if (inCellVectors)
{
inCellVectors->GetTuple(i, tuple);
outCellVectors->SetTuple(cellId, tuple);
}
if (inCellNormals)
{
inCellNormals->GetTuple(i, tuple);
outCellNormals->SetTuple(cellId, tuple);
}
}
}
cell->Delete();
ptIds->Delete();
output->SetPoints(outPoints);
outPoints->Delete();
output->CheckAttributes();
return 1;
}
int vtkRotationFilter::FillInputPortInformation(int, vtkInformation *info)
{
info->Set(vtkAlgorithm::INPUT_REQUIRED_DATA_TYPE(), "vtkDataSet");
return 1;
}
<commit_msg>ENH: Reworking of Rotation filter by J.Favre at cscs.ch. Change all hardwired transformation code to use vtkTransform<commit_after>/*=========================================================================
Program: Visualization Toolkit
Module: vtkRotationFilter.cxx
Copyright (c) Ken Martin, Will Schroeder, Bill Lorensen
All rights reserved.
See Copyright.txt or http://www.kitware.com/Copyright.htm for details.
This software is distributed WITHOUT ANY WARRANTY; without even
the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR
PURPOSE. See the above copyright notice for more information.
=========================================================================*/
#include "vtkRotationFilter.h"
#include "vtkCellData.h"
#include "vtkGenericCell.h"
#include "vtkIdList.h"
#include "vtkInformation.h"
#include "vtkInformationVector.h"
#include "vtkObjectFactory.h"
#include "vtkPointData.h"
#include "vtkUnstructuredGrid.h"
#include "vtkMath.h"
#include "vtkTransform.h"
vtkCxxRevisionMacro(vtkRotationFilter, "1.8");
vtkStandardNewMacro(vtkRotationFilter);
//---------------------------------------------------------------------------
vtkRotationFilter::vtkRotationFilter()
{
this->Axis = 2;
this->CopyInput = 0;
this->Center[0] = this->Center[1] = this->Center[2] = 0;
this->NumberOfCopies = 0;
this->Angle = 0;
}
//---------------------------------------------------------------------------
vtkRotationFilter::~vtkRotationFilter()
{
}
//---------------------------------------------------------------------------
void vtkRotationFilter::PrintSelf(ostream &os, vtkIndent indent)
{
this->Superclass::PrintSelf(os, indent);
os << indent << "Axis: " << this->Axis << endl;
os << indent << "CopyInput: " << this->CopyInput << endl;
os << indent << "Center: (" << this->Center[0] << "," << this->Center[1]
<< "," << this->Center[2] << ")" << endl;
os << indent << "NumberOfCopies: " << this->NumberOfCopies << endl;
os << indent << "Angle: " << this->Angle << endl;
}
//---------------------------------------------------------------------------
int vtkRotationFilter::RequestData(
vtkInformation *vtkNotUsed(request),
vtkInformationVector **inputVector,
vtkInformationVector *outputVector)
{
// get the info objects
vtkInformation *inInfo = inputVector[0]->GetInformationObject(0);
vtkInformation *outInfo = outputVector->GetInformationObject(0);
// get the input and ouptut
vtkDataSet *input = vtkDataSet::SafeDownCast(
inInfo->Get(vtkDataObject::DATA_OBJECT()));
vtkUnstructuredGrid *output = vtkUnstructuredGrid::SafeDownCast(
outInfo->Get(vtkDataObject::DATA_OBJECT()));
vtkIdType i;
vtkPointData *inPD = input->GetPointData();
vtkPointData *outPD = output->GetPointData();
vtkCellData *inCD = input->GetCellData();
vtkCellData *outCD = output->GetCellData();
if (!this->GetNumberOfCopies())
{
vtkErrorMacro("No number of copy set!");
return 1;
}
double tuple[3];
vtkPoints *outPoints;
double point[3], center[3], negativCenter[3];
int ptId, cellId, j, k;
vtkGenericCell *cell = vtkGenericCell::New();
vtkIdList *ptIds = vtkIdList::New();
outPoints = vtkPoints::New();
vtkIdType numPts = input->GetNumberOfPoints();
vtkIdType numCells = input->GetNumberOfCells();
if (this->CopyInput)
{
outPoints->Allocate((this->CopyInput + this->GetNumberOfCopies()) * numPts);
output->Allocate((this->CopyInput + this->GetNumberOfCopies()) * numPts);
}
else
{
outPoints->Allocate( this->GetNumberOfCopies() * numPts);
output->Allocate( this->GetNumberOfCopies() * numPts);
}
outPD->CopyAllocate(inPD);
outCD->CopyAllocate(inCD);
vtkDataArray *inPtVectors, *outPtVectors, *inPtNormals, *outPtNormals;
vtkDataArray *inCellVectors, *outCellVectors, *inCellNormals;
vtkDataArray *outCellNormals;
inPtVectors = inPD->GetVectors();
outPtVectors = outPD->GetVectors();
inPtNormals = inPD->GetNormals();
outPtNormals = outPD->GetNormals();
inCellVectors = inCD->GetVectors();
outCellVectors = outCD->GetVectors();
inCellNormals = inCD->GetNormals();
outCellNormals = outCD->GetNormals();
// Copy first points.
if (this->CopyInput)
{
for (i = 0; i < numPts; i++)
{
input->GetPoint(i, point);
ptId = outPoints->InsertNextPoint(point);
outPD->CopyData(inPD, i, ptId);
}
}
vtkTransform *localTransform = vtkTransform::New();
// Rotate points.
// double angle = this->GetAngle()*vtkMath::DegreesToRadians();
this->GetCenter(center);
negativCenter[0] = -center[0];
negativCenter[1] = -center[1];
negativCenter[2] = -center[2];
for (k = 0; k < this->GetNumberOfCopies(); k++)
{
localTransform->Identity();
localTransform->Translate(center);
switch (this->Axis)
{
case USE_X:
localTransform->RotateX((k+1)*this->GetAngle());
break;
case USE_Y:
localTransform->RotateY((k+1)*this->GetAngle());
break;
case USE_Z:
localTransform->RotateZ((k+1)*this->GetAngle());
break;
}
localTransform->Translate(negativCenter);
for (i = 0; i < numPts; i++)
{
input->GetPoint(i, point);
localTransform->TransformPoint(point, point);
ptId = outPoints->InsertNextPoint(point);
outPD->CopyData(inPD, i, ptId);
if (inPtVectors)
{
inPtVectors->GetTuple(i, tuple);
outPtVectors->SetTuple(ptId, tuple);
}
if (inPtNormals)
{
//inPtNormals->GetTuple(i, tuple);
//outPtNormals->SetTuple(ptId, tuple);
}
}
}
localTransform->Delete();
int numCellPts, cellType;
vtkIdType *newCellPts;
vtkIdList *cellPts;
// Copy original cells.
if (this->CopyInput)
{
for (i = 0; i < numCells; i++)
{
input->GetCellPoints(i, ptIds);
output->InsertNextCell(input->GetCellType(i), ptIds);
outCD->CopyData(inCD, i, i);
}
}
// Generate rotated cells.
for (k = 0; k < this->GetNumberOfCopies(); k++)
{
for (i = 0; i < numCells; i++)
{
input->GetCellPoints(i, ptIds);
input->GetCell(i, cell);
numCellPts = cell->GetNumberOfPoints();
cellType = cell->GetCellType();
cellPts = cell->GetPointIds();
// Triangle strips with even number of triangles have
// to be handled specially. A degenerate triangle is
// introduce to flip all the triangles properly.
if (cellType == VTK_TRIANGLE_STRIP && numCellPts % 2 == 0)
{
cerr << "Here\n";
}
else
{cerr << "celltype " << cellType << " numCellPts " << numCellPts << "\n";
newCellPts = new vtkIdType[numCellPts];
//for (j = numCellPts-1; j >= 0; j--)
for (j = 0; j < numCellPts; j++)
{
//newCellPts[numCellPts-1-j] = cellPts->GetId(j) + numPts*k;
newCellPts[j] = cellPts->GetId(j) + numPts*k;
if (this->CopyInput)
{
//newCellPts[numCellPts-1-j] += numPts;
newCellPts[j] += numPts;
}
}
}
cellId = output->InsertNextCell(cellType, numCellPts, newCellPts);
delete [] newCellPts;
outCD->CopyData(inCD, i, cellId);
if (inCellVectors)
{
inCellVectors->GetTuple(i, tuple);
outCellVectors->SetTuple(cellId, tuple);
}
if (inCellNormals)
{
//inCellNormals->GetTuple(i, tuple);
//outCellNormals->SetTuple(cellId, tuple);
}
}
}
cell->Delete();
ptIds->Delete();
output->SetPoints(outPoints);
outPoints->Delete();
output->CheckAttributes();
return 1;
}
int vtkRotationFilter::FillInputPortInformation(int, vtkInformation *info)
{
info->Set(vtkAlgorithm::INPUT_REQUIRED_DATA_TYPE(), "vtkDataSet");
return 1;
}
<|endoftext|>
|
<commit_before>/// \file PasskeySetup.cpp
//-----------------------------------------------------------------------------
#include "stdafx.h"
#include "PasswordSafe.h"
#include "corelib/PWCharPool.h" // for CheckPassword()
#include "ThisMfcApp.h"
#include "corelib/PwsPlatform.h"
#if defined(POCKET_PC)
#include "pocketpc/resource.h"
#include "pocketpc/PocketPC.h"
#else
#include "resource.h"
#endif
#include "corelib/util.h"
#include "PasskeySetup.h"
#include "PwFont.h"
#ifdef _DEBUG
#define new DEBUG_NEW
#undef THIS_FILE
static char THIS_FILE[] = __FILE__;
#endif
//-----------------------------------------------------------------------------
CPasskeySetup::CPasskeySetup(CWnd* pParent)
: super(CPasskeySetup::IDD, pParent)
{
m_passkey = _T("");
m_verify = _T("");
}
BOOL CPasskeySetup::OnInitDialog()
{
CDialog::OnInitDialog();
SetPasswordFont(GetDlgItem(IDC_PASSKEY));
SetPasswordFont(GetDlgItem(IDC_VERIFY));
return TRUE;
}
void CPasskeySetup::DoDataExchange(CDataExchange* pDX)
{
super::DoDataExchange(pDX);
DDX_Text(pDX, IDC_PASSKEY, (CString &)m_passkey);
DDX_Text(pDX, IDC_VERIFY, (CString &)m_verify);
}
BEGIN_MESSAGE_MAP(CPasskeySetup, super)
ON_BN_CLICKED(ID_HELP, OnHelp)
#if defined(POCKET_PC)
ON_EN_SETFOCUS(IDC_PASSKEY, OnPasskeySetfocus)
ON_EN_SETFOCUS(IDC_VERIFY, OnPasskeySetfocus)
ON_EN_KILLFOCUS(IDC_PASSKEY, OnPasskeyKillfocus)
ON_EN_KILLFOCUS(IDC_VERIFY, OnPasskeyKillfocus)
#endif
END_MESSAGE_MAP()
void CPasskeySetup::OnCancel()
{
super::OnCancel();
}
void CPasskeySetup::OnOK()
{
UpdateData(TRUE);
if (m_passkey != m_verify)
{
AfxMessageBox(_T("The two entries do not match."));
((CEdit*)GetDlgItem(IDC_VERIFY))->SetFocus();
return;
}
if (m_passkey.IsEmpty())
{
AfxMessageBox(_T("Please enter a key and verify it."));
((CEdit*)GetDlgItem(IDC_PASSKEY))->SetFocus();
return;
}
// Accept weak passwords in debug build, to make it easier to test
// Reject weak passwords in Release (prior to 3.02, we allowed the
// user to accept a weak password if she insisted).
// DK - I think this is wrong, so I have put it back in a different form.
#ifndef _DEBUG
CMyString errmess;
if (!CPasswordCharPool::CheckPassword(m_passkey, errmess)) {
CString msg(_T("Weak passphrase:\n\n"));
msg += CString(errmess);
if (m_bAllowWeakPassphrases) {
msg += _T("\n\nAccept it anyway?");
int rc = AfxMessageBox(msg, MB_YESNO | MB_ICONSTOP);
if (rc == IDNO)
return;
} else {
AfxMessageBox(msg, MB_ICONSTOP);
return;
}
}
#endif
super::OnOK();
}
void CPasskeySetup::OnHelp()
{
#if defined(POCKET_PC)
CreateProcess( _T("PegHelp.exe"), _T("pws_ce_help.html#newdatabase"), NULL, NULL, FALSE, 0, NULL, NULL, NULL, NULL );
#else
//WinHelp(0x20084, HELP_CONTEXT);
::HtmlHelp(NULL,
"pwsafe.chm::/html/create_new_db.html",
HH_DISPLAY_TOPIC, 0);
#endif
}
#if defined(POCKET_PC)
/************************************************************************/
/* Restore the state of word completion when the password field loses */
/* focus. */
/************************************************************************/
void CPasskeySetup::OnPasskeyKillfocus()
{
EnableWordCompletion( m_hWnd );
}
/************************************************************************/
/* When the password field is activated, pull up the SIP and disable */
/* word completion. */
/************************************************************************/
void CPasskeySetup::OnPasskeySetfocus()
{
DisableWordCompletion( m_hWnd );
}
#endif
//-----------------------------------------------------------------------------
//-----------------------------------------------------------------------------
<commit_msg>Allowunstrong master passphrases after due warning.<commit_after>/// \file PasskeySetup.cpp
//-----------------------------------------------------------------------------
#include "stdafx.h"
#include "PasswordSafe.h"
#include "corelib/PWCharPool.h" // for CheckPassword()
#include "ThisMfcApp.h"
#include "corelib/PwsPlatform.h"
#if defined(POCKET_PC)
#include "pocketpc/resource.h"
#include "pocketpc/PocketPC.h"
#else
#include "resource.h"
#endif
#include "corelib/util.h"
#include "PasskeySetup.h"
#include "PwFont.h"
#ifdef _DEBUG
#define new DEBUG_NEW
#undef THIS_FILE
static char THIS_FILE[] = __FILE__;
#endif
//-----------------------------------------------------------------------------
CPasskeySetup::CPasskeySetup(CWnd* pParent)
: super(CPasskeySetup::IDD, pParent)
{
m_passkey = _T("");
m_verify = _T("");
}
BOOL CPasskeySetup::OnInitDialog()
{
CDialog::OnInitDialog();
SetPasswordFont(GetDlgItem(IDC_PASSKEY));
SetPasswordFont(GetDlgItem(IDC_VERIFY));
return TRUE;
}
void CPasskeySetup::DoDataExchange(CDataExchange* pDX)
{
super::DoDataExchange(pDX);
DDX_Text(pDX, IDC_PASSKEY, (CString &)m_passkey);
DDX_Text(pDX, IDC_VERIFY, (CString &)m_verify);
}
BEGIN_MESSAGE_MAP(CPasskeySetup, super)
ON_BN_CLICKED(ID_HELP, OnHelp)
#if defined(POCKET_PC)
ON_EN_SETFOCUS(IDC_PASSKEY, OnPasskeySetfocus)
ON_EN_SETFOCUS(IDC_VERIFY, OnPasskeySetfocus)
ON_EN_KILLFOCUS(IDC_PASSKEY, OnPasskeyKillfocus)
ON_EN_KILLFOCUS(IDC_VERIFY, OnPasskeyKillfocus)
#endif
END_MESSAGE_MAP()
void CPasskeySetup::OnCancel()
{
super::OnCancel();
}
void CPasskeySetup::OnOK()
{
UpdateData(TRUE);
if (m_passkey != m_verify)
{
AfxMessageBox(_T("The two entries do not match."));
((CEdit*)GetDlgItem(IDC_VERIFY))->SetFocus();
return;
}
if (m_passkey.IsEmpty())
{
AfxMessageBox(_T("Please enter a key and verify it."));
((CEdit*)GetDlgItem(IDC_PASSKEY))->SetFocus();
return;
}
// Vox populi vox dei - folks want the ability to use a weak
// passphrase, best we can do is warn them...
// If someone want to build a version that insists on proper
// passphrases, then just uncomment the following line
//#define PWS_FORCE_STRONG_PASSPHRASE
#ifndef _DEBUG // for debug, we want no checks at all, to save time
CMyString errmess;
if (!CPasswordCharPool::CheckPassword(m_passkey, errmess)) {
CString msg(_T("Weak passphrase:\n\n"));
msg += CString(errmess);
#ifndef PWS_FORCE_STRONG_PASSPHRASE
msg += _T("\nUse it anyway?");
int rc = AfxMessageBox(msg, MB_YESNO | MB_ICONSTOP);
if (rc == IDNO)
return;
#else
msg += _T("\nPlease try another");
AfxMessageBox(msg, MB_OK | MB_ICONSTOP);
return
#endif // PWS_FORCE_STRONG_PASSPHRASE
}
#endif
super::OnOK();
}
void CPasskeySetup::OnHelp()
{
#if defined(POCKET_PC)
CreateProcess( _T("PegHelp.exe"), _T("pws_ce_help.html#newdatabase"), NULL, NULL, FALSE, 0, NULL, NULL, NULL, NULL );
#else
//WinHelp(0x20084, HELP_CONTEXT);
::HtmlHelp(NULL,
"pwsafe.chm::/html/create_new_db.html",
HH_DISPLAY_TOPIC, 0);
#endif
}
#if defined(POCKET_PC)
/************************************************************************/
/* Restore the state of word completion when the password field loses */
/* focus. */
/************************************************************************/
void CPasskeySetup::OnPasskeyKillfocus()
{
EnableWordCompletion( m_hWnd );
}
/************************************************************************/
/* When the password field is activated, pull up the SIP and disable */
/* word completion. */
/************************************************************************/
void CPasskeySetup::OnPasskeySetfocus()
{
DisableWordCompletion( m_hWnd );
}
#endif
//-----------------------------------------------------------------------------
//-----------------------------------------------------------------------------
<|endoftext|>
|
<commit_before>#include "cinder/app/App.h"
#include "cinder/app/RendererGl.h"
#include "cinder/gl/gl.h"
#include "cinder/MotionManager.h"
#include "cinder/Capture.h"
#include "cinder/Log.h"
#include "GridMesh.h"
#include "CameraLandscape.h"
#include "GridTexture.h"
#include "TimeGrid.h"
#include "Landscape.h"
#include "Constants.h"
using namespace ci;
using namespace ci::app;
using namespace std;
using namespace soso;
struct TouchInfo {
uint32_t id;
vec2 previous;
vec2 position;
};
class GridSpaceApp : public App {
public:
void setup() override;
void touchesBegan( TouchEvent event ) override;
void touchesMoved( TouchEvent event ) override;
void touchesEnded( TouchEvent event ) override;
void pinchStart();
void pinchUpdate();
void pinchEnd();
void update() override;
void draw() override;
private:
GridMesh mesh;
/*
CameraLandscape cameraLandscape;
TimeGrid timeGrid;
*/
CaptureRef capture;
CameraPersp camera;
GridTextureRef gridTexture;
Landscape landscape;
bool doDrawDebug = false;
vector<TouchInfo> touches;
ci::vec3 cameraOffset;
};
void GridSpaceApp::setup()
{
mesh.setup();
MotionManager::enable();
GLint size;
glGetIntegerv( GL_MAX_TEXTURE_SIZE, &size );
CI_LOG_I( "Max texture size: " << size );
auto target = vec3( 50, 5, 50 );
camera.lookAt( vec3( 0 ), target, vec3( 0, 1, 0 ) );
camera.setPerspective( 80, getWindowAspectRatio(), 0.1f, 1000 );
try {
auto front_facing_camera = ([] {
auto &devices = Capture::getDevices();
auto first_device = devices.front();
for( auto device : devices ) {
if( device->isFrontFacing() ) {
return device;
}
}
return first_device;
}());
capture = Capture::create( 480, 360, front_facing_camera );
capture->start();
const auto divisions = 8;
const auto size = divisions * capture->getSize();
gridTexture = make_shared<GridTexture>( size.x, size.y, divisions );
}
catch( ci::Exception &exc ) {
CI_LOG_E( "Error using device camera: " << exc.what() );
}
landscape.setup();
/*
cameraLandscape.setup( gridTexture->getBlurredTexture() );
timeGrid.setup( gridTexture->getTexture() );
*/
}
void GridSpaceApp::touchesBegan( TouchEvent event )
{
for( auto &t : event.getTouches() ) {
touches.push_back( { t.getId(), t.getPos(), t.getPos() } );
}
if( touches.size() == 2 ) {
pinchStart();
}
}
void GridSpaceApp::touchesMoved( TouchEvent event )
{
for( auto &t : event.getTouches() ) {
for( auto &s : touches ) {
if( s.id == t.getId() ) {
s.previous = s.position;
s.position = t.getPos();
}
}
}
if( touches.size() == 2 ) {
pinchUpdate();
}
}
void GridSpaceApp::touchesEnded( TouchEvent event )
{
touches.erase( std::remove_if( touches.begin(), touches.end(), [&event] (const TouchInfo &s) {
for( auto &t : event.getTouches() ) {
if (t.getId() == s.id) {
return true;
}
}
return false;
}), touches.end() );
}
void GridSpaceApp::pinchStart()
{
}
void GridSpaceApp::pinchUpdate()
{
auto base = distance(touches.at( 0 ).previous, touches.at( 1 ).previous);
auto current = distance(touches.at( 0 ).position, touches.at( 1 ).position);
auto delta = current - base;
if( isfinite( delta ) )
{
auto ray = camera.getViewDirection();
cameraOffset += delta * ray * 0.01f;
}
}
void GridSpaceApp::update()
{
auto l = length(cameraOffset);
auto maximum = 3.0f;
if( l > maximum ) {
cameraOffset *= (maximum / l);
}
camera.setEyePoint( cameraOffset );
if( MotionManager::isDataAvailable() ) {
auto r = MotionManager::getRotation();
camera.setOrientation( r );
}
if( capture->checkNewFrame() ) {
gridTexture->update( *capture->getSurface() );
}
}
void GridSpaceApp::draw()
{
gl::clear( Color( 0, 0, 0 ) );
gl::enableDepthRead();
gl::enableDepthWrite();
gl::setMatrices( camera );
// TODO: bind both blurred and normal texture and avoid rebinding textures elsewhere.
gl::ScopedTextureBind tex0( gridTexture->getTexture(), 0 );
gl::ScopedTextureBind tex1( gridTexture->getBlurredTexture(), 1 );
landscape.draw( gridTexture->getCurrentIndex() );
/*
timeGrid.draw( gridTexture->getCurrentIndex() );
cameraLandscape.draw( gridTexture->getCurrentIndex() );
*/
mesh.draw( gridTexture->getCurrentIndex() );
if( doDrawDebug )
{
if( gridTexture->getTexture() )
{
auto size = vec2(getWindowSize()) * vec2(1.0, 0.5);
gl::ScopedMatrices mat;
gl::setMatricesWindow( app::getWindowSize() );
gl::draw( gridTexture->getTexture(), Rectf( vec2(0), size ) );
gl::translate( size * vec2(0, 1) );
gl::draw( gridTexture->getBlurredTexture(), Rectf( vec2(0), size ) );
}
}
}
CINDER_APP( GridSpaceApp, RendererGl )
<commit_msg>Don't draw cross mesh.<commit_after>#include "cinder/app/App.h"
#include "cinder/app/RendererGl.h"
#include "cinder/gl/gl.h"
#include "cinder/MotionManager.h"
#include "cinder/Capture.h"
#include "cinder/Log.h"
#include "GridMesh.h"
#include "CameraLandscape.h"
#include "GridTexture.h"
#include "TimeGrid.h"
#include "Landscape.h"
#include "Constants.h"
using namespace ci;
using namespace ci::app;
using namespace std;
using namespace soso;
struct TouchInfo {
uint32_t id;
vec2 previous;
vec2 position;
};
class GridSpaceApp : public App {
public:
void setup() override;
void touchesBegan( TouchEvent event ) override;
void touchesMoved( TouchEvent event ) override;
void touchesEnded( TouchEvent event ) override;
void pinchStart();
void pinchUpdate();
void pinchEnd();
void update() override;
void draw() override;
private:
GridMesh mesh;
/*
CameraLandscape cameraLandscape;
TimeGrid timeGrid;
*/
CaptureRef capture;
CameraPersp camera;
GridTextureRef gridTexture;
Landscape landscape;
bool doDrawDebug = false;
vector<TouchInfo> touches;
ci::vec3 cameraOffset;
};
void GridSpaceApp::setup()
{
MotionManager::enable();
GLint size;
glGetIntegerv( GL_MAX_TEXTURE_SIZE, &size );
CI_LOG_I( "Max texture size: " << size );
auto target = vec3( 50, 5, 50 );
camera.lookAt( vec3( 0 ), target, vec3( 0, 1, 0 ) );
camera.setPerspective( 80, getWindowAspectRatio(), 0.1f, 1000 );
try {
auto front_facing_camera = ([] {
auto &devices = Capture::getDevices();
auto first_device = devices.front();
for( auto device : devices ) {
if( device->isFrontFacing() ) {
return device;
}
}
return first_device;
}());
capture = Capture::create( 480, 360, front_facing_camera );
capture->start();
const auto divisions = 8;
const auto size = divisions * capture->getSize();
gridTexture = make_shared<GridTexture>( size.x, size.y, divisions );
}
catch( ci::Exception &exc ) {
CI_LOG_E( "Error using device camera: " << exc.what() );
}
landscape.setup();
/*
cameraLandscape.setup( gridTexture->getBlurredTexture() );
timeGrid.setup( gridTexture->getTexture() );
mesh.setup();
*/
}
void GridSpaceApp::touchesBegan( TouchEvent event )
{
for( auto &t : event.getTouches() ) {
touches.push_back( { t.getId(), t.getPos(), t.getPos() } );
}
if( touches.size() == 2 ) {
pinchStart();
}
}
void GridSpaceApp::touchesMoved( TouchEvent event )
{
for( auto &t : event.getTouches() ) {
for( auto &s : touches ) {
if( s.id == t.getId() ) {
s.previous = s.position;
s.position = t.getPos();
}
}
}
if( touches.size() == 2 ) {
pinchUpdate();
}
}
void GridSpaceApp::touchesEnded( TouchEvent event )
{
touches.erase( std::remove_if( touches.begin(), touches.end(), [&event] (const TouchInfo &s) {
for( auto &t : event.getTouches() ) {
if (t.getId() == s.id) {
return true;
}
}
return false;
}), touches.end() );
}
void GridSpaceApp::pinchStart()
{
}
void GridSpaceApp::pinchUpdate()
{
auto base = distance(touches.at( 0 ).previous, touches.at( 1 ).previous);
auto current = distance(touches.at( 0 ).position, touches.at( 1 ).position);
auto delta = current - base;
if( isfinite( delta ) )
{
auto ray = camera.getViewDirection();
cameraOffset += delta * ray * 0.01f;
}
}
void GridSpaceApp::update()
{
auto l = length(cameraOffset);
auto maximum = 3.0f;
if( l > maximum ) {
cameraOffset *= (maximum / l);
}
camera.setEyePoint( cameraOffset );
if( MotionManager::isDataAvailable() ) {
auto r = MotionManager::getRotation();
camera.setOrientation( r );
}
if( capture->checkNewFrame() ) {
gridTexture->update( *capture->getSurface() );
}
}
void GridSpaceApp::draw()
{
gl::clear( Color( 0, 0, 0 ) );
gl::enableDepthRead();
gl::enableDepthWrite();
gl::setMatrices( camera );
// TODO: bind both blurred and normal texture and avoid rebinding textures elsewhere.
gl::ScopedTextureBind tex0( gridTexture->getTexture(), 0 );
gl::ScopedTextureBind tex1( gridTexture->getBlurredTexture(), 1 );
landscape.draw( gridTexture->getCurrentIndex() );
/*
timeGrid.draw( gridTexture->getCurrentIndex() );
cameraLandscape.draw( gridTexture->getCurrentIndex() );
mesh.draw( gridTexture->getCurrentIndex() );
*/
if( doDrawDebug )
{
if( gridTexture->getTexture() )
{
auto size = vec2(getWindowSize()) * vec2(1.0, 0.5);
gl::ScopedMatrices mat;
gl::setMatricesWindow( app::getWindowSize() );
gl::draw( gridTexture->getTexture(), Rectf( vec2(0), size ) );
gl::translate( size * vec2(0, 1) );
gl::draw( gridTexture->getBlurredTexture(), Rectf( vec2(0), size ) );
}
}
}
CINDER_APP( GridSpaceApp, RendererGl )
<|endoftext|>
|
<commit_before>#include "RGBColor.h"
RGBColor::RGBColor()
: r(.0f), g(.0f), b(.0f) {
}
RGBColor::RGBColor(const float red, const float green, const float blue)
: r(red), g(green), b(blue) {
}
RGBColor::~RGBColor() {
r = .0f;
g = .0f;
b = .0f;
}<commit_msg>Added constructor with a single value<commit_after>#include "RGBColor.h"
RGBColor::RGBColor()
: r(.0f), g(.0f), b(.0f) {
}
RGBColor::RGBColor(const float rgb)
: r(rgb), g(rgb), b (rgb) {
}
RGBColor::RGBColor(const float red, const float green, const float blue)
: r(red), g(green), b(blue) {
}
RGBColor::~RGBColor() {
r = .0f;
g = .0f;
b = .0f;
}<|endoftext|>
|
<commit_before>#include "cinder/app/App.h"
#include "cinder/app/RendererGl.h"
#include "cinder/gl/gl.h"
#include "GridMesh.h"
#include "cinder/MotionManager.h"
using namespace ci;
using namespace ci::app;
using namespace std;
using namespace soso;
class GridSpaceApp : public App {
public:
void setup() override;
void mouseDown( MouseEvent event ) override;
void update() override;
void draw() override;
private:
GridMesh mesh;
CameraPersp camera;
const ci::vec3 target = vec3( 50, 5, 50 );
};
void GridSpaceApp::setup()
{
mesh.setup();
MotionManager::enable();
camera.lookAt( vec3( 0 ), target, vec3( 0, 1, 0 ) );
camera.setPerspective( 60, getWindowAspectRatio(), 0.1f, 1000 );
}
void GridSpaceApp::mouseDown( MouseEvent event )
{
}
void GridSpaceApp::update()
{
if( MotionManager::isDataAvailable() ) {
auto rotated_target = MotionManager::getRotationMatrix() * vec4( target, 0 );
camera.lookAt( vec3( 0 ), vec3( rotated_target ), vec3( 0, 1, 0 ) );
}
}
void GridSpaceApp::draw()
{
gl::clear( Color( 0, 0, 0 ) );
gl::enableDepthRead();
gl::enableDepthWrite();
gl::setMatrices( camera );
mesh.draw();
gl::setMatricesWindowPersp( getWindowSize() );
gl::translate( vec3( getWindowCenter(), 0 ) );
gl::rotate( MotionManager::getRotation() );
gl::drawVector( vec3( 0 ), target );
gl::scale( vec3( 50 ) );
gl::drawCoordinateFrame();
}
CINDER_APP( GridSpaceApp, RendererGl )
<commit_msg>Camera::setOrientation works nicely.<commit_after>#include "cinder/app/App.h"
#include "cinder/app/RendererGl.h"
#include "cinder/gl/gl.h"
#include "GridMesh.h"
#include "cinder/MotionManager.h"
using namespace ci;
using namespace ci::app;
using namespace std;
using namespace soso;
class GridSpaceApp : public App {
public:
void setup() override;
void mouseDown( MouseEvent event ) override;
void update() override;
void draw() override;
private:
GridMesh mesh;
CameraPersp camera;
const ci::vec3 target = vec3( 50, 5, 50 );
};
void GridSpaceApp::setup()
{
mesh.setup();
MotionManager::enable();
camera.lookAt( vec3( 0 ), target, vec3( 0, 1, 0 ) );
camera.setPerspective( 60, getWindowAspectRatio(), 0.1f, 1000 );
}
void GridSpaceApp::mouseDown( MouseEvent event )
{
}
void GridSpaceApp::update()
{
if( MotionManager::isDataAvailable() ) {
auto r = MotionManager::getRotation();
camera.setOrientation( r );
}
}
void GridSpaceApp::draw()
{
gl::clear( Color( 0, 0, 0 ) );
gl::enableDepthRead();
gl::enableDepthWrite();
gl::setMatrices( camera );
mesh.draw();
gl::setMatricesWindowPersp( getWindowSize() );
gl::translate( vec3( getWindowCenter(), 0 ) );
gl::rotate( MotionManager::getRotation() );
gl::drawCube( vec3( 0 ), vec3( 50, 100, 5 ) );
gl::scale( vec3( 50 ) );
gl::drawCoordinateFrame();
}
CINDER_APP( GridSpaceApp, RendererGl )
<|endoftext|>
|
<commit_before>/**
* @file mega/posix/drivenotifyposix.cpp
* @brief Mega SDK various utilities and helper classes
*
* (c) 2013-2020 by Mega Limited, Auckland, New Zealand
*
* This file is part of the MEGA SDK - Client Access Engine.
*
* Applications using the MEGA API must present a valid application key
* and comply with the the rules set forth in the Terms of Service.
*
* The MEGA SDK is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
*
* @copyright Simplified (2-clause) BSD License.
*
* You should have received a copy of the license along with this
* program.
*/
#ifdef USE_DRIVE_NOTIFICATIONS
#include "mega/drivenotify.h"
#include <libudev.h> // Ubuntu: sudo apt-get install libudev-dev
#include <mntent.h>
#include <cstring>
#include <chrono>
namespace mega {
//
// DriveNotifyPosix
/////////////////////////////////////////////
bool DriveNotifyPosix::notifierSetup()
{
// init udev resource
mUdev = udev_new();
if (!mUdev) return false; // is udevd daemon running?
// init udev monitor
mUdevMon = udev_monitor_new_from_netlink(mUdev, "udev");
if (!mUdevMon)
{
udev_unref(mUdev);
mUdev = nullptr;
return false;
}
cacheMountedPartitions();
// On unix systems you need to define your udev rules to allow notifications for
// your device.
//
// i.e. on Ubuntu create file "100-megasync-udev.rules" either in
// /etc/udev/rules.d/ OR
// /usr/lib/udev/rules.d/
// and add line:
// SUBSYSTEM=="block", ATTRS{idDevtype}=="partition"
udev_monitor_filter_add_match_subsystem_devtype(mUdevMon, "block", "partition");
udev_monitor_enable_receiving(mUdevMon);
return true;
}
void DriveNotifyPosix::notifierTeardown()
{
// release udev monitor
if (mUdevMon)
{
udev_monitor_filter_remove(mUdevMon);
udev_monitor_unref(mUdevMon);
mUdevMon = nullptr;
}
// release udev resource
if (mUdev)
{
udev_unref(mUdev);
mUdev = nullptr;
}
mMounted.clear();
}
void DriveNotifyPosix::doInThread()
{
int fd = udev_monitor_get_fd(mUdevMon);
while (!shouldStop())
{
// use a blocking call, with a timeout, to check for device events
fd_set fds;
FD_ZERO(&fds);
FD_SET(fd, &fds);
timeval tv;
tv.tv_sec = 0;
tv.tv_usec = 250 * 1000; // 250ms
int ret = select(fd+1, &fds, nullptr, nullptr, &tv);
if (ret <= 0 || !FD_ISSET(fd, &fds)) continue;
// get any [dis]connected device
udev_device* dev = udev_monitor_receive_device(mUdevMon);
if (dev)
{
evaluateDevice(dev);
udev_device_unref(dev);
}
}
}
void DriveNotifyPosix::evaluateDevice(udev_device* dev) // dev must Not be null
{
// filter "partition" events
const char* devtype = udev_device_get_devtype(dev); // "partition"
if(strcmp(devtype, "partition")) return;
// filter "add"/"remove" actions
const char* action = udev_device_get_action(dev); // "add" / "remove"
bool added = !strcmp(action, "add");
bool removed = !added && !strcmp(action, "remove");
if (!(added || removed)) return; // ignore other possible actions
// get device location
const char* devNode = udev_device_get_devnode(dev); // "/dev/sda1"
if (!devNode) return; // did something go wrong?
const std::string& devNodeStr(devNode);
// gather drive info
DriveInfo drvInfo;
drvInfo.connected = added;
// get the mount point
if (removed)
{
// get it from the cache, because it will have already been removed from
// the relevant locations by the time getMountPoint() will attempt to read it
drvInfo.mountPoint = mMounted[devNodeStr];
mMounted.erase(devNodeStr); // remove from cache
}
else // added
{
// reading it might happen before the relevant locations have been updated,
// so allow retrying a few times, say at 100ms intervals
for (int i = 0; i < 5; ++i)
{
drvInfo.mountPoint = getMountPoint(devNodeStr);
if (!drvInfo.mountPoint.empty())
{
mMounted[devNodeStr] = drvInfo.mountPoint; // cache it
break;
}
std::this_thread::sleep_for(std::chrono::milliseconds(100));
}
}
// send notification
if (!drvInfo.mountPoint.empty())
{
add(std::move(drvInfo));
}
}
std::string DriveNotifyPosix::getMountPoint(const std::string& device)
{
std::string mountPoint;
// go to all mounts
FILE* fsMounts = setmntent("/proc/mounts", "r");
if (!fsMounts) // this should never happen
{
// make another attempt
fsMounts = setmntent("/etc/mtab", "r");
if (!fsMounts) return mountPoint;
}
// search mount point for the current device
for (mntent* mnt = getmntent(fsMounts); mnt; mnt = getmntent(fsMounts))
{
if (device == mnt->mnt_fsname)
{
mountPoint = mnt->mnt_dir;
break;
}
}
endmntent(fsMounts); // closes the file descriptor
return mountPoint;
}
void DriveNotifyPosix::cacheMountedPartitions()
{
// enumerate all mounted partitions
udev_enumerate* enumerate = udev_enumerate_new(mUdev);
udev_enumerate_add_match_subsystem(enumerate, "block");
udev_enumerate_add_match_property(enumerate, "DEVTYPE", "partition");
udev_enumerate_scan_devices(enumerate);
udev_list_entry *devices = udev_enumerate_get_list_entry(enumerate);
udev_list_entry *entry;
udev_list_entry_foreach(entry, devices) // for loop
{
// get a partition
const char* entryName = udev_list_entry_get_name(entry);
udev_device* blockDev = udev_device_new_from_syspath(mUdev, entryName);
if (!blockDev) continue;
// filter only removable ones
if (isRemovable(blockDev))
{
// get partition node
const char* devNode = udev_device_get_devnode(blockDev); // "/dev/sda1"
// cache mount point
std::string mountPoint = getMountPoint(devNode);
if (!mountPoint.empty())
{
mMounted[devNode] = mountPoint;
}
}
udev_device_unref(blockDev);
}
udev_enumerate_unref(enumerate);
}
bool DriveNotifyPosix::isRemovable(udev_device* part)
{
udev_device* parent = udev_device_get_parent(part); // do not unref this one!
if (!parent) return false;
const char* removable = udev_device_get_sysattr_value(parent, "removable");
return removable && !strcmp(removable, "1");
}
} // namespace
#endif // USE_DRIVE_NOTIFICATIONS
<commit_msg>Add null pointer checks<commit_after>/**
* @file mega/posix/drivenotifyposix.cpp
* @brief Mega SDK various utilities and helper classes
*
* (c) 2013-2020 by Mega Limited, Auckland, New Zealand
*
* This file is part of the MEGA SDK - Client Access Engine.
*
* Applications using the MEGA API must present a valid application key
* and comply with the the rules set forth in the Terms of Service.
*
* The MEGA SDK is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
*
* @copyright Simplified (2-clause) BSD License.
*
* You should have received a copy of the license along with this
* program.
*/
#ifdef USE_DRIVE_NOTIFICATIONS
#include "mega/drivenotify.h"
#include <libudev.h> // Ubuntu: sudo apt-get install libudev-dev
#include <mntent.h>
#include <cstring>
#include <chrono>
namespace mega {
//
// DriveNotifyPosix
/////////////////////////////////////////////
bool DriveNotifyPosix::notifierSetup()
{
// init udev resource
mUdev = udev_new();
if (!mUdev) return false; // is udevd daemon running?
// init udev monitor
mUdevMon = udev_monitor_new_from_netlink(mUdev, "udev");
if (!mUdevMon)
{
udev_unref(mUdev);
mUdev = nullptr;
return false;
}
cacheMountedPartitions();
// On unix systems you need to define your udev rules to allow notifications for
// your device.
//
// i.e. on Ubuntu create file "100-megasync-udev.rules" either in
// /etc/udev/rules.d/ OR
// /usr/lib/udev/rules.d/
// and add line:
// SUBSYSTEM=="block", ATTRS{idDevtype}=="partition"
udev_monitor_filter_add_match_subsystem_devtype(mUdevMon, "block", "partition");
udev_monitor_enable_receiving(mUdevMon);
return true;
}
void DriveNotifyPosix::notifierTeardown()
{
// release udev monitor
if (mUdevMon)
{
udev_monitor_filter_remove(mUdevMon);
udev_monitor_unref(mUdevMon);
mUdevMon = nullptr;
}
// release udev resource
if (mUdev)
{
udev_unref(mUdev);
mUdev = nullptr;
}
mMounted.clear();
}
void DriveNotifyPosix::doInThread()
{
int fd = udev_monitor_get_fd(mUdevMon);
while (!shouldStop())
{
// use a blocking call, with a timeout, to check for device events
fd_set fds;
FD_ZERO(&fds);
FD_SET(fd, &fds);
timeval tv;
tv.tv_sec = 0;
tv.tv_usec = 250 * 1000; // 250ms
int ret = select(fd+1, &fds, nullptr, nullptr, &tv);
if (ret <= 0 || !FD_ISSET(fd, &fds)) continue;
// get any [dis]connected device
udev_device* dev = udev_monitor_receive_device(mUdevMon);
if (dev)
{
evaluateDevice(dev);
udev_device_unref(dev);
}
}
}
void DriveNotifyPosix::evaluateDevice(udev_device* dev) // dev must Not be null
{
// filter "partition" events
const char* devtype = udev_device_get_devtype(dev); // "partition"
if (!devtype || strcmp(devtype, "partition")) return;
// filter "add"/"remove" actions
const char* action = udev_device_get_action(dev); // "add" / "remove"
bool added = action && !strcmp(action, "add");
bool removed = action && !added && !strcmp(action, "remove");
if (!(added || removed)) return; // ignore other possible actions
// get device location
const char* devNode = udev_device_get_devnode(dev); // "/dev/sda1"
if (!devNode) return; // did something go wrong?
const std::string& devNodeStr(devNode);
// gather drive info
DriveInfo drvInfo;
drvInfo.connected = added;
// get the mount point
if (removed)
{
// get it from the cache, because it will have already been removed from
// the relevant locations by the time getMountPoint() will attempt to read it
drvInfo.mountPoint = mMounted[devNodeStr];
mMounted.erase(devNodeStr); // remove from cache
}
else // added
{
// reading it might happen before the relevant locations have been updated,
// so allow retrying a few times, say at 100ms intervals
for (int i = 0; i < 5; ++i)
{
drvInfo.mountPoint = getMountPoint(devNodeStr);
if (!drvInfo.mountPoint.empty())
{
mMounted[devNodeStr] = drvInfo.mountPoint; // cache it
break;
}
std::this_thread::sleep_for(std::chrono::milliseconds(100));
}
}
// send notification
if (!drvInfo.mountPoint.empty())
{
add(std::move(drvInfo));
}
}
std::string DriveNotifyPosix::getMountPoint(const std::string& device)
{
std::string mountPoint;
// go to all mounts
FILE* fsMounts = setmntent("/proc/mounts", "r");
if (!fsMounts) // this should never happen
{
// make another attempt
fsMounts = setmntent("/etc/mtab", "r");
if (!fsMounts) return mountPoint;
}
// search mount point for the current device
for (mntent* mnt = getmntent(fsMounts); mnt; mnt = getmntent(fsMounts))
{
if (device == mnt->mnt_fsname)
{
mountPoint = mnt->mnt_dir;
break;
}
}
endmntent(fsMounts); // closes the file descriptor
return mountPoint;
}
void DriveNotifyPosix::cacheMountedPartitions()
{
// enumerate all mounted partitions
udev_enumerate* enumerate = udev_enumerate_new(mUdev);
udev_enumerate_add_match_subsystem(enumerate, "block");
udev_enumerate_add_match_property(enumerate, "DEVTYPE", "partition");
udev_enumerate_scan_devices(enumerate);
udev_list_entry *devices = udev_enumerate_get_list_entry(enumerate);
udev_list_entry *entry;
udev_list_entry_foreach(entry, devices) // for loop
{
// get a partition
const char* entryName = udev_list_entry_get_name(entry);
udev_device* blockDev = udev_device_new_from_syspath(mUdev, entryName);
if (!blockDev) continue;
// filter only removable ones
if (isRemovable(blockDev))
{
// get partition node
const char* devNode = udev_device_get_devnode(blockDev); // "/dev/sda1"
// cache mount point
std::string mountPoint = getMountPoint(devNode);
if (!mountPoint.empty())
{
mMounted[devNode] = mountPoint;
}
}
udev_device_unref(blockDev);
}
udev_enumerate_unref(enumerate);
}
bool DriveNotifyPosix::isRemovable(udev_device* part)
{
udev_device* parent = udev_device_get_parent(part); // do not unref this one!
if (!parent) return false;
const char* removable = udev_device_get_sysattr_value(parent, "removable");
return removable && !strcmp(removable, "1");
}
} // namespace
#endif // USE_DRIVE_NOTIFICATIONS
<|endoftext|>
|
<commit_before>#include "application.h"
#include "Adafruit_LEDBackpack.h"
Adafruit_8x8matrix matrix1;
Adafruit_8x8matrix matrix2;
Adafruit_8x8matrix matrix3;
static const uint8_t smile[] = {
0b00111100,
0b01000010,
0b10100101,
0b10000001,
0b10100101,
0b10011001,
0b01000010,
0b00111100
};
void setup()
{
Wire.begin();
matrix1.begin(0x70);
matrix2.begin(0x71);
matrix3.begin(0x72);
}
void loop()
{
matrix1.clear();
delay(500);
matrix1.drawBitmap(0, 0, smile, 8, 8, LED_ON);
matrix1.writeDisplay();
delay(500);
}
<commit_msg>Add Spark function and variables<commit_after>#include "application.h"
#include "Adafruit_LEDBackpack.h"
Adafruit_8x8matrix matrix1;
Adafruit_8x8matrix matrix2;
Adafruit_8x8matrix matrix3;
static const uint8_t smile[] = {
0b00111100,
0b01000010,
0b10100101,
0b10000001,
0b10100101,
0b10011001,
0b01000010,
0b00111100
};
int currentTemperature = 0;
int desiredTemperature = 0;
bool isHeatOn = false;
bool isFanOn = false;
int setTemperature(String t)
{
return 1;
}
void setup()
{
Wire.begin();
matrix1.begin(0x70);
matrix2.begin(0x71);
matrix3.begin(0x72);
Spark.function("set_temp", setTemperature);
Spark.variable("current_temp", ¤tTemperature, INT);
Spark.variable("desired_temp", &desiredTemperature, INT);
Spark.variable("is_heat_on", &isHeatOn, BOOLEAN);
Spark.variable("is_fan_on", &isFanOn, BOOLEAN);
}
void loop()
{
matrix3.clear();
matrix3.drawBitmap(0, 0, smile, 8, 8, LED_ON);
matrix3.writeDisplay();
delay(500);
}
<|endoftext|>
|
<commit_before>// Copyright (c) 2009-2015 The Bitcoin Core developers
// Distributed under the MIT software license, see the accompanying
// file COPYING or http://www.opensource.org/licenses/mit-license.php.
#include "primitives/transaction.h"
#include "hash.h"
#include "tinyformat.h"
#include "utilstrencodings.h"
std::string COutPoint::ToString() const
{
return strprintf("COutPoint(%s, %u)", hash.ToString()/*.substr(0,10)*/, n);
}
std::string COutPoint::ToStringShort() const
{
return strprintf("%s-%u", hash.ToString().substr(0,64), n);
}
CTxIn::CTxIn(COutPoint prevoutIn, CScript scriptSigIn, uint32_t nSequenceIn)
{
prevout = prevoutIn;
scriptSig = scriptSigIn;
nSequence = nSequenceIn;
}
CTxIn::CTxIn(uint256 hashPrevTx, uint32_t nOut, CScript scriptSigIn, uint32_t nSequenceIn)
{
prevout = COutPoint(hashPrevTx, nOut);
scriptSig = scriptSigIn;
nSequence = nSequenceIn;
}
std::string CTxIn::ToString() const
{
std::string str;
str += "CTxIn(";
str += prevout.ToString();
if (prevout.IsNull())
str += strprintf(", coinbase %s", HexStr(scriptSig));
else
str += strprintf(", scriptSig=%s", HexStr(scriptSig).substr(0, 24));
if (nSequence != SEQUENCE_FINAL)
str += strprintf(", nSequence=%u", nSequence);
str += ")";
return str;
}
CTxOut::CTxOut(const CAmount& nValueIn, CScript scriptPubKeyIn)
{
nValue = nValueIn;
scriptPubKey = scriptPubKeyIn;
nRounds = -10;
}
uint256 CTxOut::GetHash() const
{
return SerializeHash(*this);
}
std::string CTxOut::ToString() const
{
// 12-12-2018 - R ANDREWS - Show User the vOut ordinal
std::string IsPog = (Contains(sTxOutMessage, "<POG>")) ? "POG" : "";
return strprintf("CTxOut(nValue=%d.%08d, scriptPubKey=%s) %s", nValue / COIN, nValue % COIN, HexStr(scriptPubKey).substr(0, 30), IsPog);
}
CMutableTransaction::CMutableTransaction() : nVersion(CTransaction::CURRENT_VERSION), nLockTime(0) {}
CMutableTransaction::CMutableTransaction(const CTransaction& tx) : nVersion(tx.nVersion), vin(tx.vin), vout(tx.vout), nLockTime(tx.nLockTime) {}
uint256 CMutableTransaction::GetHash() const
{
return SerializeHash(*this);
}
std::string CMutableTransaction::ToString() const
{
std::string str;
str += strprintf("CMutableTransaction(hash=%s, ver=%d, vin.size=%u, vout.size=%u, nLockTime=%u)\n",
GetHash().ToString().substr(0,10),
nVersion,
vin.size(),
vout.size(),
nLockTime);
for (unsigned int i = 0; i < vin.size(); i++)
str += " " + vin[i].ToString() + "\n";
for (unsigned int i = 0; i < vout.size(); i++)
str += " " + vout[i].ToString() + "\n";
return str;
}
void CTransaction::UpdateHash() const
{
*const_cast<uint256*>(&hash) = SerializeHash(*this);
}
CTransaction::CTransaction() : nVersion(CTransaction::CURRENT_VERSION), vin(), vout(), nLockTime(0) { }
CTransaction::CTransaction(const CMutableTransaction &tx) : nVersion(tx.nVersion), vin(tx.vin), vout(tx.vout), nLockTime(tx.nLockTime) {
UpdateHash();
}
CTransaction& CTransaction::operator=(const CTransaction &tx) {
*const_cast<int*>(&nVersion) = tx.nVersion;
*const_cast<std::vector<CTxIn>*>(&vin) = tx.vin;
*const_cast<std::vector<CTxOut>*>(&vout) = tx.vout;
*const_cast<unsigned int*>(&nLockTime) = tx.nLockTime;
*const_cast<uint256*>(&hash) = tx.hash;
return *this;
}
CAmount CTransaction::GetValueOut() const
{
CAmount nValueOut = 0;
for (std::vector<CTxOut>::const_iterator it(vout.begin()); it != vout.end(); ++it)
{
nValueOut += it->nValue;
if (!MoneyRange(it->nValue) || !MoneyRange(nValueOut))
throw std::runtime_error("CTransaction::GetValueOut(): value out of range");
}
return nValueOut;
}
double CTransaction::ComputePriority(double dPriorityInputs, unsigned int nTxSize) const
{
nTxSize = CalculateModifiedSize(nTxSize);
if (nTxSize == 0) return 0.0;
return dPriorityInputs / nTxSize;
}
unsigned int CTransaction::CalculateModifiedSize(unsigned int nTxSize) const
{
// In order to avoid disincentivizing cleaning up the UTXO set we don't count
// the constant overhead for each txin and up to 110 bytes of scriptSig (which
// is enough to cover a compressed pubkey p2sh redemption) for priority.
// Providing any more cleanup incentive than making additional inputs free would
// risk encouraging people to create junk outputs to redeem later.
if (nTxSize == 0)
nTxSize = ::GetSerializeSize(*this, SER_NETWORK, PROTOCOL_VERSION);
for (std::vector<CTxIn>::const_iterator it(vin.begin()); it != vin.end(); ++it)
{
unsigned int offset = 41U + std::min(110U, (unsigned int)it->scriptSig.size());
if (nTxSize > offset)
nTxSize -= offset;
}
return nTxSize;
}
std::string CTransaction::ToString() const
{
std::string str;
str += strprintf("CTransaction(hash=%s, ver=%d, vin.size=%u, vout.size=%u, nLockTime=%u)\n",
GetHash().ToString().substr(0,10),
nVersion,
vin.size(),
vout.size(),
nLockTime);
for (unsigned int i = 0; i < vin.size(); i++)
str += " " + vin[i].ToString() + "\n";
for (unsigned int i = 0; i < vout.size(); i++)
str += " " + vout[i].ToString() + "\n";
return str;
}
<commit_msg>1.1.6.4f-Leisure Upgrade<commit_after>// Copyright (c) 2009-2015 The Bitcoin Core developers
// Distributed under the MIT software license, see the accompanying
// file COPYING or http://www.opensource.org/licenses/mit-license.php.
#include "primitives/transaction.h"
#include "hash.h"
#include "tinyformat.h"
#include "utilstrencodings.h"
bool Contains(std::string data, std::string instring);
std::string COutPoint::ToString() const
{
return strprintf("COutPoint(%s, %u)", hash.ToString()/*.substr(0,10)*/, n);
}
std::string COutPoint::ToStringShort() const
{
return strprintf("%s-%u", hash.ToString().substr(0,64), n);
}
CTxIn::CTxIn(COutPoint prevoutIn, CScript scriptSigIn, uint32_t nSequenceIn)
{
prevout = prevoutIn;
scriptSig = scriptSigIn;
nSequence = nSequenceIn;
}
CTxIn::CTxIn(uint256 hashPrevTx, uint32_t nOut, CScript scriptSigIn, uint32_t nSequenceIn)
{
prevout = COutPoint(hashPrevTx, nOut);
scriptSig = scriptSigIn;
nSequence = nSequenceIn;
}
std::string CTxIn::ToString() const
{
std::string str;
str += "CTxIn(";
str += prevout.ToString();
if (prevout.IsNull())
str += strprintf(", coinbase %s", HexStr(scriptSig));
else
str += strprintf(", scriptSig=%s", HexStr(scriptSig).substr(0, 24));
if (nSequence != SEQUENCE_FINAL)
str += strprintf(", nSequence=%u", nSequence);
str += ")";
return str;
}
CTxOut::CTxOut(const CAmount& nValueIn, CScript scriptPubKeyIn)
{
nValue = nValueIn;
scriptPubKey = scriptPubKeyIn;
nRounds = -10;
}
uint256 CTxOut::GetHash() const
{
return SerializeHash(*this);
}
std::string CTxOut::ToString() const
{
// 12-12-2018 - R ANDREWS - Show User the vOut ordinal
std::string IsPog = (Contains(sTxOutMessage, "<POG>")) ? "POG" : "";
return strprintf("CTxOut(nValue=%d.%08d, scriptPubKey=%s) %s", nValue / COIN, nValue % COIN, HexStr(scriptPubKey).substr(0, 30), IsPog);
}
CMutableTransaction::CMutableTransaction() : nVersion(CTransaction::CURRENT_VERSION), nLockTime(0) {}
CMutableTransaction::CMutableTransaction(const CTransaction& tx) : nVersion(tx.nVersion), vin(tx.vin), vout(tx.vout), nLockTime(tx.nLockTime) {}
uint256 CMutableTransaction::GetHash() const
{
return SerializeHash(*this);
}
std::string CMutableTransaction::ToString() const
{
std::string str;
str += strprintf("CMutableTransaction(hash=%s, ver=%d, vin.size=%u, vout.size=%u, nLockTime=%u)\n",
GetHash().ToString().substr(0,10),
nVersion,
vin.size(),
vout.size(),
nLockTime);
for (unsigned int i = 0; i < vin.size(); i++)
str += " " + vin[i].ToString() + "\n";
for (unsigned int i = 0; i < vout.size(); i++)
str += " " + vout[i].ToString() + "\n";
return str;
}
void CTransaction::UpdateHash() const
{
*const_cast<uint256*>(&hash) = SerializeHash(*this);
}
CTransaction::CTransaction() : nVersion(CTransaction::CURRENT_VERSION), vin(), vout(), nLockTime(0) { }
CTransaction::CTransaction(const CMutableTransaction &tx) : nVersion(tx.nVersion), vin(tx.vin), vout(tx.vout), nLockTime(tx.nLockTime) {
UpdateHash();
}
CTransaction& CTransaction::operator=(const CTransaction &tx) {
*const_cast<int*>(&nVersion) = tx.nVersion;
*const_cast<std::vector<CTxIn>*>(&vin) = tx.vin;
*const_cast<std::vector<CTxOut>*>(&vout) = tx.vout;
*const_cast<unsigned int*>(&nLockTime) = tx.nLockTime;
*const_cast<uint256*>(&hash) = tx.hash;
return *this;
}
CAmount CTransaction::GetValueOut() const
{
CAmount nValueOut = 0;
for (std::vector<CTxOut>::const_iterator it(vout.begin()); it != vout.end(); ++it)
{
nValueOut += it->nValue;
if (!MoneyRange(it->nValue) || !MoneyRange(nValueOut))
throw std::runtime_error("CTransaction::GetValueOut(): value out of range");
}
return nValueOut;
}
double CTransaction::ComputePriority(double dPriorityInputs, unsigned int nTxSize) const
{
nTxSize = CalculateModifiedSize(nTxSize);
if (nTxSize == 0) return 0.0;
return dPriorityInputs / nTxSize;
}
unsigned int CTransaction::CalculateModifiedSize(unsigned int nTxSize) const
{
// In order to avoid disincentivizing cleaning up the UTXO set we don't count
// the constant overhead for each txin and up to 110 bytes of scriptSig (which
// is enough to cover a compressed pubkey p2sh redemption) for priority.
// Providing any more cleanup incentive than making additional inputs free would
// risk encouraging people to create junk outputs to redeem later.
if (nTxSize == 0)
nTxSize = ::GetSerializeSize(*this, SER_NETWORK, PROTOCOL_VERSION);
for (std::vector<CTxIn>::const_iterator it(vin.begin()); it != vin.end(); ++it)
{
unsigned int offset = 41U + std::min(110U, (unsigned int)it->scriptSig.size());
if (nTxSize > offset)
nTxSize -= offset;
}
return nTxSize;
}
std::string CTransaction::ToString() const
{
std::string str;
str += strprintf("CTransaction(hash=%s, ver=%d, vin.size=%u, vout.size=%u, nLockTime=%u)\n",
GetHash().ToString().substr(0,10),
nVersion,
vin.size(),
vout.size(),
nLockTime);
for (unsigned int i = 0; i < vin.size(); i++)
str += " " + vin[i].ToString() + "\n";
for (unsigned int i = 0; i < vout.size(); i++)
str += " " + vout[i].ToString() + "\n";
return str;
}
<|endoftext|>
|
<commit_before>// Copyright 2018 Google Inc. All Rights Reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
#include <unordered_map>
#include "class_names.h"
#include "compiler_helpers.h"
#include "dbg_primitive.h"
#include "i_cor_debug_helper.h"
#include "type_signature.h"
namespace google_cloud_debugger {
bool NumericCompilerHelper::IsImplicitNumericConversionable(
const TypeSignature &source, const TypeSignature &target) {
const CorElementType &source_type = source.cor_type;
const CorElementType &target_type = target.cor_type;
// Most of the logic here is from implicit numeric conversions:
// https://docs.microsoft.com/en-us/dotnet/csharp/language-reference/language-specification/conversions#implicit-conversions
switch (source_type) {
case CorElementType::ELEMENT_TYPE_I1: {
switch (target_type) {
case CorElementType::ELEMENT_TYPE_I1:
case CorElementType::ELEMENT_TYPE_I2:
case CorElementType::ELEMENT_TYPE_I4:
case CorElementType::ELEMENT_TYPE_I8:
case CorElementType::ELEMENT_TYPE_R4:
case CorElementType::ELEMENT_TYPE_R8:
return true;
default:
return false;
}
}
case CorElementType::ELEMENT_TYPE_U1: {
switch (target_type) {
case CorElementType::ELEMENT_TYPE_U1:
case CorElementType::ELEMENT_TYPE_I2:
case CorElementType::ELEMENT_TYPE_U2:
case CorElementType::ELEMENT_TYPE_I4:
case CorElementType::ELEMENT_TYPE_U4:
case CorElementType::ELEMENT_TYPE_I8:
case CorElementType::ELEMENT_TYPE_U8:
case CorElementType::ELEMENT_TYPE_R4:
case CorElementType::ELEMENT_TYPE_R8:
return true;
default:
return false;
}
}
case CorElementType::ELEMENT_TYPE_I2: {
switch (target_type) {
case CorElementType::ELEMENT_TYPE_I2:
case CorElementType::ELEMENT_TYPE_I4:
case CorElementType::ELEMENT_TYPE_I8:
case CorElementType::ELEMENT_TYPE_R4:
case CorElementType::ELEMENT_TYPE_R8:
return true;
default:
return false;
}
}
case CorElementType::ELEMENT_TYPE_U2: {
switch (target_type) {
case CorElementType::ELEMENT_TYPE_U2:
case CorElementType::ELEMENT_TYPE_I4:
case CorElementType::ELEMENT_TYPE_U4:
case CorElementType::ELEMENT_TYPE_I8:
case CorElementType::ELEMENT_TYPE_U8:
case CorElementType::ELEMENT_TYPE_R4:
case CorElementType::ELEMENT_TYPE_R8:
return true;
default:
return false;
}
}
case CorElementType::ELEMENT_TYPE_I4: {
switch (target_type) {
case CorElementType::ELEMENT_TYPE_I4:
case CorElementType::ELEMENT_TYPE_I8:
case CorElementType::ELEMENT_TYPE_R4:
case CorElementType::ELEMENT_TYPE_R8:
return true;
default:
return false;
}
}
case CorElementType::ELEMENT_TYPE_U4: {
switch (target_type) {
case CorElementType::ELEMENT_TYPE_U4:
case CorElementType::ELEMENT_TYPE_I8:
case CorElementType::ELEMENT_TYPE_U8:
case CorElementType::ELEMENT_TYPE_R4:
case CorElementType::ELEMENT_TYPE_R8:
return true;
default:
return false;
}
}
case CorElementType::ELEMENT_TYPE_I8: {
switch (target_type) {
case CorElementType::ELEMENT_TYPE_I8:
case CorElementType::ELEMENT_TYPE_R4:
case CorElementType::ELEMENT_TYPE_R8:
return true;
default:
return false;
}
}
case CorElementType::ELEMENT_TYPE_U8: {
switch (target_type) {
case CorElementType::ELEMENT_TYPE_U8:
case CorElementType::ELEMENT_TYPE_R4:
case CorElementType::ELEMENT_TYPE_R8:
return true;
default:
return false;
}
}
case CorElementType::ELEMENT_TYPE_CHAR: {
switch (target_type) {
case CorElementType::ELEMENT_TYPE_CHAR:
case CorElementType::ELEMENT_TYPE_U2:
case CorElementType::ELEMENT_TYPE_I4:
case CorElementType::ELEMENT_TYPE_U4:
case CorElementType::ELEMENT_TYPE_I8:
case CorElementType::ELEMENT_TYPE_U8:
case CorElementType::ELEMENT_TYPE_R4:
case CorElementType::ELEMENT_TYPE_R8:
return true;
default:
return false;
}
}
case CorElementType::ELEMENT_TYPE_R4: {
switch (target_type) {
case CorElementType::ELEMENT_TYPE_R4:
case CorElementType::ELEMENT_TYPE_R8:
return true;
default:
return false;
}
}
case CorElementType::ELEMENT_TYPE_R8: {
switch (target_type) {
case CorElementType::ELEMENT_TYPE_R8:
return true;
default:
return false;
}
}
default:
return false;
}
}
bool NumericCompilerHelper::IsNumericallyPromotedToInt(
const CorElementType &source) {
return source == CorElementType::ELEMENT_TYPE_CHAR ||
source == CorElementType::ELEMENT_TYPE_I1 ||
source == CorElementType::ELEMENT_TYPE_U1 ||
source == CorElementType::ELEMENT_TYPE_I2;
}
// Returns true for I1, I2, I4 and I8 types.
inline bool IsSignedIntegralType(const CorElementType &element_type) {
return element_type == CorElementType::ELEMENT_TYPE_I1 ||
element_type == CorElementType::ELEMENT_TYPE_I2 ||
element_type == CorElementType::ELEMENT_TYPE_I4 ||
element_type == CorElementType::ELEMENT_TYPE_I8;
}
bool NumericCompilerHelper::BinaryNumericalPromotion(const CorElementType &arg1,
const CorElementType &arg2,
CorElementType *result,
std::ostream *err_stream) {
if (!TypeCompilerHelper::IsNumericalType(arg1) &&
!TypeCompilerHelper::IsNumericalType(arg2)) {
*err_stream << "Both arguments has to be of numerical types.";
return false;
}
// TODO(quoct): Add support for Decimal.
if (arg1 == CorElementType::ELEMENT_TYPE_R8 ||
arg2 == CorElementType::ELEMENT_TYPE_R8) {
*result = CorElementType::ELEMENT_TYPE_R8;
return true;
} else if (arg1 == CorElementType::ELEMENT_TYPE_R4 ||
arg2 == CorElementType::ELEMENT_TYPE_R4) {
*result = CorElementType::ELEMENT_TYPE_R4;
return true;
} else if (arg1 == CorElementType::ELEMENT_TYPE_U8 ||
arg2 == CorElementType::ELEMENT_TYPE_U8) {
// If the other operand is of type sbyte, short, int or long,
// an error will occur. This is because no integral type exists that can
// represent the full range of ulong as well as the signed integral types.
if (IsSignedIntegralType(arg1) || IsSignedIntegralType(arg2)) {
*err_stream << "If one of the argument is an unsigned long, "
<< "the other cannot be a signed integral type.";
return false;
}
*result = CorElementType::ELEMENT_TYPE_U8;
return true;
} else if (arg1 == CorElementType::ELEMENT_TYPE_I8 ||
arg2 == CorElementType::ELEMENT_TYPE_I8) {
*result = CorElementType::ELEMENT_TYPE_I8;
return true;
} else if (arg1 == CorElementType::ELEMENT_TYPE_U4 ||
arg2 == CorElementType::ELEMENT_TYPE_U4) {
// If 1 of the operand is sbyte, short or int,
// the result will be long. We can simply call
// IsSignedIntegralType without worrying about arg1
// being an I8 type because that is already checked above.
if (IsSignedIntegralType(arg1)) {
*result = CorElementType::ELEMENT_TYPE_I8;
return true;
}
if (IsSignedIntegralType(arg2)) {
*result = CorElementType::ELEMENT_TYPE_I8;
return true;
}
*result = CorElementType::ELEMENT_TYPE_U4;
return true;
} else {
// Otherwise, both operands are converted to int.
*result = CorElementType::ELEMENT_TYPE_I4;
return true;
}
}
bool TypeCompilerHelper::IsNumericalType(const CorElementType &cor_type) {
return IsIntegralType(cor_type) ||
cor_type == CorElementType::ELEMENT_TYPE_R4 ||
cor_type == CorElementType::ELEMENT_TYPE_R8;
}
bool TypeCompilerHelper::IsIntegralType(const CorElementType &cor_type) {
return cor_type == CorElementType::ELEMENT_TYPE_I1 ||
cor_type == CorElementType::ELEMENT_TYPE_U1 ||
cor_type == CorElementType::ELEMENT_TYPE_I2 ||
cor_type == CorElementType::ELEMENT_TYPE_U2 ||
cor_type == CorElementType::ELEMENT_TYPE_I4 ||
cor_type == CorElementType::ELEMENT_TYPE_U4 ||
cor_type == CorElementType::ELEMENT_TYPE_I8 ||
cor_type == CorElementType::ELEMENT_TYPE_U8 ||
cor_type == CorElementType::ELEMENT_TYPE_CHAR;
}
bool TypeCompilerHelper::IsArrayType(const CorElementType &array_type) {
return array_type == CorElementType::ELEMENT_TYPE_ARRAY ||
array_type == CorElementType::ELEMENT_TYPE_SZARRAY;
}
bool TypeCompilerHelper::IsObjectType(const CorElementType &cor_type) {
return cor_type == CorElementType::ELEMENT_TYPE_OBJECT ||
cor_type == CorElementType::ELEMENT_TYPE_CLASS ||
cor_type == CorElementType::ELEMENT_TYPE_VALUETYPE;
}
CorElementType TypeCompilerHelper::ConvertStringToCorElementType(
const std::string &type_string) {
static std::unordered_map<std::string, CorElementType> string_to_cor_type{
{kCharClassName, CorElementType::ELEMENT_TYPE_BOOLEAN},
{kSByteClassName, CorElementType::ELEMENT_TYPE_I1},
{kCharClassName, CorElementType::ELEMENT_TYPE_CHAR},
{kByteClassName, CorElementType::ELEMENT_TYPE_U1},
{kInt16ClassName, CorElementType::ELEMENT_TYPE_I2},
{kUInt16ClassName, CorElementType::ELEMENT_TYPE_U2},
{kInt32ClassName, CorElementType::ELEMENT_TYPE_I4},
{kUInt32ClassName, CorElementType::ELEMENT_TYPE_U4},
{kInt64ClassName, CorElementType::ELEMENT_TYPE_I8},
{kUInt64ClassName, CorElementType::ELEMENT_TYPE_U8},
{kStringClassName, CorElementType::ELEMENT_TYPE_STRING},
{kObjectClassName, CorElementType::ELEMENT_TYPE_OBJECT}};
if (string_to_cor_type.find(type_string) != string_to_cor_type.end()) {
return string_to_cor_type[type_string];
} else {
auto open_bracket = type_string.find("[");
if (open_bracket == std::string::npos) {
return CorElementType::ELEMENT_TYPE_OBJECT;
}
auto closing_bracket = type_string.find("]");
if (closing_bracket == std::string::npos ||
closing_bracket < open_bracket) {
return CorElementType::ELEMENT_TYPE_OBJECT;
}
// This means the type is something like System.Int32[],
// which represents a simple array.
if (open_bracket + 1 == closing_bracket) {
return CorElementType::ELEMENT_TYPE_SZARRAY;
}
// This means the type is something like System.Int32[,], which is
// a multidimensional array.
return CorElementType::ELEMENT_TYPE_ARRAY;
}
}
HRESULT TypeCompilerHelper::ConvertCorElementTypeToString(
const CorElementType &cor_type, std::string *result) {
static std::unordered_map<CorElementType, std::string> cor_type_to_string{
{CorElementType::ELEMENT_TYPE_BOOLEAN, kBooleanClassName},
{CorElementType::ELEMENT_TYPE_I1, kSByteClassName},
{CorElementType::ELEMENT_TYPE_CHAR, kCharClassName},
{CorElementType::ELEMENT_TYPE_U1, kByteClassName},
{CorElementType::ELEMENT_TYPE_I2, kInt16ClassName},
{CorElementType::ELEMENT_TYPE_U2, kUInt16ClassName},
{CorElementType::ELEMENT_TYPE_I4, kInt32ClassName},
{CorElementType::ELEMENT_TYPE_U4, kUInt32ClassName},
{CorElementType::ELEMENT_TYPE_I8, kInt64ClassName},
{CorElementType::ELEMENT_TYPE_U8, kUInt64ClassName},
{CorElementType::ELEMENT_TYPE_R4, kSingleClassName},
{CorElementType::ELEMENT_TYPE_R8, kDoubleClassName},
{CorElementType::ELEMENT_TYPE_I, kIntPtrClassName},
{CorElementType::ELEMENT_TYPE_U, kUIntPtrClassName},
{CorElementType::ELEMENT_TYPE_STRING, kStringClassName},
{CorElementType::ELEMENT_TYPE_OBJECT, kObjectClassName}};
if (result == nullptr) {
return E_INVALIDARG;
}
if (cor_type_to_string.find(cor_type) != cor_type_to_string.end()) {
*result = cor_type_to_string[cor_type];
return S_OK;
}
return E_FAIL;
}
HRESULT TypeCompilerHelper::IsBaseClass(
mdTypeDef source_class, IMetaDataImport *source_class_metadata,
const std::vector<CComPtr<ICorDebugAssembly>> &loaded_assemblies,
const std::string &target_class, ICorDebugHelper *debug_helper,
std::ostream *err_stream) {
HRESULT hr;
mdTypeDef current_class_token = source_class;
CComPtr<IMetaDataImport> current_metadata_import;
std::string current_class_name;
mdToken current_base_class_token = source_class;
current_metadata_import = source_class_metadata;
int max_class_to_traverse = 10;
while (max_class_to_traverse >= 0) {
max_class_to_traverse -= 1;
hr = debug_helper->GetTypeNameFromMdTypeDef(
current_class_token, current_metadata_import, ¤t_class_name,
¤t_base_class_token, err_stream);
if (FAILED(hr)) {
return hr;
}
if (current_class_name.compare(target_class) == 0) {
return S_OK;
}
if (current_class_name.compare(kObjectClassName)) {
return E_FAIL;
}
// Retrieves the base class token and metadata import.
CorTokenType token_type =
(CorTokenType)(TypeFromToken(current_base_class_token));
if (token_type == CorTokenType::mdtTypeDef) {
// No need to change the IMetaDataImport since we are still in the same
// module.
current_class_token = current_base_class_token;
} else if (token_type == CorTokenType::mdtTypeRef) {
CComPtr<IMetaDataImport> resolved_metadata_import;
mdTypeDef resolved_class_token;
hr = debug_helper->GetMdTypeDefAndMetaDataFromTypeRef(
current_base_class_token, loaded_assemblies, current_metadata_import,
&resolved_class_token, &resolved_metadata_import, err_stream);
if (FAILED(hr)) {
return hr;
}
current_class_token = resolved_class_token;
current_metadata_import = resolved_metadata_import;
} else {
// Not supported.
*err_stream << "Only mdTypeDef and mdTypeRef tokens are supported.";
return E_NOTIMPL;
}
}
return E_FAIL;
}
} // namespace google_cloud_debugger
<commit_msg>Add hash for corelementtype<commit_after>// Copyright 2018 Google Inc. All Rights Reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
#include <unordered_map>
#include "class_names.h"
#include "compiler_helpers.h"
#include "dbg_primitive.h"
#include "i_cor_debug_helper.h"
#include "type_signature.h"
namespace google_cloud_debugger {
bool NumericCompilerHelper::IsImplicitNumericConversionable(
const TypeSignature &source, const TypeSignature &target) {
const CorElementType &source_type = source.cor_type;
const CorElementType &target_type = target.cor_type;
// Most of the logic here is from implicit numeric conversions:
// https://docs.microsoft.com/en-us/dotnet/csharp/language-reference/language-specification/conversions#implicit-conversions
switch (source_type) {
case CorElementType::ELEMENT_TYPE_I1: {
switch (target_type) {
case CorElementType::ELEMENT_TYPE_I1:
case CorElementType::ELEMENT_TYPE_I2:
case CorElementType::ELEMENT_TYPE_I4:
case CorElementType::ELEMENT_TYPE_I8:
case CorElementType::ELEMENT_TYPE_R4:
case CorElementType::ELEMENT_TYPE_R8:
return true;
default:
return false;
}
}
case CorElementType::ELEMENT_TYPE_U1: {
switch (target_type) {
case CorElementType::ELEMENT_TYPE_U1:
case CorElementType::ELEMENT_TYPE_I2:
case CorElementType::ELEMENT_TYPE_U2:
case CorElementType::ELEMENT_TYPE_I4:
case CorElementType::ELEMENT_TYPE_U4:
case CorElementType::ELEMENT_TYPE_I8:
case CorElementType::ELEMENT_TYPE_U8:
case CorElementType::ELEMENT_TYPE_R4:
case CorElementType::ELEMENT_TYPE_R8:
return true;
default:
return false;
}
}
case CorElementType::ELEMENT_TYPE_I2: {
switch (target_type) {
case CorElementType::ELEMENT_TYPE_I2:
case CorElementType::ELEMENT_TYPE_I4:
case CorElementType::ELEMENT_TYPE_I8:
case CorElementType::ELEMENT_TYPE_R4:
case CorElementType::ELEMENT_TYPE_R8:
return true;
default:
return false;
}
}
case CorElementType::ELEMENT_TYPE_U2: {
switch (target_type) {
case CorElementType::ELEMENT_TYPE_U2:
case CorElementType::ELEMENT_TYPE_I4:
case CorElementType::ELEMENT_TYPE_U4:
case CorElementType::ELEMENT_TYPE_I8:
case CorElementType::ELEMENT_TYPE_U8:
case CorElementType::ELEMENT_TYPE_R4:
case CorElementType::ELEMENT_TYPE_R8:
return true;
default:
return false;
}
}
case CorElementType::ELEMENT_TYPE_I4: {
switch (target_type) {
case CorElementType::ELEMENT_TYPE_I4:
case CorElementType::ELEMENT_TYPE_I8:
case CorElementType::ELEMENT_TYPE_R4:
case CorElementType::ELEMENT_TYPE_R8:
return true;
default:
return false;
}
}
case CorElementType::ELEMENT_TYPE_U4: {
switch (target_type) {
case CorElementType::ELEMENT_TYPE_U4:
case CorElementType::ELEMENT_TYPE_I8:
case CorElementType::ELEMENT_TYPE_U8:
case CorElementType::ELEMENT_TYPE_R4:
case CorElementType::ELEMENT_TYPE_R8:
return true;
default:
return false;
}
}
case CorElementType::ELEMENT_TYPE_I8: {
switch (target_type) {
case CorElementType::ELEMENT_TYPE_I8:
case CorElementType::ELEMENT_TYPE_R4:
case CorElementType::ELEMENT_TYPE_R8:
return true;
default:
return false;
}
}
case CorElementType::ELEMENT_TYPE_U8: {
switch (target_type) {
case CorElementType::ELEMENT_TYPE_U8:
case CorElementType::ELEMENT_TYPE_R4:
case CorElementType::ELEMENT_TYPE_R8:
return true;
default:
return false;
}
}
case CorElementType::ELEMENT_TYPE_CHAR: {
switch (target_type) {
case CorElementType::ELEMENT_TYPE_CHAR:
case CorElementType::ELEMENT_TYPE_U2:
case CorElementType::ELEMENT_TYPE_I4:
case CorElementType::ELEMENT_TYPE_U4:
case CorElementType::ELEMENT_TYPE_I8:
case CorElementType::ELEMENT_TYPE_U8:
case CorElementType::ELEMENT_TYPE_R4:
case CorElementType::ELEMENT_TYPE_R8:
return true;
default:
return false;
}
}
case CorElementType::ELEMENT_TYPE_R4: {
switch (target_type) {
case CorElementType::ELEMENT_TYPE_R4:
case CorElementType::ELEMENT_TYPE_R8:
return true;
default:
return false;
}
}
case CorElementType::ELEMENT_TYPE_R8: {
switch (target_type) {
case CorElementType::ELEMENT_TYPE_R8:
return true;
default:
return false;
}
}
default:
return false;
}
}
bool NumericCompilerHelper::IsNumericallyPromotedToInt(
const CorElementType &source) {
return source == CorElementType::ELEMENT_TYPE_CHAR ||
source == CorElementType::ELEMENT_TYPE_I1 ||
source == CorElementType::ELEMENT_TYPE_U1 ||
source == CorElementType::ELEMENT_TYPE_I2;
}
// Returns true for I1, I2, I4 and I8 types.
inline bool IsSignedIntegralType(const CorElementType &element_type) {
return element_type == CorElementType::ELEMENT_TYPE_I1 ||
element_type == CorElementType::ELEMENT_TYPE_I2 ||
element_type == CorElementType::ELEMENT_TYPE_I4 ||
element_type == CorElementType::ELEMENT_TYPE_I8;
}
bool NumericCompilerHelper::BinaryNumericalPromotion(const CorElementType &arg1,
const CorElementType &arg2,
CorElementType *result,
std::ostream *err_stream) {
if (!TypeCompilerHelper::IsNumericalType(arg1) &&
!TypeCompilerHelper::IsNumericalType(arg2)) {
*err_stream << "Both arguments has to be of numerical types.";
return false;
}
// TODO(quoct): Add support for Decimal.
if (arg1 == CorElementType::ELEMENT_TYPE_R8 ||
arg2 == CorElementType::ELEMENT_TYPE_R8) {
*result = CorElementType::ELEMENT_TYPE_R8;
return true;
} else if (arg1 == CorElementType::ELEMENT_TYPE_R4 ||
arg2 == CorElementType::ELEMENT_TYPE_R4) {
*result = CorElementType::ELEMENT_TYPE_R4;
return true;
} else if (arg1 == CorElementType::ELEMENT_TYPE_U8 ||
arg2 == CorElementType::ELEMENT_TYPE_U8) {
// If the other operand is of type sbyte, short, int or long,
// an error will occur. This is because no integral type exists that can
// represent the full range of ulong as well as the signed integral types.
if (IsSignedIntegralType(arg1) || IsSignedIntegralType(arg2)) {
*err_stream << "If one of the argument is an unsigned long, "
<< "the other cannot be a signed integral type.";
return false;
}
*result = CorElementType::ELEMENT_TYPE_U8;
return true;
} else if (arg1 == CorElementType::ELEMENT_TYPE_I8 ||
arg2 == CorElementType::ELEMENT_TYPE_I8) {
*result = CorElementType::ELEMENT_TYPE_I8;
return true;
} else if (arg1 == CorElementType::ELEMENT_TYPE_U4 ||
arg2 == CorElementType::ELEMENT_TYPE_U4) {
// If 1 of the operand is sbyte, short or int,
// the result will be long. We can simply call
// IsSignedIntegralType without worrying about arg1
// being an I8 type because that is already checked above.
if (IsSignedIntegralType(arg1)) {
*result = CorElementType::ELEMENT_TYPE_I8;
return true;
}
if (IsSignedIntegralType(arg2)) {
*result = CorElementType::ELEMENT_TYPE_I8;
return true;
}
*result = CorElementType::ELEMENT_TYPE_U4;
return true;
} else {
// Otherwise, both operands are converted to int.
*result = CorElementType::ELEMENT_TYPE_I4;
return true;
}
}
bool TypeCompilerHelper::IsNumericalType(const CorElementType &cor_type) {
return IsIntegralType(cor_type) ||
cor_type == CorElementType::ELEMENT_TYPE_R4 ||
cor_type == CorElementType::ELEMENT_TYPE_R8;
}
bool TypeCompilerHelper::IsIntegralType(const CorElementType &cor_type) {
return cor_type == CorElementType::ELEMENT_TYPE_I1 ||
cor_type == CorElementType::ELEMENT_TYPE_U1 ||
cor_type == CorElementType::ELEMENT_TYPE_I2 ||
cor_type == CorElementType::ELEMENT_TYPE_U2 ||
cor_type == CorElementType::ELEMENT_TYPE_I4 ||
cor_type == CorElementType::ELEMENT_TYPE_U4 ||
cor_type == CorElementType::ELEMENT_TYPE_I8 ||
cor_type == CorElementType::ELEMENT_TYPE_U8 ||
cor_type == CorElementType::ELEMENT_TYPE_CHAR;
}
bool TypeCompilerHelper::IsArrayType(const CorElementType &array_type) {
return array_type == CorElementType::ELEMENT_TYPE_ARRAY ||
array_type == CorElementType::ELEMENT_TYPE_SZARRAY;
}
bool TypeCompilerHelper::IsObjectType(const CorElementType &cor_type) {
return cor_type == CorElementType::ELEMENT_TYPE_OBJECT ||
cor_type == CorElementType::ELEMENT_TYPE_CLASS ||
cor_type == CorElementType::ELEMENT_TYPE_VALUETYPE;
}
CorElementType TypeCompilerHelper::ConvertStringToCorElementType(
const std::string &type_string) {
static std::unordered_map<std::string, CorElementType> string_to_cor_type{
{kCharClassName, CorElementType::ELEMENT_TYPE_BOOLEAN},
{kSByteClassName, CorElementType::ELEMENT_TYPE_I1},
{kCharClassName, CorElementType::ELEMENT_TYPE_CHAR},
{kByteClassName, CorElementType::ELEMENT_TYPE_U1},
{kInt16ClassName, CorElementType::ELEMENT_TYPE_I2},
{kUInt16ClassName, CorElementType::ELEMENT_TYPE_U2},
{kInt32ClassName, CorElementType::ELEMENT_TYPE_I4},
{kUInt32ClassName, CorElementType::ELEMENT_TYPE_U4},
{kInt64ClassName, CorElementType::ELEMENT_TYPE_I8},
{kUInt64ClassName, CorElementType::ELEMENT_TYPE_U8},
{kStringClassName, CorElementType::ELEMENT_TYPE_STRING},
{kObjectClassName, CorElementType::ELEMENT_TYPE_OBJECT}};
if (string_to_cor_type.find(type_string) != string_to_cor_type.end()) {
return string_to_cor_type[type_string];
} else {
auto open_bracket = type_string.find("[");
if (open_bracket == std::string::npos) {
return CorElementType::ELEMENT_TYPE_OBJECT;
}
auto closing_bracket = type_string.find("]");
if (closing_bracket == std::string::npos ||
closing_bracket < open_bracket) {
return CorElementType::ELEMENT_TYPE_OBJECT;
}
// This means the type is something like System.Int32[],
// which represents a simple array.
if (open_bracket + 1 == closing_bracket) {
return CorElementType::ELEMENT_TYPE_SZARRAY;
}
// This means the type is something like System.Int32[,], which is
// a multidimensional array.
return CorElementType::ELEMENT_TYPE_ARRAY;
}
}
struct CorElementTypeHash {
std::size_t operator()(CorElementType cor_type) const {
return static_cast<std::size_t>(cor_type);
}
};
HRESULT TypeCompilerHelper::ConvertCorElementTypeToString(
const CorElementType &cor_type, std::string *result) {
static std::unordered_map<CorElementType, std::string, CorElementTypeHash> cor_type_to_string{
{CorElementType::ELEMENT_TYPE_BOOLEAN, kBooleanClassName},
{CorElementType::ELEMENT_TYPE_I1, kSByteClassName},
{CorElementType::ELEMENT_TYPE_CHAR, kCharClassName},
{CorElementType::ELEMENT_TYPE_U1, kByteClassName},
{CorElementType::ELEMENT_TYPE_I2, kInt16ClassName},
{CorElementType::ELEMENT_TYPE_U2, kUInt16ClassName},
{CorElementType::ELEMENT_TYPE_I4, kInt32ClassName},
{CorElementType::ELEMENT_TYPE_U4, kUInt32ClassName},
{CorElementType::ELEMENT_TYPE_I8, kInt64ClassName},
{CorElementType::ELEMENT_TYPE_U8, kUInt64ClassName},
{CorElementType::ELEMENT_TYPE_R4, kSingleClassName},
{CorElementType::ELEMENT_TYPE_R8, kDoubleClassName},
{CorElementType::ELEMENT_TYPE_I, kIntPtrClassName},
{CorElementType::ELEMENT_TYPE_U, kUIntPtrClassName},
{CorElementType::ELEMENT_TYPE_STRING, kStringClassName},
{CorElementType::ELEMENT_TYPE_OBJECT, kObjectClassName}};
if (result == nullptr) {
return E_INVALIDARG;
}
if (cor_type_to_string.find(cor_type) != cor_type_to_string.end()) {
*result = cor_type_to_string[cor_type];
return S_OK;
}
return E_FAIL;
}
HRESULT TypeCompilerHelper::IsBaseClass(
mdTypeDef source_class, IMetaDataImport *source_class_metadata,
const std::vector<CComPtr<ICorDebugAssembly>> &loaded_assemblies,
const std::string &target_class, ICorDebugHelper *debug_helper,
std::ostream *err_stream) {
HRESULT hr;
mdTypeDef current_class_token = source_class;
CComPtr<IMetaDataImport> current_metadata_import;
std::string current_class_name;
mdToken current_base_class_token = source_class;
current_metadata_import = source_class_metadata;
int max_class_to_traverse = 10;
while (max_class_to_traverse >= 0) {
max_class_to_traverse -= 1;
hr = debug_helper->GetTypeNameFromMdTypeDef(
current_class_token, current_metadata_import, ¤t_class_name,
¤t_base_class_token, err_stream);
if (FAILED(hr)) {
return hr;
}
if (current_class_name.compare(target_class) == 0) {
return S_OK;
}
if (current_class_name.compare(kObjectClassName)) {
return E_FAIL;
}
// Retrieves the base class token and metadata import.
CorTokenType token_type =
(CorTokenType)(TypeFromToken(current_base_class_token));
if (token_type == CorTokenType::mdtTypeDef) {
// No need to change the IMetaDataImport since we are still in the same
// module.
current_class_token = current_base_class_token;
} else if (token_type == CorTokenType::mdtTypeRef) {
CComPtr<IMetaDataImport> resolved_metadata_import;
mdTypeDef resolved_class_token;
hr = debug_helper->GetMdTypeDefAndMetaDataFromTypeRef(
current_base_class_token, loaded_assemblies, current_metadata_import,
&resolved_class_token, &resolved_metadata_import, err_stream);
if (FAILED(hr)) {
return hr;
}
current_class_token = resolved_class_token;
current_metadata_import = resolved_metadata_import;
} else {
// Not supported.
*err_stream << "Only mdTypeDef and mdTypeRef tokens are supported.";
return E_NOTIMPL;
}
}
return E_FAIL;
}
} // namespace google_cloud_debugger
<|endoftext|>
|
<commit_before>
#ifndef MANIFOLDS_FUNCTIONS_UNARY_MINUS_HH
#define MANIFOLDS_FUNCTIONS_UNARY_MINUS_HH
#include "full_function_defs.hh"
#include "function.hh"
namespace manifolds {
template <class Func>
struct UnaryMinus : Function<list<int_<24>, typename Func::indices>,
Func::input_dim, Func::output_dim>,
FunctionCommon<UnaryMinus<Func> > {
static const bool stateless = is_stateless<Func>::value;
static const ComplexOutputBehaviour complex_output = SameAsInput;
UnaryMinus() {}
UnaryMinus(const Func &f) : f(f) {}
template <class... Args> auto eval(Args... args) const { return -f(args...); }
auto GetFunction() const { return f; }
auto GetFunctions() const { return make_my_tuple(f); }
private:
Func f;
};
template <class T, class U> bool operator==(UnaryMinus<T>, U) { return false; }
template <class T> bool operator==(UnaryMinus<T> u1, UnaryMinus<T> u2) {
return u1.GetFunction() == u2.GetFunction();
}
}
#endif
<commit_msg>clang-format<commit_after>
#ifndef MANIFOLDS_FUNCTIONS_UNARY_MINUS_HH
#define MANIFOLDS_FUNCTIONS_UNARY_MINUS_HH
#include "full_function_defs.hh"
#include "function.hh"
namespace manifolds {
template <class Func>
struct UnaryMinus : Function<list<int_<24>, typename Func::indices>,
Func::input_dim, Func::output_dim>,
FunctionCommon<UnaryMinus<Func> > {
static const bool stateless = is_stateless<Func>::value;
static const ComplexOutputBehaviour complex_output = SameAsInput;
UnaryMinus() {}
UnaryMinus(const Func &f) : f(f) {}
template <class... Args> auto eval(Args... args) const { return -f(args...); }
auto GetFunction() const { return f; }
auto GetFunctions() const { return make_my_tuple(f); }
private:
Func f;
};
template <class T, class U> bool operator==(UnaryMinus<T>, U) { return false; }
template <class T> bool operator==(UnaryMinus<T> u1, UnaryMinus<T> u2) {
return u1.GetFunction() == u2.GetFunction();
}
template <class F> UnaryMinus<F> Negative(F f) { return UnaryMinus<F>(f); }
}
#endif
<|endoftext|>
|
<commit_before>///////////////////////////////////////////////////////////////////////////////////////////////////
// OpenGL Mathematics Copyright (c) 2005 - 2013 G-Truc Creation (www.g-truc.net)
///////////////////////////////////////////////////////////////////////////////////////////////////
// Created : 2005-12-21
// Updated : 2007-08-14
// Licence : This source is under MIT License
// File : glm/gtx/euler_angles.inl
///////////////////////////////////////////////////////////////////////////////////////////////////
namespace glm
{
template <typename T>
GLM_FUNC_QUALIFIER detail::tmat4x4<T, defaultp> eulerAngleX
(
T const & angleX
)
{
T cosX = glm::cos(angleX);
T sinX = glm::sin(angleX);
return detail::tmat4x4<T, defaultp>(
T(1), T(0), T(0), T(0),
T(0), cosX, sinX, T(0),
T(0),-sinX, cosX, T(0),
T(0), T(0), T(0), T(1));
}
template <typename T>
GLM_FUNC_QUALIFIER detail::tmat4x4<T, defaultp> eulerAngleY
(
T const & angleY
)
{
T cosY = glm::cos(angleY);
T sinY = glm::sin(angleY);
return detail::tmat4x4<T, defaultp>(
cosY, T(0), sinY, T(0),
T(0), T(1), T(0), T(0),
-sinY, T(0), cosY, T(0),
T(0), T(0), T(0), T(1));
}
template <typename T>
GLM_FUNC_QUALIFIER detail::tmat4x4<T, defaultp> eulerAngleZ
(
T const & angleZ
)
{
T cosZ = glm::cos(angleZ);
T sinZ = glm::sin(angleZ);
return detail::tmat4x4<T, defaultp>(
cosZ, sinZ, T(0), T(0),
-sinZ, cosZ, T(0), T(0),
T(0), T(0), T(1), T(0),
T(0), T(0), T(0), T(1));
}
template <typename T>
GLM_FUNC_QUALIFIER detail::tmat4x4<T, defaultp> eulerAngleXY
(
T const & angleX,
T const & angleY
)
{
T cosX = glm::cos(angleX);
T sinX = glm::sin(angleX);
T cosY = glm::cos(angleY);
T sinY = glm::sin(angleY);
return detail::tmat4x4<T, defaultp>(
cosY, -sinX * sinY, cosX * sinY, T(0),
T(0), cosX, sinX, T(0),
-sinY, -sinX * cosY, cosX * cosY, T(0),
T(0), T(0), T(0), T(1));
}
template <typename T>
GLM_FUNC_QUALIFIER detail::tmat4x4<T, defaultp> eulerAngleYX
(
T const & angleY,
T const & angleX
)
{
T cosX = glm::cos(angleX);
T sinX = glm::sin(angleX);
T cosY = glm::cos(angleY);
T sinY = glm::sin(angleY);
return detail::tmat4x4<T, defaultp>(
cosY, T(0), sinY, T(0),
-sinX * sinY, cosX, sinX * cosY, T(0),
-cosX * sinY, -sinX, cosX * cosY, T(0),
T(0), T(0), T(0), T(1));
}
template <typename T>
GLM_FUNC_QUALIFIER detail::tmat4x4<T, defaultp> eulerAngleXZ
(
T const & angleX,
T const & angleZ
)
{
return eulerAngleX(angleX) * eulerAngleZ(angleZ);
}
template <typename T>
GLM_FUNC_QUALIFIER detail::tmat4x4<T, defaultp> eulerAngleZX
(
T const & angleZ,
T const & angleX
)
{
return eulerAngleZ(angleZ) * eulerAngleX(angleX);
}
template <typename T>
GLM_FUNC_QUALIFIER detail::tmat4x4<T, defaultp> eulerAngleYXZ
(
T const & yaw,
T const & pitch,
T const & roll
)
{
T tmp_ch = glm::cos(yaw);
T tmp_sh = glm::sin(yaw);
T tmp_cp = glm::cos(pitch);
T tmp_sp = glm::sin(pitch);
T tmp_cb = glm::cos(roll);
T tmp_sb = glm::sin(roll);
detail::tmat4x4<T, defaultp> Result;
Result[0][0] = tmp_ch * tmp_cb + tmp_sh * tmp_sp * tmp_sb;
Result[0][1] = tmp_sb * tmp_cp;
Result[0][2] = -tmp_sh * tmp_cb + tmp_ch * tmp_sp * tmp_sb;
Result[0][3] = static_cast<T>(0);
Result[1][0] = -tmp_ch * tmp_sb + tmp_sh * tmp_sp * tmp_cb;
Result[1][1] = tmp_cb * tmp_cp;
Result[1][2] = tmp_sb * tmp_sh + tmp_ch * tmp_sp * tmp_cb;
Result[1][3] = static_cast<T>(0);
Result[2][0] = tmp_sh * tmp_cp;
Result[2][1] = -tmp_sp;
Result[2][2] = tmp_ch * tmp_cp;
Result[2][3] = static_cast<T>(0);
Result[3][0] = static_cast<T>(0);
Result[3][1] = static_cast<T>(0);
Result[3][2] = static_cast<T>(0);
Result[3][3] = static_cast<T>(1);
return Result;
}
template <typename T>
GLM_FUNC_QUALIFIER detail::tmat4x4<T, defaultp> yawPitchRoll
(
T const & yaw,
T const & pitch,
T const & roll
)
{
T tmp_ch = glm::cos(yaw);
T tmp_sh = glm::sin(yaw);
T tmp_cp = glm::cos(pitch);
T tmp_sp = glm::sin(pitch);
T tmp_cb = glm::cos(roll);
T tmp_sb = glm::sin(roll);
detail::tmat4x4<T, defaultp> Result;
Result[0][0] = tmp_ch * tmp_cb + tmp_sh * tmp_sp * tmp_sb;
Result[0][1] = tmp_sb * tmp_cp;
Result[0][2] = -tmp_sh * tmp_cb + tmp_ch * tmp_sp * tmp_sb;
Result[0][3] = static_cast<T>(0);
Result[1][0] = -tmp_ch * tmp_sb + tmp_sh * tmp_sp * tmp_cb;
Result[1][1] = tmp_cb * tmp_cp;
Result[1][2] = tmp_sb * tmp_sh + tmp_ch * tmp_sp * tmp_cb;
Result[1][3] = static_cast<T>(0);
Result[2][0] = tmp_sh * tmp_cp;
Result[2][1] = -tmp_sp;
Result[2][2] = tmp_ch * tmp_cp;
Result[2][3] = static_cast<T>(0);
Result[3][0] = static_cast<T>(0);
Result[3][1] = static_cast<T>(0);
Result[3][2] = static_cast<T>(0);
Result[3][3] = static_cast<T>(1);
return Result;
}
template <typename T>
GLM_FUNC_QUALIFIER detail::tmat2x2<T, defaultp> orientate2
(
T const & angle
)
{
T c = glm::cos(angle);
T s = glm::sin(angle);
detail::tmat2x2<T, defaultp> Result;
Result[0][0] = c;
Result[0][1] = s;
Result[1][0] = -s;
Result[1][1] = c;
return Result;
}
template <typename T>
GLM_FUNC_QUALIFIER detail::tmat3x3<T, defaultp> orientate3
(
T const & angle
)
{
T c = glm::cos(angle);
T s = glm::sin(angle);
detail::tmat3x3<T, defaultp> Result;
Result[0][0] = c;
Result[0][1] = s;
Result[0][2] = 0.0f;
Result[1][0] = -s;
Result[1][1] = c;
Result[1][2] = 0.0f;
Result[2][0] = 0.0f;
Result[2][1] = 0.0f;
Result[2][2] = 1.0f;
return Result;
}
template <typename T, precision P>
GLM_FUNC_QUALIFIER detail::tmat3x3<T, P> orientate3
(
detail::tvec3<T, P> const & angles
)
{
return detail::tmat3x3<T, P>(yawPitchRoll(angles.x, angles.y, angles.z));
}
template <typename T, precision P>
GLM_FUNC_QUALIFIER detail::tmat4x4<T, P> orientate4
(
detail::tvec3<T, P> const & angles
)
{
return yawPitchRoll(angles.z, angles.x, angles.y);
}
}//namespace glm
<commit_msg>Changed sign for eulerAngleY to make it consistent with the others<commit_after>///////////////////////////////////////////////////////////////////////////////////////////////////
// OpenGL Mathematics Copyright (c) 2005 - 2013 G-Truc Creation (www.g-truc.net)
///////////////////////////////////////////////////////////////////////////////////////////////////
// Created : 2005-12-21
// Updated : 2007-08-14
// Licence : This source is under MIT License
// File : glm/gtx/euler_angles.inl
///////////////////////////////////////////////////////////////////////////////////////////////////
namespace glm
{
template <typename T>
GLM_FUNC_QUALIFIER detail::tmat4x4<T, defaultp> eulerAngleX
(
T const & angleX
)
{
T cosX = glm::cos(angleX);
T sinX = glm::sin(angleX);
return detail::tmat4x4<T, defaultp>(
T(1), T(0), T(0), T(0),
T(0), cosX, sinX, T(0),
T(0),-sinX, cosX, T(0),
T(0), T(0), T(0), T(1));
}
template <typename T>
GLM_FUNC_QUALIFIER detail::tmat4x4<T, defaultp> eulerAngleY
(
T const & angleY
)
{
T cosY = glm::cos(angleY);
T sinY = glm::sin(angleY);
return detail::tmat4x4<T, defaultp>(
cosY, T(0), -sinY, T(0),
T(0), T(1), T(0), T(0),
sinY, T(0), cosY, T(0),
T(0), T(0), T(0), T(1));
}
template <typename T>
GLM_FUNC_QUALIFIER detail::tmat4x4<T, defaultp> eulerAngleZ
(
T const & angleZ
)
{
T cosZ = glm::cos(angleZ);
T sinZ = glm::sin(angleZ);
return detail::tmat4x4<T, defaultp>(
cosZ, sinZ, T(0), T(0),
-sinZ, cosZ, T(0), T(0),
T(0), T(0), T(1), T(0),
T(0), T(0), T(0), T(1));
}
template <typename T>
GLM_FUNC_QUALIFIER detail::tmat4x4<T, defaultp> eulerAngleXY
(
T const & angleX,
T const & angleY
)
{
T cosX = glm::cos(angleX);
T sinX = glm::sin(angleX);
T cosY = glm::cos(angleY);
T sinY = glm::sin(angleY);
return detail::tmat4x4<T, defaultp>(
cosY, -sinX * sinY, cosX * sinY, T(0),
T(0), cosX, sinX, T(0),
-sinY, -sinX * cosY, cosX * cosY, T(0),
T(0), T(0), T(0), T(1));
}
template <typename T>
GLM_FUNC_QUALIFIER detail::tmat4x4<T, defaultp> eulerAngleYX
(
T const & angleY,
T const & angleX
)
{
T cosX = glm::cos(angleX);
T sinX = glm::sin(angleX);
T cosY = glm::cos(angleY);
T sinY = glm::sin(angleY);
return detail::tmat4x4<T, defaultp>(
cosY, T(0), sinY, T(0),
-sinX * sinY, cosX, sinX * cosY, T(0),
-cosX * sinY, -sinX, cosX * cosY, T(0),
T(0), T(0), T(0), T(1));
}
template <typename T>
GLM_FUNC_QUALIFIER detail::tmat4x4<T, defaultp> eulerAngleXZ
(
T const & angleX,
T const & angleZ
)
{
return eulerAngleX(angleX) * eulerAngleZ(angleZ);
}
template <typename T>
GLM_FUNC_QUALIFIER detail::tmat4x4<T, defaultp> eulerAngleZX
(
T const & angleZ,
T const & angleX
)
{
return eulerAngleZ(angleZ) * eulerAngleX(angleX);
}
template <typename T>
GLM_FUNC_QUALIFIER detail::tmat4x4<T, defaultp> eulerAngleYXZ
(
T const & yaw,
T const & pitch,
T const & roll
)
{
T tmp_ch = glm::cos(yaw);
T tmp_sh = glm::sin(yaw);
T tmp_cp = glm::cos(pitch);
T tmp_sp = glm::sin(pitch);
T tmp_cb = glm::cos(roll);
T tmp_sb = glm::sin(roll);
detail::tmat4x4<T, defaultp> Result;
Result[0][0] = tmp_ch * tmp_cb + tmp_sh * tmp_sp * tmp_sb;
Result[0][1] = tmp_sb * tmp_cp;
Result[0][2] = -tmp_sh * tmp_cb + tmp_ch * tmp_sp * tmp_sb;
Result[0][3] = static_cast<T>(0);
Result[1][0] = -tmp_ch * tmp_sb + tmp_sh * tmp_sp * tmp_cb;
Result[1][1] = tmp_cb * tmp_cp;
Result[1][2] = tmp_sb * tmp_sh + tmp_ch * tmp_sp * tmp_cb;
Result[1][3] = static_cast<T>(0);
Result[2][0] = tmp_sh * tmp_cp;
Result[2][1] = -tmp_sp;
Result[2][2] = tmp_ch * tmp_cp;
Result[2][3] = static_cast<T>(0);
Result[3][0] = static_cast<T>(0);
Result[3][1] = static_cast<T>(0);
Result[3][2] = static_cast<T>(0);
Result[3][3] = static_cast<T>(1);
return Result;
}
template <typename T>
GLM_FUNC_QUALIFIER detail::tmat4x4<T, defaultp> yawPitchRoll
(
T const & yaw,
T const & pitch,
T const & roll
)
{
T tmp_ch = glm::cos(yaw);
T tmp_sh = glm::sin(yaw);
T tmp_cp = glm::cos(pitch);
T tmp_sp = glm::sin(pitch);
T tmp_cb = glm::cos(roll);
T tmp_sb = glm::sin(roll);
detail::tmat4x4<T, defaultp> Result;
Result[0][0] = tmp_ch * tmp_cb + tmp_sh * tmp_sp * tmp_sb;
Result[0][1] = tmp_sb * tmp_cp;
Result[0][2] = -tmp_sh * tmp_cb + tmp_ch * tmp_sp * tmp_sb;
Result[0][3] = static_cast<T>(0);
Result[1][0] = -tmp_ch * tmp_sb + tmp_sh * tmp_sp * tmp_cb;
Result[1][1] = tmp_cb * tmp_cp;
Result[1][2] = tmp_sb * tmp_sh + tmp_ch * tmp_sp * tmp_cb;
Result[1][3] = static_cast<T>(0);
Result[2][0] = tmp_sh * tmp_cp;
Result[2][1] = -tmp_sp;
Result[2][2] = tmp_ch * tmp_cp;
Result[2][3] = static_cast<T>(0);
Result[3][0] = static_cast<T>(0);
Result[3][1] = static_cast<T>(0);
Result[3][2] = static_cast<T>(0);
Result[3][3] = static_cast<T>(1);
return Result;
}
template <typename T>
GLM_FUNC_QUALIFIER detail::tmat2x2<T, defaultp> orientate2
(
T const & angle
)
{
T c = glm::cos(angle);
T s = glm::sin(angle);
detail::tmat2x2<T, defaultp> Result;
Result[0][0] = c;
Result[0][1] = s;
Result[1][0] = -s;
Result[1][1] = c;
return Result;
}
template <typename T>
GLM_FUNC_QUALIFIER detail::tmat3x3<T, defaultp> orientate3
(
T const & angle
)
{
T c = glm::cos(angle);
T s = glm::sin(angle);
detail::tmat3x3<T, defaultp> Result;
Result[0][0] = c;
Result[0][1] = s;
Result[0][2] = 0.0f;
Result[1][0] = -s;
Result[1][1] = c;
Result[1][2] = 0.0f;
Result[2][0] = 0.0f;
Result[2][1] = 0.0f;
Result[2][2] = 1.0f;
return Result;
}
template <typename T, precision P>
GLM_FUNC_QUALIFIER detail::tmat3x3<T, P> orientate3
(
detail::tvec3<T, P> const & angles
)
{
return detail::tmat3x3<T, P>(yawPitchRoll(angles.x, angles.y, angles.z));
}
template <typename T, precision P>
GLM_FUNC_QUALIFIER detail::tmat4x4<T, P> orientate4
(
detail::tvec3<T, P> const & angles
)
{
return yawPitchRoll(angles.z, angles.x, angles.y);
}
}//namespace glm
<|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.
*/
/*
* Modified by ScyllaDB
* Copyright 2015 ScyllaDB
*/
/*
* This file is part of Scylla.
*
* Scylla 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.
*
* Scylla 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 Scylla. If not, see <http://www.gnu.org/licenses/>.
*/
#include "gms/application_state.hh"
#include <seastar/core/sstring.hh>
#include <ostream>
#include <map>
#include "seastarx.hh"
namespace gms {
static const std::map<application_state, sstring> application_state_names = {
{application_state::STATUS, "STATUS"},
{application_state::LOAD, "LOAD"},
{application_state::SCHEMA, "SCHEMA"},
{application_state::DC, "DC"},
{application_state::RACK, "RACK"},
{application_state::RELEASE_VERSION, "RELEASE_VERSION"},
{application_state::REMOVAL_COORDINATOR, "REMOVAL_COORDINATOR"},
{application_state::INTERNAL_IP, "INTERNAL_IP"},
{application_state::RPC_ADDRESS, "RPC_ADDRESS"},
{application_state::SEVERITY, "SEVERITY"},
{application_state::NET_VERSION, "NET_VERSION"},
{application_state::HOST_ID, "HOST_ID"},
{application_state::TOKENS, "TOKENS"},
{application_state::SUPPORTED_FEATURES, "SUPPORTED_FEATURES"},
{application_state::CACHE_HITRATES, "CACHE_HITRATES"},
};
std::ostream& operator<<(std::ostream& os, const application_state& m) {
auto it = application_state_names.find(m);
if (it != application_state_names.end()) {
os << application_state_names.at(m);
} else {
os << "UNKNOWN";
}
return os;
}
}
<commit_msg>gossip: Print SCHEMA_TABLES_VERSION correctly<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.
*/
/*
* Modified by ScyllaDB
* Copyright 2015 ScyllaDB
*/
/*
* This file is part of Scylla.
*
* Scylla 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.
*
* Scylla 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 Scylla. If not, see <http://www.gnu.org/licenses/>.
*/
#include "gms/application_state.hh"
#include <seastar/core/sstring.hh>
#include <ostream>
#include <map>
#include "seastarx.hh"
namespace gms {
static const std::map<application_state, sstring> application_state_names = {
{application_state::STATUS, "STATUS"},
{application_state::LOAD, "LOAD"},
{application_state::SCHEMA, "SCHEMA"},
{application_state::DC, "DC"},
{application_state::RACK, "RACK"},
{application_state::RELEASE_VERSION, "RELEASE_VERSION"},
{application_state::REMOVAL_COORDINATOR, "REMOVAL_COORDINATOR"},
{application_state::INTERNAL_IP, "INTERNAL_IP"},
{application_state::RPC_ADDRESS, "RPC_ADDRESS"},
{application_state::SEVERITY, "SEVERITY"},
{application_state::NET_VERSION, "NET_VERSION"},
{application_state::HOST_ID, "HOST_ID"},
{application_state::TOKENS, "TOKENS"},
{application_state::SUPPORTED_FEATURES, "SUPPORTED_FEATURES"},
{application_state::CACHE_HITRATES, "CACHE_HITRATES"},
{application_state::SCHEMA_TABLES_VERSION, "SCHEMA_TABLES_VERSION"},
};
std::ostream& operator<<(std::ostream& os, const application_state& m) {
auto it = application_state_names.find(m);
if (it != application_state_names.end()) {
os << application_state_names.at(m);
} else {
os << "UNKNOWN";
}
return os;
}
}
<|endoftext|>
|
<commit_before>/*
* WindowTestLayer.cpp
*
* Created on: Sep 27, 2011
* Author: slundquist
*/
#include "WindowTestLayer.hpp"
#include <utils/conversions.h>
namespace PV {
WindowTestLayer::WindowTestLayer(const char * name, HyPerCol * hc, int numChannels) {
initialize_base();
initialize(name, hc, numChannels);
}
WindowTestLayer::WindowTestLayer(const char * name, HyPerCol * hc){
initialize_base();
initialize(name, hc, MAX_CHANNELS);
}
int WindowTestLayer::initialize_base()
{
//windowLayerName = NULL;
//windowLayer = NULL;
return PV_SUCCESS;
}
int WindowTestLayer::initialize(const char * name, HyPerCol * hc, int num_channels)
{
ANNLayer::initialize(name, hc, num_channels);
//PVParams * params = parent->parameters();
//windowLayerName = params->stringValue(name, "windowLayerName", NULL);
//if (windowLayerName == NULL){
// fprintf(stderr, "WindowTestLayer \"%s\" error: windowLayerName must be specified.\n", name);
// abort();
//}
return PV_SUCCESS;
}
int WindowTestLayer::communicateInitInfo() {
int status = ANNLayer::communicateInitInfo();
//HyPerLayer * origLayer = parent->getLayerFromName(windowLayerName);
//if (origLayer ==NULL) {
// fprintf(stderr, "WindowTestLayer \"%s\" error: windowLayerName \"%s\" is not a layer in the HyPerCol.\n", name, windowLayerName);
// abort();
//}
////For now, the window information must come from HyPerLCALayer
//windowLayer = dynamic_cast<HyPerLCALayer *>(origLayer);
//if (windowLayer ==NULL) {
// fprintf(stderr, "WindowTestLayer \"%s\" error: windowLayerName \"%s\" must be a HyPerLCALayer.\n", name, windowLayerName);
// abort();
//}
return status;
}
int WindowTestLayer::allocateDataStructures() {
int status = ANNLayer::allocateDataStructures();
if (status==PV_SUCCESS) {
setActivitytoOne();
}
return status;
}
// set activity to global x/y/f position, using position in border/margin as required
int WindowTestLayer::setActivitytoOne(){
//Make sure window layer is the same size as current layer
//const PVLayerLoc * windowLoc = windowLayer->getLayerLoc();
const PVLayerLoc * thisLoc = this->getLayerLoc();
//if(windowLoc->nx != thisLoc->nx || windowLoc->ny != thisLoc->ny || windowLoc->nf != thisLoc->nf || windowLoc->nb != thisLoc->nb){
// fprintf(stderr, "WindowTestLayer \"%s\" error: Size (including margins) must equal to the window layer.\n", name);
// abort();
//}
for (int kLocalExt = 0; kLocalExt < clayer->numExtended; kLocalExt++){
//int kWindow = layerIndexExt(kLocalExt, thisLoc, windowLoc);
//int kxGlobalExt = kxPos(kWindow, windowLoc->nx + 2*windowLoc->nb, windowLoc->ny + 2*windowLoc->nb, windowLoc->nf) + windowLoc->kx0;
//int kyGlobalExt = kyPos(kWindow, windowLoc->nx + 2*windowLoc->nb, windowLoc->ny + 2*windowLoc->nb, windowLoc->nf) + windowLoc->ky0;
//int kxGlobalExt = kxPos(kLocalExt, windowLoc->nx + 2*windowLoc->nb, windowLoc->ny + 2*windowLoc->nb, windowLoc->nf) + windowLoc->kx0;
//int kyGlobalExt = kyPos(kLocalExt, windowLoc->nx + 2*windowLoc->nb, windowLoc->ny + 2*windowLoc->nb, windowLoc->nf) + windowLoc->ky0;
//Get window from windowLayer
//int windowId = windowLayer->calcWindow(kxGlobalExt, kyGlobalExt);
clayer->activity->data[kLocalExt] = 1;
}
return PV_SUCCESS;
}
int WindowTestLayer::updateState(double timed, double dt)
{
//updateV();
//setActivity();
//resetGSynBuffers();
//updateActiveIndices();
return PV_SUCCESS;
}
int WindowTestLayer::publish(InterColComm* comm, double timed)
{
setActivitytoOne();
int status = comm->publish(this, clayer->activity);
return status;
//return HyPerLayer::publish(comm, time);
}
} /* namespace PV */
<commit_msg>Eliminating unused-variable warning<commit_after>/*
* WindowTestLayer.cpp
*
* Created on: Sep 27, 2011
* Author: slundquist
*/
#include "WindowTestLayer.hpp"
#include <utils/conversions.h>
namespace PV {
WindowTestLayer::WindowTestLayer(const char * name, HyPerCol * hc, int numChannels) {
initialize_base();
initialize(name, hc, numChannels);
}
WindowTestLayer::WindowTestLayer(const char * name, HyPerCol * hc){
initialize_base();
initialize(name, hc, MAX_CHANNELS);
}
int WindowTestLayer::initialize_base()
{
//windowLayerName = NULL;
//windowLayer = NULL;
return PV_SUCCESS;
}
int WindowTestLayer::initialize(const char * name, HyPerCol * hc, int num_channels)
{
ANNLayer::initialize(name, hc, num_channels);
//PVParams * params = parent->parameters();
//windowLayerName = params->stringValue(name, "windowLayerName", NULL);
//if (windowLayerName == NULL){
// fprintf(stderr, "WindowTestLayer \"%s\" error: windowLayerName must be specified.\n", name);
// abort();
//}
return PV_SUCCESS;
}
int WindowTestLayer::communicateInitInfo() {
int status = ANNLayer::communicateInitInfo();
//HyPerLayer * origLayer = parent->getLayerFromName(windowLayerName);
//if (origLayer ==NULL) {
// fprintf(stderr, "WindowTestLayer \"%s\" error: windowLayerName \"%s\" is not a layer in the HyPerCol.\n", name, windowLayerName);
// abort();
//}
////For now, the window information must come from HyPerLCALayer
//windowLayer = dynamic_cast<HyPerLCALayer *>(origLayer);
//if (windowLayer ==NULL) {
// fprintf(stderr, "WindowTestLayer \"%s\" error: windowLayerName \"%s\" must be a HyPerLCALayer.\n", name, windowLayerName);
// abort();
//}
return status;
}
int WindowTestLayer::allocateDataStructures() {
int status = ANNLayer::allocateDataStructures();
if (status==PV_SUCCESS) {
setActivitytoOne();
}
return status;
}
// set activity to global x/y/f position, using position in border/margin as required
int WindowTestLayer::setActivitytoOne(){
//Make sure window layer is the same size as current layer
//const PVLayerLoc * windowLoc = windowLayer->getLayerLoc();
//const PVLayerLoc * thisLoc = this->getLayerLoc();
//if(windowLoc->nx != thisLoc->nx || windowLoc->ny != thisLoc->ny || windowLoc->nf != thisLoc->nf || windowLoc->nb != thisLoc->nb){
// fprintf(stderr, "WindowTestLayer \"%s\" error: Size (including margins) must equal to the window layer.\n", name);
// abort();
//}
for (int kLocalExt = 0; kLocalExt < clayer->numExtended; kLocalExt++){
//int kWindow = layerIndexExt(kLocalExt, thisLoc, windowLoc);
//int kxGlobalExt = kxPos(kWindow, windowLoc->nx + 2*windowLoc->nb, windowLoc->ny + 2*windowLoc->nb, windowLoc->nf) + windowLoc->kx0;
//int kyGlobalExt = kyPos(kWindow, windowLoc->nx + 2*windowLoc->nb, windowLoc->ny + 2*windowLoc->nb, windowLoc->nf) + windowLoc->ky0;
//int kxGlobalExt = kxPos(kLocalExt, windowLoc->nx + 2*windowLoc->nb, windowLoc->ny + 2*windowLoc->nb, windowLoc->nf) + windowLoc->kx0;
//int kyGlobalExt = kyPos(kLocalExt, windowLoc->nx + 2*windowLoc->nb, windowLoc->ny + 2*windowLoc->nb, windowLoc->nf) + windowLoc->ky0;
//Get window from windowLayer
//int windowId = windowLayer->calcWindow(kxGlobalExt, kyGlobalExt);
clayer->activity->data[kLocalExt] = 1;
}
return PV_SUCCESS;
}
int WindowTestLayer::updateState(double timed, double dt)
{
//updateV();
//setActivity();
//resetGSynBuffers();
//updateActiveIndices();
return PV_SUCCESS;
}
int WindowTestLayer::publish(InterColComm* comm, double timed)
{
setActivitytoOne();
int status = comm->publish(this, clayer->activity);
return status;
//return HyPerLayer::publish(comm, time);
}
} /* namespace PV */
<|endoftext|>
|
<commit_before>#pragma once
#include "utility/memory_cast.hpp"
#include "sha3.h"
#include <assert.h>
#include <array>
#include <stdint.h>
template <size_t NBits>
class Sha3_Hasher {
public:
inline Sha3_Hasher() noexcept {
if constexpr (NBits == 256)
sha3_Init256(&_c);
else if constexpr (NBits == 384)
sha3_Init384(&_c);
else if constexpr (NBits == 256)
sha3_Init512(&_c);
else
static_assert(NBits == 256, "The following SHA3 width is supported: 256, 384, 512 bits");
}
inline void update(const void * const bufIn, const size_t len) noexcept {
assert(!_finalized);
sha3_Update(&_c, bufIn, len);
}
template <typename T>
inline void update(T&& value) noexcept {
static_assert(std::is_trivial_v<std::remove_reference_t<T>>);
this->update(std::addressof(value), sizeof(value));
}
inline std::array<uint8_t, NBits / 8> getHash() noexcept {
assert(!_finalized);
const void* const hashData = sha3_Finalize(&_c);
std::array<uint8_t, NBits / 8> hashDataArray;
::memcpy(hashDataArray.data(), hashData, hashDataArray.size());
_finalized = true;
return hashDataArray;
}
inline uint64_t get64BitHash() noexcept {
const auto fullHash = getHash();
uint64_t hash64 = 0;
for (size_t offset = 0; offset < fullHash.size(); offset += sizeof(uint64_t))
{
const auto eightBytes = memory_cast<uint64_t>(fullHash.data() + offset);
hash64 ^= eightBytes;
}
return hash64;
}
private:
sha3_context _c;
bool _finalized = false;
};
inline uint64_t sha3_64bit(const void * const bufIn, const size_t len) noexcept
{
Sha3_Hasher<256> hasher;
hasher.update(bufIn, len);
return hasher.get64BitHash();
}
<commit_msg>Sha3_Hasher added<commit_after>#pragma once
#include "utility/memory_cast.hpp"
#include "sha3.h"
#include <assert.h>
#include <array>
#include <stdint.h>
template <size_t NBits>
class Sha3_Hasher {
public:
Sha3_Hasher() noexcept
{
if constexpr (NBits == 256)
sha3_Init256(&_c);
else if constexpr (NBits == 384)
sha3_Init384(&_c);
else if constexpr (NBits == 256)
sha3_Init512(&_c);
else
static_assert(NBits == 256, "The following SHA3 width is supported: 256, 384, 512 bits");
}
void update(const void * const bufIn, const size_t len) noexcept
{
assert(!_finalized);
if (len > 0) // it's unclear whether sha3_Update support 0 length. In fact, it seems to underflow it and enter an [almost] infinite loop.
sha3_Update(&_c, bufIn, len);
else
assert(len > 0);
}
void update(const std::string& str) noexcept
{
this->update(str.data(), str.size());
}
template <typename T, typename = std::enable_if_t<is_trivially_serializable_v<std::remove_reference_t<T>>>>
void update(T&& value) noexcept
{
static_assert(is_trivially_serializable_v<std::remove_reference_t<T>>);
this->update(std::addressof(value), sizeof(value));
}
std::array<uint8_t, NBits / 8> getHash() noexcept
{
assert(!_finalized);
const void* const hashData = sha3_Finalize(&_c);
std::array<uint8_t, NBits / 8> hashDataArray;
::memcpy(hashDataArray.data(), hashData, hashDataArray.size());
_finalized = true;
return hashDataArray;
}
uint64_t get64BitHash() noexcept
{
const auto fullHash = getHash();
uint64_t hash64 = 0;
for (size_t offset = 0; offset < fullHash.size(); offset += sizeof(uint64_t))
{
const auto eightBytes = memory_cast<uint64_t>(fullHash.data() + offset);
hash64 ^= eightBytes;
}
return hash64;
}
private:
sha3_context _c;
bool _finalized = false;
};
inline uint64_t sha3_64bit(const void * const bufIn, const size_t len) noexcept
{
Sha3_Hasher<256> hasher;
hasher.update(bufIn, len);
return hasher.get64BitHash();
}
<|endoftext|>
|
<commit_before>/* Copyright (c) 2015 Brian R. Bondy. Distributed under the MPL2 license.
* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/. */
#include "./hash_set_wrap.h"
namespace HashSetWrap {
using v8::Function;
using v8::FunctionCallbackInfo;
using v8::FunctionTemplate;
using v8::Isolate;
using v8::Local;
using v8::Number;
using v8::Object;
using v8::Persistent;
using v8::String;
using v8::Boolean;
using v8::Value;
using v8::NewStringType;
#if V8_MAJOR_VERSION >= 7
#define CHECK_SET(X) X.Check()
#else
#define CHECK_SET(X) (void)X
#endif
Persistent<Function> HashSetWrap::constructor;
HashSetWrap::HashSetWrap(uint32_t bucket_count, bool multi_set)
: HashSet(bucket_count, multi_set) {
}
HashSetWrap::~HashSetWrap() {
}
void HashSetWrap::Init(Local<Object> exports) {
Isolate* isolate = exports->GetIsolate();
// Prepare constructor template
Local<FunctionTemplate> tpl = FunctionTemplate::New(isolate, New);
tpl->SetClassName(String::NewFromUtf8(isolate, "HashSet"));
tpl->InstanceTemplate()->SetInternalFieldCount(1);
// Prototype
NODE_SET_PROTOTYPE_METHOD(tpl, "add", HashSetWrap::AddItem);
NODE_SET_PROTOTYPE_METHOD(tpl, "exists", HashSetWrap::ItemExists);
constructor.Reset(isolate,
tpl->GetFunction(isolate->GetCurrentContext()).ToLocalChecked());
CHECK_SET(exports->Set(isolate->GetCurrentContext(), String::NewFromUtf8(isolate, "HashSet", NewStringType::kNormal).ToLocalChecked(),
tpl->GetFunction(isolate->GetCurrentContext()).ToLocalChecked()));
// exports->Set(String::NewFromUtf8(isolate, "HashSet"),
// tpl->GetFunction(isolate->GetCurrentContext()).ToLocalChecked());
}
void HashSetWrap::New(const FunctionCallbackInfo<Value>& args) {
Isolate* isolate = args.GetIsolate();
if (args.IsConstructCall()) {
// Invoked as constructor: `new HashSet(...)`
HashSetWrap* obj = new HashSetWrap(1024, false);
obj->Wrap(args.This());
args.GetReturnValue().Set(args.This());
} else {
// Invoked as plain function `HashSet(...)`, turn into construct call.
const int argc = 1;
Local<Value> argv[argc] = { args[0] };
Local<Function> cons = Local<Function>::New(isolate, constructor);
args.GetReturnValue().Set(
cons->NewInstance(isolate->GetCurrentContext(), argc, argv)
.ToLocalChecked());
}
}
void HashSetWrap::AddItem(const FunctionCallbackInfo<Value>& args) {
Isolate* isolate = args.GetIsolate();
String::Utf8Value str(isolate,
args[0]->ToString(isolate->GetCurrentContext())
.FromMaybe(v8::Local<v8::String>()));
const char * buffer = *str;
HashSetWrap* obj = ObjectWrap::Unwrap<HashSetWrap>(args.Holder());
obj->Add(ExampleData(buffer));
}
void HashSetWrap::ItemExists(const FunctionCallbackInfo<Value>& args) {
Isolate* isolate = args.GetIsolate();
String::Utf8Value str(isolate,
args[0]->ToString(isolate->GetCurrentContext())
.FromMaybe(v8::Local<v8::String>()));
const char * buffer = *str;
HashSetWrap* obj = ObjectWrap::Unwrap<HashSetWrap>(args.Holder());
bool exists = obj->Exists(ExampleData(buffer));
args.GetReturnValue().Set(Boolean::New(isolate, exists));
}
} // namespace HashSetWrap
<commit_msg>change export setClass<commit_after>/* Copyright (c) 2015 Brian R. Bondy. Distributed under the MPL2 license.
* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/. */
#include "./hash_set_wrap.h"
namespace HashSetWrap {
using v8::Function;
using v8::FunctionCallbackInfo;
using v8::FunctionTemplate;
using v8::Isolate;
using v8::Local;
using v8::Number;
using v8::Object;
using v8::Persistent;
using v8::String;
using v8::Boolean;
using v8::Value;
using v8::NewStringType;
#if V8_MAJOR_VERSION >= 7
#define CHECK_SET(X) X.Check()
#else
#define CHECK_SET(X) (void)X
#endif
Persistent<Function> HashSetWrap::constructor;
HashSetWrap::HashSetWrap(uint32_t bucket_count, bool multi_set)
: HashSet(bucket_count, multi_set) {
}
HashSetWrap::~HashSetWrap() {
}
void HashSetWrap::Init(Local<Object> exports) {
Isolate* isolate = exports->GetIsolate();
// Prepare constructor template
Local<FunctionTemplate> tpl = FunctionTemplate::New(isolate, New);
//tpl->SetClassName(String::NewFromUtf8(isolate, "HashSet"));
tpl->SetClassName(String::NewFromUtf8(isolate, "HashSet", NewStringType::kNormal).ToLocalChecked());
tpl->InstanceTemplate()->SetInternalFieldCount(1);
// Prototype
NODE_SET_PROTOTYPE_METHOD(tpl, "add", HashSetWrap::AddItem);
NODE_SET_PROTOTYPE_METHOD(tpl, "exists", HashSetWrap::ItemExists);
constructor.Reset(isolate,
tpl->GetFunction(isolate->GetCurrentContext()).ToLocalChecked());
CHECK_SET(exports->Set(isolate->GetCurrentContext(), String::NewFromUtf8(isolate, "HashSetecp", NewStringType::kNormal).ToLocalChecked(),
tpl->GetFunction(isolate->GetCurrentContext()).ToLocalChecked()));
// exports->Set(String::NewFromUtf8(isolate, "HashSet"),
// tpl->GetFunction(isolate->GetCurrentContext()).ToLocalChecked());
}
void HashSetWrap::New(const FunctionCallbackInfo<Value>& args) {
Isolate* isolate = args.GetIsolate();
if (args.IsConstructCall()) {
// Invoked as constructor: `new HashSet(...)`
HashSetWrap* obj = new HashSetWrap(1024, false);
obj->Wrap(args.This());
args.GetReturnValue().Set(args.This());
} else {
// Invoked as plain function `HashSet(...)`, turn into construct call.
const int argc = 1;
Local<Value> argv[argc] = { args[0] };
Local<Function> cons = Local<Function>::New(isolate, constructor);
args.GetReturnValue().Set(
cons->NewInstance(isolate->GetCurrentContext(), argc, argv)
.ToLocalChecked());
}
}
void HashSetWrap::AddItem(const FunctionCallbackInfo<Value>& args) {
Isolate* isolate = args.GetIsolate();
String::Utf8Value str(isolate,
args[0]->ToString(isolate->GetCurrentContext())
.FromMaybe(v8::Local<v8::String>()));
const char * buffer = *str;
HashSetWrap* obj = ObjectWrap::Unwrap<HashSetWrap>(args.Holder());
obj->Add(ExampleData(buffer));
}
void HashSetWrap::ItemExists(const FunctionCallbackInfo<Value>& args) {
Isolate* isolate = args.GetIsolate();
String::Utf8Value str(isolate,
args[0]->ToString(isolate->GetCurrentContext())
.FromMaybe(v8::Local<v8::String>()));
const char * buffer = *str;
HashSetWrap* obj = ObjectWrap::Unwrap<HashSetWrap>(args.Holder());
bool exists = obj->Exists(ExampleData(buffer));
args.GetReturnValue().Set(Boolean::New(isolate, exists));
}
} // namespace HashSetWrap
<|endoftext|>
|
<commit_before>/*
* Chemharp, an efficient IO library for chemistry file formats
* Copyright (C) 2015 Guillaume Fraux
*
* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/
*/
#include "chemharp/Topology.hpp"
#include "chemharp/Error.hpp"
#include <algorithm>
using namespace harp;
using std::vector;
void Connectivity::recalculate() const{
_angles.clear();
_dihedrals.clear();
for (auto const& bond1 : _bonds){
// Find angles
for (auto const& bond2 : _bonds){
if (bond1 == bond2) continue;
// Initializing angle to an invalid value
angle angle1(static_cast<size_t>(-1), static_cast<size_t>(-2), static_cast<size_t>(-3));
if (bond1[0] == bond2[1]) {
angle1 = angle(bond2[0], bond2[1], bond1[1]);
_angles.insert(angle1);
} else if (bond1[1] == bond2[0]) {
angle1 = angle(bond1[0], bond1[1], bond2[1]);
_angles.insert(angle1);
} else if (bond1[1] == bond2[1]) {
angle1 = angle(bond1[0], bond1[1], bond2[0]);
_angles.insert(angle1);
} else if (bond1[0] == bond2[0]) {
angle1 = angle(bond1[1], bond1[0], bond2[1]);
_angles.insert(angle1);
} else {
// We will not find any dihedral angle from these bonds
continue;
}
// Find dihedral angles
for (auto const& bond3 : _bonds){
if (bond2 == bond3) continue;
if (angle1[2] == bond3[0] && angle1[1] != bond3[1]){
_dihedrals.insert(dihedral(angle1[0], angle1[1], angle1[2], bond3[1]));
} else if (angle1[0] == bond3[1] && angle1[1] != bond3[0]) {
_dihedrals.insert(dihedral(bond3[0], angle1[0], angle1[1], angle1[2]));
} else if (angle1[2] == bond3[0] || angle1[2] == bond3[1]) {
// TODO this is an improper dihedral
}
}
}
}
uptodate = true;
}
void Connectivity::clear(){
_bonds.clear();
_angles.clear();
_dihedrals.clear();
}
const std::unordered_set<bond>& Connectivity::bonds() const {
if (!uptodate)
recalculate();
return _bonds;
}
const std::unordered_set<angle>& Connectivity::angles() const {
if (!uptodate)
recalculate();
return _angles;
}
const std::unordered_set<dihedral>& Connectivity::dihedrals() const {
if (!uptodate)
recalculate();
return _dihedrals;
}
void Connectivity::add_bond(size_t i, size_t j){
uptodate = false;
_bonds.insert(bond(i, j));
}
void Connectivity::remove_bond(size_t i, size_t j){
uptodate = false;
auto pos = _bonds.find(bond(i, j));
if (pos != _bonds.end()){
_bonds.erase(pos);
}
}
/******************************************************************************/
Topology::Topology(size_t natoms) {
resize(natoms);
}
Topology::Topology() : Topology(0) {}
void Topology::append(const Atom& _atom){
size_t index = static_cast<size_t>(-1);
for (size_t i = 0 ; i<_templates.size(); i++)
if (_templates[i] == _atom)
index = i;
if (index == static_cast<size_t>(-1)) { // Atom not found
_templates.push_back(_atom);
index = _templates.size() - 1;
}
_atoms.push_back(index);
}
void Topology::remove(size_t idx) {
if (idx < _atoms.size())
_atoms.erase(begin(_atoms) + idx);
auto bonds = _connect.bonds();
for (auto& bond : bonds){
if (bond[0] == idx || bond[1] == idx)
_connect.remove_bond(bond[0], bond[1]);
}
recalculate();
}
vector<bond> Topology::bonds() const{
vector<bond> res;
res.insert(begin(res), begin(_connect.bonds()), end(_connect.bonds()));
return std::move(res);
}
vector<angle> Topology::angles() const{
vector<angle> res;
res.insert(begin(res), begin(_connect.angles()), end(_connect.angles()));
return std::move(res);
}
vector<dihedral> Topology::dihedrals() const{
vector<dihedral> res;
res.insert(begin(res), begin(_connect.dihedrals()), end(_connect.dihedrals()));
return std::move(res);
}
bool Topology::isbond(size_t i, size_t j) const {
auto bonds = _connect.bonds();
auto pos = bonds.find(bond(i, j));
return pos != end(bonds);
}
bool Topology::isangle(size_t i, size_t j, size_t k) const {
auto angles = _connect.angles();
auto pos = angles.find(angle(i, j, k));
return pos != end(angles);
}
bool Topology::isdihedral(size_t i, size_t j, size_t k, size_t m) const {
auto dihedrals = _connect.dihedrals();
auto pos = dihedrals.find(dihedral(i, j, k, m));
return pos != end(dihedrals);
}
void Topology::clear(){
_templates.clear();
_atoms.clear();
_connect.clear();
}
Topology harp::dummy_topology(size_t natoms){
Topology top(0);
for (size_t i=0; i<natoms; i++)
top.append(Atom(Atom::UNDEFINED));
return top;
}
<commit_msg>Fix a warning on Clang<commit_after>/*
* Chemharp, an efficient IO library for chemistry file formats
* Copyright (C) 2015 Guillaume Fraux
*
* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/
*/
#include "chemharp/Topology.hpp"
#include "chemharp/Error.hpp"
#include <algorithm>
using namespace harp;
using std::vector;
void Connectivity::recalculate() const{
_angles.clear();
_dihedrals.clear();
for (auto const& bond1 : _bonds){
// Find angles
for (auto const& bond2 : _bonds){
if (bond1 == bond2) continue;
// Initializing angle to an invalid value
angle angle1(static_cast<size_t>(-1), static_cast<size_t>(-2), static_cast<size_t>(-3));
if (bond1[0] == bond2[1]) {
angle1 = angle(bond2[0], bond2[1], bond1[1]);
_angles.insert(angle1);
} else if (bond1[1] == bond2[0]) {
angle1 = angle(bond1[0], bond1[1], bond2[1]);
_angles.insert(angle1);
} else if (bond1[1] == bond2[1]) {
angle1 = angle(bond1[0], bond1[1], bond2[0]);
_angles.insert(angle1);
} else if (bond1[0] == bond2[0]) {
angle1 = angle(bond1[1], bond1[0], bond2[1]);
_angles.insert(angle1);
} else {
// We will not find any dihedral angle from these bonds
continue;
}
// Find dihedral angles
for (auto const& bond3 : _bonds){
if (bond2 == bond3) continue;
if (angle1[2] == bond3[0] && angle1[1] != bond3[1]){
_dihedrals.insert(dihedral(angle1[0], angle1[1], angle1[2], bond3[1]));
} else if (angle1[0] == bond3[1] && angle1[1] != bond3[0]) {
_dihedrals.insert(dihedral(bond3[0], angle1[0], angle1[1], angle1[2]));
} else if (angle1[2] == bond3[0] || angle1[2] == bond3[1]) {
// TODO this is an improper dihedral
}
}
}
}
uptodate = true;
}
void Connectivity::clear(){
_bonds.clear();
_angles.clear();
_dihedrals.clear();
}
const std::unordered_set<bond>& Connectivity::bonds() const {
if (!uptodate)
recalculate();
return _bonds;
}
const std::unordered_set<angle>& Connectivity::angles() const {
if (!uptodate)
recalculate();
return _angles;
}
const std::unordered_set<dihedral>& Connectivity::dihedrals() const {
if (!uptodate)
recalculate();
return _dihedrals;
}
void Connectivity::add_bond(size_t i, size_t j){
uptodate = false;
_bonds.insert(bond(i, j));
}
void Connectivity::remove_bond(size_t i, size_t j){
uptodate = false;
auto pos = _bonds.find(bond(i, j));
if (pos != _bonds.end()){
_bonds.erase(pos);
}
}
/******************************************************************************/
Topology::Topology(size_t natoms) {
resize(natoms);
}
Topology::Topology() : Topology(0) {}
void Topology::append(const Atom& _atom){
size_t index = static_cast<size_t>(-1);
for (size_t i = 0 ; i<_templates.size(); i++)
if (_templates[i] == _atom)
index = i;
if (index == static_cast<size_t>(-1)) { // Atom not found
_templates.push_back(_atom);
index = _templates.size() - 1;
}
_atoms.push_back(index);
}
void Topology::remove(size_t idx) {
if (idx < _atoms.size())
_atoms.erase(begin(_atoms) + idx);
auto bonds = _connect.bonds();
for (auto& bond : bonds){
if (bond[0] == idx || bond[1] == idx)
_connect.remove_bond(bond[0], bond[1]);
}
recalculate();
}
vector<bond> Topology::bonds() const{
vector<bond> res;
res.insert(begin(res), begin(_connect.bonds()), end(_connect.bonds()));
return res;
}
vector<angle> Topology::angles() const{
vector<angle> res;
res.insert(begin(res), begin(_connect.angles()), end(_connect.angles()));
return res;
}
vector<dihedral> Topology::dihedrals() const{
vector<dihedral> res;
res.insert(begin(res), begin(_connect.dihedrals()), end(_connect.dihedrals()));
return res;
}
bool Topology::isbond(size_t i, size_t j) const {
auto bonds = _connect.bonds();
auto pos = bonds.find(bond(i, j));
return pos != end(bonds);
}
bool Topology::isangle(size_t i, size_t j, size_t k) const {
auto angles = _connect.angles();
auto pos = angles.find(angle(i, j, k));
return pos != end(angles);
}
bool Topology::isdihedral(size_t i, size_t j, size_t k, size_t m) const {
auto dihedrals = _connect.dihedrals();
auto pos = dihedrals.find(dihedral(i, j, k, m));
return pos != end(dihedrals);
}
void Topology::clear(){
_templates.clear();
_atoms.clear();
_connect.clear();
}
Topology harp::dummy_topology(size_t natoms){
Topology top(0);
for (size_t i=0; i<natoms; i++)
top.append(Atom(Atom::UNDEFINED));
return top;
}
<|endoftext|>
|
<commit_before>/* Sirikata
* main.cpp
*
* Copyright (c) 2008, Daniel Reiter Horn
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are
* met:
* * Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* * Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in
* the documentation and/or other materials provided with the
* distribution.
* * Neither the name of Sirikata nor the names of its contributors may
* be used to endorse or promote products derived from this software
* without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS
* IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED
* TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A
* PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER
* OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
* EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
* PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
* PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
* LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
* NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
#include <oh/Platform.hpp>
#include <util/RoutableMessageHeader.hpp>
#include <options/Options.hpp>
#include <util/PluginManager.hpp>
#include <oh/SimulationFactory.hpp>
#include <task/EventManager.hpp>
#include <task/WorkQueue.hpp>
#include "CDNConfig.hpp"
#include <oh/ObjectHost.hpp>
#include <oh/LightInfo.hpp>
#include <oh/TopLevelSpaceConnection.hpp>
#include <oh/SpaceConnection.hpp>
#include <oh/HostedObject.hpp>
#include <oh/SpaceIDMap.hpp>
#include <network/IOServiceFactory.hpp>
#include <ObjectHost_Sirikata.pbj.hpp>
namespace Sirikata {
using Task::GenEventManager;
using Transfer::TransferManager;
OptionValue *cdnConfigFile;
OptionValue *floatExcept;
InitializeGlobalOptions main_options("",
// simulationPlugins=new OptionValue("simulationPlugins","ogregraphics",OptionValueType<String>(),"List of plugins that handle simulation."),
cdnConfigFile=new OptionValue("cdnConfig","cdn = ($import=cdn.txt)",OptionValueType<String>(),"CDN configuration."),
floatExcept=new OptionValue("sigfpe","false",OptionValueType<bool>(),"Enable floating point exceptions"),
NULL
);
std::string cut(const std::string &source, std::string::size_type start, std::string::size_type end) {
using namespace std;
while (isspace(source[start]) && start < end) {
++start;
}
while (end > start && isspace(source[end-1])) {
--end;
}
return source.substr(start,end-start);
}
namespace {
typedef std::map<OptionMapPtr, std::string> GlobalMap;
std::ostream &display (std::ostream &os, const OptionMap &om, const GlobalMap &globals, int level) {
int numspaces = level*4;
for (OptionMap::const_iterator iter = om.begin(); iter != om.end(); ++iter) {
OptionMapPtr child = (*iter).second;
os << std::string(numspaces, ' ');
os << (*iter).first << " = ";
GlobalMap::const_iterator globaliter = globals.find(child);
if (level>0 && globaliter != globals.end()) {
os << "$" << (*globaliter).second;
} else {
os << child->getValue();
if (!child->empty()) {
os << "(" << std::endl;
display(os,*child,globals,level+1);
os << std::string(numspaces, ' ');
os << ")";
}
}
os << std::endl;
}
return os;
}
}
std::ostream &operator<< (std::ostream &os, const OptionMap &om) {
GlobalMap globals;
for (OptionMap::const_iterator iter = om.begin(); iter != om.end(); ++iter) {
globals[(*iter).second] = (*iter).first;
}
return display(os, om, globals, 0);
}
enum ParseState {KEYSTATE, EQSTATE, VALUESTATE, NUMSTATES };
void handleCommand(const std::string &input, const OptionMapPtr &globalvariables, const OptionMapPtr &options, std::string::size_type &pos, const std::string &key, const std::string &value) {
if (key == "$import") {
std::string::size_type slash = value.rfind('/');
std::string::size_type backslash = value.rfind('\\');
if (slash == std::string::npos && backslash ==std::string::npos) {
std::string fname = "./" + value;
if (value.find(".txt")!=std::string::npos) {
FILE *fp = NULL;
for (int i = 0; i < 4 && fp == NULL; i++) {
fp = fopen(fname.c_str(),"rt");
fname = "./."+fname;
}
std::string str;
while (fp && !feof(fp)) {
char buf[1024];
int numread = fread(buf, 1, 1024, fp);
if (numread <= 0) {
break;
}
str += std::string(buf, buf+numread);
}
if (fp) {
fclose(fp);
} else {
SILOG(main,error,"Configuration file "<<value<<" does not exist");
}
std::string::size_type subpos = 0;
// current level becomes the global level.
parseConfig(str, options, options, subpos);
}
}
} else {
SILOG(main,error,"Unknown command "<<key<<"("<<value<<")");
}
}
void parseConfig(
const std::string &input,
const OptionMapPtr &globalvariables,
const OptionMapPtr &options,
std::string::size_type &pos)
{
std::string::size_type len = input.length();
std::string key;
std::string::size_type beginpos = pos;
OptionMapPtr currentValue;
/* states:
0 = Key, looking for '='
1 = Looking for value, but have not encountered whitespace.
2 = Value, will end at next whitespace character.
*/
ParseState state = KEYSTATE;
for (; pos <= len; ++pos) {
char ch;
if (pos >= len) {
ch = ')';
} else {
ch = input[pos];
}
if (state==KEYSTATE && ch == '#') {
/* comment up to ')' */
for (; pos < len; ++pos) {
if (input[pos]=='\n') break;
}
beginpos = pos;
} else if (ch == '(' || ch==')' || (state != KEYSTATE && isspace(ch))) {
if (state == VALUESTATE) {
std::string value(cut(input, beginpos, pos));
if (value.length()) {
OptionMapPtr toInsert;
if (value[0]=='$') {
toInsert = (*globalvariables).get(value.substr(1));
if (!toInsert) {
toInsert = OptionMapPtr(new OptionMap);
(*globalvariables).put(value.substr(1), toInsert);
}
}
if (key.length() && key[0]=='$') {
handleCommand(input,globalvariables,options,pos,key,value);
} else {
if (!toInsert) {
toInsert = (*options).get(key);
if (!toInsert) {
toInsert = OptionMapPtr(new OptionMap(value));
}
}
currentValue = options->put(key, toInsert);
}
state = KEYSTATE;
}
beginpos = pos+1;
}
if (ch == '(') {
if (!currentValue) {
currentValue = options->get(key);
if (!currentValue) {
currentValue = options->put(key, OptionMapPtr(new OptionMap));
}
}
/* Note: If you have KEY = $variable ( key1=value1 key2=value2 ) will add key1 and key2 to variable as well. */
pos++;
parseConfig(input, globalvariables, currentValue, pos);
beginpos = pos+1;
state = KEYSTATE;
} else if (ch == ')') {
break;
}
} else if (state == KEYSTATE && ch=='=') {
key = cut(input, beginpos, pos);
state = EQSTATE;
beginpos = pos+1;
currentValue = OptionMapPtr();
} else if (state == EQSTATE && !isspace(ch)) {
state = VALUESTATE;
}
}
}
}
#ifdef __GNUC__
#include <fenv.h>
#endif
int main ( int argc,const char**argv ) {
int myargc = argc+2;
const char **myargv = new const char*[myargc];
memcpy(myargv, argv, argc*sizeof(const char*));
myargv[argc] = "--moduleloglevel";
myargv[argc+1] = "transfer=fatal,ogre=fatal,task=fatal,resource=fatal";
using namespace Sirikata;
PluginManager plugins;
plugins.load ( DynamicLibrary::filename("ogregraphics") );
plugins.load ( DynamicLibrary::filename("bulletphysics") );
OptionSet::getOptions ( "" )->parse ( myargc,myargv );
#ifdef __GNUC__
if (floatExcept->as<bool>()) {
feenableexcept(FE_DIVBYZERO|FE_INVALID|FE_OVERFLOW|FE_UNDERFLOW);
}
#endif
OptionMapPtr transferOptions (new OptionMap);
{
std::string contents(cdnConfigFile->as<String>());
std::string::size_type pos(0);
parseConfig(contents, transferOptions, transferOptions, pos);
std::cout << *transferOptions;
}
initializeProtocols();
Network::IOService *ioServ = Network::IOServiceFactory::makeIOService();
SpaceID mainSpace(UUID("12345678-1111-1111-1111-DEFA01759ACE",UUID::HumanReadable()));
SpaceIDMap *spaceMap = new SpaceIDMap;
spaceMap->insert(mainSpace, Network::Address("127.0.0.1","5943"));
ObjectHost *oh = new ObjectHost(spaceMap, ioServ);
{//to deallocate HostedObjects before armageddon
HostedObjectPtr firstObject (HostedObject::construct<HostedObject>(oh));
firstObject->initializeConnect(
UUID::random(),
Location(Vector3d(0, ((double)(time(NULL)%10)) - 5 , 0), Quaternion::identity(),
Vector3f(0.2,0,0), Vector3f(0,0,1), 0.),
"meru://daniel@/cube.mesh",
BoundingSphere3f(Vector3f::nil(),1),
NULL,
mainSpace);
firstObject->setScale(Vector3f(3,3,3));
HostedObjectPtr secondObject (HostedObject::construct<HostedObject>(oh));
secondObject->initializeConnect(
UUID::random(),
Location(Vector3d(0,0,25), Quaternion::identity(),
Vector3f(0.1,0,0), Vector3f(0,0,1), 0.),
"",
BoundingSphere3f(Vector3f::nil(),0),
NULL,
mainSpace);
HostedObjectPtr thirdObject (HostedObject::construct<HostedObject>(oh));
{
LightInfo li;
li.setLightDiffuseColor(Color(0.976471, 0.992157, 0.733333));
li.setLightAmbientColor(Color(.24,.25,.18));
li.setLightSpecularColor(Color(0,0,0));
li.setLightShadowColor(Color(0,0,0));
li.setLightPower(1.0);
li.setLightRange(75);
li.setLightFalloff(1,0,0.03);
li.setLightSpotlightCone(30,40,1);
li.setCastsShadow(true);
thirdObject->initializeConnect(
UUID::random(),
Location(Vector3d(10,0,10), Quaternion::identity(),
Vector3f::nil(), Vector3f(0,0,1), 0.),
"",
BoundingSphere3f(Vector3f::nil(),0),
&li,
mainSpace);
}
ProxyManager *provider = oh->getProxyManager(mainSpace);
Task::WorkQueue *workQueue = new Task::LockFreeWorkQueue;
Task::GenEventManager *eventManager = new Task::GenEventManager(workQueue);
TransferManager *tm;
try {
tm = initializeTransferManager((*transferOptions)["cdn"], eventManager);
} catch (OptionDoesNotExist &err) {
SILOG(input,fatal,"Fatal Error: Failed to load CDN config: " << err.what());
std::cout << "Press enter to continue" << std::endl;
std::cerr << "Press enter to continue" << std::endl;
fgetc(stdin);
return 1;
}
OptionSet::getOptions("")->parse(myargc,myargv);
String graphicsCommandArguments;
{
std::ostringstream os;
os << "--transfermanager=" << tm << " ";
os << "--eventmanager=" << eventManager << " ";
os << "--workqueue=" << workQueue << " ";
graphicsCommandArguments = os.str();
}
if (!provider) {
SILOG(cppoh,error,"Failed to get TopLevelSpaceConnection for main space "<<mainSpace);
}
String graphicsPluginName ( "ogregraphics" );
String physicsPluginName ( "bulletphysics" );
SILOG(cppoh,error,"dbm: initializing graphics");
TimeSteppedSimulation *graphicsSystem=
SimulationFactory::getSingleton()
.getConstructor ( graphicsPluginName ) ( provider,graphicsCommandArguments );
SILOG(cppoh,error,"dbm: initializing physics");
TimeSteppedSimulation *physicsSystem=
SimulationFactory::getSingleton()
.getConstructor ( physicsPluginName ) ( provider,graphicsCommandArguments );
if (!physicsSystem) {
SILOG(cppoh,error,"physicsSystem NULL!");
}
else {
SILOG(cppoh,error,"physicsSystem: " << std::hex << (unsigned long)physicsSystem);
}
if ( graphicsSystem ) {
while ( graphicsSystem->tick() ) {
physicsSystem->tick();
Network::IOServiceFactory::pollService(ioServ);
}
} else {
SILOG(cppoh,error,"Fatal Error: Unable to load OGRE Graphics plugin. The PATH environment variable is ignored, so make sure you have copied the DLLs from dependencies/ogre/bin/ into the current directory. Sorry about this!");
std::cout << "Press enter to continue" << std::endl;
std::cerr << "Press enter to continue" << std::endl;
fgetc(stdin);
}
delete graphicsSystem;
delete eventManager;
delete workQueue;
}
plugins.gc();
SimulationFactory::destroy();
delete oh;
Network::IOServiceFactory::destroyIOService(ioServ);
delete spaceMap;
delete []myargv;
return 0;
}
<commit_msg>Mac does not define feenableexcept()<commit_after>/* Sirikata
* main.cpp
*
* Copyright (c) 2008, Daniel Reiter Horn
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are
* met:
* * Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* * Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in
* the documentation and/or other materials provided with the
* distribution.
* * Neither the name of Sirikata nor the names of its contributors may
* be used to endorse or promote products derived from this software
* without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS
* IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED
* TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A
* PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER
* OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
* EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
* PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
* PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
* LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
* NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
#include <oh/Platform.hpp>
#include <util/RoutableMessageHeader.hpp>
#include <options/Options.hpp>
#include <util/PluginManager.hpp>
#include <oh/SimulationFactory.hpp>
#include <task/EventManager.hpp>
#include <task/WorkQueue.hpp>
#include "CDNConfig.hpp"
#include <oh/ObjectHost.hpp>
#include <oh/LightInfo.hpp>
#include <oh/TopLevelSpaceConnection.hpp>
#include <oh/SpaceConnection.hpp>
#include <oh/HostedObject.hpp>
#include <oh/SpaceIDMap.hpp>
#include <network/IOServiceFactory.hpp>
#include <ObjectHost_Sirikata.pbj.hpp>
namespace Sirikata {
using Task::GenEventManager;
using Transfer::TransferManager;
OptionValue *cdnConfigFile;
OptionValue *floatExcept;
InitializeGlobalOptions main_options("",
// simulationPlugins=new OptionValue("simulationPlugins","ogregraphics",OptionValueType<String>(),"List of plugins that handle simulation."),
cdnConfigFile=new OptionValue("cdnConfig","cdn = ($import=cdn.txt)",OptionValueType<String>(),"CDN configuration."),
floatExcept=new OptionValue("sigfpe","false",OptionValueType<bool>(),"Enable floating point exceptions"),
NULL
);
std::string cut(const std::string &source, std::string::size_type start, std::string::size_type end) {
using namespace std;
while (isspace(source[start]) && start < end) {
++start;
}
while (end > start && isspace(source[end-1])) {
--end;
}
return source.substr(start,end-start);
}
namespace {
typedef std::map<OptionMapPtr, std::string> GlobalMap;
std::ostream &display (std::ostream &os, const OptionMap &om, const GlobalMap &globals, int level) {
int numspaces = level*4;
for (OptionMap::const_iterator iter = om.begin(); iter != om.end(); ++iter) {
OptionMapPtr child = (*iter).second;
os << std::string(numspaces, ' ');
os << (*iter).first << " = ";
GlobalMap::const_iterator globaliter = globals.find(child);
if (level>0 && globaliter != globals.end()) {
os << "$" << (*globaliter).second;
} else {
os << child->getValue();
if (!child->empty()) {
os << "(" << std::endl;
display(os,*child,globals,level+1);
os << std::string(numspaces, ' ');
os << ")";
}
}
os << std::endl;
}
return os;
}
}
std::ostream &operator<< (std::ostream &os, const OptionMap &om) {
GlobalMap globals;
for (OptionMap::const_iterator iter = om.begin(); iter != om.end(); ++iter) {
globals[(*iter).second] = (*iter).first;
}
return display(os, om, globals, 0);
}
enum ParseState {KEYSTATE, EQSTATE, VALUESTATE, NUMSTATES };
void handleCommand(const std::string &input, const OptionMapPtr &globalvariables, const OptionMapPtr &options, std::string::size_type &pos, const std::string &key, const std::string &value) {
if (key == "$import") {
std::string::size_type slash = value.rfind('/');
std::string::size_type backslash = value.rfind('\\');
if (slash == std::string::npos && backslash ==std::string::npos) {
std::string fname = "./" + value;
if (value.find(".txt")!=std::string::npos) {
FILE *fp = NULL;
for (int i = 0; i < 4 && fp == NULL; i++) {
fp = fopen(fname.c_str(),"rt");
fname = "./."+fname;
}
std::string str;
while (fp && !feof(fp)) {
char buf[1024];
int numread = fread(buf, 1, 1024, fp);
if (numread <= 0) {
break;
}
str += std::string(buf, buf+numread);
}
if (fp) {
fclose(fp);
} else {
SILOG(main,error,"Configuration file "<<value<<" does not exist");
}
std::string::size_type subpos = 0;
// current level becomes the global level.
parseConfig(str, options, options, subpos);
}
}
} else {
SILOG(main,error,"Unknown command "<<key<<"("<<value<<")");
}
}
void parseConfig(
const std::string &input,
const OptionMapPtr &globalvariables,
const OptionMapPtr &options,
std::string::size_type &pos)
{
std::string::size_type len = input.length();
std::string key;
std::string::size_type beginpos = pos;
OptionMapPtr currentValue;
/* states:
0 = Key, looking for '='
1 = Looking for value, but have not encountered whitespace.
2 = Value, will end at next whitespace character.
*/
ParseState state = KEYSTATE;
for (; pos <= len; ++pos) {
char ch;
if (pos >= len) {
ch = ')';
} else {
ch = input[pos];
}
if (state==KEYSTATE && ch == '#') {
/* comment up to ')' */
for (; pos < len; ++pos) {
if (input[pos]=='\n') break;
}
beginpos = pos;
} else if (ch == '(' || ch==')' || (state != KEYSTATE && isspace(ch))) {
if (state == VALUESTATE) {
std::string value(cut(input, beginpos, pos));
if (value.length()) {
OptionMapPtr toInsert;
if (value[0]=='$') {
toInsert = (*globalvariables).get(value.substr(1));
if (!toInsert) {
toInsert = OptionMapPtr(new OptionMap);
(*globalvariables).put(value.substr(1), toInsert);
}
}
if (key.length() && key[0]=='$') {
handleCommand(input,globalvariables,options,pos,key,value);
} else {
if (!toInsert) {
toInsert = (*options).get(key);
if (!toInsert) {
toInsert = OptionMapPtr(new OptionMap(value));
}
}
currentValue = options->put(key, toInsert);
}
state = KEYSTATE;
}
beginpos = pos+1;
}
if (ch == '(') {
if (!currentValue) {
currentValue = options->get(key);
if (!currentValue) {
currentValue = options->put(key, OptionMapPtr(new OptionMap));
}
}
/* Note: If you have KEY = $variable ( key1=value1 key2=value2 ) will add key1 and key2 to variable as well. */
pos++;
parseConfig(input, globalvariables, currentValue, pos);
beginpos = pos+1;
state = KEYSTATE;
} else if (ch == ')') {
break;
}
} else if (state == KEYSTATE && ch=='=') {
key = cut(input, beginpos, pos);
state = EQSTATE;
beginpos = pos+1;
currentValue = OptionMapPtr();
} else if (state == EQSTATE && !isspace(ch)) {
state = VALUESTATE;
}
}
}
}
#ifdef __GNUC__
#include <fenv.h>
#endif
int main ( int argc,const char**argv ) {
int myargc = argc+2;
const char **myargv = new const char*[myargc];
memcpy(myargv, argv, argc*sizeof(const char*));
myargv[argc] = "--moduleloglevel";
myargv[argc+1] = "transfer=fatal,ogre=fatal,task=fatal,resource=fatal";
using namespace Sirikata;
PluginManager plugins;
plugins.load ( DynamicLibrary::filename("ogregraphics") );
plugins.load ( DynamicLibrary::filename("bulletphysics") );
OptionSet::getOptions ( "" )->parse ( myargc,myargv );
#ifdef __GNUC__
#ifndef __APPLE__
if (floatExcept->as<bool>()) {
feenableexcept(FE_DIVBYZERO|FE_INVALID|FE_OVERFLOW|FE_UNDERFLOW);
}
#endif
#endif
OptionMapPtr transferOptions (new OptionMap);
{
std::string contents(cdnConfigFile->as<String>());
std::string::size_type pos(0);
parseConfig(contents, transferOptions, transferOptions, pos);
std::cout << *transferOptions;
}
initializeProtocols();
Network::IOService *ioServ = Network::IOServiceFactory::makeIOService();
SpaceID mainSpace(UUID("12345678-1111-1111-1111-DEFA01759ACE",UUID::HumanReadable()));
SpaceIDMap *spaceMap = new SpaceIDMap;
spaceMap->insert(mainSpace, Network::Address("127.0.0.1","5943"));
ObjectHost *oh = new ObjectHost(spaceMap, ioServ);
{//to deallocate HostedObjects before armageddon
HostedObjectPtr firstObject (HostedObject::construct<HostedObject>(oh));
firstObject->initializeConnect(
UUID::random(),
Location(Vector3d(0, ((double)(time(NULL)%10)) - 5 , 0), Quaternion::identity(),
Vector3f(0.2,0,0), Vector3f(0,0,1), 0.),
"meru://daniel@/cube.mesh",
BoundingSphere3f(Vector3f::nil(),1),
NULL,
mainSpace);
firstObject->setScale(Vector3f(3,3,3));
HostedObjectPtr secondObject (HostedObject::construct<HostedObject>(oh));
secondObject->initializeConnect(
UUID::random(),
Location(Vector3d(0,0,25), Quaternion::identity(),
Vector3f(0.1,0,0), Vector3f(0,0,1), 0.),
"",
BoundingSphere3f(Vector3f::nil(),0),
NULL,
mainSpace);
HostedObjectPtr thirdObject (HostedObject::construct<HostedObject>(oh));
{
LightInfo li;
li.setLightDiffuseColor(Color(0.976471, 0.992157, 0.733333));
li.setLightAmbientColor(Color(.24,.25,.18));
li.setLightSpecularColor(Color(0,0,0));
li.setLightShadowColor(Color(0,0,0));
li.setLightPower(1.0);
li.setLightRange(75);
li.setLightFalloff(1,0,0.03);
li.setLightSpotlightCone(30,40,1);
li.setCastsShadow(true);
thirdObject->initializeConnect(
UUID::random(),
Location(Vector3d(10,0,10), Quaternion::identity(),
Vector3f::nil(), Vector3f(0,0,1), 0.),
"",
BoundingSphere3f(Vector3f::nil(),0),
&li,
mainSpace);
}
ProxyManager *provider = oh->getProxyManager(mainSpace);
Task::WorkQueue *workQueue = new Task::LockFreeWorkQueue;
Task::GenEventManager *eventManager = new Task::GenEventManager(workQueue);
TransferManager *tm;
try {
tm = initializeTransferManager((*transferOptions)["cdn"], eventManager);
} catch (OptionDoesNotExist &err) {
SILOG(input,fatal,"Fatal Error: Failed to load CDN config: " << err.what());
std::cout << "Press enter to continue" << std::endl;
std::cerr << "Press enter to continue" << std::endl;
fgetc(stdin);
return 1;
}
OptionSet::getOptions("")->parse(myargc,myargv);
String graphicsCommandArguments;
{
std::ostringstream os;
os << "--transfermanager=" << tm << " ";
os << "--eventmanager=" << eventManager << " ";
os << "--workqueue=" << workQueue << " ";
graphicsCommandArguments = os.str();
}
if (!provider) {
SILOG(cppoh,error,"Failed to get TopLevelSpaceConnection for main space "<<mainSpace);
}
String graphicsPluginName ( "ogregraphics" );
String physicsPluginName ( "bulletphysics" );
SILOG(cppoh,error,"dbm: initializing graphics");
TimeSteppedSimulation *graphicsSystem=
SimulationFactory::getSingleton()
.getConstructor ( graphicsPluginName ) ( provider,graphicsCommandArguments );
SILOG(cppoh,error,"dbm: initializing physics");
TimeSteppedSimulation *physicsSystem=
SimulationFactory::getSingleton()
.getConstructor ( physicsPluginName ) ( provider,graphicsCommandArguments );
if (!physicsSystem) {
SILOG(cppoh,error,"physicsSystem NULL!");
}
else {
SILOG(cppoh,error,"physicsSystem: " << std::hex << (unsigned long)physicsSystem);
}
if ( graphicsSystem ) {
while ( graphicsSystem->tick() ) {
physicsSystem->tick();
Network::IOServiceFactory::pollService(ioServ);
}
} else {
SILOG(cppoh,error,"Fatal Error: Unable to load OGRE Graphics plugin. The PATH environment variable is ignored, so make sure you have copied the DLLs from dependencies/ogre/bin/ into the current directory. Sorry about this!");
std::cout << "Press enter to continue" << std::endl;
std::cerr << "Press enter to continue" << std::endl;
fgetc(stdin);
}
delete graphicsSystem;
delete eventManager;
delete workQueue;
}
plugins.gc();
SimulationFactory::destroy();
delete oh;
Network::IOServiceFactory::destroyIOService(ioServ);
delete spaceMap;
delete []myargv;
return 0;
}
<|endoftext|>
|
<commit_before>#include "Segmentation.h"
#include "Lab.h"
#include "RGB.h"
template <>
double
Segmentation<ImgClass::RGB>::distance(const ImgClass::RGB& lvalue, const ImgClass::RGB& rvalue)
{
return sqrt(
SQUARE(lvalue.R - rvalue.R)
+ SQUARE(lvalue.G - rvalue.G)
+ SQUARE(lvalue.B - rvalue.B));
}
template <>
double
Segmentation<ImgClass::RGB>::normalized_distance(const ImgClass::RGB& lvalue, const ImgClass::RGB& rvalue)
{
return sqrt(
SQUARE(lvalue.R - rvalue.R)
+ SQUARE(lvalue.G - rvalue.G)
+ SQUARE(lvalue.B - rvalue.B));
}
template <>
double
Segmentation<ImgClass::Lab>::distance(const ImgClass::Lab& lvalue, const ImgClass::Lab& rvalue)
{
return sqrt(
SQUARE(lvalue.L - rvalue.L)
+ SQUARE(lvalue.a - rvalue.a)
+ SQUARE(lvalue.b - rvalue.b));
}
template <>
double
Segmentation<ImgClass::Lab>::normalized_distance(const ImgClass::Lab& lvalue, const ImgClass::Lab& rvalue)
{
return sqrt(
SQUARE(lvalue.L - rvalue.L)
+ SQUARE(lvalue.a - rvalue.a)
+ SQUARE(lvalue.b - rvalue.b)) / 100.0;
}
/*
* std::vector<double> kernel has kernel radius for each dimensions.
* The values it needs are below:
* _kernel_spatial : the spatial radius of mean shift kernel
* _kernel_intensity : the norm threshold of mean shift kernel in L*a*b* space
*/
template <> // Specialized for ImgClass::RGB<double>
const ImgClass::Segmentation::tuple<ImgClass::RGB>
Segmentation<ImgClass::RGB>::MeanShift(const int x, const int y, std::vector<VECTOR_2D<int> >& pel_list, int Iter_Max)
{
const double radius_spatial_squared = SQUARE(_kernel_spatial);
const double radius_intensity_squared = SQUARE(_kernel_intensity);
const double displacement_min = SQUARE(0.01);
ImgClass::Segmentation::tuple<ImgClass::RGB> tuple;
// Initialize
tuple.spatial = VECTOR_2D<double>(static_cast<double>(x), static_cast<double>(y));
tuple.color = _image.get(x, y);
// Iterate until it converge
for (int i = 0; i < Iter_Max; i++) {
double N = 0.0;
ImgClass::RGB sum_diff(0.0, 0.0, 0.0);
VECTOR_2D<double> sum_d(0.0, 0.0);
for (size_t n = 0; n < pel_list.size(); n++) {
VECTOR_2D<int> r(
static_cast<int>(round(tuple.spatial.x) + pel_list[n].x),
static_cast<int>(round(tuple.spatial.y) + pel_list[n].y));
if (0 <= r.x && r.x < _width && 0 <= r.y && r.y < _height) {
ImgClass::RGB diff(_image.get(r.x, r.y) - tuple.color);
VECTOR_2D<double> d(r.x - tuple.spatial.x, r.y - tuple.spatial.y);
double ratio_intensity = norm_squared(diff) / radius_intensity_squared;
double ratio_spatial = norm_squared(d) / radius_spatial_squared;
if (ratio_intensity <= 1.0 && ratio_spatial <= 1.0) {
double coeff = 1.0 - (ratio_intensity * ratio_spatial);
N += coeff;
sum_diff += diff * coeff;
sum_d += d * coeff;
}
}
}
tuple.color += sum_diff / N;
VECTOR_2D<double> displacement(sum_d.x / N, sum_d.y / N);
tuple.spatial += displacement;
if (norm_squared(sum_diff /N) * norm_squared(displacement) < displacement_min) {
break;
}
}
return tuple;
}
/*
* std::vector<double> kernel has kernel radius for each dimensions.
* The values it needs are below:
* _kernel_spatial : the spatial radius of mean shift kernel
* _kernel_intensity : the norm threshold of mean shift kernel in L*a*b* space
*/
template <> // Specialized for ImgClass::Lab
const ImgClass::Segmentation::tuple<ImgClass::Lab>
Segmentation<ImgClass::Lab>::MeanShift(const int x, const int y, std::vector<VECTOR_2D<int> >& pel_list, int Iter_Max)
{
const double radius_spatial_squared = SQUARE(_kernel_spatial);
const double radius_intensity_squared = SQUARE(100.0 * _kernel_intensity);
const double displacement_min = SQUARE(0.001);
ImgClass::Segmentation::tuple<ImgClass::Lab> tuple;
// Initialize
tuple.spatial = VECTOR_2D<double>(static_cast<double>(x), static_cast<double>(y));
tuple.color = _image.get(x, y);
// Iterate until it converge
for (int i = 0; i < Iter_Max; i++) {
double N = 0.0;
ImgClass::Lab sum_diff(0.0, 0.0, 0.0);
VECTOR_2D<double> sum_d(0.0, 0.0);
for (size_t n = 0; n < pel_list.size(); n++) {
VECTOR_2D<int> r(
static_cast<int>(round(tuple.spatial.x) + pel_list[n].x),
static_cast<int>(round(tuple.spatial.y) + pel_list[n].y));
if (0 <= r.x && r.x < _width && 0 <= r.y && r.y < _height) {
ImgClass::Lab diff(_image.get(r.x, r.y) - tuple.color);
//diff.L /= 2.0; // Difference of Lighting is not so important in segmentation
VECTOR_2D<double> d(r.x - tuple.spatial.x, r.y - tuple.spatial.y);
double ratio_intensity = norm_squared(diff) / radius_intensity_squared;
double ratio_spatial = norm_squared(d) / radius_spatial_squared;
if (ratio_intensity <= 1.0 && ratio_spatial <= 1.0) {
double coeff = 1.0 - (ratio_intensity * ratio_spatial);
N += coeff;
sum_diff += diff * coeff;
sum_d += d * coeff;
}
}
}
tuple.color += sum_diff / N;
VECTOR_2D<double> displacement(sum_d.x / N, sum_d.y / N);
tuple.spatial += displacement;
if (norm_squared(sum_diff / N) * norm_squared(displacement) < displacement_min) {
break;
}
}
return tuple;
}
<commit_msg>Bug Fix<commit_after>#include "Segmentation.h"
#include "Lab.h"
#include "RGB.h"
template <>
double
Segmentation<ImgClass::RGB>::distance(const ImgClass::RGB& lvalue, const ImgClass::RGB& rvalue)
{
return sqrt(
SQUARE(lvalue.R - rvalue.R)
+ SQUARE(lvalue.G - rvalue.G)
+ SQUARE(lvalue.B - rvalue.B));
}
template <>
double
Segmentation<ImgClass::RGB>::normalized_distance(const ImgClass::RGB& lvalue, const ImgClass::RGB& rvalue)
{
return sqrt(
SQUARE(lvalue.R - rvalue.R)
+ SQUARE(lvalue.G - rvalue.G)
+ SQUARE(lvalue.B - rvalue.B));
}
template <>
double
Segmentation<ImgClass::Lab>::distance(const ImgClass::Lab& lvalue, const ImgClass::Lab& rvalue)
{
return sqrt(
SQUARE(lvalue.L - rvalue.L)
+ SQUARE(lvalue.a - rvalue.a)
+ SQUARE(lvalue.b - rvalue.b));
}
template <>
double
Segmentation<ImgClass::Lab>::normalized_distance(const ImgClass::Lab& lvalue, const ImgClass::Lab& rvalue)
{
return sqrt(
SQUARE(lvalue.L - rvalue.L)
+ SQUARE(lvalue.a - rvalue.a)
+ SQUARE(lvalue.b - rvalue.b)) / 100.0;
}
/*
* std::vector<double> kernel has kernel radius for each dimensions.
* The values it needs are below:
* _kernel_spatial : the spatial radius of mean shift kernel
* _kernel_intensity : the norm threshold of mean shift kernel in L*a*b* space
*/
template <> // Specialized for ImgClass::RGB<double>
const ImgClass::Segmentation::tuple<ImgClass::RGB>
Segmentation<ImgClass::RGB>::MeanShift(const int x, const int y, std::vector<VECTOR_2D<int> >& pel_list, int Iter_Max)
{
const double radius_spatial_squared = SQUARE(_kernel_spatial);
const double radius_intensity_squared = SQUARE(_kernel_intensity);
const double displacement_min = SQUARE(0.01);
ImgClass::Segmentation::tuple<ImgClass::RGB> tuple;
// Initialize
tuple.spatial = VECTOR_2D<double>(static_cast<double>(x), static_cast<double>(y));
tuple.color = _image.get(x, y);
// Iterate until it converge
for (int i = 0; i < Iter_Max; i++) {
double N = 0.0;
ImgClass::RGB sum_diff(0.0, 0.0, 0.0);
VECTOR_2D<double> sum_d(0.0, 0.0);
for (size_t n = 0; n < pel_list.size(); n++) {
VECTOR_2D<int> r(
static_cast<int>(round(tuple.spatial.x) + pel_list[n].x),
static_cast<int>(round(tuple.spatial.y) + pel_list[n].y));
if (0 <= r.x && r.x < _width && 0 <= r.y && r.y < _height) {
ImgClass::RGB diff(_image.get(r.x, r.y) - tuple.color);
VECTOR_2D<double> d(r.x - tuple.spatial.x, r.y - tuple.spatial.y);
double ratio_intensity = norm_squared(diff) / radius_intensity_squared;
double ratio_spatial = norm_squared(d) / radius_spatial_squared;
if (ratio_intensity <= 1.0 && ratio_spatial <= 1.0) {
double coeff = 1.0 - (ratio_intensity * ratio_spatial);
N += coeff;
sum_diff += diff * coeff;
sum_d += d * coeff;
}
}
}
tuple.color += sum_diff / N;
VECTOR_2D<double> displacement(sum_d.x / N, sum_d.y / N);
tuple.spatial += displacement;
if (norm_squared(sum_diff /N) * norm_squared(displacement) < displacement_min) {
break;
}
}
return tuple;
}
/*
* std::vector<double> kernel has kernel radius for each dimensions.
* The values it needs are below:
* _kernel_spatial : the spatial radius of mean shift kernel
* _kernel_intensity : the norm threshold of mean shift kernel in L*a*b* space
*/
template <> // Specialized for ImgClass::Lab
const ImgClass::Segmentation::tuple<ImgClass::Lab>
Segmentation<ImgClass::Lab>::MeanShift(const int x, const int y, std::vector<VECTOR_2D<int> >& pel_list, int Iter_Max)
{
const double radius_spatial_squared = SQUARE(_kernel_spatial);
const double radius_intensity_squared = SQUARE(100.0 * _kernel_intensity);
const double displacement_min = SQUARE(0.001);
ImgClass::Segmentation::tuple<ImgClass::Lab> tuple;
// Initialize
tuple.spatial = VECTOR_2D<double>(static_cast<double>(x), static_cast<double>(y));
tuple.color = _image.get(x, y);
// Iterate until it converge
for (int i = 0; i < Iter_Max; i++) {
double N = 0.0;
ImgClass::Lab sum_diff(0.0, 0.0, 0.0);
VECTOR_2D<double> sum_d(0.0, 0.0);
for (size_t n = 0; n < pel_list.size(); n++) {
VECTOR_2D<int> r(
static_cast<int>(round(tuple.spatial.x) + pel_list[n].x),
static_cast<int>(round(tuple.spatial.y) + pel_list[n].y));
if (0 <= r.x && r.x < _width && 0 <= r.y && r.y < _height) {
ImgClass::Lab diff(_image.get(r.x, r.y) - tuple.color);
diff.L *= 0.8; // Difference of Lighting is not so important in segmentation
VECTOR_2D<double> d(r.x - tuple.spatial.x, r.y - tuple.spatial.y);
double ratio_intensity = norm_squared(diff) / radius_intensity_squared;
double ratio_spatial = norm_squared(d) / radius_spatial_squared;
if (ratio_intensity <= 1.0 && ratio_spatial <= 1.0) {
double coeff = 1.0 - (ratio_intensity * ratio_spatial);
N += coeff;
sum_diff += diff * coeff;
sum_d += d * coeff;
}
}
}
tuple.color += sum_diff / N;
VECTOR_2D<double> displacement(sum_d.x / N, sum_d.y / N);
tuple.spatial += displacement;
if (norm_squared(sum_diff / N) * norm_squared(displacement) < displacement_min) {
break;
}
}
return tuple;
}
<|endoftext|>
|
<commit_before>
#include <cv.h>
#include "opencv2/opencv.hpp"
#include <SongLoader.h>
#include <SongPlayer.h>
//for the rasperry pi
#ifndef INT64_C
#define INT64_C(c) (c ## LL)
#define UINT64_C(c) (c ## ULL)
#endif
extern "C" {
#include <SDL.h>
#include <SDL_thread.h>
#include <SDL_ttf.h>
}
#include <iostream>
#include <stdio.h>
#include <unistd.h>
#ifdef __amd64__
#ifndef RUNNINGONINTEL
#define RUNNINGONINTEL
#endif
#else
#ifndef RUNNINGONPI
#define RUNNINGONPI
#endif
#include <wiringPi.h>
#endif
using namespace cv;
#define SCREEN_HEIGHT 768
#define SCREEN_WIDTH 1232
int cameraWorker(void* data);
void processEvents();
void signalToQuit();
void close();
//attempting double buffer
IplImage threadImage1;
IplImage threadImage2;
IplImage threadImage3;
bool updatedImage = false;
int bufferNumber = 1;
VideoCapture cap(0);
Mat frame;
SDL_Renderer* renderer = NULL;
SDL_Window* window = NULL;
SDL_Rect videoRect;
int cameraHeight;
int cameraWidth;
int noSongs;
SDL_Thread* SDLCameraThread;
SDL_Thread* SDLMusicThread;
int quit;
/***********************************************************************
/* SDL functions
/***********************************************************************/
// Initializes SDL window / renderer for use
bool init_SDL()
{
bool success = true;
if (SDL_Init(SDL_Init(SDL_INIT_VIDEO | SDL_INIT_AUDIO | SDL_INIT_TIMER)) < 0)
{
printf("SDL could not initialize! SDL Error: %s\n", SDL_GetError());
success = false;
}
else
{
window = SDL_CreateWindow("Video Application", SDL_WINDOWPOS_UNDEFINED, SDL_WINDOWPOS_UNDEFINED, SCREEN_WIDTH, SCREEN_HEIGHT, SDL_WINDOW_SHOWN);
if (window == NULL)
{
printf("Window could not be created! SDL Error: %s\n", SDL_GetError());
success = false;
}
else
{
renderer = SDL_CreateRenderer(window, -1, SDL_RENDERER_ACCELERATED | SDL_RENDERER_PRESENTVSYNC);
if (renderer == NULL)
{
printf("Renderer could not be created. SDL_Error: %s \n", SDL_GetError());
success = false;
}
else
{
SDL_SetRenderDrawColor(renderer, 0xFF, 0xFF, 0xFF, 0xFF);
}
}
}
return success;
}
bool init_CameraSettings()
{
int w, h;
bool success = true;
SDL_GetWindowSize(window, &w, &h);
videoRect.x = 0;
videoRect.y = 0;
videoRect.w = w;
videoRect.h = h-50; //change 50 to whatever height we want for the PI cam
cameraWidth = cap.get(CV_CAP_PROP_FRAME_WIDTH);
cameraHeight = cap.get(CV_CAP_PROP_FRAME_HEIGHT);
printf("Camera Width %d, Camera Height %d \n",cameraWidth,cameraHeight);
return success;
}
int cameraWorker(void* data)
{
while (!quit)
{
cap >> frame;
if(bufferNumber == 1)
{
threadImage2 = frame;
bufferNumber = 2;
}
else if (bufferNumber == 2)
{
threadImage3 = frame;
bufferNumber = 3;
}
else
{
threadImage1 = frame;
bufferNumber = 1;
}
updatedImage = true;
}
return 0;
}
// Shows an individual frame of the supplied video
int show_Camera()
{
IplImage* img = NULL;
if(updatedImage == true)
{
updatedImage = false;
if(bufferNumber == 1)
{
img = &threadImage1;
}
else if (bufferNumber == 2)
{
img = &threadImage2;
}
else
{
img = &threadImage3;
}
SDL_Surface* surface = SDL_CreateRGBSurfaceFrom((void*)img->imageData,
img->width,
img->height,
img->depth * img->nChannels,
img->widthStep,
0xff0000, 0x00ff00, 0x0000ff, 0
);
SDL_Texture* texture = SDL_CreateTextureFromSurface(renderer, surface);
SDL_FreeSurface(surface);
surface = NULL;
SDL_RendererFlip flip = SDL_FLIP_HORIZONTAL;
SDL_RenderCopyEx(renderer, texture, NULL, &videoRect ,0, NULL, flip);
SDL_DestroyTexture(texture);
return 1;
}
return 0;
}
void processEvents()
{
SDL_Event event;
while (SDL_PollEvent(&event))
{
switch(event.type)
{
case SDL_QUIT:
printf("SDL_QUIT was called\n");
signalToQuit();
close();
break;
case SDL_KEYDOWN:
switch(event.key.keysym.sym)
{
case SDLK_ESCAPE:
printf("Esc was Pressed!\n");
signalToQuit();
close();
break;
case SDLK_LEFT:
printf("Left arrow was Pressed!\n");
previousSong();
break;
case SDLK_RIGHT:
printf("Right arrow was Pressed!\n");
nextSong();
break;
case SDLK_UP:
changeVolume(0.1);
break;
case SDLK_DOWN:
changeVolume(-0.1);
break;
case SDLK_SPACE:
printf("Space was pressed!\n");
playPause();
}
}
}
}
/* Signals all the threads to quit and then waits for the threads */
void signalToQuit()
{
quit = true;
songQuit();
}
/* Cleans up and should free everything used in the program*/
void close()
{
closeSongPlayer();
SDL_DestroyRenderer(renderer);
SDL_DestroyWindow(window);
window = NULL;
renderer = NULL;
SDL_Quit();
exit(0);
}
int main(int argc, char* argv[])
{
if (!init_SDL())
{
fprintf(stderr, "Could not initialize SDL!\n");
return -1;
}
if (!cap.isOpened())
{
fprintf(stderr, "Failed to load file!\n");
return -1;
}
if (!init_CameraSettings())
{
fprintf(stderr, "Failed to load settings!\n");
return -1;
}
initSongPlayer();
noSongs = loadSong((char *)currentSong().c_str());
SDLCameraThread = SDL_CreateThread(cameraWorker, "Backup Camera Thread", NULL);
if (!noSongs)
SDLMusicThread = SDL_CreateThread(songThread, "Music Playing Thread", NULL);
int screenUpdate = 0;
while (!quit)
{
screenUpdate = show_Camera();
processEvents();
if (screenUpdate == 1)
{
SDL_SetRenderDrawColor(renderer, 0, 0, 0, 0);
SDL_RenderPresent(renderer);
SDL_RenderClear(renderer);
}
}
SDL_WaitThread(SDLCameraThread, NULL);
if (!noSongs)
SDL_WaitThread(SDLMusicThread, NULL);
return 0;
}
<commit_msg>Made SDL launch full screen<commit_after>
#include <cv.h>
#include "opencv2/opencv.hpp"
#include <SongLoader.h>
#include <SongPlayer.h>
//for the rasperry pi
#ifndef INT64_C
#define INT64_C(c) (c ## LL)
#define UINT64_C(c) (c ## ULL)
#endif
extern "C" {
#include <SDL.h>
#include <SDL_thread.h>
#include <SDL_ttf.h>
}
#include <iostream>
#include <stdio.h>
#include <unistd.h>
#ifdef __amd64__
#ifndef RUNNINGONINTEL
#define RUNNINGONINTEL
#endif
#else
#ifndef RUNNINGONPI
#define RUNNINGONPI
#endif
#include <wiringPi.h>
#endif
using namespace cv;
#define SCREEN_HEIGHT 768
#define SCREEN_WIDTH 1232
int cameraWorker(void* data);
void processEvents();
void signalToQuit();
void close();
//attempting double buffer
IplImage threadImage1;
IplImage threadImage2;
IplImage threadImage3;
bool updatedImage = false;
int bufferNumber = 1;
VideoCapture cap(0);
Mat frame;
SDL_Renderer* renderer = NULL;
SDL_Window* window = NULL;
SDL_Rect videoRect;
int cameraHeight;
int cameraWidth;
int noSongs;
SDL_Thread* SDLCameraThread;
SDL_Thread* SDLMusicThread;
int quit;
/***********************************************************************
/* SDL functions
/***********************************************************************/
// Initializes SDL window / renderer for use
bool init_SDL()
{
bool success = true;
if (SDL_Init(SDL_Init(SDL_INIT_VIDEO | SDL_INIT_AUDIO | SDL_INIT_TIMER)) < 0)
{
printf("SDL could not initialize! SDL Error: %s\n", SDL_GetError());
success = false;
}
else
{
window = SDL_CreateWindow("Video Application", SDL_WINDOWPOS_UNDEFINED, SDL_WINDOWPOS_UNDEFINED, SCREEN_WIDTH, SCREEN_HEIGHT, SDL_WINDOW_FULLSCREEN);
if (window == NULL)
{
printf("Window could not be created! SDL Error: %s\n", SDL_GetError());
success = false;
}
else
{
renderer = SDL_CreateRenderer(window, -1, SDL_RENDERER_ACCELERATED | SDL_RENDERER_PRESENTVSYNC);
if (renderer == NULL)
{
printf("Renderer could not be created. SDL_Error: %s \n", SDL_GetError());
success = false;
}
else
{
SDL_SetRenderDrawColor(renderer, 0xFF, 0xFF, 0xFF, 0xFF);
}
}
}
return success;
}
bool init_CameraSettings()
{
int w, h;
bool success = true;
SDL_GetWindowSize(window, &w, &h);
videoRect.x = 0;
videoRect.y = 0;
videoRect.w = w;
videoRect.h = h-50; //change 50 to whatever height we want for the PI cam
cameraWidth = cap.get(CV_CAP_PROP_FRAME_WIDTH);
cameraHeight = cap.get(CV_CAP_PROP_FRAME_HEIGHT);
printf("Camera Width %d, Camera Height %d \n",cameraWidth,cameraHeight);
return success;
}
int cameraWorker(void* data)
{
while (!quit)
{
cap >> frame;
if(bufferNumber == 1)
{
threadImage2 = frame;
bufferNumber = 2;
}
else if (bufferNumber == 2)
{
threadImage3 = frame;
bufferNumber = 3;
}
else
{
threadImage1 = frame;
bufferNumber = 1;
}
updatedImage = true;
}
return 0;
}
// Shows an individual frame of the supplied video
int show_Camera()
{
IplImage* img = NULL;
if(updatedImage == true)
{
updatedImage = false;
if(bufferNumber == 1)
{
img = &threadImage1;
}
else if (bufferNumber == 2)
{
img = &threadImage2;
}
else
{
img = &threadImage3;
}
SDL_Surface* surface = SDL_CreateRGBSurfaceFrom((void*)img->imageData,
img->width,
img->height,
img->depth * img->nChannels,
img->widthStep,
0xff0000, 0x00ff00, 0x0000ff, 0
);
SDL_Texture* texture = SDL_CreateTextureFromSurface(renderer, surface);
SDL_FreeSurface(surface);
surface = NULL;
SDL_RendererFlip flip = SDL_FLIP_HORIZONTAL;
SDL_RenderCopyEx(renderer, texture, NULL, &videoRect ,0, NULL, flip);
SDL_DestroyTexture(texture);
return 1;
}
return 0;
}
void processEvents()
{
SDL_Event event;
while (SDL_PollEvent(&event))
{
switch(event.type)
{
case SDL_QUIT:
printf("SDL_QUIT was called\n");
signalToQuit();
close();
break;
case SDL_KEYDOWN:
switch(event.key.keysym.sym)
{
case SDLK_ESCAPE:
printf("Esc was Pressed!\n");
signalToQuit();
close();
break;
case SDLK_LEFT:
printf("Left arrow was Pressed!\n");
previousSong();
break;
case SDLK_RIGHT:
printf("Right arrow was Pressed!\n");
nextSong();
break;
case SDLK_UP:
changeVolume(0.1);
break;
case SDLK_DOWN:
changeVolume(-0.1);
break;
case SDLK_SPACE:
printf("Space was pressed!\n");
playPause();
}
}
}
}
/* Signals all the threads to quit and then waits for the threads */
void signalToQuit()
{
quit = true;
songQuit();
}
/* Cleans up and should free everything used in the program*/
void close()
{
closeSongPlayer();
SDL_DestroyRenderer(renderer);
SDL_DestroyWindow(window);
window = NULL;
renderer = NULL;
SDL_Quit();
exit(0);
}
int main(int argc, char* argv[])
{
if (!init_SDL())
{
fprintf(stderr, "Could not initialize SDL!\n");
return -1;
}
if (!cap.isOpened())
{
fprintf(stderr, "Failed to load file!\n");
return -1;
}
if (!init_CameraSettings())
{
fprintf(stderr, "Failed to load settings!\n");
return -1;
}
initSongPlayer();
noSongs = loadSong((char *)currentSong().c_str());
SDLCameraThread = SDL_CreateThread(cameraWorker, "Backup Camera Thread", NULL);
if (!noSongs)
SDLMusicThread = SDL_CreateThread(songThread, "Music Playing Thread", NULL);
int screenUpdate = 0;
while (!quit)
{
screenUpdate = show_Camera();
processEvents();
if (screenUpdate == 1)
{
SDL_SetRenderDrawColor(renderer, 0, 0, 0, 0);
SDL_RenderPresent(renderer);
SDL_RenderClear(renderer);
}
}
SDL_WaitThread(SDLCameraThread, NULL);
if (!noSongs)
SDL_WaitThread(SDLMusicThread, NULL);
return 0;
}
<|endoftext|>
|
<commit_before>/*
* colourcombo.cpp - colour selection combo box
* Program: kalarm
* (C) 2001 - 2003 by David Jarvie software@astrojar.org.uk
*
* Some code taken from kdelibs/kdeui/kcolorcombo.cpp in the KDE libraries:
* Copyright (C) 1997 Martin Jones (mjones@kde.org)
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
*/
#include <qpainter.h>
#include <klocale.h>
#include <kcolordialog.h>
#include "kalarmapp.h"
#include "preferences.h"
#include "colourcombo.h"
ColourCombo::ColourCombo(QWidget* parent, const char* name, const QColor& defaultColour)
: QComboBox(parent, name),
mColourList(theApp()->preferences()->messageColours()),
mSelectedColour(defaultColour),
mCustomColour(255, 255, 255),
mReadOnly(false),
mDisabled(false)
{
addColours();
connect(this, SIGNAL(activated(int)), SLOT(slotActivated(int)));
connect(this, SIGNAL(highlighted(int)), SLOT(slotHighlighted(int)));
connect(theApp()->preferences(), SIGNAL(preferencesChanged()), SLOT(slotPreferencesChanged()));
}
void ColourCombo::setColour(const QColor& colour)
{
mSelectedColour = colour;
addColours();
}
/******************************************************************************
* Set a new colour selection.
*/
void ColourCombo::setColours(const ColourList& colours)
{
mColourList = colours;
if (mSelectedColour != mCustomColour
&& !mColourList.contains(mSelectedColour))
{
// The current colour has been deleted
mSelectedColour = mColourList.count() ? mColourList.first() : mCustomColour;
}
addColours();
}
/******************************************************************************
* Called when the user changes the preference settings.
* If the colour list has changed, update the colours displayed.
*/
void ColourCombo::slotPreferencesChanged()
{
const ColourList& prefColours = theApp()->preferences()->messageColours();
if (prefColours != mColourList)
setColours(prefColours); // update the display with the new colours
}
/******************************************************************************
* Enable or disable the control.
* If it is disabled, its colour is set to the dialog background colour.
*/
void ColourCombo::setEnabled(bool enable)
{
if (enable && mDisabled)
{
mDisabled = false;
setColour(mSelectedColour);
}
else if (!enable && !mDisabled)
{
mSelectedColour = color();
int end = count();
if (end > 1)
{
// Add a dialog background colour item
QPixmap pm = *pixmap(1);
pm.fill(paletteBackgroundColor());
insertItem(pm);
setCurrentItem(end);
}
mDisabled = true;
}
QComboBox::setEnabled(enable);
}
void ColourCombo::slotActivated(int index)
{
if (index)
mSelectedColour = mColourList[index - 1];
else
{
if (KColorDialog::getColor(mCustomColour, this) == QDialog::Accepted)
{
QRect rect;
drawCustomItem(rect, false);
}
mSelectedColour = mCustomColour;
}
emit activated(mSelectedColour);
}
void ColourCombo::slotHighlighted(int index)
{
mSelectedColour = index ? mColourList[index - 1] : mCustomColour;
emit highlighted(mSelectedColour);
}
/******************************************************************************
* Initialise the items in the combo box to one for each colour in the list.
*/
void ColourCombo::addColours()
{
clear();
for (ColourList::const_iterator it = mColourList.begin(); ; ++it)
{
if (it == mColourList.end())
{
mCustomColour = mSelectedColour;
break;
}
if (mSelectedColour == *it)
break;
}
QRect rect;
drawCustomItem(rect, true);
QPainter painter;
QPixmap pixmap(rect.width(), rect.height());
int i = 1;
for (ColourList::const_iterator it = mColourList.begin(); it != mColourList.end(); ++i, ++it)
{
painter.begin(&pixmap);
QBrush brush(*it);
painter.fillRect(rect, brush);
painter.end();
insertItem(pixmap);
pixmap.detach();
if (*it == mSelectedColour.rgb())
setCurrentItem(i);
}
}
void ColourCombo::drawCustomItem(QRect& rect, bool insert)
{
QPen pen;
if (qGray(mCustomColour.rgb()) < 128)
pen.setColor(Qt::white);
else
pen.setColor(Qt::black);
QPainter painter;
QFontMetrics fm = QFontMetrics(painter.font());
rect.setRect(0, 0, width(), fm.height() + 4);
QPixmap pixmap(rect.width(), rect.height());
painter.begin(&pixmap);
QBrush brush(mCustomColour);
painter.fillRect(rect, brush);
painter.setPen(pen);
painter.drawText(2, fm.ascent() + 2, i18n("Custom..."));
painter.end();
if (insert)
insertItem(pixmap);
else
changeItem(pixmap, 0);
pixmap.detach();
}
void ColourCombo::setReadOnly(bool ro)
{
mReadOnly = ro;
}
void ColourCombo::resizeEvent(QResizeEvent* re)
{
QComboBox::resizeEvent(re);
addColours();
}
void ColourCombo::mousePressEvent(QMouseEvent* e)
{
if (mReadOnly)
{
// Swallow up the event if it's the left button
if (e->button() == LeftButton)
return;
}
QComboBox::mousePressEvent(e);
}
void ColourCombo::mouseReleaseEvent(QMouseEvent* e)
{
if (!mReadOnly)
QComboBox::mouseReleaseEvent(e);
}
void ColourCombo::mouseMoveEvent(QMouseEvent* e)
{
if (!mReadOnly)
QComboBox::mouseMoveEvent(e);
}
void ColourCombo::keyPressEvent(QKeyEvent* e)
{
if (!mReadOnly)
QComboBox::keyPressEvent(e);
}
void ColourCombo::keyReleaseEvent(QKeyEvent* e)
{
if (!mReadOnly)
QComboBox::keyReleaseEvent(e);
}
#include "colourcombo.moc"
<commit_msg>Tidy up access to preferences<commit_after>/*
* colourcombo.cpp - colour selection combo box
* Program: kalarm
* (C) 2001, 2002, 2003 by David Jarvie <software@astrojar.org.uk>
*
* Some code taken from kdelibs/kdeui/kcolorcombo.cpp in the KDE libraries:
* Copyright (C) 1997 Martin Jones (mjones@kde.org)
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
*/
#include <qpainter.h>
#include <klocale.h>
#include <kcolordialog.h>
#include "kalarmapp.h"
#include "preferences.h"
#include "colourcombo.moc"
ColourCombo::ColourCombo(QWidget* parent, const char* name, const QColor& defaultColour)
: QComboBox(parent, name),
mColourList(Preferences::instance()->messageColours()),
mSelectedColour(defaultColour),
mCustomColour(255, 255, 255),
mReadOnly(false),
mDisabled(false)
{
addColours();
connect(this, SIGNAL(activated(int)), SLOT(slotActivated(int)));
connect(this, SIGNAL(highlighted(int)), SLOT(slotHighlighted(int)));
connect(Preferences::instance(), SIGNAL(preferencesChanged()), SLOT(slotPreferencesChanged()));
}
void ColourCombo::setColour(const QColor& colour)
{
mSelectedColour = colour;
addColours();
}
/******************************************************************************
* Set a new colour selection.
*/
void ColourCombo::setColours(const ColourList& colours)
{
mColourList = colours;
if (mSelectedColour != mCustomColour
&& !mColourList.contains(mSelectedColour))
{
// The current colour has been deleted
mSelectedColour = mColourList.count() ? mColourList.first() : mCustomColour;
}
addColours();
}
/******************************************************************************
* Called when the user changes the preference settings.
* If the colour list has changed, update the colours displayed.
*/
void ColourCombo::slotPreferencesChanged()
{
const ColourList& prefColours = Preferences::instance()->messageColours();
if (prefColours != mColourList)
setColours(prefColours); // update the display with the new colours
}
/******************************************************************************
* Enable or disable the control.
* If it is disabled, its colour is set to the dialog background colour.
*/
void ColourCombo::setEnabled(bool enable)
{
if (enable && mDisabled)
{
mDisabled = false;
setColour(mSelectedColour);
}
else if (!enable && !mDisabled)
{
mSelectedColour = color();
int end = count();
if (end > 1)
{
// Add a dialog background colour item
QPixmap pm = *pixmap(1);
pm.fill(paletteBackgroundColor());
insertItem(pm);
setCurrentItem(end);
}
mDisabled = true;
}
QComboBox::setEnabled(enable);
}
void ColourCombo::slotActivated(int index)
{
if (index)
mSelectedColour = mColourList[index - 1];
else
{
if (KColorDialog::getColor(mCustomColour, this) == QDialog::Accepted)
{
QRect rect;
drawCustomItem(rect, false);
}
mSelectedColour = mCustomColour;
}
emit activated(mSelectedColour);
}
void ColourCombo::slotHighlighted(int index)
{
mSelectedColour = index ? mColourList[index - 1] : mCustomColour;
emit highlighted(mSelectedColour);
}
/******************************************************************************
* Initialise the items in the combo box to one for each colour in the list.
*/
void ColourCombo::addColours()
{
clear();
for (ColourList::const_iterator it = mColourList.begin(); ; ++it)
{
if (it == mColourList.end())
{
mCustomColour = mSelectedColour;
break;
}
if (mSelectedColour == *it)
break;
}
QRect rect;
drawCustomItem(rect, true);
QPainter painter;
QPixmap pixmap(rect.width(), rect.height());
int i = 1;
for (ColourList::const_iterator it = mColourList.begin(); it != mColourList.end(); ++i, ++it)
{
painter.begin(&pixmap);
QBrush brush(*it);
painter.fillRect(rect, brush);
painter.end();
insertItem(pixmap);
pixmap.detach();
if (*it == mSelectedColour.rgb())
setCurrentItem(i);
}
}
void ColourCombo::drawCustomItem(QRect& rect, bool insert)
{
QPen pen;
if (qGray(mCustomColour.rgb()) < 128)
pen.setColor(Qt::white);
else
pen.setColor(Qt::black);
QPainter painter;
QFontMetrics fm = QFontMetrics(painter.font());
rect.setRect(0, 0, width(), fm.height() + 4);
QPixmap pixmap(rect.width(), rect.height());
painter.begin(&pixmap);
QBrush brush(mCustomColour);
painter.fillRect(rect, brush);
painter.setPen(pen);
painter.drawText(2, fm.ascent() + 2, i18n("Custom..."));
painter.end();
if (insert)
insertItem(pixmap);
else
changeItem(pixmap, 0);
pixmap.detach();
}
void ColourCombo::setReadOnly(bool ro)
{
mReadOnly = ro;
}
void ColourCombo::resizeEvent(QResizeEvent* re)
{
QComboBox::resizeEvent(re);
addColours();
}
void ColourCombo::mousePressEvent(QMouseEvent* e)
{
if (mReadOnly)
{
// Swallow up the event if it's the left button
if (e->button() == LeftButton)
return;
}
QComboBox::mousePressEvent(e);
}
void ColourCombo::mouseReleaseEvent(QMouseEvent* e)
{
if (!mReadOnly)
QComboBox::mouseReleaseEvent(e);
}
void ColourCombo::mouseMoveEvent(QMouseEvent* e)
{
if (!mReadOnly)
QComboBox::mouseMoveEvent(e);
}
void ColourCombo::keyPressEvent(QKeyEvent* e)
{
if (!mReadOnly)
QComboBox::keyPressEvent(e);
}
void ColourCombo::keyReleaseEvent(QKeyEvent* e)
{
if (!mReadOnly)
QComboBox::keyReleaseEvent(e);
}
<|endoftext|>
|
<commit_before>#include "arpTable.hpp"
using namespace std;
using namespace headers;
constexpr array<uint8_t, 6> ARPTable::nextHop::invalidMac;
void ARPTable::createCurrentTable(std::shared_ptr<RoutingTable> routingTable){
logDebug("ARPTable::createCurrentTable constructing tables for mapping");
// create a new table;
shared_ptr<table> newTable = make_shared<table>(std::vector<nextHop>(), directlyConnected);
auto next_hop_addresses = routingTable->getNextHopMapping();
newTable->nextHops.resize(next_hop_addresses->size());
for(auto nh : *next_hop_addresses){
if(nh.interface->netmapIndex == uint16_t_max){
logDebug("invalid nh interface");
abort();
}
newTable->nextHops[nh.index].netmapInterface = nh.interface->netmapIndex;
//newTable->nextHops[nh.index].mac = {{0}}; // just initialize
for(int i=0; i<6; i++){
newTable->nextHops[nh.index].mac[i] = 0;
}
if(mapping.count(nh.nh_ip)){
newTable->nextHops[nh.index].mac = mapping[nh.nh_ip].mac;
}
}
currentTable = newTable;
};
void ARPTable::prepareRequest(uint32_t ip, uint16_t iface, frame& frame){
logDebug("ARPTable::prepareRequest Preparing ARP request now");
ether* ether_hdr = reinterpret_cast<ether*>(frame.buf_ptr);
arp* arp_hdr = reinterpret_cast<arp*>(frame.buf_ptr + sizeof(ether));
shared_ptr<Interface> iface_ptr;
for(auto i : interfaces){
if(i->netmapIndex == iface){
iface_ptr = i;
break;
}
}
if(iface_ptr == nullptr){
abort();
}
ether_hdr->s_mac = iface_ptr->mac;
for(int i=0; i<6; i++){
ether_hdr->d_mac[i] = 0xff;
}
ether_hdr->ethertype = htons(0x0806);
arp_hdr->hw_type = htons(0x0001);
arp_hdr->proto_type = htons(0x0800);
arp_hdr->hw_len = 6;
arp_hdr->proto_len = 4;
arp_hdr->op = htons(arp::OP_REQUEST);
arp_hdr->s_hw_addr = iface_ptr->mac;
if(iface_ptr->IPs.empty()){
fatal("Cannot send ARP request without an IP address on interface");
}
arp_hdr->s_proto_addr = htonl(iface_ptr->IPs.front());
for(int i=0; i<6; i++){
arp_hdr->t_hw_addr[i] = 0;
}
arp_hdr->t_proto_addr = ip;
frame.len = sizeof(ether) + sizeof(arp);
}
void ARPTable::handleReply(frame& frame){
logDebug("ARPTable::handleReply Looking at ARP reply now");
// ARP is stateless -> doesn't mapper if we actually sent a request
uint32_t ip;
std::array<uint8_t, 6> mac;
ether* ether_hdr = reinterpret_cast<ether*>(frame.buf_ptr);
arp* arp_hdr = reinterpret_cast<arp*>(frame.buf_ptr + sizeof(ether));
if(ether_hdr->ethertype != htons(0x0806)){
logErr("Frame falsely sent to ARPTable::handleReply()");
return;
}
if(ntohs(arp_hdr->op) != arp::OP_REPLY){
// This is not a reply
logErr("Frame falsely sent to ARPTable::handleReply()");
return;
}
ip = ntohl(arp_hdr->s_proto_addr);
mac = arp_hdr->s_hw_addr;
nextHop nextHop;
nextHop.mac = mac;
nextHop.netmapInterface = frame.iface & frame::IFACE_ID;
auto next_hop_addresses = routingTable->getNextHopMapping();
// Check if this is a registered next hop
for(auto& nh : *next_hop_addresses){
if(nh.nh_ip == ip && nh.interface->netmapIndex == (frame.iface & frame::IFACE_ID)){
mapping.insert({ip, nextHop});
currentTable->nextHops[nh.index].mac = mac;
return;
}
}
// In case we reach this, the node is directly connected
directlyConnected.insert({ip, nextHop});
}
void ARPTable::handleRequest(frame& frame){
logDebug("ARPTable::handleRequest looking at request now");
ether* ether_hdr = reinterpret_cast<ether*>(frame.buf_ptr);
arp* arp_hdr = reinterpret_cast<arp*>(frame.buf_ptr + sizeof(ether));
if(ether_hdr->ethertype != htons(0x0806)){
logErr("Frame falsely sent to ARPTable::handleRequest()");
return;
}
if(ntohs(arp_hdr->op) != arp::OP_REQUEST){
logErr("Frame falsely sent to ARPTable::handleRequest()");
return;
}
shared_ptr<Interface> iface_ptr;
for(auto i : interfaces){
if(i->netmapIndex == (frame.iface & frame::IFACE_ID)){
iface_ptr = i;
break;
}
}
if(iface_ptr == nullptr){
abort();
}
// Check if we are asked
if(!count(iface_ptr->IPs.begin(), iface_ptr->IPs.end(),
ntohl(arp_hdr->t_proto_addr))){
logDebug("Got ARP request for some other node (IP: "
+ ip_to_str(ntohl(arp_hdr->t_proto_addr)) + "), discarding");
frame.iface = frame::IFACE_DISCARD;
return;
}
// Turn the request into a reply
arp_hdr->op = htons(arp::OP_REPLY);
arp_hdr->t_hw_addr = arp_hdr->s_hw_addr;
uint32_t t_ip = arp_hdr->t_proto_addr;
arp_hdr->t_proto_addr = arp_hdr->s_proto_addr;
arp_hdr->s_hw_addr = iface_ptr->mac;
arp_hdr->s_proto_addr = t_ip;
ether_hdr->s_mac = iface_ptr->mac;
for(int i=0; i<6; i++){
ether_hdr->d_mac[i] = 0xff;
}
}
void ARPTable::handleFrame(frame& frame){
ether* ether_hdr = reinterpret_cast<ether*>(frame.buf_ptr);
arp* arp_hdr = reinterpret_cast<arp*>(frame.buf_ptr + sizeof(ether));
if(ether_hdr->ethertype != htons(0x0806)){
logErr("Frame falsely sent to ARPTable::handleFrame()");
return;
}
if(ntohs(arp_hdr->op) == arp::OP_REQUEST){
handleRequest(frame);
} else if(ntohs(arp_hdr->op) == arp::OP_REPLY){
handleReply(frame);
} else {
logErr("Unknown ARP OP detected");
}
}
<commit_msg>save pointer to current routing table in ARPTable<commit_after>#include "arpTable.hpp"
using namespace std;
using namespace headers;
constexpr array<uint8_t, 6> ARPTable::nextHop::invalidMac;
void ARPTable::createCurrentTable(std::shared_ptr<RoutingTable> routingTable){
logDebug("ARPTable::createCurrentTable constructing tables for mapping");
this->routingTable = routingTable;
// create a new table;
shared_ptr<table> newTable = make_shared<table>(std::vector<nextHop>(), directlyConnected);
auto next_hop_addresses = routingTable->getNextHopMapping();
newTable->nextHops.resize(next_hop_addresses->size());
for(auto nh : *next_hop_addresses){
if(nh.interface->netmapIndex == uint16_t_max){
logDebug("invalid nh interface");
abort();
}
newTable->nextHops[nh.index].netmapInterface = nh.interface->netmapIndex;
//newTable->nextHops[nh.index].mac = {{0}}; // just initialize
for(int i=0; i<6; i++){
newTable->nextHops[nh.index].mac[i] = 0;
}
if(mapping.count(nh.nh_ip)){
newTable->nextHops[nh.index].mac = mapping[nh.nh_ip].mac;
}
}
currentTable = newTable;
};
void ARPTable::prepareRequest(uint32_t ip, uint16_t iface, frame& frame){
logDebug("ARPTable::prepareRequest Preparing ARP request now");
ether* ether_hdr = reinterpret_cast<ether*>(frame.buf_ptr);
arp* arp_hdr = reinterpret_cast<arp*>(frame.buf_ptr + sizeof(ether));
shared_ptr<Interface> iface_ptr;
for(auto i : interfaces){
if(i->netmapIndex == iface){
iface_ptr = i;
break;
}
}
if(iface_ptr == nullptr){
abort();
}
ether_hdr->s_mac = iface_ptr->mac;
for(int i=0; i<6; i++){
ether_hdr->d_mac[i] = 0xff;
}
ether_hdr->ethertype = htons(0x0806);
arp_hdr->hw_type = htons(0x0001);
arp_hdr->proto_type = htons(0x0800);
arp_hdr->hw_len = 6;
arp_hdr->proto_len = 4;
arp_hdr->op = htons(arp::OP_REQUEST);
arp_hdr->s_hw_addr = iface_ptr->mac;
if(iface_ptr->IPs.empty()){
fatal("Cannot send ARP request without an IP address on interface");
}
arp_hdr->s_proto_addr = htonl(iface_ptr->IPs.front());
for(int i=0; i<6; i++){
arp_hdr->t_hw_addr[i] = 0;
}
arp_hdr->t_proto_addr = ip;
frame.len = sizeof(ether) + sizeof(arp);
}
void ARPTable::handleReply(frame& frame){
logDebug("ARPTable::handleReply Looking at ARP reply now");
// ARP is stateless -> doesn't mapper if we actually sent a request
uint32_t ip;
std::array<uint8_t, 6> mac;
ether* ether_hdr = reinterpret_cast<ether*>(frame.buf_ptr);
arp* arp_hdr = reinterpret_cast<arp*>(frame.buf_ptr + sizeof(ether));
if(ether_hdr->ethertype != htons(0x0806)){
logErr("Frame falsely sent to ARPTable::handleReply()");
return;
}
if(ntohs(arp_hdr->op) != arp::OP_REPLY){
// This is not a reply
logErr("Frame falsely sent to ARPTable::handleReply()");
return;
}
ip = ntohl(arp_hdr->s_proto_addr);
mac = arp_hdr->s_hw_addr;
nextHop nextHop;
nextHop.mac = mac;
nextHop.netmapInterface = frame.iface & frame::IFACE_ID;
auto next_hop_addresses = routingTable->getNextHopMapping();
// Check if this is a registered next hop
for(auto& nh : *next_hop_addresses){
if(nh.nh_ip == ip && nh.interface->netmapIndex == (frame.iface & frame::IFACE_ID)){
mapping.insert({ip, nextHop});
currentTable->nextHops[nh.index].mac = mac;
return;
}
}
// In case we reach this, the node is directly connected
directlyConnected.insert({ip, nextHop});
}
void ARPTable::handleRequest(frame& frame){
logDebug("ARPTable::handleRequest looking at request now");
ether* ether_hdr = reinterpret_cast<ether*>(frame.buf_ptr);
arp* arp_hdr = reinterpret_cast<arp*>(frame.buf_ptr + sizeof(ether));
if(ether_hdr->ethertype != htons(0x0806)){
logErr("Frame falsely sent to ARPTable::handleRequest()");
return;
}
if(ntohs(arp_hdr->op) != arp::OP_REQUEST){
logErr("Frame falsely sent to ARPTable::handleRequest()");
return;
}
shared_ptr<Interface> iface_ptr;
for(auto i : interfaces){
if(i->netmapIndex == (frame.iface & frame::IFACE_ID)){
iface_ptr = i;
break;
}
}
if(iface_ptr == nullptr){
abort();
}
// Check if we are asked
if(!count(iface_ptr->IPs.begin(), iface_ptr->IPs.end(),
ntohl(arp_hdr->t_proto_addr))){
logDebug("Got ARP request for some other node (IP: "
+ ip_to_str(ntohl(arp_hdr->t_proto_addr)) + "), discarding");
frame.iface = frame::IFACE_DISCARD;
return;
}
// Turn the request into a reply
arp_hdr->op = htons(arp::OP_REPLY);
arp_hdr->t_hw_addr = arp_hdr->s_hw_addr;
uint32_t t_ip = arp_hdr->t_proto_addr;
arp_hdr->t_proto_addr = arp_hdr->s_proto_addr;
arp_hdr->s_hw_addr = iface_ptr->mac;
arp_hdr->s_proto_addr = t_ip;
ether_hdr->s_mac = iface_ptr->mac;
for(int i=0; i<6; i++){
ether_hdr->d_mac[i] = 0xff;
}
}
void ARPTable::handleFrame(frame& frame){
ether* ether_hdr = reinterpret_cast<ether*>(frame.buf_ptr);
arp* arp_hdr = reinterpret_cast<arp*>(frame.buf_ptr + sizeof(ether));
if(ether_hdr->ethertype != htons(0x0806)){
logErr("Frame falsely sent to ARPTable::handleFrame()");
return;
}
if(ntohs(arp_hdr->op) == arp::OP_REQUEST){
handleRequest(frame);
} else if(ntohs(arp_hdr->op) == arp::OP_REPLY){
handleReply(frame);
} else {
logErr("Unknown ARP OP detected");
}
}
<|endoftext|>
|
<commit_before>#include "stdafx.h"
#include "plugin.h"
#include "EditorTab.h"
#include "rapidjson/document.h"
#include<vector>
#define IDS_MENU_TEXT 1
#define IDS_STATUSMESSAGE 2
#define IDI_ICON 101
std::vector<HWND> windows_;
EditorStatus status_;
bool restoring_;
void StoreEditorStatus()
{
if (restoring_)
{
return;
}
EditorStatus status;
for (int i = 0; i < windows_.size(); i++)
{
HWND hwnd = windows_[i];
LRESULT count = Editor_Info(hwnd, MI_GET_DOC_COUNT, 0);
for (int i = 0; i < count; i++)
{
wchar_t fileNameRaw[2048];
LRESULT result = Editor_DocInfo(hwnd, i, MI_GET_FILE_NAME, (LPARAM)fileNameRaw);
auto docHandle = Editor_Info(hwnd, MI_INDEX_TO_DOC, i);
std::wstring fileName(fileNameRaw);
std::wstring& id = std::to_wstring(docHandle);
status.AddTab(EditorTab(fileName, id));
}
}
std::locale::global(std::locale("japanese"));
auto json = EditorStatus::SerializeToJson(status);
{
std::wofstream ofs(L"C:\\temp\\test.json", std::ios::out);
ofs << json;
}
}
int restoreCounter_ = 0;
void RestoreEditorStatus()
{
restoring_ = true;
restoreCounter_ = 0;
std::locale::global(std::locale("japanese"));
std::wstring json(L"");
{
std::wifstream ifs(L"C:\\temp\\test.json", std::ios::in);
json.append(std::istreambuf_iterator<wchar_t>(ifs), std::istreambuf_iterator<wchar_t>());
}
auto status = EditorStatus::DeserializeFromJson(json);
for (auto it = status.Tabs().begin(); it != status.Tabs().end(); it++)
{
auto& filePath = it->GetFilePath();
if (PathFileExists(filePath.c_str()))
{
wchar_t currentFileName[1024];
auto result = Editor_Info(windows_[0], MI_GET_FILE_NAME, (LPARAM)currentFileName);
if (lstrlenW(currentFileName) != 0 || Editor_GetModified(windows_[0]))
{
Editor_New(windows_[0]);
}
Editor_LoadFile(windows_[0], filePath.c_str());
}
}
restoring_ = false;
StoreEditorStatus();
}
// -----------------------------------------------------------------------------
// OnCommand
// プラグインを実行した時に呼び出されます
// パラメータ
// hwnd: ウィンドウのハンドル
EXTERN_C void WINAPI OnCommand(HWND hwnd)
{
//Editor_DocInfo(hwnd, 0, MI_CLOSE_DOC, 0);
return;
MessageBox(hwnd, L"Hello World!", L"基本的なサンプル", MB_OK);
RestoreEditorStatus();
std::locale::global(std::locale("japanese"));
//Editor_DocSaveFile(hwnd, 0, L"C:\\temp\\a.txt");
std::wofstream ofs(L"C:\\work\\mery-plugin-sdk\\SDK\\C\\Basic\\storedContent\\aaaa.txt");
LRESULT count = Editor_Info(hwnd, MI_GET_DOC_COUNT, 0);
std::wstring fileNameSum(L"");
for (int i = 0; i < count; i++)
{
wchar_t fileName[2048];
LRESULT result = Editor_DocInfo(hwnd, i, MI_GET_FILE_NAME, (LPARAM)fileName);
std::wstring fileName2(fileName);
fileNameSum += fileName2;
fileNameSum += L"\r\n";
UINT_PTR lineCount = Editor_GetDocLines(hwnd, i, POS_LOGICAL);
for (uint32_t lineIndex = 0; lineIndex < lineCount; lineIndex++)
{
GET_LINE_INFO lineInfo;
lineInfo.cch = 0;
lineInfo.yLine = lineIndex;
lineInfo.flags = FLAG_LOGICAL;
UINT_PTR size = Editor_GetLine(hwnd, &lineInfo, nullptr);
wchar_t* szLine = new wchar_t[size];
lineInfo.cch = size;
Editor_GetLine(hwnd, &lineInfo, szLine);
ofs << szLine << std::endl;
delete szLine;
}
}
ofs.close();
MessageBox(hwnd, fileNameSum.c_str(), L"Hello World!", MB_OK);
}
// -----------------------------------------------------------------------------
// QueryStatus
// プラグインが実行可能か、またはチェックされた状態かを調べます
// パラメータ
// hwnd: ウィンドウのハンドル
// pbChecked: チェックの状態
// 戻り値
// 実行可能であればTrueを返します
EXTERN_C BOOL WINAPI QueryStatus(HWND hwnd, LPBOOL pbChecked)
{
return true;
}
// -----------------------------------------------------------------------------
// GetMenuTextID
// メニューに表示するテキストのリソース識別子を取得します
// 戻り値
// リソース識別子
EXTERN_C UINT WINAPI GetMenuTextID()
{
return IDS_MENU_TEXT;
}
// -----------------------------------------------------------------------------
// GetStatusMessageID
// ツールチップに表示するテキストのリソース識別子を取得します
// 戻り値
// リソース識別子
EXTERN_C UINT WINAPI GetStatusMessageID()
{
return IDS_STATUSMESSAGE;
}
// -----------------------------------------------------------------------------
// GetIconID
// ツールバーに表示するアイコンのリソース識別子を取得します
// 戻り値
// リソース識別子
EXTERN_C UINT WINAPI GetIconID()
{
return IDI_ICON;
}
// -----------------------------------------------------------------------------
// OnEvents
// イベントが発生した時に呼び出されます
// パラメータ
// hwnd: ウィンドウのハンドル
// nEvent: イベントの種類
// lParam: メッセージ特有の追加情報
// 備考
// EVENT_CREATE: エディタを起動した時
// EVENT_CLOSE: エディタを終了した時
// EVENT_CREATE_FRAME: フレームを作成された時
// EVENT_CLOSE_FRAME: フレームが破棄された時
// EVENT_SET_FOCUS: フォーカスを取得した時
// EVENT_KILL_FOCUS: フォーカスを失った時
// EVENT_FILE_OPENED: ファイルを開いた時
// EVENT_FILE_SAVED: ファイルを保存した時
// EVENT_MODIFIED: 更新の状態が変更された時
// EVENT_CARET_MOVED: カーソルが移動した時
// EVENT_SCROLL: スクロールされた時
// EVENT_SEL_CHANGED: 選択範囲が変更された時
// EVENT_CHANGED: テキストが変更された時
// EVENT_CHAR: 文字が入力された時
// EVENT_MODE_CHANGED: 編集モードが変更された時
// EVENT_DOC_SEL_CHANGED: アクティブな文書が変更された時
// EVENT_DOC_CLOSE: 文書を閉じた時
// EVENT_TAB_MOVED: タブが移動された時
// EVENT_CUSTOM_BAR_CLOSING: カスタムバーを閉じようとした時
// EVENT_CUSTOM_BAR_CLOSED: カスタムバーを閉じた時
// EVENT_TOOL_BAR_CLOSED: ツールバーを閉じた時
// EVENT_TOOL_BAR_SHOW: ツールバーが表示された時
// EVENT_IDLE: アイドル時
EXTERN_C void WINAPI OnEvents(HWND hwnd, UINT nEvent, LPARAM lParam)
{
//std::ifstream ifs("C:\\work\\mery-plugin-sdk\\SDK\\C\\Basic\\sampleData\\data.json");
//std::istreambuf_iterator<char> it(ifs);
//std::istreambuf_iterator<char> last;
//std::string str(it, last);
//rapidjson::Document doc;
//doc.Parse(str.c_str());
if (nEvent == EVENT_CREATE_FRAME)
{
//Editor_LoadFile(hwnd, L"C:\\Users\\taka\\Downloads\\Mery\\Mery.txt");
windows_.push_back(hwnd);
RestoreEditorStatus();
}
if (nEvent == EVENT_DOC_SEL_CHANGED)
{
//状態の記憶
StoreEditorStatus();
}
if (nEvent == EVENT_CHANGED)
{
//時間経過でアクティブ文書のバックアップ
}
if (nEvent == EVENT_CREATE) { OutputDebugString(L"エディタを起動した時\n"); }
if (nEvent == EVENT_CLOSE) { OutputDebugString(L"エディタを終了した時\n"); }
if (nEvent == EVENT_CREATE_FRAME) { OutputDebugString(L"フレームを作成された時\n"); }
if (nEvent == EVENT_CLOSE_FRAME) { OutputDebugString(L"フレームが破棄された時\n"); }
if (nEvent == EVENT_SET_FOCUS) { OutputDebugString(L"フォーカスを取得した時\n"); }
if (nEvent == EVENT_KILL_FOCUS) { OutputDebugString(L"フォーカスを失った時\n"); }
if (nEvent == EVENT_FILE_OPENED) { OutputDebugString(L"ファイルを開いた時\n"); }
if (nEvent == EVENT_FILE_SAVED) { OutputDebugString(L"ファイルを保存した時\n"); }
if (nEvent == EVENT_MODIFIED) { OutputDebugString(L"更新の状態が変更された時\n"); }
if (nEvent == EVENT_CARET_MOVED) { OutputDebugString(L"カーソルが移動した時\n"); }
if (nEvent == EVENT_SCROLL) { OutputDebugString(L"スクロールされた時\n"); }
if (nEvent == EVENT_SEL_CHANGED) { OutputDebugString(L"選択範囲が変更された時\n"); }
if (nEvent == EVENT_CHANGED) { OutputDebugString(L"テキストが変更された時\n"); }
if (nEvent == EVENT_CHAR) { OutputDebugString(L"文字が入力された時\n"); }
if (nEvent == EVENT_MODE_CHANGED) { OutputDebugString(L"編集モードが変更された時\n"); }
if (nEvent == EVENT_DOC_SEL_CHANGED) { OutputDebugString(L"アクティブな文書が変更された時\n"); }
if (nEvent == EVENT_DOC_CLOSE) { OutputDebugString(L"文書を閉じた時\n"); }
if (nEvent == EVENT_TAB_MOVED) { OutputDebugString(L"タブが移動された時\n"); }
if (nEvent == EVENT_CUSTOM_BAR_CLOSING) { OutputDebugString(L"カスタムバーを閉じようとした時\n"); }
if (nEvent == EVENT_CUSTOM_BAR_CLOSED) { OutputDebugString(L"カスタムバーを閉じた時\n"); }
if (nEvent == EVENT_TOOL_BAR_CLOSED) { OutputDebugString(L"ツールバーを閉じた時\n"); }
if (nEvent == EVENT_TOOL_BAR_SHOW) { OutputDebugString(L"ツールバーが表示された時\n"); }
//if (nEvent == EVENT_IDLE) { OutputDebugString(L"アイドル時\n"); }
}
// -----------------------------------------------------------------------------
// PluginProc
// プラグインに送られるメッセージを処理します
// パラメータ
// hwnd: ウィンドウのハンドル
// nMsg: メッセージ
// wParam: メッセージ特有の追加情報
// lParam: メッセージ特有の追加情報
// 戻り値
// メッセージにより異なります
EXTERN_C LRESULT WINAPI PluginProc(HWND hwnd, UINT nMsg, WPARAM wParam, LPARAM lParam)
{
wchar_t szName[] = L"基本的なサンプル";
wchar_t szVersion[] = L"Version 2.0.0.0";
switch(nMsg)
{
case MP_GET_NAME:
if(lParam != 0)
lstrcpynW(LPWSTR(lParam), szName, wParam);
return wcslen(szName);
case MP_GET_VERSION:
if(lParam != 0)
lstrcpynW(LPWSTR(lParam), szVersion, wParam);
return wcslen(szVersion);
}
return 0;
}
<commit_msg>Change plugin data path to appData<commit_after>#include "stdafx.h"
#include "plugin.h"
#include "EditorTab.h"
#include "rapidjson/document.h"
#include<vector>
#define IDS_MENU_TEXT 1
#define IDS_STATUSMESSAGE 2
#define IDI_ICON 101
std::vector<HWND> windows_;
EditorStatus status_;
bool restoring_;
void StoreEditorStatus()
{
if (restoring_)
{
return;
}
EditorStatus status;
for (int i = 0; i < windows_.size(); i++)
{
HWND hwnd = windows_[i];
LRESULT count = Editor_Info(hwnd, MI_GET_DOC_COUNT, 0);
for (int i = 0; i < count; i++)
{
wchar_t fileNameRaw[2048];
LRESULT result = Editor_DocInfo(hwnd, i, MI_GET_FILE_NAME, (LPARAM)fileNameRaw);
auto docHandle = Editor_Info(hwnd, MI_INDEX_TO_DOC, i);
std::wstring fileName(fileNameRaw);
std::wstring& id = std::to_wstring(docHandle);
status.AddTab(EditorTab(fileName, id));
}
}
wchar_t pluginDataDir[1024];
::PathCombine(pluginDataDir, _wgetenv(L"APPDATA"), L"Mery");
if (!PathIsDirectory(pluginDataDir))
{
CreateDirectory(pluginDataDir, NULL);
}
::PathCombine(pluginDataDir, pluginDataDir, L"plugins");
if (!PathIsDirectory(pluginDataDir))
{
CreateDirectory(pluginDataDir, NULL);
}
::PathCombine(pluginDataDir, pluginDataDir, L"ResumeMeryPlugin");
if (!PathIsDirectory(pluginDataDir))
{
CreateDirectory(pluginDataDir, NULL);
}
std::locale::global(std::locale("japanese"));
auto json = EditorStatus::SerializeToJson(status);
{
wchar_t statusFilePath[1024];
::PathCombine(statusFilePath, pluginDataDir, L"status.json");
std::wofstream ofs(statusFilePath, std::ios::out);
ofs << json;
}
}
int restoreCounter_ = 0;
void RestoreEditorStatus()
{
restoring_ = true;
restoreCounter_ = 0;
std::locale::global(std::locale("japanese"));
std::wstring json(L"");
{
wchar_t statusFilePath[1024];
::PathCombine(statusFilePath, _wgetenv(L"APPDATA"), L"Mery\\plugins\\ResumeMeryPlugin\\status.json");
std::wifstream ifs(statusFilePath, std::ios::in);
if (ifs.fail())
{
restoring_ = false;
return;
}
json.append(std::istreambuf_iterator<wchar_t>(ifs), std::istreambuf_iterator<wchar_t>());
}
auto status = EditorStatus::DeserializeFromJson(json);
for (auto it = status.Tabs().begin(); it != status.Tabs().end(); it++)
{
auto& filePath = it->GetFilePath();
if (PathFileExists(filePath.c_str()))
{
wchar_t currentFileName[1024];
auto result = Editor_Info(windows_[0], MI_GET_FILE_NAME, (LPARAM)currentFileName);
if (lstrlenW(currentFileName) != 0 || Editor_GetModified(windows_[0]))
{
Editor_New(windows_[0]);
}
Editor_LoadFile(windows_[0], filePath.c_str());
}
}
restoring_ = false;
StoreEditorStatus();
}
// -----------------------------------------------------------------------------
// OnCommand
// プラグインを実行した時に呼び出されます
// パラメータ
// hwnd: ウィンドウのハンドル
EXTERN_C void WINAPI OnCommand(HWND hwnd)
{
//Editor_DocInfo(hwnd, 0, MI_CLOSE_DOC, 0);
return;
//MessageBox(hwnd, L"Hello World!", L"基本的なサンプル", MB_OK);
//RestoreEditorStatus();
//std::locale::global(std::locale("japanese"));
//std::wofstream ofs(L"C:\\work\\mery-plugin-sdk\\SDK\\C\\Basic\\storedContent\\aaaa.txt");
//LRESULT count = Editor_Info(hwnd, MI_GET_DOC_COUNT, 0);
//std::wstring fileNameSum(L"");
//for (int i = 0; i < count; i++)
//{
// wchar_t fileName[2048];
// LRESULT result = Editor_DocInfo(hwnd, i, MI_GET_FILE_NAME, (LPARAM)fileName);
// std::wstring fileName2(fileName);
// fileNameSum += fileName2;
// fileNameSum += L"\r\n";
// UINT_PTR lineCount = Editor_GetDocLines(hwnd, i, POS_LOGICAL);
// for (uint32_t lineIndex = 0; lineIndex < lineCount; lineIndex++)
// {
// GET_LINE_INFO lineInfo;
// lineInfo.cch = 0;
// lineInfo.yLine = lineIndex;
// lineInfo.flags = FLAG_LOGICAL;
// UINT_PTR size = Editor_GetLine(hwnd, &lineInfo, nullptr);
// wchar_t* szLine = new wchar_t[size];
// lineInfo.cch = size;
// Editor_GetLine(hwnd, &lineInfo, szLine);
// ofs << szLine << std::endl;
// delete szLine;
// }
//}
//ofs.close();
//MessageBox(hwnd, fileNameSum.c_str(), L"Hello World!", MB_OK);
}
// -----------------------------------------------------------------------------
// QueryStatus
// プラグインが実行可能か、またはチェックされた状態かを調べます
// パラメータ
// hwnd: ウィンドウのハンドル
// pbChecked: チェックの状態
// 戻り値
// 実行可能であればTrueを返します
EXTERN_C BOOL WINAPI QueryStatus(HWND hwnd, LPBOOL pbChecked)
{
return true;
}
// -----------------------------------------------------------------------------
// GetMenuTextID
// メニューに表示するテキストのリソース識別子を取得します
// 戻り値
// リソース識別子
EXTERN_C UINT WINAPI GetMenuTextID()
{
return IDS_MENU_TEXT;
}
// -----------------------------------------------------------------------------
// GetStatusMessageID
// ツールチップに表示するテキストのリソース識別子を取得します
// 戻り値
// リソース識別子
EXTERN_C UINT WINAPI GetStatusMessageID()
{
return IDS_STATUSMESSAGE;
}
// -----------------------------------------------------------------------------
// GetIconID
// ツールバーに表示するアイコンのリソース識別子を取得します
// 戻り値
// リソース識別子
EXTERN_C UINT WINAPI GetIconID()
{
return IDI_ICON;
}
// -----------------------------------------------------------------------------
// OnEvents
// イベントが発生した時に呼び出されます
// パラメータ
// hwnd: ウィンドウのハンドル
// nEvent: イベントの種類
// lParam: メッセージ特有の追加情報
// 備考
// EVENT_CREATE: エディタを起動した時
// EVENT_CLOSE: エディタを終了した時
// EVENT_CREATE_FRAME: フレームを作成された時
// EVENT_CLOSE_FRAME: フレームが破棄された時
// EVENT_SET_FOCUS: フォーカスを取得した時
// EVENT_KILL_FOCUS: フォーカスを失った時
// EVENT_FILE_OPENED: ファイルを開いた時
// EVENT_FILE_SAVED: ファイルを保存した時
// EVENT_MODIFIED: 更新の状態が変更された時
// EVENT_CARET_MOVED: カーソルが移動した時
// EVENT_SCROLL: スクロールされた時
// EVENT_SEL_CHANGED: 選択範囲が変更された時
// EVENT_CHANGED: テキストが変更された時
// EVENT_CHAR: 文字が入力された時
// EVENT_MODE_CHANGED: 編集モードが変更された時
// EVENT_DOC_SEL_CHANGED: アクティブな文書が変更された時
// EVENT_DOC_CLOSE: 文書を閉じた時
// EVENT_TAB_MOVED: タブが移動された時
// EVENT_CUSTOM_BAR_CLOSING: カスタムバーを閉じようとした時
// EVENT_CUSTOM_BAR_CLOSED: カスタムバーを閉じた時
// EVENT_TOOL_BAR_CLOSED: ツールバーを閉じた時
// EVENT_TOOL_BAR_SHOW: ツールバーが表示された時
// EVENT_IDLE: アイドル時
EXTERN_C void WINAPI OnEvents(HWND hwnd, UINT nEvent, LPARAM lParam)
{
//std::ifstream ifs("C:\\work\\mery-plugin-sdk\\SDK\\C\\Basic\\sampleData\\data.json");
//std::istreambuf_iterator<char> it(ifs);
//std::istreambuf_iterator<char> last;
//std::string str(it, last);
//rapidjson::Document doc;
//doc.Parse(str.c_str());
if (nEvent == EVENT_CREATE_FRAME)
{
//Editor_LoadFile(hwnd, L"C:\\Users\\taka\\Downloads\\Mery\\Mery.txt");
windows_.push_back(hwnd);
RestoreEditorStatus();
}
if (nEvent == EVENT_DOC_SEL_CHANGED)
{
//状態の記憶
StoreEditorStatus();
}
if (nEvent == EVENT_CHANGED)
{
//時間経過でアクティブ文書のバックアップ
}
if (nEvent == EVENT_CREATE) { OutputDebugString(L"エディタを起動した時\n"); }
if (nEvent == EVENT_CLOSE) { OutputDebugString(L"エディタを終了した時\n"); }
if (nEvent == EVENT_CREATE_FRAME) { OutputDebugString(L"フレームを作成された時\n"); }
if (nEvent == EVENT_CLOSE_FRAME) { OutputDebugString(L"フレームが破棄された時\n"); }
if (nEvent == EVENT_SET_FOCUS) { OutputDebugString(L"フォーカスを取得した時\n"); }
if (nEvent == EVENT_KILL_FOCUS) { OutputDebugString(L"フォーカスを失った時\n"); }
if (nEvent == EVENT_FILE_OPENED) { OutputDebugString(L"ファイルを開いた時\n"); }
if (nEvent == EVENT_FILE_SAVED) { OutputDebugString(L"ファイルを保存した時\n"); }
if (nEvent == EVENT_MODIFIED) { OutputDebugString(L"更新の状態が変更された時\n"); }
if (nEvent == EVENT_CARET_MOVED) { OutputDebugString(L"カーソルが移動した時\n"); }
if (nEvent == EVENT_SCROLL) { OutputDebugString(L"スクロールされた時\n"); }
if (nEvent == EVENT_SEL_CHANGED) { OutputDebugString(L"選択範囲が変更された時\n"); }
if (nEvent == EVENT_CHANGED) { OutputDebugString(L"テキストが変更された時\n"); }
if (nEvent == EVENT_CHAR) { OutputDebugString(L"文字が入力された時\n"); }
if (nEvent == EVENT_MODE_CHANGED) { OutputDebugString(L"編集モードが変更された時\n"); }
if (nEvent == EVENT_DOC_SEL_CHANGED) { OutputDebugString(L"アクティブな文書が変更された時\n"); }
if (nEvent == EVENT_DOC_CLOSE) { OutputDebugString(L"文書を閉じた時\n"); }
if (nEvent == EVENT_TAB_MOVED) { OutputDebugString(L"タブが移動された時\n"); }
if (nEvent == EVENT_CUSTOM_BAR_CLOSING) { OutputDebugString(L"カスタムバーを閉じようとした時\n"); }
if (nEvent == EVENT_CUSTOM_BAR_CLOSED) { OutputDebugString(L"カスタムバーを閉じた時\n"); }
if (nEvent == EVENT_TOOL_BAR_CLOSED) { OutputDebugString(L"ツールバーを閉じた時\n"); }
if (nEvent == EVENT_TOOL_BAR_SHOW) { OutputDebugString(L"ツールバーが表示された時\n"); }
//if (nEvent == EVENT_IDLE) { OutputDebugString(L"アイドル時\n"); }
}
// -----------------------------------------------------------------------------
// PluginProc
// プラグインに送られるメッセージを処理します
// パラメータ
// hwnd: ウィンドウのハンドル
// nMsg: メッセージ
// wParam: メッセージ特有の追加情報
// lParam: メッセージ特有の追加情報
// 戻り値
// メッセージにより異なります
EXTERN_C LRESULT WINAPI PluginProc(HWND hwnd, UINT nMsg, WPARAM wParam, LPARAM lParam)
{
wchar_t szName[] = L"基本的なサンプル";
wchar_t szVersion[] = L"Version 2.0.0.0";
switch(nMsg)
{
case MP_GET_NAME:
if(lParam != 0)
lstrcpynW(LPWSTR(lParam), szName, wParam);
return wcslen(szName);
case MP_GET_VERSION:
if(lParam != 0)
lstrcpynW(LPWSTR(lParam), szVersion, wParam);
return wcslen(szVersion);
}
return 0;
}
<|endoftext|>
|
<commit_before>/*
* Copyright (c) 2002-2005 The Regents of The University of Michigan
* 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 holders 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.
*
* Authors: Nathan Binkert
* Dave Greene
*/
#ifndef __BASE_MISC_HH__
#define __BASE_MISC_HH__
#include "base/compiler.hh"
#include "base/cprintf.hh"
#include "base/varargs.hh"
#if defined(__SUNPRO_CC)
#define __FUNCTION__ "how to fix me?"
#endif
// General exit message, these functions will never return and will
// either abort() if code is < 0 or exit with the code if >= 0
void __exit_message(const char *prefix, int code,
const char *func, const char *file, int line,
const char *format, CPRINTF_DECLARATION) M5_ATTR_NORETURN;
void __exit_message(const char *prefix, int code,
const char *func, const char *file, int line,
const std::string &format, CPRINTF_DECLARATION) M5_ATTR_NORETURN;
inline void
__exit_message(const char *prefix, int code,
const char *func, const char *file, int line,
const std::string& format, CPRINTF_DEFINITION)
{
__exit_message(prefix, code, func, file, line, format.c_str(),
VARARGS_ALLARGS);
}
M5_PRAGMA_NORETURN(__exit_message)
#define exit_message(prefix, code, ...) \
__exit_message(prefix, code, __FUNCTION__, __FILE__, __LINE__, \
__VA_ARGS__)
//
// This implements a cprintf based panic() function. panic() should
// be called when something happens that should never ever happen
// regardless of what the user does (i.e., an acutal m5 bug). panic()
// calls abort which can dump core or enter the debugger.
//
//
#define panic(...) exit_message("panic", -1, __VA_ARGS__)
//
// This implements a cprintf based fatal() function. fatal() should
// be called when the simulation cannot continue due to some condition
// that is the user's fault (bad configuration, invalid arguments,
// etc.) and not a simulator bug. fatal() calls abort() like
// panic() does.
//
#define fatal(...) exit_message("fatal", -1, __VA_ARGS__)
void
__base_message(std::ostream &stream, const char *prefix, bool verbose,
const char *func, const char *file, int line,
const char *format, CPRINTF_DECLARATION);
inline void
__base_message(std::ostream &stream, const char *prefix, bool verbose,
const char *func, const char *file, int line,
const std::string &format, CPRINTF_DECLARATION)
{
__base_message(stream, prefix, verbose, func, file, line, format.c_str(),
VARARGS_ALLARGS);
}
#define base_message(stream, prefix, verbose, ...) \
__base_message(stream, prefix, verbose, __FUNCTION__, __FILE__, __LINE__, \
__VA_ARGS__)
// Only print the message the first time this expression is
// encountered. i.e. This doesn't check the string itself and
// prevent duplicate strings, this prevents the statement from
// happening more than once. So, even if the arguments change and that
// would have resulted in a different message thoes messages would be
// supressed.
#define base_message_once(...) do { \
static bool once = false; \
if (!once) { \
base_message(__VA_ARGS__); \
once = true; \
} \
} while (0)
#define cond_message(cond, ...) do { \
if (cond) \
base_message(__VA_ARGS__); \
} while (0)
#define cond_message_once(cond, ...) do { \
static bool once = false; \
if (!once && cond) { \
base_message(__VA_ARGS__); \
once = true; \
} \
} while (0)
extern bool want_warn, warn_verbose;
extern bool want_info, info_verbose;
extern bool want_hack, hack_verbose;
#define warn(...) \
cond_message(want_warn, std::cerr, "warn", warn_verbose, __VA_ARGS__)
#define inform(...) \
cond_message(want_info, std::cout, "info", info_verbose, __VA_ARGS__)
#define hack(...) \
cond_message(want_hack, std::cerr, "hack", hack_verbose, __VA_ARGS__)
#define warn_once(...) \
cond_message_once(want_warn, std::cerr, "warn", warn_verbose, __VA_ARGS__)
#define inform_once(...) \
cond_message_once(want_info, std::cout, "info", info_verbose, __VA_ARGS__)
#define hack_once(...) \
cond_message_once(want_hack, std::cerr, "hack", hack_verbose, __VA_ARGS__)
#endif // __BASE_MISC_HH__
<commit_msg>misc: Add panic_if / fatal_if / chatty_assert<commit_after>/*
* Copyright (c) 2014 ARM Limited
* All rights reserved
*
* The license below extends only to copyright in the software and shall
* not be construed as granting a license to any other intellectual
* property including but not limited to intellectual property relating
* to a hardware implementation of the functionality of the software
* licensed hereunder. You may use the software subject to the license
* terms below provided that you ensure that this notice is replicated
* unmodified and in its entirety in all distributions of the software,
* modified or unmodified, in source code or in binary form.
*
* Copyright (c) 2002-2005 The Regents of The University of Michigan
* 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 holders 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.
*
* Authors: Nathan Binkert
* Dave Greene
*/
#ifndef __BASE_MISC_HH__
#define __BASE_MISC_HH__
#include "base/compiler.hh"
#include "base/cprintf.hh"
#include "base/varargs.hh"
#if defined(__SUNPRO_CC)
#define __FUNCTION__ "how to fix me?"
#endif
// General exit message, these functions will never return and will
// either abort() if code is < 0 or exit with the code if >= 0
void __exit_message(const char *prefix, int code,
const char *func, const char *file, int line,
const char *format, CPRINTF_DECLARATION) M5_ATTR_NORETURN;
void __exit_message(const char *prefix, int code,
const char *func, const char *file, int line,
const std::string &format, CPRINTF_DECLARATION) M5_ATTR_NORETURN;
inline void
__exit_message(const char *prefix, int code,
const char *func, const char *file, int line,
const std::string& format, CPRINTF_DEFINITION)
{
__exit_message(prefix, code, func, file, line, format.c_str(),
VARARGS_ALLARGS);
}
M5_PRAGMA_NORETURN(__exit_message)
#define exit_message(prefix, code, ...) \
__exit_message(prefix, code, __FUNCTION__, __FILE__, __LINE__, \
__VA_ARGS__)
//
// This implements a cprintf based panic() function. panic() should
// be called when something happens that should never ever happen
// regardless of what the user does (i.e., an acutal m5 bug). panic()
// calls abort which can dump core or enter the debugger.
//
//
#define panic(...) exit_message("panic", -1, __VA_ARGS__)
//
// This implements a cprintf based fatal() function. fatal() should
// be called when the simulation cannot continue due to some condition
// that is the user's fault (bad configuration, invalid arguments,
// etc.) and not a simulator bug. fatal() calls abort() like
// panic() does.
//
#define fatal(...) exit_message("fatal", -1, __VA_ARGS__)
/**
* Conditional panic macro that checks the supplied condition and only panics
* if the condition is true and allows the programmer to specify diagnostic
* printout. Useful to replace if + panic, or if + print + assert, etc.
*
* @param cond Condition that is checked; if true -> panic
* @param ... Printf-based format string with arguments, extends printout.
*/
#define panic_if(cond, ...) \
do { \
if ((cond)) \
exit_message("panic condition "#cond" occurred", -1, __VA_ARGS__); \
} while (0)
/**
* Conditional fatal macro that checks the supplied condition and only causes a
* fatal error if the condition is true and allows the programmer to specify
* diagnostic printout. Useful to replace if + fatal, or if + print + assert,
* etc.
*
* @param cond Condition that is checked; if true -> fatal
* @param ... Printf-based format string with arguments, extends printout.
*/
#define fatal_if(cond, ...) \
do { \
if ((cond)) \
exit_message("fatal condition "#cond" occurred", 1, __VA_ARGS__); \
} while (0)
void
__base_message(std::ostream &stream, const char *prefix, bool verbose,
const char *func, const char *file, int line,
const char *format, CPRINTF_DECLARATION);
inline void
__base_message(std::ostream &stream, const char *prefix, bool verbose,
const char *func, const char *file, int line,
const std::string &format, CPRINTF_DECLARATION)
{
__base_message(stream, prefix, verbose, func, file, line, format.c_str(),
VARARGS_ALLARGS);
}
#define base_message(stream, prefix, verbose, ...) \
__base_message(stream, prefix, verbose, __FUNCTION__, __FILE__, __LINE__, \
__VA_ARGS__)
// Only print the message the first time this expression is
// encountered. i.e. This doesn't check the string itself and
// prevent duplicate strings, this prevents the statement from
// happening more than once. So, even if the arguments change and that
// would have resulted in a different message thoes messages would be
// supressed.
#define base_message_once(...) do { \
static bool once = false; \
if (!once) { \
base_message(__VA_ARGS__); \
once = true; \
} \
} while (0)
#define cond_message(cond, ...) do { \
if (cond) \
base_message(__VA_ARGS__); \
} while (0)
#define cond_message_once(cond, ...) do { \
static bool once = false; \
if (!once && cond) { \
base_message(__VA_ARGS__); \
once = true; \
} \
} while (0)
extern bool want_warn, warn_verbose;
extern bool want_info, info_verbose;
extern bool want_hack, hack_verbose;
#define warn(...) \
cond_message(want_warn, std::cerr, "warn", warn_verbose, __VA_ARGS__)
#define inform(...) \
cond_message(want_info, std::cout, "info", info_verbose, __VA_ARGS__)
#define hack(...) \
cond_message(want_hack, std::cerr, "hack", hack_verbose, __VA_ARGS__)
#define warn_once(...) \
cond_message_once(want_warn, std::cerr, "warn", warn_verbose, __VA_ARGS__)
#define inform_once(...) \
cond_message_once(want_info, std::cout, "info", info_verbose, __VA_ARGS__)
#define hack_once(...) \
cond_message_once(want_hack, std::cerr, "hack", hack_verbose, __VA_ARGS__)
/**
* The chatty assert macro will function like a normal assert, but will allow the
* specification of additional, helpful material to aid debugging why the
* assertion actually failed. Like the normal assertion, the chatty_assert
* will not be active in fast builds.
*
* @param cond Condition that is checked; if false -> assert
* @param ... Printf-based format string with arguments, extends printout.
*/
#ifdef NDEBUG
#define chatty_assert(cond, ...)
#else //!NDEBUG
#define chatty_assert(cond, ...) \
do { \
if (!(cond)) { \
base_message(std::cerr, "assert("#cond") failing", 1, __VA_ARGS__); \
assert(cond); \
} \
} while (0)
#endif // NDEBUG
#endif // __BASE_MISC_HH__
<|endoftext|>
|
<commit_before>/*
* Copyright (c) 2014 ARM Limited
* All rights reserved
*
* The license below extends only to copyright in the software and shall
* not be construed as granting a license to any other intellectual
* property including but not limited to intellectual property relating
* to a hardware implementation of the functionality of the software
* licensed hereunder. You may use the software subject to the license
* terms below provided that you ensure that this notice is replicated
* unmodified and in its entirety in all distributions of the software,
* modified or unmodified, in source code or in binary form.
*
* Copyright (c) 2002-2005 The Regents of The University of Michigan
* 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 holders 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.
*
* Authors: Nathan Binkert
* Dave Greene
* Andreas Sandberg
*/
#ifndef __BASE_MISC_HH__
#define __BASE_MISC_HH__
#include <cassert>
#include <iostream>
#include "base/compiler.hh"
#include "base/cprintf.hh"
#if defined(__SUNPRO_CC)
#define __FUNCTION__ "how to fix me?"
#endif
void __exit_epilogue(int code,
const char *func, const char *file, int line,
const char *format) M5_ATTR_NORETURN;
// General exit message, these functions will never return and will
// either abort() if code is < 0 or exit with the code if >= 0
template<typename ...Args> void
__exit_message(const char *prefix, int code,
const char *func, const char *file, int line,
const char *format, const Args &...args) M5_ATTR_NORETURN;
template<typename ...Args> void
__exit_message(const char *prefix, int code,
const char *func, const char *file, int line,
const std::string &format, const Args &...args) M5_ATTR_NORETURN;
template<typename ...Args> void
__exit_message(const char *prefix, int code,
const char *func, const char *file, int line,
const char *format, const Args &...args)
{
std::cerr << prefix << ": ";
ccprintf(std::cerr, format, args...);
__exit_epilogue(code, func, file, line, format);
}
template<typename ...Args> void
__exit_message(const char *prefix, int code,
const char *func, const char *file, int line,
const std::string &format, const Args &...args)
{
__exit_message(prefix, code, func, file, line, format.c_str(),
args...);
}
#define exit_message(prefix, code, ...) \
__exit_message(prefix, code, __FUNCTION__, __FILE__, __LINE__, \
__VA_ARGS__)
//
// This implements a cprintf based panic() function. panic() should
// be called when something happens that should never ever happen
// regardless of what the user does (i.e., an acutal m5 bug). panic()
// calls abort which can dump core or enter the debugger.
//
//
#define panic(...) exit_message("panic", -1, __VA_ARGS__)
//
// This implements a cprintf based fatal() function. fatal() should
// be called when the simulation cannot continue due to some condition
// that is the user's fault (bad configuration, invalid arguments,
// etc.) and not a simulator bug. fatal() calls abort() like
// panic() does.
//
#define fatal(...) exit_message("fatal", -1, __VA_ARGS__)
/**
* Conditional panic macro that checks the supplied condition and only panics
* if the condition is true and allows the programmer to specify diagnostic
* printout. Useful to replace if + panic, or if + print + assert, etc.
*
* @param cond Condition that is checked; if true -> panic
* @param ... Printf-based format string with arguments, extends printout.
*/
#define panic_if(cond, ...) \
do { \
if ((cond)) \
exit_message("panic condition "#cond" occurred", -1, __VA_ARGS__); \
} while (0)
/**
* Conditional fatal macro that checks the supplied condition and only causes a
* fatal error if the condition is true and allows the programmer to specify
* diagnostic printout. Useful to replace if + fatal, or if + print + assert,
* etc.
*
* @param cond Condition that is checked; if true -> fatal
* @param ... Printf-based format string with arguments, extends printout.
*/
#define fatal_if(cond, ...) \
do { \
if ((cond)) \
exit_message("fatal condition "#cond" occurred", 1, __VA_ARGS__); \
} while (0)
void
__base_message_epilogue(std::ostream &stream, bool verbose,
const char *func, const char *file, int line,
const char *format);
template<typename ...Args> void
__base_message(std::ostream &stream, const char *prefix, bool verbose,
const char *func, const char *file, int line,
const char *format, const Args &...args)
{
stream << prefix << ": ";
ccprintf(stream, format, args...);
__base_message_epilogue(stream, verbose, func, file, line, format);
}
template<typename ...Args> void
__base_message(std::ostream &stream, const char *prefix, bool verbose,
const char *func, const char *file, int line,
const std::string &format, const Args &...args)
{
__base_message(stream, prefix, verbose, func, file, line, format.c_str(),
args...);
}
#define base_message(stream, prefix, verbose, ...) \
__base_message(stream, prefix, verbose, __FUNCTION__, __FILE__, __LINE__, \
__VA_ARGS__)
// Only print the message the first time this expression is
// encountered. i.e. This doesn't check the string itself and
// prevent duplicate strings, this prevents the statement from
// happening more than once. So, even if the arguments change and that
// would have resulted in a different message thoes messages would be
// supressed.
#define base_message_once(...) do { \
static bool once = false; \
if (!once) { \
base_message(__VA_ARGS__); \
once = true; \
} \
} while (0)
#define cond_message(cond, ...) do { \
if (cond) \
base_message(__VA_ARGS__); \
} while (0)
#define cond_message_once(cond, ...) do { \
static bool once = false; \
if (!once && cond) { \
base_message(__VA_ARGS__); \
once = true; \
} \
} while (0)
extern bool want_warn, warn_verbose;
extern bool want_info, info_verbose;
extern bool want_hack, hack_verbose;
#define warn(...) \
cond_message(want_warn, std::cerr, "warn", warn_verbose, __VA_ARGS__)
#define inform(...) \
cond_message(want_info, std::cout, "info", info_verbose, __VA_ARGS__)
#define hack(...) \
cond_message(want_hack, std::cerr, "hack", hack_verbose, __VA_ARGS__)
#define warn_once(...) \
cond_message_once(want_warn, std::cerr, "warn", warn_verbose, __VA_ARGS__)
#define inform_once(...) \
cond_message_once(want_info, std::cout, "info", info_verbose, __VA_ARGS__)
#define hack_once(...) \
cond_message_once(want_hack, std::cerr, "hack", hack_verbose, __VA_ARGS__)
/**
* The chatty assert macro will function like a normal assert, but will allow the
* specification of additional, helpful material to aid debugging why the
* assertion actually failed. Like the normal assertion, the chatty_assert
* will not be active in fast builds.
*
* @param cond Condition that is checked; if false -> assert
* @param ... Printf-based format string with arguments, extends printout.
*/
#ifdef NDEBUG
#define chatty_assert(cond, ...)
#else //!NDEBUG
#define chatty_assert(cond, ...) \
do { \
if (!(cond)) { \
base_message(std::cerr, "assert("#cond") failing", 1, __VA_ARGS__); \
assert(cond); \
} \
} while (0)
#endif // NDEBUG
#endif // __BASE_MISC_HH__
<commit_msg>base: Add a warn_if macro<commit_after>/*
* Copyright (c) 2014 ARM Limited
* All rights reserved
*
* The license below extends only to copyright in the software and shall
* not be construed as granting a license to any other intellectual
* property including but not limited to intellectual property relating
* to a hardware implementation of the functionality of the software
* licensed hereunder. You may use the software subject to the license
* terms below provided that you ensure that this notice is replicated
* unmodified and in its entirety in all distributions of the software,
* modified or unmodified, in source code or in binary form.
*
* Copyright (c) 2002-2005 The Regents of The University of Michigan
* 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 holders 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.
*
* Authors: Nathan Binkert
* Dave Greene
* Andreas Sandberg
*/
#ifndef __BASE_MISC_HH__
#define __BASE_MISC_HH__
#include <cassert>
#include <iostream>
#include "base/compiler.hh"
#include "base/cprintf.hh"
#if defined(__SUNPRO_CC)
#define __FUNCTION__ "how to fix me?"
#endif
void __exit_epilogue(int code,
const char *func, const char *file, int line,
const char *format) M5_ATTR_NORETURN;
// General exit message, these functions will never return and will
// either abort() if code is < 0 or exit with the code if >= 0
template<typename ...Args> void
__exit_message(const char *prefix, int code,
const char *func, const char *file, int line,
const char *format, const Args &...args) M5_ATTR_NORETURN;
template<typename ...Args> void
__exit_message(const char *prefix, int code,
const char *func, const char *file, int line,
const std::string &format, const Args &...args) M5_ATTR_NORETURN;
template<typename ...Args> void
__exit_message(const char *prefix, int code,
const char *func, const char *file, int line,
const char *format, const Args &...args)
{
std::cerr << prefix << ": ";
ccprintf(std::cerr, format, args...);
__exit_epilogue(code, func, file, line, format);
}
template<typename ...Args> void
__exit_message(const char *prefix, int code,
const char *func, const char *file, int line,
const std::string &format, const Args &...args)
{
__exit_message(prefix, code, func, file, line, format.c_str(),
args...);
}
#define exit_message(prefix, code, ...) \
__exit_message(prefix, code, __FUNCTION__, __FILE__, __LINE__, \
__VA_ARGS__)
//
// This implements a cprintf based panic() function. panic() should
// be called when something happens that should never ever happen
// regardless of what the user does (i.e., an acutal m5 bug). panic()
// calls abort which can dump core or enter the debugger.
//
//
#define panic(...) exit_message("panic", -1, __VA_ARGS__)
//
// This implements a cprintf based fatal() function. fatal() should
// be called when the simulation cannot continue due to some condition
// that is the user's fault (bad configuration, invalid arguments,
// etc.) and not a simulator bug. fatal() calls abort() like
// panic() does.
//
#define fatal(...) exit_message("fatal", -1, __VA_ARGS__)
/**
* Conditional panic macro that checks the supplied condition and only panics
* if the condition is true and allows the programmer to specify diagnostic
* printout. Useful to replace if + panic, or if + print + assert, etc.
*
* @param cond Condition that is checked; if true -> panic
* @param ... Printf-based format string with arguments, extends printout.
*/
#define panic_if(cond, ...) \
do { \
if ((cond)) \
exit_message("panic condition "#cond" occurred", -1, __VA_ARGS__); \
} while (0)
/**
* Conditional fatal macro that checks the supplied condition and only causes a
* fatal error if the condition is true and allows the programmer to specify
* diagnostic printout. Useful to replace if + fatal, or if + print + assert,
* etc.
*
* @param cond Condition that is checked; if true -> fatal
* @param ... Printf-based format string with arguments, extends printout.
*/
#define fatal_if(cond, ...) \
do { \
if ((cond)) \
exit_message("fatal condition "#cond" occurred", 1, __VA_ARGS__); \
} while (0)
void
__base_message_epilogue(std::ostream &stream, bool verbose,
const char *func, const char *file, int line,
const char *format);
template<typename ...Args> void
__base_message(std::ostream &stream, const char *prefix, bool verbose,
const char *func, const char *file, int line,
const char *format, const Args &...args)
{
stream << prefix << ": ";
ccprintf(stream, format, args...);
__base_message_epilogue(stream, verbose, func, file, line, format);
}
template<typename ...Args> void
__base_message(std::ostream &stream, const char *prefix, bool verbose,
const char *func, const char *file, int line,
const std::string &format, const Args &...args)
{
__base_message(stream, prefix, verbose, func, file, line, format.c_str(),
args...);
}
#define base_message(stream, prefix, verbose, ...) \
__base_message(stream, prefix, verbose, __FUNCTION__, __FILE__, __LINE__, \
__VA_ARGS__)
// Only print the message the first time this expression is
// encountered. i.e. This doesn't check the string itself and
// prevent duplicate strings, this prevents the statement from
// happening more than once. So, even if the arguments change and that
// would have resulted in a different message thoes messages would be
// supressed.
#define base_message_once(...) do { \
static bool once = false; \
if (!once) { \
base_message(__VA_ARGS__); \
once = true; \
} \
} while (0)
#define cond_message(cond, ...) do { \
if (cond) \
base_message(__VA_ARGS__); \
} while (0)
#define cond_message_once(cond, ...) do { \
static bool once = false; \
if (!once && cond) { \
base_message(__VA_ARGS__); \
once = true; \
} \
} while (0)
extern bool want_warn, warn_verbose;
extern bool want_info, info_verbose;
extern bool want_hack, hack_verbose;
#define warn(...) \
cond_message(want_warn, std::cerr, "warn", warn_verbose, __VA_ARGS__)
#define inform(...) \
cond_message(want_info, std::cout, "info", info_verbose, __VA_ARGS__)
#define hack(...) \
cond_message(want_hack, std::cerr, "hack", hack_verbose, __VA_ARGS__)
#define warn_once(...) \
cond_message_once(want_warn, std::cerr, "warn", warn_verbose, __VA_ARGS__)
#define inform_once(...) \
cond_message_once(want_info, std::cout, "info", info_verbose, __VA_ARGS__)
#define hack_once(...) \
cond_message_once(want_hack, std::cerr, "hack", hack_verbose, __VA_ARGS__)
/**
* Conditional warning macro that checks the supplied condition and
* only prints a warning if the condition is true. Useful to replace
* if + warn.
*
* @param cond Condition that is checked; if true -> warn
* @param ... Printf-based format string with arguments, extends printout.
*/
#define warn_if(cond, ...) \
do { \
if ((cond)) \
warn(__VA_ARGS__); \
} while (0)
/**
* The chatty assert macro will function like a normal assert, but will allow the
* specification of additional, helpful material to aid debugging why the
* assertion actually failed. Like the normal assertion, the chatty_assert
* will not be active in fast builds.
*
* @param cond Condition that is checked; if false -> assert
* @param ... Printf-based format string with arguments, extends printout.
*/
#ifdef NDEBUG
#define chatty_assert(cond, ...)
#else //!NDEBUG
#define chatty_assert(cond, ...) \
do { \
if (!(cond)) { \
base_message(std::cerr, "assert("#cond") failing", 1, __VA_ARGS__); \
assert(cond); \
} \
} while (0)
#endif // NDEBUG
#endif // __BASE_MISC_HH__
<|endoftext|>
|
<commit_before>/* This file is part of Fabula.
Copyright (C) 2010 Mike McQuaid <mike@mikemcquaid.com>
Fabula is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
Fabula 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 Fabula. If not, see <http://www.gnu.org/licenses/>.
*/
#include "SqlTreeModel.h"
#include <QStringList>
#include <QDebug>
#include <QSqlQuery>
#include <QSqlError>
#include <QMultiMap>
SqlTreeItem::SqlTreeItem(const QString &data, const QString &table, SqlTreeItem *parent, qint64 id, QPixmap icon)
: m_table(table), m_data(data), m_parent(parent), m_id(id), m_icon(icon), m_dirty(false)
{
}
SqlTreeItem::~SqlTreeItem()
{
if (m_parent)
m_parent->m_children.removeAll(this);
qDeleteAll(m_children);
}
SqlTreeItem *SqlTreeItem::child(int row)
{
return m_children.value(row);
}
void SqlTreeItem::appendChild(SqlTreeItem* child)
{
m_children.append(child);
}
int SqlTreeItem::childCount() const
{
return m_children.count();
}
int SqlTreeItem::row() const
{
if (m_parent)
return m_parent->m_children.indexOf(const_cast<SqlTreeItem*>(this));
return 0;
}
const QString &SqlTreeItem::table() const
{
return m_table;
}
const QString &SqlTreeItem::data() const
{
return m_data;
}
qint64 SqlTreeItem::id() const
{
return m_id;
}
void SqlTreeItem::setId(qint64 id)
{
m_id = id;
}
SqlTreeItem *SqlTreeItem::parent()
{
return m_parent;
}
void SqlTreeItem::setData(const QString &data)
{
m_data = data;
m_dirty = true;
}
bool SqlTreeItem::dirty() const
{
return m_dirty;
}
void SqlTreeItem::setDirty(bool dirty)
{
m_dirty = dirty;
}
const QList<SqlTreeItem*>& SqlTreeItem::children() const
{
return m_children;
}
QPixmap SqlTreeItem::icon() const
{
return m_icon;
}
SqlTreeModel::SqlTreeModel(QObject *parent)
: QAbstractItemModel(parent), m_rootItem(0)
{
loadData();
}
void SqlTreeModel::reset()
{
beginResetModel();
tables.clear();
delete m_rootItem;
loadData();
endResetModel();
}
void SqlTreeModel::loadData()
{
tables.append("characters");
tables.append("conversations");
m_rootItem = new SqlTreeItem("Conversations");
QSqlQuery query;
QMultiMap<QString, QString> charactersConversations;
QMap<QString, qint64> charactersIds;
QMap<QString, qint64> conversationsIds;
QPixmap characterIcon(":/icons/view-media-artist.png");
QPixmap conversationIcon(":/icons/irc-voice.png");
// TODO: Make this generic and recursive
query.exec("select characters.id, conversations.id, characters.name, conversations.name from events "
"inner join characters on events.character_id = characters.id "
"inner join conversations on events.conversation_id = conversations.id");
// TODO: Use indexOf("fieldname")
while (query.next()) {
const qint64 characterId = query.value(0).toLongLong();
const qint64 conversationId = query.value(1).toLongLong();
const QString characterName = query.value(2).toString();
const QString conversationName = query.value(3).toString();
charactersConversations.insert(characterName, conversationName);
charactersIds.insert(characterName, characterId);
conversationsIds.insert(conversationName, conversationId);
}
foreach(const QString& characterName, charactersConversations.keys()) {
const qint64 characterId = charactersIds.value(characterName);
SqlTreeItem* character = new SqlTreeItem(characterName, "characters", m_rootItem, characterId, characterIcon);
m_rootItem->appendChild(character);
foreach(const QString& conversationName, charactersConversations.values(characterName)) {
const qint64 conversationId = conversationsIds.value(conversationName);
SqlTreeItem* conversation = new SqlTreeItem(conversationName, "conversations", character, conversationId, conversationIcon);
character->appendChild(conversation);
}
}
}
SqlTreeModel::~SqlTreeModel()
{
delete m_rootItem;
}
QModelIndex SqlTreeModel::index(int row, int column, const QModelIndex &parent)
const
{
if (!hasIndex(row, column, parent))
return QModelIndex();
SqlTreeItem *parentItem = 0;
if (!parent.isValid())
parentItem = m_rootItem;
else
parentItem = static_cast<SqlTreeItem*>(parent.internalPointer());
Q_ASSERT(parentItem);
if (!parentItem)
return QModelIndex();
SqlTreeItem *childItem = parentItem->child(row);
if (childItem)
return createIndex(row, column, childItem);
else
return QModelIndex();
}
QModelIndex SqlTreeModel::parent(const QModelIndex &index) const
{
if (!index.isValid())
return QModelIndex();
SqlTreeItem *childItem = static_cast<SqlTreeItem*>(index.internalPointer());
Q_ASSERT(childItem);
if (!childItem)
return QModelIndex();
SqlTreeItem *parentItem = childItem->parent();
Q_ASSERT(parentItem);
if (!parentItem)
return QModelIndex();
if (parentItem == m_rootItem)
return QModelIndex();
return createIndex(parentItem->row(), 0, parentItem);
}
int SqlTreeModel::rowCount(const QModelIndex &parent) const
{
SqlTreeItem *parentItem = 0;
if (parent.column() > 0)
return 0;
if (!parent.isValid())
parentItem = m_rootItem;
else
parentItem = static_cast<SqlTreeItem*>(parent.internalPointer());
Q_ASSERT(parentItem);
if (!parentItem)
return 0;
return parentItem->childCount();
}
int SqlTreeModel::columnCount(const QModelIndex&) const
{
return 1;
}
QVariant SqlTreeModel::data(const QModelIndex &index, int role) const
{
if (!index.isValid())
return QVariant();
SqlTreeItem *item = static_cast<SqlTreeItem*>(index.internalPointer());
Q_ASSERT(item);
if (!item)
return QVariant();
if (role == Qt::DisplayRole)
return item->data();
if (role == Qt::DecorationRole)
return item->icon();
return QVariant();
}
bool SqlTreeModel::setData(const QModelIndex &index, const QVariant &value, int role)
{
if (!index.isValid())
return false;
if (role != Qt::EditRole)
return false;
if (value.toString().isEmpty())
return false;
SqlTreeItem *item = static_cast<SqlTreeItem*>(index.internalPointer());
Q_ASSERT(item);
if (!item)
return false;
const int id = item->id();
if (id != SqlTreeItem::INVALID_ID) {
foreach (SqlTreeItem* characterItem, m_rootItem->children()) {
Q_ASSERT(characterItem);
if (!characterItem)
return false;
if (id == characterItem->id())
characterItem->setData(value.toString());
foreach (SqlTreeItem* conversationItem, characterItem->children()) {
Q_ASSERT(conversationItem);
if (!conversationItem)
return false;
if (id == conversationItem->id())
conversationItem->setData(value.toString());
}
}
}
else
item->setData(value.toString());
emit dataChanged(index, index);
return true;
}
bool SqlTreeModel::insertRow(int, const QModelIndex &parent)
{
SqlTreeItem *parentItem = static_cast<SqlTreeItem*>(parent.internalPointer());
Q_ASSERT(parentItem);
if (!parentItem)
return false;
if (!parentItem)
parentItem = m_rootItem;
beginInsertRows(parent, 0, parentItem->childCount());
const QString newItemTable = getChildTable(parentItem->table());
SqlTreeItem* newItem = new SqlTreeItem("New Item", newItemTable, parentItem);
newItem->setDirty(true);
parentItem->appendChild(newItem);
endInsertRows();
return true;
}
QString SqlTreeModel::getChildTable(const QString& parentTable)
{
QString previousTable;
foreach(const QString& table, tables) {
if (parentTable == previousTable)
return table;
previousTable = table;
}
return QString();
}
Qt::ItemFlags SqlTreeModel::flags(const QModelIndex &index) const
{
if (!index.isValid())
return 0;
return Qt::ItemIsEnabled | Qt::ItemIsSelectable | Qt::ItemIsEditable;
}
QVariant SqlTreeModel::headerData(int, Qt::Orientation orientation,
int role) const
{
if (orientation != Qt::Horizontal || role != Qt::DisplayRole)
return QVariant();
Q_ASSERT(m_rootItem);
if (!m_rootItem)
return QVariant();
return m_rootItem->data();
}
bool SqlTreeModel::submit()
{
QList<SqlTreeItem*> newCharacters;
QList<SqlTreeItem*> newConversations;
QList<SqlTreeItem*> updatedCharacters;
QList<SqlTreeItem*> updatedConversations;
foreach (SqlTreeItem* characterItem, m_rootItem->children()) {
Q_ASSERT(characterItem);
if (!characterItem)
return false;
if (characterItem->data() == "New Item")
continue;
if (characterItem->dirty()) {
if (characterItem->id() == SqlTreeItem::INVALID_ID)
newCharacters.append(characterItem);
else
updatedCharacters.append(characterItem);
}
foreach (SqlTreeItem* conversationItem, characterItem->children()) {
Q_ASSERT(conversationItem);
if (!conversationItem)
return false;
if (conversationItem->data() == "New Item")
continue;
if (conversationItem->dirty()) {
if (conversationItem->id() == SqlTreeItem::INVALID_ID)
newConversations.append(conversationItem);
else
updatedConversations.append(conversationItem);
}
}
}
QSqlQuery query;
bool querySuccess = false;
foreach (SqlTreeItem* newCharacter, newCharacters) {
Q_ASSERT(newCharacter);
if (!newCharacter)
return false;
query.prepare("insert into characters(name) values(:name)");
query.bindValue(":name", newCharacter->data());
querySuccess = query.exec();
if (querySuccess) {
newCharacter->setId(query.lastInsertId().toInt());
newCharacter->setDirty(false);
}
else
qWarning() << query.lastQuery() << query.lastError();
}
foreach (SqlTreeItem* newConversation, newConversations) {
Q_ASSERT(newConversation);
if (!newConversation)
return false;
query.prepare("insert into conversations(name) values(:name)");
query.bindValue(":name", newConversation->data());
querySuccess = query.exec();
if (querySuccess) {
newConversation->setId(query.lastInsertId().toInt());
newConversation->setDirty(false);
}
else
qWarning() << query.lastQuery() << query.lastError();
}
// TODO: Check we update at least one row
foreach (SqlTreeItem* updatedCharacter, updatedCharacters) {
Q_ASSERT(updatedCharacter);
if (!updatedCharacter)
return false;
query.prepare("update characters set name=:name where id=:id");
query.bindValue(":name", updatedCharacter->data());
query.bindValue(":id", updatedCharacter->id());
querySuccess = query.exec();
if (querySuccess)
updatedCharacter->setDirty(false);
else
qWarning() << query.lastQuery() << query.lastError();
}
foreach (SqlTreeItem* updatedConversation, updatedConversations) {
Q_ASSERT(updatedConversation);
if (!updatedConversation)
return false;
query.prepare("update conversations set name=:name where id=:id");
query.bindValue(":name", updatedConversation->data());
query.bindValue(":id", updatedConversation->id());
querySuccess = query.exec();
if (querySuccess)
updatedConversation->setDirty(false);
else
qWarning() << query.lastQuery() << query.lastError();
}
emit submitted();
return true;
}
<commit_msg>Only list one of each character in SqlTreeModel.<commit_after>/* This file is part of Fabula.
Copyright (C) 2010 Mike McQuaid <mike@mikemcquaid.com>
Fabula is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
Fabula 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 Fabula. If not, see <http://www.gnu.org/licenses/>.
*/
#include "SqlTreeModel.h"
#include <QStringList>
#include <QDebug>
#include <QSqlQuery>
#include <QSqlError>
#include <QMultiMap>
SqlTreeItem::SqlTreeItem(const QString &data, const QString &table, SqlTreeItem *parent, qint64 id, QPixmap icon)
: m_table(table), m_data(data), m_parent(parent), m_id(id), m_icon(icon), m_dirty(false)
{
}
SqlTreeItem::~SqlTreeItem()
{
if (m_parent)
m_parent->m_children.removeAll(this);
qDeleteAll(m_children);
}
SqlTreeItem *SqlTreeItem::child(int row)
{
return m_children.value(row);
}
void SqlTreeItem::appendChild(SqlTreeItem* child)
{
m_children.append(child);
}
int SqlTreeItem::childCount() const
{
return m_children.count();
}
int SqlTreeItem::row() const
{
if (m_parent)
return m_parent->m_children.indexOf(const_cast<SqlTreeItem*>(this));
return 0;
}
const QString &SqlTreeItem::table() const
{
return m_table;
}
const QString &SqlTreeItem::data() const
{
return m_data;
}
qint64 SqlTreeItem::id() const
{
return m_id;
}
void SqlTreeItem::setId(qint64 id)
{
m_id = id;
}
SqlTreeItem *SqlTreeItem::parent()
{
return m_parent;
}
void SqlTreeItem::setData(const QString &data)
{
m_data = data;
m_dirty = true;
}
bool SqlTreeItem::dirty() const
{
return m_dirty;
}
void SqlTreeItem::setDirty(bool dirty)
{
m_dirty = dirty;
}
const QList<SqlTreeItem*>& SqlTreeItem::children() const
{
return m_children;
}
QPixmap SqlTreeItem::icon() const
{
return m_icon;
}
SqlTreeModel::SqlTreeModel(QObject *parent)
: QAbstractItemModel(parent), m_rootItem(0)
{
loadData();
}
void SqlTreeModel::reset()
{
beginResetModel();
tables.clear();
delete m_rootItem;
loadData();
endResetModel();
}
void SqlTreeModel::loadData()
{
tables.append("characters");
tables.append("conversations");
m_rootItem = new SqlTreeItem("Conversations");
QSqlQuery query;
QMultiMap<QString, QString> charactersConversations;
QMap<QString, qint64> charactersIds;
QMap<QString, qint64> conversationsIds;
QPixmap characterIcon(":/icons/view-media-artist.png");
QPixmap conversationIcon(":/icons/irc-voice.png");
// TODO: Make this generic and recursive
query.exec("select characters.id, conversations.id, characters.name, conversations.name from events "
"inner join characters on events.character_id = characters.id "
"inner join conversations on events.conversation_id = conversations.id");
// TODO: Use indexOf("fieldname")
while (query.next()) {
const qint64 characterId = query.value(0).toLongLong();
const qint64 conversationId = query.value(1).toLongLong();
const QString characterName = query.value(2).toString();
const QString conversationName = query.value(3).toString();
charactersConversations.insert(characterName, conversationName);
charactersIds.insert(characterName, characterId);
conversationsIds.insert(conversationName, conversationId);
}
foreach(const QString& characterName, charactersConversations.uniqueKeys()) {
const qint64 characterId = charactersIds.value(characterName);
SqlTreeItem* character = new SqlTreeItem(characterName, "characters", m_rootItem, characterId, characterIcon);
m_rootItem->appendChild(character);
foreach(const QString& conversationName, charactersConversations.values(characterName)) {
const qint64 conversationId = conversationsIds.value(conversationName);
SqlTreeItem* conversation = new SqlTreeItem(conversationName, "conversations", character, conversationId, conversationIcon);
character->appendChild(conversation);
}
}
}
SqlTreeModel::~SqlTreeModel()
{
delete m_rootItem;
}
QModelIndex SqlTreeModel::index(int row, int column, const QModelIndex &parent)
const
{
if (!hasIndex(row, column, parent))
return QModelIndex();
SqlTreeItem *parentItem = 0;
if (!parent.isValid())
parentItem = m_rootItem;
else
parentItem = static_cast<SqlTreeItem*>(parent.internalPointer());
Q_ASSERT(parentItem);
if (!parentItem)
return QModelIndex();
SqlTreeItem *childItem = parentItem->child(row);
if (childItem)
return createIndex(row, column, childItem);
else
return QModelIndex();
}
QModelIndex SqlTreeModel::parent(const QModelIndex &index) const
{
if (!index.isValid())
return QModelIndex();
SqlTreeItem *childItem = static_cast<SqlTreeItem*>(index.internalPointer());
Q_ASSERT(childItem);
if (!childItem)
return QModelIndex();
SqlTreeItem *parentItem = childItem->parent();
Q_ASSERT(parentItem);
if (!parentItem)
return QModelIndex();
if (parentItem == m_rootItem)
return QModelIndex();
return createIndex(parentItem->row(), 0, parentItem);
}
int SqlTreeModel::rowCount(const QModelIndex &parent) const
{
SqlTreeItem *parentItem = 0;
if (parent.column() > 0)
return 0;
if (!parent.isValid())
parentItem = m_rootItem;
else
parentItem = static_cast<SqlTreeItem*>(parent.internalPointer());
Q_ASSERT(parentItem);
if (!parentItem)
return 0;
return parentItem->childCount();
}
int SqlTreeModel::columnCount(const QModelIndex&) const
{
return 1;
}
QVariant SqlTreeModel::data(const QModelIndex &index, int role) const
{
if (!index.isValid())
return QVariant();
SqlTreeItem *item = static_cast<SqlTreeItem*>(index.internalPointer());
Q_ASSERT(item);
if (!item)
return QVariant();
if (role == Qt::DisplayRole)
return item->data();
if (role == Qt::DecorationRole)
return item->icon();
return QVariant();
}
bool SqlTreeModel::setData(const QModelIndex &index, const QVariant &value, int role)
{
if (!index.isValid())
return false;
if (role != Qt::EditRole)
return false;
if (value.toString().isEmpty())
return false;
SqlTreeItem *item = static_cast<SqlTreeItem*>(index.internalPointer());
Q_ASSERT(item);
if (!item)
return false;
const int id = item->id();
if (id != SqlTreeItem::INVALID_ID) {
foreach (SqlTreeItem* characterItem, m_rootItem->children()) {
Q_ASSERT(characterItem);
if (!characterItem)
return false;
if (id == characterItem->id())
characterItem->setData(value.toString());
foreach (SqlTreeItem* conversationItem, characterItem->children()) {
Q_ASSERT(conversationItem);
if (!conversationItem)
return false;
if (id == conversationItem->id())
conversationItem->setData(value.toString());
}
}
}
else
item->setData(value.toString());
emit dataChanged(index, index);
return true;
}
bool SqlTreeModel::insertRow(int, const QModelIndex &parent)
{
SqlTreeItem *parentItem = static_cast<SqlTreeItem*>(parent.internalPointer());
Q_ASSERT(parentItem);
if (!parentItem)
return false;
if (!parentItem)
parentItem = m_rootItem;
beginInsertRows(parent, 0, parentItem->childCount());
const QString newItemTable = getChildTable(parentItem->table());
SqlTreeItem* newItem = new SqlTreeItem("New Item", newItemTable, parentItem);
newItem->setDirty(true);
parentItem->appendChild(newItem);
endInsertRows();
return true;
}
QString SqlTreeModel::getChildTable(const QString& parentTable)
{
QString previousTable;
foreach(const QString& table, tables) {
if (parentTable == previousTable)
return table;
previousTable = table;
}
return QString();
}
Qt::ItemFlags SqlTreeModel::flags(const QModelIndex &index) const
{
if (!index.isValid())
return 0;
return Qt::ItemIsEnabled | Qt::ItemIsSelectable | Qt::ItemIsEditable;
}
QVariant SqlTreeModel::headerData(int, Qt::Orientation orientation,
int role) const
{
if (orientation != Qt::Horizontal || role != Qt::DisplayRole)
return QVariant();
Q_ASSERT(m_rootItem);
if (!m_rootItem)
return QVariant();
return m_rootItem->data();
}
bool SqlTreeModel::submit()
{
QList<SqlTreeItem*> newCharacters;
QList<SqlTreeItem*> newConversations;
QList<SqlTreeItem*> updatedCharacters;
QList<SqlTreeItem*> updatedConversations;
foreach (SqlTreeItem* characterItem, m_rootItem->children()) {
Q_ASSERT(characterItem);
if (!characterItem)
return false;
if (characterItem->data() == "New Item")
continue;
if (characterItem->dirty()) {
if (characterItem->id() == SqlTreeItem::INVALID_ID)
newCharacters.append(characterItem);
else
updatedCharacters.append(characterItem);
}
foreach (SqlTreeItem* conversationItem, characterItem->children()) {
Q_ASSERT(conversationItem);
if (!conversationItem)
return false;
if (conversationItem->data() == "New Item")
continue;
if (conversationItem->dirty()) {
if (conversationItem->id() == SqlTreeItem::INVALID_ID)
newConversations.append(conversationItem);
else
updatedConversations.append(conversationItem);
}
}
}
QSqlQuery query;
bool querySuccess = false;
foreach (SqlTreeItem* newCharacter, newCharacters) {
Q_ASSERT(newCharacter);
if (!newCharacter)
return false;
query.prepare("insert into characters(name) values(:name)");
query.bindValue(":name", newCharacter->data());
querySuccess = query.exec();
if (querySuccess) {
newCharacter->setId(query.lastInsertId().toInt());
newCharacter->setDirty(false);
}
else
qWarning() << query.lastQuery() << query.lastError();
}
foreach (SqlTreeItem* newConversation, newConversations) {
Q_ASSERT(newConversation);
if (!newConversation)
return false;
query.prepare("insert into conversations(name) values(:name)");
query.bindValue(":name", newConversation->data());
querySuccess = query.exec();
if (querySuccess) {
newConversation->setId(query.lastInsertId().toInt());
newConversation->setDirty(false);
}
else
qWarning() << query.lastQuery() << query.lastError();
}
// TODO: Check we update at least one row
foreach (SqlTreeItem* updatedCharacter, updatedCharacters) {
Q_ASSERT(updatedCharacter);
if (!updatedCharacter)
return false;
query.prepare("update characters set name=:name where id=:id");
query.bindValue(":name", updatedCharacter->data());
query.bindValue(":id", updatedCharacter->id());
querySuccess = query.exec();
if (querySuccess)
updatedCharacter->setDirty(false);
else
qWarning() << query.lastQuery() << query.lastError();
}
foreach (SqlTreeItem* updatedConversation, updatedConversations) {
Q_ASSERT(updatedConversation);
if (!updatedConversation)
return false;
query.prepare("update conversations set name=:name where id=:id");
query.bindValue(":name", updatedConversation->data());
query.bindValue(":id", updatedConversation->id());
querySuccess = query.exec();
if (querySuccess)
updatedConversation->setDirty(false);
else
qWarning() << query.lastQuery() << query.lastError();
}
emit submitted();
return true;
}
<|endoftext|>
|
<commit_before>//@author A0097630B
#include "stdafx.h"
#include "You-QueryEngine/task_model.h"
#include "exception.h"
#include "query_parser.h"
using Assert = Microsoft::VisualStudio::CppUnitTestFramework::Assert;
namespace You {
namespace NLP {
namespace UnitTests {
using boost::gregorian::date;
using boost::posix_time::ptime;
using boost::posix_time::hours;
using You::NLP::ParserException;
using You::NLP::QueryParser;
using You::NLP::ADD_QUERY;
using You::NLP::EDIT_QUERY;
using You::NLP::QUERY;
TEST_CLASS(QueryParserTests) {
public:
TEST_METHOD(throwsExceptionOnEmptyString) {
Assert::ExpectException<ParserException>([]() {
QueryParser::parse(L"");
}, L"Throws exception on empty string");
}
TEST_METHOD(throwsExceptionWhenParseFails) {
Assert::ExpectException<ParserException>([]() {
// "throw" is currently not defined, so this should work.
QueryParser::parse(L"/throw");
}, L"Throws exception on syntax error");
}
TEST_METHOD(parsesStringAsTask) {
QUERY q = QueryParser::parse(L"win");
Assert::AreEqual(QUERY(ADD_QUERY {
L"win"
}), q);
q = QueryParser::parse(L"win lottery");
Assert::AreEqual(QUERY(ADD_QUERY {
L"win lottery"
}), q);
}
TEST_METHOD(parsesStringWithDeadlineAsTask) {
QUERY q = QueryParser::parse(L"win by may 2014");
Assert::AreEqual(QUERY(ADD_QUERY {
L"win",
TaskPriority::NORMAL,
ptime(date(2014, boost::gregorian::May, 1), hours(0))
}), q);
q = QueryParser::parse(L"win lottery by dec 2014");
Assert::AreEqual(QUERY(ADD_QUERY {
L"win lottery",
TaskPriority::NORMAL,
ptime(date(2014, boost::gregorian::Dec, 1), hours(0))
}), q);
}
TEST_METHOD(parsesStringWithPriorityAsTask) {
QUERY q = QueryParser::parse(L"win!");
Assert::AreEqual(QUERY(ADD_QUERY {
L"win",
TaskPriority::HIGH
}), q);
q = QueryParser::parse(L"win lottery! by dec 2014");
Assert::AreEqual(QUERY(ADD_QUERY {
L"win lottery",
TaskPriority::HIGH,
ptime(date(2014, boost::gregorian::Dec, 1), hours(0))
}), q);
}
TEST_METHOD(parsesShowQuery) {
// Boundary case: one filter, zero sort.
QUERY q = QueryParser::parse(L"/show description='\\\\\\'meh'");
Assert::AreEqual(QUERY(SHOW_QUERY {
{
{
TaskField::DESCRIPTION,
SHOW_QUERY::Predicate::EQ,
std::wstring(L"\\\'meh")
}
},
{}
}), q);
// Boundary case: more than one filter, zero sort.
q = QueryParser::parse(L"/show description!='\\\\\\'meh', "
L"priority<high");
Assert::AreEqual(QUERY(SHOW_QUERY {
{
{
TaskField::DESCRIPTION,
SHOW_QUERY::Predicate::NOT_EQ,
std::wstring(L"\\\'meh")
},
{
TaskField::PRIORITY,
SHOW_QUERY::Predicate::LESS_THAN,
TaskPriority::HIGH
}
},
{}
}), q);
// Boundary case: zero filter, one sort.
q = QueryParser::parse(L"/show order by description ascending");
Assert::AreEqual(QUERY(SHOW_QUERY {
{},
{ { TaskField::DESCRIPTION, SHOW_QUERY::Order::ASCENDING } }
}), q);
// Boundary case: zero filter, more than one sort.
q = QueryParser::parse(L"/show order by description descending, "
L"priority");
Assert::AreEqual(QUERY(SHOW_QUERY {
{},
{
{ TaskField::DESCRIPTION, SHOW_QUERY::Order::DESCENDING },
{ TaskField::PRIORITY, SHOW_QUERY::Order::ASCENDING }
}
}), q);
// Boundary case: nonzero filter, nonzero sort.
q = QueryParser::parse(L"/show description!='\\\\\\'meh', "
L"priority<high, priority>normal, deadline>='3 oct', "
L"deadline<='7 oct' order by description descending, priority");
Assert::AreEqual(QUERY(SHOW_QUERY {
{
{
TaskField::DESCRIPTION,
SHOW_QUERY::Predicate::NOT_EQ,
std::wstring(L"\\\'meh")
},
{
TaskField::PRIORITY,
SHOW_QUERY::Predicate::LESS_THAN,
TaskPriority::HIGH
},
{
TaskField::PRIORITY,
SHOW_QUERY::Predicate::GREATER_THAN,
TaskPriority::NORMAL
},
{
TaskField::DEADLINE,
SHOW_QUERY::Predicate::GREATER_THAN_EQ,
boost::posix_time::ptime(
boost::gregorian::date(2015, 10, 3),
boost::posix_time::hours(0))
},
{
TaskField::DEADLINE,
SHOW_QUERY::Predicate::LESS_THAN_EQ,
boost::posix_time::ptime(
boost::gregorian::date(2015, 10, 7),
boost::posix_time::hours(0))
}
},
{
{ TaskField::DESCRIPTION, SHOW_QUERY::Order::DESCENDING },
{ TaskField::PRIORITY, SHOW_QUERY::Order::ASCENDING }
}
}), q);
}
TEST_METHOD(parsesEditQuery) {
QUERY q = QueryParser::parse(L"/edit 10 set description='meh'");
Assert::AreEqual(QUERY(EDIT_QUERY {
10,
L"meh"
}), q);
q = QueryParser::parse(L"/edit 10 set description='meh with spaces'");
Assert::AreEqual(QUERY(EDIT_QUERY {
10,
L"meh with spaces"
}), q);
q = QueryParser::parse(L"/edit 10 set deadline='oct 2014'");
Assert::AreEqual(QUERY(EDIT_QUERY {
10,
Utils::Option<std::wstring>(),
Utils::Option<TaskPriority>(),
ptime(date(2014, boost::gregorian::Oct, 1), hours(0))
}), q);
q = QueryParser::parse(L"/edit 10 set complete");
Assert::AreEqual(QUERY(EDIT_QUERY {
10,
Utils::Option<std::wstring>(),
Utils::Option<TaskPriority>(),
Utils::Option<boost::posix_time::ptime>(),
true
}), q);
q = QueryParser::parse(L"/edit 10 set priority=high");
Assert::AreEqual(QUERY(EDIT_QUERY {
10,
Utils::Option<std::wstring>(),
TaskPriority::HIGH
}), q);
}
TEST_METHOD(parsesEditQueryWithWrongType) {
Assert::ExpectException<ParserTypeException>([]() {
QueryParser::parse(L"/edit 10 set description='14 oct'");
});
}
TEST_METHOD(parsesDeleteQuery) {
QUERY q = QueryParser::parse(L"/delete 10");
Assert::AreEqual(QUERY(DELETE_QUERY {
10
}), q);
}
TEST_METHOD(parsesUndoQuery) {
QUERY q = QueryParser::parse(L"/undo");
Assert::AreEqual(QUERY(UNDO_QUERY {}), q);
}
};
} // namespace UnitTests
} // namespace NLP
} // namespace You
<commit_msg>Improve code coverage.<commit_after>//@author A0097630B
#include "stdafx.h"
#include "You-QueryEngine/task_model.h"
#include "exception.h"
#include "query_parser.h"
using Assert = Microsoft::VisualStudio::CppUnitTestFramework::Assert;
namespace You {
namespace NLP {
namespace UnitTests {
using boost::gregorian::date;
using boost::posix_time::ptime;
using boost::posix_time::hours;
using You::NLP::ParserException;
using You::NLP::QueryParser;
using You::NLP::ADD_QUERY;
using You::NLP::EDIT_QUERY;
using You::NLP::QUERY;
TEST_CLASS(QueryParserTests) {
public:
TEST_METHOD(throwsExceptionOnEmptyString) {
Assert::ExpectException<ParserException>([]() {
QueryParser::parse(L"");
}, L"Throws exception on empty string");
}
TEST_METHOD(throwsExceptionWhenParseFails) {
Assert::ExpectException<ParserException>([]() {
// "throw" is currently not defined, so this should work.
QueryParser::parse(L"/throw");
}, L"Throws exception on syntax error");
}
TEST_METHOD(parsesStringAsTask) {
QUERY q = QueryParser::parse(L"win");
Assert::AreEqual(QUERY(ADD_QUERY {
L"win"
}), q);
q = QueryParser::parse(L"win lottery");
Assert::AreEqual(QUERY(ADD_QUERY {
L"win lottery"
}), q);
}
TEST_METHOD(parsesStringWithDeadlineAsTask) {
QUERY q = QueryParser::parse(L"win by may 2014");
Assert::AreEqual(QUERY(ADD_QUERY {
L"win",
TaskPriority::NORMAL,
ptime(date(2014, boost::gregorian::May, 1), hours(0))
}), q);
q = QueryParser::parse(L"win lottery by dec 2014");
Assert::AreEqual(QUERY(ADD_QUERY {
L"win lottery",
TaskPriority::NORMAL,
ptime(date(2014, boost::gregorian::Dec, 1), hours(0))
}), q);
}
TEST_METHOD(parsesStringWithPriorityAsTask) {
QUERY q = QueryParser::parse(L"win!");
Assert::AreEqual(QUERY(ADD_QUERY {
L"win",
TaskPriority::HIGH
}), q);
q = QueryParser::parse(L"win lottery! by dec 2014");
Assert::AreEqual(QUERY(ADD_QUERY {
L"win lottery",
TaskPriority::HIGH,
ptime(date(2014, boost::gregorian::Dec, 1), hours(0))
}), q);
}
TEST_METHOD(parsesShowQuery) {
// Boundary case: one filter, zero sort.
QUERY q = QueryParser::parse(L"/show description='\\\\\\'meh'");
Assert::AreEqual(QUERY(SHOW_QUERY {
{
{
TaskField::DESCRIPTION,
SHOW_QUERY::Predicate::EQ,
std::wstring(L"\\\'meh")
}
},
{}
}), q);
// Boundary case: more than one filter, zero sort.
q = QueryParser::parse(L"/show description!='\\\\\\'meh', "
L"priority<high");
Assert::AreEqual(QUERY(SHOW_QUERY {
{
{
TaskField::DESCRIPTION,
SHOW_QUERY::Predicate::NOT_EQ,
std::wstring(L"\\\'meh")
},
{
TaskField::PRIORITY,
SHOW_QUERY::Predicate::LESS_THAN,
TaskPriority::HIGH
}
},
{}
}), q);
// Boundary case: zero filter, one sort.
q = QueryParser::parse(L"/show order by description ascending");
Assert::AreEqual(QUERY(SHOW_QUERY {
{},
{ { TaskField::DESCRIPTION, SHOW_QUERY::Order::ASCENDING } }
}), q);
// Boundary case: zero filter, more than one sort.
q = QueryParser::parse(L"/show order by description descending, "
L"priority");
Assert::AreEqual(QUERY(SHOW_QUERY {
{},
{
{ TaskField::DESCRIPTION, SHOW_QUERY::Order::DESCENDING },
{ TaskField::PRIORITY, SHOW_QUERY::Order::ASCENDING }
}
}), q);
// Boundary case: nonzero filter, nonzero sort.
q = QueryParser::parse(L"/show description!='\\\\\\'meh', "
L"priority<high, priority>normal, deadline>='3 oct', "
L"deadline<='7 oct', complete=true order by description descending, priority");
Assert::AreEqual(QUERY(SHOW_QUERY {
{
{
TaskField::DESCRIPTION,
SHOW_QUERY::Predicate::NOT_EQ,
std::wstring(L"\\\'meh")
},
{
TaskField::PRIORITY,
SHOW_QUERY::Predicate::LESS_THAN,
TaskPriority::HIGH
},
{
TaskField::PRIORITY,
SHOW_QUERY::Predicate::GREATER_THAN,
TaskPriority::NORMAL
},
{
TaskField::DEADLINE,
SHOW_QUERY::Predicate::GREATER_THAN_EQ,
boost::posix_time::ptime(
boost::gregorian::date(2015, 10, 3),
boost::posix_time::hours(0))
},
{
TaskField::DEADLINE,
SHOW_QUERY::Predicate::LESS_THAN_EQ,
boost::posix_time::ptime(
boost::gregorian::date(2015, 10, 7),
boost::posix_time::hours(0))
},
{
TaskField::COMPLETE,
SHOW_QUERY::Predicate::EQ,
true
}
},
{
{ TaskField::DESCRIPTION, SHOW_QUERY::Order::DESCENDING },
{ TaskField::PRIORITY, SHOW_QUERY::Order::ASCENDING }
}
}), q);
}
TEST_METHOD(parsesShowQueryWithWrongType) {
Assert::ExpectException<ParserTypeException>([]() {
QueryParser::parse(L"/show description=false");
});
}
TEST_METHOD(parsesEditQuery) {
QUERY q = QueryParser::parse(L"/edit 10 set description='meh'");
Assert::AreEqual(QUERY(EDIT_QUERY {
10,
L"meh"
}), q);
q = QueryParser::parse(L"/edit 10 set description='meh with spaces'");
Assert::AreEqual(QUERY(EDIT_QUERY {
10,
L"meh with spaces"
}), q);
q = QueryParser::parse(L"/edit 10 set deadline='oct 2014'");
Assert::AreEqual(QUERY(EDIT_QUERY {
10,
Utils::Option<std::wstring>(),
Utils::Option<TaskPriority>(),
ptime(date(2014, boost::gregorian::Oct, 1), hours(0))
}), q);
q = QueryParser::parse(L"/edit 10 set complete");
Assert::AreEqual(QUERY(EDIT_QUERY {
10,
Utils::Option<std::wstring>(),
Utils::Option<TaskPriority>(),
Utils::Option<boost::posix_time::ptime>(),
true
}), q);
q = QueryParser::parse(L"/edit 10 set priority=high");
Assert::AreEqual(QUERY(EDIT_QUERY {
10,
Utils::Option<std::wstring>(),
TaskPriority::HIGH
}), q);
}
TEST_METHOD(parsesEditQueryWithWrongType) {
Assert::ExpectException<ParserTypeException>([]() {
QueryParser::parse(L"/edit 10 set description='14 oct'");
});
}
TEST_METHOD(parsesDeleteQuery) {
QUERY q = QueryParser::parse(L"/delete 10");
Assert::AreEqual(QUERY(DELETE_QUERY {
10
}), q);
}
TEST_METHOD(parsesUndoQuery) {
QUERY q = QueryParser::parse(L"/undo");
Assert::AreEqual(QUERY(UNDO_QUERY {}), q);
}
};
} // namespace UnitTests
} // namespace NLP
} // namespace You
<|endoftext|>
|
<commit_before>#include "TmxScene.h"
using namespace hb;
TmxScene::TmxScene(const std::string& scene_name, const std::string& file_name, std::function<void(const Tmx::Map*)>&& post_init):
Game::Scene(scene_name, [](){}),
m_post_init(std::move(post_init))
{
HB_CHECK_TMXPARSER_VERSION();
m_init = [this, file_name]()
{
Tmx::Map* map = new Tmx::Map();
map->ParseFile(file_name);
if (map->HasError())
{
hb_log("error code: " << map->GetErrorCode() << std::endl);
hb_log("error text: " << map->GetErrorText().c_str() << std::endl);
std::exit(map->GetErrorCode());
}
int last_slash = file_name.find_last_of("/");
std::string path = file_name.substr(0, last_slash +1);
std::string c = map->GetBackgroundColor();
if (c.size() != 0)
{
int r = std::stoul(c.substr(1,2), nullptr, 16);
int g = std::stoul(c.substr(3,2), nullptr, 16);
int b = std::stoul(c.substr(5,2), nullptr, 16);
Color color(r, g, b);
Renderer::setClearColor(color);
}
if (map->GetOrientation() == Tmx::TMX_MO_ORTHOGONAL)
{
Renderer::getCamera().setAxisX(Vector3d(map->GetTileWidth(), 0, 0));
Renderer::getCamera().setAxisY(Vector3d(0, map->GetTileHeight(), 0));
Renderer::getCamera().setAxisZ(Vector3d(0, 0, 1));
}
else if (map->GetOrientation() == Tmx::TMX_MO_ISOMETRIC)
{
Renderer::getCamera().setAxisX(Vector3d(map->GetTileWidth(), map->GetTileHeight(), map->GetTileHeight()));
Renderer::getCamera().setAxisY(Vector3d(-map->GetTileWidth(), map->GetTileHeight(), map->GetTileHeight()));
Renderer::getCamera().setAxisZ(Vector3d(0, 0, 1));
}
GameObject::setNextGameObjectId(map->GetNextObjectId());
// Make Image layers
for (int i = 0; i < map->GetNumImageLayers(); ++i)
{
const Tmx::ImageLayer* layer = map->GetImageLayer(i);
if (not layer->IsVisible()) continue;
GameObject *image_layer_go = new GameObject();
image_layer_go->setName(layer->GetName());
image_layer_go->setPosition(Vector3d(layer->GetX()/map->GetTileWidth(), layer->GetY()/map->GetTileHeight(), layer->GetZOrder()));
Texture tex = Texture::loadFromFile(path + layer->GetImage()->GetSource(), Rect(0, 0, layer->GetImage()->GetWidth(), layer->GetImage()->GetHeight()));
Sprite sprite = Sprite(tex);
auto sprite_comp = new SpriteComponent(sprite);
image_layer_go->addComponent(sprite_comp);
}
// Make tile layers
for (int i = 0; i < map->GetNumTileLayers(); ++i)
{
const Tmx::TileLayer* layer = map->GetTileLayer(i);
if (not layer->IsVisible()) continue;
GameObject *tile_layer_go = new GameObject();
tile_layer_go->setName(layer->GetName());
tile_layer_go->setPosition(Vector3d(0, 0, layer->GetZOrder()));
for (int y = 0; y < layer->GetHeight(); ++y)
{
for (int x = 0; x < layer->GetWidth(); ++x)
{
if (layer->GetTileTilesetIndex(x, y) == -1) continue;
int gid = layer->GetTileId(x, y);
const Tmx::Tileset *tileset = map->FindTileset(gid);
int lid = gid - tileset->GetFirstGid();
std::vector<int> anim;
Time t_anim = Time::seconds(0);
const Tmx::Tile* tile = tileset->GetTile(lid);
if (tile->IsAnimated())
{
t_anim = Time::milliseconds(tile->GetTotalDuration() / tile->GetFrameCount());
for (auto anim_frame : tile->GetFrames())
{
anim.push_back(anim_frame.GetTileID());
}
}
else
{
anim.push_back(lid);
}
Texture tex = Texture::loadFromFile(path + tileset->GetImage()->GetSource(), Rect(0, 0, tileset->GetImage()->GetWidth(), tileset->GetImage()->GetHeight()));
Sprite sprite = Sprite(tex, Vector2d(tileset->GetTileWidth(), tileset->GetTileHeight()), Vector2d(tileset->GetMargin(), tileset->GetMargin()));
auto sprite_comp = new SpriteComponent(sprite, anim, t_anim);
sprite_comp->setPosition(Vector3d(x, y, 0));
tile_layer_go->addComponent(sprite_comp);
}
}
}
// Make GameObjects
for (int i = 0; i < map->GetNumObjectGroups(); ++i)
{
const Tmx::ObjectGroup* obj_grp = map->GetObjectGroup(i);
if (not obj_grp->IsVisible()) continue;
for (int j = 0; j < obj_grp->GetNumObjects(); ++j)
{
TmxObjectTypeFactory::makeObject(map, i, j);
}
}
m_post_init(map);
delete map;
};
}
TmxScene::TmxScene(const std::string& scene_name, const std::string& file_name, std::function<void(const Tmx::Map*)>& post_init):
TmxScene(scene_name, file_name, std::function<void(const Tmx::Map*)>(post_init))
{
}
TmxScene::~TmxScene()
{
}
<commit_msg>Updated to new tmxparser version<commit_after>#include "TmxScene.h"
using namespace hb;
TmxScene::TmxScene(const std::string& scene_name, const std::string& file_name, std::function<void(const Tmx::Map*)>&& post_init):
Game::Scene(scene_name, [](){}),
m_post_init(std::move(post_init))
{
HB_CHECK_TMXPARSER_VERSION();
m_init = [this, file_name]()
{
Tmx::Map* map = new Tmx::Map();
map->ParseFile(file_name);
if (map->HasError())
{
hb_log("error code: " << map->GetErrorCode() << std::endl);
hb_log("error text: " << map->GetErrorText().c_str() << std::endl);
std::exit(map->GetErrorCode());
}
int last_slash = file_name.find_last_of("/");
std::string path = file_name.substr(0, last_slash +1);
std::string c = map->GetBackgroundColor();
if (c.size() != 0)
{
int r = std::stoul(c.substr(1,2), nullptr, 16);
int g = std::stoul(c.substr(3,2), nullptr, 16);
int b = std::stoul(c.substr(5,2), nullptr, 16);
Color color(r, g, b);
Renderer::setClearColor(color);
}
if (map->GetOrientation() == Tmx::TMX_MO_ORTHOGONAL)
{
Renderer::getCamera().setAxisX(Vector3d(map->GetTileWidth(), 0, 0));
Renderer::getCamera().setAxisY(Vector3d(0, map->GetTileHeight(), 0));
Renderer::getCamera().setAxisZ(Vector3d(0, 0, 1));
}
else if (map->GetOrientation() == Tmx::TMX_MO_ISOMETRIC)
{
Renderer::getCamera().setAxisX(Vector3d(map->GetTileWidth(), map->GetTileHeight(), map->GetTileHeight()));
Renderer::getCamera().setAxisY(Vector3d(-map->GetTileWidth(), map->GetTileHeight(), map->GetTileHeight()));
Renderer::getCamera().setAxisZ(Vector3d(0, 0, 1));
}
GameObject::setNextGameObjectId(map->GetNextObjectId());
// Make Image layers
for (int i = 0; i < map->GetNumImageLayers(); ++i)
{
const Tmx::ImageLayer* layer = map->GetImageLayer(i);
if (not layer->IsVisible()) continue;
GameObject *image_layer_go = new GameObject();
image_layer_go->setName(layer->GetName());
image_layer_go->setPosition(Vector3d(layer->GetX()/map->GetTileWidth(), layer->GetY()/map->GetTileHeight(), layer->GetZOrder()));
Texture tex = Texture::loadFromFile(path + layer->GetImage()->GetSource(), Rect(0, 0, layer->GetImage()->GetWidth(), layer->GetImage()->GetHeight()));
Sprite sprite = Sprite(tex);
auto sprite_comp = new SpriteComponent(sprite);
image_layer_go->addComponent(sprite_comp);
}
// Make tile layers
for (int i = 0; i < map->GetNumTileLayers(); ++i)
{
const Tmx::TileLayer* layer = map->GetTileLayer(i);
if (not layer->IsVisible()) continue;
GameObject *tile_layer_go = new GameObject();
tile_layer_go->setName(layer->GetName());
tile_layer_go->setPosition(Vector3d(0, 0, layer->GetZOrder()));
for (int y = 0; y < layer->GetHeight(); ++y)
{
for (int x = 0; x < layer->GetWidth(); ++x)
{
if (layer->GetTileTilesetIndex(x, y) == -1) continue;
int gid = layer->GetTileGid(x, y);
const Tmx::Tileset *tileset = map->FindTileset(gid);
int lid = gid - tileset->GetFirstGid();
std::vector<int> anim;
Time t_anim = Time::seconds(0);
const Tmx::Tile* tile = tileset->GetTile(lid);
if (tile->IsAnimated())
{
t_anim = Time::milliseconds(tile->GetTotalDuration() / tile->GetFrameCount());
for (auto anim_frame : tile->GetFrames())
{
anim.push_back(anim_frame.GetTileID());
}
}
else
{
anim.push_back(lid);
}
Texture tex = Texture::loadFromFile(path + tileset->GetImage()->GetSource(), Rect(0, 0, tileset->GetImage()->GetWidth(), tileset->GetImage()->GetHeight()));
Sprite sprite = Sprite(tex, Vector2d(tileset->GetTileWidth(), tileset->GetTileHeight()), Vector2d(tileset->GetMargin(), tileset->GetMargin()));
auto sprite_comp = new SpriteComponent(sprite, anim, t_anim);
sprite_comp->setPosition(Vector3d(x, y, 0));
tile_layer_go->addComponent(sprite_comp);
}
}
}
// Make GameObjects
for (int i = 0; i < map->GetNumObjectGroups(); ++i)
{
const Tmx::ObjectGroup* obj_grp = map->GetObjectGroup(i);
if (not obj_grp->IsVisible()) continue;
for (int j = 0; j < obj_grp->GetNumObjects(); ++j)
{
TmxObjectTypeFactory::makeObject(map, i, j);
}
}
m_post_init(map);
delete map;
};
}
TmxScene::TmxScene(const std::string& scene_name, const std::string& file_name, std::function<void(const Tmx::Map*)>& post_init):
TmxScene(scene_name, file_name, std::function<void(const Tmx::Map*)>(post_init))
{
}
TmxScene::~TmxScene()
{
}
<|endoftext|>
|
<commit_before>#pragma once
#include <array>
#include <cmath>
#include <string>
#include <memory>
#include <typeinfo>
#include <typeindex>
#include "./debugger.hpp"
namespace darwin {
enum class status {
null,ready,busy,leisure,error
};
enum class results {
null,success,failure
};
enum class colors {
white,black,red,green,blue,pink,yellow,cyan
};
enum class attris {
bright,underline
};
enum class commands {
echo_on,echo_off,reset_cursor,reset_attri,clrscr
};
class pixel final {
char mChar=' ';
std::array<bool,2> mAttris= {{false,false}};
std::array<colors,2> mColors= {{colors::white,colors::black}};
public:
pixel()=default;
pixel(const pixel&)=default;
pixel(char ch,bool bright,bool underline,colors fcolor,colors bcolor):mChar(ch),mAttris( {
bright,underline
}),mColors({fcolor,bcolor}) {}
~pixel()=default;
void set_char(char c) {
mChar=c;
}
char get_char() const {
return mChar;
}
void set_front_color(colors c) {
mColors[0]=c;
}
colors get_front_color() const {
return mColors[0];
}
void set_back_color(colors c) {
mColors[1]=c;
}
colors get_back_color() const {
return mColors[1];
}
void set_colors(const std::array<colors,2>& c) {
mColors=c;
}
const std::array<colors,2>& get_colors() const {
return mColors;
}
void set_bright(bool value) {
mAttris[0]=value;
}
bool is_bright() const {
return mAttris[0];
}
void set_underline(bool value) {
mAttris[1]=value;
}
bool is_underline() const {
return mAttris[1];
}
void set_attris(const std::array<bool,2>& a) {
mAttris=a;
}
const std::array<bool,2>& get_attris() const {
return mAttris;
}
};
class drawable {
public:
static double draw_line_precision;
drawable()=default;
drawable(const drawable&)=default;
virtual ~drawable()=default;
virtual std::type_index get_type() const final {
return typeid(*this);
}
virtual std::shared_ptr<drawable> clone() noexcept {
return nullptr;
}
virtual bool usable() const noexcept=0;
virtual void clear()=0;
virtual void fill(const pixel&)=0;
virtual void resize(std::size_t,std::size_t)=0;
virtual std::size_t get_width() const=0;
virtual std::size_t get_height() const=0;
virtual const pixel& get_pixel(std::size_t,std::size_t) const=0;
virtual void draw_pixel(int,int,const pixel&)=0;
virtual void draw_line(int p0x,int p0y,int p1x,int p1y,const pixel& pix) {
if(!this->usable())
Darwin_Error("Use of not available object.");
if(p0x<0||p0y<0||p1x<0||p1y<0||p0x>this->get_width()-1||p0y>this->get_height()-1||p1x>this->get_width()-1||p1y>this->get_height()-1)
Darwin_Warning("Out of range.");
long w(p1x-p0x),h(p1y-p0y);
double distance(std::sqrt(std::pow(w,2)+std::pow(h,2))*draw_line_precision);
for(double c=0; c<=1; c+=1.0/distance)
this->draw_pixel(static_cast<int>(p0x+w*c),static_cast<int>(p0y+h*c),pix);
this->draw_pixel(p0x,p0y,pix);
this->draw_pixel(p1x,p1y,pix);
}
virtual void draw_rect(int x,int y,int w,int h,const pixel& pix) {
if(!this->usable())
Darwin_Error("Use of not available object.");
if(x<0||y<0||x>this->get_width()-1||y>this->get_height()-1||x+w>this->get_width()||y+h>this->get_height())
Darwin_Warning("Out of range.");
for(int i=0;i<w;w>0?++i:--i)
{
this->draw_pixel(x+i,y,pix);
this->draw_pixel(x+i,y+h-1,pix);
}
for(int i=1;i<h-1;h>0?++i:--i)
{
this->draw_pixel(x,y+i,pix);
this->draw_pixel(x+w-1,y+i,pix);
}
}
virtual void fill_rect(int x,int y,int w,int h,const pixel& pix) {
if(!this->usable())
Darwin_Error("Use of not available object.");
if(x<0||y<0||x>this->get_width()-1||y>this->get_height()-1||x+w>this->get_width()||y+h>this->get_height())
Darwin_Warning("Out of range.");
for(int cy=0;cy<h;h>0?++cy:--cy)
for(int cx=0;cx<w;w>0?++cx:--cx)
this->draw_pixel(x+cx,y+cy,pix);
}
virtual void draw_string(int x,int y,const std::string& str,const pixel& pix)
{
if(!this->usable())
Darwin_Error("Use of not available object.");
if(x<0||y<0||x>this->get_width()-1||y>this->get_height()-1||x+str.size()>this->get_width())
Darwin_Warning("Out of range.");
pixel p=pix;
for(int i=0;i<str.size();++i)
{
p.set_char(str.at(i));
this->draw_pixel(x+i,y,p);
}
}
virtual void draw_picture(int col,int row,const drawable& pic) {
if(!this->usable()||!pic.usable())
Darwin_Error("Use of not available object.");
if(col<0||row<0||col>this->get_width()-1||row>this->get_height()-1)
Darwin_Warning("Out of range.");
int y0(row>=0?row:0),y1(row>=0?0:-row);
while(y0<this->get_height()&&y1<pic.get_height()) {
int x0(col>=0?col:0),x1(col>=0?0:-col);
while(x0<this->get_width()&&x1<pic.get_width()) {
this->draw_pixel(x0,y0,pic.get_pixel(x1,y1));
++x0;
++x1;
}
++y0;
++y1;
}
}
};
double drawable::draw_line_precision=1.5;
}<commit_msg>增加三角形填充<commit_after>#pragma once
#include <array>
#include <cmath>
#include <string>
#include <memory>
#include <typeinfo>
#include <typeindex>
#include "./debugger.hpp"
namespace darwin {
enum class status {
null,ready,busy,leisure,error
};
enum class results {
null,success,failure
};
enum class colors {
white,black,red,green,blue,pink,yellow,cyan
};
enum class attris {
bright,underline
};
enum class commands {
echo_on,echo_off,reset_cursor,reset_attri,clrscr
};
class pixel final {
char mChar=' ';
std::array<bool,2> mAttris= {{false,false}};
std::array<colors,2> mColors= {{colors::white,colors::black}};
public:
pixel()=default;
pixel(const pixel&)=default;
pixel(char ch,bool bright,bool underline,colors fcolor,colors bcolor):mChar(ch),mAttris( {
bright,underline
}),mColors({fcolor,bcolor}) {}
~pixel()=default;
void set_char(char c) {
mChar=c;
}
char get_char() const {
return mChar;
}
void set_front_color(colors c) {
mColors[0]=c;
}
colors get_front_color() const {
return mColors[0];
}
void set_back_color(colors c) {
mColors[1]=c;
}
colors get_back_color() const {
return mColors[1];
}
void set_colors(const std::array<colors,2>& c) {
mColors=c;
}
const std::array<colors,2>& get_colors() const {
return mColors;
}
void set_bright(bool value) {
mAttris[0]=value;
}
bool is_bright() const {
return mAttris[0];
}
void set_underline(bool value) {
mAttris[1]=value;
}
bool is_underline() const {
return mAttris[1];
}
void set_attris(const std::array<bool,2>& a) {
mAttris=a;
}
const std::array<bool,2>& get_attris() const {
return mAttris;
}
};
class drawable {
public:
static double draw_line_precision;
drawable()=default;
drawable(const drawable&)=default;
virtual ~drawable()=default;
virtual std::type_index get_type() const final {
return typeid(*this);
}
virtual std::shared_ptr<drawable> clone() noexcept {
return nullptr;
}
virtual bool usable() const noexcept=0;
virtual void clear()=0;
virtual void fill(const pixel&)=0;
virtual void resize(std::size_t,std::size_t)=0;
virtual std::size_t get_width() const=0;
virtual std::size_t get_height() const=0;
virtual const pixel& get_pixel(std::size_t,std::size_t) const=0;
virtual void draw_pixel(int,int,const pixel&)=0;
virtual void draw_line(int p0x,int p0y,int p1x,int p1y,const pixel& pix) {
if(!this->usable())
Darwin_Error("Use of not available object.");
if(p0x<0||p0y<0||p1x<0||p1y<0||p0x>this->get_width()-1||p0y>this->get_height()-1||p1x>this->get_width()-1||p1y>this->get_height()-1)
Darwin_Warning("Out of range.");
long w(p1x-p0x),h(p1y-p0y);
double distance(std::sqrt(std::pow(w,2)+std::pow(h,2))*draw_line_precision);
for(double c=0; c<=1; c+=1.0/distance)
this->draw_pixel(static_cast<int>(p0x+w*c),static_cast<int>(p0y+h*c),pix);
this->draw_pixel(p0x,p0y,pix);
this->draw_pixel(p1x,p1y,pix);
}
virtual void draw_rect(int x,int y,int w,int h,const pixel& pix) {
if(!this->usable())
Darwin_Error("Use of not available object.");
if(x<0||y<0||x>this->get_width()-1||y>this->get_height()-1||x+w>this->get_width()||y+h>this->get_height())
Darwin_Warning("Out of range.");
for(int i=0;i<w;w>0?++i:--i)
{
this->draw_pixel(x+i,y,pix);
this->draw_pixel(x+i,y+h-1,pix);
}
for(int i=1;i<h-1;h>0?++i:--i)
{
this->draw_pixel(x,y+i,pix);
this->draw_pixel(x+w-1,y+i,pix);
}
}
virtual void fill_rect(int x,int y,int w,int h,const pixel& pix) {
if(!this->usable())
Darwin_Error("Use of not available object.");
if(x<0||y<0||x>this->get_width()-1||y>this->get_height()-1||x+w>this->get_width()||y+h>this->get_height())
Darwin_Warning("Out of range.");
for(int cy=0;cy<h;h>0?++cy:--cy)
for(int cx=0;cx<w;w>0?++cx:--cx)
this->draw_pixel(x+cx,y+cy,pix);
}
virtual void fill_triangle(int x1,int y1,int x2,int y2,int x3,int y3,const pixel& pix)
{
if(!this->usable())
Darwin_Error("Use of not available object.");
int v1x(x2-x1),v1y(y2-y1),v2x(x3-x2),v2y(y3-y2);
if(v1x*v2y-v2x*v1y==0)
Darwin_Error("Three points in a line.");
if(y2<y1)
{
std::swap(y1,y2);
std::swap(x1,x2);
}
if(y3<y2)
{
std::swap(y2,y3);
std::swap(x2,x3);
}
if(y2<y1)
{
std::swap(y1,y2);
std::swap(x1,x2);
}
if(y1==y2)
{
double k1(double(x3-x1)/double(y3-y1)),k2(double(x3-x2)/double(y3-y2));
for(int y=0;y<y3-y2;++y)
this->draw_line(x1+k1*y,y1+y,x2+k2*y,y2+y,pix);
this->draw_pixel(x3,y3,pix);
}else if(y2==y3){
double k1(double(x3-x1)/double(y3-y1)),k2(double(x2-x1)/double(y2-y1));
for(int y=1;y<=y2-y1;++y)
this->draw_line(x1+k1*y,y1+y,x1+k2*y,y1+y,pix);
this->draw_pixel(x1,y1,pix);
}else{
double k1(double(x3-x1)/double(y3-y1)),k2(double(x3-x2)/double(y3-y2)),k3(double(x2-x1)/double(y2-y1));
for(int y=1;y<y3-y1;++y)
{
if(y<y2-y1)
this->draw_line(x1+k1*y,y1+y,x1+k3*y,y1+y,pix);
else
this->draw_line(x1+k1*y,y1+y,x2+k2*(y-y2),y1+y,pix);
}
this->draw_pixel(x3,y3,pix);
}
}
virtual void draw_string(int x,int y,const std::string& str,const pixel& pix)
{
if(!this->usable())
Darwin_Error("Use of not available object.");
if(x<0||y<0||x>this->get_width()-1||y>this->get_height()-1||x+str.size()>this->get_width())
Darwin_Warning("Out of range.");
pixel p=pix;
for(int i=0;i<str.size();++i)
{
p.set_char(str.at(i));
this->draw_pixel(x+i,y,p);
}
}
virtual void draw_picture(int col,int row,const drawable& pic) {
if(!this->usable()||!pic.usable())
Darwin_Error("Use of not available object.");
if(col<0||row<0||col>this->get_width()-1||row>this->get_height()-1)
Darwin_Warning("Out of range.");
int y0(row>=0?row:0),y1(row>=0?0:-row);
while(y0<this->get_height()&&y1<pic.get_height()) {
int x0(col>=0?col:0),x1(col>=0?0:-col);
while(x0<this->get_width()&&x1<pic.get_width()) {
this->draw_pixel(x0,y0,pic.get_pixel(x1,y1));
++x0;
++x1;
}
++y0;
++y1;
}
}
};
double drawable::draw_line_precision=1.5;
}<|endoftext|>
|
<commit_before>/*
* File: TopologyOracle.hpp
* Author: manuhalo
*
* Created on 25 giugno 2012, 10.36
*/
#ifndef TOPOLOGYORACLE_HPP
#define TOPOLOGYORACLE_HPP
#include "Topology.hpp"
#include "SimTimeInterval.hpp"
#include "zipf_distribution.hpp"
#include <fstream>
#include "Cache.hpp"
// % of requests taking places at a give hour, starting from midnight
const double usrPctgByHour[] = {
4, 2, 1.5, 1.5, 1, 0.5, 0.5, 1, 1, 1.5, 2, 2.5, 3, 4, 4.5, 4.5, 4, 4, 4, 6, 12, 15, 12, 8
//0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23
};
// weight of the days of the week when determining request scheduling (M->S)
const double dayWeights[] = {0.8, 0.9, 1, 0.8, 1.2, 1.3, 1.2};
// M T W T F S S
const double sessionLength[] = {0.1, 0.2, 0.3, 0.4, 0.5, 0.6, 0.7, 0.8, 0.9, 1,
1, 1, 1, 1, 1, 1, 1, 1}; // 50% linear zapping, 50% entire content
/* Switching to a linear session length, this will no longer be used
// average session length (percentage) for the 0-25% quartile (most popular)
const double sessionLength1Q[] = {0.18, 0.20, 0.23, 0.27, 0.30, 0.32, 0.39, 0.48, 0.57, 0.70};
// average session length (percentage) for the 25-50% quartile
const double sessionLength2Q[] = {0.19, 0.21, 0.29, 0.33, 0.36, 0.45, 0.54, 0.59, 0.63, 0.70};
// average session length (percentage) for the 50-75% quartile
const double sessionLength3Q[] = {0.20, 0.30, 0.35, 0.42, 0.49, 0.53, 0.57, 0.59, 0.63, 0.80};
// average session length (percentage) for the 75-100% quartile (least popular)
const double sessionLength4Q[] = {0.20, 0.30, 0.33, 0.37, 0.43, 0.49, 0.56, 0.60, 0.65, 0.81};
*/
typedef Cache<ContentElement*, Capacity, SimTime> ContentCache;
typedef std::map<ContentElement*, std::set<PonUser> > ContentMap;
typedef std::map<uint, ContentMap> AsidContentMap;
typedef std::map<PonUser, ContentCache> UserCacheMap;
typedef std::map<Vertex, ContentCache> LocalCacheMap;
typedef std::map<PonUser, SimTimeInterval*> UserViewMap;
struct FlowStats {
std::vector<double> avgFlowDuration;
std::vector<double> avgPeerFlowDuration;
std::vector<double> avgCacheFlowDuration;
std::vector<float> avgUserCacheOccupancy;
std::vector<float> avgASCacheOccupancy;
std::vector<uint> servedRequests;
std::vector<uint> localRequests;
std::vector<uint> completedRequests;
std::vector<uint> fromASCache;
std::vector<uint> fromPeers;
std::vector<uint> fromCentralServer;
std::vector<uint> congestionBlocked;
};
/* The TopologyOracle keeps track of what everyone is caching and uses that
* information to match requesters to sources with the appropriate content.
* Essentially it serves as a global tracker (in the BitTorrent sense).
* We keep both a map of all the user caching a particular content (to fetch
* potential sources quickly) and a map of what each individual user is caching
* (to be able to simulate finite-size caching).
*/
class TopologyOracle{
protected:
SimMode mode; // VoD or IPTV
uint contentNum; // # of contents in the catalog
double avgContentLength; //average content length in minutes
double devContentLength; // std deviation of content length
double avgHoursPerUser; // hours of viewing per user per round
uint bitrate; // bitrate of the encoded content in Mbps
Topology* topo;
AsidContentMap* asidContentMap; // keeps track of content available in each AS
UserCacheMap* userCacheMap; // keeps track of content available at each user
LocalCacheMap* localCacheMap; // keeps track of content available in each CDN cache
uint ponCardinality; // users per PON
CachePolicy policy; // cache content replacement policy
uint maxCacheSize;
uint maxLocCacheSize;
FlowStats flowStats;
bool reducedCaching; // if true, use only a single CDN in the core;
// if false, one CDN micro cache in each AS
bool preCaching; // if true, AS caches are pre-filled with popular content and never updated
uint maxUploads; // max number of concurrent uploads for the optimization problem
/* the following map associates to each content the expected number of concurrent
* uploads that the oracle expects at a given time. How to populate in a sensible
* way is something I am still to figure out.
*/
std::map<ContentElement*, double> contentRateMap;
public:
TopologyOracle(Topology* topo, po::variables_map vm);
~TopologyOracle();
bool serveRequest(Flow* flow, Scheduler* scheduler);
void addToCache(PonUser user, ContentElement* content,
Capacity sizeDownloaded, SimTime time);
void clearUserCache();
void clearLocalCache();
std::set<PonUser> getSources(ContentElement* content, uint asid);
void notifyCompletedFlow(Flow* flow, Scheduler* scheduler);
void notifyEndRound(uint endingRound);
// this is a hack and should be removed
Topology* getTopology() {return topo;}
void printStats(uint currentRound);
void addContent(ContentElement* content);
void removeContent(ContentElement* content);
bool checkIfCached(PonUser user, ContentElement* content, Capacity sizeRequested);
bool checkIfCached(Vertex lCache, ContentElement* content, Capacity sizeRequested);
void getFromLocalCache(Vertex lCache, ContentElement* content, SimTime time);
void removeFromCMap(ContentElement* content, PonUser user);
/* optimizeCaching implements the optimal caching algorithm to minimize storage
* space while keeping high level of locality, by ensuring that some minimal
* number of replicas are always available. Replicas are determined based on
* popularity estimation (to be implemented). the function should be called
* before adding elements to the cache, as it determines whether or not the
* new element is worth storing and which elements should be erased to make
* space for it. It returns a pair of bool, the first of which tells whether
* the optimization was successful (i.e., a valid solution was found), and the
* second telling whether the requested element should be cached. The second
* boolean value should only be taken into consideration if the first is true.
*/
std::pair<bool, bool> optimizeCaching(PonUser user, ContentElement* content,
Capacity sizeRequested);
void takeSnapshot(SimTime time, uint round) const {
this->topo->printTopology(time, round);
}
FlowStats getFlowStats() const {
return this->flowStats;
}
// The next methods are virtualized so that VoD and IPTV can reimplement them
/* generateUserViewMap() generates content requests for all the elements
* of the catalog for the current round, then schedules those requests as flows
* in the scheduler.
*/
virtual void generateUserViewMap(Scheduler* scheduler) = 0;
/* populateCatalog() instantiates the ContentElement that compose the catalog
* and stores them in an appropriate data structure.
*/
virtual void populateCatalog() = 0;
/* updateCatalog() performs general maintenance on the catalog at the end of
* a round (e.g. removing expired content, generating new one etc.)
*/
virtual void updateCatalog(uint currentRound) = 0;
/* generateNewRequest() is a legacy method that generates a single request for
* a specific user. It's only used in the IPTV model and it's being kept
* for "backward compatibility". It should be removed in the future.
*/
virtual void generateNewRequest(PonUser user, SimTime time,
Scheduler* scheduler) = 0;
/* preCache() pushes the most popular content in the AS caches. It must be
* ovveridden by the specialized classes as determining the most popular
* elements of the catalog depends on the simulation mode
*/
virtual void preCache() = 0;
};
#endif /* TOPOLOGYORACLE_HPP */
<commit_msg>optimizeCaching() now requires the current simulation time to extrapolate the current hour for rate calculation purposes<commit_after>/*
* File: TopologyOracle.hpp
* Author: manuhalo
*
* Created on 25 giugno 2012, 10.36
*/
#ifndef TOPOLOGYORACLE_HPP
#define TOPOLOGYORACLE_HPP
#include "Topology.hpp"
#include "SimTimeInterval.hpp"
#include "zipf_distribution.hpp"
#include <fstream>
#include "Cache.hpp"
// % of requests taking places at a give hour, starting from midnight
const std::vector<double> usrPctgByHour = {
4, 2, 1.5, 1.5, 1, 0.5, 0.5, 1, 1, 1.5, 2, 2.5, 3, 4, 4.5, 4.5, 4, 4, 4, 6, 12, 15, 12, 8
//0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23
};
// weight of the days of the week when determining request scheduling (M->S)
const double dayWeights[] = {0.8, 0.9, 1, 0.8, 1.2, 1.3, 1.2};
// M T W T F S S
const std::vector<double> sessionLength = {0.1, 0.2, 0.3, 0.4, 0.5, 0.6, 0.7, 0.8, 0.9, 1,
1, 1, 1, 1, 1, 1, 1, 1}; // 50% linear zapping, 50% entire content
/* Switching to a linear session length, this will no longer be used
// average session length (percentage) for the 0-25% quartile (most popular)
const double sessionLength1Q[] = {0.18, 0.20, 0.23, 0.27, 0.30, 0.32, 0.39, 0.48, 0.57, 0.70};
// average session length (percentage) for the 25-50% quartile
const double sessionLength2Q[] = {0.19, 0.21, 0.29, 0.33, 0.36, 0.45, 0.54, 0.59, 0.63, 0.70};
// average session length (percentage) for the 50-75% quartile
const double sessionLength3Q[] = {0.20, 0.30, 0.35, 0.42, 0.49, 0.53, 0.57, 0.59, 0.63, 0.80};
// average session length (percentage) for the 75-100% quartile (least popular)
const double sessionLength4Q[] = {0.20, 0.30, 0.33, 0.37, 0.43, 0.49, 0.56, 0.60, 0.65, 0.81};
*/
typedef Cache<ContentElement*, Capacity, SimTime> ContentCache;
typedef std::map<ContentElement*, std::set<PonUser> > ContentMap;
typedef std::map<uint, ContentMap> AsidContentMap;
typedef std::map<PonUser, ContentCache> UserCacheMap;
typedef std::map<Vertex, ContentCache> LocalCacheMap;
typedef std::map<PonUser, SimTimeInterval*> UserViewMap;
struct FlowStats {
std::vector<double> avgFlowDuration;
std::vector<double> avgPeerFlowDuration;
std::vector<double> avgCacheFlowDuration;
std::vector<float> avgUserCacheOccupancy;
std::vector<float> avgASCacheOccupancy;
std::vector<uint> servedRequests;
std::vector<uint> localRequests;
std::vector<uint> completedRequests;
std::vector<uint> fromASCache;
std::vector<uint> fromPeers;
std::vector<uint> fromCentralServer;
std::vector<uint> congestionBlocked;
};
/* The TopologyOracle keeps track of what everyone is caching and uses that
* information to match requesters to sources with the appropriate content.
* Essentially it serves as a global tracker (in the BitTorrent sense).
* We keep both a map of all the user caching a particular content (to fetch
* potential sources quickly) and a map of what each individual user is caching
* (to be able to simulate finite-size caching).
*/
class TopologyOracle{
protected:
SimMode mode; // VoD or IPTV
uint contentNum; // # of contents in the catalog
double avgContentLength; //average content length in minutes
double devContentLength; // std deviation of content length
double avgHoursPerUser; // hours of viewing per user per round
double avgReqLength; // derivative, but useful for the popularity estimation
uint bitrate; // bitrate of the encoded content in Mbps
Topology* topo;
AsidContentMap* asidContentMap; // keeps track of content available in each AS
UserCacheMap* userCacheMap; // keeps track of content available at each user
LocalCacheMap* localCacheMap; // keeps track of content available in each CDN cache
uint ponCardinality; // users per PON
CachePolicy policy; // cache content replacement policy
uint maxCacheSize;
uint maxLocCacheSize;
FlowStats flowStats;
bool reducedCaching; // if true, use only a single CDN in the core;
// if false, one CDN micro cache in each AS
bool preCaching; // if true, AS caches are pre-filled with popular content and never updated
uint maxUploads; // max number of concurrent uploads for the optimization problem
/* the following map associates to each content the expected number of concurrent
* uploads that the oracle expects per user per day.
*/
std::map<ContentElement*, double> contentRateMap;
public:
TopologyOracle(Topology* topo, po::variables_map vm);
~TopologyOracle();
bool serveRequest(Flow* flow, Scheduler* scheduler);
void addToCache(PonUser user, ContentElement* content,
Capacity sizeDownloaded, SimTime time);
void clearUserCache();
void clearLocalCache();
std::set<PonUser> getSources(ContentElement* content, uint asid);
void notifyCompletedFlow(Flow* flow, Scheduler* scheduler);
void notifyEndRound(uint endingRound);
// this is a hack and should be removed
Topology* getTopology() {return topo;}
void printStats(uint currentRound);
void addContent(ContentElement* content);
void removeContent(ContentElement* content);
bool checkIfCached(PonUser user, ContentElement* content, Capacity sizeRequested);
bool checkIfCached(Vertex lCache, ContentElement* content, Capacity sizeRequested);
void getFromLocalCache(Vertex lCache, ContentElement* content, SimTime time);
void removeFromCMap(ContentElement* content, PonUser user);
/* optimizeCaching implements the optimal caching algorithm to minimize storage
* space while keeping high level of locality, by ensuring that some minimal
* number of replicas are always available. Replicas are determined based on
* popularity estimation (to be implemented). the function should be called
* before adding elements to the cache, as it determines whether or not the
* new element is worth storing and which elements should be erased to make
* space for it. It returns a pair of bool, the first of which tells whether
* the optimization was successful (i.e., a valid solution was found), and the
* second telling whether the requested element should be cached. The second
* boolean value should only be taken into consideration if the first is true.
*/
std::pair<bool, bool> optimizeCaching(PonUser user, ContentElement* content,
Capacity sizeRequested, SimTime time);
void takeSnapshot(SimTime time, uint round) const {
this->topo->printTopology(time, round);
}
FlowStats getFlowStats() const {
return this->flowStats;
}
// The next methods are virtualized so that VoD and IPTV can reimplement them
/* generateUserViewMap() generates content requests for all the elements
* of the catalog for the current round, then schedules those requests as flows
* in the scheduler.
*/
virtual void generateUserViewMap(Scheduler* scheduler) = 0;
/* populateCatalog() instantiates the ContentElement that compose the catalog
* and stores them in an appropriate data structure.
*/
virtual void populateCatalog() = 0;
/* updateCatalog() performs general maintenance on the catalog at the end of
* a round (e.g. removing expired content, generating new one etc.)
*/
virtual void updateCatalog(uint currentRound) = 0;
/* generateNewRequest() is a legacy method that generates a single request for
* a specific user. It's only used in the IPTV model and it's being kept
* for "backward compatibility". It should be removed in the future.
*/
virtual void generateNewRequest(PonUser user, SimTime time,
Scheduler* scheduler) = 0;
/* preCache() pushes the most popular content in the AS caches. It must be
* ovveridden by the specialized classes as determining the most popular
* elements of the catalog depends on the simulation mode
*/
virtual void preCache() = 0;
};
#endif /* TOPOLOGYORACLE_HPP */
<|endoftext|>
|
<commit_before>// Begin CVS Header
// $Source: /Volumes/Home/Users/shoops/cvs/copasi_dev/copasi/UI/CQCopasiApplication.cpp,v $
// $Revision: 1.1 $
// $Name: $
// $Author: shoops $
// $Date: 2012/02/22 16:28:45 $
// End CVS Header
// Copyright (C) 2011 by Pedro Mendes, Virginia Tech Intellectual
// Properties, Inc., University of Heidelberg, and The University
// of Manchester.
// All rights reserved.
#include <QFileOpenEvent>
#include <QString>
#include "CQCopasiApplication.h"
#include "copasiui3window.h"
#include "listviews.h"
CQCopasiApplication::CQCopasiApplication(int & argc, char ** argv):
QApplication(argc, argv),
mpMainWindow(NULL),
mFile(),
mStarting(true)
{}
CQCopasiApplication::~CQCopasiApplication()
{}
// virtual
bool CQCopasiApplication::event(QEvent * pEvent)
{
switch (pEvent->type())
{
case QEvent::FileOpen:
if (mStarting)
{
mFile = static_cast<QFileOpenEvent *>(pEvent)->file();
}
else
{
mpMainWindow->slotFileOpen(mFile);
}
pEvent->accept();
return true;
break;
default:
break;
}
return QApplication::event(pEvent);
}
void CQCopasiApplication::setMainWindow(CopasiUI3Window * pMainWindow)
{
mpMainWindow = pMainWindow;
processEvents();
mpMainWindow->openInitialDocument(mFile);
mStarting = false;
}
<commit_msg>- the file open event on mac needs to open new files (otherwise whenever another file is double clicked, the first file will be reloaded)<commit_after>// Begin CVS Header
// $Source: /Volumes/Home/Users/shoops/cvs/copasi_dev/copasi/UI/CQCopasiApplication.cpp,v $
// $Revision: 1.1 $
// $Name: $
// $Author: shoops $
// $Date: 2012/02/22 16:28:45 $
// End CVS Header
// Copyright (C) 2011 by Pedro Mendes, Virginia Tech Intellectual
// Properties, Inc., University of Heidelberg, and The University
// of Manchester.
// All rights reserved.
#include <QFileOpenEvent>
#include <QString>
#include "CQCopasiApplication.h"
#include "copasiui3window.h"
#include "listviews.h"
CQCopasiApplication::CQCopasiApplication(int & argc, char ** argv):
QApplication(argc, argv),
mpMainWindow(NULL),
mFile(),
mStarting(true)
{}
CQCopasiApplication::~CQCopasiApplication()
{}
// virtual
bool CQCopasiApplication::event(QEvent * pEvent)
{
switch (pEvent->type())
{
case QEvent::FileOpen:
if (mStarting)
{
mFile = static_cast<QFileOpenEvent *>(pEvent)->file();
}
else
{
// need to take the new file, otherwise whenever the application
// is open we will re-open the first file that was supposed to be
// opened.
mFile = static_cast<QFileOpenEvent *>(pEvent)->file();
mpMainWindow->slotFileOpen(mFile);
}
pEvent->accept();
return true;
break;
default:
break;
}
return QApplication::event(pEvent);
}
void CQCopasiApplication::setMainWindow(CopasiUI3Window * pMainWindow)
{
mpMainWindow = pMainWindow;
processEvents();
mpMainWindow->openInitialDocument(mFile);
mStarting = false;
}
<|endoftext|>
|
<commit_before>/*************************************************************************/
/* translation_loader_po.cpp */
/*************************************************************************/
/* This file is part of: */
/* GODOT ENGINE */
/* https://godotengine.org */
/*************************************************************************/
/* Copyright (c) 2007-2020 Juan Linietsky, Ariel Manzur. */
/* Copyright (c) 2014-2020 Godot Engine contributors (cf. AUTHORS.md). */
/* */
/* 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 "translation_loader_po.h"
#include "core/os/file_access.h"
#include "core/translation.h"
RES TranslationLoaderPO::load_translation(FileAccess *f, Error *r_error) {
enum Status {
STATUS_NONE,
STATUS_READING_ID,
STATUS_READING_STRING,
};
Status status = STATUS_NONE;
String msg_id;
String msg_str;
String config;
if (r_error) {
*r_error = ERR_FILE_CORRUPT;
}
Ref<Translation> translation = Ref<Translation>(memnew(Translation));
int line = 1;
bool skip_this = false;
bool skip_next = false;
bool is_eof = false;
while (!is_eof) {
String l = f->get_line().strip_edges();
is_eof = f->eof_reached();
// If we reached last line and it's not a content line, break, otherwise let processing that last loop
if (is_eof && l.empty()) {
if (status == STATUS_READING_ID) {
memdelete(f);
ERR_FAIL_V_MSG(RES(), f->get_path() + ":" + itos(line) + " Unexpected EOF while reading 'msgid' at file: ");
} else {
break;
}
}
if (l.begins_with("msgid")) {
if (status == STATUS_READING_ID) {
memdelete(f);
ERR_FAIL_V_MSG(RES(), f->get_path() + ":" + itos(line) + " Unexpected 'msgid', was expecting 'msgstr' while parsing: ");
}
if (msg_id != "") {
if (!skip_this) {
translation->add_message(msg_id, msg_str);
}
} else if (config == "") {
config = msg_str;
}
l = l.substr(5, l.length()).strip_edges();
status = STATUS_READING_ID;
msg_id = "";
msg_str = "";
skip_this = skip_next;
skip_next = false;
}
if (l.begins_with("msgstr")) {
if (status != STATUS_READING_ID) {
memdelete(f);
ERR_FAIL_V_MSG(RES(), f->get_path() + ":" + itos(line) + " Unexpected 'msgstr', was expecting 'msgid' while parsing: ");
}
l = l.substr(6, l.length()).strip_edges();
status = STATUS_READING_STRING;
}
if (l == "" || l.begins_with("#")) {
if (l.find("fuzzy") != -1) {
skip_next = true;
}
line++;
continue; //nothing to read or comment
}
ERR_FAIL_COND_V_MSG(!l.begins_with("\"") || status == STATUS_NONE, RES(), f->get_path() + ":" + itos(line) + " Invalid line '" + l + "' while parsing: ");
l = l.substr(1, l.length());
// Find final quote, ignoring escaped ones (\").
// The escape_next logic is necessary to properly parse things like \\"
// where the blackslash is the one being escaped, not the quote.
int end_pos = -1;
bool escape_next = false;
for (int i = 0; i < l.length(); i++) {
if (l[i] == '\\' && !escape_next) {
escape_next = true;
continue;
}
if (l[i] == '"' && !escape_next) {
end_pos = i;
break;
}
escape_next = false;
}
ERR_FAIL_COND_V_MSG(end_pos == -1, RES(), f->get_path() + ":" + itos(line) + ": Expected '\"' at end of message while parsing file.");
l = l.substr(0, end_pos);
l = l.c_unescape();
if (status == STATUS_READING_ID) {
msg_id += l;
} else {
msg_str += l;
}
line++;
}
f->close();
memdelete(f);
if (status == STATUS_READING_STRING) {
if (msg_id != "") {
if (!skip_this) {
translation->add_message(msg_id, msg_str);
}
} else if (config == "") {
config = msg_str;
}
}
ERR_FAIL_COND_V_MSG(config == "", RES(), "No config found in file: " + f->get_path() + ".");
Vector<String> configs = config.split("\n");
for (int i = 0; i < configs.size(); i++) {
String c = configs[i].strip_edges();
int p = c.find(":");
if (p == -1) {
continue;
}
String prop = c.substr(0, p).strip_edges();
String value = c.substr(p + 1, c.length()).strip_edges();
if (prop == "X-Language" || prop == "Language") {
translation->set_locale(value);
}
}
if (r_error) {
*r_error = OK;
}
return translation;
}
RES TranslationLoaderPO::load(const String &p_path, const String &p_original_path, Error *r_error, bool p_use_sub_threads, float *r_progress, bool p_no_cache) {
if (r_error) {
*r_error = ERR_CANT_OPEN;
}
FileAccess *f = FileAccess::open(p_path, FileAccess::READ);
ERR_FAIL_COND_V_MSG(!f, RES(), "Cannot open file '" + p_path + "'.");
return load_translation(f, r_error);
}
void TranslationLoaderPO::get_recognized_extensions(List<String> *p_extensions) const {
p_extensions->push_back("po");
//p_extensions->push_back("mo"); //mo in the future...
}
bool TranslationLoaderPO::handles_type(const String &p_type) const {
return (p_type == "Translation");
}
String TranslationLoaderPO::get_resource_type(const String &p_path) const {
if (p_path.get_extension().to_lower() == "po") {
return "Translation";
}
return "";
}
<commit_msg>PO loader: Fix unclosed files and error messages<commit_after>/*************************************************************************/
/* translation_loader_po.cpp */
/*************************************************************************/
/* This file is part of: */
/* GODOT ENGINE */
/* https://godotengine.org */
/*************************************************************************/
/* Copyright (c) 2007-2020 Juan Linietsky, Ariel Manzur. */
/* Copyright (c) 2014-2020 Godot Engine contributors (cf. AUTHORS.md). */
/* */
/* 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 "translation_loader_po.h"
#include "core/os/file_access.h"
#include "core/translation.h"
RES TranslationLoaderPO::load_translation(FileAccess *f, Error *r_error) {
enum Status {
STATUS_NONE,
STATUS_READING_ID,
STATUS_READING_STRING,
};
Status status = STATUS_NONE;
String msg_id;
String msg_str;
String config;
if (r_error) {
*r_error = ERR_FILE_CORRUPT;
}
Ref<Translation> translation = Ref<Translation>(memnew(Translation));
int line = 1;
bool skip_this = false;
bool skip_next = false;
bool is_eof = false;
const String path = f->get_path();
while (!is_eof) {
String l = f->get_line().strip_edges();
is_eof = f->eof_reached();
// If we reached last line and it's not a content line, break, otherwise let processing that last loop
if (is_eof && l.empty()) {
if (status == STATUS_READING_ID) {
memdelete(f);
ERR_FAIL_V_MSG(RES(), "Unexpected EOF while reading 'msgid' at: " + path + ":" + itos(line));
} else {
break;
}
}
if (l.begins_with("msgid")) {
if (status == STATUS_READING_ID) {
memdelete(f);
ERR_FAIL_V_MSG(RES(), "Unexpected 'msgid', was expecting 'msgstr' while parsing: " + path + ":" + itos(line));
}
if (msg_id != "") {
if (!skip_this) {
translation->add_message(msg_id, msg_str);
}
} else if (config == "") {
config = msg_str;
}
l = l.substr(5, l.length()).strip_edges();
status = STATUS_READING_ID;
msg_id = "";
msg_str = "";
skip_this = skip_next;
skip_next = false;
}
if (l.begins_with("msgstr")) {
if (status != STATUS_READING_ID) {
memdelete(f);
ERR_FAIL_V_MSG(RES(), "Unexpected 'msgstr', was expecting 'msgid' while parsing: " + path + ":" + itos(line));
}
l = l.substr(6, l.length()).strip_edges();
status = STATUS_READING_STRING;
}
if (l == "" || l.begins_with("#")) {
if (l.find("fuzzy") != -1) {
skip_next = true;
}
line++;
continue; //nothing to read or comment
}
if (!l.begins_with("\"") || status == STATUS_NONE) {
memdelete(f);
ERR_FAIL_V_MSG(RES(), "Invalid line '" + l + "' while parsing: " + path + ":" + itos(line));
}
l = l.substr(1, l.length());
// Find final quote, ignoring escaped ones (\").
// The escape_next logic is necessary to properly parse things like \\"
// where the blackslash is the one being escaped, not the quote.
int end_pos = -1;
bool escape_next = false;
for (int i = 0; i < l.length(); i++) {
if (l[i] == '\\' && !escape_next) {
escape_next = true;
continue;
}
if (l[i] == '"' && !escape_next) {
end_pos = i;
break;
}
escape_next = false;
}
if (end_pos == -1) {
memdelete(f);
ERR_FAIL_V_MSG(RES(), "Expected '\"' at end of message while parsing: " + path + ":" + itos(line));
}
l = l.substr(0, end_pos);
l = l.c_unescape();
if (status == STATUS_READING_ID) {
msg_id += l;
} else {
msg_str += l;
}
line++;
}
memdelete(f);
if (status == STATUS_READING_STRING) {
if (msg_id != "") {
if (!skip_this) {
translation->add_message(msg_id, msg_str);
}
} else if (config == "") {
config = msg_str;
}
}
ERR_FAIL_COND_V_MSG(config == "", RES(), "No config found in file: " + path + ".");
Vector<String> configs = config.split("\n");
for (int i = 0; i < configs.size(); i++) {
String c = configs[i].strip_edges();
int p = c.find(":");
if (p == -1) {
continue;
}
String prop = c.substr(0, p).strip_edges();
String value = c.substr(p + 1, c.length()).strip_edges();
if (prop == "X-Language" || prop == "Language") {
translation->set_locale(value);
}
}
if (r_error) {
*r_error = OK;
}
return translation;
}
RES TranslationLoaderPO::load(const String &p_path, const String &p_original_path, Error *r_error, bool p_use_sub_threads, float *r_progress, bool p_no_cache) {
if (r_error) {
*r_error = ERR_CANT_OPEN;
}
FileAccess *f = FileAccess::open(p_path, FileAccess::READ);
ERR_FAIL_COND_V_MSG(!f, RES(), "Cannot open file '" + p_path + "'.");
return load_translation(f, r_error);
}
void TranslationLoaderPO::get_recognized_extensions(List<String> *p_extensions) const {
p_extensions->push_back("po");
}
bool TranslationLoaderPO::handles_type(const String &p_type) const {
return (p_type == "Translation");
}
String TranslationLoaderPO::get_resource_type(const String &p_path) const {
if (p_path.get_extension().to_lower() == "po") {
return "Translation";
}
return "";
}
<|endoftext|>
|
<commit_before>// Copyright (c) 2017 The PIVX developers
// Distributed under the MIT software license, see the accompanying
// file COPYING or http://www.opensource.org/licenses/mit-license.php.
#include "accumulatormap.h"
#include "accumulators.h"
#include "main.h"
#include "txdb.h"
#include "libzerocoin/Denominations.h"
using namespace libzerocoin;
using namespace std;
AccumulatorMap::AccumulatorMap()
{
//construct accumulators for all denominations
for (auto& denom : zerocoinDenomList) {
unique_ptr<Accumulator> uptr(new Accumulator(Params().Zerocoin_Params(), denom));
mapAccumulators.insert(make_pair(denom, std::move(uptr)));
}
}
void AccumulatorMap::Reset()
{
mapAccumulators.clear();
for (auto& denom : zerocoinDenomList) {
unique_ptr<Accumulator> uptr(new Accumulator(Params().Zerocoin_Params(), denom));
mapAccumulators.insert(make_pair(denom, std::move(uptr)));
}
}
bool AccumulatorMap::Load(uint256 nCheckpoint)
{
for (auto& denom : zerocoinDenomList) {
uint32_t nChecksum = ParseChecksum(nCheckpoint, denom);
CBigNum bnValue;
if (!zerocoinDB->ReadAccumulatorValue(nChecksum, bnValue)) {
LogPrintf("%s : cannot find checksum %d", __func__, nChecksum);
return false;
}
mapAccumulators.at(denom)->setValue(bnValue);
}
return true;
}
bool AccumulatorMap::Accumulate(PublicCoin pubCoin, bool fSkipValidation)
{
CoinDenomination denom = pubCoin.getDenomination();
if (denom == CoinDenomination::ZQ_ERROR)
return false;
if (fSkipValidation)
mapAccumulators.at(denom)->increment(pubCoin.getValue());
else
mapAccumulators.at(denom)->accumulate(pubCoin);
return true;
}
CBigNum AccumulatorMap::GetValue(CoinDenomination denom)
{
if (denom == CoinDenomination::ZQ_ERROR)
return CBigNum(0);
return mapAccumulators.at(denom)->getValue();
}
uint256 AccumulatorMap::GetCheckpoint()
{
uint256 nCheckpoint;
//Prevent possible overflows from future changes to the list and forgetting to update this code
assert(zerocoinDenomList.size() == 8);
for (auto& denom : zerocoinDenomList) {
CBigNum bnValue = mapAccumulators.at(denom)->getValue();
uint32_t nCheckSum = GetChecksum(bnValue);
nCheckpoint = nCheckpoint << 32 | nCheckSum;
}
return nCheckpoint;
}
<commit_msg>Add comments to accumulatormap.cpp.<commit_after>// Copyright (c) 2017 The PIVX developers
// Distributed under the MIT software license, see the accompanying
// file COPYING or http://www.opensource.org/licenses/mit-license.php.
#include "accumulatormap.h"
#include "accumulators.h"
#include "main.h"
#include "txdb.h"
#include "libzerocoin/Denominations.h"
using namespace libzerocoin;
using namespace std;
//Construct accumulators for all denominations
AccumulatorMap::AccumulatorMap()
{
for (auto& denom : zerocoinDenomList) {
unique_ptr<Accumulator> uptr(new Accumulator(Params().Zerocoin_Params(), denom));
mapAccumulators.insert(make_pair(denom, std::move(uptr)));
}
}
//Reset each accumulator to its default state
void AccumulatorMap::Reset()
{
mapAccumulators.clear();
for (auto& denom : zerocoinDenomList) {
unique_ptr<Accumulator> uptr(new Accumulator(Params().Zerocoin_Params(), denom));
mapAccumulators.insert(make_pair(denom, std::move(uptr)));
}
}
//Load a checkpoint containing 8 32bit checksums of accumulator values.
bool AccumulatorMap::Load(uint256 nCheckpoint)
{
for (auto& denom : zerocoinDenomList) {
uint32_t nChecksum = ParseChecksum(nCheckpoint, denom);
CBigNum bnValue;
if (!zerocoinDB->ReadAccumulatorValue(nChecksum, bnValue)) {
LogPrintf("%s : cannot find checksum %d", __func__, nChecksum);
return false;
}
mapAccumulators.at(denom)->setValue(bnValue);
}
return true;
}
//Add a zerocoin to the accumulator of its denomination.
bool AccumulatorMap::Accumulate(PublicCoin pubCoin, bool fSkipValidation)
{
CoinDenomination denom = pubCoin.getDenomination();
if (denom == CoinDenomination::ZQ_ERROR)
return false;
if (fSkipValidation)
mapAccumulators.at(denom)->increment(pubCoin.getValue());
else
mapAccumulators.at(denom)->accumulate(pubCoin);
return true;
}
//Get the value of a specific accumulator
CBigNum AccumulatorMap::GetValue(CoinDenomination denom)
{
if (denom == CoinDenomination::ZQ_ERROR)
return CBigNum(0);
return mapAccumulators.at(denom)->getValue();
}
//Calculate a 32bit checksum of each accumulator value. Concatenate checksums into uint256
uint256 AccumulatorMap::GetCheckpoint()
{
uint256 nCheckpoint;
//Prevent possible overflows from future changes to the list and forgetting to update this code
assert(zerocoinDenomList.size() == 8);
for (auto& denom : zerocoinDenomList) {
CBigNum bnValue = mapAccumulators.at(denom)->getValue();
uint32_t nCheckSum = GetChecksum(bnValue);
nCheckpoint = nCheckpoint << 32 | nCheckSum;
}
return nCheckpoint;
}
<|endoftext|>
|
<commit_before>/*
* Copyright 2016 Nu-book Inc.
* Copyright 2016 ZXing authors
* Copyright 2020 Axel Waggershauser
*
* 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 "ODDataBarReader.h"
#include "ODDataBarCommon.h"
#include "BarcodeFormat.h"
#include "Result.h"
#include "GTIN.h"
#include "TextDecoder.h"
#include <sstream>
#include <iomanip>
#include <unordered_set>
namespace ZXing::OneD {
using namespace DataBar;
DataBarReader::DataBarReader(const DecodeHints&) {}
DataBarReader::~DataBarReader() = default;
static bool IsCharacterPair(PatternView v, int modsLeft, int modsRight)
{
float modSizeRef = ModSizeFinder(v);
return IsCharacter(LeftChar(v), modsLeft, modSizeRef) && IsCharacter(RightChar(v), modsRight, modSizeRef);
}
static bool IsLeftPair(const PatternView& v)
{
return IsFinder(v[8], v[9], v[10], v[11], v[12]) && IsGuard(v[-1], v[11]) && IsCharacterPair(v, 16, 15);
}
static bool IsRightPair(const PatternView& v)
{
return IsFinder(v[12], v[11], v[10], v[9], v[8]) && IsGuard(v[9], v[21]) && IsCharacterPair(v, 15, 16);
}
static Character ReadDataCharacter(const PatternView& view, bool outsideChar, bool rightPair)
{
constexpr int OUTSIDE_EVEN_TOTAL_SUBSET[] = {1, 10, 34, 70, 126};
constexpr int INSIDE_ODD_TOTAL_SUBSET[] = {4, 20, 48, 81};
constexpr int OUTSIDE_GSUM[] = {0, 161, 961, 2015, 2715};
constexpr int INSIDE_GSUM[] = {0, 336, 1036, 1516};
constexpr int OUTSIDE_ODD_WIDEST[] = {8, 6, 4, 3, 1};
constexpr int INSIDE_ODD_WIDEST[] = {2, 4, 6, 8};
Array4I oddPattern = {}, evnPattern = {};
if (!ReadDataCharacterRaw(view, outsideChar ? 16 : 15, outsideChar == rightPair, oddPattern, evnPattern))
return {};
auto calcChecksumPortion = [](const Array4I& counts) {
int res = 0;
for (auto it = counts.rbegin(); it != counts.rend(); ++it)
res = 9 * res + *it;
return res;
};
int checksumPortion = calcChecksumPortion(oddPattern) + 3 * calcChecksumPortion(evnPattern);
if (outsideChar) {
int oddSum = Reduce(oddPattern);
assert((oddSum & 1) == 0 && oddSum <= 12 && oddSum >= 4); // checked in ReadDataCharacterRaw
int group = (12 - oddSum) / 2;
int oddWidest = OUTSIDE_ODD_WIDEST[group];
int evnWidest = 9 - oddWidest;
int vOdd = GetValue(oddPattern, oddWidest, false);
int vEvn = GetValue(evnPattern, evnWidest, true);
int tEvn = OUTSIDE_EVEN_TOTAL_SUBSET[group];
int gSum = OUTSIDE_GSUM[group];
return {vOdd * tEvn + vEvn + gSum, checksumPortion};
} else {
int evnSum = Reduce(evnPattern);
assert((evnSum & 1) == 0 && evnSum <= 12 && evnSum >= 4); // checked in ReadDataCharacterRaw
int group = (10 - evnSum) / 2;
int oddWidest = INSIDE_ODD_WIDEST[group];
int evnWidest = 9 - oddWidest;
int vOdd = GetValue(oddPattern, oddWidest, true);
int vEvn = GetValue(evnPattern, evnWidest, false);
int tOdd = INSIDE_ODD_TOTAL_SUBSET[group];
int gSum = INSIDE_GSUM[group];
return {vEvn * tOdd + vOdd + gSum, checksumPortion};
}
}
int ParseFinderPattern(const PatternView& view, bool reversed)
{
static constexpr std::array<FixedPattern<5, 15>, 10> FINDER_PATTERNS = {{
{3, 8, 2, 1, 1},
{3, 5, 5, 1, 1},
{3, 3, 7, 1, 1},
{3, 1, 9, 1, 1},
{2, 7, 4, 1, 1},
{2, 5, 6, 1, 1},
{2, 3, 8, 1, 1},
{1, 5, 7, 1, 1},
{1, 3, 9, 1, 1},
}};
// TODO: c++20 constexpr inversion from FIND_PATTERN?
static constexpr std::array<FixedPattern<5, 15>, 10> REVERSED_FINDER_PATTERNS = {{
{1, 1, 2, 8, 3}, {1, 1, 5, 5, 3}, {1, 1, 7, 3, 3}, {1, 1, 9, 1, 3}, {1, 1, 4, 7, 2},
{1, 1, 6, 5, 2}, {1, 1, 8, 3, 2}, {1, 1, 7, 5, 1}, {1, 1, 9, 3, 1},
}};
return ParseFinderPattern(view, reversed, FINDER_PATTERNS, REVERSED_FINDER_PATTERNS);
}
static Pair ReadPair(const PatternView& view, bool rightPair)
{
if (int pattern = ParseFinderPattern(Finder(view), rightPair))
if (auto outside = ReadDataCharacter(rightPair ? RightChar(view) : LeftChar(view), true, rightPair))
if (auto inside = ReadDataCharacter(rightPair ? LeftChar(view) : RightChar(view), false, rightPair)) {
// include left and right guards
int xStart = view.pixelsInFront() - (rightPair ? 0 : view[-1] + std::min(view[-2], view[-1]));
int xStop = view.pixelsTillEnd() + (rightPair ? view[FULL_PAIR_SIZE] + view[FULL_PAIR_SIZE + 1] : 0);
return {outside, inside, pattern, xStart, xStop};
}
return {};
}
static bool ChecksumIsValid(Pair leftPair, Pair rightPair)
{
auto checksum = [](Pair p) { return p.left.checksum + 4 * p.right.checksum; };
int a = (checksum(leftPair) + 16 * checksum(rightPair)) % 79;
int b = 9 * (std::abs(leftPair.finder) - 1) + (std::abs(rightPair.finder) - 1);
if (b > 72)
b--;
if (b > 8)
b--;
return a == b;
}
static std::string ConstructText(Pair leftPair, Pair rightPair)
{
auto value = [](Pair p) { return 1597 * p.left.value + p.right.value; };
auto res = 4537077LL * value(leftPair) + value(rightPair);
std::ostringstream txt;
txt << std::setw(13) << std::setfill('0') << res;
txt << GTIN::ComputeCheckDigit(txt.str());
return txt.str();
}
struct State : public RowReader::DecodingState
{
std::unordered_set<Pair, PairHash> leftPairs;
std::unordered_set<Pair, PairHash> rightPairs;
};
Result DataBarReader::decodePattern(int rowNumber, const PatternView& view,
std::unique_ptr<RowReader::DecodingState>& state) const
{
#if 0 // non-stacked version
auto next = view.subView(-1, PAIR_SIZE);
// yes: the first view we test is at index 1 (black bar at 0 would be the guard pattern)
while (next.shift(2)) {
if (IsLeftPair(next)) {
if (auto leftPair = ReadPair(next, false); leftPair && next.skipSymbol() && IsRightPair(next)) {
if (auto rightPair = ReadPair(next, true); rightPair && CheckChecksum(leftPair, rightPair)) {
return {ConstructText(leftPair, rightPair), rowNumber, leftPair.xStart, rightPair.xStop,
BarcodeFormat::DataBar};
}
}
}
}
#else
if (!state)
state.reset(new State);
auto* prevState = static_cast<State*>(state.get());
auto next = view.subView(0, FULL_PAIR_SIZE + 2); // +2 reflects the guard pattern on the right
// yes: the first view we test is at index 1 (black bar at 0 would be the guard pattern)
while (next.shift(1)) {
if (IsLeftPair(next)) {
if (auto leftPair = ReadPair(next, false)) {
leftPair.y = rowNumber;
prevState->leftPairs.insert(leftPair);
next.shift(FULL_PAIR_SIZE - 1);
}
}
if (next.shift(1) && IsRightPair(next)) {
if (auto rightPair = ReadPair(next, true)) {
rightPair.y = rowNumber;
prevState->rightPairs.insert(rightPair);
}
}
}
for (const auto& leftPair : prevState->leftPairs)
for (const auto& rightPair : prevState->rightPairs)
if (ChecksumIsValid(leftPair, rightPair))
return {TextDecoder::FromLatin1(ConstructText(leftPair, rightPair)),
EstimatePosition(leftPair, rightPair), BarcodeFormat::DataBar};
#endif
return Result(DecodeStatus::NotFound);
}
} // namespace ZXing::OneD
<commit_msg>DataBar: add recent out-of-bounds fix also to disabled non-stacked codepath<commit_after>/*
* Copyright 2016 Nu-book Inc.
* Copyright 2016 ZXing authors
* Copyright 2020 Axel Waggershauser
*
* 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 "ODDataBarReader.h"
#include "ODDataBarCommon.h"
#include "BarcodeFormat.h"
#include "Result.h"
#include "GTIN.h"
#include "TextDecoder.h"
#include <sstream>
#include <iomanip>
#include <unordered_set>
namespace ZXing::OneD {
using namespace DataBar;
DataBarReader::DataBarReader(const DecodeHints&) {}
DataBarReader::~DataBarReader() = default;
static bool IsCharacterPair(PatternView v, int modsLeft, int modsRight)
{
float modSizeRef = ModSizeFinder(v);
return IsCharacter(LeftChar(v), modsLeft, modSizeRef) && IsCharacter(RightChar(v), modsRight, modSizeRef);
}
static bool IsLeftPair(const PatternView& v)
{
return IsFinder(v[8], v[9], v[10], v[11], v[12]) && IsGuard(v[-1], v[11]) && IsCharacterPair(v, 16, 15);
}
static bool IsRightPair(const PatternView& v)
{
return IsFinder(v[12], v[11], v[10], v[9], v[8]) && IsGuard(v[9], v[21]) && IsCharacterPair(v, 15, 16);
}
static Character ReadDataCharacter(const PatternView& view, bool outsideChar, bool rightPair)
{
constexpr int OUTSIDE_EVEN_TOTAL_SUBSET[] = {1, 10, 34, 70, 126};
constexpr int INSIDE_ODD_TOTAL_SUBSET[] = {4, 20, 48, 81};
constexpr int OUTSIDE_GSUM[] = {0, 161, 961, 2015, 2715};
constexpr int INSIDE_GSUM[] = {0, 336, 1036, 1516};
constexpr int OUTSIDE_ODD_WIDEST[] = {8, 6, 4, 3, 1};
constexpr int INSIDE_ODD_WIDEST[] = {2, 4, 6, 8};
Array4I oddPattern = {}, evnPattern = {};
if (!ReadDataCharacterRaw(view, outsideChar ? 16 : 15, outsideChar == rightPair, oddPattern, evnPattern))
return {};
auto calcChecksumPortion = [](const Array4I& counts) {
int res = 0;
for (auto it = counts.rbegin(); it != counts.rend(); ++it)
res = 9 * res + *it;
return res;
};
int checksumPortion = calcChecksumPortion(oddPattern) + 3 * calcChecksumPortion(evnPattern);
if (outsideChar) {
int oddSum = Reduce(oddPattern);
assert((oddSum & 1) == 0 && oddSum <= 12 && oddSum >= 4); // checked in ReadDataCharacterRaw
int group = (12 - oddSum) / 2;
int oddWidest = OUTSIDE_ODD_WIDEST[group];
int evnWidest = 9 - oddWidest;
int vOdd = GetValue(oddPattern, oddWidest, false);
int vEvn = GetValue(evnPattern, evnWidest, true);
int tEvn = OUTSIDE_EVEN_TOTAL_SUBSET[group];
int gSum = OUTSIDE_GSUM[group];
return {vOdd * tEvn + vEvn + gSum, checksumPortion};
} else {
int evnSum = Reduce(evnPattern);
assert((evnSum & 1) == 0 && evnSum <= 12 && evnSum >= 4); // checked in ReadDataCharacterRaw
int group = (10 - evnSum) / 2;
int oddWidest = INSIDE_ODD_WIDEST[group];
int evnWidest = 9 - oddWidest;
int vOdd = GetValue(oddPattern, oddWidest, true);
int vEvn = GetValue(evnPattern, evnWidest, false);
int tOdd = INSIDE_ODD_TOTAL_SUBSET[group];
int gSum = INSIDE_GSUM[group];
return {vEvn * tOdd + vOdd + gSum, checksumPortion};
}
}
int ParseFinderPattern(const PatternView& view, bool reversed)
{
static constexpr std::array<FixedPattern<5, 15>, 10> FINDER_PATTERNS = {{
{3, 8, 2, 1, 1},
{3, 5, 5, 1, 1},
{3, 3, 7, 1, 1},
{3, 1, 9, 1, 1},
{2, 7, 4, 1, 1},
{2, 5, 6, 1, 1},
{2, 3, 8, 1, 1},
{1, 5, 7, 1, 1},
{1, 3, 9, 1, 1},
}};
// TODO: c++20 constexpr inversion from FIND_PATTERN?
static constexpr std::array<FixedPattern<5, 15>, 10> REVERSED_FINDER_PATTERNS = {{
{1, 1, 2, 8, 3}, {1, 1, 5, 5, 3}, {1, 1, 7, 3, 3}, {1, 1, 9, 1, 3}, {1, 1, 4, 7, 2},
{1, 1, 6, 5, 2}, {1, 1, 8, 3, 2}, {1, 1, 7, 5, 1}, {1, 1, 9, 3, 1},
}};
return ParseFinderPattern(view, reversed, FINDER_PATTERNS, REVERSED_FINDER_PATTERNS);
}
static Pair ReadPair(const PatternView& view, bool rightPair)
{
if (int pattern = ParseFinderPattern(Finder(view), rightPair))
if (auto outside = ReadDataCharacter(rightPair ? RightChar(view) : LeftChar(view), true, rightPair))
if (auto inside = ReadDataCharacter(rightPair ? LeftChar(view) : RightChar(view), false, rightPair)) {
// include left and right guards
int xStart = view.pixelsInFront() - (rightPair ? 0 : view[-1] + std::min(view[-2], view[-1]));
int xStop = view.pixelsTillEnd() + (rightPair ? view[FULL_PAIR_SIZE] + view[FULL_PAIR_SIZE + 1] : 0);
return {outside, inside, pattern, xStart, xStop};
}
return {};
}
static bool ChecksumIsValid(Pair leftPair, Pair rightPair)
{
auto checksum = [](Pair p) { return p.left.checksum + 4 * p.right.checksum; };
int a = (checksum(leftPair) + 16 * checksum(rightPair)) % 79;
int b = 9 * (std::abs(leftPair.finder) - 1) + (std::abs(rightPair.finder) - 1);
if (b > 72)
b--;
if (b > 8)
b--;
return a == b;
}
static std::string ConstructText(Pair leftPair, Pair rightPair)
{
auto value = [](Pair p) { return 1597 * p.left.value + p.right.value; };
auto res = 4537077LL * value(leftPair) + value(rightPair);
std::ostringstream txt;
txt << std::setw(13) << std::setfill('0') << res;
txt << GTIN::ComputeCheckDigit(txt.str());
return txt.str();
}
struct State : public RowReader::DecodingState
{
std::unordered_set<Pair, PairHash> leftPairs;
std::unordered_set<Pair, PairHash> rightPairs;
};
Result DataBarReader::decodePattern(int rowNumber, const PatternView& view,
std::unique_ptr<RowReader::DecodingState>& state) const
{
#if 0 // non-stacked version
auto next = view.subView(-1, FULL_PAIR_SIZE + 2);
// yes: the first view we test is at index 1 (black bar at 0 would be the guard pattern)
while (next.shift(2)) {
if (IsLeftPair(next)) {
if (auto leftPair = ReadPair(next, false); leftPair && next.shift(FULL_PAIR_SIZE) && IsRightPair(next)) {
if (auto rightPair = ReadPair(next, true); rightPair && ChecksumIsValid(leftPair, rightPair)) {
return {ConstructText(leftPair, rightPair), rowNumber, leftPair.xStart, rightPair.xStop,
BarcodeFormat::DataBar};
}
}
}
}
#else
if (!state)
state.reset(new State);
auto* prevState = static_cast<State*>(state.get());
auto next = view.subView(0, FULL_PAIR_SIZE + 2); // +2 reflects the guard pattern on the right
// yes: the first view we test is at index 1 (black bar at 0 would be the guard pattern)
while (next.shift(1)) {
if (IsLeftPair(next)) {
if (auto leftPair = ReadPair(next, false)) {
leftPair.y = rowNumber;
prevState->leftPairs.insert(leftPair);
next.shift(FULL_PAIR_SIZE - 1);
}
}
if (next.shift(1) && IsRightPair(next)) {
if (auto rightPair = ReadPair(next, true)) {
rightPair.y = rowNumber;
prevState->rightPairs.insert(rightPair);
}
}
}
for (const auto& leftPair : prevState->leftPairs)
for (const auto& rightPair : prevState->rightPairs)
if (ChecksumIsValid(leftPair, rightPair))
return {TextDecoder::FromLatin1(ConstructText(leftPair, rightPair)),
EstimatePosition(leftPair, rightPair), BarcodeFormat::DataBar};
#endif
return Result(DecodeStatus::NotFound);
}
} // namespace ZXing::OneD
<|endoftext|>
|
<commit_before>#ifdef WIN32
#include <intrin.h>
#include <windows.h>
#endif
#include "glresource.hpp"
#include "event.hpp"
#if !defined(WIN32) && !defined(ANDROID)
#include <GL/glx.h>
#include "glxext.h"
#endif
namespace rs {
namespace {
bool g_bglfuncInit = false;
}
#define GLGETPROC(name) SDL_GL_GetProcAddress(BOOST_PP_STRINGIZE(name))
#if defined(_WIN32)
namespace {
using SetSwapInterval_t = bool APIENTRY (*)(int);
SetSwapInterval_t g_setswapinterval = nullptr;
}
void LoadGLAux() {
g_setswapinterval = (SetSwapInterval_t)GLGETPROC(wglSwapIntervalEXT);
}
#else
namespace {
#ifdef __ANDROID__
using SetSwapInterval_t = void GL_APIENTRY (*)(int);
#else
using SetSwapInterval_t = void APIENTRY (*)(int);
#endif
SetSwapInterval_t g_setswapinterval = nullptr;
}
void LoadGLAux() {
// EXTかSGIのどちらかが存在する事を期待
try {
g_setswapinterval = (SetSwapInterval_t)GLGETPROC(glXSwapIntervalSGI);
} catch(const std::runtime_error& e) {
g_setswapinterval = (SetSwapInterval_t)GLGETPROC(glXSwapIntervalEXT);
}
}
#endif
bool GLWrap::isGLFuncLoaded() {
return g_bglfuncInit;
}
void IGL_Draw::setSwapInterval(int n) {
g_setswapinterval(n);
}
void IGL_OtherSingle::setSwapInterval(int n) {
GLW.getDrawHandler().postExec([=](){
IGL_Draw().setSwapInterval(n);
});
}
// OpenGL関数ロード
// FuncNameで読み込めなければFuncNameARBとFuncNameEXTで試す
#define GLDEFINE(...)
#define DEF_GLMETHOD(ret_type, num, name, args, argnames) \
GLWrap::name = nullptr; \
GLWrap::name = (typename GLWrap::t_##name) GLGETPROC(name); \
if(GLWrap::name == nullptr) GLWrap::name = (typename GLWrap::t_##name)GLGETPROC(BOOST_PP_CAT(name,ARB)); \
if(GLWrap::name == nullptr) GLWrap::name = (typename GLWrap::t_##name)GLGETPROC(BOOST_PP_CAT(name,EXT)); \
Assert(Warn, GLWrap::name != nullptr, "could not load OpenGL function: %1%", #name)
void GLWrap::loadGLFunc() {
// 各種API関数
#ifndef ANDROID
#ifdef ANDROID
#include "android_gl.inc"
#elif defined(WIN32)
#include "mingw_gl.inc"
#else
#include "linux_gl.inc"
#endif
#endif
// その他OS依存なAPI関数
LoadGLAux();
g_bglfuncInit = true;
}
#undef DEF_GLMETHOD
#undef GLDEFINE
// ---------------------- GLShader ----------------------
void GLShader::_initShader() {
_idSh = GL.glCreateShader(c_glShFlag[_flag]);
const auto* pStr = _source.c_str();
GL.glShaderSource(_idSh, 1, &pStr, nullptr);
GL.glCompileShader(_idSh);
// エラーが無かったか確認
GLint compiled;
GL.glGetShaderiv(_idSh, GL_COMPILE_STATUS, &compiled);
AssertT(Throw, compiled==GL_TRUE, (GLE_ShaderError)(const std::string&)(GLuint), _source, _idSh)
}
GLShader::GLShader() {}
GLShader::GLShader(ShType flag, const std::string& src): _idSh(0), _flag(flag), _source(src) {
_initShader();
}
GLShader::~GLShader() {
onDeviceLost();
}
bool GLShader::isEmpty() const {
return _source.empty();
}
int GLShader::getShaderID() const {
return _idSh;
}
void GLShader::onDeviceLost() {
if(_idSh!=0) {
GL.glDeleteShader(_idSh);
_idSh = 0;
}
}
void GLShader::onDeviceReset() {
if(!isEmpty() && _idSh==0)
_initShader();
}
ShType GLShader::getShaderType() const {
return _flag;
}
// ---------------------- draw::Program ----------------------
namespace draw {
Program::Program(HProg hProg):
Token(hProg), _idProg(hProg.ref()->getProgramID()) {}
void Program::exec() {
GL.glUseProgram(_idProg);
}
}
// ---------------------- GLProgram ----------------------
void GLProgram::_setShader(HSh hSh) {
if(hSh)
_shader[hSh.ref()->getShaderType()] = hSh;
}
void GLProgram::_initProgram() {
_idProg = GL.glCreateProgram();
for(int i=0 ; i<static_cast<int>(ShType::NUM_SHTYPE) ; i++) {
auto& sh = _shader[i];
// Geometryシェーダー以外は必須
if(sh.valid()) {
GL.glAttachShader(_idProg, sh.cref()->getShaderID());
GLEC_ChkP(Trap)
} else {
AssertT(Trap, i==ShType::GEOMETRY, (GLE_Error)(const char*), "missing shader elements (vertex or fragment)")
}
}
GL.glLinkProgram(_idProg);
// エラーが無いかチェック
int ib;
GL.glGetProgramiv(_idProg, GL_LINK_STATUS, &ib);
AssertT(Throw, ib==GL_TRUE, (GLE_ProgramError)(GLuint), _idProg)
}
GLProgram::~GLProgram() {
if(mgr_gl.isInDtor()) {
for(auto& p : _shader)
p.setNull();
}
onDeviceLost();
}
void GLProgram::onDeviceLost() {
if(_idProg != 0) {
// ShaderはProgramをDeleteすれば自動的にdetachされる
GL.glDeleteProgram(_idProg);
_idProg = 0;
}
}
void GLProgram::onDeviceReset() {
if(_idProg == 0) {
// 先にshaderがresetされてないかもしれないので、ここでしておく
for(auto& s : _shader) {
if(s)
s.cref()->onDeviceReset();
}
_initProgram();
}
}
const HLSh& GLProgram::getShader(ShType type) const {
return _shader[(int)type];
}
OPGLint GLProgram::getUniformID(const std::string& name) const {
GLint id = GL.glGetUniformLocation(getProgramID(), name.c_str());
AssertTP(Warn, id>=0, (GLE_ParamNotFound)(const std::string&), name)
return id>=0 ? OPGLint(id) : OPGLint(spn::none);
}
OPGLint GLProgram::getAttribID(const std::string& name) const {
GLint id = GL.glGetAttribLocation(getProgramID(), name.c_str());
AssertT(Warn, id>=0, (GLE_ParamNotFound)(const std::string&), name)
return id>=0 ? OPGLint(id) : OPGLint(spn::none);
}
GLuint GLProgram::getProgramID() const {
return _idProg;
}
int GLProgram::_getNumParam(GLenum flag) const {
int iv;
GL.glGetProgramiv(getProgramID(), flag, &iv);
return iv;
}
int GLProgram::getNActiveAttribute() const {
return _getNumParam(GL_ACTIVE_ATTRIBUTES);
}
int GLProgram::getNActiveUniform() const {
return _getNumParam(GL_ACTIVE_UNIFORMS);
}
GLParamInfo GLProgram::_getActiveParam(int n, InfoF infoF) const {
GLchar buff[128];
GLsizei len;
GLint sz;
GLenum typ;
(GL.*infoF)(getProgramID(), n, countof(buff), &len, &sz, &typ, buff);
GLParamInfo ret = *GLFormat::QueryGLSLInfo(typ);
ret.name = buff;
return std::move(ret);
}
GLParamInfo GLProgram::getActiveAttribute(int n) const {
return _getActiveParam(n, &IGL::glGetActiveAttrib);
}
GLParamInfo GLProgram::getActiveUniform(int n) const {
return _getActiveParam(n, &IGL::glGetActiveUniform);
}
void GLProgram::use() const {
GL.glUseProgram(getProgramID());
}
// ------------------ GLParamInfo ------------------
GLParamInfo::GLParamInfo(const GLSLFormatDesc& desc): GLSLFormatDesc(desc) {}
}
<commit_msg>GLProgram: getUniform/AttribIDではエラーチェックをしないように変更<commit_after>#ifdef WIN32
#include <intrin.h>
#include <windows.h>
#endif
#include "glresource.hpp"
#include "event.hpp"
#if !defined(WIN32) && !defined(ANDROID)
#include <GL/glx.h>
#include "glxext.h"
#endif
namespace rs {
namespace {
bool g_bglfuncInit = false;
}
#define GLGETPROC(name) SDL_GL_GetProcAddress(BOOST_PP_STRINGIZE(name))
#if defined(_WIN32)
namespace {
using SetSwapInterval_t = bool APIENTRY (*)(int);
SetSwapInterval_t g_setswapinterval = nullptr;
}
void LoadGLAux() {
g_setswapinterval = (SetSwapInterval_t)GLGETPROC(wglSwapIntervalEXT);
}
#else
namespace {
#ifdef __ANDROID__
using SetSwapInterval_t = void GL_APIENTRY (*)(int);
#else
using SetSwapInterval_t = void APIENTRY (*)(int);
#endif
SetSwapInterval_t g_setswapinterval = nullptr;
}
void LoadGLAux() {
// EXTかSGIのどちらかが存在する事を期待
try {
g_setswapinterval = (SetSwapInterval_t)GLGETPROC(glXSwapIntervalSGI);
} catch(const std::runtime_error& e) {
g_setswapinterval = (SetSwapInterval_t)GLGETPROC(glXSwapIntervalEXT);
}
}
#endif
bool GLWrap::isGLFuncLoaded() {
return g_bglfuncInit;
}
void IGL_Draw::setSwapInterval(int n) {
g_setswapinterval(n);
}
void IGL_OtherSingle::setSwapInterval(int n) {
GLW.getDrawHandler().postExec([=](){
IGL_Draw().setSwapInterval(n);
});
}
// OpenGL関数ロード
// FuncNameで読み込めなければFuncNameARBとFuncNameEXTで試す
#define GLDEFINE(...)
#define DEF_GLMETHOD(ret_type, num, name, args, argnames) \
GLWrap::name = nullptr; \
GLWrap::name = (typename GLWrap::t_##name) GLGETPROC(name); \
if(GLWrap::name == nullptr) GLWrap::name = (typename GLWrap::t_##name)GLGETPROC(BOOST_PP_CAT(name,ARB)); \
if(GLWrap::name == nullptr) GLWrap::name = (typename GLWrap::t_##name)GLGETPROC(BOOST_PP_CAT(name,EXT)); \
Assert(Warn, GLWrap::name != nullptr, "could not load OpenGL function: %1%", #name)
void GLWrap::loadGLFunc() {
// 各種API関数
#ifndef ANDROID
#ifdef ANDROID
#include "android_gl.inc"
#elif defined(WIN32)
#include "mingw_gl.inc"
#else
#include "linux_gl.inc"
#endif
#endif
// その他OS依存なAPI関数
LoadGLAux();
g_bglfuncInit = true;
}
#undef DEF_GLMETHOD
#undef GLDEFINE
// ---------------------- GLShader ----------------------
void GLShader::_initShader() {
_idSh = GL.glCreateShader(c_glShFlag[_flag]);
const auto* pStr = _source.c_str();
GL.glShaderSource(_idSh, 1, &pStr, nullptr);
GL.glCompileShader(_idSh);
// エラーが無かったか確認
GLint compiled;
GL.glGetShaderiv(_idSh, GL_COMPILE_STATUS, &compiled);
AssertT(Throw, compiled==GL_TRUE, (GLE_ShaderError)(const std::string&)(GLuint), _source, _idSh)
}
GLShader::GLShader() {}
GLShader::GLShader(ShType flag, const std::string& src): _idSh(0), _flag(flag), _source(src) {
_initShader();
}
GLShader::~GLShader() {
onDeviceLost();
}
bool GLShader::isEmpty() const {
return _source.empty();
}
int GLShader::getShaderID() const {
return _idSh;
}
void GLShader::onDeviceLost() {
if(_idSh!=0) {
GL.glDeleteShader(_idSh);
_idSh = 0;
}
}
void GLShader::onDeviceReset() {
if(!isEmpty() && _idSh==0)
_initShader();
}
ShType GLShader::getShaderType() const {
return _flag;
}
// ---------------------- draw::Program ----------------------
namespace draw {
Program::Program(HProg hProg):
Token(hProg), _idProg(hProg.ref()->getProgramID()) {}
void Program::exec() {
GL.glUseProgram(_idProg);
}
}
// ---------------------- GLProgram ----------------------
void GLProgram::_setShader(HSh hSh) {
if(hSh)
_shader[hSh.ref()->getShaderType()] = hSh;
}
void GLProgram::_initProgram() {
_idProg = GL.glCreateProgram();
for(int i=0 ; i<static_cast<int>(ShType::NUM_SHTYPE) ; i++) {
auto& sh = _shader[i];
// Geometryシェーダー以外は必須
if(sh.valid()) {
GL.glAttachShader(_idProg, sh.cref()->getShaderID());
GLEC_ChkP(Trap)
} else {
AssertT(Trap, i==ShType::GEOMETRY, (GLE_Error)(const char*), "missing shader elements (vertex or fragment)")
}
}
GL.glLinkProgram(_idProg);
// エラーが無いかチェック
int ib;
GL.glGetProgramiv(_idProg, GL_LINK_STATUS, &ib);
AssertT(Throw, ib==GL_TRUE, (GLE_ProgramError)(GLuint), _idProg)
}
GLProgram::~GLProgram() {
if(mgr_gl.isInDtor()) {
for(auto& p : _shader)
p.setNull();
}
onDeviceLost();
}
void GLProgram::onDeviceLost() {
if(_idProg != 0) {
// ShaderはProgramをDeleteすれば自動的にdetachされる
GL.glDeleteProgram(_idProg);
_idProg = 0;
}
}
void GLProgram::onDeviceReset() {
if(_idProg == 0) {
// 先にshaderがresetされてないかもしれないので、ここでしておく
for(auto& s : _shader) {
if(s)
s.cref()->onDeviceReset();
}
_initProgram();
}
}
const HLSh& GLProgram::getShader(ShType type) const {
return _shader[(int)type];
}
OPGLint GLProgram::getUniformID(const std::string& name) const {
GLint id = GL.glGetUniformLocation_NC(getProgramID(), name.c_str());
AssertTP(Warn, id>=0, (GLE_ParamNotFound)(const std::string&), name)
return id>=0 ? OPGLint(id) : OPGLint(spn::none);
}
OPGLint GLProgram::getAttribID(const std::string& name) const {
GLint id = GL.glGetAttribLocation_NC(getProgramID(), name.c_str());
AssertT(Warn, id>=0, (GLE_ParamNotFound)(const std::string&), name)
return id>=0 ? OPGLint(id) : OPGLint(spn::none);
}
GLuint GLProgram::getProgramID() const {
return _idProg;
}
int GLProgram::_getNumParam(GLenum flag) const {
int iv;
GL.glGetProgramiv(getProgramID(), flag, &iv);
return iv;
}
int GLProgram::getNActiveAttribute() const {
return _getNumParam(GL_ACTIVE_ATTRIBUTES);
}
int GLProgram::getNActiveUniform() const {
return _getNumParam(GL_ACTIVE_UNIFORMS);
}
GLParamInfo GLProgram::_getActiveParam(int n, InfoF infoF) const {
GLchar buff[128];
GLsizei len;
GLint sz;
GLenum typ;
(GL.*infoF)(getProgramID(), n, countof(buff), &len, &sz, &typ, buff);
GLParamInfo ret = *GLFormat::QueryGLSLInfo(typ);
ret.name = buff;
return std::move(ret);
}
GLParamInfo GLProgram::getActiveAttribute(int n) const {
return _getActiveParam(n, &IGL::glGetActiveAttrib);
}
GLParamInfo GLProgram::getActiveUniform(int n) const {
return _getActiveParam(n, &IGL::glGetActiveUniform);
}
void GLProgram::use() const {
GL.glUseProgram(getProgramID());
}
// ------------------ GLParamInfo ------------------
GLParamInfo::GLParamInfo(const GLSLFormatDesc& desc): GLSLFormatDesc(desc) {}
}
<|endoftext|>
|
<commit_before>/*
* Copyright 2011 Google Inc.
*
* Use of this source code is governed by a BSD-style license that can be
* found in the LICENSE file.
*/
#include "gm.h"
#include "SkSurface.h"
#include "SkCanvas.h"
static void drawContents(SkSurface* surface, SkColor fillC) {
SkSize size = SkSize::Make(surface->width(), surface->height());
SkAutoTUnref<SkCanvas> canvas(surface->newCanvas());
SkScalar stroke = size.fWidth / 10;
SkScalar radius = (size.fWidth - stroke) / 2;
SkPaint paint;
paint.setAntiAlias(true);
paint.setColor(fillC);
canvas->drawCircle(size.fWidth/2, size.fHeight/2, radius, paint);
paint.setStyle(SkPaint::kStroke_Style);
paint.setStrokeWidth(stroke);
paint.setColor(SK_ColorBLACK);
canvas->drawCircle(size.fWidth/2, size.fHeight/2, radius, paint);
}
static void test_surface(SkCanvas* canvas, SkSurface* surf) {
drawContents(surf, SK_ColorRED);
SkImage* imgR = surf->newImageShapshot();
drawContents(surf, SK_ColorGREEN);
SkImage* imgG = surf->newImageShapshot();
drawContents(surf, SK_ColorBLUE);
imgR->draw(canvas, 0, 0, NULL);
imgG->draw(canvas, 0, 80, NULL);
surf->draw(canvas, 0, 160, NULL);
imgG->unref();
imgR->unref();
}
class ImageGM : public skiagm::GM {
void* fBuffer;
size_t fBufferSize;
SkSize fSize;
enum {
W = 64,
H = 64,
RB = W * 4 + 8,
};
public:
ImageGM() {
fBufferSize = RB * H;
fBuffer = sk_malloc_throw(fBufferSize);
fSize.set(SkIntToScalar(W), SkIntToScalar(H));
}
virtual ~ImageGM() {
sk_free(fBuffer);
}
protected:
virtual SkString onShortName() {
return SkString("image");
}
virtual SkISize onISize() {
return SkISize::Make(640, 480);
}
virtual void onDraw(SkCanvas* canvas) {
// since we draw into this directly, we need to start fresh
sk_bzero(fBuffer, fBufferSize);
SkImage::Info info;
info.fWidth = W;
info.fHeight = H;
info.fColorType = SkImage::kPMColor_ColorType;
info.fAlphaType = SkImage::kPremul_AlphaType;
SkAutoTUnref<SkSurface> surf0(SkSurface::NewRasterDirect(info, NULL, fBuffer, RB));
SkAutoTUnref<SkSurface> surf1(SkSurface::NewRaster(info, NULL));
SkAutoTUnref<SkSurface> surf2(SkSurface::NewPicture(info.fWidth, info.fHeight));
test_surface(canvas, surf0);
canvas->translate(80, 0);
test_surface(canvas, surf1);
canvas->translate(80, 0);
test_surface(canvas, surf2);
}
private:
typedef skiagm::GM INHERITED;
};
//////////////////////////////////////////////////////////////////////////////
static skiagm::GM* MyFactory(void*) { return new ImageGM; }
static skiagm::GMRegistry reg(MyFactory);
<commit_msg>update to surface.getCanvas()<commit_after>/*
* Copyright 2011 Google Inc.
*
* Use of this source code is governed by a BSD-style license that can be
* found in the LICENSE file.
*/
#include "gm.h"
#include "SkSurface.h"
#include "SkCanvas.h"
static void drawContents(SkSurface* surface, SkColor fillC) {
SkSize size = SkSize::Make(surface->width(), surface->height());
SkCanvas* canvas = surface->getCanvas();
SkScalar stroke = size.fWidth / 10;
SkScalar radius = (size.fWidth - stroke) / 2;
SkPaint paint;
paint.setAntiAlias(true);
paint.setColor(fillC);
canvas->drawCircle(size.fWidth/2, size.fHeight/2, radius, paint);
paint.setStyle(SkPaint::kStroke_Style);
paint.setStrokeWidth(stroke);
paint.setColor(SK_ColorBLACK);
canvas->drawCircle(size.fWidth/2, size.fHeight/2, radius, paint);
}
static void test_surface(SkCanvas* canvas, SkSurface* surf) {
drawContents(surf, SK_ColorRED);
SkImage* imgR = surf->newImageShapshot();
drawContents(surf, SK_ColorGREEN);
SkImage* imgG = surf->newImageShapshot();
drawContents(surf, SK_ColorBLUE);
SkPaint paint;
// paint.setFilterBitmap(true);
// paint.setAlpha(0x80);
imgR->draw(canvas, 0, 0, &paint);
imgG->draw(canvas, 0, 80, &paint);
surf->draw(canvas, 0, 160, &paint);
imgG->unref();
imgR->unref();
}
class ImageGM : public skiagm::GM {
void* fBuffer;
size_t fBufferSize;
SkSize fSize;
enum {
W = 64,
H = 64,
RB = W * 4 + 8,
};
public:
ImageGM() {
fBufferSize = RB * H;
fBuffer = sk_malloc_throw(fBufferSize);
fSize.set(SkIntToScalar(W), SkIntToScalar(H));
}
virtual ~ImageGM() {
sk_free(fBuffer);
}
protected:
virtual SkString onShortName() {
return SkString("image");
}
virtual SkISize onISize() {
return SkISize::Make(640, 480);
}
virtual void onDraw(SkCanvas* canvas) {
canvas->translate(10, 10);
canvas->scale(2, 2);
// since we draw into this directly, we need to start fresh
sk_bzero(fBuffer, fBufferSize);
SkImage::Info info;
info.fWidth = W;
info.fHeight = H;
info.fColorType = SkImage::kPMColor_ColorType;
info.fAlphaType = SkImage::kPremul_AlphaType;
SkAutoTUnref<SkSurface> surf0(SkSurface::NewRasterDirect(info, NULL, fBuffer, RB));
SkAutoTUnref<SkSurface> surf1(SkSurface::NewRaster(info, NULL));
SkAutoTUnref<SkSurface> surf2(SkSurface::NewPicture(info.fWidth, info.fHeight));
test_surface(canvas, surf0);
canvas->translate(80, 0);
test_surface(canvas, surf1);
canvas->translate(80, 0);
test_surface(canvas, surf2);
}
private:
typedef skiagm::GM INHERITED;
};
//////////////////////////////////////////////////////////////////////////////
static skiagm::GM* MyFactory(void*) { return new ImageGM; }
static skiagm::GMRegistry reg(MyFactory);
<|endoftext|>
|
<commit_before>/*
* File: newsimpletest.cpp
* Author: msk
*
* Created on Feb 4, 2013, 2:33:58 PM
*/
#include <stdlib.h>
#include <iostream>
/*
* Simple C++ Test Suite
*/
void hazelcast::client::IMap::remove(K key);
void testRemove() {
K key;
hazelcast::client::IMap iMap;
iMap.remove(key);
if (true /*check result*/) {
std::cout << "%TEST_FAILED% time=0 testname=testRemove (newsimpletest) message=error message sample" << std::endl;
}
}
int main(int argc, char** argv) {
std::cout << "%SUITE_STARTING% newsimpletest" << std::endl;
std::cout << "%SUITE_STARTED%" << std::endl;
std::cout << "%TEST_STARTED% testRemove (newsimpletest)" << std::endl;
testRemove();
std::cout << "%TEST_FINISHED% time=0 testRemove (newsimpletest)" << std::endl;
std::cout << "%SUITE_FINISHED% time=0" << std::endl;
return (EXIT_SUCCESS);
}
<commit_msg>cleanup<commit_after><|endoftext|>
|
<commit_before>/*
Library EDK - How to use Extensible Development Kit
Copyright (C) 2013 Eduardo Moura Sales Martins
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
email: edimartin@gmail.com.br
AV: Walmor M. de Souza 392 Casa
Gravatai RS Brazil 94065100
*/
//Include the Window
#include "edk/Window.h"
//Include the View to render Graphics
#include "edk/ViewGU2D.h"
//Include the FontMap render
#include "edk/fonts/FontMap.h"
class RenderView: public edk::ViewGU2D{
public:
RenderView(){}
~RenderView(){}
void load(edk::rectf32){
this->camera.position.x = 7;
this->camera.position.y = -0.5f;
this->camera.setSize(16.f,10.f);
//create the message
text.createStringMap("Hello EDK World");
}
void unload(){
//remove the message
text.deleteMap();
}
//render the scene in the vew
void drawScene(edk::rectf32){
//draw the message
text.draw();
}
private:
edk::fonts::FontMap text;
};
int main(){
edk::Window win;
//create the window with the buttons
win.createWindow(800,600,"EDK HELLO WORLD",EDK_WINDOW_BUTTONS);
//set the background color fo the window
win.cleanColor = edk::color3ui8(0,0,0);
//Create a view to draw the scene
RenderView view;
view.backgroundColor = edk::color4f32(1,1,1,1); //set the viewColor
view.frame.origin = edk::vec2f32(50,50); //set the view position inside the Window View
view.frame.size = edk::size2f32(700,500); //set the size of the View
//add the view in the Window
win.addSubview(&view);
//Loop
while(win.isOpened()){
//Clean the Windows
win.clean();
//load the Window Events
win.loadEvents();
//update the Views with the events pre-loaded
win.updateViews();
//check if click to close de Window
if(win.eventButtonClose()){
//close the window
win.closeWindow();
}
//test if release the ESC key
if(win.eventGetKeyReleaseSize()){
for(edk::uint32 i=0u;i<win.eventGetKeyReleaseSize();i++){
if(win.eventGetKeyRelease(i) == edk::key::escape){
//close Window
win.closeWindow();
}
}
}
//draw the View's
win.drawView();
//render the scene
win.render();
}
//remove the view from window
win.removeSubview(&view);
return 0;
}
<commit_msg>Forgot to set the text color to be showed.<commit_after>/*
Library EDK - How to use Extensible Development Kit
Copyright (C) 2013 Eduardo Moura Sales Martins
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
email: edimartin@gmail.com.br
AV: Walmor M. de Souza 392 Casa
Gravatai RS Brazil 94065100
*/
//Include the Window
#include "edk/Window.h"
//Include the View to render Graphics
#include "edk/ViewGU2D.h"
//Include the FontMap render
#include "edk/fonts/FontMap.h"
class RenderView: public edk::ViewGU2D{
public:
RenderView(){}
~RenderView(){}
void load(edk::rectf32){
this->camera.position.x = 7;
this->camera.position.y = -0.5f;
this->camera.setSize(16.f,10.f);
//create the message
text.createStringMap("Hello EDK World");
text.setColor(0.f,0.f,0.f,1.f);
}
void unload(){
//remove the message
text.deleteMap();
}
//render the scene in the vew
void drawScene(edk::rectf32){
//draw the message
text.draw();
}
private:
edk::fonts::FontMap text;
};
int main(){
edk::Window win;
//create the window with the buttons
win.createWindow(800,600,"EDK HELLO WORLD",EDK_WINDOW_BUTTONS);
//set the background color fo the window
win.cleanColor = edk::color3ui8(0,0,0);
//Create a view to draw the scene
RenderView view;
view.backgroundColor = edk::color4f32(1,1,1,1); //set the viewColor
view.frame.origin = edk::vec2f32(50,50); //set the view position inside the Window View
view.frame.size = edk::size2f32(700,500); //set the size of the View
//add the view in the Window
win.addSubview(&view);
//Loop
while(win.isOpened()){
//Clean the Windows
win.clean();
//load the Window Events
win.loadEvents();
//update the Views with the events pre-loaded
win.updateViews();
//check if click to close de Window
if(win.eventButtonClose()){
//close the window
win.closeWindow();
}
//test if release the ESC key
if(win.eventGetKeyReleaseSize()){
for(edk::uint32 i=0u;i<win.eventGetKeyReleaseSize();i++){
if(win.eventGetKeyRelease(i) == edk::key::escape){
//close Window
win.closeWindow();
}
}
}
//draw the View's
win.drawView();
//render the scene
win.render();
}
//remove the view from window
win.removeSubview(&view);
return 0;
}
<|endoftext|>
|
<commit_before>/*************************************************************************
*
* OpenOffice.org - a multi-platform office productivity suite
*
* $RCSfile: attrlistimpl.hxx,v $
*
* $Revision: 1.3 $
*
* last change: $Author: rt $ $Date: 2005-09-08 12:03:33 $
*
* The Contents of this file are made available subject to
* the terms of GNU Lesser General Public License Version 2.1.
*
*
* GNU Lesser General Public License Version 2.1
* =============================================
* Copyright 2005 by Sun Microsystems, Inc.
* 901 San Antonio Road, Palo Alto, CA 94303, USA
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License version 2.1, as published by the Free Software Foundation.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston,
* MA 02111-1307 USA
*
************************************************************************/
#include <cppuhelper/implbase2.hxx>
namespace sax_expatwrap
{
struct AttributeListImpl_impl;
class AttributeListImpl :
public WeakImplHelper2< XAttributeList, XCloneable >
{
public:
AttributeListImpl();
AttributeListImpl( const AttributeListImpl & );
~AttributeListImpl();
public:
virtual sal_Int16 SAL_CALL getLength(void) throw(RuntimeException);
virtual OUString SAL_CALL getNameByIndex(sal_Int16 i) throw(RuntimeException);
virtual OUString SAL_CALL getTypeByIndex(sal_Int16 i) throw(RuntimeException);
virtual OUString SAL_CALL getTypeByName(const OUString& aName) throw(RuntimeException);
virtual OUString SAL_CALL getValueByIndex(sal_Int16 i) throw(RuntimeException);
virtual OUString SAL_CALL getValueByName(const OUString& aName) throw( RuntimeException);
public:
virtual Reference< XCloneable > SAL_CALL createClone() throw(RuntimeException);
public:
void addAttribute( const OUString &sName , const OUString &sType , const OUString &sValue );
void clear();
void removeAttribute( const OUString &sName );
void setAttributeList( const Reference< XAttributeList > & );
private:
struct AttributeListImpl_impl *m_pImpl;
};
}
<commit_msg>INTEGRATION: CWS custommeta (1.3.48); FILE MERGED 2007/12/07 13:40:15 mst 1.3.48.1: - sax/source/expatwrap/attrlistimpl.{hxx,cxx}: rename class AttributeListImpl to AttributeList, in preparation for export<commit_after>/*************************************************************************
*
* OpenOffice.org - a multi-platform office productivity suite
*
* $RCSfile: attrlistimpl.hxx,v $
*
* $Revision: 1.4 $
*
* last change: $Author: obo $ $Date: 2008-02-26 14:40:37 $
*
* The Contents of this file are made available subject to
* the terms of GNU Lesser General Public License Version 2.1.
*
*
* GNU Lesser General Public License Version 2.1
* =============================================
* Copyright 2005 by Sun Microsystems, Inc.
* 901 San Antonio Road, Palo Alto, CA 94303, USA
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License version 2.1, as published by the Free Software Foundation.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston,
* MA 02111-1307 USA
*
************************************************************************/
#ifndef _SAX_ATTRLISTIMPL_HXX
#define _SAX_ATTRLISTIMPL_HXX
#include "sal/config.h"
//#include "sax/saxdllapi.h"
#include <cppuhelper/implbase2.hxx>
#include <com/sun/star/uno/RuntimeException.hpp>
#include <com/sun/star/util/XCloneable.hpp>
#include <com/sun/star/xml/sax/XAttributeList.hpp>
namespace sax_expatwrap
{
struct AttributeList_impl;
//FIXME
class /*SAX_DLLPUBLIC*/ AttributeList :
public ::cppu::WeakImplHelper2<
::com::sun::star::xml::sax::XAttributeList,
::com::sun::star::util::XCloneable >
{
public:
AttributeList();
AttributeList( const AttributeList & );
virtual ~AttributeList();
void addAttribute( const ::rtl::OUString &sName ,
const ::rtl::OUString &sType , const ::rtl::OUString &sValue );
void clear();
void removeAttribute( const ::rtl::OUString &sName );
void setAttributeList( const ::com::sun::star::uno::Reference<
::com::sun::star::xml::sax::XAttributeList > & );
public:
// XAttributeList
virtual sal_Int16 SAL_CALL getLength(void)
throw(::com::sun::star::uno::RuntimeException);
virtual ::rtl::OUString SAL_CALL getNameByIndex(sal_Int16 i)
throw(::com::sun::star::uno::RuntimeException);
virtual ::rtl::OUString SAL_CALL getTypeByIndex(sal_Int16 i)
throw(::com::sun::star::uno::RuntimeException);
virtual ::rtl::OUString SAL_CALL getTypeByName(const ::rtl::OUString& aName)
throw(::com::sun::star::uno::RuntimeException);
virtual ::rtl::OUString SAL_CALL getValueByIndex(sal_Int16 i)
throw(::com::sun::star::uno::RuntimeException);
virtual ::rtl::OUString SAL_CALL getValueByName(const ::rtl::OUString& aName)
throw( ::com::sun::star::uno::RuntimeException);
// XCloneable
virtual ::com::sun::star::uno::Reference< XCloneable > SAL_CALL
createClone() throw(::com::sun::star::uno::RuntimeException);
private:
struct AttributeList_impl *m_pImpl;
};
}
#endif
<|endoftext|>
|
<commit_before>/*************************************************************************
*
* OpenOffice.org - a multi-platform office productivity suite
*
* $RCSfile: listenercalls.cxx,v $
*
* $Revision: 1.5 $
*
* last change: $Author: kz $ $Date: 2006-07-21 14:41:30 $
*
* The Contents of this file are made available subject to
* the terms of GNU Lesser General Public License Version 2.1.
*
*
* GNU Lesser General Public License Version 2.1
* =============================================
* Copyright 2005 by Sun Microsystems, Inc.
* 901 San Antonio Road, Palo Alto, CA 94303, USA
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License version 2.1, as published by the Free Software Foundation.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston,
* MA 02111-1307 USA
*
************************************************************************/
// MARKER(update_precomp.py): autogen include statement, do not remove
#include "precompiled_sc.hxx"
#include <com/sun/star/util/XModifyListener.hpp>
#include <tools/debug.hxx>
#include "listenercalls.hxx"
using namespace com::sun::star;
//------------------------------------------------------------------------
ScUnoListenerCalls::ScUnoListenerCalls()
{
}
ScUnoListenerCalls::~ScUnoListenerCalls()
{
DBG_ASSERT( aEntries.empty(), "unhandled listener calls remaining" );
}
void ScUnoListenerCalls::Add( const uno::Reference<util::XModifyListener>& rListener,
const lang::EventObject& rEvent )
{
if ( rListener.is() )
aEntries.push_back( ScUnoListenerEntry( rListener, rEvent ) );
}
void ScUnoListenerCalls::ExecuteAndClear()
{
// Execute all stored calls and remove them from the list.
// During each modified() call, Add may be called again.
// These new calls are executed here, too.
if (!aEntries.empty())
{
std::list<ScUnoListenerEntry>::iterator aItr(aEntries.begin());
std::list<ScUnoListenerEntry>::iterator aEndItr(aEntries.end());
while ( aItr != aEndItr )
{
ScUnoListenerEntry aEntry = *aItr;
try
{
aEntry.xListener->modified( aEntry.aEvent );
}
catch ( uno::RuntimeException )
{
// the listener is an external object and may throw a RuntimeException
// for reasons we don't know
}
// New calls that are added during the modified() call are appended to the end
// of aEntries, so the loop will catch them, too (as long as erase happens
// after modified).
aItr = aEntries.erase(aItr);
}
}
}
<commit_msg>INTEGRATION: CWS changefileheader (1.5.492); FILE MERGED 2008/03/31 17:19:34 rt 1.5.492.1: #i87441# Change license header to LPGL v3.<commit_after>/*************************************************************************
*
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* Copyright 2008 by Sun Microsystems, Inc.
*
* OpenOffice.org - a multi-platform office productivity suite
*
* $RCSfile: listenercalls.cxx,v $
* $Revision: 1.6 $
*
* This file is part of OpenOffice.org.
*
* OpenOffice.org is free software: you can redistribute it and/or modify
* it under the terms of the GNU Lesser General Public License version 3
* only, as published by the Free Software Foundation.
*
* OpenOffice.org is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Lesser General Public License version 3 for more details
* (a copy is included in the LICENSE file that accompanied this code).
*
* You should have received a copy of the GNU Lesser General Public License
* version 3 along with OpenOffice.org. If not, see
* <http://www.openoffice.org/license.html>
* for a copy of the LGPLv3 License.
*
************************************************************************/
// MARKER(update_precomp.py): autogen include statement, do not remove
#include "precompiled_sc.hxx"
#include <com/sun/star/util/XModifyListener.hpp>
#include <tools/debug.hxx>
#include "listenercalls.hxx"
using namespace com::sun::star;
//------------------------------------------------------------------------
ScUnoListenerCalls::ScUnoListenerCalls()
{
}
ScUnoListenerCalls::~ScUnoListenerCalls()
{
DBG_ASSERT( aEntries.empty(), "unhandled listener calls remaining" );
}
void ScUnoListenerCalls::Add( const uno::Reference<util::XModifyListener>& rListener,
const lang::EventObject& rEvent )
{
if ( rListener.is() )
aEntries.push_back( ScUnoListenerEntry( rListener, rEvent ) );
}
void ScUnoListenerCalls::ExecuteAndClear()
{
// Execute all stored calls and remove them from the list.
// During each modified() call, Add may be called again.
// These new calls are executed here, too.
if (!aEntries.empty())
{
std::list<ScUnoListenerEntry>::iterator aItr(aEntries.begin());
std::list<ScUnoListenerEntry>::iterator aEndItr(aEntries.end());
while ( aItr != aEndItr )
{
ScUnoListenerEntry aEntry = *aItr;
try
{
aEntry.xListener->modified( aEntry.aEvent );
}
catch ( uno::RuntimeException )
{
// the listener is an external object and may throw a RuntimeException
// for reasons we don't know
}
// New calls that are added during the modified() call are appended to the end
// of aEntries, so the loop will catch them, too (as long as erase happens
// after modified).
aItr = aEntries.erase(aItr);
}
}
}
<|endoftext|>
|
<commit_before>/*
This file is part of KOrganizer.
Copyright (c) 2001 Cornelius Schumacher <schumacher@kde.org>
Copyright (C) 2003-2004 Reinhold Kainhofer <reinhold@kainhofer.com>
This program is free software; you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation; either version 2 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program; if not, write to the Free Software
Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
As a special exception, permission is given to link this program
with any edition of Qt, and distribute the resulting executable,
without including the source code for Qt in the source distribution.
*/
#include <kcmultidialog.h>
#include <ksettings/dialog.h>
#include <libkdepim/categoryeditdialog.h>
#include "calendarview.h"
#include "koprefsdialog.h"
#include "koprefs.h"
#include "koeventeditor.h"
#include "kotodoeditor.h"
#include "kojournaleditor.h"
#include "searchdialog.h"
#include "filtereditdialog.h"
#ifndef KORG_NOARCHIVE
#include "archivedialog.h"
#endif
#include "koviewmanager.h"
#include "koagendaview.h"
#include "koglobals.h"
#include "kodialogmanager.h"
#include "kodialogmanager.moc"
// FIXME: Handle KOEventViewerDialogs in dialog manager. Pass
// KOPrefs::mCompactDialog.
class KODialogManager::DialogManagerVisitor : public IncidenceBase::Visitor
{
public:
DialogManagerVisitor() : mDialogManager( 0 ) {}
bool act( IncidenceBase *incidence, KODialogManager *manager )
{
mDialogManager = manager;
return incidence->accept( *this );
}
protected:
KODialogManager *mDialogManager;
};
class KODialogManager::EditorDialogVisitor :
public KODialogManager::DialogManagerVisitor
{
public:
EditorDialogVisitor() : DialogManagerVisitor(), mEditor( 0 ) {}
KOIncidenceEditor *editor() const { return mEditor; }
protected:
bool visit( Event * ) { mEditor = mDialogManager->getEventEditor(); return mEditor; }
bool visit( Todo * ) { mEditor = mDialogManager->getTodoEditor(); return mEditor; }
bool visit( Journal * ) { mEditor = mDialogManager->getJournalEditor(); return mEditor; }
protected:
KOIncidenceEditor *mEditor;
};
KODialogManager::KODialogManager( CalendarView *mainView ) :
QObject(), mMainView( mainView )
{
mOptionsDialog = 0;
mSearchDialog = 0;
mArchiveDialog = 0;
mFilterEditDialog = 0;
mCategoryEditDialog = new KPIM::CategoryEditDialog( KOPrefs::instance(), mMainView );
connect( mainView, SIGNAL( categoriesChanged() ),
mCategoryEditDialog, SLOT( reload() ) );
KOGlobals::fitDialogToScreen( mCategoryEditDialog );
}
KODialogManager::~KODialogManager()
{
delete mOptionsDialog;
delete mSearchDialog;
#ifndef KORG_NOARCHIVE
delete mArchiveDialog;
#endif
delete mFilterEditDialog;
}
void KODialogManager::errorSaveIncidence( QWidget *parent, Incidence *incidence )
{
KMessageBox::sorry( parent, i18n("Unable to save %1 \"%2\".")
.arg( i18n( incidence->type() ) )
.arg( incidence->summary() ) );
}
void KODialogManager::showOptionsDialog()
{
if (!mOptionsDialog) {
#if 0
mOptionsDialog = new KConfigureDialog();
// mOptionsDialog = new KConfigureDialog( KConfigureDialog::Configurable );
// mOptionsDialog = new KConfigureDialog( mMainView );
connect( mOptionsDialog->dialog(),
SIGNAL( configCommitted( const QCString & ) ),
mMainView, SLOT( updateConfig() ) );
#else
mOptionsDialog = new KCMultiDialog( mMainView, "KorganizerPreferences" );
connect( mOptionsDialog, SIGNAL( configCommitted( const QCString & ) ),
mMainView, SLOT( updateConfig() ) );
#if 0
connect( mOptionsDialog, SIGNAL( applyClicked() ),
mMainView, SLOT( updateConfig() ) );
connect( mOptionsDialog, SIGNAL( okClicked() ),
mMainView, SLOT( updateConfig() ) );
// @TODO Find a way to do this with KCMultiDialog
connect(mCategoryEditDialog,SIGNAL(categoryConfigChanged()),
mOptionsDialog,SLOT(updateCategories()));
#endif
QStringList modules;
modules.append( "korganizer_configmain.desktop" );
modules.append( "korganizer_configtime.desktop" );
modules.append( "korganizer_configviews.desktop" );
modules.append( "korganizer_configfonts.desktop" );
modules.append( "korganizer_configcolors.desktop" );
modules.append( "korganizer_configgroupscheduling.desktop" );
modules.append( "korganizer_configgroupautomation.desktop" );
modules.append( "korganizer_configfreebusy.desktop" );
modules.append( "korganizer_configplugins.desktop" );
modules.append( "korganizer_configdesignerfields.desktop" );
// add them all
QStringList::iterator mit;
for ( mit = modules.begin(); mit != modules.end(); ++mit )
mOptionsDialog->addModule( *mit );
#endif
}
mOptionsDialog->show();
mOptionsDialog->raise();
}
void KODialogManager::showCategoryEditDialog()
{
mCategoryEditDialog->show();
}
void KODialogManager::showSearchDialog()
{
if (!mSearchDialog) {
mSearchDialog = new SearchDialog(mMainView->calendar(),mMainView);
connect(mSearchDialog,SIGNAL(showIncidenceSignal(Incidence *)),
mMainView,SLOT(showIncidence(Incidence *)));
connect(mSearchDialog,SIGNAL(editIncidenceSignal(Incidence *)),
mMainView,SLOT(editIncidence(Incidence *)));
connect(mSearchDialog,SIGNAL(deleteIncidenceSignal(Incidence *)),
mMainView, SLOT(deleteIncidence(Incidence *)));
connect(mMainView,SIGNAL(closingDown()),mSearchDialog,SLOT(reject()));
}
// make sure the widget is on top again
mSearchDialog->show();
mSearchDialog->raise();
}
void KODialogManager::showArchiveDialog()
{
#ifndef KORG_NOARCHIVE
if (!mArchiveDialog) {
mArchiveDialog = new ArchiveDialog(mMainView->calendar(),mMainView);
connect(mArchiveDialog,SIGNAL(eventsDeleted()),
mMainView,SLOT(updateView()));
connect(mArchiveDialog,SIGNAL(autoArchivingSettingsModified()),
mMainView,SLOT(slotAutoArchivingSettingsModified()));
}
mArchiveDialog->show();
mArchiveDialog->raise();
// Workaround.
QApplication::restoreOverrideCursor();
#endif
}
void KODialogManager::showFilterEditDialog( QPtrList<CalFilter> *filters )
{
if ( !mFilterEditDialog ) {
mFilterEditDialog = new FilterEditDialog( filters, mMainView );
connect( mFilterEditDialog, SIGNAL( filterChanged() ),
mMainView, SLOT( updateFilter() ) );
connect( mFilterEditDialog, SIGNAL( editCategories() ),
mCategoryEditDialog, SLOT( show() ) );
connect( mCategoryEditDialog, SIGNAL( categoryConfigChanged() ),
mFilterEditDialog, SLOT( updateCategoryConfig() ) );
}
mFilterEditDialog->show();
mFilterEditDialog->raise();
}
KOIncidenceEditor *KODialogManager::getEditor( Incidence *incidence )
{
if ( !incidence ) return 0;
EditorDialogVisitor v;
if ( v.act( incidence, this ) ) {
return v.editor();
} else
return 0;
}
KOEventEditor *KODialogManager::getEventEditor()
{
KOEventEditor *eventEditor = new KOEventEditor( mMainView->calendar(),
mMainView );
connectEditor( eventEditor );
return eventEditor;
}
void KODialogManager::connectTypeAhead( KOEventEditor *editor,
KOAgendaView *agenda )
{
if ( editor && agenda ) {
agenda->setTypeAheadReceiver( editor->typeAheadReceiver() );
connect( editor, SIGNAL( focusReceivedSignal() ),
agenda, SLOT( finishTypeAhead() ) );
}
}
void KODialogManager::connectEditor( KOIncidenceEditor*editor )
{
/* connect( editor, SIGNAL( deleteIncidenceSignal( Incidence * ) ),
mMainView, SLOT( deleteIncidence( Incidence * ) ) );*/
connect( mCategoryEditDialog, SIGNAL( categoryConfigChanged() ),
editor, SLOT( updateCategoryConfig() ) );
connect( editor, SIGNAL( editCategories() ),
mCategoryEditDialog, SLOT( show() ) );
connect( editor, SIGNAL( dialogClose( Incidence * ) ),
mMainView, SLOT( dialogClosing( Incidence * ) ) );
connect( editor, SIGNAL( editCanceled( Incidence * ) ),
mMainView, SLOT( editCanceled( Incidence * ) ) );
connect( mMainView, SIGNAL( closingDown() ), editor, SLOT( reject() ) );
connect( editor, SIGNAL( deleteAttendee( Incidence * ) ),
mMainView, SLOT( cancelAttendees( Incidence * ) ) );
}
KOTodoEditor *KODialogManager::getTodoEditor()
{
KOTodoEditor *todoEditor = new KOTodoEditor( mMainView->calendar(), mMainView );
connectEditor( todoEditor );
return todoEditor;
}
KOJournalEditor *KODialogManager::getJournalEditor()
{
KOJournalEditor *journalEditor = new KOJournalEditor( mMainView->calendar(), mMainView );
connectEditor( journalEditor );
return journalEditor;
}
void KODialogManager::updateSearchDialog()
{
if (mSearchDialog) mSearchDialog->updateView();
}
<commit_msg>It's a SIGNAL, not a SLOT!<commit_after>/*
This file is part of KOrganizer.
Copyright (c) 2001 Cornelius Schumacher <schumacher@kde.org>
Copyright (C) 2003-2004 Reinhold Kainhofer <reinhold@kainhofer.com>
This program is free software; you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation; either version 2 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program; if not, write to the Free Software
Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
As a special exception, permission is given to link this program
with any edition of Qt, and distribute the resulting executable,
without including the source code for Qt in the source distribution.
*/
#include <kcmultidialog.h>
#include <ksettings/dialog.h>
#include <libkdepim/categoryeditdialog.h>
#include "calendarview.h"
#include "koprefsdialog.h"
#include "koprefs.h"
#include "koeventeditor.h"
#include "kotodoeditor.h"
#include "kojournaleditor.h"
#include "searchdialog.h"
#include "filtereditdialog.h"
#ifndef KORG_NOARCHIVE
#include "archivedialog.h"
#endif
#include "koviewmanager.h"
#include "koagendaview.h"
#include "koglobals.h"
#include "kodialogmanager.h"
#include "kodialogmanager.moc"
// FIXME: Handle KOEventViewerDialogs in dialog manager. Pass
// KOPrefs::mCompactDialog.
class KODialogManager::DialogManagerVisitor : public IncidenceBase::Visitor
{
public:
DialogManagerVisitor() : mDialogManager( 0 ) {}
bool act( IncidenceBase *incidence, KODialogManager *manager )
{
mDialogManager = manager;
return incidence->accept( *this );
}
protected:
KODialogManager *mDialogManager;
};
class KODialogManager::EditorDialogVisitor :
public KODialogManager::DialogManagerVisitor
{
public:
EditorDialogVisitor() : DialogManagerVisitor(), mEditor( 0 ) {}
KOIncidenceEditor *editor() const { return mEditor; }
protected:
bool visit( Event * ) { mEditor = mDialogManager->getEventEditor(); return mEditor; }
bool visit( Todo * ) { mEditor = mDialogManager->getTodoEditor(); return mEditor; }
bool visit( Journal * ) { mEditor = mDialogManager->getJournalEditor(); return mEditor; }
protected:
KOIncidenceEditor *mEditor;
};
KODialogManager::KODialogManager( CalendarView *mainView ) :
QObject(), mMainView( mainView )
{
mOptionsDialog = 0;
mSearchDialog = 0;
mArchiveDialog = 0;
mFilterEditDialog = 0;
mCategoryEditDialog = new KPIM::CategoryEditDialog( KOPrefs::instance(), mMainView );
connect( mainView, SIGNAL( categoriesChanged() ),
mCategoryEditDialog, SLOT( reload() ) );
KOGlobals::fitDialogToScreen( mCategoryEditDialog );
}
KODialogManager::~KODialogManager()
{
delete mOptionsDialog;
delete mSearchDialog;
#ifndef KORG_NOARCHIVE
delete mArchiveDialog;
#endif
delete mFilterEditDialog;
}
void KODialogManager::errorSaveIncidence( QWidget *parent, Incidence *incidence )
{
KMessageBox::sorry( parent, i18n("Unable to save %1 \"%2\".")
.arg( i18n( incidence->type() ) )
.arg( incidence->summary() ) );
}
void KODialogManager::showOptionsDialog()
{
if (!mOptionsDialog) {
#if 0
mOptionsDialog = new KConfigureDialog();
// mOptionsDialog = new KConfigureDialog( KConfigureDialog::Configurable );
// mOptionsDialog = new KConfigureDialog( mMainView );
connect( mOptionsDialog->dialog(),
SIGNAL( configCommitted( const QCString & ) ),
mMainView, SLOT( updateConfig() ) );
#else
mOptionsDialog = new KCMultiDialog( mMainView, "KorganizerPreferences" );
connect( mOptionsDialog, SIGNAL( configCommitted( const QCString & ) ),
mMainView, SLOT( updateConfig() ) );
#if 0
connect( mOptionsDialog, SIGNAL( applyClicked() ),
mMainView, SLOT( updateConfig() ) );
connect( mOptionsDialog, SIGNAL( okClicked() ),
mMainView, SLOT( updateConfig() ) );
// @TODO Find a way to do this with KCMultiDialog
connect(mCategoryEditDialog,SIGNAL(categoryConfigChanged()),
mOptionsDialog,SLOT(updateCategories()));
#endif
QStringList modules;
modules.append( "korganizer_configmain.desktop" );
modules.append( "korganizer_configtime.desktop" );
modules.append( "korganizer_configviews.desktop" );
modules.append( "korganizer_configfonts.desktop" );
modules.append( "korganizer_configcolors.desktop" );
modules.append( "korganizer_configgroupscheduling.desktop" );
modules.append( "korganizer_configgroupautomation.desktop" );
modules.append( "korganizer_configfreebusy.desktop" );
modules.append( "korganizer_configplugins.desktop" );
modules.append( "korganizer_configdesignerfields.desktop" );
// add them all
QStringList::iterator mit;
for ( mit = modules.begin(); mit != modules.end(); ++mit )
mOptionsDialog->addModule( *mit );
#endif
}
mOptionsDialog->show();
mOptionsDialog->raise();
}
void KODialogManager::showCategoryEditDialog()
{
mCategoryEditDialog->show();
}
void KODialogManager::showSearchDialog()
{
if (!mSearchDialog) {
mSearchDialog = new SearchDialog(mMainView->calendar(),mMainView);
connect(mSearchDialog,SIGNAL(showIncidenceSignal(Incidence *)),
mMainView,SLOT(showIncidence(Incidence *)));
connect(mSearchDialog,SIGNAL(editIncidenceSignal(Incidence *)),
mMainView,SLOT(editIncidence(Incidence *)));
connect(mSearchDialog,SIGNAL(deleteIncidenceSignal(Incidence *)),
mMainView, SLOT(deleteIncidence(Incidence *)));
connect(mMainView,SIGNAL(closingDown()),mSearchDialog,SLOT(reject()));
}
// make sure the widget is on top again
mSearchDialog->show();
mSearchDialog->raise();
}
void KODialogManager::showArchiveDialog()
{
#ifndef KORG_NOARCHIVE
if (!mArchiveDialog) {
mArchiveDialog = new ArchiveDialog(mMainView->calendar(),mMainView);
connect(mArchiveDialog,SIGNAL(eventsDeleted()),
mMainView,SLOT(updateView()));
connect(mArchiveDialog,SIGNAL(autoArchivingSettingsModified()),
mMainView,SLOT(slotAutoArchivingSettingsModified()));
}
mArchiveDialog->show();
mArchiveDialog->raise();
// Workaround.
QApplication::restoreOverrideCursor();
#endif
}
void KODialogManager::showFilterEditDialog( QPtrList<CalFilter> *filters )
{
if ( !mFilterEditDialog ) {
mFilterEditDialog = new FilterEditDialog( filters, mMainView );
connect( mFilterEditDialog, SIGNAL( filterChanged() ),
mMainView, SLOT( updateFilter() ) );
connect( mFilterEditDialog, SIGNAL( editCategories() ),
mCategoryEditDialog, SLOT( show() ) );
connect( mCategoryEditDialog, SIGNAL( categoryConfigChanged() ),
mFilterEditDialog, SLOT( updateCategoryConfig() ) );
}
mFilterEditDialog->show();
mFilterEditDialog->raise();
}
KOIncidenceEditor *KODialogManager::getEditor( Incidence *incidence )
{
if ( !incidence ) return 0;
EditorDialogVisitor v;
if ( v.act( incidence, this ) ) {
return v.editor();
} else
return 0;
}
KOEventEditor *KODialogManager::getEventEditor()
{
KOEventEditor *eventEditor = new KOEventEditor( mMainView->calendar(),
mMainView );
connectEditor( eventEditor );
return eventEditor;
}
void KODialogManager::connectTypeAhead( KOEventEditor *editor,
KOAgendaView *agenda )
{
if ( editor && agenda ) {
agenda->setTypeAheadReceiver( editor->typeAheadReceiver() );
connect( editor, SIGNAL( focusReceivedSignal() ),
agenda, SLOT( finishTypeAhead() ) );
}
}
void KODialogManager::connectEditor( KOIncidenceEditor*editor )
{
/* connect( editor, SIGNAL( deleteIncidenceSignal( Incidence * ) ),
mMainView, SLOT( deleteIncidence( Incidence * ) ) );*/
connect( mCategoryEditDialog, SIGNAL( categoryConfigChanged() ),
editor, SLOT( updateCategoryConfig() ) );
connect( editor, SIGNAL( editCategories() ),
mCategoryEditDialog, SLOT( show() ) );
connect( editor, SIGNAL( dialogClose( Incidence * ) ),
mMainView, SLOT( dialogClosing( Incidence * ) ) );
connect( editor, SIGNAL( editCanceled( Incidence * ) ),
mMainView, SLOT( editCanceled( Incidence * ) ) );
connect( mMainView, SIGNAL( closingDown() ), editor, SLOT( reject() ) );
connect( editor, SIGNAL( deleteAttendee( Incidence * ) ),
mMainView, SIGNAL( cancelAttendees( Incidence * ) ) );
}
KOTodoEditor *KODialogManager::getTodoEditor()
{
KOTodoEditor *todoEditor = new KOTodoEditor( mMainView->calendar(), mMainView );
connectEditor( todoEditor );
return todoEditor;
}
KOJournalEditor *KODialogManager::getJournalEditor()
{
KOJournalEditor *journalEditor = new KOJournalEditor( mMainView->calendar(), mMainView );
connectEditor( journalEditor );
return journalEditor;
}
void KODialogManager::updateSearchDialog()
{
if (mSearchDialog) mSearchDialog->updateView();
}
<|endoftext|>
|
<commit_before>/***************************************************************************
**
** Copyright (C) 2010 Nokia Corporation and/or its subsidiary(-ies).
** All rights reserved.
** Contact: Nokia Corporation (directui@nokia.com)
**
** This file is part of duihome.
**
** If you have questions regarding the use of this file, please contact
** Nokia at directui@nokia.com.
**
** This library is free software; you can redistribute it and/or
** modify it under the terms of the GNU Lesser General Public
** License version 2.1 as published by the Free Software Foundation
** and appearing in the file LICENSE.LGPL included in the packaging
** of this file.
**
****************************************************************************/
#include "launcher.h"
#include "desktopview.h"
#include "desktop.h"
#include "notificationarea.h"
#include "mainwindow.h"
#include "switcher.h"
#include "statusindicator.h"
#include "contextframeworkcontext.h"
#include "appletspace.h"
#include "quicklaunchbar.h"
#include <DuiViewCreator>
#include <DuiDeviceProfile>
#include <DuiSceneManager>
#include <DuiModalSceneWindow>
#include <DuiPannableViewport>
#include <DuiApplication>
#include <DuiOverlay>
#include <QGraphicsLinearLayout>
#ifdef BENCHMARKS_ON
#include <QTextStream>
#include <QFile>
#include <QTimer>
#include <QTime>
#include <QFileSystemWatcher>
#include <QDir>
// These should really be private variables if one has more than one
// instance of Desktop
static bool benchmarking = false;
static QTime lastUpdate;
static int frameCount = 0;
static int fps = 0;
const int MillisecsInSec = 1000;
const int FpsRefreshInterval = 1000;
void DesktopView::writeFps()
{
QFile file("/tmp/duihome_benchmarks/benchmark_results.txt");
file.open(QIODevice::WriteOnly | QIODevice::Append);
QTextStream ts(&file);
QString fpsString = QString::number(fps);
QDateTime now = QDateTime::currentDateTime();
QString nowString = now.toString(Qt::ISODate);
ts << fpsString << " " << nowString << endl;
file.close();
}
void DesktopView::startBenchmarking()
{
frameCount = 0;
fps = 0;
lastUpdate = QTime::currentTime();
benchmarking = true;
update();
}
void DesktopView::stopBenchmarking()
{
benchmarking = false;
}
#endif
DesktopView::DesktopView(Desktop *desktop) :
DuiWidgetView(desktop),
switcher(new Switcher),
quickLaunchBar(new QuickLaunchBar),
quickLaunchBarWindow(new DuiOverlay),
launcher(new Launcher),
launcherWindow(new DuiModalSceneWindow),
launcherViewport(new DuiPannableViewport(launcherWindow)),
appletSpace(new AppletSpace),
appletSpaceWindow(new DuiModalSceneWindow),
appletSpaceViewport(new DuiPannableViewport(appletSpaceWindow))
{
// Create the main layout that contains the switcher etc.
QGraphicsLinearLayout *mainLayout = new QGraphicsLinearLayout(Qt::Vertical);
mainLayout->setContentsMargins(0, 0, 0, 0);
mainLayout->setSpacing(0);
desktop->setLayout(mainLayout);
// Create phone network status indicator
phoneNetworkIndicator = new PhoneNetworkStatusIndicator(contextFrameworkContext, desktop);
// Create switcher
mainLayout->addItem(switcher);
connect(desktop, SIGNAL(viewportSizePosChanged(const QSizeF &, const QRectF &, const QPointF &)),
switcher, SLOT(viewportSizePosChanged(const QSizeF &, const QRectF &, const QPointF &)));
// Fill the rest with empty space
mainLayout->addStretch();
// Create a quick launch bar
quickLaunchBar = new QuickLaunchBar;
connect(quickLaunchBar, SIGNAL(toggleLauncherButtonClicked()), this, SLOT(toggleLauncher()));
connect(quickLaunchBar, SIGNAL(toggleAppletSpaceButtonClicked()), this, SLOT(toggleAppletSpace()));
// Create a layout for the quick launch bar window
QGraphicsLinearLayout *windowLayout = new QGraphicsLinearLayout();
windowLayout->setContentsMargins(0, 0, 0, 0);
windowLayout->addItem(quickLaunchBar);
quickLaunchBarWindow->setLayout(windowLayout);
quickLaunchBarWindow->setObjectName("QuickLaunchBarOverlay");
MainWindow::instance()->sceneManager()->showWindowNow(quickLaunchBarWindow);
// Put the launcher inside a pannable viewport
launcherViewport->setWidget(launcher);
launcherViewport->setMinimumSize(DuiApplication::activeWindow()->visibleSceneSize());
launcherViewport->setMaximumSize(DuiApplication::activeWindow()->visibleSceneSize());
// Create a layout for the launcher window
windowLayout = new QGraphicsLinearLayout();
windowLayout->setContentsMargins(0, 0, 0, 0);
windowLayout->addItem(launcherViewport);
launcherWindow->setLayout(windowLayout);
launcherWindow->setObjectName("LauncherWindow");
MainWindow::instance()->sceneManager()->hideWindowNow(launcherWindow);
// Put the applet space inside a pannable viewport
connect(appletSpace, SIGNAL(closed()), this, SLOT(toggleAppletSpace()));
appletSpaceViewport->setWidget(appletSpace);
appletSpaceViewport->setMinimumSize(DuiApplication::activeWindow()->visibleSceneSize());
appletSpaceViewport->setMaximumSize(DuiApplication::activeWindow()->visibleSceneSize());
// Create a layout for the applet space window
windowLayout = new QGraphicsLinearLayout();
windowLayout->setContentsMargins(0, 0, 0, 0);
windowLayout->addItem(appletSpaceViewport);
appletSpaceWindow->setLayout(windowLayout);
appletSpaceWindow->setObjectName("AppletSpaceWindow");
MainWindow::instance()->sceneManager()->hideWindowNow(appletSpaceWindow);
#ifdef BENCHMARKS_ON
QDir dir;
if(!dir.exists("/tmp/duihome_benchmarks")) {
dir.mkdir("/tmp/duihome_benchmarks");
}
connect(DuiApplication::instance(), SIGNAL(startBenchmarking()), this, SLOT(startBenchmarking()));
connect(DuiApplication::instance(), SIGNAL(stopBenchmarking()), this, SLOT(stopBenchmarking()));
#endif
}
DesktopView::~DesktopView()
{
delete launcherWindow;
}
#ifdef BENCHMARKS_ON
void DesktopView::paint(QPainter *painter, const QStyleOptionGraphicsItem *option, QWidget *widget)
{
DuiWidgetView::paint(painter, option, widget);
if (benchmarking) {
QTime now = QTime::currentTime();
++frameCount;
if (lastUpdate.msecsTo(now) > FpsRefreshInterval) {
fps = (MillisecsInSec * frameCount) / (lastUpdate.msecsTo(now));
frameCount = 0;
lastUpdate = now;
writeFps();
}
update();
}
}
#endif
void DesktopView::drawBackground(QPainter *painter, const QStyleOptionGraphicsItem *) const
{
// Draw the background image
const QPixmap *pixmap = style()->desktopBackgroundImage();
if (pixmap != NULL) {
// Always draw the background texture without rotation
const QTransform w = painter->worldTransform();
painter->setWorldTransform(QTransform());
// Use the actual screen size for painting the background because it does not rotate
QPointF p = w.map(QPointF(0, 0));
QPointF offset(-p.x() + w.dx(), -p.y() + w.dy());
painter->drawTiledPixmap(QRectF(0, 0, DuiDeviceProfile::instance()->resolution().width(), DuiDeviceProfile::instance()->resolution().height()), *pixmap, offset);
// Reset the transform
painter->setWorldTransform(w);
}
if (!model()->notificationAreaOpen()) {
// Draw the top image
pixmap = style()->desktopBackgroundTop();
if (pixmap != NULL) {
painter->drawTiledPixmap(QRectF(0, -pixmap->height(), geometry().width(), pixmap->height()), *pixmap);
}
}
// Draw the bottom image
pixmap = style()->desktopBackgroundBottom();
if (pixmap != NULL) {
painter->drawTiledPixmap(QRectF(0, geometry().height(), geometry().width(), pixmap->height()), *pixmap);
}
}
QRectF DesktopView::boundingRect() const
{
// The area to be drawn includes the top and bottom images in addition to the actual content
int top = 0;
int bottom = 0;
const QPixmap *topPixmap = style()->desktopBackgroundTop();
const QPixmap *bottomPixmap = style()->desktopBackgroundBottom();
if (topPixmap != NULL) {
top = topPixmap->height();
}
if (bottomPixmap != NULL) {
bottom = bottomPixmap->height();
}
QRectF rect(0, -top, geometry().width(), geometry().height() + top + bottom);
return rect.united(QRectF(0, 0, DuiDeviceProfile::instance()->resolution().width(), DuiDeviceProfile::instance()->resolution().height()));
}
void DesktopView::toggleLauncher()
{
if (launcherWindow->isVisible()) {
hideLauncher();
} else {
showLauncher();
}
}
void DesktopView::showLauncher()
{
launcher->setEnabled(true);
launcher->openRootCategory();
MainWindow::instance()->sceneManager()->showWindow(launcherWindow);
// Set the launcher window below other modal scene windows
// @todo TODO get rid of the hardcoded value when DuiSceneManager enables dynamic allocation of Z values
launcherWindow->parentItem()->setZValue(300);
}
void DesktopView::hideLauncher()
{
// Disable the launcher so that during the disappear animation of
// the dialog it's not possible to launch another application
launcher->setEnabled(false);
// Scroll the launcher above the screen
MainWindow::instance()->sceneManager()->hideWindow(launcherWindow);
}
void DesktopView::toggleAppletSpace()
{
if (appletSpaceWindow->isVisible()) {
appletSpaceWindow->disappear();
appletSpace->setEnabled(false);
} else {
appletSpaceWindow->appear();
appletSpace->setEnabled(true);
}
}
void DesktopView::setGeometry(const QRectF &rect)
{
DuiWidgetView::setGeometry(rect);
// Set the launcher viewport to the size of the desktop
launcherViewport->setMinimumSize(rect.size());
launcherViewport->setMaximumSize(rect.size());
}
DUI_REGISTER_VIEW_NEW(DesktopView, Desktop)
<commit_msg>Changes: Moved the file openrations for benchmarking from writeFps() to start/stopBenchmarking()<commit_after>/***************************************************************************
**
** Copyright (C) 2010 Nokia Corporation and/or its subsidiary(-ies).
** All rights reserved.
** Contact: Nokia Corporation (directui@nokia.com)
**
** This file is part of duihome.
**
** If you have questions regarding the use of this file, please contact
** Nokia at directui@nokia.com.
**
** This library is free software; you can redistribute it and/or
** modify it under the terms of the GNU Lesser General Public
** License version 2.1 as published by the Free Software Foundation
** and appearing in the file LICENSE.LGPL included in the packaging
** of this file.
**
****************************************************************************/
#include "launcher.h"
#include "desktopview.h"
#include "desktop.h"
#include "notificationarea.h"
#include "mainwindow.h"
#include "switcher.h"
#include "statusindicator.h"
#include "contextframeworkcontext.h"
#include "appletspace.h"
#include "quicklaunchbar.h"
#include <DuiViewCreator>
#include <DuiDeviceProfile>
#include <DuiSceneManager>
#include <DuiModalSceneWindow>
#include <DuiPannableViewport>
#include <DuiApplication>
#include <DuiOverlay>
#include <QGraphicsLinearLayout>
#ifdef BENCHMARKS_ON
#include <QTextStream>
#include <QFile>
#include <QTimer>
#include <QTime>
#include <QFileSystemWatcher>
#include <QDir>
// These should really be private variables if one has more than one
// instance of Desktop
static bool benchmarking = false;
static QTime lastUpdate;
static int frameCount = 0;
static int fps = 0;
static QFile* fpsFile;
static QTextStream* fpsStream;
const int MillisecsInSec = 1000;
const int FpsRefreshInterval = 1000;
void DesktopView::writeFps()
{
if (!benchmarking)
return;
QString fpsString = QString::number(fps);
QDateTime now = QDateTime::currentDateTime();
QString nowString = now.toString(Qt::ISODate);
*fpsStream << fpsString << " " << nowString << endl;
fpsStream->flush();
}
void DesktopView::startBenchmarking()
{
fpsFile = new QFile("/tmp/duihome_benchmarks/benchmark_results.txt");
fpsFile->open(QIODevice::WriteOnly | QIODevice::Append);
fpsStream = new QTextStream(fpsFile);
frameCount = 0;
fps = 0;
lastUpdate = QTime::currentTime();
benchmarking = true;
update();
}
void DesktopView::stopBenchmarking()
{
benchmarking = false;
delete fpsStream;
delete fpsFile;
}
#endif
DesktopView::DesktopView(Desktop *desktop) :
DuiWidgetView(desktop),
switcher(new Switcher),
quickLaunchBar(new QuickLaunchBar),
quickLaunchBarWindow(new DuiOverlay),
launcher(new Launcher),
launcherWindow(new DuiModalSceneWindow),
launcherViewport(new DuiPannableViewport(launcherWindow)),
appletSpace(new AppletSpace),
appletSpaceWindow(new DuiModalSceneWindow),
appletSpaceViewport(new DuiPannableViewport(appletSpaceWindow))
{
// Create the main layout that contains the switcher etc.
QGraphicsLinearLayout *mainLayout = new QGraphicsLinearLayout(Qt::Vertical);
mainLayout->setContentsMargins(0, 0, 0, 0);
mainLayout->setSpacing(0);
desktop->setLayout(mainLayout);
// Create phone network status indicator
phoneNetworkIndicator = new PhoneNetworkStatusIndicator(contextFrameworkContext, desktop);
// Create switcher
mainLayout->addItem(switcher);
connect(desktop, SIGNAL(viewportSizePosChanged(const QSizeF &, const QRectF &, const QPointF &)),
switcher, SLOT(viewportSizePosChanged(const QSizeF &, const QRectF &, const QPointF &)));
// Fill the rest with empty space
mainLayout->addStretch();
// Create a quick launch bar
quickLaunchBar = new QuickLaunchBar;
connect(quickLaunchBar, SIGNAL(toggleLauncherButtonClicked()), this, SLOT(toggleLauncher()));
connect(quickLaunchBar, SIGNAL(toggleAppletSpaceButtonClicked()), this, SLOT(toggleAppletSpace()));
// Create a layout for the quick launch bar window
QGraphicsLinearLayout *windowLayout = new QGraphicsLinearLayout();
windowLayout->setContentsMargins(0, 0, 0, 0);
windowLayout->addItem(quickLaunchBar);
quickLaunchBarWindow->setLayout(windowLayout);
quickLaunchBarWindow->setObjectName("QuickLaunchBarOverlay");
MainWindow::instance()->sceneManager()->showWindowNow(quickLaunchBarWindow);
// Put the launcher inside a pannable viewport
launcherViewport->setWidget(launcher);
launcherViewport->setMinimumSize(DuiApplication::activeWindow()->visibleSceneSize());
launcherViewport->setMaximumSize(DuiApplication::activeWindow()->visibleSceneSize());
// Create a layout for the launcher window
windowLayout = new QGraphicsLinearLayout();
windowLayout->setContentsMargins(0, 0, 0, 0);
windowLayout->addItem(launcherViewport);
launcherWindow->setLayout(windowLayout);
launcherWindow->setObjectName("LauncherWindow");
MainWindow::instance()->sceneManager()->hideWindowNow(launcherWindow);
// Put the applet space inside a pannable viewport
connect(appletSpace, SIGNAL(closed()), this, SLOT(toggleAppletSpace()));
appletSpaceViewport->setWidget(appletSpace);
appletSpaceViewport->setMinimumSize(DuiApplication::activeWindow()->visibleSceneSize());
appletSpaceViewport->setMaximumSize(DuiApplication::activeWindow()->visibleSceneSize());
// Create a layout for the applet space window
windowLayout = new QGraphicsLinearLayout();
windowLayout->setContentsMargins(0, 0, 0, 0);
windowLayout->addItem(appletSpaceViewport);
appletSpaceWindow->setLayout(windowLayout);
appletSpaceWindow->setObjectName("AppletSpaceWindow");
MainWindow::instance()->sceneManager()->hideWindowNow(appletSpaceWindow);
#ifdef BENCHMARKS_ON
QDir dir;
if(!dir.exists("/tmp/duihome_benchmarks")) {
dir.mkdir("/tmp/duihome_benchmarks");
}
connect(DuiApplication::instance(), SIGNAL(startBenchmarking()), this, SLOT(startBenchmarking()));
connect(DuiApplication::instance(), SIGNAL(stopBenchmarking()), this, SLOT(stopBenchmarking()));
#endif
}
DesktopView::~DesktopView()
{
delete launcherWindow;
}
#ifdef BENCHMARKS_ON
void DesktopView::paint(QPainter *painter, const QStyleOptionGraphicsItem *option, QWidget *widget)
{
DuiWidgetView::paint(painter, option, widget);
if (benchmarking) {
QTime now = QTime::currentTime();
++frameCount;
if (lastUpdate.msecsTo(now) > FpsRefreshInterval) {
fps = (MillisecsInSec * frameCount) / (lastUpdate.msecsTo(now));
frameCount = 0;
lastUpdate = now;
writeFps();
}
update();
}
}
#endif
void DesktopView::drawBackground(QPainter *painter, const QStyleOptionGraphicsItem *) const
{
// Draw the background image
const QPixmap *pixmap = style()->desktopBackgroundImage();
if (pixmap != NULL) {
// Always draw the background texture without rotation
const QTransform w = painter->worldTransform();
painter->setWorldTransform(QTransform());
// Use the actual screen size for painting the background because it does not rotate
QPointF p = w.map(QPointF(0, 0));
QPointF offset(-p.x() + w.dx(), -p.y() + w.dy());
painter->drawTiledPixmap(QRectF(0, 0, DuiDeviceProfile::instance()->resolution().width(), DuiDeviceProfile::instance()->resolution().height()), *pixmap, offset);
// Reset the transform
painter->setWorldTransform(w);
}
if (!model()->notificationAreaOpen()) {
// Draw the top image
pixmap = style()->desktopBackgroundTop();
if (pixmap != NULL) {
painter->drawTiledPixmap(QRectF(0, -pixmap->height(), geometry().width(), pixmap->height()), *pixmap);
}
}
// Draw the bottom image
pixmap = style()->desktopBackgroundBottom();
if (pixmap != NULL) {
painter->drawTiledPixmap(QRectF(0, geometry().height(), geometry().width(), pixmap->height()), *pixmap);
}
}
QRectF DesktopView::boundingRect() const
{
// The area to be drawn includes the top and bottom images in addition to the actual content
int top = 0;
int bottom = 0;
const QPixmap *topPixmap = style()->desktopBackgroundTop();
const QPixmap *bottomPixmap = style()->desktopBackgroundBottom();
if (topPixmap != NULL) {
top = topPixmap->height();
}
if (bottomPixmap != NULL) {
bottom = bottomPixmap->height();
}
QRectF rect(0, -top, geometry().width(), geometry().height() + top + bottom);
return rect.united(QRectF(0, 0, DuiDeviceProfile::instance()->resolution().width(), DuiDeviceProfile::instance()->resolution().height()));
}
void DesktopView::toggleLauncher()
{
if (launcherWindow->isVisible()) {
hideLauncher();
} else {
showLauncher();
}
}
void DesktopView::showLauncher()
{
launcher->setEnabled(true);
launcher->openRootCategory();
MainWindow::instance()->sceneManager()->showWindow(launcherWindow);
// Set the launcher window below other modal scene windows
// @todo TODO get rid of the hardcoded value when DuiSceneManager enables dynamic allocation of Z values
launcherWindow->parentItem()->setZValue(300);
}
void DesktopView::hideLauncher()
{
// Disable the launcher so that during the disappear animation of
// the dialog it's not possible to launch another application
launcher->setEnabled(false);
// Scroll the launcher above the screen
MainWindow::instance()->sceneManager()->hideWindow(launcherWindow);
}
void DesktopView::toggleAppletSpace()
{
if (appletSpaceWindow->isVisible()) {
appletSpaceWindow->disappear();
appletSpace->setEnabled(false);
} else {
appletSpaceWindow->appear();
appletSpace->setEnabled(true);
}
}
void DesktopView::setGeometry(const QRectF &rect)
{
DuiWidgetView::setGeometry(rect);
// Set the launcher viewport to the size of the desktop
launcherViewport->setMinimumSize(rect.size());
launcherViewport->setMaximumSize(rect.size());
}
DUI_REGISTER_VIEW_NEW(DesktopView, Desktop)
<|endoftext|>
|
<commit_before>/* fileInstaller.cc KPilot
**
** Copyright (C) 1998-2001 by Dan Pilone
**
** This is a class that does "the work" of adding and deleting
** files in the pending_install directory of KPilot. It is used
** by the fileInstallWidget and by the daemon's drag-and-drop
** file accepter.
*/
/*
** 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 in a file called COPYING; if not, write to
** the Free Software Foundation, Inc., 59 Temple Place, Suite 330, Boston,
** MA 02111-1307, USA.
*/
/*
** Bug reports and questions can be sent to kde-pim@kde.org
*/
static const char *fileinstaller_id =
"$Id$";
#ifndef _KPILOT_OPTIONS_H
#include "options.h"
#endif
#include <unistd.h>
#ifndef QSTRING_H
#include <qstring.h>
#endif
#ifndef QSTRLIST_H
#include <qstrlist.h>
#endif
#ifndef QDIR_H
#include <qdir.h>
#endif
#ifndef _KGLOBAL_H
#include <kglobal.h>
#endif
#ifndef _KSTDDIRS_H
#include <kstddirs.h>
#endif
#ifndef _KURL_H
#include <kurl.h>
#endif
#ifndef _KIO_NETACCESS_H
#include <kio/netaccess.h>
#endif
#include "fileInstaller.moc"
FileInstaller::FileInstaller() :
enabled(true)
{
FUNCTIONSETUP;
fDirName = KGlobal::dirs()->saveLocation("data",
CSL1("kpilot/pending_install/"));
fPendingCopies = 0;
(void) fileinstaller_id;
}
/* virtual */ FileInstaller::~FileInstaller()
{
FUNCTIONSETUP;
}
void FileInstaller::clearPending()
{
FUNCTIONSETUP;
unsigned int i;
QDir installDir(fDirName);
// Start from 2 to skip . and ..
//
for (i = 2; i < installDir.count(); i++)
{
QFile::remove(fDirName + installDir[i]);
}
if (i > 2)
{
emit filesChanged();
}
}
/* virtual */ bool FileInstaller::runCopy(const QString & s)
{
FUNCTIONSETUP;
#ifdef DEBUG
DEBUGDAEMON << fname << ": Copying " << s << endl;
#endif
KURL srcName(s);
KURL destDir(fDirName + CSL1("/") + srcName.filename());
return KIO::NetAccess::copy(srcName, destDir);
}
void FileInstaller::addFiles(const QStringList & fileList)
{
FUNCTIONSETUP;
if (!enabled) return;
unsigned int succ = 0;
for(QStringList::ConstIterator it = fileList.begin();
it != fileList.end(); ++it)
{
if (runCopy(*it))
succ++;
}
if (succ)
{
emit filesChanged();
}
}
void FileInstaller::addFile(const QString & file)
{
FUNCTIONSETUP;
if (!enabled) return;
if (runCopy(file))
{
emit(filesChanged());
}
}
/* slot */ void FileInstaller::copyCompleted()
{
FUNCTIONSETUP;
}
const QStringList FileInstaller::fileNames() const
{
FUNCTIONSETUP;
QDir installDir(fDirName);
return installDir.entryList(QDir::Files |
QDir::NoSymLinks | QDir::Readable);
}
/* slot */ void FileInstaller::setEnabled(bool b)
{
FUNCTIONSETUP;
enabled=b;
}
<commit_msg>Use the new methods instead of deprecates ones.<commit_after>/* fileInstaller.cc KPilot
**
** Copyright (C) 1998-2001 by Dan Pilone
**
** This is a class that does "the work" of adding and deleting
** files in the pending_install directory of KPilot. It is used
** by the fileInstallWidget and by the daemon's drag-and-drop
** file accepter.
*/
/*
** 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 in a file called COPYING; if not, write to
** the Free Software Foundation, Inc., 59 Temple Place, Suite 330, Boston,
** MA 02111-1307, USA.
*/
/*
** Bug reports and questions can be sent to kde-pim@kde.org
*/
static const char *fileinstaller_id =
"$Id$";
#ifndef _KPILOT_OPTIONS_H
#include "options.h"
#endif
#include <unistd.h>
#ifndef QSTRING_H
#include <qstring.h>
#endif
#ifndef QSTRLIST_H
#include <qstrlist.h>
#endif
#ifndef QDIR_H
#include <qdir.h>
#endif
#ifndef _KGLOBAL_H
#include <kglobal.h>
#endif
#ifndef _KSTDDIRS_H
#include <kstddirs.h>
#endif
#ifndef _KURL_H
#include <kurl.h>
#endif
#ifndef _KIO_NETACCESS_H
#include <kio/netaccess.h>
#endif
#include "fileInstaller.moc"
FileInstaller::FileInstaller() :
enabled(true)
{
FUNCTIONSETUP;
fDirName = KGlobal::dirs()->saveLocation("data",
CSL1("kpilot/pending_install/"));
fPendingCopies = 0;
(void) fileinstaller_id;
}
/* virtual */ FileInstaller::~FileInstaller()
{
FUNCTIONSETUP;
}
void FileInstaller::clearPending()
{
FUNCTIONSETUP;
unsigned int i;
QDir installDir(fDirName);
// Start from 2 to skip . and ..
//
for (i = 2; i < installDir.count(); i++)
{
QFile::remove(fDirName + installDir[i]);
}
if (i > 2)
{
emit filesChanged();
}
}
/* virtual */ bool FileInstaller::runCopy(const QString & s)
{
FUNCTIONSETUP;
#ifdef DEBUG
DEBUGDAEMON << fname << ": Copying " << s << endl;
#endif
KURL srcName(s);
KURL destDir(fDirName + CSL1("/") + srcName.filename());
return KIO::NetAccess::copy(srcName, destDir, 0L);
}
void FileInstaller::addFiles(const QStringList & fileList)
{
FUNCTIONSETUP;
if (!enabled) return;
unsigned int succ = 0;
for(QStringList::ConstIterator it = fileList.begin();
it != fileList.end(); ++it)
{
if (runCopy(*it))
succ++;
}
if (succ)
{
emit filesChanged();
}
}
void FileInstaller::addFile(const QString & file)
{
FUNCTIONSETUP;
if (!enabled) return;
if (runCopy(file))
{
emit(filesChanged());
}
}
/* slot */ void FileInstaller::copyCompleted()
{
FUNCTIONSETUP;
}
const QStringList FileInstaller::fileNames() const
{
FUNCTIONSETUP;
QDir installDir(fDirName);
return installDir.entryList(QDir::Files |
QDir::NoSymLinks | QDir::Readable);
}
/* slot */ void FileInstaller::setEnabled(bool b)
{
FUNCTIONSETUP;
enabled=b;
}
<|endoftext|>
|
<commit_before>/* KPilot
**
** Copyright (C) 1998-2001 by Dan Pilone
**
** This is a class that does "the work" of adding and deleting
** files in the pending_install directory of KPilot. It is used
** by the fileInstallWidget and by the daemon's drag-and-drop
** file accepter.
*/
/*
** 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 in a file called COPYING; if not, write to
** the Free Software Foundation, Inc., 59 Temple Place, Suite 330, Boston,
** MA 02111-1307, USA.
*/
/*
** Bug reports and questions can be sent to kde-pim@kde.org
*/
static const char *fileinstaller_id =
"$Id$";
#include "options.h"
#include <unistd.h>
#include <qstring.h>
#include <qstrlist.h>
#include <qdir.h>
#include <kglobal.h>
#include <kstandarddirs.h>
#include <kurl.h>
#include <kio/netaccess.h>
#include <kmessagebox.h>
#include "fileInstaller.moc"
FileInstaller::FileInstaller() :
enabled(true)
{
FUNCTIONSETUP;
fDirName = KGlobal::dirs()->saveLocation("data",
CSL1("kpilot/pending_install/"));
fPendingCopies = 0;
(void) fileinstaller_id;
}
/* virtual */ FileInstaller::~FileInstaller()
{
FUNCTIONSETUP;
}
void FileInstaller::clearPending()
{
FUNCTIONSETUP;
unsigned int i;
QDir installDir(fDirName);
// Start from 2 to skip . and ..
//
for (i = 2; i < installDir.count(); i++)
{
QFile::remove(fDirName + installDir[i]);
}
if (i > 2)
{
emit filesChanged();
}
}
/* virtual */ bool FileInstaller::runCopy(const QString & s, QWidget* w )
{
FUNCTIONSETUP;
if(!(s.endsWith("pdb", false) || s.endsWith("prc", false))) {
KMessageBox::detailedSorry(w, i18n("Cannot install %1").arg(s),
i18n("Only PalmOS database files (like *.pdb and *.prc) can be installed by the file installer."));
return false;
}
#ifdef DEBUG
DEBUGDAEMON << fname << ": Copying " << s << endl;
#endif
KURL srcName(s);
KURL destDir(fDirName + CSL1("/") + srcName.filename());
#if KDE_IS_VERSION(3,1,9)
return KIO::NetAccess::copy(srcName, destDir, w);
#else
return KIO::NetAccess::copy(srcName,destDir);
#endif
}
void FileInstaller::addFiles(const QStringList & fileList, QWidget* w)
{
FUNCTIONSETUP;
if (!enabled) return;
unsigned int succ = 0;
for(QStringList::ConstIterator it = fileList.begin();
it != fileList.end(); ++it)
{
if (runCopy( *it, w ))
succ++;
}
if (succ)
{
emit filesChanged();
}
}
void FileInstaller::addFile( const QString & file, QWidget* w )
{
FUNCTIONSETUP;
if (!enabled) return;
if (runCopy(file, w))
{
emit(filesChanged());
}
}
/* slot */ void FileInstaller::copyCompleted()
{
FUNCTIONSETUP;
}
const QStringList FileInstaller::fileNames() const
{
FUNCTIONSETUP;
QDir installDir(fDirName);
return installDir.entryList(QDir::Files |
QDir::NoSymLinks | QDir::Readable);
}
/* slot */ void FileInstaller::setEnabled(bool b)
{
FUNCTIONSETUP;
enabled=b;
}
<commit_msg>KDE_NO_COMPAT fixes<commit_after>/* KPilot
**
** Copyright (C) 1998-2001 by Dan Pilone
**
** This is a class that does "the work" of adding and deleting
** files in the pending_install directory of KPilot. It is used
** by the fileInstallWidget and by the daemon's drag-and-drop
** file accepter.
*/
/*
** 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 in a file called COPYING; if not, write to
** the Free Software Foundation, Inc., 59 Temple Place, Suite 330, Boston,
** MA 02111-1307, USA.
*/
/*
** Bug reports and questions can be sent to kde-pim@kde.org
*/
static const char *fileinstaller_id =
"$Id$";
#include "options.h"
#include <unistd.h>
#include <qstring.h>
#include <qstrlist.h>
#include <qdir.h>
#include <kglobal.h>
#include <kstandarddirs.h>
#include <kurl.h>
#include <kio/netaccess.h>
#include <kmessagebox.h>
#include "fileInstaller.moc"
FileInstaller::FileInstaller() :
enabled(true)
{
FUNCTIONSETUP;
fDirName = KGlobal::dirs()->saveLocation("data",
CSL1("kpilot/pending_install/"));
fPendingCopies = 0;
(void) fileinstaller_id;
}
/* virtual */ FileInstaller::~FileInstaller()
{
FUNCTIONSETUP;
}
void FileInstaller::clearPending()
{
FUNCTIONSETUP;
unsigned int i;
QDir installDir(fDirName);
// Start from 2 to skip . and ..
//
for (i = 2; i < installDir.count(); i++)
{
QFile::remove(fDirName + installDir[i]);
}
if (i > 2)
{
emit filesChanged();
}
}
/* virtual */ bool FileInstaller::runCopy(const QString & s, QWidget* w )
{
FUNCTIONSETUP;
if(!(s.endsWith("pdb", false) || s.endsWith("prc", false))) {
KMessageBox::detailedSorry(w, i18n("Cannot install %1").arg(s),
i18n("Only PalmOS database files (like *.pdb and *.prc) can be installed by the file installer."));
return false;
}
#ifdef DEBUG
DEBUGDAEMON << fname << ": Copying " << s << endl;
#endif
KURL srcName(s);
KURL destDir(fDirName + CSL1("/") + srcName.fileName());
#if KDE_IS_VERSION(3,1,9)
return KIO::NetAccess::copy(srcName, destDir, w);
#else
return KIO::NetAccess::copy(srcName,destDir);
#endif
}
void FileInstaller::addFiles(const QStringList & fileList, QWidget* w)
{
FUNCTIONSETUP;
if (!enabled) return;
unsigned int succ = 0;
for(QStringList::ConstIterator it = fileList.begin();
it != fileList.end(); ++it)
{
if (runCopy( *it, w ))
succ++;
}
if (succ)
{
emit filesChanged();
}
}
void FileInstaller::addFile( const QString & file, QWidget* w )
{
FUNCTIONSETUP;
if (!enabled) return;
if (runCopy(file, w))
{
emit(filesChanged());
}
}
/* slot */ void FileInstaller::copyCompleted()
{
FUNCTIONSETUP;
}
const QStringList FileInstaller::fileNames() const
{
FUNCTIONSETUP;
QDir installDir(fDirName);
return installDir.entryList(QDir::Files |
QDir::NoSymLinks | QDir::Readable);
}
/* slot */ void FileInstaller::setEnabled(bool b)
{
FUNCTIONSETUP;
enabled=b;
}
<|endoftext|>
|
<commit_before>/*
This file is part of the kolab resource - the implementation of the
Kolab storage format. See www.kolab.org for documentation on this.
Copyright (c) 2004 Bo Thorsen <bo@sonofthor.dk>
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.
In addition, as a special exception, the copyright holders give
permission to link the code of this program with any edition of
the Qt library by Trolltech AS, Norway (or with modified versions
of Qt that use the same license as Qt), and distribute linked
combinations including the two. You must obey the GNU General
Public License in all respects for all of the code used other than
Qt. If you modify this file, you may extend this exception to
your version of the file, but you are not obligated to do so. If
you do not wish to do so, delete this exception statement from
your version.
*/
#include "task.h"
#include <libkcal/todo.h>
#include <kdebug.h>
using namespace Kolab;
KCal::Todo* Task::xmlToTask( const QString& xml, const QString& tz )
{
Task task( tz );
task.load( xml );
KCal::Todo* todo = new KCal::Todo();
task.saveTo( todo );
return todo;
}
QString Task::taskToXML( KCal::Todo* todo, const QString& tz )
{
Task task( tz, todo );
return task.saveXML();
}
Task::Task( const QString& tz, KCal::Todo* task )
: Incidence( tz ), mPriority( 5 ), mPercentCompleted( 0 ),
mStatus( KCal::Incidence::StatusNone ),
mHasStartDate( false ), mHasDueDate( false ),
mHasCompletedDate( false )
{
if ( task )
setFields( task );
}
Task::~Task()
{
}
void Task::setPriority( int priority )
{
mPriority = priority;
}
int Task::priority() const
{
return mPriority;
}
void Task::setPercentCompleted( int percent )
{
mPercentCompleted = percent;
}
int Task::percentCompleted() const
{
return mPercentCompleted;
}
void Task::setStatus( KCal::Incidence::Status status )
{
mStatus = status;
}
KCal::Incidence::Status Task::status() const
{
return mStatus;
}
void Task::setParent( const QString& parentUid )
{
mParent = parentUid;
}
QString Task::parent() const
{
return mParent;
}
void Task::setDueDate( const QDateTime& date )
{
mDueDate = date;
mHasDueDate = true;
}
QDateTime Task::dueDate() const
{
return mDueDate;
}
void Task::setHasStartDate( bool v )
{
mHasStartDate = v;
}
bool Task::hasStartDate() const
{
return mHasStartDate;
}
bool Task::hasDueDate() const
{
return mHasDueDate;
}
void Task::setCompletedDate( const QDateTime& date )
{
mCompletedDate = date;
mHasCompletedDate = true;
}
QDateTime Task::completedDate() const
{
return mCompletedDate;
}
bool Task::hasCompletedDate() const
{
return mHasCompletedDate;
}
bool Task::loadAttribute( QDomElement& element )
{
QString tagName = element.tagName();
if ( tagName == "priority" ) {
bool ok;
int priority = element.text().toInt( &ok );
if ( !ok || priority < 0 || priority > 9 )
priority = 5;
setPriority( priority );
} else if ( tagName == "completed" ) {
bool ok;
int percent = element.text().toInt( &ok );
if ( !ok || percent < 0 || percent > 100 )
percent = 0;
setPercentCompleted( percent );
} else if ( tagName == "status" ) {
if ( element.text() == "in-progress" )
setStatus( KCal::Incidence::StatusInProcess );
else if ( element.text() == "completed" )
setStatus( KCal::Incidence::StatusCompleted );
else if ( element.text() == "waiting-on-someone-else" )
setStatus( KCal::Incidence::StatusNeedsAction );
else if ( element.text() == "deferred" )
// Guessing a status here
setStatus( KCal::Incidence::StatusCanceled );
else
// Default
setStatus( KCal::Incidence::StatusNone );
} else if ( tagName == "due-date" )
setDueDate( stringToDateTime( element.text() ) );
else if ( tagName == "parent" )
setParent( element.text() );
else if ( tagName == "x-completed-date" )
setCompletedDate( stringToDateTime( element.text() ) );
else if ( tagName == "start-date" ) {
setHasStartDate( true );
setStartDate( element.text() );
} else
return Incidence::loadAttribute( element );
// We handled this
return true;
}
bool Task::saveAttributes( QDomElement& element ) const
{
// Save the base class elements
Incidence::saveAttributes( element );
writeString( element, "priority", QString::number( priority() ) );
writeString( element, "completed", QString::number( percentCompleted() ) );
switch( status() ) {
case KCal::Incidence::StatusInProcess:
writeString( element, "status", "in-progress" );
break;
case KCal::Incidence::StatusCompleted:
writeString( element, "status", "completed" );
break;
case KCal::Incidence::StatusNeedsAction:
writeString( element, "status", "waiting-on-someone-else" );
break;
case KCal::Incidence::StatusCanceled:
writeString( element, "status", "deferred" );
break;
case KCal::Incidence::StatusNone:
writeString( element, "status", "not-started" );
break;
case KCal::Incidence::StatusTentative:
case KCal::Incidence::StatusConfirmed:
case KCal::Incidence::StatusDraft:
case KCal::Incidence::StatusFinal:
case KCal::Incidence::StatusX:
// All of these are saved as StatusNone.
writeString( element, "status", "not-started" );
break;
}
if ( hasDueDate() )
writeString( element, "due-date", dateTimeToString( dueDate() ) );
if ( !parent().isNull() )
writeString( element, "parent", parent() );
if ( hasCompletedDate() && percentCompleted() == 100)
writeString( element, "x-completed-date", dateTimeToString( completedDate() ) );
return true;
}
bool Task::loadXML( const QDomDocument& document )
{
QDomElement top = document.documentElement();
if ( top.tagName() != "task" ) {
qWarning( "XML error: Top tag was %s instead of the expected task",
top.tagName().ascii() );
return false;
}
setHasStartDate( false ); // todo's don't necessarily have one
for ( QDomNode n = top.firstChild(); !n.isNull(); n = n.nextSibling() ) {
if ( n.isComment() )
continue;
if ( n.isElement() ) {
QDomElement e = n.toElement();
if ( !loadAttribute( e ) )
// TODO: Unhandled tag - save for later storage
kdDebug() << "Warning: Unhandled tag " << e.tagName() << endl;
} else
kdDebug() << "Node is not a comment or an element???" << endl;
}
return true;
}
QString Task::saveXML() const
{
QDomDocument document = domTree();
QDomElement element = document.createElement( "task" );
element.setAttribute( "version", "1.0" );
saveAttributes( element );
if ( !hasStartDate() ) {
// events and journals always have a start date, but tasks don't.
// Remove the entry done by the inherited save above, because we
// don't have one.
QDomNodeList l = element.elementsByTagName( "start-date" );
Q_ASSERT( l.count() == 1 );
element.removeChild( l.item( 0 ) );
}
document.appendChild( element );
return document.toString();
}
void Task::setFields( const KCal::Todo* task )
{
Incidence::setFields( task );
setPriority( task->priority() );
setPercentCompleted( task->percentComplete() );
setStatus( task->status() );
setHasStartDate( task->hasStartDate() );
if ( task->hasDueDate() )
setDueDate( localToUTC( task->dtDue() ) );
else
mHasDueDate = false;
if ( task->relatedTo() )
setParent( task->relatedTo()->uid() );
else
setParent( QString::null );
if ( task->hasCompletedDate() && task->percentComplete() == 100 )
setCompletedDate( localToUTC( task->completed() ) );
else
mHasCompletedDate = false;
}
void Task::saveTo( KCal::Todo* task )
{
Incidence::saveTo( task );
task->setPriority( priority() );
task->setPercentComplete( percentCompleted() );
task->setStatus( status() );
task->setHasStartDate( hasStartDate() );
task->setHasDueDate( hasDueDate() );
if ( hasDueDate() )
task->setDtDue( utcToLocal( dueDate() ) );
if ( !parent().isNull() )
task->setRelatedToUid( parent() );
if ( hasCompletedDate() && task->percentComplete() == 100 )
task->setCompleted( utcToLocal( mCompletedDate ) );
}
<commit_msg>After long hours of tracking down the problem that the hierarchy of the to-do list was lost in the kolab resource, here's the fix. Every now and then korganizer's tasks would loose their parents, mostly when conflict resolution is triggered.<commit_after>/*
This file is part of the kolab resource - the implementation of the
Kolab storage format. See www.kolab.org for documentation on this.
Copyright (c) 2004 Bo Thorsen <bo@sonofthor.dk>
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.
In addition, as a special exception, the copyright holders give
permission to link the code of this program with any edition of
the Qt library by Trolltech AS, Norway (or with modified versions
of Qt that use the same license as Qt), and distribute linked
combinations including the two. You must obey the GNU General
Public License in all respects for all of the code used other than
Qt. If you modify this file, you may extend this exception to
your version of the file, but you are not obligated to do so. If
you do not wish to do so, delete this exception statement from
your version.
*/
#include "task.h"
#include <libkcal/todo.h>
#include <kdebug.h>
using namespace Kolab;
KCal::Todo* Task::xmlToTask( const QString& xml, const QString& tz )
{
Task task( tz );
task.load( xml );
KCal::Todo* todo = new KCal::Todo();
task.saveTo( todo );
return todo;
}
QString Task::taskToXML( KCal::Todo* todo, const QString& tz )
{
Task task( tz, todo );
return task.saveXML();
}
Task::Task( const QString& tz, KCal::Todo* task )
: Incidence( tz ), mPriority( 5 ), mPercentCompleted( 0 ),
mStatus( KCal::Incidence::StatusNone ),
mHasStartDate( false ), mHasDueDate( false ),
mHasCompletedDate( false )
{
if ( task )
setFields( task );
}
Task::~Task()
{
}
void Task::setPriority( int priority )
{
mPriority = priority;
}
int Task::priority() const
{
return mPriority;
}
void Task::setPercentCompleted( int percent )
{
mPercentCompleted = percent;
}
int Task::percentCompleted() const
{
return mPercentCompleted;
}
void Task::setStatus( KCal::Incidence::Status status )
{
mStatus = status;
}
KCal::Incidence::Status Task::status() const
{
return mStatus;
}
void Task::setParent( const QString& parentUid )
{
mParent = parentUid;
}
QString Task::parent() const
{
return mParent;
}
void Task::setDueDate( const QDateTime& date )
{
mDueDate = date;
mHasDueDate = true;
}
QDateTime Task::dueDate() const
{
return mDueDate;
}
void Task::setHasStartDate( bool v )
{
mHasStartDate = v;
}
bool Task::hasStartDate() const
{
return mHasStartDate;
}
bool Task::hasDueDate() const
{
return mHasDueDate;
}
void Task::setCompletedDate( const QDateTime& date )
{
mCompletedDate = date;
mHasCompletedDate = true;
}
QDateTime Task::completedDate() const
{
return mCompletedDate;
}
bool Task::hasCompletedDate() const
{
return mHasCompletedDate;
}
bool Task::loadAttribute( QDomElement& element )
{
QString tagName = element.tagName();
if ( tagName == "priority" ) {
bool ok;
int priority = element.text().toInt( &ok );
if ( !ok || priority < 0 || priority > 9 )
priority = 5;
setPriority( priority );
} else if ( tagName == "completed" ) {
bool ok;
int percent = element.text().toInt( &ok );
if ( !ok || percent < 0 || percent > 100 )
percent = 0;
setPercentCompleted( percent );
} else if ( tagName == "status" ) {
if ( element.text() == "in-progress" )
setStatus( KCal::Incidence::StatusInProcess );
else if ( element.text() == "completed" )
setStatus( KCal::Incidence::StatusCompleted );
else if ( element.text() == "waiting-on-someone-else" )
setStatus( KCal::Incidence::StatusNeedsAction );
else if ( element.text() == "deferred" )
// Guessing a status here
setStatus( KCal::Incidence::StatusCanceled );
else
// Default
setStatus( KCal::Incidence::StatusNone );
} else if ( tagName == "due-date" )
setDueDate( stringToDateTime( element.text() ) );
else if ( tagName == "parent" )
setParent( element.text() );
else if ( tagName == "x-completed-date" )
setCompletedDate( stringToDateTime( element.text() ) );
else if ( tagName == "start-date" ) {
setHasStartDate( true );
setStartDate( element.text() );
} else
return Incidence::loadAttribute( element );
// We handled this
return true;
}
bool Task::saveAttributes( QDomElement& element ) const
{
// Save the base class elements
Incidence::saveAttributes( element );
writeString( element, "priority", QString::number( priority() ) );
writeString( element, "completed", QString::number( percentCompleted() ) );
switch( status() ) {
case KCal::Incidence::StatusInProcess:
writeString( element, "status", "in-progress" );
break;
case KCal::Incidence::StatusCompleted:
writeString( element, "status", "completed" );
break;
case KCal::Incidence::StatusNeedsAction:
writeString( element, "status", "waiting-on-someone-else" );
break;
case KCal::Incidence::StatusCanceled:
writeString( element, "status", "deferred" );
break;
case KCal::Incidence::StatusNone:
writeString( element, "status", "not-started" );
break;
case KCal::Incidence::StatusTentative:
case KCal::Incidence::StatusConfirmed:
case KCal::Incidence::StatusDraft:
case KCal::Incidence::StatusFinal:
case KCal::Incidence::StatusX:
// All of these are saved as StatusNone.
writeString( element, "status", "not-started" );
break;
}
if ( hasDueDate() )
writeString( element, "due-date", dateTimeToString( dueDate() ) );
if ( !parent().isNull() )
writeString( element, "parent", parent() );
if ( hasCompletedDate() && percentCompleted() == 100)
writeString( element, "x-completed-date", dateTimeToString( completedDate() ) );
return true;
}
bool Task::loadXML( const QDomDocument& document )
{
QDomElement top = document.documentElement();
if ( top.tagName() != "task" ) {
qWarning( "XML error: Top tag was %s instead of the expected task",
top.tagName().ascii() );
return false;
}
setHasStartDate( false ); // todo's don't necessarily have one
for ( QDomNode n = top.firstChild(); !n.isNull(); n = n.nextSibling() ) {
if ( n.isComment() )
continue;
if ( n.isElement() ) {
QDomElement e = n.toElement();
if ( !loadAttribute( e ) )
// TODO: Unhandled tag - save for later storage
kdDebug() << "Warning: Unhandled tag " << e.tagName() << endl;
} else
kdDebug() << "Node is not a comment or an element???" << endl;
}
return true;
}
QString Task::saveXML() const
{
QDomDocument document = domTree();
QDomElement element = document.createElement( "task" );
element.setAttribute( "version", "1.0" );
saveAttributes( element );
if ( !hasStartDate() ) {
// events and journals always have a start date, but tasks don't.
// Remove the entry done by the inherited save above, because we
// don't have one.
QDomNodeList l = element.elementsByTagName( "start-date" );
Q_ASSERT( l.count() == 1 );
element.removeChild( l.item( 0 ) );
}
document.appendChild( element );
return document.toString();
}
void Task::setFields( const KCal::Todo* task )
{
Incidence::setFields( task );
setPriority( task->priority() );
setPercentCompleted( task->percentComplete() );
setStatus( task->status() );
setHasStartDate( task->hasStartDate() );
if ( task->hasDueDate() )
setDueDate( localToUTC( task->dtDue() ) );
else
mHasDueDate = false;
if ( task->relatedTo() )
setParent( task->relatedTo()->uid() );
else if ( !task->relatedToUid().isEmpty() )
setParent( task->relatedToUid() );
else
setParent( QString::null );
if ( task->hasCompletedDate() && task->percentComplete() == 100 )
setCompletedDate( localToUTC( task->completed() ) );
else
mHasCompletedDate = false;
}
void Task::saveTo( KCal::Todo* task )
{
Incidence::saveTo( task );
task->setPriority( priority() );
task->setPercentComplete( percentCompleted() );
task->setStatus( status() );
task->setHasStartDate( hasStartDate() );
task->setHasDueDate( hasDueDate() );
if ( hasDueDate() )
task->setDtDue( utcToLocal( dueDate() ) );
if ( !parent().isNull() )
task->setRelatedToUid( parent() );
if ( hasCompletedDate() && task->percentComplete() == 100 )
task->setCompleted( utcToLocal( mCompletedDate ) );
}
<|endoftext|>
|
<commit_before>/*
* Copyright 2019 Benoy Bose
*
* 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 "compiler/ParserDriver.hh"
#include "ast/Unit.hh"
#include "ast/Statement.hh"
#include "ast/ReferenceExpression.hh"
#include "ast/ArrayAccessExpression.hh"
#include "ast/LiteralExpression.hh"
#include "ast/BinaryExpression.hh"
#include "HoocTestHelper.hh"
#include <boost/test/unit_test.hpp>
#include <boost/filesystem.hpp>
using namespace std;
using namespace hooc;
using namespace hooc::compiler;
using namespace hooc::ast;
BOOST_AUTO_TEST_SUITE(BinaryExpressionTest)
BOOST_AUTO_TEST_CASE(BinaryExpression1) {
const std::string source = "2 + 3;";
ParserDriver driver(source, "test.hoo");
auto module = driver.BuildModule();
BOOST_CHECK(module->Success());
auto unit = module->GetUnit();
auto unit_items = unit->GetItems();
BOOST_CHECK_EQUAL(1, unit_items.size());
auto unit_item = *(unit_items.begin());
BOOST_CHECK_EQUAL(UNIT_ITEM_STATEMENT, unit_item->GetUnitItemType());
auto stmt = (Statement *) unit_item;
BOOST_CHECK_EQUAL(STMT_EXPRESSION, stmt->GetStatementType());
auto expr = ((ExpressionStatement *) unit_item)->GetExpression();
BOOST_CHECK_EQUAL(EXPRESSION_BINARY, expr->GetExpressionType());
auto binary_expr = (BinaryExpression *) expr;
auto lvalue = binary_expr->GetLeftExpression();
auto rvalue = binary_expr->GetRightExpression();
auto opr = binary_expr->GetOperator();
BOOST_CHECK_LITERAL_EXPRESSION(lvalue, LITERAL_INTEGER, "2");
BOOST_CHECK_LITERAL_EXPRESSION(rvalue, LITERAL_INTEGER, "3");
BOOST_CHECK_EQUAL(OPERATOR_ADD, opr->GetOperatorType());
}
BOOST_AUTO_TEST_CASE(BinaryExpression2) {
const std::string source = "a - b;";
ParserDriver driver(source, "test.hoo");
auto module = driver.BuildModule();
BOOST_CHECK(module->Success());
auto unit = module->GetUnit();
auto unit_items = unit->GetItems();
BOOST_CHECK_EQUAL(1, unit_items.size());
auto unit_item = *(unit_items.begin());
BOOST_CHECK_EQUAL(UNIT_ITEM_STATEMENT, unit_item->GetUnitItemType());
auto stmt = (Statement *) unit_item;
BOOST_CHECK_EQUAL(STMT_EXPRESSION, stmt->GetStatementType());
auto expr = ((ExpressionStatement *) unit_item)->GetExpression();
BOOST_CHECK_EQUAL(EXPRESSION_BINARY, expr->GetExpressionType());
auto binary_expr = (BinaryExpression *) expr;
auto lvalue = binary_expr->GetLeftExpression();
auto rvalue = binary_expr->GetRightExpression();
auto opr = binary_expr->GetOperator();
BOOST_CHECK_REFERENCE_EXPRESSION(lvalue, "a");
BOOST_CHECK_REFERENCE_EXPRESSION(rvalue, "b");
BOOST_CHECK_EQUAL(OPERATOR_SUB, opr->GetOperatorType());
}
BOOST_AUTO_TEST_CASE(BinaryExpression3) {
const std::string source = "2 / 3 * 4;";
ParserDriver driver(source, "test.hoo");
auto module = driver.BuildModule();
BOOST_CHECK(module->Success());
auto unit = module->GetUnit();
auto unit_items = unit->GetItems();
BOOST_CHECK_EQUAL(1, unit_items.size());
auto unit_item = *(unit_items.begin());
BOOST_CHECK_EQUAL(UNIT_ITEM_STATEMENT, unit_item->GetUnitItemType());
auto stmt = (Statement *) unit_item;
BOOST_CHECK_EQUAL(STMT_EXPRESSION, stmt->GetStatementType());
auto expr = ((ExpressionStatement *) unit_item)->GetExpression();
BOOST_CHECK_EQUAL(EXPRESSION_BINARY, expr->GetExpressionType());
auto binary_expr = (BinaryExpression *) expr;
auto left_value = binary_expr->GetLeftExpression();
auto right_value = binary_expr->GetRightExpression();
auto opr = binary_expr->GetOperator();
BOOST_CHECK_EQUAL(EXPRESSION_BINARY, left_value->GetExpressionType());
auto binary_expr_1 = (BinaryExpression*) left_value;
auto binary_expr_1_left_value = binary_expr_1->GetLeftExpression();
auto binary_expr_1_right_value = binary_expr_1->GetRightExpression();
BOOST_CHECK_LITERAL_EXPRESSION(binary_expr_1_left_value, LITERAL_INTEGER, "2");
BOOST_CHECK_LITERAL_EXPRESSION(binary_expr_1_right_value, LITERAL_INTEGER, "3");
BOOST_CHECK_EQUAL(OPERATOR_DIV, binary_expr_1->GetOperator()->GetOperatorType());
BOOST_CHECK_LITERAL_EXPRESSION(right_value, LITERAL_INTEGER, "4");
BOOST_CHECK_EQUAL(OPERATOR_MUL, opr->GetOperatorType());
}
BOOST_AUTO_TEST_CASE(BinaryExpression4) {
const std::string source = "a / b * c % d;";
ParserDriver driver(source, "test.hoo");
auto module = driver.BuildModule();
BOOST_CHECK(module->Success());
auto unit = module->GetUnit();
auto unit_items = unit->GetItems();
BOOST_CHECK_EQUAL(1, unit_items.size());
auto unit_item = *(unit_items.begin());
BOOST_CHECK_EQUAL(UNIT_ITEM_STATEMENT, unit_item->GetUnitItemType());
auto stmt = (Statement *) unit_item;
BOOST_CHECK_EQUAL(STMT_EXPRESSION, stmt->GetStatementType());
auto expr = ((ExpressionStatement *) unit_item)->GetExpression();
BOOST_CHECK_EQUAL(EXPRESSION_BINARY, expr->GetExpressionType());
auto binary_expr = (BinaryExpression *) expr;
auto opr = binary_expr->GetOperator();
auto left_expr = binary_expr->GetLeftExpression();
auto right_expr = binary_expr->GetRightExpression();
BOOST_CHECK_EQUAL(EXPRESSION_BINARY, left_expr->GetExpressionType());
BOOST_CHECK_REFERENCE_EXPRESSION(right_expr, "d");
BOOST_CHECK_EQUAL(OPERATOR_MOD, opr->GetOperatorType());
opr = ((BinaryExpression *) left_expr)->GetOperator();
right_expr = ((BinaryExpression *) left_expr)->GetRightExpression();
left_expr = ((BinaryExpression *) left_expr)->GetLeftExpression();
BOOST_CHECK_EQUAL(EXPRESSION_BINARY, left_expr->GetExpressionType());
BOOST_CHECK_REFERENCE_EXPRESSION(right_expr, "c");
BOOST_CHECK_EQUAL(OPERATOR_MUL, opr->GetOperatorType());
opr = ((BinaryExpression *) left_expr)->GetOperator();
right_expr = ((BinaryExpression *) left_expr)->GetRightExpression();
left_expr = ((BinaryExpression *) left_expr)->GetLeftExpression();
BOOST_CHECK_REFERENCE_EXPRESSION(left_expr, "a");
BOOST_CHECK_REFERENCE_EXPRESSION(right_expr, "b");
BOOST_CHECK_EQUAL(OPERATOR_DIV, opr->GetOperatorType());
}
BOOST_AUTO_TEST_CASE(BinaryExpression5) {
const std::string source = "(a / b) * (c % d);";
ParserDriver driver(source, "test.hoo");
auto module = driver.BuildModule();
BOOST_CHECK(module->Success());
auto unit = module->GetUnit();
auto unit_items = unit->GetItems();
BOOST_CHECK_EQUAL(1, unit_items.size());
auto unit_item = *(unit_items.begin());
BOOST_CHECK_EQUAL(UNIT_ITEM_STATEMENT, unit_item->GetUnitItemType());
auto stmt = (Statement *) unit_item;
BOOST_CHECK_EQUAL(STMT_EXPRESSION, stmt->GetStatementType());
auto expr = ((ExpressionStatement *) unit_item)->GetExpression();
BOOST_CHECK_EQUAL(EXPRESSION_BINARY, expr->GetExpressionType());
auto binary_expr = (BinaryExpression *) expr;
auto opr = binary_expr->GetOperator();
auto left_expr = binary_expr->GetLeftExpression();
auto right_expr = binary_expr->GetRightExpression();
BOOST_CHECK_EQUAL(EXPRESSION_BINARY, left_expr->GetExpressionType());
BOOST_CHECK_EQUAL(EXPRESSION_BINARY, right_expr->GetExpressionType());
BOOST_CHECK_EQUAL(OPERATOR_MUL, opr->GetOperatorType());
auto l1 = ((BinaryExpression *) left_expr)->GetLeftExpression();
auto l2 = ((BinaryExpression *) left_expr)->GetRightExpression();
opr = ((BinaryExpression *) left_expr)->GetOperator();
BOOST_CHECK_REFERENCE_EXPRESSION(l1, "a");
BOOST_CHECK_REFERENCE_EXPRESSION(l2, "b");
BOOST_CHECK_EQUAL(OPERATOR_DIV, opr->GetOperatorType());
auto r1 = ((BinaryExpression *) right_expr)->GetLeftExpression();
auto r2 = ((BinaryExpression *) right_expr)->GetRightExpression();
opr = ((BinaryExpression *) right_expr)->GetOperator();
BOOST_CHECK_REFERENCE_EXPRESSION(r1, "c");
BOOST_CHECK_REFERENCE_EXPRESSION(r2, "d");
BOOST_CHECK_EQUAL(OPERATOR_MOD, opr->GetOperatorType());
}
BOOST_AUTO_TEST_SUITE_END()<commit_msg>Tested equal comparison of array index access expressions.<commit_after>/*
* Copyright 2019 Benoy Bose
*
* 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 "compiler/ParserDriver.hh"
#include "ast/Unit.hh"
#include "ast/Statement.hh"
#include "ast/ReferenceExpression.hh"
#include "ast/ArrayAccessExpression.hh"
#include "ast/LiteralExpression.hh"
#include "ast/BinaryExpression.hh"
#include "HoocTestHelper.hh"
#include <boost/test/unit_test.hpp>
#include <boost/filesystem.hpp>
using namespace std;
using namespace hooc;
using namespace hooc::compiler;
using namespace hooc::ast;
BOOST_AUTO_TEST_SUITE(BinaryExpressionTest)
BOOST_AUTO_TEST_CASE(BinaryExpression1) {
const std::string source = "2 + 3;";
ParserDriver driver(source, "test.hoo");
auto module = driver.BuildModule();
BOOST_CHECK(module->Success());
auto unit = module->GetUnit();
auto unit_items = unit->GetItems();
BOOST_CHECK_EQUAL(1, unit_items.size());
auto unit_item = *(unit_items.begin());
BOOST_CHECK_EQUAL(UNIT_ITEM_STATEMENT, unit_item->GetUnitItemType());
auto stmt = (Statement *) unit_item;
BOOST_CHECK_EQUAL(STMT_EXPRESSION, stmt->GetStatementType());
auto expr = ((ExpressionStatement *) unit_item)->GetExpression();
BOOST_CHECK_EQUAL(EXPRESSION_BINARY, expr->GetExpressionType());
auto binary_expr = (BinaryExpression *) expr;
auto lvalue = binary_expr->GetLeftExpression();
auto rvalue = binary_expr->GetRightExpression();
auto opr = binary_expr->GetOperator();
BOOST_CHECK_LITERAL_EXPRESSION(lvalue, LITERAL_INTEGER, "2");
BOOST_CHECK_LITERAL_EXPRESSION(rvalue, LITERAL_INTEGER, "3");
BOOST_CHECK_EQUAL(OPERATOR_ADD, opr->GetOperatorType());
}
BOOST_AUTO_TEST_CASE(BinaryExpression2) {
const std::string source = "a - b;";
ParserDriver driver(source, "test.hoo");
auto module = driver.BuildModule();
BOOST_CHECK(module->Success());
auto unit = module->GetUnit();
auto unit_items = unit->GetItems();
BOOST_CHECK_EQUAL(1, unit_items.size());
auto unit_item = *(unit_items.begin());
BOOST_CHECK_EQUAL(UNIT_ITEM_STATEMENT, unit_item->GetUnitItemType());
auto stmt = (Statement *) unit_item;
BOOST_CHECK_EQUAL(STMT_EXPRESSION, stmt->GetStatementType());
auto expr = ((ExpressionStatement *) unit_item)->GetExpression();
BOOST_CHECK_EQUAL(EXPRESSION_BINARY, expr->GetExpressionType());
auto binary_expr = (BinaryExpression *) expr;
auto lvalue = binary_expr->GetLeftExpression();
auto rvalue = binary_expr->GetRightExpression();
auto opr = binary_expr->GetOperator();
BOOST_CHECK_REFERENCE_EXPRESSION(lvalue, "a");
BOOST_CHECK_REFERENCE_EXPRESSION(rvalue, "b");
BOOST_CHECK_EQUAL(OPERATOR_SUB, opr->GetOperatorType());
}
BOOST_AUTO_TEST_CASE(BinaryExpression3) {
const std::string source = "2 / 3 * 4;";
ParserDriver driver(source, "test.hoo");
auto module = driver.BuildModule();
BOOST_CHECK(module->Success());
auto unit = module->GetUnit();
auto unit_items = unit->GetItems();
BOOST_CHECK_EQUAL(1, unit_items.size());
auto unit_item = *(unit_items.begin());
BOOST_CHECK_EQUAL(UNIT_ITEM_STATEMENT, unit_item->GetUnitItemType());
auto stmt = (Statement *) unit_item;
BOOST_CHECK_EQUAL(STMT_EXPRESSION, stmt->GetStatementType());
auto expr = ((ExpressionStatement *) unit_item)->GetExpression();
BOOST_CHECK_EQUAL(EXPRESSION_BINARY, expr->GetExpressionType());
auto binary_expr = (BinaryExpression *) expr;
auto left_value = binary_expr->GetLeftExpression();
auto right_value = binary_expr->GetRightExpression();
auto opr = binary_expr->GetOperator();
BOOST_CHECK_EQUAL(EXPRESSION_BINARY, left_value->GetExpressionType());
auto binary_expr_1 = (BinaryExpression*) left_value;
auto binary_expr_1_left_value = binary_expr_1->GetLeftExpression();
auto binary_expr_1_right_value = binary_expr_1->GetRightExpression();
BOOST_CHECK_LITERAL_EXPRESSION(binary_expr_1_left_value, LITERAL_INTEGER, "2");
BOOST_CHECK_LITERAL_EXPRESSION(binary_expr_1_right_value, LITERAL_INTEGER, "3");
BOOST_CHECK_EQUAL(OPERATOR_DIV, binary_expr_1->GetOperator()->GetOperatorType());
BOOST_CHECK_LITERAL_EXPRESSION(right_value, LITERAL_INTEGER, "4");
BOOST_CHECK_EQUAL(OPERATOR_MUL, opr->GetOperatorType());
}
BOOST_AUTO_TEST_CASE(BinaryExpression4) {
const std::string source = "a / b * c % d;";
ParserDriver driver(source, "test.hoo");
auto module = driver.BuildModule();
BOOST_CHECK(module->Success());
auto unit = module->GetUnit();
auto unit_items = unit->GetItems();
BOOST_CHECK_EQUAL(1, unit_items.size());
auto unit_item = *(unit_items.begin());
BOOST_CHECK_EQUAL(UNIT_ITEM_STATEMENT, unit_item->GetUnitItemType());
auto stmt = (Statement *) unit_item;
BOOST_CHECK_EQUAL(STMT_EXPRESSION, stmt->GetStatementType());
auto expr = ((ExpressionStatement *) unit_item)->GetExpression();
BOOST_CHECK_EQUAL(EXPRESSION_BINARY, expr->GetExpressionType());
auto binary_expr = (BinaryExpression *) expr;
auto opr = binary_expr->GetOperator();
auto left_expr = binary_expr->GetLeftExpression();
auto right_expr = binary_expr->GetRightExpression();
BOOST_CHECK_EQUAL(EXPRESSION_BINARY, left_expr->GetExpressionType());
BOOST_CHECK_REFERENCE_EXPRESSION(right_expr, "d");
BOOST_CHECK_EQUAL(OPERATOR_MOD, opr->GetOperatorType());
opr = ((BinaryExpression *) left_expr)->GetOperator();
right_expr = ((BinaryExpression *) left_expr)->GetRightExpression();
left_expr = ((BinaryExpression *) left_expr)->GetLeftExpression();
BOOST_CHECK_EQUAL(EXPRESSION_BINARY, left_expr->GetExpressionType());
BOOST_CHECK_REFERENCE_EXPRESSION(right_expr, "c");
BOOST_CHECK_EQUAL(OPERATOR_MUL, opr->GetOperatorType());
opr = ((BinaryExpression *) left_expr)->GetOperator();
right_expr = ((BinaryExpression *) left_expr)->GetRightExpression();
left_expr = ((BinaryExpression *) left_expr)->GetLeftExpression();
BOOST_CHECK_REFERENCE_EXPRESSION(left_expr, "a");
BOOST_CHECK_REFERENCE_EXPRESSION(right_expr, "b");
BOOST_CHECK_EQUAL(OPERATOR_DIV, opr->GetOperatorType());
}
BOOST_AUTO_TEST_CASE(BinaryExpression5) {
const std::string source = "(a / b) * (c % d);";
ParserDriver driver(source, "test.hoo");
auto module = driver.BuildModule();
BOOST_CHECK(module->Success());
auto unit = module->GetUnit();
auto unit_items = unit->GetItems();
BOOST_CHECK_EQUAL(1, unit_items.size());
auto unit_item = *(unit_items.begin());
BOOST_CHECK_EQUAL(UNIT_ITEM_STATEMENT, unit_item->GetUnitItemType());
auto stmt = (Statement *) unit_item;
BOOST_CHECK_EQUAL(STMT_EXPRESSION, stmt->GetStatementType());
auto expr = ((ExpressionStatement *) unit_item)->GetExpression();
BOOST_CHECK_EQUAL(EXPRESSION_BINARY, expr->GetExpressionType());
auto binary_expr = (BinaryExpression *) expr;
auto opr = binary_expr->GetOperator();
auto left_expr = binary_expr->GetLeftExpression();
auto right_expr = binary_expr->GetRightExpression();
BOOST_CHECK_EQUAL(EXPRESSION_BINARY, left_expr->GetExpressionType());
BOOST_CHECK_EQUAL(EXPRESSION_BINARY, right_expr->GetExpressionType());
BOOST_CHECK_EQUAL(OPERATOR_MUL, opr->GetOperatorType());
auto l1 = ((BinaryExpression *) left_expr)->GetLeftExpression();
auto l2 = ((BinaryExpression *) left_expr)->GetRightExpression();
opr = ((BinaryExpression *) left_expr)->GetOperator();
BOOST_CHECK_REFERENCE_EXPRESSION(l1, "a");
BOOST_CHECK_REFERENCE_EXPRESSION(l2, "b");
BOOST_CHECK_EQUAL(OPERATOR_DIV, opr->GetOperatorType());
auto r1 = ((BinaryExpression *) right_expr)->GetLeftExpression();
auto r2 = ((BinaryExpression *) right_expr)->GetRightExpression();
opr = ((BinaryExpression *) right_expr)->GetOperator();
BOOST_CHECK_REFERENCE_EXPRESSION(r1, "c");
BOOST_CHECK_REFERENCE_EXPRESSION(r2, "d");
BOOST_CHECK_EQUAL(OPERATOR_MOD, opr->GetOperatorType());
}
BOOST_AUTO_TEST_CASE(BinaryExpression6) {
const std::string source = "a[0] == b[1];";
ParserDriver driver(source, "test.hoo");
auto module = driver.BuildModule();
BOOST_CHECK(module->Success());
auto unit = module->GetUnit();
auto unit_items = unit->GetItems();
BOOST_CHECK_EQUAL(1, unit_items.size());
auto unit_item = *(unit_items.begin());
BOOST_CHECK_EQUAL(UNIT_ITEM_STATEMENT, unit_item->GetUnitItemType());
auto stmt = (Statement *) unit_item;
BOOST_CHECK_EQUAL(STMT_EXPRESSION, stmt->GetStatementType());
auto expr = ((ExpressionStatement *) unit_item)->GetExpression();
BOOST_CHECK_EQUAL(EXPRESSION_BINARY, expr->GetExpressionType());
auto binary_expr = (BinaryExpression *) expr;
auto opr = binary_expr->GetOperator();
auto left_expr = binary_expr->GetLeftExpression();
auto right_expr = binary_expr->GetRightExpression();
BOOST_CHECK_EQUAL(OPERATOR_EQUAL, opr->GetOperatorType());
auto a_array = (ArrayAccessExpression *) left_expr;
auto b_array = (ArrayAccessExpression *) right_expr;
auto a = a_array->GetContainer();
auto index0 = a_array->GetIndex();
BOOST_CHECK_REFERENCE_EXPRESSION(a, "a");
BOOST_CHECK_LITERAL_EXPRESSION(index0, LITERAL_INTEGER, "0");
auto b = b_array->GetContainer();
auto index1 = b_array->GetIndex();
BOOST_CHECK_REFERENCE_EXPRESSION(b, "b");
BOOST_CHECK_LITERAL_EXPRESSION(index1, LITERAL_INTEGER, "1");
}
BOOST_AUTO_TEST_SUITE_END()<|endoftext|>
|
<commit_before><commit_msg>make style<commit_after><|endoftext|>
|
<commit_before>// Copyright (c) 2015 Pavel Novy. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "rfl-scan/compilation_db.h"
#include "llvm/ADT/SmallString.h"
#include "llvm/ADT/ArrayRef.h"
#include "llvm/Support/Path.h"
#include "llvm/Support/raw_os_ostream.h"
namespace rfl {
namespace scan {
ScanCompilationDatabase::ScanCompilationDatabase(
CompilationDatabase &cdb,
std::vector<std::string> sources) : compilation_db_(cdb), source_files_(sources){
}
ScanCompilationDatabase::~ScanCompilationDatabase() {
}
char const *const kHeaderExtensions[] = {".h", ".hh", ".hpp", ".h++"};
char const *const kSourceExtensions[] = {".cc", ".cpp", ".cxx", ".c++", ".c"};
void ScanCompilationDatabase::cleanupCommands(std::vector<CompileCommand> &cmds,
StringRef const &filename) const {
// go through all commandlines and replace -c file with ours
for (CompileCommand &cmd : cmds) {
for (std::vector<std::string>::iterator it = cmd.CommandLine.begin();
it != cmd.CommandLine.end();) {
if (!it->empty() && it->compare("-c") == 0) {
++it;
it->assign(filename);
} else {
++it;
}
}
// since this is header we need to specify that's a c++ header
cmd.CommandLine.insert(cmd.CommandLine.begin() + 1, "c++");
cmd.CommandLine.insert(cmd.CommandLine.begin() + 1, "-x");
}
}
std::vector<CompileCommand> ScanCompilationDatabase::getCompileCommands(
StringRef file) const {
std::vector<CompileCommand> result = compilation_db_.getCompileCommands(file);
if (result.empty()) {
// check whether this is a header, if so, try to find .cc file
StringRef ext = sys::path::extension(file);
ArrayRef<char const *> hdr_exts(kHeaderExtensions);
ArrayRef<char const *> src_exts(kSourceExtensions);
for (ArrayRef<char const *>::const_iterator it = hdr_exts.begin();
it != hdr_exts.end();
++it) {
if (ext.compare(*it) == 0) {
// header extensions match, so try to replace it with source ext.
for (ArrayRef<char const *>::const_iterator cit = src_exts.begin();
cit != src_exts.end();
++cit) {
SmallString<1024> src_file(file);
sys::path::replace_extension(src_file, *cit);
result = compilation_db_.getCompileCommands(src_file);
if (result.size()) {
cleanupCommands(result,file);
return result;
}
}
break;
}
}
outs() << "No luck for: " << file << "\n";
outs().flush();
// Nothing found, try all other files
for (std::string const &src : source_files_) {
if (src.compare(file) == 0)
continue;
result = getCompileCommands(src);
if (!result.empty())
cleanupCommands(result,file);
return result;
}
}
return result;
}
std::vector<std::string> ScanCompilationDatabase::getAllFiles() const {
return source_files_;
}
std::vector<CompileCommand> ScanCompilationDatabase::getAllCompileCommands() const {
std::vector<CompileCommand> cmds;
for (std::string const &source : source_files_) {
std::vector<CompileCommand> source_cmds =
compilation_db_.getCompileCommands(source);
if (!source_cmds.empty())
cmds.insert(cmds.end(), source_cmds.begin(), source_cmds.end());
}
return cmds;
}
} // namespace scan
} // namespace rfl
<commit_msg>CompilationDB cleanup, Fix -gsplit-dwarf creating more then one compilation job<commit_after>// Copyright (c) 2015 Pavel Novy. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "rfl-scan/compilation_db.h"
#include "llvm/ADT/SmallString.h"
#include "llvm/ADT/ArrayRef.h"
#include "llvm/Support/Path.h"
#include "llvm/Support/raw_os_ostream.h"
namespace rfl {
namespace scan {
ScanCompilationDatabase::ScanCompilationDatabase(
CompilationDatabase &cdb,
std::vector<std::string> sources) : compilation_db_(cdb), source_files_(sources){
}
ScanCompilationDatabase::~ScanCompilationDatabase() {
}
char const *const kHeaderExtensions[] = {".h", ".hh", ".hpp", ".h++"};
char const *const kSourceExtensions[] = {".cc", ".cpp", ".cxx", ".c++", ".c"};
void ScanCompilationDatabase::cleanupCommands(std::vector<CompileCommand> &cmds,
StringRef const &filename) const {
// go through all commandlines and replace -c file with ours
for (CompileCommand &cmd : cmds) {
for (std::vector<std::string>::iterator it = cmd.CommandLine.begin();
it != cmd.CommandLine.end();) {
if (!it->empty() && it->compare("-c") == 0) {
++it;
it->assign(filename);
} else if (it->compare("-gsplit-dwarf") == 0) {
it = cmd.CommandLine.erase(it);
}
else {
++it;
}
}
// since this is header we need to specify that's a c++ header
cmd.CommandLine.insert(cmd.CommandLine.begin() + 1, "c++");
cmd.CommandLine.insert(cmd.CommandLine.begin() + 1, "-x");
}
}
std::vector<CompileCommand> ScanCompilationDatabase::getCompileCommands(
StringRef file) const {
std::vector<CompileCommand> result = compilation_db_.getCompileCommands(file);
if (!result.empty())
return result;
// check whether this is a header, if so, try to find .cc file
StringRef ext = sys::path::extension(file);
ArrayRef<char const *> hdr_exts(kHeaderExtensions);
ArrayRef<char const *> src_exts(kSourceExtensions);
for (ArrayRef<char const *>::const_iterator it = hdr_exts.begin();
it != hdr_exts.end();
++it) {
if (ext.compare(*it) == 0) {
// header extensions match, so try to replace it with source ext.
for (ArrayRef<char const *>::const_iterator cit = src_exts.begin();
cit != src_exts.end();
++cit) {
SmallString<1024> src_file(file);
sys::path::replace_extension(src_file, *cit);
result = compilation_db_.getCompileCommands(src_file);
if (result.size()) {
cleanupCommands(result,file);
return result;
}
}
break;
}
}
outs() << "No luck for: " << file << "\n";
outs().flush();
// Nothing found, try all other files
for (std::string const &src : source_files_) {
if (src.compare(file) == 0)
continue;
result = getCompileCommands(src);
if (!result.empty())
cleanupCommands(result,file);
return result;
}
return result;
}
std::vector<std::string> ScanCompilationDatabase::getAllFiles() const {
return source_files_;
}
std::vector<CompileCommand> ScanCompilationDatabase::getAllCompileCommands() const {
std::vector<CompileCommand> cmds;
for (std::string const &source : source_files_) {
std::vector<CompileCommand> source_cmds =
compilation_db_.getCompileCommands(source);
if (!source_cmds.empty())
cmds.insert(cmds.end(), source_cmds.begin(), source_cmds.end());
}
return cmds;
}
} // namespace scan
} // namespace rfl
<|endoftext|>
|
<commit_before>#include <sys/errno.h>
#include <sys/ioctl.h>
#include <sys/socket.h>
#include <sys/un.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#include <errno.h>
#include <fcntl.h>
#include <netdb.h>
#include <common/buffer.h>
#include <common/endian.h>
#include <event/action.h>
#include <event/callback.h>
#include <event/event_system.h>
#include <io/socket.h>
struct socket_address {
union address_union {
struct sockaddr sockaddr_;
struct sockaddr_in inet_;
struct sockaddr_in6 inet6_;
struct sockaddr_un unix_;
operator std::string (void) const
{
/* XXX getnameinfo(3); */
char address[256]; /* XXX*/
const char *p;
std::ostringstream str;
switch (sockaddr_.sa_family) {
case AF_INET:
p = ::inet_ntop(inet_.sin_family,
&inet_.sin_addr,
address, sizeof address);
ASSERT(p != NULL);
str << '[' << address << ']' << ':' << ntohs(inet_.sin_port);
break;
case AF_INET6:
p = ::inet_ntop(inet6_.sin6_family,
&inet6_.sin6_addr,
address, sizeof address);
ASSERT(p != NULL);
str << '[' << address << ']' << ':' << ntohs(inet6_.sin6_port);
break;
default:
return ("<unsupported-address-family>");
}
return (str.str());
}
} addr_;
size_t addrlen_;
socket_address(void)
: addr_(),
addrlen_(0)
{
memset(&addr_, 0, sizeof addr_);
}
bool operator() (int domain, int socktype, int protocol, const std::string& str)
{
switch (domain) {
case AF_UNSPEC:
case AF_INET6:
case AF_INET: {
std::string::size_type pos = str.find(']');
if (pos == std::string::npos)
return (false);
if (pos < 3 || str[0] != '[' || str[pos + 1] != ':')
return (false);
std::string name(str, 1, pos - 1);
std::string service(str, pos + 2);
struct addrinfo hints;
memset(&hints, 0, sizeof hints);
hints.ai_family = domain;
hints.ai_socktype = socktype;
hints.ai_protocol = protocol;
struct addrinfo *ai;
int rv = getaddrinfo(name.c_str(), service.c_str(), &hints, &ai);
if (rv != 0) {
ERROR("/socket/address") << "Could not look up " << str << ": " << strerror(errno);
return (false);
}
/*
* Just use the first one.
* XXX Will we ever get one in the wrong family? Is the hint mandatory?
*/
memcpy(&addr_.sockaddr_, ai->ai_addr, ai->ai_addrlen);
addrlen_ = ai->ai_addrlen;
freeaddrinfo(ai);
break;
}
case AF_UNIX:
addr_.unix_.sun_family = domain;
strncpy(addr_.unix_.sun_path, str.c_str(), sizeof addr_.unix_.sun_path);
addrlen_ = sizeof addr_.unix_;
#if !defined(__linux__) && !defined(__sun__)
addr_.unix_.sun_len = addrlen_;
#endif
break;
default:
ERROR("/socket/address") << "Addresss family not supported: " << domain;
return (false);
}
return (true);
}
};
Socket::Socket(int fd, int domain, int socktype, int protocol)
: FileDescriptor(fd),
log_("/socket"),
domain_(domain),
socktype_(socktype),
protocol_(protocol),
accept_action_(NULL),
accept_callback_(NULL),
connect_callback_(NULL),
connect_action_(NULL)
{
ASSERT(fd_ != -1);
}
Socket::~Socket()
{
ASSERT(accept_action_ == NULL);
ASSERT(accept_callback_ == NULL);
ASSERT(connect_callback_ == NULL);
ASSERT(connect_action_ == NULL);
}
Action *
Socket::accept(EventCallback *cb)
{
ASSERT(accept_action_ == NULL);
ASSERT(accept_callback_ == NULL);
accept_callback_ = cb;
accept_action_ = accept_schedule();
return (cancellation(this, &Socket::accept_cancel));
}
bool
Socket::bind(const std::string& name)
{
socket_address addr;
if (!addr(domain_, socktype_, protocol_, name)) {
ERROR(log_) << "Invalid name for bind: " << name;
return (false);
}
int rv = ::bind(fd_, &addr.addr_.sockaddr_, addr.addrlen_);
if (rv == -1)
return (false);
return (true);
}
Action *
Socket::connect(const std::string& name, EventCallback *cb)
{
ASSERT(connect_callback_ == NULL);
ASSERT(connect_action_ == NULL);
socket_address addr;
if (!addr(domain_, socktype_, protocol_, name)) {
ERROR(log_) << "Invalid name for connect: " << name;
cb->event(Event(Event::Error, EINVAL));
return (EventSystem::instance()->schedule(cb));
}
/*
* TODO
*
* If the address we are connecting to is the address of another
* Socket, set up some sort of zero-copy IO between them. This is
* easy enough if we do it right here. Trying to do it at the file
* descriptor level seems to be really hard since there's a lot of
* races possible there. This way, we're still at the point of the
* connection set up.
*
* We may want to allow the connection to complete so that calls to
* getsockname(2) and getpeername(2) do what you'd expect. We may
* still want to poll on the file descriptors even, to make it
* possible to use tcpdrop, etc., to reset the connections. I guess
* the thing to do is poll if there's no input ready.
*/
int rv = ::connect(fd_, &addr.addr_.sockaddr_, addr.addrlen_);
switch (rv) {
case 0:
cb->event(Event(Event::Done, 0));
connect_action_ = EventSystem::instance()->schedule(cb);
break;
case -1:
switch (errno) {
case EINPROGRESS:
connect_callback_ = cb;
connect_action_ = connect_schedule();
break;
default:
cb->event(Event(Event::Error, errno));
connect_action_ = EventSystem::instance()->schedule(cb);
break;
}
break;
default:
HALT(log_) << "Connect returned unexpected value: " << rv;
}
return (cancellation(this, &Socket::connect_cancel));
}
bool
Socket::listen(int backlog)
{
int rv = ::listen(fd_, backlog);
if (rv == -1)
return (false);
return (true);
}
std::string
Socket::getpeername(void) const
{
socket_address::address_union un;
socklen_t len;
int rv;
len = sizeof un;
rv = ::getpeername(fd_, &un.sockaddr_, &len);
if (rv == -1)
return ("<unknown>");
/* XXX Check len. */
return ((std::string)un);
}
std::string
Socket::getsockname(void) const
{
socket_address::address_union un;
socklen_t len;
int rv;
len = sizeof un;
rv = ::getsockname(fd_, &un.sockaddr_, &len);
if (rv == -1)
return ("<unknown>");
/* XXX Check len. */
return ((std::string)un);
}
void
Socket::accept_callback(Event e)
{
accept_action_->cancel();
accept_action_ = NULL;
switch (e.type_) {
case Event::Done:
break;
case Event::EOS:
case Event::Error:
accept_callback_->event(Event(Event::Error, e.error_));
accept_action_ = EventSystem::instance()->schedule(accept_callback_);
accept_callback_ = NULL;
return;
default:
HALT(log_) << "Unexpected event: " << e;
}
int s = ::accept(fd_, NULL, NULL);
if (s == -1) {
switch (errno) {
case EAGAIN:
accept_action_ = accept_schedule();
return;
default:
accept_callback_->event(Event(Event::Error, errno));
accept_action_ = EventSystem::instance()->schedule(accept_callback_);
accept_callback_ = NULL;
return;
}
}
Socket *child = new Socket(s, domain_, socktype_, protocol_);
accept_callback_->event(Event(Event::Done, 0, (void *)child));
Action *a = EventSystem::instance()->schedule(accept_callback_);
accept_action_ = a;
accept_callback_ = NULL;
}
void
Socket::accept_cancel(void)
{
ASSERT(accept_action_ != NULL);
accept_action_->cancel();
accept_action_ = NULL;
if (accept_callback_ != NULL) {
delete accept_callback_;
accept_callback_ = NULL;
}
}
Action *
Socket::accept_schedule(void)
{
EventCallback *cb = callback(this, &Socket::accept_callback);
Action *a = EventSystem::instance()->poll(EventPoll::Readable, fd_, cb);
return (a);
}
void
Socket::connect_callback(Event e)
{
connect_action_->cancel();
connect_action_ = NULL;
switch (e.type_) {
case Event::Done:
connect_callback_->event(Event(Event::Done, 0));
break;
case Event::EOS:
case Event::Error:
connect_callback_->event(Event(Event::Error, e.error_));
break;
default:
HALT(log_) << "Unexpected event: " << e;
}
Action *a = EventSystem::instance()->schedule(connect_callback_);
connect_action_ = a;
connect_callback_ = NULL;
}
void
Socket::connect_cancel(void)
{
ASSERT(connect_action_ != NULL);
connect_action_->cancel();
connect_action_ = NULL;
if (connect_callback_ != NULL) {
delete connect_callback_;
connect_callback_ = NULL;
}
}
Action *
Socket::connect_schedule(void)
{
EventCallback *cb = callback(this, &Socket::connect_callback);
Action *a = EventSystem::instance()->poll(EventPoll::Writable, fd_, cb);
return (a);
}
Socket *
Socket::create(SocketAddressFamily family, SocketType type, const std::string& protocol, const std::string& hint)
{
int typenum;
switch (type) {
case SocketTypeStream:
typenum = SOCK_STREAM;
break;
case SocketTypeDatagram:
typenum = SOCK_DGRAM;
break;
default:
ERROR("/socket") << "Unsupported socket type.";
return (NULL);
}
int protonum;
if (protocol == "") {
protonum = 0;
} else {
struct protoent *proto = getprotobyname(protocol.c_str());
if (proto == NULL) {
ERROR("/socket") << "Invalid protocol: " << protocol;
return (NULL);
}
protonum = proto->p_proto;
}
int domainnum;
switch (family) {
case SocketAddressFamilyIP:
if (hint == "") {
ERROR("/socket") << "Must specify hint address for IP sockets or specify IPv4 or IPv6 explicitly.";
return (NULL);
} else {
socket_address addr;
if (!addr(AF_UNSPEC, typenum, protonum, hint)) {
ERROR("/socket") << "Invalid hint: " << hint;
return (NULL);
}
/* XXX Just make socket_address::operator() smarter about AF_UNSPEC? */
switch (addr.addr_.sockaddr_.sa_family) {
case AF_INET:
domainnum = AF_INET;
break;
case AF_INET6:
domainnum = AF_INET6;
break;
default:
ERROR("/socket") << "Unsupported address family for hint: " << hint;
return (NULL);
}
break;
}
case SocketAddressFamilyIPv4:
domainnum = AF_INET;
break;
case SocketAddressFamilyIPv6:
domainnum = AF_INET6;
break;
case SocketAddressFamilyUnix:
domainnum = AF_UNIX;
break;
default:
ERROR("/socket") << "Unsupported address family.";
return (NULL);
}
int s = ::socket(domainnum, typenum, protonum);
if (s == -1) {
/*
* If we were trying to create an IPv6 socket for a request that
* did not specify IPv4 vs. IPv6 and the system claims that the
* protocol is not supported, try explicitly creating an IPv4
* socket.
*/
if (errno == EPROTONOSUPPORT && domainnum == AF_INET6 &&
family == SocketAddressFamilyIP) {
DEBUG("/socket") << "IPv6 socket create failed; trying IPv4.";
return (Socket::create(SocketAddressFamilyIPv4, type, protocol, hint));
}
ERROR("/socket") << "Could not create socket: " << strerror(errno);
return (NULL);
}
return (new Socket(s, domainnum, typenum, protonum));
}
<commit_msg>Work around an incredibly-stupid regression in latest Mac OS X.<commit_after>#include <sys/errno.h>
#include <sys/ioctl.h>
#include <sys/socket.h>
#include <sys/un.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#include <errno.h>
#include <fcntl.h>
#include <netdb.h>
#include <common/buffer.h>
#include <common/endian.h>
#include <event/action.h>
#include <event/callback.h>
#include <event/event_system.h>
#include <io/socket.h>
struct socket_address {
union address_union {
struct sockaddr sockaddr_;
struct sockaddr_in inet_;
struct sockaddr_in6 inet6_;
struct sockaddr_un unix_;
operator std::string (void) const
{
/* XXX getnameinfo(3); */
char address[256]; /* XXX*/
const char *p;
std::ostringstream str;
switch (sockaddr_.sa_family) {
case AF_INET:
p = ::inet_ntop(inet_.sin_family,
&inet_.sin_addr,
address, sizeof address);
ASSERT(p != NULL);
str << '[' << address << ']' << ':' << ntohs(inet_.sin_port);
break;
case AF_INET6:
p = ::inet_ntop(inet6_.sin6_family,
&inet6_.sin6_addr,
address, sizeof address);
ASSERT(p != NULL);
str << '[' << address << ']' << ':' << ntohs(inet6_.sin6_port);
break;
default:
return ("<unsupported-address-family>");
}
return (str.str());
}
} addr_;
size_t addrlen_;
socket_address(void)
: addr_(),
addrlen_(0)
{
memset(&addr_, 0, sizeof addr_);
}
bool operator() (int domain, int socktype, int protocol, const std::string& str)
{
switch (domain) {
case AF_UNSPEC:
case AF_INET6:
case AF_INET: {
std::string::size_type pos = str.find(']');
if (pos == std::string::npos)
return (false);
if (pos < 3 || str[0] != '[' || str[pos + 1] != ':')
return (false);
std::string name(str, 1, pos - 1);
std::string service(str, pos + 2);
struct addrinfo hints;
memset(&hints, 0, sizeof hints);
hints.ai_family = domain;
hints.ai_socktype = socktype;
hints.ai_protocol = protocol;
/*
* Mac OS X ~Snow Leopard~ cannot handle a service name
* of "0" where older Mac OS X could. Don't know if
* that is because it's not in services(5) or due to
* some attempt at input validation. So work around it
* here, sigh.
*/
const char *servptr;
if (service == "" || service == "0")
servptr = NULL;
else
servptr = service.c_str();
struct addrinfo *ai;
int rv = getaddrinfo(name.c_str(), servptr, &hints, &ai);
if (rv != 0) {
ERROR("/socket/address") << "Could not look up " << str << ": " << gai_strerror(rv);
return (false);
}
/*
* Just use the first one.
* XXX Will we ever get one in the wrong family? Is the hint mandatory?
*/
memcpy(&addr_.sockaddr_, ai->ai_addr, ai->ai_addrlen);
addrlen_ = ai->ai_addrlen;
freeaddrinfo(ai);
break;
}
case AF_UNIX:
addr_.unix_.sun_family = domain;
strncpy(addr_.unix_.sun_path, str.c_str(), sizeof addr_.unix_.sun_path);
addrlen_ = sizeof addr_.unix_;
#if !defined(__linux__) && !defined(__sun__)
addr_.unix_.sun_len = addrlen_;
#endif
break;
default:
ERROR("/socket/address") << "Addresss family not supported: " << domain;
return (false);
}
return (true);
}
};
Socket::Socket(int fd, int domain, int socktype, int protocol)
: FileDescriptor(fd),
log_("/socket"),
domain_(domain),
socktype_(socktype),
protocol_(protocol),
accept_action_(NULL),
accept_callback_(NULL),
connect_callback_(NULL),
connect_action_(NULL)
{
ASSERT(fd_ != -1);
}
Socket::~Socket()
{
ASSERT(accept_action_ == NULL);
ASSERT(accept_callback_ == NULL);
ASSERT(connect_callback_ == NULL);
ASSERT(connect_action_ == NULL);
}
Action *
Socket::accept(EventCallback *cb)
{
ASSERT(accept_action_ == NULL);
ASSERT(accept_callback_ == NULL);
accept_callback_ = cb;
accept_action_ = accept_schedule();
return (cancellation(this, &Socket::accept_cancel));
}
bool
Socket::bind(const std::string& name)
{
socket_address addr;
if (!addr(domain_, socktype_, protocol_, name)) {
ERROR(log_) << "Invalid name for bind: " << name;
return (false);
}
int rv = ::bind(fd_, &addr.addr_.sockaddr_, addr.addrlen_);
if (rv == -1)
return (false);
return (true);
}
Action *
Socket::connect(const std::string& name, EventCallback *cb)
{
ASSERT(connect_callback_ == NULL);
ASSERT(connect_action_ == NULL);
socket_address addr;
if (!addr(domain_, socktype_, protocol_, name)) {
ERROR(log_) << "Invalid name for connect: " << name;
cb->event(Event(Event::Error, EINVAL));
return (EventSystem::instance()->schedule(cb));
}
/*
* TODO
*
* If the address we are connecting to is the address of another
* Socket, set up some sort of zero-copy IO between them. This is
* easy enough if we do it right here. Trying to do it at the file
* descriptor level seems to be really hard since there's a lot of
* races possible there. This way, we're still at the point of the
* connection set up.
*
* We may want to allow the connection to complete so that calls to
* getsockname(2) and getpeername(2) do what you'd expect. We may
* still want to poll on the file descriptors even, to make it
* possible to use tcpdrop, etc., to reset the connections. I guess
* the thing to do is poll if there's no input ready.
*/
int rv = ::connect(fd_, &addr.addr_.sockaddr_, addr.addrlen_);
switch (rv) {
case 0:
cb->event(Event(Event::Done, 0));
connect_action_ = EventSystem::instance()->schedule(cb);
break;
case -1:
switch (errno) {
case EINPROGRESS:
connect_callback_ = cb;
connect_action_ = connect_schedule();
break;
default:
cb->event(Event(Event::Error, errno));
connect_action_ = EventSystem::instance()->schedule(cb);
break;
}
break;
default:
HALT(log_) << "Connect returned unexpected value: " << rv;
}
return (cancellation(this, &Socket::connect_cancel));
}
bool
Socket::listen(int backlog)
{
int rv = ::listen(fd_, backlog);
if (rv == -1)
return (false);
return (true);
}
std::string
Socket::getpeername(void) const
{
socket_address::address_union un;
socklen_t len;
int rv;
len = sizeof un;
rv = ::getpeername(fd_, &un.sockaddr_, &len);
if (rv == -1)
return ("<unknown>");
/* XXX Check len. */
return ((std::string)un);
}
std::string
Socket::getsockname(void) const
{
socket_address::address_union un;
socklen_t len;
int rv;
len = sizeof un;
rv = ::getsockname(fd_, &un.sockaddr_, &len);
if (rv == -1)
return ("<unknown>");
/* XXX Check len. */
return ((std::string)un);
}
void
Socket::accept_callback(Event e)
{
accept_action_->cancel();
accept_action_ = NULL;
switch (e.type_) {
case Event::Done:
break;
case Event::EOS:
case Event::Error:
accept_callback_->event(Event(Event::Error, e.error_));
accept_action_ = EventSystem::instance()->schedule(accept_callback_);
accept_callback_ = NULL;
return;
default:
HALT(log_) << "Unexpected event: " << e;
}
int s = ::accept(fd_, NULL, NULL);
if (s == -1) {
switch (errno) {
case EAGAIN:
accept_action_ = accept_schedule();
return;
default:
accept_callback_->event(Event(Event::Error, errno));
accept_action_ = EventSystem::instance()->schedule(accept_callback_);
accept_callback_ = NULL;
return;
}
}
Socket *child = new Socket(s, domain_, socktype_, protocol_);
accept_callback_->event(Event(Event::Done, 0, (void *)child));
Action *a = EventSystem::instance()->schedule(accept_callback_);
accept_action_ = a;
accept_callback_ = NULL;
}
void
Socket::accept_cancel(void)
{
ASSERT(accept_action_ != NULL);
accept_action_->cancel();
accept_action_ = NULL;
if (accept_callback_ != NULL) {
delete accept_callback_;
accept_callback_ = NULL;
}
}
Action *
Socket::accept_schedule(void)
{
EventCallback *cb = callback(this, &Socket::accept_callback);
Action *a = EventSystem::instance()->poll(EventPoll::Readable, fd_, cb);
return (a);
}
void
Socket::connect_callback(Event e)
{
connect_action_->cancel();
connect_action_ = NULL;
switch (e.type_) {
case Event::Done:
connect_callback_->event(Event(Event::Done, 0));
break;
case Event::EOS:
case Event::Error:
connect_callback_->event(Event(Event::Error, e.error_));
break;
default:
HALT(log_) << "Unexpected event: " << e;
}
Action *a = EventSystem::instance()->schedule(connect_callback_);
connect_action_ = a;
connect_callback_ = NULL;
}
void
Socket::connect_cancel(void)
{
ASSERT(connect_action_ != NULL);
connect_action_->cancel();
connect_action_ = NULL;
if (connect_callback_ != NULL) {
delete connect_callback_;
connect_callback_ = NULL;
}
}
Action *
Socket::connect_schedule(void)
{
EventCallback *cb = callback(this, &Socket::connect_callback);
Action *a = EventSystem::instance()->poll(EventPoll::Writable, fd_, cb);
return (a);
}
Socket *
Socket::create(SocketAddressFamily family, SocketType type, const std::string& protocol, const std::string& hint)
{
int typenum;
switch (type) {
case SocketTypeStream:
typenum = SOCK_STREAM;
break;
case SocketTypeDatagram:
typenum = SOCK_DGRAM;
break;
default:
ERROR("/socket") << "Unsupported socket type.";
return (NULL);
}
int protonum;
if (protocol == "") {
protonum = 0;
} else {
struct protoent *proto = getprotobyname(protocol.c_str());
if (proto == NULL) {
ERROR("/socket") << "Invalid protocol: " << protocol;
return (NULL);
}
protonum = proto->p_proto;
}
int domainnum;
switch (family) {
case SocketAddressFamilyIP:
if (hint == "") {
ERROR("/socket") << "Must specify hint address for IP sockets or specify IPv4 or IPv6 explicitly.";
return (NULL);
} else {
socket_address addr;
if (!addr(AF_UNSPEC, typenum, protonum, hint)) {
ERROR("/socket") << "Invalid hint: " << hint;
return (NULL);
}
/* XXX Just make socket_address::operator() smarter about AF_UNSPEC? */
switch (addr.addr_.sockaddr_.sa_family) {
case AF_INET:
domainnum = AF_INET;
break;
case AF_INET6:
domainnum = AF_INET6;
break;
default:
ERROR("/socket") << "Unsupported address family for hint: " << hint;
return (NULL);
}
break;
}
case SocketAddressFamilyIPv4:
domainnum = AF_INET;
break;
case SocketAddressFamilyIPv6:
domainnum = AF_INET6;
break;
case SocketAddressFamilyUnix:
domainnum = AF_UNIX;
break;
default:
ERROR("/socket") << "Unsupported address family.";
return (NULL);
}
int s = ::socket(domainnum, typenum, protonum);
if (s == -1) {
/*
* If we were trying to create an IPv6 socket for a request that
* did not specify IPv4 vs. IPv6 and the system claims that the
* protocol is not supported, try explicitly creating an IPv4
* socket.
*/
if (errno == EPROTONOSUPPORT && domainnum == AF_INET6 &&
family == SocketAddressFamilyIP) {
DEBUG("/socket") << "IPv6 socket create failed; trying IPv4.";
return (Socket::create(SocketAddressFamilyIPv4, type, protocol, hint));
}
ERROR("/socket") << "Could not create socket: " << strerror(errno);
return (NULL);
}
return (new Socket(s, domainnum, typenum, protonum));
}
<|endoftext|>
|
<commit_before>#ifndef ITERBASE_HPP_
#define ITERBASE_HPP_
// This file consists of utilities used for the generic nature of the
// iterable wrapper classes. As such, the contents of this file should be
// considered UNDOCUMENTED and is subject to change without warning. This
// also applies to the name of the file. No user code should include
// this file directly.
#include <utility>
#include <iterator>
#include <cstddef>
namespace iter {
// because std::advance assumes a lot and is actually smart, I need a dumb
// version that will work with most things
template <typename InputIt, typename Distance>
void dumb_advance(InputIt& iter, Distance distance) {
for (Distance i(0); i < distance; ++i) {
++iter;
}
}
// iter will not be incremented past end
template <typename InputIt, typename Distance>
void dumb_advance(InputIt& iter, const InputIt& end, Distance distance=1) {
for (Distance i(0); i < distance && iter != end; ++i) {
++iter;
}
}
template <typename ForwardIt, typename Distance>
ForwardIt dumb_next(ForwardIt it, Distance distance) {
dumb_advance(it, distance);
return it;
}
template <typename ForwardIt, typename Distance>
ForwardIt dumb_next(
ForwardIt it, const ForwardIt& end, Distance distance=1) {
dumb_advance(it, end, distance);
return it;
}
// iterator_type<C> is the type of C's iterator
template <typename Container>
using iterator_type =
decltype(std::begin(std::declval<Container&>()));
// iterator_deref<C> is the type obtained by dereferencing an iterator
// to an object of type C
template <typename Container>
using iterator_deref =
decltype(*std::declval<iterator_type<Container>&>());
// iterator_type<C> is the type of C's iterator
template <typename Container>
using reverse_iterator_type =
decltype(std::declval<Container&>().rbegin());
// iterator_deref<C> is the type obtained by dereferencing an iterator
// to an object of type C
template <typename Container>
using reverse_iterator_deref =
decltype(*std::declval<reverse_iterator_type<Container>&>());
}
#endif // #ifndef ITERBASE_HPP_
<commit_msg>make distances default to 1 (correctly)<commit_after>#ifndef ITERBASE_HPP_
#define ITERBASE_HPP_
// This file consists of utilities used for the generic nature of the
// iterable wrapper classes. As such, the contents of this file should be
// considered UNDOCUMENTED and is subject to change without warning. This
// also applies to the name of the file. No user code should include
// this file directly.
#include <utility>
#include <iterator>
#include <cstddef>
namespace iter {
// because std::advance assumes a lot and is actually smart, I need a dumb
// version that will work with most things
template <typename InputIt, typename Distance =std::size_t>
void dumb_advance(InputIt& iter, Distance distance=1) {
for (Distance i(0); i < distance; ++i) {
++iter;
}
}
// iter will not be incremented past end
template <typename InputIt, typename Distance =std::size_t>
void dumb_advance(InputIt& iter, const InputIt& end, Distance distance=1) {
for (Distance i(0); i < distance && iter != end; ++i) {
++iter;
}
}
template <typename ForwardIt, typename Distance =std::size_t>
ForwardIt dumb_next(ForwardIt it, Distance distance=1) {
dumb_advance(it, distance);
return it;
}
template <typename ForwardIt, typename Distance =std::size_t>
ForwardIt dumb_next(
ForwardIt it, const ForwardIt& end, Distance distance=1) {
dumb_advance(it, end, distance);
return it;
}
// iterator_type<C> is the type of C's iterator
template <typename Container>
using iterator_type =
decltype(std::begin(std::declval<Container&>()));
// iterator_deref<C> is the type obtained by dereferencing an iterator
// to an object of type C
template <typename Container>
using iterator_deref =
decltype(*std::declval<iterator_type<Container>&>());
// iterator_type<C> is the type of C's iterator
template <typename Container>
using reverse_iterator_type =
decltype(std::declval<Container&>().rbegin());
// iterator_deref<C> is the type obtained by dereferencing an iterator
// to an object of type C
template <typename Container>
using reverse_iterator_deref =
decltype(*std::declval<reverse_iterator_type<Container>&>());
// For combinatoric functions, if the Containers iterator dereferences
// to a reference, then this is a std::reference_wrapper for that type
// otherwise it's a non-const of that type
template <typename Container>
using collection_item_type =
typename std::conditional<
std::is_reference<iterator_deref<Container>>::value,
std::reference_wrapper<
typename std::remove_reference<
iterator_deref<Container>>::type>,
typename std::remove_const<
iterator_deref<Container>>::type>::type;
}
#endif // #ifndef ITERBASE_HPP_
<|endoftext|>
|
<commit_before>/*
* Copyright 2016-2017 gtalent2@gmail.com
*
* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/.
*/
#include <ox/fs/filesystem.hpp>
#include <ox/std/std.hpp>
#include "addresses.hpp"
#include "media.hpp"
#include "gba.hpp"
#include "../gfx.hpp"
namespace nostalgia {
namespace core {
using namespace ox;
#define TILE_ADDR ((CharBlock*) 0x06000000)
#define TILE8_ADDR ((CharBlock8*) 0x06000000)
const auto GBA_TILE_COLUMNS = 32;
// map ASCII values to the nostalgia charset
static char charMap[128] = {
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
38, // !
0,
0,
0,
0,
0,
0,
42, // (
43, // )
0,
0,
37, // ,
0,
39, // .
0,
27, // 0
28, // 1
29, // 2
30, // 3
31, // 4
32, // 5
33, // 6
34, // 7
35, // 8
36, // 9
40, // :
0, // ;
0, // <
41, // =
0,
0,
0,
1, // A
2, // B
3, // C
4, // D
5, // E
6, // F
7, // G
8, // H
9, // I
10, // J
11, // K
12, // L
13, // M
14, // N
15, // O
16, // P
17, // Q
18, // R
19, // S
20, // T
21, // U
22, // V
23, // W
24, // X
25, // Y
26, // Z
44, // [
0, // backslash
45, // ]
0,
0,
0,
1, // a
2, // b
3, // c
4, // d
5, // e
6, // f
7, // g
8, // h
9, // i
10, // j
11, // k
12, // l
13, // m
14, // n
15, // o
16, // p
17, // q
18, // r
19, // s
20, // t
21, // u
22, // v
23, // w
24, // x
25, // y
26, // z
46, // {
0, // |
48, // }
};
ox::Error initGfx(Context *ctx) {
/* Sprite Mode ----\ */
/* ---\| */
/* Background 0 -\|| */
/* Objects -----\||| */
/* |||| */
REG_DISPCNT = 0x1100;
return 0;
}
// Do NOT use Context in the GBA version of this function.
ox::Error initConsole(Context*) {
const auto CharsetInode = 101;
const auto PaletteStart = sizeof(GbaImageDataHeader);
ox::Error err = 0;
auto fs = (FileStore32*) findMedia();
GbaImageDataHeader imgData;
REG_BG0CNT = (28 << 8) | 1;
if (fs) {
// load the header
err |= fs->read(CharsetInode, 0, sizeof(imgData), &imgData, nullptr);
// load palette
err |= fs->read(CharsetInode, PaletteStart,
512, (uint16_t*) &MEM_PALLETE_BG[0], nullptr);
if (imgData.bpp == 4) {
err |= fs->read(CharsetInode, __builtin_offsetof(GbaImageData, tiles),
sizeof(Tile) * imgData.tileCount, (uint16_t*) &TILE_ADDR[0][1], nullptr);
} else if (imgData.bpp == 8) {
REG_BG0CNT |= (1 << 7); // set to use 8 bits per pixel
err |= fs->read(CharsetInode, __builtin_offsetof(GbaImageData, tiles),
sizeof(Tile8) * imgData.tileCount, (uint16_t*) &TILE8_ADDR[0][1], nullptr);
} else {
err = 1;
}
} else {
err = 1;
}
return err;
}
// Do NOT use Context in the GBA version of this function.
void puts(Context*, int loc, const char *str) {
for (int i = 0; str[i]; i++) {
MEM_BG_MAP[28][loc + i] = charMap[(int) str[i]];
}
}
void setTile(Context *ctx, int layer, int column, int row, uint16_t tile) {
MEM_BG_MAP[28 + layer][row * GBA_TILE_COLUMNS + column] = tile;
}
}
}
<commit_msg>Fill out remaining comments for missing characters in charset table<commit_after>/*
* Copyright 2016-2017 gtalent2@gmail.com
*
* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/.
*/
#include <ox/fs/filesystem.hpp>
#include <ox/std/std.hpp>
#include "addresses.hpp"
#include "media.hpp"
#include "gba.hpp"
#include "../gfx.hpp"
namespace nostalgia {
namespace core {
using namespace ox;
#define TILE_ADDR ((CharBlock*) 0x06000000)
#define TILE8_ADDR ((CharBlock8*) 0x06000000)
const auto GBA_TILE_COLUMNS = 32;
// map ASCII values to the nostalgia charset
static char charMap[128] = {
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0, // space
38, // !
0, // "
0, // #
0, // $
0, // %
0, // &
0, // '
42, // (
43, // )
0, // *
0, // +
37, // ,
0, // -
39, // .
0, // /
27, // 0
28, // 1
29, // 2
30, // 3
31, // 4
32, // 5
33, // 6
34, // 7
35, // 8
36, // 9
40, // :
0, // ;
0, // <
41, // =
0, // >
0, // ?
0, // @
1, // A
2, // B
3, // C
4, // D
5, // E
6, // F
7, // G
8, // H
9, // I
10, // J
11, // K
12, // L
13, // M
14, // N
15, // O
16, // P
17, // Q
18, // R
19, // S
20, // T
21, // U
22, // V
23, // W
24, // X
25, // Y
26, // Z
44, // [
0, // backslash
45, // ]
0, // ^
0, // _
0, // `
1, // a
2, // b
3, // c
4, // d
5, // e
6, // f
7, // g
8, // h
9, // i
10, // j
11, // k
12, // l
13, // m
14, // n
15, // o
16, // p
17, // q
18, // r
19, // s
20, // t
21, // u
22, // v
23, // w
24, // x
25, // y
26, // z
46, // {
0, // |
48, // }
0, // ~
};
ox::Error initGfx(Context *ctx) {
/* Sprite Mode ----\ */
/* ---\| */
/* Background 0 -\|| */
/* Objects -----\||| */
/* |||| */
REG_DISPCNT = 0x1100;
return 0;
}
// Do NOT use Context in the GBA version of this function.
ox::Error initConsole(Context*) {
const auto CharsetInode = 101;
const auto PaletteStart = sizeof(GbaImageDataHeader);
ox::Error err = 0;
auto fs = (FileStore32*) findMedia();
GbaImageDataHeader imgData;
REG_BG0CNT = (28 << 8) | 1;
if (fs) {
// load the header
err |= fs->read(CharsetInode, 0, sizeof(imgData), &imgData, nullptr);
// load palette
err |= fs->read(CharsetInode, PaletteStart,
512, (uint16_t*) &MEM_PALLETE_BG[0], nullptr);
if (imgData.bpp == 4) {
err |= fs->read(CharsetInode, __builtin_offsetof(GbaImageData, tiles),
sizeof(Tile) * imgData.tileCount, (uint16_t*) &TILE_ADDR[0][1], nullptr);
} else if (imgData.bpp == 8) {
REG_BG0CNT |= (1 << 7); // set to use 8 bits per pixel
err |= fs->read(CharsetInode, __builtin_offsetof(GbaImageData, tiles),
sizeof(Tile8) * imgData.tileCount, (uint16_t*) &TILE8_ADDR[0][1], nullptr);
} else {
err = 1;
}
} else {
err = 1;
}
return err;
}
// Do NOT use Context in the GBA version of this function.
void puts(Context*, int loc, const char *str) {
for (int i = 0; str[i]; i++) {
MEM_BG_MAP[28][loc + i] = charMap[(int) str[i]];
}
}
void setTile(Context *ctx, int layer, int column, int row, uint16_t tile) {
MEM_BG_MAP[28 + layer][row * GBA_TILE_COLUMNS + column] = tile;
}
}
}
<|endoftext|>
|
<commit_before>// Copyright (c) 2009-2019 The Bitcoin Core developers
// Copyright (c) 2014-2019 The DigiByte Core developers
// Copyright (c) 2014-2019 The Auroracoin Developers
// Distributed under the MIT software license, see the accompanying
// file COPYING or http://www.opensource.org/licenses/mit-license.php.
#include <qt/test/rpcnestedtests.h>
#include <fs.h>
#include <interfaces/node.h>
#include <rpc/server.h>
#include <qt/rpcconsole.h>
#include <test/setup_common.h>
#include <univalue.h>
#include <util/system.h>
#include <QDir>
#include <QtGlobal>
static UniValue rpcNestedTest_rpc(const JSONRPCRequest& request)
{
if (request.fHelp) {
return "help message";
}
return request.params.write(0, 0);
}
static const CRPCCommand vRPCCommands[] =
{
{ "test", "rpcNestedTest", &rpcNestedTest_rpc, {} },
};
void RPCNestedTests::rpcNestedTests()
{
// do some test setup
// could be moved to a more generic place when we add more tests on QT level
tableRPC.appendCommand("rpcNestedTest", &vRPCCommands[0]);
//mempool.setSanityCheck(1.0);
LogInstance().DisconnectTestLogger(); // Already started by the common test setup, so stop it to avoid interference
TestingSetup test;
if (RPCIsInWarmup(nullptr)) SetRPCWarmupFinished();
std::string result;
std::string result2;
std::string filtered;
auto node = interfaces::MakeNode();
RPCConsole::RPCExecuteCommandLine(*node, result, "getblockchaininfo()[chain]", &filtered); //simple result filtering with path
QVERIFY(result=="main");
QVERIFY(filtered == "getblockchaininfo()[chain]");
RPCConsole::RPCExecuteCommandLine(*node, result, "getblock(getbestblockhash())"); //simple 2 level nesting
RPCConsole::RPCExecuteCommandLine(*node, result, "getblock(getblock(getbestblockhash())[hash], true)");
RPCConsole::RPCExecuteCommandLine(*node, result, "getblock( getblock( getblock(getbestblockhash())[hash] )[hash], true)"); //4 level nesting with whitespace, filtering path and boolean parameter
RPCConsole::RPCExecuteCommandLine(*node, result, "getblockchaininfo");
QVERIFY(result.substr(0,1) == "{");
RPCConsole::RPCExecuteCommandLine(*node, result, "getblockchaininfo()");
QVERIFY(result.substr(0,1) == "{");
RPCConsole::RPCExecuteCommandLine(*node, result, "getblockchaininfo "); //whitespace at the end will be tolerated
QVERIFY(result.substr(0,1) == "{");
(RPCConsole::RPCExecuteCommandLine(*node, result, "getblockchaininfo()[\"chain\"]")); //Quote path identifier are allowed, but look after a child containing the quotes in the key
QVERIFY(result == "null");
(RPCConsole::RPCExecuteCommandLine(*node, result, "createrawtransaction [] {} 0")); //parameter not in brackets are allowed
(RPCConsole::RPCExecuteCommandLine(*node, result2, "createrawtransaction([],{},0)")); //parameter in brackets are allowed
QVERIFY(result == result2);
(RPCConsole::RPCExecuteCommandLine(*node, result2, "createrawtransaction( [], {} , 0 )")); //whitespace between parameters is allowed
QVERIFY(result == result2);
RPCConsole::RPCExecuteCommandLine(*node, result, "getblock(getbestblockhash())[tx][0]", &filtered);
QVERIFY(result == "4a5e1e4baab89f3a32518a88c31bc87f618f76673e2cc77ab2127b7afdeda33b");
QVERIFY(filtered == "getblock(getbestblockhash())[tx][0]");
RPCConsole::RPCParseCommandLine(nullptr, result, "importprivkey", false, &filtered);
QVERIFY(filtered == "importprivkey(…)");
RPCConsole::RPCParseCommandLine(nullptr, result, "signmessagewithprivkey abc", false, &filtered);
QVERIFY(filtered == "signmessagewithprivkey(…)");
RPCConsole::RPCParseCommandLine(nullptr, result, "signmessagewithprivkey abc,def", false, &filtered);
QVERIFY(filtered == "signmessagewithprivkey(…)");
RPCConsole::RPCParseCommandLine(nullptr, result, "signrawtransactionwithkey(abc)", false, &filtered);
QVERIFY(filtered == "signrawtransactionwithkey(…)");
RPCConsole::RPCParseCommandLine(nullptr, result, "walletpassphrase(help())", false, &filtered);
QVERIFY(filtered == "walletpassphrase(…)");
RPCConsole::RPCParseCommandLine(nullptr, result, "walletpassphrasechange(help(walletpassphrasechange(abc)))", false, &filtered);
QVERIFY(filtered == "walletpassphrasechange(…)");
RPCConsole::RPCParseCommandLine(nullptr, result, "help(encryptwallet(abc, def))", false, &filtered);
QVERIFY(filtered == "help(encryptwallet(…))");
RPCConsole::RPCParseCommandLine(nullptr, result, "help(importprivkey())", false, &filtered);
QVERIFY(filtered == "help(importprivkey(…))");
RPCConsole::RPCParseCommandLine(nullptr, result, "help(importprivkey(help()))", false, &filtered);
QVERIFY(filtered == "help(importprivkey(…))");
RPCConsole::RPCParseCommandLine(nullptr, result, "help(importprivkey(abc), walletpassphrase(def))", false, &filtered);
QVERIFY(filtered == "help(importprivkey(…), walletpassphrase(…))");
RPCConsole::RPCExecuteCommandLine(*node, result, "rpcNestedTest");
QVERIFY(result == "[]");
RPCConsole::RPCExecuteCommandLine(*node, result, "rpcNestedTest ''");
QVERIFY(result == "[\"\"]");
RPCConsole::RPCExecuteCommandLine(*node, result, "rpcNestedTest \"\"");
QVERIFY(result == "[\"\"]");
RPCConsole::RPCExecuteCommandLine(*node, result, "rpcNestedTest '' abc");
QVERIFY(result == "[\"\",\"abc\"]");
RPCConsole::RPCExecuteCommandLine(*node, result, "rpcNestedTest abc '' abc");
QVERIFY(result == "[\"abc\",\"\",\"abc\"]");
RPCConsole::RPCExecuteCommandLine(*node, result, "rpcNestedTest abc abc");
QVERIFY(result == "[\"abc\",\"abc\"]");
RPCConsole::RPCExecuteCommandLine(*node, result, "rpcNestedTest abc\t\tabc");
QVERIFY(result == "[\"abc\",\"abc\"]");
RPCConsole::RPCExecuteCommandLine(*node, result, "rpcNestedTest(abc )");
QVERIFY(result == "[\"abc\"]");
RPCConsole::RPCExecuteCommandLine(*node, result, "rpcNestedTest( abc )");
QVERIFY(result == "[\"abc\"]");
RPCConsole::RPCExecuteCommandLine(*node, result, "rpcNestedTest( abc , cba )");
QVERIFY(result == "[\"abc\",\"cba\"]");
// do the QVERIFY_EXCEPTION_THROWN checks only with Qt5.3 and higher (QVERIFY_EXCEPTION_THROWN was introduced in Qt5.3)
QVERIFY_EXCEPTION_THROWN(RPCConsole::RPCExecuteCommandLine(*node, result, "getblockchaininfo() .\n"), std::runtime_error); //invalid syntax
QVERIFY_EXCEPTION_THROWN(RPCConsole::RPCExecuteCommandLine(*node, result, "getblockchaininfo() getblockchaininfo()"), std::runtime_error); //invalid syntax
(RPCConsole::RPCExecuteCommandLine(*node, result, "getblockchaininfo(")); //tolerate non closing brackets if we have no arguments
(RPCConsole::RPCExecuteCommandLine(*node, result, "getblockchaininfo()()()")); //tolerate non command brackts
QVERIFY_EXCEPTION_THROWN(RPCConsole::RPCExecuteCommandLine(*node, result, "getblockchaininfo(True)"), UniValue); //invalid argument
QVERIFY_EXCEPTION_THROWN(RPCConsole::RPCExecuteCommandLine(*node, result, "a(getblockchaininfo(True))"), UniValue); //method not found
QVERIFY_EXCEPTION_THROWN(RPCConsole::RPCExecuteCommandLine(*node, result, "rpcNestedTest abc,,abc"), std::runtime_error); //don't tollerate empty arguments when using ,
QVERIFY_EXCEPTION_THROWN(RPCConsole::RPCExecuteCommandLine(*node, result, "rpcNestedTest(abc,,abc)"), std::runtime_error); //don't tollerate empty arguments when using ,
QVERIFY_EXCEPTION_THROWN(RPCConsole::RPCExecuteCommandLine(*node, result, "rpcNestedTest(abc,,)"), std::runtime_error); //don't tollerate empty arguments when using ,
}
<commit_msg>Bitcoin: f466c4ce846000b2f984b4759f89f3f793fa0100 (Add missing ECC_Stop(); in GUI rpcnestedtests.cpp).<commit_after>// Copyright (c) 2009-2019 The Bitcoin Core developers
// Copyright (c) 2014-2019 The DigiByte Core developers
// Copyright (c) 2014-2019 The Auroracoin Developers
// Distributed under the MIT software license, see the accompanying
// file COPYING or http://www.opensource.org/licenses/mit-license.php.
#include <qt/test/rpcnestedtests.h>
#include <fs.h>
#include <interfaces/node.h>
#include <rpc/server.h>
#include <qt/rpcconsole.h>
#include <test/setup_common.h>
#include <univalue.h>
#include <util/system.h>
#include <QDir>
#include <QtGlobal>
static UniValue rpcNestedTest_rpc(const JSONRPCRequest& request)
{
if (request.fHelp) {
return "help message";
}
return request.params.write(0, 0);
}
static const CRPCCommand vRPCCommands[] =
{
{ "test", "rpcNestedTest", &rpcNestedTest_rpc, {} },
};
void RPCNestedTests::rpcNestedTests()
{
// do some test setup
// could be moved to a more generic place when we add more tests on QT level
tableRPC.appendCommand("rpcNestedTest", &vRPCCommands[0]);
//mempool.setSanityCheck(1.0);
ECC_Stop(); // Already started by the common test setup, so stop it to avoid interference
LogInstance().DisconnectTestLogger();
TestingSetup test;
if (RPCIsInWarmup(nullptr)) SetRPCWarmupFinished();
std::string result;
std::string result2;
std::string filtered;
auto node = interfaces::MakeNode();
RPCConsole::RPCExecuteCommandLine(*node, result, "getblockchaininfo()[chain]", &filtered); //simple result filtering with path
QVERIFY(result=="main");
QVERIFY(filtered == "getblockchaininfo()[chain]");
RPCConsole::RPCExecuteCommandLine(*node, result, "getblock(getbestblockhash())"); //simple 2 level nesting
RPCConsole::RPCExecuteCommandLine(*node, result, "getblock(getblock(getbestblockhash())[hash], true)");
RPCConsole::RPCExecuteCommandLine(*node, result, "getblock( getblock( getblock(getbestblockhash())[hash] )[hash], true)"); //4 level nesting with whitespace, filtering path and boolean parameter
RPCConsole::RPCExecuteCommandLine(*node, result, "getblockchaininfo");
QVERIFY(result.substr(0,1) == "{");
RPCConsole::RPCExecuteCommandLine(*node, result, "getblockchaininfo()");
QVERIFY(result.substr(0,1) == "{");
RPCConsole::RPCExecuteCommandLine(*node, result, "getblockchaininfo "); //whitespace at the end will be tolerated
QVERIFY(result.substr(0,1) == "{");
(RPCConsole::RPCExecuteCommandLine(*node, result, "getblockchaininfo()[\"chain\"]")); //Quote path identifier are allowed, but look after a child containing the quotes in the key
QVERIFY(result == "null");
(RPCConsole::RPCExecuteCommandLine(*node, result, "createrawtransaction [] {} 0")); //parameter not in brackets are allowed
(RPCConsole::RPCExecuteCommandLine(*node, result2, "createrawtransaction([],{},0)")); //parameter in brackets are allowed
QVERIFY(result == result2);
(RPCConsole::RPCExecuteCommandLine(*node, result2, "createrawtransaction( [], {} , 0 )")); //whitespace between parameters is allowed
QVERIFY(result == result2);
RPCConsole::RPCExecuteCommandLine(*node, result, "getblock(getbestblockhash())[tx][0]", &filtered);
QVERIFY(result == "4a5e1e4baab89f3a32518a88c31bc87f618f76673e2cc77ab2127b7afdeda33b");
QVERIFY(filtered == "getblock(getbestblockhash())[tx][0]");
RPCConsole::RPCParseCommandLine(nullptr, result, "importprivkey", false, &filtered);
QVERIFY(filtered == "importprivkey(…)");
RPCConsole::RPCParseCommandLine(nullptr, result, "signmessagewithprivkey abc", false, &filtered);
QVERIFY(filtered == "signmessagewithprivkey(…)");
RPCConsole::RPCParseCommandLine(nullptr, result, "signmessagewithprivkey abc,def", false, &filtered);
QVERIFY(filtered == "signmessagewithprivkey(…)");
RPCConsole::RPCParseCommandLine(nullptr, result, "signrawtransactionwithkey(abc)", false, &filtered);
QVERIFY(filtered == "signrawtransactionwithkey(…)");
RPCConsole::RPCParseCommandLine(nullptr, result, "walletpassphrase(help())", false, &filtered);
QVERIFY(filtered == "walletpassphrase(…)");
RPCConsole::RPCParseCommandLine(nullptr, result, "walletpassphrasechange(help(walletpassphrasechange(abc)))", false, &filtered);
QVERIFY(filtered == "walletpassphrasechange(…)");
RPCConsole::RPCParseCommandLine(nullptr, result, "help(encryptwallet(abc, def))", false, &filtered);
QVERIFY(filtered == "help(encryptwallet(…))");
RPCConsole::RPCParseCommandLine(nullptr, result, "help(importprivkey())", false, &filtered);
QVERIFY(filtered == "help(importprivkey(…))");
RPCConsole::RPCParseCommandLine(nullptr, result, "help(importprivkey(help()))", false, &filtered);
QVERIFY(filtered == "help(importprivkey(…))");
RPCConsole::RPCParseCommandLine(nullptr, result, "help(importprivkey(abc), walletpassphrase(def))", false, &filtered);
QVERIFY(filtered == "help(importprivkey(…), walletpassphrase(…))");
RPCConsole::RPCExecuteCommandLine(*node, result, "rpcNestedTest");
QVERIFY(result == "[]");
RPCConsole::RPCExecuteCommandLine(*node, result, "rpcNestedTest ''");
QVERIFY(result == "[\"\"]");
RPCConsole::RPCExecuteCommandLine(*node, result, "rpcNestedTest \"\"");
QVERIFY(result == "[\"\"]");
RPCConsole::RPCExecuteCommandLine(*node, result, "rpcNestedTest '' abc");
QVERIFY(result == "[\"\",\"abc\"]");
RPCConsole::RPCExecuteCommandLine(*node, result, "rpcNestedTest abc '' abc");
QVERIFY(result == "[\"abc\",\"\",\"abc\"]");
RPCConsole::RPCExecuteCommandLine(*node, result, "rpcNestedTest abc abc");
QVERIFY(result == "[\"abc\",\"abc\"]");
RPCConsole::RPCExecuteCommandLine(*node, result, "rpcNestedTest abc\t\tabc");
QVERIFY(result == "[\"abc\",\"abc\"]");
RPCConsole::RPCExecuteCommandLine(*node, result, "rpcNestedTest(abc )");
QVERIFY(result == "[\"abc\"]");
RPCConsole::RPCExecuteCommandLine(*node, result, "rpcNestedTest( abc )");
QVERIFY(result == "[\"abc\"]");
RPCConsole::RPCExecuteCommandLine(*node, result, "rpcNestedTest( abc , cba )");
QVERIFY(result == "[\"abc\",\"cba\"]");
// do the QVERIFY_EXCEPTION_THROWN checks only with Qt5.3 and higher (QVERIFY_EXCEPTION_THROWN was introduced in Qt5.3)
QVERIFY_EXCEPTION_THROWN(RPCConsole::RPCExecuteCommandLine(*node, result, "getblockchaininfo() .\n"), std::runtime_error); //invalid syntax
QVERIFY_EXCEPTION_THROWN(RPCConsole::RPCExecuteCommandLine(*node, result, "getblockchaininfo() getblockchaininfo()"), std::runtime_error); //invalid syntax
(RPCConsole::RPCExecuteCommandLine(*node, result, "getblockchaininfo(")); //tolerate non closing brackets if we have no arguments
(RPCConsole::RPCExecuteCommandLine(*node, result, "getblockchaininfo()()()")); //tolerate non command brackts
QVERIFY_EXCEPTION_THROWN(RPCConsole::RPCExecuteCommandLine(*node, result, "getblockchaininfo(True)"), UniValue); //invalid argument
QVERIFY_EXCEPTION_THROWN(RPCConsole::RPCExecuteCommandLine(*node, result, "a(getblockchaininfo(True))"), UniValue); //method not found
QVERIFY_EXCEPTION_THROWN(RPCConsole::RPCExecuteCommandLine(*node, result, "rpcNestedTest abc,,abc"), std::runtime_error); //don't tollerate empty arguments when using ,
QVERIFY_EXCEPTION_THROWN(RPCConsole::RPCExecuteCommandLine(*node, result, "rpcNestedTest(abc,,abc)"), std::runtime_error); //don't tollerate empty arguments when using ,
QVERIFY_EXCEPTION_THROWN(RPCConsole::RPCExecuteCommandLine(*node, result, "rpcNestedTest(abc,,)"), std::runtime_error); //don't tollerate empty arguments when using ,
}
<|endoftext|>
|
<commit_before>//
// Copyright (c) 2010 Advanced Micro Devices, Inc. All rights reserved.
//
#ifndef VERSIONS_HPP_
#define VERSIONS_HPP_
#include "utils/macros.hpp"
#ifndef AMD_PLATFORM_NAME
# define AMD_PLATFORM_NAME "AMD Accelerated Parallel Processing"
#endif // AMD_PLATFORM_NAME
#ifndef AMD_PLATFORM_BUILD_NUMBER
# define AMD_PLATFORM_BUILD_NUMBER 2275
#endif // AMD_PLATFORM_BUILD_NUMBER
#ifndef AMD_PLATFORM_REVISION_NUMBER
# define AMD_PLATFORM_REVISION_NUMBER 0
#endif // AMD_PLATFORM_REVISION_NUMBER
#ifndef AMD_PLATFORM_RELEASE_INFO
# define AMD_PLATFORM_RELEASE_INFO
#endif // AMD_PLATFORM_RELEASE_INFO
#define AMD_BUILD_STRING XSTR(AMD_PLATFORM_BUILD_NUMBER) \
"." XSTR(AMD_PLATFORM_REVISION_NUMBER)
#ifndef AMD_PLATFORM_INFO
# define AMD_PLATFORM_INFO "AMD-APP" AMD_PLATFORM_RELEASE_INFO \
DEBUG_ONLY("." IF(IS_OPTIMIZED,"opt","dbg")) " (" AMD_BUILD_STRING ")"
#endif // ATI_PLATFORM_INFO
#endif // VERSIONS_HPP_
<commit_msg>P4 to Git Change 1341218 by johtaylo@johtaylo-jtincrementor-increment on 2016/11/15 03:00:04<commit_after>//
// Copyright (c) 2010 Advanced Micro Devices, Inc. All rights reserved.
//
#ifndef VERSIONS_HPP_
#define VERSIONS_HPP_
#include "utils/macros.hpp"
#ifndef AMD_PLATFORM_NAME
# define AMD_PLATFORM_NAME "AMD Accelerated Parallel Processing"
#endif // AMD_PLATFORM_NAME
#ifndef AMD_PLATFORM_BUILD_NUMBER
# define AMD_PLATFORM_BUILD_NUMBER 2276
#endif // AMD_PLATFORM_BUILD_NUMBER
#ifndef AMD_PLATFORM_REVISION_NUMBER
# define AMD_PLATFORM_REVISION_NUMBER 0
#endif // AMD_PLATFORM_REVISION_NUMBER
#ifndef AMD_PLATFORM_RELEASE_INFO
# define AMD_PLATFORM_RELEASE_INFO
#endif // AMD_PLATFORM_RELEASE_INFO
#define AMD_BUILD_STRING XSTR(AMD_PLATFORM_BUILD_NUMBER) \
"." XSTR(AMD_PLATFORM_REVISION_NUMBER)
#ifndef AMD_PLATFORM_INFO
# define AMD_PLATFORM_INFO "AMD-APP" AMD_PLATFORM_RELEASE_INFO \
DEBUG_ONLY("." IF(IS_OPTIMIZED,"opt","dbg")) " (" AMD_BUILD_STRING ")"
#endif // ATI_PLATFORM_INFO
#endif // VERSIONS_HPP_
<|endoftext|>
|
<commit_before>//
// Copyright (c) 2010 Advanced Micro Devices, Inc. All rights reserved.
//
#ifndef VERSIONS_HPP_
#define VERSIONS_HPP_
#include "utils/macros.hpp"
#ifndef AMD_PLATFORM_NAME
# define AMD_PLATFORM_NAME "AMD Accelerated Parallel Processing"
#endif // AMD_PLATFORM_NAME
#ifndef AMD_PLATFORM_BUILD_NUMBER
# define AMD_PLATFORM_BUILD_NUMBER 1619
#endif // AMD_PLATFORM_BUILD_NUMBER
#ifndef AMD_PLATFORM_REVISION_NUMBER
# define AMD_PLATFORM_REVISION_NUMBER 0
#endif // AMD_PLATFORM_REVISION_NUMBER
#ifndef AMD_PLATFORM_RELEASE_INFO
# define AMD_PLATFORM_RELEASE_INFO
#endif // AMD_PLATFORM_RELEASE_INFO
#define AMD_BUILD_STRING XSTR(AMD_PLATFORM_BUILD_NUMBER) \
"." XSTR(AMD_PLATFORM_REVISION_NUMBER)
#ifndef AMD_PLATFORM_INFO
# define AMD_PLATFORM_INFO "AMD-APP" AMD_PLATFORM_RELEASE_INFO \
DEBUG_ONLY("." IF(IS_OPTIMIZED,"opt","dbg")) " (" AMD_BUILD_STRING ")"
#endif // ATI_PLATFORM_INFO
#endif // VERSIONS_HPP_
<commit_msg>P4 to Git Change 1070089 by johtaylo@johtaylo-JTBUILDER03-increment on 2014/08/26 03:00:12<commit_after>//
// Copyright (c) 2010 Advanced Micro Devices, Inc. All rights reserved.
//
#ifndef VERSIONS_HPP_
#define VERSIONS_HPP_
#include "utils/macros.hpp"
#ifndef AMD_PLATFORM_NAME
# define AMD_PLATFORM_NAME "AMD Accelerated Parallel Processing"
#endif // AMD_PLATFORM_NAME
#ifndef AMD_PLATFORM_BUILD_NUMBER
# define AMD_PLATFORM_BUILD_NUMBER 1620
#endif // AMD_PLATFORM_BUILD_NUMBER
#ifndef AMD_PLATFORM_REVISION_NUMBER
# define AMD_PLATFORM_REVISION_NUMBER 0
#endif // AMD_PLATFORM_REVISION_NUMBER
#ifndef AMD_PLATFORM_RELEASE_INFO
# define AMD_PLATFORM_RELEASE_INFO
#endif // AMD_PLATFORM_RELEASE_INFO
#define AMD_BUILD_STRING XSTR(AMD_PLATFORM_BUILD_NUMBER) \
"." XSTR(AMD_PLATFORM_REVISION_NUMBER)
#ifndef AMD_PLATFORM_INFO
# define AMD_PLATFORM_INFO "AMD-APP" AMD_PLATFORM_RELEASE_INFO \
DEBUG_ONLY("." IF(IS_OPTIMIZED,"opt","dbg")) " (" AMD_BUILD_STRING ")"
#endif // ATI_PLATFORM_INFO
#endif // VERSIONS_HPP_
<|endoftext|>
|
<commit_before>//
// Copyright (c) 2010 Advanced Micro Devices, Inc. All rights reserved.
//
#ifndef VERSIONS_HPP_
#define VERSIONS_HPP_
#include "utils/macros.hpp"
#ifndef AMD_PLATFORM_NAME
#define AMD_PLATFORM_NAME "AMD Accelerated Parallel Processing"
#endif // AMD_PLATFORM_NAME
#ifndef AMD_PLATFORM_BUILD_NUMBER
#define AMD_PLATFORM_BUILD_NUMBER 2556
#endif // AMD_PLATFORM_BUILD_NUMBER
#ifndef AMD_PLATFORM_REVISION_NUMBER
#define AMD_PLATFORM_REVISION_NUMBER 0
#endif // AMD_PLATFORM_REVISION_NUMBER
#ifndef AMD_PLATFORM_RELEASE_INFO
#define AMD_PLATFORM_RELEASE_INFO
#endif // AMD_PLATFORM_RELEASE_INFO
#define AMD_BUILD_STRING \
XSTR(AMD_PLATFORM_BUILD_NUMBER) \
"." XSTR(AMD_PLATFORM_REVISION_NUMBER)
#ifndef AMD_PLATFORM_INFO
#define AMD_PLATFORM_INFO \
"AMD-APP" AMD_PLATFORM_RELEASE_INFO DEBUG_ONLY( \
"." IF(IS_OPTIMIZED, "opt", "dbg")) " (" AMD_BUILD_STRING ")"
#endif // ATI_PLATFORM_INFO
#endif // VERSIONS_HPP_
<commit_msg>P4 to Git Change 1494295 by johtaylo@johtaylo-jtincrementor2-increment on 2017/12/14 03:00:21<commit_after>//
// Copyright (c) 2010 Advanced Micro Devices, Inc. All rights reserved.
//
#ifndef VERSIONS_HPP_
#define VERSIONS_HPP_
#include "utils/macros.hpp"
#ifndef AMD_PLATFORM_NAME
#define AMD_PLATFORM_NAME "AMD Accelerated Parallel Processing"
#endif // AMD_PLATFORM_NAME
#ifndef AMD_PLATFORM_BUILD_NUMBER
#define AMD_PLATFORM_BUILD_NUMBER 2557
#endif // AMD_PLATFORM_BUILD_NUMBER
#ifndef AMD_PLATFORM_REVISION_NUMBER
#define AMD_PLATFORM_REVISION_NUMBER 0
#endif // AMD_PLATFORM_REVISION_NUMBER
#ifndef AMD_PLATFORM_RELEASE_INFO
#define AMD_PLATFORM_RELEASE_INFO
#endif // AMD_PLATFORM_RELEASE_INFO
#define AMD_BUILD_STRING \
XSTR(AMD_PLATFORM_BUILD_NUMBER) \
"." XSTR(AMD_PLATFORM_REVISION_NUMBER)
#ifndef AMD_PLATFORM_INFO
#define AMD_PLATFORM_INFO \
"AMD-APP" AMD_PLATFORM_RELEASE_INFO DEBUG_ONLY( \
"." IF(IS_OPTIMIZED, "opt", "dbg")) " (" AMD_BUILD_STRING ")"
#endif // ATI_PLATFORM_INFO
#endif // VERSIONS_HPP_
<|endoftext|>
|
<commit_before>//
// Copyright (c) 2010 Advanced Micro Devices, Inc. All rights reserved.
//
#ifndef VERSIONS_HPP_
#define VERSIONS_HPP_
#include "utils/macros.hpp"
#ifndef AMD_PLATFORM_NAME
# define AMD_PLATFORM_NAME "AMD Accelerated Parallel Processing"
#endif // AMD_PLATFORM_NAME
#ifndef AMD_PLATFORM_BUILD_NUMBER
# define AMD_PLATFORM_BUILD_NUMBER 1748
#endif // AMD_PLATFORM_BUILD_NUMBER
#ifndef AMD_PLATFORM_REVISION_NUMBER
# define AMD_PLATFORM_REVISION_NUMBER 0
#endif // AMD_PLATFORM_REVISION_NUMBER
#ifndef AMD_PLATFORM_RELEASE_INFO
# define AMD_PLATFORM_RELEASE_INFO
#endif // AMD_PLATFORM_RELEASE_INFO
#define AMD_BUILD_STRING XSTR(AMD_PLATFORM_BUILD_NUMBER) \
"." XSTR(AMD_PLATFORM_REVISION_NUMBER)
#ifndef AMD_PLATFORM_INFO
# define AMD_PLATFORM_INFO "AMD-APP" AMD_PLATFORM_RELEASE_INFO \
DEBUG_ONLY("." IF(IS_OPTIMIZED,"opt","dbg")) " (" AMD_BUILD_STRING ")"
#endif // ATI_PLATFORM_INFO
#endif // VERSIONS_HPP_
<commit_msg>P4 to Git Change 1128129 by johtaylo@johtaylo-JTBUILDER03-increment on 2015/03/06 03:00:15<commit_after>//
// Copyright (c) 2010 Advanced Micro Devices, Inc. All rights reserved.
//
#ifndef VERSIONS_HPP_
#define VERSIONS_HPP_
#include "utils/macros.hpp"
#ifndef AMD_PLATFORM_NAME
# define AMD_PLATFORM_NAME "AMD Accelerated Parallel Processing"
#endif // AMD_PLATFORM_NAME
#ifndef AMD_PLATFORM_BUILD_NUMBER
# define AMD_PLATFORM_BUILD_NUMBER 1749
#endif // AMD_PLATFORM_BUILD_NUMBER
#ifndef AMD_PLATFORM_REVISION_NUMBER
# define AMD_PLATFORM_REVISION_NUMBER 0
#endif // AMD_PLATFORM_REVISION_NUMBER
#ifndef AMD_PLATFORM_RELEASE_INFO
# define AMD_PLATFORM_RELEASE_INFO
#endif // AMD_PLATFORM_RELEASE_INFO
#define AMD_BUILD_STRING XSTR(AMD_PLATFORM_BUILD_NUMBER) \
"." XSTR(AMD_PLATFORM_REVISION_NUMBER)
#ifndef AMD_PLATFORM_INFO
# define AMD_PLATFORM_INFO "AMD-APP" AMD_PLATFORM_RELEASE_INFO \
DEBUG_ONLY("." IF(IS_OPTIMIZED,"opt","dbg")) " (" AMD_BUILD_STRING ")"
#endif // ATI_PLATFORM_INFO
#endif // VERSIONS_HPP_
<|endoftext|>
|
<commit_before>//
// Copyright (c) 2010 Advanced Micro Devices, Inc. All rights reserved.
//
#ifndef VERSIONS_HPP_
#define VERSIONS_HPP_
#include "utils/macros.hpp"
#ifndef AMD_PLATFORM_NAME
# define AMD_PLATFORM_NAME "AMD Accelerated Parallel Processing"
#endif // AMD_PLATFORM_NAME
#ifndef AMD_PLATFORM_BUILD_NUMBER
# define AMD_PLATFORM_BUILD_NUMBER 2139
#endif // AMD_PLATFORM_BUILD_NUMBER
#ifndef AMD_PLATFORM_REVISION_NUMBER
# define AMD_PLATFORM_REVISION_NUMBER 0
#endif // AMD_PLATFORM_REVISION_NUMBER
#ifndef AMD_PLATFORM_RELEASE_INFO
# define AMD_PLATFORM_RELEASE_INFO
#endif // AMD_PLATFORM_RELEASE_INFO
#define AMD_BUILD_STRING XSTR(AMD_PLATFORM_BUILD_NUMBER) \
"." XSTR(AMD_PLATFORM_REVISION_NUMBER)
#ifndef AMD_PLATFORM_INFO
# define AMD_PLATFORM_INFO "AMD-APP" AMD_PLATFORM_RELEASE_INFO \
DEBUG_ONLY("." IF(IS_OPTIMIZED,"opt","dbg")) " (" AMD_BUILD_STRING ")"
#endif // ATI_PLATFORM_INFO
#endif // VERSIONS_HPP_
<commit_msg>P4 to Git Change 1278058 by johtaylo@johtaylo-JTBUILDER03-increment on 2016/06/09 03:00:11<commit_after>//
// Copyright (c) 2010 Advanced Micro Devices, Inc. All rights reserved.
//
#ifndef VERSIONS_HPP_
#define VERSIONS_HPP_
#include "utils/macros.hpp"
#ifndef AMD_PLATFORM_NAME
# define AMD_PLATFORM_NAME "AMD Accelerated Parallel Processing"
#endif // AMD_PLATFORM_NAME
#ifndef AMD_PLATFORM_BUILD_NUMBER
# define AMD_PLATFORM_BUILD_NUMBER 2140
#endif // AMD_PLATFORM_BUILD_NUMBER
#ifndef AMD_PLATFORM_REVISION_NUMBER
# define AMD_PLATFORM_REVISION_NUMBER 0
#endif // AMD_PLATFORM_REVISION_NUMBER
#ifndef AMD_PLATFORM_RELEASE_INFO
# define AMD_PLATFORM_RELEASE_INFO
#endif // AMD_PLATFORM_RELEASE_INFO
#define AMD_BUILD_STRING XSTR(AMD_PLATFORM_BUILD_NUMBER) \
"." XSTR(AMD_PLATFORM_REVISION_NUMBER)
#ifndef AMD_PLATFORM_INFO
# define AMD_PLATFORM_INFO "AMD-APP" AMD_PLATFORM_RELEASE_INFO \
DEBUG_ONLY("." IF(IS_OPTIMIZED,"opt","dbg")) " (" AMD_BUILD_STRING ")"
#endif // ATI_PLATFORM_INFO
#endif // VERSIONS_HPP_
<|endoftext|>
|
<commit_before>/*
* Copyright 2010 Utkin Dmitry
*
* 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.
*/
/*
* This file is part of the WSF Staff project.
* Please, visit http://code.google.com/p/staff for more information.
*/
#ifdef WIN32
#include <my_global.h>
#endif
#include <mysql.h>
#include <set>
#include <algorithm>
#include <staff/utils/SharedPtr.h>
#include <staff/utils/stringutils.h>
#include <staff/utils/tostring.h>
#include <staff/utils/fromstring.h>
#include <staff/utils/Log.h>
#include <staff/xml/Element.h>
#include <staff/common/Exception.h>
#include <staff/common/Runtime.h>
#include <staff/common/DataObject.h>
#include <staff/das/common/DataSource.h>
#include <staff/das/common/Executor.h>
#include "MySql.h"
namespace staff
{
namespace das
{
class MySqlProvider::MySqlImpl
{
public:
MySqlImpl():
m_sHost("localhost"),
m_sPort("3306"),
m_ushPort(0)
{
m_sSupportedDmlStmt.insert("INSERT");
m_sSupportedDmlStmt.insert("REPLACE");
m_sSupportedDmlStmt.insert("UPDATE");
m_sSupportedDmlStmt.insert("DELETE");
m_sSupportedDmlStmt.insert("SELECT");
}
public:
static const std::string m_sName;
static const std::string m_sDescr;
std::string m_sHost;
std::string m_sPort;
unsigned short m_ushPort;
std::string m_sDataBase;
std::string m_sLogin;
std::string m_sPassword;
std::set<std::string> m_sSupportedDmlStmt;
};
const std::string MySqlProvider::MySqlImpl::m_sName = "staff.das.MySql";
const std::string MySqlProvider::MySqlImpl::m_sDescr = "MySql data access provider";
// ---------------------------------------------------------------
class MySqlQueryExecutor: public IQueryExecutor
{
public:
MySqlQueryExecutor(MySqlProvider* pProvider,
const std::string& sHost,
unsigned short ushPort,
const std::string& sDataBase,
const std::string& sLogin,
const std::string& sPassword):
m_pProvider(pProvider), m_pStmt(NULL),
m_nFieldsCount(0), m_nRowsCount(0), m_nCurrentRow(0),
m_bConnected(false)
{
mysql_init(&m_tConn);
MYSQL* pResult = mysql_real_connect(&m_tConn, sHost.c_str(), sLogin.c_str(),
sPassword.c_str(), sDataBase.c_str(),
ushPort, NULL, 0);
STAFF_ASSERT(pResult, std::string("Failed to connect to db: ") + mysql_error(&m_tConn));
m_bConnected = true;
int nResult = mysql_set_character_set(&m_tConn, "UTF8");
STAFF_ASSERT(nResult == 0, std::string("error setting encoding: ") + mysql_error(&m_tConn));
}
virtual ~MySqlQueryExecutor()
{
if (m_bConnected)
{
Reset();
mysql_close(&m_tConn);
m_bConnected = false;
}
}
virtual void Reset()
{
if (m_pStmt)
{
mysql_stmt_close(m_pStmt);
m_pStmt = NULL;
m_nFieldsCount = 0;
m_nRowsCount = 0;
m_nCurrentRow = 0;
}
}
virtual void Execute(const std::string& sExecute, const StringList& rlsParams)
{
STAFF_ASSERT(m_bConnected, "Not Initialized");
Reset();
// workaround: MySQL does not support prepared statements for DML other than:
// INSERT, REPLACE, UPDATE, DELETE, CREATE TABLE, SELECT
std::string sDml = sExecute;
StringTrimLeft(sDml);
std::string::size_type nPos = sDml.find_first_of(" \n\r\t");
if (nPos != std::string::npos)
sDml.erase(nPos);
std::transform(sDml.begin(), sDml.end(), sDml.begin(), ::toupper);
if (m_pProvider->m_pImpl->m_sSupportedDmlStmt.count(sDml) == 0) {
// execute query without using of stmt
// no parameters are supported in that mode
int nStatus = mysql_query(&m_tConn, sExecute.c_str());
STAFF_ASSERT(nStatus == 0, "error executing query #" + ToString(nStatus) + ": \n"
+ std::string(mysql_error(&m_tConn))
+ "\nQuery was:\n----------\n" + sExecute + "\n----------\n");
return;
}
MYSQL_BIND* paBind = NULL;
m_pStmt = mysql_stmt_init(&m_tConn);
STAFF_ASSERT(m_pStmt, "Can't init STMT: "
+ std::string(mysql_error(&m_tConn))
+ "\nQuery was:\n----------\n" + sExecute + "\n----------\n");
try
{
paBind = reinterpret_cast<MYSQL_BIND*>(malloc(sizeof(MYSQL_BIND) * rlsParams.size()));
STAFF_ASSERT(paBind, "Memory allocation failed!");
memset(paBind, 0, sizeof(MYSQL_BIND) * rlsParams.size());
int nStatus = mysql_stmt_prepare(m_pStmt, sExecute.c_str(), sExecute.size());
STAFF_ASSERT(nStatus == 0, "Failed to prepare STMT: "
+ std::string(mysql_stmt_error(m_pStmt))
+ "\nQuery was:\n----------\n" + sExecute + "\n----------\n");
unsigned long nParamCount = mysql_stmt_param_count(m_pStmt);
STAFF_ASSERT(nParamCount == rlsParams.size(), "STMT count != params count: "
+ ToString(nParamCount) + " != " + ToString(rlsParams.size()) );
int nPos = 0;
static my_bool bNull = 1;
static my_bool bNotNull = 0;
for (StringList::const_iterator itParam = rlsParams.begin();
itParam != rlsParams.end(); ++itParam, ++nPos)
{
MYSQL_BIND* pBind = &paBind[nPos];
pBind->buffer_type = MYSQL_TYPE_STRING;
if (*itParam == STAFF_DAS_NULL_VALUE)
{
pBind->is_null = &bNull;
}
else
{
pBind->is_null = &bNotNull;
pBind->buffer = const_cast<void*>(reinterpret_cast<const void*>(itParam->c_str()));
pBind->buffer_length = itParam->size();
pBind->length = &pBind->buffer_length;
}
}
STAFF_ASSERT(mysql_stmt_bind_param(m_pStmt, paBind) == 0,
"Failed to bind param: #" + ToString(nStatus) + ": \n"
+ std::string(mysql_stmt_error(m_pStmt))
+ "\nQuery was:\n----------\n" + sExecute + "\n----------\n");
nStatus = mysql_stmt_execute(m_pStmt);
STAFF_ASSERT(nStatus == 0, "error executing query #" + ToString(nStatus) + ": \n"
+ std::string(mysql_stmt_error(m_pStmt))
+ "\nQuery was:\n----------\n" + sExecute + "\n----------\n");
free(paBind);
}
catch (...)
{
mysql_stmt_close(m_pStmt);
m_pStmt = NULL;
free(paBind);
throw;
}
int nFieldsCount = mysql_stmt_field_count(m_pStmt);
if (nFieldsCount > 0)
{
my_bool bUpdateMaxLength = 1;
mysql_stmt_attr_set(m_pStmt, STMT_ATTR_UPDATE_MAX_LENGTH, &bUpdateMaxLength);
int nRes = mysql_stmt_store_result(m_pStmt);
STAFF_ASSERT(!nRes, "Can not retrieve result: \n"
+ std::string(mysql_error(&m_tConn)));
m_nFieldsCount = nFieldsCount;
m_nRowsCount = mysql_stmt_num_rows(m_pStmt);
}
}
virtual void GetFieldsNames(StringList& rNames)
{
if (rNames.size() != m_nFieldsCount)
{
rNames.resize(m_nFieldsCount);
}
if (m_pStmt)
{
MYSQL_FIELD* pFields = m_pStmt->fields;
const char* szFieldName = NULL;
int nField = 0;
for (StringList::iterator itItem = rNames.begin();
itItem != rNames.end(); ++itItem, ++nField)
{
szFieldName = pFields[nField].name;
STAFF_ASSERT(szFieldName, "Error while getting field name");
*itItem = szFieldName;
}
}
}
virtual bool GetNextResult(StringList& rResult)
{
if (!m_pStmt || m_nCurrentRow == m_nRowsCount)
{
return false;
}
if (rResult.size() != m_nFieldsCount)
{
rResult.resize(m_nFieldsCount);
}
MYSQL_BIND* paBind = reinterpret_cast<MYSQL_BIND*>(malloc(sizeof(MYSQL_BIND) * m_nFieldsCount));
STAFF_ASSERT(paBind, "Memory allocation failed!");
memset(paBind, 0, sizeof(MYSQL_BIND) * m_nFieldsCount);
try
{
MYSQL_RES* pMetadata = mysql_stmt_result_metadata(m_pStmt);
for (unsigned nField = 0; nField < m_nFieldsCount; ++nField)
{
unsigned long ulMaxLength = pMetadata->fields[nField].max_length;
paBind[nField].buffer_type = MYSQL_TYPE_STRING;
paBind[nField].is_null = &paBind[nField].is_null_value;
if (ulMaxLength)
{
char* szData = reinterpret_cast<char*>(malloc(ulMaxLength));
STAFF_ASSERT(szData, "Memory allocation failed!");
memset(szData, 0, ulMaxLength);
paBind[nField].buffer = szData;
paBind[nField].buffer_length = ulMaxLength;
}
}
mysql_free_result(pMetadata);
STAFF_ASSERT(!mysql_stmt_bind_result(m_pStmt, paBind), "Can't bind result: \n"
+ std::string(mysql_stmt_error(m_pStmt)));
if (mysql_stmt_fetch(m_pStmt))
{
LogWarning() << "can't fetch stmt: " << mysql_stmt_error(m_pStmt);
Reset();
return false;
}
unsigned nField = 0;
for (StringList::iterator itResult = rResult.begin();
itResult != rResult.end(); ++itResult, ++nField)
{
if (paBind[nField].is_null_value)
{
*itResult = STAFF_DAS_NULL_VALUE;
}
else
{
STAFF_ASSERT(!mysql_stmt_fetch_column(m_pStmt, &paBind[nField], nField, 0),
"Failed to fetch column: " + std::string(mysql_stmt_error(m_pStmt)));
itResult->assign(static_cast<const char*>(paBind[nField].buffer),
paBind[nField].buffer_length);
}
free(paBind[nField].buffer);
}
}
catch (...)
{
free(paBind);
throw;
}
free(paBind);
++m_nCurrentRow;
return true;
}
private:
MYSQL m_tConn;
MySqlProvider* m_pProvider;
MYSQL_RES* m_pResult;
MYSQL_STMT* m_pStmt;
unsigned m_nFieldsCount;
unsigned long long m_nRowsCount;
unsigned long long m_nCurrentRow;
bool m_bConnected;
};
MySqlProvider::MySqlProvider()
{
m_pImpl = new MySqlImpl;
}
MySqlProvider::~MySqlProvider()
{
delete m_pImpl;
}
void MySqlProvider::Init(const xml::Element& rConfig)
{
// initialize connection
const xml::Element& rConnection = rConfig.GetChildElementByName("connection");
m_pImpl->m_sHost = rConnection.GetChildElementByName("host").GetTextValue();
m_pImpl->m_sPort = rConnection.GetChildElementByName("port").GetTextValue();
m_pImpl->m_sDataBase = rConnection.GetChildElementByName("db").GetTextValue();
m_pImpl->m_sLogin = rConnection.GetChildElementByName("login").GetTextValue();
m_pImpl->m_sPassword = rConnection.GetChildElementByName("password").GetTextValue();
FromString(m_pImpl->m_sPort, m_pImpl->m_ushPort);
}
void MySqlProvider::Deinit()
{
}
const std::string& MySqlProvider::GetName() const
{
return MySqlImpl::m_sName;
}
const std::string& MySqlProvider::GetDescr() const
{
return MySqlImpl::m_sDescr;
}
PExecutor MySqlProvider::GetExecutor()
{
return new MySqlQueryExecutor(this, m_pImpl->m_sHost, m_pImpl->m_ushPort,
m_pImpl->m_sDataBase, m_pImpl->m_sLogin,
m_pImpl->m_sPassword);
}
}
}
<commit_msg>das:mysql added "SET" to list of supported DML with prepaired statements<commit_after>/*
* Copyright 2010 Utkin Dmitry
*
* 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.
*/
/*
* This file is part of the WSF Staff project.
* Please, visit http://code.google.com/p/staff for more information.
*/
#ifdef WIN32
#include <my_global.h>
#endif
#include <mysql.h>
#include <set>
#include <algorithm>
#include <staff/utils/SharedPtr.h>
#include <staff/utils/stringutils.h>
#include <staff/utils/tostring.h>
#include <staff/utils/fromstring.h>
#include <staff/utils/Log.h>
#include <staff/xml/Element.h>
#include <staff/common/Exception.h>
#include <staff/common/Runtime.h>
#include <staff/common/DataObject.h>
#include <staff/das/common/DataSource.h>
#include <staff/das/common/Executor.h>
#include "MySql.h"
namespace staff
{
namespace das
{
class MySqlProvider::MySqlImpl
{
public:
MySqlImpl():
m_sHost("localhost"),
m_sPort("3306"),
m_ushPort(0)
{
m_sSupportedDmlStmt.insert("INSERT");
m_sSupportedDmlStmt.insert("REPLACE");
m_sSupportedDmlStmt.insert("UPDATE");
m_sSupportedDmlStmt.insert("DELETE");
m_sSupportedDmlStmt.insert("SELECT");
m_sSupportedDmlStmt.insert("SET");
}
public:
static const std::string m_sName;
static const std::string m_sDescr;
std::string m_sHost;
std::string m_sPort;
unsigned short m_ushPort;
std::string m_sDataBase;
std::string m_sLogin;
std::string m_sPassword;
std::set<std::string> m_sSupportedDmlStmt;
};
const std::string MySqlProvider::MySqlImpl::m_sName = "staff.das.MySql";
const std::string MySqlProvider::MySqlImpl::m_sDescr = "MySql data access provider";
// ---------------------------------------------------------------
class MySqlQueryExecutor: public IQueryExecutor
{
public:
MySqlQueryExecutor(MySqlProvider* pProvider,
const std::string& sHost,
unsigned short ushPort,
const std::string& sDataBase,
const std::string& sLogin,
const std::string& sPassword):
m_pProvider(pProvider), m_pStmt(NULL),
m_nFieldsCount(0), m_nRowsCount(0), m_nCurrentRow(0),
m_bConnected(false)
{
mysql_init(&m_tConn);
MYSQL* pResult = mysql_real_connect(&m_tConn, sHost.c_str(), sLogin.c_str(),
sPassword.c_str(), sDataBase.c_str(),
ushPort, NULL, 0);
STAFF_ASSERT(pResult, std::string("Failed to connect to db: ") + mysql_error(&m_tConn));
m_bConnected = true;
int nResult = mysql_set_character_set(&m_tConn, "UTF8");
STAFF_ASSERT(nResult == 0, std::string("error setting encoding: ") + mysql_error(&m_tConn));
}
virtual ~MySqlQueryExecutor()
{
if (m_bConnected)
{
Reset();
mysql_close(&m_tConn);
m_bConnected = false;
}
}
virtual void Reset()
{
if (m_pStmt)
{
mysql_stmt_close(m_pStmt);
m_pStmt = NULL;
m_nFieldsCount = 0;
m_nRowsCount = 0;
m_nCurrentRow = 0;
}
}
virtual void Execute(const std::string& sExecute, const StringList& rlsParams)
{
STAFF_ASSERT(m_bConnected, "Not Initialized");
Reset();
// workaround: MySQL does not support prepared statements for DML other than:
// INSERT, REPLACE, UPDATE, DELETE, CREATE TABLE, SELECT
std::string sDml = sExecute;
StringTrimLeft(sDml);
std::string::size_type nPos = sDml.find_first_of(" \n\r\t");
if (nPos != std::string::npos)
sDml.erase(nPos);
std::transform(sDml.begin(), sDml.end(), sDml.begin(), ::toupper);
if (m_pProvider->m_pImpl->m_sSupportedDmlStmt.count(sDml) == 0) {
// execute query without using of stmt
// no parameters are supported in that mode
int nStatus = mysql_query(&m_tConn, sExecute.c_str());
STAFF_ASSERT(nStatus == 0, "error executing query #" + ToString(nStatus) + ": \n"
+ std::string(mysql_error(&m_tConn))
+ "\nQuery was:\n----------\n" + sExecute + "\n----------\n");
return;
}
MYSQL_BIND* paBind = NULL;
m_pStmt = mysql_stmt_init(&m_tConn);
STAFF_ASSERT(m_pStmt, "Can't init STMT: "
+ std::string(mysql_error(&m_tConn))
+ "\nQuery was:\n----------\n" + sExecute + "\n----------\n");
try
{
paBind = reinterpret_cast<MYSQL_BIND*>(malloc(sizeof(MYSQL_BIND) * rlsParams.size()));
STAFF_ASSERT(paBind, "Memory allocation failed!");
memset(paBind, 0, sizeof(MYSQL_BIND) * rlsParams.size());
int nStatus = mysql_stmt_prepare(m_pStmt, sExecute.c_str(), sExecute.size());
STAFF_ASSERT(nStatus == 0, "Failed to prepare STMT: "
+ std::string(mysql_stmt_error(m_pStmt))
+ "\nQuery was:\n----------\n" + sExecute + "\n----------\n");
unsigned long nParamCount = mysql_stmt_param_count(m_pStmt);
STAFF_ASSERT(nParamCount == rlsParams.size(), "STMT count != params count: "
+ ToString(nParamCount) + " != " + ToString(rlsParams.size()) );
int nPos = 0;
static my_bool bNull = 1;
static my_bool bNotNull = 0;
for (StringList::const_iterator itParam = rlsParams.begin();
itParam != rlsParams.end(); ++itParam, ++nPos)
{
MYSQL_BIND* pBind = &paBind[nPos];
pBind->buffer_type = MYSQL_TYPE_STRING;
if (*itParam == STAFF_DAS_NULL_VALUE)
{
pBind->is_null = &bNull;
}
else
{
pBind->is_null = &bNotNull;
pBind->buffer = const_cast<void*>(reinterpret_cast<const void*>(itParam->c_str()));
pBind->buffer_length = itParam->size();
pBind->length = &pBind->buffer_length;
}
}
STAFF_ASSERT(mysql_stmt_bind_param(m_pStmt, paBind) == 0,
"Failed to bind param: #" + ToString(nStatus) + ": \n"
+ std::string(mysql_stmt_error(m_pStmt))
+ "\nQuery was:\n----------\n" + sExecute + "\n----------\n");
nStatus = mysql_stmt_execute(m_pStmt);
STAFF_ASSERT(nStatus == 0, "error executing query #" + ToString(nStatus) + ": \n"
+ std::string(mysql_stmt_error(m_pStmt))
+ "\nQuery was:\n----------\n" + sExecute + "\n----------\n");
free(paBind);
}
catch (...)
{
mysql_stmt_close(m_pStmt);
m_pStmt = NULL;
free(paBind);
throw;
}
int nFieldsCount = mysql_stmt_field_count(m_pStmt);
if (nFieldsCount > 0)
{
my_bool bUpdateMaxLength = 1;
mysql_stmt_attr_set(m_pStmt, STMT_ATTR_UPDATE_MAX_LENGTH, &bUpdateMaxLength);
int nRes = mysql_stmt_store_result(m_pStmt);
STAFF_ASSERT(!nRes, "Can not retrieve result: \n"
+ std::string(mysql_error(&m_tConn)));
m_nFieldsCount = nFieldsCount;
m_nRowsCount = mysql_stmt_num_rows(m_pStmt);
}
}
virtual void GetFieldsNames(StringList& rNames)
{
if (rNames.size() != m_nFieldsCount)
{
rNames.resize(m_nFieldsCount);
}
if (m_pStmt)
{
MYSQL_FIELD* pFields = m_pStmt->fields;
const char* szFieldName = NULL;
int nField = 0;
for (StringList::iterator itItem = rNames.begin();
itItem != rNames.end(); ++itItem, ++nField)
{
szFieldName = pFields[nField].name;
STAFF_ASSERT(szFieldName, "Error while getting field name");
*itItem = szFieldName;
}
}
}
virtual bool GetNextResult(StringList& rResult)
{
if (!m_pStmt || m_nCurrentRow == m_nRowsCount)
{
return false;
}
if (rResult.size() != m_nFieldsCount)
{
rResult.resize(m_nFieldsCount);
}
MYSQL_BIND* paBind = reinterpret_cast<MYSQL_BIND*>(malloc(sizeof(MYSQL_BIND) * m_nFieldsCount));
STAFF_ASSERT(paBind, "Memory allocation failed!");
memset(paBind, 0, sizeof(MYSQL_BIND) * m_nFieldsCount);
try
{
MYSQL_RES* pMetadata = mysql_stmt_result_metadata(m_pStmt);
for (unsigned nField = 0; nField < m_nFieldsCount; ++nField)
{
unsigned long ulMaxLength = pMetadata->fields[nField].max_length;
paBind[nField].buffer_type = MYSQL_TYPE_STRING;
paBind[nField].is_null = &paBind[nField].is_null_value;
if (ulMaxLength)
{
char* szData = reinterpret_cast<char*>(malloc(ulMaxLength));
STAFF_ASSERT(szData, "Memory allocation failed!");
memset(szData, 0, ulMaxLength);
paBind[nField].buffer = szData;
paBind[nField].buffer_length = ulMaxLength;
}
}
mysql_free_result(pMetadata);
STAFF_ASSERT(!mysql_stmt_bind_result(m_pStmt, paBind), "Can't bind result: \n"
+ std::string(mysql_stmt_error(m_pStmt)));
if (mysql_stmt_fetch(m_pStmt))
{
LogWarning() << "can't fetch stmt: " << mysql_stmt_error(m_pStmt);
Reset();
return false;
}
unsigned nField = 0;
for (StringList::iterator itResult = rResult.begin();
itResult != rResult.end(); ++itResult, ++nField)
{
if (paBind[nField].is_null_value)
{
*itResult = STAFF_DAS_NULL_VALUE;
}
else
{
STAFF_ASSERT(!mysql_stmt_fetch_column(m_pStmt, &paBind[nField], nField, 0),
"Failed to fetch column: " + std::string(mysql_stmt_error(m_pStmt)));
itResult->assign(static_cast<const char*>(paBind[nField].buffer),
paBind[nField].buffer_length);
}
free(paBind[nField].buffer);
}
}
catch (...)
{
free(paBind);
throw;
}
free(paBind);
++m_nCurrentRow;
return true;
}
private:
MYSQL m_tConn;
MySqlProvider* m_pProvider;
MYSQL_RES* m_pResult;
MYSQL_STMT* m_pStmt;
unsigned m_nFieldsCount;
unsigned long long m_nRowsCount;
unsigned long long m_nCurrentRow;
bool m_bConnected;
};
MySqlProvider::MySqlProvider()
{
m_pImpl = new MySqlImpl;
}
MySqlProvider::~MySqlProvider()
{
delete m_pImpl;
}
void MySqlProvider::Init(const xml::Element& rConfig)
{
// initialize connection
const xml::Element& rConnection = rConfig.GetChildElementByName("connection");
m_pImpl->m_sHost = rConnection.GetChildElementByName("host").GetTextValue();
m_pImpl->m_sPort = rConnection.GetChildElementByName("port").GetTextValue();
m_pImpl->m_sDataBase = rConnection.GetChildElementByName("db").GetTextValue();
m_pImpl->m_sLogin = rConnection.GetChildElementByName("login").GetTextValue();
m_pImpl->m_sPassword = rConnection.GetChildElementByName("password").GetTextValue();
FromString(m_pImpl->m_sPort, m_pImpl->m_ushPort);
}
void MySqlProvider::Deinit()
{
}
const std::string& MySqlProvider::GetName() const
{
return MySqlImpl::m_sName;
}
const std::string& MySqlProvider::GetDescr() const
{
return MySqlImpl::m_sDescr;
}
PExecutor MySqlProvider::GetExecutor()
{
return new MySqlQueryExecutor(this, m_pImpl->m_sHost, m_pImpl->m_ushPort,
m_pImpl->m_sDataBase, m_pImpl->m_sLogin,
m_pImpl->m_sPassword);
}
}
}
<|endoftext|>
|
<commit_before>//
// Copyright (c) 2010 Advanced Micro Devices, Inc. All rights reserved.
//
#ifndef VERSIONS_HPP_
#define VERSIONS_HPP_
#include "utils/macros.hpp"
#ifndef AMD_PLATFORM_NAME
#define AMD_PLATFORM_NAME "AMD Accelerated Parallel Processing"
#endif // AMD_PLATFORM_NAME
#ifndef AMD_PLATFORM_BUILD_NUMBER
#define AMD_PLATFORM_BUILD_NUMBER 2888
#endif // AMD_PLATFORM_BUILD_NUMBER
#ifndef AMD_PLATFORM_REVISION_NUMBER
#define AMD_PLATFORM_REVISION_NUMBER 0
#endif // AMD_PLATFORM_REVISION_NUMBER
#ifndef AMD_PLATFORM_RELEASE_INFO
#define AMD_PLATFORM_RELEASE_INFO
#endif // AMD_PLATFORM_RELEASE_INFO
#define AMD_BUILD_STRING \
XSTR(AMD_PLATFORM_BUILD_NUMBER) \
"." XSTR(AMD_PLATFORM_REVISION_NUMBER)
#ifndef AMD_PLATFORM_INFO
#define AMD_PLATFORM_INFO \
"AMD-APP" AMD_PLATFORM_RELEASE_INFO DEBUG_ONLY( \
"." IF(IS_OPTIMIZED, "opt", "dbg")) " (" AMD_BUILD_STRING ")"
#endif // ATI_PLATFORM_INFO
#endif // VERSIONS_HPP_
<commit_msg>P4 to Git Change 1777875 by chui@ocl-promo-incrementor on 2019/05/03 03:00:03<commit_after>//
// Copyright (c) 2010 Advanced Micro Devices, Inc. All rights reserved.
//
#ifndef VERSIONS_HPP_
#define VERSIONS_HPP_
#include "utils/macros.hpp"
#ifndef AMD_PLATFORM_NAME
#define AMD_PLATFORM_NAME "AMD Accelerated Parallel Processing"
#endif // AMD_PLATFORM_NAME
#ifndef AMD_PLATFORM_BUILD_NUMBER
#define AMD_PLATFORM_BUILD_NUMBER 2889
#endif // AMD_PLATFORM_BUILD_NUMBER
#ifndef AMD_PLATFORM_REVISION_NUMBER
#define AMD_PLATFORM_REVISION_NUMBER 0
#endif // AMD_PLATFORM_REVISION_NUMBER
#ifndef AMD_PLATFORM_RELEASE_INFO
#define AMD_PLATFORM_RELEASE_INFO
#endif // AMD_PLATFORM_RELEASE_INFO
#define AMD_BUILD_STRING \
XSTR(AMD_PLATFORM_BUILD_NUMBER) \
"." XSTR(AMD_PLATFORM_REVISION_NUMBER)
#ifndef AMD_PLATFORM_INFO
#define AMD_PLATFORM_INFO \
"AMD-APP" AMD_PLATFORM_RELEASE_INFO DEBUG_ONLY( \
"." IF(IS_OPTIMIZED, "opt", "dbg")) " (" AMD_BUILD_STRING ")"
#endif // ATI_PLATFORM_INFO
#endif // VERSIONS_HPP_
<|endoftext|>
|
<commit_before>#include <iostream>
#include <string>
#include <vector>
#include <stdexcept>
#include <boost/compute.hpp>
#include <algorithm>
#include <QtGui>
#include <QtOpenGL>
#include <boost/compute/command_queue.hpp>
#include <boost/compute/kernel.hpp>
#include <boost/compute/program.hpp>
#include <boost/compute/source.hpp>
#include <boost/compute/system.hpp>
#include <boost/compute/interop/opengl.hpp>
using namespace std;
namespace compute = boost::compute;
int main (int argc, char* argv[])
{
// get the default compute device
compute::device gpu = compute::system::default_device();
// create a compute context and command queue
compute::context ctx(gpu);
compute::command_queue queue(ctx, gpu);
//set some default values for when no commandline arguments are given
//create accuracy variable
int accuracy = 90;
// create vector on device
compute::vector<int> device_accuracy(1);
// copy from host to device
compute::copy(host_data,
accuracy,
device_accuracy.begin());
//create polygons variable
int polygons = 50;
// create vector on device
compute::vector<int> device_polygons(1);
// copy from host to device
compute::copy(host_data,
host_data + 5,
device_vector.begin());
//create vertices variable
int vertices = 6;
// create vector on device
compute::vector<int> device_vector(5);
// copy from host to device
compute::copy(host_data,
host_data + 5,
device_vector.begin());
//read input commandline arguments
for (int i = 1; i < argc; ++i)
{
if (std::string(argv[i]) == "-a")
{
//initialise desired accuracy variable according to commandline argument -a
accuracy = ;
}
if (std::string(argv[i]) == "-p")
{
//initialise maximum polygons variable according to commandline argument -p
polygons = ;
}
if (std::string(argv[i]) == "-v")
{
//initialise maximum verices per polygon variable according to commandline argument -v
vertices = ;
}
}
//create leaderDNA variable
// create data array on host
int host_data[] = { 1, 3, 5, 7, 9 };
// create vector on device
compute::vector<int> device_vector(5);
// copy from host to device
compute::copy(host_data,
host_data + 5,
device_vector.begin());
//create mutatedDNA variable
// create data array on host
int host_data[] = { 1, 3, 5, 7, 9 };
// create vector on device
compute::vector<int> device_vector(5);
// copy from host to device
compute::copy(host_data,
host_data + 5,
device_vector.begin());
//create leaderDNArender variable
// create data array on host
int host_data[] = { 1, 3, 5, 7, 9 };
// create vector on device
compute::vector<int> device_vector(5);
// copy from host to device
compute::copy(host_data,
host_data + 5,
device_vector.begin());
//create mutatedDNArender variable
// create data array on host
int host_data[] = { 1, 3, 5, 7, 9 };
// create vector on device
compute::vector<int> device_vector(5);
// copy from host to device
compute::copy(host_data,
host_data + 5,
device_vector.begin());
//create original image variable + load image into gpu memory
if (std::string(argv[i]) == "")
{
//load file according to commandline argument into gpu vector
//get x(max), y(max). (image dimensions)
//make image vector on device
compute::vector<float> originalimage(ctx, n);
// copy data to the device
compute::copy(
host_vector.begin(),
host_vector.end(),
device_vector.begin(),
queue
);
}
//initialise DNA with a random seed
//create random leader dna
// generate random dna vector on the host
std::vector<float> host_vector(1000000);
std::generate(host_vector.begin(), host_vector.end(), rand);
// create vector on the device
compute::vector<float> device_vector(1000000, ctx);
// copy data to the device
compute::copy(
host_vector.begin(),
host_vector.end(),
device_vector.begin(),
queue
);
//run render loop until desired accuracy is reached
while (leaderaccuracy<accuracy)
{
//render leader DNA to a raster image in opengl texture
boost::compute::function<int (int)> renderDNA =
boost::compute::make_function_from_source<int (int)>(
"renderDNA",
"int renderDNA(int x)
{ //for each shape in dna
{
glEnable(GL_TEXTURE_2D);
glBindTexture(GL_TEXTURE_2D, gl_texture_);
glBegin(GL_QUADS);
glTexCoord2f(0, 0); glVertex2f(0, 0);
glTexCoord2f(0, 1); glVertex2f(0, h);
glTexCoord2f(1, 1); glVertex2f(w, h);
glTexCoord2f(1, 0); glVertex2f(w, 0);
glEnd();
} }"
);
//compute fitness of leader dna image
//compute what % match DNAimage is to original image
boost::compute::function<int (int)> computefitnesspercent =
boost::compute::make_function_from_source<int (int)>(
"computefitnesspercent",
"int computefitnesspercent(int x) { //read leader dna
//compare input dna to leader dna to find changed polygons
compareDNA(leaderDNA,DNA);
//create bounding box containing changed polygons
//render leader dna within bounding box
leaderrender = renderDNA(leaderDNA,boundx,boundy);
//render input dna within bounding box
inputrender = renderDNA(DNA,boundx,boundy);
//compare leader and input dna rendered bounding boxes
compareimage(leaderrender,inputrender);
//returns % match }"
);
while ()
{
//mutate from the leaderDNA
boost::compute::function<int (int)> mutateDNA =
boost::compute::make_function_from_source<int (int)>(
"mutateDNA",
"int mutateDNA(int DNA)
{
//mutate input DNA randomly
mutated_shape = RANDINT(NUM_SHAPES);
double roulette = RANDDOUBLE(2.8);
double drastic = RANDDOUBLE(2);
// mutate color
if(roulette<1)
{
if(dna_test[mutated_shape].a < 0.01 // completely transparent shapes are stupid
|| roulette<0.25)
{
if(drastic < 1)
{
dna_test[mutated_shape].a += RANDDOUBLE(0.1);
dna_test[mutated_shape].a = CLAMP(dna_test[mutated_shape].a, 0.0, 1.0);
}
else
dna_test[mutated_shape].a = RANDDOUBLE(1.0);
}
else if(roulette<0.50)
{
if(drastic < 1)
{
dna_test[mutated_shape].r += RANDDOUBLE(0.1);
dna_test[mutated_shape].r = CLAMP(dna_test[mutated_shape].r, 0.0, 1.0);
}
else
dna_test[mutated_shape].r = RANDDOUBLE(1.0);
}
else if(roulette<0.75)
{
if(drastic < 1)
{
dna_test[mutated_shape].g += RANDDOUBLE(0.1);
dna_test[mutated_shape].g = CLAMP(dna_test[mutated_shape].g, 0.0, 1.0);
}
else
dna_test[mutated_shape].g = RANDDOUBLE(1.0);
}
else
{
if(drastic < 1)
{
dna_test[mutated_shape].b += RANDDOUBLE(0.1);
dna_test[mutated_shape].b = CLAMP(dna_test[mutated_shape].b, 0.0, 1.0);
}
else
dna_test[mutated_shape].b = RANDDOUBLE(1.0);
}
}
// mutate shape
else if(roulette < 2.0)
{
int point_i = RANDINT(NUM_POINTS);
if(roulette<1.5)
{
if(drastic < 1)
{
dna_test[mutated_shape].points[point_i].x += (int)RANDDOUBLE(WIDTH/10.0);
dna_test[mutated_shape].points[point_i].x = CLAMP(dna_test[mutated_shape].points[point_i].x, 0, WIDTH-1);
}
else
dna_test[mutated_shape].points[point_i].x = RANDDOUBLE(WIDTH);
}
else
{
if(drastic < 1)
{
dna_test[mutated_shape].points[point_i].y += (int)RANDDOUBLE(HEIGHT/10.0);
dna_test[mutated_shape].points[point_i].y = CLAMP(dna_test[mutated_shape].points[point_i].y, 0, HEIGHT-1);
}
else
dna_test[mutated_shape].points[point_i].y = RANDDOUBLE(HEIGHT);
}
}
// mutate stacking
else
{
int destination = RANDINT(NUM_SHAPES);
shape_t s = dna_test[mutated_shape];
dna_test[mutated_shape] = dna_test[destination];
dna_test[destination] = s;
return destination;
}
return -1;
}"
);
//render mutated DNA to a raster image in opengl texture
boost::compute::function<int (int)> renderDNA =
boost::compute::make_function_from_source<int (int)>(
"renderDNA",
"int renderDNA(int x)
{
//for each shape in dna
{
glEnable(GL_TEXTURE_2D);
glBindTexture(GL_TEXTURE_2D, gl_texture_);
glBegin(GL_QUADS);
glTexCoord2f(0, 0); glVertex2f(0, 0);
glTexCoord2f(0, 1); glVertex2f(0, h);
glTexCoord2f(1, 1); glVertex2f(w, h);
glTexCoord2f(1, 0); glVertex2f(w, 0);
glEnd();
} }"
);
//compute fitness of mutated dna image vs leader dna image
//compute what % match DNAimage is to original image
boost::compute::function<int (int)> computefitnesspercent =
boost::compute::make_function_from_source<int (int)>(
"computefitnesspercent",
"int computefitnesspercent(int x) { //read leader dna
//compare input dna to leader dna to find changed polygons
compareDNA(leaderDNA,DNA);
//create bounding box containing changed polygons
//render leader dna within bounding box
leaderrender = renderDNA(leaderDNA,boundx,boundy);
//render input dna within bounding box
inputrender = renderDNA(DNA,boundx,boundy);
//compare leader and input dna rendered bounding boxes
compareimage(leaderrender,inputrender);
//returns % match }"
);
//check if it is fitter, if so overwrite leaderDNA
while (fitness(mutatedDNA,originalimage) < leaderfitness))
{
//overwrite leaderDNA
leaderDNA = mutatedDNA;
//save dna to disk
// start by writing a temp file.
pFile = fopen ("volution.dna.temp","w");
fprintf (pFile, DNA);
fclose (pFile);
// Then rename the real backup to a secondary backup.
result = rename("volution.dna","volution_2.dna");
// Then rename the temp file to the primary backup
result = rename("volution.dna.temp","volution.dna");
// Then delete the temp file
result = remove("volution.dna.temp");
}
}
//perform final render, output svg and raster image
//render DNA and save resulting image to disk as .svg file and raster image (.png)
//render image from DNA
renderDNA(DNA);
//save resultant image to disk as svg and png files
//render input DNA to an svg file
boost::compute::function<int (int)> renderSVG =
boost::compute::make_function_from_source<int (int)>(
"renderSVG",
"int renderSVG(int x) {
//for each shape in dna
{
//add shape to svg file
}
}"
);
}<commit_msg>tidying<commit_after>#include <iostream>
#include <string>
#include <vector>
#include <stdexcept>
#include <boost/compute.hpp>
#include <algorithm>
#include <QtGui>
#include <QtOpenGL>
#include <boost/compute/command_queue.hpp>
#include <boost/compute/kernel.hpp>
#include <boost/compute/program.hpp>
#include <boost/compute/source.hpp>
#include <boost/compute/system.hpp>
#include <boost/compute/interop/opengl.hpp>
using namespace std;
namespace compute = boost::compute;
int main (int argc, char* argv[])
{
// get the default compute device
compute::device gpu = compute::system::default_device();
// create a compute context and command queue
compute::context ctx(gpu);
compute::command_queue queue(ctx, gpu);
//set some default values for when no commandline arguments are given
//create accuracy variable
int accuracy = 90;
// create vector on device
compute::vector<int> device_accuracy(1);
// copy from host to device
compute::copy(host_data,
accuracy,
device_accuracy.begin());
//create polygons variable
int polygons = 50;
// create vector on device
compute::vector<int> device_polygons(1);
// copy from host to device
compute::copy(host_data,
host_data + 5,
device_vector.begin());
//create vertices variable
int vertices = 6;
// create vector on device
compute::vector<int> device_vector(5);
// copy from host to device
compute::copy(host_data,
host_data + 5,
device_vector.begin());
//read input commandline arguments
for (int i = 1; i < argc; ++i)
{
if (std::string(argv[i]) == "-a")
{
//initialise desired accuracy variable according to commandline argument -a
accuracy = ;
}
if (std::string(argv[i]) == "-p")
{
//initialise maximum polygons variable according to commandline argument -p
polygons = ;
}
if (std::string(argv[i]) == "-v")
{
//initialise maximum verices per polygon variable according to commandline argument -v
vertices = ;
}
}
//create leaderDNA variable
// create data array on host
int host_data[] = { 1, 3, 5, 7, 9 };
// create vector on device
compute::vector<int> device_vector(5);
// copy from host to device
compute::copy(host_data,
host_data + 5,
device_vector.begin());
//create mutatedDNA variable
// create data array on host
int host_data[] = { 1, 3, 5, 7, 9 };
// create vector on device
compute::vector<int> device_vector(5);
// copy from host to device
compute::copy(host_data,
host_data + 5,
device_vector.begin());
//create leaderDNArender variable
// create data array on host
int host_data[] = { 1, 3, 5, 7, 9 };
// create vector on device
compute::vector<int> device_vector(5);
// copy from host to device
compute::copy(host_data,
host_data + 5,
device_vector.begin());
//create mutatedDNArender variable
// create data array on host
int host_data[] = { 1, 3, 5, 7, 9 };
// create vector on device
compute::vector<int> device_vector(5);
// copy from host to device
compute::copy(host_data,
host_data + 5,
device_vector.begin());
//create original image variable + load image into gpu memory
if (std::string(argv[i]) == "")
{
//load file according to commandline argument into gpu vector
//get x(max), y(max). (image dimensions)
//make image vector on device
compute::vector<float> originalimage(ctx, n);
// copy data to the device
compute::copy(
host_vector.begin(),
host_vector.end(),
device_vector.begin(),
queue
);
}
//initialise DNA with a random seed
//create random leader dna
// generate random dna vector on the host
std::vector<float> host_vector(1000000);
std::generate(host_vector.begin(), host_vector.end(), rand);
// create vector on the device
compute::vector<float> device_vector(1000000, ctx);
// copy data to the device
compute::copy(
host_vector.begin(),
host_vector.end(),
device_vector.begin(),
queue
);
//run render loop until desired accuracy is reached
while (leaderaccuracy<accuracy)
{
//render leader DNA to a raster image in opengl texture
boost::compute::function<int (int)> renderDNA =
boost::compute::make_function_from_source<int (int)>(
"renderDNA",
"int renderDNA(int x)
{ //for each shape in dna
{
glEnable(GL_TEXTURE_2D);
glBindTexture(GL_TEXTURE_2D, gl_texture_);
glBegin(GL_QUADS);
glTexCoord2f(0, 0); glVertex2f(0, 0);
glTexCoord2f(0, 1); glVertex2f(0, h);
glTexCoord2f(1, 1); glVertex2f(w, h);
glTexCoord2f(1, 0); glVertex2f(w, 0);
glEnd();
} }"
);
//compute fitness of leader dna image
//compute what % match DNAimage is to original image
boost::compute::function<int (int)> computefitnesspercent =
boost::compute::make_function_from_source<int (int)>(
"computefitnesspercent",
"int computefitnesspercent(int x) { //read leader dna
//compare input dna to leader dna to find changed polygons
compareDNA(leaderDNA,DNA);
//create bounding box containing changed polygons
//render leader dna within bounding box
leaderrender = renderDNA(leaderDNA,boundx,boundy);
//render input dna within bounding box
inputrender = renderDNA(DNA,boundx,boundy);
//compare leader and input dna rendered bounding boxes
compareimage(leaderrender,inputrender);
//returns % match }"
);
while ()
{
//mutate from the leaderDNA
boost::compute::function<int (int)> mutateDNA =
boost::compute::make_function_from_source<int (int)>(
"mutateDNA",
"int mutateDNA(int DNA)
{
//mutate input DNA randomly
mutated_shape = RANDINT(NUM_SHAPES);
double roulette = RANDDOUBLE(3);
// mutate color
//randomly change mutated_shape colour
// mutate shape
//randomly move one vertex in mutated_shape
// mutate stacking
//randomly move one shape up or down stack in mutated_shape
);
//render mutated DNA to a raster image in opengl texture
boost::compute::function<int (int)> renderDNA =
boost::compute::make_function_from_source<int (int)>(
"renderDNA",
"int renderDNA(int x)
{
//for each shape in dna
{
glEnable(GL_TEXTURE_2D);
glBindTexture(GL_TEXTURE_2D, gl_texture_);
glBegin(GL_QUADS);
glTexCoord2f(0, 0); glVertex2f(0, 0);
glTexCoord2f(0, 1); glVertex2f(0, h);
glTexCoord2f(1, 1); glVertex2f(w, h);
glTexCoord2f(1, 0); glVertex2f(w, 0);
glEnd();
} }"
);
//compute fitness of mutated dna image vs leader dna image
//compute what % match DNAimage is to original image
boost::compute::function<int (int)> computefitnesspercent =
boost::compute::make_function_from_source<int (int)>(
"computefitnesspercent",
"int computefitnesspercent(int x) { //read leader dna
//compare input dna to leader dna to find changed polygons
compareDNA(leaderDNA,DNA);
//create bounding box containing changed polygons
//render leader dna within bounding box
leaderrender = renderDNA(leaderDNA,boundx,boundy);
//render input dna within bounding box
inputrender = renderDNA(DNA,boundx,boundy);
//compare leader and input dna rendered bounding boxes
compareimage(leaderrender,inputrender);
//returns % match }"
);
//check if it is fitter, if so overwrite leaderDNA
while (fitness(mutatedDNA,originalimage) < leaderfitness))
{
//overwrite leaderDNA
leaderDNA = mutatedDNA;
//save dna to disk
pFile = fopen ("volution.dna","w");
fprintf (pFile, DNA);
fclose (pFile);
}
}
//perform final render, output svg and raster image
//render DNA and save resulting image to disk as .svg file and raster image (.png)
//render image from DNA
renderDNA(DNA);
//save resultant image to disk as svg and png files
//render input DNA to an svg file
boost::compute::function<int (int)> renderSVG =
boost::compute::make_function_from_source<int (int)>(
"renderSVG",
"int renderSVG(int x) {
//for each shape in dna
{
//add shape to svg file
}
}"
);
}<|endoftext|>
|
<commit_before>//
// Copyright (c) 2010 Advanced Micro Devices, Inc. All rights reserved.
//
#ifndef VERSIONS_HPP_
#define VERSIONS_HPP_
#include "utils/macros.hpp"
#ifndef AMD_PLATFORM_NAME
# define AMD_PLATFORM_NAME "AMD Accelerated Parallel Processing"
#endif // AMD_PLATFORM_NAME
#ifndef AMD_PLATFORM_BUILD_NUMBER
# define AMD_PLATFORM_BUILD_NUMBER 2117
#endif // AMD_PLATFORM_BUILD_NUMBER
#ifndef AMD_PLATFORM_REVISION_NUMBER
# define AMD_PLATFORM_REVISION_NUMBER 0
#endif // AMD_PLATFORM_REVISION_NUMBER
#ifndef AMD_PLATFORM_RELEASE_INFO
# define AMD_PLATFORM_RELEASE_INFO
#endif // AMD_PLATFORM_RELEASE_INFO
#define AMD_BUILD_STRING XSTR(AMD_PLATFORM_BUILD_NUMBER) \
"." XSTR(AMD_PLATFORM_REVISION_NUMBER)
#ifndef AMD_PLATFORM_INFO
# define AMD_PLATFORM_INFO "AMD-APP" AMD_PLATFORM_RELEASE_INFO \
DEBUG_ONLY("." IF(IS_OPTIMIZED,"opt","dbg")) " (" AMD_BUILD_STRING ")"
#endif // ATI_PLATFORM_INFO
#endif // VERSIONS_HPP_
<commit_msg>P4 to Git Change 1270301 by johtaylo@johtaylo-JTBUILDER03-increment on 2016/05/18 03:00:10<commit_after>//
// Copyright (c) 2010 Advanced Micro Devices, Inc. All rights reserved.
//
#ifndef VERSIONS_HPP_
#define VERSIONS_HPP_
#include "utils/macros.hpp"
#ifndef AMD_PLATFORM_NAME
# define AMD_PLATFORM_NAME "AMD Accelerated Parallel Processing"
#endif // AMD_PLATFORM_NAME
#ifndef AMD_PLATFORM_BUILD_NUMBER
# define AMD_PLATFORM_BUILD_NUMBER 2118
#endif // AMD_PLATFORM_BUILD_NUMBER
#ifndef AMD_PLATFORM_REVISION_NUMBER
# define AMD_PLATFORM_REVISION_NUMBER 0
#endif // AMD_PLATFORM_REVISION_NUMBER
#ifndef AMD_PLATFORM_RELEASE_INFO
# define AMD_PLATFORM_RELEASE_INFO
#endif // AMD_PLATFORM_RELEASE_INFO
#define AMD_BUILD_STRING XSTR(AMD_PLATFORM_BUILD_NUMBER) \
"." XSTR(AMD_PLATFORM_REVISION_NUMBER)
#ifndef AMD_PLATFORM_INFO
# define AMD_PLATFORM_INFO "AMD-APP" AMD_PLATFORM_RELEASE_INFO \
DEBUG_ONLY("." IF(IS_OPTIMIZED,"opt","dbg")) " (" AMD_BUILD_STRING ")"
#endif // ATI_PLATFORM_INFO
#endif // VERSIONS_HPP_
<|endoftext|>
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.