text
stringlengths
54
60.6k
<commit_before>// This file is part of the uSTL library, an STL implementation. // // Copyright (c) 2005 by Mike Sharov <[email protected]> // This file is free software, distributed under the MIT License. #include "ofstream.h" #include "ustring.h" #include "uexception.h" #include <unistd.h> #include <errno.h> #include <stdio.h> #include <stdarg.h> namespace ustl { //---------------------------------------------------------------------- ifstream cin (STDIN_FILENO); ofstream cout (STDOUT_FILENO); ofstream cerr (STDERR_FILENO); //---------------------------------------------------------------------- /// Default constructor. ofstream::ofstream (void) : ostringstream() ,_file() { reserve (255); } /// Constructs a stream for writing to \p ofd ofstream::ofstream (int ofd) : ostringstream() ,_file (ofd) { clear (_file.rdstate()); reserve (255); } /// Constructs a stream for writing to \p filename. ofstream::ofstream (const char* filename, openmode mode) : ostringstream() ,_file (filename, mode) { clear (_file.rdstate()); } /// Default destructor. ofstream::~ofstream (void) noexcept { try { flush(); } catch (...) {} if (_file.fd() <= STDERR_FILENO) // Do not close cin,cout,cerr _file.detach(); } /// Flushes the buffer and closes the file. void ofstream::close (void) { clear (_file.rdstate()); flush(); _file.close(); } /// Flushes the buffer to the file. ostream& ofstream::flush (void) { clear(); while (good() && pos() && overflow (remaining())) {} clear (_file.rdstate()); return *this; } /// Seeks to \p p based on \p d. ofstream& ofstream::seekp (off_t p, seekdir d) { flush(); _file.seekp (p, d); clear (_file.rdstate()); return *this; } /// Called when more buffer space (\p n bytes) is needed. ofstream::size_type ofstream::overflow (size_type n) { if (eof() || (n > remaining() && n < capacity() - pos())) return ostringstream::overflow (n); size_type bw = _file.write (cdata(), pos()); clear (_file.rdstate()); erase (begin(), bw); if (remaining() < n) ostringstream::overflow (n); return remaining(); } //---------------------------------------------------------------------- /// Constructs a stream to read from \p ifd. ifstream::ifstream (int ifd) : istringstream () ,_buffer (255,'\0') ,_file (ifd) { link (_buffer.data(), streamsize(0)); } /// Constructs a stream to read from \p filename. ifstream::ifstream (const char* filename, openmode mode) : istringstream () ,_buffer (255,'\0') ,_file (filename, mode) { clear (_file.rdstate()); link (_buffer.data(), streamsize(0)); } /// Reads at least \p n more bytes and returns available bytes. ifstream::size_type ifstream::underflow (size_type n) { if (eof()) return istringstream::underflow (n); const ssize_t freeSpace = _buffer.size() - pos(); const ssize_t neededFreeSpace = max (n, _buffer.size() / 2); const size_t oughtToErase = Align (max (0, neededFreeSpace - freeSpace)); const size_type nToErase = min (pos(), oughtToErase); _buffer.memlink::erase (_buffer.begin(), nToErase); const uoff_t oldPos (pos() - nToErase); size_type br = oldPos; if (_buffer.size() - br < n) { _buffer.resize (br + neededFreeSpace); link (_buffer.data(), streamsize(0)); } cout.flush(); size_type brn = 1; for (; br < oldPos + n && brn && _file.good(); br += brn) brn = _file.readsome (_buffer.begin() + br, _buffer.size() - br); clear (_file.rdstate()); _buffer[br] = 0; link (_buffer.data(), br); seek (oldPos); return remaining(); } /// Flushes the input. int ifstream::sync (void) { istringstream::sync(); underflow (0U); clear (_file.rdstate()); return -good(); } /// Seeks to \p p based on \p d. ifstream& ifstream::seekg (off_t p, seekdir d) { _buffer.clear(); link (_buffer); _file.seekg (p, d); clear (_file.rdstate()); return *this; } //---------------------------------------------------------------------- } // namespace ustl <commit_msg>Add missing ifstream default ctor<commit_after>// This file is part of the uSTL library, an STL implementation. // // Copyright (c) 2005 by Mike Sharov <[email protected]> // This file is free software, distributed under the MIT License. #include "ofstream.h" #include "ustring.h" #include "uexception.h" #include <unistd.h> #include <errno.h> #include <stdio.h> #include <stdarg.h> namespace ustl { //---------------------------------------------------------------------- ifstream cin (STDIN_FILENO); ofstream cout (STDOUT_FILENO); ofstream cerr (STDERR_FILENO); //---------------------------------------------------------------------- /// Default constructor. ofstream::ofstream (void) : ostringstream() ,_file() { reserve (255); } /// Constructs a stream for writing to \p ofd ofstream::ofstream (int ofd) : ostringstream() ,_file (ofd) { clear (_file.rdstate()); reserve (255); } /// Constructs a stream for writing to \p filename. ofstream::ofstream (const char* filename, openmode mode) : ostringstream() ,_file (filename, mode) { clear (_file.rdstate()); } /// Default destructor. ofstream::~ofstream (void) noexcept { try { flush(); } catch (...) {} if (_file.fd() <= STDERR_FILENO) // Do not close cin,cout,cerr _file.detach(); } /// Flushes the buffer and closes the file. void ofstream::close (void) { clear (_file.rdstate()); flush(); _file.close(); } /// Flushes the buffer to the file. ostream& ofstream::flush (void) { clear(); while (good() && pos() && overflow (remaining())) {} clear (_file.rdstate()); return *this; } /// Seeks to \p p based on \p d. ofstream& ofstream::seekp (off_t p, seekdir d) { flush(); _file.seekp (p, d); clear (_file.rdstate()); return *this; } /// Called when more buffer space (\p n bytes) is needed. ofstream::size_type ofstream::overflow (size_type n) { if (eof() || (n > remaining() && n < capacity() - pos())) return ostringstream::overflow (n); size_type bw = _file.write (cdata(), pos()); clear (_file.rdstate()); erase (begin(), bw); if (remaining() < n) ostringstream::overflow (n); return remaining(); } //---------------------------------------------------------------------- /// Constructs an unattached stream ifstream::ifstream (void) : istringstream() ,_buffer (255,'\0') ,_file() { link (_buffer.data(), streamsize(0)); } /// Constructs a stream to read from \p ifd. ifstream::ifstream (int ifd) : istringstream() ,_buffer (255,'\0') ,_file (ifd) { link (_buffer.data(), streamsize(0)); } /// Constructs a stream to read from \p filename. ifstream::ifstream (const char* filename, openmode mode) : istringstream() ,_buffer (255,'\0') ,_file (filename, mode) { clear (_file.rdstate()); link (_buffer.data(), streamsize(0)); } /// Reads at least \p n more bytes and returns available bytes. ifstream::size_type ifstream::underflow (size_type n) { if (eof()) return istringstream::underflow (n); const ssize_t freeSpace = _buffer.size() - pos(); const ssize_t neededFreeSpace = max (n, _buffer.size() / 2); const size_t oughtToErase = Align (max (0, neededFreeSpace - freeSpace)); const size_type nToErase = min (pos(), oughtToErase); _buffer.memlink::erase (_buffer.begin(), nToErase); const uoff_t oldPos (pos() - nToErase); size_type br = oldPos; if (_buffer.size() - br < n) { _buffer.resize (br + neededFreeSpace); link (_buffer.data(), streamsize(0)); } cout.flush(); size_type brn = 1; for (; br < oldPos + n && brn && _file.good(); br += brn) brn = _file.readsome (_buffer.begin() + br, _buffer.size() - br); clear (_file.rdstate()); _buffer[br] = 0; link (_buffer.data(), br); seek (oldPos); return remaining(); } /// Flushes the input. int ifstream::sync (void) { istringstream::sync(); underflow (0U); clear (_file.rdstate()); return -good(); } /// Seeks to \p p based on \p d. ifstream& ifstream::seekg (off_t p, seekdir d) { _buffer.clear(); link (_buffer); _file.seekg (p, d); clear (_file.rdstate()); return *this; } //---------------------------------------------------------------------- } // namespace ustl <|endoftext|>
<commit_before>#define BOOST_FILESYSTEM_VERSION 3 #define USE_FILESYSTEM_THREE #include <boost/filesystem.hpp> #include <fstream> #include "path.h" #include "kazbase/exceptions.h" #include "kazbase/string.h" namespace os { namespace path { std::string join(const std::string& p1, const std::string& p2) { return p1 + OS_SEP + p2; } std::string abs_path(const std::string& p) { #ifdef USE_FILESYSTEM_THREE return boost::filesystem3::complete(p).normalize().string(); #else return boost::filesystem::complete(p).normalize().string(); #endif } std::pair<std::string, std::string> split(const std::string& path) { boost::filesystem::path p(path); #ifdef USE_FILESYSTEM_THREE return std::make_pair(p.parent_path().string(), p.filename().string()); #else return std::make_pair(p.branch_path().string(), p.leaf()); #endif } bool exists(const std::string& path) { return boost::filesystem::exists(path); } std::string dir_name(const std::string& path) { return boost::filesystem::path(path).branch_path().string(); } bool is_absolute(const std::string& path) { return boost::filesystem::path(path).is_complete(); } bool is_dir(const std::string& path) { return boost::filesystem::is_directory(path); } bool is_file(const std::string& path) { return boost::filesystem::is_regular_file(path); } bool is_link(const std::string& path) { return boost::filesystem::is_symlink(path); } std::pair<std::string, std::string> split_ext(const std::string& path) { boost::filesystem::path bp(path); std::string name = bp.stem().string(); std::string ext = bp.extension().string(); return std::make_pair(name, ext); } std::string rel_path(const std::string& path, const std::string& start) { assert(0); } static std::string get_env_var(const std::string& name) { char* env = getenv(name.c_str()); if(env) { return std::string(env); } return std::string(); } std::string expand_user(const std::string& path) { std::string cp = path; if(!str::starts_with(path, "~")) { return path; } std::string home = get_env_var("HOME"); if(home.empty()) { return path; } return str::replace(cp, "~", home); } void hide_dir(const std::string& path) { #ifdef WIN32 assert(0 && "Not Implemented"); #else //On Unix systems, prefix with a dot std::pair<std::string, std::string> parts = os::path::split(path); std::string final = parts.first + "." + parts.second; boost::filesystem::rename(path, final); #endif } std::vector<std::string> list_dir(const std::string& path) { std::vector<std::string> results; boost::filesystem::directory_iterator end; for(boost::filesystem::directory_iterator it(path); it != end; ++it) { #ifdef USE_FILESYSTEM_THREE results.push_back((*it).path().filename().string()); #else results.push_back((*it).path().filename()); #endif } return results; } std::string read_file_contents(const std::string& path) { std::ifstream t(path); std::string str((std::istreambuf_iterator<char>(t)), std::istreambuf_iterator<char>()); return str; } std::string exe_path() { #ifdef WIN32 assert(0 && "Not implemented"); #else char buff[1024]; ssize_t len = ::readlink("/proc/self/exe", buff, sizeof(buff)-1); if (len != -1) { buff[len] = '\0'; return os::path::dir_name(std::string(buff)); } else { throw RuntimeError("Unable to work out the program path"); } #endif } std::string working_directory() { char buff[PATH_MAX]; getcwd(buff, PATH_MAX); std::string cwd(buff); return cwd; } } } <commit_msg>Temporary hack around the boost::filesystem versioning nonsense<commit_after>#define BOOST_FILESYSTEM_VERSION 3 #define USE_FILESYSTEM_THREE #include <boost/filesystem.hpp> #include <fstream> #include "path.h" #include "kazbase/exceptions.h" #include "kazbase/string.h" namespace os { namespace path { std::string join(const std::string& p1, const std::string& p2) { return p1 + OS_SEP + p2; } std::string abs_path(const std::string& p) { return boost::filesystem::complete(p).normalize().string(); } std::pair<std::string, std::string> split(const std::string& path) { boost::filesystem::path p(path); #ifdef USE_FILESYSTEM_THREE return std::make_pair(p.parent_path().string(), p.filename().string()); #else return std::make_pair(p.branch_path().string(), p.leaf()); #endif } bool exists(const std::string& path) { return boost::filesystem::exists(path); } std::string dir_name(const std::string& path) { return boost::filesystem::path(path).branch_path().string(); } bool is_absolute(const std::string& path) { return boost::filesystem::path(path).is_complete(); } bool is_dir(const std::string& path) { return boost::filesystem::is_directory(path); } bool is_file(const std::string& path) { return boost::filesystem::is_regular_file(path); } bool is_link(const std::string& path) { return boost::filesystem::is_symlink(path); } std::pair<std::string, std::string> split_ext(const std::string& path) { boost::filesystem::path bp(path); std::string name = bp.stem().string(); std::string ext = bp.extension().string(); return std::make_pair(name, ext); } std::string rel_path(const std::string& path, const std::string& start) { assert(0); } static std::string get_env_var(const std::string& name) { char* env = getenv(name.c_str()); if(env) { return std::string(env); } return std::string(); } std::string expand_user(const std::string& path) { std::string cp = path; if(!str::starts_with(path, "~")) { return path; } std::string home = get_env_var("HOME"); if(home.empty()) { return path; } return str::replace(cp, "~", home); } void hide_dir(const std::string& path) { #ifdef WIN32 assert(0 && "Not Implemented"); #else //On Unix systems, prefix with a dot std::pair<std::string, std::string> parts = os::path::split(path); std::string final = parts.first + "." + parts.second; boost::filesystem::rename(path, final); #endif } std::vector<std::string> list_dir(const std::string& path) { std::vector<std::string> results; boost::filesystem::directory_iterator end; for(boost::filesystem::directory_iterator it(path); it != end; ++it) { #ifdef USE_FILESYSTEM_THREE results.push_back((*it).path().filename().string()); #else results.push_back((*it).path().filename()); #endif } return results; } std::string read_file_contents(const std::string& path) { std::ifstream t(path); std::string str((std::istreambuf_iterator<char>(t)), std::istreambuf_iterator<char>()); return str; } std::string exe_path() { #ifdef WIN32 assert(0 && "Not implemented"); #else char buff[1024]; ssize_t len = ::readlink("/proc/self/exe", buff, sizeof(buff)-1); if (len != -1) { buff[len] = '\0'; return os::path::dir_name(std::string(buff)); } else { throw RuntimeError("Unable to work out the program path"); } #endif } std::string working_directory() { char buff[PATH_MAX]; getcwd(buff, PATH_MAX); std::string cwd(buff); return cwd; } } } <|endoftext|>
<commit_before>// This code is based on Sabberstone project. // Copyright (c) 2017-2019 SabberStone Team, darkfriend77 & rnilva // RosettaStone is hearthstone simulator using C++ with reinforcement learning. // Copyright (c) 2019 Chris Ohk, Youngjoong Kim, SeungHyun Jeon #ifndef ROSETTASTONE_EFFECTS_HPP #define ROSETTASTONE_EFFECTS_HPP #include <Rosetta/Enchants/Effect.hpp> namespace RosettaStone { //! //! \brief Effects class. //! //! This class lists specific effects such as Taunt, Poisonous and Stealth. //! class Effects { public: //! Creates effect that increases attack by \p n. static Effect* AttackN(int n) { return new Effect(GameTag::ATK, EffectOperator::ADD, n); } //! Creates effect that increases health by \p n. static Effect* HealthN(int n) { return new Effect(GameTag::HEALTH, EffectOperator::ADD, n); } //! Creates effect that increases attack and health by \p n. static std::vector<Effect*> AttackHealthN(int n) { return { AttackN(n), HealthN(n) }; } //! Creates effect that reduces cost by \p n. static Effect* ReduceCost(int n) { return new Effect(GameTag::COST, EffectOperator::SUB, n); } //! A minion ability which forces the opposing player to direct any //! melee attacks toward enemy targets with this ability. inline static Effect* Taunt = new Effect(GameTag::TAUNT, EffectOperator::SET, 1); //! A minion ability that causes any minion damaged by them to be destroyed. inline static Effect* Poisonous = new Effect(GameTag::POISONOUS, EffectOperator::SET, 1); //! An ability which causes a minion to ignore the next damage it receives. inline static Effect* DivineShield = new Effect(GameTag::DIVINE_SHIELD, EffectOperator::SET, 1); //! An ability which allows a character to attack twice per turn. inline static Effect* Windfury = new Effect(GameTag::WINDFURY, EffectOperator::SET, 1); //! An ability allowing a minion to attack the same turn it is summoned or //! brought under a new player's control. inline static Effect* Charge = new Effect(GameTag::CHARGE, EffectOperator::SET, 1); //! A minion ability which prevents that minion from being the target of //! enemy attacks, spells and effects until they attack. inline static Effect* Stealth = new Effect(GameTag::STEALTH, EffectOperator::SET, 1); //! An ability that prevents characters from receiving any damage, and //! prevents the opponent from specifically targeting them with any type of //! action. inline static Effect* Immune = new Effect(GameTag::IMMUNE, EffectOperator::SET, 1); }; } // namespace RosettaStone #endif // ROSETTASTONE_EFFECTS_HPP <commit_msg>feat(card-impl): Add SetAttack(), SetMaxhealth() and SetAttackHealth()<commit_after>// This code is based on Sabberstone project. // Copyright (c) 2017-2019 SabberStone Team, darkfriend77 & rnilva // RosettaStone is hearthstone simulator using C++ with reinforcement learning. // Copyright (c) 2019 Chris Ohk, Youngjoong Kim, SeungHyun Jeon #ifndef ROSETTASTONE_EFFECTS_HPP #define ROSETTASTONE_EFFECTS_HPP #include <Rosetta/Enchants/Effect.hpp> namespace RosettaStone { //! //! \brief Effects class. //! //! This class lists specific effects such as Taunt, Poisonous and Stealth. //! class Effects { public: //! Creates effect that increases attack by \p n. static Effect* AttackN(int n) { return new Effect(GameTag::ATK, EffectOperator::ADD, n); } //! Creates effect that increases health by \p n. static Effect* HealthN(int n) { return new Effect(GameTag::HEALTH, EffectOperator::ADD, n); } //! Creates effect that increases attack and health by \p n. static std::vector<Effect*> AttackHealthN(int n) { return { AttackN(n), HealthN(n) }; } //! Creates effect that sets attack to \p n. static Effect* SetAttack(int n) { return new Effect(GameTag::ATK, EffectOperator::SET, n); } //! Creates effect that sets max health to \p n. static Effect* SetMaxHealth(int n) { return new Effect(GameTag::HEALTH, EffectOperator::SET, n); } //! Creates effect that sets attack and health to \p n. static std::vector<Effect*> SetAttackHealth(int n) { return { SetAttack(n), SetMaxHealth(n) }; } //! Creates effect that reduces cost by \p n. static Effect* ReduceCost(int n) { return new Effect(GameTag::COST, EffectOperator::SUB, n); } //! A minion ability which forces the opposing player to direct any //! melee attacks toward enemy targets with this ability. inline static Effect* Taunt = new Effect(GameTag::TAUNT, EffectOperator::SET, 1); //! A minion ability that causes any minion damaged by them to be destroyed. inline static Effect* Poisonous = new Effect(GameTag::POISONOUS, EffectOperator::SET, 1); //! An ability which causes a minion to ignore the next damage it receives. inline static Effect* DivineShield = new Effect(GameTag::DIVINE_SHIELD, EffectOperator::SET, 1); //! An ability which allows a character to attack twice per turn. inline static Effect* Windfury = new Effect(GameTag::WINDFURY, EffectOperator::SET, 1); //! An ability allowing a minion to attack the same turn it is summoned or //! brought under a new player's control. inline static Effect* Charge = new Effect(GameTag::CHARGE, EffectOperator::SET, 1); //! A minion ability which prevents that minion from being the target of //! enemy attacks, spells and effects until they attack. inline static Effect* Stealth = new Effect(GameTag::STEALTH, EffectOperator::SET, 1); //! An ability that prevents characters from receiving any damage, and //! prevents the opponent from specifically targeting them with any type of //! action. inline static Effect* Immune = new Effect(GameTag::IMMUNE, EffectOperator::SET, 1); }; } // namespace RosettaStone #endif // ROSETTASTONE_EFFECTS_HPP <|endoftext|>
<commit_before>// Time: ctor: O(m * n), // update: O(logm + logn), // query: O(logm + logn) // Space: O(m * n) // Segment Tree solution. class NumMatrix { public: NumMatrix(vector<vector<int>> &matrix) : matrix_(matrix) { if (!matrix.empty() && !matrix[0].empty()) { const int m = matrix.size(); const int n = matrix[0].size(); root_ = buildHelper(matrix, make_pair(0, 0), make_pair(m - 1, n - 1)); } } void update(int row, int col, int val) { if (matrix_[row][col] != val) { matrix_[row][col] = val; updateHelper(root_, make_pair(row, col), val); } } int sumRegion(int row1, int col1, int row2, int col2) { return sumRangeHelper(root_, make_pair(row1, col1), make_pair(row2, col2)); } private: vector<vector<int>>& matrix_; class SegmentTreeNode { public: pair<int, int> start, end; int sum; vector<SegmentTreeNode *> neighbor; SegmentTreeNode(const pair<int, int>& i, const pair<int, int>& j, int s) : start(i), end(j), sum(s) { } }; SegmentTreeNode *root_; // Build segment tree. SegmentTreeNode *buildHelper(const vector<vector<int>>& matrix, const pair<int, int>& start, const pair<int, int>& end) { if (start.first > end.first || start.second > end.second) { return nullptr; } // The root's start and end is given by build method. SegmentTreeNode *root = new SegmentTreeNode(start, end, 0); // If start equals to end, there will be no children for this node. if (start == end) { root->sum = matrix[start.first][start.second]; return root; } int mid_x = (start.first + end.first) / 2; int mid_y = (start.second + end.second) / 2; root->neighbor.emplace_back(buildHelper(matrix, start, make_pair(mid_x, mid_y))); root->neighbor.emplace_back(buildHelper(matrix, make_pair(start.first, mid_y + 1), make_pair(mid_x, end.second))); root->neighbor.emplace_back(buildHelper(matrix, make_pair(mid_x + 1, start.second), make_pair(end.first, mid_y))); root->neighbor.emplace_back(buildHelper(matrix, make_pair(mid_x + 1, mid_y + 1), end)); for (auto& node : root->neighbor) { if (node) { root->sum += node->sum; } } return root; } void updateHelper(SegmentTreeNode *root, const pair<int, int>& i, int val) { // Out of range. if (root == nullptr || (root->start.first > i.first || root->start.second > i.second) || (root->end.first < i.first || root->end.second < i.second)) { return; } // Change the node's value with [i] to the new given value. if ((root->start.first == i.first && root->start.second == i.second) && (root->end.first == i.first && root->end.second == i.second)) { root->sum = val; return; } for (auto& node : root->neighbor) { updateHelper(node, i, val); } root->sum = 0; for (auto& node : root->neighbor) { if (node) { root->sum += node->sum; } } } int sumRangeHelper(SegmentTreeNode *root, const pair<int, int>& start, const pair<int, int>& end) { // Out of range. if (root == nullptr || (root->start.first > end.first || root->start.second > end.second) || (root->end.first < start.first || root->end.second < start.second)) { return 0; } // Current segment is totally within range [start, end] if ((root->start.first >= start.first && root->start.second >= start.second) && (root->end.first <= end.first && root->end.second <= end.second)) { return root->sum; } int sum = 0; for (auto& node : root->neighbor) { if (node) { sum += sumRangeHelper(node, start, end); } } return sum; } }; // Time: ctor: O(m * n) // update: O(logm * logn) // query: O(logm * logn) // Space: O(m * n) // Binary Indexed Tree (BIT) solution. class NumMatrix2 { public: NumMatrix(vector<vector<int>> &matrix) : matrix_(matrix) { if (matrix_.empty()) { return; } bit_ = vector<vector<int>>(matrix_.size() + 1, vector<int>(matrix_[0].size() + 1)); for (int i = 1; i < bit_.size(); ++i) { for (int j = 1; j < bit_[0].size(); ++j) { bit_[i][j] = matrix[i - 1][j - 1] + bit_[i - 1][j] + bit_[i][j - 1] - bit_[i - 1][j - 1]; } } for (int i = bit_.size() - 1; i >= 1; --i) { for (int j = bit_[0].size() - 1; j >= 1; --j) { int last_i = i - lower_bit(i), last_j = j - lower_bit(j); bit_[i][j] = bit_[i][j] - bit_[i][last_j] - bit_[last_i][j] + bit_[last_i][last_j]; } } } void update(int row, int col, int val) { if (val - matrix_[row][col]) { add(row, col, val - matrix_[row][col]); matrix_[row][col] = val; } } int sumRegion(int row1, int col1, int row2, int col2) { return sum(row2, col2) - sum(row2, col1 - 1) - sum(row1 - 1, col2) + sum(row1 - 1, col1 - 1); } private: vector<vector<int>> &matrix_; vector<vector<int>> bit_; int sum(int row, int col) { ++row, ++col; int sum = 0; for (int i = row; i > 0; i -= lower_bit(i)) { for (int j = col; j > 0; j -= lower_bit(j)) { sum += bit_[i][j]; } } return sum; } void add(int row, int col, int val) { ++row, ++col; for (int i = row; i <= matrix_.size(); i += lower_bit(i)) { for (int j = col; j <= matrix_[0].size(); j += lower_bit(j)) { bit_[i][j] += val; } } } int lower_bit(int i) { return i & -i; } }; // Your NumMatrix object will be instantiated and called as such: // NumMatrix numMatrix(matrix); // numMatrix.sumRegion(0, 1, 2, 3); // numMatrix.update(1, 1, 10); // numMatrix.sumRegion(1, 2, 3, 4); <commit_msg>Update range-sum-query-2d-mutable.cpp<commit_after>// Time: ctor: O(m * n), // update: O(logm + logn), // query: O(logm + logn) // Space: O(m * n) // Segment Tree solution. class NumMatrix { public: NumMatrix(vector<vector<int>> &matrix) : matrix_(matrix) { if (!matrix.empty() && !matrix[0].empty()) { const int m = matrix.size(); const int n = matrix[0].size(); root_ = buildHelper(matrix, make_pair(0, 0), make_pair(m - 1, n - 1)); } } void update(int row, int col, int val) { if (matrix_[row][col] != val) { matrix_[row][col] = val; updateHelper(root_, make_pair(row, col), val); } } int sumRegion(int row1, int col1, int row2, int col2) { return sumRangeHelper(root_, make_pair(row1, col1), make_pair(row2, col2)); } private: vector<vector<int>>& matrix_; class SegmentTreeNode { public: pair<int, int> start, end; int sum; vector<SegmentTreeNode *> neighbor; SegmentTreeNode(const pair<int, int>& i, const pair<int, int>& j, int s) : start(i), end(j), sum(s) { } }; SegmentTreeNode *root_; // Build segment tree. SegmentTreeNode *buildHelper(const vector<vector<int>>& matrix, const pair<int, int>& start, const pair<int, int>& end) { if (start.first > end.first || start.second > end.second) { return nullptr; } // The root's start and end is given by build method. SegmentTreeNode *root = new SegmentTreeNode(start, end, 0); // If start equals to end, there will be no children for this node. if (start == end) { root->sum = matrix[start.first][start.second]; return root; } int mid_x = (start.first + end.first) / 2; int mid_y = (start.second + end.second) / 2; root->neighbor.emplace_back(buildHelper(matrix, start, make_pair(mid_x, mid_y))); root->neighbor.emplace_back(buildHelper(matrix, make_pair(start.first, mid_y + 1), make_pair(mid_x, end.second))); root->neighbor.emplace_back(buildHelper(matrix, make_pair(mid_x + 1, start.second), make_pair(end.first, mid_y))); root->neighbor.emplace_back(buildHelper(matrix, make_pair(mid_x + 1, mid_y + 1), end)); for (auto& node : root->neighbor) { if (node) { root->sum += node->sum; } } return root; } void updateHelper(SegmentTreeNode *root, const pair<int, int>& i, int val) { // Out of range. if (root == nullptr || (root->start.first > i.first || root->start.second > i.second) || (root->end.first < i.first || root->end.second < i.second)) { return; } // Change the node's value with [i] to the new given value. if ((root->start.first == i.first && root->start.second == i.second) && (root->end.first == i.first && root->end.second == i.second)) { root->sum = val; return; } for (auto& node : root->neighbor) { updateHelper(node, i, val); } root->sum = 0; for (auto& node : root->neighbor) { if (node) { root->sum += node->sum; } } } int sumRangeHelper(SegmentTreeNode *root, const pair<int, int>& start, const pair<int, int>& end) { // Out of range. if (root == nullptr || (root->start.first > end.first || root->start.second > end.second) || (root->end.first < start.first || root->end.second < start.second)) { return 0; } // Current segment is totally within range [start, end] if ((root->start.first >= start.first && root->start.second >= start.second) && (root->end.first <= end.first && root->end.second <= end.second)) { return root->sum; } int sum = 0; for (auto& node : root->neighbor) { if (node) { sum += sumRangeHelper(node, start, end); } } return sum; } }; // Time: ctor: O(m * n) // update: O(logm * logn) // query: O(logm * logn) // Space: O(m * n) // Binary Indexed Tree (BIT) solution. class NumMatrix2 { public: NumMatrix(vector<vector<int>> &matrix) : matrix_(matrix) { if (matrix_.empty()) { return; } bit_ = vector<vector<int>>(matrix_.size() + 1, vector<int>(matrix_[0].size() + 1)); for (int i = 1; i < bit_.size(); ++i) { for (int j = 1; j < bit_[0].size(); ++j) { bit_[i][j] = matrix[i - 1][j - 1] + bit_[i - 1][j] + bit_[i][j - 1] - bit_[i - 1][j - 1]; } } for (int i = bit_.size() - 1; i >= 1; --i) { for (int j = bit_[0].size() - 1; j >= 1; --j) { int last_i = i - lower_bit(i), last_j = j - lower_bit(j); bit_[i][j] = bit_[i][j] - bit_[i][last_j] - bit_[last_i][j] + bit_[last_i][last_j]; } } } void update(int row, int col, int val) { if (val - matrix_[row][col]) { add(row, col, val - matrix_[row][col]); matrix_[row][col] = val; } } int sumRegion(int row1, int col1, int row2, int col2) { return sum(row2, col2) - sum(row2, col1 - 1) - sum(row1 - 1, col2) + sum(row1 - 1, col1 - 1); } private: vector<vector<int>> &matrix_; vector<vector<int>> bit_; int sum(int row, int col) { ++row, ++col; int sum = 0; for (int i = row; i > 0; i -= lower_bit(i)) { for (int j = col; j > 0; j -= lower_bit(j)) { sum += bit_[i][j]; } } return sum; } void add(int row, int col, int val) { ++row, ++col; for (int i = row; i <= matrix_.size(); i += lower_bit(i)) { for (int j = col; j <= matrix_[0].size(); j += lower_bit(j)) { bit_[i][j] += val; } } } inline int lower_bit(int i) { return i & -i; } }; // Your NumMatrix object will be instantiated and called as such: // NumMatrix numMatrix(matrix); // numMatrix.sumRegion(0, 1, 2, 3); // numMatrix.update(1, 1, 10); // numMatrix.sumRegion(1, 2, 3, 4); <|endoftext|>
<commit_before>#include "musicdownloadquerywythread.h" #include "musicdownloadqueryyytthread.h" #include "musicsemaphoreloop.h" #include "musiccoreutils.h" #include "musicnumberutils.h" #include "musictime.h" #///QJson import #include "qjson/parser.h" MusicDownLoadQueryWYThread::MusicDownLoadQueryWYThread(QObject *parent) : MusicDownLoadQueryThreadAbstract(parent) { m_queryServer = "WangYi"; } QString MusicDownLoadQueryWYThread::getClassName() { return staticMetaObject.className(); } void MusicDownLoadQueryWYThread::startToSearch(QueryType type, const QString &text) { if(!m_manager) { return; } M_LOGGER_INFO(QString("%1 startToSearch %2").arg(getClassName()).arg(text)); m_searchText = text.trimmed(); m_currentType = type; QUrl musicUrl = MusicUtils::Algorithm::mdII(WY_SONG_SEARCH_URL, false); deleteAll(); QNetworkRequest request; request.setUrl(musicUrl); request.setRawHeader("Content-Type", "application/x-www-form-urlencoded"); request.setRawHeader("Origin", MusicUtils::Algorithm::mdII(WY_BASE_URL, false).toUtf8()); request.setRawHeader("Referer", MusicUtils::Algorithm::mdII(WY_BASE_URL, false).toUtf8()); #ifndef QT_NO_SSL QSslConfiguration sslConfig = request.sslConfiguration(); sslConfig.setPeerVerifyMode(QSslSocket::VerifyNone); request.setSslConfiguration(sslConfig); #endif m_reply = m_manager->post(request, MusicUtils::Algorithm::mdII(WY_SONG_QUERY_URL, false).arg(text).arg(0).toUtf8()); connect(m_reply, SIGNAL(finished()), SLOT(downLoadFinished())); connect(m_reply, SIGNAL(error(QNetworkReply::NetworkError)), SLOT(replyError(QNetworkReply::NetworkError))); } void MusicDownLoadQueryWYThread::startToSingleSearch(const QString &text) { if(!m_manager) { return; } M_LOGGER_INFO(QString("%1 startToSingleSearch %2").arg(getClassName()).arg(text)); QUrl musicUrl = MusicUtils::Algorithm::mdII(WY_SONG_URL, false).arg(text); deleteAll(); QNetworkRequest request; request.setUrl(musicUrl); request.setRawHeader("Content-Type", "application/x-www-form-urlencoded"); request.setRawHeader("Origin", MusicUtils::Algorithm::mdII(WY_BASE_URL, false).toUtf8()); request.setRawHeader("Referer", MusicUtils::Algorithm::mdII(WY_BASE_URL, false).toUtf8()); #ifndef QT_NO_SSL QSslConfiguration sslConfig = request.sslConfiguration(); sslConfig.setPeerVerifyMode(QSslSocket::VerifyNone); request.setSslConfiguration(sslConfig); #endif QNetworkReply *reply = m_manager->get(request); connect(reply, SIGNAL(finished()), SLOT(singleDownLoadFinished())); connect(reply, SIGNAL(error(QNetworkReply::NetworkError)), SLOT(replyError(QNetworkReply::NetworkError))); } void MusicDownLoadQueryWYThread::downLoadFinished() { if(!m_reply || !m_manager) { deleteAll(); return; } M_LOGGER_INFO(QString("%1 downLoadFinished").arg(getClassName())); emit clearAllItems(); ///Clear origin items m_musicSongInfos.clear(); ///Empty the last search to songsInfo if(m_reply->error() == QNetworkReply::NoError) { QJson::Parser parser; bool ok; QVariant data = parser.parse(m_reply->readAll(), &ok); if(ok) { QVariantMap value = data.toMap(); if(value.contains("code") && value["code"].toInt() == 200) { value = value["result"].toMap(); QVariantList datas = value["songs"].toList(); foreach(const QVariant &var, datas) { if(var.isNull()) { continue; } value = var.toMap(); if(m_currentType != MovieQuery) { MusicObject::MusicSongInformation musicInfo; musicInfo.m_songName = value["name"].toString(); musicInfo.m_timeLength = MusicTime::msecTime2LabelJustified(value["duration"].toInt()); musicInfo.m_songId = QString::number(value["id"].toInt()); musicInfo.m_lrcUrl = MusicUtils::Algorithm::mdII(WY_SONG_LRC_URL, false).arg(musicInfo.m_songId); QVariantMap albumObject = value["album"].toMap(); musicInfo.m_smallPicUrl = albumObject["picUrl"].toString(); musicInfo.m_albumId = QString::number(albumObject["id"].toInt()); musicInfo.m_albumName = albumObject["name"].toString(); QVariantList artistsArray = value["artists"].toList(); foreach(const QVariant &artistValue, artistsArray) { if(artistValue.isNull()) { continue; } QVariantMap artistMap = artistValue.toMap(); musicInfo.m_artistId = QString::number(artistMap["id"].toULongLong()); musicInfo.m_singerName = artistMap["name"].toString(); } if(!m_querySimplify) { if(!m_manager || m_stateCode != MusicNetworkAbstract::Init) return; readFromMusicSongAttribute(&musicInfo, value, m_searchQuality, m_queryAllRecords); if(!m_manager || m_stateCode != MusicNetworkAbstract::Init) return; if(musicInfo.m_songAttrs.isEmpty()) { continue; } MusicSearchedItem item; item.m_songName = musicInfo.m_songName; item.m_singerName = musicInfo.m_singerName; item.m_albumName = musicInfo.m_albumName; item.m_time = musicInfo.m_timeLength; item.m_type = mapQueryServerString(); emit createSearchedItems(item); } m_musicSongInfos << musicInfo; } else { int mvid = value["mvid"].toLongLong(); if(mvid == 0) { continue; } if(!m_manager || m_stateCode != MusicNetworkAbstract::Init) return; startMVListQuery(mvid); if(!m_manager || m_stateCode != MusicNetworkAbstract::Init) return; } } } } } ///extra yyt movie if(m_queryExtraMovie && m_currentType == MovieQuery) { MusicSemaphoreLoop loop; MusicDownLoadQueryYYTThread *yyt = new MusicDownLoadQueryYYTThread(this); connect(yyt, SIGNAL(createSearchedItems(MusicSearchedItem)), SIGNAL(createSearchedItems(MusicSearchedItem))); connect(yyt, SIGNAL(downLoadDataChanged(QString)), &loop, SLOT(quit())); yyt->startToSearch(MusicDownLoadQueryYYTThread::MovieQuery, m_searchText); loop.exec(); m_musicSongInfos << yyt->getMusicSongInfos(); } emit downLoadDataChanged(QString()); deleteAll(); M_LOGGER_INFO(QString("%1 downLoadFinished deleteAll").arg(getClassName())); } void MusicDownLoadQueryWYThread::singleDownLoadFinished() { QNetworkReply *reply = MObject_cast(QNetworkReply*, QObject::sender()); M_LOGGER_INFO(QString("%1 singleDownLoadFinished").arg(getClassName())); emit clearAllItems(); ///Clear origin items m_musicSongInfos.clear(); ///Empty the last search to songsInfo if(reply && m_manager &&reply->error() == QNetworkReply::NoError) { QByteArray bytes = reply->readAll();///Get all the data obtained by request QJson::Parser parser; bool ok; QVariant data = parser.parse(bytes, &ok); if(ok) { QVariantMap value = data.toMap(); if(value.contains("songs") && value["code"].toInt() == 200) { QVariantList datas = value["songs"].toList(); foreach(const QVariant &var, datas) { if(var.isNull()) { continue; } value = var.toMap(); MusicObject::MusicSongInformation musicInfo; musicInfo.m_songName = value["name"].toString(); musicInfo.m_timeLength = MusicTime::msecTime2LabelJustified(value["duration"].toInt()); musicInfo.m_songId = QString::number(value["id"].toInt()); musicInfo.m_lrcUrl = MusicUtils::Algorithm::mdII(WY_SONG_LRC_URL, false).arg(musicInfo.m_songId); QVariantMap albumObject = value["album"].toMap(); musicInfo.m_smallPicUrl = albumObject["picUrl"].toString(); musicInfo.m_albumId = QString::number(albumObject["id"].toInt()); musicInfo.m_albumName = albumObject["name"].toString(); QVariantList artistsArray = value["artists"].toList(); foreach(const QVariant &artistValue, artistsArray) { if(artistValue.isNull()) { continue; } QVariantMap artistMap = artistValue.toMap(); musicInfo.m_artistId = QString::number(artistMap["id"].toULongLong()); musicInfo.m_singerName = artistMap["name"].toString(); } if(!m_manager || m_stateCode != MusicNetworkAbstract::Init) return; readFromMusicSongAttribute(&musicInfo, value, m_searchQuality, true); if(!m_manager || m_stateCode != MusicNetworkAbstract::Init) return; if(!musicInfo.m_songAttrs.isEmpty()) { MusicSearchedItem item; item.m_songName = musicInfo.m_songName; item.m_singerName = musicInfo.m_singerName; item.m_albumName = musicInfo.m_albumName; item.m_time = musicInfo.m_timeLength; item.m_type = mapQueryServerString(); emit createSearchedItems(item); m_musicSongInfos << musicInfo; } } } } } emit downLoadDataChanged(QString()); deleteAll(); M_LOGGER_INFO(QString("%1 singleDownLoadFinished deleteAll").arg(getClassName())); } void MusicDownLoadQueryWYThread::startMVListQuery(int id) { QNetworkRequest request; request.setUrl(QUrl(MusicUtils::Algorithm::mdII(WY_SONG_MV_URL, false).arg(id))); request.setRawHeader("Content-Type", "application/x-www-form-urlencoded"); request.setRawHeader("Origin", MusicUtils::Algorithm::mdII(WY_BASE_URL, false).toUtf8()); request.setRawHeader("Referer", MusicUtils::Algorithm::mdII(WY_BASE_URL, false).toUtf8()); #ifndef QT_NO_SSL QSslConfiguration sslConfig = request.sslConfiguration(); sslConfig.setPeerVerifyMode(QSslSocket::VerifyNone); request.setSslConfiguration(sslConfig); #endif MusicSemaphoreLoop loop; QNetworkReply *reply = m_manager->get(request); QObject::connect(reply, SIGNAL(finished()), &loop, SLOT(quit())); QObject::connect(reply, SIGNAL(error(QNetworkReply::NetworkError)), &loop, SLOT(quit())); loop.exec(); if(!reply || reply->error() != QNetworkReply::NoError) { return; } qDebug() << reply->readAll(); QJson::Parser parser; bool ok; QVariant data = parser.parse(reply->readAll(), &ok); if(ok) { QVariantMap value = data.toMap(); if(value.contains("code") && value["code"].toInt() == 200) { value = value["data"].toMap(); MusicObject::MusicSongInformation musicInfo; musicInfo.m_songName = value["name"].toString(); musicInfo.m_singerName = value["artistName"].toString(); musicInfo.m_timeLength = MusicTime::msecTime2LabelJustified(value["duration"].toInt()); value = value["brs"].toMap(); foreach(const QString &key, value.keys()) { int bit = key.toInt(); MusicObject::MusicSongAttribute attr; if(bit <= 625) attr.m_bitrate = MB_500; else if(bit > 625 && bit <= 875) attr.m_bitrate = MB_750; else if(bit > 875) attr.m_bitrate = MB_1000; attr.m_url = value[key].toString(); attr.m_format = MusicUtils::Core::fileSuffix(attr.m_url); if(!m_manager || m_stateCode != MusicNetworkAbstract::Init) return; attr.m_size = MusicUtils::Number::size2Label(getUrlFileSize(attr.m_url)); if(!m_manager || m_stateCode != MusicNetworkAbstract::Init) return; musicInfo.m_songAttrs.append(attr); } if(musicInfo.m_songAttrs.isEmpty()) { return; } MusicSearchedItem item; item.m_songName = musicInfo.m_songName; item.m_singerName = musicInfo.m_singerName; item.m_time = musicInfo.m_timeLength; item.m_type = mapQueryServerString(); emit createSearchedItems(item); m_musicSongInfos << musicInfo; } } } <commit_msg>Clean code[645455]<commit_after>#include "musicdownloadquerywythread.h" #include "musicdownloadqueryyytthread.h" #include "musicsemaphoreloop.h" #include "musiccoreutils.h" #include "musicnumberutils.h" #include "musictime.h" #///QJson import #include "qjson/parser.h" MusicDownLoadQueryWYThread::MusicDownLoadQueryWYThread(QObject *parent) : MusicDownLoadQueryThreadAbstract(parent) { m_queryServer = "WangYi"; } QString MusicDownLoadQueryWYThread::getClassName() { return staticMetaObject.className(); } void MusicDownLoadQueryWYThread::startToSearch(QueryType type, const QString &text) { if(!m_manager) { return; } M_LOGGER_INFO(QString("%1 startToSearch %2").arg(getClassName()).arg(text)); m_searchText = text.trimmed(); m_currentType = type; QUrl musicUrl = MusicUtils::Algorithm::mdII(WY_SONG_SEARCH_URL, false); deleteAll(); QNetworkRequest request; request.setUrl(musicUrl); request.setRawHeader("Content-Type", "application/x-www-form-urlencoded"); request.setRawHeader("Origin", MusicUtils::Algorithm::mdII(WY_BASE_URL, false).toUtf8()); request.setRawHeader("Referer", MusicUtils::Algorithm::mdII(WY_BASE_URL, false).toUtf8()); #ifndef QT_NO_SSL QSslConfiguration sslConfig = request.sslConfiguration(); sslConfig.setPeerVerifyMode(QSslSocket::VerifyNone); request.setSslConfiguration(sslConfig); #endif m_reply = m_manager->post(request, MusicUtils::Algorithm::mdII(WY_SONG_QUERY_URL, false).arg(text).arg(0).toUtf8()); connect(m_reply, SIGNAL(finished()), SLOT(downLoadFinished())); connect(m_reply, SIGNAL(error(QNetworkReply::NetworkError)), SLOT(replyError(QNetworkReply::NetworkError))); } void MusicDownLoadQueryWYThread::startToSingleSearch(const QString &text) { if(!m_manager) { return; } M_LOGGER_INFO(QString("%1 startToSingleSearch %2").arg(getClassName()).arg(text)); QUrl musicUrl = MusicUtils::Algorithm::mdII(WY_SONG_URL, false).arg(text); deleteAll(); QNetworkRequest request; request.setUrl(musicUrl); request.setRawHeader("Content-Type", "application/x-www-form-urlencoded"); request.setRawHeader("Origin", MusicUtils::Algorithm::mdII(WY_BASE_URL, false).toUtf8()); request.setRawHeader("Referer", MusicUtils::Algorithm::mdII(WY_BASE_URL, false).toUtf8()); #ifndef QT_NO_SSL QSslConfiguration sslConfig = request.sslConfiguration(); sslConfig.setPeerVerifyMode(QSslSocket::VerifyNone); request.setSslConfiguration(sslConfig); #endif QNetworkReply *reply = m_manager->get(request); connect(reply, SIGNAL(finished()), SLOT(singleDownLoadFinished())); connect(reply, SIGNAL(error(QNetworkReply::NetworkError)), SLOT(replyError(QNetworkReply::NetworkError))); } void MusicDownLoadQueryWYThread::downLoadFinished() { if(!m_reply || !m_manager) { deleteAll(); return; } M_LOGGER_INFO(QString("%1 downLoadFinished").arg(getClassName())); emit clearAllItems(); ///Clear origin items m_musicSongInfos.clear(); ///Empty the last search to songsInfo if(m_reply->error() == QNetworkReply::NoError) { QJson::Parser parser; bool ok; QVariant data = parser.parse(m_reply->readAll(), &ok); if(ok) { QVariantMap value = data.toMap(); if(value.contains("code") && value["code"].toInt() == 200) { value = value["result"].toMap(); QVariantList datas = value["songs"].toList(); foreach(const QVariant &var, datas) { if(var.isNull()) { continue; } value = var.toMap(); if(m_currentType != MovieQuery) { MusicObject::MusicSongInformation musicInfo; musicInfo.m_songName = value["name"].toString(); musicInfo.m_timeLength = MusicTime::msecTime2LabelJustified(value["duration"].toInt()); musicInfo.m_songId = QString::number(value["id"].toInt()); musicInfo.m_lrcUrl = MusicUtils::Algorithm::mdII(WY_SONG_LRC_URL, false).arg(musicInfo.m_songId); QVariantMap albumObject = value["album"].toMap(); musicInfo.m_smallPicUrl = albumObject["picUrl"].toString(); musicInfo.m_albumId = QString::number(albumObject["id"].toInt()); musicInfo.m_albumName = albumObject["name"].toString(); QVariantList artistsArray = value["artists"].toList(); foreach(const QVariant &artistValue, artistsArray) { if(artistValue.isNull()) { continue; } QVariantMap artistMap = artistValue.toMap(); musicInfo.m_artistId = QString::number(artistMap["id"].toULongLong()); musicInfo.m_singerName = artistMap["name"].toString(); } if(!m_querySimplify) { if(!m_manager || m_stateCode != MusicNetworkAbstract::Init) return; readFromMusicSongAttribute(&musicInfo, value, m_searchQuality, m_queryAllRecords); if(!m_manager || m_stateCode != MusicNetworkAbstract::Init) return; if(musicInfo.m_songAttrs.isEmpty()) { continue; } MusicSearchedItem item; item.m_songName = musicInfo.m_songName; item.m_singerName = musicInfo.m_singerName; item.m_albumName = musicInfo.m_albumName; item.m_time = musicInfo.m_timeLength; item.m_type = mapQueryServerString(); emit createSearchedItems(item); } m_musicSongInfos << musicInfo; } else { int mvid = value["mvid"].toLongLong(); if(mvid == 0) { continue; } if(!m_manager || m_stateCode != MusicNetworkAbstract::Init) return; startMVListQuery(mvid); if(!m_manager || m_stateCode != MusicNetworkAbstract::Init) return; } } } } } ///extra yyt movie if(m_queryExtraMovie && m_currentType == MovieQuery) { MusicSemaphoreLoop loop; MusicDownLoadQueryYYTThread *yyt = new MusicDownLoadQueryYYTThread(this); connect(yyt, SIGNAL(createSearchedItems(MusicSearchedItem)), SIGNAL(createSearchedItems(MusicSearchedItem))); connect(yyt, SIGNAL(downLoadDataChanged(QString)), &loop, SLOT(quit())); yyt->startToSearch(MusicDownLoadQueryYYTThread::MovieQuery, m_searchText); loop.exec(); m_musicSongInfos << yyt->getMusicSongInfos(); } emit downLoadDataChanged(QString()); deleteAll(); M_LOGGER_INFO(QString("%1 downLoadFinished deleteAll").arg(getClassName())); } void MusicDownLoadQueryWYThread::singleDownLoadFinished() { QNetworkReply *reply = MObject_cast(QNetworkReply*, QObject::sender()); M_LOGGER_INFO(QString("%1 singleDownLoadFinished").arg(getClassName())); emit clearAllItems(); ///Clear origin items m_musicSongInfos.clear(); ///Empty the last search to songsInfo if(reply && m_manager &&reply->error() == QNetworkReply::NoError) { QByteArray bytes = reply->readAll();///Get all the data obtained by request QJson::Parser parser; bool ok; QVariant data = parser.parse(bytes, &ok); if(ok) { QVariantMap value = data.toMap(); if(value.contains("songs") && value["code"].toInt() == 200) { QVariantList datas = value["songs"].toList(); foreach(const QVariant &var, datas) { if(var.isNull()) { continue; } value = var.toMap(); MusicObject::MusicSongInformation musicInfo; musicInfo.m_songName = value["name"].toString(); musicInfo.m_timeLength = MusicTime::msecTime2LabelJustified(value["duration"].toInt()); musicInfo.m_songId = QString::number(value["id"].toInt()); musicInfo.m_lrcUrl = MusicUtils::Algorithm::mdII(WY_SONG_LRC_URL, false).arg(musicInfo.m_songId); QVariantMap albumObject = value["album"].toMap(); musicInfo.m_smallPicUrl = albumObject["picUrl"].toString(); musicInfo.m_albumId = QString::number(albumObject["id"].toInt()); musicInfo.m_albumName = albumObject["name"].toString(); QVariantList artistsArray = value["artists"].toList(); foreach(const QVariant &artistValue, artistsArray) { if(artistValue.isNull()) { continue; } QVariantMap artistMap = artistValue.toMap(); musicInfo.m_artistId = QString::number(artistMap["id"].toULongLong()); musicInfo.m_singerName = artistMap["name"].toString(); } if(!m_manager || m_stateCode != MusicNetworkAbstract::Init) return; readFromMusicSongAttribute(&musicInfo, value, m_searchQuality, true); if(!m_manager || m_stateCode != MusicNetworkAbstract::Init) return; if(!musicInfo.m_songAttrs.isEmpty()) { MusicSearchedItem item; item.m_songName = musicInfo.m_songName; item.m_singerName = musicInfo.m_singerName; item.m_albumName = musicInfo.m_albumName; item.m_time = musicInfo.m_timeLength; item.m_type = mapQueryServerString(); emit createSearchedItems(item); m_musicSongInfos << musicInfo; } } } } } emit downLoadDataChanged(QString()); deleteAll(); M_LOGGER_INFO(QString("%1 singleDownLoadFinished deleteAll").arg(getClassName())); } void MusicDownLoadQueryWYThread::startMVListQuery(int id) { QNetworkRequest request; request.setUrl(QUrl(MusicUtils::Algorithm::mdII(WY_SONG_MV_URL, false).arg(id))); request.setRawHeader("Content-Type", "application/x-www-form-urlencoded"); request.setRawHeader("Origin", MusicUtils::Algorithm::mdII(WY_BASE_URL, false).toUtf8()); request.setRawHeader("Referer", MusicUtils::Algorithm::mdII(WY_BASE_URL, false).toUtf8()); #ifndef QT_NO_SSL QSslConfiguration sslConfig = request.sslConfiguration(); sslConfig.setPeerVerifyMode(QSslSocket::VerifyNone); request.setSslConfiguration(sslConfig); #endif MusicSemaphoreLoop loop; QNetworkReply *reply = m_manager->get(request); QObject::connect(reply, SIGNAL(finished()), &loop, SLOT(quit())); QObject::connect(reply, SIGNAL(error(QNetworkReply::NetworkError)), &loop, SLOT(quit())); loop.exec(); if(!reply || reply->error() != QNetworkReply::NoError) { return; } QJson::Parser parser; bool ok; QVariant data = parser.parse(reply->readAll(), &ok); if(ok) { QVariantMap value = data.toMap(); if(value.contains("code") && value["code"].toInt() == 200) { value = value["data"].toMap(); MusicObject::MusicSongInformation musicInfo; musicInfo.m_songName = value["name"].toString(); musicInfo.m_singerName = value["artistName"].toString(); musicInfo.m_timeLength = MusicTime::msecTime2LabelJustified(value["duration"].toInt()); value = value["brs"].toMap(); foreach(const QString &key, value.keys()) { int bit = key.toInt(); MusicObject::MusicSongAttribute attr; if(bit <= 625) attr.m_bitrate = MB_500; else if(bit > 625 && bit <= 875) attr.m_bitrate = MB_750; else if(bit > 875) attr.m_bitrate = MB_1000; attr.m_url = value[key].toString(); attr.m_format = MusicUtils::Core::fileSuffix(attr.m_url); if(!m_manager || m_stateCode != MusicNetworkAbstract::Init) return; attr.m_size = MusicUtils::Number::size2Label(getUrlFileSize(attr.m_url)); if(!m_manager || m_stateCode != MusicNetworkAbstract::Init) return; musicInfo.m_songAttrs.append(attr); } if(musicInfo.m_songAttrs.isEmpty()) { return; } MusicSearchedItem item; item.m_songName = musicInfo.m_songName; item.m_singerName = musicInfo.m_singerName; item.m_time = musicInfo.m_timeLength; item.m_type = mapQueryServerString(); emit createSearchedItems(item); m_musicSongInfos << musicInfo; } } } <|endoftext|>
<commit_before>// This code is based on Sabberstone project. // Copyright (c) 2017-2019 SabberStone Team, darkfriend77 & rnilva // RosettaStone is hearthstone simulator using C++ with reinforcement learning. // Copyright (c) 2019 Chris Ohk, Youngjoong Kim, SeungHyun Jeon #ifndef ROSETTASTONE_CHARACTER_HPP #define ROSETTASTONE_CHARACTER_HPP #include <Rosetta/Models/Entity.hpp> namespace RosettaStone { class Player; //! //! \brief Abstract character class that stores hero and minion data. //! //! This class inherits from Entity class. Also, it stores some //! attributes that only characters have such as attack and health. //! class Character : public Entity { public: //! Default constructor. Character() = default; //! Constructs character with given \p _owner, \p _card and \p tags. //! \param _owner The owner of the card. //! \param _card The card. //! \param tags The game tags. Character(Player& _owner, Card& _card, std::map<GameTag, int> tags); //! Default destructor. virtual ~Character() = default; //! Default copy constructor. Character(const Character& c) = default; //! Default move constructor. Character(Character&& c) = default; //! Default copy assignment operator. Character& operator=(const Character& c) = default; //! Default move assignment operator. Character& operator=(Character&& c) = default; //! Returns the value of attack. //! \return The value of attack. virtual int GetAttack() const; //! Sets the value of attack. //! \param attack The value of attack. void SetAttack(int attack); //! Returns the value of pre-damage. //! \return The value of pre-damage. int GetPreDamage() const; //! Sets the value of pre-damage. //! \param preDamage The value of pre-damage. void SetPreDamage(int preDamage); //! Returns the value of damage. //! \return The value of damage. int GetDamage() const; //! Sets the value of damage. //! \param damage The value of damage. void SetDamage(int damage); //! Returns the value of health. //! \return The value of health. int GetHealth() const; //! Sets the value of health. //! \param health The value of health. void SetHealth(int health); //! Returns the value of spell power. //! \return The value of spell power. int GetSpellPower() const; //! Sets the value of spell power. //! \param spellPower The value of spell power. void SetSpellPower(int spellPower); //! Returns the number of attacks at this turn. //! \return The number of attacks at this turn. int GetNumAttacksThisTurn() const; //! Gets the number of attacks at this turn. //! \param amount The number of attacks at this turn. void SetNumAttacksThisTurn(int amount); //! Returns whether attack is possible. //! \return Whether attack is possible. bool CanAttack() const; //! Returns whether the target is valid in combat. //! \param opponent The opponent player. //! \param target A pointer to the target. //! \return true if the target is valid, and false otherwise. bool IsValidCombatTarget(Player& opponent, Character* target) const; //! Returns a list of valid target in combat. //! \param opponent The opponent player. //! \return A list of pointer to valid target. std::vector<Character*> GetValidCombatTargets(Player& opponent) const; //! Takes damage from a certain other entity. //! \param source An entity to give damage. //! \param damage The value of damage. //! \return Final damage taking into account ability. int TakeDamage(Entity& source, int damage); //! Takes heal up all taken damage. //! \param source An entity to give full heal. void TakeFullHeal(Entity& source); //! Takes heal a specified amount of health. //! \param source An entity to give heal. //! \param heal The value of heal. void TakeHeal(Entity& source, int heal); std::function<void(Player*, Entity*)> preDamageTrigger; }; } // namespace RosettaStone #endif // ROSETTASTONE_CHARACTER_HPP <commit_msg>feat(card-impl): Add variable 'afterAttackTrigger'<commit_after>// This code is based on Sabberstone project. // Copyright (c) 2017-2019 SabberStone Team, darkfriend77 & rnilva // RosettaStone is hearthstone simulator using C++ with reinforcement learning. // Copyright (c) 2019 Chris Ohk, Youngjoong Kim, SeungHyun Jeon #ifndef ROSETTASTONE_CHARACTER_HPP #define ROSETTASTONE_CHARACTER_HPP #include <Rosetta/Models/Entity.hpp> namespace RosettaStone { class Player; //! //! \brief Abstract character class that stores hero and minion data. //! //! This class inherits from Entity class. Also, it stores some //! attributes that only characters have such as attack and health. //! class Character : public Entity { public: //! Default constructor. Character() = default; //! Constructs character with given \p _owner, \p _card and \p tags. //! \param _owner The owner of the card. //! \param _card The card. //! \param tags The game tags. Character(Player& _owner, Card& _card, std::map<GameTag, int> tags); //! Default destructor. virtual ~Character() = default; //! Default copy constructor. Character(const Character& c) = default; //! Default move constructor. Character(Character&& c) = default; //! Default copy assignment operator. Character& operator=(const Character& c) = default; //! Default move assignment operator. Character& operator=(Character&& c) = default; //! Returns the value of attack. //! \return The value of attack. virtual int GetAttack() const; //! Sets the value of attack. //! \param attack The value of attack. void SetAttack(int attack); //! Returns the value of pre-damage. //! \return The value of pre-damage. int GetPreDamage() const; //! Sets the value of pre-damage. //! \param preDamage The value of pre-damage. void SetPreDamage(int preDamage); //! Returns the value of damage. //! \return The value of damage. int GetDamage() const; //! Sets the value of damage. //! \param damage The value of damage. void SetDamage(int damage); //! Returns the value of health. //! \return The value of health. int GetHealth() const; //! Sets the value of health. //! \param health The value of health. void SetHealth(int health); //! Returns the value of spell power. //! \return The value of spell power. int GetSpellPower() const; //! Sets the value of spell power. //! \param spellPower The value of spell power. void SetSpellPower(int spellPower); //! Returns the number of attacks at this turn. //! \return The number of attacks at this turn. int GetNumAttacksThisTurn() const; //! Gets the number of attacks at this turn. //! \param amount The number of attacks at this turn. void SetNumAttacksThisTurn(int amount); //! Returns whether attack is possible. //! \return Whether attack is possible. bool CanAttack() const; //! Returns whether the target is valid in combat. //! \param opponent The opponent player. //! \param target A pointer to the target. //! \return true if the target is valid, and false otherwise. bool IsValidCombatTarget(Player& opponent, Character* target) const; //! Returns a list of valid target in combat. //! \param opponent The opponent player. //! \return A list of pointer to valid target. std::vector<Character*> GetValidCombatTargets(Player& opponent) const; //! Takes damage from a certain other entity. //! \param source An entity to give damage. //! \param damage The value of damage. //! \return Final damage taking into account ability. int TakeDamage(Entity& source, int damage); //! Takes heal up all taken damage. //! \param source An entity to give full heal. void TakeFullHeal(Entity& source); //! Takes heal a specified amount of health. //! \param source An entity to give heal. //! \param heal The value of heal. void TakeHeal(Entity& source, int heal); std::function<void(Player*, Entity*)> afterAttackTrigger; std::function<void(Player*, Entity*)> preDamageTrigger; }; } // namespace RosettaStone #endif // ROSETTASTONE_CHARACTER_HPP <|endoftext|>
<commit_before>#include "Adafruit_ZeroI2S.h" #include "wiring_private.h" Adafruit_ZeroI2S::Adafruit_ZeroI2S(uint8_t FS_PIN, uint8_t SCK_PIN, uint8_t TX_PIN, uint8_t RX_PIN) : _fs(FS_PIN), _sck(SCK_PIN), _tx(TX_PIN), _rx(RX_PIN) {} Adafruit_ZeroI2S::Adafruit_ZeroI2S() : _fs(PIN_I2S_FS), _sck(PIN_I2S_SCK), _tx(PIN_I2S_SDO), _rx(PIN_I2S_SDI) {} bool Adafruit_ZeroI2S::begin(I2SSlotSize width, int fs_freq, int mck_mult) { pinPeripheral(_fs, PIO_I2S); pinPeripheral(_sck, PIO_I2S); pinPeripheral(_rx, PIO_I2S); pinPeripheral(_tx, PIO_I2S); I2S->CTRLA.bit.ENABLE = 0; //initialize clock control MCLK->APBDMASK.reg |= MCLK_APBDMASK_I2S; GCLK->PCHCTRL[I2S_GCLK_ID_0].reg = GCLK_PCHCTRL_GEN_GCLK2_Val | (1 << GCLK_PCHCTRL_CHEN_Pos); GCLK->PCHCTRL[I2S_GCLK_ID_1].reg = GCLK_PCHCTRL_GEN_GCLK2_Val | (1 << GCLK_PCHCTRL_CHEN_Pos); //software reset I2S->CTRLA.bit.SWRST = 1; while(I2S->SYNCBUSY.bit.SWRST || I2S->SYNCBUSY.bit.ENABLE); //wait for sync uint32_t mckFreq = (fs_freq * mck_mult); uint32_t sckFreq = fs_freq * I2S_NUM_SLOTS * ( (width + 1) << 3); //CLKCTRL[0] is used for the tx channel I2S->CLKCTRL[0].reg = I2S_CLKCTRL_MCKSEL_GCLK | I2S_CLKCTRL_MCKOUTDIV( (VARIANT_GCLK2_FREQ/mckFreq) - 1) | I2S_CLKCTRL_MCKDIV((VARIANT_GCLK2_FREQ/sckFreq) - 1) | I2S_CLKCTRL_SCKSEL_MCKDIV | I2S_CLKCTRL_MCKEN | I2S_CLKCTRL_FSSEL_SCKDIV | I2S_CLKCTRL_BITDELAY_I2S | I2S_CLKCTRL_FSWIDTH_HALF | I2S_CLKCTRL_NBSLOTS(I2S_NUM_SLOTS - 1) | I2S_CLKCTRL_SLOTSIZE(width); uint8_t wordSize; switch(width){ case I2S_8_BIT: wordSize = I2S_TXCTRL_DATASIZE_8_Val; break; case I2S_16_BIT: wordSize = I2S_TXCTRL_DATASIZE_16_Val; break; case I2S_24_BIT: wordSize = I2S_TXCTRL_DATASIZE_24_Val; break; case I2S_32_BIT: wordSize = I2S_TXCTRL_DATASIZE_32_Val; break; } I2S->TXCTRL.reg = I2S_TXCTRL_DMA_SINGLE | I2S_TXCTRL_MONO_STEREO | I2S_TXCTRL_BITREV_MSBIT | I2S_TXCTRL_EXTEND_ZERO | I2S_TXCTRL_WORDADJ_RIGHT | I2S_TXCTRL_DATASIZE(wordSize) | I2S_TXCTRL_TXSAME_ZERO | I2S_TXCTRL_TXDEFAULT_ZERO; I2S->RXCTRL.reg = I2S_RXCTRL_DMA_SINGLE | I2S_RXCTRL_MONO_STEREO | I2S_RXCTRL_BITREV_MSBIT | I2S_RXCTRL_EXTEND_ZERO | I2S_RXCTRL_WORDADJ_RIGHT | I2S_RXCTRL_DATASIZE(wordSize) | I2S_RXCTRL_SLOTADJ_RIGHT | I2S_RXCTRL_CLKSEL_CLK0 | I2S_RXCTRL_SERMODE_RX; while(I2S->SYNCBUSY.bit.ENABLE); //wait for sync I2S->CTRLA.bit.ENABLE = 1; return true; } void Adafruit_ZeroI2S::enableTx() { I2S->CTRLA.bit.CKEN0 = 1; while(I2S->SYNCBUSY.bit.CKEN0); I2S->CTRLA.bit.TXEN = 1; while(I2S->SYNCBUSY.bit.TXEN); } void Adafruit_ZeroI2S::disableTx() { I2S->CTRLA.bit.TXEN = 0; while(I2S->SYNCBUSY.bit.TXEN); } void Adafruit_ZeroI2S::enableRx(uint8_t clk) { I2S->CTRLA.bit.CKEN0 = 1; while(I2S->SYNCBUSY.bit.CKEN0); I2S->CTRLA.bit.RXEN = 1; while(I2S->SYNCBUSY.bit.RXEN); } void Adafruit_ZeroI2S::disableRx() { I2S->CTRLA.bit.RXEN = 0; while(I2S->SYNCBUSY.bit.RXEN); } void Adafruit_ZeroI2S::enableMCLK() { pinPeripheral(PIN_I2S_MCK, PIO_I2S); } void Adafruit_ZeroI2S::disableMCLK() { pinMode(PIN_I2S_MCK, INPUT); } bool Adafruit_ZeroI2S::txReady() { return ((!I2S->INTFLAG.bit.TXRDY0) || I2S->SYNCBUSY.bit.TXDATA ); } void Adafruit_ZeroI2S::write(int32_t left, int32_t right) { while( (!I2S->INTFLAG.bit.TXRDY0) || I2S->SYNCBUSY.bit.TXDATA ); I2S->INTFLAG.bit.TXUR0 = 1; I2S->TXDATA.reg = left; while( (!I2S->INTFLAG.bit.TXRDY0) || I2S->SYNCBUSY.bit.TXDATA ); I2S->INTFLAG.bit.TXUR0 = 1; I2S->TXDATA.reg = right; } void Adafruit_ZeroI2S::read(int32_t *left, int32_t *right) { while( (!I2S->INTFLAG.bit.RXRDY0) || I2S->SYNCBUSY.bit.RXDATA ); *left = I2S->RXDATA.reg; while( (!I2S->INTFLAG.bit.RXRDY0) || I2S->SYNCBUSY.bit.RXDATA ); *right = I2S->RXDATA.reg; } <commit_msg>DM: lower clock rate necessary for 44.1khz<commit_after>#include "Adafruit_ZeroI2S.h" #include "wiring_private.h" Adafruit_ZeroI2S::Adafruit_ZeroI2S(uint8_t FS_PIN, uint8_t SCK_PIN, uint8_t TX_PIN, uint8_t RX_PIN) : _fs(FS_PIN), _sck(SCK_PIN), _tx(TX_PIN), _rx(RX_PIN) {} Adafruit_ZeroI2S::Adafruit_ZeroI2S() : _fs(PIN_I2S_FS), _sck(PIN_I2S_SCK), _tx(PIN_I2S_SDO), _rx(PIN_I2S_SDI) {} bool Adafruit_ZeroI2S::begin(I2SSlotSize width, int fs_freq, int mck_mult) { pinPeripheral(_fs, PIO_I2S); pinPeripheral(_sck, PIO_I2S); pinPeripheral(_rx, PIO_I2S); pinPeripheral(_tx, PIO_I2S); I2S->CTRLA.bit.ENABLE = 0; //initialize clock control MCLK->APBDMASK.reg |= MCLK_APBDMASK_I2S; GCLK->PCHCTRL[I2S_GCLK_ID_0].reg = GCLK_PCHCTRL_GEN_GCLK1_Val | (1 << GCLK_PCHCTRL_CHEN_Pos); GCLK->PCHCTRL[I2S_GCLK_ID_1].reg = GCLK_PCHCTRL_GEN_GCLK1_Val | (1 << GCLK_PCHCTRL_CHEN_Pos); //software reset I2S->CTRLA.bit.SWRST = 1; while(I2S->SYNCBUSY.bit.SWRST || I2S->SYNCBUSY.bit.ENABLE); //wait for sync uint32_t mckFreq = (fs_freq * mck_mult); uint32_t sckFreq = fs_freq * I2S_NUM_SLOTS * ( (width + 1) << 3); //CLKCTRL[0] is used for the tx channel I2S->CLKCTRL[0].reg = I2S_CLKCTRL_MCKSEL_GCLK | I2S_CLKCTRL_MCKOUTDIV( (VARIANT_GCLK1_FREQ/mckFreq) - 1) | I2S_CLKCTRL_MCKDIV((VARIANT_GCLK1_FREQ/sckFreq) - 1) | I2S_CLKCTRL_SCKSEL_MCKDIV | I2S_CLKCTRL_MCKEN | I2S_CLKCTRL_FSSEL_SCKDIV | I2S_CLKCTRL_BITDELAY_I2S | I2S_CLKCTRL_FSWIDTH_HALF | I2S_CLKCTRL_NBSLOTS(I2S_NUM_SLOTS - 1) | I2S_CLKCTRL_SLOTSIZE(width); uint8_t wordSize; switch(width){ case I2S_8_BIT: wordSize = I2S_TXCTRL_DATASIZE_8_Val; break; case I2S_16_BIT: wordSize = I2S_TXCTRL_DATASIZE_16_Val; break; case I2S_24_BIT: wordSize = I2S_TXCTRL_DATASIZE_24_Val; break; case I2S_32_BIT: wordSize = I2S_TXCTRL_DATASIZE_32_Val; break; } I2S->TXCTRL.reg = I2S_TXCTRL_DMA_SINGLE | I2S_TXCTRL_MONO_STEREO | I2S_TXCTRL_BITREV_MSBIT | I2S_TXCTRL_EXTEND_ZERO | I2S_TXCTRL_WORDADJ_RIGHT | I2S_TXCTRL_DATASIZE(wordSize) | I2S_TXCTRL_TXSAME_ZERO | I2S_TXCTRL_TXDEFAULT_ZERO; I2S->RXCTRL.reg = I2S_RXCTRL_DMA_SINGLE | I2S_RXCTRL_MONO_STEREO | I2S_RXCTRL_BITREV_MSBIT | I2S_RXCTRL_EXTEND_ZERO | I2S_RXCTRL_WORDADJ_RIGHT | I2S_RXCTRL_DATASIZE(wordSize) | I2S_RXCTRL_SLOTADJ_RIGHT | I2S_RXCTRL_CLKSEL_CLK0 | I2S_RXCTRL_SERMODE_RX; while(I2S->SYNCBUSY.bit.ENABLE); //wait for sync I2S->CTRLA.bit.ENABLE = 1; return true; } void Adafruit_ZeroI2S::enableTx() { I2S->CTRLA.bit.CKEN0 = 1; while(I2S->SYNCBUSY.bit.CKEN0); I2S->CTRLA.bit.TXEN = 1; while(I2S->SYNCBUSY.bit.TXEN); } void Adafruit_ZeroI2S::disableTx() { I2S->CTRLA.bit.TXEN = 0; while(I2S->SYNCBUSY.bit.TXEN); } void Adafruit_ZeroI2S::enableRx(uint8_t clk) { I2S->CTRLA.bit.CKEN0 = 1; while(I2S->SYNCBUSY.bit.CKEN0); I2S->CTRLA.bit.RXEN = 1; while(I2S->SYNCBUSY.bit.RXEN); } void Adafruit_ZeroI2S::disableRx() { I2S->CTRLA.bit.RXEN = 0; while(I2S->SYNCBUSY.bit.RXEN); } void Adafruit_ZeroI2S::enableMCLK() { pinPeripheral(PIN_I2S_MCK, PIO_I2S); } void Adafruit_ZeroI2S::disableMCLK() { pinMode(PIN_I2S_MCK, INPUT); } bool Adafruit_ZeroI2S::txReady() { return ((!I2S->INTFLAG.bit.TXRDY0) || I2S->SYNCBUSY.bit.TXDATA ); } void Adafruit_ZeroI2S::write(int32_t left, int32_t right) { while( (!I2S->INTFLAG.bit.TXRDY0) || I2S->SYNCBUSY.bit.TXDATA ); I2S->INTFLAG.bit.TXUR0 = 1; I2S->TXDATA.reg = left; while( (!I2S->INTFLAG.bit.TXRDY0) || I2S->SYNCBUSY.bit.TXDATA ); I2S->INTFLAG.bit.TXUR0 = 1; I2S->TXDATA.reg = right; } void Adafruit_ZeroI2S::read(int32_t *left, int32_t *right) { while( (!I2S->INTFLAG.bit.RXRDY0) || I2S->SYNCBUSY.bit.RXDATA ); *left = I2S->RXDATA.reg; while( (!I2S->INTFLAG.bit.RXRDY0) || I2S->SYNCBUSY.bit.RXDATA ); *right = I2S->RXDATA.reg; } <|endoftext|>
<commit_before>/* * File: multi_bounded_queue.hpp * Author: Barath Kannan * Vector of bounded list queues. * Created on 28 January 2017, 09:42 AM */ #ifndef BK_CONQ_MULTI_BOUNDED_QUEUE_HPP #define BK_CONQ_MULTI_BOUNDED_QUEUE_HPP #include <thread> #include <vector> #include <mutex> #include <memory> #include <numeric> #include <bk_conq/bounded_queue.hpp> #include <bk_conq/details/tlos.hpp> namespace bk_conq { template<typename TT> class multi_bounded_queue; template <template <typename> class Q, typename T> class multi_bounded_queue<Q<T>> : public bounded_queue<T, multi_bounded_queue<Q<T>>> { friend bounded_queue<T, multi_bounded_queue<Q<T>>>; public: multi_bounded_queue(size_t N, size_t subqueues) : _hitlist([&]() {return hitlist_sequence(); }), _enqueue_identifier([&]() { return get_enqueue_index(); }, [&](size_t indx) {return return_enqueue_index(indx); }) { static_assert(std::is_base_of<bk_conq::bounded_queue_typed_tag<T>, Q<T>>::value, "Q<T> must be a bounded queue"); for (size_t i = 0; i < subqueues; ++i) { _q.push_back(std::make_unique<padded_bounded_queue>(N)); } } multi_bounded_queue(const multi_bounded_queue&) = delete; void operator=(const multi_bounded_queue&) = delete; protected: template <typename R> bool sp_enqueue_impl(R&& input) { size_t indx = _enqueue_identifier.get(); return _q[indx]->mp_enqueue(std::forward<R>(input)); } template <typename R> bool mp_enqueue_impl(R&& input) { size_t indx = _enqueue_identifier.get(); return _q[indx]->mp_enqueue(std::forward<R>(input)); } bool sc_dequeue_impl(T& output) { auto& hitlist = _hitlist.get(); for (auto it = hitlist.cbegin(); it != hitlist.cend(); ++it) { if (_q[*it]->sc_dequeue(output)) { if (hitlist.cbegin() == it) return true; //as below auto nonconstit = hitlist.erase(it, it); for (auto it2 = hitlist.begin(); it2 != nonconstit; ++it2) std::iter_swap(nonconstit, it2); return true; } } return false; } bool mc_dequeue_impl(T& output) { auto& hitlist = _hitlist.get(); for (auto it = hitlist.cbegin(); it != hitlist.cend(); ++it) { if (_q[*it]->mc_dequeue_uncontended(output)) { if (hitlist.cbegin() == it) return true; //funky magic - range erase returns an iterator, but an empty range is provided so contents aren't changed //this converts a const iterator to an iterator in constant time auto nonconstit = hitlist.erase(it, it); for (auto it2 = hitlist.begin(); it2 != nonconstit; ++it2) std::iter_swap(nonconstit, it2); return true; } } for (auto it = hitlist.cbegin(); it != hitlist.cend(); ++it) { if (_q[*it]->mc_dequeue(output)) { if (hitlist.cbegin() == it) return true; //as above auto nonconstit = hitlist.erase(it, it); for (auto it2 = hitlist.begin(); it2 != nonconstit; ++it2) std::iter_swap(nonconstit, it2); return true; } } return false; } bool mc_dequeue_uncontended_impl(T& output) { auto& hitlist = _hitlist.get(); for (auto it = hitlist.cbegin(); it != hitlist.cend(); ++it) { if (_q[*it]->mc_dequeue_uncontended(output)) { if (hitlist.cbegin() == it) return true; //as above auto nonconstit = hitlist.erase(it, it); for (auto it2 = hitlist.begin(); it2 != nonconstit; ++it2) std::iter_swap(nonconstit, it2); return true; } } return false; } private: class padded_bounded_queue : public Q<T> { public: padded_bounded_queue(size_t N) : Q<T>(N) {} private: char padding[64]; }; std::vector<size_t> hitlist_sequence() { std::vector<size_t> hitlist(_q.size()); std::iota(hitlist.begin(), hitlist.end(), 0); return hitlist; } size_t get_enqueue_index() { std::lock_guard<std::mutex> lock(_m); if (_unused_enqueue_indexes.empty()) { return (_enqueue_index++) % _q.size(); } size_t ret = _unused_enqueue_indexes.back(); _unused_enqueue_indexes.pop_back(); return ret; } void return_enqueue_index(size_t index) { std::lock_guard<std::mutex> lock(_m); _unused_enqueue_indexes.push_back(index); } std::vector<size_t> _unused_enqueue_indexes; std::vector<std::unique_ptr<padded_bounded_queue>> _q; std::atomic<size_t> _enqueue_indx{ 0 }; size_t _enqueue_index{ 0 }; std::mutex _m; details::tlos<std::vector<size_t>, multi_bounded_queue<Q<T>>> _hitlist; details::tlos<size_t, multi_bounded_queue<Q<T>>> _enqueue_identifier; }; }//namespace bk_conq #endif // BK_CONQ_MULTI_BOUNDED_QUEUE_HPP <commit_msg>remove unused atomic<commit_after>/* * File: multi_bounded_queue.hpp * Author: Barath Kannan * Vector of bounded list queues. * Created on 28 January 2017, 09:42 AM */ #ifndef BK_CONQ_MULTI_BOUNDED_QUEUE_HPP #define BK_CONQ_MULTI_BOUNDED_QUEUE_HPP #include <thread> #include <vector> #include <mutex> #include <memory> #include <numeric> #include <bk_conq/bounded_queue.hpp> #include <bk_conq/details/tlos.hpp> namespace bk_conq { template<typename TT> class multi_bounded_queue; template <template <typename> class Q, typename T> class multi_bounded_queue<Q<T>> : public bounded_queue<T, multi_bounded_queue<Q<T>>> { friend bounded_queue<T, multi_bounded_queue<Q<T>>>; public: multi_bounded_queue(size_t N, size_t subqueues) : _hitlist([&]() {return hitlist_sequence(); }), _enqueue_identifier([&]() { return get_enqueue_index(); }, [&](size_t indx) {return return_enqueue_index(indx); }) { static_assert(std::is_base_of<bk_conq::bounded_queue_typed_tag<T>, Q<T>>::value, "Q<T> must be a bounded queue"); for (size_t i = 0; i < subqueues; ++i) { _q.push_back(std::make_unique<padded_bounded_queue>(N)); } } multi_bounded_queue(const multi_bounded_queue&) = delete; void operator=(const multi_bounded_queue&) = delete; protected: template <typename R> bool sp_enqueue_impl(R&& input) { size_t indx = _enqueue_identifier.get(); return _q[indx]->mp_enqueue(std::forward<R>(input)); } template <typename R> bool mp_enqueue_impl(R&& input) { size_t indx = _enqueue_identifier.get(); return _q[indx]->mp_enqueue(std::forward<R>(input)); } bool sc_dequeue_impl(T& output) { auto& hitlist = _hitlist.get(); for (auto it = hitlist.cbegin(); it != hitlist.cend(); ++it) { if (_q[*it]->sc_dequeue(output)) { if (hitlist.cbegin() == it) return true; //as below auto nonconstit = hitlist.erase(it, it); for (auto it2 = hitlist.begin(); it2 != nonconstit; ++it2) std::iter_swap(nonconstit, it2); return true; } } return false; } bool mc_dequeue_impl(T& output) { auto& hitlist = _hitlist.get(); for (auto it = hitlist.cbegin(); it != hitlist.cend(); ++it) { if (_q[*it]->mc_dequeue_uncontended(output)) { if (hitlist.cbegin() == it) return true; //funky magic - range erase returns an iterator, but an empty range is provided so contents aren't changed //this converts a const iterator to an iterator in constant time auto nonconstit = hitlist.erase(it, it); for (auto it2 = hitlist.begin(); it2 != nonconstit; ++it2) std::iter_swap(nonconstit, it2); return true; } } for (auto it = hitlist.cbegin(); it != hitlist.cend(); ++it) { if (_q[*it]->mc_dequeue(output)) { if (hitlist.cbegin() == it) return true; //as above auto nonconstit = hitlist.erase(it, it); for (auto it2 = hitlist.begin(); it2 != nonconstit; ++it2) std::iter_swap(nonconstit, it2); return true; } } return false; } bool mc_dequeue_uncontended_impl(T& output) { auto& hitlist = _hitlist.get(); for (auto it = hitlist.cbegin(); it != hitlist.cend(); ++it) { if (_q[*it]->mc_dequeue_uncontended(output)) { if (hitlist.cbegin() == it) return true; //as above auto nonconstit = hitlist.erase(it, it); for (auto it2 = hitlist.begin(); it2 != nonconstit; ++it2) std::iter_swap(nonconstit, it2); return true; } } return false; } private: class padded_bounded_queue : public Q<T> { public: padded_bounded_queue(size_t N) : Q<T>(N) {} private: char padding[64]; }; std::vector<size_t> hitlist_sequence() { std::vector<size_t> hitlist(_q.size()); std::iota(hitlist.begin(), hitlist.end(), 0); return hitlist; } size_t get_enqueue_index() { std::lock_guard<std::mutex> lock(_m); if (_unused_enqueue_indexes.empty()) { return (_enqueue_index++) % _q.size(); } size_t ret = _unused_enqueue_indexes.back(); _unused_enqueue_indexes.pop_back(); return ret; } void return_enqueue_index(size_t index) { std::lock_guard<std::mutex> lock(_m); _unused_enqueue_indexes.push_back(index); } std::vector<size_t> _unused_enqueue_indexes; std::vector<std::unique_ptr<padded_bounded_queue>> _q; size_t _enqueue_index{ 0 }; std::mutex _m; details::tlos<std::vector<size_t>, multi_bounded_queue<Q<T>>> _hitlist; details::tlos<size_t, multi_bounded_queue<Q<T>>> _enqueue_identifier; }; }//namespace bk_conq #endif // BK_CONQ_MULTI_BOUNDED_QUEUE_HPP <|endoftext|>
<commit_before>/* * Copyright (c) 2012 The WebRTC project authors. All Rights Reserved. * * Use of this source code is governed by a BSD-style license * that can be found in the LICENSE file in the root of the source * tree. An additional intellectual property rights grant can be found * in the file PATENTS. All contributing project authors may * be found in the AUTHORS file in the root of the source tree. */ #include "video_capture_impl.h" #include "common_video/libyuv/include/webrtc_libyuv.h" #include "critical_section_wrapper.h" #include "module_common_types.h" #include "ref_count.h" #include "tick_util.h" #include "trace.h" #include "video_capture_config.h" #include <stdlib.h> namespace webrtc { namespace videocapturemodule { VideoCaptureModule* VideoCaptureImpl::Create( const WebRtc_Word32 id, VideoCaptureExternal*& externalCapture) { RefCountImpl<VideoCaptureImpl>* implementation = new RefCountImpl<VideoCaptureImpl>(id); externalCapture = implementation; return implementation; } const char* VideoCaptureImpl::CurrentDeviceName() const { return _deviceUniqueId; } WebRtc_Word32 VideoCaptureImpl::ChangeUniqueId(const WebRtc_Word32 id) { _id = id; return 0; } // returns the number of milliseconds until the module want a worker thread to call Process WebRtc_Word32 VideoCaptureImpl::TimeUntilNextProcess() { CriticalSectionScoped cs(&_callBackCs); WebRtc_Word32 timeToNormalProcess = kProcessInterval - (WebRtc_Word32)((TickTime::Now() - _lastProcessTime).Milliseconds()); return timeToNormalProcess; } // Process any pending tasks such as timeouts WebRtc_Word32 VideoCaptureImpl::Process() { CriticalSectionScoped cs(&_callBackCs); const TickTime now = TickTime::Now(); _lastProcessTime = TickTime::Now(); // Handle No picture alarm if (_lastProcessFrameCount.Ticks() == _incomingFrameTimes[0].Ticks() && _captureAlarm != Raised) { if (_noPictureAlarmCallBack && _captureCallBack) { _captureAlarm = Raised; _captureCallBack->OnNoPictureAlarm(_id, _captureAlarm); } } else if (_lastProcessFrameCount.Ticks() != _incomingFrameTimes[0].Ticks() && _captureAlarm != Cleared) { if (_noPictureAlarmCallBack && _captureCallBack) { _captureAlarm = Cleared; _captureCallBack->OnNoPictureAlarm(_id, _captureAlarm); } } // Handle frame rate callback if ((now - _lastFrameRateCallbackTime).Milliseconds() > kFrameRateCallbackInterval) { if (_frameRateCallBack && _captureCallBack) { const WebRtc_UWord32 frameRate = CalculateFrameRate(now); _captureCallBack->OnCaptureFrameRate(_id, frameRate); } _lastFrameRateCallbackTime = now; // Can be set by EnableFrameRateCallback } _lastProcessFrameCount = _incomingFrameTimes[0]; return 0; } VideoCaptureImpl::VideoCaptureImpl(const WebRtc_Word32 id) : _id(id), _deviceUniqueId(NULL), _apiCs(*CriticalSectionWrapper::CreateCriticalSection()), _captureDelay(0), _requestedCapability(), _callBackCs(*CriticalSectionWrapper::CreateCriticalSection()), _lastProcessTime(TickTime::Now()), _lastFrameRateCallbackTime(TickTime::Now()), _frameRateCallBack(false), _noPictureAlarmCallBack(false), _captureAlarm(Cleared), _setCaptureDelay(0), _dataCallBack(NULL), _captureCallBack(NULL), _lastProcessFrameCount(TickTime::Now()), _rotateFrame(kRotateNone), last_capture_time_(TickTime::MillisecondTimestamp()) { _requestedCapability.width = kDefaultWidth; _requestedCapability.height = kDefaultHeight; _requestedCapability.maxFPS = 30; _requestedCapability.rawType = kVideoI420; _requestedCapability.codecType = kVideoCodecUnknown; memset(_incomingFrameTimes, 0, sizeof(_incomingFrameTimes)); } VideoCaptureImpl::~VideoCaptureImpl() { DeRegisterCaptureDataCallback(); DeRegisterCaptureCallback(); delete &_callBackCs; delete &_apiCs; if (_deviceUniqueId) delete[] _deviceUniqueId; } WebRtc_Word32 VideoCaptureImpl::RegisterCaptureDataCallback( VideoCaptureDataCallback& dataCallBack) { CriticalSectionScoped cs(&_apiCs); CriticalSectionScoped cs2(&_callBackCs); _dataCallBack = &dataCallBack; return 0; } WebRtc_Word32 VideoCaptureImpl::DeRegisterCaptureDataCallback() { CriticalSectionScoped cs(&_apiCs); CriticalSectionScoped cs2(&_callBackCs); _dataCallBack = NULL; return 0; } WebRtc_Word32 VideoCaptureImpl::RegisterCaptureCallback(VideoCaptureFeedBack& callBack) { CriticalSectionScoped cs(&_apiCs); CriticalSectionScoped cs2(&_callBackCs); _captureCallBack = &callBack; return 0; } WebRtc_Word32 VideoCaptureImpl::DeRegisterCaptureCallback() { CriticalSectionScoped cs(&_apiCs); CriticalSectionScoped cs2(&_callBackCs); _captureCallBack = NULL; return 0; } WebRtc_Word32 VideoCaptureImpl::SetCaptureDelay(WebRtc_Word32 delayMS) { CriticalSectionScoped cs(&_apiCs); _captureDelay = delayMS; return 0; } WebRtc_Word32 VideoCaptureImpl::CaptureDelay() { CriticalSectionScoped cs(&_apiCs); return _setCaptureDelay; } WebRtc_Word32 VideoCaptureImpl::DeliverCapturedFrame(I420VideoFrame& captureFrame, WebRtc_Word64 capture_time) { UpdateFrameCount(); // frame count used for local frame rate callback. const bool callOnCaptureDelayChanged = _setCaptureDelay != _captureDelay; // Capture delay changed if (_setCaptureDelay != _captureDelay) { _setCaptureDelay = _captureDelay; } // Set the capture time if (capture_time != 0) { captureFrame.set_render_time_ms(capture_time); } else { captureFrame.set_render_time_ms(TickTime::MillisecondTimestamp()); } if (captureFrame.render_time_ms() == last_capture_time_) { // We don't allow the same capture time for two frames, drop this one. return -1; } last_capture_time_ = captureFrame.render_time_ms(); if (_dataCallBack) { if (callOnCaptureDelayChanged) { _dataCallBack->OnCaptureDelayChanged(_id, _captureDelay); } _dataCallBack->OnIncomingCapturedFrame(_id, captureFrame); } return 0; } WebRtc_Word32 VideoCaptureImpl::DeliverEncodedCapturedFrame( VideoFrame& captureFrame, WebRtc_Word64 capture_time, VideoCodecType codecType) { UpdateFrameCount(); // frame count used for local frame rate callback. const bool callOnCaptureDelayChanged = _setCaptureDelay != _captureDelay; // Capture delay changed if (_setCaptureDelay != _captureDelay) { _setCaptureDelay = _captureDelay; } // Set the capture time if (capture_time != 0) { captureFrame.SetRenderTime(capture_time); } else { captureFrame.SetRenderTime(TickTime::MillisecondTimestamp()); } if (captureFrame.RenderTimeMs() == last_capture_time_) { // We don't allow the same capture time for two frames, drop this one. return -1; } last_capture_time_ = captureFrame.RenderTimeMs(); if (_dataCallBack) { if (callOnCaptureDelayChanged) { _dataCallBack->OnCaptureDelayChanged(_id, _captureDelay); } _dataCallBack->OnIncomingCapturedEncodedFrame(_id, captureFrame, codecType); } return 0; } WebRtc_Word32 VideoCaptureImpl::IncomingFrame( WebRtc_UWord8* videoFrame, WebRtc_Word32 videoFrameLength, const VideoCaptureCapability& frameInfo, WebRtc_Word64 captureTime/*=0*/) { WEBRTC_TRACE(webrtc::kTraceStream, webrtc::kTraceVideoCapture, _id, "IncomingFrame width %d, height %d", (int) frameInfo.width, (int) frameInfo.height); TickTime startProcessTime = TickTime::Now(); CriticalSectionScoped cs(&_callBackCs); const WebRtc_Word32 width = frameInfo.width; const WebRtc_Word32 height = frameInfo.height; if (frameInfo.codecType == kVideoCodecUnknown) { // Not encoded, convert to I420. const VideoType commonVideoType = RawVideoTypeToCommonVideoVideoType(frameInfo.rawType); if (frameInfo.rawType != kVideoMJPEG && CalcBufferSize(commonVideoType, width, abs(height)) != videoFrameLength) { WEBRTC_TRACE(webrtc::kTraceError, webrtc::kTraceVideoCapture, _id, "Wrong incoming frame length."); return -1; } int stride_y = 0; int stride_uv = 0; int target_width = width; int target_height = height; // Rotating resolution when for 90/270 degree rotations. if (_rotateFrame == kRotate90 || _rotateFrame == kRotate270) { target_width = abs(height); target_height = width; } Calc16ByteAlignedStride(target_width, &stride_y, &stride_uv); // Setting absolute height (in case it was negative). // In Windows, the image starts bottom left, instead of top left. // Setting a negative source height, inverts the image (within LibYuv). int ret = _captureFrame.CreateEmptyFrame(target_width, abs(target_height), stride_y, stride_uv, stride_uv); if (ret < 0) { WEBRTC_TRACE(webrtc::kTraceError, webrtc::kTraceVideoCapture, _id, "Failed to allocate I420 frame."); return -1; } const int conversionResult = ConvertToI420(commonVideoType, videoFrame, 0, 0, // No cropping width, height, videoFrameLength, _rotateFrame, &_captureFrame); if (conversionResult < 0) { WEBRTC_TRACE(webrtc::kTraceError, webrtc::kTraceVideoCapture, _id, "Failed to convert capture frame from type %d to I420", frameInfo.rawType); return -1; } DeliverCapturedFrame(_captureFrame, captureTime); } else // Encoded format { if (_capture_encoded_frame.CopyFrame(videoFrameLength, videoFrame) != 0) { WEBRTC_TRACE(webrtc::kTraceError, webrtc::kTraceVideoCapture, _id, "Failed to copy captured frame of length %d", static_cast<int>(videoFrameLength)); } DeliverEncodedCapturedFrame(_capture_encoded_frame, captureTime, frameInfo.codecType); } const WebRtc_UWord32 processTime = (WebRtc_UWord32)(TickTime::Now() - startProcessTime).Milliseconds(); if (processTime > 10) // If the process time is too long MJPG will not work well. { WEBRTC_TRACE(webrtc::kTraceWarning, webrtc::kTraceVideoCapture, _id, "Too long processing time of Incoming frame: %ums", (unsigned int) processTime); } return 0; } WebRtc_Word32 VideoCaptureImpl::IncomingFrameI420( const VideoFrameI420& video_frame, WebRtc_Word64 captureTime) { CriticalSectionScoped cs(&_callBackCs); int size_y = video_frame.height * video_frame.y_pitch; int size_u = video_frame.u_pitch * ((video_frame.height + 1) / 2); int size_v = video_frame.v_pitch * ((video_frame.height + 1) / 2); // TODO(mikhal): Can we use Swap here? This will do a memcpy. int ret = _captureFrame.CreateFrame(size_y, video_frame.y_plane, size_u, video_frame.u_plane, size_v, video_frame.v_plane, video_frame.width, video_frame.height, video_frame.y_pitch, video_frame.u_pitch, video_frame.v_pitch); if (ret < 0) { WEBRTC_TRACE(webrtc::kTraceError, webrtc::kTraceVideoCapture, _id, "Failed to create I420VideoFrame"); return -1; } DeliverCapturedFrame(_captureFrame, captureTime); return 0; } WebRtc_Word32 VideoCaptureImpl::SetCaptureRotation(VideoCaptureRotation rotation) { CriticalSectionScoped cs(&_apiCs); CriticalSectionScoped cs2(&_callBackCs); switch (rotation){ case kCameraRotate0: _rotateFrame = kRotateNone; break; case kCameraRotate90: _rotateFrame = kRotate90; break; case kCameraRotate180: _rotateFrame = kRotate180; break; case kCameraRotate270: _rotateFrame = kRotate270; break; } return 0; } WebRtc_Word32 VideoCaptureImpl::EnableFrameRateCallback(const bool enable) { CriticalSectionScoped cs(&_apiCs); CriticalSectionScoped cs2(&_callBackCs); _frameRateCallBack = enable; if (enable) { _lastFrameRateCallbackTime = TickTime::Now(); } return 0; } WebRtc_Word32 VideoCaptureImpl::EnableNoPictureAlarm(const bool enable) { CriticalSectionScoped cs(&_apiCs); CriticalSectionScoped cs2(&_callBackCs); _noPictureAlarmCallBack = enable; return 0; } void VideoCaptureImpl::UpdateFrameCount() { if (_incomingFrameTimes[0].MicrosecondTimestamp() == 0) { // first no shift } else { // shift for (int i = (kFrameRateCountHistorySize - 2); i >= 0; i--) { _incomingFrameTimes[i + 1] = _incomingFrameTimes[i]; } } _incomingFrameTimes[0] = TickTime::Now(); } WebRtc_UWord32 VideoCaptureImpl::CalculateFrameRate(const TickTime& now) { WebRtc_Word32 num = 0; WebRtc_Word32 nrOfFrames = 0; for (num = 1; num < (kFrameRateCountHistorySize - 1); num++) { if (_incomingFrameTimes[num].Ticks() <= 0 || (now - _incomingFrameTimes[num]).Milliseconds() > kFrameRateHistoryWindowMs) // don't use data older than 2sec { break; } else { nrOfFrames++; } } if (num > 1) { WebRtc_Word64 diff = (now - _incomingFrameTimes[num - 1]).Milliseconds(); if (diff > 0) { return WebRtc_UWord32((nrOfFrames * 1000.0f / diff) + 0.5f); } } return nrOfFrames; } } // namespace videocapturemodule } // namespace webrtc <commit_msg>Setting capture stride to width<commit_after>/* * Copyright (c) 2012 The WebRTC project authors. All Rights Reserved. * * Use of this source code is governed by a BSD-style license * that can be found in the LICENSE file in the root of the source * tree. An additional intellectual property rights grant can be found * in the file PATENTS. All contributing project authors may * be found in the AUTHORS file in the root of the source tree. */ #include "video_capture_impl.h" #include "common_video/libyuv/include/webrtc_libyuv.h" #include "critical_section_wrapper.h" #include "module_common_types.h" #include "ref_count.h" #include "tick_util.h" #include "trace.h" #include "video_capture_config.h" #include <stdlib.h> namespace webrtc { namespace videocapturemodule { VideoCaptureModule* VideoCaptureImpl::Create( const WebRtc_Word32 id, VideoCaptureExternal*& externalCapture) { RefCountImpl<VideoCaptureImpl>* implementation = new RefCountImpl<VideoCaptureImpl>(id); externalCapture = implementation; return implementation; } const char* VideoCaptureImpl::CurrentDeviceName() const { return _deviceUniqueId; } WebRtc_Word32 VideoCaptureImpl::ChangeUniqueId(const WebRtc_Word32 id) { _id = id; return 0; } // returns the number of milliseconds until the module want a worker thread to call Process WebRtc_Word32 VideoCaptureImpl::TimeUntilNextProcess() { CriticalSectionScoped cs(&_callBackCs); WebRtc_Word32 timeToNormalProcess = kProcessInterval - (WebRtc_Word32)((TickTime::Now() - _lastProcessTime).Milliseconds()); return timeToNormalProcess; } // Process any pending tasks such as timeouts WebRtc_Word32 VideoCaptureImpl::Process() { CriticalSectionScoped cs(&_callBackCs); const TickTime now = TickTime::Now(); _lastProcessTime = TickTime::Now(); // Handle No picture alarm if (_lastProcessFrameCount.Ticks() == _incomingFrameTimes[0].Ticks() && _captureAlarm != Raised) { if (_noPictureAlarmCallBack && _captureCallBack) { _captureAlarm = Raised; _captureCallBack->OnNoPictureAlarm(_id, _captureAlarm); } } else if (_lastProcessFrameCount.Ticks() != _incomingFrameTimes[0].Ticks() && _captureAlarm != Cleared) { if (_noPictureAlarmCallBack && _captureCallBack) { _captureAlarm = Cleared; _captureCallBack->OnNoPictureAlarm(_id, _captureAlarm); } } // Handle frame rate callback if ((now - _lastFrameRateCallbackTime).Milliseconds() > kFrameRateCallbackInterval) { if (_frameRateCallBack && _captureCallBack) { const WebRtc_UWord32 frameRate = CalculateFrameRate(now); _captureCallBack->OnCaptureFrameRate(_id, frameRate); } _lastFrameRateCallbackTime = now; // Can be set by EnableFrameRateCallback } _lastProcessFrameCount = _incomingFrameTimes[0]; return 0; } VideoCaptureImpl::VideoCaptureImpl(const WebRtc_Word32 id) : _id(id), _deviceUniqueId(NULL), _apiCs(*CriticalSectionWrapper::CreateCriticalSection()), _captureDelay(0), _requestedCapability(), _callBackCs(*CriticalSectionWrapper::CreateCriticalSection()), _lastProcessTime(TickTime::Now()), _lastFrameRateCallbackTime(TickTime::Now()), _frameRateCallBack(false), _noPictureAlarmCallBack(false), _captureAlarm(Cleared), _setCaptureDelay(0), _dataCallBack(NULL), _captureCallBack(NULL), _lastProcessFrameCount(TickTime::Now()), _rotateFrame(kRotateNone), last_capture_time_(TickTime::MillisecondTimestamp()) { _requestedCapability.width = kDefaultWidth; _requestedCapability.height = kDefaultHeight; _requestedCapability.maxFPS = 30; _requestedCapability.rawType = kVideoI420; _requestedCapability.codecType = kVideoCodecUnknown; memset(_incomingFrameTimes, 0, sizeof(_incomingFrameTimes)); } VideoCaptureImpl::~VideoCaptureImpl() { DeRegisterCaptureDataCallback(); DeRegisterCaptureCallback(); delete &_callBackCs; delete &_apiCs; if (_deviceUniqueId) delete[] _deviceUniqueId; } WebRtc_Word32 VideoCaptureImpl::RegisterCaptureDataCallback( VideoCaptureDataCallback& dataCallBack) { CriticalSectionScoped cs(&_apiCs); CriticalSectionScoped cs2(&_callBackCs); _dataCallBack = &dataCallBack; return 0; } WebRtc_Word32 VideoCaptureImpl::DeRegisterCaptureDataCallback() { CriticalSectionScoped cs(&_apiCs); CriticalSectionScoped cs2(&_callBackCs); _dataCallBack = NULL; return 0; } WebRtc_Word32 VideoCaptureImpl::RegisterCaptureCallback(VideoCaptureFeedBack& callBack) { CriticalSectionScoped cs(&_apiCs); CriticalSectionScoped cs2(&_callBackCs); _captureCallBack = &callBack; return 0; } WebRtc_Word32 VideoCaptureImpl::DeRegisterCaptureCallback() { CriticalSectionScoped cs(&_apiCs); CriticalSectionScoped cs2(&_callBackCs); _captureCallBack = NULL; return 0; } WebRtc_Word32 VideoCaptureImpl::SetCaptureDelay(WebRtc_Word32 delayMS) { CriticalSectionScoped cs(&_apiCs); _captureDelay = delayMS; return 0; } WebRtc_Word32 VideoCaptureImpl::CaptureDelay() { CriticalSectionScoped cs(&_apiCs); return _setCaptureDelay; } WebRtc_Word32 VideoCaptureImpl::DeliverCapturedFrame(I420VideoFrame& captureFrame, WebRtc_Word64 capture_time) { UpdateFrameCount(); // frame count used for local frame rate callback. const bool callOnCaptureDelayChanged = _setCaptureDelay != _captureDelay; // Capture delay changed if (_setCaptureDelay != _captureDelay) { _setCaptureDelay = _captureDelay; } // Set the capture time if (capture_time != 0) { captureFrame.set_render_time_ms(capture_time); } else { captureFrame.set_render_time_ms(TickTime::MillisecondTimestamp()); } if (captureFrame.render_time_ms() == last_capture_time_) { // We don't allow the same capture time for two frames, drop this one. return -1; } last_capture_time_ = captureFrame.render_time_ms(); if (_dataCallBack) { if (callOnCaptureDelayChanged) { _dataCallBack->OnCaptureDelayChanged(_id, _captureDelay); } _dataCallBack->OnIncomingCapturedFrame(_id, captureFrame); } return 0; } WebRtc_Word32 VideoCaptureImpl::DeliverEncodedCapturedFrame( VideoFrame& captureFrame, WebRtc_Word64 capture_time, VideoCodecType codecType) { UpdateFrameCount(); // frame count used for local frame rate callback. const bool callOnCaptureDelayChanged = _setCaptureDelay != _captureDelay; // Capture delay changed if (_setCaptureDelay != _captureDelay) { _setCaptureDelay = _captureDelay; } // Set the capture time if (capture_time != 0) { captureFrame.SetRenderTime(capture_time); } else { captureFrame.SetRenderTime(TickTime::MillisecondTimestamp()); } if (captureFrame.RenderTimeMs() == last_capture_time_) { // We don't allow the same capture time for two frames, drop this one. return -1; } last_capture_time_ = captureFrame.RenderTimeMs(); if (_dataCallBack) { if (callOnCaptureDelayChanged) { _dataCallBack->OnCaptureDelayChanged(_id, _captureDelay); } _dataCallBack->OnIncomingCapturedEncodedFrame(_id, captureFrame, codecType); } return 0; } WebRtc_Word32 VideoCaptureImpl::IncomingFrame( WebRtc_UWord8* videoFrame, WebRtc_Word32 videoFrameLength, const VideoCaptureCapability& frameInfo, WebRtc_Word64 captureTime/*=0*/) { WEBRTC_TRACE(webrtc::kTraceStream, webrtc::kTraceVideoCapture, _id, "IncomingFrame width %d, height %d", (int) frameInfo.width, (int) frameInfo.height); TickTime startProcessTime = TickTime::Now(); CriticalSectionScoped cs(&_callBackCs); const WebRtc_Word32 width = frameInfo.width; const WebRtc_Word32 height = frameInfo.height; if (frameInfo.codecType == kVideoCodecUnknown) { // Not encoded, convert to I420. const VideoType commonVideoType = RawVideoTypeToCommonVideoVideoType(frameInfo.rawType); if (frameInfo.rawType != kVideoMJPEG && CalcBufferSize(commonVideoType, width, abs(height)) != videoFrameLength) { WEBRTC_TRACE(webrtc::kTraceError, webrtc::kTraceVideoCapture, _id, "Wrong incoming frame length."); return -1; } int stride_y = width; int stride_uv = (width + 1) / 2; int target_width = width; int target_height = height; // Rotating resolution when for 90/270 degree rotations. if (_rotateFrame == kRotate90 || _rotateFrame == kRotate270) { target_width = abs(height); target_height = width; } // TODO(mikhal): Update correct aligned stride values. //Calc16ByteAlignedStride(target_width, &stride_y, &stride_uv); // Setting absolute height (in case it was negative). // In Windows, the image starts bottom left, instead of top left. // Setting a negative source height, inverts the image (within LibYuv). int ret = _captureFrame.CreateEmptyFrame(target_width, abs(target_height), stride_y, stride_uv, stride_uv); if (ret < 0) { WEBRTC_TRACE(webrtc::kTraceError, webrtc::kTraceVideoCapture, _id, "Failed to allocate I420 frame."); return -1; } const int conversionResult = ConvertToI420(commonVideoType, videoFrame, 0, 0, // No cropping width, height, videoFrameLength, _rotateFrame, &_captureFrame); if (conversionResult < 0) { WEBRTC_TRACE(webrtc::kTraceError, webrtc::kTraceVideoCapture, _id, "Failed to convert capture frame from type %d to I420", frameInfo.rawType); return -1; } DeliverCapturedFrame(_captureFrame, captureTime); } else // Encoded format { if (_capture_encoded_frame.CopyFrame(videoFrameLength, videoFrame) != 0) { WEBRTC_TRACE(webrtc::kTraceError, webrtc::kTraceVideoCapture, _id, "Failed to copy captured frame of length %d", static_cast<int>(videoFrameLength)); } DeliverEncodedCapturedFrame(_capture_encoded_frame, captureTime, frameInfo.codecType); } const WebRtc_UWord32 processTime = (WebRtc_UWord32)(TickTime::Now() - startProcessTime).Milliseconds(); if (processTime > 10) // If the process time is too long MJPG will not work well. { WEBRTC_TRACE(webrtc::kTraceWarning, webrtc::kTraceVideoCapture, _id, "Too long processing time of Incoming frame: %ums", (unsigned int) processTime); } return 0; } WebRtc_Word32 VideoCaptureImpl::IncomingFrameI420( const VideoFrameI420& video_frame, WebRtc_Word64 captureTime) { CriticalSectionScoped cs(&_callBackCs); int size_y = video_frame.height * video_frame.y_pitch; int size_u = video_frame.u_pitch * ((video_frame.height + 1) / 2); int size_v = video_frame.v_pitch * ((video_frame.height + 1) / 2); // TODO(mikhal): Can we use Swap here? This will do a memcpy. int ret = _captureFrame.CreateFrame(size_y, video_frame.y_plane, size_u, video_frame.u_plane, size_v, video_frame.v_plane, video_frame.width, video_frame.height, video_frame.y_pitch, video_frame.u_pitch, video_frame.v_pitch); if (ret < 0) { WEBRTC_TRACE(webrtc::kTraceError, webrtc::kTraceVideoCapture, _id, "Failed to create I420VideoFrame"); return -1; } DeliverCapturedFrame(_captureFrame, captureTime); return 0; } WebRtc_Word32 VideoCaptureImpl::SetCaptureRotation(VideoCaptureRotation rotation) { CriticalSectionScoped cs(&_apiCs); CriticalSectionScoped cs2(&_callBackCs); switch (rotation){ case kCameraRotate0: _rotateFrame = kRotateNone; break; case kCameraRotate90: _rotateFrame = kRotate90; break; case kCameraRotate180: _rotateFrame = kRotate180; break; case kCameraRotate270: _rotateFrame = kRotate270; break; } return 0; } WebRtc_Word32 VideoCaptureImpl::EnableFrameRateCallback(const bool enable) { CriticalSectionScoped cs(&_apiCs); CriticalSectionScoped cs2(&_callBackCs); _frameRateCallBack = enable; if (enable) { _lastFrameRateCallbackTime = TickTime::Now(); } return 0; } WebRtc_Word32 VideoCaptureImpl::EnableNoPictureAlarm(const bool enable) { CriticalSectionScoped cs(&_apiCs); CriticalSectionScoped cs2(&_callBackCs); _noPictureAlarmCallBack = enable; return 0; } void VideoCaptureImpl::UpdateFrameCount() { if (_incomingFrameTimes[0].MicrosecondTimestamp() == 0) { // first no shift } else { // shift for (int i = (kFrameRateCountHistorySize - 2); i >= 0; i--) { _incomingFrameTimes[i + 1] = _incomingFrameTimes[i]; } } _incomingFrameTimes[0] = TickTime::Now(); } WebRtc_UWord32 VideoCaptureImpl::CalculateFrameRate(const TickTime& now) { WebRtc_Word32 num = 0; WebRtc_Word32 nrOfFrames = 0; for (num = 1; num < (kFrameRateCountHistorySize - 1); num++) { if (_incomingFrameTimes[num].Ticks() <= 0 || (now - _incomingFrameTimes[num]).Milliseconds() > kFrameRateHistoryWindowMs) // don't use data older than 2sec { break; } else { nrOfFrames++; } } if (num > 1) { WebRtc_Word64 diff = (now - _incomingFrameTimes[num - 1]).Milliseconds(); if (diff > 0) { return WebRtc_UWord32((nrOfFrames * 1000.0f / diff) + 0.5f); } } return nrOfFrames; } } // namespace videocapturemodule } // namespace webrtc <|endoftext|>
<commit_before>/************************************************************************* * * OpenOffice.org - a multi-platform office productivity suite * * $RCSfile: communi.hxx,v $ * * $Revision: 1.2 $ * * last change: $Author: vg $ $Date: 2007-04-11 18:20:35 $ * * The Contents of this file are made available subject to * the terms of GNU Lesser General Public License Version 2.1. * * * GNU Lesser General Public License Version 2.1 * ============================================= * Copyright 2005 by Sun Microsystems, Inc. * 901 San Antonio Road, Palo Alto, CA 94303, USA * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License version 2.1, as published by the Free Software Foundation. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, * MA 02111-1307 USA * ************************************************************************/ #ifndef _COMMUNI_HXX #define _COMMUNI_HXX #ifndef _SVARRAY_HXX //autogen #include <svtools/svarray.hxx> #endif #ifndef _VOS_THREAD_HXX_ //autogen #include <vos/thread.hxx> #endif #ifndef _VOS_MUTEX_HXX_ //autogen #include <vos/mutex.hxx> #endif #ifndef _SV_TIMER_HXX #include <vcl/timer.hxx> #endif #ifndef _SIMPLECM_HXX #include <automation/simplecm.hxx> #endif class SvStream; class SvMemoryStream; //class Application; class CommunicationManagerServerAcceptThread; SV_DECL_PTRARR_SORT( CommunicationLinkList, CommunicationLink*, 1, 10 ) class MultiCommunicationManager : public CommunicationManager { public: MultiCommunicationManager( BOOL bUseMultiChannel = FALSE ); virtual ~MultiCommunicationManager(); virtual BOOL StopCommunication(); // Hlt alle CommunicationLinks an virtual BOOL IsLinkValid( CommunicationLink* pCL ); virtual USHORT GetCommunicationLinkCount(); virtual CommunicationLinkRef GetCommunicationLink( USHORT nNr ); protected: virtual void CallConnectionOpened( CommunicationLink* pCL ); virtual void CallConnectionClosed( CommunicationLink* pCL ); CommunicationLinkList *ActiveLinks; CommunicationLinkList *InactiveLinks; /// Hier sind die CommunicationLinks drin, die sich noch nicht selbst abgemeldet haben. /// allerdings schon ein StopCommunication gekriegt haben, bzw ein ConnectionTerminated virtual void DestroyingLink( CommunicationLink *pCL ); // Link trgt sich im Destruktor aus }; class CommunicationManagerServer : public MultiCommunicationManager { public: CommunicationManagerServer( BOOL bUseMultiChannel = FALSE ):MultiCommunicationManager( bUseMultiChannel ){;} }; class CommunicationManagerClient : public MultiCommunicationManager, public ICommunicationManagerClient { public: CommunicationManagerClient( BOOL bUseMultiChannel = FALSE ); }; class CommunicationLinkViaSocket : public SimpleCommunicationLinkViaSocket, public NAMESPACE_VOS(OThread) { public: CommunicationLinkViaSocket( CommunicationManager *pMan, NAMESPACE_VOS(OStreamSocket) *pSocket ); virtual ~CommunicationLinkViaSocket(); virtual BOOL IsCommunicationError(); virtual BOOL DoTransferDataStream( SvStream *pDataStream, CMProtocol nProtocol = CM_PROTOCOL_OLDSTYLE ); // Diese sind Virtuelle Links!!!! virtual long ConnectionClosed( void* = NULL ); virtual long DataReceived( void* = NULL ); virtual BOOL StopCommunication(); void SetPutDataReceivedHdl( Link lPutDataReceived ){ mlPutDataReceived = lPutDataReceived; } Link GetDataReceivedLink () {Link aLink = LINK( this, CommunicationLinkViaSocket, DataReceived ); return aLink;} DECL_LINK( PutDataReceivedHdl, CommunicationLinkViaSocket* ); protected: virtual void SAL_CALL run(); virtual BOOL ShutdownCommunication(); ULONG nConnectionClosedEventId; ULONG nDataReceivedEventId; NAMESPACE_VOS(OMutex) aMConnectionClosed; // Notwendig, da Event verarbeitet werden kann bevor Variable gesetzt ist NAMESPACE_VOS(OMutex) aMDataReceived; // Notwendig, da Event verarbeitet werden kann bevor Variable gesetzt ist virtual void WaitForShutdown(); DECL_LINK( ShutdownLink, void* ); Timer aShutdownTimer; BOOL bShutdownStarted; BOOL bDestroying; Link mlPutDataReceived; }; class CommunicationManagerServerViaSocket : public CommunicationManagerServer { friend class CommunicationManagerServerAcceptThread; public: using CommunicationManager::StartCommunication; CommunicationManagerServerViaSocket( ULONG nPort, USHORT nMaxCon, BOOL bUseMultiChannel = FALSE ); virtual ~CommunicationManagerServerViaSocket(); virtual BOOL StartCommunication(); virtual BOOL StopCommunication(); protected: ULONG nPortToListen; USHORT nMaxConnections; private: CommunicationManagerServerAcceptThread *pAcceptThread; void AddConnection( CommunicationLink *pNewConnection ); }; class CommunicationManagerServerAcceptThread: public NAMESPACE_VOS(OThread) { public: CommunicationManagerServerAcceptThread( CommunicationManagerServerViaSocket* pServer, ULONG nPort, USHORT nMaxCon = CM_UNLIMITED_CONNECTIONS ); virtual ~CommunicationManagerServerAcceptThread(); CommunicationLinkRef GetNewConnection(){ CommunicationLinkRef xTemp = xmNewConnection; xmNewConnection.Clear(); return xTemp; } protected: virtual void SAL_CALL run(); private: CommunicationManagerServerViaSocket* pMyServer; NAMESPACE_VOS(OAcceptorSocket) *pAcceptorSocket; ULONG nPortToListen; USHORT nMaxConnections; ULONG nAddConnectionEventId; NAMESPACE_VOS(OMutex) aMAddConnection; // Notwendig, da Event verarbeitet werden kann bevor Variable gesetzt ist void CallInfoMsg( InfoString aMsg ){ pMyServer->CallInfoMsg( aMsg ); } CM_InfoType GetInfoType(){ return pMyServer->GetInfoType(); } // Diese beiden werden zum Transport der Connection vom Thread zum Mainthread verwendet. CommunicationLinkRef xmNewConnection; DECL_LINK( AddConnection, void* ); }; class CommunicationManagerClientViaSocket : public CommunicationManagerClient, CommonSocketFunctions { public: using CommunicationManager::StartCommunication; CommunicationManagerClientViaSocket( ByteString aHost, ULONG nPort, BOOL bUseMultiChannel = FALSE ); CommunicationManagerClientViaSocket( BOOL bUseMultiChannel = FALSE ); virtual ~CommunicationManagerClientViaSocket(); virtual BOOL StartCommunication(){ return StartCommunication( aHostToTalk, nPortToTalk );} virtual BOOL StartCommunication( ByteString aHost, ULONG nPort ){ return DoStartCommunication( this, (ICommunicationManagerClient*) this, aHost, nPort );} private: ByteString aHostToTalk; ULONG nPortToTalk; protected: virtual CommunicationLink *CreateCommunicationLink( CommunicationManager *pCM, NAMESPACE_VOS(OConnectorSocket) *pCS ){ return new CommunicationLinkViaSocket( pCM, pCS ); } }; #endif <commit_msg>INTEGRATION: CWS gurke (1.2.10); FILE MERGED 2007/07/20 08:03:32 gh 1.2.10.1: #148724#testtool communication crashes on shutdown in Timer::Timeout<commit_after>/************************************************************************* * * OpenOffice.org - a multi-platform office productivity suite * * $RCSfile: communi.hxx,v $ * * $Revision: 1.3 $ * * last change: $Author: rt $ $Date: 2007-07-24 11:28:49 $ * * 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 _COMMUNI_HXX #define _COMMUNI_HXX #ifndef _SVARRAY_HXX //autogen #include <svtools/svarray.hxx> #endif #ifndef _VOS_THREAD_HXX_ //autogen #include <vos/thread.hxx> #endif #ifndef _VOS_MUTEX_HXX_ //autogen #include <vos/mutex.hxx> #endif #ifndef _SV_TIMER_HXX #include <vcl/timer.hxx> #endif #ifndef _SIMPLECM_HXX #include <automation/simplecm.hxx> #endif class SvStream; class SvMemoryStream; //class Application; class CommunicationManagerServerAcceptThread; SV_DECL_PTRARR_SORT( CommunicationLinkList, CommunicationLink*, 1, 10 ) class MultiCommunicationManager : public CommunicationManager { public: MultiCommunicationManager( BOOL bUseMultiChannel = FALSE ); virtual ~MultiCommunicationManager(); virtual BOOL StopCommunication(); // Hlt alle CommunicationLinks an virtual BOOL IsLinkValid( CommunicationLink* pCL ); virtual USHORT GetCommunicationLinkCount(); virtual CommunicationLinkRef GetCommunicationLink( USHORT nNr ); void DoQuickShutdown( BOOL bQuickShutdown = TRUE) { bGracefullShutdown = !bQuickShutdown; } protected: virtual void CallConnectionOpened( CommunicationLink* pCL ); virtual void CallConnectionClosed( CommunicationLink* pCL ); CommunicationLinkList *ActiveLinks; CommunicationLinkList *InactiveLinks; /// Hier sind die CommunicationLinks drin, die sich noch nicht selbst abgemeldet haben. /// allerdings schon ein StopCommunication gekriegt haben, bzw ein ConnectionTerminated virtual void DestroyingLink( CommunicationLink *pCL ); // Link trgt sich im Destruktor aus BOOL bGracefullShutdown; }; class CommunicationManagerServer : public MultiCommunicationManager { public: CommunicationManagerServer( BOOL bUseMultiChannel = FALSE ):MultiCommunicationManager( bUseMultiChannel ){;} }; class CommunicationManagerClient : public MultiCommunicationManager, public ICommunicationManagerClient { public: CommunicationManagerClient( BOOL bUseMultiChannel = FALSE ); }; class CommunicationLinkViaSocket : public SimpleCommunicationLinkViaSocket, public NAMESPACE_VOS(OThread) { public: CommunicationLinkViaSocket( CommunicationManager *pMan, NAMESPACE_VOS(OStreamSocket) *pSocket ); virtual ~CommunicationLinkViaSocket(); virtual BOOL IsCommunicationError(); virtual BOOL DoTransferDataStream( SvStream *pDataStream, CMProtocol nProtocol = CM_PROTOCOL_OLDSTYLE ); // Diese sind Virtuelle Links!!!! virtual long ConnectionClosed( void* = NULL ); virtual long DataReceived( void* = NULL ); virtual BOOL StopCommunication(); void SetPutDataReceivedHdl( Link lPutDataReceived ){ mlPutDataReceived = lPutDataReceived; } Link GetDataReceivedLink () {Link aLink = LINK( this, CommunicationLinkViaSocket, DataReceived ); return aLink;} DECL_LINK( PutDataReceivedHdl, CommunicationLinkViaSocket* ); protected: virtual void SAL_CALL run(); virtual BOOL ShutdownCommunication(); ULONG nConnectionClosedEventId; ULONG nDataReceivedEventId; NAMESPACE_VOS(OMutex) aMConnectionClosed; // Notwendig, da Event verarbeitet werden kann bevor Variable gesetzt ist NAMESPACE_VOS(OMutex) aMDataReceived; // Notwendig, da Event verarbeitet werden kann bevor Variable gesetzt ist virtual void WaitForShutdown(); DECL_LINK( ShutdownLink, void* ); Timer aShutdownTimer; BOOL bShutdownStarted; BOOL bDestroying; Link mlPutDataReceived; }; class CommunicationManagerServerViaSocket : public CommunicationManagerServer { friend class CommunicationManagerServerAcceptThread; public: using CommunicationManager::StartCommunication; CommunicationManagerServerViaSocket( ULONG nPort, USHORT nMaxCon, BOOL bUseMultiChannel = FALSE ); virtual ~CommunicationManagerServerViaSocket(); virtual BOOL StartCommunication(); virtual BOOL StopCommunication(); protected: ULONG nPortToListen; USHORT nMaxConnections; private: CommunicationManagerServerAcceptThread *pAcceptThread; void AddConnection( CommunicationLink *pNewConnection ); }; class CommunicationManagerServerAcceptThread: public NAMESPACE_VOS(OThread) { public: CommunicationManagerServerAcceptThread( CommunicationManagerServerViaSocket* pServer, ULONG nPort, USHORT nMaxCon = CM_UNLIMITED_CONNECTIONS ); virtual ~CommunicationManagerServerAcceptThread(); CommunicationLinkRef GetNewConnection(){ CommunicationLinkRef xTemp = xmNewConnection; xmNewConnection.Clear(); return xTemp; } protected: virtual void SAL_CALL run(); private: CommunicationManagerServerViaSocket* pMyServer; NAMESPACE_VOS(OAcceptorSocket) *pAcceptorSocket; ULONG nPortToListen; USHORT nMaxConnections; ULONG nAddConnectionEventId; NAMESPACE_VOS(OMutex) aMAddConnection; // Notwendig, da Event verarbeitet werden kann bevor Variable gesetzt ist void CallInfoMsg( InfoString aMsg ){ pMyServer->CallInfoMsg( aMsg ); } CM_InfoType GetInfoType(){ return pMyServer->GetInfoType(); } // Diese beiden werden zum Transport der Connection vom Thread zum Mainthread verwendet. CommunicationLinkRef xmNewConnection; DECL_LINK( AddConnection, void* ); }; class CommunicationManagerClientViaSocket : public CommunicationManagerClient, CommonSocketFunctions { public: using CommunicationManager::StartCommunication; CommunicationManagerClientViaSocket( ByteString aHost, ULONG nPort, BOOL bUseMultiChannel = FALSE ); CommunicationManagerClientViaSocket( BOOL bUseMultiChannel = FALSE ); virtual ~CommunicationManagerClientViaSocket(); virtual BOOL StartCommunication(){ return StartCommunication( aHostToTalk, nPortToTalk );} virtual BOOL StartCommunication( ByteString aHost, ULONG nPort ){ return DoStartCommunication( this, (ICommunicationManagerClient*) this, aHost, nPort );} private: ByteString aHostToTalk; ULONG nPortToTalk; protected: virtual CommunicationLink *CreateCommunicationLink( CommunicationManager *pCM, NAMESPACE_VOS(OConnectorSocket) *pCS ){ return new CommunicationLinkViaSocket( pCM, pCS ); } }; #endif <|endoftext|>
<commit_before>/*=================================================================== The Medical Imaging Interaction Toolkit (MITK) Copyright (c) German Cancer Research Center, Division of Medical and Biological Informatics. All rights reserved. This software is distributed WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See LICENSE.txt or http://www.mitk.org for details. ===================================================================*/ #include "mitkSurface.h" #include "mitkSurfaceToSurfaceFilter.h" #include "mitkCommon.h" #include "mitkNumericTypes.h" #include "vtkPolyData.h" #include "vtkSphereSource.h" #include <fstream> int mitkSurfaceToSurfaceFilterTest(int /*argc*/, char* /*argv*/[]) { mitk::Surface::Pointer surface; surface = mitk::Surface::New(); vtkSphereSource* sphereSource = vtkSphereSource::New(); sphereSource->SetCenter(0,0,0); sphereSource->SetRadius(5.0); sphereSource->SetThetaResolution(10); sphereSource->SetPhiResolution(10); sphereSource->Update(); vtkPolyData* polys = sphereSource->GetOutput(); surface->SetVtkPolyData( polys ); sphereSource->Delete(); mitk::SurfaceToSurfaceFilter::Pointer filter = mitk::SurfaceToSurfaceFilter::New(); std::cout << "Testing mitk::SurfaceToSurfaceFilter::SetInput() and ::GetNumberOfInputs() : " ; filter->SetInput( surface ); if ( filter->GetNumberOfInputs() < 1 ) { std::cout<<"[FAILED] : zero inputs set "<<std::endl; return EXIT_FAILURE; } std::cout << "Testing if GetInput returns the right Input : " << std::endl; if ( filter->GetInput() != surface ) { std::cout<<"[FAILED] : GetInput does not return correct input. "<<std::endl; return EXIT_FAILURE; } std::cout << "[SUCCESS] : input correct" << std::endl; if ( filter->GetInput(5) != NULL ) { std::cout<<"[FAILED] : GetInput returns inputs that were not set. "<<std::endl; return EXIT_FAILURE; } std::cout << "[SUCCESS] : Input nr.5 was not set -> is NULL" << std::endl; std::cout << "Testing whether Output is created correctly : " << std::endl; if ( filter->GetNumberOfOutputs() != filter->GetNumberOfInputs() ) { std::cout <<"[FAILED] : number of outputs != number of inputs" << std::endl; return EXIT_FAILURE; } std::cout << "[SUCCESS] : number of inputs == number of outputs." << std::endl; mitk::Surface::Pointer outputSurface = filter->GetOutput(); if ( outputSurface->GetVtkPolyData()->GetNumberOfPolys() != surface->GetVtkPolyData()->GetNumberOfPolys() ) { std::cout << "[FAILED] : number of Polys in PolyData of output != number of Polys in PolyData of input" << std::endl; return EXIT_FAILURE; } std::cout << "[SUCCESS] : number of Polys in PolyData of input and output are identical." << std::endl; filter->Update(); outputSurface = filter->GetOutput(); if ( outputSurface->GetSizeOfPolyDataSeries() != surface->GetSizeOfPolyDataSeries() ) { std::cout << "[FAILED] : number of PolyDatas in PolyDataSeries of output != number of PolyDatas of input" << std::endl; return EXIT_FAILURE; } std::cout << "[SUCCESS] : Size of PolyDataSeries of input and output are identical." << std::endl; //std::cout << "Testing RemoveInputs() : " << std::endl; //unsigned int numOfInputs = filter->GetNumberOfInputs(); //filter->RemoveInputs( mitk::Surface::New() ); //if ( filter->GetNumberOfInputs() != numOfInputs ) //{ // std::cout << "[FAILED] : input was removed that was not set." << std::endl; // return EXIT_FAILURE; //} //std::cout << "[SUCCESS] : no input was removed that was not set." << std::endl; //filter->RemoveInputs( surface ); //if ( filter->GetNumberOfInputs() != 0 ) //{ // std::cout << "[FAILED] : existing input was not removed correctly." << std::endl; // return EXIT_FAILURE; //} //std::cout << "[SUCCESS] : existing input was removed correctly." << std::endl; std::cout<<"[TEST DONE]"<<std::endl; return EXIT_SUCCESS; } <commit_msg>Enhanced test for SurfaceToSurfaceFilter<commit_after>/*=================================================================== The Medical Imaging Interaction Toolkit (MITK) Copyright (c) German Cancer Research Center, Division of Medical and Biological Informatics. All rights reserved. This software is distributed WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See LICENSE.txt or http://www.mitk.org for details. ===================================================================*/ #include "mitkSurface.h" #include "mitkSurfaceToSurfaceFilter.h" #include "mitkCommon.h" #include "mitkNumericTypes.h" #include "mitkTestingMacros.h" #include "vtkPolyData.h" #include "vtkSphereSource.h" int mitkSurfaceToSurfaceFilterTest(int /*argc*/, char* /*argv*/[]) { mitk::Surface::Pointer surface; surface = mitk::Surface::New(); vtkSphereSource* sphereSource = vtkSphereSource::New(); sphereSource->SetCenter(0,0,0); sphereSource->SetRadius(5.0); sphereSource->SetThetaResolution(10); sphereSource->SetPhiResolution(10); sphereSource->Update(); vtkPolyData* polys = sphereSource->GetOutput(); surface->SetVtkPolyData( polys ); sphereSource->Delete(); mitk::SurfaceToSurfaceFilter::Pointer filter = mitk::SurfaceToSurfaceFilter::New(); MITK_TEST_OUTPUT(<<"Testing mitk::SurfaceToSurfaceFilter::SetInput() and ::GetNumberOfInputs() : "); filter->SetInput( surface ); MITK_TEST_CONDITION(filter->GetNumberOfInputs() == 1, "Number of inputs must be 1" ); MITK_TEST_OUTPUT(<<"Testing if GetInput returns the right Input : "); mitk::Surface::Pointer input = const_cast<mitk::Surface*>(filter->GetInput()); MITK_ASSERT_EQUAL(input, surface, "GetInput() should return correct input. "); MITK_TEST_CONDITION(filter->GetInput(5) == NULL, "GetInput(5) should return NULL. "); MITK_TEST_OUTPUT(<<"Testing whether Output is created correctly : "); MITK_TEST_CONDITION(filter->GetNumberOfOutputs() == filter->GetNumberOfInputs(), "Test if number of outputs == number of inputs"); mitk::Surface::Pointer outputSurface = filter->GetOutput(); MITK_ASSERT_EQUAL(outputSurface, surface, "Test if output == input"); filter->Update(); outputSurface = filter->GetOutput(); MITK_TEST_CONDITION(outputSurface->GetSizeOfPolyDataSeries() == surface->GetSizeOfPolyDataSeries(), "Test if number of PolyDatas in PolyDataSeries of output == number of PolyDatas of input"); mitk::SurfaceToSurfaceFilter::Pointer s2sFilter = mitk::SurfaceToSurfaceFilter::New(); MITK_TEST_FOR_EXCEPTION(mitk::Exception, s2sFilter->CreateOutputForInput(500)); std::vector<vtkPolyData*> polydatas; for (unsigned int i = 0; i < 5; ++i) { sphereSource = vtkSphereSource::New(); sphereSource->SetCenter(0,i,0); sphereSource->SetRadius(5.0 + i); sphereSource->SetThetaResolution(10); sphereSource->SetPhiResolution(10); sphereSource->Update(); vtkPolyData* poly = sphereSource->GetOutput(); mitk::Surface::Pointer s = mitk::Surface::New(); s->SetVtkPolyData( poly ); s2sFilter->SetInput(i, s); polydatas.push_back(s2sFilter->GetOutput(i)->GetVtkPolyData()); sphereSource->Delete(); } // Test if the outputs are not recreated each time another input is added for (unsigned int i = 0; i < 5; ++i) { MITK_TEST_CONDITION(s2sFilter->GetOutput(i)->GetVtkPolyData() == polydatas.at(i), "Test if pointers are still equal"); } // Test if the outputs are recreated after calling CreateOutputsForAllInputs() s2sFilter->CreateOutputsForAllInputs(); for (unsigned int i = 0; i < 5; ++i) { MITK_TEST_CONDITION(s2sFilter->GetOutput(i)->GetVtkPolyData() != polydatas.at(i), "Test if pointers are not equal"); } //std::cout << "Testing RemoveInputs() : " << std::endl; //unsigned int numOfInputs = filter->GetNumberOfInputs(); //filter->RemoveInputs( mitk::Surface::New() ); //if ( filter->GetNumberOfInputs() != numOfInputs ) //{ // std::cout << "[FAILED] : input was removed that was not set." << std::endl; // return EXIT_FAILURE; //} //std::cout << "[SUCCESS] : no input was removed that was not set." << std::endl; //filter->RemoveInputs( surface ); //if ( filter->GetNumberOfInputs() != 0 ) //{ // std::cout << "[FAILED] : existing input was not removed correctly." << std::endl; // return EXIT_FAILURE; //} //std::cout << "[SUCCESS] : existing input was removed correctly." << std::endl; return EXIT_SUCCESS; } <|endoftext|>
<commit_before>// Copyright (c) 2019 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 <amount.h> #include <arith_uint256.h> #include <compressor.h> #include <consensus/merkle.h> #include <core_io.h> #include <crypto/common.h> #include <crypto/siphash.h> #include <key_io.h> #include <memusage.h> #include <netbase.h> #include <policy/settings.h> #include <pow.h> #include <pubkey.h> #include <rpc/util.h> #include <script/signingprovider.h> #include <script/standard.h> #include <serialize.h> #include <streams.h> #include <test/fuzz/FuzzedDataProvider.h> #include <test/fuzz/fuzz.h> #include <uint256.h> #include <util/moneystr.h> #include <util/strencodings.h> #include <util/system.h> #include <util/time.h> #include <version.h> #include <cassert> #include <limits> #include <vector> void initialize() { SelectParams(CBaseChainParams::REGTEST); } void test_one_input(const std::vector<uint8_t>& buffer) { if (buffer.size() < sizeof(uint256) + sizeof(uint160)) { return; } FuzzedDataProvider fuzzed_data_provider(buffer.data(), buffer.size()); const uint256 u256(fuzzed_data_provider.ConsumeBytes<unsigned char>(sizeof(uint256))); const uint160 u160(fuzzed_data_provider.ConsumeBytes<unsigned char>(sizeof(uint160))); const uint64_t u64 = fuzzed_data_provider.ConsumeIntegral<uint64_t>(); const int64_t i64 = fuzzed_data_provider.ConsumeIntegral<int64_t>(); const uint32_t u32 = fuzzed_data_provider.ConsumeIntegral<uint32_t>(); const int32_t i32 = fuzzed_data_provider.ConsumeIntegral<int32_t>(); const uint16_t u16 = fuzzed_data_provider.ConsumeIntegral<uint16_t>(); const int16_t i16 = fuzzed_data_provider.ConsumeIntegral<int16_t>(); const uint8_t u8 = fuzzed_data_provider.ConsumeIntegral<uint8_t>(); const int8_t i8 = fuzzed_data_provider.ConsumeIntegral<int8_t>(); // We cannot assume a specific value of std::is_signed<char>::value: // ConsumeIntegral<char>() instead of casting from {u,}int8_t. const char ch = fuzzed_data_provider.ConsumeIntegral<char>(); const bool b = fuzzed_data_provider.ConsumeBool(); const Consensus::Params& consensus_params = Params().GetConsensus(); (void)CheckProofOfWork(u256, u32, consensus_params); if (u64 <= MAX_MONEY) { const uint64_t compressed_money_amount = CompressAmount(u64); assert(u64 == DecompressAmount(compressed_money_amount)); static const uint64_t compressed_money_amount_max = CompressAmount(MAX_MONEY - 1); assert(compressed_money_amount <= compressed_money_amount_max); } else { (void)CompressAmount(u64); } static const uint256 u256_min(uint256S("0000000000000000000000000000000000000000000000000000000000000000")); static const uint256 u256_max(uint256S("ffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff")); const std::vector<uint256> v256{u256, u256_min, u256_max}; (void)ComputeMerkleRoot(v256); (void)CountBits(u64); (void)DecompressAmount(u64); (void)FormatISO8601Date(i64); (void)FormatISO8601DateTime(i64); // FormatMoney(i) not defined when i == std::numeric_limits<int64_t>::min() if (i64 != std::numeric_limits<int64_t>::min()) { int64_t parsed_money; if (ParseMoney(FormatMoney(i64), parsed_money)) { assert(parsed_money == i64); } } (void)GetSizeOfCompactSize(u64); (void)GetSpecialScriptSize(u32); // (void)GetVirtualTransactionSize(i64, i64); // function defined only for a subset of int64_t inputs // (void)GetVirtualTransactionSize(i64, i64, u32); // function defined only for a subset of int64_t/uint32_t inputs (void)HexDigit(ch); (void)MoneyRange(i64); (void)i64tostr(i64); (void)IsDigit(ch); (void)IsSpace(ch); (void)IsSwitchChar(ch); (void)itostr(i32); (void)memusage::DynamicUsage(ch); (void)memusage::DynamicUsage(i16); (void)memusage::DynamicUsage(i32); (void)memusage::DynamicUsage(i64); (void)memusage::DynamicUsage(i8); (void)memusage::DynamicUsage(u16); (void)memusage::DynamicUsage(u32); (void)memusage::DynamicUsage(u64); (void)memusage::DynamicUsage(u8); const unsigned char uch = static_cast<unsigned char>(u8); (void)memusage::DynamicUsage(uch); (void)MillisToTimeval(i64); const double d = ser_uint64_to_double(u64); assert(ser_double_to_uint64(d) == u64); const float f = ser_uint32_to_float(u32); assert(ser_float_to_uint32(f) == u32); (void)SighashToStr(uch); (void)SipHashUint256(u64, u64, u256); (void)SipHashUint256Extra(u64, u64, u256, u32); (void)ToLower(ch); (void)ToUpper(ch); // ValueFromAmount(i) not defined when i == std::numeric_limits<int64_t>::min() if (i64 != std::numeric_limits<int64_t>::min()) { int64_t parsed_money; if (ParseMoney(ValueFromAmount(i64).getValStr(), parsed_money)) { assert(parsed_money == i64); } } const arith_uint256 au256 = UintToArith256(u256); assert(ArithToUint256(au256) == u256); assert(uint256S(au256.GetHex()) == u256); (void)au256.bits(); (void)au256.GetCompact(/* fNegative= */ false); (void)au256.GetCompact(/* fNegative= */ true); (void)au256.getdouble(); (void)au256.GetHex(); (void)au256.GetLow64(); (void)au256.size(); (void)au256.ToString(); const CKeyID key_id{u160}; const CScriptID script_id{u160}; // CTxDestination = CNoDestination ∪ PKHash ∪ ScriptHash ∪ WitnessV0ScriptHash ∪ WitnessV0KeyHash ∪ WitnessUnknown const PKHash pk_hash{u160}; const ScriptHash script_hash{u160}; const WitnessV0KeyHash witness_v0_key_hash{u160}; const WitnessV0ScriptHash witness_v0_script_hash{u256}; const std::vector<CTxDestination> destinations{pk_hash, script_hash, witness_v0_key_hash, witness_v0_script_hash}; const SigningProvider store; for (const CTxDestination& destination : destinations) { (void)DescribeAddress(destination); (void)EncodeDestination(destination); (void)GetKeyForDestination(store, destination); (void)GetScriptForDestination(destination); (void)IsValidDestination(destination); } { CDataStream stream(SER_NETWORK, INIT_PROTO_VERSION); uint256 deserialized_u256; stream << u256; stream >> deserialized_u256; assert(u256 == deserialized_u256 && stream.empty()); uint160 deserialized_u160; stream << u160; stream >> deserialized_u160; assert(u160 == deserialized_u160 && stream.empty()); uint64_t deserialized_u64; stream << u64; stream >> deserialized_u64; assert(u64 == deserialized_u64 && stream.empty()); int64_t deserialized_i64; stream << i64; stream >> deserialized_i64; assert(i64 == deserialized_i64 && stream.empty()); uint32_t deserialized_u32; stream << u32; stream >> deserialized_u32; assert(u32 == deserialized_u32 && stream.empty()); int32_t deserialized_i32; stream << i32; stream >> deserialized_i32; assert(i32 == deserialized_i32 && stream.empty()); uint16_t deserialized_u16; stream << u16; stream >> deserialized_u16; assert(u16 == deserialized_u16 && stream.empty()); int16_t deserialized_i16; stream << i16; stream >> deserialized_i16; assert(i16 == deserialized_i16 && stream.empty()); uint8_t deserialized_u8; stream << u8; stream >> deserialized_u8; assert(u8 == deserialized_u8 && stream.empty()); int8_t deserialized_i8; stream << i8; stream >> deserialized_i8; assert(i8 == deserialized_i8 && stream.empty()); char deserialized_ch; stream << ch; stream >> deserialized_ch; assert(ch == deserialized_ch && stream.empty()); bool deserialized_b; stream << b; stream >> deserialized_b; assert(b == deserialized_b && stream.empty()); } } <commit_msg>tests: Fuzz HasAllDesirableServiceFlags(...) and MayHaveUsefulAddressDB(...)<commit_after>// Copyright (c) 2019 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 <amount.h> #include <arith_uint256.h> #include <compressor.h> #include <consensus/merkle.h> #include <core_io.h> #include <crypto/common.h> #include <crypto/siphash.h> #include <key_io.h> #include <memusage.h> #include <netbase.h> #include <policy/settings.h> #include <pow.h> #include <protocol.h> #include <pubkey.h> #include <rpc/util.h> #include <script/signingprovider.h> #include <script/standard.h> #include <serialize.h> #include <streams.h> #include <test/fuzz/FuzzedDataProvider.h> #include <test/fuzz/fuzz.h> #include <uint256.h> #include <util/moneystr.h> #include <util/strencodings.h> #include <util/system.h> #include <util/time.h> #include <version.h> #include <cassert> #include <limits> #include <vector> void initialize() { SelectParams(CBaseChainParams::REGTEST); } void test_one_input(const std::vector<uint8_t>& buffer) { if (buffer.size() < sizeof(uint256) + sizeof(uint160)) { return; } FuzzedDataProvider fuzzed_data_provider(buffer.data(), buffer.size()); const uint256 u256(fuzzed_data_provider.ConsumeBytes<unsigned char>(sizeof(uint256))); const uint160 u160(fuzzed_data_provider.ConsumeBytes<unsigned char>(sizeof(uint160))); const uint64_t u64 = fuzzed_data_provider.ConsumeIntegral<uint64_t>(); const int64_t i64 = fuzzed_data_provider.ConsumeIntegral<int64_t>(); const uint32_t u32 = fuzzed_data_provider.ConsumeIntegral<uint32_t>(); const int32_t i32 = fuzzed_data_provider.ConsumeIntegral<int32_t>(); const uint16_t u16 = fuzzed_data_provider.ConsumeIntegral<uint16_t>(); const int16_t i16 = fuzzed_data_provider.ConsumeIntegral<int16_t>(); const uint8_t u8 = fuzzed_data_provider.ConsumeIntegral<uint8_t>(); const int8_t i8 = fuzzed_data_provider.ConsumeIntegral<int8_t>(); // We cannot assume a specific value of std::is_signed<char>::value: // ConsumeIntegral<char>() instead of casting from {u,}int8_t. const char ch = fuzzed_data_provider.ConsumeIntegral<char>(); const bool b = fuzzed_data_provider.ConsumeBool(); const Consensus::Params& consensus_params = Params().GetConsensus(); (void)CheckProofOfWork(u256, u32, consensus_params); if (u64 <= MAX_MONEY) { const uint64_t compressed_money_amount = CompressAmount(u64); assert(u64 == DecompressAmount(compressed_money_amount)); static const uint64_t compressed_money_amount_max = CompressAmount(MAX_MONEY - 1); assert(compressed_money_amount <= compressed_money_amount_max); } else { (void)CompressAmount(u64); } static const uint256 u256_min(uint256S("0000000000000000000000000000000000000000000000000000000000000000")); static const uint256 u256_max(uint256S("ffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff")); const std::vector<uint256> v256{u256, u256_min, u256_max}; (void)ComputeMerkleRoot(v256); (void)CountBits(u64); (void)DecompressAmount(u64); (void)FormatISO8601Date(i64); (void)FormatISO8601DateTime(i64); // FormatMoney(i) not defined when i == std::numeric_limits<int64_t>::min() if (i64 != std::numeric_limits<int64_t>::min()) { int64_t parsed_money; if (ParseMoney(FormatMoney(i64), parsed_money)) { assert(parsed_money == i64); } } (void)GetSizeOfCompactSize(u64); (void)GetSpecialScriptSize(u32); // (void)GetVirtualTransactionSize(i64, i64); // function defined only for a subset of int64_t inputs // (void)GetVirtualTransactionSize(i64, i64, u32); // function defined only for a subset of int64_t/uint32_t inputs (void)HexDigit(ch); (void)MoneyRange(i64); (void)i64tostr(i64); (void)IsDigit(ch); (void)IsSpace(ch); (void)IsSwitchChar(ch); (void)itostr(i32); (void)memusage::DynamicUsage(ch); (void)memusage::DynamicUsage(i16); (void)memusage::DynamicUsage(i32); (void)memusage::DynamicUsage(i64); (void)memusage::DynamicUsage(i8); (void)memusage::DynamicUsage(u16); (void)memusage::DynamicUsage(u32); (void)memusage::DynamicUsage(u64); (void)memusage::DynamicUsage(u8); const unsigned char uch = static_cast<unsigned char>(u8); (void)memusage::DynamicUsage(uch); (void)MillisToTimeval(i64); const double d = ser_uint64_to_double(u64); assert(ser_double_to_uint64(d) == u64); const float f = ser_uint32_to_float(u32); assert(ser_float_to_uint32(f) == u32); (void)SighashToStr(uch); (void)SipHashUint256(u64, u64, u256); (void)SipHashUint256Extra(u64, u64, u256, u32); (void)ToLower(ch); (void)ToUpper(ch); // ValueFromAmount(i) not defined when i == std::numeric_limits<int64_t>::min() if (i64 != std::numeric_limits<int64_t>::min()) { int64_t parsed_money; if (ParseMoney(ValueFromAmount(i64).getValStr(), parsed_money)) { assert(parsed_money == i64); } } const arith_uint256 au256 = UintToArith256(u256); assert(ArithToUint256(au256) == u256); assert(uint256S(au256.GetHex()) == u256); (void)au256.bits(); (void)au256.GetCompact(/* fNegative= */ false); (void)au256.GetCompact(/* fNegative= */ true); (void)au256.getdouble(); (void)au256.GetHex(); (void)au256.GetLow64(); (void)au256.size(); (void)au256.ToString(); const CKeyID key_id{u160}; const CScriptID script_id{u160}; // CTxDestination = CNoDestination ∪ PKHash ∪ ScriptHash ∪ WitnessV0ScriptHash ∪ WitnessV0KeyHash ∪ WitnessUnknown const PKHash pk_hash{u160}; const ScriptHash script_hash{u160}; const WitnessV0KeyHash witness_v0_key_hash{u160}; const WitnessV0ScriptHash witness_v0_script_hash{u256}; const std::vector<CTxDestination> destinations{pk_hash, script_hash, witness_v0_key_hash, witness_v0_script_hash}; const SigningProvider store; for (const CTxDestination& destination : destinations) { (void)DescribeAddress(destination); (void)EncodeDestination(destination); (void)GetKeyForDestination(store, destination); (void)GetScriptForDestination(destination); (void)IsValidDestination(destination); } { CDataStream stream(SER_NETWORK, INIT_PROTO_VERSION); uint256 deserialized_u256; stream << u256; stream >> deserialized_u256; assert(u256 == deserialized_u256 && stream.empty()); uint160 deserialized_u160; stream << u160; stream >> deserialized_u160; assert(u160 == deserialized_u160 && stream.empty()); uint64_t deserialized_u64; stream << u64; stream >> deserialized_u64; assert(u64 == deserialized_u64 && stream.empty()); int64_t deserialized_i64; stream << i64; stream >> deserialized_i64; assert(i64 == deserialized_i64 && stream.empty()); uint32_t deserialized_u32; stream << u32; stream >> deserialized_u32; assert(u32 == deserialized_u32 && stream.empty()); int32_t deserialized_i32; stream << i32; stream >> deserialized_i32; assert(i32 == deserialized_i32 && stream.empty()); uint16_t deserialized_u16; stream << u16; stream >> deserialized_u16; assert(u16 == deserialized_u16 && stream.empty()); int16_t deserialized_i16; stream << i16; stream >> deserialized_i16; assert(i16 == deserialized_i16 && stream.empty()); uint8_t deserialized_u8; stream << u8; stream >> deserialized_u8; assert(u8 == deserialized_u8 && stream.empty()); int8_t deserialized_i8; stream << i8; stream >> deserialized_i8; assert(i8 == deserialized_i8 && stream.empty()); char deserialized_ch; stream << ch; stream >> deserialized_ch; assert(ch == deserialized_ch && stream.empty()); bool deserialized_b; stream << b; stream >> deserialized_b; assert(b == deserialized_b && stream.empty()); } { const ServiceFlags service_flags = (ServiceFlags)u64; (void)HasAllDesirableServiceFlags(service_flags); (void)MayHaveUsefulAddressDB(service_flags); } } <|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. */ /* */ /**************************************************************************************/ #include "BaseDemo.hpp" #include "vl/EdgeExtractor.hpp" #include "vl/EdgeRenderer.hpp" #include "vl/LoadWriterManager.hpp" class App_EdgeRendering: public BaseDemo { public: void setupScene() { // setup common states vl::ref<vl::Light> camera_light = new vl::Light(0); vl::ref<vl::EnableSet> enables = new vl::EnableSet; enables->enable(vl::EN_DEPTH_TEST); enables->enable(vl::EN_LIGHTING); // red material fx vl::ref<vl::Effect> red_fx = new vl::Effect; red_fx->shader()->setEnableSet(enables.get()); red_fx->shader()->gocMaterial()->setDiffuse(vlut::red); red_fx->shader()->setRenderState(camera_light.get()); // green material fx vl::ref<vl::Effect> green_fx = new vl::Effect; green_fx->shader()->setEnableSet(enables.get()); green_fx->shader()->gocMaterial()->setDiffuse(vlut::green); green_fx->shader()->setRenderState(camera_light.get()); // blue material fx vl::ref<vl::Effect> yellow_fx = new vl::Effect; yellow_fx->shader()->setEnableSet(enables.get()); yellow_fx->shader()->gocMaterial()->setDiffuse(vlut::yellow); yellow_fx->shader()->setRenderState(camera_light.get()); // add box, cylinder, cone actors to the scene vl::ref<vl::Geometry> geom1 = vlut::makeBox (vl::vec3(-7,0,0),5,5,5); vl::ref<vl::Geometry> geom2 = vlut::makeCylinder(vl::vec3(0,0,0), 5,5, 10,2, true, true); vl::ref<vl::Geometry> geom3 = vlut::makeCone (vl::vec3(+7,0,0),5,5, 20, true); // needed since we enabled the lighting geom1->computeNormals(); geom2->computeNormals(); geom3->computeNormals(); // add the actors to the scene sceneManager()->tree()->addActor( geom1.get(), red_fx.get(), mRendering->transform() ); sceneManager()->tree()->addActor( geom2.get(), green_fx.get(), mRendering->transform() ); sceneManager()->tree()->addActor( geom3.get(), yellow_fx.get(), mRendering->transform() ); } void initEvent() { BaseDemo::initEvent(); // initialize our renderings to use the camera, the scene-manager, rendering target etc. from the default renderingTree() mRendering = (vl::VisualizationLibrary::rendering()->as<vl::Rendering>()); mSolidRenderer = mRendering->renderer(); // mic fixme: review all documentation // bind an vl::EdgeRenderer to the mEdgeRenderer in order to perform automatic edge extraction and rendering. // we set the clear flags to be vl::CF_CLEAR_DEPTH (by default is set to CF_CLEAR_COLOR_DEPTH) because when the // wireframe rendering starts we want to preserve the color-buffer as generated by the solid rendering but we // want to clear the Z-buffer as it is needed by the hidden-line-removal algorithm implemented by vl::EdgeRenderer. mEdgeRenderer = new vl::EdgeRenderer; mRendering->renderers().push_back( mEdgeRenderer.get() ); mEdgeRenderer->setClearFlags(vl::CF_CLEAR_DEPTH); // hidden line and crease options mEdgeRenderer->setShowHiddenLines(true); mEdgeRenderer->setShowCreases(true); mEdgeRenderer->setCreaseAngle(35.0f); // style options mEdgeRenderer->setLineWidth(2.0f); mEdgeRenderer->setSmoothLines(true); mEdgeRenderer->setDefaultLineColor(vlut::black); // fills mSceneManager with a few actors. // the beauty of this system is that you setup your actors ony once in a single scene managers and // they will be rendered twice, first using a normal renderer and then using the wireframe renderer. setupScene(); } // user controls: // '1' = edge rendering off. // '2' = edge rendering on: silhouette only. // '3' = edge rendering on: silhouette + creases. // '4' = edge rendering on: silhouette + creases + hidden lines. // '5' = hidden line removal wireframe: silhouette + creases. // '6' = hidden line removal wireframe: silhouette + creases + hidden lines. void keyPressEvent(unsigned short ch, vl::EKey key) { BaseDemo::keyPressEvent(ch, key); if (ch == '1') { mSolidRenderer->setEnableMask(0xFFFFFFFF); mEdgeRenderer->setEnableMask(0); vl::Log::print("Edge rendering disabled.\n"); } else if (ch == '2') { mSolidRenderer->setEnableMask(0xFFFFFFFF); // preserve color buffer, clear depth buffer mEdgeRenderer->setClearFlags(vl::CF_CLEAR_DEPTH); mEdgeRenderer->setEnableMask(0xFFFFFFFF); mEdgeRenderer->setShowCreases(false); mEdgeRenderer->setShowHiddenLines(false); vl::Log::print("Edge rendering enabled. Creases = off, hidden lines = off.\n"); } else if (ch == '3') { mSolidRenderer->setEnableMask(0xFFFFFFFF); // preserve color buffer, clear depth buffer mEdgeRenderer->setClearFlags(vl::CF_CLEAR_DEPTH); mEdgeRenderer->setEnableMask(0xFFFFFFFF); mEdgeRenderer->setShowCreases(true); mEdgeRenderer->setShowHiddenLines(false); vl::Log::print("Edge rendering enabled. Creases = on, hidden lines = off.\n"); } else if (ch == '4') { mSolidRenderer->setEnableMask(0xFFFFFFFF); // preserve color buffer, clear depth buffer mEdgeRenderer->setClearFlags(vl::CF_CLEAR_DEPTH); mEdgeRenderer->setEnableMask(0xFFFFFFFF); mEdgeRenderer->setShowCreases(true); mEdgeRenderer->setShowHiddenLines(true); vl::Log::print("Edge rendering enabled. Creases = on, hidden lines = on.\n"); } else if (ch == '5') { mSolidRenderer->setEnableMask(0); // clear color and depth buffer mEdgeRenderer->setClearFlags(vl::CF_CLEAR_COLOR_DEPTH); mEdgeRenderer->setEnableMask(0xFFFFFFFF); mEdgeRenderer->setShowCreases(true); mEdgeRenderer->setShowHiddenLines(false); vl::Log::print("Hidden line removal wireframe enabled. Creases = on, hidden lines = off.\n"); } if (ch == '6') { mSolidRenderer->setEnableMask(0); // clear color and depth buffer mEdgeRenderer->setClearFlags(vl::CF_CLEAR_COLOR_DEPTH); mEdgeRenderer->setEnableMask(0xFFFFFFFF); mEdgeRenderer->setShowCreases(true); mEdgeRenderer->setShowHiddenLines(true); vl::Log::print("Hidden line removal wireframe enabled. Creases = on, hidden lines = on.\n"); } } void resizeEvent(int /*w*/, int /*h*/) { // solid rendering: update viewport and projection matrix mRendering->camera()->viewport()->setWidth(mRendering->renderTarget()->width()); mRendering->camera()->viewport()->setHeight(mRendering->renderTarget()->height()); mRendering->camera()->setProjectionAsPerspective(); } void loadModel(const std::vector<vl::String>& files) { // resets the scene mSceneManager->tree()->actors()->clear(); // resets the EdgeRenderer cache mEdgeRenderer->clearCache(); for(unsigned int i=0; i<files.size(); ++i) { vl::ref<vl::ResourceDatabase> resource_db = vl::loadResource(files[i],true); if (!resource_db || resource_db->count<vl::Actor>() == 0) { vl::Log::error("No data found.\n"); continue; } std::vector< vl::ref<vl::Actor> > actors; resource_db->get<vl::Actor>(actors); for(unsigned i=0; i<actors.size(); ++i) { vl::ref<vl::Actor> actor = actors[i].get(); // define a reasonable Shader actor->effect()->shader()->setRenderState( new vl::Light(0) ); actor->effect()->shader()->enable(vl::EN_DEPTH_TEST); actor->effect()->shader()->enable(vl::EN_LIGHTING); actor->effect()->shader()->gocLightModel()->setTwoSide(true); // add the actor to the scene mSceneManager->tree()->addActor( actor.get() ); } } // position the camera to nicely see the objects in the scene trackball()->adjustView( mSceneManager.get(), vl::vec3(0,0,1)/*direction*/, vl::vec3(0,1,0)/*up*/, 1.0f/*bias*/ ); } // laod the files dropped in the window void fileDroppedEvent(const std::vector<vl::String>& files) { loadModel(files); } protected: vl::ref< vl::Renderer > mSolidRenderer; vl::ref< vl::EdgeRenderer > mEdgeRenderer; vl::ref<vl::Rendering> mRendering; vl::ref<vl::SceneManagerActorTree> mSceneManager; }; // Have fun! <commit_msg>Updated comments of App_EdgeRendering demo test.<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. */ /* */ /**************************************************************************************/ #include "BaseDemo.hpp" #include "vl/EdgeExtractor.hpp" #include "vl/EdgeRenderer.hpp" #include "vl/LoadWriterManager.hpp" class App_EdgeRendering: public BaseDemo { public: void setupScene() { // setup common states vl::ref<vl::Light> camera_light = new vl::Light(0); vl::ref<vl::EnableSet> enables = new vl::EnableSet; enables->enable(vl::EN_DEPTH_TEST); enables->enable(vl::EN_LIGHTING); // red material fx vl::ref<vl::Effect> red_fx = new vl::Effect; red_fx->shader()->setEnableSet(enables.get()); red_fx->shader()->gocMaterial()->setDiffuse(vlut::red); red_fx->shader()->setRenderState(camera_light.get()); // green material fx vl::ref<vl::Effect> green_fx = new vl::Effect; green_fx->shader()->setEnableSet(enables.get()); green_fx->shader()->gocMaterial()->setDiffuse(vlut::green); green_fx->shader()->setRenderState(camera_light.get()); // blue material fx vl::ref<vl::Effect> yellow_fx = new vl::Effect; yellow_fx->shader()->setEnableSet(enables.get()); yellow_fx->shader()->gocMaterial()->setDiffuse(vlut::yellow); yellow_fx->shader()->setRenderState(camera_light.get()); // add box, cylinder, cone actors to the scene vl::ref<vl::Geometry> geom1 = vlut::makeBox (vl::vec3(-7,0,0),5,5,5); vl::ref<vl::Geometry> geom2 = vlut::makeCylinder(vl::vec3(0,0,0), 5,5, 10,2, true, true); vl::ref<vl::Geometry> geom3 = vlut::makeCone (vl::vec3(+7,0,0),5,5, 20, true); // needed since we enabled the lighting geom1->computeNormals(); geom2->computeNormals(); geom3->computeNormals(); // add the actors to the scene sceneManager()->tree()->addActor( geom1.get(), red_fx.get(), mRendering->transform() ); sceneManager()->tree()->addActor( geom2.get(), green_fx.get(), mRendering->transform() ); sceneManager()->tree()->addActor( geom3.get(), yellow_fx.get(), mRendering->transform() ); } void initEvent() { BaseDemo::initEvent(); // retrieve the default rendering mRendering = (vl::VisualizationLibrary::rendering()->as<vl::Rendering>()); // retrieve the default renderer, which we'll use as the solid-renderer mSolidRenderer = mRendering->renderer(); // create our EdgeRenderer mEdgeRenderer = new vl::EdgeRenderer; // we set the clear flags to be vl::CF_CLEAR_DEPTH (by default is set to CF_CLEAR_COLOR_DEPTH) because // when the wireframe rendering starts we want to preserve the color-buffer as generated by the solid // rendering but we want to clear the Z-buffer as it is needed by the hidden-line-removal algorithm // implemented by vl::EdgeRenderer. mEdgeRenderer->setClearFlags(vl::CF_CLEAR_DEPTH); // enqueue the EdgeRenderer in the rendering, will be executed after mSolidRenderer mRendering->renderers().push_back( mEdgeRenderer.get() ); // hidden line and crease options mEdgeRenderer->setShowHiddenLines(true); mEdgeRenderer->setShowCreases(true); mEdgeRenderer->setCreaseAngle(35.0f); // style options mEdgeRenderer->setLineWidth(2.0f); mEdgeRenderer->setSmoothLines(true); mEdgeRenderer->setDefaultLineColor(vlut::black); // fills mSceneManager with a few actors. // the beauty of this system is that you setup your actors ony once in a single scene managers and // they will be rendered twice, first using a normal renderer and then using the wireframe renderer. setupScene(); } // user controls: // '1' = edge rendering off. // '2' = edge rendering on: silhouette only. // '3' = edge rendering on: silhouette + creases. // '4' = edge rendering on: silhouette + creases + hidden lines. // '5' = hidden line removal wireframe: silhouette + creases. // '6' = hidden line removal wireframe: silhouette + creases + hidden lines. void keyPressEvent(unsigned short ch, vl::EKey key) { BaseDemo::keyPressEvent(ch, key); if (ch == '1') { mSolidRenderer->setEnableMask(0xFFFFFFFF); mEdgeRenderer->setEnableMask(0); vl::Log::print("Edge rendering disabled.\n"); } else if (ch == '2') { mSolidRenderer->setEnableMask(0xFFFFFFFF); // preserve color buffer, clear depth buffer mEdgeRenderer->setClearFlags(vl::CF_CLEAR_DEPTH); mEdgeRenderer->setEnableMask(0xFFFFFFFF); mEdgeRenderer->setShowCreases(false); mEdgeRenderer->setShowHiddenLines(false); vl::Log::print("Edge rendering enabled. Creases = off, hidden lines = off.\n"); } else if (ch == '3') { mSolidRenderer->setEnableMask(0xFFFFFFFF); // preserve color buffer, clear depth buffer mEdgeRenderer->setClearFlags(vl::CF_CLEAR_DEPTH); mEdgeRenderer->setEnableMask(0xFFFFFFFF); mEdgeRenderer->setShowCreases(true); mEdgeRenderer->setShowHiddenLines(false); vl::Log::print("Edge rendering enabled. Creases = on, hidden lines = off.\n"); } else if (ch == '4') { mSolidRenderer->setEnableMask(0xFFFFFFFF); // preserve color buffer, clear depth buffer mEdgeRenderer->setClearFlags(vl::CF_CLEAR_DEPTH); mEdgeRenderer->setEnableMask(0xFFFFFFFF); mEdgeRenderer->setShowCreases(true); mEdgeRenderer->setShowHiddenLines(true); vl::Log::print("Edge rendering enabled. Creases = on, hidden lines = on.\n"); } else if (ch == '5') { mSolidRenderer->setEnableMask(0); // clear color and depth buffer mEdgeRenderer->setClearFlags(vl::CF_CLEAR_COLOR_DEPTH); mEdgeRenderer->setEnableMask(0xFFFFFFFF); mEdgeRenderer->setShowCreases(true); mEdgeRenderer->setShowHiddenLines(false); vl::Log::print("Hidden line removal wireframe enabled. Creases = on, hidden lines = off.\n"); } if (ch == '6') { mSolidRenderer->setEnableMask(0); // clear color and depth buffer mEdgeRenderer->setClearFlags(vl::CF_CLEAR_COLOR_DEPTH); mEdgeRenderer->setEnableMask(0xFFFFFFFF); mEdgeRenderer->setShowCreases(true); mEdgeRenderer->setShowHiddenLines(true); vl::Log::print("Hidden line removal wireframe enabled. Creases = on, hidden lines = on.\n"); } } void resizeEvent(int /*w*/, int /*h*/) { // solid rendering: update viewport and projection matrix mRendering->camera()->viewport()->setWidth(mRendering->renderTarget()->width()); mRendering->camera()->viewport()->setHeight(mRendering->renderTarget()->height()); mRendering->camera()->setProjectionAsPerspective(); } void loadModel(const std::vector<vl::String>& files) { // resets the scene mSceneManager->tree()->actors()->clear(); // resets the EdgeRenderer cache mEdgeRenderer->clearCache(); for(unsigned int i=0; i<files.size(); ++i) { vl::ref<vl::ResourceDatabase> resource_db = vl::loadResource(files[i],true); if (!resource_db || resource_db->count<vl::Actor>() == 0) { vl::Log::error("No data found.\n"); continue; } std::vector< vl::ref<vl::Actor> > actors; resource_db->get<vl::Actor>(actors); for(unsigned i=0; i<actors.size(); ++i) { vl::ref<vl::Actor> actor = actors[i].get(); // define a reasonable Shader actor->effect()->shader()->setRenderState( new vl::Light(0) ); actor->effect()->shader()->enable(vl::EN_DEPTH_TEST); actor->effect()->shader()->enable(vl::EN_LIGHTING); actor->effect()->shader()->gocLightModel()->setTwoSide(true); // add the actor to the scene mSceneManager->tree()->addActor( actor.get() ); } } // position the camera to nicely see the objects in the scene trackball()->adjustView( mSceneManager.get(), vl::vec3(0,0,1)/*direction*/, vl::vec3(0,1,0)/*up*/, 1.0f/*bias*/ ); } // laod the files dropped in the window void fileDroppedEvent(const std::vector<vl::String>& files) { loadModel(files); } protected: vl::ref< vl::Renderer > mSolidRenderer; vl::ref< vl::EdgeRenderer > mEdgeRenderer; vl::ref<vl::Rendering> mRendering; vl::ref<vl::SceneManagerActorTree> mSceneManager; }; // Have fun! <|endoftext|>
<commit_before>/* * this file is part of the oxygen gtk engine * Copyright (c) 2010 Hugo Pereira Da Costa <[email protected]> * Copyright (c) 2010 Ruslan Kabatsayev <[email protected]> * * based on the Null Theme Engine for Gtk+. * Copyright (c) 2008 Robert Staudinger <[email protected]> * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 2 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 <gtk/gtk.h> #include <dlfcn.h> #include <string> #include "oxygen_version.h" enum WinDecoOptions { WinIsMaximized=1<<0, WinIsShaded=1<<2, WinIsResizable=1<<3, WinIsActive=1<<4, WinHasAlpha=1<<5, }; //! button status enum ButtonStatus { Normal, Disabled, // this shouldn't be specified by WMs unless button is really insensitive Hovered, Pressed, ButtonStatusCount }; //! buttons enum ButtonType { ButtonHelp=0, ButtonMax, ButtonMin, ButtonClose, ButtonMenu, ButtonSticky, ButtonAbove, ButtonBelow, ButtonShade, ButtonUnmax, ButtonUnstick, ButtonUnshade, ButtonUndoAbove, ButtonUndoBelow, ButtonTypeCount }; enum Metric { BorderLeft=0, BorderRight, BorderBottom, // BorderTop includes title and resize handle heights BorderTop, ButtonSpacing, ButtonMarginTop, ButtonMarginBottom, ShadowLeft, ShadowTop, ShadowRight, ShadowBottom, MetricsCount }; //___________________________________________________________________ // external pointers to functions void (*drawWindowDecoration)(cairo_t*, unsigned long, gint, gint, gint, gint, const gchar**, gint, gint) = 0L; void (*drawWindecoButton)(cairo_t*, unsigned long, unsigned long, unsigned long, gint, gint, gint, gint) = 0L; void (*drawWindecoShapeMask)(cairo_t*, unsigned long, gint, gint, gint, gint) = 0L; void (*drawWindowShadow)(cairo_t*, unsigned long, gint, gint, gint, gint) = 0L; gint (*getWindecoABIVersion)(void) = 0L; gint (*getWindecoMetric)(unsigned long) = 0L; gint (*getWindecoButtonSize)(unsigned long) = 0L; // window dimensions int ww( 700 ); int wh( 200 ); // widgets GtkWidget *mw0( 0L ); GtkWidget *mw1( 0L ); const gboolean useAlpha( TRUE ); // windeco metrics int shadowLeft=0; int shadowRight=0; int shadowTop=0; int shadowBottom=0; int borderLeft=0; int borderRight=0; int borderTop=0; int borderBottom=0; int dw=0; int dh=0; //___________________________________________________________________ gboolean initLib() { void* library; char* error=0; char* moduleDir=gtk_rc_get_module_dir(); if(moduleDir) { std::string libpath(moduleDir+std::string("/liboxygen-gtk.so")); g_free(moduleDir); library=dlopen(libpath.c_str(),RTLD_LAZY); bool success=false; do{ if(!library) { break; } else { getWindecoABIVersion=(gint(*)(void))dlsym(library, "getWindecoABIVersion"); if((error=dlerror())!=0L) { break; } else { #define EXPECTED_ABI_VERSION 3 gint version=getWindecoABIVersion(); if(version != EXPECTED_ABI_VERSION) { fprintf(stderr, "ABI version %d is not equal to expected version %d\n", version, EXPECTED_ABI_VERSION); return FALSE; } } // store drawWindowDecoration symbol drawWindowDecoration = (void(*)(cairo_t*, unsigned long, gint, gint, gint, gint, const gchar**, gint, gint))dlsym(library, "drawWindowDecoration"); if((error=dlerror())!=0L) break; // store drawWindecoButton symbol drawWindecoButton = (void (*)(cairo_t*, unsigned long, unsigned long, unsigned long, gint, gint, gint, gint))dlsym(library, "drawWindecoButton"); if((error=dlerror())!=0L) break; // store drawWindecoShapeMask symbol drawWindecoShapeMask=(void (*)(cairo_t*, unsigned long, gint, gint, gint, gint))dlsym(library, "drawWindecoShapeMask"); if((error=dlerror())!=0L) break; // store drawWindowShadow symbol drawWindowShadow=(void (*)(cairo_t*, unsigned long, gint, gint, gint, gint))dlsym(library, "drawWindowShadow"); if((error=dlerror())!=0L) break; // store drawWindecoMetric symbol getWindecoMetric=(gint (*)(unsigned long))dlsym(library, "getWindecoMetric"); if((error=dlerror())!=0L) break; // store drawWindecoButtonSize symbol getWindecoButtonSize=(gint (*)(unsigned long))dlsym(library, "getWindecoButtonSize"); if((error=dlerror())!=0L) break; } } while(0); if(error) { fprintf(stderr, "%s\n", error); return FALSE; } } return TRUE; } void getMetrics() { shadowLeft=getWindecoMetric(ShadowLeft); shadowRight=getWindecoMetric(ShadowRight); shadowTop=getWindecoMetric(ShadowTop); shadowBottom=getWindecoMetric(ShadowBottom); borderLeft=getWindecoMetric(BorderLeft); borderRight=getWindecoMetric(BorderRight); borderTop=getWindecoMetric(BorderTop); borderBottom=getWindecoMetric(BorderBottom); dw = borderLeft + borderRight + shadowLeft + shadowRight; dh = borderTop + borderBottom + shadowTop + shadowBottom; } //___________________________________________________________________ gboolean on_expose(GtkWidget* mw0, GdkEventExpose* event, gpointer user_data) { cairo_t* cr=gdk_cairo_create( gtk_widget_get_window( mw0 ) ); // define options int opt( WinIsResizable ); if( useAlpha ) opt |= WinHasAlpha; if( !gtk_window_is_active( GTK_WINDOW(mw1) ) ) opt|= WinIsActive; drawWindowShadow(cr, opt, 0, 0, mw0->allocation.width, mw0->allocation.height); const gchar* windowStrings[] = { "This is a caption", "WindowClass10110111", 0 }; drawWindowDecoration(cr, opt, 0+shadowLeft, 0+shadowTop, mw0->allocation.width-shadowLeft-shadowRight, mw0->allocation.height-shadowTop-shadowBottom, windowStrings, 0, 20*ButtonTypeCount); for( int status=0; status<ButtonStatusCount; status++) { for( int type=0; type<ButtonTypeCount; type++) { int buttonSize=getWindecoButtonSize(type); int buttonSpacing=getWindecoMetric(ButtonSpacing); int dbut=buttonSize+buttonSpacing; drawWindecoButton(cr, type, status, opt, mw0->allocation.width-shadowRight-borderRight-buttonSize-buttonSize*type, status*dbut+shadowTop+(borderTop-buttonSize)/2, buttonSize, buttonSize); } } cairo_destroy(cr); return TRUE; } //___________________________________________________________________ gboolean on_configure1(GtkWidget* mw1, GdkEventConfigure* event, gpointer user_data) { static int w=0, h=0; gboolean redraw( event->width != w || event->height != h ); if( redraw ) { w=event->width; h=event->height; int opt( WinIsActive|WinIsResizable ); if( useAlpha ) opt|= WinHasAlpha; gtk_window_resize(GTK_WINDOW(mw0), event->width+dw, event->height+dh); if(!useAlpha) { GdkBitmap* mask=gdk_pixmap_new(0L, event->width+dw, event->height+dh, 1); cairo_t* cr=gdk_cairo_create(mask); drawWindecoShapeMask(cr, opt, 0+shadowLeft, 0+shadowRight, event->width+dw-shadowLeft-shadowRight, event->height+dh-shadowTop-shadowBottom); gdk_window_shape_combine_mask( gtk_widget_get_window( mw0 ), 0L, 0, 0 ); // remove old mask gdk_window_shape_combine_mask( gtk_widget_get_window( mw0 ), mask, 0, 0 ); // apply new mask gdk_pixmap_unref(mask); } } return FALSE; } //___________________________________________________________________ gboolean on_configure0(GtkWidget* mw0, GdkEventConfigure* event, gpointer user_data) { static int w=0, h=0; static gboolean active=FALSE; gboolean redraw( event->width != w || event->height != h ); if(!(gtk_window_is_active(GTK_WINDOW(mw1))!=active)) { active ^= TRUE; redraw = TRUE; } if( redraw ) { w=event->width; h=event->height; gdk_window_begin_paint_rect( gtk_widget_get_window( mw0 ), (GdkRectangle*)&mw0->allocation); on_expose(mw0, 0L, 0L ); gdk_window_end_paint( gtk_widget_get_window( mw0 ) ); } return FALSE; } //___________________________________________________________________ int main(int argc, char** argv) { // load methods from style library if(!initLib()) return 1; // initialize gtk gtk_init(&argc, &argv); processCommandLine(argc,argv); // draw mw0=gtk_window_new(GTK_WINDOW_TOPLEVEL); mw1=gtk_window_new(GTK_WINDOW_TOPLEVEL); GdkColormap* cmap=gdk_screen_get_rgba_colormap(gdk_screen_get_default()); gtk_widget_set_colormap(mw0, cmap); g_signal_connect(G_OBJECT(mw0), "destroy", G_CALLBACK(gtk_main_quit), 0L); g_signal_connect(G_OBJECT(mw1), "destroy", G_CALLBACK(gtk_main_quit), 0L); gtk_window_set_default_size( GTK_WINDOW(mw1), ww, wh ); gtk_window_set_default_size( GTK_WINDOW(mw0), ww+dw, wh+dh ); gtk_window_set_decorated(GTK_WINDOW(mw0), FALSE); gtk_window_set_title( GTK_WINDOW(mw1), "This is a caption"); g_signal_connect( G_OBJECT(mw0), "expose-event", G_CALLBACK(on_expose), 0L); g_signal_connect( G_OBJECT(mw1), "configure-event", G_CALLBACK(on_configure1), 0L); g_signal_connect( G_OBJECT(mw0), "configure-event", G_CALLBACK(on_configure0), 0L); gtk_widget_show( mw1 ); gtk_widget_show( mw0 ); gtk_window_move( GTK_WINDOW(mw0), 300, 320); gtk_window_move( GTK_WINDOW(mw1), 300, 320); // FIXME: this call crashes in Oxygen::StyleHelper::initializeRefSurface() // if done right after gtk_init() call, i.e. until any widget is created getMetrics(); gtk_main(); return 0; } <commit_msg>Make deco window draggable<commit_after>/* * this file is part of the oxygen gtk engine * Copyright (c) 2010 Hugo Pereira Da Costa <[email protected]> * Copyright (c) 2010 Ruslan Kabatsayev <[email protected]> * * based on the Null Theme Engine for Gtk+. * Copyright (c) 2008 Robert Staudinger <[email protected]> * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 2 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 <gtk/gtk.h> #include <dlfcn.h> #include <string> #include "oxygen_version.h" enum WinDecoOptions { WinIsMaximized=1<<0, WinIsShaded=1<<2, WinIsResizable=1<<3, WinIsActive=1<<4, WinHasAlpha=1<<5, }; //! button status enum ButtonStatus { Normal, Disabled, // this shouldn't be specified by WMs unless button is really insensitive Hovered, Pressed, ButtonStatusCount }; //! buttons enum ButtonType { ButtonHelp=0, ButtonMax, ButtonMin, ButtonClose, ButtonMenu, ButtonSticky, ButtonAbove, ButtonBelow, ButtonShade, ButtonUnmax, ButtonUnstick, ButtonUnshade, ButtonUndoAbove, ButtonUndoBelow, ButtonTypeCount }; enum Metric { BorderLeft=0, BorderRight, BorderBottom, // BorderTop includes title and resize handle heights BorderTop, ButtonSpacing, ButtonMarginTop, ButtonMarginBottom, ShadowLeft, ShadowTop, ShadowRight, ShadowBottom, MetricsCount }; //___________________________________________________________________ // external pointers to functions void (*drawWindowDecoration)(cairo_t*, unsigned long, gint, gint, gint, gint, const gchar**, gint, gint) = 0L; void (*drawWindecoButton)(cairo_t*, unsigned long, unsigned long, unsigned long, gint, gint, gint, gint) = 0L; void (*drawWindecoShapeMask)(cairo_t*, unsigned long, gint, gint, gint, gint) = 0L; void (*drawWindowShadow)(cairo_t*, unsigned long, gint, gint, gint, gint) = 0L; gint (*getWindecoABIVersion)(void) = 0L; gint (*getWindecoMetric)(unsigned long) = 0L; gint (*getWindecoButtonSize)(unsigned long) = 0L; // window dimensions int ww( 700 ); int wh( 200 ); // widgets GtkWidget *mw0( 0L ); GtkWidget *mw1( 0L ); const gboolean useAlpha( TRUE ); // windeco metrics int shadowLeft=0; int shadowRight=0; int shadowTop=0; int shadowBottom=0; int borderLeft=0; int borderRight=0; int borderTop=0; int borderBottom=0; int dw=0; int dh=0; //___________________________________________________________________ gboolean initLib() { void* library; char* error=0; char* moduleDir=gtk_rc_get_module_dir(); if(moduleDir) { std::string libpath(moduleDir+std::string("/liboxygen-gtk.so")); g_free(moduleDir); library=dlopen(libpath.c_str(),RTLD_LAZY); bool success=false; do{ if(!library) { break; } else { getWindecoABIVersion=(gint(*)(void))dlsym(library, "getWindecoABIVersion"); if((error=dlerror())!=0L) { break; } else { #define EXPECTED_ABI_VERSION 3 gint version=getWindecoABIVersion(); if(version != EXPECTED_ABI_VERSION) { fprintf(stderr, "ABI version %d is not equal to expected version %d\n", version, EXPECTED_ABI_VERSION); return FALSE; } } // store drawWindowDecoration symbol drawWindowDecoration = (void(*)(cairo_t*, unsigned long, gint, gint, gint, gint, const gchar**, gint, gint))dlsym(library, "drawWindowDecoration"); if((error=dlerror())!=0L) break; // store drawWindecoButton symbol drawWindecoButton = (void (*)(cairo_t*, unsigned long, unsigned long, unsigned long, gint, gint, gint, gint))dlsym(library, "drawWindecoButton"); if((error=dlerror())!=0L) break; // store drawWindecoShapeMask symbol drawWindecoShapeMask=(void (*)(cairo_t*, unsigned long, gint, gint, gint, gint))dlsym(library, "drawWindecoShapeMask"); if((error=dlerror())!=0L) break; // store drawWindowShadow symbol drawWindowShadow=(void (*)(cairo_t*, unsigned long, gint, gint, gint, gint))dlsym(library, "drawWindowShadow"); if((error=dlerror())!=0L) break; // store drawWindecoMetric symbol getWindecoMetric=(gint (*)(unsigned long))dlsym(library, "getWindecoMetric"); if((error=dlerror())!=0L) break; // store drawWindecoButtonSize symbol getWindecoButtonSize=(gint (*)(unsigned long))dlsym(library, "getWindecoButtonSize"); if((error=dlerror())!=0L) break; } } while(0); if(error) { fprintf(stderr, "%s\n", error); return FALSE; } } return TRUE; } void getMetrics() { shadowLeft=getWindecoMetric(ShadowLeft); shadowRight=getWindecoMetric(ShadowRight); shadowTop=getWindecoMetric(ShadowTop); shadowBottom=getWindecoMetric(ShadowBottom); borderLeft=getWindecoMetric(BorderLeft); borderRight=getWindecoMetric(BorderRight); borderTop=getWindecoMetric(BorderTop); borderBottom=getWindecoMetric(BorderBottom); dw = borderLeft + borderRight + shadowLeft + shadowRight; dh = borderTop + borderBottom + shadowTop + shadowBottom; } //___________________________________________________________________ gboolean on_expose(GtkWidget* mw0, GdkEventExpose* event, gpointer user_data) { cairo_t* cr=gdk_cairo_create( gtk_widget_get_window( mw0 ) ); // define options int opt( WinIsResizable ); if( useAlpha ) opt |= WinHasAlpha; if( !gtk_window_is_active( GTK_WINDOW(mw1) ) ) opt|= WinIsActive; drawWindowShadow(cr, opt, 0, 0, mw0->allocation.width, mw0->allocation.height); const gchar* windowStrings[] = { "This is a caption", "WindowClass10110111", 0 }; drawWindowDecoration(cr, opt, 0+shadowLeft, 0+shadowTop, mw0->allocation.width-shadowLeft-shadowRight, mw0->allocation.height-shadowTop-shadowBottom, windowStrings, 0, 20*ButtonTypeCount); for( int status=0; status<ButtonStatusCount; status++) { for( int type=0; type<ButtonTypeCount; type++) { int buttonSize=getWindecoButtonSize(type); int buttonSpacing=getWindecoMetric(ButtonSpacing); int dbut=buttonSize+buttonSpacing; drawWindecoButton(cr, type, status, opt, mw0->allocation.width-shadowRight-borderRight-buttonSize-buttonSize*type, status*dbut+shadowTop+(borderTop-buttonSize)/2, buttonSize, buttonSize); } } cairo_destroy(cr); return TRUE; } //___________________________________________________________________ gboolean on_configure1(GtkWidget* mw1, GdkEventConfigure* event, gpointer user_data) { static int w=0, h=0; gboolean redraw( event->width != w || event->height != h ); if( redraw ) { w=event->width; h=event->height; int opt( WinIsActive|WinIsResizable ); if( useAlpha ) opt|= WinHasAlpha; gtk_window_resize(GTK_WINDOW(mw0), event->width+dw, event->height+dh); if(!useAlpha) { GdkBitmap* mask=gdk_pixmap_new(0L, event->width+dw, event->height+dh, 1); cairo_t* cr=gdk_cairo_create(mask); drawWindecoShapeMask(cr, opt, 0+shadowLeft, 0+shadowRight, event->width+dw-shadowLeft-shadowRight, event->height+dh-shadowTop-shadowBottom); gdk_window_shape_combine_mask( gtk_widget_get_window( mw0 ), 0L, 0, 0 ); // remove old mask gdk_window_shape_combine_mask( gtk_widget_get_window( mw0 ), mask, 0, 0 ); // apply new mask gdk_pixmap_unref(mask); } } return FALSE; } //___________________________________________________________________ gboolean on_configure0(GtkWidget* mw0, GdkEventConfigure* event, gpointer user_data) { static int w=0, h=0; static gboolean active=FALSE; gboolean redraw( event->width != w || event->height != h ); if(!(gtk_window_is_active(GTK_WINDOW(mw1))!=active)) { active ^= TRUE; redraw = TRUE; } if( redraw ) { w=event->width; h=event->height; gdk_window_begin_paint_rect( gtk_widget_get_window( mw0 ), (GdkRectangle*)&mw0->allocation); on_expose(mw0, 0L, 0L ); gdk_window_end_paint( gtk_widget_get_window( mw0 ) ); } return FALSE; } //___________________________________________________________________ gboolean on_press0(GtkWindow* window, GdkEventButton* event, GdkWindowEdge edge) { if(event->type == GDK_BUTTON_PRESS) if(event->button == 1) gtk_window_begin_move_drag(window,event->button,event->x_root,event->y_root,event->time); } //___________________________________________________________________ int main(int argc, char** argv) { // load methods from style library if(!initLib()) return 1; // initialize gtk gtk_init(&argc, &argv); processCommandLine(argc,argv); // draw mw0=gtk_window_new(GTK_WINDOW_TOPLEVEL); mw1=gtk_window_new(GTK_WINDOW_TOPLEVEL); GdkColormap* cmap=gdk_screen_get_rgba_colormap(gdk_screen_get_default()); gtk_widget_set_colormap(mw0, cmap); g_signal_connect(G_OBJECT(mw0), "destroy", G_CALLBACK(gtk_main_quit), 0L); g_signal_connect(G_OBJECT(mw1), "destroy", G_CALLBACK(gtk_main_quit), 0L); gtk_window_set_default_size( GTK_WINDOW(mw1), ww, wh ); gtk_window_set_default_size( GTK_WINDOW(mw0), ww+dw, wh+dh ); gtk_window_set_decorated(GTK_WINDOW(mw0), FALSE); gtk_widget_add_events(mw0,GDK_BUTTON_PRESS_MASK); gtk_window_set_title( GTK_WINDOW(mw1), "This is a caption"); g_signal_connect( G_OBJECT(mw0), "expose-event", G_CALLBACK(on_expose), 0L); g_signal_connect( G_OBJECT(mw1), "configure-event", G_CALLBACK(on_configure1), 0L); g_signal_connect( G_OBJECT(mw0), "configure-event", G_CALLBACK(on_configure0), 0L); g_signal_connect( G_OBJECT(mw0), "button-press-event", G_CALLBACK(on_press0), NULL); gtk_widget_show( mw1 ); gtk_widget_show( mw0 ); gtk_window_move( GTK_WINDOW(mw0), 300, 320); gtk_window_move( GTK_WINDOW(mw1), 300, 320); // FIXME: this call crashes in Oxygen::StyleHelper::initializeRefSurface() // if done right after gtk_init() call, i.e. until any widget is created getMetrics(); gtk_main(); return 0; } <|endoftext|>
<commit_before>// This file is a part of the IncludeOS unikernel - www.includeos.org // // Copyright 2015-2016 Oslo and Akershus University College of Applied Sciences // and Alfred Bratterud // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. #ifndef HTTP_REQUEST_HPP #define HTTP_REQUEST_HPP #include "message.hpp" #include "methods.hpp" #include "version.hpp" namespace http { //---------------------------------------- // This class is used to represent // an http request message //---------------------------------------- class Request : public Message { public: //---------------------------------------- // Default constructor // // Constructs a request message as follows: // // <GET / HTTP/1.1> //---------------------------------------- explicit Request() = default; //---------------------------------------- // Constructor to construct a request // message from the incoming character // stream of data which is a C-String // // @param request - The character stream of data // @param length - The length of the character stream // // @param limit - Capacity of how many fields can // be added //---------------------------------------- explicit Request(const char* request, const size_t length, const Limit limit = 100); //---------------------------------------- // Constructor to construct a request // message from the incoming character // stream of data which is a <std::string> // object // // @param request - The character stream of data // // @param limit - Capacity of how many fields can // be added //---------------------------------------- explicit Request(std::string request, const Limit limit = 100); //---------------------------------------- // Default copy constructor //---------------------------------------- Request(Request&) = default; //---------------------------------------- // Default move constructor //---------------------------------------- Request(Request&&) = default; //---------------------------------------- // Default destructor //---------------------------------------- ~Request() noexcept = default; //---------------------------------------- // Default copy assignment operator //---------------------------------------- Request& operator = (Request&) = default; //---------------------------------------- // Default move assignment operator //---------------------------------------- Request& operator = (Request&&) = default; //---------------------------------------- // Get the method of the request message // // @return - The method of the request //---------------------------------------- Method method() const noexcept; //---------------------------------------- // Set the method of the request message // // @param method - The method to set // // @return - The object that invoked this // method //---------------------------------------- Request& set_method(const Method method); //---------------------------------------- // Get the URI of the request message // // @return - The URI of the request //---------------------------------------- const URI& uri() const noexcept; //---------------------------------------- // Set the URI of the request message // // @param uri - The URI to set // // @return - The object that invoked this // method //---------------------------------------- Request& set_uri(const URI& uri); //---------------------------------------- // Get the version of the request message // // @return - The version of the request //---------------------------------------- const Version& version() const noexcept; //---------------------------------------- // Set the version of the request message // // @param version - The version to set // // @return - The object that invoked this // method //---------------------------------------- Request& set_version(const Version& version) noexcept; //---------------------------------------- // Get the value associated with the name // field from a query string // // @tparam (std::string) name - The name to find the associated // value // // @return - The associated value if name was found, // an empty string otherwise //---------------------------------------- template <typename Name> std::string query_value(Name&& name) const noexcept; //---------------------------------------- // Get the value associated with the name // field from the message body in a post request // // @tparam (std::string) name - The name to find the associated // value // // @return - The associated value if name was found, // an empty string otherwise //---------------------------------------- template <typename Name> std::string post_value(Name&& name) const noexcept; //---------------------------------------- // Reset the request message as if it was now // default constructed // // @return - The object that invoked this method //---------------------------------------- virtual Request& reset() noexcept override; //---------------------------------------- // Get a string representation of this // class // // @return - A string representation //---------------------------------------- virtual std::string to_string() const override; //---------------------------------------- // Operator to transform this class // into string form //---------------------------------------- operator std::string () const; //---------------------------------------- private: //---------------------------------------- // Class data members //---------------------------------------- const std::string request_; span field_; //---------------------------------------- // Request-line parts //---------------------------------------- Method method_{GET}; URI uri_{"/"}; Version version_{1U, 1U}; //---------------------------------------- // Private request parser //---------------------------------------- http_parser parser_; http_parser_settings settings_; //---------------------------------------- // Configure the parser settings // // @return - The object that invoked this // method //---------------------------------------- Request& configure_settings() noexcept; //---------------------------------------- // Execute the parser //---------------------------------------- void execute_parser() noexcept; //---------------------------------------- // Find the value associated with a name // in the following format: // // name=value // // @tparam (std::string) data - The data to search through // @tparam (std::string) name - The name to find the associated // value // // @return - The associated value if name was found, // an empty string otherwise //---------------------------------------- template <typename Data, typename Name> std::string get_value(Data&& data, Name&& name) const noexcept; }; //< class Request /**--v----------- Implementation Details -----------v--**/ /////////////////////////////////////////////////////////////////////////////// template <typename Name> inline std::string Request::query_value(Name&& name) const noexcept { return get_value(uri(), std::forward<Name>(name)); } /////////////////////////////////////////////////////////////////////////////// template <typename Name> inline std::string Request::post_value(Name&& name) const noexcept { if (method() not_eq POST) return std::string{}; return get_value(get_body(), std::forward<Name>(name)); } /////////////////////////////////////////////////////////////////////////////// template <typename Data, typename Name> inline std::string Request::get_value(Data&& data, Name&& name) const noexcept { if (data.empty() || name.empty()) return std::string{}; //--------------------------------- auto target = data.find(std::forward<Name>(name)); //--------------------------------- if (target == std::string::npos) return std::string{}; //--------------------------------- auto focal_point = data.substr(target); //--------------------------------- focal_point = focal_point.substr(0, focal_point.find_first_of('&')); //--------------------------------- auto lock_and_load = focal_point.find('='); //--------------------------------- if (lock_and_load == std::string::npos) return std::string{}; //--------------------------------- return focal_point.substr(lock_and_load + 1); } /////////////////////////////////////////////////////////////////////////////// inline Request_ptr make_request(buffer_t buf, const size_t len) { return std::make_shared<Request>(reinterpret_cast<char*>(buf.get()), len); } /////////////////////////////////////////////////////////////////////////////// inline Request_ptr make_request(std::string request) { return std::make_shared<Request>(std::move(request)); } /////////////////////////////////////////////////////////////////////////////// inline std::ostream& operator << (std::ostream& output_device, const Request& req) { return output_device << req.to_string(); } /**--^----------- Implementation Details -----------^--**/ } //< namespace http #endif //< HTTP_REQUEST_HPP <commit_msg>Fixed minor bug...<commit_after>// This file is a part of the IncludeOS unikernel - www.includeos.org // // Copyright 2015-2016 Oslo and Akershus University College of Applied Sciences // and Alfred Bratterud // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. #ifndef HTTP_REQUEST_HPP #define HTTP_REQUEST_HPP #include "message.hpp" #include "methods.hpp" #include "version.hpp" namespace http { //---------------------------------------- // This class is used to represent // an http request message //---------------------------------------- class Request : public Message { public: //---------------------------------------- // Default constructor // // Constructs a request message as follows: // // <GET / HTTP/1.1> //---------------------------------------- explicit Request() = default; //---------------------------------------- // Constructor to construct a request // message from the incoming character // stream of data which is a C-String // // @param request - The character stream of data // @param length - The length of the character stream // // @param limit - Capacity of how many fields can // be added //---------------------------------------- explicit Request(const char* request, const size_t length, const Limit limit = 100); //---------------------------------------- // Constructor to construct a request // message from the incoming character // stream of data which is a <std::string> // object // // @param request - The character stream of data // // @param limit - Capacity of how many fields can // be added //---------------------------------------- explicit Request(std::string request, const Limit limit = 100); //---------------------------------------- // Default copy constructor //---------------------------------------- Request(Request&) = default; //---------------------------------------- // Default move constructor //---------------------------------------- Request(Request&&) = default; //---------------------------------------- // Default destructor //---------------------------------------- ~Request() noexcept = default; //---------------------------------------- // Default copy assignment operator //---------------------------------------- Request& operator = (Request&) = default; //---------------------------------------- // Default move assignment operator //---------------------------------------- Request& operator = (Request&&) = default; //---------------------------------------- // Get the method of the request message // // @return - The method of the request //---------------------------------------- Method method() const noexcept; //---------------------------------------- // Set the method of the request message // // @param method - The method to set // // @return - The object that invoked this // method //---------------------------------------- Request& set_method(const Method method); //---------------------------------------- // Get the URI of the request message // // @return - The URI of the request //---------------------------------------- const URI& uri() const noexcept; //---------------------------------------- // Set the URI of the request message // // @param uri - The URI to set // // @return - The object that invoked this // method //---------------------------------------- Request& set_uri(const URI& uri); //---------------------------------------- // Get the version of the request message // // @return - The version of the request //---------------------------------------- const Version& version() const noexcept; //---------------------------------------- // Set the version of the request message // // @param version - The version to set // // @return - The object that invoked this // method //---------------------------------------- Request& set_version(const Version& version) noexcept; //---------------------------------------- // Get the value associated with the name // field from a query string // // @tparam (std::string) name - The name to find the associated // value // // @return - The associated value if name was found, // an empty string otherwise //---------------------------------------- template <typename Name> std::string query_value(Name&& name) const noexcept; //---------------------------------------- // Get the value associated with the name // field from the message body in a post request // // @tparam (std::string) name - The name to find the associated // value // // @return - The associated value if name was found, // an empty string otherwise //---------------------------------------- template <typename Name> std::string post_value(Name&& name) const noexcept; //---------------------------------------- // Reset the request message as if it was now // default constructed // // @return - The object that invoked this method //---------------------------------------- virtual Request& reset() noexcept override; //---------------------------------------- // Get a string representation of this // class // // @return - A string representation //---------------------------------------- virtual std::string to_string() const override; //---------------------------------------- // Operator to transform this class // into string form //---------------------------------------- operator std::string () const; //---------------------------------------- private: //---------------------------------------- // Class data members //---------------------------------------- const std::string request_; span field_; //---------------------------------------- // Request-line parts //---------------------------------------- Method method_{GET}; URI uri_{"/"}; Version version_{1U, 1U}; //---------------------------------------- // Private request parser //---------------------------------------- http_parser parser_; http_parser_settings settings_; //---------------------------------------- // Configure the parser settings // // @return - The object that invoked this // method //---------------------------------------- Request& configure_settings() noexcept; //---------------------------------------- // Execute the parser //---------------------------------------- void execute_parser() noexcept; //---------------------------------------- // Find the value associated with a name // in the following format: // // name=value // // @tparam (std::string) data - The data to search through // @tparam (std::string) name - The name to find the associated // value // // @return - The associated value if name was found, // an empty string otherwise //---------------------------------------- template <typename Data, typename Name> std::string get_value(Data&& data, Name&& name) const noexcept; }; //< class Request /**--v----------- Implementation Details -----------v--**/ /////////////////////////////////////////////////////////////////////////////// template <typename Name> inline std::string Request::query_value(Name&& name) const noexcept { return get_value(uri(), std::forward<Name>(name)); } /////////////////////////////////////////////////////////////////////////////// template <typename Name> inline std::string Request::post_value(Name&& name) const noexcept { if (method() not_eq POST) return std::string{}; return get_value(get_body().to_string(), std::forward<Name>(name)); } /////////////////////////////////////////////////////////////////////////////// template <typename Data, typename Name> inline std::string Request::get_value(Data&& data, Name&& name) const noexcept { if (data.empty() || name.empty()) return std::string{}; //--------------------------------- auto target = data.find(std::forward<Name>(name)); //--------------------------------- if (target == std::string::npos) return std::string{}; //--------------------------------- auto focal_point = data.substr(target); //--------------------------------- focal_point = focal_point.substr(0, focal_point.find_first_of('&')); //--------------------------------- auto lock_and_load = focal_point.find('='); //--------------------------------- if (lock_and_load == std::string::npos) return std::string{}; //--------------------------------- return focal_point.substr(lock_and_load + 1); } /////////////////////////////////////////////////////////////////////////////// inline Request_ptr make_request(buffer_t buf, const size_t len) { return std::make_shared<Request>(reinterpret_cast<char*>(buf.get()), len); } /////////////////////////////////////////////////////////////////////////////// inline Request_ptr make_request(std::string request) { return std::make_shared<Request>(std::move(request)); } /////////////////////////////////////////////////////////////////////////////// inline std::ostream& operator << (std::ostream& output_device, const Request& req) { return output_device << req.to_string(); } /**--^----------- Implementation Details -----------^--**/ } //< namespace http #endif //< HTTP_REQUEST_HPP <|endoftext|>
<commit_before>#include <tuple> #include <utility> #include <iostream> #include <typeinfo> enum class for_tuple_keys : int { nothing = 0, break_, //return_ in future continue_ }; template <size_t size> class VarargsIterator { template <size_t index, bool isOk = (index < size)> struct Iterator { static auto turn(auto t, auto func) { auto ret = func(std::get<index>(t)); if (ret == for_tuple_keys::break_) return ret; return Iterator<index + 1>::turn(t, func); } }; template <size_t index> struct Iterator<index, false> { static auto turn(auto t, auto func) { return for_tuple_keys::nothing; } }; public: static auto iterate(auto holder, auto func) { return Iterator<0>::turn(holder, func); } }; #define ftuple_kw(key) \ return for_tuple_keys::key ## _ #define for_tuple(name, args...) \ { [@FORMAT "\n" @] \ VarargsIterator<std::tuple_size<decltype(args)>::value>::iterate \ (args, [&](auto &name) \ [@ );%NL \ } %NL @] int main() { for_tuple(x, std::make_tuple(42, "Hello", 3.14)) { if (typeid(x) == typeid(double)) ftuple_kw(break); std::cout << x << std::endl; } } <commit_msg>Update examples<commit_after>#include <tuple> #include <utility> #include <iostream> #include <typeinfo> enum class for_tuple_keys : int { continue_ = 0, break_ }; template <size_t size> struct TupleIterator { template <class T, class V, size_t index = 0> static auto iterate(T holder, V func) { if constexpr (index < size) if (auto ret = func(std::get<index>(holder)); ret != for_tuple_keys::break_) return iterate<T, V, index + 1>(holder, func); return for_tuple_keys::continue_; } }; #define ftuple_kw(key) \ return for_tuple_keys::key ## _ #define for_tuple(name, args...) \ { \ auto tuple = args; \ TupleIterator<std::tuple_size<decltype(tuple)>::value>::iterate(tuple, [&](auto x) \ [@ ); } @] int main() { for_tuple(x, std::make_tuple(42, "Hello", 3.14)) { std::cout << x << std::endl; if constexpr (std::is_same<const char *, decltype(x)>::value) ftuple_kw(break); else ftuple_kw(continue); } } <|endoftext|>
<commit_before>/* * nextpnr -- Next Generation Place and Route * * Copyright (C) 2018 Clifford Wolf <[email protected]> * Copyright (C) 2018 Miodrag Milanovic <[email protected]> * * Permission to use, copy, modify, and/or distribute this software for any * purpose with or without fee is hereby granted, provided that the above * copyright notice and this permission notice appear in all copies. * * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR * ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN * ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF * OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. * */ #ifndef NO_GUI #include <QApplication> #include "application.h" #include "mainwindow.h" #endif #ifndef NO_PYTHON #include "pybindings.h" #endif #include <boost/filesystem/convenience.hpp> #include <boost/program_options.hpp> #include <fstream> #include <iostream> #include "command.h" #include "design_utils.h" #include "jsonparse.h" #include "log.h" #include "timing.h" #include "version.h" NEXTPNR_NAMESPACE_BEGIN CommandHandler::CommandHandler(int argc, char **argv) : argc(argc), argv(argv) { log_files.push_back(stdout); } bool CommandHandler::parseOptions() { options.add(getGeneralOptions()).add(getArchOptions()); try { po::parsed_options parsed = po::command_line_parser(argc, argv) .style(po::command_line_style::default_style ^ po::command_line_style::allow_guessing) .options(options) .positional(pos) .run(); po::store(parsed, vm); po::notify(vm); return true; } catch (std::exception &e) { std::cout << e.what() << "\n"; return false; } } bool CommandHandler::executeBeforeContext() { if (vm.count("help") || argc == 1) { std::cout << boost::filesystem::basename(argv[0]) << " -- Next Generation Place and Route (git sha1 " GIT_COMMIT_HASH_STR ")\n"; std::cout << options << "\n"; return argc != 1; } if (vm.count("version")) { std::cout << boost::filesystem::basename(argv[0]) << " -- Next Generation Place and Route (git sha1 " GIT_COMMIT_HASH_STR ")\n"; return true; } validate(); return false; } po::options_description CommandHandler::getGeneralOptions() { po::options_description general("General options"); general.add_options()("help,h", "show help"); general.add_options()("verbose,v", "verbose output"); general.add_options()("quiet,q", "quiet mode, only errors displayed"); general.add_options()("debug", "debug output"); general.add_options()("force,f", "keep running after errors"); #ifndef NO_GUI general.add_options()("gui", "start gui"); #endif #ifndef NO_PYTHON general.add_options()("run", po::value<std::vector<std::string>>(), "python file to execute instead of default flow"); pos.add("run", -1); general.add_options()("pre-pack", po::value<std::vector<std::string>>(), "python file to run before packing"); general.add_options()("pre-place", po::value<std::vector<std::string>>(), "python file to run before placement"); general.add_options()("pre-route", po::value<std::vector<std::string>>(), "python file to run before routing"); general.add_options()("post-route", po::value<std::vector<std::string>>(), "python file to run after routing"); #endif general.add_options()("json", po::value<std::string>(), "JSON design file to ingest"); general.add_options()("seed", po::value<int>(), "seed value for random number generator"); general.add_options()("slack_redist_iter", po::value<int>(), "number of iterations between slack redistribution"); general.add_options()("cstrweight", po::value<float>(), "placer weighting for relative constraint satisfaction"); general.add_options()("pack-only", "pack design only without placement or routing"); general.add_options()("version,V", "show version"); general.add_options()("test", "check architecture database integrity"); general.add_options()("freq", po::value<double>(), "set target frequency for design in MHz"); general.add_options()("no-tmdriv", "disable timing-driven placement"); general.add_options()("save", po::value<std::string>(), "project file to write"); general.add_options()("load", po::value<std::string>(), "project file to read"); return general; } void CommandHandler::setupContext(Context *ctx) { if (vm.count("verbose")) { ctx->verbose = true; } if (vm.count("debug")) { ctx->verbose = true; ctx->debug = true; } if (vm.count("quiet")) { log_quiet_warnings = true; } if (vm.count("force")) { ctx->force = true; } if (vm.count("seed")) { ctx->rngseed(vm["seed"].as<int>()); } if (vm.count("slack_redist_iter")) { ctx->slack_redist_iter = vm["slack_redist_iter"].as<int>(); if (vm.count("freq") && vm["freq"].as<double>() == 0) { ctx->auto_freq = true; #ifndef NO_GUI if (!vm.count("gui")) #endif log_warning("Target frequency not specified. Will optimise for max frequency.\n"); } } if (vm.count("cstrweight")) { settings->set("placer1/constraintWeight", vm["cstrweight"].as<float>()); } if (vm.count("freq")) { auto freq = vm["freq"].as<double>(); if (freq > 0) ctx->target_freq = freq * 1e6; } ctx->timing_driven = true; if (vm.count("no-tmdriv")) ctx->timing_driven = false; } int CommandHandler::executeMain(std::unique_ptr<Context> ctx) { if (vm.count("test")) { ctx->archcheck(); return 0; } #ifndef NO_GUI if (vm.count("gui")) { Application a(argc, argv); MainWindow w(std::move(ctx), chipArgs); try { if (vm.count("json")) { std::string filename = vm["json"].as<std::string>(); std::ifstream f(filename); w.notifyChangeContext(); if (!parse_json_file(f, filename, w.getContext())) log_error("Loading design failed.\n"); customAfterLoad(w.getContext()); w.updateLoaded(); } else if (vm.count("load")) { w.projectLoad(vm["load"].as<std::string>()); } else w.notifyChangeContext(); } catch (log_execution_error_exception) { // show error is handled by gui itself } w.show(); return a.exec(); } #endif if (vm.count("json")) { std::string filename = vm["json"].as<std::string>(); std::ifstream f(filename); if (!parse_json_file(f, filename, ctx.get())) log_error("Loading design failed.\n"); customAfterLoad(ctx.get()); } #ifndef NO_PYTHON init_python(argv[0], true); python_export_global("ctx", *ctx); if (vm.count("run")) { std::vector<std::string> files = vm["run"].as<std::vector<std::string>>(); for (auto filename : files) execute_python_file(filename.c_str()); } else #endif if (vm.count("json") || vm.count("load")) { run_script_hook("pre-pack"); if (!ctx->pack() && !ctx->force) log_error("Packing design failed.\n"); assign_budget(ctx.get()); ctx->check(); print_utilisation(ctx.get()); run_script_hook("pre-place"); if (!vm.count("pack-only")) { if (!ctx->place() && !ctx->force) log_error("Placing design failed.\n"); ctx->check(); run_script_hook("pre-route"); if (!ctx->route() && !ctx->force) log_error("Routing design failed.\n"); } run_script_hook("post-route"); customBitstream(ctx.get()); } if (vm.count("save")) { project.save(ctx.get(), vm["save"].as<std::string>()); } #ifndef NO_PYTHON deinit_python(); #endif return 0; } void CommandHandler::conflicting_options(const boost::program_options::variables_map &vm, const char *opt1, const char *opt2) { if (vm.count(opt1) && !vm[opt1].defaulted() && vm.count(opt2) && !vm[opt2].defaulted()) { std::string msg = "Conflicting options '" + std::string(opt1) + "' and '" + std::string(opt2) + "'."; log_error("%s\n", msg.c_str()); } } int CommandHandler::exec() { try { if (!parseOptions()) return -1; if (executeBeforeContext()) return 0; std::unique_ptr<Context> ctx; if (vm.count("load") && vm.count("gui") == 0) { ctx = project.load(vm["load"].as<std::string>()); } else { ctx = createContext(); } settings = std::unique_ptr<Settings>(new Settings(ctx.get())); setupContext(ctx.get()); setupArchContext(ctx.get()); return executeMain(std::move(ctx)); } catch (log_execution_error_exception) { return -1; } } void CommandHandler::run_script_hook(const std::string &name) { #ifndef NO_PYTHON if (vm.count(name)) { std::vector<std::string> files = vm[name].as<std::vector<std::string>>(); for (auto filename : files) execute_python_file(filename.c_str()); } #endif } NEXTPNR_NAMESPACE_END <commit_msg>add "randomize-seed" command-line option<commit_after>/* * nextpnr -- Next Generation Place and Route * * Copyright (C) 2018 Clifford Wolf <[email protected]> * Copyright (C) 2018 Miodrag Milanovic <[email protected]> * * Permission to use, copy, modify, and/or distribute this software for any * purpose with or without fee is hereby granted, provided that the above * copyright notice and this permission notice appear in all copies. * * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR * ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN * ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF * OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. * */ #ifndef NO_GUI #include <QApplication> #include "application.h" #include "mainwindow.h" #endif #ifndef NO_PYTHON #include "pybindings.h" #endif #include <boost/filesystem/convenience.hpp> #include <boost/program_options.hpp> #include <fstream> #include <iostream> #include "command.h" #include "design_utils.h" #include "jsonparse.h" #include "log.h" #include "timing.h" #include "version.h" NEXTPNR_NAMESPACE_BEGIN CommandHandler::CommandHandler(int argc, char **argv) : argc(argc), argv(argv) { log_files.push_back(stdout); } bool CommandHandler::parseOptions() { options.add(getGeneralOptions()).add(getArchOptions()); try { po::parsed_options parsed = po::command_line_parser(argc, argv) .style(po::command_line_style::default_style ^ po::command_line_style::allow_guessing) .options(options) .positional(pos) .run(); po::store(parsed, vm); po::notify(vm); return true; } catch (std::exception &e) { std::cout << e.what() << "\n"; return false; } } bool CommandHandler::executeBeforeContext() { if (vm.count("help") || argc == 1) { std::cout << boost::filesystem::basename(argv[0]) << " -- Next Generation Place and Route (git sha1 " GIT_COMMIT_HASH_STR ")\n"; std::cout << options << "\n"; return argc != 1; } if (vm.count("version")) { std::cout << boost::filesystem::basename(argv[0]) << " -- Next Generation Place and Route (git sha1 " GIT_COMMIT_HASH_STR ")\n"; return true; } validate(); return false; } po::options_description CommandHandler::getGeneralOptions() { po::options_description general("General options"); general.add_options()("help,h", "show help"); general.add_options()("verbose,v", "verbose output"); general.add_options()("quiet,q", "quiet mode, only errors displayed"); general.add_options()("debug", "debug output"); general.add_options()("force,f", "keep running after errors"); #ifndef NO_GUI general.add_options()("gui", "start gui"); #endif #ifndef NO_PYTHON general.add_options()("run", po::value<std::vector<std::string>>(), "python file to execute instead of default flow"); pos.add("run", -1); general.add_options()("pre-pack", po::value<std::vector<std::string>>(), "python file to run before packing"); general.add_options()("pre-place", po::value<std::vector<std::string>>(), "python file to run before placement"); general.add_options()("pre-route", po::value<std::vector<std::string>>(), "python file to run before routing"); general.add_options()("post-route", po::value<std::vector<std::string>>(), "python file to run after routing"); #endif general.add_options()("json", po::value<std::string>(), "JSON design file to ingest"); general.add_options()("seed", po::value<int>(), "seed value for random number generator"); general.add_options()("randomize-seed,r", "randomize seed value for random number generator"); general.add_options()("slack_redist_iter", po::value<int>(), "number of iterations between slack redistribution"); general.add_options()("cstrweight", po::value<float>(), "placer weighting for relative constraint satisfaction"); general.add_options()("pack-only", "pack design only without placement or routing"); general.add_options()("version,V", "show version"); general.add_options()("test", "check architecture database integrity"); general.add_options()("freq", po::value<double>(), "set target frequency for design in MHz"); general.add_options()("no-tmdriv", "disable timing-driven placement"); general.add_options()("save", po::value<std::string>(), "project file to write"); general.add_options()("load", po::value<std::string>(), "project file to read"); return general; } void CommandHandler::setupContext(Context *ctx) { if (vm.count("verbose")) { ctx->verbose = true; } if (vm.count("debug")) { ctx->verbose = true; ctx->debug = true; } if (vm.count("quiet")) { log_quiet_warnings = true; } if (vm.count("force")) { ctx->force = true; } if (vm.count("seed")) { ctx->rngseed(vm["seed"].as<int>()); } if (vm.count("randomize-seed")) { srand(time(NULL)); int r; do { r = rand(); } while(r == 0); ctx->rngseed(r); } if (vm.count("slack_redist_iter")) { ctx->slack_redist_iter = vm["slack_redist_iter"].as<int>(); if (vm.count("freq") && vm["freq"].as<double>() == 0) { ctx->auto_freq = true; #ifndef NO_GUI if (!vm.count("gui")) #endif log_warning("Target frequency not specified. Will optimise for max frequency.\n"); } } if (vm.count("cstrweight")) { settings->set("placer1/constraintWeight", vm["cstrweight"].as<float>()); } if (vm.count("freq")) { auto freq = vm["freq"].as<double>(); if (freq > 0) ctx->target_freq = freq * 1e6; } ctx->timing_driven = true; if (vm.count("no-tmdriv")) ctx->timing_driven = false; } int CommandHandler::executeMain(std::unique_ptr<Context> ctx) { if (vm.count("test")) { ctx->archcheck(); return 0; } #ifndef NO_GUI if (vm.count("gui")) { Application a(argc, argv); MainWindow w(std::move(ctx), chipArgs); try { if (vm.count("json")) { std::string filename = vm["json"].as<std::string>(); std::ifstream f(filename); w.notifyChangeContext(); if (!parse_json_file(f, filename, w.getContext())) log_error("Loading design failed.\n"); customAfterLoad(w.getContext()); w.updateLoaded(); } else if (vm.count("load")) { w.projectLoad(vm["load"].as<std::string>()); } else w.notifyChangeContext(); } catch (log_execution_error_exception) { // show error is handled by gui itself } w.show(); return a.exec(); } #endif if (vm.count("json")) { std::string filename = vm["json"].as<std::string>(); std::ifstream f(filename); if (!parse_json_file(f, filename, ctx.get())) log_error("Loading design failed.\n"); customAfterLoad(ctx.get()); } #ifndef NO_PYTHON init_python(argv[0], true); python_export_global("ctx", *ctx); if (vm.count("run")) { std::vector<std::string> files = vm["run"].as<std::vector<std::string>>(); for (auto filename : files) execute_python_file(filename.c_str()); } else #endif if (vm.count("json") || vm.count("load")) { run_script_hook("pre-pack"); if (!ctx->pack() && !ctx->force) log_error("Packing design failed.\n"); assign_budget(ctx.get()); ctx->check(); print_utilisation(ctx.get()); run_script_hook("pre-place"); if (!vm.count("pack-only")) { if (!ctx->place() && !ctx->force) log_error("Placing design failed.\n"); ctx->check(); run_script_hook("pre-route"); if (!ctx->route() && !ctx->force) log_error("Routing design failed.\n"); } run_script_hook("post-route"); customBitstream(ctx.get()); } if (vm.count("save")) { project.save(ctx.get(), vm["save"].as<std::string>()); } #ifndef NO_PYTHON deinit_python(); #endif return 0; } void CommandHandler::conflicting_options(const boost::program_options::variables_map &vm, const char *opt1, const char *opt2) { if (vm.count(opt1) && !vm[opt1].defaulted() && vm.count(opt2) && !vm[opt2].defaulted()) { std::string msg = "Conflicting options '" + std::string(opt1) + "' and '" + std::string(opt2) + "'."; log_error("%s\n", msg.c_str()); } } int CommandHandler::exec() { try { if (!parseOptions()) return -1; if (executeBeforeContext()) return 0; std::unique_ptr<Context> ctx; if (vm.count("load") && vm.count("gui") == 0) { ctx = project.load(vm["load"].as<std::string>()); } else { ctx = createContext(); } settings = std::unique_ptr<Settings>(new Settings(ctx.get())); setupContext(ctx.get()); setupArchContext(ctx.get()); return executeMain(std::move(ctx)); } catch (log_execution_error_exception) { return -1; } } void CommandHandler::run_script_hook(const std::string &name) { #ifndef NO_PYTHON if (vm.count(name)) { std::vector<std::string> files = vm[name].as<std::vector<std::string>>(); for (auto filename : files) execute_python_file(filename.c_str()); } #endif } NEXTPNR_NAMESPACE_END <|endoftext|>
<commit_before>#include "PoissonDiskSampling.h" PoissonDiskSampling::PoissonDiskSampling(int pointWidth, int pointHeight, double pointMinDist, double pointCount) : m_width(pointWidth), m_height(pointHeight), m_minDist(pointMinDist), m_pointCount(pointCount), m_cellSize(m_minDist / 1.414214f), m_gridWidth(ceil(m_width / m_cellSize)), m_gridHeight(ceil(m_height / m_cellSize)), m_grid(std::vector<std::vector<std::shared_ptr<Point>>>(m_gridWidth, std::vector<std::shared_ptr<Point>>(m_gridHeight, nullptr))) { } <commit_msg>Implement Generate() : create firstPoint and assign it<commit_after>#include "PoissonDiskSampling.h" #include <random> PoissonDiskSampling::PoissonDiskSampling(int pointWidth, int pointHeight, double pointMinDist, double pointCount) : m_width(pointWidth), m_height(pointHeight), m_minDist(pointMinDist), m_pointCount(pointCount), m_cellSize(m_minDist / 1.414214f), m_gridWidth(ceil(m_width / m_cellSize)), m_gridHeight(ceil(m_height / m_cellSize)), m_grid(std::vector<std::vector<std::shared_ptr<Point>>>(m_gridWidth, std::vector<std::shared_ptr<Point>>(m_gridHeight, nullptr))) { } std::vector<std::pair<double, double>> PoissonDiskSampling::Generate() { std::random_device rd; std::mt19937 gen(rd()); Point firstPoint(gen() / m_width, gen() / m_height); m_process.push_back(firstPoint); m_sample.push_back(std::make_pair(firstPoint.x, firstPoint.y)); int firstPointX = firstPoint.x / m_cellSize; int firstPointY = firstPoint.y / m_cellSize; m_grid[firstPointX][firstPointY] = std::make_shared<Point>(firstPoint); while (!m_process.empty()) { } } <|endoftext|>
<commit_before>/** * Appcelerator Titanium Mobile * Copyright (c) 2009-2012 by Appcelerator, Inc. All Rights Reserved. * Licensed under the terms of the Apache Public License * Please see the LICENSE included with this distribution for details. */ #include "TiRootObject.h" #include "NativeStringInterface.h" #include "TiGenericFunctionObject.h" #include "TiLocaleObject.h" #include "TiLogger.h" #include "TiMessageStrings.h" #include "TiTitaniumObject.h" #include "TiTimeoutManager.h" #include "TiV8EventContainerFactory.h" #include "V8Utils.h" #include <QSettings> #include <fstream> #include <sstream> #include <QString> #include <QUrl> #include <unistd.h> using namespace titanium; static Handle<ObjectTemplate> g_rootTemplate; static const string rootFolder = "app/native/assets/"; // Application properties defined at compile in tiapp.xml // can be read using this settings instance. It is read only. static QSettings defaultSettings("app/native/assets/app_properties.ini", QSettings::IniFormat); TiRootObject::TiRootObject() : TiObject("") { } TiRootObject::~TiRootObject() { if (!context_.IsEmpty()) { context_.Dispose(); } NativeStringInterface::deleteInstance(); } void TiRootObject::onCreateStaticMembers() { TiObject* ti = TiTitaniumObject::createObject(objectFactory_); addMember(ti); addMember(ti, "Ti"); createStringMethods(); TiGenericFunctionObject::addGenericFunctionToParent(this, "L", this, _L); // TODO: use the same object as Ti.Locale.getString TiGenericFunctionObject::addGenericFunctionToParent(this, "clearInterval", this, _clearInterval); TiGenericFunctionObject::addGenericFunctionToParent(this, "clearTimeout", this, _clearTimeout); TiGenericFunctionObject::addGenericFunctionToParent(this, "globalRequire", this, _globalRequire); TiGenericFunctionObject::addGenericFunctionToParent(this, "setInterval", this, _setInterval); TiGenericFunctionObject::addGenericFunctionToParent(this, "setTimeout", this, _setTimeout); } VALUE_MODIFY TiRootObject::onChildValueChange(TiObject* childObject, Handle<Value>, Handle<Value> newValue) { Local<Object> obj = getValue()->ToObject(); obj->Set(String::New(childObject->getName()), newValue); return VALUE_MODIFY_ALLOW; } void TiRootObject::addMember(TiObject* object, const char* name) { TiObject::addMember(object, name); if (name == NULL) { name = object->getName(); } Handle<Object> obj = getValue()->ToObject(); Handle<Value> newValue = object->getValue(); if (newValue.IsEmpty()) { newValue = globalTemplate_->NewInstance(); object->forceSetValue(newValue); TiObject::setTiObjectToJsObject(newValue, object); } obj->Set(String::New(name), newValue); } TiRootObject* TiRootObject::createRootObject() { TiRootObject* obj = new TiRootObject; return obj; } int TiRootObject::executeScript(NativeObjectFactory* objectFactory, const char* javaScript, MESSAGELOOPENTRY messageLoopEntry, void* context) { HandleScope handleScope; objectFactory_ = objectFactory; globalTemplate_ = ObjectTemplate::New(); TiV8EventContainerFactory* eventFactory = TiV8EventContainerFactory::createEventContainerFactory(globalTemplate_); objectFactory->setEventContainerFactory(eventFactory); onSetGetPropertyCallback(&globalTemplate_); onSetFunctionCallback(&globalTemplate_); g_rootTemplate = ObjectTemplate::New(); context_ = Context::New(NULL, g_rootTemplate); forceSetValue(context_->Global()); context_->Global()->SetHiddenValue(String::New("globalTemplate_"), External::New(&globalTemplate_)); context_->Global()->SetHiddenValue(String::New("context_"), External::New(&context_)); setTiObjectToJsObject(context_->Global(), this); Context::Scope context_scope(context_); initializeTiObject(NULL); bool scriptHasError = false; const char* bootstrapFilename = "bootstrap.js"; string bootstrapJavascript; { ifstream ifs((string("app/native/framework/") + bootstrapFilename).c_str()); if (!ifs) { TiLogger::getInstance().log(Ti::Msg::ERROR__Cannot_load_bootstrap_js); return -1; } getline(ifs, bootstrapJavascript, string::traits_type::to_char_type(string::traits_type::eof())); ifs.close(); } TryCatch tryCatch; Handle<Script> compiledBootstrapScript = Script::Compile(String::New(bootstrapJavascript.c_str()), String::New(bootstrapFilename)); if (compiledBootstrapScript.IsEmpty()) { String::Utf8Value error(tryCatch.Exception()); TiLogger::getInstance().log(*error); return -1; } Handle<Value> bootstrapResult = compiledBootstrapScript->Run(); if (bootstrapResult.IsEmpty()) { Local<Value> exception = tryCatch.Exception(); // FIXME: need a way to prevent double "filename + line" output Handle<Message> msg = tryCatch.Message(); stringstream ss; ss << bootstrapFilename << " line "; if (msg.IsEmpty()) { ss << "?"; } else { ss << msg->GetLineNumber(); } ss << ": " << *String::Utf8Value(exception); TiLogger::getInstance().log(ss.str().c_str()); return -1; } const char* filename = "app.js"; Handle<Script> compiledScript = Script::Compile(String::New(javaScript), String::New(filename)); string err_msg; if (compiledScript.IsEmpty()) { ReportException(tryCatch, true, err_msg); return 1; } compiledScript->Run(); if (tryCatch.HasCaught()) { ReportException(tryCatch, true, err_msg); scriptHasError = true; } // show script error QString deployType = defaultSettings.value("deploytype").toString(); if (scriptHasError && deployType.compare(QString("development")) == 0) { // clean up display data size_t start_pos = 0; while((start_pos = err_msg.find("\n", start_pos)) != std::string::npos) { err_msg.replace(start_pos, 1, "\\n"); } start_pos = 0; while((start_pos = err_msg.find("'", start_pos)) != std::string::npos) { err_msg.erase(start_pos, 1); } static const string javaScriptErrorAlert = string("var win1 = Titanium.UI.createWindow({") + string("backgroundColor:'red'") + string("});") + string("var label1 = Titanium.UI.createLabel({") + string("color:'#61f427',") + string("textAlign:'center',") + string("text:") + "'" + err_msg + "'," + //string("font:{fontSize:8,fontFamily:'Helvetica Neue',fontStyle:'italic'},") + string("});") + string("win1.add(label1);") + string("win1.open();"); compiledScript = Script::Compile(String::New(javaScriptErrorAlert.c_str())); compiledScript->Run(); } onStartMessagePump(); return (messageLoopEntry)(context); } Handle<Object> TiRootObject::createProxyObject() { return globalTemplate_->NewInstance(); } void TiRootObject::createStringMethods() { Local<Value> str = context_->Global()->Get(String::New("String")); if (!str->IsObject()) { // This should never happen ThrowException(String::New(Ti::Msg::INTERNAL__Global_String_symbol_is_not_an_object)); } Local<Object> strObj = str->ToObject(); const NativeStringInterface* nsi = objectFactory_->getNativeStringInterface(); strObj->Set(String::New("format"), FunctionTemplate::New(nsi->format)->GetFunction()); strObj->Set(String::New("formatCurrency"), FunctionTemplate::New(nsi->formatCurrency)->GetFunction()); strObj->Set(String::New("formatDate"), FunctionTemplate::New(nsi->formatDate)->GetFunction()); strObj->Set(String::New("formatDecimal"), FunctionTemplate::New(nsi->formatDecimal)->GetFunction()); strObj->Set(String::New("formatTime"), FunctionTemplate::New(nsi->formatTime)->GetFunction()); } /* Methods defined by Global */ Handle<Value> TiRootObject::_L(void* arg1, TiObject* arg2, const Arguments& arg3) { return TiLocaleObject::_getString(arg1, arg2, arg3); } Handle<Value> TiRootObject::_clearInterval(void*, TiObject*, const Arguments& args) { if ((args.Length() != 1) || (!args[0]->IsNumber())) { return ThrowException(String::New(Ti::Msg::Invalid_arguments)); } clearTimeoutHelper(args, true); return Undefined(); } Handle<Value> TiRootObject::_clearTimeout(void*, TiObject*, const Arguments& args) { if ((args.Length() != 1) || (!args[0]->IsNumber())) { return ThrowException(String::New(Ti::Msg::Invalid_arguments)); } clearTimeoutHelper(args, false); return Undefined(); } void TiRootObject::clearTimeoutHelper(const Arguments& args, bool interval) { Handle<Number> number = Handle<Number>::Cast(args[0]); TiTimeoutManager* timeoutManager = TiTimeoutManager::instance(); timeoutManager->clearTimeout((int)number->Value(), interval); } Handle<Value> TiRootObject::_globalRequire(void*, TiObject*, const Arguments& args) { if (args.Length() < 2) { return ThrowException(String::New(Ti::Msg::Missing_argument)); } string id = *String::Utf8Value(args[0]->ToString()); string parentFolder = *String::Utf8Value(args[1]->ToString()); // CommonJS path rules if (id.find("/") == 0) { id.replace(id.find("/"), std::string("/").length(), rootFolder); } else if (id.find("./") == 0) { id.replace(id.find("./"), std::string("./").length(), parentFolder); } else if (id.find("../") == 0) { // count ../../../ in id and strip off back of parentFolder int count = 0; size_t idx = 0; size_t pos = 0; while (true) { idx = id.find("../", pos); if (idx == std::string::npos) { break; } else { pos = idx + 3; count++; } } // strip leading ../../ off module id id = id.substr(pos); // strip paths off the parent folder idx = 0; pos = parentFolder.size(); for (int i = 0; i < count; i++) { idx = parentFolder.find_last_of("/", pos); pos = idx - 1; } if (idx == std::string::npos) { return ThrowException(String::New("Unable to find module")); } parentFolder = parentFolder.substr(0, idx + 1); id = parentFolder + id; } else { string tempId = rootFolder + id; ifstream ifs((tempId + ".js").c_str()); if (!ifs) { id = parentFolder + id; } else { id = rootFolder + id; } } string filename = id + ".js"; // check if cached static map<string, Persistent<Value> > cache; map<string, Persistent<Value> >::const_iterator cachedValue = cache.find(id); if (cachedValue != cache.end()) { return cachedValue->second; } string javascript; { ifstream ifs((filename).c_str()); if (!ifs) { Local<Value> taggedMessage = String::New((string(Ti::Msg::No_such_native_module) + " " + id).c_str()); return ThrowException(taggedMessage); } getline(ifs, javascript, string::traits_type::to_char_type(string::traits_type::eof())); ifs.close(); } // wrap the module { size_t idx = filename.find_last_of("/"); parentFolder = filename.substr(0, idx + 1); static const string requireWithParent = "var require = function (id) { return globalRequire(id, '" + parentFolder + "')};\n"; static const string preWrap = "(function () {" + requireWithParent + "\nvar module = { exports: {} }; var exports = module.exports;\n"; static const string postWrap = "\nreturn module.exports; })();"; javascript = preWrap + javascript + postWrap; } TryCatch tryCatch; Handle<Script> compiledScript = Script::Compile(String::New(javascript.c_str()), String::New(filename.c_str())); if (compiledScript.IsEmpty()) { std::string err_msg; DisplayExceptionLine(tryCatch, err_msg); return tryCatch.ReThrow(); } Persistent<Value> result = Persistent<Value>::New(compiledScript->Run()); if (result.IsEmpty()) { return tryCatch.ReThrow(); } // cache result cache.insert(pair<string, Persistent<Value> >(id, result)); return result; } Handle<Value> TiRootObject::_setInterval(void*, TiObject*, const Arguments& args) { return setTimeoutHelper(args, true); } Handle<Value> TiRootObject::_setTimeout(void*, TiObject*, const Arguments& args) { return setTimeoutHelper(args, false); } Handle<Value> TiRootObject::setTimeoutHelper(const Arguments& args, bool interval) { HandleScope handleScope; if ((args.Length() != 2) || (!args[0]->IsFunction()) || (!args[1]->IsNumber())) { ThrowException(String::New(Ti::Msg::Invalid_arguments)); } Handle<Function> function = Handle<Function>::Cast(args[0]); Handle<Number> number = Handle<Number>::Cast(args[1]); TiTimeoutManager* timeoutManager = TiTimeoutManager::instance(); int id = timeoutManager->createTimeout((int)number->Value(), function, interval); Handle<Number> timerId = Number::New(id); return timerId; } <commit_msg>updated text color<commit_after>/** * Appcelerator Titanium Mobile * Copyright (c) 2009-2012 by Appcelerator, Inc. All Rights Reserved. * Licensed under the terms of the Apache Public License * Please see the LICENSE included with this distribution for details. */ #include "TiRootObject.h" #include "NativeStringInterface.h" #include "TiGenericFunctionObject.h" #include "TiLocaleObject.h" #include "TiLogger.h" #include "TiMessageStrings.h" #include "TiTitaniumObject.h" #include "TiTimeoutManager.h" #include "TiV8EventContainerFactory.h" #include "V8Utils.h" #include <QSettings> #include <fstream> #include <sstream> #include <QString> #include <QUrl> #include <unistd.h> using namespace titanium; static Handle<ObjectTemplate> g_rootTemplate; static const string rootFolder = "app/native/assets/"; // Application properties defined at compile in tiapp.xml // can be read using this settings instance. It is read only. static QSettings defaultSettings("app/native/assets/app_properties.ini", QSettings::IniFormat); TiRootObject::TiRootObject() : TiObject("") { } TiRootObject::~TiRootObject() { if (!context_.IsEmpty()) { context_.Dispose(); } NativeStringInterface::deleteInstance(); } void TiRootObject::onCreateStaticMembers() { TiObject* ti = TiTitaniumObject::createObject(objectFactory_); addMember(ti); addMember(ti, "Ti"); createStringMethods(); TiGenericFunctionObject::addGenericFunctionToParent(this, "L", this, _L); // TODO: use the same object as Ti.Locale.getString TiGenericFunctionObject::addGenericFunctionToParent(this, "clearInterval", this, _clearInterval); TiGenericFunctionObject::addGenericFunctionToParent(this, "clearTimeout", this, _clearTimeout); TiGenericFunctionObject::addGenericFunctionToParent(this, "globalRequire", this, _globalRequire); TiGenericFunctionObject::addGenericFunctionToParent(this, "setInterval", this, _setInterval); TiGenericFunctionObject::addGenericFunctionToParent(this, "setTimeout", this, _setTimeout); } VALUE_MODIFY TiRootObject::onChildValueChange(TiObject* childObject, Handle<Value>, Handle<Value> newValue) { Local<Object> obj = getValue()->ToObject(); obj->Set(String::New(childObject->getName()), newValue); return VALUE_MODIFY_ALLOW; } void TiRootObject::addMember(TiObject* object, const char* name) { TiObject::addMember(object, name); if (name == NULL) { name = object->getName(); } Handle<Object> obj = getValue()->ToObject(); Handle<Value> newValue = object->getValue(); if (newValue.IsEmpty()) { newValue = globalTemplate_->NewInstance(); object->forceSetValue(newValue); TiObject::setTiObjectToJsObject(newValue, object); } obj->Set(String::New(name), newValue); } TiRootObject* TiRootObject::createRootObject() { TiRootObject* obj = new TiRootObject; return obj; } int TiRootObject::executeScript(NativeObjectFactory* objectFactory, const char* javaScript, MESSAGELOOPENTRY messageLoopEntry, void* context) { HandleScope handleScope; objectFactory_ = objectFactory; globalTemplate_ = ObjectTemplate::New(); TiV8EventContainerFactory* eventFactory = TiV8EventContainerFactory::createEventContainerFactory(globalTemplate_); objectFactory->setEventContainerFactory(eventFactory); onSetGetPropertyCallback(&globalTemplate_); onSetFunctionCallback(&globalTemplate_); g_rootTemplate = ObjectTemplate::New(); context_ = Context::New(NULL, g_rootTemplate); forceSetValue(context_->Global()); context_->Global()->SetHiddenValue(String::New("globalTemplate_"), External::New(&globalTemplate_)); context_->Global()->SetHiddenValue(String::New("context_"), External::New(&context_)); setTiObjectToJsObject(context_->Global(), this); Context::Scope context_scope(context_); initializeTiObject(NULL); bool scriptHasError = false; const char* bootstrapFilename = "bootstrap.js"; string bootstrapJavascript; { ifstream ifs((string("app/native/framework/") + bootstrapFilename).c_str()); if (!ifs) { TiLogger::getInstance().log(Ti::Msg::ERROR__Cannot_load_bootstrap_js); return -1; } getline(ifs, bootstrapJavascript, string::traits_type::to_char_type(string::traits_type::eof())); ifs.close(); } TryCatch tryCatch; Handle<Script> compiledBootstrapScript = Script::Compile(String::New(bootstrapJavascript.c_str()), String::New(bootstrapFilename)); if (compiledBootstrapScript.IsEmpty()) { String::Utf8Value error(tryCatch.Exception()); TiLogger::getInstance().log(*error); return -1; } Handle<Value> bootstrapResult = compiledBootstrapScript->Run(); if (bootstrapResult.IsEmpty()) { Local<Value> exception = tryCatch.Exception(); // FIXME: need a way to prevent double "filename + line" output Handle<Message> msg = tryCatch.Message(); stringstream ss; ss << bootstrapFilename << " line "; if (msg.IsEmpty()) { ss << "?"; } else { ss << msg->GetLineNumber(); } ss << ": " << *String::Utf8Value(exception); TiLogger::getInstance().log(ss.str().c_str()); return -1; } const char* filename = "app.js"; Handle<Script> compiledScript = Script::Compile(String::New(javaScript), String::New(filename)); string err_msg; if (compiledScript.IsEmpty()) { ReportException(tryCatch, true, err_msg); return 1; } compiledScript->Run(); if (tryCatch.HasCaught()) { ReportException(tryCatch, true, err_msg); scriptHasError = true; } // show script error QString deployType = defaultSettings.value("deploytype").toString(); if (scriptHasError && deployType.compare(QString("development")) == 0) { // clean up display data size_t start_pos = 0; while((start_pos = err_msg.find("\n", start_pos)) != std::string::npos) { err_msg.replace(start_pos, 1, "\\n"); } start_pos = 0; while((start_pos = err_msg.find("'", start_pos)) != std::string::npos) { err_msg.erase(start_pos, 1); } static const string javaScriptErrorAlert = string("var win1 = Titanium.UI.createWindow({") + string("backgroundColor:'red'") + string("});") + string("var label1 = Titanium.UI.createLabel({") + string("color:'white',") + string("textAlign:'center',") + string("text:") + "'" + err_msg + "'," + string("font:{fontSize:8,fontFamily:'Helvetica Neue',fontStyle:'Bold'},") + string("});") + string("win1.add(label1);") + string("win1.open();"); compiledScript = Script::Compile(String::New(javaScriptErrorAlert.c_str())); compiledScript->Run(); } onStartMessagePump(); return (messageLoopEntry)(context); } Handle<Object> TiRootObject::createProxyObject() { return globalTemplate_->NewInstance(); } void TiRootObject::createStringMethods() { Local<Value> str = context_->Global()->Get(String::New("String")); if (!str->IsObject()) { // This should never happen ThrowException(String::New(Ti::Msg::INTERNAL__Global_String_symbol_is_not_an_object)); } Local<Object> strObj = str->ToObject(); const NativeStringInterface* nsi = objectFactory_->getNativeStringInterface(); strObj->Set(String::New("format"), FunctionTemplate::New(nsi->format)->GetFunction()); strObj->Set(String::New("formatCurrency"), FunctionTemplate::New(nsi->formatCurrency)->GetFunction()); strObj->Set(String::New("formatDate"), FunctionTemplate::New(nsi->formatDate)->GetFunction()); strObj->Set(String::New("formatDecimal"), FunctionTemplate::New(nsi->formatDecimal)->GetFunction()); strObj->Set(String::New("formatTime"), FunctionTemplate::New(nsi->formatTime)->GetFunction()); } /* Methods defined by Global */ Handle<Value> TiRootObject::_L(void* arg1, TiObject* arg2, const Arguments& arg3) { return TiLocaleObject::_getString(arg1, arg2, arg3); } Handle<Value> TiRootObject::_clearInterval(void*, TiObject*, const Arguments& args) { if ((args.Length() != 1) || (!args[0]->IsNumber())) { return ThrowException(String::New(Ti::Msg::Invalid_arguments)); } clearTimeoutHelper(args, true); return Undefined(); } Handle<Value> TiRootObject::_clearTimeout(void*, TiObject*, const Arguments& args) { if ((args.Length() != 1) || (!args[0]->IsNumber())) { return ThrowException(String::New(Ti::Msg::Invalid_arguments)); } clearTimeoutHelper(args, false); return Undefined(); } void TiRootObject::clearTimeoutHelper(const Arguments& args, bool interval) { Handle<Number> number = Handle<Number>::Cast(args[0]); TiTimeoutManager* timeoutManager = TiTimeoutManager::instance(); timeoutManager->clearTimeout((int)number->Value(), interval); } Handle<Value> TiRootObject::_globalRequire(void*, TiObject*, const Arguments& args) { if (args.Length() < 2) { return ThrowException(String::New(Ti::Msg::Missing_argument)); } string id = *String::Utf8Value(args[0]->ToString()); string parentFolder = *String::Utf8Value(args[1]->ToString()); // CommonJS path rules if (id.find("/") == 0) { id.replace(id.find("/"), std::string("/").length(), rootFolder); } else if (id.find("./") == 0) { id.replace(id.find("./"), std::string("./").length(), parentFolder); } else if (id.find("../") == 0) { // count ../../../ in id and strip off back of parentFolder int count = 0; size_t idx = 0; size_t pos = 0; while (true) { idx = id.find("../", pos); if (idx == std::string::npos) { break; } else { pos = idx + 3; count++; } } // strip leading ../../ off module id id = id.substr(pos); // strip paths off the parent folder idx = 0; pos = parentFolder.size(); for (int i = 0; i < count; i++) { idx = parentFolder.find_last_of("/", pos); pos = idx - 1; } if (idx == std::string::npos) { return ThrowException(String::New("Unable to find module")); } parentFolder = parentFolder.substr(0, idx + 1); id = parentFolder + id; } else { string tempId = rootFolder + id; ifstream ifs((tempId + ".js").c_str()); if (!ifs) { id = parentFolder + id; } else { id = rootFolder + id; } } string filename = id + ".js"; // check if cached static map<string, Persistent<Value> > cache; map<string, Persistent<Value> >::const_iterator cachedValue = cache.find(id); if (cachedValue != cache.end()) { return cachedValue->second; } string javascript; { ifstream ifs((filename).c_str()); if (!ifs) { Local<Value> taggedMessage = String::New((string(Ti::Msg::No_such_native_module) + " " + id).c_str()); return ThrowException(taggedMessage); } getline(ifs, javascript, string::traits_type::to_char_type(string::traits_type::eof())); ifs.close(); } // wrap the module { size_t idx = filename.find_last_of("/"); parentFolder = filename.substr(0, idx + 1); static const string requireWithParent = "var require = function (id) { return globalRequire(id, '" + parentFolder + "')};\n"; static const string preWrap = "(function () {" + requireWithParent + "\nvar module = { exports: {} }; var exports = module.exports;\n"; static const string postWrap = "\nreturn module.exports; })();"; javascript = preWrap + javascript + postWrap; } TryCatch tryCatch; Handle<Script> compiledScript = Script::Compile(String::New(javascript.c_str()), String::New(filename.c_str())); if (compiledScript.IsEmpty()) { std::string err_msg; DisplayExceptionLine(tryCatch, err_msg); return tryCatch.ReThrow(); } Persistent<Value> result = Persistent<Value>::New(compiledScript->Run()); if (result.IsEmpty()) { return tryCatch.ReThrow(); } // cache result cache.insert(pair<string, Persistent<Value> >(id, result)); return result; } Handle<Value> TiRootObject::_setInterval(void*, TiObject*, const Arguments& args) { return setTimeoutHelper(args, true); } Handle<Value> TiRootObject::_setTimeout(void*, TiObject*, const Arguments& args) { return setTimeoutHelper(args, false); } Handle<Value> TiRootObject::setTimeoutHelper(const Arguments& args, bool interval) { HandleScope handleScope; if ((args.Length() != 2) || (!args[0]->IsFunction()) || (!args[1]->IsNumber())) { ThrowException(String::New(Ti::Msg::Invalid_arguments)); } Handle<Function> function = Handle<Function>::Cast(args[0]); Handle<Number> number = Handle<Number>::Cast(args[1]); TiTimeoutManager* timeoutManager = TiTimeoutManager::instance(); int id = timeoutManager->createTimeout((int)number->Value(), function, interval); Handle<Number> timerId = Number::New(id); return timerId; } <|endoftext|>
<commit_before>/************************************************************************* * * OpenOffice.org - a multi-platform office productivity suite * * $RCSfile: servres.cxx,v $ * * $Revision: 1.4 $ * * last change: $Author: rt $ $Date: 2007-04-26 09:39:34 $ * * 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_automation.hxx" #include <string.h> #include "servres.hrc" #include "servuid.hxx" #include "servres.hxx" ModalDialogGROSSER_TEST_DLG::ModalDialogGROSSER_TEST_DLG( Window * pParent, const ResId & rResId, BOOL bFreeRes ) : ModalDialog( pParent, rResId ), aCheckBox1( this, ResId( 1, *rResId.GetResMgr() ) ), aTriStateBox1( this, ResId( 1, *rResId.GetResMgr() ) ), aOKButton1( this, ResId( 1, *rResId.GetResMgr() ) ), aTimeField1( this, ResId( 1, *rResId.GetResMgr() ) ), aMultiLineEdit1( this, ResId( 1, *rResId.GetResMgr() ) ), aGroupBox1( this, ResId( 1, *rResId.GetResMgr() ) ), aRadioButton1( this, ResId( 1, *rResId.GetResMgr() ) ), aRadioButton2( this, ResId( 2, *rResId.GetResMgr() ) ), aMultiListBox1( this, ResId( 1, *rResId.GetResMgr() ) ), aComboBox1( this, ResId( 1, *rResId.GetResMgr() ) ), aDateBox1( this, ResId( 1, *rResId.GetResMgr() ) ), aFixedText1( this, ResId( 1, *rResId.GetResMgr() ) ) { if( bFreeRes ) FreeResource(); } MenuMENU_CLIENT::MenuMENU_CLIENT( const ResId & rResId, BOOL ) : MenuBar( rResId ) { // No subresources, automatic free resource } <commit_msg>INTEGRATION: CWS changefileheader (1.4.46); FILE MERGED 2008/03/28 16:03:36 rt 1.4.46.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: servres.cxx,v $ * $Revision: 1.5 $ * * 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_automation.hxx" #include <string.h> #include "servres.hrc" #include "servuid.hxx" #include "servres.hxx" ModalDialogGROSSER_TEST_DLG::ModalDialogGROSSER_TEST_DLG( Window * pParent, const ResId & rResId, BOOL bFreeRes ) : ModalDialog( pParent, rResId ), aCheckBox1( this, ResId( 1, *rResId.GetResMgr() ) ), aTriStateBox1( this, ResId( 1, *rResId.GetResMgr() ) ), aOKButton1( this, ResId( 1, *rResId.GetResMgr() ) ), aTimeField1( this, ResId( 1, *rResId.GetResMgr() ) ), aMultiLineEdit1( this, ResId( 1, *rResId.GetResMgr() ) ), aGroupBox1( this, ResId( 1, *rResId.GetResMgr() ) ), aRadioButton1( this, ResId( 1, *rResId.GetResMgr() ) ), aRadioButton2( this, ResId( 2, *rResId.GetResMgr() ) ), aMultiListBox1( this, ResId( 1, *rResId.GetResMgr() ) ), aComboBox1( this, ResId( 1, *rResId.GetResMgr() ) ), aDateBox1( this, ResId( 1, *rResId.GetResMgr() ) ), aFixedText1( this, ResId( 1, *rResId.GetResMgr() ) ) { if( bFreeRes ) FreeResource(); } MenuMENU_CLIENT::MenuMENU_CLIENT( const ResId & rResId, BOOL ) : MenuBar( rResId ) { // No subresources, automatic free resource } <|endoftext|>
<commit_before>/** * Copyright (c) 2014 Charles J. Ezell III. * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU Affero General 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 General Public License for more details. * * You should have received a copy of the GNU Affero General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. * * As a special exception, the copyright holders give permission to link the * code of portions of this program with the OpenSSL library under certain * conditions as described in each individual source file and distribute * linked combinations including the program with the OpenSSL library. You * must comply with the GNU Affero General Public License in all respects for * all of the code used other than as permitted herein. If you modify file(s) * with this exception, you may extend this exception to your version of the * file(s), but you are not obligated to do so. If you do not wish to do so, * delete this exception statement from your version. If you delete this * exception statement from all source files in the program, then also delete * it in the license file. */ #include "mdb_conduit.h" #include <algorithm> #include <exception> #include <fstream> #include <sstream> #include <cstdint> #include <vector> #include <boost/filesystem/operations.hpp> #include <boost/program_options.hpp> #include <mongo/db/json.h> #include "mdb_pipeline.h" //Driver. int main(int argc, char** argv, char** env) { return conduit::conduit_main(argc, argv, env); } // --- Implementation --- // using namespace std; using mongo::BSONObj; namespace fs = boost::filesystem; namespace po = boost::program_options; //These are the valid input data types. enum class InputFormat : uint8_t { JSON, BSON }; //Describe the various things that can go wrong when parsing the //command-line arguments. enum class CommandLineStatus : uint8_t { OK, NO_PIPELINE, NO_DATA_FILE, INVALID_FORMAT, CONFLICTING_OPTIONS, EXCEPTION_CAUGHT, FAILED_INITIALIZATION, FAILED_DEINITIALIZATION, }; //Converts a json array into bson. BSONObj convertJsonArrayToBson(const string& json) { //Ugh. fromjson() doesn't support top-level arrays? //This is annoying but I'm not concerned about JSON input performance. string rawJson("{\"w\":"); rawJson.append(json); rawJson.append("}"); //TODO: return better errors for the user than just: //code FailedToParse: FailedToParse: Expecting '{': offset:0 of:[{$match:{v:1}}] auto wrapped(mongo::fromjson(rawJson)), result(wrapped.getField("w").Obj()); return result.getOwned(); } //Read a file into a string. No JSON validation is performed. string loadSmallFile(const fs::path& path) { ifstream file(path.native()); return string(istreambuf_iterator<char>(file), istreambuf_iterator<char>()); } BSONObj readSmallBsonFile(const fs::path& path) { //Temp, just for testing. //Based off of BSONTool::processFile(). //Going to rewrite this to use a memmapped file //and wrap it all in BsonFileDocumentSource. ifstream file(path.native()); vector<char> data(fs::file_size(path)); copy(istreambuf_iterator<char>(file), istreambuf_iterator<char>(), data.begin()); mongo::BSONArrayBuilder b; char* p(&data[0]), *end(p + data.size()); while(p < end) { size_t objsize(0); if((p+4) < end) { memcpy(&objsize, p, 4); } else { stringstream ss; const size_t offset(p - &data[0]); ss << "Unexpected end of BSON file '" << path.native() << "' at " << offset << " bytes."; throw runtime_error(ss.str()); } if(objsize > mongo::BSONObjMaxUserSize) { stringstream ss; const size_t offset(p - &data[0]); ss << "BSON file '" << path.native() << "' appears to be corrupt near " << offset << " bytes."; throw runtime_error(ss.str()); } BSONObj temp(p); b.append(temp); p += objsize; } return b.obj(); } BSONObj loadFile(const InputFormat format, const fs::path& path) { BSONObj result; switch(format) { case InputFormat::BSON: return readSmallBsonFile(path); case InputFormat::JSON: return convertJsonArrayToBson(loadSmallFile(path)); default: throw runtime_error("Unknown format for '" + path.native() + "': somebody screwed up."); } } InputFormat getInputFormat(const string& desc, const string& format) { if("bson" == format) { return InputFormat::BSON; } else if("json" == format) { return InputFormat::JSON; } else { throw logic_error("Unknown " + desc + " format: '" + format + "'"); } } CommandLineStatus getInputFormats( const string& formatSpec, InputFormat& pipelineFormat, InputFormat& dataFormat) { auto delimIdx(formatSpec.find('-')); if(string::npos == delimIdx || formatSpec.size() < delimIdx+1) { cerr << "Invalid format: '" << formatSpec << "'"; return CommandLineStatus::INVALID_FORMAT; } pipelineFormat = getInputFormat( "pipeline", formatSpec.substr(0, delimIdx)); dataFormat = getInputFormat("data", formatSpec.substr(delimIdx+1)); return CommandLineStatus::OK; } CommandLineStatus checkForConflictingOptions( const po::variables_map& variables, const string& opt1, const string& opt2) { bool opt1Set(variables.count(opt1) && !variables[opt1].defaulted()), opt2Set(variables.count(opt2) && !variables[opt2].defaulted()); if (opt1Set && opt2Set) { cerr << "Conflicting options: '" << opt1 << "' and '" << opt2 << "'."; return CommandLineStatus::CONFLICTING_OPTIONS; } return CommandLineStatus::OK; } //Parse any command-line arguments. //This can throw if something really unexpected happens. CommandLineStatus parse_options( int argc, char** argv, char** env, BSONObj& pipeline, BSONObj& data) { po::options_description options("Options"); options.add_options() ("help", "Show usage") ("eval,e", po::value<string>(), "A JSON pipeline to evaluate.") ("pipeline,p", po::value<fs::path>(), "The path to a pipeline to evaluate.") ("data,d", po::value<fs::path>()->required(), "The path to a data file to run the pipeline on.") ("format,f", po::value<string>()->default_value("bson-bson"), "Specifies the input and output format for --pipeline and --data, respectively. One of: bson-bson, json-json, json-bson, bson-json.") ; po::positional_options_description p; p.add("data", -1); po::variables_map variables; po::store(po::command_line_parser(argc, argv). options(options).positional(p).run(), variables); auto conflictCheck(checkForConflictingOptions(variables, "eval", "pipeline")); if(CommandLineStatus::OK != conflictCheck) { return conflictCheck; } po::notify(variables); if (variables.count("help")) { cout << options << "\n"; return CommandLineStatus::OK; } InputFormat pipelineFormat, dataFormat; auto formatsResult = getInputFormats( variables["format"].as<string>(), pipelineFormat, dataFormat ); if(CommandLineStatus::OK != formatsResult) { return formatsResult; } if (variables.count("eval")) { auto pipelineJson(variables["eval"].as<string>()); pipeline = convertJsonArrayToBson(pipelineJson); } else if(variables.count("pipeline")) { auto path(variables["pipeline"].as<fs::path>()); pipeline = loadFile(pipelineFormat, path); } else { cerr << "You must provide a pipeline via either --eval or --pipeline."; return CommandLineStatus::NO_PIPELINE; } if (variables.count("data")) { auto path(variables["data"].as<fs::path>()); data = loadFile(dataFormat, path); } else { //TODO: it might be nice to have a pipeline validation mode. cerr << "You must provide a data file."; return CommandLineStatus::NO_DATA_FILE; } return CommandLineStatus::OK; } namespace conduit { int conduit_main(int argc, char** argv, char** env) { try { const Status initResult(intialize_module(argc, argv, env)); if(!initResult.isOK()) { cerr << "Initialization failed: " << initResult.toString() << '\n'; return static_cast<int>( CommandLineStatus::FAILED_INITIALIZATION); } BSONObj data, pipeline; auto parseResult(parse_options(argc, argv, env, pipeline, data)); if(CommandLineStatus::OK != parseResult) { return static_cast<int>(parseResult); } conduit::Pipeline conduit(pipeline); mongo::BSONObjBuilder result; conduit(data, result); string jsonResult(result.obj().jsonString()); cout << jsonResult << '\n'; const Status deinitResult(deinitalize_module()); if(!deinitResult.isOK()) { cerr << "Initialization failed: " << initResult.toString() << '\n'; return static_cast<int>( CommandLineStatus::FAILED_DEINITIALIZATION); } return 0; } catch(exception& e) { std::cerr << e.what() << '\n'; //We're already toast, don't worry about whether this succeeds. deinitalize_module(); return static_cast<int>(CommandLineStatus::EXCEPTION_CAUGHT); } } } //namespace conduit. <commit_msg>Make --help always work.<commit_after>/** * Copyright (c) 2014 Charles J. Ezell III. * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU Affero General 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 General Public License for more details. * * You should have received a copy of the GNU Affero General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. * * As a special exception, the copyright holders give permission to link the * code of portions of this program with the OpenSSL library under certain * conditions as described in each individual source file and distribute * linked combinations including the program with the OpenSSL library. You * must comply with the GNU Affero General Public License in all respects for * all of the code used other than as permitted herein. If you modify file(s) * with this exception, you may extend this exception to your version of the * file(s), but you are not obligated to do so. If you do not wish to do so, * delete this exception statement from your version. If you delete this * exception statement from all source files in the program, then also delete * it in the license file. */ #include "mdb_conduit.h" #include <algorithm> #include <exception> #include <fstream> #include <sstream> #include <cstdint> #include <vector> #include <boost/filesystem/operations.hpp> #include <boost/program_options.hpp> #include <mongo/db/json.h> #include "mdb_pipeline.h" //Driver. int main(int argc, char** argv, char** env) { return conduit::conduit_main(argc, argv, env); } // --- Implementation --- // using namespace std; using mongo::BSONObj; namespace fs = boost::filesystem; namespace po = boost::program_options; //These are the valid input data types. enum class InputFormat : uint8_t { JSON, BSON }; //Describe the various things that can go wrong when parsing the //command-line arguments. enum class CommandLineStatus : uint8_t { OK, SHOWED_HELP, NO_PIPELINE, NO_DATA_FILE, INVALID_FORMAT, CONFLICTING_OPTIONS, EXCEPTION_CAUGHT, FAILED_INITIALIZATION, FAILED_DEINITIALIZATION, }; //Converts a json array into bson. BSONObj convertJsonArrayToBson(const string& json) { //Ugh. fromjson() doesn't support top-level arrays? //This is annoying but I'm not concerned about JSON input performance. string rawJson("{\"w\":"); rawJson.append(json); rawJson.append("}"); //TODO: return better errors for the user than just: //code FailedToParse: FailedToParse: Expecting '{': offset:0 of:[{$match:{v:1}}] auto wrapped(mongo::fromjson(rawJson)), result(wrapped.getField("w").Obj()); return result.getOwned(); } //Read a file into a string. No JSON validation is performed. string loadSmallFile(const fs::path& path) { ifstream file(path.native()); return string(istreambuf_iterator<char>(file), istreambuf_iterator<char>()); } BSONObj readSmallBsonFile(const fs::path& path) { //Temp, just for testing. //Based off of BSONTool::processFile(). //Going to rewrite this to use a memmapped file //and wrap it all in BsonFileDocumentSource. ifstream file(path.native()); vector<char> data(fs::file_size(path)); copy(istreambuf_iterator<char>(file), istreambuf_iterator<char>(), data.begin()); mongo::BSONArrayBuilder b; char* p(&data[0]), *end(p + data.size()); while(p < end) { size_t objsize(0); if((p+4) < end) { memcpy(&objsize, p, 4); } else { stringstream ss; const size_t offset(p - &data[0]); ss << "Unexpected end of BSON file '" << path.native() << "' at " << offset << " bytes."; throw runtime_error(ss.str()); } if(objsize > mongo::BSONObjMaxUserSize) { stringstream ss; const size_t offset(p - &data[0]); ss << "BSON file '" << path.native() << "' appears to be corrupt near " << offset << " bytes."; throw runtime_error(ss.str()); } BSONObj temp(p); b.append(temp); p += objsize; } return b.obj(); } BSONObj loadFile(const InputFormat format, const fs::path& path) { BSONObj result; switch(format) { case InputFormat::BSON: return readSmallBsonFile(path); case InputFormat::JSON: return convertJsonArrayToBson(loadSmallFile(path)); default: throw runtime_error("Unknown format for '" + path.native() + "': somebody screwed up."); } } InputFormat getInputFormat(const string& desc, const string& format) { if("bson" == format) { return InputFormat::BSON; } else if("json" == format) { return InputFormat::JSON; } else { throw logic_error("Unknown " + desc + " format: '" + format + "'"); } } CommandLineStatus getInputFormats( const string& formatSpec, InputFormat& pipelineFormat, InputFormat& dataFormat) { auto delimIdx(formatSpec.find('-')); if(string::npos == delimIdx || formatSpec.size() < delimIdx+1) { cerr << "Invalid format: '" << formatSpec << "'"; return CommandLineStatus::INVALID_FORMAT; } pipelineFormat = getInputFormat( "pipeline", formatSpec.substr(0, delimIdx)); dataFormat = getInputFormat("data", formatSpec.substr(delimIdx+1)); return CommandLineStatus::OK; } CommandLineStatus checkForConflictingOptions( const po::variables_map& variables, const string& opt1, const string& opt2) { bool opt1Set(variables.count(opt1) && !variables[opt1].defaulted()), opt2Set(variables.count(opt2) && !variables[opt2].defaulted()); if (opt1Set && opt2Set) { cerr << "Conflicting options: '" << opt1 << "' and '" << opt2 << "'."; return CommandLineStatus::CONFLICTING_OPTIONS; } return CommandLineStatus::OK; } //Parse any command-line arguments. //This can throw if something really unexpected happens. CommandLineStatus parse_options( int argc, char** argv, char** env, BSONObj& pipeline, BSONObj& data) { po::options_description options("Options"); options.add_options() ("help", "Show usage") ("eval,e", po::value<string>(), "A JSON pipeline to evaluate.") ("pipeline,p", po::value<fs::path>(), "The path to a pipeline to evaluate.") ("data,d", po::value<fs::path>(), "The path to a data file to run the pipeline on.") ("format,f", po::value<string>()->default_value("bson-bson"), "Specifies the input and output format for --pipeline and --data, respectively. One of: bson-bson, json-json, json-bson, bson-json.") ; po::positional_options_description p; p.add("data", -1); po::variables_map variables; po::store(po::command_line_parser(argc, argv). options(options).positional(p).run(), variables); auto conflictCheck(checkForConflictingOptions(variables, "eval", "pipeline")); if(CommandLineStatus::OK != conflictCheck) { return conflictCheck; } po::notify(variables); if (variables.count("help")) { cout << options << "\n"; return CommandLineStatus::OK; } InputFormat pipelineFormat, dataFormat; auto formatsResult = getInputFormats( variables["format"].as<string>(), pipelineFormat, dataFormat ); if(CommandLineStatus::OK != formatsResult) { return formatsResult; } if (variables.count("eval")) { auto pipelineJson(variables["eval"].as<string>()); pipeline = convertJsonArrayToBson(pipelineJson); } else if(variables.count("pipeline")) { auto path(variables["pipeline"].as<fs::path>()); pipeline = loadFile(pipelineFormat, path); } else { cerr << "You must provide a pipeline via either --eval or --pipeline."; return CommandLineStatus::NO_PIPELINE; } if (variables.count("data")) { auto path(variables["data"].as<fs::path>()); data = loadFile(dataFormat, path); } else { //TODO: it might be nice to have a pipeline validation mode. cerr << "You must provide a data file."; return CommandLineStatus::NO_DATA_FILE; } return CommandLineStatus::OK; } namespace conduit { int conduit_main(int argc, char** argv, char** env) { try { const Status initResult(intialize_module(argc, argv, env)); if(!initResult.isOK()) { cerr << "Initialization failed: " << initResult.toString() << '\n'; return static_cast<int>( CommandLineStatus::FAILED_INITIALIZATION); } BSONObj data, pipeline; auto parseResult(parse_options(argc, argv, env, pipeline, data)); if(CommandLineStatus::OK != parseResult) { return static_cast<int>(parseResult); } if(CommandLineStatus::SHOWED_HELP != parseResult) { return 0; } conduit::Pipeline conduit(pipeline); mongo::BSONObjBuilder result; conduit(data, result); string jsonResult(result.obj().jsonString()); cout << jsonResult << '\n'; const Status deinitResult(deinitalize_module()); if(!deinitResult.isOK()) { cerr << "Initialization failed: " << initResult.toString() << '\n'; return static_cast<int>( CommandLineStatus::FAILED_DEINITIALIZATION); } return 0; } catch(exception& e) { std::cerr << e.what() << '\n'; //We're already toast, don't worry about whether this succeeds. deinitalize_module(); return static_cast<int>(CommandLineStatus::EXCEPTION_CAUGHT); } } } //namespace conduit. <|endoftext|>
<commit_before>#include "ofApp.h" //-------------------------------------------------------------- void ofApp::setup() { ofSetLogLevel(OF_LOG_NOTICE); ofDisableArbTex(); ofBackground(ofColor::black); ofImage image; image.setUseTexture(false); if (!image.load("testcard.png")) { ofLogError("ofApp::setup") << "Could not load image!"; return; } this->texture.enableMipmap(); this->texture.loadData(image.getPixels()); // Load warp settings from file if one exists. this->warpController.loadSettings("settings.json"); if (this->warpController.getWarps().empty()) { // Otherwise create warps from scratch. shared_ptr<ofxWarpBase> warp; warp = this->warpController.buildWarp<ofxWarpPerspective>(); warp->setSize(this->texture.getWidth(), this->texture.getHeight()); warp->setEdges(ofVec4f(0.0f, 0.0f, 1.0f, 1.0f)); warp = this->warpController.buildWarp<ofxWarpBilinear>(); warp->setSize(this->texture.getWidth(), this->texture.getHeight()); warp->setEdges(ofVec4f(1.0f, 0.0f, 0.0f, 1.0f)); warp = this->warpController.buildWarp<ofxWarpPerspectiveBilinear>(); warp->setSize(this->texture.getWidth(), this->texture.getHeight()); warp->setEdges(ofVec4f(0.0f, 1.0f, 0.0f, 0.0f)); warp = this->warpController.buildWarp<ofxWarpPerspectiveBilinear>(); warp->setSize(this->texture.getWidth(), this->texture.getHeight()); warp->setEdges(ofVec4f(0.0f, 1.0f, 1.0f, 0.0f)); } this->srcAreas.resize(this->warpController.getNumWarps()); // Start with full area mode. this->areaMode = -1; this->keyPressed('a'); this->useBeginEnd = false; } //-------------------------------------------------------------- void ofApp::exit() { this->warpController.saveSettings("settings.json"); } //-------------------------------------------------------------- void ofApp::update() { ofSetWindowTitle(ofToString(ofGetFrameRate(), 2) + " FPS :: " + areaName + " :: " + (this->useBeginEnd ? "begin()/end()" : "draw()")); } //-------------------------------------------------------------- void ofApp::draw() { ofBackground(ofColor::black); if (this->texture.isAllocated()) { for (auto i = 0; i < this->warpController.getNumWarps(); ++i) { auto warp = this->warpController.getWarp(i); if (this->useBeginEnd) { warp->begin(); auto bounds = warp->getBounds(); this->texture.drawSubsection(bounds.x, bounds.y, bounds.width, bounds.height, this->srcAreas[i].x, this->srcAreas[i].y, this->srcAreas[i].width, this->srcAreas[i].height); warp->end(); } else { warp->draw(this->texture, this->srcAreas[i]); } } } ostringstream oss; oss << ofToString(ofGetFrameRate(), 2) << " fps" << endl; oss << "[a]rea mode: " << areaName << endl; oss << "[d]raw mode: " << (this->useBeginEnd ? "begin()/end()" : "draw()") << endl; oss << "[w]arp edit: " << (this->warpController.getWarp(0)->isEditing() ? "on" : "off"); ofSetColor(ofColor::white); ofDrawBitmapStringHighlight(oss.str(), 10, 20); } //-------------------------------------------------------------- void ofApp::keyPressed(int key) { if (key == 'f') { ofToggleFullscreen(); } else if (key == 'a') { this->areaMode = (this->areaMode + 1) % 3; if (this->areaMode == 0) { // Draw the full image for each warp. auto area = ofRectangle(0, 0, this->texture.getWidth(), this->texture.getHeight()); for (auto i = 0; i < this->warpController.getNumWarps(); ++i) { this->srcAreas[i] = area; } this->areaName = "full"; } else if (this->areaMode == 1) { // Draw a corner region of the image so that all warps make up the entire image. for (auto i = 0; i < this->warpController.getNumWarps(); ++i) { static const auto overlap = 0; if (i == 0) { // Top-left. this->srcAreas[i] = ofRectangle(0, 0, this->texture.getWidth() * 0.5f + overlap, this->texture.getHeight() * 0.5f + overlap); } else if (i == 1) { // Top-right. this->srcAreas[i] = ofRectangle(this->texture.getWidth() * 0.5f - overlap, 0, this->texture.getWidth() * 0.5f + overlap, this->texture.getHeight() * 0.5f + overlap); } else if (i == 2) { // Bottom-right. this->srcAreas[i] = ofRectangle(this->texture.getWidth() * 0.5f - overlap, this->texture.getHeight() * 0.5f - overlap, this->texture.getWidth() * 0.5f + overlap, this->texture.getHeight() * 0.5f + overlap); } else { // Bottom-left. this->srcAreas[i] = ofRectangle(0, this->texture.getHeight() * 0.5f - overlap, this->texture.getWidth() * 0.5f + overlap, this->texture.getHeight() * 0.5f + overlap); } } this->areaName = "corners"; } else { // Draw a random region of the image for each warp. auto x1 = ofRandom(0, this->texture.getWidth() - 150); auto y1 = ofRandom(0, this->texture.getHeight() - 150); auto x2 = ofRandom(x1 + 150, this->texture.getWidth()); auto y2 = ofRandom(y1 + 150, this->texture.getHeight()); auto area = ofRectangle(x1, y1, x2 - x1, y2 - y1); for (auto i = 0; i < this->warpController.getNumWarps(); ++i) { this->srcAreas[i] = area; } this->areaName = "random"; } } else if (key == 'd') { this->useBeginEnd ^= 1; } } //-------------------------------------------------------------- void ofApp::keyReleased(int key){ } //-------------------------------------------------------------- void ofApp::mouseMoved(int x, int y){ } //-------------------------------------------------------------- void ofApp::mouseDragged(int x, int y, int button){ } //-------------------------------------------------------------- void ofApp::mousePressed(int x, int y, int button){ } //-------------------------------------------------------------- void ofApp::mouseReleased(int x, int y, int button){ } //-------------------------------------------------------------- void ofApp::mouseEntered(int x, int y){ } //-------------------------------------------------------------- void ofApp::mouseExited(int x, int y){ } //-------------------------------------------------------------- void ofApp::windowResized(int w, int h){ } //-------------------------------------------------------------- void ofApp::gotMessage(ofMessage msg){ } //-------------------------------------------------------------- void ofApp::dragEvent(ofDragInfo dragInfo){ } <commit_msg>Set the overlap in the example to something non-zero.<commit_after>#include "ofApp.h" //-------------------------------------------------------------- void ofApp::setup() { ofSetLogLevel(OF_LOG_NOTICE); ofDisableArbTex(); ofBackground(ofColor::black); ofImage image; image.setUseTexture(false); if (!image.load("testcard.png")) { ofLogError("ofApp::setup") << "Could not load image!"; return; } this->texture.enableMipmap(); this->texture.loadData(image.getPixels()); // Load warp settings from file if one exists. this->warpController.loadSettings("settings.json"); if (this->warpController.getWarps().empty()) { // Otherwise create warps from scratch. shared_ptr<ofxWarpBase> warp; warp = this->warpController.buildWarp<ofxWarpPerspective>(); warp->setSize(this->texture.getWidth(), this->texture.getHeight()); warp->setEdges(ofVec4f(0.0f, 0.0f, 1.0f, 1.0f)); warp = this->warpController.buildWarp<ofxWarpBilinear>(); warp->setSize(this->texture.getWidth(), this->texture.getHeight()); warp->setEdges(ofVec4f(1.0f, 0.0f, 0.0f, 1.0f)); warp = this->warpController.buildWarp<ofxWarpPerspectiveBilinear>(); warp->setSize(this->texture.getWidth(), this->texture.getHeight()); warp->setEdges(ofVec4f(0.0f, 1.0f, 0.0f, 0.0f)); warp = this->warpController.buildWarp<ofxWarpPerspectiveBilinear>(); warp->setSize(this->texture.getWidth(), this->texture.getHeight()); warp->setEdges(ofVec4f(0.0f, 1.0f, 1.0f, 0.0f)); } this->srcAreas.resize(this->warpController.getNumWarps()); // Start with full area mode. this->areaMode = -1; this->keyPressed('a'); this->useBeginEnd = false; } //-------------------------------------------------------------- void ofApp::exit() { this->warpController.saveSettings("settings.json"); } //-------------------------------------------------------------- void ofApp::update() { ofSetWindowTitle(ofToString(ofGetFrameRate(), 2) + " FPS :: " + areaName + " :: " + (this->useBeginEnd ? "begin()/end()" : "draw()")); } //-------------------------------------------------------------- void ofApp::draw() { ofBackground(ofColor::black); if (this->texture.isAllocated()) { for (auto i = 0; i < this->warpController.getNumWarps(); ++i) { auto warp = this->warpController.getWarp(i); if (this->useBeginEnd) { warp->begin(); auto bounds = warp->getBounds(); this->texture.drawSubsection(bounds.x, bounds.y, bounds.width, bounds.height, this->srcAreas[i].x, this->srcAreas[i].y, this->srcAreas[i].width, this->srcAreas[i].height); warp->end(); } else { warp->draw(this->texture, this->srcAreas[i]); } } } ostringstream oss; oss << ofToString(ofGetFrameRate(), 2) << " fps" << endl; oss << "[a]rea mode: " << areaName << endl; oss << "[d]raw mode: " << (this->useBeginEnd ? "begin()/end()" : "draw()") << endl; oss << "[w]arp edit: " << (this->warpController.getWarp(0)->isEditing() ? "on" : "off"); ofSetColor(ofColor::white); ofDrawBitmapStringHighlight(oss.str(), 10, 20); } //-------------------------------------------------------------- void ofApp::keyPressed(int key) { if (key == 'f') { ofToggleFullscreen(); } else if (key == 'a') { this->areaMode = (this->areaMode + 1) % 3; if (this->areaMode == 0) { // Draw the full image for each warp. auto area = ofRectangle(0, 0, this->texture.getWidth(), this->texture.getHeight()); for (auto i = 0; i < this->warpController.getNumWarps(); ++i) { this->srcAreas[i] = area; } this->areaName = "full"; } else if (this->areaMode == 1) { // Draw a corner region of the image so that all warps make up the entire image. for (auto i = 0; i < this->warpController.getNumWarps(); ++i) { static const auto overlap = 10.0f; if (i == 0) { // Top-left. this->srcAreas[i] = ofRectangle(0, 0, this->texture.getWidth() * 0.5f + overlap, this->texture.getHeight() * 0.5f + overlap); } else if (i == 1) { // Top-right. this->srcAreas[i] = ofRectangle(this->texture.getWidth() * 0.5f - overlap, 0, this->texture.getWidth() * 0.5f + overlap, this->texture.getHeight() * 0.5f + overlap); } else if (i == 2) { // Bottom-right. this->srcAreas[i] = ofRectangle(this->texture.getWidth() * 0.5f - overlap, this->texture.getHeight() * 0.5f - overlap, this->texture.getWidth() * 0.5f + overlap, this->texture.getHeight() * 0.5f + overlap); } else { // Bottom-left. this->srcAreas[i] = ofRectangle(0, this->texture.getHeight() * 0.5f - overlap, this->texture.getWidth() * 0.5f + overlap, this->texture.getHeight() * 0.5f + overlap); } } this->areaName = "corners"; } else { // Draw a random region of the image for each warp. auto x1 = ofRandom(0, this->texture.getWidth() - 150); auto y1 = ofRandom(0, this->texture.getHeight() - 150); auto x2 = ofRandom(x1 + 150, this->texture.getWidth()); auto y2 = ofRandom(y1 + 150, this->texture.getHeight()); auto area = ofRectangle(x1, y1, x2 - x1, y2 - y1); for (auto i = 0; i < this->warpController.getNumWarps(); ++i) { this->srcAreas[i] = area; } this->areaName = "random"; } } else if (key == 'd') { this->useBeginEnd ^= 1; } } //-------------------------------------------------------------- void ofApp::keyReleased(int key){ } //-------------------------------------------------------------- void ofApp::mouseMoved(int x, int y){ } //-------------------------------------------------------------- void ofApp::mouseDragged(int x, int y, int button){ } //-------------------------------------------------------------- void ofApp::mousePressed(int x, int y, int button){ } //-------------------------------------------------------------- void ofApp::mouseReleased(int x, int y, int button){ } //-------------------------------------------------------------- void ofApp::mouseEntered(int x, int y){ } //-------------------------------------------------------------- void ofApp::mouseExited(int x, int y){ } //-------------------------------------------------------------- void ofApp::windowResized(int w, int h){ } //-------------------------------------------------------------- void ofApp::gotMessage(ofMessage msg){ } //-------------------------------------------------------------- void ofApp::dragEvent(ofDragInfo dragInfo){ } <|endoftext|>
<commit_before><commit_msg>Better RTL debug start/stop in MpMisc.<commit_after><|endoftext|>
<commit_before>#ifndef LINEARALGEBRA_HH #define LINEARALGEBRA_HH #define LA_COMPLEX_SUPPORT #include "lapackpp.h" #include "HCL_Rn_d.h" typedef LaGenMatDouble Matrix; typedef LaVectorDouble Vector; typedef LaSymmMatDouble SymmetricMatrix; /** Functions for matrix operations */ namespace LinearAlgebra { //!< A assumed symmetric positive definite! double spd_log_determinant(const Matrix &A); //!< A assumed symmetric positive definite! double spd_determinant(const Matrix &A); //!< A assumed symmetric! double log_determinant(const Matrix &A); //!< A assumed symmetric! double determinant(const Matrix &A); void matrix_power(const Matrix &A, Matrix &B, double power); void cholesky_factor(const Matrix &A, Matrix &B); //!< A assumed symmetric, B symmetric positive definite! void generalized_eigenvalues(const Matrix &A, const Matrix &B, Vector &eigvals, Matrix &eigvecs); //!< B assumed symmetric positive definite! void generalized_eigenvalues(const Matrix &A, const Matrix &B, LaVectorComplex &eigvals, LaGenMatComplex &eigvecs); void map_m2v(const Matrix &m, Vector &v); void map_v2m(const Vector &v, Matrix &m); void map_hclv2lapackm(const HCL_RnVector_d &hcl_v, Matrix &lapack_m); void map_lapackm2hclv(const Matrix &lapack_m, HCL_RnVector_d &hcl_v); double cond(const Matrix &m); bool is_spd(const Matrix &m); bool is_singular(const Matrix &m); void force_min_eig(Matrix &m, double min_eig); void inverse(const Matrix &m, Matrix &inv); }; #endif /* LINEARALGEBRA_HH */ <commit_msg>an important comment<commit_after>#ifndef LINEARALGEBRA_HH #define LINEARALGEBRA_HH #define LA_COMPLEX_SUPPORT #include "lapackpp.h" #include "HCL_Rn_d.h" typedef LaGenMatDouble Matrix; typedef LaVectorDouble Vector; typedef LaSymmMatDouble SymmetricMatrix; /** Functions for matrix operations */ namespace LinearAlgebra { //!< A assumed symmetric positive definite! double spd_log_determinant(const Matrix &A); //!< A assumed symmetric positive definite! double spd_determinant(const Matrix &A); //!< A assumed symmetric! double log_determinant(const Matrix &A); //!< A assumed symmetric! double determinant(const Matrix &A); void matrix_power(const Matrix &A, Matrix &B, double power); // Computes the lower triangular Cholesky matrix //!< A assumed symmetric positive definite void cholesky_factor(const Matrix &A, Matrix &B); //!< A assumed symmetric, B symmetric positive definite! void generalized_eigenvalues(const Matrix &A, const Matrix &B, Vector &eigvals, Matrix &eigvecs); //!< B assumed symmetric positive definite! void generalized_eigenvalues(const Matrix &A, const Matrix &B, LaVectorComplex &eigvals, LaGenMatComplex &eigvecs); void map_m2v(const Matrix &m, Vector &v); void map_v2m(const Vector &v, Matrix &m); void map_hclv2lapackm(const HCL_RnVector_d &hcl_v, Matrix &lapack_m); void map_lapackm2hclv(const Matrix &lapack_m, HCL_RnVector_d &hcl_v); double cond(const Matrix &m); bool is_spd(const Matrix &m); bool is_singular(const Matrix &m); void force_min_eig(Matrix &m, double min_eig); void inverse(const Matrix &m, Matrix &inv); }; #endif /* LINEARALGEBRA_HH */ <|endoftext|>
<commit_before>//----------------------------------------------- // // This file is part of the Siv3D Engine. // // Copyright (c) 2008-2019 Ryo Suzuki // Copyright (c) 2016-2019 OpenSiv3D Project // // Licensed under the MIT License. // //----------------------------------------------- # pragma once # include "Duration.hpp" # include "Easing.hpp" # include "Scene.hpp" namespace s3d { class Transition { private: double m_inDuration = 0.0; double m_outDuration = 0.0; double m_value = 0.0; public: explicit constexpr Transition(const Duration& inDuration = SecondsF(0.2), const Duration& outDuration = SecondsF(0.1), double initialValue = 0.0) noexcept : m_inDuration(static_cast<double>(inDuration.count())) , m_outDuration(static_cast<double>(outDuration.count())) , m_value(initialValue) {} void update(bool in, double deltaSec = Scene::DeltaTime()); [[nodiscard]] constexpr double value() const noexcept { return m_value; } [[nodiscard]] constexpr double easeIn(double easingFunction(double) = Easing::Quart) const { return EaseIn(easingFunction, m_value); } [[nodiscard]] constexpr double easeOut(double easingFunction(double) = Easing::Quart) const { return EaseOut(easingFunction, m_value); } [[nodiscard]] constexpr double easeInOut(double easingFunction(double) = Easing::Quart) const { return EaseInOut(easingFunction, m_value); } }; } <commit_msg>Transition::isZero(), isOne()<commit_after>//----------------------------------------------- // // This file is part of the Siv3D Engine. // // Copyright (c) 2008-2019 Ryo Suzuki // Copyright (c) 2016-2019 OpenSiv3D Project // // Licensed under the MIT License. // //----------------------------------------------- # pragma once # include "Duration.hpp" # include "Easing.hpp" # include "Scene.hpp" namespace s3d { class Transition { private: double m_inDuration = 0.0; double m_outDuration = 0.0; double m_value = 0.0; public: explicit constexpr Transition(const Duration& inDuration = SecondsF(0.2), const Duration& outDuration = SecondsF(0.1), double initialValue = 0.0) noexcept : m_inDuration(static_cast<double>(inDuration.count())) , m_outDuration(static_cast<double>(outDuration.count())) , m_value(initialValue) {} void update(bool in, double deltaSec = Scene::DeltaTime()); [[nodiscard]] constexpr double value() const noexcept { return m_value; } [[nodiscard]] constexpr bool isZero() const noexcept { return (m_value == 0.0); } [[nodiscard]] constexpr bool isOne() const noexcept { return (m_value == 1.0); } [[nodiscard]] constexpr double easeIn(double easingFunction(double) = Easing::Quart) const { return EaseIn(easingFunction, m_value); } [[nodiscard]] constexpr double easeOut(double easingFunction(double) = Easing::Quart) const { return EaseOut(easingFunction, m_value); } [[nodiscard]] constexpr double easeInOut(double easingFunction(double) = Easing::Quart) const { return EaseInOut(easingFunction, m_value); } }; } <|endoftext|>
<commit_before>#include <pybind11/embed.h> #include <iostream> #include "term_window.h" #include "draw_pane.h" #include <wx/dcbuffer.h> #include "term_context.h" #include "term_buffer.h" #include "term_line.h" #include "term_cell.h" #include "term_network.h" #include "color_theme.h" #include <bitset> extern wxCoord PADDING; class __DCAttributesChanger { public: __DCAttributesChanger(wxDC * pdc) : m_pDC(pdc) , back(pdc->GetBackground()) , txt_fore(pdc->GetTextForeground()) , txt_back(pdc->GetTextBackground()) { } ~__DCAttributesChanger() { m_pDC->SetTextForeground(txt_fore); m_pDC->SetTextBackground(txt_back); m_pDC->SetBackground(back); } wxDC * m_pDC; const wxBrush & back; const wxColour & txt_fore; const wxColour & txt_back; }; void DrawPane::DrawContent(wxDC &dc, wxString & content, uint16_t & last_fore_color, uint16_t & last_back_color, uint16_t & last_mode, uint16_t fore_color, uint16_t back_color, uint16_t mode, wxCoord & last_x, wxCoord & last_y, wxCoord y) { wxSize content_size = dc.GetTextExtent(content); bool multi_line = content.Find('\n', true) > 0; wxSize content_last_line_size {0, 0}; wxSize content_before_last_line_size {0, 0}; std::bitset<16> m(last_mode); if (multi_line) { content_last_line_size = dc.GetTextExtent(content.AfterLast('\n')); content_before_last_line_size.SetHeight(content_size.GetHeight() - content_last_line_size.GetHeight()); content_before_last_line_size.SetWidth(content_size.GetWidth()); } if (last_back_color != TermCell::DefaultBackColorIndex || m.test(TermCell::Cursor)) { wxBrush brush(m_ColorTable[m.test(TermCell::Cursor) ? (uint16_t)TermCell::DefaultCursorColorIndex : last_back_color]); dc.SetBrush(brush); dc.SetPen(wxPen(m_ColorTable[m.test(TermCell::Cursor) ? (uint16_t)TermCell::DefaultCursorColorIndex : last_back_color])); if (multi_line) { dc.DrawRectangle(wxPoint(last_x, last_y), content_before_last_line_size); dc.DrawRectangle(wxPoint(PADDING, last_y + content_before_last_line_size.GetHeight()), content_last_line_size); } else { dc.DrawRectangle(wxPoint(last_x, last_y), content_size); } } dc.SetTextForeground(m_ColorTable[last_fore_color]); dc.SetTextBackground(m_ColorTable[last_back_color]); dc.DrawText(content, last_x, last_y); if (multi_line) { last_x = PADDING + content_last_line_size.GetWidth(); } else { last_x += content_size.GetWidth(); } last_y = y; content.Clear(); last_fore_color = fore_color; last_back_color = back_color; last_mode = mode; } void DrawPane::CalculateClipRegion(wxRegion & clipRegion, TermBufferPtr buffer) { wxRect clientSize = GetClientSize(); clipRegion.Union(clientSize); auto rows = buffer->GetRows(); for (auto row = 0u; row < rows; row++) { auto line = buffer->GetLine(row); if (!clipRegion.IsEmpty() && row == line->GetLastRenderLineIndex() && !line->IsModified()) { wxRect rowRect(0, PADDING + row * m_LineHeight, clientSize.GetWidth(), m_LineHeight); clipRegion.Subtract(rowRect); } } } void DrawPane::DoPaint(wxDC & dc, TermBufferPtr buffer, bool full_paint) { __DCAttributesChanger changer(&dc); wxBrush backgroundBrush(m_ColorTable[TermCell::DefaultBackColorIndex]); wxString content {""}; wxDCFontChanger fontChanger(dc, *GetFont()); auto rows = buffer->GetRows(); auto cols = buffer->GetCols(); auto y = PADDING; uint16_t last_fore_color = TermCell::DefaultForeColorIndex; uint16_t last_back_color = TermCell::DefaultBackColorIndex; wxCoord last_y = PADDING; wxCoord last_x = PADDING; uint16_t last_mode = 0; dc.SetBackground( backgroundBrush ); dc.Clear(); for (auto row = 0u; row < rows; row++) { auto line = buffer->GetLine(row); if (!full_paint && row == line->GetLastRenderLineIndex() && !line->IsModified()) { y += m_LineHeight; if (content.Length() > 0) { DrawContent(dc, content, last_fore_color, last_back_color, last_mode, TermCell::DefaultForeColorIndex, TermCell::DefaultBackColorIndex, 0, last_x, last_y, y); } last_x = PADDING; last_y = y; continue; } line->SetLastRenderLineIndex(row); line->SetModified(false); for (auto col = 0u; col < cols; col++) { auto cell = line->GetCell(col); wchar_t ch = 0; uint16_t fore_color = TermCell::DefaultForeColorIndex; uint16_t back_color = TermCell::DefaultBackColorIndex; uint16_t mode = 0; if (cell && cell->GetChar() != 0) { fore_color = cell->GetForeColorIndex(); back_color = cell->GetBackColorIndex(); mode = cell->GetMode(); ch = cell->GetChar(); } else if (!cell) { ch = ' '; } if (ch != 0) { if (last_fore_color != fore_color || last_back_color != back_color || last_mode != mode) { DrawContent(dc, content, last_fore_color, last_back_color, last_mode, fore_color, back_color, mode, last_x, last_y, y); } content.append(ch); } } y += m_LineHeight; if (last_x == PADDING) { if (row != rows - 1) content.append("\n"); } else if (content.Length() > 0) { DrawContent(dc, content, last_fore_color, last_back_color, last_mode, TermCell::DefaultForeColorIndex, TermCell::DefaultBackColorIndex, 0, last_x, last_y, y); last_x = PADDING; last_y = y; } } if (content.Length() > 0) { dc.SetTextForeground(m_ColorTable[last_fore_color]); dc.SetTextBackground(m_ColorTable[last_back_color]); dc.DrawText(content, last_x, last_y); } } <commit_msg>handle reverse and cusor mode<commit_after>#include <pybind11/embed.h> #include <iostream> #include "term_window.h" #include "draw_pane.h" #include <wx/dcbuffer.h> #include "term_context.h" #include "term_buffer.h" #include "term_line.h" #include "term_cell.h" #include "term_network.h" #include "color_theme.h" #include <bitset> extern wxCoord PADDING; class __DCAttributesChanger { public: __DCAttributesChanger(wxDC * pdc) : m_pDC(pdc) , back(pdc->GetBackground()) , txt_fore(pdc->GetTextForeground()) , txt_back(pdc->GetTextBackground()) { } ~__DCAttributesChanger() { m_pDC->SetTextForeground(txt_fore); m_pDC->SetTextBackground(txt_back); m_pDC->SetBackground(back); } wxDC * m_pDC; const wxBrush & back; const wxColour & txt_fore; const wxColour & txt_back; }; void DrawPane::DrawContent(wxDC &dc, wxString & content, uint16_t & last_fore_color, uint16_t & last_back_color, uint16_t & last_mode, uint16_t fore_color, uint16_t back_color, uint16_t mode, wxCoord & last_x, wxCoord & last_y, wxCoord y) { wxSize content_size = dc.GetTextExtent(content); bool multi_line = content.Find('\n', true) > 0; wxSize content_last_line_size {0, 0}; wxSize content_before_last_line_size {0, 0}; std::bitset<16> m(last_mode); if (multi_line) { content_last_line_size = dc.GetTextExtent(content.AfterLast('\n')); content_before_last_line_size.SetHeight(content_size.GetHeight() - content_last_line_size.GetHeight()); content_before_last_line_size.SetWidth(content_size.GetWidth()); } uint16_t back_color_use = last_back_color; uint16_t fore_color_use = last_fore_color; if (m.test(TermCell::Cursor)) { back_color_use = TermCell::DefaultCursorColorIndex; fore_color_use = last_back_color; } if (m.test(TermCell::Reverse)) { uint16_t tmp = back_color_use; back_color_use = fore_color_use; fore_color_use = tmp; } if (back_color_use != TermCell::DefaultBackColorIndex) { wxBrush brush(m_ColorTable[back_color_use]); dc.SetBrush(brush); dc.SetPen(wxPen(m_ColorTable[back_color_use])); if (multi_line) { dc.DrawRectangle(wxPoint(last_x, last_y), content_before_last_line_size); dc.DrawRectangle(wxPoint(PADDING, last_y + content_before_last_line_size.GetHeight()), content_last_line_size); } else { dc.DrawRectangle(wxPoint(last_x, last_y), content_size); } } dc.SetTextForeground(m_ColorTable[fore_color_use]); dc.SetTextBackground(m_ColorTable[back_color_use]); dc.DrawText(content, last_x, last_y); if (multi_line) { last_x = PADDING + content_last_line_size.GetWidth(); } else { last_x += content_size.GetWidth(); } last_y = y; content.Clear(); last_fore_color = fore_color; last_back_color = back_color; last_mode = mode; } void DrawPane::CalculateClipRegion(wxRegion & clipRegion, TermBufferPtr buffer) { wxRect clientSize = GetClientSize(); clipRegion.Union(clientSize); auto rows = buffer->GetRows(); for (auto row = 0u; row < rows; row++) { auto line = buffer->GetLine(row); if (!clipRegion.IsEmpty() && row == line->GetLastRenderLineIndex() && !line->IsModified()) { wxRect rowRect(0, PADDING + row * m_LineHeight, clientSize.GetWidth(), m_LineHeight); clipRegion.Subtract(rowRect); } } } void DrawPane::DoPaint(wxDC & dc, TermBufferPtr buffer, bool full_paint) { __DCAttributesChanger changer(&dc); wxBrush backgroundBrush(m_ColorTable[TermCell::DefaultBackColorIndex]); wxString content {""}; wxDCFontChanger fontChanger(dc, *GetFont()); auto rows = buffer->GetRows(); auto cols = buffer->GetCols(); auto y = PADDING; uint16_t last_fore_color = TermCell::DefaultForeColorIndex; uint16_t last_back_color = TermCell::DefaultBackColorIndex; wxCoord last_y = PADDING; wxCoord last_x = PADDING; uint16_t last_mode = 0; dc.SetBackground( backgroundBrush ); dc.Clear(); for (auto row = 0u; row < rows; row++) { auto line = buffer->GetLine(row); if (!full_paint && row == line->GetLastRenderLineIndex() && !line->IsModified()) { y += m_LineHeight; if (content.Length() > 0) { DrawContent(dc, content, last_fore_color, last_back_color, last_mode, TermCell::DefaultForeColorIndex, TermCell::DefaultBackColorIndex, 0, last_x, last_y, y); } last_x = PADDING; last_y = y; continue; } line->SetLastRenderLineIndex(row); line->SetModified(false); for (auto col = 0u; col < cols; col++) { auto cell = line->GetCell(col); wchar_t ch = 0; uint16_t fore_color = TermCell::DefaultForeColorIndex; uint16_t back_color = TermCell::DefaultBackColorIndex; uint16_t mode = 0; if (cell && cell->GetChar() != 0) { fore_color = cell->GetForeColorIndex(); back_color = cell->GetBackColorIndex(); mode = cell->GetMode(); ch = cell->GetChar(); } else if (!cell) { ch = ' '; } if (ch != 0) { if (last_fore_color != fore_color || last_back_color != back_color || last_mode != mode) { DrawContent(dc, content, last_fore_color, last_back_color, last_mode, fore_color, back_color, mode, last_x, last_y, y); } content.append(ch); } } y += m_LineHeight; if (last_x == PADDING) { if (row != rows - 1) content.append("\n"); } else if (content.Length() > 0) { DrawContent(dc, content, last_fore_color, last_back_color, last_mode, TermCell::DefaultForeColorIndex, TermCell::DefaultBackColorIndex, 0, last_x, last_y, y); last_x = PADDING; last_y = y; } } if (content.Length() > 0) { dc.SetTextForeground(m_ColorTable[last_fore_color]); dc.SetTextBackground(m_ColorTable[last_back_color]); dc.DrawText(content, last_x, last_y); } } <|endoftext|>
<commit_before>// Copyright (C) 2016 Elviss Strazdins // This file is part of the Ouzel engine. #include <algorithm> #include "Engine.h" #include "CompileConfig.h" #include "Cache.h" #if defined(OUZEL_SUPPORTS_OPENGL) || defined(OUZEL_SUPPORTS_OPENGLES) #include "RendererOGL.h" #endif #if defined(SUPPORTS_DIRECT3D11) #include "RendererD3D11.h" #endif #include "Utils.h" #include "Renderer.h" #include "FileSystem.h" #if defined(OUZEL_PLATFORM_OSX) || defined(OUZEL_PLATFORM_IOS) || defined(OUZEL_PLATFORM_TVOS) #include "InputApple.h" #elif defined(OUZEL_PLATFORM_WINDOWS) #include "InputWin.h" #endif ouzel::AppPtr ouzelMain(const std::vector<std::string>& args); namespace ouzel { static EnginePtr sharedEngine; EnginePtr Engine::getInstance() { if (!sharedEngine) { sharedEngine.reset(new Engine()); } return sharedEngine; } Engine::Engine() { } Engine::~Engine() { } void Engine::setArgs(const std::vector<std::string>& args) { _args = args; } std::set<Renderer::Driver> Engine::getAvailableDrivers() const { std::set<Renderer::Driver> availableDrivers; #if defined(OUZEL_SUPPORTS_OPENGL) || defined(OUZEL_SUPPORTS_OPENGLES) availableDrivers.insert(Renderer::Driver::OPENGL); #elif defined(SUPPORTS_DIRECT3D11) availableDrivers.insert(Renderer::Driver::DIRECT3D11); #endif return availableDrivers; } bool Engine::init() { _app = ouzelMain(_args); if (!_app) { return false; } Settings settings = _app->getSettings(); _targetFPS = settings.targetFPS; #if defined(OUZEL_PLATFORM_OSX) || defined(OUZEL_PLATFORM_IOS) || defined(OUZEL_PLATFORM_TVOS) settings.driver = Renderer::Driver::OPENGL; #elif defined(SUPPORTS_DIRECT3D11) settings.driver = Renderer::Driver::DIRECT3D11; #endif _eventDispatcher.reset(new EventDispatcher()); _cache.reset(new Cache()); _fileSystem.reset(new FileSystem()); _sceneManager.reset(new SceneManager()); #if defined(OUZEL_PLATFORM_OSX) || defined(OUZEL_PLATFORM_IOS) || defined(OUZEL_PLATFORM_TVOS) _input.reset(new InputApple()); #elif defined(OUZEL_PLATFORM_WINDOWS) _input.reset(new InputWin()); #else _input.reset(new Input()); #endif switch (settings.driver) { #if defined(OUZEL_SUPPORTS_OPENGL) || defined(OUZEL_SUPPORTS_OPENGLES) case Renderer::Driver::OPENGL: _renderer.reset(new RendererOGL()); break; #endif #if defined(SUPPORTS_DIRECT3D11) case Renderer::Driver::DIRECT3D11: _renderer.reset(new RendererD3D11()); break; #endif default: _renderer.reset(new Renderer()); break; } if (!_renderer->init(settings.size, settings.resizable, settings.fullscreen, settings.driver)) { return false; } _previousFrameTime = getCurrentMicroSeconds(); return true; } void Engine::exit() { _active = false; } void Engine::begin() { _app->begin(); } void Engine::end() { _app.reset(); // remove the active scene _sceneManager->setScene(ScenePtr()); _cache.reset(); } bool Engine::run() { uint64_t currentTime = getCurrentMicroSeconds(); float delta = static_cast<float>((currentTime - _previousFrameTime)) / 1000000.0f; _previousFrameTime = currentTime; _currentFPS = 1.0f / delta; _input->update(); _eventDispatcher->update(); lock(); for (const UpdateCallbackPtr& updateCallback : _updateCallbacks) { if (!updateCallback->_remove) { updateCallback->callback(delta); } } unlock(); _renderer->clear(); _sceneManager->draw(); _renderer->present(); return _active; } void Engine::scheduleUpdate(const UpdateCallbackPtr& callback) { if (_locked) { _updateCallbackAddList.insert(callback); } else { std::vector<UpdateCallbackPtr>::iterator i = std::find(_updateCallbacks.begin(), _updateCallbacks.end(), callback); if (i == _updateCallbacks.end()) { callback->_remove = false; _updateCallbacks.push_back(callback); } } } void Engine::unscheduleUpdate(const UpdateCallbackPtr& callback) { if (_locked) { callback->_remove = true; _updateCallbackRemoveList.insert(callback); } else { std::vector<UpdateCallbackPtr>::iterator i = std::find(_updateCallbacks.begin(), _updateCallbacks.end(), callback); if (i != _updateCallbacks.end()) { _updateCallbacks.erase(i); } } } void Engine::lock() { ++_locked; } void Engine::unlock() { if (--_locked == 0) { if (!_updateCallbackAddList.empty()) { for (const UpdateCallbackPtr& updateCallback : _updateCallbackAddList) { scheduleUpdate(updateCallback); } _updateCallbackAddList.clear(); } if (!_updateCallbackRemoveList.empty()) { for (const UpdateCallbackPtr& updateCallback : _updateCallbackRemoveList) { unscheduleUpdate(updateCallback); } _updateCallbackRemoveList.clear(); } } } } <commit_msg>Call update only if update callback is set<commit_after>// Copyright (C) 2016 Elviss Strazdins // This file is part of the Ouzel engine. #include <algorithm> #include "Engine.h" #include "CompileConfig.h" #include "Cache.h" #if defined(OUZEL_SUPPORTS_OPENGL) || defined(OUZEL_SUPPORTS_OPENGLES) #include "RendererOGL.h" #endif #if defined(SUPPORTS_DIRECT3D11) #include "RendererD3D11.h" #endif #include "Utils.h" #include "Renderer.h" #include "FileSystem.h" #if defined(OUZEL_PLATFORM_OSX) || defined(OUZEL_PLATFORM_IOS) || defined(OUZEL_PLATFORM_TVOS) #include "InputApple.h" #elif defined(OUZEL_PLATFORM_WINDOWS) #include "InputWin.h" #endif ouzel::AppPtr ouzelMain(const std::vector<std::string>& args); namespace ouzel { static EnginePtr sharedEngine; EnginePtr Engine::getInstance() { if (!sharedEngine) { sharedEngine.reset(new Engine()); } return sharedEngine; } Engine::Engine() { } Engine::~Engine() { } void Engine::setArgs(const std::vector<std::string>& args) { _args = args; } std::set<Renderer::Driver> Engine::getAvailableDrivers() const { std::set<Renderer::Driver> availableDrivers; #if defined(OUZEL_SUPPORTS_OPENGL) || defined(OUZEL_SUPPORTS_OPENGLES) availableDrivers.insert(Renderer::Driver::OPENGL); #elif defined(SUPPORTS_DIRECT3D11) availableDrivers.insert(Renderer::Driver::DIRECT3D11); #endif return availableDrivers; } bool Engine::init() { _app = ouzelMain(_args); if (!_app) { return false; } Settings settings = _app->getSettings(); _targetFPS = settings.targetFPS; #if defined(OUZEL_PLATFORM_OSX) || defined(OUZEL_PLATFORM_IOS) || defined(OUZEL_PLATFORM_TVOS) settings.driver = Renderer::Driver::OPENGL; #elif defined(SUPPORTS_DIRECT3D11) settings.driver = Renderer::Driver::DIRECT3D11; #endif _eventDispatcher.reset(new EventDispatcher()); _cache.reset(new Cache()); _fileSystem.reset(new FileSystem()); _sceneManager.reset(new SceneManager()); #if defined(OUZEL_PLATFORM_OSX) || defined(OUZEL_PLATFORM_IOS) || defined(OUZEL_PLATFORM_TVOS) _input.reset(new InputApple()); #elif defined(OUZEL_PLATFORM_WINDOWS) _input.reset(new InputWin()); #else _input.reset(new Input()); #endif switch (settings.driver) { #if defined(OUZEL_SUPPORTS_OPENGL) || defined(OUZEL_SUPPORTS_OPENGLES) case Renderer::Driver::OPENGL: _renderer.reset(new RendererOGL()); break; #endif #if defined(SUPPORTS_DIRECT3D11) case Renderer::Driver::DIRECT3D11: _renderer.reset(new RendererD3D11()); break; #endif default: _renderer.reset(new Renderer()); break; } if (!_renderer->init(settings.size, settings.resizable, settings.fullscreen, settings.driver)) { return false; } _previousFrameTime = getCurrentMicroSeconds(); return true; } void Engine::exit() { _active = false; } void Engine::begin() { _app->begin(); } void Engine::end() { _app.reset(); // remove the active scene _sceneManager->setScene(ScenePtr()); _cache.reset(); } bool Engine::run() { uint64_t currentTime = getCurrentMicroSeconds(); float delta = static_cast<float>((currentTime - _previousFrameTime)) / 1000000.0f; _previousFrameTime = currentTime; _currentFPS = 1.0f / delta; _input->update(); _eventDispatcher->update(); lock(); for (const UpdateCallbackPtr& updateCallback : _updateCallbacks) { if (!updateCallback->_remove && updateCallback->callback) { updateCallback->callback(delta); } } unlock(); _renderer->clear(); _sceneManager->draw(); _renderer->present(); return _active; } void Engine::scheduleUpdate(const UpdateCallbackPtr& callback) { if (_locked) { _updateCallbackAddList.insert(callback); } else { std::vector<UpdateCallbackPtr>::iterator i = std::find(_updateCallbacks.begin(), _updateCallbacks.end(), callback); if (i == _updateCallbacks.end()) { callback->_remove = false; _updateCallbacks.push_back(callback); } } } void Engine::unscheduleUpdate(const UpdateCallbackPtr& callback) { if (_locked) { callback->_remove = true; _updateCallbackRemoveList.insert(callback); } else { std::vector<UpdateCallbackPtr>::iterator i = std::find(_updateCallbacks.begin(), _updateCallbacks.end(), callback); if (i != _updateCallbacks.end()) { _updateCallbacks.erase(i); } } } void Engine::lock() { ++_locked; } void Engine::unlock() { if (--_locked == 0) { if (!_updateCallbackAddList.empty()) { for (const UpdateCallbackPtr& updateCallback : _updateCallbackAddList) { scheduleUpdate(updateCallback); } _updateCallbackAddList.clear(); } if (!_updateCallbackRemoveList.empty()) { for (const UpdateCallbackPtr& updateCallback : _updateCallbackRemoveList) { unscheduleUpdate(updateCallback); } _updateCallbackRemoveList.clear(); } } } } <|endoftext|>
<commit_before>/************************************************************************* * * OpenOffice.org - a multi-platform office productivity suite * * $RCSfile: metafunctions.hxx,v $ * * $Revision: 1.7 $ * * last change: $Author: thb $ $Date: 2006-07-13 12:03:25 $ * * 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 INCLUDED_BASEBMP_METAFUNCTIONS_HXX #define INCLUDED_BASEBMP_METAFUNCTIONS_HXX #include <boost/mpl/integral_c.hpp> #include <vigra/metaprogramming.hxx> #include <vigra/numerictraits.hxx> namespace basebmp { // TODO(Q3): move to generic place (o3tl?) /** template meta function: add const qualifier to 2nd type, if given 1st type has it */ template<typename A, typename B> struct clone_const { typedef B type; }; template<typename A, typename B> struct clone_const<const A,B> { typedef const B type; }; /** template meta function: add const qualifier to plain type (if not already there) */ template <typename T> struct add_const { typedef const T type; }; template <typename T> struct add_const<const T> { typedef const T type; }; /// template meta function: remove const qualifier from plain type template <typename T> struct remove_const { typedef T type; }; template <typename T> struct remove_const<const T> { typedef T type; }; //-------------------------------------------------------------- /// Base class for an adaptable ternary functor template< typename A1, typename A2, typename A3, typename R > struct TernaryFunctorBase { typedef A1 first_argument_type; typedef A2 second_argument_type; typedef A3 third_argument_type; typedef R result_type; }; //-------------------------------------------------------------- /** template meta function: ensure that given integer type is unsigned If given integer type is already unsigned, return as-is - otherwise, convert to unsigned type of same or greater range. */ template< typename T > struct make_unsigned; #define BASEBMP_MAKE_UNSIGNED(T,U) \ template<> struct make_unsigned<T> { \ typedef U type; \ }; BASEBMP_MAKE_UNSIGNED(signed char,unsigned char) BASEBMP_MAKE_UNSIGNED(unsigned char,unsigned char) BASEBMP_MAKE_UNSIGNED(short,unsigned short) BASEBMP_MAKE_UNSIGNED(unsigned short,unsigned short) BASEBMP_MAKE_UNSIGNED(int,unsigned int) BASEBMP_MAKE_UNSIGNED(unsigned int,unsigned int) BASEBMP_MAKE_UNSIGNED(long,unsigned long) BASEBMP_MAKE_UNSIGNED(unsigned long,unsigned long) #undef BASEBMP_MAKE_UNSIGNED /// cast integer to unsigned type of similar size template< typename T > inline typename make_unsigned<T>::type unsigned_cast( T value ) { return static_cast< typename make_unsigned<T>::type >(value); } //-------------------------------------------------------------- /// returns true, if given number is strictly less than 0 template< typename T > inline bool is_negative( T x ) { return x < 0; } /// Overload for ints (branch-free) inline bool is_negative( int x ) { // force logic shift (result for signed shift right is undefined) return static_cast<unsigned int>(x) >> (sizeof(int)*8-1); } //-------------------------------------------------------------- /// Results in VigraTrueType, if T is of integer type and scalar template< typename T, typename trueCase, typename falseCase > struct ifScalarIntegral { typedef typename vigra::If< typename vigra::NumericTraits< T >::isIntegral, typename vigra::If< typename vigra::NumericTraits< T >::isScalar, trueCase, falseCase >::type, falseCase >::type type; }; /// Results in VigraTrueType, if T is of non-integer type and scalar template< typename T, typename trueCase, typename falseCase > struct ifScalarNonIntegral { typedef typename vigra::If< typename vigra::NumericTraits< T >::isIntegral, falseCase, typename vigra::If< typename vigra::NumericTraits< T >::isScalar, trueCase, falseCase >::type >::type type; }; /// Results in VigraTrueType, if both T1 and T2 are of integer type and scalar template< typename T1, typename T2, typename trueCase, typename falseCase > struct ifBothScalarIntegral { typedef typename ifScalarIntegral< T1, typename ifScalarIntegral< T2, trueCase, falseCase >::type, falseCase >::type type; }; //-------------------------------------------------------------- /// Count number of trailing zeros template< int val > struct numberOfTrailingZeros { enum { next = val >> 1 }; enum { value = vigra::IfBool< (val & 1) == 0, numberOfTrailingZeros<next>, boost::mpl::integral_c< int,-1 > > ::type::value + 1 }; }; template<> struct numberOfTrailingZeros<0> { enum { value = 0 }; }; //-------------------------------------------------------------- /// Count number of one bits template< int val > struct bitcount { enum { next = val >> 1 }; enum { value = bitcount<next>::value + (val & 1) }; }; template<> struct bitcount<0> { enum { value = 0 }; }; //-------------------------------------------------------------- /// Shift left for positive shift value, and right otherwise template< typename T > inline T shiftLeft( T v, int shift ) { return shift > 0 ? v << shift : v >> (-shift); } /// Shift right for positive shift value, and left otherwise template< typename T > inline T shiftRight( T v, int shift ) { return shift > 0 ? v >> shift : v << (-shift); } } // namespace basebmp #endif /* INCLUDED_BASEBMP_METAFUNCTIONS_HXX */ <commit_msg>INTEGRATION: CWS aquavcl01 (1.7.22); FILE MERGED 2007/06/21 09:00:07 pl 1.7.22.1: #i78704# add a new pixelformat, minor cosmetics<commit_after>/************************************************************************* * * OpenOffice.org - a multi-platform office productivity suite * * $RCSfile: metafunctions.hxx,v $ * * $Revision: 1.8 $ * * last change: $Author: rt $ $Date: 2007-07-05 08:54:06 $ * * 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 INCLUDED_BASEBMP_METAFUNCTIONS_HXX #define INCLUDED_BASEBMP_METAFUNCTIONS_HXX #include <boost/mpl/integral_c.hpp> #include <vigra/metaprogramming.hxx> #include <vigra/numerictraits.hxx> namespace basebmp { // TODO(Q3): move to generic place (o3tl?) /** template meta function: add const qualifier to 2nd type, if given 1st type has it */ template<typename A, typename B> struct clone_const { typedef B type; }; template<typename A, typename B> struct clone_const<const A,B> { typedef const B type; }; /** template meta function: add const qualifier to plain type (if not already there) */ template <typename T> struct add_const { typedef const T type; }; template <typename T> struct add_const<const T> { typedef const T type; }; /// template meta function: remove const qualifier from plain type template <typename T> struct remove_const { typedef T type; }; template <typename T> struct remove_const<const T> { typedef T type; }; //-------------------------------------------------------------- /// Base class for an adaptable ternary functor template< typename A1, typename A2, typename A3, typename R > struct TernaryFunctorBase { typedef A1 first_argument_type; typedef A2 second_argument_type; typedef A3 third_argument_type; typedef R result_type; }; //-------------------------------------------------------------- /** template meta function: ensure that given integer type is unsigned If given integer type is already unsigned, return as-is - otherwise, convert to unsigned type of same or greater range. */ template< typename T > struct make_unsigned; #define BASEBMP_MAKE_UNSIGNED(T,U) \ template<> struct make_unsigned<T> { \ typedef U type; \ }; BASEBMP_MAKE_UNSIGNED(signed char,unsigned char) BASEBMP_MAKE_UNSIGNED(unsigned char,unsigned char) BASEBMP_MAKE_UNSIGNED(short,unsigned short) BASEBMP_MAKE_UNSIGNED(unsigned short,unsigned short) BASEBMP_MAKE_UNSIGNED(int,unsigned int) BASEBMP_MAKE_UNSIGNED(unsigned int,unsigned int) BASEBMP_MAKE_UNSIGNED(long,unsigned long) BASEBMP_MAKE_UNSIGNED(unsigned long,unsigned long) #undef BASEBMP_MAKE_UNSIGNED /// cast integer to unsigned type of similar size template< typename T > inline typename make_unsigned<T>::type unsigned_cast( T value ) { return static_cast< typename make_unsigned<T>::type >(value); } //-------------------------------------------------------------- /// returns true, if given number is strictly less than 0 template< typename T > inline bool is_negative( T x ) { return x < 0; } /// Overload for ints (branch-free) inline bool is_negative( int x ) { // force logic shift (result for signed shift right is undefined) return static_cast<unsigned int>(x) >> (sizeof(int)*8-1); } //-------------------------------------------------------------- /// Results in VigraTrueType, if T is of integer type and scalar template< typename T, typename trueCase, typename falseCase > struct ifScalarIntegral { typedef typename vigra::If< typename vigra::NumericTraits< T >::isIntegral, typename vigra::If< typename vigra::NumericTraits< T >::isScalar, trueCase, falseCase >::type, falseCase >::type type; }; /// Results in VigraTrueType, if T is of non-integer type and scalar template< typename T, typename trueCase, typename falseCase > struct ifScalarNonIntegral { typedef typename vigra::If< typename vigra::NumericTraits< T >::isIntegral, falseCase, typename vigra::If< typename vigra::NumericTraits< T >::isScalar, trueCase, falseCase >::type >::type type; }; /// Results in VigraTrueType, if both T1 and T2 are of integer type and scalar template< typename T1, typename T2, typename trueCase, typename falseCase > struct ifBothScalarIntegral { typedef typename ifScalarIntegral< T1, typename ifScalarIntegral< T2, trueCase, falseCase >::type, falseCase >::type type; }; //-------------------------------------------------------------- /// Count number of trailing zeros template< unsigned int val > struct numberOfTrailingZeros { enum { next = val >> 1 }; enum { value = vigra::IfBool< (val & 1) == 0, numberOfTrailingZeros<next>, boost::mpl::integral_c< int,-1 > > ::type::value + 1 }; }; template<> struct numberOfTrailingZeros<0> { enum { value = 0 }; }; //-------------------------------------------------------------- /// Count number of one bits template< unsigned int val > struct bitcount { enum { next = val >> 1 }; enum { value = bitcount<next>::value + (val & 1) }; }; template<> struct bitcount<0> { enum { value = 0 }; }; //-------------------------------------------------------------- /// Shift left for positive shift value, and right otherwise template< typename T > inline T shiftLeft( T v, int shift ) { return shift > 0 ? v << shift : v >> (-shift); } /// Shift right for positive shift value, and left otherwise template< typename T > inline T shiftRight( T v, int shift ) { return shift > 0 ? v >> shift : v << (-shift); } } // namespace basebmp #endif /* INCLUDED_BASEBMP_METAFUNCTIONS_HXX */ <|endoftext|>
<commit_before>// Standard Library includes #include <iostream> #include <string> //! Main function of the mpags-cipher program int main(int /*argc*/, char* /*argv*/[]) { // Hello world for C++ using strings std::string msg {"Hello World!"}; std::cout << msg << "\n"; // No requirement to return from main, but we do so for clarity and // consistency with other functions. return 0; } <commit_msg>Implement mpags-cipher Exercise 2<commit_after>// Standard Library includes #include <iostream> #include <string> //! Main function of the mpags-cipher program int main(int /*argc*/, char* /*argv*/[]) { // Integer variable int answer {1}; answer = 42; std::cout << "The answer is " << answer << "\n"; // double with const const double pi {3.14}; std::cout << "PI is " << pi << " to 2dp\n"; // Product... std::cout << "answer * pi = " << answer*pi << "\n"; // Division std::cout << "pi / answer = " << pi / answer << "\n"; int rewsna {24}; std::cout << "answer / rewsna = " << answer / rewsna << "\n"; // Hello world for C++ using strings std::string msg {"Hello World!"}; std::cout << msg << "\n"; auto singleChar = msg[4]; std::cout << "5th char of message = " << singleChar << "\n"; // No requirement to return from main, but we do so for clarity and // consistency with other functions. return 0; } <|endoftext|>
<commit_before>#include <fcntl.h> #include <stdio.h> #include <sys/stat.h> #include <unistd.h> #include <sys/socket.h> #include <sys/un.h> #include <errno.h> #define MAX_BUF 1024 #include <sstream> #include <iostream> #include <string> #include <chrono> using namespace std; #include <boost/property_tree/json_parser.hpp> const static double PI = 3.14159265; const static int iConstRound = 1; const static double iConstRoundLimit = sin(iConstRound*PI/180.0); static int fd = -1; #include <signal.h> #include <stdio.h> void sigcatch(int) { if(fd > 0) { close(fd); } exit(0); } int main(int ac,char*av[]) { system("rm -f /tmp/mpu.6050.unix.domain"); if (SIG_ERR == signal(SIGINT, sigcatch)) { printf("failed to set signal handler.n"); exit(1); } fd = socket( AF_LOCAL, SOCK_DGRAM, 0 ); struct sockaddr_un addr; bzero( &addr, sizeof(addr) ); addr.sun_family = AF_LOCAL; strcpy( addr.sun_path, "/tmp/mpu.6050.unix.domain" ); int use = 1; if (::setsockopt(fd, SOL_SOCKET, SO_REUSEADDR, &use, sizeof(int)) < 0) { perror("setsockopt(SO_REUSEADDR) failed"); } struct timeval timeout; timeout.tv_sec = 0; timeout.tv_usec = 1000; if (::setsockopt(fd, SOL_SOCKET, SO_RCVTIMEO, &timeout, sizeof(timeout)) < 0) { perror("setsockopt(SO_RCVTIMEO) failed"); } if(::bind(fd, (struct sockaddr*)&addr, sizeof(addr)) < 0) { printf(" cannot bind socket: %d. \n",errno); close(fd); return 0; } char buf[MAX_BUF]; double degree = 90.0; if(ac > 1) { degree = ::atof(av[1]); } degree = std::fabs(degree); int iRound = degree/iConstRound; double dRemain = degree - (iRound *iConstRound); double startDeg = 0.0; bool restartBase = true; chrono::steady_clock::time_point start = std::chrono::steady_clock::now(); int msRun = 0; // 1000 ms while(msRun < 1000) { chrono::steady_clock::time_point end = std::chrono::steady_clock::now(); msRun = chrono::duration_cast<chrono::milliseconds>(end - start).count(); //printf("msRun=<%d>\n",msRun); socklen_t len = sizeof(addr); int ret = ::recvfrom(fd, buf, MAX_BUF, 0, (struct sockaddr *)&addr, &len); if(ret>0){ //printf("Received: %s\n", buf); string recvStr(buf,ret); //std::cout << recvStr << std::endl; std::stringstream ss; ss << recvStr; try { boost::property_tree::ptree pt; boost::property_tree::read_json(ss, pt); auto current = pt.get<double>("yaw"); //std::cout << current << std::endl; if(restartBase) { startDeg = current; restartBase = false; continue; } double dRoundRad = 0.0; if(iRound >0) { dRoundRad = iConstRoundLimit; } else { dRoundRad = sin(PI*dRemain/180.0); } double diffDeg = std::fabs(current - startDeg); /// over if(diffDeg > iConstRound) { diffDeg = 360 - startDeg + current; } double diffRad = (PI*diffDeg/180.0); double diff = dRoundRad - sin(diffRad); std::cout << "diff=<" << diff <<">"<< std::endl; if(diff <=0) { if(iRound >0) { iRound--; restartBase = true; } else { break; } } } catch(std::exception e) { std::cout << e.what() << std::endl; } } else if (ret==0){ //printf("ret=<%d>\n",ret); } else { //printf("ret=<%d>\n",ret); } } close(fd); return 0; } <commit_msg>Update turn.cpp<commit_after>#include <fcntl.h> #include <stdio.h> #include <sys/stat.h> #include <unistd.h> #include <sys/socket.h> #include <sys/un.h> #include <errno.h> #define MAX_BUF 1024 #include <sstream> #include <iostream> #include <string> #include <chrono> using namespace std; #include <boost/property_tree/json_parser.hpp> const static double PI = 3.14159265; const static int iConstRound = 60; const static double iConstRoundLimit = sin(iConstRound*PI/180.0); static int fd = -1; #include <signal.h> #include <stdio.h> void sigcatch(int) { if(fd > 0) { close(fd); } exit(0); } int main(int ac,char*av[]) { system("rm -f /tmp/mpu.6050.unix.domain"); if (SIG_ERR == signal(SIGINT, sigcatch)) { printf("failed to set signal handler.n"); exit(1); } fd = socket( AF_LOCAL, SOCK_DGRAM, 0 ); struct sockaddr_un addr; bzero( &addr, sizeof(addr) ); addr.sun_family = AF_LOCAL; strcpy( addr.sun_path, "/tmp/mpu.6050.unix.domain" ); int use = 1; if (::setsockopt(fd, SOL_SOCKET, SO_REUSEADDR, &use, sizeof(int)) < 0) { perror("setsockopt(SO_REUSEADDR) failed"); } struct timeval timeout; timeout.tv_sec = 0; timeout.tv_usec = 1000; if (::setsockopt(fd, SOL_SOCKET, SO_RCVTIMEO, &timeout, sizeof(timeout)) < 0) { perror("setsockopt(SO_RCVTIMEO) failed"); } if(::bind(fd, (struct sockaddr*)&addr, sizeof(addr)) < 0) { printf(" cannot bind socket: %d. \n",errno); close(fd); return 0; } char buf[MAX_BUF]; double degree = 90.0; if(ac > 1) { degree = ::atof(av[1]); } degree = std::fabs(degree); int iRound = degree/iConstRound; double dRemain = degree - (iRound *iConstRound); double startDeg = 0.0; bool restartBase = true; chrono::steady_clock::time_point start = std::chrono::steady_clock::now(); int msRun = 0; // 1000 ms while(msRun < 1000) { chrono::steady_clock::time_point end = std::chrono::steady_clock::now(); msRun = chrono::duration_cast<chrono::milliseconds>(end - start).count(); //printf("msRun=<%d>\n",msRun); socklen_t len = sizeof(addr); int ret = ::recvfrom(fd, buf, MAX_BUF, 0, (struct sockaddr *)&addr, &len); if(ret>0){ //printf("Received: %s\n", buf); string recvStr(buf,ret); //std::cout << recvStr << std::endl; std::stringstream ss; ss << recvStr; try { boost::property_tree::ptree pt; boost::property_tree::read_json(ss, pt); auto current = pt.get<double>("yaw"); //std::cout << current << std::endl; if(restartBase) { startDeg = current; restartBase = false; continue; } double dRoundRad = 0.0; if(iRound >0) { dRoundRad = iConstRoundLimit; } else { dRoundRad = sin(PI*dRemain/180.0); } double diffDeg = std::fabs(current - startDeg); /// over if(diffDeg > iConstRound) { diffDeg = std::fabs(360 -diffDeg); } double diffRad = (PI*diffDeg/180.0); double diff = dRoundRad - sin(diffRad); std::cout << "diff=<" << diff <<">"<< std::endl; if(diff <=0) { if(iRound >0) { iRound--; restartBase = true; } else { break; } } } catch(std::exception e) { std::cout << e.what() << std::endl; } } else if (ret==0){ //printf("ret=<%d>\n",ret); } else { //printf("ret=<%d>\n",ret); } } close(fd); return 0; } <|endoftext|>
<commit_before>#include "simdjson.h" #include <unistd.h> #include "benchmark.h" SIMDJSON_PUSH_DISABLE_ALL_WARNINGS // #define RAPIDJSON_SSE2 // bad for performance // #define RAPIDJSON_SSE42 // bad for performance #include "rapidjson/document.h" #include "rapidjson/reader.h" #include "rapidjson/stringbuffer.h" #include "rapidjson/writer.h" #include "sajson.h" SIMDJSON_POP_DISABLE_WARNINGS using namespace rapidjson; using namespace simdjson; struct stat_s { size_t number_count; size_t object_count; size_t array_count; size_t null_count; size_t true_count; size_t false_count; bool valid; }; typedef struct stat_s stat_t; bool stat_equal(const stat_t &s1, const stat_t &s2) { return (s1.valid == s2.valid) && (s1.number_count == s2.number_count) && (s1.object_count == s2.object_count) && (s1.array_count == s2.array_count) && (s1.null_count == s2.null_count) && (s1.true_count == s2.true_count) && (s1.false_count == s2.false_count); } void print_stat(const stat_t &s) { if (!s.valid) { printf("invalid\n"); return; } printf("number: %zu object: %zu array: %zu null: %zu true: %zu false: %zu\n", s.number_count, s.object_count, s.array_count, s.null_count, s.true_count, s.false_count); } really_inline void simdjson_process_atom(stat_t &s, simdjson::dom::element element) { if (element.is<double>()) { s.number_count++; } else if (element.is<bool>()) { simdjson::error_code err; bool v; element.get<bool>().tie(v,err); if (v) { s.true_count++; } else { s.false_count++; } } else if (element.is_null()) { s.null_count++; } } void simdjson_recurse(stat_t &s, simdjson::dom::element element) { if (element.is<simdjson::dom::array>()) { s.array_count++; auto [array, array_error] = element.get<simdjson::dom::array>(); if (array_error) { std::cerr << array_error << std::endl; abort(); } for (auto child : array) { if (child.is<simdjson::dom::array>() || child.is<simdjson::dom::object>()) { simdjson_recurse(s, child); } else { simdjson_process_atom(s, child); } } } else if (element.is<simdjson::dom::object>()) { s.object_count++; auto [object, object_error] = element.get<simdjson::dom::object>(); if (object_error) { std::cerr << object_error << std::endl; abort(); } for (auto field : object) { if (field.value.is<simdjson::dom::array>() || field.value.is<simdjson::dom::object>()) { simdjson_recurse(s, field.value); } else { simdjson_process_atom(s, field.value); } } } else { simdjson_process_atom(s, element); } } never_inline stat_t simdjson_compute_stats(const simdjson::padded_string &p) { stat_t s{}; simdjson::dom::parser parser; auto [doc, error] = parser.parse(p); if (error) { s.valid = false; return s; } s.valid = true; simdjson_recurse(s, doc); return s; } // see // https://github.com/miloyip/nativejson-benchmark/blob/master/src/tests/sajsontest.cpp void sajson_traverse(stat_t &stats, const sajson::value &node) { using namespace sajson; switch (node.get_type()) { case TYPE_NULL: stats.null_count++; break; case TYPE_FALSE: stats.false_count++; break; case TYPE_TRUE: stats.true_count++; break; case TYPE_ARRAY: { stats.array_count++; auto length = node.get_length(); for (size_t i = 0; i < length; ++i) { sajson_traverse(stats, node.get_array_element(i)); } break; } case TYPE_OBJECT: { stats.object_count++; auto length = node.get_length(); for (auto i = 0u; i < length; ++i) { sajson_traverse(stats, node.get_object_value(i)); } break; } case TYPE_STRING: // skip break; case TYPE_DOUBLE: case TYPE_INTEGER: stats.number_count++; // node.get_number_value(); break; default: assert(false && "unknown node type"); } } never_inline stat_t sasjon_compute_stats(const simdjson::padded_string &p) { stat_t answer{}; char *buffer = (char *)malloc(p.size()); if (buffer == nullptr) { return answer; } memcpy(buffer, p.data(), p.size()); auto d = sajson::parse(sajson::dynamic_allocation(), sajson::mutable_string_view(p.size(), buffer)); answer.valid = d.is_valid(); if (!answer.valid) { free(buffer); return answer; } answer.number_count = 0; answer.object_count = 0; answer.array_count = 0; answer.null_count = 0; answer.true_count = 0; answer.false_count = 0; sajson_traverse(answer, d.get_root()); free(buffer); return answer; } void rapid_traverse(stat_t &stats, const rapidjson::Value &v) { switch (v.GetType()) { case kNullType: stats.null_count++; break; case kFalseType: stats.false_count++; break; case kTrueType: stats.true_count++; break; case kObjectType: for (Value::ConstMemberIterator m = v.MemberBegin(); m != v.MemberEnd(); ++m) { rapid_traverse(stats, m->value); } stats.object_count++; break; case kArrayType: for (Value::ConstValueIterator i = v.Begin(); i != v.End(); ++i) { // v.Size(); rapid_traverse(stats, *i); } stats.array_count++; break; case kStringType: break; case kNumberType: stats.number_count++; break; } } never_inline stat_t rapid_compute_stats(const simdjson::padded_string &p) { stat_t answer{}; char *buffer = (char *)malloc(p.size() + 1); if (buffer == nullptr) { return answer; } memcpy(buffer, p.data(), p.size()); buffer[p.size()] = '\0'; rapidjson::Document d; d.ParseInsitu<kParseValidateEncodingFlag>(buffer); answer.valid = !d.HasParseError(); if (!answer.valid) { free(buffer); return answer; } answer.number_count = 0; answer.object_count = 0; answer.array_count = 0; answer.null_count = 0; answer.true_count = 0; answer.false_count = 0; rapid_traverse(answer, d); free(buffer); return answer; } never_inline stat_t rapid_accurate_compute_stats(const simdjson::padded_string &p) { stat_t answer{}; char *buffer = (char *)malloc(p.size() + 1); if (buffer == nullptr) { return answer; } memcpy(buffer, p.data(), p.size()); buffer[p.size()] = '\0'; rapidjson::Document d; d.ParseInsitu<kParseValidateEncodingFlag | kParseFullPrecisionFlag>(buffer); answer.valid = !d.HasParseError(); if (!answer.valid) { free(buffer); return answer; } answer.number_count = 0; answer.object_count = 0; answer.array_count = 0; answer.null_count = 0; answer.true_count = 0; answer.false_count = 0; rapid_traverse(answer, d); free(buffer); return answer; } int main(int argc, char *argv[]) { bool verbose = false; bool just_data = false; int c; while ((c = getopt(argc, argv, "vt")) != -1) switch (c) { case 't': just_data = true; break; case 'v': verbose = true; break; default: abort(); } if (optind >= argc) { std::cerr << "Using different parsers, we compute the content statistics of " "JSON documents." << std::endl; std::cerr << "Usage: " << argv[0] << " <jsonfile>" << std::endl; std::cerr << "Or " << argv[0] << " -v <jsonfile>" << std::endl; exit(1); } const char *filename = argv[optind]; if (optind + 1 < argc) { std::cerr << "warning: ignoring everything after " << argv[optind + 1] << std::endl; } auto [p, error] = simdjson::padded_string::load(filename); if (error) { std::cerr << "Could not load the file " << filename << std::endl; return EXIT_FAILURE; } // Gigabyte: https://en.wikipedia.org/wiki/Gigabyte if (verbose) { std::cout << "Input has "; if (p.size() > 1000 * 1000) std::cout << p.size() / (1000 * 1000) << " MB "; else if (p.size() > 1000) std::cout << p.size() / 1000 << " KB "; else std::cout << p.size() << " B "; std::cout << std::endl; } stat_t s1 = simdjson_compute_stats(p); if (verbose) { printf("simdjson: "); print_stat(s1); } stat_t s2 = rapid_compute_stats(p); if (verbose) { printf("rapid: "); print_stat(s2); } stat_t s2a = rapid_accurate_compute_stats(p); if (verbose) { printf("rapid full: "); print_stat(s2a); } stat_t s3 = sasjon_compute_stats(p); if (verbose) { printf("sasjon: "); print_stat(s3); } assert(stat_equal(s1, s2)); assert(stat_equal(s1, s3)); int repeat = 50; size_t volume = p.size(); if (just_data) { printf("name cycles_per_byte cycles_per_byte_err gb_per_s gb_per_s_err \n"); } BEST_TIME("simdjson ", simdjson_compute_stats(p).valid, true, , repeat, volume, !just_data); BEST_TIME("RapidJSON ", rapid_compute_stats(p).valid, true, , repeat, volume, !just_data); BEST_TIME("RapidJSON (precise) ", rapid_accurate_compute_stats(p).valid, true, , repeat, volume, !just_data); BEST_TIME("sasjon ", sasjon_compute_stats(p).valid, true, , repeat, volume, !just_data); } <commit_msg>New API traversal tests. (#931)<commit_after>#include "simdjson.h" #include <unistd.h> #include "benchmark.h" SIMDJSON_PUSH_DISABLE_ALL_WARNINGS // #define RAPIDJSON_SSE2 // bad for performance // #define RAPIDJSON_SSE42 // bad for performance #include "rapidjson/document.h" #include "rapidjson/reader.h" #include "rapidjson/stringbuffer.h" #include "rapidjson/writer.h" #include "sajson.h" SIMDJSON_POP_DISABLE_WARNINGS using namespace rapidjson; using namespace simdjson; struct stat_s { size_t number_count; size_t object_count; size_t array_count; size_t null_count; size_t true_count; size_t false_count; bool valid; }; typedef struct stat_s stat_t; bool stat_equal(const stat_t &s1, const stat_t &s2) { return (s1.valid == s2.valid) && (s1.number_count == s2.number_count) && (s1.object_count == s2.object_count) && (s1.array_count == s2.array_count) && (s1.null_count == s2.null_count) && (s1.true_count == s2.true_count) && (s1.false_count == s2.false_count); } void print_stat(const stat_t &s) { if (!s.valid) { printf("invalid\n"); return; } printf("number: %zu object: %zu array: %zu null: %zu true: %zu false: %zu\n", s.number_count, s.object_count, s.array_count, s.null_count, s.true_count, s.false_count); } really_inline void simdjson_process_atom(stat_t &s, simdjson::dom::element element) { if (element.is<double>()) { s.number_count++; } else if (element.is<bool>()) { simdjson::error_code err; bool v; element.get<bool>().tie(v, err); if (v) { s.true_count++; } else { s.false_count++; } } else if (element.is_null()) { s.null_count++; } } void simdjson_recurse(stat_t &s, simdjson::dom::element element) { if (element.is<simdjson::dom::array>()) { s.array_count++; auto [array, array_error] = element.get<simdjson::dom::array>(); if (array_error) { std::cerr << array_error << std::endl; abort(); } for (auto child : array) { if (child.is<simdjson::dom::array>() || child.is<simdjson::dom::object>()) { simdjson_recurse(s, child); } else { simdjson_process_atom(s, child); } } } else if (element.is<simdjson::dom::object>()) { s.object_count++; auto [object, object_error] = element.get<simdjson::dom::object>(); if (object_error) { std::cerr << object_error << std::endl; abort(); } for (auto field : object) { if (field.value.is<simdjson::dom::array>() || field.value.is<simdjson::dom::object>()) { simdjson_recurse(s, field.value); } else { simdjson_process_atom(s, field.value); } } } else { simdjson_process_atom(s, element); } } never_inline stat_t simdjson_compute_stats(const simdjson::padded_string &p) { stat_t s{}; simdjson::dom::parser parser; auto [doc, error] = parser.parse(p); if (error) { s.valid = false; return s; } s.valid = true; simdjson_recurse(s, doc); return s; } /// struct Stat { size_t objectCount; size_t arrayCount; size_t numberCount; size_t stringCount; size_t trueCount; size_t falseCount; size_t nullCount; size_t memberCount; // Number of members in all objects size_t elementCount; // Number of elements in all arrays size_t stringLength; // Number of code units in all strings }; static void GenStatPlus(Stat &stat, const dom::element &v) { switch (v.type()) { case dom::element_type::ARRAY: for (dom::element child : dom::array(v)) { GenStatPlus(stat, child); stat.elementCount++; } stat.arrayCount++; break; case dom::element_type::OBJECT: for (dom::key_value_pair kv : dom::object(v)) { GenStatPlus(stat, dom::element(kv.value)); stat.memberCount++; stat.stringCount++; } stat.objectCount++; break; case dom::element_type::INT64: case dom::element_type::UINT64: case dom::element_type::DOUBLE: stat.numberCount++; break; case dom::element_type::STRING: { stat.stringCount++; std::string_view sv = v.get<std::string_view>(); stat.stringLength += sv.size(); } break; case dom::element_type::BOOL: if (v.get<bool>()) { stat.trueCount++; } else { stat.falseCount++; } break; case dom::element_type::NULL_VALUE: ++stat.nullCount; break; } } static void RapidGenStat(Stat &stat, const rapidjson::Value &v) { switch (v.GetType()) { case kNullType: stat.nullCount++; break; case kFalseType: stat.falseCount++; break; case kTrueType: stat.trueCount++; break; case kObjectType: for (Value::ConstMemberIterator m = v.MemberBegin(); m != v.MemberEnd(); ++m) { stat.stringLength += m->name.GetStringLength(); RapidGenStat(stat, m->value); } stat.objectCount++; stat.memberCount += (v.MemberEnd() - v.MemberBegin()); stat.stringCount += (v.MemberEnd() - v.MemberBegin()); // Key break; case kArrayType: for (Value::ConstValueIterator i = v.Begin(); i != v.End(); ++i) RapidGenStat(stat, *i); stat.arrayCount++; stat.elementCount += v.Size(); break; case kStringType: stat.stringCount++; stat.stringLength += v.GetStringLength(); break; case kNumberType: stat.numberCount++; break; } } never_inline Stat rapidjson_compute_stats_ref(const rapidjson::Value &doc) { Stat s{}; RapidGenStat(s, doc); return s; } never_inline Stat simdjson_compute_stats_refplus(const simdjson::dom::element &doc) { Stat s{}; GenStatPlus(s, doc); return s; } // see // https://github.com/miloyip/nativejson-benchmark/blob/master/src/tests/sajsontest.cpp void sajson_traverse(stat_t &stats, const sajson::value &node) { using namespace sajson; switch (node.get_type()) { case TYPE_NULL: stats.null_count++; break; case TYPE_FALSE: stats.false_count++; break; case TYPE_TRUE: stats.true_count++; break; case TYPE_ARRAY: { stats.array_count++; auto length = node.get_length(); for (size_t i = 0; i < length; ++i) { sajson_traverse(stats, node.get_array_element(i)); } break; } case TYPE_OBJECT: { stats.object_count++; auto length = node.get_length(); for (auto i = 0u; i < length; ++i) { sajson_traverse(stats, node.get_object_value(i)); } break; } case TYPE_STRING: // skip break; case TYPE_DOUBLE: case TYPE_INTEGER: stats.number_count++; // node.get_number_value(); break; default: assert(false && "unknown node type"); } } never_inline stat_t sasjon_compute_stats(const simdjson::padded_string &p) { stat_t answer{}; char *buffer = (char *)malloc(p.size()); if (buffer == nullptr) { return answer; } memcpy(buffer, p.data(), p.size()); auto d = sajson::parse(sajson::dynamic_allocation(), sajson::mutable_string_view(p.size(), buffer)); answer.valid = d.is_valid(); if (!answer.valid) { free(buffer); return answer; } answer.number_count = 0; answer.object_count = 0; answer.array_count = 0; answer.null_count = 0; answer.true_count = 0; answer.false_count = 0; sajson_traverse(answer, d.get_root()); free(buffer); return answer; } void rapid_traverse(stat_t &stats, const rapidjson::Value &v) { switch (v.GetType()) { case kNullType: stats.null_count++; break; case kFalseType: stats.false_count++; break; case kTrueType: stats.true_count++; break; case kObjectType: for (Value::ConstMemberIterator m = v.MemberBegin(); m != v.MemberEnd(); ++m) { rapid_traverse(stats, m->value); } stats.object_count++; break; case kArrayType: for (Value::ConstValueIterator i = v.Begin(); i != v.End(); ++i) { // v.Size(); rapid_traverse(stats, *i); } stats.array_count++; break; case kStringType: break; case kNumberType: stats.number_count++; break; } } never_inline stat_t rapid_compute_stats(const simdjson::padded_string &p) { stat_t answer{}; char *buffer = (char *)malloc(p.size() + 1); if (buffer == nullptr) { return answer; } memcpy(buffer, p.data(), p.size()); buffer[p.size()] = '\0'; rapidjson::Document d; d.ParseInsitu<kParseValidateEncodingFlag>(buffer); answer.valid = !d.HasParseError(); if (!answer.valid) { free(buffer); return answer; } answer.number_count = 0; answer.object_count = 0; answer.array_count = 0; answer.null_count = 0; answer.true_count = 0; answer.false_count = 0; rapid_traverse(answer, d); free(buffer); return answer; } never_inline stat_t rapid_accurate_compute_stats(const simdjson::padded_string &p) { stat_t answer{}; char *buffer = (char *)malloc(p.size() + 1); if (buffer == nullptr) { return answer; } memcpy(buffer, p.data(), p.size()); buffer[p.size()] = '\0'; rapidjson::Document d; d.ParseInsitu<kParseValidateEncodingFlag | kParseFullPrecisionFlag>(buffer); answer.valid = !d.HasParseError(); if (!answer.valid) { free(buffer); return answer; } answer.number_count = 0; answer.object_count = 0; answer.array_count = 0; answer.null_count = 0; answer.true_count = 0; answer.false_count = 0; rapid_traverse(answer, d); free(buffer); return answer; } int main(int argc, char *argv[]) { bool verbose = false; bool just_data = false; int c; while ((c = getopt(argc, argv, "vt")) != -1) switch (c) { case 't': just_data = true; break; case 'v': verbose = true; break; default: abort(); } if (optind >= argc) { std::cerr << "Using different parsers, we compute the content statistics of " "JSON documents." << std::endl; std::cerr << "Usage: " << argv[0] << " <jsonfile>" << std::endl; std::cerr << "Or " << argv[0] << " -v <jsonfile>" << std::endl; exit(1); } const char *filename = argv[optind]; if (optind + 1 < argc) { std::cerr << "warning: ignoring everything after " << argv[optind + 1] << std::endl; } auto [p, error] = simdjson::padded_string::load(filename); if (error) { std::cerr << "Could not load the file " << filename << std::endl; return EXIT_FAILURE; } // Gigabyte: https://en.wikipedia.org/wiki/Gigabyte if (verbose) { std::cout << "Input has "; if (p.size() > 1000 * 1000) std::cout << p.size() / (1000 * 1000) << " MB "; else if (p.size() > 1000) std::cout << p.size() / 1000 << " KB "; else std::cout << p.size() << " B "; std::cout << std::endl; } stat_t s1 = simdjson_compute_stats(p); if (verbose) { printf("simdjson: "); print_stat(s1); } stat_t s2 = rapid_compute_stats(p); if (verbose) { printf("rapid: "); print_stat(s2); } stat_t s2a = rapid_accurate_compute_stats(p); if (verbose) { printf("rapid full: "); print_stat(s2a); } stat_t s3 = sasjon_compute_stats(p); if (verbose) { printf("sasjon: "); print_stat(s3); } assert(stat_equal(s1, s2)); assert(stat_equal(s1, s3)); int repeat = 50; size_t volume = p.size(); if (just_data) { printf("name cycles_per_byte cycles_per_byte_err gb_per_s gb_per_s_err \n"); } BEST_TIME("simdjson ", simdjson_compute_stats(p).valid, true, , repeat, volume, !just_data); BEST_TIME("RapidJSON ", rapid_compute_stats(p).valid, true, , repeat, volume, !just_data); BEST_TIME("RapidJSON (precise) ", rapid_accurate_compute_stats(p).valid, true, , repeat, volume, !just_data); BEST_TIME("sasjon ", sasjon_compute_stats(p).valid, true, , repeat, volume, !just_data); if (!just_data) { printf("API traversal tests\n"); printf("Based on https://github.com/miloyip/nativejson-benchmark\n"); simdjson::dom::parser parser; auto [doc, err] = parser.parse(p); if (err) { std::cerr << err << std::endl; } size_t refval = simdjson_compute_stats_refplus(doc).objectCount; BEST_TIME("simdjson ", simdjson_compute_stats_refplus(doc).objectCount, refval, , repeat, volume, !just_data); char *buffer = (char *)malloc(p.size() + 1); memcpy(buffer, p.data(), p.size()); buffer[p.size()] = '\0'; rapidjson::Document d; d.ParseInsitu<kParseValidateEncodingFlag>(buffer); BEST_TIME("rapid ", rapidjson_compute_stats_ref(d).objectCount, refval, , repeat, volume, !just_data); free(buffer); } } <|endoftext|>
<commit_before>// Copyright 2019 DeepMind Technologies Ltd. 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 "open_spiel/algorithms/state_distribution.h" #include <algorithm> #include <functional> #include <map> #include <memory> #include <numeric> #include <string> #include <vector> #include "open_spiel/abseil-cpp/absl/algorithm/container.h" #include "open_spiel/abseil-cpp/absl/strings/str_cat.h" #include "open_spiel/simultaneous_move_game.h" #include "open_spiel/spiel.h" namespace open_spiel { namespace algorithms { std::vector<double> Normalize(const std::vector<double>& weights) { std::vector<double> probs(weights); const double normalizer = absl::c_accumulate(weights, 0.); absl::c_for_each(probs, [&probs, normalizer](double& w) { w = (normalizer == 0.0 ? 1.0 / probs.size() : w / normalizer); }); return probs; } std::unique_ptr<open_spiel::HistoryDistribution> CloneBeliefs( const open_spiel::HistoryDistribution& beliefs) { auto beliefs_copy = absl::make_unique<open_spiel::HistoryDistribution>(); for (int i = 0; i < beliefs.first.size(); ++i) { beliefs_copy->first.push_back(beliefs.first[i]->Clone()); beliefs_copy->second.push_back(beliefs.second[i]); } return beliefs_copy; } HistoryDistribution GetStateDistribution(const State& state, const Policy* opponent_policy) { std::shared_ptr<const Game> game = state.GetGame(); GameType game_type = game->GetType(); if (game_type.information == GameType::Information::kPerfectInformation) { HistoryDistribution dist; // We can't use brace initialization here as it triggers the copy ctor. dist.first.push_back(state.Clone()); dist.second.push_back(1.); return dist; } SPIEL_CHECK_EQ(game_type.information, GameType::Information::kImperfectInformation); SPIEL_CHECK_EQ(game_type.dynamics, GameType::Dynamics::kSequential); SPIEL_CHECK_NE(game_type.chance_mode, GameType::ChanceMode::kSampledStochastic); SPIEL_CHECK_FALSE(state.IsChanceNode()); SPIEL_CHECK_FALSE(state.IsTerminal()); Player player = state.CurrentPlayer(); std::string info_state_string = state.InformationStateString(); // Generate the (info state, action) map for the current player using // the state's history. std::map<std::string, Action> infostate_action_map; std::vector<Action> history = state.History(); std::unique_ptr<State> tmp_state = game->NewInitialState(); for (Action action : history) { if (tmp_state->CurrentPlayer() == player) { infostate_action_map[tmp_state->InformationStateString()] = action; } tmp_state->ApplyAction(action); } // Add the current one to this list with an invalid action so that the // information state is included. infostate_action_map[info_state_string] = kInvalidAction; // Should get to the exact same state by re-applying the history. SPIEL_CHECK_EQ(tmp_state->ToString(), state.ToString()); // Now, do a breadth-first search of all the candidate histories, removing // them whenever their (infostate, action) is not contained in the map above. // The search finishes when all the information states of the states in // the list have been found. We use two lists: final_states contains the ones // that have been found, while states are the current candidates. std::vector<std::unique_ptr<State>> final_states; std::vector<double> final_probs; std::vector<std::unique_ptr<State>> states; std::vector<double> probs; states.push_back(game->NewInitialState()); probs.push_back(1.0); while (!states.empty()) { for (int idx = 0; idx < states.size();) { if (states[idx]->IsTerminal()) { // Terminal cannot be a valid history in an information state, so stop // considering this line. } else if (states[idx]->IsChanceNode()) { // At chance nodes, just add all the children and delete the state. for (std::pair<Action, double> action_and_prob : states[idx]->ChanceOutcomes()) { states.push_back(states[idx]->Child(action_and_prob.first)); probs.push_back(probs[idx] * action_and_prob.second); } } else if (states[idx]->CurrentPlayer() != player) { // At opponent nodes, similar to chance nodes but get the probability // from the policy instead. std::string opp_infostate_str = states[idx]->InformationStateString(); ActionsAndProbs state_policy = opponent_policy->GetStatePolicy(*states[idx]); for (Action action : states[idx]->LegalActions()) { double action_prob = GetProb(state_policy, action); states.push_back(states[idx]->Child(action)); probs.push_back(probs[idx] * action_prob); } } else if (states[idx]->CurrentPlayer() == player) { std::string my_infostate_str = states[idx]->InformationStateString(); // First check if this state is in the target information state. If // add it to the final set and don't check for expansion. if (my_infostate_str == info_state_string) { final_states.push_back(states[idx]->Clone()); final_probs.push_back(probs[idx]); } else { // Check for expansion of this candidate. To expand this candidate, // the (infostate, action) pair must be contained in the map. for (Action action : states[idx]->LegalActions()) { auto iter = infostate_action_map.find(my_infostate_str); if (iter != infostate_action_map.end() && action == iter->second) { states.push_back(states[idx]->Child(action)); probs.push_back(probs[idx]); } } } } else { SpielFatalError( absl::StrCat("Unknown player: ", states[idx]->CurrentPlayer())); } // Delete entries at the index i. Rather than call erase, which would // shift everything, simply swap with the last element and call // pop_back(), which can be done in constant time. std::swap(states[idx], states.back()); std::swap(probs[idx], probs.back()); states.pop_back(); probs.pop_back(); // Do not increment the counter index here because the current one points // to a valid state that was just expanded. } } // Now normalize the probs return {std::move(final_states), Normalize(final_probs)}; } std::unique_ptr<HistoryDistribution> UpdateIncrementalStateDistribution( const State& state, const Policy* opponent_policy, int player_id, std::unique_ptr<HistoryDistribution> previous) { if (previous == nullptr) previous = std::make_unique<HistoryDistribution>(); if (previous->first.empty()) { // If the previous pair is empty, then we have to do a BFS to find all // relevant nodes: return std::make_unique<HistoryDistribution>( GetStateDistribution(state, opponent_policy)); } // The current state must be one action ahead of the dist ones. const std::vector<Action> history = state.History(); Action action = history.back(); for (int i = 0; i < previous->first.size(); ++i) { std::unique_ptr<State>& parent = previous->first[i]; double& prob = previous->second[i]; if (Near(prob, 0.)) continue; SPIEL_CHECK_EQ(history.size(), parent->History().size() + 1); switch (parent->GetType()) { case StateType::kChance: { open_spiel::ActionsAndProbs outcomes = parent->ChanceOutcomes(); double action_prob = GetProb(outcomes, action); // If we don't find the chance outcome, then the state we're in is // impossible, so we set it to zero. if (action_prob == -1) { prob = 0; continue; } SPIEL_CHECK_PROB(action_prob); prob *= action_prob; break; } case StateType::kDecision: { if (parent->CurrentPlayer() == player_id) break; open_spiel::ActionsAndProbs policy = opponent_policy->GetStatePolicy(*parent); double action_prob = GetProb(policy, action); SPIEL_CHECK_PROB(action_prob); prob *= action_prob; break; } case StateType::kTerminal: ABSL_FALLTHROUGH_INTENDED; default: SpielFatalError("Unknown state type."); } if (prob == 0) continue; parent->ApplyAction(action); } previous->second = Normalize(previous->second); return previous; } } // namespace algorithms } // namespace open_spiel <commit_msg>Allows UpdateIncrementalStateDistribution to make any number of updates, rather than requiring that the parent state is one action ahead of the beliefs.<commit_after>// Copyright 2019 DeepMind Technologies Ltd. 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 "open_spiel/algorithms/state_distribution.h" #include <algorithm> #include <functional> #include <map> #include <memory> #include <numeric> #include <string> #include <vector> #include "open_spiel/abseil-cpp/absl/algorithm/container.h" #include "open_spiel/abseil-cpp/absl/strings/str_cat.h" #include "open_spiel/simultaneous_move_game.h" #include "open_spiel/spiel.h" namespace open_spiel::algorithms { namespace { std::vector<double> Normalize(const std::vector<double>& weights) { std::vector<double> probs(weights); const double normalizer = absl::c_accumulate(weights, 0.); absl::c_for_each(probs, [&probs, normalizer](double& w) { w = (normalizer == 0.0 ? 1.0 / probs.size() : w / normalizer); }); return probs; } void AdvanceBeliefHistoryOneAction(HistoryDistribution* previous, Action action, Player player_id, const Policy* opponent_policy) { for (int i = 0; i < previous->first.size(); ++i) { std::unique_ptr<State>& parent = previous->first[i]; double& prob = previous->second[i]; if (Near(prob, 0.)) continue; switch (parent->GetType()) { case StateType::kChance: { open_spiel::ActionsAndProbs outcomes = parent->ChanceOutcomes(); double action_prob = GetProb(outcomes, action); // If we don't find the chance outcome, then the state we're in is // impossible, so we set it to zero. if (action_prob == -1) { prob = 0; continue; } SPIEL_CHECK_PROB(action_prob); prob *= action_prob; break; } case StateType::kDecision: { if (parent->CurrentPlayer() == player_id) break; open_spiel::ActionsAndProbs policy = opponent_policy->GetStatePolicy(*parent); double action_prob = GetProb(policy, action); SPIEL_CHECK_PROB(action_prob); prob *= action_prob; break; } case StateType::kTerminal: ABSL_FALLTHROUGH_INTENDED; default: SpielFatalError("Unknown state type."); } if (prob == 0) continue; parent->ApplyAction(action); } previous->second = Normalize(previous->second); } int GetBeliefHistorySize(HistoryDistribution* beliefs) { int belief_history_size = 0; for (int i = 0; i < beliefs->first.size(); ++i) { belief_history_size = std::max(belief_history_size, static_cast<int>(beliefs->first[i]->History().size())); } return belief_history_size; } } // namespace std::unique_ptr<open_spiel::HistoryDistribution> CloneBeliefs( const open_spiel::HistoryDistribution& beliefs) { auto beliefs_copy = absl::make_unique<open_spiel::HistoryDistribution>(); for (int i = 0; i < beliefs.first.size(); ++i) { beliefs_copy->first.push_back(beliefs.first[i]->Clone()); beliefs_copy->second.push_back(beliefs.second[i]); } return beliefs_copy; } HistoryDistribution GetStateDistribution(const State& state, const Policy* opponent_policy) { std::shared_ptr<const Game> game = state.GetGame(); GameType game_type = game->GetType(); if (game_type.information == GameType::Information::kPerfectInformation) { HistoryDistribution dist; // We can't use brace initialization here as it triggers the copy ctor. dist.first.push_back(state.Clone()); dist.second.push_back(1.); return dist; } SPIEL_CHECK_EQ(game_type.information, GameType::Information::kImperfectInformation); SPIEL_CHECK_EQ(game_type.dynamics, GameType::Dynamics::kSequential); SPIEL_CHECK_NE(game_type.chance_mode, GameType::ChanceMode::kSampledStochastic); SPIEL_CHECK_FALSE(state.IsChanceNode()); SPIEL_CHECK_FALSE(state.IsTerminal()); Player player = state.CurrentPlayer(); std::string info_state_string = state.InformationStateString(); // Generate the (info state, action) map for the current player using // the state's history. std::map<std::string, Action> infostate_action_map; std::vector<Action> history = state.History(); std::unique_ptr<State> tmp_state = game->NewInitialState(); for (Action action : history) { if (tmp_state->CurrentPlayer() == player) { infostate_action_map[tmp_state->InformationStateString()] = action; } tmp_state->ApplyAction(action); } // Add the current one to this list with an invalid action so that the // information state is included. infostate_action_map[info_state_string] = kInvalidAction; // Should get to the exact same state by re-applying the history. SPIEL_CHECK_EQ(tmp_state->ToString(), state.ToString()); // Now, do a breadth-first search of all the candidate histories, removing // them whenever their (infostate, action) is not contained in the map above. // The search finishes when all the information states of the states in // the list have been found. We use two lists: final_states contains the ones // that have been found, while states are the current candidates. std::vector<std::unique_ptr<State>> final_states; std::vector<double> final_probs; std::vector<std::unique_ptr<State>> states; std::vector<double> probs; states.push_back(game->NewInitialState()); probs.push_back(1.0); while (!states.empty()) { for (int idx = 0; idx < states.size();) { if (states[idx]->IsTerminal()) { // Terminal cannot be a valid history in an information state, so stop // considering this line. } else if (states[idx]->IsChanceNode()) { // At chance nodes, just add all the children and delete the state. for (std::pair<Action, double> action_and_prob : states[idx]->ChanceOutcomes()) { states.push_back(states[idx]->Child(action_and_prob.first)); probs.push_back(probs[idx] * action_and_prob.second); } } else if (states[idx]->CurrentPlayer() != player) { // At opponent nodes, similar to chance nodes but get the probability // from the policy instead. std::string opp_infostate_str = states[idx]->InformationStateString(); ActionsAndProbs state_policy = opponent_policy->GetStatePolicy(*states[idx]); for (Action action : states[idx]->LegalActions()) { double action_prob = GetProb(state_policy, action); states.push_back(states[idx]->Child(action)); probs.push_back(probs[idx] * action_prob); } } else if (states[idx]->CurrentPlayer() == player) { std::string my_infostate_str = states[idx]->InformationStateString(); // First check if this state is in the target information state. If // add it to the final set and don't check for expansion. if (my_infostate_str == info_state_string) { final_states.push_back(states[idx]->Clone()); final_probs.push_back(probs[idx]); } else { // Check for expansion of this candidate. To expand this candidate, // the (infostate, action) pair must be contained in the map. for (Action action : states[idx]->LegalActions()) { auto iter = infostate_action_map.find(my_infostate_str); if (iter != infostate_action_map.end() && action == iter->second) { states.push_back(states[idx]->Child(action)); probs.push_back(probs[idx]); } } } } else { SpielFatalError( absl::StrCat("Unknown player: ", states[idx]->CurrentPlayer())); } // Delete entries at the index i. Rather than call erase, which would // shift everything, simply swap with the last element and call // pop_back(), which can be done in constant time. std::swap(states[idx], states.back()); std::swap(probs[idx], probs.back()); states.pop_back(); probs.pop_back(); // Do not increment the counter index here because the current one points // to a valid state that was just expanded. } } // Now normalize the probs return {std::move(final_states), Normalize(final_probs)}; } std::unique_ptr<HistoryDistribution> UpdateIncrementalStateDistribution( const State& state, const Policy* opponent_policy, int player_id, std::unique_ptr<HistoryDistribution> previous) { if (previous == nullptr) previous = std::make_unique<HistoryDistribution>(); if (previous->first.empty()) { // If the previous pair is empty, then we have to do a BFS to find all // relevant nodes: return std::make_unique<HistoryDistribution>( GetStateDistribution(state, opponent_policy)); } // The current state must be one action ahead of the dist ones. const std::vector<Action> history = state.History(); int belief_history_size = GetBeliefHistorySize(previous.get()); while (belief_history_size < history.size()) { AdvanceBeliefHistoryOneAction(previous.get(), history[belief_history_size], player_id, opponent_policy); belief_history_size = GetBeliefHistorySize(previous.get()); } return previous; } } // namespace open_spiel::algorithms <|endoftext|>
<commit_before>#include <ros/ros.h> #include <tf/transform_listener.h> #include <tf/transform_broadcaster.h> #include <tf_conversions/tf_eigen.h> #include <pcl_ros/point_cloud.h> #include <pcl/point_types.h> #include <pcl/io/pcd_io.h> #include <pcl/ModelCoefficients.h> #include <pcl/filters/project_inliers.h> #include <pcl/surface/convex_hull.h> #include <iostream> #include <sstream> #include <vector> #include <sensor_msgs/PointCloud2.h> #include <boost/foreach.hpp> #include <image_transport/image_transport.h> #include <opencv2/highgui/highgui.hpp> #include <cv_bridge/cv_bridge.h> //#include <signal.h> typedef pcl::PointCloud<pcl::PointXYZRGB> PointCloud; tf::TransformListener * listener; tf::TransformBroadcaster * br; ros::Publisher pub; image_transport::Publisher imagePub; int fileCounter = 0; //const std::string fileExt = ".pcd"; const std::string fileExt = ".jpg"; void callback(const PointCloud::ConstPtr& msg) { pcl::PointCloud<pcl::PointXYZRGB>::Ptr cloud (new pcl::PointCloud<pcl::PointXYZRGB>); cloud->width = msg->width; cloud->height = msg->height; cloud->is_dense = false; cloud->points.resize (cloud->width * cloud->height); tf::StampedTransform transform; try{ listener->lookupTransform("/camera_depth_optical_frame", "/iiwa_flange_link", ros::Time(0), transform); Eigen::Affine3d tranMat; tf::transformTFToEigen (transform, tranMat); Eigen::Matrix3d rotMat = tranMat.linear(); Eigen::Vector3d zDirection = rotMat.col(2); //std::cout<< zDirection.transpose()<< std::endl; br->sendTransform(tf::StampedTransform(transform, ros::Time::now(), "/camera_depth_optical_frame", "iiwa_end_effector_link")); printf ("Cloud: width = %d, height = %d\n", msg->width, msg->height); int i = 0; BOOST_FOREACH (const pcl::PointXYZRGB& pt, msg->points) { //printf ("\t(%f, %f, %f)\n", pt.x, pt.y, pt.z); Eigen::Vector3d newVec(pt.x - transform.getOrigin().x(), pt.y - transform.getOrigin().y(), pt.z - transform.getOrigin().z()); if (newVec.dot(zDirection) > 0) { cloud->points[i].x = pt.x; cloud->points[i].y = pt.y; cloud->points[i].z = pt.z; cloud->points[i].r = pt.r; cloud->points[i].g = pt.g; cloud->points[i].b = pt.b; } i++; } // Create a set of planar coefficients with X=Y=0,Z=1 pcl::ModelCoefficients::Ptr coefficients (new pcl::ModelCoefficients ()); coefficients->values.resize (4); coefficients->values[0] = zDirection(0); coefficients->values[1] = zDirection(1); coefficients->values[2] = zDirection(2); coefficients->values[3] = ((-1)*(zDirection(0)*transform.getOrigin().x())) - (zDirection(1)*transform.getOrigin().y()) - (zDirection(2)*transform.getOrigin().z());//d= -a*x0 -b*y0 -c*z0 pcl::PointCloud<pcl::PointXYZRGB>::Ptr cloud_projected (new pcl::PointCloud<pcl::PointXYZRGB>); //cloud_projected->width = cloud->width; //cloud_projected->height = cloud->height; //cloud_projected->is_dense = false; //cloud_projected->points.resize (cloud->width * cloud->height); // Create the filtering object pcl::ProjectInliers<pcl::PointXYZRGB> proj; proj.setModelType (pcl::SACMODEL_PLANE); proj.setInputCloud (cloud); proj.setModelCoefficients (coefficients); proj.filter (*cloud_projected); cloud_projected->header.frame_id = msg->header.frame_id; cloud_projected->header.stamp = msg->header.stamp; pub.publish(*cloud_projected); //cv_bridge::CvImagePtr cv::Mat image(480, 640, CV_8UC3, cv::Scalar(0, 0, 0)); cv::Vec3b intensity; //std::cout<<cloud_projected->width<<std::endl; //std::cout<<cloud_projected->height<<std::endl; i = 0; for(int v = 0; v < 480; ++v) { for(int u = 0; u < 640; ++u) { intensity.val[0] = cloud_projected->points[i].b; intensity.val[1] = cloud_projected->points[i].g; intensity.val[2] = cloud_projected->points[i].r; image.at<cv::Vec3b>(cv::Point(u,v)) = intensity; i++; } } cv_bridge::CvImage imageMsg; imageMsg.header.frame_id = msg->header.frame_id; imageMsg.header.stamp = ros::Time::now(); imageMsg.encoding = "bgr8"; // Or whatever imageMsg.image = image; // Your cv::Mat //sensor_msgs::ImagePtr imageMsg = cv_bridge::CvImage(, , image).toImageMsg(); imagePub.publish(imageMsg.toImageMsg()); //cloud->header.frame_id = msg->header.frame_id; //cloud->header.stamp = msg->header.stamp; //pub.publish(*cloud); std::ostringstream oss; oss << fileCounter << fileExt; std::cout << oss.str()<< " created." << std::endl; cv::imwrite(oss.str(), image); //pcl::io::savePCDFileASCII (oss.str(), *cloud); fileCounter++; //ros::shutdown(); } catch (tf::TransformException &ex) { ROS_ERROR("%s",ex.what()); ros::Duration(1.0).sleep(); } } /* void mySigintHandler(int sig) { // Do some custom action. // For example, publish a stop message to some other nodes. printf ("Closing node...\n"); // All the default sigint handler does is call shutdown() ros::shutdown(); }*/ int main(int argc, char** argv) { ros::init(argc, argv, "bg_subtraction"); ros::NodeHandle nh, ng, n; listener = new tf::TransformListener; br = new tf::TransformBroadcaster; ros::Subscriber sub = nh.subscribe<PointCloud>("/camera/depth_registered/points", 1, callback); pub = n.advertise<PointCloud>("/bg_subtracted", 1); image_transport::ImageTransport it(ng); imagePub = it.advertise("/bg_subtracted_image", 1); ros::spin(); } <commit_msg>modified bg_subtraction for kinectv2 and getting rgb portion of the image<commit_after>#include <ros/ros.h> #include <message_filters/subscriber.h> #include <message_filters/sync_policies/approximate_time.h> #include <message_filters/synchronizer.h> #include <tf/transform_listener.h> #include <tf/transform_broadcaster.h> #include <tf_conversions/tf_eigen.h> #include <pcl_ros/point_cloud.h> #include <pcl/point_types.h> #include <pcl/io/pcd_io.h> #include <pcl/ModelCoefficients.h> #include <pcl/filters/project_inliers.h> #include <pcl/surface/convex_hull.h> #include <iostream> #include <sstream> #include <vector> #include <sensor_msgs/PointCloud2.h> #include <sensor_msgs/Image.h> #include <boost/foreach.hpp> #include <image_transport/image_transport.h> #include <opencv2/highgui/highgui.hpp> #include <cv_bridge/cv_bridge.h> //#include <signal.h> typedef pcl::PointCloud<pcl::PointXYZRGB> PointCloud; typedef message_filters::sync_policies::ApproximateTime<PointCloud, sensor_msgs::Image> SyncPolicy; tf::TransformListener * listener; tf::TransformBroadcaster * br; ros::Publisher pub; image_transport::Publisher imagePub; int fileCounter = 0; //const std::string fileExt = ".pcd"; const std::string fileExt = ".jpg"; void callback(const PointCloud::ConstPtr& msg, const sensor_msgs::Image::ConstPtr& imageRgb) { pcl::PointCloud<pcl::PointXYZRGB>::Ptr cloud (new pcl::PointCloud<pcl::PointXYZRGB>); cloud->width = msg->width; cloud->height = msg->height; cloud->is_dense = false; cloud->points.resize (cloud->width * cloud->height); tf::StampedTransform transform; try{ listener->lookupTransform("/kinect2_ir_optical_frame", "/iiwa_flange_link", ros::Time(0), transform); Eigen::Affine3d tranMat; tf::transformTFToEigen (transform, tranMat); Eigen::Matrix3d rotMat = tranMat.linear(); Eigen::Vector3d zDirection = rotMat.col(2); //std::cout<< zDirection.transpose()<< std::endl; br->sendTransform(tf::StampedTransform(transform, ros::Time::now(), "/kinect2_ir_optical_frame", "iiwa_end_effector_link")); printf ("Cloud: width = %d, height = %d\n", msg->width, msg->height); int i = 0; BOOST_FOREACH (const pcl::PointXYZRGB& pt, msg->points) { //printf ("\t(%f, %f, %f)\n", pt.x, pt.y, pt.z); Eigen::Vector3d newVec(pt.x - transform.getOrigin().x(), pt.y - transform.getOrigin().y(), pt.z - transform.getOrigin().z()); if (newVec.dot(zDirection) > -0.01) { cloud->points[i].x = pt.x; cloud->points[i].y = pt.y; cloud->points[i].z = pt.z; cloud->points[i].r = pt.r; cloud->points[i].g = pt.g; cloud->points[i].b = pt.b; } i++; } // Create a set of planar coefficients with X=Y=0,Z=1 pcl::ModelCoefficients::Ptr coefficients (new pcl::ModelCoefficients ()); coefficients->values.resize (4); coefficients->values[0] = zDirection(0); coefficients->values[1] = zDirection(1); coefficients->values[2] = zDirection(2); coefficients->values[3] = ((-1)*(zDirection(0)*transform.getOrigin().x())) - (zDirection(1)*transform.getOrigin().y()) - (zDirection(2)*transform.getOrigin().z());//d= -a*x0 -b*y0 -c*z0 pcl::PointCloud<pcl::PointXYZRGB>::Ptr cloud_projected (new pcl::PointCloud<pcl::PointXYZRGB>); //cloud_projected->width = cloud->width; //cloud_projected->height = cloud->height; //cloud_projected->is_dense = false; //cloud_projected->points.resize (cloud->width * cloud->height); // Create the filtering object pcl::ProjectInliers<pcl::PointXYZRGB> proj; proj.setModelType (pcl::SACMODEL_PLANE); proj.setInputCloud (cloud); proj.setModelCoefficients (coefficients); proj.filter (*cloud_projected); cloud_projected->header.frame_id = msg->header.frame_id; cloud_projected->header.stamp = msg->header.stamp; pub.publish(*cloud_projected); //cv_bridge::CvImagePtr cv::Mat image(1080, 1920, CV_8UC3, cv::Scalar(0, 0, 0)); cv::Mat image_rgb(1080, 1920, CV_8UC3, cv::Scalar(0, 0, 0)); cv::Vec3b intensity, rgb_intensity; //std::cout<<cloud_projected->width<<std::endl; //std::cout<<cloud_projected->height<<std::endl; i = 0; int j = 0; //the following are used to hold the indexes of the first and last occurance of rgb within our pointcloud //so that the subsequent inner loop can get fill only the needed rgb values in our rgb image. int start_rgb, end_rgb; for(int v = 0; v < 1080; ++v) { for(int u = 0; u < 1920; ++u) { intensity.val[0] = cloud_projected->points[i].b; intensity.val[1] = cloud_projected->points[i].g; intensity.val[2] = cloud_projected->points[i++].r; image.at<cv::Vec3b>(cv::Point(u,v)) = intensity; if(start_rgb == 0) { if(intensity != cv::Vec3b(0,0,0)) { start_rgb = u; } } else { if(intensity != cv::Vec3b(0,0,0)) { end_rgb = u; } } } for (int u = 0; u < 1920; ++u) { if (u >= start_rgb && u < end_rgb) { rgb_intensity.val[0] = imageRgb->data[3*j]; rgb_intensity.val[1] = imageRgb->data[3*j + 1]; rgb_intensity.val[2] = imageRgb->data[3*j + 2]; image_rgb.at<cv::Vec3b>(cv::Point(u,v)) = rgb_intensity; } j++; } start_rgb = 0; end_rgb = 0; } cv_bridge::CvImage imageMsg; imageMsg.header.frame_id = msg->header.frame_id; imageMsg.header.stamp = ros::Time::now(); imageMsg.encoding = "bgr8"; // Or whatever imageMsg.image = image; // Your cv::Mat //sensor_msgs::ImagePtr imageMsg = cv_bridge::CvImage(, , image).toImageMsg(); imagePub.publish(imageMsg.toImageMsg()); //cloud->header.frame_id = msg->header.frame_id; //cloud->header.stamp = msg->header.stamp; //pub.publish(*cloud); std::ostringstream oss; oss << fileCounter << fileExt; std::cout << oss.str()<< " created." << std::endl; cv::imwrite(oss.str(), image); std::ostringstream oss_rgb; oss_rgb << fileCounter << "_rgb" << fileExt; std::cout << oss_rgb.str()<< " created." << std::endl; cv::imwrite(oss_rgb.str(), image_rgb); //pcl::io::savePCDFileASCII (oss.str(), *cloud); fileCounter++; //ros::shutdown(); } catch (tf::TransformException &ex) { ROS_ERROR("%s",ex.what()); ros::Duration(1.0).sleep(); } } /* void mySigintHandler(int sig) { // Do some custom action. // For example, publish a stop message to some other nodes. printf ("Closing node...\n"); // All the default sigint handler does is call shutdown() ros::shutdown(); }*/ int main(int argc, char** argv) { ros::init(argc, argv, "bg_subtraction"); ros::NodeHandle nh, ng, n; listener = new tf::TransformListener; br = new tf::TransformBroadcaster; //ros::Subscriber sub = nh.subscribe<PointCloud>("/kinect2/hd/points", 1, callback); message_filters::Subscriber<PointCloud> registeredSub(nh, "/kinect2/hd/points", 1); message_filters::Subscriber<sensor_msgs::Image> rgbSub(nh, "/kinect2/hd/image_color", 1); message_filters::Synchronizer<SyncPolicy> sync(SyncPolicy(10), registeredSub, rgbSub); sync.registerCallback(boost::bind(&callback, _1, _2)); pub = n.advertise<PointCloud>("/bg_subtracted", 1); image_transport::ImageTransport it(ng); imagePub = it.advertise("/bg_subtracted_image", 1); ros::spin(); } <|endoftext|>
<commit_before>/* --------------------------------------------------------------------------- ** This software is in the public domain, furnished "as is", without technical ** support, and with no warranty, express or implied, as to its usefulness for ** any purpose. ** ** v4l2compress_jpeg.cpp ** ** Read YUYC from a V4L2 capture -> compress in JPEG using libjpeg -> write to a V4L2 output device ** ** -------------------------------------------------------------------------*/ #include <unistd.h> #include <string.h> #include <errno.h> #include <stdlib.h> #include <linux/videodev2.h> #include <sys/ioctl.h> #include <stdint.h> #include <signal.h> #include <fstream> #include "logger.h" #include "V4l2Device.h" #include "V4l2Capture.h" #include "V4l2Output.h" #include <jpeglib.h> int stop=0; /* --------------------------------------------------------------------------- ** SIGINT handler ** -------------------------------------------------------------------------*/ void sighandler(int) { printf("SIGINT\n"); stop =1; } /* --------------------------------------------------------------------------- ** convert yuyv -> jpeg ** -------------------------------------------------------------------------*/ unsigned long yuyv2jpeg(char* image_buffer, unsigned int width, unsigned int height, unsigned int quality) { struct jpeg_error_mgr jerr; struct jpeg_compress_struct cinfo; jpeg_create_compress(&cinfo); cinfo.image_width = width; cinfo.image_height = height; cinfo.input_components = 3; cinfo.err = jpeg_std_error(&jerr); unsigned char* dest = NULL; unsigned long destsize = 0; jpeg_mem_dest(&cinfo, &dest, &destsize); jpeg_set_defaults(&cinfo); jpeg_set_quality(&cinfo, quality, TRUE); jpeg_start_compress(&cinfo, TRUE); unsigned char bufline[cinfo.image_width * 3]; while (cinfo.next_scanline < cinfo.image_height) { // convert line from YUYV -> YUV for (unsigned int i = 0; i < cinfo.image_width; i += 2) { unsigned int base = cinfo.next_scanline*cinfo.image_width * 2 ; bufline[i*3 ] = image_buffer[base + i*2 ]; bufline[i*3+1] = image_buffer[base + i*2+1]; bufline[i*3+2] = image_buffer[base + i*2+3]; bufline[i*3+3] = image_buffer[base + i*2+2]; bufline[i*3+4] = image_buffer[base + i*2+1]; bufline[i*3+5] = image_buffer[base + i*2+3]; } JSAMPROW row = bufline; jpeg_write_scanlines(&cinfo, &row, 1); } jpeg_finish_compress(&cinfo); if (dest != NULL) { if (destsize < width*height*2) { memcpy(image_buffer, dest, destsize); } else { LOG(WARN) << "Buffer to small size:" << width*height*2 << " " << destsize; } free(dest); } jpeg_destroy_compress(&cinfo); return destsize; } /* --------------------------------------------------------------------------- ** main ** -------------------------------------------------------------------------*/ int main(int argc, char* argv[]) { int verbose=0; const char *in_devname = "/dev/video0"; const char *out_devname = "/dev/video1"; int width = 640; int height = 480; int fps = 10; int c = 0; V4l2Access::IoType ioTypeIn = V4l2Access::IOTYPE_MMAP; V4l2Access::IoType ioTypeOut = V4l2Access::IOTYPE_MMAP; while ((c = getopt (argc, argv, "h" "W:H:F:" "rw")) != -1) { switch (c) { case 'v': verbose = 1; if (optarg && *optarg=='v') verbose++; break; case 'W': width = atoi(optarg); break; case 'H': height = atoi(optarg); break; case 'F': fps = atoi(optarg); break; case 'r': ioTypeIn = V4l2Access::IOTYPE_READWRITE; break; case 'w': ioTypeOut = V4l2Access::IOTYPE_READWRITE; break; case 'h': { std::cout << argv[0] << " [-v[v]] [-W width] [-H height] source_device dest_device" << std::endl; std::cout << "\t -v : verbose " << std::endl; std::cout << "\t -vv : very verbose " << std::endl; std::cout << "\t -W width : V4L2 capture width (default "<< width << ")" << std::endl; std::cout << "\t -H height : V4L2 capture height (default "<< height << ")" << std::endl; std::cout << "\t -F fps : V4L2 capture framerate (default "<< fps << ")" << std::endl; std::cout << "\t -r : V4L2 capture using read interface (default use memory mapped buffers)" << std::endl; std::cout << "\t -w : V4L2 capture using write interface (default use memory mapped buffers)" << std::endl; std::cout << "\t source_device : V4L2 capture device (default "<< in_devname << ")" << std::endl; std::cout << "\t dest_device : V4L2 capture device (default "<< out_devname << ")" << std::endl; exit(0); } } } if (optind<argc) { in_devname = argv[optind]; optind++; } if (optind<argc) { out_devname = argv[optind]; optind++; } // initialize log4cpp initLogger(verbose); // init V4L2 capture interface V4L2DeviceParameters param(in_devname,V4L2_PIX_FMT_YUYV,width,height,fps,verbose); V4l2Capture* videoCapture = V4l2Capture::create(param, ioTypeIn); if (videoCapture == NULL) { LOG(WARN) << "Cannot create V4L2 capture interface for device:" << in_devname; } else { // init V4L2 output interface V4L2DeviceParameters outparam(out_devname, V4L2_PIX_FMT_JPEG, videoCapture->getWidth(), videoCapture->getHeight(), 0, verbose); V4l2Output* videoOutput = V4l2Output::create(outparam, ioTypeOut); if (videoOutput == NULL) { LOG(WARN) << "Cannot create V4L2 output interface for device:" << out_devname; } else { timeval tv; LOG(NOTICE) << "Start Compressing " << in_devname << " to " << out_devname; signal(SIGINT,sighandler); while (!stop) { tv.tv_sec=1; tv.tv_usec=0; int ret = videoCapture->isReadable(&tv); if (ret == 1) { char buffer[videoCapture->getBufferSize()]; int rsize = videoCapture->read(buffer, sizeof(buffer)); if (rsize == -1) { LOG(NOTICE) << "stop " << strerror(errno); stop=1; } else { // compress rsize = yuyv2jpeg(buffer, width, height, 95); int wsize = videoOutput->write(buffer, rsize); LOG(DEBUG) << "Copied " << rsize << " " << wsize; } } else if (ret == -1) { LOG(NOTICE) << "stop " << strerror(errno); stop=1; } } delete videoOutput; } delete videoCapture; } return 0; } <commit_msg>add option to specify JPEG quality and subsampling<commit_after>/* --------------------------------------------------------------------------- ** This software is in the public domain, furnished "as is", without technical ** support, and with no warranty, express or implied, as to its usefulness for ** any purpose. ** ** v4l2compress_jpeg.cpp ** ** Read YUYC from a V4L2 capture -> compress in JPEG using libjpeg -> write to a V4L2 output device ** ** -------------------------------------------------------------------------*/ #include <unistd.h> #include <string.h> #include <errno.h> #include <stdlib.h> #include <linux/videodev2.h> #include <sys/ioctl.h> #include <stdint.h> #include <signal.h> #include <fstream> #include "logger.h" #include "V4l2Device.h" #include "V4l2Capture.h" #include "V4l2Output.h" #include <jpeglib.h> int stop=0; /* --------------------------------------------------------------------------- ** SIGINT handler ** -------------------------------------------------------------------------*/ void sighandler(int) { printf("SIGINT\n"); stop =1; } void jpeg_setsubsampling(struct jpeg_compress_struct& cinfo, unsigned int subsampling) { if (subsampling == 0) { cinfo.comp_info[0].h_samp_factor = 1; cinfo.comp_info[0].v_samp_factor = 1; } else if (subsampling == 1) { cinfo.comp_info[0].h_samp_factor = 2; cinfo.comp_info[0].v_samp_factor = 1; } else if (subsampling == 2) { cinfo.comp_info[0].h_samp_factor = 2; cinfo.comp_info[0].v_samp_factor = 2; } cinfo.comp_info[1].h_samp_factor = 1; cinfo.comp_info[1].v_samp_factor = 1; cinfo.comp_info[2].h_samp_factor = 1; cinfo.comp_info[2].v_samp_factor = 1; } /* --------------------------------------------------------------------------- ** convert yuyv -> jpeg ** -------------------------------------------------------------------------*/ unsigned long yuyv2jpeg(char* image_buffer, unsigned int width, unsigned int height, unsigned int quality, unsigned int subsampling) { struct jpeg_error_mgr jerr; struct jpeg_compress_struct cinfo; jpeg_create_compress(&cinfo); cinfo.image_width = width; cinfo.image_height = height; cinfo.input_components = 3; cinfo.err = jpeg_std_error(&jerr); unsigned char* dest = NULL; unsigned long destsize = 0; jpeg_mem_dest(&cinfo, &dest, &destsize); jpeg_set_defaults(&cinfo); jpeg_set_quality(&cinfo, quality, TRUE); jpeg_setsubsampling(cinfo,subsampling); jpeg_start_compress(&cinfo, TRUE); unsigned char bufline[cinfo.image_width * 3]; while (cinfo.next_scanline < cinfo.image_height) { // convert line from YUYV -> YUV for (unsigned int i = 0; i < cinfo.image_width; i += 2) { unsigned int base = cinfo.next_scanline*cinfo.image_width * 2 ; bufline[i*3 ] = image_buffer[base + i*2 ]; bufline[i*3+1] = image_buffer[base + i*2+1]; bufline[i*3+2] = image_buffer[base + i*2+3]; bufline[i*3+3] = image_buffer[base + i*2+2]; bufline[i*3+4] = image_buffer[base + i*2+1]; bufline[i*3+5] = image_buffer[base + i*2+3]; } JSAMPROW row = bufline; jpeg_write_scanlines(&cinfo, &row, 1); } jpeg_finish_compress(&cinfo); if (dest != NULL) { if (destsize < width*height*2) { memcpy(image_buffer, dest, destsize); } else { LOG(WARN) << "Buffer to small size:" << width*height*2 << " " << destsize; } free(dest); } jpeg_destroy_compress(&cinfo); return destsize; } /* --------------------------------------------------------------------------- ** main ** -------------------------------------------------------------------------*/ int main(int argc, char* argv[]) { int verbose=0; const char *in_devname = "/dev/video0"; const char *out_devname = "/dev/video1"; int width = 640; int height = 480; int fps = 10; int quality = 99; int subsampling = 1; V4l2Access::IoType ioTypeIn = V4l2Access::IOTYPE_MMAP; V4l2Access::IoType ioTypeOut = V4l2Access::IOTYPE_MMAP; int c = 0; while ((c = getopt (argc, argv, "h" "W:H:F:" "rw" "q:s:")) != -1) { switch (c) { case 'v': verbose = 1; if (optarg && *optarg=='v') verbose++; break; // capture options case 'W': width = atoi(optarg); break; case 'H': height = atoi(optarg); break; case 'F': fps = atoi(optarg); break; case 'r': ioTypeIn = V4l2Access::IOTYPE_READWRITE; break; // output options case 'w': ioTypeOut = V4l2Access::IOTYPE_READWRITE; break; // JPEG options case 'q': quality = atoi(optarg); break; case 's': subsampling = atoi(optarg); break; case 'h': { std::cout << argv[0] << " [-v[v]] [-W width] [-H height] source_device dest_device" << std::endl; std::cout << "\t -v : verbose " << std::endl; std::cout << "\t -vv : very verbose " << std::endl; std::cout << "\t -W width : V4L2 capture width (default "<< width << ")" << std::endl; std::cout << "\t -H height : V4L2 capture height (default "<< height << ")" << std::endl; std::cout << "\t -F fps : V4L2 capture framerate (default "<< fps << ")" << std::endl; std::cout << "\t -r : V4L2 capture using read interface (default use memory mapped buffers)" << std::endl; std::cout << "\t -w : V4L2 capture using write interface (default use memory mapped buffers)" << std::endl; std::cout << "\tcompressor options" << std::endl; std::cout << "\t -q <quality> : JPEG quality" << std::endl; std::cout << "\t -s <subsampling> : JPEG sumsampling (0->JPEG 4:4:4 0->JPEG 4:2:2 0->JPEG 4:2:0)" << std::endl; std::cout << "\t source_device : V4L2 capture device (default "<< in_devname << ")" << std::endl; std::cout << "\t dest_device : V4L2 output device (default "<< out_devname << ")" << std::endl; exit(0); } } } if (optind<argc) { in_devname = argv[optind]; optind++; } if (optind<argc) { out_devname = argv[optind]; optind++; } // initialize log4cpp initLogger(verbose); // init V4L2 capture interface V4L2DeviceParameters param(in_devname,V4L2_PIX_FMT_YUYV,width,height,fps,verbose); V4l2Capture* videoCapture = V4l2Capture::create(param, ioTypeIn); if (videoCapture == NULL) { LOG(WARN) << "Cannot create V4L2 capture interface for device:" << in_devname; } else { // init V4L2 output interface V4L2DeviceParameters outparam(out_devname, V4L2_PIX_FMT_JPEG, videoCapture->getWidth(), videoCapture->getHeight(), 0, verbose); V4l2Output* videoOutput = V4l2Output::create(outparam, ioTypeOut); if (videoOutput == NULL) { LOG(WARN) << "Cannot create V4L2 output interface for device:" << out_devname; } else { timeval tv; LOG(NOTICE) << "Start Compressing " << in_devname << " to " << out_devname; signal(SIGINT,sighandler); while (!stop) { tv.tv_sec=1; tv.tv_usec=0; int ret = videoCapture->isReadable(&tv); if (ret == 1) { char buffer[videoCapture->getBufferSize()]; int rsize = videoCapture->read(buffer, sizeof(buffer)); if (rsize == -1) { LOG(NOTICE) << "stop " << strerror(errno); stop=1; } else { // compress rsize = yuyv2jpeg(buffer, width, height, quality, subsampling); int wsize = videoOutput->write(buffer, rsize); LOG(DEBUG) << "Copied " << rsize << " " << wsize; } } else if (ret == -1) { LOG(NOTICE) << "stop " << strerror(errno); stop=1; } } delete videoOutput; } delete videoCapture; } return 0; } <|endoftext|>
<commit_before>/*- * Copyright (c) 2010 Benjamin Close <[email protected]> * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * THIS SOFTWARE IS PROVIDED BY THE AUTHOR 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 AUTHOR 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 <assert.h> #include <config.h> #include <iostream> #include "Camera.h" #if ENABLE_VIDEO #include <video/VideoDecoder.h> #endif using namespace std; namespace wcl { struct Camera::Priv { #if ENABLE_VIDEO VideoDecoder *decoder; #endif }; Camera::CameraBuffer::CameraBuffer(): start(0) {} Camera::Camera() : buffers(NULL), bufferSize(0), numBuffers(0), conversionBuffer(NULL), areParametersSet(false), internal(NULL) { } Camera::~Camera() { this->destroyBuffers(); if(this->conversionBuffer != NULL){ delete (unsigned char *)this->conversionBuffer->start; delete this->conversionBuffer; } if(this->internal){ #if ENABLE_VIDEO delete this->internal->decoder; #endif delete this->internal; } } void Camera::allocateBuffers(const size_t size, const unsigned count) { this->destroyBuffers(); this->buffers = new CameraBuffer[count]; for(unsigned i =0; i < count; i++) this->buffers[i].length = size; } void Camera::destroyBuffers() { if( this->buffers ) delete [] this->buffers; this->numBuffers=0; } Camera::CameraParameters Camera::getParameters() const { return this->parameters; } int Camera::convertPixelYUYV422toRGB8(const int y, const int u, const int v ) { unsigned int pixel32 = 0; unsigned char *pixel = (unsigned char *)&pixel32; int r, g, b; r = y + (1.370705 * (v-128)); g = y - (0.698001 * (v-128)) - (0.337633 * (u-128)); b = y + (1.732446 * (u-128)); if(r > 255) r = 255; if(g > 255) g = 255; if(b > 255) b = 255; if(r < 0) r = 0; if(g < 0) g = 0; if(b < 0) b = 0; pixel[0] = r * 220 / 256; pixel[1] = g * 220 / 256; pixel[2] = b * 220 / 256; return pixel32; } void Camera::convertImageYUYV422toRGB8(const unsigned char *yuv, unsigned char *rgb, const unsigned int width, const unsigned int height) { unsigned int in, out = 0; unsigned int pixel_16; unsigned char pixel_24[3]; unsigned int pixel32; int y0, u, y1, v; for(in = 0; in < width * height * 2; in += 4) { pixel_16 = yuv[in + 3] << 24 | yuv[in + 2] << 16 | yuv[in + 1] << 8 | yuv[in + 0]; y0 = (pixel_16 & 0x000000ff); u = (pixel_16 & 0x0000ff00) >> 8; y1 = (pixel_16 & 0x00ff0000) >> 16; v = (pixel_16 & 0xff000000) >> 24; pixel32 = Camera::convertPixelYUYV422toRGB8(y0, u, v); pixel_24[0] = (pixel32 & 0x000000ff); pixel_24[1] = (pixel32 & 0x0000ff00) >> 8; pixel_24[2] = (pixel32 & 0x00ff0000) >> 16; rgb[out++] = pixel_24[0]; rgb[out++] = pixel_24[1]; rgb[out++] = pixel_24[2]; pixel32 = Camera::convertPixelYUYV422toRGB8(y1, u, v); pixel_24[0] = (pixel32 & 0x000000ff); pixel_24[1] = (pixel32 & 0x0000ff00) >> 8; pixel_24[2] = (pixel32 & 0x00ff0000) >> 16; rgb[out++] = pixel_24[0]; rgb[out++] = pixel_24[1]; rgb[out++] = pixel_24[2]; } } void Camera::convertImageMONO8toRGB8( const unsigned char *mono, unsigned char *rgb, const unsigned int width, const unsigned int height ) { unsigned int in, out=0; for(in = 0; in < width * height; in++ ) { rgb[out+0]=mono[in]; rgb[out+1]=mono[in]; rgb[out+2]=mono[in]; out+=3; } } void Camera::setConfiguration(Configuration c) { assert (c.width != 0); assert (c.height != 0); assert (c.fps != 0); this->activeConfiguration = c; } std::vector<Camera::Configuration> Camera::getSupportedConfigurations() const { return this->supportedConfigurations; } Camera::Configuration Camera::findConfiguration(Camera::Configuration partialConfig) const { for (std::vector<Configuration>::const_iterator it = supportedConfigurations.begin(); it < supportedConfigurations.end(); ++it) { // does this config match what we are looking for? if (partialConfig.format != ANY && (*it).format != partialConfig.format) continue; if (partialConfig.width != 0 && (*it).width != partialConfig.width) continue; if (partialConfig.height != 0 && (*it).height != partialConfig.height) continue; if (partialConfig.fps != 0 && (*it).fps != partialConfig.fps) continue; // matches everything we asked for! return *it; } throw std::string("Could not find configuration that met the criteria."); } /** * Perform a software conversion of the frame to the requested format. * The first call to this function is expensive as an internal buffer must be * setup to support the conversion. Successive calls with the same format * only incur the performance hit of the conversion. Changing image formats * will also incurr an reallocation performance hit. * * @param f The format to convert the frame too * @return A pointer to the converted frame */ const unsigned char *Camera::getFrame(const ImageFormat f ) { const unsigned char *frame = this->getFrame(); // Handle the same image format being requested if( this->activeConfiguration.format == f ) return frame; unsigned width = this->activeConfiguration.width; unsigned height = this->activeConfiguration.height; this->setupConversionBuffer(this->getFormatBufferSize(f)); unsigned char *buffer=(unsigned char *)this->conversionBuffer->start; switch( f ){ case RGB8: { switch( this->activeConfiguration.format){ case MONO8: convertImageMONO8toRGB8(frame, buffer, width, height); return buffer; case YUYV422: convertImageYUYV422toRGB8( frame, buffer, width, height); return buffer; #if ENABLE_VIDEO case MJPEG:{ // Init the video decoder on the first MJPEG decoding frame if( this->internal == NULL){ this->internal = new Priv; this->internal->decoder = new VideoDecoder(width, height,CODEC_ID_MJPEG, false ); } internal->decoder->nextFrame(frame, this->getFormatBufferSize()); return internal->decoder->getFrame(); } #endif default: ; } goto NOTIMP; } case MJPEG: case YUYV422: case YUYV411: case RGB16: case RGB32: case BGR8: case MONO8: case MONO16: default: NOTIMP: assert(0 && "Camera::getFrame(const ImageFormat) - Requested Conversion Not Implemented"); } return NULL; } unsigned Camera::getFormatBytesPerPixel() const { return Camera::getFormatBytesPerPixel(this->activeConfiguration.format); } unsigned Camera::getFormatBytesPerPixel(const ImageFormat f ) const { switch( f ){ case RGB8: return 3; case RGB16: return 6; case RGB32: return 12; case BGR8: return 3; case MONO8: return 1; case MONO16: return 2; case YUYV422: return 4; case YUYV411: return 4; case MJPEG: return 12; } } unsigned Camera::getFormatBufferSize() const { return Camera::getFormatBufferSize( this->activeConfiguration.format); } unsigned Camera::getFormatBufferSize(const ImageFormat f ) const { return (this->getFormatBytesPerPixel(f) * this->getActiveConfiguration().width * this->activeConfiguration.height); } void Camera::setupConversionBuffer( const size_t buffersize ) { if( this->conversionBuffer ){ if( this->conversionBuffer->length == buffersize ) return; delete this->conversionBuffer; } this->conversionBuffer = new CameraBuffer; this->conversionBuffer->length = buffersize; this->conversionBuffer->start = (void *)new unsigned char[buffersize]; } bool Camera::hasParameters() const { return areParametersSet; } void Camera::setParameters(const Camera::CameraParameters& p) { areParametersSet = true; this->parameters = p; } void Camera::printDetails(bool state) { Configuration a = this->getActiveConfiguration(); cout << "Camera: " << this->id << " (" << this->getTypeIdentifier() << ")" << this->imageFormatToString(a.format) << ":" << a.width << "x" << a.height << "@" << a.fps << endl; if ( state ){ cout << "Features/Modes" << endl; for(std::vector<Configuration>::iterator it = supportedConfigurations.begin(); it != supportedConfigurations.end(); ++it ){ Configuration c = *it; cout << "\t" << this->imageFormatToString(c.format) << " " << c.width << "x" << c.height << " @" << c.fps << endl; } } } const char *Camera::imageFormatToString(const ImageFormat f ) { switch(f) { case MJPEG: return "MJPEG"; case YUYV422: return "YUYV422"; case YUYV411: return "YUYV411"; case RGB8: return "RGB8"; case RGB16: return "RGB16"; case RGB32: return "RGB32"; case BGR8: return "BGR8"; case MONO8: return "MONO8"; case MONO16: return "MONO16"; case ANY: default: return "UNKNOWN:"; }; } } <commit_msg>camera: Mark the buffers as being freed. This fixes a double free between UVCCamera Shutdown + delete UVCCamera<commit_after>/*- * Copyright (c) 2010 Benjamin Close <[email protected]> * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * THIS SOFTWARE IS PROVIDED BY THE AUTHOR 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 AUTHOR 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 <assert.h> #include <config.h> #include <iostream> #include "Camera.h" #if ENABLE_VIDEO #include <video/VideoDecoder.h> #endif using namespace std; namespace wcl { struct Camera::Priv { #if ENABLE_VIDEO VideoDecoder *decoder; #endif }; Camera::CameraBuffer::CameraBuffer(): start(0) {} Camera::Camera() : buffers(NULL), bufferSize(0), numBuffers(0), conversionBuffer(NULL), areParametersSet(false), internal(NULL) { } Camera::~Camera() { this->destroyBuffers(); if(this->conversionBuffer != NULL){ delete (unsigned char *)this->conversionBuffer->start; delete this->conversionBuffer; } if(this->internal){ #if ENABLE_VIDEO delete this->internal->decoder; #endif delete this->internal; } } void Camera::allocateBuffers(const size_t size, const unsigned count) { this->destroyBuffers(); this->buffers = new CameraBuffer[count]; for(unsigned i =0; i < count; i++) this->buffers[i].length = size; } void Camera::destroyBuffers() { if( this->buffers ) delete [] this->buffers; this->buffers = NULL; this->numBuffers=0; } Camera::CameraParameters Camera::getParameters() const { return this->parameters; } int Camera::convertPixelYUYV422toRGB8(const int y, const int u, const int v ) { unsigned int pixel32 = 0; unsigned char *pixel = (unsigned char *)&pixel32; int r, g, b; r = y + (1.370705 * (v-128)); g = y - (0.698001 * (v-128)) - (0.337633 * (u-128)); b = y + (1.732446 * (u-128)); if(r > 255) r = 255; if(g > 255) g = 255; if(b > 255) b = 255; if(r < 0) r = 0; if(g < 0) g = 0; if(b < 0) b = 0; pixel[0] = r * 220 / 256; pixel[1] = g * 220 / 256; pixel[2] = b * 220 / 256; return pixel32; } void Camera::convertImageYUYV422toRGB8(const unsigned char *yuv, unsigned char *rgb, const unsigned int width, const unsigned int height) { unsigned int in, out = 0; unsigned int pixel_16; unsigned char pixel_24[3]; unsigned int pixel32; int y0, u, y1, v; for(in = 0; in < width * height * 2; in += 4) { pixel_16 = yuv[in + 3] << 24 | yuv[in + 2] << 16 | yuv[in + 1] << 8 | yuv[in + 0]; y0 = (pixel_16 & 0x000000ff); u = (pixel_16 & 0x0000ff00) >> 8; y1 = (pixel_16 & 0x00ff0000) >> 16; v = (pixel_16 & 0xff000000) >> 24; pixel32 = Camera::convertPixelYUYV422toRGB8(y0, u, v); pixel_24[0] = (pixel32 & 0x000000ff); pixel_24[1] = (pixel32 & 0x0000ff00) >> 8; pixel_24[2] = (pixel32 & 0x00ff0000) >> 16; rgb[out++] = pixel_24[0]; rgb[out++] = pixel_24[1]; rgb[out++] = pixel_24[2]; pixel32 = Camera::convertPixelYUYV422toRGB8(y1, u, v); pixel_24[0] = (pixel32 & 0x000000ff); pixel_24[1] = (pixel32 & 0x0000ff00) >> 8; pixel_24[2] = (pixel32 & 0x00ff0000) >> 16; rgb[out++] = pixel_24[0]; rgb[out++] = pixel_24[1]; rgb[out++] = pixel_24[2]; } } void Camera::convertImageMONO8toRGB8( const unsigned char *mono, unsigned char *rgb, const unsigned int width, const unsigned int height ) { unsigned int in, out=0; for(in = 0; in < width * height; in++ ) { rgb[out+0]=mono[in]; rgb[out+1]=mono[in]; rgb[out+2]=mono[in]; out+=3; } } void Camera::setConfiguration(Configuration c) { assert (c.width != 0); assert (c.height != 0); assert (c.fps != 0); this->activeConfiguration = c; } std::vector<Camera::Configuration> Camera::getSupportedConfigurations() const { return this->supportedConfigurations; } Camera::Configuration Camera::findConfiguration(Camera::Configuration partialConfig) const { for (std::vector<Configuration>::const_iterator it = supportedConfigurations.begin(); it < supportedConfigurations.end(); ++it) { // does this config match what we are looking for? if (partialConfig.format != ANY && (*it).format != partialConfig.format) continue; if (partialConfig.width != 0 && (*it).width != partialConfig.width) continue; if (partialConfig.height != 0 && (*it).height != partialConfig.height) continue; if (partialConfig.fps != 0 && (*it).fps != partialConfig.fps) continue; // matches everything we asked for! return *it; } throw std::string("Could not find configuration that met the criteria."); } /** * Perform a software conversion of the frame to the requested format. * The first call to this function is expensive as an internal buffer must be * setup to support the conversion. Successive calls with the same format * only incur the performance hit of the conversion. Changing image formats * will also incurr an reallocation performance hit. * * @param f The format to convert the frame too * @return A pointer to the converted frame */ const unsigned char *Camera::getFrame(const ImageFormat f ) { const unsigned char *frame = this->getFrame(); // Handle the same image format being requested if( this->activeConfiguration.format == f ) return frame; unsigned width = this->activeConfiguration.width; unsigned height = this->activeConfiguration.height; this->setupConversionBuffer(this->getFormatBufferSize(f)); unsigned char *buffer=(unsigned char *)this->conversionBuffer->start; switch( f ){ case RGB8: { switch( this->activeConfiguration.format){ case MONO8: convertImageMONO8toRGB8(frame, buffer, width, height); return buffer; case YUYV422: convertImageYUYV422toRGB8( frame, buffer, width, height); return buffer; #if ENABLE_VIDEO case MJPEG:{ // Init the video decoder on the first MJPEG decoding frame if( this->internal == NULL){ this->internal = new Priv; this->internal->decoder = new VideoDecoder(width, height,CODEC_ID_MJPEG, false ); } internal->decoder->nextFrame(frame, this->getFormatBufferSize()); return internal->decoder->getFrame(); } #endif default: ; } goto NOTIMP; } case MJPEG: case YUYV422: case YUYV411: case RGB16: case RGB32: case BGR8: case MONO8: case MONO16: default: NOTIMP: assert(0 && "Camera::getFrame(const ImageFormat) - Requested Conversion Not Implemented"); } return NULL; } unsigned Camera::getFormatBytesPerPixel() const { return Camera::getFormatBytesPerPixel(this->activeConfiguration.format); } unsigned Camera::getFormatBytesPerPixel(const ImageFormat f ) const { switch( f ){ case RGB8: return 3; case RGB16: return 6; case RGB32: return 12; case BGR8: return 3; case MONO8: return 1; case MONO16: return 2; case YUYV422: return 4; case YUYV411: return 4; case MJPEG: return 12; } } unsigned Camera::getFormatBufferSize() const { return Camera::getFormatBufferSize( this->activeConfiguration.format); } unsigned Camera::getFormatBufferSize(const ImageFormat f ) const { return (this->getFormatBytesPerPixel(f) * this->getActiveConfiguration().width * this->activeConfiguration.height); } void Camera::setupConversionBuffer( const size_t buffersize ) { if( this->conversionBuffer ){ if( this->conversionBuffer->length == buffersize ) return; delete this->conversionBuffer; } this->conversionBuffer = new CameraBuffer; this->conversionBuffer->length = buffersize; this->conversionBuffer->start = (void *)new unsigned char[buffersize]; } bool Camera::hasParameters() const { return areParametersSet; } void Camera::setParameters(const Camera::CameraParameters& p) { areParametersSet = true; this->parameters = p; } void Camera::printDetails(bool state) { Configuration a = this->getActiveConfiguration(); cout << "Camera: " << this->id << " (" << this->getTypeIdentifier() << ")" << this->imageFormatToString(a.format) << ":" << a.width << "x" << a.height << "@" << a.fps << endl; if ( state ){ cout << "Features/Modes" << endl; for(std::vector<Configuration>::iterator it = supportedConfigurations.begin(); it != supportedConfigurations.end(); ++it ){ Configuration c = *it; cout << "\t" << this->imageFormatToString(c.format) << " " << c.width << "x" << c.height << " @" << c.fps << endl; } } } const char *Camera::imageFormatToString(const ImageFormat f ) { switch(f) { case MJPEG: return "MJPEG"; case YUYV422: return "YUYV422"; case YUYV411: return "YUYV411"; case RGB8: return "RGB8"; case RGB16: return "RGB16"; case RGB32: return "RGB32"; case BGR8: return "BGR8"; case MONO8: return "MONO8"; case MONO16: return "MONO16"; case ANY: default: return "UNKNOWN:"; }; } } <|endoftext|>
<commit_before>/** * @file MAchievementsDetails.cpp * @brief Get Achievements that a user can unlock. * * (c) 2013-2014 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. */ #include "MAchievementsDetails.h" using namespace mega; using namespace Platform; MAchievementsDetails::MAchievementsDetails(MegaAchievementsDetails *achievementsDetails, bool cMemoryOwn) { this->achievementsDetails = achievementsDetails; this->cMemoryOwn = cMemoryOwn; } MAchievementsDetails::~MAchievementsDetails() { if (cMemoryOwn) delete achievementsDetails; } MegaAchievementsDetails* MAchievementsDetails::getCPtr() { return achievementsDetails; } int64 MAchievementsDetails::getBaseStorage() { return achievementsDetails ? achievementsDetails->getBaseStorage() : 0; } int64 MAchievementsDetails::getClassStorage(int class_id) { return achievementsDetails ? achievementsDetails->getClassStorage(class_id) : 0; } int64 MAchievementsDetails::getClassTransfer(int class_id) { return achievementsDetails ? achievementsDetails->getClassTransfer(class_id) : 0; } int MAchievementsDetails::getClassExpire(int class_id) { return achievementsDetails ? achievementsDetails->getClassExpire(class_id) : 0; } unsigned int MAchievementsDetails::getAwardsCount() { return achievementsDetails ? achievementsDetails->getAwardsCount() : 0; } int MAchievementsDetails::getAwardClass(unsigned int index) { return achievementsDetails ? achievementsDetails->getAwardClass(index) : 0; } int MAchievementsDetails::getAwardId(unsigned int index) { return achievementsDetails ? achievementsDetails->getAwardId(index) : 0; } int64 MAchievementsDetails::getAwardTimestamp(unsigned int index) { return achievementsDetails ? achievementsDetails->getAwardTimestamp(index) : 0; } int64 MAchievementsDetails::getAwardExpirationTs(unsigned int index) { return achievementsDetails ? achievementsDetails->getAwardExpirationTs(index) : 0; } MStringList^ MAchievementsDetails::getAwardEmails(unsigned int index) { return achievementsDetails ? ref new MStringList(achievementsDetails->getAwardEmails(index), true) : nullptr; } int MAchievementsDetails::getRewardsCount() { return achievementsDetails ? achievementsDetails->getRewardsCount() : 0; } int MAchievementsDetails::getRewardAwardId(unsigned int index) { return achievementsDetails ? achievementsDetails->getRewardAwardId(index) : 0; } int64 MAchievementsDetails::getRewardStorage(unsigned int index) { return achievementsDetails ? achievementsDetails->getRewardStorage(index) : 0; } int64 MAchievementsDetails::getRewardTransfer(unsigned int index) { return achievementsDetails ? achievementsDetails->getRewardTransfer(index) : 0; } int64 MAchievementsDetails::getRewardStorageByAwardId(int award_id) { return achievementsDetails ? achievementsDetails->getRewardStorageByAwardId(award_id) : 0; } int64 MAchievementsDetails::getRewardTransferByAwardId(int award_id) { return achievementsDetails ? achievementsDetails->getRewardTransferByAwardId(award_id) : 0; } int MAchievementsDetails::getRewardExpire(unsigned int index) { return achievementsDetails ? achievementsDetails->getRewardExpire(index) : 0; } MAchievementsDetails^ MAchievementsDetails::copy() { return achievementsDetails ? ref new MAchievementsDetails(achievementsDetails->copy(), true) : nullptr; } int64 MAchievementsDetails::currentStorage() { return achievementsDetails ? achievementsDetails->currentStorage() : 0; } int64 MAchievementsDetails::currentTransfer() { return achievementsDetails ? achievementsDetails->currentTransfer() : 0; } int64 MAchievementsDetails::currentStorageReferrals() { return achievementsDetails ? achievementsDetails->currentStorageReferrals() : 0; } int64 MAchievementsDetails::currentTransferReferrals() { return achievementsDetails ? achievementsDetails->currentTransferReferrals() : 0; } <commit_msg>Change the return values by the methods of `MAchievementsDetails` for a better error identification (WP & UWP bindings)<commit_after>/** * @file MAchievementsDetails.cpp * @brief Get Achievements that a user can unlock. * * (c) 2013-2014 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. */ #include "MAchievementsDetails.h" using namespace mega; using namespace Platform; MAchievementsDetails::MAchievementsDetails(MegaAchievementsDetails *achievementsDetails, bool cMemoryOwn) { this->achievementsDetails = achievementsDetails; this->cMemoryOwn = cMemoryOwn; } MAchievementsDetails::~MAchievementsDetails() { if (cMemoryOwn) delete achievementsDetails; } MegaAchievementsDetails* MAchievementsDetails::getCPtr() { return achievementsDetails; } int64 MAchievementsDetails::getBaseStorage() { return achievementsDetails ? achievementsDetails->getBaseStorage() : -1; } int64 MAchievementsDetails::getClassStorage(int class_id) { return achievementsDetails ? achievementsDetails->getClassStorage(class_id) : -1; } int64 MAchievementsDetails::getClassTransfer(int class_id) { return achievementsDetails ? achievementsDetails->getClassTransfer(class_id) : -1; } int MAchievementsDetails::getClassExpire(int class_id) { return achievementsDetails ? achievementsDetails->getClassExpire(class_id) : 0; } unsigned int MAchievementsDetails::getAwardsCount() { return achievementsDetails ? achievementsDetails->getAwardsCount() : 0; } int MAchievementsDetails::getAwardClass(unsigned int index) { return achievementsDetails ? achievementsDetails->getAwardClass(index) : 0; } int MAchievementsDetails::getAwardId(unsigned int index) { return achievementsDetails ? achievementsDetails->getAwardId(index) : 0; } int64 MAchievementsDetails::getAwardTimestamp(unsigned int index) { return achievementsDetails ? achievementsDetails->getAwardTimestamp(index) : -1; } int64 MAchievementsDetails::getAwardExpirationTs(unsigned int index) { return achievementsDetails ? achievementsDetails->getAwardExpirationTs(index) : -1; } MStringList^ MAchievementsDetails::getAwardEmails(unsigned int index) { return achievementsDetails ? ref new MStringList(achievementsDetails->getAwardEmails(index), true) : nullptr; } int MAchievementsDetails::getRewardsCount() { return achievementsDetails ? achievementsDetails->getRewardsCount() : -1; } int MAchievementsDetails::getRewardAwardId(unsigned int index) { return achievementsDetails ? achievementsDetails->getRewardAwardId(index) : -1; } int64 MAchievementsDetails::getRewardStorage(unsigned int index) { return achievementsDetails ? achievementsDetails->getRewardStorage(index) : -1; } int64 MAchievementsDetails::getRewardTransfer(unsigned int index) { return achievementsDetails ? achievementsDetails->getRewardTransfer(index) : -1; } int64 MAchievementsDetails::getRewardStorageByAwardId(int award_id) { return achievementsDetails ? achievementsDetails->getRewardStorageByAwardId(award_id) : -1; } int64 MAchievementsDetails::getRewardTransferByAwardId(int award_id) { return achievementsDetails ? achievementsDetails->getRewardTransferByAwardId(award_id) : -1; } int MAchievementsDetails::getRewardExpire(unsigned int index) { return achievementsDetails ? achievementsDetails->getRewardExpire(index) : 0; } MAchievementsDetails^ MAchievementsDetails::copy() { return achievementsDetails ? ref new MAchievementsDetails(achievementsDetails->copy(), true) : nullptr; } int64 MAchievementsDetails::currentStorage() { return achievementsDetails ? achievementsDetails->currentStorage() : -1; } int64 MAchievementsDetails::currentTransfer() { return achievementsDetails ? achievementsDetails->currentTransfer() : -1; } int64 MAchievementsDetails::currentStorageReferrals() { return achievementsDetails ? achievementsDetails->currentStorageReferrals() : -1; } int64 MAchievementsDetails::currentTransferReferrals() { return achievementsDetails ? achievementsDetails->currentTransferReferrals() : -1; } <|endoftext|>
<commit_before>/* * Author(s): * - Cedric Gestes <[email protected]> * - Chris Kilner <[email protected]> * * Copyright (C) 2010 Aldebaran Robotics */ #include <qi/serialization/message.hpp> #include <vector> namespace qi { namespace serialization { #if 0 #define __QI_DEBUG_SERIALIZATION_DATA_R(x, d) { \ std::string sig = qi::signature< x >::value(); \ std::cout << "read (" << sig << "): " << d << std::endl; \ } #define __QI_DEBUG_SERIALIZATION_DATA_W(x, d) { \ std::string sig = qi::signature< x >::value(); \ std::cout << "write(" << sig << "): " << d << std::endl; \ } #else # define __QI_DEBUG_SERIALIZATION_DATA_R(x, d) # define __QI_DEBUG_SERIALIZATION_DATA_W(x, d) #endif #define QI_SIMPLE_SERIALIZER_IMPL(Name, Type) \ void Message::read##Name(Type& b) \ { \ b = *((Type *) fData.data()); \ fData.erase(0, sizeof(Type)); \ __QI_DEBUG_SERIALIZATION_DATA_R(Type, b); \ } \ \ void Message::write##Name(const Type& b) \ { \ fData.append((char *)&b, sizeof(b)); \ __QI_DEBUG_SERIALIZATION_DATA_W(Type, b); \ } QI_SIMPLE_SERIALIZER_IMPL(Bool, bool); QI_SIMPLE_SERIALIZER_IMPL(Char, char); QI_SIMPLE_SERIALIZER_IMPL(Int, int); QI_SIMPLE_SERIALIZER_IMPL(Float, float); //SIMPLE_SERIALIZER(Float, double); void Message::readDouble(double& d) { memcpy(&d, fData.data(), sizeof(double)); fData.erase(0, sizeof(double)); __QI_DEBUG_SERIALIZATION_DATA_R(double, d); } void Message::writeDouble(const double& d) { fData.append((char *)&d, sizeof(d)); __QI_DEBUG_SERIALIZATION_DATA_W(double, d); } // string void Message::readString(std::string& s) { int sz; readInt(sz); s.clear(); if (sz) { s.append(fData.data(), sz); fData.erase(0, sz); __QI_DEBUG_SERIALIZATION_DATA_R(std::string, s); } } void Message::writeString(const std::string &s) { writeInt(s.size()); if (s.size()) { fData.append(s.data(), s.size()); __QI_DEBUG_SERIALIZATION_DATA_W(std::string, s); } } } } <commit_msg>message: check if not empty<commit_after>/* * Author(s): * - Cedric Gestes <[email protected]> * - Chris Kilner <[email protected]> * * Copyright (C) 2010 Aldebaran Robotics */ #include <qi/serialization/message.hpp> #include <vector> namespace qi { namespace serialization { #if 0 #define __QI_DEBUG_SERIALIZATION_DATA_R(x, d) { \ std::string sig = qi::signature< x >::value(); \ std::cout << "read (" << sig << "): " << d << std::endl; \ } #define __QI_DEBUG_SERIALIZATION_DATA_W(x, d) { \ std::string sig = qi::signature< x >::value(); \ std::cout << "write(" << sig << "): " << d << std::endl; \ } #else # define __QI_DEBUG_SERIALIZATION_DATA_R(x, d) # define __QI_DEBUG_SERIALIZATION_DATA_W(x, d) #endif #define QI_SIMPLE_SERIALIZER_IMPL(Name, Type) \ void Message::read##Name(Type& b) \ { \ b = *((Type *) fData.data()); \ fData.erase(0, sizeof(Type)); \ __QI_DEBUG_SERIALIZATION_DATA_R(Type, b); \ } \ \ void Message::write##Name(const Type& b) \ { \ fData.append((char *)&b, sizeof(b)); \ __QI_DEBUG_SERIALIZATION_DATA_W(Type, b); \ } QI_SIMPLE_SERIALIZER_IMPL(Bool, bool); QI_SIMPLE_SERIALIZER_IMPL(Char, char); QI_SIMPLE_SERIALIZER_IMPL(Int, int); QI_SIMPLE_SERIALIZER_IMPL(Float, float); //SIMPLE_SERIALIZER(Float, double); void Message::readDouble(double& d) { memcpy(&d, fData.data(), sizeof(double)); fData.erase(0, sizeof(double)); __QI_DEBUG_SERIALIZATION_DATA_R(double, d); } void Message::writeDouble(const double& d) { fData.append((char *)&d, sizeof(d)); __QI_DEBUG_SERIALIZATION_DATA_W(double, d); } // string void Message::readString(std::string& s) { int sz; readInt(sz); s.clear(); if (sz) { s.append(fData.data(), sz); fData.erase(0, sz); __QI_DEBUG_SERIALIZATION_DATA_R(std::string, s); } } void Message::writeString(const std::string &s) { writeInt(s.size()); if (!s.empty()) { fData.append(s.data(), s.size()); __QI_DEBUG_SERIALIZATION_DATA_W(std::string, s); } } } } <|endoftext|>
<commit_before>#include "jobwidget.h" #include "debug.h" #include "restoredialog.h" #include "utils.h" #include <QMenu> #include <QMessageBox> JobWidget::JobWidget(QWidget *parent) : QWidget(parent), _saveEnabled(false) { _ui.setupUi(this); _ui.archiveListWidget->setAttribute(Qt::WA_MacShowFocusRect, false); _ui.infoLabel->hide(); _fsEventUpdate.setSingleShot(true); connect(&_fsEventUpdate, &QTimer::timeout, this, &JobWidget::verifyJob); connect(_ui.infoLabel, &TextLabel::clicked, this, &JobWidget::showJobPathsWarn); connect(_ui.jobNameLineEdit, &QLineEdit::textChanged, [&]() { emit enableSave(canSaveNew()); }); connect(_ui.jobTreeWidget, &FilePickerWidget::selectionChanged, [&]() { if(_job->objectKey().isEmpty()) emit enableSave(canSaveNew()); else save(); }); connect(_ui.jobTreeWidget, &FilePickerWidget::settingChanged, [&]() { if(!_job->objectKey().isEmpty()) save(); }); connect(_ui.includeScheduledCheckBox, &QCheckBox::toggled, this, &JobWidget::save); connect(_ui.preservePathsCheckBox, &QCheckBox::toggled, this, &JobWidget::save); connect(_ui.traverseMountCheckBox, &QCheckBox::toggled, this, &JobWidget::save); connect(_ui.followSymLinksCheckBox, &QCheckBox::toggled, this, &JobWidget::save); connect(_ui.skipNoDumpCheckBox, &QCheckBox::toggled, this, &JobWidget::save); connect(_ui.skipFilesSizeSpinBox, &QSpinBox::editingFinished, this, &JobWidget::save); connect(_ui.skipFilesCheckBox, &QCheckBox::toggled, this, &JobWidget::save); connect(_ui.skipFilesLineEdit, &QLineEdit::editingFinished, this, &JobWidget::save); connect(_ui.hideButton, &QPushButton::clicked, this, &JobWidget::collapse); connect(_ui.restoreButton, &QPushButton::clicked, this, &JobWidget::restoreButtonClicked); connect(_ui.backupButton, &QPushButton::clicked, this, &JobWidget::backupButtonClicked); connect(_ui.archiveListWidget, &ArchiveListWidget::inspectArchive, this, &JobWidget::inspectJobArchive); connect(_ui.archiveListWidget, &ArchiveListWidget::restoreArchive, this, &JobWidget::restoreJobArchive); connect(_ui.archiveListWidget, &ArchiveListWidget::deleteArchives, this, &JobWidget::deleteJobArchives); connect(_ui.skipFilesDefaultsButton, &QPushButton::clicked, [&]() { QSettings settings; _ui.skipFilesLineEdit->setText( settings.value("app/skip_system_files", DEFAULT_SKIP_FILES).toString()); }); connect(_ui.archiveListWidget, &ArchiveListWidget::customContextMenuRequested, this, &JobWidget::showArchiveListMenu); connect(_ui.actionDelete, &QAction::triggered, _ui.archiveListWidget, &ArchiveListWidget::removeSelectedItems); connect(_ui.actionRestore, &QAction::triggered, _ui.archiveListWidget, &ArchiveListWidget::restoreSelectedItem); connect(_ui.actionInspect, &QAction::triggered, _ui.archiveListWidget, &ArchiveListWidget::inspectSelectedItem); } JobWidget::~JobWidget() { } JobPtr JobWidget::job() const { return _job; } void JobWidget::setJob(const JobPtr &job) { if(_job) { _job->removeWatcher(); disconnect(_job.data(), &Job::fsEvent, this, &JobWidget::fsEventReceived); disconnect(_job.data(), &Job::changed, this, &JobWidget::updateDetails); } _saveEnabled = false; _job = job; // Creating a new job? if(_job->objectKey().isEmpty()) { _ui.tabWidget->setTabEnabled(_ui.tabWidget->indexOf(_ui.archiveListTab), false); _ui.restoreButton->hide(); _ui.backupButton->hide(); _ui.jobNameLabel->hide(); _ui.infoLabel->hide(); _ui.jobNameLineEdit->clear(); _ui.jobNameLineEdit->show(); _ui.jobNameLineEdit->setFocus(); } else { _ui.tabWidget->setTabEnabled(_ui.tabWidget->indexOf(_ui.archiveListTab), true); _ui.restoreButton->show(); _ui.backupButton->show(); _ui.jobNameLabel->show(); _ui.jobNameLineEdit->hide(); connect(_job.data(), &Job::changed, this, &JobWidget::updateDetails); connect(_job.data(), &Job::fsEvent, this, &JobWidget::fsEventReceived); job->installWatcher(); } _ui.tabWidget->setCurrentWidget(_ui.jobTreeTab); updateDetails(); _saveEnabled = true; } void JobWidget::save() { if(_saveEnabled && !_job->name().isEmpty()) { DEBUG << "SAVE JOB"; _job->setUrls(_ui.jobTreeWidget->getSelectedUrls()); _job->removeWatcher(); _job->installWatcher(); _job->setOptionScheduledEnabled( _ui.includeScheduledCheckBox->isChecked()); _job->setOptionPreservePaths(_ui.preservePathsCheckBox->isChecked()); _job->setOptionTraverseMount(_ui.traverseMountCheckBox->isChecked()); _job->setOptionFollowSymLinks(_ui.followSymLinksCheckBox->isChecked()); _job->setOptionSkipNoDump(_ui.skipNoDumpCheckBox->isChecked()); _job->setOptionSkipFilesSize(_ui.skipFilesSizeSpinBox->value()); _job->setOptionSkipFiles(_ui.skipFilesCheckBox->isChecked()); _job->setOptionSkipFilesPatterns(_ui.skipFilesLineEdit->text()); _job->setSettingShowHidden(_ui.jobTreeWidget->settingShowHidden()); _job->setSettingShowSystem(_ui.jobTreeWidget->settingShowSystem()); _job->setSettingHideSymlinks(_ui.jobTreeWidget->settingHideSymlinks()); _job->save(); verifyJob(); } } void JobWidget::saveNew() { if(!canSaveNew()) return; DEBUG << "SAVE NEW JOB"; _job->setName(_ui.jobNameLineEdit->text()); if(!_job->archives().isEmpty()) { auto confirm = QMessageBox::question(this, "Add job", tr("Assign %1 found archives to this" " Job?").arg(_job->archives().count()), QMessageBox::Yes | QMessageBox::No, QMessageBox::No); QList<ArchivePtr> empty; if(confirm == QMessageBox::No) _job->setArchives(empty); } save(); foreach(ArchivePtr archive, _job->archives()) { archive->setJobRef(_job->objectKey()); archive->save(); } emit jobAdded(_job); } void JobWidget::updateMatchingArchives(QList<ArchivePtr> archives) { if(!archives.isEmpty()) { _ui.infoLabel->setText(tr("Found %1 unassigned archives matching this" " Job description. Go to Archives tab below" " to review.").arg(archives.count())); _ui.infoLabel->show(); _ui.tabWidget->setTabEnabled(_ui.tabWidget->indexOf(_ui.archiveListTab), true); } else { _ui.infoLabel->clear(); _ui.infoLabel->hide(); _ui.tabWidget->setTabEnabled(_ui.tabWidget->indexOf(_ui.archiveListTab), false); } _job->setArchives(archives); _ui.archiveListWidget->clear(); _ui.archiveListWidget->addArchives(_job->archives()); _ui.tabWidget->setTabText(_ui.tabWidget->indexOf(_ui.archiveListTab), tr("Archives (%1)").arg(_job->archives().count())); } void JobWidget::updateDetails() { if(!_job) return; DEBUG << "UPDATE JOB DETAILS"; _saveEnabled = false; _ui.jobNameLabel->setText(_job->name()); _ui.jobTreeWidget->setSettingShowHidden(_job->settingShowHidden()); _ui.jobTreeWidget->setSettingShowSystem(_job->settingShowSystem()); _ui.jobTreeWidget->setSettingHideSymlinks(_job->settingHideSymlinks()); _ui.jobTreeWidget->blockSignals(true); _ui.jobTreeWidget->setSelectedUrls(_job->urls()); _ui.jobTreeWidget->blockSignals(false); _ui.archiveListWidget->clear(); _ui.archiveListWidget->addArchives(_job->archives()); _ui.includeScheduledCheckBox->setChecked(_job->optionScheduledEnabled()); _ui.preservePathsCheckBox->setChecked(_job->optionPreservePaths()); _ui.traverseMountCheckBox->setChecked(_job->optionTraverseMount()); _ui.followSymLinksCheckBox->setChecked(_job->optionFollowSymLinks()); _ui.skipNoDumpCheckBox->setChecked(_job->optionSkipNoDump()); _ui.skipFilesSizeSpinBox->setValue(_job->optionSkipFilesSize()); _ui.skipFilesCheckBox->setChecked(_job->optionSkipFiles()); _ui.skipFilesLineEdit->setText(_job->optionSkipFilesPatterns()); _ui.tabWidget->setTabText(_ui.tabWidget->indexOf(_ui.archiveListTab), tr("Archives (%1)").arg(_job->archives().count())); verifyJob(); _saveEnabled = true; } void JobWidget::restoreButtonClicked() { if(_job && !_job->archives().isEmpty()) { ArchivePtr archive = _job->archives().first(); RestoreDialog restoreDialog(archive, this); if(QDialog::Accepted == restoreDialog.exec()) emit restoreJobArchive(archive, restoreDialog.getOptions()); } } void JobWidget::backupButtonClicked() { if(_job) emit backupJob(_job); } bool JobWidget::canSaveNew() { if(_job->objectKey().isEmpty() && !_ui.jobNameLineEdit->text().isEmpty()) { _job->setName(_ui.jobNameLineEdit->text()); if(!_job->findObjectWithKey(_job->name())) { emit findMatchingArchives(_job->archivePrefix()); if(!_ui.jobTreeWidget->getSelectedUrls().isEmpty()) return true; } else { _ui.infoLabel->setText(tr("Job name must be unique amongst existing" " Jobs.")); _ui.infoLabel->show(); } } return false; } void JobWidget::showArchiveListMenu(const QPoint &pos) { QPoint globalPos = _ui.archiveListWidget->viewport()->mapToGlobal(pos); QMenu archiveListMenu(_ui.archiveListWidget); if(!_ui.archiveListWidget->selectedItems().isEmpty()) { if(_ui.archiveListWidget->selectedItems().count() == 1) { archiveListMenu.addAction(_ui.actionInspect); archiveListMenu.addAction(_ui.actionRestore); } archiveListMenu.addAction(_ui.actionDelete); } archiveListMenu.exec(globalPos); } void JobWidget::fsEventReceived() { _fsEventUpdate.start(250); //coalesce update events with a 250ms time delay } void JobWidget::showJobPathsWarn() { if(_job->urls().isEmpty()) return; QMessageBox *msg = new QMessageBox(this); msg->setAttribute(Qt::WA_DeleteOnClose, true); msg->setText(tr("Previously selected backup paths for this Job are not" " accessible anymore and thus backups may be incomplete." " Mount missing drives or make a new selection. Press Show" " details to list all backup paths for Job %1:").arg(_job->name())); QStringList urls; foreach(QUrl url, _job->urls()) urls << url.toLocalFile(); msg->setDetailedText(urls.join('\n')); msg->show(); } void JobWidget::verifyJob() { if(_job->objectKey().isEmpty()) return; _ui.jobTreeWidget->blockSignals(true); _ui.jobTreeWidget->setSelectedUrls(_job->urls()); _ui.jobTreeWidget->blockSignals(false); _ui.infoLabel->setVisible(!_job->validateUrls()); if(!_job->validateUrls()) { if(_job->urls().isEmpty()) { _ui.infoLabel->setText(tr("This Job has no backup paths selected. " "Please make a selection.")); } else { _ui.infoLabel->setText(tr("Previously selected backup paths are not" " accessible. Click here for details.")); } } } <commit_msg>Use the provided Job name for the LineEdit.<commit_after>#include "jobwidget.h" #include "debug.h" #include "restoredialog.h" #include "utils.h" #include <QMenu> #include <QMessageBox> JobWidget::JobWidget(QWidget *parent) : QWidget(parent), _saveEnabled(false) { _ui.setupUi(this); _ui.archiveListWidget->setAttribute(Qt::WA_MacShowFocusRect, false); _ui.infoLabel->hide(); _fsEventUpdate.setSingleShot(true); connect(&_fsEventUpdate, &QTimer::timeout, this, &JobWidget::verifyJob); connect(_ui.infoLabel, &TextLabel::clicked, this, &JobWidget::showJobPathsWarn); connect(_ui.jobNameLineEdit, &QLineEdit::textChanged, [&]() { emit enableSave(canSaveNew()); }); connect(_ui.jobTreeWidget, &FilePickerWidget::selectionChanged, [&]() { if(_job->objectKey().isEmpty()) emit enableSave(canSaveNew()); else save(); }); connect(_ui.jobTreeWidget, &FilePickerWidget::settingChanged, [&]() { if(!_job->objectKey().isEmpty()) save(); }); connect(_ui.includeScheduledCheckBox, &QCheckBox::toggled, this, &JobWidget::save); connect(_ui.preservePathsCheckBox, &QCheckBox::toggled, this, &JobWidget::save); connect(_ui.traverseMountCheckBox, &QCheckBox::toggled, this, &JobWidget::save); connect(_ui.followSymLinksCheckBox, &QCheckBox::toggled, this, &JobWidget::save); connect(_ui.skipNoDumpCheckBox, &QCheckBox::toggled, this, &JobWidget::save); connect(_ui.skipFilesSizeSpinBox, &QSpinBox::editingFinished, this, &JobWidget::save); connect(_ui.skipFilesCheckBox, &QCheckBox::toggled, this, &JobWidget::save); connect(_ui.skipFilesLineEdit, &QLineEdit::editingFinished, this, &JobWidget::save); connect(_ui.hideButton, &QPushButton::clicked, this, &JobWidget::collapse); connect(_ui.restoreButton, &QPushButton::clicked, this, &JobWidget::restoreButtonClicked); connect(_ui.backupButton, &QPushButton::clicked, this, &JobWidget::backupButtonClicked); connect(_ui.archiveListWidget, &ArchiveListWidget::inspectArchive, this, &JobWidget::inspectJobArchive); connect(_ui.archiveListWidget, &ArchiveListWidget::restoreArchive, this, &JobWidget::restoreJobArchive); connect(_ui.archiveListWidget, &ArchiveListWidget::deleteArchives, this, &JobWidget::deleteJobArchives); connect(_ui.skipFilesDefaultsButton, &QPushButton::clicked, [&]() { QSettings settings; _ui.skipFilesLineEdit->setText( settings.value("app/skip_system_files", DEFAULT_SKIP_FILES).toString()); }); connect(_ui.archiveListWidget, &ArchiveListWidget::customContextMenuRequested, this, &JobWidget::showArchiveListMenu); connect(_ui.actionDelete, &QAction::triggered, _ui.archiveListWidget, &ArchiveListWidget::removeSelectedItems); connect(_ui.actionRestore, &QAction::triggered, _ui.archiveListWidget, &ArchiveListWidget::restoreSelectedItem); connect(_ui.actionInspect, &QAction::triggered, _ui.archiveListWidget, &ArchiveListWidget::inspectSelectedItem); } JobWidget::~JobWidget() { } JobPtr JobWidget::job() const { return _job; } void JobWidget::setJob(const JobPtr &job) { if(_job) { _job->removeWatcher(); disconnect(_job.data(), &Job::fsEvent, this, &JobWidget::fsEventReceived); disconnect(_job.data(), &Job::changed, this, &JobWidget::updateDetails); } _saveEnabled = false; _job = job; // Creating a new job? if(_job->objectKey().isEmpty()) { _ui.tabWidget->setTabEnabled(_ui.tabWidget->indexOf(_ui.archiveListTab), false); _ui.restoreButton->hide(); _ui.backupButton->hide(); _ui.infoLabel->hide(); _ui.jobNameLabel->hide(); _ui.jobNameLineEdit->setText(_job->name()); _ui.jobNameLineEdit->show(); _ui.jobNameLineEdit->setFocus(); } else { _ui.tabWidget->setTabEnabled(_ui.tabWidget->indexOf(_ui.archiveListTab), true); _ui.restoreButton->show(); _ui.backupButton->show(); _ui.jobNameLabel->show(); _ui.jobNameLineEdit->hide(); connect(_job.data(), &Job::changed, this, &JobWidget::updateDetails); connect(_job.data(), &Job::fsEvent, this, &JobWidget::fsEventReceived); job->installWatcher(); } _ui.tabWidget->setCurrentWidget(_ui.jobTreeTab); updateDetails(); _saveEnabled = true; } void JobWidget::save() { if(_saveEnabled && !_job->name().isEmpty()) { DEBUG << "SAVE JOB"; _job->setUrls(_ui.jobTreeWidget->getSelectedUrls()); _job->removeWatcher(); _job->installWatcher(); _job->setOptionScheduledEnabled( _ui.includeScheduledCheckBox->isChecked()); _job->setOptionPreservePaths(_ui.preservePathsCheckBox->isChecked()); _job->setOptionTraverseMount(_ui.traverseMountCheckBox->isChecked()); _job->setOptionFollowSymLinks(_ui.followSymLinksCheckBox->isChecked()); _job->setOptionSkipNoDump(_ui.skipNoDumpCheckBox->isChecked()); _job->setOptionSkipFilesSize(_ui.skipFilesSizeSpinBox->value()); _job->setOptionSkipFiles(_ui.skipFilesCheckBox->isChecked()); _job->setOptionSkipFilesPatterns(_ui.skipFilesLineEdit->text()); _job->setSettingShowHidden(_ui.jobTreeWidget->settingShowHidden()); _job->setSettingShowSystem(_ui.jobTreeWidget->settingShowSystem()); _job->setSettingHideSymlinks(_ui.jobTreeWidget->settingHideSymlinks()); _job->save(); verifyJob(); } } void JobWidget::saveNew() { if(!canSaveNew()) return; DEBUG << "SAVE NEW JOB"; _job->setName(_ui.jobNameLineEdit->text()); if(!_job->archives().isEmpty()) { auto confirm = QMessageBox::question(this, "Add job", tr("Assign %1 found archives to this" " Job?").arg(_job->archives().count()), QMessageBox::Yes | QMessageBox::No, QMessageBox::No); QList<ArchivePtr> empty; if(confirm == QMessageBox::No) _job->setArchives(empty); } save(); foreach(ArchivePtr archive, _job->archives()) { archive->setJobRef(_job->objectKey()); archive->save(); } emit jobAdded(_job); } void JobWidget::updateMatchingArchives(QList<ArchivePtr> archives) { if(!archives.isEmpty()) { _ui.infoLabel->setText(tr("Found %1 unassigned archives matching this" " Job description. Go to Archives tab below" " to review.").arg(archives.count())); _ui.infoLabel->show(); _ui.tabWidget->setTabEnabled(_ui.tabWidget->indexOf(_ui.archiveListTab), true); } else { _ui.infoLabel->clear(); _ui.infoLabel->hide(); _ui.tabWidget->setTabEnabled(_ui.tabWidget->indexOf(_ui.archiveListTab), false); } _job->setArchives(archives); _ui.archiveListWidget->clear(); _ui.archiveListWidget->addArchives(_job->archives()); _ui.tabWidget->setTabText(_ui.tabWidget->indexOf(_ui.archiveListTab), tr("Archives (%1)").arg(_job->archives().count())); } void JobWidget::updateDetails() { if(!_job) return; DEBUG << "UPDATE JOB DETAILS"; _saveEnabled = false; _ui.jobNameLabel->setText(_job->name()); _ui.jobTreeWidget->setSettingShowHidden(_job->settingShowHidden()); _ui.jobTreeWidget->setSettingShowSystem(_job->settingShowSystem()); _ui.jobTreeWidget->setSettingHideSymlinks(_job->settingHideSymlinks()); _ui.jobTreeWidget->blockSignals(true); _ui.jobTreeWidget->setSelectedUrls(_job->urls()); _ui.jobTreeWidget->blockSignals(false); _ui.archiveListWidget->clear(); _ui.archiveListWidget->addArchives(_job->archives()); _ui.includeScheduledCheckBox->setChecked(_job->optionScheduledEnabled()); _ui.preservePathsCheckBox->setChecked(_job->optionPreservePaths()); _ui.traverseMountCheckBox->setChecked(_job->optionTraverseMount()); _ui.followSymLinksCheckBox->setChecked(_job->optionFollowSymLinks()); _ui.skipNoDumpCheckBox->setChecked(_job->optionSkipNoDump()); _ui.skipFilesSizeSpinBox->setValue(_job->optionSkipFilesSize()); _ui.skipFilesCheckBox->setChecked(_job->optionSkipFiles()); _ui.skipFilesLineEdit->setText(_job->optionSkipFilesPatterns()); _ui.tabWidget->setTabText(_ui.tabWidget->indexOf(_ui.archiveListTab), tr("Archives (%1)").arg(_job->archives().count())); verifyJob(); _saveEnabled = true; } void JobWidget::restoreButtonClicked() { if(_job && !_job->archives().isEmpty()) { ArchivePtr archive = _job->archives().first(); RestoreDialog restoreDialog(archive, this); if(QDialog::Accepted == restoreDialog.exec()) emit restoreJobArchive(archive, restoreDialog.getOptions()); } } void JobWidget::backupButtonClicked() { if(_job) emit backupJob(_job); } bool JobWidget::canSaveNew() { if(_job->objectKey().isEmpty() && !_ui.jobNameLineEdit->text().isEmpty()) { _job->setName(_ui.jobNameLineEdit->text()); if(!_job->findObjectWithKey(_job->name())) { emit findMatchingArchives(_job->archivePrefix()); if(!_ui.jobTreeWidget->getSelectedUrls().isEmpty()) return true; } else { _ui.infoLabel->setText(tr("Job name must be unique amongst existing" " Jobs.")); _ui.infoLabel->show(); } } return false; } void JobWidget::showArchiveListMenu(const QPoint &pos) { QPoint globalPos = _ui.archiveListWidget->viewport()->mapToGlobal(pos); QMenu archiveListMenu(_ui.archiveListWidget); if(!_ui.archiveListWidget->selectedItems().isEmpty()) { if(_ui.archiveListWidget->selectedItems().count() == 1) { archiveListMenu.addAction(_ui.actionInspect); archiveListMenu.addAction(_ui.actionRestore); } archiveListMenu.addAction(_ui.actionDelete); } archiveListMenu.exec(globalPos); } void JobWidget::fsEventReceived() { _fsEventUpdate.start(250); //coalesce update events with a 250ms time delay } void JobWidget::showJobPathsWarn() { if(_job->urls().isEmpty()) return; QMessageBox *msg = new QMessageBox(this); msg->setAttribute(Qt::WA_DeleteOnClose, true); msg->setText(tr("Previously selected backup paths for this Job are not" " accessible anymore and thus backups may be incomplete." " Mount missing drives or make a new selection. Press Show" " details to list all backup paths for Job %1:").arg(_job->name())); QStringList urls; foreach(QUrl url, _job->urls()) urls << url.toLocalFile(); msg->setDetailedText(urls.join('\n')); msg->show(); } void JobWidget::verifyJob() { if(_job->objectKey().isEmpty()) return; _ui.jobTreeWidget->blockSignals(true); _ui.jobTreeWidget->setSelectedUrls(_job->urls()); _ui.jobTreeWidget->blockSignals(false); _ui.infoLabel->setVisible(!_job->validateUrls()); if(!_job->validateUrls()) { if(_job->urls().isEmpty()) { _ui.infoLabel->setText(tr("This Job has no backup paths selected. " "Please make a selection.")); } else { _ui.infoLabel->setText(tr("Previously selected backup paths are not" " accessible. Click here for details.")); } } } <|endoftext|>
<commit_before>/** ****************************************************************************** * Xenia : Xbox 360 Emulator Research Project * ****************************************************************************** * Copyright 2013 Ben Vanik. All rights reserved. * * Released under the BSD license - see LICENSE in the root for more details. * ****************************************************************************** */ #include "xenia/kernel/xfile.h" #include "xenia/base/byte_stream.h" #include "xenia/base/logging.h" #include "xenia/base/math.h" #include "xenia/kernel/kernel_state.h" #include "xenia/kernel/xevent.h" namespace xe { namespace kernel { XFile::XFile(KernelState* kernel_state, vfs::File* file) : XObject(kernel_state, kTypeFile), file_(file) { async_event_ = threading::Event::CreateAutoResetEvent(false); } XFile::XFile() : XObject(kTypeFile) {} XFile::~XFile() { // TODO(benvanik): signal that the file is closing? async_event_->Set(); file_->Destroy(); } X_STATUS XFile::QueryDirectory(X_FILE_DIRECTORY_INFORMATION* out_info, size_t length, const char* file_name, bool restart) { assert_not_null(out_info); vfs::Entry* entry = nullptr; if (file_name != nullptr) { // Only queries in the current directory are supported for now. assert_true(std::strchr(file_name, '\\') == nullptr); find_engine_.SetRule(file_name); // Always restart the search? find_index_ = 0; entry = file_->entry()->IterateChildren(find_engine_, &find_index_); if (!entry) { return X_STATUS_NO_SUCH_FILE; } } else { if (restart) { find_index_ = 0; } entry = file_->entry()->IterateChildren(find_engine_, &find_index_); if (!entry) { return X_STATUS_NO_SUCH_FILE; } } auto end = reinterpret_cast<uint8_t*>(out_info) + length; const auto& entry_name = entry->name(); if (reinterpret_cast<uint8_t*>(&out_info->file_name[0]) + entry_name.size() > end) { assert_always("Buffer overflow?"); return X_STATUS_NO_SUCH_FILE; } out_info->next_entry_offset = 0; out_info->file_index = static_cast<uint32_t>(find_index_); out_info->creation_time = entry->create_timestamp(); out_info->last_access_time = entry->access_timestamp(); out_info->last_write_time = entry->write_timestamp(); out_info->change_time = entry->write_timestamp(); out_info->end_of_file = entry->size(); out_info->allocation_size = entry->allocation_size(); out_info->attributes = entry->attributes(); out_info->file_name_length = static_cast<uint32_t>(entry_name.size()); std::memcpy(out_info->file_name, entry_name.data(), entry_name.size()); return X_STATUS_SUCCESS; } X_STATUS XFile::Read(void* buffer, size_t buffer_length, size_t byte_offset, size_t* out_bytes_read, uint32_t apc_context) { if (byte_offset == -1) { // Read from current position. byte_offset = position_; } size_t bytes_read = 0; X_STATUS result = file_->ReadSync(buffer, buffer_length, byte_offset, &bytes_read); if (XSUCCEEDED(result)) { position_ += bytes_read; } XIOCompletion::IONotification notify; notify.apc_context = apc_context; notify.num_bytes = uint32_t(bytes_read); notify.status = result; NotifyIOCompletionPorts(notify); if (out_bytes_read) { *out_bytes_read = bytes_read; } async_event_->Set(); return result; } X_STATUS XFile::Write(const void* buffer, size_t buffer_length, size_t byte_offset, size_t* out_bytes_written, uint32_t apc_context) { if (byte_offset == -1) { // Write from current position. byte_offset = position_; } size_t bytes_written = 0; X_STATUS result = file_->WriteSync(buffer, buffer_length, byte_offset, &bytes_written); if (XSUCCEEDED(result)) { position_ += bytes_written; } XIOCompletion::IONotification notify; notify.apc_context = apc_context; notify.num_bytes = uint32_t(bytes_written); notify.status = result; NotifyIOCompletionPorts(notify); if (out_bytes_written) { *out_bytes_written = bytes_written; } async_event_->Set(); return result; } void XFile::RegisterIOCompletionPort(uint32_t key, object_ref<XIOCompletion> port) { std::lock_guard<std::mutex> lock(completion_port_lock_); completion_ports_.push_back({key, port}); } void XFile::RemoveIOCompletionPort(uint32_t key) { std::lock_guard<std::mutex> lock(completion_port_lock_); for (auto it = completion_ports_.begin(); it != completion_ports_.end(); it++) { if (it->first == key) { completion_ports_.erase(it); break; } } } bool XFile::Save(ByteStream* stream) { XELOGD("XFile %.8X (%s)", handle(), file_->entry()->absolute_path().c_str()); if (!SaveObject(stream)) { return false; } stream->Write(file_->entry()->absolute_path()); stream->Write<uint64_t>(position_); stream->Write(file_access()); return true; } object_ref<XFile> XFile::Restore(KernelState* kernel_state, ByteStream* stream) { auto file = new XFile(); file->kernel_state_ = kernel_state; if (!file->RestoreObject(stream)) { delete file; return nullptr; } auto abs_path = stream->Read<std::string>(); uint64_t position = stream->Read<uint64_t>(); auto access = stream->Read<uint32_t>(); XELOGD("XFile %.8X (%s)", file->handle(), abs_path.c_str()); vfs::File* vfs_file = nullptr; vfs::FileAction action; auto res = kernel_state->file_system()->OpenFile( abs_path, vfs::FileDisposition::kOpen, access, &vfs_file, &action); if (XFAILED(res)) { XELOGE("Failed to open XFile: error %.8X", res); return object_ref<XFile>(file); } file->file_ = vfs_file; file->position_ = position; return object_ref<XFile>(file); } void XFile::NotifyIOCompletionPorts( XIOCompletion::IONotification& notification) { std::lock_guard<std::mutex> lock(completion_port_lock_); for (auto port : completion_ports_) { notification.key_context = port.first; port.second->QueueNotification(notification); } } } // namespace kernel } // namespace xe <commit_msg>XFile setup async_event_ in the restore constructor<commit_after>/** ****************************************************************************** * Xenia : Xbox 360 Emulator Research Project * ****************************************************************************** * Copyright 2013 Ben Vanik. All rights reserved. * * Released under the BSD license - see LICENSE in the root for more details. * ****************************************************************************** */ #include "xenia/kernel/xfile.h" #include "xenia/base/byte_stream.h" #include "xenia/base/logging.h" #include "xenia/base/math.h" #include "xenia/kernel/kernel_state.h" #include "xenia/kernel/xevent.h" namespace xe { namespace kernel { XFile::XFile(KernelState* kernel_state, vfs::File* file) : XObject(kernel_state, kTypeFile), file_(file) { async_event_ = threading::Event::CreateAutoResetEvent(false); } XFile::XFile() : XObject(kTypeFile) { async_event_ = threading::Event::CreateAutoResetEvent(false); } XFile::~XFile() { // TODO(benvanik): signal that the file is closing? async_event_->Set(); file_->Destroy(); } X_STATUS XFile::QueryDirectory(X_FILE_DIRECTORY_INFORMATION* out_info, size_t length, const char* file_name, bool restart) { assert_not_null(out_info); vfs::Entry* entry = nullptr; if (file_name != nullptr) { // Only queries in the current directory are supported for now. assert_true(std::strchr(file_name, '\\') == nullptr); find_engine_.SetRule(file_name); // Always restart the search? find_index_ = 0; entry = file_->entry()->IterateChildren(find_engine_, &find_index_); if (!entry) { return X_STATUS_NO_SUCH_FILE; } } else { if (restart) { find_index_ = 0; } entry = file_->entry()->IterateChildren(find_engine_, &find_index_); if (!entry) { return X_STATUS_NO_SUCH_FILE; } } auto end = reinterpret_cast<uint8_t*>(out_info) + length; const auto& entry_name = entry->name(); if (reinterpret_cast<uint8_t*>(&out_info->file_name[0]) + entry_name.size() > end) { assert_always("Buffer overflow?"); return X_STATUS_NO_SUCH_FILE; } out_info->next_entry_offset = 0; out_info->file_index = static_cast<uint32_t>(find_index_); out_info->creation_time = entry->create_timestamp(); out_info->last_access_time = entry->access_timestamp(); out_info->last_write_time = entry->write_timestamp(); out_info->change_time = entry->write_timestamp(); out_info->end_of_file = entry->size(); out_info->allocation_size = entry->allocation_size(); out_info->attributes = entry->attributes(); out_info->file_name_length = static_cast<uint32_t>(entry_name.size()); std::memcpy(out_info->file_name, entry_name.data(), entry_name.size()); return X_STATUS_SUCCESS; } X_STATUS XFile::Read(void* buffer, size_t buffer_length, size_t byte_offset, size_t* out_bytes_read, uint32_t apc_context) { if (byte_offset == -1) { // Read from current position. byte_offset = position_; } size_t bytes_read = 0; X_STATUS result = file_->ReadSync(buffer, buffer_length, byte_offset, &bytes_read); if (XSUCCEEDED(result)) { position_ += bytes_read; } XIOCompletion::IONotification notify; notify.apc_context = apc_context; notify.num_bytes = uint32_t(bytes_read); notify.status = result; NotifyIOCompletionPorts(notify); if (out_bytes_read) { *out_bytes_read = bytes_read; } async_event_->Set(); return result; } X_STATUS XFile::Write(const void* buffer, size_t buffer_length, size_t byte_offset, size_t* out_bytes_written, uint32_t apc_context) { if (byte_offset == -1) { // Write from current position. byte_offset = position_; } size_t bytes_written = 0; X_STATUS result = file_->WriteSync(buffer, buffer_length, byte_offset, &bytes_written); if (XSUCCEEDED(result)) { position_ += bytes_written; } XIOCompletion::IONotification notify; notify.apc_context = apc_context; notify.num_bytes = uint32_t(bytes_written); notify.status = result; NotifyIOCompletionPorts(notify); if (out_bytes_written) { *out_bytes_written = bytes_written; } async_event_->Set(); return result; } void XFile::RegisterIOCompletionPort(uint32_t key, object_ref<XIOCompletion> port) { std::lock_guard<std::mutex> lock(completion_port_lock_); completion_ports_.push_back({key, port}); } void XFile::RemoveIOCompletionPort(uint32_t key) { std::lock_guard<std::mutex> lock(completion_port_lock_); for (auto it = completion_ports_.begin(); it != completion_ports_.end(); it++) { if (it->first == key) { completion_ports_.erase(it); break; } } } bool XFile::Save(ByteStream* stream) { XELOGD("XFile %.8X (%s)", handle(), file_->entry()->absolute_path().c_str()); if (!SaveObject(stream)) { return false; } stream->Write(file_->entry()->absolute_path()); stream->Write<uint64_t>(position_); stream->Write(file_access()); return true; } object_ref<XFile> XFile::Restore(KernelState* kernel_state, ByteStream* stream) { auto file = new XFile(); file->kernel_state_ = kernel_state; if (!file->RestoreObject(stream)) { delete file; return nullptr; } auto abs_path = stream->Read<std::string>(); uint64_t position = stream->Read<uint64_t>(); auto access = stream->Read<uint32_t>(); XELOGD("XFile %.8X (%s)", file->handle(), abs_path.c_str()); vfs::File* vfs_file = nullptr; vfs::FileAction action; auto res = kernel_state->file_system()->OpenFile( abs_path, vfs::FileDisposition::kOpen, access, &vfs_file, &action); if (XFAILED(res)) { XELOGE("Failed to open XFile: error %.8X", res); return object_ref<XFile>(file); } file->file_ = vfs_file; file->position_ = position; return object_ref<XFile>(file); } void XFile::NotifyIOCompletionPorts( XIOCompletion::IONotification& notification) { std::lock_guard<std::mutex> lock(completion_port_lock_); for (auto port : completion_ports_) { notification.key_context = port.first; port.second->QueueNotification(notification); } } } // namespace kernel } // namespace xe <|endoftext|>
<commit_before>/* * Copyright (C) 2017 Rhys Ulerich * * 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/. */ #ifndef DESCENDU_SEXP_HPP #define DESCENDU_SEXP_HPP #include <cctype> #include <iostream> #include <iterator> #include <sstream> #include <stdexcept> #include <string> #include <type_traits> #include <utility> namespace descendu { namespace sexp { // TODO Track line/column as input processed // TODO Record line/column within each node // Such tracking most useful within stateful parser enum struct node_type { list=1, symbol, string }; template<class OutputStream> auto& operator<<(OutputStream& os, node_type type) { switch (type) { case node_type::list: os << "list"; break; case node_type::symbol: os << "symbol"; break; case node_type::string: os << "string"; break; default: throw std::logic_error("unimplemented"); } return os; } std::string to_string(const node_type& node) { std::ostringstream oss; oss << node; return oss.str(); } // Forward to permit use during error handling class node; std::string to_string(const node& sexp); // switch (node.type) { // case node_type::list: /* Use list-like methods */ break; // case node_type::symbol: /* Use node.string */ break; // case node_type::string: /* Use node.string */ break; // } class node : std::vector<node> { typedef std::vector<node> base_type; public: // Discern which type of data is contained. node_type type; // For string node access std::string string; // For list node access using base_type::at; using base_type::back; using base_type::begin; using base_type::cbegin; using base_type::cend; using base_type::emplace_back; using base_type::end; using base_type::front; using base_type::pop_back; using base_type::size; // Construct a string node explicit node(const std::string& s, const bool is_symbol = true) : base_type(0) , type(is_symbol ? node_type::symbol : node_type::string) , string(s) {}; // Move into a string node explicit node(std::string&& s, const bool is_symbol = true) : base_type(0) , type(is_symbol ? node_type::symbol : node_type::string) , string(s) {}; // Construct an empty list node node() : base_type() , type(node_type::list) , string() {}; bool operator==(const node& other) const { if (type != other.type) return false; switch (type) { case node_type::symbol: case node_type::string: return string == other.string; case node_type::list: return static_cast<const base_type&>(*this) == other; default: throw std::logic_error("Unimplemented case"); } } bool operator!=(const node& other) const { return !(*this == other); } // TODO Cleaner way to detect entire string consumed? // Permits directly casting a symbol node to any numeric type template<class T, typename = std::enable_if_t<std::is_arithmetic<T>::value>> explicit operator T() const { if (this->type != node_type::symbol) { throw std::logic_error(to_string(*this)); // Caller misused } T retval; std::istringstream iss(this->string); iss >> std::noskipws >> retval; if (!iss) { throw std::domain_error(to_string(*this)); // Malformed input } iss.get(); if (!iss.eof()) { throw std::invalid_argument(to_string(*this)); // Extraneous input } return retval; } }; namespace impl { // Helper to process C99 and S-expression escapes for parse(...) just below template<typename InputIt> std::string& append_maybe_escaped( const char c, std::string &acc, // Reference! InputIt& next, // Reference! InputIt end, const bool quoted) { if (c != '\\') return acc += c; if (next == end) throw std::invalid_argument("backslash precedes EOF"); const char q = *next++; switch (q) { case 'a': return acc += '\a'; case 'b': return acc += '\b'; case 'f': return acc += '\f'; case 'n': return acc += '\n'; case 'r': return acc += '\r'; case 't': return acc += '\t'; case 'v': return acc += '\v'; case '\'': case '\\': case '"': case '?': return acc += q; case 'x': case '0': case '1': case '2': case '3': case '4': case '5': case '6': case '7': case '8': case '9': case 'A': case 'B': case 'C': case 'D': case 'E': case 'F': throw new std::logic_error("Escaping via numeric codes unimplemented"); case '(': case ')': if (!quoted) return acc += q; // Possibly fall through } throw new std::invalid_argument(std::string("Improper escape \\") + q); } } // namespace impl // Parse zero or more S-expressions in the input returning a list. // Notice parsed input is wrapped in one additional list. That is, // 1) "(foo)(bar)" returned as ((foo)(bar)) // 2) "(foo)" returned as ((foo)) // 3) "foo" returned as (foo) // 4) "" returned as () // as otherwise non-list or trivial inputs problematic. // Based upon https://en.wikipedia.org/wiki/S-expression#Parsing // and grotesquely extended to handle different input with checking. template<typename InputIt> node parse(InputIt next, InputIt end) { node sexp; sexp.emplace_back(); std::string word; int level = 0; bool in_string = 0; while (next != end) { const char c = *next++; if (std::isspace(c)) { if (in_string) { sexp.back().emplace_back(std::move(word)); word.clear(); } in_string = false; } else if (c == '(') { ++level; sexp.emplace_back(); } else if (c == ')') { if (level == 0) { throw std::invalid_argument("unopened right parenthesis"); } if (in_string) { sexp.back().emplace_back(std::move(word)); word.clear(); } in_string = false; node temp(std::move(sexp.back())); sexp.pop_back(); sexp.back().emplace_back(std::move(temp)); --level; } else if (c == '"') { if (in_string) { sexp.back().emplace_back(std::move(word)); word.clear(); } in_string = false; for (;;) { if (next == end) throw std::invalid_argument("unclosed quote"); const char q = *next++; if (q == '"') break; impl::append_maybe_escaped(q, word, next, end, /*quoted*/true); } sexp.back().emplace_back(std::move(word), /*string*/false); word.clear(); } else { impl::append_maybe_escaped(c, word, next, end, /*quoted*/false); in_string = true; } } if (level != 0) { throw std::invalid_argument("unclosed left parenthesis"); } if (in_string) { // Required for final top-level string sexp.back().emplace_back(word); } if (!sexp.size()) { throw std::logic_error("sanity failure on size"); } if (sexp.front().type != node_type::list) { throw std::logic_error("sanity failure on type"); } return sexp.front(); } node parse(const std::string& in) { return parse(in.cbegin(), in.cend()); } node parse(std::istream& is) { return parse( std::istream_iterator<char>(is), std::istream_iterator<char>()); } template<typename OutputIterator> void copy(const node& sexp, OutputIterator out) { switch (sexp.type) { case node_type::list: { *out++ = '('; std::size_t count = 0; for (const auto& term : sexp) { if (count++) { *out++ = ' '; } copy(term, out); } *out++ = ')'; } break; case node_type::symbol: for (const char c : sexp.string) { switch (c) { case '\a': *out++ = '\\'; *out++ = 'a'; break; case '\b': *out++ = '\\'; *out++ = 'b'; break; case '\f': *out++ = '\\'; *out++ = 'f'; break; case '\n': *out++ = '\\'; *out++ = 'n'; break; case ' ': *out++ = '\\'; *out++ = ' '; break; case '?': *out++ = '\\'; *out++ = '?'; break; case '"': *out++ = '\\'; *out++ = '"'; break; case '(': *out++ = '\\'; *out++ = '('; break; case ')': *out++ = '\\'; *out++ = ')'; break; case '\'': *out++ = '\\'; *out++ = '\''; break; case '\\': *out++ = '\\'; *out++ = '\\'; break; case '\r': *out++ = '\\'; *out++ = 'r'; break; case '\t': *out++ = '\\'; *out++ = 't'; break; case '\v': *out++ = '\\'; *out++ = 'v'; break; default: *out++ = c; } } break; case node_type::string: *out++ = '"'; for (const char c : sexp.string) { switch (c) { case '\a': *out++ = '\\'; *out++ = 'a'; break; case '\b': *out++ = '\\'; *out++ = 'b'; break; case '\f': *out++ = '\\'; *out++ = 'f'; break; case '"': *out++ = '\\'; *out++ = '"'; break; case '\\': *out++ = '\\'; *out++ = '\\'; break; default: *out++ = c; } } *out++ = '"'; break; default: throw std::logic_error("Unimplemented case"); } } void copy(const node& sexp, std::ostream& os) { return copy(sexp, std::ostream_iterator<char>(os)); } std::string to_string(const node& sexp) { std::ostringstream oss; std::ostream_iterator<char> it(oss); copy(sexp, it); return oss.str(); } } // namespace } // namespace #endif <commit_msg>Add missing include<commit_after>/* * Copyright (C) 2017 Rhys Ulerich * * 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/. */ #ifndef DESCENDU_SEXP_HPP #define DESCENDU_SEXP_HPP #include <cctype> #include <iostream> #include <iterator> #include <sstream> #include <stdexcept> #include <string> #include <type_traits> #include <utility> #include <vector> namespace descendu { namespace sexp { // TODO Track line/column as input processed // TODO Record line/column within each node // Such tracking most useful within stateful parser enum struct node_type { list=1, symbol, string }; template<class OutputStream> auto& operator<<(OutputStream& os, node_type type) { switch (type) { case node_type::list: os << "list"; break; case node_type::symbol: os << "symbol"; break; case node_type::string: os << "string"; break; default: throw std::logic_error("unimplemented"); } return os; } std::string to_string(const node_type& node) { std::ostringstream oss; oss << node; return oss.str(); } // Forward to permit use during error handling class node; std::string to_string(const node& sexp); // switch (node.type) { // case node_type::list: /* Use list-like methods */ break; // case node_type::symbol: /* Use node.string */ break; // case node_type::string: /* Use node.string */ break; // } class node : std::vector<node> { typedef std::vector<node> base_type; public: // Discern which type of data is contained. node_type type; // For string node access std::string string; // For list node access using base_type::at; using base_type::back; using base_type::begin; using base_type::cbegin; using base_type::cend; using base_type::emplace_back; using base_type::end; using base_type::front; using base_type::pop_back; using base_type::size; // Construct a string node explicit node(const std::string& s, const bool is_symbol = true) : base_type(0) , type(is_symbol ? node_type::symbol : node_type::string) , string(s) {}; // Move into a string node explicit node(std::string&& s, const bool is_symbol = true) : base_type(0) , type(is_symbol ? node_type::symbol : node_type::string) , string(s) {}; // Construct an empty list node node() : base_type() , type(node_type::list) , string() {}; bool operator==(const node& other) const { if (type != other.type) return false; switch (type) { case node_type::symbol: case node_type::string: return string == other.string; case node_type::list: return static_cast<const base_type&>(*this) == other; default: throw std::logic_error("Unimplemented case"); } } bool operator!=(const node& other) const { return !(*this == other); } // TODO Cleaner way to detect entire string consumed? // Permits directly casting a symbol node to any numeric type template<class T, typename = std::enable_if_t<std::is_arithmetic<T>::value>> explicit operator T() const { if (this->type != node_type::symbol) { throw std::logic_error(to_string(*this)); // Caller misused } T retval; std::istringstream iss(this->string); iss >> std::noskipws >> retval; if (!iss) { throw std::domain_error(to_string(*this)); // Malformed input } iss.get(); if (!iss.eof()) { throw std::invalid_argument(to_string(*this)); // Extraneous input } return retval; } }; namespace impl { // Helper to process C99 and S-expression escapes for parse(...) just below template<typename InputIt> std::string& append_maybe_escaped( const char c, std::string &acc, // Reference! InputIt& next, // Reference! InputIt end, const bool quoted) { if (c != '\\') return acc += c; if (next == end) throw std::invalid_argument("backslash precedes EOF"); const char q = *next++; switch (q) { case 'a': return acc += '\a'; case 'b': return acc += '\b'; case 'f': return acc += '\f'; case 'n': return acc += '\n'; case 'r': return acc += '\r'; case 't': return acc += '\t'; case 'v': return acc += '\v'; case '\'': case '\\': case '"': case '?': return acc += q; case 'x': case '0': case '1': case '2': case '3': case '4': case '5': case '6': case '7': case '8': case '9': case 'A': case 'B': case 'C': case 'D': case 'E': case 'F': throw new std::logic_error("Escaping via numeric codes unimplemented"); case '(': case ')': if (!quoted) return acc += q; // Possibly fall through } throw new std::invalid_argument(std::string("Improper escape \\") + q); } } // namespace impl // Parse zero or more S-expressions in the input returning a list. // Notice parsed input is wrapped in one additional list. That is, // 1) "(foo)(bar)" returned as ((foo)(bar)) // 2) "(foo)" returned as ((foo)) // 3) "foo" returned as (foo) // 4) "" returned as () // as otherwise non-list or trivial inputs problematic. // Based upon https://en.wikipedia.org/wiki/S-expression#Parsing // and grotesquely extended to handle different input with checking. template<typename InputIt> node parse(InputIt next, InputIt end) { node sexp; sexp.emplace_back(); std::string word; int level = 0; bool in_string = 0; while (next != end) { const char c = *next++; if (std::isspace(c)) { if (in_string) { sexp.back().emplace_back(std::move(word)); word.clear(); } in_string = false; } else if (c == '(') { ++level; sexp.emplace_back(); } else if (c == ')') { if (level == 0) { throw std::invalid_argument("unopened right parenthesis"); } if (in_string) { sexp.back().emplace_back(std::move(word)); word.clear(); } in_string = false; node temp(std::move(sexp.back())); sexp.pop_back(); sexp.back().emplace_back(std::move(temp)); --level; } else if (c == '"') { if (in_string) { sexp.back().emplace_back(std::move(word)); word.clear(); } in_string = false; for (;;) { if (next == end) throw std::invalid_argument("unclosed quote"); const char q = *next++; if (q == '"') break; impl::append_maybe_escaped(q, word, next, end, /*quoted*/true); } sexp.back().emplace_back(std::move(word), /*string*/false); word.clear(); } else { impl::append_maybe_escaped(c, word, next, end, /*quoted*/false); in_string = true; } } if (level != 0) { throw std::invalid_argument("unclosed left parenthesis"); } if (in_string) { // Required for final top-level string sexp.back().emplace_back(word); } if (!sexp.size()) { throw std::logic_error("sanity failure on size"); } if (sexp.front().type != node_type::list) { throw std::logic_error("sanity failure on type"); } return sexp.front(); } node parse(const std::string& in) { return parse(in.cbegin(), in.cend()); } node parse(std::istream& is) { return parse( std::istream_iterator<char>(is), std::istream_iterator<char>()); } template<typename OutputIterator> void copy(const node& sexp, OutputIterator out) { switch (sexp.type) { case node_type::list: { *out++ = '('; std::size_t count = 0; for (const auto& term : sexp) { if (count++) { *out++ = ' '; } copy(term, out); } *out++ = ')'; } break; case node_type::symbol: for (const char c : sexp.string) { switch (c) { case '\a': *out++ = '\\'; *out++ = 'a'; break; case '\b': *out++ = '\\'; *out++ = 'b'; break; case '\f': *out++ = '\\'; *out++ = 'f'; break; case '\n': *out++ = '\\'; *out++ = 'n'; break; case ' ': *out++ = '\\'; *out++ = ' '; break; case '?': *out++ = '\\'; *out++ = '?'; break; case '"': *out++ = '\\'; *out++ = '"'; break; case '(': *out++ = '\\'; *out++ = '('; break; case ')': *out++ = '\\'; *out++ = ')'; break; case '\'': *out++ = '\\'; *out++ = '\''; break; case '\\': *out++ = '\\'; *out++ = '\\'; break; case '\r': *out++ = '\\'; *out++ = 'r'; break; case '\t': *out++ = '\\'; *out++ = 't'; break; case '\v': *out++ = '\\'; *out++ = 'v'; break; default: *out++ = c; } } break; case node_type::string: *out++ = '"'; for (const char c : sexp.string) { switch (c) { case '\a': *out++ = '\\'; *out++ = 'a'; break; case '\b': *out++ = '\\'; *out++ = 'b'; break; case '\f': *out++ = '\\'; *out++ = 'f'; break; case '"': *out++ = '\\'; *out++ = '"'; break; case '\\': *out++ = '\\'; *out++ = '\\'; break; default: *out++ = c; } } *out++ = '"'; break; default: throw std::logic_error("Unimplemented case"); } } void copy(const node& sexp, std::ostream& os) { return copy(sexp, std::ostream_iterator<char>(os)); } std::string to_string(const node& sexp) { std::ostringstream oss; std::ostream_iterator<char> it(oss); copy(sexp, it); return oss.str(); } } // namespace } // namespace #endif <|endoftext|>
<commit_before>/************************************************************************* * * OpenOffice.org - a multi-platform office productivity suite * * $RCSfile: reflcnst.hxx,v $ * * $Revision: 1.5 $ * * last change: $Author: rt $ $Date: 2005-09-09 05:15:25 $ * * 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 _REFLCNST_HXX_ #define _REFLCNST_HXX_ #ifndef _REGISTRY_REFLTYPE_HXX_ #include <registry/refltype.hxx> #endif #ifndef _SAL_MACROS_H_ #include <sal/macros.h> #endif #include <string.h> #define REGTYPE_IEEE_NATIVE 1 extern const sal_uInt32 magic; extern const sal_uInt16 minorVersion; extern const sal_uInt16 majorVersion; #define OFFSET_MAGIC 0 #define OFFSET_SIZE (OFFSET_MAGIC + sizeof(magic)) #define OFFSET_MINOR_VERSION (OFFSET_SIZE + sizeof(sal_uInt32)) #define OFFSET_MAJOR_VERSION (OFFSET_MINOR_VERSION + sizeof(minorVersion)) #define OFFSET_N_ENTRIES (OFFSET_MAJOR_VERSION + sizeof(sal_uInt16)) #define OFFSET_TYPE_SOURCE (OFFSET_N_ENTRIES + sizeof(sal_uInt16)) #define OFFSET_TYPE_CLASS (OFFSET_TYPE_SOURCE + sizeof(sal_uInt16)) #define OFFSET_THIS_TYPE (OFFSET_TYPE_CLASS + sizeof(sal_uInt16)) #define OFFSET_UIK (OFFSET_THIS_TYPE + sizeof(sal_uInt16)) #define OFFSET_DOKU (OFFSET_UIK + sizeof(sal_uInt16)) #define OFFSET_FILENAME (OFFSET_DOKU + sizeof(sal_uInt16)) #define OFFSET_N_SUPERTYPES (OFFSET_FILENAME + sizeof(sal_uInt16)) #define OFFSET_SUPERTYPES (OFFSET_N_SUPERTYPES + sizeof(sal_uInt16)) #define OFFSET_CP_SIZE (OFFSET_SUPERTYPES + sizeof(sal_uInt16)) #define OFFSET_CP (OFFSET_CP_SIZE + sizeof(sal_uInt16)) #define CP_OFFSET_ENTRY_SIZE 0 #define CP_OFFSET_ENTRY_TAG (CP_OFFSET_ENTRY_SIZE + sizeof(sal_uInt32)) #define CP_OFFSET_ENTRY_DATA (CP_OFFSET_ENTRY_TAG + sizeof(sal_uInt16)) #define CP_OFFSET_ENTRY_UIK1 CP_OFFSET_ENTRY_DATA #define CP_OFFSET_ENTRY_UIK2 (CP_OFFSET_ENTRY_UIK1 + sizeof(sal_uInt32)) #define CP_OFFSET_ENTRY_UIK3 (CP_OFFSET_ENTRY_UIK2 + sizeof(sal_uInt16)) #define CP_OFFSET_ENTRY_UIK4 (CP_OFFSET_ENTRY_UIK3 + sizeof(sal_uInt16)) #define CP_OFFSET_ENTRY_UIK5 (CP_OFFSET_ENTRY_UIK4 + sizeof(sal_uInt32)) #define FIELD_OFFSET_ACCESS 0 #define FIELD_OFFSET_NAME (FIELD_OFFSET_ACCESS + sizeof(sal_uInt16)) #define FIELD_OFFSET_TYPE (FIELD_OFFSET_NAME + sizeof(sal_uInt16)) #define FIELD_OFFSET_VALUE (FIELD_OFFSET_TYPE + sizeof(sal_uInt16)) #define FIELD_OFFSET_DOKU (FIELD_OFFSET_VALUE + sizeof(sal_uInt16)) #define FIELD_OFFSET_FILENAME (FIELD_OFFSET_DOKU + sizeof(sal_uInt16)) //#define FIELD_ENTRY_SIZE (FIELD_OFFSET_FILENAME + sizeof(sal_uInt16)) #define PARAM_OFFSET_TYPE 0 #define PARAM_OFFSET_MODE (PARAM_OFFSET_TYPE + sizeof(sal_uInt16)) #define PARAM_OFFSET_NAME (PARAM_OFFSET_MODE + sizeof(sal_uInt16)) //#define PARAM_ENTRY_SIZE (PARAM_OFFSET_NAME + sizeof(sal_uInt16)) #define METHOD_OFFSET_SIZE 0 #define METHOD_OFFSET_MODE (METHOD_OFFSET_SIZE + sizeof(sal_uInt16)) #define METHOD_OFFSET_NAME (METHOD_OFFSET_MODE + sizeof(sal_uInt16)) #define METHOD_OFFSET_RETURN (METHOD_OFFSET_NAME + sizeof(sal_uInt16)) #define METHOD_OFFSET_DOKU (METHOD_OFFSET_RETURN + sizeof(sal_uInt16)) #define METHOD_OFFSET_PARAM_COUNT (METHOD_OFFSET_DOKU + sizeof(sal_uInt16)) //#define METHOD_OFFSET_PARAM(i) (METHOD_OFFSET_PARAM_COUNT + sizeof(sal_uInt16) + (i * PARAM_ENTRY_SIZE)) #define REFERENCE_OFFSET_TYPE 0 #define REFERENCE_OFFSET_NAME (REFERENCE_OFFSET_TYPE + sizeof(sal_uInt16)) #define REFERENCE_OFFSET_DOKU (REFERENCE_OFFSET_NAME + sizeof(sal_uInt16)) #define REFERENCE_OFFSET_ACCESS (REFERENCE_OFFSET_DOKU + sizeof(sal_uInt16)) //#define REFERENCE_ENTRY_SIZE (REFERENCE_OFFSET_ACCESS + sizeof(sal_uInt16)) enum CPInfoTag { CP_TAG_INVALID = RT_TYPE_NONE, CP_TAG_CONST_BOOL = RT_TYPE_BOOL, CP_TAG_CONST_BYTE = RT_TYPE_BYTE, CP_TAG_CONST_INT16 = RT_TYPE_INT16, CP_TAG_CONST_UINT16 = RT_TYPE_UINT16, CP_TAG_CONST_INT32 = RT_TYPE_INT32, CP_TAG_CONST_UINT32 = RT_TYPE_UINT32, CP_TAG_CONST_INT64 = RT_TYPE_INT64, CP_TAG_CONST_UINT64 = RT_TYPE_UINT64, CP_TAG_CONST_FLOAT = RT_TYPE_FLOAT, CP_TAG_CONST_DOUBLE = RT_TYPE_DOUBLE, CP_TAG_CONST_STRING = RT_TYPE_STRING, CP_TAG_UTF8_NAME, CP_TAG_UIK }; inline sal_uInt32 writeBYTE(sal_uInt8* buffer, sal_uInt8 v) { buffer[0] = v; return sizeof(sal_uInt8); } inline sal_uInt16 readBYTE(const sal_uInt8* buffer, sal_uInt8& v) { v = buffer[0]; return sizeof(sal_uInt8); } inline sal_uInt32 writeINT16(sal_uInt8* buffer, sal_Int16 v) { buffer[0] = (sal_uInt8)((v >> 8) & 0xFF); buffer[1] = (sal_uInt8)((v >> 0) & 0xFF); return sizeof(sal_Int16); } inline sal_uInt32 readINT16(const sal_uInt8* buffer, sal_Int16& v) { v = ((buffer[0] << 8) | (buffer[1] << 0)); return sizeof(sal_Int16); } inline sal_uInt32 writeUINT16(sal_uInt8* buffer, sal_uInt16 v) { buffer[0] = (sal_uInt8)((v >> 8) & 0xFF); buffer[1] = (sal_uInt8)((v >> 0) & 0xFF); return sizeof(sal_uInt16); } inline sal_uInt32 readUINT16(const sal_uInt8* buffer, sal_uInt16& v) { v = ((buffer[0] << 8) | (buffer[1] << 0)); return sizeof(sal_uInt16); } inline sal_uInt32 writeINT32(sal_uInt8* buffer, sal_Int32 v) { buffer[0] = (sal_uInt8)((v >> 24) & 0xFF); buffer[1] = (sal_uInt8)((v >> 16) & 0xFF); buffer[2] = (sal_uInt8)((v >> 8) & 0xFF); buffer[3] = (sal_uInt8)((v >> 0) & 0xFF); return sizeof(sal_Int32); } inline sal_uInt32 readINT32(const sal_uInt8* buffer, sal_Int32& v) { v = ( (buffer[0] << 24) | (buffer[1] << 16) | (buffer[2] << 8) | (buffer[3] << 0) ); return sizeof(sal_Int32); } inline sal_uInt32 writeUINT32(sal_uInt8* buffer, sal_uInt32 v) { buffer[0] = (sal_uInt8)((v >> 24) & 0xFF); buffer[1] = (sal_uInt8)((v >> 16) & 0xFF); buffer[2] = (sal_uInt8)((v >> 8) & 0xFF); buffer[3] = (sal_uInt8)((v >> 0) & 0xFF); return sizeof(sal_uInt32); } inline sal_uInt32 readUINT32(const sal_uInt8* buffer, sal_uInt32& v) { v = ( (buffer[0] << 24) | (buffer[1] << 16) | (buffer[2] << 8) | (buffer[3] << 0) ); return sizeof(sal_uInt32); } inline sal_uInt32 writeINT64(sal_uInt8* buffer, sal_Int64 v) { buffer[0] = (sal_uInt8)((v >> 56) & 0xFF); buffer[1] = (sal_uInt8)((v >> 48) & 0xFF); buffer[2] = (sal_uInt8)((v >> 40) & 0xFF); buffer[3] = (sal_uInt8)((v >> 32) & 0xFF); buffer[4] = (sal_uInt8)((v >> 24) & 0xFF); buffer[5] = (sal_uInt8)((v >> 16) & 0xFF); buffer[6] = (sal_uInt8)((v >> 8) & 0xFF); buffer[7] = (sal_uInt8)((v >> 0) & 0xFF); return sizeof(sal_Int64); } inline sal_uInt32 readINT64(const sal_uInt8* buffer, sal_Int64& v) { v = ( ((sal_Int64)buffer[0] << 56) | ((sal_Int64)buffer[1] << 48) | ((sal_Int64)buffer[2] << 40) | ((sal_Int64)buffer[3] << 32) | ((sal_Int64)buffer[4] << 24) | ((sal_Int64)buffer[5] << 16) | ((sal_Int64)buffer[6] << 8) | ((sal_Int64)buffer[7] << 0) ); return sizeof(sal_Int64); } inline sal_uInt32 writeUINT64(sal_uInt8* buffer, sal_uInt64 v) { buffer[0] = (sal_uInt8)((v >> 56) & 0xFF); buffer[1] = (sal_uInt8)((v >> 48) & 0xFF); buffer[2] = (sal_uInt8)((v >> 40) & 0xFF); buffer[3] = (sal_uInt8)((v >> 32) & 0xFF); buffer[4] = (sal_uInt8)((v >> 24) & 0xFF); buffer[5] = (sal_uInt8)((v >> 16) & 0xFF); buffer[6] = (sal_uInt8)((v >> 8) & 0xFF); buffer[7] = (sal_uInt8)((v >> 0) & 0xFF); return sizeof(sal_uInt64); } inline sal_uInt32 readUINT64(const sal_uInt8* buffer, sal_uInt64& v) { v = ( ((sal_uInt64)buffer[0] << 56) | ((sal_uInt64)buffer[1] << 48) | ((sal_uInt64)buffer[2] << 40) | ((sal_uInt64)buffer[3] << 32) | ((sal_uInt64)buffer[4] << 24) | ((sal_uInt64)buffer[5] << 16) | ((sal_uInt64)buffer[6] << 8) | ((sal_uInt64)buffer[7] << 0) ); return sizeof(sal_uInt64); } inline sal_uInt32 writeUtf8(sal_uInt8* buffer, const sal_Char* v) { sal_uInt32 size = strlen(v) + 1; memcpy(buffer, v, size); return (size); } inline sal_uInt32 readUtf8(const sal_uInt8* buffer, sal_Char* v, sal_uInt32 maxSize) { sal_uInt32 size = SAL_MIN(strlen((const sal_Char*) buffer) + 1, maxSize); memcpy(v, buffer, size); if (size == maxSize) v[size - 1] = '\0'; return (size); } sal_uInt32 writeFloat(sal_uInt8* buffer, float v); sal_uInt32 readFloat(const sal_uInt8* buffer, float& v); sal_uInt32 writeDouble(sal_uInt8* buffer, double v); sal_uInt32 readDouble(const sal_uInt8* buffer, double& v); sal_uInt32 writeString(sal_uInt8* buffer, const sal_Unicode* v); sal_uInt32 readString(const sal_uInt8* buffer, sal_Unicode* v, sal_uInt32 maxSize); sal_uInt32 UINT16StringLen(const sal_uInt8* wstring); #endif <commit_msg>INTEGRATION: CWS changefileheader (1.5.66); FILE MERGED 2008/04/01 15:23:07 thb 1.5.66.3: #i85898# Stripping all external header guards 2008/04/01 12:32:40 thb 1.5.66.2: #i85898# Stripping all external header guards 2008/03/31 07:25:17 rt 1.5.66.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: reflcnst.hxx,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. * ************************************************************************/ #ifndef _REFLCNST_HXX_ #define _REFLCNST_HXX_ #include <registry/refltype.hxx> #include <sal/macros.h> #include <string.h> #define REGTYPE_IEEE_NATIVE 1 extern const sal_uInt32 magic; extern const sal_uInt16 minorVersion; extern const sal_uInt16 majorVersion; #define OFFSET_MAGIC 0 #define OFFSET_SIZE (OFFSET_MAGIC + sizeof(magic)) #define OFFSET_MINOR_VERSION (OFFSET_SIZE + sizeof(sal_uInt32)) #define OFFSET_MAJOR_VERSION (OFFSET_MINOR_VERSION + sizeof(minorVersion)) #define OFFSET_N_ENTRIES (OFFSET_MAJOR_VERSION + sizeof(sal_uInt16)) #define OFFSET_TYPE_SOURCE (OFFSET_N_ENTRIES + sizeof(sal_uInt16)) #define OFFSET_TYPE_CLASS (OFFSET_TYPE_SOURCE + sizeof(sal_uInt16)) #define OFFSET_THIS_TYPE (OFFSET_TYPE_CLASS + sizeof(sal_uInt16)) #define OFFSET_UIK (OFFSET_THIS_TYPE + sizeof(sal_uInt16)) #define OFFSET_DOKU (OFFSET_UIK + sizeof(sal_uInt16)) #define OFFSET_FILENAME (OFFSET_DOKU + sizeof(sal_uInt16)) #define OFFSET_N_SUPERTYPES (OFFSET_FILENAME + sizeof(sal_uInt16)) #define OFFSET_SUPERTYPES (OFFSET_N_SUPERTYPES + sizeof(sal_uInt16)) #define OFFSET_CP_SIZE (OFFSET_SUPERTYPES + sizeof(sal_uInt16)) #define OFFSET_CP (OFFSET_CP_SIZE + sizeof(sal_uInt16)) #define CP_OFFSET_ENTRY_SIZE 0 #define CP_OFFSET_ENTRY_TAG (CP_OFFSET_ENTRY_SIZE + sizeof(sal_uInt32)) #define CP_OFFSET_ENTRY_DATA (CP_OFFSET_ENTRY_TAG + sizeof(sal_uInt16)) #define CP_OFFSET_ENTRY_UIK1 CP_OFFSET_ENTRY_DATA #define CP_OFFSET_ENTRY_UIK2 (CP_OFFSET_ENTRY_UIK1 + sizeof(sal_uInt32)) #define CP_OFFSET_ENTRY_UIK3 (CP_OFFSET_ENTRY_UIK2 + sizeof(sal_uInt16)) #define CP_OFFSET_ENTRY_UIK4 (CP_OFFSET_ENTRY_UIK3 + sizeof(sal_uInt16)) #define CP_OFFSET_ENTRY_UIK5 (CP_OFFSET_ENTRY_UIK4 + sizeof(sal_uInt32)) #define FIELD_OFFSET_ACCESS 0 #define FIELD_OFFSET_NAME (FIELD_OFFSET_ACCESS + sizeof(sal_uInt16)) #define FIELD_OFFSET_TYPE (FIELD_OFFSET_NAME + sizeof(sal_uInt16)) #define FIELD_OFFSET_VALUE (FIELD_OFFSET_TYPE + sizeof(sal_uInt16)) #define FIELD_OFFSET_DOKU (FIELD_OFFSET_VALUE + sizeof(sal_uInt16)) #define FIELD_OFFSET_FILENAME (FIELD_OFFSET_DOKU + sizeof(sal_uInt16)) //#define FIELD_ENTRY_SIZE (FIELD_OFFSET_FILENAME + sizeof(sal_uInt16)) #define PARAM_OFFSET_TYPE 0 #define PARAM_OFFSET_MODE (PARAM_OFFSET_TYPE + sizeof(sal_uInt16)) #define PARAM_OFFSET_NAME (PARAM_OFFSET_MODE + sizeof(sal_uInt16)) //#define PARAM_ENTRY_SIZE (PARAM_OFFSET_NAME + sizeof(sal_uInt16)) #define METHOD_OFFSET_SIZE 0 #define METHOD_OFFSET_MODE (METHOD_OFFSET_SIZE + sizeof(sal_uInt16)) #define METHOD_OFFSET_NAME (METHOD_OFFSET_MODE + sizeof(sal_uInt16)) #define METHOD_OFFSET_RETURN (METHOD_OFFSET_NAME + sizeof(sal_uInt16)) #define METHOD_OFFSET_DOKU (METHOD_OFFSET_RETURN + sizeof(sal_uInt16)) #define METHOD_OFFSET_PARAM_COUNT (METHOD_OFFSET_DOKU + sizeof(sal_uInt16)) //#define METHOD_OFFSET_PARAM(i) (METHOD_OFFSET_PARAM_COUNT + sizeof(sal_uInt16) + (i * PARAM_ENTRY_SIZE)) #define REFERENCE_OFFSET_TYPE 0 #define REFERENCE_OFFSET_NAME (REFERENCE_OFFSET_TYPE + sizeof(sal_uInt16)) #define REFERENCE_OFFSET_DOKU (REFERENCE_OFFSET_NAME + sizeof(sal_uInt16)) #define REFERENCE_OFFSET_ACCESS (REFERENCE_OFFSET_DOKU + sizeof(sal_uInt16)) //#define REFERENCE_ENTRY_SIZE (REFERENCE_OFFSET_ACCESS + sizeof(sal_uInt16)) enum CPInfoTag { CP_TAG_INVALID = RT_TYPE_NONE, CP_TAG_CONST_BOOL = RT_TYPE_BOOL, CP_TAG_CONST_BYTE = RT_TYPE_BYTE, CP_TAG_CONST_INT16 = RT_TYPE_INT16, CP_TAG_CONST_UINT16 = RT_TYPE_UINT16, CP_TAG_CONST_INT32 = RT_TYPE_INT32, CP_TAG_CONST_UINT32 = RT_TYPE_UINT32, CP_TAG_CONST_INT64 = RT_TYPE_INT64, CP_TAG_CONST_UINT64 = RT_TYPE_UINT64, CP_TAG_CONST_FLOAT = RT_TYPE_FLOAT, CP_TAG_CONST_DOUBLE = RT_TYPE_DOUBLE, CP_TAG_CONST_STRING = RT_TYPE_STRING, CP_TAG_UTF8_NAME, CP_TAG_UIK }; inline sal_uInt32 writeBYTE(sal_uInt8* buffer, sal_uInt8 v) { buffer[0] = v; return sizeof(sal_uInt8); } inline sal_uInt16 readBYTE(const sal_uInt8* buffer, sal_uInt8& v) { v = buffer[0]; return sizeof(sal_uInt8); } inline sal_uInt32 writeINT16(sal_uInt8* buffer, sal_Int16 v) { buffer[0] = (sal_uInt8)((v >> 8) & 0xFF); buffer[1] = (sal_uInt8)((v >> 0) & 0xFF); return sizeof(sal_Int16); } inline sal_uInt32 readINT16(const sal_uInt8* buffer, sal_Int16& v) { v = ((buffer[0] << 8) | (buffer[1] << 0)); return sizeof(sal_Int16); } inline sal_uInt32 writeUINT16(sal_uInt8* buffer, sal_uInt16 v) { buffer[0] = (sal_uInt8)((v >> 8) & 0xFF); buffer[1] = (sal_uInt8)((v >> 0) & 0xFF); return sizeof(sal_uInt16); } inline sal_uInt32 readUINT16(const sal_uInt8* buffer, sal_uInt16& v) { v = ((buffer[0] << 8) | (buffer[1] << 0)); return sizeof(sal_uInt16); } inline sal_uInt32 writeINT32(sal_uInt8* buffer, sal_Int32 v) { buffer[0] = (sal_uInt8)((v >> 24) & 0xFF); buffer[1] = (sal_uInt8)((v >> 16) & 0xFF); buffer[2] = (sal_uInt8)((v >> 8) & 0xFF); buffer[3] = (sal_uInt8)((v >> 0) & 0xFF); return sizeof(sal_Int32); } inline sal_uInt32 readINT32(const sal_uInt8* buffer, sal_Int32& v) { v = ( (buffer[0] << 24) | (buffer[1] << 16) | (buffer[2] << 8) | (buffer[3] << 0) ); return sizeof(sal_Int32); } inline sal_uInt32 writeUINT32(sal_uInt8* buffer, sal_uInt32 v) { buffer[0] = (sal_uInt8)((v >> 24) & 0xFF); buffer[1] = (sal_uInt8)((v >> 16) & 0xFF); buffer[2] = (sal_uInt8)((v >> 8) & 0xFF); buffer[3] = (sal_uInt8)((v >> 0) & 0xFF); return sizeof(sal_uInt32); } inline sal_uInt32 readUINT32(const sal_uInt8* buffer, sal_uInt32& v) { v = ( (buffer[0] << 24) | (buffer[1] << 16) | (buffer[2] << 8) | (buffer[3] << 0) ); return sizeof(sal_uInt32); } inline sal_uInt32 writeINT64(sal_uInt8* buffer, sal_Int64 v) { buffer[0] = (sal_uInt8)((v >> 56) & 0xFF); buffer[1] = (sal_uInt8)((v >> 48) & 0xFF); buffer[2] = (sal_uInt8)((v >> 40) & 0xFF); buffer[3] = (sal_uInt8)((v >> 32) & 0xFF); buffer[4] = (sal_uInt8)((v >> 24) & 0xFF); buffer[5] = (sal_uInt8)((v >> 16) & 0xFF); buffer[6] = (sal_uInt8)((v >> 8) & 0xFF); buffer[7] = (sal_uInt8)((v >> 0) & 0xFF); return sizeof(sal_Int64); } inline sal_uInt32 readINT64(const sal_uInt8* buffer, sal_Int64& v) { v = ( ((sal_Int64)buffer[0] << 56) | ((sal_Int64)buffer[1] << 48) | ((sal_Int64)buffer[2] << 40) | ((sal_Int64)buffer[3] << 32) | ((sal_Int64)buffer[4] << 24) | ((sal_Int64)buffer[5] << 16) | ((sal_Int64)buffer[6] << 8) | ((sal_Int64)buffer[7] << 0) ); return sizeof(sal_Int64); } inline sal_uInt32 writeUINT64(sal_uInt8* buffer, sal_uInt64 v) { buffer[0] = (sal_uInt8)((v >> 56) & 0xFF); buffer[1] = (sal_uInt8)((v >> 48) & 0xFF); buffer[2] = (sal_uInt8)((v >> 40) & 0xFF); buffer[3] = (sal_uInt8)((v >> 32) & 0xFF); buffer[4] = (sal_uInt8)((v >> 24) & 0xFF); buffer[5] = (sal_uInt8)((v >> 16) & 0xFF); buffer[6] = (sal_uInt8)((v >> 8) & 0xFF); buffer[7] = (sal_uInt8)((v >> 0) & 0xFF); return sizeof(sal_uInt64); } inline sal_uInt32 readUINT64(const sal_uInt8* buffer, sal_uInt64& v) { v = ( ((sal_uInt64)buffer[0] << 56) | ((sal_uInt64)buffer[1] << 48) | ((sal_uInt64)buffer[2] << 40) | ((sal_uInt64)buffer[3] << 32) | ((sal_uInt64)buffer[4] << 24) | ((sal_uInt64)buffer[5] << 16) | ((sal_uInt64)buffer[6] << 8) | ((sal_uInt64)buffer[7] << 0) ); return sizeof(sal_uInt64); } inline sal_uInt32 writeUtf8(sal_uInt8* buffer, const sal_Char* v) { sal_uInt32 size = strlen(v) + 1; memcpy(buffer, v, size); return (size); } inline sal_uInt32 readUtf8(const sal_uInt8* buffer, sal_Char* v, sal_uInt32 maxSize) { sal_uInt32 size = SAL_MIN(strlen((const sal_Char*) buffer) + 1, maxSize); memcpy(v, buffer, size); if (size == maxSize) v[size - 1] = '\0'; return (size); } sal_uInt32 writeFloat(sal_uInt8* buffer, float v); sal_uInt32 readFloat(const sal_uInt8* buffer, float& v); sal_uInt32 writeDouble(sal_uInt8* buffer, double v); sal_uInt32 readDouble(const sal_uInt8* buffer, double& v); sal_uInt32 writeString(sal_uInt8* buffer, const sal_Unicode* v); sal_uInt32 readString(const sal_uInt8* buffer, sal_Unicode* v, sal_uInt32 maxSize); sal_uInt32 UINT16StringLen(const sal_uInt8* wstring); #endif <|endoftext|>
<commit_before> // Copyright 2010-2012 University of Washington. All Rights Reserved. // LICENSE_PLACEHOLDER // This software was created with Government support under DE // AC05-76RL01830 awarded by the United States Department of // Energy. The Government has certain rights in the software. #include <boost/test/unit_test.hpp> #include "Grappa.hpp" #include "Message.hpp" #include "MessagePool.hpp" #include "CompletionEvent.hpp" #include "ConditionVariable.hpp" #include "Delegate.hpp" #include "Tasking.hpp" #include "GlobalAllocator.hpp" #include "ParallelLoop.hpp" #include "Array.hpp" BOOST_AUTO_TEST_SUITE( New_loop_tests ); using namespace Grappa; using Grappa::wait; static bool touched = false; void test_on_all_cores() { BOOST_MESSAGE("Testing on_all_cores..."); on_all_cores([] { BOOST_MESSAGE("hello world from " << mycore() << "!"); touched = true; }); BOOST_CHECK_EQUAL(delegate::read(make_global(&touched,1)), true); BOOST_CHECK_EQUAL(touched, true); } void test_loop_decomposition() { BOOST_MESSAGE("Testing loop_decomposition_private..."); int N = 16; CompletionEvent ce(N); impl::loop_decomposition_private<2>(0, N, [&ce](int64_t start, int64_t iters) { VLOG(1) << "loop(" << start << ", " << iters << ")"; ce.complete(iters); }); ce.wait(); } void test_loop_decomposition_global() { BOOST_MESSAGE("Testing loop_decomposition_public..."); int N = 160000; CompletionEvent ce(N); auto ce_addr = make_global(&ce); impl::loop_decomposition_public(0, N, [ce_addr](int64_t start, int64_t iters) { if ( start%10000==0 ) { BOOST_MESSAGE("loop(" << start << ", " << iters << ")"); } complete(ce_addr,iters); }); ce.wait(); } CompletionEvent my_ce; void test_forall_here() { BOOST_MESSAGE("Testing forall_here..."); const int N = 15; { int x = 0; forall_here(0, N, [&x](int64_t start, int64_t iters) { CHECK(mycore() == 0); for (int64_t i=0; i<iters; i++) { x++; } }); BOOST_CHECK_EQUAL(x, N); } { int x = 0; forall_here<&my_ce,2>(0, N, [&x](int64_t start, int64_t iters) { CHECK(mycore() == 0); for (int64_t i=0; i<iters; i++) { x++; } }); BOOST_CHECK_EQUAL(x, N); } } static int test_global = 0; CompletionEvent test_global_ce; GlobalCompletionEvent my_gce; void test_forall_global_private() { BOOST_MESSAGE("Testing forall_global..."); const int64_t N = 1 << 8; BOOST_MESSAGE(" private"); forall_global_private(0, N, [](int64_t start, int64_t iters) { for (int i=0; i<iters; i++) { test_global++; } }); on_all_cores([]{ BOOST_CHECK_EQUAL(test_global, N/cores()); test_global = 0; }); forall_global_private<&test_global_ce>(0, N, [](int64_t start, int64_t iters) { for (int i=0; i<iters; i++) { test_global++; } }); on_all_cores([]{ BOOST_CHECK_EQUAL(test_global, N/cores()); test_global = 0; }); } void test_forall_global_public() { BOOST_MESSAGE("Testing forall_global_public..."); VLOG(1) << "forall_global_public"; const int64_t N = 1 << 8; on_all_cores([]{ test_global = 0; }); forall_global_public(0, N, [](int64_t s, int64_t n) { test_global += n; }); int total = 0; for (Core c = 0; c < cores(); c++) { total += delegate::read(make_global(&test_global, c)); } BOOST_CHECK_EQUAL(total, N); BOOST_MESSAGE(" with nested spawns"); VLOG(1) << "nested spawns"; on_all_cores([]{ test_global = 0; }); forall_global_public<&my_gce>(0, N, [](int64_t s, int64_t n){ for (int i=s; i<s+n; i++) { publicTask<&my_gce>([]{ test_global++; }); } }); // TODO: use reduction total = 0; for (Core c = 0; c < cores(); c++) { total += delegate::read(make_global(&test_global, c)); } BOOST_CHECK_EQUAL(total, N); } void test_forall_localized() { BOOST_MESSAGE("Testing forall_localized..."); VLOG(1) << "testing forall_localized"; const int64_t N = 100; auto array = Grappa_typed_malloc<int64_t>(N); forall_localized(array, N, [](int64_t i, int64_t& e) { e = 1; }); for (int i=0; i<N; i++) { BOOST_CHECK_EQUAL(delegate::read(array+i), 1); } BOOST_MESSAGE("Testing forall_localized_async..."); VLOG(1) << "testing forall_localized_async"; VLOG(1) << "start spawning"; forall_localized_async<&my_gce>(array+ 0, 25, [](int64_t i, int64_t& e) { e = 2; }); VLOG(1) << "after async"; forall_localized_async<&my_gce>(array+25, 25, [](int64_t i, int64_t& e) { e = 2; }); VLOG(1) << "after async"; forall_localized_async<&my_gce>(array+50, 25, [](int64_t i, int64_t& e) { e = 2; }); VLOG(1) << "after async"; forall_localized_async<&my_gce>(array+75, 25, [](int64_t i, int64_t& e) { e = 2; }); VLOG(1) << "done spawning"; my_gce.wait(); int npb = block_size / sizeof(int64_t); auto * base = array.localize(); auto * end = (array+N).localize(); for (auto* x = base; x < end; x++) { BOOST_CHECK_EQUAL(*x, 2); } VLOG(1) << "checking indexing..."; Grappa::memset(array, 0, N); forall_localized(array, N, [](int64_t i, int64_t& e){ e = i; }); for (int i=0; i<N; i++) { BOOST_CHECK_EQUAL(delegate::read(array+i), i); } Grappa::memset(array, 0, N); forall_localized_async<&my_gce>(array, N, [](int64_t i, int64_t& e){ e = i; }); my_gce.wait(); for (int i=0; i<N; i++) { BOOST_CHECK_EQUAL(delegate::read(array+i), i); } } void user_main(void * args) { CHECK(Grappa::cores() >= 2); // at least 2 nodes for these tests... test_on_all_cores(); test_loop_decomposition(); test_loop_decomposition_global(); test_forall_here(); test_forall_global_private(); test_forall_global_public(); test_forall_localized(); } BOOST_AUTO_TEST_CASE( test1 ) { Grappa_init( &(boost::unit_test::framework::master_test_suite().argc), &(boost::unit_test::framework::master_test_suite().argv) ); Grappa_activate(); Grappa_run_user_main( &user_main, (void*)NULL ); Grappa_finish( 0 ); } BOOST_AUTO_TEST_SUITE_END(); <commit_msg>Fix New_loop_test that was broken for non-power-of-2 nproc.<commit_after> // Copyright 2010-2012 University of Washington. All Rights Reserved. // LICENSE_PLACEHOLDER // This software was created with Government support under DE // AC05-76RL01830 awarded by the United States Department of // Energy. The Government has certain rights in the software. #include <boost/test/unit_test.hpp> #include "Grappa.hpp" #include "Message.hpp" #include "MessagePool.hpp" #include "CompletionEvent.hpp" #include "ConditionVariable.hpp" #include "Delegate.hpp" #include "Tasking.hpp" #include "GlobalAllocator.hpp" #include "ParallelLoop.hpp" #include "Array.hpp" BOOST_AUTO_TEST_SUITE( New_loop_tests ); using namespace Grappa; using Grappa::wait; static bool touched = false; void test_on_all_cores() { BOOST_MESSAGE("Testing on_all_cores..."); on_all_cores([] { BOOST_MESSAGE("hello world from " << mycore() << "!"); touched = true; }); BOOST_CHECK_EQUAL(delegate::read(make_global(&touched,1)), true); BOOST_CHECK_EQUAL(touched, true); } void test_loop_decomposition() { BOOST_MESSAGE("Testing loop_decomposition_private..."); int N = 16; CompletionEvent ce(N); impl::loop_decomposition_private<2>(0, N, [&ce](int64_t start, int64_t iters) { VLOG(1) << "loop(" << start << ", " << iters << ")"; ce.complete(iters); }); ce.wait(); } void test_loop_decomposition_global() { BOOST_MESSAGE("Testing loop_decomposition_public..."); int N = 160000; CompletionEvent ce(N); auto ce_addr = make_global(&ce); impl::loop_decomposition_public(0, N, [ce_addr](int64_t start, int64_t iters) { if ( start%10000==0 ) { BOOST_MESSAGE("loop(" << start << ", " << iters << ")"); } complete(ce_addr,iters); }); ce.wait(); } CompletionEvent my_ce; void test_forall_here() { BOOST_MESSAGE("Testing forall_here..."); const int N = 15; { int x = 0; forall_here(0, N, [&x](int64_t start, int64_t iters) { CHECK(mycore() == 0); for (int64_t i=0; i<iters; i++) { x++; } }); BOOST_CHECK_EQUAL(x, N); } { int x = 0; forall_here<&my_ce,2>(0, N, [&x](int64_t start, int64_t iters) { CHECK(mycore() == 0); for (int64_t i=0; i<iters; i++) { x++; } }); BOOST_CHECK_EQUAL(x, N); } } static int test_global = 0; CompletionEvent test_global_ce; GlobalCompletionEvent my_gce; void test_forall_global_private() { BOOST_MESSAGE("Testing forall_global..."); const int64_t N = 1 << 8; BOOST_MESSAGE(" private"); forall_global_private(0, N, [](int64_t start, int64_t iters) { for (int i=0; i<iters; i++) { test_global++; } }); on_all_cores([]{ range_t r = blockDist(0,N,mycore(),cores()); BOOST_CHECK_EQUAL(test_global, r.end-r.start); test_global = 0; }); forall_global_private<&test_global_ce>(0, N, [](int64_t start, int64_t iters) { for (int i=0; i<iters; i++) { test_global++; } }); on_all_cores([]{ range_t r = blockDist(0,N,mycore(),cores()); BOOST_CHECK_EQUAL(test_global, r.end-r.start); test_global = 0; }); } void test_forall_global_public() { BOOST_MESSAGE("Testing forall_global_public..."); VLOG(1) << "forall_global_public"; const int64_t N = 1 << 8; on_all_cores([]{ test_global = 0; }); forall_global_public(0, N, [](int64_t s, int64_t n) { test_global += n; }); int total = 0; for (Core c = 0; c < cores(); c++) { total += delegate::read(make_global(&test_global, c)); } BOOST_CHECK_EQUAL(total, N); BOOST_MESSAGE(" with nested spawns"); VLOG(1) << "nested spawns"; on_all_cores([]{ test_global = 0; }); forall_global_public<&my_gce>(0, N, [](int64_t s, int64_t n){ for (int i=s; i<s+n; i++) { publicTask<&my_gce>([]{ test_global++; }); } }); // TODO: use reduction total = 0; for (Core c = 0; c < cores(); c++) { total += delegate::read(make_global(&test_global, c)); } BOOST_CHECK_EQUAL(total, N); } void test_forall_localized() { BOOST_MESSAGE("Testing forall_localized..."); VLOG(1) << "testing forall_localized"; const int64_t N = 100; auto array = Grappa_typed_malloc<int64_t>(N); forall_localized(array, N, [](int64_t i, int64_t& e) { e = 1; }); for (int i=0; i<N; i++) { BOOST_CHECK_EQUAL(delegate::read(array+i), 1); } BOOST_MESSAGE("Testing forall_localized_async..."); VLOG(1) << "testing forall_localized_async"; VLOG(1) << "start spawning"; forall_localized_async<&my_gce>(array+ 0, 25, [](int64_t i, int64_t& e) { e = 2; }); VLOG(1) << "after async"; forall_localized_async<&my_gce>(array+25, 25, [](int64_t i, int64_t& e) { e = 2; }); VLOG(1) << "after async"; forall_localized_async<&my_gce>(array+50, 25, [](int64_t i, int64_t& e) { e = 2; }); VLOG(1) << "after async"; forall_localized_async<&my_gce>(array+75, 25, [](int64_t i, int64_t& e) { e = 2; }); VLOG(1) << "done spawning"; my_gce.wait(); int npb = block_size / sizeof(int64_t); auto * base = array.localize(); auto * end = (array+N).localize(); for (auto* x = base; x < end; x++) { BOOST_CHECK_EQUAL(*x, 2); } VLOG(1) << "checking indexing..."; Grappa::memset(array, 0, N); forall_localized(array, N, [](int64_t i, int64_t& e){ e = i; }); for (int i=0; i<N; i++) { BOOST_CHECK_EQUAL(delegate::read(array+i), i); } Grappa::memset(array, 0, N); forall_localized_async<&my_gce>(array, N, [](int64_t i, int64_t& e){ e = i; }); my_gce.wait(); for (int i=0; i<N; i++) { BOOST_CHECK_EQUAL(delegate::read(array+i), i); } } void user_main(void * args) { CHECK(Grappa::cores() >= 2); // at least 2 nodes for these tests... test_on_all_cores(); test_loop_decomposition(); test_loop_decomposition_global(); test_forall_here(); test_forall_global_private(); test_forall_global_public(); test_forall_localized(); } BOOST_AUTO_TEST_CASE( test1 ) { Grappa_init( &(boost::unit_test::framework::master_test_suite().argc), &(boost::unit_test::framework::master_test_suite().argv) ); Grappa_activate(); Grappa_run_user_main( &user_main, (void*)NULL ); Grappa_finish( 0 ); } BOOST_AUTO_TEST_SUITE_END(); <|endoftext|>
<commit_before>/** * For conditions of distribution and use, see copyright notice in license.txt * * @file JavascriptModule.cpp * @brief */ #include "StableHeaders.h" #include "DebugOperatorNew.h" #include "JavascriptModule.h" #include "ScriptMetaTypeDefines.h" #include "JavascriptEngine.h" #include "EC_Script.h" #include "SceneManager.h" #include "InputContext.h" #include "InputServiceInterface.h" #include "UiServiceInterface.h" #include "Frame.h" #include "ConsoleCommandServiceInterface.h" #include <QtScript> Q_SCRIPT_DECLARE_QMETAOBJECT(QPushButton, QWidget*) ///@todo Remove? This is already done in ScriptMetaTypeDefines.cpp #include "MemoryLeakCheck.h" std::string JavascriptModule::type_name_static_ = "Javascript"; JavascriptModule *javascriptModuleInstance_ = 0; JavascriptModule::JavascriptModule() : IModule(type_name_static_), engine(new QScriptEngine(this)) { } JavascriptModule::~JavascriptModule() { } void JavascriptModule::Load() { DECLARE_MODULE_EC(EC_Script); } void JavascriptModule::PreInitialize() { } void JavascriptModule::Initialize() { connect(GetFramework(), SIGNAL(SceneAdded(const QString&)), this, SLOT(SceneAdded(const QString&))); LogInfo("Module " + Name() + " initializing..."); assert(!javascriptModuleInstance_); javascriptModuleInstance_ = this; // Register ourselves as javascript scripting service. boost::shared_ptr<JavascriptModule> jsmodule = framework_->GetModuleManager()->GetModule<JavascriptModule>().lock(); boost::weak_ptr<ScriptServiceInterface> service = boost::dynamic_pointer_cast<ScriptServiceInterface>(jsmodule); framework_->GetServiceManager()->RegisterService(Foundation::Service::ST_JavascriptScripting, service); engine->globalObject().setProperty("print", engine->newFunction(Print)); QScriptValue objectbutton= engine->scriptValueFromQMetaObject<QPushButton>(); engine->globalObject().setProperty("QPushButton", objectbutton); JavascriptModule::RunScript("jsmodules/lib/json2.js"); RunString("print('Hello from qtscript');"); } void JavascriptModule::PostInitialize() { input_ = GetFramework()->Input().RegisterInputContext("ScriptInput", 100); Foundation::UiServiceInterface *ui = GetFramework()->GetService<Foundation::UiServiceInterface>(); //Foundation::SoundServiceInterface *sound = GetFramework()->GetService<Foundation::SoundServiceInterface>(); // Add Naali Core API objcects as js services. services_["input"] = input_.get(); services_["ui"] = ui; //services_["sound"] = sound; services_["frame"] = GetFramework()->GetFrame(); RegisterConsoleCommand(Console::CreateCommand( "JsExec", "Execute given code in the embedded Javascript interpreter. Usage: JsExec(mycodestring)", Console::Bind(this, &JavascriptModule::ConsoleRunString))); RegisterConsoleCommand(Console::CreateCommand( "JsLoad", "Execute a javascript file. JsLoad(myjsfile.js)", Console::Bind(this, &JavascriptModule::ConsoleRunFile))); } void JavascriptModule::Uninitialize() { } void JavascriptModule::Update(f64 frametime) { RESETPROFILER; } bool JavascriptModule::HandleEvent(event_category_id_t category_id, event_id_t event_id, IEventData* data) { return false; } Console::CommandResult JavascriptModule::ConsoleRunString(const StringVector &params) { if (params.size() != 1) return Console::ResultFailure("Usage: JsExec(print 1 + 1)"); JavascriptModule::RunString(QString::fromStdString(params[0])); return Console::ResultSuccess(); } Console::CommandResult JavascriptModule::ConsoleRunFile(const StringVector &params) { if (params.size() != 1) return Console::ResultFailure("Usage: JsLoad(myfile.js)"); JavascriptModule::RunScript(QString::fromStdString(params[0])); return Console::ResultSuccess(); } JavascriptModule *JavascriptModule::GetInstance() { assert(javascriptModuleInstance_); return javascriptModuleInstance_; } void JavascriptModule::RunString(const QString &codestr, const QVariantMap &context) { QMapIterator<QString, QVariant> i(context); while (i.hasNext()) { i.next(); engine->globalObject().setProperty(i.key(), engine->newQObject(i.value().value<QObject*>())); } engine->evaluate(codestr); } void JavascriptModule::RunScript(const QString &scriptFileName) { QFile scriptFile(scriptFileName); scriptFile.open(QIODevice::ReadOnly); engine->evaluate(scriptFile.readAll(), scriptFileName); scriptFile.close(); } void JavascriptModule::SceneAdded(const QString &name) { Scene::ScenePtr scene = GetFramework()->GetScene(name.toStdString()); connect(scene.get(), SIGNAL(ComponentAdded(Scene::Entity*, Foundation::ComponentInterface*, AttributeChange::Type)), SLOT(ComponentAdded(Scene::Entity*, Foundation::ComponentInterface*, AttributeChange::Type))); connect(scene.get(), SIGNAL(ComponentRemoved(Scene::Entity*, Foundation::ComponentInterface*, AttributeChange::Type)), SLOT(ComponentRemoved(Scene::Entity*, Foundation::ComponentInterface*, AttributeChange::Type))); //! @todo only most recently added scene has been saved to services_ map change this so that we can have access to multiple scenes in script side. services_["scene"] = scene.get(); } void JavascriptModule::ScriptChanged(const QString &scriptRef) { EC_Script *sender = dynamic_cast<EC_Script*>(this->sender()); if(!sender && sender->type.Get()!= "js") return; JavascriptEngine *javaScriptInstance = new JavascriptEngine(scriptRef); sender->SetScriptInstance(javaScriptInstance); //Register all services to script engine-> ServiceMap::iterator iter = services_.begin(); for(; iter != services_.end(); iter++) javaScriptInstance->RegisterService(iter.value(), iter.key()); //Send entity that owns the EC_Script component. javaScriptInstance->RegisterService(sender->GetParentEntity(), "me"); if (sender->runOnLoad.Get()) sender->Run(); } void JavascriptModule::ComponentAdded(Scene::Entity* entity, Foundation::ComponentInterface* comp, AttributeChange::Type change) { if(comp->TypeName() == "EC_Script") connect(comp, SIGNAL(ScriptRefChanged(const QString &)), SLOT(ScriptChanged(const QString &))); } void JavascriptModule::ComponentRemoved(Scene::Entity* entity, Foundation::ComponentInterface* comp, AttributeChange::Type change) { if(comp->TypeName() == "EC_Script") disconnect(comp, SIGNAL(ScriptRefChanged(const QString &)), this, SLOT(ScriptChanged(const QString &))); } QScriptValue Print(QScriptContext *context, QScriptEngine *engine) { std::cout << "{QtScript} " << context->argument(0).toString().toStdString() << "\n"; return QScriptValue(); } QScriptValue ScriptRunFile(QScriptContext *context, QScriptEngine *engine) { JavascriptModule::GetInstance()->RunScript(context->argument(0).toString()); return QScriptValue(); } extern "C" void POCO_LIBRARY_API SetProfiler(Foundation::Profiler *profiler); void SetProfiler(Foundation::Profiler *profiler) { Foundation::ProfilerSection::SetProfiler(profiler); } POCO_BEGIN_MANIFEST(IModule) POCO_EXPORT_CLASS(JavascriptModule) POCO_END_MANIFEST <commit_msg>Run (EC_Script) scripts only with type "js" in JavascriptModule.<commit_after>/** * For conditions of distribution and use, see copyright notice in license.txt * * @file JavascriptModule.cpp * @brief */ #include "StableHeaders.h" #include "DebugOperatorNew.h" #include "JavascriptModule.h" #include "ScriptMetaTypeDefines.h" #include "JavascriptEngine.h" #include "EC_Script.h" #include "SceneManager.h" #include "InputContext.h" #include "InputServiceInterface.h" #include "UiServiceInterface.h" #include "Frame.h" #include "ConsoleCommandServiceInterface.h" #include <QtScript> Q_SCRIPT_DECLARE_QMETAOBJECT(QPushButton, QWidget*) ///@todo Remove? This is already done in ScriptMetaTypeDefines.cpp #include "MemoryLeakCheck.h" std::string JavascriptModule::type_name_static_ = "Javascript"; JavascriptModule *javascriptModuleInstance_ = 0; JavascriptModule::JavascriptModule() : IModule(type_name_static_), engine(new QScriptEngine(this)) { } JavascriptModule::~JavascriptModule() { } void JavascriptModule::Load() { DECLARE_MODULE_EC(EC_Script); } void JavascriptModule::PreInitialize() { } void JavascriptModule::Initialize() { connect(GetFramework(), SIGNAL(SceneAdded(const QString&)), this, SLOT(SceneAdded(const QString&))); LogInfo("Module " + Name() + " initializing..."); assert(!javascriptModuleInstance_); javascriptModuleInstance_ = this; // Register ourselves as javascript scripting service. boost::shared_ptr<JavascriptModule> jsmodule = framework_->GetModuleManager()->GetModule<JavascriptModule>().lock(); boost::weak_ptr<ScriptServiceInterface> service = boost::dynamic_pointer_cast<ScriptServiceInterface>(jsmodule); framework_->GetServiceManager()->RegisterService(Foundation::Service::ST_JavascriptScripting, service); engine->globalObject().setProperty("print", engine->newFunction(Print)); QScriptValue objectbutton= engine->scriptValueFromQMetaObject<QPushButton>(); engine->globalObject().setProperty("QPushButton", objectbutton); JavascriptModule::RunScript("jsmodules/lib/json2.js"); RunString("print('Hello from qtscript');"); } void JavascriptModule::PostInitialize() { input_ = GetFramework()->Input().RegisterInputContext("ScriptInput", 100); Foundation::UiServiceInterface *ui = GetFramework()->GetService<Foundation::UiServiceInterface>(); //Foundation::SoundServiceInterface *sound = GetFramework()->GetService<Foundation::SoundServiceInterface>(); // Add Naali Core API objcects as js services. services_["input"] = input_.get(); services_["ui"] = ui; //services_["sound"] = sound; services_["frame"] = GetFramework()->GetFrame(); RegisterConsoleCommand(Console::CreateCommand( "JsExec", "Execute given code in the embedded Javascript interpreter. Usage: JsExec(mycodestring)", Console::Bind(this, &JavascriptModule::ConsoleRunString))); RegisterConsoleCommand(Console::CreateCommand( "JsLoad", "Execute a javascript file. JsLoad(myjsfile.js)", Console::Bind(this, &JavascriptModule::ConsoleRunFile))); } void JavascriptModule::Uninitialize() { } void JavascriptModule::Update(f64 frametime) { RESETPROFILER; } bool JavascriptModule::HandleEvent(event_category_id_t category_id, event_id_t event_id, IEventData* data) { return false; } Console::CommandResult JavascriptModule::ConsoleRunString(const StringVector &params) { if (params.size() != 1) return Console::ResultFailure("Usage: JsExec(print 1 + 1)"); JavascriptModule::RunString(QString::fromStdString(params[0])); return Console::ResultSuccess(); } Console::CommandResult JavascriptModule::ConsoleRunFile(const StringVector &params) { if (params.size() != 1) return Console::ResultFailure("Usage: JsLoad(myfile.js)"); JavascriptModule::RunScript(QString::fromStdString(params[0])); return Console::ResultSuccess(); } JavascriptModule *JavascriptModule::GetInstance() { assert(javascriptModuleInstance_); return javascriptModuleInstance_; } void JavascriptModule::RunString(const QString &codestr, const QVariantMap &context) { QMapIterator<QString, QVariant> i(context); while (i.hasNext()) { i.next(); engine->globalObject().setProperty(i.key(), engine->newQObject(i.value().value<QObject*>())); } engine->evaluate(codestr); } void JavascriptModule::RunScript(const QString &scriptFileName) { QFile scriptFile(scriptFileName); scriptFile.open(QIODevice::ReadOnly); engine->evaluate(scriptFile.readAll(), scriptFileName); scriptFile.close(); } void JavascriptModule::SceneAdded(const QString &name) { Scene::ScenePtr scene = GetFramework()->GetScene(name.toStdString()); connect(scene.get(), SIGNAL(ComponentAdded(Scene::Entity*, Foundation::ComponentInterface*, AttributeChange::Type)), SLOT(ComponentAdded(Scene::Entity*, Foundation::ComponentInterface*, AttributeChange::Type))); connect(scene.get(), SIGNAL(ComponentRemoved(Scene::Entity*, Foundation::ComponentInterface*, AttributeChange::Type)), SLOT(ComponentRemoved(Scene::Entity*, Foundation::ComponentInterface*, AttributeChange::Type))); //! @todo only most recently added scene has been saved to services_ map change this so that we can have access to multiple scenes in script side. services_["scene"] = scene.get(); } void JavascriptModule::ScriptChanged(const QString &scriptRef) { EC_Script *sender = dynamic_cast<EC_Script*>(this->sender()); if(!sender) return; if (sender->type.Get() != "js") return; JavascriptEngine *javaScriptInstance = new JavascriptEngine(scriptRef); sender->SetScriptInstance(javaScriptInstance); //Register all services to script engine-> ServiceMap::iterator iter = services_.begin(); for(; iter != services_.end(); iter++) javaScriptInstance->RegisterService(iter.value(), iter.key()); //Send entity that owns the EC_Script component. javaScriptInstance->RegisterService(sender->GetParentEntity(), "me"); if (sender->runOnLoad.Get()) sender->Run(); } void JavascriptModule::ComponentAdded(Scene::Entity* entity, Foundation::ComponentInterface* comp, AttributeChange::Type change) { if(comp->TypeName() == "EC_Script") connect(comp, SIGNAL(ScriptRefChanged(const QString &)), SLOT(ScriptChanged(const QString &))); } void JavascriptModule::ComponentRemoved(Scene::Entity* entity, Foundation::ComponentInterface* comp, AttributeChange::Type change) { if(comp->TypeName() == "EC_Script") disconnect(comp, SIGNAL(ScriptRefChanged(const QString &)), this, SLOT(ScriptChanged(const QString &))); } QScriptValue Print(QScriptContext *context, QScriptEngine *engine) { std::cout << "{QtScript} " << context->argument(0).toString().toStdString() << "\n"; return QScriptValue(); } QScriptValue ScriptRunFile(QScriptContext *context, QScriptEngine *engine) { JavascriptModule::GetInstance()->RunScript(context->argument(0).toString()); return QScriptValue(); } extern "C" void POCO_LIBRARY_API SetProfiler(Foundation::Profiler *profiler); void SetProfiler(Foundation::Profiler *profiler) { Foundation::ProfilerSection::SetProfiler(profiler); } POCO_BEGIN_MANIFEST(IModule) POCO_EXPORT_CLASS(JavascriptModule) POCO_END_MANIFEST <|endoftext|>
<commit_before>/****************************************************************************/ /** * @file Bmp.cpp * @author Naohisa Sakamoto */ /*---------------------------------------------------------------------------- * * Copyright (c) Visualization Laboratory, Kyoto University. * All rights reserved. * See http://www.viz.media.kyoto-u.ac.jp/kvs/copyright/ for details. * * $Id: Bmp.cpp 1402 2012-12-07 01:32:08Z [email protected] $ */ /****************************************************************************/ #include "Bmp.h" #include <iostream> #include <fstream> #include <string> #include <cstring> #include <kvs/Message> #include <kvs/File> namespace { void Flip( const size_t width, const size_t height, kvs::UInt8* pixels ) { const size_t stride = width * 3; kvs::UInt8* pdata = pixels; const size_t end_line = height / 2; for ( size_t i = 0; i < end_line; i++ ) { kvs::UInt8* src = pdata + ( i * stride ); kvs::UInt8* dst = pdata + ( ( height - i - 1 ) * stride ); for ( size_t j = 0; j < stride; j++ ) { std::swap( *src, *dst ); src++; dst++; } } } } namespace kvs { /*===========================================================================*/ /** * @brief Check the file extension. * @param filename [in] filename * @return true, if the specified file is a Bitmap file format */ /*===========================================================================*/ bool Bmp::CheckExtension( const std::string& filename ) { const kvs::File file( filename ); if ( file.extension() == "bmp" || file.extension() == "BMP" ) { return true; } return false; } /*==========================================================================*/ /** * @brief Constructs a new Bmp class. * @param width [in] width * @param height [in] height * @param data [in] pixel data */ /*==========================================================================*/ Bmp::Bmp( const size_t width, const size_t height, const kvs::ValueArray<kvs::UInt8>& pixels ): m_width( width ), m_height( height ), m_bpp( 3 ), m_pixels( pixels ) { this->set_header(); } /*==========================================================================*/ /** * @brief Constructs a new Bmp class. * @param filename [in] filename */ /*==========================================================================*/ Bmp::Bmp( const std::string& filename ) { this->read( filename ); } /*===========================================================================*/ /** * @brief Prints information of the bitmap image. * @param os [in] output stream * @param indent [in] indent */ /*===========================================================================*/ void Bmp::print( std::ostream& os, const kvs::Indent& indent ) const { os << indent << "Filename : " << BaseClass::filename() << std::endl; m_file_header.print( os, indent ); m_info_header.print( os, indent ); } /*==========================================================================*/ /** * @brief Reads the bitmap format image. * @param filename [in] filename * @return true, if the read process is done successfully */ /*==========================================================================*/ bool Bmp::read( const std::string& filename ) { BaseClass::setFilename( filename ); BaseClass::setSuccess( true ); // Open the file. std::ifstream ifs( filename.c_str(), std::ios::binary | std::ios::in ); if( !ifs.is_open() ) { kvsMessageError( "Cannot open %s.", filename.c_str() ); BaseClass::setSuccess( false ); return false; } // Read header information. m_file_header.read( ifs ); m_info_header.read( ifs ); // Chech whether this file is supported or not. if ( m_info_header.bpp() != 24 ) { ifs.close(); BaseClass::setSuccess( false ); return false; } m_width = m_info_header.width(); m_height = m_info_header.height() < 0 ? -1 * m_info_header.height() : m_info_header.height(); m_bpp = m_info_header.bpp(); this->skip_header_and_pallete( ifs ); const size_t nchannels = 3; // NOTE: color mode only supported now. m_pixels.allocate( m_width * m_height * nchannels ); kvs::UInt8* data = m_pixels.data(); const size_t bpp = 3; const size_t bpl = m_width * bpp; const size_t padding = m_width % 4; const size_t upper_left = ( m_height - 1 ) * bpl; for ( size_t j = 0; j < m_height; j++ ) { // The origin of BMP is a lower-left point. const size_t line_index = upper_left - j * bpl; for ( size_t i = 0; i < m_width; i++ ) { // BGR -> RGB const size_t index = line_index + 3 * i; ifs.read( reinterpret_cast<char*>( data + index + 2 ), 1 ); ifs.read( reinterpret_cast<char*>( data + index + 1 ), 1 ); ifs.read( reinterpret_cast<char*>( data + index + 0 ), 1 ); } // Padding. ifs.seekg( padding, std::ios::cur ); } if ( m_info_header.height() < 0 ) { ::Flip( m_width, m_height, data ); } ifs.close(); return true; } /*==========================================================================*/ /** * @brief Writes the bitmap format image. * @param filename [in] filename * @return true, if the write process is done successfully */ /*==========================================================================*/ bool Bmp::write( const std::string& filename ) { BaseClass::setFilename( filename ); BaseClass::setSuccess( true ); std::ofstream ofs( filename.c_str(), std::ios::out | std::ios::trunc | std::ios::binary ); if( !ofs.is_open() ) { kvsMessageError( "Cannot open %s.", BaseClass::filename().c_str() ); BaseClass::setSuccess( false ); return false; } this->set_header(); m_file_header.write( ofs ); m_info_header.write( ofs ); kvs::UInt8* data = m_pixels.data(); const size_t bpp = 3; const size_t bpl = m_width * bpp; const size_t padding = m_width % 4; const size_t lower_left = ( m_height - 1 ) * bpl; for ( size_t j = 0; j < m_height; j++ ) { // The origin of BMP is a lower-left point. const size_t line_index = lower_left - j * bpl; for ( size_t i = 0; i < m_width; i++ ) { // RGB -> BGR const size_t index = line_index + 3 * i; ofs.write( reinterpret_cast<char*>( data + index + 2 ), 1 ); ofs.write( reinterpret_cast<char*>( data + index + 1 ), 1 ); ofs.write( reinterpret_cast<char*>( data + index + 0 ), 1 ); } // Padding. for ( size_t i = 0; i < padding; i++ ) ofs.write( "0", 1 ); } ofs.close(); return true; } /*==========================================================================*/ /** * @brief Skips the header and pallete region. * @param ifs [in] input file stream */ /*==========================================================================*/ void Bmp::skip_header_and_pallete( std::ifstream& ifs ) { ifs.clear(); ifs.seekg( m_file_header.offset() + m_info_header.colsused() * 4, std::ios::beg ); } /*==========================================================================*/ /** * @brief Sets the bitmap image header information. */ /*==========================================================================*/ void Bmp::set_header() { const char* magic_num = "BM"; const kvs::UInt32 offset = 54; const kvs::UInt32 bpp = 3; const kvs::UInt32 padding = kvs::UInt32( m_height * ( m_width % 4 ) ); //m_fileh.type = 0x4d42; // "BM"; '0x424d', if big endian. //m_fileh.type = 0x424d; // "BM"; '0x424d', if big endian. memcpy( &( m_file_header.m_type ), magic_num, sizeof( kvs::UInt16 ) ); m_file_header.m_size = kvs::UInt32( offset + m_width * m_height * bpp + padding ); m_file_header.m_reserved1 = 0; m_file_header.m_reserved2 = 0; m_file_header.m_offset = offset; m_info_header.m_size = 40; m_info_header.m_width = kvs::Int32( m_width ); m_info_header.m_height = kvs::Int32( m_height ); m_info_header.m_nplanes = 1; m_info_header.m_bpp = 24; m_info_header.m_compression = 0L; // 0L: no compress, // 1L: 8-bit run-length encoding, 2L: 4-bit m_info_header.m_bitmapsize = kvs::UInt32( m_width * m_height * bpp + padding ); m_info_header.m_hresolution = 0; m_info_header.m_vresolution = 0; m_info_header.m_colsused = 0; m_info_header.m_colsimportant = 0; } } // end of namespace kvs <commit_msg>Fixed a problem.<commit_after>/****************************************************************************/ /** * @file Bmp.cpp * @author Naohisa Sakamoto */ /*---------------------------------------------------------------------------- * * Copyright (c) Visualization Laboratory, Kyoto University. * All rights reserved. * See http://www.viz.media.kyoto-u.ac.jp/kvs/copyright/ for details. * * $Id: Bmp.cpp 1402 2012-12-07 01:32:08Z [email protected] $ */ /****************************************************************************/ #include "Bmp.h" #include <iostream> #include <fstream> #include <string> #include <cstring> #include <kvs/Message> #include <kvs/File> #include <kvs/Math> namespace { void Flip( const size_t width, const size_t height, kvs::UInt8* pixels ) { const size_t stride = width * 3; kvs::UInt8* pdata = pixels; const size_t end_line = height / 2; for ( size_t i = 0; i < end_line; i++ ) { kvs::UInt8* src = pdata + ( i * stride ); kvs::UInt8* dst = pdata + ( ( height - i - 1 ) * stride ); for ( size_t j = 0; j < stride; j++ ) { std::swap( *src, *dst ); src++; dst++; } } } } namespace kvs { /*===========================================================================*/ /** * @brief Check the file extension. * @param filename [in] filename * @return true, if the specified file is a Bitmap file format */ /*===========================================================================*/ bool Bmp::CheckExtension( const std::string& filename ) { const kvs::File file( filename ); if ( file.extension() == "bmp" || file.extension() == "BMP" ) { return true; } return false; } /*==========================================================================*/ /** * @brief Constructs a new Bmp class. * @param width [in] width * @param height [in] height * @param data [in] pixel data */ /*==========================================================================*/ Bmp::Bmp( const size_t width, const size_t height, const kvs::ValueArray<kvs::UInt8>& pixels ): m_width( width ), m_height( height ), m_bpp( 3 ), m_pixels( pixels ) { this->set_header(); } /*==========================================================================*/ /** * @brief Constructs a new Bmp class. * @param filename [in] filename */ /*==========================================================================*/ Bmp::Bmp( const std::string& filename ) { this->read( filename ); } /*===========================================================================*/ /** * @brief Prints information of the bitmap image. * @param os [in] output stream * @param indent [in] indent */ /*===========================================================================*/ void Bmp::print( std::ostream& os, const kvs::Indent& indent ) const { os << indent << "Filename : " << BaseClass::filename() << std::endl; m_file_header.print( os, indent ); m_info_header.print( os, indent ); } /*==========================================================================*/ /** * @brief Reads the bitmap format image. * @param filename [in] filename * @return true, if the read process is done successfully */ /*==========================================================================*/ bool Bmp::read( const std::string& filename ) { BaseClass::setFilename( filename ); BaseClass::setSuccess( true ); // Open the file. std::ifstream ifs( filename.c_str(), std::ios::binary | std::ios::in ); if( !ifs.is_open() ) { kvsMessageError( "Cannot open %s.", filename.c_str() ); BaseClass::setSuccess( false ); return false; } // Read header information. m_file_header.read( ifs ); m_info_header.read( ifs ); // Chech whether this file is supported or not. if ( !( m_info_header.bpp() == 24 || m_info_header.bpp() == 32 ) ) { ifs.close(); BaseClass::setSuccess( false ); return false; } this->skip_header_and_pallete( ifs ); m_width = m_info_header.width(); m_height = kvs::Math::Abs( m_info_header.height() ); // NOTE: The pixel data is stored as 24-bit color data in kvs::Bmp // without depending on m_info_header.bpp(). m_bpp = 24; // NOTE: 24-bit color data (R, G, and B channels) only supported. const size_t nchannels = 3; m_pixels.allocate( m_width * m_height * nchannels ); kvs::UInt8* data = m_pixels.data(); const size_t bpl = m_width * ( m_bpp / 8 ); const size_t padding = ( m_width * ( m_info_header.bpp() / 8 ) ) % 4; const size_t upper_left = ( m_height - 1 ) * bpl; const size_t received = m_info_header.bpp() == 24 ? 0 : 1; for ( size_t j = 0; j < m_height; j++ ) { // The origin of BMP is a lower-left point. const size_t line_index = upper_left - j * bpl; for ( size_t i = 0; i < m_width; i++ ) { // BGR -> RGB const size_t index = line_index + 3 * i; ifs.read( (char*)( data + index + 2 ), 1 ); ifs.read( (char*)( data + index + 1 ), 1 ); ifs.read( (char*)( data + index + 0 ), 1 ); ifs.seekg( received, std::ios::cur ); // ignored } // Padding. (4-byte alignment) ifs.seekg( padding, std::ios::cur ); } if ( m_info_header.height() < 0 ) { ::Flip( m_width, m_height, data ); } ifs.close(); return true; } /*==========================================================================*/ /** * @brief Writes the bitmap format image. * @param filename [in] filename * @return true, if the write process is done successfully */ /*==========================================================================*/ bool Bmp::write( const std::string& filename ) { BaseClass::setFilename( filename ); BaseClass::setSuccess( true ); std::ofstream ofs( filename.c_str(), std::ios::out | std::ios::trunc | std::ios::binary ); if( !ofs.is_open() ) { kvsMessageError( "Cannot open %s.", BaseClass::filename().c_str() ); BaseClass::setSuccess( false ); return false; } this->set_header(); m_file_header.write( ofs ); m_info_header.write( ofs ); kvs::UInt8* data = m_pixels.data(); const size_t bpp = 3; const size_t bpl = m_width * bpp; const size_t padding = m_width % 4; const size_t lower_left = ( m_height - 1 ) * bpl; for ( size_t j = 0; j < m_height; j++ ) { // The origin of BMP is a lower-left point. const size_t line_index = lower_left - j * bpl; for ( size_t i = 0; i < m_width; i++ ) { // RGB -> BGR const size_t index = line_index + 3 * i; ofs.write( reinterpret_cast<char*>( data + index + 2 ), 1 ); ofs.write( reinterpret_cast<char*>( data + index + 1 ), 1 ); ofs.write( reinterpret_cast<char*>( data + index + 0 ), 1 ); } // Padding. for ( size_t i = 0; i < padding; i++ ) ofs.write( "0", 1 ); } ofs.close(); return true; } /*==========================================================================*/ /** * @brief Skips the header and pallete region. * @param ifs [in] input file stream */ /*==========================================================================*/ void Bmp::skip_header_and_pallete( std::ifstream& ifs ) { ifs.clear(); ifs.seekg( m_file_header.offset() + m_info_header.colsused() * 4, std::ios::beg ); } /*==========================================================================*/ /** * @brief Sets the bitmap image header information. */ /*==========================================================================*/ void Bmp::set_header() { const char* magic_num = "BM"; const kvs::UInt32 offset = 54; const kvs::UInt32 bpp = 3; const kvs::UInt32 padding = kvs::UInt32( m_height * ( m_width % 4 ) ); //m_fileh.type = 0x4d42; // "BM"; '0x424d', if big endian. //m_fileh.type = 0x424d; // "BM"; '0x424d', if big endian. memcpy( &( m_file_header.m_type ), magic_num, sizeof( kvs::UInt16 ) ); m_file_header.m_size = kvs::UInt32( offset + m_width * m_height * bpp + padding ); m_file_header.m_reserved1 = 0; m_file_header.m_reserved2 = 0; m_file_header.m_offset = offset; m_info_header.m_size = 40; m_info_header.m_width = kvs::Int32( m_width ); m_info_header.m_height = kvs::Int32( m_height ); m_info_header.m_nplanes = 1; m_info_header.m_bpp = 24; m_info_header.m_compression = 0L; // 0L: no compress, // 1L: 8-bit run-length encoding, 2L: 4-bit m_info_header.m_bitmapsize = kvs::UInt32( m_width * m_height * bpp + padding ); m_info_header.m_hresolution = 0; m_info_header.m_vresolution = 0; m_info_header.m_colsused = 0; m_info_header.m_colsimportant = 0; } } // end of namespace kvs <|endoftext|>
<commit_before>/*========================================================================= Program: Monteverdi2 Language: C++ Date: $Date$ Version: $Revision$ Copyright (c) Centre National d'Etudes Spatiales. All rights reserved. See OTBCopyright.txt for details. This software is distributed WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the above copyright notices for more information. =========================================================================*/ #include "mvdMainWindow.h" #include "ui_mvdMainWindow.h" // // Qt includes (sorted by alphabetic order) //// Must be included before system/custom includes. #include <QtGui> // // System includes (sorted by alphabetic order) // // ITK includes (sorted by alphabetic order) // // OTB includes (sorted by alphabetic order) // // Monteverdi includes (sorted by alphabetic order) #include "mvdAboutDialog.h" #include "mvdApplication.h" #include "mvdColorDynamicsWidget.h" #include "mvdColorSetupWidget.h" #include "mvdDatasetModel.h" #include "mvdGLImageWidget.h" #include "mvdVectorImageModel.h" namespace mvd { /* TRANSLATOR mvd::MainWindow Necessary for lupdate to be aware of C++ namespaces. Context comment for translator. */ /*****************************************************************************/ MainWindow ::MainWindow( QWidget* parent, Qt::WindowFlags flags ) : QMainWindow( parent, flags ), m_UI( new mvd::Ui::MainWindow() ) { m_UI->setupUi( this ); Initialize(); } /*****************************************************************************/ MainWindow ::~MainWindow() { } /*****************************************************************************/ void MainWindow ::Initialize() { setObjectName( "mvd::MainWindow" ); setWindowTitle( PROJECT_NAME ); // Set the GLImageWidget as the centralWidget in MainWindow. setCentralWidget( new GLImageWidget( this ) ); InitializeDockWidgets(); // Connect Quit action of main menu to QApplication's quit() slot. QObject::connect( m_UI->action_Quit, SIGNAL( activated() ), qApp, SLOT( quit() ) ); // Connect the setLargestPossibleregion QObject::connect( this, SIGNAL( LargestPossibleRegionChanged(const ImageRegionType&) ), centralWidget(), SLOT( OnLargestPossibleRegionChanged(const ImageRegionType&)) ); // Connect Appllication and MainWindow when selected model is about // to change. QObject::connect( qApp, SIGNAL( AboutToChangeSelectedModel( const AbstractModel* ) ), this, SLOT( OnAboutToChangeSelectedModel( const AbstractModel* ) ) ); // Connect Appllication and MainWindow when selected model has been // changed. QObject::connect( qApp, SIGNAL( SelectedModelChanged( const AbstractModel* ) ), this, SLOT( OnSelectedModelChanged( const AbstractModel* ) ) ); } /*****************************************************************************/ void MainWindow ::InitializeDockWidgets() { AddWidgetToDock( new ColorSetupWidget( this ), VIDEO_COLOR_SETUP_DOCK, tr( "Video color setup" ), Qt::LeftDockWidgetArea ); AddWidgetToDock( new ColorDynamicsWidget( this ), VIDEO_COLOR_DYNAMICS_DOCK, tr( "Video color dynamics" ), Qt::LeftDockWidgetArea ); #if 0 QToolBox* toolBox = new QToolBox( this ); toolBox->setObjectName( "mvd::VideoColorToolBox" ); toolBox->addItem( new ColorSetupWidget( toolBox ), tr( "Video color setup" ) ); toolBox->addItem( new ColorDynamicsWidget( toolBox ), tr( "Video color dynamics" ) ); AddWidgetToDock( toolBox, "videoColorSettingsDock", tr( "Video color dynamics" ), Qt::LeftDockWidgetArea ); #endif } /*****************************************************************************/ void MainWindow ::AddWidgetToDock( QWidget* widget, const QString& dockName, const QString& dockTitle, Qt::DockWidgetArea dockArea ) { // New dock. QDockWidget* dockWidget = new QDockWidget( dockTitle, this ); // You can use findChild( dockName ) to get dock-widget. dockWidget->setObjectName( dockName ); dockWidget->setWidget( widget ); // Features. dockWidget->setFloating( true ); dockWidget->setFeatures( QDockWidget::DockWidgetMovable | QDockWidget::DockWidgetFloatable ); // Add dock. addDockWidget( dockArea, dockWidget ); } /*****************************************************************************/ /* SLOTS */ /*****************************************************************************/ void MainWindow ::on_action_Open_activated() { QString filename( QFileDialog::getOpenFileName( this, tr( "Open file..." ) ) ); if( filename.isNull() ) { return; } // TODO: Replace with complex model (list of DatasetModel) when // implemented. DatasetModel* model = new DatasetModel(); model->setObjectName( "mvd::DatasetModel('" + filename + "'" ); try { model->ImportImage( filename ); } catch( std::exception& exc ) { delete model; model = NULL; QMessageBox::warning( this, tr("Exception!"), exc.what() ); return; } Application::Instance()->SetModel( model ); } /*****************************************************************************/ void MainWindow ::on_action_About_activated() { AboutDialog aboutDialog( this ); aboutDialog.exec(); } /*****************************************************************************/ void MainWindow ::OnAboutToChangeSelectedModel( const AbstractModel* ) { const Application* app = Application::ConstInstance(); assert( app!=NULL ); const DatasetModel* datasetModel = qobject_cast< const DatasetModel* >( app->GetModel() ); if( datasetModel==NULL ) { return; } assert( datasetModel->HasSelectedImageModel() ); const VectorImageModel* vectorImageModel = qobject_cast< const VectorImageModel* >( datasetModel->GetSelectedImageModel() ); assert( vectorImageModel!=NULL ); // Disconnect previously selected model from view. QObject::disconnect( vectorImageModel, SIGNAL( settingsUpdated() ), // to: centralWidget(), SLOT( updateGL() ) ); QWidget* widget = GetColorSetupDock()->widget(); assert( widget!=NULL ); // Disconnect previously selected model from UI controller. QObject::disconnect( GetColorSetupDock()->widget(), SIGNAL( CurrentIndexChanged( ColorSetupWidget::Channel, int ) ), // from: vectorImageModel, SLOT( OnCurrentIndexChanged( ColorSetupWidget::Channel, int ) ) ); } /*****************************************************************************/ void MainWindow ::OnSelectedModelChanged( const AbstractModel* model ) { ColorSetupWidget* colorSetupWidget = qobject_cast< ColorSetupWidget* >( GetColorSetupDock()->widget() ); assert( colorSetupWidget!=NULL ); const DatasetModel* datasetModel = qobject_cast< const DatasetModel* >( model ); assert( datasetModel!=NULL ); assert( datasetModel->HasSelectedImageModel() ); const VectorImageModel* vectorImageModel = qobject_cast< const VectorImageModel* >( datasetModel->GetSelectedImageModel() ); assert( vectorImageModel!=NULL ); // Connect newly selected model to UI controller. QObject::connect( colorSetupWidget, SIGNAL( CurrentIndexChanged( ColorSetupWidget::Channel, int ) ), // to: vectorImageModel, SLOT( OnCurrentIndexChanged( ColorSetupWidget::Channel, int ) ) ); // Connect newly selected model to view. QObject::connect( vectorImageModel, SIGNAL( SettingsUpdated() ), // to: centralWidget(), SLOT( updateGL() ) ); // Setup color-setup controller. colorSetupWidget->blockSignals( true ); { colorSetupWidget->SetComponents( vectorImageModel->GetBandNames() ); for( int i=0; i<ColorSetupWidget::CHANNEL_COUNT; ++i ) { colorSetupWidget->SetCurrentIndex( ColorSetupWidget::Channel( i ), vectorImageModel->GetSettings().RgbChannel( i ) ); } } colorSetupWidget->blockSignals( false ); // set the largest possible region of the image // TODO: rename signal name when handling DataSets collections // TODO: move signal into mvdApplication and link it to DockWidget // and ImageView. emit LargestPossibleRegionChanged( vectorImageModel->GetOutput( 0 )->GetLargestPossibleRegion() ); } /*****************************************************************************/ } // end namespace 'mvd' <commit_msg>ENH: Docked (by default) floating widgets (ColorSetup, ColorDyanmics).<commit_after>/*========================================================================= Program: Monteverdi2 Language: C++ Date: $Date$ Version: $Revision$ Copyright (c) Centre National d'Etudes Spatiales. All rights reserved. See OTBCopyright.txt for details. This software is distributed WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the above copyright notices for more information. =========================================================================*/ #include "mvdMainWindow.h" #include "ui_mvdMainWindow.h" // // Qt includes (sorted by alphabetic order) //// Must be included before system/custom includes. #include <QtGui> // // System includes (sorted by alphabetic order) // // ITK includes (sorted by alphabetic order) // // OTB includes (sorted by alphabetic order) // // Monteverdi includes (sorted by alphabetic order) #include "mvdAboutDialog.h" #include "mvdApplication.h" #include "mvdColorDynamicsWidget.h" #include "mvdColorSetupWidget.h" #include "mvdDatasetModel.h" #include "mvdGLImageWidget.h" #include "mvdVectorImageModel.h" namespace mvd { /* TRANSLATOR mvd::MainWindow Necessary for lupdate to be aware of C++ namespaces. Context comment for translator. */ /*****************************************************************************/ MainWindow ::MainWindow( QWidget* parent, Qt::WindowFlags flags ) : QMainWindow( parent, flags ), m_UI( new mvd::Ui::MainWindow() ) { m_UI->setupUi( this ); Initialize(); } /*****************************************************************************/ MainWindow ::~MainWindow() { } /*****************************************************************************/ void MainWindow ::Initialize() { setObjectName( "mvd::MainWindow" ); setWindowTitle( PROJECT_NAME ); // Set the GLImageWidget as the centralWidget in MainWindow. setCentralWidget( new GLImageWidget( this ) ); InitializeDockWidgets(); // Connect Quit action of main menu to QApplication's quit() slot. QObject::connect( m_UI->action_Quit, SIGNAL( activated() ), qApp, SLOT( quit() ) ); // Connect the setLargestPossibleregion QObject::connect( this, SIGNAL( LargestPossibleRegionChanged(const ImageRegionType&) ), centralWidget(), SLOT( OnLargestPossibleRegionChanged(const ImageRegionType&)) ); // Connect Appllication and MainWindow when selected model is about // to change. QObject::connect( qApp, SIGNAL( AboutToChangeSelectedModel( const AbstractModel* ) ), this, SLOT( OnAboutToChangeSelectedModel( const AbstractModel* ) ) ); // Connect Appllication and MainWindow when selected model has been // changed. QObject::connect( qApp, SIGNAL( SelectedModelChanged( const AbstractModel* ) ), this, SLOT( OnSelectedModelChanged( const AbstractModel* ) ) ); } /*****************************************************************************/ void MainWindow ::InitializeDockWidgets() { AddWidgetToDock( new ColorSetupWidget( this ), VIDEO_COLOR_SETUP_DOCK, tr( "Video color setup" ), Qt::LeftDockWidgetArea ); AddWidgetToDock( new ColorDynamicsWidget( this ), VIDEO_COLOR_DYNAMICS_DOCK, tr( "Video color dynamics" ), Qt::LeftDockWidgetArea ); #if 0 QToolBox* toolBox = new QToolBox( this ); toolBox->setObjectName( "mvd::VideoColorToolBox" ); toolBox->addItem( new ColorSetupWidget( toolBox ), tr( "Video color setup" ) ); toolBox->addItem( new ColorDynamicsWidget( toolBox ), tr( "Video color dynamics" ) ); AddWidgetToDock( toolBox, "videoColorSettingsDock", tr( "Video color dynamics" ), Qt::LeftDockWidgetArea ); #endif } /*****************************************************************************/ void MainWindow ::AddWidgetToDock( QWidget* widget, const QString& dockName, const QString& dockTitle, Qt::DockWidgetArea dockArea ) { // New dock. QDockWidget* dockWidget = new QDockWidget( dockTitle, this ); // You can use findChild( dockName ) to get dock-widget. dockWidget->setObjectName( dockName ); dockWidget->setWidget( widget ); // Features. dockWidget->setFloating( false ); dockWidget->setFeatures( QDockWidget::DockWidgetMovable | QDockWidget::DockWidgetFloatable ); // Add dock. addDockWidget( dockArea, dockWidget ); } /*****************************************************************************/ /* SLOTS */ /*****************************************************************************/ void MainWindow ::on_action_Open_activated() { QString filename( QFileDialog::getOpenFileName( this, tr( "Open file..." ) ) ); if( filename.isNull() ) { return; } // TODO: Replace with complex model (list of DatasetModel) when // implemented. DatasetModel* model = new DatasetModel(); model->setObjectName( "mvd::DatasetModel('" + filename + "'" ); try { model->ImportImage( filename ); } catch( std::exception& exc ) { delete model; model = NULL; QMessageBox::warning( this, tr("Exception!"), exc.what() ); return; } Application::Instance()->SetModel( model ); } /*****************************************************************************/ void MainWindow ::on_action_About_activated() { AboutDialog aboutDialog( this ); aboutDialog.exec(); } /*****************************************************************************/ void MainWindow ::OnAboutToChangeSelectedModel( const AbstractModel* ) { const Application* app = Application::ConstInstance(); assert( app!=NULL ); const DatasetModel* datasetModel = qobject_cast< const DatasetModel* >( app->GetModel() ); if( datasetModel==NULL ) { return; } assert( datasetModel->HasSelectedImageModel() ); const VectorImageModel* vectorImageModel = qobject_cast< const VectorImageModel* >( datasetModel->GetSelectedImageModel() ); assert( vectorImageModel!=NULL ); // Disconnect previously selected model from view. QObject::disconnect( vectorImageModel, SIGNAL( settingsUpdated() ), // to: centralWidget(), SLOT( updateGL() ) ); QWidget* widget = GetColorSetupDock()->widget(); assert( widget!=NULL ); // Disconnect previously selected model from UI controller. QObject::disconnect( GetColorSetupDock()->widget(), SIGNAL( CurrentIndexChanged( ColorSetupWidget::Channel, int ) ), // from: vectorImageModel, SLOT( OnCurrentIndexChanged( ColorSetupWidget::Channel, int ) ) ); } /*****************************************************************************/ void MainWindow ::OnSelectedModelChanged( const AbstractModel* model ) { ColorSetupWidget* colorSetupWidget = qobject_cast< ColorSetupWidget* >( GetColorSetupDock()->widget() ); assert( colorSetupWidget!=NULL ); const DatasetModel* datasetModel = qobject_cast< const DatasetModel* >( model ); assert( datasetModel!=NULL ); assert( datasetModel->HasSelectedImageModel() ); const VectorImageModel* vectorImageModel = qobject_cast< const VectorImageModel* >( datasetModel->GetSelectedImageModel() ); assert( vectorImageModel!=NULL ); // Connect newly selected model to UI controller. QObject::connect( colorSetupWidget, SIGNAL( CurrentIndexChanged( ColorSetupWidget::Channel, int ) ), // to: vectorImageModel, SLOT( OnCurrentIndexChanged( ColorSetupWidget::Channel, int ) ) ); // Connect newly selected model to view. QObject::connect( vectorImageModel, SIGNAL( SettingsUpdated() ), // to: centralWidget(), SLOT( updateGL() ) ); // Setup color-setup controller. colorSetupWidget->blockSignals( true ); { colorSetupWidget->SetComponents( vectorImageModel->GetBandNames() ); for( int i=0; i<ColorSetupWidget::CHANNEL_COUNT; ++i ) { colorSetupWidget->SetCurrentIndex( ColorSetupWidget::Channel( i ), vectorImageModel->GetSettings().RgbChannel( i ) ); } } colorSetupWidget->blockSignals( false ); // set the largest possible region of the image // TODO: rename signal name when handling DataSets collections // TODO: move signal into mvdApplication and link it to DockWidget // and ImageView. emit LargestPossibleRegionChanged( vectorImageModel->GetOutput( 0 )->GetLargestPossibleRegion() ); } /*****************************************************************************/ } // end namespace 'mvd' <|endoftext|>
<commit_before>//===- lib/ReaderWriter/ELF/Mips/MipsRelocationHandler.cpp ----------------===// // // The LLVM Linker // // This file is distributed under the University of Illinois Open Source // License. See LICENSE.TXT for details. // //===----------------------------------------------------------------------===// #include "MipsTargetHandler.h" #include "MipsLinkingContext.h" #include "MipsRelocationHandler.h" #include "lld/ReaderWriter/RelocationHelperFunctions.h" using namespace lld; using namespace elf; using namespace llvm::ELF; static inline void applyReloc(uint8_t *loc, uint32_t result, uint32_t mask) { auto target = reinterpret_cast<llvm::support::ulittle32_t *>(loc); *target = (uint32_t(*target) & ~mask) | (result & mask); } template <size_t BITS, class T> inline T signExtend(T val) { if (val & (T(1) << (BITS - 1))) val |= T(-1) << BITS; return val; } /// \brief R_MIPS_32 /// local/external: word32 S + A (truncate) static void reloc32(uint8_t *location, uint64_t P, uint64_t S, int64_t A) { applyReloc(location, S + A, 0xffffffff); } /// \brief R_MIPS_PC32 /// local/external: word32 S + A i- P (truncate) void relocpc32(uint8_t *location, uint64_t P, uint64_t S, int64_t A) { applyReloc(location, S + A - P, 0xffffffff); } /// \brief R_MIPS_26 /// local : ((A | ((P + 4) & 0x3F000000)) + S) >> 2 static void reloc26loc(uint8_t *location, uint64_t P, uint64_t S, int32_t A) { uint32_t result = ((A << 2) | ((P + 4) & 0x3f000000)) + S; applyReloc(location, result >> 2, 0x03ffffff); } /// \brief LLD_R_MIPS_GLOBAL_26 /// external: (sign-extend(A) + S) >> 2 static void reloc26ext(uint8_t *location, uint64_t S, int32_t A) { uint32_t result = signExtend<28>(A << 2) + S; applyReloc(location, result >> 2, 0x03ffffff); } /// \brief R_MIPS_HI16 /// local/external: hi16 (AHL + S) - (short)(AHL + S) (truncate) /// _gp_disp : hi16 (AHL + GP - P) - (short)(AHL + GP - P) (verify) static void relocHi16(uint8_t *location, uint64_t P, uint64_t S, int64_t AHL, bool isGPDisp) { int32_t result = 0; if (isGPDisp) result = (AHL + S - P) - (int16_t)(AHL + S - P); else result = (AHL + S) - (int16_t)(AHL + S); applyReloc(location, result >> 16, 0xffff); } /// \brief R_MIPS_LO16 /// local/external: lo16 AHL + S (truncate) /// _gp_disp : lo16 AHL + GP - P + 4 (verify) static void relocLo16(uint8_t *location, uint64_t P, uint64_t S, int64_t AHL, bool isGPDisp) { int32_t result = 0; if (isGPDisp) result = AHL + S - P + 4; else result = AHL + S; applyReloc(location, result, 0xffff); } /// \brief R_MIPS_GOT16, R_MIPS_CALL16 /// rel16 G (verify) static void relocGOT(uint8_t *location, uint64_t P, uint64_t S, int64_t A, uint64_t GP) { int32_t G = (int32_t)(S - GP); applyReloc(location, G, 0xffff); } /// \brief R_MIPS_TLS_DTPREL_HI16, R_MIPS_TLS_TPREL_HI16, LLD_R_MIPS_HI16 /// (S + A) >> 16 static void relocGeneralHi16(uint8_t *location, uint64_t S, int64_t A) { int32_t result = S + A + 0x8000; applyReloc(location, result >> 16, 0xffff); } /// \brief R_MIPS_TLS_DTPREL_LO16, R_MIPS_TLS_TPREL_LO16, LLD_R_MIPS_LO16 /// S + A static void relocGeneralLo16(uint8_t *location, uint64_t S, int64_t A) { int32_t result = S + A; applyReloc(location, result, 0xffff); } /// \brief R_MIPS_GPREL32 /// local: rel32 A + S + GP0 – GP (truncate) static void relocGPRel32(uint8_t *location, uint64_t P, uint64_t S, int64_t A, uint64_t GP) { int32_t result = A + S + 0 - GP; applyReloc(location, result, 0xffffffff); } /// \brief LLD_R_MIPS_32_HI16 static void reloc32hi16(uint8_t *location, uint64_t S, int64_t A) { applyReloc(location, (S + A + 0x8000) & 0xffff0000, 0xffffffff); } std::error_code MipsTargetRelocationHandler::applyRelocation( ELFWriter &writer, llvm::FileOutputBuffer &buf, const lld::AtomLayout &atom, const Reference &ref) const { if (ref.kindNamespace() != lld::Reference::KindNamespace::ELF) return std::error_code(); assert(ref.kindArch() == Reference::KindArch::Mips); AtomLayout *gpAtom = _mipsTargetLayout.getGP(); uint64_t gpAddr = gpAtom ? gpAtom->_virtualAddr : 0; AtomLayout *gpDispAtom = _mipsTargetLayout.getGPDisp(); bool isGpDisp = gpDispAtom && ref.target() == gpDispAtom->_atom; uint8_t *atomContent = buf.getBufferStart() + atom._fileOffset; uint8_t *location = atomContent + ref.offsetInAtom(); uint64_t targetVAddress = writer.addressOfAtom(ref.target()); uint64_t relocVAddress = atom._virtualAddr + ref.offsetInAtom(); switch (ref.kindValue()) { case R_MIPS_NONE: break; case R_MIPS_32: reloc32(location, relocVAddress, targetVAddress, ref.addend()); break; case R_MIPS_26: reloc26loc(location, relocVAddress, targetVAddress, ref.addend()); break; case R_MIPS_HI16: relocHi16(location, relocVAddress, targetVAddress, ref.addend(), isGpDisp); break; case R_MIPS_LO16: relocLo16(location, relocVAddress, targetVAddress, ref.addend(), isGpDisp); break; case R_MIPS_GOT16: relocGOT(location, relocVAddress, targetVAddress, ref.addend(), gpAddr); break; case R_MIPS_CALL16: relocGOT(location, relocVAddress, targetVAddress, ref.addend(), gpAddr); break; case R_MIPS_TLS_GD: relocGOT(location, relocVAddress, targetVAddress, ref.addend(), gpAddr); break; case R_MIPS_TLS_LDM: case R_MIPS_TLS_GOTTPREL: relocGOT(location, relocVAddress, targetVAddress, ref.addend(), gpAddr); break; case R_MIPS_TLS_DTPREL_HI16: case R_MIPS_TLS_TPREL_HI16: relocGeneralHi16(location, targetVAddress, ref.addend()); break; case R_MIPS_TLS_DTPREL_LO16: case R_MIPS_TLS_TPREL_LO16: relocGeneralLo16(location, targetVAddress, ref.addend()); break; case R_MIPS_GPREL32: relocGPRel32(location, relocVAddress, targetVAddress, ref.addend(), gpAddr); break; case R_MIPS_JALR: // We do not do JALR optimization now. break; case R_MIPS_REL32: case R_MIPS_JUMP_SLOT: case R_MIPS_COPY: case R_MIPS_TLS_DTPMOD32: case R_MIPS_TLS_DTPREL32: case R_MIPS_TLS_TPREL32: // Ignore runtime relocations. break; case R_MIPS_PC32: relocpc32(location, relocVAddress, targetVAddress, ref.addend()); break; case LLD_R_MIPS_GLOBAL_GOT: // Do nothing. break; case LLD_R_MIPS_32_HI16: reloc32hi16(location, targetVAddress, ref.addend()); break; case LLD_R_MIPS_GLOBAL_26: reloc26ext(location, targetVAddress, ref.addend()); break; case LLD_R_MIPS_HI16: relocGeneralHi16(location, targetVAddress, 0); break; case LLD_R_MIPS_LO16: relocGeneralLo16(location, targetVAddress, 0); break; case LLD_R_MIPS_STO_PLT: // Do nothing. break; default: { std::string str; llvm::raw_string_ostream s(str); s << "Unhandled Mips relocation: " << ref.kindValue(); llvm_unreachable(s.str().c_str()); } } return std::error_code(); } <commit_msg>Fix unicode chars into ascii in comment lines.<commit_after>//===- lib/ReaderWriter/ELF/Mips/MipsRelocationHandler.cpp ----------------===// // // The LLVM Linker // // This file is distributed under the University of Illinois Open Source // License. See LICENSE.TXT for details. // //===----------------------------------------------------------------------===// #include "MipsTargetHandler.h" #include "MipsLinkingContext.h" #include "MipsRelocationHandler.h" #include "lld/ReaderWriter/RelocationHelperFunctions.h" using namespace lld; using namespace elf; using namespace llvm::ELF; static inline void applyReloc(uint8_t *loc, uint32_t result, uint32_t mask) { auto target = reinterpret_cast<llvm::support::ulittle32_t *>(loc); *target = (uint32_t(*target) & ~mask) | (result & mask); } template <size_t BITS, class T> inline T signExtend(T val) { if (val & (T(1) << (BITS - 1))) val |= T(-1) << BITS; return val; } /// \brief R_MIPS_32 /// local/external: word32 S + A (truncate) static void reloc32(uint8_t *location, uint64_t P, uint64_t S, int64_t A) { applyReloc(location, S + A, 0xffffffff); } /// \brief R_MIPS_PC32 /// local/external: word32 S + A i- P (truncate) void relocpc32(uint8_t *location, uint64_t P, uint64_t S, int64_t A) { applyReloc(location, S + A - P, 0xffffffff); } /// \brief R_MIPS_26 /// local : ((A | ((P + 4) & 0x3F000000)) + S) >> 2 static void reloc26loc(uint8_t *location, uint64_t P, uint64_t S, int32_t A) { uint32_t result = ((A << 2) | ((P + 4) & 0x3f000000)) + S; applyReloc(location, result >> 2, 0x03ffffff); } /// \brief LLD_R_MIPS_GLOBAL_26 /// external: (sign-extend(A) + S) >> 2 static void reloc26ext(uint8_t *location, uint64_t S, int32_t A) { uint32_t result = signExtend<28>(A << 2) + S; applyReloc(location, result >> 2, 0x03ffffff); } /// \brief R_MIPS_HI16 /// local/external: hi16 (AHL + S) - (short)(AHL + S) (truncate) /// _gp_disp : hi16 (AHL + GP - P) - (short)(AHL + GP - P) (verify) static void relocHi16(uint8_t *location, uint64_t P, uint64_t S, int64_t AHL, bool isGPDisp) { int32_t result = 0; if (isGPDisp) result = (AHL + S - P) - (int16_t)(AHL + S - P); else result = (AHL + S) - (int16_t)(AHL + S); applyReloc(location, result >> 16, 0xffff); } /// \brief R_MIPS_LO16 /// local/external: lo16 AHL + S (truncate) /// _gp_disp : lo16 AHL + GP - P + 4 (verify) static void relocLo16(uint8_t *location, uint64_t P, uint64_t S, int64_t AHL, bool isGPDisp) { int32_t result = 0; if (isGPDisp) result = AHL + S - P + 4; else result = AHL + S; applyReloc(location, result, 0xffff); } /// \brief R_MIPS_GOT16, R_MIPS_CALL16 /// rel16 G (verify) static void relocGOT(uint8_t *location, uint64_t P, uint64_t S, int64_t A, uint64_t GP) { int32_t G = (int32_t)(S - GP); applyReloc(location, G, 0xffff); } /// \brief R_MIPS_TLS_DTPREL_HI16, R_MIPS_TLS_TPREL_HI16, LLD_R_MIPS_HI16 /// (S + A) >> 16 static void relocGeneralHi16(uint8_t *location, uint64_t S, int64_t A) { int32_t result = S + A + 0x8000; applyReloc(location, result >> 16, 0xffff); } /// \brief R_MIPS_TLS_DTPREL_LO16, R_MIPS_TLS_TPREL_LO16, LLD_R_MIPS_LO16 /// S + A static void relocGeneralLo16(uint8_t *location, uint64_t S, int64_t A) { int32_t result = S + A; applyReloc(location, result, 0xffff); } /// \brief R_MIPS_GPREL32 /// local: rel32 A + S + GP0 - GP (truncate) static void relocGPRel32(uint8_t *location, uint64_t P, uint64_t S, int64_t A, uint64_t GP) { int32_t result = A + S + 0 - GP; applyReloc(location, result, 0xffffffff); } /// \brief LLD_R_MIPS_32_HI16 static void reloc32hi16(uint8_t *location, uint64_t S, int64_t A) { applyReloc(location, (S + A + 0x8000) & 0xffff0000, 0xffffffff); } std::error_code MipsTargetRelocationHandler::applyRelocation( ELFWriter &writer, llvm::FileOutputBuffer &buf, const lld::AtomLayout &atom, const Reference &ref) const { if (ref.kindNamespace() != lld::Reference::KindNamespace::ELF) return std::error_code(); assert(ref.kindArch() == Reference::KindArch::Mips); AtomLayout *gpAtom = _mipsTargetLayout.getGP(); uint64_t gpAddr = gpAtom ? gpAtom->_virtualAddr : 0; AtomLayout *gpDispAtom = _mipsTargetLayout.getGPDisp(); bool isGpDisp = gpDispAtom && ref.target() == gpDispAtom->_atom; uint8_t *atomContent = buf.getBufferStart() + atom._fileOffset; uint8_t *location = atomContent + ref.offsetInAtom(); uint64_t targetVAddress = writer.addressOfAtom(ref.target()); uint64_t relocVAddress = atom._virtualAddr + ref.offsetInAtom(); switch (ref.kindValue()) { case R_MIPS_NONE: break; case R_MIPS_32: reloc32(location, relocVAddress, targetVAddress, ref.addend()); break; case R_MIPS_26: reloc26loc(location, relocVAddress, targetVAddress, ref.addend()); break; case R_MIPS_HI16: relocHi16(location, relocVAddress, targetVAddress, ref.addend(), isGpDisp); break; case R_MIPS_LO16: relocLo16(location, relocVAddress, targetVAddress, ref.addend(), isGpDisp); break; case R_MIPS_GOT16: relocGOT(location, relocVAddress, targetVAddress, ref.addend(), gpAddr); break; case R_MIPS_CALL16: relocGOT(location, relocVAddress, targetVAddress, ref.addend(), gpAddr); break; case R_MIPS_TLS_GD: relocGOT(location, relocVAddress, targetVAddress, ref.addend(), gpAddr); break; case R_MIPS_TLS_LDM: case R_MIPS_TLS_GOTTPREL: relocGOT(location, relocVAddress, targetVAddress, ref.addend(), gpAddr); break; case R_MIPS_TLS_DTPREL_HI16: case R_MIPS_TLS_TPREL_HI16: relocGeneralHi16(location, targetVAddress, ref.addend()); break; case R_MIPS_TLS_DTPREL_LO16: case R_MIPS_TLS_TPREL_LO16: relocGeneralLo16(location, targetVAddress, ref.addend()); break; case R_MIPS_GPREL32: relocGPRel32(location, relocVAddress, targetVAddress, ref.addend(), gpAddr); break; case R_MIPS_JALR: // We do not do JALR optimization now. break; case R_MIPS_REL32: case R_MIPS_JUMP_SLOT: case R_MIPS_COPY: case R_MIPS_TLS_DTPMOD32: case R_MIPS_TLS_DTPREL32: case R_MIPS_TLS_TPREL32: // Ignore runtime relocations. break; case R_MIPS_PC32: relocpc32(location, relocVAddress, targetVAddress, ref.addend()); break; case LLD_R_MIPS_GLOBAL_GOT: // Do nothing. break; case LLD_R_MIPS_32_HI16: reloc32hi16(location, targetVAddress, ref.addend()); break; case LLD_R_MIPS_GLOBAL_26: reloc26ext(location, targetVAddress, ref.addend()); break; case LLD_R_MIPS_HI16: relocGeneralHi16(location, targetVAddress, 0); break; case LLD_R_MIPS_LO16: relocGeneralLo16(location, targetVAddress, 0); break; case LLD_R_MIPS_STO_PLT: // Do nothing. break; default: { std::string str; llvm::raw_string_ostream s(str); s << "Unhandled Mips relocation: " << ref.kindValue(); llvm_unreachable(s.str().c_str()); } } return std::error_code(); } <|endoftext|>
<commit_before>#pragma once #include <cstdint> #include <vector> #include <string> #if __BIG_ENDIAN #define RTP_HEADER(port, subclass, ack, sfs) \ (((port & 0x0F) << 4) | ((subclass & 0x03) << 2) | ((ack & 0x01) << 1) | \ (sfs & 0x01)) #else #define RTP_HEADER(port, subclass, ack, sfs) \ (((sfs & 0x01) << 7) | ((ack & 0x01) << 6) | ((subclass & 0x03) << 4) | \ (port & 0x0F)) #endif #define BASE_STATION_ADDR (1) #define LOOPBACK_ADDR (127) namespace rtp { /// static const unsigned int MAX_DATA_SZ = 120; /** * @brief { port enumerations for different communication protocols } */ enum port { SINK = 0x00, LINK = 0x01, CONTROL = 0x02, SETPOINT = 0x03, GSTROBE = 0x04, DISCOVER = 0x05, LOGGER = 0x06, TCP = 0x07, LEGACY = 0x0E }; namespace { // type of data field used in all packet classes // - must be 8 bits, (typedef used for eaiser compiler // type error debugging) typedef uint8_t data_t; } class header_data { public: enum type { control, tuning, ota, misc }; header_data() : t(control), address(0), port_fields(0){}; size_t size() const { return 2; } // datav_it_t pack(size_t payload_size, bool headless = false) { // if (d.size()) return d.begin(); // // payload size + number of bytes in header is top byte // // since that's required for the cc1101/cc1201 with // // variable packet sizes // d.push_back(payload_size + (headless ? 0 : 2)); // if (headless == false) { // d.push_back(address); // d.push_back(port_fields); // } // return d.begin(); // } type t; data_t address; friend class payload_data; // common header byte - union so it's easier to put into vector data_t port_fields; struct { #if __BIG_ENDIAN data_t sfs : 1, ack : 1, subclass : 2, port : 4; #else data_t port : 4, subclass : 2, ack : 1, sfs : 1; #endif } __attribute__((packed)); }; class payload_data { public: payload_data() {}; std::vector<data_t> d; size_t size() const { return d.size(); } template <class T> void fill(const std::vector<T>& v) { d = v; } void fill(const std::string& str) { for (const char& c : str) d.push_back(c); d.push_back('\0'); } }; /** * @brief { Real-Time packet definition } */ class packet { public: rtp::header_data header; rtp::payload_data payload; packet(){}; packet(const std::string& s) { payload.fill(s); } template <class T> packet(const std::vector<T>& v) { payload.fill(v); } size_t size(bool includeHeader = true) { if (includeHeader) return payload.size() + header.size(); else return payload.size(); } int port() const { return static_cast<int>(header.port); } template <class T> void port(T p) { header.port = static_cast<unsigned int>(p); } int subclass() { return header.subclass; } template <class T> void subclass(T c) { header.subclass = static_cast<unsigned int>(c); } bool ack() { return header.ack; } void ack(bool b) { header.ack = b; } bool sfs() { return header.sfs; } void sfs(bool b) { header.sfs = b; } int address() { return header.address; } void address(int a) { header.address = static_cast<unsigned int>(a); } template <class T> void recv(const std::vector<T>& v) { payload.fill(v); // sort out header } void pack(std::vector<data_t> *buffer, bool includeHeader = false) const { buffer->reserve(MAX_DATA_SZ); // first byte is total size (excluding the size byte) const uint8_t total_size = payload.size() + (includeHeader ? 2 : 0); buffer->push_back(total_size); // header data if (includeHeader) { buffer->push_back(header.address); buffer->push_back(header.port_fields); } // payload buffer->insert(buffer->end(), payload.d.begin(), payload.d.end()); } }; } <commit_msg>slight rtp cleanup<commit_after>#pragma once #include <cstdint> #include <vector> #include <string> #if __BIG_ENDIAN #define RTP_HEADER(port, subclass, ack, sfs) \ (((port & 0x0F) << 4) | ((subclass & 0x03) << 2) | ((ack & 0x01) << 1) | \ (sfs & 0x01)) #else #define RTP_HEADER(port, subclass, ack, sfs) \ (((sfs & 0x01) << 7) | ((ack & 0x01) << 6) | ((subclass & 0x03) << 4) | \ (port & 0x0F)) #endif #define BASE_STATION_ADDR (1) #define LOOPBACK_ADDR (127) namespace rtp { /// static const unsigned int MAX_DATA_SZ = 120; /** * @brief { port enumerations for different communication protocols } */ enum port { SINK = 0x00, LINK = 0x01, CONTROL = 0x02, SETPOINT = 0x03, GSTROBE = 0x04, DISCOVER = 0x05, LOGGER = 0x06, TCP = 0x07, LEGACY = 0x0E }; namespace { // type of data field used in all packet classes // - must be 8 bits, (typedef used for eaiser compiler // type error debugging) typedef uint8_t data_t; } class header_data { public: enum type { control, tuning, ota, misc }; header_data() : t(control), address(0), port_fields(0){}; size_t size() const { return 2; } type t; data_t address; friend class payload_data; // common header byte - union so it's easier to put into vector data_t port_fields; struct { #if __BIG_ENDIAN data_t sfs : 1, ack : 1, subclass : 2, port : 4; #else data_t port : 4, subclass : 2, ack : 1, sfs : 1; #endif } __attribute__((packed)); }; class payload_data { public: payload_data() {}; std::vector<data_t> d; size_t size() const { return d.size(); } template <class T> void fill(const std::vector<T>& v) { d = v; } void fill(const std::string& str) { for (const char& c : str) d.push_back(c); d.push_back('\0'); } }; /** * @brief { Real-Time packet definition } */ class packet { public: rtp::header_data header; rtp::payload_data payload; packet(){}; packet(const std::string& s) { payload.fill(s); } template <class T> packet(const std::vector<T>& v) { payload.fill(v); } size_t size(bool includeHeader = true) { if (includeHeader) return payload.size() + header.size(); else return payload.size(); } int port() const { return static_cast<int>(header.port); } template <class T> void port(T p) { header.port = static_cast<unsigned int>(p); } int subclass() { return header.subclass; } template <class T> void subclass(T c) { header.subclass = static_cast<unsigned int>(c); } bool ack() { return header.ack; } void ack(bool b) { header.ack = b; } bool sfs() { return header.sfs; } void sfs(bool b) { header.sfs = b; } int address() { return header.address; } void address(int a) { header.address = static_cast<unsigned int>(a); } template <class T> void recv(const std::vector<T>& v) { payload.fill(v); // sort out header } void pack(std::vector<data_t> *buffer, bool includeHeader = false) const { // first byte is total size (excluding the size byte) const uint8_t total_size = payload.size() + (includeHeader ? header.size() : 0); buffer->reserve(total_size + 1); buffer->push_back(total_size); // header data if (includeHeader) { buffer->push_back(header.address); buffer->push_back(header.port_fields); } // payload buffer->insert(buffer->end(), payload.d.begin(), payload.d.end()); } }; } <|endoftext|>
<commit_before>/* NES_Keyboard.h - A library to control a keyboard with an NES controller. *WARNING* This code requires a Leonardo or Micro (NOT DUE!!!) (The Due runs on 3.3v and would likely break if you try to run this code) Copyright (c) 2014 James P. McCullough. All rights reserved. */ #include "NES_Keyboard.h" #include <Arduino.h> byte count[] = {0,0,0,0,0,0,0,0}; char keys[] = "abcdefgh"; NES_Keyboard::NES_Keyboard(void) { pulse = 5; latch = 7; data = 9; pinMode(latch, OUTPUT); pinMode(pulse, OUTPUT); pinMode(data, INPUT); digitalWrite(latch, LOW); digitalWrite(pulse, LOW); } NES_Keyboard::NES_Keyboard(byte p, byte l, byte d) { pulse = p; latch = l; data = d; pinMode(latch, OUTPUT); pinMode(pulse, OUTPUT); pinMode(data, INPUT); digitalWrite(latch, LOW); digitalWrite(pulse, LOW); } void NES_Keyboard::latchData(void) { digitalWrite(latch, HIGH); delayMicroseconds(12); digitalWrite(latch, LOW); delayMicroseconds(6); } void NES_Keyboard::pulseClock(void) { digitalWrite(pulse, HIGH); delayMicroseconds(5); digitalWrite(pulse, LOW); delayMicroseconds(5); } void NES_Keyboard::storeData(void) { data_byte = 0; for (int i = 0; i < 8; i++) { data_byte = data_byte | (digitalRead(data) << i); pulseClock(); } } void NES_Keyboard::readData(void) { for (int i = 0; i < 8; i++) { tempbit = bitRead(data_byte, i); if (tempbit == 0 && count[i] == 0) { count[i] = 1; Keyboard.press(keys[i]); } else if (tempbit == 1 && count[i] == 1) { count[i] = 0; Keyboard.release(keys[i]); } } delay(16); } void NES_Keyboard::setKeys(char input[]) { for (int i = 0; i < 8; i++) { keys[i] = input[i]; } }<commit_msg>Added Comments<commit_after>/* NES_Keyboard.h - A library to control a keyboard with an NES controller. *WARNING* This code requires a Leonardo or Micro (NOT DUE!!!) (The Due runs on 3.3v and would likely break if you try to run this code) Copyright (c) 2014 James P. McCullough. All rights reserved. */ #include "NES_Keyboard.h" #include <Arduino.h> //stores 1 or 0 indicating whether a button is pressed or not byte count[] = {0,0,0,0,0,0,0,0}; char keys[] = "abcdefgh"; //the keys to be pressed NES_Keyboard::NES_Keyboard(void) { pulse = 5; latch = 7; data = 9; pinMode(latch, OUTPUT); pinMode(pulse, OUTPUT); pinMode(data, INPUT); //set a clean low signal digitalWrite(latch, LOW); digitalWrite(pulse, LOW); } NES_Keyboard::NES_Keyboard(byte p, byte l, byte d) { pulse = p; latch = l; data = d; pinMode(latch, OUTPUT); pinMode(pulse, OUTPUT); pinMode(data, INPUT); digitalWrite(latch, LOW); digitalWrite(pulse, LOW); } //tells controller to latch data by sending 12uS pulse on latch pin void NES_Keyboard::latchData(void) { digitalWrite(latch, HIGH); delayMicroseconds(12); digitalWrite(latch, LOW); delayMicroseconds(6); } //shifts data from controller by pulsing clock pin void NES_Keyboard::pulseClock(void) { digitalWrite(pulse, HIGH); delayMicroseconds(5); digitalWrite(pulse, LOW); delayMicroseconds(5); } <<<<<<< HEAD ======= //stores data from controller to be iterated through >>>>>>> Added Comments void NES_Keyboard::storeData(void) { data_byte = 0; for (int i = 0; i < 8; i++) { data_byte = data_byte | (digitalRead(data) << i); pulseClock(); } } //iterates through data and presses appropiate keys void NES_Keyboard::readData(void) { for (int i = 0; i < 8; i++) { tempbit = bitRead(data_byte, i); if (tempbit == 0 && count[i] == 0) { count[i] = 1; Keyboard.press(keys[i]); } else if (tempbit == 1 && count[i] == 1) { count[i] = 0; Keyboard.release(keys[i]); } } delay(16); } //set which keys to be pressed void NES_Keyboard::setKeys(char input[]) { for (int i = 0; i < 8; i++) { keys[i] = input[i]; } }<|endoftext|>
<commit_before>/** * Copyright (C) 2021 3D Repo Ltd * * This program 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. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Affero General Public License for more details. * * You should have received a copy of the GNU Affero General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ #include "repo_license.h" #include "repo_log.h" #include "datastructure/repo_uuid.h" #include "repo_exception.h" #include "repo_utils.h" using namespace repo::lib; #ifdef REPO_LICENSE_CHECK #include "cryptolens/Error.hpp" static const std::string licenseEnvVarName = "REPO_LICENSE"; static const std::string instanceUuidEnvVarName = "REPO_INSTANCE_ID"; static const std::string pubKeyModulus = LICENSE_RSA_PUB_KEY_MOD; static const std::string pubKeyExponent = LICENSE_RSA_PUB_KEY_EXP; static const std::string authToken = LICENSE_AUTH_TOKEN; static const int floatingTimeIntervalSec = LICENSE_TIMEOUT_SECONDS; static const int productId = LICENSE_PRODUCT_ID; std::string LicenseValidator::instanceUuid; std::string LicenseValidator::license; std::unique_ptr<Cryptolens> LicenseValidator::cryptolensHandle; std::string LicenseValidator::getInstanceUuid() { instanceUuid = instanceUuid.empty() ? repo::lib::getEnvString(instanceUuidEnvVarName) : instanceUuid; if (instanceUuid.empty()) { instanceUuid = repo::lib::RepoUUID::createUUID().toString(); repoInfo << instanceUuidEnvVarName << " is not set. Setting machine instance ID to " << instanceUuid; } return instanceUuid; } std::string LicenseValidator::getLicenseString() { std::string licenseStr = repo::lib::getEnvString(licenseEnvVarName); if (licenseStr.empty()) { std::string errMsg = "License not found, please ensure " + licenseEnvVarName + " is set."; repoError << errMsg; throw repo::lib::RepoInvalidLicenseException(errMsg); } return licenseStr; } std::string LicenseValidator::getFormattedUtcTime(time_t timeStamp) { struct tm tstruct = *gmtime(&timeStamp); char buf[80]; strftime(buf, sizeof(buf), "%Y/%m/%d %X", &tstruct); std::string formatedStr(buf); return formatedStr; } #endif void LicenseValidator::activate() { #ifdef REPO_LICENSE_CHECK if (!instanceUuid.empty() || cryptolensHandle) { repoError << " Attempting to activate more than once, aborting activation"; return; } license = getLicenseString(); cryptolens::Error e; cryptolensHandle = std::unique_ptr<Cryptolens>(new Cryptolens(e)); cryptolensHandle->signature_verifier.set_modulus_base64(e, pubKeyModulus); cryptolensHandle->signature_verifier.set_exponent_base64(e, pubKeyExponent); cryptolensHandle->machine_code_computer.set_machine_code(e, getInstanceUuid()); cryptolens::optional<cryptolens::LicenseKey> licenseKey = cryptolensHandle->activate_floating ( e, authToken, productId, license, floatingTimeIntervalSec ); if (e) { cryptolens::ActivateError error = cryptolens::ActivateError::from_reason(e.get_reason()); std::string errMsg = error.what(); repoError << "License activation failed: " << errMsg; throw repo::lib::RepoInvalidLicenseException(errMsg); } else { bool licenseBlocked = licenseKey->get_block(); bool licenseExpired = static_cast<bool>(licenseKey->check().has_expired(time(0))); if (!licenseExpired && !licenseBlocked) { repoTrace << "****License activation summary****"; repoTrace << "- session license ID: " << instanceUuid; repoTrace << "- server message: " << licenseKey->get_notes().has_value() ? licenseKey->get_notes().value() : ""; repoTrace << "- server respose ok: true"; repoTrace << "- license blocked: " << licenseBlocked; repoTrace << "- license expired: " << licenseExpired; repoTrace << "- license expiry on: " << getFormattedUtcTime(licenseKey->get_expires()) << " (UTC)"; if (licenseKey->get_activated_machines().has_value()) repoTrace << "- #activated instances: " << licenseKey->get_activated_machines()->size(); if (licenseKey->get_maxnoofmachines().has_value()) repoTrace << "- allowed instances: " << licenseKey->get_maxnoofmachines().value(); repoInfo << "License activated"; repoTrace << "**********************************"; } else { std::string errMsg = licenseExpired ? "License expired." : " License is blocked"; repoError << "License activation failed: " << errMsg; deactivate(); throw repo::lib::RepoInvalidLicenseException(errMsg); } } #endif } void LicenseValidator::deactivate() { #ifdef REPO_LICENSE_CHECK if (instanceUuid.empty() || !cryptolensHandle) { repoError << " Attempting to deactivate without activation, aborting deactivation"; return; } cryptolens::Error e; cryptolensHandle->deactivate( e, authToken, productId, license, instanceUuid, true); if (e) { repoTrace << "****License deactivation summary****"; cryptolens::ActivateError error = cryptolens::ActivateError::from_reason(e.get_reason()); repoTrace << "- server message: " << error.what(); repoTrace << "- session license ID: " << instanceUuid; repoTrace << "- deactivation result: session not removed from license. Error trying to deactivate license. "; repoTrace << " this allocation will time out in less than " << floatingTimeIntervalSec << " seconds"; repoTrace << "************************************"; repoError << "License deactivation failed: " << error.what(); } else { repoInfo << "License allocation relinquished"; } cryptolensHandle.reset(); instanceUuid.clear(); #endif }<commit_msg>ISSUE #519 needs bracketing<commit_after>/** * Copyright (C) 2021 3D Repo Ltd * * This program 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. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Affero General Public License for more details. * * You should have received a copy of the GNU Affero General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ #include "repo_license.h" #include "repo_log.h" #include "datastructure/repo_uuid.h" #include "repo_exception.h" #include "repo_utils.h" using namespace repo::lib; #ifdef REPO_LICENSE_CHECK #include "cryptolens/Error.hpp" static const std::string licenseEnvVarName = "REPO_LICENSE"; static const std::string instanceUuidEnvVarName = "REPO_INSTANCE_ID"; static const std::string pubKeyModulus = LICENSE_RSA_PUB_KEY_MOD; static const std::string pubKeyExponent = LICENSE_RSA_PUB_KEY_EXP; static const std::string authToken = LICENSE_AUTH_TOKEN; static const int floatingTimeIntervalSec = LICENSE_TIMEOUT_SECONDS; static const int productId = LICENSE_PRODUCT_ID; std::string LicenseValidator::instanceUuid; std::string LicenseValidator::license; std::unique_ptr<Cryptolens> LicenseValidator::cryptolensHandle; std::string LicenseValidator::getInstanceUuid() { instanceUuid = instanceUuid.empty() ? repo::lib::getEnvString(instanceUuidEnvVarName) : instanceUuid; if (instanceUuid.empty()) { instanceUuid = repo::lib::RepoUUID::createUUID().toString(); repoInfo << instanceUuidEnvVarName << " is not set. Setting machine instance ID to " << instanceUuid; } return instanceUuid; } std::string LicenseValidator::getLicenseString() { std::string licenseStr = repo::lib::getEnvString(licenseEnvVarName); if (licenseStr.empty()) { std::string errMsg = "License not found, please ensure " + licenseEnvVarName + " is set."; repoError << errMsg; throw repo::lib::RepoInvalidLicenseException(errMsg); } return licenseStr; } std::string LicenseValidator::getFormattedUtcTime(time_t timeStamp) { struct tm tstruct = *gmtime(&timeStamp); char buf[80]; strftime(buf, sizeof(buf), "%Y/%m/%d %X", &tstruct); std::string formatedStr(buf); return formatedStr; } #endif void LicenseValidator::activate() { #ifdef REPO_LICENSE_CHECK if (!instanceUuid.empty() || cryptolensHandle) { repoError << " Attempting to activate more than once, aborting activation"; return; } license = getLicenseString(); cryptolens::Error e; cryptolensHandle = std::unique_ptr<Cryptolens>(new Cryptolens(e)); cryptolensHandle->signature_verifier.set_modulus_base64(e, pubKeyModulus); cryptolensHandle->signature_verifier.set_exponent_base64(e, pubKeyExponent); cryptolensHandle->machine_code_computer.set_machine_code(e, getInstanceUuid()); cryptolens::optional<cryptolens::LicenseKey> licenseKey = cryptolensHandle->activate_floating ( e, authToken, productId, license, floatingTimeIntervalSec ); if (e) { cryptolens::ActivateError error = cryptolens::ActivateError::from_reason(e.get_reason()); std::string errMsg = error.what(); repoError << "License activation failed: " << errMsg; throw repo::lib::RepoInvalidLicenseException(errMsg); } else { bool licenseBlocked = licenseKey->get_block(); bool licenseExpired = static_cast<bool>(licenseKey->check().has_expired(time(0))); if (!licenseExpired && !licenseBlocked) { repoTrace << "****License activation summary****"; repoTrace << "- session license ID: " << instanceUuid; repoTrace << "- server message: " << (licenseKey->get_notes().has_value() ? licenseKey->get_notes().value() : ""); repoTrace << "- server respose ok: true"; repoTrace << "- license blocked: " << licenseBlocked; repoTrace << "- license expired: " << licenseExpired; repoTrace << "- license expiry on: " << getFormattedUtcTime(licenseKey->get_expires()) << " (UTC)"; if (licenseKey->get_activated_machines().has_value()) repoTrace << "- #activated instances: " << licenseKey->get_activated_machines()->size(); if (licenseKey->get_maxnoofmachines().has_value()) repoTrace << "- allowed instances: " << licenseKey->get_maxnoofmachines().value(); repoInfo << "License activated"; repoTrace << "**********************************"; } else { std::string errMsg = licenseExpired ? "License expired." : " License is blocked"; repoError << "License activation failed: " << errMsg; deactivate(); throw repo::lib::RepoInvalidLicenseException(errMsg); } } #endif } void LicenseValidator::deactivate() { #ifdef REPO_LICENSE_CHECK if (instanceUuid.empty() || !cryptolensHandle) { repoError << " Attempting to deactivate without activation, aborting deactivation"; return; } cryptolens::Error e; cryptolensHandle->deactivate( e, authToken, productId, license, instanceUuid, true); if (e) { repoTrace << "****License deactivation summary****"; cryptolens::ActivateError error = cryptolens::ActivateError::from_reason(e.get_reason()); repoTrace << "- server message: " << error.what(); repoTrace << "- session license ID: " << instanceUuid; repoTrace << "- deactivation result: session not removed from license. Error trying to deactivate license. "; repoTrace << " this allocation will time out in less than " << floatingTimeIntervalSec << " seconds"; repoTrace << "************************************"; repoError << "License deactivation failed: " << error.what(); } else { repoInfo << "License allocation relinquished"; } cryptolensHandle.reset(); instanceUuid.clear(); #endif }<|endoftext|>
<commit_before>//===- AMDGPUUnifyDivergentExitNodes.cpp ----------------------------------===// // // The LLVM Compiler Infrastructure // // This file is distributed under the University of Illinois Open Source // License. See LICENSE.TXT for details. // //===----------------------------------------------------------------------===// // // This is a variant of the UnifyDivergentExitNodes pass. Rather than ensuring // there is at most one ret and one unreachable instruction, it ensures there is // at most one divergent exiting block. // // StructurizeCFG can't deal with multi-exit regions formed by branches to // multiple return nodes. It is not desirable to structurize regions with // uniform branches, so unifying those to the same return block as divergent // branches inhibits use of scalar branching. It still can't deal with the case // where one branch goes to return, and one unreachable. Replace unreachable in // this case with a return. // //===----------------------------------------------------------------------===// #include "AMDGPU.h" #include "llvm/ADT/ArrayRef.h" #include "llvm/ADT/SmallPtrSet.h" #include "llvm/ADT/SmallVector.h" #include "llvm/ADT/StringRef.h" #include "llvm/Analysis/DivergenceAnalysis.h" #include "llvm/Analysis/PostDominators.h" #include "llvm/Analysis/TargetTransformInfo.h" #include "llvm/Analysis/Utils/Local.h" #include "llvm/IR/BasicBlock.h" #include "llvm/IR/CFG.h" #include "llvm/IR/Constants.h" #include "llvm/IR/Function.h" #include "llvm/IR/InstrTypes.h" #include "llvm/IR/Instructions.h" #include "llvm/IR/Intrinsics.h" #include "llvm/IR/Type.h" #include "llvm/Pass.h" #include "llvm/Support/Casting.h" #include "llvm/Transforms/Scalar.h" #include "llvm/Transforms/Utils.h" using namespace llvm; #define DEBUG_TYPE "amdgpu-unify-divergent-exit-nodes" namespace { class AMDGPUUnifyDivergentExitNodes : public FunctionPass { public: static char ID; // Pass identification, replacement for typeid AMDGPUUnifyDivergentExitNodes() : FunctionPass(ID) { initializeAMDGPUUnifyDivergentExitNodesPass(*PassRegistry::getPassRegistry()); } // We can preserve non-critical-edgeness when we unify function exit nodes void getAnalysisUsage(AnalysisUsage &AU) const override; bool runOnFunction(Function &F) override; }; } // end anonymous namespace char AMDGPUUnifyDivergentExitNodes::ID = 0; char &llvm::AMDGPUUnifyDivergentExitNodesID = AMDGPUUnifyDivergentExitNodes::ID; INITIALIZE_PASS_BEGIN(AMDGPUUnifyDivergentExitNodes, DEBUG_TYPE, "Unify divergent function exit nodes", false, false) INITIALIZE_PASS_DEPENDENCY(PostDominatorTreeWrapperPass) INITIALIZE_PASS_DEPENDENCY(DivergenceAnalysis) INITIALIZE_PASS_END(AMDGPUUnifyDivergentExitNodes, DEBUG_TYPE, "Unify divergent function exit nodes", false, false) void AMDGPUUnifyDivergentExitNodes::getAnalysisUsage(AnalysisUsage &AU) const{ // TODO: Preserve dominator tree. AU.addRequired<PostDominatorTreeWrapperPass>(); AU.addRequired<DivergenceAnalysis>(); // No divergent values are changed, only blocks and branch edges. AU.addPreserved<DivergenceAnalysis>(); // We preserve the non-critical-edgeness property AU.addPreservedID(BreakCriticalEdgesID); // This is a cluster of orthogonal Transforms AU.addPreservedID(LowerSwitchID); FunctionPass::getAnalysisUsage(AU); AU.addRequired<TargetTransformInfoWrapperPass>(); } /// \returns true if \p BB is reachable through only uniform branches. /// XXX - Is there a more efficient way to find this? static bool isUniformlyReached(const DivergenceAnalysis &DA, BasicBlock &BB) { SmallVector<BasicBlock *, 8> Stack; SmallPtrSet<BasicBlock *, 8> Visited; for (BasicBlock *Pred : predecessors(&BB)) Stack.push_back(Pred); while (!Stack.empty()) { BasicBlock *Top = Stack.pop_back_val(); if (!DA.isUniform(Top->getTerminator())) return false; for (BasicBlock *Pred : predecessors(Top)) { if (Visited.insert(Pred).second) Stack.push_back(Pred); } } return true; } static BasicBlock *unifyReturnBlockSet(Function &F, ArrayRef<BasicBlock *> ReturningBlocks, const TargetTransformInfo &TTI, StringRef Name) { // Otherwise, we need to insert a new basic block into the function, add a PHI // nodes (if the function returns values), and convert all of the return // instructions into unconditional branches. BasicBlock *NewRetBlock = BasicBlock::Create(F.getContext(), Name, &F); PHINode *PN = nullptr; if (F.getReturnType()->isVoidTy()) { ReturnInst::Create(F.getContext(), nullptr, NewRetBlock); } else { // If the function doesn't return void... add a PHI node to the block... PN = PHINode::Create(F.getReturnType(), ReturningBlocks.size(), "UnifiedRetVal"); NewRetBlock->getInstList().push_back(PN); ReturnInst::Create(F.getContext(), PN, NewRetBlock); } // Loop over all of the blocks, replacing the return instruction with an // unconditional branch. for (BasicBlock *BB : ReturningBlocks) { // Add an incoming element to the PHI node for every return instruction that // is merging into this new block... if (PN) PN->addIncoming(BB->getTerminator()->getOperand(0), BB); BB->getInstList().pop_back(); // Remove the return insn BranchInst::Create(NewRetBlock, BB); } for (BasicBlock *BB : ReturningBlocks) { // Cleanup possible branch to unconditional branch to the return. simplifyCFG(BB, TTI, {2}); } return NewRetBlock; } bool AMDGPUUnifyDivergentExitNodes::runOnFunction(Function &F) { auto &PDT = getAnalysis<PostDominatorTreeWrapperPass>().getPostDomTree(); if (PDT.getRoots().size() <= 1) return false; DivergenceAnalysis &DA = getAnalysis<DivergenceAnalysis>(); // Loop over all of the blocks in a function, tracking all of the blocks that // return. SmallVector<BasicBlock *, 4> ReturningBlocks; SmallVector<BasicBlock *, 4> UnreachableBlocks; for (BasicBlock *BB : PDT.getRoots()) { if (isa<ReturnInst>(BB->getTerminator())) { if (!isUniformlyReached(DA, *BB)) ReturningBlocks.push_back(BB); } else if (isa<UnreachableInst>(BB->getTerminator())) { if (!isUniformlyReached(DA, *BB)) UnreachableBlocks.push_back(BB); } } if (!UnreachableBlocks.empty()) { BasicBlock *UnreachableBlock = nullptr; if (UnreachableBlocks.size() == 1) { UnreachableBlock = UnreachableBlocks.front(); } else { UnreachableBlock = BasicBlock::Create(F.getContext(), "UnifiedUnreachableBlock", &F); new UnreachableInst(F.getContext(), UnreachableBlock); for (BasicBlock *BB : UnreachableBlocks) { BB->getInstList().pop_back(); // Remove the unreachable inst. BranchInst::Create(UnreachableBlock, BB); } } if (!ReturningBlocks.empty()) { // Don't create a new unreachable inst if we have a return. The // structurizer/annotator can't handle the multiple exits Type *RetTy = F.getReturnType(); Value *RetVal = RetTy->isVoidTy() ? nullptr : UndefValue::get(RetTy); UnreachableBlock->getInstList().pop_back(); // Remove the unreachable inst. Function *UnreachableIntrin = Intrinsic::getDeclaration(F.getParent(), Intrinsic::amdgcn_unreachable); // Insert a call to an intrinsic tracking that this is an unreachable // point, in case we want to kill the active lanes or something later. CallInst::Create(UnreachableIntrin, {}, "", UnreachableBlock); // Don't create a scalar trap. We would only want to trap if this code was // really reached, but a scalar trap would happen even if no lanes // actually reached here. ReturnInst::Create(F.getContext(), RetVal, UnreachableBlock); ReturningBlocks.push_back(UnreachableBlock); } } // Now handle return blocks. if (ReturningBlocks.empty()) return false; // No blocks return if (ReturningBlocks.size() == 1) return false; // Already has a single return block const TargetTransformInfo &TTI = getAnalysis<TargetTransformInfoWrapperPass>().getTTI(F); unifyReturnBlockSet(F, ReturningBlocks, TTI, "UnifiedReturnBlock"); return true; } <commit_msg>AMDGPU: Use eraseFromParent to delete am instruction when it is no longer needed.<commit_after>//===- AMDGPUUnifyDivergentExitNodes.cpp ----------------------------------===// // // The LLVM Compiler Infrastructure // // This file is distributed under the University of Illinois Open Source // License. See LICENSE.TXT for details. // //===----------------------------------------------------------------------===// // // This is a variant of the UnifyDivergentExitNodes pass. Rather than ensuring // there is at most one ret and one unreachable instruction, it ensures there is // at most one divergent exiting block. // // StructurizeCFG can't deal with multi-exit regions formed by branches to // multiple return nodes. It is not desirable to structurize regions with // uniform branches, so unifying those to the same return block as divergent // branches inhibits use of scalar branching. It still can't deal with the case // where one branch goes to return, and one unreachable. Replace unreachable in // this case with a return. // //===----------------------------------------------------------------------===// #include "AMDGPU.h" #include "llvm/ADT/ArrayRef.h" #include "llvm/ADT/SmallPtrSet.h" #include "llvm/ADT/SmallVector.h" #include "llvm/ADT/StringRef.h" #include "llvm/Analysis/DivergenceAnalysis.h" #include "llvm/Analysis/PostDominators.h" #include "llvm/Analysis/TargetTransformInfo.h" #include "llvm/Analysis/Utils/Local.h" #include "llvm/IR/BasicBlock.h" #include "llvm/IR/CFG.h" #include "llvm/IR/Constants.h" #include "llvm/IR/Function.h" #include "llvm/IR/InstrTypes.h" #include "llvm/IR/Instructions.h" #include "llvm/IR/Intrinsics.h" #include "llvm/IR/Type.h" #include "llvm/Pass.h" #include "llvm/Support/Casting.h" #include "llvm/Transforms/Scalar.h" #include "llvm/Transforms/Utils.h" using namespace llvm; #define DEBUG_TYPE "amdgpu-unify-divergent-exit-nodes" namespace { class AMDGPUUnifyDivergentExitNodes : public FunctionPass { public: static char ID; // Pass identification, replacement for typeid AMDGPUUnifyDivergentExitNodes() : FunctionPass(ID) { initializeAMDGPUUnifyDivergentExitNodesPass(*PassRegistry::getPassRegistry()); } // We can preserve non-critical-edgeness when we unify function exit nodes void getAnalysisUsage(AnalysisUsage &AU) const override; bool runOnFunction(Function &F) override; }; } // end anonymous namespace char AMDGPUUnifyDivergentExitNodes::ID = 0; char &llvm::AMDGPUUnifyDivergentExitNodesID = AMDGPUUnifyDivergentExitNodes::ID; INITIALIZE_PASS_BEGIN(AMDGPUUnifyDivergentExitNodes, DEBUG_TYPE, "Unify divergent function exit nodes", false, false) INITIALIZE_PASS_DEPENDENCY(PostDominatorTreeWrapperPass) INITIALIZE_PASS_DEPENDENCY(DivergenceAnalysis) INITIALIZE_PASS_END(AMDGPUUnifyDivergentExitNodes, DEBUG_TYPE, "Unify divergent function exit nodes", false, false) void AMDGPUUnifyDivergentExitNodes::getAnalysisUsage(AnalysisUsage &AU) const{ // TODO: Preserve dominator tree. AU.addRequired<PostDominatorTreeWrapperPass>(); AU.addRequired<DivergenceAnalysis>(); // No divergent values are changed, only blocks and branch edges. AU.addPreserved<DivergenceAnalysis>(); // We preserve the non-critical-edgeness property AU.addPreservedID(BreakCriticalEdgesID); // This is a cluster of orthogonal Transforms AU.addPreservedID(LowerSwitchID); FunctionPass::getAnalysisUsage(AU); AU.addRequired<TargetTransformInfoWrapperPass>(); } /// \returns true if \p BB is reachable through only uniform branches. /// XXX - Is there a more efficient way to find this? static bool isUniformlyReached(const DivergenceAnalysis &DA, BasicBlock &BB) { SmallVector<BasicBlock *, 8> Stack; SmallPtrSet<BasicBlock *, 8> Visited; for (BasicBlock *Pred : predecessors(&BB)) Stack.push_back(Pred); while (!Stack.empty()) { BasicBlock *Top = Stack.pop_back_val(); if (!DA.isUniform(Top->getTerminator())) return false; for (BasicBlock *Pred : predecessors(Top)) { if (Visited.insert(Pred).second) Stack.push_back(Pred); } } return true; } static BasicBlock *unifyReturnBlockSet(Function &F, ArrayRef<BasicBlock *> ReturningBlocks, const TargetTransformInfo &TTI, StringRef Name) { // Otherwise, we need to insert a new basic block into the function, add a PHI // nodes (if the function returns values), and convert all of the return // instructions into unconditional branches. BasicBlock *NewRetBlock = BasicBlock::Create(F.getContext(), Name, &F); PHINode *PN = nullptr; if (F.getReturnType()->isVoidTy()) { ReturnInst::Create(F.getContext(), nullptr, NewRetBlock); } else { // If the function doesn't return void... add a PHI node to the block... PN = PHINode::Create(F.getReturnType(), ReturningBlocks.size(), "UnifiedRetVal"); NewRetBlock->getInstList().push_back(PN); ReturnInst::Create(F.getContext(), PN, NewRetBlock); } // Loop over all of the blocks, replacing the return instruction with an // unconditional branch. for (BasicBlock *BB : ReturningBlocks) { // Add an incoming element to the PHI node for every return instruction that // is merging into this new block... if (PN) PN->addIncoming(BB->getTerminator()->getOperand(0), BB); // Remove and delete the return inst. BB->getTerminator()->eraseFromParent(); BranchInst::Create(NewRetBlock, BB); } for (BasicBlock *BB : ReturningBlocks) { // Cleanup possible branch to unconditional branch to the return. simplifyCFG(BB, TTI, {2}); } return NewRetBlock; } bool AMDGPUUnifyDivergentExitNodes::runOnFunction(Function &F) { auto &PDT = getAnalysis<PostDominatorTreeWrapperPass>().getPostDomTree(); if (PDT.getRoots().size() <= 1) return false; DivergenceAnalysis &DA = getAnalysis<DivergenceAnalysis>(); // Loop over all of the blocks in a function, tracking all of the blocks that // return. SmallVector<BasicBlock *, 4> ReturningBlocks; SmallVector<BasicBlock *, 4> UnreachableBlocks; for (BasicBlock *BB : PDT.getRoots()) { if (isa<ReturnInst>(BB->getTerminator())) { if (!isUniformlyReached(DA, *BB)) ReturningBlocks.push_back(BB); } else if (isa<UnreachableInst>(BB->getTerminator())) { if (!isUniformlyReached(DA, *BB)) UnreachableBlocks.push_back(BB); } } if (!UnreachableBlocks.empty()) { BasicBlock *UnreachableBlock = nullptr; if (UnreachableBlocks.size() == 1) { UnreachableBlock = UnreachableBlocks.front(); } else { UnreachableBlock = BasicBlock::Create(F.getContext(), "UnifiedUnreachableBlock", &F); new UnreachableInst(F.getContext(), UnreachableBlock); for (BasicBlock *BB : UnreachableBlocks) { // Remove and delete the unreachable inst. BB->getTerminator()->eraseFromParent(); BranchInst::Create(UnreachableBlock, BB); } } if (!ReturningBlocks.empty()) { // Don't create a new unreachable inst if we have a return. The // structurizer/annotator can't handle the multiple exits Type *RetTy = F.getReturnType(); Value *RetVal = RetTy->isVoidTy() ? nullptr : UndefValue::get(RetTy); // Remove and delete the unreachable inst. UnreachableBlock->getTerminator()->eraseFromParent(); Function *UnreachableIntrin = Intrinsic::getDeclaration(F.getParent(), Intrinsic::amdgcn_unreachable); // Insert a call to an intrinsic tracking that this is an unreachable // point, in case we want to kill the active lanes or something later. CallInst::Create(UnreachableIntrin, {}, "", UnreachableBlock); // Don't create a scalar trap. We would only want to trap if this code was // really reached, but a scalar trap would happen even if no lanes // actually reached here. ReturnInst::Create(F.getContext(), RetVal, UnreachableBlock); ReturningBlocks.push_back(UnreachableBlock); } } // Now handle return blocks. if (ReturningBlocks.empty()) return false; // No blocks return if (ReturningBlocks.size() == 1) return false; // Already has a single return block const TargetTransformInfo &TTI = getAnalysis<TargetTransformInfoWrapperPass>().getTTI(F); unifyReturnBlockSet(F, ReturningBlocks, TTI, "UnifiedReturnBlock"); return true; } <|endoftext|>
<commit_before>/************************************************************************* * * OpenOffice.org - a multi-platform office productivity suite * * $RCSfile: SysShentry.cxx,v $ * * $Revision: 1.3 $ * * last change: $Author: hr $ $Date: 2006-06-19 14:20:47 $ * * 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 * ************************************************************************/ //----------------------------------------------------------------------- // includes of other projects //----------------------------------------------------------------------- #ifndef _CPPUHELPER_FACTORY_HXX_ #include <cppuhelper/factory.hxx> #endif #ifndef _COM_SUN_STAR_CONTAINER_XSET_HPP_ #include <com/sun/star/container/XSet.hpp> #endif #ifndef _OSL_DIAGNOSE_H_ #include <osl/diagnose.h> #endif #ifndef _SYSSHEXEC_HXX_ #include "SysShExec.hxx" #endif //----------------------------------------------------------------------- // namespace directives //----------------------------------------------------------------------- using namespace ::rtl ; using namespace ::com::sun::star::uno ; using namespace ::com::sun::star::container ; using namespace ::com::sun::star::lang ; using namespace ::com::sun::star::registry ; using namespace ::cppu ; using com::sun::star::system::XSystemShellExecute; //----------------------------------------------------------------------- // defines //----------------------------------------------------------------------- #define SYSSHEXEC_SERVICE_NAME "com.sun.star.system.SystemShellExecute" #define SYSSHEXEC_IMPL_NAME "com.sun.star.system.SystemShellExecute" #define SYSSHEXEC_REGKEY_NAME "/com.sun.star.system.SystemShellExecute/UNO/SERVICES/com.sun.star.system.SystemShellExecute" //----------------------------------------------------------------------- // //----------------------------------------------------------------------- namespace { Reference< XInterface > SAL_CALL createInstance( const Reference< XMultiServiceFactory >& ) { return Reference< XInterface >( static_cast< XSystemShellExecute* >( new CSysShExec( ) ) ); } } //----------------------------------------------------------------------- // the 3 important functions which will be exported //----------------------------------------------------------------------- extern "C" { //---------------------------------------------------------------------- // component_getImplementationEnvironment //---------------------------------------------------------------------- void SAL_CALL component_getImplementationEnvironment( const sal_Char ** ppEnvTypeName, uno_Environment ** /*ppEnv*/ ) { *ppEnvTypeName = CPPU_CURRENT_LANGUAGE_BINDING_NAME; } //----------------------------------------------------------------------- // //----------------------------------------------------------------------- sal_Bool SAL_CALL component_writeInfo( void* /*pServiceManager*/, void* pRegistryKey ) { sal_Bool bRetVal = sal_True; if ( pRegistryKey ) { try { Reference< XRegistryKey > pXNewKey( static_cast< XRegistryKey* >( pRegistryKey ) ); pXNewKey->createKey( OUString::createFromAscii( SYSSHEXEC_REGKEY_NAME ) ); } catch( InvalidRegistryException& ) { OSL_ENSURE(sal_False, "InvalidRegistryException caught"); bRetVal = sal_False; } } return bRetVal; } //---------------------------------------------------------------------- // component_getFactory // returns a factory to create XFilePicker-Services //---------------------------------------------------------------------- void* SAL_CALL component_getFactory( const sal_Char* pImplName, uno_Interface* pSrvManager, uno_Interface* /*pRegistryKey*/ ) { void* pRet = 0; if ( pSrvManager && ( 0 == rtl_str_compare( pImplName, SYSSHEXEC_IMPL_NAME ) ) ) { Sequence< OUString > aSNS( 1 ); aSNS.getArray( )[0] = OUString::createFromAscii( SYSSHEXEC_SERVICE_NAME ); Reference< XSingleServiceFactory > xFactory ( createOneInstanceFactory( reinterpret_cast< XMultiServiceFactory* > ( pSrvManager ), OUString::createFromAscii( pImplName ), createInstance, aSNS ) ); if ( xFactory.is() ) { xFactory->acquire(); pRet = xFactory.get(); } } return pRet; } } // extern "C" <commit_msg>INTEGRATION: CWS pchfix02 (1.3.32); FILE MERGED 2006/09/01 17:39:08 kaib 1.3.32.1: #i68856# Added header markers and pch files<commit_after>/************************************************************************* * * OpenOffice.org - a multi-platform office productivity suite * * $RCSfile: SysShentry.cxx,v $ * * $Revision: 1.4 $ * * last change: $Author: obo $ $Date: 2006-09-17 01:43:23 $ * * The Contents of this file are made available subject to * the terms of GNU Lesser General Public License Version 2.1. * * * GNU Lesser General Public License Version 2.1 * ============================================= * Copyright 2005 by Sun Microsystems, Inc. * 901 San Antonio Road, Palo Alto, CA 94303, USA * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License version 2.1, as published by the Free Software Foundation. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, * MA 02111-1307 USA * ************************************************************************/ // MARKER(update_precomp.py): autogen include statement, do not remove #include "precompiled_shell.hxx" //----------------------------------------------------------------------- // includes of other projects //----------------------------------------------------------------------- #ifndef _CPPUHELPER_FACTORY_HXX_ #include <cppuhelper/factory.hxx> #endif #ifndef _COM_SUN_STAR_CONTAINER_XSET_HPP_ #include <com/sun/star/container/XSet.hpp> #endif #ifndef _OSL_DIAGNOSE_H_ #include <osl/diagnose.h> #endif #ifndef _SYSSHEXEC_HXX_ #include "SysShExec.hxx" #endif //----------------------------------------------------------------------- // namespace directives //----------------------------------------------------------------------- using namespace ::rtl ; using namespace ::com::sun::star::uno ; using namespace ::com::sun::star::container ; using namespace ::com::sun::star::lang ; using namespace ::com::sun::star::registry ; using namespace ::cppu ; using com::sun::star::system::XSystemShellExecute; //----------------------------------------------------------------------- // defines //----------------------------------------------------------------------- #define SYSSHEXEC_SERVICE_NAME "com.sun.star.system.SystemShellExecute" #define SYSSHEXEC_IMPL_NAME "com.sun.star.system.SystemShellExecute" #define SYSSHEXEC_REGKEY_NAME "/com.sun.star.system.SystemShellExecute/UNO/SERVICES/com.sun.star.system.SystemShellExecute" //----------------------------------------------------------------------- // //----------------------------------------------------------------------- namespace { Reference< XInterface > SAL_CALL createInstance( const Reference< XMultiServiceFactory >& ) { return Reference< XInterface >( static_cast< XSystemShellExecute* >( new CSysShExec( ) ) ); } } //----------------------------------------------------------------------- // the 3 important functions which will be exported //----------------------------------------------------------------------- extern "C" { //---------------------------------------------------------------------- // component_getImplementationEnvironment //---------------------------------------------------------------------- void SAL_CALL component_getImplementationEnvironment( const sal_Char ** ppEnvTypeName, uno_Environment ** /*ppEnv*/ ) { *ppEnvTypeName = CPPU_CURRENT_LANGUAGE_BINDING_NAME; } //----------------------------------------------------------------------- // //----------------------------------------------------------------------- sal_Bool SAL_CALL component_writeInfo( void* /*pServiceManager*/, void* pRegistryKey ) { sal_Bool bRetVal = sal_True; if ( pRegistryKey ) { try { Reference< XRegistryKey > pXNewKey( static_cast< XRegistryKey* >( pRegistryKey ) ); pXNewKey->createKey( OUString::createFromAscii( SYSSHEXEC_REGKEY_NAME ) ); } catch( InvalidRegistryException& ) { OSL_ENSURE(sal_False, "InvalidRegistryException caught"); bRetVal = sal_False; } } return bRetVal; } //---------------------------------------------------------------------- // component_getFactory // returns a factory to create XFilePicker-Services //---------------------------------------------------------------------- void* SAL_CALL component_getFactory( const sal_Char* pImplName, uno_Interface* pSrvManager, uno_Interface* /*pRegistryKey*/ ) { void* pRet = 0; if ( pSrvManager && ( 0 == rtl_str_compare( pImplName, SYSSHEXEC_IMPL_NAME ) ) ) { Sequence< OUString > aSNS( 1 ); aSNS.getArray( )[0] = OUString::createFromAscii( SYSSHEXEC_SERVICE_NAME ); Reference< XSingleServiceFactory > xFactory ( createOneInstanceFactory( reinterpret_cast< XMultiServiceFactory* > ( pSrvManager ), OUString::createFromAscii( pImplName ), createInstance, aSNS ) ); if ( xFactory.is() ) { xFactory->acquire(); pRet = xFactory.get(); } } return pRet; } } // extern "C" <|endoftext|>
<commit_before>/* * Copyright (c) 2002-2010 Stephen Williams ([email protected]) * * This source code is free software; you can redistribute it * and/or modify it in source code form 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 "config.h" # include <iostream> # include <cassert> # include <typeinfo> # include "compiler.h" # include "netlist.h" # include "netmisc.h" NexusSet* NetExpr::nex_input(bool) { cerr << get_fileline() << ": internal error: nex_input not implemented: " << *this << endl; return 0; } NexusSet* NetProc::nex_input(bool) { cerr << get_fileline() << ": internal error: NetProc::nex_input not implemented" << endl; return 0; } NexusSet* NetEBinary::nex_input(bool rem_out) { NexusSet*result = left_->nex_input(rem_out); NexusSet*tmp = right_->nex_input(rem_out); result->add(*tmp); delete tmp; return result; } NexusSet* NetEConcat::nex_input(bool rem_out) { if (parms_[0] == NULL) return NULL; NexusSet*result = parms_[0]->nex_input(rem_out); for (unsigned idx = 1 ; idx < parms_.count() ; idx += 1) { if (parms_[idx] == NULL) { delete result; return NULL; } NexusSet*tmp = parms_[idx]->nex_input(rem_out); result->add(*tmp); delete tmp; } return result; } NexusSet* NetEAccess::nex_input(bool) { return new NexusSet; } /* * A constant has not inputs, so always return an empty set. */ NexusSet* NetEConst::nex_input(bool) { return new NexusSet; } NexusSet* NetECReal::nex_input(bool) { return new NexusSet; } NexusSet* NetEEvent::nex_input(bool) { return new NexusSet; } NexusSet* NetENetenum::nex_input(bool) { return new NexusSet; } NexusSet* NetEScope::nex_input(bool) { return new NexusSet; } NexusSet* NetESelect::nex_input(bool rem_out) { NexusSet*result = base_? base_->nex_input(rem_out) : new NexusSet(); NexusSet*tmp = expr_->nex_input(rem_out); if (tmp == NULL) { delete result; return NULL; } result->add(*tmp); delete tmp; /* See the comment for NetESignal below. */ if (base_ && warn_sens_entire_vec) { cerr << get_fileline() << ": warning: @* is sensitive to all " "bits in '" << *expr_ << "'." << endl; } return result; } /* * The $fread, etc. system functions can have NULL arguments. */ NexusSet* NetESFunc::nex_input(bool rem_out) { if (parms_.size() == 0) return new NexusSet; NexusSet*result; if (parms_[0]) result = parms_[0]->nex_input(rem_out); else result = new NexusSet; for (unsigned idx = 1 ; idx < parms_.size() ; idx += 1) { if (parms_[idx]) { NexusSet*tmp = parms_[idx]->nex_input(rem_out); result->add(*tmp); delete tmp; } } return result; } NexusSet* NetESignal::nex_input(bool rem_out) { /* * This is not what I would expect for the various selects (bit, * part, index, array). This code adds all the bits/array words * instead of building the appropriate select and then using it * as the trigger. Other simulators also add everything. */ NexusSet*result = new NexusSet; /* If we have an array index add it to the sensitivity list. */ if (word_) { NexusSet*tmp; tmp = word_->nex_input(rem_out); result->add(*tmp); delete tmp; if (warn_sens_entire_arr) { cerr << get_fileline() << ": warning: @* is sensitive to all " << net_->array_count() << " words in array '" << name() << "'." << endl; } } for (unsigned idx = 0 ; idx < net_->pin_count() ; idx += 1) result->add(net_->pin(idx).nexus()); return result; } NexusSet* NetETernary::nex_input(bool rem_out) { NexusSet*tmp; NexusSet*result = cond_->nex_input(rem_out); tmp = true_val_->nex_input(rem_out); result->add(*tmp); delete tmp; tmp = false_val_->nex_input(rem_out); result->add(*tmp); delete tmp; return result; } NexusSet* NetEUFunc::nex_input(bool rem_out) { NexusSet*result = new NexusSet; for (unsigned idx = 0 ; idx < parms_.count() ; idx += 1) { NexusSet*tmp = parms_[idx]->nex_input(rem_out); result->add(*tmp); delete tmp; } return result; } NexusSet* NetEUnary::nex_input(bool rem_out) { return expr_->nex_input(rem_out); } NexusSet* NetAssign_::nex_input(bool rem_out) { NexusSet*result = new NexusSet; if (word_) { NexusSet*tmp = word_->nex_input(rem_out); result->add(*tmp); delete tmp; } if (base_) { NexusSet*tmp = base_->nex_input(rem_out); result->add(*tmp); delete tmp; } return result; } NexusSet* NetAssignBase::nex_input(bool rem_out) { NexusSet*result = rval_->nex_input(rem_out); /* It is possible that the lval_ can have nex_input values. In particular, index expressions are statement inputs as well, so should be addressed here. */ for (NetAssign_*cur = lval_ ; cur ; cur = cur->more) { NexusSet*tmp = cur->nex_input(rem_out); result->add(*tmp); delete tmp; } return result; } /* * The nex_input of a begin/end block is the NexusSet of bits that the * block reads from outside the block. That means it is the union of * the nex_input for all the substatements. * * The input set for a sequential set is not exactly the union of the * input sets because there is the possibility of intermediate values, * that don't deserve to be in the input set. To wit: * * begin * t = a + b; * c = ~t; * end * * In this example, "t" should not be in the input set because it is * used by the sequence as a temporary value. */ NexusSet* NetBlock::nex_input(bool rem_out) { if (last_ == 0) return new NexusSet; if (type_ == PARA) { cerr << get_fileline() << ": internal error: Sorry, " << "I don't know how to synthesize fork/join blocks." << endl; return 0; } NetProc*cur = last_->next_; /* This is the accumulated input set. */ NexusSet*result = new NexusSet; /* This is an accumulated output set. */ NexusSet*prev = new NexusSet; do { /* Get the inputs for the current statement. */ NexusSet*tmp = cur->nex_input(rem_out); /* Add the current input set to the accumulated input set. */ if (tmp != 0) result->add(*tmp); delete tmp; /* Add the current outputs to the accumulated output set, so they can be removed from the input set below. */ cur->nex_output(*prev); cur = cur->next_; } while (cur != last_->next_); /* Remove from the input set those bits that are outputs from other statements. They aren't really inputs to the block, just internal intermediate values. */ if (rem_out) result->rem(*prev); return result; } /* * The inputs to a case statement are the inputs to the expression, * the inputs to all the guards, and the inputs to all the guarded * statements. */ NexusSet* NetCase::nex_input(bool rem_out) { NexusSet*result = expr_->nex_input(rem_out); if (result == 0) return 0; for (unsigned idx = 0 ; idx < nitems_ ; idx += 1) { /* Skip cases that have empty statements. */ if (items_[idx].statement == 0) continue; NexusSet*tmp = items_[idx].statement->nex_input(rem_out); assert(tmp); result->add(*tmp); delete tmp; /* Usually, this is the guard expression. The default case is special and is identified by a null guard. The default guard obviously has no input. */ if (items_[idx].guard) { tmp = items_[idx].guard->nex_input(rem_out); assert(tmp); result->add(*tmp); delete tmp; } } return result; } NexusSet* NetCAssign::nex_input(bool) { cerr << get_fileline() << ": internal warning: NetCAssign::nex_input()" << " not implemented." << endl; return new NexusSet; } NexusSet* NetCondit::nex_input(bool rem_out) { NexusSet*result = expr_->nex_input(rem_out); if (if_ != 0) { NexusSet*tmp = if_->nex_input(rem_out); result->add(*tmp); delete tmp; } if (else_ != 0) { NexusSet*tmp = else_->nex_input(rem_out); result->add(*tmp); delete tmp; } return result; } NexusSet* NetForce::nex_input(bool) { cerr << get_fileline() << ": internal warning: NetForce::nex_input()" << " not implemented." << endl; return new NexusSet; } NexusSet* NetForever::nex_input(bool rem_out) { NexusSet*result = statement_->nex_input(rem_out); return result; } /* * The NetPDelay statement is a statement of the form * * #<expr> <statement> * * The nex_input set is the input set of the <statement>. Do *not* * include the input set of the <expr> because it does not affect the * result. The statement can be omitted. */ NexusSet* NetPDelay::nex_input(bool rem_out) { if (statement_ == 0) return 0; NexusSet*result = statement_->nex_input(rem_out); return result; } NexusSet* NetRepeat::nex_input(bool rem_out) { NexusSet*result = statement_->nex_input(rem_out); NexusSet*tmp = expr_->nex_input(rem_out); result->add(*tmp); delete tmp; return result; } /* * The $display, etc. system tasks can have NULL arguments. */ NexusSet* NetSTask::nex_input(bool rem_out) { if (parms_.count() == 0) return new NexusSet; NexusSet*result; if (parms_[0]) result = parms_[0]->nex_input(rem_out); else result = new NexusSet; for (unsigned idx = 1 ; idx < parms_.count() ; idx += 1) { if (parms_[idx]) { NexusSet*tmp = parms_[idx]->nex_input(rem_out); result->add(*tmp); delete tmp; } } return result; } /* * The NetUTask represents a call to a user defined task. There are no * parameters to consider, because the compiler already removed them * and converted them to blocking assignments. */ NexusSet* NetUTask::nex_input(bool) { return new NexusSet; } NexusSet* NetWhile::nex_input(bool rem_out) { NexusSet*result = proc_->nex_input(rem_out); NexusSet*tmp = cond_->nex_input(rem_out); result->add(*tmp); delete tmp; return result; } <commit_msg>Don't include local signals in @* sensitivity list.<commit_after>/* * Copyright (c) 2002-2011 Stephen Williams ([email protected]) * * This source code is free software; you can redistribute it * and/or modify it in source code form 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 "config.h" # include <iostream> # include <cassert> # include <typeinfo> # include "compiler.h" # include "netlist.h" # include "netmisc.h" NexusSet* NetExpr::nex_input(bool) { cerr << get_fileline() << ": internal error: nex_input not implemented: " << *this << endl; return 0; } NexusSet* NetProc::nex_input(bool) { cerr << get_fileline() << ": internal error: NetProc::nex_input not implemented" << endl; return 0; } NexusSet* NetEBinary::nex_input(bool rem_out) { NexusSet*result = left_->nex_input(rem_out); NexusSet*tmp = right_->nex_input(rem_out); result->add(*tmp); delete tmp; return result; } NexusSet* NetEConcat::nex_input(bool rem_out) { if (parms_[0] == NULL) return NULL; NexusSet*result = parms_[0]->nex_input(rem_out); for (unsigned idx = 1 ; idx < parms_.count() ; idx += 1) { if (parms_[idx] == NULL) { delete result; return NULL; } NexusSet*tmp = parms_[idx]->nex_input(rem_out); result->add(*tmp); delete tmp; } return result; } NexusSet* NetEAccess::nex_input(bool) { return new NexusSet; } /* * A constant has not inputs, so always return an empty set. */ NexusSet* NetEConst::nex_input(bool) { return new NexusSet; } NexusSet* NetECReal::nex_input(bool) { return new NexusSet; } NexusSet* NetEEvent::nex_input(bool) { return new NexusSet; } NexusSet* NetENetenum::nex_input(bool) { return new NexusSet; } NexusSet* NetEScope::nex_input(bool) { return new NexusSet; } NexusSet* NetESelect::nex_input(bool rem_out) { NexusSet*result = base_? base_->nex_input(rem_out) : new NexusSet(); NexusSet*tmp = expr_->nex_input(rem_out); if (tmp == NULL) { delete result; return NULL; } result->add(*tmp); delete tmp; /* See the comment for NetESignal below. */ if (base_ && warn_sens_entire_vec) { cerr << get_fileline() << ": warning: @* is sensitive to all " "bits in '" << *expr_ << "'." << endl; } return result; } /* * The $fread, etc. system functions can have NULL arguments. */ NexusSet* NetESFunc::nex_input(bool rem_out) { if (parms_.size() == 0) return new NexusSet; NexusSet*result; if (parms_[0]) result = parms_[0]->nex_input(rem_out); else result = new NexusSet; for (unsigned idx = 1 ; idx < parms_.size() ; idx += 1) { if (parms_[idx]) { NexusSet*tmp = parms_[idx]->nex_input(rem_out); result->add(*tmp); delete tmp; } } return result; } NexusSet* NetESignal::nex_input(bool rem_out) { /* * This is not what I would expect for the various selects (bit, * part, index, array). This code adds all the bits/array words * instead of building the appropriate select and then using it * as the trigger. Other simulators also add everything. */ NexusSet*result = new NexusSet; /* Local signals are not added to the sensitivity list. */ if (net_->local_flag()) return result; /* If we have an array index add it to the sensitivity list. */ if (word_) { NexusSet*tmp; tmp = word_->nex_input(rem_out); result->add(*tmp); delete tmp; if (warn_sens_entire_arr) { cerr << get_fileline() << ": warning: @* is sensitive to all " << net_->array_count() << " words in array '" << name() << "'." << endl; } } for (unsigned idx = 0 ; idx < net_->pin_count() ; idx += 1) result->add(net_->pin(idx).nexus()); return result; } NexusSet* NetETernary::nex_input(bool rem_out) { NexusSet*tmp; NexusSet*result = cond_->nex_input(rem_out); tmp = true_val_->nex_input(rem_out); result->add(*tmp); delete tmp; tmp = false_val_->nex_input(rem_out); result->add(*tmp); delete tmp; return result; } NexusSet* NetEUFunc::nex_input(bool rem_out) { NexusSet*result = new NexusSet; for (unsigned idx = 0 ; idx < parms_.count() ; idx += 1) { NexusSet*tmp = parms_[idx]->nex_input(rem_out); result->add(*tmp); delete tmp; } return result; } NexusSet* NetEUnary::nex_input(bool rem_out) { return expr_->nex_input(rem_out); } NexusSet* NetAssign_::nex_input(bool rem_out) { NexusSet*result = new NexusSet; if (word_) { NexusSet*tmp = word_->nex_input(rem_out); result->add(*tmp); delete tmp; } if (base_) { NexusSet*tmp = base_->nex_input(rem_out); result->add(*tmp); delete tmp; } return result; } NexusSet* NetAssignBase::nex_input(bool rem_out) { NexusSet*result = rval_->nex_input(rem_out); /* It is possible that the lval_ can have nex_input values. In particular, index expressions are statement inputs as well, so should be addressed here. */ for (NetAssign_*cur = lval_ ; cur ; cur = cur->more) { NexusSet*tmp = cur->nex_input(rem_out); result->add(*tmp); delete tmp; } return result; } /* * The nex_input of a begin/end block is the NexusSet of bits that the * block reads from outside the block. That means it is the union of * the nex_input for all the substatements. * * The input set for a sequential set is not exactly the union of the * input sets because there is the possibility of intermediate values, * that don't deserve to be in the input set. To wit: * * begin * t = a + b; * c = ~t; * end * * In this example, "t" should not be in the input set because it is * used by the sequence as a temporary value. */ NexusSet* NetBlock::nex_input(bool rem_out) { if (last_ == 0) return new NexusSet; if (type_ == PARA) { cerr << get_fileline() << ": internal error: Sorry, " << "I don't know how to synthesize fork/join blocks." << endl; return 0; } NetProc*cur = last_->next_; /* This is the accumulated input set. */ NexusSet*result = new NexusSet; /* This is an accumulated output set. */ NexusSet*prev = new NexusSet; do { /* Get the inputs for the current statement. */ NexusSet*tmp = cur->nex_input(rem_out); /* Add the current input set to the accumulated input set. */ if (tmp != 0) result->add(*tmp); delete tmp; /* Add the current outputs to the accumulated output set, so they can be removed from the input set below. */ cur->nex_output(*prev); cur = cur->next_; } while (cur != last_->next_); /* Remove from the input set those bits that are outputs from other statements. They aren't really inputs to the block, just internal intermediate values. */ if (rem_out) result->rem(*prev); return result; } /* * The inputs to a case statement are the inputs to the expression, * the inputs to all the guards, and the inputs to all the guarded * statements. */ NexusSet* NetCase::nex_input(bool rem_out) { NexusSet*result = expr_->nex_input(rem_out); if (result == 0) return 0; for (unsigned idx = 0 ; idx < nitems_ ; idx += 1) { /* Skip cases that have empty statements. */ if (items_[idx].statement == 0) continue; NexusSet*tmp = items_[idx].statement->nex_input(rem_out); assert(tmp); result->add(*tmp); delete tmp; /* Usually, this is the guard expression. The default case is special and is identified by a null guard. The default guard obviously has no input. */ if (items_[idx].guard) { tmp = items_[idx].guard->nex_input(rem_out); assert(tmp); result->add(*tmp); delete tmp; } } return result; } NexusSet* NetCAssign::nex_input(bool) { cerr << get_fileline() << ": internal warning: NetCAssign::nex_input()" << " not implemented." << endl; return new NexusSet; } NexusSet* NetCondit::nex_input(bool rem_out) { NexusSet*result = expr_->nex_input(rem_out); if (if_ != 0) { NexusSet*tmp = if_->nex_input(rem_out); result->add(*tmp); delete tmp; } if (else_ != 0) { NexusSet*tmp = else_->nex_input(rem_out); result->add(*tmp); delete tmp; } return result; } NexusSet* NetForce::nex_input(bool) { cerr << get_fileline() << ": internal warning: NetForce::nex_input()" << " not implemented." << endl; return new NexusSet; } NexusSet* NetForever::nex_input(bool rem_out) { NexusSet*result = statement_->nex_input(rem_out); return result; } /* * The NetPDelay statement is a statement of the form * * #<expr> <statement> * * The nex_input set is the input set of the <statement>. Do *not* * include the input set of the <expr> because it does not affect the * result. The statement can be omitted. */ NexusSet* NetPDelay::nex_input(bool rem_out) { if (statement_ == 0) return 0; NexusSet*result = statement_->nex_input(rem_out); return result; } NexusSet* NetRepeat::nex_input(bool rem_out) { NexusSet*result = statement_->nex_input(rem_out); NexusSet*tmp = expr_->nex_input(rem_out); result->add(*tmp); delete tmp; return result; } /* * The $display, etc. system tasks can have NULL arguments. */ NexusSet* NetSTask::nex_input(bool rem_out) { if (parms_.count() == 0) return new NexusSet; NexusSet*result; if (parms_[0]) result = parms_[0]->nex_input(rem_out); else result = new NexusSet; for (unsigned idx = 1 ; idx < parms_.count() ; idx += 1) { if (parms_[idx]) { NexusSet*tmp = parms_[idx]->nex_input(rem_out); result->add(*tmp); delete tmp; } } return result; } /* * The NetUTask represents a call to a user defined task. There are no * parameters to consider, because the compiler already removed them * and converted them to blocking assignments. */ NexusSet* NetUTask::nex_input(bool) { return new NexusSet; } NexusSet* NetWhile::nex_input(bool rem_out) { NexusSet*result = proc_->nex_input(rem_out); NexusSet*tmp = cond_->nex_input(rem_out); result->add(*tmp); delete tmp; return result; } <|endoftext|>
<commit_before>#include "modinterface.h" #ifndef MODIFACE_ROBOBO #define MODIFACE_ROBOBO class ModuleInterface { public: ModuleInterface(std::tr1::unordered_map<std::string, Server>* serverMap, std::tr1::unordered_map<std::string, Module>* moduleMap); void sendToServer(std::string server, std::string rawLine); std::tr1::unordered_map<std::string, std::string> getServerData(std::string server); void callHook(std::string server, std::vector<std::string> parsedLine); void callHookOut(std::string server, std::vector<std::string> parsedLine); private: std::tr1::unordered_map<std::string, Server>* servers; std::tr1::unordered_map<std::string, Module>* modules; std::string parseNickFromHost(std::string host); bool charIsNumeric(char number); bool isChanType(char chanPrefix); }; ModuleInterface::ModuleInterface(std::tr1::unordered_map<std::string, Server>* serverMap, std::tr1::unordered_map<std::string, Module>* moduleMap) { servers = serverMap; modules = moduleMap; } void ModuleInterface::sendToServer(std::string server, std::string rawLine) { for (std::tr1::unordered_map<std::string, Server>::iterator serverIter = servers->begin(); serverIter != servers->end(); serverIter++) { if (serverIter->first == server) serverIter->second.sendLine(rawLine); } } std::tr1::unordered_map<std::string, std::string> ModuleInterface::getServerData(std::string server) { for (std::tr1::unordered_map<std::string, Server>::iterator serverIter = servers->begin(); serverIter != servers->end(); serverIter++) { if (serverIter->first == server) return serverIter->second.getInfo(); } } void ModuleInterface::callHook(std::string server, std::vector<std::string> parsedLine) { if (parsedLine[1] == "PRIVMSG") { if (parsedLine[3][0] == (char)1) { if (parsedLine[3][parsedLine.size()-1] == (char)1) parsedLine[3] = parsedLine[3].substr(1, parsedLine[3].size()-2); else parsedLine[3] = parsedLine[3].substr(1); if (isChanType(parsedLine[2][0])) { for (std::tr1::unordered_map<std::string, Module>::iterator modIter = modules->begin(); modIter != modules->end(); modIter++) modIter->second.onChannelCTCP(server, parsedLine[2], '0', parseNickFromHost(parsedLine[0]), parsedLine[3]); } else if (isChanType(parsedLine[2][1]) { for (std::tr1::unordered_map<std::string, Module>::iterator modIter = modules->begin(); modIter != modules->end(); modIter++) modIter->second.onChannelCTCP(server, parsedLine[2].substr(1), parsedLine[2][0], parseNickFromHost(parsedLine[0]), parsedLine[3]); } else { for (std::tr1::unordered_map<std::string, Module>::iterator modIter = modules->begin(); modIter != modules->end(); modIter++) modIter->second.onUserCTCP(server, parseNickFromHost(parsedLine[0]), parsedLine[3]); } } else { if (isChanType(parsedLine[2][0])) { for (std::tr1::unordered_map<std::string, Module>::iterator modIter = modules->begin(); modIter != modules->end(); modIter++) modIter->second.onChannelMsg(server, parsedLine[2], '0', parseNickFromHost(parsedLine[0]), parsedLine[3]); } else if (isChanType(parsedLine[2][1])) { for (std::tr1::unordered_map<std::string, Module>::iterator modIter = modules->begin(); modIter != modules->end(); modIter++) modIter->second.onChannelMsg(server, parsedLine[2].substr(1), parsedLine[2][0], parseNickFromHost(parsedLine[0]), parsedLine[3]); } else { for (std::tr1::unordered_map<std::string, Module>::iterator modIter = modules->begin(); modIter != modules->end(); modIter++) modIter->second.onUserMsg(server, parseNickFromHost(parsedLine[0]), parsedLine[3]); } } } else if (parsedLine[1] == "NOTICE") { if (parsedLine[3][0] == (char)1) { if (parsedLine[3][parsedLine.size()-1] == (char)1) parsedLine[3] = parsedLine[3].substr(1, parsedLine[3].size()-2); else parsedLine[3] = parsedLine[3].substr(1); if (isChanType(parsedLine[2][0])) { for (std::tr1::unordered_map<std::string, Module>::iterator modIter = modules->begin(); modIter != modules->end(); modIter++) modIter->second.onChannelCTCPReply(server, parsedLine[2], '0', parseNickFromHost(parsedLine[0]), parsedLine[3]); } else if (isChanType(parsedLine[2][1])) { for (std::tr1::unordered_map<std::string, Module>::iterator modIter = modules->begin(); modIter != modules->end(); modIter++) modIter->second.onChannelCTCPReply(server, parsedLine[2].substr(1), parsedLine[2][0], parseNickFromHost(parsedLine[0]), parsedLine[3]); } else { for (std::tr1::unordered_map<std::string, Module>::iterator modIter = modules->begin(); modIter != modules->end(); modIter++) modIter->second.onUserCTCPReply(server, parseNickFromHost(parsedLine[0]), parsedLine[3]); } } else { if (isChanType(parsedLine[2][0])) { for (std::tr1::unordered_map<std::string, Module>::iterator modIter = modules->begin(); modIter != modules->end(); modIter++) modIter->second.onChannelNotice(server, parsedLine[2], '0', parseNickFromHost(parsedLine[0]), parsedLine[3]); } else if (isChanType(parsedLine[2][1])) { for (std::tr1::unordered_map<std::string, Module>::iterator modIter = modules->begin(); modIter != modules->end(); modIter++) modIter->second.onChannelNotice(server, parsedLine[2].substr(1), parsedLine[2][0], parseNickFromHost(parsedLine[0]), parsedLine[3]); } else { for (std::tr1::unordered_map<std::string, Module>::iterator modIter = modules->begin(); modIter != modules->end(); modIter++) modIter->second.onUserNotice(server, parseNickFromHost(parsedLine[0]), parsedLine[3]); } } } else if (parsedLine[1] == "JOIN") { if (parsedLine[0][0] == ':') parsedLine[0] = parsedLine[0].substr(1); for (std::tr1::unordered_map<std::string, Module>::iterator modIter = modules->begin(); modIter != modules->end(); modIter++) modIter->second.onChannelJoin(server, parsedLine[2], parsedLine[0]); } else if (parsedLine[1] == "PART") { if (parsedLine[0][0] == ':') parsedLine[0] = parsedLine[0].substr(1); for (std::tr1::unordered_map<std::string, Module>::iterator modIter = modules->begin(); modIter != modules->end(); modIter++) modIter->second.onChannelPart(server, parsedLine[2], parsedLine[0], parsedLine[3]); } else if (parsedLine[1] == "QUIT") { if (parsedLine[0][0] == ':') parsedLine[0] = parsedLine[0].substr(1); for (std::tr1::unordered_map<std::string, Module>::iterator modIter = modules->begin(); modIter != modules->end(); modIter++) modIter->second.onUserQuit(server, parsedLine[0], parsedLine[2]); } else if (parsedLine[1] == "KICK") { for (std::tr1::unordered_map<std::string, Module>::iterator modIter = modules->begin(); modIter != modules->end(); modIter++) modIter->second.onChannelKick(server, parsedLine[2], parseNickFromHost(parsedLine[0]), parsedLine[3], parsedLine[4]); } else if (parsedLine[1].size() == 3 && charIsNumeric(parsedLine[1][0]) && charIsNumeric(parsedLine[1][1]) && charIsNumeric(parsedLine[1][2])) { for (std::tr1::unordered_map<std::string, Module>::iterator modIter = modules->begin(); modIter != modules->end(); modIter++) modIter->second.onNumeric(server, parsedLine[1], parsedLine); } else { for (std::tr1::unordered_map<std::string, Module>::iterator modIter = modules->begin(); modIter != modules->end(); modIter++) modIter->second.onOtherData(server, parsedLine); } } void ModuleInterface::callHookOut(std::string server, std::vector<std::string> parsedLine) { } std::string ModuleInterface::parseNickFromHost(std::string host) { if (host[0] == ':') host = host.substr(1); return host.substr(0, host.find_first_of('!')); } bool ModuleInterface::charIsNumeric(char number) { if (number == '0' || number == '1' || number == '2' || number == '3' || number == '4' || number == '5' || number == '6' || number == '7' || number == '8' || number == '9') return true; return false; } bool ModuleInterface::isChanType(char chanPrefix) { std::vector<char> prefixes; for (std::tr1::unordered_map<std::string, Server>::iterator serverIter = servers->begin(); serverIter != servers->end(); serverIter++) { prefixes = serverIter->second.getChanTypes(); for (unsigned int i = 0; i < prefixes.size(); i++) { if (chanPrefix == prefixes[i]) return true; } } return false; } #endif<commit_msg>Add all out hooks to the interface<commit_after>#include "modinterface.h" #ifndef MODIFACE_ROBOBO #define MODIFACE_ROBOBO class ModuleInterface { public: ModuleInterface(std::tr1::unordered_map<std::string, Server>* serverMap, std::tr1::unordered_map<std::string, Module>* moduleMap); void sendToServer(std::string server, std::string rawLine); std::tr1::unordered_map<std::string, std::string> getServerData(std::string server); void callHook(std::string server, std::vector<std::string> parsedLine); void callHookOut(std::string server, std::vector<std::string> parsedLine); private: std::tr1::unordered_map<std::string, Server>* servers; std::tr1::unordered_map<std::string, Module>* modules; std::string parseNickFromHost(std::string host); bool charIsNumeric(char number); bool isChanType(char chanPrefix); }; ModuleInterface::ModuleInterface(std::tr1::unordered_map<std::string, Server>* serverMap, std::tr1::unordered_map<std::string, Module>* moduleMap) { servers = serverMap; modules = moduleMap; } void ModuleInterface::sendToServer(std::string server, std::string rawLine) { for (std::tr1::unordered_map<std::string, Server>::iterator serverIter = servers->begin(); serverIter != servers->end(); serverIter++) { if (serverIter->first == server) serverIter->second.sendLine(rawLine); } } std::tr1::unordered_map<std::string, std::string> ModuleInterface::getServerData(std::string server) { for (std::tr1::unordered_map<std::string, Server>::iterator serverIter = servers->begin(); serverIter != servers->end(); serverIter++) { if (serverIter->first == server) return serverIter->second.getInfo(); } } void ModuleInterface::callHook(std::string server, std::vector<std::string> parsedLine) { if (parsedLine[1] == "PRIVMSG") { if (parsedLine[3][0] == (char)1) { // CTCP if (parsedLine[3][parsedLine.size()-1] == (char)1) // trim CTCP characters parsedLine[3] = parsedLine[3].substr(1, parsedLine[3].size()-2); else parsedLine[3] = parsedLine[3].substr(1); if (isChanType(parsedLine[2][0])) { for (std::tr1::unordered_map<std::string, Module>::iterator modIter = modules->begin(); modIter != modules->end(); modIter++) modIter->second.onChannelCTCP(server, parsedLine[2], '0', parseNickFromHost(parsedLine[0]), parsedLine[3]); } else if (isChanType(parsedLine[2][1]) { for (std::tr1::unordered_map<std::string, Module>::iterator modIter = modules->begin(); modIter != modules->end(); modIter++) modIter->second.onChannelCTCP(server, parsedLine[2].substr(1), parsedLine[2][0], parseNickFromHost(parsedLine[0]), parsedLine[3]); } else { for (std::tr1::unordered_map<std::string, Module>::iterator modIter = modules->begin(); modIter != modules->end(); modIter++) modIter->second.onUserCTCP(server, parseNickFromHost(parsedLine[0]), parsedLine[3]); } } else { if (isChanType(parsedLine[2][0])) { for (std::tr1::unordered_map<std::string, Module>::iterator modIter = modules->begin(); modIter != modules->end(); modIter++) modIter->second.onChannelMsg(server, parsedLine[2], '0', parseNickFromHost(parsedLine[0]), parsedLine[3]); } else if (isChanType(parsedLine[2][1])) { for (std::tr1::unordered_map<std::string, Module>::iterator modIter = modules->begin(); modIter != modules->end(); modIter++) modIter->second.onChannelMsg(server, parsedLine[2].substr(1), parsedLine[2][0], parseNickFromHost(parsedLine[0]), parsedLine[3]); } else { for (std::tr1::unordered_map<std::string, Module>::iterator modIter = modules->begin(); modIter != modules->end(); modIter++) modIter->second.onUserMsg(server, parseNickFromHost(parsedLine[0]), parsedLine[3]); } } } else if (parsedLine[1] == "NOTICE") { if (parsedLine[3][0] == (char)1) { if (parsedLine[3][parsedLine.size()-1] == (char)1) parsedLine[3] = parsedLine[3].substr(1, parsedLine[3].size()-2); else parsedLine[3] = parsedLine[3].substr(1); if (isChanType(parsedLine[2][0])) { for (std::tr1::unordered_map<std::string, Module>::iterator modIter = modules->begin(); modIter != modules->end(); modIter++) modIter->second.onChannelCTCPReply(server, parsedLine[2], '0', parseNickFromHost(parsedLine[0]), parsedLine[3]); } else if (isChanType(parsedLine[2][1])) { for (std::tr1::unordered_map<std::string, Module>::iterator modIter = modules->begin(); modIter != modules->end(); modIter++) modIter->second.onChannelCTCPReply(server, parsedLine[2].substr(1), parsedLine[2][0], parseNickFromHost(parsedLine[0]), parsedLine[3]); } else { for (std::tr1::unordered_map<std::string, Module>::iterator modIter = modules->begin(); modIter != modules->end(); modIter++) modIter->second.onUserCTCPReply(server, parseNickFromHost(parsedLine[0]), parsedLine[3]); } } else { if (isChanType(parsedLine[2][0])) { for (std::tr1::unordered_map<std::string, Module>::iterator modIter = modules->begin(); modIter != modules->end(); modIter++) modIter->second.onChannelNotice(server, parsedLine[2], '0', parseNickFromHost(parsedLine[0]), parsedLine[3]); } else if (isChanType(parsedLine[2][1])) { for (std::tr1::unordered_map<std::string, Module>::iterator modIter = modules->begin(); modIter != modules->end(); modIter++) modIter->second.onChannelNotice(server, parsedLine[2].substr(1), parsedLine[2][0], parseNickFromHost(parsedLine[0]), parsedLine[3]); } else { for (std::tr1::unordered_map<std::string, Module>::iterator modIter = modules->begin(); modIter != modules->end(); modIter++) modIter->second.onUserNotice(server, parseNickFromHost(parsedLine[0]), parsedLine[3]); } } } else if (parsedLine[1] == "JOIN") { if (parsedLine[0][0] == ':') parsedLine[0] = parsedLine[0].substr(1); for (std::tr1::unordered_map<std::string, Module>::iterator modIter = modules->begin(); modIter != modules->end(); modIter++) modIter->second.onChannelJoin(server, parsedLine[2], parsedLine[0]); } else if (parsedLine[1] == "PART") { if (parsedLine[0][0] == ':') parsedLine[0] = parsedLine[0].substr(1); for (std::tr1::unordered_map<std::string, Module>::iterator modIter = modules->begin(); modIter != modules->end(); modIter++) modIter->second.onChannelPart(server, parsedLine[2], parsedLine[0], parsedLine[3]); } else if (parsedLine[1] == "QUIT") { if (parsedLine[0][0] == ':') parsedLine[0] = parsedLine[0].substr(1); for (std::tr1::unordered_map<std::string, Module>::iterator modIter = modules->begin(); modIter != modules->end(); modIter++) modIter->second.onUserQuit(server, parsedLine[0], parsedLine[2]); } else if (parsedLine[1] == "KICK") { for (std::tr1::unordered_map<std::string, Module>::iterator modIter = modules->begin(); modIter != modules->end(); modIter++) modIter->second.onChannelKick(server, parsedLine[2], parseNickFromHost(parsedLine[0]), parsedLine[3], parsedLine[4]); } else if (parsedLine[1].size() == 3 && charIsNumeric(parsedLine[1][0]) && charIsNumeric(parsedLine[1][1]) && charIsNumeric(parsedLine[1][2])) { for (std::tr1::unordered_map<std::string, Module>::iterator modIter = modules->begin(); modIter != modules->end(); modIter++) modIter->second.onNumeric(server, parsedLine[1], parsedLine); } else { for (std::tr1::unordered_map<std::string, Module>::iterator modIter = modules->begin(); modIter != modules->end(); modIter++) modIter->second.onOtherData(server, parsedLine); } } void ModuleInterface::callHookOut(std::string server, std::vector<std::string> parsedLine) { if (parsedLine[1] == "PRIVMSG") { if (parsedLine[3][0] == (char)1) { // CTCP if (parsedLine[3][parsedLine.size()-1] == (char)1) // trim CTCP characters parsedLine[3] = parsedLine[3].substr(1,parsedLine.size()-2); else parsedLine[3] = parsedLine[3].substr(1); if (isChanType(parsedLine[2][0])) { for (std::tr1::unordered_map<std::string, Module>::iterator modIter = modules->begin(); modIter != modules->end(); modIter++) modIter->second.onOutChannelCTCP(server, parsedLine[2], '0', parsedLine[3]); } else if (isChanType(parsedLine[2][1])) { for (std::tr1::unordered_map<std::string, Module>::iterator modIter = modules->begin(); modIter != modules->end(); modIter++) modIter->second.onOutChannelCTCP(server, parsedLine[2].substr(1), parsedLine[2][0], parsedLine[3]); } else { for (std::tr1::unordered_map<std::string, Module>::iterator modIter = modules->begin(); modIter != modules->end(); modIter++) modIter->second.onOutUserCTCP(server, parsedLine[2], parsedLine[3]); } } else { if (isChanType(parsedLine[2][0])) { for (std::tr1::unordered_map<std::string, Module>::iterator modIter = modules->begin(); modIter != modules->end(); modIter++) modIter->second.onOutChannelMessage(server, parsedLine[2], '0', parsedLine[3]); } else if (isChanType(parsedLine[2][1])) { for (std::tr1::unordered_map<std::string, Module>::iterator modIter = modules->begin(); modIter != modules->end(); modIter++) modIter->second.onOutChannelMessage(server, parsedLine[2].substr(1), parsedLine[2][0], parsedLine[3]); } else { for (std::tr1::unordered_map<std::string, Module>::iterator modIter = modules->begin(); modIter != modules->end(); modIter++) modIter->second.onOutUserMessage(server, parsedLine[2], parsedLine[3]); } } } else if (parsedLine[1] == "NOTICE") { if (parsedLine[3][0] == (char)1) { // CTCP reply if (parsedLine[3][parsedLine.size()-1] == (char)1) // trim both characters parsedLine[3] = parsedLine[3].substr(1, parsedLine.size()-2); else parsedLine[3] = parsedLine[3].substr(1); if (isChanType(parsedLine[2][0])) { for (std::tr1::unordered_map<std::string, Module>::iterator modIter = modules->begin(); modIter != modules->end(); modIter++) modIter->second.onOutChannelCTCPReply(server, parsedLine[2], '0', parsedLine[3]); } else if (isChanType(parsedLine[2][1])) { for (std::tr1::unordered_map<std::string, Module>::iterator modIter = modules->begin(); modIter != modules->end(); modIter++) modIter->second.onOutChannelCTCPReply(server, parsedLine[2].substr(1), parsedLine[2][0], parsedLine[3]); } else { for (std::tr1::unordered_map<std::string, Module>::iterator modIter = modules->begin(); modIter != modules->end(); modIter++) modIter->second.onOutUserCTCPReply(server, parsedLine[2], parsedLine[3]); } } else { if (isChanType(parsedLine[2][0])) { for (std::tr1::unordered_map<std::string, Module>::iterator modIter = modules->begin(); modIter != modules->end(); modIter++) modIter->second.onOutChannelNotice(server, parsedLine[2], '0', parsedLine[3]); } else if (isChanType(parsedLine[2][1])) { for (std::tr1::unordered_map<std::string, Module>::iterator modIter = modules->begin(); modIter != modules->end(); modIter++) modIter->second.onOutChannelNotice(server, parsedLine[2].substr(1), parsedLine[2][0], parsedLine[3]); } else { for (std::tr1::unordered_map<std::string, Module>::iterator modIter = modules->begin(); modIter != modules->end(); modIter++) modIter->second.onOutUserNotice(server, parsedLine[2], parsedLine[3]); } } } else { for (std::tr1::unordered_map<std::string, Module>::iterator modIter = modules->begin(); modIter != modules->end(); modIter++) modIter->second.onOutOtherData(server, parsedLine); } } std::string ModuleInterface::parseNickFromHost(std::string host) { if (host[0] == ':') host = host.substr(1); return host.substr(0, host.find_first_of('!')); } bool ModuleInterface::charIsNumeric(char number) { if (number == '0' || number == '1' || number == '2' || number == '3' || number == '4' || number == '5' || number == '6' || number == '7' || number == '8' || number == '9') return true; return false; } bool ModuleInterface::isChanType(char chanPrefix) { std::vector<char> prefixes; for (std::tr1::unordered_map<std::string, Server>::iterator serverIter = servers->begin(); serverIter != servers->end(); serverIter++) { prefixes = serverIter->second.getChanTypes(); for (unsigned int i = 0; i < prefixes.size(); i++) { if (chanPrefix == prefixes[i]) return true; } } return false; } #endif<|endoftext|>
<commit_before><commit_msg>RSComputer: Replace inefficient HashSet iteration by deque<commit_after><|endoftext|>
<commit_before>/*------------------------------------------------------------------------- * drawElements Quality Program Tester Core * ---------------------------------------- * * Copyright 2014 The Android Open Source Project * * 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. * *//*! * \file * \brief X11 utilities. *//*--------------------------------------------------------------------*/ #include "tcuX11.hpp" #include "gluRenderConfig.hpp" #include "deMemory.h" #include <X11/Xutil.h> namespace tcu { namespace x11 { enum { DEFAULT_WINDOW_WIDTH = 400, DEFAULT_WINDOW_HEIGHT = 300 }; EventState::EventState (void) : m_quit(false) { } EventState::~EventState (void) { } void EventState::setQuitFlag (bool quit) { de::ScopedLock lock(m_mutex); m_quit = quit; } bool EventState::getQuitFlag (void) { de::ScopedLock lock(m_mutex); return m_quit; } Display::Display (EventState& eventState, const char* name) : m_eventState (eventState) , m_display (DE_NULL) , m_deleteAtom (DE_NULL) { m_display = XOpenDisplay((char*)name); // Won't modify argument string. if (!m_display) throw ResourceError("Failed to open display", name, __FILE__, __LINE__); m_deleteAtom = XInternAtom(m_display, "WM_DELETE_WINDOW", False); } Display::~Display (void) { XCloseDisplay(m_display); } void Display::processEvents (void) { XEvent event; while (XPending(m_display)) { XNextEvent(m_display, &event); // \todo [2010-10-27 pyry] Handle ConfigureNotify? if (event.type == ClientMessage && (unsigned)event.xclient.data.l[0] == m_deleteAtom) m_eventState.setQuitFlag(true); } } bool Display::getVisualInfo (VisualID visualID, XVisualInfo& dst) { XVisualInfo query; query.visualid = visualID; int numVisuals = 0; XVisualInfo* response = XGetVisualInfo(m_display, VisualIDMask, &query, &numVisuals); bool succ = false; if (response != DE_NULL) { if (numVisuals > 0) // should be 1, but you never know... { dst = response[0]; succ = true; } XFree(response); } return succ; } ::Visual* Display::getVisual (VisualID visualID) { XVisualInfo info; if (getVisualInfo(visualID, info)) return info.visual; return DE_NULL; } Window::Window (Display& display, int width, int height, ::Visual* visual) : m_display (display) , m_colormap (None) , m_window (None) , m_visible (false) { XSetWindowAttributes swa; ::Display* const dpy = m_display.getXDisplay(); ::Window root = DefaultRootWindow(dpy); unsigned long mask = CWBorderPixel | CWEventMask; // If redirect is enabled, window size can't be guaranteed and it is up to // the window manager to decide whether to honor sizing requests. However, // overriding that causes window to appear as an overlay, which causes // other issues, so this is disabled by default. const bool overrideRedirect = false; if (overrideRedirect) { mask |= CWOverrideRedirect; swa.override_redirect = true; } if (visual == DE_NULL) visual = CopyFromParent; else { XVisualInfo info = XVisualInfo(); bool succ = display.getVisualInfo(XVisualIDFromVisual(visual), info); TCU_CHECK_INTERNAL(succ); root = RootWindow(dpy, info.screen); m_colormap = XCreateColormap(dpy, root, visual, AllocNone); swa.colormap = m_colormap; mask |= CWColormap; } swa.border_pixel = 0; swa.event_mask = ExposureMask|KeyPressMask|KeyReleaseMask|StructureNotifyMask; if (width == glu::RenderConfig::DONT_CARE) width = DEFAULT_WINDOW_WIDTH; if (height == glu::RenderConfig::DONT_CARE) height = DEFAULT_WINDOW_HEIGHT; m_window = XCreateWindow(dpy, root, 0, 0, width, height, 0, CopyFromParent, InputOutput, visual, mask, &swa); TCU_CHECK(m_window); Atom deleteAtom = m_display.getDeleteAtom(); XSetWMProtocols(dpy, m_window, &deleteAtom, 1); } void Window::setVisibility (bool visible) { ::Display* dpy = m_display.getXDisplay(); int eventType = None; XEvent event; if (visible == m_visible) return; if (visible) { XMapWindow(dpy, m_window); eventType = MapNotify; } else { XUnmapWindow(dpy, m_window); eventType = UnmapNotify; } // We are only interested about exposure/structure notify events, not user input XSelectInput(dpy, m_window, ExposureMask | StructureNotifyMask); do { XNextEvent(dpy, &event); } while (event.type != eventType); m_visible = visible; } void Window::getDimensions (int* width, int* height) const { int x, y; ::Window root; unsigned width_, height_, borderWidth, depth; XGetGeometry(m_display.getXDisplay(), m_window, &root, &x, &y, &width_, &height_, &borderWidth, &depth); if (width != DE_NULL) *width = static_cast<int>(width_); if (height != DE_NULL) *height = static_cast<int>(height_); } void Window::setDimensions (int width, int height) { const unsigned int mask = CWWidth | CWHeight; XWindowChanges changes; changes.width = width; changes.height = height; XConfigureWindow(m_display.getXDisplay(), m_window, mask, &changes); } void Window::processEvents (void) { // A bit of a hack, since we don't really handle all the events. m_display.processEvents(); } Window::~Window (void) { XDestroyWindow(m_display.getXDisplay(), m_window); if (m_colormap != None) XFreeColormap(m_display.getXDisplay(), m_colormap); } } // x11 } // tcu <commit_msg>x11: Fix deadlock am: 5e863331b2 am: 7d0ad652ff<commit_after>/*------------------------------------------------------------------------- * drawElements Quality Program Tester Core * ---------------------------------------- * * Copyright 2014 The Android Open Source Project * * 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. * *//*! * \file * \brief X11 utilities. *//*--------------------------------------------------------------------*/ #include "tcuX11.hpp" #include "gluRenderConfig.hpp" #include "deMemory.h" #include <X11/Xutil.h> namespace tcu { namespace x11 { enum { DEFAULT_WINDOW_WIDTH = 400, DEFAULT_WINDOW_HEIGHT = 300 }; EventState::EventState (void) : m_quit(false) { } EventState::~EventState (void) { } void EventState::setQuitFlag (bool quit) { de::ScopedLock lock(m_mutex); m_quit = quit; } bool EventState::getQuitFlag (void) { de::ScopedLock lock(m_mutex); return m_quit; } Display::Display (EventState& eventState, const char* name) : m_eventState (eventState) , m_display (DE_NULL) , m_deleteAtom (DE_NULL) { m_display = XOpenDisplay((char*)name); // Won't modify argument string. if (!m_display) throw ResourceError("Failed to open display", name, __FILE__, __LINE__); m_deleteAtom = XInternAtom(m_display, "WM_DELETE_WINDOW", False); } Display::~Display (void) { XCloseDisplay(m_display); } void Display::processEvents (void) { XEvent event; while (XPending(m_display)) { XNextEvent(m_display, &event); // \todo [2010-10-27 pyry] Handle ConfigureNotify? if (event.type == ClientMessage && (unsigned)event.xclient.data.l[0] == m_deleteAtom) m_eventState.setQuitFlag(true); } } bool Display::getVisualInfo (VisualID visualID, XVisualInfo& dst) { XVisualInfo query; query.visualid = visualID; int numVisuals = 0; XVisualInfo* response = XGetVisualInfo(m_display, VisualIDMask, &query, &numVisuals); bool succ = false; if (response != DE_NULL) { if (numVisuals > 0) // should be 1, but you never know... { dst = response[0]; succ = true; } XFree(response); } return succ; } ::Visual* Display::getVisual (VisualID visualID) { XVisualInfo info; if (getVisualInfo(visualID, info)) return info.visual; return DE_NULL; } Window::Window (Display& display, int width, int height, ::Visual* visual) : m_display (display) , m_colormap (None) , m_window (None) , m_visible (false) { XSetWindowAttributes swa; ::Display* const dpy = m_display.getXDisplay(); ::Window root = DefaultRootWindow(dpy); unsigned long mask = CWBorderPixel | CWEventMask; // If redirect is enabled, window size can't be guaranteed and it is up to // the window manager to decide whether to honor sizing requests. However, // overriding that causes window to appear as an overlay, which causes // other issues, so this is disabled by default. const bool overrideRedirect = false; if (overrideRedirect) { mask |= CWOverrideRedirect; swa.override_redirect = true; } if (visual == DE_NULL) visual = CopyFromParent; else { XVisualInfo info = XVisualInfo(); bool succ = display.getVisualInfo(XVisualIDFromVisual(visual), info); TCU_CHECK_INTERNAL(succ); root = RootWindow(dpy, info.screen); m_colormap = XCreateColormap(dpy, root, visual, AllocNone); swa.colormap = m_colormap; mask |= CWColormap; } swa.border_pixel = 0; swa.event_mask = ExposureMask|KeyPressMask|KeyReleaseMask|StructureNotifyMask; if (width == glu::RenderConfig::DONT_CARE) width = DEFAULT_WINDOW_WIDTH; if (height == glu::RenderConfig::DONT_CARE) height = DEFAULT_WINDOW_HEIGHT; m_window = XCreateWindow(dpy, root, 0, 0, width, height, 0, CopyFromParent, InputOutput, visual, mask, &swa); TCU_CHECK(m_window); Atom deleteAtom = m_display.getDeleteAtom(); XSetWMProtocols(dpy, m_window, &deleteAtom, 1); } void Window::setVisibility (bool visible) { ::Display* dpy = m_display.getXDisplay(); int eventType = None; XEvent event; if (visible == m_visible) return; if (visible) { XMapWindow(dpy, m_window); eventType = MapNotify; } else { XUnmapWindow(dpy, m_window); eventType = UnmapNotify; } // We are only interested about exposure/structure notify events, not user input XSelectInput(dpy, m_window, ExposureMask | StructureNotifyMask); do { XWindowEvent(dpy, m_window, ExposureMask | StructureNotifyMask, &event); } while (event.type != eventType); m_visible = visible; } void Window::getDimensions (int* width, int* height) const { int x, y; ::Window root; unsigned width_, height_, borderWidth, depth; XGetGeometry(m_display.getXDisplay(), m_window, &root, &x, &y, &width_, &height_, &borderWidth, &depth); if (width != DE_NULL) *width = static_cast<int>(width_); if (height != DE_NULL) *height = static_cast<int>(height_); } void Window::setDimensions (int width, int height) { const unsigned int mask = CWWidth | CWHeight; XWindowChanges changes; changes.width = width; changes.height = height; XConfigureWindow(m_display.getXDisplay(), m_window, mask, &changes); } void Window::processEvents (void) { // A bit of a hack, since we don't really handle all the events. m_display.processEvents(); } Window::~Window (void) { XDestroyWindow(m_display.getXDisplay(), m_window); if (m_colormap != None) XFreeColormap(m_display.getXDisplay(), m_colormap); } } // x11 } // tcu <|endoftext|>
<commit_before>// Application.cpp #include "Header.h" //================================================================================================== wxIMPLEMENT_APP( Application ); //================================================================================================== Application::Application( void ) { rubiksCube = 0; rotationHistoryIndex = -1; } //================================================================================================== /*virtual*/ Application::~Application( void ) { delete rubiksCube; } //================================================================================================== /*virtual*/ bool Application::OnInit( void ) { if( !wxApp::OnInit() ) return false; wxInitAllImageHandlers(); // There is never a solution to the following scenerio. Can this happen in the 3x3x3 case? // I was able to get it to happen in the 4x4x4 case. Using tri-cycles, one can shift the // entire set of four forward or backward, as a whole, with wrapping, by multiples of 2 only. // It follows that if the two quads are mis-aligned by an odd number of rotations, they cannot // come into alignment using just tri-cycles. If there was a way to swap two opposite edges or // corners, then it may be possible to finish with tri-cycles. // // To answer this question, yes, there is a way. Chris Hardwick gives the sequence // {2r, 2U, 2r, 2U, 2u, 2r, 2u}, which will swap to opposite edge peices. Tri-cycles // can then be used to solve the final layer. TriCycleSolver::TriCycleSequence triCycleSequence; int quadCorners[4] = { 1, 2, 3, 0 }; // Corners int quadEdges[4] = { 0, 1, 2, 3 }; // Edges bool result = TriCycleSolver::FindSmallestTriCycleSequenceThatOrdersQuadTheSame( quadCorners, quadEdges, triCycleSequence ); Frame* frame = new Frame( 0, wxDefaultPosition, wxSize( 500, 500 ) ); frame->Show(); return true; } //================================================================================================== /*virtual*/ int Application::OnExit( void ) { return 0; } //================================================================================================== void Application::RotationHistoryAppend( const RubiksCube::Rotation& rotation ) { // We always append to the history at our current location, which means // forfeiting any rotations that are in our future. if( rotationHistoryIndex != -1 ) rotationHistory.resize( rotationHistoryIndex ); else rotationHistoryIndex = 0; rotationHistory.push_back( rotation ); rotationHistoryIndex++; } //================================================================================================== bool Application::RotationHistoryGoForward( RubiksCube::Rotation& rotation ) { if( !RotationHistoryCanGoForward() ) return false; rotation = rotationHistory[ rotationHistoryIndex++ ]; rotation.angle *= -1.0; return true; } //================================================================================================== bool Application::RotationHistoryGoBackward( RubiksCube::Rotation& rotation ) { if( !RotationHistoryCanGoBackward() ) return false; rotation = rotationHistory[ --rotationHistoryIndex ]; return true; } //================================================================================================== bool Application::RotationHistoryCanGoForward( void ) { if( rotationHistoryIndex == -1 || rotationHistoryIndex == rotationHistory.size() ) return false; return true; } //================================================================================================== bool Application::RotationHistoryCanGoBackward( void ) { if( rotationHistoryIndex == -1 || rotationHistoryIndex == 0 ) return false; return true; } //================================================================================================== void Application::RotationHistoryClear( void ) { rotationHistory.clear(); rotationHistoryIndex = -1; } // Application.cpp<commit_msg>clarify<commit_after>// Application.cpp #include "Header.h" //================================================================================================== wxIMPLEMENT_APP( Application ); //================================================================================================== Application::Application( void ) { rubiksCube = 0; rotationHistoryIndex = -1; } //================================================================================================== /*virtual*/ Application::~Application( void ) { delete rubiksCube; } //================================================================================================== /*virtual*/ bool Application::OnInit( void ) { if( !wxApp::OnInit() ) return false; wxInitAllImageHandlers(); // There is never a solution to the following scenerio. Can this happen in the 3x3x3 case? // I was able to get it to happen in the 4x4x4 case. Using tri-cycles, one can shift the // entire set of four forward or backward, as a whole, with wrapping, by multiples of 2 only. // It follows that if the two quads are mis-aligned by an odd number of rotations, they cannot // come into alignment using just tri-cycles. If there was a way to swap two opposite edges or // corners, then it may be possible to finish with tri-cycles. // // To answer this question, yes, there is a way. Chris Hardwick gives the sequence // {2r, 2U, 2r, 2U, 2u, 2r, 2u}, which will swap to opposite edge peices. Tri-cycles // can then be used to solve the final layer. Also, I don't believe this misalignment // can happen in the 3x3x3 case. It can, however, in the 4x4x4 case. TriCycleSolver::TriCycleSequence triCycleSequence; int quadCorners[4] = { 1, 2, 3, 0 }; // Corners int quadEdges[4] = { 0, 1, 2, 3 }; // Edges bool result = TriCycleSolver::FindSmallestTriCycleSequenceThatOrdersQuadTheSame( quadCorners, quadEdges, triCycleSequence ); Frame* frame = new Frame( 0, wxDefaultPosition, wxSize( 500, 500 ) ); frame->Show(); return true; } //================================================================================================== /*virtual*/ int Application::OnExit( void ) { return 0; } //================================================================================================== void Application::RotationHistoryAppend( const RubiksCube::Rotation& rotation ) { // We always append to the history at our current location, which means // forfeiting any rotations that are in our future. if( rotationHistoryIndex != -1 ) rotationHistory.resize( rotationHistoryIndex ); else rotationHistoryIndex = 0; rotationHistory.push_back( rotation ); rotationHistoryIndex++; } //================================================================================================== bool Application::RotationHistoryGoForward( RubiksCube::Rotation& rotation ) { if( !RotationHistoryCanGoForward() ) return false; rotation = rotationHistory[ rotationHistoryIndex++ ]; rotation.angle *= -1.0; return true; } //================================================================================================== bool Application::RotationHistoryGoBackward( RubiksCube::Rotation& rotation ) { if( !RotationHistoryCanGoBackward() ) return false; rotation = rotationHistory[ --rotationHistoryIndex ]; return true; } //================================================================================================== bool Application::RotationHistoryCanGoForward( void ) { if( rotationHistoryIndex == -1 || rotationHistoryIndex == rotationHistory.size() ) return false; return true; } //================================================================================================== bool Application::RotationHistoryCanGoBackward( void ) { if( rotationHistoryIndex == -1 || rotationHistoryIndex == 0 ) return false; return true; } //================================================================================================== void Application::RotationHistoryClear( void ) { rotationHistory.clear(); rotationHistoryIndex = -1; } // Application.cpp<|endoftext|>
<commit_before>#include <FileUtils.hpp> #include <algorithm> #include <dirent.h> #include <sstream> #include <stdexcept> #include <stdio.h> #include <stdlib.h> #include <iostream> void FileUtils::readFolder(const char* folderPath, std::vector<std::string>& files) { DIR *dir; struct dirent *ent; // Try opening folder if ((dir = opendir(folderPath)) != NULL) { fprintf(stdout, " Opening directory [%s]\n", folderPath); // Save all true directory names into a vector of strings while ((ent = readdir(dir)) != NULL) { // Ignore . and .. as valid folder names std::string name = std::string(ent->d_name); if (name.compare(".") != 0 && name.compare("..") != 0) { files.push_back(std::string(ent->d_name)); } } closedir(dir); // Sort alphabetically vector of folder names std::sort(files.begin(), files.end()); fprintf(stdout, " Found [%d] files\n", (int) files.size()); } else { std::stringstream ss; ss << "Could not open directory [" << folderPath << "]"; throw std::runtime_error(ss.str()); } } // -------------------------------------------------------------------------- void FileUtils::saveFeatures(const std::string &filename, const std::vector<cv::KeyPoint>& keypoints, const cv::Mat& descriptors) { printf("-- Saving feature descriptors to [%s] using OpenCV FileStorage\n", filename.c_str()); cv::FileStorage fs(filename.c_str(), cv::FileStorage::WRITE); if (!fs.isOpened()) { std::stringstream ss; ss << "Could not open file [" << filename << "]"; throw std::runtime_error(ss.str()); } fs << "TotalKeypoints" << descriptors.rows; fs << "DescriptorSize" << descriptors.cols; // Recall this is in Bytes fs << "DescriptorType" << descriptors.type(); // CV_8U = 0 for binary descriptors fs << "KeyPoints" << "{"; for (int i = 0; i < descriptors.rows; i++) { cv::KeyPoint k = keypoints[i]; fs << "KeyPoint" << "{"; fs << "x" << k.pt.x; fs << "y" << k.pt.y; fs << "size" << k.size; fs << "angle" << k.angle; fs << "response" << k.response; fs << "octave" << k.octave; fs << "descriptor" << descriptors.row(i); fs << "}"; } fs << "}"; // End of structure node fs.release(); } // -------------------------------------------------------------------------- void FileUtils::loadFeatures(const std::string& filename, std::vector<cv::KeyPoint>& keypoints, cv::Mat& descriptors) { CV_Error(CV_StsNotImplemented, "Not yet implemented method"); printf( "-- Loading feature descriptors from [%s] using OpenCV FileStorage\n", filename.c_str()); cv::FileStorage fs(filename.c_str(), cv::FileStorage::READ); if (fs.isOpened() == false) { std::stringstream ss; ss << "Could not open file [" << filename << "]"; throw std::runtime_error(ss.str()); } int rows, cols, type; rows = (int) fs["TotalKeypoints"]; cols = (int) fs["DescriptorSize"]; type = (int) fs["DescriptorType"]; descriptors.create(rows, cols, type); keypoints.reserve(rows); cv::FileNode keypointsSequence = fs["KeyPoints"]; int idx = 0; for (cv::FileNodeIterator it = keypointsSequence.begin(); it != keypointsSequence.end(); it++, idx++) { keypoints.push_back( cv::KeyPoint((float) (*it)["x"], (float) (*it)["y"], (float) (*it)["size"], (float) (*it)["angle"], (float) (*it)["response"], (int) (*it)["octave"])); cv::Mat descriptor; (*it)["descriptor"] >> descriptor; descriptor.copyTo(descriptors.row(idx)); std::cout << descriptors.row(idx) << std::endl; getchar(); } fs.release(); } <commit_msg>Common/FileUtils.cpp * Moved out status message to the calling function. * Changed keypoints list to a sequence. * In function loadFeatures, deleted not implemented cv_error.<commit_after>#include <FileUtils.hpp> #include <algorithm> #include <dirent.h> #include <sstream> #include <stdexcept> #include <stdio.h> #include <stdlib.h> #include <iostream> void FileUtils::readFolder(const char* folderPath, std::vector<std::string>& files) { DIR *dir; struct dirent *ent; // Try opening folder if ((dir = opendir(folderPath)) != NULL) { fprintf(stdout, " Opening directory [%s]\n", folderPath); // Save all true directory names into a vector of strings while ((ent = readdir(dir)) != NULL) { // Ignore . and .. as valid folder names std::string name = std::string(ent->d_name); if (name.compare(".") != 0 && name.compare("..") != 0) { files.push_back(std::string(ent->d_name)); } } closedir(dir); // Sort alphabetically vector of folder names std::sort(files.begin(), files.end()); fprintf(stdout, " Found [%d] files\n", (int) files.size()); } else { std::stringstream ss; ss << "Could not open directory [" << folderPath << "]"; throw std::runtime_error(ss.str()); } } // -------------------------------------------------------------------------- void FileUtils::saveFeatures(const std::string &filename, const std::vector<cv::KeyPoint>& keypoints, const cv::Mat& descriptors) { cv::FileStorage fs(filename.c_str(), cv::FileStorage::WRITE); if (!fs.isOpened()) { std::stringstream ss; ss << "Could not open file [" << filename << "]"; throw std::runtime_error(ss.str()); } fs << "TotalKeypoints" << descriptors.rows; fs << "DescriptorSize" << descriptors.cols; // Recall this is in Bytes fs << "DescriptorType" << descriptors.type(); // CV_8U = 0 for binary descriptors fs << "KeyPoints" << "["; for (int i = 0; i < descriptors.rows; i++) { cv::KeyPoint k = keypoints[i]; fs << "KeyPoint" << "{"; fs << "x" << k.pt.x; fs << "y" << k.pt.y; fs << "size" << k.size; fs << "angle" << k.angle; fs << "response" << k.response; fs << "octave" << k.octave; fs << "descriptor" << descriptors.row(i); fs << "}"; } fs << "]"; // End of structure node fs.release(); } // -------------------------------------------------------------------------- void FileUtils::loadFeatures(const std::string& filename, std::vector<cv::KeyPoint>& keypoints, cv::Mat& descriptors) { printf( "-- Loading feature descriptors from [%s] using OpenCV FileStorage\n", filename.c_str()); cv::FileStorage fs(filename.c_str(), cv::FileStorage::READ); if (fs.isOpened() == false) { std::stringstream ss; ss << "Could not open file [" << filename << "]"; throw std::runtime_error(ss.str()); } int rows, cols, type; rows = (int) fs["TotalKeypoints"]; cols = (int) fs["DescriptorSize"]; type = (int) fs["DescriptorType"]; descriptors.create(rows, cols, type); keypoints.reserve(rows); cv::FileNode keypointsSequence = fs["KeyPoints"]; int idx = 0; for (cv::FileNodeIterator it = keypointsSequence.begin(); it != keypointsSequence.end(); it++, idx++) { keypoints.push_back( cv::KeyPoint((float) (*it)["x"], (float) (*it)["y"], (float) (*it)["size"], (float) (*it)["angle"], (float) (*it)["response"], (int) (*it)["octave"])); cv::Mat descriptor; (*it)["descriptor"] >> descriptor; descriptor.copyTo(descriptors.row(idx)); std::cout << descriptors.row(idx) << std::endl; getchar(); } fs.release(); } <|endoftext|>
<commit_before>/* qgvdial is a cross platform Google Voice Dialer Copyright (C) 2009-2013 Yuvraaj Kelkar 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 Contact: [email protected] */ #include "IMainWindow.h" #include "Lib.h" #include "ContactsModel.h" IMainWindow::IMainWindow(QObject *parent) : QObject(parent) , db(this) , gvApi(true, this) , oContacts(this) , oInbox(this) , oPhones(this) , m_loginTask(NULL) , m_contactsModel(NULL) , m_inboxModel(NULL) , m_acctFactory(createPhoneAccountFactory (this)) { qRegisterMetaType<ContactInfo>("ContactInfo"); connect(&gvApi, SIGNAL(twoStepAuthentication(AsyncTaskToken*)), this, SLOT(onTFARequest(AsyncTaskToken*))); }//IMainWindow::IMainWindow void IMainWindow::init() { connect (qApp, SIGNAL(aboutToQuit()), this, SLOT(onQuit())); }//IMainWindow::init void IMainWindow::onQuit() { QList<QNetworkCookie> cookies = gvApi.getAllCookies (); db.saveCookies (cookies); db.deinit (); }//IMainWindow::onQuit void IMainWindow::onInitDone() { QString user, pass; do { db.init (Lib::ref().getDbDir()); QList<QNetworkCookie> cookies; if (db.loadCookies (cookies)) { gvApi.setAllCookies (cookies); } if (db.usernameIsCached () && db.getUserPass (user,pass)) { // Begin login beginLogin (user, pass); } else { // Ask the user for login credentials uiRequestLoginDetails(); } //! Begin the work to identify all phone accounts AsyncTaskToken *task = new AsyncTaskToken(this); if (NULL == task) { Q_WARN("Failed to allocate task token for account identification"); break; } connect(task, SIGNAL(completed()), this, SLOT(onAccountsIdentified())); if (!m_acctFactory->identifyAll (task)) { delete task; } } while (0); }//IMainWindow::onInitDone void IMainWindow::beginLogin(const QString &user, const QString &pass) { bool ok; do { if (m_loginTask) { Q_WARN("Login is in progress"); break; } // Begin logon m_loginTask = new AsyncTaskToken(this); if (NULL == m_loginTask) { Q_WARN("Failed to allocate token"); break; } ok = connect(m_loginTask, SIGNAL(completed()), this, SLOT(loginCompleted())); Q_ASSERT(ok); m_loginTask->inParams["user"] = user; m_loginTask->inParams["pass"] = pass; Q_DEBUG("Login using user ") << user; if (!gvApi.login (m_loginTask)) { Q_WARN("Failed to log in"); break; } m_user = user; m_pass = pass; uiSetUserPass(false); } while (0); }//IMainWindow::beginLogin void IMainWindow::onTFARequest(AsyncTaskToken *task) { Q_ASSERT(m_loginTask == task); uiRequestTFALoginDetails(task); }//IMainWindow::onTFARequest void IMainWindow::resumeTFAAuth(void *ctx, int pin, bool useAlt) { Q_ASSERT(m_loginTask == ctx); if (useAlt) { gvApi.resumeTFAAltLogin (m_loginTask); } else { m_loginTask->inParams["user_pin"] = QString::number (pin); gvApi.resumeTFALogin (m_loginTask); } }//IMainWindow::resumeTFAAuth void IMainWindow::loginCompleted() { QString strAppPw; AsyncTaskToken *task = (AsyncTaskToken *) QObject::sender (); Q_ASSERT(m_loginTask == task); m_loginTask = NULL; do { if (ATTS_SUCCESS == task->status) { Q_DEBUG("Login successful"); db.putUserPass (m_user, m_pass); if (task->inParams.contains ("user_pin")) { db.setTFAFlag (true); // Open UI to ask for application specific password uiRequestApplicationPassword(); } else if (db.getAppPass (strAppPw)) { onUiGotApplicationPassword (strAppPw); } else { // Assume that the GV password is the contacts password. // If this is not true then the login will fail and the // application password will be requested. onUiGotApplicationPassword (m_pass); } QDateTime after; db.getLatestInboxEntry (after); oInbox.refresh ("all", after); oPhones.refresh (); } else if (ATTS_NW_ERROR == task->status) { Q_WARN("Login failed because of network error"); uiSetUserPass (true); uiRequestLoginDetails(); } else if (ATTS_USER_CANCEL == task->status) { Q_WARN("User canceled login"); uiSetUserPass (true); uiRequestLoginDetails(); db.clearCookies (); db.clearTFAFlag (); } else { Q_WARN(QString("Login failed: %1").arg (task->errorString)); m_pass.clear (); uiSetUserPass(true); uiRequestLoginDetails(); db.clearCookies (); db.clearTFAFlag (); } } while (0); uiLoginDone (task->status, task->errorString); task->deleteLater (); }//IMainWindow::loginCompleted void IMainWindow::onUiGotApplicationPassword(const QString &appPw) { Q_DEBUG("User gave app specific password"); // Begin contacts login oContacts.login (m_user, appPw); }//IMainWindow::onUiGotApplicationPassword void IMainWindow::onUserLogoutRequest() { AsyncTaskToken *task = new AsyncTaskToken(this); connect(task, SIGNAL(completed()), this, SLOT(onLogoutDone())); gvApi.logout (task); }//IMainWindow::onUserLogoutRequest void IMainWindow::onLogoutDone() { AsyncTaskToken *task = (AsyncTaskToken *) QObject::sender (); uiSetUserPass (true); onUserLogoutDone(); task->deleteLater (); }//IMainWindow::onLogoutDone void IMainWindow::onAccountsIdentified() { AsyncTaskToken *task = (AsyncTaskToken *) QObject::sender (); task->deleteLater (); }//IMainWindow::onAccountsIdentified <commit_msg>compile warnings<commit_after>/* qgvdial is a cross platform Google Voice Dialer Copyright (C) 2009-2013 Yuvraaj Kelkar 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 Contact: [email protected] */ #include "IMainWindow.h" #include "Lib.h" #include "ContactsModel.h" IMainWindow::IMainWindow(QObject *parent) : QObject(parent) , db(this) , gvApi(true, this) , oContacts(this) , oInbox(this) , oPhones(this) , m_loginTask(NULL) , m_contactsModel(NULL) , m_inboxModel(NULL) , m_acctFactory(createPhoneAccountFactory (this)) { qRegisterMetaType<ContactInfo>("ContactInfo"); connect(&gvApi, SIGNAL(twoStepAuthentication(AsyncTaskToken*)), this, SLOT(onTFARequest(AsyncTaskToken*))); }//IMainWindow::IMainWindow void IMainWindow::init() { connect (qApp, SIGNAL(aboutToQuit()), this, SLOT(onQuit())); }//IMainWindow::init void IMainWindow::onQuit() { QList<QNetworkCookie> cookies = gvApi.getAllCookies (); db.saveCookies (cookies); db.deinit (); }//IMainWindow::onQuit void IMainWindow::onInitDone() { QString user, pass; do { db.init (Lib::ref().getDbDir()); QList<QNetworkCookie> cookies; if (db.loadCookies (cookies)) { gvApi.setAllCookies (cookies); } if (db.usernameIsCached () && db.getUserPass (user,pass)) { // Begin login beginLogin (user, pass); } else { // Ask the user for login credentials uiRequestLoginDetails(); } //! Begin the work to identify all phone accounts AsyncTaskToken *task = new AsyncTaskToken(this); if (NULL == task) { Q_WARN("Failed to allocate task token for account identification"); break; } connect(task, SIGNAL(completed()), this, SLOT(onAccountsIdentified())); if (!m_acctFactory->identifyAll (task)) { delete task; } } while (0); }//IMainWindow::onInitDone void IMainWindow::beginLogin(const QString &user, const QString &pass) { bool ok; do { if (m_loginTask) { Q_WARN("Login is in progress"); break; } // Begin logon m_loginTask = new AsyncTaskToken(this); if (NULL == m_loginTask) { Q_WARN("Failed to allocate token"); break; } ok = connect(m_loginTask, SIGNAL(completed()), this, SLOT(loginCompleted())); Q_ASSERT(ok); if (!ok) { Q_CRIT("Failed to connect signal"); } m_loginTask->inParams["user"] = user; m_loginTask->inParams["pass"] = pass; Q_DEBUG("Login using user ") << user; if (!gvApi.login (m_loginTask)) { Q_WARN("Failed to log in"); break; } m_user = user; m_pass = pass; uiSetUserPass(false); } while (0); }//IMainWindow::beginLogin void IMainWindow::onTFARequest(AsyncTaskToken *task) { Q_ASSERT(m_loginTask == task); uiRequestTFALoginDetails(task); }//IMainWindow::onTFARequest void IMainWindow::resumeTFAAuth(void *ctx, int pin, bool useAlt) { Q_ASSERT(m_loginTask == ctx); if (m_loginTask != ctx) { Q_CRIT("Context mismatch!!"); } if (useAlt) { gvApi.resumeTFAAltLogin (m_loginTask); } else { m_loginTask->inParams["user_pin"] = QString::number (pin); gvApi.resumeTFALogin (m_loginTask); } }//IMainWindow::resumeTFAAuth void IMainWindow::loginCompleted() { QString strAppPw; AsyncTaskToken *task = (AsyncTaskToken *) QObject::sender (); Q_ASSERT(m_loginTask == task); m_loginTask = NULL; do { if (ATTS_SUCCESS == task->status) { Q_DEBUG("Login successful"); db.putUserPass (m_user, m_pass); if (task->inParams.contains ("user_pin")) { db.setTFAFlag (true); // Open UI to ask for application specific password uiRequestApplicationPassword(); } else if (db.getAppPass (strAppPw)) { onUiGotApplicationPassword (strAppPw); } else { // Assume that the GV password is the contacts password. // If this is not true then the login will fail and the // application password will be requested. onUiGotApplicationPassword (m_pass); } QDateTime after; db.getLatestInboxEntry (after); oInbox.refresh ("all", after); oPhones.refresh (); } else if (ATTS_NW_ERROR == task->status) { Q_WARN("Login failed because of network error"); uiSetUserPass (true); uiRequestLoginDetails(); } else if (ATTS_USER_CANCEL == task->status) { Q_WARN("User canceled login"); uiSetUserPass (true); uiRequestLoginDetails(); db.clearCookies (); db.clearTFAFlag (); } else { Q_WARN(QString("Login failed: %1").arg (task->errorString)); m_pass.clear (); uiSetUserPass(true); uiRequestLoginDetails(); db.clearCookies (); db.clearTFAFlag (); } } while (0); uiLoginDone (task->status, task->errorString); task->deleteLater (); }//IMainWindow::loginCompleted void IMainWindow::onUiGotApplicationPassword(const QString &appPw) { Q_DEBUG("User gave app specific password"); // Begin contacts login oContacts.login (m_user, appPw); }//IMainWindow::onUiGotApplicationPassword void IMainWindow::onUserLogoutRequest() { AsyncTaskToken *task = new AsyncTaskToken(this); connect(task, SIGNAL(completed()), this, SLOT(onLogoutDone())); gvApi.logout (task); }//IMainWindow::onUserLogoutRequest void IMainWindow::onLogoutDone() { AsyncTaskToken *task = (AsyncTaskToken *) QObject::sender (); uiSetUserPass (true); onUserLogoutDone(); task->deleteLater (); }//IMainWindow::onLogoutDone void IMainWindow::onAccountsIdentified() { AsyncTaskToken *task = (AsyncTaskToken *) QObject::sender (); task->deleteLater (); }//IMainWindow::onAccountsIdentified <|endoftext|>
<commit_before>#include "glog/logging.h" #include "gtest/gtest.h" #include "quantities/astronomy.hpp" #include "quantities/BIPM.hpp" #include "quantities/constants.hpp" #include "quantities/dimensionless.hpp" #include "quantities/elementary_functions.hpp" #include "quantities/quantities.hpp" #include "quantities/si.hpp" #include "quantities/uk.hpp" #include "testing_utilities/algebra.hpp" #include "testing_utilities/almost_equals.hpp" #include "testing_utilities/explicit_operators.hpp" #include "testing_utilities/numerics.hpp" using principia::astronomy::EarthMass; using principia::astronomy::JulianYear; using principia::astronomy::JupiterMass; using principia::astronomy::LightYear; using principia::astronomy::LunarDistance; using principia::astronomy::Parsec; using principia::astronomy::SolarMass; using principia::constants::ElectronMass; using principia::constants::GravitationalConstant; using principia::constants::SpeedOfLight; using principia::constants::StandardGravity; using principia::constants::VacuumPermeability; using principia::constants::VacuumPermittivity; using principia::quantities::Abs; using principia::quantities::Cos; using principia::quantities::Dimensionless; using principia::quantities::Exp; using principia::quantities::Log; using principia::quantities::Log10; using principia::quantities::Log2; using principia::quantities::Mass; using principia::quantities::Product; using principia::quantities::Sin; using principia::quantities::Speed; using principia::quantities::Sqrt; using principia::si::Ampere; using principia::si::AstronomicalUnit; using principia::si::Candela; using principia::si::Cycle; using principia::si::Day; using principia::si::Degree; using principia::si::Hour; using principia::si::Kelvin; using principia::si::Kilogram; using principia::si::Mega; using principia::si::Metre; using principia::si::Mole; using principia::si::Radian; using principia::si::Second; using principia::si::Steradian; using principia::testing_utilities::AbsoluteError; using principia::testing_utilities::AlmostEquals; using principia::testing_utilities::RelativeError; using principia::testing_utilities::Times; using principia::uk::Foot; using principia::uk::Furlong; using principia::uk::Mile; using principia::uk::Rood; using testing::Lt; namespace principia { namespace geometry { class QuantitiesTest : public testing::Test { protected: }; TEST_F(QuantitiesTest, AbsoluteValue) { EXPECT_EQ(Abs(-1729), Dimensionless(1729)); EXPECT_EQ(Abs(1729), Dimensionless(1729)); } TEST_F(QuantitiesTest, DimensionlessComparisons) { testing_utilities::TestOrder(Dimensionless(0), Dimensionless(1)); testing_utilities::TestOrder(Dimensionless(-1), Dimensionless(0)); testing_utilities::TestOrder(-e, e); testing_utilities::TestOrder(Dimensionless(3), π); testing_utilities::TestOrder(Dimensionless(42), Dimensionless(1729)); } TEST_F(QuantitiesTest, DimensionfulComparisons) { testing_utilities::TestOrder(EarthMass, JupiterMass); testing_utilities::TestOrder(LightYear, Parsec); testing_utilities::TestOrder(-SpeedOfLight, SpeedOfLight); testing_utilities::TestOrder(SpeedOfLight * Day, LightYear); } TEST_F(QuantitiesTest, DimensionlessOperations) { Dimensionless const zero = 0; Dimensionless const one = 1; Dimensionless const taxi = 1729; Dimensionless const answer = 42; Dimensionless const heegner = 163; testing_utilities::TestField( zero, one, taxi, 4 * π / 3, heegner, answer, -e, 2); } TEST_F(QuantitiesTest, DimensionlfulOperations) { Dimensionless const zero = 0; Dimensionless const one = 1; Dimensionless const taxi = 1729; testing_utilities::TestVectorSpace( 0 * Metre / Second, SpeedOfLight, 88 * Mile / Hour, -340.29 * Metre / Second, zero, one, -2 * π, taxi, 2); // Dimensionful multiplication is a tensor product, see [Tao 2012]. testing_utilities::TestBilinearMap( Times<Product<Mass, Speed>, Mass, Speed>, SolarMass, ElectronMass, SpeedOfLight, 1 * Furlong / JulianYear, -e, 2); } TEST_F(QuantitiesTest, DimensionlessExponentiation) { Dimensionless const number = π - 42; Dimensionless positivePowers = 1; Dimensionless negativePowers = 1; EXPECT_EQ(Dimensionless(1), number.Pow<0>()); for (int i = 1; i < 10; ++i) { positivePowers *= number; negativePowers /= number; EXPECT_THAT(number.Pow(i), AlmostEquals(positivePowers, i)); EXPECT_THAT(number.Pow(-i), AlmostEquals(negativePowers, i)); } } // The Greek letters cause a warning when stringified by the macros, because // apparently Visual Studio doesn't encode strings in UTF-8 by default. #pragma warning(disable: 4566) TEST_F(QuantitiesTest, Formatting) { auto const allTheUnits = 1 * Metre * Kilogram * Second * Ampere * Kelvin / (Mole * Candela * Cycle * Radian * Steradian); std::string const expected = std::string("1e+000 m kg s A K mol^-1") + " cd^-1 cycle^-1 rad^-1 sr^-1"; std::string const actual = ToString(allTheUnits, 0); EXPECT_EQ(expected, actual); std::string π16 = "3.1415926535897931e+000"; EXPECT_EQ(ToString(π), π16); } TEST_F(QuantitiesTest, PhysicalConstants) { // By definition. EXPECT_THAT(1 / SpeedOfLight.Pow<2>(), AlmostEquals(VacuumPermittivity * VacuumPermeability, 2)); // The Keplerian approximation for the mass of the Sun // is fairly accurate. EXPECT_THAT(RelativeError( 4 * π.Pow<2>() * AstronomicalUnit.Pow<3>() / (GravitationalConstant * JulianYear.Pow<2>()), SolarMass), Lt(4E-5)); EXPECT_THAT(RelativeError(1 * Parsec, 3.26156 * LightYear), Lt(2E-6)); // The Keplerian approximation for the mass of the Earth // is pretty bad, but the error is still only 1%. EXPECT_THAT(RelativeError( 4 * π.Pow<2>() * LunarDistance.Pow<3>() / (GravitationalConstant * (27.321582 * Day).Pow<2>()), EarthMass), Lt(1E-2)); EXPECT_THAT(RelativeError(1 * SolarMass, 1047 * JupiterMass), Lt(4E-4)); // Delambre & Méchain. EXPECT_THAT(RelativeError( GravitationalConstant * EarthMass / (40 * Mega(Metre) / (2 * π)).Pow<2>(), StandardGravity), Lt(4E-3)); // Talleyrand. EXPECT_THAT(RelativeError(π * Sqrt(1 * Metre / StandardGravity), 1 * Second), Lt(4E-3)); } #pragma warning(default: 4566) TEST_F(QuantitiesTest, TrigonometricFunctions) { EXPECT_EQ(Cos(0 * Degree), 1); EXPECT_EQ(Sin(0 * Degree), 0); EXPECT_THAT(AbsoluteError(Cos(90 * Degree), 0), Lt(1E-16)); EXPECT_EQ(Sin(90 * Degree), 1); EXPECT_EQ(Cos(180 * Degree), -1); EXPECT_THAT(AbsoluteError(Sin(180 * Degree), 0), Lt(1E-15)); EXPECT_THAT(AbsoluteError(Cos(-90 * Degree), 0), Lt(1E-16)); EXPECT_EQ(Sin(-90 * Degree), -1); for (int k = 1; k < 360; ++k) { // Don't test for multiples of 90 degrees as zeros lead to horrible // conditioning. if (k % 90 != 0) { EXPECT_THAT(Cos((90 - k) * Degree), AlmostEquals(Sin(k * Degree), 50)); EXPECT_THAT(Sin(k * Degree) / Cos(k * Degree), AlmostEquals(Tan(k * Degree), 2)); EXPECT_THAT(((k + 179) % 360 - 179) * Degree, AlmostEquals(ArcTan(Sin(k * Degree), Cos(k * Degree)), 80)); EXPECT_THAT(((k + 179) % 360 - 179) * Degree, AlmostEquals(ArcTan(Sin(k * Degree) * AstronomicalUnit, Cos(k * Degree) * AstronomicalUnit), 80)); EXPECT_THAT(Cos(ArcCos(Cos(k * Degree))), AlmostEquals(Cos(k * Degree), 10)); EXPECT_THAT(Sin(ArcSin(Sin(k * Degree))), AlmostEquals(Sin(k * Degree), 1)); } } // Horribly conditioned near 0, so not in the loop above. EXPECT_EQ(Tan(ArcTan(Tan(-42 * Degree))), Tan(-42 * Degree)); } TEST_F(QuantitiesTest, HyperbolicFunctions) { EXPECT_EQ(Sinh(0 * Radian), 0); EXPECT_EQ(Cosh(0 * Radian), 1); EXPECT_EQ(Tanh(0 * Radian), 0); // Limits: EXPECT_EQ(Sinh(20 * Radian), Cosh(20 * Radian)); EXPECT_EQ(Tanh(20 * Radian), 1); EXPECT_EQ(Sinh(-20 * Radian), -Cosh(-20 * Radian)); EXPECT_EQ(Tanh(-20 * Radian), -1); EXPECT_EQ(Sinh(2 * Radian) / Cosh(2 * Radian), Tanh(2 * Radian)); EXPECT_THAT(ArcSinh(Sinh(-10 * Degree)), AlmostEquals(-10 * Degree, 2)); EXPECT_THAT(ArcCosh(Cosh(-10 * Degree)), AlmostEquals(10 * Degree, 20)); EXPECT_THAT(ArcTanh(Tanh(-10 * Degree)), AlmostEquals(-10 * Degree, 1)); } TEST_F(QuantitiesTest, ExpLogAndSqrt) { EXPECT_EQ(Exp(1), e); EXPECT_THAT(Exp(Log(4.2) + Log(1.729)), AlmostEquals(4.2 * 1.729, 1)); EXPECT_EQ(Exp(Log(2) * Log2(1.729)), 1.729); EXPECT_EQ(Exp(Log(10) * Log10(1.729)), 1.729); EXPECT_THAT(Exp(Log(2) / 2), AlmostEquals(Sqrt(2), 1)); EXPECT_EQ(Exp(Log(Rood / Foot.Pow<2>()) / 2) * Foot, Sqrt(Rood)); } } // namespace geometry } // namespace principia <commit_msg>Lint errors<commit_after>#include <string> #include "glog/logging.h" #include "gtest/gtest.h" #include "quantities/astronomy.hpp" #include "quantities/BIPM.hpp" #include "quantities/constants.hpp" #include "quantities/dimensionless.hpp" #include "quantities/elementary_functions.hpp" #include "quantities/quantities.hpp" #include "quantities/si.hpp" #include "quantities/uk.hpp" #include "testing_utilities/algebra.hpp" #include "testing_utilities/almost_equals.hpp" #include "testing_utilities/explicit_operators.hpp" #include "testing_utilities/numerics.hpp" using principia::astronomy::EarthMass; using principia::astronomy::JulianYear; using principia::astronomy::JupiterMass; using principia::astronomy::LightYear; using principia::astronomy::LunarDistance; using principia::astronomy::Parsec; using principia::astronomy::SolarMass; using principia::constants::ElectronMass; using principia::constants::GravitationalConstant; using principia::constants::SpeedOfLight; using principia::constants::StandardGravity; using principia::constants::VacuumPermeability; using principia::constants::VacuumPermittivity; using principia::quantities::Abs; using principia::quantities::Cos; using principia::quantities::Dimensionless; using principia::quantities::Exp; using principia::quantities::Log; using principia::quantities::Log10; using principia::quantities::Log2; using principia::quantities::Mass; using principia::quantities::Product; using principia::quantities::Sin; using principia::quantities::Speed; using principia::quantities::Sqrt; using principia::si::Ampere; using principia::si::AstronomicalUnit; using principia::si::Candela; using principia::si::Cycle; using principia::si::Day; using principia::si::Degree; using principia::si::Hour; using principia::si::Kelvin; using principia::si::Kilogram; using principia::si::Mega; using principia::si::Metre; using principia::si::Mole; using principia::si::Radian; using principia::si::Second; using principia::si::Steradian; using principia::testing_utilities::AbsoluteError; using principia::testing_utilities::AlmostEquals; using principia::testing_utilities::RelativeError; using principia::testing_utilities::Times; using principia::uk::Foot; using principia::uk::Furlong; using principia::uk::Mile; using principia::uk::Rood; using testing::Lt; namespace principia { namespace geometry { class QuantitiesTest : public testing::Test { protected: }; TEST_F(QuantitiesTest, AbsoluteValue) { EXPECT_EQ(Abs(-1729), Dimensionless(1729)); EXPECT_EQ(Abs(1729), Dimensionless(1729)); } TEST_F(QuantitiesTest, DimensionlessComparisons) { testing_utilities::TestOrder(Dimensionless(0), Dimensionless(1)); testing_utilities::TestOrder(Dimensionless(-1), Dimensionless(0)); testing_utilities::TestOrder(-e, e); testing_utilities::TestOrder(Dimensionless(3), π); testing_utilities::TestOrder(Dimensionless(42), Dimensionless(1729)); } TEST_F(QuantitiesTest, DimensionfulComparisons) { testing_utilities::TestOrder(EarthMass, JupiterMass); testing_utilities::TestOrder(LightYear, Parsec); testing_utilities::TestOrder(-SpeedOfLight, SpeedOfLight); testing_utilities::TestOrder(SpeedOfLight * Day, LightYear); } TEST_F(QuantitiesTest, DimensionlessOperations) { Dimensionless const zero = 0; Dimensionless const one = 1; Dimensionless const taxi = 1729; Dimensionless const answer = 42; Dimensionless const heegner = 163; testing_utilities::TestField( zero, one, taxi, 4 * π / 3, heegner, answer, -e, 2); } TEST_F(QuantitiesTest, DimensionlfulOperations) { Dimensionless const zero = 0; Dimensionless const one = 1; Dimensionless const taxi = 1729; testing_utilities::TestVectorSpace( 0 * Metre / Second, SpeedOfLight, 88 * Mile / Hour, -340.29 * Metre / Second, zero, one, -2 * π, taxi, 2); // Dimensionful multiplication is a tensor product, see [Tao 2012]. testing_utilities::TestBilinearMap( Times<Product<Mass, Speed>, Mass, Speed>, SolarMass, ElectronMass, SpeedOfLight, 1 * Furlong / JulianYear, -e, 2); } TEST_F(QuantitiesTest, DimensionlessExponentiation) { Dimensionless const number = π - 42; Dimensionless positivePowers = 1; Dimensionless negativePowers = 1; EXPECT_EQ(Dimensionless(1), number.Pow<0>()); for (int i = 1; i < 10; ++i) { positivePowers *= number; negativePowers /= number; EXPECT_THAT(number.Pow(i), AlmostEquals(positivePowers, i)); EXPECT_THAT(number.Pow(-i), AlmostEquals(negativePowers, i)); } } // The Greek letters cause a warning when stringified by the macros, because // apparently Visual Studio doesn't encode strings in UTF-8 by default. #pragma warning(disable: 4566) TEST_F(QuantitiesTest, Formatting) { auto const allTheUnits = 1 * Metre * Kilogram * Second * Ampere * Kelvin / (Mole * Candela * Cycle * Radian * Steradian); std::string const expected = std::string("1e+000 m kg s A K mol^-1") + " cd^-1 cycle^-1 rad^-1 sr^-1"; std::string const actual = ToString(allTheUnits, 0); EXPECT_EQ(expected, actual); std::string π16 = "3.1415926535897931e+000"; EXPECT_EQ(ToString(π), π16); } TEST_F(QuantitiesTest, PhysicalConstants) { // By definition. EXPECT_THAT(1 / SpeedOfLight.Pow<2>(), AlmostEquals(VacuumPermittivity * VacuumPermeability, 2)); // The Keplerian approximation for the mass of the Sun // is fairly accurate. EXPECT_THAT(RelativeError( 4 * π.Pow<2>() * AstronomicalUnit.Pow<3>() / (GravitationalConstant * JulianYear.Pow<2>()), SolarMass), Lt(4E-5)); EXPECT_THAT(RelativeError(1 * Parsec, 3.26156 * LightYear), Lt(2E-6)); // The Keplerian approximation for the mass of the Earth // is pretty bad, but the error is still only 1%. EXPECT_THAT(RelativeError( 4 * π.Pow<2>() * LunarDistance.Pow<3>() / (GravitationalConstant * (27.321582 * Day).Pow<2>()), EarthMass), Lt(1E-2)); EXPECT_THAT(RelativeError(1 * SolarMass, 1047 * JupiterMass), Lt(4E-4)); // Delambre & Méchain. EXPECT_THAT(RelativeError( GravitationalConstant * EarthMass / (40 * Mega(Metre) / (2 * π)).Pow<2>(), StandardGravity), Lt(4E-3)); // Talleyrand. EXPECT_THAT(RelativeError(π * Sqrt(1 * Metre / StandardGravity), 1 * Second), Lt(4E-3)); } #pragma warning(default: 4566) TEST_F(QuantitiesTest, TrigonometricFunctions) { EXPECT_EQ(Cos(0 * Degree), 1); EXPECT_EQ(Sin(0 * Degree), 0); EXPECT_THAT(AbsoluteError(Cos(90 * Degree), 0), Lt(1E-16)); EXPECT_EQ(Sin(90 * Degree), 1); EXPECT_EQ(Cos(180 * Degree), -1); EXPECT_THAT(AbsoluteError(Sin(180 * Degree), 0), Lt(1E-15)); EXPECT_THAT(AbsoluteError(Cos(-90 * Degree), 0), Lt(1E-16)); EXPECT_EQ(Sin(-90 * Degree), -1); for (int k = 1; k < 360; ++k) { // Don't test for multiples of 90 degrees as zeros lead to horrible // conditioning. if (k % 90 != 0) { EXPECT_THAT(Cos((90 - k) * Degree), AlmostEquals(Sin(k * Degree), 50)); EXPECT_THAT(Sin(k * Degree) / Cos(k * Degree), AlmostEquals(Tan(k * Degree), 2)); EXPECT_THAT(((k + 179) % 360 - 179) * Degree, AlmostEquals(ArcTan(Sin(k * Degree), Cos(k * Degree)), 80)); EXPECT_THAT(((k + 179) % 360 - 179) * Degree, AlmostEquals(ArcTan(Sin(k * Degree) * AstronomicalUnit, Cos(k * Degree) * AstronomicalUnit), 80)); EXPECT_THAT(Cos(ArcCos(Cos(k * Degree))), AlmostEquals(Cos(k * Degree), 10)); EXPECT_THAT(Sin(ArcSin(Sin(k * Degree))), AlmostEquals(Sin(k * Degree), 1)); } } // Horribly conditioned near 0, so not in the loop above. EXPECT_EQ(Tan(ArcTan(Tan(-42 * Degree))), Tan(-42 * Degree)); } TEST_F(QuantitiesTest, HyperbolicFunctions) { EXPECT_EQ(Sinh(0 * Radian), 0); EXPECT_EQ(Cosh(0 * Radian), 1); EXPECT_EQ(Tanh(0 * Radian), 0); // Limits: EXPECT_EQ(Sinh(20 * Radian), Cosh(20 * Radian)); EXPECT_EQ(Tanh(20 * Radian), 1); EXPECT_EQ(Sinh(-20 * Radian), -Cosh(-20 * Radian)); EXPECT_EQ(Tanh(-20 * Radian), -1); EXPECT_EQ(Sinh(2 * Radian) / Cosh(2 * Radian), Tanh(2 * Radian)); EXPECT_THAT(ArcSinh(Sinh(-10 * Degree)), AlmostEquals(-10 * Degree, 2)); EXPECT_THAT(ArcCosh(Cosh(-10 * Degree)), AlmostEquals(10 * Degree, 20)); EXPECT_THAT(ArcTanh(Tanh(-10 * Degree)), AlmostEquals(-10 * Degree, 1)); } TEST_F(QuantitiesTest, ExpLogAndSqrt) { EXPECT_EQ(Exp(1), e); EXPECT_THAT(Exp(Log(4.2) + Log(1.729)), AlmostEquals(4.2 * 1.729, 1)); EXPECT_EQ(Exp(Log(2) * Log2(1.729)), 1.729); EXPECT_EQ(Exp(Log(10) * Log10(1.729)), 1.729); EXPECT_THAT(Exp(Log(2) / 2), AlmostEquals(Sqrt(2), 1)); EXPECT_EQ(Exp(Log(Rood / Foot.Pow<2>()) / 2) * Foot, Sqrt(Rood)); } } // namespace geometry } // namespace principia <|endoftext|>
<commit_before>// Author: Chrono Law // Copyright (c) 2015-2016 #ifndef _NGX_BUF_HPP #define _NGX_BUF_HPP #include "NgxPool.hpp" class NgxBuf final : public NgxWrapper<ngx_buf_t> { public: typedef NgxWrapper<ngx_buf_t> super_type; typedef NgxBuf this_type; public: NgxBuf(const NgxPool& p, std::size_t n): super_type(p.buffer(n)) {} NgxBuf(ngx_buf_t* buf):super_type(buf) {} ~NgxBuf() = default; public: // readable range void range(u_char* a, u_char* b) const { get()->pos = a; get()->last = b; get()->memory = true; } // convenitable method void range(ngx_str_t* s) const { range(s->data, s->data + s->len); boundary(s->data, s->data + s->len); } void boundary(u_char* a, u_char* b) const { get()->start = a; get()->end = b; } ngx_str_t range() const { return ngx_str_t{ static_cast<std::size_t>(get()->last - get()->pos), get()->pos}; } ngx_str_t boundary() const { return ngx_str_t{ static_cast<std::size_t>(get()->end - get()->start), get()->start}; } public: template<typename ... Args> void printf(const Args& ... args) const { get()->last = ngx_slprintf(get()->pos, get()->end, args ...); } void copy(u_char* src, size_t n) const { get()->last = ngx_copy(get()->pos, src, n); } public: std::size_t size() const { return ngx_buf_size(get()); } void clear() const { get()->pos = get()->last; } void reset() const { get()->pos = get()->start; get()->last = get()->start; } // ngx_uint_t capacity() const // { // return get()->end - get()->start; // } public: bool empty() const { return get()->pos == get()->last; } bool full() const { return get()->pos == get()->end; } public: void consume(std::size_t n) const { if(n > size()) { n = size(); } get()->pos += n; } void produce(std::size_t n) const { get()->last += n; if(get()->last > get()->end) { get()->last = get()->end; } } public: u_char* begin() const { return get()->pos; } u_char* end() const { return get()->last; } public: bool memory() const { return ngx_buf_in_memory(get()); } bool memoryonly() const { return ngx_buf_in_memory_only(get()); } bool special() const { return ngx_buf_special(get()); } public: bool last() const { return get()->last_buf || get()->last_in_chain; } void finish(bool flag = true) const { get()->last_buf = flag; get()->last_in_chain = flag; } }; #endif //_NGX_BUF_HPP <commit_msg>NgxBuf.hpp<commit_after>// Author: Chrono Law // Copyright (c) 2015-2016 #ifndef _NGX_BUF_HPP #define _NGX_BUF_HPP #include "NgxPool.hpp" class NgxBuf final : public NgxWrapper<ngx_buf_t> { public: typedef NgxWrapper<ngx_buf_t> super_type; typedef NgxBuf this_type; public: NgxBuf(const NgxPool& p, std::size_t n): super_type(p.buffer(n)) {} NgxBuf(ngx_buf_t* buf):super_type(buf) {} ~NgxBuf() = default; public: // readable range void range(u_char* a, u_char* b) const { get()->pos = a; get()->last = b; get()->memory = true; } void boundary(u_char* a, u_char* b) const { get()->start = a; get()->end = b; } ngx_str_t range() const { return ngx_str_t{ static_cast<std::size_t>(get()->last - get()->pos), get()->pos}; } ngx_str_t boundary() const { return ngx_str_t{ static_cast<std::size_t>(get()->end - get()->start), get()->start}; } public: // convenitable method void range(ngx_str_t* s) const { range(s->data, s->data + s->len); boundary(s->data, s->data + s->len); } void range(ngx_str_t& s) const { range(&s); } public: template<typename ... Args> void printf(const Args& ... args) const { get()->last = ngx_slprintf(get()->pos, get()->end, args ...); } void copy(u_char* src, size_t n) const { get()->last = ngx_copy(get()->pos, src, n); } public: std::size_t size() const { return ngx_buf_size(get()); } void clear() const { get()->pos = get()->last; } void reset() const { get()->pos = get()->start; get()->last = get()->start; } // ngx_uint_t capacity() const // { // return get()->end - get()->start; // } public: bool empty() const { return get()->pos == get()->last; } bool full() const { return get()->pos == get()->end; } public: void consume(std::size_t n) const { if(n > size()) { n = size(); } get()->pos += n; } void produce(std::size_t n) const { get()->last += n; if(get()->last > get()->end) { get()->last = get()->end; } } public: u_char* begin() const { return get()->pos; } u_char* end() const { return get()->last; } public: bool memory() const { return ngx_buf_in_memory(get()); } bool memoryonly() const { return ngx_buf_in_memory_only(get()); } bool special() const { return ngx_buf_special(get()); } public: bool last() const { return get()->last_buf || get()->last_in_chain; } void finish(bool flag = true) const { get()->last_buf = flag; get()->last_in_chain = flag; } }; #endif //_NGX_BUF_HPP <|endoftext|>
<commit_before>#include <bts/blockchain/transaction_creation_state.hpp> #include <bts/blockchain/balance_operations.hpp> namespace bts { namespace blockchain { transaction_creation_state::transaction_creation_state( chain_interface_ptr prev_state ) :pending_state(prev_state),required_signatures(1),eval_state(&pending_state) { } void transaction_creation_state::withdraw( const asset& amount_to_withdraw ) { share_type left_to_withdraw = amount_to_withdraw.amount; for( auto item : pending_state._balance_id_to_record ) { if( item.second.asset_id() == amount_to_withdraw.asset_id ) { auto owner = item.second.owner(); if( owner && eval_state.signed_keys.find(*owner) != eval_state.signed_keys.end() ) { auto withdraw_from_balance = std::min<share_type>( item.second.balance, left_to_withdraw ); left_to_withdraw -= withdraw_from_balance; trx.withdraw( item.first, withdraw_from_balance ); eval_state.evaluate_operation( trx.operations.back() ); required_signatures.front().owners.insert( *owner ); required_signatures.front().required = required_signatures.front().owners.size(); if( left_to_withdraw == 0 ) break; } } } FC_ASSERT( left_to_withdraw == 0 ); } void transaction_creation_state::add_known_key( const address& key ) { eval_state.signed_keys.insert(key); } public_key_type transaction_creation_state::deposit( const asset& amount, const public_key_type& to, slate_id_type slate, const optional<private_key_type>& one_time_key, const string& memo, const optional<private_key_type>& from, bool stealth ) { public_key_type receive_key = to; if( !one_time_key ) { trx.deposit( to, amount, slate ); } else { withdraw_with_signature by_account; receive_key = by_account.encrypt_memo_data( *one_time_key, to, from ? *from : fc::ecc::private_key(), memo, one_time_key->get_public_key(), to_memo, stealth ); deposit_operation op; op.amount = amount.amount; op.condition = withdraw_condition( by_account, amount.asset_id, slate ); trx.operations.emplace_back(op); } eval_state.evaluate_operation( trx.operations.back() ); return receive_key; } void transaction_creation_state::pay_fee( const asset& amount ) { // TODO } } } <commit_msg>[GS] Fix build (MSVS)<commit_after>#include <bts/blockchain/transaction_creation_state.hpp> #include <bts/blockchain/balance_operations.hpp> #include <algorithm> namespace bts { namespace blockchain { transaction_creation_state::transaction_creation_state( chain_interface_ptr prev_state ) :pending_state(prev_state),required_signatures(1),eval_state(&pending_state) { } void transaction_creation_state::withdraw( const asset& amount_to_withdraw ) { share_type left_to_withdraw = amount_to_withdraw.amount; for( auto item : pending_state._balance_id_to_record ) { if( item.second.asset_id() == amount_to_withdraw.asset_id ) { auto owner = item.second.owner(); if( owner && eval_state.signed_keys.find(*owner) != eval_state.signed_keys.end() ) { auto withdraw_from_balance = std::min<share_type>( item.second.balance, left_to_withdraw ); left_to_withdraw -= withdraw_from_balance; trx.withdraw( item.first, withdraw_from_balance ); eval_state.evaluate_operation( trx.operations.back() ); required_signatures.front().owners.insert( *owner ); required_signatures.front().required = required_signatures.front().owners.size(); if( left_to_withdraw == 0 ) break; } } } FC_ASSERT( left_to_withdraw == 0 ); } void transaction_creation_state::add_known_key( const address& key ) { eval_state.signed_keys.insert(key); } public_key_type transaction_creation_state::deposit( const asset& amount, const public_key_type& to, slate_id_type slate, const optional<private_key_type>& one_time_key, const string& memo, const optional<private_key_type>& from, bool stealth ) { public_key_type receive_key = to; if( !one_time_key ) { trx.deposit( to, amount, slate ); } else { withdraw_with_signature by_account; receive_key = by_account.encrypt_memo_data( *one_time_key, to, from ? *from : fc::ecc::private_key(), memo, one_time_key->get_public_key(), to_memo, stealth ); deposit_operation op; op.amount = amount.amount; op.condition = withdraw_condition( by_account, amount.asset_id, slate ); trx.operations.emplace_back(op); } eval_state.evaluate_operation( trx.operations.back() ); return receive_key; } void transaction_creation_state::pay_fee( const asset& amount ) { // TODO } } } <|endoftext|>
<commit_before>/* * MPT C++ config interface */ #include <sys/uio.h> #include "node.h" #include "array.h" #include "config.h" __MPT_NAMESPACE_BEGIN template <> int typeinfo<configuration::element>::id() { static int id = 0; if (!id) { id = make_id(); } return id; } // non-trivial path operations array::content *path::array_content() const { if (!base || !(flags & HasArray)) { return 0; } return reinterpret_cast<array::content *>(const_cast<char *>(base)) - 1; } path::path(const char *path, int s, int a) : base(0), off(0), len(0) { sep = s; assign = a; mpt_path_set(this, path, -1); } path::path(const path &from) : base(0) { *this = from; } path::~path() { mpt_path_fini(this); } path &path::operator =(const path &from) { if (this == &from) { return *this; } array::content *s = from.array_content(), *t = array_content(); if (s != t) { if (s) s->addref(); if (t) t->unref(); } memcpy(this, &from, sizeof(*this)); return *this; } span<const char> path::data() const { array::content *d = array_content(); size_t skip, max; if (!d || (skip = off + len) > (max = d->length())) { return span<const char>(0, 0); } return span<const char>(static_cast<char *>(d->data()) + skip, max - skip); } bool path::clear_data() { array::content *d = array_content(); return d ? d->set_length(off + len) : true; } void path::set(const char *path, int len, int s, int a) { if (s >= 0) this->sep = s; if (a >= 0) this->assign = a; mpt_path_set(this, path, len); } int path::del() { return mpt_path_del(this); } int path::add(int) { return mpt_path_add(this, len); } bool path::next() { return (mpt_path_next(this) < 0) ? false : true; } // default implementation for config bool config::set(const char *p, const char *val, int sep) { path where(p, sep, 0); if (!val) { return (remove(&where) < 0) ? false : true; } value tmp(val); return assign(&where, &tmp) < 0 ? false : true; } const metatype *config::get(const char *base, int sep, int len) { path to; to.set(base, len, sep, 0); return query(&to); } void config::del(const char *p, int sep, int len) { path where; where.set(p, len, sep, 0); remove(&where); } int config::environ(const char *glob, int sep, char * const env[]) { return mpt_config_environ(this, glob, sep, env); } metatype *config::global(const path *p) { return mpt_config_global(p); } // config with private element store configuration::configuration() { } configuration::~configuration() { } // private element access configuration::element *configuration::get_element(const unique_array<configuration::element> &arr, path &p) { const span<const char> name = p.value(); int len; if ((len = mpt_path_next(&p)) < 0) { return 0; } for (element *e = arr.begin(), *to = arr.end(); e < to; ++e) { if (e->unused() || !e->equal(name.begin(), len)) { continue; } if (!p.empty()) { return get_element(*e, p); } return e; } return 0; } configuration::element *configuration::make_element(unique_array<configuration::element> &arr, path &p) { const span<const char> name = p.value(); int len; if ((len = mpt_path_next(&p)) < 0) { return 0; } element *unused = 0; for (element *e = arr.begin(), *to = arr.end(); e < to; ++e) { if (e->unused()) { if (!unused) unused = e; } if (!e->equal(name.begin(), len)) { continue; } if (!p.empty()) { return make_element(*e, p); } return e; } if (!unused) { if (!(unused = arr.insert(arr.length()))) { return 0; } } else { unused->resize(0); unused->set_instance(0); } unused->set_name(name.begin(), len); return p.empty() ? unused : make_element(*unused, p); } // config interface int configuration::assign(const path *dest, const value *val) { // no 'self' element(s) if (!dest || dest->empty()) { return BadArgument; } // find existing path p = *dest; metatype *m; element *curr; if (!val) { if (!(curr = get_element(_sub, p))) { return 0; } int type = 0; if ((m = curr->instance())) { type = m->type(); } curr->set_instance(0); return type; } if (!(m = metatype::create(*val))) { return BadType; } if (!(curr = make_element(_sub, p))) { m->unref(); return BadOperation; } curr->set_instance(m); return m->type(); } const metatype *configuration::query(const path *dest) const { // no 'self' element(s) if (!dest || dest->empty()) { return 0; } // find existing path p = *dest; element *curr; if (!(curr = get_element(_sub, p))) { return 0; } return curr->instance(); } int configuration::remove(const path *dest) { // clear root element if (!dest) { return 0; } // clear configuration if (dest->empty()) { _sub.resize(0); return 0; } path p = *dest; element *curr; // requested element not found if (!(curr = get_element(_sub, p))) { return BadOperation; } curr->resize(0); // remove childen from element curr->set_name(0); // mark element as unused curr->set_instance(0); // remove element data return 0; } __MPT_NAMESPACE_END <commit_msg>fix: skip unused config element<commit_after>/* * MPT C++ config interface */ #include <sys/uio.h> #include "node.h" #include "array.h" #include "config.h" __MPT_NAMESPACE_BEGIN template <> int typeinfo<configuration::element>::id() { static int id = 0; if (!id) { id = make_id(); } return id; } // non-trivial path operations array::content *path::array_content() const { if (!base || !(flags & HasArray)) { return 0; } return reinterpret_cast<array::content *>(const_cast<char *>(base)) - 1; } path::path(const char *path, int s, int a) : base(0), off(0), len(0) { sep = s; assign = a; mpt_path_set(this, path, -1); } path::path(const path &from) : base(0) { *this = from; } path::~path() { mpt_path_fini(this); } path &path::operator =(const path &from) { if (this == &from) { return *this; } array::content *s = from.array_content(), *t = array_content(); if (s != t) { if (s) s->addref(); if (t) t->unref(); } memcpy(this, &from, sizeof(*this)); return *this; } span<const char> path::data() const { array::content *d = array_content(); size_t skip, max; if (!d || (skip = off + len) > (max = d->length())) { return span<const char>(0, 0); } return span<const char>(static_cast<char *>(d->data()) + skip, max - skip); } bool path::clear_data() { array::content *d = array_content(); return d ? d->set_length(off + len) : true; } void path::set(const char *path, int len, int s, int a) { if (s >= 0) this->sep = s; if (a >= 0) this->assign = a; mpt_path_set(this, path, len); } int path::del() { return mpt_path_del(this); } int path::add(int) { return mpt_path_add(this, len); } bool path::next() { return (mpt_path_next(this) < 0) ? false : true; } // default implementation for config bool config::set(const char *p, const char *val, int sep) { path where(p, sep, 0); if (!val) { return (remove(&where) < 0) ? false : true; } value tmp(val); return assign(&where, &tmp) < 0 ? false : true; } const metatype *config::get(const char *base, int sep, int len) { path to; to.set(base, len, sep, 0); return query(&to); } void config::del(const char *p, int sep, int len) { path where; where.set(p, len, sep, 0); remove(&where); } int config::environ(const char *glob, int sep, char * const env[]) { return mpt_config_environ(this, glob, sep, env); } metatype *config::global(const path *p) { return mpt_config_global(p); } // config with private element store configuration::configuration() { } configuration::~configuration() { } // private element access configuration::element *configuration::get_element(const unique_array<configuration::element> &arr, path &p) { const span<const char> name = p.value(); int len; if ((len = mpt_path_next(&p)) < 0) { return 0; } for (element *e = arr.begin(), *to = arr.end(); e < to; ++e) { if (e->unused() || !e->equal(name.begin(), len)) { continue; } if (!p.empty()) { return get_element(*e, p); } return e; } return 0; } configuration::element *configuration::make_element(unique_array<configuration::element> &arr, path &p) { const span<const char> name = p.value(); int len; if ((len = mpt_path_next(&p)) < 0) { return 0; } element *unused = 0; for (element *e = arr.begin(), *to = arr.end(); e < to; ++e) { if (e->unused()) { if (!unused) unused = e; continue; } if (!e->equal(name.begin(), len)) { continue; } if (!p.empty()) { return make_element(*e, p); } return e; } if (!unused) { if (!(unused = arr.insert(arr.length()))) { return 0; } } else { unused->resize(0); unused->set_instance(0); } unused->set_name(name.begin(), len); return p.empty() ? unused : make_element(*unused, p); } // config interface int configuration::assign(const path *dest, const value *val) { // no 'self' element(s) if (!dest || dest->empty()) { return BadArgument; } // find existing path p = *dest; metatype *m; element *curr; if (!val) { if (!(curr = get_element(_sub, p))) { return 0; } int type = 0; if ((m = curr->instance())) { type = m->type(); } curr->set_instance(0); return type; } if (!(m = metatype::create(*val))) { return BadType; } if (!(curr = make_element(_sub, p))) { m->unref(); return BadOperation; } curr->set_instance(m); return m->type(); } const metatype *configuration::query(const path *dest) const { // no 'self' element(s) if (!dest || dest->empty()) { return 0; } // find existing path p = *dest; element *curr; if (!(curr = get_element(_sub, p))) { return 0; } return curr->instance(); } int configuration::remove(const path *dest) { // clear root element if (!dest) { return 0; } // clear configuration if (dest->empty()) { _sub.resize(0); return 0; } path p = *dest; element *curr; // requested element not found if (!(curr = get_element(_sub, p))) { return BadOperation; } curr->resize(0); // remove childen from element curr->set_name(0); // mark element as unused curr->set_instance(0); // remove element data return 0; } __MPT_NAMESPACE_END <|endoftext|>
<commit_before>/********************************************************************* * * Copyright 2012 the original author or authors. * See the NOTICE file distributed with this work for additional * information regarding copyright ownership. * * 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<stdio.h> #include<time.h> #include<unistd.h> #include<pwd.h> #include<iostream> #include<fstream> #include<gphoto2/gphoto2.h> #include<gphoto2/gphoto2-context.h> #include<boost/filesystem.hpp> #include<ros/ros.h> #include<rospilot/CaptureImage.h> #include<std_srvs/Empty.h> #include<sensor_msgs/fill_image.h> #include<sensor_msgs/CompressedImage.h> #include<ptp.h> #include<usb_camera.h> #include<video_recorder.h> class CameraNode { private: ros::NodeHandle node; // NOTE: We don't need to guard this with a mutex, because callbacks // are called in spinOnce() in the main thread BaseCamera *camera; JpegDecoder *jpegDecoder; H264Encoder *h264Encoder; SoftwareVideoRecorder *videoRecorder; ros::Publisher imagePub; ros::ServiceServer captureServiceServer; ros::ServiceServer startRecordServiceServer; ros::ServiceServer stopRecordServiceServer; std::string videoDevice; std::string codec; // "mjpeg" or "h264" CodecID codecId; std::string mediaPath; int width; int height; int framerate; private: bool sendPreview() { sensor_msgs::CompressedImage image; if(camera != nullptr && camera->getLiveImage(&image)) { bool keyFrame = false; if (codec == "mjpeg") { keyFrame = true; } imagePub.publish(image); if (codec == "h264" && image.format == "mjpeg") { jpegDecoder->decodeInPlace(&image); h264Encoder->encodeInPlace(&image, &keyFrame); } if (videoRecorder != nullptr) { videoRecorder->writeFrame(&image, keyFrame); } return true; } return false; } // TODO: find a library that does this static std::string expandTildes(const std::string path) { if (path[0] != '~') { return path; } std::string user = ""; int i = 1; for (; i < path.size() && path[i] != '/'; i++) { user += path[i]; } if (user.size() == 0) { user = getpwuid(geteuid())->pw_name; } return std::string("/home/") + user + path.substr(i); } BaseCamera *createCamera() { std::string cameraType; node.param("camera_type", cameraType, std::string("usb")); node.param("video_device", videoDevice, std::string("/dev/video0")); node.param("image_width", width, 1920); node.param("image_height", height, 1080); node.param("framerate", framerate, 30); node.param("codec", codec, std::string("mjpeg")); if (codec == "h264") { codecId = CODEC_ID_H264; } else if (codec == "mjpeg") { codecId = CODEC_ID_MJPEG; } else { ROS_FATAL("Unknown codec: %s", codec.c_str()); } node.param("media_path", mediaPath, std::string("~/.rospilot/media")); mediaPath = expandTildes(mediaPath); if (cameraType == "ptp") { return new PtpCamera(); } else if (cameraType == "usb") { ROS_INFO("Requesting camera res %dx%d", width, height); UsbCamera *camera = new UsbCamera(videoDevice, width, height, framerate); // Read the width and height, since the camera may have altered it to // something it supports width = camera->getWidth(); height = camera->getHeight(); ROS_INFO("Camera selected res %dx%d", width, height); return camera; } else { ROS_FATAL("Unsupported camera type: %s", cameraType.c_str()); return nullptr; } } public: CameraNode() : node("~") { imagePub = node.advertise<sensor_msgs::CompressedImage>( "image_raw/compressed", 1); captureServiceServer = node.advertiseService( "capture_image", &CameraNode::captureImageCallback, this); startRecordServiceServer = node.advertiseService( "start_record", &CameraNode::startRecordHandler, this); stopRecordServiceServer = node.advertiseService( "stop_record", &CameraNode::stopRecordHandler, this); camera = createCamera(); jpegDecoder = new JpegDecoder(width, height, PIX_FMT_YUV420P); h264Encoder = new SoftwareH264Encoder(width, height, PIX_FMT_YUV420P); PixelFormat recordingPixelFormat; if (codec == "h264") { recordingPixelFormat = PIX_FMT_YUV420P; } else if (codec == "mjpeg") { // TODO: Do we need to detect this dynamically? // Different cameras might be 4:2:0, 4:2:2, or 4:4:4 recordingPixelFormat = PIX_FMT_YUVJ422P; } videoRecorder = new SoftwareVideoRecorder(width, height, recordingPixelFormat, codecId); } ~CameraNode() { if (camera != nullptr) { delete camera; } delete jpegDecoder; delete h264Encoder; delete videoRecorder; } bool spin() { ROS_INFO("camera node is running."); while (node.ok()) { // Process any pending service callbacks ros::spinOnce(); std::string newVideoDevice; node.getParam("video_device", newVideoDevice); if (newVideoDevice != videoDevice) { if (camera != nullptr) { delete camera; } camera = createCamera(); } if(!sendPreview()) { // Sleep and hope the camera recovers usleep(1000*1000); } // Run at 1kHz usleep(1000); } return true; } bool startRecordHandler(std_srvs::Empty::Request& request, std_srvs::Empty::Response &response) { time_t t = time(nullptr); struct tm *tmp = localtime(&t); char str[100]; strftime(str, sizeof(str), "%Y-%m-%d_%H%M%S.mp4", tmp); std::string path = mediaPath + "/" + str; return videoRecorder->start(path.c_str()); } bool stopRecordHandler(std_srvs::Empty::Request& request, std_srvs::Empty::Response &response) { return videoRecorder->stop(); } bool captureImageCallback(std_srvs::Empty::Request& request, std_srvs::Empty::Response &response) { if (camera != nullptr) { time_t t = time(nullptr); struct tm *tmp = localtime(&t); char str[100]; strftime(str, sizeof(str), "%Y-%m-%d_%H%M%S", tmp); std::string basePath = mediaPath + "/" + str; std::string path = basePath + ".jpg"; for (int i = 1; boost::filesystem::exists(path); i++) { std::stringstream ss; ss << basePath << "_" << i << ".jpg"; path = ss.str(); } sensor_msgs::CompressedImage image; if (!camera->captureImage(&image)) { return false; } std::fstream fout(path, std::fstream::out); fout.write((char*) image.data.data(), image.data.size()); fout.close(); return true; } return false; } }; int main(int argc, char **argv) { ros::init(argc, argv, "camera"); CameraNode a; a.spin(); return 0; } <commit_msg>Improve media path expansion<commit_after>/********************************************************************* * * Copyright 2012 the original author or authors. * See the NOTICE file distributed with this work for additional * information regarding copyright ownership. * * 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<stdio.h> #include<time.h> #include<unistd.h> #include<pwd.h> #include<iostream> #include<fstream> #include<gphoto2/gphoto2.h> #include<gphoto2/gphoto2-context.h> #include<boost/filesystem.hpp> #include<wordexp.h> #include<ros/ros.h> #include<rospilot/CaptureImage.h> #include<std_srvs/Empty.h> #include<sensor_msgs/fill_image.h> #include<sensor_msgs/CompressedImage.h> #include<ptp.h> #include<usb_camera.h> #include<video_recorder.h> class CameraNode { private: ros::NodeHandle node; // NOTE: We don't need to guard this with a mutex, because callbacks // are called in spinOnce() in the main thread BaseCamera *camera; JpegDecoder *jpegDecoder; H264Encoder *h264Encoder; SoftwareVideoRecorder *videoRecorder; ros::Publisher imagePub; ros::ServiceServer captureServiceServer; ros::ServiceServer startRecordServiceServer; ros::ServiceServer stopRecordServiceServer; std::string videoDevice; std::string codec; // "mjpeg" or "h264" CodecID codecId; std::string mediaPath; int width; int height; int framerate; private: bool sendPreview() { sensor_msgs::CompressedImage image; if(camera != nullptr && camera->getLiveImage(&image)) { bool keyFrame = false; if (codec == "mjpeg") { keyFrame = true; } imagePub.publish(image); if (codec == "h264" && image.format == "mjpeg") { jpegDecoder->decodeInPlace(&image); h264Encoder->encodeInPlace(&image, &keyFrame); } if (videoRecorder != nullptr) { videoRecorder->writeFrame(&image, keyFrame); } return true; } return false; } BaseCamera *createCamera() { std::string cameraType; node.param("camera_type", cameraType, std::string("usb")); node.param("video_device", videoDevice, std::string("/dev/video0")); node.param("image_width", width, 1920); node.param("image_height", height, 1080); node.param("framerate", framerate, 30); node.param("codec", codec, std::string("mjpeg")); if (codec == "h264") { codecId = CODEC_ID_H264; } else if (codec == "mjpeg") { codecId = CODEC_ID_MJPEG; } else { ROS_FATAL("Unknown codec: %s", codec.c_str()); } node.param("media_path", mediaPath, std::string("~/.rospilot/media")); wordexp_t p; wordexp(mediaPath.c_str(), &p, 0); if (p.we_wordc != 1) { ROS_ERROR("Got too many words when expanding media path: %s", mediaPath.c_str()); } else { mediaPath = p.we_wordv[0]; } wordfree(&p); if (cameraType == "ptp") { return new PtpCamera(); } else if (cameraType == "usb") { ROS_INFO("Requesting camera res %dx%d", width, height); UsbCamera *camera = new UsbCamera(videoDevice, width, height, framerate); // Read the width and height, since the camera may have altered it to // something it supports width = camera->getWidth(); height = camera->getHeight(); ROS_INFO("Camera selected res %dx%d", width, height); return camera; } else { ROS_FATAL("Unsupported camera type: %s", cameraType.c_str()); return nullptr; } } public: CameraNode() : node("~") { imagePub = node.advertise<sensor_msgs::CompressedImage>( "image_raw/compressed", 1); captureServiceServer = node.advertiseService( "capture_image", &CameraNode::captureImageCallback, this); startRecordServiceServer = node.advertiseService( "start_record", &CameraNode::startRecordHandler, this); stopRecordServiceServer = node.advertiseService( "stop_record", &CameraNode::stopRecordHandler, this); camera = createCamera(); jpegDecoder = new JpegDecoder(width, height, PIX_FMT_YUV420P); h264Encoder = new SoftwareH264Encoder(width, height, PIX_FMT_YUV420P); PixelFormat recordingPixelFormat; if (codec == "h264") { recordingPixelFormat = PIX_FMT_YUV420P; } else if (codec == "mjpeg") { // TODO: Do we need to detect this dynamically? // Different cameras might be 4:2:0, 4:2:2, or 4:4:4 recordingPixelFormat = PIX_FMT_YUVJ422P; } videoRecorder = new SoftwareVideoRecorder(width, height, recordingPixelFormat, codecId); } ~CameraNode() { if (camera != nullptr) { delete camera; } delete jpegDecoder; delete h264Encoder; delete videoRecorder; } bool spin() { ROS_INFO("camera node is running."); while (node.ok()) { // Process any pending service callbacks ros::spinOnce(); std::string newVideoDevice; node.getParam("video_device", newVideoDevice); if (newVideoDevice != videoDevice) { if (camera != nullptr) { delete camera; } camera = createCamera(); } if(!sendPreview()) { // Sleep and hope the camera recovers usleep(1000*1000); } // Run at 1kHz usleep(1000); } return true; } bool startRecordHandler(std_srvs::Empty::Request& request, std_srvs::Empty::Response &response) { time_t t = time(nullptr); struct tm *tmp = localtime(&t); char str[100]; strftime(str, sizeof(str), "%Y-%m-%d_%H%M%S.mp4", tmp); std::string path = mediaPath + "/" + str; return videoRecorder->start(path.c_str()); } bool stopRecordHandler(std_srvs::Empty::Request& request, std_srvs::Empty::Response &response) { return videoRecorder->stop(); } bool captureImageCallback(std_srvs::Empty::Request& request, std_srvs::Empty::Response &response) { if (camera != nullptr) { time_t t = time(nullptr); struct tm *tmp = localtime(&t); char str[100]; strftime(str, sizeof(str), "%Y-%m-%d_%H%M%S", tmp); std::string basePath = mediaPath + "/" + str; std::string path = basePath + ".jpg"; for (int i = 1; boost::filesystem::exists(path); i++) { std::stringstream ss; ss << basePath << "_" << i << ".jpg"; path = ss.str(); } sensor_msgs::CompressedImage image; if (!camera->captureImage(&image)) { return false; } std::fstream fout(path, std::fstream::out); fout.write((char*) image.data.data(), image.data.size()); fout.close(); return true; } return false; } }; int main(int argc, char **argv) { ros::init(argc, argv, "camera"); CameraNode a; a.spin(); return 0; } <|endoftext|>
<commit_before>/****************** <VPR heading BEGIN do not edit this line> ***************** * * VR Juggler Portable Runtime * * Original Authors: * Allen Bierbaum, Patrick Hartling, Kevin Meinert, Carolina Cruz-Neira * * ----------------------------------------------------------------- * File: $RCSfile$ * Date modified: $Date$ * Version: $Revision$ * ----------------------------------------------------------------- * ****************** <VPR heading END do not edit this line> ******************/ /*************** <auto-copyright.pl BEGIN do not edit this line> ************** * * VR Juggler is (C) Copyright 1998-2003 by Iowa State University * * Original Authors: * Allen Bierbaum, Christopher Just, * Patrick Hartling, Kevin Meinert, * Carolina Cruz-Neira, Albert Baker * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Library General Public * License as published by the Free Software Foundation; either * version 2 of the License, or (at your option) any later version. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Library General Public License for more details. * * You should have received a copy of the GNU Library General Public * License along with this library; if not, write to the * Free Software Foundation, Inc., 59 Temple Place - Suite 330, * Boston, MA 02111-1307, USA. * *************** <auto-copyright.pl END do not edit this line> ***************/ /* Copyright (c) 2002 Peter O'Gorman <[email protected]> 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 <vpr/vprConfig.h> #include <stdio.h> #include <stdlib.h> #include <string.h> #include <sys/types.h> #include <sys/stat.h> #include <stdarg.h> #include <limits.h> #include <mach-o/dyld.h> #include <vpr/Util/Assert.h> #include <vpr/Util/Debug.h> #include <vpr/md/DARWIN/DynLoad/LibraryDYLD.h> #ifndef _POSIX_SOURCE /* * Structure filled in by dladdr(). */ typedef struct dl_info { const char *dli_fname; /* Pathname of shared object */ void *dli_fbase; /* Base address of shared object */ const char *dli_sname; /* Name of nearest symbol */ void *dli_saddr; /* Address of nearest symbol */ } Dl_info; #endif /* ! _POSIX_SOURCE */ #define RTLD_LAZY 0x1 #define RTLD_NOW 0x2 #define RTLD_LOCAL 0x4 #define RTLD_GLOBAL 0x8 #ifndef _POSIX_SOURCE #define RTLD_NOLOAD 0x10 #define RTLD_NODELETE 0x80 /* * Special handle arguments for dlsym(). */ #define RTLD_NEXT ((void *) -1) /* Search subsequent objects. */ #define RTLD_DEFAULT ((void *) -2) /* Use default search algorithm. */ #endif /* ! _POSIX_SOURCE */ namespace { static const unsigned int ERR_STR_LEN(256); // Copied from error() found in dlfcn_simple.c from dlcompat. static const char* error(int setget, const char *str, ...) { static char errstr[ERR_STR_LEN]; static int err_filled = 0; const char *retval; NSLinkEditErrors ler; int lerno; const char *dylderrstr; const char *file; va_list arg; if (setget <= 0) { va_start(arg, str); strncpy(errstr, "dlsimple: ", ERR_STR_LEN); vsnprintf(errstr + 10, ERR_STR_LEN - 10, str, arg); va_end(arg); /* We prefer to use the dyld error string if setget is 0 */ if (setget == 0) { NSLinkEditError(&ler, &lerno, &file, &dylderrstr); fprintf(stderr,"dyld: %s\n",dylderrstr); if (dylderrstr && strlen(dylderrstr)) strncpy(errstr,dylderrstr,ERR_STR_LEN); } err_filled = 1; retval = NULL; } else { if (!err_filled) retval = NULL; else retval = errstr; err_filled = 0; } return retval; } } namespace vpr { vpr::ReturnStatus LibraryDYLD::load() { vpr::ReturnStatus status; if ( std::string("") != mName ) { mLibrary = internalDlopen(mName.c_str(), RTLD_NOW | RTLD_GLOBAL); } else { mLibrary = internalDlopen(NULL, RTLD_NOW | RTLD_GLOBAL); } if ( NULL == mLibrary ) { vprDEBUG_CONT(vprDBG_ALL, vprDBG_WARNING_LVL) << std::endl << vprDEBUG_FLUSH; vprDEBUG(vprDBG_ALL, vprDBG_WARNING_LVL) << clrOutNORM(clrYELLOW, "WARNING:") << " Could not load '" << mName << "'\n" << vprDEBUG_FLUSH; vprDEBUG_NEXT(vprDBG_ALL, vprDBG_WARNING_LVL) << internalDlerror() << std::endl << vprDEBUG_FLUSH; status.setCode(vpr::ReturnStatus::Fail); } return status; } vpr::ReturnStatus LibraryDYLD::unload() { vprASSERT(mLibrary != NULL && "No library to unload"); vpr::ReturnStatus status; if ( internalDlclose(mLibrary) != 0 ) { status.setCode(vpr::ReturnStatus::Fail); } else { mLibrary = NULL; } return status; } void* LibraryDYLD::findSymbolAndLibrary(const char* symbolName, LibraryDYLD& lib) { boost::ignore_unused_variable_warning(symbolName); boost::ignore_unused_variable_warning(lib); vprASSERT(false && "Not implemented yet"); return NULL; } // Copied from dlopen() found in dlfcn_simple.c from dlcompat. void* LibraryDYLD::internalDlopen(const char* path, int mode) { void *module = 0; NSObjectFileImage ofi = 0; NSObjectFileImageReturnCode ofirc; static int (*make_private_module_public) (NSModule module) = 0; unsigned int flags = NSLINKMODULE_OPTION_RETURN_ON_ERROR | NSLINKMODULE_OPTION_PRIVATE; /* If we got no path, the app wants the global namespace, use -1 as the marker in this case */ if (!path) return (void *)-1; /* Create the object file image, works for things linked with the -bundle arg to ld */ ofirc = NSCreateObjectFileImageFromFile(path, &ofi); switch (ofirc) { case NSObjectFileImageSuccess: /* It was okay, so use NSLinkModule to link in the image */ if (!(mode & RTLD_LAZY)) flags += NSLINKMODULE_OPTION_BINDNOW; module = NSLinkModule(ofi, path,flags); /* Don't forget to destroy the object file image, unless you like leaks */ NSDestroyObjectFileImage(ofi); /* If the mode was global, then change the module, this avoids multiply defined symbol errors to first load private then make global. Silly, isn't it. */ if ((mode & RTLD_GLOBAL)) { if (!make_private_module_public) { _dyld_func_lookup("__dyld_NSMakePrivateModulePublic", (unsigned long *)&make_private_module_public); } make_private_module_public(module); } break; case NSObjectFileImageInappropriateFile: /* It may have been a dynamic library rather than a bundle, try to load it */ module = (void *)NSAddImage(path, NSADDIMAGE_OPTION_RETURN_ON_ERROR); break; case NSObjectFileImageFailure: error(0,"Object file setup failure : \"%s\"", path); return 0; case NSObjectFileImageArch: error(0,"No object for this architecture : \"%s\"", path); return 0; case NSObjectFileImageFormat: error(0,"Bad object file format : \"%s\"", path); return 0; case NSObjectFileImageAccess: error(0,"Can't read object file : \"%s\"", path); return 0; } if (!module) error(0, "Can not open \"%s\"", path); return module; } // Copied from dlerror() found in dlfcn_simple.c from dlcompat. const char* LibraryDYLD::internalDlerror() { return error(1, (char *)NULL); } // Copied from dlclose() found in dlfcn_simple.c from dlcompat. int LibraryDYLD::internalDlclose(void* handle) { if ((((struct mach_header *)handle)->magic == MH_MAGIC) || (((struct mach_header *)handle)->magic == MH_CIGAM)) { error(-1, "Can't remove dynamic libraries on darwin"); return 0; } if (!NSUnLinkModule(handle, 0)) { error(0, "unable to unlink module %s", NSNameOfModule(handle)); return 1; } return 0; } // Copied from dlsym found in dlfcn_simple.c from dlcompat. void* LibraryDYLD::internalDlsym(void* handle, const char* symbol) { int sym_len = strlen(symbol); void *value = NULL; char *malloc_sym = NULL; NSSymbol *nssym = 0; malloc_sym = malloc(sym_len + 2); if (malloc_sym) { sprintf(malloc_sym, "_%s", symbol); /* If the handle is -1, if is the app global context */ if (handle == (void *)-1) { /* Global context, use NSLookupAndBindSymbol */ if (NSIsSymbolNameDefined(malloc_sym)) { nssym = NSLookupAndBindSymbol(malloc_sym); } } /* Now see if the handle is a struch mach_header* or not, use NSLookupSymbol in image for libraries, and NSLookupSymbolInModule for bundles */ else { /* Check for both possible magic numbers depending on x86/ppc byte order */ if ((((struct mach_header *)handle)->magic == MH_MAGIC) || (((struct mach_header *)handle)->magic == MH_CIGAM)) { if (NSIsSymbolNameDefinedInImage((struct mach_header *)handle, malloc_sym)) { nssym = NSLookupSymbolInImage((struct mach_header *)handle, malloc_sym, NSLOOKUPSYMBOLINIMAGE_OPTION_BIND | NSLOOKUPSYMBOLINIMAGE_OPTION_RETURN_ON_ERROR); } } else { nssym = NSLookupSymbolInModule(handle, malloc_sym); } } if (!nssym) { error(0, "Symbol \"%s\" Not found", symbol); } value = NSAddressOfSymbol(nssym); free(malloc_sym); } else { error(-1, "Unable to allocate memory"); } return value; } } // End of vpr namespace <commit_msg>Added a missing #include.<commit_after>/****************** <VPR heading BEGIN do not edit this line> ***************** * * VR Juggler Portable Runtime * * Original Authors: * Allen Bierbaum, Patrick Hartling, Kevin Meinert, Carolina Cruz-Neira * * ----------------------------------------------------------------- * File: $RCSfile$ * Date modified: $Date$ * Version: $Revision$ * ----------------------------------------------------------------- * ****************** <VPR heading END do not edit this line> ******************/ /*************** <auto-copyright.pl BEGIN do not edit this line> ************** * * VR Juggler is (C) Copyright 1998-2003 by Iowa State University * * Original Authors: * Allen Bierbaum, Christopher Just, * Patrick Hartling, Kevin Meinert, * Carolina Cruz-Neira, Albert Baker * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Library General Public * License as published by the Free Software Foundation; either * version 2 of the License, or (at your option) any later version. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Library General Public License for more details. * * You should have received a copy of the GNU Library General Public * License along with this library; if not, write to the * Free Software Foundation, Inc., 59 Temple Place - Suite 330, * Boston, MA 02111-1307, USA. * *************** <auto-copyright.pl END do not edit this line> ***************/ /* Copyright (c) 2002 Peter O'Gorman <[email protected]> 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 <vpr/vprConfig.h> #include <stdio.h> #include <stdlib.h> #include <string.h> #include <sys/types.h> #include <sys/stat.h> #include <stdarg.h> #include <limits.h> #include <mach-o/dyld.h> #include <boost/concept_check.hpp> #include <vpr/Util/Assert.h> #include <vpr/Util/Debug.h> #include <vpr/md/DARWIN/DynLoad/LibraryDYLD.h> #ifndef _POSIX_SOURCE /* * Structure filled in by dladdr(). */ typedef struct dl_info { const char *dli_fname; /* Pathname of shared object */ void *dli_fbase; /* Base address of shared object */ const char *dli_sname; /* Name of nearest symbol */ void *dli_saddr; /* Address of nearest symbol */ } Dl_info; #endif /* ! _POSIX_SOURCE */ #define RTLD_LAZY 0x1 #define RTLD_NOW 0x2 #define RTLD_LOCAL 0x4 #define RTLD_GLOBAL 0x8 #ifndef _POSIX_SOURCE #define RTLD_NOLOAD 0x10 #define RTLD_NODELETE 0x80 /* * Special handle arguments for dlsym(). */ #define RTLD_NEXT ((void *) -1) /* Search subsequent objects. */ #define RTLD_DEFAULT ((void *) -2) /* Use default search algorithm. */ #endif /* ! _POSIX_SOURCE */ namespace { static const unsigned int ERR_STR_LEN(256); // Copied from error() found in dlfcn_simple.c from dlcompat. static const char* error(int setget, const char *str, ...) { static char errstr[ERR_STR_LEN]; static int err_filled = 0; const char *retval; NSLinkEditErrors ler; int lerno; const char *dylderrstr; const char *file; va_list arg; if (setget <= 0) { va_start(arg, str); strncpy(errstr, "dlsimple: ", ERR_STR_LEN); vsnprintf(errstr + 10, ERR_STR_LEN - 10, str, arg); va_end(arg); /* We prefer to use the dyld error string if setget is 0 */ if (setget == 0) { NSLinkEditError(&ler, &lerno, &file, &dylderrstr); fprintf(stderr,"dyld: %s\n",dylderrstr); if (dylderrstr && strlen(dylderrstr)) strncpy(errstr,dylderrstr,ERR_STR_LEN); } err_filled = 1; retval = NULL; } else { if (!err_filled) retval = NULL; else retval = errstr; err_filled = 0; } return retval; } } namespace vpr { vpr::ReturnStatus LibraryDYLD::load() { vpr::ReturnStatus status; if ( std::string("") != mName ) { mLibrary = internalDlopen(mName.c_str(), RTLD_NOW | RTLD_GLOBAL); } else { mLibrary = internalDlopen(NULL, RTLD_NOW | RTLD_GLOBAL); } if ( NULL == mLibrary ) { vprDEBUG_CONT(vprDBG_ALL, vprDBG_WARNING_LVL) << std::endl << vprDEBUG_FLUSH; vprDEBUG(vprDBG_ALL, vprDBG_WARNING_LVL) << clrOutNORM(clrYELLOW, "WARNING:") << " Could not load '" << mName << "'\n" << vprDEBUG_FLUSH; vprDEBUG_NEXT(vprDBG_ALL, vprDBG_WARNING_LVL) << internalDlerror() << std::endl << vprDEBUG_FLUSH; status.setCode(vpr::ReturnStatus::Fail); } return status; } vpr::ReturnStatus LibraryDYLD::unload() { vprASSERT(mLibrary != NULL && "No library to unload"); vpr::ReturnStatus status; if ( internalDlclose(mLibrary) != 0 ) { status.setCode(vpr::ReturnStatus::Fail); } else { mLibrary = NULL; } return status; } void* LibraryDYLD::findSymbolAndLibrary(const char* symbolName, LibraryDYLD& lib) { boost::ignore_unused_variable_warning(symbolName); boost::ignore_unused_variable_warning(lib); vprASSERT(false && "Not implemented yet"); return NULL; } // Copied from dlopen() found in dlfcn_simple.c from dlcompat. void* LibraryDYLD::internalDlopen(const char* path, int mode) { void *module = 0; NSObjectFileImage ofi = 0; NSObjectFileImageReturnCode ofirc; static int (*make_private_module_public) (NSModule module) = 0; unsigned int flags = NSLINKMODULE_OPTION_RETURN_ON_ERROR | NSLINKMODULE_OPTION_PRIVATE; /* If we got no path, the app wants the global namespace, use -1 as the marker in this case */ if (!path) return (void *)-1; /* Create the object file image, works for things linked with the -bundle arg to ld */ ofirc = NSCreateObjectFileImageFromFile(path, &ofi); switch (ofirc) { case NSObjectFileImageSuccess: /* It was okay, so use NSLinkModule to link in the image */ if (!(mode & RTLD_LAZY)) flags += NSLINKMODULE_OPTION_BINDNOW; module = NSLinkModule(ofi, path,flags); /* Don't forget to destroy the object file image, unless you like leaks */ NSDestroyObjectFileImage(ofi); /* If the mode was global, then change the module, this avoids multiply defined symbol errors to first load private then make global. Silly, isn't it. */ if ((mode & RTLD_GLOBAL)) { if (!make_private_module_public) { _dyld_func_lookup("__dyld_NSMakePrivateModulePublic", (unsigned long *)&make_private_module_public); } make_private_module_public(module); } break; case NSObjectFileImageInappropriateFile: /* It may have been a dynamic library rather than a bundle, try to load it */ module = (void *)NSAddImage(path, NSADDIMAGE_OPTION_RETURN_ON_ERROR); break; case NSObjectFileImageFailure: error(0,"Object file setup failure : \"%s\"", path); return 0; case NSObjectFileImageArch: error(0,"No object for this architecture : \"%s\"", path); return 0; case NSObjectFileImageFormat: error(0,"Bad object file format : \"%s\"", path); return 0; case NSObjectFileImageAccess: error(0,"Can't read object file : \"%s\"", path); return 0; } if (!module) error(0, "Can not open \"%s\"", path); return module; } // Copied from dlerror() found in dlfcn_simple.c from dlcompat. const char* LibraryDYLD::internalDlerror() { return error(1, (char *)NULL); } // Copied from dlclose() found in dlfcn_simple.c from dlcompat. int LibraryDYLD::internalDlclose(void* handle) { if ((((struct mach_header *)handle)->magic == MH_MAGIC) || (((struct mach_header *)handle)->magic == MH_CIGAM)) { error(-1, "Can't remove dynamic libraries on darwin"); return 0; } if (!NSUnLinkModule(handle, 0)) { error(0, "unable to unlink module %s", NSNameOfModule(handle)); return 1; } return 0; } // Copied from dlsym found in dlfcn_simple.c from dlcompat. void* LibraryDYLD::internalDlsym(void* handle, const char* symbol) { int sym_len = strlen(symbol); void *value = NULL; char *malloc_sym = NULL; NSSymbol *nssym = 0; malloc_sym = malloc(sym_len + 2); if (malloc_sym) { sprintf(malloc_sym, "_%s", symbol); /* If the handle is -1, if is the app global context */ if (handle == (void *)-1) { /* Global context, use NSLookupAndBindSymbol */ if (NSIsSymbolNameDefined(malloc_sym)) { nssym = NSLookupAndBindSymbol(malloc_sym); } } /* Now see if the handle is a struch mach_header* or not, use NSLookupSymbol in image for libraries, and NSLookupSymbolInModule for bundles */ else { /* Check for both possible magic numbers depending on x86/ppc byte order */ if ((((struct mach_header *)handle)->magic == MH_MAGIC) || (((struct mach_header *)handle)->magic == MH_CIGAM)) { if (NSIsSymbolNameDefinedInImage((struct mach_header *)handle, malloc_sym)) { nssym = NSLookupSymbolInImage((struct mach_header *)handle, malloc_sym, NSLOOKUPSYMBOLINIMAGE_OPTION_BIND | NSLOOKUPSYMBOLINIMAGE_OPTION_RETURN_ON_ERROR); } } else { nssym = NSLookupSymbolInModule(handle, malloc_sym); } } if (!nssym) { error(0, "Symbol \"%s\" Not found", symbol); } value = NSAddressOfSymbol(nssym); free(malloc_sym); } else { error(-1, "Unable to allocate memory"); } return value; } } // End of vpr namespace <|endoftext|>
<commit_before>//#define _DEBUG #include <algorithm> #include <climits> #include <cstddef> #include <memory> #include <string> #include <vector> #ifdef _DEBUG #include <iostream> #endif #include "js6chars.hpp" std::string char_repr(char value, bool* cannot_use, char forbidden); std::string str_repr(const char* str, bool* cannot_use, char forbidden); std::string str_repr(std::string const& in, bool* cannot_use, char forbidden); static std::string small_number_repr(int value) { return value == 0 ? "+[]" : value == 1 ? "++[[]][+[]]" : "++[" + number_repr(value -1) + "][+[]]"; } static std::string number_repr_helper(int value) { if (value < 10) return small_number_repr(value) + "+[]"; return number_repr_helper(value/10) + "+(" + small_number_repr(value%10) + ")"; } std::string number_repr(int value) { if (value < 0) { return std::string("+(") + char_repr('-') + "+(" + number_repr_helper(-value) + "))"; } return value < 10 ? small_number_repr(value) : std::string("+(") + number_repr_helper(value) + ")"; } namespace { template <std::size_t N> std::string from_known(char value, const char (&real_str)[N], std::string&& generated) { std::string shortest_match; char const* it = std::find(std::begin(real_str), std::end(real_str), value); for ( ; it != std::end(real_str) ; it = std::find(std::next(it), std::end(real_str), value)) { std::string match = "(" + generated + "+[])" + "[" + number_repr((int)(it - real_str)) + "]"; if (shortest_match.empty() || shortest_match.size() > match.size()) { shortest_match = match; } } return shortest_match; } } struct Generator { virtual std::string operator() (char, bool*, char) = 0; }; // 0123456789 should be omitted from require variable as trivally constructibles struct NumberGenerator : Generator { static constexpr const char* generate = "0123456789"; static constexpr const char* require = ""; std::string operator() (char value, bool* /*cannot_use*/, char /*forbidden*/) override { return number_repr(value-'0') + "+[]"; } }; struct UndefinedGenerator : Generator { static constexpr const char* generate = "undefi"; static constexpr const char* require = ""; std::string operator() (char value, bool* /*cannot_use*/, char /*forbidden*/) override { return from_known(value, "undefined", "[][+[]]"); } }; struct NanGenerator : Generator { static constexpr const char* generate = "Na"; static constexpr const char* require = "u"; std::string operator() (char value, bool* cannot_use, char forbidden) override { return from_known(value, "NaN", "+" + char_repr('u', cannot_use, forbidden)); } }; struct SmallerNanGenerator : Generator { static constexpr const char* generate = "Na"; static constexpr const char* require = ""; std::string operator() (char value, bool* /*cannot_use*/, char forbidden) override { return forbidden != '!' ? from_known(value, "NaN", "+(![]+[])") : ""; } }; struct PlusGenerator : Generator { static constexpr const char* generate = "+"; static constexpr const char* require = "e"; std::string operator() (char value, bool* cannot_use, char forbidden) override { return from_known(value, "1e+30", "+(" + str_repr("1e30", cannot_use, forbidden) + ")"); } }; struct FindGenerator : Generator { static constexpr const char* generate = "ucto ()"; static constexpr const char* require = "find"; std::string operator() (char value, bool* cannot_use, char forbidden) override { return from_known(value, "function find()", "[][" + str_repr("find", cannot_use, forbidden) + "]"); } }; struct TrueGenerator : Generator { static constexpr const char* generate = "true"; static constexpr const char* require = ""; std::string operator() (char value, bool* /*cannot_use*/, char forbidden) override { return forbidden != '!' ? from_known(value, "true", "!![]") : ""; } }; struct FalseGenerator : Generator { static constexpr const char* generate = "false"; static constexpr const char* require = ""; std::string operator() (char value, bool* /*cannot_use*/, char forbidden) override { return forbidden != '!' ? from_known(value, "false", "![]") : ""; } }; struct InfinityGenerator : Generator { static constexpr const char* generate = "Infity"; static constexpr const char* require = "e"; std::string operator() (char value, bool* cannot_use, char forbidden) override { return from_known(value, "Infinity", "+(" + str_repr("1e1000", cannot_use, forbidden) + ")"); } }; struct SquareBracketGenerator : Generator { static constexpr const char* generate = "[objct AayIa]"; static constexpr const char* require = "entris"; std::string operator() (char value, bool* cannot_use, char forbidden) override { return from_known(value, "[object Array Iterator]", "[][" + str_repr("entries", cannot_use, forbidden) + "]"); } }; struct ClassArrayGenerator : Generator { static constexpr const char* generate = "fi Aay()"; static constexpr const char* require = "constru"; std::string operator() (char value, bool* cannot_use, char forbidden) override { return from_known(value, "function Array()", "[][" + str_repr("constructor", cannot_use, forbidden) + "]"); } }; struct ClassBooleanGenerator : Generator { static constexpr const char* generate = "fi Blea()"; static constexpr const char* require = "constru"; std::string operator() (char value, bool* cannot_use, char forbidden) override { return from_known(value, "function Boolean()", "(![])[" + str_repr("constructor", cannot_use, forbidden) + "]"); } }; struct ClassNumberGenerator : Generator { static constexpr const char* generate = "fi Nmbe()"; static constexpr const char* require = "constru"; std::string operator() (char value, bool* cannot_use, char forbidden) override { return from_known(value, "function Number()", "(+[])[" + str_repr("constructor", cannot_use, forbidden) + "]"); } }; struct ClassStringGenerator : Generator { static constexpr const char* generate = "fi Sg()"; static constexpr const char* require = "constru"; std::string operator() (char value, bool* cannot_use, char forbidden) override { return from_known(value, "function String()", "([]+[])[" + str_repr("constructor", cannot_use, forbidden) + "]"); } }; struct ClassFunctionGenerator : Generator { static constexpr const char* generate = " F()"; static constexpr const char* require = "construfid"; std::string operator() (char value, bool* cannot_use, char forbidden) override { return from_known(value, "function Function()", "[][" + str_repr("find", cannot_use, forbidden) + "][" + str_repr("constructor", cannot_use, forbidden) + "]"); } }; struct NumberInBaseGenerator : Generator { static constexpr const char* generate = "abcdefhjklmpqsuvwxyz"; static constexpr const char* require = "toSring"; std::string operator() (char value, bool* cannot_use, char forbidden) override { int base = 11 + value -'a'; if (base <= 30) { // max is 36 base = ((int)(base/10) +1) * 10; } return "(" + number_repr(10 + value -'a') + ")[" + str_repr("toString", cannot_use, forbidden) + "](" + number_repr(base) + ")"; } }; struct CGenerator : Generator { static constexpr const char* generate = "C"; static constexpr const char* require = "findconstructorreturn atob(arguments[])N"; std::string operator() (char, bool* cannot_use, char forbidden) override { return "[][" + str_repr("find", cannot_use, forbidden) + "][" + str_repr("constructor", cannot_use, forbidden) + "](" + str_repr("return atob(arguments[0])", cannot_use, forbidden) + ")(" + str_repr("20N", cannot_use, forbidden) + ")[" + number_repr(1) + "]"; } }; struct AllGenerator : Generator { static constexpr const char* require = "construfmChade";// and also ! std::string operator() (char value, bool* cannot_use, char forbidden) override { return "([]+[])[" + str_repr("constructor", cannot_use, forbidden) + "][" + str_repr("fromCharCode", cannot_use, forbidden) + "](" + number_repr((int)value) + ")"; } }; template <class Gen> void push_dependency(auto&& tree, char c) { constexpr const char* str = Gen::require; #ifdef _DEBUG std::cout << " (" << ((int)c) << ")'" << c << "' requires \"" << str << "\"" << std::endl; #endif tree[c - CHAR_MIN].emplace_back(str, std::make_unique<Gen>()); } template <class Gen> void push_dependencies(auto&& tree) { for (auto it = Gen::generate ; !!*it ; ++it) { push_dependency<Gen>(tree, *it); } } auto build_dependency_tree() { // for each char we declare the list of all the available Generator able to build it // give nthe definition of required entries // eg.: // '[' -> [ (find), call [].find ] std::vector< std::vector< std::pair<std::string, std::unique_ptr<Generator>> > > tree(256); #ifdef _DEBUG std::cout << "Start build_dependency_tree" << std::endl; #endif push_dependencies<NumberGenerator>(tree); push_dependencies<UndefinedGenerator>(tree); push_dependencies<NanGenerator>(tree); push_dependencies<SmallerNanGenerator>(tree); push_dependencies<PlusGenerator>(tree); push_dependencies<FindGenerator>(tree); push_dependencies<TrueGenerator>(tree); push_dependencies<FalseGenerator>(tree); push_dependencies<InfinityGenerator>(tree); push_dependencies<SquareBracketGenerator>(tree); push_dependencies<ClassArrayGenerator>(tree); push_dependencies<ClassBooleanGenerator>(tree); push_dependencies<ClassNumberGenerator>(tree); push_dependencies<ClassStringGenerator>(tree); push_dependencies<ClassFunctionGenerator>(tree); push_dependencies<NumberInBaseGenerator>(tree); push_dependencies<CGenerator>(tree); push_dependencies<NumberInBaseGenerator>(tree); push_dependencies<ClassNumberGenerator>(tree); push_dependencies<ClassStringGenerator>(tree); push_dependencies<ClassFunctionGenerator>(tree); push_dependencies<NumberInBaseGenerator>(tree); push_dependencies<CGenerator>(tree); for (int c = (int)CHAR_MIN ; c <= (int)CHAR_MAX ; ++c) { unsigned idx = c - CHAR_MIN; if (tree[idx].empty()) { push_dependency<AllGenerator>(tree, (char)c); } } #ifdef _DEBUG std::cout << "End build_dependency_tree" << std::endl; #endif return tree; } std::string char_repr(char value, bool* cannot_use, char forbidden) { static const auto tree = build_dependency_tree(); #ifdef _DEBUG std::cout << "Generating (" << ((int)value) << ")'" << value << "'"; if (forbidden) std::cout << " with forbidden (" << ((int)forbidden) << ")'" << forbidden << "'"; std::cout << std::endl; #endif auto const& choices = tree[value - CHAR_MIN]; #ifdef _DEBUG std::cout << " # " << choices.size() << " candidates" << std::endl; #endif // Keep only generators that can be used (do no require stuff being computed) std::vector<Generator*> generators; for (auto const& choice : choices) { std::string const& require = choice.first; #ifdef _DEBUG std::cout << " candidate with require: " << require << std::endl; #endif if (std::find_if(require.begin(), require.end(), [cannot_use](auto c) { return cannot_use[c - CHAR_MIN]; }) == require.end()) { generators.push_back(choice.second.get()); } } #ifdef _DEBUG std::cout << " # " << generators.size() << " selected" << std::endl; #endif // Find the best match cannot_use[value - CHAR_MIN] = true; std::string best_match; for (auto gen : generators) { std::string match = gen->operator()(value, cannot_use, forbidden); #ifdef _DEBUG std::cout << " :(" << ((int)value) << ")'" << value << "': " << match << std::endl; #endif if (best_match.empty() || best_match.size() > match.size()) { best_match = match; } } cannot_use[value - CHAR_MIN] = false; return best_match; } std::string char_repr(char value) { bool tab[CHAR_MAX-CHAR_MIN] = { 0 }; std::fill(std::begin(tab), std::end(tab), false); return char_repr(value, tab, '\0'); } std::string str_repr(const char* str, bool* cannot_use, char forbidden) { std::string out {}; for (auto it = str ; *it ; ++it) { if (cannot_use[*it - CHAR_MIN]) { return out; } } for (auto it = str ; *it ; ++it) { if (it != str) { out += '+'; } out += '('; auto forchar = char_repr(*it, cannot_use, forbidden); if (forchar.empty()) { return ""; } out += forchar; out += ')'; } return out; } std::string str_repr(std::string const& in, bool* cannot_use, char forbidden) { return str_repr(in.c_str(), cannot_use, forbidden); } std::string str_repr(const char* str) { bool tab[CHAR_MAX-CHAR_MIN] = { 0 }; std::fill(std::begin(tab), std::end(tab), false); return str_repr(str, tab, '\0'); } std::string str_repr(std::string const& in) { return str_repr(in.c_str()); } std::string run_command(const char* str) { return std::string("[][") + str_repr("constructor") + "][" + str_repr("constructor") + "](" + str_repr(str) + ")()"; } std::string run_command(std::string const& in) { return run_command(in.c_str()); } <commit_msg>Fix partial computations issues<commit_after>//#define _DEBUG #include <algorithm> #include <climits> #include <cstddef> #include <memory> #include <string> #include <vector> #ifdef _DEBUG #include <iostream> #include <typeinfo> #endif #include "js6chars.hpp" std::string char_repr(char value, bool* cannot_use, char forbidden); std::string str_repr(const char* str, bool* cannot_use, char forbidden); std::string str_repr(std::string const& in, bool* cannot_use, char forbidden); static std::string small_number_repr(int value) { return value == 0 ? "+[]" : value == 1 ? "++[[]][+[]]" : "++[" + number_repr(value -1) + "][+[]]"; } static std::string number_repr_helper(int value) { if (value < 10) return small_number_repr(value) + "+[]"; return number_repr_helper(value/10) + "+(" + small_number_repr(value%10) + ")"; } std::string number_repr(int value) { if (value < 0) { return std::string("+(") + char_repr('-') + "+(" + number_repr_helper(-value) + "))"; } return value < 10 ? small_number_repr(value) : std::string("+(") + number_repr_helper(value) + ")"; } namespace { template <std::size_t N> std::string from_known(char value, const char (&real_str)[N], std::string&& generated) { std::string shortest_match; char const* it = std::find(std::begin(real_str), std::end(real_str), value); for ( ; it != std::end(real_str) ; it = std::find(std::next(it), std::end(real_str), value)) { std::string match = "(" + generated + "+[])" + "[" + number_repr((int)(it - real_str)) + "]"; if (shortest_match.empty() || shortest_match.size() > match.size()) { shortest_match = match; } } return shortest_match; } } struct Generator { virtual std::string operator() (char, bool*, char) = 0; }; // 0123456789 should be omitted from require variable as trivally constructibles struct NumberGenerator : Generator { static constexpr const char* generate = "0123456789"; static constexpr const char* require = ""; std::string operator() (char value, bool* /*cannot_use*/, char /*forbidden*/) override { return number_repr(value-'0') + "+[]"; } }; struct UndefinedGenerator : Generator { static constexpr const char* generate = "undefi"; static constexpr const char* require = ""; std::string operator() (char value, bool* /*cannot_use*/, char /*forbidden*/) override { return from_known(value, "undefined", "[][+[]]"); } }; struct NanGenerator : Generator { static constexpr const char* generate = "Na"; static constexpr const char* require = "u"; std::string operator() (char value, bool* cannot_use, char forbidden) override { return from_known(value, "NaN", "+" + char_repr('u', cannot_use, forbidden)); } }; struct SmallerNanGenerator : Generator { static constexpr const char* generate = "Na"; static constexpr const char* require = ""; std::string operator() (char value, bool* /*cannot_use*/, char forbidden) override { return forbidden != '!' ? from_known(value, "NaN", "+(![]+[])") : ""; } }; struct PlusGenerator : Generator { static constexpr const char* generate = "+"; static constexpr const char* require = "e"; std::string operator() (char value, bool* cannot_use, char forbidden) override { std::string data = str_repr("1e30", cannot_use, forbidden); return data.empty() ? "" : from_known(value, "1e+30", "+(" + data + ")"); } }; struct FindGenerator : Generator { static constexpr const char* generate = "ucto ()"; static constexpr const char* require = "find"; std::string operator() (char value, bool* cannot_use, char forbidden) override { std::string data = str_repr("find", cannot_use, forbidden); return data.empty() ? "" : from_known(value, "function find()", "[][" + data + "]"); } }; struct TrueGenerator : Generator { static constexpr const char* generate = "true"; static constexpr const char* require = ""; std::string operator() (char value, bool* /*cannot_use*/, char forbidden) override { return forbidden != '!' ? from_known(value, "true", "!![]") : ""; } }; struct FalseGenerator : Generator { static constexpr const char* generate = "false"; static constexpr const char* require = ""; std::string operator() (char value, bool* /*cannot_use*/, char forbidden) override { return forbidden != '!' ? from_known(value, "false", "![]") : ""; } }; struct InfinityGenerator : Generator { static constexpr const char* generate = "Infity"; static constexpr const char* require = "e"; std::string operator() (char value, bool* cannot_use, char forbidden) override { std::string data = str_repr("1e1000", cannot_use, forbidden); return data.empty() ? "" : from_known(value, "Infinity", "+(" + data + ")"); } }; struct SquareBracketGenerator : Generator { static constexpr const char* generate = "[objct AayIa]"; static constexpr const char* require = "entris"; std::string operator() (char value, bool* cannot_use, char forbidden) override { std::string data = str_repr("entries", cannot_use, forbidden); return data.empty() ? "" : from_known(value, "[object Array Iterator]", "[][" + data + "]"); } }; struct ClassArrayGenerator : Generator { static constexpr const char* generate = "fi Aay()"; static constexpr const char* require = "constru"; std::string operator() (char value, bool* cannot_use, char forbidden) override { std::string data = str_repr("constructor", cannot_use, forbidden); return data.empty() ? "" : from_known(value, "function Array()", "[][" + data + "]"); } }; struct ClassBooleanGenerator : Generator { static constexpr const char* generate = "fi Blea()"; static constexpr const char* require = "constru"; std::string operator() (char value, bool* cannot_use, char forbidden) override { std::string data = str_repr("constructor", cannot_use, forbidden); return data.empty() ? "" : from_known(value, "function Boolean()", "(![])[" + data + "]"); } }; struct ClassNumberGenerator : Generator { static constexpr const char* generate = "fi Nmbe()"; static constexpr const char* require = "constru"; std::string operator() (char value, bool* cannot_use, char forbidden) override { std::string data = str_repr("constructor", cannot_use, forbidden); return data.empty() ? "" : from_known(value, "function Number()", "(+[])[" + data + "]"); } }; struct ClassStringGenerator : Generator { static constexpr const char* generate = "fi Sg()"; static constexpr const char* require = "constru"; std::string operator() (char value, bool* cannot_use, char forbidden) override { std::string data = str_repr("constructor", cannot_use, forbidden); return data.empty() ? "" : from_known(value, "function String()", "([]+[])[" + data + "]"); } }; struct ClassFunctionGenerator : Generator { static constexpr const char* generate = " F()"; static constexpr const char* require = "construfid"; std::string operator() (char value, bool* cannot_use, char forbidden) override { std::string method_label = str_repr("find", cannot_use, forbidden); std::string constructor = str_repr("constructor", cannot_use, forbidden); return method_label.empty() || constructor.empty() ? "" : from_known(value, "function Function()", "[][" + method_label + "][" + constructor + "]"); } }; struct NumberInBaseGenerator : Generator { static constexpr const char* generate = "abcdefhjklmpqsuvwxyz"; static constexpr const char* require = "toSring"; std::string operator() (char value, bool* cannot_use, char forbidden) override { int base = 11 + value -'a'; if (base <= 30) { // max is 36 base = ((int)(base/10) +1) * 10; } std::string data = str_repr("toString", cannot_use, forbidden); return data.empty() ? "" : "(" + number_repr(10 + value -'a') + ")[" + data + "](" + number_repr(base) + ")"; } }; struct CGenerator : Generator { static constexpr const char* generate = "C"; static constexpr const char* require = "findconstructorreturn atob(arguments[])N"; std::string operator() (char, bool* cannot_use, char forbidden) override { std::string method_label = str_repr("find", cannot_use, forbidden); std::string constructor = str_repr("constructor", cannot_use, forbidden); std::string running_code = str_repr("return atob(arguments[0])", cannot_use, forbidden); std::string parameter = str_repr("20N", cannot_use, forbidden); return method_label.empty() || constructor.empty() || running_code.empty() || parameter.empty() ? "" : "[][" + method_label + "][" + constructor + "](" + running_code + ")(" + parameter + ")[" + number_repr(1) + "]"; } }; struct AllGenerator : Generator { static constexpr const char* require = "construfmChade";// and also ! std::string operator() (char value, bool* cannot_use, char forbidden) override { std::string constructor = str_repr("constructor", cannot_use, forbidden); std::string method_charcode = str_repr("fromCharCode", cannot_use, forbidden); return constructor.empty() || method_charcode.empty() ? "" : "([]+[])[" + constructor + "][" + method_charcode + "](" + number_repr((int)value) + ")"; } }; template <class Gen> void push_dependency(auto&& tree, char c) { constexpr const char* str = Gen::require; #ifdef _DEBUG std::cout << " (" << ((int)c) << ")'" << c << "' requires \"" << str << "\"" << std::endl; #endif tree[c - CHAR_MIN].emplace_back(str, std::make_unique<Gen>()); } template <class Gen> void push_dependencies(auto&& tree) { for (auto it = Gen::generate ; !!*it ; ++it) { push_dependency<Gen>(tree, *it); } } auto build_dependency_tree() { // for each char we declare the list of all the available Generator able to build it // give nthe definition of required entries // eg.: // '[' -> [ (find), call [].find ] std::vector< std::vector< std::pair<std::string, std::unique_ptr<Generator>> > > tree(256); #ifdef _DEBUG std::cout << "Start build_dependency_tree" << std::endl; #endif push_dependencies<NumberGenerator>(tree); push_dependencies<UndefinedGenerator>(tree); push_dependencies<NanGenerator>(tree); push_dependencies<SmallerNanGenerator>(tree); push_dependencies<PlusGenerator>(tree); push_dependencies<FindGenerator>(tree); push_dependencies<TrueGenerator>(tree); push_dependencies<FalseGenerator>(tree); push_dependencies<InfinityGenerator>(tree); push_dependencies<SquareBracketGenerator>(tree); push_dependencies<ClassArrayGenerator>(tree); push_dependencies<ClassBooleanGenerator>(tree); push_dependencies<ClassNumberGenerator>(tree); push_dependencies<ClassStringGenerator>(tree); push_dependencies<ClassFunctionGenerator>(tree); push_dependencies<NumberInBaseGenerator>(tree); push_dependencies<CGenerator>(tree); push_dependencies<NumberInBaseGenerator>(tree); push_dependencies<ClassNumberGenerator>(tree); push_dependencies<ClassStringGenerator>(tree); push_dependencies<ClassFunctionGenerator>(tree); push_dependencies<NumberInBaseGenerator>(tree); push_dependencies<CGenerator>(tree); for (int c = (int)CHAR_MIN ; c <= (int)CHAR_MAX ; ++c) { unsigned idx = c - CHAR_MIN; if (tree[idx].empty()) { push_dependency<AllGenerator>(tree, (char)c); } } #ifdef _DEBUG std::cout << "End build_dependency_tree" << std::endl; #endif return tree; } std::string char_repr(char value, bool* cannot_use, char forbidden) { static const auto tree = build_dependency_tree(); #ifdef _DEBUG unsigned iter_id = std::count(cannot_use, cannot_use+256, true); for (unsigned i {} ; i != iter_id ; ++i) { std::cout << " "; } std::cout << "Generating (" << ((int)value) << ")'" << value << "'"; if (forbidden) std::cout << " with forbidden (" << ((int)forbidden) << ")'" << forbidden << "'"; std::cout << std::endl; #endif auto const& choices = tree[value - CHAR_MIN]; #ifdef _DEBUG for (unsigned i {} ; i != iter_id ; ++i) { std::cout << " "; } std::cout << " # " << choices.size() << " candidates" << std::endl; #endif // Keep only generators that can be used (do no require stuff being computed) std::vector<Generator*> generators; for (auto const& choice : choices) { std::string const& require = choice.first; if (std::find_if(require.begin(), require.end(), [cannot_use](auto c) { return cannot_use[c - CHAR_MIN]; }) == require.end()) { generators.push_back(choice.second.get()); } } #ifdef _DEBUG for (unsigned i {} ; i != iter_id ; ++i) { std::cout << " "; } std::cout << " # " << generators.size() << " selected" << std::endl; #endif // Find the best match cannot_use[value - CHAR_MIN] = true; std::string best_match; for (auto gen : generators) { #ifdef _DEBUG for (unsigned i {} ; i != iter_id ; ++i) { std::cout << " "; } std::cout << " :using generator <" << typeid(*gen).name() << ">" << std::endl; #endif std::string match = gen->operator()(value, cannot_use, forbidden); #ifdef _DEBUG for (unsigned i {} ; i != iter_id ; ++i) { std::cout << " "; } std::cout << " :(" << ((int)value) << ")'" << value << "': <" << typeid(*gen).name() << "> : " << match << std::endl; #endif if (best_match.empty() || (best_match.size() > match.size() && ! match.empty())) { best_match = match; } } cannot_use[value - CHAR_MIN] = false; return best_match; } std::string char_repr(char value) { bool tab[CHAR_MAX-CHAR_MIN] = { 0 }; std::fill(std::begin(tab), std::end(tab), false); return char_repr(value, tab, '\0'); } std::string str_repr(const char* str, bool* cannot_use, char forbidden) { std::string out {}; for (auto it = str ; *it ; ++it) { if (cannot_use[*it - CHAR_MIN]) { return out; } } for (auto it = str ; *it ; ++it) { if (it != str) { out += '+'; } out += '('; auto forchar = char_repr(*it, cannot_use, forbidden); if (forchar.empty()) { return ""; } out += forchar; out += ')'; } return out; } std::string str_repr(std::string const& in, bool* cannot_use, char forbidden) { return str_repr(in.c_str(), cannot_use, forbidden); } std::string str_repr(const char* str) { bool tab[CHAR_MAX-CHAR_MIN] = { 0 }; std::fill(std::begin(tab), std::end(tab), false); return str_repr(str, tab, '\0'); } std::string str_repr(std::string const& in) { return str_repr(in.c_str()); } std::string run_command(const char* str) { return std::string("[][") + str_repr("constructor") + "][" + str_repr("constructor") + "](" + str_repr(str) + ")()"; } std::string run_command(std::string const& in) { return run_command(in.c_str()); } <|endoftext|>
<commit_before>#include "common/params.h" #ifndef _GNU_SOURCE #define _GNU_SOURCE #endif // _GNU_SOURCE #include <stdio.h> #include <stdlib.h> #include <unistd.h> #include <dirent.h> #include <sys/file.h> #include <sys/stat.h> #include <map> #include <string> #include <string.h> #include "common/util.h" #include "common/utilpp.h" namespace { template <typename T> T* null_coalesce(T* a, T* b) { return a != NULL ? a : b; } static const char* default_params_path = null_coalesce(const_cast<const char*>(getenv("PARAMS_PATH")), "/data/params"); #ifdef QCOM static const char* persistent_params_path = null_coalesce(const_cast<const char*>(getenv("PERSISTENT_PARAMS_PATH")), "/persist/comma/params"); #else static const char* persistent_params_path = default_params_path; #endif } //namespace static int fsync_dir(const char* path){ int result = 0; int fd = open(path, O_RDONLY); if (fd < 0){ result = -1; goto cleanup; } result = fsync(fd); if (result < 0) { goto cleanup; } cleanup: int result_close = 0; if (fd >= 0){ result_close = close(fd); } if (result_close < 0) { return result_close; } else { return result; } } static int ensure_dir_exists(const char* path) { struct stat st; if (stat(path, &st) == -1) { return mkdir(path, 0700); } return 0; } int write_db_value(const char* key, const char* value, size_t value_size, bool persistent_param) { // Information about safely and atomically writing a file: https://lwn.net/Articles/457667/ // 1) Create temp file // 2) Write data to temp file // 3) fsync() the temp file // 4) rename the temp file to the real name // 5) fsync() the containing directory int lock_fd = -1; int tmp_fd = -1; int result; char tmp_path[1024]; char path[1024]; char *tmp_dir; ssize_t bytes_written; const char* params_path = persistent_param ? persistent_params_path : default_params_path; // Make sure params path exists result = ensure_dir_exists(params_path); if (result < 0) { goto cleanup; } result = snprintf(path, sizeof(path), "%s/d", params_path); if (result < 0) { goto cleanup; } // See if the symlink exists, otherwise create it struct stat st; if (stat(path, &st) == -1) { // Create temp folder result = snprintf(path, sizeof(path), "%s/.tmp_XXXXXX", params_path); if (result < 0) { goto cleanup; } tmp_dir = mkdtemp(path); if (tmp_dir == NULL){ goto cleanup; } // Set permissions result = chmod(tmp_dir, 0777); if (result < 0) { goto cleanup; } // Symlink it to temp link result = snprintf(tmp_path, sizeof(tmp_path), "%s.link", tmp_dir); if (result < 0) { goto cleanup; } result = symlink(tmp_dir, tmp_path); if (result < 0) { goto cleanup; } // Move symlink to <params>/d result = snprintf(path, sizeof(path), "%s/d", params_path); if (result < 0) { goto cleanup; } result = rename(tmp_path, path); if (result < 0) { goto cleanup; } } // Write value to temp. result = snprintf(tmp_path, sizeof(tmp_path), "%s/.tmp_value_XXXXXX", params_path); if (result < 0) { goto cleanup; } tmp_fd = mkstemp(tmp_path); bytes_written = write(tmp_fd, value, value_size); if (bytes_written != value_size) { result = -20; goto cleanup; } // Build lock path result = snprintf(path, sizeof(path), "%s/.lock", params_path); if (result < 0) { goto cleanup; } lock_fd = open(path, O_CREAT); // Build key path result = snprintf(path, sizeof(path), "%s/d/%s", params_path, key); if (result < 0) { goto cleanup; } // Take lock. result = flock(lock_fd, LOCK_EX); if (result < 0) { goto cleanup; } // change permissions to 0666 for apks result = fchmod(tmp_fd, 0666); if (result < 0) { goto cleanup; } // fsync to force persist the changes. result = fsync(tmp_fd); if (result < 0) { goto cleanup; } // Move temp into place. result = rename(tmp_path, path); if (result < 0) { goto cleanup; } // fsync parent directory result = snprintf(path, sizeof(path), "%s/d", params_path); if (result < 0) { goto cleanup; } result = fsync_dir(path); if (result < 0) { goto cleanup; } cleanup: // Release lock. if (lock_fd >= 0) { close(lock_fd); } if (tmp_fd >= 0) { if (result < 0) { remove(tmp_path); } close(tmp_fd); } return result; } int delete_db_value(const char* key, bool persistent_param) { int lock_fd = -1; int result; char path[1024]; const char* params_path = persistent_param ? persistent_params_path : default_params_path; // Build lock path, and open lockfile result = snprintf(path, sizeof(path), "%s/.lock", params_path); if (result < 0) { goto cleanup; } lock_fd = open(path, O_CREAT); // Take lock. result = flock(lock_fd, LOCK_EX); if (result < 0) { goto cleanup; } // Build key path result = snprintf(path, sizeof(path), "%s/d/%s", params_path, key); if (result < 0) { goto cleanup; } // Delete value. result = remove(path); if (result != 0) { result = ERR_NO_VALUE; goto cleanup; } // fsync parent directory result = snprintf(path, sizeof(path), "%s/d", params_path); if (result < 0) { goto cleanup; } result = fsync_dir(path); if (result < 0) { goto cleanup; } cleanup: // Release lock. if (lock_fd >= 0) { close(lock_fd); } return result; } int read_db_value(const char* key, char** value, size_t* value_sz, bool persistent_param) { char path[1024]; const char* params_path = persistent_param ? persistent_params_path : default_params_path; int result = snprintf(path, sizeof(path), "%s/d/%s", params_path, key); if (result < 0) { return result; } *value = static_cast<char*>(read_file(path, value_sz)); if (*value == NULL) { return -22; } return 0; } void read_db_value_blocking(const char* key, char** value, size_t* value_sz, bool persistent_param) { while (1) { const int result = read_db_value(key, value, value_sz, persistent_param); if (result == 0) { return; } else { // Sleep for 0.1 seconds. usleep(100000); } } } int read_db_all(std::map<std::string, std::string> *params, bool persistent_param) { int err = 0; const char* params_path = persistent_param ? persistent_params_path : default_params_path; std::string lock_path = util::string_format("%s/.lock", params_path); int lock_fd = open(lock_path.c_str(), 0); if (lock_fd < 0) return -1; err = flock(lock_fd, LOCK_SH); if (err < 0) return err; std::string key_path = util::string_format("%s/d", params_path); DIR *d = opendir(key_path.c_str()); if (!d) { close(lock_fd); return -1; } struct dirent *de = NULL; while ((de = readdir(d))) { if (!isalnum(de->d_name[0])) continue; std::string key = std::string(de->d_name); std::string value = util::read_file(util::string_format("%s/%s", key_path.c_str(), key.c_str())); (*params)[key] = value; } closedir(d); close(lock_fd); return 0; } std::vector<char> read_db_bytes(const char* param_name, bool persistent_param) { std::vector<char> bytes; char* value; size_t sz; int result = read_db_value(param_name, &value, &sz, persistent_param); if (result == 0) { bytes.assign(value, value+sz); free(value); } return bytes; } bool read_db_bool(const char* param_name, bool persistent_param) { std::vector<char> bytes = read_db_bytes(param_name, persistent_param); return bytes.size() > 0 and bytes[0] == '1'; } <commit_msg>close lock_fd if flock failed (#2231)<commit_after>#include "common/params.h" #ifndef _GNU_SOURCE #define _GNU_SOURCE #endif // _GNU_SOURCE #include <stdio.h> #include <stdlib.h> #include <unistd.h> #include <dirent.h> #include <sys/file.h> #include <sys/stat.h> #include <map> #include <string> #include <string.h> #include "common/util.h" #include "common/utilpp.h" namespace { template <typename T> T* null_coalesce(T* a, T* b) { return a != NULL ? a : b; } static const char* default_params_path = null_coalesce(const_cast<const char*>(getenv("PARAMS_PATH")), "/data/params"); #ifdef QCOM static const char* persistent_params_path = null_coalesce(const_cast<const char*>(getenv("PERSISTENT_PARAMS_PATH")), "/persist/comma/params"); #else static const char* persistent_params_path = default_params_path; #endif } //namespace static int fsync_dir(const char* path){ int result = 0; int fd = open(path, O_RDONLY); if (fd < 0){ result = -1; goto cleanup; } result = fsync(fd); if (result < 0) { goto cleanup; } cleanup: int result_close = 0; if (fd >= 0){ result_close = close(fd); } if (result_close < 0) { return result_close; } else { return result; } } static int ensure_dir_exists(const char* path) { struct stat st; if (stat(path, &st) == -1) { return mkdir(path, 0700); } return 0; } int write_db_value(const char* key, const char* value, size_t value_size, bool persistent_param) { // Information about safely and atomically writing a file: https://lwn.net/Articles/457667/ // 1) Create temp file // 2) Write data to temp file // 3) fsync() the temp file // 4) rename the temp file to the real name // 5) fsync() the containing directory int lock_fd = -1; int tmp_fd = -1; int result; char tmp_path[1024]; char path[1024]; char *tmp_dir; ssize_t bytes_written; const char* params_path = persistent_param ? persistent_params_path : default_params_path; // Make sure params path exists result = ensure_dir_exists(params_path); if (result < 0) { goto cleanup; } result = snprintf(path, sizeof(path), "%s/d", params_path); if (result < 0) { goto cleanup; } // See if the symlink exists, otherwise create it struct stat st; if (stat(path, &st) == -1) { // Create temp folder result = snprintf(path, sizeof(path), "%s/.tmp_XXXXXX", params_path); if (result < 0) { goto cleanup; } tmp_dir = mkdtemp(path); if (tmp_dir == NULL){ goto cleanup; } // Set permissions result = chmod(tmp_dir, 0777); if (result < 0) { goto cleanup; } // Symlink it to temp link result = snprintf(tmp_path, sizeof(tmp_path), "%s.link", tmp_dir); if (result < 0) { goto cleanup; } result = symlink(tmp_dir, tmp_path); if (result < 0) { goto cleanup; } // Move symlink to <params>/d result = snprintf(path, sizeof(path), "%s/d", params_path); if (result < 0) { goto cleanup; } result = rename(tmp_path, path); if (result < 0) { goto cleanup; } } // Write value to temp. result = snprintf(tmp_path, sizeof(tmp_path), "%s/.tmp_value_XXXXXX", params_path); if (result < 0) { goto cleanup; } tmp_fd = mkstemp(tmp_path); bytes_written = write(tmp_fd, value, value_size); if (bytes_written != value_size) { result = -20; goto cleanup; } // Build lock path result = snprintf(path, sizeof(path), "%s/.lock", params_path); if (result < 0) { goto cleanup; } lock_fd = open(path, O_CREAT); // Build key path result = snprintf(path, sizeof(path), "%s/d/%s", params_path, key); if (result < 0) { goto cleanup; } // Take lock. result = flock(lock_fd, LOCK_EX); if (result < 0) { goto cleanup; } // change permissions to 0666 for apks result = fchmod(tmp_fd, 0666); if (result < 0) { goto cleanup; } // fsync to force persist the changes. result = fsync(tmp_fd); if (result < 0) { goto cleanup; } // Move temp into place. result = rename(tmp_path, path); if (result < 0) { goto cleanup; } // fsync parent directory result = snprintf(path, sizeof(path), "%s/d", params_path); if (result < 0) { goto cleanup; } result = fsync_dir(path); if (result < 0) { goto cleanup; } cleanup: // Release lock. if (lock_fd >= 0) { close(lock_fd); } if (tmp_fd >= 0) { if (result < 0) { remove(tmp_path); } close(tmp_fd); } return result; } int delete_db_value(const char* key, bool persistent_param) { int lock_fd = -1; int result; char path[1024]; const char* params_path = persistent_param ? persistent_params_path : default_params_path; // Build lock path, and open lockfile result = snprintf(path, sizeof(path), "%s/.lock", params_path); if (result < 0) { goto cleanup; } lock_fd = open(path, O_CREAT); // Take lock. result = flock(lock_fd, LOCK_EX); if (result < 0) { goto cleanup; } // Build key path result = snprintf(path, sizeof(path), "%s/d/%s", params_path, key); if (result < 0) { goto cleanup; } // Delete value. result = remove(path); if (result != 0) { result = ERR_NO_VALUE; goto cleanup; } // fsync parent directory result = snprintf(path, sizeof(path), "%s/d", params_path); if (result < 0) { goto cleanup; } result = fsync_dir(path); if (result < 0) { goto cleanup; } cleanup: // Release lock. if (lock_fd >= 0) { close(lock_fd); } return result; } int read_db_value(const char* key, char** value, size_t* value_sz, bool persistent_param) { char path[1024]; const char* params_path = persistent_param ? persistent_params_path : default_params_path; int result = snprintf(path, sizeof(path), "%s/d/%s", params_path, key); if (result < 0) { return result; } *value = static_cast<char*>(read_file(path, value_sz)); if (*value == NULL) { return -22; } return 0; } void read_db_value_blocking(const char* key, char** value, size_t* value_sz, bool persistent_param) { while (1) { const int result = read_db_value(key, value, value_sz, persistent_param); if (result == 0) { return; } else { // Sleep for 0.1 seconds. usleep(100000); } } } int read_db_all(std::map<std::string, std::string> *params, bool persistent_param) { int err = 0; const char* params_path = persistent_param ? persistent_params_path : default_params_path; std::string lock_path = util::string_format("%s/.lock", params_path); int lock_fd = open(lock_path.c_str(), 0); if (lock_fd < 0) return -1; err = flock(lock_fd, LOCK_SH); if (err < 0) { close(lock_fd); return err; } std::string key_path = util::string_format("%s/d", params_path); DIR *d = opendir(key_path.c_str()); if (!d) { close(lock_fd); return -1; } struct dirent *de = NULL; while ((de = readdir(d))) { if (!isalnum(de->d_name[0])) continue; std::string key = std::string(de->d_name); std::string value = util::read_file(util::string_format("%s/%s", key_path.c_str(), key.c_str())); (*params)[key] = value; } closedir(d); close(lock_fd); return 0; } std::vector<char> read_db_bytes(const char* param_name, bool persistent_param) { std::vector<char> bytes; char* value; size_t sz; int result = read_db_value(param_name, &value, &sz, persistent_param); if (result == 0) { bytes.assign(value, value+sz); free(value); } return bytes; } bool read_db_bool(const char* param_name, bool persistent_param) { std::vector<char> bytes = read_db_bytes(param_name, persistent_param); return bytes.size() > 0 and bytes[0] == '1'; } <|endoftext|>
<commit_before>#include <stdio.h> #include <stdlib.h> #include "common/visionbuf.h" #include "common/visionipc.h" #include "common/swaglog.h" #include "models/driving.h" volatile sig_atomic_t do_exit = 0; static void set_do_exit(int sig) { do_exit = 1; } // globals bool run_model; mat3 cur_transform; pthread_mutex_t transform_lock; void* live_thread(void *arg) { int err; set_thread_name("live"); Context * c = Context::create(); SubSocket * live_calibration_sock = SubSocket::create(c, "liveCalibration"); assert(live_calibration_sock != NULL); Poller * poller = Poller::create({live_calibration_sock}); /* import numpy as np from common.transformations.model import medmodel_frame_from_road_frame medmodel_frame_from_ground = medmodel_frame_from_road_frame[:, (0, 1, 3)] ground_from_medmodel_frame = np.linalg.inv(medmodel_frame_from_ground) */ Eigen::Matrix<float, 3, 3> ground_from_medmodel_frame; ground_from_medmodel_frame << 0.00000000e+00, 0.00000000e+00, 1.00000000e+00, -1.09890110e-03, 0.00000000e+00, 2.81318681e-01, -1.84808520e-20, 9.00738606e-04,-4.28751576e-02; Eigen::Matrix<float, 3, 3> eon_intrinsics; eon_intrinsics << 910.0, 0.0, 582.0, 0.0, 910.0, 437.0, 0.0, 0.0, 1.0; while (!do_exit) { for (auto sock : poller->poll(10)){ Message * msg = sock->receive(); auto amsg = kj::heapArray<capnp::word>((msg->getSize() / sizeof(capnp::word)) + 1); memcpy(amsg.begin(), msg->getData(), msg->getSize()); capnp::FlatArrayMessageReader cmsg(amsg); cereal::Event::Reader event = cmsg.getRoot<cereal::Event>(); if (event.isLiveCalibration()) { pthread_mutex_lock(&transform_lock); auto extrinsic_matrix = event.getLiveCalibration().getExtrinsicMatrix(); Eigen::Matrix<float, 3, 4> extrinsic_matrix_eigen; for (int i = 0; i < 4*3; i++){ extrinsic_matrix_eigen(i / 4, i % 4) = extrinsic_matrix[i]; } auto camera_frame_from_road_frame = eon_intrinsics * extrinsic_matrix_eigen; Eigen::Matrix<float, 3, 3> camera_frame_from_ground; camera_frame_from_ground.col(0) = camera_frame_from_road_frame.col(0); camera_frame_from_ground.col(1) = camera_frame_from_road_frame.col(1); camera_frame_from_ground.col(2) = camera_frame_from_road_frame.col(3); auto warp_matrix = camera_frame_from_ground * ground_from_medmodel_frame; for (int i=0; i<3*3; i++) { cur_transform.v[i] = warp_matrix(i / 3, i % 3); } run_model = true; pthread_mutex_unlock(&transform_lock); } delete msg; } } delete live_calibration_sock; delete poller; delete c; return NULL; } int main(int argc, char **argv) { int err; set_realtime_priority(1); // start calibration thread pthread_t live_thread_handle; err = pthread_create(&live_thread_handle, NULL, live_thread, NULL); assert(err == 0); // messaging Context *msg_context = Context::create(); PubSocket *model_sock = PubSocket::create(msg_context, "model"); PubSocket *posenet_sock = PubSocket::create(msg_context, "cameraOdometry"); SubSocket *pathplan_sock = SubSocket::create(msg_context, "pathPlan", "127.0.0.1", true); assert(model_sock != NULL); assert(posenet_sock != NULL); assert(pathplan_sock != NULL); // cl init cl_device_id device_id; cl_context context; cl_command_queue q; { // TODO: refactor this cl_platform_id platform_id[2]; cl_uint num_devices; cl_uint num_platforms; err = clGetPlatformIDs(sizeof(platform_id)/sizeof(cl_platform_id), platform_id, &num_platforms); assert(err == 0); #ifdef QCOM int clPlatform = 0; #else // don't use nvidia on pc, it's broken // TODO: write this nicely int clPlatform = num_platforms-1; #endif char cBuffer[1024]; clGetPlatformInfo(platform_id[clPlatform], CL_PLATFORM_NAME, sizeof(cBuffer), &cBuffer, NULL); LOGD("got %d opencl platform(s), using %s", num_platforms, cBuffer); err = clGetDeviceIDs(platform_id[clPlatform], CL_DEVICE_TYPE_DEFAULT, 1, &device_id, &num_devices); assert(err == 0); context = clCreateContext(NULL, 1, &device_id, NULL, NULL, &err); assert(err == 0); q = clCreateCommandQueue(context, device_id, 0, &err); assert(err == 0); } // init the models ModelState model; model_init(&model, device_id, context, true); LOGW("models loaded, modeld starting"); // debayering does a 2x downscale mat3 yuv_transform = transform_scale_buffer((mat3){{ 1.0, 0.0, 0.0, 0.0, 1.0, 0.0, 0.0, 0.0, 1.0, }}, 0.5); // loop VisionStream stream; while (!do_exit) { VisionStreamBufs buf_info; err = visionstream_init(&stream, VISION_STREAM_YUV, true, &buf_info); if (err) { printf("visionstream connect fail\n"); usleep(100000); continue; } LOGW("connected with buffer size: %d", buf_info.buf_len); // one frame in memory cl_mem yuv_cl; VisionBuf yuv_ion = visionbuf_allocate_cl(buf_info.buf_len, device_id, context, &yuv_cl); double last = 0; int desire = -1; while (!do_exit) { VIPCBuf *buf; VIPCBufExtra extra; buf = visionstream_get(&stream, &extra); if (buf == NULL) { printf("visionstream get failed\n"); break; } pthread_mutex_lock(&transform_lock); mat3 transform = cur_transform; const bool run_model_this_iter = run_model; pthread_mutex_unlock(&transform_lock); Message *msg = pathplan_sock->receive(true); if (msg != NULL) { // TODO: copy and pasted from camerad/main.cc auto amsg = kj::heapArray<capnp::word>((msg->getSize() / sizeof(capnp::word)) + 1); memcpy(amsg.begin(), msg->getData(), msg->getSize()); capnp::FlatArrayMessageReader cmsg(amsg); cereal::Event::Reader event = cmsg.getRoot<cereal::Event>(); // TODO: path planner timeout? desire = ((int)event.getPathPlan().getDesire()) - 1; delete msg; } double mt1 = 0, mt2 = 0; if (run_model_this_iter) { float vec_desire[DESIRE_LEN] = {0}; if (desire >= 0 && desire < DESIRE_LEN) { vec_desire[desire] = 1.0; } mat3 model_transform = matmul3(yuv_transform, transform); mt1 = millis_since_boot(); // TODO: don't make copies! memcpy(yuv_ion.addr, buf->addr, buf_info.buf_len); ModelDataRaw model_buf = model_eval_frame(&model, q, yuv_cl, buf_info.width, buf_info.height, model_transform, NULL, vec_desire); mt2 = millis_since_boot(); model_publish(model_sock, extra.frame_id, model_buf, extra.timestamp_eof); posenet_publish(posenet_sock, extra.frame_id, model_buf, extra.timestamp_eof); LOGD("model process: %.2fms, from last %.2fms", mt2-mt1, mt1-last); last = mt1; } } visionbuf_free(&yuv_ion); } visionstream_destroy(&stream); delete model_sock; delete posenet_sock; delete pathplan_sock; delete msg_context; model_free(&model); LOG("joining live_thread"); err = pthread_join(live_thread_handle, NULL); assert(err == 0); return 0; } <commit_msg>modeld, cleanup visionipc when recovering from fault<commit_after>#include <stdio.h> #include <stdlib.h> #include "common/visionbuf.h" #include "common/visionipc.h" #include "common/swaglog.h" #include "models/driving.h" volatile sig_atomic_t do_exit = 0; static void set_do_exit(int sig) { do_exit = 1; } // globals bool run_model; mat3 cur_transform; pthread_mutex_t transform_lock; void* live_thread(void *arg) { int err; set_thread_name("live"); Context * c = Context::create(); SubSocket * live_calibration_sock = SubSocket::create(c, "liveCalibration"); assert(live_calibration_sock != NULL); Poller * poller = Poller::create({live_calibration_sock}); /* import numpy as np from common.transformations.model import medmodel_frame_from_road_frame medmodel_frame_from_ground = medmodel_frame_from_road_frame[:, (0, 1, 3)] ground_from_medmodel_frame = np.linalg.inv(medmodel_frame_from_ground) */ Eigen::Matrix<float, 3, 3> ground_from_medmodel_frame; ground_from_medmodel_frame << 0.00000000e+00, 0.00000000e+00, 1.00000000e+00, -1.09890110e-03, 0.00000000e+00, 2.81318681e-01, -1.84808520e-20, 9.00738606e-04,-4.28751576e-02; Eigen::Matrix<float, 3, 3> eon_intrinsics; eon_intrinsics << 910.0, 0.0, 582.0, 0.0, 910.0, 437.0, 0.0, 0.0, 1.0; while (!do_exit) { for (auto sock : poller->poll(10)){ Message * msg = sock->receive(); auto amsg = kj::heapArray<capnp::word>((msg->getSize() / sizeof(capnp::word)) + 1); memcpy(amsg.begin(), msg->getData(), msg->getSize()); capnp::FlatArrayMessageReader cmsg(amsg); cereal::Event::Reader event = cmsg.getRoot<cereal::Event>(); if (event.isLiveCalibration()) { pthread_mutex_lock(&transform_lock); auto extrinsic_matrix = event.getLiveCalibration().getExtrinsicMatrix(); Eigen::Matrix<float, 3, 4> extrinsic_matrix_eigen; for (int i = 0; i < 4*3; i++){ extrinsic_matrix_eigen(i / 4, i % 4) = extrinsic_matrix[i]; } auto camera_frame_from_road_frame = eon_intrinsics * extrinsic_matrix_eigen; Eigen::Matrix<float, 3, 3> camera_frame_from_ground; camera_frame_from_ground.col(0) = camera_frame_from_road_frame.col(0); camera_frame_from_ground.col(1) = camera_frame_from_road_frame.col(1); camera_frame_from_ground.col(2) = camera_frame_from_road_frame.col(3); auto warp_matrix = camera_frame_from_ground * ground_from_medmodel_frame; for (int i=0; i<3*3; i++) { cur_transform.v[i] = warp_matrix(i / 3, i % 3); } run_model = true; pthread_mutex_unlock(&transform_lock); } delete msg; } } delete live_calibration_sock; delete poller; delete c; return NULL; } int main(int argc, char **argv) { int err; set_realtime_priority(1); // start calibration thread pthread_t live_thread_handle; err = pthread_create(&live_thread_handle, NULL, live_thread, NULL); assert(err == 0); // messaging Context *msg_context = Context::create(); PubSocket *model_sock = PubSocket::create(msg_context, "model"); PubSocket *posenet_sock = PubSocket::create(msg_context, "cameraOdometry"); SubSocket *pathplan_sock = SubSocket::create(msg_context, "pathPlan", "127.0.0.1", true); assert(model_sock != NULL); assert(posenet_sock != NULL); assert(pathplan_sock != NULL); // cl init cl_device_id device_id; cl_context context; cl_command_queue q; { // TODO: refactor this cl_platform_id platform_id[2]; cl_uint num_devices; cl_uint num_platforms; err = clGetPlatformIDs(sizeof(platform_id)/sizeof(cl_platform_id), platform_id, &num_platforms); assert(err == 0); #ifdef QCOM int clPlatform = 0; #else // don't use nvidia on pc, it's broken // TODO: write this nicely int clPlatform = num_platforms-1; #endif char cBuffer[1024]; clGetPlatformInfo(platform_id[clPlatform], CL_PLATFORM_NAME, sizeof(cBuffer), &cBuffer, NULL); LOGD("got %d opencl platform(s), using %s", num_platforms, cBuffer); err = clGetDeviceIDs(platform_id[clPlatform], CL_DEVICE_TYPE_DEFAULT, 1, &device_id, &num_devices); assert(err == 0); context = clCreateContext(NULL, 1, &device_id, NULL, NULL, &err); assert(err == 0); q = clCreateCommandQueue(context, device_id, 0, &err); assert(err == 0); } // init the models ModelState model; model_init(&model, device_id, context, true); LOGW("models loaded, modeld starting"); // debayering does a 2x downscale mat3 yuv_transform = transform_scale_buffer((mat3){{ 1.0, 0.0, 0.0, 0.0, 1.0, 0.0, 0.0, 0.0, 1.0, }}, 0.5); // loop VisionStream stream; while (!do_exit) { VisionStreamBufs buf_info; err = visionstream_init(&stream, VISION_STREAM_YUV, true, &buf_info); if (err) { printf("visionstream connect fail\n"); usleep(100000); continue; } LOGW("connected with buffer size: %d", buf_info.buf_len); // one frame in memory cl_mem yuv_cl; VisionBuf yuv_ion = visionbuf_allocate_cl(buf_info.buf_len, device_id, context, &yuv_cl); double last = 0; int desire = -1; while (!do_exit) { VIPCBuf *buf; VIPCBufExtra extra; buf = visionstream_get(&stream, &extra); if (buf == NULL) { printf("visionstream get failed\n"); visionstream_destroy(&stream); break; } pthread_mutex_lock(&transform_lock); mat3 transform = cur_transform; const bool run_model_this_iter = run_model; pthread_mutex_unlock(&transform_lock); Message *msg = pathplan_sock->receive(true); if (msg != NULL) { // TODO: copy and pasted from camerad/main.cc auto amsg = kj::heapArray<capnp::word>((msg->getSize() / sizeof(capnp::word)) + 1); memcpy(amsg.begin(), msg->getData(), msg->getSize()); capnp::FlatArrayMessageReader cmsg(amsg); cereal::Event::Reader event = cmsg.getRoot<cereal::Event>(); // TODO: path planner timeout? desire = ((int)event.getPathPlan().getDesire()) - 1; delete msg; } double mt1 = 0, mt2 = 0; if (run_model_this_iter) { float vec_desire[DESIRE_LEN] = {0}; if (desire >= 0 && desire < DESIRE_LEN) { vec_desire[desire] = 1.0; } mat3 model_transform = matmul3(yuv_transform, transform); mt1 = millis_since_boot(); // TODO: don't make copies! memcpy(yuv_ion.addr, buf->addr, buf_info.buf_len); ModelDataRaw model_buf = model_eval_frame(&model, q, yuv_cl, buf_info.width, buf_info.height, model_transform, NULL, vec_desire); mt2 = millis_since_boot(); model_publish(model_sock, extra.frame_id, model_buf, extra.timestamp_eof); posenet_publish(posenet_sock, extra.frame_id, model_buf, extra.timestamp_eof); LOGD("model process: %.2fms, from last %.2fms", mt2-mt1, mt1-last); last = mt1; } } visionbuf_free(&yuv_ion); } visionstream_destroy(&stream); delete model_sock; delete posenet_sock; delete pathplan_sock; delete msg_context; model_free(&model); LOG("joining live_thread"); err = pthread_join(live_thread_handle, NULL); assert(err == 0); return 0; } <|endoftext|>
<commit_before> #pragma once #include "quantities/parser.hpp" #include <array> #include <string> #include "quantities/astronomy.hpp" #include "quantities/dimensions.hpp" #include "quantities/named_quantities.hpp" #include "quantities/si.hpp" namespace principia { namespace quantities { namespace internal_parser { using internal_dimensions::Dimensions; using RuntimeDimensions = std::array<std::int64_t, 8>; template<typename Q> struct ExtractDimensions {}; template<> struct ExtractDimensions<double> { static constexpr RuntimeDimensions dimensions() { return {{0, 0, 0, 0, 0, 0, 0, 0}}; } }; template<std::int64_t LengthExponent, std::int64_t MassExponent, std::int64_t TimeExponent, std::int64_t CurrentExponent, std::int64_t TemperatureExponent, std::int64_t AmountExponent, std::int64_t LuminousIntensityExponent, std::int64_t AngleExponent> struct ExtractDimensions<Quantity<Dimensions<LengthExponent, MassExponent, TimeExponent, CurrentExponent, TemperatureExponent, AmountExponent, LuminousIntensityExponent, AngleExponent>>> { static constexpr RuntimeDimensions dimensions() { return {{LengthExponent, MassExponent, TimeExponent, CurrentExponent, TemperatureExponent, AmountExponent, LuminousIntensityExponent, AngleExponent}}; } }; struct Unit { template<typename Q> explicit Unit(Q const& quantity); Unit(RuntimeDimensions&& dimensions, double scale); RuntimeDimensions dimensions; double scale; }; template<typename Q> Unit::Unit(Q const& quantity) : dimensions(ExtractDimensions<Q>::dimensions()), scale(quantity / SIUnit<Q>()) {} inline Unit::Unit(RuntimeDimensions&& dimensions, double const scale) : dimensions(dimensions), scale(scale) {} inline Unit operator*(Unit const& left, Unit const& right) { RuntimeDimensions dimensions; for (std::int64_t i = 0; i < dimensions.size(); ++i) { dimensions[i] = left.dimensions[i] + right.dimensions[i]; } return {std::move(dimensions), left.scale * right.scale}; } inline Unit operator/(Unit const& left, Unit const& right) { RuntimeDimensions dimensions; for (std::int64_t i = 0; i < dimensions.size(); ++i) { dimensions[i] = left.dimensions[i] - right.dimensions[i]; } return {std::move(dimensions), left.scale / right.scale}; } inline Unit operator^(Unit const& left, int const exponent) { RuntimeDimensions dimensions; for (std::int64_t i = 0; i < dimensions.size(); ++i) { dimensions[i] = left.dimensions[i] * exponent; } return {std::move(dimensions), std::pow(left.scale, exponent)}; } inline Unit ParseUnit(std::string const& s) { // Unitless quantities. if (s == "") { return Unit(1.0); // Units of length. } else if (s == u8"μm") { return Unit(si::Micro(si::Metre)); } else if (s == "mm") { return Unit(si::Milli(si::Metre)); } else if (s == "cm") { return Unit(si::Centi(si::Metre)); } else if (s == "m") { return Unit(si::Metre); } else if (s == "km") { return Unit(si::Kilo(si::Metre)); } else if (s == u8"R🜨") { return Unit(astronomy::TerrestrialEquatorialRadius); } else if (s == u8"R☉") { return Unit(astronomy::SolarRadius); } else if (s == "au") { return Unit(astronomy::AstronomicalUnit); // Units of mass. } else if (s == "kg") { return Unit(si::Kilogram); // Units of time. } else if (s == "ms") { return Unit(si::Milli(si::Second)); } else if (s == "s") { return Unit(si::Second); } else if (s == "min") { return Unit(si::Minute); } else if (s == "h") { return Unit(si::Hour); } else if (s == "d") { return Unit(si::Day); // Units of gravitational parameter. } else if (s == u8"GGM🜨") { return Unit(astronomy::TerrestrialGravitationalParameter); } else if (s == u8"GGM☉") { return Unit(astronomy::SolarGravitationalParameter); // Units of power. } else if (s == "W") { return Unit(si::Watt); // Units of angle. } else if (s == "deg" || s == u8"°") { return Unit(si::Degree); } else if (s == "rad") { return Unit(si::Radian); // Units of solid angle. } else if (s == "sr") { return Unit(si::Steradian); } else { LOG(FATAL) << "Unsupported unit " << s; base::noreturn(); } } inline int ParseExponent(std::string const& s) { // Parse an int. char* interpreted_end; char const* const c_string = s.c_str(); int const exponent = std::strtol(c_string, &interpreted_end, /*base=*/10); int const interpreted = interpreted_end - c_string; CHECK_LT(0, interpreted) << "invalid integer number " << s; return exponent; } inline Unit ParseExponentiationUnit(std::string const& s) { int const first_caret = s.find('^'); if (first_caret == std::string::npos) { return ParseUnit(s); } else { int const first_nonblank = s.find_first_not_of(' ', first_caret + 1); CHECK_NE(std::string::npos, first_nonblank); int const last_nonblank = s.find_last_not_of(' ', first_caret - 1); CHECK_NE(std::string::npos, last_nonblank); auto const left = ParseUnit(s.substr(0, last_nonblank + 1)); auto const right = ParseExponent(s.substr(first_nonblank)); return left ^ right; } } inline Unit ParseProductUnit(std::string const& s) { // For a product we are looking for a blank character that is not next to a // carret. int first_blank; int first_nonblank; int last_nonblank; for (int start = 0;; start = first_blank + 1) { first_blank = s.find(' ', start); if (first_blank == std::string::npos) { return ParseExponentiationUnit(s); } else { first_nonblank = s.find_first_not_of(' ', first_blank + 1); last_nonblank = s.find_last_not_of(' ', first_blank - 1); if ((first_nonblank == std::string::npos || s[first_nonblank] != '^') && (last_nonblank == std::string::npos || s[last_nonblank] != '^')) { break; } } } auto const left = ParseExponentiationUnit(s.substr(0, last_nonblank + 1)); auto const right = ParseProductUnit(s.substr(first_nonblank)); return left * right; } inline Unit ParseQuotientUnit(std::string const& s) { // Look for the slash from the back to achieve proper associativity. int const last_slash = s.rfind('/'); if (last_slash == std::string::npos) { // Not a quotient. return ParseProductUnit(s); } else { // A quotient. Parse each half. int const first_nonblank = s.find_first_not_of(' ', last_slash + 1); CHECK_NE(std::string::npos, first_nonblank); int const last_nonblank = s.find_last_not_of(' ', last_slash - 1); CHECK_NE(std::string::npos, last_nonblank); auto const left = ParseQuotientUnit(s.substr(0, last_nonblank + 1)); auto const right = ParseExponentiationUnit(s.substr(first_nonblank)); return left / right; } } template<typename Q> Q ParseQuantity(std::string const& s) { // Parse a double. char* interpreted_end; char const* const c_string = s.c_str(); double const magnitude = std::strtod(c_string, &interpreted_end); int const interpreted = interpreted_end - c_string; CHECK_LT(0, interpreted) << "invalid floating-point number " << s; // Locate the unit. It may be empty for a double. int const first_nonblank = s.find_first_not_of(' ', interpreted); int const last_nonblank = s.find_last_not_of(' '); std::string unit_string; if (first_nonblank != std::string::npos) { unit_string = s.substr(first_nonblank, last_nonblank - first_nonblank + 1); } Unit const unit = ParseQuotientUnit(unit_string); CHECK(ExtractDimensions<Q>::dimensions() == unit.dimensions); return magnitude * unit.scale * SIUnit<Q>(); } } // namespace internal_parser } // namespace quantities } // namespace principia <commit_msg>not ggm<commit_after> #pragma once #include "quantities/parser.hpp" #include <array> #include <string> #include "quantities/astronomy.hpp" #include "quantities/dimensions.hpp" #include "quantities/named_quantities.hpp" #include "quantities/si.hpp" namespace principia { namespace quantities { namespace internal_parser { using internal_dimensions::Dimensions; using RuntimeDimensions = std::array<std::int64_t, 8>; template<typename Q> struct ExtractDimensions {}; template<> struct ExtractDimensions<double> { static constexpr RuntimeDimensions dimensions() { return {{0, 0, 0, 0, 0, 0, 0, 0}}; } }; template<std::int64_t LengthExponent, std::int64_t MassExponent, std::int64_t TimeExponent, std::int64_t CurrentExponent, std::int64_t TemperatureExponent, std::int64_t AmountExponent, std::int64_t LuminousIntensityExponent, std::int64_t AngleExponent> struct ExtractDimensions<Quantity<Dimensions<LengthExponent, MassExponent, TimeExponent, CurrentExponent, TemperatureExponent, AmountExponent, LuminousIntensityExponent, AngleExponent>>> { static constexpr RuntimeDimensions dimensions() { return {{LengthExponent, MassExponent, TimeExponent, CurrentExponent, TemperatureExponent, AmountExponent, LuminousIntensityExponent, AngleExponent}}; } }; struct Unit { template<typename Q> explicit Unit(Q const& quantity); Unit(RuntimeDimensions&& dimensions, double scale); RuntimeDimensions dimensions; double scale; }; template<typename Q> Unit::Unit(Q const& quantity) : dimensions(ExtractDimensions<Q>::dimensions()), scale(quantity / SIUnit<Q>()) {} inline Unit::Unit(RuntimeDimensions&& dimensions, double const scale) : dimensions(dimensions), scale(scale) {} inline Unit operator*(Unit const& left, Unit const& right) { RuntimeDimensions dimensions; for (std::int64_t i = 0; i < dimensions.size(); ++i) { dimensions[i] = left.dimensions[i] + right.dimensions[i]; } return {std::move(dimensions), left.scale * right.scale}; } inline Unit operator/(Unit const& left, Unit const& right) { RuntimeDimensions dimensions; for (std::int64_t i = 0; i < dimensions.size(); ++i) { dimensions[i] = left.dimensions[i] - right.dimensions[i]; } return {std::move(dimensions), left.scale / right.scale}; } inline Unit operator^(Unit const& left, int const exponent) { RuntimeDimensions dimensions; for (std::int64_t i = 0; i < dimensions.size(); ++i) { dimensions[i] = left.dimensions[i] * exponent; } return {std::move(dimensions), std::pow(left.scale, exponent)}; } inline Unit ParseUnit(std::string const& s) { // Unitless quantities. if (s == "") { return Unit(1.0); // Units of length. } else if (s == u8"μm") { return Unit(si::Micro(si::Metre)); } else if (s == "mm") { return Unit(si::Milli(si::Metre)); } else if (s == "cm") { return Unit(si::Centi(si::Metre)); } else if (s == "m") { return Unit(si::Metre); } else if (s == "km") { return Unit(si::Kilo(si::Metre)); } else if (s == u8"R🜨") { return Unit(astronomy::TerrestrialEquatorialRadius); } else if (s == u8"R☉") { return Unit(astronomy::SolarRadius); } else if (s == "au") { return Unit(astronomy::AstronomicalUnit); // Units of mass. } else if (s == "kg") { return Unit(si::Kilogram); // Units of time. } else if (s == "ms") { return Unit(si::Milli(si::Second)); } else if (s == "s") { return Unit(si::Second); } else if (s == "min") { return Unit(si::Minute); } else if (s == "h") { return Unit(si::Hour); } else if (s == "d") { return Unit(si::Day); // Units of gravitational parameter. } else if (s == u8"GM🜨") { return Unit(astronomy::TerrestrialGravitationalParameter); } else if (s == u8"GM☉") { return Unit(astronomy::SolarGravitationalParameter); // Units of power. } else if (s == "W") { return Unit(si::Watt); // Units of angle. } else if (s == "deg" || s == u8"°") { return Unit(si::Degree); } else if (s == "rad") { return Unit(si::Radian); // Units of solid angle. } else if (s == "sr") { return Unit(si::Steradian); } else { LOG(FATAL) << "Unsupported unit " << s; base::noreturn(); } } inline int ParseExponent(std::string const& s) { // Parse an int. char* interpreted_end; char const* const c_string = s.c_str(); int const exponent = std::strtol(c_string, &interpreted_end, /*base=*/10); int const interpreted = interpreted_end - c_string; CHECK_LT(0, interpreted) << "invalid integer number " << s; return exponent; } inline Unit ParseExponentiationUnit(std::string const& s) { int const first_caret = s.find('^'); if (first_caret == std::string::npos) { return ParseUnit(s); } else { int const first_nonblank = s.find_first_not_of(' ', first_caret + 1); CHECK_NE(std::string::npos, first_nonblank); int const last_nonblank = s.find_last_not_of(' ', first_caret - 1); CHECK_NE(std::string::npos, last_nonblank); auto const left = ParseUnit(s.substr(0, last_nonblank + 1)); auto const right = ParseExponent(s.substr(first_nonblank)); return left ^ right; } } inline Unit ParseProductUnit(std::string const& s) { // For a product we are looking for a blank character that is not next to a // carret. int first_blank; int first_nonblank; int last_nonblank; for (int start = 0;; start = first_blank + 1) { first_blank = s.find(' ', start); if (first_blank == std::string::npos) { return ParseExponentiationUnit(s); } else { first_nonblank = s.find_first_not_of(' ', first_blank + 1); last_nonblank = s.find_last_not_of(' ', first_blank - 1); if ((first_nonblank == std::string::npos || s[first_nonblank] != '^') && (last_nonblank == std::string::npos || s[last_nonblank] != '^')) { break; } } } auto const left = ParseExponentiationUnit(s.substr(0, last_nonblank + 1)); auto const right = ParseProductUnit(s.substr(first_nonblank)); return left * right; } inline Unit ParseQuotientUnit(std::string const& s) { // Look for the slash from the back to achieve proper associativity. int const last_slash = s.rfind('/'); if (last_slash == std::string::npos) { // Not a quotient. return ParseProductUnit(s); } else { // A quotient. Parse each half. int const first_nonblank = s.find_first_not_of(' ', last_slash + 1); CHECK_NE(std::string::npos, first_nonblank); int const last_nonblank = s.find_last_not_of(' ', last_slash - 1); CHECK_NE(std::string::npos, last_nonblank); auto const left = ParseQuotientUnit(s.substr(0, last_nonblank + 1)); auto const right = ParseExponentiationUnit(s.substr(first_nonblank)); return left / right; } } template<typename Q> Q ParseQuantity(std::string const& s) { // Parse a double. char* interpreted_end; char const* const c_string = s.c_str(); double const magnitude = std::strtod(c_string, &interpreted_end); int const interpreted = interpreted_end - c_string; CHECK_LT(0, interpreted) << "invalid floating-point number " << s; // Locate the unit. It may be empty for a double. int const first_nonblank = s.find_first_not_of(' ', interpreted); int const last_nonblank = s.find_last_not_of(' '); std::string unit_string; if (first_nonblank != std::string::npos) { unit_string = s.substr(first_nonblank, last_nonblank - first_nonblank + 1); } Unit const unit = ParseQuotientUnit(unit_string); CHECK(ExtractDimensions<Q>::dimensions() == unit.dimensions); return magnitude * unit.scale * SIUnit<Q>(); } } // namespace internal_parser } // namespace quantities } // namespace principia <|endoftext|>
<commit_before>#include "k/context.h" #include "etl/armv7m/mpu.h" #include "etl/armv7m/types.h" #include "common/message.h" #include "common/descriptor.h" #include "k/address_range.h" #include "k/context_layout.h" #include "k/object_table.h" #include "k/registers.h" #include "k/reply_sender.h" #include "k/scheduler.h" #include "k/unprivileged.h" using etl::armv7m::Word; namespace k { /******************************************************************************* * Context-specific stuff */ Context::Context() : _stack{nullptr}, _keys{}, _ctx_item{this}, _sender_item{this}, _priority{0}, _state{State::stopped}, _saved_brand{0} {} void Context::nullify_exchanged_keys(unsigned preserved) { // Had to do this somewhere, this is as good a place as any. // (The fields in question are private, so this can't be at top level.) // (Putting it in the ctor hits the ill-defined non-trivial ctor rules.) static_assert(K_CONTEXT_SAVE_OFFSET == __builtin_offsetof(Context, _save), "K_CONTEXT_SAVE_OFFSET is wrong"); // Right, actual implementation now: for (unsigned i = preserved; i < config::n_message_keys; ++i) { _keys[i] = Key::null(); } } Descriptor Context::get_descriptor() const { return _save.sys.m.d0; } Keys & Context::get_message_keys() { return *reinterpret_cast<Keys *>(_keys); } void Context::do_syscall() { switch (get_descriptor().get_sysnum()) { case 0: // IPC do_ipc(); break; case 1: // Copy Key do_copy_key(); break; default: do_bad_sys(); break; } } void Context::do_ipc() { auto d = get_descriptor(); // Perform first phase of IPC. if (d.get_send_enabled()) { key(d.get_target()).deliver_from(this); } else if (d.get_receive_enabled()) { key(d.get_source()).get()->deliver_to(this); } else { // Simply return with registers unchanged. // (Weirdo.) } do_deferred_switch(); } void Context::do_copy_key() { auto d = get_descriptor(); key(d.get_target()) = key(d.get_source()); } void Context::do_bad_sys() { put_message(0, Message::failure(Exception::bad_syscall)); } void Context::complete_receive(BlockingSender * sender) { sender->on_blocked_delivery_accepted(_save.sys.m, _save.sys.b, get_message_keys()); _save.sys.m.d0 = _save.sys.m.d0.sanitized(); } void Context::complete_receive(Exception e, uint32_t param) { _save.sys.m = Message::failure(e, param); _save.sys.b = 0; nullify_exchanged_keys(); } void Context::block_in_receive(List<Context> & list) { // TODO should we decide to permit non-blocking recieves... here's the spot. _ctx_item.unlink(); list.insert(&_ctx_item); _state = State::receiving; pend_switch(); } void Context::complete_blocked_receive(Brand brand, Sender * sender) { runnable.insert(&_ctx_item); _state = State::runnable; sender->on_delivery_accepted(_save.sys.m, get_message_keys()); _save.sys.m.d0 = _save.sys.m.d0.sanitized(); _save.sys.b = brand; pend_switch(); } void Context::complete_blocked_receive(Exception e, uint32_t param) { _ctx_item.unlink(); // from the receiver list runnable.insert(&_ctx_item); _state = State::runnable; complete_receive(e, param); pend_switch(); } void Context::put_message(Brand brand, Message const & m) { _save.sys.m = m; _save.sys.m.d0 = _save.sys.m.d0.sanitized(); _save.sys.b = brand; } void Context::apply_to_mpu() { using etl::armv7m::mpu; for (unsigned i = 0; i < config::n_task_regions; ++i) { mpu.write_rnr(i); auto object = _memory_regions[i].get(); if (object->is_address_range()) { auto range = static_cast<AddressRange *>(object); auto region = range->get_region_for_brand(_memory_regions[i].get_brand()); mpu.write_rbar(region.rbar); mpu.write_rasr(region.rasr); } else { mpu.write_rasr(0); mpu.write_rbar(0); } } } void Context::make_runnable() { switch (_state) { case State::sending: on_blocked_delivery_failed(Exception::would_block); break; case State::receiving: complete_blocked_receive(Exception::would_block); break; case State::stopped: runnable.insert(&_ctx_item); _state = State::runnable; break; case State::runnable: break; } } /******************************************************************************* * Implementation of Sender and BlockingSender */ Priority Context::get_priority() const { return _priority; } void Context::on_delivery_accepted(Message & m, Keys & k) { auto d = get_descriptor(); m = _save.sys.m; k.keys[0] = d.is_call() ? make_reply_key() : Key::null(); for (unsigned ki = 1; ki < config::n_message_keys; ++ki) { k.keys[ki] = key(ki); } if (d.get_receive_enabled()) { auto source = d.is_call() ? make_reply_key() : key(d.get_source()); source.get()->deliver_to(this); } } void Context::on_delivery_failed(Exception e, uint32_t param) { // Deliver the exception. _save.sys.m = Message::failure(e, param); _save.sys.b = 0; // Avoid looking like we delivered any pre-existing keys. nullify_exchanged_keys(); } void Context::block_in_send(Brand brand, List<BlockingSender> & list) { ETL_ASSERT(this == current); if (get_descriptor().get_block()) { _saved_brand = brand; list.insert(&_sender_item); _ctx_item.unlink(); _state = State::sending; pend_switch(); } else { // Unprivileged code is unwilling to block for delivery. on_delivery_failed(Exception::would_block); } } void Context::on_blocked_delivery_accepted(Message & m, Brand & b, Keys & k) { runnable.insert(&_ctx_item); _state = State::runnable; b = _saved_brand; on_delivery_accepted(m, k); pend_switch(); } void Context::on_blocked_delivery_failed(Exception e, uint32_t param) { runnable.insert(&_ctx_item); _state = State::runnable; on_delivery_failed(e, param); pend_switch(); } Key Context::make_reply_key() const { auto maybe_key = object_table[_reply_gate_index].ptr->make_key(0); if (maybe_key) return maybe_key.ref(); return Key::null(); } /******************************************************************************* * Implementation of Object */ void Context::deliver_from(Brand brand, Sender * sender) { Message m; Keys k; sender->on_delivery_accepted(m, k); switch (m.d0.get_selector()) { case 0: do_read_register(brand, m, k); break; case 1: do_write_register(brand, m, k); break; case 2: do_read_key(brand, m, k); break; case 3: do_write_key(brand, m, k); break; case 4: do_read_region(brand, m, k); break; case 5: do_write_region(brand, m, k); break; case 6: do_make_runnable(brand, m, k); break; case 7: do_read_priority(brand, m, k); break; case 8: do_write_priority(brand, m, k); break; default: do_badop(m, k); break; } } void Context::do_read_register(Brand, Message const & arg, Keys & k) { ReplySender reply_sender; switch (arg.d1) { case 13: reply_sender.set_message({ Descriptor::zero(), reinterpret_cast<Word>(_stack), }); break; #define GP_EF(n) \ case n: { \ apply_to_mpu(); \ auto r = uload(&_stack->r ## n); \ current->apply_to_mpu(); \ if (r) { \ reply_sender.set_message({ \ Descriptor::zero(), \ r.ref(), \ }); \ } else { \ reply_sender.set_message(Message::failure(Exception::fault)); \ } \ break; \ } GP_EF(0); GP_EF(1); GP_EF(2); GP_EF(3); GP_EF(12); GP_EF(14); GP_EF(15); #undef GP_EF case 16: { apply_to_mpu(); auto r = uload(&_stack->psr); current->apply_to_mpu(); if (r) { reply_sender.set_message({ Descriptor::zero(), r.ref(), }); } else { reply_sender.set_message(Message::failure(Exception::fault)); } break; } case 4: case 5: case 6: case 7: case 8: case 9: case 10: case 11: reply_sender.set_message({Descriptor::zero(), _save.raw[arg.d1 - 4]}); break; default: reply_sender.set_message(Message::failure(Exception::index_out_of_range)); break; } k.keys[0].deliver_from(&reply_sender); } void Context::do_write_register(Brand, Message const & arg, Keys & k) { auto r = arg.d1; auto v = arg.d2; ReplySender reply_sender; switch (r) { case 13: _stack = reinterpret_cast<decltype(_stack)>(v); break; #define GP_EF(n) \ case n: { \ if (!ustore(&_stack->r ## n, v)) { \ reply_sender.set_message(Message::failure(Exception::fault)); \ } \ break; \ } GP_EF(0); GP_EF(1); GP_EF(2); GP_EF(3); GP_EF(12); GP_EF(14); GP_EF(15); #undef GP case 16: { if (!ustore(&_stack->psr, v)) { reply_sender.set_message(Message::failure(Exception::fault)); } break; } case 4: case 5: case 6: case 7: case 8: case 9: case 10: case 11: _save.raw[r - 4] = v; break; default: reply_sender.set_message(Message::failure(Exception::index_out_of_range)); break; } k.keys[0].deliver_from(&reply_sender); } void Context::do_read_key(Brand, Message const & arg, Keys & k) { auto r = arg.d1; ReplySender reply_sender; if (r >= config::n_task_keys) { reply_sender.set_message(Message::failure(Exception::index_out_of_range)); } else { reply_sender.set_key(1, key(r)); } k.keys[0].deliver_from(&reply_sender); } void Context::do_write_key(Brand, Message const & arg, Keys & k) { auto r = arg.d1; auto & reply = k.keys[0]; auto & new_key = k.keys[1]; ReplySender reply_sender; if (r >= config::n_task_keys) { reply_sender.set_message(Message::failure(Exception::index_out_of_range)); } else { key(r) = new_key; } reply.deliver_from(&reply_sender); } void Context::do_read_region(Brand, Message const & arg, Keys & k) { auto n = arg.d1; ReplySender reply_sender; if (n < config::n_task_regions) { reply_sender.set_key(1, _memory_regions[n]); } else { reply_sender.set_message(Message::failure(Exception::index_out_of_range)); } k.keys[0].deliver_from(&reply_sender); } void Context::do_write_region(Brand, Message const & arg, Keys & k) { auto n = arg.d1; auto & reply = k.keys[0]; auto & object_key = k.keys[1]; ReplySender reply_sender; if (n < config::n_task_regions) { _memory_regions[n] = object_key; } else { reply_sender.set_message(Message::failure(Exception::index_out_of_range)); } if (current == this) apply_to_mpu(); reply.deliver_from(&reply_sender); } void Context::do_make_runnable(Brand, Message const & arg, Keys & k) { make_runnable(); pend_switch(); ReplySender reply_sender; k.keys[0].deliver_from(&reply_sender); } void Context::do_read_priority(Brand, Message const & arg, Keys & k) { ReplySender reply_sender; reply_sender.set_message({Descriptor::zero(), _priority}); k.keys[0].deliver_from(&reply_sender); } void Context::do_write_priority(Brand, Message const & arg, Keys & k) { auto priority = arg.d1; ReplySender reply_sender; if (priority < config::n_priorities) { _priority = priority; if (_ctx_item.is_linked()) _ctx_item.reinsert(); if (_sender_item.is_linked()) _sender_item.reinsert(); } else { reply_sender.set_message(Message::failure(Exception::index_out_of_range)); } k.keys[0].deliver_from(&reply_sender); } } // namespace k <commit_msg>k/context: use dispatch table over switch.<commit_after>#include "k/context.h" #include "etl/array_count.h" #include "etl/armv7m/mpu.h" #include "etl/armv7m/types.h" #include "common/message.h" #include "common/descriptor.h" #include "k/address_range.h" #include "k/context_layout.h" #include "k/object_table.h" #include "k/registers.h" #include "k/reply_sender.h" #include "k/scheduler.h" #include "k/unprivileged.h" using etl::armv7m::Word; namespace k { /******************************************************************************* * Context-specific stuff */ Context::Context() : _stack{nullptr}, _keys{}, _ctx_item{this}, _sender_item{this}, _priority{0}, _state{State::stopped}, _saved_brand{0} {} void Context::nullify_exchanged_keys(unsigned preserved) { // Had to do this somewhere, this is as good a place as any. // (The fields in question are private, so this can't be at top level.) // (Putting it in the ctor hits the ill-defined non-trivial ctor rules.) static_assert(K_CONTEXT_SAVE_OFFSET == __builtin_offsetof(Context, _save), "K_CONTEXT_SAVE_OFFSET is wrong"); // Right, actual implementation now: for (unsigned i = preserved; i < config::n_message_keys; ++i) { _keys[i] = Key::null(); } } Descriptor Context::get_descriptor() const { return _save.sys.m.d0; } Keys & Context::get_message_keys() { return *reinterpret_cast<Keys *>(_keys); } void Context::do_syscall() { switch (get_descriptor().get_sysnum()) { case 0: // IPC do_ipc(); break; case 1: // Copy Key do_copy_key(); break; default: do_bad_sys(); break; } } void Context::do_ipc() { auto d = get_descriptor(); // Perform first phase of IPC. if (d.get_send_enabled()) { key(d.get_target()).deliver_from(this); } else if (d.get_receive_enabled()) { key(d.get_source()).get()->deliver_to(this); } else { // Simply return with registers unchanged. // (Weirdo.) } do_deferred_switch(); } void Context::do_copy_key() { auto d = get_descriptor(); key(d.get_target()) = key(d.get_source()); } void Context::do_bad_sys() { put_message(0, Message::failure(Exception::bad_syscall)); } void Context::complete_receive(BlockingSender * sender) { sender->on_blocked_delivery_accepted(_save.sys.m, _save.sys.b, get_message_keys()); _save.sys.m.d0 = _save.sys.m.d0.sanitized(); } void Context::complete_receive(Exception e, uint32_t param) { _save.sys.m = Message::failure(e, param); _save.sys.b = 0; nullify_exchanged_keys(); } void Context::block_in_receive(List<Context> & list) { // TODO should we decide to permit non-blocking recieves... here's the spot. _ctx_item.unlink(); list.insert(&_ctx_item); _state = State::receiving; pend_switch(); } void Context::complete_blocked_receive(Brand brand, Sender * sender) { runnable.insert(&_ctx_item); _state = State::runnable; sender->on_delivery_accepted(_save.sys.m, get_message_keys()); _save.sys.m.d0 = _save.sys.m.d0.sanitized(); _save.sys.b = brand; pend_switch(); } void Context::complete_blocked_receive(Exception e, uint32_t param) { _ctx_item.unlink(); // from the receiver list runnable.insert(&_ctx_item); _state = State::runnable; complete_receive(e, param); pend_switch(); } void Context::put_message(Brand brand, Message const & m) { _save.sys.m = m; _save.sys.m.d0 = _save.sys.m.d0.sanitized(); _save.sys.b = brand; } void Context::apply_to_mpu() { using etl::armv7m::mpu; for (unsigned i = 0; i < config::n_task_regions; ++i) { mpu.write_rnr(i); auto object = _memory_regions[i].get(); if (object->is_address_range()) { auto range = static_cast<AddressRange *>(object); auto region = range->get_region_for_brand(_memory_regions[i].get_brand()); mpu.write_rbar(region.rbar); mpu.write_rasr(region.rasr); } else { mpu.write_rasr(0); mpu.write_rbar(0); } } } void Context::make_runnable() { switch (_state) { case State::sending: on_blocked_delivery_failed(Exception::would_block); break; case State::receiving: complete_blocked_receive(Exception::would_block); break; case State::stopped: runnable.insert(&_ctx_item); _state = State::runnable; break; case State::runnable: break; } } /******************************************************************************* * Implementation of Sender and BlockingSender */ Priority Context::get_priority() const { return _priority; } void Context::on_delivery_accepted(Message & m, Keys & k) { auto d = get_descriptor(); m = _save.sys.m; k.keys[0] = d.is_call() ? make_reply_key() : Key::null(); for (unsigned ki = 1; ki < config::n_message_keys; ++ki) { k.keys[ki] = key(ki); } if (d.get_receive_enabled()) { auto source = d.is_call() ? make_reply_key() : key(d.get_source()); source.get()->deliver_to(this); } } void Context::on_delivery_failed(Exception e, uint32_t param) { // Deliver the exception. _save.sys.m = Message::failure(e, param); _save.sys.b = 0; // Avoid looking like we delivered any pre-existing keys. nullify_exchanged_keys(); } void Context::block_in_send(Brand brand, List<BlockingSender> & list) { ETL_ASSERT(this == current); if (get_descriptor().get_block()) { _saved_brand = brand; list.insert(&_sender_item); _ctx_item.unlink(); _state = State::sending; pend_switch(); } else { // Unprivileged code is unwilling to block for delivery. on_delivery_failed(Exception::would_block); } } void Context::on_blocked_delivery_accepted(Message & m, Brand & b, Keys & k) { runnable.insert(&_ctx_item); _state = State::runnable; b = _saved_brand; on_delivery_accepted(m, k); pend_switch(); } void Context::on_blocked_delivery_failed(Exception e, uint32_t param) { runnable.insert(&_ctx_item); _state = State::runnable; on_delivery_failed(e, param); pend_switch(); } Key Context::make_reply_key() const { auto maybe_key = object_table[_reply_gate_index].ptr->make_key(0); if (maybe_key) return maybe_key.ref(); return Key::null(); } /******************************************************************************* * Implementation of Context protocol. */ using IpcImpl = void (Context::*)(Brand, Message const &, Keys &); void Context::deliver_from(Brand brand, Sender * sender) { Message m; Keys k; sender->on_delivery_accepted(m, k); static constexpr IpcImpl dispatch[] { &Context::do_read_register, &Context::do_write_register, &Context::do_read_key, &Context::do_write_key, &Context::do_read_region, &Context::do_write_region, &Context::do_make_runnable, &Context::do_read_priority, &Context::do_write_priority, }; if (m.d0.get_selector() < etl::array_count(dispatch)) { auto fn = dispatch[m.d0.get_selector()]; (this->*fn)(brand, m, k); } else { do_badop(m, k); } } void Context::do_read_register(Brand, Message const & arg, Keys & k) { ReplySender reply_sender; switch (arg.d1) { case 13: reply_sender.set_message({ Descriptor::zero(), reinterpret_cast<Word>(_stack), }); break; #define GP_EF(n) \ case n: { \ apply_to_mpu(); \ auto r = uload(&_stack->r ## n); \ current->apply_to_mpu(); \ if (r) { \ reply_sender.set_message({ \ Descriptor::zero(), \ r.ref(), \ }); \ } else { \ reply_sender.set_message(Message::failure(Exception::fault)); \ } \ break; \ } GP_EF(0); GP_EF(1); GP_EF(2); GP_EF(3); GP_EF(12); GP_EF(14); GP_EF(15); #undef GP_EF case 16: { apply_to_mpu(); auto r = uload(&_stack->psr); current->apply_to_mpu(); if (r) { reply_sender.set_message({ Descriptor::zero(), r.ref(), }); } else { reply_sender.set_message(Message::failure(Exception::fault)); } break; } case 4: case 5: case 6: case 7: case 8: case 9: case 10: case 11: reply_sender.set_message({Descriptor::zero(), _save.raw[arg.d1 - 4]}); break; default: reply_sender.set_message(Message::failure(Exception::index_out_of_range)); break; } k.keys[0].deliver_from(&reply_sender); } void Context::do_write_register(Brand, Message const & arg, Keys & k) { auto r = arg.d1; auto v = arg.d2; ReplySender reply_sender; switch (r) { case 13: _stack = reinterpret_cast<decltype(_stack)>(v); break; #define GP_EF(n) \ case n: { \ if (!ustore(&_stack->r ## n, v)) { \ reply_sender.set_message(Message::failure(Exception::fault)); \ } \ break; \ } GP_EF(0); GP_EF(1); GP_EF(2); GP_EF(3); GP_EF(12); GP_EF(14); GP_EF(15); #undef GP case 16: { if (!ustore(&_stack->psr, v)) { reply_sender.set_message(Message::failure(Exception::fault)); } break; } case 4: case 5: case 6: case 7: case 8: case 9: case 10: case 11: _save.raw[r - 4] = v; break; default: reply_sender.set_message(Message::failure(Exception::index_out_of_range)); break; } k.keys[0].deliver_from(&reply_sender); } void Context::do_read_key(Brand, Message const & arg, Keys & k) { auto r = arg.d1; ReplySender reply_sender; if (r >= config::n_task_keys) { reply_sender.set_message(Message::failure(Exception::index_out_of_range)); } else { reply_sender.set_key(1, key(r)); } k.keys[0].deliver_from(&reply_sender); } void Context::do_write_key(Brand, Message const & arg, Keys & k) { auto r = arg.d1; auto & reply = k.keys[0]; auto & new_key = k.keys[1]; ReplySender reply_sender; if (r >= config::n_task_keys) { reply_sender.set_message(Message::failure(Exception::index_out_of_range)); } else { key(r) = new_key; } reply.deliver_from(&reply_sender); } void Context::do_read_region(Brand, Message const & arg, Keys & k) { auto n = arg.d1; ReplySender reply_sender; if (n < config::n_task_regions) { reply_sender.set_key(1, _memory_regions[n]); } else { reply_sender.set_message(Message::failure(Exception::index_out_of_range)); } k.keys[0].deliver_from(&reply_sender); } void Context::do_write_region(Brand, Message const & arg, Keys & k) { auto n = arg.d1; auto & reply = k.keys[0]; auto & object_key = k.keys[1]; ReplySender reply_sender; if (n < config::n_task_regions) { _memory_regions[n] = object_key; } else { reply_sender.set_message(Message::failure(Exception::index_out_of_range)); } if (current == this) apply_to_mpu(); reply.deliver_from(&reply_sender); } void Context::do_make_runnable(Brand, Message const & arg, Keys & k) { make_runnable(); pend_switch(); ReplySender reply_sender; k.keys[0].deliver_from(&reply_sender); } void Context::do_read_priority(Brand, Message const & arg, Keys & k) { ReplySender reply_sender; reply_sender.set_message({Descriptor::zero(), _priority}); k.keys[0].deliver_from(&reply_sender); } void Context::do_write_priority(Brand, Message const & arg, Keys & k) { auto priority = arg.d1; ReplySender reply_sender; if (priority < config::n_priorities) { _priority = priority; if (_ctx_item.is_linked()) _ctx_item.reinsert(); if (_sender_item.is_linked()) _sender_item.reinsert(); } else { reply_sender.set_message(Message::failure(Exception::index_out_of_range)); } k.keys[0].deliver_from(&reply_sender); } } // namespace k <|endoftext|>
<commit_before>/****************************************************************************** * @file prngcl_constant.cpp * @author Vadim Demchik <[email protected]> * @version 1.0 * * @brief [PRNGCL library] * contains implementation, description and initialization procedures of * constant "pseudo-random number generator", * which produces series of constant values for debugging purposes * * * @section LICENSE * * Copyright (c) 2013, Vadim Demchik * 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. * *****************************************************************************/ #include "hgpu_prng.h" #define HGPU_PRNG_CONSTANT_m (4294967296.0) /**< devider for production a floating-point PRNs on integer value. */ #define HGPU_PRNG_CONSTANT_min 0 /**< minimal possible integer value, that could be produced by PRNG. */ #define HGPU_PRNG_CONSTANT_max 4294967295 /**< maximal possible integer value, that could be produced by PRNG (=2^32-1). */ #define HGPU_PRNG_CONSTANT_min_FP (0.0) /**< minimal possible floating value, that could be produced by PRNG. */ #define HGPU_PRNG_CONSTANT_max_FP (4294967295.0/4294967296.0) /**< maximal possible floating value, that could be produced by PRNG. */ #define HGPU_PRNG_CONSTANT_k (0.0) /**< value for conversion of single to double precision (0 means do not convert to double). */ typedef struct { unsigned int x; } HGPU_PRNG_CONSTANT_state_t; static void HGPU_PRNG_CONSTANT_initialize(void* PRNG_state, unsigned int PRNG_randseries); static unsigned int HGPU_PRNG_CONSTANT_produce_one_uint_CPU(void* PRNG_state); static double HGPU_PRNG_CONSTANT_produce_one_double_CPU(void* PRNG_state); static void HGPU_PRNG_CONSTANT_init_GPU(HGPU_GPU_context* context,void* PRNG_state,HGPU_PRNG_parameters* PRNG_parameters); static char* HGPU_PRNG_CONSTANT_options_GPU(HGPU_GPU_context* context,void* PRNG_state,HGPU_PRNG_parameters* PRNG_parameters); static void HGPU_PRNG_CONSTANT_parameters_set(void* PRNG_state,HGPU_parameter** parameters); static void HGPU_PRNG_CONSTANT_initialize(void* PRNG_state, unsigned int PRNG_randseries){ HGPU_PRNG_CONSTANT_state_t* state = (HGPU_PRNG_CONSTANT_state_t*) PRNG_state; HGPU_PRNG_srand(PRNG_randseries); state->x = HGPU_PRNG_rand32bit(); } static unsigned int HGPU_PRNG_CONSTANT_produce_one_uint_CPU(void* PRNG_state){ HGPU_PRNG_CONSTANT_state_t* state = (HGPU_PRNG_CONSTANT_state_t*) PRNG_state; return (state->x); } static double HGPU_PRNG_CONSTANT_produce_one_double_CPU(void* PRNG_state){ double y = (double) HGPU_PRNG_CONSTANT_produce_one_uint_CPU(PRNG_state); return (y / HGPU_PRNG_CONSTANT_m); } static void HGPU_PRNG_CONSTANT_init_GPU(HGPU_GPU_context* context,void* PRNG_state,HGPU_PRNG_parameters* PRNG_parameters){ HGPU_PRNG_CONSTANT_state_t* state = (HGPU_PRNG_CONSTANT_state_t*) PRNG_state; size_t randoms_size = HGPU_GPU_context_buffer_size_align(context,PRNG_parameters->instances * PRNG_parameters->samples); cl_float4* PRNG_randoms = NULL; cl_double4* PRNG_randoms_double = NULL; if (PRNG_parameters->precision==HGPU_precision_double) PRNG_randoms_double = (cl_double4*) calloc(randoms_size,sizeof(cl_double4)); else PRNG_randoms = (cl_float4*) calloc(randoms_size,sizeof(cl_float4)); if ((!PRNG_randoms_double) && (!PRNG_randoms)) HGPU_error_message(HGPU_ERROR_NO_MEMORY,"could not allocate memory for randoms"); unsigned int seed_table_id = 0; unsigned int randoms_id = 0; if (PRNG_parameters->precision==HGPU_precision_double) randoms_id = HGPU_GPU_context_buffer_init(context,PRNG_randoms_double,HGPU_GPU_buffer_type_io,randoms_size,sizeof(cl_double4)); else randoms_id = HGPU_GPU_context_buffer_init(context,PRNG_randoms,HGPU_GPU_buffer_type_io,randoms_size,sizeof(cl_float4)); HGPU_GPU_context_buffer_set_name(context,randoms_id,(char*) "(CONSTANT) PRNG_randoms"); PRNG_parameters->id_buffer_input_seeds = HGPU_GPU_MAX_BUFFERS; PRNG_parameters->id_buffer_seeds = HGPU_GPU_MAX_BUFFERS; PRNG_parameters->id_buffer_randoms = randoms_id; } static char* HGPU_PRNG_CONSTANT_options_GPU(HGPU_GPU_context* context,void* PRNG_state,HGPU_PRNG_parameters* PRNG_parameters){ char* result = NULL; if ((!context) || (!PRNG_state)) return result; result = (char*) calloc(HGPU_GPU_MAX_OPTIONS_LENGTH,sizeof(char)); HGPU_PRNG_CONSTANT_state_t* state = (HGPU_PRNG_CONSTANT_state_t*) PRNG_state; int j = 0; if (PRNG_parameters->precision==HGPU_precision_double) j += sprintf_s(result+j,HGPU_GPU_MAX_OPTIONS_LENGTH-j,"-D CONSTANT_FP=(%1.23e)",(state->x / HGPU_PRNG_CONSTANT_m)); else j += sprintf_s(result+j,HGPU_GPU_MAX_OPTIONS_LENGTH-j,"-D CONSTANT_FP=(%1.16f)",(state->x / HGPU_PRNG_CONSTANT_m)); return result; } static void HGPU_PRNG_CONSTANT_parameters_set(void* PRNG_state,HGPU_parameter** parameters){ if ((!parameters) || (!PRNG_state)) return; HGPU_PRNG_CONSTANT_state_t* state = (HGPU_PRNG_CONSTANT_state_t*) PRNG_state; HGPU_parameter* parameter = HGPU_parameters_get_by_name(parameters,(char*) HGPU_PARAMETER_PRNG_SEED1); if (parameter) (*state).x = parameter->value_integer; } static const HGPU_PRNG_description HGPU_PRNG_CONSTANT_description = { "CONSTANT", // name 32, // bitness HGPU_PRNG_output_type_double, // PRNG GPU output type HGPU_PRNG_CONSTANT_min, // PRNG_min_uint_value HGPU_PRNG_CONSTANT_max, // PRNG_max_uint_value HGPU_PRNG_CONSTANT_min_FP, // PRNG_min_double_value HGPU_PRNG_CONSTANT_max_FP, // PRNG_max_double_value HGPU_PRNG_CONSTANT_k, // PRNG_k_value sizeof(HGPU_PRNG_CONSTANT_state_t), // size of PRNG state &HGPU_PRNG_CONSTANT_initialize, // PRNG initialization &HGPU_PRNG_CONSTANT_parameters_set, // PRNG additional parameters initialization &HGPU_PRNG_CONSTANT_produce_one_uint_CPU, // PRNG production one unsigned integer &HGPU_PRNG_CONSTANT_produce_one_double_CPU, // PRNG production one double // &HGPU_PRNG_CONSTANT_init_GPU, // PRNG init for GPU procedure &HGPU_PRNG_CONSTANT_options_GPU, // PRNG additional compilation options "random/prngcl_constant.cl", // PRNG source codes NULL, // PRNG init kernel "constant_series" // PRNG production kernel }; const HGPU_PRNG_description* HGPU_PRNG_CONSTANT = &HGPU_PRNG_CONSTANT_description; <commit_msg>Delete prngcl_constant.cpp<commit_after><|endoftext|>
<commit_before>#include "loging.h" #include "task.h" #include "preferences.h" #include <qdatetime.h> #include <qstring.h> #include <qfile.h> #include <qtextstream.h> #include <qregexp.h> #include <iostream> #define LOG_START 1 #define LOG_STOP 2 #define LOG_NEW_TOTAL_TIME 3 #define LOG_NEW_SESSION_TIME 4 Loging *Loging::_instance = 0; Loging::Loging() { _preferences = Preferences::instance(); } void Loging::start( Task * task) { log(task, LOG_START); } void Loging::stop( Task * task) { log(task, LOG_STOP); } // when time is reset... void Loging::newTotalTime( Task * task, long minutes) { log(task, LOG_NEW_TOTAL_TIME, minutes); } void Loging::newSessionTime( Task * task, long minutes) { log(task, LOG_NEW_SESSION_TIME, minutes); } void Loging::log( Task * task, short type, long minutes) { if(_preferences->timeLoging()) { QFile f(_preferences->timeLog()); if ( f.open( IO_WriteOnly | IO_Append) ) { QTextStream out( &f ); // use a text stream if( type == LOG_START) { out << "<starting "; } else if( type == LOG_STOP ) { out << "<stopping "; } else if( type == LOG_NEW_TOTAL_TIME) { out << "<new_total_time "; } else if( type == LOG_NEW_SESSION_TIME) { out << "<new_session_time "; } else { cerr << "Programming error!"; } out << "task=\"" << constructTaskName(task) << "\" " << "date=\"" << QDateTime::currentDateTime().toString() << "\" "; if ( type == LOG_NEW_TOTAL_TIME || type == LOG_NEW_SESSION_TIME) { out << "new_total=\"" << minutes << "\" "; } out << "/>\n"; f.close(); } else { cerr << "Couldn't write to time-log file"; } } } Loging *Loging::instance() { if (_instance == 0) { _instance = new Loging(); } return _instance; } QString Loging::constructTaskName(Task *task) { QListViewItem *item = task; QString name = escapeXML(task->name()); while( ( item = item->parent() ) ) { name = escapeXML(((Task *)item)->name()) + name.prepend('/'); } return name; } // why the hell do I need to do this?!? #define QS(c) QString::fromLatin1(c) QString Loging::escapeXML( QString string) { QString result = QString(string); result.replace( QRegExp(QS("&")), QS("&amp;") ); result.replace( QRegExp(QS("<")), QS("&lt;") ); result.replace( QRegExp(QS(">")), QS("&gt;") ); result.replace( QRegExp(QS("'")), QS("&apos;") ); result.replace( QRegExp(QS("\"")), QS("&quot;") ); // protect also our task-separator result.replace( QRegExp(QS("/")), QS("&slash;") ); return result; } Loging::~Loging() { } <commit_msg>fix compile for gcc 3.1<commit_after>#include "loging.h" #include "task.h" #include "preferences.h" #include <qdatetime.h> #include <qstring.h> #include <qfile.h> #include <qtextstream.h> #include <qregexp.h> #include <iostream> #define LOG_START 1 #define LOG_STOP 2 #define LOG_NEW_TOTAL_TIME 3 #define LOG_NEW_SESSION_TIME 4 Loging *Loging::_instance = 0; Loging::Loging() { _preferences = Preferences::instance(); } void Loging::start( Task * task) { log(task, LOG_START); } void Loging::stop( Task * task) { log(task, LOG_STOP); } // when time is reset... void Loging::newTotalTime( Task * task, long minutes) { log(task, LOG_NEW_TOTAL_TIME, minutes); } void Loging::newSessionTime( Task * task, long minutes) { log(task, LOG_NEW_SESSION_TIME, minutes); } void Loging::log( Task * task, short type, long minutes) { if(_preferences->timeLoging()) { QFile f(_preferences->timeLog()); if ( f.open( IO_WriteOnly | IO_Append) ) { QTextStream out( &f ); // use a text stream if( type == LOG_START) { out << "<starting "; } else if( type == LOG_STOP ) { out << "<stopping "; } else if( type == LOG_NEW_TOTAL_TIME) { out << "<new_total_time "; } else if( type == LOG_NEW_SESSION_TIME) { out << "<new_session_time "; } else { std::cerr << "Programming error!"; } out << "task=\"" << constructTaskName(task) << "\" " << "date=\"" << QDateTime::currentDateTime().toString() << "\" "; if ( type == LOG_NEW_TOTAL_TIME || type == LOG_NEW_SESSION_TIME) { out << "new_total=\"" << minutes << "\" "; } out << "/>\n"; f.close(); } else { std::cerr << "Couldn't write to time-log file"; } } } Loging *Loging::instance() { if (_instance == 0) { _instance = new Loging(); } return _instance; } QString Loging::constructTaskName(Task *task) { QListViewItem *item = task; QString name = escapeXML(task->name()); while( ( item = item->parent() ) ) { name = escapeXML(((Task *)item)->name()) + name.prepend('/'); } return name; } // why the hell do I need to do this?!? #define QS(c) QString::fromLatin1(c) QString Loging::escapeXML( QString string) { QString result = QString(string); result.replace( QRegExp(QS("&")), QS("&amp;") ); result.replace( QRegExp(QS("<")), QS("&lt;") ); result.replace( QRegExp(QS(">")), QS("&gt;") ); result.replace( QRegExp(QS("'")), QS("&apos;") ); result.replace( QRegExp(QS("\"")), QS("&quot;") ); // protect also our task-separator result.replace( QRegExp(QS("/")), QS("&slash;") ); return result; } Loging::~Loging() { } <|endoftext|>
<commit_before>// Copyright (c) 2010 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "base/logging.h" #include "media/base/callback.h" #include "media/base/media.h" #include "remoting/base/capture_data.h" #include "remoting/base/encoder_vp8.h" #include "remoting/proto/video.pb.h" extern "C" { #define VPX_CODEC_DISABLE_COMPAT 1 #include "third_party/libvpx/include/vpx/vpx_codec.h" #include "third_party/libvpx/include/vpx/vpx_encoder.h" #include "third_party/libvpx/include/vpx/vp8cx.h" } namespace remoting { EncoderVp8::EncoderVp8() : initialized_(false), codec_(NULL), image_(NULL), last_timestamp_(0) { } EncoderVp8::~EncoderVp8() { if (initialized_) { vpx_codec_err_t ret = vpx_codec_destroy(codec_.get()); DCHECK(ret == VPX_CODEC_OK) << "Failed to destroy codec"; } } bool EncoderVp8::Init(int width, int height) { codec_.reset(new vpx_codec_ctx_t()); image_.reset(new vpx_image_t()); memset(image_.get(), 0, sizeof(vpx_image_t)); image_->fmt = VPX_IMG_FMT_YV12; // libvpx seems to require both to be assigned. image_->d_w = width; image_->w = width; image_->d_h = height; image_->h = height; vpx_codec_enc_cfg_t config; const vpx_codec_iface_t* algo = (const vpx_codec_iface_t*)media::GetVp8CxAlgoAddress(); CHECK(algo); vpx_codec_err_t ret = vpx_codec_enc_config_default(algo, &config, 0); if (ret != VPX_CODEC_OK) return false; // TODO(hclam): Tune the parameters to better suit the application. config.rc_target_bitrate = width * height * config.rc_target_bitrate / config.g_w / config.g_h; config.g_w = width; config.g_h = height; config.g_pass = VPX_RC_ONE_PASS; config.g_profile = 1; config.g_threads = 2; config.rc_min_quantizer = 0; config.rc_max_quantizer = 15; config.g_timebase.num = 1; config.g_timebase.den = 30; if (vpx_codec_enc_init(codec_.get(), algo, &config, 0)) return false; return true; } static int clip_byte(int x) { if (x > 255) return 255; else if (x < 0) return 0; else return x; } bool EncoderVp8::PrepareImage(scoped_refptr<CaptureData> capture_data) { const int plane_size = capture_data->width() * capture_data->height(); if (!yuv_image_.get()) { // YUV image size is 1.5 times of a plane. Multiplication is performed first // to avoid rounding error. const int size = plane_size * 3 / 2; yuv_image_.reset(new uint8[size]); // Reset image value to 128 so we just need to fill in the y plane. memset(yuv_image_.get(), 128, size); // Fill in the information for |image_|. unsigned char* image = reinterpret_cast<unsigned char*>(yuv_image_.get()); image_->planes[0] = image; image_->planes[1] = image + plane_size; // The V plane starts from 1.25 of the plane size. image_->planes[2] = image + plane_size + plane_size / 4; // In YV12 Y plane has full width, UV plane has half width because of // subsampling. image_->stride[0] = image_->w; image_->stride[1] = image_->w / 2; image_->stride[2] = image_->w / 2; } // And then do RGB->YUV conversion. // Currently we just produce the Y channel as the average of RGB. This will // giv ae gray scale image after conversion. // TODO(sergeyu): Move this code to a separate routine. // TODO(sergeyu): Optimize this code. DCHECK(capture_data->pixel_format() == media::VideoFrame::RGB32) << "Only RGB32 is supported"; uint8* in = capture_data->data_planes().data[0]; const int in_stride = capture_data->data_planes().strides[0]; uint8* y_out = yuv_image_.get(); uint8* u_out = yuv_image_.get() + plane_size; uint8* v_out = yuv_image_.get() + plane_size + plane_size / 4; const int out_stride = image_->stride[0]; for (int i = 0; i < capture_data->height(); ++i) { for (int j = 0; j < capture_data->width(); ++j) { // Since the input pixel format is RGB32, there are 4 bytes per pixel. uint8* pixel = in + 4 * j; y_out[j] = clip_byte(((pixel[0] * 66 + pixel[1] * 129 + pixel[2] * 25 + 128) >> 8) + 16); if (i % 2 == 0 && j % 2 == 0) { u_out[j / 2] = clip_byte(((pixel[0] * -38 + pixel[1] * -74 + pixel[2] * 112 + 128) >> 8) + 128); v_out[j / 2] = clip_byte(((pixel[0] * 112 + pixel[1] * -94 + pixel[2] * -18 + 128) >> 8) + 128); } } in += in_stride; y_out += out_stride; if (i % 2 == 0) { u_out += out_stride / 2; v_out += out_stride / 2; } } return true; } void EncoderVp8::Encode(scoped_refptr<CaptureData> capture_data, bool key_frame, DataAvailableCallback* data_available_callback) { if (!initialized_) { bool ret = Init(capture_data->width(), capture_data->height()); // TODO(hclam): Handle error better. DCHECK(ret) << "Initialization of encoder failed"; initialized_ = ret; } if (!PrepareImage(capture_data)) { NOTREACHED() << "Can't image data for encoding"; } // Do the actual encoding. vpx_codec_err_t ret = vpx_codec_encode(codec_.get(), image_.get(), last_timestamp_, 1, 0, VPX_DL_REALTIME); DCHECK_EQ(ret, VPX_CODEC_OK) << "Encoding error: " << vpx_codec_err_to_string(ret) << "\n" << "Details: " << vpx_codec_error(codec_.get()) << "\n" << vpx_codec_error_detail(codec_.get()); // TODO(hclam): fix this. last_timestamp_ += 100; // Read the encoded data. vpx_codec_iter_t iter = NULL; bool got_data = false; // TODO(hclam): Make sure we get exactly one frame from the packet. // TODO(hclam): We should provide the output buffer to avoid one copy. VideoPacket* message = new VideoPacket(); while (!got_data) { const vpx_codec_cx_pkt_t* packet = vpx_codec_get_cx_data(codec_.get(), &iter); if (!packet) continue; switch (packet->kind) { case VPX_CODEC_CX_FRAME_PKT: got_data = true; message->set_data(packet->data.frame.buf, packet->data.frame.sz); break; default: break; } } message->mutable_format()->set_encoding(VideoPacketFormat::ENCODING_VP8); message->set_flags(VideoPacket::FIRST_PACKET | VideoPacket::LAST_PACKET); data_available_callback->Run(message); delete data_available_callback; } } // namespace remoting <commit_msg>Fix RGB->YUV conversion: input is BGR instead of RGB.<commit_after>// Copyright (c) 2010 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "base/logging.h" #include "media/base/callback.h" #include "media/base/media.h" #include "remoting/base/capture_data.h" #include "remoting/base/encoder_vp8.h" #include "remoting/proto/video.pb.h" extern "C" { #define VPX_CODEC_DISABLE_COMPAT 1 #include "third_party/libvpx/include/vpx/vpx_codec.h" #include "third_party/libvpx/include/vpx/vpx_encoder.h" #include "third_party/libvpx/include/vpx/vp8cx.h" } namespace remoting { EncoderVp8::EncoderVp8() : initialized_(false), codec_(NULL), image_(NULL), last_timestamp_(0) { } EncoderVp8::~EncoderVp8() { if (initialized_) { vpx_codec_err_t ret = vpx_codec_destroy(codec_.get()); DCHECK(ret == VPX_CODEC_OK) << "Failed to destroy codec"; } } bool EncoderVp8::Init(int width, int height) { codec_.reset(new vpx_codec_ctx_t()); image_.reset(new vpx_image_t()); memset(image_.get(), 0, sizeof(vpx_image_t)); image_->fmt = VPX_IMG_FMT_YV12; // libvpx seems to require both to be assigned. image_->d_w = width; image_->w = width; image_->d_h = height; image_->h = height; vpx_codec_enc_cfg_t config; const vpx_codec_iface_t* algo = (const vpx_codec_iface_t*)media::GetVp8CxAlgoAddress(); CHECK(algo); vpx_codec_err_t ret = vpx_codec_enc_config_default(algo, &config, 0); if (ret != VPX_CODEC_OK) return false; // TODO(hclam): Tune the parameters to better suit the application. config.rc_target_bitrate = width * height * config.rc_target_bitrate / config.g_w / config.g_h; config.g_w = width; config.g_h = height; config.g_pass = VPX_RC_ONE_PASS; config.g_profile = 1; config.g_threads = 2; config.rc_min_quantizer = 0; config.rc_max_quantizer = 15; config.g_timebase.num = 1; config.g_timebase.den = 30; if (vpx_codec_enc_init(codec_.get(), algo, &config, 0)) return false; return true; } static int clip_byte(int x) { if (x > 255) return 255; else if (x < 0) return 0; else return x; } bool EncoderVp8::PrepareImage(scoped_refptr<CaptureData> capture_data) { const int plane_size = capture_data->width() * capture_data->height(); if (!yuv_image_.get()) { // YUV image size is 1.5 times of a plane. Multiplication is performed first // to avoid rounding error. const int size = plane_size * 3 / 2; yuv_image_.reset(new uint8[size]); // Reset image value to 128 so we just need to fill in the y plane. memset(yuv_image_.get(), 128, size); // Fill in the information for |image_|. unsigned char* image = reinterpret_cast<unsigned char*>(yuv_image_.get()); image_->planes[0] = image; image_->planes[1] = image + plane_size; // The V plane starts from 1.25 of the plane size. image_->planes[2] = image + plane_size + plane_size / 4; // In YV12 Y plane has full width, UV plane has half width because of // subsampling. image_->stride[0] = image_->w; image_->stride[1] = image_->w / 2; image_->stride[2] = image_->w / 2; } // And then do RGB->YUV conversion. // Currently we just produce the Y channel as the average of RGB. This will // giv ae gray scale image after conversion. // TODO(sergeyu): Move this code to a separate routine. // TODO(sergeyu): Optimize this code. DCHECK(capture_data->pixel_format() == media::VideoFrame::RGB32) << "Only RGB32 is supported"; uint8* in = capture_data->data_planes().data[0]; const int in_stride = capture_data->data_planes().strides[0]; uint8* y_out = yuv_image_.get(); uint8* u_out = yuv_image_.get() + plane_size; uint8* v_out = yuv_image_.get() + plane_size + plane_size / 4; const int out_stride = image_->stride[0]; for (int i = 0; i < capture_data->height(); ++i) { for (int j = 0; j < capture_data->width(); ++j) { // Since the input pixel format is RGB32, there are 4 bytes per pixel. uint8* pixel = in + 4 * j; y_out[j] = clip_byte(((pixel[2] * 66 + pixel[1] * 129 + pixel[0] * 25 + 128) >> 8) + 16); if (i % 2 == 0 && j % 2 == 0) { u_out[j / 2] = clip_byte(((pixel[2] * -38 + pixel[1] * -74 + pixel[0] * 112 + 128) >> 8) + 128); v_out[j / 2] = clip_byte(((pixel[2] * 112 + pixel[1] * -94 + pixel[1] * -18 + 128) >> 8) + 128); } } in += in_stride; y_out += out_stride; if (i % 2 == 0) { u_out += out_stride / 2; v_out += out_stride / 2; } } return true; } void EncoderVp8::Encode(scoped_refptr<CaptureData> capture_data, bool key_frame, DataAvailableCallback* data_available_callback) { if (!initialized_) { bool ret = Init(capture_data->width(), capture_data->height()); // TODO(hclam): Handle error better. DCHECK(ret) << "Initialization of encoder failed"; initialized_ = ret; } if (!PrepareImage(capture_data)) { NOTREACHED() << "Can't image data for encoding"; } // Do the actual encoding. vpx_codec_err_t ret = vpx_codec_encode(codec_.get(), image_.get(), last_timestamp_, 1, 0, VPX_DL_REALTIME); DCHECK_EQ(ret, VPX_CODEC_OK) << "Encoding error: " << vpx_codec_err_to_string(ret) << "\n" << "Details: " << vpx_codec_error(codec_.get()) << "\n" << vpx_codec_error_detail(codec_.get()); // TODO(hclam): fix this. last_timestamp_ += 100; // Read the encoded data. vpx_codec_iter_t iter = NULL; bool got_data = false; // TODO(hclam): Make sure we get exactly one frame from the packet. // TODO(hclam): We should provide the output buffer to avoid one copy. VideoPacket* message = new VideoPacket(); while (!got_data) { const vpx_codec_cx_pkt_t* packet = vpx_codec_get_cx_data(codec_.get(), &iter); if (!packet) continue; switch (packet->kind) { case VPX_CODEC_CX_FRAME_PKT: got_data = true; message->set_data(packet->data.frame.buf, packet->data.frame.sz); break; default: break; } } message->mutable_format()->set_encoding(VideoPacketFormat::ENCODING_VP8); message->set_flags(VideoPacket::FIRST_PACKET | VideoPacket::LAST_PACKET); data_available_callback->Run(message); delete data_available_callback; } } // namespace remoting <|endoftext|>
<commit_before>// Copyright (c) 2011 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "remoting/base/encoder_vp8.h" #include "base/logging.h" #include "media/base/callback.h" #include "media/base/yuv_convert.h" #include "remoting/base/capture_data.h" #include "remoting/base/util.h" #include "remoting/proto/video.pb.h" extern "C" { #define VPX_CODEC_DISABLE_COMPAT 1 #include "third_party/libvpx/source/libvpx/vpx/vpx_codec.h" #include "third_party/libvpx/source/libvpx/vpx/vpx_encoder.h" #include "third_party/libvpx/source/libvpx/vpx/vp8cx.h" } namespace remoting { EncoderVp8::EncoderVp8() : initialized_(false), codec_(NULL), image_(NULL), last_timestamp_(0) { } EncoderVp8::~EncoderVp8() { if (initialized_) { vpx_codec_err_t ret = vpx_codec_destroy(codec_.get()); DCHECK(ret == VPX_CODEC_OK) << "Failed to destroy codec"; } } bool EncoderVp8::Init(int width, int height) { codec_.reset(new vpx_codec_ctx_t()); image_.reset(new vpx_image_t()); memset(image_.get(), 0, sizeof(vpx_image_t)); image_->fmt = VPX_IMG_FMT_YV12; // libvpx seems to require both to be assigned. image_->d_w = width; image_->w = width; image_->d_h = height; image_->h = height; vpx_codec_enc_cfg_t config; const vpx_codec_iface_t* algo = vpx_codec_vp8_cx(); CHECK(algo); vpx_codec_err_t ret = vpx_codec_enc_config_default(algo, &config, 0); if (ret != VPX_CODEC_OK) return false; // TODO(hclam): Tune the parameters to better suit the application. config.rc_target_bitrate = width * height * config.rc_target_bitrate / config.g_w / config.g_h; config.g_w = width; config.g_h = height; config.g_pass = VPX_RC_ONE_PASS; config.g_profile = 1; config.g_threads = 2; config.rc_min_quantizer = 0; config.rc_max_quantizer = 15; config.g_timebase.num = 1; config.g_timebase.den = 30; if (vpx_codec_enc_init(codec_.get(), algo, &config, 0)) return false; return true; } static int RoundToTwosMultiple(int x) { return x & (~1); } // Align the sides of the rectange to multiples of 2. static gfx::Rect AlignRect(const gfx::Rect& rect, int width, int height) { CHECK(rect.width() > 0 && rect.height() > 0); int x = RoundToTwosMultiple(rect.x()); int y = RoundToTwosMultiple(rect.y()); int right = std::min(RoundToTwosMultiple(rect.right() + 1), RoundToTwosMultiple(width)); int bottom = std::min(RoundToTwosMultiple(rect.bottom() + 1), RoundToTwosMultiple(height)); // Do the final check to make sure the width and height are not negative. gfx::Rect r(x, y, right - x, bottom - y); if (r.width() <= 0 || r.height() <= 0) { r.set_width(0); r.set_height(0); } return r; } bool EncoderVp8::PrepareImage(scoped_refptr<CaptureData> capture_data, std::vector<gfx::Rect>* updated_rects) { const int plane_size = capture_data->width() * capture_data->height(); if (!yuv_image_.get()) { // YUV image size is 1.5 times of a plane. Multiplication is performed first // to avoid rounding error. const int size = plane_size * 3 / 2; yuv_image_.reset(new uint8[size]); // Reset image value to 128 so we just need to fill in the y plane. memset(yuv_image_.get(), 128, size); // Fill in the information for |image_|. unsigned char* image = reinterpret_cast<unsigned char*>(yuv_image_.get()); image_->planes[0] = image; image_->planes[1] = image + plane_size; // The V plane starts from 1.25 of the plane size. image_->planes[2] = image + plane_size + plane_size / 4; // In YV12 Y plane has full width, UV plane has half width because of // subsampling. image_->stride[0] = image_->w; image_->stride[1] = image_->w / 2; image_->stride[2] = image_->w / 2; } // Perform RGB->YUV conversion. if (capture_data->pixel_format() != media::VideoFrame::RGB32) { LOG(ERROR) << "Only RGB32 is supported"; return false; } const InvalidRects& rects = capture_data->dirty_rects(); const uint8* in = capture_data->data_planes().data[0]; const int in_stride = capture_data->data_planes().strides[0]; uint8* y_out = yuv_image_.get(); uint8* u_out = yuv_image_.get() + plane_size; uint8* v_out = yuv_image_.get() + plane_size + plane_size / 4; const int y_stride = image_->stride[0]; const int uv_stride = image_->stride[1]; DCHECK(updated_rects->empty()); for (InvalidRects::const_iterator r = rects.begin(); r != rects.end(); ++r) { // Align the rectangle report it as updated. gfx::Rect rect = AlignRect(*r, image_->w, image_->h); updated_rects->push_back(rect); ConvertRGB32ToYUVWithRect(in, y_out, u_out, v_out, rect.x(), rect.y(), rect.width(), rect.height(), in_stride, y_stride, uv_stride); } return true; } void EncoderVp8::Encode(scoped_refptr<CaptureData> capture_data, bool key_frame, DataAvailableCallback* data_available_callback) { if (!initialized_) { bool ret = Init(capture_data->width(), capture_data->height()); // TODO(hclam): Handle error better. DCHECK(ret) << "Initialization of encoder failed"; initialized_ = ret; } std::vector<gfx::Rect> updated_rects; if (!PrepareImage(capture_data, &updated_rects)) { NOTREACHED() << "Can't image data for encoding"; } // Do the actual encoding. vpx_codec_err_t ret = vpx_codec_encode(codec_.get(), image_.get(), last_timestamp_, 1, 0, VPX_DL_REALTIME); DCHECK_EQ(ret, VPX_CODEC_OK) << "Encoding error: " << vpx_codec_err_to_string(ret) << "\n" << "Details: " << vpx_codec_error(codec_.get()) << "\n" << vpx_codec_error_detail(codec_.get()); // TODO(hclam): fix this. last_timestamp_ += 100; // Read the encoded data. vpx_codec_iter_t iter = NULL; bool got_data = false; // TODO(hclam): Make sure we get exactly one frame from the packet. // TODO(hclam): We should provide the output buffer to avoid one copy. VideoPacket* message = new VideoPacket(); while (!got_data) { const vpx_codec_cx_pkt_t* packet = vpx_codec_get_cx_data(codec_.get(), &iter); if (!packet) continue; switch (packet->kind) { case VPX_CODEC_CX_FRAME_PKT: got_data = true; // TODO(sergeyu): Split each frame into multiple partitions. message->set_data(packet->data.frame.buf, packet->data.frame.sz); break; default: break; } } message->mutable_format()->set_encoding(VideoPacketFormat::ENCODING_VP8); message->set_flags(VideoPacket::FIRST_PACKET | VideoPacket::LAST_PACKET | VideoPacket::LAST_PARTITION); for (size_t i = 0; i < updated_rects.size(); ++i) { Rect* rect = message->add_dirty_rects(); rect->set_x(updated_rects[i].x()); rect->set_y(updated_rects[i].y()); rect->set_width(updated_rects[i].width()); rect->set_height(updated_rects[i].height()); } data_available_callback->Run(message); delete data_available_callback; } } // namespace remoting <commit_msg>Lower image quality for chromoting to improve encode speed and compression ratio<commit_after>// Copyright (c) 2011 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "remoting/base/encoder_vp8.h" #include "base/logging.h" #include "media/base/callback.h" #include "media/base/yuv_convert.h" #include "remoting/base/capture_data.h" #include "remoting/base/util.h" #include "remoting/proto/video.pb.h" extern "C" { #define VPX_CODEC_DISABLE_COMPAT 1 #include "third_party/libvpx/source/libvpx/vpx/vpx_codec.h" #include "third_party/libvpx/source/libvpx/vpx/vpx_encoder.h" #include "third_party/libvpx/source/libvpx/vpx/vp8cx.h" } namespace remoting { EncoderVp8::EncoderVp8() : initialized_(false), codec_(NULL), image_(NULL), last_timestamp_(0) { } EncoderVp8::~EncoderVp8() { if (initialized_) { vpx_codec_err_t ret = vpx_codec_destroy(codec_.get()); DCHECK(ret == VPX_CODEC_OK) << "Failed to destroy codec"; } } bool EncoderVp8::Init(int width, int height) { codec_.reset(new vpx_codec_ctx_t()); image_.reset(new vpx_image_t()); memset(image_.get(), 0, sizeof(vpx_image_t)); image_->fmt = VPX_IMG_FMT_YV12; // libvpx seems to require both to be assigned. image_->d_w = width; image_->w = width; image_->d_h = height; image_->h = height; vpx_codec_enc_cfg_t config; const vpx_codec_iface_t* algo = vpx_codec_vp8_cx(); CHECK(algo); vpx_codec_err_t ret = vpx_codec_enc_config_default(algo, &config, 0); if (ret != VPX_CODEC_OK) return false; // TODO(hclam): Tune the parameters to better suit the application. config.rc_target_bitrate = width * height * config.rc_target_bitrate / config.g_w / config.g_h; config.g_w = width; config.g_h = height; config.g_pass = VPX_RC_ONE_PASS; config.g_profile = 1; config.g_threads = 2; config.rc_min_quantizer = 20; config.rc_max_quantizer = 30; config.g_timebase.num = 1; config.g_timebase.den = 30; if (vpx_codec_enc_init(codec_.get(), algo, &config, 0)) return false; return true; } static int RoundToTwosMultiple(int x) { return x & (~1); } // Align the sides of the rectange to multiples of 2. static gfx::Rect AlignRect(const gfx::Rect& rect, int width, int height) { CHECK(rect.width() > 0 && rect.height() > 0); int x = RoundToTwosMultiple(rect.x()); int y = RoundToTwosMultiple(rect.y()); int right = std::min(RoundToTwosMultiple(rect.right() + 1), RoundToTwosMultiple(width)); int bottom = std::min(RoundToTwosMultiple(rect.bottom() + 1), RoundToTwosMultiple(height)); // Do the final check to make sure the width and height are not negative. gfx::Rect r(x, y, right - x, bottom - y); if (r.width() <= 0 || r.height() <= 0) { r.set_width(0); r.set_height(0); } return r; } bool EncoderVp8::PrepareImage(scoped_refptr<CaptureData> capture_data, std::vector<gfx::Rect>* updated_rects) { const int plane_size = capture_data->width() * capture_data->height(); if (!yuv_image_.get()) { // YUV image size is 1.5 times of a plane. Multiplication is performed first // to avoid rounding error. const int size = plane_size * 3 / 2; yuv_image_.reset(new uint8[size]); // Reset image value to 128 so we just need to fill in the y plane. memset(yuv_image_.get(), 128, size); // Fill in the information for |image_|. unsigned char* image = reinterpret_cast<unsigned char*>(yuv_image_.get()); image_->planes[0] = image; image_->planes[1] = image + plane_size; // The V plane starts from 1.25 of the plane size. image_->planes[2] = image + plane_size + plane_size / 4; // In YV12 Y plane has full width, UV plane has half width because of // subsampling. image_->stride[0] = image_->w; image_->stride[1] = image_->w / 2; image_->stride[2] = image_->w / 2; } // Perform RGB->YUV conversion. if (capture_data->pixel_format() != media::VideoFrame::RGB32) { LOG(ERROR) << "Only RGB32 is supported"; return false; } const InvalidRects& rects = capture_data->dirty_rects(); const uint8* in = capture_data->data_planes().data[0]; const int in_stride = capture_data->data_planes().strides[0]; uint8* y_out = yuv_image_.get(); uint8* u_out = yuv_image_.get() + plane_size; uint8* v_out = yuv_image_.get() + plane_size + plane_size / 4; const int y_stride = image_->stride[0]; const int uv_stride = image_->stride[1]; DCHECK(updated_rects->empty()); for (InvalidRects::const_iterator r = rects.begin(); r != rects.end(); ++r) { // Align the rectangle report it as updated. gfx::Rect rect = AlignRect(*r, image_->w, image_->h); updated_rects->push_back(rect); ConvertRGB32ToYUVWithRect(in, y_out, u_out, v_out, rect.x(), rect.y(), rect.width(), rect.height(), in_stride, y_stride, uv_stride); } return true; } void EncoderVp8::Encode(scoped_refptr<CaptureData> capture_data, bool key_frame, DataAvailableCallback* data_available_callback) { if (!initialized_) { bool ret = Init(capture_data->width(), capture_data->height()); // TODO(hclam): Handle error better. DCHECK(ret) << "Initialization of encoder failed"; initialized_ = ret; } std::vector<gfx::Rect> updated_rects; if (!PrepareImage(capture_data, &updated_rects)) { NOTREACHED() << "Can't image data for encoding"; } // Do the actual encoding. vpx_codec_err_t ret = vpx_codec_encode(codec_.get(), image_.get(), last_timestamp_, 1, 0, VPX_DL_REALTIME); DCHECK_EQ(ret, VPX_CODEC_OK) << "Encoding error: " << vpx_codec_err_to_string(ret) << "\n" << "Details: " << vpx_codec_error(codec_.get()) << "\n" << vpx_codec_error_detail(codec_.get()); // TODO(hclam): fix this. last_timestamp_ += 100; // Read the encoded data. vpx_codec_iter_t iter = NULL; bool got_data = false; // TODO(hclam): Make sure we get exactly one frame from the packet. // TODO(hclam): We should provide the output buffer to avoid one copy. VideoPacket* message = new VideoPacket(); while (!got_data) { const vpx_codec_cx_pkt_t* packet = vpx_codec_get_cx_data(codec_.get(), &iter); if (!packet) continue; switch (packet->kind) { case VPX_CODEC_CX_FRAME_PKT: got_data = true; // TODO(sergeyu): Split each frame into multiple partitions. message->set_data(packet->data.frame.buf, packet->data.frame.sz); break; default: break; } } message->mutable_format()->set_encoding(VideoPacketFormat::ENCODING_VP8); message->set_flags(VideoPacket::FIRST_PACKET | VideoPacket::LAST_PACKET | VideoPacket::LAST_PARTITION); for (size_t i = 0; i < updated_rects.size(); ++i) { Rect* rect = message->add_dirty_rects(); rect->set_x(updated_rects[i].x()); rect->set_y(updated_rects[i].y()); rect->set_width(updated_rects[i].width()); rect->set_height(updated_rects[i].height()); } data_available_callback->Run(message); delete data_available_callback; } } // namespace remoting <|endoftext|>
<commit_before>// Copyright 2013 The Flutter Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "flutter/shell/platform/embedder/tests/embedder_test_context_gl.h" #include "flutter/fml/make_copyable.h" #include "flutter/fml/paths.h" #include "flutter/runtime/dart_vm.h" #include "flutter/shell/platform/embedder/tests/embedder_assertions.h" #include "flutter/shell/platform/embedder/tests/embedder_test_compositor_gl.h" #include "flutter/testing/testing.h" #include "tests/embedder_test.h" #include "third_party/dart/runtime/bin/elf_loader.h" #include "third_party/skia/include/core/SkSurface.h" namespace flutter { namespace testing { EmbedderTestContextGL::EmbedderTestContextGL(std::string assets_path) : EmbedderTestContext(assets_path) {} EmbedderTestContextGL::~EmbedderTestContextGL() { SetGLGetFBOCallback(nullptr); } void EmbedderTestContextGL::SetupSurface(SkISize surface_size) { FML_CHECK(!gl_surface_); gl_surface_ = std::make_unique<TestGLSurface>(surface_size); } bool EmbedderTestContextGL::GLMakeCurrent() { FML_CHECK(gl_surface_) << "GL surface must be initialized."; return gl_surface_->MakeCurrent(); } bool EmbedderTestContextGL::GLClearCurrent() { FML_CHECK(gl_surface_) << "GL surface must be initialized."; return gl_surface_->ClearCurrent(); } bool EmbedderTestContextGL::GLPresent(uint32_t fbo_id) { FML_CHECK(gl_surface_) << "GL surface must be initialized."; gl_surface_present_count_++; GLPresentCallback callback; { std::scoped_lock lock(gl_callback_mutex_); callback = gl_present_callback_; } if (callback) { callback(fbo_id); } FireRootSurfacePresentCallbackIfPresent( [&]() { return gl_surface_->GetRasterSurfaceSnapshot(); }); return gl_surface_->Present(); } void EmbedderTestContextGL::SetGLGetFBOCallback(GLGetFBOCallback callback) { std::scoped_lock lock(gl_callback_mutex_); gl_get_fbo_callback_ = callback; } void EmbedderTestContextGL::SetGLPresentCallback(GLPresentCallback callback) { std::scoped_lock lock(gl_callback_mutex_); gl_present_callback_ = callback; } uint32_t EmbedderTestContextGL::GLGetFramebuffer(FlutterFrameInfo frame_info) { FML_CHECK(gl_surface_) << "GL surface must be initialized."; GLGetFBOCallback callback; { std::scoped_lock lock(gl_callback_mutex_); callback = gl_get_fbo_callback_; } if (callback) { callback(frame_info); } const auto size = frame_info.size; return gl_surface_->GetFramebuffer(size.width, size.height); } bool EmbedderTestContextGL::GLMakeResourceCurrent() { FML_CHECK(gl_surface_) << "GL surface must be initialized."; return gl_surface_->MakeResourceCurrent(); } void* EmbedderTestContextGL::GLGetProcAddress(const char* name) { FML_CHECK(gl_surface_) << "GL surface must be initialized."; return gl_surface_->GetProcAddress(name); } size_t EmbedderTestContextGL::GetSurfacePresentCount() const { return gl_surface_present_count_; } EmbedderTestContextType EmbedderTestContextGL::GetContextType() const { return EmbedderTestContextType::kOpenGLContext; } uint32_t EmbedderTestContextGL::GetWindowFBOId() const { FML_CHECK(gl_surface_); return gl_surface_->GetWindowFBOId(); } void EmbedderTestContextGL::SetupCompositor() { FML_CHECK(!compositor_) << "Already set up a compositor in this context."; FML_CHECK(gl_surface_) << "Set up the GL surface before setting up a compositor."; compositor_ = std::make_unique<EmbedderTestCompositorGL>( gl_surface_->GetSurfaceSize(), gl_surface_->GetGrContext()); } } // namespace testing } // namespace flutter <commit_msg>Detach the newly created EGL context from the main thread in the embedder unit tests (#24908)<commit_after>// Copyright 2013 The Flutter Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "flutter/shell/platform/embedder/tests/embedder_test_context_gl.h" #include "flutter/fml/make_copyable.h" #include "flutter/fml/paths.h" #include "flutter/runtime/dart_vm.h" #include "flutter/shell/platform/embedder/tests/embedder_assertions.h" #include "flutter/shell/platform/embedder/tests/embedder_test_compositor_gl.h" #include "flutter/testing/testing.h" #include "tests/embedder_test.h" #include "third_party/dart/runtime/bin/elf_loader.h" #include "third_party/skia/include/core/SkSurface.h" namespace flutter { namespace testing { EmbedderTestContextGL::EmbedderTestContextGL(std::string assets_path) : EmbedderTestContext(assets_path) {} EmbedderTestContextGL::~EmbedderTestContextGL() { SetGLGetFBOCallback(nullptr); } void EmbedderTestContextGL::SetupSurface(SkISize surface_size) { FML_CHECK(!gl_surface_); gl_surface_ = std::make_unique<TestGLSurface>(surface_size); } bool EmbedderTestContextGL::GLMakeCurrent() { FML_CHECK(gl_surface_) << "GL surface must be initialized."; return gl_surface_->MakeCurrent(); } bool EmbedderTestContextGL::GLClearCurrent() { FML_CHECK(gl_surface_) << "GL surface must be initialized."; return gl_surface_->ClearCurrent(); } bool EmbedderTestContextGL::GLPresent(uint32_t fbo_id) { FML_CHECK(gl_surface_) << "GL surface must be initialized."; gl_surface_present_count_++; GLPresentCallback callback; { std::scoped_lock lock(gl_callback_mutex_); callback = gl_present_callback_; } if (callback) { callback(fbo_id); } FireRootSurfacePresentCallbackIfPresent( [&]() { return gl_surface_->GetRasterSurfaceSnapshot(); }); return gl_surface_->Present(); } void EmbedderTestContextGL::SetGLGetFBOCallback(GLGetFBOCallback callback) { std::scoped_lock lock(gl_callback_mutex_); gl_get_fbo_callback_ = callback; } void EmbedderTestContextGL::SetGLPresentCallback(GLPresentCallback callback) { std::scoped_lock lock(gl_callback_mutex_); gl_present_callback_ = callback; } uint32_t EmbedderTestContextGL::GLGetFramebuffer(FlutterFrameInfo frame_info) { FML_CHECK(gl_surface_) << "GL surface must be initialized."; GLGetFBOCallback callback; { std::scoped_lock lock(gl_callback_mutex_); callback = gl_get_fbo_callback_; } if (callback) { callback(frame_info); } const auto size = frame_info.size; return gl_surface_->GetFramebuffer(size.width, size.height); } bool EmbedderTestContextGL::GLMakeResourceCurrent() { FML_CHECK(gl_surface_) << "GL surface must be initialized."; return gl_surface_->MakeResourceCurrent(); } void* EmbedderTestContextGL::GLGetProcAddress(const char* name) { FML_CHECK(gl_surface_) << "GL surface must be initialized."; return gl_surface_->GetProcAddress(name); } size_t EmbedderTestContextGL::GetSurfacePresentCount() const { return gl_surface_present_count_; } EmbedderTestContextType EmbedderTestContextGL::GetContextType() const { return EmbedderTestContextType::kOpenGLContext; } uint32_t EmbedderTestContextGL::GetWindowFBOId() const { FML_CHECK(gl_surface_); return gl_surface_->GetWindowFBOId(); } void EmbedderTestContextGL::SetupCompositor() { FML_CHECK(!compositor_) << "Already set up a compositor in this context."; FML_CHECK(gl_surface_) << "Set up the GL surface before setting up a compositor."; compositor_ = std::make_unique<EmbedderTestCompositorGL>( gl_surface_->GetSurfaceSize(), gl_surface_->GetGrContext()); GLClearCurrent(); } } // namespace testing } // namespace flutter <|endoftext|>
<commit_before>#include "Lowe_Andersen.h" #include "Polymer.h" #include "Monomer.h" #include "consts.h" using namespace consts; #include<cmath> using namespace std; Lowe_Andersen::Lowe_Andersen(Polymer &poly, double dtime, double nu) : poly(poly), nu(nu), uniform_real(0.,1.), gauss_real(0.,1.) { time_step(dtime); update_sigma(); } double Lowe_Andersen::update_sigma() { sigma=sqrt(2*ref_k*poly.temp()/poly.monomer_mass); return sigma; } double Lowe_Andersen::time_step() {return dtime;} double Lowe_Andersen::time_step(double dt) { dtime=dt; dtime2=dtime/2; nu_dt=nu*dtime; return dtime; } void Lowe_Andersen::propagate() { double delta_v=0, therm_v=0; auto m_i= poly.monomers.begin(); auto m_j= m_i; // velocity verlet for (auto& m : poly.monomers) { m.velocity += dtime2*m.force/poly.monomer_mass; m.position += dtime*m.velocity; } //Lowe_Andersen for (m_i = poly.monomers.begin(); m_i != poly.monomers.end(); ++m_i) { if ( nu_dt < uniform_real(generator) ) continue; m_j=m_i; ++m_j; if ( m_j == poly.monomers.end() ) m_j=poly.monomers.begin(); delta_v=m_i->velocity - m_j->velocity; therm_v=poly.monomer_mass*0.5*( delta_v - copysign( sigma, delta_v )*gauss_real(generator) ); m_i->velocity += therm_v; m_j->velocity -= therm_v; } // second half of vel. verlet poly.update_forces(); for (auto& m : poly.monomers) { m.velocity += dtime2*m.force/poly.monomer_mass; } } <commit_msg>Umbennen der Variablen um Verwechslung zu vermeiden<commit_after>#include "Lowe_Andersen.h" #include "Polymer.h" #include "Monomer.h" #include "consts.h" using namespace consts; #include<cmath> using namespace std; Lowe_Andersen::Lowe_Andersen(Polymer &poly, double dtime, double nu) : poly(poly), nu(nu), uniform_real(0.,1.), gauss_real(0.,1.) { time_step(dtime); update_sigma(); } double Lowe_Andersen::update_sigma() { sigma=sqrt(2*ref_k*poly.temp()/poly.monomer_mass); return sigma; } double Lowe_Andersen::time_step() {return dtime;} double Lowe_Andersen::time_step(double dt) { dtime=dt; dtime2=dtime/2; nu_dt=nu*dtime; return dtime; } void Lowe_Andersen::propagate() { double delta_v=0, therm_v=0; auto mi= poly.monomers.begin(); auto mj= mi; // velocity verlet for (auto& m : poly.monomers) { m.velocity += dtime2*m.force/poly.monomer_mass; m.position += dtime*m.velocity; } //Lowe_Andersen for (mi = poly.monomers.begin(); mi != poly.monomers.end(); ++mi) { if ( nu_dt < uniform_real(generator) ) continue; mj=mi; ++mj; if ( mj == poly.monomers.end() ) mj=poly.monomers.begin(); delta_v=mi->velocity - mj->velocity; therm_v=poly.monomer_mass*0.5*( delta_v - copysign( sigma, delta_v )*gauss_real(generator) ); mi->velocity += therm_v; mj->velocity -= therm_v; } // second half of vel. verlet poly.update_forces(); for (auto& m : poly.monomers) { m.velocity += dtime2*m.force/poly.monomer_mass; } } <|endoftext|>
<commit_before>/* libs/graphics/effects/Sk2DPathEffect.cpp ** ** Copyright 2006, The Android Open Source Project ** ** 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 "Sk2DPathEffect.h" #include "SkBlitter.h" #include "SkPath.h" #include "SkScan.h" class Sk2DPathEffectBlitter : public SkBlitter { public: Sk2DPathEffectBlitter(Sk2DPathEffect* pe, SkPath* dst) : fPE(pe), fDst(dst) {} virtual void blitH(int x, int y, int count) { fPE->nextSpan(x, y, count, fDst); } private: Sk2DPathEffect* fPE; SkPath* fDst; }; //////////////////////////////////////////////////////////////////////////////////// Sk2DPathEffect::Sk2DPathEffect(const SkMatrix& mat) : fMatrix(mat) { mat.invert(&fInverse); } bool Sk2DPathEffect::filterPath(SkPath* dst, const SkPath& src, SkScalar* width) { Sk2DPathEffectBlitter blitter(this, dst); SkPath tmp; SkIRect ir; src.transform(fInverse, &tmp); tmp.getBounds().round(&ir); if (!ir.isEmpty()) { // need to pass a clip to fillpath, required for inverse filltypes, // even though those do not make sense for this patheffect SkRegion clip(ir); this->begin(ir, dst); SkScan::FillPath(tmp, clip, &blitter); this->end(dst); } return true; } void Sk2DPathEffect::nextSpan(int x, int y, int count, SkPath* path) { const SkMatrix& mat = this->getMatrix(); SkPoint src, dst; src.set(SkIntToScalar(x) + SK_ScalarHalf, SkIntToScalar(y) + SK_ScalarHalf); do { mat.mapPoints(&dst, &src, 1); this->next(dst, x++, y, path); src.fX += SK_Scalar1; } while (--count > 0); } void Sk2DPathEffect::begin(const SkIRect& uvBounds, SkPath* dst) {} void Sk2DPathEffect::next(const SkPoint& loc, int u, int v, SkPath* dst) {} void Sk2DPathEffect::end(SkPath* dst) {} //////////////////////////////////////////////////////////////////////////////// void Sk2DPathEffect::flatten(SkFlattenableWriteBuffer& buffer) { buffer.writeMul4(&fMatrix, sizeof(fMatrix)); } Sk2DPathEffect::Sk2DPathEffect(SkFlattenableReadBuffer& buffer) { buffer.read(&fMatrix, sizeof(fMatrix)); fMatrix.invert(&fInverse); } SkFlattenable::Factory Sk2DPathEffect::getFactory() { return CreateProc; } SkFlattenable* Sk2DPathEffect::CreateProc(SkFlattenableReadBuffer& buffer) { return SkNEW_ARGS(Sk2DPathEffect, (buffer)); } <commit_msg>Fix unnitialized memory in Sk2DPathEffect. The SkDescriptor checksum calculation for Sk2DPathEffect currently evaluates all the bytes in the embedded SkMatrix. This includes the type mask, which contains some uninitialized padding. Changing it to use SkMatrix::flatten() and SkMatrix::unflatten() (as SkGroupShape was doing) avoids the uninitialized data errors.<commit_after>/* libs/graphics/effects/Sk2DPathEffect.cpp ** ** Copyright 2006, The Android Open Source Project ** ** 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 "Sk2DPathEffect.h" #include "SkBlitter.h" #include "SkPath.h" #include "SkScan.h" class Sk2DPathEffectBlitter : public SkBlitter { public: Sk2DPathEffectBlitter(Sk2DPathEffect* pe, SkPath* dst) : fPE(pe), fDst(dst) {} virtual void blitH(int x, int y, int count) { fPE->nextSpan(x, y, count, fDst); } private: Sk2DPathEffect* fPE; SkPath* fDst; }; //////////////////////////////////////////////////////////////////////////////////// Sk2DPathEffect::Sk2DPathEffect(const SkMatrix& mat) : fMatrix(mat) { mat.invert(&fInverse); } bool Sk2DPathEffect::filterPath(SkPath* dst, const SkPath& src, SkScalar* width) { Sk2DPathEffectBlitter blitter(this, dst); SkPath tmp; SkIRect ir; src.transform(fInverse, &tmp); tmp.getBounds().round(&ir); if (!ir.isEmpty()) { // need to pass a clip to fillpath, required for inverse filltypes, // even though those do not make sense for this patheffect SkRegion clip(ir); this->begin(ir, dst); SkScan::FillPath(tmp, clip, &blitter); this->end(dst); } return true; } void Sk2DPathEffect::nextSpan(int x, int y, int count, SkPath* path) { const SkMatrix& mat = this->getMatrix(); SkPoint src, dst; src.set(SkIntToScalar(x) + SK_ScalarHalf, SkIntToScalar(y) + SK_ScalarHalf); do { mat.mapPoints(&dst, &src, 1); this->next(dst, x++, y, path); src.fX += SK_Scalar1; } while (--count > 0); } void Sk2DPathEffect::begin(const SkIRect& uvBounds, SkPath* dst) {} void Sk2DPathEffect::next(const SkPoint& loc, int u, int v, SkPath* dst) {} void Sk2DPathEffect::end(SkPath* dst) {} //////////////////////////////////////////////////////////////////////////////// void Sk2DPathEffect::flatten(SkFlattenableWriteBuffer& buffer) { char storage[SkMatrix::kMaxFlattenSize]; uint32_t size = fMatrix.flatten(storage); buffer.write32(size); buffer.write(storage, size); } Sk2DPathEffect::Sk2DPathEffect(SkFlattenableReadBuffer& buffer) { char storage[SkMatrix::kMaxFlattenSize]; uint32_t size = buffer.readS32(); SkASSERT(size <= sizeof(storage)); buffer.read(storage, size); fMatrix.unflatten(storage); fMatrix.invert(&fInverse); } SkFlattenable::Factory Sk2DPathEffect::getFactory() { return CreateProc; } SkFlattenable* Sk2DPathEffect::CreateProc(SkFlattenableReadBuffer& buffer) { return SkNEW_ARGS(Sk2DPathEffect, (buffer)); } <|endoftext|>
<commit_before>/* * OpenSSL Hash Functions * (C) 1999-2007 Jack Lloyd * * Distributed under the terms of the Botan license */ #include <botan/internal/openssl_engine.h> #include <openssl/evp.h> namespace Botan { namespace { /* * EVP Hash Function */ class EVP_HashFunction : public HashFunction { public: void clear(); std::string name() const { return algo_name; } HashFunction* clone() const; EVP_HashFunction(const EVP_MD*, const std::string&); ~EVP_HashFunction(); private: void add_data(const byte[], size_t); void final_result(byte[]); std::string algo_name; EVP_MD_CTX md; }; /* * Update an EVP Hash Calculation */ void EVP_HashFunction::add_data(const byte input[], size_t length) { EVP_DigestUpdate(&md, input, length); } /* * Finalize an EVP Hash Calculation */ void EVP_HashFunction::final_result(byte output[]) { EVP_DigestFinal_ex(&md, output, 0); const EVP_MD* algo = EVP_MD_CTX_md(&md); EVP_DigestInit_ex(&md, algo, 0); } /* * Clear memory of sensitive data */ void EVP_HashFunction::clear() { const EVP_MD* algo = EVP_MD_CTX_md(&md); EVP_DigestInit_ex(&md, algo, 0); } /* * Return a clone of this object */ HashFunction* EVP_HashFunction::clone() const { const EVP_MD* algo = EVP_MD_CTX_md(&md); return new EVP_HashFunction(algo, name()); } /* * Create an EVP hash function */ EVP_HashFunction::EVP_HashFunction(const EVP_MD* algo, const std::string& name) : HashFunction(EVP_MD_size(algo), EVP_MD_block_size(algo)), algo_name(name) { EVP_MD_CTX_init(&md); EVP_DigestInit_ex(&md, algo, 0); } /* * Destroy an EVP hash function */ EVP_HashFunction::~EVP_HashFunction() { EVP_MD_CTX_cleanup(&md); } } /* * Look for an algorithm with this name */ HashFunction* OpenSSL_Engine::find_hash(const SCAN_Name& request, Algorithm_Factory&) const { #if !defined(OPENSSL_NO_SHA) if(request.algo_name() == "SHA-160") return new EVP_HashFunction(EVP_sha1(), "SHA-160"); #endif #if !defined(OPENSSL_NO_SHA256) if(request.algo_name() == "SHA-224") return new EVP_HashFunction(EVP_sha224(), "SHA-224"); if(request.algo_name() == "SHA-256") return new EVP_HashFunction(EVP_sha256(), "SHA-256"); #endif #if !defined(OPENSSL_NO_SHA512) if(request.algo_name() == "SHA-384") return new EVP_HashFunction(EVP_sha384(), "SHA-384"); if(request.algo_name() == "SHA-512") return new EVP_HashFunction(EVP_sha512(), "SHA-512"); #endif #if !defined(OPENSSL_NO_MD2) if(request.algo_name() == "MD2") return new EVP_HashFunction(EVP_md2(), "MD2"); #endif #if !defined(OPENSSL_NO_MD4) if(request.algo_name() == "MD4") return new EVP_HashFunction(EVP_md4(), "MD4"); #endif #if !defined(OPENSSL_NO_MD5) if(request.algo_name() == "MD5") return new EVP_HashFunction(EVP_md5(), "MD5"); #endif #if !defined(OPENSSL_NO_RIPEMD) if(request.algo_name() == "RIPEMD-160") return new EVP_HashFunction(EVP_ripemd160(), "RIPEMD-160"); #endif return 0; } } <commit_msg>Fix compile<commit_after>/* * OpenSSL Hash Functions * (C) 1999-2007 Jack Lloyd * * Distributed under the terms of the Botan license */ #include <botan/internal/openssl_engine.h> #include <openssl/evp.h> namespace Botan { namespace { /* * EVP Hash Function */ class EVP_HashFunction : public HashFunction { public: void clear(); std::string name() const { return algo_name; } HashFunction* clone() const; size_t hash_block_size() const { return block_size; } EVP_HashFunction(const EVP_MD*, const std::string&); ~EVP_HashFunction(); private: void add_data(const byte[], size_t); void final_result(byte[]); size_t block_size; std::string algo_name; EVP_MD_CTX md; }; /* * Update an EVP Hash Calculation */ void EVP_HashFunction::add_data(const byte input[], size_t length) { EVP_DigestUpdate(&md, input, length); } /* * Finalize an EVP Hash Calculation */ void EVP_HashFunction::final_result(byte output[]) { EVP_DigestFinal_ex(&md, output, 0); const EVP_MD* algo = EVP_MD_CTX_md(&md); EVP_DigestInit_ex(&md, algo, 0); } /* * Clear memory of sensitive data */ void EVP_HashFunction::clear() { const EVP_MD* algo = EVP_MD_CTX_md(&md); EVP_DigestInit_ex(&md, algo, 0); } /* * Return a clone of this object */ HashFunction* EVP_HashFunction::clone() const { const EVP_MD* algo = EVP_MD_CTX_md(&md); return new EVP_HashFunction(algo, name()); } /* * Create an EVP hash function */ EVP_HashFunction::EVP_HashFunction(const EVP_MD* algo, const std::string& name) : HashFunction(EVP_MD_size(algo)), block_size(EVP_MD_block_size(algo)), algo_name(name) { EVP_MD_CTX_init(&md); EVP_DigestInit_ex(&md, algo, 0); } /* * Destroy an EVP hash function */ EVP_HashFunction::~EVP_HashFunction() { EVP_MD_CTX_cleanup(&md); } } /* * Look for an algorithm with this name */ HashFunction* OpenSSL_Engine::find_hash(const SCAN_Name& request, Algorithm_Factory&) const { #if !defined(OPENSSL_NO_SHA) if(request.algo_name() == "SHA-160") return new EVP_HashFunction(EVP_sha1(), "SHA-160"); #endif #if !defined(OPENSSL_NO_SHA256) if(request.algo_name() == "SHA-224") return new EVP_HashFunction(EVP_sha224(), "SHA-224"); if(request.algo_name() == "SHA-256") return new EVP_HashFunction(EVP_sha256(), "SHA-256"); #endif #if !defined(OPENSSL_NO_SHA512) if(request.algo_name() == "SHA-384") return new EVP_HashFunction(EVP_sha384(), "SHA-384"); if(request.algo_name() == "SHA-512") return new EVP_HashFunction(EVP_sha512(), "SHA-512"); #endif #if !defined(OPENSSL_NO_MD2) if(request.algo_name() == "MD2") return new EVP_HashFunction(EVP_md2(), "MD2"); #endif #if !defined(OPENSSL_NO_MD4) if(request.algo_name() == "MD4") return new EVP_HashFunction(EVP_md4(), "MD4"); #endif #if !defined(OPENSSL_NO_MD5) if(request.algo_name() == "MD5") return new EVP_HashFunction(EVP_md5(), "MD5"); #endif #if !defined(OPENSSL_NO_RIPEMD) if(request.algo_name() == "RIPEMD-160") return new EVP_HashFunction(EVP_ripemd160(), "RIPEMD-160"); #endif return 0; } } <|endoftext|>
<commit_before><commit_msg>replacing std::copy with std::copy_n<commit_after><|endoftext|>
<commit_before><commit_msg>Fix typog<commit_after><|endoftext|>
<commit_before>/* * Simulator.cc : part of the Mace toolkit for building distributed systems * * Copyright (c) 2011, Charles Killian, James W. Anderson * 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 names of the contributors, nor their associated universities * or organizations 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. * * ----END-OF-LEGAL-STUFF---- */ #include "PrintNodeFormatter.h" #include "Simulator.h" #include "SearchRandomUtil.h" #include "SearchStepRandomUtil.h" //#include "BestFirstRandomUtil.h" typedef SearchRandomUtil BestFirstRandomUtil; #include "ReplayRandomUtil.h" #include "LastNailRandomUtil.h" namespace macemc { void __Simulator__::dumpState() { ADD_SELECTORS("__Simulator__::dumpState"); if (! maceout.isNoop()) { SimApplication& app = SimApplication::Instance(); maceout << "Application State: " << app << Log::endl; /* mace::PrintNode pr("root", ""); app.print(pr, "SimApplication"); std::ostringstream os; mace::PrintNodeFormatter::print(os, pr); maceout << "Begin Printer State" << std::endl << os.str() << Log::endl; maceout << "End Printer State" << Log::endl; */ // std::ostringstream longos; // mace::PrintNodeFormatter::printWithTypes(longos, pr); // maceout << longos.str() << std::endl; // maceout << "Application State: " << app << std::endl; maceout << "EventsPending State: " << SimEventWeighted::PrintableInstance() << Log::endl; SimNetwork& net = SimNetwork::Instance(); maceout << "Network State: " << net << Log::endl; // Sim& sched = SimScheduler::Instance(); // maceout << "Scheduler State: " << sched << Log::endl; } } void __Simulator__::initializeVars() { use_hash = params::get("USE_STATE_HASHES", false); use_broken_hash = params::get("USE_BROKEN_HASH", false); loggingStartStep = params::get<unsigned>("LOGGING_START_STEP", 0); max_dead_paths = params::get("MAX_DEAD_PATHS", 1); num_nodes = params::get<int>("num_nodes"); // Make sure our random number generator is the appropriate one if (params::containsKey("RANDOM_REPLAY_FILE")) { use_hash = false; assert_safety = true; if (params::get<std::string>("RANDOM_REPLAY_FILE") == "-") { print_errors = true; RandomUtil::seedRandom(TimeUtil::timeu()); } else { print_errors = false; RandomUtil::seedRandom(0); } max_steps_error = true; randomUtil = ReplayRandomUtil::SetInstance(); divergenceMonitor = params::get("RUN_DIVERGENCE_MONITOR",false); } else if (params::containsKey("LAST_NAIL_REPLAY_FILE")) { RandomUtil::seedRandom(0); max_dead_paths = INT_MAX; use_hash = false; assert_safety = false; // print_errors = false; print_errors = true; max_steps_error = false; randomUtil = LastNailRandomUtil::SetInstance(); divergenceMonitor = params::get("RUN_DIVERGENCE_MONITOR",true); std::string statfilestr = "lastnail_" + params::get<std::string>("STAT_FILE", "stats.log"); params::set("ERROR_PATH_FILE_TAG", "-lastnail-"); FILE* statfile = fopen(statfilestr.c_str(), "w"); if (statfile == NULL) { Log::perror("Could not open stat file"); exit(1); } Log::add("Sim::printStats",statfile,LOG_TIMESTAMP_DISABLED,LOG_NAME_DISABLED,LOG_THREADID_DISABLED); Log::add("DEBUG::Sim::printStats",statfile,LOG_TIMESTAMP_DISABLED,LOG_NAME_DISABLED,LOG_THREADID_DISABLED); } else { if (params::get("VARIABLE_SRAND", false)) { RandomUtil::seedRandom(TimeUtil::timeu()); } else { RandomUtil::seedRandom(0); } print_errors = true; assert_safety = false; max_steps_error = true; if (params::get("USE_BEST_FIRST", true)) { randomUtil = BestFirstRandomUtil::SetInstance(); } else if (params::get("USE_STEP_SEARCH", false)) { randomUtil = SearchStepRandomUtil::SetInstance(); } else { randomUtil = SearchRandomUtil::SetInstance(); } if (params::get("TRACE_TRANSITION_TIMES", false)) { Log::logToFile("transition_times.log", "TransitionTimes", "w", LOG_TIMESTAMP_DISABLED); } divergenceMonitor = params::get("RUN_DIVERGENCE_MONITOR",true); FILE* statfile = fopen(params::get<std::string>("STAT_FILE", "stats.log").c_str(), "w"); if (statfile == NULL) { Log::perror("Could not open stat file"); exit(1); } Log::add("Sim::printStats",statfile,LOG_TIMESTAMP_DISABLED,LOG_NAME_DISABLED,LOG_THREADID_DISABLED); Log::add("DEBUG::Sim::printStats",statfile,LOG_TIMESTAMP_DISABLED,LOG_NAME_DISABLED,LOG_THREADID_DISABLED); } } } <commit_msg>Adding output path option for generated files ------------------------------------------------------------------------ r1154 | ckillian | 2011-06-23 16:40:22 -0400 (Thu, 23 Jun 2011) | 1 line<commit_after>/* * Simulator.cc : part of the Mace toolkit for building distributed systems * * Copyright (c) 2011, Charles Killian, James W. Anderson * 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 names of the contributors, nor their associated universities * or organizations 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. * * ----END-OF-LEGAL-STUFF---- */ #include "PrintNodeFormatter.h" #include "Simulator.h" #include "SearchRandomUtil.h" #include "SearchStepRandomUtil.h" //#include "BestFirstRandomUtil.h" typedef SearchRandomUtil BestFirstRandomUtil; #include "ReplayRandomUtil.h" #include "LastNailRandomUtil.h" namespace macemc { void __Simulator__::dumpState() { ADD_SELECTORS("__Simulator__::dumpState"); if (! maceout.isNoop()) { SimApplication& app = SimApplication::Instance(); maceout << "Application State: " << app << Log::endl; /* mace::PrintNode pr("root", ""); app.print(pr, "SimApplication"); std::ostringstream os; mace::PrintNodeFormatter::print(os, pr); maceout << "Begin Printer State" << std::endl << os.str() << Log::endl; maceout << "End Printer State" << Log::endl; */ // std::ostringstream longos; // mace::PrintNodeFormatter::printWithTypes(longos, pr); // maceout << longos.str() << std::endl; // maceout << "Application State: " << app << std::endl; maceout << "EventsPending State: " << SimEventWeighted::PrintableInstance() << Log::endl; SimNetwork& net = SimNetwork::Instance(); maceout << "Network State: " << net << Log::endl; // Sim& sched = SimScheduler::Instance(); // maceout << "Scheduler State: " << sched << Log::endl; } } void __Simulator__::initializeVars() { use_hash = params::get("USE_STATE_HASHES", false); use_broken_hash = params::get("USE_BROKEN_HASH", false); loggingStartStep = params::get<unsigned>("LOGGING_START_STEP", 0); max_dead_paths = params::get("MAX_DEAD_PATHS", 1); num_nodes = params::get<int>("num_nodes"); // Make sure our random number generator is the appropriate one if (params::containsKey("RANDOM_REPLAY_FILE")) { use_hash = false; assert_safety = true; if (params::get<std::string>("RANDOM_REPLAY_FILE") == "-") { print_errors = true; RandomUtil::seedRandom(TimeUtil::timeu()); } else { print_errors = false; RandomUtil::seedRandom(0); } max_steps_error = true; randomUtil = ReplayRandomUtil::SetInstance(); divergenceMonitor = params::get("RUN_DIVERGENCE_MONITOR",false); } else if (params::containsKey("LAST_NAIL_REPLAY_FILE")) { RandomUtil::seedRandom(0); max_dead_paths = INT_MAX; use_hash = false; assert_safety = false; // print_errors = false; print_errors = true; max_steps_error = false; randomUtil = LastNailRandomUtil::SetInstance(); divergenceMonitor = params::get("RUN_DIVERGENCE_MONITOR",true); std::string sfilename(params::get<std::string>("OUTPUT_PATH", "") + "lastnail_" + params::get<std::string>("STAT_FILE", "stats.log")); params::set("ERROR_PATH_FILE_TAG", "-lastnail-"); FILE* statfile = fopen(sfilename.c_str(), "w"); if (statfile == NULL) { Log::perror("Could not open stat file"); exit(1); } Log::add("Sim::printStats",statfile,LOG_TIMESTAMP_DISABLED,LOG_NAME_DISABLED,LOG_THREADID_DISABLED); Log::add("DEBUG::Sim::printStats",statfile,LOG_TIMESTAMP_DISABLED,LOG_NAME_DISABLED,LOG_THREADID_DISABLED); } else { if (params::get("VARIABLE_SRAND", false)) { RandomUtil::seedRandom(TimeUtil::timeu()); } else { RandomUtil::seedRandom(0); } print_errors = true; assert_safety = false; max_steps_error = true; if (params::get("USE_BEST_FIRST", true)) { randomUtil = BestFirstRandomUtil::SetInstance(); } else if (params::get("USE_STEP_SEARCH", false)) { randomUtil = SearchStepRandomUtil::SetInstance(); } else { randomUtil = SearchRandomUtil::SetInstance(); } if (params::get("TRACE_TRANSITION_TIMES", false)) { Log::logToFile("transition_times.log", "TransitionTimes", "w", LOG_TIMESTAMP_DISABLED); } divergenceMonitor = params::get("RUN_DIVERGENCE_MONITOR",true); std::string sfilename(params::get<std::string>("OUTPUT_PATH", "") + params::get<std::string>("STAT_FILE", "stats.log")); FILE* statfile = fopen(sfilename.c_str(), "w"); if (statfile == NULL) { Log::perror("Could not open stat file"); exit(1); } Log::add("Sim::printStats",statfile,LOG_TIMESTAMP_DISABLED,LOG_NAME_DISABLED,LOG_THREADID_DISABLED); Log::add("DEBUG::Sim::printStats",statfile,LOG_TIMESTAMP_DISABLED,LOG_NAME_DISABLED,LOG_THREADID_DISABLED); } } } <|endoftext|>
<commit_before>#include <Poco/Exception.h> #include <Poco/Logger.h> #include <Poco/String.h> #include "di/Injectable.h" #include "policy/SensorHistoryRules.h" #include "util/TimespanParser.h" BEEEON_OBJECT_BEGIN(BeeeOn, SensorHistoryRules) BEEEON_OBJECT_PROPERTY("rules", &SensorHistoryRules::parseAndSetRules) BEEEON_OBJECT_PROPERTY("acceptZeroInterval", &SensorHistoryRules::setAcceptZeroInterval) BEEEON_OBJECT_END(BeeeOn, SensorHistoryRules) using namespace std; using namespace Poco; using namespace BeeeOn; SensorHistoryRules::Span::Span( const Timespan &_min, const Timespan &_max): min(_min), max(_max) { if (min > max) throw InvalidArgumentException("min > max for " + toString()); } bool SensorHistoryRules::Span::operator <(const Span &other) const { return (min < other.min) && (max <= other.min); } string SensorHistoryRules::Span::toString() const { if (min == max) return SensorHistoryRules::asString(min); return SensorHistoryRules::asString(min) + ".." + SensorHistoryRules::asString(max); } string SensorHistoryRules::asString(const Timespan &time) { if (time == 0) return "0"; if (time.microseconds() > 0) return to_string(time.totalMicroseconds()) + " us"; if (time.milliseconds() > 0) return to_string(time.totalMilliseconds()) + " ms"; if (time.seconds() > 0) return to_string(time.totalSeconds()) + " s"; if (time.minutes() > 0) return to_string(time.totalMinutes()) + " m"; if (time.hours() > 0) return to_string(time.totalHours()) + " h"; return to_string(time.days()) + " d"; } SensorHistoryRules::SensorHistoryRules(): m_acceptZeroInterval(false) { } SensorHistoryRules::~SensorHistoryRules() { } void SensorHistoryRules::parseAndSetRules(const std::map<std::string, std::string> &rules) { map<Span, Span> spans; SharedPtr<Span> missing; for (const auto &pair : rules) { const string &key = trim(pair.first); const string &value = trim(pair.second); if (key == "*") { if (!missing.isNull()) throw ExistsException("duplicate '*' rule"); missing = new Span(parseSpan(value)); } else { const Span &span = parseSpan(key); const Span &interval = parseSpan(value); logger().information( "registering rule " + span.toString() + " -> " + interval.toString(), __FILE__, __LINE__); const auto result = spans.emplace(span, interval); if (!result.second) { const auto conflict = result.first->first; throw ExistsException( "span " + span.toString() + " is overlapping with " + conflict.toString()); } } } setRules(spans); setMissing(missing); } void SensorHistoryRules::setRules(const std::map<Span, Span> &rules) { m_rules = rules; } void SensorHistoryRules::setMissing(SharedPtr<Span> interval) { m_missing = interval; } void SensorHistoryRules::setAcceptZeroInterval(bool accept) { m_acceptZeroInterval = accept; } bool SensorHistoryRules::accept( const TimeInterval &range, const Timespan &interval) const { const Timespan &span = range.end() - range.start(); const Span &needle = {span, span}; if (interval == 0 && !m_acceptZeroInterval) { if (logger().debug()) { logger().debug( "zero interval not allowed for " + needle.toString(), __FILE__, __LINE__); } return false; } const auto it = m_rules.find(needle); if (it == m_rules.end() && m_missing.isNull()) { if (logger().debug()) { logger().debug( "no such rule for " + needle.toString(), __FILE__, __LINE__); } return false; } else if (it == m_rules.end()) { if (logger().debug()) { logger().debug( "applying the rule 'missing' for " + needle.toString(), __FILE__, __LINE__); } } const auto &rule = it == m_rules.end() ? *m_missing : it->second; const bool result = interval >= rule.min && interval <= rule.max; if (logger().debug()) { if (result) { logger().debug( "interval " + asString(interval) + " is not allowed for " + needle.toString(), __FILE__, __LINE__); } else { logger().debug( "interval " + asString(interval) + " allowed for " + needle.toString(), __FILE__, __LINE__); } } return result; } Timespan SensorHistoryRules::parseTime(const string &input, bool max) { static const Timespan TDIFF_MAX = Timestamp::TIMEVAL_MAX; const auto part = trim(input); if (max && part == "max") return TDIFF_MAX; const bool hasPlus = part.back() == '+'; const string &noPlus = hasPlus ? trim(string(part.begin(), part.end() - 1)) : part; const Timespan &time = TimespanParser::parse(noPlus); return hasPlus ? time + 1 : time; } SensorHistoryRules::Span SensorHistoryRules::parseSpan(const string &input) { const auto sep = input.find(".."); if (sep == string::npos) { if (input.find("+") != string::npos) throw SyntaxException("'+' is not allowed for " + input); const auto span = parseTime(input, true); return {span, span}; } const auto left = parseTime(input.substr(0, sep)); const auto right = parseTime({input.begin() + sep + 2, input.end()}, true); return {left, right}; } <commit_msg>SensorHistoryRules: improve debug logging<commit_after>#include <Poco/Exception.h> #include <Poco/Logger.h> #include <Poco/String.h> #include "di/Injectable.h" #include "policy/SensorHistoryRules.h" #include "util/TimespanParser.h" BEEEON_OBJECT_BEGIN(BeeeOn, SensorHistoryRules) BEEEON_OBJECT_PROPERTY("rules", &SensorHistoryRules::parseAndSetRules) BEEEON_OBJECT_PROPERTY("acceptZeroInterval", &SensorHistoryRules::setAcceptZeroInterval) BEEEON_OBJECT_END(BeeeOn, SensorHistoryRules) using namespace std; using namespace Poco; using namespace BeeeOn; SensorHistoryRules::Span::Span( const Timespan &_min, const Timespan &_max): min(_min), max(_max) { if (min > max) throw InvalidArgumentException("min > max for " + toString()); } bool SensorHistoryRules::Span::operator <(const Span &other) const { return (min < other.min) && (max <= other.min); } string SensorHistoryRules::Span::toString() const { if (min == max) return SensorHistoryRules::asString(min); return SensorHistoryRules::asString(min) + ".." + SensorHistoryRules::asString(max); } string SensorHistoryRules::asString(const Timespan &time) { if (time == 0) return "0"; if (time.microseconds() > 0) return to_string(time.totalMicroseconds()) + " us"; if (time.milliseconds() > 0) return to_string(time.totalMilliseconds()) + " ms"; if (time.seconds() > 0) return to_string(time.totalSeconds()) + " s"; if (time.minutes() > 0) return to_string(time.totalMinutes()) + " m"; if (time.hours() > 0) return to_string(time.totalHours()) + " h"; return to_string(time.days()) + " d"; } SensorHistoryRules::SensorHistoryRules(): m_acceptZeroInterval(false) { } SensorHistoryRules::~SensorHistoryRules() { } void SensorHistoryRules::parseAndSetRules(const std::map<std::string, std::string> &rules) { map<Span, Span> spans; SharedPtr<Span> missing; for (const auto &pair : rules) { const string &key = trim(pair.first); const string &value = trim(pair.second); if (key == "*") { if (!missing.isNull()) throw ExistsException("duplicate '*' rule"); missing = new Span(parseSpan(value)); } else { const Span &span = parseSpan(key); const Span &interval = parseSpan(value); logger().information( "registering rule " + span.toString() + " -> " + interval.toString(), __FILE__, __LINE__); const auto result = spans.emplace(span, interval); if (!result.second) { const auto conflict = result.first->first; throw ExistsException( "span " + span.toString() + " is overlapping with " + conflict.toString()); } } } setRules(spans); setMissing(missing); } void SensorHistoryRules::setRules(const std::map<Span, Span> &rules) { m_rules = rules; } void SensorHistoryRules::setMissing(SharedPtr<Span> interval) { m_missing = interval; } void SensorHistoryRules::setAcceptZeroInterval(bool accept) { m_acceptZeroInterval = accept; } bool SensorHistoryRules::accept( const TimeInterval &range, const Timespan &interval) const { const Timespan &span = range.end() - range.start(); const Span &needle = {span, span}; if (interval == 0 && !m_acceptZeroInterval) { if (logger().debug()) { logger().debug( "zero interval not allowed for " + needle.toString(), __FILE__, __LINE__); } return false; } const auto it = m_rules.find(needle); if (it == m_rules.end() && m_missing.isNull()) { if (logger().error()) { logger().error( "no such rule for " + needle.toString(), __FILE__, __LINE__); } return false; } else if (it == m_rules.end()) { if (logger().debug()) { logger().debug( "applying the rule 'missing' for " + needle.toString(), __FILE__, __LINE__); } } else { if (logger().debug()) { logger().debug( "range " + needle.toString() + " matched with rule " + it->first.toString(), __FILE__, __LINE__); } } const auto &rule = it == m_rules.end() ? *m_missing : it->second; const bool result = interval >= rule.min && interval <= rule.max; if (result) { if (logger().error()) { logger().error( "interval " + asString(interval) + " is not allowed for " + rule.toString(), __FILE__, __LINE__); } } else { if (logger().debug()) { logger().debug( "interval " + asString(interval) + " allowed for " + rule.toString(), __FILE__, __LINE__); } } return result; } Timespan SensorHistoryRules::parseTime(const string &input, bool max) { static const Timespan TDIFF_MAX = Timestamp::TIMEVAL_MAX; const auto part = trim(input); if (max && part == "max") return TDIFF_MAX; const bool hasPlus = part.back() == '+'; const string &noPlus = hasPlus ? trim(string(part.begin(), part.end() - 1)) : part; const Timespan &time = TimespanParser::parse(noPlus); return hasPlus ? time + 1 : time; } SensorHistoryRules::Span SensorHistoryRules::parseSpan(const string &input) { const auto sep = input.find(".."); if (sep == string::npos) { if (input.find("+") != string::npos) throw SyntaxException("'+' is not allowed for " + input); const auto span = parseTime(input, true); return {span, span}; } const auto left = parseTime(input.substr(0, sep)); const auto right = parseTime({input.begin() + sep + 2, input.end()}, true); return {left, right}; } <|endoftext|>
<commit_before>// Copyright (c) 2019 The PIVX developers // Distributed under the MIT software license, see the accompanying // file COPYING or http://www.opensource.org/licenses/mit-license.php. #include "qt/pivx/masternodeswidget.h" #include "qt/pivx/forms/ui_masternodeswidget.h" #include "qt/pivx/qtutils.h" #include "qt/pivx/mnrow.h" #include "qt/pivx/mninfodialog.h" #include "qt/pivx/masternodewizarddialog.h" #include "activemasternode.h" #include "clientmodel.h" #include "guiutil.h" #include "init.h" #include "masternode-sync.h" #include "masternodeconfig.h" #include "masternodeman.h" #include "sync.h" #include "wallet/wallet.h" #include "walletmodel.h" #include "askpassphrasedialog.h" #include "util.h" #include "qt/pivx/optionbutton.h" #include <boost/filesystem.hpp> #include <iostream> #include <fstream> #define DECORATION_SIZE 65 #define NUM_ITEMS 3 class MNHolder : public FurListRow<QWidget*> { public: MNHolder(); explicit MNHolder(bool _isLightTheme) : FurListRow(), isLightTheme(_isLightTheme){} MNRow* createHolder(int pos) override{ return new MNRow(); } void init(QWidget* holder,const QModelIndex &index, bool isHovered, bool isSelected) const override{ MNRow* row = static_cast<MNRow*>(holder); QString label = index.data(Qt::DisplayRole).toString(); QString address = index.sibling(index.row(), MNModel::ADDRESS).data(Qt::DisplayRole).toString(); QString status = index.sibling(index.row(), MNModel::STATUS).data(Qt::DisplayRole).toString(); bool wasCollateralAccepted = index.sibling(index.row(), MNModel::WAS_COLLATERAL_ACCEPTED).data(Qt::DisplayRole).toBool(); row->updateView("Address: " + address, label, status, wasCollateralAccepted); } QColor rectColor(bool isHovered, bool isSelected) override{ return getRowColor(isLightTheme, isHovered, isSelected); } ~MNHolder() override{} bool isLightTheme; }; #include "qt/pivx/moc_masternodeswidget.cpp" MasterNodesWidget::MasterNodesWidget(PIVXGUI *parent) : PWidget(parent), ui(new Ui::MasterNodesWidget) { ui->setupUi(this); delegate = new FurAbstractListItemDelegate( DECORATION_SIZE, new MNHolder(isLightTheme()), this ); mnModel = new MNModel(this); this->setStyleSheet(parent->styleSheet()); /* Containers */ setCssProperty(ui->left, "container"); ui->left->setContentsMargins(0,20,0,20); setCssProperty(ui->right, "container-right"); ui->right->setContentsMargins(20,20,20,20); /* Light Font */ QFont fontLight; fontLight.setWeight(QFont::Light); /* Title */ ui->labelTitle->setText(tr("Masternodes")); setCssTitleScreen(ui->labelTitle); ui->labelTitle->setFont(fontLight); ui->labelSubtitle1->setText(tr("Full nodes that incentivize node operators to perform the core consensus functions\nand vote on the treasury system receiving a periodic reward.")); setCssSubtitleScreen(ui->labelSubtitle1); /* Buttons */ ui->pushButtonSave->setText(tr("Create Masternode Controller")); setCssBtnPrimary(ui->pushButtonSave); /* Options */ ui->btnAbout->setTitleClassAndText("btn-title-grey", "What is a Masternode?"); ui->btnAbout->setSubTitleClassAndText("text-subtitle", "FAQ explaining what Masternodes are"); ui->btnAboutController->setTitleClassAndText("btn-title-grey", "What is a Controller?"); ui->btnAboutController->setSubTitleClassAndText("text-subtitle", "FAQ explaining what is a Masternode Controller"); setCssProperty(ui->listMn, "container"); ui->listMn->setItemDelegate(delegate); ui->listMn->setIconSize(QSize(DECORATION_SIZE, DECORATION_SIZE)); ui->listMn->setMinimumHeight(NUM_ITEMS * (DECORATION_SIZE + 2)); ui->listMn->setAttribute(Qt::WA_MacShowFocusRect, false); ui->listMn->setSelectionBehavior(QAbstractItemView::SelectRows); ui->emptyContainer->setVisible(false); setCssProperty(ui->pushImgEmpty, "img-empty-master"); ui->labelEmpty->setText(tr("No active Masternode yet")); setCssProperty(ui->labelEmpty, "text-empty"); connect(ui->pushButtonSave, SIGNAL(clicked()), this, SLOT(onCreateMNClicked())); connect(ui->listMn, SIGNAL(clicked(QModelIndex)), this, SLOT(onMNClicked(QModelIndex))); connect(ui->btnAbout, &OptionButton::clicked, [this](){window->openFAQ(9);}); connect(ui->btnAboutController, &OptionButton::clicked, [this](){window->openFAQ(10);}); } void MasterNodesWidget::showEvent(QShowEvent *event){ if (mnModel) mnModel->updateMNList(); if(!timer) { timer = new QTimer(this); connect(timer, &QTimer::timeout, [this]() {mnModel->updateMNList();}); } timer->start(30000); } void MasterNodesWidget::hideEvent(QHideEvent *event){ if(timer) timer->stop(); } void MasterNodesWidget::loadWalletModel(){ if(walletModel) { ui->listMn->setModel(mnModel); ui->listMn->setModelColumn(AddressTableModel::Label); updateListState(); } } void MasterNodesWidget::updateListState() { if (mnModel->rowCount() > 0) { ui->listMn->setVisible(true); ui->emptyContainer->setVisible(false); } else { ui->listMn->setVisible(false); ui->emptyContainer->setVisible(true); } } void MasterNodesWidget::onMNClicked(const QModelIndex &index){ ui->listMn->setCurrentIndex(index); QRect rect = ui->listMn->visualRect(index); QPoint pos = rect.topRight(); pos.setX(pos.x() - (DECORATION_SIZE * 2)); pos.setY(pos.y() + (DECORATION_SIZE * 1.5)); if(!this->menu){ this->menu = new TooltipMenu(window, this); this->menu->setEditBtnText(tr("Start")); this->menu->setDeleteBtnText(tr("Delete")); this->menu->setCopyBtnText(tr("Info")); connect(this->menu, &TooltipMenu::message, this, &AddressesWidget::message); connect(this->menu, SIGNAL(onEditClicked()), this, SLOT(onEditMNClicked())); connect(this->menu, SIGNAL(onDeleteClicked()), this, SLOT(onDeleteMNClicked())); connect(this->menu, SIGNAL(onCopyClicked()), this, SLOT(onInfoMNClicked())); this->menu->adjustSize(); }else { this->menu->hide(); } this->index = index; menu->move(pos); menu->show(); // Back to regular status ui->listMn->scrollTo(index); ui->listMn->clearSelection(); ui->listMn->setFocus(); } void MasterNodesWidget::onEditMNClicked(){ if(walletModel) { if (index.sibling(index.row(), MNModel::WAS_COLLATERAL_ACCEPTED).data(Qt::DisplayRole).toBool()) { // Start MN QString strAlias = this->index.data(Qt::DisplayRole).toString(); if (ask(tr("Start Master Node"), tr("Are you sure you want to start masternode %1?\n").arg(strAlias))) { if (!verifyWalletUnlocked()) return; startAlias(strAlias); } }else { inform(tr("Cannot start masternode, the collateral transaction has not been accepted by the network.\nPlease wait few more minutes.")); } } } void MasterNodesWidget::startAlias(QString strAlias){ QString strStatusHtml; strStatusHtml += "Alias: " + strAlias + " "; for (CMasternodeConfig::CMasternodeEntry mne : masternodeConfig.getEntries()) { if (mne.getAlias() == strAlias.toStdString()) { std::string strError; CMasternodeBroadcast mnb; if (CMasternodeBroadcast::Create(mne.getIp(), mne.getPrivKey(), mne.getTxHash(), mne.getOutputIndex(), strError, mnb)) { strStatusHtml += "successfully started."; mnodeman.UpdateMasternodeList(mnb); mnb.Relay(); mnModel->updateMNList(); } else { strStatusHtml += "failed to start.\nError: " + QString::fromStdString(strError); } break; } } inform(strStatusHtml); } void MasterNodesWidget::onInfoMNClicked(){ if(!verifyWalletUnlocked()) return; showHideOp(true); MnInfoDialog* dialog = new MnInfoDialog(window); QString label = index.data(Qt::DisplayRole).toString(); QString address = index.sibling(index.row(), MNModel::ADDRESS).data(Qt::DisplayRole).toString(); QString status = index.sibling(index.row(), MNModel::STATUS).data(Qt::DisplayRole).toString(); QString txId = index.sibling(index.row(), MNModel::COLLATERAL_ID).data(Qt::DisplayRole).toString(); QString outIndex = index.sibling(index.row(), MNModel::COLLATERAL_OUT_INDEX).data(Qt::DisplayRole).toString(); QString pubKey = index.sibling(index.row(), MNModel::PUB_KEY).data(Qt::DisplayRole).toString(); dialog->setData(pubKey, label, address, txId, outIndex, status); dialog->adjustSize(); showDialog(dialog, 3, 17); if (dialog->exportMN){ if (ask(tr("Remote Masternode Data"), tr("You are just about to export the required data to run a Masternode\non a remote server to your clipboard.\n\n\n" "You will only have to paste the data in the pivx.conf file\nof your remote server and start it, " "then start the Masternode using\nthis controller wallet (select the Masternode in the list and press \"start\").\n" ))) { // export data QString exportedMN = "masternode=1\n" "externalip=" + address.split(":")[0] + "\n" + "masternodeaddr=" + address + + "\n" + "masternodeprivkey=" + index.sibling(index.row(), MNModel::PRIV_KEY).data(Qt::DisplayRole).toString() + "\n"; GUIUtil::setClipboard(exportedMN); inform(tr("Masternode exported!, check your clipboard")); } } dialog->deleteLater(); } void MasterNodesWidget::onDeleteMNClicked(){ QString qAliasString = index.data(Qt::DisplayRole).toString(); std::string aliasToRemove = qAliasString.toStdString(); if (!ask(tr("Delete Master Node"), tr("You are just about to delete Master Node:\n%1\n\nAre you sure?").arg(qAliasString))) return; std::string strConfFile = "masternode.conf"; std::string strDataDir = GetDataDir().string(); if (strConfFile != boost::filesystem::basename(strConfFile) + boost::filesystem::extension(strConfFile)){ throw std::runtime_error(strprintf(_("masternode.conf %s resides outside data directory %s"), strConfFile, strDataDir)); } boost::filesystem::path pathBootstrap = GetDataDir() / strConfFile; if (boost::filesystem::exists(pathBootstrap)) { boost::filesystem::path pathMasternodeConfigFile = GetMasternodeConfigFile(); boost::filesystem::ifstream streamConfig(pathMasternodeConfigFile); if (!streamConfig.good()) { inform(tr("Invalid masternode.conf file")); return; } int lineNumToRemove = -1; int linenumber = 1; std::string lineCopy = ""; for (std::string line; std::getline(streamConfig, line); linenumber++) { if (line.empty()) continue; std::istringstream iss(line); std::string comment, alias, ip, privKey, txHash, outputIndex; if (iss >> comment) { if (comment.at(0) == '#') continue; iss.str(line); iss.clear(); } if (!(iss >> alias >> ip >> privKey >> txHash >> outputIndex)) { iss.str(line); iss.clear(); if (!(iss >> alias >> ip >> privKey >> txHash >> outputIndex)) { streamConfig.close(); inform(tr("Error parsing masternode.conf file")); return; } } if (aliasToRemove == alias) { lineNumToRemove = linenumber; } else lineCopy += line + "\n"; } if (lineCopy.size() == 0) { lineCopy = "# Masternode config file\n" "# Format: alias IP:port masternodeprivkey collateral_output_txid collateral_output_index\n" "# Example: mn1 127.0.0.2:51472 93HaYBVUCYjEMeeH1Y4sBGLALQZE1Yc1K64xiqgX37tGBDQL8Xg 2bcd3c84c84f87eaa86e4e56834c92927a07f9e18718810b92e0d0324456a67c 0\n"; } streamConfig.close(); if (lineNumToRemove != -1) { boost::filesystem::path pathConfigFile("masternode_temp.conf"); if (!pathConfigFile.is_complete()) pathConfigFile = GetDataDir() / pathConfigFile; FILE* configFile = fopen(pathConfigFile.string().c_str(), "w"); fwrite(lineCopy.c_str(), std::strlen(lineCopy.c_str()), 1, configFile); fclose(configFile); boost::filesystem::path pathOldConfFile("old_masternode.conf"); if (!pathOldConfFile.is_complete()) pathOldConfFile = GetDataDir() / pathOldConfFile; if (boost::filesystem::exists(pathOldConfFile)) { boost::filesystem::remove(pathOldConfFile); } rename(pathMasternodeConfigFile, pathOldConfFile); boost::filesystem::path pathNewConfFile("masternode.conf"); if (!pathNewConfFile.is_complete()) pathNewConfFile = GetDataDir() / pathNewConfFile; rename(pathConfigFile, pathNewConfFile); // Remove alias masternodeConfig.remove(aliasToRemove); // Update list mnModel->removeMn(index); updateListState(); } } else{ inform(tr("masternode.conf file doesn't exists")); } } void MasterNodesWidget::onCreateMNClicked(){ if(verifyWalletUnlocked()) { if(walletModel->getBalance() <= (COIN * 10000)){ inform(tr("No enough balance to create a master node, 10,000 PIV required.")); return; } showHideOp(true); MasterNodeWizardDialog *dialog = new MasterNodeWizardDialog(walletModel, window); if(openDialogWithOpaqueBackgroundY(dialog, window, 5, 7)) { if (dialog->isOk) { // Update list mnModel->addMn(dialog->mnEntry); updateListState(); // add mn inform(dialog->returnStr); } else { warn(tr("Error creating master node"), dialog->returnStr); } } dialog->deleteLater(); } } void MasterNodesWidget::changeTheme(bool isLightTheme, QString& theme){ static_cast<MNHolder*>(this->delegate->getRowFactory())->isLightTheme = isLightTheme; } MasterNodesWidget::~MasterNodesWidget() { delete ui; } <commit_msg>[Trivial][UI] MN screen, inform and warn texts changed --> "Master node" for "Masternode".<commit_after>// Copyright (c) 2019 The PIVX developers // Distributed under the MIT software license, see the accompanying // file COPYING or http://www.opensource.org/licenses/mit-license.php. #include "qt/pivx/masternodeswidget.h" #include "qt/pivx/forms/ui_masternodeswidget.h" #include "qt/pivx/qtutils.h" #include "qt/pivx/mnrow.h" #include "qt/pivx/mninfodialog.h" #include "qt/pivx/masternodewizarddialog.h" #include "activemasternode.h" #include "clientmodel.h" #include "guiutil.h" #include "init.h" #include "masternode-sync.h" #include "masternodeconfig.h" #include "masternodeman.h" #include "sync.h" #include "wallet/wallet.h" #include "walletmodel.h" #include "askpassphrasedialog.h" #include "util.h" #include "qt/pivx/optionbutton.h" #include <boost/filesystem.hpp> #include <iostream> #include <fstream> #define DECORATION_SIZE 65 #define NUM_ITEMS 3 class MNHolder : public FurListRow<QWidget*> { public: MNHolder(); explicit MNHolder(bool _isLightTheme) : FurListRow(), isLightTheme(_isLightTheme){} MNRow* createHolder(int pos) override{ return new MNRow(); } void init(QWidget* holder,const QModelIndex &index, bool isHovered, bool isSelected) const override{ MNRow* row = static_cast<MNRow*>(holder); QString label = index.data(Qt::DisplayRole).toString(); QString address = index.sibling(index.row(), MNModel::ADDRESS).data(Qt::DisplayRole).toString(); QString status = index.sibling(index.row(), MNModel::STATUS).data(Qt::DisplayRole).toString(); bool wasCollateralAccepted = index.sibling(index.row(), MNModel::WAS_COLLATERAL_ACCEPTED).data(Qt::DisplayRole).toBool(); row->updateView("Address: " + address, label, status, wasCollateralAccepted); } QColor rectColor(bool isHovered, bool isSelected) override{ return getRowColor(isLightTheme, isHovered, isSelected); } ~MNHolder() override{} bool isLightTheme; }; #include "qt/pivx/moc_masternodeswidget.cpp" MasterNodesWidget::MasterNodesWidget(PIVXGUI *parent) : PWidget(parent), ui(new Ui::MasterNodesWidget) { ui->setupUi(this); delegate = new FurAbstractListItemDelegate( DECORATION_SIZE, new MNHolder(isLightTheme()), this ); mnModel = new MNModel(this); this->setStyleSheet(parent->styleSheet()); /* Containers */ setCssProperty(ui->left, "container"); ui->left->setContentsMargins(0,20,0,20); setCssProperty(ui->right, "container-right"); ui->right->setContentsMargins(20,20,20,20); /* Light Font */ QFont fontLight; fontLight.setWeight(QFont::Light); /* Title */ ui->labelTitle->setText(tr("Masternodes")); setCssTitleScreen(ui->labelTitle); ui->labelTitle->setFont(fontLight); ui->labelSubtitle1->setText(tr("Full nodes that incentivize node operators to perform the core consensus functions\nand vote on the treasury system receiving a periodic reward.")); setCssSubtitleScreen(ui->labelSubtitle1); /* Buttons */ ui->pushButtonSave->setText(tr("Create Masternode Controller")); setCssBtnPrimary(ui->pushButtonSave); /* Options */ ui->btnAbout->setTitleClassAndText("btn-title-grey", "What is a Masternode?"); ui->btnAbout->setSubTitleClassAndText("text-subtitle", "FAQ explaining what Masternodes are"); ui->btnAboutController->setTitleClassAndText("btn-title-grey", "What is a Controller?"); ui->btnAboutController->setSubTitleClassAndText("text-subtitle", "FAQ explaining what is a Masternode Controller"); setCssProperty(ui->listMn, "container"); ui->listMn->setItemDelegate(delegate); ui->listMn->setIconSize(QSize(DECORATION_SIZE, DECORATION_SIZE)); ui->listMn->setMinimumHeight(NUM_ITEMS * (DECORATION_SIZE + 2)); ui->listMn->setAttribute(Qt::WA_MacShowFocusRect, false); ui->listMn->setSelectionBehavior(QAbstractItemView::SelectRows); ui->emptyContainer->setVisible(false); setCssProperty(ui->pushImgEmpty, "img-empty-master"); ui->labelEmpty->setText(tr("No active Masternode yet")); setCssProperty(ui->labelEmpty, "text-empty"); connect(ui->pushButtonSave, SIGNAL(clicked()), this, SLOT(onCreateMNClicked())); connect(ui->listMn, SIGNAL(clicked(QModelIndex)), this, SLOT(onMNClicked(QModelIndex))); connect(ui->btnAbout, &OptionButton::clicked, [this](){window->openFAQ(9);}); connect(ui->btnAboutController, &OptionButton::clicked, [this](){window->openFAQ(10);}); } void MasterNodesWidget::showEvent(QShowEvent *event){ if (mnModel) mnModel->updateMNList(); if(!timer) { timer = new QTimer(this); connect(timer, &QTimer::timeout, [this]() {mnModel->updateMNList();}); } timer->start(30000); } void MasterNodesWidget::hideEvent(QHideEvent *event){ if(timer) timer->stop(); } void MasterNodesWidget::loadWalletModel(){ if(walletModel) { ui->listMn->setModel(mnModel); ui->listMn->setModelColumn(AddressTableModel::Label); updateListState(); } } void MasterNodesWidget::updateListState() { if (mnModel->rowCount() > 0) { ui->listMn->setVisible(true); ui->emptyContainer->setVisible(false); } else { ui->listMn->setVisible(false); ui->emptyContainer->setVisible(true); } } void MasterNodesWidget::onMNClicked(const QModelIndex &index){ ui->listMn->setCurrentIndex(index); QRect rect = ui->listMn->visualRect(index); QPoint pos = rect.topRight(); pos.setX(pos.x() - (DECORATION_SIZE * 2)); pos.setY(pos.y() + (DECORATION_SIZE * 1.5)); if(!this->menu){ this->menu = new TooltipMenu(window, this); this->menu->setEditBtnText(tr("Start")); this->menu->setDeleteBtnText(tr("Delete")); this->menu->setCopyBtnText(tr("Info")); connect(this->menu, &TooltipMenu::message, this, &AddressesWidget::message); connect(this->menu, SIGNAL(onEditClicked()), this, SLOT(onEditMNClicked())); connect(this->menu, SIGNAL(onDeleteClicked()), this, SLOT(onDeleteMNClicked())); connect(this->menu, SIGNAL(onCopyClicked()), this, SLOT(onInfoMNClicked())); this->menu->adjustSize(); }else { this->menu->hide(); } this->index = index; menu->move(pos); menu->show(); // Back to regular status ui->listMn->scrollTo(index); ui->listMn->clearSelection(); ui->listMn->setFocus(); } void MasterNodesWidget::onEditMNClicked(){ if(walletModel) { if (index.sibling(index.row(), MNModel::WAS_COLLATERAL_ACCEPTED).data(Qt::DisplayRole).toBool()) { // Start MN QString strAlias = this->index.data(Qt::DisplayRole).toString(); if (ask(tr("Start Masternode"), tr("Are you sure you want to start masternode %1?\n").arg(strAlias))) { if (!verifyWalletUnlocked()) return; startAlias(strAlias); } }else { inform(tr("Cannot start masternode, the collateral transaction has not been accepted by the network.\nPlease wait few more minutes.")); } } } void MasterNodesWidget::startAlias(QString strAlias){ QString strStatusHtml; strStatusHtml += "Alias: " + strAlias + " "; for (CMasternodeConfig::CMasternodeEntry mne : masternodeConfig.getEntries()) { if (mne.getAlias() == strAlias.toStdString()) { std::string strError; CMasternodeBroadcast mnb; if (CMasternodeBroadcast::Create(mne.getIp(), mne.getPrivKey(), mne.getTxHash(), mne.getOutputIndex(), strError, mnb)) { strStatusHtml += "successfully started."; mnodeman.UpdateMasternodeList(mnb); mnb.Relay(); mnModel->updateMNList(); } else { strStatusHtml += "failed to start.\nError: " + QString::fromStdString(strError); } break; } } inform(strStatusHtml); } void MasterNodesWidget::onInfoMNClicked(){ if(!verifyWalletUnlocked()) return; showHideOp(true); MnInfoDialog* dialog = new MnInfoDialog(window); QString label = index.data(Qt::DisplayRole).toString(); QString address = index.sibling(index.row(), MNModel::ADDRESS).data(Qt::DisplayRole).toString(); QString status = index.sibling(index.row(), MNModel::STATUS).data(Qt::DisplayRole).toString(); QString txId = index.sibling(index.row(), MNModel::COLLATERAL_ID).data(Qt::DisplayRole).toString(); QString outIndex = index.sibling(index.row(), MNModel::COLLATERAL_OUT_INDEX).data(Qt::DisplayRole).toString(); QString pubKey = index.sibling(index.row(), MNModel::PUB_KEY).data(Qt::DisplayRole).toString(); dialog->setData(pubKey, label, address, txId, outIndex, status); dialog->adjustSize(); showDialog(dialog, 3, 17); if (dialog->exportMN){ if (ask(tr("Remote Masternode Data"), tr("You are just about to export the required data to run a Masternode\non a remote server to your clipboard.\n\n\n" "You will only have to paste the data in the pivx.conf file\nof your remote server and start it, " "then start the Masternode using\nthis controller wallet (select the Masternode in the list and press \"start\").\n" ))) { // export data QString exportedMN = "masternode=1\n" "externalip=" + address.split(":")[0] + "\n" + "masternodeaddr=" + address + + "\n" + "masternodeprivkey=" + index.sibling(index.row(), MNModel::PRIV_KEY).data(Qt::DisplayRole).toString() + "\n"; GUIUtil::setClipboard(exportedMN); inform(tr("Masternode exported!, check your clipboard")); } } dialog->deleteLater(); } void MasterNodesWidget::onDeleteMNClicked(){ QString qAliasString = index.data(Qt::DisplayRole).toString(); std::string aliasToRemove = qAliasString.toStdString(); if (!ask(tr("Delete Masternode"), tr("You are just about to delete Masternode:\n%1\n\nAre you sure?").arg(qAliasString))) return; std::string strConfFile = "masternode.conf"; std::string strDataDir = GetDataDir().string(); if (strConfFile != boost::filesystem::basename(strConfFile) + boost::filesystem::extension(strConfFile)){ throw std::runtime_error(strprintf(_("masternode.conf %s resides outside data directory %s"), strConfFile, strDataDir)); } boost::filesystem::path pathBootstrap = GetDataDir() / strConfFile; if (boost::filesystem::exists(pathBootstrap)) { boost::filesystem::path pathMasternodeConfigFile = GetMasternodeConfigFile(); boost::filesystem::ifstream streamConfig(pathMasternodeConfigFile); if (!streamConfig.good()) { inform(tr("Invalid masternode.conf file")); return; } int lineNumToRemove = -1; int linenumber = 1; std::string lineCopy = ""; for (std::string line; std::getline(streamConfig, line); linenumber++) { if (line.empty()) continue; std::istringstream iss(line); std::string comment, alias, ip, privKey, txHash, outputIndex; if (iss >> comment) { if (comment.at(0) == '#') continue; iss.str(line); iss.clear(); } if (!(iss >> alias >> ip >> privKey >> txHash >> outputIndex)) { iss.str(line); iss.clear(); if (!(iss >> alias >> ip >> privKey >> txHash >> outputIndex)) { streamConfig.close(); inform(tr("Error parsing masternode.conf file")); return; } } if (aliasToRemove == alias) { lineNumToRemove = linenumber; } else lineCopy += line + "\n"; } if (lineCopy.size() == 0) { lineCopy = "# Masternode config file\n" "# Format: alias IP:port masternodeprivkey collateral_output_txid collateral_output_index\n" "# Example: mn1 127.0.0.2:51472 93HaYBVUCYjEMeeH1Y4sBGLALQZE1Yc1K64xiqgX37tGBDQL8Xg 2bcd3c84c84f87eaa86e4e56834c92927a07f9e18718810b92e0d0324456a67c 0\n"; } streamConfig.close(); if (lineNumToRemove != -1) { boost::filesystem::path pathConfigFile("masternode_temp.conf"); if (!pathConfigFile.is_complete()) pathConfigFile = GetDataDir() / pathConfigFile; FILE* configFile = fopen(pathConfigFile.string().c_str(), "w"); fwrite(lineCopy.c_str(), std::strlen(lineCopy.c_str()), 1, configFile); fclose(configFile); boost::filesystem::path pathOldConfFile("old_masternode.conf"); if (!pathOldConfFile.is_complete()) pathOldConfFile = GetDataDir() / pathOldConfFile; if (boost::filesystem::exists(pathOldConfFile)) { boost::filesystem::remove(pathOldConfFile); } rename(pathMasternodeConfigFile, pathOldConfFile); boost::filesystem::path pathNewConfFile("masternode.conf"); if (!pathNewConfFile.is_complete()) pathNewConfFile = GetDataDir() / pathNewConfFile; rename(pathConfigFile, pathNewConfFile); // Remove alias masternodeConfig.remove(aliasToRemove); // Update list mnModel->removeMn(index); updateListState(); } } else{ inform(tr("masternode.conf file doesn't exists")); } } void MasterNodesWidget::onCreateMNClicked(){ if(verifyWalletUnlocked()) { if(walletModel->getBalance() <= (COIN * 10000)){ inform(tr("Not enough balance to create a masternode, 10,000 PIV required.")); return; } showHideOp(true); MasterNodeWizardDialog *dialog = new MasterNodeWizardDialog(walletModel, window); if(openDialogWithOpaqueBackgroundY(dialog, window, 5, 7)) { if (dialog->isOk) { // Update list mnModel->addMn(dialog->mnEntry); updateListState(); // add mn inform(dialog->returnStr); } else { warn(tr("Error creating masternode"), dialog->returnStr); } } dialog->deleteLater(); } } void MasterNodesWidget::changeTheme(bool isLightTheme, QString& theme){ static_cast<MNHolder*>(this->delegate->getRowFactory())->isLightTheme = isLightTheme; } MasterNodesWidget::~MasterNodesWidget() { delete ui; } <|endoftext|>
<commit_before><commit_msg>[idyntree-model-info] added print of relative frame transformations<commit_after><|endoftext|>
<commit_before><commit_msg>Adding avatar_url to select statement<commit_after><|endoftext|>
<commit_before>#include <boost/thread/thread.hpp> #include <iostream> using std::cout; using std::endl; #include <string> using std::string; #include <fstream> using std::ifstream; #include <sstream> using std::stringstream; #include <vector> using std::vector; #include "liblager_connect.h" #include "liblager_convert.h" #include "liblager_recognize.h" /* Globals */ /// Global vector of SubscribedGestures vector<SubscribedGesture> g_subscribed_gestures; /***************************************************************************** * Callback handler * *****************************************************************************/ /** * Reads the program arguments and returns whether sensor buttons are going to * be used to start/stop gesture detection, or whether buttons will be ignored * and detection will be active at all times. */ bool DetermineButtonUse(const int argc, const char** argv) { bool use_buttons; if ((argc > 1) && (std::string(argv[1]).find("--no_buttons") != std::string::npos)) { cout << "Gesture detection will be active at all times." << endl; use_buttons = false; } else { cout << "Gesture detection will be active while pressing a button." << endl; use_buttons = true; } return use_buttons; } /** * Reads the program arguments and returns whether the gesture input is going * to be compared to subscribed gestures or to a fixed list of gestures in a * file. */ 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; } /** * Reads the program arguments and returns whether or not the input and * subscribed gestures will be drawn on screen via lager_viewer. */ 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; } /** * Reads a file named gestures.dat and parses it to save its gestures into the * global vector of SubscribedGestures. */ int GetSubscribedGesturesFromFile() { ifstream gestures_file; string current_line; 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); SubscribedGesture new_gesture; ss >> new_gesture.name >> new_gesture.lager; new_gesture.pid = 0; g_subscribed_gestures.push_back(new_gesture); cout << "Added Name: " << new_gesture.name << " Lager: " << new_gesture.lager << endl; } return RECOGNIZER_NO_ERROR; } /** * Takes a reference to a SubscribedGesture and an input gesture LaGeR string, * and draws them on screen via lager_viewer. */ void DrawMatchingGestures(const SubscribedGesture& closest_gesture, string gesture_string) { 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 << 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()); } /** * The main loop of the LaGeR Recognizer. */ int main(int argc, const char *argv[]) { bool use_buttons = DetermineButtonUse(argc, argv); bool use_gestures_file = DetermineGesturesFileUse(argc, argv); bool draw_gestures = DetermineGestureDrawing(argc, argv); bool match_found = false; LagerConverter* lager_converter = LagerConverter::Instance(); LagerRecognizer* lager_recognizer = LagerRecognizer::Instance(&g_subscribed_gestures); if (use_gestures_file) { GetSubscribedGesturesFromFile(); } else { CreateGestureSubscriptionQueue(); boost::thread subscription_updater(AddSubscribedGestures, &g_subscribed_gestures); } cout << " ________________________________ " << endl; cout << "| |" << endl; cout << "| COLLECTING DATA... |" << endl; cout << "|________________________________|" << endl; cout << " " << endl; lager_converter->SetUseButtons(use_buttons); lager_converter->Start(); while(true) { string gesture_string = lager_converter->BlockingGetLagerString(); if (g_subscribed_gestures.size() > 0) { SubscribedGesture recognized_gesture = lager_recognizer->RecognizeGesture( draw_gestures, gesture_string, match_found); if (draw_gestures) { DrawMatchingGestures(recognized_gesture, gesture_string); } if (match_found && (!use_gestures_file && recognized_gesture.pid != 0)) { SendDetectedGestureMessage(recognized_gesture.name, recognized_gesture.pid); } } } } /* main */ <commit_msg>Lager Recognizer: Find program arguments in any position<commit_after>#include <boost/thread/thread.hpp> #include <iostream> using std::cout; using std::endl; #include <string> using std::string; #include <fstream> using std::ifstream; #include <sstream> using std::stringstream; #include <vector> using std::vector; #include "liblager_connect.h" #include "liblager_convert.h" #include "liblager_recognize.h" /* Globals */ /// Global vector of SubscribedGestures vector<SubscribedGesture> g_subscribed_gestures; /***************************************************************************** * Callback handler * *****************************************************************************/ /** * Reads the program arguments and returns whether a given string is present */ bool DetermineArgumentPresent(const int argc, const char** argv, const char* string_to_find) { bool string_found = false; if (argc > 1) { int i = 1; for (; i < argc; i++) { string_found = std::string(argv[i]).find(string_to_find) != std::string::npos; if (string_found) { break; } } } return string_found; } /** * Reads the program arguments and returns whether sensor buttons are going to * be used to start/stop gesture detection, or whether buttons will be ignored * and detection will be active at all times. */ bool DetermineButtonUse(const int argc, const char** argv) { bool use_buttons; if (DetermineArgumentPresent(argc, argv, "--no_buttons")) { cout << "Gesture detection will be active at all times." << endl; use_buttons = false; } else { cout << "Gesture detection will be active while pressing a button." << endl; use_buttons = true; } return use_buttons; } /** * Reads the program arguments and returns whether the gesture input is going * to be compared to subscribed gestures or to a fixed list of gestures in a * file. */ bool DetermineGesturesFileUse(const int argc, const char** argv) { bool use_gestures_file; if (DetermineArgumentPresent(argc, argv, "--use_gestures_file")) { 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; } /** * Reads the program arguments and returns whether or not the input and * subscribed gestures will be drawn on screen via lager_viewer. */ bool DetermineGestureDrawing(const int argc, const char** argv) { bool draw_gestures; if (DetermineArgumentPresent(argc, argv, "--draw_gestures")) { 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; } /** * Reads a file named gestures.dat and parses it to save its gestures into the * global vector of SubscribedGestures. */ int GetSubscribedGesturesFromFile() { ifstream gestures_file; string current_line; 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); SubscribedGesture new_gesture; ss >> new_gesture.name >> new_gesture.lager; new_gesture.pid = 0; g_subscribed_gestures.push_back(new_gesture); cout << "Added Name: " << new_gesture.name << " Lager: " << new_gesture.lager << endl; } return RECOGNIZER_NO_ERROR; } /** * Takes a reference to a SubscribedGesture and an input gesture LaGeR string, * and draws them on screen via lager_viewer. */ void DrawMatchingGestures(const SubscribedGesture& closest_gesture, string gesture_string) { 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 << 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()); } /** * The main loop of the LaGeR Recognizer. */ int main(int argc, const char *argv[]) { bool use_buttons = DetermineButtonUse(argc, argv); bool use_gestures_file = DetermineGesturesFileUse(argc, argv); bool draw_gestures = DetermineGestureDrawing(argc, argv); bool match_found = false; LagerConverter* lager_converter = LagerConverter::Instance(); LagerRecognizer* lager_recognizer = LagerRecognizer::Instance(&g_subscribed_gestures); if (use_gestures_file) { GetSubscribedGesturesFromFile(); } else { CreateGestureSubscriptionQueue(); boost::thread subscription_updater(AddSubscribedGestures, &g_subscribed_gestures); } cout << " ________________________________ " << endl; cout << "| |" << endl; cout << "| COLLECTING DATA... |" << endl; cout << "|________________________________|" << endl; cout << " " << endl; lager_converter->SetUseButtons(use_buttons); lager_converter->Start(); while(true) { string gesture_string = lager_converter->BlockingGetLagerString(); if (g_subscribed_gestures.size() > 0) { SubscribedGesture recognized_gesture = lager_recognizer->RecognizeGesture( draw_gestures, gesture_string, match_found); if (draw_gestures) { DrawMatchingGestures(recognized_gesture, gesture_string); } if (match_found && (!use_gestures_file && recognized_gesture.pid != 0)) { SendDetectedGestureMessage(recognized_gesture.name, recognized_gesture.pid); } } } } /* main */ <|endoftext|>
<commit_before><commit_msg>corrected title height calculation in case of a zoom<commit_after><|endoftext|>
<commit_before>// Listen to map_store_POINTS files: // - store them in a local object // - maintain a list and broadcast the list // - support queries, which sent a specific cloud back // - listen for // LCM example program for interacting with PCL data // In this case it pushes the data back out to LCM in // a different message type for which the "collections" // renderer can view it in the LCM viewer // mfallon aug 2012 #include <stdio.h> #include <inttypes.h> #include <lcm/lcm.h> #include <iostream> #include <pcl/io/pcd_io.h> #include <pcl/point_types.h> #include <lcmtypes/visualization.h> #include <path_util/path_util.h> #include "map_store.hpp" #include <boost/shared_ptr.hpp> using namespace std; using namespace pcl; typedef boost::shared_ptr<otdf::ModelInterface> otdfPtr; ///////////////////////////////////// map_store::map_store(lcm_t* publish_lcm): publish_lcm_(publish_lcm) { pc_vis_ = new pointcloud_vis(publish_lcm_); // obj: id name type reset // pts: id name type reset objcoll usergb rgb pc_vis_->obj_cfg_list.push_back( obj_cfg(1000,"Pose - Dump",5,0) ); float colors_b[] ={0.0,0.0,1.0}; vector <float> colors_v; colors_v.assign(colors_b,colors_b+4*sizeof(float)); pc_vis_->ptcld_cfg_list.push_back( ptcld_cfg(1001,"Cloud - Dump" ,1,0, 1000,1,colors_v)); // pc_vis_->obj_cfg_list.push_back( obj_cfg(1100,"Pose - Current",5,0) ); float colors_r[] ={1.0,0.0,0.0}; colors_v.assign(colors_r,colors_r+4*sizeof(float)); pc_vis_->ptcld_cfg_list.push_back( ptcld_cfg(1101,"Cloud - Current" ,1,0, 1100,1,colors_v)); // LCM: lcm_t* subscribe_lcm_ = publish_lcm_; drc_pointcloud2_t_subscribe(subscribe_lcm_, "LOCAL_MAP_POINTS", pointcloud_handler_aux, this); drc_localize_reinitialize_cmd_t_subscribe(subscribe_lcm_, "SEG_REQUEST", seg_request_handler_aux, this); drc_localize_reinitialize_cmd_t_subscribe(subscribe_lcm_, "SEG_UPDATE", seg_update_handler_aux, this); drc_localize_reinitialize_cmd_t_subscribe(subscribe_lcm_, "DUMP_MAPS", dump_maps_handler_aux, this); drc_localize_reinitialize_cmd_t_subscribe(subscribe_lcm_, "CURRENT_MAP_ID", current_map_handler_aux, this); } void map_store::initialize(){ } void map_store::publish_affordance_collection(LocalMap m){ cout <<m.map_id << " | " << m.utime << "| " << m.cloud->size() << " cloud size\n"; // Send a pose drc_affordance_collection_t affs_coll; affs_coll.map_id = m.map_id; affs_coll.name = (char*) "homers_desk"; affs_coll.map_utime = m.utime; affs_coll.naffs = m.objects.size(); drc_affordance_t affs[affs_coll.naffs]; cout << m.objects.size() << " Objects\n"; for (size_t i=0;i <m.objects.size(); i++){ affs[i].map_utime = m.utime; affs[i].map_id = m.map_id; affs[i].name = (char*) m.object_names[i].c_str(); affs[i].otdf_id = m.object_ids[i]; otdfPtr object= m.objects[i]; std::map<std::string, double> param_map = object->params_map_; // all parameters defined in the object template std::map<std::string, double>::iterator it; cout << "params.size() is " << (int) param_map.size() << endl; affs[i].nparams=param_map.size(); double* params = new double[affs[i].nparams]; char** param_names = new char*[affs[i].nparams]; int j; for (it=param_map.begin(),j=0 ; it != param_map.end(); it++ , j++){ cout << (*it).first << " => " << (*it).second << " | "; param_names[j] = (char*) (*it).first.c_str(); params[j] = (*it).second; } affs[i].params = params; affs[i].param_names = param_names; affs[i].nstates=0; affs[i].states=NULL; affs[i].state_names=NULL; affs[i].nptids=0; affs[i].ptids=NULL; cout << endl; } affs_coll.affs = affs; drc_affordance_collection_t_publish(publish_lcm_, "AFFORDANCE_COLLECTION", &affs_coll); cout << "affs gone\n"; } void map_store::publish_local_map(unsigned int map_id){ cout << "publish_local_map called\n"; LocalMap m = maps[map_id]; publish_affordance_collection(m); cout <<m.map_id << " | " << m.utime << "| " << m.cloud->size() << " cloud size\n"; Eigen::Isometry3d offset_pose = m.base_pose; offset_pose.translation() << m.base_pose.translation().x(), m.base_pose.translation().y(), m.base_pose.translation().z(); Isometry3dTime offset_poseT = Isometry3dTime(m.utime, offset_pose); pc_vis_->pose_to_lcm_from_list(1100, offset_poseT); pc_vis_->ptcld_to_lcm_from_list(1101, *(m.cloud), offset_poseT.utime, offset_poseT.utime); cout << m.objects.size() << " Objects\n"; for (size_t i=0;i <m.objects.size(); i++){ otdfPtr object= m.objects[i]; std::map<std::string, double> params = object->params_map_; // all parameters defined in the object template std::map<std::string, double>::iterator it; cout << "params.size() is " << (int) params.size() << endl; for (it=params.begin() ; it != params.end(); it++ ){ cout << (*it).first << " => " << (*it).second << " | "; } cout << endl; } } void map_store::dump_maps(DumpCode code, double x_offset){ if (code == DUMP_SCREEN){ cout << "dump screen set\n"; } cout << "dump maps blah\n"; for (size_t i=0;i<maps.size() ; i++){ LocalMap m = maps[i]; cout <<m.map_id << " | " << m.utime << "| " << m.cloud->size() << " cloud size\n"; Eigen::Isometry3d offset_pose = m.base_pose; offset_pose.translation() << m.base_pose.translation().x() + x_offset*i, m.base_pose.translation().y()+ x_offset, m.base_pose.translation().z(); Isometry3dTime offset_poseT = Isometry3dTime(m.utime, offset_pose); pc_vis_->pose_to_lcm_from_list(1000, offset_poseT); pc_vis_->ptcld_to_lcm_from_list(1001, *(m.cloud), offset_poseT.utime, offset_poseT.utime); cout << m.objects.size() << " Objects\n"; for (size_t i=0;i <m.objects.size(); i++){ otdfPtr object= m.objects[i]; std::map<std::string, double> params = object->params_map_; // all parameters defined in the object template std::map<std::string, double>::iterator it; cout << "params.size() is " << (int) params.size() << endl; for (it=params.begin() ; it != params.end(); it++ ){ cout << (*it).first << " => " << (*it).second << " | "; } cout << endl; } } } void map_store::dump_maps_handler(const drc_localize_reinitialize_cmd_t *msg){ cout << "dump maps requested\n"; dump_maps(DUMP_SCREEN,40.0); // Sent a specific map to main gui publish_local_map(0); } void map_store::current_map_handler(const drc_localize_reinitialize_cmd_t *msg){ cout << "map\n"; // contains which map to visualise // ... transmit the specified map to the segmentation gui (continously @ 1Hz in a different thread) } void map_store::seg_request_handler(const drc_localize_reinitialize_cmd_t *msg){ cout << "segmentation map requested\n"; // ... transmit the map to the segmentation gui } void map_store::seg_update_handler(const drc_localize_reinitialize_cmd_t *msg){ cout << "received segmentation\n"; // ... log the segmentation } void create_otdf_object_instance (otdfPtr &object, string otdf_name)//(RendererOtdf *self) { // std::string filename = self->otdf_filenames[self->otdf_id]+".otdf"; // std::transform(filename.begin(), filename.end(), filename.begin(), ::tolower); string otdf_models_path = std::string(getModelsPath()) + "/otdf/"; // getModelsPath gives /drc/software/build/ std::string filepath = otdf_models_path+ otdf_name +".otdf";//(*self->otdf_dir_name_ptr)+filename; std::cout << "instantiating " << filepath << std::endl; std::string xml_string; std::fstream xml_file(filepath.c_str(), std::fstream::in); while ( xml_file.good() ) { std::string line; std::getline( xml_file, line); xml_string += (line + "\n"); } xml_file.close(); object = otdf::parseOTDF(xml_string); } void map_store::pointcloud_handler(const drc_pointcloud2_t *msg){ cout << "got ptd handler\n"; // Create new local map object, store cloud pcl::PointCloud<pcl::PointXYZRGB>::Ptr cloud (new pcl::PointCloud<pcl::PointXYZRGB> ()); pc_lcm_->unpack_pointcloud2( (const ptools_pointcloud2_t*) msg, cloud); LocalMap map; //Eigen::Isometry3d base_pose; map.map_id =maps.size(); // use a counter instead map.utime =maps.size();// msg->utime; // use time later.. map.base_pose.setIdentity(); map.cloud =cloud; otdfPtr object( new otdf::ModelInterface); create_otdf_object_instance(object,"cylinder"); object->setParam("x", 0.66); // just for adding data object->setParam("y", -0.31); object->setParam("z", 0.45); object->setParam("roll", 0.0); object->setParam("pitch", 0.0); object->setParam("yaw", 0.0); object->setParam("radius", 0.16); object->setParam("length", 0.41); object->setParam("mass", 1.00); object->update(); map.objects.push_back(object); map.object_ids.push_back(DRC_AFFORDANCE_T_CYLINDER); map.object_names.push_back("uraniumrod"); otdfPtr object2( new otdf::ModelInterface); create_otdf_object_instance(object2,"lever"); object2->setParam("x", maps.size()+1); object2->setParam("y", 17); object2->setParam("z", 5); object2->update(); map.objects.push_back(object2); map.object_ids.push_back(DRC_AFFORDANCE_T_LEVER); map.object_names.push_back("savereactor"); maps.push_back(map); } int main(int argc, char ** argv) { lcm_t * lcm; lcm = lcm_create(NULL); map_store app(lcm); while(1) lcm_handle(lcm); lcm_destroy(lcm); return 0; } <commit_msg>changed aff type<commit_after>// Listen to map_store_POINTS files: // - store them in a local object // - maintain a list and broadcast the list // - support queries, which sent a specific cloud back // - listen for // LCM example program for interacting with PCL data // In this case it pushes the data back out to LCM in // a different message type for which the "collections" // renderer can view it in the LCM viewer // mfallon aug 2012 #include <stdio.h> #include <inttypes.h> #include <lcm/lcm.h> #include <iostream> #include <pcl/io/pcd_io.h> #include <pcl/point_types.h> #include <lcmtypes/visualization.h> #include <path_util/path_util.h> #include "map_store.hpp" #include <boost/shared_ptr.hpp> using namespace std; using namespace pcl; typedef boost::shared_ptr<otdf::ModelInterface> otdfPtr; ///////////////////////////////////// map_store::map_store(lcm_t* publish_lcm): publish_lcm_(publish_lcm) { pc_vis_ = new pointcloud_vis(publish_lcm_); // obj: id name type reset // pts: id name type reset objcoll usergb rgb pc_vis_->obj_cfg_list.push_back( obj_cfg(1000,"Pose - Dump",5,0) ); float colors_b[] ={0.0,0.0,1.0}; vector <float> colors_v; colors_v.assign(colors_b,colors_b+4*sizeof(float)); pc_vis_->ptcld_cfg_list.push_back( ptcld_cfg(1001,"Cloud - Dump" ,1,0, 1000,1,colors_v)); // pc_vis_->obj_cfg_list.push_back( obj_cfg(1100,"Pose - Current",5,0) ); float colors_r[] ={1.0,0.0,0.0}; colors_v.assign(colors_r,colors_r+4*sizeof(float)); pc_vis_->ptcld_cfg_list.push_back( ptcld_cfg(1101,"Cloud - Current" ,1,0, 1100,1,colors_v)); // LCM: lcm_t* subscribe_lcm_ = publish_lcm_; drc_pointcloud2_t_subscribe(subscribe_lcm_, "LOCAL_MAP_POINTS", pointcloud_handler_aux, this); drc_localize_reinitialize_cmd_t_subscribe(subscribe_lcm_, "SEG_REQUEST", seg_request_handler_aux, this); drc_localize_reinitialize_cmd_t_subscribe(subscribe_lcm_, "SEG_UPDATE", seg_update_handler_aux, this); drc_localize_reinitialize_cmd_t_subscribe(subscribe_lcm_, "DUMP_MAPS", dump_maps_handler_aux, this); drc_localize_reinitialize_cmd_t_subscribe(subscribe_lcm_, "CURRENT_MAP_ID", current_map_handler_aux, this); } void map_store::initialize(){ } void map_store::publish_affordance_collection(LocalMap m){ cout <<m.map_id << " | " << m.utime << "| " << m.cloud->size() << " cloud size\n"; // Send a pose drc_affordance_collection_t affs_coll; affs_coll.map_id = m.map_id; affs_coll.name = (char*) "homers_desk"; affs_coll.map_utime = m.utime; affs_coll.naffs = m.objects.size(); drc_affordance_t affs[affs_coll.naffs]; cout << m.objects.size() << " Objects\n"; for (size_t i=0;i <m.objects.size(); i++){ affs[i].map_utime = m.utime; affs[i].map_id = m.map_id; affs[i].name = (char*) m.object_names[i].c_str(); affs[i].otdf_id = m.object_ids[i]; otdfPtr object= m.objects[i]; std::map<std::string, double> param_map = object->params_map_; // all parameters defined in the object template std::map<std::string, double>::iterator it; cout << "params.size() is " << (int) param_map.size() << endl; affs[i].nparams=param_map.size(); double* params = new double[affs[i].nparams]; char** param_names = new char*[affs[i].nparams]; int j; for (it=param_map.begin(),j=0 ; it != param_map.end(); it++ , j++){ cout << (*it).first << " => " << (*it).second << " | "; param_names[j] = (char*) (*it).first.c_str(); params[j] = (*it).second; } affs[i].params = params; affs[i].param_names = param_names; affs[i].nstates=0; affs[i].states=NULL; affs[i].state_names=NULL; affs[i].nptinds=0; affs[i].ptinds=NULL; cout << endl; } affs_coll.affs = affs; drc_affordance_collection_t_publish(publish_lcm_, "AFFORDANCE_COLLECTION", &affs_coll); cout << "affs gone\n"; } void map_store::publish_local_map(unsigned int map_id){ cout << "publish_local_map called\n"; LocalMap m = maps[map_id]; publish_affordance_collection(m); cout <<m.map_id << " | " << m.utime << "| " << m.cloud->size() << " cloud size\n"; Eigen::Isometry3d offset_pose = m.base_pose; offset_pose.translation() << m.base_pose.translation().x(), m.base_pose.translation().y(), m.base_pose.translation().z(); Isometry3dTime offset_poseT = Isometry3dTime(m.utime, offset_pose); pc_vis_->pose_to_lcm_from_list(1100, offset_poseT); pc_vis_->ptcld_to_lcm_from_list(1101, *(m.cloud), offset_poseT.utime, offset_poseT.utime); cout << m.objects.size() << " Objects\n"; for (size_t i=0;i <m.objects.size(); i++){ otdfPtr object= m.objects[i]; std::map<std::string, double> params = object->params_map_; // all parameters defined in the object template std::map<std::string, double>::iterator it; cout << "params.size() is " << (int) params.size() << endl; for (it=params.begin() ; it != params.end(); it++ ){ cout << (*it).first << " => " << (*it).second << " | "; } cout << endl; } } void map_store::dump_maps(DumpCode code, double x_offset){ if (code == DUMP_SCREEN){ cout << "dump screen set\n"; } cout << "dump maps blah\n"; for (size_t i=0;i<maps.size() ; i++){ LocalMap m = maps[i]; cout <<m.map_id << " | " << m.utime << "| " << m.cloud->size() << " cloud size\n"; Eigen::Isometry3d offset_pose = m.base_pose; offset_pose.translation() << m.base_pose.translation().x() + x_offset*i, m.base_pose.translation().y()+ x_offset, m.base_pose.translation().z(); Isometry3dTime offset_poseT = Isometry3dTime(m.utime, offset_pose); pc_vis_->pose_to_lcm_from_list(1000, offset_poseT); pc_vis_->ptcld_to_lcm_from_list(1001, *(m.cloud), offset_poseT.utime, offset_poseT.utime); cout << m.objects.size() << " Objects\n"; for (size_t i=0;i <m.objects.size(); i++){ otdfPtr object= m.objects[i]; std::map<std::string, double> params = object->params_map_; // all parameters defined in the object template std::map<std::string, double>::iterator it; cout << "params.size() is " << (int) params.size() << endl; for (it=params.begin() ; it != params.end(); it++ ){ cout << (*it).first << " => " << (*it).second << " | "; } cout << endl; } } } void map_store::dump_maps_handler(const drc_localize_reinitialize_cmd_t *msg){ cout << "dump maps requested\n"; dump_maps(DUMP_SCREEN,40.0); // Sent a specific map to main gui publish_local_map(0); } void map_store::current_map_handler(const drc_localize_reinitialize_cmd_t *msg){ cout << "map\n"; // contains which map to visualise // ... transmit the specified map to the segmentation gui (continously @ 1Hz in a different thread) } void map_store::seg_request_handler(const drc_localize_reinitialize_cmd_t *msg){ cout << "segmentation map requested\n"; // ... transmit the map to the segmentation gui } void map_store::seg_update_handler(const drc_localize_reinitialize_cmd_t *msg){ cout << "received segmentation\n"; // ... log the segmentation } void create_otdf_object_instance (otdfPtr &object, string otdf_name)//(RendererOtdf *self) { // std::string filename = self->otdf_filenames[self->otdf_id]+".otdf"; // std::transform(filename.begin(), filename.end(), filename.begin(), ::tolower); string otdf_models_path = std::string(getModelsPath()) + "/otdf/"; // getModelsPath gives /drc/software/build/ std::string filepath = otdf_models_path+ otdf_name +".otdf";//(*self->otdf_dir_name_ptr)+filename; std::cout << "instantiating " << filepath << std::endl; std::string xml_string; std::fstream xml_file(filepath.c_str(), std::fstream::in); while ( xml_file.good() ) { std::string line; std::getline( xml_file, line); xml_string += (line + "\n"); } xml_file.close(); object = otdf::parseOTDF(xml_string); } void map_store::pointcloud_handler(const drc_pointcloud2_t *msg){ cout << "got ptd handler\n"; // Create new local map object, store cloud pcl::PointCloud<pcl::PointXYZRGB>::Ptr cloud (new pcl::PointCloud<pcl::PointXYZRGB> ()); pc_lcm_->unpack_pointcloud2( (const ptools_pointcloud2_t*) msg, cloud); LocalMap map; //Eigen::Isometry3d base_pose; map.map_id =maps.size(); // use a counter instead map.utime =maps.size();// msg->utime; // use time later.. map.base_pose.setIdentity(); map.cloud =cloud; otdfPtr object( new otdf::ModelInterface); create_otdf_object_instance(object,"cylinder"); object->setParam("x", 0.66); // just for adding data object->setParam("y", -0.31); object->setParam("z", 0.45); object->setParam("roll", 0.0); object->setParam("pitch", 0.0); object->setParam("yaw", 0.0); object->setParam("radius", 0.16); object->setParam("length", 0.41); object->setParam("mass", 1.00); object->update(); map.objects.push_back(object); map.object_ids.push_back(DRC_AFFORDANCE_T_CYLINDER); map.object_names.push_back("uraniumrod"); otdfPtr object2( new otdf::ModelInterface); create_otdf_object_instance(object2,"lever"); object2->setParam("x", maps.size()+1); object2->setParam("y", 17); object2->setParam("z", 5); object2->update(); map.objects.push_back(object2); map.object_ids.push_back(DRC_AFFORDANCE_T_LEVER); map.object_names.push_back("savereactor"); maps.push_back(map); } int main(int argc, char ** argv) { lcm_t * lcm; lcm = lcm_create(NULL); map_store app(lcm); while(1) lcm_handle(lcm); lcm_destroy(lcm); return 0; } <|endoftext|>
<commit_before>#include "common.h" #include "SoftXMT.hpp" #include "ForkJoin.hpp" #include "Cache.hpp" #include "Delegate.hpp" #include "PerformanceTools.hpp" #include "GlobalAllocator.hpp" #include "timer.h" #include "GlobalTaskJoiner.hpp" GRAPPA_DEFINE_EVENT_GROUP(bfs); #define read SoftXMT_delegate_read_word #define write SoftXMT_delegate_write_word #define cmp_swap SoftXMT_delegate_compare_and_swap_word #define fetch_add SoftXMT_delegate_fetch_and_add_word #define BUF_LEN 16384 static int64_t buf[BUF_LEN]; static int64_t kbuf; static GlobalAddress<int64_t> vlist; static GlobalAddress<int64_t> xoff; static GlobalAddress<int64_t> xadj; static GlobalAddress<int64_t> bfs_tree; static GlobalAddress<int64_t> k2; static int64_t nadj; #define XOFF(k) (xoff+2*(k)) #define XENDOFF(k) (xoff+2*(k)+1) #define GA64(name) ((GlobalAddress<int64_t>,name)) static void bfs_visit_neighbor(uint64_t packed, GlobalAddress<GlobalTaskJoiner> rjoiner) { int64_t vo = packed & 0xFFFFFFFF; int64_t v = packed >> 32; #ifdef DEBUG CHECK(vo < nadj) << "unpacking 'vo' unsuccessful (" << vo << " < " << nadj << ")"; CHECK(v < nadj) << "unpacking 'v' unsuccessful (" << v << " < " << nadj << ")"; GRAPPA_EVENT(visit_neighbor_ev, "visit neighbor of vertex", 1, bfs, v); #endif const int64_t j = read(xadj+vo); if (cmp_swap(bfs_tree+j, -1, v)) { while (kbuf == -1) { SoftXMT_yield(); } if (kbuf < BUF_LEN) { buf[kbuf] = j; (kbuf)++; } else { kbuf = -1; // lock other threads out temporarily int64_t voff = fetch_add(k2, BUF_LEN); Incoherent<int64_t>::RW cvlist(vlist+voff, BUF_LEN); for (int64_t vk=0; vk < BUF_LEN; vk++) { cvlist[vk] = buf[vk]; } buf[0] = j; kbuf = 1; } } GlobalTaskJoiner::remoteSignal(rjoiner); } static void bfs_visit_vertex(int64_t k, GlobalAddress<GlobalTaskJoiner> rjoiner) { const int64_t v = read(vlist+k); int64_t buf[2]; Incoherent<int64_t>::RO cr(xoff+2*v, 2, buf); const int64_t vstart = cr[0], vend = cr[1]; for (int64_t vo = vstart; vo < vend; vo++) { uint64_t packed = (((uint64_t)v) << 32) | vo; global_joiner.registerTask(); // register these new tasks on *this task*'s joiner SoftXMT_publicTask(&bfs_visit_neighbor, packed, global_joiner.addr()); } GlobalTaskJoiner::remoteSignal(rjoiner); } void bfs_level(Node nid, int64_t start, int64_t end) { range_t r = blockDist(start, end, nid, SoftXMT_nodes()); kbuf = 0; global_joiner.reset(); for (int64_t i = r.start; i < r.end; i++) { global_joiner.registerTask(); SoftXMT_publicTask(&bfs_visit_vertex, i, global_joiner.addr()); } global_joiner.wait(); } void clear_buffers() { if (kbuf) { int64_t voff = fetch_add(k2, kbuf); VLOG(2) << "flushing vlist buffer (kbuf=" << kbuf << ", k2=" << voff << ")"; Incoherent<int64_t>::RW cvlist(vlist+voff, kbuf); for (int64_t vk=0; vk < kbuf; vk++) { cvlist[vk] = buf[vk]; } kbuf = 0; } } LOOP_FUNCTOR(bfs_node, nid, GA64(_vlist)GA64(_xoff)GA64(_xadj)GA64(_bfs_tree)GA64(_k2)((int64_t,_nadj))) { // setup globals kbuf = 0; vlist = _vlist; xoff = _xoff; xadj = _xadj; bfs_tree = _bfs_tree; k2 = _k2; nadj = _nadj; int64_t k1 = 0, _k2 = 1; while (k1 != _k2) { VLOG(2) << "k1=" << k1 << ", k2=" << _k2; const int64_t oldk2 = _k2; bfs_level(SoftXMT_mynode(), k1, oldk2); SoftXMT_barrier_suspending(); clear_buffers(); SoftXMT_barrier_suspending(); k1 = oldk2; _k2 = read(k2); } } double make_bfs_tree(csr_graph * g, GlobalAddress<int64_t> bfs_tree, int64_t root) { int64_t NV = g->nv; GlobalAddress<int64_t> vlist = SoftXMT_typed_malloc<int64_t>(NV); double t; t = timer(); // start with root as only thing in vlist write(vlist, root); int64_t k1 = 0, k2 = 1; GlobalAddress<int64_t> k2addr = make_global(&k2); // initialize bfs_tree to -1 SoftXMT_memset(bfs_tree, (int64_t)-1, NV); write(bfs_tree+root, root); // parent of root is self { bfs_node f(vlist, g->xoff, g->xadj, bfs_tree, k2addr, g->nadj); fork_join_custom(&f); } t = timer() - t; SoftXMT_free(vlist); SoftXMT_merge_and_dump_stats(); return t; } <commit_msg>Use AsyncParallelFor (and GlobalTaskJoiner) in BFS.<commit_after>#include "common.h" #include "SoftXMT.hpp" #include "ForkJoin.hpp" #include "Cache.hpp" #include "Delegate.hpp" #include "PerformanceTools.hpp" #include "GlobalAllocator.hpp" #include "timer.h" #include "GlobalTaskJoiner.hpp" #include "AsyncParallelFor.hpp" GRAPPA_DEFINE_EVENT_GROUP(bfs); #define read SoftXMT_delegate_read_word #define write SoftXMT_delegate_write_word #define cmp_swap SoftXMT_delegate_compare_and_swap_word #define fetch_add SoftXMT_delegate_fetch_and_add_word #define BUF_LEN 16384 static int64_t buf[BUF_LEN]; static int64_t kbuf; static GlobalAddress<int64_t> vlist; static GlobalAddress<int64_t> xoff; static GlobalAddress<int64_t> xadj; static GlobalAddress<int64_t> bfs_tree; static GlobalAddress<int64_t> k2; static int64_t nadj; #define XOFF(k) (xoff+2*(k)) #define XENDOFF(k) (xoff+2*(k)+1) #define GA64(name) ((GlobalAddress<int64_t>,name)) void bfs_visit_neighbor(int64_t estart, int64_t eiters, GlobalAddress<void*> packed) { int64_t v = (int64_t)packed.pointer(); //const int64_t j = read(xadj+vo); //VLOG(1) << "estart: " << estart << ", eiters: " << eiters; int64_t cbuf[eiters]; Incoherent<int64_t>::RO cadj(xadj+estart, eiters, cbuf); for (int64_t i = 0; i < eiters; i++) { const int64_t j = cadj[i]; //VLOG(1) << "v = " << v << ", j = " << j << ", i = " << i << ", eiters = " << eiters; if (cmp_swap(bfs_tree+j, -1, v)) { while (kbuf == -1) { SoftXMT_yield(); } if (kbuf < BUF_LEN) { buf[kbuf] = j; (kbuf)++; } else { // TODO: swap buffer! kbuf = -1; // lock other threads out temporarily int64_t voff = fetch_add(k2, BUF_LEN); Incoherent<int64_t>::RW cvlist(vlist+voff, BUF_LEN); for (int64_t vk=0; vk < BUF_LEN; vk++) { cvlist[vk] = buf[vk]; } buf[0] = j; kbuf = 1; } } } } void bfs_visit_vertex(int64_t kstart, int64_t kiters) { //VLOG(1) << "bfs_visit_vertex(" << kstart << ", " << kiters << ")"; int64_t buf[kiters]; Incoherent<int64_t>::RO cvlist(vlist+kstart, kiters, buf); for (int64_t i=0; i<kiters; i++) { const int64_t v = cvlist[i]; int64_t buf[2]; Incoherent<int64_t>::RO cxoff(xoff+2*v, 2, buf); const int64_t vstart = cxoff[0], vend = cxoff[1]; GlobalAddress<void*> packed = make_global( (void**)(v) ); //VLOG(1) << "apfor<bfs_visit_neighbor>(" << vstart << ", " << vend << ")"; async_parallel_for<void*, bfs_visit_neighbor, joinerSpawn_hack<void*,bfs_visit_neighbor> >(vstart, vend-vstart, packed); //for (int64_t vo = vstart; vo < vend; vo++) { //uint64_t packed = (((uint64_t)v) << 32) | vo; //global_joiner.registerTask(); // register these new tasks on *this task*'s joiner //SoftXMT_publicTask(&bfs_visit_neighbor, packed, global_joiner.addr()); //} } } void bfs_level(Node nid, int64_t start, int64_t end) { range_t r = blockDist(start, end, nid, SoftXMT_nodes()); kbuf = 0; global_joiner.reset(); VLOG(2) << "phase start <" << end-start << "> (" << r.start << ", " << r.end << ")"; async_parallel_for< bfs_visit_vertex, joinerSpawn<bfs_visit_vertex> >(r.start, r.end-r.start); //for (int64_t i = r.start; i < r.end; i++) { //global_joiner.registerTask(); //SoftXMT_publicTask(&bfs_visit_vertex, i, global_joiner.addr()); //} global_joiner.wait(); VLOG(2) << "phase complete"; } void clear_buffers() { if (kbuf) { int64_t voff = fetch_add(k2, kbuf); VLOG(2) << "flushing vlist buffer (kbuf=" << kbuf << ", k2=" << voff << ")"; Incoherent<int64_t>::RW cvlist(vlist+voff, kbuf); for (int64_t vk=0; vk < kbuf; vk++) { cvlist[vk] = buf[vk]; } kbuf = 0; } } LOOP_FUNCTOR(bfs_node, nid, GA64(_vlist)GA64(_xoff)GA64(_xadj)GA64(_bfs_tree)GA64(_k2)((int64_t,_nadj))) { // setup globals kbuf = 0; vlist = _vlist; xoff = _xoff; xadj = _xadj; bfs_tree = _bfs_tree; k2 = _k2; nadj = _nadj; int64_t k1 = 0, _k2 = 1; while (k1 != _k2) { VLOG(2) << "k1=" << k1 << ", k2=" << _k2; const int64_t oldk2 = _k2; bfs_level(SoftXMT_mynode(), k1, oldk2); SoftXMT_barrier_suspending(); clear_buffers(); SoftXMT_barrier_suspending(); k1 = oldk2; _k2 = read(k2); } } double make_bfs_tree(csr_graph * g, GlobalAddress<int64_t> bfs_tree, int64_t root) { int64_t NV = g->nv; GlobalAddress<int64_t> vlist = SoftXMT_typed_malloc<int64_t>(NV); double t; t = timer(); // start with root as only thing in vlist write(vlist, root); int64_t k1 = 0, k2 = 1; GlobalAddress<int64_t> k2addr = make_global(&k2); // initialize bfs_tree to -1 SoftXMT_memset(bfs_tree, (int64_t)-1, NV); write(bfs_tree+root, root); // parent of root is self { bfs_node f(vlist, g->xoff, g->xadj, bfs_tree, k2addr, g->nadj); fork_join_custom(&f); } t = timer() - t; SoftXMT_free(vlist); SoftXMT_merge_and_dump_stats(); return t; } <|endoftext|>
<commit_before>/****************************************************************************** * SOFA, Simulation Open-Framework Architecture, version 1.0 beta 4 * * (c) 2006-2009 MGH, INRIA, USTL, UJF, CNRS * * * * This program is free software; you can redistribute it and/or modify it * * under the terms of the GNU General Public License as published by the Free * * Software Foundation; either version 2 of the License, or (at your option) * * any later version. * * * * This program is distributed in the hope that it will be useful, but WITHOUT * * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or * * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for * * more details. * * * * You should have received a copy of the GNU General Public License along * * with this program; if not, write to the Free Software Foundation, Inc., 51 * * Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. * ******************************************************************************* * SOFA :: Applications * * * * Authors: M. Adam, J. Allard, B. Andre, P-J. Bensoussan, S. Cotin, C. Duriez,* * H. Delingette, F. Falipou, F. Faure, S. Fonteneau, L. Heigeas, C. Mendoza, * * M. Nesme, P. Neumann, J-P. de la Plata Alcade, F. Poyer and F. Roy * * * * Contact information: [email protected] * ******************************************************************************/ #include <sofa/gui/PickHandler.h> #include <sofa/component/collision/ComponentMouseInteraction.h> #include <sofa/component/collision/RayContact.h> #include <sofa/simulation/common/InitVisitor.h> #include <sofa/simulation/common/MechanicalVisitor.h> #include <sofa/helper/gl/DrawManager.h> #include <sofa/simulation/common/Simulation.h> #include <iostream> namespace sofa { using namespace component::collision; namespace gui { PickHandler::PickHandler():interactorInUse(false), mouseStatus(DEACTIVATED),mouseButton(NONE),renderCallback(NULL) { operations[LEFT] = operations[MIDDLE] = operations[RIGHT] = NULL; mouseNode = simulation::getSimulation()->newNode("Mouse"); mouseContainer = new MouseContainer; mouseContainer->resize(1); mouseContainer->setName("MousePosition"); mouseNode->addObject(mouseContainer); mouseCollision = new MouseCollisionModel; mouseCollision->setNbRay(1); mouseCollision->getRay(0).l() = 1000000; mouseCollision->setName("MouseCollisionModel"); mouseNode->addObject(mouseCollision); mouseNode->init(); mouseContainer->init(); mouseCollision->init(); typedef component::collision::ComponentMouseInteraction::ComponentMouseInteractionFactory MouseFactory; const MouseFactory *factory = MouseFactory::getInstance(); for (MouseFactory::const_iterator it = factory->begin(); it != factory->end(); ++it) { instanceComponents.push_back(it->second->createInstance(NULL)); instanceComponents.back()->init(mouseNode); } interaction = instanceComponents.back(); } PickHandler::~PickHandler() { for (unsigned int i=0; i<operations.size(); ++i) { delete operations[i]; } if( renderCallback ) delete renderCallback; // for (unsigned int i=0;i<instanceComponents.size();++i) delete instanceComponents[i]; } void PickHandler::init() { core::collision::Pipeline *pipeline; simulation::getSimulation()->getContext()->get(pipeline, core::objectmodel::BaseContext::SearchRoot); useCollisions = (pipeline != NULL); if (simulation::getSimulation()->DrawUtility.getSystemDraw() != sofa::helper::gl::DrawManager::OGRE) { _fboParams.depthInternalformat = GL_DEPTH_COMPONENT24; _fboParams.colorInternalformat = GL_RGBA32F; _fboParams.colorFormat = GL_RGBA; _fboParams.colorType = GL_FLOAT; _fbo.setFormat(_fboParams); _fbo.init(GL_MAX_TEXTURE_SIZE,GL_MAX_TEXTURE_SIZE); } } void PickHandler::reset() { activateRay(false); mouseButton = NONE; for (unsigned int i=0; i<instanceComponents.size(); ++i) instanceComponents[i]->reset(); } Operation *PickHandler::changeOperation(sofa::component::configurationsetting::MouseButtonSetting* setting) { if (operations[setting->getButton()]) delete operations[setting->getButton()]; Operation *mouseOp=OperationFactory::Instanciate(setting->getOperationType()); mouseOp->configure(this,setting); operations[setting->getButton()]=mouseOp; return mouseOp; } Operation *PickHandler::changeOperation(MOUSE_BUTTON button, const std::string &op) { if (operations[button]) delete operations[button]; Operation *mouseOp=OperationFactory::Instanciate(op); mouseOp->configure(this,button); operations[button]=mouseOp; return mouseOp; } void PickHandler::activateRay(bool act) { if (interactorInUse && !act) { mouseNode->detachFromGraph(); operations[LEFT]->endOperation(); operations[MIDDLE]->endOperation(); operations[RIGHT]->endOperation(); interaction->deactivate(); interactorInUse=false; } else if (!interactorInUse && act) { Node *root = static_cast<Node*>(simulation::getSimulation()->getContext()); root->addChild(mouseNode); interaction->activate(); interactorInUse=true; } } bool PickHandler::needToCastRay() { return !getInteraction()->mouseInteractor->isMouseAttached(); } void PickHandler::setCompatibleInteractor() { if (!lastPicked.body && !lastPicked.mstate) return; if (lastPicked.body) { if (interaction->isCompatible(lastPicked.body->getContext())) return; for (unsigned int i=0; i<instanceComponents.size(); ++i) { if (instanceComponents[i] != interaction && instanceComponents[i]->isCompatible(lastPicked.body->getContext())) { interaction->deactivate(); interaction = instanceComponents[i]; interaction->activate(); } } } else { if (interaction->isCompatible(lastPicked.mstate->getContext())) return; for (unsigned int i=0; i<instanceComponents.size(); ++i) { if (instanceComponents[i] != interaction && instanceComponents[i]->isCompatible(lastPicked.mstate->getContext())) { interaction->deactivate(); interaction = instanceComponents[i]; interaction->activate(); } } } } void PickHandler::updateRay(const sofa::defaulttype::Vector3 &position,const sofa::defaulttype::Vector3 &orientation) { if (!interactorInUse) return; mouseCollision->getRay(0).origin() = position+orientation*interaction->mouseInteractor->getDistanceFromMouse(); mouseCollision->getRay(0).direction() = orientation; simulation::MechanicalPropagatePositionVisitor().execute(mouseCollision->getContext()); if (needToCastRay()) { lastPicked=findCollision(); setCompatibleInteractor(); interaction->mouseInteractor->setMouseRayModel(mouseCollision); interaction->mouseInteractor->setBodyPicked(lastPicked); for (unsigned int i=0; i<callbacks.size(); ++i) { callbacks[i]->execute(lastPicked); } } if(mouseButton != NONE) { switch (mouseStatus) { case PRESSED: { operations[mouseButton]->start(); mouseStatus=ACTIVATED; break; } case RELEASED: { operations[mouseButton]->end(); mouseStatus=DEACTIVATED; break; } case ACTIVATED: { operations[mouseButton]->execution(); } case DEACTIVATED: { } } } for (unsigned int i=0; i<operations.size(); ++i) { operations[i]->wait(); } } //Clear the node create, and destroy all its components void PickHandler::handleMouseEvent(MOUSE_STATUS status, MOUSE_BUTTON button) { if (!interaction) return; mouseButton=button; mouseStatus=status; } ComponentMouseInteraction *PickHandler::getInteraction() { return interaction; } component::collision::BodyPicked PickHandler::findCollision() { if (useCollisions) { component::collision::BodyPicked picked=findCollisionUsingPipeline(); if (picked.body) return picked; } return findCollisionUsingBruteForce(); //return findCollisionUsingColourCoding(); } component::collision::BodyPicked PickHandler::findCollisionUsingPipeline() { const defaulttype::Vector3& origin = mouseCollision->getRay(0).origin(); const defaulttype::Vector3& direction = mouseCollision->getRay(0).direction(); const double& maxLength = mouseCollision->getRay(0).l(); BodyPicked result; const std::set< sofa::component::collision::BaseRayContact*> &contacts = mouseCollision->getContacts(); for (std::set< sofa::component::collision::BaseRayContact*>::const_iterator it=contacts.begin(); it != contacts.end(); ++it) { const sofa::helper::vector<core::collision::DetectionOutput*>& output = (*it)->getDetectionOutputs(); sofa::core::CollisionModel *modelInCollision; for (unsigned int i=0; i<output.size(); ++i) { if (output[i]->elem.first.getCollisionModel() == mouseCollision) { modelInCollision = output[i]->elem.second.getCollisionModel(); if (!modelInCollision->isSimulated()) continue; const double d = (output[i]->point[1]-origin)*direction; if (d<0.0 || d>maxLength) continue; if (result.body == NULL || d < result.rayLength) { result.body=modelInCollision; result.indexCollisionElement = output[i]->elem.second.getIndex(); result.point = output[i]->point[1]; result.dist = (output[i]->point[1]-output[i]->point[0]).norm(); result.rayLength = d; } } else if (output[i]->elem.second.getCollisionModel() == mouseCollision) { modelInCollision = output[i]->elem.first.getCollisionModel(); if (!modelInCollision->isSimulated()) continue; const double d = (output[i]->point[0]-origin)*direction; if (d<0.0 || d>maxLength) continue; if (result.body == NULL || d < result.rayLength) { result.body=modelInCollision; result.indexCollisionElement = output[i]->elem.first.getIndex(); result.point = output[i]->point[0]; result.dist = (output[i]->point[1]-output[i]->point[0]).norm(); result.rayLength = d; } } } } return result; } component::collision::BodyPicked PickHandler::findCollisionUsingBruteForce() { const defaulttype::Vector3& origin = mouseCollision->getRay(0).origin(); const defaulttype::Vector3& direction = mouseCollision->getRay(0).direction(); const double& maxLength = mouseCollision->getRay(0).l(); return findCollisionUsingBruteForce(origin, direction, maxLength); } component::collision::BodyPicked PickHandler::findCollisionUsingColourCoding() { const defaulttype::Vector3& origin = mouseCollision->getRay(0).origin(); const defaulttype::Vector3& direction = mouseCollision->getRay(0).direction(); return findCollisionUsingColourCoding(origin, direction); } component::collision::BodyPicked PickHandler::findCollisionUsingBruteForce(const defaulttype::Vector3& origin, const defaulttype::Vector3& direction, double maxLength) { BodyPicked result; // Look for particles hit by this ray simulation::MechanicalPickParticlesVisitor picker(origin, direction, maxLength, 0); core::objectmodel::BaseNode* rootNode = dynamic_cast<core::objectmodel::BaseNode*>(sofa::simulation::getSimulation()->getContext()); if (rootNode) picker.execute(rootNode->getContext()); else std::cerr << "ERROR: root node not found." << std::endl; if (!picker.particles.empty()) { core::behavior::BaseMechanicalState *mstate = picker.particles.begin()->second.first; result.mstate=mstate; result.indexCollisionElement = picker.particles.begin()->second.second; result.point[0] = mstate->getPX(result.indexCollisionElement); result.point[1] = mstate->getPY(result.indexCollisionElement); result.point[2] = mstate->getPZ(result.indexCollisionElement); result.dist = 0; result.rayLength = (result.point-origin)*direction; } return result; } component::collision::BodyPicked PickHandler::findCollisionUsingColourCoding(const defaulttype::Vector3& origin, const defaulttype::Vector3& direction) { BodyPicked result; static const float threshold = 0.001f; sofa::defaulttype::Vec4f color; int x = mousePosition.screenWidth - mousePosition.x; int y = mousePosition.screenHeight - mousePosition.y; _fbo.start(); if(renderCallback) { renderCallback->render(); } glReadPixels(x,y,1,1,_fboParams.colorFormat,_fboParams.colorType,color.elems); _fbo.stop(); result = _decodeColour(color, origin, direction); return result; } component::collision::BodyPicked PickHandler::_decodeColour(const sofa::defaulttype::Vec4f& colour, const defaulttype::Vector3& origin, const defaulttype::Vector3& direction) { using namespace core::objectmodel; using namespace core::behavior; using namespace sofa::defaulttype; static const float threshold = 0.001f; component::collision::BodyPicked result; result.dist = 0; if( colour[0] > threshold ) { helper::vector<core::CollisionModel*> listCollisionModel; sofa::simulation::getSimulation()->getContext()->get<core::CollisionModel>(&listCollisionModel,BaseContext::SearchRoot); const int totalCollisionModel = listCollisionModel.size(); const int indexListCollisionModel = (int) ( colour[0] * (float)totalCollisionModel + 0.5) - 1; result.body = listCollisionModel[indexListCollisionModel]; result.indexCollisionElement = (int) ( colour[1] * result.body->getSize() ); if( colour[2] < threshold && colour[3] < threshold ) { /* no barycentric weights */ core::behavior::BaseMechanicalState *mstate; result.body->getContext()->get(mstate,BaseContext::Local); if(mstate) { result.point[0] = mstate->getPX(result.indexCollisionElement); result.point[1] = mstate->getPY(result.indexCollisionElement); result.point[2] = mstate->getPZ(result.indexCollisionElement); } } result.rayLength = (result.point-origin)*direction; } return result; } } } <commit_msg>r7815/sofa-dev : FIX: compilation<commit_after>/****************************************************************************** * SOFA, Simulation Open-Framework Architecture, version 1.0 beta 4 * * (c) 2006-2009 MGH, INRIA, USTL, UJF, CNRS * * * * This program is free software; you can redistribute it and/or modify it * * under the terms of the GNU General Public License as published by the Free * * Software Foundation; either version 2 of the License, or (at your option) * * any later version. * * * * This program is distributed in the hope that it will be useful, but WITHOUT * * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or * * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for * * more details. * * * * You should have received a copy of the GNU General Public License along * * with this program; if not, write to the Free Software Foundation, Inc., 51 * * Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. * ******************************************************************************* * SOFA :: Applications * * * * Authors: M. Adam, J. Allard, B. Andre, P-J. Bensoussan, S. Cotin, C. Duriez,* * H. Delingette, F. Falipou, F. Faure, S. Fonteneau, L. Heigeas, C. Mendoza, * * M. Nesme, P. Neumann, J-P. de la Plata Alcade, F. Poyer and F. Roy * * * * Contact information: [email protected] * ******************************************************************************/ #include <sofa/gui/PickHandler.h> #include <sofa/component/collision/ComponentMouseInteraction.h> #include <sofa/component/collision/RayContact.h> #include <sofa/simulation/common/InitVisitor.h> #include <sofa/simulation/common/MechanicalVisitor.h> #include <sofa/helper/gl/DrawManager.h> #include <sofa/simulation/common/Simulation.h> #include <iostream> namespace sofa { using namespace component::collision; namespace gui { PickHandler::PickHandler():interactorInUse(false), mouseStatus(DEACTIVATED),mouseButton(NONE),renderCallback(NULL) { operations[LEFT] = operations[MIDDLE] = operations[RIGHT] = NULL; mouseNode = simulation::getSimulation()->newNode("Mouse"); mouseContainer = new MouseContainer; mouseContainer->resize(1); mouseContainer->setName("MousePosition"); mouseNode->addObject(mouseContainer); mouseCollision = new MouseCollisionModel; mouseCollision->setNbRay(1); mouseCollision->getRay(0).l() = 1000000; mouseCollision->setName("MouseCollisionModel"); mouseNode->addObject(mouseCollision); mouseNode->init(); mouseContainer->init(); mouseCollision->init(); typedef component::collision::ComponentMouseInteraction::ComponentMouseInteractionFactory MouseFactory; const MouseFactory *factory = MouseFactory::getInstance(); for (MouseFactory::const_iterator it = factory->begin(); it != factory->end(); ++it) { instanceComponents.push_back(it->second->createInstance(NULL)); instanceComponents.back()->init(mouseNode); } interaction = instanceComponents.back(); } PickHandler::~PickHandler() { for (unsigned int i=0; i<operations.size(); ++i) { delete operations[i]; } if( renderCallback ) delete renderCallback; // for (unsigned int i=0;i<instanceComponents.size();++i) delete instanceComponents[i]; } void PickHandler::init() { core::collision::Pipeline *pipeline; simulation::getSimulation()->getContext()->get(pipeline, core::objectmodel::BaseContext::SearchRoot); useCollisions = (pipeline != NULL); #ifdef SOFA_GUI_QTOGREVIEWER if (simulation::getSimulation()->DrawUtility.getSystemDraw() != sofa::helper::gl::DrawManager::OGRE) #endif { _fboParams.depthInternalformat = GL_DEPTH_COMPONENT24; _fboParams.colorInternalformat = GL_RGBA32F; _fboParams.colorFormat = GL_RGBA; _fboParams.colorType = GL_FLOAT; _fbo.setFormat(_fboParams); _fbo.init(GL_MAX_TEXTURE_SIZE,GL_MAX_TEXTURE_SIZE); } } void PickHandler::reset() { activateRay(false); mouseButton = NONE; for (unsigned int i=0; i<instanceComponents.size(); ++i) instanceComponents[i]->reset(); } Operation *PickHandler::changeOperation(sofa::component::configurationsetting::MouseButtonSetting* setting) { if (operations[setting->getButton()]) delete operations[setting->getButton()]; Operation *mouseOp=OperationFactory::Instanciate(setting->getOperationType()); mouseOp->configure(this,setting); operations[setting->getButton()]=mouseOp; return mouseOp; } Operation *PickHandler::changeOperation(MOUSE_BUTTON button, const std::string &op) { if (operations[button]) delete operations[button]; Operation *mouseOp=OperationFactory::Instanciate(op); mouseOp->configure(this,button); operations[button]=mouseOp; return mouseOp; } void PickHandler::activateRay(bool act) { if (interactorInUse && !act) { mouseNode->detachFromGraph(); operations[LEFT]->endOperation(); operations[MIDDLE]->endOperation(); operations[RIGHT]->endOperation(); interaction->deactivate(); interactorInUse=false; } else if (!interactorInUse && act) { Node *root = static_cast<Node*>(simulation::getSimulation()->getContext()); root->addChild(mouseNode); interaction->activate(); interactorInUse=true; } } bool PickHandler::needToCastRay() { return !getInteraction()->mouseInteractor->isMouseAttached(); } void PickHandler::setCompatibleInteractor() { if (!lastPicked.body && !lastPicked.mstate) return; if (lastPicked.body) { if (interaction->isCompatible(lastPicked.body->getContext())) return; for (unsigned int i=0; i<instanceComponents.size(); ++i) { if (instanceComponents[i] != interaction && instanceComponents[i]->isCompatible(lastPicked.body->getContext())) { interaction->deactivate(); interaction = instanceComponents[i]; interaction->activate(); } } } else { if (interaction->isCompatible(lastPicked.mstate->getContext())) return; for (unsigned int i=0; i<instanceComponents.size(); ++i) { if (instanceComponents[i] != interaction && instanceComponents[i]->isCompatible(lastPicked.mstate->getContext())) { interaction->deactivate(); interaction = instanceComponents[i]; interaction->activate(); } } } } void PickHandler::updateRay(const sofa::defaulttype::Vector3 &position,const sofa::defaulttype::Vector3 &orientation) { if (!interactorInUse) return; mouseCollision->getRay(0).origin() = position+orientation*interaction->mouseInteractor->getDistanceFromMouse(); mouseCollision->getRay(0).direction() = orientation; simulation::MechanicalPropagatePositionVisitor().execute(mouseCollision->getContext()); if (needToCastRay()) { lastPicked=findCollision(); setCompatibleInteractor(); interaction->mouseInteractor->setMouseRayModel(mouseCollision); interaction->mouseInteractor->setBodyPicked(lastPicked); for (unsigned int i=0; i<callbacks.size(); ++i) { callbacks[i]->execute(lastPicked); } } if(mouseButton != NONE) { switch (mouseStatus) { case PRESSED: { operations[mouseButton]->start(); mouseStatus=ACTIVATED; break; } case RELEASED: { operations[mouseButton]->end(); mouseStatus=DEACTIVATED; break; } case ACTIVATED: { operations[mouseButton]->execution(); } case DEACTIVATED: { } } } for (unsigned int i=0; i<operations.size(); ++i) { operations[i]->wait(); } } //Clear the node create, and destroy all its components void PickHandler::handleMouseEvent(MOUSE_STATUS status, MOUSE_BUTTON button) { if (!interaction) return; mouseButton=button; mouseStatus=status; } ComponentMouseInteraction *PickHandler::getInteraction() { return interaction; } component::collision::BodyPicked PickHandler::findCollision() { if (useCollisions) { component::collision::BodyPicked picked=findCollisionUsingPipeline(); if (picked.body) return picked; } return findCollisionUsingBruteForce(); //return findCollisionUsingColourCoding(); } component::collision::BodyPicked PickHandler::findCollisionUsingPipeline() { const defaulttype::Vector3& origin = mouseCollision->getRay(0).origin(); const defaulttype::Vector3& direction = mouseCollision->getRay(0).direction(); const double& maxLength = mouseCollision->getRay(0).l(); BodyPicked result; const std::set< sofa::component::collision::BaseRayContact*> &contacts = mouseCollision->getContacts(); for (std::set< sofa::component::collision::BaseRayContact*>::const_iterator it=contacts.begin(); it != contacts.end(); ++it) { const sofa::helper::vector<core::collision::DetectionOutput*>& output = (*it)->getDetectionOutputs(); sofa::core::CollisionModel *modelInCollision; for (unsigned int i=0; i<output.size(); ++i) { if (output[i]->elem.first.getCollisionModel() == mouseCollision) { modelInCollision = output[i]->elem.second.getCollisionModel(); if (!modelInCollision->isSimulated()) continue; const double d = (output[i]->point[1]-origin)*direction; if (d<0.0 || d>maxLength) continue; if (result.body == NULL || d < result.rayLength) { result.body=modelInCollision; result.indexCollisionElement = output[i]->elem.second.getIndex(); result.point = output[i]->point[1]; result.dist = (output[i]->point[1]-output[i]->point[0]).norm(); result.rayLength = d; } } else if (output[i]->elem.second.getCollisionModel() == mouseCollision) { modelInCollision = output[i]->elem.first.getCollisionModel(); if (!modelInCollision->isSimulated()) continue; const double d = (output[i]->point[0]-origin)*direction; if (d<0.0 || d>maxLength) continue; if (result.body == NULL || d < result.rayLength) { result.body=modelInCollision; result.indexCollisionElement = output[i]->elem.first.getIndex(); result.point = output[i]->point[0]; result.dist = (output[i]->point[1]-output[i]->point[0]).norm(); result.rayLength = d; } } } } return result; } component::collision::BodyPicked PickHandler::findCollisionUsingBruteForce() { const defaulttype::Vector3& origin = mouseCollision->getRay(0).origin(); const defaulttype::Vector3& direction = mouseCollision->getRay(0).direction(); const double& maxLength = mouseCollision->getRay(0).l(); return findCollisionUsingBruteForce(origin, direction, maxLength); } component::collision::BodyPicked PickHandler::findCollisionUsingColourCoding() { const defaulttype::Vector3& origin = mouseCollision->getRay(0).origin(); const defaulttype::Vector3& direction = mouseCollision->getRay(0).direction(); return findCollisionUsingColourCoding(origin, direction); } component::collision::BodyPicked PickHandler::findCollisionUsingBruteForce(const defaulttype::Vector3& origin, const defaulttype::Vector3& direction, double maxLength) { BodyPicked result; // Look for particles hit by this ray simulation::MechanicalPickParticlesVisitor picker(origin, direction, maxLength, 0); core::objectmodel::BaseNode* rootNode = dynamic_cast<core::objectmodel::BaseNode*>(sofa::simulation::getSimulation()->getContext()); if (rootNode) picker.execute(rootNode->getContext()); else std::cerr << "ERROR: root node not found." << std::endl; if (!picker.particles.empty()) { core::behavior::BaseMechanicalState *mstate = picker.particles.begin()->second.first; result.mstate=mstate; result.indexCollisionElement = picker.particles.begin()->second.second; result.point[0] = mstate->getPX(result.indexCollisionElement); result.point[1] = mstate->getPY(result.indexCollisionElement); result.point[2] = mstate->getPZ(result.indexCollisionElement); result.dist = 0; result.rayLength = (result.point-origin)*direction; } return result; } component::collision::BodyPicked PickHandler::findCollisionUsingColourCoding(const defaulttype::Vector3& origin, const defaulttype::Vector3& direction) { BodyPicked result; static const float threshold = 0.001f; sofa::defaulttype::Vec4f color; int x = mousePosition.screenWidth - mousePosition.x; int y = mousePosition.screenHeight - mousePosition.y; _fbo.start(); if(renderCallback) { renderCallback->render(); } glReadPixels(x,y,1,1,_fboParams.colorFormat,_fboParams.colorType,color.elems); _fbo.stop(); result = _decodeColour(color, origin, direction); return result; } component::collision::BodyPicked PickHandler::_decodeColour(const sofa::defaulttype::Vec4f& colour, const defaulttype::Vector3& origin, const defaulttype::Vector3& direction) { using namespace core::objectmodel; using namespace core::behavior; using namespace sofa::defaulttype; static const float threshold = 0.001f; component::collision::BodyPicked result; result.dist = 0; if( colour[0] > threshold ) { helper::vector<core::CollisionModel*> listCollisionModel; sofa::simulation::getSimulation()->getContext()->get<core::CollisionModel>(&listCollisionModel,BaseContext::SearchRoot); const int totalCollisionModel = listCollisionModel.size(); const int indexListCollisionModel = (int) ( colour[0] * (float)totalCollisionModel + 0.5) - 1; result.body = listCollisionModel[indexListCollisionModel]; result.indexCollisionElement = (int) ( colour[1] * result.body->getSize() ); if( colour[2] < threshold && colour[3] < threshold ) { /* no barycentric weights */ core::behavior::BaseMechanicalState *mstate; result.body->getContext()->get(mstate,BaseContext::Local); if(mstate) { result.point[0] = mstate->getPX(result.indexCollisionElement); result.point[1] = mstate->getPY(result.indexCollisionElement); result.point[2] = mstate->getPZ(result.indexCollisionElement); } } result.rayLength = (result.point-origin)*direction; } return result; } } } <|endoftext|>
<commit_before>//===-- SymbolVendorMacOSX.cpp ----------------------------------*- C++ -*-===// // // The LLVM Compiler Infrastructure // // This file is distributed under the University of Illinois Open Source // License. See LICENSE.TXT for details. // //===----------------------------------------------------------------------===// #include "SymbolVendorMacOSX.h" #include <libxml/parser.h> #include <libxml/tree.h> #include <string.h> #include <AvailabilityMacros.h> #include "lldb/Core/Module.h" #include "lldb/Core/PluginManager.h" #include "lldb/Core/Section.h" #include "lldb/Core/StreamString.h" #include "lldb/Core/Timer.h" #include "lldb/Host/Host.h" #include "lldb/Host/Symbols.h" #include "lldb/Symbol/ObjectFile.h" using namespace lldb; using namespace lldb_private; //---------------------------------------------------------------------- // SymbolVendorMacOSX constructor //---------------------------------------------------------------------- SymbolVendorMacOSX::SymbolVendorMacOSX(const lldb::ModuleSP &module_sp) : SymbolVendor (module_sp) { } //---------------------------------------------------------------------- // Destructor //---------------------------------------------------------------------- SymbolVendorMacOSX::~SymbolVendorMacOSX() { } static bool UUIDsMatch(Module *module, ObjectFile *ofile) { if (module && ofile) { // Make sure the UUIDs match lldb_private::UUID dsym_uuid; if (ofile->GetUUID(&dsym_uuid)) return dsym_uuid == module->GetUUID(); // Emit some warning messages since the UUIDs do not match! const FileSpec &m_file_spec = module->GetFileSpec(); const FileSpec &o_file_spec = ofile->GetFileSpec(); StreamString ss_m_path, ss_o_path; m_file_spec.Dump(&ss_m_path); o_file_spec.Dump(&ss_o_path); StreamString ss_m_uuid, ss_o_uuid; module->GetUUID().Dump(&ss_m_uuid); dsym_uuid.Dump(&ss_o_uuid); Host::SystemLog (Host::eSystemLogWarning, "warning: UUID mismatch detected between module '%s' (%s) and:\n\t'%s' (%s)\n", ss_m_path.GetData(), ss_m_uuid.GetData(), ss_o_path.GetData(), ss_o_uuid.GetData()); } return false; } static void ReplaceDSYMSectionsWithExecutableSections (ObjectFile *exec_objfile, ObjectFile *dsym_objfile) { // We need both the executable and the dSYM to live off of the // same section lists. So we take all of the sections from the // executable, and replace them in the dSYM. This allows section // offset addresses that come from the dSYM to automatically // get updated as images (shared libraries) get loaded and // unloaded. SectionList *exec_section_list = exec_objfile->GetSectionList(); SectionList *dsym_section_list = dsym_objfile->GetSectionList(); if (exec_section_list && dsym_section_list) { const uint32_t num_exec_sections = dsym_section_list->GetSize(); uint32_t exec_sect_idx; for (exec_sect_idx = 0; exec_sect_idx < num_exec_sections; ++exec_sect_idx) { SectionSP exec_sect_sp(exec_section_list->GetSectionAtIndex(exec_sect_idx)); if (exec_sect_sp.get()) { // Try and replace any sections that exist in both the executable // and in the dSYM with those from the executable. If we fail to // replace the one in the dSYM, then add the executable section to // the dSYM. if (dsym_section_list->ReplaceSection(exec_sect_sp->GetID(), exec_sect_sp, 0) == false) dsym_section_list->AddSection(exec_sect_sp); } } dsym_section_list->Finalize(); // Now that we're done adding sections, finalize to build fast-lookup caches } } void SymbolVendorMacOSX::Initialize() { PluginManager::RegisterPlugin (GetPluginNameStatic(), GetPluginDescriptionStatic(), CreateInstance); } void SymbolVendorMacOSX::Terminate() { PluginManager::UnregisterPlugin (CreateInstance); } const char * SymbolVendorMacOSX::GetPluginNameStatic() { return "symbol-vendor.macosx"; } const char * SymbolVendorMacOSX::GetPluginDescriptionStatic() { return "Symbol vendor for MacOSX that looks for dSYM files that match executables."; } //---------------------------------------------------------------------- // CreateInstance // // Platforms can register a callback to use when creating symbol // vendors to allow for complex debug information file setups, and to // also allow for finding separate debug information files. //---------------------------------------------------------------------- SymbolVendor* SymbolVendorMacOSX::CreateInstance (const lldb::ModuleSP &module_sp) { if (!module_sp) return NULL; Timer scoped_timer (__PRETTY_FUNCTION__, "SymbolVendorMacOSX::CreateInstance (module = %s/%s)", module_sp->GetFileSpec().GetDirectory().AsCString(), module_sp->GetFileSpec().GetFilename().AsCString()); SymbolVendorMacOSX* symbol_vendor = new SymbolVendorMacOSX(module_sp); if (symbol_vendor) { char path[PATH_MAX]; path[0] = '\0'; // Try and locate the dSYM file on Mac OS X ObjectFile * obj_file = module_sp->GetObjectFile(); if (obj_file) { Timer scoped_timer2 ("SymbolVendorMacOSX::CreateInstance () locate dSYM", "SymbolVendorMacOSX::CreateInstance (module = %s/%s) locate dSYM", module_sp->GetFileSpec().GetDirectory().AsCString(), module_sp->GetFileSpec().GetFilename().AsCString()); // First check to see if the module has a symbol file in mind already. // If it does, then we MUST use that. FileSpec dsym_fspec (module_sp->GetSymbolFileFileSpec()); ObjectFileSP dsym_objfile_sp; if (!dsym_fspec) { // No symbol file was specified in the module, lets try and find // one ourselves. const FileSpec &file_spec = obj_file->GetFileSpec(); if (file_spec) { ModuleSpec module_spec(file_spec, module_sp->GetArchitecture()); module_spec.GetUUID() = module_sp->GetUUID(); dsym_fspec = Symbols::LocateExecutableSymbolFile (module_spec); if (module_spec.GetSourceMappingList().GetSize()) { module_sp->GetSourceMappingList().Append (module_spec.GetSourceMappingList (), true); } } } if (dsym_fspec) { DataBufferSP dsym_file_data_sp; dsym_objfile_sp = ObjectFile::FindPlugin(module_sp, &dsym_fspec, 0, dsym_fspec.GetByteSize(), dsym_file_data_sp); if (UUIDsMatch(module_sp.get(), dsym_objfile_sp.get())) { char dsym_path[PATH_MAX]; if (module_sp->GetSourceMappingList().IsEmpty() && dsym_fspec.GetPath(dsym_path, sizeof(dsym_path))) { lldb_private::UUID dsym_uuid; if (dsym_objfile_sp->GetUUID(&dsym_uuid)) { char uuid_cstr_buf[64]; const char *uuid_cstr = dsym_uuid.GetAsCString (uuid_cstr_buf, sizeof(uuid_cstr_buf)); if (uuid_cstr) { char *resources = strstr (dsym_path, "/Contents/Resources/"); if (resources) { char dsym_uuid_plist_path[PATH_MAX]; resources[strlen("/Contents/Resources/")] = '\0'; snprintf(dsym_uuid_plist_path, sizeof(dsym_uuid_plist_path), "%s%s.plist", dsym_path, uuid_cstr); FileSpec dsym_uuid_plist_spec(dsym_uuid_plist_path, false); if (dsym_uuid_plist_spec.Exists()) { xmlDoc *doc = ::xmlReadFile (dsym_uuid_plist_path, NULL, 0); if (doc) { char DBGBuildSourcePath[PATH_MAX]; char DBGSourcePath[PATH_MAX]; DBGBuildSourcePath[0] = '\0'; DBGSourcePath[0] = '\0'; for (xmlNode *node = doc->children; node; node = node ? node->next : NULL) { if (node->type == XML_ELEMENT_NODE) { if (node->name && strcmp((const char*)node->name, "plist") == 0) { xmlNode *dict_node = node->children; while (dict_node && dict_node->type != XML_ELEMENT_NODE) dict_node = dict_node->next; if (dict_node && dict_node->name && strcmp((const char *)dict_node->name, "dict") == 0) { for (xmlNode *key_node = dict_node->children; key_node; key_node = key_node->next) { if (key_node && key_node->type == XML_ELEMENT_NODE && key_node->name) { if (strcmp((const char *)key_node->name, "key") == 0) { const char *key_name = (const char *)::xmlNodeGetContent(key_node); if (strcmp(key_name, "DBGBuildSourcePath") == 0) { xmlNode *value_node = key_node->next; while (value_node && value_node->type != XML_ELEMENT_NODE) value_node = value_node->next; if (value_node && value_node->name) { if (strcmp((const char *)value_node->name, "string") == 0) { const char *node_content = (const char *)::xmlNodeGetContent(value_node); if (node_content) { strncpy(DBGBuildSourcePath, node_content, sizeof(DBGBuildSourcePath)); } } key_node = value_node; } } else if (strcmp(key_name, "DBGSourcePath") == 0) { xmlNode *value_node = key_node->next; while (value_node && value_node->type != XML_ELEMENT_NODE) value_node = value_node->next; if (value_node && value_node->name) { if (strcmp((const char *)value_node->name, "string") == 0) { const char *node_content = (const char *)::xmlNodeGetContent(value_node); if (node_content) { FileSpec resolved_source_path(node_content, true); resolved_source_path.GetPath(DBGSourcePath, sizeof(DBGSourcePath)); } } key_node = value_node; } } } } } } } } } ::xmlFreeDoc (doc); if (DBGBuildSourcePath[0] && DBGSourcePath[0]) { module_sp->GetSourceMappingList().Append (ConstString(DBGBuildSourcePath), ConstString(DBGSourcePath), true); } } } } } } } ReplaceDSYMSectionsWithExecutableSections (obj_file, dsym_objfile_sp.get()); symbol_vendor->AddSymbolFileRepresentation(dsym_objfile_sp); return symbol_vendor; } } // Just create our symbol vendor using the current objfile as this is either // an executable with no dSYM (that we could locate), an executable with // a dSYM that has a UUID that doesn't match. symbol_vendor->AddSymbolFileRepresentation(obj_file->shared_from_this()); } } return symbol_vendor; } //------------------------------------------------------------------ // PluginInterface protocol //------------------------------------------------------------------ const char * SymbolVendorMacOSX::GetPluginName() { return "SymbolVendorMacOSX"; } const char * SymbolVendorMacOSX::GetShortPluginName() { return GetPluginNameStatic(); } uint32_t SymbolVendorMacOSX::GetPluginVersion() { return 1; } <commit_msg>Fix wrong logic with respect to warning messages.<commit_after>//===-- SymbolVendorMacOSX.cpp ----------------------------------*- C++ -*-===// // // The LLVM Compiler Infrastructure // // This file is distributed under the University of Illinois Open Source // License. See LICENSE.TXT for details. // //===----------------------------------------------------------------------===// #include "SymbolVendorMacOSX.h" #include <libxml/parser.h> #include <libxml/tree.h> #include <string.h> #include <AvailabilityMacros.h> #include "lldb/Core/Module.h" #include "lldb/Core/PluginManager.h" #include "lldb/Core/Section.h" #include "lldb/Core/StreamString.h" #include "lldb/Core/Timer.h" #include "lldb/Host/Host.h" #include "lldb/Host/Symbols.h" #include "lldb/Symbol/ObjectFile.h" using namespace lldb; using namespace lldb_private; //---------------------------------------------------------------------- // SymbolVendorMacOSX constructor //---------------------------------------------------------------------- SymbolVendorMacOSX::SymbolVendorMacOSX(const lldb::ModuleSP &module_sp) : SymbolVendor (module_sp) { } //---------------------------------------------------------------------- // Destructor //---------------------------------------------------------------------- SymbolVendorMacOSX::~SymbolVendorMacOSX() { } static bool UUIDsMatch(Module *module, ObjectFile *ofile) { if (module && ofile) { // Make sure the UUIDs match lldb_private::UUID dsym_uuid; if (!ofile->GetUUID(&dsym_uuid)) { Host::SystemLog (Host::eSystemLogWarning, "warning: failed to get the uuid for object file: '%s'\n", ofile->GetFileSpec().GetFilename().GetCString()); return false; } if (dsym_uuid == module->GetUUID()) return true; // Emit some warning messages since the UUIDs do not match! const FileSpec &m_file_spec = module->GetFileSpec(); const FileSpec &o_file_spec = ofile->GetFileSpec(); StreamString ss_m_path, ss_o_path; m_file_spec.Dump(&ss_m_path); o_file_spec.Dump(&ss_o_path); StreamString ss_m_uuid, ss_o_uuid; module->GetUUID().Dump(&ss_m_uuid); dsym_uuid.Dump(&ss_o_uuid); Host::SystemLog (Host::eSystemLogWarning, "warning: UUID mismatch detected between module '%s' (%s) and:\n\t'%s' (%s)\n", ss_m_path.GetData(), ss_m_uuid.GetData(), ss_o_path.GetData(), ss_o_uuid.GetData()); } return false; } static void ReplaceDSYMSectionsWithExecutableSections (ObjectFile *exec_objfile, ObjectFile *dsym_objfile) { // We need both the executable and the dSYM to live off of the // same section lists. So we take all of the sections from the // executable, and replace them in the dSYM. This allows section // offset addresses that come from the dSYM to automatically // get updated as images (shared libraries) get loaded and // unloaded. SectionList *exec_section_list = exec_objfile->GetSectionList(); SectionList *dsym_section_list = dsym_objfile->GetSectionList(); if (exec_section_list && dsym_section_list) { const uint32_t num_exec_sections = dsym_section_list->GetSize(); uint32_t exec_sect_idx; for (exec_sect_idx = 0; exec_sect_idx < num_exec_sections; ++exec_sect_idx) { SectionSP exec_sect_sp(exec_section_list->GetSectionAtIndex(exec_sect_idx)); if (exec_sect_sp.get()) { // Try and replace any sections that exist in both the executable // and in the dSYM with those from the executable. If we fail to // replace the one in the dSYM, then add the executable section to // the dSYM. if (dsym_section_list->ReplaceSection(exec_sect_sp->GetID(), exec_sect_sp, 0) == false) dsym_section_list->AddSection(exec_sect_sp); } } dsym_section_list->Finalize(); // Now that we're done adding sections, finalize to build fast-lookup caches } } void SymbolVendorMacOSX::Initialize() { PluginManager::RegisterPlugin (GetPluginNameStatic(), GetPluginDescriptionStatic(), CreateInstance); } void SymbolVendorMacOSX::Terminate() { PluginManager::UnregisterPlugin (CreateInstance); } const char * SymbolVendorMacOSX::GetPluginNameStatic() { return "symbol-vendor.macosx"; } const char * SymbolVendorMacOSX::GetPluginDescriptionStatic() { return "Symbol vendor for MacOSX that looks for dSYM files that match executables."; } //---------------------------------------------------------------------- // CreateInstance // // Platforms can register a callback to use when creating symbol // vendors to allow for complex debug information file setups, and to // also allow for finding separate debug information files. //---------------------------------------------------------------------- SymbolVendor* SymbolVendorMacOSX::CreateInstance (const lldb::ModuleSP &module_sp) { if (!module_sp) return NULL; Timer scoped_timer (__PRETTY_FUNCTION__, "SymbolVendorMacOSX::CreateInstance (module = %s/%s)", module_sp->GetFileSpec().GetDirectory().AsCString(), module_sp->GetFileSpec().GetFilename().AsCString()); SymbolVendorMacOSX* symbol_vendor = new SymbolVendorMacOSX(module_sp); if (symbol_vendor) { char path[PATH_MAX]; path[0] = '\0'; // Try and locate the dSYM file on Mac OS X ObjectFile * obj_file = module_sp->GetObjectFile(); if (obj_file) { Timer scoped_timer2 ("SymbolVendorMacOSX::CreateInstance () locate dSYM", "SymbolVendorMacOSX::CreateInstance (module = %s/%s) locate dSYM", module_sp->GetFileSpec().GetDirectory().AsCString(), module_sp->GetFileSpec().GetFilename().AsCString()); // First check to see if the module has a symbol file in mind already. // If it does, then we MUST use that. FileSpec dsym_fspec (module_sp->GetSymbolFileFileSpec()); ObjectFileSP dsym_objfile_sp; if (!dsym_fspec) { // No symbol file was specified in the module, lets try and find // one ourselves. const FileSpec &file_spec = obj_file->GetFileSpec(); if (file_spec) { ModuleSpec module_spec(file_spec, module_sp->GetArchitecture()); module_spec.GetUUID() = module_sp->GetUUID(); dsym_fspec = Symbols::LocateExecutableSymbolFile (module_spec); if (module_spec.GetSourceMappingList().GetSize()) { module_sp->GetSourceMappingList().Append (module_spec.GetSourceMappingList (), true); } } } if (dsym_fspec) { DataBufferSP dsym_file_data_sp; dsym_objfile_sp = ObjectFile::FindPlugin(module_sp, &dsym_fspec, 0, dsym_fspec.GetByteSize(), dsym_file_data_sp); if (UUIDsMatch(module_sp.get(), dsym_objfile_sp.get())) { char dsym_path[PATH_MAX]; if (module_sp->GetSourceMappingList().IsEmpty() && dsym_fspec.GetPath(dsym_path, sizeof(dsym_path))) { lldb_private::UUID dsym_uuid; if (dsym_objfile_sp->GetUUID(&dsym_uuid)) { char uuid_cstr_buf[64]; const char *uuid_cstr = dsym_uuid.GetAsCString (uuid_cstr_buf, sizeof(uuid_cstr_buf)); if (uuid_cstr) { char *resources = strstr (dsym_path, "/Contents/Resources/"); if (resources) { char dsym_uuid_plist_path[PATH_MAX]; resources[strlen("/Contents/Resources/")] = '\0'; snprintf(dsym_uuid_plist_path, sizeof(dsym_uuid_plist_path), "%s%s.plist", dsym_path, uuid_cstr); FileSpec dsym_uuid_plist_spec(dsym_uuid_plist_path, false); if (dsym_uuid_plist_spec.Exists()) { xmlDoc *doc = ::xmlReadFile (dsym_uuid_plist_path, NULL, 0); if (doc) { char DBGBuildSourcePath[PATH_MAX]; char DBGSourcePath[PATH_MAX]; DBGBuildSourcePath[0] = '\0'; DBGSourcePath[0] = '\0'; for (xmlNode *node = doc->children; node; node = node ? node->next : NULL) { if (node->type == XML_ELEMENT_NODE) { if (node->name && strcmp((const char*)node->name, "plist") == 0) { xmlNode *dict_node = node->children; while (dict_node && dict_node->type != XML_ELEMENT_NODE) dict_node = dict_node->next; if (dict_node && dict_node->name && strcmp((const char *)dict_node->name, "dict") == 0) { for (xmlNode *key_node = dict_node->children; key_node; key_node = key_node->next) { if (key_node && key_node->type == XML_ELEMENT_NODE && key_node->name) { if (strcmp((const char *)key_node->name, "key") == 0) { const char *key_name = (const char *)::xmlNodeGetContent(key_node); if (strcmp(key_name, "DBGBuildSourcePath") == 0) { xmlNode *value_node = key_node->next; while (value_node && value_node->type != XML_ELEMENT_NODE) value_node = value_node->next; if (value_node && value_node->name) { if (strcmp((const char *)value_node->name, "string") == 0) { const char *node_content = (const char *)::xmlNodeGetContent(value_node); if (node_content) { strncpy(DBGBuildSourcePath, node_content, sizeof(DBGBuildSourcePath)); } } key_node = value_node; } } else if (strcmp(key_name, "DBGSourcePath") == 0) { xmlNode *value_node = key_node->next; while (value_node && value_node->type != XML_ELEMENT_NODE) value_node = value_node->next; if (value_node && value_node->name) { if (strcmp((const char *)value_node->name, "string") == 0) { const char *node_content = (const char *)::xmlNodeGetContent(value_node); if (node_content) { FileSpec resolved_source_path(node_content, true); resolved_source_path.GetPath(DBGSourcePath, sizeof(DBGSourcePath)); } } key_node = value_node; } } } } } } } } } ::xmlFreeDoc (doc); if (DBGBuildSourcePath[0] && DBGSourcePath[0]) { module_sp->GetSourceMappingList().Append (ConstString(DBGBuildSourcePath), ConstString(DBGSourcePath), true); } } } } } } } ReplaceDSYMSectionsWithExecutableSections (obj_file, dsym_objfile_sp.get()); symbol_vendor->AddSymbolFileRepresentation(dsym_objfile_sp); return symbol_vendor; } } // Just create our symbol vendor using the current objfile as this is either // an executable with no dSYM (that we could locate), an executable with // a dSYM that has a UUID that doesn't match. symbol_vendor->AddSymbolFileRepresentation(obj_file->shared_from_this()); } } return symbol_vendor; } //------------------------------------------------------------------ // PluginInterface protocol //------------------------------------------------------------------ const char * SymbolVendorMacOSX::GetPluginName() { return "SymbolVendorMacOSX"; } const char * SymbolVendorMacOSX::GetShortPluginName() { return GetPluginNameStatic(); } uint32_t SymbolVendorMacOSX::GetPluginVersion() { return 1; } <|endoftext|>
<commit_before>#ifndef IG_CHIRP_SAMPLE_FORMAT_HPP #define IG_CHIRP_SAMPLE_FORMAT_HPP #include <chirp/exceptions.hpp> namespace chirp { /// /// /// enum class byte_order { big_endian, little_endian }; /// /// /// class sample_format { public: // Not default constructible sample_format() = delete; // Typedefs /// Integral type for counting channels (unsigned 8 bit integer) using channel_count = std::uint8_t; /// Integral type for counting bits (unsigned 8 bit integer) using bit_count = std::uint8_t; /// Integral type for byte sizes using byte_count = std::uint32_t; /// Construct an sample format with a maximum of eight bits per sample. /// /// @param bits_per_sample The number of bits that each sample /// consists of. /// @param channels The number of interleaved channels /// @pre bits_per_sample <= 8 sample_format( bit_count bits_per_sample, channel_count channels ) : _bits_per_sample( bits_per_sample ), _endianness( byte_order::little_endian ), _channels( channels ) { if( _bits_per_sample > 8 ) { throw byte_order_exception{}; } } /// Construct an sample format, with more than eight bits per sample. /// /// @param bits_per_sample The number of bits that each sample /// consists of. This value must be >8 /// @param endianness The byte order of each sample /// @param channels The number of interleaved channels /// @pre bits_per_sample > 8 sample_format( bit_count bits_per_sample, byte_order endianness, channel_count channels ) : _bits_per_sample( bits_per_sample ), _endianness( endianness ), _channels( channels ) { if( _bits_per_sample <= 8 ) { throw byte_order_exception{}; } } /// Retrieve the bits per sample of the sample format /// @returns The number of bits per individual sample bit_count bits_per_sample() const { return _bits_per_sample; } /// Retrieve the endianness of the sample format /// @returns The byte order of each individual sample /// @throws byte_order_exception is thrown if the format has samples /// that is less or equal to one byte /// size. Byte order does not apply /// unless the samples are of multiple /// bytes. /// @pre this.bits_per_sample() > 8 byte_order endianness() const { if( _bits_per_sample <=8 ) { throw byte_order_exception{}; } return _endianness; } /// Retrieve the number channels of the sample format /// @returns The number of interleaved channels channel_count channels() const { return _channels; } /// bool operator==( sample_format const& lhs ) const { return _bits_per_sample == lhs._bits_per_sample && _endianness == lhs._endianness && _channels == lhs._channels; } /// bool operator!=( sample_format const& lhs ) const { return !(*this == lhs); } /// byte_count bytes_per_frame() const { return (_bits_per_sample / 8) * _channels; } private: bit_count _bits_per_sample; ///< The number of bits per individual sample byte_order _endianness; ///< The byte order of each sample channel_count _channels; ///< The number of interleaved channels }; // Constants for common sample formats extern sample_format const eight_bits_mono; extern sample_format const eight_bits_stereo; extern sample_format const sixteen_bits_little_endian_mono; extern sample_format const sixteen_bits_big_endian_mono; extern sample_format const sixteen_bits_little_endian_stereo; extern sample_format const sixteen_bits_big_endian_stereo; } #endif // IG_CHIRP_SAMPLE_FORMAT_HPP<commit_msg>Avoid recalculating bytes per frame<commit_after>#ifndef IG_CHIRP_SAMPLE_FORMAT_HPP #define IG_CHIRP_SAMPLE_FORMAT_HPP #include <chirp/exceptions.hpp> namespace chirp { /// /// /// enum class byte_order { big_endian, little_endian }; /// /// /// class sample_format { public: // Not default constructible sample_format() = delete; // Typedefs /// Integral type for counting channels (unsigned 8 bit integer) using channel_count = std::uint8_t; /// Integral type for counting bits (unsigned 8 bit integer) using bit_count = std::uint8_t; /// Integral type for byte sizes using byte_count = std::uint32_t; /// Construct an sample format with a maximum of eight bits per sample. /// /// @param bits_per_sample The number of bits that each sample /// consists of. /// @param channels The number of interleaved channels /// @pre bits_per_sample <= 8 sample_format( bit_count bits_per_sample, channel_count channels ) : _bits_per_sample( bits_per_sample ), _endianness( byte_order::little_endian ), _channels( channels ), _bytes_per_frame( (_bits_per_sample / 8) * _channels ) { if( _bits_per_sample > 8 ) { throw byte_order_exception{}; } } /// Construct an sample format, with more than eight bits per sample. /// /// @param bits_per_sample The number of bits that each sample /// consists of. This value must be >8 /// @param endianness The byte order of each sample /// @param channels The number of interleaved channels /// @pre bits_per_sample > 8 sample_format( bit_count bits_per_sample, byte_order endianness, channel_count channels ) : _bits_per_sample( bits_per_sample ), _endianness( endianness ), _channels( channels ), _bytes_per_frame( (_bits_per_sample / 8) * _channels ) { if( _bits_per_sample <= 8 ) { throw byte_order_exception{}; } } /// Retrieve the bits per sample of the sample format /// @returns The number of bits per individual sample bit_count bits_per_sample() const { return _bits_per_sample; } /// Retrieve the endianness of the sample format /// @returns The byte order of each individual sample /// @throws byte_order_exception is thrown if the format has samples /// that is less or equal to one byte /// size. Byte order does not apply /// unless the samples are of multiple /// bytes. /// @pre this.bits_per_sample() > 8 byte_order endianness() const { if( _bits_per_sample <=8 ) { throw byte_order_exception{}; } return _endianness; } /// Retrieve the number channels of the sample format /// @returns The number of interleaved channels channel_count channels() const { return _channels; } /// bool operator==( sample_format const& lhs ) const { return _bits_per_sample == lhs._bits_per_sample && _endianness == lhs._endianness && _channels == lhs._channels; } /// bool operator!=( sample_format const& lhs ) const { return !(*this == lhs); } /// byte_count bytes_per_frame() const { return _bytes_per_frame; } private: bit_count _bits_per_sample; ///< The number of bits per individual sample byte_order _endianness; ///< The byte order of each sample channel_count _channels; ///< The number of interleaved channels byte_count _bytes_per_frame; ///< The number of bytes per frame }; // Constants for common sample formats extern sample_format const eight_bits_mono; extern sample_format const eight_bits_stereo; extern sample_format const sixteen_bits_little_endian_mono; extern sample_format const sixteen_bits_big_endian_mono; extern sample_format const sixteen_bits_little_endian_stereo; extern sample_format const sixteen_bits_big_endian_stereo; } #endif // IG_CHIRP_SAMPLE_FORMAT_HPP<|endoftext|>
<commit_before>// Copyright (c) 2009 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "chrome/browser/gtk/info_bubble_gtk.h" #include <gdk/gdkkeysyms.h> #include <gtk/gtk.h> #include "app/gfx/path.h" #include "app/l10n_util.h" #include "base/basictypes.h" #include "base/gfx/gtk_util.h" #include "base/gfx/rect.h" #include "base/logging.h" #include "chrome/browser/gtk/gtk_theme_provider.h" #include "chrome/common/gtk_util.h" #include "chrome/common/notification_service.h" namespace { // The height of the arrow, and the width will be about twice the height. const int kArrowSize = 5; // Number of pixels to the start of the arrow from the edge of the window. const int kArrowX = 13; // Number of pixels between the tip of the arrow and the region we're // pointing to. const int kArrowToContentPadding = -6; // We draw flat diagonal corners, each corner is an NxN square. const int kCornerSize = 3; // Margins around the content. const int kTopMargin = kArrowSize + kCornerSize + 6; const int kBottomMargin = kCornerSize + 6; const int kLeftMargin = kCornerSize + 6; const int kRightMargin = kCornerSize + 6; const GdkColor kBackgroundColor = GDK_COLOR_RGB(0xff, 0xff, 0xff); const GdkColor kFrameColor = GDK_COLOR_RGB(0x63, 0x63, 0x63); const gchar* kInfoBubbleToplevelKey = "__INFO_BUBBLE_TOPLEVEL__"; enum FrameType { FRAME_MASK, FRAME_STROKE, }; // Make the points for our polygon frame, either for fill (the mask), or for // when we stroke the border. NOTE: This seems a bit overcomplicated, but it // requires a bunch of careful fudging to get the pixels rasterized exactly // where we want them, the arrow to have a 1 pixel point, etc. // TODO(deanm): Windows draws with Skia and uses some PNG images for the // corners. This is a lot more work, but they get anti-aliasing. std::vector<GdkPoint> MakeFramePolygonPoints(int width, int height, FrameType type) { using gtk_util::MakeBidiGdkPoint; std::vector<GdkPoint> points; bool ltr = l10n_util::GetTextDirection() == l10n_util::LEFT_TO_RIGHT; // If we have a stroke, we have to offset some of our points by 1 pixel. // We have to inset by 1 pixel when we draw horizontal lines that are on the // bottom or when we draw vertical lines that are closer to the end (end is // right for ltr). int y_off = (type == FRAME_MASK) ? 0 : -1; // We use this one for LTR. int x_off_l = ltr ? y_off : 0; // We use this one for RTL. int x_off_r = !ltr ? -y_off : 0; // Top left corner. points.push_back(MakeBidiGdkPoint( x_off_r, kArrowSize + kCornerSize - 1, width, ltr)); points.push_back(MakeBidiGdkPoint( kCornerSize + x_off_r - 1, kArrowSize, width, ltr)); // The arrow. points.push_back(MakeBidiGdkPoint( kArrowX - kArrowSize + x_off_r, kArrowSize, width, ltr)); points.push_back(MakeBidiGdkPoint( kArrowX + x_off_r, 0, width, ltr)); points.push_back(MakeBidiGdkPoint( kArrowX + 1 + x_off_l, 0, width, ltr)); points.push_back(MakeBidiGdkPoint( kArrowX + kArrowSize + 1 + x_off_l, kArrowSize, width, ltr)); // Top right corner. points.push_back(MakeBidiGdkPoint( width - kCornerSize + 1 + x_off_l, kArrowSize, width, ltr)); points.push_back(MakeBidiGdkPoint( width + x_off_l, kArrowSize + kCornerSize - 1, width, ltr)); // Bottom right corner. points.push_back(MakeBidiGdkPoint( width + x_off_l, height - kCornerSize, width, ltr)); points.push_back(MakeBidiGdkPoint( width - kCornerSize + x_off_r, height + y_off, width, ltr)); // Bottom left corner. points.push_back(MakeBidiGdkPoint( kCornerSize + x_off_l, height + y_off, width, ltr)); points.push_back(MakeBidiGdkPoint( x_off_r, height - kCornerSize, width, ltr)); return points; } gboolean HandleExpose(GtkWidget* widget, GdkEventExpose* event, gpointer unused) { GdkDrawable* drawable = GDK_DRAWABLE(event->window); GdkGC* gc = gdk_gc_new(drawable); gdk_gc_set_rgb_fg_color(gc, &kFrameColor); // Stroke the frame border. std::vector<GdkPoint> points = MakeFramePolygonPoints( widget->allocation.width, widget->allocation.height, FRAME_STROKE); gdk_draw_polygon(drawable, gc, FALSE, &points[0], points.size()); g_object_unref(gc); return FALSE; // Propagate so our children paint, etc. } } // namespace // static InfoBubbleGtk* InfoBubbleGtk::Show(GtkWindow* transient_toplevel, const gfx::Rect& rect, GtkWidget* content, GtkThemeProvider* provider, InfoBubbleGtkDelegate* delegate) { InfoBubbleGtk* bubble = new InfoBubbleGtk(provider); bubble->Init(transient_toplevel, rect, content); bubble->set_delegate(delegate); return bubble; } InfoBubbleGtk::InfoBubbleGtk(GtkThemeProvider* provider) : delegate_(NULL), window_(NULL), theme_provider_(provider), accel_group_(gtk_accel_group_new()), screen_x_(0), screen_y_(0) { } InfoBubbleGtk::~InfoBubbleGtk() { g_object_unref(accel_group_); } void InfoBubbleGtk::Init(GtkWindow* transient_toplevel, const gfx::Rect& rect, GtkWidget* content) { DCHECK(!window_); rect_ = rect; window_ = gtk_window_new(GTK_WINDOW_TOPLEVEL); gtk_window_set_transient_for(GTK_WINDOW(window_), transient_toplevel); gtk_window_set_decorated(GTK_WINDOW(window_), FALSE); gtk_window_set_resizable(GTK_WINDOW(window_), FALSE); gtk_widget_set_app_paintable(window_, TRUE); // Have GTK double buffer around the expose signal. gtk_widget_set_double_buffered(window_, TRUE); // Make sure that our window can be focused. GTK_WIDGET_SET_FLAGS(window_, GTK_CAN_FOCUS); // Attach our accelerator group to the window with an escape accelerator. gtk_accel_group_connect(accel_group_, GDK_Escape, static_cast<GdkModifierType>(0), static_cast<GtkAccelFlags>(0), g_cclosure_new(G_CALLBACK(&HandleEscapeThunk), this, NULL)); gtk_window_add_accel_group(GTK_WINDOW(window_), accel_group_); GtkWidget* alignment = gtk_alignment_new(0.0, 0.0, 1.0, 1.0); gtk_alignment_set_padding(GTK_ALIGNMENT(alignment), kTopMargin, kBottomMargin, kLeftMargin, kRightMargin); gtk_container_add(GTK_CONTAINER(alignment), content); gtk_container_add(GTK_CONTAINER(window_), alignment); // GtkWidget only exposes the bitmap mask interface. Use GDK to more // efficently mask a GdkRegion. Make sure the window is realized during // HandleSizeAllocate, so the mask can be applied to the GdkWindow. gtk_widget_realize(window_); UpdateScreenX(); screen_y_ = rect.y() + rect.height() + kArrowToContentPadding; // For RTL, we will have to move the window again when it is allocated, but // this should be somewhat close to its final position. gtk_window_move(GTK_WINDOW(window_), screen_x_, screen_y_); GtkRequisition req; gtk_widget_size_request(window_, &req); gtk_widget_add_events(window_, GDK_BUTTON_PRESS_MASK | GDK_BUTTON_RELEASE_MASK); g_signal_connect(window_, "expose-event", G_CALLBACK(HandleExpose), NULL); g_signal_connect(window_, "size-allocate", G_CALLBACK(HandleSizeAllocateThunk), this); g_signal_connect(window_, "configure-event", G_CALLBACK(&HandleConfigureThunk), this); g_signal_connect(window_, "button-press-event", G_CALLBACK(&HandleButtonPressThunk), this); g_signal_connect(window_, "destroy", G_CALLBACK(&HandleDestroyThunk), this); // Set some data which helps the browser know whether it should appear // active. g_object_set_data(G_OBJECT(window_->window), kInfoBubbleToplevelKey, transient_toplevel); gtk_widget_show_all(window_); // Make sure our window has focus, is brought to the top, etc. gtk_window_present(GTK_WINDOW(window_)); // We add a GTK (application level) grab. This means we will get all // keyboard and mouse events for our application, even if they were delivered // on another window. This allows us to close when the user clicks outside // of the info bubble. We don't use an X grab since that would steal // keystrokes from your window manager, prevent you from interacting with // other applications, etc. // // Before adding the grab, we need to ensure that the bubble is added // to the window group of the top level window. This ensures that the // grab only affects the current browser window, and not all the open // browser windows in the application. gtk_window_group_add_window(gtk_window_get_group(transient_toplevel), GTK_WINDOW(window_)); gtk_grab_add(window_); registrar_.Add(this, NotificationType::BROWSER_THEME_CHANGED, NotificationService::AllSources()); theme_provider_->InitThemesFor(this); } void InfoBubbleGtk::UpdateScreenX() { if (l10n_util::GetTextDirection() == l10n_util::RIGHT_TO_LEFT) { screen_x_ = rect_.x() + (rect_.width() / 2) - window_->allocation.width + kArrowX; } else { screen_x_ = rect_.x() + (rect_.width() / 2) - kArrowX; } } void InfoBubbleGtk::Observe(NotificationType type, const NotificationSource& source, const NotificationDetails& details) { DCHECK_EQ(type.value, NotificationType::BROWSER_THEME_CHANGED); if (theme_provider_->UseGtkTheme()) { gtk_widget_modify_bg(window_, GTK_STATE_NORMAL, NULL); } else { // Set the background color, so we don't need to paint it manually. gtk_widget_modify_bg(window_, GTK_STATE_NORMAL, &kBackgroundColor); } } // static GtkWindow* InfoBubbleGtk::GetToplevelForInfoBubble( const GdkWindow* bubble_window) { if (!bubble_window) return NULL; return reinterpret_cast<GtkWindow*>( g_object_get_data(G_OBJECT(bubble_window), kInfoBubbleToplevelKey)); } void InfoBubbleGtk::Close(bool closed_by_escape) { // Notify the delegate that we're about to close. This gives the chance // to save state / etc from the hosted widget before it's destroyed. if (delegate_) delegate_->InfoBubbleClosing(this, closed_by_escape); DCHECK(window_); gtk_widget_destroy(window_); // |this| has been deleted, see HandleDestroy. } gboolean InfoBubbleGtk::HandleEscape() { Close(true); // Close by escape. return TRUE; } // When our size is initially allocated or changed, we need to recompute // and apply our shape mask region. void InfoBubbleGtk::HandleSizeAllocate() { if (l10n_util::GetTextDirection() == l10n_util::RIGHT_TO_LEFT) { UpdateScreenX(); gtk_window_move(GTK_WINDOW(window_), screen_x_, screen_y_); } DCHECK(window_->allocation.x == 0 && window_->allocation.y == 0); std::vector<GdkPoint> points = MakeFramePolygonPoints( window_->allocation.width, window_->allocation.height, FRAME_MASK); GdkRegion* mask_region = gdk_region_polygon(&points[0], points.size(), GDK_EVEN_ODD_RULE); gdk_window_shape_combine_region(window_->window, mask_region, 0, 0); gdk_region_destroy(mask_region); } gboolean InfoBubbleGtk::HandleConfigure(GdkEventConfigure* event) { // If the window is moved someplace besides where we want it, move it back. // TODO(deanm): In the end, I will probably remove this code and just let // the user move around the bubble like a normal dialog. I want to try // this for now and see if it causes problems when any window managers. if (event->x != screen_x_ || event->y != screen_y_) gtk_window_move(GTK_WINDOW(window_), screen_x_, screen_y_); return FALSE; } gboolean InfoBubbleGtk::HandleButtonPress(GdkEventButton* event) { // If we got a click in our own window, that's ok. if (event->window == window_->window) return FALSE; // Propagate. // Otherwise we had a click outside of our window, close ourself. Close(); return TRUE; } gboolean InfoBubbleGtk::HandleDestroy() { // We are self deleting, we have a destroy signal setup to catch when we // destroy the widget manually, or the window was closed via X. This will // delete the InfoBubbleGtk object. delete this; return FALSE; // Propagate. } <commit_msg>Use gtk_window_set_skip_taskbar_hint on info bubble popups so they don't show up in the task bar.<commit_after>// Copyright (c) 2009 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "chrome/browser/gtk/info_bubble_gtk.h" #include <gdk/gdkkeysyms.h> #include <gtk/gtk.h> #include "app/gfx/path.h" #include "app/l10n_util.h" #include "base/basictypes.h" #include "base/gfx/gtk_util.h" #include "base/gfx/rect.h" #include "base/logging.h" #include "chrome/browser/gtk/gtk_theme_provider.h" #include "chrome/common/gtk_util.h" #include "chrome/common/notification_service.h" namespace { // The height of the arrow, and the width will be about twice the height. const int kArrowSize = 5; // Number of pixels to the start of the arrow from the edge of the window. const int kArrowX = 13; // Number of pixels between the tip of the arrow and the region we're // pointing to. const int kArrowToContentPadding = -6; // We draw flat diagonal corners, each corner is an NxN square. const int kCornerSize = 3; // Margins around the content. const int kTopMargin = kArrowSize + kCornerSize + 6; const int kBottomMargin = kCornerSize + 6; const int kLeftMargin = kCornerSize + 6; const int kRightMargin = kCornerSize + 6; const GdkColor kBackgroundColor = GDK_COLOR_RGB(0xff, 0xff, 0xff); const GdkColor kFrameColor = GDK_COLOR_RGB(0x63, 0x63, 0x63); const gchar* kInfoBubbleToplevelKey = "__INFO_BUBBLE_TOPLEVEL__"; enum FrameType { FRAME_MASK, FRAME_STROKE, }; // Make the points for our polygon frame, either for fill (the mask), or for // when we stroke the border. NOTE: This seems a bit overcomplicated, but it // requires a bunch of careful fudging to get the pixels rasterized exactly // where we want them, the arrow to have a 1 pixel point, etc. // TODO(deanm): Windows draws with Skia and uses some PNG images for the // corners. This is a lot more work, but they get anti-aliasing. std::vector<GdkPoint> MakeFramePolygonPoints(int width, int height, FrameType type) { using gtk_util::MakeBidiGdkPoint; std::vector<GdkPoint> points; bool ltr = l10n_util::GetTextDirection() == l10n_util::LEFT_TO_RIGHT; // If we have a stroke, we have to offset some of our points by 1 pixel. // We have to inset by 1 pixel when we draw horizontal lines that are on the // bottom or when we draw vertical lines that are closer to the end (end is // right for ltr). int y_off = (type == FRAME_MASK) ? 0 : -1; // We use this one for LTR. int x_off_l = ltr ? y_off : 0; // We use this one for RTL. int x_off_r = !ltr ? -y_off : 0; // Top left corner. points.push_back(MakeBidiGdkPoint( x_off_r, kArrowSize + kCornerSize - 1, width, ltr)); points.push_back(MakeBidiGdkPoint( kCornerSize + x_off_r - 1, kArrowSize, width, ltr)); // The arrow. points.push_back(MakeBidiGdkPoint( kArrowX - kArrowSize + x_off_r, kArrowSize, width, ltr)); points.push_back(MakeBidiGdkPoint( kArrowX + x_off_r, 0, width, ltr)); points.push_back(MakeBidiGdkPoint( kArrowX + 1 + x_off_l, 0, width, ltr)); points.push_back(MakeBidiGdkPoint( kArrowX + kArrowSize + 1 + x_off_l, kArrowSize, width, ltr)); // Top right corner. points.push_back(MakeBidiGdkPoint( width - kCornerSize + 1 + x_off_l, kArrowSize, width, ltr)); points.push_back(MakeBidiGdkPoint( width + x_off_l, kArrowSize + kCornerSize - 1, width, ltr)); // Bottom right corner. points.push_back(MakeBidiGdkPoint( width + x_off_l, height - kCornerSize, width, ltr)); points.push_back(MakeBidiGdkPoint( width - kCornerSize + x_off_r, height + y_off, width, ltr)); // Bottom left corner. points.push_back(MakeBidiGdkPoint( kCornerSize + x_off_l, height + y_off, width, ltr)); points.push_back(MakeBidiGdkPoint( x_off_r, height - kCornerSize, width, ltr)); return points; } gboolean HandleExpose(GtkWidget* widget, GdkEventExpose* event, gpointer unused) { GdkDrawable* drawable = GDK_DRAWABLE(event->window); GdkGC* gc = gdk_gc_new(drawable); gdk_gc_set_rgb_fg_color(gc, &kFrameColor); // Stroke the frame border. std::vector<GdkPoint> points = MakeFramePolygonPoints( widget->allocation.width, widget->allocation.height, FRAME_STROKE); gdk_draw_polygon(drawable, gc, FALSE, &points[0], points.size()); g_object_unref(gc); return FALSE; // Propagate so our children paint, etc. } } // namespace // static InfoBubbleGtk* InfoBubbleGtk::Show(GtkWindow* transient_toplevel, const gfx::Rect& rect, GtkWidget* content, GtkThemeProvider* provider, InfoBubbleGtkDelegate* delegate) { InfoBubbleGtk* bubble = new InfoBubbleGtk(provider); bubble->Init(transient_toplevel, rect, content); bubble->set_delegate(delegate); return bubble; } InfoBubbleGtk::InfoBubbleGtk(GtkThemeProvider* provider) : delegate_(NULL), window_(NULL), theme_provider_(provider), accel_group_(gtk_accel_group_new()), screen_x_(0), screen_y_(0) { } InfoBubbleGtk::~InfoBubbleGtk() { g_object_unref(accel_group_); } void InfoBubbleGtk::Init(GtkWindow* transient_toplevel, const gfx::Rect& rect, GtkWidget* content) { DCHECK(!window_); rect_ = rect; window_ = gtk_window_new(GTK_WINDOW_TOPLEVEL); gtk_window_set_transient_for(GTK_WINDOW(window_), transient_toplevel); gtk_window_set_skip_taskbar_hint(GTK_WINDOW(window_), TRUE); gtk_window_set_decorated(GTK_WINDOW(window_), FALSE); gtk_window_set_resizable(GTK_WINDOW(window_), FALSE); gtk_widget_set_app_paintable(window_, TRUE); // Have GTK double buffer around the expose signal. gtk_widget_set_double_buffered(window_, TRUE); // Make sure that our window can be focused. GTK_WIDGET_SET_FLAGS(window_, GTK_CAN_FOCUS); // Attach our accelerator group to the window with an escape accelerator. gtk_accel_group_connect(accel_group_, GDK_Escape, static_cast<GdkModifierType>(0), static_cast<GtkAccelFlags>(0), g_cclosure_new(G_CALLBACK(&HandleEscapeThunk), this, NULL)); gtk_window_add_accel_group(GTK_WINDOW(window_), accel_group_); GtkWidget* alignment = gtk_alignment_new(0.0, 0.0, 1.0, 1.0); gtk_alignment_set_padding(GTK_ALIGNMENT(alignment), kTopMargin, kBottomMargin, kLeftMargin, kRightMargin); gtk_container_add(GTK_CONTAINER(alignment), content); gtk_container_add(GTK_CONTAINER(window_), alignment); // GtkWidget only exposes the bitmap mask interface. Use GDK to more // efficently mask a GdkRegion. Make sure the window is realized during // HandleSizeAllocate, so the mask can be applied to the GdkWindow. gtk_widget_realize(window_); UpdateScreenX(); screen_y_ = rect.y() + rect.height() + kArrowToContentPadding; // For RTL, we will have to move the window again when it is allocated, but // this should be somewhat close to its final position. gtk_window_move(GTK_WINDOW(window_), screen_x_, screen_y_); GtkRequisition req; gtk_widget_size_request(window_, &req); gtk_widget_add_events(window_, GDK_BUTTON_PRESS_MASK | GDK_BUTTON_RELEASE_MASK); g_signal_connect(window_, "expose-event", G_CALLBACK(HandleExpose), NULL); g_signal_connect(window_, "size-allocate", G_CALLBACK(HandleSizeAllocateThunk), this); g_signal_connect(window_, "configure-event", G_CALLBACK(&HandleConfigureThunk), this); g_signal_connect(window_, "button-press-event", G_CALLBACK(&HandleButtonPressThunk), this); g_signal_connect(window_, "destroy", G_CALLBACK(&HandleDestroyThunk), this); // Set some data which helps the browser know whether it should appear // active. g_object_set_data(G_OBJECT(window_->window), kInfoBubbleToplevelKey, transient_toplevel); gtk_widget_show_all(window_); // Make sure our window has focus, is brought to the top, etc. gtk_window_present(GTK_WINDOW(window_)); // We add a GTK (application level) grab. This means we will get all // keyboard and mouse events for our application, even if they were delivered // on another window. This allows us to close when the user clicks outside // of the info bubble. We don't use an X grab since that would steal // keystrokes from your window manager, prevent you from interacting with // other applications, etc. // // Before adding the grab, we need to ensure that the bubble is added // to the window group of the top level window. This ensures that the // grab only affects the current browser window, and not all the open // browser windows in the application. gtk_window_group_add_window(gtk_window_get_group(transient_toplevel), GTK_WINDOW(window_)); gtk_grab_add(window_); registrar_.Add(this, NotificationType::BROWSER_THEME_CHANGED, NotificationService::AllSources()); theme_provider_->InitThemesFor(this); } void InfoBubbleGtk::UpdateScreenX() { if (l10n_util::GetTextDirection() == l10n_util::RIGHT_TO_LEFT) { screen_x_ = rect_.x() + (rect_.width() / 2) - window_->allocation.width + kArrowX; } else { screen_x_ = rect_.x() + (rect_.width() / 2) - kArrowX; } } void InfoBubbleGtk::Observe(NotificationType type, const NotificationSource& source, const NotificationDetails& details) { DCHECK_EQ(type.value, NotificationType::BROWSER_THEME_CHANGED); if (theme_provider_->UseGtkTheme()) { gtk_widget_modify_bg(window_, GTK_STATE_NORMAL, NULL); } else { // Set the background color, so we don't need to paint it manually. gtk_widget_modify_bg(window_, GTK_STATE_NORMAL, &kBackgroundColor); } } // static GtkWindow* InfoBubbleGtk::GetToplevelForInfoBubble( const GdkWindow* bubble_window) { if (!bubble_window) return NULL; return reinterpret_cast<GtkWindow*>( g_object_get_data(G_OBJECT(bubble_window), kInfoBubbleToplevelKey)); } void InfoBubbleGtk::Close(bool closed_by_escape) { // Notify the delegate that we're about to close. This gives the chance // to save state / etc from the hosted widget before it's destroyed. if (delegate_) delegate_->InfoBubbleClosing(this, closed_by_escape); DCHECK(window_); gtk_widget_destroy(window_); // |this| has been deleted, see HandleDestroy. } gboolean InfoBubbleGtk::HandleEscape() { Close(true); // Close by escape. return TRUE; } // When our size is initially allocated or changed, we need to recompute // and apply our shape mask region. void InfoBubbleGtk::HandleSizeAllocate() { if (l10n_util::GetTextDirection() == l10n_util::RIGHT_TO_LEFT) { UpdateScreenX(); gtk_window_move(GTK_WINDOW(window_), screen_x_, screen_y_); } DCHECK(window_->allocation.x == 0 && window_->allocation.y == 0); std::vector<GdkPoint> points = MakeFramePolygonPoints( window_->allocation.width, window_->allocation.height, FRAME_MASK); GdkRegion* mask_region = gdk_region_polygon(&points[0], points.size(), GDK_EVEN_ODD_RULE); gdk_window_shape_combine_region(window_->window, mask_region, 0, 0); gdk_region_destroy(mask_region); } gboolean InfoBubbleGtk::HandleConfigure(GdkEventConfigure* event) { // If the window is moved someplace besides where we want it, move it back. // TODO(deanm): In the end, I will probably remove this code and just let // the user move around the bubble like a normal dialog. I want to try // this for now and see if it causes problems when any window managers. if (event->x != screen_x_ || event->y != screen_y_) gtk_window_move(GTK_WINDOW(window_), screen_x_, screen_y_); return FALSE; } gboolean InfoBubbleGtk::HandleButtonPress(GdkEventButton* event) { // If we got a click in our own window, that's ok. if (event->window == window_->window) return FALSE; // Propagate. // Otherwise we had a click outside of our window, close ourself. Close(); return TRUE; } gboolean InfoBubbleGtk::HandleDestroy() { // We are self deleting, we have a destroy signal setup to catch when we // destroy the widget manually, or the window was closed via X. This will // delete the InfoBubbleGtk object. delete this; return FALSE; // Propagate. } <|endoftext|>
<commit_before><commit_msg>If a sync message can't be routed, respond immediately with an error. This will allow us to process alerts correctly if they happen after the tab has been closed in the browser process.<commit_after><|endoftext|>
<commit_before> #include <stdio.h> #include <iostream> #include <thread> #include <mutex> #include <atomic> #include <queue> #include <vector> #include <algorithm> #include <sstream> //#include <boost/date_time/gregorian/gregorian.hpp> #include <boost/date_time/posix_time/posix_time.hpp> #include <boost/format.hpp> #include <boost/filesystem.hpp> #include <fstream> #include "stringTool.h" #include "writeHddThread.h" #include "json.hpp" #define DAQmxErrChk(functionCall) { if( DAQmxFailed(error=(functionCall)) ) { goto Error; } //ParamFilter using Filter = std::vector<std::string>; //Default parameters //Task parameters int32 error = 0; TaskHandle taskHandle = 0; char errBuff[2048] = { '\0' }; int32 i; //Channel parameters //char chan[] = "Dev1/ai0"; std::string channel = "Dev1/ai0"; float64 min = -1.0; float64 max = 6.0; //Timing parameters //char source[] = "OnboardClock"; std::string source = "OnboardClock"; int32 samplesPerChan = 80000; float64 sampleRate = 80000.0; // Data read parameters int32 bufferSize = 80814; //float64 *data1; //float64 *data2; //float64 *(data[2]); int32 pointsToRead = -1; float64 timeout = 10.0; //sec // ReadTime std::atomic<int32> readTime;//sec,-1 for infinity std::atomic<int32> nowReadTime; //SaveConfig::Config *config; const std::string configFileName = "parameter.conf"; std::string savePath = "."; //Mutex //std::mutex writeFileMutex; //std::mutex parameterMutex; //std::mutex readDataMutex[2]; //CheckOnOff double_t &checkA = WriteHddThread::checkA; double_t &checkB = WriteHddThread::checkB; //Flags std::atomic<int> readStatus; const int HOLD = 0; const int DO = 1; const int EXIT = -1; bool use_TCP = false; //ip config std::string ip_host = "127.0.0.1"; //Tcp parameters uint16_t tcpPort = 23333; std::future<bool> readStartFlag; std::promise<bool> readStartFlag_writer; //std::atomic<bool> isReading; std::string saveMode = "BIT"; int output_local(std::string msg) { std::cout << boost::posix_time::to_iso_extended_string(boost::posix_time::second_clock::local_time()) << "\t" << msg << std::endl; std::cout.flush(); return 0; } int output_toClient(std::string msg) { TcpServer::TcpServer *server = tcpServer; if (server) { if (server->is_online(0)) server->send(msg); } return 0; } int output(std::string msg) { output_local(msg); output_toClient(msg); return 0; } //!Save the parameter in paramHelper to a config file nlohmann::json paramHelperToJson(ParamSet::ParamHelper &ph) { nlohmann::json json; for (auto item : ph.bindlist()) { switch (item.second.second) { case ParamSet::ParamHelper::INTEGER: json[item.first] = *((int*)item.second.first); break; case ParamSet::ParamHelper::TEXT: json[item.first] = *((std::string*)item.second.first); break; case ParamSet::ParamHelper::FLOAT64: json[item.first] = *((double*)item.second.first); break; } } return json; } int saveConfig() { configJson = paramHelperToJson(*paramHelper); std::ofstream ofs(configFileName); if (ofs.is_open()) { ofs << configJson.dump(4); output_local("Save config succeed!"); } else { output_local((boost::format("Can't open file: %s") % configFileName).str()); } ofs.close(); return 0; } //!Load parameters from config file to paramHelper int loadConfig() { std::ifstream ifs(configFileName); if (ifs.is_open()) { //file exists try { output_local("Read Configuation file succeed!"); configJson.clear(); ifs >> configJson; ParamSet::VariableBind bind = paramHelper->bindlist(); for (auto &item : configJson.items()) { if (bind.find(item.key()) == bind.cend()) { output_local((boost::format("Error occured: key \"%s\" is not valid") % item.key()).str()); continue; } ParamSet::VariableBindItem binditem = bind[item.key()]; switch (binditem.second) { case ParamSet::ParamHelper::INTEGER: *((int*)binditem.first) = configJson[item.key()].get<int>(); break; case ParamSet::ParamHelper::TEXT: *((std::string*)binditem.first) = configJson[item.key()].get<std::string>(); break; case ParamSet::ParamHelper::FLOAT64: *((double*)binditem.first) = configJson[item.key()].get<double>(); break; } } } catch(std::exception e) { output_local((boost::format("Error occured while reading config file:%s") % e.what()).str()); } } else { //file not exists saveConfig(); } ifs.close(); return 0; } int createDir(std::string dir) { boost::filesystem::path path(dir); if (boost::filesystem::exists(path)) { if (!boost::filesystem::is_directory(path)) { output((boost::format("%s is not a directory name!") % path.string()).str()); return 1; } return 0; } else { return boost::filesystem::create_directories(path) ? 0 : 1; } } int decode(std::string source, std::string target) { //using DataPoint = std::pair < int32, int32 >; //std::vector<DataPoint> result; std::ofstream ofs; std::ifstream ifs; //writeFileMutex.lock(); ifs.open(source, std::ios::binary); ofs.open(target); bool first = true; int32 position = 0; bool status; while (!ifs.eof()) { //header using Header = WriteHddThread::Header; Header header; ifs.read((char*)&header, sizeof(Header)); if (ifs.eof()) break; ofs << "#" << boost::posix_time::to_iso_extended_string(header.ptime) << std::endl; if (first) { ofs << position << "\t" << int32(header.first) << "\n"; status = !(header.first == 0); first = false; } else { if (status != !(header.first == 0)) { int8 value = status ? 1 : 0; ofs << position - 1 << "\t" << int32(value) << std::endl; ofs << position << "\t" << 1 - value << std::endl; status = !status; } } int32 *buffer = new int32[header.bodySize]; ifs.read((char*)buffer, sizeof(int32)*header.bodySize); int i; for (i = 0; i < header.bodySize - 1; i++) { position += buffer[i]; int8 value = status ? 1 : 0; ofs << position - 1 << "\t" << int32(value) << std::endl; ofs << position << "\t" << 1 - value << std::endl; status = !status; } position += buffer[i]; std::cout << "position:" << position << std::endl; delete buffer; } int8 value = status ? 1 : 0; position--; ofs << position << "\t" << int32(value) << std::endl; ifs.close(); ofs.close(); //writeFileMutex.unlock(); return 0; } int decode_raw(std::string source, std::string target) { std::ofstream ofs; std::ifstream ifs; ifs.open(source, std::ios::binary); ofs.open(target); int count = 0; double_t *buffer = new double_t[bufferSize]; while (!ifs.eof()) { ifs.read((char*)buffer, bufferSize * sizeof(double_t)); for (int i = 0; i < ifs.gcount() / sizeof(double_t); i++) { ofs << count << "\t" << buffer[i] << std::endl; count++; } } delete[] buffer; return 0; } int timeDiff(std::string source, std::string target) { //using DataPoint = std::pair < int32, int32 >; //std::vector<DataPoint> result; std::ofstream ofs; std::ifstream ifs; //writeFileMutex.lock(); ifs.open(source, std::ios::binary); ofs.open(target); bool first = true; int32 position = 0; bool status; boost::posix_time::ptime ptime; while (!ifs.eof()) { //header using Header = WriteHddThread::Header; Header header; ifs.read((char*)&header, sizeof(Header)); if (ifs.eof()) break; //ofs << "#" << boost::posix_time::to_iso_extended_string(header.ptime) << std::endl; if (first) { ptime = header.ptime; first = false; } else { ofs << (header.ptime - ptime).total_microseconds() / 1000000.0 << std::endl; ptime = header.ptime; } int32 *buffer = new int32[header.bodySize]; ifs.read((char*)buffer, sizeof(int32)*header.bodySize); int i; for (i = 0; i < header.bodySize - 1; i++) { position += buffer[i]; int8 value = status ? 1 : 0; //ofs << position - 1 << "\t" << int32(value) << std::endl; //ofs << position << "\t" << 1 - value << std::endl; status = !status; } position += buffer[i]; std::cout << "position:" << position << std::endl; delete buffer; } int8 value = status ? 1 : 0; position--; //ofs << position << "\t" << int32(value) << std::endl; ifs.close(); ofs.close(); //writeFileMutex.unlock(); return 0; } int main(int argc, char *argv[]) { if (argc == 1) { return 0; } std::string cmd = argv[1]; if (cmd == "-d") { /* if (argc == 4) { std::string source = argv[2]; std::string target = argv[3]; decode(source, target); return 0; } */ if (argc >= 3) { for (int i = 2; i < argc; i++) { std::string source = argv[i]; std::string target = source + ".out"; decode(source, target); } return 0; } } else if (cmd == "-dr") { if (argc >= 3) { for (int i = 2; i < argc; i++) { std::string source = argv[i]; std::string target = source + ".out"; decode_raw(source, target); } return 0; } } else if (cmd == "-dt") { if (argc >= 3) { for (int i = 2; i < argc; i++) { std::string source = argv[i]; std::string target = source + ".tdiff"; timeDiff(source, target); } return 0; } } std::cout << "Wrong use\n" << std::endl; return 0; } <commit_msg>fixing bug<commit_after> #include <stdio.h> #include <iostream> #include <thread> #include <mutex> #include <atomic> #include <queue> #include <vector> #include <algorithm> #include <sstream> //#include <boost/date_time/gregorian/gregorian.hpp> #include <boost/date_time/posix_time/posix_time.hpp> #include <boost/format.hpp> #include <boost/filesystem.hpp> #include <fstream> #include "stringTool.h" #include "writeHddThread.h" using int32 = int using float64 = double #define DAQmxErrChk(functionCall) { if( DAQmxFailed(error=(functionCall)) ) { goto Error; } //ParamFilter using Filter = std::vector<std::string>; //Default parameters //Task parameters int32 error = 0; TaskHandle taskHandle = 0; char errBuff[2048] = { '\0' }; int32 i; //Channel parameters //char chan[] = "Dev1/ai0"; std::string channel = "Dev1/ai0"; float64 min = -1.0; float64 max = 6.0; //Timing parameters //char source[] = "OnboardClock"; std::string source = "OnboardClock"; int32 samplesPerChan = 80000; float64 sampleRate = 80000.0; // Data read parameters int32 bufferSize = 80814; //float64 *data1; //float64 *data2; //float64 *(data[2]); int32 pointsToRead = -1; float64 timeout = 10.0; //sec // ReadTime std::atomic<int32> readTime;//sec,-1 for infinity std::atomic<int32> nowReadTime; //SaveConfig::Config *config; const std::string configFileName = "parameter.conf"; std::string savePath = "."; //Mutex //std::mutex writeFileMutex; //std::mutex parameterMutex; //std::mutex readDataMutex[2]; //CheckOnOff double_t &checkA = WriteHddThread::checkA; double_t &checkB = WriteHddThread::checkB; //Flags std::atomic<int> readStatus; const int HOLD = 0; const int DO = 1; const int EXIT = -1; bool use_TCP = false; //ip config std::string ip_host = "127.0.0.1"; //Tcp parameters uint16_t tcpPort = 23333; std::future<bool> readStartFlag; std::promise<bool> readStartFlag_writer; //std::atomic<bool> isReading; std::string saveMode = "BIT"; int output_local(std::string msg) { std::cout << boost::posix_time::to_iso_extended_string(boost::posix_time::second_clock::local_time()) << "\t" << msg << std::endl; std::cout.flush(); return 0; } int output_toClient(std::string msg) { TcpServer::TcpServer *server = tcpServer; if (server) { if (server->is_online(0)) server->send(msg); } return 0; } int output(std::string msg) { output_local(msg); output_toClient(msg); return 0; } //!Save the parameter in paramHelper to a config file nlohmann::json paramHelperToJson(ParamSet::ParamHelper &ph) { nlohmann::json json; for (auto item : ph.bindlist()) { switch (item.second.second) { case ParamSet::ParamHelper::INTEGER: json[item.first] = *((int*)item.second.first); break; case ParamSet::ParamHelper::TEXT: json[item.first] = *((std::string*)item.second.first); break; case ParamSet::ParamHelper::FLOAT64: json[item.first] = *((double*)item.second.first); break; } } return json; } int saveConfig() { configJson = paramHelperToJson(*paramHelper); std::ofstream ofs(configFileName); if (ofs.is_open()) { ofs << configJson.dump(4); output_local("Save config succeed!"); } else { output_local((boost::format("Can't open file: %s") % configFileName).str()); } ofs.close(); return 0; } //!Load parameters from config file to paramHelper int loadConfig() { std::ifstream ifs(configFileName); if (ifs.is_open()) { //file exists try { output_local("Read Configuation file succeed!"); configJson.clear(); ifs >> configJson; ParamSet::VariableBind bind = paramHelper->bindlist(); for (auto &item : configJson.items()) { if (bind.find(item.key()) == bind.cend()) { output_local((boost::format("Error occured: key \"%s\" is not valid") % item.key()).str()); continue; } ParamSet::VariableBindItem binditem = bind[item.key()]; switch (binditem.second) { case ParamSet::ParamHelper::INTEGER: *((int*)binditem.first) = configJson[item.key()].get<int>(); break; case ParamSet::ParamHelper::TEXT: *((std::string*)binditem.first) = configJson[item.key()].get<std::string>(); break; case ParamSet::ParamHelper::FLOAT64: *((double*)binditem.first) = configJson[item.key()].get<double>(); break; } } } catch(std::exception e) { output_local((boost::format("Error occured while reading config file:%s") % e.what()).str()); } } else { //file not exists saveConfig(); } ifs.close(); return 0; } int createDir(std::string dir) { boost::filesystem::path path(dir); if (boost::filesystem::exists(path)) { if (!boost::filesystem::is_directory(path)) { output((boost::format("%s is not a directory name!") % path.string()).str()); return 1; } return 0; } else { return boost::filesystem::create_directories(path) ? 0 : 1; } } int decode(std::string source, std::string target) { //using DataPoint = std::pair < int32, int32 >; //std::vector<DataPoint> result; std::ofstream ofs; std::ifstream ifs; //writeFileMutex.lock(); ifs.open(source, std::ios::binary); ofs.open(target); bool first = true; int32 position = 0; bool status; while (!ifs.eof()) { //header using Header = WriteHddThread::Header; Header header; ifs.read((char*)&header, sizeof(Header)); if (ifs.eof()) break; ofs << "#" << boost::posix_time::to_iso_extended_string(header.ptime) << std::endl; if (first) { ofs << position << "\t" << int32(header.first) << "\n"; status = !(header.first == 0); first = false; } else { if (status != !(header.first == 0)) { int8 value = status ? 1 : 0; ofs << position - 1 << "\t" << int32(value) << std::endl; ofs << position << "\t" << 1 - value << std::endl; status = !status; } } int32 *buffer = new int32[header.bodySize]; ifs.read((char*)buffer, sizeof(int32)*header.bodySize); int i; for (i = 0; i < header.bodySize - 1; i++) { position += buffer[i]; int8 value = status ? 1 : 0; ofs << position - 1 << "\t" << int32(value) << std::endl; ofs << position << "\t" << 1 - value << std::endl; status = !status; } position += buffer[i]; std::cout << "position:" << position << std::endl; delete buffer; } int8 value = status ? 1 : 0; position--; ofs << position << "\t" << int32(value) << std::endl; ifs.close(); ofs.close(); //writeFileMutex.unlock(); return 0; } int decode_raw(std::string source, std::string target) { std::ofstream ofs; std::ifstream ifs; ifs.open(source, std::ios::binary); ofs.open(target); int count = 0; double_t *buffer = new double_t[bufferSize]; while (!ifs.eof()) { ifs.read((char*)buffer, bufferSize * sizeof(double_t)); for (int i = 0; i < ifs.gcount() / sizeof(double_t); i++) { ofs << count << "\t" << buffer[i] << std::endl; count++; } } delete[] buffer; return 0; } int timeDiff(std::string source, std::string target) { //using DataPoint = std::pair < int32, int32 >; //std::vector<DataPoint> result; std::ofstream ofs; std::ifstream ifs; //writeFileMutex.lock(); ifs.open(source, std::ios::binary); ofs.open(target); bool first = true; int32 position = 0; bool status; boost::posix_time::ptime ptime; while (!ifs.eof()) { //header using Header = WriteHddThread::Header; Header header; ifs.read((char*)&header, sizeof(Header)); if (ifs.eof()) break; //ofs << "#" << boost::posix_time::to_iso_extended_string(header.ptime) << std::endl; if (first) { ptime = header.ptime; first = false; } else { ofs << (header.ptime - ptime).total_microseconds() / 1000000.0 << std::endl; ptime = header.ptime; } int32 *buffer = new int32[header.bodySize]; ifs.read((char*)buffer, sizeof(int32)*header.bodySize); int i; for (i = 0; i < header.bodySize - 1; i++) { position += buffer[i]; int8 value = status ? 1 : 0; //ofs << position - 1 << "\t" << int32(value) << std::endl; //ofs << position << "\t" << 1 - value << std::endl; status = !status; } position += buffer[i]; std::cout << "position:" << position << std::endl; delete buffer; } int8 value = status ? 1 : 0; position--; //ofs << position << "\t" << int32(value) << std::endl; ifs.close(); ofs.close(); //writeFileMutex.unlock(); return 0; } int main(int argc, char *argv[]) { if (argc == 1) { return 0; } std::string cmd = argv[1]; if (cmd == "-d") { /* if (argc == 4) { std::string source = argv[2]; std::string target = argv[3]; decode(source, target); return 0; } */ if (argc >= 3) { for (int i = 2; i < argc; i++) { std::string source = argv[i]; std::string target = source + ".out"; decode(source, target); } return 0; } } else if (cmd == "-dr") { if (argc >= 3) { for (int i = 2; i < argc; i++) { std::string source = argv[i]; std::string target = source + ".out"; decode_raw(source, target); } return 0; } } else if (cmd == "-dt") { if (argc >= 3) { for (int i = 2; i < argc; i++) { std::string source = argv[i]; std::string target = source + ".tdiff"; timeDiff(source, target); } return 0; } } std::cout << "Wrong use\n" << std::endl; return 0; } <|endoftext|>
<commit_before>/* * @(#)$Id$ * * Copyright (c) 2004 Intel Corporation. All rights reserved. * * This file is distributed under the terms in the attached INTEL-LICENSE file. * If you do not find these files, copies can be found by writing to: * Intel Research Berkeley, 2150 Shattuck Avenue, Suite 1300, * Berkeley, CA, 94704. Attention: Intel License Inquiry. * * DESCRIPTION: P2's concrete type system: String type. * */ #include <iostream> #include "val_str.h" #include "val_double.h" class OperStr : public opr::OperCompare<Val_Str> { virtual ValuePtr _plus (const ValuePtr& v1, const ValuePtr& v2) const { return Val_Str::mk( Val_Str::cast(v1) + Val_Str::cast(v2) ); }; }; const opr::Oper* Val_Str::oper_ = new OperStr(); // // Marshal a string // void Val_Str::xdr_marshal_subtype( XDR *x ) { const char *st = s.c_str(); long sl = s.length(); xdr_long(x, &sl); xdr_string(x, const_cast<char **>(&st), sl + 1); } /** The preallocated string buffer used for unmarshaling strings */ const int STATIC_STRING_BUFFER = 10000; ValuePtr Val_Str::xdr_unmarshal( XDR *x ) { long sl; xdr_long(x, &sl); // Now fetch the string itself static char stringBuffer[STATIC_STRING_BUFFER]; if (sl + 1 <= STATIC_STRING_BUFFER) { // We can use the static buffer xdr_string(x, (char**) &stringBuffer, sl + 1); stringBuffer[sl] = 0; // make sure it's null terminated string st(stringBuffer, sl); return mk(st); } else { // We can't use the static buffer. We must allocate a one-shot // buffer char * localBuffer = new char[sl + 1]; xdr_string(x, &localBuffer, sl); localBuffer[sl] = 0; string st(localBuffer, sl); delete localBuffer; return mk(st); } } int Val_Str::compareTo(ValuePtr other) const { if (other->typeCode() != Value::STR) { return false; } return s.compare(cast(other)); } // // Casting: we special-case doubles... // string Val_Str::cast(ValuePtr v) { return v->toString(); } /* * End of file */ <commit_msg>Fixed bug with char[] and char*<commit_after>/* * @(#)$Id$ * * Copyright (c) 2004 Intel Corporation. All rights reserved. * * This file is distributed under the terms in the attached INTEL-LICENSE file. * If you do not find these files, copies can be found by writing to: * Intel Research Berkeley, 2150 Shattuck Avenue, Suite 1300, * Berkeley, CA, 94704. Attention: Intel License Inquiry. * * DESCRIPTION: P2's concrete type system: String type. * */ #include <iostream> #include "val_str.h" #include "val_double.h" class OperStr : public opr::OperCompare<Val_Str> { virtual ValuePtr _plus (const ValuePtr& v1, const ValuePtr& v2) const { return Val_Str::mk( Val_Str::cast(v1) + Val_Str::cast(v2) ); }; }; const opr::Oper* Val_Str::oper_ = new OperStr(); // // Marshal a string // void Val_Str::xdr_marshal_subtype( XDR *x ) { const char *st = s.c_str(); long sl = s.length(); xdr_long(x, &sl); xdr_string(x, const_cast<char **>(&st), sl + 1); } ValuePtr Val_Str::xdr_unmarshal( XDR *x ) { long sl; xdr_long(x, &sl); // Now fetch the string itself static const int STATIC_STRING_BUFFER = 10000; if (sl + 1 <= STATIC_STRING_BUFFER) { // We can use the static buffer static char stringBuffer[STATIC_STRING_BUFFER]; static char* sb = &(stringBuffer[0]); xdr_string(x, &sb, sl + 1); sb[sl] = 0; // make sure it's null terminated string st(sb, sl); return mk(st); } else { // We can't use the static buffer. We must allocate a one-shot // buffer char * localBuffer = new char[sl + 1]; xdr_string(x, &localBuffer, sl); localBuffer[sl] = 0; string st(localBuffer, sl); delete localBuffer; return mk(st); } } int Val_Str::compareTo(ValuePtr other) const { if (other->typeCode() != Value::STR) { return false; } return s.compare(cast(other)); } // // Casting: we special-case doubles... // string Val_Str::cast(ValuePtr v) { return v->toString(); } /* * End of file */ <|endoftext|>
<commit_before>/* * Copyright (c) 2013 Per Johansson * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``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 AUTHOR 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 <string> #include <boost/asio.hpp> #include <signal.h> #include <sys/wait.h> #include "spawn.hh" #include "smart_fd.hh" #include "osx_system_idle.h" #define STEREO_LINE ":stereo" #define TV_LINE ":tv" using boost::asio::io_service; using boost::asio::posix::stream_descriptor; using boost::asio::ip::tcp; void reap(pid_t pid) { pid_t r; int status; do r = waitpid(pid, &status, 0); while (r == -1 && errno == EINTR); if (r == -1) throw std::system_error(errno, std::system_category(), "waitpid"); } smart_fd spawn_movactl(pid_t *pid = NULL) { smart_pipe iopipe; extern char **environ; static const char *const args[] = { "movactl", STEREO_LINE, "listen", "volume", "power", "audio_source", NULL}; spawn::file_actions actions; actions.add_stdout(iopipe.write); actions.addclose(iopipe.write); int err = posix_spawn(pid, "/usr/local/bin/movactl", actions, NULL, (char**)args, environ); if (err) throw std::system_error(err, std::system_category(), "posix_spawn"); return std::move(iopipe.read); } smart_fd spawn_psxstatus(pid_t *pid = NULL) { smart_pipe iopipe; extern char **environ; static const char *const args[] = { "psx-status", NULL }; spawn::file_actions actions; actions.add_stdout(iopipe.write); actions.addclose(iopipe.write); int err = posix_spawn(pid, "/usr/local/bin/psx-status", actions, NULL, (char**)args, environ); if (err) throw std::system_error(err, std::system_category(), "posix_spawn"); return std::move(iopipe.read); } void movactl_send(const std::vector<std::string> &args) { std::vector<const char *> argv; pid_t pid; std::cout << "--movactl"; argv.push_back("movactl"); argv.push_back("--"); for (auto &a : args) { std::cout << " " << a; argv.push_back(a.c_str()); } argv.push_back(NULL); std::cout << "\n"; int err = posix_spawn(&pid, "/usr/local/bin/movactl", NULL, NULL, (char**)&argv[0], NULL); if (err) throw std::system_error(err, std::system_category(), "posix_spawn"); reap(pid); } constexpr unsigned int fnv1a_hash(const char *str) { return *str ? (fnv1a_hash(str + 1) ^ *str) * 16777619U : 2166136261U; } std::string itos(int v) { std::ostringstream ss; ss << v; return ss.str(); } void power_on(const std::string &stereo, const std::string &tv) { time_t now = time(NULL); struct tm tm = {0}; localtime_r(&now, &tm); if (tm.tm_hour < 7) return; if (tm.tm_hour == 7 && tm.tm_min < 30) return; movactl_send({STEREO_LINE, "power", "on"}); movactl_send({TV_LINE, "power", "on"}); movactl_send({STEREO_LINE, "source", "select", stereo}); movactl_send({TV_LINE, "source", "select", tv}); } void switch_from(const std::string &from, const std::map<std::string, std::string> &values) { auto it = values.find("audio_source"); if (it == values.end()) { std::cerr << "switch_from(" << from << "): No audio source\n"; return; } if (it->second != from) { std::cerr << "switch_from(" << from << "): audio_source == " << it->second << "\n"; return; } it = values.find("playstation"); if (it != values.end() && it->second == "up") { movactl_send({STEREO_LINE, "source", "select", "vcr"}); movactl_send({TV_LINE, "source", "select", "hdmi1"}); return; } it = values.find("wii"); if (it != values.end() && it->second == "on") { movactl_send({STEREO_LINE, "source", "select", "dss"}); movactl_send({TV_LINE, "source", "select", "component"}); return; } it = values.find("tv"); if (it != values.end() && it->second == "on") { movactl_send({STEREO_LINE, "source", "select", "tv"}); movactl_send({TV_LINE, "source", "select", "hdmi1"}); return; } #ifdef IDLE struct timespec idle; if (IDLE(&idle) == 0 && idle.tv_sec <= 600) { movactl_send({STEREO_LINE, "source", "select", "dvd"}); movactl_send({TV_LINE, "source", "select", "hdmi1"}); return; } #endif movactl_send({STEREO_LINE, "power", "off"}); } void update(const std::string &line) { std::string stat, value; static std::map<std::string, std::string> values; std::cout << "update: " << line << "\n"; std::istringstream(line) >> stat >> value; if (value == "negotiating") return; auto elem = values.insert(make_pair(stat, value)); if (!elem.second && elem.first->second == value) { std::cerr << "Not updating " << elem.first->first << ", " << value << " == " << elem.first->second << "\n"; return; } elem.first->second = value; switch(fnv1a_hash(stat.c_str())) { case fnv1a_hash("volume"): movactl_send({TV_LINE, "volume", "value", itos(atoi(value.c_str()) + 72)}); break; case fnv1a_hash("power"): movactl_send({TV_LINE, "power", value}); break; case fnv1a_hash("audio_source"): switch(fnv1a_hash(value.c_str())) { case fnv1a_hash("tv"): movactl_send({STEREO_LINE, "volume", "value", "-37"}); break; case fnv1a_hash("dvd"): case fnv1a_hash("vcr1"): movactl_send({STEREO_LINE, "volume", "value", "-37"}); break; case fnv1a_hash("dss"): movactl_send({STEREO_LINE, "volume", "value", "-37"}); break; } break; case fnv1a_hash("playstation"): if (value == "up") power_on("vcr", "hdmi1"); else switch_from("vcr1", values); break; case fnv1a_hash("tv"): if (value == "on") power_on("tv", "hdmi1"); else switch_from("tv", values); break; case fnv1a_hash("wii"): if (value == "on") power_on("dss", "component"); else switch_from("dss", values); break; } } std::unique_ptr<boost::asio::deadline_timer> psxtimer; void update_playstation_timeout(const std::string &line, const boost::system::error_code &error) { if (error) { std::cerr << "update_playstation_timeout: skipping " << line << " (" << error << ")\n"; return; } update("playstation " + line); } void update_playstation(const std::string &line) { psxtimer->expires_from_now(boost::posix_time::seconds(3)); psxtimer->async_wait(std::bind(update_playstation_timeout, std::string(line), std::placeholders::_1)); } template <typename T> class input { public: T object; boost::asio::streambuf buffer; std::istream stream; bool active; const std::string ewhat; std::function<void(const std::string&)> update_fn; template <typename ...Args> input(std::string ewhat, std::function<void(const std::string&)> update_fn, Args &&...args) : object(args...), stream(&buffer), active(false), ewhat(ewhat), update_fn(update_fn) { } void activate() { if (!active) { boost::asio::async_read_until(object, buffer, '\n', std::bind(&input<T>::handle, this, std::placeholders::_1, std::placeholders::_2)); active = true; } } void handle(const boost::system::error_code &error, std::size_t bytes) { active = false; if (error) throw boost::system::system_error(error, ewhat); std::string line; while (std::getline(stream, line).good()) update_fn(line); stream.clear(); activate(); } }; void connect_tcp(io_service &io, tcp::socket &socket, const tcp::resolver::query &query) { tcp::resolver resolver(io); tcp::resolver::iterator iterator = resolver.resolve(query); tcp::resolver::iterator itend; boost::system::error_code ec; for ( ; iterator != itend ; iterator++) { if (!socket.connect(*iterator, ec)) break; } if (iterator == itend) throw boost::system::system_error(ec); } int main() { try { while (1) { pid_t movapid; smart_fd movafd = spawn_movactl(&movapid); io_service io; input<stream_descriptor> movainput("movactl", update, io, movafd); movafd.release(); pid_t psxpid; smart_fd psxfd = spawn_psxstatus(&psxpid); input<stream_descriptor> psxinput("playstation", update_playstation, io, psxfd); psxfd.release(); input<boost::asio::serial_port> wiitvinput("wii/tv", update, io, "/dev/ttyACM0"); wiitvinput.object.set_option(boost::asio::serial_port_base::baud_rate(9600)); psxtimer.reset(new boost::asio::deadline_timer(io)); try { while (1) { movainput.activate(); psxinput.activate(); wiitvinput.activate(); io.run(); io.reset(); } } catch (boost::system::system_error &e) { std::cerr << "err: " << e.what() << "\n"; } kill(movapid, SIGTERM); reap(movapid); kill(psxpid, SIGTERM); reap(psxpid); } } catch (std::exception &e) { std::cerr << "exception: " << e.what() << "\n"; } return 1; } <commit_msg>Add airplay (computer)<commit_after>/* * Copyright (c) 2013 Per Johansson * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``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 AUTHOR 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 <string> #include <boost/asio.hpp> #include <signal.h> #include <sys/wait.h> #include "spawn.hh" #include "smart_fd.hh" #include "osx_system_idle.h" #define STEREO_LINE ":stereo" #define TV_LINE ":tv" using boost::asio::io_service; using boost::asio::posix::stream_descriptor; using boost::asio::ip::tcp; void reap(pid_t pid) { pid_t r; int status; do r = waitpid(pid, &status, 0); while (r == -1 && errno == EINTR); if (r == -1) throw std::system_error(errno, std::system_category(), "waitpid"); } smart_fd spawn_movactl(pid_t *pid = NULL) { smart_pipe iopipe; extern char **environ; static const char *const args[] = { "movactl", STEREO_LINE, "listen", "volume", "power", "audio_source", NULL}; spawn::file_actions actions; actions.add_stdout(iopipe.write); actions.addclose(iopipe.write); int err = posix_spawn(pid, "/usr/local/bin/movactl", actions, NULL, (char**)args, environ); if (err) throw std::system_error(err, std::system_category(), "posix_spawn"); return std::move(iopipe.read); } smart_fd spawn_psxstatus(pid_t *pid = NULL) { smart_pipe iopipe; extern char **environ; static const char *const args[] = { "psx-status", NULL }; spawn::file_actions actions; actions.add_stdout(iopipe.write); actions.addclose(iopipe.write); int err = posix_spawn(pid, "/usr/local/bin/psx-status", actions, NULL, (char**)args, environ); if (err) throw std::system_error(err, std::system_category(), "posix_spawn"); return std::move(iopipe.read); } void movactl_send(const std::vector<std::string> &args) { std::vector<const char *> argv; pid_t pid; std::cout << "--movactl"; argv.push_back("movactl"); argv.push_back("--"); for (auto &a : args) { std::cout << " " << a; argv.push_back(a.c_str()); } argv.push_back(NULL); std::cout << "\n"; int err = posix_spawn(&pid, "/usr/local/bin/movactl", NULL, NULL, (char**)&argv[0], NULL); if (err) throw std::system_error(err, std::system_category(), "posix_spawn"); reap(pid); } constexpr unsigned int fnv1a_hash(const char *str) { return *str ? (fnv1a_hash(str + 1) ^ *str) * 16777619U : 2166136261U; } std::string itos(int v) { std::ostringstream ss; ss << v; return ss.str(); } void power_on(const std::string &stereo, const std::string &tv) { time_t now = time(NULL); struct tm tm = {0}; localtime_r(&now, &tm); if (tm.tm_hour < 7) return; if (tm.tm_hour == 7 && tm.tm_min < 30) return; movactl_send({STEREO_LINE, "power", "on"}); movactl_send({TV_LINE, "power", "on"}); movactl_send({STEREO_LINE, "source", "select", stereo}); movactl_send({TV_LINE, "source", "select", tv}); } void switch_from(const std::string &from, const std::map<std::string, std::string> &values) { auto it = values.find("audio_source"); if (it == values.end()) { std::cerr << "switch_from(" << from << "): No audio source\n"; return; } if (it->second != from) { std::cerr << "switch_from(" << from << "): audio_source == " << it->second << "\n"; return; } it = values.find("playstation"); if (it != values.end() && it->second == "up") { movactl_send({STEREO_LINE, "source", "select", "vcr"}); movactl_send({TV_LINE, "source", "select", "hdmi1"}); return; } it = values.find("wii"); if (it != values.end() && it->second == "on") { movactl_send({STEREO_LINE, "source", "select", "dss"}); movactl_send({TV_LINE, "source", "select", "component"}); return; } it = values.find("tv"); if (it != values.end() && it->second == "on") { movactl_send({STEREO_LINE, "source", "select", "tv"}); movactl_send({TV_LINE, "source", "select", "hdmi1"}); return; } #ifdef IDLE struct timespec idle; if (IDLE(&idle) == 0 && idle.tv_sec <= 600) { movactl_send({STEREO_LINE, "source", "select", "dvd"}); movactl_send({TV_LINE, "source", "select", "hdmi1"}); return; } #endif movactl_send({STEREO_LINE, "power", "off"}); } void update(const std::string &line) { std::string stat, value; static std::map<std::string, std::string> values; std::cout << "update: " << line << "\n"; std::istringstream(line) >> stat >> value; if (value == "negotiating") return; auto elem = values.insert(make_pair(stat, value)); if (!elem.second && elem.first->second == value) { std::cerr << "Not updating " << elem.first->first << ", " << value << " == " << elem.first->second << "\n"; return; } elem.first->second = value; switch(fnv1a_hash(stat.c_str())) { case fnv1a_hash("volume"): movactl_send({TV_LINE, "volume", "value", itos(atoi(value.c_str()) + 72)}); break; case fnv1a_hash("power"): movactl_send({TV_LINE, "power", value}); break; case fnv1a_hash("audio_source"): switch(fnv1a_hash(value.c_str())) { case fnv1a_hash("tv"): movactl_send({STEREO_LINE, "volume", "value", "-37"}); break; case fnv1a_hash("dvd"): case fnv1a_hash("vcr1"): movactl_send({STEREO_LINE, "volume", "value", "-37"}); break; case fnv1a_hash("dss"): movactl_send({STEREO_LINE, "volume", "value", "-37"}); break; } break; case fnv1a_hash("playstation"): if (value == "up") power_on("vcr", "hdmi1"); else switch_from("vcr1", values); break; case fnv1a_hash("tv"): if (value == "on") power_on("tv", "hdmi1"); else switch_from("tv", values); break; case fnv1a_hash("wii"): if (value == "on") power_on("dss", "component"); else switch_from("dss", values); break; case fnv1a_hash("airplay"): if (value == "on") power_on("dvd", "hdmi1"); else switch_from("dvd", values); break; } } std::unique_ptr<boost::asio::deadline_timer> psxtimer; void update_playstation_timeout(const std::string &line, const boost::system::error_code &error) { if (error) { std::cerr << "update_playstation_timeout: skipping " << line << " (" << error << ")\n"; return; } update("playstation " + line); } void update_playstation(const std::string &line) { psxtimer->expires_from_now(boost::posix_time::seconds(3)); psxtimer->async_wait(std::bind(update_playstation_timeout, std::string(line), std::placeholders::_1)); } template <typename T> class input { public: T object; boost::asio::streambuf buffer; std::istream stream; bool active; const std::string ewhat; std::function<void(const std::string&)> update_fn; template <typename ...Args> input(std::string ewhat, std::function<void(const std::string&)> update_fn, Args &&...args) : object(args...), stream(&buffer), active(false), ewhat(ewhat), update_fn(update_fn) { } void activate() { if (!active) { boost::asio::async_read_until(object, buffer, '\n', std::bind(&input<T>::handle, this, std::placeholders::_1, std::placeholders::_2)); active = true; } } void handle(const boost::system::error_code &error, std::size_t bytes) { active = false; if (error) throw boost::system::system_error(error, ewhat); std::string line; while (std::getline(stream, line).good()) update_fn(line); stream.clear(); activate(); } }; void connect_tcp(io_service &io, tcp::socket &socket, const tcp::resolver::query &query) { tcp::resolver resolver(io); tcp::resolver::iterator iterator = resolver.resolve(query); tcp::resolver::iterator itend; boost::system::error_code ec; for ( ; iterator != itend ; iterator++) { if (!socket.connect(*iterator, ec)) break; } if (iterator == itend) throw boost::system::system_error(ec); } int main() { tcp::resolver::query apquery("vardagsrum", "7120"); try { while (1) { pid_t movapid; smart_fd movafd = spawn_movactl(&movapid); io_service io; input<stream_descriptor> movainput("movactl", update, io, movafd); movafd.release(); pid_t psxpid; smart_fd psxfd = spawn_psxstatus(&psxpid); input<stream_descriptor> psxinput("playstation", update_playstation, io, psxfd); psxfd.release(); input<boost::asio::serial_port> wiitvinput("wii/tv", update, io, "/dev/ttyACM0"); wiitvinput.object.set_option(boost::asio::serial_port_base::baud_rate(9600)); input<tcp::socket> apinput("airplay", update, io); connect_tcp(io, apinput.object, apquery); apinput.object.set_option(boost::asio::socket_base::keep_alive(true)); psxtimer.reset(new boost::asio::deadline_timer(io)); try { while (1) { movainput.activate(); psxinput.activate(); wiitvinput.activate(); apinput.activate(); io.run(); io.reset(); } } catch (boost::system::system_error &e) { std::cerr << "err: " << e.what() << "\n"; } kill(movapid, SIGTERM); reap(movapid); kill(psxpid, SIGTERM); reap(psxpid); } } catch (std::exception &e) { std::cerr << "exception: " << e.what() << "\n"; } return 1; } <|endoftext|>
<commit_before>/** * \description This is the main for the new version of the mert algorithm developed during the 2nd MT marathon */ #include <limits> #include <unistd.h> #include <cstdlib> #include <iostream> #include <fstream> #include <cmath> #include <ctime> #include <getopt.h> #include "Data.h" #include "Point.h" #include "Scorer.h" #include "ScorerFactory.h" #include "ScoreData.h" #include "FeatureData.h" #include "Optimizer.h" #include "Types.h" #include "Timer.h" #include "Util.h" #include "../moses/src/ThreadPool.h" float min_interval = 1e-3; using namespace std; void usage(int ret) { cerr<<"usage: mert -d <dimensions> (mandatory )"<<endl; cerr<<"[-n] retry ntimes (default 1)"<<endl; cerr<<"[-m] number of random directions in powell (default 0)"<<endl; cerr<<"[-o] the indexes to optimize(default all)"<<endl; cerr<<"[-t] the optimizer(default powell)"<<endl; cerr<<"[-r] the random seed (defaults to system clock)"<<endl; cerr<<"[--sctype|-s] the scorer type (default BLEU)"<<endl; cerr<<"[--scconfig|-c] configuration string passed to scorer"<<endl; cerr<<"[--scfile|-S] comma separated list of scorer data files (default score.data)"<<endl; cerr<<"[--ffile|-F] comma separated list of feature data files (default feature.data)"<<endl; cerr<<"[--ifile|-i] the starting point data file (default init.opt)"<<endl; #ifdef WITH_THREADS cerr<<"[--threads|-T] use multiple threads (default 1)"<<endl; #endif cerr<<"[--shard-count] Split data into shards, optimize for each shard and average"<<endl; cerr<<"[--shard-size] Shard size as proportion of data. If 0, use non-overlapping shards"<<endl; cerr<<"[-v] verbose level"<<endl; cerr<<"[--help|-h] print this message and exit"<<endl; exit(ret); } static struct option long_options[] = { {"pdim", 1, 0, 'd'}, {"ntry",1,0,'n'}, {"nrandom",1,0,'m'}, {"rseed",required_argument,0,'r'}, {"optimize",1,0,'o'}, {"pro",required_argument,0,'p'}, {"type",1,0,'t'}, {"sctype",1,0,'s'}, {"scconfig",required_argument,0,'c'}, {"scfile",1,0,'S'}, {"ffile",1,0,'F'}, {"ifile",1,0,'i'}, #ifdef WITH_THREADS {"threads", required_argument,0,'T'}, #endif {"shard-count", required_argument, 0, 'a'}, {"shard-size", required_argument, 0, 'b'}, {"verbose",1,0,'v'}, {"help",no_argument,0,'h'}, {0, 0, 0, 0} }; int option_index; /** * Runs an optimisation, or a random restart. */ class OptimizationTask : public Moses::Task { public: OptimizationTask(Optimizer* optimizer, const Point& point) : m_optimizer(optimizer), m_point(point) {} ~OptimizationTask() {} void resetOptimizer() { if (m_optimizer) { delete m_optimizer; m_optimizer = NULL; } } bool DeleteAfterExecution() { return false; } void Run() { m_score = m_optimizer->Run(m_point); } statscore_t getScore() const { return m_score; } const Point& getPoint() const { return m_point; } private: // Do not allow the user to instanciate without arguments. OptimizationTask() {} Optimizer* m_optimizer; Point m_point; statscore_t m_score; }; int main (int argc, char **argv) { ResetUserTime(); /* Timer timer; timer.start("Starting..."); */ int c,pdim,i; pdim=-1; int ntry=1; int nrandom=0; int seed=0; bool hasSeed = false; #ifdef WITH_THREADS size_t threads=1; #endif float shard_size = 0; size_t shard_count = 0; string type("powell"); string scorertype("BLEU"); string scorerconfig(""); string scorerfile("statscore.data"); string featurefile("features.data"); string initfile("init.opt"); string tooptimizestr(""); vector<unsigned> tooptimize; vector<vector<parameter_t> > start_list; vector<parameter_t> min; vector<parameter_t> max; // NOTE: those mins and max are the bound for the starting points of the algorithm, not strict bound on the result! while ((c=getopt_long (argc, argv, "o:r:d:n:m:t:s:S:F:v:p:", long_options, &option_index)) != -1) { switch (c) { case 'o': tooptimizestr = string(optarg); break; case 'd': pdim = strtol(optarg, NULL, 10); break; case 'n': ntry=strtol(optarg, NULL, 10); break; case 'm': nrandom=strtol(optarg, NULL, 10); break; case 'r': seed=strtol(optarg, NULL, 10); hasSeed = true; break; case 't': type=string(optarg); break; case's': scorertype=string(optarg); break; case 'c': scorerconfig = string(optarg); break; case 'S': scorerfile=string(optarg); break; case 'F': featurefile=string(optarg); break; case 'i': initfile=string(optarg); break; case 'v': setverboselevel(strtol(optarg,NULL,10)); break; #ifdef WITH_THREADS case 'T': threads = strtol(optarg, NULL, 10); if (threads < 1) threads = 1; break; #endif case 'a': shard_count = strtof(optarg,NULL); break; case 'b': shard_size = strtof(optarg,NULL); break; case 'h': usage(0); break; default: usage(1); } } if (pdim < 0) usage(1); cerr << "shard_size = " << shard_size << " shard_count = " << shard_count << endl; if (shard_size && !shard_count) { cerr << "Error: shard-size provided without shard-count" << endl; exit(1); } if (shard_size > 1 || shard_size < 0) { cerr << "Error: shard-size should be between 0 and 1" << endl; exit(1); } if (hasSeed) { cerr << "Seeding random numbers with " << seed << endl; srandom(seed); } else { cerr << "Seeding random numbers with system clock " << endl; srandom(time(NULL)); } // read in starting points std::string onefile; while (!initfile.empty()) { getNextPound(initfile, onefile, ","); vector<parameter_t> start; ifstream opt(onefile.c_str()); if(opt.fail()) { cerr<<"could not open initfile: " << initfile << endl; exit(3); } start.resize(pdim);//to do:read from file int j; for( j=0; j<pdim&&!opt.fail(); j++) opt>>start[j]; if(j<pdim) { cerr<<initfile<<":Too few starting weights." << endl; exit(3); } start_list.push_back(start); // for the first time, also read in the min/max values for scores if (start_list.size() == 1) { min.resize(pdim); for( j=0; j<pdim&&!opt.fail(); j++) opt>>min[j]; if(j<pdim) { cerr<<initfile<<":Too few minimum weights." << endl; cerr<<"error could not initialize start point with " << initfile << endl; std::cerr << "j: " << j << ", pdim: " << pdim << std::endl; exit(3); } max.resize(pdim); for( j=0; j<pdim&&!opt.fail(); j++) opt>>max[j]; if(j<pdim) { cerr<<initfile<<":Too few maximum weights." << endl; exit(3); } } opt.close(); } vector<string> ScoreDataFiles; if (scorerfile.length() > 0) { Tokenize(scorerfile.c_str(), ',', &ScoreDataFiles); } vector<string> FeatureDataFiles; if (featurefile.length() > 0) { Tokenize(featurefile.c_str(), ',', &FeatureDataFiles); } if (ScoreDataFiles.size() != FeatureDataFiles.size()) { throw runtime_error("Error: there is a different number of previous score and feature files"); } // it make sense to know what parameter set were used to generate the nbest Scorer *TheScorer = ScorerFactory::getScorer(scorertype,scorerconfig); //load data Data D(*TheScorer); for (size_t i=0; i < ScoreDataFiles.size(); i++) { cerr<<"Loading Data from: "<< ScoreDataFiles.at(i) << " and " << FeatureDataFiles.at(i) << endl; D.load(FeatureDataFiles.at(i), ScoreDataFiles.at(i)); } //ADDED_BY_TS D.remove_duplicates(); //END_ADDED PrintUserTime("Data loaded"); // starting point score over latest n-best, accumulative n-best //vector<unsigned> bests; //compute bests with sparse features needs to be implemented //currently sparse weights are not even loaded //statscore_t score = TheScorer->score(bests); if (tooptimizestr.length() > 0) { cerr << "Weights to optimize: " << tooptimizestr << endl; // Parse string to get weights to optimize, and set them as active std::string substring; int index; while (!tooptimizestr.empty()) { getNextPound(tooptimizestr, substring, ","); index = D.getFeatureIndex(substring); cerr << "FeatNameIndex:" << index << " to insert" << endl; //index = strtol(substring.c_str(), NULL, 10); if (index >= 0 && index < pdim) { tooptimize.push_back(index); } else { cerr << "Index " << index << " is out of bounds. Allowed indexes are [0," << (pdim-1) << "]." << endl; } } } else { //set all weights as active tooptimize.resize(pdim);//We'll optimize on everything for(int i=0; i<pdim; i++) { tooptimize[i]=1; } } // treat sparse features just like regular features if (D.hasSparseFeatures()) { D.mergeSparseFeatures(); } #ifdef WITH_THREADS cerr << "Creating a pool of " << threads << " threads" << endl; Moses::ThreadPool pool(threads); #endif Point::setpdim(pdim); Point::setdim(tooptimize.size()); //starting points consist of specified points and random restarts vector<Point> startingPoints; for (size_t i = 0; i < start_list.size(); ++i) { startingPoints.push_back(Point(start_list[i],min,max)); } for (int i = 0; i < ntry; ++i) { startingPoints.push_back(Point(start_list[0],min,max)); startingPoints.back().Randomize(); } vector<vector<OptimizationTask*> > allTasks(1); //optional sharding vector<Data> shards; if (shard_count) { D.createShards(shard_count, shard_size, scorerconfig, shards); allTasks.resize(shard_count); } // launch tasks for (size_t i = 0 ; i < allTasks.size(); ++i) { Data& data = D; if (shard_count) data = shards[i]; //use the sharded data if it exists vector<OptimizationTask*>& tasks = allTasks[i]; Optimizer *O = OptimizerFactory::BuildOptimizer(pdim,tooptimize,start_list[0],type,nrandom); O->SetScorer(data.getScorer()); O->SetFData(data.getFeatureData()); //A task for each start point for (size_t j = 0; j < startingPoints.size(); ++j) { OptimizationTask* task = new OptimizationTask(O, startingPoints[j]); tasks.push_back(task); #ifdef WITH_THREADS pool.Submit(task); #else task->Run(); #endif } } // wait for all threads to finish #ifdef WITH_THREADS pool.Stop(true); #endif statscore_t total = 0; Point totalP; // collect results for (size_t i = 0; i < allTasks.size(); ++i) { statscore_t best=0, mean=0, var=0; Point bestP; for (size_t j = 0; j < allTasks[i].size(); ++j) { statscore_t score = allTasks[i][j]->getScore(); mean += score; var += score*score; if (score > best) { bestP = allTasks[i][j]->getPoint(); best = score; } } mean/=(float)ntry; var/=(float)ntry; var=sqrt(abs(var-mean*mean)); if (verboselevel()>1) cerr<<"shard " << i << " best score: "<< best << " variance of the score (for "<<ntry<<" try): "<<var<<endl; totalP += bestP; total += best; if (verboselevel()>1) cerr << "bestP " << bestP << endl; } //cerr << "totalP: " << totalP << endl; Point finalP = totalP * (1.0 / allTasks.size()); statscore_t final = total / allTasks.size(); if (verboselevel()>1) cerr << "bestP: " << finalP << endl; // L1-Normalization of the best Point if ((int)tooptimize.size() == pdim) finalP.NormalizeL1(); cerr << "Best point: " << finalP << " => " << final << endl; ofstream res("weights.txt"); res<<finalP<<endl; for (size_t i = 0; i < allTasks.size(); ++i) { allTasks[i][0]->resetOptimizer(); for (size_t j = 0; j < allTasks[i].size(); ++j) { delete allTasks[i][j]; } } delete TheScorer; PrintUserTime("Stopping..."); } <commit_msg>Introduce anonymous namespace.<commit_after>/** * \description This is the main for the new version of the mert algorithm developed during the 2nd MT marathon */ #include <limits> #include <unistd.h> #include <cstdlib> #include <iostream> #include <fstream> #include <cmath> #include <ctime> #include <getopt.h> #include "Data.h" #include "Point.h" #include "Scorer.h" #include "ScorerFactory.h" #include "ScoreData.h" #include "FeatureData.h" #include "Optimizer.h" #include "Types.h" #include "Timer.h" #include "Util.h" #include "../moses/src/ThreadPool.h" using namespace std; namespace { float min_interval = 1e-3; /** * Runs an optimisation, or a random restart. */ class OptimizationTask : public Moses::Task { public: OptimizationTask(Optimizer* optimizer, const Point& point) : m_optimizer(optimizer), m_point(point) {} ~OptimizationTask() {} void resetOptimizer() { if (m_optimizer) { delete m_optimizer; m_optimizer = NULL; } } bool DeleteAfterExecution() const { return false; } void Run() { m_score = m_optimizer->Run(m_point); } statscore_t getScore() const { return m_score; } const Point& getPoint() const { return m_point; } private: // Do not allow the user to instanciate without arguments. OptimizationTask() {} Optimizer* m_optimizer; Point m_point; statscore_t m_score; }; void usage(int ret) { cerr<<"usage: mert -d <dimensions> (mandatory )"<<endl; cerr<<"[-n] retry ntimes (default 1)"<<endl; cerr<<"[-m] number of random directions in powell (default 0)"<<endl; cerr<<"[-o] the indexes to optimize(default all)"<<endl; cerr<<"[-t] the optimizer(default powell)"<<endl; cerr<<"[-r] the random seed (defaults to system clock)"<<endl; cerr<<"[--sctype|-s] the scorer type (default BLEU)"<<endl; cerr<<"[--scconfig|-c] configuration string passed to scorer"<<endl; cerr<<"[--scfile|-S] comma separated list of scorer data files (default score.data)"<<endl; cerr<<"[--ffile|-F] comma separated list of feature data files (default feature.data)"<<endl; cerr<<"[--ifile|-i] the starting point data file (default init.opt)"<<endl; #ifdef WITH_THREADS cerr<<"[--threads|-T] use multiple threads (default 1)"<<endl; #endif cerr<<"[--shard-count] Split data into shards, optimize for each shard and average"<<endl; cerr<<"[--shard-size] Shard size as proportion of data. If 0, use non-overlapping shards"<<endl; cerr<<"[-v] verbose level"<<endl; cerr<<"[--help|-h] print this message and exit"<<endl; exit(ret); } static struct option long_options[] = { {"pdim", 1, 0, 'd'}, {"ntry",1,0,'n'}, {"nrandom",1,0,'m'}, {"rseed",required_argument,0,'r'}, {"optimize",1,0,'o'}, {"pro",required_argument,0,'p'}, {"type",1,0,'t'}, {"sctype",1,0,'s'}, {"scconfig",required_argument,0,'c'}, {"scfile",1,0,'S'}, {"ffile",1,0,'F'}, {"ifile",1,0,'i'}, #ifdef WITH_THREADS {"threads", required_argument,0,'T'}, #endif {"shard-count", required_argument, 0, 'a'}, {"shard-size", required_argument, 0, 'b'}, {"verbose",1,0,'v'}, {"help",no_argument,0,'h'}, {0, 0, 0, 0} }; int option_index; } // anonymous namespace int main (int argc, char **argv) { ResetUserTime(); /* Timer timer; timer.start("Starting..."); */ int c,pdim,i; pdim=-1; int ntry=1; int nrandom=0; int seed=0; bool hasSeed = false; #ifdef WITH_THREADS size_t threads=1; #endif float shard_size = 0; size_t shard_count = 0; string type("powell"); string scorertype("BLEU"); string scorerconfig(""); string scorerfile("statscore.data"); string featurefile("features.data"); string initfile("init.opt"); string tooptimizestr(""); vector<unsigned> tooptimize; vector<vector<parameter_t> > start_list; vector<parameter_t> min; vector<parameter_t> max; // NOTE: those mins and max are the bound for the starting points of the algorithm, not strict bound on the result! while ((c=getopt_long (argc, argv, "o:r:d:n:m:t:s:S:F:v:p:", long_options, &option_index)) != -1) { switch (c) { case 'o': tooptimizestr = string(optarg); break; case 'd': pdim = strtol(optarg, NULL, 10); break; case 'n': ntry=strtol(optarg, NULL, 10); break; case 'm': nrandom=strtol(optarg, NULL, 10); break; case 'r': seed=strtol(optarg, NULL, 10); hasSeed = true; break; case 't': type=string(optarg); break; case's': scorertype=string(optarg); break; case 'c': scorerconfig = string(optarg); break; case 'S': scorerfile=string(optarg); break; case 'F': featurefile=string(optarg); break; case 'i': initfile=string(optarg); break; case 'v': setverboselevel(strtol(optarg,NULL,10)); break; #ifdef WITH_THREADS case 'T': threads = strtol(optarg, NULL, 10); if (threads < 1) threads = 1; break; #endif case 'a': shard_count = strtof(optarg,NULL); break; case 'b': shard_size = strtof(optarg,NULL); break; case 'h': usage(0); break; default: usage(1); } } if (pdim < 0) usage(1); cerr << "shard_size = " << shard_size << " shard_count = " << shard_count << endl; if (shard_size && !shard_count) { cerr << "Error: shard-size provided without shard-count" << endl; exit(1); } if (shard_size > 1 || shard_size < 0) { cerr << "Error: shard-size should be between 0 and 1" << endl; exit(1); } if (hasSeed) { cerr << "Seeding random numbers with " << seed << endl; srandom(seed); } else { cerr << "Seeding random numbers with system clock " << endl; srandom(time(NULL)); } // read in starting points std::string onefile; while (!initfile.empty()) { getNextPound(initfile, onefile, ","); vector<parameter_t> start; ifstream opt(onefile.c_str()); if(opt.fail()) { cerr<<"could not open initfile: " << initfile << endl; exit(3); } start.resize(pdim);//to do:read from file int j; for( j=0; j<pdim&&!opt.fail(); j++) opt>>start[j]; if(j<pdim) { cerr<<initfile<<":Too few starting weights." << endl; exit(3); } start_list.push_back(start); // for the first time, also read in the min/max values for scores if (start_list.size() == 1) { min.resize(pdim); for( j=0; j<pdim&&!opt.fail(); j++) opt>>min[j]; if(j<pdim) { cerr<<initfile<<":Too few minimum weights." << endl; cerr<<"error could not initialize start point with " << initfile << endl; std::cerr << "j: " << j << ", pdim: " << pdim << std::endl; exit(3); } max.resize(pdim); for( j=0; j<pdim&&!opt.fail(); j++) opt>>max[j]; if(j<pdim) { cerr<<initfile<<":Too few maximum weights." << endl; exit(3); } } opt.close(); } vector<string> ScoreDataFiles; if (scorerfile.length() > 0) { Tokenize(scorerfile.c_str(), ',', &ScoreDataFiles); } vector<string> FeatureDataFiles; if (featurefile.length() > 0) { Tokenize(featurefile.c_str(), ',', &FeatureDataFiles); } if (ScoreDataFiles.size() != FeatureDataFiles.size()) { throw runtime_error("Error: there is a different number of previous score and feature files"); } // it make sense to know what parameter set were used to generate the nbest Scorer *TheScorer = ScorerFactory::getScorer(scorertype,scorerconfig); //load data Data D(*TheScorer); for (size_t i=0; i < ScoreDataFiles.size(); i++) { cerr<<"Loading Data from: "<< ScoreDataFiles.at(i) << " and " << FeatureDataFiles.at(i) << endl; D.load(FeatureDataFiles.at(i), ScoreDataFiles.at(i)); } //ADDED_BY_TS D.remove_duplicates(); //END_ADDED PrintUserTime("Data loaded"); // starting point score over latest n-best, accumulative n-best //vector<unsigned> bests; //compute bests with sparse features needs to be implemented //currently sparse weights are not even loaded //statscore_t score = TheScorer->score(bests); if (tooptimizestr.length() > 0) { cerr << "Weights to optimize: " << tooptimizestr << endl; // Parse string to get weights to optimize, and set them as active std::string substring; int index; while (!tooptimizestr.empty()) { getNextPound(tooptimizestr, substring, ","); index = D.getFeatureIndex(substring); cerr << "FeatNameIndex:" << index << " to insert" << endl; //index = strtol(substring.c_str(), NULL, 10); if (index >= 0 && index < pdim) { tooptimize.push_back(index); } else { cerr << "Index " << index << " is out of bounds. Allowed indexes are [0," << (pdim-1) << "]." << endl; } } } else { //set all weights as active tooptimize.resize(pdim);//We'll optimize on everything for(int i=0; i<pdim; i++) { tooptimize[i]=1; } } // treat sparse features just like regular features if (D.hasSparseFeatures()) { D.mergeSparseFeatures(); } #ifdef WITH_THREADS cerr << "Creating a pool of " << threads << " threads" << endl; Moses::ThreadPool pool(threads); #endif Point::setpdim(pdim); Point::setdim(tooptimize.size()); //starting points consist of specified points and random restarts vector<Point> startingPoints; for (size_t i = 0; i < start_list.size(); ++i) { startingPoints.push_back(Point(start_list[i],min,max)); } for (int i = 0; i < ntry; ++i) { startingPoints.push_back(Point(start_list[0],min,max)); startingPoints.back().Randomize(); } vector<vector<OptimizationTask*> > allTasks(1); //optional sharding vector<Data> shards; if (shard_count) { D.createShards(shard_count, shard_size, scorerconfig, shards); allTasks.resize(shard_count); } // launch tasks for (size_t i = 0 ; i < allTasks.size(); ++i) { Data& data = D; if (shard_count) data = shards[i]; //use the sharded data if it exists vector<OptimizationTask*>& tasks = allTasks[i]; Optimizer *O = OptimizerFactory::BuildOptimizer(pdim,tooptimize,start_list[0],type,nrandom); O->SetScorer(data.getScorer()); O->SetFData(data.getFeatureData()); //A task for each start point for (size_t j = 0; j < startingPoints.size(); ++j) { OptimizationTask* task = new OptimizationTask(O, startingPoints[j]); tasks.push_back(task); #ifdef WITH_THREADS pool.Submit(task); #else task->Run(); #endif } } // wait for all threads to finish #ifdef WITH_THREADS pool.Stop(true); #endif statscore_t total = 0; Point totalP; // collect results for (size_t i = 0; i < allTasks.size(); ++i) { statscore_t best=0, mean=0, var=0; Point bestP; for (size_t j = 0; j < allTasks[i].size(); ++j) { statscore_t score = allTasks[i][j]->getScore(); mean += score; var += score*score; if (score > best) { bestP = allTasks[i][j]->getPoint(); best = score; } } mean/=(float)ntry; var/=(float)ntry; var=sqrt(abs(var-mean*mean)); if (verboselevel()>1) cerr<<"shard " << i << " best score: "<< best << " variance of the score (for "<<ntry<<" try): "<<var<<endl; totalP += bestP; total += best; if (verboselevel()>1) cerr << "bestP " << bestP << endl; } //cerr << "totalP: " << totalP << endl; Point finalP = totalP * (1.0 / allTasks.size()); statscore_t final = total / allTasks.size(); if (verboselevel()>1) cerr << "bestP: " << finalP << endl; // L1-Normalization of the best Point if ((int)tooptimize.size() == pdim) finalP.NormalizeL1(); cerr << "Best point: " << finalP << " => " << final << endl; ofstream res("weights.txt"); res<<finalP<<endl; for (size_t i = 0; i < allTasks.size(); ++i) { allTasks[i][0]->resetOptimizer(); for (size_t j = 0; j < allTasks[i].size(); ++j) { delete allTasks[i][j]; } } delete TheScorer; PrintUserTime("Stopping..."); } <|endoftext|>
<commit_before>// demo.cpp #include "demo.h" namespace demo { void Demo::startup() { } void Demo::run() { } bool Demo::isRunning() const { } void Demo::shutdown() { } } // End nspc demo<commit_msg>Initialize the graphics api in the demo start up sequence.<commit_after>// demo.cpp #include "demo.h" #include "demo/render/grapi.h" namespace demo { void Demo::startup() { // initialize the components GrApi::init(); } void Demo::run() { } bool Demo::isRunning() const { } void Demo::shutdown() { } } // End nspc demo<|endoftext|>
<commit_before>#include"manager.h" #include"user.h" #include<sstream> #include"config.h" #include"utils.h" #include <liblog.h> MODULE_LOG_NAME("CManager"); CManager::CManager(CConnectionPool * DatabaseFile) { m_pDatabase=DatabaseFile; } CManager::~CManager() { } bool CManager::getUserByID(int nID, IUser ** ppUser) { if (!ppUser) { setError(InvalidParam, 4, "The pointer is NULL."); return false; } IUser* n = new CUser(m_pDatabase); try { std::shared_ptr<sql::Connection> c(m_pDatabase->getConnection(REGID_MYSQL_CONN),MYSQL_CONN_RELEASER); std::shared_ptr<sql::Statement> stat(c->createStatement()); std::stringstream str; str << "SELECT * FROM UserInfoDatabase WHERE id = " << nID; stat->execute(str.str()); std::shared_ptr<sql::ResultSet> result(stat->getResultSet()); result->next(); TUserBasicInfo Basicinfo; Basicinfo.email = result->getString("email"); Basicinfo.gender = result->getInt("gender"); Basicinfo.id = result->getInt("id"); Basicinfo.name = result->getString("name"); n->setReadLevel(result->getInt("ReadLevel")); n->setAuthLevel(result->getInt("AuthLevel")); n->setBasicInfo(Basicinfo); ((CUser*)n)->straightsetpassword(result->getString("password").c_str()); ((CUser*)n)->sign(); (*ppUser) = n; return true; } catch (sql::SQLException& e) { setError(DatabaseError, 9, (std::string("There is some wrong with our database.\n") + e.what()).c_str()); return false; } return true; } bool CManager::insertUser(IUser * pUser) { TUserBasicInfo info; pUser->getBasicInfo(info); if (verify(info.name.c_str(), info.email.c_str())) { if (!((CUser*)pUser)->insert()) { transferError(pUser); return false; } } else return false; } bool CManager::getUserByName(const char * strName, IUser ** ppUser) { int type=0; for (int i = 0; i < strlen(strName); i++) { if (strName[i] == '@') { type = 1; break; } else if ((strName[i] <= 'z' && strName[i] >= 'a') || (strName[i] <= 'Z' && strName[i] >= 'A') || strName[i] == '_') type = 2; else if (strName[i] <= '9' && strName[i] >= '0') {} else { setError(InvalidParam, -1, "Invalid string."); return false; } } if (!type) { int nId; std::stringstream ss; ss << strName; ss >> nId; return getUserByID(nId, ppUser); } if (type == 1) { if (!ppUser) { setError(InvalidParam, 4, "The pointer is NULL."); return false; } try { std::shared_ptr<sql::Connection> c(m_pDatabase->getConnection(REGID_MYSQL_CONN), MYSQL_CONN_RELEASER); std::shared_ptr<sql::Statement> stat(c->createStatement()); std::stringstream str; str << "SELECT * FROM UserInfoDatabase WHERE email = " << '\'' << str2sql(strName) << '\''; stat->execute(str.str()); std::shared_ptr<sql::ResultSet> result(stat->getResultSet()); result->next(); TUserBasicInfo Basicinfo; Basicinfo.email = result->getString("email"); Basicinfo.gender = result->getInt("gender"); Basicinfo.id = result->getInt("id"); Basicinfo.name = result->getString("name"); (*ppUser)->setReadLevel(result->getInt("ReadLevel")); (*ppUser)->setBasicInfo(Basicinfo); ((CUser*)(*ppUser))->straightsetpassword(result->getString("password").c_str()); ((CUser*)(*ppUser))->sign(); return true; } catch (sql::SQLException& e) { setError(DatabaseError, 9, (std::string("There is some wrong with our database.\n") + e.what()).c_str()); return false; } return true; } if (type == 2) { if (!ppUser) { setError(InvalidParam, 4, "The pointer is NULL."); return false; } try { std::shared_ptr<sql::Connection> c(m_pDatabase->getConnection(REGID_MYSQL_CONN),MYSQL_CONN_RELEASER); std::shared_ptr<sql::Statement> stat(c->createStatement()); std::stringstream str; str << "SELECT * FROM UserInfoDatabase WHERE name = " << '\'' << str2sql(strName) << '\''; stat->execute(str.str()); std::shared_ptr<sql::ResultSet> result(stat->getResultSet()); result->next(); TUserBasicInfo Basicinfo; Basicinfo.email = result->getString("email"); Basicinfo.gender = result->getInt("gender"); Basicinfo.id = result->getInt("id"); Basicinfo.name = result->getString("name"); (*ppUser)->setReadLevel(result->getInt("ReadLevel")); (*ppUser)->setBasicInfo(Basicinfo); ((CUser*)(*ppUser))->straightsetpassword(result->getString("password").c_str()); ((CUser*)(*ppUser))->sign(); return true; } catch (sql::SQLException& e) { setError(DatabaseError, 9, (std::string("There is some wrong with our database.\n") + e.what()).c_str()); return false; } } return false; } bool CManager::verify(const char* strName,const char * strEmail) { if (!strName || !strEmail) return false; try { std::shared_ptr<sql::Connection> c(m_pDatabase->getConnection(REGID_MYSQL_CONN), MYSQL_CONN_RELEASER); std::shared_ptr<sql::Statement> stat(c->createStatement()); std::stringstream str1; str1 << "SELECT * FROM UserInfoDatabase WHERE name = " << '\'' << str2sql(strName) << '\''; stat->execute(str1.str()); std::shared_ptr<sql::ResultSet> result1(stat->getResultSet()); int flag = 1; if (result1->next()) flag = 0; std::stringstream str2; str2 << "SELECT * FROM UserInfoDatabase WHERE email = " << '\'' << str2sql(strEmail) << '\''; stat->execute(str2.str()); std::shared_ptr<sql::ResultSet> result2(stat->getResultSet()); if (result2->next()) flag = 0; if (flag) return true; else { setError(InvalidParam, 99, "Repeated"); return false; } } catch (sql::SQLException& e) { lprintf("An error occurred while verifying: %s", e.what()); return false; } return false; }<commit_msg>bugfix<commit_after>#include"manager.h" #include"user.h" #include<sstream> #include"config.h" #include"utils.h" #include <liblog.h> MODULE_LOG_NAME("CManager"); CManager::CManager(CConnectionPool * DatabaseFile) { m_pDatabase=DatabaseFile; } CManager::~CManager() { } bool CManager::getUserByID(int nID, IUser ** ppUser) { if (!ppUser) { setError(InvalidParam, 4, "The pointer is NULL."); return false; } IUser* n = new CUser(m_pDatabase); try { std::shared_ptr<sql::Connection> c(m_pDatabase->getConnection(REGID_MYSQL_CONN),MYSQL_CONN_RELEASER); std::shared_ptr<sql::Statement> stat(c->createStatement()); std::stringstream str; str << "SELECT * FROM UserInfoDatabase WHERE id = " << nID; stat->execute(str.str()); std::shared_ptr<sql::ResultSet> result(stat->getResultSet()); result->next(); TUserBasicInfo Basicinfo; Basicinfo.email = result->getString("email"); Basicinfo.gender = result->getInt("gender"); Basicinfo.id = result->getInt("id"); Basicinfo.name = result->getString("name"); n->setReadLevel(result->getInt("ReadLevel")); n->setAuthLevel(result->getInt("AuthLevel")); n->setBasicInfo(Basicinfo); ((CUser*)n)->straightsetpassword(result->getString("password").c_str()); ((CUser*)n)->sign(); (*ppUser) = n; return true; } catch (sql::SQLException& e) { setError(DatabaseError, 9, (std::string("There is some wrong with our database.\n") + e.what()).c_str()); return false; } return true; } bool CManager::insertUser(IUser * pUser) { TUserBasicInfo info; pUser->getBasicInfo(info); if (verify(info.name.c_str(), info.email.c_str())) { if (!((CUser*)pUser)->insert()) { transferError(pUser); return false; } return true; } else return false; } bool CManager::getUserByName(const char * strName, IUser ** ppUser) { int type=0; for (int i = 0; i < strlen(strName); i++) { if (strName[i] == '@') { type = 1; break; } else if ((strName[i] <= 'z' && strName[i] >= 'a') || (strName[i] <= 'Z' && strName[i] >= 'A') || strName[i] == '_') type = 2; else if (strName[i] <= '9' && strName[i] >= '0') {} else { setError(InvalidParam, -1, "Invalid string."); return false; } } if (!type) { int nId; std::stringstream ss; ss << strName; ss >> nId; return getUserByID(nId, ppUser); } if (type == 1) { if (!ppUser) { setError(InvalidParam, 4, "The pointer is NULL."); return false; } try { std::shared_ptr<sql::Connection> c(m_pDatabase->getConnection(REGID_MYSQL_CONN), MYSQL_CONN_RELEASER); std::shared_ptr<sql::Statement> stat(c->createStatement()); std::stringstream str; str << "SELECT * FROM UserInfoDatabase WHERE email = " << '\'' << str2sql(strName) << '\''; stat->execute(str.str()); std::shared_ptr<sql::ResultSet> result(stat->getResultSet()); result->next(); TUserBasicInfo Basicinfo; Basicinfo.email = result->getString("email"); Basicinfo.gender = result->getInt("gender"); Basicinfo.id = result->getInt("id"); Basicinfo.name = result->getString("name"); (*ppUser)->setReadLevel(result->getInt("ReadLevel")); (*ppUser)->setBasicInfo(Basicinfo); ((CUser*)(*ppUser))->straightsetpassword(result->getString("password").c_str()); ((CUser*)(*ppUser))->sign(); return true; } catch (sql::SQLException& e) { setError(DatabaseError, 9, (std::string("There is some wrong with our database.\n") + e.what()).c_str()); return false; } return true; } if (type == 2) { if (!ppUser) { setError(InvalidParam, 4, "The pointer is NULL."); return false; } try { std::shared_ptr<sql::Connection> c(m_pDatabase->getConnection(REGID_MYSQL_CONN),MYSQL_CONN_RELEASER); std::shared_ptr<sql::Statement> stat(c->createStatement()); std::stringstream str; str << "SELECT * FROM UserInfoDatabase WHERE name = " << '\'' << str2sql(strName) << '\''; stat->execute(str.str()); std::shared_ptr<sql::ResultSet> result(stat->getResultSet()); result->next(); TUserBasicInfo Basicinfo; Basicinfo.email = result->getString("email"); Basicinfo.gender = result->getInt("gender"); Basicinfo.id = result->getInt("id"); Basicinfo.name = result->getString("name"); (*ppUser)->setReadLevel(result->getInt("ReadLevel")); (*ppUser)->setBasicInfo(Basicinfo); ((CUser*)(*ppUser))->straightsetpassword(result->getString("password").c_str()); ((CUser*)(*ppUser))->sign(); return true; } catch (sql::SQLException& e) { setError(DatabaseError, 9, (std::string("There is some wrong with our database.\n") + e.what()).c_str()); return false; } } return false; } bool CManager::verify(const char* strName,const char * strEmail) { if (!strName || !strEmail) return false; try { std::shared_ptr<sql::Connection> c(m_pDatabase->getConnection(REGID_MYSQL_CONN), MYSQL_CONN_RELEASER); std::shared_ptr<sql::Statement> stat(c->createStatement()); std::stringstream str1; str1 << "SELECT * FROM UserInfoDatabase WHERE name = " << '\'' << str2sql(strName) << '\''; stat->execute(str1.str()); std::shared_ptr<sql::ResultSet> result1(stat->getResultSet()); int flag = 1; if (result1->next()) flag = 0; std::stringstream str2; str2 << "SELECT * FROM UserInfoDatabase WHERE email = " << '\'' << str2sql(strEmail) << '\''; stat->execute(str2.str()); std::shared_ptr<sql::ResultSet> result2(stat->getResultSet()); if (result2->next()) flag = 0; if (flag) return true; else { setError(InvalidParam, 99, "Repeated"); return false; } } catch (sql::SQLException& e) { lprintf("An error occurred while verifying: %s", e.what()); return false; } return false; }<|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: simpleguesser.cxx,v $ * $Revision: 1.5 $ * * 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. * ************************************************************************/ /** * * * * * TODO * - Add exception throwing when h == NULL * - Not init h when implicit constructor is launched */ // MARKER(update_precomp.py): autogen include statement, do not remove #include "precompiled_lingucomponent.hxx" #include <string.h> #include <sstream> #include <iostream> #include <libtextcat/textcat.h> #include <libtextcat/common.h> #include <libtextcat/constants.h> #include <libtextcat/fingerprint.h> #include <libtextcat/utf8misc.h> #include <sal/types.h> #include "altstrfunc.hxx" #include "simpleguesser.hxx" #ifndef _UTF8_ #define _UTF8_ #endif using namespace std; /** * This 3 following structures are from fingerprint.c and textcat.c */ typedef struct ngram_t { sint2 rank; char str[MAXNGRAMSIZE+1]; } ngram_t; typedef struct fp_t { const char *name; ngram_t *fprint; uint4 size; } fp_t; typedef struct textcat_t{ void **fprint; char *fprint_disable; uint4 size; uint4 maxsize; char output[MAXOUTPUTSIZE]; } textcat_t; /** end of the 3 structs */ SimpleGuesser::SimpleGuesser() { h = NULL; } SimpleGuesser::SimpleGuesser(const char* confFile, const char* prefix) { h = special_textcat_Init(confFile, prefix); } void SimpleGuesser::operator=(SimpleGuesser& sg){ if(h){textcat_Done(h);} h = sg.h; } SimpleGuesser::~SimpleGuesser() { if(h){textcat_Done(h);} } /*! \fn SimpleGuesser::GuessLanguage(char* text) */ vector<Guess> SimpleGuesser::GuessLanguage(char* text) { vector<Guess> guesses; if(!h){return guesses;} //calculate le number of unicode charcters (symbols) int len = utfstrlen(text); if( len > MAX_STRING_LENGTH_TO_ANALYSE ){len = MAX_STRING_LENGTH_TO_ANALYSE ;} char *guess_list = textcat_Classify(h, text, len); if(strcmp(guess_list, _TEXTCAT_RESULT_SHORT) == 0){ return guesses; } int current_pointer = 0; for(int i = 0; guess_list[current_pointer] != '\0'; i++) { while(guess_list[current_pointer] != GUESS_SEPARATOR_OPEN && guess_list[current_pointer] != '\0'){ current_pointer++; } if(guess_list[current_pointer] != '\0') { Guess g((char*)(guess_list + current_pointer),i); guesses.push_back(g); current_pointer++; } } return guesses; } /*! \fn SimpleGuesser::GuessPrimaryLanguage(char* text) */ Guess SimpleGuesser::GuessPrimaryLanguage(char* text) { vector<Guess> ret = GuessLanguage(text); if(ret.size() > 0){ return GuessLanguage(text)[0]; } else{ return Guess(); } } /** * Is used to know wich language is available, unavailable or both * when mask = 0xF0, return only Available * when mask = 0x0F, return only Unavailable * when mask = 0xFF, return both Available and Unavailable */ vector<Guess> SimpleGuesser::GetManagedLanguages(const char mask) { size_t i; textcat_t *tables = (textcat_t*)h; vector<Guess> lang; if(!h){return lang;} for (i=0; i<tables->size; i++) { if(tables->fprint_disable[i] & mask){ string langStr = "["; langStr += (char*)fp_Name(tables->fprint[i]); Guess g( (char *)langStr.c_str() , i); lang.push_back(g); } } return lang; } vector<Guess> SimpleGuesser::GetAvailableLanguages(){ return GetManagedLanguages( sal::static_int_cast< char >( 0xF0 ) ); } vector<Guess> SimpleGuesser::GetUnavailableLanguages(){ return GetManagedLanguages( sal::static_int_cast< char >( 0x0F )); } vector<Guess> SimpleGuesser::GetAllManagedLanguages(){ return GetManagedLanguages( sal::static_int_cast< char >( 0xFF )); } void SimpleGuesser::XableLanguage(string lang, char mask){ size_t i; textcat_t *tables = (textcat_t*)h; if(!h){return;} for (i=0; i<tables->size; i++) { string language(fp_Name(tables->fprint[i])); if(start(language,lang) == 0){ //cout << language << endl; tables->fprint_disable[i] = mask; //continue; } } } void SimpleGuesser::EnableLanguage(string lang){ XableLanguage(lang, sal::static_int_cast< char >( 0xF0 )); } void SimpleGuesser::DisableLanguage(string lang){ XableLanguage(lang, sal::static_int_cast< char >( 0x0F )); } /** * */ void SimpleGuesser::SetDBPath(const char* path, const char* prefix){ if(h){ textcat_Done(h); } h = special_textcat_Init(path, prefix); } <commit_msg>INTEGRATION: CWS tl50 (1.4.62); FILE MERGED 2008/02/27 15:29:57 tl 1.4.62.1: #i86321# removed unused code<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: simpleguesser.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. * ************************************************************************/ /** * * * * * TODO * - Add exception throwing when h == NULL * - Not init h when implicit constructor is launched */ // MARKER(update_precomp.py): autogen include statement, do not remove #include "precompiled_lingucomponent.hxx" #include <string.h> #include <sstream> #include <iostream> #include <libtextcat/textcat.h> #include <libtextcat/common.h> #include <libtextcat/constants.h> #include <libtextcat/fingerprint.h> #include <libtextcat/utf8misc.h> #include <sal/types.h> #include "altstrfunc.hxx" #include "simpleguesser.hxx" #ifndef _UTF8_ #define _UTF8_ #endif using namespace std; /** * This 3 following structures are from fingerprint.c and textcat.c */ typedef struct ngram_t { sint2 rank; char str[MAXNGRAMSIZE+1]; } ngram_t; typedef struct fp_t { const char *name; ngram_t *fprint; uint4 size; } fp_t; typedef struct textcat_t{ void **fprint; char *fprint_disable; uint4 size; uint4 maxsize; char output[MAXOUTPUTSIZE]; } textcat_t; /** end of the 3 structs */ SimpleGuesser::SimpleGuesser() { h = NULL; } void SimpleGuesser::operator=(SimpleGuesser& sg){ if(h){textcat_Done(h);} h = sg.h; } SimpleGuesser::~SimpleGuesser() { if(h){textcat_Done(h);} } /*! \fn SimpleGuesser::GuessLanguage(char* text) */ vector<Guess> SimpleGuesser::GuessLanguage(char* text) { vector<Guess> guesses; if(!h){return guesses;} //calculate le number of unicode charcters (symbols) int len = utfstrlen(text); if( len > MAX_STRING_LENGTH_TO_ANALYSE ){len = MAX_STRING_LENGTH_TO_ANALYSE ;} char *guess_list = textcat_Classify(h, text, len); if(strcmp(guess_list, _TEXTCAT_RESULT_SHORT) == 0){ return guesses; } int current_pointer = 0; for(int i = 0; guess_list[current_pointer] != '\0'; i++) { while(guess_list[current_pointer] != GUESS_SEPARATOR_OPEN && guess_list[current_pointer] != '\0'){ current_pointer++; } if(guess_list[current_pointer] != '\0') { Guess g((char*)(guess_list + current_pointer)); guesses.push_back(g); current_pointer++; } } return guesses; } /*! \fn SimpleGuesser::GuessPrimaryLanguage(char* text) */ Guess SimpleGuesser::GuessPrimaryLanguage(char* text) { vector<Guess> ret = GuessLanguage(text); if(ret.size() > 0){ return GuessLanguage(text)[0]; } else{ return Guess(); } } /** * Is used to know wich language is available, unavailable or both * when mask = 0xF0, return only Available * when mask = 0x0F, return only Unavailable * when mask = 0xFF, return both Available and Unavailable */ vector<Guess> SimpleGuesser::GetManagedLanguages(const char mask) { size_t i; textcat_t *tables = (textcat_t*)h; vector<Guess> lang; if(!h){return lang;} for (i=0; i<tables->size; i++) { if(tables->fprint_disable[i] & mask){ string langStr = "["; langStr += (char*)fp_Name(tables->fprint[i]); Guess g( (char *)langStr.c_str()); lang.push_back(g); } } return lang; } vector<Guess> SimpleGuesser::GetAvailableLanguages(){ return GetManagedLanguages( sal::static_int_cast< char >( 0xF0 ) ); } vector<Guess> SimpleGuesser::GetUnavailableLanguages(){ return GetManagedLanguages( sal::static_int_cast< char >( 0x0F )); } vector<Guess> SimpleGuesser::GetAllManagedLanguages(){ return GetManagedLanguages( sal::static_int_cast< char >( 0xFF )); } void SimpleGuesser::XableLanguage(string lang, char mask){ size_t i; textcat_t *tables = (textcat_t*)h; if(!h){return;} for (i=0; i<tables->size; i++) { string language(fp_Name(tables->fprint[i])); if(start(language,lang) == 0){ //cout << language << endl; tables->fprint_disable[i] = mask; //continue; } } } void SimpleGuesser::EnableLanguage(string lang){ XableLanguage(lang, sal::static_int_cast< char >( 0xF0 )); } void SimpleGuesser::DisableLanguage(string lang){ XableLanguage(lang, sal::static_int_cast< char >( 0x0F )); } /** * */ void SimpleGuesser::SetDBPath(const char* path, const char* prefix){ if(h){ textcat_Done(h); } h = special_textcat_Init(path, prefix); } <|endoftext|>